1 # This file is part of FNP-Redakcja, licensed under GNU Affero GPLv3 or later.
2 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
4 """Replacing relative addresses of illustrations with absolute URLs."""
7 from urllib.parse import quote, unquote, urljoin
8 from django.conf import settings
11 SRC_RE = re.compile(r'''(<ilustr\b[^>]*?\bsrc\s*=\s*)(["'])(.*?)\2''', re.S)
15 return src.startswith(('http://', 'https://'))
18 def absolutize(text, gallery_url, gallery_dir):
19 """Replaces relative `src` of illustrations in text with absolute URLs.
21 Only replaces addresses of files which exist in the gallery.
22 Returns the new text, a list of replaced and a list of unresolved addresses.
31 path = os.path.normpath(os.path.join(gallery_dir, unquote(src)))
32 if not src or not os.path.isfile(path):
33 unresolved.append(src)
36 url = urljoin(gallery_url, quote(src, safe='/%'))
37 return m.group(1) + m.group(2) + url + m.group(2)
39 return SRC_RE.sub(repl, text), fixed, unresolved
43 def __init__(self, base_url, **author):
44 self.images_url = urljoin(base_url, settings.MEDIA_URL + settings.IMAGE_DIR)
45 self.images_dir = os.path.join(settings.MEDIA_ROOT, settings.IMAGE_DIR)
47 self.stats = dict.fromkeys(['books', 'fixed', 'unresolved', 'conflicts'], 0)
49 def fix_book(self, book):
51 gallery_url = gallery_dir = None
53 gallery_url = urljoin(self.images_url, quote(book.gallery) + '/')
54 gallery_dir = os.path.join(self.images_dir, book.gallery)
56 for chunk in book.chunk_set.all():
60 head_text = head.materialize()
61 if gallery_url is None:
62 unresolved = [m.group(3) for m in SRC_RE.finditer(head_text)
63 if not is_absolute(m.group(3))]
65 self.stats['unresolved'] += len(unresolved)
68 new_text, fixed, unresolved = absolutize(head_text, gallery_url, gallery_dir)
69 self.stats['fixed'] += len(fixed)
70 self.stats['unresolved'] += len(unresolved)
74 new_text, description='Pełne adresy ilustracji.',
75 publishable=head.publishable,