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
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 = {
64 def document_text(request, name):
66 document = getstorage().get(name)
67 except DocumentNotFound:
70 if request.method == 'POST':
71 form = DocumentForm(request.POST, instance = document)
73 document = form.save(document_author = request.user.username)
74 return HttpResponse(json.dumps({'text': document.plain_text, 'meta': document.meta(), 'revision': document.revision()}))
76 return HttpResponse(json.dumps({'errors': form.errors}))
78 return HttpResponse(json.dumps({'text': document.plain_text, 'meta': document.meta(), 'revision': document.revision()}))
83 def document_gallery(request, directory):
85 base_dir = os.path.join(
86 smart_unicode(settings.MEDIA_ROOT),
87 smart_unicode(settings.FILEBROWSER_DIRECTORY),
88 smart_unicode(directory) )
90 def map_to_url(filename):
92 return '%s%s%s/%s' % (
93 smart_unicode(settings.MEDIA_URL),
94 smart_unicode(settings.FILEBROWSER_DIRECTORY),
95 smart_unicode(directory),
96 smart_unicode(filename)
99 def is_image(filename):
100 return os.path.splitext(f)[1].lower() in (u'.jpg', u'.jpeg', u'.png')
102 images = [ map_to_url(f) for f in map(smart_unicode, os.listdir(base_dir)) if is_image(f) ]
104 return HttpResponse(json.dumps(images))
105 except (IndexError, OSError), exc:
107 traceback.print_exc()
112 def document_diff(request, name, revA, revB):
113 storage = getstorage()
114 docA = storage.get(name, int(revA))
115 docB = storage.get(name, int(revB))
118 return HttpResponse(nice_diff.html_diff_table(docA.plain_text.splitlines(),
119 docB.plain_text.splitlines()) )
122 def document_history(request, name):
123 storage = getstorage()
126 json.dumps(storage.history(name), cls=DateTimeEncoder),
127 mimetype='application/json')
131 def document_publish(request, name, version):
132 storage = getstorage()
136 document = storage.get(name, revision = int(version))
137 except DocumentNotFound:
140 api = wlapi.WLAPI(settings.WL_API_CONFIG)
142 result = {"success": True, "result": api.publish_book(document)}
143 except wlapi.APICallException, e:
144 result = {"success": False, "reason": str(e)}
146 return HttpResponse( json.dumps(result), mimetype='application/json')