Logging for staging, removed unused requirements.
[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 storage, Document, DocumentNotFound
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': storage.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 = storage.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     docA = storage.get(name, int(revA))
106     docB = storage.get(name, int(revB)) 
107     
108     
109     return HttpResponse(nice_diff.html_diff_table(docA.plain_text.splitlines(), 
110                                          docB.plain_text.splitlines()) )                                           
111     
112 @never_cache    
113 def document_history(request, name):
114     return HttpResponse( 
115                 json.dumps(storage.history(name), cls=DateTimeEncoder), 
116                 mimetype='application/json')
117     
118     
119 import urllib, urllib2
120
121 @never_cache
122 def document_publish(request, name, version):
123     # get the document
124     try:
125         document = storage.get(name, revision = int(version))
126     except DocumentNotFound:        
127         raise Http404
128     
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")
134     
135     
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")
140     
141     try:
142         response = opener.open(rq)                 
143         result = {"success": True, "message": response.read()}        
144     except urllib2.HTTPError, e:
145         logger.exception("Failed to send")
146         if e.code == 500:
147             return HttpResponse(e.read(), mimetype='text/plain')                        
148         result = {"success": False, "reason": e.read(), "errno": e.code}
149         
150     return HttpResponse( json.dumps(result), mimetype='application/json')