1f53771e146332a01bff6c73bb919df50f311c60
[redakcja.git] / apps / explorer / views.py
1 # -*- coding: utf-8 -*-
2 import urllib2
3 import hg
4 from librarian import html, parser, dcparser, ParseError, ValidationError
5
6 from django.conf import settings
7 from django.contrib.auth.decorators import login_required, permission_required
8 from django.core.paginator import Paginator, InvalidPage, EmptyPage
9 from django.core.urlresolvers import reverse
10 from django.http import HttpResponseRedirect, HttpResponse
11 from django.utils import simplejson as json
12 from django.views.generic.simple import direct_to_template
13
14 from explorer import forms, models
15
16
17 #
18 # Some useful decorators
19 #
20 def with_repo(view):
21     """Open a repository for this view"""
22     def view_with_repo(request, *args, **kwargs):          
23         kwargs['repo'] = hg.Repository(settings.REPOSITORY_PATH)
24         return view(request, *args, **kwargs)
25     return view_with_repo
26
27 #
28 def ajax_login_required(view):
29     """Similar ro @login_required, but instead of redirect, 
30     just return some JSON stuff with error."""
31     def view_with_auth(request, *args, **kwargs):
32         if request.user.is_authenticated():
33             return view(request, *args, **kwargs)
34         # not authenticated
35         return HttpResponse( json.dumps({'result': 'access_denied'}) );
36     return view_with_auth
37
38 #
39 # View all files
40 #
41 @with_repo
42 def file_list(request, repo):
43     paginator = Paginator( repo.file_list('default'), 100);
44     bookform = forms.BookUploadForm()
45
46     try:
47         page = int(request.GET.get('page', '1'))
48     except ValueError:
49         page = 1
50
51     try:
52         files = paginator.page(page)
53     except (EmptyPage, InvalidPage):
54         files = paginator.page(paginator.num_pages)
55
56     return direct_to_template(request, 'explorer/file_list.html', extra_context={
57         'files': files, 'page': page, 'bookform': bookform,
58     })
59
60 @permission_required('explorer.can_add_files')
61 @with_repo
62 def file_upload(request, repo):
63     form = forms.BookUploadForm(request.POST, request.FILES)
64     if form.is_valid():
65         f = request.FILES['file']        
66
67         def upload_action():
68             print 'Adding file: %s' % f.name
69             repo._add_file(f.name, f.read().decode('utf-8'))
70             repo._commit(message="File %s uploaded from platform by %s" %
71                 (f.name, request.user.username), user=request.user.username)
72
73         repo.in_branch(upload_action, 'default')
74         return HttpResponseRedirect( reverse('editor_view', kwargs={'path': f.name}) )
75
76     return direct_to_template(request, 'explorer/file_upload.html',
77         extra_context = {'form' : form} )
78    
79 #
80 # Edit the file
81 #
82
83 @ajax_login_required
84 @with_repo
85 def file_xml(request, repo, path):
86     if request.method == 'POST':
87         errors = None
88         form = forms.BookForm(request.POST)
89         if form.is_valid():
90             print 'Saving whole text.', request.user.username
91             def save_action():
92                 print 'In branch: ' + repo.repo[None].branch()
93                 repo._add_file(path, form.cleaned_data['content'])                
94                 repo._commit(message=(form.cleaned_data['commit_message'] or 'Lokalny zapis platformy.'),\
95                      user=request.user.username)
96             try:
97                 # wczytaj dokument z ciągu znaków -> weryfikacja
98                 document = parser.WLDocument.from_string(form.cleaned_data['content'])
99
100                 #  save to user's branch
101                 repo.in_branch(save_action, models.user_branch(request.user) );
102             except (ParseError, ValidationError), e:
103                 errors = [e.message]              
104
105         if not errors:
106             errors = dict( (field[0], field[1].as_text()) for field in form.errors.iteritems() )
107
108         return HttpResponse(json.dumps({'result': errors and 'error' or 'ok', 'errors': errors}));
109
110     form = forms.BookForm()
111     data = repo.get_file(path, models.user_branch(request.user))
112     form.fields['content'].initial = data
113     return HttpResponse( json.dumps({'result': 'ok', 'content': data}) ) 
114
115 @ajax_login_required
116 @with_repo
117 def file_dc(request, path, repo):
118     errors = None
119
120     if request.method == 'POST':
121         form = forms.DublinCoreForm(request.POST)
122         
123         if form.is_valid():
124             def save_action():
125                 file_contents = repo._get_file(path)
126
127                 # wczytaj dokument z repozytorium
128                 document = parser.WLDocument.from_string(file_contents)                    
129                 document.book_info.update(form.cleaned_data)
130                 
131                 print "SAVING DC"
132
133                 # zapisz
134                 repo._add_file(path, document.serialize())
135                 repo._commit( \
136                     message=(form.cleaned_data['commit_message'] or 'Lokalny zapis platformy.'), \
137                     user=request.user.username )
138                 
139             try:
140                 repo.in_branch(save_action, models.user_branch(request.user) )
141             except (ParseError, ValidationError), e:
142                 errors = [e.message]
143
144         if errors is None:
145             errors = ["Pole '%s': %s\n" % (field[0], field[1].as_text()) for field in form.errors.iteritems()]
146
147         return HttpResponse( json.dumps({'result': errors and 'error' or 'ok', 'errors': errors}) );
148     
149     # this is unused currently, but may come in handy 
150     content = []
151     
152     try:
153         fulltext = repo.get_file(path, models.user_branch(request.user))
154         bookinfo = dcparser.BookInfo.from_string(fulltext)
155         content = bookinfo.to_dict()
156     except (ParseError, ValidationError), e:
157         errors = [e.message]
158
159     return HttpResponse( json.dumps({'result': errors and 'error' or 'ok', 
160         'errors': errors, 'content': content }) ) 
161
162 # Display the main editor view
163
164 @login_required
165 def display_editor(request, path):
166     return direct_to_template(request, 'explorer/editor.html', extra_context={
167         'hash': path, 'panel_list': ['lewy', 'prawy'],
168     })
169
170 # ===============
171 # = Panel views =
172 # ===============
173
174 @ajax_login_required
175 @with_repo
176 def xmleditor_panel(request, path, repo):
177     form = forms.BookForm()
178     text = repo.get_file(path, models.user_branch(request.user))
179     
180     return direct_to_template(request, 'explorer/panels/xmleditor.html', extra_context={
181         'fpath': path,
182         'text': text,
183     })
184     
185
186 @ajax_login_required
187 def gallery_panel(request, path):
188     return direct_to_template(request, 'explorer/panels/gallery.html', extra_context={
189         'fpath': path,
190         'form': forms.ImageFoldersForm(),
191     })
192
193 @ajax_login_required
194 @with_repo
195 def htmleditor_panel(request, path, repo):
196     user_branch = models.user_branch(request.user)
197     try:
198         return direct_to_template(request, 'explorer/panels/htmleditor.html', extra_context={
199             'fpath': path,
200             'html': html.transform(repo.get_file(path, user_branch), is_file=False),
201         })
202     except (ParseError, ValidationError), e:
203         return direct_to_template(request, 'explorer/panels/parse_error.html', extra_context={
204             'fpath': path, 'exception_type': type(e).__name__, 'exception': e, 'panel_name': 'Edytor HTML'}) 
205
206 @ajax_login_required
207 @with_repo
208 def dceditor_panel(request, path, repo):
209     user_branch = models.user_branch(request.user)
210
211     try:
212         doc_text = repo.get_file(path, user_branch)
213         document = parser.WLDocument.from_string(doc_text)
214         form = forms.DublinCoreForm(info=document.book_info)       
215         print "FORM: ", form
216         return direct_to_template(request, 'explorer/panels/dceditor.html', extra_context={
217             'fpath': path,
218             'form': form,
219         })
220     except (ParseError, ValidationError), e:
221         return direct_to_template(request, 'explorer/panels/parse_error.html', extra_context={
222             'fpath': path, 'exception_type': type(e).__name__, 'exception': e, 
223             'panel_name': 'Edytor DublinCore'}) 
224
225 # =================
226 # = Utility views =
227 # =================
228 @ajax_login_required
229 def folder_images(request, folder):
230     return direct_to_template(request, 'explorer/folder_images.html', extra_context={
231         'images': models.get_images_from_folder(folder),
232     })
233
234
235 def _add_references(message, issues):
236     return message + " - " + ", ".join(map(lambda issue: "Refs #%d" % issue['id'], issues))
237
238 def _get_issues_for_file(path):
239     if not path.endswith('.xml'):
240         raise ValueError('Path must end with .xml')
241
242     book_id = path[:-4]
243     uf = None
244
245     try:
246         uf = urllib2.urlopen(settings.REDMINE_URL + 'publications/issues/%s.json' % book_id)
247         return json.loads(uf.read())
248     except urllib2.HTTPError:
249         return []
250     finally:
251         if uf: uf.close()
252
253
254 # =================
255 # = Pull requests =
256 # =================
257 def pull_requests(request):
258     return direct_to_template(request, 'manager/pull_request.html', extra_context = {
259         'objects': models.PullRequest.objects.all()} )