3 @todo Add params for disable/enable state machines
4 @todo Separate voicemail/sms into separate conversation instances
5 @todo Setup addressbook, voicemail, sms state machines
6 @todo Add option to use screen name as callback
7 @todo Get a callback for missed calls to force an update of the voicemail state machine
8 @todo Get a callback on an incoming call and if its from GV, auto-pickup
9 @todo Use state-strategies to keep mega-state-machine generic
10 @todo Observe when connected/disconnected to disconnect CM
20 import util.go_utils as gobject_utils
21 import util.coroutines as coroutines
29 import simple_presence
33 import channel_manager
36 _moduleLogger = logging.getLogger("connection")
39 class TheOneRingConnection(
40 telepathy.server.Connection,
41 telepathy.server.ConnectionInterfaceRequests, # already a mixin
42 contacts.ContactsMixin,
43 aliasing.AliasingMixin,
44 simple_presence.SimplePresenceMixin,
45 presence.PresenceMixin,
46 capabilities.CapabilitiesMixin,
49 # Overriding a base class variable
50 # Should the forwarding number be handled by the alias or by an option?
51 _mandatory_parameters = {
56 # Overriding a base class variable
57 _optional_parameters = {
59 _parameter_defaults = {
62 @gtk_toolbox.log_exception(_moduleLogger)
63 def __init__(self, manager, parameters):
64 self.check_parameters(parameters)
65 account = unicode(parameters['account'])
66 encodedAccount = parameters['account'].encode('utf-8')
67 encodedPassword = parameters['password'].encode('utf-8')
68 encodedCallback = parameters['forward'].encode('utf-8')
69 if not encodedCallback:
70 raise telepathy.errors.InvalidArgument("User must specify what number GV forwards calls to")
72 # Connection init must come first
73 telepathy.server.Connection.__init__(
75 constants._telepathy_protocol_name_,
77 constants._telepathy_implementation_name_
79 telepathy.server.ConnectionInterfaceRequests.__init__(self)
80 contacts.ContactsMixin.__init__(self)
81 aliasing.AliasingMixin.__init__(self)
82 simple_presence.SimplePresenceMixin.__init__(self)
83 presence.PresenceMixin.__init__(self)
84 capabilities.CapabilitiesMixin.__init__(self)
86 self._manager = weakref.proxy(manager)
91 self._callbackNumber = encodedCallback
92 self._channelManager = channel_manager.ChannelManager(self)
94 self._session = gvoice.session.Session(None)
96 self.set_self_handle(handle.create_handle(self, 'connection'))
99 _moduleLogger.info("Connection to the account %s created" % account)
111 return self._credentials[0]
114 def userAliasType(self):
115 return self.USER_ALIAS_ACCOUNT
117 def handle(self, handleType, handleId):
118 self.check_handle(handleType, handleId)
119 return self._handles[handleType, handleId]
121 @gtk_toolbox.log_exception(_moduleLogger)
124 For org.freedesktop.telepathy.Connection
126 _moduleLogger.info("Connecting...")
128 telepathy.CONNECTION_STATUS_CONNECTING,
129 telepathy.CONNECTION_STATUS_REASON_REQUESTED
132 cookieFilePath = None
133 self._session = gvoice.session.Session(cookieFilePath)
135 self._callback = coroutines.func_sink(
136 coroutines.expand_positional(
137 self._on_conversations_updated
140 self.session.conversations.updateSignalHandler.register_sink(
143 self.session.login(*self._credentials)
144 self.session.backend.set_callback_number(self._callbackNumber)
145 except gvoice.backend.NetworkError, e:
146 _moduleLogger.exception("Connection Failed")
148 telepathy.CONNECTION_STATUS_DISCONNECTED,
149 telepathy.CONNECTION_STATUS_REASON_NETWORK_ERROR
152 _moduleLogger.exception("Connection Failed")
154 telepathy.CONNECTION_STATUS_DISCONNECTED,
155 telepathy.CONNECTION_STATUS_REASON_AUTHENTICATION_FAILED
158 _moduleLogger.info("Connected")
160 telepathy.CONNECTION_STATUS_CONNECTED,
161 telepathy.CONNECTION_STATUS_REASON_REQUESTED
164 @gtk_toolbox.log_exception(_moduleLogger)
165 def Disconnect(self):
167 For org.freedesktop.telepathy.Connection
168 @bug Not properly logging out. Cookie files need to be per connection and removed
170 _moduleLogger.info("Disconnecting")
172 self.session.conversations.updateSignalHandler.unregister_sink(
175 self._callback = None
176 self._channelManager.close()
177 self.session.logout()
180 _moduleLogger.info("Disconnected")
182 _moduleLogger.exception("Disconnecting Failed")
184 telepathy.CONNECTION_STATUS_DISCONNECTED,
185 telepathy.CONNECTION_STATUS_REASON_REQUESTED
187 self.manager.disconnected(self)
189 @gtk_toolbox.log_exception(_moduleLogger)
190 def RequestChannel(self, type, handleType, handleId, suppressHandler):
192 For org.freedesktop.telepathy.Connection
194 @param type DBus interface name for base channel type
195 @param handleId represents a contact, list, etc according to handleType
197 @returns DBus object path for the channel created or retrieved
199 self.check_connected()
200 self.check_handle(handleType, handleId)
202 h = self.handle(handleType, handleId) if handleId != 0 else None
203 props = self._generate_props(type, h, suppressHandler)
204 if hasattr(self, "_validate_handle"):
205 # HACK Newer python-telepathy
206 self._validate_handle(props)
208 chan = self._channelManager.channel_for_props(props, signal=True)
209 path = chan._object_path
210 _moduleLogger.info("RequestChannel Object Path: %s" % path)
213 @gtk_toolbox.log_exception(_moduleLogger)
214 def RequestHandles(self, handleType, names, sender):
216 For org.freedesktop.telepathy.Connection
217 Overiding telepathy.server.Connecton to allow custom handles
219 self.check_connected()
220 self.check_handle_type(handleType)
224 requestedHandleName = name.encode('utf-8')
225 if handleType == telepathy.HANDLE_TYPE_CONTACT:
226 _moduleLogger.info("RequestHandles Contact: %s" % requestedHandleName)
227 requestedContactId, requestedContactNumber = handle.ContactHandle.from_handle_name(
230 h = handle.create_handle(self, 'contact', requestedContactId, requestedContactNumber)
231 elif handleType == telepathy.HANDLE_TYPE_LIST:
232 # Support only server side (immutable) lists
233 _moduleLogger.info("RequestHandles List: %s" % requestedHandleName)
234 h = handle.create_handle(self, 'list', requestedHandleName)
236 raise telepathy.errors.NotAvailable('Handle type unsupported %d' % handleType)
238 self.add_client_handle(h, sender)
241 def _generate_props(self, channelType, handle, suppressHandler, initiatorHandle=None):
242 targetHandle = 0 if handle is None else handle.get_id()
243 targetHandleType = telepathy.HANDLE_TYPE_NONE if handle is None else handle.get_type()
245 telepathy.CHANNEL_INTERFACE + '.ChannelType': channelType,
246 telepathy.CHANNEL_INTERFACE + '.TargetHandle': targetHandle,
247 telepathy.CHANNEL_INTERFACE + '.TargetHandleType': targetHandleType,
248 telepathy.CHANNEL_INTERFACE + '.Requested': suppressHandler
251 if initiatorHandle is not None:
252 props[telepathy.CHANNEL_INTERFACE + '.InitiatorHandle'] = initiatorHandle.id
257 @gtk_toolbox.log_exception(_moduleLogger)
258 def _on_conversations_updated(self, conv, conversationIds):
259 # @todo get conversations update running
260 # @todo test conversatiuons
261 _moduleLogger.info("Incoming messages from: %r" % (conversationIds, ))
262 for contactId, phoneNumber in conversationIds:
263 h = handle.create_handle(self, 'contact', contactId, phoneNumber)
264 # Just let the TextChannel decide whether it should be reported to the user or not
265 props = self._generate_props(telepathy.CHANNEL_TYPE_TEXT, h, False)
266 channel = self._channelManager.channel_for_props(props, signal=True)