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
16 import conic as _conic
18 except (ImportError, OSError):
23 import util.coroutines as coroutines
32 import simple_presence
36 import channel_manager
39 _moduleLogger = logging.getLogger("connection")
42 class TheOneRingConnection(
44 requests.RequestsMixin,
45 contacts.ContactsMixin,
46 aliasing.AliasingMixin,
47 simple_presence.SimplePresenceMixin,
48 presence.PresenceMixin,
49 capabilities.CapabilitiesMixin,
52 # Overriding a base class variable
53 # Should the forwarding number be handled by the alias or by an option?
54 _mandatory_parameters = {
59 # Overriding a base class variable
60 _optional_parameters = {
62 _parameter_defaults = {
65 @gtk_toolbox.log_exception(_moduleLogger)
66 def __init__(self, manager, parameters):
67 self.check_parameters(parameters)
68 account = unicode(parameters['account'])
69 encodedAccount = parameters['account'].encode('utf-8')
70 encodedPassword = parameters['password'].encode('utf-8')
71 encodedCallback = parameters['forward'].encode('utf-8')
72 if not encodedCallback:
73 raise telepathy.errors.InvalidArgument("User must specify what number GV forwards calls to")
75 # Connection init must come first
76 tp.Connection.__init__(
78 constants._telepathy_protocol_name_,
80 constants._telepathy_implementation_name_
82 requests.RequestsMixin.__init__(self)
83 contacts.ContactsMixin.__init__(self)
84 aliasing.AliasingMixin.__init__(self)
85 simple_presence.SimplePresenceMixin.__init__(self)
86 presence.PresenceMixin.__init__(self)
87 capabilities.CapabilitiesMixin.__init__(self)
89 self.__manager = weakref.proxy(manager)
90 self.__credentials = (
94 self.__callbackNumber = encodedCallback
95 self.__channelManager = channel_manager.ChannelManager(self)
97 self.__session = gvoice.session.Session(None)
99 self.__connection = conic.Connection()
100 self.__connectionEventId = None
102 self.__connection = None
103 self.__connectionEventId = None
105 self.set_self_handle(handle.create_handle(self, 'connection'))
107 self.__callback = None
108 _moduleLogger.info("Connection to the account %s created" % account)
112 return self.__manager
116 return self.__session
120 return self.__credentials[0]
123 def userAliasType(self):
124 return self.USER_ALIAS_ACCOUNT
126 def handle_by_name(self, handleType, handleName):
127 requestedHandleName = handleName.encode('utf-8')
128 if handleType == telepathy.HANDLE_TYPE_CONTACT:
129 _moduleLogger.info("RequestHandles Contact: %s" % requestedHandleName)
130 requestedContactId, requestedContactNumber = handle.ContactHandle.from_handle_name(
133 h = handle.create_handle(self, 'contact', requestedContactId, requestedContactNumber)
134 elif handleType == telepathy.HANDLE_TYPE_LIST:
135 # Support only server side (immutable) lists
136 _moduleLogger.info("RequestHandles List: %s" % requestedHandleName)
137 h = handle.create_handle(self, 'list', requestedHandleName)
139 raise telepathy.errors.NotAvailable('Handle type unsupported %d' % handleType)
143 def _channel_manager(self):
144 return self.__channelManager
146 @gtk_toolbox.log_exception(_moduleLogger)
149 For org.freedesktop.telepathy.Connection
151 _moduleLogger.info("Connecting...")
153 telepathy.CONNECTION_STATUS_CONNECTING,
154 telepathy.CONNECTION_STATUS_REASON_REQUESTED
157 cookieFilePath = None
158 self.__session = gvoice.session.Session(cookieFilePath)
160 self.__callback = coroutines.func_sink(
161 coroutines.expand_positional(
162 self._on_conversations_updated
165 self.session.voicemails.updateSignalHandler.register_sink(
168 self.session.texts.updateSignalHandler.register_sink(
171 self.session.login(*self.__credentials)
172 self.session.backend.set_callback_number(self.__callbackNumber)
173 except gvoice.backend.NetworkError, e:
174 _moduleLogger.exception("Connection Failed")
176 telepathy.CONNECTION_STATUS_DISCONNECTED,
177 telepathy.CONNECTION_STATUS_REASON_NETWORK_ERROR
181 _moduleLogger.exception("Connection Failed")
183 telepathy.CONNECTION_STATUS_DISCONNECTED,
184 telepathy.CONNECTION_STATUS_REASON_AUTHENTICATION_FAILED
188 _moduleLogger.info("Connected")
190 telepathy.CONNECTION_STATUS_CONNECTED,
191 telepathy.CONNECTION_STATUS_REASON_REQUESTED
193 if self.__connection is not None:
194 self.__connectionEventId = self.__connection.connect("connection-event", self._on_connection_change)
196 @gtk_toolbox.log_exception(_moduleLogger)
197 def Disconnect(self):
199 For org.freedesktop.telepathy.Connection
202 telepathy.CONNECTION_STATUS_DISCONNECTED,
203 telepathy.CONNECTION_STATUS_REASON_REQUESTED
208 _moduleLogger.exception("Error durring disconnect")
210 @gtk_toolbox.log_exception(_moduleLogger)
211 def RequestChannel(self, type, handleType, handleId, suppressHandler):
213 For org.freedesktop.telepathy.Connection
215 @param type DBus interface name for base channel type
216 @param handleId represents a contact, list, etc according to handleType
218 @returns DBus object path for the channel created or retrieved
220 self.check_connected()
221 self.check_handle(handleType, handleId)
223 h = self.get_handle_by_id(handleType, handleId) if handleId != 0 else None
224 props = self._generate_props(type, h, suppressHandler)
225 self._validate_handle(props)
227 chan = self.__channelManager.channel_for_props(props, signal=True)
228 path = chan._object_path
229 _moduleLogger.info("RequestChannel Object Path: %s" % path)
232 def _generate_props(self, channelType, handle, suppressHandler, initiatorHandle=None):
233 targetHandle = 0 if handle is None else handle.get_id()
234 targetHandleType = telepathy.HANDLE_TYPE_NONE if handle is None else handle.get_type()
236 telepathy.CHANNEL_INTERFACE + '.ChannelType': channelType,
237 telepathy.CHANNEL_INTERFACE + '.TargetHandle': targetHandle,
238 telepathy.CHANNEL_INTERFACE + '.TargetHandleType': targetHandleType,
239 telepathy.CHANNEL_INTERFACE + '.Requested': suppressHandler
242 if initiatorHandle is not None:
243 props[telepathy.CHANNEL_INTERFACE + '.InitiatorHandle'] = initiatorHandle.id
247 def _disconnect(self):
248 _moduleLogger.info("Disconnecting")
249 self.session.voicemails.updateSignalHandler.unregister_sink(
252 self.session.texts.updateSignalHandler.unregister_sink(
255 self.__callback = None
257 self.__channelManager.close()
258 self.session.logout()
260 self.__session = None
261 if self.__connection is not None:
262 self.__connection.disconnect(self.__connectionEventId)
263 self.__connectionEventId = None
265 self.manager.disconnected(self)
266 _moduleLogger.info("Disconnected")
268 @gtk_toolbox.log_exception(_moduleLogger)
269 def _on_conversations_updated(self, conv, conversationIds):
270 _moduleLogger.debug("Incoming messages from: %r" % (conversationIds, ))
271 for contactId, phoneNumber in conversationIds:
272 h = handle.create_handle(self, 'contact', contactId, phoneNumber)
273 # Just let the TextChannel decide whether it should be reported to the user or not
274 props = self._generate_props(telepathy.CHANNEL_TYPE_TEXT, h, False)
275 channel = self.__channelManager.channel_for_props(props, signal=True)
277 @gtk_toolbox.log_exception(_moduleLogger)
278 def _on_connection_change(self, connection, event):
282 status = event.get_status()
283 error = event.get_error()
284 iap_id = event.get_iap_id()
285 bearer = event.get_bearer_type()
287 if status == conic.STATUS_DISCONNECTED:
288 _moduleLogger.info("Disconnecting due to loss of network connection")
290 telepathy.CONNECTION_STATUS_DISCONNECTED,
291 telepathy.CONNECTION_STATUS_REASON_NETWORK_ERROR
296 _moduleLogger.exception("Error durring disconnect")