comparison src/memory/memory.py @ 587:952322b1d490

Remove trailing whitespaces.
author Emmanuel Gil Peyrot <linkmauve@linkmauve.fr>
date Fri, 18 Jan 2013 17:55:34 +0100
parents 89f9a50ce7bf
children beaf6bec2fcd
comparison
equal deleted inserted replaced
586:6a718ede8be1 587:952322b1d490
38 38
39 39
40 class Params(): 40 class Params():
41 """This class manage parameters with xml""" 41 """This class manage parameters with xml"""
42 ### TODO: add desciption in params 42 ### TODO: add desciption in params
43 43
44 #TODO: move Watched in a plugin 44 #TODO: move Watched in a plugin
45 default_xml = u""" 45 default_xml = u"""
46 <params> 46 <params>
47 <general> 47 <general>
48 </general> 48 </general>
82 source_map = getNodesMap(source_node.childNodes) 82 source_map = getNodesMap(source_node.childNodes)
83 dest_map = getNodesMap(dest_node.childNodes) 83 dest_map = getNodesMap(dest_node.childNodes)
84 source_set = set(source_map.keys()) 84 source_set = set(source_map.keys())
85 dest_set = set(dest_map.keys()) 85 dest_set = set(dest_map.keys())
86 to_add = source_set.difference(dest_set) 86 to_add = source_set.difference(dest_set)
87 87
88 for node_key in to_add: 88 for node_key in to_add:
89 dest_node.appendChild(source_map[node_key].cloneNode(True)) 89 dest_node.appendChild(source_map[node_key].cloneNode(True))
90 90
91 to_recurse = source_set - to_add 91 to_recurse = source_set - to_add
92 for node_key in to_recurse: 92 for node_key in to_recurse:
95 def load_xml(self, xml_file): 95 def load_xml(self, xml_file):
96 """Load parameters template from file""" 96 """Load parameters template from file"""
97 self.dom = minidom.parse(xml_file) 97 self.dom = minidom.parse(xml_file)
98 default_dom = minidom.parseString(Params.default_xml.encode('utf-8')) 98 default_dom = minidom.parseString(Params.default_xml.encode('utf-8'))
99 self._mergeParams(default_dom.documentElement, self.dom.documentElement) 99 self._mergeParams(default_dom.documentElement, self.dom.documentElement)
100 100
101 def loadGenParams(self): 101 def loadGenParams(self):
102 """Load general parameters data from storage 102 """Load general parameters data from storage
103 @return: deferred triggered once params are loaded""" 103 @return: deferred triggered once params are loaded"""
104 return self.storage.loadGenParams(self.params_gen) 104 return self.storage.loadGenParams(self.params_gen)
105 105
106 def loadIndParams(self, profile, cache=None): 106 def loadIndParams(self, profile, cache=None):
107 """Load individual parameters 107 """Load individual parameters
108 set self.params cache or a temporary cache 108 set self.params cache or a temporary cache
109 @param profile: profile to load (*must exist*) 109 @param profile: profile to load (*must exist*)
110 @param cache: if not None, will be used to store the value, as a short time cache 110 @param cache: if not None, will be used to store the value, as a short time cache
111 @return: deferred triggered once params are loaded""" 111 @return: deferred triggered once params are loaded"""
112 if cache == None: 112 if cache == None:
113 self.params[profile] = {} 113 self.params[profile] = {}
114 return self.storage.loadIndParams(self.params[profile] if cache==None else cache, profile) 114 return self.storage.loadIndParams(self.params[profile] if cache==None else cache, profile)
115 115
116 def purgeProfile(self, profile): 116 def purgeProfile(self, profile):
117 """Remove cache data of a profile 117 """Remove cache data of a profile
118 @param profile: %(doc_profile)s""" 118 @param profile: %(doc_profile)s"""
119 try: 119 try:
120 del self.params[profile] 120 del self.params[profile]
277 """Helper method to get a specific attribute 277 """Helper method to get a specific attribute
278 @param name: name of the parameter 278 @param name: name of the parameter
279 @param category: category of the parameter 279 @param category: category of the parameter
280 @param attr: name of the attribute (default: "value") 280 @param attr: name of the attribute (default: "value")
281 @param profile: owner of the param (@ALL@ for everyone) 281 @param profile: owner of the param (@ALL@ for everyone)
282 282
283 @return: attribute""" 283 @return: attribute"""
284 #FIXME: looks really dirty and buggy, need to be reviewed/refactored 284 #FIXME: looks really dirty and buggy, need to be reviewed/refactored
285 node = self.__getParamNode(name, category) 285 node = self.__getParamNode(name, category)
286 if not node: 286 if not node:
287 error(_("Requested param [%(name)s] in category [%(category)s] doesn't exist !") % {'name':name, 'category':category}) 287 error(_("Requested param [%(name)s] in category [%(category)s] doesn't exist !") % {'name':name, 'category':category})
288 raise exceptions.NotFound 288 raise exceptions.NotFound
289 289
290 if node[0] == 'general': 290 if node[0] == 'general':
291 value = self.__getParam(None, category, name, 'general') 291 value = self.__getParam(None, category, name, 'general')
292 return self.__getAttr(node[1], attr, value) 292 return self.__getAttr(node[1], attr, value)
293 293
294 assert(node[0] == 'individual') 294 assert(node[0] == 'individual')
295 295
296 profile = self.getProfileName(profile_key) 296 profile = self.getProfileName(profile_key)
297 if not profile: 297 if not profile:
298 error(_('Requesting a param for an non-existant profile')) 298 error(_('Requesting a param for an non-existant profile'))
299 raise exceptions.ProfileUnknownError 299 raise exceptions.ProfileUnknownError
300 300
301 if profile not in self.params: 301 if profile not in self.params:
302 error(_('Requesting synchronous param for not connected profile')) 302 error(_('Requesting synchronous param for not connected profile'))
303 raise exceptions.NotConnectedProfileError(profile) 303 raise exceptions.NotConnectedProfileError(profile)
304 304
305 if attr == "value": 305 if attr == "value":
306 value = self.__getParam(profile, category, name) 306 value = self.__getParam(profile, category, name)
307 return self.__getAttr(node[1], attr, value) 307 return self.__getAttr(node[1], attr, value)
308 308
309 def asyncGetStringParamA(self, name, category, attr="value", profile_key="@DEFAULT@"): 309 def asyncGetStringParamA(self, name, category, attr="value", profile_key="@DEFAULT@"):
310 d = self.asyncGetParamA(name, category, attr, profile_key) 310 d = self.asyncGetParamA(name, category, attr, profile_key)
323 return None 323 return None
324 324
325 if node[0] == 'general': 325 if node[0] == 'general':
326 value = self.__getParam(None, category, name, 'general') 326 value = self.__getParam(None, category, name, 'general')
327 return defer.succeed(self.__getAttr(node[1], attr, value)) 327 return defer.succeed(self.__getAttr(node[1], attr, value))
328 328
329 assert(node[0] == 'individual') 329 assert(node[0] == 'individual')
330 330
331 profile = self.getProfileName(profile_key) 331 profile = self.getProfileName(profile_key)
332 if not profile: 332 if not profile:
333 error(_('Requesting a param for a non-existant profile')) 333 error(_('Requesting a param for a non-existant profile'))
334 return defer.fail() 334 return defer.fail()
335 335
336 if attr != "value": 336 if attr != "value":
337 return defer.succeed(node[1].getAttribute(attr)) 337 return defer.succeed(node[1].getAttribute(attr))
338 try: 338 try:
339 value = self.__getParam(profile, category, name) 339 value = self.__getParam(profile, category, name)
340 return defer.succeed(self.__getAttr(node[1], attr, value)) 340 return defer.succeed(self.__getAttr(node[1], attr, value))
341 except exceptions.ProfileNotInCacheError: 341 except exceptions.ProfileNotInCacheError:
394 continue 394 continue
395 dest_params[node.getAttribute('name')] = node 395 dest_params[node.getAttribute('name')] = node
396 396
397 for param_node in params: 397 for param_node in params:
398 name = param_node.getAttribute('name') 398 name = param_node.getAttribute('name')
399 399
400 if name not in dest_params: 400 if name not in dest_params:
401 dest_params[name] = param_node.cloneNode(True) 401 dest_params[name] = param_node.cloneNode(True)
402 dest_cat.appendChild(dest_params[name]) 402 dest_cat.appendChild(dest_params[name])
403 403
404 profile_value = self.__getParam(profile, category, name, type_node.nodeName, cache=profile_cache) 404 profile_value = self.__getParam(profile, category, name, type_node.nodeName, cache=profile_cache)
405 if profile_value!=None: #there is a value for this profile, we must change the default 405 if profile_value!=None: #there is a value for this profile, we must change the default
406 dest_params[name].setAttribute('value', profile_value) 406 dest_params[name].setAttribute('value', profile_value)
407 if new_node: 407 if new_node:
408 prof_xml.documentElement.appendChild(dest_cat) 408 prof_xml.documentElement.appendChild(dest_cat)
409 return prof_xml 409 return prof_xml
410 410
411 411
412 if self.params.has_key(profile): 412 if self.params.has_key(profile):
413 d = defer.succeed(None) 413 d = defer.succeed(None)
414 profile_cache = self.params[profile] 414 profile_cache = self.params[profile]
415 else: 415 else:
416 #profile is not in cache, we load values in a short time cache 416 #profile is not in cache, we load values in a short time cache
433 Take params xml as skeleton""" 433 Take params xml as skeleton"""
434 profile = self.getProfileName(profile_key) 434 profile = self.getProfileName(profile_key)
435 if not profile: 435 if not profile:
436 error(_("Asking params for inexistant profile")) 436 error(_("Asking params for inexistant profile"))
437 return "" 437 return ""
438 438
439 def returnXML(prof_xml): 439 def returnXML(prof_xml):
440 return_xml = prof_xml.toxml() 440 return_xml = prof_xml.toxml()
441 prof_xml.unlink() 441 prof_xml.unlink()
442 return return_xml 442 return return_xml
443 443
444 return self.__constructProfileXml(profile).addCallback(returnXML) 444 return self.__constructProfileXml(profile).addCallback(returnXML)
445 445
446 def getParamsForCategory(self, category, profile_key): 446 def getParamsForCategory(self, category, profile_key):
447 """Return node's xml for selected category""" 447 """Return node's xml for selected category"""
448 #TODO: manage category of general type (without existant profile) 448 #TODO: manage category of general type (without existant profile)
449 profile = self.getProfileName(profile_key) 449 profile = self.getProfileName(profile_key)
458 prof_xml.unlink() 458 prof_xml.unlink()
459 return result 459 return result
460 460
461 prof_xml.unlink() 461 prof_xml.unlink()
462 return "<category />" 462 return "<category />"
463 463
464 d = self.__constructProfileXml(profile) 464 d = self.__constructProfileXml(profile)
465 return d.addCallback(returnCategoryXml) 465 return d.addCallback(returnCategoryXml)
466 466
467 def __getParamNode(self, name, category, _type="@ALL@"): #FIXME: is _type useful ? 467 def __getParamNode(self, name, category, _type="@ALL@"): #FIXME: is _type useful ?
468 """Return a node from the param_xml 468 """Return a node from the param_xml
473 @GENERAL@ only search in general type 473 @GENERAL@ only search in general type
474 @INDIVIDUAL@ only search in individual type 474 @INDIVIDUAL@ only search in individual type
475 @return: a tuple with the node type and the the node, or None if not found""" 475 @return: a tuple with the node type and the the node, or None if not found"""
476 476
477 for type_node in self.dom.documentElement.childNodes: 477 for type_node in self.dom.documentElement.childNodes:
478 if ( ((_type == "@ALL@" or _type == "@GENERAL@") and type_node.nodeName == 'general') 478 if ( ((_type == "@ALL@" or _type == "@GENERAL@") and type_node.nodeName == 'general')
479 or ( (_type == "@ALL@" or _type == "@INDIVIDUAL@") and type_node.nodeName == 'individual') ): 479 or ( (_type == "@ALL@" or _type == "@INDIVIDUAL@") and type_node.nodeName == 'individual') ):
480 for node in type_node.getElementsByTagName('category'): 480 for node in type_node.getElementsByTagName('category'):
481 if node.getAttribute("name") == category: 481 if node.getAttribute("name") == category:
482 params = node.getElementsByTagName("param") 482 params = node.getElementsByTagName("param")
483 for param in params: 483 for param in params:
484 if param.getAttribute("name") == name: 484 if param.getAttribute("name") == name:
485 return (type_node.nodeName, param) 485 return (type_node.nodeName, param)
486 return None 486 return None
487 487
488 def getParamsCategories(self): 488 def getParamsCategories(self):
489 """return the categories availables""" 489 """return the categories availables"""
490 categories=[] 490 categories=[]
491 for cat in self.dom.getElementsByTagName("category"): 491 for cat in self.dom.getElementsByTagName("category"):
492 name = cat.getAttribute("name") 492 name = cat.getAttribute("name")
505 505
506 node = self.__getParamNode(name, category, '@ALL@') 506 node = self.__getParamNode(name, category, '@ALL@')
507 if not node: 507 if not node:
508 error(_('Requesting an unknown parameter (%(category)s/%(name)s)') % {'category':category, 'name':name}) 508 error(_('Requesting an unknown parameter (%(category)s/%(name)s)') % {'category':category, 'name':name})
509 return 509 return
510 510
511 if node[0] == 'general': 511 if node[0] == 'general':
512 self.params_gen[(category, name)] = value 512 self.params_gen[(category, name)] = value
513 self.storage.setGenParam(category, name, value) 513 self.storage.setGenParam(category, name, value)
514 for profile in self.storage.getProfilesList(): 514 for profile in self.storage.getProfilesList():
515 if self.host.isConnected(profile): 515 if self.host.isConnected(profile):
516 self.host.bridge.paramUpdate(name, value, category, profile) 516 self.host.bridge.paramUpdate(name, value, category, profile)
517 return 517 return
518 518
519 assert (node[0] == 'individual') 519 assert (node[0] == 'individual')
520 assert (profile_key != "@NONE@") 520 assert (profile_key != "@NONE@")
521 521
522 _type = node[1].getAttribute("type") 522 _type = node[1].getAttribute("type")
523 if _type=="button": 523 if _type=="button":
524 print "clique",node.toxml() 524 print "clique",node.toxml()
525 else: 525 else:
526 if self.host.isConnected(profile): #key can not exists if profile is not connected 526 if self.host.isConnected(profile): #key can not exists if profile is not connected
531 class Memory: 531 class Memory:
532 """This class manage all persistent informations""" 532 """This class manage all persistent informations"""
533 533
534 def __init__(self, host): 534 def __init__(self, host):
535 info (_("Memory manager init")) 535 info (_("Memory manager init"))
536 self.initialized = defer.Deferred() 536 self.initialized = defer.Deferred()
537 self.host = host 537 self.host = host
538 self.entitiesCache={} #XXX: keep presence/last resource/other data in cache 538 self.entitiesCache={} #XXX: keep presence/last resource/other data in cache
539 # /!\ an entity is not necessarily in roster 539 # /!\ an entity is not necessarily in roster
540 self.subscriptions={} 540 self.subscriptions={}
541 self.server_features={} #used to store discovery's informations 541 self.server_features={} #used to store discovery's informations
609 def startProfileSession(self, profile): 609 def startProfileSession(self, profile):
610 """"Iniatialise session for a profile 610 """"Iniatialise session for a profile
611 @param profile: %(doc_profile)s""" 611 @param profile: %(doc_profile)s"""
612 info(_("[%s] Profile session started" % profile)) 612 info(_("[%s] Profile session started" % profile))
613 self.entitiesCache[profile] = {} 613 self.entitiesCache[profile] = {}
614 614
615 def purgeProfileSession(self, profile): 615 def purgeProfileSession(self, profile):
616 """Delete cache of data of profile 616 """Delete cache of data of profile
617 @param profile: %(doc_profile)s""" 617 @param profile: %(doc_profile)s"""
618 info(_("[%s] Profile session purge" % profile)) 618 info(_("[%s] Profile session purge" % profile))
619 self.params.purgeProfile(profile) 619 self.params.purgeProfile(profile)
626 def save(self): 626 def save(self):
627 """Save parameters and all memory things to file/db""" 627 """Save parameters and all memory things to file/db"""
628 #TODO: need to encrypt files (at least passwords !) and set permissions 628 #TODO: need to encrypt files (at least passwords !) and set permissions
629 param_file_xml = os.path.expanduser(self.getConfig('','local_dir')+ 629 param_file_xml = os.path.expanduser(self.getConfig('','local_dir')+
630 self.host.get_const('savefile_param_xml')) 630 self.host.get_const('savefile_param_xml'))
631 631
632 self.params.save_xml(param_file_xml) 632 self.params.save_xml(param_file_xml)
633 debug(_("params saved")) 633 debug(_("params saved"))
634 634
635 def getProfilesList(self): 635 def getProfilesList(self):
636 return self.storage.getProfilesList() 636 return self.storage.getProfilesList()
645 def createProfile(self, name): 645 def createProfile(self, name):
646 """Create a new profile 646 """Create a new profile
647 @param name: Profile name 647 @param name: Profile name
648 """ 648 """
649 return self.params.createProfile(name) 649 return self.params.createProfile(name)
650 650
651 def asyncCreateProfile(self, name): 651 def asyncCreateProfile(self, name):
652 """Create a new profile 652 """Create a new profile
653 @param name: Profile name 653 @param name: Profile name
654 """ 654 """
655 return self.params.asyncCreateProfile(name) 655 return self.params.asyncCreateProfile(name)
656 656
657 def deleteProfile(self, name): 657 def deleteProfile(self, name):
658 """Delete an existing profile 658 """Delete an existing profile
659 @param name: Name of the profile""" 659 @param name: Name of the profile"""
660 return self.params.deleteProfile(name) 660 return self.params.deleteProfile(name)
661 661
672 @param feature: string of the feature 672 @param feature: string of the feature
673 @param profile: which profile is using this server ?""" 673 @param profile: which profile is using this server ?"""
674 if not self.server_features.has_key(profile): 674 if not self.server_features.has_key(profile):
675 self.server_features[profile] = [] 675 self.server_features[profile] = []
676 self.server_features[profile].append(feature) 676 self.server_features[profile].append(feature)
677 677
678 def addServerIdentity(self, category, _type, entity, profile): 678 def addServerIdentity(self, category, _type, entity, profile):
679 """Add an identity discovered from server 679 """Add an identity discovered from server
680 @param feature: string of the feature 680 @param feature: string of the feature
681 @param profile: which profile is using this server ?""" 681 @param profile: which profile is using this server ?"""
682 if not profile in self.server_identities: 682 if not profile in self.server_identities:
725 return "" 725 return ""
726 try: 726 try:
727 return self.entitiesCache[profile][entity]["last_resource"] 727 return self.entitiesCache[profile][entity]["last_resource"]
728 except KeyError: 728 except KeyError:
729 return "" 729 return ""
730 730
731 def getPresenceStatus(self, profile_key): 731 def getPresenceStatus(self, profile_key):
732 profile = self.getProfileName(profile_key) 732 profile = self.getProfileName(profile_key)
733 if not profile: 733 if not profile:
734 error(_('Asking contacts for a non-existant profile')) 734 error(_('Asking contacts for a non-existant profile'))
735 return {} 735 return {}
780 @param profile_key: %(doc_profile_key)s 780 @param profile_key: %(doc_profile_key)s
781 @return: dict withs values for each key in keys_list. 781 @return: dict withs values for each key in keys_list.
782 if there is no value of a given key, resulting dict will 782 if there is no value of a given key, resulting dict will
783 have nothing with that key nether 783 have nothing with that key nether
784 @raise: exceptions.UnknownEntityError if entity is not in cache 784 @raise: exceptions.UnknownEntityError if entity is not in cache
785 exceptions.ProfileNotInCacheError if profile is not in cache 785 exceptions.ProfileNotInCacheError if profile is not in cache
786 """ 786 """
787 profile = self.getProfileName(profile_key) 787 profile = self.getProfileName(profile_key)
788 if not profile: 788 if not profile:
789 raise exceptions.UnknownProfileError(_('Trying to get entity data for a non-existant profile')) 789 raise exceptions.UnknownProfileError(_('Trying to get entity data for a non-existant profile'))
790 if not profile in self.entitiesCache: 790 if not profile in self.entitiesCache:
817 profile = self.getProfileName(profile_key) 817 profile = self.getProfileName(profile_key)
818 assert(profile) 818 assert(profile)
819 if not self.subscriptions.has_key(profile): 819 if not self.subscriptions.has_key(profile):
820 self.subscriptions[profile] = {} 820 self.subscriptions[profile] = {}
821 self.subscriptions[profile][entity_jid] = _type 821 self.subscriptions[profile][entity_jid] = _type
822 822
823 def delWaitingSub(self, entity_jid, profile_key): 823 def delWaitingSub(self, entity_jid, profile_key):
824 """Called when a subcription request is finished""" 824 """Called when a subcription request is finished"""
825 profile = self.getProfileName(profile_key) 825 profile = self.getProfileName(profile_key)
826 assert(profile) 826 assert(profile)
827 if self.subscriptions.has_key(profile) and self.subscriptions[profile].has_key(entity_jid): 827 if self.subscriptions.has_key(profile) and self.subscriptions[profile].has_key(entity_jid):
828 del self.subscriptions[profile][entity_jid] 828 del self.subscriptions[profile][entity_jid]
829 829
830 def getWaitingSub(self, profile_key): 830 def getWaitingSub(self, profile_key):
831 """Called to get a list of currently waiting subscription requests""" 831 """Called to get a list of currently waiting subscription requests"""
832 profile = self.getProfileName(profile_key) 832 profile = self.getProfileName(profile_key)
833 if not profile: 833 if not profile:
834 error(_('Asking waiting subscriptions for a non-existant profile')) 834 error(_('Asking waiting subscriptions for a non-existant profile'))
835 return {} 835 return {}
836 if not self.subscriptions.has_key(profile): 836 if not self.subscriptions.has_key(profile):
837 return {} 837 return {}
838 838
839 return self.subscriptions[profile] 839 return self.subscriptions[profile]
840 840
841 def getStringParamA(self, name, category, attr="value", profile_key='@DEFAULT@'): 841 def getStringParamA(self, name, category, attr="value", profile_key='@DEFAULT@'):
842 return self.params.getStringParamA(name, category, attr, profile_key) 842 return self.params.getStringParamA(name, category, attr, profile_key)
843 843
844 def getParamA(self, name, category, attr="value", profile_key='@DEFAULT@'): 844 def getParamA(self, name, category, attr="value", profile_key='@DEFAULT@'):
845 return self.params.getParamA(name, category, attr, profile_key) 845 return self.params.getParamA(name, category, attr, profile_key)
846 846
847 def asyncGetParamA(self, name, category, attr="value", profile_key='@DEFAULT@'): 847 def asyncGetParamA(self, name, category, attr="value", profile_key='@DEFAULT@'):
848 return self.params.asyncGetParamA(name, category, attr, profile_key) 848 return self.params.asyncGetParamA(name, category, attr, profile_key)
849 849
850 def asyncGetStringParamA(self, name, category, attr="value", profile_key='@DEFAULT@'): 850 def asyncGetStringParamA(self, name, category, attr="value", profile_key='@DEFAULT@'):
851 return self.params.asyncGetStringParamA(name, category, attr, profile_key) 851 return self.params.asyncGetStringParamA(name, category, attr, profile_key)
852 852
853 def getParamsUI(self, profile_key): 853 def getParamsUI(self, profile_key):
854 return self.params.getParamsUI(profile_key) 854 return self.params.getParamsUI(profile_key)
855 855
856 def getParams(self, profile_key): 856 def getParams(self, profile_key):
857 return self.params.getParams(profile_key) 857 return self.params.getParams(profile_key)
858 858
859 def getParamsForCategory(self, category, profile_key): 859 def getParamsForCategory(self, category, profile_key):
860 return self.params.getParamsForCategory(category, profile_key) 860 return self.params.getParamsForCategory(category, profile_key)
861 861
862 def getParamsCategories(self): 862 def getParamsCategories(self):
863 return self.params.getParamsCategories() 863 return self.params.getParamsCategories()
864 864
865 def setParam(self, name, value, category, profile_key): 865 def setParam(self, name, value, category, profile_key):
866 return self.params.setParam(name, value, category, profile_key) 866 return self.params.setParam(name, value, category, profile_key)
867 867
868 def importParams(self, xml): 868 def importParams(self, xml):
869 return self.params.importParams(xml) 869 return self.params.importParams(xml)
870 870
871 def setDefault(self, name, category, callback, errback=None): 871 def setDefault(self, name, category, callback, errback=None):
872 return self.params.setDefault(name, category, callback, errback) 872 return self.params.setDefault(name, category, callback, errback)