3 from librarian import html, parser, dcparser, ParseError, ValidationError
5 from django.conf import settings
6 from django.contrib.auth.decorators import login_required, permission_required
7 from django.core.paginator import Paginator, InvalidPage, EmptyPage
8 from django.core.urlresolvers import reverse
9 from django.http import HttpResponseRedirect, HttpResponse
10 from django.utils import simplejson as json
11 from django.views.generic.simple import direct_to_template
13 from explorer import forms, models
17 # Some useful decorators
20 """Open a repository for this view"""
21 def view_with_repo(request, *args, **kwargs):
22 kwargs['repo'] = hg.Repository(settings.REPOSITORY_PATH)
23 return view(request, *args, **kwargs)
27 def ajax_login_required(view):
28 """Similar ro @login_required, but instead of redirect,
29 just return some JSON stuff with error."""
30 def view_with_auth(request, *args, **kwargs):
31 if request.user.is_authenticated():
32 return view(request, *args, **kwargs)
34 return HttpResponse( json.dumps({'result': 'access_denied'}) );
41 def file_list(request, repo):
42 paginator = Paginator( repo.file_list('default'), 100);
43 bookform = forms.BookUploadForm()
46 page = int(request.GET.get('page', '1'))
51 files = paginator.page(page)
52 except (EmptyPage, InvalidPage):
53 files = paginator.page(paginator.num_pages)
55 return direct_to_template(request, 'explorer/file_list.html', extra_context={
56 'files': files, 'page': page, 'bookform': bookform,
59 @permission_required('explorer.can_add_files')
61 def file_upload(request, repo):
62 form = forms.BookUploadForm(request.POST, request.FILES)
64 f = request.FILES['file']
67 print 'Adding file: %s' % f.name
68 repo._add_file(f.name, f.read().decode('utf-8'))
69 repo._commit(message="File %s uploaded from platform by %s" %
70 (f.name, request.user.username), user=request.user.username)
72 repo.in_branch(upload_action, 'default')
73 return HttpResponseRedirect( reverse('editor_view', kwargs={'path': f.name}) )
75 return direct_to_template(request, 'explorer/file_upload.html',
76 extra_context = {'form' : form} )
84 def file_xml(request, repo, path):
85 if request.method == 'POST':
87 form = forms.BookForm(request.POST)
89 print 'Saving whole text.', request.user.username
91 print 'In branch: ' + repo.repo[None].branch()
92 repo._add_file(path, form.cleaned_data['content'])
93 repo._commit(message=(form.cleaned_data['commit_message'] or 'Lokalny zapis platformy.'),\
94 user=request.user.username)
96 # wczytaj dokument z ciągu znaków -> weryfikacja
97 document = parser.WLDocument.from_string(form.cleaned_data['content'])
99 # save to user's branch
100 repo.in_branch(save_action, models.user_branch(request.user) );
101 except (ParseError, ValidationError), e:
105 errors = dict( (field[0], field[1].as_text()) for field in form.errors.iteritems() )
107 return HttpResponse(json.dumps({'result': errors and 'error' or 'ok', 'errors': errors}));
109 form = forms.BookForm()
110 data = repo.get_file(path, models.user_branch(request.user))
111 form.fields['content'].initial = data
112 return HttpResponse( json.dumps({'result': 'ok', 'content': data}) )
116 def file_dc(request, path, repo):
119 if request.method == 'POST':
120 form = forms.DublinCoreForm(request.POST)
124 file_contents = repo._get_file(path)
126 # wczytaj dokument z repozytorium
127 document = parser.WLDocument.from_string(file_contents)
128 document.book_info.update(form.cleaned_data)
133 repo._add_file(path, document.serialize())
135 message=(form.cleaned_data['commit_message'] or 'Lokalny zapis platformy.'), \
136 user=request.user.username )
139 repo.in_branch(save_action, models.user_branch(request.user) )
140 except (ParseError, ValidationError), e:
144 errors = ["Pole '%s': %s\n" % (field[0], field[1].as_text()) for field in form.errors.iteritems()]
146 return HttpResponse( json.dumps({'result': errors and 'error' or 'ok', 'errors': errors}) );
148 # this is unused currently, but may come in handy
152 fulltext = repo.get_file(path, models.user_branch(request.user))
153 bookinfo = dcparser.BookInfo.from_string(fulltext)
154 content = bookinfo.to_dict()
155 except (ParseError, ValidationError), e:
158 return HttpResponse( json.dumps({'result': errors and 'error' or 'ok',
159 'errors': errors, 'content': content }) )
161 # Display the main editor view
164 def display_editor(request, path):
165 return direct_to_template(request, 'explorer/editor.html', extra_context={
166 'hash': path, 'panel_list': ['lewy', 'prawy'],
175 def xmleditor_panel(request, path, repo):
176 form = forms.BookForm()
177 text = repo.get_file(path, models.user_branch(request.user))
179 return direct_to_template(request, 'explorer/panels/xmleditor.html', extra_context={
186 def gallery_panel(request, path):
187 return direct_to_template(request, 'explorer/panels/gallery.html', extra_context={
189 'form': forms.ImageFoldersForm(),
194 def htmleditor_panel(request, path, repo):
195 user_branch = models.user_branch(request.user)
197 return direct_to_template(request, 'explorer/panels/htmleditor.html', extra_context={
199 'html': html.transform(repo.get_file(path, user_branch), is_file=False),
201 except (ParseError, ValidationError), e:
202 return direct_to_template(request, 'explorer/panels/parse_error.html', extra_context={
203 'fpath': path, 'exception_type': type(e).__name__, 'exception': e, 'panel_name': 'Edytor HTML'})
207 def dceditor_panel(request, path, repo):
208 user_branch = models.user_branch(request.user)
211 doc_text = repo.get_file(path, user_branch)
213 document = parser.WLDocument.from_string(doc_text)
214 form = forms.DublinCoreForm(info=document.book_info)
216 return direct_to_template(request, 'explorer/panels/dceditor.html', extra_context={
220 except (ParseError, ValidationError), e:
221 return direct_to_template(request, 'explorer/panels/parse_error.html', extra_context={
222 'fpath': path, 'exception_type': type(e).__name__, 'exception': e,
223 'panel_name': 'Edytor DublinCore'})
229 def folder_images(request, folder):
230 return direct_to_template(request, 'explorer/folder_images.html', extra_context={
231 'images': models.get_images_from_folder(folder),
235 def _add_references(message, issues):
236 return message + " - " + ", ".join(map(lambda issue: "Refs #%d" % issue['id'], issues))
238 def _get_issues_for_file(path):
239 if not path.endswith('.xml'):
240 raise ValueError('Path must end with .xml')
246 uf = urllib2.urlopen(settings.REDMINE_URL + 'publications/issues/%s.json' % book_id)
247 return json.loads(uf.read())
248 except urllib2.HTTPError:
257 def pull_requests(request):
258 return direct_to_template(request, 'manager/pull_request.html', extra_context = {
259 'objects': models.PullRequest.objects.all()} )