Maemo: Attempting to save on battery by forcing a disconnect on network connection...
[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.go_utils as gobject_utils
24 import util.coroutines as coroutines
25 import gtk_toolbox
26
27 import gvoice
28 import handle
29
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         telepathy.server.ConnectionInterfaceRequests, # already a mixin
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                 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 handle(self, handleType, handleId):
127                 self.check_handle(handleType, handleId)
128                 return self._handles[handleType, handleId]
129
130         @gtk_toolbox.log_exception(_moduleLogger)
131         def Connect(self):
132                 """
133                 For org.freedesktop.telepathy.Connection
134                 """
135                 _moduleLogger.info("Connecting...")
136                 self.StatusChanged(
137                         telepathy.CONNECTION_STATUS_CONNECTING,
138                         telepathy.CONNECTION_STATUS_REASON_REQUESTED
139                 )
140                 try:
141                         cookieFilePath = None
142                         self._session = gvoice.session.Session(cookieFilePath)
143
144                         self._callback = coroutines.func_sink(
145                                 coroutines.expand_positional(
146                                         self._on_conversations_updated
147                                 )
148                         )
149                         self.session.voicemails.updateSignalHandler.register_sink(
150                                 self._callback
151                         )
152                         self.session.texts.updateSignalHandler.register_sink(
153                                 self._callback
154                         )
155                         self.session.login(*self._credentials)
156                         self.session.backend.set_callback_number(self._callbackNumber)
157                 except gvoice.backend.NetworkError, e:
158                         _moduleLogger.exception("Connection Failed")
159                         self.StatusChanged(
160                                 telepathy.CONNECTION_STATUS_DISCONNECTED,
161                                 telepathy.CONNECTION_STATUS_REASON_NETWORK_ERROR
162                         )
163                         return
164                 except Exception, e:
165                         _moduleLogger.exception("Connection Failed")
166                         self.StatusChanged(
167                                 telepathy.CONNECTION_STATUS_DISCONNECTED,
168                                 telepathy.CONNECTION_STATUS_REASON_AUTHENTICATION_FAILED
169                         )
170                         return
171
172                 _moduleLogger.info("Connected")
173                 self.StatusChanged(
174                         telepathy.CONNECTION_STATUS_CONNECTED,
175                         telepathy.CONNECTION_STATUS_REASON_REQUESTED
176                 )
177                 if self._connection is not None:
178                         self._connectionEventId = self._connection.connect("connection-event", self._on_connection_change)
179
180         @gtk_toolbox.log_exception(_moduleLogger)
181         def Disconnect(self):
182                 """
183                 For org.freedesktop.telepathy.Connection
184                 @bug Not properly logging out.  Cookie files need to be per connection and removed
185                 """
186                 self.StatusChanged(
187                         telepathy.CONNECTION_STATUS_DISCONNECTED,
188                         telepathy.CONNECTION_STATUS_REASON_REQUESTED
189                 )
190                 try:
191                         self._disconnect()
192                 except Exception:
193                         _moduleLogger.exception("Error durring disconnect")
194
195         @gtk_toolbox.log_exception(_moduleLogger)
196         def RequestChannel(self, type, handleType, handleId, suppressHandler):
197                 """
198                 For org.freedesktop.telepathy.Connection
199
200                 @param type DBus interface name for base channel type
201                 @param handleId represents a contact, list, etc according to handleType
202
203                 @returns DBus object path for the channel created or retrieved
204                 """
205                 self.check_connected()
206                 self.check_handle(handleType, handleId)
207
208                 h = self.handle(handleType, handleId) if handleId != 0 else None
209                 props = self._generate_props(type, h, suppressHandler)
210                 if hasattr(self, "_validate_handle"):
211                         # HACK Newer python-telepathy
212                         self._validate_handle(props)
213
214                 chan = self._channelManager.channel_for_props(props, signal=True)
215                 path = chan._object_path
216                 _moduleLogger.info("RequestChannel Object Path: %s" % path)
217                 return path
218
219         @gtk_toolbox.log_exception(_moduleLogger)
220         def RequestHandles(self, handleType, names, sender):
221                 """
222                 For org.freedesktop.telepathy.Connection
223                 Overiding telepathy.server.Connecton to allow custom handles
224                 """
225                 self.check_connected()
226                 self.check_handle_type(handleType)
227
228                 handles = []
229                 for name in names:
230                         requestedHandleName = name.encode('utf-8')
231                         if handleType == telepathy.HANDLE_TYPE_CONTACT:
232                                 _moduleLogger.info("RequestHandles Contact: %s" % requestedHandleName)
233                                 requestedContactId, requestedContactNumber = handle.ContactHandle.from_handle_name(
234                                         requestedHandleName
235                                 )
236                                 h = handle.create_handle(self, 'contact', requestedContactId, requestedContactNumber)
237                         elif handleType == telepathy.HANDLE_TYPE_LIST:
238                                 # Support only server side (immutable) lists
239                                 _moduleLogger.info("RequestHandles List: %s" % requestedHandleName)
240                                 h = handle.create_handle(self, 'list', requestedHandleName)
241                         else:
242                                 raise telepathy.errors.NotAvailable('Handle type unsupported %d' % handleType)
243                         handles.append(h.id)
244                         self.add_client_handle(h, sender)
245                 return handles
246
247         def _generate_props(self, channelType, handle, suppressHandler, initiatorHandle=None):
248                 targetHandle = 0 if handle is None else handle.get_id()
249                 targetHandleType = telepathy.HANDLE_TYPE_NONE if handle is None else handle.get_type()
250                 props = {
251                         telepathy.CHANNEL_INTERFACE + '.ChannelType': channelType,
252                         telepathy.CHANNEL_INTERFACE + '.TargetHandle': targetHandle,
253                         telepathy.CHANNEL_INTERFACE + '.TargetHandleType': targetHandleType,
254                         telepathy.CHANNEL_INTERFACE + '.Requested': suppressHandler
255                 }
256
257                 if initiatorHandle is not None:
258                         props[telepathy.CHANNEL_INTERFACE + '.InitiatorHandle'] = initiatorHandle.id
259
260                 return props
261
262         def _disconnect(self):
263                 _moduleLogger.info("Disconnecting")
264                 self.session.voicemails.updateSignalHandler.unregister_sink(
265                         self._callback
266                 )
267                 self.session.texts.updateSignalHandler.unregister_sink(
268                         self._callback
269                 )
270                 self._callback = None
271
272                 self._channelManager.close()
273                 self.session.logout()
274                 self.session.close()
275                 self._session = None
276                 if self._connection is not None:
277                         self._connection.disconnect(self._connectionEventId)
278                         self._connectionEventId = None
279
280                 self.manager.disconnected(self)
281                 _moduleLogger.info("Disconnected")
282
283         @gobject_utils.async
284         @gtk_toolbox.log_exception(_moduleLogger)
285         def _on_conversations_updated(self, conv, conversationIds):
286                 _moduleLogger.debug("Incoming messages from: %r" % (conversationIds, ))
287                 for contactId, phoneNumber in conversationIds:
288                         h = handle.create_handle(self, 'contact', contactId, phoneNumber)
289                         # Just let the TextChannel decide whether it should be reported to the user or not
290                         props = self._generate_props(telepathy.CHANNEL_TYPE_TEXT, h, False)
291                         channel = self._channelManager.channel_for_props(props, signal=True)
292
293         @gtk_toolbox.log_exception(_moduleLogger)
294         def _on_connection_change(self, connection, event):
295                 """
296                 @note Maemo specific
297                 """
298                 status = event.get_status()
299                 error = event.get_error()
300                 iap_id = event.get_iap_id()
301                 bearer = event.get_bearer_type()
302
303                 if status == conic.STATUS_DISCONNECTED:
304                         _moduleLogger.info("Disconnecting due to loss of network connection")
305                         self.StatusChanged(
306                                 telepathy.CONNECTION_STATUS_DISCONNECTED,
307                                 telepathy.CONNECTION_STATUS_REASON_NETWORK_ERROR
308                         )
309                         try:
310                                 self._disconnect()
311                         except Exception:
312                                 _moduleLogger.exception("Error durring disconnect")