1 # -*- coding: utf-8 -*-
4 from datetime import date
8 from librarian import html, parser, dcparser
9 from librarian import ParseError, ValidationError
11 from django.conf import settings
12 from django.contrib.auth.decorators import login_required, permission_required
14 from django.core.urlresolvers import reverse
15 from django.http import HttpResponseRedirect, HttpResponse, HttpResponseNotFound
16 from django.utils import simplejson as json
17 from django.views.generic.simple import direct_to_template
18 from django.contrib.auth.decorators import login_required
20 from explorer import forms, models
21 from toolbar import models as toolbar_models
23 from django.forms.util import ErrorList
26 # Some useful decorators
28 def file_branch(fileid, user=None):
29 parts = fileid.split('$')
30 return ('personal_'+ user.username + '_' if user is not None else '') \
33 def file_path(fileid):
34 return 'pub_'+fileid+'.xml'
37 """Open a repository for this view"""
38 def view_with_repo(request, *args, **kwargs):
39 kwargs['repo'] = hg.Repository(settings.REPOSITORY_PATH)
40 return view(request, *args, **kwargs)
44 def ajax_login_required(view):
45 """Similar ro @login_required, but instead of redirect,
46 just return some JSON stuff with error."""
47 def view_with_auth(request, *args, **kwargs):
48 if request.user.is_authenticated():
49 return view(request, *args, **kwargs)
51 return HttpResponse( json.dumps({'result': 'access_denied', 'errors': ['Brak dostępu.']}) );
58 def file_list(request, repo):
60 latest_default = repo.get_branch_tip('default')
63 for file in repo.repo[latest_default]:
64 m = re.match(u'^pub_([^/]+).xml$', file.decode('utf-8'), re.UNICODE)
68 bookform = forms.BookUploadForm()
70 return direct_to_template(request, 'explorer/file_list.html', extra_context={
71 'files': fl, 'bookform': bookform,
74 @permission_required('explorer.can_add_files')
76 def file_upload(request, repo):
78 if request.method == 'POST':
79 form = forms.BookUploadForm(request.POST, request.FILES)
83 f = request.FILES['file']
84 decoded = f.read().decode('utf-8')
85 fileid = form.cleaned_data['bookname'].lower()
86 rpath = file_path(fileid)
88 if form.cleaned_data['autoxml']:
89 decoded = librarian.wrap_text(decoded, unicode(date.today()) )
92 repo._add_file(rpath, decoded.encode('utf-8') )
93 repo._commit(message="File %s uploaded by user %s" % \
94 (rpath, request.user.username), user=request.user.username)
96 repo.in_branch(upload_action, 'default')
98 # if everything is ok, redirect to the editor
99 return HttpResponseRedirect( reverse('editor_view',
100 kwargs={'path': fileid}) )
102 except hg.RepositoryException, e:
103 other_errors.append(u'Błąd repozytorium: ' + unicode(e) )
104 #except UnicodeDecodeError, e:
105 # other_errors.append(u'Niepoprawne kodowanie pliku: ' + e.reason \
106 # + u'. Żądane kodowanie: ' + e.encoding)
110 form = forms.BookUploadForm()
111 return direct_to_template(request, 'explorer/file_upload.html',\
112 extra_context = {'form' : form, 'other_errors': other_errors})
120 def file_xml(request, repo, path):
121 rpath = file_path(path)
122 if request.method == 'POST':
125 form = forms.BookForm(request.POST)
127 print 'Saving whole text.', request.user.username
129 # encode it back to UTF-8, so we can put it into repo
130 encoded_data = form.cleaned_data['content'].encode('utf-8')
133 repo._add_file(rpath, encoded_data)
134 repo._commit(message=(form.cleaned_data['commit_message'] or 'Lokalny zapis platformy.'),\
135 user=request.user.username)
138 # wczytaj dokument z ciągu znaków -> weryfikacja
139 document = parser.WLDocument.from_string(form.cleaned_data['content'])
140 except (ParseError, ValidationError), e:
141 warnings = [u'Niepoprawny dokument XML: ' + unicode(e.message)]
143 # save to user's branch
144 repo.in_branch(save_action, file_branch(path, request.user) );
145 except UnicodeDecodeError, e:
146 errors = [u'Błąd kodowania danych przed zapisem: ' + unicode(e.message)]
147 except hg.RepositoryException, e:
148 errors = [u'Błąd repozytorium: ' + unicode(e.message)]
151 errors = dict( (field[0], field[1].as_text()) for field in form.errors.iteritems() )
153 return HttpResponse( json.dumps({'result': errors and 'error' or 'ok',
154 'errors': errors, 'warnings': warnings}) );
156 form = forms.BookForm()
157 data = repo.get_file(rpath, file_branch(path, request.user))
158 form.fields['content'].initial = data
159 return HttpResponse( json.dumps({'result': 'ok', 'content': data}) )
163 def file_update_local(request, path, repo):
167 wlock = repo.write_lock()
169 tipA = repo.get_branch_tip('default')
170 tipB = repo.get_branch_tip( file_branch(path, request.user) )
172 nodeA = repo.getnode(tipA)
173 nodeB = repo.getnode(tipB)
175 # do some wild checks - see file_commit() for more info
176 if (repo.common_ancestor(tipA, tipB) == nodeA) \
177 or (nodeB in nodeA.parents()):
178 result = 'nothing-to-do'
181 repo.merge_revisions(tipB, tipA, \
182 request.user.username, 'Personal branch update.')
184 except hg.UncleanMerge, e:
186 result = 'fatal-error'
187 except hg.RepositoryException, e:
189 result = 'fatal-error'
194 raise Exception("Ouch, this shouldn't happen!")
196 return HttpResponse( json.dumps({'result': result, 'errors': errors}) );
200 def file_commit(request, path, repo):
203 local_modified = False
204 if request.method == 'POST':
205 form = forms.MergeForm(request.POST)
208 wlock = repo.write_lock()
210 tipA = repo.get_branch_tip('default')
211 tipB = repo.get_branch_tip( file_branch(path, request.user) )
213 nodeA = repo.getnode(tipA)
214 nodeB = repo.getnode(tipB)
216 print repr(nodeA), repr(nodeB), repo.common_ancestor(tipA, tipB), repo.common_ancestor(tipB, tipA)
218 if repo.common_ancestor(tipB, tipA) == nodeA:
222 # * <- can also be here!
227 # The local branch has been recently updated,
228 # so we don't need to update yet again, but we need to
229 # merge down to default branch, even if there was
230 # no commit's since last update
231 repo.merge_revisions(tipA, tipB, \
232 request.user.username, form.cleaned_data['message'])
234 elif any( p.branch()==nodeB.branch() for p in nodeA.parents()):
242 # Default has no changes, to update from this branch
243 # since the last merge of local to default.
244 if nodeB not in nodeA.parents():
245 repo.merge_revisions(tipA, tipB, \
246 request.user.username, form.cleaned_data['message'])
249 result = 'nothing-to-do'
250 elif repo.common_ancestor(tipA, tipB) == nodeB:
254 # * <- this case overlaps with previos one
260 # There was a recent merge to the defaul branch and
261 # no changes to local branch recently.
263 # Use the fact, that user is prepared to see changes, to
264 # update his branch if there are any
265 if nodeB not in nodeA.parents():
266 repo.merge_revisions(tipB, tipA, \
267 request.user.username, 'Personal branch update during merge.')
268 local_modified = True
271 result = 'nothing-to-do'
273 # both branches have changes made to them, so
275 repo.merge_revisions(tipB, tipA, \
276 request.user.username, 'Personal branch update during merge.')
278 local_modified = True
281 tipB = repo.get_branch_tip( file_branch(path, request.user) )
283 # and merge back to the default
284 repo.merge_revisions(tipA, tipB, \
285 request.user.username, form.cleaned_data['message'])
287 except hg.UncleanMerge, e:
289 result = 'fatal-error'
290 except hg.RepositoryException, e:
292 result = 'fatal-error'
297 errors = [ form.errors['message'].as_text() ]
299 result = 'fatal-error'
301 return HttpResponse( json.dumps({'result': result, 'errors': errors, 'localmodified': local_modified}) );
303 return HttpResponse( json.dumps({'result': 'fatal-error', 'errors': ['No data posted']}) )
308 def file_dc(request, path, repo):
310 rpath = file_path(path)
312 if request.method == 'POST':
313 form = forms.DublinCoreForm(request.POST)
318 file_contents = repo._get_file(rpath)
320 # wczytaj dokument z repozytorium
321 document = parser.WLDocument.from_string(file_contents)
322 document.book_info.update(form.cleaned_data)
325 repo._write_file(rpath, document.serialize().encode('utf-8'))
327 message=(form.cleaned_data['commit_message'] or 'Lokalny zapis platformy.'), \
328 user=request.user.username )
331 repo.in_branch(save_action, file_branch(path, request.user) )
332 except UnicodeEncodeError, e:
333 errors = ['Bład wewnętrzny: nie można zakodować pliku do utf-8']
334 except (ParseError, ValidationError), e:
338 errors = ["Pole '%s': %s\n" % (field[0], field[1].as_text()) for field in form.errors.iteritems()]
340 return HttpResponse( json.dumps({'result': errors and 'error' or 'ok', 'errors': errors}) );
342 # this is unused currently, but may come in handy
346 fulltext = repo.get_file(rpath, file_branch(path, request.user))
347 bookinfo = dcparser.BookInfo.from_string(fulltext)
348 content = bookinfo.to_dict()
349 except (ParseError, ValidationError), e:
352 return HttpResponse( json.dumps({'result': errors and 'error' or 'ok',
353 'errors': errors, 'content': content }) )
355 # Display the main editor view
359 def display_editor(request, path, repo):
361 # this is the only entry point where we create an autobranch for the user
362 # if it doesn't exists. All other views SHOULD fail.
363 def ensure_branch_exists():
364 parent = repo.get_branch_tip('default')
365 repo._create_branch(file_branch(path, request.user), parent)
368 repo.with_wlock(ensure_branch_exists)
370 return direct_to_template(request, 'explorer/editor.html', extra_context={
372 'panel_list': ['lewy', 'prawy'],
373 'availble_panels': models.EditorPanel.objects.all(),
374 'scriptlets': toolbar_models.Scriptlet.objects.all()
377 return direct_to_template(request, 'explorer/nofile.html', \
378 extra_context = { 'fileid': path })
383 class panel_view(object):
385 def __new__(cls, request, name, path, **kwargs):
387 panel = models.EditorPanel.objects.get(id=name)
388 method = getattr(cls, name + '_panel', None)
389 if not panel or method is None:
390 raise HttpResponseNotFound
392 extra_context = method(request, path, panel, **kwargs)
394 if not isinstance(extra_context, dict):
397 extra_context.update({
398 'toolbar_groups': panel.toolbar_groups.all(),
399 'toolbar_extra_group': panel.toolbar_extra,
403 return direct_to_template(request, 'explorer/panels/'+name+'.html',\
404 extra_context=extra_context)
409 def xmleditor_panel(request, path, panel, repo):
410 rpath = file_path(path)
411 return {'text': repo.get_file(rpath, file_branch(path, request.user))}
415 def gallery_panel(request, path, panel):
416 return {'form': forms.ImageFoldersForm() }
421 def htmleditor_panel(request, path, panel, repo):
422 rpath = file_path(path)
423 user_branch = file_branch(path, request.user)
425 result = html.transform(repo.get_file(rpath, user_branch), is_file=False)
426 print "HTML: %r" % result
427 return {'html': result}
428 except (ParseError, ValidationError), e:
429 return direct_to_template(request, 'explorer/panels/parse_error.html', extra_context={
430 'fileid': path, 'exception_type': type(e).__name__, 'exception': e,
431 'panel_name': panel.display_name})
436 def dceditor_panel(request, path, panel, repo):
437 user_branch = file_branch(path, request.user)
438 rpath = file_path(path)
440 doc_text = repo.get_file(rpath, user_branch)
441 document = parser.WLDocument.from_string(doc_text)
442 form = forms.DublinCoreForm(info=document.book_info)
443 return {'form': form}
444 except (ParseError, ValidationError), e:
445 return direct_to_template(request, 'explorer/panels/parse_error.html', extra_context={
446 'fileid': path, 'exception_type': type(e).__name__, 'exception': e,
447 'panel_name': panel.display_name})
450 ## Editor "commands" and "dialogs"
454 def print_html(request, path, repo):
455 user_branch = file_branch(path, request.user)
456 rpath = file_path(path)
458 html.transform(repo.get_file(rpath, user_branch), is_file=False),
459 mimetype="text/html")
463 def print_xml(request, path, repo):
464 user_branch = file_branch(path, request.user)
465 rpath = file_path(path)
466 return HttpResponse( repo.get_file(rpath, user_branch), mimetype="text/plain; charset=utf-8")
468 @permission_required('explorer.can_add_files')
469 def split_text(request, path):
470 rpath = file_path(path)
472 if request.method == "POST":
473 sform = forms.SplitForm(request.POST, prefix='splitform')
474 dcform = forms.DublinCoreForm(request.POST, prefix='dcform')
476 print "validating sform"
479 # if sform.cleaned_data['autoxml']:
480 # print "validating dcform"
481 # valid = dcform.is_valid()
483 print "valid is ", valid
486 uri = path + '$' + sform.cleaned_data['partname']
487 child_rpath = file_path(uri)
488 repo = hg.Repository(settings.REPOSITORY_PATH)
490 # save the text into parent's branch
492 if repo._file_exists(child_rpath):
493 el = sform._errors.get('partname', ErrorList())
494 el.append("Part with this name already exists")
495 sform._errors['partname'] = el
498 fulltext = sform.cleaned_data['fulltext']
499 fulltext = fulltext.replace(u'<include-tag-placeholder />',
500 librarian.xinclude_forURI(u'wlrepo://'+uri) )
502 repo._write_file(rpath, fulltext.encode('utf-8'))
504 newtext = sform.cleaned_data['splittext']
505 if sform.cleaned_data['autoxml']:
506 # this is a horrible hack - really
507 bi = dcparser.BookInfo.from_element(librarian.DEFAULT_BOOKINFO.to_etree())
508 bi.update(dcform.data)
510 newtext = librarian.wrap_text(newtext, \
511 unicode(date.today()), bookinfo=bi )
513 repo._add_file(child_rpath, newtext.encode('utf-8'))
514 repo._commit(message="Split from '%s' to '%s'" % (path, uri), \
515 user=request.user.username )
518 if repo.in_branch(split_action, file_branch(path, request.user)):
519 # redirect to success
521 uri = urllib.quote( unicode(uri).encode('utf-8'))
522 return HttpResponseRedirect( reverse('split-success',\
523 kwargs={'path': path})+'?child='+uri )
525 try: # to read the current DC
526 repo = hg.Repository(settings.REPOSITORY_PATH)
527 fulltext = repo.get_file(rpath, file_branch(path, request.user))
528 bookinfo = dcparser.BookInfo.from_string(fulltext)
529 except (ParseError, ValidationError):
530 bookinfo = librarian.DEFAULT_BOOKINFO
532 sform = forms.SplitForm(prefix='splitform')
533 dcform = forms.DublinCoreForm(prefix='dcform', info=bookinfo)
535 return direct_to_template(request, 'explorer/split.html', extra_context={
536 'splitform': sform, 'dcform': dcform, 'fileid': path} )
538 def split_success(request, path):
539 return direct_to_template(request, 'explorer/split_success.html',\
540 extra_context={'fileid': path, 'cfileid': request.GET['child']} )
547 def folder_images(request, folder):
548 return direct_to_template(request, 'explorer/folder_images.html', extra_context={
549 'images': models.get_images_from_folder(folder),
552 def _add_references(message, issues):
553 return message + " - " + ", ".join(map(lambda issue: "Refs #%d" % issue['id'], issues))
555 def _get_issues_for_file(fileid):
558 uf = urllib2.urlopen(settings.REDMINE_URL + 'publications/issues/%s.json' % fileid)
559 return json.loads(uf.read())
560 except urllib2.HTTPError:
568 #def pull_requests(request):
569 # return direct_to_template(request, 'manager/pull_request.html', extra_context = {
570 # 'objects': models.PullRequest.objects.all()} )