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
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': storage.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 = storage.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 docA = storage.get(name, int(revA))
106 docB = storage.get(name, int(revB))
109 return HttpResponse(nice_diff.html_diff_table(docA.plain_text.splitlines(),
110 docB.plain_text.splitlines()) )
113 def document_history(request, name):
115 json.dumps(storage.history(name), cls=DateTimeEncoder),
116 mimetype='application/json')
119 import urllib, urllib2
122 def document_publish(request, name, version):
125 document = storage.get(name, revision = int(version))
126 except DocumentNotFound:
129 auth_handler = urllib2.HTTPDigestAuthHandler();
130 auth_handler.add_password(
131 realm="localhost:8000",
132 uri="http://localhost:8000/api/",
133 user="test", passwd="test")
136 opener = urllib2.build_opener(auth_handler)
137 rq = urllib2.Request("http://localhost:8000/api/books.json")
138 rq.add_data(json.dumps({"text": document.text, "compressed": False}))
139 rq.add_header("Content-Type", "application/json")
142 response = opener.open(rq)
143 result = {"success": True, "message": response.read()}
144 except urllib2.HTTPError, e:
145 logger.exception("Failed to send")
147 return HttpResponse(e.read(), mimetype='text/plain')
148 result = {"success": False, "reason": e.read(), "errno": e.code}
150 return HttpResponse( json.dumps(result), mimetype='application/json')