Czytanie plików PNG a nie JPG w galerii.
[redakcja.git] / apps / explorer / views.py
1 # -*- coding: utf-8 -*-
2 import urllib2
3
4 import logging
5 log = logging.getLogger('platforma.explorer.views')
6
7 from django.conf import settings
8 from django.contrib.auth.decorators import login_required, permission_required
9
10 from django.core.urlresolvers import reverse
11 from django.http import HttpResponse, Http404
12 from django.utils import simplejson as json
13 from django.views.generic.simple import direct_to_template
14 from django.shortcuts import render_to_response
15 from django.template import RequestContext
16 from django.contrib.auth.decorators import login_required
17
18 from explorer import forms, models
19 import os
20 # from api.models import PullRequest
21 from bookthemes.models import Theme
22
23 def ajax_login_required(view):
24     """Similar ro @login_required, but instead of redirect, 
25     just return some JSON stuff with error."""
26     def view_with_auth(request, *args, **kwargs):
27         if request.user.is_authenticated():
28             return view(request, *args, **kwargs)
29         # not authenticated
30         return HttpResponse( json.dumps({'result': 'access_denied', 'errors': ['Brak dostępu.']}) );
31     return view_with_auth
32
33 @login_required
34 def display_editor(request, path):
35     user = request.GET.get('user', request.user.username)
36     gallery_form = forms.GalleryChoiceForm()
37     
38     return render_to_response('explorer/editor.html',
39         # mimetype="text/html",
40         dictionary = {
41             'fileid': path,
42             'euser': user,
43             'gallery_form': gallery_form,
44             'available_themes': ({'first_letter': t.name[0].upper(), 'name': t.name} for t in Theme.objects.order_by('name')),
45         }, context_instance=RequestContext(request))
46
47 #
48 # View all files
49 #
50 def file_list(request):   
51     from wiki.views import document_list
52
53     # short-circut the api document list
54     # doctree = library_resource.handler.read(request)
55     # print "DOCTREE:", doctree['documents']
56         
57     return document_list(request, 'explorer/file_list.html')
58     
59     # return direct_to_template(request, 'explorer/file_list.html', extra_context={
60     #     'files': files, 'bookform': bookform,
61     # })
62
63 @permission_required('api.document.can_add')
64 def file_upload(request):
65     from api.resources import library_resource
66     from api.forms import DocumentUploadForm
67     from django.http import HttpRequest, HttpResponseRedirect
68
69     response = library_resource.handler.create(request)
70
71     if isinstance(response, HttpResponse):
72         data = json.loads(response.content)
73         
74         if response.status_code == 201:
75             return HttpResponseRedirect( \
76                 reverse("editor_view", args=[ data['name'] ]) )
77         else:
78             bookform = DocumentUploadForm(request.POST, request.FILES)
79             bookform.is_valid()
80             
81             return direct_to_template(request, 'explorer/file_upload.html',
82                 extra_context={'bookform': bookform } )
83           
84
85 @login_required
86 def print_html(request, **kwargs):
87     from api.resources import document_html_resource
88
89     kwargs['stylesheet'] = 'legacy'
90     
91     output = document_html_resource.handler.read(request, **kwargs)
92
93     if isinstance(output, HttpResponse):
94         # errors = json.loads(output.content)
95         output.mimetype = "text/plain"
96         return output
97     
98     return direct_to_template(request, 'html4print.html',
99         extra_context={'output': output, 'docid': kwargs['docid']},
100         mimetype="text/html" )
101
102
103 def _add_references(message, issues):
104     return message + " - " + ", ".join(map(lambda issue: "Refs #%d" % issue['id'], issues))
105
106 def _get_issues_for_file(fileid):
107     uf = None
108     try:
109         uf = urllib2.urlopen(settings.REDMINE_URL + 'publications/issues/%s.json' % fileid)
110         return json.loads(uf.read())
111     except urllib2.HTTPError:
112         return []
113     finally:
114         if uf: uf.close()
115
116 # =================
117 # = Pull requests =
118 # =================
119 def pull_requests(request):    
120     objects = PullRequest.objects.order_by('-status', 'timestamp')
121
122     if not request.user.has_perm('explorer.book.can_share'):
123         objects = objects.filter(comitter=request.user)
124
125     return direct_to_template(request, 'manager/pull_request.html', 
126         extra_context = {'objects': objects} )
127
128
129 #
130 # Testing
131 #
132 def renderer_test(request):
133     return direct_to_template(request, 'renderer.html', mimetype="text/html",
134         extra_context = {} )
135
136
137 def document_gallery(request, directory):
138     try:
139         base_dir = os.path.join(settings.MEDIA_ROOT, settings.FILEBROWSER_DIRECTORY, directory)
140         print base_dir
141         images = ['%s%s%s/%s' % (settings.MEDIA_URL, settings.FILEBROWSER_DIRECTORY, directory, f) for f in os.listdir(base_dir) if f.lower().endswith('.png')]
142         return HttpResponse(json.dumps(images))
143     except (IndexError, OSError), e:
144         raise Http404