2 * This file is part of Jenirok.
4 * Jenirok is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
9 * Jenirok is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with Jenirok. If not, see <http://www.gnu.org/licenses/>.
19 #include <QtCore/QDebug>
24 static const QString SITE_URLS[] =
26 "http://wap.eniro.fi/",
27 "http://wap.eniro.se/",
28 "http://wap.eniro.dk/"
31 const QString INVALID_LOGIN_STRING = "Invalid login details";
32 const QString PERSON_REGEXP = "<td class=\"hTd2\">(.*)<b>(.*)</td>";
33 const QString YELLOW_REGEXP = "<td class=\"hTd2\">(.*)<span class=\"gray\"\\}>(.*)</td>";
34 const QString NUMBER_REGEXP = "<div class=\"callRow\">(.*)</div>";
35 const QString LOGIN_CHECK = "<input class=\"inpTxt\" id=\"loginformUsername\"";
38 // Regexp used to remove numbers from string
39 QRegExp Eniro::numberCleaner_ = QRegExp("([^0-9]+)");
41 // Removes html tags from string
42 QRegExp Eniro::tagStripper_ = QRegExp("<([^>]+)>");
44 Eniro::Eniro(Site site, QObject *parent): QObject(parent), site_(site),
45 username_(""), password_(""), loggedIn_(false), error_(NO_ERROR),
46 errorString_(""), maxResults_(10), findNumber_(true),
47 pendingSearches_(), pendingNumberRequests_()
49 connect(&http_, SIGNAL(requestFinished(int, bool)), this, SLOT(httpReady(int, bool)));
61 for(searchMap::iterator sit = pendingSearches_.begin();
62 sit != pendingSearches_.end(); sit++)
71 pendingSearches_.clear();
73 for(numberMap::iterator nit = pendingNumberRequests_.begin();
74 nit != pendingNumberRequests_.end(); nit++)
83 pendingNumberRequests_.clear();
84 pendingLoginRequests_.clear();
87 void Eniro::setMaxResults(unsigned int value)
92 void Eniro::setFindNumber(bool value)
97 void Eniro::setSite(Eniro::Site site)
102 void Eniro::login(QString const& username,
103 QString const& password)
105 username_ = username;
106 password_ = password;
117 void Eniro::testLogin()
119 QUrl url = createUrl("", "");
121 url.addQueryItem("what", "mobwp");
122 http_.setHost(url.host(), url.port(80));
123 int id = http_.get(url.encodedPath() + '?' + url.encodedQuery());
125 pendingLoginRequests_.insert(id);
128 bool Eniro::search(SearchDetails const& details)
130 SearchType type = details.type;
132 // Only logged in users can use other than person search
138 QUrl url = createUrl(details.query, details.location);
163 url.addQueryItem("what", what);
165 http_.setHost(url.host(), url.port(80));
166 int id = http_.get(url.encodedPath() + '?' + url.encodedQuery());
168 QVector <Result> results;
170 // Store search data for later identification
171 SearchData* newData = new SearchData;
172 newData->details = details;
173 newData->results = results;
174 newData->foundNumbers = 0;
175 newData->numbersTotal = 0;
177 // Store request id so that it can be identified later
178 pendingSearches_[id] = newData;
183 Eniro::Error Eniro::error() const
188 const QString& Eniro::errorString() const
193 void Eniro::httpReady(int id, bool error)
197 qDebug() << "Error: " << http_.errorString();
200 searchMap::const_iterator searchIt;
201 numberMap::const_iterator numberIt;
203 // Check if request is pending search request
204 if((searchIt = pendingSearches_.find(id)) !=
205 pendingSearches_.end())
209 error_ = CONNECTION_FAILURE;
210 errorString_ = http_.errorString();
211 emitRequestFinished(id, searchIt.value(), true);
215 QString result(http_.readAll());
217 // Load results from html data
218 loadResults(id, result);
221 // Check if request is pending number requests
222 else if((numberIt = pendingNumberRequests_.find(id)) !=
223 pendingNumberRequests_.end())
227 error_ = CONNECTION_FAILURE;
228 errorString_ = http_.errorString();
229 delete pendingNumberRequests_[id];
230 pendingNumberRequests_.remove(id);
234 QString result(http_.readAll());
236 // Load number from html data
237 loadNumber(id, result);
240 // Check for login request
241 else if(pendingLoginRequests_.find(id) !=
242 pendingLoginRequests_.end())
248 QString result(http_.readAll());
250 // If html source contains LOGIN_CHECK, login failed
251 if(result.indexOf(LOGIN_CHECK) != -1)
261 emit loginStatus(success);
266 // Loads results from html source code
267 void Eniro::loadResults(int id, QString const& httpData)
269 searchMap::iterator it = pendingSearches_.find(id);
272 switch(it.value()->details.type)
275 expr = YELLOW_REGEXP;
278 expr = PERSON_REGEXP;
287 bool requestsPending = false;
292 while((pos = rx.indexIn(httpData, pos)) != -1)
294 pos += rx.matchedLength();
297 data = stripTags(data);
298 QStringList rows = data.split('\n');
300 for(int i = 0; i < rows.size(); i++)
302 // Remove white spaces
303 QString trimmed = rows.at(i).trimmed().toLower();
305 // Remove empty strings
306 if(trimmed.isEmpty())
313 // Convert words to uppercase
314 rows[i] = ucFirst(trimmed);
320 int size = rows.size();
325 result.name = rows[0];
329 result.name = rows[0];
330 result.city = rows[1];
334 result.name = rows[0];
335 result.street = rows[1];
336 result.city = rows[2];
340 result.name = rows[0];
341 // Remove slashes and spaces from number
342 result.number = cleanUpNumber(rows[1]);
343 result.street = rows[2];
344 result.city = rows[3];
352 it.value()->results.push_back(result);
354 unsigned int foundResults = ++(it.value()->numbersTotal);
356 // If phone number searh is enabled, we have to make another
357 // request to find it out
358 if(findNumber_ && size < 4 && loggedIn_ &&
359 it.value()->details.type != YELLOW_PAGES)
361 requestsPending = true;
362 getNumberForResult(id, it.value()->results.size() - 1, it.value()->details);
364 // Otherwise result is ready
367 emit resultAvailable(result, it.value()->details);
370 // Stop searching if max results is reached
371 if(maxResults_ && (foundResults >= maxResults_))
377 // If number there were no results or no phone numbers needed to
378 // be fetched, the whole request is ready
379 if(it.value()->numbersTotal == 0 || !requestsPending)
383 if(httpData.indexOf(LOGIN_CHECK) != -1)
385 error_ = INVALID_LOGIN;
386 errorString_ = INVALID_LOGIN_STRING;
390 emitRequestFinished(it.key(), it.value(), error);
394 // Loads phone number from html source
395 void Eniro::loadNumber(int id, QString const& result)
397 numberMap::iterator numberIt = pendingNumberRequests_.find(id);
399 // Make sure that id exists in pending number requests
400 if(numberIt == pendingNumberRequests_.end() || numberIt.value() == 0)
405 searchMap::iterator searchIt = pendingSearches_.find(numberIt.value()->searchId);
407 if(searchIt == pendingSearches_.end() || searchIt.value() == 0)
412 QRegExp rx(NUMBER_REGEXP);
418 if((pos = rx.indexIn(result, pos)) != -1)
420 QString data = rx.cap(1);
421 data = stripTags(data);
423 QString trimmed = data.trimmed();
425 if(!trimmed.isEmpty())
427 // Remove whitespaces from number
428 searchIt.value()->results[numberIt.value()->index].number = cleanUpNumber(trimmed);
430 emit resultAvailable(searchIt.value()->results[numberIt.value()->index], searchIt.value()->details);
432 unsigned int found = ++searchIt.value()->foundNumbers;
434 // Check if all numbers have been found
435 if(found >= searchIt.value()->numbersTotal)
437 emitRequestFinished(searchIt.key(), searchIt.value(), false);
440 // If number was found, there was no error
447 error_ = INVALID_LOGIN;
448 errorString_ = INVALID_LOGIN;
449 emitRequestFinished(searchIt.key(), searchIt.value(), true);
452 // Remove number request
453 int key = numberIt.key();
455 delete pendingNumberRequests_[key];
456 pendingNumberRequests_[key] = 0;
457 pendingNumberRequests_.remove(key);
461 QUrl Eniro::createUrl(QString const& query, QString const& location)
463 QUrl url(SITE_URLS[site_] + "query");
467 url.addQueryItem("search_word", query);
470 if(!location.isEmpty())
472 url.addQueryItem("geo_area", location);
477 url.addQueryItem("hpp", QString::number(maxResults_));
481 url.addQueryItem("login_name", username_);
482 url.addQueryItem("login_password", password_);
485 QByteArray path = url.encodedQuery().replace('+', "%2B");
486 url.setEncodedQuery(path);
491 // Creates a new request for phone number retrieval
492 void Eniro::getNumberForResult(int id, int index, SearchDetails const& details)
494 QUrl url = createUrl(details.query, details.location);
495 url.addQueryItem("what", "mobwpinfo");
496 url.addQueryItem("search_number", QString::number(index + 1));
498 http_.setHost(url.host(), url.port(80));
499 int requestId = http_.get(url.encodedPath() + '?' + url.encodedQuery());
500 NumberData* number = new NumberData;
501 number->searchId = id;
502 number->index = index;
503 pendingNumberRequests_[requestId] = number;
507 void Eniro::emitRequestFinished(int key, SearchData* data, bool error)
510 // Do not emit "Request aborted" error
511 if(!(error && (http_.error() == QHttp::Aborted)))
513 emit requestFinished(data->results, data->details, error);
516 delete pendingSearches_[key];
517 pendingSearches_[key] = 0;
518 pendingSearches_.remove(key);
521 QString Eniro::ucFirst(QString& str)
523 if (str.size() < 1) {
527 QStringList tokens = str.split(" ");
528 QList<QString>::iterator tokItr;
530 for (tokItr = tokens.begin(); tokItr != tokens.end(); ++tokItr)
532 (*tokItr) = (*tokItr).at(0).toUpper() + (*tokItr).mid(1);
535 return tokens.join(" ");
538 QString& Eniro::cleanUpNumber(QString& number)
540 return number.replace(numberCleaner_, "");
543 QString& Eniro::stripTags(QString& string)
545 return string.replace(tagStripper_, "");
548 QMap <Eniro::Site, Eniro::SiteDetails> Eniro::getSites()
550 QMap <Site, SiteDetails> sites;
552 details.name = tr("Finnish");
556 details.name = tr("Swedish");
560 details.name = tr("Danish");
567 Eniro::Site Eniro::stringToSite(QString const& str)
571 QString lower = str.toLower();
573 if(lower == "se" || lower == "swedish")
577 else if(lower == "dk" || lower == "danish")
585 Eniro::SearchDetails::SearchDetails(QString const& q,