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()
104 self.__connectionEventId = None
106 self.__connection = None
107 self.__connectionEventId = None
108 self.__cachePath = os.sep.join((constants._data_path_, "cache", self.username))
110 os.makedirs(self.__cachePath)
115 self.set_self_handle(handle.create_handle(self, 'connection'))
117 self.__callback = None
118 _moduleLogger.info("Connection to the account %s created" % account)
122 return self.__manager
126 return self.__session
130 return self.__credentials[0]
133 def callbackNumberParameter(self):
134 return self.__callbackNumberParameter
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)
146 raise telepathy.errors.NotAvailable('Handle type unsupported %d' % handleType)
150 def _channel_manager(self):
151 return self.__channelManager
153 @gtk_toolbox.log_exception(_moduleLogger)
156 For org.freedesktop.telepathy.Connection
158 _moduleLogger.info("Connecting...")
160 telepathy.CONNECTION_STATUS_CONNECTING,
161 telepathy.CONNECTION_STATUS_REASON_REQUESTED
164 self.__session.load(self.__cachePath)
166 self.__callback = coroutines.func_sink(
167 coroutines.expand_positional(
168 self._on_conversations_updated
171 self.session.voicemails.updateSignalHandler.register_sink(
174 self.session.texts.updateSignalHandler.register_sink(
177 self.session.login(*self.__credentials)
178 if not self.__callbackNumberParameter:
179 callback = gvoice.backend.get_sane_callback(
182 self.__callbackNumberParameter = util_misc.normalize_number(callback)
183 self.session.backend.set_callback_number(self.__callbackNumberParameter)
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")
194 telepathy.CONNECTION_STATUS_DISCONNECTED,
195 telepathy.CONNECTION_STATUS_REASON_NETWORK_ERROR
199 _moduleLogger.exception("Connection Failed")
201 telepathy.CONNECTION_STATUS_DISCONNECTED,
202 telepathy.CONNECTION_STATUS_REASON_AUTHENTICATION_FAILED
206 _moduleLogger.info("Connected")
208 telepathy.CONNECTION_STATUS_CONNECTED,
209 telepathy.CONNECTION_STATUS_REASON_REQUESTED
211 if self.__connection is not None:
212 self.__connectionEventId = self.__connection.connect("connection-event", self._on_connection_change)
214 @gtk_toolbox.log_exception(_moduleLogger)
215 def Disconnect(self):
217 For org.freedesktop.telepathy.Connection
220 telepathy.CONNECTION_STATUS_DISCONNECTED,
221 telepathy.CONNECTION_STATUS_REASON_REQUESTED
226 _moduleLogger.exception("Error durring disconnect")
228 @gtk_toolbox.log_exception(_moduleLogger)
229 def RequestChannel(self, type, handleType, handleId, suppressHandler):
231 For org.freedesktop.telepathy.Connection
233 @param type DBus interface name for base channel type
234 @param handleId represents a contact, list, etc according to handleType
236 @returns DBus object path for the channel created or retrieved
238 self.check_connected()
239 self.check_handle(handleType, handleId)
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)
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))
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()
254 telepathy.CHANNEL_INTERFACE + '.ChannelType': channelType,
255 telepathy.CHANNEL_INTERFACE + '.TargetHandle': targetHandle,
256 telepathy.CHANNEL_INTERFACE + '.TargetHandleType': targetHandleType,
257 telepathy.CHANNEL_INTERFACE + '.Requested': suppressHandler
260 if initiatorHandle is not None:
261 props[telepathy.CHANNEL_INTERFACE + '.InitiatorHandle'] = initiatorHandle.id
265 def _disconnect(self):
266 _moduleLogger.info("Disconnecting")
267 self.session.voicemails.updateSignalHandler.unregister_sink(
270 self.session.texts.updateSignalHandler.unregister_sink(
273 self.__callback = None
275 self.__channelManager.close()
276 self.session.save(self.__cachePath)
277 self.session.logout()
279 self.__session = None
280 if self.__connection is not None:
281 self.__connection.disconnect(self.__connectionEventId)
282 self.__connectionEventId = None
284 self.manager.disconnected(self)
285 _moduleLogger.info("Disconnected")
287 @gtk_toolbox.log_exception(_moduleLogger)
288 def _on_conversations_updated(self, conv, conversationIds):
289 _moduleLogger.debug("Incoming messages from: %r" % (conversationIds, ))
290 for phoneNumber in conversationIds:
291 h = self.get_handle_by_name(telepathy.HANDLE_TYPE_CONTACT, phoneNumber)
292 # Just let the TextChannel decide whether it should be reported to the user or not
293 props = self._generate_props(telepathy.CHANNEL_TYPE_TEXT, h, False)
294 chan = self.__channelManager.channel_for_props(props, signal=True)
296 @gtk_toolbox.log_exception(_moduleLogger)
297 def _on_connection_change(self, connection, event):
301 @todo Make this delayed to handle background switching of networks. First I need to verify I receive connected
303 status = event.get_status()
304 error = event.get_error()
305 iap_id = event.get_iap_id()
306 bearer = event.get_bearer_type()
308 if status == conic.STATUS_DISCONNECTED:
309 _moduleLogger.info("Disconnecting due to loss of network connection")
311 telepathy.CONNECTION_STATUS_DISCONNECTED,
312 telepathy.CONNECTION_STATUS_REASON_NETWORK_ERROR
317 _moduleLogger.exception("Error durring disconnect")
319 _moduleLogger.info("Other status: %r" % (status, ))