- better size calculation
[buliscores] / src / backendkicker.cpp
1 #include <QtNetwork/QNetworkAccessManager>
2 #include <QtNetwork/QNetworkRequest>
3 #include <QUrl>
4 #include <QRegExp>
5 #include <QDebug>
6 #include <QStringList>
7 #include <QDateTime>
8 #include <QSettings>
9
10 #include "backendkicker.h"
11
12 BackendKicker::BackendKicker(QObject *parent) :
13     QObject(parent)
14 {
15     QSettings settings("David Solbach", "BuliScores");
16     this->setLeague(settings.value("League", "1. Bundesliga").toString());
17
18     this->update();
19 }
20
21 Match* BackendKicker::getMatch(QString hometeam, QString awayteam, QDateTime date)
22 {
23     QListIterator<Match*> iter(m_matchlist);
24     Match*        match;
25
26     while (iter.hasNext()) {
27         match = iter.next();
28         if (match->awayTeam() == awayteam &&
29             match->homeTeam() == hometeam) {
30             return match;
31         }
32     }
33
34     match = new Match(hometeam, awayteam, date, this);
35     m_matchlist.append(match);
36
37     return match;
38 }
39
40 QList<Match*> BackendKicker::matchList()
41 {
42     return m_matchlist;
43 }
44
45 static QDateTime parseDate(QString datehtml)
46 {
47     static QDateTime    lastParsedDate;
48     QStringList         tokens;
49     QDate               date;
50
51     int month, day, hour, minute;
52
53     //qDebug() << "parseDate in: " << datehtml;
54
55     tokens = datehtml.split(QRegExp("[>.&;:<\"]"), QString::SkipEmptyParts);
56     date = QDate::currentDate();
57
58     qDebug() << tokens;
59     if (tokens.count() < 6) {
60         return lastParsedDate;
61     }
62
63     month  = (tokens.at(2)).toInt();
64     day    = (tokens.at(1)).toInt();
65     hour   = (tokens.at(4)).toInt();
66     minute = (tokens.at(5)).toInt();
67
68     lastParsedDate =  QDateTime(QDate(date.year(), month, day),
69                                 QTime(hour, minute));
70
71     return lastParsedDate;
72 }
73
74 static QString parseTeam(QString teamhtml)
75 {
76     QString team;
77
78     //qDebug() << "parseTeam in: " << teamhtml;
79
80     teamhtml.truncate(teamhtml.indexOf("</a>"));
81     team = teamhtml.mid(teamhtml.lastIndexOf(">") + 1);
82
83     qDebug() << "parseTeam out: " << team;
84     return team;
85 }
86
87 static int parseScore(Match* match, QString scorehtml)
88 {
89     int         score = -1;
90     QStringList tokens;
91
92     qDebug() << "parseScore in: " << scorehtml;
93     tokens = scorehtml.split(QRegExp("[>&();:<]"), QString::SkipEmptyParts);
94     qDebug() << tokens;
95
96     if (tokens.count() == 7) {
97         // no extra color tag -> either not started, halftime or finished
98         if (tokens.at(4) == "-") {
99             // no first half results -> match not started yet
100             match->setState(Match::NotStarted);
101         } else if (tokens.at(1) == "-") {
102             // second half has not been started but there are first
103             // half results -> currently half time
104             match->setScore(tokens.at(4).toInt(), tokens.at(5).toInt());
105             match->setState(Match::HalfTime);
106         } else {
107             // no color tag and no "-" -> game is finished
108             match->setScore(tokens.at(1).toInt(), tokens.at(3).toInt());
109             match->setState(Match::Finished);
110         }
111     } else {
112         // there is a color tag which means that either first
113         // half or second half are currently running
114         if (tokens.at(4).contains("color")) {
115             // first half score marked red -> first half running
116             match->setScore(tokens.at(5).toInt(), tokens.at(6).toInt());
117             match->setState(Match::FirstHalf);
118         } else if (tokens.at(1).contains("color")) {
119             // second half score marked res -> second half running
120             match->setState(Match::SecondHalf);
121             match->setScore(tokens.at(2).toInt(), tokens.at(3).toInt());
122         }
123
124     }
125     qDebug() << "match out: " << match;
126
127     return score;
128 }
129
130 void BackendKicker::parsePage (QString htmlstr)
131 {
132     QStringList     rawmatches;
133     QString         hometeam, awayteam, tmp;
134     QRegExp         rx;
135     QDateTime       date;
136     Match*          match;
137
138     int             pos     = 0;
139     int             count   = 0;
140
141     //qDebug() << "parsePage in: " << htmlstr;
142
143     rx.setPattern("<td class=\"first\">(.*)<td class=\"aligncenter last\">");
144     rx.setMinimal(true);
145     while ((pos = rx.indexIn(htmlstr, pos)) != -1) {
146          ++count;
147          rawmatches.append(htmlstr.mid(pos, rx.matchedLength()));
148          qDebug() << "MATCH " << count << ":" << htmlstr.mid(pos, rx.matchedLength()) << "\n\n";
149          pos += rx.matchedLength();
150      }
151
152     rx.setPattern("<td.*>(.*)</td>");
153
154     QStringList::iterator i;
155     for (i = rawmatches.begin(); i != rawmatches.end(); ++i) {
156         pos = 0;
157         count = 0;
158         while ((pos = rx.indexIn(*i, pos)) != -1) {
159              ++count;
160              tmp = (*i).mid(pos, rx.matchedLength());
161              pos += rx.matchedLength();
162              switch (count) {
163              case 2: // date
164                  date = parseDate(tmp);
165                  break;
166              case 3: // hometeam
167                  hometeam = parseTeam(tmp);
168                  break;
169              case 5: // awayteam
170                  awayteam = parseTeam(tmp);
171                  match = getMatch(hometeam, awayteam, date);
172                  break;
173              case 6: // scores
174                  parseScore(match, tmp);
175                  break;
176              default:
177                 ;;
178              }
179         }
180     }
181 }
182
183 void BackendKicker::setLeague(QString league)
184 {
185     if (league == "1. Bundesliga") {
186         m_URL = "http://www.kicker.de/news/fussball/bundesliga/spieltag/1-bundesliga/2010-11/spieltag.html";
187     } else if (league == "2. Bundesliga") {
188         m_URL = "http://www.kicker.de/news/fussball/bundesliga/spieltag/2-bundesliga/2010-11/spieltag.html";
189     } else if (league == "tipp3 Bundesliga") {
190         m_URL = "http://www.kicker.de/news/fussball/intligen/oesterreich/tipp3-bundesliga/2010-11/spieltag.html";
191     }
192
193     // delete last data
194     this->m_matchlist.clear();
195     emit matchListChanged();
196 }
197
198 void BackendKicker::update()
199 {
200     //QString URL = "file:///home/david/Projects/git-buliscores/testdata/spieltag.html";
201
202     QNetworkAccessManager *manager = new QNetworkAccessManager(this);
203     connect(manager, SIGNAL(finished(QNetworkReply*)),
204             this, SLOT(dlndFinished(QNetworkReply*)));
205
206     qDebug() << "URL: " << m_URL;
207     manager->get(QNetworkRequest(QUrl(m_URL)));
208 }
209
210 void BackendKicker::dlndFinished(QNetworkReply *reply)
211 {
212     QString         rawdata;
213
214     if (reply->error() != QNetworkReply::NoError) {
215         // TODO proper user friendly error handling here!
216         qDebug() << "dlnd failed: error: " << reply->error();
217     }
218
219     rawdata = reply->readAll();
220     parsePage(rawdata);
221     emit matchListChanged();
222 }