Adding conic dependency, fixing bug with disconnecting from conic, reducing the numbe...
[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 """
7
8
9 import os
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 util.misc as util_misc
25 import gtk_toolbox
26
27 import gvoice
28 import handle
29
30 import requests
31 import contacts
32 import aliasing
33 import simple_presence
34 import presence
35 import capabilities
36
37 import channel_manager
38
39
40 _moduleLogger = logging.getLogger("connection")
41
42
43 class TheOneRingConnection(
44         tp.Connection,
45         requests.RequestsMixin,
46         contacts.ContactsMixin,
47         aliasing.AliasingMixin,
48         simple_presence.SimplePresenceMixin,
49         presence.PresenceMixin,
50         capabilities.CapabilitiesMixin,
51 ):
52
53         # overiding base class variable
54         _mandatory_parameters = {
55                 'account' : 's',
56                 'password' : 's',
57         }
58         # overiding base class variable
59         _optional_parameters = {
60                 'forward' : 's',
61         }
62         _parameter_defaults = {
63                 'forward' : '',
64         }
65         _secret_parameters = set((
66                 "password",
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                 self.__session = gvoice.session.Session(None)
81                 tp.Connection.__init__(
82                         self,
83                         constants._telepathy_protocol_name_,
84                         account,
85                         constants._telepathy_implementation_name_
86                 )
87                 requests.RequestsMixin.__init__(self)
88                 contacts.ContactsMixin.__init__(self)
89                 aliasing.AliasingMixin.__init__(self)
90                 simple_presence.SimplePresenceMixin.__init__(self)
91                 presence.PresenceMixin.__init__(self)
92                 capabilities.CapabilitiesMixin.__init__(self)
93
94                 self.__manager = weakref.proxy(manager)
95                 self.__credentials = (
96                         encodedAccount,
97                         encodedPassword,
98                 )
99                 self.__callbackNumberParameter = encodedCallback
100                 self.__channelManager = channel_manager.ChannelManager(self)
101
102                 if conic is not None:
103                         self.__connection = conic.Connection()
104                 else:
105                         self.__connection = None
106                 self.__cachePath = os.sep.join((constants._data_path_, "cache", self.username))
107                 try:
108                         os.makedirs(self.__cachePath)
109                 except OSError, e:
110                         if e.errno != 17:
111                                 raise
112
113                 self.set_self_handle(handle.create_handle(self, 'connection'))
114
115                 self.__callback = None
116                 _moduleLogger.info("Connection to the account %s created" % account)
117
118         @property
119         def manager(self):
120                 return self.__manager
121
122         @property
123         def session(self):
124                 return self.__session
125
126         @property
127         def username(self):
128                 return self.__credentials[0]
129
130         @property
131         def callbackNumberParameter(self):
132                 return self.__callbackNumberParameter
133
134         def get_handle_by_name(self, handleType, handleName):
135                 requestedHandleName = handleName.encode('utf-8')
136                 if handleType == telepathy.HANDLE_TYPE_CONTACT:
137                         _moduleLogger.info("get_handle_by_name Contact: %s" % requestedHandleName)
138                         h = handle.create_handle(self, 'contact', requestedHandleName)
139                 elif handleType == telepathy.HANDLE_TYPE_LIST:
140                         # Support only server side (immutable) lists
141                         _moduleLogger.info("get_handle_by_name List: %s" % requestedHandleName)
142                         h = handle.create_handle(self, 'list', requestedHandleName)
143                 else:
144                         raise telepathy.errors.NotAvailable('Handle type unsupported %d' % handleType)
145                 return h
146
147         @property
148         def _channel_manager(self):
149                 return self.__channelManager
150
151         @gtk_toolbox.log_exception(_moduleLogger)
152         def Connect(self):
153                 """
154                 For org.freedesktop.telepathy.Connection
155                 """
156                 _moduleLogger.info("Connecting...")
157                 self.StatusChanged(
158                         telepathy.CONNECTION_STATUS_CONNECTING,
159                         telepathy.CONNECTION_STATUS_REASON_REQUESTED
160                 )
161                 try:
162                         self.__session.load(self.__cachePath)
163
164                         self.__callback = coroutines.func_sink(
165                                 coroutines.expand_positional(
166                                         self._on_conversations_updated
167                                 )
168                         )
169                         self.session.voicemails.updateSignalHandler.register_sink(
170                                 self.__callback
171                         )
172                         self.session.texts.updateSignalHandler.register_sink(
173                                 self.__callback
174                         )
175                         self.session.login(*self.__credentials)
176                         if not self.__callbackNumberParameter:
177                                 callback = gvoice.backend.get_sane_callback(
178                                         self.session.backend
179                                 )
180                                 self.__callbackNumberParameter = util_misc.normalize_number(callback)
181                         self.session.backend.set_callback_number(self.__callbackNumberParameter)
182
183                         subscribeHandle = self.get_handle_by_name(telepathy.HANDLE_TYPE_LIST, "subscribe")
184                         subscribeProps = self._generate_props(telepathy.CHANNEL_TYPE_CONTACT_LIST, subscribeHandle, False)
185                         self.__channelManager.channel_for_props(subscribeProps, signal=True)
186                         publishHandle = self.get_handle_by_name(telepathy.HANDLE_TYPE_LIST, "publish")
187                         publishProps = self._generate_props(telepathy.CHANNEL_TYPE_CONTACT_LIST, publishHandle, False)
188                         self.__channelManager.channel_for_props(publishProps, signal=True)
189                 except gvoice.backend.NetworkError, e:
190                         _moduleLogger.exception("Connection Failed")
191                         self.StatusChanged(
192                                 telepathy.CONNECTION_STATUS_DISCONNECTED,
193                                 telepathy.CONNECTION_STATUS_REASON_NETWORK_ERROR
194                         )
195                         return
196                 except Exception, e:
197                         _moduleLogger.exception("Connection Failed")
198                         self.StatusChanged(
199                                 telepathy.CONNECTION_STATUS_DISCONNECTED,
200                                 telepathy.CONNECTION_STATUS_REASON_AUTHENTICATION_FAILED
201                         )
202                         return
203
204                 _moduleLogger.info("Connected")
205                 self.StatusChanged(
206                         telepathy.CONNECTION_STATUS_CONNECTED,
207                         telepathy.CONNECTION_STATUS_REASON_REQUESTED
208                 )
209                 if self.__connection is not None:
210                         self.__connectionEventId = self.__connection.connect("connection-event", self._on_connection_change)
211
212         @gtk_toolbox.log_exception(_moduleLogger)
213         def Disconnect(self):
214                 """
215                 For org.freedesktop.telepathy.Connection
216                 """
217                 self.StatusChanged(
218                         telepathy.CONNECTION_STATUS_DISCONNECTED,
219                         telepathy.CONNECTION_STATUS_REASON_REQUESTED
220                 )
221                 try:
222                         self._disconnect()
223                 except Exception:
224                         _moduleLogger.exception("Error durring disconnect")
225
226         @gtk_toolbox.log_exception(_moduleLogger)
227         def RequestChannel(self, type, handleType, handleId, suppressHandler):
228                 """
229                 For org.freedesktop.telepathy.Connection
230
231                 @param type DBus interface name for base channel type
232                 @param handleId represents a contact, list, etc according to handleType
233
234                 @returns DBus object path for the channel created or retrieved
235                 """
236                 self.check_connected()
237                 self.check_handle(handleType, handleId)
238
239                 h = self.get_handle_by_id(handleType, handleId) if handleId != 0 else None
240                 props = self._generate_props(type, h, suppressHandler)
241                 self._validate_handle(props)
242
243                 chan = self.__channelManager.channel_for_props(props, signal=True)
244                 path = chan._object_path
245                 _moduleLogger.info("RequestChannel Object Path (%s): %s" % (type.rsplit(".", 1)[-1], path))
246                 return path
247
248         def _generate_props(self, channelType, handle, suppressHandler, initiatorHandle=None):
249                 targetHandle = 0 if handle is None else handle.get_id()
250                 targetHandleType = telepathy.HANDLE_TYPE_NONE if handle is None else handle.get_type()
251                 props = {
252                         telepathy.CHANNEL_INTERFACE + '.ChannelType': channelType,
253                         telepathy.CHANNEL_INTERFACE + '.TargetHandle': targetHandle,
254                         telepathy.CHANNEL_INTERFACE + '.TargetHandleType': targetHandleType,
255                         telepathy.CHANNEL_INTERFACE + '.Requested': suppressHandler
256                 }
257
258                 if initiatorHandle is not None:
259                         props[telepathy.CHANNEL_INTERFACE + '.InitiatorHandle'] = initiatorHandle.id
260
261                 return props
262
263         def _disconnect(self):
264                 _moduleLogger.info("Disconnecting")
265                 self.session.voicemails.updateSignalHandler.unregister_sink(
266                         self.__callback
267                 )
268                 self.session.texts.updateSignalHandler.unregister_sink(
269                         self.__callback
270                 )
271                 self.__callback = None
272
273                 self.__channelManager.close()
274                 self.session.save(self.__cachePath)
275                 self.session.logout()
276                 self.session.close()
277
278                 self.manager.disconnected(self)
279                 _moduleLogger.info("Disconnected")
280
281         @gtk_toolbox.log_exception(_moduleLogger)
282         def _on_conversations_updated(self, conv, conversationIds):
283                 _moduleLogger.debug("Incoming messages from: %r" % (conversationIds, ))
284                 for phoneNumber in conversationIds:
285                         h = self.get_handle_by_name(telepathy.HANDLE_TYPE_CONTACT, phoneNumber)
286                         # Just let the TextChannel decide whether it should be reported to the user or not
287                         props = self._generate_props(telepathy.CHANNEL_TYPE_TEXT, h, False)
288                         if self.__channelManager.channel_exists(props):
289                                 continue
290
291                         # Maemo 4.1's RTComm opens a window for a chat regardless if a
292                         # message is received or not, so we need to do some filtering here
293                         mergedConv = conv.get_conversation(phoneNumber)
294                         unreadConvs = [
295                                 conversation
296                                 for conversation in mergedConv.conversations
297                                 if not conversation.isRead and not conversation.isArchived
298                         ]
299                         if not unreadConvs:
300                                 continue
301
302                         chan = self.__channelManager.channel_for_props(props, signal=True)
303
304         @gtk_toolbox.log_exception(_moduleLogger)
305         def _on_connection_change(self, connection, event):
306                 """
307                 @note Maemo specific
308
309                 @todo Make this delayed to handle background switching of networks.  First I need to verify I receive connected
310                 """
311                 if not self.session.is_logged_in():
312                         _moduleLogger.info("Received connection change event when not logged in")
313                         return
314                 status = event.get_status()
315                 error = event.get_error()
316                 iap_id = event.get_iap_id()
317                 bearer = event.get_bearer_type()
318
319                 if status == conic.STATUS_DISCONNECTED:
320                         _moduleLogger.info("Disconnecting due to loss of network connection")
321                         self.StatusChanged(
322                                 telepathy.CONNECTION_STATUS_DISCONNECTED,
323                                 telepathy.CONNECTION_STATUS_REASON_NETWORK_ERROR
324                         )
325                         try:
326                                 self._disconnect()
327                         except Exception:
328                                 _moduleLogger.exception("Error durring disconnect")
329                 else:
330                         _moduleLogger.info("Other status: %r" % (status, ))