Architecture changed to allow easier addition of new phone books. Norwegian phonebook...
[jenirok] / src / common / eniro.cpp
index 0b8579b..0958893 100644 (file)
 
 namespace
 {
-    static const QString SITE_URLS[] =
+    static const QString SITE_URLS[Eniro::SITE_COUNT] =
     {
             "http://wap.eniro.fi/",
             "http://wap.eniro.se/",
             "http://wap.eniro.dk/"
     };
 
-    const QString INVALID_LOGIN_STRING = "Invalid login details";
-    const QString PERSON_REGEXP = "<td class=\"hTd2\">(.*)<b>(.*)</td>";
-    const QString YELLOW_REGEXP = "<td class=\"hTd2\">(.*)<span class=\"gray\"\\}>(.*)</td>";
-    const QString NUMBER_REGEXP = "<div class=\"callRow\">(.*)</div>";
-    const QString LOGIN_CHECK = "<input class=\"inpTxt\" id=\"loginformUsername\"";
-}
+    static const QString SITE_NAMES[Eniro::SITE_COUNT] =
+    {
+         "finnish",
+         "swedish",
+         "danish"
+    };
 
-// Regexp used to remove numbers from string
-QRegExp Eniro::numberCleaner_ = QRegExp("([^0-9]+)");
+    static const QString SITE_IDS[Eniro::SITE_COUNT] =
+    {
+         "fi",
+         "se",
+         "dk"
+    };
 
-// Removes html tags from string
-QRegExp Eniro::tagStripper_ = QRegExp("<([^>]+)>");
+    static const QString INVALID_LOGIN_STRING = "Invalid login details";
+    static const QString TIMEOUT_STRING = "Request timed out";
+    static const QString PERSON_REGEXP = "<td class=\"hTd2\">(.*)<b>(.*)</td>";
+    static const QString YELLOW_REGEXP = "<td class=\"hTd2\">(.*)<span class=\"gray\"\\}>(.*)</td>";
+    static const QString NUMBER_REGEXP = "<div class=\"callRow\">(.*)</div>";
+    static const QString LOGIN_CHECK = "<input class=\"inpTxt\" id=\"loginformUsername\"";
+}
 
-Eniro::Eniro(Site site, QObject *parent): QObject(parent), site_(site),
-username_(""), password_(""), loggedIn_(false), error_(NO_ERROR),
-errorString_(""), maxResults_(10), findNumber_(true),
-pendingSearches_(), pendingNumberRequests_()
+Eniro::Eniro(QObject *parent): Source(parent), site_(Eniro::FI),
+loggedIn_(false), username_(""), password_(""),
+timerId_(0), pendingSearches_(), pendingNumberRequests_()
 {
-    connect(&http_, SIGNAL(requestFinished(int, bool)), this, SLOT(httpReady(int, bool)));
 }
 
 Eniro::~Eniro()
 {
-    abort();
 }
 
 void Eniro::abort()
 {
-    http_.abort();
+    Source::abort();
 
     for(searchMap::iterator sit = pendingSearches_.begin();
     sit != pendingSearches_.end(); sit++)
@@ -84,19 +90,33 @@ void Eniro::abort()
     pendingLoginRequests_.clear();
 }
 
-void Eniro::setMaxResults(unsigned int value)
+void Eniro::setSite(Eniro::Site site)
 {
-    maxResults_ = value;
+    site_ = site;
 }
 
-void Eniro::setFindNumber(bool value)
+void Eniro::timerEvent(QTimerEvent* t)
 {
-    findNumber_ = value;
-}
+    Q_UNUSED(t);
 
-void Eniro::setSite(Eniro::Site site)
-{
-    site_ = site;
+    int currentId = http_.currentId();
+
+    if(currentId)
+    {
+        searchMap::const_iterator it = pendingSearches_.find(currentId);
+
+        if(it != pendingSearches_.end())
+        {
+            QVector <Eniro::Result> results = it.value()->results;
+            SearchDetails details = it.value()->details;
+
+            abort();
+
+            setError(TIMEOUT, TIMEOUT_STRING);
+
+            emit requestFinished(results, details, true);
+        }
+    }
 }
 
 void Eniro::login(QString const& username,
@@ -114,19 +134,10 @@ void Eniro::logout()
     loggedIn_ = false;
 }
 
-void Eniro::testLogin()
+void Eniro::search(SearchDetails const& details)
 {
-    QUrl url = createUrl("", "");
+    resetTimeout();
 
-    url.addQueryItem("what", "mobwp");
-    http_.setHost(url.host(), url.port(80));
-    int id = http_.get(url.encodedPath() + '?' + url.encodedQuery());
-
-    pendingLoginRequests_.insert(id);
-}
-
-bool Eniro::search(SearchDetails const& details)
-{
     SearchType type = details.type;
 
     // Only logged in users can use other than person search
@@ -165,7 +176,7 @@ bool Eniro::search(SearchDetails const& details)
     http_.setHost(url.host(), url.port(80));
     int id = http_.get(url.encodedPath() + '?' + url.encodedQuery());
 
-    QVector <Result> results;
+    QVector <Source::Result> results;
 
     // Store search data for later identification
     SearchData* newData = new SearchData;
@@ -177,26 +188,11 @@ bool Eniro::search(SearchDetails const& details)
     // Store request id so that it can be identified later
     pendingSearches_[id] = newData;
 
-    return true;
 }
 
-Eniro::Error Eniro::error() const
+void Eniro::handleHttpData(int id, QString const& data)
 {
-    return error_;
-}
-
-const QString& Eniro::errorString() const
-{
-    return errorString_;
-}
-
-void Eniro::httpReady(int id, bool error)
-{
-    if(error)
-    {
-        qDebug() << "Error: " << http_.errorString();
-    }
-
+    qDebug() << "Handle:" << id;
     searchMap::const_iterator searchIt;
     numberMap::const_iterator numberIt;
 
@@ -204,37 +200,17 @@ void Eniro::httpReady(int id, bool error)
     if((searchIt = pendingSearches_.find(id)) !=
         pendingSearches_.end())
     {
-        if(error)
-        {
-            error_ = CONNECTION_FAILURE;
-            errorString_ = http_.errorString();
-            emitRequestFinished(id, searchIt.value(), true);
-            return;
-        }
-
-        QString result(http_.readAll());
-
+        qDebug() << "Load results";
         // Load results from html data
-        loadResults(id, result);
+        loadResults(id, data);
     }
 
     // Check if request is pending number requests
     else if((numberIt = pendingNumberRequests_.find(id)) !=
         pendingNumberRequests_.end())
     {
-        if(error)
-        {
-            error_ = CONNECTION_FAILURE;
-            errorString_ = http_.errorString();
-            delete pendingNumberRequests_[id];
-            pendingNumberRequests_.remove(id);
-            return;
-        }
-
-        QString result(http_.readAll());
-
         // Load number from html data
-        loadNumber(id, result);
+        loadNumber(id, data);
     }
 
     // Check for login request
@@ -243,17 +219,8 @@ void Eniro::httpReady(int id, bool error)
     {
         bool success = true;
 
-        if(!error)
-        {
-            QString result(http_.readAll());
-
-            // If html source contains LOGIN_CHECK, login failed
-            if(result.indexOf(LOGIN_CHECK) != -1)
-            {
-                success = false;
-            }
-        }
-        else
+        // If html source contains LOGIN_CHECK, login failed
+        if(data.indexOf(LOGIN_CHECK) != -1)
         {
             success = false;
         }
@@ -263,6 +230,37 @@ void Eniro::httpReady(int id, bool error)
 
 }
 
+void Eniro::handleHttpError(int id)
+{
+    searchMap::const_iterator searchIt;
+    numberMap::const_iterator numberIt;
+
+    // Check if request is pending search request
+    if((searchIt = pendingSearches_.find(id)) !=
+        pendingSearches_.end())
+    {
+        setError(CONNECTION_FAILURE, http_.errorString());
+        emitRequestFinished(id, searchIt.value(), true);
+    }
+
+    // Check if request is pending number requests
+    else if((numberIt = pendingNumberRequests_.find(id)) !=
+        pendingNumberRequests_.end())
+    {
+        setError(CONNECTION_FAILURE, http_.errorString());
+        delete pendingNumberRequests_[id];
+        pendingNumberRequests_.remove(id);
+    }
+
+    // Check for login request
+    else if(pendingLoginRequests_.find(id) !=
+        pendingLoginRequests_.end())
+    {
+        emit loginStatus(false);
+
+    }
+}
+
 // Loads results from html source code
 void Eniro::loadResults(int id, QString const& httpData)
 {
@@ -355,7 +353,7 @@ void Eniro::loadResults(int id, QString const& httpData)
 
         // If phone number searh is enabled, we have to make another
         // request to find it out
-        if(findNumber_ && size < 4 && loggedIn_ &&
+        if(getFindNumber() && size < 4 && loggedIn_ &&
                 it.value()->details.type != YELLOW_PAGES)
         {
             requestsPending = true;
@@ -367,14 +365,16 @@ void Eniro::loadResults(int id, QString const& httpData)
             emit resultAvailable(result, it.value()->details);
         }
 
+        unsigned int maxResults = getMaxResults();
+
         // Stop searching if max results is reached
-        if(maxResults_ && (foundResults >= maxResults_))
+        if(maxResults && (foundResults >= maxResults))
         {
             break;
         }
     }
 
-    // If number there were no results or no phone numbers needed to
+    // If there were no results or no phone numbers needed to
     // be fetched, the whole request is ready
     if(it.value()->numbersTotal == 0 || !requestsPending)
     {
@@ -382,8 +382,7 @@ void Eniro::loadResults(int id, QString const& httpData)
 
         if(httpData.indexOf(LOGIN_CHECK) != -1)
         {
-            error_ = INVALID_LOGIN;
-            errorString_ = INVALID_LOGIN_STRING;
+            setError(INVALID_LOGIN, INVALID_LOGIN_STRING),
             error = true;
         }
 
@@ -444,8 +443,7 @@ void Eniro::loadNumber(int id, QString const& result)
 
     if(error)
     {
-        error_ = INVALID_LOGIN;
-        errorString_ = INVALID_LOGIN;
+        setError(INVALID_LOGIN, INVALID_LOGIN_STRING);
         emitRequestFinished(searchIt.key(), searchIt.value(), true);
     }
 
@@ -472,9 +470,11 @@ QUrl Eniro::createUrl(QString const& query, QString const& location)
         url.addQueryItem("geo_area", location);
     }
 
-    if(maxResults_)
+    unsigned int maxResults = getMaxResults();
+
+    if(maxResults)
     {
-        url.addQueryItem("hpp", QString::number(maxResults_));
+        url.addQueryItem("hpp", QString::number(maxResults));
     }
     if(loggedIn_)
     {
@@ -482,8 +482,7 @@ QUrl Eniro::createUrl(QString const& query, QString const& location)
         url.addQueryItem("login_password", password_);
     }
 
-    QByteArray path = url.encodedQuery().replace('+', "%2B");
-    url.setEncodedQuery(path);
+    fixUrl(url);
 
     return url;
 }
@@ -506,60 +505,25 @@ void Eniro::getNumberForResult(int id, int index, SearchDetails const& details)
 
 void Eniro::emitRequestFinished(int key, SearchData* data, bool error)
 {
-
-    // Do not emit "Request aborted" error
-    if(!(error && (http_.error() == QHttp::Aborted)))
-    {
-        emit requestFinished(data->results, data->details, error);
-    }
-
+    emit requestFinished(data->results, data->details, error);
     delete pendingSearches_[key];
     pendingSearches_[key] = 0;
     pendingSearches_.remove(key);
 }
 
-QString Eniro::ucFirst(QString& str)
-{
-    if (str.size() < 1) {
-        return "";
-    }
-
-    QStringList tokens = str.split(" ");
-    QList<QString>::iterator tokItr;
-
-    for (tokItr = tokens.begin(); tokItr != tokens.end(); ++tokItr)
-    {
-        (*tokItr) = (*tokItr).at(0).toUpper() + (*tokItr).mid(1);
-    }
-
-    return tokens.join(" ");
-}
-
-QString& Eniro::cleanUpNumber(QString& number)
-{
-    return number.replace(numberCleaner_, "");
-}
-
-QString& Eniro::stripTags(QString& string)
-{
-    return string.replace(tagStripper_, "");
-}
 
 QMap <Eniro::Site, Eniro::SiteDetails> Eniro::getSites()
 {
     QMap <Site, SiteDetails> sites;
     SiteDetails details;
-    details.name = tr("Finnish");
-    details.id = "fi";
-    sites[FI] = details;
-
-    details.name = tr("Swedish");
-    details.id = "se";
-    sites[SE] = details;
 
-    details.name = tr("Danish");
-    details.id = "dk";
-    sites[DK] = details;
+    for(int i = 0; i < SITE_COUNT; i++)
+    {
+        SiteDetails details;
+        details.name = SITE_NAMES[i];
+        details.id = SITE_IDS[i];
+        sites[static_cast<Site>(i)] = details;
+    }
 
     return sites;
 }
@@ -567,26 +531,16 @@ QMap <Eniro::Site, Eniro::SiteDetails> Eniro::getSites()
 Eniro::Site Eniro::stringToSite(QString const& str)
 {
     Site site = FI;
-
     QString lower = str.toLower();
 
-    if(lower == "se" || lower == "swedish")
-    {
-        site = SE;
-    }
-    else if(lower == "dk" || lower == "danish")
+    for(int i = 0; i < SITE_COUNT; i++)
     {
-        site = DK;
+        if(lower == SITE_NAMES[i] || lower == SITE_IDS[i])
+        {
+            site = static_cast <Site> (i);
+            break;
+        }
     }
 
     return site;
 }
-
-Eniro::SearchDetails::SearchDetails(QString const& q,
-                                    QString const& loc,
-                                    SearchType t)
-{
-    query = q;
-    location = loc;
-    type = t;
-}