More porting to Qt5
[quandoparte] / application / stationschedulemodel.cpp
1 /*
2
3 Copyright (C) 2011 Luciano Montanaro <mikelima@cirulla.net>
4
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2 of the License, or
8 (at your option) any later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13 General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with this program; see the file COPYING.  If not, write to
17 the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
18 Boston, MA 02110-1301, USA.
19
20 */
21
22 #include "stationschedulemodel.h"
23
24 #include "dataprovider.h"
25 #include "settings.h"
26
27 #include <QtGlobal>
28 #include <QDebug>
29 #if (QT_VERSION >= QT_VERSION_CHECK(5, 1, 0))
30 #include <QtWebKitWidgets>
31 #else
32 #include <QWebElement>
33 #include <QWebFrame>
34 #include <QWebPage>
35 #endif
36
37 StationScheduleModel::StationScheduleModel(const QString &name, QObject *parent) :
38     QAbstractListModel(parent),
39     m_name(name),
40     m_error(QString())
41
42 {
43     DataProvider *provider = DataProvider::instance();
44     connect(provider, SIGNAL(stationScheduleReady(QByteArray,QUrl)),
45             this, SLOT(parse(QByteArray,QUrl)));
46     connect(provider, SIGNAL(error()),
47             this, SLOT(onNetworkError()));
48     Settings *settings = Settings::instance();
49     m_scheduleType = settings->showArrivalsPreferred() ? ArrivalSchedule : DepartureSchedule;
50 #if (QT_VERSION < QT_VERSION_CHECK(5, 0, 0))
51     setRoleNames(roleNames());
52 #endif
53 }
54
55 const QString &StationScheduleModel::name()
56 {
57     return m_name;
58 }
59
60 void StationScheduleModel::setName(const QString &name)
61 {
62     if (name != m_name) {
63         m_name = name;
64         emit nameChanged();
65     }
66 }
67
68 const QString &StationScheduleModel::code()
69 {
70     return m_code;
71 }
72
73 void StationScheduleModel::setCode(const QString &code)
74 {
75     if (code != m_code) {
76         m_code = code;
77         emit codeChanged();
78     }
79 }
80
81 const QString &StationScheduleModel::error()
82 {
83     return m_error;
84 }
85
86 void StationScheduleModel::setError(const QString &error)
87 {
88     if (error != m_error) {
89         m_error = error;
90         emit errorChanged();
91     }
92 }
93
94 QHash<int, QByteArray> StationScheduleModel::roleNames() const
95 {
96     QHash<int, QByteArray> roles;
97     roles[TrainRole] = "train";
98     roles[DepartureStationRole] = "departureStation";
99     roles[DepartureTimeRole] = "departureTime";
100     roles[ArrivalStationRole] = "arrivalStation";
101     roles[ArrivalTimeRole] = "arrivalTime";
102     roles[DetailsUrlRole] = "detailsUrl";
103     roles[DelayRole] = "delay";
104     roles[DelayClassRole] = "delayClass";
105     roles[ExpectedPlatformRole] = "expectedPlatform";
106     roles[ActualPlatformRole] = "actualPlatform";
107
108     return roles;
109 }
110
111 StationScheduleModel::ScheduleType StationScheduleModel::type()
112 {
113     return m_scheduleType;
114 }
115
116 void StationScheduleModel::setType(StationScheduleModel::ScheduleType type)
117 {
118     if (type != m_scheduleType) {
119         emit layoutAboutToBeChanged();
120         beginResetModel();
121         m_scheduleType = type;
122         emit typeChanged();
123         endResetModel();
124         emit layoutChanged();
125         Settings *settings = Settings::instance();
126         settings->setShowArrivalsPreferred(m_scheduleType == ArrivalSchedule ? true : false);
127     }
128 }
129
130 static void parseDelayClass(const QWebElement &element, StationScheduleItem &item)
131 {
132     if (!element.isNull()) {
133         QWebElement image = element.findFirst("img");
134         if (!image.isNull()) {
135             int delayClass = 42;
136             QString imageName = image.attribute("src");
137             if (!imageName.isEmpty()) {
138                 QRegExp delayClassRegexp("pallinoRit([0-9])\\.png");
139                 int pos = delayClassRegexp.indexIn(imageName);
140                 qDebug() << "regexp matched at pos:" << pos << "match:" << delayClassRegexp.cap(0);
141                 delayClass =  (pos >= 0) ? delayClassRegexp.cap(1).toInt() : 0;
142             }
143             item.setDelayClass(delayClass);
144         } else {
145             qDebug() << "img not found";
146         }
147     } else {
148         qDebug() << "div.bloccotreno not found";
149     }
150 }
151
152 static void parseDetailsUrl(const QWebElement &element, StationScheduleItem &item)
153 {
154     if (!element.isNull()) {
155         QWebElement link = element.findFirst("a");
156         QString url = link.attribute("href");
157         item.setDetailsUrl(url);
158     } else {
159         qDebug() << "link not found";
160     }
161 }
162
163 static void parseTrain(const QString &text, StationScheduleItem &item)
164 {
165     QRegExp filter("^(Per|Da) (.*)\\n"
166                    "Delle ore (.*)\n"
167                    "Binario Previsto: (.*)\n"
168                    "Binario Reale: (.*)\n"
169                    "(.*)$");
170     int pos = filter.indexIn(text);
171     if (pos >= 0) {
172         if (filter.cap(1) == "Per") {
173             item.setDepartureStation(filter.cap(2));
174             item.setDepartureTime(filter.cap(3));
175         } else {
176             item.setArrivalStation(filter.cap(2));
177             item.setArrivalTime(filter.cap(3));
178         }
179         item.setDelay(filter.cap(6));
180         item.setExpectedPlatform(filter.cap(4));
181         item.setActualPlatform(filter.cap(5));
182     } else {
183         qDebug() << "could not parse" << text;
184     }
185 }
186
187 StationScheduleItem parseResult(const QWebElement &result)
188 {
189     StationScheduleItem item;
190
191     QWebElement current = result.findFirst("h2");
192     if (!current.isNull()) {
193         item.setTrain(current.toPlainText());
194     }
195     parseDetailsUrl(result, item);
196     current = result.findFirst("div.bloccotreno");
197     parseDelayClass(current, item);
198     QString rawText = current.toPlainText();
199     parseTrain(rawText, item);
200
201     qDebug() << "train:" << item.train();
202     qDebug() << "delayClass:" << item.delayClass();
203     qDebug() << "detailsUrl:" << item.detailsUrl();
204     qDebug() << "departureStation:" << item.departureStation();
205     qDebug() << "departureTime:" << item.departureTime();
206     qDebug() << "arrivalStation:" << item.arrivalStation();
207     qDebug() << "arrivalTime:" << item.arrivalTime();
208     qDebug() << "expectedPlatform:" << item.expectedPlatform();
209     qDebug() << "actualPlatform:" << item.actualPlatform();
210     qDebug() << "delay:" << item.delay();
211     return item;
212 }
213
214 void StationScheduleModel::parse(const QByteArray &htmlReply, const QUrl &baseUrl)
215 {
216     Q_UNUSED(baseUrl);
217     qDebug() << "--- start of query result --- cut here ------";
218     qDebug() << QString::fromUtf8(htmlReply.constData());
219     qDebug() << "--- end of query result ----- cut here ------";
220
221     emit layoutAboutToBeChanged();
222     beginResetModel();
223 #if (QT_VERSION <= QT_VERSION_CHECK(5, 0, 0))
224     QWebPage page;
225     page.mainFrame()->setContent(htmlReply, "text/html", baseUrl);
226     QWebElement doc = page.mainFrame()->documentElement();
227
228     // Check if the page is reporting an error before parsing it
229     QWebElement errorElement = doc.findFirst("span.errore");
230     if (!errorElement.isNull()) {
231         m_departureSchedules.clear();
232         m_arrivalSchedules.clear();
233         QString errorText = errorElement.toPlainText().trimmed();
234         if (errorText == "localita' non trovata") {
235             setError(tr("Unknown station"));
236         } else {
237             setError(tr("Unknown error"));
238         }
239         qDebug() << "error:" << error();
240         return;
241     }
242     // Find the first div
243     QWebElement current = doc.findFirst("div");
244
245     qDebug() << "skipping to the departures";
246     // Skip to the first div of class corpocentrale, which contains the first
247     // departure-related contents
248     while (!current.classes().contains("corpocentrale")) {
249         current = current.nextSibling();
250         qDebug() << "skipping to the next element";
251         if (current.isNull())
252             break;
253     }
254     // Mark every div as a departure class element; the next corpocentrale
255     // marks the start of the arrivals section
256     qDebug() << "marking departures";
257     do {
258         if (current.classes().contains("bloccorisultato")) {
259             StationScheduleItem schedule = parseResult(current);
260             if (schedule.isValid()) {
261                 m_departureSchedules << schedule;
262             }
263         }
264         current = current.nextSibling();
265         qDebug() << "marking as departures";
266         if (current.isNull())
267             break;
268     } while (!current.classes().contains("corpocentrale"));
269
270     // Mark everything as an arrival, until reaching the footer
271     while (!current.classes().contains("footer")) {
272         if (current.classes().contains("bloccorisultato")) {
273             StationScheduleItem schedule = parseResult(current);
274             if (schedule.isValid()) {
275                 m_arrivalSchedules << schedule;
276             }
277         }
278         current = current.nextSibling();
279         qDebug() << "marking as arrival";
280         if (current.isNull())
281             break;
282     }
283 #endif
284     endResetModel();
285     emit layoutChanged();
286 }
287
288 void StationScheduleModel::onNetworkError()
289 {
290     qDebug()<< "Station Schedule Model got a Network Error";
291     m_error = tr("Network error");
292     emit errorChanged();
293 }
294
295 void StationScheduleModel::fetch(const QString &name, const QString &code)
296 {
297     DataProvider *provider = DataProvider::instance();
298
299     if (!error().isEmpty())
300         setError(QString());
301     m_departureSchedules.clear();
302     m_arrivalSchedules.clear();
303     provider->fetchStationSchedule(name, code);
304     setName(name);
305     setCode(code);
306 }
307
308 int StationScheduleModel::rowCount(const QModelIndex &parent) const
309 {
310     Q_UNUSED(parent);
311     if (m_scheduleType == DepartureSchedule) {
312         return m_departureSchedules.count();
313     } else {
314         return m_arrivalSchedules.count();
315     }
316 }
317
318 QVariant StationScheduleModel::data(const QModelIndex &index, int role) const
319 {
320     if (!index.isValid()) {
321         return QVariant();
322     }
323     const QList<StationScheduleItem> &schedules =
324             (m_scheduleType == DepartureSchedule) ? m_departureSchedules : m_arrivalSchedules;
325     if (index.row() < 0 || index.row() >= schedules.count()) {
326         return QVariant();
327     }
328     StationScheduleItem item = schedules[index.row()];
329     switch (role) {
330     case Qt::DisplayRole:
331     case TrainRole:
332         return QVariant::fromValue(item.train());
333     case DepartureStationRole:
334         return QVariant::fromValue(item.departureStation());
335     case DepartureTimeRole:
336         return QVariant::fromValue(item.departureTime());
337     case ArrivalStationRole:
338         return QVariant::fromValue(item.arrivalStation());
339     case ArrivalTimeRole:
340         return QVariant::fromValue(item.arrivalTime());
341     case DetailsUrlRole:
342         return QVariant::fromValue(item.detailsUrl());
343     case DelayRole:
344         return QVariant::fromValue(item.delay());
345     case DelayClassRole:
346         return QVariant::fromValue(item.delayClass());
347     case ExpectedPlatformRole:
348         return QVariant::fromValue(item.expectedPlatform());
349     case ActualPlatformRole:
350         return QVariant::fromValue(item.actualPlatform());
351     default:
352         return QVariant::fromValue(QString("Unknown role requested"));
353     }
354 }