OOoDocument.py 23.2 KB
Newer Older
1
# -*- coding: utf-8 -*-
Bartek Górny's avatar
Bartek Górny committed
2 3 4
##############################################################################
#
# Copyright (c) 2002-2006 Nexedi SARL and Contributors. All Rights Reserved.
5
# Copyright (c) 2006-2007 Nexedi SA and Contributors. All Rights Reserved.
Bartek Górny's avatar
Bartek Górny committed
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
#
# WARNING: This program as such is intended to be used by professional
# programmers who take the whole responsability of assessing all potential
# consequences resulting from its eventual inadequacies and bugs
# End users who are looking for a ready-to-use solution with commercial
# garantees and support are strongly adviced to contract a Free Software
# Service Company
#
# This program is Free Software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, 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., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
#
##############################################################################

30
import xmlrpclib, base64, re, zipfile, cStringIO
31
from warnings import warn
32
from xmlrpclib import Fault
33 34
from xmlrpclib import Transport
from xmlrpclib import SafeTransport
Bartek Górny's avatar
Bartek Górny committed
35
from AccessControl import ClassSecurityInfo
36
from AccessControl import Unauthorized
Bartek Górny's avatar
Bartek Górny committed
37
from OFS.Image import Pdata
38
from OFS.Image import File as OFSFile
39 40 41 42
try:
    from OFS.content_types import guess_content_type
except ImportError:
    from zope.contenttype import guess_content_type
43 44
from Products.CMFCore.utils import getToolByName, _setCacheHeaders,\
    _ViewEmulator
45
from Products.ERP5Type import Permissions, PropertySheet, Constraint
Bartek Górny's avatar
Bartek Górny committed
46
from Products.ERP5Type.Cache import CachingMethod
47
from Products.ERP5Type.UnrestrictedMethod import UnrestrictedMethod
48
from Products.ERP5.Document.File import File
49
from Products.ERP5.Document.Document import PermanentURLMixIn
50 51 52
from Products.ERP5.Document.Document import ConversionCacheMixin
from Products.ERP5.Document.Document import ConversionError
from Products.ERP5.Document.Document import NotConvertedError
53
from zLOG import LOG, ERROR
54

Bartek Górny's avatar
Bartek Górny committed
55 56 57
enc=base64.encodestring
dec=base64.decodestring

58
_MARKER = []
59
STANDARD_IMAGE_FORMAT_LIST = ('png', 'jpg', 'gif', 'tiff', )
60

61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
class TimeoutTransport(SafeTransport):
  """A xmlrpc transport with configurable timeout.
  """
  def __init__(self, timeout=None, scheme='http'):
    self._timeout = timeout
    self._scheme = scheme

  def send_content(self, connection, request_body):
    connection.putheader("Content-Type", "text/xml")
    connection.putheader("Content-Length", str(len(request_body)))
    connection.endheaders()
    if self._timeout:
      connection._conn.sock.settimeout(self._timeout)
    if request_body:
      connection.send(request_body)

  def make_connection(self, h):
    if self._scheme == 'http':
      return Transport.make_connection(self, h)
    return SafeTransport.make_connection(self, h)


83
class OOoDocument(PermanentURLMixIn, File, ConversionCacheMixin):
Bartek Górny's avatar
Bartek Górny committed
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
  """
    A file document able to convert OOo compatible files to
    any OOo supported format, to capture metadata and to
    update metadata in OOo documents.

    This class can be used:

    - to create an OOo document database with powerful indexing (r/o)
      and metadata handling (r/w) features (ex. change title in ERP5 ->
      title is changed in OOo document)

    - to massively convert MS Office documents to OOo format

    - to easily keep snapshots (in PDF and/or OOo format) of OOo documents
      generated from OOo templates

    This class may be used in the future:

    - to create editable OOo templates (ex. by adding tags in WYSIWYG mode
      and using tags to make document dynamic - ask kevin for more info)

    - to automatically sign / encrypt OOo documents based on user

    - to automatically sign / encrypt PDF generated from OOo documents based on user

    This class should not be used:

    - to store files in formats not supported by OOo

    - to stored pure images (use Image for that)

    - as a general file conversion system (use portal_transforms for that)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
116 117 118

    TODO:
    - better permissions
Bartek Górny's avatar
Bartek Górny committed
119 120 121 122 123 124 125
  """
  # CMF Type Definition
  meta_type = 'ERP5 OOo Document'
  portal_type = 'OOo Document'
  isPortalContent = 1
  isRADContent = 1

126
  searchable_property_list = ('asText', 'title', 'description', 'id', 'reference',
127 128
                              'version', 'short_title',
                              'subject', 'source_reference', 'source_project_title',)
Bartek Górny's avatar
Bartek Górny committed
129 130 131 132 133 134 135

  # Declarative security
  security = ClassSecurityInfo()
  security.declareObjectProtected(Permissions.AccessContentsInformation)

  # Default Properties
  property_sheets = ( PropertySheet.Base
136 137
                    , PropertySheet.XMLObject
                    , PropertySheet.Reference
Bartek Górny's avatar
Bartek Górny committed
138 139 140
                    , PropertySheet.CategoryCore
                    , PropertySheet.DublinCore
                    , PropertySheet.Version
141
                    , PropertySheet.Document
142 143 144 145
                    , PropertySheet.Snapshot
                    , PropertySheet.ExternalDocument
                    , PropertySheet.Url
                    , PropertySheet.Periodicity
146
                    , PropertySheet.SortIndex
Bartek Górny's avatar
Bartek Górny committed
147 148
                    )

149
  # regular expressions for stripping xml from ODF documents
150 151
  rx_strip = re.compile('<[^>]*?>', re.DOTALL|re.MULTILINE)
  rx_compr = re.compile('\s+')
152

153 154
  security.declareProtected(Permissions.AccessContentsInformation,
                            'isSupportBaseDataConversion')
155 156 157 158 159 160
  def isSupportBaseDataConversion(self):
    """
    OOoDocument is needed to conversion to base format.
    """
    return True

161 162 163 164
  def _setFile(self, data, precondition=None):
    File._setFile(self, data, precondition=precondition)
    if self.hasBaseData():
      # This is a hack - XXX - new accessor needed to delete properties
Yusei Tahara's avatar
Yusei Tahara committed
165 166 167 168
      try:
        delattr(self, 'base_data')
      except AttributeError:
        pass
169

170
  security.declareProtected(Permissions.View, 'index_html')
171
  def index_html(self, REQUEST, RESPONSE, format=None, display=None, **kw):
172
    """
173 174 175
      Default renderer with conversion support. Format is
      a string. The list of available formats can be obtained
      by calling getTargetFormatItemList.
176
    """
177
    # Accelerate rendering in Web mode
178
    _setCacheHeaders(_ViewEmulator().__of__(self), {'format' : format})
179 180 181 182 183 184

    # Verify that the format is acceptable (from permission point of view)
    method = self._getTypeBasedMethod('checkConversionFormatPermission', 
        fallback_script_id = 'Document_checkConversionFormatPermission')
    if not method(format=format):
      raise Unauthorized("OOoDocument: user does not have enough permission to access document"
185
                         " in %s format" % (format or 'original'))
186

187
    # Return the original file by default
188 189 190 191
    if self.getSourceReference() is not None:
      filename = self.getSourceReference()
    else:
      filename = self.getId()
192
    if format is None:
193 194
      RESPONSE.setHeader('Content-Disposition',
                         'attachment; filename="%s"' % filename)
195 196 197
      return File.index_html(self, REQUEST, RESPONSE)
    # Make sure file is converted to base format
    if not self.hasBaseData():
198
      raise NotConvertedError
199
    # Else try to convert the document and return it
200
    mime, result = self.convert(format=format, display=display, **kw)
201
    converted_filename = '%s.%s'%(filename.split('.')[0],  format)
202 203
    if not mime:
      mime = getToolByName(self, 'mimetypes_registry').lookupExtension('name.%s' % format)
Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
204 205 206 207
    RESPONSE.setHeader('Content-Length', len(result))
    RESPONSE.setHeader('Content-Type', mime)
    RESPONSE.setHeader('Accept-Ranges', 'bytes')
    if format not in STANDARD_IMAGE_FORMAT_LIST:
208 209
      RESPONSE.setHeader('Content-Disposition',
                         'attachment; filename="%s"' % converted_filename)
Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
210
    return result
211

212
  # Format conversion implementation
213
  def _getServerCoordinate(self):
Bartek Górny's avatar
Bartek Górny committed
214
    """
215 216
      Returns the oood conversion server coordinates
      as defined in preferences.
Bartek Górny's avatar
Bartek Górny committed
217
    """
218 219 220
    preference_tool = getToolByName(self, 'portal_preferences')
    address = preference_tool.getPreferredOoodocServerAddress()
    port = preference_tool.getPreferredOoodocServerPortNumber()
221
    if address in ('', None) or port in ('', None) :
222
      raise ConversionError('OOoDocument: can not proceed with conversion:'
223
            ' conversion server host and port is not defined in preferences')
224
    return address, port
Bartek Górny's avatar
Bartek Górny committed
225 226 227

  def _mkProxy(self):
    """
228
      Create an XML-RPC proxy to access the conversion server.
Bartek Górny's avatar
Bartek Górny committed
229
    """
230 231 232 233
    server_proxy = xmlrpclib.ServerProxy(
             'http://%s:%d' % self._getServerCoordinate(),
             allow_none=True,
             transport=TimeoutTransport(timeout=360, scheme='http'))
234
    return server_proxy
Bartek Górny's avatar
Bartek Górny committed
235

236 237
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getTargetFormatItemList')
Bartek Górny's avatar
Bartek Górny committed
238 239 240 241 242
  def getTargetFormatItemList(self):
    """
      Returns a list of acceptable formats for conversion
      in the form of tuples (for listfield in ERP5Form)

243 244
      NOTE: it is the responsability of the conversion server
      to provide an extensive list of conversion formats.
Bartek Górny's avatar
Bartek Górny committed
245
    """
246
    if not self.hasBaseData():
247
      raise NotConvertedError
248

249
    def cached_getTargetFormatItemList(content_type):
250
      server_proxy = self._mkProxy()
251
      try:
252 253 254 255 256 257 258 259 260 261
        allowed_target_item_list = server_proxy.getAllowedTargetItemList(
                                                      content_type)
        try:
          response_code, response_dict, response_message = \
                                             allowed_target_item_list
        except ValueError:
          # Compatibility with older oood where getAllowedTargetItemList only
          # returned response_dict
          response_code, response_dict, response_message = \
                         200, dict(response_data=allowed_target_item_list), ''
262

263 264 265 266 267
        if response_code == 200:
          allowed = response_dict['response_data']
        else:
          # This is very temporary code - XXX needs to be changed
          # so that the system can retry
268
          raise ConversionError("OOoDocument: can not get list of allowed acceptable"
269 270
                                " formats for conversion: %s (%s)" % (
                                      response_code, response_message))
271

272 273 274 275
      except Fault, f:
        allowed = server_proxy.getAllowedTargets(content_type)
        warn('Your oood version is too old, using old method '
            'getAllowedTargets instead of getAllowedTargetList',
276
             DeprecationWarning)
277 278 279

      # tuple order is reversed to be compatible with ERP5 Form
      return [(y, x) for x, y in allowed]
Bartek Górny's avatar
Bartek Górny committed
280

281
    # Cache valid format list
282 283 284 285
    cached_getTargetFormatItemList = CachingMethod(
                                cached_getTargetFormatItemList,
                                id="OOoDocument_getTargetFormatItemList",
                                cache_factory='erp5_ui_medium')
Bartek Górny's avatar
Bartek Górny committed
286

287 288
    return cached_getTargetFormatItemList(self.getBaseContentType())

289 290
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getTargetFormatTitleList')
291
  def getTargetFormatTitleList(self):
Bartek Górny's avatar
Bartek Górny committed
292 293 294 295 296
    """
      Returns a list of acceptable formats for conversion
    """
    return map(lambda x: x[0], self.getTargetFormatItemList())

297 298
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getTargetFormatList')
299
  def getTargetFormatList(self):
Bartek Górny's avatar
Bartek Górny committed
300
    """
301
      Returns a list of acceptable formats for conversion
Bartek Górny's avatar
Bartek Górny committed
302
    """
303
    return map(lambda x: x[1], self.getTargetFormatItemList())
Bartek Górny's avatar
Bartek Górny committed
304

305 306
  security.declareProtected(Permissions.ModifyPortalContent,
                            'isTargetFormatAllowed')
307
  def isTargetFormatAllowed(self, format):
308
    """
309 310 311 312 313 314 315 316 317 318
      Checks if the current document can be converted
      into the specified target format.
    """
    return format in self.getTargetFormatList()

  security.declarePrivate('_convert')
  def _convert(self, format):
    """
      Communicates with server to convert a file 
    """
319
    if not self.hasBaseData():
320
      raise NotConvertedError
321 322 323
    if format == 'text-content':
      # Extract text from the ODF file
      cs = cStringIO.StringIO()
324
      cs.write(str(self.getBaseData()))
325 326 327 328 329 330
      z = zipfile.ZipFile(cs)
      s = z.read('content.xml')
      s = self.rx_strip.sub(" ", s) # strip xml
      s = self.rx_compr.sub(" ", s) # compress multiple spaces
      cs.close()
      z.close()
331
      return 'text/plain', s
332
    server_proxy = self._mkProxy()
333
    orig_format = self.getBaseContentType()
334
    generate_result = server_proxy.run_generate(self.getId(),
335
                                       enc(str(self.getBaseData())),
336
                                       None,
337 338
                                       format,
                                       orig_format)
339 340 341 342 343 344
    try:
      response_code, response_dict, response_message = generate_result
    except ValueError:
      # This is for backward compatibility with older oood version returning
      # only response_dict
      response_dict = generate_result
345

346
    # XXX: handle possible OOOd server failure
347
    return response_dict['mime'], Pdata(dec(response_dict['data']))
348

349
  # Conversion API
350
  security.declareProtected(Permissions.View, 'convert')
351
  def convert(self, format, display=None, **kw):
352 353 354 355
    """Convert the document to the given format.

    If a conversion is already stored for this format, it is returned
    directly, otherwise the conversion is stored for the next time.
Bartek Górny's avatar
Bartek Górny committed
356
    """
357 358
    #XXX if document is empty, stop to try to convert.
    #XXX but I don't know what is a appropriate mime-type.(Yusei)
359
    if self.get_size() == 0:
360
      return 'text/plain', ''
361

362 363
    # Make sure we can support html and pdf by default
    is_html = 0
364
    requires_pdf_first = 0
365
    original_format = format
366
    if format == 'base-data':
367 368
      if not self.hasBaseData():
        raise NotConvertedError
369
      return self.getBaseContentType(), str(self.getBaseData())
370
    if format == 'pdf':
371 372
      format_list = [x for x in self.getTargetFormatList()
                                          if x.endswith('pdf')]
373
      format = format_list[0]
374
    elif format in STANDARD_IMAGE_FORMAT_LIST:
375 376
      format_list = [x for x in self.getTargetFormatList()
                                          if x.endswith(format)]
377 378 379 380 381 382 383 384
      if len(format_list):
        format = format_list[0]
      else:
        # We must fist make a PDF
        requires_pdf_first = 1
        format_list = [x for x in self.getTargetFormatList()
                                          if x.endswith('pdf')]
        format = format_list[0]
385
    elif format == 'html':
386 387
      format_list = [x for x in self.getTargetFormatList()
                              if x.startswith('html') or x.endswith('html')]
388 389
      format = format_list[0]
      is_html = 1
390 391
    elif format in ('txt', 'text', 'text-content'):
      format_list = self.getTargetFormatList()
392 393 394 395
      # if possible, we try to get utf8 text. ('enc.txt' will encode to utf8)
      if 'enc.txt' in format_list:
        format = 'enc.txt'
      elif format not in format_list:
396 397 398 399 400 401 402
        #Text conversion is not supported by oood, do it in other way
        if not self.hasConversion(format=original_format):
          #Do real conversion for text
          mime, data = self._convert(format='text-content')
          self.setConversion(data, mime, format=original_format)
          return mime, data
        return self.getConversion(format=original_format)
403 404
    # Raise an error if the format is not supported
    if not self.isTargetFormatAllowed(format):
405
      raise ConversionError("OOoDocument: target format %s is not supported" % format)
406 407
    # Check if we have already a base conversion
    if not self.hasBaseData():
408
      raise NotConvertedError
409
    # Return converted file
410 411 412 413 414 415 416 417 418
    if requires_pdf_first:
      # We should use original_format whenever we wish to
      # display an image version of a document which needs to go
      # through PDF
      if display is None:
        has_format = self.hasConversion(format=original_format)
      else:
        has_format = self.hasConversion(format=original_format, display=display)
    elif display is None or original_format not in STANDARD_IMAGE_FORMAT_LIST:
419
      has_format = self.hasConversion(format=original_format)
420
    else:
421
      has_format = self.hasConversion(format=original_format, display=display)
422
    if not has_format:
423 424 425 426 427 428
      # Do real conversion
      mime, data = self._convert(format)
      if is_html:
        # Extra processing required since
        # we receive a zip file
        cs = cStringIO.StringIO()
429
        cs.write(str(data))
Jean-Paul Smets's avatar
Jean-Paul Smets committed
430
        z = zipfile.ZipFile(cs) # A disk file would be more RAM efficient
431 432 433
        for f in z.infolist():
          fn = f.filename
          if fn.endswith('html'):
434 435 436
            if self.getPortalType() == 'Presentation'\
                  and not (fn.find('impr') >= 0):
              continue
437 438 439
            data = z.read(fn)
            break
        mime = 'text/html'
440
        self._populateConversionCacheWithHTML(zip_file=z) # Maybe some parts should be asynchronous for
441
                                         # better usability
442 443
        z.close()
        cs.close()
444 445
      if (display is None or original_format not in STANDARD_IMAGE_FORMAT_LIST) \
        and not requires_pdf_first:
446
        self.setConversion(data, mime, format=original_format)
447
      else:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
448
        temp_image = self.portal_contributions.newContent(
449 450 451
                                       portal_type='Image',
                                       temp_object=1)
        temp_image._setData(data)
452
        mime, data = temp_image.convert(original_format, display=display)
453 454 455 456 457 458 459
        if requires_pdf_first:
          if display is None:
            self.setConversion(data, mime, format=original_format)
          else:
            self.setConversion(data, mime, format=original_format, display=display)
        else:
          if display is None:
460
            self.setConversion(data, mime, format=original_format)
461
          else:
462
            self.setConversion(data, mime, format=original_format, display=display)
463 464
    if requires_pdf_first:
      format = original_format
465
    if display is None or original_format not in STANDARD_IMAGE_FORMAT_LIST:
466
      return self.getConversion(format=original_format)
467
    else:
468
      return self.getConversion(format=original_format, display=display)
469

470 471 472 473 474 475 476
  security.declareProtected(Permissions.View, 'asTextContent')
  def asTextContent(self):
    """
      Extract plain text from ooo docs by stripping the XML file.
      This is the simplest way, the most universal and it is compatible
      will all formats.
    """
477 478 479 480 481
    if not self.hasConversion(format='txt'):
      mime, data = self._convert(format='text-content')
      self.setConversion(data, mime, format='txt')
      return mime, data
    return self.getConversion(format='txt')
482

483
  security.declareProtected(Permissions.ModifyPortalContent,
484 485
                            '_populateConversionCacheWithHTML')
  def _populateConversionCacheWithHTML(self, zip_file=None):
486 487 488 489 490
    """
    Extract content from the ODF zip file and populate the document.
    Optional parameter zip_file prevents from converting content twice.
    """
    if zip_file is None:
491
      format_list = [x for x in self.getTargetFormatList()
492
                                if x.startswith('html') or x.endswith('html')]
493 494 495
      format = format_list[0]
      mime, data = self._convert(format)
      archive_file = cStringIO.StringIO()
496
      archive_file.write(str(data))
497 498 499 500 501 502
      zip_file = zipfile.ZipFile(archive_file)
      must_close = 1
    else:
      must_close = 0
    for f in zip_file.infolist():
      file_name = f.filename
503 504
      document = self.get(file_name, None)
      if document is not None:
505
        self.manage_delObjects([file_name]) # For compatibility with old implementation
506
      if file_name.endswith('html'):
507 508
        mime = 'text/html'
        data = zip_file.read(file_name)
509
      else:
510 511
        mime = guess_content_type(file_name)[0]
        data = Pdata(zip_file.read(file_name))
512
      self.setConversion(data, mime=mime, format='_embedded', file_name=file_name)
513 514 515 516
    if must_close:
      zip_file.close()
      archive_file.close()

517
  def _getExtensibleContent(self, request, name):
518
    try:
519
      mime, data = self.getConversion(format='_embedded', file_name=name)
520
      return OFSFile(name, name, data, content_type=mime).__of__(self.aq_parent)
521 522
    except KeyError:
      return PermanentURLMixIn._getExtensibleContent(self, request, name)
523

524
  # Base format implementation
525 526 527 528 529 530
  security.declareProtected(Permissions.AccessContentsInformation, 'hasBaseData')
  def hasBaseData(self):
    """
      OOo instances implement conversion to a base format. We should therefore
      use the default accessor.
    """
Jean-Paul Smets's avatar
Typo.  
Jean-Paul Smets committed
531
    return self._baseHasBaseData()
532

533 534
  security.declarePrivate('_convertToBaseFormat')
  def _convertToBaseFormat(self):
Bartek Górny's avatar
Bartek Górny committed
535
    """
536 537 538
      Converts the original document into ODF
      by invoking the conversion server. Store the result
      on the object. Update metadata information.
Bartek Górny's avatar
Bartek Górny committed
539
    """
540
    server_proxy = self._mkProxy()
541 542
    response_code, response_dict, response_message = server_proxy.run_convert(
                                      self.getSourceReference() or self.getId(),
543
                                      enc(str(self.getData())))
544 545 546 547 548 549 550 551
    if response_code == 200:
      # sucessfully converted document
      self._setBaseData(dec(response_dict['data']))
      metadata = response_dict['meta']
      self._base_metadata = metadata
      if metadata.get('MIMEType', None) is not None:
        self._setBaseContentType(metadata['MIMEType'])
    else:
552 553
      # Explicitly raise the exception!
      raise ConversionError(
554 555
                "OOoDocument: Error converting document to base format %s:%s:"
                                       % (response_code, response_message))
Bartek Górny's avatar
Bartek Górny committed
556

557 558
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getContentInformation')
559
  def getContentInformation(self):
Bartek Górny's avatar
Bartek Górny committed
560
    """
561 562
      Returns the metadata extracted by the conversion
      server.
Bartek Górny's avatar
Bartek Górny committed
563
    """
564
    return getattr(self, '_base_metadata', {})
Bartek Górny's avatar
Bartek Górny committed
565

566 567
  security.declareProtected(Permissions.ModifyPortalContent,
                            'updateBaseMetadata')
568
  def updateBaseMetadata(self, **kw):
Bartek Górny's avatar
Bartek Górny committed
569
    """
570 571 572
      Updates metadata information in the converted OOo document
      based on the values provided by the user. This is implemented
      through the invocation of the conversion server.
Bartek Górny's avatar
Bartek Górny committed
573
    """
574 575 576 577
    if not self.hasBaseData():
      raise NotConvertedError

    self.clearConversionCache()
578

579
    server_proxy = self._mkProxy()
580 581
    response_code, response_dict, response_message = \
          server_proxy.run_setmetadata(self.getId(),
582
                                       enc(str(self.getBaseData())),
583
                                       kw)
584 585 586
    if response_code == 200:
      # successful meta data extraction
      self._setBaseData(dec(response_dict['data']))
587
      self.updateFileMetadata() # record in workflow history # XXX must put appropriate comments.
588
    else:
589
      # Explicitly raise the exception!
590
      raise ConversionError("OOoDocument: error getting document metadata %s:%s"
591
                        % (response_code, response_message))