Old python-telepathy didn'
[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 Observe when connected/disconnected to disconnect CM
8 """
9
10
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 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         telepathy.server.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                 telepathy.server.Connection.__init__(
77                         self,
78                         constants._telepathy_protocol_name_,
79                         account,
80                         constants._telepathy_implementation_name_
81                 )
82                 #telepathy.server.ConnectionInterfaceRequests.__init__(self)
83                 requests.RequestsMixin.__init__(self)
84                 contacts.ContactsMixin.__init__(self)
85                 aliasing.AliasingMixin.__init__(self)
86                 simple_presence.SimplePresenceMixin.__init__(self)
87                 presence.PresenceMixin.__init__(self)
88                 capabilities.CapabilitiesMixin.__init__(self)
89
90                 self.__manager = weakref.proxy(manager)
91                 self.__credentials = (
92                         encodedAccount,
93                         encodedPassword,
94                 )
95                 self.__callbackNumber = encodedCallback
96                 self.__channelManager = channel_manager.ChannelManager(self)
97
98                 self.__session = gvoice.session.Session(None)
99                 if conic is not None:
100                         self.__connection = conic.Connection()
101                         self.__connectionEventId = None
102                 else:
103                         self.__connection = None
104                         self.__connectionEventId = None
105
106                 self.set_self_handle(handle.create_handle(self, 'connection'))
107
108                 self.__callback = None
109                 _moduleLogger.info("Connection to the account %s created" % account)
110
111         @property
112         def manager(self):
113                 return self.__manager
114
115         @property
116         def session(self):
117                 return self.__session
118
119         @property
120         def username(self):
121                 return self.__credentials[0]
122
123         @property
124         def userAliasType(self):
125                 return self.USER_ALIAS_ACCOUNT
126
127         def handle(self, handleType, handleId):
128                 self.check_handle(handleType, handleId)
129                 return self._handles[handleType, handleId]
130
131         @property
132         def _channel_manager(self):
133                 return self.__channelManager
134
135         @gtk_toolbox.log_exception(_moduleLogger)
136         def Connect(self):
137                 """
138                 For org.freedesktop.telepathy.Connection
139                 """
140                 _moduleLogger.info("Connecting...")
141                 self.StatusChanged(
142                         telepathy.CONNECTION_STATUS_CONNECTING,
143                         telepathy.CONNECTION_STATUS_REASON_REQUESTED
144                 )
145                 try:
146                         cookieFilePath = None
147                         self.__session = gvoice.session.Session(cookieFilePath)
148
149                         self.__callback = coroutines.func_sink(
150                                 coroutines.expand_positional(
151                                         self._on_conversations_updated
152                                 )
153                         )
154                         self.session.voicemails.updateSignalHandler.register_sink(
155                                 self.__callback
156                         )
157                         self.session.texts.updateSignalHandler.register_sink(
158                                 self.__callback
159                         )
160                         self.session.login(*self.__credentials)
161                         self.session.backend.set_callback_number(self.__callbackNumber)
162                 except gvoice.backend.NetworkError, e:
163                         _moduleLogger.exception("Connection Failed")
164                         self.StatusChanged(
165                                 telepathy.CONNECTION_STATUS_DISCONNECTED,
166                                 telepathy.CONNECTION_STATUS_REASON_NETWORK_ERROR
167                         )
168                         return
169                 except Exception, e:
170                         _moduleLogger.exception("Connection Failed")
171                         self.StatusChanged(
172                                 telepathy.CONNECTION_STATUS_DISCONNECTED,
173                                 telepathy.CONNECTION_STATUS_REASON_AUTHENTICATION_FAILED
174                         )
175                         return
176
177                 _moduleLogger.info("Connected")
178                 self.StatusChanged(
179                         telepathy.CONNECTION_STATUS_CONNECTED,
180                         telepathy.CONNECTION_STATUS_REASON_REQUESTED
181                 )
182                 if self.__connection is not None:
183                         self.__connectionEventId = self.__connection.connect("connection-event", self._on_connection_change)
184
185         @gtk_toolbox.log_exception(_moduleLogger)
186         def Disconnect(self):
187                 """
188                 For org.freedesktop.telepathy.Connection
189                 @bug Not properly logging out.  Cookie files need to be per connection and removed
190                 """
191                 self.StatusChanged(
192                         telepathy.CONNECTION_STATUS_DISCONNECTED,
193                         telepathy.CONNECTION_STATUS_REASON_REQUESTED
194                 )
195                 try:
196                         self._disconnect()
197                 except Exception:
198                         _moduleLogger.exception("Error durring disconnect")
199
200         @gtk_toolbox.log_exception(_moduleLogger)
201         def RequestChannel(self, type, handleType, handleId, suppressHandler):
202                 """
203                 For org.freedesktop.telepathy.Connection
204
205                 @param type DBus interface name for base channel type
206                 @param handleId represents a contact, list, etc according to handleType
207
208                 @returns DBus object path for the channel created or retrieved
209                 """
210                 self.check_connected()
211                 self.check_handle(handleType, handleId)
212
213                 h = self.handle(handleType, handleId) if handleId != 0 else None
214                 props = self._generate_props(type, h, suppressHandler)
215                 if hasattr(self, "_validate_handle"):
216                         # HACK Newer python-telepathy
217                         self._validate_handle(props)
218
219                 chan = self.__channelManager.channel_for_props(props, signal=True)
220                 path = chan._object_path
221                 _moduleLogger.info("RequestChannel Object Path: %s" % path)
222                 return path
223
224         @gtk_toolbox.log_exception(_moduleLogger)
225         def RequestHandles(self, handleType, names, sender):
226                 """
227                 For org.freedesktop.telepathy.Connection
228                 Overiding telepathy.server.Connecton to allow custom handles
229                 """
230                 self.check_connected()
231                 self.check_handle_type(handleType)
232
233                 handles = []
234                 for name in names:
235                         requestedHandleName = name.encode('utf-8')
236                         if handleType == telepathy.HANDLE_TYPE_CONTACT:
237                                 _moduleLogger.info("RequestHandles Contact: %s" % requestedHandleName)
238                                 requestedContactId, requestedContactNumber = handle.ContactHandle.from_handle_name(
239                                         requestedHandleName
240                                 )
241                                 h = handle.create_handle(self, 'contact', requestedContactId, requestedContactNumber)
242                         elif handleType == telepathy.HANDLE_TYPE_LIST:
243                                 # Support only server side (immutable) lists
244                                 _moduleLogger.info("RequestHandles List: %s" % requestedHandleName)
245                                 h = handle.create_handle(self, 'list', requestedHandleName)
246                         else:
247                                 raise telepathy.errors.NotAvailable('Handle type unsupported %d' % handleType)
248                         handles.append(h.id)
249                         self.add_client_handle(h, sender)
250                 return handles
251
252         def _generate_props(self, channelType, handle, suppressHandler, initiatorHandle=None):
253                 targetHandle = 0 if handle is None else handle.get_id()
254                 targetHandleType = telepathy.HANDLE_TYPE_NONE if handle is None else handle.get_type()
255                 props = {
256                         telepathy.CHANNEL_INTERFACE + '.ChannelType': channelType,
257                         telepathy.CHANNEL_INTERFACE + '.TargetHandle': targetHandle,
258                         telepathy.CHANNEL_INTERFACE + '.TargetHandleType': targetHandleType,
259                         telepathy.CHANNEL_INTERFACE + '.Requested': suppressHandler
260                 }
261
262                 if initiatorHandle is not None:
263                         props[telepathy.CHANNEL_INTERFACE + '.InitiatorHandle'] = initiatorHandle.id
264
265                 return props
266
267         def _disconnect(self):
268                 _moduleLogger.info("Disconnecting")
269                 self.session.voicemails.updateSignalHandler.unregister_sink(
270                         self.__callback
271                 )
272                 self.session.texts.updateSignalHandler.unregister_sink(
273                         self.__callback
274                 )
275                 self.__callback = None
276
277                 self.__channelManager.close()
278                 self.session.logout()
279                 self.session.close()
280                 self.__session = None
281                 if self.__connection is not None:
282                         self.__connection.disconnect(self.__connectionEventId)
283                         self.__connectionEventId = None
284
285                 self.manager.disconnected(self)
286                 _moduleLogger.info("Disconnected")
287
288         @gtk_toolbox.log_exception(_moduleLogger)
289         def _on_conversations_updated(self, conv, conversationIds):
290                 _moduleLogger.debug("Incoming messages from: %r" % (conversationIds, ))
291                 for contactId, phoneNumber in conversationIds:
292                         h = handle.create_handle(self, 'contact', contactId, phoneNumber)
293                         # Just let the TextChannel decide whether it should be reported to the user or not
294                         props = self._generate_props(telepathy.CHANNEL_TYPE_TEXT, h, False)
295                         channel = self.__channelManager.channel_for_props(props, signal=True)
296
297         @gtk_toolbox.log_exception(_moduleLogger)
298         def _on_connection_change(self, connection, event):
299                 """
300                 @note Maemo specific
301                 """
302                 status = event.get_status()
303                 error = event.get_error()
304                 iap_id = event.get_iap_id()
305                 bearer = event.get_bearer_type()
306
307                 if status == conic.STATUS_DISCONNECTED:
308                         _moduleLogger.info("Disconnecting due to loss of network connection")
309                         self.StatusChanged(
310                                 telepathy.CONNECTION_STATUS_DISCONNECTED,
311                                 telepathy.CONNECTION_STATUS_REASON_NETWORK_ERROR
312                         )
313                         try:
314                                 self._disconnect()
315                         except Exception:
316                                 _moduleLogger.exception("Error durring disconnect")