1 from librarian import html
2 import hg, urllib2, time
4 from django.utils import simplejson as json
6 from librarian import dcparser
8 from django.views.generic.simple import direct_to_template
10 from django.conf import settings
11 from django.http import HttpResponseRedirect, HttpResponse
13 from django.core.urlresolvers import reverse
14 from django.core.paginator import Paginator, InvalidPage, EmptyPage
16 from django.contrib.auth.decorators import login_required, permission_required
18 from explorer import forms, models
21 # Some useful decorators
24 """Open a repository for this view"""
25 def view_with_repo(request, *args, **kwargs):
26 kwargs['repo'] = hg.Repository(settings.REPOSITORY_PATH)
27 return view(request, *args, **kwargs)
31 def ajax_login_required(view):
32 """Similar ro @login_required, but instead of redirect,
33 just return some JSON stuff with error."""
34 def view_with_auth(request, *args, **kwargs):
35 if request.user.is_authenticated():
36 return view(request, *args, **kwargs)
38 return HttpResponse( json.dumps({'result': 'access_denied'}) );
45 def file_list(request, repo):
46 paginator = Paginator( repo.file_list('default'), 100);
47 bookform = forms.BookUploadForm()
50 page = int(request.GET.get('page', '1'))
55 files = paginator.page(page)
56 except (EmptyPage, InvalidPage):
57 files = paginator.page(paginator.num_pages)
59 return direct_to_template(request, 'explorer/file_list.html', extra_context={
60 'files': files, 'page': page, 'bookform': bookform,
63 @permission_required('explorer.can_add_files')
65 def file_upload(request, repo):
66 form = forms.BookUploadForm(request.POST, request.FILES)
68 f = request.FILES['file']
71 print 'Adding file: %s' % f.name
72 repo._add_file(f.name, f.read().decode('utf-8'))
73 repo._commit(message="File %s uploaded from platform by %s" %
74 (f.name, request.user.username), user=request.user.username)
76 repo.in_branch(upload_action, 'default')
77 return HttpResponseRedirect( reverse('editor_view', kwargs={'path': f.name}) )
79 return direct_to_template(request, 'explorer/file_upload.html',
80 extra_context = {'form' : form} )
88 def file_xml(request, repo, path):
89 if request.method == 'POST':
90 form = forms.BookForm(request.POST)
92 print 'Saving whole text.', request.user.username
94 print 'In branch: ' + repo.repo[None].branch()
95 repo._add_file(path, form.cleaned_data['content'])
96 repo._commit(message=(form.cleaned_data['commit_message'] or 'Lokalny zapis platformy.'), user=request.user.username)
98 print repo.in_branch(save_action, models.user_branch(request.user) );
103 errors = dict( (field[0], field[1].as_text()) for field in form.errors.iteritems() )
104 return HttpResponse( json.dumps({'result': result, 'errors': errors}) );
106 form = forms.BookForm()
107 data = repo.get_file(path, models.user_branch(request.user))
108 form.fields['content'].initial = data
109 return HttpResponse( json.dumps({'result': 'ok', 'content': data}) )
113 def file_dc(request, path, repo):
114 if request.method == 'POST':
115 form = forms.DublinCoreForm(request.POST)
119 file_contents = repo._get_file(path)
120 doc = etree.fromstring(file_contents)
122 book_info = dcparser.BookInfo()
123 for name, value in form.cleaned_data.items():
124 if value is not None and value != '':
125 setattr(book_info, name, value)
126 rdf = etree.XML(book_info.to_xml())
128 old_rdf = doc.getroottree().find('//{http://www.w3.org/1999/02/22-rdf-syntax-ns#}RDF')
129 old_rdf.getparent().remove(old_rdf)
131 repo._add_file(path, etree.tostring(doc, pretty_print=True, encoding=unicode))
132 repo._commit(message=(form.cleaned_data['commit_message'] or 'Lokalny zapis platformy.'), user=request.user.username)
134 repo.in_branch(save_action, models.user_branch(request.user) )
140 errors = dict( (field[0], field[1].as_text()) for field in form.errors.iteritems() )
141 return HttpResponse( json.dumps({'result': result, 'errors': errors}) );
143 fulltext = repo.get_file(path, models.user_branch(request.user))
144 form = forms.DublinCoreForm(text=fulltext)
145 return HttpResponse( json.dumps({'result': 'ok', 'content': fulltext}) )
147 # Display the main editor view
150 def display_editor(request, path):
151 return direct_to_template(request, 'explorer/editor.html', extra_context={
152 'hash': path, 'panel_list': ['lewy', 'prawy'],
161 def xmleditor_panel(request, path, repo):
162 form = forms.BookForm()
163 text = repo.get_file(path, models.user_branch(request.user))
165 return direct_to_template(request, 'explorer/panels/xmleditor.html', extra_context={
172 def gallery_panel(request, path):
173 return direct_to_template(request, 'explorer/panels/gallery.html', extra_context={
175 'form': forms.ImageFoldersForm(),
180 def htmleditor_panel(request, path, repo):
181 user_branch = models.user_branch(request.user)
182 return direct_to_template(request, 'explorer/panels/htmleditor.html', extra_context={
184 'html': html.transform(repo.get_file(path, user_branch), is_file=False),
190 def dceditor_panel(request, path, repo):
191 user_branch = models.user_branch(request.user)
192 text = repo.get_file(path, user_branch)
193 form = forms.DublinCoreForm(text=text)
195 return direct_to_template(request, 'explorer/panels/dceditor.html', extra_context={
205 def folder_images(request, folder):
206 return direct_to_template(request, 'explorer/folder_images.html', extra_context={
207 'images': models.get_images_from_folder(folder),
211 def _add_references(message, issues):
212 return message + " - " + ", ".join(map(lambda issue: "Refs #%d" % issue['id'], issues))
214 def _get_issues_for_file(path):
215 if not path.endswith('.xml'):
216 raise ValueError('Path must end with .xml')
222 uf = urllib2.urlopen(settings.REDMINE_URL + 'publications/issues/%s.json' % book_id)
223 return json.loads(uf.read())
224 except urllib2.HTTPError:
233 def pull_requests(request):
234 return direct_to_template(request, 'manager/pull_request.html', extra_context = {
235 'objects': models.PullRequest.objects.all()} )