pdf: make thumbnail url vary with PDF form file content (#78879)
gitea/passerelle/pipeline/head This commit looks good Details

This commit is contained in:
Benjamin Dauvergne 2023-06-22 10:43:50 +02:00
parent 1afe1a8649
commit 5d05b38653
3 changed files with 37 additions and 1 deletions

View File

@ -15,6 +15,8 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import base64
import functools
import hashlib
import os
import subprocess
import tempfile
@ -139,6 +141,14 @@ class Resource(BaseResource):
class Meta:
verbose_name = _('PDF')
@functools.cached_property
def pdf_hash(self):
if self.fill_form_file:
with self.fill_form_file.open() as fd:
return hashlib.md5(fd.read()).hexdigest()
else:
return '0'
@classmethod
def get_manager_form_class(cls, **kwargs):
kwargs['exclude'] = tuple(kwargs.get('exclude') or ()) + ('fields_mapping',)

View File

@ -46,7 +46,7 @@
<map name="map-page-{{ page_number }}">
{{ image_map|safe }}
</map>
<img src="{% url "pdf-page-thumbnail" connector="pdf" slug=object.slug page_number=page_number %}" usemap="#map-page-{{ page_number }}">
<img src="{% url "pdf-page-thumbnail" connector="pdf" slug=object.slug page_number=page_number %}?hash={{ object.pdf_hash }}" usemap="#map-page-{{ page_number }}">
</div>
</div>
<div class="pdf-fields-mapping-edit-form--fields">

View File

@ -34,6 +34,7 @@ from tests.utils import generic_endpoint_url, setup_access_rights
with open(os.path.join(os.path.dirname(__file__), 'data', 'minimal.pdf'), 'rb') as fd:
pdf_content = fd.read()
pdf_b64content = base64.b64encode(pdf_content).decode()
with open(os.path.join(os.path.dirname(__file__), 'data', 'pdf-form.pdf'), 'rb') as fd:
acroform_content = fd.read()
acroform_b64content = base64.b64encode(acroform_content).decode()
@ -325,3 +326,28 @@ def test_add_or_edit(app, admin_user, pdf, cerfa_content):
pdf.fill_form_file.save('form.pdf', ContentFile(cerfa_content))
resp = app.get('/manage/pdf/test/edit')
assert b'fields_mapping' not in resp.content
def test_thumbnail_url_contains_hash(app, admin_user, pdf, cerfa_content):
pdf.fill_form_file.save('form.pdf', ContentFile(cerfa_content))
app = login(app)
resp = app.get('/pdf/test/')
resp = resp.click('Fill form: Edit fields mapping')
img_tags = resp.pyquery('img')
urls = [img_tag.attrib['src'] for img_tag in img_tags]
assert len(urls) == 5 # cerfa_content has 5 pages
assert all('?hash=' in url for url in urls)
assert not any(url.endswith('?hash=0') for url in urls)
first_url = urls[0]
pdf.fill_form_file.save('form.pdf', ContentFile(acroform_content))
resp = app.get('/pdf/test/')
resp = resp.click('Fill form: Edit fields mapping')
img_tags = resp.pyquery('img')
urls = [img_tag.attrib['src'] for img_tag in img_tags]
assert len(urls) == 1 # acroform_content has 1 page
assert all('?hash=' in url for url in urls)
assert not any(url.endswith('?hash=0') for url in urls)
assert urls[0] != first_url