78a194222d75e6d89bbcea3eac990eb6a17013ad
[redakcja.git] / apps / wiki / views.py
1 import os
2
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
7
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
12
13 #
14 # Quick hack around caching problems, TODO: use ETags
15 #
16 from django.views.decorators.cache import never_cache
17
18 import logging
19 logger = logging.getLogger("fnp.peanut.api")
20
21 import nice_diff
22 import operator
23
24 MAX_LAST_DOCS = 10
25
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)
31
32 @never_cache
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)
39     })  
40
41 @never_cache
42 def document_detail(request, name, template_name = 'wiki/document_details.html'):
43     print "Trying to get", repr(name)
44     try:
45         document = getstorage().get(name)
46     except DocumentNotFound:        
47         raise Http404
48     
49     access_time = datetime.now()
50     last_documents = request.session.get("wiki_last_docs", {})      
51     last_documents[name] = access_time
52     
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   
57                 
58     if request.method == 'POST':        
59         form = DocumentForm(request.POST, instance = document)
60         if form.is_valid():
61             document = form.save(document_author = request.user.username)
62             return HttpResponse(json.dumps({'text': document.plain_text, 'meta': document.meta(), 'revision': document.revision()}))
63         else:
64             return HttpResponse(json.dumps({'errors': form.errors}))
65     else:
66         form = DocumentForm(instance = document)
67
68     return direct_to_template(request, template_name, extra_context = {
69         'document': document,
70         'form': form,
71     })
72
73
74 @never_cache
75 def document_gallery(request, directory):
76     try:
77         base_dir = os.path.join(
78                     smart_unicode(settings.MEDIA_ROOT), 
79                     smart_unicode(settings.FILEBROWSER_DIRECTORY),
80                     smart_unicode(directory) )
81         
82         def map_to_url(filename):           
83                          
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)
89             )
90             
91         def is_image(filename):
92             return os.path.splitext(f)[1].lower() in (u'.jpg', u'.jpeg', u'.png')
93             
94         images = [ map_to_url(f) for f in map(smart_unicode, os.listdir(base_dir)) if is_image(f) ]
95         images.sort()
96         return HttpResponse(json.dumps(images))
97     except (IndexError, OSError), exc:
98         import traceback
99         traceback.print_exc()
100
101         raise Http404
102     
103 @never_cache
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)) 
108     
109     
110     return HttpResponse(nice_diff.html_diff_table(docA.plain_text.splitlines(), 
111                                          docB.plain_text.splitlines()) )                                           
112     
113 @never_cache    
114 def document_history(request, name):
115     storage = getstorage()
116     
117     return HttpResponse( 
118                 json.dumps(storage.history(name), cls=DateTimeEncoder), 
119                 mimetype='application/json')
120     
121     
122 import urllib, urllib2
123
124 @never_cache
125 def document_publish(request, name, version):
126     storage = getstorage()
127     
128     # get the document
129     try:
130         document = storage.get(name, revision = int(version))
131     except DocumentNotFound:        
132         raise Http404
133     
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")
139     
140     
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")
145     
146     try:
147         response = opener.open(rq)                 
148         result = {"success": True, "message": response.read()}        
149     except urllib2.HTTPError, e:
150         logger.exception("Failed to send")
151         if e.code == 500:
152             return HttpResponse(e.read(), mimetype='text/plain')                        
153         result = {"success": False, "reason": e.read(), "errno": e.code}
154         
155     return HttpResponse( json.dumps(result), mimetype='application/json')