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