7a34cad2cc1c5e4d7c7b5e02ac0af7efe3230bea
[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 from django.contrib.auth.decorators import login_required
10
11 from explorer import forms, models
12
13 #
14 # Some useful decorators
15 #
16 def with_repo(view):
17     """Open a repository for this view"""
18     def view_with_repo(request, *args, **kwargs):          
19         kwargs['repo'] = hg.Repository(settings.REPOSITORY_PATH)
20         return view(request, *args, **kwargs)
21     return view_with_repo
22
23 #
24 def ajax_login_required(view):
25     """Similar ro @login_required, but instead of redirect, 
26     just return some JSON stuff with error."""
27     def view_with_auth(request, *args, **kwargs):
28         if request.user.is_authenticated():
29             return view(request, *args, **kwargs)
30         # not authenticated
31         return HttpResponse( json.dumps({'result': 'access_denied'}) );
32     return view_with_auth
33
34 #
35 # View all files
36 #
37
38 @with_repo
39 def file_list(request, repo):
40     return direct_to_template(request, 'explorer/file_list.html', extra_context={
41         'objects': repo.all_files(),
42     })
43 #
44 # Edit the file
45 #
46
47 @ajax_login_required
48 @with_repo
49 def file_xml(request, repo, path):
50     if request.method == 'POST':
51         form = forms.BookForm(request.POST)
52         if form.is_valid():
53             print 'Saving whole text.', request.user.username
54             def save_action():
55                 print 'In branch: ' + repo.repo[None].branch()
56                 print repo._add_file(path, form.cleaned_data['content'])
57                 print repo.repo.status()
58                 print repo._commit(message=(form.cleaned_data['commit_message'] or 'Lokalny zapis platformy.'), user=request.user.username)
59
60             print repo.in_branch(save_action, models.user_branch(request.user) );
61             result = "ok"
62         else:
63             result = "error"
64
65         errors = dict( (field[0], field[1].as_text()) for field in form.errors.iteritems() )
66         return HttpResponse( json.dumps({'result': result, 'errors': errors}) );
67
68     form = forms.BookForm()
69     data = repo.get_file(path, models.user_branch(request.user))
70     form.fields['content'].initial = data
71     return HttpResponse( json.dumps({'result': 'ok', 'content': data}) ) 
72
73 @ajax_login_required
74 @with_repo
75 def file_dc(request, path, repo):
76     if request.method == 'POST':
77         form = forms.DublinCoreForm(request.POST)
78         if form.is_valid():
79             form.save(repo, path)
80             result = "ok"
81         else:
82             result = "error" 
83
84         errors = dict( (field[0], field[1].as_text()) for field in form.errors.iteritems() )
85         return HttpResponse( json.dumps({'result': result, 'errors': errors}) );
86     
87     fulltext = repo.get_file(path, models.user_branch(request.user))
88     form = forms.DublinCoreForm(text=fulltext)       
89     return HttpResponse( json.dumps({'result': 'ok', 'content': fulltext}) ) 
90
91 # Display the main editor view
92
93 @login_required
94 def display_editor(request, path):
95     return direct_to_template(request, 'explorer/editor.html', extra_context={
96         'hash': path, 'panel_list': ['lewy', 'prawy'],
97     })
98
99 # ===============
100 # = Panel views =
101 # ===============
102
103 @ajax_login_required
104 @with_repo
105 def xmleditor_panel(request, path, repo):
106     form = forms.BookForm()
107     text = repo.get_file(path, models.user_branch(request.user))
108     
109     return direct_to_template(request, 'explorer/panels/xmleditor.html', extra_context={
110         'fpath': path,
111         'text': text,
112     })
113     
114
115 @ajax_login_required
116 def gallery_panel(request, path):
117     return direct_to_template(request, 'explorer/panels/gallery.html', extra_context={
118         'fpath': path,
119         'form': forms.ImageFoldersForm(),
120     })
121
122 @ajax_login_required
123 @with_repo
124 def htmleditor_panel(request, path, repo):
125     user_branch = models.user_branch(request.user)
126     return direct_to_template(request, 'explorer/panels/htmleditor.html', extra_context={
127         'fpath': path,
128         'html': html.transform(repo.get_file(path, user_branch), is_file=False),
129     })
130  
131
132 @ajax_login_required
133 @with_repo
134 def dceditor_panel(request, path, repo):
135     user_branch = models.user_branch(request.user)
136     text = repo.get_file(path, user_branch)
137     form = forms.DublinCoreForm(text=text)       
138
139     return direct_to_template(request, 'explorer/panels/dceditor.html', extra_context={
140         'fpath': path,
141         'form': form,
142     })
143
144
145 # =================
146 # = Utility views =
147 # =================
148 @ajax_login_required
149 def folder_images(request, folder):
150     return direct_to_template(request, 'explorer/folder_images.html', extra_context={
151         'images': models.get_images_from_folder(folder),
152     })
153
154
155 def _add_references(message, issues):
156     return message + " - " + ", ".join(map(lambda issue: "Refs #%d" % issue['id'], issues))
157
158 def _get_issues_for_file(path):
159     if not path.endswith('.xml'):
160         raise ValueError('Path must end with .xml')
161
162     book_id = path[:-4]
163     uf = None
164
165     try:
166         uf = urllib2.urlopen(settings.REDMINE_URL + 'publications/issues/%s.json' % book_id)
167         return json.loads(uf.read())
168     except urllib2.HTTPError:
169         return []
170     finally:
171         if uf: uf.close()
172
173
174 # =================
175 # = Pull requests =
176 # =================
177 def pull_requests(request):
178     return direct_to_template(request, 'manager/pull_request.html', extra_context = {
179         'objects': models.PullRequest.objects.all()} )