comparison sat/plugins/plugin_xep_0163.py @ 2562:26edcf3a30eb

core, setup: huge cleaning: - moved directories from src and frontends/src to sat and sat_frontends, which is the recommanded naming convention - move twisted directory to root - removed all hacks from setup.py, and added missing dependencies, it is now clean - use https URL for website in setup.py - removed "Environment :: X11 Applications :: GTK", as wix is deprecated and removed - renamed sat.sh to sat and fixed its installation - added python_requires to specify Python version needed - replaced glib2reactor which use deprecated code by gtk3reactor sat can now be installed directly from virtualenv without using --system-site-packages anymore \o/
author Goffi <goffi@goffi.org>
date Mon, 02 Apr 2018 19:44:50 +0200
parents src/plugins/plugin_xep_0163.py@0046283a285d
children 56f94936df1e
comparison
equal deleted inserted replaced
2561:bd30dc3ffe5a 2562:26edcf3a30eb
1 #!/usr/bin/env python2
2 # -*- coding: utf-8 -*-
3
4 # SAT plugin for Personal Eventing Protocol (xep-0163)
5 # Copyright (C) 2009-2018 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 sat.core.i18n import _
21 from sat.core import exceptions
22 from sat.core.constants import Const as C
23 from sat.core.log import getLogger
24 log = getLogger(__name__)
25 from twisted.words.xish import domish
26
27 from wokkel import disco, pubsub
28 from wokkel.formats import Mood
29
30 NS_USER_MOOD = 'http://jabber.org/protocol/mood'
31
32 PLUGIN_INFO = {
33 C.PI_NAME: "Personal Eventing Protocol Plugin",
34 C.PI_IMPORT_NAME: "XEP-0163",
35 C.PI_TYPE: "XEP",
36 C.PI_PROTOCOLS: ["XEP-0163", "XEP-0107"],
37 C.PI_DEPENDENCIES: ["XEP-0060"],
38 C.PI_MAIN: "XEP_0163",
39 C.PI_HANDLER: "no",
40 C.PI_DESCRIPTION: _("""Implementation of Personal Eventing Protocol""")
41 }
42
43
44 class XEP_0163(object):
45
46 def __init__(self, host):
47 log.info(_("PEP plugin initialization"))
48 self.host = host
49 self.pep_events = set()
50 self.pep_out_cb = {}
51 host.trigger.add("PubSub Disco Info", self.disoInfoTrigger)
52 host.bridge.addMethod("PEPSend", ".plugin", in_sign='sa{ss}s', out_sign='', method=self.PEPSend, async=True) # args: type(MOOD, TUNE, etc), data, profile_key;
53 self.addPEPEvent("MOOD", NS_USER_MOOD, self.userMoodCB, self.sendMood)
54
55 def disoInfoTrigger(self, disco_info, profile):
56 """Add info from managed PEP
57
58 @param disco_info: list of disco feature as returned by PubSub,
59 will be filled with PEP features
60 @param profile: profile we are handling
61 """
62 disco_info.extend(map(disco.DiscoFeature, self.pep_events))
63 return True
64
65 def addPEPEvent(self, event_type, node, in_callback, out_callback=None, notify=True):
66 """Add a Personal Eventing Protocol event manager
67
68 @param event_type(unicode): type of the event (always uppercase), can be MOOD, TUNE, etc
69 @param node(unicode): namespace of the node (e.g. http://jabber.org/protocol/mood for User Mood)
70 @param in_callback(callable): method to call when this event occur
71 the callable will be called with (itemsEvent, profile) as arguments
72 @param out_callback(callable,None): method to call when we want to publish this event (must return a deferred)
73 the callable will be called when sendPEPEvent is called
74 @param notify(bool): add autosubscribe (+notify) if True
75 """
76 if out_callback:
77 self.pep_out_cb[event_type] = out_callback
78 self.pep_events.add(node)
79 if notify:
80 self.pep_events.add(node + "+notify")
81 def filterPEPEvent(client, itemsEvent):
82 """Ignore messages which are not coming from PEP (i.e. main server)
83
84 @param itemsEvent(pubsub.ItemsEvent): pubsub event
85 """
86 if itemsEvent.sender.user or itemsEvent.sender.resource:
87 log.debug("ignoring non PEP event from {} (profile={})".format(itemsEvent.sender.full(), client.profile))
88 return
89 in_callback(itemsEvent, client.profile)
90
91 self.host.plugins["XEP-0060"].addManagedNode(node, items_cb=filterPEPEvent)
92
93 def sendPEPEvent(self, node, data, profile):
94 """Publish the event data
95
96 @param node(unicode): node namespace
97 @param data: domish.Element to use as payload
98 @param profile: profile which send the data
99 """
100 client = self.host.getClient(profile)
101 item = pubsub.Item(payload=data)
102 return self.host.plugins["XEP-0060"].publish(client, None, node, [item])
103
104 def PEPSend(self, event_type, data, profile_key=C.PROF_KEY_NONE):
105 """Send personal event after checking the data is alright
106
107 @param event_type: type of event (eg: MOOD, TUNE), must be in self.pep_out_cb.keys()
108 @param data: dict of {string:string} of event_type dependant data
109 @param profile_key: profile who send the event
110 """
111 profile = self.host.memory.getProfileName(profile_key)
112 if not profile:
113 log.error(_(u'Trying to send personal event with an unknown profile key [%s]') % profile_key)
114 raise exceptions.ProfileUnknownError
115 if not event_type in self.pep_out_cb.keys():
116 log.error(_('Trying to send personal event for an unknown type'))
117 raise exceptions.DataError('Type unknown')
118 return self.pep_out_cb[event_type](data, profile)
119
120 def userMoodCB(self, itemsEvent, profile):
121 if not itemsEvent.items:
122 log.debug(_("No item found"))
123 return
124 try:
125 mood_elt = [child for child in itemsEvent.items[0].elements() if child.name == "mood"][0]
126 except IndexError:
127 log.error(_("Can't find mood element in mood event"))
128 return
129 mood = Mood.fromXml(mood_elt)
130 if not mood:
131 log.debug(_("No mood found"))
132 return
133 self.host.bridge.psEvent(C.PS_PEP, itemsEvent.sender.full(), itemsEvent.nodeIdentifier,
134 "MOOD", {"mood": mood.value or "", "text": mood.text or ""}, profile)
135
136 def sendMood(self, data, profile):
137 """Send XEP-0107's User Mood
138
139 @param data: must include mood and text
140 @param profile: profile which send the mood"""
141 try:
142 value = data['mood'].lower()
143 text = data['text'] if 'text' in data else ''
144 except KeyError:
145 raise exceptions.DataError("Mood data must contain at least 'mood' key")
146 mood = UserMood(value, text)
147 return self.sendPEPEvent(NS_USER_MOOD, mood, profile)
148
149
150 class UserMood(Mood, domish.Element):
151 """Improved wokkel Mood which is also a domish.Element"""
152
153 def __init__(self, value, text=None):
154 Mood.__init__(self, value, text)
155 domish.Element.__init__(self, (NS_USER_MOOD, 'mood'))
156 self.addElement(value)
157 if text:
158 self.addElement('text', content=text)