cached_convertable.py 8.72 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 30
# -*- 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.
#
##############################################################################

import md5
Jean-Paul Smets's avatar
Jean-Paul Smets committed
31
import string
Jean-Paul Smets's avatar
Jean-Paul Smets committed
32

Jean-Paul Smets's avatar
Jean-Paul Smets committed
33
from Acquisition import aq_base
Jean-Paul Smets's avatar
Jean-Paul Smets committed
34 35
from AccessControl import ClassSecurityInfo
from Products.ERP5Type import Permissions
Jean-Paul Smets's avatar
Jean-Paul Smets committed
36 37
from Products.CMFCore.utils import getToolByName
from Products.ERP5Type.Cache import DEFAULT_CACHE_SCOPE
38 39 40
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
41

42 43 44 45 46
def makeSortedTuple(kw):
  items = kw.items()
  items.sort()
  return tuple(items)

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

Jean-Paul Smets's avatar
Jean-Paul Smets committed
58 59 60 61
class CachedConvertableMixin:
  """
  This class provides a generic implementation of IConvertable.

Ivan Tyagov's avatar
Ivan Tyagov committed
62
    This class provides a generic API to store using portal_caches plugin structure
Jean-Paul Smets's avatar
Jean-Paul Smets committed
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
    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()


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

  def _getCacheFactory(self):
    """
    """
    if self.isTempObject():
      return
    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)

95
  def _getCacheKey(self, **kw):
96 97 98 99 100 101 102 103
    """
    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.
    """
104 105 106 107
    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
108 109 110 111 112 113 114 115 116 117 118 119

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

  security.declareProtected(Permissions.ModifyPortalContent, 'setConversion')
120
  def setConversion(self, data, mime=None, date=None, **kw):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
121 122
    """
    """
123
    cache_id = self._getCacheKey(**kw)
124 125 126 127 128

    if isinstance(data, OFSImage):
      # data.data should be a Pdata object
      data = data.data

129 130 131 132 133 134 135 136 137 138 139 140
    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)
    else:
      cached_value = data
      conversion_md5 = md5.new(cached_value).hexdigest()
      size = len(cached_value)
141

142 143 144 145 146 147 148 149
    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}
Jean-Paul Smets's avatar
Jean-Paul Smets committed
150 151 152
    if self.isTempObject():
      if getattr(aq_base(self), 'temp_conversion_data', None) is None:
        self.temp_conversion_data = {}
153
      self.temp_conversion_data[cache_id] = stored_data_dict
Jean-Paul Smets's avatar
Jean-Paul Smets committed
154 155 156
      return
    cache_factory = self._getCacheFactory()
    cache_duration = cache_factory.cache_duration
157 158 159 160 161 162 163 164 165 166
    # The purpose of this transaction cache is to help calls
    # to the same cache value in the same transaction.
    tv = getTransactionalVariable(None)
    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
167 168
    """
    """
169
    cache_id = self._getCacheKey(**kw)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
170 171
    if self.isTempObject():
      return getattr(aq_base(self), 'temp_conversion_data', {})[cache_id]
172 173 174 175 176 177 178
    # The purpose of this cache is to help calls to the same cache value
    # in the same transaction.
    tv = getTransactionalVariable(None)
    try:
      return tv[cache_id]
    except KeyError:
      pass
Jean-Paul Smets's avatar
Jean-Paul Smets committed
179
    for cache_plugin in self._getCacheFactory().getCachePluginList():
180 181
      cache_entry = cache_plugin.get(cache_id, DEFAULT_CACHE_SCOPE)
      if cache_entry is not None:
182 183
        data_dict = cache_entry.getValue()
        if data_dict:
Nicolas Delaby's avatar
Nicolas Delaby committed
184 185 186 187 188 189 190 191
          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)
192 193
          content_md5 = data_dict['content_md5']
          if content_md5 != self.getContentMd5():
194
            raise KeyError, 'Conversion cache key is compromised for %r' % cache_id
195 196 197 198
          # 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
199 200
    raise KeyError, 'Conversion cache key does not exists for %r' % cache_id

201 202 203 204 205 206 207
  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
208 209 210 211 212
  security.declareProtected(Permissions.View, 'getConversionSize')
  def getConversionSize(self, **kw):
    """
    """
    try:
213
      return self._getConversionDataDict(**kw)['size']
Jean-Paul Smets's avatar
Jean-Paul Smets committed
214
    except KeyError:
215
      # If conversion doesn't exists return 0
Jean-Paul Smets's avatar
Jean-Paul Smets committed
216 217
      return 0

218 219 220 221 222 223 224 225 226
  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
227
    """
228
    return self._getConversionDataDict(**kw)['conversion_md5']
Jean-Paul Smets's avatar
Jean-Paul Smets committed
229 230 231 232 233

  security.declareProtected(Permissions.ModifyPortalContent, 'updateContentMd5')
  def updateContentMd5(self):
    """Update md5 checksum from the original file
    """
234
    mime, data = self.convert(None)
235
    if data is not None:
236 237 238 239
      if isinstance(data, Pdata):
        self._setContentMd5(hashPdataObject(aq_base(data)))
      else:
        self._setContentMd5(md5.new(data).hexdigest()) # Reindex is useless
240 241
    else:
      self._setContentMd5(None)