source: main/waeup.kofa/trunk/src/waeup/kofa/students/fileviewlets.py @ 12438

Last change on this file since 12438 was 12438, checked in by Henrik Bettermann, 10 years ago

Propset svn:keywords "Id"

  • Property svn:keywords set to Id
File size: 9.7 KB
RevLine 
[12438]1## $Id: fileviewlets.py 12438 2015-01-11 08:27:37Z henrik $
[12421]2##
3## Copyright (C) 2014 Uli Fouquet & Henrik Bettermann
4## This program is free software; you can redistribute it and/or modify
5## it under the terms of the GNU General Public License as published by
6## the Free Software Foundation; either version 2 of the License, or
7## (at your option) any later version.
8##
9## This program is distributed in the hope that it will be useful,
10## but WITHOUT ANY WARRANTY; without even the implied warranty of
11## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12## GNU General Public License for more details.
13##
14## You should have received a copy of the GNU General Public License
15## along with this program; if not, write to the Free Software
16## Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17##
18
19import os
20import grok
21from zope.component import getUtility
22from waeup.kofa.interfaces import MessageFactory as _
23from waeup.kofa.interfaces import (
24    IExtFileStore, IFileStoreNameChooser, IKofaObject)
25from waeup.kofa.utils.helpers import string_from_bytes, file_size
26from waeup.kofa.browser import DEFAULT_IMAGE_PATH
27
28from waeup.kofa.students.interfaces import IStudent, IStudentsUtils
29
30from waeup.kofa.browser.layout import (
31    default_filedisplay_template,
32    default_fileupload_template)
33
34from waeup.kofa.students.browser import (
35    StudentBaseDisplayFormPage, StudentBaseManageFormPage,
36    StudentClearanceDisplayFormPage, StudentClearanceManageFormPage,
37    ExportPDFClearanceSlipPage, StudentFilesUploadPage)
38
39from waeup.kofa.utils.helpers import get_fileformat
40
41grok.context(IKofaObject) # Make IKofaObject the default context
42grok.templatedir('browser_templates')
43
44ALLOWED_FILE_EXTENSIONS = ('jpg', 'png', 'pdf', 'tif', 'fpm')
45
46def handle_file_delete(context, view, download_name):
47    """Handle deletion of student file.
48
49    """
50    store = getUtility(IExtFileStore)
51    store.deleteFileByContext(context, attr=download_name)
52    context.writeLogMessage(view, 'deleted: %s' % download_name)
53    view.flash(_('${a} deleted.', mapping = {'a':download_name}))
54    return
55
56def handle_file_upload(upload, context, view, max_size, download_name=None):
57    """Handle upload of student file.
58
59    Returns `True` in case of success or `False`.
60
61    Please note that file pointer passed in (`upload`) most probably
62    points to end of file when leaving this function.
63    """
64    # Check some file requirements first
65    size = file_size(upload)
66    if size > max_size:
67        view.flash(_('Uploaded file is too big.'), type="danger")
68        return False
69    upload.seek(0) # file pointer moved when determining size
70    dummy,ext = os.path.splitext(upload.filename)
71    # fpm files are expected to be fingerprint minutiae, file
72    # format is not yet checked
73    if ext == '.fpm':
74        file_format = 'fpm'
75    else:
76        file_format = get_fileformat(None, upload.read(512))
77        upload.seek(0) # same here
78    if file_format is None:
79        view.flash(_('Could not determine file type.'), type="danger")
80        return False
81    basename, expected_ext = os.path.splitext(download_name)
82    if expected_ext:
83        if '.' + file_format != expected_ext:
84            view.flash(_('${a} file format expected.',
85                mapping = {'a':expected_ext[1:]}), type="danger")
86            return False
87    else:
88        if not file_format in ALLOWED_FILE_EXTENSIONS:
89            view.flash(
90                _('Only the following extensions are allowed: ${a}',
91                mapping = {'a':', '.join(ALLOWED_FILE_EXTENSIONS)}),
92                type="danger")
93            return False
94        download_name += '.' + file_format
95    store = getUtility(IExtFileStore)
96    file_id = IFileStoreNameChooser(context).chooseName(attr=download_name)
97    store.createFile(file_id, upload)
98    context.writeLogMessage(view, 'uploaded: %s (%s)' % (
99        download_name,upload.filename))
100    view.flash(_('File ${a} uploaded.', mapping = {'a':download_name}))
101    return True
102
103# File viewlets for student base page
104
105class FileManager(grok.ViewletManager):
106    """Viewlet manager for uploading files, preferably scanned images.
107    """
108    grok.name('files')
109
110class FileDisplay(grok.Viewlet):
111    """Base file display viewlet.
112    """
113    grok.baseclass()
114    grok.context(IStudent)
115    grok.viewletmanager(FileManager)
116    grok.view(StudentClearanceDisplayFormPage)
117    template = default_filedisplay_template
118    grok.order(1)
119    grok.require('waeup.viewStudent')
120    label = _(u'File')
121    title = _(u'Scan')
122    download_name = u'filename.jpg'
123
124    @property
125    def file_exists(self):
126        image = getUtility(IExtFileStore).getFileByContext(
127            self.context, attr=self.download_name)
128        if image:
129            return True
130        else:
131            return False
132
133class FileUpload(FileDisplay):
134    """Base upload viewlet.
135    """
136    grok.baseclass()
137    grok.context(IStudent)
138    grok.viewletmanager(FileManager)
139    grok.view(StudentClearanceManageFormPage)
140    template = default_fileupload_template
141    grok.require('waeup.uploadStudentFile')
142    tab_redirect = '#tab2-top'
143    mus = 1024 * 150
144    upload_button =_('Upload selected file')
145    delete_button = _('Delete')
146
147    @property
148    def show_viewlet(self):
149        students_utils = getUtility(IStudentsUtils)
150        if self.__name__ in students_utils.SKIP_UPLOAD_VIEWLETS:
151            return False
152        return True
153
154    @property
155    def input_name(self):
156        return "%s" % self.__name__
157
158    def update(self):
159        self.max_upload_size = string_from_bytes(self.mus)
160        delete_button = self.request.form.get(
161            'delete_%s' % self.input_name, None)
162        upload_button = self.request.form.get(
163            'upload_%s' % self.input_name, None)
164        if delete_button:
165            handle_file_delete(
166                context=self.context, view=self.view,
167                download_name=self.download_name)
168            self.view.redirect(
169                self.view.url(
170                    self.context, self.view.__name__) + self.tab_redirect)
171            return
172        if upload_button:
173            upload = self.request.form.get(self.input_name, None)
174            if upload:
175                # We got a fresh upload
176                handle_file_upload(upload,
177                    self.context, self.view, self.mus, self.download_name)
178                self.view.redirect(
179                    self.view.url(
180                        self.context, self.view.__name__) + self.tab_redirect)
181            else:
182                self.view.flash(_('No local file selected.'), type="danger")
183                self.view.redirect(
184                    self.view.url(
185                        self.context, self.view.__name__) + self.tab_redirect)
186        return
187
188class PassportDisplay(FileDisplay):
189    """Passport display viewlet.
190    """
191    grok.order(1)
192    grok.context(IStudent)
193    grok.view(StudentBaseDisplayFormPage)
194    grok.require('waeup.viewStudent')
195    grok.template('imagedisplay')
196    label = _(u'Passport Picture')
197    download_name = u'passport.jpg'
198
199class PassportUploadManage(FileUpload):
200    """Passport upload viewlet for officers.
201    """
202    grok.order(1)
203    grok.context(IStudent)
204    grok.view(StudentBaseManageFormPage)
205    grok.require('waeup.manageStudent')
206    grok.template('imageupload')
207    label = _(u'Passport Picture (jpg only)')
208    mus = 1024 * 50
209    download_name = u'passport.jpg'
210    tab_redirect = '#tab2'
211
212class PassportUploadEdit(PassportUploadManage):
213    """Passport upload viewlet for students.
214    """
215    grok.view(StudentFilesUploadPage)
216    grok.require('waeup.uploadStudentFile')
217
218class BirthCertificateDisplay(FileDisplay):
219    """Birth Certificate display viewlet.
220    """
221    grok.order(1)
222    label = _(u'Birth Certificate')
223    title = _(u'Birth Certificate Scan')
224    download_name = u'birth_certificate'
225
226class BirthCertificateSlip(BirthCertificateDisplay):
227    grok.view(ExportPDFClearanceSlipPage)
228
229class BirthCertificateUpload(FileUpload):
230    """Birth Certificate upload viewlet.
231    """
232    grok.order(1)
233    label = _(u'Birth Certificate')
234    title = _(u'Birth Certificate Scan')
235    mus = 1024 * 150
236    download_name = u'birth_certificate'
237    tab_redirect = '#tab2-top'
238
239class Image(grok.View):
240    """Renders images for students.
241    """
242    grok.baseclass()
243    grok.name('none.jpg')
244    grok.context(IStudent)
245    grok.require('waeup.viewStudent')
246    download_name = u'none.jpg'
247
248    def render(self):
249        # A filename chooser turns a context into a filename suitable
250        # for file storage.
251        image = getUtility(IExtFileStore).getFileByContext(
252            self.context, attr=self.download_name)
253        if image is None:
254            # show placeholder image
255            self.response.setHeader('Content-Type', 'image/jpeg')
256            return open(DEFAULT_IMAGE_PATH, 'rb').read()
257        dummy,ext = os.path.splitext(image.name)
258        if ext == '.jpg':
259            self.response.setHeader('Content-Type', 'image/jpeg')
260        elif ext == '.fpm':
261            self.response.setHeader('Content-Type', 'application/binary')
262        elif ext == '.png':
263            self.response.setHeader('Content-Type', 'image/png')
264        elif ext == '.pdf':
265            self.response.setHeader('Content-Type', 'application/pdf')
266        elif ext == '.tif':
267            self.response.setHeader('Content-Type', 'image/tiff')
268        return image
269
270class Passport(Image):
271    """Renders jpeg passport picture.
272    """
273    grok.name('passport.jpg')
274    download_name = u'passport.jpg'
275    grok.context(IStudent)
276
277class ApplicationSlipImage(Image):
278    """Renders application slip scan.
279    """
280    grok.name('application_slip')
281    download_name = u'application_slip'
282
283class BirthCertificateImage(Image):
284    """Renders birth certificate scan.
285    """
286    grok.name('birth_certificate')
287    download_name = u'birth_certificate'
Note: See TracBrowser for help on using the repository browser.