Naprawiony formularz DC. Closes #12.
[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 from django.core.paginator import Paginator, InvalidPage, EmptyPage
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     paginator = Paginator( repo.file_list('default'), 100);
44     bookform = forms.BookUploadForm()
45
46     try:
47         page = int(request.GET.get('page', '1'))
48     except ValueError:
49         page = 1
50
51     try:
52         files = paginator.page(page)
53     except (EmptyPage, InvalidPage):
54         files = paginator.page(paginator.num_pages)
55
56     return direct_to_template(request, 'explorer/file_list.html', extra_context={
57         'files': files, 'page': page, 'bookform': bookform,
58     })
59
60 @permission_required('explorer.can_add_files')
61 @with_repo
62 def file_upload(request, repo):
63     other_errors = []
64     if request.method == 'POST':
65         form = forms.BookUploadForm(request.POST, request.FILES)
66         if form.is_valid():
67             try:
68                 # prepare the data
69                 f = request.FILES['file']
70                 decoded = f.read().decode('utf-8')
71
72                 def upload_action():
73                     print 'Adding file: %s' % f.name
74                     repo._add_file(f.name, f.read().decode('utf-8'))
75                     repo._commit(
76                         message="File %s uploaded from platform by %s" %\
77                             (f.name, request.user.username), \
78                         user=request.user.username \
79                     )
80                     
81                     # end of upload
82
83                 repo.in_branch(upload_action, 'default')
84
85                 # if everything is ok, redirect to the editor
86                 return HttpResponseRedirect( reverse('editor_view',
87                         kwargs={'path': f.name}) )
88
89             except hg.RepositoryException, e:
90                 other_errors.append(u'Błąd repozytorium: ' + unicode(e) )
91             except UnicodeDecodeError, e:
92                 other_errors.append(u'Niepoprawne kodowanie pliku: ' + e.reason \
93                  + u'. Żądane kodowanie: ' + e.encoding)
94         # invalid form
95
96     # get
97     form = forms.BookUploadForm()
98     return direct_to_template(request, 'explorer/file_upload.html',
99         extra_context = {'form' : form, 'other_errors': other_errors})
100    
101 #
102 # Edit the file
103 #
104
105 @ajax_login_required
106 @with_repo
107 def file_xml(request, repo, path):
108     if request.method == 'POST':
109         errors = None
110         form = forms.BookForm(request.POST)
111         if form.is_valid():
112             print 'Saving whole text.', request.user.username
113             def save_action():
114                 print 'In branch: ' + repo.repo[None].branch()
115                 repo._add_file(path, form.cleaned_data['content'])                
116                 repo._commit(message=(form.cleaned_data['commit_message'] or 'Lokalny zapis platformy.'),\
117                      user=request.user.username)
118             try:
119                 # wczytaj dokument z ciągu znaków -> weryfikacja
120                 document = parser.WLDocument.from_string(form.cleaned_data['content'])
121
122                 #  save to user's branch
123                 repo.in_branch(save_action, models.user_branch(request.user) );
124             except (ParseError, ValidationError), e:
125                 errors = [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', 'errors': errors}));
131
132     form = forms.BookForm()
133     data = repo.get_file(path, models.user_branch(request.user))
134     form.fields['content'].initial = data
135     return HttpResponse( json.dumps({'result': 'ok', 'content': data}) ) 
136
137 @ajax_login_required
138 @with_repo
139 def file_dc(request, path, repo):
140     errors = None
141
142     if request.method == 'POST':
143         form = forms.DublinCoreForm(request.POST)
144         
145         if form.is_valid():
146             def save_action():
147                 file_contents = repo._get_file(path)
148
149                 # wczytaj dokument z repozytorium
150                 document = parser.WLDocument.from_string(file_contents)                    
151                 document.book_info.update(form.cleaned_data)
152                 
153                 print "SAVING DC"
154
155                 # zapisz
156                 repo._add_file(path, document.serialize())
157                 repo._commit( \
158                     message=(form.cleaned_data['commit_message'] or 'Lokalny zapis platformy.'), \
159                     user=request.user.username )
160                 
161             try:
162                 repo.in_branch(save_action, models.user_branch(request.user) )
163             except (ParseError, ValidationError), e:
164                 errors = [e.message]
165
166         if errors is None:
167             errors = ["Pole '%s': %s\n" % (field[0], field[1].as_text()) for field in form.errors.iteritems()]
168
169         return HttpResponse( json.dumps({'result': errors and 'error' or 'ok', 'errors': errors}) );
170     
171     # this is unused currently, but may come in handy 
172     content = []
173     
174     try:
175         fulltext = repo.get_file(path, models.user_branch(request.user))
176         bookinfo = dcparser.BookInfo.from_string(fulltext)
177         content = bookinfo.to_dict()
178     except (ParseError, ValidationError), e:
179         errors = [e.message]
180
181     return HttpResponse( json.dumps({'result': errors and 'error' or 'ok', 
182         'errors': errors, 'content': content }) ) 
183
184 # Display the main editor view
185
186 @login_required
187 def display_editor(request, path):
188     return direct_to_template(request, 'explorer/editor.html', extra_context={
189         'hash': path,
190         'panel_list': ['lewy', 'prawy'],
191         'scriptlets': toolbar_models.Scriptlet.objects.all()
192     })
193
194 # ===============
195 # = Panel views =
196 # ===============
197
198 @ajax_login_required
199 @with_repo
200 def xmleditor_panel(request, path, repo):
201     form = forms.BookForm()
202     text = repo.get_file(path, models.user_branch(request.user))
203     
204     return direct_to_template(request, 'explorer/panels/xmleditor.html', extra_context={
205         'fpath': path,
206         'text': text,
207     })
208     
209
210 @ajax_login_required
211 def gallery_panel(request, path):
212     return direct_to_template(request, 'explorer/panels/gallery.html', extra_context={
213         'fpath': path,
214         'form': forms.ImageFoldersForm(),
215     })
216
217 @ajax_login_required
218 @with_repo
219 def htmleditor_panel(request, path, repo):
220     user_branch = models.user_branch(request.user)
221     try:
222         return direct_to_template(request, 'explorer/panels/htmleditor.html', extra_context={
223             'fpath': path,
224             'html': html.transform(repo.get_file(path, user_branch), is_file=False),
225         })
226     except (ParseError, ValidationError), e:
227         return direct_to_template(request, 'explorer/panels/parse_error.html', extra_context={
228             'fpath': path, 'exception_type': type(e).__name__, 'exception': e, 'panel_name': 'Edytor HTML'}) 
229
230 @ajax_login_required
231 @with_repo
232 def dceditor_panel(request, path, repo):
233     user_branch = models.user_branch(request.user)
234
235     try:
236         doc_text = repo.get_file(path, user_branch)
237         document = parser.WLDocument.from_string(doc_text)
238         form = forms.DublinCoreForm(info=document.book_info)       
239         return direct_to_template(request, 'explorer/panels/dceditor.html', extra_context={
240             'fpath': path,
241             'form': form,
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, 
246             'panel_name': 'Edytor DublinCore'}) 
247
248 # =================
249 # = Utility views =
250 # =================
251 @ajax_login_required
252 def folder_images(request, folder):
253     return direct_to_template(request, 'explorer/folder_images.html', extra_context={
254         'images': models.get_images_from_folder(folder),
255     })
256
257
258 def _add_references(message, issues):
259     return message + " - " + ", ".join(map(lambda issue: "Refs #%d" % issue['id'], issues))
260
261 def _get_issues_for_file(path):
262     if not path.endswith('.xml'):
263         raise ValueError('Path must end with .xml')
264
265     book_id = path[:-4]
266     uf = None
267
268     try:
269         uf = urllib2.urlopen(settings.REDMINE_URL + 'publications/issues/%s.json' % book_id)
270         return json.loads(uf.read())
271     except urllib2.HTTPError:
272         return []
273     finally:
274         if uf: uf.close()
275
276
277 # =================
278 # = Pull requests =
279 # =================
280 def pull_requests(request):
281     return direct_to_template(request, 'manager/pull_request.html', extra_context = {
282         'objects': models.PullRequest.objects.all()} )