Dodanie middleware EditorSettings.
[redakcja.git] / apps / explorer / views.py
1 import urllib2
2 import hg
3 from lxml import etree
4 from librarian import html,dcparser
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         form = forms.BookForm(request.POST)
88         if form.is_valid():
89             print 'Saving whole text.', request.user.username
90             def save_action():
91                 print 'In branch: ' + repo.repo[None].branch()
92                 repo._add_file(path, form.cleaned_data['content'])                
93                 repo._commit(message=(form.cleaned_data['commit_message'] or 'Lokalny zapis platformy.'), user=request.user.username)
94
95             print repo.in_branch(save_action, models.user_branch(request.user) );
96             result = "ok"
97         else:
98             result = "error"
99
100         errors = dict( (field[0], field[1].as_text()) for field in form.errors.iteritems() )
101         return HttpResponse( json.dumps({'result': result, 'errors': errors}) );
102
103     form = forms.BookForm()
104     data = repo.get_file(path, models.user_branch(request.user))
105     form.fields['content'].initial = data
106     return HttpResponse( json.dumps({'result': 'ok', 'content': data}) ) 
107
108 @ajax_login_required
109 @with_repo
110 def file_dc(request, path, repo):
111     if request.method == 'POST':
112         form = forms.DublinCoreForm(request.POST)
113         
114         if form.is_valid():
115             def save_action():
116                 file_contents = repo._get_file(path)
117                 doc = etree.fromstring(file_contents)
118
119                 book_info = dcparser.BookInfo()
120                 for name, value in form.cleaned_data.items():
121                     if value is not None and value != '':
122                         setattr(book_info, name, value)
123                 rdf = etree.XML(book_info.to_xml())
124
125                 old_rdf = doc.getroottree().find('//{http://www.w3.org/1999/02/22-rdf-syntax-ns#}RDF')
126                 old_rdf.getparent().remove(old_rdf)
127                 doc.insert(0, rdf)
128                 repo._add_file(path, etree.tostring(doc, pretty_print=True, encoding=unicode))
129                 repo._commit(message=(form.cleaned_data['commit_message'] or 'Lokalny zapis platformy.'), user=request.user.username)
130
131             repo.in_branch(save_action, models.user_branch(request.user) )
132
133             result = "ok"
134         else:
135             result = "error" 
136
137         errors = dict( (field[0], field[1].as_text()) for field in form.errors.iteritems() )
138         return HttpResponse( json.dumps({'result': result, 'errors': errors}) );
139     
140     fulltext = repo.get_file(path, models.user_branch(request.user))
141     form = forms.DublinCoreForm(text=fulltext)       
142     return HttpResponse( json.dumps({'result': 'ok', 'content': fulltext}) ) 
143
144 # Display the main editor view
145
146 @login_required
147 def display_editor(request, path):
148     return direct_to_template(request, 'explorer/editor.html', extra_context={
149         'hash': path, 'panel_list': ['lewy', 'prawy'],
150     })
151
152 # ===============
153 # = Panel views =
154 # ===============
155
156 @ajax_login_required
157 @with_repo
158 def xmleditor_panel(request, path, repo):
159     form = forms.BookForm()
160     text = repo.get_file(path, models.user_branch(request.user))
161     
162     return direct_to_template(request, 'explorer/panels/xmleditor.html', extra_context={
163         'fpath': path,
164         'text': text,
165     })
166     
167
168 @ajax_login_required
169 def gallery_panel(request, path):
170     return direct_to_template(request, 'explorer/panels/gallery.html', extra_context={
171         'fpath': path,
172         'form': forms.ImageFoldersForm(),
173     })
174
175 @ajax_login_required
176 @with_repo
177 def htmleditor_panel(request, path, repo):
178     user_branch = models.user_branch(request.user)
179     return direct_to_template(request, 'explorer/panels/htmleditor.html', extra_context={
180         'fpath': path,
181         'html': html.transform(repo.get_file(path, user_branch), is_file=False),
182     })
183  
184
185 @ajax_login_required
186 @with_repo
187 def dceditor_panel(request, path, repo):
188     user_branch = models.user_branch(request.user)
189     text = repo.get_file(path, user_branch)
190     form = forms.DublinCoreForm(text=text)       
191
192     return direct_to_template(request, 'explorer/panels/dceditor.html', extra_context={
193         'fpath': path,
194         'form': form,
195     })
196
197
198 # =================
199 # = Utility views =
200 # =================
201 @ajax_login_required
202 def folder_images(request, folder):
203     return direct_to_template(request, 'explorer/folder_images.html', extra_context={
204         'images': models.get_images_from_folder(folder),
205     })
206
207
208 def _add_references(message, issues):
209     return message + " - " + ", ".join(map(lambda issue: "Refs #%d" % issue['id'], issues))
210
211 def _get_issues_for_file(path):
212     if not path.endswith('.xml'):
213         raise ValueError('Path must end with .xml')
214
215     book_id = path[:-4]
216     uf = None
217
218     try:
219         uf = urllib2.urlopen(settings.REDMINE_URL + 'publications/issues/%s.json' % book_id)
220         return json.loads(uf.read())
221     except urllib2.HTTPError:
222         return []
223     finally:
224         if uf: uf.close()
225
226
227 # =================
228 # = Pull requests =
229 # =================
230 def pull_requests(request):
231     return direct_to_template(request, 'manager/pull_request.html', extra_context = {
232         'objects': models.PullRequest.objects.all()} )