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