Providing focus to the lists for faster search
[gc-dialer] / src / session.py
index 03e9449..8dbdba0 100644 (file)
@@ -3,6 +3,7 @@ from __future__ import with_statement
 import os
 import time
 import datetime
+import contextlib
 import logging
 
 try:
@@ -23,6 +24,15 @@ import constants
 _moduleLogger = logging.getLogger(__name__)
 
 
+@contextlib.contextmanager
+def notify_busy(log, message):
+       log.push_busy(message)
+       try:
+               yield
+       finally:
+               log.pop(message)
+
+
 class _DraftContact(object):
 
        def __init__(self, title, description, numbersWithDescriptions):
@@ -44,23 +54,25 @@ class Draft(QtCore.QObject):
 
        recipientsChanged = QtCore.pyqtSignal()
 
-       def __init__(self, pool, backend):
+       def __init__(self, pool, backend, errorLog):
                QtCore.QObject.__init__(self)
+               self._errorLog = errorLog
                self._contacts = {}
                self._pool = pool
                self._backend = backend
 
        def send(self, text):
-               assert 0 < len(self._contacts)
-               numbers = [contact.selectedNumber for contact in self._contacts.itervalues()]
+               assert 0 < len(self._contacts), "No contacts selected"
+               numbers = [misc_utils.make_ugly(contact.selectedNumber) for contact in self._contacts.itervalues()]
                le = concurrent.AsyncLinearExecution(self._pool, self._send)
                le.start(numbers, text)
 
        def call(self):
-               assert len(self._contacts) == 1
+               assert len(self._contacts) == 1, "Must select 1 and only 1 contact"
                (contact, ) = self._contacts.itervalues()
+               number = misc_utils.make_ugly(contact.selectedNumber)
                le = concurrent.AsyncLinearExecution(self._pool, self._call)
-               le.start(contact.selectedNumber)
+               le.start(number)
 
        def cancel(self):
                le = concurrent.AsyncLinearExecution(self._pool, self._cancel)
@@ -77,7 +89,7 @@ class Draft(QtCore.QObject):
                self.recipientsChanged.emit()
 
        def remove_contact(self, contactId):
-               assert contactId in self._contacts
+               assert contactId in self._contacts, "Contact missing"
                del self._contacts[contactId]
                self.recipientsChanged.emit()
 
@@ -102,7 +114,7 @@ class Draft(QtCore.QObject):
        def set_selected_number(self, cid, number):
                # @note I'm lazy, this isn't firing any kind of signal since only one
                # controller right now and that is the viewer
-               assert number in (nWD[0] for nWD in self._contacts[cid].numbers)
+               assert number in (nWD[0] for nWD in self._contacts[cid].numbers), "Number not selectable"
                self._contacts[cid].selectedNumber = number
 
        def clear(self):
@@ -114,11 +126,12 @@ class Draft(QtCore.QObject):
        def _send(self, numbers, text):
                self.sendingMessage.emit()
                try:
-                       yield (
-                               self._backend[0].send_sms,
-                               (numbers, text),
-                               {},
-                       )
+                       with notify_busy(self._errorLog, "Sending Text"):
+                               yield (
+                                       self._backend[0].send_sms,
+                                       (numbers, text),
+                                       {},
+                               )
                        self.sentMessage.emit()
                        self.clear()
                except Exception, e:
@@ -127,11 +140,12 @@ class Draft(QtCore.QObject):
        def _call(self, number):
                self.calling.emit()
                try:
-                       yield (
-                               self._backend[0].call,
-                               (number, ),
-                               {},
-                       )
+                       with notify_busy(self._errorLog, "Calling"):
+                               yield (
+                                       self._backend[0].call,
+                                       (number, ),
+                                       {},
+                               )
                        self.called.emit()
                        self.clear()
                except Exception, e:
@@ -140,11 +154,12 @@ class Draft(QtCore.QObject):
        def _cancel(self):
                self.cancelling.emit()
                try:
-                       yield (
-                               self._backend[0].cancel,
-                               (),
-                               {},
-                       )
+                       with notify_busy(self._errorLog, "Cancelling"):
+                               yield (
+                                       self._backend[0].cancel,
+                                       (),
+                                       {},
+                               )
                        self.cancelled.emit()
                except Exception, e:
                        self.error.emit(str(e))
@@ -152,6 +167,8 @@ class Draft(QtCore.QObject):
 
 class Session(QtCore.QObject):
 
+       # @todo Somehow add support for csv contacts
+
        stateChange = QtCore.pyqtSignal(str)
        loggedOut = QtCore.pyqtSignal()
        loggedIn = QtCore.pyqtSignal()
@@ -168,20 +185,21 @@ class Session(QtCore.QObject):
        LOGGINGIN_STATE = "logging in"
        LOGGEDIN_STATE = "logged in"
 
-       _OLDEST_COMPATIBLE_FORMAT_VERSION = misc_utils.parse_version("1.2.0")
+       _OLDEST_COMPATIBLE_FORMAT_VERSION = misc_utils.parse_version("1.1.90")
 
        _LOGGEDOUT_TIME = -1
        _LOGGINGIN_TIME = 0
 
-       def __init__(self, cachePath = None):
+       def __init__(self, errorLog, cachePath = None):
                QtCore.QObject.__init__(self)
+               self._errorLog = errorLog
                self._pool = qore_utils.AsyncPool()
                self._backend = []
                self._loggedInTime = self._LOGGEDOUT_TIME
                self._loginOps = []
                self._cachePath = cachePath
                self._username = None
-               self._draft = Draft(self._pool, self._backend)
+               self._draft = Draft(self._pool, self._backend, self._errorLog)
 
                self._contacts = {}
                self._contactUpdateTime = datetime.datetime(1971, 1, 1)
@@ -204,8 +222,8 @@ class Session(QtCore.QObject):
                return self._draft
 
        def login(self, username, password):
-               assert self.state == self.LOGGEDOUT_STATE
-               assert username != ""
+               assert self.state == self.LOGGEDOUT_STATE, "Can only log-in when logged out (currently %s" % self.state
+               assert username != "", "No username specified"
                if self._cachePath is not None:
                        cookiePath = os.path.join(self._cachePath, "%s.cookies" % username)
                else:
@@ -221,21 +239,21 @@ class Session(QtCore.QObject):
                le.start(username, password)
 
        def logout(self):
-               assert self.state != self.LOGGEDOUT_STATE
+               assert self.state != self.LOGGEDOUT_STATE, "Can only logout if logged in (currently %s" % self.state
                self._pool.stop()
                self._loggedInTime = self._LOGGEDOUT_TIME
                self._backend[0].persist()
                self._save_to_cache()
 
        def clear(self):
-               assert self.state == self.LOGGEDOUT_STATE
+               assert self.state == self.LOGGEDOUT_STATE, "Can only clear when logged out (currently %s" % self.state
                self._backend[0].logout()
                del self._backend[0]
                self._clear_cache()
                self._draft.clear()
 
        def logout_and_clear(self):
-               assert self.state != self.LOGGEDOUT_STATE
+               assert self.state != self.LOGGEDOUT_STATE, "Can only logout if logged in (currently %s" % self.state
                self._pool.stop()
                self._loggedInTime = self._LOGGEDOUT_TIME
                self.clear()
@@ -287,14 +305,15 @@ class Session(QtCore.QObject):
        def _set_dnd(self, dnd):
                # I'm paranoid about our state geting out of sync so we set no matter
                # what but act as if we have the cannonical state
-               assert self.state == self.LOGGEDIN_STATE
+               assert self.state == self.LOGGEDIN_STATE, "DND requires being logged in (currently %s" % self.state
                oldDnd = self._dnd
                try:
-                       yield (
-                               self._backend[0].set_dnd,
-                               (dnd, ),
-                               {},
-                       )
+                       with notify_busy(self._errorLog, "Setting DND Status"):
+                               yield (
+                                       self._backend[0].set_dnd,
+                                       (dnd, ),
+                                       {},
+                               )
                except Exception, e:
                        self.error.emit(str(e))
                        return
@@ -322,7 +341,7 @@ class Session(QtCore.QObject):
        def _set_callback_number(self, callback):
                # I'm paranoid about our state geting out of sync so we set no matter
                # what but act as if we have the cannonical state
-               assert self.state == self.LOGGEDIN_STATE
+               assert self.state == self.LOGGEDIN_STATE, "Callbacks configurable only when logged in (currently %s" % self.state
                oldCallback = self._callback
                try:
                        yield (
@@ -338,58 +357,66 @@ class Session(QtCore.QObject):
                        self.callbackNumberChanged.emit(self._callback)
 
        def _login(self, username, password):
-               self._loggedInTime = self._LOGGINGIN_TIME
-               self.stateChange.emit(self.LOGGINGIN_STATE)
-               finalState = self.LOGGEDOUT_STATE
-               try:
+               with notify_busy(self._errorLog, "Logging In"):
+                       self._loggedInTime = self._LOGGINGIN_TIME
+                       self.stateChange.emit(self.LOGGINGIN_STATE)
+                       finalState = self.LOGGEDOUT_STATE
                        isLoggedIn = False
-
-                       if not isLoggedIn and self._backend[0].is_quick_login_possible():
-                               isLoggedIn = yield (
-                                       self._backend[0].is_authed,
-                                       (),
-                                       {},
-                               )
-                               if isLoggedIn:
-                                       _moduleLogger.info("Logged in through cookies")
-                               else:
-                                       # Force a clearing of the cookies
-                                       yield (
-                                               self._backend[0].logout,
+                       try:
+                               if not isLoggedIn and self._backend[0].is_quick_login_possible():
+                                       isLoggedIn = yield (
+                                               self._backend[0].is_authed,
                                                (),
                                                {},
                                        )
+                                       if isLoggedIn:
+                                               _moduleLogger.info("Logged in through cookies")
+                                       else:
+                                               # Force a clearing of the cookies
+                                               yield (
+                                                       self._backend[0].logout,
+                                                       (),
+                                                       {},
+                                               )
+
+                               if not isLoggedIn:
+                                       isLoggedIn = yield (
+                                               self._backend[0].login,
+                                               (username, password),
+                                               {},
+                                       )
+                                       if isLoggedIn:
+                                               _moduleLogger.info("Logged in through credentials")
 
-                       if not isLoggedIn:
-                               isLoggedIn = yield (
-                                       self._backend[0].login,
-                                       (username, password),
-                                       {},
-                               )
                                if isLoggedIn:
-                                       _moduleLogger.info("Logged in through credentials")
-
-                       if isLoggedIn:
-                               self._loggedInTime = int(time.time())
-                               oldUsername = self._username
-                               self._username = username
-                               finalState = self.LOGGEDIN_STATE
-                               self.loggedIn.emit()
-                               if oldUsername != self._username:
-                                       needOps = not self._load()
+                                       self._loggedInTime = int(time.time())
+                                       oldUsername = self._username
+                                       self._username = username
+                                       finalState = self.LOGGEDIN_STATE
+                                       if oldUsername != self._username:
+                                               needOps = not self._load()
+                                       else:
+                                               needOps = True
+
+                                       self.loggedIn.emit()
+
+                                       if needOps:
+                                               loginOps = self._loginOps[:]
+                                       else:
+                                               loginOps = []
+                                       del self._loginOps[:]
+                                       for asyncOp in loginOps:
+                                               asyncOp.start()
                                else:
-                                       needOps = True
-                               if needOps:
-                                       loginOps = self._loginOps[:]
-                               else:
-                                       loginOps = []
-                               del self._loginOps[:]
-                               for asyncOp in loginOps:
-                                       asyncOp.start()
-               except Exception, e:
-                       self.error.emit(str(e))
-               finally:
-                       self.stateChange.emit(finalState)
+                                       self._loggedInTime = self._LOGGEDOUT_TIME
+                                       self.error.emit("Error logging in")
+                       except Exception, e:
+                               self._loggedInTime = self._LOGGEDOUT_TIME
+                               self.error.emit(str(e))
+                       finally:
+                               self.stateChange.emit(finalState)
+                       if isLoggedIn and self._callback:
+                               self.set_callback_number(self._callback)
 
        def _load(self):
                updateContacts = len(self._contacts) != 0
@@ -519,11 +546,12 @@ class Session(QtCore.QObject):
 
        def _update_contacts(self):
                try:
-                       self._contacts = yield (
-                               self._backend[0].get_contacts,
-                               (),
-                               {},
-                       )
+                       with notify_busy(self._errorLog, "Updating Contacts"):
+                               self._contacts = yield (
+                                       self._backend[0].get_contacts,
+                                       (),
+                                       {},
+                               )
                except Exception, e:
                        self.error.emit(str(e))
                        return
@@ -532,11 +560,12 @@ class Session(QtCore.QObject):
 
        def _update_messages(self):
                try:
-                       self._messages = yield (
-                               self._backend[0].get_messages,
-                               (),
-                               {},
-                       )
+                       with notify_busy(self._errorLog, "Updating Messages"):
+                               self._messages = yield (
+                                       self._backend[0].get_messages,
+                                       (),
+                                       {},
+                               )
                except Exception, e:
                        self.error.emit(str(e))
                        return
@@ -545,11 +574,12 @@ class Session(QtCore.QObject):
 
        def _update_history(self):
                try:
-                       self._history = yield (
-                               self._backend[0].get_recent,
-                               (),
-                               {},
-                       )
+                       with notify_busy(self._errorLog, "Updating History"):
+                               self._history = yield (
+                                       self._backend[0].get_recent,
+                                       (),
+                                       {},
+                               )
                except Exception, e:
                        self.error.emit(str(e))
                        return
@@ -577,7 +607,7 @@ class Session(QtCore.QObject):
                        self._push_login_op(op)
 
        def _push_login_op(self, asyncOp):
-               assert self.state != self.LOGGEDIN_STATE
+               assert self.state != self.LOGGEDIN_STATE, "Can only queue work when logged out"
                if asyncOp in self._loginOps:
                        _moduleLogger.info("Skipping queueing duplicate op: %r" % asyncOp)
                        return