Welcome to mirror list, hosted at ThFree Co, Russian Federation.

presence.py « modules « common « gajim - dev.gajim.org/gajim/gajim.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 28a3a607ac50e986cd8ae750540a955780d984ad (plain)
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
# This file is part of Gajim.
#
# Gajim 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; version 3 only.
#
# Gajim 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 Gajim. If not, see <http://www.gnu.org/licenses/>.

# Presence handler

from __future__ import annotations

from typing import Any

import time

import nbxmpp
from nbxmpp.namespaces import Namespace
from nbxmpp.protocol import JID
from nbxmpp.structs import PresenceProperties
from nbxmpp.structs import StanzaHandler

from gajim.common import app
from gajim.common import idle
from gajim.common import types
from gajim.common.events import PresenceReceived
from gajim.common.events import ShowChanged
from gajim.common.events import SubscribedPresenceReceived
from gajim.common.events import SubscribePresenceReceived
from gajim.common.events import UnsubscribedPresenceReceived
from gajim.common.i18n import _
from gajim.common.modules.base import BaseModule
from gajim.common.structs import PresenceData


class Presence(BaseModule):

    _nbxmpp_extends = 'BasePresence'
    _nbxmpp_methods = [
        'subscribed',
    ]

    def __init__(self, con: types.Client) -> None:
        BaseModule.__init__(self, con)

        self.handlers = [
            StanzaHandler(name='presence',
                          callback=self._presence_received,
                          typ='available',
                          priority=50),
            StanzaHandler(name='presence',
                          callback=self._presence_received,
                          typ='unavailable',
                          priority=50),
            StanzaHandler(name='presence',
                          callback=self._subscribe_received,
                          typ='subscribe',
                          priority=49),
            StanzaHandler(name='presence',
                          callback=self._subscribed_received,
                          typ='subscribed',
                          priority=49),
            StanzaHandler(name='presence',
                          callback=self._unsubscribe_received,
                          typ='unsubscribe',
                          priority=49),
            StanzaHandler(name='presence',
                          callback=self._unsubscribed_received,
                          typ='unsubscribed',
                          priority=49),
        ]

        self._presence_store: dict[JID, PresenceData] = {}

        # keep the jids we auto added (transports contacts) to not send the
        # SUBSCRIBED event to GUI
        self.automatically_added: list[str] = []

        # list of jid to auto-authorize
        self._jids_for_auto_auth: set[str] = set()

    def _presence_received(self,
                           _con: types.xmppClient,
                           stanza: nbxmpp.protocol.Presence,
                           properties: PresenceProperties
                           ) -> None:

        if properties.from_muc:
            # MUC occupant presences are already handled in MUC module
            return

        contact = self._con.get_module('Contacts').get_contact(properties.jid)
        if contact.is_groupchat:
            # Presence from the MUC itself, used for MUC avatar
            # handled in VCardAvatars module
            return

        self._log.info('Received from %s', properties.jid)

        presence_data = PresenceData.from_presence(properties)
        self._presence_store[properties.jid] = presence_data

        contact.update_presence(presence_data)

        if properties.is_self_presence:
            app.ged.raise_event(ShowChanged(account=self._account,
                                            show=properties.show.value))
            return

        jid = properties.jid.bare
        roster_item = self._con.get_module('Roster').get_item(jid)
        if not properties.is_self_bare and roster_item is None:
            # Handle only presence from roster contacts
            self._log.warning('Unknown presence received')
            self._log.warning(stanza)
            return

        show = properties.show.value
        if properties.type.is_unavailable:
            show = 'offline'

        event_attrs: dict[str, Any] = {
            'account': self._account,
            'conn': self._con,
            'stanza': stanza,
            'prio': properties.priority,
            'need_add_in_roster': False,
            'popup': False,
            'ptype': properties.type.value,
            'jid': properties.jid.new_as_bare(),
            'resource': properties.jid.resource,
            'id_': properties.id,
            'fjid': str(properties.jid),
            'timestamp': properties.timestamp,
            'avatar_sha': properties.avatar_sha,
            'user_nick': properties.nickname,
            'show': show,
            'new_show': show,
            'old_show': 0,
            'status': properties.status,
            'contact_list': [],
            'contact': None,
        }

        app.ged.raise_event(PresenceReceived(**event_attrs))

    def _subscribe_received(self,
                            _con: types.xmppClient,
                            _stanza: nbxmpp.protocol.Presence,
                            properties: PresenceProperties
                            ) -> None:
        jid = properties.jid.bare
        fjid = str(properties.jid)

        is_transport = app.jid_is_transport(fjid)
        auto_auth = app.settings.get_account_setting(self._account, 'autoauth')

        self._log.info('Received Subscribe: %s, transport: %s, '
                       'auto_auth: %s, user_nick: %s',
                       properties.jid, is_transport,
                       auto_auth, properties.nickname)

        if auto_auth or jid in self._jids_for_auto_auth:
            self._log.info('Auto respond with subscribed: %s', jid)
            self.subscribed(jid)
            return

        status = (properties.status or
                  _('I would like to add you to my roster.'))

        app.ged.raise_event(SubscribePresenceReceived(
            conn=self._con,
            account=self._account,
            jid=jid,
            fjid=fjid,
            status=status,
            user_nick=properties.nickname,
            is_transport=is_transport))

        raise nbxmpp.NodeProcessed

    def _subscribed_received(self,
                             _con: types.xmppClient,
                             _stanza: nbxmpp.protocol.Presence,
                             properties: PresenceProperties
                             ) -> None:
        jid = properties.jid.bare
        self._log.info('Received Subscribed: %s', properties.jid)
        if jid in self.automatically_added:
            self.automatically_added.remove(jid)
            raise nbxmpp.NodeProcessed

        app.ged.raise_event(SubscribedPresenceReceived(
            account=self._account,
            jid=properties.jid))
        raise nbxmpp.NodeProcessed

    def _unsubscribe_received(self,
                              _con: types.xmppClient,
                              _stanza: nbxmpp.protocol.Presence,
                              properties: PresenceProperties
                              ) -> None:
        self._log.info('Received Unsubscribe: %s', properties.jid)
        raise nbxmpp.NodeProcessed

    def _unsubscribed_received(self,
                               _con: types.xmppClient,
                               _stanza: nbxmpp.protocol.Presence,
                               properties: PresenceProperties
                               ) -> None:
        self._log.info('Received Unsubscribed: %s', properties.jid)
        app.ged.raise_event(UnsubscribedPresenceReceived(
            conn=self._con,
            account=self._account,
            jid=properties.jid.bare))
        raise nbxmpp.NodeProcessed

    def unsubscribed(self, jid: JID | str) -> None:
        self._log.info('Unsubscribed: %s', jid)
        self._jids_for_auto_auth.discard(str(jid))
        self._nbxmpp('BasePresence').unsubscribed(jid)

    def unsubscribe(self, jid: JID | str) -> None:
        self._log.info('Unsubscribe from %s', jid)
        self._jids_for_auto_auth.discard(str(jid))
        self._nbxmpp('BasePresence').unsubscribe(jid)

    def subscribe(self,
                  jid: JID | str,
                  msg: str | None = None,
                  name: str | None = None,
                  groups: list[str] | set[str] | None = None,
                  auto_auth: bool = False
                  ) -> None:
        self._log.info('Request Subscription to %s', jid)

        if auto_auth:
            self._jids_for_auto_auth.add(jid)

        self._con.get_module('Roster').set_item(jid, name, groups=groups)
        self._nbxmpp('BasePresence').subscribe(jid,
                                               status=msg,
                                               nick=app.nicks[self._account])

    def get_presence(self,
                     to: str | None = None,
                     typ: str | None = None,
                     priority: int | None = None,
                     show: str | None = None,
                     status: str | None = None,
                     nick: str | None = None,
                     caps: bool = True,
                     idle_time: bool = False
                     ) -> nbxmpp.Presence:
        if show not in ('chat', 'away', 'xa', 'dnd'):
            # Gajim sometimes passes invalid show values here
            # until this is fixed this is a workaround
            show = None
        presence = nbxmpp.Presence(to, typ, priority, show, status)
        if nick is not None:
            nick_tag = presence.setTag('nick', namespace=Namespace.NICK)
            nick_tag.setData(nick)

        if (idle_time and
                app.is_installed('IDLE') and
                app.settings.get('autoaway')):
            idle_sec = idle.Monitor.get_idle_sec()
            time_ = time.strftime('%Y-%m-%dT%H:%M:%SZ',
                                  time.gmtime(time.time() - idle_sec))

            idle_node = presence.setTag('idle', namespace=Namespace.IDLE)
            idle_node.setAttr('since', time_)

        caps = self._con.get_module('Caps').caps
        if caps is not None and typ != 'unavailable':
            presence.setTag('c',
                            namespace=Namespace.CAPS,
                            attrs=caps._asdict())

        return presence

    def send_presence(self, *args: Any, **kwargs: Any) -> None:
        if not app.account_is_connected(self._account):
            return
        presence = self.get_presence(*args, **kwargs)
        app.plugin_manager.extension_point(
            'send-presence', self._account, presence)
        self._log.debug('Send presence:\n%s', presence)
        self._con.connection.send(presence)