roster.py 11.2 KB
Newer Older
louiz’'s avatar
louiz’ committed
1
# Copyright 2010-2011 Florent Le Coz <louiz@louiz.org>
2 3 4 5
#
# This file is part of Poezio.
#
# Poezio is free software: you can redistribute it and/or modify
6
# it under the terms of the zlib license. See the COPYING file.
7 8 9
"""
Defines the Roster and RosterGroup classes
"""
10 11
import logging
log = logging.getLogger(__name__)
12

13 14
from typing import List

mathieui's avatar
mathieui committed
15 16 17
from poezio.config import config
from poezio.contact import Contact
from poezio.roster_sorting import SORTING_METHODS, GROUP_SORTING_METHODS
18 19

from os import path as p
20
from datetime import datetime
mathieui's avatar
mathieui committed
21
from poezio.common import safeJID
louiz’'s avatar
louiz’ committed
22
from slixmpp.exceptions import IqError, IqTimeout
23
from slixmpp import JID
24

mathieui's avatar
mathieui committed
25

26
class Roster:
mathieui's avatar
mathieui committed
27
    """
louiz’'s avatar
louiz’ committed
28
    The proxy class to get the roster from slixmpp.
29
    Caches Contact and RosterGroup objects.
mathieui's avatar
mathieui committed
30
    """
31

32
    DEFAULT_FILTER = (lambda x, y: None, None)
mathieui's avatar
mathieui committed
33

34
    def __init__(self):
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
        self.__node = None

        # A tuple(function, *args) function to filter contacts
        # on search, for example
        self.contact_filter = self.DEFAULT_FILTER
        self.groups = {}
        self.contacts = {}
        self.length = 0
        self.connected = 0
        self.folded_groups = []

        # Used for caching roster infos
        self.last_built = datetime.now()
        self.last_modified = datetime.now()

    def reset(self):
51
        """
louiz’'s avatar
louiz’ committed
52
        node: the RosterSingle from slixmpp
53 54
        """
        self.__node = None
55 56 57 58

        # A tuple(function, *args) function to filter contacts
        # on search, for example
        self.contact_filter = self.DEFAULT_FILTER
mathieui's avatar
mathieui committed
59 60
        self.folded_groups = set(
            config.get('folded_roster_groups', section='var').split(':'))
61 62
        self.groups = {}
        self.contacts = {}
mathieui's avatar
mathieui committed
63 64
        self.length = 0
        self.connected = 0
65

66 67 68 69 70 71 72 73 74 75 76
        # Used for caching roster infos
        self.last_built = datetime.now()
        self.last_modified = datetime.now()

    def modified(self):
        self.last_modified = datetime.now()

    @property
    def needs_rebuild(self):
        return self.last_modified >= self.last_built

77 78
    def __getitem__(self, key):
        """Get a Contact from his bare JID"""
79
        key = safeJID(key).bare
80 81 82 83 84 85
        if key in self.contacts and self.contacts[key] is not None:
            return self.contacts[key]
        if key in self.jids():
            contact = Contact(self.__node[key])
            self.contacts[key] = contact
            return contact
86

87 88 89
    def __setitem__(self, key, value):
        """Set the a Contact value for the bare jid key"""
        self.contacts[key] = value
90

mathieui's avatar
mathieui committed
91 92 93 94 95 96 97 98
    def remove(self, jid):
        """Send a removal iq to the server"""
        jid = safeJID(jid).bare
        if self.__node[jid]:
            try:
                self.__node[jid].send_presence(ptype='unavailable')
                self.__node.remove(jid)
            except (IqError, IqTimeout):
mathieui's avatar
mathieui committed
99
                log.debug('IqError when removing %s:', jid, exc_info=True)
mathieui's avatar
mathieui committed
100

101
    def __delitem__(self, jid):
mathieui's avatar
mathieui committed
102
        """Remove a contact from the roster view"""
103
        jid = safeJID(jid).bare
104
        contact = self[jid]
mathieui's avatar
mathieui committed
105 106
        if not contact:
            return
mathieui's avatar
mathieui committed
107 108
        del self.contacts[contact.bare_jid]

109 110 111 112
        for group in list(self.groups.values()):
            group.remove(contact)
            if not group:
                del self.groups[group.name]
mathieui's avatar
mathieui committed
113
        self.modified()
114

115 116 117 118 119 120
    def __iter__(self):
        """Iterate over the jids of the contacts"""
        return iter(self.contacts.values())

    def __contains__(self, key):
        """True if the bare jid is in the roster, false otherwise"""
121
        return safeJID(key).bare in self.jids()
122

mathieui's avatar
mathieui committed
123 124 125 126 127
    @property
    def jid(self):
        """Our JID"""
        return self.__node.jid

128
    def get_and_set(self, jid):
mathieui's avatar
mathieui committed
129 130
        contact = self.contacts.get(jid)
        if contact is None:
131 132 133
            contact = Contact(self.__node[jid])
            self.contacts[jid] = contact
            return contact
mathieui's avatar
mathieui committed
134
        return contact
135

mathieui's avatar
mathieui committed
136
    def set_node(self, value):
louiz’'s avatar
louiz’ committed
137
        """Set the slixmpp RosterSingle for our roster"""
mathieui's avatar
mathieui committed
138 139
        self.__node = value

140
    def get_groups(self, sort=''):
mathieui's avatar
mathieui committed
141
        """Return a list of the RosterGroups"""
142
        group_list = sorted(
mathieui's avatar
mathieui committed
143 144
            (group for group in self.groups.values() if group),
            key=lambda x: x.name.lower() if x.name else '')
145

146
        for sorting in sort.split(':'):
147 148 149 150 151 152
            if sorting == 'reverse':
                group_list = list(reversed(group_list))
            else:
                method = GROUP_SORTING_METHODS.get(sorting, lambda x: 0)
                group_list = sorted(group_list, key=method)
        return group_list
mathieui's avatar
mathieui committed
153

154 155 156 157
    def get_group(self, name):
        """Return a group or create it if not present"""
        if name in self.groups:
            return self.groups[name]
mathieui's avatar
mathieui committed
158 159
        self.groups[name] = RosterGroup(
            name, folded=name in self.folded_groups)
160 161 162 163 164

    def add(self, jid):
        """Subscribe to a jid"""
        self.__node.subscribe(jid)

165
    def jids(self) -> List[JID]:
166
        """List of the contact JIDS"""
167 168 169 170 171
        l = []
        for key in self.__node.keys():
            contact = self.get_and_set(key)
            if key != self.jid and (contact and self.exists(contact)):
                l.append(key)
mathieui's avatar
mathieui committed
172
        self.update_size(l)
173
        return l
174

mathieui's avatar
mathieui committed
175 176 177 178 179
    def update_size(self, jids=None):
        if jids is None:
            jids = self.jids()
        self.length = len(jids)

louiz’'s avatar
louiz’ committed
180 181
    def get_contacts(self):
        """
182
        Return a list of all the contacts
louiz’'s avatar
louiz’ committed
183
        """
184
        return [self[jid] for jid in self.jids()]
louiz’'s avatar
louiz’ committed
185

mathieui's avatar
mathieui committed
186 187 188 189 190 191 192
    def get_contacts_sorted_filtered(self, sort=''):
        """
        Return a list of all the contacts sorted with a criteria
        """
        contact_list = []
        for contact in self.get_contacts():
            if contact.bare_jid != self.jid:
193
                if self.contact_filter is not self.DEFAULT_FILTER:
mathieui's avatar
mathieui committed
194 195 196 197 198 199 200 201 202 203 204 205 206 207
                    if self.contact_filter[0](contact, self.contact_filter[1]):
                        contact_list.append(contact)
                else:
                    contact_list.append(contact)
        contact_list = sorted(contact_list, key=SORTING_METHODS['name'])

        for sorting in sort.split(':'):
            if sorting == 'reverse':
                contact_list = list(reversed(contact_list))
            else:
                method = SORTING_METHODS.get(sorting, lambda x: 0)
                contact_list = sorted(contact_list, key=method)
        return contact_list

208 209 210 211 212
    def save_to_config_file(self):
        """
        Save various information to the config file
        e.g. the folded groups
        """
213
        folded_groups = ':'.join([group.name for group in self.groups.values()\
214
                                      if group.folded])
mathieui's avatar
mathieui committed
215
        log.debug('folded:%s\n', folded_groups)
mathieui's avatar
mathieui committed
216
        return config.silent_set('folded_roster_groups', folded_groups, 'var')
217

mathieui's avatar
mathieui committed
218
    def get_nb_connected_contacts(self):
mathieui's avatar
mathieui committed
219 220 221
        """
        Get the number of connected contacts
        """
mathieui's avatar
mathieui committed
222
        return self.connected
223 224 225 226

    def update_contact_groups(self, contact):
        """Regenerate the RosterGroups when receiving a contact update"""
        if not isinstance(contact, Contact):
mathieui's avatar
mathieui committed
227
            contact = self.get_and_set(contact)
228 229 230 231 232 233 234 235 236
        if not contact:
            return
        for name, group in self.groups.items():
            if name in contact.groups and contact not in group:
                group.add(contact)
            elif contact in group and name not in contact.groups:
                group.remove(contact)

        for group in contact.groups:
237
            if group not in self.groups:
mathieui's avatar
mathieui committed
238 239
                self.groups[group] = RosterGroup(
                    group, folded=group in self.folded_groups)
240
                self.groups[group].add(contact)
mathieui's avatar
mathieui committed
241

242 243
    def __len__(self):
        """
mathieui's avatar
mathieui committed
244 245 246
        Return the number of contacts
        (used to return the display size, but now we have
        the display cache in RosterWin for that)
247
        """
mathieui's avatar
mathieui committed
248
        return self.length
249 250 251

    def __repr__(self):
        ret = '== Roster:\nContacts:\n'
252
        for contact in self.contacts.values():
mathieui's avatar
mathieui committed
253
            ret += '%s\n' % (contact, )
254
        ret += 'Groups\n'
255
        for group in self.groups:
mathieui's avatar
mathieui committed
256
            ret += '%s\n' % (group, )
257 258
        return ret + '\n'

259 260 261
    def export(self, path):
        """Export a list of bare jids to a given file"""
        if p.isfile(path):
262
            return False
263
        try:
264
            f = open(path, 'w+', encoding='utf-8')
mathieui's avatar
mathieui committed
265 266 267 268
            f.writelines([
                str(i) + "\n" for i in self.contacts
                if self[i] and (self[i].subscription == "both" or self[i].ask)
            ])
269 270
            f.close()
            return True
mathieui's avatar
mathieui committed
271
        except OSError:
272
            return False
mathieui's avatar
mathieui committed
273

274 275 276 277 278 279 280 281 282
    def exists(self, contact):
        if not contact:
            return False
        for group in contact.groups:
            if contact not in self.groups.get(group, tuple()):
                return False
        return True


283
class RosterGroup:
284
    """
285 286 287
    A RosterGroup is a group containing contacts
    It can be Friends/Family etc, but also can be
    Online/Offline or whatever
288
    """
mathieui's avatar
mathieui committed
289

mathieui's avatar
mathieui committed
290 291 292
    def __init__(self, name, contacts=None, folded=False):
        if not contacts:
            contacts = []
293
        self.contacts = set(contacts)
294
        self.name = name if name is not None else ''
mathieui's avatar
mathieui committed
295
        self.folded = folded  # if the group content is to be shown
296

297 298 299
    def __iter__(self):
        """Iterate over the contacts"""
        return iter(self.contacts)
300

301 302
    def __repr__(self):
        return '<Roster_group: %s; %s>' % (self.name, self.contacts)
303

304
    def __len__(self):
mathieui's avatar
mathieui committed
305
        """Number of contacts in the group"""
306
        return len(self.contacts)
307

308
    def __contains__(self, contact):
309
        """
310
        Return a bool, telling if the contact is in the group
311
        """
312 313 314 315 316 317 318 319 320 321
        return contact in self.contacts

    def add(self, contact):
        """Add a contact to the group"""
        self.contacts.add(contact)

    def remove(self, contact):
        """Remove a contact from the group if present"""
        if contact in self.contacts:
            self.contacts.remove(contact)
322

323
    def get_contacts(self, contact_filter=None, sort=''):
324
        """Return the group contacts, filtered and sorted"""
325 326 327
        if contact_filter is Roster.DEFAULT_FILTER or contact_filter is None:
            contact_list = self.contacts.copy()
        else:
mathieui's avatar
mathieui committed
328 329 330
            contact_list = [
                contact for contact in self.contacts.copy()
                if contact_filter[0](contact, contact_filter[1])
331
            ]
332
        contact_list = sorted(contact_list, key=SORTING_METHODS['name'])
333

334
        for sorting in sort.split(':'):
335 336 337
            if sorting == 'reverse':
                contact_list = list(reversed(contact_list))
            else:
338
                method = SORTING_METHODS.get(sorting, lambda x: 0)
339 340 341
                contact_list = sorted(contact_list, key=method)
        return contact_list

342
    def toggle_folded(self):
mathieui's avatar
mathieui committed
343
        """Fold/unfold the group in the roster"""
344
        self.folded = not self.folded
345 346 347 348 349 350
        if self.folded:
            if self.name not in roster.folded_groups:
                roster.folded_groups.add(self.name)
        else:
            if self.name in roster.folded_groups:
                roster.folded_groups.remove(self.name)
351

352
    def get_nb_connected_contacts(self):
mathieui's avatar
mathieui committed
353
        """Return the number of connected contacts"""
354
        return len([1 for contact in self.contacts if len(contact)])
355

mathieui's avatar
mathieui committed
356 357


mathieui's avatar
mathieui committed
358
# Shared roster object
359
roster = Roster()