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 Decide if we should do what the spec suggests and hold onto a singleton contactlist
18 import conic as _conic
20 except (ImportError, OSError):
25 import util.coroutines as coroutines
26 import util.misc as util_misc
35 import simple_presence
39 import channel_manager
42 _moduleLogger = logging.getLogger("connection")
45 class TheOneRingConnection(
47 requests.RequestsMixin,
48 contacts.ContactsMixin,
49 aliasing.AliasingMixin,
50 simple_presence.SimplePresenceMixin,
51 presence.PresenceMixin,
52 capabilities.CapabilitiesMixin,
55 # Overriding a base class variable
56 # Should the forwarding number be handled by the alias or by an option?
57 _mandatory_parameters = {
61 # Overriding a base class variable
62 _optional_parameters = {
65 _parameter_defaults = {
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 tp.Connection.__init__(
82 constants._telepathy_protocol_name_,
84 constants._telepathy_implementation_name_
86 requests.RequestsMixin.__init__(self)
87 contacts.ContactsMixin.__init__(self)
88 aliasing.AliasingMixin.__init__(self)
89 simple_presence.SimplePresenceMixin.__init__(self)
90 presence.PresenceMixin.__init__(self)
91 capabilities.CapabilitiesMixin.__init__(self)
93 self.__manager = weakref.proxy(manager)
94 self.__credentials = (
98 self.__callbackNumberParameter = encodedCallback
99 self.__channelManager = channel_manager.ChannelManager(self)
101 self.__session = gvoice.session.Session(None)
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 cookieFilePath = None
165 self.__session = gvoice.session.Session(cookieFilePath)
166 self.__session.load(self.__cachePath)
168 self.__callback = coroutines.func_sink(
169 coroutines.expand_positional(
170 self._on_conversations_updated
173 self.session.voicemails.updateSignalHandler.register_sink(
176 self.session.texts.updateSignalHandler.register_sink(
179 self.session.login(*self.__credentials)
180 if not self.__callbackNumberParameter:
181 callback = gvoice.backend.get_sane_callback(
184 self.__callbackNumberParameter = util_misc.normalize_number(callback)
185 self.session.backend.set_callback_number(self.__callbackNumberParameter)
186 except gvoice.backend.NetworkError, e:
187 _moduleLogger.exception("Connection Failed")
189 telepathy.CONNECTION_STATUS_DISCONNECTED,
190 telepathy.CONNECTION_STATUS_REASON_NETWORK_ERROR
194 _moduleLogger.exception("Connection Failed")
196 telepathy.CONNECTION_STATUS_DISCONNECTED,
197 telepathy.CONNECTION_STATUS_REASON_AUTHENTICATION_FAILED
201 _moduleLogger.info("Connected")
203 telepathy.CONNECTION_STATUS_CONNECTED,
204 telepathy.CONNECTION_STATUS_REASON_REQUESTED
206 if self.__connection is not None:
207 self.__connectionEventId = self.__connection.connect("connection-event", self._on_connection_change)
209 @gtk_toolbox.log_exception(_moduleLogger)
210 def Disconnect(self):
212 For org.freedesktop.telepathy.Connection
215 telepathy.CONNECTION_STATUS_DISCONNECTED,
216 telepathy.CONNECTION_STATUS_REASON_REQUESTED
221 _moduleLogger.exception("Error durring disconnect")
223 @gtk_toolbox.log_exception(_moduleLogger)
224 def RequestChannel(self, type, handleType, handleId, suppressHandler):
226 For org.freedesktop.telepathy.Connection
228 @param type DBus interface name for base channel type
229 @param handleId represents a contact, list, etc according to handleType
231 @returns DBus object path for the channel created or retrieved
233 self.check_connected()
234 self.check_handle(handleType, handleId)
236 h = self.get_handle_by_id(handleType, handleId) if handleId != 0 else None
237 props = self._generate_props(type, h, suppressHandler)
238 self._validate_handle(props)
240 chan = self.__channelManager.channel_for_props(props, signal=True)
241 path = chan._object_path
242 _moduleLogger.info("RequestChannel Object Path: %s" % path)
245 def _generate_props(self, channelType, handle, suppressHandler, initiatorHandle=None):
246 targetHandle = 0 if handle is None else handle.get_id()
247 targetHandleType = telepathy.HANDLE_TYPE_NONE if handle is None else handle.get_type()
249 telepathy.CHANNEL_INTERFACE + '.ChannelType': channelType,
250 telepathy.CHANNEL_INTERFACE + '.TargetHandle': targetHandle,
251 telepathy.CHANNEL_INTERFACE + '.TargetHandleType': targetHandleType,
252 telepathy.CHANNEL_INTERFACE + '.Requested': suppressHandler
255 if initiatorHandle is not None:
256 props[telepathy.CHANNEL_INTERFACE + '.InitiatorHandle'] = initiatorHandle.id
260 def _disconnect(self):
261 _moduleLogger.info("Disconnecting")
262 self.session.voicemails.updateSignalHandler.unregister_sink(
265 self.session.texts.updateSignalHandler.unregister_sink(
268 self.__callback = None
270 self.__channelManager.close()
271 self.session.save(self.__cachePath)
272 self.session.logout()
274 self.__session = None
275 if self.__connection is not None:
276 self.__connection.disconnect(self.__connectionEventId)
277 self.__connectionEventId = None
279 self.manager.disconnected(self)
280 _moduleLogger.info("Disconnected")
282 @gtk_toolbox.log_exception(_moduleLogger)
283 def _on_conversations_updated(self, conv, conversationIds):
284 _moduleLogger.debug("Incoming messages from: %r" % (conversationIds, ))
285 for phoneNumber in conversationIds:
286 h = self.get_handle_by_name(telepathy.HANDLE_TYPE_CONTACT, phoneNumber)
287 # Just let the TextChannel decide whether it should be reported to the user or not
288 props = self._generate_props(telepathy.CHANNEL_TYPE_TEXT, h, False)
289 chan = self.__channelManager.channel_for_props(props, signal=True)
291 @gtk_toolbox.log_exception(_moduleLogger)
292 def _on_connection_change(self, connection, event):
296 @todo Make this delayed to handle background switching of networks
298 status = event.get_status()
299 error = event.get_error()
300 iap_id = event.get_iap_id()
301 bearer = event.get_bearer_type()
303 if status == conic.STATUS_DISCONNECTED:
304 _moduleLogger.info("Disconnecting due to loss of network connection")
306 telepathy.CONNECTION_STATUS_DISCONNECTED,
307 telepathy.CONNECTION_STATUS_REASON_NETWORK_ERROR
312 _moduleLogger.exception("Error durring disconnect")