124a574380689502e1bc708e7704c8eee9a63632
[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     kwargs['stylesheet'] = 'legacy'
121     
122     output = document_html_resource.handler.read(request, **kwargs)
123
124     if isinstance(output, HttpResponse):
125         # errors = json.loads(output.content)
126         output.mimetype = "text/plain"
127         return output
128     
129     return direct_to_template(request, 'html4print.html',
130         extra_context={'output': output, 'docid': kwargs['docid']},
131         mimetype="text/html" )
132
133
134 def _add_references(message, issues):
135     return message + " - " + ", ".join(map(lambda issue: "Refs #%d" % issue['id'], issues))
136
137 def _get_issues_for_file(fileid):
138     uf = None
139     try:
140         uf = urllib2.urlopen(settings.REDMINE_URL + 'publications/issues/%s.json' % fileid)
141         return json.loads(uf.read())
142     except urllib2.HTTPError:
143         return []
144     finally:
145         if uf: uf.close()
146
147 # =================
148 # = Pull requests =
149 # =================
150 def pull_requests(request):
151     from explorer.models import PullRequest
152
153     objects = PullRequest.objects.order_by('status')
154
155     if not request.user.has_perm('explorer.book.can_share'):
156         objects = objects.filter(comitter=request.user)
157
158     
159     return direct_to_template(request, 'manager/pull_request.html', 
160         extra_context = {'objects': objects} )