roster.py 10.6 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
10
11

"""
Defines the Roster and RosterGroup classes
"""
12
13
import logging
log = logging.getLogger(__name__)
14
15

from config import config
16
from contact import Contact
17
18
19
from roster_sorting import SORTING_METHODS, GROUP_SORTING_METHODS

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

24

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

31
    def __init__(self):
32
        """
louiz’'s avatar
louiz’ committed
33
        node: the RosterSingle from slixmpp
34
35
36
        """
        self.__node = None
        self.contact_filter = None # A tuple(function, *args)
37
38
                                    # function to filter contacts,
                                    # on search, for example
39
        self.folded_groups = set(config.get(
40
41
                'folded_roster_groups',
                '',
42
                section='var').split(':'))
43
44
        self.groups = {}
        self.contacts = {}
45

46
47
48
49
50
51
52
53
54
55
56
        # 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

57
58
    def __getitem__(self, key):
        """Get a Contact from his bare JID"""
59
        key = safeJID(key).bare
60
61
62
63
64
65
        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
66

67
68
69
    def __setitem__(self, key, value):
        """Set the a Contact value for the bare jid key"""
        self.contacts[key] = value
70

mathieui's avatar
mathieui committed
71
72
73
74
75
76
77
78
    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
79
                log.debug('IqError when removing %s:', jid, exc_info=True)
mathieui's avatar
mathieui committed
80

81
    def __delitem__(self, jid):
mathieui's avatar
mathieui committed
82
        """Remove a contact from the roster view"""
83
        jid = safeJID(jid).bare
84
        contact = self[jid]
mathieui's avatar
mathieui committed
85
86
        if not contact:
            return
mathieui's avatar
mathieui committed
87
88
        del self.contacts[contact.bare_jid]

89
90
91
92
        for group in list(self.groups.values()):
            group.remove(contact)
            if not group:
                del self.groups[group.name]
mathieui's avatar
mathieui committed
93
        self.modified()
94

95
96
97
98
99
100
    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"""
101
        return safeJID(key).bare in self.jids()
102

mathieui's avatar
mathieui committed
103
104
105
106
107
    @property
    def jid(self):
        """Our JID"""
        return self.__node.jid

108
109
110
111
112
113
114
    def get_and_set(self, jid):
        if not jid in self.contacts:
            contact = Contact(self.__node[jid])
            self.contacts[jid] = contact
            return contact
        return self.contacts[jid]

mathieui's avatar
mathieui committed
115
    def set_node(self, value):
louiz’'s avatar
louiz’ committed
116
        """Set the slixmpp RosterSingle for our roster"""
mathieui's avatar
mathieui committed
117
118
        self.__node = value

119
    def get_groups(self, sort=''):
mathieui's avatar
mathieui committed
120
        """Return a list of the RosterGroups"""
121
        group_list = sorted(
mathieui's avatar
mathieui committed
122
                (group for group in self.groups.values() if group),
123
124
125
                key=lambda x: x.name.lower() if x.name else ''
            )

126
        for sorting in sort.split(':'):
127
128
129
130
131
132
            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
133

134
135
136
137
138
139
140
141
142
143
144
145
    def get_group(self, name):
        """Return a group or create it if not present"""
        if name in self.groups:
            return self.groups[name]
        self.groups[name] = RosterGroup(name, folded=name in self.folded_groups)

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

    def jids(self):
        """List of the contact JIDS"""
146
147
148
149
150
151
        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)
        return l
152

louiz’'s avatar
louiz’ committed
153
154
    def get_contacts(self):
        """
155
        Return a list of all the contacts
louiz’'s avatar
louiz’ committed
156
        """
157
        return [self[jid] for jid in self.jids()]
louiz’'s avatar
louiz’ committed
158

mathieui's avatar
mathieui committed
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
    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:
                if self.contact_filter:
                    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

181
182
183
184
185
    def save_to_config_file(self):
        """
        Save various information to the config file
        e.g. the folded groups
        """
186
        folded_groups = ':'.join([group.name for group in self.groups.values()\
187
                                      if group.folded])
mathieui's avatar
mathieui committed
188
        log.debug('folded:%s\n', folded_groups)
mathieui's avatar
mathieui committed
189
        return config.silent_set('folded_roster_groups', folded_groups, 'var')
190

mathieui's avatar
mathieui committed
191
    def get_nb_connected_contacts(self):
mathieui's avatar
mathieui committed
192
193
194
        """
        Get the number of connected contacts
        """
195
196
        n = 0
        for contact in self:
197
            if self.exists(contact) and len(contact):
198
199
200
201
202
203
                n += 1
        return n

    def update_contact_groups(self, contact):
        """Regenerate the RosterGroups when receiving a contact update"""
        if not isinstance(contact, Contact):
mathieui's avatar
mathieui committed
204
            contact = self.get_and_set(contact)
205
206
207
208
209
210
211
212
213
214
215
216
        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:
            if not group in self.groups:
                self.groups[group] = RosterGroup(group, folded=group in self.folded_groups)
                self.groups[group].add(contact)
mathieui's avatar
mathieui committed
217

218
219
    def __len__(self):
        """
mathieui's avatar
mathieui committed
220
221
222
        Return the number of contacts
        (used to return the display size, but now we have
        the display cache in RosterWin for that)
223
        """
224
        return len(self.jids())
225
226
227

    def __repr__(self):
        ret = '== Roster:\nContacts:\n'
228
        for contact in self.contacts.values():
229
230
            ret += '%s\n' % (contact,)
        ret += 'Groups\n'
231
        for group in self.groups:
232
233
234
            ret += '%s\n' % (group,)
        return ret + '\n'

235
236
237
238
239
    def export(self, path):
        """Export a list of bare jids to a given file"""
        if p.isfile(path):
            return
        try:
240
            f = open(path, 'w+', encoding='utf-8')
mathieui's avatar
mathieui committed
241
            f.writelines([str(i) + "\n" for i in self.contacts if self[i] and (self[i].subscription == "both" or self[i].ask)])
242
243
244
245
            f.close()
            return True
        except IOError:
            return
mathieui's avatar
mathieui committed
246
247
248
        except OSError:
            return

249

250
251
252
253
254
255
256
257
258
    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


259
class RosterGroup(object):
260
    """
261
262
263
    A RosterGroup is a group containing contacts
    It can be Friends/Family etc, but also can be
    Online/Offline or whatever
264
    """
mathieui's avatar
mathieui committed
265
266
267
    def __init__(self, name, contacts=None, folded=False):
        if not contacts:
            contacts = []
268
        self.contacts = set(contacts)
269
        self.name = name if name is not None else ''
270
        self.folded = folded    # if the group content is to be shown
271

272
273
274
    def __iter__(self):
        """Iterate over the contacts"""
        return iter(self.contacts)
275

276
277
    def __repr__(self):
        return '<Roster_group: %s; %s>' % (self.name, self.contacts)
278

279
    def __len__(self):
mathieui's avatar
mathieui committed
280
        """Number of contacts in the group"""
281
        return len(self.contacts)
282

283
    def __contains__(self, contact):
284
        """
285
        Return a bool, telling if the contact is in the group
286
        """
287
288
289
290
291
292
293
294
295
296
        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)
297

298
    def get_contacts(self, contact_filter=None, sort=''):
299
        """Return the group contacts, filtered and sorted"""
300
        contact_list = self.contacts.copy() if not contact_filter\
mathieui's avatar
mathieui committed
301
            else [contact for contact in self.contacts.copy() if contact_filter[0](contact, contact_filter[1])]
302
        contact_list = sorted(contact_list, key=SORTING_METHODS['name'])
303

304
        for sorting in sort.split(':'):
305
306
307
            if sorting == 'reverse':
                contact_list = list(reversed(contact_list))
            else:
308
                method = SORTING_METHODS.get(sorting, lambda x: 0)
309
310
311
                contact_list = sorted(contact_list, key=method)
        return contact_list

312
    def toggle_folded(self):
mathieui's avatar
mathieui committed
313
        """Fold/unfold the group in the roster"""
314
        self.folded = not self.folded
315
316
317
318
319
320
        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)
321

322
    def get_nb_connected_contacts(self):
mathieui's avatar
mathieui committed
323
        """Return the number of connected contacts"""
324
        return len([1 for contact in self.contacts if len(contact)])
325

326
327
328
329
330
def create_roster():
    "Create the global roster object"
    global roster
    roster = Roster()

mathieui's avatar
mathieui committed
331
# Shared roster object
332
roster = None