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
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 = {
61 # Overriding a base class variable
62 _optional_parameters = {
64 _parameter_defaults = {
67 @gtk_toolbox.log_exception(_moduleLogger)
68 def __init__(self, manager, parameters):
69 self.check_parameters(parameters)
70 account = unicode(parameters['account'])
71 encodedAccount = parameters['account'].encode('utf-8')
72 encodedPassword = parameters['password'].encode('utf-8')
73 encodedCallback = parameters['forward'].encode('utf-8')
74 if not encodedCallback:
75 raise telepathy.errors.InvalidArgument("User must specify what number GV forwards calls to")
77 # Connection init must come first
78 tp.Connection.__init__(
80 constants._telepathy_protocol_name_,
82 constants._telepathy_implementation_name_
84 requests.RequestsMixin.__init__(self)
85 contacts.ContactsMixin.__init__(self)
86 aliasing.AliasingMixin.__init__(self)
87 simple_presence.SimplePresenceMixin.__init__(self)
88 presence.PresenceMixin.__init__(self)
89 capabilities.CapabilitiesMixin.__init__(self)
91 self.__manager = weakref.proxy(manager)
92 self.__credentials = (
96 self.__callbackNumber = encodedCallback
97 self.__channelManager = channel_manager.ChannelManager(self)
99 self.__session = gvoice.session.Session(None)
100 if conic is not None:
101 self.__connection = conic.Connection()
102 self.__connectionEventId = None
104 self.__connection = None
105 self.__connectionEventId = 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 userAliasType(self):
132 return self.USER_ALIAS_ACCOUNT
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 requestedContactId, requestedContactNumber = handle.ContactHandle.from_handle_name(
141 if not requestedContactId:
142 # Sometimes GV doesn't give us a contactid for contacts, so
143 # let's slow things down just a tad for better consistency for
145 ids = list(self.session.addressbook.find_contacts_with_number(requestedContactNumber))
147 requestedContactId = ids[0]
148 h = handle.create_handle(self, 'contact', requestedContactId, requestedContactNumber)
149 elif handleType == telepathy.HANDLE_TYPE_LIST:
150 # Support only server side (immutable) lists
151 _moduleLogger.info("get_handle_by_name List: %s" % requestedHandleName)
152 h = handle.create_handle(self, 'list', requestedHandleName)
154 raise telepathy.errors.NotAvailable('Handle type unsupported %d' % handleType)
158 def _channel_manager(self):
159 return self.__channelManager
161 @gtk_toolbox.log_exception(_moduleLogger)
164 For org.freedesktop.telepathy.Connection
166 _moduleLogger.info("Connecting...")
168 telepathy.CONNECTION_STATUS_CONNECTING,
169 telepathy.CONNECTION_STATUS_REASON_REQUESTED
172 cookieFilePath = None
173 self.__session = gvoice.session.Session(cookieFilePath)
174 self.__session.load(self.__cachePath)
176 self.__callback = coroutines.func_sink(
177 coroutines.expand_positional(
178 self._on_conversations_updated
181 self.session.voicemails.updateSignalHandler.register_sink(
184 self.session.texts.updateSignalHandler.register_sink(
187 self.session.login(*self.__credentials)
188 self.session.backend.set_callback_number(self.__callbackNumber)
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" % 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()
277 self.__session = None
278 if self.__connection is not None:
279 self.__connection.disconnect(self.__connectionEventId)
280 self.__connectionEventId = None
282 self.manager.disconnected(self)
283 _moduleLogger.info("Disconnected")
285 @gtk_toolbox.log_exception(_moduleLogger)
286 def _on_conversations_updated(self, conv, conversationIds):
287 _moduleLogger.debug("Incoming messages from: %r" % (conversationIds, ))
288 for contactId, phoneNumber in conversationIds:
289 handleName = handle.ContactHandle.to_handle_name(contactId, phoneNumber)
290 h = self.get_handle_by_name(telepathy.HANDLE_TYPE_CONTACT, handleName)
291 # Just let the TextChannel decide whether it should be reported to the user or not
292 props = self._generate_props(telepathy.CHANNEL_TYPE_TEXT, h, False)
293 chan = self.__channelManager.channel_for_props(props, signal=True)
295 @gtk_toolbox.log_exception(_moduleLogger)
296 def _on_connection_change(self, connection, event):
300 status = event.get_status()
301 error = event.get_error()
302 iap_id = event.get_iap_id()
303 bearer = event.get_bearer_type()
305 if status == conic.STATUS_DISCONNECTED:
306 _moduleLogger.info("Disconnecting due to loss of network connection")
308 telepathy.CONNECTION_STATUS_DISCONNECTED,
309 telepathy.CONNECTION_STATUS_REASON_NETWORK_ERROR
314 _moduleLogger.exception("Error durring disconnect")