Forcing calls to quit immediately rather than giving time to cancel to fix issues...
[theonering] / src / connection.py
index 591f7b7..71e3920 100644 (file)
+import os
 import weakref
 import logging
 
 import telepathy
 
 import constants
+import tp
+import util.misc as misc_utils
+
 import gvoice
 import handle
+
+import aliasing
+import avatars
+import capabilities
+import contacts
+import presence
+import requests
+import simple_presence
+
+import autogv
 import channel_manager
 
 
-_moduleLogger = logging.getLogger("connection")
+_moduleLogger = logging.getLogger(__name__)
+
+
+class TheOneRingOptions(object):
+
+       ignoreDND = True
+
+       useGVContacts = True
+
+       assert gvoice.session.Session._DEFAULTS["contacts"][1] == "hours"
+       contactsPollPeriodInHours = gvoice.session.Session._DEFAULTS["contacts"][0]
+
+       assert gvoice.session.Session._DEFAULTS["voicemail"][1] == "minutes"
+       voicemailPollPeriodInMinutes = gvoice.session.Session._DEFAULTS["voicemail"][0]
+
+       assert gvoice.session.Session._DEFAULTS["texts"][1] == "minutes"
+       textsPollPeriodInMinutes = gvoice.session.Session._DEFAULTS["texts"][0]
 
+       def __init__(self, parameters = None):
+               if parameters is None:
+                       return
+               self.ignoreDND = parameters["ignore-dnd"]
+               self.useGVContacts = parameters["use-gv-contacts"]
+               self.contactsPollPeriodInHours = parameters['contacts-poll-period-in-hours']
+               self.voicemailPollPeriodInMinutes = parameters['voicemail-poll-period-in-minutes']
+               self.textsPollPeriodInMinutes = parameters['texts-poll-period-in-minutes']
 
-class TheOneRingConnection(telepathy.server.Connection):
 
-       # Overriding a base class variable
+class TheOneRingConnection(
+       tp.Connection,
+       aliasing.AliasingMixin,
+       avatars.AvatarsMixin,
+       capabilities.CapabilitiesMixin,
+       contacts.ContactsMixin,
+       requests.RequestsMixin,
+       simple_presence.TheOneRingPresence,
+       simple_presence.SimplePresenceMixin,
+       presence.PresenceMixin,
+):
+
+       # overiding base class variable
        _mandatory_parameters = {
-               'username' : 's',
-               'password' : 's',
-               'forward' : 's',
+               'account': 's',
+               'password': 's',
        }
-       # Overriding a base class variable
+       # overiding base class variable
        _optional_parameters = {
+               'forward': 's',
+               'ignore-dnd': 'b',
+               'use-gv-contacts': 'b',
+               'contacts-poll-period-in-hours': 'i',
+               'voicemail-poll-period-in-minutes': 'i',
+               'texts-poll-period-in-minutes': 'i',
        }
        _parameter_defaults = {
+               'forward': '',
+               'ignore-dnd': TheOneRingOptions.ignoreDND,
+               'use-gv-contacts': TheOneRingOptions.useGVContacts,
+               'contacts-poll-period-in-hours': TheOneRingOptions.contactsPollPeriodInHours,
+               'voicemail-poll-period-in-minutes': TheOneRingOptions.voicemailPollPeriodInMinutes,
+               'texts-poll-period-in-minutes': TheOneRingOptions.textsPollPeriodInMinutes,
        }
+       _secret_parameters = set((
+               "password",
+       ))
 
+       @misc_utils.log_exception(_moduleLogger)
        def __init__(self, manager, parameters):
-               try:
-                       self.check_parameters(parameters)
-                       account = unicode(parameters['username'])
-
-                       telepathy.server.Connection.__init__(
-                               self,
-                               constants._telepathy_protocol_name_,
-                               account,
-                               constants._telepathy_implementation_name_
-                       )
+               self._loggers = []
 
-                       self._manager = weakref.proxy(manager)
-                       self._credentials = (
-                               parameters['username'].encode('utf-8'),
-                               parameters['password'].encode('utf-8'),
-                       )
-                       self._callbackNumber = parameters['forward'].encode('utf-8')
-                       self._channelManager = channel_manager.ChannelManager(self)
+               self.check_parameters(parameters)
+               account = unicode(parameters['account'])
+               encodedAccount = parameters['account'].encode('utf-8')
+               encodedPassword = parameters['password'].encode('utf-8')
+               encodedCallback = misc_utils.normalize_number(parameters['forward'].encode('utf-8'))
+               if encodedCallback and not misc_utils.is_valid_number(encodedCallback):
+                       raise telepathy.errors.InvalidArgument("Invalid forwarding number")
+
+               # Connection init must come first
+               self.__options = TheOneRingOptions(parameters)
+               self.__accountName = account
+               self.__session = None
+               tp.Connection.__init__(
+                       self,
+                       constants._telepathy_protocol_name_,
+                       account,
+                       constants._telepathy_implementation_name_
+               )
+               aliasing.AliasingMixin.__init__(self)
+               avatars.AvatarsMixin.__init__(self)
+               capabilities.CapabilitiesMixin.__init__(self)
+               contacts.ContactsMixin.__init__(self)
+               requests.RequestsMixin.__init__(self)
+               simple_presence.TheOneRingPresence.__init__(self, self.__options.ignoreDND)
+               simple_presence.SimplePresenceMixin.__init__(self, self)
+               presence.PresenceMixin.__init__(self, self)
 
-                       cookieFilePath = "%s/cookies.txt" % constants._data_path_
-                       self._session = gvoice.session.Session(cookieFilePath)
+               self.__manager = weakref.proxy(manager)
+               self.__credentials = (
+                       encodedAccount,
+                       encodedPassword,
+               )
+               self.__callbackNumberParameter = encodedCallback
+               self.__channelManager = channel_manager.ChannelManager(self)
 
-                       self.set_self_handle(handle.create_handle(self, 'connection'))
+               self.__cachePath = os.sep.join((constants._data_path_, "cache", self.username))
+               try:
+                       os.makedirs(self.__cachePath)
+               except OSError, e:
+                       if e.errno != 17:
+                               raise
+
+               self.set_self_handle(handle.create_handle(self, 'connection'))
+               self._plumbing = [
+                       autogv.NewGVConversations(weakref.ref(self)),
+                       autogv.RefreshVoicemail(weakref.ref(self)),
+                       autogv.AutoDisconnect(weakref.ref(self)),
+                       autogv.DelayEnableContactIntegration(constants._telepathy_implementation_name_),
+               ]
 
-                       _moduleLogger.info("Connection to the account %s created" % account)
-               except Exception, e:
-                       _moduleLogger.exception("Failed to create Connection")
-                       raise
+               _moduleLogger.info("Connection to the account %s created" % account)
+               self._timedDisconnect = autogv.TimedDisconnect(weakref.ref(self))
+               self._timedDisconnect.start()
 
        @property
        def manager(self):
-               return self._manager
+               return self.__manager
 
        @property
        def session(self):
-               return self._session
+               return self.__session
+
+       @property
+       def options(self):
+               return self.__options
 
        @property
        def username(self):
-               return self._credentials[0]
+               return self.__credentials[0]
 
-       def handle(self, handleType, handleId):
-               self.check_handle(handleType, handleId)
-               return self._handles[handleType, handleId]
+       @property
+       def callbackNumberParameter(self):
+               return self.__callbackNumberParameter
+
+       def get_handle_by_name(self, handleType, handleName):
+               requestedHandleName = handleName.encode('utf-8')
+
+               # We need to return an existing or create a new handle.  Unfortunately
+               # handle init's take care of normalizing the handle name.  So we have
+               # to create a new handle regardless and burn some handle id's and burn
+               # some extra memory of creating objects we throw away if the handle
+               # already exists.
+               if handleType == telepathy.HANDLE_TYPE_CONTACT:
+                       h = handle.create_handle(self, 'contact', requestedHandleName)
+               elif handleType == telepathy.HANDLE_TYPE_LIST:
+                       # Support only server side (immutable) lists
+                       h = handle.create_handle(self, 'list', requestedHandleName)
+               else:
+                       raise telepathy.errors.NotAvailable('Handle type unsupported %d' % handleType)
+
+               for candidate in self._handles.itervalues():
+                       if candidate.get_name() == h.get_name():
+                               h = candidate
+                               _moduleLogger.debug("Re-used handle for %s, I hoped this helped" % handleName)
+                               break
+
+               return h
+
+       def force_log_display(self):
+               accountNumber = misc_utils.normalize_number(self.session.backend.get_account_number())
+               debugHandle = self.get_handle_by_name(
+                       telepathy.HANDLE_TYPE_CONTACT,
+                       accountNumber,
+               )
+               debugPromptProps = self.generate_props(telepathy.CHANNEL_TYPE_TEXT, debugHandle, False)
+               self.__channelManager.channel_for_props(debugPromptProps, signal=True)
+
+       def log_to_user(self, component, message):
+               for logger in self._loggers:
+                       logger.log_message(component, message)
+
+       def add_logger(self, logger):
+               self._loggers.append(logger)
+
+       def remove_logger(self, logger):
+               self._loggers.remove(logger)
+
+       @property
+       def _channel_manager(self):
+               return self.__channelManager
 
+       @misc_utils.log_exception(_moduleLogger)
        def Connect(self):
                """
                For org.freedesktop.telepathy.Connection
                """
+               if self.__session is None:
+                       self.__session = gvoice.session.Session(
+                               cookiePath = os.path.join(constants._data_path_, "%s.cookies" % self.__accountName),
+                               defaults = {
+                                       "contacts": (self.__options.contactsPollPeriodInHours, "hours"),
+                                       "voicemail": (self.__options.voicemailPollPeriodInMinutes, "minutes"),
+                                       "texts": (self.__options.textsPollPeriodInMinutes, "minutes"),
+                               },
+                       )
+
+               if self._status != telepathy.CONNECTION_STATUS_DISCONNECTED:
+                       _moduleLogger.info("Attempting connect when not disconnected")
+                       return
                _moduleLogger.info("Connecting...")
                self.StatusChanged(
                        telepathy.CONNECTION_STATUS_CONNECTING,
                        telepathy.CONNECTION_STATUS_REASON_REQUESTED
                )
+               self._timedDisconnect.stop()
+               self.session.login(
+                       self.__credentials[0],
+                       self.__credentials[1],
+                       self._on_login,
+                       self._on_login_error,
+               )
+
+       @misc_utils.log_exception(_moduleLogger)
+       def _on_login(self, *args):
+               _moduleLogger.info("Connected, setting up...")
                try:
-                       self.session.login(*self._credentials)
-                       self.session.backend.set_callback_number(self._callbackNumber)
-               except gvoice.backend.NetworkError, e:
-                       _moduleLogger.exception("Connection Failed")
-                       self.StatusChanged(
-                               telepathy.CONNECTION_STATUS_DISCONNECTED,
-                               telepathy.CONNECTION_STATUS_REASON_NETWORK_ERROR
-                       )
-               except Exception, e:
-                       _moduleLogger.exception("Connection Failed")
-                       self.StatusChanged(
-                               telepathy.CONNECTION_STATUS_DISCONNECTED,
-                               telepathy.CONNECTION_STATUS_REASON_AUTHENTICATION_FAILED
-                       )
+                       self.session.load(self.__cachePath)
+
+                       for plumber in self._plumbing:
+                               plumber.start()
+                       if not self.__callbackNumberParameter:
+                               callback = gvoice.backend.get_sane_callback(
+                                       self.session.backend
+                               )
+                               self.__callbackNumberParameter = misc_utils.normalize_number(callback)
+                       self.session.backend.set_callback_number(self.__callbackNumberParameter)
+
+                       subscribeHandle = self.get_handle_by_name(telepathy.HANDLE_TYPE_LIST, "subscribe")
+                       subscribeProps = self.generate_props(telepathy.CHANNEL_TYPE_CONTACT_LIST, subscribeHandle, False)
+                       self.__channelManager.channel_for_props(subscribeProps, signal=True)
+               except Exception:
+                       _moduleLogger.exception("Setup failed")
+                       self.disconnect(telepathy.CONNECTION_STATUS_REASON_AUTHENTICATION_FAILED)
+                       return
+
+               _moduleLogger.info("Connected and set up")
+               self.StatusChanged(
+                       telepathy.CONNECTION_STATUS_CONNECTED,
+                       telepathy.CONNECTION_STATUS_REASON_REQUESTED
+               )
+
+       @misc_utils.log_exception(_moduleLogger)
+       def _on_login_error(self, error):
+               _moduleLogger.error(error)
+               if isinstance(error, StopIteration):
+                       pass
+               elif isinstance(error, gvoice.backend.NetworkError):
+                       self.disconnect(telepathy.CONNECTION_STATUS_REASON_NETWORK_ERROR)
                else:
-                       _moduleLogger.info("Connected")
-                       self.StatusChanged(
-                               telepathy.CONNECTION_STATUS_CONNECTED,
-                               telepathy.CONNECTION_STATUS_REASON_REQUESTED
-                       )
+                       self.disconnect(telepathy.CONNECTION_STATUS_REASON_AUTHENTICATION_FAILED)
 
+       @misc_utils.log_exception(_moduleLogger)
        def Disconnect(self):
                """
                For org.freedesktop.telepathy.Connection
-               @bug Not properly logging out.  Cookie files need to be per connection and removed
                """
-               _moduleLogger.info("Disconnecting")
-               try:
-                       self.session.logout()
-                       _moduleLogger.info("Disconnected")
-               except Exception:
-                       _moduleLogger.exception("Disconnecting Failed")
-               self.StatusChanged(
-                       telepathy.CONNECTION_STATUS_DISCONNECTED,
-                       telepathy.CONNECTION_STATUS_REASON_REQUESTED
-               )
+               _moduleLogger.info("Kicking off disconnect")
+               self.disconnect(telepathy.CONNECTION_STATUS_REASON_REQUESTED)
 
+       @misc_utils.log_exception(_moduleLogger)
        def RequestChannel(self, type, handleType, handleId, suppressHandler):
                """
                For org.freedesktop.telepathy.Connection
@@ -129,62 +303,57 @@ class TheOneRingConnection(telepathy.server.Connection):
                @returns DBus object path for the channel created or retrieved
                """
                self.check_connected()
+               self.check_handle(handleType, handleId)
 
-               channel = None
-               channelManager = self._channelManager
-               handle = self.handle(handleType, handleId)
-
-               if type == telepathy.CHANNEL_TYPE_CONTACT_LIST:
-                       _moduleLogger.info("RequestChannel ContactList")
-                       channel = channelManager.channel_for_list(handle, suppressHandler)
-               elif type == telepathy.CHANNEL_TYPE_TEXT:
-                       _moduleLogger.info("RequestChannel Text")
-                       channel = channelManager.channel_for_text(handle, None, suppressHandler)
-               elif type == telepathy.CHANNEL_TYPE_STREAMED_MEDIA:
-                       _moduleLogger.info("RequestChannel Media")
-                       channel = channelManager.channel_for_text(handle, None, suppressHandler)
-               else:
-                       raise telepathy.NotImplemented("unknown channel type %s" % type)
+               h = self.get_handle_by_id(handleType, handleId) if handleId != 0 else None
+               props = self.generate_props(type, h, suppressHandler)
+               self._validate_handle(props)
 
-               _moduleLogger.info("RequestChannel Object Path: %s" % channel._object_path)
-               return channel._object_path
+               chan = self.__channelManager.channel_for_props(props, signal=True)
+               path = chan._object_path
+               _moduleLogger.info("RequestChannel Object Path (%s): %s" % (type.rsplit(".", 1)[-1], path))
+               return path
 
-       def RequestHandles(self, handleType, names, sender):
-               """
-               For org.freedesktop.telepathy.Connection
-               """
-               self.check_connected()
-               self.check_handle_type(handleType)
-
-               handles = []
-               for name in names:
-                       name = name.encode('utf-8')
-                       if handleType == telepathy.HANDLE_TYPE_CONTACT:
-                               _moduleLogger.info("RequestHandles Contact: %s" % name)
-                               h = self._create_contact_handle(name)
-                       elif handleType == telepathy.HANDLE_TYPE_LIST:
-                               # Support only server side (immutable) lists
-                               _moduleLogger.info("RequestHandles List: %s" % name)
-                               h = handle.create_handle(self, 'list', name)
-                       else:
-                               raise telepathy.NotAvailable('Handle type unsupported %d' % handleType)
-                       handles.append(h.id)
-                       self.add_client_handle(h, sender)
-               return handles
-
-       def _create_contact_handle(self, name):
-               requestedContactId = name
-
-               contacts = self.session.addressbook.get_contacts()
-               contactsFound = [
-                       contactId for contactId in contacts
-                       if contactId == requestedContactId
-               ]
+       def generate_props(self, channelType, handleObj, suppressHandler, initiatorHandle=None):
+               targetHandle = 0 if handleObj is None else handleObj.get_id()
+               targetHandleType = telepathy.HANDLE_TYPE_NONE if handleObj is None else handleObj.get_type()
+               props = {
+                       telepathy.CHANNEL_INTERFACE + '.ChannelType': channelType,
+                       telepathy.CHANNEL_INTERFACE + '.TargetHandle': targetHandle,
+                       telepathy.CHANNEL_INTERFACE + '.TargetHandleType': targetHandleType,
+                       telepathy.CHANNEL_INTERFACE + '.Requested': suppressHandler
+               }
 
-               if 0 < len(contactsFound):
-                       contactId = contactsFound[0]
-                       if len(contactsFound) != 1:
-                               _moduleLogger.error("Contact ID was not unique: %s for %s" % (contactId, ))
-               else:
-                       contactId = requestedContactId
-               h = handle.create_handle(self, 'contact', contactId)
+               if initiatorHandle is not None:
+                       props[telepathy.CHANNEL_INTERFACE + '.InitiatorHandle'] = initiatorHandle.id
+
+               return props
+
+       def disconnect(self, reason):
+               _moduleLogger.info("Disconnecting")
+
+               self._timedDisconnect.stop()
+
+               # Not having the disconnect first can cause weird behavior with clients
+               # including not being able to reconnect or even crashing
+               self.StatusChanged(
+                       telepathy.CONNECTION_STATUS_DISCONNECTED,
+                       reason,
+               )
+
+               for plumber in self._plumbing:
+                       plumber.stop()
+
+               self.__channelManager.close()
+               self.manager.disconnected(self)
+
+               self.session.save(self.__cachePath)
+               self.session.shutdown()
+               self.session.close()
+
+               # In case one of the above items takes too long (which it should never
+               # do), we leave the starting of the shutdown-on-idle counter to the
+               # very end
+               self.manager.disconnect_completed()
+
+               _moduleLogger.info("Disconnected")