Forgot to update some todos upon completion
[theonering] / src / connection.py
1
2 """
3 @todo Add params for different state machines update times
4 @todo Get a callback for missed calls to force an update of the voicemail state machine
5 @todo Get a callback on an incoming call and if its from GV, auto-pickup
6 @todo Decide if we should do what the spec suggests and hold onto a singleton contactlist
7 """
8
9
10 import os
11 import weakref
12 import logging
13
14 import telepathy
15
16 try:
17         import conic as _conic
18         conic = _conic
19 except (ImportError, OSError):
20         conic = None
21
22 import constants
23 import tp
24 import util.coroutines as coroutines
25 import util.misc as util_misc
26 import gtk_toolbox
27
28 import gvoice
29 import handle
30
31 import requests
32 import contacts
33 import aliasing
34 import simple_presence
35 import presence
36 import capabilities
37
38 import channel_manager
39
40
41 _moduleLogger = logging.getLogger("connection")
42
43
44 class TheOneRingConnection(
45         tp.Connection,
46         requests.RequestsMixin,
47         contacts.ContactsMixin,
48         aliasing.AliasingMixin,
49         simple_presence.SimplePresenceMixin,
50         presence.PresenceMixin,
51         capabilities.CapabilitiesMixin,
52 ):
53
54         # Overriding a base class variable
55         # Should the forwarding number be handled by the alias or by an option?
56         _mandatory_parameters = {
57                 'account' : 's',
58                 'password' : 's',
59         }
60         # Overriding a base class variable
61         _optional_parameters = {
62                 'forward' : 's',
63         }
64         _parameter_defaults = {
65                 'forward' : '',
66         }
67
68         @gtk_toolbox.log_exception(_moduleLogger)
69         def __init__(self, manager, parameters):
70                 self.check_parameters(parameters)
71                 account = unicode(parameters['account'])
72                 encodedAccount = parameters['account'].encode('utf-8')
73                 encodedPassword = parameters['password'].encode('utf-8')
74                 encodedCallback = util_misc.normalize_number(parameters['forward'].encode('utf-8'))
75                 if encodedCallback and not util_misc.is_valid_number(encodedCallback):
76                         raise telepathy.errors.InvalidArgument("Invalid forwarding number")
77
78                 # Connection init must come first
79                 self.__session = gvoice.session.Session(None)
80                 tp.Connection.__init__(
81                         self,
82                         constants._telepathy_protocol_name_,
83                         account,
84                         constants._telepathy_implementation_name_
85                 )
86                 requests.RequestsMixin.__init__(self)
87                 contacts.ContactsMixin.__init__(self)
88                 aliasing.AliasingMixin.__init__(self)
89                 simple_presence.SimplePresenceMixin.__init__(self)
90                 presence.PresenceMixin.__init__(self)
91                 capabilities.CapabilitiesMixin.__init__(self)
92
93                 self.__manager = weakref.proxy(manager)
94                 self.__credentials = (
95                         encodedAccount,
96                         encodedPassword,
97                 )
98                 self.__callbackNumberParameter = encodedCallback
99                 self.__channelManager = channel_manager.ChannelManager(self)
100
101                 if conic is not None:
102                         self.__connection = conic.Connection()
103                         self.__connectionEventId = None
104                 else:
105                         self.__connection = None
106                         self.__connectionEventId = None
107                 self.__cachePath = os.sep.join((constants._data_path_, "cache", self.username))
108                 try:
109                         os.makedirs(self.__cachePath)
110                 except OSError, e:
111                         if e.errno != 17:
112                                 raise
113
114                 self.set_self_handle(handle.create_handle(self, 'connection'))
115
116                 self.__callback = None
117                 _moduleLogger.info("Connection to the account %s created" % account)
118
119         @property
120         def manager(self):
121                 return self.__manager
122
123         @property
124         def session(self):
125                 return self.__session
126
127         @property
128         def username(self):
129                 return self.__credentials[0]
130
131         @property
132         def callbackNumberParameter(self):
133                 return self.__callbackNumberParameter
134
135         def get_handle_by_name(self, handleType, handleName):
136                 requestedHandleName = handleName.encode('utf-8')
137                 if handleType == telepathy.HANDLE_TYPE_CONTACT:
138                         _moduleLogger.info("get_handle_by_name Contact: %s" % requestedHandleName)
139                         h = handle.create_handle(self, 'contact', requestedHandleName)
140                 elif handleType == telepathy.HANDLE_TYPE_LIST:
141                         # Support only server side (immutable) lists
142                         _moduleLogger.info("get_handle_by_name List: %s" % requestedHandleName)
143                         h = handle.create_handle(self, 'list', requestedHandleName)
144                 else:
145                         raise telepathy.errors.NotAvailable('Handle type unsupported %d' % handleType)
146                 return h
147
148         @property
149         def _channel_manager(self):
150                 return self.__channelManager
151
152         @gtk_toolbox.log_exception(_moduleLogger)
153         def Connect(self):
154                 """
155                 For org.freedesktop.telepathy.Connection
156                 """
157                 _moduleLogger.info("Connecting...")
158                 self.StatusChanged(
159                         telepathy.CONNECTION_STATUS_CONNECTING,
160                         telepathy.CONNECTION_STATUS_REASON_REQUESTED
161                 )
162                 try:
163                         self.__session.load(self.__cachePath)
164
165                         self.__callback = coroutines.func_sink(
166                                 coroutines.expand_positional(
167                                         self._on_conversations_updated
168                                 )
169                         )
170                         self.session.voicemails.updateSignalHandler.register_sink(
171                                 self.__callback
172                         )
173                         self.session.texts.updateSignalHandler.register_sink(
174                                 self.__callback
175                         )
176                         self.session.login(*self.__credentials)
177                         if not self.__callbackNumberParameter:
178                                 callback = gvoice.backend.get_sane_callback(
179                                         self.session.backend
180                                 )
181                                 self.__callbackNumberParameter = util_misc.normalize_number(callback)
182                         self.session.backend.set_callback_number(self.__callbackNumberParameter)
183                 except gvoice.backend.NetworkError, e:
184                         _moduleLogger.exception("Connection Failed")
185                         self.StatusChanged(
186                                 telepathy.CONNECTION_STATUS_DISCONNECTED,
187                                 telepathy.CONNECTION_STATUS_REASON_NETWORK_ERROR
188                         )
189                         return
190                 except Exception, e:
191                         _moduleLogger.exception("Connection Failed")
192                         self.StatusChanged(
193                                 telepathy.CONNECTION_STATUS_DISCONNECTED,
194                                 telepathy.CONNECTION_STATUS_REASON_AUTHENTICATION_FAILED
195                         )
196                         return
197
198                 _moduleLogger.info("Connected")
199                 self.StatusChanged(
200                         telepathy.CONNECTION_STATUS_CONNECTED,
201                         telepathy.CONNECTION_STATUS_REASON_REQUESTED
202                 )
203                 if self.__connection is not None:
204                         self.__connectionEventId = self.__connection.connect("connection-event", self._on_connection_change)
205
206         @gtk_toolbox.log_exception(_moduleLogger)
207         def Disconnect(self):
208                 """
209                 For org.freedesktop.telepathy.Connection
210                 """
211                 self.StatusChanged(
212                         telepathy.CONNECTION_STATUS_DISCONNECTED,
213                         telepathy.CONNECTION_STATUS_REASON_REQUESTED
214                 )
215                 try:
216                         self._disconnect()
217                 except Exception:
218                         _moduleLogger.exception("Error durring disconnect")
219
220         @gtk_toolbox.log_exception(_moduleLogger)
221         def RequestChannel(self, type, handleType, handleId, suppressHandler):
222                 """
223                 For org.freedesktop.telepathy.Connection
224
225                 @param type DBus interface name for base channel type
226                 @param handleId represents a contact, list, etc according to handleType
227
228                 @returns DBus object path for the channel created or retrieved
229                 """
230                 self.check_connected()
231                 self.check_handle(handleType, handleId)
232
233                 h = self.get_handle_by_id(handleType, handleId) if handleId != 0 else None
234                 props = self._generate_props(type, h, suppressHandler)
235                 self._validate_handle(props)
236
237                 chan = self.__channelManager.channel_for_props(props, signal=True)
238                 path = chan._object_path
239                 _moduleLogger.info("RequestChannel Object Path: %s" % path)
240                 return path
241
242         def _generate_props(self, channelType, handle, suppressHandler, initiatorHandle=None):
243                 targetHandle = 0 if handle is None else handle.get_id()
244                 targetHandleType = telepathy.HANDLE_TYPE_NONE if handle is None else handle.get_type()
245                 props = {
246                         telepathy.CHANNEL_INTERFACE + '.ChannelType': channelType,
247                         telepathy.CHANNEL_INTERFACE + '.TargetHandle': targetHandle,
248                         telepathy.CHANNEL_INTERFACE + '.TargetHandleType': targetHandleType,
249                         telepathy.CHANNEL_INTERFACE + '.Requested': suppressHandler
250                 }
251
252                 if initiatorHandle is not None:
253                         props[telepathy.CHANNEL_INTERFACE + '.InitiatorHandle'] = initiatorHandle.id
254
255                 return props
256
257         def _disconnect(self):
258                 _moduleLogger.info("Disconnecting")
259                 self.session.voicemails.updateSignalHandler.unregister_sink(
260                         self.__callback
261                 )
262                 self.session.texts.updateSignalHandler.unregister_sink(
263                         self.__callback
264                 )
265                 self.__callback = None
266
267                 self.__channelManager.close()
268                 self.session.save(self.__cachePath)
269                 self.session.logout()
270                 self.session.close()
271                 self.__session = None
272                 if self.__connection is not None:
273                         self.__connection.disconnect(self.__connectionEventId)
274                         self.__connectionEventId = None
275
276                 self.manager.disconnected(self)
277                 _moduleLogger.info("Disconnected")
278
279         @gtk_toolbox.log_exception(_moduleLogger)
280         def _on_conversations_updated(self, conv, conversationIds):
281                 _moduleLogger.debug("Incoming messages from: %r" % (conversationIds, ))
282                 for phoneNumber in conversationIds:
283                         h = self.get_handle_by_name(telepathy.HANDLE_TYPE_CONTACT, phoneNumber)
284                         # Just let the TextChannel decide whether it should be reported to the user or not
285                         props = self._generate_props(telepathy.CHANNEL_TYPE_TEXT, h, False)
286                         chan = self.__channelManager.channel_for_props(props, signal=True)
287
288         @gtk_toolbox.log_exception(_moduleLogger)
289         def _on_connection_change(self, connection, event):
290                 """
291                 @note Maemo specific
292
293                 @todo Make this delayed to handle background switching of networks
294                 """
295                 status = event.get_status()
296                 error = event.get_error()
297                 iap_id = event.get_iap_id()
298                 bearer = event.get_bearer_type()
299
300                 if status == conic.STATUS_DISCONNECTED:
301                         _moduleLogger.info("Disconnecting due to loss of network connection")
302                         self.StatusChanged(
303                                 telepathy.CONNECTION_STATUS_DISCONNECTED,
304                                 telepathy.CONNECTION_STATUS_REASON_NETWORK_ERROR
305                         )
306                         try:
307                                 self._disconnect()
308                         except Exception:
309                                 _moduleLogger.exception("Error durring disconnect")