Some error banner delays fixed.
[jenirok] / src / daemon / calllistener.cpp
index 93fb100..4307347 100644 (file)
  */
 
 #include <QtCore/QDebug>
-#include <QtSql/QSqlQuery>
+#include <QtCore/QTimer>
 #include "calllistener.h"
 #include "settings.h"
+#include "cache.h"
+#include "contactmanager.h"
+#include "connectionmanager.h"
 #include "db.h"
 
 namespace
 {
-       const QString CALL_SERVICE_NAME = "com.nokia.csd";
-       const QString CALL_SERVICE_PATH = "/com/nokia/csd/call";
-       const QString CALL_SERVICE_INTERFACE = "com.nokia.csd.Call";
-       const QString CALL_SERVICE_INSTANCE_NAME = "com.nokia.csd.Call.Instance";
-       const QString CALL_SIGNAL_INCOMING = "Coming";
-       const QString CALL_SIGNAL_RELEASE = "Release";
-       const QString CALL_SIGNAL_TERMINATED = "Terminated";
+    const QString CALL_SERVICE_NAME = "com.nokia.csd";
+    const QString CALL_SERVICE_PATH = "/com/nokia/csd/call";
+    const QString CALL_SERVICE_INTERFACE = "com.nokia.csd.Call";
+    const QString CALL_SERVICE_INSTANCE_NAME = "com.nokia.csd.Call.Instance";
+    const QString CALL_SIGNAL_INCOMING = "Coming";
+    const QString CALL_SIGNAL_RELEASE = "Release";
+    const QString CALL_SIGNAL_TERMINATED = "Terminated";
 }
 
 QDBusConnection CallListener::systemBus_ = QDBusConnection::systemBus();
 
-CallListener::CallListener(): eniro_(0), contactManager_(0), box_(0), label_(0)
+CallListener::CallListener(): eniro_(0),
+closeConnection_(false), initialized_(false), box_(0), label_(0),
+retries_(-1), site_(Eniro::FI), timer_(0)
 {
 }
 
 CallListener::~CallListener()
 {
-       end();
+    end();
+    DB::removeDatabase();
 }
 
-void CallListener::begin()
+bool CallListener::begin()
 {
-       systemBus_.connect(CALL_SERVICE_NAME,
-                                  CALL_SERVICE_PATH,
-                                  CALL_SERVICE_INTERFACE,
-                                  CALL_SIGNAL_INCOMING,
-                                  this,
-                                  SLOT(incomingCall(QDBusObjectPath, QString)));
-
-       systemBus_.connect(CALL_SERVICE_NAME,
-                                      CALL_SERVICE_PATH,
-                                      CALL_SERVICE_INTERFACE,
-                                      CALL_SIGNAL_RELEASE,
-                                      this,
-                                      SLOT(callTerminate()));
+    if(Settings::instance()->getConnectionType() == Settings::ALWAYS_ASK)
+    {
+        qDebug() << "Bad connection settings, unable to start";
+        return false;
+    }
 
-       contactManager_ = new ContactManager;
+    systemBus_.connect(CALL_SERVICE_NAME,
+                       CALL_SERVICE_PATH,
+                       CALL_SERVICE_INTERFACE,
+                       CALL_SIGNAL_INCOMING,
+                       this,
+                       SLOT(incomingCall(QDBusObjectPath, QString)));
 
-       eniro_ = new Eniro(Eniro::stringToSite(Settings::instance()->get("site")));
+    systemBus_.connect(CALL_SERVICE_NAME,
+                       CALL_SERVICE_PATH,
+                       CALL_SERVICE_INTERFACE,
+                       CALL_SIGNAL_RELEASE,
+                       this,
+                       SLOT(callTerminate()));
 
-       eniro_->setMaxResults(1);
-       eniro_->setFindNumber(false);
+    site_ = Eniro::stringToSite(Settings::instance()->get("site"));
 
-       connect(eniro_, SIGNAL(requestFinished(QVector <Eniro::Result> const&,
-                       Eniro::SearchDetails const&, bool)),
-                       this, SLOT(requestFinished(QVector <Eniro::Result> const&,
-                       Eniro::SearchDetails const&, bool)));
+    qDebug() << "Starting...";
 
-       box_ = new InformationBox();
-       label_ = new QLabel("", box_);
-       label_->setMargin(10);
-       box_->setWidget(label_);
+    return true;
 
 }
 
 void CallListener::end()
 {
-       systemBus_.disconnect(CALL_SERVICE_NAME,
-                                          CALL_SERVICE_PATH,
-                                          CALL_SERVICE_INTERFACE,
-                                          CALL_SIGNAL_INCOMING,
-                                          this,
-                                          SLOT(incomingCall(QDBusObjectPath, QString)));
-
-       systemBus_.disconnect(CALL_SERVICE_NAME,
-                                              CALL_SERVICE_PATH,
-                                              CALL_SERVICE_INTERFACE,
-                                              CALL_SIGNAL_RELEASE,
-                                              this,
-                                              SLOT(callTerminate()));
+    systemBus_.disconnect(CALL_SERVICE_NAME,
+                          CALL_SERVICE_PATH,
+                          CALL_SERVICE_INTERFACE,
+                          CALL_SIGNAL_INCOMING,
+                          this,
+                          SLOT(incomingCall(QDBusObjectPath, QString)));
+
+    systemBus_.disconnect(CALL_SERVICE_NAME,
+                          CALL_SERVICE_PATH,
+                          CALL_SERVICE_INTERFACE,
+                          CALL_SIGNAL_RELEASE,
+                          this,
+                          SLOT(callTerminate()));
+
+    searchClose();
 
-       delete eniro_;
-       eniro_ = 0;
-       delete box_;
-       box_ = 0;
-       delete label_;
-       label_ = 0;
 }
 
 void CallListener::search(Eniro::SearchDetails const& details)
 {
-       label_->setText(tr("Searching..."));
-       box_->show();
+    qDebug() << "Search called";
+
+    searchInit();
+
+    Eniro::Result result;
+
+    if(Cache::instance().findItem(details.query, result))
+    {
 
-       DB::connect();
+        qDebug() << "Found from cache";
 
-       QSqlQuery query;
-       query.prepare("SELECT name, street, city FROM cache WHERE number = :number");
-       query.bindValue(":number", details.query);
+        showDelayedResult(createResult(result.name,
+                                       result.street,
+                                       result.city), BANNER_DELAY);
+    }
+    else
+    {
+        retries_ = 0;
+        currentSearch_ = details.query;
+
+        if(!handleConnection())
+        {
+            qDebug() << "Unable to connect";
+            return;
+        }
 
-       if(query.exec() && query.next())
-       {
-               showResult(createResult(query.value(0).toString(),
-                               query.value(1).toString(),
-                               query.value(2).toString()));
+        showDelayedResult(tr("Searching..."), BANNER_DELAY);
 
-       }
-       else
-       {
-               eniro_->search(details);
-       }
+        qDebug() << "Starting to search...";
 
-       DB::disconnect();
+        eniro_->search(details);
+    }
 
 }
 
 void CallListener::requestFinished(QVector <Eniro::Result> const& results,
-                                          Eniro::SearchDetails const& details,
-                                          bool error)
+                                   Eniro::SearchDetails const& details,
+                                   bool error)
 {
-    qDebug() << "Found: " << results.size();
-
     // If box is not visible, the call must have been terminated already
-    if(!box_->isVisible())
+    if(!initialized_ || !box_->isVisible())
     {
-       return;
+        return;
     }
 
     QString message;
@@ -147,93 +152,347 @@ void CallListener::requestFinished(QVector <Eniro::Result> const& results,
     if(error)
     {
         qDebug() << "Error: " << eniro_->errorString();
-        message = tr("Search failed:") + " " + eniro_->errorString();
+
+        if(retries_ < SEARCH_RETRIES && retries_ >= 0)
+        {
+            retries_++;
+            eniro_->search(Eniro::SearchDetails(currentSearch_));
+            return;
+        }
+        else
+        {
+            timedMessage_ = "";
+            QString errorString;
+            Eniro::Error error = eniro_->error();
+
+            switch(error)
+            {
+            case Eniro::TIMEOUT:
+                errorString = tr("Request timed out");
+                break;
+            default:
+                errorString = eniro_->errorString();
+                break;
+            }
+
+            showError(tr("Searching failed:") + " " + errorString + ".");
+        }
     }
-    else if(results.size() == 0)
+    else
     {
-       message = tr("Phone number was not found");
+        timedMessage_ = "";
+
+        if(results.size() == 0)
+        {
+            message = tr("Phone number was not found");
+            showResult(message);
+        }
+        else
+        {
+            message = createResult(results.at(0).name, results.at(0).street,
+                                   results.at(0).city);
+            showResult(message);
+            Eniro::Result result = results.at(0);
+            result.number = details.query;
+            Cache::instance().addItem(result);
+        }
     }
-    else
+
+    retries_ = -1;
+    currentSearch_ = "";
+
+    if(closeConnection_)
     {
-       message = createResult(results.at(0).name, results.at(0).street, results.at(0).city);
-       QSqlQuery query;
+        ConnectionManager cm;
+        cm.disconnect(true);
+        closeConnection_ = false;
+    }
+}
 
-       DB::connect();
+QString CallListener::createResult(QString const& name, QString const& street, QString const& city)
+{
+    QString result = "<b>" + name + "</b>";
 
-       query.prepare("INSERT INTO cache(number, name, street, city) VALUES(:number, :name, :street, :city)");
-       query.bindValue(":number", details.query);
-       query.bindValue(":name", results.at(0).name);
-       query.bindValue(":street", results.at(0).street);
-       query.bindValue(":city", results.at(0).city);
+    if(!street.isEmpty() || !city.isEmpty())
+    {
+        result += "<br>";
 
-       if(!query.exec())
-       {
-               qDebug() << "Unable to save cache";
-       }
+        if(!street.isEmpty())
+        {
+            result += street + ", ";
+        }
 
-       QString cacheSize = Settings::instance()->get("cache_size");
+        result += city;
+    }
 
-       // Delete old entries from cache
-       if(cacheSize.toInt() > 0)
-       {
-               if(!query.exec("DELETE c1 FROM cache AS c1 LEFT JOIN (SELECT id FROM cache ORDER BY id DESC LIMIT " + cacheSize + ") AS c2 ON c1.id = c2.id WHERE c2.id IS NULL"))
-               {
-                       qDebug() << "Unable to delete old cache entries";
-               }
-       }
+    return result;
+}
 
-       DB::disconnect();
+void CallListener::showResult(QString const& text)
+{
+    if(!initialized_)
+    {
+        return;
     }
 
-    showResult(message);
+    label_->setText("<font color='black'>" + text + "</font>");
+
+    if(box_->isVisible())
+    {
+        box_->hide();
+    }
 
+    box_->show();
 }
 
-QString CallListener::createResult(QString const& name, QString const& street, QString const& city)
+void CallListener::incomingCall(QDBusObjectPath path, QString number)
 {
-       QString result = "<b>" + name + "</b>";
+    qDebug() << "Incoming: " << number;
 
-       if(!street.isEmpty() || !city.isEmpty())
-       {
-               result += "<br>";
+    ContactManager cm;
 
-               if(!street.isEmpty())
-               {
-                       result += street + ", ";
-               }
+    if(!cm.numberExists(number))
+    {
+        qDebug() << "Number doesn't exist";
 
-               result += city;
-       }
+        systemBus_.connect(CALL_SERVICE_NAME,
+                           path.path(),
+                           CALL_SERVICE_INSTANCE_NAME,
+                           CALL_SIGNAL_TERMINATED,
+                           this,
+                           SLOT(callTerminate()));
 
-       return result;
+        search(Eniro::SearchDetails(number));
+    }
+    else
+    {
+        qDebug() << "Number exists";
+    }
 }
 
-void CallListener::showResult(QString const& text)
+void CallListener::callTerminate()
 {
-       label_->setText(text);
-       box_->hide();
-       box_->show();
+    if(box_ && box_->isVisible())
+    {
+        box_->hide();
+    }
+
+    if(closeConnection_)
+    {
+        ConnectionManager cm;
+        cm.disconnect(true);
+        closeConnection_ = false;
+    }
+
+    searchClose();
 }
 
-void CallListener::incomingCall(QDBusObjectPath path, QString number)
+void CallListener::showDelayedResult(QString const& text, int delay)
 {
-       qDebug() << number;
+    timedMessage_ = text;
+    QTimer::singleShot(delay, this, SLOT(showTimedMessage()));
+}
 
-       if(!contactManager_->numberExists(number))
-       {
+void CallListener::showTimedMessage()
+{
+    if(timedMessage_.size() == 0 || !initialized_)
+    {
+        return;
+    }
 
-               systemBus_.connect(CALL_SERVICE_NAME,
-                                  path.path(),
-                                  CALL_SERVICE_INSTANCE_NAME,
-                                  CALL_SIGNAL_TERMINATED,
-                                  this,
-                                  SLOT(callTerminate()));
+    showResult(timedMessage_);
 
-               search(Eniro::SearchDetails(number));
-       }
+    timedMessage_ = "";
 }
 
-void CallListener::callTerminate()
+void CallListener::searchInit()
+{
+    qDebug() << "Initializing search...";
+
+    if(initialized_)
+    {
+        qDebug() << "Already initialized";
+        return;
+    }
+
+    eniro_ = new Eniro(site_);
+    eniro_->setMaxResults(1);
+    eniro_->setFindNumber(false);
+    eniro_->setTimeout(REQUEST_TIMEOUT);
+
+    connect(eniro_, SIGNAL(requestFinished(QVector <Eniro::Result> const&,
+                                           Eniro::SearchDetails const&, bool)),
+                                           this, SLOT(requestFinished(QVector <Eniro::Result> const&,
+                                                                      Eniro::SearchDetails const&, bool)));
+    box_ = new InformationBox;
+    label_ = new QLabel("", box_);
+    label_->setMargin(8);
+    label_->setWordWrap(true);
+    box_->setWidget(label_);
+    initialized_ = true;
+}
+
+void CallListener::searchClose()
 {
-       box_->hide();
+    initialized_ = false;
+
+    qDebug() << "Closing search...";
+
+    if(eniro_)
+    {
+        disconnect(eniro_, SIGNAL(requestFinished(QVector <Eniro::Result> const&,
+                                                  Eniro::SearchDetails const&, bool)),
+                                                  this, SLOT(requestFinished(QVector <Eniro::Result> const&,
+                                                                             Eniro::SearchDetails const&, bool)));
+    }
+
+    delete eniro_;
+    eniro_ = 0;
+    delete box_;
+    box_ = 0;
+    label_ = 0;
+}
+
+bool CallListener::handleConnection()
+{
+    if(!initialized_)
+    {
+        return false;
+    }
+
+    ConnectionManager cm;
+
+    if(cm.isConnected())
+    {
+        closeConnection_ = false;
+        return true;
+    }
+
+    closeConnection_ = true;
+
+    Settings::ConnectionType configType = Settings::instance()->getConnectionType();
+
+    if(configType == Settings::ALWAYS_ASK)
+    {
+        showError(tr("Automatic connecting is not allowed by settings."), BANNER_DELAY);
+        return false;
+    }
+
+    showDelayedResult(tr("Connecting..."), BANNER_DELAY);
+
+    ConnectionManager::Connection best;
+
+    ConnectionManager::ConnectionType lookupType = ConnectionManager::NO_TYPE;
+
+    switch(configType)
+    {
+    case Settings::WLAN:
+        lookupType = ConnectionManager::WLAN;
+        break;
+    case Settings::GPRS:
+        lookupType = ConnectionManager::GPRS;
+        break;
+    default:
+        lookupType = ConnectionManager::NO_TYPE;
+        break;
+    }
+
+    int cretries = 0;
+
+    while(cretries < CONNECTION_LOOKUP_RETRIES)
+    {
+        if(!initialized_)
+        {
+            return false;
+        }
+
+        if(cm.getBestConnection(best, lookupType))
+        {
+            break;
+        }
+
+        qDebug() << "No connections found, retrying...";
+
+        cretries++;
+
+        sleep(WAIT_BETWEEN_RETRIES);
+
+    }
+
+    if(cretries >= CONNECTION_LOOKUP_RETRIES)
+    {
+        showError(tr("No available 3G or WLAN networks found."));
+        return false;
+    }
+
+    int retries = 0;
+
+    while(retries < CONNECT_RETRIES)
+    {
+        if(!initialized_)
+        {
+            return false;
+        }
+
+        sleep(WAIT_BETWEEN_RETRIES);
+
+        if(cm.connect(best.id))
+        {
+            break;
+        }
+        else if(cm.error() == ConnectionManager::INVALID_IAP)
+        {
+            showError(tr("Selected access point doesn't exist."));
+            return false;
+        }
+
+        qDebug() << "Unable to connect, retrying...";
+        retries++;
+
+    }
+
+    if(initialized_ && retries >= CONNECT_RETRIES)
+    {
+        showError(tr("Unable to connect to network."));
+        return false;
+    }
+
+    return initialized_;
+}
+
+void CallListener::showError(QString const& msg, int timeout)
+{
+    qDebug() << "Error: " << msg;
+    box_->setTimeout(ERROR_BANNER_TIMEOUT);
+
+    if(timeout)
+    {
+        showDelayedResult(msg, timeout);
+    }
+    else
+    {
+        showResult(msg);
+    }
+}
+
+void CallListener::timerEvent(QTimerEvent* event)
+{
+    Q_UNUSED(event);
+    killTimer(timer_);
+    timer_ = 0;
+}
+
+void CallListener::sleep(int ms)
+{
+    if(timer_)
+    {
+        killTimer(timer_);
+    }
+
+    timer_ = startTimer(ms);
+
+    while(timer_)
+    {
+        QCoreApplication::processEvents(QEventLoop::WaitForMoreEvents);
+    }
 }