File: ODFFile.py

package info (click to toggle)
python-odf 1.3.4%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 6,356 kB
  • ctags: 1,902
  • sloc: python: 21,654; makefile: 352; sh: 10; xml: 2
file content (213 lines) | stat: -rw-r--r-- 7,402 bytes parent folder | download | duplicates (6)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
# -*- coding: utf-8 -*-
# Copyright (C) 2007-2008 Søren Roug, European Environment Agency
#
# This is free software.  You may redistribute it under the terms
# of the Apache license and the GNU General Public License Version
# 2 or at your option any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public
# License along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
#
# Contributor(s):
#

#Python imports
import zipfile
from odf.odf2xhtml import ODF2XHTML
from odf.namespaces import OFFICENS, TEXTNS, XLINKNS
from odf.opendocument import odmimetypes

#Zope imports
from OFS.Image import File, cookId
from Globals import InitializeClass
from Globals import DTMLFile
from AccessControl import ClassSecurityInfo
from AccessControl.Permissions import view_management_screens, view, change_images_and_files
try:
    from cStringIO import StringIO
except ImportError:
    from StringIO import StringIO

class ODF2XHTMLBody(ODF2XHTML):

    def rewritelink(self, imghref):
        imghref = imghref.replace("Pictures/","index_html?pict=")
        return imghref

manage_addODFFileForm=DTMLFile('dtml/odffileAdd', globals())

def manage_addODFFile(self, id='', file='',title='', precondition='', content_type='', conversion='embedded',
                   REQUEST=None):
    """Add a new File object.

    Creates a new File object 'id' with the contents of 'file'"""

    id = str(id)
    title = str(title)
    conversion = str(conversion)
    content_type = str(content_type)
    precondition = str(precondition)

    suffix = ''
    newid, title = cookId(id, title, file)
    if id == '' and newid[-4:-2]== '.o' and newid[-2] in ['d','t']:
        id = newid[:-4]
        suffix = id[-3:]
    else:
        id = newid
    self = self.this()

    # First, we create the file without data:
    self._setObject(id, ODFFile(id, title, '', suffix, content_type, precondition, conversion))

    # Now we "upload" the data.  By doing this in two steps, we
    # can use a database trick to make the upload more efficient.
    if file:
        self._getOb(id).manage_upload(file)
    if content_type:
        self._getOb(id).content_type = content_type

    if REQUEST is not None:
        REQUEST['RESPONSE'].redirect(self.absolute_url()+'/manage_main')


class ODFFile(File):
    """ ODFFile class """

    meta_type = "OpenDocument File"
#   icon = 'misc_/ODFFile/presentation'

#   manage_options = (
#       (File.manage_options[5],
#        File.manage_options[3],
#        File.manage_options[6],)
#   )

    security = ClassSecurityInfo()

    def __init__(self, id, title, file, suffix, content_type='', precondition='', conversion='embedded'):
        """ constructor """
        self.xhtml = "<h1>Nothing uploaded</h1>"
        self.conversion = conversion
        self.suffix = suffix
        self._pictures = {}
        File.__dict__['__init__'](self, id, title, file, content_type, precondition)


    ###########################
    #         ZMI FORMS       #
    ###########################



    security.declareProtected(view, 'index_html')

    def index_html(self, REQUEST=None, RESPONSE=None):
        """ Show the HTML part """
        if REQUEST.has_key('pict'):
            return self.Pictures(REQUEST['pict'], REQUEST, RESPONSE)

        rsp = []
        if self.conversion == 'embedded':
             rsp.append(self.standard_html_header(self, REQUEST, RESPONSE))
        rsp.append(self.xhtml)
        if self.conversion == 'embedded':
             rsp.append(self.standard_html_footer(self, REQUEST, RESPONSE))
        return(''.join(rsp))

    manage_editForm = DTMLFile('dtml/odfEdit',globals())
    manage_editForm._setName('manage_editForm')
    manage=manage_main = manage_editForm
    manage_uploadForm = manage_editForm

    def manage_edit(self, title, content_type, precondition='',
                    filedata=None, conversion='none', REQUEST=None):
        """
        Changes the title and content type attributes of the OpenDocument File.
        """
        ODFFile.inheritedAttribute('manage_edit')(self, title, content_type, precondition, filedata)
        conversion = str(conversion)
        if self.conversion != conversion:
            self.conversion = conversion
            self.update_xhtml()

        if REQUEST:
            message="Saved changes."
            return self.manage_main(self,REQUEST,manage_tabs_message=message)

    security.declareProtected(change_images_and_files, 'uploadFile')
    def uploadFile(self, file):
        """ asociates a file to the ODFFile object """
        data, size = self._read_data(file)
        content_type = self._get_content_type(file, data, self.__name__, 'undefined')
        self.update_data(data, content_type, size)
        self._p_changed = 1

    security.declareProtected(view, 'download')
    def download(self, REQUEST, RESPONSE):
        """ set for download asociated file """
        self.REQUEST.RESPONSE.setHeader('Content-Type', self.content_type)
        self.REQUEST.RESPONSE.setHeader('Content-Length', self.size)
        self.REQUEST.RESPONSE.setHeader('Content-Disposition', 'attachment;filename="' + self.id() + self.suffix + '"')
        return ODFFile.inheritedAttribute('index_html')(self, REQUEST, RESPONSE)

    security.declareProtected(view, 'download')
    def picture_list(self, REQUEST, RESPONSE):
        """ Show list of pictures """
        return "\n".join(self._pictures.keys())

    security.declareProtected(view, 'download')
    def Pictures(self, pict, REQUEST, RESPONSE):
        """ set for download asociated file """
        suffices = {
         'wmf':'image/x-wmf',
         'png':'image/png',
         'gif':'image/gif',
         'jpg':'image/jpeg',
         'jpeg':'image/jpeg'
         }

        suffix = pict[pict.rfind(".")+1:]
        ct = suffices.get(suffix,'application/octet-stream')
        self.REQUEST.RESPONSE.setHeader('Content-Type', ct)
        return self._pictures[pict]

    def _save_pictures(self, fd):
        self._pictures = {}
        z = zipfile.ZipFile(fd)
        for zinfo in z.infolist():
            if zinfo.filename[0:9] == 'Pictures/':
                pictname = zinfo.filename[9:]
                self._pictures[pictname] = z.read(zinfo.filename)
        z.close()

    # private
    update_xhtml__roles__=()
    def update_xhtml(self):
        if self.size == 0:
            return
        if self.conversion == 'embedded':
            odhandler = ODF2XHTMLBody(embedable=True)
        else:
            odhandler = ODF2XHTMLBody(embedable=False)
        fd = StringIO(str(self.data))
        self._save_pictures(fd)
        fd.seek(0)
        self.xhtml = odhandler.odf2xhtml(fd).encode('us-ascii','xmlcharrefreplace')
        self.title = odhandler.title

    update_data__roles__=()
    def update_data(self, data, content_type=None, size=None):
        File.__dict__['update_data'](self, data, content_type, size)
        suffix = odmimetypes.get(content_type)
        if suffix:
            self.suffix = suffix
        self.update_xhtml()

InitializeClass(ODFFile)