From f8cb0614a1cb8922aa366e67f2796280aa14f0a2 Mon Sep 17 00:00:00 2001 From: Graeme Watt Date: Wed, 15 Dec 2021 12:59:26 +0000 Subject: [PATCH] records: refactor default preview_location code * Also now allow for a thumbnail file without a matching image file. --- hepdata/modules/records/views.py | 31 ++++++++++++++++++++----------- 1 file changed, 20 insertions(+), 11 deletions(-) diff --git a/hepdata/modules/records/views.py b/hepdata/modules/records/views.py index 5e20bb6e..8185fcb4 100644 --- a/hepdata/modules/records/views.py +++ b/hepdata/modules/records/views.py @@ -338,24 +338,33 @@ def get_table_details(recid, data_recid, version): tmp_assoc_files[key] = {} if not alt_location.lower().startswith('http'): - if "thumb_" in alt_location and associated_data_file.file_type.lower() in IMAGE_TYPES: - tmp_assoc_files[key]['preview_location'] = '/record/resource/{0}?view=true'.format( - associated_data_file.id) + if location_parts[-1].startswith('thumb_') and associated_data_file.file_type.lower() in IMAGE_TYPES: + tmp_assoc_files[key]['thumbnail_id'] = associated_data_file.id else: tmp_assoc_files[key].update({'description': associated_data_file.file_description, 'type': associated_data_file.file_type, 'id': associated_data_file.id, 'alt_location': alt_location}) + if associated_data_file.file_type.lower() in IMAGE_TYPES: # add a default if no thumbnail + tmp_assoc_files[key]['preview_location'] = f'/record/resource/{associated_data_file.id}?view=true' - # If there is no matching thumbnail available for an image file, - # just use the image file itself as the preview location. + # Check if there is a matching thumbnail available for an image file. for key, value in tmp_assoc_files.items(): - if (all(k in value for k in ('alt_location', 'type', 'id')) and - not value['alt_location'].lower().startswith('http') and - value['type'].lower() in IMAGE_TYPES and - 'preview_location' not in value): - tmp_assoc_files[key]['preview_location'] = \ - '/record/resource/{0}?view=true'.format(value['id']) + if 'thumbnail_id' in value: + thumbnail_id = tmp_assoc_files[key].pop('thumbnail_id') + tmp_assoc_files[key]['preview_location'] = f'/record/resource/{thumbnail_id}?view=true' + + # Allow for the (unlikely?) special case where there is a + # thumbnail file without a matching image file. + if len(value.keys()) == 1: # only 'thumbnail_id' + for associated_data_file in datasub_record.resources: + if associated_data_file.id == thumbnail_id: + tmp_assoc_files[key].update({ + 'description': associated_data_file.file_description, + 'type': associated_data_file.file_type, + 'id': associated_data_file.id, + 'alt_location': associated_data_file.file_location}) + break # add associated files to the table contents table_contents['associated_files'] = list(tmp_assoc_files.values())