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