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
17 import conic as _conic
19 except (ImportError, OSError):
24 import util.coroutines as coroutines
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 # Overriding a base class variable
54 # Should the forwarding number be handled by the alias or by an option?
55 _mandatory_parameters = {
60 # Overriding a base class variable
61 _optional_parameters = {
63 _parameter_defaults = {
66 @gtk_toolbox.log_exception(_moduleLogger)
67 def __init__(self, manager, parameters):
68 self.check_parameters(parameters)
69 account = unicode(parameters['account'])
70 encodedAccount = parameters['account'].encode('utf-8')
71 encodedPassword = parameters['password'].encode('utf-8')
72 encodedCallback = parameters['forward'].encode('utf-8')
73 if not encodedCallback:
74 raise telepathy.errors.InvalidArgument("User must specify what number GV forwards calls to")
76 # Connection init must come first
77 tp.Connection.__init__(
79 constants._telepathy_protocol_name_,
81 constants._telepathy_implementation_name_
83 requests.RequestsMixin.__init__(self)
84 contacts.ContactsMixin.__init__(self)
85 aliasing.AliasingMixin.__init__(self)
86 simple_presence.SimplePresenceMixin.__init__(self)
87 presence.PresenceMixin.__init__(self)
88 capabilities.CapabilitiesMixin.__init__(self)
90 self.__manager = weakref.proxy(manager)
91 self.__credentials = (
95 self.__callbackNumber = encodedCallback
96 self.__channelManager = channel_manager.ChannelManager(self)
98 self.__session = gvoice.session.Session(None)
100 self.__connection = conic.Connection()
101 self.__connectionEventId = None
103 self.__connection = None
104 self.__connectionEventId = None
105 self.__cachePath = os.sep.join((constants._data_path_, "cache", self.username))
107 os.makedirs(self.__cachePath)
112 self.set_self_handle(handle.create_handle(self, 'connection'))
114 self.__callback = None
115 _moduleLogger.info("Connection to the account %s created" % account)
119 return self.__manager
123 return self.__session
127 return self.__credentials[0]
130 def userAliasType(self):
131 return self.USER_ALIAS_ACCOUNT
133 def get_handle_by_name(self, handleType, handleName):
134 requestedHandleName = handleName.encode('utf-8')
135 if handleType == telepathy.HANDLE_TYPE_CONTACT:
136 _moduleLogger.info("get_handle_by_name Contact: %s" % requestedHandleName)
137 requestedContactId, requestedContactNumber = handle.ContactHandle.from_handle_name(
140 if not requestedContactId:
141 # Sometimes GV doesn't give us a contactid for contacts, so
142 # let's slow things down just a tad for better consistency for
144 ids = list(self.session.addressbook.find_contacts_with_number(requestedContactNumber))
146 requestedContactId = ids[0]
147 h = handle.create_handle(self, 'contact', requestedContactId, requestedContactNumber)
148 elif handleType == telepathy.HANDLE_TYPE_LIST:
149 # Support only server side (immutable) lists
150 _moduleLogger.info("get_handle_by_name List: %s" % requestedHandleName)
151 h = handle.create_handle(self, 'list', requestedHandleName)
153 raise telepathy.errors.NotAvailable('Handle type unsupported %d' % handleType)
157 def _channel_manager(self):
158 return self.__channelManager
160 @gtk_toolbox.log_exception(_moduleLogger)
163 For org.freedesktop.telepathy.Connection
165 _moduleLogger.info("Connecting...")
167 telepathy.CONNECTION_STATUS_CONNECTING,
168 telepathy.CONNECTION_STATUS_REASON_REQUESTED
171 cookieFilePath = None
172 self.__session = gvoice.session.Session(cookieFilePath)
173 self.__session.load(self.__cachePath)
175 self.__callback = coroutines.func_sink(
176 coroutines.expand_positional(
177 self._on_conversations_updated
180 self.session.voicemails.updateSignalHandler.register_sink(
183 self.session.texts.updateSignalHandler.register_sink(
186 self.session.login(*self.__credentials)
187 self.session.backend.set_callback_number(self.__callbackNumber)
188 except gvoice.backend.NetworkError, e:
189 _moduleLogger.exception("Connection Failed")
191 telepathy.CONNECTION_STATUS_DISCONNECTED,
192 telepathy.CONNECTION_STATUS_REASON_NETWORK_ERROR
196 _moduleLogger.exception("Connection Failed")
198 telepathy.CONNECTION_STATUS_DISCONNECTED,
199 telepathy.CONNECTION_STATUS_REASON_AUTHENTICATION_FAILED
203 _moduleLogger.info("Connected")
205 telepathy.CONNECTION_STATUS_CONNECTED,
206 telepathy.CONNECTION_STATUS_REASON_REQUESTED
208 if self.__connection is not None:
209 self.__connectionEventId = self.__connection.connect("connection-event", self._on_connection_change)
211 @gtk_toolbox.log_exception(_moduleLogger)
212 def Disconnect(self):
214 For org.freedesktop.telepathy.Connection
217 telepathy.CONNECTION_STATUS_DISCONNECTED,
218 telepathy.CONNECTION_STATUS_REASON_REQUESTED
223 _moduleLogger.exception("Error durring disconnect")
225 @gtk_toolbox.log_exception(_moduleLogger)
226 def RequestChannel(self, type, handleType, handleId, suppressHandler):
228 For org.freedesktop.telepathy.Connection
230 @param type DBus interface name for base channel type
231 @param handleId represents a contact, list, etc according to handleType
233 @returns DBus object path for the channel created or retrieved
235 self.check_connected()
236 self.check_handle(handleType, handleId)
238 h = self.get_handle_by_id(handleType, handleId) if handleId != 0 else None
239 props = self._generate_props(type, h, suppressHandler)
240 self._validate_handle(props)
242 chan = self.__channelManager.channel_for_props(props, signal=True)
243 path = chan._object_path
244 _moduleLogger.info("RequestChannel Object Path: %s" % path)
247 def _generate_props(self, channelType, handle, suppressHandler, initiatorHandle=None):
248 targetHandle = 0 if handle is None else handle.get_id()
249 targetHandleType = telepathy.HANDLE_TYPE_NONE if handle is None else handle.get_type()
251 telepathy.CHANNEL_INTERFACE + '.ChannelType': channelType,
252 telepathy.CHANNEL_INTERFACE + '.TargetHandle': targetHandle,
253 telepathy.CHANNEL_INTERFACE + '.TargetHandleType': targetHandleType,
254 telepathy.CHANNEL_INTERFACE + '.Requested': suppressHandler
257 if initiatorHandle is not None:
258 props[telepathy.CHANNEL_INTERFACE + '.InitiatorHandle'] = initiatorHandle.id
262 def _disconnect(self):
263 _moduleLogger.info("Disconnecting")
264 self.session.voicemails.updateSignalHandler.unregister_sink(
267 self.session.texts.updateSignalHandler.unregister_sink(
270 self.__callback = None
272 self.__channelManager.close()
273 self.session.save(self.__cachePath)
274 self.session.logout()
276 self.__session = None
277 if self.__connection is not None:
278 self.__connection.disconnect(self.__connectionEventId)
279 self.__connectionEventId = None
281 self.manager.disconnected(self)
282 _moduleLogger.info("Disconnected")
284 @gtk_toolbox.log_exception(_moduleLogger)
285 def _on_conversations_updated(self, conv, conversationIds):
286 _moduleLogger.debug("Incoming messages from: %r" % (conversationIds, ))
287 for contactId, phoneNumber in conversationIds:
288 handleName = handle.ContactHandle.to_handle_name(contactId, phoneNumber)
289 h = self.get_handle_by_name(telepathy.HANDLE_TYPE_CONTACT, handleName)
290 # Just let the TextChannel decide whether it should be reported to the user or not
291 props = self._generate_props(telepathy.CHANNEL_TYPE_TEXT, h, False)
292 channel = self.__channelManager.channel_for_props(props, signal=True)
294 @gtk_toolbox.log_exception(_moduleLogger)
295 def _on_connection_change(self, connection, event):
299 status = event.get_status()
300 error = event.get_error()
301 iap_id = event.get_iap_id()
302 bearer = event.get_bearer_type()
304 if status == conic.STATUS_DISCONNECTED:
305 _moduleLogger.info("Disconnecting due to loss of network connection")
307 telepathy.CONNECTION_STATUS_DISCONNECTED,
308 telepathy.CONNECTION_STATUS_REASON_NETWORK_ERROR
313 _moduleLogger.exception("Error durring disconnect")