Changed loading banner to show instantly when call is coming.
[jenirok] / src / daemon / calllistener.cpp
index 93fb100..7990f8a 100644 (file)
  */
 
 #include <QtCore/QDebug>
+#include <QtCore/QTimer>
 #include <QtSql/QSqlQuery>
+#include <QtSql/QSqlError>
 #include "calllistener.h"
 #include "settings.h"
-#include "db.h"
+#include "cache.h"
+#include "contactmanager.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), connectionManager_(0),
+closeConnection_(false), initialized_(false), box_(0), label_(0),
+retries_(-1), site_(Eniro::FI)
 {
 }
 
 CallListener::~CallListener()
 {
-       end();
+    end();
 }
 
 void 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_INCOMING,
+                       this,
+                       SLOT(incomingCall(QDBusObjectPath, QString)));
 
-       systemBus_.connect(CALL_SERVICE_NAME,
-                                      CALL_SERVICE_PATH,
-                                      CALL_SERVICE_INTERFACE,
-                                      CALL_SIGNAL_RELEASE,
-                                      this,
-                                      SLOT(callTerminate()));
+    systemBus_.connect(CALL_SERVICE_NAME,
+                       CALL_SERVICE_PATH,
+                       CALL_SERVICE_INTERFACE,
+                       CALL_SIGNAL_RELEASE,
+                       this,
+                       SLOT(callTerminate()));
 
-       contactManager_ = new ContactManager;
+    site_ = Eniro::stringToSite(Settings::instance()->get("site"));
+    Settings::close();
 
-       eniro_ = new Eniro(Eniro::stringToSite(Settings::instance()->get("site")));
-
-       eniro_->setMaxResults(1);
-       eniro_->setFindNumber(false);
-
-       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(10);
-       box_->setWidget(label_);
+    qDebug() << "Starting...";
 
 }
 
 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()));
-
-       delete eniro_;
-       eniro_ = 0;
-       delete box_;
-       box_ = 0;
-       delete label_;
-       label_ = 0;
+    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();
+
 }
 
 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;
+
+        showDelayedResult(tr("Searching..."), BANNER_DELAY);
 
-       if(query.exec() && query.next())
-       {
-               showResult(createResult(query.value(0).toString(),
-                               query.value(1).toString(),
-                               query.value(2).toString()));
+        if(!connectionManager_->isConnected())
+        {
+            connectionManager_->connect();
+            closeConnection_ = true;
+        }
+        else
+        {
+            closeConnection_ = false;
+        }
 
-       }
-       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 +148,185 @@ void CallListener::requestFinished(QVector <Eniro::Result> const& results,
     if(error)
     {
         qDebug() << "Error: " << eniro_->errorString();
-        message = tr("Search failed:") + " " + eniro_->errorString();
-    }
-    else if(results.size() == 0)
-    {
-       message = tr("Phone number was not found");
+
+        if(retries_ < NUMBER_OF_RETRIES && retries_ >= 0)
+        {
+            retries_++;
+            eniro_->search(Eniro::SearchDetails(currentSearch_));
+            return;
+        }
+        else
+        {
+            timedMessage_ = "";
+            message = tr("Search failed:") + " " + eniro_->errorString() + ".";
+            showResult(message);
+        }
     }
     else
     {
-       message = createResult(results.at(0).name, results.at(0).street, results.at(0).city);
-       QSqlQuery query;
-
-       DB::connect();
-
-       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(!query.exec())
-       {
-               qDebug() << "Unable to save cache";
-       }
-
-       QString cacheSize = Settings::instance()->get("cache_size");
-
-       // 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";
-               }
-       }
-
-       DB::disconnect();
+        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);
+        }
     }
 
-    showResult(message);
+    retries_ = -1;
+    currentSearch_ = "";
 
+    if(closeConnection_ && connectionManager_)
+    {
+        connectionManager_->disconnect(true);
+        closeConnection_ = false;
+    }
 }
 
 QString CallListener::createResult(QString const& name, QString const& street, QString const& city)
 {
-       QString result = "<b>" + name + "</b>";
+    QString result = "<b>" + name + "</b>";
 
-       if(!street.isEmpty() || !city.isEmpty())
-       {
-               result += "<br>";
+    if(!street.isEmpty() || !city.isEmpty())
+    {
+        result += "<br>";
 
-               if(!street.isEmpty())
-               {
-                       result += street + ", ";
-               }
+        if(!street.isEmpty())
+        {
+            result += street + ", ";
+        }
 
-               result += city;
-       }
+        result += city;
+    }
 
-       return result;
+    return result;
 }
 
 void CallListener::showResult(QString const& text)
 {
-       label_->setText(text);
-       box_->hide();
-       box_->show();
+    if(!initialized_)
+    {
+        return;
+    }
+
+    label_->setText("<font color='black'>" + text + "</font>");
+
+    if(box_->isVisible())
+    {
+        box_->hide();
+    }
+
+    box_->show();
 }
 
 void CallListener::incomingCall(QDBusObjectPath path, QString number)
 {
-       qDebug() << number;
+    qDebug() << "Incoming: " << number;
 
-       if(!contactManager_->numberExists(number))
-       {
+    ContactManager cm;
 
-               systemBus_.connect(CALL_SERVICE_NAME,
-                                  path.path(),
-                                  CALL_SERVICE_INSTANCE_NAME,
-                                  CALL_SIGNAL_TERMINATED,
-                                  this,
-                                  SLOT(callTerminate()));
+    if(!cm.numberExists(number))
+    {
+        qDebug() << "Number doesn't exist";
+
+        systemBus_.connect(CALL_SERVICE_NAME,
+                           path.path(),
+                           CALL_SERVICE_INSTANCE_NAME,
+                           CALL_SIGNAL_TERMINATED,
+                           this,
+                           SLOT(callTerminate()));
 
-               search(Eniro::SearchDetails(number));
-       }
+        search(Eniro::SearchDetails(number));
+    }
+    else
+    {
+        qDebug() << "Number exists";
+    }
 }
 
 void CallListener::callTerminate()
 {
-       box_->hide();
+    if(initialized_ && box_ && box_->isVisible())
+    {
+        box_->hide();
+    }
+
+    if(closeConnection_ && connectionManager_)
+    {
+        connectionManager_->disconnect(true);
+        closeConnection_ = false;
+    }
+
+    searchClose();
+}
+
+void CallListener::showDelayedResult(QString const& text, int delay)
+{
+    timedMessage_ = text;
+    QTimer::singleShot(delay, this, SLOT(showTimedMessage()));
+}
+
+void CallListener::showTimedMessage()
+{
+    if(timedMessage_.size() == 0 || !initialized_)
+    {
+        return;
+    }
+
+    showResult(timedMessage_);
+
+    timedMessage_ = "";
+}
+
+void CallListener::searchInit()
+{
+    qDebug() << "Initializing search...";
+
+    connectionManager_ = new ConnectionManager;
+
+    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);
+    box_->setWidget(label_);
+    initialized_ = true;
+}
+
+void CallListener::searchClose()
+{
+    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 connectionManager_;
+    connectionManager_ = 0;
+    delete eniro_;
+    eniro_ = 0;
+    delete box_;
+    box_ = 0;
 }