Absolute URLs on ilustr
[redakcja.git] / src / documents / ilustr.py
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.
3 #
4 """Replacing relative addresses of illustrations with absolute URLs."""
5 import os.path
6 import re
7 from urllib.parse import quote, unquote, urljoin
8 from django.conf import settings
9
10
11 SRC_RE = re.compile(r'''(<ilustr\b[^>]*?\bsrc\s*=\s*)(["'])(.*?)\2''', re.S)
12
13
14 def is_absolute(src):
15     return src.startswith(('http://', 'https://'))
16
17
18 def absolutize(text, gallery_url, gallery_dir):
19     """Replaces relative `src` of illustrations in text with absolute URLs.
20
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.
23     """
24     fixed = []
25     unresolved = []
26
27     def repl(m):
28         src = m.group(3)
29         if is_absolute(src):
30             return m.group(0)
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)
34             return m.group(0)
35         fixed.append(src)
36         url = urljoin(gallery_url, quote(src, safe='/%'))
37         return m.group(1) + m.group(2) + url + m.group(2)
38
39     return SRC_RE.sub(repl, text), fixed, unresolved
40
41
42 class IlustrFixer:
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)
46         self.author = author
47         self.stats = dict.fromkeys(['books', 'fixed', 'unresolved', 'conflicts'], 0)
48
49     def fix_book(self, book):
50         if not book.gallery:
51             gallery_url = gallery_dir = None
52         else:
53             gallery_url = urljoin(self.images_url, quote(book.gallery) + '/')
54             gallery_dir = os.path.join(self.images_dir, book.gallery)
55
56         for chunk in book.chunk_set.all():
57             head = chunk.head
58             if head is None:
59                 continue
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))]
64                 if unresolved:
65                     self.stats['unresolved'] += len(unresolved)
66                 continue
67
68             new_text, fixed, unresolved = absolutize(head_text, gallery_url, gallery_dir)
69             self.stats['fixed'] += len(fixed)
70             self.stats['unresolved'] += len(unresolved)
71
72             if fixed:
73                 chunk.commit(
74                     new_text, description='Pełne adresy ilustracji.',
75                     publishable=head.publishable,
76                     **self.author)