9 import util.misc as misc_utils
20 import simple_presence
23 import channel_manager
26 _moduleLogger = logging.getLogger(__name__)
29 class TheOneRingOptions(object):
35 assert gvoice.session.Session._DEFAULTS["contacts"][1] == "hours"
36 contactsPollPeriodInHours = gvoice.session.Session._DEFAULTS["contacts"][0]
38 assert gvoice.session.Session._DEFAULTS["voicemail"][1] == "minutes"
39 voicemailPollPeriodInMinutes = gvoice.session.Session._DEFAULTS["voicemail"][0]
41 assert gvoice.session.Session._DEFAULTS["texts"][1] == "minutes"
42 textsPollPeriodInMinutes = gvoice.session.Session._DEFAULTS["texts"][0]
44 def __init__(self, parameters = None):
45 if parameters is None:
47 self.ignoreDND = parameters["ignore-dnd"]
48 self.useGVContacts = parameters["use-gv-contacts"]
49 self.contactsPollPeriodInHours = parameters['contacts-poll-period-in-hours']
50 self.voicemailPollPeriodInMinutes = parameters['voicemail-poll-period-in-minutes']
51 self.textsPollPeriodInMinutes = parameters['texts-poll-period-in-minutes']
54 class TheOneRingConnection(
56 aliasing.AliasingMixin,
58 capabilities.CapabilitiesMixin,
59 contacts.ContactsMixin,
60 requests.RequestsMixin,
61 simple_presence.TheOneRingPresence,
62 simple_presence.SimplePresenceMixin,
63 presence.PresenceMixin,
66 # overiding base class variable
67 _mandatory_parameters = {
71 # overiding base class variable
72 _optional_parameters = {
75 'use-gv-contacts': 'b',
76 'contacts-poll-period-in-hours': 'i',
77 'voicemail-poll-period-in-minutes': 'i',
78 'texts-poll-period-in-minutes': 'i',
80 _parameter_defaults = {
82 'ignore-dnd': TheOneRingOptions.ignoreDND,
83 'use-gv-contacts': TheOneRingOptions.useGVContacts,
84 'contacts-poll-period-in-hours': TheOneRingOptions.contactsPollPeriodInHours,
85 'voicemail-poll-period-in-minutes': TheOneRingOptions.voicemailPollPeriodInMinutes,
86 'texts-poll-period-in-minutes': TheOneRingOptions.textsPollPeriodInMinutes,
88 _secret_parameters = set((
92 @misc_utils.log_exception(_moduleLogger)
93 def __init__(self, manager, parameters):
96 self.check_parameters(parameters)
97 account = unicode(parameters['account'])
98 encodedAccount = parameters['account'].encode('utf-8')
99 encodedPassword = parameters['password'].encode('utf-8')
100 encodedCallback = misc_utils.normalize_number(parameters['forward'].encode('utf-8'))
101 if encodedCallback and not misc_utils.is_valid_number(encodedCallback):
102 raise telepathy.errors.InvalidArgument("Invalid forwarding number")
104 # Connection init must come first
105 self.__options = TheOneRingOptions(parameters)
106 self.__accountName = account
107 self.__session = None
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 requests.RequestsMixin.__init__(self)
119 simple_presence.TheOneRingPresence.__init__(self, self.__options.ignoreDND)
120 simple_presence.SimplePresenceMixin.__init__(self, self)
121 presence.PresenceMixin.__init__(self, self)
123 self.__manager = weakref.proxy(manager)
124 self.__credentials = (
128 self.__callbackNumberParameter = encodedCallback
129 self.__channelManager = channel_manager.ChannelManager(self)
131 self.__cachePath = os.sep.join((constants._data_path_, "cache", self.username))
133 os.makedirs(self.__cachePath)
138 self.set_self_handle(handle.create_handle(self, 'connection'))
140 autogv.NewGVConversations(weakref.ref(self)),
141 autogv.RefreshVoicemail(weakref.ref(self)),
142 autogv.AutoDisconnect(weakref.ref(self)),
143 autogv.DelayEnableContactIntegration(constants._telepathy_implementation_name_),
146 _moduleLogger.info("Connection to the account %s created" % account)
147 self._timedDisconnect = autogv.TimedDisconnect(weakref.ref(self))
148 self._timedDisconnect.start()
152 return self.__manager
156 return self.__session
160 return self.__options
164 return self.__credentials[0]
167 def callbackNumberParameter(self):
168 return self.__callbackNumberParameter
170 def get_handle_by_name(self, handleType, handleName):
171 requestedHandleName = handleName.encode('utf-8')
173 # We need to return an existing or create a new handle. Unfortunately
174 # handle init's take care of normalizing the handle name. So we have
175 # to create a new handle regardless and burn some handle id's and burn
176 # some extra memory of creating objects we throw away if the handle
178 if handleType == telepathy.HANDLE_TYPE_CONTACT:
179 h = handle.create_handle(self, 'contact', requestedHandleName)
180 elif handleType == telepathy.HANDLE_TYPE_LIST:
181 # Support only server side (immutable) lists
182 h = handle.create_handle(self, 'list', requestedHandleName)
184 raise telepathy.errors.NotAvailable('Handle type unsupported %d' % handleType)
186 for candidate in self._handles.itervalues():
187 if candidate.get_name() == h.get_name():
189 _moduleLogger.debug("Re-used handle for %s, I hoped this helped" % handleName)
194 def log_to_user(self, component, message):
195 for logger in self._loggers:
196 logger.log_message(component, message)
198 def add_logger(self, logger):
199 self._loggers.append(logger)
201 def remove_logger(self, logger):
202 self._loggers.remove(logger)
205 def _channel_manager(self):
206 return self.__channelManager
208 @misc_utils.log_exception(_moduleLogger)
211 For org.freedesktop.telepathy.Connection
213 if self.__session is None:
214 self.__session = gvoice.session.Session(
215 cookiePath = os.path.join(constants._data_path_, "%s.cookies" % self.__accountName),
217 "contacts": (self.__options.contactsPollPeriodInHours, "hours"),
218 "voicemail": (self.__options.voicemailPollPeriodInMinutes, "minutes"),
219 "texts": (self.__options.textsPollPeriodInMinutes, "minutes"),
223 if self._status != telepathy.CONNECTION_STATUS_DISCONNECTED:
224 _moduleLogger.info("Attempting connect when not disconnected")
226 _moduleLogger.info("Connecting...")
228 telepathy.CONNECTION_STATUS_CONNECTING,
229 telepathy.CONNECTION_STATUS_REASON_REQUESTED
231 self._timedDisconnect.stop()
233 self.__credentials[0],
234 self.__credentials[1],
236 self._on_login_error,
239 @misc_utils.log_exception(_moduleLogger)
240 def _on_login(self, *args):
241 _moduleLogger.info("Connected, setting up...")
243 self.session.load(self.__cachePath)
245 for plumber in self._plumbing:
247 if not self.__callbackNumberParameter:
248 callback = gvoice.backend.get_sane_callback(
251 self.__callbackNumberParameter = misc_utils.normalize_number(callback)
252 self.session.backend.set_callback_number(self.__callbackNumberParameter)
254 subscribeHandle = self.get_handle_by_name(telepathy.HANDLE_TYPE_LIST, "subscribe")
255 subscribeProps = self.generate_props(telepathy.CHANNEL_TYPE_CONTACT_LIST, subscribeHandle, False)
256 self.__channelManager.channel_for_props(subscribeProps, signal=True)
257 publishHandle = self.get_handle_by_name(telepathy.HANDLE_TYPE_LIST, "publish")
258 publishProps = self.generate_props(telepathy.CHANNEL_TYPE_CONTACT_LIST, publishHandle, False)
259 self.__channelManager.channel_for_props(publishProps, signal=True)
261 _moduleLogger.exception("Setup failed")
262 self.disconnect(telepathy.CONNECTION_STATUS_REASON_AUTHENTICATION_FAILED)
265 _moduleLogger.info("Connected and set up")
267 telepathy.CONNECTION_STATUS_CONNECTED,
268 telepathy.CONNECTION_STATUS_REASON_REQUESTED
271 @misc_utils.log_exception(_moduleLogger)
272 def _on_login_error(self, error):
273 _moduleLogger.error(error)
274 if isinstance(error, StopIteration):
276 elif isinstance(error, gvoice.backend.NetworkError):
277 self.disconnect(telepathy.CONNECTION_STATUS_REASON_NETWORK_ERROR)
279 self.disconnect(telepathy.CONNECTION_STATUS_REASON_AUTHENTICATION_FAILED)
281 @misc_utils.log_exception(_moduleLogger)
282 def Disconnect(self):
284 For org.freedesktop.telepathy.Connection
286 _moduleLogger.info("Kicking off disconnect")
287 self.disconnect(telepathy.CONNECTION_STATUS_REASON_REQUESTED)
289 @misc_utils.log_exception(_moduleLogger)
290 def RequestChannel(self, type, handleType, handleId, suppressHandler):
292 For org.freedesktop.telepathy.Connection
294 @param type DBus interface name for base channel type
295 @param handleId represents a contact, list, etc according to handleType
297 @returns DBus object path for the channel created or retrieved
299 self.check_connected()
300 self.check_handle(handleType, handleId)
302 h = self.get_handle_by_id(handleType, handleId) if handleId != 0 else None
303 props = self.generate_props(type, h, suppressHandler)
304 self._validate_handle(props)
306 chan = self.__channelManager.channel_for_props(props, signal=True)
307 path = chan._object_path
308 _moduleLogger.info("RequestChannel Object Path (%s): %s" % (type.rsplit(".", 1)[-1], path))
311 def generate_props(self, channelType, handleObj, suppressHandler, initiatorHandle=None):
312 targetHandle = 0 if handleObj is None else handleObj.get_id()
313 targetHandleType = telepathy.HANDLE_TYPE_NONE if handleObj is None else handleObj.get_type()
315 telepathy.CHANNEL_INTERFACE + '.ChannelType': channelType,
316 telepathy.CHANNEL_INTERFACE + '.TargetHandle': targetHandle,
317 telepathy.CHANNEL_INTERFACE + '.TargetHandleType': targetHandleType,
318 telepathy.CHANNEL_INTERFACE + '.Requested': suppressHandler
321 if initiatorHandle is not None:
322 props[telepathy.CHANNEL_INTERFACE + '.InitiatorHandle'] = initiatorHandle.id
326 def disconnect(self, reason):
327 _moduleLogger.info("Disconnecting")
329 self._timedDisconnect.stop()
331 # Not having the disconnect first can cause weird behavior with clients
332 # including not being able to reconnect or even crashing
334 telepathy.CONNECTION_STATUS_DISCONNECTED,
338 for plumber in self._plumbing:
341 self.__channelManager.close()
342 self.manager.disconnected(self)
344 self.session.save(self.__cachePath)
345 self.session.shutdown()
348 # In case one of the above items takes too long (which it should never
349 # do), we leave the starting of the shutdown-on-idle counter to the
351 self.manager.disconnect_completed()
353 _moduleLogger.info("Disconnected")