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
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
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 paginator = Paginator( repo.file_list('default'), 100);
44 bookform = forms.BookUploadForm()
47 page = int(request.GET.get('page', '1'))
52 files = paginator.page(page)
53 except (EmptyPage, InvalidPage):
54 files = paginator.page(paginator.num_pages)
56 return direct_to_template(request, 'explorer/file_list.html', extra_context={
57 'files': files, 'page': page, 'bookform': bookform,
60 @permission_required('explorer.can_add_files')
62 def file_upload(request, repo):
63 form = forms.BookUploadForm(request.POST, request.FILES)
65 f = request.FILES['file']
68 print 'Adding file: %s' % f.name
69 repo._add_file(f.name, f.read().decode('utf-8'))
70 repo._commit(message="File %s uploaded from platform by %s" %
71 (f.name, request.user.username), user=request.user.username)
73 repo.in_branch(upload_action, 'default')
74 return HttpResponseRedirect( reverse('editor_view', kwargs={'path': f.name}) )
76 return direct_to_template(request, 'explorer/file_upload.html',
77 extra_context = {'form' : form} )
85 def file_xml(request, repo, path):
86 if request.method == 'POST':
88 form = forms.BookForm(request.POST)
90 print 'Saving whole text.', request.user.username
92 print 'In branch: ' + repo.repo[None].branch()
93 repo._add_file(path, form.cleaned_data['content'])
94 repo._commit(message=(form.cleaned_data['commit_message'] or 'Lokalny zapis platformy.'),\
95 user=request.user.username)
97 # wczytaj dokument z ciągu znaków -> weryfikacja
98 document = parser.WLDocument.from_string(form.cleaned_data['content'])
100 # save to user's branch
101 repo.in_branch(save_action, models.user_branch(request.user) );
102 except (ParseError, ValidationError), e:
106 errors = dict( (field[0], field[1].as_text()) for field in form.errors.iteritems() )
108 return HttpResponse(json.dumps({'result': errors and 'error' or 'ok', 'errors': errors}));
110 form = forms.BookForm()
111 data = repo.get_file(path, models.user_branch(request.user))
112 form.fields['content'].initial = data
113 return HttpResponse( json.dumps({'result': 'ok', 'content': data}) )
117 def file_dc(request, path, repo):
120 if request.method == 'POST':
121 form = forms.DublinCoreForm(request.POST)
125 file_contents = repo._get_file(path)
127 # wczytaj dokument z repozytorium
128 document = parser.WLDocument.from_string(file_contents)
129 document.book_info.update(form.cleaned_data)
134 repo._add_file(path, document.serialize())
136 message=(form.cleaned_data['commit_message'] or 'Lokalny zapis platformy.'), \
137 user=request.user.username )
140 repo.in_branch(save_action, models.user_branch(request.user) )
141 except (ParseError, ValidationError), e:
145 errors = ["Pole '%s': %s\n" % (field[0], field[1].as_text()) for field in form.errors.iteritems()]
147 return HttpResponse( json.dumps({'result': errors and 'error' or 'ok', 'errors': errors}) );
149 # this is unused currently, but may come in handy
153 fulltext = repo.get_file(path, models.user_branch(request.user))
154 bookinfo = dcparser.BookInfo.from_string(fulltext)
155 content = bookinfo.to_dict()
156 except (ParseError, ValidationError), e:
159 return HttpResponse( json.dumps({'result': errors and 'error' or 'ok',
160 'errors': errors, 'content': content }) )
162 # Display the main editor view
165 def display_editor(request, path):
166 return direct_to_template(request, 'explorer/editor.html', extra_context={
168 'panel_list': ['lewy', 'prawy'],
169 'scriptlets': toolbar_models.Scriptlet.objects.all()
178 def xmleditor_panel(request, path, repo):
179 form = forms.BookForm()
180 text = repo.get_file(path, models.user_branch(request.user))
182 return direct_to_template(request, 'explorer/panels/xmleditor.html', extra_context={
189 def gallery_panel(request, path):
190 return direct_to_template(request, 'explorer/panels/gallery.html', extra_context={
192 'form': forms.ImageFoldersForm(),
197 def htmleditor_panel(request, path, repo):
198 user_branch = models.user_branch(request.user)
200 return direct_to_template(request, 'explorer/panels/htmleditor.html', extra_context={
202 'html': html.transform(repo.get_file(path, user_branch), is_file=False),
204 except (ParseError, ValidationError), e:
205 return direct_to_template(request, 'explorer/panels/parse_error.html', extra_context={
206 'fpath': path, 'exception_type': type(e).__name__, 'exception': e, 'panel_name': 'Edytor HTML'})
210 def dceditor_panel(request, path, repo):
211 user_branch = models.user_branch(request.user)
214 doc_text = repo.get_file(path, user_branch)
215 document = parser.WLDocument.from_string(doc_text)
216 form = forms.DublinCoreForm(info=document.book_info)
217 return direct_to_template(request, 'explorer/panels/dceditor.html', extra_context={
221 except (ParseError, ValidationError), e:
222 return direct_to_template(request, 'explorer/panels/parse_error.html', extra_context={
223 'fpath': path, 'exception_type': type(e).__name__, 'exception': e,
224 'panel_name': 'Edytor DublinCore'})
230 def folder_images(request, folder):
231 return direct_to_template(request, 'explorer/folder_images.html', extra_context={
232 'images': models.get_images_from_folder(folder),
236 def _add_references(message, issues):
237 return message + " - " + ", ".join(map(lambda issue: "Refs #%d" % issue['id'], issues))
239 def _get_issues_for_file(path):
240 if not path.endswith('.xml'):
241 raise ValueError('Path must end with .xml')
247 uf = urllib2.urlopen(settings.REDMINE_URL + 'publications/issues/%s.json' % book_id)
248 return json.loads(uf.read())
249 except urllib2.HTTPError:
258 def pull_requests(request):
259 return direct_to_template(request, 'manager/pull_request.html', extra_context = {
260 'objects': models.PullRequest.objects.all()} )