931cf78d0cbf75f62a35e4e1434153ddf27a35b8
[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
12 # import google_diff
13 import difflib
14
15
16 class DateTimeEncoder(json.JSONEncoder):
17      def default(self, obj):
18          if isinstance(obj, datetime):
19              return datetime.ctime(obj) + " " + (datetime.tzname(obj) or 'GMT')
20          return json.JSONEncoder.default(self, obj)
21
22 def document_list(request, template_name = 'wiki/document_list.html'):
23     return direct_to_template(request, template_name, extra_context = {
24         'document_list': storage.all(),
25     })
26
27
28 def document_detail(request, name, template_name = 'wiki/document_details.html'):
29     try:
30         document = storage.get(name)
31     except DocumentNotFound:
32         # WTF ?!
33         raise Http404 
34         # document = Document(storage, name = name, text = '')
35
36     if request.method == 'POST':
37         form = DocumentForm(request.POST, instance = document)
38         if form.is_valid():
39             document = form.save()
40             return HttpResponse(json.dumps({'text': document.plain_text, 'meta': document.meta(), 'revision': document.revision()}))
41         else:
42             return HttpResponse(json.dumps({'errors': form.errors}))
43     else:
44         form = DocumentForm(instance = document)
45
46     return direct_to_template(request, template_name, extra_context = {
47         'document': document,
48         'form': form,
49     })
50
51
52 def document_gallery(request, directory):
53     try:
54         base_dir = os.path.join(settings.MEDIA_ROOT, settings.FILEBROWSER_DIRECTORY, directory)
55         images = [u'%s%s%s/%s' % (settings.MEDIA_URL, settings.FILEBROWSER_DIRECTORY, directory, f) for f in os.listdir(base_dir) if os.path.splitext(f)[1].lower() in (u'.jpg', u'.jpeg', u'.png')]
56         images.sort()
57         return HttpResponse(json.dumps(images))
58     except (IndexError, OSError), exc:
59         import traceback
60         traceback.print_exc()
61
62         raise Http404
63     
64 def document_diff(request, name, revA, revB):
65     differ = difflib.HtmlDiff(wrapcolumn=60)
66      
67     docA = storage.get(name, int(revA))
68     docB = storage.get(name, int(revB))
69      
70     return HttpResponse(differ.make_table(
71                                 docA.plain_text.splitlines(),
72                                 docB.plain_text.splitlines() ) )                                           
73     
74     
75 def document_history(reuqest, name):
76     return HttpResponse( json.dumps(storage.history(name), cls=DateTimeEncoder), mimetype='application/json')