Mercurial > libervia-backend
comparison libervia/backend/plugins/plugin_exp_list_of_interest.py @ 4071:4b842c1fb686
refactoring: renamed `sat` package to `libervia.backend`
author | Goffi <goffi@goffi.org> |
---|---|
date | Fri, 02 Jun 2023 11:49:51 +0200 |
parents | sat/plugins/plugin_exp_list_of_interest.py@524856bd7b19 |
children | 0d7bb4df2343 |
comparison
equal
deleted
inserted
replaced
4070:d10748475025 | 4071:4b842c1fb686 |
---|---|
1 #!/usr/bin/env python3 | |
2 | |
3 | |
4 # SAT plugin to detect language (experimental) | |
5 # Copyright (C) 2009-2021 Jérôme Poisson (goffi@goffi.org) | |
6 | |
7 # This program is free software: you can redistribute it and/or modify | |
8 # it under the terms of the GNU Affero General Public License as published by | |
9 # the Free Software Foundation, either version 3 of the License, or | |
10 # (at your option) any later version. | |
11 | |
12 # This program is distributed in the hope that it will be useful, | |
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of | |
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | |
15 # GNU Affero General Public License for more details. | |
16 | |
17 # You should have received a copy of the GNU Affero General Public License | |
18 # along with this program. If not, see <http://www.gnu.org/licenses/>. | |
19 | |
20 from libervia.backend.core.i18n import _ | |
21 from libervia.backend.core.constants import Const as C | |
22 from libervia.backend.core.xmpp import SatXMPPEntity | |
23 from libervia.backend.core import exceptions | |
24 from libervia.backend.core.log import getLogger | |
25 from libervia.backend.tools.common import data_format | |
26 from libervia.backend.tools.common import uri | |
27 from wokkel import disco, iwokkel, pubsub | |
28 from zope.interface import implementer | |
29 from twisted.internet import defer | |
30 from twisted.words.protocols.jabber import error as jabber_error, jid | |
31 from twisted.words.protocols.jabber.xmlstream import XMPPHandler | |
32 from twisted.words.xish import domish | |
33 | |
34 log = getLogger(__name__) | |
35 | |
36 | |
37 PLUGIN_INFO = { | |
38 C.PI_NAME: "List of Interest", | |
39 C.PI_IMPORT_NAME: "LIST_INTEREST", | |
40 C.PI_TYPE: "EXP", | |
41 C.PI_PROTOCOLS: [], | |
42 C.PI_DEPENDENCIES: ["XEP-0060", "XEP-0329", "XEP-0106"], | |
43 C.PI_RECOMMENDATIONS: [], | |
44 C.PI_MAIN: "ListInterest", | |
45 C.PI_HANDLER: "yes", | |
46 C.PI_DESCRIPTION: _("Experimental handling of interesting XMPP locations"), | |
47 } | |
48 | |
49 NS_LIST_INTEREST = "https://salut-a-toi/protocol/list-interest:0" | |
50 | |
51 | |
52 class ListInterest(object): | |
53 namespace = NS_LIST_INTEREST | |
54 | |
55 def __init__(self, host): | |
56 log.info(_("List of Interest plugin initialization")) | |
57 self.host = host | |
58 self._p = self.host.plugins["XEP-0060"] | |
59 host.bridge.add_method( | |
60 "interests_list", | |
61 ".plugin", | |
62 in_sign="ssss", | |
63 out_sign="aa{ss}", | |
64 method=self._list_interests, | |
65 async_=True, | |
66 ) | |
67 host.bridge.add_method( | |
68 "interests_file_sharing_register", | |
69 ".plugin", | |
70 in_sign="sssssss", | |
71 out_sign="", | |
72 method=self._register_file_sharing, | |
73 async_=True, | |
74 ) | |
75 host.bridge.add_method( | |
76 "interest_retract", | |
77 ".plugin", | |
78 in_sign="sss", | |
79 out_sign="", | |
80 method=self._interest_retract, | |
81 async_=True, | |
82 ) | |
83 | |
84 def get_handler(self, client): | |
85 return ListInterestHandler(self) | |
86 | |
87 @defer.inlineCallbacks | |
88 def createNode(self, client): | |
89 try: | |
90 # TODO: check auto-create, no need to create node first if available | |
91 options = {self._p.OPT_ACCESS_MODEL: self._p.ACCESS_WHITELIST} | |
92 yield self._p.createNode( | |
93 client, | |
94 client.jid.userhostJID(), | |
95 nodeIdentifier=NS_LIST_INTEREST, | |
96 options=options, | |
97 ) | |
98 except jabber_error.StanzaError as e: | |
99 if e.condition == "conflict": | |
100 log.debug(_("requested node already exists")) | |
101 | |
102 async def register_pubsub(self, client, namespace, service, node, item_id=None, | |
103 creator=False, name=None, element=None, extra=None): | |
104 """Register an interesting element in personal list | |
105 | |
106 @param namespace(unicode): namespace of the interest | |
107 this is used as a cache, to avoid the need to retrieve the item only to get | |
108 its namespace | |
109 @param service(jid.JID): target pubsub service | |
110 @param node(unicode): target pubsub node | |
111 @param item_id(unicode, None): target pubsub id | |
112 @param creator(bool): True if client's profile is the creator of the node | |
113 This is used a cache, to avoid the need to retrieve affiliations | |
114 @param name(unicode, None): name of the interest | |
115 @param element(domish.Element, None): element to attach | |
116 may be used to cache some extra data | |
117 @param extra(dict, None): extra data, key can be: | |
118 - thumb_url: http(s) URL of a thumbnail | |
119 """ | |
120 if extra is None: | |
121 extra = {} | |
122 await self.createNode(client) | |
123 interest_elt = domish.Element((NS_LIST_INTEREST, "interest")) | |
124 interest_elt["namespace"] = namespace | |
125 if name is not None: | |
126 interest_elt['name'] = name | |
127 thumb_url = extra.get('thumb_url') | |
128 if thumb_url: | |
129 interest_elt['thumb_url'] = thumb_url | |
130 pubsub_elt = interest_elt.addElement("pubsub") | |
131 pubsub_elt["service"] = service.full() | |
132 pubsub_elt["node"] = node | |
133 if item_id is not None: | |
134 pubsub_elt["item"] = item_id | |
135 if creator: | |
136 pubsub_elt["creator"] = C.BOOL_TRUE | |
137 if element is not None: | |
138 pubsub_elt.addChild(element) | |
139 uri_kwargs = { | |
140 "path": service.full(), | |
141 "node": node | |
142 } | |
143 if item_id: | |
144 uri_kwargs['id'] = item_id | |
145 interest_uri = uri.build_xmpp_uri("pubsub", **uri_kwargs) | |
146 # we use URI of the interest as item id to avoid duplicates | |
147 item_elt = pubsub.Item(interest_uri, payload=interest_elt) | |
148 await self._p.publish( | |
149 client, client.jid.userhostJID(), NS_LIST_INTEREST, items=[item_elt] | |
150 ) | |
151 | |
152 def _register_file_sharing( | |
153 self, service, repos_type, namespace, path, name, extra_raw, | |
154 profile | |
155 ): | |
156 client = self.host.get_client(profile) | |
157 extra = data_format.deserialise(extra_raw) | |
158 | |
159 return defer.ensureDeferred(self.register_file_sharing( | |
160 client, jid.JID(service), repos_type or None, namespace or None, path or None, | |
161 name or None, extra | |
162 )) | |
163 | |
164 def normalise_file_sharing_service(self, client, service): | |
165 # FIXME: Q&D fix as the bare file sharing service JID will lead to user own | |
166 # repository, which thus would not be the same for the host and the guest. | |
167 # By specifying the user part, we for the use of the host repository. | |
168 # A cleaner way should be implemented | |
169 if service.user is None: | |
170 service.user = self.host.plugins['XEP-0106'].escape(client.jid.user) | |
171 | |
172 def get_file_sharing_id(self, service, namespace, path): | |
173 return f"{service}_{namespace or ''}_{path or ''}" | |
174 | |
175 async def register_file_sharing( | |
176 self, client, service, repos_type=None, namespace=None, path=None, name=None, | |
177 extra=None): | |
178 """Register an interesting file repository in personal list | |
179 | |
180 @param service(jid.JID): service of the file repository | |
181 @param repos_type(unicode): type of the repository | |
182 @param namespace(unicode, None): namespace of the repository | |
183 @param path(unicode, None): path of the repository | |
184 @param name(unicode, None): name of the repository | |
185 @param extra(dict, None): same as [register_pubsub] | |
186 """ | |
187 if extra is None: | |
188 extra = {} | |
189 self.normalise_file_sharing_service(client, service) | |
190 await self.createNode(client) | |
191 item_id = self.get_file_sharing_id(service, namespace, path) | |
192 interest_elt = domish.Element((NS_LIST_INTEREST, "interest")) | |
193 interest_elt["namespace"] = self.host.get_namespace("fis") | |
194 if name is not None: | |
195 interest_elt['name'] = name | |
196 thumb_url = extra.get('thumb_url') | |
197 if thumb_url: | |
198 interest_elt['thumb_url'] = thumb_url | |
199 | |
200 file_sharing_elt = interest_elt.addElement("file_sharing") | |
201 file_sharing_elt["service"] = service.full() | |
202 if repos_type is not None: | |
203 file_sharing_elt["type"] = repos_type | |
204 if namespace is not None: | |
205 file_sharing_elt["namespace"] = namespace | |
206 if path is not None: | |
207 file_sharing_elt["path"] = path | |
208 item_elt = pubsub.Item(item_id, payload=interest_elt) | |
209 await self._p.publish( | |
210 client, client.jid.userhostJID(), NS_LIST_INTEREST, items=[item_elt] | |
211 ) | |
212 | |
213 def _list_interests_serialise(self, interests_data): | |
214 interests = [] | |
215 for item_elt in interests_data[0]: | |
216 interest_data = {"id": item_elt['id']} | |
217 interest_elt = item_elt.interest | |
218 if interest_elt.hasAttribute('namespace'): | |
219 interest_data['namespace'] = interest_elt.getAttribute('namespace') | |
220 if interest_elt.hasAttribute('name'): | |
221 interest_data['name'] = interest_elt.getAttribute('name') | |
222 if interest_elt.hasAttribute('thumb_url'): | |
223 interest_data['thumb_url'] = interest_elt.getAttribute('thumb_url') | |
224 elt = interest_elt.firstChildElement() | |
225 if elt.uri != NS_LIST_INTEREST: | |
226 log.warning("unexpected child element, ignoring: {xml}".format( | |
227 xml = elt.toXml())) | |
228 continue | |
229 if elt.name == 'pubsub': | |
230 interest_data.update({ | |
231 "type": "pubsub", | |
232 "service": elt['service'], | |
233 "node": elt['node'], | |
234 }) | |
235 for attr in ('item', 'creator'): | |
236 if elt.hasAttribute(attr): | |
237 interest_data[attr] = elt[attr] | |
238 elif elt.name == 'file_sharing': | |
239 interest_data.update({ | |
240 "type": "file_sharing", | |
241 "service": elt['service'], | |
242 }) | |
243 if elt.hasAttribute('type'): | |
244 interest_data['subtype'] = elt['type'] | |
245 for attr in ('files_namespace', 'path'): | |
246 if elt.hasAttribute(attr): | |
247 interest_data[attr] = elt[attr] | |
248 else: | |
249 log.warning("unknown element, ignoring: {xml}".format(xml=elt.toXml())) | |
250 continue | |
251 interests.append(interest_data) | |
252 | |
253 return interests | |
254 | |
255 def _list_interests(self, service, node, namespace, profile): | |
256 service = jid.JID(service) if service else None | |
257 node = node or None | |
258 namespace = namespace or None | |
259 client = self.host.get_client(profile) | |
260 d = defer.ensureDeferred(self.list_interests(client, service, node, namespace)) | |
261 d.addCallback(self._list_interests_serialise) | |
262 return d | |
263 | |
264 async def list_interests(self, client, service=None, node=None, namespace=None): | |
265 """Retrieve list of interests | |
266 | |
267 @param service(jid.JID, None): service to use | |
268 None to use own PEP | |
269 @param node(unicode, None): node to use | |
270 None to use default node | |
271 @param namespace(unicode, None): filter interests of this namespace | |
272 None to retrieve all interests | |
273 @return: same as [XEP_0060.get_items] | |
274 """ | |
275 # TODO: if a MAM filter were available, it would improve performances | |
276 if not node: | |
277 node = NS_LIST_INTEREST | |
278 items, metadata = await self._p.get_items(client, service, node) | |
279 if namespace is not None: | |
280 filtered_items = [] | |
281 for item in items: | |
282 try: | |
283 interest_elt = next(item.elements(NS_LIST_INTEREST, "interest")) | |
284 except StopIteration: | |
285 log.warning(_("Missing interest element: {xml}").format( | |
286 xml=item.toXml())) | |
287 continue | |
288 if interest_elt.getAttribute("namespace") == namespace: | |
289 filtered_items.append(item) | |
290 items = filtered_items | |
291 | |
292 return (items, metadata) | |
293 | |
294 def _interest_retract(self, service_s, item_id, profile_key): | |
295 d = self._p._retract_item( | |
296 service_s, NS_LIST_INTEREST, item_id, True, profile_key) | |
297 d.addCallback(lambda __: None) | |
298 return d | |
299 | |
300 async def get(self, client: SatXMPPEntity, item_id: str) -> dict: | |
301 """Retrieve a specific interest in profile's list""" | |
302 items_data = await self._p.get_items(client, None, NS_LIST_INTEREST, item_ids=[item_id]) | |
303 try: | |
304 return self._list_interests_serialise(items_data)[0] | |
305 except IndexError: | |
306 raise exceptions.NotFound | |
307 | |
308 | |
309 @implementer(iwokkel.IDisco) | |
310 class ListInterestHandler(XMPPHandler): | |
311 | |
312 def __init__(self, plugin_parent): | |
313 self.plugin_parent = plugin_parent | |
314 | |
315 def getDiscoInfo(self, requestor, target, nodeIdentifier=""): | |
316 return [ | |
317 disco.DiscoFeature(NS_LIST_INTEREST), | |
318 ] | |
319 | |
320 def getDiscoItems(self, requestor, target, nodeIdentifier=""): | |
321 return [] |