comparison sat/core/xmpp.py @ 3249:f16c96c7a91a

core (xmpp): helper method to launch a plugin method: the `p` client method can be used to launch a method for a plugin, with a default value if the plugin is not available (or an Exception to raise).
author Goffi <goffi@goffi.org>
date Fri, 03 Apr 2020 18:02:31 +0200
parents b10d207f95f9
children 6cf4bd6972c2
comparison
equal deleted inserted replaced
3248:5d67502bdc8c 3249:f16c96c7a91a
58 # we use 2 "@" which is illegal in a jid, to be sure we are not mixing keys 58 # we use 2 "@" which is illegal in a jid, to be sure we are not mixing keys
59 # with roster jids 59 # with roster jids
60 ROSTER_VER_KEY = "@version@" 60 ROSTER_VER_KEY = "@version@"
61 61
62 62
63 class ClientPluginWrapper:
64 """Use a plugin with default value if plugin is missing"""
65
66 def __init__(self, client, plugin_name, missing):
67 self.client = client
68 self.plugin = client.host_app.plugins.get(plugin_name)
69 if self.plugin is None:
70 self.plugin_name = plugin_name
71 self.missing = missing
72
73 def __getattr__(self, attr):
74 if self.plugin is None:
75 missing = self.missing
76 if isinstance(missing, type) and issubclass(missing, Exception):
77 raise missing(f"plugin {self.plugin_name!r} is not available")
78 elif isinstance(missing, Exception):
79 raise missing
80 else:
81 return lambda *args, **kwargs: missing
82 return partial(getattr(self.plugin, attr), self.client)
83
84
63 class SatXMPPEntity: 85 class SatXMPPEntity:
64 """Common code for Client and Component""" 86 """Common code for Client and Component"""
65 # profile is added there when startConnection begins and removed when it is finished 87 # profile is added there when startConnection begins and removed when it is finished
66 profiles_connecting = set() 88 profiles_connecting = set()
67 89
734 ) 756 )
735 else: 757 else:
736 log.warning(_("No message found")) 758 log.warning(_("No message found"))
737 return data 759 return data
738 760
761 ## helper methods ##
762
763 def p(self, plugin_name, missing=exceptions.MissingModule):
764 """Get a plugin if available
765
766 @param plugin_name(str): name of the plugin
767 @param missing(object): value to return if plugin is missing
768 if it is a subclass of Exception, it will be raised with a helping str as
769 argument.
770 @return (object): requested plugin wrapper, or default value
771 The plugin wrapper will return the method with client set as first
772 positional argument
773 """
774 return ClientPluginWrapper(self, plugin_name, missing)
775
739 776
740 @implementer(iwokkel.IDisco) 777 @implementer(iwokkel.IDisco)
741 class SatXMPPClient(SatXMPPEntity, wokkel_client.XMPPClient): 778 class SatXMPPClient(SatXMPPEntity, wokkel_client.XMPPClient):
742 trigger_suffix = "" 779 trigger_suffix = ""
743 is_component = False 780 is_component = False