Basic changes, to display nicer names.
[redakcja.git] / apps / wiki / models.py
1 # -*- coding: utf-8 -*-
2 #
3 # This file is part of FNP-Redakcja, licensed under GNU Affero GPLv3 or later.
4 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
5 #
6 import re
7 import os
8 import vstorage
9 from vstorage import DocumentNotFound
10 from wiki import settings, constants
11 from django.utils.translation import ugettext_lazy as _
12
13 from django.http import Http404
14
15 import logging
16 logger = logging.getLogger("fnp.wiki")
17
18 _PCHARS_DICT = dict(zip((ord(x) for x in u"ĄĆĘŁŃÓŚŻŹąćęłńóśżź "), u"ACELNOSZZacelnoszz_"))
19
20 # I know this is barbaric, but I didn't find a better solution ;(
21 def split_name(name):
22     parts = name.translate(_PCHARS_DICT).split('__')
23     logger.info("SPLIT %r -> %r", name, parts)
24     return parts
25
26 def join_name(*parts, **kwargs):
27     name = u'__'.join(p.translate(_PCHARS_DICT) for p in parts)
28     logger.info("JOIN %r -> %r", parts, name)
29     return name
30
31 def normalize_name(name):
32     """
33     >>> normalize_name("gąska".decode('utf-8'))
34     u'gaska'
35     """
36     return name.translate(_PCHARS_DICT).lower()
37
38 STAGE_TAGS_RE = re.compile(r'^#stage-finished: (.*)$', re.MULTILINE)
39
40
41 class DocumentStorage(object):
42     def __init__(self, path):
43         self.vstorage = vstorage.VersionedStorage(path)
44
45     def get(self, name, revision=None):
46         text, rev = self.vstorage.page_text(name, revision)
47         return Document(self, name=name, text=text, revision=rev)
48
49     def get_by_tag(self, name, tag):
50         text, rev = self.vstorage.page_text_by_tag(name, tag)
51         return Document(self, name=name, text=text, revision=rev)
52
53     def get_or_404(self, *args, **kwargs):
54         try:
55             return self.get(*args, **kwargs)
56         except DocumentNotFound:
57             raise Http404
58
59     def put(self, document, author, comment, parent=None):
60         self.vstorage.save_text(
61                 title=document.name,
62                 text=document.text,
63                 author=author,
64                 comment=comment,
65                 parent=parent)
66
67         return document
68
69     def create_document(self, text, name):
70         title = u', '.join(p.title for p in split_name(name))
71
72         if text is None:
73             text = u''
74
75         document = Document(self, name=name, text=text, title=title)
76         return self.put(document, u"<wiki>", u"Document created.")
77
78     def delete(self, name, author, comment):
79         self.vstorage.delete_page(name, author, comment)
80
81     def all(self):
82         return list(self.vstorage.all_pages())
83
84     def history(self, title):
85         def stage_desc(match):
86             stage = match.group(1)
87             return _("Finished stage: %s") % constants.DOCUMENT_STAGES_DICT[stage]
88
89         for changeset in self.vstorage.page_history(title):
90             changeset['description'] = STAGE_TAGS_RE.sub(stage_desc, changeset['description'])
91             yield changeset
92
93
94
95 class Document(object):
96     META_REGEX = re.compile(r'\s*<!--\s(.*?)-->', re.DOTALL | re.MULTILINE)
97
98     def __init__(self, storage, **kwargs):
99         self.storage = storage
100         for attr, value in kwargs.iteritems():
101             setattr(self, attr, value)
102
103     def add_tag(self, tag, revision, author):
104         """ Add document specific tag """
105         logger.debug("Adding tag %s to doc %s version %d", tag, self.name, revision)
106         self.storage.vstorage.add_page_tag(self.name, revision, tag, user=author)
107
108     @property
109     def plain_text(self):
110         return re.sub(self.META_REGEX, '', self.text, 1)
111
112     def meta(self):
113         result = {}
114
115         m = re.match(self.META_REGEX, self.text)
116         if m:
117             for line in m.group(1).split('\n'):
118                 try:
119                     k, v = line.split(':', 1)
120                     result[k.strip()] = v.strip()
121                 except ValueError:
122                     continue
123
124         gallery = result.get('gallery', self.name.replace(' ', '_'))
125
126         if gallery.startswith('/'):
127             gallery = os.path.basename(gallery)
128
129         result['gallery'] = gallery
130         return result
131
132     def info(self):
133         return self.storage.vstorage.page_meta(self.name, self.revision)
134
135 def getstorage():
136     return DocumentStorage(settings.REPOSITORY_PATH)
137
138 #
139 # Django models
140 #