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
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
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)
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)
35 def document_detail(request, name, template_name = 'wiki/document_details.html'):
37 document = storage.get(name)
38 except DocumentNotFound:
41 access_time = datetime.now()
42 last_documents = request.session.get("wiki_last_docs", {})
43 last_documents[name] = access_time
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
50 if request.method == 'POST':
52 form = DocumentForm(request.POST, instance = document)
54 document = form.save()
55 return HttpResponse(json.dumps({'text': document.plain_text, 'meta': document.meta(), 'revision': document.revision()}))
57 return HttpResponse(json.dumps({'errors': form.errors}))
59 form = DocumentForm(instance = document)
61 return direct_to_template(request, template_name, extra_context = {
67 def document_gallery(request, directory):
69 base_dir = os.path.join(
70 smart_unicode(settings.MEDIA_ROOT),
71 smart_unicode(settings.FILEBROWSER_DIRECTORY),
72 smart_unicode(directory) )
74 def map_to_url(filename):
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)
83 def is_image(filename):
84 return os.path.splitext(f)[1].lower() in (u'.jpg', u'.jpeg', u'.png')
86 images = [ map_to_url(f) for f in map(smart_unicode, os.listdir(base_dir)) if is_image(f) ]
88 return HttpResponse(json.dumps(images))
89 except (IndexError, OSError), exc:
95 def document_diff(request, name, revA, revB):
96 docA = storage.get(name, int(revA))
97 docB = storage.get(name, int(revB))
100 return HttpResponse(nice_diff.html_diff_table(docA.plain_text.splitlines(),
101 docB.plain_text.splitlines()) )
104 def document_history(reuqest, name):
105 return HttpResponse( json.dumps(storage.history(name), cls=DateTimeEncoder), mimetype='application/json')