fa87b316ee5e3aa237ace3054efc00073f692358
[theonering] / src / connection.py
1 import weakref
2 import logging
3
4 import telepathy
5
6 import constants
7 import util.go_utils as gobject_utils
8 import util.coroutines as coroutines
9 import gtk_toolbox
10 import gvoice
11 import handle
12 import aliasing
13 import simple_presence
14 import channel_manager
15
16
17 _moduleLogger = logging.getLogger("connection")
18
19
20 class TheOneRingConnection(
21         telepathy.server.Connection,
22         aliasing.AliasingMixin,
23         simple_presence.SimplePresenceMixin,
24 ):
25
26         # Overriding a base class variable
27         # Should the forwarding number be handled by the alias or by an option?
28         _mandatory_parameters = {
29                 'username' : 's',
30                 'password' : 's',
31                 'forward' : 's',
32         }
33         # Overriding a base class variable
34         _optional_parameters = {
35         }
36         _parameter_defaults = {
37         }
38
39         def __init__(self, manager, parameters):
40                 self.check_parameters(parameters)
41                 try:
42                         account = unicode(parameters['username'])
43
44                         # Connection init must come first
45                         telepathy.server.Connection.__init__(
46                                 self,
47                                 constants._telepathy_protocol_name_,
48                                 account,
49                                 constants._telepathy_implementation_name_
50                         )
51                         aliasing.AliasingMixin.__init__(self)
52                         simple_presence.SimplePresenceMixin.__init__(self)
53
54                         self._manager = weakref.proxy(manager)
55                         self._credentials = (
56                                 parameters['username'].encode('utf-8'),
57                                 parameters['password'].encode('utf-8'),
58                         )
59                         self._callbackNumber = parameters['forward'].encode('utf-8')
60                         self._channelManager = channel_manager.ChannelManager(self)
61
62                         cookieFilePath = None
63                         self._session = gvoice.session.Session(cookieFilePath)
64
65                         self.set_self_handle(handle.create_handle(self, 'connection'))
66
67                         _moduleLogger.info("Connection to the account %s created" % account)
68                 except Exception, e:
69                         _moduleLogger.exception("Failed to create Connection")
70                         raise
71
72         @property
73         def manager(self):
74                 return self._manager
75
76         @property
77         def session(self):
78                 return self._session
79
80         @property
81         def username(self):
82                 return self._credentials[0]
83
84         def handle(self, handleType, handleId):
85                 self.check_handle(handleType, handleId)
86                 return self._handles[handleType, handleId]
87
88         @gtk_toolbox.log_exception(_moduleLogger)
89         def Connect(self):
90                 """
91                 For org.freedesktop.telepathy.Connection
92                 """
93                 _moduleLogger.info("Connecting...")
94                 self.StatusChanged(
95                         telepathy.CONNECTION_STATUS_CONNECTING,
96                         telepathy.CONNECTION_STATUS_REASON_REQUESTED
97                 )
98                 try:
99                         self.session.conversations.updateSignalHandler.register_sink(
100                                 self._on_conversations_updated
101                         )
102                         self.session.login(*self._credentials)
103                         self.session.backend.set_callback_number(self._callbackNumber)
104                 except gvoice.backend.NetworkError, e:
105                         _moduleLogger.exception("Connection Failed")
106                         self.StatusChanged(
107                                 telepathy.CONNECTION_STATUS_DISCONNECTED,
108                                 telepathy.CONNECTION_STATUS_REASON_NETWORK_ERROR
109                         )
110                 except Exception, e:
111                         _moduleLogger.exception("Connection Failed")
112                         self.StatusChanged(
113                                 telepathy.CONNECTION_STATUS_DISCONNECTED,
114                                 telepathy.CONNECTION_STATUS_REASON_AUTHENTICATION_FAILED
115                         )
116                 else:
117                         _moduleLogger.info("Connected")
118                         self.StatusChanged(
119                                 telepathy.CONNECTION_STATUS_CONNECTED,
120                                 telepathy.CONNECTION_STATUS_REASON_REQUESTED
121                         )
122
123         @gtk_toolbox.log_exception(_moduleLogger)
124         def Disconnect(self):
125                 """
126                 For org.freedesktop.telepathy.Connection
127                 @bug Not properly logging out.  Cookie files need to be per connection and removed
128                 """
129                 _moduleLogger.info("Disconnecting")
130                 try:
131                         self.session.conversations.updateSignalHandler.unregister_sink(
132                                 self._on_conversations_updated
133                         )
134                         self._channelManager.close()
135                         self.session.logout()
136                         _moduleLogger.info("Disconnected")
137                 except Exception:
138                         _moduleLogger.exception("Disconnecting Failed")
139                 self.StatusChanged(
140                         telepathy.CONNECTION_STATUS_DISCONNECTED,
141                         telepathy.CONNECTION_STATUS_REASON_REQUESTED
142                 )
143
144         @gtk_toolbox.log_exception(_moduleLogger)
145         def RequestChannel(self, type, handleType, handleId, suppressHandler):
146                 """
147                 For org.freedesktop.telepathy.Connection
148
149                 @param type DBus interface name for base channel type
150                 @param handleId represents a contact, list, etc according to handleType
151
152                 @returns DBus object path for the channel created or retrieved
153                 """
154                 self.check_connected()
155                 self.check_handle(handleType, handleId)
156
157                 channel = None
158                 channelManager = self._channelManager
159                 handle = self.handle(handleType, handleId)
160
161                 if type == telepathy.CHANNEL_TYPE_CONTACT_LIST:
162                         _moduleLogger.info("RequestChannel ContactList")
163                         channel = channelManager.channel_for_list(handle, suppressHandler)
164                 elif type == telepathy.CHANNEL_TYPE_TEXT:
165                         _moduleLogger.info("RequestChannel Text")
166                         channel = channelManager.channel_for_text(handle, suppressHandler)
167                 elif type == telepathy.CHANNEL_TYPE_STREAMED_MEDIA:
168                         _moduleLogger.info("RequestChannel Media")
169                         channel = channelManager.channel_for_call(handle, suppressHandler)
170                 else:
171                         raise telepathy.errors.NotImplemented("unknown channel type %s" % type)
172
173                 _moduleLogger.info("RequestChannel Object Path: %s" % channel._object_path)
174                 return channel._object_path
175
176         @gtk_toolbox.log_exception(_moduleLogger)
177         def RequestHandles(self, handleType, names, sender):
178                 """
179                 For org.freedesktop.telepathy.Connection
180                 Overiding telepathy.server.Connecton to allow custom handles
181                 """
182                 self.check_connected()
183                 self.check_handle_type(handleType)
184
185                 handles = []
186                 for name in names:
187                         name = name.encode('utf-8')
188                         if handleType == telepathy.HANDLE_TYPE_CONTACT:
189                                 _moduleLogger.info("RequestHandles Contact: %s" % name)
190                                 h = self._create_contact_handle(name)
191                         elif handleType == telepathy.HANDLE_TYPE_LIST:
192                                 # Support only server side (immutable) lists
193                                 _moduleLogger.info("RequestHandles List: %s" % name)
194                                 h = handle.create_handle(self, 'list', name)
195                         else:
196                                 raise telepathy.errors.NotAvailable('Handle type unsupported %d' % handleType)
197                         handles.append(h.id)
198                         self.add_client_handle(h, sender)
199                 return handles
200
201         def _create_contact_handle(self, requestedHandleName):
202                 requestedContactId, requestedContactNumber = handle.ContactHandle.from_handle_name(
203                         requestedHandleName
204                 )
205                 h = handle.create_handle(self, 'contact', requestedContactId, requestedContactNumber)
206                 return h
207
208         @coroutines.func_sink
209         @coroutines.expand_positional
210         @gobject_utils.async
211         @gtk_toolbox.log_exception(_moduleLogger)
212         def _on_conversations_updated(self, conversationIds):
213                 # @todo get conversations update running
214                 # @todo test conversatiuons
215                 _moduleLogger.info("Incoming messages from: %r" % (conversationIds, ))
216                 channelManager = self._channelManager
217                 for contactId, phoneNumber in conversationIds:
218                         h = self._create_contact_handle(contactId, phoneNumber)
219                         # if its new, __init__ will take care of things
220                         # if its old, its own update will take care of it
221                         channel = channelManager.channel_for_text(handle)