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