Merge branch 'master' of stigma.nowoczesnapolska.org.pl:platforma
[redakcja.git] / apps / explorer / views.py
1 # -*- coding: utf-8 -*-
2 import urllib2
3 import hg, re
4 from datetime import date
5
6 import librarian
7
8 from librarian import html, parser, dcparser
9 from librarian import ParseError, ValidationError
10
11 from django.conf import settings
12 from django.contrib.auth.decorators import login_required, permission_required
13
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
19
20 from explorer import forms, models
21 from toolbar import models as toolbar_models
22
23 from django.forms.util import ErrorList
24
25 import wlrepo
26
27 #
28 # Some useful decorators
29
30 def file_branch(fileid, user=None):
31     parts = fileid.split('$')
32     return ('personal_'+ user.username + '_' if user is not None else '') \
33         + 'file_' + parts[0]
34
35 def file_path(fileid):
36     return 'pub_'+fileid+'.xml'
37
38 def with_repo(view):
39     """Open a repository for this view"""
40     def view_with_repo(request, *args, **kwargs):          
41         kwargs['repo'] = wlrepo.open_library(settings.REPOSITORY_PATH, 'hg')
42         return view(request, *args, **kwargs)
43     return view_with_repo
44
45 #
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)
52         # not authenticated
53         return HttpResponse( json.dumps({'result': 'access_denied', 'errors': ['Brak dostÄ™pu.']}) );
54     return view_with_auth
55
56 @login_required
57 # @with_repo
58 def display_editor(request, path):
59     # this is the only entry point where we create an autobranch for the user
60     # if it doesn't exists. All other views SHOULD fail.
61     #def ensure_branch_exists():
62     #    parent = repo.get_branch_tip('default')
63     #    repo._create_branch(file_branch(path, request.user), parent)
64
65 #    try:
66     #    repo.with_wlock(ensure_branch_exists)
67
68     return direct_to_template(request, 'explorer/editor.html', extra_context={
69         'fileid': path,
70         'panel_list': ['lewy', 'prawy'],
71         'availble_panels': models.EditorPanel.objects.all(),
72         # 'scriptlets': toolbar_models.Scriptlet.objects.all()
73     })
74     
75 #
76 # View all files
77 #
78 @with_repo
79 def file_list(request, repo):   
80     import api.forms
81     from api.resources import library_resource
82
83     bookform = api.forms.DocumentUploadForm()
84
85     # short-circut the api document list
86     doctree = library_resource.handler.read(request)
87     # print "DOCTREE:", doctree['documents']
88         
89     return direct_to_template(request, 'explorer/file_list.html', extra_context={
90         'filetree': doctree['documents'], 'bookform': bookform,
91     })
92
93 @permission_required('explorer.can_add_files')
94 @with_repo
95 def file_upload(request, repo):
96     from api.resources import library_resource
97     from api.forms import DocumentUploadForm
98     from django.http import HttpRequest, HttpResponseRedirect
99
100     response = library_resource.handler.create(request)
101
102     if isinstance(response, HttpResponse):
103         data = json.loads(response.content)
104         
105         if response.status_code == 201:
106             return HttpResponseRedirect( \
107                 reverse("editor_view", args=[ data['name'] ]) )
108         else:
109             bookform = DocumentUploadForm(request.POST, request.FILES)
110             bookform.is_valid()
111             
112             return direct_to_template(request, 'explorer/file_upload.html',
113                 extra_context={'bookform': bookform } )
114           
115
116 @login_required
117 def print_html(request, **kwargs):
118     from api.resources import document_html_resource
119     
120     output = document_html_resource.handler.read(request, **kwargs)
121
122     if isinstance(output, HttpResponse):
123         # errors = json.loads(output.content)
124         output.mimetype = "text/plain"
125         return output
126     
127     return direct_to_template(request, 'html4print.html',
128         extra_context={'output': output, 'docid': kwargs['docid']},
129         mimetype="text/html" )
130
131
132 def _add_references(message, issues):
133     return message + " - " + ", ".join(map(lambda issue: "Refs #%d" % issue['id'], issues))
134
135 def _get_issues_for_file(fileid):
136     uf = None
137     try:
138         uf = urllib2.urlopen(settings.REDMINE_URL + 'publications/issues/%s.json' % fileid)
139         return json.loads(uf.read())
140     except urllib2.HTTPError:
141         return []
142     finally:
143         if uf: uf.close()
144
145 # =================
146 # = Pull requests =
147 # =================
148 #def pull_requests(request):
149 #    return direct_to_template(request, 'manager/pull_request.html', extra_context = {
150 #        'objects': models.PullRequest.objects.all()} )