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
14 # Quick hack around caching problems, TODO: use ETags
16 from django.views.decorators.cache import never_cache
19 logger = logging.getLogger("fnp.peanut.api")
26 class DateTimeEncoder(json.JSONEncoder):
27 def default(self, obj):
28 if isinstance(obj, datetime):
29 return datetime.ctime(obj) + " " + (datetime.tzname(obj) or 'GMT')
30 return json.JSONEncoder.default(self, obj)
33 def document_list(request, template_name = 'wiki/document_list.html'):
34 # TODO: find a way to cache "Storage All"
35 return direct_to_template(request, template_name, extra_context = {
36 'document_list': getstorage().all(),
37 'last_docs': sorted(request.session.get("wiki_last_docs", {}).items(),
38 key=operator.itemgetter(1), reverse = True)
42 def document_detail(request, name, template_name = 'wiki/document_details.html'):
43 print "Trying to get", repr(name)
45 document = getstorage().get(name)
46 except DocumentNotFound:
49 access_time = datetime.now()
50 last_documents = request.session.get("wiki_last_docs", {})
51 last_documents[name] = access_time
53 if len(last_documents) > MAX_LAST_DOCS:
54 oldest_key = min(last_documents, key = last_documents.__getitem__)
55 del last_documents[oldest_key]
56 request.session['wiki_last_docs'] = last_documents
58 if request.method == 'POST':
59 form = DocumentForm(request.POST, instance = document)
61 document = form.save(document_author = request.user.username)
62 return HttpResponse(json.dumps({'text': document.plain_text, 'meta': document.meta(), 'revision': document.revision()}))
64 return HttpResponse(json.dumps({'errors': form.errors}))
66 form = DocumentForm(instance = document)
68 return direct_to_template(request, template_name, extra_context = {
75 def document_gallery(request, directory):
77 base_dir = os.path.join(
78 smart_unicode(settings.MEDIA_ROOT),
79 smart_unicode(settings.FILEBROWSER_DIRECTORY),
80 smart_unicode(directory) )
82 def map_to_url(filename):
84 return '%s%s%s/%s' % (
85 smart_unicode(settings.MEDIA_URL),
86 smart_unicode(settings.FILEBROWSER_DIRECTORY),
87 smart_unicode(directory),
88 smart_unicode(filename)
91 def is_image(filename):
92 return os.path.splitext(f)[1].lower() in (u'.jpg', u'.jpeg', u'.png')
94 images = [ map_to_url(f) for f in map(smart_unicode, os.listdir(base_dir)) if is_image(f) ]
96 return HttpResponse(json.dumps(images))
97 except (IndexError, OSError), exc:
104 def document_diff(request, name, revA, revB):
105 storage = getstorage()
106 docA = storage.get(name, int(revA))
107 docB = storage.get(name, int(revB))
110 return HttpResponse(nice_diff.html_diff_table(docA.plain_text.splitlines(),
111 docB.plain_text.splitlines()) )
114 def document_history(request, name):
115 storage = getstorage()
118 json.dumps(storage.history(name), cls=DateTimeEncoder),
119 mimetype='application/json')
122 import urllib, urllib2
125 def document_publish(request, name, version):
126 storage = getstorage()
130 document = storage.get(name, revision = int(version))
131 except DocumentNotFound:
134 auth_handler = urllib2.HTTPDigestAuthHandler();
135 auth_handler.add_password(
136 realm="localhost:8000",
137 uri="http://localhost:8000/api/",
138 user="test", passwd="test")
141 opener = urllib2.build_opener(auth_handler)
142 rq = urllib2.Request("http://localhost:8000/api/books.json")
143 rq.add_data(json.dumps({"text": document.text, "compressed": False}))
144 rq.add_header("Content-Type", "application/json")
147 response = opener.open(rq)
148 result = {"success": True, "message": response.read()}
149 except urllib2.HTTPError, e:
150 logger.exception("Failed to send")
152 return HttpResponse(e.read(), mimetype='text/plain')
153 result = {"success": False, "reason": e.read(), "errno": e.code}
155 return HttpResponse( json.dumps(result), mimetype='application/json')