summaryrefslogtreecommitdiff
path: root/butterfly/connection.py
blob: 3f0d18f980c1586926c1fdc3e7e6ffc4941a3e07 (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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
# telepathy-butterfly - an MSN connection manager for Telepathy
#
# Copyright (C) 2006-2007 Ali Sabil <ali.sabil@gmail.com>
# Copyright (C) 2007 Johann Prieur <johann.prieur@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 weakref
import logging

import dbus
import telepathy
import papyon
import papyon.event

from butterfly.presence import ButterflyPresence
from butterfly.aliasing import ButterflyAliasing
from butterfly.avatars import ButterflyAvatars
from butterfly.capabilities import ButterflyCapabilities
from butterfly.handle import ButterflyHandleFactory, network_to_extension
from butterfly.contacts import ButterflyContacts
from butterfly.channel_manager import ButterflyChannelManager
from butterfly.mail_notification import ButterflyMailNotification

__all__ = ['ButterflyConnection']

logger = logging.getLogger('Butterfly.Connection')


class ButterflyConnection(telepathy.server.Connection,
        telepathy.server.ConnectionInterfaceRequests,
        ButterflyPresence,
        ButterflyAliasing,
        ButterflyAvatars,
        ButterflyCapabilities,
        ButterflyContacts,
        ButterflyMailNotification,
        papyon.event.ClientEventInterface,
        papyon.event.InviteEventInterface,
        papyon.event.OfflineMessagesEventInterface):

    _secret_parameters = set([
            'password',
            'http-proxy-password',
            'https-proxy-password'
            ])
    _mandatory_parameters = {
            'account' : 's',
            'password' : 's'
            }
    _optional_parameters = {
            'server' : 's',
            'port' : 'q',
            'http-proxy-server' : 's',
            'http-proxy-port' : 'q',
            'http-proxy-username' : 's',
            'http-proxy-password' : 's',
            'https-proxy-server' : 's',
            'https-proxy-port' : 'q',
            'https-proxy-username' : 's',
            'https-proxy-password' : 's',
            'http-method' : 'b',
            }
    _parameter_defaults = {
            'server' : 'messenger.hotmail.com',
            'port' : 1863,
            'http-method' : False
            }

    def __init__(self, manager, parameters):
        self.check_parameters(parameters)

        try:
            account = unicode(parameters['account'])
            self._server = (parameters['server'].encode('utf-8'), parameters['port'])

            # Build the proxies configurations
            self._proxies = {}
            proxy = build_proxy_infos(parameters, 'http')
            if proxy is not None:
                self._proxies['http'] = proxy
            proxy = build_proxy_infos(parameters, 'https')
            if proxy is not None:
                self._proxies['https'] = proxy

            self._suggested_proxies = []

            # If the HTTP proxy parameters have been set, don't try any
            # others proxies automatically.
            if 'http' not in self._proxies:
                self._fill_suggested_proxies()
                self._use_next_proxy()

            self._manager = weakref.proxy(manager)
            self._new_client(use_http=parameters['http-method'])
            self._account = (parameters['account'].encode('utf-8'),
                    parameters['password'].encode('utf-8'))
            self._channel_manager = ButterflyChannelManager(self)

            # Call parent initializers
            telepathy.server.Connection.__init__(self, 'msn', account, 'butterfly')
            telepathy.server.ConnectionInterfaceRequests.__init__(self)
            ButterflyPresence.__init__(self)
            ButterflyAliasing.__init__(self)
            ButterflyAvatars.__init__(self)
            ButterflyCapabilities.__init__(self)
            ButterflyContacts.__init__(self)
            ButterflyMailNotification.__init__(self)

            self.set_self_handle(ButterflyHandleFactory(self, 'self'))

            self.__disconnect_reason = telepathy.CONNECTION_STATUS_REASON_NONE_SPECIFIED
            self._initial_presence = papyon.Presence.INVISIBLE
            self._initial_personal_message = None

            logger.info("Connection to the account %s created" % account)
        except Exception, e:
            import traceback
            logger.exception("Failed to create Connection")
            raise

    def _new_client(self, use_http=False):
        if hasattr(self, '_msn_client') and self._msn_client:
            if self._msn_client.state != papyon.event.ClientState.CLOSED:
                self._msn_client.logout()
            self._msn_client._events_handlers.remove(self)

        if use_http:
            self._tried_http = True
            self._msn_client = papyon.Client(self._server, self._proxies,
                papyon.transport.HTTPPollConnection)
        else:
            self._tried_http = False
            self._msn_client = papyon.Client(self._server, self._proxies)

        papyon.event.ClientEventInterface.__init__(self, self._msn_client)
        papyon.event.InviteEventInterface.__init__(self, self._msn_client)
        papyon.event.OfflineMessagesEventInterface.__init__(self, self._msn_client)

    def _fill_suggested_proxies(self):
        try:
            import libproxy
        except ImportError:
            return

        factory = libproxy.ProxyFactory()
        proxies = factory.getProxies('http://gateway.messenger.msn.com/')

        # Remove socks proxies that papyon doesn't support.
        proxies = [p for p in proxies if p.startswith('http://') or p == 'direct://']

        if proxies:
            self._suggested_proxies = proxies

    def _use_next_proxy(self):
        if not self._suggested_proxies:
            return False

        # Use the first one.
        proxy = self._suggested_proxies.pop(0)

        if proxy == 'direct://':
            if 'http' in self._proxies:
                del self._proxies['http']
            return True

        # libproxy documentation states:
        #
        #  * The format of the returned proxy strings are as follows:
        #  *   - http://[username:password@]proxy:port
        #  *   - socks://[username:password@]proxy:port
        #  *   - direct://
        #  etc.
        #
        # We've already removed every proxy other than http and
        # direct, and have dealt with direct, so any other element
        # will be an HTTP proxy:

        proxy = proxy[len('http://'):]

        # Get username and password out.
        if '@' in proxy:
            auth, proxy = proxy.split('@')
            user, password = auth.split(':')
        else:
            user = password = None

        server, port = proxy.split(':')

        self._proxies['http'] = \
            papyon.ProxyInfos(host=server, port=int(port), type='http',
                user=user, password=password)

        if user:
            logger.info('Using proxy: http://%s:***@%s:%u' % (user, server, int(port)))
        else:
            logger.info('Using proxy: http://%s:%u' % (server, int(port)))

        return True

    @property
    def manager(self):
        return self._manager

    @property
    def msn_client(self):
        return self._msn_client

    def handle(self, handle_type, handle_id):
        self.check_handle(handle_type, handle_id)
        return self._handles[handle_type, handle_id]

    def Connect(self):
        if self._status == telepathy.CONNECTION_STATUS_DISCONNECTED:
            logger.info("Connecting")
            self.__disconnect_reason = telepathy.CONNECTION_STATUS_REASON_NONE_SPECIFIED
            self._msn_client.login(*self._account)

    def Disconnect(self):
        logger.info("Disconnecting")
        self.__disconnect_reason = telepathy.CONNECTION_STATUS_REASON_REQUESTED
        if self._msn_client.state != papyon.event.ClientState.CLOSED:
            self._msn_client.logout()

    def GetInterfaces(self):
        # The self._interfaces set is only ever touched in ButterflyConnection.__init__,
        # where connection interfaces are added.

        # The mail notification interface is added then too, but also removed in its
        # ButterflyMailNotification.__init__ because it might not actually be available.
        # It is added before the connection status turns to connected, if available.

        # The spec denotes that this method can return a subset of the actually
        # available interfaces before connected. As the only possible change will
        # be adding the mail notification interface before connecting, this is fine.

        return self._interfaces

    def RequestHandles(self, handle_type, names, sender):
        self.check_connected()
        self.check_handle_type(handle_type)

        handles = []
        for name in names:
            if handle_type == telepathy.HANDLE_TYPE_CONTACT:
                network_id = papyon.NetworkID.MSN
                for network, extension in network_to_extension.items():
                    if name.endswith(extension):
                        name = name[0:-len(extension)]
                        network_id = network
                        break
                contacts = self.msn_client.address_book.contacts.\
                        search_by_account(name).\
                        search_by_network_id(network_id)
                handle = ButterflyHandleFactory(self, 'contact',
                        name, network_id)
            elif handle_type == telepathy.HANDLE_TYPE_LIST:
                handle = ButterflyHandleFactory(self, 'list', name)
            elif handle_type == telepathy.HANDLE_TYPE_GROUP:
                handle = ButterflyHandleFactory(self, 'group', name)
            else:
                raise telepathy.NotAvailable('Handle type unsupported %d' % handle_type)
            handles.append(handle.id)
            self.add_client_handle(handle, sender)
        return handles

    def _generate_props(self, channel_type, handle, suppress_handler, initiator_handle=None):
        props = {
            telepathy.CHANNEL_INTERFACE + '.ChannelType': channel_type,
            telepathy.CHANNEL_INTERFACE + '.TargetHandle': handle.get_id(),
            telepathy.CHANNEL_INTERFACE + '.TargetHandleType': handle.get_type(),
            telepathy.CHANNEL_INTERFACE + '.Requested': suppress_handler
            }

        if initiator_handle is not None:
            if initiator_handle.get_type() is not telepathy.HANDLE_TYPE_NONE:
                props[telepathy.CHANNEL_INTERFACE + '.InitiatorHandle'] = \
                        initiator_handle.get_id()

        return props


    @dbus.service.method(telepathy.CONNECTION, in_signature='suub',
        out_signature='o', async_callbacks=('_success', '_error'))
    def RequestChannel(self, type, handle_type, handle_id, suppress_handler,
            _success, _error):
        self.check_connected()
        channel_manager = self._channel_manager

        if handle_id == telepathy.HANDLE_TYPE_NONE:
            handle = telepathy.server.handle.NoneHandle()
        else:
            handle = self.handle(handle_type, handle_id)
        props = self._generate_props(type, handle, suppress_handler)
        self._validate_handle(props)

        channel = channel_manager.channel_for_props(props, signal=False)

        _success(channel._object_path)
        self.signal_new_channels([channel])

    # papyon.event.ClientEventInterface
    def on_client_state_changed(self, state):
        if state == papyon.event.ClientState.CONNECTING:
            self.StatusChanged(telepathy.CONNECTION_STATUS_CONNECTING,
                    telepathy.CONNECTION_STATUS_REASON_REQUESTED)
        elif state == papyon.event.ClientState.SYNCHRONIZED:
            handle = ButterflyHandleFactory(self, 'list', 'subscribe')
            props = self._generate_props(telepathy.CHANNEL_TYPE_CONTACT_LIST,
                handle, False)
            self._channel_manager.channel_for_props(props, signal=True)

            handle = ButterflyHandleFactory(self, 'list', 'publish')
            props = self._generate_props(telepathy.CHANNEL_TYPE_CONTACT_LIST,
                handle, False)
            self._channel_manager.channel_for_props(props, signal=True)

            #handle = ButterflyHandleFactory(self, 'list', 'hide')
            #props = self._generate_props(telepathy.CHANNEL_TYPE_CONTACT_LIST,
            #    handle, False)
            #self._channel_manager.channel_for_props(props, signal=True)

            #handle = ButterflyHandleFactory(self, 'list', 'allow')
            #props = self._generate_propstelepathy.CHANNEL_TYPE_CONTACT_LIST,
            #    handle, False)
            #self._channel_manager.channel_for_props(props, signal=True)

            #handle = ButterflyHandleFactory(self, 'list', 'deny')
            #props = self._generate_props(telepathy.CHANNEL_TYPE_CONTACT_LIST,
            #    handle, False)
            #self._channel_manager.channel_for_props(props, signal=True)

            for group in self.msn_client.address_book.groups:
                handle = ButterflyHandleFactory(self, 'group',
                        group.name.decode("utf-8"))
                props = self._generate_props(
                    telepathy.CHANNEL_TYPE_CONTACT_LIST, handle, False)
                self._channel_manager.channel_for_props(props, signal=True)
        elif state == papyon.event.ClientState.OPEN:
            self._populate_capabilities()
            if self._client.profile.profile['EmailEnabled'] == '1':
                self.enable_mail_notification_interface()
            self.StatusChanged(telepathy.CONNECTION_STATUS_CONNECTED,
                    telepathy.CONNECTION_STATUS_REASON_REQUESTED)
            presence = self._initial_presence
            message = self._initial_personal_message
            if presence is not None:
                self._client.profile.presence = presence
            if message is not None:
                self._client.profile.personal_message = message
            self._client.profile.end_point_name = "PAPYON"

            if (presence is not None) or (message is not None):
                self._presence_changed(ButterflyHandleFactory(self, 'self'),
                        self._client.profile.presence,
                        self._client.profile.personal_message)
        elif state == papyon.event.ClientState.CLOSED:
            self.StatusChanged(telepathy.CONNECTION_STATUS_DISCONNECTED,
                    self.__disconnect_reason)
            #FIXME
            self._channel_manager.close()
            self._advertise_disconnected()

    # papyon.event.ClientEventInterface
    def on_client_error(self, type, error):
        if type == papyon.event.ClientErrorType.NETWORK:
            # Only move onto the next proxy if we've not already tried
            # HTTP and we're in the connecting state. We don't want to
            # connect to HTTP if we're already connected and we lose
            # connectivity (see fd.o#26147).
            if self._status == telepathy.CONNECTION_STATUS_CONNECTING and \
                    (self._tried_http is False or \
                   (self._tried_http is True and self._use_next_proxy())):
                logger.info("Failed to connect, trying HTTP "
                            "(possibly again with another proxy)")
                self._new_client(use_http=True)
                self._msn_client.login(*self._account)
            else:
                self.__disconnect_reason = telepathy.CONNECTION_STATUS_REASON_NETWORK_ERROR
        elif type == papyon.event.ClientErrorType.AUTHENTICATION:
            self.__disconnect_reason = telepathy.CONNECTION_STATUS_REASON_AUTHENTICATION_FAILED
        elif type == papyon.event.ClientErrorType.PROTOCOL and \
             error == papyon.event.ProtocolError.OTHER_CLIENT:
            self.__disconnect_reason = telepathy.CONNECTION_STATUS_REASON_NAME_IN_USE
        else:
            self.__disconnect_reason = telepathy.CONNECTION_STATUS_REASON_NONE_SPECIFIED

    # papyon.event.InviteEventInterface
    def on_invite_conversation(self, conversation):
        logger.debug("Conversation invite")

        if len(conversation.participants) == 1:
            p = list(conversation.participants)[0]
            handle = ButterflyHandleFactory(self, 'contact',
                    p.account, p.network_id)
        else:
            handle = telepathy.server.handle.NoneHandle()

        props = self._generate_props(telepathy.CHANNEL_TYPE_TEXT,
            handle, False, initiator_handle=handle)

        channel = self._channel_manager.channel_for_props(props,
            signal=True, conversation=conversation)

        if channel._conversation is not conversation:
            # If we get an existing channel, attach the conversation object to it
            channel.attach_conversation(conversation)

    # papyon.event.InviteEventInterface
    def on_invite_conference(self, call):
        logger.debug("Call invite")
        handle = ButterflyHandleFactory(self, 'contact', call.peer.account,
                call.peer.network_id)

        props = self._generate_props(telepathy.CHANNEL_TYPE_STREAMED_MEDIA,
                handle, False, initiator_handle=handle)

        channel = self._channel_manager.channel_for_props(props,
                signal=True, call=call)

    # papyon.event.InviteEventInterface
    def on_invite_webcam(self, session, producer):
        direction = (producer and "send") or "receive"
        logger.debug("Invitation to %s webcam" % direction)

        handle = ButterflyHandleFactory(self, 'contact', session.peer.account,
                session.peer.network_id)
        props = self._generate_props(telepathy.CHANNEL_TYPE_STREAMED_MEDIA,
                handle, False, initiator_handle=handle)
        channel = self._channel_manager.channel_for_props(props, signal=True,
                call=session)

    # papyon.event.OfflineMessagesEventInterface
    def on_oim_messages_received(self, messages):
        # We got notified we received some offlines messages so we
        #are going to fetch them
        self.msn_client.oim_box.fetch_messages(messages)

    # papyon.event.OfflineMessagesEventInterface
    def on_oim_messages_fetched(self, messages):
        for message in messages:
            if message.sender is None:
                continue
            # Request butterfly text channel (creation, what happen when it exist)
            sender = message.sender
            logger.info('received offline message from %s : %s' % (sender.account, message.text))
            handle = ButterflyHandleFactory(self, 'contact',
                    sender.account, sender.network_id)
            props = self._generate_props(telepathy.CHANNEL_TYPE_TEXT,
                handle, False)
            channel = self._channel_manager.channel_for_props(props,
                signal=True)
            # Notify it of the message
            channel.offline_message_received(message)

    # papyon.event.InviteEventInterface
    def on_invite_file_transfer(self, session):
        logger.debug("File transfer invite")
        handle = ButterflyHandleFactory(self, 'contact', session.peer.account,
                session.peer.network_id)

        props = self._generate_props(telepathy.CHANNEL_TYPE_FILE_TRANSFER,
                handle, False)
        channel = self._channel_manager.create_channel_for_props(props,
                signal=True, session=session)

    def _advertise_disconnected(self):
        self._manager.disconnected(self)


def build_proxy_infos(parameters, proxy_type='http'):
    server_key = proxy_type + '-proxy-server'
    port_key = proxy_type + '-proxy-port'
    username_key = proxy_type + '-proxy-username'
    password_key = proxy_type + '-proxy-password'
    if server_key in parameters and port_key in parameters:
        return papyon.ProxyInfos(host = parameters[server_key],
                port = parameters[port_key],
                type = proxy_type,
                user = parameters.get(username_key, None),
                password = parameters.get(password_key, None) )
    else:
        return None