Subscription.py 35.6 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 31
##############################################################################
#
# Copyright (c) 2002 Nexedi SARL and Contributors. All Rights Reserved.
#          Sebastien Robin <seb@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.
#
##############################################################################

from Globals import PersistentMapping
from time import gmtime,strftime # for anchors
from SyncCode import SyncCode
32
from AccessControl import ClassSecurityInfo
Sebastien Robin's avatar
Sebastien Robin committed
33 34
from Products.CMFCore.utils import getToolByName
from Acquisition import Implicit, aq_base
Jean-Paul Smets's avatar
Jean-Paul Smets committed
35
from Products.ERP5Type.Core.Folder import Folder
36 37 38
from Products.ERP5Type.Base import Base
from Products.ERP5Type import Permissions
from Products.ERP5Type import PropertySheet
Sebastien Robin's avatar
Sebastien Robin committed
39
from DateTime import DateTime
Jean-Paul Smets's avatar
Jean-Paul Smets committed
40 41 42 43
from zLOG import LOG

import md5

44 45 46 47 48
try:
    from base64 import b64encode, b64decode
except ImportError:
    from base64 import encodestring as b64encode, decodestring as b64decode

49 50
#class Conflict(SyncCode, Implicit):
class Conflict(SyncCode, Base):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
51 52 53
  """
    object_path : the path of the obect
    keyword : an identifier of the conflict
54 55
    publisher_value : the value that we have locally
    subscriber_value : the value sent by the remote box
Jean-Paul Smets's avatar
Jean-Paul Smets committed
56 57

  """
58
  isIndexable = 0
59
  isPortalContent = 0 # Make sure RAD generated accessors at the class level
60

61 62
  def __init__(self, object_path=None, keyword=None, xupdate=None, 
      publisher_value=None, subscriber_value=None, subscriber=None):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
63 64
    self.object_path=object_path
    self.keyword = keyword
65 66 67
    self.setLocalValue(publisher_value)
    self.setRemoteValue(subscriber_value)
    self.subscriber = subscriber
68
    self.resetXupdate()
69
    self.copy_path = None
Jean-Paul Smets's avatar
Jean-Paul Smets committed
70 71 72

  def getObjectPath(self):
    """
73
    get the object path
Jean-Paul Smets's avatar
Jean-Paul Smets committed
74 75 76
    """
    return self.object_path

77
  def getPublisherValue(self):
78 79 80
    """
    get the domain
    """
81
    return self.publisher_value
82

83 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
  def getXupdateList(self):
    """
    get the xupdate wich gave an error
    """
    xupdate_list = []
    if len(self.xupdate)>0:
      for xupdate in self.xupdate:
        xupdate_list+= [xupdate]
    return xupdate_list

  def resetXupdate(self):
    """
    Reset the xupdate list
    """
    self.xupdate = PersistentMapping()

  def setXupdate(self, xupdate):
    """
    set the xupdate
    """
    if xupdate == None:
      self.resetXupdate()
    else:
      self.xupdate = self.getXupdateList() + [xupdate]

  def setXupdateList(self, xupdate):
    """
    set the xupdate
    """
    self.xupdate = xupdate

114 115 116 117 118
  def setLocalValue(self, value):
    """
    get the domain
    """
    try:
119
      self.publisher_value = value
120
    except TypeError: # It happens when we try to store StringIO
121
      self.publisher_value = None
122

123
  def getSubscriberValue(self):
124 125 126
    """
    get the domain
    """
127
    return self.subscriber_value
128 129 130 131 132 133

  def setRemoteValue(self, value):
    """
    get the domain
    """
    try:
134
      self.subscriber_value = value
135
    except TypeError: # It happens when we try to store StringIO
136
      self.subscriber_value = None
137

138
  def applyPublisherValue(self):
Sebastien Robin's avatar
Sebastien Robin committed
139 140 141 142 143
    """
      after a conflict resolution, we have decided
      to keep the local version of this object
    """
    p_sync = getToolByName(self,'portal_synchronizations')
144
    p_sync.applyPublisherValue(self)
Sebastien Robin's avatar
Sebastien Robin committed
145

146 147 148 149 150 151 152 153
  def applyPublisherDocument(self):
    """
      after a conflict resolution, we have decided
      to keep the local version of this object
    """
    p_sync = getToolByName(self,'portal_synchronizations')
    p_sync.applyPublisherDocument(self)

154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183
  def getPublisherDocument(self):
    """
      after a conflict resolution, we have decided
      to keep the local version of this object
    """
    p_sync = getToolByName(self,'portal_synchronizations')
    return p_sync.getPublisherDocument(self)

  def getPublisherDocumentPath(self):
    """
      after a conflict resolution, we have decided
      to keep the local version of this object
    """
    p_sync = getToolByName(self,'portal_synchronizations')
    return p_sync.getPublisherDocumentPath(self)

  def getSubscriberDocument(self):
    """
      after a conflict resolution, we have decided
      to keep the local version of this object
    """
    p_sync = getToolByName(self,'portal_synchronizations')
    return p_sync.getSubscriberDocument(self)

  def getSubscriberDocumentPath(self):
    """
      after a conflict resolution, we have decided
      to keep the local version of this object
    """
    p_sync = getToolByName(self,'portal_synchronizations')
184
    return p_sync.getSubscriberDocumentPath(self)
185

186
  def applySubscriberDocument(self):
187 188 189 190 191 192 193
    """
      after a conflict resolution, we have decided
      to keep the local version of this object
    """
    p_sync = getToolByName(self,'portal_synchronizations')
    p_sync.applySubscriberDocument(self)

194
  def applySubscriberValue(self,object=None):
Sebastien Robin's avatar
Sebastien Robin committed
195 196 197 198
    """
    get the domain
    """
    p_sync = getToolByName(self,'portal_synchronizations')
199
    p_sync.applySubscriberValue(self,object=object)
Sebastien Robin's avatar
Sebastien Robin committed
200

201
  def setSubscriber(self, subscriber):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
202 203 204
    """
    set the domain
    """
205
    self.subscriber = subscriber
Jean-Paul Smets's avatar
Jean-Paul Smets committed
206

207
  def getSubscriber(self):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
208 209 210
    """
    get the domain
    """
211
    return self.subscriber
Jean-Paul Smets's avatar
Jean-Paul Smets committed
212

213 214 215 216 217 218
  def getKeyword(self):
    """
    get the domain
    """
    return self.keyword

219
  def getPropertyId(self):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
220
    """
221
    get the property id
Jean-Paul Smets's avatar
Jean-Paul Smets committed
222
    """
223
    return self.keyword
Jean-Paul Smets's avatar
Jean-Paul Smets committed
224

225 226 227 228 229 230 231 232 233 234 235 236
  def getCopyPath(self):
    """
    Get the path of the copy, or None if none has been made
    """
    copy_path = self.copy_path
    return copy_path
    
  def setCopyPath(self, path):
    """
    """
    self.copy_path = path
    
237

238
class Signature(Folder,SyncCode):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
239 240 241 242 243
  """
    status -- SENT, CONFLICT...
    md5_object -- An MD5 value of a given document
    #uid -- The UID of the document
    id -- the ID of the document
244
    gid -- the global id of the document
Jean-Paul Smets's avatar
Jean-Paul Smets committed
245 246 247 248
    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
  """
249
  isIndexable = 0
250 251
  isPortalContent = 0 # Make sure RAD generated accessors at the class level
  
Jean-Paul Smets's avatar
Jean-Paul Smets committed
252
  # Constructor
253
  def __init__(self,gid=None, id=None, status=None, xml_string=None,object=None):
254
    self.setGid(gid)
255 256
    if object is not None:
      self.setPath(object.getPhysicalPath())
Nicolas Delaby's avatar
Nicolas Delaby committed
257 258
    else:
      self.setPath(None)
259
    self.setId(id)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
260 261 262 263 264 265
    self.status = status
    self.setXML(xml_string)
    self.partial_xml = None
    self.action = None
    self.setTempXML(None)
    self.resetConflictList()
266
    self.md5_string = None
Jean-Paul Smets's avatar
Jean-Paul Smets committed
267
    self.force = 0
268 269
    self.setSubscriberXupdate(None)
    self.setPublisherXupdate(None)
270
    Folder.__init__(self,id)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
271 272 273 274 275 276 277 278 279 280 281 282 283 284

  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(self.getTempXML())
      self.setTempXML(None)
285
      self.setPartialXML(None)
286
      self.setSubscriberXupdate(None)
Sebastien Robin's avatar
Sebastien Robin committed
287
      self.setPublisherXupdate(None)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
288 289
      if len(self.getConflictList())>0:
        self.resetConflictList()
Sebastien Robin's avatar
Sebastien Robin committed
290 291 292
      # XXX This may be a problem, if the document is changed
      # during a synchronization
      self.setLastSynchronizationDate(DateTime())
293
      self.getParentValue().removeRemainingObjectPath(self.getPath())
294 295 296
    if status == self.NOT_SYNCHRONIZED:
      self.setTempXML(None)
      self.setPartialXML(None)
297 298 299
    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()
Jean-Paul Smets's avatar
Jean-Paul Smets committed
300 301 302 303 304 305 306

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

307 308 309 310 311 312 313 314 315 316 317 318
  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

Jean-Paul Smets's avatar
Jean-Paul Smets committed
319 320 321 322 323 324 325 326 327 328 329 330
  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

Sebastien Robin's avatar
Sebastien Robin committed
331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358
  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)

Jean-Paul Smets's avatar
Jean-Paul Smets committed
359 360 361 362 363 364 365
  def setXML(self, xml):
    """
      set the XML corresponding to the object
    """
    self.xml = xml
    if self.xml != None:
      self.setTempXML(None) # We make sure that the xml will not be erased
366
      self.setMD5(xml)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
367 368 369 370 371

  def getXML(self):
    """
      set the XML corresponding to the object
    """
372 373 374 375
    xml =  getattr(self,'xml',None)
    if xml == '':
      xml = None
    return xml
Jean-Paul Smets's avatar
Jean-Paul Smets committed
376 377 378 379 380 381 382 383 384 385 386 387 388 389 390

  def setTempXML(self, xml):
    """
      This is the xml temporarily saved, it will
      be stored with setXML when we will receive
      the confirmation of synchronization
    """
    self.temp_xml = xml

  def getTempXML(self):
    """
      get the temp xml
    """
    return self.temp_xml

391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414
  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

Jean-Paul Smets's avatar
Jean-Paul Smets committed
415 416 417 418 419 420 421 422 423 424
  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
    """
425
    return self.md5_string
Jean-Paul Smets's avatar
Jean-Paul Smets committed
426 427 428 429 430 431 432 433

  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
    """
434
    return ((md5.new(xml_string).digest()) == self.getMD5())
Jean-Paul Smets's avatar
Jean-Paul Smets committed
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

  def setRid(self, rid):
    """
      set the rid
    """
    self.rid = rid

  def getRid(self):
    """
      get the rid
    """
    return self.rid

  def setId(self, id):
    """
      set the id
    """
    self.id = id

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

460 461 462 463 464 465 466 467 468 469 470 471
  def setGid(self, gid):
    """
      set the id
    """
    self.gid = gid

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

Jean-Paul Smets's avatar
Jean-Paul Smets committed
472 473 474 475 476
  def setPartialXML(self, xml):
    """
    Set the partial string we will have to
    deliver in the future
    """
477 478
    if type(xml) is type(u'a'):
      xml = xml.encode('utf-8')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
479 480 481 482 483 484 485
    self.partial_xml = xml

  def getPartialXML(self):
    """
    Set the partial string we will have to
    deliver in the future
    """
486
    #LOG('Subscriber.getPartialXML',0,'partial_xml: %s' % str(self.partial_xml))
487 488
    if self.partial_xml is not None:
      self.partial_xml = self.partial_xml.replace('@-@@-@','--') # need to put back '--'
Jean-Paul Smets's avatar
Jean-Paul Smets committed
489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522
    return self.partial_xml

  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
    """
    conflict_list = []
    if len(self.conflict_list)>0:
      for conflict in self.conflict_list:
        conflict_list += [conflict]
    return 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
    """
523
    # LOG('setConflictList, list',0,conflict_list)
Sebastien Robin's avatar
Sebastien Robin committed
524
    if conflict_list is None or conflict_list==[]:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
525 526
      self.resetConflictList()
    else:
Sebastien Robin's avatar
Sebastien Robin committed
527 528 529 530 531 532
      self.conflict_list = conflict_list

  def delConflict(self, conflict):
    """
    Return the actual action for a partial synchronization
    """
533
    # LOG('delConflict, conflict',0,conflict)
Sebastien Robin's avatar
Sebastien Robin committed
534 535 536 537 538 539 540 541 542
    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()
Jean-Paul Smets's avatar
Jean-Paul Smets committed
543

544 545 546 547
  def getObject(self):
    """
    Returns the object corresponding to this signature
    """
548
    return self.getParentValue().getObjectFromGid(self.getGid())
549

550 551 552 553 554
  def checkSynchronizationNeeded(self, object):
    """
    We will look at date, if there is no changes, no need to syncrhonize
    """
    last_modification = DateTime(object.ModificationDate())
555
    # LOG('checkSynchronizationNeeded object.ModificationDate()',0,object.ModificationDate())
556 557 558 559 560 561 562 563 564 565
    last_synchronization = self.getLastSynchronizationDate()
    parent = object.aq_parent
    # XXX CPS Specific
    if parent.id == 'portal_repository': # Make sure there is no sub objects
    #if 1:
      if last_synchronization is not None and last_modification is not None \
        and self.getSubscriberXupdate() is None and self.getPublisherXupdate() is None and \
        self.getStatus()==self.NOT_SYNCHRONIZED:
        if last_synchronization > last_modification:
        #if 1:
566
          # LOG('checkSynchronizationNeeded, no modification on: ',0,object.id)
567 568 569
          self.setStatus(self.SYNCHRONIZED)
    

570

571 572
def addSubscription( self, id, title='', REQUEST=None ):
    """
573
    Add a new Subscribption
574 575 576 577 578 579 580 581
    """
    o = Subscription( id ,'','','','','','')
    self._setObject( id, o )
    if REQUEST is not None:
        return self.manage_main(self, REQUEST, update_menu=1)
    return o

#class Subscription(SyncCode, Implicit):
582 583
#class Subscription(Folder, SyncCode, Implicit, Folder, Impli):
class Subscription(Folder, SyncCode):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600
  """
    Subscription hold the definition of a master ODB
    from/to which a selection of objects will be synchronised

    Subscription defined by::

    publication_url -- a URI to a publication

    subsribtion_url -- URL of ourselves

    destination_path -- the place where objects are stored

    query   -- a query which defines a local set of documents which
           are going to be synchronised

    xml_mapping -- a PageTemplate to map documents to XML

601 602
    gpg_key -- the name of a gpg key to use

Jean-Paul Smets's avatar
Jean-Paul Smets committed
603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618
    Subscription also holds private data to manage
    the synchronisation. We choose to keep an MD5 value for
    all documents which belong to the synchronisation process::

    signatures -- a dictionnary which contains the signature
           of documents at the time they were synchronized

    session_id -- it defines the id of the session
         with the server.

    last_anchor - it defines the id of the last synchronisation

    next_anchor - it defines the id of the current synchronisation

  """

619
  meta_type='ERP5 Subscription'
620
  portal_type='SyncML Subscription' # may be useful in the future...
621 622 623
  isPortalContent = 1
  isRADContent = 1
  icon = None
624
  isIndexable = 0
625
  user = None
626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642

  # Declarative properties
  property_sheets = ( PropertySheet.Base
                    , PropertySheet.SimpleItem )

  allowed_types = ( 'Signatures',)

  # Declarative constructors
  constructors =   (addSubscription,)

  # Declarative security
  security = ClassSecurityInfo()
  security.declareProtected(Permissions.ManagePortal,
                            'manage_editProperties',
                            'manage_changeProperties',
                            'manage_propertiesForm',
                              )
Jean-Paul Smets's avatar
Jean-Paul Smets committed
643 644

  # Constructor
645 646 647
  def __init__(self, id, title, publication_url, subscription_url, 
      destination_path, query, xml_mapping, conduit, gpg_key, id_generator, 
      gid_generator, flow_type, login, password):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
648 649 650 651 652 653 654 655 656
    """
      We need to create a dictionnary of
      signatures of documents which belong to the synchronisation
      process
    """
    self.id = id
    self.publication_url = (publication_url)
    self.subscription_url = str(subscription_url)
    self.destination_path = str(destination_path)
657
    self.setQuery(query)
658
    self.setXMLMapping(xml_mapping)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
659 660
    self.anchor = None
    self.session_id = 0
661
    #self.signatures = PersistentMapping()
Jean-Paul Smets's avatar
Jean-Paul Smets committed
662 663
    self.last_anchor = '00000000T000000Z'
    self.next_anchor = '00000000T000000Z'
664 665
    self.flow_type = flow_type
    self.login = login
666
    self.password=password
Jean-Paul Smets's avatar
Jean-Paul Smets committed
667
    self.domain_type = self.SUB
668
    self.gpg_key = gpg_key
669 670
    self.setGidGenerator(gid_generator)
    self.setSynchronizationIdGenerator(id_generator)
671
    self.setConduit(conduit)
672 673
    Folder.__init__(self, id)
    self.title = title
Sebastien Robin's avatar
Sebastien Robin committed
674
    
Jean-Paul Smets's avatar
Jean-Paul Smets committed
675 676
    #self.signatures = PersitentMapping()

677 678 679 680 681 682 683 684 685 686 687 688
  def getTitle(self):
    """
    getter for title
    """
    return getattr(self,'title',None)

  def setTitle(self, value):
    """
    setter for title
    """
    self.title = value

Jean-Paul Smets's avatar
Jean-Paul Smets committed
689 690 691 692 693 694 695 696 697 698 699 700
  # Accessors
  def getRemoteId(self, id, path=None):
    """
      Returns the remote id from a know local id
      Returns None if...
      path allows to implement recursive sync
    """
    pass

  def getSynchronizationType(self, default=None):
    """
    """
701 702 703
    # XXXXXXXXXXXXXXXXXXXXXXXXXXXXX
    # XXX for debugging only, to be removed
    dict_sign = {}
704 705
    for o in self.objectValues():
      dict_sign[o.getId()] = o.getStatus()
706
    # LOG('getSignature',0,'signatures_status: %s' % str(dict_sign))
707
    # XXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Jean-Paul Smets's avatar
Jean-Paul Smets committed
708
    code = self.SLOW_SYNC
709
    if len(self.objectValues()) > 0:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
710 711 712
      code = self.TWO_WAY
    if default is not None:
      code = default
713
    # LOG('Subscription',0,'getSynchronizationType: %s' % code)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
714 715
    return code

716 717
  def setXMLMapping(self, value):
    """
718
    this the name of the method used in order to set the xml
719 720 721 722 723
    """
    if value == '':
      value = None
    self.xml_mapping = value

724 725 726 727 728
  def checkCorrectRemoteSessionId(self, session_id):
    """
    We will see if the last session id was the same
    wich means that the same message was sent again

729
    return True if the session id was not seen, False if already seen
730 731 732
    """
    last_session_id = getattr(self,'last_session_id',None)
    if last_session_id == session_id:
733
      return False 
734
    self.last_session_id = session_id
735
    return True
736

Sebastien Robin's avatar
Sebastien Robin committed
737 738 739 740 741
  def checkCorrectRemoteMessageId(self, message_id):
    """
    We will see if the last message id was the same
    wich means that the same message was sent again

742
    return True if the message id was not seen, False if already seen
Sebastien Robin's avatar
Sebastien Robin committed
743 744
    """
    last_message_id = getattr(self,'last_message_id',None)
745 746
    # LOG('checkCorrectRemoteMessageId  last_message_id =',0,last_message_id)
    # LOG('checkCorrectRemoteMessageId  message_id =',0,message_id)
Sebastien Robin's avatar
Sebastien Robin committed
747
    if last_message_id == message_id:
748
      return False
Sebastien Robin's avatar
Sebastien Robin committed
749
    self.last_message_id = message_id
750
    return True
Sebastien Robin's avatar
Sebastien Robin committed
751 752 753 754 755 756

  def initLastMessageId(self, last_message_id=None):
    """
    set the last message id to 0
    """
    self.last_message_id=last_message_id
757 758 759 760 761 762 763 764 765 766 767 768 769

  def getLastSentMessage(self):
    """
    This is the getter for the last message we have sent
    """
    return getattr(self,'last_sent_message','')

  def setLastSentMessage(self,xml):
    """
    This is the setter for the last message we have sent
    """
    self.last_sent_message = xml

Jean-Paul Smets's avatar
Jean-Paul Smets committed
770 771 772 773 774 775 776 777 778 779 780 781 782
  def getLocalId(self, rid, path=None):
    """
      Returns the local id from a know remote id
      Returns None if...
    """
    pass

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

783 784 785 786 787 788
  def getDomainType(self):
    """
      return the ID
    """
    return self.domain_type

Jean-Paul Smets's avatar
Jean-Paul Smets committed
789 790 791 792 793 794
  def setId(self, id):
    """
      set the ID
    """
    self.id = id

795 796 797 798 799 800 801 802 803 804 805 806 807
  def setConduit(self, value):
    """
      set the Conduit
    """
    self.conduit = value

  def getConduit(self):
    """
      get the Conduit

    """
    return getattr(self,'conduit',None)

Jean-Paul Smets's avatar
Jean-Paul Smets committed
808 809 810 811 812 813
  def getQuery(self):
    """
      return the query
    """
    return self.query

814 815 816 817 818 819
  def getGPGKey(self):
    """
      return the gnupg key name
    """
    return getattr(self,'gpg_key','')

820 821 822 823 824 825
  def setGPGKey(self, value):
    """
      setter for the gnupg key name
    """
    self.gpg_key = value

Jean-Paul Smets's avatar
Jean-Paul Smets committed
826 827 828 829
  def setQuery(self, query):
    """
      set the query
    """
830 831
    if query == '':
      query = None
Jean-Paul Smets's avatar
Jean-Paul Smets committed
832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851
    self.query = query

  def getPublicationUrl(self):
    """
      return the publication url
    """
    return self.publication_url

  def getLocalUrl(self):
    """
      return the publication url
    """
    return self.publication_url

  def setPublicationUrl(self, publication_url):
    """
      return the publication url
    """
    self.publication_url = publication_url

852
  def getXMLMapping(self):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
853 854 855
    """
      return the xml mapping
    """
856 857
    xml_mapping = getattr(self,'xml_mapping','asXML')
    return xml_mapping
Jean-Paul Smets's avatar
Jean-Paul Smets committed
858

859
  def getXMLFromObject(self,object):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
860 861 862
    """
      return the xml mapping
    """
863 864 865 866 867 868 869
    xml_mapping = self.getXMLMapping()
    xml = ''
    if xml_mapping is not None:
      func = getattr(object,xml_mapping,None)
      if func is not None:
        xml = func()
    return xml
Jean-Paul Smets's avatar
Jean-Paul Smets committed
870

871
  def setGidGenerator(self, method):
872 873 874 875
    """
    This set the method name wich allows to find a gid
    from any object
    """
876
    if method in (None,'','None'):
877 878
      method = 'getId'
    self.gid_generator = method
879 880 881 882 883 884 885 886

  def getGidGenerator(self):
    """
    This get the method name wich allows to find a gid
    from any object
    """
    return self.gid_generator

887 888 889 890 891 892 893 894 895 896 897 898 899 900
  def getFlowType(self):
    """
    This method return the type of the data within the xml message :
      - text for VCard's
      - xml for others
    """
    return getattr(self, 'flow_type', 'xml')

  def setFlowType(self, flow_type):
    """
    set the flow type (xml or text)
    """
    self.flow_type=flow_type

901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955
  def getLogin(self):
    """
    This method return the login of this subscription
    """
    return getattr(self, 'login', '')

  def setLogin(self, new_login):
    """
    set the login at new_login
    """
    self.login=new_login

  def getPassword(self):
    """
    This method return the password of this subscription
    """
    return getattr(self, 'password', '')

  def setPassword(self, new_password):
    """
    set the password at new_password
    """
    self.password=new_password
  

  def setAuthentication(self, auth):
    """
      set the value of the authentication requirement
    """
    self.auth_required = auth

  def getAuthenticationFormat(self):
    """
      return the format of authentication
    """
    return getattr(self, 'authentication_format', '')

  def getAuthenticationType(self):
    """
      return the type of authentication
    """
    return getattr(self, 'authentication_type', '')

  def setAuthenticationFormat(self, authentication_format):
    """
      set the format of authentication
    """
    self.authentication_format = authentication_format

  def setAuthenticationType(self, authentication_type):
    """
      set the type of authentication
    """
    self.authentication_type = authentication_type

956 957 958 959 960 961 962 963
  def getGidFromObject(self, object):
    """
    """
    o_base = aq_base(object)
    o_gid = None
    gid_gen = self.getGidGenerator()
    if callable(gid_gen):
      o_gid=gid_gen(object)
964
    elif getattr(o_base, gid_gen, None) is not None:
965
      generator = getattr(object, gid_gen)
966
      o_gid = generator() # XXX - used to be o_gid = generator(object=object) which is redundant
967 968 969
    elif gid_gen is not None:
      # It might be a script python
      generator = getattr(object,gid_gen)
970
      o_gid = generator() # XXX - used to be o_gid = generator(object=object) which is redundant
971
    LOG('getGidFromObject',0,'o_gid: %s' % repr(o_gid))
972 973
    return o_gid

974 975 976 977 978 979 980 981 982 983
  def getObjectFromGid(self, gid):
    """
    This tries to get the object with the given gid
    This uses the query if it exist
    """
    signature = self.getSignature(gid)
    # First look if we do already have the mapping between
    # the id and the gid
    object_list = self.getObjectList()
    destination = self.getDestination()
984 985 986
    # LOG('getObjectFromGid', 0, 'self: %s' % self)    
    # LOG('getObjectFromGid',0,'gid: %s' % repr(gid))
    # LOG('getObjectFromGid oject_list',0,object_list)
987
    if signature is not None and signature.getId() is not None:
988 989 990 991
      o_id = signature.getId()
      o = None
      try:
        o = destination._getOb(o_id)
992
      except (AttributeError, KeyError, TypeError):
993 994 995 996
        pass
      if o is not None and o in object_list:
        return o
    for o in object_list:
997 998 999
      o_gid = self.getGidFromObject(o)
      if o_gid == gid:
        return o
1000
    # LOG('getObjectFromGid',0,'returning None')
1001 1002
    return None

1003 1004 1005 1006 1007 1008 1009 1010 1011
#  def setOneWaySyncFromServer(self,value):
#    """
#    If this option is enabled, then we will not 
#    send our own modifications
#    """
#    self.one_way_sync_from_server = value
#


1012 1013 1014 1015 1016 1017 1018 1019
  def getObjectList(self):
    """
    This returns the list of sub-object corresponding
    to the query
    """
    destination = self.getDestination()
    query = self.getQuery()
    query_list = []
1020 1021
    if query is None:
      return query_list
Sebastien Robin's avatar
Sebastien Robin committed
1022
    if isinstance(query, str):
1023 1024 1025
      query_method = getattr(destination,query,None)
      if query_method is not None:
        query_list = query_method()
1026
    elif callable(query): # XXX - used to be if callable(query)
1027
      query_list = query(destination)
1028 1029
    return [x for x in query_list
              if not getattr(x,'_conflict_resolution',False)]
1030

1031
  def generateNewIdWithGenerator(self, object=None,gid=None):
1032 1033 1034
    """
    This tries to generate a new Id
    """
1035
    id_generator = self.getSynchronizationIdGenerator()
1036
    if id_generator is not None:
1037
      o_base = aq_base(object)
1038 1039
      new_id = None
      if callable(id_generator):
1040
        new_id = id_generator(object,gid=gid)
1041
      elif getattr(o_base, id_generator, None) is not None:
1042
        generator = getattr(object, id_generator)
1043
        new_id = generator()
1044 1045 1046 1047
      else: 
        # This is probably a python scrip
        generator = getattr(object, id_generator)
        new_id = generator(object=object,gid=gid)
1048 1049
      LOG('generateNewId, new_id: ',0,new_id)
      return new_id
1050 1051
    return None

1052
  def setSynchronizationIdGenerator(self, method):
1053 1054 1055 1056
    """
    This set the method name wich allows to generate
    a new id
    """
1057 1058
    if method in ('','None'):
      method = None
1059
    self.synchronization_id_generator = method
1060

1061
  def getSynchronizationIdGenerator(self):
1062 1063 1064
    """
    This get the method name wich allows to generate a new id
    """
1065
    return getattr(self, 'synchronization_id_generator', None)
1066

Jean-Paul Smets's avatar
Jean-Paul Smets committed
1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084
  def getSubscriptionUrl(self):
    """
      return the subscription url
    """
    return self.subscription_url

  def setSubscriptionUrl(self, subscription_url):
    """
      set the subscription url
    """
    self.subscription_url = subscription_url

  def getDestinationPath(self):
    """
      return the destination path
    """
    return self.destination_path

1085 1086 1087 1088 1089 1090
  def getDestination(self):
    """
      return the destination object itself
    """
    return self.unrestrictedTraverse(self.getDestinationPath())

Jean-Paul Smets's avatar
Jean-Paul Smets committed
1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101
  def setDestinationPath(self, destination_path):
    """
      set the destination path
    """
    self.destination_path = destination_path

  def getSubscription(self):
    """
      return the current subscription
    """
    return self
Sebastien Robin's avatar
Sebastien Robin committed
1102 1103 1104 1105 1106 1107
    
  def setSessionId(self, session_id):
    """
      set the session id
    """
    self.session_id = session_id
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1108 1109 1110 1111 1112

  def getSessionId(self):
    """
      return the session id
    """
Sebastien Robin's avatar
Sebastien Robin committed
1113 1114 1115 1116 1117 1118 1119
    #self.session_id += 1 #to be commented
    return self.session_id

  def incrementSessionId(self):
    """
      increment and return the session id
    """
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1120
    self.session_id += 1
Sebastien Robin's avatar
Sebastien Robin committed
1121
    self.resetMessageId() # for a new session, the message Id must be reset
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1122 1123
    return self.session_id

Sebastien Robin's avatar
Sebastien Robin committed
1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145
  def incrementMessageId(self):
    """
      return the message id
    """
    #self.message_id += 1
    #return self.message_id
    #return 5
    value = getattr(self, 'message_id', 0)
    self.message_id = value +1
    return self.message_id

  def getMessageId(self):
    """
      increment and return the message id
    """
    return self.message_id

  def resetMessageId(self):
    """
      set the message id to 0
    """
    self.message_id = 0
1146 1147 1148 1149 1150 1151
  
  def setMessageId(self, message_id):
    """
      set the message id to message_id
    """
    self.message_id = message_id
Sebastien Robin's avatar
Sebastien Robin committed
1152

Jean-Paul Smets's avatar
Jean-Paul Smets committed
1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196
  def getLastAnchor(self):
    """
      return the id of the last synchronisation
    """
    return self.last_anchor

  def getNextAnchor(self):
    """
      return the id of the current synchronisation
    """
    return self.next_anchor

  def setLastAnchor(self, last_anchor):
    """
      set the value last anchor
    """
    self.last_anchor = last_anchor

  def setNextAnchor(self, next_anchor):
    """
      set the value next anchor
    """
    # We store the old next anchor as the new last one
    self.last_anchor = self.next_anchor
    self.next_anchor = next_anchor

  def NewAnchor(self):
    """
      set a new anchor
    """
    self.last_anchor = self.next_anchor
    self.next_anchor = strftime("%Y%m%dT%H%M%SZ", gmtime())

  def resetAnchors(self):
    """
      reset both last and next anchors
    """
    self.last_anchor = self.NULL_ANCHOR
    self.next_anchor = self.NULL_ANCHOR

  def addSignature(self, signature):
    """
      add a Signature to the subscription
    """
1197 1198
    if signature.getGid() in self.objectIds():
      self._delObject(signature.getGid())
1199
    self._setObject(signature.getGid(), aq_base(signature) )
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1200

1201
  def delSignature(self, gid):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1202 1203 1204
    """
      add a Signature to the subscription
    """
1205 1206
    #del self.signatures[gid]
    self._delObject(gid)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1207

1208
  def getSignature(self, gid):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1209 1210 1211
    """
      add a Signature to the subscription
    """
1212 1213 1214
    o = None
    if gid in self.objectIds():
      o = self._getOb(gid)
1215 1216
    #if o is not None:
    #  return o.__of__(self)
1217
    return o
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1218 1219 1220 1221 1222

  def getSignatureList(self):
    """
      add a Signature to the subscription
    """
1223
    return self.objectValues()
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1224

1225
  def hasSignature(self, gid):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1226 1227 1228
    """
      Check if there's a signature with this uid
    """
1229 1230
    #return self.signatures.has_key(gid)
    return gid in self.objectIds()
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1231 1232 1233 1234 1235

  def resetAllSignatures(self):
    """
      Reset all signatures
    """
1236 1237 1238
    while len(self.objectIds())>0:
      for id in self.objectIds():
        self._delObject(id)
1239

1240
  def getGidList(self):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1241 1242 1243
    """
    Returns the list of ids from signature
    """
1244
    return self.objectIds()
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1245 1246 1247 1248 1249 1250 1251 1252 1253 1254

  def getConflictList(self):
    """
    Return the list of all conflicts from all signatures
    """
    conflict_list = []
    for signature in self.getSignatureList():
      conflict_list += signature.getConflictList()
    return conflict_list

1255
  def getRemainingObjectPathList(self):
1256 1257 1258 1259
    """
    We should now wich objects should still
    synchronize
    """
1260
    return getattr(self,'remaining_object_path_list',None)
1261

1262
  def setRemainingObjectPathList(self, value):
1263 1264 1265 1266
    """
    We should now wich objects should still
    synchronize
    """
1267
    setattr(self,'remaining_object_path_list',value)
1268

1269
  def removeRemainingObjectPath(self, object_path):
1270 1271 1272 1273
    """
    We should now wich objects should still
    synchronize
    """
1274
    remaining_object_list = self.getRemainingObjectPathList()
1275 1276 1277
    if remaining_object_list is not None:
      new_list = []
      for o in remaining_object_list:
1278
        if o != object_path:
1279
          new_list.append(o)
1280
      self.setRemainingObjectPathList(new_list)
1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295

#  def getCurrentObject(self):
#    """
#    When we send some partial data, then we should
#    always synchronize the same object until it is finished
#    """
#    getattr(self,'current_object',None)
#
#  def setCurrentObject(self,object):
#    """
#    When we send some partial data, then we should
#    always synchronize the same object until it is finished
#    """
#    setattr(self,'current_object',object)

Jean-Paul Smets's avatar
Jean-Paul Smets committed
1296 1297 1298 1299
  def startSynchronization(self):
    """
    Set the status of every object as NOT_SYNCHRONIZED
    """
1300
    for o in self.objectValues():
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1301
      # Change the status only if we are not in a conflict mode
1302
      if not(o.getStatus() in (self.CONFLICT,self.PUB_CONFLICT_MERGE,
1303
                                                        self.PUB_CONFLICT_CLIENT_WIN)):
1304 1305 1306
        o.setStatus(self.NOT_SYNCHRONIZED)
        o.setPartialXML(None)
        o.setTempXML(None)
1307
    self.setRemainingObjectPathList(None)
1308

1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334

  def isAuthenticated(self):
    """
    return True if the subscriber is authenticated for this session, False 
    in other case
    """
    return self.is_authenticated
    
  def setAuthenticated(self, value):
    """
      set at True or False the value of is_authenticated is the subscriber
      is authenticated for this session or not
    """
    self.is_authenticated = value

  def encode(self, format, string_to_encode):
    """
      return the string_to_encode encoded with format format
    """
    if format in ('', None):
      return string_to_encode
    if format == 'b64':
      return b64encode(string_to_encode)
    #elif format is .... put here the other formats
    else:#if there is no format corresponding with format, raise an error
      LOG('encode : unknown or not implemented format :', 0, format)
1335
      raise ValueError, "Sorry, the server ask for the format %s but it's unknow or not implemented" % format
1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372

  def decode(self, format, string_to_decode):
    """
      return the string_to_decode decoded with format format
    """
    string_to_decode = string_to_decode.encode('utf-8')
    if format in ('', None):
      return string_to_decode
    if format == 'b64':
      return b64decode(string_to_decode)
    #elif format is .... put here the other formats
    else:#if there is no format corresponding with format, raise an error
      LOG('decode : unknown or not implemented format :', 0, format)
      raise ValueError, "Sorry, the format %s is unknow or not implemented" % format

  def isDecodeEncodeTheSame(self, string_encoded, string_decoded, format):
    """
      return True if the string_encoded is equal to string_decoded encoded 
      in format
    """
    isTheSame=False
    if self.encode(format, string_decoded) == string_encoded:
      isTheSame=True
    return isTheSame


  def setUser(self, user):
    """
      save the user logged in to log him on each transaction
    """
    self.user=user

  def getUser(self):
    """
      retrun the user logged in
    """
    return self.user