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 Document, DocumentNotFound, getstorage
9 from wiki.forms import DocumentForm, DocumentTextSaveForm
10 from datetime import datetime
11 from django.utils.encoding import smart_unicode
15 # Quick hack around caching problems, TODO: use ETags
17 from django.views.decorators.cache import never_cache
20 logger = logging.getLogger("fnp.peanut.api")
27 class DateTimeEncoder(json.JSONEncoder):
28 def default(self, obj):
29 if isinstance(obj, datetime):
30 return datetime.ctime(obj) + " " + (datetime.tzname(obj) or 'GMT')
31 return json.JSONEncoder.default(self, obj)
34 def document_list(request, template_name = 'wiki/document_list.html'):
35 # TODO: find a way to cache "Storage All"
36 return direct_to_template(request, template_name, extra_context = {
37 'document_list': getstorage().all(),
38 'last_docs': sorted(request.session.get("wiki_last_docs", {}).items(),
39 key=operator.itemgetter(1), reverse = True)
43 def document_detail(request, name, template_name = 'wiki/document_details.html'):
46 document = getstorage().get(name)
47 except DocumentNotFound:
50 access_time = datetime.now()
51 last_documents = request.session.get("wiki_last_docs", {})
52 last_documents[name] = access_time
54 if len(last_documents) > MAX_LAST_DOCS:
55 oldest_key = min(last_documents, key = last_documents.__getitem__)
56 del last_documents[oldest_key]
57 request.session['wiki_last_docs'] = last_documents
59 return direct_to_template(request, template_name, extra_context = {
61 'document_info': document.info,
62 'document_meta': document.meta,
63 'text_save_form': DocumentTextSaveForm(),
67 def document_text(request, name):
69 document = getstorage().get(name)
70 except DocumentNotFound:
73 if request.method == 'POST':
74 form = DocumentForm(request.POST, instance = document)
76 document = form.save(document_author = request.user.username)
77 return HttpResponse(json.dumps({'text': document.plain_text, 'meta': document.meta(), 'revision': document.revision()}))
79 return HttpResponse(json.dumps({'errors': list(form.errors)}))
81 return HttpResponse(json.dumps({'text': document.plain_text, 'meta': document.meta(), 'revision': document.revision()}))
86 def document_gallery(request, directory):
88 base_dir = os.path.join(
89 smart_unicode(settings.MEDIA_ROOT),
90 smart_unicode(settings.FILEBROWSER_DIRECTORY),
91 smart_unicode(directory) )
93 def map_to_url(filename):
95 return '%s%s%s/%s' % (
96 smart_unicode(settings.MEDIA_URL),
97 smart_unicode(settings.FILEBROWSER_DIRECTORY),
98 smart_unicode(directory),
99 smart_unicode(filename)
102 def is_image(filename):
103 return os.path.splitext(f)[1].lower() in (u'.jpg', u'.jpeg', u'.png')
105 images = [ map_to_url(f) for f in map(smart_unicode, os.listdir(base_dir)) if is_image(f) ]
107 return HttpResponse(json.dumps(images))
108 except (IndexError, OSError), exc:
110 traceback.print_exc()
115 def document_diff(request, name, revA, revB):
116 storage = getstorage()
117 docA = storage.get(name, int(revA))
118 docB = storage.get(name, int(revB))
121 return HttpResponse(nice_diff.html_diff_table(docA.plain_text.splitlines(),
122 docB.plain_text.splitlines()) )
125 def document_history(request, name):
126 storage = getstorage()
129 json.dumps(storage.history(name), cls=DateTimeEncoder),
130 mimetype='application/json')
134 def document_publish(request, name, version):
135 storage = getstorage()
139 document = storage.get(name, revision = int(version))
140 except DocumentNotFound:
143 api = wlapi.WLAPI(settings.WL_API_CONFIG)
145 result = {"success": True, "result": api.publish_book(document)}
146 except wlapi.APICallException, e:
147 result = {"success": False, "reason": str(e)}
149 return HttpResponse( json.dumps(result), mimetype='application/json')