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
16 import conic as _conic
18 except (ImportError, OSError):
23 import util.coroutines as coroutines
24 import util.misc as util_misc
33 import simple_presence
37 import channel_manager
40 _moduleLogger = logging.getLogger("connection")
43 class TheOneRingConnection(
45 requests.RequestsMixin,
46 contacts.ContactsMixin,
47 aliasing.AliasingMixin,
48 simple_presence.SimplePresenceMixin,
49 presence.PresenceMixin,
50 capabilities.CapabilitiesMixin,
53 # overiding base class variable
54 _mandatory_parameters = {
58 # overiding base class variable
59 _optional_parameters = {
62 _parameter_defaults = {
65 _secret_parameters = set((
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")
79 # Connection init must come first
80 self.__session = gvoice.session.Session(None)
81 tp.Connection.__init__(
83 constants._telepathy_protocol_name_,
85 constants._telepathy_implementation_name_
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)
94 self.__manager = weakref.proxy(manager)
95 self.__credentials = (
99 self.__callbackNumberParameter = encodedCallback
100 self.__channelManager = channel_manager.ChannelManager(self)
102 if conic is not None:
103 self.__connection = conic.Connection()
105 self.__connection = None
106 self.__cachePath = os.sep.join((constants._data_path_, "cache", self.username))
108 os.makedirs(self.__cachePath)
113 self.set_self_handle(handle.create_handle(self, 'connection'))
115 self.__callback = None
116 _moduleLogger.info("Connection to the account %s created" % account)
120 return self.__manager
124 return self.__session
128 return self.__credentials[0]
131 def callbackNumberParameter(self):
132 return self.__callbackNumberParameter
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)
144 raise telepathy.errors.NotAvailable('Handle type unsupported %d' % handleType)
148 def _channel_manager(self):
149 return self.__channelManager
151 @gtk_toolbox.log_exception(_moduleLogger)
154 For org.freedesktop.telepathy.Connection
156 _moduleLogger.info("Connecting...")
158 telepathy.CONNECTION_STATUS_CONNECTING,
159 telepathy.CONNECTION_STATUS_REASON_REQUESTED
162 self.__session.load(self.__cachePath)
164 self.__callback = coroutines.func_sink(
165 coroutines.expand_positional(
166 self._on_conversations_updated
169 self.session.voicemails.updateSignalHandler.register_sink(
172 self.session.texts.updateSignalHandler.register_sink(
175 self.session.login(*self.__credentials)
176 if not self.__callbackNumberParameter:
177 callback = gvoice.backend.get_sane_callback(
180 self.__callbackNumberParameter = util_misc.normalize_number(callback)
181 self.session.backend.set_callback_number(self.__callbackNumberParameter)
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")
192 telepathy.CONNECTION_STATUS_DISCONNECTED,
193 telepathy.CONNECTION_STATUS_REASON_NETWORK_ERROR
197 _moduleLogger.exception("Connection Failed")
199 telepathy.CONNECTION_STATUS_DISCONNECTED,
200 telepathy.CONNECTION_STATUS_REASON_AUTHENTICATION_FAILED
204 _moduleLogger.info("Connected")
206 telepathy.CONNECTION_STATUS_CONNECTED,
207 telepathy.CONNECTION_STATUS_REASON_REQUESTED
209 if self.__connection is not None:
210 self.__connectionEventId = self.__connection.connect("connection-event", self._on_connection_change)
212 @gtk_toolbox.log_exception(_moduleLogger)
213 def Disconnect(self):
215 For org.freedesktop.telepathy.Connection
218 telepathy.CONNECTION_STATUS_DISCONNECTED,
219 telepathy.CONNECTION_STATUS_REASON_REQUESTED
224 _moduleLogger.exception("Error durring disconnect")
226 @gtk_toolbox.log_exception(_moduleLogger)
227 def RequestChannel(self, type, handleType, handleId, suppressHandler):
229 For org.freedesktop.telepathy.Connection
231 @param type DBus interface name for base channel type
232 @param handleId represents a contact, list, etc according to handleType
234 @returns DBus object path for the channel created or retrieved
236 self.check_connected()
237 self.check_handle(handleType, handleId)
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)
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))
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()
252 telepathy.CHANNEL_INTERFACE + '.ChannelType': channelType,
253 telepathy.CHANNEL_INTERFACE + '.TargetHandle': targetHandle,
254 telepathy.CHANNEL_INTERFACE + '.TargetHandleType': targetHandleType,
255 telepathy.CHANNEL_INTERFACE + '.Requested': suppressHandler
258 if initiatorHandle is not None:
259 props[telepathy.CHANNEL_INTERFACE + '.InitiatorHandle'] = initiatorHandle.id
263 def _disconnect(self):
264 _moduleLogger.info("Disconnecting")
265 self.session.voicemails.updateSignalHandler.unregister_sink(
268 self.session.texts.updateSignalHandler.unregister_sink(
271 self.__callback = None
273 self.__channelManager.close()
274 self.session.save(self.__cachePath)
275 self.session.logout()
278 self.manager.disconnected(self)
279 _moduleLogger.info("Disconnected")
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):
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)
296 for conversation in mergedConv.conversations
297 if not conversation.isRead and not conversation.isArchived
302 chan = self.__channelManager.channel_for_props(props, signal=True)
304 @gtk_toolbox.log_exception(_moduleLogger)
305 def _on_connection_change(self, connection, event):
309 @todo Make this delayed to handle background switching of networks. First I need to verify I receive connected
311 if not self.session.is_logged_in():
312 _moduleLogger.info("Received connection change event when not logged in")
314 status = event.get_status()
315 error = event.get_error()
316 iap_id = event.get_iap_id()
317 bearer = event.get_bearer_type()
319 if status == conic.STATUS_DISCONNECTED:
320 _moduleLogger.info("Disconnecting due to loss of network connection")
322 telepathy.CONNECTION_STATUS_DISCONNECTED,
323 telepathy.CONNECTION_STATUS_REASON_NETWORK_ERROR
328 _moduleLogger.exception("Error durring disconnect")
330 _moduleLogger.info("Other status: %r" % (status, ))