Signature.py 13.4 KB
Newer Older
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.
#          Danièle Vanbaelinghem <daniele@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
from Products.ERP5Type.Globals import PersistentMapping
31 32 33 34 35
from time import gmtime,strftime # for anchors
from SyncCode import SyncCode
from AccessControl import ClassSecurityInfo
from Products.CMFCore.utils import getToolByName
from Acquisition import Implicit, aq_base
36
from Products.ERP5Type.Accessor.Constant import PropertyGetter as ConstantGetter
37 38 39 40
from Products.ERP5Type.Core.Folder import Folder
from Products.ERP5Type.Base import Base
from Products.ERP5Type import Permissions
from Products.ERP5Type import PropertySheet
41
from Products.ERP5.Document import Document
42 43
from DateTime import DateTime
from zLOG import LOG, DEBUG, INFO
44 45 46
import cStringIO
from OFS.Image import Pdata
from OFS.Image import File
47 48 49
import md5
from base64 import b64encode, b64decode, b16encode, b16decode

50
class Signature(Folder, SyncCode, File):
51 52 53 54 55 56 57 58 59 60
  """
    status -- SENT, CONFLICT...
    md5_object -- An MD5 value of a given document
    #uid -- The UID of the document
    id -- the ID of the document
    gid -- the global id of the document
    rid -- the uid of the document on the remote database,
        only needed on the server.
    xml -- the xml of the object at the time where it was synchronized
  """
61 62
  isIndexable = ConstantGetter('isIndexable', value=False)
  # Make sure RAD generated accessors at the class level
63 64 65 66 67 68 69 70

  # Constructor
  def __init__(self,
               id=None,
               rid=None,
               status=None,
               xml_string=None,
               object=None):
71
    Folder.__init__(self, id)
72
    File.__init__(self, id, '', '')
73 74 75 76 77 78 79 80 81
    if object is not None:
      self.setPath(object.getPhysicalPath())
      self.setObjectId(object.getId())
    else:
      self.setPath(None)
    self.setId(id)
    self.setRid(rid)
    self.status = status
    self.setXML(xml_string)
82
    self.setPartialXML(None)
83 84 85 86 87 88 89
    self.action = None
    self.setTempXML(None)
    self.resetConflictList()
    self.md5_string = None
    self.force = 0
    self.setSubscriberXupdate(None)
    self.setPublisherXupdate(None)
90
    self.last_data_partial_xml = None
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

  def setStatus(self, status):
    """
      set the Status (see SyncCode for numbers)
    """
    self.status = status
    if status == self.SYNCHRONIZED:
      temp_xml = self.getTempXML()
      self.setForce(0)
      if temp_xml is not None:
        # This happens when we have sent the xml
        # and we just get the confirmation
        self.setXML(temp_xml)
      self.setTempXML(None)
      self.setPartialXML(None)
      self.setSubscriberXupdate(None)
      self.setPublisherXupdate(None)
      if len(self.getConflictList())>0:
        self.resetConflictList()
      # XXX This may be a problem, if the document is changed
      # during a synchronization
      self.setLastSynchronizationDate(DateTime())
      self.getParentValue().removeRemainingObjectPath(self.getPath())
    if status == self.NOT_SYNCHRONIZED:
      self.setTempXML(None)
      self.setPartialXML(None)
    elif status in (self.PUB_CONFLICT_MERGE, self.SENT):
      # We have a solution for the conflict, don't need to keep the list
      self.resetConflictList()

  def getStatus(self):
    """
      get the Status (see SyncCode for numbers)
    """
    return self.status

  def getPath(self):
    """
      get the force value (if we need to force update or not)
    """
    return getattr(self, 'path', None)

  def setPath(self, path):
    """
      set the force value (if we need to force update or not)
    """
    self.path = path

  def getForce(self):
    """
      get the force value (if we need to force update or not)
    """
    return self.force

  def setForce(self, force):
    """
      set the force value (if we need to force update or not)
    """
    self.force = force

  def getLastModificationDate(self):
    """
      get the last modfication date, so that we don't always
      check the xml
    """
    return getattr(self, 'modification_date', None)

  def setLastModificationDate(self,value):
    """
      set the last modfication date, so that we don't always
      check the xml
    """
    setattr(self, 'modification_date', value)

  def getLastSynchronizationDate(self):
    """
      get the last modfication date, so that we don't always
      check the xml
    """
    return getattr(self, 'synchronization_date', None)

  def setLastSynchronizationDate(self,value):
    """
      set the last modfication date, so that we don't always
      check the xml
    """
    setattr(self, 'synchronization_date', value)
178 179 180 181 182 183 184
  
  def hasXML(self):
    """
      return True if the xml is available
    """
    return bool(getattr(self, 'xml', None))
  
185 186 187 188
  def setXML(self, xml):
    """
      set the XML corresponding to the object
    """
189 190 191
    if xml is not None:
      # convert the string to Pdata if the big size
      file = cStringIO.StringIO(xml)
192
      self.xml, size = self.getParentValue()._read_data(file)
193 194
      self.setTempXML(None) # We make sure that the xml will not be erased
      self.setMD5(xml)
195 196
    else:
      self.xml = None
197

198
  def getXML(self, default=None):
199 200 201 202
    """
      get the XML corresponding to the object
    """
    #Never return empty string
203 204 205 206 207 208
    if self.hasXML():
      if isinstance(self.xml, Pdata):
        return str(self.xml)
      elif isinstance(self.xml, str):
        return self.xml
      else:
209
        raise ValueError, "the self.xml haven't good type"
210
    else:
211
      return default
212 213 214 215 216 217

  def hasTempXML(self):
    """
      Return true if the temp_xml is available
    """
    return bool(getattr(self, 'temp_xml', None))
218 219 220 221 222 223 224

  def setTempXML(self, xml):
    """
      This is the xml temporarily saved, it will
      be stored with setXML when we will receive
      the confirmation of synchronization
    """
225 226
    if xml is not None:
      file = cStringIO.StringIO(xml)
227
      self.temp_xml, size = self.getParentValue()._read_data(file)
228 229
    else:
      self.temp_xml = None
230

231
  def getTempXML(self, default=None):
232 233 234
    """
      get the temp xml
    """
235 236 237 238 239 240
    if self.hasTempXML():
      if isinstance(self.temp_xml, Pdata):
        return str(self.temp_xml)
      elif isinstance(self.temp_xml, str):
        return self.temp_xml
      else:
241
        raise ValueError, "the self.xml haven't good type"
242
    else:
243
      return default
244 245 246 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 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337

  def setSubscriberXupdate(self, xupdate):
    """
    set the full temp xupdate
    """
    self.subscriber_xupdate = xupdate

  def getSubscriberXupdate(self):
    """
    get the full temp xupdate
    """
    return self.subscriber_xupdate

  def setPublisherXupdate(self, xupdate):
    """
    set the full temp xupdate
    """
    self.publisher_xupdate = xupdate

  def getPublisherXupdate(self):
    """
    get the full temp xupdate
    """
    return self.publisher_xupdate

  def setMD5(self, xml):
    """
      set the MD5 object of this signature
    """
    self.md5_string = md5.new(xml).digest()

  def getMD5(self):
    """
      get the MD5 object of this signature
    """
    return self.md5_string

  def checkMD5(self, xml_string):
    """
    check if the given md5_object returns the same things as
    the one stored in this signature, this is very usefull
    if we want to know if an objects has changed or not
    Returns 1 if MD5 are equals, else it returns 0
    """
    return ((md5.new(xml_string).digest()) == self.getMD5())

  def setRid(self, rid):
    """
      set the rid
    """
    if isinstance(rid, unicode):
      rid = rid.encode('utf-8')
    self.rid = rid

  def getRid(self):
    """
      get the rid
    """
    return getattr(self, 'rid', None)

  def setId(self, id):
    """
      set the id
    """
    if isinstance(id, unicode):
      id = id.encode('utf-8')
    self.id = id

  def getId(self):
    """
      get the id
    """
    return self.id

  def getGid(self):
    """
      get the gid
    """
    return self.getId()

  def setObjectId(self, id):
    """
      set the id of the object associated to this signature
    """
    if isinstance(id, unicode):
      id = id.encode('utf-8')
    self.object_id = id

  def getObjectId(self):
    """
      get the id of the object associated to this signature
    """
    return getattr(self, 'object_id', None)

338 339 340 341 342 343
  def hasPartialXML(self):
    """
      Return true is the partial xml is available
    """
    return bool(getattr(self, 'partial_xml', None))

344 345 346 347 348
  def setPartialXML(self, xml):
    """
    Set the partial string we will have to
    deliver in the future
    """
349 350 351 352 353 354 355 356
    if xml is not None:
      # change encoding of xml to convert in file
      try:
        xml = xml.encode('utf-8')
      except UnicodeDecodeError:
        xml = xml.decode('utf-8').encode('ascii','xmlcharrefreplace')
      # convert the string to Pdata if the big size
      file = cStringIO.StringIO(xml)
357
      self.partial_xml, size = self.getParentValue()._read_data(file)
358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375
      if not isinstance(self.partial_xml, Pdata):
        self.partial_xml = Pdata(self.partial_xml)
      self.last_data_partial_xml = self.partial_xml.getLastPdata()
    else:
      self.partial_xml = None
      self.last_data_partial_xml = None

  def appendPartialXML(self, xml):
    """
    Append the partial string we will have to deliver in the future
    """
    if xml is not None:
      try:
        xml = xml.encode('utf-8')
      except UnicodeDecodeError:
        xml = xml.decode('utf-8').encode('ascii','xmlcharrefreplace')
      
      file = cStringIO.StringIO(xml)
376
      xml_append, size = self.getParentValue()._read_data(file)
377 378 379 380 381 382 383 384
      if not isinstance(xml_append, Pdata):
        xml_append = Pdata(xml_append)
      last_data = xml_append.getLastPdata()
      if self.last_data_partial_xml is not None:
        self.last_data_partial_xml.next = xml_append
      else:
        self.partial_xml = xml_append
      self.last_data_partial_xml = last_data
385 386 387 388 389 390 391
  
  def getFirstChunkPdata(self, size_lines):
    """
    """
    chunk = list()
    chunk.append(self.partial_xml.data)
    size = chunk[0].count('\n')
392 393 394

    current = self.partial_xml
    next = current.next
395
    while size < size_lines and next is not None:
396 397 398 399
      current = next
      size += current.data.count('\n')
      chunk.append(current.data)
      next = current.next
400 401 402 403
     
    if size == size_lines:
      self.partial_xml = next
    elif size > size_lines:
404
      overflow = size - size_lines
405
      data_list = chunk[-1].split('\n')
406
      chunk[-1] = '\n'.join(data_list[:-overflow])
407 408
      current.data = '\n'.join(data_list[-overflow:])
      self.partial_xml = current
409 410 411
 
    return ''.join(chunk)

412

413
  def getPartialXML(self, default=None):
414 415 416 417
    """
    Set the partial string we will have to
    deliver in the future
    """
418 419 420 421
    if self.hasPartialXML():
      if isinstance(self.partial_xml, Pdata):
        return str(self.partial_xml)
      else:
422
        raise ValueError, "the self.xml haven't good type"
423
    else:
424
      return default
425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481

  def getAction(self):
    """
    Return the actual action for a partial synchronization
    """
    return self.action

  def setAction(self, action):
    """
    Return the actual action for a partial synchronization
    """
    self.action = action

  def getConflictList(self):
    """
    Return the actual action for a partial synchronization
    """
    returned_conflict_list = []
    if len(self.conflict_list)>0:
      returned_conflict_list.extend(self.conflict_list)
    return returned_conflict_list

  def resetConflictList(self):
    """
    Return the actual action for a partial synchronization
    """
    self.conflict_list = PersistentMapping()

  def setConflictList(self, conflict_list):
    """
    Return the actual action for a partial synchronization
    """
    if conflict_list is None or conflict_list == []:
      self.resetConflictList()
    else:
      self.conflict_list = conflict_list

  def delConflict(self, conflict):
    """
    Return the actual action for a partial synchronization
    """
    conflict_list = []
    for c in self.getConflictList():
      #LOG('delConflict, c==conflict',0,c==aq_base(conflict))
      if c != aq_base(conflict):
        conflict_list += [c]
    if conflict_list != []:
      self.setConflictList(conflict_list)
    else:
      self.resetConflictList()

  def getObject(self):
    """
    Returns the object corresponding to this signature
    """
    return self.getParentValue().getObjectFromGid(self.getObjectId())