Small fix to Eniro setting handling.
[jenirok] / src / common / eniro.cpp
1 /*
2  * This file is part of Jenirok.
3  *
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.
8  *
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.
13  *
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/>.
16  *
17  */
18
19 #include <QtCore/QDebug>
20 #include "eniro.h"
21
22 namespace
23 {
24     static const QString SITE_URLS[Eniro::SITE_COUNT] =
25     {
26             "http://wap.eniro.fi/",
27             "http://wap.eniro.se/",
28             "http://wap.eniro.dk/"
29     };
30
31     static const QString SITE_NAMES[Eniro::SITE_COUNT] =
32     {
33          "finnish",
34          "swedish",
35          "danish"
36     };
37
38     static const QString SITE_IDS[Eniro::SITE_COUNT] =
39     {
40          "fi",
41          "se",
42          "dk"
43     };
44
45     static const QString INVALID_LOGIN_STRING = "Invalid login details";
46     static const QString TIMEOUT_STRING = "Request timed out";
47     static const QString PERSON_REGEXP = "<td class=\"hTd2\">(.*)<b>(.*)</td>";
48     static const QString YELLOW_REGEXP = "<td class=\"hTd2\">(.*)<span class=\"gray\">(.*)</td>";
49     static const QString SINGLE_REGEXP = "<div class=\"header\">(.*)</div>(.*)<div class=\"callRow\">(.*)</div>";
50     static const QString NUMBER_REGEXP = "<div class=\"callRow\">(.*)</div>";
51     static const QString LOGIN_CHECK = "<input class=\"inpTxt\" id=\"loginformUsername\"";
52 }
53
54 Eniro::Eniro(QObject *parent): Source(parent), site_(Eniro::FI),
55 loggedIn_(false), username_(""), password_(""),
56 timerId_(0), pendingSearches_(), pendingNumberRequests_()
57 {
58 }
59
60 Eniro::~Eniro()
61 {
62 }
63
64 void Eniro::abort()
65 {
66     Source::abort();
67
68     for(searchMap::iterator sit = pendingSearches_.begin();
69     sit != pendingSearches_.end(); sit++)
70     {
71         if(sit.value() != 0)
72         {
73             delete sit.value();
74             sit.value() = 0;
75         }
76     }
77
78     pendingSearches_.clear();
79
80     for(numberMap::iterator nit = pendingNumberRequests_.begin();
81     nit != pendingNumberRequests_.end(); nit++)
82     {
83         if(nit.value() != 0)
84         {
85             delete nit.value();
86             nit.value() = 0;
87         }
88     }
89
90     pendingNumberRequests_.clear();
91     pendingLoginRequests_.clear();
92 }
93
94 void Eniro::setSite(Eniro::Site site)
95 {
96     site_ = site;
97 }
98
99 void Eniro::timerEvent(QTimerEvent* t)
100 {
101     Q_UNUSED(t);
102
103     int currentId = http_.currentId();
104
105     if(currentId)
106     {
107         searchMap::const_iterator it = pendingSearches_.find(currentId);
108
109         if(it != pendingSearches_.end())
110         {
111             QVector <Eniro::Result> results = it.value()->results;
112             SearchDetails details = it.value()->details;
113
114             abort();
115
116             setError(TIMEOUT, TIMEOUT_STRING);
117
118             emit requestFinished(results, details, true);
119         }
120     }
121 }
122
123 void Eniro::login(QString const& username,
124                   QString const& password)
125 {
126     username_ = username;
127     password_ = password;
128     loggedIn_ = true;
129 }
130
131 void Eniro::logout()
132 {
133     username_ = "";
134     password_ = "";
135     loggedIn_ = false;
136 }
137
138 void Eniro::search(SearchDetails const& details)
139 {
140     resetTimeout();
141
142     SearchType type = details.type;
143
144     // Only logged in users can use other than person search
145     if(!loggedIn_)
146     {
147         type = PERSONS;
148     }
149
150     QUrl url = createUrl(details.query, details.location);
151     QString what;
152
153     if(loggedIn_)
154     {
155         switch(type)
156         {
157         case YELLOW_PAGES:
158             what = "mobcs";
159             break;
160
161         case PERSONS:
162             what = "mobwp";
163             break;
164
165         default:
166             what = "moball";
167             break;
168         }
169
170     }
171     else
172     {
173         what = "moball";
174     }
175
176     url.addQueryItem("what", what);
177
178     http_.setHost(url.host(), url.port(80));
179     int id = http_.get(url.encodedPath() + '?' + url.encodedQuery());
180
181     QVector <Source::Result> results;
182
183     // Store search data for later identification
184     SearchData* newData = new SearchData;
185     newData->details = details;
186     newData->results = results;
187     newData->foundNumbers = 0;
188     newData->numbersTotal = 0;
189
190     // Store request id so that it can be identified later
191     pendingSearches_[id] = newData;
192
193 }
194
195 void Eniro::handleHttpData(int id, QByteArray const& data)
196 {
197     searchMap::const_iterator searchIt;
198     numberMap::const_iterator numberIt;
199
200     // Check if request is pending search request
201     if((searchIt = pendingSearches_.find(id)) !=
202         pendingSearches_.end())
203     {
204         // Load results from html data
205         loadResults(id, data);
206     }
207
208     // Check if request is pending number requests
209     else if((numberIt = pendingNumberRequests_.find(id)) !=
210         pendingNumberRequests_.end())
211     {
212         // Load number from html data
213         loadNumber(id, data);
214     }
215
216     // Check for login request
217     else if(pendingLoginRequests_.find(id) !=
218         pendingLoginRequests_.end())
219     {
220         bool success = true;
221
222         // If html source contains LOGIN_CHECK, login failed
223         if(data.indexOf(LOGIN_CHECK) != -1)
224         {
225             success = false;
226         }
227
228         emit loginStatus(success);
229     }
230
231 }
232
233 void Eniro::handleHttpError(int id)
234 {
235     searchMap::const_iterator searchIt;
236     numberMap::const_iterator numberIt;
237
238     // Check if request is pending search request
239     if((searchIt = pendingSearches_.find(id)) !=
240         pendingSearches_.end())
241     {
242         setError(CONNECTION_FAILURE, http_.errorString());
243         emitRequestFinished(id, searchIt.value(), true);
244     }
245
246     // Check if request is pending number requests
247     else if((numberIt = pendingNumberRequests_.find(id)) !=
248         pendingNumberRequests_.end())
249     {
250         setError(CONNECTION_FAILURE, http_.errorString());
251         delete pendingNumberRequests_[id];
252         pendingNumberRequests_.remove(id);
253     }
254
255     // Check for login request
256     else if(pendingLoginRequests_.find(id) !=
257         pendingLoginRequests_.end())
258     {
259         emit loginStatus(false);
260
261     }
262 }
263
264 // Loads results from html source code
265 void Eniro::loadResults(int id, QString const& httpData)
266 {
267     searchMap::iterator it = pendingSearches_.find(id);
268
269     QRegExp rx("((" + YELLOW_REGEXP + ")|(" + PERSON_REGEXP + ")|(" + SINGLE_REGEXP + "))");
270     rx.setMinimal(true);
271
272     bool requestsPending = false;
273     int pos = 0;
274     QString data;
275
276     // Find all matches
277     while((pos = rx.indexIn(httpData, pos)) != -1)
278     {
279         pos += rx.matchedLength();
280
281         data = rx.cap(1);
282
283         data = stripTags(data);
284         QStringList rows = data.split('\n');
285
286         for(int i = 0; i < rows.size(); i++)
287         {
288             // Remove white spaces
289             QString trimmed = rows.at(i).trimmed().toLower();
290
291             // Remove empty strings
292             if(trimmed.isEmpty())
293             {
294                 rows.removeAt(i);
295                 i--;
296             }
297             else
298             {
299                 // Convert words to uppercase
300                 rows[i] = ucFirst(trimmed);
301             }
302         }
303
304         Result result;
305
306         int size = rows.size();
307
308         switch(size)
309         {
310         case 1:
311             result.name = rows[0];
312             break;
313
314         case 2:
315             result.name = rows[0];
316             result.city = rows[1];
317             break;
318
319         case 3:
320             if(isPhoneNumber(rows[1]))
321             {
322                 result.name = rows[0];
323                 result.number = cleanUpNumber(rows[1]);
324                 result.city = rows[2];
325             }
326             else
327             {
328                 result.name = rows[0];
329                 result.street = rows[1];
330                 result.city = rows[2];
331             }
332             break;
333
334         case 4:
335             result.name = rows[0];
336             // Remove slashes and spaces from number
337             result.number = cleanUpNumber(rows[1]);
338             result.street = rows[2];
339             result.city = rows[3];
340             break;
341
342         default:
343             continue;
344
345         }
346
347         it.value()->results.push_back(result);
348
349         unsigned int foundResults = ++(it.value()->numbersTotal);
350
351         // If phone number searh is enabled, we have to make another
352         // request to find it out
353         if(getFindNumber() && size < 4 && loggedIn_ &&
354                 it.value()->details.type != YELLOW_PAGES)
355         {
356             requestsPending = true;
357             getNumberForResult(id, it.value()->results.size() - 1, it.value()->details);
358         }
359         // Otherwise result is ready
360         else
361         {
362             emit resultAvailable(result, it.value()->details);
363         }
364
365         unsigned int maxResults = getMaxResults();
366
367         // Stop searching if max results is reached
368         if(maxResults && (foundResults >= maxResults))
369         {
370             break;
371         }
372     }
373
374     // If there were no results or no phone numbers needed to
375     // be fetched, the whole request is ready
376     if(it.value()->numbersTotal == 0 || !requestsPending)
377     {
378         bool error = false;
379
380         if(httpData.indexOf(LOGIN_CHECK) != -1)
381         {
382             setError(INVALID_LOGIN, INVALID_LOGIN_STRING),
383             error = true;
384         }
385
386         emitRequestFinished(it.key(), it.value(), error);
387     }
388 }
389
390 // Loads phone number from html source
391 void Eniro::loadNumber(int id, QString const& result)
392 {
393     numberMap::iterator numberIt = pendingNumberRequests_.find(id);
394
395     // Make sure that id exists in pending number requests
396     if(numberIt == pendingNumberRequests_.end() || numberIt.value() == 0)
397     {
398         return;
399     }
400
401     searchMap::iterator searchIt = pendingSearches_.find(numberIt.value()->searchId);
402
403     if(searchIt == pendingSearches_.end() || searchIt.value() == 0)
404     {
405         return;
406     }
407
408     QRegExp rx(NUMBER_REGEXP);
409     rx.setMinimal(true);
410
411     int pos = 0;
412     bool error = true;
413
414     if((pos = rx.indexIn(result, pos)) != -1)
415     {
416         QString data = rx.cap(1);
417         data = stripTags(data);
418
419         QString trimmed = data.trimmed();
420
421         if(!trimmed.isEmpty())
422         {
423             // Remove whitespaces from number
424             searchIt.value()->results[numberIt.value()->index].number = cleanUpNumber(trimmed);
425
426             emit resultAvailable(searchIt.value()->results[numberIt.value()->index], searchIt.value()->details);
427
428             unsigned int found = ++searchIt.value()->foundNumbers;
429
430             // Check if all numbers have been found
431             if(found >= searchIt.value()->numbersTotal)
432             {
433                 emitRequestFinished(searchIt.key(), searchIt.value(), false);
434             }
435
436             // If number was found, there was no error
437             error = false;
438         }
439     }
440
441     if(error)
442     {
443         setError(INVALID_LOGIN, INVALID_LOGIN_STRING);
444         emitRequestFinished(searchIt.key(), searchIt.value(), true);
445     }
446
447     // Remove number request
448     int key = numberIt.key();
449
450     delete pendingNumberRequests_[key];
451     pendingNumberRequests_[key] = 0;
452     pendingNumberRequests_.remove(key);
453
454 }
455
456 QUrl Eniro::createUrl(QString const& query, QString const& location)
457 {
458     QUrl url(SITE_URLS[site_] + "query");
459
460     if(!query.isEmpty())
461     {
462         url.addQueryItem("search_word", query);
463     }
464
465     if(!location.isEmpty())
466     {
467         url.addQueryItem("geo_area", location);
468     }
469
470     unsigned int maxResults = getMaxResults();
471
472     if(maxResults)
473     {
474         url.addQueryItem("hpp", QString::number(maxResults));
475     }
476     if(loggedIn_)
477     {
478         url.addQueryItem("login_name", username_);
479         url.addQueryItem("login_password", password_);
480     }
481
482     fixUrl(url);
483
484     return url;
485 }
486
487 // Creates a new request for phone number retrieval
488 void Eniro::getNumberForResult(int id, int index, SearchDetails const& details)
489 {
490     QUrl url = createUrl(details.query, details.location);
491     url.addQueryItem("what", "mobwpinfo");
492     url.addQueryItem("search_number", QString::number(index + 1));
493
494     http_.setHost(url.host(), url.port(80));
495     int requestId = http_.get(url.encodedPath() + '?' + url.encodedQuery());
496     NumberData* number = new NumberData;
497     number->searchId = id;
498     number->index = index;
499     pendingNumberRequests_[requestId] = number;
500
501 }
502
503 void Eniro::emitRequestFinished(int key, SearchData* data, bool error)
504 {
505     emit requestFinished(data->results, data->details, error);
506     delete pendingSearches_[key];
507     pendingSearches_[key] = 0;
508     pendingSearches_.remove(key);
509 }
510
511
512 QMap <Eniro::Site, Eniro::SiteDetails> Eniro::getSites()
513 {
514     QMap <Site, SiteDetails> sites;
515
516     for(int i = 0; i < SITE_COUNT; i++)
517     {
518         SiteDetails details;
519         details.name = SITE_NAMES[i];
520         details.id = SITE_IDS[i];
521         sites[static_cast<Site>(i)] = details;
522     }
523
524     return sites;
525 }
526
527 Eniro::Site Eniro::stringToSite(QString const& str)
528 {
529     Site site = FI;
530     QString lower = str.toLower();
531
532     for(int i = 0; i < SITE_COUNT; i++)
533     {
534         if(lower == SITE_NAMES[i] || lower == SITE_IDS[i])
535         {
536             site = static_cast <Site> (i);
537             break;
538         }
539     }
540
541     return site;
542 }