9 import util.misc as misc_utils
20 import simple_presence
23 import channel_manager
26 _moduleLogger = logging.getLogger(__name__)
29 class TheOneRingOptions(object):
33 assert gvoice.session.Session._DEFAULTS["contacts"][1] == "hours"
34 contactsPollPeriodInHours = gvoice.session.Session._DEFAULTS["contacts"][0]
36 assert gvoice.session.Session._DEFAULTS["voicemail"][1] == "minutes"
37 voicemailPollPeriodInMinutes = gvoice.session.Session._DEFAULTS["voicemail"][0]
39 assert gvoice.session.Session._DEFAULTS["texts"][1] == "minutes"
40 textsPollPeriodInMinutes = gvoice.session.Session._DEFAULTS["texts"][0]
42 def __init__(self, parameters = None):
43 if parameters is None:
45 self.useGVContacts = parameters["use-gv-contacts"]
46 self.contactsPollPeriodInHours = parameters['contacts-poll-period-in-hours']
47 self.voicemailPollPeriodInMinutes = parameters['voicemail-poll-period-in-minutes']
48 self.textsPollPeriodInMinutes = parameters['texts-poll-period-in-minutes']
51 class TheOneRingConnection(
53 aliasing.AliasingMixin,
55 capabilities.CapabilitiesMixin,
56 contacts.ContactsMixin,
57 presence.PresenceMixin,
58 requests.RequestsMixin,
59 simple_presence.SimplePresenceMixin,
62 # overiding base class variable
63 _mandatory_parameters = {
67 # overiding base class variable
68 _optional_parameters = {
70 'use-gv-contacts': 'b',
71 'contacts-poll-period-in-hours': 'i',
72 'voicemail-poll-period-in-minutes': 'i',
73 'texts-poll-period-in-minutes': 'i',
75 _parameter_defaults = {
77 'use-gv-contacts': TheOneRingOptions.useGVContacts,
78 'contacts-poll-period-in-hours': TheOneRingOptions.contactsPollPeriodInHours,
79 'voicemail-poll-period-in-minutes': TheOneRingOptions.voicemailPollPeriodInMinutes,
80 'texts-poll-period-in-minutes': TheOneRingOptions.textsPollPeriodInMinutes,
82 _secret_parameters = set((
86 @misc_utils.log_exception(_moduleLogger)
87 def __init__(self, manager, parameters):
90 self.check_parameters(parameters)
91 account = unicode(parameters['account'])
92 encodedAccount = parameters['account'].encode('utf-8')
93 encodedPassword = parameters['password'].encode('utf-8')
94 encodedCallback = misc_utils.normalize_number(parameters['forward'].encode('utf-8'))
95 if encodedCallback and not misc_utils.is_valid_number(encodedCallback):
96 raise telepathy.errors.InvalidArgument("Invalid forwarding number")
98 # Connection init must come first
99 self.__options = TheOneRingOptions(parameters)
100 self.__session = gvoice.session.Session(
103 "contacts": (self.__options.contactsPollPeriodInHours, "hours"),
104 "voicemail": (self.__options.voicemailPollPeriodInMinutes, "minutes"),
105 "texts": (self.__options.textsPollPeriodInMinutes, "minutes"),
108 tp.Connection.__init__(
110 constants._telepathy_protocol_name_,
112 constants._telepathy_implementation_name_
114 aliasing.AliasingMixin.__init__(self)
115 avatars.AvatarsMixin.__init__(self)
116 capabilities.CapabilitiesMixin.__init__(self)
117 contacts.ContactsMixin.__init__(self)
118 presence.PresenceMixin.__init__(self)
119 requests.RequestsMixin.__init__(self)
120 simple_presence.SimplePresenceMixin.__init__(self)
122 self.__manager = weakref.proxy(manager)
123 self.__credentials = (
127 self.__callbackNumberParameter = encodedCallback
128 self.__channelManager = channel_manager.ChannelManager(self)
130 self.__cachePath = os.sep.join((constants._data_path_, "cache", self.username))
132 os.makedirs(self.__cachePath)
137 self.set_self_handle(handle.create_handle(self, 'connection'))
139 autogv.NewGVConversations(weakref.ref(self)),
140 autogv.RefreshVoicemail(weakref.ref(self)),
141 autogv.AutoDisconnect(weakref.ref(self)),
142 autogv.DelayEnableContactIntegration(constants._telepathy_implementation_name_),
145 _moduleLogger.info("Connection to the account %s created" % account)
146 self._timedDisconnect = autogv.TimedDisconnect(weakref.ref(self))
147 self._timedDisconnect.start()
151 return self.__manager
155 return self.__session
159 return self.__options
163 return self.__credentials[0]
166 def callbackNumberParameter(self):
167 return self.__callbackNumberParameter
169 def get_handle_by_name(self, handleType, handleName):
170 requestedHandleName = handleName.encode('utf-8')
172 # We need to return an existing or create a new handle. Unfortunately
173 # handle init's take care of normalizing the handle name. So we have
174 # to create a new handle regardless and burn some handle id's and burn
175 # some extra memory of creating objects we throw away if the handle
177 if handleType == telepathy.HANDLE_TYPE_CONTACT:
178 h = handle.create_handle(self, 'contact', requestedHandleName)
179 elif handleType == telepathy.HANDLE_TYPE_LIST:
180 # Support only server side (immutable) lists
181 h = handle.create_handle(self, 'list', requestedHandleName)
183 raise telepathy.errors.NotAvailable('Handle type unsupported %d' % handleType)
185 for candidate in self._handles.itervalues():
186 if candidate.get_name() == h.get_name():
188 _moduleLogger.debug("Re-used handle for %s, I hoped this helped" % handleName)
193 def log_to_user(self, component, message):
194 for logger in self._loggers:
195 logger.log_message(component, message)
197 def add_logger(self, logger):
198 self._loggers.append(logger)
200 def remove_logger(self, logger):
201 self._loggers.remove(logger)
204 def _channel_manager(self):
205 return self.__channelManager
207 @misc_utils.log_exception(_moduleLogger)
210 For org.freedesktop.telepathy.Connection
212 if self._status != telepathy.CONNECTION_STATUS_DISCONNECTED:
213 _moduleLogger.info("Attempting connect when not disconnected")
215 _moduleLogger.info("Connecting...")
217 telepathy.CONNECTION_STATUS_CONNECTING,
218 telepathy.CONNECTION_STATUS_REASON_REQUESTED
220 self._timedDisconnect.stop()
222 self.__credentials[0],
223 self.__credentials[1],
225 self._on_login_error,
228 @misc_utils.log_exception(_moduleLogger)
229 def _on_login(self, *args):
230 _moduleLogger.info("Connected, setting up...")
232 self.__session.load(self.__cachePath)
234 for plumber in self._plumbing:
236 if not self.__callbackNumberParameter:
237 callback = gvoice.backend.get_sane_callback(
240 self.__callbackNumberParameter = misc_utils.normalize_number(callback)
241 self.session.backend.set_callback_number(self.__callbackNumberParameter)
243 subscribeHandle = self.get_handle_by_name(telepathy.HANDLE_TYPE_LIST, "subscribe")
244 subscribeProps = self.generate_props(telepathy.CHANNEL_TYPE_CONTACT_LIST, subscribeHandle, False)
245 self.__channelManager.channel_for_props(subscribeProps, signal=True)
246 publishHandle = self.get_handle_by_name(telepathy.HANDLE_TYPE_LIST, "publish")
247 publishProps = self.generate_props(telepathy.CHANNEL_TYPE_CONTACT_LIST, publishHandle, False)
248 self.__channelManager.channel_for_props(publishProps, signal=True)
250 _moduleLogger.exception("Setup failed")
251 self.disconnect(telepathy.CONNECTION_STATUS_REASON_AUTHENTICATION_FAILED)
254 _moduleLogger.info("Connected and set up")
256 telepathy.CONNECTION_STATUS_CONNECTED,
257 telepathy.CONNECTION_STATUS_REASON_REQUESTED
260 @misc_utils.log_exception(_moduleLogger)
261 def _on_login_error(self, error):
262 _moduleLogger.error(error)
263 if isinstance(error, StopIteration):
265 elif isinstance(error, gvoice.backend.NetworkError):
266 self.disconnect(telepathy.CONNECTION_STATUS_REASON_NETWORK_ERROR)
268 self.disconnect(telepathy.CONNECTION_STATUS_REASON_AUTHENTICATION_FAILED)
270 @misc_utils.log_exception(_moduleLogger)
271 def Disconnect(self):
273 For org.freedesktop.telepathy.Connection
275 _moduleLogger.info("Kicking off disconnect")
276 self.disconnect(telepathy.CONNECTION_STATUS_REASON_REQUESTED)
278 @misc_utils.log_exception(_moduleLogger)
279 def RequestChannel(self, type, handleType, handleId, suppressHandler):
281 For org.freedesktop.telepathy.Connection
283 @param type DBus interface name for base channel type
284 @param handleId represents a contact, list, etc according to handleType
286 @returns DBus object path for the channel created or retrieved
288 self.check_connected()
289 self.check_handle(handleType, handleId)
291 h = self.get_handle_by_id(handleType, handleId) if handleId != 0 else None
292 props = self.generate_props(type, h, suppressHandler)
293 self._validate_handle(props)
295 chan = self.__channelManager.channel_for_props(props, signal=True)
296 path = chan._object_path
297 _moduleLogger.info("RequestChannel Object Path (%s): %s" % (type.rsplit(".", 1)[-1], path))
300 def generate_props(self, channelType, handleObj, suppressHandler, initiatorHandle=None):
301 targetHandle = 0 if handleObj is None else handleObj.get_id()
302 targetHandleType = telepathy.HANDLE_TYPE_NONE if handleObj is None else handleObj.get_type()
304 telepathy.CHANNEL_INTERFACE + '.ChannelType': channelType,
305 telepathy.CHANNEL_INTERFACE + '.TargetHandle': targetHandle,
306 telepathy.CHANNEL_INTERFACE + '.TargetHandleType': targetHandleType,
307 telepathy.CHANNEL_INTERFACE + '.Requested': suppressHandler
310 if initiatorHandle is not None:
311 props[telepathy.CHANNEL_INTERFACE + '.InitiatorHandle'] = initiatorHandle.id
315 def disconnect(self, reason):
316 _moduleLogger.info("Disconnecting")
318 self._timedDisconnect.stop()
320 # Not having the disconnect first can cause weird behavior with clients
321 # including not being able to reconnect or even crashing
323 telepathy.CONNECTION_STATUS_DISCONNECTED,
327 for plumber in self._plumbing:
330 self.__channelManager.close()
331 self.manager.disconnected(self)
333 self.session.save(self.__cachePath)
334 self.session.logout()
337 # In case one of the above items takes too long (which it should never
338 # do), we leave the starting of the shutdown-on-idle counter to the
340 self.manager.disconnect_completed()
342 _moduleLogger.info("Disconnected")