cached_convertable.py 10.5 KB
Newer Older
Jean-Paul Smets's avatar
Jean-Paul Smets committed
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
# -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (c) 2009 Nexedi SA and Contributors. All Rights Reserved.
#                    Jean-Paul Smets-Solanes <jp@nexedi.com>
#
# 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 31 32 33
try:
  from hashlib import md5 as md5_new
except ImportError:
  from md5 import new as md5_new
Jean-Paul Smets's avatar
Jean-Paul Smets committed
34
import string
Jean-Paul Smets's avatar
Jean-Paul Smets committed
35

Jean-Paul Smets's avatar
Jean-Paul Smets committed
36
from Acquisition import aq_base
Jean-Paul Smets's avatar
Jean-Paul Smets committed
37 38
from AccessControl import ClassSecurityInfo
from Products.ERP5Type import Permissions
Jean-Paul Smets's avatar
Jean-Paul Smets committed
39 40
from Products.CMFCore.utils import getToolByName
from Products.ERP5Type.Cache import DEFAULT_CACHE_SCOPE
41 42 43
from Products.ERP5Type.TransactionalVariable import getTransactionalVariable
from OFS.Image import Pdata, Image as OFSImage
from DateTime import DateTime
Jean-Paul Smets's avatar
Jean-Paul Smets committed
44

45 46 47 48 49
def makeSortedTuple(kw):
  items = kw.items()
  items.sort()
  return tuple(items)

Nicolas Dumazet's avatar
Nicolas Dumazet committed
50
def hashPdataObject(pdata_object):
51 52 53
  """Pdata objects are iterable, use this feature strongly
  to minimize memory footprint.
  """
54
  md5_hash = md5_new()
Nicolas Dumazet's avatar
Nicolas Dumazet committed
55
  next = pdata_object
56
  while next is not None:
Nicolas Dumazet's avatar
Nicolas Dumazet committed
57 58
    md5_hash.update(next.data)
    next = next.next
59 60
  return md5_hash.hexdigest()

Jean-Paul Smets's avatar
Jean-Paul Smets committed
61 62 63 64
class CachedConvertableMixin:
  """
  This class provides a generic implementation of IConvertable.

Ivan Tyagov's avatar
Ivan Tyagov committed
65
    This class provides a generic API to store using portal_caches plugin structure
Jean-Paul Smets's avatar
Jean-Paul Smets committed
66 67 68 69 70 71 72 73 74 75 76 77 78 79
    various converted versions of a file or of a string.

    Versions are stored in dictionaries; the class stores also
    generation time of every format and its mime-type string.
    Format can be a string or a tuple (e.g. format, resolution).
  """

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

  def _getCacheFactory(self):
    """
    """
80 81
    if self.getOriginalDocument() is None:
      return None
Jean-Paul Smets's avatar
Jean-Paul Smets committed
82 83 84 85 86 87 88 89 90 91 92 93
    cache_tool = getToolByName(self, 'portal_caches')
    preference_tool = getToolByName(self, 'portal_preferences')
    cache_factory_name = preference_tool.getPreferredConversionCacheFactory('document_cache_factory')
    cache_factory = cache_tool.getRamCacheRoot().get(cache_factory_name)
    #XXX This conditional statement should be remove as soon as
    #Broadcasting will be enable among all zeo clients.
    #Interaction which update portal_caches should interact with all nodes.
    if cache_factory is None and getattr(cache_tool, cache_factory_name, None) is not None:
      #ram_cache_root is not up to date for current node
      cache_tool.updateCache()
    return cache_tool.getRamCacheRoot().get(cache_factory_name)

94 95 96 97 98
  security.declareProtected(Permissions.AccessContentsInformation,
                                                             'generateCacheId')
  def generateCacheId(self, **kw):
    """
    """
99
    return self._getCacheKey(**kw)
100

101
  def _getCacheKey(self, **kw):
102 103 104 105 106 107 108 109
    """
    Returns the key to use for the cache entries. For now,
    use the object uid. 

    TODO: XXX-JPS use instance in the future
    http://pypi.python.org/pypi/uuid/ to generate
    a uuid stored as private property.
    """
110 111 112 113
    format_cache_id = str(makeSortedTuple(kw)).\
                             translate(string.maketrans('', ''), '[]()<>\'", ')
    return '%s:%s:%s' % (aq_base(self).getUid(), self.getRevision(),
                         format_cache_id)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
114 115 116 117 118 119 120 121 122 123 124 125

  security.declareProtected(Permissions.View, 'hasConversion')
  def hasConversion(self, **kw):
    """
    """
    try:
      self.getConversion(**kw)
      return True
    except KeyError:
      return False

  security.declareProtected(Permissions.ModifyPortalContent, 'setConversion')
126
  def setConversion(self, data, mime=None, date=None, **kw):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
127 128
    """
    """
129 130 131 132 133 134 135 136 137
    cache_id = self._getCacheKey(**kw)
    if data is None:
      cached_value = None
      conversion_md5 = None
      size = 0
    elif isinstance(data, Pdata):
      cached_value = aq_base(data)
      conversion_md5 = hashPdataObject(cached_value)
      size = len(cached_value)
Nicolas Delaby's avatar
Nicolas Delaby committed
138 139
    elif isinstance(data, OFSImage):
      cached_value = data
140
      conversion_md5 = md5_new(str(data.data)).hexdigest()
Nicolas Delaby's avatar
Nicolas Delaby committed
141
      size = len(data.data)
142 143
    else:
      cached_value = data
144
      conversion_md5 = md5_new(cached_value).hexdigest()
145 146 147 148 149 150 151 152 153
      size = len(cached_value)
    if date is None:
      date = DateTime()
    stored_data_dict = {'content_md5': self.getContentMd5(),
                        'conversion_md5': conversion_md5,
                        'mime': mime,
                        'data': cached_value,
                        'date': date,
                        'size': size}
154 155
    cache_factory = self._getCacheFactory()
    if cache_factory is None:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
156 157
      if getattr(aq_base(self), 'temp_conversion_data', None) is None:
        self.temp_conversion_data = {}
158
      self.temp_conversion_data[cache_id] = stored_data_dict
Jean-Paul Smets's avatar
Jean-Paul Smets committed
159 160
      return
    cache_duration = cache_factory.cache_duration
161 162
    # The purpose of this transaction cache is to help calls
    # to the same cache value in the same transaction.
163
    tv = getTransactionalVariable()
164 165 166 167 168 169 170
    tv[cache_id] = stored_data_dict
    for cache_plugin in cache_factory.getCachePluginList():
      cache_plugin.set(cache_id, DEFAULT_CACHE_SCOPE,
                       stored_data_dict, cache_duration=cache_duration)

  security.declareProtected(Permissions.View, '_getConversionDataDict')
  def _getConversionDataDict(self, **kw):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
171 172
    """
    """
173
    cache_id = self._getCacheKey(**kw)
174 175
    cache_factory = self._getCacheFactory()
    if cache_factory is None:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
176
      return getattr(aq_base(self), 'temp_conversion_data', {})[cache_id]
177 178
    # The purpose of this cache is to help calls to the same cache value
    # in the same transaction.
179
    tv = getTransactionalVariable()
180 181 182 183
    try:
      return tv[cache_id]
    except KeyError:
      pass
184
    for cache_plugin in cache_factory.getCachePluginList():
185 186
      cache_entry = cache_plugin.get(cache_id, DEFAULT_CACHE_SCOPE)
      if cache_entry is not None:
187 188
        data_dict = cache_entry.getValue()
        if data_dict:
Nicolas Delaby's avatar
Nicolas Delaby committed
189 190 191 192 193 194 195 196
          if isinstance(data_dict, tuple):
            # Backward compatibility: if cached value is a tuple
            # as it was before refactoring
            # http://svn.erp5.org?rev=35216&view=rev
            # raise a KeyError to invalidate this cache entry and force
            # calculation of a new conversion
            raise KeyError('Old cache conversion format,'\
                               'cache entry invalidated for key:%r' % cache_id)
197 198
          content_md5 = data_dict['content_md5']
          if content_md5 != self.getContentMd5():
199
            raise KeyError, 'Conversion cache key is compromised for %r' % cache_id
200 201 202 203
          # Fill transactional cache in order to help
          # querying real cache during same transaction
          tv[cache_id] = data_dict
          return data_dict
Jean-Paul Smets's avatar
Jean-Paul Smets committed
204 205
    raise KeyError, 'Conversion cache key does not exists for %r' % cache_id

206 207 208 209 210 211 212
  security.declareProtected(Permissions.View, 'getConversion')
  def getConversion(self, **kw):
    """
    """
    cached_dict = self._getConversionDataDict(**kw)
    return cached_dict['mime'], cached_dict['data']

Jean-Paul Smets's avatar
Jean-Paul Smets committed
213 214 215 216 217
  security.declareProtected(Permissions.View, 'getConversionSize')
  def getConversionSize(self, **kw):
    """
    """
    try:
218
      return self._getConversionDataDict(**kw)['size']
Jean-Paul Smets's avatar
Jean-Paul Smets committed
219
    except KeyError:
220
      # If conversion doesn't exists return 0
Jean-Paul Smets's avatar
Jean-Paul Smets committed
221 222
      return 0

223 224 225 226 227 228 229 230 231
  security.declareProtected(Permissions.View, 'getConversionDate')
  def getConversionDate(self, **kw):
    """
    """
    return self._getConversionDataDict(**kw)['date']

  security.declareProtected(Permissions.View, 'getConversionMd5')
  def getConversionMd5(self, **kw):
    """
Jean-Paul Smets's avatar
Jean-Paul Smets committed
232
    """
233
    return self._getConversionDataDict(**kw)['conversion_md5']
Jean-Paul Smets's avatar
Jean-Paul Smets committed
234 235 236 237 238

  security.declareProtected(Permissions.ModifyPortalContent, 'updateContentMd5')
  def updateContentMd5(self):
    """Update md5 checksum from the original file
    """
239
    mime, data = self.convert(None)
240
    if data is not None:
241 242 243
      if isinstance(data, Pdata):
        self._setContentMd5(hashPdataObject(aq_base(data)))
      else:
244
        self._setContentMd5(md5_new(data).hexdigest()) # Reindex is useless
245 246
    else:
      self._setContentMd5(None)
247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284

  security.declareProtected(Permissions.AccessContentsInformation,
                            'getTargetFormatItemList')
  def getTargetFormatItemList(self):
    """
      Returns a list of acceptable formats for conversion
      in the form of tuples (for listfield in ERP5Form)

      NOTE: it is the responsability of the respecive type based script
      to provide an extensive list of conversion formats.
    """
    method = self._getTypeBasedMethod('getTargetFormatItemList',
              fallback_script_id='Base_getTargetFormatItemList')
    return method()

  security.declareProtected(Permissions.AccessContentsInformation,
                            'getTargetFormatTitleList')
  def getTargetFormatTitleList(self):
    """
      Returns a list of acceptable formats for conversion
    """
    return map(lambda x: x[0], self.getTargetFormatItemList())

  security.declareProtected(Permissions.AccessContentsInformation,
                            'getTargetFormatList')
  def getTargetFormatList(self):
    """
      Returns a list of acceptable formats for conversion
    """
    return map(lambda x: x[1], self.getTargetFormatItemList())

  security.declareProtected(Permissions.ModifyPortalContent,
                            'isTargetFormatAllowed')
  def isTargetFormatAllowed(self, format):
    """
      Checks if the current document can be converted
      into the specified target format.
    """
285
    return format in self.getTargetFormatList()