Pushing out 0.7.0-4 deb
[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 @bug Reporting of network errors on login (I think its because two CM's are attempting to be created for some odd reason)
7 @bug Integration with system contacts, like what Sofia does, isn't working
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         # overiding base class variable
56         _mandatory_parameters = {
57                 'account' : 's',
58                 'password' : 's',
59         }
60         # overiding base class variable
61         _optional_parameters = {
62                 'forward' : 's',
63         }
64         _parameter_defaults = {
65                 'forward' : '',
66         }
67         _secret_parameters = set((
68                 "password",
69         ))
70
71         @gtk_toolbox.log_exception(_moduleLogger)
72         def __init__(self, manager, parameters):
73                 self.check_parameters(parameters)
74                 account = unicode(parameters['account'])
75                 encodedAccount = parameters['account'].encode('utf-8')
76                 encodedPassword = parameters['password'].encode('utf-8')
77                 encodedCallback = util_misc.normalize_number(parameters['forward'].encode('utf-8'))
78                 if encodedCallback and not util_misc.is_valid_number(encodedCallback):
79                         raise telepathy.errors.InvalidArgument("Invalid forwarding number")
80
81                 # Connection init must come first
82                 self.__session = gvoice.session.Session(None)
83                 tp.Connection.__init__(
84                         self,
85                         constants._telepathy_protocol_name_,
86                         account,
87                         constants._telepathy_implementation_name_
88                 )
89                 requests.RequestsMixin.__init__(self)
90                 contacts.ContactsMixin.__init__(self)
91                 aliasing.AliasingMixin.__init__(self)
92                 simple_presence.SimplePresenceMixin.__init__(self)
93                 presence.PresenceMixin.__init__(self)
94                 capabilities.CapabilitiesMixin.__init__(self)
95
96                 self.__manager = weakref.proxy(manager)
97                 self.__credentials = (
98                         encodedAccount,
99                         encodedPassword,
100                 )
101                 self.__callbackNumberParameter = encodedCallback
102                 self.__channelManager = channel_manager.ChannelManager(self)
103
104                 if conic is not None:
105                         self.__connection = conic.Connection()
106                 else:
107                         self.__connection = 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                         h = handle.create_handle(self, 'contact', requestedHandleName)
141                 elif handleType == telepathy.HANDLE_TYPE_LIST:
142                         # Support only server side (immutable) lists
143                         _moduleLogger.info("get_handle_by_name 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                         self.__session.load(self.__cachePath)
165
166                         self.__callback = coroutines.func_sink(
167                                 coroutines.expand_positional(
168                                         self._on_conversations_updated
169                                 )
170                         )
171                         self.session.voicemails.updateSignalHandler.register_sink(
172                                 self.__callback
173                         )
174                         self.session.texts.updateSignalHandler.register_sink(
175                                 self.__callback
176                         )
177                         self.session.login(*self.__credentials)
178                         if not self.__callbackNumberParameter:
179                                 callback = gvoice.backend.get_sane_callback(
180                                         self.session.backend
181                                 )
182                                 self.__callbackNumberParameter = util_misc.normalize_number(callback)
183                         self.session.backend.set_callback_number(self.__callbackNumberParameter)
184
185                         subscribeHandle = self.get_handle_by_name(telepathy.HANDLE_TYPE_LIST, "subscribe")
186                         subscribeProps = self._generate_props(telepathy.CHANNEL_TYPE_CONTACT_LIST, subscribeHandle, False)
187                         self.__channelManager.channel_for_props(subscribeProps, signal=True)
188                         publishHandle = self.get_handle_by_name(telepathy.HANDLE_TYPE_LIST, "publish")
189                         publishProps = self._generate_props(telepathy.CHANNEL_TYPE_CONTACT_LIST, publishHandle, False)
190                         self.__channelManager.channel_for_props(publishProps, signal=True)
191                 except gvoice.backend.NetworkError, e:
192                         _moduleLogger.exception("Connection Failed")
193                         self.StatusChanged(
194                                 telepathy.CONNECTION_STATUS_DISCONNECTED,
195                                 telepathy.CONNECTION_STATUS_REASON_NETWORK_ERROR
196                         )
197                         return
198                 except Exception, e:
199                         _moduleLogger.exception("Connection Failed")
200                         self.StatusChanged(
201                                 telepathy.CONNECTION_STATUS_DISCONNECTED,
202                                 telepathy.CONNECTION_STATUS_REASON_AUTHENTICATION_FAILED
203                         )
204                         return
205
206                 _moduleLogger.info("Connected")
207                 self.StatusChanged(
208                         telepathy.CONNECTION_STATUS_CONNECTED,
209                         telepathy.CONNECTION_STATUS_REASON_REQUESTED
210                 )
211                 if self.__connection is not None:
212                         self.__connectionEventId = self.__connection.connect("connection-event", self._on_connection_change)
213
214         @gtk_toolbox.log_exception(_moduleLogger)
215         def Disconnect(self):
216                 """
217                 For org.freedesktop.telepathy.Connection
218                 """
219                 self.StatusChanged(
220                         telepathy.CONNECTION_STATUS_DISCONNECTED,
221                         telepathy.CONNECTION_STATUS_REASON_REQUESTED
222                 )
223                 try:
224                         self._disconnect()
225                 except Exception:
226                         _moduleLogger.exception("Error durring disconnect")
227
228         @gtk_toolbox.log_exception(_moduleLogger)
229         def RequestChannel(self, type, handleType, handleId, suppressHandler):
230                 """
231                 For org.freedesktop.telepathy.Connection
232
233                 @param type DBus interface name for base channel type
234                 @param handleId represents a contact, list, etc according to handleType
235
236                 @returns DBus object path for the channel created or retrieved
237                 """
238                 self.check_connected()
239                 self.check_handle(handleType, handleId)
240
241                 h = self.get_handle_by_id(handleType, handleId) if handleId != 0 else None
242                 props = self._generate_props(type, h, suppressHandler)
243                 self._validate_handle(props)
244
245                 chan = self.__channelManager.channel_for_props(props, signal=True)
246                 path = chan._object_path
247                 _moduleLogger.info("RequestChannel Object Path (%s): %s" % (type.rsplit(".", 1)[-1], path))
248                 return path
249
250         def _generate_props(self, channelType, handle, suppressHandler, initiatorHandle=None):
251                 targetHandle = 0 if handle is None else handle.get_id()
252                 targetHandleType = telepathy.HANDLE_TYPE_NONE if handle is None else handle.get_type()
253                 props = {
254                         telepathy.CHANNEL_INTERFACE + '.ChannelType': channelType,
255                         telepathy.CHANNEL_INTERFACE + '.TargetHandle': targetHandle,
256                         telepathy.CHANNEL_INTERFACE + '.TargetHandleType': targetHandleType,
257                         telepathy.CHANNEL_INTERFACE + '.Requested': suppressHandler
258                 }
259
260                 if initiatorHandle is not None:
261                         props[telepathy.CHANNEL_INTERFACE + '.InitiatorHandle'] = initiatorHandle.id
262
263                 return props
264
265         def _disconnect(self):
266                 _moduleLogger.info("Disconnecting")
267                 self.session.voicemails.updateSignalHandler.unregister_sink(
268                         self.__callback
269                 )
270                 self.session.texts.updateSignalHandler.unregister_sink(
271                         self.__callback
272                 )
273                 self.__callback = None
274
275                 self.__channelManager.close()
276                 self.session.save(self.__cachePath)
277                 self.session.logout()
278                 self.session.close()
279
280                 self.manager.disconnected(self)
281                 _moduleLogger.info("Disconnected")
282
283         @gtk_toolbox.log_exception(_moduleLogger)
284         def _on_conversations_updated(self, conv, conversationIds):
285                 _moduleLogger.debug("Incoming messages from: %r" % (conversationIds, ))
286                 for phoneNumber in conversationIds:
287                         h = self.get_handle_by_name(telepathy.HANDLE_TYPE_CONTACT, phoneNumber)
288                         # Just let the TextChannel decide whether it should be reported to the user or not
289                         props = self._generate_props(telepathy.CHANNEL_TYPE_TEXT, h, False)
290                         if self.__channelManager.channel_exists(props):
291                                 continue
292
293                         # Maemo 4.1's RTComm opens a window for a chat regardless if a
294                         # message is received or not, so we need to do some filtering here
295                         mergedConv = conv.get_conversation(phoneNumber)
296                         unreadConvs = [
297                                 conversation
298                                 for conversation in mergedConv.conversations
299                                 if not conversation.isRead and not conversation.isArchived
300                         ]
301                         if not unreadConvs:
302                                 continue
303
304                         chan = self.__channelManager.channel_for_props(props, signal=True)
305
306         @gtk_toolbox.log_exception(_moduleLogger)
307         def _on_connection_change(self, connection, event):
308                 """
309                 @note Maemo specific
310
311                 @todo Make this delayed to handle background switching of networks.  First I need to verify I receive connected
312                 """
313                 if not self.session.is_logged_in():
314                         _moduleLogger.info("Received connection change event when not logged in")
315                         return
316                 status = event.get_status()
317                 error = event.get_error()
318                 iap_id = event.get_iap_id()
319                 bearer = event.get_bearer_type()
320
321                 if status == conic.STATUS_DISCONNECTED:
322                         _moduleLogger.info("Disconnecting due to loss of network connection")
323                         self.StatusChanged(
324                                 telepathy.CONNECTION_STATUS_DISCONNECTED,
325                                 telepathy.CONNECTION_STATUS_REASON_NETWORK_ERROR
326                         )
327                         try:
328                                 self._disconnect()
329                         except Exception:
330                                 _moduleLogger.exception("Error durring disconnect")
331                 else:
332                         _moduleLogger.info("Other status: %r" % (status, ))