Merge branch 'master' of git@stigma:platforma
[redakcja.git] / apps / explorer / views.py
1 from librarian import html
2 import hg, urllib2, time
3 from django.utils import simplejson as json
4
5 from django.views.generic.simple import direct_to_template
6
7 from django.conf import settings
8 from django.http import HttpResponseRedirect, HttpResponse
9
10 from django.core.urlresolvers import reverse
11 from django.core.paginator import Paginator, InvalidPage, EmptyPage
12
13 from django.contrib.auth.decorators import login_required
14
15 from explorer import forms, models
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(), 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 @login_required
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         print 'Adding file: %s' % f.name
67         repo.add_file(f.name, f.read().decode('utf-8'))
68         return HttpResponseRedirect( reverse('editor_view', kwargs={'path': f.name}) )
69
70     return direct_to_template(request, 'explorer/file_upload.html',
71         extra_context = {'form' : form} )
72    
73 #
74 # Edit the file
75 #
76
77 @ajax_login_required
78 @with_repo
79 def file_xml(request, repo, path):
80     if request.method == 'POST':
81         form = forms.BookForm(request.POST)
82         if form.is_valid():
83             print 'Saving whole text.', request.user.username
84             def save_action():
85                 print 'In branch: ' + repo.repo[None].branch()
86                 repo._add_file(path, form.cleaned_data['content'])                
87                 repo._commit(message=(form.cleaned_data['commit_message'] or 'Lokalny zapis platformy.'), user=request.user.username)
88
89             print repo.in_branch(save_action, models.user_branch(request.user) );
90             result = "ok"
91         else:
92             result = "error"
93
94         errors = dict( (field[0], field[1].as_text()) for field in form.errors.iteritems() )
95         return HttpResponse( json.dumps({'result': result, 'errors': errors}) );
96
97     form = forms.BookForm()
98     data = repo.get_file(path, models.user_branch(request.user))
99     form.fields['content'].initial = data
100     return HttpResponse( json.dumps({'result': 'ok', 'content': data}) ) 
101
102 @ajax_login_required
103 @with_repo
104 def file_dc(request, path, repo):
105     if request.method == 'POST':
106         form = forms.DublinCoreForm(request.POST)
107         if form.is_valid():
108             form.save(repo, path)
109             result = "ok"
110         else:
111             result = "error" 
112
113         errors = dict( (field[0], field[1].as_text()) for field in form.errors.iteritems() )
114         return HttpResponse( json.dumps({'result': result, 'errors': errors}) );
115     
116     fulltext = repo.get_file(path, models.user_branch(request.user))
117     form = forms.DublinCoreForm(text=fulltext)       
118     return HttpResponse( json.dumps({'result': 'ok', 'content': fulltext}) ) 
119
120 # Display the main editor view
121
122 @login_required
123 def display_editor(request, path):
124     return direct_to_template(request, 'explorer/editor.html', extra_context={
125         'hash': path, 'panel_list': ['lewy', 'prawy'],
126     })
127
128 # ===============
129 # = Panel views =
130 # ===============
131
132 @ajax_login_required
133 @with_repo
134 def xmleditor_panel(request, path, repo):
135     form = forms.BookForm()
136     text = repo.get_file(path, models.user_branch(request.user))
137     
138     return direct_to_template(request, 'explorer/panels/xmleditor.html', extra_context={
139         'fpath': path,
140         'text': text,
141     })
142     
143
144 @ajax_login_required
145 def gallery_panel(request, path):
146     return direct_to_template(request, 'explorer/panels/gallery.html', extra_context={
147         'fpath': path,
148         'form': forms.ImageFoldersForm(),
149     })
150
151 @ajax_login_required
152 @with_repo
153 def htmleditor_panel(request, path, repo):
154     user_branch = models.user_branch(request.user)
155     return direct_to_template(request, 'explorer/panels/htmleditor.html', extra_context={
156         'fpath': path,
157         'html': html.transform(repo.get_file(path, user_branch), is_file=False),
158     })
159  
160
161 @ajax_login_required
162 @with_repo
163 def dceditor_panel(request, path, repo):
164     user_branch = models.user_branch(request.user)
165     text = repo.get_file(path, user_branch)
166     form = forms.DublinCoreForm(text=text)       
167
168     return direct_to_template(request, 'explorer/panels/dceditor.html', extra_context={
169         'fpath': path,
170         'form': form,
171     })
172
173
174 # =================
175 # = Utility views =
176 # =================
177 @ajax_login_required
178 def folder_images(request, folder):
179     return direct_to_template(request, 'explorer/folder_images.html', extra_context={
180         'images': models.get_images_from_folder(folder),
181     })
182
183
184 def _add_references(message, issues):
185     return message + " - " + ", ".join(map(lambda issue: "Refs #%d" % issue['id'], issues))
186
187 def _get_issues_for_file(path):
188     if not path.endswith('.xml'):
189         raise ValueError('Path must end with .xml')
190
191     book_id = path[:-4]
192     uf = None
193
194     try:
195         uf = urllib2.urlopen(settings.REDMINE_URL + 'publications/issues/%s.json' % book_id)
196         return json.loads(uf.read())
197     except urllib2.HTTPError:
198         return []
199     finally:
200         if uf: uf.close()
201
202
203 # =================
204 # = Pull requests =
205 # =================
206 def pull_requests(request):
207     return direct_to_template(request, 'manager/pull_request.html', extra_context = {
208         'objects': models.PullRequest.objects.all()} )