1 # -*- coding: utf-8 -*-
4 from librarian import html, parser, dcparser, ParseError, ValidationError
6 from django.conf import settings
7 from django.contrib.auth.decorators import login_required, permission_required
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
14 from explorer import forms, models
15 from toolbar import models as toolbar_models
18 # Some useful decorators
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)
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)
35 return HttpResponse( json.dumps({'result': 'access_denied'}) );
42 def file_list(request, repo):
43 latest_default = repo.repo.branchtags()['default']
44 files = list( repo.repo[latest_default] )
45 bookform = forms.BookUploadForm()
47 return direct_to_template(request, 'explorer/file_list.html', extra_context={
48 'files': files, 'bookform': bookform,
51 @permission_required('explorer.can_add_files')
53 def file_upload(request, repo):
55 if request.method == 'POST':
56 form = forms.BookUploadForm(request.POST, request.FILES)
60 f = request.FILES['file']
61 decoded = f.read().decode('utf-8')
64 print 'Adding file: %s' % f.name
65 repo._add_file(f.name, decoded.encode('utf-8') )
67 message="File %s uploaded from platform by %s" %\
68 (f.name, request.user.username), \
69 user=request.user.username \
74 repo.in_branch(upload_action, 'default')
76 # if everything is ok, redirect to the editor
77 return HttpResponseRedirect( reverse('editor_view',
78 kwargs={'path': f.name}) )
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)
88 form = forms.BookUploadForm()
89 return direct_to_template(request, 'explorer/file_upload.html',
90 extra_context = {'form' : form, 'other_errors': other_errors})
98 def file_xml(request, repo, path):
99 if request.method == 'POST':
101 form = forms.BookForm(request.POST)
103 print 'Saving whole text.', request.user.username
105 print 'In branch: ' + repo.repo[None].branch()
106 repo._add_file(path, form.cleaned_data['content'])
107 repo._commit(message=(form.cleaned_data['commit_message'] or 'Lokalny zapis platformy.'),\
108 user=request.user.username)
110 # wczytaj dokument z ciągu znaków -> weryfikacja
111 document = parser.WLDocument.from_string(form.cleaned_data['content'])
113 # save to user's branch
114 repo.in_branch(save_action, models.user_branch(request.user) );
115 except (ParseError, ValidationError), e:
119 errors = dict( (field[0], field[1].as_text()) for field in form.errors.iteritems() )
121 return HttpResponse(json.dumps({'result': errors and 'error' or 'ok', 'errors': errors}));
123 form = forms.BookForm()
124 data = repo.get_file(path, models.user_branch(request.user))
125 form.fields['content'].initial = data
126 return HttpResponse( json.dumps({'result': 'ok', 'content': data}) )
130 def file_dc(request, path, repo):
133 if request.method == 'POST':
134 form = forms.DublinCoreForm(request.POST)
138 file_contents = repo._get_file(path)
140 # wczytaj dokument z repozytorium
141 document = parser.WLDocument.from_string(file_contents)
142 document.book_info.update(form.cleaned_data)
147 repo._write_file(path, document.serialize())
149 message=(form.cleaned_data['commit_message'] or 'Lokalny zapis platformy.'), \
150 user=request.user.username )
153 repo.in_branch(save_action, models.user_branch(request.user) )
154 except (ParseError, ValidationError), e:
158 errors = ["Pole '%s': %s\n" % (field[0], field[1].as_text()) for field in form.errors.iteritems()]
160 return HttpResponse( json.dumps({'result': errors and 'error' or 'ok', 'errors': errors}) );
162 # this is unused currently, but may come in handy
166 fulltext = repo.get_file(path, models.user_branch(request.user))
167 bookinfo = dcparser.BookInfo.from_string(fulltext)
168 content = bookinfo.to_dict()
169 except (ParseError, ValidationError), e:
172 return HttpResponse( json.dumps({'result': errors and 'error' or 'ok',
173 'errors': errors, 'content': content }) )
175 # Display the main editor view
179 def display_editor(request, path, repo):
181 if not repo.file_exists(path, models.user_branch(request.user)):
183 data = repo.get_file(path, 'default')
187 repo._add_file(path, data)
188 repo._commit(message='File import from default branch',
189 user=request.user.username)
191 repo.in_branch(new_file, models.user_branch(request.user) )
192 except hg.RepositoryException, e:
193 return direct_to_template(request, 'explorer/file_unavailble.html',\
194 extra_context = { 'path': path, 'error': e })
196 return direct_to_template(request, 'explorer/editor.html', extra_context={
198 'panel_list': ['lewy', 'prawy'],
199 'scriptlets': toolbar_models.Scriptlet.objects.all()
208 def xmleditor_panel(request, path, repo):
209 text = repo.get_file(path, models.user_branch(request.user))
211 return direct_to_template(request, 'explorer/panels/xmleditor.html', extra_context={
218 def gallery_panel(request, path):
219 return direct_to_template(request, 'explorer/panels/gallery.html', extra_context={
221 'form': forms.ImageFoldersForm(),
226 def htmleditor_panel(request, path, repo):
227 user_branch = models.user_branch(request.user)
229 return direct_to_template(request, 'explorer/panels/htmleditor.html', extra_context={
231 'html': html.transform(repo.get_file(path, user_branch), is_file=False),
233 except (ParseError, ValidationError), e:
234 return direct_to_template(request, 'explorer/panels/parse_error.html', extra_context={
235 'fpath': path, 'exception_type': type(e).__name__, 'exception': e, 'panel_name': 'Edytor HTML'})
239 def dceditor_panel(request, path, repo):
240 user_branch = models.user_branch(request.user)
243 doc_text = repo.get_file(path, user_branch)
244 document = parser.WLDocument.from_string(doc_text)
245 form = forms.DublinCoreForm(info=document.book_info)
246 return direct_to_template(request, 'explorer/panels/dceditor.html', extra_context={
250 except (ParseError, ValidationError), e:
251 return direct_to_template(request, 'explorer/panels/parse_error.html', extra_context={
252 'fpath': path, 'exception_type': type(e).__name__, 'exception': e,
253 'panel_name': 'Edytor DublinCore'})
259 def folder_images(request, folder):
260 return direct_to_template(request, 'explorer/folder_images.html', extra_context={
261 'images': models.get_images_from_folder(folder),
265 def _add_references(message, issues):
266 return message + " - " + ", ".join(map(lambda issue: "Refs #%d" % issue['id'], issues))
268 def _get_issues_for_file(path):
269 if not path.endswith('.xml'):
270 raise ValueError('Path must end with .xml')
276 uf = urllib2.urlopen(settings.REDMINE_URL + 'publications/issues/%s.json' % book_id)
277 return json.loads(uf.read())
278 except urllib2.HTTPError:
287 def pull_requests(request):
288 return direct_to_template(request, 'manager/pull_request.html', extra_context = {
289 'objects': models.PullRequest.objects.all()} )