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):
88 self.check_parameters(parameters)
89 account = unicode(parameters['account'])
90 encodedAccount = parameters['account'].encode('utf-8')
91 encodedPassword = parameters['password'].encode('utf-8')
92 encodedCallback = misc_utils.normalize_number(parameters['forward'].encode('utf-8'))
93 if encodedCallback and not misc_utils.is_valid_number(encodedCallback):
94 raise telepathy.errors.InvalidArgument("Invalid forwarding number")
96 # Connection init must come first
97 self.__options = TheOneRingOptions(parameters)
98 self.__session = gvoice.session.Session(
101 "contacts": (self.__options.contactsPollPeriodInHours, "hours"),
102 "voicemail": (self.__options.voicemailPollPeriodInMinutes, "minutes"),
103 "texts": (self.__options.textsPollPeriodInMinutes, "minutes"),
106 tp.Connection.__init__(
108 constants._telepathy_protocol_name_,
110 constants._telepathy_implementation_name_
112 aliasing.AliasingMixin.__init__(self)
113 avatars.AvatarsMixin.__init__(self)
114 capabilities.CapabilitiesMixin.__init__(self)
115 contacts.ContactsMixin.__init__(self)
116 presence.PresenceMixin.__init__(self)
117 requests.RequestsMixin.__init__(self)
118 simple_presence.SimplePresenceMixin.__init__(self)
120 self.__manager = weakref.proxy(manager)
121 self.__credentials = (
125 self.__callbackNumberParameter = encodedCallback
126 self.__channelManager = channel_manager.ChannelManager(self)
128 self.__cachePath = os.sep.join((constants._data_path_, "cache", self.username))
130 os.makedirs(self.__cachePath)
135 self.set_self_handle(handle.create_handle(self, 'connection'))
137 autogv.NewGVConversations(weakref.ref(self)),
138 autogv.RefreshVoicemail(weakref.ref(self)),
139 autogv.AutoDisconnect(weakref.ref(self)),
140 autogv.DelayEnableContactIntegration(constants._telepathy_implementation_name_),
143 _moduleLogger.info("Connection to the account %s created" % account)
144 self._timedDisconnect = autogv.TimedDisconnect(weakref.ref(self))
145 self._timedDisconnect.start()
149 return self.__manager
153 return self.__session
157 return self.__options
161 return self.__credentials[0]
164 def callbackNumberParameter(self):
165 return self.__callbackNumberParameter
167 def get_handle_by_name(self, handleType, handleName):
168 requestedHandleName = handleName.encode('utf-8')
169 if handleType == telepathy.HANDLE_TYPE_CONTACT:
170 h = handle.create_handle(self, 'contact', requestedHandleName)
171 elif handleType == telepathy.HANDLE_TYPE_LIST:
172 # Support only server side (immutable) lists
173 h = handle.create_handle(self, 'list', requestedHandleName)
175 raise telepathy.errors.NotAvailable('Handle type unsupported %d' % handleType)
179 def _channel_manager(self):
180 return self.__channelManager
182 @misc_utils.log_exception(_moduleLogger)
185 For org.freedesktop.telepathy.Connection
187 if self._status != telepathy.CONNECTION_STATUS_DISCONNECTED:
188 _moduleLogger.info("Attempting connect when not disconnected")
190 _moduleLogger.info("Connecting...")
192 telepathy.CONNECTION_STATUS_CONNECTING,
193 telepathy.CONNECTION_STATUS_REASON_REQUESTED
195 self._timedDisconnect.stop()
197 self.__credentials[0],
198 self.__credentials[1],
200 self._on_login_error,
203 @misc_utils.log_exception(_moduleLogger)
204 def _on_login(self, *args):
205 _moduleLogger.info("Connected, setting up...")
207 self.__session.load(self.__cachePath)
209 for plumber in self._plumbing:
211 if not self.__callbackNumberParameter:
212 callback = gvoice.backend.get_sane_callback(
215 self.__callbackNumberParameter = misc_utils.normalize_number(callback)
216 self.session.backend.set_callback_number(self.__callbackNumberParameter)
218 subscribeHandle = self.get_handle_by_name(telepathy.HANDLE_TYPE_LIST, "subscribe")
219 subscribeProps = self.generate_props(telepathy.CHANNEL_TYPE_CONTACT_LIST, subscribeHandle, False)
220 self.__channelManager.channel_for_props(subscribeProps, signal=True)
221 publishHandle = self.get_handle_by_name(telepathy.HANDLE_TYPE_LIST, "publish")
222 publishProps = self.generate_props(telepathy.CHANNEL_TYPE_CONTACT_LIST, publishHandle, False)
223 self.__channelManager.channel_for_props(publishProps, signal=True)
225 _moduleLogger.exception("Setup failed")
226 self.disconnect(telepathy.CONNECTION_STATUS_REASON_AUTHENTICATION_FAILED)
229 _moduleLogger.info("Connected and set up")
231 telepathy.CONNECTION_STATUS_CONNECTED,
232 telepathy.CONNECTION_STATUS_REASON_REQUESTED
235 @misc_utils.log_exception(_moduleLogger)
236 def _on_login_error(self, error):
237 _moduleLogger.error(error)
238 if isinstance(error, gvoice.backend.NetworkError):
239 self.disconnect(telepathy.CONNECTION_STATUS_REASON_NETWORK_ERROR)
241 self.disconnect(telepathy.CONNECTION_STATUS_REASON_AUTHENTICATION_FAILED)
243 @misc_utils.log_exception(_moduleLogger)
244 def Disconnect(self):
246 For org.freedesktop.telepathy.Connection
248 _moduleLogger.info("Kicking off disconnect")
249 self.disconnect(telepathy.CONNECTION_STATUS_REASON_REQUESTED)
251 @misc_utils.log_exception(_moduleLogger)
252 def RequestChannel(self, type, handleType, handleId, suppressHandler):
254 For org.freedesktop.telepathy.Connection
256 @param type DBus interface name for base channel type
257 @param handleId represents a contact, list, etc according to handleType
259 @returns DBus object path for the channel created or retrieved
261 self.check_connected()
262 self.check_handle(handleType, handleId)
264 h = self.get_handle_by_id(handleType, handleId) if handleId != 0 else None
265 props = self.generate_props(type, h, suppressHandler)
266 self._validate_handle(props)
268 chan = self.__channelManager.channel_for_props(props, signal=True)
269 path = chan._object_path
270 _moduleLogger.info("RequestChannel Object Path (%s): %s" % (type.rsplit(".", 1)[-1], path))
273 def generate_props(self, channelType, handleObj, suppressHandler, initiatorHandle=None):
274 targetHandle = 0 if handleObj is None else handleObj.get_id()
275 targetHandleType = telepathy.HANDLE_TYPE_NONE if handleObj is None else handleObj.get_type()
277 telepathy.CHANNEL_INTERFACE + '.ChannelType': channelType,
278 telepathy.CHANNEL_INTERFACE + '.TargetHandle': targetHandle,
279 telepathy.CHANNEL_INTERFACE + '.TargetHandleType': targetHandleType,
280 telepathy.CHANNEL_INTERFACE + '.Requested': suppressHandler
283 if initiatorHandle is not None:
284 props[telepathy.CHANNEL_INTERFACE + '.InitiatorHandle'] = initiatorHandle.id
288 def disconnect(self, reason):
289 _moduleLogger.info("Disconnecting")
291 self._timedDisconnect.stop()
293 # Not having the disconnect first can cause weird behavior with clients
294 # including not being able to reconnect or even crashing
296 telepathy.CONNECTION_STATUS_DISCONNECTED,
300 for plumber in self._plumbing:
303 self.__channelManager.close()
304 self.manager.disconnected(self)
306 self.session.save(self.__cachePath)
307 self.session.logout()
310 # In case one of the above items takes too long (which it should never
311 # do), we leave the starting of the shutdown-on-idle counter to the
313 self.manager.disconnect_completed()
315 _moduleLogger.info("Disconnected")