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_([\\w\\$0-9_-]+).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(fileid)
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 return {'html': html.transform(repo.get_file(rpath, user_branch), is_file=False)}
426 except (ParseError, ValidationError), e:
427 return direct_to_template(request, 'explorer/panels/parse_error.html', extra_context={
428 'fileid': path, 'exception_type': type(e).__name__, 'exception': e,
429 'panel_name': panel.display_name})
434 def dceditor_panel(request, path, panel, repo):
435 user_branch = file_branch(path, request.user)
436 rpath = file_path(path)
438 doc_text = repo.get_file(rpath, user_branch)
439 document = parser.WLDocument.from_string(doc_text)
440 form = forms.DublinCoreForm(info=document.book_info)
441 return {'form': form}
442 except (ParseError, ValidationError), e:
443 return direct_to_template(request, 'explorer/panels/parse_error.html', extra_context={
444 'fileid': path, 'exception_type': type(e).__name__, 'exception': e,
445 'panel_name': panel.display_name})
448 ## Editor "commands" and "dialogs"
452 def print_html(request, path, repo):
453 user_branch = file_branch(path, request.user)
454 rpath = file_path(path)
456 html.transform(repo.get_file(rpath, user_branch), is_file=False),
457 mimetype="text/html")
461 def print_xml(request, path, repo):
462 user_branch = file_branch(path, request.user)
463 rpath = file_path(path)
464 return HttpResponse( repo.get_file(rpath, user_branch), mimetype="text/plain; charset=utf-8")
466 @permission_required('explorer.can_add_files')
467 def split_text(request, path):
468 rpath = file_path(path)
470 if request.method == "POST":
471 sform = forms.SplitForm(request.POST, prefix='splitform')
472 dcform = forms.DublinCoreForm(request.POST, prefix='dcform')
474 print "validating sform"
477 if sform.cleaned_data['autoxml']:
478 print "validating dcform"
479 valid = dcform.is_valid()
481 print "valid is ", valid
483 uri = path + '$' + sform.cleaned_data['partname']
484 child_rpath = file_path(uri)
485 repo = hg.Repository(settings.REPOSITORY_PATH)
487 # save the text into parent's branch
489 if repo._file_exists(child_rpath):
490 el = sform._errors.get('partname', ErrorList())
491 el.append("Part with this name already exists")
492 sform._errors['partname'] = el
495 fulltext = sform.cleaned_data['fulltext']
496 fulltext = fulltext.replace(u'<include-tag-placeholder />',
497 librarian.xinclude_forURI('wlrepo://'+uri) )
499 repo._write_file(rpath, fulltext.encode('utf-8'))
501 newtext = sform.cleaned_data['splittext']
502 if sform.cleaned_data['autoxml']:
503 # this is a horrible hack - really
504 bi = dcparser.BookInfo.from_element(librarian.DEFAULT_BOOKINFO.to_etree())
505 bi.update(dcform.cleaned_data)
507 newtext = librarian.wrap_text(newtext, \
508 unicode(date.today()), bookinfo=bi )
510 repo._add_file(child_rpath, newtext.encode('utf-8'))
511 repo._commit(message="Split from '%s' to '%s'" % (path, uri), \
512 user=request.user.username )
515 if repo.in_branch(split_action, file_branch(path, request.user)):
516 # redirect to success
517 return HttpResponseRedirect( reverse('split-success',\
518 kwargs={'path': path})+'?child='+uri)
520 try: # to read the current DC
521 repo = hg.Repository(settings.REPOSITORY_PATH)
522 fulltext = repo.get_file(rpath, file_branch(path, request.user))
523 bookinfo = dcparser.BookInfo.from_string(fulltext)
524 except (ParseError, ValidationError):
525 bookinfo = librarian.DEFAULT_BOOKINFO
527 sform = forms.SplitForm(prefix='splitform')
528 dcform = forms.DublinCoreForm(prefix='dcform', info=bookinfo)
530 return direct_to_template(request, 'explorer/split.html', extra_context={
531 'splitform': sform, 'dcform': dcform, 'fileid': path} )
533 def split_success(request, path):
534 return direct_to_template(request, 'explorer/split_success.html',\
535 extra_context={'fileid': path, 'cfileid': request.GET['child']} )
542 def folder_images(request, folder):
543 return direct_to_template(request, 'explorer/folder_images.html', extra_context={
544 'images': models.get_images_from_folder(folder),
547 def _add_references(message, issues):
548 return message + " - " + ", ".join(map(lambda issue: "Refs #%d" % issue['id'], issues))
550 def _get_issues_for_file(fileid):
553 uf = urllib2.urlopen(settings.REDMINE_URL + 'publications/issues/%s.json' % fileid)
554 return json.loads(uf.read())
555 except urllib2.HTTPError:
563 #def pull_requests(request):
564 # return direct_to_template(request, 'manager/pull_request.html', extra_context = {
565 # 'objects': models.PullRequest.objects.all()} )