10 except (ImportError, OSError):
15 import util.coroutines as coroutines
16 import util.misc as util_misc
25 import simple_presence
29 import channel_manager
32 _moduleLogger = logging.getLogger("connection")
35 class TheOneRingConnection(
37 requests.RequestsMixin,
38 contacts.ContactsMixin,
39 aliasing.AliasingMixin,
40 simple_presence.SimplePresenceMixin,
41 presence.PresenceMixin,
42 capabilities.CapabilitiesMixin,
45 # overiding base class variable
46 _mandatory_parameters = {
50 # overiding base class variable
51 _optional_parameters = {
54 _parameter_defaults = {
57 _secret_parameters = set((
61 @gtk_toolbox.log_exception(_moduleLogger)
62 def __init__(self, manager, parameters):
63 self.check_parameters(parameters)
64 account = unicode(parameters['account'])
65 encodedAccount = parameters['account'].encode('utf-8')
66 encodedPassword = parameters['password'].encode('utf-8')
67 encodedCallback = util_misc.normalize_number(parameters['forward'].encode('utf-8'))
68 if encodedCallback and not util_misc.is_valid_number(encodedCallback):
69 raise telepathy.errors.InvalidArgument("Invalid forwarding number")
71 # Connection init must come first
72 self.__session = gvoice.session.Session(None)
73 tp.Connection.__init__(
75 constants._telepathy_protocol_name_,
77 constants._telepathy_implementation_name_
79 requests.RequestsMixin.__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)
87 self.__credentials = (
91 self.__callbackNumberParameter = encodedCallback
92 self.__channelManager = channel_manager.ChannelManager(self)
95 self.__connection = conic.Connection()
97 self.__connection = None
98 self.__cachePath = os.sep.join((constants._data_path_, "cache", self.username))
100 os.makedirs(self.__cachePath)
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 callbackNumberParameter(self):
124 return self.__callbackNumberParameter
126 def get_handle_by_name(self, handleType, handleName):
127 requestedHandleName = handleName.encode('utf-8')
128 if handleType == telepathy.HANDLE_TYPE_CONTACT:
129 _moduleLogger.info("get_handle_by_name Contact: %s" % requestedHandleName)
130 h = handle.create_handle(self, 'contact', requestedHandleName)
131 elif handleType == telepathy.HANDLE_TYPE_LIST:
132 # Support only server side (immutable) lists
133 _moduleLogger.info("get_handle_by_name List: %s" % requestedHandleName)
134 h = handle.create_handle(self, 'list', requestedHandleName)
136 raise telepathy.errors.NotAvailable('Handle type unsupported %d' % handleType)
140 def _channel_manager(self):
141 return self.__channelManager
143 @gtk_toolbox.log_exception(_moduleLogger)
146 For org.freedesktop.telepathy.Connection
148 _moduleLogger.info("Connecting...")
150 telepathy.CONNECTION_STATUS_CONNECTING,
151 telepathy.CONNECTION_STATUS_REASON_REQUESTED
154 self.__session.load(self.__cachePath)
156 self.__callback = coroutines.func_sink(
157 coroutines.expand_positional(
158 self._on_conversations_updated
161 self.session.voicemails.updateSignalHandler.register_sink(
164 self.session.texts.updateSignalHandler.register_sink(
167 self.session.login(*self.__credentials)
168 if not self.__callbackNumberParameter:
169 callback = gvoice.backend.get_sane_callback(
172 self.__callbackNumberParameter = util_misc.normalize_number(callback)
173 self.session.backend.set_callback_number(self.__callbackNumberParameter)
175 subscribeHandle = self.get_handle_by_name(telepathy.HANDLE_TYPE_LIST, "subscribe")
176 subscribeProps = self._generate_props(telepathy.CHANNEL_TYPE_CONTACT_LIST, subscribeHandle, False)
177 self.__channelManager.channel_for_props(subscribeProps, signal=True)
178 publishHandle = self.get_handle_by_name(telepathy.HANDLE_TYPE_LIST, "publish")
179 publishProps = self._generate_props(telepathy.CHANNEL_TYPE_CONTACT_LIST, publishHandle, False)
180 self.__channelManager.channel_for_props(publishProps, signal=True)
181 except gvoice.backend.NetworkError, e:
182 _moduleLogger.exception("Connection Failed")
184 telepathy.CONNECTION_STATUS_DISCONNECTED,
185 telepathy.CONNECTION_STATUS_REASON_NETWORK_ERROR
189 _moduleLogger.exception("Connection Failed")
191 telepathy.CONNECTION_STATUS_DISCONNECTED,
192 telepathy.CONNECTION_STATUS_REASON_AUTHENTICATION_FAILED
196 _moduleLogger.info("Connected")
198 telepathy.CONNECTION_STATUS_CONNECTED,
199 telepathy.CONNECTION_STATUS_REASON_REQUESTED
201 if self.__connection is not None:
202 self.__connectionEventId = self.__connection.connect("connection-event", self._on_connection_change)
204 @gtk_toolbox.log_exception(_moduleLogger)
205 def Disconnect(self):
207 For org.freedesktop.telepathy.Connection
210 telepathy.CONNECTION_STATUS_DISCONNECTED,
211 telepathy.CONNECTION_STATUS_REASON_REQUESTED
216 _moduleLogger.exception("Error durring disconnect")
218 @gtk_toolbox.log_exception(_moduleLogger)
219 def RequestChannel(self, type, handleType, handleId, suppressHandler):
221 For org.freedesktop.telepathy.Connection
223 @param type DBus interface name for base channel type
224 @param handleId represents a contact, list, etc according to handleType
226 @returns DBus object path for the channel created or retrieved
228 self.check_connected()
229 self.check_handle(handleType, handleId)
231 h = self.get_handle_by_id(handleType, handleId) if handleId != 0 else None
232 props = self._generate_props(type, h, suppressHandler)
233 self._validate_handle(props)
235 chan = self.__channelManager.channel_for_props(props, signal=True)
236 path = chan._object_path
237 _moduleLogger.info("RequestChannel Object Path (%s): %s" % (type.rsplit(".", 1)[-1], path))
240 def _generate_props(self, channelType, handle, suppressHandler, initiatorHandle=None):
241 targetHandle = 0 if handle is None else handle.get_id()
242 targetHandleType = telepathy.HANDLE_TYPE_NONE if handle is None else handle.get_type()
244 telepathy.CHANNEL_INTERFACE + '.ChannelType': channelType,
245 telepathy.CHANNEL_INTERFACE + '.TargetHandle': targetHandle,
246 telepathy.CHANNEL_INTERFACE + '.TargetHandleType': targetHandleType,
247 telepathy.CHANNEL_INTERFACE + '.Requested': suppressHandler
250 if initiatorHandle is not None:
251 props[telepathy.CHANNEL_INTERFACE + '.InitiatorHandle'] = initiatorHandle.id
255 def _disconnect(self):
256 _moduleLogger.info("Disconnecting")
257 self.session.voicemails.updateSignalHandler.unregister_sink(
260 self.session.texts.updateSignalHandler.unregister_sink(
263 self.__callback = None
265 self.__channelManager.close()
266 self.session.save(self.__cachePath)
267 self.session.logout()
270 self.manager.disconnected(self)
271 _moduleLogger.info("Disconnected")
273 @gtk_toolbox.log_exception(_moduleLogger)
274 def _on_conversations_updated(self, conv, conversationIds):
275 _moduleLogger.debug("Incoming messages from: %r" % (conversationIds, ))
276 for phoneNumber in conversationIds:
277 h = self.get_handle_by_name(telepathy.HANDLE_TYPE_CONTACT, phoneNumber)
278 # Just let the TextChannel decide whether it should be reported to the user or not
279 props = self._generate_props(telepathy.CHANNEL_TYPE_TEXT, h, False)
280 if self.__channelManager.channel_exists(props):
283 # Maemo 4.1's RTComm opens a window for a chat regardless if a
284 # message is received or not, so we need to do some filtering here
285 mergedConv = conv.get_conversation(phoneNumber)
288 for conversation in mergedConv.conversations
289 if not conversation.isRead and not conversation.isArchived
294 chan = self.__channelManager.channel_for_props(props, signal=True)
296 @gtk_toolbox.log_exception(_moduleLogger)
297 def _on_connection_change(self, connection, event):
301 if not self.session.is_logged_in():
302 _moduleLogger.info("Received connection change event when not logged in")
304 status = event.get_status()
305 error = event.get_error()
306 iap_id = event.get_iap_id()
307 bearer = event.get_bearer_type()
309 if status == conic.STATUS_DISCONNECTED:
310 _moduleLogger.info("Disconnecting due to loss of network connection")
312 telepathy.CONNECTION_STATUS_DISCONNECTED,
313 telepathy.CONNECTION_STATUS_REASON_NETWORK_ERROR
318 _moduleLogger.exception("Error durring disconnect")
320 _moduleLogger.info("Other status: %r" % (status, ))