Skip to content

Commit

Permalink
Fix assigning files to nonexistent assets
Browse files Browse the repository at this point in the history
  • Loading branch information
Sanqui committed Aug 12, 2024
1 parent ebdf21d commit 6210c8e
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 6 deletions.
29 changes: 24 additions & 5 deletions rhinventory/admin_views/file.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ def details_view(self):
if id is None:
return redirect(return_url)

model = self.get_one(id)
model: File | None = self.get_one(id)

if model is None:
flash('Record does not exist.', 'error')
Expand All @@ -116,7 +116,12 @@ def details_view(self):
file_assign_form.process(request.form)

if request.method == "POST" and file_assign_form.validate():
model.assign(file_assign_form.asset.data)
try:
model.assign(file_assign_form.asset.data)
except ValueError as e:
flash(f"Failed to assign file to asset: {e}", 'error')
return redirect(url_for("file.details_view", id=id))

db.session.add(model)
log("Update", model, user=current_user)
db.session.commit()
Expand Down Expand Up @@ -184,7 +189,12 @@ def upload_view(self):
else:
asset_ids = [File.read_rh_barcode(file) for file in image_files]
for file, asset_id in zip(image_files, asset_ids):
file.assign(asset_id)
try:
file.assign(asset_id)
except ValueError:
# Probably failed to assign file to asset because asset doesn't exist
# Ignore this
pass

print("Creating thumbnails...")
# Create thumbnails in parallel
Expand Down Expand Up @@ -314,11 +324,20 @@ def rotate_view(self):
@require_write_access
def assign_view(self):
id = get_mdict_item_or_list(request.args, 'id')
model = self.get_one(id)
model: File | None = self.get_one(id)
if not model:
flash('Record does not exist.', 'error')
return redirect(url_for("file.details_view", id=id))

asset_id = get_mdict_item_or_list(request.args, 'asset_id')
assert isinstance(asset_id, int)

model.assign(asset_id)
try:
model.assign(asset_id)
except ValueError as e:
flash(f"Failed to assign file to asset: {e}", 'error')
return redirect(url_for("file.details_view", id=id))

db.session.add(model)
log("Update", model, user=current_user)
db.session.commit()
Expand Down
11 changes: 10 additions & 1 deletion rhinventory/models/file.py
Original file line number Diff line number Diff line change
Expand Up @@ -242,10 +242,19 @@ def auto_assign(self):
if asset_id:
self.assign(asset_id)

def assign(self, asset_id):
def assign(self, asset_id: int):
'''Assigns File to a given Asset and renames file and thumbnail'''

from rhinventory.models.asset import Asset # avoid circular import

if not asset_id:
return

# check that asset exists
asset = Asset.query.get(asset_id)
if not asset:
raise ValueError("Trying to assign to asset that does not exist")

self.asset_id = asset_id

files_dir = current_app.config['FILE_STORE_LOCATIONS'][self.storage.value]
Expand Down

0 comments on commit 6210c8e

Please sign in to comment.