df6937379e481330126b1b4adc5e70117751b7ee
[redakcja.git] / apps / wiki / views.py
1 import os
2
3 from django.conf import settings
4 from django.views.generic.simple import direct_to_template
5 from django.http import HttpResponse, Http404
6 from django.utils import simplejson as json
7
8 from wiki.models import storage, Document, DocumentNotFound
9 from wiki.forms import DocumentForm
10 from datetime import datetime
11 from django.utils.encoding import smart_unicode
12
13 # import google_diff
14 # import difflib
15 import nice_diff
16 import operator
17
18 MAX_LAST_DOCS = 10
19
20 class DateTimeEncoder(json.JSONEncoder):
21      def default(self, obj):
22          if isinstance(obj, datetime):
23              return datetime.ctime(obj) + " " + (datetime.tzname(obj) or 'GMT')
24          return json.JSONEncoder.default(self, obj)
25
26 def document_list(request, template_name = 'wiki/document_list.html'):
27     # TODO: find a way to cache "Storage All"
28     return direct_to_template(request, template_name, extra_context = {
29         'document_list': storage.all(),
30         'last_docs': sorted(request.session.get("wiki_last_docs", {}).items(), 
31                         key=operator.itemgetter(1), reverse = True)
32     })  
33
34
35 def document_detail(request, name, template_name = 'wiki/document_details.html'):
36     try:
37         document = storage.get(name)
38     except DocumentNotFound:        
39         raise Http404
40     
41     access_time = datetime.now()
42     last_documents = request.session.get("wiki_last_docs", {})      
43     last_documents[name] = access_time
44     
45     if len(last_documents) > MAX_LAST_DOCS:
46         oldest_key = min(last_documents, key = last_documents.__getitem__)
47         del last_documents[oldest_key]        
48     request.session['wiki_last_docs'] = last_documents   
49                 
50     if request.method == 'POST':
51         
52         form = DocumentForm(request.POST, instance = document)
53         if form.is_valid():
54             document = form.save()
55             return HttpResponse(json.dumps({'text': document.plain_text, 'meta': document.meta(), 'revision': document.revision()}))
56         else:
57             return HttpResponse(json.dumps({'errors': form.errors}))
58     else:
59         form = DocumentForm(instance = document)
60
61     return direct_to_template(request, template_name, extra_context = {
62         'document': document,
63         'form': form,
64     })
65
66
67 def document_gallery(request, directory):
68     try:
69         base_dir = os.path.join(
70                     smart_unicode(settings.MEDIA_ROOT), 
71                     smart_unicode(settings.FILEBROWSER_DIRECTORY),
72                     smart_unicode(directory) )
73         
74         def map_to_url(filename):           
75                          
76             return '%s%s%s/%s' % (
77                         smart_unicode(settings.MEDIA_URL),                         
78                         smart_unicode(settings.FILEBROWSER_DIRECTORY),
79                         smart_unicode(directory),
80                         smart_unicode(filename)
81             )
82             
83         def is_image(filename):
84             return os.path.splitext(f)[1].lower() in (u'.jpg', u'.jpeg', u'.png')
85             
86         images = [ map_to_url(f) for f in map(smart_unicode, os.listdir(base_dir)) if is_image(f) ]
87         images.sort()
88         return HttpResponse(json.dumps(images))
89     except (IndexError, OSError), exc:
90         import traceback
91         traceback.print_exc()
92
93         raise Http404
94     
95 def document_diff(request, name, revA, revB):     
96     docA = storage.get(name, int(revA))
97     docB = storage.get(name, int(revB)) 
98     
99     
100     return HttpResponse(nice_diff.html_diff_table(docA.plain_text.splitlines(), 
101                                          docB.plain_text.splitlines()) )                                           
102     
103     
104 def document_history(reuqest, name):
105     return HttpResponse( json.dumps(storage.history(name), cls=DateTimeEncoder), mimetype='application/json')