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
 
  28 # Some useful decorators
 
  30 def file_branch(fileid, user=None):
 
  31     parts = fileid.split('$')
 
  32     return ('personal_'+ user.username + '_' if user is not None else '') \
 
  35 def file_path(fileid):
 
  36     return 'pub_'+fileid+'.xml'
 
  39     """Open a repository for this view"""
 
  40     def view_with_repo(request, *args, **kwargs):          
 
  41         kwargs['repo'] = wlrepo.MercurialLibrary(settings.REPOSITORY_PATH)
 
  42         return view(request, *args, **kwargs)
 
  46 def ajax_login_required(view):
 
  47     """Similar ro @login_required, but instead of redirect, 
 
  48     just return some JSON stuff with error."""
 
  49     def view_with_auth(request, *args, **kwargs):
 
  50         if request.user.is_authenticated():
 
  51             return view(request, *args, **kwargs)
 
  53         return HttpResponse( json.dumps({'result': 'access_denied', 'errors': ['Brak dostępu.']}) );
 
  60 def file_list(request, repo):   
 
  62     from api.resources import library_resource
 
  64     bookform = api.forms.DocumentUploadForm()
 
  66     # short-circut the api document list
 
  67     doctree = library_resource.handler.read(request)
 
  68     print doctree['documents']
 
  70     return direct_to_template(request, 'explorer/file_list.html', extra_context={
 
  71         'filetree': doctree['documents'], '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):    
 
 360     # this is the only entry point where we create an autobranch for the user
 
 361     # if it doesn't exists. All other views SHOULD fail.
 
 362     #def ensure_branch_exists():
 
 363     #    parent = repo.get_branch_tip('default')
 
 364     #    repo._create_branch(file_branch(path, request.user), parent)
 
 367     #    repo.with_wlock(ensure_branch_exists)
 
 369     return direct_to_template(request, 'explorer/editor.html', extra_context={
 
 371         'panel_list': ['lewy', 'prawy'],
 
 372         'availble_panels': models.EditorPanel.objects.all(),
 
 373         # 'scriptlets': toolbar_models.Scriptlet.objects.all()
 
 376 #        return direct_to_template(request, 'explorer/nofile.html', \
 
 377 #            extra_context = { 'fileid': path })
 
 382 class panel_view(object):
 
 384     def __new__(cls, request, name, path, **kwargs):
 
 386         panel = models.EditorPanel.objects.get(id=name)
 
 387         method = getattr(cls, name + '_panel', None)
 
 388         if not panel or method is None:
 
 389             raise HttpResponseNotFound
 
 391         extra_context = method(request, path, panel, **kwargs)
 
 393         if not isinstance(extra_context, dict):
 
 396         extra_context.update({
 
 397             'toolbar_groups': panel.toolbar_groups.all(),
 
 398             'toolbar_extra_group': panel.toolbar_extra,
 
 402         return direct_to_template(request, 'explorer/panels/'+name+'.html',\
 
 403             extra_context=extra_context)
 
 408     def xmleditor_panel(request, path, panel, repo):
 
 409         rpath = file_path(path)
 
 410         return {'text': repo.get_file(rpath, file_branch(path, request.user))}
 
 414     def gallery_panel(request, path, panel):
 
 415         return {'form': forms.ImageFoldersForm() }
 
 420     def htmleditor_panel(request, path, panel, repo):
 
 421         rpath = file_path(path)
 
 422         user_branch = file_branch(path, request.user)
 
 424             result = html.transform(repo.get_file(rpath, user_branch), is_file=False)
 
 425             print "HTML: %r" % result
 
 426             return {'html': result}
 
 427         except (ParseError, ValidationError), e:
 
 428             return direct_to_template(request, 'explorer/panels/parse_error.html', extra_context={
 
 429             'fileid': path, 'exception_type': type(e).__name__, 'exception': e,
 
 430             'panel_name': panel.display_name})
 
 435     def dceditor_panel(request, path, panel, repo):
 
 436         user_branch = file_branch(path, request.user)
 
 437         rpath = file_path(path)
 
 439             doc_text = repo.get_file(rpath, user_branch)
 
 440             document = parser.WLDocument.from_string(doc_text)
 
 441             form = forms.DublinCoreForm(info=document.book_info)
 
 442             return {'form': form}
 
 443         except (ParseError, ValidationError), e:
 
 444             return direct_to_template(request, 'explorer/panels/parse_error.html', extra_context={
 
 445             'fileid': path, 'exception_type': type(e).__name__, 'exception': e,
 
 446             'panel_name': panel.display_name})
 
 449 ## Editor "commands" and "dialogs"
 
 453 def print_html(request, path, repo):
 
 454     user_branch = file_branch(path, request.user)
 
 455     rpath = file_path(path)
 
 457         html.transform(repo.get_file(rpath, user_branch), is_file=False),
 
 458         mimetype="text/html")
 
 462 def print_xml(request, path, repo):
 
 463     user_branch = file_branch(path, request.user)
 
 464     rpath = file_path(path)
 
 465     return HttpResponse( repo.get_file(rpath, user_branch), mimetype="text/plain; charset=utf-8")
 
 467 @permission_required('explorer.can_add_files')
 
 468 def split_text(request, path):
 
 469     rpath = file_path(path)
 
 471     if request.method == "POST":
 
 472         sform = forms.SplitForm(request.POST, prefix='splitform')
 
 473         dcform = forms.DublinCoreForm(request.POST, prefix='dcform')
 
 475         print "validating sform"
 
 478 #            if sform.cleaned_data['autoxml']:
 
 479 #                print "validating dcform"
 
 480 #                valid = dcform.is_valid()
 
 482         print "valid is ", valid
 
 485             uri = path + '$' + sform.cleaned_data['partname']
 
 486             child_rpath = file_path(uri)
 
 487             repo = hg.Repository(settings.REPOSITORY_PATH)            
 
 489             # save the text into parent's branch
 
 491                 if repo._file_exists(child_rpath):
 
 492                     el = sform._errors.get('partname', ErrorList())
 
 493                     el.append("Part with this name already exists")
 
 494                     sform._errors['partname'] = el
 
 497                 fulltext = sform.cleaned_data['fulltext']               
 
 498                 fulltext = fulltext.replace(u'<include-tag-placeholder />',
 
 499                     librarian.xinclude_forURI(u'wlrepo://'+uri) )
 
 501                 repo._write_file(rpath, fulltext.encode('utf-8'))
 
 503                 newtext = sform.cleaned_data['splittext']
 
 504                 if sform.cleaned_data['autoxml']:
 
 505                     # this is a horrible hack - really
 
 506                     bi = dcparser.BookInfo.from_element(librarian.DEFAULT_BOOKINFO.to_etree())
 
 507                     bi.update(dcform.data)
 
 509                     newtext = librarian.wrap_text(newtext, \
 
 510                         unicode(date.today()), bookinfo=bi )
 
 512                 repo._add_file(child_rpath, newtext.encode('utf-8'))                
 
 513                 repo._commit(message="Split from '%s' to '%s'" % (path, uri), \
 
 514                     user=request.user.username )
 
 517             if repo.in_branch(split_action, file_branch(path, request.user)):
 
 518                 # redirect to success
 
 520                 uri = urllib.quote( unicode(uri).encode('utf-8'))
 
 521                 return HttpResponseRedirect( reverse('split-success',\
 
 522                     kwargs={'path': path})+'?child='+uri )
 
 524         try: # to read the current DC
 
 525             repo = hg.Repository(settings.REPOSITORY_PATH)
 
 526             fulltext = repo.get_file(rpath, file_branch(path, request.user))
 
 527             bookinfo = dcparser.BookInfo.from_string(fulltext)
 
 528         except (ParseError, ValidationError):
 
 529             bookinfo = librarian.DEFAULT_BOOKINFO
 
 531         sform = forms.SplitForm(prefix='splitform')
 
 532         dcform = forms.DublinCoreForm(prefix='dcform', info=bookinfo)
 
 534     return direct_to_template(request, 'explorer/split.html', extra_context={
 
 535         'splitform': sform, 'dcform': dcform, 'fileid': path} )
 
 537 def split_success(request, path):
 
 538     return direct_to_template(request, 'explorer/split_success.html',\
 
 539         extra_context={'fileid': path, 'cfileid': request.GET['child']} )
 
 546 def folder_images(request, folder):
 
 547     return direct_to_template(request, 'explorer/folder_images.html', extra_context={
 
 548         'images': models.get_images_from_folder(folder),
 
 551 def _add_references(message, issues):
 
 552     return message + " - " + ", ".join(map(lambda issue: "Refs #%d" % issue['id'], issues))
 
 554 def _get_issues_for_file(fileid):
 
 557         uf = urllib2.urlopen(settings.REDMINE_URL + 'publications/issues/%s.json' % fileid)
 
 558         return json.loads(uf.read())
 
 559     except urllib2.HTTPError:
 
 567 #def pull_requests(request):
 
 568 #    return direct_to_template(request, 'manager/pull_request.html', extra_context = {
 
 569 #        'objects': models.PullRequest.objects.all()} )