From: Radek Czajka Date: Mon, 16 Nov 2026 07:39:55 +0000 (+0100) Subject: Absolute URLs on ilustr X-Git-Url: https://git.mdrn.pl/redakcja.git/commitdiff_plain/f01db0e7ea781ecc960673271a861523638393cc?ds=sidebyside Absolute URLs on ilustr --- diff --git a/src/documents/ilustr.py b/src/documents/ilustr.py new file mode 100644 index 00000000..30102adb --- /dev/null +++ b/src/documents/ilustr.py @@ -0,0 +1,76 @@ +# This file is part of FNP-Redakcja, licensed under GNU Affero GPLv3 or later. +# Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information. +# +"""Replacing relative addresses of illustrations with absolute URLs.""" +import os.path +import re +from urllib.parse import quote, unquote, urljoin +from django.conf import settings + + +SRC_RE = re.compile(r'''(]*?\bsrc\s*=\s*)(["'])(.*?)\2''', re.S) + + +def is_absolute(src): + return src.startswith(('http://', 'https://')) + + +def absolutize(text, gallery_url, gallery_dir): + """Replaces relative `src` of illustrations in text with absolute URLs. + + Only replaces addresses of files which exist in the gallery. + Returns the new text, a list of replaced and a list of unresolved addresses. + """ + fixed = [] + unresolved = [] + + def repl(m): + src = m.group(3) + if is_absolute(src): + return m.group(0) + path = os.path.normpath(os.path.join(gallery_dir, unquote(src))) + if not src or not os.path.isfile(path): + unresolved.append(src) + return m.group(0) + fixed.append(src) + url = urljoin(gallery_url, quote(src, safe='/%')) + return m.group(1) + m.group(2) + url + m.group(2) + + return SRC_RE.sub(repl, text), fixed, unresolved + + +class IlustrFixer: + def __init__(self, base_url, **author): + self.images_url = urljoin(base_url, settings.MEDIA_URL + settings.IMAGE_DIR) + self.images_dir = os.path.join(settings.MEDIA_ROOT, settings.IMAGE_DIR) + self.author = author + self.stats = dict.fromkeys(['books', 'fixed', 'unresolved', 'conflicts'], 0) + + def fix_book(self, book): + if not book.gallery: + gallery_url = gallery_dir = None + else: + gallery_url = urljoin(self.images_url, quote(book.gallery) + '/') + gallery_dir = os.path.join(self.images_dir, book.gallery) + + for chunk in book.chunk_set.all(): + head = chunk.head + if head is None: + continue + head_text = head.materialize() + if gallery_url is None: + unresolved = [m.group(3) for m in SRC_RE.finditer(head_text) + if not is_absolute(m.group(3))] + if unresolved: + self.stats['unresolved'] += len(unresolved) + continue + + new_text, fixed, unresolved = absolutize(head_text, gallery_url, gallery_dir) + self.stats['fixed'] += len(fixed) + self.stats['unresolved'] += len(unresolved) + + if fixed: + chunk.commit( + new_text, description='Pełne adresy ilustracji.', + publishable=head.publishable, + **self.author) diff --git a/src/documents/models/book.py b/src/documents/models/book.py index aa4e776e..1245ceab 100644 --- a/src/documents/models/book.py +++ b/src/documents/models/book.py @@ -307,6 +307,26 @@ class Book(models.Model): valid_about = self.correct_about() assert bi.about == valid_about, _("rdf:about is not") + " " + valid_about + srcs = self.relative_ilustr_srcs(changes=changes) + assert not srcs, 'Ilustracje bez pełnego adresu: ' + ', '.join( + src or '(pusty)' for src in srcs) + + def relative_ilustr_srcs(self, changes=None): + """Returns `src` of illustrations which aren't absolute URLs. + + Those only work relative to the gallery, so they break + outside of it. Checks the current text, unless `changes` are given. + """ + from lxml import etree + try: + tree = etree.fromstring(self.materialize(changes=changes).encode('utf-8')) + except (self.NoTextError, etree.XMLSyntaxError): + return [] + return [ + elem.get('src', '') for elem in tree.iter('ilustr') + if not elem.get('src', '').startswith(('http://', 'https://')) + ] + def publishable_error(self): try: return self.assert_publishable() diff --git a/src/documents/templates/documents/base.html b/src/documents/templates/documents/base.html index f8368888..c2c72434 100644 --- a/src/documents/templates/documents/base.html +++ b/src/documents/templates/documents/base.html @@ -52,6 +52,14 @@
+ {% if messages %} + {% for message in messages %} + + {% endfor %} + {% endif %} {% block content %}
diff --git a/src/documents/templates/documents/book_detail.html b/src/documents/templates/documents/book_detail.html index a9c4d2b0..8bf4329a 100644 --- a/src/documents/templates/documents/book_detail.html +++ b/src/documents/templates/documents/book_detail.html @@ -173,6 +173,19 @@ {% endif %}

+ {% with srcs=book.relative_ilustr_srcs %} + {% if srcs %} +
+ {% csrf_token %} + Ilustracje bez pełnego adresu: + {% for src in srcs %}{{ src|default:"(pusty)" }}{% if not forloop.last %}, {% endif %}{% endfor %} + {% if user.is_authenticated %} + + {% endif %} +
+ {% endif %} + {% endwith %} + {% if publishable %}

{% trans "Full XML" %}
diff --git a/src/documents/urls.py b/src/documents/urls.py index 60aa3fae..f23aad88 100644 --- a/src/documents/urls.py +++ b/src/documents/urls.py @@ -31,6 +31,7 @@ urlpatterns = [ path('create/', views.create_missing, name='documents_create_missing'), path('book//publish', views.publish, name="documents_publish"), + path('book//fix-ilustr', views.fix_ilustr, name="documents_fix_ilustr"), path('book//', views.book, name="documents_book"), path('book//gallery/', diff --git a/src/documents/views.py b/src/documents/views.py index e87dc6db..cab58bee 100644 --- a/src/documents/views.py +++ b/src/documents/views.py @@ -11,7 +11,7 @@ import os from urllib.parse import quote_plus, unquote, urlsplit, urlunsplit from django.conf import settings -from django.contrib import auth +from django.contrib import auth, messages from django.contrib.auth.models import User from django.contrib.auth.decorators import login_required, permission_required from django.urls import reverse @@ -676,6 +676,22 @@ def publish(request, slug): return http.HttpResponseRedirect(book.get_absolute_url()) +@require_POST +@login_required +def fix_ilustr(request, slug): + from .ilustr import IlustrFixer + book = get_object_or_404(Book, slug=slug) + protocol = 'https://' if request.is_secure() else 'http://' + fixer = IlustrFixer(protocol + request.get_host(), author=request.user) + with transaction.atomic(): + fixer.fix_book(book) + if fixer.stats['unresolved'] or fixer.stats['conflicts']: + messages.warning(request, 'Nie wszystkie ilustracje udało się naprawić.') + elif fixer.stats['fixed']: + messages.success(request, 'Naprawiono adresy ilustracji.') + return http.HttpResponseRedirect(book.get_absolute_url()) + + @require_POST @login_required def publish_image(request, slug): diff --git a/src/redakcja/static/js/wiki/view_properties.js b/src/redakcja/static/js/wiki/view_properties.js index dde914fc..6ae6e571 100644 --- a/src/redakcja/static/js/wiki/view_properties.js +++ b/src/redakcja/static/js/wiki/view_properties.js @@ -171,7 +171,7 @@ self.doc.refreshImageGallery({ success: function(galleryImages) { - $.each(self.doc.galleryImages, (i, imgItem) => { + $.each(galleryImages, (i, imgItem) => { let img = $("").attr("src", imgItem.thumb).attr('title', imgItem.url).data('url', imgItem.url).on('click', function() { imglist.find('img').removeClass('active'); $(this).addClass('active'); diff --git a/src/wiki/static/wiki/scss/visual.scss b/src/wiki/static/wiki/scss/visual.scss index 027340a0..3130a156 100644 --- a/src/wiki/static/wiki/scss/visual.scss +++ b/src/wiki/static/wiki/scss/visual.scss @@ -4,5 +4,18 @@ font-size: 1rem; line-height: 1.5; } + + // Images require absolute src. + [x-node="ilustr"]:not([x-a-wl-src^="http://"]):not([x-a-wl-src^="https://"]) { + outline: 3px solid #dc3545; + + &::before { + content: "Ilustracja bez pełnego adresu"; + display: block; + color: #dc3545; + font-family: sans-serif; + font-size: .8rem; + } + } }