summaryrefslogtreecommitdiff
path: root/sunshine/channel/contact_list.py
blob: d23777fa997599ffee1da5b61a1029b2ee65f871 (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
# telepathy-sunshine is the GaduGadu connection manager for Telepathy
#
# Copyright (C) 2006-2007 Ali Sabil <ali.sabil@gmail.com>
# Copyright (C) 2010 Krzysztof Klinikowski <kkszysiu@gmail.com>
#
# This program 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; either version 2 of the License, or
# (at your option) any later version.
#
# This program 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 this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

import logging
import weakref

import telepathy

import xml.etree.ElementTree as ET

from sunshine.util.decorator import async
from sunshine.handle import SunshineHandleFactory
from sunshine.channel import SunshineChannel

from sunshine.lqsoft.pygadu.twisted_protocol import GaduClient
from sunshine.lqsoft.pygadu.models import GaduProfile, GaduContact

__all__ = ['SunshineContactListChannelFactory']

logger = logging.getLogger('Sunshine.ContactListChannel')

class HandleMutex(object):
    def __init__(self):
        self._handles = set()
        self._keys = {}
        self._callbacks = {}

    def is_locked(self, handle):
        return (handle in self._handles)

    def is_owned(self, key, handle):
        return (handle in self._handles and self._keys[handle] == key)

    def lock(self, key, handle):
        if self.is_locked(handle):
            return False
        self._handles.add(handle)
        self._keys[handle] = key
        return True

    def unlock(self, key, handle):
        if not self.is_owned(key, handle):
            return
        self._handles.remove(handle)
        del self._keys[handle]
        callbacks = self._callbacks.get(handle, [])[:]
        self._callbacks[handle] = []
        for callback in callbacks:
            callback[0](*callback[1:])

    def add_callback(self, key, handle, callback):
        if self.is_owned(key, handle):
            return
        if not self.is_locked(handle):
            callback[0](*callback[1:])
        else:
            self._callbacks.setdefault(handle, []).append(callback)

class Lockable(object):
    def __init__(self, mutex, key, cb_name):
        self._mutex = mutex
        self._key = key
        self._cb_name = cb_name

    def __call__(self, func):
        def method(object, handle, *args, **kwargs):
            def finished_cb(*user_data):
                self._mutex.unlock(self._key, handle)

            def unlocked_cb():
                self._mutex.lock(self._key, handle)
                kwargs[self._cb_name] = finished_cb
                if func(object, handle, *args, **kwargs):
                    finished_cb()

            self._mutex.add_callback(self._key, handle, (unlocked_cb,))

        return method

mutex = HandleMutex()


def SunshineContactListChannelFactory(connection, manager, handle, props):
    handle = connection.handle(
        props[telepathy.CHANNEL_INTERFACE + '.TargetHandleType'],
        props[telepathy.CHANNEL_INTERFACE + '.TargetHandle'])

    if handle.get_name() == 'stored':
        raise telepathy.errors.NotImplemented
    elif handle.get_name() == 'subscribe':
        channel_class = SunshineSubscribeListChannel
    elif handle.get_name() == 'publish':
        raise telepathy.errors.NotImplemented
    elif handle.get_name() == 'hide':
        raise telepathy.errors.NotImplemented
    elif handle.get_name() == 'allow':
        raise telepathy.errors.NotImplemented
    elif handle.get_name() == 'deny':
        raise telepathy.errors.NotImplemented
    else:
        logger.error("Unknown list type : " + handle.get_name())
        raise telepathy.errors.InvalidHandle
    return channel_class(connection, manager, props)


class SunshineListChannel(
        SunshineChannel,
        telepathy.server.ChannelTypeContactList,
        telepathy.server.ChannelInterfaceGroup):
    "Abstract Contact List channels"

    def __init__(self, connection, manager, props, object_path=None):
        self._conn_ref = weakref.ref(connection)
        telepathy.server.ChannelTypeContactList.__init__(self, connection, manager, props, object_path=object_path)
        SunshineChannel.__init__(self, connection, props)
        telepathy.server.ChannelInterfaceGroup.__init__(self)
        self._populate(connection)

    def GetLocalPendingMembersWithInfo(self):
        return []

    @async
    def _populate(self, connection):
        added = set()
        local_pending = set()
        remote_pending = set()

        for contact in connection.gadu_client.contacts:
            ad, lp, rp = self._filter_contact(contact)
            if ad or lp or rp:
                handle = SunshineHandleFactory(self._conn_ref(), 'contact',
                        contact.uin, None)
                #capabilities
                self._conn_ref().contactAdded(handle)
                if ad: added.add(handle)
                if lp: local_pending.add(handle)
                if rp: remote_pending.add(handle)
        self._conn_ref().contactAdded(self._conn_ref().GetSelfHandle())
        self.MembersChanged('', added, (), local_pending, remote_pending, 0,
                telepathy.CHANNEL_GROUP_CHANGE_REASON_NONE)

    def _filter_contact(self, contact):
        return (False, False, False)

    def _contains_handle(self, handle):
        members, local_pending, remote_pending = self.GetAllMembers()
        return (handle in members) or (handle in local_pending) or \
                (handle in remote_pending)


class SunshineSubscribeListChannel(SunshineListChannel):
    """Subscribe List channel.

    This channel contains the list of contact to whom the current used is
    'subscribed', basically this list contains the contact for whom you are
    supposed to receive presence notification."""

    def __init__(self, connection, manager, props):
        SunshineListChannel.__init__(self, connection, manager, props,
                object_path='RosterChannel/List/subscribe')
        self.GroupFlagsChanged(telepathy.CHANNEL_GROUP_FLAG_CAN_ADD |
                telepathy.CHANNEL_GROUP_FLAG_CAN_REMOVE, 0)

    def AddMembers(self, contacts, message):
        logger.info("Subscribe - AddMembers called")
        for h in contacts:
            self._add(h, message)


        """
        for h in contacts:
            handle = self._conn.handle(telepathy.constants.HANDLE_TYPE_CONTACT, h)
            contact_xml = ET.Element("Contact")
            ET.SubElement(contact_xml, "Guid").text = str(handle.name)
            ET.SubElement(contact_xml, "GGNumber").text = str(handle.name)
            ET.SubElement(contact_xml, "ShowName").text = str(handle.name)
            ET.SubElement(contact_xml, "Groups")
            c = GaduContact.from_xml(contact_xml)
            self._conn_ref().gadu_client.addContact( c )
            self._conn_ref().gadu_client.notifyAboutContact( c )
            logger.info("Adding contact: %s" % (handle.name))
            self.MembersChanged('', [handle], (), (), (), 0,
                    telepathy.CHANNEL_GROUP_CHANGE_REASON_INVITED)

            #alias and group settings for new contacts are bit tricky
            #try to set alias
            handle.contact.ShowName = self._conn_ref().get_contact_alias(handle.id)
            #and group
            if self._conn_ref().pending_contacts_to_group.has_key(handle.name):
                logger.info("Trying to add temporary group.")
                handle.contact.updateGroups(self._conn_ref().pending_contacts_to_group[handle.name])
            self._conn_ref().contactAdded(handle)
            logger.info("Contact added.")
        self._conn_ref().exportContactsFile()
        """

    def RemoveMembers(self, contacts, message):
        for h in contacts:
            self._remove(h)

        """
        for h in contacts:
            handle = self._conn.handle(telepathy.HANDLE_TYPE_CONTACT, h)
            contact = handle.contact
            self._conn_ref().gadu_client.removeContact(contact, notify=True)
            self.MembersChanged('', (), [handle], (), (), 0,
                    telepathy.CHANNEL_GROUP_CHANGE_REASON_NONE)
        self._conn_ref().exportContactsFile()
        """

    def _filter_contact(self, contact):
        return (True, False, False)

    def _add(self, handle_id, message):
        handle = self._conn.handle(telepathy.HANDLE_TYPE_CONTACT, handle_id)
        if handle.contact is not None:
            return True

        contact_xml = ET.Element("Contact")
        ET.SubElement(contact_xml, "Guid").text = str(handle.name)
        ET.SubElement(contact_xml, "GGNumber").text = str(handle.name)
        ET.SubElement(contact_xml, "ShowName").text = str(handle.name)
        ET.SubElement(contact_xml, "Groups")
        c = GaduContact.from_xml(contact_xml)
        self._conn_ref().gadu_client.addContact( c )
        self._conn_ref().gadu_client.notifyAboutContact( c )
        logger.info("Adding contact: %s" % (handle.name))
        self.MembersChanged('', [handle], (), (), (), 0,
                    telepathy.CHANNEL_GROUP_CHANGE_REASON_INVITED)

        #alias and group settings for new contacts are bit tricky
        #try to set alias
        handle.contact.ShowName = self._conn_ref().get_contact_alias(handle.id)
        #and group
        if self._conn_ref().pending_contacts_to_group.has_key(handle.name):
            logger.info("Trying to add temporary group.")
            handle.contact.updateGroups(self._conn_ref().pending_contacts_to_group[handle.name])
        self._conn_ref().contactAdded(handle)
        logger.info("Contact added.")
        self._conn_ref().exportContactsFile()

    def _remove(self, handle_id):
        handle = self._conn.handle(telepathy.HANDLE_TYPE_CONTACT, h)
        contact = handle.contact
        self._conn_ref().gadu_client.removeContact(contact, notify=True)
        self.MembersChanged('', (), [handle], (), (), 0,
                    telepathy.CHANNEL_GROUP_CHANGE_REASON_NONE)
        self._conn_ref().exportContactsFile()