Javascript refactoring. History view now displays tags
[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 vstorage
8 from vstorage import DocumentNotFound
9 from wiki import settings
10
11 class DocumentStorage(object):
12     def __init__(self, path):
13         self.vstorage = vstorage.VersionedStorage(path)
14
15     def get(self, name, revision = None):
16         if revision is None:
17             text = self.vstorage.page_text(name)
18         else:
19             text = self.vstorage.revision_text(name, revision)
20         return Document(self, name = name, text = text)
21
22     def put(self, document, author, comment, parent):
23         self.vstorage.save_text(
24                 title = document.name,
25                 text = document.text, 
26                 author = author, 
27                 comment = comment, 
28                 parent = parent)
29
30     def delete(self, name, author, comment):
31         self.vstorage.delete_page(name, author, comment)
32
33     def all(self):
34         return list(self.vstorage.all_pages())
35     
36     def history(self, title):
37         return list(self.vstorage.page_history(title))
38
39     def _info(self, name):
40         return self.vstorage.page_meta(name)
41
42
43 class Document(object):
44     META_REGEX = re.compile(r'\s*<!--\s(.*?)-->', re.DOTALL | re.MULTILINE)
45
46     def __init__(self, storage, **kwargs):
47         self.storage = storage
48         for attr, value in kwargs.iteritems():
49             setattr(self, attr, value)
50
51     def revision(self):
52         try:
53             return self.storage._info(self.name)[0]
54         except DocumentNotFound:
55             return - 1
56
57     @property
58     def plain_text(self):
59         return re.sub(self.META_REGEX, '', self.text, 1)
60
61     def meta(self):
62         result = {}
63
64         m = re.match(self.META_REGEX, self.text)
65         if m:
66             for line in m.group(1).split('\n'):
67                 try:
68                     k, v = line.split(':', 1)
69                     result[k.strip()] = v.strip()
70                 except ValueError:
71                     continue                
72                 
73         if 'gallery' not in result:
74             result['gallery'] = (settings.GALLERY_URL + self.name).replace(' ', '_')
75             
76         if 'title' not in result:
77             result['title'] = self.name.title()            
78
79         return result
80     
81     def info(self):
82         return dict(zip(
83             ('revision', 'last_update', 'last_comitter', 'commit_message'),
84             self.storage._info(self.name)
85         ))                         
86
87 def getstorage():
88     return DocumentStorage(settings.REPOSITORY_PATH)