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'):
36 print "Trying to get", repr(name)
38 document = storage.get(name)
39 except DocumentNotFound:
42 access_time = datetime.now()
43 last_documents = request.session.get("wiki_last_docs", {})
44 last_documents[name] = access_time
46 if len(last_documents) > MAX_LAST_DOCS:
47 oldest_key = min(last_documents, key = last_documents.__getitem__)
48 del last_documents[oldest_key]
49 request.session['wiki_last_docs'] = last_documents
51 if request.method == 'POST':
52 form = DocumentForm(request.POST, instance = document)
54 document = form.save(document_author = request.user.username)
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(request, name):
106 json.dumps(storage.history(name), cls=DateTimeEncoder),
107 mimetype='application/json')
110 def document_publish(request, name, version):
113 document = storage.get(name, revision = int(version))
114 except DocumentNotFound:
117 poster.streaminghttp.register_openers()
120 http = httplib2.Http()
121 http.add_credentials("test", "test")
122 http.follow_all_redirects = True
123 datagen, headers = poster.encode.multipart_encode({name: document.plain_text})
125 for key, value in headers.items():
126 headers[key] = unicode(value)
129 resp, data = http.request("http://localhost:8000/api/books.json",
130 method = "POST", body = ''.join(datagen), headers = headers)
134 if resp.status == 201: # success
135 result = {"success": True}
137 result = {"success": False, "errno": resp.status, "reason": resp.reason}
139 result = {"success": False, "errno": 500, "reason": unicode(e)}
141 return HttpResponse( json.dumps(result), mimetype='application/json')