cached_convertable.py 8.37 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)

47 48 49 50 51 52 53 54 55 56 57 58 59 60
def hashPdataObject(data):
  """Pdata objects are iterable, use this feature strongly
  to minimize memory footprint.
  """
  md5_hash = md5.new()
  next = chunk = data.next
  if next is None:
    md5_hash.update(data.data)
  while next is not None:
    chunk = next
    md5_hash.update(chunk)
    next = data.next
  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 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
    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)

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

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

  security.declareProtected(Permissions.ModifyPortalContent, 'setConversion')
123
  def setConversion(self, data, mime=None, date=None, **kw):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
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
    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)
    elif isinstance(data, OFSImage):
      cached_value = data
      conversion_md5 = md5.new(str(data.data)).hexdigest()
      size = len(data.data)
    else:
      cached_value = data
      conversion_md5 = md5.new(cached_value).hexdigest()
      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}
Jean-Paul Smets's avatar
Jean-Paul Smets committed
151 152 153
    if self.isTempObject():
      if getattr(aq_base(self), 'temp_conversion_data', None) is None:
        self.temp_conversion_data = {}
154
      self.temp_conversion_data[cache_id] = stored_data_dict
Jean-Paul Smets's avatar
Jean-Paul Smets committed
155 156 157
      return
    cache_factory = self._getCacheFactory()
    cache_duration = cache_factory.cache_duration
158 159 160 161 162 163 164 165 166 167
    # 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
168 169
    """
    """
170
    cache_id = self._getCacheKey(**kw)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
171 172
    if self.isTempObject():
      return getattr(aq_base(self), 'temp_conversion_data', {})[cache_id]
173 174 175 176 177 178 179
    # 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
180
    for cache_plugin in self._getCacheFactory().getCachePluginList():
181 182
      cache_entry = cache_plugin.get(cache_id, DEFAULT_CACHE_SCOPE)
      if cache_entry is not None:
183 184 185 186
        data_dict = cache_entry.getValue()
        if data_dict:
          content_md5 = data_dict['content_md5']
          if content_md5 != self.getContentMd5():
187
            raise KeyError, 'Conversion cache key is compromised for %r' % cache_id
188 189 190 191
          # 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
192 193
    raise KeyError, 'Conversion cache key does not exists for %r' % cache_id

194 195 196 197 198 199 200
  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
201 202 203 204 205
  security.declareProtected(Permissions.View, 'getConversionSize')
  def getConversionSize(self, **kw):
    """
    """
    try:
206
      return self._getConversionDataDict(**kw)['size']
Jean-Paul Smets's avatar
Jean-Paul Smets committed
207
    except KeyError:
208
      # If conversion doesn't exists return 0
Jean-Paul Smets's avatar
Jean-Paul Smets committed
209 210
      return 0

211 212 213 214 215 216 217 218 219
  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
220
    """
221
    return self._getConversionDataDict(**kw)['conversion_md5']
Jean-Paul Smets's avatar
Jean-Paul Smets committed
222 223 224 225 226

  security.declareProtected(Permissions.ModifyPortalContent, 'updateContentMd5')
  def updateContentMd5(self):
    """Update md5 checksum from the original file
    """
227
    mime, data = self.convert(None)
228
    if data is not None:
229 230 231 232
      if isinstance(data, Pdata):
        self._setContentMd5(hashPdataObject(aq_base(data)))
      else:
        self._setContentMd5(md5.new(data).hexdigest()) # Reindex is useless
233 234
    else:
      self._setContentMd5(None)