Sailfish port mostly done, bumped version to 6.0
[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     QWebPage page;
224     page.mainFrame()->setContent(htmlReply, "text/html", baseUrl);
225     QWebElement doc = page.mainFrame()->documentElement();
226
227     // Check if the page is reporting an error before parsing it
228     QWebElement errorElement = doc.findFirst("span.errore");
229     if (!errorElement.isNull()) {
230         m_departureSchedules.clear();
231         m_arrivalSchedules.clear();
232         QString errorText = errorElement.toPlainText().trimmed();
233         if (errorText == "localita' non trovata") {
234             setError(tr("Unknown station"));
235         } else {
236             setError(tr("Unknown error"));
237         }
238         qDebug() << "error:" << error();
239         return;
240     }
241     // Find the first div
242     QWebElement current = doc.findFirst("div");
243
244     qDebug() << "skipping to the departures";
245     // Skip to the first div of class corpocentrale, which contains the first
246     // departure-related contents
247     while (!current.classes().contains("corpocentrale")) {
248         current = current.nextSibling();
249         qDebug() << "skipping to the next element";
250         if (current.isNull())
251             break;
252     }
253     // Mark every div as a departure class element; the next corpocentrale
254     // marks the start of the arrivals section
255     qDebug() << "marking departures";
256     do {
257         if (current.classes().contains("bloccorisultato")) {
258             StationScheduleItem schedule = parseResult(current);
259             if (schedule.isValid()) {
260                 m_departureSchedules << schedule;
261             }
262         }
263         current = current.nextSibling();
264         qDebug() << "marking as departures";
265         if (current.isNull())
266             break;
267     } while (!current.classes().contains("corpocentrale"));
268
269     // Mark everything as an arrival, until reaching the footer
270     while (!current.classes().contains("footer")) {
271         if (current.classes().contains("bloccorisultato")) {
272             StationScheduleItem schedule = parseResult(current);
273             if (schedule.isValid()) {
274                 m_arrivalSchedules << schedule;
275             }
276         }
277         current = current.nextSibling();
278         qDebug() << "marking as arrival";
279         if (current.isNull())
280             break;
281     }
282     endResetModel();
283     emit layoutChanged();
284 }
285
286 void StationScheduleModel::onNetworkError()
287 {
288     qDebug()<< "Station Schedule Model got a Network Error";
289     m_error = tr("Network error");
290     emit errorChanged();
291 }
292
293 void StationScheduleModel::fetch(const QString &name, const QString &code)
294 {
295     DataProvider *provider = DataProvider::instance();
296
297     if (!error().isEmpty())
298         setError(QString());
299     m_departureSchedules.clear();
300     m_arrivalSchedules.clear();
301     provider->fetchStationSchedule(name, code);
302     setName(name);
303     setCode(code);
304 }
305
306 int StationScheduleModel::rowCount(const QModelIndex &parent) const
307 {
308     Q_UNUSED(parent);
309     if (m_scheduleType == DepartureSchedule) {
310         return m_departureSchedules.count();
311     } else {
312         return m_arrivalSchedules.count();
313     }
314 }
315
316 QVariant StationScheduleModel::data(const QModelIndex &index, int role) const
317 {
318     if (!index.isValid()) {
319         return QVariant();
320     }
321     const QList<StationScheduleItem> &schedules =
322             (m_scheduleType == DepartureSchedule) ? m_departureSchedules : m_arrivalSchedules;
323     if (index.row() < 0 || index.row() >= schedules.count()) {
324         return QVariant();
325     }
326     StationScheduleItem item = schedules[index.row()];
327     switch (role) {
328     case Qt::DisplayRole:
329     case TrainRole:
330         return QVariant::fromValue(item.train());
331     case DepartureStationRole:
332         return QVariant::fromValue(item.departureStation());
333     case DepartureTimeRole:
334         return QVariant::fromValue(item.departureTime());
335     case ArrivalStationRole:
336         return QVariant::fromValue(item.arrivalStation());
337     case ArrivalTimeRole:
338         return QVariant::fromValue(item.arrivalTime());
339     case DetailsUrlRole:
340         return QVariant::fromValue(item.detailsUrl());
341     case DelayRole:
342         return QVariant::fromValue(item.delay());
343     case DelayClassRole:
344         return QVariant::fromValue(item.delayClass());
345     case ExpectedPlatformRole:
346         return QVariant::fromValue(item.expectedPlatform());
347     case ActualPlatformRole:
348         return QVariant::fromValue(item.actualPlatform());
349     default:
350         return QVariant::fromValue(QString("Unknown role requested"));
351     }
352 }