21c9fe5b6f20e4cfaa07e7e0ef81442e264bd9a9
[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 import httplib2
14 import poster
15 import nice_diff
16 import operator
17
18 MAX_LAST_DOCS = 10
19
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)
25
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)
32     })  
33
34
35 def document_detail(request, name, template_name = 'wiki/document_details.html'):
36     print "Trying to get", repr(name)
37     try:
38         document = storage.get(name)
39     except DocumentNotFound:        
40         raise Http404
41     
42     access_time = datetime.now()
43     last_documents = request.session.get("wiki_last_docs", {})      
44     last_documents[name] = access_time
45     
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   
50                 
51     if request.method == 'POST':        
52         form = DocumentForm(request.POST, instance = document)
53         if form.is_valid():
54             document = form.save(document_author = request.user.username)
55             return HttpResponse(json.dumps({'text': document.plain_text, 'meta': document.meta(), 'revision': document.revision()}))
56         else:
57             return HttpResponse(json.dumps({'errors': form.errors}))
58     else:
59         form = DocumentForm(instance = document)
60
61     return direct_to_template(request, template_name, extra_context = {
62         'document': document,
63         'form': form,
64     })
65
66
67 def document_gallery(request, directory):
68     try:
69         base_dir = os.path.join(
70                     smart_unicode(settings.MEDIA_ROOT), 
71                     smart_unicode(settings.FILEBROWSER_DIRECTORY),
72                     smart_unicode(directory) )
73         
74         def map_to_url(filename):           
75                          
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)
81             )
82             
83         def is_image(filename):
84             return os.path.splitext(f)[1].lower() in (u'.jpg', u'.jpeg', u'.png')
85             
86         images = [ map_to_url(f) for f in map(smart_unicode, os.listdir(base_dir)) if is_image(f) ]
87         images.sort()
88         return HttpResponse(json.dumps(images))
89     except (IndexError, OSError), exc:
90         import traceback
91         traceback.print_exc()
92
93         raise Http404
94     
95 def document_diff(request, name, revA, revB):     
96     docA = storage.get(name, int(revA))
97     docB = storage.get(name, int(revB)) 
98     
99     
100     return HttpResponse(nice_diff.html_diff_table(docA.plain_text.splitlines(), 
101                                          docB.plain_text.splitlines()) )                                           
102     
103     
104 def document_history(request, name):
105     return HttpResponse( 
106                 json.dumps(storage.history(name), cls=DateTimeEncoder), 
107                 mimetype='application/json')
108
109
110 def document_publish(request, name, version):
111     # get the document
112     try:
113         document = storage.get(name, revision = int(version))
114     except DocumentNotFound:        
115         raise Http404
116     
117     poster.streaminghttp.register_openers()
118     
119     # send request to WL
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})
124     
125     for key, value in headers.items():
126         headers[key] = unicode(value)
127         
128     try:
129         resp, data = http.request("http://localhost:8000/api/books.json", 
130             method = "POST", body = ''.join(datagen), headers = headers)
131         
132         print resp, data    
133     
134         if resp.status == 201: # success
135             result = {"success": True}
136         else:
137             result = {"success": False, "errno": resp.status, "reason": resp.reason}
138     except Exception, e:
139         result = {"success": False, "errno": 500, "reason": unicode(e)}
140         
141     return HttpResponse( json.dumps(result), mimetype='application/json')