82c9d39859f76eb889fb5e74278a4d2370fbd3bb
[redakcja.git] / apps / explorer / views.py
1 # -*- coding: utf-8 -*-
2 import urllib2
3 import hg
4 from librarian import html, parser, dcparser, ParseError, ValidationError
5
6 from django.conf import settings
7 from django.contrib.auth.decorators import login_required, permission_required
8
9 from django.core.urlresolvers import reverse
10 from django.http import HttpResponseRedirect, HttpResponse
11 from django.utils import simplejson as json
12 from django.views.generic.simple import direct_to_template
13
14 from explorer import forms, models
15 from toolbar import models as toolbar_models
16
17 #
18 # Some useful decorators
19 #
20 def with_repo(view):
21     """Open a repository for this view"""
22     def view_with_repo(request, *args, **kwargs):          
23         kwargs['repo'] = hg.Repository(settings.REPOSITORY_PATH)
24         return view(request, *args, **kwargs)
25     return view_with_repo
26
27 #
28 def ajax_login_required(view):
29     """Similar ro @login_required, but instead of redirect, 
30     just return some JSON stuff with error."""
31     def view_with_auth(request, *args, **kwargs):
32         if request.user.is_authenticated():
33             return view(request, *args, **kwargs)
34         # not authenticated
35         return HttpResponse( json.dumps({'result': 'access_denied'}) );
36     return view_with_auth
37
38 #
39 # View all files
40 #
41 @with_repo
42 def file_list(request, repo):
43     latest_default = repo.repo.branchtags()['default']
44     files = list( repo.repo[latest_default] )
45     bookform = forms.BookUploadForm()
46
47     return direct_to_template(request, 'explorer/file_list.html', extra_context={
48         'files': files, 'bookform': bookform,
49     })
50
51 @permission_required('explorer.can_add_files')
52 @with_repo
53 def file_upload(request, repo):
54     other_errors = []
55     if request.method == 'POST':
56         form = forms.BookUploadForm(request.POST, request.FILES)
57         if form.is_valid():
58             try:
59                 # prepare the data
60                 f = request.FILES['file']
61                 decoded = f.read().decode('utf-8')
62
63                 def upload_action():
64                     print 'Adding file: %s' % f.name
65                     repo._add_file(f.name, decoded.encode('utf-8') )
66                     repo._commit(
67                         message="File %s uploaded from platform by %s" %\
68                             (f.name, request.user.username), \
69                         user=request.user.username \
70                     )
71                     
72                     # end of upload
73
74                 repo.in_branch(upload_action, 'default')
75
76                 # if everything is ok, redirect to the editor
77                 return HttpResponseRedirect( reverse('editor_view',
78                         kwargs={'path': f.name}) )
79
80             except hg.RepositoryException, e:
81                 other_errors.append(u'Błąd repozytorium: ' + unicode(e) )
82             except UnicodeDecodeError, e:
83                 other_errors.append(u'Niepoprawne kodowanie pliku: ' + e.reason \
84                  + u'. Żądane kodowanie: ' + e.encoding)
85         # invalid form
86
87     # get
88     form = forms.BookUploadForm()
89     return direct_to_template(request, 'explorer/file_upload.html',
90         extra_context = {'form' : form, 'other_errors': other_errors})
91    
92 #
93 # Edit the file
94 #
95
96 @ajax_login_required
97 @with_repo
98 def file_xml(request, repo, path):
99     if request.method == 'POST':
100         errors = None
101         warnings = None
102         form = forms.BookForm(request.POST)
103         if form.is_valid():
104             print 'Saving whole text.', request.user.username
105             try:
106                 # encode it back to UTF-8, so we can put it into repo
107                 encoded_data = form.cleaned_data['content'].encode('utf-8')
108
109                 def save_action():                    
110                     repo._add_file(path, encoded_data)
111                     repo._commit(message=(form.cleaned_data['commit_message'] or 'Lokalny zapis platformy.'),\
112                          user=request.user.username)
113
114                 try:
115                     # wczytaj dokument z ciągu znaków -> weryfikacja
116                     document = parser.WLDocument.from_string(form.cleaned_data['content'])
117                 except (ParseError, ValidationError), e:
118                     warnings = [u'Niepoprawny dokument XML: ' + unicode(e.message)]
119
120                 #  save to user's branch
121                 repo.in_branch(save_action, models.user_branch(request.user) );
122             except UnicodeDecodeError, e:
123                 errors = [u'Błąd kodowania danych przed zapisem: ' + unicode(e.message)]
124             except RepositoryException, e:
125                 errors = [u'Błąd repozytorium: ' + unicode(e.message)]            
126
127         if not errors:
128             errors = dict( (field[0], field[1].as_text()) for field in form.errors.iteritems() )
129
130         return HttpResponse( json.dumps({'result': errors and 'error' or 'ok',
131             'errors': errors, 'warnings': warnings}) );
132
133     form = forms.BookForm()
134     data = repo.get_file(path, models.user_branch(request.user))
135     form.fields['content'].initial = data
136     return HttpResponse( json.dumps({'result': 'ok', 'content': data}) ) 
137
138 @ajax_login_required
139 @with_repo
140 def file_dc(request, path, repo):
141     errors = None
142
143     if request.method == 'POST':
144         form = forms.DublinCoreForm(request.POST)
145         
146         if form.is_valid():
147             def save_action():
148                 file_contents = repo._get_file(path)
149
150                 # wczytaj dokument z repozytorium
151                 document = parser.WLDocument.from_string(file_contents)                    
152                 document.book_info.update(form.cleaned_data)
153                 
154                 print "SAVING DC"
155
156                 # zapisz
157                 repo._write_file(path, document.serialize())
158                 repo._commit( \
159                     message=(form.cleaned_data['commit_message'] or 'Lokalny zapis platformy.'), \
160                     user=request.user.username )
161                 
162             try:
163                 repo.in_branch(save_action, models.user_branch(request.user) )
164             except (ParseError, ValidationError), e:
165                 errors = [e.message]
166
167         if errors is None:
168             errors = ["Pole '%s': %s\n" % (field[0], field[1].as_text()) for field in form.errors.iteritems()]
169
170         return HttpResponse( json.dumps({'result': errors and 'error' or 'ok', 'errors': errors}) );
171     
172     # this is unused currently, but may come in handy 
173     content = []
174     
175     try:
176         fulltext = repo.get_file(path, models.user_branch(request.user))
177         bookinfo = dcparser.BookInfo.from_string(fulltext)
178         content = bookinfo.to_dict()
179     except (ParseError, ValidationError), e:
180         errors = [e.message]
181
182     return HttpResponse( json.dumps({'result': errors and 'error' or 'ok', 
183         'errors': errors, 'content': content }) ) 
184
185 # Display the main editor view
186
187 @login_required
188 @with_repo
189 def display_editor(request, path, repo):
190     
191     if not repo.file_exists(path, models.user_branch(request.user)):
192         try:
193             data = repo.get_file(path, 'default')
194             print type(data)
195
196             def new_file():
197                 repo._add_file(path, data)
198                 repo._commit(message='File import from default branch',
199                     user=request.user.username)
200                 
201             repo.in_branch(new_file, models.user_branch(request.user) )
202         except hg.RepositoryException, e:
203             return direct_to_template(request, 'explorer/file_unavailble.html',\
204                 extra_context = { 'path': path, 'error': e })
205
206     return direct_to_template(request, 'explorer/editor.html', extra_context={
207         'hash': path,
208         'panel_list': ['lewy', 'prawy'],
209         'scriptlets': toolbar_models.Scriptlet.objects.all()
210     })
211
212 # ===============
213 # = Panel views =
214 # ===============
215
216 @ajax_login_required
217 @with_repo
218 def xmleditor_panel(request, path, repo):
219     text = repo.get_file(path, models.user_branch(request.user))
220     
221     return direct_to_template(request, 'explorer/panels/xmleditor.html', extra_context={
222         'fpath': path,
223         'text': text,
224     })
225     
226
227 @ajax_login_required
228 def gallery_panel(request, path):
229     return direct_to_template(request, 'explorer/panels/gallery.html', extra_context={
230         'fpath': path,
231         'form': forms.ImageFoldersForm(),
232     })
233
234 @ajax_login_required
235 @with_repo
236 def htmleditor_panel(request, path, repo):
237     user_branch = models.user_branch(request.user)
238     try:
239         return direct_to_template(request, 'explorer/panels/htmleditor.html', extra_context={
240             'fpath': path,
241             'html': html.transform(repo.get_file(path, user_branch), is_file=False),
242         })
243     except (ParseError, ValidationError), e:
244         return direct_to_template(request, 'explorer/panels/parse_error.html', extra_context={
245             'fpath': path, 'exception_type': type(e).__name__, 'exception': e, 'panel_name': 'Edytor HTML'}) 
246
247 @ajax_login_required
248 @with_repo
249 def dceditor_panel(request, path, repo):
250     user_branch = models.user_branch(request.user)
251
252     try:
253         doc_text = repo.get_file(path, user_branch)
254         document = parser.WLDocument.from_string(doc_text)
255         form = forms.DublinCoreForm(info=document.book_info)       
256         return direct_to_template(request, 'explorer/panels/dceditor.html', extra_context={
257             'fpath': path,
258             'form': form,
259         })
260     except (ParseError, ValidationError), e:
261         return direct_to_template(request, 'explorer/panels/parse_error.html', extra_context={
262             'fpath': path, 'exception_type': type(e).__name__, 'exception': e, 
263             'panel_name': 'Edytor DublinCore'}) 
264
265 # =================
266 # = Utility views =
267 # =================
268 @ajax_login_required
269 def folder_images(request, folder):
270     return direct_to_template(request, 'explorer/folder_images.html', extra_context={
271         'images': models.get_images_from_folder(folder),
272     })
273
274
275 def _add_references(message, issues):
276     return message + " - " + ", ".join(map(lambda issue: "Refs #%d" % issue['id'], issues))
277
278 def _get_issues_for_file(path):
279     if not path.endswith('.xml'):
280         raise ValueError('Path must end with .xml')
281
282     book_id = path[:-4]
283     uf = None
284
285     try:
286         uf = urllib2.urlopen(settings.REDMINE_URL + 'publications/issues/%s.json' % book_id)
287         return json.loads(uf.read())
288     except urllib2.HTTPError:
289         return []
290     finally:
291         if uf: uf.close()
292
293
294 # =================
295 # = Pull requests =
296 # =================
297 def pull_requests(request):
298     return direct_to_template(request, 'manager/pull_request.html', extra_context = {
299         'objects': models.PullRequest.objects.all()} )