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 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(self, handleType, handleId):
127 self.check_handle(handleType, handleId)
128 return self._handles[handleType, handleId]
131 def _channel_manager(self):
132 return self.__channelManager
134 @gtk_toolbox.log_exception(_moduleLogger)
137 For org.freedesktop.telepathy.Connection
139 _moduleLogger.info("Connecting...")
141 telepathy.CONNECTION_STATUS_CONNECTING,
142 telepathy.CONNECTION_STATUS_REASON_REQUESTED
145 cookieFilePath = None
146 self.__session = gvoice.session.Session(cookieFilePath)
148 self.__callback = coroutines.func_sink(
149 coroutines.expand_positional(
150 self._on_conversations_updated
153 self.session.voicemails.updateSignalHandler.register_sink(
156 self.session.texts.updateSignalHandler.register_sink(
159 self.session.login(*self.__credentials)
160 self.session.backend.set_callback_number(self.__callbackNumber)
161 except gvoice.backend.NetworkError, e:
162 _moduleLogger.exception("Connection Failed")
164 telepathy.CONNECTION_STATUS_DISCONNECTED,
165 telepathy.CONNECTION_STATUS_REASON_NETWORK_ERROR
169 _moduleLogger.exception("Connection Failed")
171 telepathy.CONNECTION_STATUS_DISCONNECTED,
172 telepathy.CONNECTION_STATUS_REASON_AUTHENTICATION_FAILED
176 _moduleLogger.info("Connected")
178 telepathy.CONNECTION_STATUS_CONNECTED,
179 telepathy.CONNECTION_STATUS_REASON_REQUESTED
181 if self.__connection is not None:
182 self.__connectionEventId = self.__connection.connect("connection-event", self._on_connection_change)
184 @gtk_toolbox.log_exception(_moduleLogger)
185 def Disconnect(self):
187 For org.freedesktop.telepathy.Connection
188 @bug Not properly logging out. Cookie files need to be per connection and removed
191 telepathy.CONNECTION_STATUS_DISCONNECTED,
192 telepathy.CONNECTION_STATUS_REASON_REQUESTED
197 _moduleLogger.exception("Error durring disconnect")
199 @gtk_toolbox.log_exception(_moduleLogger)
200 def RequestChannel(self, type, handleType, handleId, suppressHandler):
202 For org.freedesktop.telepathy.Connection
204 @param type DBus interface name for base channel type
205 @param handleId represents a contact, list, etc according to handleType
207 @returns DBus object path for the channel created or retrieved
209 self.check_connected()
210 self.check_handle(handleType, handleId)
212 h = self.handle(handleType, handleId) if handleId != 0 else None
213 props = self._generate_props(type, h, suppressHandler)
214 if hasattr(self, "_validate_handle"):
215 # HACK Newer python-telepathy
216 self._validate_handle(props)
218 chan = self.__channelManager.channel_for_props(props, signal=True)
219 path = chan._object_path
220 _moduleLogger.info("RequestChannel Object Path: %s" % path)
223 @gtk_toolbox.log_exception(_moduleLogger)
224 def RequestHandles(self, handleType, names, sender):
226 For org.freedesktop.telepathy.Connection
227 Overiding telepathy.server.Connecton to allow custom handles
229 self.check_connected()
230 self.check_handle_type(handleType)
234 requestedHandleName = name.encode('utf-8')
235 if handleType == telepathy.HANDLE_TYPE_CONTACT:
236 _moduleLogger.info("RequestHandles Contact: %s" % requestedHandleName)
237 requestedContactId, requestedContactNumber = handle.ContactHandle.from_handle_name(
240 h = handle.create_handle(self, 'contact', requestedContactId, requestedContactNumber)
241 elif handleType == telepathy.HANDLE_TYPE_LIST:
242 # Support only server side (immutable) lists
243 _moduleLogger.info("RequestHandles List: %s" % requestedHandleName)
244 h = handle.create_handle(self, 'list', requestedHandleName)
246 raise telepathy.errors.NotAvailable('Handle type unsupported %d' % handleType)
248 self.add_client_handle(h, sender)
251 def _generate_props(self, channelType, handle, suppressHandler, initiatorHandle=None):
252 targetHandle = 0 if handle is None else handle.get_id()
253 targetHandleType = telepathy.HANDLE_TYPE_NONE if handle is None else handle.get_type()
255 telepathy.CHANNEL_INTERFACE + '.ChannelType': channelType,
256 telepathy.CHANNEL_INTERFACE + '.TargetHandle': targetHandle,
257 telepathy.CHANNEL_INTERFACE + '.TargetHandleType': targetHandleType,
258 telepathy.CHANNEL_INTERFACE + '.Requested': suppressHandler
261 if initiatorHandle is not None:
262 props[telepathy.CHANNEL_INTERFACE + '.InitiatorHandle'] = initiatorHandle.id
266 def _disconnect(self):
267 _moduleLogger.info("Disconnecting")
268 self.session.voicemails.updateSignalHandler.unregister_sink(
271 self.session.texts.updateSignalHandler.unregister_sink(
274 self.__callback = None
276 self.__channelManager.close()
277 self.session.logout()
279 self.__session = None
280 if self.__connection is not None:
281 self.__connection.disconnect(self.__connectionEventId)
282 self.__connectionEventId = None
284 self.manager.disconnected(self)
285 _moduleLogger.info("Disconnected")
287 @gtk_toolbox.log_exception(_moduleLogger)
288 def _on_conversations_updated(self, conv, conversationIds):
289 _moduleLogger.debug("Incoming messages from: %r" % (conversationIds, ))
290 for contactId, phoneNumber in conversationIds:
291 h = handle.create_handle(self, 'contact', contactId, phoneNumber)
292 # Just let the TextChannel decide whether it should be reported to the user or not
293 props = self._generate_props(telepathy.CHANNEL_TYPE_TEXT, h, False)
294 channel = self.__channelManager.channel_for_props(props, signal=True)
296 @gtk_toolbox.log_exception(_moduleLogger)
297 def _on_connection_change(self, connection, event):
301 status = event.get_status()
302 error = event.get_error()
303 iap_id = event.get_iap_id()
304 bearer = event.get_bearer_type()
306 if status == conic.STATUS_DISCONNECTED:
307 _moduleLogger.info("Disconnecting due to loss of network connection")
309 telepathy.CONNECTION_STATUS_DISCONNECTED,
310 telepathy.CONNECTION_STATUS_REASON_NETWORK_ERROR
315 _moduleLogger.exception("Error durring disconnect")