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 @todo Decide if we should do what the spec suggests and hold onto a singleton contactlist
17 import conic as _conic
19 except (ImportError, OSError):
24 import util.coroutines as coroutines
25 import util.misc as util_misc
34 import simple_presence
38 import channel_manager
41 _moduleLogger = logging.getLogger("connection")
44 class TheOneRingConnection(
46 requests.RequestsMixin,
47 contacts.ContactsMixin,
48 aliasing.AliasingMixin,
49 simple_presence.SimplePresenceMixin,
50 presence.PresenceMixin,
51 capabilities.CapabilitiesMixin,
54 # Overriding a base class variable
55 # Should the forwarding number be handled by the alias or by an option?
56 _mandatory_parameters = {
60 # Overriding a base class variable
61 _optional_parameters = {
64 _parameter_defaults = {
68 @gtk_toolbox.log_exception(_moduleLogger)
69 def __init__(self, manager, parameters):
70 self.check_parameters(parameters)
71 account = unicode(parameters['account'])
72 encodedAccount = parameters['account'].encode('utf-8')
73 encodedPassword = parameters['password'].encode('utf-8')
74 encodedCallback = util_misc.normalize_number(parameters['forward'].encode('utf-8'))
75 if encodedCallback and not util_misc.is_valid_number(encodedCallback):
76 raise telepathy.errors.InvalidArgument("Invalid forwarding number")
78 # Connection init must come first
79 self.__session = gvoice.session.Session(None)
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 if conic is not None:
102 self.__connection = conic.Connection()
103 self.__connectionEventId = None
105 self.__connection = None
106 self.__connectionEventId = None
107 self.__cachePath = os.sep.join((constants._data_path_, "cache", self.username))
109 os.makedirs(self.__cachePath)
114 self.set_self_handle(handle.create_handle(self, 'connection'))
116 self.__callback = None
117 _moduleLogger.info("Connection to the account %s created" % account)
121 return self.__manager
125 return self.__session
129 return self.__credentials[0]
132 def callbackNumberParameter(self):
133 return self.__callbackNumberParameter
135 def get_handle_by_name(self, handleType, handleName):
136 requestedHandleName = handleName.encode('utf-8')
137 if handleType == telepathy.HANDLE_TYPE_CONTACT:
138 _moduleLogger.info("get_handle_by_name Contact: %s" % requestedHandleName)
139 h = handle.create_handle(self, 'contact', requestedHandleName)
140 elif handleType == telepathy.HANDLE_TYPE_LIST:
141 # Support only server side (immutable) lists
142 _moduleLogger.info("get_handle_by_name List: %s" % requestedHandleName)
143 h = handle.create_handle(self, 'list', requestedHandleName)
145 raise telepathy.errors.NotAvailable('Handle type unsupported %d' % handleType)
149 def _channel_manager(self):
150 return self.__channelManager
152 @gtk_toolbox.log_exception(_moduleLogger)
155 For org.freedesktop.telepathy.Connection
157 _moduleLogger.info("Connecting...")
159 telepathy.CONNECTION_STATUS_CONNECTING,
160 telepathy.CONNECTION_STATUS_REASON_REQUESTED
163 self.__session.load(self.__cachePath)
165 self.__callback = coroutines.func_sink(
166 coroutines.expand_positional(
167 self._on_conversations_updated
170 self.session.voicemails.updateSignalHandler.register_sink(
173 self.session.texts.updateSignalHandler.register_sink(
176 self.session.login(*self.__credentials)
177 if not self.__callbackNumberParameter:
178 callback = gvoice.backend.get_sane_callback(
181 self.__callbackNumberParameter = util_misc.normalize_number(callback)
182 self.session.backend.set_callback_number(self.__callbackNumberParameter)
183 except gvoice.backend.NetworkError, e:
184 _moduleLogger.exception("Connection Failed")
186 telepathy.CONNECTION_STATUS_DISCONNECTED,
187 telepathy.CONNECTION_STATUS_REASON_NETWORK_ERROR
191 _moduleLogger.exception("Connection Failed")
193 telepathy.CONNECTION_STATUS_DISCONNECTED,
194 telepathy.CONNECTION_STATUS_REASON_AUTHENTICATION_FAILED
198 _moduleLogger.info("Connected")
200 telepathy.CONNECTION_STATUS_CONNECTED,
201 telepathy.CONNECTION_STATUS_REASON_REQUESTED
203 if self.__connection is not None:
204 self.__connectionEventId = self.__connection.connect("connection-event", self._on_connection_change)
206 @gtk_toolbox.log_exception(_moduleLogger)
207 def Disconnect(self):
209 For org.freedesktop.telepathy.Connection
212 telepathy.CONNECTION_STATUS_DISCONNECTED,
213 telepathy.CONNECTION_STATUS_REASON_REQUESTED
218 _moduleLogger.exception("Error durring disconnect")
220 @gtk_toolbox.log_exception(_moduleLogger)
221 def RequestChannel(self, type, handleType, handleId, suppressHandler):
223 For org.freedesktop.telepathy.Connection
225 @param type DBus interface name for base channel type
226 @param handleId represents a contact, list, etc according to handleType
228 @returns DBus object path for the channel created or retrieved
230 self.check_connected()
231 self.check_handle(handleType, handleId)
233 h = self.get_handle_by_id(handleType, handleId) if handleId != 0 else None
234 props = self._generate_props(type, h, suppressHandler)
235 self._validate_handle(props)
237 chan = self.__channelManager.channel_for_props(props, signal=True)
238 path = chan._object_path
239 _moduleLogger.info("RequestChannel Object Path: %s" % path)
242 def _generate_props(self, channelType, handle, suppressHandler, initiatorHandle=None):
243 targetHandle = 0 if handle is None else handle.get_id()
244 targetHandleType = telepathy.HANDLE_TYPE_NONE if handle is None else handle.get_type()
246 telepathy.CHANNEL_INTERFACE + '.ChannelType': channelType,
247 telepathy.CHANNEL_INTERFACE + '.TargetHandle': targetHandle,
248 telepathy.CHANNEL_INTERFACE + '.TargetHandleType': targetHandleType,
249 telepathy.CHANNEL_INTERFACE + '.Requested': suppressHandler
252 if initiatorHandle is not None:
253 props[telepathy.CHANNEL_INTERFACE + '.InitiatorHandle'] = initiatorHandle.id
257 def _disconnect(self):
258 _moduleLogger.info("Disconnecting")
259 self.session.voicemails.updateSignalHandler.unregister_sink(
262 self.session.texts.updateSignalHandler.unregister_sink(
265 self.__callback = None
267 self.__channelManager.close()
268 self.session.save(self.__cachePath)
269 self.session.logout()
271 self.__session = None
272 if self.__connection is not None:
273 self.__connection.disconnect(self.__connectionEventId)
274 self.__connectionEventId = None
276 self.manager.disconnected(self)
277 _moduleLogger.info("Disconnected")
279 @gtk_toolbox.log_exception(_moduleLogger)
280 def _on_conversations_updated(self, conv, conversationIds):
281 _moduleLogger.debug("Incoming messages from: %r" % (conversationIds, ))
282 for phoneNumber in conversationIds:
283 h = self.get_handle_by_name(telepathy.HANDLE_TYPE_CONTACT, phoneNumber)
284 # Just let the TextChannel decide whether it should be reported to the user or not
285 props = self._generate_props(telepathy.CHANNEL_TYPE_TEXT, h, False)
286 chan = self.__channelManager.channel_for_props(props, signal=True)
288 @gtk_toolbox.log_exception(_moduleLogger)
289 def _on_connection_change(self, connection, event):
293 @todo Make this delayed to handle background switching of networks
295 status = event.get_status()
296 error = event.get_error()
297 iap_id = event.get_iap_id()
298 bearer = event.get_bearer_type()
300 if status == conic.STATUS_DISCONNECTED:
301 _moduleLogger.info("Disconnecting due to loss of network connection")
303 telepathy.CONNECTION_STATUS_DISCONNECTED,
304 telepathy.CONNECTION_STATUS_REASON_NETWORK_ERROR
309 _moduleLogger.exception("Error durring disconnect")