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