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