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 Observe when connected/disconnected to disconnect CM
17 import conic as _conic
19 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(
43 telepathy.server.Connection,
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 telepathy.server.Connection.__init__(
78 constants._telepathy_protocol_name_,
80 constants._telepathy_implementation_name_
82 #telepathy.server.ConnectionInterfaceRequests.__init__(self)
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
106 self.set_self_handle(handle.create_handle(self, 'connection'))
108 self.__callback = None
109 _moduleLogger.info("Connection to the account %s created" % account)
113 return self.__manager
117 return self.__session
121 return self.__credentials[0]
124 def userAliasType(self):
125 return self.USER_ALIAS_ACCOUNT
127 def handle(self, handleType, handleId):
128 self.check_handle(handleType, handleId)
129 return self._handles[handleType, handleId]
132 def _channel_manager(self):
133 return self.__channelManager
135 @gtk_toolbox.log_exception(_moduleLogger)
138 For org.freedesktop.telepathy.Connection
140 _moduleLogger.info("Connecting...")
142 telepathy.CONNECTION_STATUS_CONNECTING,
143 telepathy.CONNECTION_STATUS_REASON_REQUESTED
146 cookieFilePath = None
147 self.__session = gvoice.session.Session(cookieFilePath)
149 self.__callback = coroutines.func_sink(
150 coroutines.expand_positional(
151 self._on_conversations_updated
154 self.session.voicemails.updateSignalHandler.register_sink(
157 self.session.texts.updateSignalHandler.register_sink(
160 self.session.login(*self.__credentials)
161 self.session.backend.set_callback_number(self.__callbackNumber)
162 except gvoice.backend.NetworkError, e:
163 _moduleLogger.exception("Connection Failed")
165 telepathy.CONNECTION_STATUS_DISCONNECTED,
166 telepathy.CONNECTION_STATUS_REASON_NETWORK_ERROR
170 _moduleLogger.exception("Connection Failed")
172 telepathy.CONNECTION_STATUS_DISCONNECTED,
173 telepathy.CONNECTION_STATUS_REASON_AUTHENTICATION_FAILED
177 _moduleLogger.info("Connected")
179 telepathy.CONNECTION_STATUS_CONNECTED,
180 telepathy.CONNECTION_STATUS_REASON_REQUESTED
182 if self.__connection is not None:
183 self.__connectionEventId = self.__connection.connect("connection-event", self._on_connection_change)
185 @gtk_toolbox.log_exception(_moduleLogger)
186 def Disconnect(self):
188 For org.freedesktop.telepathy.Connection
189 @bug Not properly logging out. Cookie files need to be per connection and removed
192 telepathy.CONNECTION_STATUS_DISCONNECTED,
193 telepathy.CONNECTION_STATUS_REASON_REQUESTED
198 _moduleLogger.exception("Error durring disconnect")
200 @gtk_toolbox.log_exception(_moduleLogger)
201 def RequestChannel(self, type, handleType, handleId, suppressHandler):
203 For org.freedesktop.telepathy.Connection
205 @param type DBus interface name for base channel type
206 @param handleId represents a contact, list, etc according to handleType
208 @returns DBus object path for the channel created or retrieved
210 self.check_connected()
211 self.check_handle(handleType, handleId)
213 h = self.handle(handleType, handleId) if handleId != 0 else None
214 props = self._generate_props(type, h, suppressHandler)
215 if hasattr(self, "_validate_handle"):
216 # HACK Newer python-telepathy
217 self._validate_handle(props)
219 chan = self.__channelManager.channel_for_props(props, signal=True)
220 path = chan._object_path
221 _moduleLogger.info("RequestChannel Object Path: %s" % path)
224 @gtk_toolbox.log_exception(_moduleLogger)
225 def RequestHandles(self, handleType, names, sender):
227 For org.freedesktop.telepathy.Connection
228 Overiding telepathy.server.Connecton to allow custom handles
230 self.check_connected()
231 self.check_handle_type(handleType)
235 requestedHandleName = name.encode('utf-8')
236 if handleType == telepathy.HANDLE_TYPE_CONTACT:
237 _moduleLogger.info("RequestHandles Contact: %s" % requestedHandleName)
238 requestedContactId, requestedContactNumber = handle.ContactHandle.from_handle_name(
241 h = handle.create_handle(self, 'contact', requestedContactId, requestedContactNumber)
242 elif handleType == telepathy.HANDLE_TYPE_LIST:
243 # Support only server side (immutable) lists
244 _moduleLogger.info("RequestHandles List: %s" % requestedHandleName)
245 h = handle.create_handle(self, 'list', requestedHandleName)
247 raise telepathy.errors.NotAvailable('Handle type unsupported %d' % handleType)
249 self.add_client_handle(h, sender)
252 def _generate_props(self, channelType, handle, suppressHandler, initiatorHandle=None):
253 targetHandle = 0 if handle is None else handle.get_id()
254 targetHandleType = telepathy.HANDLE_TYPE_NONE if handle is None else handle.get_type()
256 telepathy.CHANNEL_INTERFACE + '.ChannelType': channelType,
257 telepathy.CHANNEL_INTERFACE + '.TargetHandle': targetHandle,
258 telepathy.CHANNEL_INTERFACE + '.TargetHandleType': targetHandleType,
259 telepathy.CHANNEL_INTERFACE + '.Requested': suppressHandler
262 if initiatorHandle is not None:
263 props[telepathy.CHANNEL_INTERFACE + '.InitiatorHandle'] = initiatorHandle.id
267 def _disconnect(self):
268 _moduleLogger.info("Disconnecting")
269 self.session.voicemails.updateSignalHandler.unregister_sink(
272 self.session.texts.updateSignalHandler.unregister_sink(
275 self.__callback = None
277 self.__channelManager.close()
278 self.session.logout()
280 self.__session = None
281 if self.__connection is not None:
282 self.__connection.disconnect(self.__connectionEventId)
283 self.__connectionEventId = None
285 self.manager.disconnected(self)
286 _moduleLogger.info("Disconnected")
288 @gtk_toolbox.log_exception(_moduleLogger)
289 def _on_conversations_updated(self, conv, conversationIds):
290 _moduleLogger.debug("Incoming messages from: %r" % (conversationIds, ))
291 for contactId, phoneNumber in conversationIds:
292 h = handle.create_handle(self, 'contact', contactId, phoneNumber)
293 # Just let the TextChannel decide whether it should be reported to the user or not
294 props = self._generate_props(telepathy.CHANNEL_TYPE_TEXT, h, False)
295 channel = self.__channelManager.channel_for_props(props, signal=True)
297 @gtk_toolbox.log_exception(_moduleLogger)
298 def _on_connection_change(self, connection, event):
302 status = event.get_status()
303 error = event.get_error()
304 iap_id = event.get_iap_id()
305 bearer = event.get_bearer_type()
307 if status == conic.STATUS_DISCONNECTED:
308 _moduleLogger.info("Disconnecting due to loss of network connection")
310 telepathy.CONNECTION_STATUS_DISCONNECTED,
311 telepathy.CONNECTION_STATUS_REASON_NETWORK_ERROR
316 _moduleLogger.exception("Error durring disconnect")