Project

General

Profile

Download (5.85 KB) Statistics
| Branch: | Tag: | Revision:

root / extra / modules / form.py @ e8b79d7d

1
from quixote.form.widget import ButtonWidget
2
from qommon.form import *
3
from qommon import get_cfg, get_logger
4

    
5
from strongbox import StrongboxItem
6

    
7
class FileWithPreviewAndStrongboxWidget(CompositeWidget):
8
    """Widget that proposes a File Upload widget but that stores the file
9
    ondisk so it has a "readonly" mode where the filename is shown."""
10
    token = None
11

    
12
    def __init__(self, name, value=None, **kwargs):
13
        CompositeWidget.__init__(self, name, value, **kwargs)
14
        self.value = value
15
        self.preview = kwargs.get('readonly')
16
        preview = kwargs.get('readonly')
17
        if not preview:
18
            del kwargs['title']
19
            if kwargs.has_key('hint'):
20
                del kwargs['hint']
21
            self.add(FileWidget, 'file', **kwargs)
22
            self.add(HiddenWidget, 'existing-file-token')
23
            self.add(CheckboxWidget, 'orexisting',
24
                            title = _('Or use previous file'), value=True)
25
            if get_cfg('misc', {}).get('aq-strongbox') and get_request().user:
26
                root_url = get_publisher().get_root_url()
27
                self.add(HiddenWidget, 'strongbox');
28
                self.widgets.append(HtmlWidget(
29
                        htmltext('<a href="%smyspace/strongbox/pick?id=%s" rel="popup">%s</a>') % (
30
                                root_url, name, _('Use file from strongbox'))))
31
        else:
32
            session = get_session()
33
            self.add(HiddenWidget, 'token')
34
            del kwargs['title']
35
            self.add(StringWidget, 'filename', **kwargs)
36
            if self.value and self.value.orig_filename:
37
                    wid = self.get_widget('filename')
38
                    get_request().form[wid.name] = self.value.orig_filename
39

    
40
            # Is this still mandatory ?
41
            if hasattr(get_request(), 'tempfiles'):
42
                if name in get_request().tempfiles:
43
                    token = get_request().tempfiles[name]
44
                    wid = self.get_widget('token')
45
                    get_request().form[wid.name] = token
46

    
47
    def render_content(self):
48
        r = TemplateIO(html=True)
49
        hasvalue = False
50
        if isinstance(self.value, PicklableUpload):
51
            filetype = mimetypes.guess_type(self.value.orig_filename)
52
            hasvalue = True
53
            if filetype and filetype[0] and filetype[0].startswith("image"):
54
                session = get_session()
55
                if session.tempfiles and self.token in session.tempfiles.keys():
56
                    session.tempfiles[self.token]['value'] = self.value.fp.read()
57
                    r += htmltext('<img alt="%s" src="tempfile?t=%s" />' % \
58
                                            (self.value.orig_filename,
59
                                             self.token))
60
                    self.value.fp.seek(0)
61
        for widget in self.get_widgets():
62
            if widget is self.get_widget('orexisting'):
63
                if not hasvalue:
64
                    continue
65
                widget.title = _('Or use previously uploaded file (%s)') % self.value.orig_filename
66
                widget.value = True
67
                widget.extra_css_class = 'or-existing'
68
                widget.render_br = False
69
                get_response().add_javascript(['jquery.js', 'fileupload.js'])
70
            if widget is self.get_widget('existing-file-token'):
71
                if not hasvalue:
72
                    continue
73
                widget.value = get_session().add_tempfile(self.value)
74
            r += widget.render()
75
        return r.getvalue()
76

    
77
    def _parse(self, request):
78
        session = get_session()
79
        if self.get('file') or self.get('orexisting') or self.get('strongbox'):
80
            if self.get('strongbox'):
81
                sffile = StrongboxItem.get(self.get('strongbox'))
82
                if sffile.user_id == get_request().user.id:
83
                    self.value = Upload(os.path.basename(sffile.file.orig_filename), sffile.file.content_type)
84
                    self.value.fp = file(sffile.file.filename)
85
                    token = get_session().add_tempfile(self.value)
86
                    if not hasattr(get_request(), 'tempfiles'):
87
                        get_request().tempfiles = {}
88
                    get_request().tempfiles[self.name] = token
89
                    self.value = None
90
                    self.get_widget('file').clear_error()
91
            elif self.get('file'):
92
                self.value = self.get('file')
93
                token = get_session().add_tempfile(self.value)
94
                if not hasattr(get_request(), 'tempfiles'):
95
                    get_request().tempfiles = {}
96
                get_request().tempfiles[self.name] = token
97
                self.value = None
98
            else:
99
                token = self.get('existing-file-token')
100
                if not hasattr(get_request(), 'tempfiles'):
101
                    get_request().tempfiles = {}
102
                get_request().tempfiles[self.name] = token
103
                self.get_widget('file').clear_error()
104
        else:
105
            token = self.get('token')
106

    
107
        if session.tempfiles and session.tempfiles.has_key(token):
108
            self.token = token
109
            if not isinstance(self.value, PicklableUpload):
110
                self.value = PicklableUpload(session.tempfiles[token]['orig_filename'],
111
                    session.tempfiles[token]['content_type'],
112
                    session.tempfiles[token]['charset'])
113
                self.value.fp = tempfile.TemporaryFile()
114
                dirname = os.path.join(get_publisher().app_dir, 'tempfiles')
115
                filename = os.path.join(dirname, token)
116
                self.value.fp.write(open(filename).read())
117
            self.value.get_file_pointer().seek(0)
118

    
119
    def cleanup(self):
120
        if self.token:
121
            dirname = os.path.join(get_publisher().app_dir, 'tempfiles')
122
            filename = os.path.join(dirname, self.token)
123
            if os.path.exists(filename):
124
                os.unlink(filename)
125

    
(14-14/26)