diff --git a/engine/departureinfo.cpp b/engine/departureinfo.cpp index 5fdccd7..674e9f8 100644 --- a/engine/departureinfo.cpp +++ b/engine/departureinfo.cpp @@ -1,369 +1,369 @@ /* * Copyright 2012 Friedrich Pülz * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as * published by the Free Software Foundation; either version 2 or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ // Header #include "departureinfo.h" // Own includes #include "global.h" // Qt includes #include PublicTransportInfo::PublicTransportInfo(QObject* parent): QObject(parent) { } PublicTransportInfo::~PublicTransportInfo() { } PublicTransportInfo::PublicTransportInfo( const QHash< Enums::TimetableInformation, QVariant >& data, Corrections corrections, QObject *parent ) : QObject(parent), m_data(data) { m_isValid = false; // Insert -1 as Delay if none is given (-1 means "no delay information available") if ( !contains(Enums::Delay) ) { insert( Enums::Delay, -1 ); } if ( corrections.testFlag(DeduceMissingValues) ) { // Guess date value if none is given, // this could produce wrong dates (better give DepartureDate in scripts) if ( !contains(Enums::DepartureDate) && contains(Enums::DepartureTime) ) { QTime departureTime = value( Enums::DepartureTime ).toTime(); if ( departureTime < QTime::currentTime().addSecs(-5 * 60) ) { qDebug() << "Guessed DepartureDate as tomorrow"; insert( Enums::DepartureDate, QDate::currentDate().addDays(1) ); } else { qDebug() << "Guessed DepartureDate as today"; insert( Enums::DepartureDate, QDate::currentDate() ); } } } if ( corrections.testFlag(CombineToPreferredValueType) ) { // Convert date value from string if not given as date if ( !contains(Enums::DepartureDateTime) ) { if ( contains(Enums::DepartureTime) ) { const QTime time = value( Enums::DepartureTime ).toTime(); QDate date; if ( contains(Enums::DepartureDate) ) { date = value( Enums::DepartureDate ).toDate(); } else if ( time < QTime::currentTime().addSecs(-5 * 60) ) { qDebug() << "Guessed DepartureDate as tomorrow"; date = QDate::currentDate().addDays( 1 ); } else { qDebug() << "Guessed DepartureDate as today"; date = QDate::currentDate(); } insert( Enums::DepartureDateTime, QDateTime(date, time) ); remove( Enums::DepartureDate ); remove( Enums::DepartureTime ); } else { qDebug() << "No DepartureDateTime or DepartureTime information given"; } } } if ( corrections.testFlag(TestValuesForCorrectFormat) ) { // Check RouteTimes values if ( contains(Enums::RouteTimes) ) { if ( value(Enums::RouteTimes).canConvert(QVariant::List) ) { QVariantList vars = value( Enums::RouteTimes ).toList(); foreach ( const QVariant &var, vars ) { // Convert from QVariant to QTime if ( !var.canConvert(QVariant::DateTime) || !var.toDateTime().isValid() ) { // Value for DepartureTime is not QDateTime - kWarning() << "Invalid time in RouteTimes:" << var; + qWarning() << "Invalid time in RouteTimes:" << var; remove( Enums::RouteTimes ); break; } } } else { // No list of values given for RouteTimes, remove the invalid value - kWarning() << "RouteTimes value is invalid (not a list of values): " + qWarning() << "RouteTimes value is invalid (not a list of values): " << value(Enums::RouteTimes); remove( Enums::RouteTimes ); } } } } JourneyInfo::JourneyInfo( const TimetableData &data, Corrections corrections, QObject *parent ) : PublicTransportInfo( data, corrections, parent ) { if ( corrections.testFlag(DeduceMissingValues) ) { // Guess arrival date value if none is given, // this could produce wrong dates (better give ArrivalDate eg. in scripts) if ( !contains(Enums::ArrivalDateTime) && !contains(Enums::ArrivalDate) && contains(Enums::ArrivalTime) ) { QTime arrivalTime = value(Enums::ArrivalTime).toTime(); if ( arrivalTime < QTime::currentTime().addSecs(-5 * 60) ) { insert( Enums::ArrivalDate, QDate::currentDate().addDays(1) ); } else { insert( Enums::ArrivalDate, QDate::currentDate() ); } } // Deduce Duration from DepartureDateTime and ArrivalDateTime if ( value(Enums::Duration).toInt() <= 0 && contains(Enums::DepartureDateTime) && contains(Enums::ArrivalDateTime) ) { QDateTime departure = value( Enums::DepartureDateTime ).toDateTime(); QDateTime arrival = value( Enums::ArrivalDateTime ).toDateTime(); int minsDuration = departure.secsTo( arrival ) / 60; if ( minsDuration < 0 ) { - kWarning() << "Calculated duration is negative" << minsDuration + qWarning() << "Calculated duration is negative" << minsDuration << "departure" << departure << "arrival" << arrival; insert( Enums::Duration, -1 ); } else { insert( Enums::Duration, minsDuration ); } } } // TODO Move to PublicTransportInfo? ...or is it already in there? if ( corrections.testFlag(TestValuesForCorrectFormat) ) { // Test departure time format if ( contains(Enums::DepartureTime) && !value(Enums::DepartureTime).canConvert(QVariant::Time) ) { // Value for DepartureTime is not QTime - kWarning() << "DepartureTime needs to be convertable to QTime:" + qWarning() << "DepartureTime needs to be convertable to QTime:" << value(Enums::DepartureTime); remove( Enums::DepartureTime ); } // Test departure date format if ( contains(Enums::DepartureDate) && (!value(Enums::DepartureDate).canConvert(QVariant::Date) || !value(Enums::DepartureDate).toDate().isValid()) ) { - kWarning() << "DepartureDate needs to be convertable to QDate:" + qWarning() << "DepartureDate needs to be convertable to QDate:" << value( Enums::DepartureDate ); remove( Enums::DepartureDate ); } // Check ArrivalDate value if ( contains(Enums::ArrivalDate) && (!value(Enums::ArrivalDate).canConvert(QVariant::Date) || !value(Enums::ArrivalDate).toDate().isValid()) ) { - kWarning() << "ArrivalDate needs to be convertable to QDate:" + qWarning() << "ArrivalDate needs to be convertable to QDate:" << value(Enums::ArrivalDate); remove( Enums::ArrivalDate ); } // Check Duration value if ( contains(Enums::Duration) && value(Enums::Duration).toInt() <= 0 && value(Enums::Duration).canConvert(QVariant::String) ) { - kWarning() << "Duration needs to be convertable to int:" << value(Enums::Duration); + qWarning() << "Duration needs to be convertable to int:" << value(Enums::Duration); remove( Enums::Duration ); } // Check RouteTimesDeparture values if ( contains(Enums::RouteTimesDeparture) ) { if ( !value(Enums::RouteTimesDeparture).canConvert(QVariant::List) ) { - kWarning() << "Value for RouteTimesDeparture needs to be a list" + qWarning() << "Value for RouteTimesDeparture needs to be a list" << value(Enums::RouteTimesDeparture); remove( Enums::RouteTimesDeparture ); } else { QVariantList vars = value( Enums::RouteTimesDeparture ).toList(); foreach( const QVariant &var, vars ) { if ( !var.canConvert(QVariant::DateTime) ) { - kWarning() << "Invalid time in RouteTimesDeparture" << var; + qWarning() << "Invalid time in RouteTimesDeparture" << var; remove( Enums::RouteTimesDeparture ); break; } } } } // Check RouteTimesArrival values if ( contains(Enums::RouteTimesArrival) ) { if ( !value(Enums::RouteTimesArrival).canConvert(QVariant::List) ) { - kWarning() << "Value for RouteTimesArrival needs to be a list" + qWarning() << "Value for RouteTimesArrival needs to be a list" << value(Enums::RouteTimesArrival); remove( Enums::RouteTimesArrival ); } else { QVariantList vars = value( Enums::RouteTimesArrival ).toList(); foreach( const QVariant &var, vars ) { if ( !var.canConvert(QVariant::DateTime) ) { - kWarning() << "Invalid time in RouteTimesArrival" << var; + qWarning() << "Invalid time in RouteTimesArrival" << var; remove( Enums::RouteTimesArrival ); break; } } } } } if ( corrections.testFlag(CombineToPreferredValueType) ) { // If the duration value is invalid, but there are departure and arrival date and time // values available, calculate the duration between departure and arrival if ( value(Enums::Duration).toInt() <= 0 && contains(Enums::DepartureDate) && contains(Enums::DepartureTime) && contains(Enums::ArrivalDate) && contains(Enums::ArrivalTime) ) { QDateTime departure( value(Enums::DepartureDate).toDate(), value(Enums::ArrivalTime).toTime() ); QDateTime arrival( value(Enums::ArrivalDate).toDate(), value(Enums::ArrivalTime).toTime() ); int minsDuration = departure.secsTo( arrival ) / 60; if ( minsDuration < 0 ) { qDebug() << "Calculated duration is negative" << minsDuration << "departure" << departure << "arrival" << arrival; insert( Enums::Duration, -1 ); } else { insert( Enums::Duration, minsDuration ); } } // Combine ArrivalTime and ArrivalDate to ArrivalDateTime if ( !contains(Enums::ArrivalDateTime) ) { if ( contains(Enums::ArrivalTime) ) { const QTime time = value( Enums::ArrivalTime ).toTime(); QDate date; if ( contains(Enums::ArrivalDate) ) { date = value( Enums::ArrivalDate ).toDate(); } else if ( time < QTime::currentTime().addSecs(-5 * 60) ) { qDebug() << "Guessed ArrivalDate as tomorrow"; date = QDate::currentDate().addDays( 1 ); } else { qDebug() << "Guessed ArrivalDate as today"; date = QDate::currentDate(); } insert( Enums::ArrivalDateTime, QDateTime(date, time) ); remove( Enums::ArrivalDate ); remove( Enums::ArrivalTime ); } else { - kWarning() << "No ArrivalDateTime or ArrivalTime information given"; + qWarning() << "No ArrivalDateTime or ArrivalTime information given"; } } } m_isValid = contains(Enums::DepartureDateTime) && contains(Enums::ArrivalDateTime) && contains(Enums::StartStopName) && contains(Enums::TargetStopName); } StopInfo::StopInfo( QObject *parent ) : PublicTransportInfo(parent) { m_isValid = false; } StopInfo::StopInfo( const QHash< Enums::TimetableInformation, QVariant >& data, QObject *parent ) : PublicTransportInfo(parent) { m_data.unite( data ); m_isValid = contains( Enums::StopName ); } StopInfo::StopInfo( const QString &name, const QString& id, int weight, qreal longitude, qreal latitude, const QString &city, const QString &countryCode, QObject *parent ) : PublicTransportInfo(parent) { insert( Enums::StopName, name ); if ( !id.isNull() ) { insert( Enums::StopID, id ); } if ( longitude != 0.0 ) { insert( Enums::StopLongitude, longitude ); } if ( latitude != 0.0 ) { insert( Enums::StopLatitude, latitude ); } if ( !city.isNull() ) { insert( Enums::StopCity, city ); } if ( !countryCode.isNull() ) { insert( Enums::StopCountryCode, countryCode ); } if ( weight != -1 ) { insert( Enums::StopWeight, weight ); } m_isValid = !name.isEmpty(); } DepartureInfo::DepartureInfo( QObject *parent ) : PublicTransportInfo(parent) { m_isValid = false; } DepartureInfo::DepartureInfo( const TimetableData &data, Corrections corrections, QObject *parent ) : PublicTransportInfo( data, corrections, parent ) { if ( (contains(Enums::RouteStops) || contains(Enums::RouteTimes)) && value(Enums::RouteTimes).toList().count() != value(Enums::RouteStops).toStringList().count() ) { int difference = value(Enums::RouteStops).toList().count() - value(Enums::RouteTimes).toList().count(); if ( difference > 0 ) { // More route stops than times, add invalid times qDebug() << "The script stored" << difference << "more route stops than route times " "for a departure, invalid route times will be added"; QVariantList routeTimes = value( Enums::RouteTimes ).toList(); while ( difference > 0 ) { routeTimes << QDateTime(); --difference; } } else { // More route times than stops, add empty stops qDebug() << "The script stored" << -difference << "more route times than route " "stops for a departure, empty route stops will be added"; QStringList routeStops = value( Enums::RouteStops ).toStringList(); while ( difference < 0 ) { routeStops << QString(); ++difference; } } } m_isValid = contains( Enums::TransportLine ) && contains( Enums::Target ) && contains( Enums::DepartureDateTime ); } QStringList JourneyInfo::vehicleIconNames() const { if ( !contains(Enums::TypesOfVehicleInJourney) ) { return QStringList(); } QVariantList vehicles = value( Enums::TypesOfVehicleInJourney ).toList(); QStringList iconNames; foreach( QVariant vehicle, vehicles ) { iconNames << Global::vehicleTypeToIcon( static_cast( vehicle.toInt() ) ); } return iconNames; } QStringList JourneyInfo::vehicleNames( bool plural ) const { if ( !contains( Enums::TypesOfVehicleInJourney ) ) { return QStringList(); } QVariantList vehicles = value( Enums::TypesOfVehicleInJourney ).toList(); QStringList names; foreach( QVariant vehicle, vehicles ) { names << Global::vehicleTypeToString( static_cast( vehicle.toInt() ), plural ); } return names; } diff --git a/engine/global.cpp b/engine/global.cpp index c098048..00ab5f3 100644 --- a/engine/global.cpp +++ b/engine/global.cpp @@ -1,439 +1,439 @@ /* * Copyright 2012 Friedrich Pülz * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as * published by the Free Software Foundation; either version 2 or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ // Header #include "global.h" // KDE includes #include // Qt includes #include #include #include Enums::VehicleType Global::vehicleTypeFromString( QString sVehicleType ) { return Enums::stringToVehicleType( sVehicleType.toAscii().data() ); } QString Global::vehicleTypeToString( const Enums::VehicleType& vehicleType, bool plural ) { switch ( vehicleType ) { case Enums::Tram: return plural ? i18nc( "@info/plain", "trams" ) : i18nc( "@info/plain", "tram" ); case Enums::Bus: return plural ? i18nc( "@info/plain", "buses" ) : i18nc( "@info/plain", "bus" ); case Enums::Subway: return plural ? i18nc( "@info/plain", "subways" ) : i18nc( "@info/plain", "subway" ); case Enums::InterurbanTrain: return plural ? i18nc( "@info/plain", "interurban trains" ) : i18nc( "@info/plain", "interurban train" ); case Enums::Metro: return plural ? i18nc( "@info/plain", "metros" ) : i18nc( "@info/plain", "metro" ); case Enums::TrolleyBus: return plural ? i18nc( "@info/plain", "trolley buses" ) : i18nc( "@info/plain", "trolley bus" ); case Enums::RegionalTrain: return plural ? i18nc( "@info/plain", "regional trains" ) : i18nc( "@info/plain", "regional train" ); case Enums::RegionalExpressTrain: return plural ? i18nc( "@info/plain", "regional express trains" ) : i18nc( "@info/plain", "regional express train" ); case Enums::InterregionalTrain: return plural ? i18nc( "@info/plain", "interregional trains" ) : i18nc( "@info/plain", "interregional train" ); case Enums::IntercityTrain: return plural ? i18nc( "@info/plain", "intercity / eurocity trains" ) : i18nc( "@info/plain", "intercity / eurocity train" ); case Enums::HighSpeedTrain: return plural ? i18nc( "@info/plain", "intercity express trains" ) : i18nc( "@info/plain", "intercity express train" ); case Enums::Feet: return i18nc( "@info/plain", "Footway" ); case Enums::Ferry: return plural ? i18nc( "@info/plain", "ferries" ) : i18nc( "@info/plain", "ferry" ); case Enums::Ship: return plural ? i18nc( "@info/plain", "ships" ) : i18nc( "@info/plain", "ship" ); case Enums::Plane: return plural ? i18nc( "@info/plain airplanes", "planes" ) : i18nc( "@info/plain an airplane", "plane" ); case Enums::UnknownVehicleType: default: return i18nc( "@info/plain Unknown type of vehicle", "Unknown" ); } } QString Global::vehicleTypeToIcon( const Enums::VehicleType& vehicleType ) { switch ( vehicleType ) { case Enums::Tram: return "vehicle_type_tram"; case Enums::Bus: return "vehicle_type_bus"; case Enums::Subway: return "vehicle_type_subway"; case Enums::Metro: return "vehicle_type_metro"; case Enums::TrolleyBus: return "vehicle_type_trolleybus"; case Enums::Feet: return "vehicle_type_feet"; case Enums::InterurbanTrain: return "vehicle_type_train_interurban"; case Enums::RegionalTrain: // aIcon not done yet, using this for now case Enums::RegionalExpressTrain: return "vehicle_type_train_regional"; case Enums::InterregionalTrain: return "vehicle_type_train_interregional"; case Enums::IntercityTrain: return "vehicle_type_train_intercity"; case Enums::HighSpeedTrain: return "vehicle_type_train_highspeed"; case Enums::Ferry: case Enums::Ship: return "vehicle_type_ferry"; case Enums::Plane: return "vehicle_type_plane"; case Enums::UnknownVehicleType: default: return "status_unknown"; } } Enums::TimetableInformation Global::timetableInformationFromString( const QString& sTimetableInformation ) { const QString sInfo = sTimetableInformation.toLower(); if ( sInfo == QLatin1String("nothing") ) { return Enums::Nothing; } else if ( sInfo == QLatin1String("departuredatetime") ) { return Enums::DepartureDateTime; } else if ( sInfo == QLatin1String("departuredate") ) { return Enums::DepartureDate; } else if ( sInfo == QLatin1String("departuretime") ) { return Enums::DepartureTime; } else if ( sInfo == QLatin1String("typeofvehicle") ) { return Enums::TypeOfVehicle; } else if ( sInfo == QLatin1String("transportline") ) { return Enums::TransportLine; } else if ( sInfo == QLatin1String("flightnumber") ) { return Enums::FlightNumber; } else if ( sInfo == QLatin1String("target") ) { return Enums::Target; } else if ( sInfo == QLatin1String("targetshortened") ) { return Enums::TargetShortened; } else if ( sInfo == QLatin1String("platform") ) { return Enums::Platform; } else if ( sInfo == QLatin1String("delay") ) { return Enums::Delay; } else if ( sInfo == QLatin1String("delayreason") ) { return Enums::DelayReason; } else if ( sInfo == QLatin1String("journeynews") ) { return Enums::JourneyNews; } else if ( sInfo == QLatin1String("journeynewsother") ) { // DEPRECATED - kWarning() << "JourneyNewsOther is deprecated, use JourneyNews instead"; + qWarning() << "JourneyNewsOther is deprecated, use JourneyNews instead"; return Enums::JourneyNewsOther; } else if ( sInfo == QLatin1String("journeynewslink") ) { // DEPRECATED - kWarning() << "JourneyNewsLink is deprecated, use JourneyNewsUrl instead"; + qWarning() << "JourneyNewsLink is deprecated, use JourneyNewsUrl instead"; return Enums::JourneyNewsUrl; } else if ( sInfo == QLatin1String("journeynewsurl") ) { return Enums::JourneyNewsUrl; } else if ( sInfo == QLatin1String("status") ) { return Enums::Status; } else if ( sInfo == QLatin1String("routestops") ) { return Enums::RouteStops; } else if ( sInfo == QLatin1String("routestopsshortened") ) { return Enums::RouteStopsShortened; } else if ( sInfo == QLatin1String("routetimes") ) { return Enums::RouteTimes; } else if ( sInfo == QLatin1String("routetimesdeparture") ) { return Enums::RouteTimesDeparture; } else if ( sInfo == QLatin1String("routetimesarrival") ) { return Enums::RouteTimesArrival; } else if ( sInfo == QLatin1String("routeexactstops") ) { return Enums::RouteExactStops; } else if ( sInfo == QLatin1String("routetypesofvehicles") ) { return Enums::RouteTypesOfVehicles; } else if ( sInfo == QLatin1String("routetransportlines") ) { return Enums::RouteTransportLines; } else if ( sInfo == QLatin1String("routeplatformsdeparture") ) { return Enums::RoutePlatformsDeparture; } else if ( sInfo == QLatin1String("routeplatformsarrival") ) { return Enums::RoutePlatformsArrival; } else if ( sInfo == QLatin1String("routetimesdeparturedelay") ) { return Enums::RouteTimesDepartureDelay; } else if ( sInfo == QLatin1String("routetimesarrivaldelay") ) { return Enums::RouteTimesArrivalDelay; } else if ( sInfo == QLatin1String("routenews") ) { return Enums::RouteNews; } else if ( sInfo == QLatin1String("routesubjourneys") ) { return Enums::RouteSubJourneys; } else if ( sInfo == QLatin1String("routedataurl") ) { return Enums::RouteDataUrl; } else if ( sInfo == QLatin1String("operator") ) { return Enums::Operator; } else if ( sInfo == QLatin1String("duration") ) { return Enums::Duration; } else if ( sInfo == QLatin1String("startstopname") ) { return Enums::StartStopName; } else if ( sInfo == QLatin1String("startstopid") ) { return Enums::StartStopID; } else if ( sInfo == QLatin1String("targetstopname") ) { return Enums::TargetStopName; } else if ( sInfo == QLatin1String("targetstopid") ) { return Enums::TargetStopID; } else if ( sInfo == QLatin1String("arrivaldatetime") ) { return Enums::ArrivalDateTime; } else if ( sInfo == QLatin1String("arrivaldate") ) { return Enums::ArrivalDate; } else if ( sInfo == QLatin1String("arrivaltime") ) { return Enums::ArrivalTime; } else if ( sInfo == QLatin1String("changes") ) { return Enums::Changes; } else if ( sInfo == QLatin1String("typesofvehicleinjourney") ) { return Enums::TypesOfVehicleInJourney; } else if ( sInfo == QLatin1String("pricing") ) { return Enums::Pricing; } else if ( sInfo == QLatin1String("isnightline") ) { return Enums::IsNightLine; } else if ( sInfo == QLatin1String("stopname") ) { return Enums::StopName; } else if ( sInfo == QLatin1String("stopid") ) { return Enums::StopID; } else if ( sInfo == QLatin1String("stopweight") ) { return Enums::StopWeight; } else if ( sInfo == QLatin1String("stopcity") ) { return Enums::StopCity; } else if ( sInfo == QLatin1String("stopcountrycode") ) { return Enums::StopCountryCode; } else if ( sInfo == QLatin1String("stoplongitude") ) { return Enums::StopLongitude; } else if ( sInfo == QLatin1String("stoplatitude") ) { return Enums::StopLatitude; } else if ( sInfo == QLatin1String("requestdata") ) { return Enums::RequestData; } else { qDebug() << sTimetableInformation << "is an unknown timetable information value! Assuming value Nothing."; return Enums::Nothing; } } QString Global::timetableInformationToString( Enums::TimetableInformation timetableInformation ) { return Enums::toString( timetableInformation ); } bool Global::checkTimetableInformation( Enums::TimetableInformation info, const QVariant &value ) { if ( !value.isValid() ) { return false; } switch ( info ) { case Enums::DepartureDateTime: case Enums::ArrivalDateTime: return value.toDateTime().isValid(); case Enums::DepartureDate: case Enums::ArrivalDate: return value.toDate().isValid(); case Enums::DepartureTime: case Enums::ArrivalTime: return value.toTime().isValid(); case Enums::TypeOfVehicle: return vehicleTypeFromString( value.toString() ) != Enums::UnknownVehicleType; case Enums::TransportLine: case Enums::Target: case Enums::TargetShortened: case Enums::Platform: case Enums::DelayReason: case Enums::JourneyNews: case Enums::JourneyNewsOther: // DEPRECATED case Enums::JourneyNewsUrl: case Enums::Operator: case Enums::Status: case Enums::StartStopName: case Enums::StartStopID: case Enums::StopCity: case Enums::StopCountryCode: case Enums::TargetStopName: case Enums::TargetStopID: case Enums::Pricing: case Enums::StopName: case Enums::StopID: case Enums::RouteDataUrl: return !value.toString().trimmed().isEmpty(); case Enums::StopLongitude: case Enums::StopLatitude: if ( !value.canConvert(QVariant::Double) ) { return false; } else { bool ok; (void) value.toReal( &ok ); return ok; } case Enums::Delay: return value.canConvert( QVariant::Int ) && value.toInt() >= -1; case Enums::Duration: case Enums::StopWeight: case Enums::Changes: case Enums::RouteExactStops: return value.canConvert( QVariant::Int ) && value.toInt() >= 0; case Enums::TypesOfVehicleInJourney: case Enums::RouteTimes: case Enums::RouteTimesDeparture: case Enums::RouteTimesArrival: case Enums::RouteTypesOfVehicles: case Enums::RouteTimesDepartureDelay: case Enums::RouteTimesArrivalDelay: case Enums::RouteSubJourneys: return !value.toList().isEmpty(); case Enums::IsNightLine: return value.canConvert( QVariant::Bool ); case Enums::RouteStops: case Enums::RouteStopsShortened: case Enums::RouteTransportLines: case Enums::RoutePlatformsDeparture: case Enums::RoutePlatformsArrival: case Enums::RouteNews: return !value.toStringList().isEmpty(); case Enums::RequestData: default: return true; } } QString Global::decodeHtmlEntities( const QString& html ) { if ( html.isEmpty() ) { return html; } QString ret = html; QRegExp rx( "(?:&#)([0-9]+)(?:;)" ); rx.setMinimal( true ); int pos = 0; while ( (pos = rx.indexIn(ret, pos)) != -1 ) { const int charCode = rx.cap( 1 ).toInt(); ret.replace( QString("&#%1;").arg(charCode), QChar(charCode) ); } return ret.replace( QLatin1String(" "), QLatin1String(" ") ) .replace( QLatin1String("&"), QLatin1String("&") ) .replace( QLatin1String("<"), QLatin1String("<") ) .replace( QLatin1String(">"), QLatin1String(">") ) .replace( QLatin1String("ß"), QLatin1String("ß") ) .replace( QLatin1String("ä"), QLatin1String("ä") ) .replace( QLatin1String("Ä"), QLatin1String("Ä") ) .replace( QLatin1String("ö"), QLatin1String("ö") ) .replace( QLatin1String("Ö"), QLatin1String("Ö") ) .replace( QLatin1String("ü"), QLatin1String("ü") ) .replace( QLatin1String("Ü"), QLatin1String("Ü") ); } QString Global::encodeHtmlEntities( const QString &html, HtmlEntityEncodeFlags flags ) { if ( html.isEmpty() ) { return html; } QString ret = html; if ( flags.testFlag(EncodeLessThan) ) { ret.replace( QLatin1String("<"), QLatin1String("<") ); } if ( flags.testFlag(EncodeGreaterThan) ) { ret.replace( QLatin1String(">"), QLatin1String(">") ); } if ( flags.testFlag(EncodeAmpersand) ) { ret.replace( QLatin1String("&"), QLatin1String("&") ); } if ( flags.testFlag(EncodeUmlauts) ) { ret.replace( QLatin1String("ß"), QLatin1String("ß") ) .replace( QLatin1String("ä"), QLatin1String("ä") ) .replace( QLatin1String("Ä"), QLatin1String("Ä") ) .replace( QLatin1String("ö"), QLatin1String("ö") ) .replace( QLatin1String("Ö"), QLatin1String("Ö") ) .replace( QLatin1String("ü"), QLatin1String("ü") ) .replace( QLatin1String("Ü"), QLatin1String("Ü") ); } if ( flags.testFlag(EncodeSpace) ) { ret.replace( QLatin1String(" "), QLatin1String(" ") ); } return ret; } QString Global::decodeHtml( const QByteArray& document, const QByteArray& fallbackCharset ) { // Get charset of the received document and convert it to a unicode QString // First parse the charset with a regexp to get a fallback charset // if QTextCodec::codecForHtml doesn't find the charset QTextCodec *textCodec = QTextCodec::codecForHtml( document, 0 ); if ( textCodec ) { return textCodec->toUnicode( document ); } else { if ( !fallbackCharset.isEmpty() ) { textCodec = QTextCodec::codecForName( fallbackCharset ); if ( !textCodec ) { qDebug() << "Fallback charset" << fallbackCharset << "not found! Using utf8 now."; textCodec = QTextCodec::codecForName( "UTF-8" ); } } else { QString sDocument = QString( document ); QRegExp rxCharset( "(?:.*]*>)", Qt::CaseInsensitive ); rxCharset.setMinimal( true ); if ( rxCharset.indexIn(sDocument) != -1 ) { textCodec = QTextCodec::codecForName( rxCharset.cap(1).trimmed().toUtf8() ); } else { qDebug() << "No fallback charset specified and manual codec search failed, using utf8"; textCodec = QTextCodec::codecForName( "UTF-8" ); } } return textCodec ? textCodec->toUnicode(document) : QString::fromUtf8(document); } } QString Global::decode( const QByteArray &document, const QByteArray &charset ) { if ( !charset.isEmpty() ) { QTextCodec *textCodec = QTextCodec::codecForName( charset ); if ( !textCodec ) { qDebug() << "Charset" << charset << "not found! Using utf8 now."; textCodec = QTextCodec::codecForName( "UTF-8" ); } return textCodec->toUnicode( document ); } else { return QString::fromUtf8( document ); } } diff --git a/engine/gtfs/gtfsimporter.cpp b/engine/gtfs/gtfsimporter.cpp index 338bdc1..eacb4a1 100644 --- a/engine/gtfs/gtfsimporter.cpp +++ b/engine/gtfs/gtfsimporter.cpp @@ -1,790 +1,790 @@ /* * Copyright 2012 Friedrich Pülz * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as * published by the Free Software Foundation; either version 2 or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "gtfsimporter.h" #include "gtfsdatabase.h" #include "serviceproviderdatareader.h" #include "serviceproviderdata.h" #include #include #include #include #include #include #include #include #include #include #include GtfsImporter::GtfsImporter( const QString &providerName ) : m_state(Initializing), m_providerName(providerName), m_quit(false) { // Register state enum to be able to use it in queued connections qRegisterMetaType< GtfsImporter::State >( "GtfsImporter::State" ); QMutexLocker locker( &m_mutex ); // Delete already existing database, if any, to prevent failure due to a corrupted database const QString databasePath = GtfsDatabase::databasePath( m_providerName ); if ( QFile::exists(databasePath) ) { // Remove the database file and the connection to it GtfsDatabase::closeDatabase( m_providerName ); if ( !QFile::remove(databasePath) ) { - kWarning() << "Already existing GTFS database for" << m_providerName + qWarning() << "Already existing GTFS database for" << m_providerName << "could not be removed" << databasePath; } } if ( !GtfsDatabase::initDatabase(providerName, &m_errorString) ) { m_state = FatalError; kDebug() << m_errorString; } else { m_state = Initialized; } } GtfsImporter::~GtfsImporter() { QMutexLocker locker( &m_mutex ); m_quit = true; } void GtfsImporter::quit() { QMutexLocker locker( &m_mutex ); if ( m_state == Importing ) { kDebug() << "Quits at next checkpoint"; } m_quit = true; } void GtfsImporter::suspend() { QMutexLocker locker( &m_mutex ); if ( m_state == Importing ) { m_state = ImportingSuspended; kDebug() << "Suspend"; } } void GtfsImporter::resume() { QMutexLocker locker( &m_mutex ); if ( m_state == ImportingSuspended ) { m_state = Importing; } } void GtfsImporter::startImport( const QString &fileName ) { m_mutex.lock(); m_fileName = fileName; m_mutex.unlock(); start( LowPriority ); } void GtfsImporter::setError( GtfsImporter::State errorState, const QString &errorText ) { m_mutex.lock(); if ( errorState <= m_state ) { // A more or equally fatal error is already recorded m_mutex.unlock(); return; } m_state = errorState; m_errorString = errorText; m_mutex.unlock(); kDebug() << errorText; if ( errorState == FatalError ) { emit logMessage( i18nc("@info/plain GTFS feed import logbook entry", "Fatal error: %1", errorText) ); emit finished( errorState, errorText ); } else { emit logMessage( i18nc("@info/plain GTFS feed import logbook entry", "Error: %1", errorText) ); } } bool GtfsImporter::checkFileList( const QStringList &requiredFiles, const QStringList &availableFiles, QStringList *missingFiles ) { *missingFiles = requiredFiles; foreach ( const QString &file, availableFiles ) { missingFiles->removeOne( file ); } return missingFiles->isEmpty(); } const KArchiveDirectory *GtfsImporter::findFeedDataDirectory( const KArchiveDirectory *directory, const QStringList &requiredFiles, QStringList *missingFiles, int level ) { // Do not recurse too deep if ( level > 10 ) { return 0; } // Test if the current directory is the GTFS feed data directory QStringList directoryEntries = directory->entries(); if ( checkFileList(requiredFiles, directoryEntries, missingFiles) ) { // The given directory contains all required files return directory; } else if ( missingFiles->count() < requiredFiles.count() ) { // At least one required field has been found, // most probably this is the data directory, but some files are missing return directory; } // Test subdirectories foreach ( const QString &directoryEntry, directoryEntries ) { const KArchiveEntry *entry = directory->entry( directoryEntry ); if ( entry->isDirectory() ) { kDebug() << "Search GTFS feed data directory in level" << level << entry->name(); const KArchiveDirectory *subDirectory = dynamic_cast< const KArchiveDirectory* >( entry ); const KArchiveDirectory *foundDirectory = findFeedDataDirectory( subDirectory, requiredFiles, missingFiles, level + 1 ); if ( foundDirectory ) { // The GTFS data files have been found inside this directory return foundDirectory; } } } // Did not find the GTFS feed data directory return 0; } void GtfsImporter::run() { m_mutex.lock(); m_state = Importing; const QString fileName = m_fileName; const QString providerName = m_providerName; QSqlDatabase database = GtfsDatabase::database( m_providerName ); m_mutex.unlock(); emit logMessage( i18nc("@info/plain GTFS feed import logbook entry", "Start import of GTFS feed for %1", providerName) ); // stop_times.txt is the biggest, importing it takes most time QStringList requiredFiles; requiredFiles << "agency.txt" << "stops.txt" << "routes.txt" << "trips.txt" << "stop_times.txt"; KZip gtfsZipFile( fileName ); if ( !gtfsZipFile.open(QIODevice::ReadOnly) ) { setError( FatalError, "Can not open file " + fileName + ": " + gtfsZipFile.device()->errorString() ); return; } const QString tmpGtfsDir = KGlobal::dirs()->saveLocation( "tmp", QFileInfo(fileName).fileName() + "_dir/" ); // Find the GTFS feed data directory, containing the .txt files, eg. stop_times.txt QStringList missingFiles; const KArchiveDirectory *feedDataDirectory = findFeedDataDirectory( gtfsZipFile.directory(), requiredFiles, &missingFiles ); if ( !missingFiles.isEmpty() ) { kDebug() << "Required file(s) missing in GTFS feed: " << missingFiles.join(", "); setError( FatalError, i18ncp("@info/plain", "Required file missing in GTFS feed: %1", "Required files missing in GTFS feed: %1", missingFiles.join(", ")) ); return; } Q_ASSERT( feedDataDirectory ); // Extract data directory of the GTFS feed feedDataDirectory->copyTo( tmpGtfsDir ); gtfsZipFile.close(); // Calculate total file size (for progress calculations) QFileInfoList fileInfos = QDir( tmpGtfsDir ).entryInfoList( QDir::Files | QDir::NoDotAndDotDot ); qint64 totalFileSize = 0; foreach ( const QFileInfo &fileInfo, fileInfos ) { totalFileSize += fileInfo.size(); } QString errorText; if ( !GtfsDatabase::createDatabaseTables(&errorText, database) ) { setError( FatalError, "Error initializing tables in the database: " + errorText ); return; } bool errors = false; qint64 totalFilePosition = 0; foreach ( const QFileInfo &fileInfo, fileInfos ) { QStringList requiredFields; int minimalRecordCount = 0; if ( fileInfo.fileName() == "agency.txt" ) { requiredFields << "agency_name" << "agency_url" << "agency_timezone"; } else if ( fileInfo.fileName() == "stops.txt" ) { requiredFields << "stop_id" << "stop_name" << "stop_lat" << "stop_lon"; minimalRecordCount = 1; } else if ( fileInfo.fileName() == "routes.txt" ) { requiredFields << "route_id" << "route_short_name" << "route_long_name" << "route_type"; minimalRecordCount = 1; } else if ( fileInfo.fileName() == "trips.txt" ) { requiredFields << "trip_id" << "route_id" << "service_id"; minimalRecordCount = 1; } else if ( fileInfo.fileName() == "stop_times.txt" ) { requiredFields << "trip_id" << "arrival_time" << "departure_time" << "stop_id" << "stop_sequence"; minimalRecordCount = 1; } else if ( fileInfo.fileName() == "calendar.txt" ) { requiredFields << "service_id" << "monday" << "tuesday" << "wednesday" << "thursday" << "friday" << "saturday" << "sunday" << "start_date" << "end_date"; } else if ( fileInfo.fileName() == "calendar_dates.txt" ) { requiredFields << "service_id" << "date" << "exception_type"; } else if ( fileInfo.fileName() == "fare_attributes.txt" ) { requiredFields << "fare_id" << "price" << "currency_type" << "payment_method" << "transfers"; } else if ( fileInfo.fileName() == "fare_rules.txt" ) { requiredFields << "fare_id"; } else if ( fileInfo.fileName() == "shapes.txt" ) { emit logMessage( i18nc("@info/plain GTFS feed import logbook entry", "Skip shapes.txt, data is unused") ); // requiredFields << "shape_id" << "shape_pt_lat" << "shape_pt_lon" << "shape_pt_sequence"; totalFilePosition += fileInfo.size(); continue; } else if ( fileInfo.fileName() == "frequencies.txt" ) { requiredFields << "trip_id" << "start_time" << "end_time" << "headway_secs"; } else if ( fileInfo.fileName() == "transfers.txt" ) { requiredFields << "from_stop_id" << "to_stop_id" << "transfer_type"; } else { kDebug() << "Unexpected filename:" << fileInfo.fileName(); emit logMessage( i18nc("@info/plain GTFS feed import logbook entry", "Unexpected filename: %1", fileInfo.fileName()) ); totalFilePosition += fileInfo.size(); continue; } if ( !writeGtfsDataToDatabase(database, fileInfo.filePath(), requiredFields, minimalRecordCount, totalFilePosition, totalFileSize) ) { errors = true; } totalFilePosition += fileInfo.size(); emit progress( qreal(totalFilePosition) / qreal(totalFileSize), fileInfo.baseName() ); m_mutex.lock(); if ( m_quit ) { m_mutex.unlock(); setError( FatalError, "Importing was cancelled" ); return; } m_mutex.unlock(); } m_mutex.lock(); m_state = errors ? FinishedWithErrors : FinishedSuccessfully; kDebug() << "Importer finished" << m_providerName; if ( errors ) { emit logMessage( i18nc("@info/plain GTFS feed import logbook entry", "Import finished with error %1", m_errorString) ); } else { emit logMessage( i18nc("@info/plain GTFS feed import logbook entry", "Import finished successfully") ); } const QString errorString = m_errorString; m_mutex.unlock(); emit finished( errors ? FinishedWithErrors : FinishedSuccessfully, errorString ); return; } bool GtfsImporter::writeGtfsDataToDatabase( QSqlDatabase database, const QString &fileName, const QStringList &requiredFields, int minimalRecordCount, qint64 totalFilePosition, qint64 totalFileSize ) { // Open the file QFile file( fileName ); if ( !file.open(QIODevice::ReadOnly) ) { setError( FatalError, "Cannot open file " + fileName ); return false; } // Check if the file is empty if ( file.atEnd() ) { file.close(); if ( minimalRecordCount == 0 ) { return true; } else { setError( FatalError, "Empty file " + fileName ); return false; } } // Open the database if ( !database.isValid() || !database.isOpen() ) { file.close(); setError( FatalError, "Can not open database" ); return false; } const QString tableName = QFileInfo(file).baseName(); emit logMessage( i18nc("@info/plain GTFS feed import logbook entry", "Import GTFS data for table %1", tableName) ); // Read first line from file (header with used field names) QStringList fieldNames; if ( file.atEnd() || !readHeader(decode(file.readLine()), &fieldNames, requiredFields) ) { file.close(); return false; // Error in header } // Get types of the fields QList fieldTypes; foreach ( const QString &fieldName, fieldNames ) { fieldTypes << GtfsDatabase::typeOfField( fieldName ); } QSqlRecord table = database.record( tableName ); QStringList unavailableFieldNames; // Field names not used in the database QList unavailableFieldIndices; for ( int i = fieldNames.count() - 1; i >= 0; --i ) { const QString fieldName = fieldNames[i]; if ( !table.contains(fieldName) && fieldName != "monday" && fieldName != "tuesday" && fieldName != "wednesday" && fieldName != "thursday" && fieldName != "friday" && fieldName != "saturday" && fieldName != "sunday" ) { // The current field name is not available in the database, skip it's value in each row unavailableFieldNames << fieldNames[i]; unavailableFieldIndices << i; fieldNames.removeAt( i ); } } if ( !unavailableFieldNames.isEmpty() ) { kDebug() << "Not all used fields are available in the database:" << unavailableFieldNames << "table:" << tableName; emit logMessage( i18nc("@info/plain GTFS feed import logbook entry", "Not all used fields are available in table %1: %2", tableName, unavailableFieldNames.join(", ")) ); } QStringList dbFieldNames = fieldNames; QStringList missingRequiredFields; // Fields that are required and missing, but available in provider data if ( tableName == QLatin1String("calendar") ) { // All day fields in GTFS feeds get combined into "weekdays" in the database // (a string with "1" or "0" for each day) dbFieldNames.removeOne( "monday" ); dbFieldNames.removeOne( "tuesday" ); dbFieldNames.removeOne( "wednesday" ); dbFieldNames.removeOne( "thursday" ); dbFieldNames.removeOne( "friday" ); dbFieldNames.removeOne( "saturday" ); dbFieldNames.removeOne( "sunday" ); dbFieldNames.append( "weekdays" ); } else if ( tableName == QLatin1String("agency") ) { const QStringList requiredAgencyFields = QStringList() << "agency_name" << "agency_url" << "agency_timezone"; foreach ( const QString &requiredAgencyField, requiredAgencyFields ) { if ( !fieldNames.contains(requiredAgencyField) ) { missingRequiredFields << requiredAgencyField; } } if ( !missingRequiredFields.isEmpty() ) { dbFieldNames = QStringList() << "agency_id" << "agency_name" << "agency_url" << "agency_timezone"; } } QString placeholder( '?' ); for ( int i = 1; i < dbFieldNames.count(); ++i ) { placeholder += ",?"; } // Simple benchmark, prints the time it took until the Block got destructed KDebug::Block insertBlock( ("Import GTFS table " + tableName).toUtf8() ); // Create a query for the database QSqlQuery query( database ); // Performance optimization if( !query.exec("PRAGMA synchronous=OFF;") ) { qDebug() << query.lastError(); emit logMessage( query.lastError().text() ); } // Disable journal completely, because it's much faster // and there is nothing to loose, if the import crashes the database will // very likely go corrupt, but the import can be simply restarted if( !query.exec("PRAGMA journal_mode=OFF;") ) { qDebug() << query.lastError(); emit logMessage( query.lastError().text() ); } // Begin transaction if ( !database.driver()->beginTransaction() ) { qDebug() << database.lastError(); emit logMessage( database.lastError().text() ); } // Prepare an INSERT query to be used for each dataset to be inserted query.prepare( QString("INSERT OR REPLACE INTO %1 (%2) VALUES (%3)") .arg(tableName, dbFieldNames.join(","), placeholder) ); int counter = 0; while ( missingRequiredFields.isEmpty() && !file.atEnd() ) { const QByteArray line = file.readLine().trimmed(); QVariantList fieldValues; if ( readFields(line, &fieldValues, fieldTypes, fieldNames.count()) ) { // Remove values for fields that do not exist in the database, but in the GTFS feed, // eg. when multiple values of the feed get combined into a single value in the // database, for example "monday", "tuesday", ... get combined to "weekdays". for ( int i = 0; i < unavailableFieldIndices.count(); ++i ) { fieldValues.removeAt( unavailableFieldIndices[i] ); } // Add current field values to the prepared query and execute it if ( tableName == "calendar" ) { QString weekdays = "0000000"; for ( int i = 0; i < fieldNames.count(); ++i ) { const QString fieldName = fieldNames[i]; if ( fieldValues[i].toInt() > 0 ) { if ( fieldName == "sunday" ) { weekdays[0] = '1'; } else if ( fieldName == "monday" ) { weekdays[1] = '1'; } else if ( fieldName == "tuesday" ) { weekdays[2] = '1'; } else if ( fieldName == "wednesday" ) { weekdays[3] = '1'; } else if ( fieldName == "thursday" ) { weekdays[4] = '1'; } else if ( fieldName == "friday" ) { weekdays[5] = '1'; } else if ( fieldName == "saturday" ) { weekdays[6] = '1'; } else { query.addBindValue( fieldValues[i] ); } } else if ( fieldName != "monday" && fieldName != "tuesday" && fieldName != "wednesday" && fieldName != "thursday" && fieldName != "friday" && fieldName != "saturday" && fieldName != "sunday" ) { query.addBindValue( fieldValues[i] ); } } query.addBindValue( weekdays ); } else if ( tableName == "stop_times" ) { // If only one of "departure_time" and "arrival_time" is set, // copy the value to both fields int departureTime = -1; int arrivalTime = -1; int departureTimeIndex = -1; int arrivalTimeIndex = -1; for ( int i = 0; i < fieldNames.count(); ++i ) { if ( fieldNames[i] == "departure_time" ) { departureTime = fieldValues[i].toInt(); departureTimeIndex = i; } else if ( fieldNames[i] == "arrival_time" ) { arrivalTime = fieldValues[i].toInt(); arrivalTimeIndex = i; } } if ( departureTimeIndex >= 0 ) { arrivalTime = departureTime; fieldValues[ arrivalTimeIndex ] = departureTime; } else if ( departureTime < 0 ) { departureTime = arrivalTime; fieldValues[ departureTimeIndex ] = arrivalTime; } foreach ( const QVariant &fieldValue, fieldValues ) { query.addBindValue( fieldValue ); } } else { foreach ( const QVariant &fieldValue, fieldValues ) { query.addBindValue( fieldValue ); } } if ( !query.exec() ) { QMutexLocker locker( &m_mutex ); emit logMessage( query.lastError().text() ); kDebug() << query.lastError(); kDebug() << "With this query:" << query.lastQuery(); const int error = query.lastError().number(); if ( error == 10 || error == 11 ) { // SQLite error codes for malformed database files setError( FatalError, "Database is corrupted" ); return false; } continue; } // New row has been inserted into the DB successfully ++counter; // counter is now >= 1 // Start a new transaction after 50000 INSERTs if ( counter % 50000 == 0 ) { if ( !database.driver()->commitTransaction() ) { qDebug() << database.lastError(); emit logMessage( database.lastError().text() ); } if ( !database.driver()->beginTransaction() ) { qDebug() << database.lastError(); emit logMessage( database.lastError().text() ); } } // Report progress and check for quit/suspend after each 500 INSERTs if ( counter % 500 == 0 ) { // Report progress emit progress( qreal(totalFilePosition + file.pos()) / qreal(totalFileSize), tableName ); // Check if the job should be cancelled m_mutex.lock(); if ( m_quit ) { m_mutex.unlock(); setError( FatalError, "Importer was cancelled" ); return false; } // Check if the job should be suspended if ( m_state == ImportingSuspended ) { // Commit before going to sleep for suspension if ( !database.driver()->commitTransaction() ) { qDebug() << database.lastError(); emit logMessage( database.lastError().text() ); } do { // Do not lock while sleeping, otherwise ::resume() results in a deadlock m_mutex.unlock(); // Suspend import for one second sleep( 1 ); // Lock mutex again, to check if m_state is still ImportingSuspended m_mutex.lock(); kDebug() << "Next check for suspended state" << m_state; } while ( m_state == ImportingSuspended ); // Start a new transaction if ( !database.driver()->beginTransaction() ) { qDebug() << database.lastError(); emit logMessage( database.lastError().text() ); } } // Unlock mutex again m_mutex.unlock(); } } } if ( !missingRequiredFields.isEmpty() ) { // Only insert one row into the database, because the GTFS feed did not include this data // Currently only used for the "agency" table Q_ASSERT( tableName == QLatin1String("agency") ); const ServiceProviderData *providerData = ServiceProviderDataReader::read( m_providerName, &m_errorString ); if ( !providerData ) { m_state = FatalError; kDebug() << m_errorString; } else { kDebug() << "Missing required fields, that get filled with data of the provider plugin" << missingRequiredFields; QVariantList fieldValues = QVariantList() << 0 // agency_id << providerData->name() << providerData->url() << providerData->timeZone(); foreach ( const QVariant &fieldValue, fieldValues ) { query.addBindValue( fieldValue ); } if ( query.exec() ) { ++counter; } else { QMutexLocker locker( &m_mutex ); emit logMessage( query.lastError().text() ); kDebug() << query.lastError(); kDebug() << "With this query:" << query.lastQuery(); const int error = query.lastError().number(); if ( error == 10 || error == 11 ) { // SQLite error codes for malformed database files setError( FatalError, "Database is corrupted" ); } } } } // End transaction, restore synchronous=FULL if ( !database.driver()->commitTransaction() ) { qDebug() << database.lastError(); emit logMessage( database.lastError().text() ); } if( !query.exec("PRAGMA synchronous=FULL;") ) { qDebug() << query.lastError(); emit logMessage( query.lastError().text() ); } // Close the file again file.close(); // Return true (success) if at least one stop has been read if ( counter >= minimalRecordCount ) { return true; } else { setError( FatalError, "Not enough records found in " + tableName ); kDebug() << "Minimal record count is" << minimalRecordCount << "but only" << counter << "records were added"; return false; } } bool GtfsImporter::readHeader( const QString &header, QStringList *fieldNames, const QStringList &requiredFields ) { QStringList names = header.simplified().split(','); *fieldNames = QStringList(); if ( names.isEmpty() ) { setError( FatalError, "No field names found in header: " + header ); return false; } // Only allow alphanumerical characters as field names (and prevent SQL injection). QRegExp regExp( "[^A-Z0-9_]", Qt::CaseInsensitive ); foreach ( const QString &fieldName, names ) { QString name = fieldName.trimmed(); if ( (name.startsWith('"') && name.endsWith('"')) || (name.startsWith('\'') && name.endsWith('\'')) ) { name = name.mid( 1, name.length() - 2 ); } if ( regExp.indexIn(name) != -1 ) { emit logMessage( i18nc("@info", "Field name %1 contains " "a disallowed character %2' at %3", fieldName, regExp.cap(), regExp.pos()) ); - kWarning() << "Field name" << fieldName << "contains a disallowed character" + qWarning() << "Field name" << fieldName << "contains a disallowed character" << regExp.cap() << "at" << regExp.pos(); } else { fieldNames->append( name ); } } // Check required fields foreach ( const QString &requiredField, requiredFields ) { if ( !fieldNames->contains(requiredField) ) { emit logMessage( i18nc("@info", "Required field '%1' is missing", requiredField) ); kDebug() << "Required field missing:" << requiredField << *fieldNames; if ( requiredField == QLatin1String("agency_name") ) { kDebug() << "Will use agency name from plugin data"; } else if ( requiredField == QLatin1String("agency_url") ) { kDebug() << "Will use agency URL from plugin data"; } else if ( requiredField == QLatin1String("agency_timezone") ) { kDebug() << "Will use timezone from plugin data"; } else { setError( FatalError, "Required field missing: " + requiredField ); kDebug() << "in this header line:" << header; return false; } } } return true; } bool GtfsImporter::readFields( const QByteArray &line, QVariantList *fieldValues, const QList &fieldTypes, int expectedFieldCount ) { int pos = 0; QList::ConstIterator fieldType = fieldTypes.constBegin(); while ( pos < line.length() && fieldType != fieldTypes.constEnd() ) { int endPos = pos; QByteArray newField; if ( line[pos] == '"' ) { // A field with a quotation mark in it must start and end with a quotation mark, // all other quotation marks must be preceded with another quotation mark ++endPos; while ( endPos < line.length() ) { if ( line[endPos] == '"' ) { if ( endPos + 1 >= line.length() || line[endPos + 1] == ',' ) { break; // At the end of the field / line } if ( line[endPos + 1] == '"' ) { ++endPos; // Two quotation marks read, skip them } } ++endPos; } if ( endPos >= line.length() || line[endPos] != '"' ) { - kWarning() << "No field end delimiter found in line" << line; - kWarning() << "for field starting with a delimiter at position" << pos; - kWarning() << "Read until the end of the line"; + qWarning() << "No field end delimiter found in line" << line; + qWarning() << "for field starting with a delimiter at position" << pos; + qWarning() << "Read until the end of the line"; // Do not remove 1, because it gets done below, // there is no delimiter to remove at the end endPos = line.length(); } // Add field value without the quotation marks around it // and doubled quotation marks replaced with single ones newField = line.mid( pos + 1, endPos - pos - 1 ) .replace( QByteArray("\"\""), QByteArray("\"") ); pos = endPos + 2; } else if ( line[pos] == ',' ) { // Empty field, newField stays empty ++pos; } else { // Field without quotation marks, read until the next ',' endPos = line.indexOf( ',', pos ); if ( endPos < 0 ) { endPos = line.length(); } // Add field value newField = line.mid( pos, endPos - pos ); pos = endPos + 1; } // Append the new field value fieldValues->append( GtfsDatabase::convertFieldValue(newField.trimmed(), *fieldType) ); ++fieldType; if ( pos == line.length() && line[pos - 1] == ',' && fieldType != fieldTypes.constEnd() ) { // The current line ends after a ','. Add another empty field: fieldValues->append( GtfsDatabase::convertFieldValue(QByteArray(), *fieldType) ); ++fieldType; } } if ( fieldValues->isEmpty() ) { return false; } else if ( fieldValues->count() < expectedFieldCount ) { - kWarning() << "Header contains" << expectedFieldCount << "fields, but a line was read " + qWarning() << "Header contains" << expectedFieldCount << "fields, but a line was read " "with only" << fieldValues->count() << "field values. Using empty/default values:"; - kWarning() << "Values: " << *fieldValues; + qWarning() << "Values: " << *fieldValues; while ( fieldValues->count() < expectedFieldCount ) { fieldValues->append( QVariant() ); } } return true; } #include "gtfsimporter.moc" diff --git a/engine/gtfs/gtfsservice.cpp b/engine/gtfs/gtfsservice.cpp index 931c970..f156819 100644 --- a/engine/gtfs/gtfsservice.cpp +++ b/engine/gtfs/gtfsservice.cpp @@ -1,676 +1,676 @@ /* * Copyright 2013 Friedrich Pülz * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as * published by the Free Software Foundation; either version 2 or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ // Own includes #include "gtfsservice.h" #include "serviceprovider.h" #include "serviceproviderdata.h" #include "serviceproviderglobal.h" #include "serviceprovidergtfs.h" // KDE includes #include #include #include #include #include #include #include // Qt includes #include #include #include const qreal ImportGtfsToDatabaseJob::PROGRESS_PART_FOR_FEED_DOWNLOAD = 0.1; AbstractGtfsDatabaseJob::AbstractGtfsDatabaseJob( const QString &destination, const QString &operation, const QMap< QString, QVariant > ¶meters, QObject *parent ) : ServiceJob(destination, operation, parameters, parent) { Q_ASSERT( qobject_cast(parent) ); Q_ASSERT( qobject_cast(parent->parent()) ); } ImportGtfsToDatabaseJob::ImportGtfsToDatabaseJob( const QString &destination, const QString &operation, const QMap< QString, QVariant > ¶meters, QObject *parent ) : AbstractGtfsDatabaseJob(destination, operation, parameters, parent), m_state(Initializing), m_data(0), m_importer(0), m_onlyGetInformation(false) { setCapabilities( Suspendable | Killable ); QString errorMessage; m_data = ServiceProviderDataReader::read( parameters["serviceProviderId"].toString(), &errorMessage ); if ( !m_data ) { setError( GtfsErrorInvalidProviderId ); setErrorText( errorMessage ); return; } if ( m_data->type() != Enums::GtfsProvider ) { setError( GtfsErrorWrongProviderType ); setErrorText( i18nc("@info/plain", "Not a GTFS provider") ); } } UpdateGtfsToDatabaseJob::UpdateGtfsToDatabaseJob( const QString& destination, const QString &operation, const QMap< QString, QVariant > ¶meters, QObject *parent ) : ImportGtfsToDatabaseJob(destination, operation, parameters, parent) { } ImportGtfsToDatabaseJob::~ImportGtfsToDatabaseJob() { if ( m_importer ) { m_importer->quit(); kDebug() << "Wait 10 second for the import thread to quit..."; m_importer->wait( 10000 ); delete m_importer; } } DeleteGtfsDatabaseJob::DeleteGtfsDatabaseJob( const QString &destination, const QString &operation, const QMap< QString, QVariant > ¶meters, QObject *parent ) : AbstractGtfsDatabaseJob(destination, operation, parameters, parent) { m_serviceProviderId = parameters["serviceProviderId"].toString(); } bool AbstractGtfsDatabaseJob::canImportGtfsFeed() { GtfsService *service = qobject_cast< GtfsService* >( parent() ); Plasma::DataEngine *engine = qobject_cast< Plasma::DataEngine* >( service->parent() ); Q_ASSERT( engine ); // Get the QMetaObject of the engine const QMetaObject *meta = engine->metaObject(); // Find the slot of the engine to start the request const int slotIndex = meta->indexOfSlot( "tryToStartGtfsFeedImportJob(Plasma::ServiceJob*)" ); Q_ASSERT( slotIndex != -1 ); meta->method( slotIndex ).invoke( engine, Qt::DirectConnection, Q_RETURN_ARG(bool, m_canAccessGtfsDatabase), Q_ARG(const Plasma::ServiceJob*, this) ); // If an import is already running for the provider, the operation cannot be executed now, // only updateGtfsFeedInfo can be executed while importing a GTFS feed if ( !m_canAccessGtfsDatabase ) { - kWarning() << "The GTFS feed already gets imported"; + qWarning() << "The GTFS feed already gets imported"; return false; } return true; } void AbstractGtfsDatabaseJob::start() { QTimer::singleShot( 0, this, SLOT(tryToWork()) ); } void AbstractGtfsDatabaseJob::tryToWork() { if ( error() != NoGtfsError ) { kDebug() << error(); // Error found in constructor, eg. no provider with the given ID found or no GTFS provider setResult( false ); return; } if ( isAccessingGtfsDatabase() && !canImportGtfsFeed() ) { // Cannot start another GTFS database accessing job kDebug() << "Import is already running"; setError( GtfsErrorFeedImportAlreadyRunning ); setErrorText( i18nc("@info/plain", "The GTFS feed already gets imported.") ); setResult( false ); return; } // No problems, do the work now work(); } void ImportGtfsToDatabaseJob::registerAtJobTracker() { KIO::getJobTracker()->registerJob( this ); emitDescription(); } void ImportGtfsToDatabaseJob::emitDescription() { if ( error() != NoGtfsError || !data() ) { kDebug() << error(); // Error found in constructor, eg. no provider with the given ID found or no GTFS provider emit description( this, errorString() ); return; } // Emit a description about what's done in this job const QPair< QString, QString > field1 = qMakePair( i18nc("@info/plain Label for GTFS service provider", "Service Provider"), data()->name() ); const QPair< QString, QString > field2 = qMakePair( i18nc("@info/plain Label for GTFS feed source URLs", "Source"), m_data->feedUrl() ); if ( m_onlyGetInformation ) { emit description( this, i18nc("@info", "Update GTFS feed info"), field1, field2 ); } else { emit description( this, i18nc("@info", "Import GTFS feed"), field1, field2 ); } } void UpdateGtfsToDatabaseJob::emitDescription() { if ( error() != NoGtfsError || !data() ) { kDebug() << error(); // Error found in constructor, eg. no provider with the given ID found or no GTFS provider emit description( this, errorString() ); return; } emit description( this, i18nc("@info", "Updating GTFS feed"), qMakePair(i18nc("@info/plain Label for GTFS service provider", "Service Provider"), data()->name()), qMakePair(i18nc("@info/plain Label for GTFS feed source URLs", "Source"), data()->feedUrl()) ); } void ImportGtfsToDatabaseJob::work() { Q_ASSERT( m_data ); emitDescription(); // Start the job by first requesting GTFS feed information statFeed(); } void UpdateGtfsToDatabaseJob::tryToWork() { QString errorMessage; if ( ServiceProviderGtfs::isGtfsFeedImportFinished(data()->id(), data()->feedUrl(), ServiceProviderGlobal::cache(), &errorMessage) ) { AbstractGtfsDatabaseJob::tryToWork(); } else { setError( GtfsErrorFeedImportRequired ); setErrorText( errorMessage ); setResult( false ); } } void UpdateGtfsToDatabaseJob::work() { QString errorMessage; if ( ServiceProviderGtfs::isGtfsFeedImportFinished(data()->id(), data()->feedUrl(), ServiceProviderGlobal::cache(), &errorMessage) ) { // Emit a description about what's done in this job emitDescription(); setCapabilities( Suspendable | Killable ); // Start the job by first requesting GTFS feed information statFeed(); } else { setError( GtfsErrorFeedImportRequired ); setErrorText( errorMessage ); setResult( false ); } } void DeleteGtfsDatabaseJob::work() { // Close the database before deleting it, // otherwise a newly created database won't get opened, // because the already opened database connection gets used instead GtfsDatabase::closeDatabase( m_serviceProviderId ); // Delete the database file const QString databasePath = GtfsDatabase::databasePath( m_serviceProviderId ); if ( !QFile::remove(databasePath) ) { kDebug() << "Failed to delete GTFS database"; setError( GtfsErrorCannotDeleteDatabase ); setErrorText( i18nc("@info/plain", "The GTFS database could not be deleted.") ); setResult( false ); return; } kDebug() << "Finished deleting GTFS database of" << m_serviceProviderId; // Update the accessor cache file to indicate that the GTFS feed needs to be imported again KConfig config( ServiceProviderGlobal::cacheFileName(), KConfig::SimpleConfig ); KConfigGroup group = config.group( m_serviceProviderId ); KConfigGroup gtfsGroup = group.group( "gtfs" ); gtfsGroup.writeEntry( "feedImportFinished", false ); // Write to disk now, important for the data engine to get the correct state // directly after this job has finished gtfsGroup.sync(); // Finished successfully setResult( true ); } bool ImportGtfsToDatabaseJob::doKill() { if ( m_state == ReadingFeed ) { m_importer->quit(); } m_state = KillingJob; return true; } bool ImportGtfsToDatabaseJob::doSuspend() { if ( m_state == ReadingFeed ) { m_importer->suspend(); } return true; } bool ImportGtfsToDatabaseJob::doResume() { if ( m_state == ReadingFeed ) { m_importer->resume(); } return true; } void ImportGtfsToDatabaseJob::statFeed() { if ( m_state == DownloadingFeed || m_state == ReadingFeed || m_state == StatingFeed ) { kDebug() << "Feed already gets downloaded / was downloaded and gets imported / gets stated"; return; } if ( !m_data ) { // There was an error in the constructor, error already set setResult( false ); return; } kDebug() << "Request GTFS feed information for" << m_data->id(); emit infoMessage( this, i18nc("@info/plain", "Checking GTFS feed source") ); m_state = StatingFeed; QNetworkAccessManager *manager = new QNetworkAccessManager( this ); connect( manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(statFeedFinished(QNetworkReply*)) ); QNetworkRequest request( m_data->feedUrl() ); manager->head( request ); } void ImportGtfsToDatabaseJob::statFeedFinished( QNetworkReply *reply ) { if ( m_state == KillingJob || isSuspended() ) { return; } // Check if there is a valid redirection QString redirectUrl = reply->attribute( QNetworkRequest::RedirectionTargetAttribute ).toString(); if ( reply->error() != QNetworkReply::NoError && reply->header(QNetworkRequest::ContentLengthHeader).toInt() == 0 && reply->url() != m_lastRedirectUrl ) { // Headers were requested, empty result // Now download completely, using get instead of head kDebug() << "Possible redirection, requesting headers lead to an error reply" << reply->url(); m_lastRedirectUrl = reply->url().toString(); reply->manager()->get( QNetworkRequest(reply->url()) ); reply->deleteLater(); return; } else if( !redirectUrl.isEmpty() && redirectUrl != m_lastRedirectUrl ) { // Redirect to redirectUrl, store last redirection kDebug() << "Redirecting to" << redirectUrl; m_lastRedirectUrl = redirectUrl; reply->manager()->head( QNetworkRequest(redirectUrl) ); reply->deleteLater(); return; } // Not redirected anymore m_lastRedirectUrl.clear(); if ( reply->error() == QNetworkReply::NoError ) { QString contentType = reply->header( QNetworkRequest::ContentTypeHeader ).toString(); // If ';' is not included in contentType, QString::left() returns the whole string const KMimeType::Ptr mimeType = KMimeType::mimeType( contentType.left(contentType.indexOf(';')) ); if ( mimeType && mimeType->isValid() ) { if ( !mimeType->is("application/zip") && !mimeType->is("application/octet-stream") ) { kDebug() << "Invalid mime type:" << reply->header(QNetworkRequest::ContentTypeHeader).toString(); setError( GtfsErrorWrongFeedFormat ); setErrorText( i18nc("@info/plain", "Wrong GTFS feed format: %1", mimeType->name()) ); setResult( false ); return; } } else { kDebug() << "Could not create KMimeType object for" << reply->header(QNetworkRequest::ContentTypeHeader).toString(); } // Use KDateTime and UTC time to not get confused with different locales KDateTime newLastModified = KDateTime::fromString( reply->header(QNetworkRequest::LastModifiedHeader).toString() ).toUtc(); qulonglong newSizeInBytes = reply->header( QNetworkRequest::ContentLengthHeader ).toULongLong(); // emit size and lastModified? // qDebug() << ">>>>> GTFS feed was last modified (UTC):" << newLastModified // << "and it's size is:" << (newSizeInBytes/qreal(1024*1024)) << "MB"; // Read accessor information cache QSharedPointer cache = ServiceProviderGlobal::cache(); QString errorMessage; const bool importFinished = ServiceProviderGtfs::isGtfsFeedImportFinished( data()->id(), data()->feedUrl(), cache, &errorMessage ); KConfigGroup group = cache->group( data()->id() ); KConfigGroup gtfsGroup = group.group( "gtfs" ); KDateTime lastModified = KDateTime::fromString( gtfsGroup.readEntry("feedModifiedTime", QString()) ); qulonglong sizeInBytes = gtfsGroup.readEntry( "feedSizeInBytes", qulonglong(-1) ); gtfsGroup.writeEntry( "feedModifiedTime", newLastModified.toString() ); gtfsGroup.writeEntry( "feedSizeInBytes", newSizeInBytes ); gtfsGroup.writeEntry( "feedUrl", data()->feedUrl() ); // Needed to have the GTFS feed information available directly after this job is finished gtfsGroup.sync(); // Stop here for "updateGtfsFeedInfo" operation if ( m_onlyGetInformation ) { m_state = Ready; setResult( importFinished ); return; } if ( !importFinished ) { qDebug() << errorMessage << m_data->id(); } // qDebug() << "Old last modified:" << lastModified // << "new size:" << (sizeInBytes/qreal(1024*1024)) << "MB"; if ( !importFinished // GTFS import not finished or never started? || (newLastModified.isValid() && lastModified.isValid() && // GTFS feed modified? newLastModified != lastModified) || (newSizeInBytes > 0 && newSizeInBytes != sizeInBytes) // Size changed? || (newSizeInBytes == 0 && !newLastModified.isValid() && // If both are not available... lastModified.daysTo(KDateTime::currentUtcDateTime()) > 7) ) // ...upate weekly { kDebug() << "Download new GTFS feed version for" << m_data->id(); // A newer GTFS feed is available or it was not imported / import did not finish m_state = Initializing; downloadFeed(); } else { // Newest version of the GTFS feed is already downloaded and completely imported m_state = Ready; setResult( true ); } } else { // Track this job to show the error registerAtJobTracker(); kDebug() << "GTFS feed not available: " << m_data->feedUrl() << reply->errorString(); m_state = ErrorDownloadingFeed; setError( GtfsErrorDownloadFailed ); setErrorText( reply->errorString() ); // TODO setResult( false ); } reply->manager()->deleteLater(); reply->deleteLater(); } void ImportGtfsToDatabaseJob::slotSpeed( KJob *job, ulong speed ) { Q_UNUSED( job ); emitSpeed( speed ); } void ImportGtfsToDatabaseJob::downloadFeed() { if ( m_state == DownloadingFeed || m_state == ReadingFeed || m_state == StatingFeed ) { kDebug() << "Feed already gets downloaded / was downloaded and gets imported / gets stated"; return; } if ( m_state == KillingJob || isSuspended() ) { return; } // Track this job at least from now on, // because the download/import can take some time registerAtJobTracker(); kDebug() << "Start GTFS feed import for" << m_data->id(); KTemporaryFile tmpFile; if ( tmpFile.open() ) { kDebug() << "Downloading GTFS feed from" << m_data->feedUrl() << "to" << tmpFile.fileName(); emit infoMessage( this, i18nc("@info/plain", "Downloading GTFS feed") ); m_state = DownloadingFeed; tmpFile.setAutoRemove( false ); // Do not remove the target file while downloading // Set progress to 0 m_progress = 0.0; emitPercent( 0, 1000 ); // KFileItem gtfsFeed( m_info->feedUrl(), QString(), S_IFREG | S_IFSOCK ); // kDebug() << "LAST MODIFIED:" << gtfsFeed.timeString( KFileItem::ModificationTime ); // Update provider cache KConfig config( ServiceProviderGlobal::cacheFileName(), KConfig::SimpleConfig ); KConfigGroup group = config.group( data()->id() ); KConfigGroup gtfsGroup = group.group( "gtfs" ); gtfsGroup.writeEntry( "feedImportFinished", false ); KIO::FileCopyJob *job = KIO::file_copy( m_data->feedUrl(), QUrl(tmpFile.fileName()), -1, KIO::Overwrite | KIO::HideProgressInfo ); connect( job, SIGNAL(result(KJob*)), this, SLOT(feedReceived(KJob*)) ); connect( job, SIGNAL(percent(KJob*,ulong)), this, SLOT(downloadProgress(KJob*,ulong)) ); connect( job, SIGNAL(mimetype(KIO::Job*,QString)), this, SLOT(mimeType(KIO::Job*,QString)) ); connect( job, SIGNAL(totalSize(KJob*,qulonglong)), this, SLOT(totalSize(KJob*,qulonglong)) ); connect( job, SIGNAL(speed(KJob*,ulong)), this, SLOT(slotSpeed(KJob*,ulong)) ); } else { kDebug() << "Could not create a temporary file to download the GTFS feed"; // TODO emit error... } } void ImportGtfsToDatabaseJob::mimeType( KIO::Job *job, const QString &type ) { Q_UNUSED( job ); const KMimeType::Ptr mimeType = KMimeType::mimeType( type ); if ( mimeType && mimeType->isValid() ) { if ( !mimeType->is("application/zip") && !mimeType->is("application/octet-stream") ) { kDebug() << "Invalid mime type:" << type; setError( GtfsErrorWrongFeedFormat ); setErrorText( i18nc("@info/plain", "Wrong GTFS feed format: %1", mimeType->name()) ); setResult( false ); return; } } else { kDebug() << "Could not create KMimeType object for" << type; } } void ImportGtfsToDatabaseJob::totalSize( KJob* job, qulonglong size ) { Q_UNUSED( job ); KConfig config( ServiceProviderGlobal::cacheFileName(), KConfig::SimpleConfig ); KConfigGroup group = config.group( data()->id() ); KConfigGroup gtfsGroup = group.group( "gtfs" ); gtfsGroup.writeEntry( "feedSizeInBytes", size ); } void ImportGtfsToDatabaseJob::downloadProgress( KJob *job, ulong percent ) { Q_UNUSED( job ); m_progress = (qreal(percent) / 100.0) * PROGRESS_PART_FOR_FEED_DOWNLOAD; // TODO Remove m_progress emitPercent( percent * 10 * PROGRESS_PART_FOR_FEED_DOWNLOAD, 1000 ); } void ImportGtfsToDatabaseJob::feedReceived( KJob *job ) { if ( m_state == KillingJob || isSuspended() ) { return; } // Emit progress for finished download m_progress = PROGRESS_PART_FOR_FEED_DOWNLOAD; emitPercent( 1000 * PROGRESS_PART_FOR_FEED_DOWNLOAD, 1000 ); KIO::FileCopyJob *fileCopyJob = qobject_cast( job ); QString tmpFilePath = fileCopyJob->destUrl().path(); if ( job->error() != 0 ) { kDebug() << "Error downloading GTFS feed:" << job->errorString(); emit infoMessage( this, i18nc("@info/plain", "Error downloading GTFS feed: " "%1", job->errorString()) ); m_state = ErrorDownloadingFeed; if ( !QFile::remove(tmpFilePath) ) { kDebug() << "Could not remove the temporary GTFS feed file"; } setError( GtfsErrorDownloadFailed ); setErrorText( job->errorString() ); // TODO setResult( false ); return; } kDebug() << "GTFS feed received at" << tmpFilePath; // Read feed and write data into the DB m_state = ReadingFeed; emit infoMessage( this, i18nc("@info/plain", "Importing GTFS feed") ); m_importer = new GtfsImporter( m_data->id() ); connect( m_importer, SIGNAL(logMessage(QString)), this, SLOT(logMessage(QString)) ); connect( m_importer, SIGNAL(progress(qreal,QString)), this, SLOT(importerProgress(qreal,QString)) ); connect( m_importer, SIGNAL(finished(GtfsImporter::State,QString)), this, SLOT(importerFinished(GtfsImporter::State,QString)) ); m_importer->startImport( tmpFilePath ); } void ImportGtfsToDatabaseJob::logMessage( const QString &message ) { emit warning( this, message ); } void ImportGtfsToDatabaseJob::importerProgress( qreal importerProgress, const QString ¤tTableName ) { m_progress = PROGRESS_PART_FOR_FEED_DOWNLOAD * (1.0 - importerProgress) + importerProgress; emitPercent( m_progress * 1000, 1000 ); if ( currentTableName != m_lastTableName ) { emit infoMessage( this, i18nc("@info/plain", "Importing GTFS feed (%1)", currentTableName) ); m_lastTableName = currentTableName; } } void ImportGtfsToDatabaseJob::importerFinished( GtfsImporter::State state, const QString &errorText ) { // Remove temporary file if ( m_importer && !QFile::remove(m_importer->sourceFileName()) ) { - kWarning() << "Could not remove the temporary GTFS feed file"; + qWarning() << "Could not remove the temporary GTFS feed file"; } // Update 'feedImportFinished' field in the cache KConfig config( ServiceProviderGlobal::cacheFileName(), KConfig::SimpleConfig ); KConfigGroup group = config.group( data()->id() ); KConfigGroup gtfsGroup = group.group( "gtfs" ); gtfsGroup.writeEntry( "feedImportFinished", state != GtfsImporter::FatalError ); // Write to disk now, important for the data engine to get the correct state // directly after this job has finished gtfsGroup.sync(); // Emit progress with 1.0, ie. finsihed m_progress = 1.0; emitPercent( 1000, 1000 ); kDebug() << "Finished" << state << errorText; // Ignore GtfsImporter::FinishedWithErrors if ( state == GtfsImporter::FatalError ) { m_state = ErrorReadingFeed; kDebug() << "There was an error importing the GTFS feed into the database" << errorText; emit infoMessage( this, errorText ); } else { m_state = Ready; emit infoMessage( this, i18nc("@info/plain", "GTFS feed has been successfully imported") ); } if ( m_importer ) { m_importer->quit(); m_importer->wait(); delete m_importer; m_importer = 0; } if ( m_state == Ready ) { // Update accessor information cache setResult( true ); } else { setError( GtfsErrorImportFailed ); setErrorText( errorText ); setResult( false ); } } QString ImportGtfsToDatabaseJob::serviceProviderId() const { return m_data ? m_data->id() : QString(); } GtfsService::GtfsService( const QString &name, QObject *parent ) : Service(parent), m_name(name) { // This associates the service with the "publictransport.operations" file setName( "publictransport" ); } Plasma::ServiceJob* GtfsService::createJob( const QString &operation, QMap< QString, QVariant > ¶meters ) { // Check if a valid provider ID is available in the parameters const QString providerId = parameters["serviceProviderId"].toString(); if ( providerId.isEmpty() ) { - kWarning() << "No 'serviceProviderId' parameter given to GTFS service operation"; + qWarning() << "No 'serviceProviderId' parameter given to GTFS service operation"; return 0; } if ( operation == QLatin1String("updateGtfsDatabase") ) { UpdateGtfsToDatabaseJob *updateJob = new UpdateGtfsToDatabaseJob( "PublicTransport", operation, parameters, this ); return updateJob; } else if ( operation == QLatin1String("importGtfsFeed") ) { ImportGtfsToDatabaseJob *importJob = new ImportGtfsToDatabaseJob( "PublicTransport", operation, parameters, this ); // Directly register import jobs, ie. also show "Check Feed Source" importJob->registerAtJobTracker(); return importJob; } else if ( operation == QLatin1String("deleteGtfsDatabase") ) { DeleteGtfsDatabaseJob *deleteJob = new DeleteGtfsDatabaseJob( "PublicTransport", operation, parameters, this ); return deleteJob; } else if ( operation == QLatin1String("updateGtfsFeedInfo") ) { ImportGtfsToDatabaseJob *updateFeedInfoJob = new ImportGtfsToDatabaseJob( "PublicTransport", operation, parameters, this ); updateFeedInfoJob->setOnlyGetInformation( true ); return updateFeedInfoJob; } else { - kWarning() << "Operation" << operation << "not supported"; + qWarning() << "Operation" << operation << "not supported"; return 0; } } diff --git a/engine/gtfs/serviceprovidergtfs.cpp b/engine/gtfs/serviceprovidergtfs.cpp index 8ee7cd9..0cd8804 100644 --- a/engine/gtfs/serviceprovidergtfs.cpp +++ b/engine/gtfs/serviceprovidergtfs.cpp @@ -1,908 +1,908 @@ /* * Copyright 2013 Friedrich Pülz * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as * published by the Free Software Foundation; either version 2 or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ // Header #include "serviceprovidergtfs.h" // Own includes #include "serviceproviderdata.h" #include "serviceproviderglobal.h" #include "departureinfo.h" #include "gtfsservice.h" #include "gtfsrealtime.h" #include "request.h" // KDE includes #include #include #include #include #include #include #include #include #include #include #include #include // Qt includes #include #include #include #include #include #include #include #include #include const qreal ServiceProviderGtfs::PROGRESS_PART_FOR_FEED_DOWNLOAD = 0.1; ServiceProviderGtfs::ServiceProviderGtfs( const ServiceProviderData *data, QObject *parent, const QSharedPointer &cache ) : ServiceProvider(data, parent, cache), m_state(Initializing), m_service(0) #ifdef BUILD_GTFS_REALTIME , m_tripUpdates(0), m_alerts(0) #endif { // Ensure that the GTFS feed was imported and the database is valid if ( updateGtfsDatabaseState(data->id(), data->feedUrl(), cache) == QLatin1String("ready") ) { m_state = Ready; // Load agency information from database and request GTFS-realtime data loadAgencyInformation(); #ifdef BUILD_GTFS_REALTIME updateRealtimeData(); #endif } else { m_state = Error; } // Update database, if a new version of the GTFS feed is available // and an initial import has finished successfully updateGtfsDatabase(); } ServiceProviderGtfs::~ServiceProviderGtfs() { // Free all agency objects qDeleteAll( m_agencyCache ); #ifdef BUILD_GTFS_REALTIME delete m_tripUpdates; delete m_alerts; #endif } QString ServiceProviderGtfs::updateGtfsDatabaseState( const QString &providerId, const QString &feedUrl, const QSharedPointer< KConfig > &_cache, QVariantHash *stateData ) { // Read 'feedImportFinished' value from provider cache QSharedPointer< KConfig > cache = _cache.isNull() ? ServiceProviderGlobal::cache() : _cache; KConfigGroup group = cache->group( providerId ); KConfigGroup gtfsGroup = group.group( "gtfs" ); QString errorMessage; bool importFinished = isGtfsFeedImportFinished( providerId, feedUrl, cache, &errorMessage ); // Update GTFS feed state fields that do not need the import to be finished already if ( stateData ) { // Data might not be available, // the "updateGtfsFeedInfo" operation of the GTFS service can be run to get the data qlonglong sizeInBytes = gtfsGroup.readEntry( "feedSizeInBytes", qlonglong(-1) ); QDateTime lastModified = QDateTime::fromString( gtfsGroup.readEntry("feedModifiedTime", QString()), Qt::ISODate ); stateData->insert( "gtfsFeedSize", sizeInBytes ); stateData->insert( "gtfsFeedModifiedTime", lastModified ); } // GTFS feed was successfully imported from the currently used feed URL if ( importFinished ) { // Import was marked as finished, test if the database file still exists and // is not empty (some space is needed for the tables also if they are empty) QFileInfo fi( GtfsDatabase::databasePath(providerId) ); if ( fi.exists() && fi.size() > 10000 ) { // Try to initialize the database if ( !GtfsDatabase::initDatabase(providerId, &errorMessage) ) { - kWarning() << "Error initializing the database" << errorMessage; + qWarning() << "Error initializing the database" << errorMessage; // Update 'feedImportFinished' field in the cache gtfsGroup.writeEntry( "feedImportFinished", false ); // Write to disk now if someone wants to read the value directly after this function gtfsGroup.sync(); if ( stateData ) { stateData->insert( "gtfsFeedImported", false ); stateData->insert( "statusMessage", errorMessage ); } return "gtfs_feed_import_pending"; } // Database exists, feed marked as imported and feed URL did not change // since the import, set state data and return state "ready" if ( stateData ) { stateData->insert( "gtfsFeedImported", true ); // Insert a status message stateData->insert( "statusMessage", i18nc("@info/plain", "GTFS feed succesfully imported") ); // Update GTFS database state fields const QString databasePath = GtfsDatabase::databasePath( providerId ); const QFileInfo databaseInfo( databasePath ); stateData->insert( "gtfsDatabasePath", databasePath ); stateData->insert( "gtfsDatabaseSize", databaseInfo.size() ); stateData->insert( "gtfsDatabaseModifiedTime", databaseInfo.lastModified().toString(Qt::ISODate) ); // Add an 'updatable' field to the state data const bool updatable = ServiceProviderGtfs::isUpdateAvailable( providerId, feedUrl, cache ); stateData->insert( "updatable", updatable ); } return "ready"; } else { - kWarning() << "GTFS database file not found or empty database" << fi.filePath(); + qWarning() << "GTFS database file not found or empty database" << fi.filePath(); // The provider cache says the import has been finished, // but the database file does not exist any longer or is empty gtfsGroup.writeEntry( "feedImportFinished", false ); // Write to disk now if someone wants to read the value directly after this function gtfsGroup.sync(); // The GTFS feed has not been imported successfully yet // or the database file was deleted/corrupted if ( stateData ) { stateData->insert( "gtfsFeedImported", false ); stateData->insert( "statusMessage", i18nc("@info/plain", "GTFS feed not imported") ); } return "gtfs_feed_import_pending"; } } else { // GTFS feed was not imported or the feed URL has changed since the import if ( stateData ) { stateData->insert( "gtfsFeedImported", false ); stateData->insert( "statusMessage", errorMessage ); } return "gtfs_feed_import_pending"; } } bool ServiceProviderGtfs::isTestResultUnchanged( const QString &providerId, const QString &feedUrl, const QSharedPointer< KConfig > &cache ) { // The test result changes when the GTFS feed was updated return isUpdateAvailable( providerId, feedUrl, cache ); } bool ServiceProviderGtfs::isTestResultUnchanged( const QSharedPointer &cache ) const { return isTestResultUnchanged( data()->id(), data()->feedUrl(), cache ); } bool ServiceProviderGtfs::runTests( QString *errorMessage ) const { Q_UNUSED( errorMessage ); if ( m_state == Ready ) { // The GTFS feed was successfully imported return true; } const QUrl feedUrl( m_data->feedUrl() ); if ( feedUrl.isEmpty() || !feedUrl.isValid() ) { if ( errorMessage ) { *errorMessage = i18nc("@info/plain", "Invalid GTFS feed URL: %1", m_data->feedUrl()); } return false; } // No errors found return true; } void ServiceProviderGtfs::updateGtfsDatabase() { if ( m_service ) { kDebug() << "Is already updating, please wait"; return; } Plasma::DataEngine *engine = qobject_cast< Plasma::DataEngine* >( parent() ); Q_ASSERT( engine ); m_service = engine->serviceForSource( "GTFS" ); KConfigGroup op = m_service->operationDescription("updateGtfsDatabase"); op.writeEntry( "serviceProviderId", m_data->id() ); m_service->startOperationCall( op ); } #ifdef BUILD_GTFS_REALTIME bool ServiceProviderGtfs::isRealtimeDataAvailable() const { return !m_data->realtimeTripUpdateUrl().isEmpty() || !m_data->realtimeAlertsUrl().isEmpty(); } void ServiceProviderGtfs::updateRealtimeData() { // m_state = DownloadingFeed; if ( !m_data->realtimeTripUpdateUrl().isEmpty() ) { KIO::StoredTransferJob *tripUpdatesJob = KIO::storedGet( m_data->realtimeTripUpdateUrl(), KIO::Reload, KIO::Overwrite | KIO::HideProgressInfo ); connect( tripUpdatesJob, SIGNAL(result(KJob*)), this, SLOT(realtimeTripUpdatesReceived(KJob*)) ); kDebug() << "Updating GTFS-realtime trip update data" << m_data->realtimeTripUpdateUrl(); } if ( !m_data->realtimeAlertsUrl().isEmpty() ) { KIO::StoredTransferJob *alertsJob = KIO::storedGet( m_data->realtimeAlertsUrl(), KIO::Reload, KIO::Overwrite | KIO::HideProgressInfo ); connect( alertsJob, SIGNAL(result(KJob*)), this, SLOT(realtimeAlertsReceived(KJob*)) ); kDebug() << "Updating GTFS-realtime alerts data" << m_data->realtimeAlertsUrl(); } if ( m_data->realtimeTripUpdateUrl().isEmpty() && m_data->realtimeAlertsUrl().isEmpty() ) { m_state = Ready; } } void ServiceProviderGtfs::realtimeTripUpdatesReceived( KJob *job ) { KIO::StoredTransferJob *transferJob = qobject_cast( job ); if ( job->error() != 0 ) { kDebug() << "Error downloading GTFS-realtime trip updates:" << job->errorString(); return; } delete m_tripUpdates; m_tripUpdates = GtfsRealtimeTripUpdate::fromProtocolBuffer( transferJob->data() ); if ( m_alerts || m_data->realtimeAlertsUrl().isEmpty() ) { m_state = Ready; } } void ServiceProviderGtfs::realtimeAlertsReceived( KJob *job ) { KIO::StoredTransferJob *transferJob = qobject_cast( job ); if ( job->error() != 0 ) { kDebug() << "Error downloading GTFS-realtime alerts:" << job->errorString(); return; } delete m_alerts; m_alerts = GtfsRealtimeAlert::fromProtocolBuffer( transferJob->data() ); if ( m_tripUpdates || m_data->realtimeTripUpdateUrl().isEmpty() ) { m_state = Ready; } } #endif // BUILD_GTFS_REALTIME void ServiceProviderGtfs::loadAgencyInformation() { if ( m_state != Ready ) { return; } QSqlQuery query( QSqlDatabase::database(m_data->id()) ); if ( !query.exec("SELECT * FROM agency") ) { kDebug() << "Could not load agency information from database:" << query.lastError(); return; } // Clear previously loaded agency data qDeleteAll( m_agencyCache ); m_agencyCache.clear(); // Read agency records from the database QSqlRecord record = query.record(); const int agencyIdColumn = record.indexOf( "agency_id" ); const int agencyNameColumn = record.indexOf( "agency_name" ); const int agencyUrlColumn = record.indexOf( "agency_url" ); const int agencyTimezoneColumn = record.indexOf( "agency_timezone" ); const int agencyLanguageColumn = record.indexOf( "agency_lang" ); const int agencyPhoneColumn = record.indexOf( "agency_phone" ); while ( query.next() ) { AgencyInformation *agency = new AgencyInformation; agency->name = query.value( agencyNameColumn ).toString(); agency->url = query.value( agencyUrlColumn ).toString(); agency->language = query.value( agencyLanguageColumn ).toString(); agency->phone = query.value( agencyPhoneColumn ).toString(); const QString timeZone = query.value(agencyTimezoneColumn).toString(); agency->timezone = new KTimeZone( timeZone.isEmpty() ? m_data->timeZone() : timeZone ); const uint id = query.value( agencyIdColumn ).toUInt(); m_agencyCache.insert( id, agency ); } } int ServiceProviderGtfs::AgencyInformation::timeZoneOffset() const { return timezone && timezone->isValid() ? timezone->currentOffset( Qt::LocalTime ) : 0; } qint64 ServiceProviderGtfs::databaseSize() const { QFileInfo fi( GtfsDatabase::databasePath(m_data->id()) ); return fi.size(); } ServiceProviderGtfs::AgencyInformation::~AgencyInformation() { delete timezone; } // NOTE When changing this function, also update ProjectPrivate::gtfsProviderFeatures() // in TimetableMate! QList ServiceProviderGtfs::features() const { QList features; features << Enums::ProvidesDepartures << Enums::ProvidesArrivals << Enums::ProvidesStopSuggestions << Enums::ProvidesRouteInformation << Enums::ProvidesStopID << Enums::ProvidesStopGeoPosition; // Enums::ProvidesStopsByGeoPosition TODO #ifdef BUILD_GTFS_REALTIME if ( !m_data->realtimeAlertsUrl().isEmpty() ) { features << Enums::ProvidesNews; } if ( !m_data->realtimeTripUpdateUrl().isEmpty() ) { features << Enums::ProvidesDelays; } #endif return features; } QDateTime ServiceProviderGtfs::timeFromSecondsSinceMidnight( const QDate &dateAtMidnight, int secondsSinceMidnight, QDate *date ) const { const int secondsInOneDay = 60 * 60 * 24; QDate resultDate = dateAtMidnight; while ( secondsSinceMidnight >= secondsInOneDay ) { secondsSinceMidnight -= secondsInOneDay; resultDate.addDays( 1 ); if ( date ) { date->addDays( 1 ); } } return QDateTime( resultDate, QTime(secondsSinceMidnight / (60 * 60), (secondsSinceMidnight / 60) % 60, secondsSinceMidnight % 60) ); } bool ServiceProviderGtfs::isGtfsFeedImportFinished( const QString &providerId, const QString &feedUrl, const QSharedPointer &_cache, QString *errorMessage ) { const QSharedPointer &cache = _cache.isNull() ? ServiceProviderGlobal::cache() : _cache; // Check if the GTFS feed import is marked as finished in the cache KConfigGroup group = cache->group( providerId ); KConfigGroup gtfsGroup = group.group( "gtfs" ); if ( gtfsGroup.readEntry("feedImportFinished", false) ) { // GTFS feed import is marked as finished, check if the feed URL has changed since if ( feedUrl.isEmpty() ) { // Feed URL not given, no change expected here (eg. directly after a finished import) return true; } const QString importedGtfsFeedUrl = gtfsGroup.readEntry( "feedUrl", QString() ); if ( importedGtfsFeedUrl == feedUrl ) { // Feed URL did not change, import is finished return true; } else { // Feed URL was modified, re-import needed, // update "feedImportFinished" field in the cache gtfsGroup.writeEntry( "feedImportFinished", false ); gtfsGroup.sync(); if ( errorMessage ) { *errorMessage = i18nc("@info/plain", "GTFS feed was imported, but the feed URL " "has changed. Please re-import the feed from the new URL."); } return false; } } // GTFS feed import is marked as not finished or was not found in the cache if ( errorMessage ) { *errorMessage = i18nc("@info/plain", "GTFS feed not imported. " "Please import it explicitly first."); } return false; } bool ServiceProviderGtfs::isUpdateAvailable( const QString &providerId, const QString &feedUrl, const QSharedPointer &_cache ) { const QSharedPointer cache = _cache.isNull() ? ServiceProviderGlobal::cache() : _cache; KConfigGroup group = cache->group( providerId ); KConfigGroup gtfsGroup = group.group( "gtfs" ); const bool importFinished = isGtfsFeedImportFinished( providerId, feedUrl, cache ); const QString databasePath = GtfsDatabase::databasePath( providerId ); const QFileInfo databaseInfo( databasePath ); const bool databaseReady = importFinished && databaseInfo.exists(); if ( databaseReady ) { // Check if an update is available const QString feedModifiedTimeString = gtfsGroup.readEntry( "feedModifiedTime", QString() ); const QDateTime gtfsFeedModifiedTime = QDateTime::fromString( feedModifiedTimeString, Qt::ISODate ); const QDateTime gtfsDatabaseModifiedTime = databaseInfo.lastModified(); return gtfsFeedModifiedTime.isValid() && gtfsFeedModifiedTime > gtfsDatabaseModifiedTime; } // GTFS feed not imported or database deleted return false; } uint ServiceProviderGtfs::stopIdFromName( const QString &stopName, bool *ok ) { // Try to get the ID for the given stop name. Only select stops, no stations (with one or // more sub stops) by requiring 'location_type=0', location_type 1 is for stations. // It's fast, because 'stop_name' is part of a compound index in the database. QString stopValue = stopName; stopValue.replace( '\'', "\'\'" ); QSqlQuery query( QSqlDatabase::database(m_data->id()) ); query.setForwardOnly( true ); // Don't cache records if ( !query.exec("SELECT stops.stop_id FROM stops WHERE stop_name='" + stopValue + "' " "AND (location_type IS NULL OR location_type=0)") ) { - kWarning() << query.lastError(); + qWarning() << query.lastError(); kDebug() << query.executedQuery(); if ( ok ) { *ok = false; } return 0; } QSqlRecord stopRecord = query.record(); if ( query.next() ) { if ( ok ) { *ok = true; } return query.value( query.record().indexOf("stop_id") ).toUInt(); } else { bool _ok; const uint stopId = stopName.toUInt( &_ok ); if ( ok ) { *ok = _ok; } if ( !_ok ) { kDebug() << "No stop with the given name found (needs the exact name):" << stopName; return 0; } return stopId; } } void ServiceProviderGtfs::requestDepartures( const DepartureRequest &request ) { requestDeparturesOrArrivals( &request ); } void ServiceProviderGtfs::requestArrivals( const ArrivalRequest &request ) { requestDeparturesOrArrivals( &request ); } void ServiceProviderGtfs::requestDeparturesOrArrivals( const DepartureRequest *request ) { uint stopId; if ( !request->stopId().isEmpty() ) { // A stop ID is available, testing for it's ID in stop_times is not necessary bool ok; stopId = request->stopId().toUInt( &ok ); if ( !ok ) { - kWarning() << "Invalid stop ID" << request->stopId() << "only numeric IDs allowed"; + qWarning() << "Invalid stop ID" << request->stopId() << "only numeric IDs allowed"; return; } } else { // Try to get the ID for the given stop name. bool ok; stopId = stopIdFromName( request->stop(), &ok ); if ( !ok ) { emit requestFailed( this, ErrorParsingFailed /*TODO*/, "No stop with the given name found (needs the exact name or an ID): " + request->stop(), QUrl(), request ); return; } } QSqlQuery query( QSqlDatabase::database(m_data->id()) ); query.setForwardOnly( true ); // Don't cache records // This creates a temporary table to calculate min/max fares for departures. // These values should be added into the db while importing, doing it here takes too long // const QString createJoinedFareTable = "CREATE TEMPORARY TABLE IF NOT EXISTS tmp_fares AS " // "SELECT * FROM fare_rules JOIN fare_attributes USING (fare_id);"; // if ( !query.prepare(createJoinedFareTable) || !query.exec() ) { // kDebug() << "Error while creating a temporary table fore min/max fare calculation:" // << query.lastError(); // kDebug() << query.executedQuery(); // return; // } // Query the needed departure info from the database. // It's fast, because all JOINs are done using INTEGER PRIMARY KEYs and // because 'stop_id' and 'departure_time' are part of a compound index in the database. // Sorting by 'arrival_time' may be a bit slower because is has no index in the database, // but if arrival_time values do not differ too much from the deaprture_time values, they // are also already sorted. // The tables 'calendar' and 'calendar_dates' are also fully implemented by the query below. // TODO: Create a new (temporary) table for each connected departure/arrival source and use // that (much smaller) table here for performance reasons const QString routeSeparator = "||"; const QTime time = request->dateTime().time(); const QString queryString = QString( "SELECT times.departure_time, times.arrival_time, times.stop_headsign, " "routes.route_type, routes.route_short_name, routes.route_long_name, " "trips.trip_headsign, routes.agency_id, stops.stop_id, trips.trip_id, " "routes.route_id, times.stop_sequence, " "( SELECT group_concat(route_stop.stop_name, '%5') AS route_stops " "FROM stop_times AS route_times INNER JOIN stops AS route_stop USING (stop_id) " "WHERE route_times.trip_id=times.trip_id AND route_times.stop_sequence %4= times.stop_sequence " "ORDER BY departure_time ) AS route_stops, " "( SELECT group_concat(route_times.departure_time, '%5') AS route_times " "FROM stop_times AS route_times " "WHERE route_times.trip_id=times.trip_id AND route_times.stop_sequence %4= times.stop_sequence " "ORDER BY departure_time ) AS route_times " // "( SELECT min(price) FROM tmp_fares WHERE origin_id=stops.zone_id AND price>0 ) AS min_price, " // "( SELECT max(price) FROM tmp_fares WHERE origin_id=stops.zone_id ) AS max_price, " // "( SELECT currency_type FROM tmp_fares WHERE origin_id=stops.zone_id LIMIT 1 ) AS currency_type " "FROM stops INNER JOIN stop_times AS times USING (stop_id) " "INNER JOIN trips USING (trip_id) " "INNER JOIN routes USING (route_id) " "LEFT JOIN calendar USING (service_id) " "LEFT JOIN calendar_dates ON (trips.service_id=calendar_dates.service_id " "AND strftime('%Y%m%d') LIKE calendar_dates.date) " "WHERE stop_id=%1 AND departure_time>%2 " "AND (calendar_dates.date IS NULL " // No matching record in calendar_dates table for today "OR NOT (calendar_dates.exception_type=2)) " // Journey is not removed today "AND (calendar.weekdays IS NULL " // No matching record in calendar table => always available "OR (strftime('%Y%m%d') BETWEEN calendar.start_date " // Current date is in the range... "AND calendar.end_date " // ...where the service is available... "AND substr(calendar.weekdays, strftime('%w') + 1, 1)='1') " // ...and it's available at the current weekday "OR (calendar_dates.date IS NOT NULL " // Or there is a matching record in calendar_dates for today... "AND calendar_dates.exception_type=1)) " // ...and this record adds availability of the service for today "ORDER BY departure_time " "LIMIT %3" ) .arg( stopId ) .arg( time.hour() * 60 * 60 + time.minute() * 60 + time.second() ) .arg( request->count() ) .arg( request->parseMode() == ParseForArrivals ? '<' : '>' ) // For arrivals route_stops/route_times need stops before the home stop .arg( routeSeparator ); if ( !query.prepare(queryString) || !query.exec() ) { kDebug() << "Error while querying for departures:" << query.lastError(); kDebug() << query.executedQuery(); return; } if ( query.size() == 0 ) { kDebug() << "Got an empty record"; return; } kDebug() << "Query executed"; kDebug() << query.executedQuery(); QSqlRecord record = query.record(); const int agencyIdColumn = record.indexOf( "agency_id" ); const int tripIdColumn = record.indexOf( "trip_id" ); const int routeIdColumn = record.indexOf( "route_id" ); const int stopIdColumn = record.indexOf( "stop_id" ); const int arrivalTimeColumn = record.indexOf( "arrival_time" ); const int departureTimeColumn = record.indexOf( "departure_time" ); const int routeShortNameColumn = record.indexOf( "route_short_name" ); const int routeLongNameColumn = record.indexOf( "route_long_name" ); const int routeTypeColumn = record.indexOf( "route_type" ); const int tripHeadsignColumn = record.indexOf( "trip_headsign" ); const int stopSequenceColumn = record.indexOf( "stop_sequence" ); const int stopHeadsignColumn = record.indexOf( "stop_headsign" ); const int routeStopsColumn = record.indexOf( "route_stops" ); const int routeTimesColumn = record.indexOf( "route_times" ); // const int fareMinPriceColumn = record.indexOf( "min_price" ); // const int fareMaxPriceColumn = record.indexOf( "max_price" ); // const int fareCurrencyColumn = record.indexOf( "currency_type" ); // Prepare agency information, if only one is given, it is used for all records AgencyInformation *agency = 0; if ( m_agencyCache.count() == 1 ) { agency = m_agencyCache.values().first(); } // Create a list of DepartureInfo objects from the query result DepartureInfoList departures; while ( query.next() ) { const QDate dateAtMidnight = request->dateTime().date(); // Load agency information from cache const QVariant agencyIdValue = query.value( agencyIdColumn ); if ( m_agencyCache.count() > 1 ) { Q_ASSERT( agencyIdValue.isValid() ); // GTFS says, that agency_id can only be null, if there is only one agency agency = m_agencyCache[ agencyIdValue.toUInt() ]; } // Time values are stored as seconds since midnight of the associated date int arrivalTimeValue = query.value(arrivalTimeColumn).toInt(); int departureTimeValue = query.value(departureTimeColumn).toInt(); QDateTime arrivalTime = timeFromSecondsSinceMidnight( dateAtMidnight, arrivalTimeValue ); QDateTime departureTime = timeFromSecondsSinceMidnight( dateAtMidnight, departureTimeValue ); // Apply timezone offset int offsetSeconds = agency ? agency->timeZoneOffset() : 0; if ( offsetSeconds != 0 ) { arrivalTime.addSecs( offsetSeconds ); departureTime.addSecs( offsetSeconds ); } TimetableData data; data[ Enums::DepartureDateTime ] = request->parseMode() == ParseForArrivals ? arrivalTime : departureTime; data[ Enums::TypeOfVehicle ] = vehicleTypeFromGtfsRouteType( query.value(routeTypeColumn).toInt() ); data[ Enums::Operator ] = agency ? agency->name : QString(); const QString transportLine = query.value(routeShortNameColumn).toString(); data[ Enums::TransportLine ] = !transportLine.isEmpty() ? transportLine : query.value(routeLongNameColumn).toString(); const QStringList routeStops = query.value(routeStopsColumn).toString().split( routeSeparator ); if ( routeStops.isEmpty() ) { // This happens, if the current departure is actually no departure, but an arrival at // the target station and vice versa for arrivals. continue; } data[ Enums::RouteStops ] = routeStops; data[ Enums::RouteExactStops ] = routeStops.count(); const QString tripHeadsign = query.value(tripHeadsignColumn).toString(); const QString stopHeadsign = query.value(stopHeadsignColumn).toString(); data[ Enums::Target ] = !tripHeadsign.isEmpty() ? tripHeadsign : (!stopHeadsign.isEmpty() ? stopHeadsign : (request->parseMode() == ParseForArrivals ? routeStops.first() : routeStops.last())); const QStringList routeTimeValues = query.value(routeTimesColumn).toString().split( routeSeparator ); QVariantList routeTimes; foreach ( const QString routeTimeValue, routeTimeValues ) { routeTimes << timeFromSecondsSinceMidnight( dateAtMidnight, routeTimeValue.toInt() ); } data[ Enums::RouteTimes ] = routeTimes; // const QString symbol = KCurrencyCode( query.value(fareCurrencyColumn).toString() ).defaultSymbol(); // data[ Pricing ] = KGlobal::locale()->formatMoney( // query.value(fareMinPriceColumn).toDouble(), symbol ) + " - " + // KGlobal::locale()->formatMoney( query.value(fareMaxPriceColumn).toDouble(), symbol ); #ifdef BUILD_GTFS_REALTIME if ( m_alerts ) { QStringList journeyNews; QString journeyNewsLink; foreach ( const GtfsRealtimeAlert &alert, *m_alerts ) { if ( alert.isActiveAt(QDateTime::currentDateTime()) ) { journeyNews << alert.description; journeyNewsLink = alert.url; } } if ( !journeyNews.isEmpty() ) { data[ Enums::JourneyNews ] = journeyNews.join( ", " ); data[ Enums::JourneyNewsLink ] = journeyNewsLink; } } if ( m_tripUpdates ) { uint tripId = query.value(tripIdColumn).toUInt(); uint routeId = query.value(routeIdColumn).toUInt(); uint stopId = query.value(stopIdColumn).toUInt(); uint stopSequence = query.value(stopSequenceColumn).toUInt(); foreach ( const GtfsRealtimeTripUpdate &tripUpdate, *m_tripUpdates ) { if ( (tripUpdate.tripId > 0 && tripId == tripUpdate.tripId) || (tripUpdate.routeId > 0 && routeId == tripUpdate.routeId) || (tripUpdate.tripId <= 0 && tripUpdate.routeId <= 0) ) { kDebug() << "tripId or routeId matched or not queried!"; foreach ( const GtfsRealtimeStopTimeUpdate &stopTimeUpdate, tripUpdate.stopTimeUpdates ) { if ( (stopTimeUpdate.stopId > 0 && stopId == stopTimeUpdate.stopId) || (stopTimeUpdate.stopSequence > 0 && stopSequence == stopTimeUpdate.stopSequence) || (stopTimeUpdate.stopId <= 0 && stopTimeUpdate.stopSequence <= 0) ) { kDebug() << "stopId matched or stopsequence matched or not queried!"; // Found a matching stop time update kDebug() << "Delays:" << stopTimeUpdate.arrivalDelay << stopTimeUpdate.departureDelay; } } } } } #endif // Create new departure information object and add it to the departure list. // Do not use any corrections in the DepartureInfo constructor, because all values // from the database are already in the correct format departures << DepartureInfoPtr( new DepartureInfo(data, PublicTransportInfo::NoCorrection) ); } // TODO Do not use a list of pointers here, maybe use data sharing for PublicTransportInfo/StopInfo? // The objects in departures are deleted in a connected slot in the data engine... const ArrivalRequest *arrivalRequest = dynamic_cast< const ArrivalRequest* >( request ); if ( arrivalRequest ) { emit arrivalsReceived( this, QUrl(), departures, GlobalTimetableInfo(), *arrivalRequest ); } else { emit departuresReceived( this, QUrl(), departures, GlobalTimetableInfo(), *request ); } } void ServiceProviderGtfs::requestStopSuggestions( const StopSuggestionRequest &request ) { QSqlQuery query( QSqlDatabase::database(m_data->id()) ); query.setForwardOnly( true ); QString stopValue = request.stop(); stopValue.replace( '\'', "\'\'" ); if ( !query.prepare(QString("SELECT * FROM stops WHERE stop_name LIKE '%%2%' LIMIT %1") .arg(STOP_SUGGESTION_LIMIT).arg(stopValue)) || !query.exec() ) { // Check of the error is a "disk I/O error", ie. the database file may have been deleted checkForDiskIoError( query.lastError(), &request ); kDebug() << query.lastError(); kDebug() << query.executedQuery(); return; } emit stopsReceived( this, QUrl(), stopsFromQuery(&query, &request), request ); } void ServiceProviderGtfs::requestStopsByGeoPosition( const StopsByGeoPositionRequest &request ) { QSqlQuery query( QSqlDatabase::database(m_data->id()) ); query.setForwardOnly( true ); kDebug() << "Get stops near:" << request.distance() << "meters ==" << (request.distance() * 0.009 / 2); if ( !query.prepare(QString("SELECT * FROM stops " "WHERE stop_lon between (%2-%4) and (%2+%4) " "AND stop_lat between (%3-%4) and (%3+%4) LIMIT %1") .arg(STOP_SUGGESTION_LIMIT).arg(request.longitude()).arg(request.latitude()) .arg(request.distance() * 0.000009 / 2)) // Calculate degree from meters = 360/40,070,000 || !query.exec() ) { // Check of the error is a "disk I/O error", ie. the database file may have been deleted checkForDiskIoError( query.lastError(), &request ); kDebug() << query.lastError(); kDebug() << query.executedQuery(); return; } emit stopsReceived( this, QUrl(), stopsFromQuery(&query, &request), request ); } StopInfoList ServiceProviderGtfs::stopsFromQuery( QSqlQuery *query, const StopSuggestionRequest *request ) const { QSqlRecord record = query->record(); const int stopIdColumn = record.indexOf( "stop_id" ); const int stopNameColumn = record.indexOf( "stop_name" ); const int stopLongitudeColumn = record.indexOf( "stop_lon" ); const int stopLatitudeColumn = record.indexOf( "stop_lat" ); StopInfoList stops; while ( query->next() ) { const QString stopName = query->value(stopNameColumn).toString(); const QString id = query->value(stopIdColumn).toString(); const qreal longitude = query->value(stopLongitudeColumn).toReal(); const qreal latitude = query->value(stopLatitudeColumn).toReal(); int weight = -1; if ( !dynamic_cast(request) ) { // Compute a weight value for the found stop name. // The less different the found stop name is compared to the search string, the higher // it's weight gets. If the found name equals the search string, the weight becomes 100. // Use 84 as maximal starting weight value (if stopName doesn't equal the search string), // because maximally 15 bonus points are added which makes 99, less than total equality 100. weight = stopName == request->stop() ? 100 : 84 - qMin( 84, qAbs(stopName.length() - request->stop().length()) ); if ( weight < 100 && stopName.startsWith(request->stop()) ) { // 15 weight points bonus if the found stop name starts with the search string weight = qMin( 100, weight + 15 ); } if ( weight < 100 ) { // Test if the search string is the start of a new word in stopName // Start at 2, because startsWith is already tested above and at least a space must // follow to start a new word int pos = stopName.indexOf( request->stop(), 2, Qt::CaseInsensitive ); if ( pos != -1 && stopName[pos - 1].isSpace() ) { // 10 weight points bonus if a word in the found stop name // starts with the search string weight = qMin( 100, weight + 10 ); } } } stops << StopInfoPtr( new StopInfo(stopName, id, weight, longitude, latitude, request->city()) ); } if ( stops.isEmpty() ) { kDebug() << "No stops found"; } return stops; } bool ServiceProviderGtfs::checkForDiskIoError( const QSqlError &error, const AbstractRequest *request ) { Q_UNUSED( request ); // Check if the error is a "disk I/O" error or a "no such table" error, // ie. the database file may have been deleted/corrupted. // The error numbers (1, 10) are database dependend and work with SQLite if ( error.number() == 10 || error.number() == 1 ) { - kWarning() << "Disk I/O error reported from database, reimport the GTFS feed" + qWarning() << "Disk I/O error reported from database, reimport the GTFS feed" << error.text(); emit requestFailed( this, ErrorParsingFailed, i18nc("@info/plain", "The GTFS database is corrupted, please reimport " "the GTFS feed"), QUrl(), request ); m_state = Initializing; QString errorText; if ( !GtfsDatabase::initDatabase(m_data->id(), &errorText) ) { kDebug() << "Error initializing the database" << errorText; m_state = Error; return true; } QFileInfo fi( GtfsDatabase::databasePath(m_data->id()) ); if ( fi.exists() && fi.size() > 10000 ) { loadAgencyInformation(); #ifdef BUILD_GTFS_REALTIME updateRealtimeData(); #endif } return true; } else { return false; } } Enums::VehicleType ServiceProviderGtfs::vehicleTypeFromGtfsRouteType( int gtfsRouteType ) { switch ( gtfsRouteType ) { case 0: // Tram, Streetcar, Light rail. Any light rail or street level system within a metropolitan area. return Enums::Tram; case 1: // Subway, Metro. Any underground rail system within a metropolitan area. return Enums::Subway; case 2: // Rail. Used for intercity or long-distance travel. return Enums::IntercityTrain; case 3: // Bus. Used for short- and long-distance bus routes. return Enums::Bus; case 4: // Ferry. Used for short- and long-distance boat service. return Enums::Ferry; case 5: // Cable car. Used for street-level cable cars where the cable runs beneath the car. return Enums::TrolleyBus; case 6: // Gondola, Suspended cable car. Typically used for aerial cable cars where the car is suspended from the cable. return Enums::UnknownVehicleType; // TODO Add new type to VehicleType: eg. Gondola case 7: // Funicular. Any rail system designed for steep inclines. return Enums::UnknownVehicleType; // TODO Add new type to VehicleType: eg. Funicular default: return Enums::UnknownVehicleType; } } diff --git a/engine/publictransportdataengine.cpp b/engine/publictransportdataengine.cpp index 8fe024f..7af437e 100644 --- a/engine/publictransportdataengine.cpp +++ b/engine/publictransportdataengine.cpp @@ -1,2744 +1,2744 @@ /* * Copyright 2013 Friedrich Pülz * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as * published by the Free Software Foundation; either version 2 or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ // Header #include "publictransportdataengine.h" // Own includes #include "serviceprovider.h" #include "serviceproviderdata.h" #include "serviceprovidertestdata.h" #include "serviceproviderglobal.h" #include "global.h" #include "request.h" #include "timetableservice.h" #include "datasource.h" #ifdef BUILD_PROVIDER_TYPE_SCRIPT #include "script/serviceproviderscript.h" #endif #ifdef BUILD_PROVIDER_TYPE_GTFS #include "gtfs/serviceprovidergtfs.h" #include "gtfs/gtfsservice.h" #endif // KDE/Plasma includes #include #include // Qt includes #include #include #include #include #include const int PublicTransportEngine::DEFAULT_TIME_OFFSET = 0; const int PublicTransportEngine::PROVIDER_CLEANUP_TIMEOUT = 10000; // 10 seconds Plasma::Service* PublicTransportEngine::serviceForSource( const QString &name ) { #ifdef BUILD_PROVIDER_TYPE_GTFS // Return the GTFS service for "GTFS" or "gtfs" names if ( name.toLower() == QLatin1String("gtfs") ) { GtfsService *service = new GtfsService( name, this ); service->setDestination( name ); connect( service, SIGNAL(finished(Plasma::ServiceJob*)), this, SLOT(gtfsServiceJobFinished(Plasma::ServiceJob*)) ); return service; } #endif // If the name of a data requesting source is given, return the timetable service const SourceType type = sourceTypeFromName( name ); if ( isDataRequestingSourceType(type) ) { const QString nonAmbiguousName = disambiguateSourceName( name ); if ( m_dataSources.contains(nonAmbiguousName) ) { // Data source exists TimetableService *service = new TimetableService( this, name, this ); service->setDestination( name ); return service; } } // No service for the given name found return 0; } void PublicTransportEngine::publishData( DataSource *dataSource, const QString &newlyRequestedProviderId ) { Q_ASSERT( dataSource ); TimetableDataSource *timetableDataSource = dynamic_cast< TimetableDataSource* >( dataSource ); if ( timetableDataSource ) { foreach ( const QString &usingDataSource, timetableDataSource->usingDataSources() ) { setData( usingDataSource, timetableDataSource->data() ); } return; } setData( dataSource->name(), dataSource->data() ); ProvidersDataSource *providersSource = dynamic_cast< ProvidersDataSource* >( dataSource ); if ( providersSource ) { // Update "ServiceProvider " sources, which are also contained in the // DataSource object for the "ServiceProviders" data source. // Check which data sources of changed providers of that type are connected QStringList sources = Plasma::DataEngine::sources(); const QStringList changedProviders = providersSource->takeChangedProviders(); foreach ( const QString changedProviderId, changedProviders ) { const QString providerSource = sourceTypeKeyword(ServiceProviderSource) + ' ' + changedProviderId; if ( sources.contains(providerSource) ) { // Found a data source for the current changed provider, clear it and set new data removeAllData( providerSource ); setData( providerSource, providersSource->providerData(changedProviderId) ); } } if ( !newlyRequestedProviderId.isEmpty() ) { const QString providerSource = sourceTypeKeyword(ServiceProviderSource) + ' ' + newlyRequestedProviderId; removeAllData( providerSource ); setData( providerSource, providersSource->providerData(newlyRequestedProviderId) ); } } } ProvidersDataSource *PublicTransportEngine::providersDataSource() const { const QString name = sourceTypeKeyword( ServiceProvidersSource ); ProvidersDataSource *dataSource = dynamic_cast< ProvidersDataSource* >( m_dataSources[name] ); Q_ASSERT_X( dataSource, "PublicTransportEngine::providersDataSource()", "ProvidersDataSource is not available in m_dataSources!" ); return dataSource; } #ifdef BUILD_PROVIDER_TYPE_GTFS bool PublicTransportEngine::tryToStartGtfsFeedImportJob( Plasma::ServiceJob *job ) { Q_ASSERT( job ); updateServiceProviderSource(); ProvidersDataSource *dataSource = providersDataSource(); Q_ASSERT( dataSource ); const QString providerId = job->property( "serviceProviderId" ).toString(); if ( dataSource->providerState(providerId) == QLatin1String("importing_gtfs_feed") ) { // GTFS feed already gets imported, cannot start another import job return false; } // Update provider state in service provider data source(s) QVariantHash stateData = dataSource->providerStateData( providerId ); const QString databasePath = GtfsDatabase::databasePath( providerId ); stateData[ "gtfsDatabasePath" ] = databasePath; stateData[ "gtfsDatabaseSize" ] = 0; stateData[ "progress" ] = 0; QString state; if ( job->operationName() == QLatin1String("importGtfsFeed") ) { state = "importing_gtfs_feed"; } else if ( job->operationName() == QLatin1String("deleteGtfsDatabase") ) { state = "gtfs_feed_import_pending"; } else { // The operations "updateGtfsDatabase" and "updateGtfsFeedInfo" can run in the background state = "ready"; } dataSource->setProviderState( providerId, state, stateData ); // Store the state in the cache QSharedPointer< KConfig > cache = ServiceProviderGlobal::cache(); KConfigGroup group = cache->group( providerId ); group.writeEntry( "state", state ); KConfigGroup stateGroup = group.group( "stateData" ); for ( QVariantHash::ConstIterator it = stateData.constBegin(); it != stateData.constEnd(); ++it ) { if ( isStateDataCached(it.key()) ) { stateGroup.writeEntry( it.key(), it.value() ); } } publishData( dataSource ); // Connect to messages of the job to update the provider state connect( job, SIGNAL(infoMessage(KJob*,QString,QString)), this, SLOT(gtfsImportJobInfoMessage(KJob*,QString,QString)) ); connect( job, SIGNAL(percent(KJob*,ulong)), this, SLOT(gtfsImportJobPercent(KJob*,ulong)) ); // The import job can be started return true; } void PublicTransportEngine::gtfsServiceJobFinished( Plasma::ServiceJob *job ) { // Disconnect messages of the job disconnect( job, SIGNAL(infoMessage(KJob*,QString,QString)), this, SLOT(gtfsImportJobInfoMessage(KJob*,QString,QString)) ); disconnect( job, SIGNAL(percent(KJob*,ulong)), this, SLOT(gtfsImportJobPercent(KJob*,ulong)) ); // Check that the job was not canceled because another database job was already running const bool canAccessGtfsDatabase = job->property("canAccessGtfsDatabase").toBool(); const bool isAccessingGtfsDatabase = job->property("isAccessingGtfsDatabase").toBool(); const QString providerId = job->property( "serviceProviderId" ).toString(); if ( (!canAccessGtfsDatabase && isAccessingGtfsDatabase) || providerId.isEmpty() ) { // Invalid job or cancelled, because another import job is already running // for the provider return; } // Reset state in "ServiceProviders", "ServiceProvider " data sources // Do not read and give the current feed URL for the provider to updateProviderState(), // because the feed URL should not have changed since the beginning of the feed import QVariantHash stateData; const QString state = updateProviderState( providerId, &stateData, "GTFS", QString(), false ); ProvidersDataSource *dataSource = providersDataSource(); dataSource->setProviderState( providerId, state, stateData ); publishData( dataSource ); } void PublicTransportEngine::gtfsImportJobInfoMessage( KJob *job, const QString &plain, const QString &rich ) { // Update "ServiceProviders", "ServiceProvider " data sources const QString providerId = job->property( "serviceProviderId" ).toString(); ProvidersDataSource *dataSource = providersDataSource(); QVariantHash stateData = dataSource->providerStateData( providerId ); stateData[ "statusMessage" ] = plain; if ( rich.isEmpty() ) { stateData.remove( "statusMessageRich" ); } else { stateData[ "statusMessageRich" ] = rich; } dataSource->setProviderStateData( providerId, stateData ); publishData( dataSource ); } void PublicTransportEngine::gtfsImportJobPercent( KJob *job, ulong percent ) { // Update "ServiceProviders", "ServiceProvider " data sources const QString providerId = job->property( "serviceProviderId" ).toString(); ProvidersDataSource *dataSource = providersDataSource(); QVariantHash stateData = dataSource->providerStateData( providerId ); stateData[ "progress" ] = int( percent ); dataSource->setProviderStateData( providerId, stateData ); publishData( dataSource ); } #endif // BUILD_PROVIDER_TYPE_GTFS PublicTransportEngine::PublicTransportEngine( QObject* parent, const QVariantList& args ) : Plasma::DataEngine( parent, args ), m_fileSystemWatcher(0), m_providerUpdateDelayTimer(0), m_cleanupTimer(0) { // We ignore any arguments - data engines do not have much use for them Q_UNUSED( args ) // This prevents applets from setting an unnecessarily high update interval // and using too much CPU. // 60 seconds should be enough, departure / arrival times have minute precision (except for GTFS). setMinimumPollingInterval( 60000 ); // Cleanup the cache from obsolete data for providers that were uninstalled // while the engine was not running ServiceProviderGlobal::cleanupCache(); // Get notified when data sources are no longer used connect( this, SIGNAL(sourceRemoved(QString)), this, SLOT(slotSourceRemoved(QString)) ); // Get notified when the network state changes to update data sources, // which update timers were missed because of missing network connection QDBusConnection::sessionBus().connect( "org.kde.kded", "/modules/networkstatus", "org.kde.Solid.Networking.Client", "statusChanged", this, SLOT(networkStateChanged(uint)) ); // Create "ServiceProviders" and "ServiceProvider [providerId]" data source object const QString name = sourceTypeKeyword( ServiceProvidersSource ); m_dataSources.insert( name, new ProvidersDataSource(name) ); updateServiceProviderSource(); // Ensure the local provider installation directory exists in the users HOME and will not // get removed, by creating a small file in it so that the directory is never empty. // If an installation directory gets removed, the file system watcher would need to watch the // parent directory instead to get notified when it gets created again. const QString installationSubDirectory = ServiceProviderGlobal::installationSubDirectory(); const QString saveDir = KGlobal::dirs()->saveLocation( "data", installationSubDirectory ); QFile saveDirKeeper( saveDir + "Do not remove this directory" ); saveDirKeeper.open( QIODevice::WriteOnly ); saveDirKeeper.write( "If this directory gets removed, PublicTransport will not get notified " "about installed provider files in that directory." ); saveDirKeeper.close(); // Create a file system watcher for the provider plugin installation directories // to get notified about new/modified/removed providers const QStringList directories = KGlobal::dirs()->findDirs( "data", installationSubDirectory ); m_fileSystemWatcher = new QFileSystemWatcher( directories ); connect( m_fileSystemWatcher, SIGNAL(directoryChanged(QString)), this, SLOT(serviceProviderDirChanged(QString)) ); } PublicTransportEngine::~PublicTransportEngine() { if ( !m_runningSources.isEmpty() || !m_providers.isEmpty() ) { qDebug() << m_runningSources.count() << "data sources are still being updated," << m_providers.count() << "providers used, abort and delete all providers"; QStringList providerIds = m_providers.keys(); foreach ( const QString &providerId, providerIds ) { deleteProvider( providerId, false ); } } delete m_fileSystemWatcher; delete m_providerUpdateDelayTimer; qDeleteAll( m_dataSources ); m_dataSources.clear(); // Providers cached in m_cachedProviders get deleted automatically (QSharedPointer) // and need no special handling, since they are not used currently } QStringList PublicTransportEngine::sources() const { QStringList sources = Plasma::DataEngine::sources(); sources << sourceTypeKeyword(LocationsSource) << sourceTypeKeyword(ServiceProvidersSource) << sourceTypeKeyword(ErroneousServiceProvidersSource) << sourceTypeKeyword(VehicleTypesSource); sources.removeDuplicates(); return sources; } void PublicTransportEngine::networkStateChanged( uint state ) { if ( state != 4 ) { // 4 => Connected, see Solid::Networking::Status return; } // Network is connected again, check for missed update timers in connected data sources for ( QHash::ConstIterator it = m_dataSources.constBegin(); it != m_dataSources.constEnd(); ++it ) { // Check if the current data source is a timetable data source, without running update TimetableDataSource *dataSource = dynamic_cast< TimetableDataSource* >( *it ); if ( !dataSource || m_runningSources.contains(it.key()) ) { continue; } // Check if the next automatic update time was missed (stored in the data source) const QDateTime nextAutomaticUpdate = dataSource->value("nextAutomaticUpdate").toDateTime(); if ( nextAutomaticUpdate <= QDateTime::currentDateTime() ) { // Found a timetable data source that should have been updated already and // is not currently being updated (not in m_runningSources). // This happens if there was no network connection while an automatic update // was triggered. If the system is suspended the QTimer's for automatic updates // are not triggered at all. // Do now manually request updates for all connected sources, ie. do what should // have been done in updateTimeout(). foreach ( const QString &sourceName, dataSource->usingDataSources() ) { updateTimetableDataSource( SourceRequestData(sourceName) ); } } } } bool PublicTransportEngine::isProviderUsed( const QString &providerId ) { // Check if a request is currently running for the provider foreach ( const QString &runningSource, m_runningSources ) { if ( runningSource.contains(providerId) ) { return true; } } // Check if a data source is connected that uses the provider for ( QHash< QString, DataSource* >::ConstIterator it = m_dataSources.constBegin(); it != m_dataSources.constEnd(); ++it ) { Q_ASSERT( *it ); TimetableDataSource *dataSource = dynamic_cast< TimetableDataSource* >( *it ); if ( dataSource && dataSource->providerId() == providerId ) { return true; } } // The provider is not used any longer by the engine return false; } void PublicTransportEngine::slotSourceRemoved( const QString &sourceName ) { const QString nonAmbiguousName = disambiguateSourceName( sourceName ); if ( m_dataSources.contains(nonAmbiguousName) ) { // If this is a timetable data source, which might be associated with multiple // ambiguous source names, check if this data source is still connected under other names TimetableDataSource *timetableDataSource = dynamic_cast< TimetableDataSource* >( m_dataSources[nonAmbiguousName] ); if ( timetableDataSource ) { timetableDataSource->removeUsingDataSource( sourceName ); if ( timetableDataSource->usageCount() > 0 ) { // The TimetableDataSource object is still used by other connected data sources return; } } if ( sourceName == sourceTypeKeyword(ServiceProvidersSource) ) { // Do not remove ServiceProviders data source return; } // If a provider was used by the source, // remove the provider if it is not used by another source const DataSource *dataSource = m_dataSources.take( nonAmbiguousName ); Q_ASSERT( dataSource ); if ( dataSource->data().contains("serviceProvider") ) { const QString providerId = dataSource->value("serviceProvider").toString(); if ( !providerId.isEmpty() && !isProviderUsed(providerId) ) { // Move provider from the list of used providers to the list of cached providers m_cachedProviders.insert( providerId, m_providers.take(providerId) ); } } // Start the cleanup timer, will delete cached providers after a timeout startCleanupLater(); // The data source is no longer used, delete it delete dataSource; } else if ( nonAmbiguousName.startsWith(sourceTypeKeyword(ServiceProviderSource)) ) { // A "ServiceProvider xx_xx" data source was removed, data for these sources // is stored in the "ServiceProviders" data source object in m_dataSources. // Remove not installed providers also from the "ServiceProviders" data source. const QString providerId = nonAmbiguousName.mid( QString(sourceTypeKeyword(ServiceProviderSource)).length() + 1 ); if ( !providerId.isEmpty() && !isProviderUsed(providerId) ) { // Test if the provider is installed const QStringList providerPaths = ServiceProviderGlobal::installedProviders(); bool isInstalled = false; foreach ( const QString &providerPath, providerPaths ) { const QString &installedProviderId = ServiceProviderGlobal::idFromFileName( providerPath ); if ( providerId == installedProviderId ) { isInstalled = true; break; } } if ( !isInstalled ) { qDebug() << "Remove provider" << providerId; // Provider is not installed, remove it from the "ServiceProviders" data source providersDataSource()->removeProvider( providerId ); removeData( sourceTypeKeyword(ServiceProvidersSource), providerId ); } } } } void PublicTransportEngine::startCleanupLater() { // Create the timer if it is not currently running if ( !m_cleanupTimer ) { m_cleanupTimer = new QTimer( this ); m_cleanupTimer->setInterval( PROVIDER_CLEANUP_TIMEOUT ); connect( m_cleanupTimer, SIGNAL(timeout()), this, SLOT(cleanup()) ); } // (Re)start the timer m_cleanupTimer->start(); } void PublicTransportEngine::cleanup() { // Delete the timer delete m_cleanupTimer; m_cleanupTimer = 0; // Remove all shared pointers of unused cached providers, // ie. delete the provider objects m_cachedProviders.clear(); } QVariantHash PublicTransportEngine::serviceProviderData( const ServiceProvider *provider ) { Q_ASSERT( provider ); return serviceProviderData( *(provider->data()), provider ); } QVariantHash PublicTransportEngine::serviceProviderData( const ServiceProviderData &data, const ServiceProvider *provider ) { QVariantHash dataServiceProvider; dataServiceProvider.insert( "id", data.id() ); dataServiceProvider.insert( "fileName", data.fileName() ); dataServiceProvider.insert( "type", ServiceProviderGlobal::typeName(data.type()) ); #ifdef BUILD_PROVIDER_TYPE_GTFS if ( data.type() == Enums::GtfsProvider ) { dataServiceProvider.insert( "feedUrl", data.feedUrl() ); } #endif #ifdef BUILD_PROVIDER_TYPE_SCRIPT if ( data.type() == Enums::ScriptedProvider ) { dataServiceProvider.insert( "scriptFileName", data.scriptFileName() ); } #endif dataServiceProvider.insert( "name", data.name() ); dataServiceProvider.insert( "url", data.url() ); dataServiceProvider.insert( "shortUrl", data.shortUrl() ); dataServiceProvider.insert( "country", data.country() ); dataServiceProvider.insert( "cities", data.cities() ); dataServiceProvider.insert( "credit", data.credit() ); dataServiceProvider.insert( "useSeparateCityValue", data.useSeparateCityValue() ); dataServiceProvider.insert( "onlyUseCitiesInList", data.onlyUseCitiesInList() ); dataServiceProvider.insert( "author", data.author() ); dataServiceProvider.insert( "shortAuthor", data.shortAuthor() ); dataServiceProvider.insert( "email", data.email() ); dataServiceProvider.insert( "description", data.description() ); dataServiceProvider.insert( "version", data.version() ); QStringList changelog; foreach ( const ChangelogEntry &entry, data.changelog() ) { changelog << QString( "%2 (%1): %3" ).arg( entry.version ).arg( entry.author ).arg( entry.description ); } dataServiceProvider.insert( "changelog", changelog ); // To get the list of features, ServiceProviderData is not enough // A given ServiceProvider or cached data gets used if available. Otherwise the ServiceProvider // gets created just to get the list of features const QSharedPointer cache = ServiceProviderGlobal::cache(); KConfigGroup providerGroup = cache->group( data.id() ); if ( provider ) { // Write features to the return value const QList< Enums::ProviderFeature > features = provider->features(); const QStringList featureStrings = ServiceProviderGlobal::featureStrings( features ); dataServiceProvider.insert( "features", featureStrings ); dataServiceProvider.insert( "featureNames", ServiceProviderGlobal::featureNames(features) ); // Make sure, features have been written to the cache providerGroup.writeEntry( "features", featureStrings ); } else { // Check stored feature strings and re-read features if an invalid string was found bool ok; QStringList featureStrings = providerGroup.readEntry("features", QStringList()); const bool featureListIsEmpty = featureStrings.removeOne("(none)"); QList< Enums::ProviderFeature > features = ServiceProviderGlobal::featuresFromFeatureStrings( featureStrings, &ok ); if ( (featureListIsEmpty || !featureStrings.isEmpty()) && ok ) { // Feature list could be read from cache dataServiceProvider.insert( "features", featureStrings ); dataServiceProvider.insert( "featureNames", ServiceProviderGlobal::featureNames(features) ); } else { qDebug() << "No cached feature data was found for provider" << data.id(); // No cached feature data was found for the provider, // create the provider to get the feature list and store it in the cache bool newlyCreated; ProviderPointer _provider = providerFromId( data.id(), &newlyCreated ); features = _provider->features(); featureStrings = ServiceProviderGlobal::featureStrings( features ); const QStringList featuresNames = ServiceProviderGlobal::featureNames( features ); // Remove provider from the list again to delete it if ( newlyCreated ) { m_providers.remove( data.id() ); } // If no features are supported write "(none)" to the cache // to indicate that features have been written to the cache if ( featureStrings.isEmpty() ) { featureStrings.append( "(none)" ); } // Write features to the return value dataServiceProvider.insert( "features", featureStrings ); dataServiceProvider.insert( "featureNames", featuresNames ); // Write features to cache providerGroup.writeEntry( "features", featureStrings ); } } return dataServiceProvider; } QVariantHash PublicTransportEngine::locations() { QVariantHash ret; const QStringList providers = ServiceProviderGlobal::installedProviders(); // Update ServiceProviders source to fill m_erroneousProviders updateServiceProviderSource(); foreach( const QString &provider, providers ) { if ( QFileInfo(provider).isSymLink() ) { // Service provider XML file is a symlink for a default service provider, skip it continue; } const QString providerFileName = QFileInfo( provider ).fileName(); const QString providerId = ServiceProviderGlobal::idFromFileName( providerFileName ); if ( m_erroneousProviders.contains(providerId) ) { // Service provider is erroneous continue; } const int pos = providerFileName.indexOf('_'); if ( pos > 0 ) { // Found an underscore (not the first character) // Cut location code from the service providers XML filename const QString location = providerFileName.mid( 0, pos ).toLower(); if ( !ret.contains(location) ) { // Location is not already added to [ret] // Get the filename of the default provider for the current location const QString defaultProviderFileName = ServiceProviderGlobal::defaultProviderForLocation( location ); // Extract service provider ID from the filename const QString defaultProviderId = ServiceProviderGlobal::idFromFileName( defaultProviderFileName ); // Store location values in a hash and insert it into [ret] QVariantHash locationHash; locationHash.insert( "name", location ); if ( location == "international" ) { locationHash.insert( "description", i18n("International providers. " "There is one for getting flight departures/arrivals.") ); } else { locationHash.insert( "description", i18n("Service providers for %1.", KGlobal::locale()->countryCodeToName(location)) ); } locationHash.insert( "defaultProvider", defaultProviderId ); ret.insert( location, locationHash ); } } } return ret; } PublicTransportEngine::ProviderPointer PublicTransportEngine::providerFromId( const QString &id, bool *newlyCreated ) { if ( m_providers.contains(id) ) { // The provider was already created and is currently used by the engine if ( newlyCreated ) { *newlyCreated = false; } return m_providers[ id ]; } else if ( m_cachedProviders.contains(id) ) { // The provider was already created, is now unused by the engine, // but is still cached (cleanup timeout not reached yet) if ( newlyCreated ) { *newlyCreated = false; } // Move provider back from the list of cached providers to the list of used providers const ProviderPointer provider = m_cachedProviders.take( id ); m_providers.insert( id, provider ); return provider; } else { // Provider not currently used or cached if ( newlyCreated ) { *newlyCreated = true; } // Try to create the provider ServiceProvider *provider = createProvider( id, this ); if ( !provider ) { // Return an invalid ProviderPointer, when the provider could not be created return ProviderPointer::create(); } // Check the state of the provider, it needs to be "ready" ProvidersDataSource *dataSource = providersDataSource(); if ( dataSource ) { const QString state = dataSource->providerState( id ); if ( state != QLatin1String("ready") ) { - kWarning() << "Provider" << id << "is not ready, state is" << state; + qWarning() << "Provider" << id << "is not ready, state is" << state; return ProviderPointer::create(); } } // Connect provider, when it was created successfully connect( provider, SIGNAL(departuresReceived(ServiceProvider*,QUrl,DepartureInfoList,GlobalTimetableInfo,DepartureRequest)), this, SLOT(departuresReceived(ServiceProvider*,QUrl,DepartureInfoList,GlobalTimetableInfo,DepartureRequest)) ); connect( provider, SIGNAL(arrivalsReceived(ServiceProvider*,QUrl,ArrivalInfoList,GlobalTimetableInfo,ArrivalRequest)), this, SLOT(arrivalsReceived(ServiceProvider*,QUrl,ArrivalInfoList,GlobalTimetableInfo,ArrivalRequest)) ); connect( provider, SIGNAL(journeysReceived(ServiceProvider*,QUrl,JourneyInfoList,GlobalTimetableInfo,JourneyRequest)), this, SLOT(journeysReceived(ServiceProvider*,QUrl,JourneyInfoList,GlobalTimetableInfo,JourneyRequest)) ); connect( provider, SIGNAL(stopsReceived(ServiceProvider*,QUrl,StopInfoList,StopSuggestionRequest)), this, SLOT(stopsReceived(ServiceProvider*,QUrl,StopInfoList,StopSuggestionRequest)) ); connect( provider, SIGNAL(additionalDataReceived(ServiceProvider*,QUrl,TimetableData,AdditionalDataRequest)), this, SLOT(additionalDataReceived(ServiceProvider*,QUrl,TimetableData,AdditionalDataRequest)) ); connect( provider, SIGNAL(requestFailed(ServiceProvider*,ErrorCode,QString,QUrl,const AbstractRequest*)), this, SLOT(requestFailed(ServiceProvider*,ErrorCode,QString,QUrl,const AbstractRequest*)) ); // Create a ProviderPointer for the created provider and // add it to the list of currently used providers const ProviderPointer pointer( provider ); m_providers.insert( id, pointer ); return pointer; } } bool PublicTransportEngine::updateServiceProviderForCountrySource( const SourceRequestData &data ) { QString providerId; if ( data.defaultParameter.contains('_') ) { // Seems that a service provider ID is given providerId = data.defaultParameter; } else { // Assume a country code in name if ( !updateServiceProviderSource() || !updateLocationSource() ) { return false; } // The defaultParameter stored in data is a location code // (ie. "international" or a two letter country code) QVariantHash locations = m_dataSources[ sourceTypeKeyword(LocationsSource) ]->data(); QVariantHash locationCountry = locations[ data.defaultParameter.toLower() ].toHash(); QString defaultProvider = locationCountry[ "defaultProvider" ].toString(); if ( defaultProvider.isEmpty() ) { // No provider for the location found return false; } providerId = defaultProvider; } updateProviderData( providerId ); publishData( providersDataSource(), providerId ); return true; } bool PublicTransportEngine::updateProviderData( const QString &providerId, const QSharedPointer &cache ) { QVariantHash providerData; QString errorMessage; ProvidersDataSource *providersSource = providersDataSource(); // Test if the provider is valid if ( testServiceProvider(providerId, &providerData, &errorMessage, cache) ) { QVariantHash stateData; const QString state = updateProviderState( providerId, &stateData, providerData["type"].toString(), providerData.value("feedUrl").toString() ); providerData["error"] = false; providersSource->addProvider( providerId, ProvidersDataSource::ProviderData(providerData, state, stateData) ); return true; } else { // Invalid provider providerData["id"] = providerId; providerData["error"] = true; providerData["errorMessage"] = errorMessage; // Prepare state data with the error message and a boolean whether or not the provider // is installed or could not be found (only possible if the provider data source was // manually requested) QVariantHash stateData; stateData["statusMessage"] = errorMessage; stateData["isInstalled"] = ServiceProviderGlobal::isProviderInstalled( providerId ); providersSource->addProvider( providerId, ProvidersDataSource::ProviderData(providerData, "error", stateData) ); return false; } } bool PublicTransportEngine::updateServiceProviderSource() { const QString name = sourceTypeKeyword( ServiceProvidersSource ); ProvidersDataSource *providersSource = providersDataSource(); if ( providersSource->isDirty() ) { const QStringList providers = ServiceProviderGlobal::installedProviders(); if ( providers.isEmpty() ) { - kWarning() << "Could not find any service provider plugins"; + qWarning() << "Could not find any service provider plugins"; } else { QStringList loadedProviders; m_erroneousProviders.clear(); QSharedPointer cache = ServiceProviderGlobal::cache(); foreach( const QString &provider, providers ) { const QString providerId = ServiceProviderGlobal::idFromFileName( QUrl(provider).fileName() ); if ( updateProviderData(providerId, cache) ) { loadedProviders << providerId; } } // Print information about loaded/erroneous providers qDebug() << "Loaded" << loadedProviders.count() << "service providers"; if ( !m_erroneousProviders.isEmpty() ) { - kWarning() << "Erroneous service provider plugins, that could not be loaded:" + qWarning() << "Erroneous service provider plugins, that could not be loaded:" << m_erroneousProviders; } } // Mark and update all providers that are no longer installed QSharedPointer< KConfig > cache = ServiceProviderGlobal::cache(); const QStringList uninstalledProviderIDs = providersSource->markUninstalledProviders(); foreach ( const QString &uninstalledProviderID, uninstalledProviderIDs ) { // Clear all values stored in the cache for the provider ServiceProviderGlobal::clearCache( uninstalledProviderID, cache ); // Delete the provider and update it's state and other data deleteProvider( uninstalledProviderID ); updateProviderData( uninstalledProviderID, cache ); } // Insert the data source m_dataSources.insert( name, providersSource ); } // Remove all old data, some service providers may have been updated and are now erroneous removeAllData( name ); publishData( providersSource ); return true; } QString PublicTransportEngine::updateProviderState( const QString &providerId, QVariantHash *stateData, const QString &providerType, const QString &feedUrl, bool readFromCache ) { Q_ASSERT( stateData ); QSharedPointer< KConfig > cache = ServiceProviderGlobal::cache(); KConfigGroup group = cache->group( providerId ); const QString cachedState = readFromCache ? group.readEntry("state", QString()) : QString(); #ifdef BUILD_PROVIDER_TYPE_GTFS // Currently type is only used for GTFS const Enums::ServiceProviderType type = ServiceProviderGlobal::typeFromString( providerType ); #endif // BUILD_PROVIDER_TYPE_GTFS // Test if there is an error if ( m_erroneousProviders.contains(providerId) ) { stateData->insert( "statusMessage", m_erroneousProviders[providerId].toString() ); return "error"; } if ( !cachedState.isEmpty() ) { // State is stored in the cache, // also read state data from cache KConfigGroup stateGroup = group.group( "stateData" ); foreach ( const QString &key, stateGroup.keyList() ) { stateData->insert( key, stateGroup.readEntry(key) ); } #ifdef BUILD_PROVIDER_TYPE_GTFS if ( type == Enums::GtfsProvider ) { // Update state and add dynamic state data const QString state = ServiceProviderGtfs::updateGtfsDatabaseState( providerId, feedUrl, cache, stateData ); if ( state != QLatin1String("ready") ) { // The database is invalid/deleted, but the cache says the import was finished deleteProvider( providerId ); } return state; } else #endif // BUILD_PROVIDER_TYPE_GTFS { if ( cachedState != QLatin1String("ready") ) { // Provider not ready, cannot use it deleteProvider( providerId ); } // State of non-GTFS providers does not need more tests, // if there is an error only the fields "error" and "errorMessage" are available // in the data source, no fields "state" or "stateData" return cachedState; } } // !state.isEmpty() // State is not stored in the cache or is out of date QString state = "ready"; #ifdef BUILD_PROVIDER_TYPE_GTFS if ( type == Enums::GtfsProvider ) { state = ServiceProviderGtfs::updateGtfsDatabaseState( providerId, feedUrl, cache, stateData ); } #endif // BUILD_PROVIDER_TYPE_GTFS // Ensure a status message is given (or at least warn if not) if ( stateData->value("statusMessage").toString().isEmpty() ) { if ( state == QLatin1String("ready") ) { stateData->insert( "statusMessage", i18nc("@info/plain", "The provider is ready to use") ); } else { - kWarning() << "Missing status message explaining why the provider" << providerId + qWarning() << "Missing status message explaining why the provider" << providerId << "is not ready"; } } // Store the state in the cache group.writeEntry( "state", state ); // Write state data to the cache KConfigGroup stateGroup = group.group( "stateData" ); for ( QVariantHash::ConstIterator it = stateData->constBegin(); it != stateData->constEnd(); ++it ) { if ( isStateDataCached(it.key()) ) { stateGroup.writeEntry( it.key(), it.value() ); } } return state; } bool PublicTransportEngine::isStateDataCached( const QString &stateDataKey ) { return stateDataKey != QLatin1String("progress") && stateDataKey != QLatin1String("gtfsDatabasePath") && stateDataKey != QLatin1String("gtfsDatabaseSize") && stateDataKey != QLatin1String("gtfsDatabaseModifiedTime") && stateDataKey != QLatin1String("gtfsFeedImported") && stateDataKey != QLatin1String("gtfsFeedSize") && stateDataKey != QLatin1String("gtfsFeedModifiedTime"); } bool PublicTransportEngine::testServiceProvider( const QString &providerId, QVariantHash *providerData, QString *errorMessage, const QSharedPointer &_cache ) { const bool providerUsed = m_providers.contains( providerId ); const bool providerCached = m_cachedProviders.contains( providerId ); if ( providerUsed || providerCached ) { // The provider is cached in the engine, ie. it is valid, // use it's ServiceProviderData object const ProviderPointer provider = providerUsed ? m_providers[providerId] : m_cachedProviders[providerId]; *providerData = serviceProviderData( provider.data() ); errorMessage->clear(); return true; } // Read cached data for the provider QSharedPointer cache = _cache.isNull() ? ServiceProviderGlobal::cache() : _cache; ServiceProviderTestData testData = ServiceProviderTestData::read( providerId, cache ); // TODO Needs to be done for each provider sub class here foreach ( Enums::ServiceProviderType type, ServiceProviderGlobal::availableProviderTypes() ) { switch ( type ) { #ifdef BUILD_PROVIDER_TYPE_SCRIPT case Enums::ScriptedProvider: if ( !ServiceProviderScript::isTestResultUnchanged(providerId, cache) ) { qDebug() << "Script changed" << providerId; testData.setSubTypeTestStatus( ServiceProviderTestData::Pending ); testData.write( providerId, cache ); } break; #endif case Enums::GtfsProvider: break; case Enums::InvalidProvider: default: - kWarning() << "Provider type unknown" << type; + qWarning() << "Provider type unknown" << type; break; } } // Check the cache if the provider plugin .pts file can be read if ( testData.xmlStructureTestStatus() == ServiceProviderTestData::Failed ) { // The XML structure of the provider plugin .pts file is marked as failed in the cache // Cannot add provider data to data sources, the file needs to be fixed first - kWarning() << "Provider plugin" << providerId << "is invalid."; + qWarning() << "Provider plugin" << providerId << "is invalid."; qDebug() << "Fix the provider file at" << ServiceProviderGlobal::fileNameFromId(providerId); qDebug() << testData.errorMessage(); qDebug() << "************************************"; providerData->clear(); *errorMessage = testData.errorMessage(); m_erroneousProviders.insert( providerId, testData.errorMessage() ); updateErroneousServiceProviderSource(); return false; } // The sub type test may already be marked as failed in the cache, // but when provider data can be read it should be added to provider data source // also when the provider plugin is invalid // Read provider data from the XML file QString _errorMessage; const QScopedPointer data( ServiceProviderDataReader::read(providerId, &_errorMessage) ); if ( data.isNull() ) { // Could not read provider data if ( testData.isXmlStructureTestPending() ) { // Store error message in cache and do not reread unchanged XMLs everytime testData.setXmlStructureTestStatus( ServiceProviderTestData::Failed, _errorMessage ); testData.write( providerId, cache ); } providerData->clear(); *errorMessage = _errorMessage; m_erroneousProviders.insert( providerId, _errorMessage ); updateErroneousServiceProviderSource(); return false; } // Check if support for the used provider type has been build into the engine if ( !ServiceProviderGlobal::isProviderTypeAvailable(data->type()) ) { providerData->clear(); _errorMessage = i18nc("@info/plain", "Support for provider type %1 is not available", ServiceProviderGlobal::typeName(data->type(), ServiceProviderGlobal::ProviderTypeNameWithoutUnsupportedHint)); *errorMessage = _errorMessage; m_erroneousProviders.insert( providerId, _errorMessage ); updateErroneousServiceProviderSource(); return false; } // Mark the XML test as passed if not done already if ( testData.isXmlStructureTestPending() ) { testData.setXmlStructureTestStatus( ServiceProviderTestData::Passed ); testData.write( providerId, cache ); } // XML file structure test is passed, run provider type test if not done already switch ( testData.subTypeTestStatus() ) { case ServiceProviderTestData::Pending: { // Need to create the provider to run tests in derived classes (in the constructor) const QScopedPointer provider( createProviderForData(data.data(), this, cache) ); data->setParent( 0 ); // Prevent deletion of data when the provider gets deleted // Read test data again, because it may have been changed in the provider constructor testData = ServiceProviderTestData::read( providerId, cache ); // Run the sub type test if it is still pending testData = provider->runSubTypeTest( testData, cache ); // Read test data again, updated in the ServiceProvider constructor if ( testData.results().testFlag(ServiceProviderTestData::SubTypeTestFailed) ) { // Sub-type test failed - kWarning() << "Test failed for" << providerId << testData.errorMessage(); + qWarning() << "Test failed for" << providerId << testData.errorMessage(); providerData->clear(); *errorMessage = testData.errorMessage(); m_erroneousProviders.insert( providerId, testData.errorMessage() ); updateErroneousServiceProviderSource(); return false; } // The provider is already created, use it in serviceProviderData(), if needed *providerData = serviceProviderData( provider.data() ); break; } case ServiceProviderTestData::Failed: // Test is marked as failed in the cache *errorMessage = testData.errorMessage(); m_erroneousProviders.insert( providerId, testData.errorMessage() ); updateErroneousServiceProviderSource(); *providerData = serviceProviderData( *data ); return false; case ServiceProviderTestData::Passed: // Test is marked as passed in the cache *providerData = serviceProviderData( *data ); break; } m_erroneousProviders.remove( providerId ); const QLatin1String name = sourceTypeKeyword( ErroneousServiceProvidersSource ); removeData( name, providerId ); errorMessage->clear(); return true; } bool PublicTransportEngine::updateErroneousServiceProviderSource() { const QLatin1String name = sourceTypeKeyword( ErroneousServiceProvidersSource ); setData( name, static_cast(m_erroneousProviders) ); return true; } bool PublicTransportEngine::updateLocationSource() { const QLatin1String name = sourceTypeKeyword( LocationsSource ); if ( m_dataSources.contains(name) ) { setData( name, m_dataSources[name]->data() ); } else { SimpleDataSource *dataSource = new SimpleDataSource( name, locations() ); m_dataSources.insert( name, dataSource ); setData( name, dataSource->data() ); } return true; } QString PublicTransportEngine::providerIdFromSourceName( const QString &sourceName ) { const int pos = sourceName.indexOf( ' ' ); if ( pos == -1 ) { //|| pos = sourceName.length() - 1 ) { return QString(); } const int endPos = sourceName.indexOf( '|', pos + 1 ); return fixProviderId( sourceName.mid(pos + 1, endPos - pos - 1).trimmed() ); } ParseDocumentMode PublicTransportEngine::parseModeFromSourceType( PublicTransportEngine::SourceType type ) { switch ( type ) { case DeparturesSource: return ParseForDepartures; case ArrivalsSource: return ParseForArrivals; case StopsSource: return ParseForStopSuggestions; case JourneysDepSource: return ParseForJourneysByDepartureTime; case JourneysArrSource: return ParseForJourneysByArrivalTime; case JourneysSource: return ParseForJourneysByDepartureTime; default: return ParseInvalid; } } bool PublicTransportEngine::enoughDataAvailable( DataSource *dataSource, const SourceRequestData &sourceData ) const { TimetableDataSource *timetableDataSource = dynamic_cast< TimetableDataSource* >( dataSource ); if ( !timetableDataSource ) { return true; } AbstractTimetableItemRequest *request = sourceData.request; return timetableDataSource->enoughDataAvailable( request->dateTime(), request->count() ); } bool PublicTransportEngine::updateTimetableDataSource( const SourceRequestData &data ) { const QString nonAmbiguousName = disambiguateSourceName( data.name ); bool containsDataSource = m_dataSources.contains( nonAmbiguousName ); if ( containsDataSource && isSourceUpToDate(nonAmbiguousName) && enoughDataAvailable(m_dataSources[nonAmbiguousName], data) ) { // Data is stored in the map and up to date TimetableDataSource *dataSource = dynamic_cast< TimetableDataSource* >( m_dataSources[nonAmbiguousName] ); dataSource->addUsingDataSource( QSharedPointer(data.request->clone()), data.name, data.request->dateTime(), data.request->count() ); setData( data.name, dataSource->data() ); } else if ( m_runningSources.contains(nonAmbiguousName) ) { // Source gets already processed qDebug() << "Source already gets processed, please wait" << data.name; } else if ( data.parseMode == ParseInvalid || !data.request ) { - kWarning() << "Invalid source" << data.name; + qWarning() << "Invalid source" << data.name; return false; } else { // Request new data TimetableDataSource *dataSource = containsDataSource ? dynamic_cast< TimetableDataSource* >( m_dataSources[nonAmbiguousName] ) : new TimetableDataSource(nonAmbiguousName); dataSource->clear(); dataSource->addUsingDataSource( QSharedPointer(data.request->clone()), data.name, data.request->dateTime(), data.request->count() ); m_dataSources[ nonAmbiguousName ] = dataSource; // Start the request request( data ); } return true; } void PublicTransportEngine::requestAdditionalData( const QString &sourceName, int updateItem, int count ) { TimetableDataSource *dataSource = testDataSourceForAdditionalDataRequests( sourceName ); if ( dataSource ) { // Start additional data requests bool dataChanged = false; for ( int itemNumber = updateItem; itemNumber < updateItem + count; ++itemNumber ) { dataChanged = requestAdditionalData(sourceName, itemNumber, dataSource) || dataChanged; } if ( dataChanged ) { // Publish changes to "additionalDataState" fields publishData( dataSource ); } } } TimetableDataSource *PublicTransportEngine::testDataSourceForAdditionalDataRequests( const QString &sourceName ) { // Try to get a pointer to the provider with the provider ID from the source name const QString providerId = providerIdFromSourceName( sourceName ); const ProviderPointer provider = providerFromId( providerId ); if ( provider.isNull() || provider->type() == Enums::InvalidProvider ) { emit additionalDataRequestFinished( sourceName, -1, false, QString("Service provider %1 could not be created").arg(providerId) ); return 0; // Service provider couldn't be created } // Test if the provider supports additional data if ( !provider->features().contains(Enums::ProvidesAdditionalData) ) { emit additionalDataRequestFinished( sourceName, -1, false, i18nc("@info/plain", "Additional data not supported") ); - kWarning() << "Additional data not supported by" << provider->id(); + qWarning() << "Additional data not supported by" << provider->id(); return 0; // Service provider does not support additional data } // Test if the source with the given name is cached const QString nonAmbiguousName = disambiguateSourceName( sourceName ); if ( !m_dataSources.contains(nonAmbiguousName) ) { emit additionalDataRequestFinished( sourceName, -1, false, "Data source to update not found: " + sourceName ); return 0; } // Get the data list, currently only for departures/arrivals TODO: journeys TimetableDataSource *dataSource = dynamic_cast< TimetableDataSource* >( m_dataSources[nonAmbiguousName] ); if ( !dataSource ) { emit additionalDataRequestFinished( sourceName, -1, false, "Data source is not a timetable data source: " + sourceName ); return 0; } return dataSource; } bool PublicTransportEngine::requestAdditionalData( const QString &sourceName, int itemNumber, TimetableDataSource *dataSource ) { QVariantList items = dataSource->timetableItems(); if ( itemNumber >= items.count() || itemNumber < 0 ) { emit additionalDataRequestFinished( sourceName, itemNumber, false, QString("Item to update (%1) not found in data source").arg(itemNumber) ); return false; } // Get the timetable item stored in the data source at the given index QVariantHash item = items[ itemNumber ].toHash(); // Check if additional data is already included or was already requested const QString additionalDataState = item["additionalDataState"].toString(); if ( additionalDataState == QLatin1String("included") ) { emit additionalDataRequestFinished( sourceName, itemNumber, false, QString("Additional data is already included for item %1").arg(itemNumber) ); return false; } else if ( additionalDataState == QLatin1String("busy") ) { qDebug() << "Additional data for item" << itemNumber << "already requested, please wait"; emit additionalDataRequestFinished( sourceName, itemNumber, false, QString("Additional data was already requested for item %1, please wait") .arg(itemNumber) ); return false; } // Check if the timetable item is valid, // extract values needed for the additional data request job const QDateTime dateTime = item[ "DepartureDateTime" ].toDateTime(); const QString transportLine = item[ "TransportLine" ].toString(); const QString target = item[ "Target" ].toString(); const QString routeDataUrl = item[ "RouteDataUrl" ].toString(); if ( routeDataUrl.isEmpty() && (!dateTime.isValid() || transportLine.isEmpty() || target.isEmpty()) ) { emit additionalDataRequestFinished( sourceName, itemNumber, false, QString("Item to update is invalid: %1, %2, %3") .arg(dateTime.toString()).arg(transportLine, target) ); return false; } // Store state of additional data in the timetable item item["additionalDataState"] = "busy"; items[ itemNumber ] = item; dataSource->setTimetableItems( items ); // Found data of the timetable item to update const SourceRequestData sourceData( dataSource->name() ); const ProviderPointer provider = providerFromId( dataSource->providerId() ); Q_ASSERT( provider ); provider->requestAdditionalData( AdditionalDataRequest(dataSource->name(), itemNumber, sourceData.request->stop(), sourceData.request->stopId(), dateTime, transportLine, target, sourceData.request->city(), routeDataUrl) ); return true; } QString PublicTransportEngine::fixProviderId( const QString &providerId ) { if ( !providerId.isEmpty() ) { return providerId; } // No service provider ID given, use the default one for the users country const QString country = KGlobal::locale()->country(); // Try to find the XML filename of the default accessor for [country] const QString filePath = ServiceProviderGlobal::defaultProviderForLocation( country ); if ( filePath.isEmpty() ) { return 0; } // Extract service provider ID from filename const QString defaultProviderId = ServiceProviderGlobal::idFromFileName( filePath ); qDebug() << "No service provider ID given, using the default one for country" << country << "which is" << defaultProviderId; return defaultProviderId; } QString PublicTransportEngine::disambiguateSourceName( const QString &sourceName ) { // Remove count argument QString ret = sourceName; ret.remove( QRegExp("(count=[^\\|]+)") ); // Round time parameter values to 15 minutes precision QRegExp rx( "(time=[^\\|]+|datetime=[^\\|]+)" ); if ( rx.indexIn(ret) != -1 ) { // Get the time value const QString timeParameter = rx.cap( 1 ); QDateTime time; if ( timeParameter.startsWith(QLatin1String("time=")) ) { time = QDateTime( QDate::currentDate(), QTime::fromString(timeParameter.mid(5), "hh:mm") ); } else { // startsWith "datetime=" time = QDateTime::fromString( timeParameter.mid(9), Qt::ISODate ); if ( !time.isValid() ) { time = QDateTime::fromString( timeParameter.mid(9) ); } } // Round 15 minutes qint64 msecs = time.toMSecsSinceEpoch(); time = QDateTime::fromMSecsSinceEpoch( msecs - msecs % (1000 * 60 * 15) ); // Replace old time parameter with a new one ret.replace( rx.pos(), rx.matchedLength(), QLatin1String("datetime=") + time.toString(Qt::ISODate) ); } // Read parameters to reorder them afterwards const SourceType type = sourceTypeFromName( ret ); const QString typeKeyword = sourceTypeKeyword( type ); const QStringList parameterPairs = ret.mid( typeKeyword.length() ) .trimmed().split( '|', QString::SkipEmptyParts ); QString defaultParameter; QHash< QString, QString > parameters; for ( int i = 0; i < parameterPairs.length(); ++i ) { const QString parameter = parameterPairs.at( i ).trimmed(); const int pos = parameter.indexOf( '=' ); if ( pos == -1 ) { // No parameter name given, this is the default parameter, eg. the provider ID defaultParameter = fixProviderId( parameter ); } else { // Only add parameters with non-empty parameter name and value, // make parameter value lower case (eg. stop names) const QString parameterName = parameter.left( pos ); const QString parameterValue = parameter.mid( pos + 1 ).trimmed(); if ( !parameterName.isEmpty() && !parameterValue.isEmpty() ) { parameters[ parameterName ] = parameterValue; } } } // Build non-ambiguous source name with standardized parameter order ret = typeKeyword + ' ' + defaultParameter; if ( parameters.contains(QLatin1String("city")) ) { ret += "|city=" + parameters["city"].toLower(); } if ( parameters.contains(QLatin1String("stop")) ) { ret += "|stop=" + parameters["stop"].toLower(); } if ( parameters.contains(QLatin1String("stopid")) ) { ret += "|stopid=" + parameters["stopid"]; } if ( parameters.contains(QLatin1String("originstop")) ) { ret += "|originstop=" + parameters["originstop"].toLower(); } if ( parameters.contains(QLatin1String("originstopid")) ) { ret += "|originstopid=" + parameters["originstopid"]; } if ( parameters.contains(QLatin1String("targetstop")) ) { ret += "|targetstop=" + parameters["targetstop"].toLower(); } if ( parameters.contains(QLatin1String("targetstopid")) ) { ret += "|targetstopid=" + parameters["targetstopid"]; } if ( parameters.contains(QLatin1String("timeoffset")) ) { ret += "|timeoffset=" + parameters["timeoffset"]; } if ( parameters.contains(QLatin1String("time")) ) { ret += "|time=" + parameters["time"]; } if ( parameters.contains(QLatin1String("datetime")) ) { ret += "|datetime=" + parameters["datetime"]; } if ( parameters.contains(QLatin1String("count")) ) { ret += "|count=" + parameters["count"]; } if ( parameters.contains(QLatin1String("longitude")) ) { ret += "|longitude=" + parameters["longitude"]; } if ( parameters.contains(QLatin1String("latitude")) ) { ret += "|latitude=" + parameters["latitude"]; } return ret; } void PublicTransportEngine::serviceProviderDirChanged( const QString &path ) { Q_UNUSED( path ) // Use a timer to prevent loading all service providers again and again, for every changed file // in a possibly big list of files. It reloads the providers maximally every 250ms. // Otherwise it can freeze plasma for a while if eg. all provider files are changed at once. if ( !m_providerUpdateDelayTimer ) { m_providerUpdateDelayTimer = new QTimer( this ); connect( m_providerUpdateDelayTimer, SIGNAL(timeout()), this, SLOT(reloadChangedProviders()) ); } m_providerUpdateDelayTimer->start( 250 ); } void PublicTransportEngine::deleteProvider( const QString &providerId, bool keepProviderDataSources ) { // Clear all cached data const QStringList cachedSources = m_dataSources.keys(); foreach( const QString &cachedSource, cachedSources ) { const QString currentProviderId = providerIdFromSourceName( cachedSource ); if ( currentProviderId == providerId ) { // Disconnect provider and abort all running requests, // take provider from the provider list without caching it ProviderPointer provider = m_providers.take( providerId ); if ( provider ) { disconnect( provider.data(), 0, this, 0 ); provider->abortAllRequests(); } m_runningSources.removeOne( cachedSource ); if ( keepProviderDataSources ) { // Update data source for the provider TimetableDataSource *timetableSource = dynamic_cast< TimetableDataSource* >( m_dataSources[cachedSource] ); if ( timetableSource ) { // Stop automatic updates timetableSource->stopUpdateTimer(); // Update manually foreach ( const QString &sourceName, timetableSource->usingDataSources() ) { updateTimetableDataSource( SourceRequestData(sourceName) ); } } } else { // Delete data source for the provider delete m_dataSources.take( cachedSource ); } } } } void PublicTransportEngine::reloadChangedProviders() { qDebug() << "Reload service providers (the service provider dir changed)"; delete m_providerUpdateDelayTimer; m_providerUpdateDelayTimer = 0; // Notify the providers data source about the changed provider directory. // Do not remove it here, so that it can track which providers have changed ProvidersDataSource *providersSource = providersDataSource(); if ( providersSource ) { providersSource->providersHaveChanged(); } // Remove cached locations source to have it updated delete m_dataSources.take( sourceTypeKeyword(LocationsSource) ); // Clear all cached data (use the new provider to parse the data again) const QStringList cachedSources = m_dataSources.keys(); const QSharedPointer< KConfig > cache = ServiceProviderGlobal::cache(); foreach( const QString &cachedSource, cachedSources ) { const QString providerId = providerIdFromSourceName( cachedSource ); if ( !providerId.isEmpty() && (ServiceProviderGlobal::isSourceFileModified(providerId, cache) #ifdef BUILD_PROVIDER_TYPE_SCRIPT || !ServiceProviderScript::isTestResultUnchanged(providerId, cache) #endif ) ) { m_providers.remove( providerId ); m_cachedProviders.remove( providerId ); m_erroneousProviders.remove( providerId ); updateProviderData( providerId, cache ); TimetableDataSource *timetableSource = dynamic_cast< TimetableDataSource* >( m_dataSources[cachedSource] ); if ( timetableSource ) { // Stop automatic updates timetableSource->stopUpdateTimer(); // Update manually foreach ( const QString &sourceName, timetableSource->usingDataSources() ) { updateTimetableDataSource( SourceRequestData(sourceName) ); } } } } updateLocationSource(); updateServiceProviderSource(); updateErroneousServiceProviderSource(); } const QLatin1String PublicTransportEngine::sourceTypeKeyword( SourceType sourceType ) { switch ( sourceType ) { case ServiceProviderSource: return QLatin1String("ServiceProvider"); case ServiceProvidersSource: return QLatin1String("ServiceProviders"); case ErroneousServiceProvidersSource: return QLatin1String("ErroneousServiceProviders"); case LocationsSource: return QLatin1String("Locations"); case VehicleTypesSource: return QLatin1String("VehicleTypes"); case DeparturesSource: return QLatin1String("Departures"); case ArrivalsSource: return QLatin1String("Arrivals"); case StopsSource: return QLatin1String("Stops"); case JourneysSource: return QLatin1String("Journeys"); case JourneysDepSource: return QLatin1String("JourneysDep"); case JourneysArrSource: return QLatin1String("JourneysArr"); default: return QLatin1String(""); } } PublicTransportEngine::SourceType PublicTransportEngine::sourceTypeFromName( const QString &sourceName ) { // Get type of the source, do not match case insensitive, otherwise there can be multiple // sources with the same data but only different case if ( sourceName.startsWith(sourceTypeKeyword(ServiceProviderSource) + ' ') ) { return ServiceProviderSource; } else if ( sourceName.compare(sourceTypeKeyword(ServiceProvidersSource)) == 0 ) { return ServiceProvidersSource; } else if ( sourceName.compare(sourceTypeKeyword(ErroneousServiceProvidersSource)) == 0 ) { return ErroneousServiceProvidersSource; } else if ( sourceName.compare(sourceTypeKeyword(LocationsSource)) == 0 ) { return LocationsSource; } else if ( sourceName.compare(sourceTypeKeyword(VehicleTypesSource)) == 0 ) { return VehicleTypesSource; } else if ( sourceName.startsWith(sourceTypeKeyword(DeparturesSource)) ) { return DeparturesSource; } else if ( sourceName.startsWith(sourceTypeKeyword(ArrivalsSource)) ) { return ArrivalsSource; } else if ( sourceName.startsWith(sourceTypeKeyword(StopsSource)) ) { return StopsSource; } else if ( sourceName.startsWith(sourceTypeKeyword(JourneysDepSource)) ) { return JourneysDepSource; } else if ( sourceName.startsWith(sourceTypeKeyword(JourneysArrSource)) ) { return JourneysArrSource; } else if ( sourceName.startsWith(sourceTypeKeyword(JourneysSource)) ) { return JourneysSource; } else { return InvalidSourceName; } } PublicTransportEngine::SourceRequestData::SourceRequestData( const QString &name ) : name(name), type(sourceTypeFromName(name)), parseMode(parseModeFromSourceType(type)), request(0) { if ( isDataRequestingSourceType(type) ) { // Extract parameters, which follow after the source type keyword in name // and are delimited with '|' QStringList parameters = name.mid( QString(sourceTypeKeyword(type)).length() ) .trimmed().split( '|', QString::SkipEmptyParts ); switch ( parseMode ) { case ParseForDepartures: request = new DepartureRequest( name, parseMode ); break; case ParseForArrivals: request = new ArrivalRequest( name, parseMode ); break; case ParseForStopSuggestions: { bool hasLongitude = false, hasLatitude = false; for ( int i = 0; i < parameters.length(); ++i ) { const QString parameter = parameters.at( i ).trimmed(); const QString parameterName = parameter.left( parameter.indexOf('=') ); if ( parameterName == QLatin1String("longitude") ) { hasLongitude = true; } else if ( parameterName == QLatin1String("latitude") ) { hasLatitude = true; } } if ( hasLongitude && hasLatitude ) { request = new StopsByGeoPositionRequest( name, parseMode ); } else { request = new StopSuggestionRequest( name, parseMode ); } break; } case ParseForJourneysByDepartureTime: case ParseForJourneysByArrivalTime: request = new JourneyRequest( name, parseMode ); break; default: - kWarning() << "Cannot create a request for parse mode" << parseMode; + qWarning() << "Cannot create a request for parse mode" << parseMode; return; } // Read parameters for ( int i = 0; i < parameters.length(); ++i ) { const QString parameter = parameters.at( i ).trimmed(); const int pos = parameter.indexOf( '=' ); if ( pos == -1 ) { if ( !defaultParameter.isEmpty() ) { - kWarning() << "More than one parameters without name given:" + qWarning() << "More than one parameters without name given:" << defaultParameter << parameter; } // No parameter name given, assume the service provider ID defaultParameter = parameter; } else { const QString parameterName = parameter.left( pos ); const QString parameterValue = parameter.mid( pos + 1 ).trimmed(); if ( parameterValue.isEmpty() ) { - kWarning() << "Empty parameter value for parameter" << parameterName; + qWarning() << "Empty parameter value for parameter" << parameterName; } else if ( parameterName == QLatin1String("city") ) { request->setCity( parameterValue ); } else if ( parameterName == QLatin1String("stop") ) { request->setStop( parameterValue ); } else if ( parameterName == QLatin1String("stopid") ) { request->setStopId( parameterValue ); } else if ( parameterName == QLatin1String("targetstop") ) { JourneyRequest *journeyRequest = dynamic_cast< JourneyRequest* >( request ); if ( !journeyRequest ) { - kWarning() << "The 'targetstop' parameter is only used for journey requests"; + qWarning() << "The 'targetstop' parameter is only used for journey requests"; } else { journeyRequest->setTargetStop( parameterValue ); } } else if ( parameterName == QLatin1String("targetstopid") ) { JourneyRequest *journeyRequest = dynamic_cast< JourneyRequest* >( request ); if ( !journeyRequest ) { - kWarning() << "The 'targetstopId' parameter is only used for journey requests"; + qWarning() << "The 'targetstopId' parameter is only used for journey requests"; } else { journeyRequest->setTargetStopId( parameterValue ); } } else if ( parameterName == QLatin1String("originstop") ) { JourneyRequest *journeyRequest = dynamic_cast< JourneyRequest* >( request ); if ( !journeyRequest ) { - kWarning() << "The 'originstop' parameter is only used for journey requests"; + qWarning() << "The 'originstop' parameter is only used for journey requests"; } else { journeyRequest->setStop( parameterValue ); } } else if ( parameterName == QLatin1String("originstopid") ) { JourneyRequest *journeyRequest = dynamic_cast< JourneyRequest* >( request ); if ( !journeyRequest ) { - kWarning() << "The 'originstopId' parameter is only used for journey requests"; + qWarning() << "The 'originstopId' parameter is only used for journey requests"; } else { journeyRequest->setStopId( parameterValue ); } } else if ( parameterName == QLatin1String("timeoffset") ) { request->setDateTime( QDateTime::currentDateTime().addSecs(parameterValue.toInt() * 60) ); } else if ( parameterName == QLatin1String("time") ) { request->setDateTime( QDateTime(QDate::currentDate(), QTime::fromString(parameterValue, "hh:mm")) ); } else if ( parameterName == QLatin1String("datetime") ) { request->setDateTime( QDateTime::fromString(parameterValue, Qt::ISODate) ); if ( !request->dateTime().isValid() ) { request->setDateTime( QDateTime::fromString(parameterValue) ); } } else if ( parameterName == QLatin1String("count") ) { bool ok; request->setCount( parameterValue.toInt(&ok) ); if ( !ok ) { - kWarning() << "Bad value for 'count' in source name:" << parameterValue; + qWarning() << "Bad value for 'count' in source name:" << parameterValue; request->setCount( 20 ); } } else if ( dynamic_cast(request) ) { StopsByGeoPositionRequest *stopRequest = dynamic_cast< StopsByGeoPositionRequest* >( request ); bool ok; if ( parameterName == QLatin1String("longitude") ) { stopRequest->setLongitude( parameterValue.toFloat(&ok) ); if ( !ok ) { - kWarning() << "Bad value for 'longitude' in source name:" << parameterValue; + qWarning() << "Bad value for 'longitude' in source name:" << parameterValue; } } else if ( parameterName == QLatin1String("latitude") ) { stopRequest->setLatitude( parameterValue.toFloat(&ok) ); if ( !ok ) { - kWarning() << "Bad value for 'latitude' in source name:" << parameterValue; + qWarning() << "Bad value for 'latitude' in source name:" << parameterValue; } } else if ( parameterName == QLatin1String("distance") ) { stopRequest->setDistance( parameterValue.toInt(&ok) ); if ( !ok ) { - kWarning() << "Bad value for 'distance' in source name:" << parameterValue; + qWarning() << "Bad value for 'distance' in source name:" << parameterValue; } } else { - kWarning() << "Unknown argument" << parameterName; + qWarning() << "Unknown argument" << parameterName; } } else { - kWarning() << "Unknown argument" << parameterName; + qWarning() << "Unknown argument" << parameterName; } } } if ( !request->dateTime().isValid() ) { // No date/time value given, use default offset from now request->setDateTime( QDateTime::currentDateTime().addSecs(DEFAULT_TIME_OFFSET * 60) ); } // The default parameter is the provider ID for data requesting sources, // use the default provider for the users country if no ID is given defaultParameter = PublicTransportEngine::fixProviderId( defaultParameter ); } else { // Extract provider ID or country code, which follow after the source type keyword in name defaultParameter = name.mid( QString(sourceTypeKeyword(type)).length() ).trimmed(); } } PublicTransportEngine::SourceRequestData::~SourceRequestData() { delete request; } bool PublicTransportEngine::SourceRequestData::isValid() const { if ( type == InvalidSourceName ) { - kWarning() << "Invalid source name" << name; + qWarning() << "Invalid source name" << name; return false; } if ( isDataRequestingSourceType(type) ) { if ( parseMode == ParseForDepartures || parseMode == ParseForArrivals ) { // Check if the stop name/ID is missing if ( !request || (request->stop().isEmpty() && request->stopId().isEmpty()) ) { - kWarning() << "No stop ID or name in data source name" << name; + qWarning() << "No stop ID or name in data source name" << name; return false; } } else if ( parseMode == ParseForStopSuggestions ) { // Check if the stop name or geo coordinates are missing if ( !request || (!dynamic_cast(request) && request->stop().isEmpty()) ) { - kWarning() << "Stop name (part) is missing in data source name" << name; + qWarning() << "Stop name (part) is missing in data source name" << name; return false; } } else if ( parseMode == ParseForJourneysByArrivalTime || parseMode == ParseForJourneysByDepartureTime ) { // Make sure non empty originstop(id) and targetstop(id) parameters are available JourneyRequest *journeyRequest = dynamic_cast< JourneyRequest* >( request ); if ( !journeyRequest ) { - kWarning() << "Internal error: Not a JourneyRequest object but parseMode is" + qWarning() << "Internal error: Not a JourneyRequest object but parseMode is" << parseMode; return false; } if ( journeyRequest->stop().isEmpty() && journeyRequest->stopId().isEmpty() ) { - kWarning() << "No stop ID or name for the origin stop in data source name" << name; + qWarning() << "No stop ID or name for the origin stop in data source name" << name; return false; } if ( journeyRequest->targetStop().isEmpty() && journeyRequest->targetStopId().isEmpty() ) { - kWarning() << "No stop ID or name for the target stop in data source name" << name; + qWarning() << "No stop ID or name for the target stop in data source name" << name; return false; } } } return true; } bool PublicTransportEngine::sourceRequestEvent( const QString &name ) { // If name is associated with a data source that runs asynchronously, // create the source first with empty data, gets updated once the request has finished SourceRequestData data( name ); if ( data.isValid() && isDataRequestingSourceType(data.type) ) { setData( name, DataEngine::Data() ); } return requestOrUpdateSourceEvent( data ); } bool PublicTransportEngine::updateSourceEvent( const QString &name ) { return requestOrUpdateSourceEvent( SourceRequestData(name), true ); } bool PublicTransportEngine::requestOrUpdateSourceEvent( const SourceRequestData &sourceData, bool update ) { if ( !sourceData.isValid() ) { return false; } switch ( sourceData.type ) { case ServiceProviderSource: return updateServiceProviderForCountrySource( sourceData ); case ServiceProvidersSource: return updateServiceProviderSource(); case ErroneousServiceProvidersSource: return updateErroneousServiceProviderSource(); case LocationsSource: return updateLocationSource(); case DeparturesSource: case ArrivalsSource: case StopsSource: case JourneysSource: case JourneysArrSource: case JourneysDepSource: { return updateTimetableDataSource( sourceData ); } // This data source never changes, ie. needs no updates case VehicleTypesSource: if ( !update ) { initVehicleTypesSource(); } return true; case InvalidSourceName: default: qDebug() << "Source name incorrect" << sourceData.name; return false; } } void PublicTransportEngine::initVehicleTypesSource() { QVariantHash vehicleTypes; const int index = Enums::staticMetaObject.indexOfEnumerator("VehicleType"); const QMetaEnum enumerator = Enums::staticMetaObject.enumerator( index ); // Start at i = 1 to skip Enums::InvalidVehicleType for ( int i = 1; i < enumerator.keyCount(); ++i ) { Enums::VehicleType vehicleType = static_cast< Enums::VehicleType >( enumerator.value(i) ); QVariantHash vehicleTypeData; vehicleTypeData.insert( "id", enumerator.key(i) ); vehicleTypeData.insert( "name", Global::vehicleTypeToString(vehicleType) ); vehicleTypeData.insert( "namePlural", Global::vehicleTypeToString(vehicleType, true) ); vehicleTypeData.insert( "iconName", Global::vehicleTypeToIcon(vehicleType) ); vehicleTypes.insert( QString::number(enumerator.value(i)), vehicleTypeData ); } setData( sourceTypeKeyword(VehicleTypesSource), vehicleTypes ); } void PublicTransportEngine::timetableDataReceived( ServiceProvider *provider, const QUrl &requestUrl, const DepartureInfoList &items, const GlobalTimetableInfo &globalInfo, const DepartureRequest &request, bool deleteDepartureInfos, bool isDepartureData ) { Q_UNUSED( requestUrl ); Q_UNUSED( provider ); Q_UNUSED( deleteDepartureInfos ); const QString sourceName = request.sourceName(); DEBUG_ENGINE_JOBS( items.count() << (isDepartureData ? "departures" : "arrivals") << "received" << sourceName ); const QString nonAmbiguousName = disambiguateSourceName( sourceName ); if ( !m_dataSources.contains(nonAmbiguousName) ) { - kWarning() << "Data source already removed"; + qWarning() << "Data source already removed"; return; } TimetableDataSource *dataSource = dynamic_cast< TimetableDataSource* >( m_dataSources[nonAmbiguousName] ); Q_ASSERT( dataSource ); m_runningSources.removeOne( nonAmbiguousName ); QVariantList departuresData; const QString itemKey = isDepartureData ? "departures" : "arrivals"; foreach( const DepartureInfoPtr &departureInfo, items ) { QVariantHash departureData; TimetableData departure = departureInfo->data(); for ( TimetableData::ConstIterator it = departure.constBegin(); it != departure.constEnd(); ++it ) { if ( it.value().isValid() ) { departureData.insert( Global::timetableInformationToString(it.key()), it.value() ); } } departureData.insert( "Nightline", departureInfo->isNightLine() ); departureData.insert( "Expressline", departureInfo->isExpressLine() ); // Add existing additional data const uint hash = TimetableDataSource::hashForDeparture( departure, isDepartureData ); if ( dataSource->additionalData().contains(hash) ) { // Found already downloaded additional data, add it to the updated departure data const TimetableData additionalData = dataSource->additionalData( hash ); if ( !additionalData.isEmpty() ) { bool hasAdditionalData = false; for ( TimetableData::ConstIterator it = additionalData.constBegin(); it != additionalData.constEnd(); ++it ) { if ( it.key() != Enums::RouteDataUrl ) { hasAdditionalData = true; } departureData.insert( Global::timetableInformationToString(it.key()), it.value() ); } departureData[ "additionalDataState" ] = hasAdditionalData ? "included" : "error"; } } if ( !departureData.contains("additionalDataState") ) { departureData[ "additionalDataState" ] = provider->features().contains(Enums::ProvidesAdditionalData) ? "notrequested" : "notsupported"; } departuresData << departureData; } // Cleanup the data source later startDataSourceCleanupLater( dataSource ); dataSource->setValue( itemKey, departuresData ); // if ( deleteDepartureInfos ) { // qDebug() << "Delete" << items.count() << "departures/arrivals"; // qDeleteAll( departures ); // } // Fill the data source with general information const QDateTime dateTime = QDateTime::currentDateTime(); dataSource->setValue( "serviceProvider", provider->id() ); dataSource->setValue( "delayInfoAvailable", globalInfo.delayInfoAvailable ); dataSource->setValue( "requestUrl", requestUrl ); dataSource->setValue( "parseMode", request.parseModeName() ); dataSource->setValue( "error", false ); dataSource->setValue( "updated", dateTime ); // Store a proposal for the next download time QDateTime last = items.isEmpty() ? dateTime : items.last()->value(Enums::DepartureDateTime).toDateTime(); dataSource->setNextDownloadTimeProposal( dateTime.addSecs(dateTime.secsTo(last) / 3) ); const QDateTime nextUpdateTime = provider->nextUpdateTime( dataSource->updateFlags(), dateTime, dataSource->nextDownloadTimeProposal(), dataSource->data() ); const QDateTime minManualUpdateTime = provider->nextUpdateTime( dataSource->updateFlags() | UpdateWasRequestedManually, dateTime, dataSource->nextDownloadTimeProposal(), dataSource->data() ); // Store update times in the data source dataSource->setValue( "nextAutomaticUpdate", nextUpdateTime ); dataSource->setValue( "minManualUpdateTime", minManualUpdateTime ); // Publish the data source and cache it publishData( dataSource ); m_dataSources[ nonAmbiguousName ] = dataSource; int msecsUntilUpdate = dateTime.msecsTo( nextUpdateTime ); Q_ASSERT( msecsUntilUpdate >= 10000 ); // Make sure to not produce too many updates by mistake DEBUG_ENGINE_JOBS( "Update data source in" << KGlobal::locale()->prettyFormatDuration(msecsUntilUpdate) ); if ( !dataSource->updateTimer() ) { QTimer *updateTimer = new QTimer( this ); connect( updateTimer, SIGNAL(timeout()), this, SLOT(updateTimeout()) ); dataSource->setUpdateTimer( updateTimer ); } dataSource->updateTimer()->start( msecsUntilUpdate ); } void PublicTransportEngine::startDataSourceCleanupLater( TimetableDataSource *dataSource ) { if ( !dataSource->cleanupTimer() ) { QTimer *cleanupTimer = new QTimer( this ); cleanupTimer->setInterval( 2500 ); connect( cleanupTimer, SIGNAL(timeout()), this, SLOT(cleanupTimeout()) ); dataSource->setCleanupTimer( cleanupTimer ); } dataSource->cleanupTimer()->start(); } void PublicTransportEngine::updateTimeout() { // Find the timetable data source to which the timer belongs which timeout() signal was emitted QTimer *timer = qobject_cast< QTimer* >( sender() ); TimetableDataSource *dataSource = dataSourceFromTimer( timer ); if ( !dataSource ) { // No data source found that started the timer, // should not happen the data source should have deleted the timer on destruction - kWarning() << "Timeout received from an unknown update timer"; + qWarning() << "Timeout received from an unknown update timer"; return; } // Found the timetable data source of the timer, // requests updates for all connected sources (possibly multiple combined stops) foreach ( const QString &sourceName, dataSource->usingDataSources() ) { updateTimetableDataSource( SourceRequestData(sourceName) ); } // TODO FIXME Do not update while running additional data requests? } void PublicTransportEngine::cleanupTimeout() { // Find the timetable data source to which the timer belongs which timeout() signal was emitted QTimer *timer = qobject_cast< QTimer* >( sender() ); TimetableDataSource *dataSource = dataSourceFromTimer( timer ); if ( !dataSource ) { // No data source found that started the timer, // should not happen the data source should have deleted the timer on destruction - kWarning() << "Timeout received from an unknown cleanup timer"; + qWarning() << "Timeout received from an unknown cleanup timer"; return; } // Found the timetable data source of the timer dataSource->cleanup(); dataSource->setCleanupTimer( 0 ); // Deletes the timer } void PublicTransportEngine::additionalDataReceived( ServiceProvider *provider, const QUrl &requestUrl, const TimetableData &data, const AdditionalDataRequest &request ) { Q_UNUSED( provider ); Q_UNUSED( requestUrl ); // Check if the destination data source exists const QString nonAmbiguousName = disambiguateSourceName( request.sourceName() ); if ( !m_dataSources.contains(nonAmbiguousName) ) { - kWarning() << "Additional data received for a source that was already removed:" + qWarning() << "Additional data received for a source that was already removed:" << nonAmbiguousName; emit additionalDataRequestFinished( request.sourceName(), request.itemNumber(), false, "Data source to update was already removed" ); return; } // Get the list of timetable items from the existing data source TimetableDataSource *dataSource = dynamic_cast< TimetableDataSource* >( m_dataSources[nonAmbiguousName] ); Q_ASSERT( dataSource ); QVariantList items = dataSource->timetableItems(); if ( request.itemNumber() >= items.count() ) { emit additionalDataRequestFinished( request.sourceName(), request.itemNumber(), false, QString("Item %1 not found in the data source (with %2 items)") .arg(request.itemNumber()).arg(items.count()) ); return; } // Get the timetable item for which additional data was received // and insert the new data into it bool newDataInserted = false; TimetableData _data = data; QVariantHash item = items[ request.itemNumber() ].toHash(); for ( TimetableData::ConstIterator it = data.constBegin(); it != data.constEnd(); ++it ) { // Check if there already is data in the current additional data field const QString key = Global::timetableInformationToString( it.key() ); const bool isRouteDataUrl = key == Enums::toString(Enums::RouteDataUrl); if ( item.contains(key) && item[key].isValid() && !isRouteDataUrl ) { // The timetable item already contains data for the current field, // do not allow updates here, only additional data - kWarning() << "Cannot update timetable data in additional data requests"; - kWarning() << "Tried to update field" << key << "to value" << it.value() + qWarning() << "Cannot update timetable data in additional data requests"; + qWarning() << "Tried to update field" << key << "to value" << it.value() << "from value" << item[key] << "in data source" << request.sourceName(); } else { // Allow to add the additional data field item.insert( key, it.value() ); if ( !isRouteDataUrl ) { newDataInserted = true; if ( key == Enums::toString(Enums::RouteStops) ) { // Added a RouteStops field, automatically generate RouteStopsShortened const QString routeStopsShortenedKey = Global::timetableInformationToString( Enums::RouteStopsShortened ); if ( !item.contains(routeStopsShortenedKey) ) { const QStringList routeStopsShortened = removeCityNameFromStops( it.value().toStringList() ); item.insert( routeStopsShortenedKey, routeStopsShortened ); _data.insert( Enums::RouteStopsShortened, routeStopsShortened ); } } } } } if ( !newDataInserted ) { const QString errorMessage = i18nc("@info/plain", "No additional data found"); emit additionalDataRequestFinished( request.sourceName(), request.itemNumber(), false, errorMessage ); item[ "additionalDataState" ] = "error"; item[ "additionalDataError" ] = errorMessage; items[ request.itemNumber() ] = item; dataSource->setTimetableItems( items ); return; } item[ "additionalDataState" ] = "included"; // Store the changed item back into the item list of the data source items[ request.itemNumber() ] = item; dataSource->setTimetableItems( items ); // Also store received additional data separately // to not loose additional data after updating the data source const uint hash = TimetableDataSource::hashForDeparture( item, dataSource->timetableItemKey() != QLatin1String("arrivals") ); dataSource->setAdditionalData( hash, _data ); startDataSourceCleanupLater( dataSource ); QTimer *updateDelayTimer; if ( dataSource->updateAdditionalDataDelayTimer() ) { // Use existing timer, restart it with a longer interval and // publish the new data of the data source after the timeout updateDelayTimer = dataSource->updateAdditionalDataDelayTimer(); updateDelayTimer->setInterval( 250 ); } else { // Create timer with a shorter interval, but directly publish the new data of the // data source. The timer is used here to delay further publishing of new data, // ie. combine multiple updates and publish them at once. publishData( dataSource ); updateDelayTimer = new QTimer( this ); updateDelayTimer->setInterval( 150 ); connect( updateDelayTimer, SIGNAL(timeout()), this, SLOT(updateDataSourcesWithNewAdditionData()) ); dataSource->setUpdateAdditionalDataDelayTimer( updateDelayTimer ); } // (Re-)start the additional data update timer updateDelayTimer->start(); // Emit result emit additionalDataRequestFinished( request.sourceName(), request.itemNumber(), true ); } TimetableDataSource *PublicTransportEngine::dataSourceFromTimer( QTimer *timer ) const { for ( QHash< QString, DataSource* >::ConstIterator it = m_dataSources.constBegin(); it != m_dataSources.constEnd(); ++it ) { TimetableDataSource *dataSource = dynamic_cast< TimetableDataSource* >( *it ); if ( dataSource && (dataSource->updateAdditionalDataDelayTimer() == timer || dataSource->updateTimer() == timer || dataSource->cleanupTimer() == timer) ) { return dataSource; } } // The timer is not used any longer return 0; } void PublicTransportEngine::updateDataSourcesWithNewAdditionData() { QTimer *updateDelayTimer = qobject_cast< QTimer* >( sender() ); Q_ASSERT( updateDelayTimer ); TimetableDataSource *dataSource = dataSourceFromTimer( updateDelayTimer ); if ( !dataSource ) { - kWarning() << "Data source was already removed"; + qWarning() << "Data source was already removed"; return; } const int interval = updateDelayTimer->interval(); dataSource->setUpdateAdditionalDataDelayTimer( 0 ); // Deletes the timer // Do the upate, but only after long delays, // because the update is already done before short delays if ( interval > 150 ) { // Was delayed for a longer time publishData( dataSource ); } } void PublicTransportEngine::departuresReceived( ServiceProvider *provider, const QUrl &requestUrl, const DepartureInfoList &departures, const GlobalTimetableInfo &globalInfo, const DepartureRequest &request, bool deleteDepartureInfos ) { timetableDataReceived( provider, requestUrl, departures, globalInfo, request, deleteDepartureInfos, true ); } void PublicTransportEngine::arrivalsReceived( ServiceProvider *provider, const QUrl &requestUrl, const ArrivalInfoList &arrivals, const GlobalTimetableInfo &globalInfo, const ArrivalRequest &request, bool deleteDepartureInfos ) { timetableDataReceived( provider, requestUrl, arrivals, globalInfo, request, deleteDepartureInfos, false ); } void PublicTransportEngine::journeysReceived( ServiceProvider* provider, const QUrl &requestUrl, const JourneyInfoList &journeys, const GlobalTimetableInfo &globalInfo, const JourneyRequest &request, bool deleteJourneyInfos ) { Q_UNUSED( provider ); Q_UNUSED( deleteJourneyInfos ); const QString sourceName = request.sourceName(); DEBUG_ENGINE_JOBS( journeys.count() << "journeys received" << sourceName ); const QString nonAmbiguousName = disambiguateSourceName( sourceName ); m_runningSources.removeOne( nonAmbiguousName ); if ( !m_dataSources.contains(nonAmbiguousName) ) { - kWarning() << "Data source already removed" << nonAmbiguousName; + qWarning() << "Data source already removed" << nonAmbiguousName; return; } TimetableDataSource *dataSource = dynamic_cast< TimetableDataSource* >( m_dataSources[nonAmbiguousName] ); if ( !dataSource ) { - kWarning() << "Data source already deleted" << nonAmbiguousName; + qWarning() << "Data source already deleted" << nonAmbiguousName; return; } dataSource->clear(); QVariantList journeysData; foreach( const JourneyInfoPtr &journeyInfo, journeys ) { if ( !journeyInfo->isValid() ) { continue; } QVariantHash journeyData; TimetableData journey = journeyInfo->data(); for ( TimetableData::ConstIterator it = journey.constBegin(); it != journey.constEnd(); ++it ) { if ( it.value().isValid() ) { journeyData.insert( Global::timetableInformationToString(it.key()), it.value() ); } } journeysData << journeyData; } dataSource->setValue( "journeys", journeysData ); int journeyCount = journeys.count(); QDateTime first, last; if ( journeyCount > 0 ) { first = journeys.first()->value(Enums::DepartureDateTime).toDateTime(); last = journeys.last()->value(Enums::DepartureDateTime).toDateTime(); } else { first = last = QDateTime::currentDateTime(); } // if ( deleteJourneyInfos ) { // qDeleteAll( journeys ); TODO // } // Store a proposal for the next download time int secs = ( journeyCount / 3 ) * first.secsTo( last ); QDateTime downloadTime = QDateTime::currentDateTime().addSecs( secs ); dataSource->setNextDownloadTimeProposal( downloadTime ); // Store received data in the data source map dataSource->setValue( "serviceProvider", provider->id() ); dataSource->setValue( "delayInfoAvailable", globalInfo.delayInfoAvailable ); dataSource->setValue( "requestUrl", requestUrl ); dataSource->setValue( "parseMode", request.parseModeName() ); dataSource->setValue( "error", false ); dataSource->setValue( "updated", QDateTime::currentDateTime() ); dataSource->setValue( "nextAutomaticUpdate", downloadTime ); dataSource->setValue( "minManualUpdateTime", downloadTime ); // TODO setData( sourceName, dataSource->data() ); m_dataSources[ nonAmbiguousName ] = dataSource; } void PublicTransportEngine::stopsReceived( ServiceProvider *provider, const QUrl &requestUrl, const StopInfoList &stops, const StopSuggestionRequest &request, bool deleteStopInfos ) { Q_UNUSED( provider ); Q_UNUSED( deleteStopInfos ); const QString sourceName = request.sourceName(); m_runningSources.removeOne( disambiguateSourceName(sourceName) ); DEBUG_ENGINE_JOBS( stops.count() << "stop suggestions received" << sourceName ); QVariantList stopsData; foreach( const StopInfoPtr &stopInfo, stops ) { QVariantHash stopData; TimetableData stop = stopInfo->data(); for ( TimetableData::ConstIterator it = stop.constBegin(); it != stop.constEnd(); ++it ) { if ( it.value().isValid() ) { stopData.insert( Global::timetableInformationToString(it.key()), it.value() ); } } stopsData << stopData; } setData( sourceName, "stops", stopsData ); setData( sourceName, "serviceProvider", provider->id() ); setData( sourceName, "requestUrl", requestUrl ); setData( sourceName, "parseMode", request.parseModeName() ); setData( sourceName, "error", false ); setData( sourceName, "updated", QDateTime::currentDateTime() ); // if ( deleteStopInfos ) { // qDeleteAll( stops ); TODO // } } void PublicTransportEngine::requestFailed( ServiceProvider *provider, ErrorCode errorCode, const QString &errorMessage, const QUrl &requestUrl, const AbstractRequest *request ) { Q_UNUSED( provider ); qDebug() << errorCode << errorMessage << "- Requested URL:" << requestUrl; const AdditionalDataRequest *additionalDataRequest = dynamic_cast< const AdditionalDataRequest* >( request ); if ( additionalDataRequest ) { // A request for additional data failed emit additionalDataRequestFinished( request->sourceName(), additionalDataRequest->itemNumber(), false, errorMessage ); // Check if the destination data source exists const QString nonAmbiguousName = disambiguateSourceName( request->sourceName() ); if ( m_dataSources.contains(nonAmbiguousName) ) { // Get the list of timetable items from the existing data source TimetableDataSource *dataSource = dynamic_cast< TimetableDataSource* >( m_dataSources[nonAmbiguousName] ); Q_ASSERT( dataSource ); QVariantList items = dataSource->timetableItems(); if ( additionalDataRequest->itemNumber() < items.count() ) { // Found the item for which the request failed, // reset additional data included/waiting fields QVariantHash item = items[ additionalDataRequest->itemNumber() ].toHash(); item[ "additionalDataState" ] = "error"; item[ "additionalDataError" ] = errorMessage; items[ additionalDataRequest->itemNumber() ] = item; dataSource->setTimetableItems( items ); // Publish updated fields publishData( dataSource ); } else { - kWarning() << "Timetable item" << additionalDataRequest->itemNumber() + qWarning() << "Timetable item" << additionalDataRequest->itemNumber() << "not found in data source" << request->sourceName() << "additional data error discarded"; } } else { - kWarning() << "Data source" << request->sourceName() + qWarning() << "Data source" << request->sourceName() << "not found, additional data error discarded"; } // Do not mark the whole timetable data source as erroneous // when a request for additional data has failed return; } // Remove erroneous source from running sources list m_runningSources.removeOne( disambiguateSourceName(request->sourceName()) ); const QString sourceName = request->sourceName(); setData( sourceName, "serviceProvider", provider->id() ); setData( sourceName, "requestUrl", requestUrl ); setData( sourceName, "parseMode", request->parseModeName() ); setData( sourceName, "receivedData", "nothing" ); setData( sourceName, "error", true ); setData( sourceName, "errorCode", errorCode ); setData( sourceName, "errorMessage", errorMessage ); setData( sourceName, "updated", QDateTime::currentDateTime() ); } bool PublicTransportEngine::requestUpdate( const QString &sourceName ) { // Find the TimetableDataSource object for sourceName const QString nonAmbiguousName = disambiguateSourceName( sourceName ); if ( !m_dataSources.contains(nonAmbiguousName) ) { - kWarning() << "Not an existing timetable data source:" << sourceName; + qWarning() << "Not an existing timetable data source:" << sourceName; emit updateRequestFinished( sourceName, false, i18nc("@info", "Data source is not an existing timetable data source: %1", sourceName) ); return false; } TimetableDataSource *dataSource = dynamic_cast< TimetableDataSource* >( m_dataSources[nonAmbiguousName] ); if ( !dataSource ) { - kWarning() << "Internal error: Invalid pointer to the data source stored"; + qWarning() << "Internal error: Invalid pointer to the data source stored"; emit updateRequestFinished( sourceName, false, "Internal error: Invalid pointer to the data source stored" ); return false; } // Check if updates are blocked to prevent to many useless updates const QDateTime nextUpdateTime = sourceUpdateTime( dataSource, UpdateWasRequestedManually ); if ( QDateTime::currentDateTime() < nextUpdateTime ) { qDebug() << "Too early to update again, update request rejected" << nextUpdateTime; emit updateRequestFinished( sourceName, false, i18nc("@info", "Update request rejected, earliest update time: %1", nextUpdateTime.toString()) ); return false; } // Stop automatic updates dataSource->stopUpdateTimer(); // Start the request const bool result = request( sourceName ); if ( result ) { emit updateRequestFinished( sourceName ); } else { emit updateRequestFinished( sourceName, false, i18nc("@info", "Request failed") ); } return result; } bool PublicTransportEngine::requestMoreItems( const QString &sourceName, Enums::MoreItemsDirection direction ) { // Find the TimetableDataSource object for sourceName const QString nonAmbiguousName = disambiguateSourceName( sourceName ); if ( !m_dataSources.contains(nonAmbiguousName) ) { - kWarning() << "Not an existing timetable data source:" << sourceName; + qWarning() << "Not an existing timetable data source:" << sourceName; emit moreItemsRequestFinished( sourceName, direction, false, i18nc("@info", "Data source is not an existing timetable data source: %1", sourceName) ); return false; } else if ( m_runningSources.contains(nonAmbiguousName) ) { // The data source currently gets processed or updated, including requests for more items qDebug() << "Source currently gets processed, please wait" << sourceName; emit moreItemsRequestFinished( sourceName, direction, false, i18nc("@info", "Source currently gets processed, please try again later") ); return false; } TimetableDataSource *dataSource = dynamic_cast< TimetableDataSource* >( m_dataSources[nonAmbiguousName] ); if ( !dataSource ) { - kWarning() << "Internal error: Invalid pointer to the data source stored"; + qWarning() << "Internal error: Invalid pointer to the data source stored"; emit moreItemsRequestFinished( sourceName, direction, false, "Internal error" ); return false; } const SourceRequestData data( sourceName ); qDebug() << data.defaultParameter; const ProviderPointer provider = providerFromId( data.defaultParameter ); if ( provider.isNull() ) { // Service provider couldn't be created, should only happen after provider updates, // where the provider worked to get timetable items, but the new provider version // does not work any longer and no more items can be requested emit moreItemsRequestFinished( sourceName, direction, false, "Provider could not be created" ); return false; } // Start the request QSharedPointer< AbstractRequest > request = dataSource->request( sourceName ); const QVariantList items = dataSource->timetableItems(); if ( items.isEmpty() ) { // TODO - kWarning() << "No timetable items in data source" << sourceName; + qWarning() << "No timetable items in data source" << sourceName; emit moreItemsRequestFinished( sourceName, direction, false, i18nc("@info", "No timetable items in data source") ); return false; } const QVariantHash item = (direction == Enums::EarlierItems ? items.first() : items.last()).toHash(); const QVariantMap _requestData = item[Enums::toString(Enums::RequestData)].toMap(); // TODO Convert to hash from map.. QVariantHash requestData; for ( QVariantMap::ConstIterator it = _requestData.constBegin(); it != _requestData.constEnd(); ++it ) { requestData.insert( it.key(), it.value() ); } // Start the request m_runningSources << nonAmbiguousName; provider->requestMoreItems( MoreItemsRequest(sourceName, request, requestData, direction) ); emit moreItemsRequestFinished( sourceName, direction ); return true; } ErrorCode PublicTransportEngine::errorCodeFromState( const QString &stateId ) { if ( stateId == QLatin1String("ready") ) { return NoError; } else if ( stateId == QLatin1String("gtfs_feed_import_pending") || stateId == QLatin1String("importing_gtfs_feed") ) { return ErrorNeedsImport; } else { return ErrorParsingFailed; } } bool PublicTransportEngine::request( const SourceRequestData &data ) { // Try to get the specific provider from m_providers (if it's not in there it is created) const ProviderPointer provider = providerFromId( data.defaultParameter ); if ( provider.isNull() || provider->type() == Enums::InvalidProvider ) { // Service provider couldn't be created // Remove erroneous source from running sources list const QString sourceName = data.request->sourceName(); m_runningSources.removeOne( disambiguateSourceName(sourceName) ); ProvidersDataSource *dataSource = providersDataSource(); const QString state = dataSource->providerState( data.defaultParameter ); if ( state != QLatin1String("ready") ) { const QVariantHash stateData = dataSource->providerStateData( data.defaultParameter ); setData( sourceName, "serviceProvider", data.defaultParameter ); setData( sourceName, "parseMode", data.request->parseModeName() ); setData( sourceName, "receivedData", "nothing" ); setData( sourceName, "error", true ); setData( sourceName, "errorCode", errorCodeFromState(state) ); setData( sourceName, "errorMessage", stateData["statusMessage"].toString() ); setData( sourceName, "updated", QDateTime::currentDateTime() ); } return false; } else if ( provider->useSeparateCityValue() && data.request->city().isEmpty() && !dynamic_cast(data.request) ) { qDebug() << QString("Service provider %1 needs a separate city value. Add to source name " "'|city=X', where X stands for the city name.") .arg( data.defaultParameter ); return false; // Service provider needs a separate city value } else if ( !provider->features().contains(Enums::ProvidesJourneys) && (data.parseMode == ParseForJourneysByDepartureTime || data.parseMode == ParseForJourneysByArrivalTime) ) { qDebug() << QString("Service provider %1 doesn't support journey searches.") .arg( data.defaultParameter ); return false; // Service provider doesn't support journey searches } // Store source name as currently being processed, to not start another // request if there is already a running one m_runningSources << disambiguateSourceName( data.name ); // Start the request provider->request( data.request ); return true; } int PublicTransportEngine::secsUntilUpdate( const QString &sourceName, QString *errorMessage ) { return getSecsUntilUpdate( sourceName, errorMessage ); } int PublicTransportEngine::minSecsUntilUpdate( const QString &sourceName, QString *errorMessage ) { return getSecsUntilUpdate( sourceName, errorMessage, UpdateWasRequestedManually ); } int PublicTransportEngine::getSecsUntilUpdate( const QString &sourceName, QString *errorMessage, UpdateFlags updateFlags ) { const QString nonAmbiguousName = disambiguateSourceName( sourceName ); if ( !m_dataSources.contains(nonAmbiguousName) ) { // The data source is not a timetable data source or does not exist if ( errorMessage ) { *errorMessage = i18nc("@info", "Data source is not an existing timetable " "data source: %1", sourceName); } return -1; } TimetableDataSource *dataSource = dynamic_cast< TimetableDataSource* >( m_dataSources[nonAmbiguousName] ); if ( !dataSource ) { - kWarning() << "Internal error: Invalid pointer to the data source stored"; + qWarning() << "Internal error: Invalid pointer to the data source stored"; return -1; } const QDateTime time = sourceUpdateTime( dataSource, updateFlags ); return qMax( -1, QDateTime::currentDateTime().secsTo(time) ); } QDateTime PublicTransportEngine::sourceUpdateTime( TimetableDataSource *dataSource, UpdateFlags updateFlags ) { const QString providerId = fixProviderId( dataSource->providerId() ); const ProviderPointer provider = providerFromId( providerId ); if ( provider.isNull() || provider->type() == Enums::InvalidProvider ) { return QDateTime(); } return provider->nextUpdateTime( dataSource->updateFlags() | updateFlags, dataSource->lastUpdate(), dataSource->nextDownloadTimeProposal(), dataSource->data() ); } bool PublicTransportEngine::isSourceUpToDate( const QString &nonAmbiguousName, UpdateFlags updateFlags ) { if ( !m_dataSources.contains(nonAmbiguousName) ) { return false; } TimetableDataSource *dataSource = dynamic_cast< TimetableDataSource* >( m_dataSources[nonAmbiguousName] ); if ( !dataSource ) { // The data source is not a timetable data source, no periodic updates needed return true; } const QDateTime nextUpdateTime = sourceUpdateTime( dataSource, updateFlags ); DEBUG_ENGINE_JOBS( "Wait time until next download:" << KGlobal::locale()->prettyFormatDuration( (QDateTime::currentDateTime().msecsTo(nextUpdateTime))) ); return QDateTime::currentDateTime() < nextUpdateTime; } ServiceProvider *PublicTransportEngine::createProvider( const QString &serviceProviderId, QObject *parent, const QSharedPointer &cache ) { ServiceProviderData *data = ServiceProviderDataReader::read( serviceProviderId ); return data ? createProviderForData(data, parent, cache) : 0; } ServiceProvider *PublicTransportEngine::createProviderForData( const ServiceProviderData *data, QObject *parent, const QSharedPointer &cache ) { if ( !ServiceProviderGlobal::isProviderTypeAvailable(data->type()) ) { - kWarning() << "Cannot create provider of type" << data->typeName() << "because the engine " + qWarning() << "Cannot create provider of type" << data->typeName() << "because the engine " "has been built without support for that provider type"; return 0; } // Warn if the format of the provider plugin is unsupported if ( data->fileFormatVersion() != QLatin1String("1.1") ) { - kWarning() << "The Provider" << data->id() << "was designed for an unsupported " + qWarning() << "The Provider" << data->id() << "was designed for an unsupported " "provider plugin format version, update to version 1.1"; return 0; } switch ( data->type() ) { #ifdef BUILD_PROVIDER_TYPE_SCRIPT case Enums::ScriptedProvider: return new ServiceProviderScript( data, parent, cache ); #endif #ifdef BUILD_PROVIDER_TYPE_GTFS case Enums::GtfsProvider: return new ServiceProviderGtfs( data, parent, cache ); #endif case Enums::InvalidProvider: default: - kWarning() << "Invalid/unknown provider type" << data->type(); + qWarning() << "Invalid/unknown provider type" << data->type(); return 0; } } QStringList PublicTransportEngine::removeCityNameFromStops( const QStringList &stopNames ) { // Find words at the beginning/end of target and route stop names that have many // occurrences. These words are most likely the city names where the stops are in. // But the timetable becomes easier to read and looks nicer, if not each stop name // includes the same city name. QHash< QString, int > firstWordCounts; // Counts occurrences of words at the beginning QHash< QString, int > lastWordCounts; // Counts occurrences of words at the end // minWordOccurrence is the minimum occurence count of a word in stop names to have the word // removed. maxWordOccurrence is the maximum number of occurences to count, if this number // of occurences has been found, just remove that word. const int minWordOccurrence = qMax( 2, stopNames.count() ); const int maxWordOccurrence = qMax( 3, stopNames.count() / 2 ); // This regular expression gets used to search for word at the end, possibly including // a colon before the last word QRegExp rxLastWord( ",?\\s+\\S+$" ); // These strings store the words with the most occurrences in stop names at the beginning/end QString removeFirstWord; QString removeLastWord; // Analyze stop names foreach ( const QString &stopName, stopNames ) { // Find word to remove from beginning/end of stop names, if not already found if ( !removeFirstWord.isEmpty() || !removeLastWord.isEmpty() ) { break; } int pos = stopName.indexOf( ' ' ); const QString newFirstWord = stopName.left( pos ); if ( pos > 0 && ++firstWordCounts[newFirstWord] >= maxWordOccurrence ) { removeFirstWord = newFirstWord; } if ( rxLastWord.indexIn(stopName) != -1 && ++lastWordCounts[rxLastWord.cap()] >= maxWordOccurrence ) { removeLastWord = rxLastWord.cap(); } } // Remove word with most occurrences from beginning/end of stop names if ( removeFirstWord.isEmpty() && removeLastWord.isEmpty() ) { // If no first/last word with at least maxWordOccurrence occurrences was found, // find the word with the most occurrences int max = 0; // Find word at the beginning with most occurrences for ( QHash< QString, int >::ConstIterator it = firstWordCounts.constBegin(); it != firstWordCounts.constEnd(); ++it ) { if ( it.value() > max ) { max = it.value(); removeFirstWord = it.key(); } } // Find word at the end with more occurrences for ( QHash< QString, int >::ConstIterator it = lastWordCounts.constBegin(); it != lastWordCounts.constEnd(); ++it ) { if ( it.value() > max ) { max = it.value(); removeLastWord = it.key(); } } if ( max < minWordOccurrence ) { // The first/last word with the most occurrences has too few occurrences // Do not remove any word removeFirstWord.clear(); removeLastWord.clear(); } else if ( !removeLastWord.isEmpty() ) { // removeLastWord has more occurrences than removeFirstWord removeFirstWord.clear(); } } if ( !removeFirstWord.isEmpty() ) { // Remove removeFirstWord from all stop names QStringList returnStopNames; foreach ( const QString &stopName, stopNames ) { if ( stopName.startsWith(removeFirstWord) ) { returnStopNames << stopName.mid( removeFirstWord.length() + 1 ); } else { returnStopNames << stopName; } } return returnStopNames; } else if ( !removeLastWord.isEmpty() ) { // Remove removeLastWord from all stop names QStringList returnStopNames; foreach ( const QString &stopName, stopNames ) { if ( stopName.endsWith(removeLastWord) ) { returnStopNames << stopName.left( stopName.length() - removeLastWord.length() ); } else { returnStopNames << stopName; } } return returnStopNames; } else { // Nothing to remove found return stopNames; } } // This does the magic that allows Plasma to load // this plugin. The first argument must match // the X-Plasma-EngineName in the .desktop file. K_EXPORT_PLASMA_DATAENGINE( publictransport, PublicTransportEngine ) // this is needed since PublicTransportEngine is a QObject #include "build/publictransportdataengine.moc" diff --git a/engine/script/script_thread.cpp b/engine/script/script_thread.cpp index bcae49c..290a4fa 100644 --- a/engine/script/script_thread.cpp +++ b/engine/script/script_thread.cpp @@ -1,907 +1,907 @@ /* * Copyright 2012 Friedrich Pülz * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as * published by the Free Software Foundation; either version 2 or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ // Header #include "script_thread.h" // Own includes #include "config.h" #include "scriptapi.h" #include "script/serviceproviderscript.h" #include "serviceproviderdata.h" #include "request.h" #include "serviceproviderglobal.h" // KDE includes #include #include #include #include #include #include #include // Qt includes #include #include #include #include #include #include #include #include #include ScriptJob::ScriptJob( const ScriptData &data, const QSharedPointer< Storage > &scriptStorage, QObject* parent ) : ThreadWeaver::Job(parent), m_engine(0), m_mutex(new QMutex(QMutex::Recursive)), m_data(data), m_eventLoop(0), m_published(0), m_quit(false), m_success(true) { Q_ASSERT_X( data.isValid(), "ScriptJob constructor", "Needs valid script data" ); // Use global storage, may contain non-persistent data from earlier requests. // Does not need to live in this thread, it does not create any new QObjects. QMutexLocker locker( m_mutex ); m_objects.storage = scriptStorage; qRegisterMetaType( "DepartureRequest" ); qRegisterMetaType( "ArrivalRequest" ); qRegisterMetaType( "JourneyRequest" ); qRegisterMetaType( "StopSuggestionRequest" ); qRegisterMetaType( "StopsByGeoPositionRequest" ); qRegisterMetaType( "AdditionalDataRequest" ); } ScriptJob::~ScriptJob() { // Abort, if still running requestAbort(); // Do some cleanup if not done already cleanup(); delete m_mutex; } void ScriptJob::requestAbort() { m_mutex->lock(); if ( !m_engine ) { // Is already finished m_mutex->unlock(); return; } else if ( m_quit ) { // Is already aborting, wait for the script engine to get destroyed QEventLoop loop; connect( m_engine, SIGNAL(destroyed(QObject*)), &loop, SLOT(quit()) ); m_mutex->unlock(); // Run the event loop, waiting for the engine to get destroyed or a 1 second timeout QTimer::singleShot( 1000, &loop, SLOT(quit()) ); loop.exec(); return; } // Is still running, remember to abort m_quit = true; // Abort running network requests, if any if ( m_objects.network->hasRunningRequests() ) { m_objects.network->abortAllRequests(); } // Abort script evaluation if ( m_engine ) { m_engine->abortEvaluation(); } // Wake waiting event loops if ( m_eventLoop ) { QEventLoop *loop = m_eventLoop; m_eventLoop = 0; loop->quit(); } m_mutex->unlock(); // Wait until signals are processed qApp->processEvents(); } ScriptAgent::ScriptAgent( QScriptEngine* engine, QObject *parent ) : QObject(parent), QScriptEngineAgent(engine) { } void ScriptAgent::functionExit( qint64 scriptId, const QScriptValue& returnValue ) { Q_UNUSED( scriptId ); Q_UNUSED( returnValue ); QTimer::singleShot( 250, this, SLOT(checkExecution()) ); } void ScriptAgent::checkExecution() { if ( !engine()->isEvaluating() ) { emit scriptFinished(); } } void ScriptJob::run() { m_mutex->lock(); if ( !loadScript(m_data.program) ) { kDebug() << "Script could not be loaded correctly"; m_mutex->unlock(); return; } QScriptEngine *engine = m_engine; ScriptObjects objects = m_objects; const QString scriptFileName = m_data.provider.scriptFileName(); const QScriptValueList arguments = QScriptValueList() << request()->toScriptValue( engine ); const ParseDocumentMode parseMode = request()->parseMode(); m_mutex->unlock(); // Add call to the appropriate function QString functionName; switch ( parseMode ) { case ParseForDepartures: case ParseForArrivals: functionName = ServiceProviderScript::SCRIPT_FUNCTION_GETTIMETABLE; break; case ParseForJourneysByDepartureTime: case ParseForJourneysByArrivalTime: functionName = ServiceProviderScript::SCRIPT_FUNCTION_GETJOURNEYS; break; case ParseForStopSuggestions: functionName = ServiceProviderScript::SCRIPT_FUNCTION_GETSTOPSUGGESTIONS; break; case ParseForAdditionalData: functionName = ServiceProviderScript::SCRIPT_FUNCTION_GETADDITIONALDATA; break; default: kDebug() << "Parse mode unsupported:" << parseMode; break; } if ( functionName.isEmpty() ) { // This should never happen, therefore no i18n handleError( "Unknown parse mode" ); return; } // Check if the script function is implemented QScriptValue function = engine->globalObject().property( functionName ); if ( !function.isFunction() ) { handleError( i18nc("@info/plain", "Function %1 not implemented by " "the script %1", functionName, scriptFileName) ); return; } // Store start time of the script QElapsedTimer timer; timer.start(); // Call script function QScriptValue result = function.call( QScriptValue(), arguments ); if ( engine->hasUncaughtException() ) { // TODO Get filename where the exception occured, maybe use ScriptAgent for that handleError( i18nc("@info/plain", "Error in script function %1, " "line %2: %3.", functionName, engine->uncaughtExceptionLineNumber(), engine->uncaughtException().toString()) ); return; } // Inform about script run time DEBUG_ENGINE_JOBS( "Script finished in" << (timer.elapsed() / 1000.0) << "seconds: " << scriptFileName << parseMode ); GlobalTimetableInfo globalInfo; globalInfo.requestDate = QDate::currentDate(); globalInfo.delayInfoAvailable = !objects.result->isHintGiven( ResultObject::NoDelaysForStop ); // The called function returned, but asynchronous network requests may have been started. // Slots in the script may be connected to those requests and start script execution again. // In the execution new network requests may get started and so on. // // Wait until all network requests are finished and the script is not evaluating at the same // time. Define a global timeout, each waitFor() call subtracts the elapsed time. // // NOTE Network requests by default use a 30 seconds timeout, the global timeout should // be bigger. Synchronous requests that were started by signals of running asynchronous // requests are accounted as script execution time here. Synchronous requests that were // started before are already done. const int startTimeout = 60000; int timeout = startTimeout; while ( objects.network->hasRunningRequests() || engine->isEvaluating() ) { // Wait until all asynchronous network requests are finished if ( !waitFor(objects.network.data(), SIGNAL(allRequestsFinished()), WaitForNetwork, &timeout) ) { if ( timeout <= 0 ) { // Timeout expired while waiting for network requests to finish, // abort all requests that are still running objects.network->abortAllRequests(); QMutexLocker locker( m_mutex ); m_success = false; m_errorString = i18nc("@info", "Timeout expired after %1 while waiting for " "network requests to finish", KGlobal::locale()->prettyFormatDuration(startTimeout)); } cleanup(); return; } // Wait for script execution to finish, ie. slots connected to the last finished request(s) ScriptAgent agent( engine ); if ( !waitFor(&agent, SIGNAL(scriptFinished()), WaitForScriptFinish, &timeout) ) { if ( timeout <= 0 ) { // Timeout expired while waiting for script execution to finish, abort evaluation engine->abortEvaluation(); QMutexLocker locker( m_mutex ); m_success = false; m_errorString = i18nc("@info", "Timeout expired after %1 while waiting for script " "execution to finish", KGlobal::locale()->prettyFormatDuration(startTimeout)); } cleanup(); return; } // Check for new exceptions after waiting for script execution to finish (again) if ( engine->hasUncaughtException() ) { // TODO Get filename where the exception occured, maybe use ScriptAgent for that handleError( i18nc("@info/plain", "Error in script function %1, " "line %2: %3.", functionName, engine->uncaughtExceptionLineNumber(), engine->uncaughtException().toString()) ); return; } } // Publish remaining items, if any publish(); // Cleanup cleanup(); } void ScriptJob::cleanup() { QMutexLocker locker( m_mutex ); if ( !m_objects.storage.isNull() ) { m_objects.storage->checkLifetime(); } if ( !m_objects.result.isNull() ) { disconnect( m_objects.result.data(), 0, this, 0 ); } if ( m_engine ) { m_engine->deleteLater(); m_engine = 0; } } void ScriptJob::handleError( const QString &errorMessage ) { QMutexLocker locker( m_mutex ); kDebug() << "Error:" << errorMessage; kDebug() << "Backtrace:" << m_engine->uncaughtExceptionBacktrace().join("\n"); m_errorString = errorMessage; m_success = false; cleanup(); } QScriptValue networkRequestToScript( QScriptEngine *engine, const NetworkRequestPtr &request ) { return engine->newQObject( const_cast(request), QScriptEngine::QtOwnership, QScriptEngine::PreferExistingWrapperObject ); } void networkRequestFromScript( const QScriptValue &object, NetworkRequestPtr &request ) { request = qobject_cast( object.toQObject() ); } bool importExtension( QScriptEngine *engine, const QString &extension ) { if ( !ServiceProviderScript::allowedExtensions().contains(extension, Qt::CaseInsensitive) ) { if ( engine->availableExtensions().contains(extension, Qt::CaseInsensitive) ) { kDebug() << "Extension" << extension << "is not allowed currently"; } else { kDebug() << "Extension" << extension << "could not be found"; kDebug() << "Available extensions:" << engine->availableExtensions(); } kDebug() << "Allowed extensions:" << ServiceProviderScript::allowedExtensions(); return false; } else { if ( engine->importExtension(extension).isUndefined() ) { return true; } else { if ( engine->hasUncaughtException() ) { kDebug() << "Could not import extension" << extension << engine->uncaughtExceptionLineNumber() << engine->uncaughtException().toString(); kDebug() << "Backtrace:" << engine->uncaughtExceptionBacktrace().join("\n"); } return false; } } } bool ScriptJob::waitFor( QObject *sender, const char *signal, WaitForType type, int *timeout ) { if ( *timeout <= 0 ) { return false; } // Do not wait if the job was aborted or failed QMutexLocker locker( m_mutex ); if ( !m_success || m_quit ) { return false; } QScriptEngine *engine = m_engine; ScriptObjects objects = m_objects; // Test if the target condition is already met if ( (type == WaitForNetwork && objects.network->hasRunningRequests()) || (type == WaitForScriptFinish && engine->isEvaluating()) ) { // Not finished yet, wait for the given signal, // that should get emitted when the target condition is met QEventLoop loop; connect( sender, signal, &loop, SLOT(quit()) ); // Add a timeout to not wait forever (eg. because of an infinite loop in the script). // Use a QTimer variable to be able to check if the timeout caused the event loop to quit // rather than the given signal QTimer timer; timer.setSingleShot( true ); connect( &timer, SIGNAL(timeout()), &loop, SLOT(quit()) ); // Store a pointer to the event loop, to be able to quit it on abort. // Then start the timeout. m_eventLoop = &loop; QElapsedTimer elapsedTimer; elapsedTimer.start(); timer.start( *timeout ); m_mutex->unlock(); // Start the event loop waiting for the given signal / timeout. // QScriptEngine continues execution here or network requests continue to get handled and // may call script slots on finish. loop.exec(); // Test if the timeout has expired, ie. if the timer is no longer running (single shot) m_mutex->lock(); const bool timeoutExpired = !timer.isActive(); // Update remaining time of the timeout if ( timeoutExpired ) { *timeout = 0; } else { *timeout -= elapsedTimer.elapsed(); } // Test if the job was aborted while waiting if ( !m_eventLoop || m_quit ) { // Job was aborted m_eventLoop = 0; return false; } m_eventLoop = 0; // Generate errors if the timeout has expired and abort network requests / script execution if ( timeoutExpired ) { return false; } } // The target condition was met in time or was already met return true; } QScriptValue include( QScriptContext *context, QScriptEngine *engine ) { // Check argument count, include() call in global context? const QScriptContextInfo contextInfo( context->parentContext() ); if ( context->argumentCount() < 1 ) { context->throwError( i18nc("@info/plain", "One argument expected for include()") ); return engine->undefinedValue(); } else if ( context->parentContext() && context->parentContext()->parentContext() ) { QScriptContext *parentContext = context->parentContext()->parentContext(); bool error = false; while ( parentContext ) { const QScriptContextInfo parentContextInfo( parentContext ); if ( !parentContextInfo.fileName().isEmpty() && parentContextInfo.fileName() == contextInfo.fileName() ) { // Parent context is in the same file, error error = true; break; } parentContext = parentContext->parentContext(); } if ( error ) { context->throwError( i18nc("@info/plain", "include() calls must be in global context") ); return engine->undefinedValue(); } } // Check if this include() call is before all other statements QVariantHash includeData = context->callee().data().toVariant().toHash(); if ( includeData.contains(contextInfo.fileName()) ) { const quint16 maxIncludeLine = includeData[ contextInfo.fileName() ].toInt(); if ( contextInfo.lineNumber() > maxIncludeLine ) { context->throwError( i18nc("@info/plain", "include() calls must be the first statements") ); return engine->undefinedValue(); } } // Get argument and check that it's not pointing to another directory const QString fileName = context->argument(0).toString(); if ( fileName.contains('/') ) { context->throwError( i18nc("@info/plain", "Cannot include files from other directories") ); return engine->undefinedValue(); } // Find the script to be included const QString subDirectory = ServiceProviderGlobal::installationSubDirectory(); const QString filePath = KGlobal::dirs()->findResource( "data", subDirectory + fileName ); // Check if the script was already included QStringList includedFiles = engine->globalObject().property( "includedFiles" ).toVariant().toStringList(); if ( includedFiles.contains(filePath) ) { - kWarning() << "File already included" << filePath; + qWarning() << "File already included" << filePath; return engine->undefinedValue(); } // Try to open the file to be included QFile scriptFile( filePath ); if ( !scriptFile.open(QIODevice::ReadOnly) ) { context->throwError( i18nc("@info/plain", "Cannot find file to be included: " "%1", fileName) ); return engine->undefinedValue(); } // Read the file QTextStream stream( &scriptFile ); const QString program = stream.readAll(); scriptFile.close(); if ( !includeData.contains(scriptFile.fileName()) ) { includeData[ scriptFile.fileName() ] = maxIncludeLine( program ); QScriptValue includeFunction = engine->globalObject().property("include"); Q_ASSERT( includeFunction.isValid() ); includeFunction.setData( qScriptValueFromValue(engine, includeData) ); engine->globalObject().setProperty( "include", includeFunction, QScriptValue::KeepExistingFlags ); } // Set script context QScriptContext *parent = context->parentContext(); if ( parent ) { context->setActivationObject( parent->activationObject() ); context->setThisObject( parent->thisObject() ); } // Store included files in global property "includedFiles" includedFiles << filePath; includedFiles.removeDuplicates(); QScriptValue::PropertyFlags flags = QScriptValue::ReadOnly | QScriptValue::Undeletable; engine->globalObject().setProperty( "includedFiles", engine->newVariant(includedFiles), flags ); // Evaluate script return engine->evaluate( program, filePath ); } quint16 maxIncludeLine( const QString &program ) { // Get first lines of script code until the first statement which is not an include() call // The regular expression matches in blocks: Multiline comments (needs non-greedy regexp), // one line comments, whitespaces & newlines, include("...") calls and semi-colons (needed, // because the regexp is non-greedy) QRegExp programRegExp( "\\s*(?:\\s*//[^\\n]*\\n|/\\*.*\\*/|[\\s\\n]+|include\\s*\\(\\s*\"[^\"]*\"\\s*\\)|;)+" ); programRegExp.setMinimal( true ); int pos = 0, nextPos = 0; QString programBegin; while ( (pos = programRegExp.indexIn(program, pos)) == nextPos ) { const QString capture = programRegExp.cap(); programBegin.append( capture ); pos += programRegExp.matchedLength(); nextPos = pos; } return programBegin.count( '\n' ); } bool ScriptJob::loadScript( const QSharedPointer< QScriptProgram > &script ) { if ( !script ) { kDebug() << "Invalid script data"; return false; } // Create script engine QMutexLocker locker( m_mutex ); m_engine = new QScriptEngine(); foreach ( const QString &extension, m_data.provider.scriptExtensions() ) { if ( !importExtension(m_engine, extension) ) { m_errorString = i18nc("@info/plain", "Could not load script extension " "%1.", extension); m_success = false; cleanup(); return false; } } // Create and attach script objects. // The Storage object is already created and will not be replaced by a new instance. // It lives in the GUI thread and gets used in all thread jobs to not erase non-persistently // stored data after each request. m_objects.createObjects( m_data ); m_objects.attachToEngine( m_engine, m_data ); // Connect the publish() signal directly (the result object lives in the thread that gets // run by this job, this job itself lives in the GUI thread). Connect directly to ensure // the script objects and the request are still valid (prevent crashes). connect( m_objects.result.data(), SIGNAL(publish()), this, SLOT(publish()), Qt::DirectConnection ); // Load the script program m_mutex->unlock(); m_engine->evaluate( *script ); m_mutex->lock(); if ( m_engine->hasUncaughtException() ) { kDebug() << "Error in the script" << m_engine->uncaughtExceptionLineNumber() << m_engine->uncaughtException().toString(); kDebug() << "Backtrace:" << m_engine->uncaughtExceptionBacktrace().join("\n"); m_errorString = i18nc("@info/plain", "Error in script, line %1: %2.", m_engine->uncaughtExceptionLineNumber(), m_engine->uncaughtException().toString()); m_success = false; cleanup(); return false; } else { return true; } } bool ScriptJob::hasDataToBePublished() const { QMutexLocker locker( m_mutex ); return !m_objects.isValid() ? false : m_objects.result->count() > m_published; } void ScriptJob::publish() { // This slot gets run in the thread of this job // Only publish, if there is data which is not already published if ( hasDataToBePublished() ) { m_mutex->lock(); GlobalTimetableInfo globalInfo; const QList< TimetableData > data = m_objects.result->data().mid( m_published ); const ResultObject::Features features = m_objects.result->features(); const ResultObject::Hints hints = m_objects.result->hints(); const QString lastUserUrl = m_objects.network->lastUserUrl(); const bool couldNeedForcedUpdate = m_published > 0; const MoreItemsRequest *moreItemsRequest = dynamic_cast(request()); const AbstractRequest *_request = moreItemsRequest ? moreItemsRequest->request().data() : request(); const ParseDocumentMode parseMode = request()->parseMode(); m_lastUrl = m_objects.network->lastUrl(); // TODO Store all URLs m_lastUserUrl = m_objects.network->lastUserUrl(); m_published += data.count(); // Unlock mutex after copying the request object, then emit it with an xxxReady() signal switch ( parseMode ) { case ParseForDepartures: { Q_ASSERT(dynamic_cast(_request)); const DepartureRequest departureRequest = *dynamic_cast(_request); m_mutex->unlock(); emit departuresReady( data, features, hints, lastUserUrl, globalInfo, departureRequest, couldNeedForcedUpdate ); break; } case ParseForArrivals: { Q_ASSERT(dynamic_cast(_request)); const ArrivalRequest arrivalRequest = *dynamic_cast(_request); m_mutex->unlock(); emit arrivalsReady( data, features, hints, lastUserUrl, globalInfo, arrivalRequest, couldNeedForcedUpdate ); break; } case ParseForJourneysByDepartureTime: case ParseForJourneysByArrivalTime: { Q_ASSERT(dynamic_cast(_request)); const JourneyRequest journeyRequest = *dynamic_cast(_request); m_mutex->unlock(); emit journeysReady( data, features, hints, lastUserUrl, globalInfo, journeyRequest, couldNeedForcedUpdate ); break; } case ParseForStopSuggestions: { Q_ASSERT(dynamic_cast(_request)); const StopSuggestionRequest stopSuggestionRequest = *dynamic_cast< const StopSuggestionRequest* >( _request ); m_mutex->unlock(); emit stopSuggestionsReady( data, features, hints, lastUserUrl, globalInfo, stopSuggestionRequest, couldNeedForcedUpdate ); break; } case ParseForAdditionalData: { if ( data.count() > 1 ) { - kWarning() << "The script added more than one result in an additional data request"; + qWarning() << "The script added more than one result in an additional data request"; kDebug() << "All received additional data for item" << dynamic_cast(_request)->itemNumber() << ':' << data; m_errorString = i18nc("@info/plain", "The script added more than one result in " "an additional data request."); m_success = false; cleanup(); m_mutex->unlock(); return; } // Additional data gets requested per timetable item, only one result expected const TimetableData additionalData = data.first(); if ( additionalData.isEmpty() ) { - kWarning() << "Did not find any additional data."; + qWarning() << "Did not find any additional data."; m_errorString = i18nc("@info/plain", "TODO."); // TODO m_success = false; cleanup(); m_mutex->unlock(); return; } Q_ASSERT(dynamic_cast(_request)); const AdditionalDataRequest additionalDataRequest = *dynamic_cast< const AdditionalDataRequest* >( _request ); m_mutex->unlock(); emit additionalDataReady( additionalData, features, hints, lastUserUrl, globalInfo, additionalDataRequest, couldNeedForcedUpdate ); break; } default: m_mutex->unlock(); kDebug() << "Parse mode unsupported:" << parseMode; break; } } } class DepartureJobPrivate { public: DepartureJobPrivate( const DepartureRequest &request ) : request(request) {}; DepartureRequest request; }; DepartureJob::DepartureJob( const ScriptData &data, const QSharedPointer< Storage > &scriptStorage, const DepartureRequest& request, QObject* parent ) : ScriptJob(data, scriptStorage, parent), d(new DepartureJobPrivate(request)) { } DepartureJob::~DepartureJob() { delete d; } const AbstractRequest *DepartureJob::request() const { QMutexLocker locker( m_mutex ); return &d->request; } QString ScriptJob::sourceName() const { QMutexLocker locker( m_mutex ); return request()->sourceName(); } const AbstractRequest *ScriptJob::cloneRequest() const { QMutexLocker locker( m_mutex ); return request()->clone(); } class ArrivalJobPrivate { public: ArrivalJobPrivate( const ArrivalRequest &request ) : request(request) {}; ArrivalRequest request; }; ArrivalJob::ArrivalJob( const ScriptData &data, const QSharedPointer< Storage > &scriptStorage, const ArrivalRequest& request, QObject* parent ) : ScriptJob(data, scriptStorage, parent), d(new ArrivalJobPrivate(request)) { } ArrivalJob::~ArrivalJob() { delete d; } const AbstractRequest *ArrivalJob::request() const { QMutexLocker locker( m_mutex ); return &d->request; } class JourneyJobPrivate { public: JourneyJobPrivate( const JourneyRequest &request ) : request(request) {}; JourneyRequest request; }; JourneyJob::JourneyJob( const ScriptData &data, const QSharedPointer< Storage > &scriptStorage, const JourneyRequest& request, QObject* parent ) : ScriptJob(data, scriptStorage, parent), d(new JourneyJobPrivate(request)) { } JourneyJob::~JourneyJob() { delete d; } const AbstractRequest *JourneyJob::request() const { QMutexLocker locker( m_mutex ); return &d->request; } class StopSuggestionsJobPrivate { public: StopSuggestionsJobPrivate( const StopSuggestionRequest &request ) : request(request) {}; StopSuggestionRequest request; }; StopSuggestionsJob::StopSuggestionsJob( const ScriptData &data, const QSharedPointer< Storage > &scriptStorage, const StopSuggestionRequest& request, QObject* parent ) : ScriptJob(data, scriptStorage, parent), d(new StopSuggestionsJobPrivate(request)) { } StopSuggestionsJob::~StopSuggestionsJob() { delete d; } const AbstractRequest *StopSuggestionsJob::request() const { QMutexLocker locker( m_mutex ); return &d->request; } class StopsByGeoPositionJobPrivate { public: StopsByGeoPositionJobPrivate( const StopsByGeoPositionRequest &request ) : request(request) {}; StopsByGeoPositionRequest request; }; StopsByGeoPositionJob::StopsByGeoPositionJob( const ScriptData &data, const QSharedPointer< Storage > &scriptStorage, const StopsByGeoPositionRequest& request, QObject* parent ) : ScriptJob(data, scriptStorage, parent), d(new StopsByGeoPositionJobPrivate(request)) { } StopsByGeoPositionJob::~StopsByGeoPositionJob() { delete d; } const AbstractRequest *StopsByGeoPositionJob::request() const { QMutexLocker locker( m_mutex ); return &d->request; } class AdditionalDataJobPrivate { public: AdditionalDataJobPrivate( const AdditionalDataRequest &request ) : request(request) {}; AdditionalDataRequest request; }; AdditionalDataJob::AdditionalDataJob( const ScriptData &data, const QSharedPointer< Storage > &scriptStorage, const AdditionalDataRequest &request, QObject *parent ) : ScriptJob(data, scriptStorage, parent), d(new AdditionalDataJobPrivate(request)) { } AdditionalDataJob::~AdditionalDataJob() { delete d; } const AbstractRequest *AdditionalDataJob::request() const { QMutexLocker locker( m_mutex ); return &d->request; } class MoreItemsJobPrivate { public: MoreItemsJobPrivate( const MoreItemsRequest &request ) : request(request) {}; MoreItemsRequest request; }; MoreItemsJob::MoreItemsJob( const ScriptData &data, const QSharedPointer< Storage > &scriptStorage, const MoreItemsRequest &request, QObject *parent ) : ScriptJob(data, scriptStorage, parent), d(new MoreItemsJobPrivate(request)) { } MoreItemsJob::~MoreItemsJob() { delete d; } const AbstractRequest *MoreItemsJob::request() const { QMutexLocker locker( m_mutex ); return &d->request; } bool ScriptJob::success() const { QMutexLocker locker( m_mutex ); return m_success; } int ScriptJob::publishedItems() const { QMutexLocker locker( m_mutex ); return m_published; } QString ScriptJob::errorString() const { QMutexLocker locker( m_mutex ); return m_errorString; } QString ScriptJob::lastDownloadUrl() const { QMutexLocker locker( m_mutex ); return m_lastUrl; } QString ScriptJob::lastUserUrl() const { QMutexLocker locker( m_mutex ); return m_lastUserUrl; } diff --git a/engine/script/scriptapi.cpp b/engine/script/scriptapi.cpp index ab0288d..37a7f69 100644 --- a/engine/script/scriptapi.cpp +++ b/engine/script/scriptapi.cpp @@ -1,2378 +1,2379 @@ /* * Copyright 2012 Friedrich Pülz * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as * published by the Free Software Foundation; either version 2 or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ // Header #include "scriptapi.h" // Own includes #include "config.h" #include "global.h" #include "serviceproviderglobal.h" // KDE includes #include #include #include #include #include // Qt includes #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include // Other includes #include namespace ScriptApi { NetworkRequest::NetworkRequest( QObject *parent ) : QObject(parent), m_mutex(new QMutex(QMutex::Recursive)), m_network(0), m_isFinished(false), m_request(0), m_reply(0) { } NetworkRequest::NetworkRequest( const QString &url, const QString &userUrl, Network *network, QObject* parent ) : QObject(parent), m_mutex(new QMutex(QMutex::Recursive)), m_url(url), m_userUrl(userUrl.isEmpty() ? url : userUrl), m_network(network), m_isFinished(false), m_request(new QNetworkRequest(url)), m_reply(0) { } NetworkRequest::~NetworkRequest() { abort(); delete m_request; delete m_mutex; } void NetworkRequest::abort() { const bool timedOut = qobject_cast< QTimer* >( sender() ); if ( !isRunning() ) { if ( timedOut ) { kDebug() << "Timeout, but request already finished"; } return; } // isRunning() returned true => m_reply != 0 m_mutex->lockInline(); disconnect( m_reply, 0, this, 0 ); m_reply->abort(); m_reply->deleteLater(); m_reply = 0; const QString url = m_url; const QVariant userData = m_userData; m_mutex->unlockInline(); emit aborted( timedOut ); emit finished( QByteArray(), true, i18nc("@info/plain", "The request was aborted"), -1, 0, url, userData ); } void NetworkRequest::slotReadyRead() { m_mutex->lockInline(); if ( !m_reply ) { // Prevent crashes on exit m_mutex->unlockInline(); - kWarning() << "Reply object already deleted, aborted?"; + qWarning() << "Reply object already deleted, aborted?"; return; } // Read all data, decode it and give it to the script QByteArray data = m_reply->readAll(); m_data.append( data ); if ( data.isEmpty() ) { - kWarning() << "Error downloading" << m_url << m_reply->errorString(); + qWarning() << "Error downloading" << m_url << m_reply->errorString(); } m_mutex->unlockInline(); emit readyRead( data ); } QByteArray gzipDecompress( QByteArray compressData ) { // Strip header and trailer compressData.remove( 0, 10 ); compressData.chop( 12 ); // FIXME Decompress in one chunk, because otherwise it fails with error -3 "distance too far back", // estimate size of uncompressed data, expect that the data was compressed at best to 20% size, // limit to 512KB const int chunkSize = qMin( int(compressData.size() / 0.2), 512 * 1024 ); kDebug() << "Chunk size:" << chunkSize; if ( chunkSize == 512 * 1024 ) { - kWarning() << "Maximum chunk size for decompression reached, may fail"; + qWarning() << "Maximum chunk size for decompression reached, may fail"; } unsigned char buffer[ chunkSize ]; z_stream stream; stream.next_in = (Bytef*)(compressData.data()); stream.avail_in = compressData.size(); stream.total_in = 0; stream.total_out = 0; stream.zalloc = Z_NULL; stream.zfree = Z_NULL; stream.opaque = Z_NULL; if ( inflateInit2(&stream, -8) != Z_OK ) { kDebug() << "cmpr_stream error!"; return QByteArray(); } QByteArray uncompressed; do { stream.next_out = buffer; stream.avail_out = chunkSize; int status = inflate( &stream, Z_SYNC_FLUSH ); if ( status == Z_OK || status == Z_STREAM_END ) { uncompressed.append( QByteArray::fromRawData( (char*)buffer, chunkSize - stream.avail_out) ); if ( status == Z_STREAM_END ) { break; } } else { - kWarning() << "Error while decompressing" << status << stream.msg; + qWarning() << "Error while decompressing" << status << stream.msg; if ( status == Z_NEED_DICT || status == Z_DATA_ERROR || status == Z_MEM_ERROR ) { inflateEnd( &stream ); } return QByteArray(); } } while( stream.avail_out == 0 ); inflateEnd( &stream ); return uncompressed; } void NetworkRequest::slotFinished() { m_mutex->lockInline(); if ( !m_reply ) { // Prevent crashes on exit m_mutex->unlockInline(); - kWarning() << "Reply object already deleted, aborted?"; + qWarning() << "Reply object already deleted, aborted?"; return; } if ( m_reply->attribute(QNetworkRequest::RedirectionTargetAttribute).isValid() ) { if ( m_redirectUrl.isValid() ) { - kWarning() << "Only one redirection allowed, from" << m_url << "to" << m_redirectUrl; - kWarning() << "New redirection to" + qWarning() << "Only one redirection allowed, from" << m_url << "to" << m_redirectUrl; + qWarning() << "New redirection to" << m_reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl(); } else { m_redirectUrl = m_reply->attribute( QNetworkRequest::RedirectionTargetAttribute ).toUrl(); DEBUG_NETWORK("Redirection to" << m_redirectUrl); // Delete the reply m_reply->deleteLater(); m_reply = 0; delete m_request; m_request = new QNetworkRequest( m_redirectUrl ); const QUrl redirectUrl = m_redirectUrl; m_mutex->unlockInline(); emit redirected( redirectUrl ); return; } } const int size = m_reply->size(); const int statusCode = m_reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); // Read all data, decode it and give it to the script m_data.append( m_reply->readAll() ); if ( m_data.isEmpty() ) { - kWarning() << "Error downloading" << m_url + qWarning() << "Error downloading" << m_url << (m_reply ? m_reply->errorString() : "Reply already deleted"); } // Check if the data is compressed and was not decompressed by QNetworkAccessManager if ( m_data.length() >= 2 && quint8(m_data[0]) == 0x1f && quint8(m_data[1]) == 0x8b ) { // Data is compressed, uncompress it // NOTE qUncompress() did not work here, "invalid zip" m_data = gzipDecompress( m_data ); DEBUG_NETWORK("Uncompressed data from" << size << "Bytes to" << m_data.size() << "Bytes, ratio:" << (100 - (m_data.isEmpty() ? 100 : qRound(100 * size / m_data.size()))) << '%'); } DEBUG_NETWORK("Request finished" << m_reply->url()); if ( m_reply->url().isEmpty() ) { - kWarning() << "Empty URL in QNetworkReply!"; + qWarning() << "Empty URL in QNetworkReply!"; } const bool hasError = m_reply->error() != QNetworkReply::NoError; const QString errorString = m_reply->errorString(); m_reply->deleteLater(); m_reply = 0; m_isFinished = true; const QByteArray data = m_data; const QString url = m_url; const QVariant userData = m_userData; m_mutex->unlockInline(); emit finished( data, hasError, errorString, statusCode, size, url, userData ); } void NetworkRequest::started( QNetworkReply* reply, int timeout ) { m_mutex->lockInline(); if ( !m_network ) { - kWarning() << "Can't decode, no m_network given..."; + qWarning() << "Can't decode, no m_network given..."; m_mutex->unlockInline(); return; } m_data.clear(); m_reply = reply; if ( timeout > 0 ) { QTimer::singleShot( timeout, this, SLOT(abort()) ); } // Connect to signals of reply only when the associated signals of this class are connected if ( receivers(SIGNAL(readyRead(QByteArray))) > 0 ) { connect( m_reply, SIGNAL(readyRead()), this, SLOT(slotReadyRead()) ); } connect( m_reply, SIGNAL(finished()), this, SLOT(slotFinished()) ); m_mutex->unlockInline(); emit started(); } bool NetworkRequest::isValid() const { QMutexLocker locker( m_mutex ); if ( m_request ) { return true; } else { // Default constructor used, not available to scripts kDebug() << "Request is invalid"; return false; } } QByteArray NetworkRequest::getCharset( const QString& charset ) const { QMutexLocker locker( m_mutex ); QByteArray baCharset; if ( charset.isEmpty() ) { // No charset given, use the one specified in the ContentType header baCharset = m_request->header( QNetworkRequest::ContentTypeHeader ).toByteArray(); // No ContentType header, use utf8 if ( baCharset.isEmpty() ) { baCharset = "utf8"; } } else { baCharset = charset.toUtf8(); } return baCharset; } QByteArray NetworkRequest::postDataByteArray() const { QMutexLocker locker( m_mutex ); return m_postData; } void NetworkRequest::setPostData( const QString& postData, const QString& charset ) { if ( !isValid() ) { return; } if ( isRunning() ) { kDebug() << "Cannot set POST data for an already running request!"; return; } QByteArray baCharset = getCharset( charset ); QTextCodec *codec = QTextCodec::codecForName( baCharset ); QMutexLocker locker( m_mutex ); if ( codec ) { m_request->setHeader( QNetworkRequest::ContentTypeHeader, baCharset ); m_postData = codec->fromUnicode( postData ); } else { kDebug() << "Codec" << baCharset << "couldn't be found to encode the data " "to post, now using UTF-8"; m_request->setHeader( QNetworkRequest::ContentTypeHeader, "utf8" ); m_postData = postData.toUtf8(); } } QString NetworkRequest::header( const QString &header, const QString& charset ) const { if ( !isValid() ) { return QString(); } QByteArray baCharset = getCharset( charset ); QTextCodec *codec = QTextCodec::codecForName( baCharset ); QMutexLocker locker( m_mutex ); return m_request->rawHeader( codec ? codec->fromUnicode(header) : header.toUtf8() ); } void NetworkRequest::setHeader( const QString& header, const QString& value, const QString& charset ) { if ( !isValid() ) { return; } if ( isRunning() ) { kDebug() << "Cannot set headers for an already running request!"; return; } QByteArray baCharset = getCharset( charset ); QTextCodec *codec = QTextCodec::codecForName( baCharset ); QMutexLocker locker( m_mutex ); if ( codec ) { m_request->setRawHeader( codec->fromUnicode(header), codec->fromUnicode(value) ); } else { kDebug() << "Codec" << baCharset << "couldn't be found to encode the data " "to post, now using UTF-8"; m_request->setRawHeader( header.toUtf8(), value.toUtf8() ); } } QNetworkRequest* NetworkRequest::request() const { QMutexLocker locker( m_mutex ); return m_request; } Network::Network( const QByteArray &fallbackCharset, QObject* parent ) : QObject(parent), m_mutex(new QMutex(QMutex::Recursive)), m_fallbackCharset(fallbackCharset), m_manager(new QNetworkAccessManager()), m_quit(false), m_synchronousRequestCount(0), m_lastDownloadAborted(false) { qRegisterMetaType< NetworkRequest* >( "NetworkRequest*" ); qRegisterMetaType< NetworkRequest::Ptr >( "NetworkRequest::Ptr" ); } Network::~Network() { // Quit event loop of possibly running synchronous requests m_mutex->lock(); m_quit = true; m_mutex->unlock(); // Notify about the abort request to abort running synchronous requests abortSynchronousRequests(); qApp->processEvents(); // Handle the signal const QList< NetworkRequest::Ptr > _runningRequests = runningRequests(); if ( !_runningRequests.isEmpty() ) { - kWarning() << "Deleting Network object with" << _runningRequests.count() + qWarning() << "Deleting Network object with" << _runningRequests.count() << "running requests"; foreach ( const NetworkRequest::Ptr &request, _runningRequests ) { request->abort(); } } delete m_mutex; m_manager->deleteLater(); } NetworkRequest* Network::createRequest( const QString& url, const QString &userUrl ) { NetworkRequest *request = new NetworkRequest( url, userUrl, this, parent() ); NetworkRequest::Ptr requestPtr( request ); m_mutex->lock(); m_requests << requestPtr; m_mutex->unlock(); connect( request, SIGNAL(started()), this, SLOT(slotRequestStarted()) ); connect( request, SIGNAL(finished(QByteArray,bool,QString,int,int)), this, SLOT(slotRequestFinished(QByteArray,bool,QString,int,int)) ); connect( request, SIGNAL(aborted()), this, SLOT(slotRequestAborted()) ); connect( request, SIGNAL(redirected(QUrl)), this, SLOT(slotRequestRedirected(QUrl)) ); return request; } NetworkRequest::Ptr Network::getSharedRequest( NetworkRequest *request ) const { QMutexLocker locker( m_mutex ); foreach ( const NetworkRequest::Ptr &sharedRequest, m_requests ) { if ( sharedRequest.data() == request ) { return sharedRequest; } } return NetworkRequest::Ptr(); } void Network::slotRequestStarted() { NetworkRequest *request = qobject_cast< NetworkRequest* >( sender() ); NetworkRequest::Ptr sharedRequest = getSharedRequest( request ); Q_ASSERT( sharedRequest ); // This slot should only be connected to signals of NetworkRequest m_mutex->lockInline(); m_lastDownloadAborted = false; m_mutex->unlockInline(); emit requestStarted( sharedRequest ); } void Network::slotRequestFinished( const QByteArray &data, bool error, const QString &errorString, int statusCode, int size ) { NetworkRequest *request = qobject_cast< NetworkRequest* >( sender() ); NetworkRequest::Ptr sharedRequest = getSharedRequest( request ); Q_ASSERT( sharedRequest ); // This slot should only be connected to signals of NetworkRequest // Remove finished request from request list and add it to the list of finished requests // to not have it deleted here. The script might try to use the request object later, // eg. because of connected slots, and will crash if the request object was already deleted. // This way NetworkRequest objects stay alive at least as long as the Network object does. m_mutex->lockInline(); const QDateTime timestamp = QDateTime::currentDateTime(); m_requests.removeOne( sharedRequest ); m_finishedRequests << sharedRequest; m_mutex->unlockInline(); emit requestFinished( sharedRequest, data, error, errorString, timestamp, statusCode, size ); if ( !hasRunningRequests() ) { emit allRequestsFinished(); } } void Network::slotRequestRedirected( const QUrl &newUrl ) { NetworkRequest *request = qobject_cast< NetworkRequest* >( sender() ); NetworkRequest::Ptr sharedRequest = getSharedRequest( request ); Q_ASSERT( sharedRequest ); // This slot should only be connected to signals of NetworkRequest m_mutex->lockInline(); QNetworkReply *reply = m_manager->get( *request->request() ); m_lastUrl = newUrl.toString(); m_mutex->unlockInline(); request->started( reply ); DEBUG_NETWORK("Redirected to" << newUrl); emit requestRedirected( sharedRequest, newUrl ); } void Network::slotRequestAborted() { m_mutex->lockInline(); if ( m_quit ) { m_mutex->unlockInline(); return; } NetworkRequest *request = qobject_cast< NetworkRequest* >( sender() ); NetworkRequest::Ptr sharedRequest = getSharedRequest( request ); if ( !sharedRequest ) { - kWarning() << "Network object already deleted?"; + qWarning() << "Network object already deleted?"; } // Q_ASSERT( sharedRequest ); // This slot should only be connected to signals of NetworkRequest DEBUG_NETWORK("Aborted" << request->url()); m_lastDownloadAborted = true; m_mutex->unlockInline(); emit requestAborted( sharedRequest ); } bool Network::checkRequest( NetworkRequest* request ) { // Wrong argument type from script or no argument if ( !request ) { kDebug() << "Need a NetworkRequest object as argument, create it with " "'network.createRequest(url)'"; return false; } // The same request can not be executed more than once at a time if ( request->isRunning() ) { kDebug() << "Request is currently running" << request->url(); return false; } else if ( request->isFinished() ) { kDebug() << "Request is already finished" << request->url(); return false; } return request->isValid(); } void Network::get( NetworkRequest* request, int timeout ) { if ( !checkRequest(request) ) { return; } // Create a get request m_mutex->lockInline(); QNetworkReply *reply = m_manager->get( *request->request() ); m_lastUrl = request->url(); m_lastUserUrl = request->userUrl(); m_mutex->unlockInline(); request->started( reply, timeout ); } void Network::head( NetworkRequest* request, int timeout ) { if ( !checkRequest(request) ) { return; } // Create a head request m_mutex->lockInline(); QNetworkReply *reply = m_manager->head( *request->request() ); m_lastUrl = request->url(); m_lastUserUrl = request->userUrl(); m_mutex->unlockInline(); request->started( reply, timeout ); } void Network::post( NetworkRequest* request, int timeout ) { if ( !checkRequest(request) ) { return; } // Create a head request m_mutex->lockInline(); QNetworkReply *reply = m_manager->post( *request->request(), request->postDataByteArray() ); m_lastUrl = request->url(); m_lastUserUrl = request->userUrl(); m_mutex->unlockInline(); request->started( reply, timeout ); } void Network::abortAllRequests() { const QList< NetworkRequest::Ptr > requests = runningRequests(); DEBUG_NETWORK("Abort" << requests.count() << "request(s)"); for ( int i = requests.count() - 1; i >= 0; --i ) { // Calling abort automatically removes the aborted request from m_createdRequests requests[i]->abort(); } // Notify about the abort request to abort running synchronous requests abortSynchronousRequests(); } void Network::abortSynchronousRequests() { emit doAbortSynchronousRequests(); } QByteArray Network::getSynchronous( const QString &url, const QString &userUrl, int timeout ) { // Create a get request QNetworkRequest request( url ); DEBUG_NETWORK("Start synchronous request" << url); m_mutex->lockInline(); QNetworkReply *reply = m_manager->get( request ); ++m_synchronousRequestCount; m_lastUrl = url; m_lastUserUrl = userUrl.isEmpty() ? url : userUrl; m_lastDownloadAborted = false; m_mutex->unlockInline(); emit synchronousRequestStarted( url ); const QTime start = QTime::currentTime(); int redirectCount = 0; const int maxRedirections = 3; forever { // Use an event loop to wait for execution of the request, // ie. make netAccess.download() synchronous for scripts QEventLoop eventLoop; connect( reply, SIGNAL(finished()), &eventLoop, SLOT(quit()) ); connect( this, SIGNAL(doAbortSynchronousRequests()), &eventLoop, SLOT(quit()) ); if ( timeout > 0 ) { QTimer::singleShot( timeout, &eventLoop, SLOT(quit()) ); } if ( !reply->isFinished() ) { eventLoop.exec( QEventLoop::ExcludeUserInputEvents ); } m_mutex->lock(); const bool quit = m_quit || m_lastDownloadAborted || reply->isRunning(); m_mutex->unlock(); // Check if the timeout occured before the request finished if ( quit ) { DEBUG_NETWORK("Cancelled, destroyed or timeout while downloading" << url); emitSynchronousRequestFinished( url, QByteArray(), true ); return QByteArray(); } if ( reply->attribute(QNetworkRequest::RedirectionTargetAttribute).isValid() ) { ++redirectCount; if ( redirectCount > maxRedirections ) { reply->deleteLater(); emitSynchronousRequestFinished( url, QByteArray("Too many redirections"), true, 200, start.msecsTo(QTime::currentTime()) ); return QByteArray(); } // Request the redirection target const QUrl redirectUrl = reply->attribute( QNetworkRequest::RedirectionTargetAttribute ).toUrl(); request.setUrl( redirectUrl ); DEBUG_NETWORK("Redirected to" << redirectUrl); m_mutex->lock(); delete reply; reply = m_manager->get( request ); m_lastUrl = redirectUrl.toString(); m_mutex->unlock(); emit synchronousRequestRedirected( redirectUrl.toEncoded() ); } else { // No (more) redirection break; } } const int time = start.msecsTo( QTime::currentTime() ); const int statusCode = reply->attribute( QNetworkRequest::HttpStatusCodeAttribute ).toInt(); DEBUG_NETWORK("Waited" << (time / 1000.0) << "seconds for download of" << url << "Status:" << statusCode); // Read all data, decode it and give it to the script QByteArray data = reply->readAll(); reply->deleteLater(); if ( data.isEmpty() ) { - kWarning() << "Error downloading" << url << reply->errorString(); + qWarning() << "Error downloading" << url << reply->errorString(); emitSynchronousRequestFinished( url, QByteArray(), true, statusCode, time ); return QByteArray(); } else { emitSynchronousRequestFinished( url, data, false, statusCode, time, data.size() ); return data; } } void Network::emitSynchronousRequestFinished( const QString &url, const QByteArray &data, bool cancelled, int statusCode, int waitTime, int size ) { m_mutex->lock(); --m_synchronousRequestCount; m_mutex->unlock(); emit synchronousRequestFinished( url, data, cancelled, statusCode, waitTime, size ); if ( !hasRunningRequests() ) { emit allRequestsFinished(); } } ResultObject::ResultObject( QObject* parent ) : QObject(parent), m_mutex(new QMutex()), m_features(DefaultFeatures), m_hints(NoHint) { } ResultObject::~ResultObject() { delete m_mutex; } bool ResultObject::isHintGiven( ResultObject::Hint hint ) const { QMutexLocker locker( m_mutex ); return m_hints.testFlag( hint ); } void ResultObject::giveHint( ResultObject::Hint hint, bool enable ) { QMutexLocker locker( m_mutex ); if ( enable ) { // Remove incompatible flags of hint if any if ( hint == CityNamesAreLeft && m_hints.testFlag(CityNamesAreRight) ) { m_hints &= ~CityNamesAreRight; } else if ( hint == CityNamesAreRight && m_hints.testFlag(CityNamesAreLeft) ) { m_hints &= ~CityNamesAreLeft; } m_hints |= hint; } else { m_hints &= ~hint; } } bool ResultObject::isFeatureEnabled( ResultObject::Feature feature ) const { QMutexLocker locker( m_mutex ); return m_features.testFlag( feature ); } void ResultObject::enableFeature( ResultObject::Feature feature, bool enable ) { QMutexLocker locker( m_mutex ); if ( enable ) { m_features |= feature; } else { m_features &= ~feature; } } void ResultObject::dataList( const QList< TimetableData > &dataList, PublicTransportInfoList *infoList, ParseDocumentMode parseMode, Enums::VehicleType defaultVehicleType, const GlobalTimetableInfo *globalInfo, ResultObject::Features features, ResultObject::Hints hints ) { // TODO Use features and hints QDate curDate; QTime lastTime; int dayAdjustment = hints.testFlag(DatesNeedAdjustment) ? QDate::currentDate().daysTo(globalInfo->requestDate) : 0; if ( dayAdjustment != 0 ) { kDebug() << "Dates get adjusted by" << dayAdjustment << "days"; } // Find words at the beginning/end of target and route stop names that have many // occurrences. These words are most likely the city names where the stops are in. // But the timetable becomes easier to read and looks nicer, if not each stop name // includes the same city name. QHash< QString, int > firstWordCounts; // Counts occurrences of words at the beginning QHash< QString, int > lastWordCounts; // Counts occurrences of words at the end // This is the range of occurrences of one word in stop names, // that causes that word to be removed const int minWordOccurrence = qMax( 2, dataList.count() ); const int maxWordOccurrence = qMax( 3, dataList.count() / 2 ); // This regular expression gets used to search for word at the end, possibly including // a colon before the last word QRegExp rxLastWord( ",?\\s+\\S+$" ); // These strings store the words with the most occurrences in stop names at the beginning/end QString removeFirstWord; QString removeLastWord; // Read timetable data from the script for ( int i = 0; i < dataList.count(); ++i ) { TimetableData timetableData = dataList[ i ]; // Set default vehicle type if none is set if ( !timetableData.contains(Enums::TypeOfVehicle) || timetableData[Enums::TypeOfVehicle].toString().isEmpty() ) { timetableData[ Enums::TypeOfVehicle ] = static_cast( defaultVehicleType ); } if ( parseMode != ParseForStopSuggestions ) { QDateTime dateTime = timetableData[ Enums::DepartureDateTime ].toDateTime(); QDate departureDate = timetableData[ Enums::DepartureDate ].toDate(); QTime departureTime = timetableData[ Enums::DepartureTime ].toTime(); if ( !dateTime.isValid() && !departureTime.isValid() ) { kDebug() << "No departure time given!" << timetableData[Enums::DepartureTime]; kDebug() << "Use eg. helper.matchTime() to convert a string to a time object"; } if ( !dateTime.isValid() ) { if ( departureDate.isValid() ) { dateTime = QDateTime( departureDate, departureTime ); } else if ( curDate.isNull() ) { // First departure if ( QTime::currentTime().hour() < 3 && departureTime.hour() > 21 ) { dateTime.setDate( QDate::currentDate().addDays(-1) ); } else if ( QTime::currentTime().hour() > 21 && departureTime.hour() < 3 ) { dateTime.setDate( QDate::currentDate().addDays(1) ); } else { dateTime.setDate( QDate::currentDate() ); } } else if ( lastTime.secsTo(departureTime) < -5 * 60 ) { // Time too much ealier than last time, estimate it's tomorrow dateTime.setDate( curDate.addDays(1) ); } else { dateTime.setDate( curDate ); } timetableData[ Enums::DepartureDateTime ] = dateTime; } if ( dayAdjustment != 0 ) { dateTime.setDate( dateTime.date().addDays(dayAdjustment) ); timetableData[ Enums::DepartureDateTime ] = dateTime; } curDate = dateTime.date(); lastTime = departureTime; } // Create info object for the timetable data PublicTransportInfoPtr info; if ( parseMode == ParseForJourneysByDepartureTime || parseMode == ParseForJourneysByArrivalTime ) { info = QSharedPointer( new JourneyInfo(timetableData) ); } else if ( parseMode == ParseForDepartures || parseMode == ParseForArrivals ) { info = QSharedPointer( new DepartureInfo(timetableData) ); } else if ( parseMode == ParseForStopSuggestions ) { info = QSharedPointer( new StopInfo(timetableData) ); } if ( !info->isValid() ) { info.clear(); continue; } // Find word to remove from beginning/end of stop names, if not already found // TODO Use hint from the data engine.. if ( features.testFlag(AutoRemoveCityFromStopNames) && removeFirstWord.isEmpty() && removeLastWord.isEmpty() ) { // First count the first/last word of the target stop name const QString target = info->value( Enums::Target ).toString(); int pos = target.indexOf( ' ' ); if ( pos > 0 && ++firstWordCounts[target.left(pos)] >= maxWordOccurrence ) { removeFirstWord = target.left(pos); } if ( rxLastWord.indexIn(target) != -1 && ++lastWordCounts[rxLastWord.cap()] >= maxWordOccurrence ) { removeLastWord = rxLastWord.cap(); } // Check if route stop names are available if ( info->contains(Enums::RouteStops) ) { QStringList stops = info->value( Enums::RouteStops ).toStringList(); QString target = info->value( Enums::Target ).toString(); // TODO Break if 70% or at least three of the route stop names // begin/end with the same word // int minCount = qMax( 3, int(stops.count() * 0.7) ); foreach ( const QString &stop, stops ) { // Test first word pos = stop.indexOf( ' ' ); const QString newFirstWord = stop.left( pos ); if ( pos > 0 && ++firstWordCounts[newFirstWord] >= maxWordOccurrence ) { removeFirstWord = newFirstWord; break; } // Test last word if ( rxLastWord.indexIn(stop) != -1 && ++lastWordCounts[rxLastWord.cap()] >= maxWordOccurrence ) { removeLastWord = rxLastWord.cap(); break; } } } } infoList->append( info ); } // Remove word with most occurrences from beginning/end of stop names if ( features.testFlag(AutoRemoveCityFromStopNames) ) { if ( removeFirstWord.isEmpty() && removeLastWord.isEmpty() ) { // If no first/last word with at least maxWordOccurrence occurrences was found, // find the word with the most occurrences int max = 0; // Find word at the beginning with most occurrences for ( QHash< QString, int >::ConstIterator it = firstWordCounts.constBegin(); it != firstWordCounts.constEnd(); ++it ) { if ( it.value() > max ) { max = it.value(); removeFirstWord = it.key(); } } // Find word at the end with more occurrences for ( QHash< QString, int >::ConstIterator it = lastWordCounts.constBegin(); it != lastWordCounts.constEnd(); ++it ) { if ( it.value() > max ) { max = it.value(); removeLastWord = it.key(); } } if ( max < minWordOccurrence ) { // The first/last word with the most occurrences has too few occurrences // Do not remove any word removeFirstWord.clear(); removeLastWord.clear(); } else if ( !removeLastWord.isEmpty() ) { // removeLastWord has more occurrences than removeFirstWord removeFirstWord.clear(); } } if ( !removeFirstWord.isEmpty() ) { // Remove removeFirstWord from all stop names for ( int i = 0; i < infoList->count(); ++i ) { QSharedPointer info = infoList->at( i ); QString target = info->value( Enums::Target ).toString(); if ( target.startsWith(removeFirstWord) ) { target = target.mid( removeFirstWord.length() + 1 ); info->insert( Enums::TargetShortened, target ); } QStringList stops = info->value( Enums::RouteStops ).toStringList(); for ( int i = 0; i < stops.count(); ++i ) { if ( stops[i].startsWith(removeFirstWord) ) { stops[i] = stops[i].mid( removeFirstWord.length() + 1 ); } } info->insert( Enums::RouteStopsShortened, stops ); } } else if ( !removeLastWord.isEmpty() ) { // Remove removeLastWord from all stop names for ( int i = 0; i < infoList->count(); ++i ) { QSharedPointer info = infoList->at( i ); QString target = info->value( Enums::Target ).toString(); if ( target.endsWith(removeLastWord) ) { target = target.left( target.length() - removeLastWord.length() ); info->insert( Enums::TargetShortened, target ); } QStringList stops = info->value( Enums::RouteStops ).toStringList(); for ( int i = 0; i < stops.count(); ++i ) { if ( stops[i].endsWith(removeLastWord) ) { stops[i] = stops[i].left( stops[i].length() - removeLastWord.length() ); } } info->insert( Enums::RouteStopsShortened, stops ); } } } } QString Helper::decodeHtmlEntities( const QString& html ) { return Global::decodeHtmlEntities( html ); } QString Helper::encodeHtmlEntities( const QString &html ) { return Global::encodeHtmlEntities( html ); } QString Helper::decodeHtml( const QByteArray &document, const QByteArray &fallbackCharset ) { return Global::decodeHtml( document, fallbackCharset ); } QString Helper::decode( const QByteArray &document, const QByteArray &charset ) { return Global::decode( document, charset ); } Helper::Helper( const QString &serviceProviderId, QObject *parent ) : QObject(parent), m_mutex(new QMutex()), m_serviceProviderId(serviceProviderId), m_errorMessageRepetition(0) { } Helper::~Helper() { emitRepeatedMessageWarning(); delete m_mutex; } void Helper::emitRepeatedMessageWarning() { QMutexLocker locker( m_mutex ); if ( m_errorMessageRepetition > 0 ) { kDebug() << "(Last error message repeated" << m_errorMessageRepetition << "times)"; m_errorMessageRepetition = 0; emit messageReceived( i18nc("@info/plain", "Last error message repeated %1 times", m_errorMessageRepetition), QScriptContextInfo() ); } } void Helper::messageReceived( const QString &message, const QString &failedParseText, ErrorSeverity severity ) { m_mutex->lock(); if ( message == m_lastErrorMessage ) { ++m_errorMessageRepetition; m_mutex->unlock(); return; } m_lastErrorMessage = message; QScriptContextInfo info( context()->parentContext() ); const QString serviceProviderId = m_serviceProviderId; m_mutex->unlock(); emitRepeatedMessageWarning(); emit messageReceived( message, info, failedParseText, severity ); // Output debug message and a maximum count of 200 characters of the text where the parsing failed QString shortParseText = failedParseText.trimmed().left(350); int diff = failedParseText.length() - shortParseText.length(); if ( diff > 0 ) { shortParseText.append(QString("... <%1 more chars>").arg(diff)); } shortParseText = shortParseText.replace('\n', "\n "); // Indent #ifdef ENABLE_DEBUG_SCRIPT_ERROR m_mutex->lock(); const QString name = severity == Information ? "Information" : (severity == Warning ? "Warning" : "Fatal error"); DEBUG_SCRIPT_ERROR( QString("%1 in %2-script, function %3(), file %4, line %5") .arg(name) .arg(m_serviceProviderId) .arg(info.functionName().isEmpty() ? "[anonymous]" : info.functionName()) .arg(QFileInfo(info.fileName()).fileName()) .arg(info.lineNumber()) ); m_mutex->unlock(); DEBUG_SCRIPT_ERROR( message ); if ( !shortParseText.isEmpty() ) { DEBUG_SCRIPT_ERROR( QString("The text of the document where parsing failed is: \"%1\"") .arg(shortParseText) ); } #endif // Log the complete message to the log file. QString logFileName = KGlobal::dirs()->saveLocation( "data", "plasma_engine_publictransport" ); logFileName.append( "serviceproviders.log" ); if ( !logFileName.isEmpty() ) { QFile logFile(logFileName); if ( logFile.size() > 1024 * 512 ) { // == 0.5 MB if ( !logFile.remove() ) { kDebug() << "Error: Couldn't delete old log file."; } else { kDebug() << "Deleted old log file, because it was getting too big."; } } if ( !logFile.open(QIODevice::Append | QIODevice::Text) ) { kDebug() << "Couldn't open the log file in append mode" << logFileName << logFile.errorString(); return; } - logFile.write( QString("%1 (%2, in function %3(), file %4, line %5):\n \"%6\"\n Failed while reading this text: \"%7\"\n-------------------------------------\n\n") + logFile.write( QString("%1 (%2, in function %3(), file %4, line %5):\n \"%6\"\n Failed while reading this text: +\"%7\"\n-------------------------------------\n\n") .arg(serviceProviderId) .arg(QDateTime::currentDateTime().toString()) .arg(info.functionName().isEmpty() ? "[anonymous]" : info.functionName()) .arg(QFileInfo(info.fileName()).fileName()) .arg(info.lineNumber()) .arg(message) .arg(failedParseText.trimmed()).toUtf8() ); logFile.close(); } } void ResultObject::addData( const QVariantMap &item ) { m_mutex->lockInline(); TimetableData data; for ( QVariantMap::ConstIterator it = item.constBegin(); it != item.constEnd(); ++it ) { bool ok; Enums::TimetableInformation info = static_cast< Enums::TimetableInformation >( it.key().toInt(&ok) ); if ( !ok || info == Enums::Nothing ) { info = Global::timetableInformationFromString( it.key() ); } const QVariant value = it.value(); if ( info == Enums::Nothing ) { - kWarning() << "Invalid property name" << it.key() << "with value" << value; + qWarning() << "Invalid property name" << it.key() << "with value" << value; QString message; if ( it.key() == QLatin1String("length") && value.canConvert(QVariant::Int) && item.count() == value.toInt() + 1 ) // +1 for the "length" property { // Seems like a list was given and autoconverted to QVariantMap in this way message = i18nc("@info/plain", "Invalid property name \"%1\" " "with value \"%2\", seems like a list was passed to " "result.addData() instead of an object with properties.", it.key(), value.toString()); context()->throwError( message ); } else { message = i18nc("@info/plain", "Invalid property name \"%1\" with value \"%2\"", it.key(), value.toString()); } const int count = m_timetableData.count(); m_mutex->unlockInline(); emit invalidDataReceived( info, message, context()->parentContext(), count, item ); m_mutex->lockInline(); continue; } else if ( value.isNull() ) { // Null value received, simply leave the data empty continue; } else if ( !value.isValid() ) { - kWarning() << "Value for" << info << "is invalid or null" << value; + qWarning() << "Value for" << info << "is invalid or null" << value; const QString message = i18nc("@info/plain", "Invalid value received for \"%1\"", it.key()); const int count = m_timetableData.count(); m_mutex->unlockInline(); emit invalidDataReceived( info, message, context()->parentContext(), count, item ); m_mutex->lockInline(); continue; } else if ( info == Enums::TypeOfVehicle && static_cast(value.toInt()) == Enums::InvalidVehicleType && Global::vehicleTypeFromString(value.toString()) == Enums::InvalidVehicleType ) { - kWarning() << "Invalid type of vehicle value" << value; + qWarning() << "Invalid type of vehicle value" << value; const QString message = i18nc("@info/plain", "Invalid type of vehicle received: \"%1\"", value.toString()); const int count = m_timetableData.count(); m_mutex->unlockInline(); emit invalidDataReceived( info, message, context()->parentContext(), count, item ); m_mutex->lockInline(); } else if ( info == Enums::TypesOfVehicleInJourney || info == Enums::RouteTypesOfVehicles ) { const QVariantList types = value.toList(); foreach ( const QVariant &type, types ) { if ( static_cast(type.toInt()) == Enums::InvalidVehicleType && Global::vehicleTypeFromString(type.toString()) == Enums::InvalidVehicleType ) { kDebug() << "Invalid type of vehicle value in" << Global::timetableInformationToString(info) << value; const QString message = i18nc("@info/plain", "Invalid type of vehicle received in \"%1\": \"%2\"", Global::timetableInformationToString(info), type.toString()); const int count = m_timetableData.count(); m_mutex->unlockInline(); emit invalidDataReceived( info, message, context()->parentContext(), count, item ); m_mutex->lockInline(); } } } else if ( info == Enums::JourneyNewsUrl ) { QString url = value.toString(); if ( url.startsWith('/') ) { // Prepend provider URL to relative URLs - kWarning() << "Prepending provider URL to relative JourneyNewsUrls is not implemented"; + qWarning() << "Prepending provider URL to relative JourneyNewsUrls is not implemented"; // url.prepend( m_ ); TODO } } else if ( info == Enums::JourneyNewsOther ) { // DEPRECATED - kWarning() << "JourneyNewsOther is deprecated, use JourneyNews instead"; + qWarning() << "JourneyNewsOther is deprecated, use JourneyNews instead"; info = Enums::JourneyNews; } if ( m_features.testFlag(AutoDecodeHtmlEntities) ) { if ( value.canConvert(QVariant::String) && (info == Enums::StopName || info == Enums::Target || info == Enums::StartStopName || info == Enums::TargetStopName || info == Enums::Operator || info == Enums::TransportLine || info == Enums::Platform || info == Enums::DelayReason || info == Enums::Status || info == Enums::Pricing) ) { // Decode HTML entities in string values data[ info ] = Global::decodeHtmlEntities( value.toString() ).trimmed(); } else if ( value.canConvert(QVariant::StringList) && (info == Enums::RouteStops || info == Enums::RoutePlatformsDeparture || info == Enums::RoutePlatformsArrival) ) { // Decode HTML entities in string list values QStringList stops = value.toStringList(); for ( QStringList::Iterator it = stops.begin(); it != stops.end(); ++it ) { *it = Helper::trim( Global::decodeHtmlEntities(*it) ); } data[ info ] = stops; } else { // Other values don't need decoding data[ info ] = value; } } else { data[ info ] = value; } } m_timetableData << data; if ( m_features.testFlag(AutoPublish) && m_timetableData.count() == 10 ) { // Publish the first 10 data items automatically m_mutex->unlockInline(); emit publish(); } else { m_mutex->unlockInline(); } } QString Helper::trim( const QString& str ) { return QString(str).trimmed() .replace( QRegExp("^( )+|( )+$", Qt::CaseInsensitive), QString() ) .trimmed(); } QString Helper::simplify( const QString &str ) { return QString(str).replace( QRegExp("( )+", Qt::CaseInsensitive), QString() ) .simplified(); } QString Helper::stripTags( const QString& str ) { const QString attributePattern = "\\w+(?:\\s*=\\s*(?:\"[^\"]*\"|'[^']*'|[^\"'>\\s]+))?"; QRegExp rx( QString("<\\/?\\w+(?:\\s+%1)*(?:\\s*/)?>").arg(attributePattern) ); rx.setMinimal( true ); return QString( str ).remove( rx ); } QString Helper::camelCase( const QString& str ) { QString ret = str.toLower(); QRegExp rx( "(^\\w)|\\W(\\w)" ); int pos = 0; while ( (pos = rx.indexIn(ret, pos)) != -1 ) { if ( rx.pos(2) == -1 || rx.pos(2) >= ret.length() ) { ret[ rx.pos(1) ] = ret[ rx.pos(1) ].toUpper(); } else { ret[ rx.pos(2) ] = ret[ rx.pos(2) ].toUpper(); } pos += rx.matchedLength(); } return ret; } QString Helper::extractBlock( const QString& str, const QString& beginString, const QString& endString ) { int pos = str.indexOf( beginString ); if ( pos == -1 ) { return ""; } int end = str.indexOf( endString, pos + 1 ); return str.mid( pos, end - pos ); } QVariantMap Helper::matchTime( const QString& str, const QString& format ) { QString pattern = QRegExp::escape( format ); pattern = pattern.replace( "hh", "\\d{2}" ) .replace( "h", "\\d{1,2}" ) .replace( "mm", "\\d{2}" ) .replace( "m", "\\d{1,2}" ) .replace( "AP", "(AM|PM)" ) .replace( "ap", "(am|pm)" ); QVariantMap ret; QRegExp rx( pattern ); if ( rx.indexIn(str) != -1 ) { QTime time = QTime::fromString( rx.cap(), format ); ret.insert( "hour", time.hour() ); ret.insert( "minute", time.minute() ); } else if ( format != "hh:mm" ) { // Try default format if the one specified doesn't work QRegExp rx2( "\\d{1,2}:\\d{2}" ); if ( rx2.indexIn(str) != -1 ) { QTime time = QTime::fromString( rx2.cap(), "hh:mm" ); ret.insert( "hour", time.hour() ); ret.insert( "minute", time.minute() ); } else { ret.insert( "error", true ); DEBUG_SCRIPT_HELPER("Couldn't match time in" << str << pattern); } } else { ret.insert( "error", true ); DEBUG_SCRIPT_HELPER("Couldn't match time in" << str << pattern); } return ret; } QDate Helper::matchDate( const QString& str, const QString& format ) { QString pattern = QRegExp::escape( format ).replace( "d", "D" ); pattern = pattern.replace( "DD", "\\d{2}" ) .replace( "D", "\\d{1,2}" ) .replace( "MM", "\\d{2}" ) .replace( "M", "\\d{1,2}" ) .replace( "yyyy", "\\d{4}" ) .replace( "yy", "\\d{2}" ); QRegExp rx( pattern ); QDate date; if ( rx.indexIn(str) != -1 ) { date = QDate::fromString( rx.cap(), format ); } else if ( format != "yyyy-MM-dd" ) { // Try default format if the one specified doesn't work QRegExp rx2( "\\d{2,4}-\\d{2}-\\d{2}" ); if ( rx2.indexIn(str) != -1 ) { date = QDate::fromString( rx2.cap(), "yyyy-MM-dd" ); } } if ( !date.isValid() ) { DEBUG_SCRIPT_HELPER("Couldn't match date in" << str << pattern); } // Adjust date, needed for formats with only two "yy" for year matching // A year 12 means 2012, not 1912 if ( date.year() < 1970 ) { date.setDate( date.year() + 100, date.month(), date.day() ); } return date; } QString Helper::formatTime( int hour, int minute, const QString& format ) { return QTime( hour, minute ).toString( format ); } QString Helper::formatDate( int year, int month, int day, const QString& format ) { return QDate( year, month, day ).toString( format ); } QString Helper::formatDateTime( const QDateTime& dateTime, const QString& format ) { return dateTime.toString( format ); } int Helper::duration( const QString& sTime1, const QString& sTime2, const QString& format ) { QTime time1 = QTime::fromString( sTime1, format ); QTime time2 = QTime::fromString( sTime2, format ); if ( !time1.isValid() || !time2.isValid() ) { return -1; } return time1.secsTo( time2 ) / 60; } QString Helper::addMinsToTime( const QString& sTime, int minsToAdd, const QString& format ) { QTime time = QTime::fromString( sTime, format ); if ( !time.isValid() ) { DEBUG_SCRIPT_HELPER("Couldn't parse the given time" << sTime << format); return ""; } return time.addSecs( minsToAdd * 60 ).toString( format ); } QString Helper::addDaysToDate( const QString& sDate, int daysToAdd, const QString& format ) { QDate date = QDate::fromString( sDate, format ).addDays( daysToAdd ); if ( !date.isValid() ) { DEBUG_SCRIPT_HELPER("Couldn't parse the given date" << sDate << format); return sDate; } return date.toString( format ); } QDateTime Helper::addDaysToDate( const QDateTime& dateTime, int daysToAdd ) { return dateTime.addDays( daysToAdd ); } QStringList Helper::splitSkipEmptyParts( const QString& str, const QString& sep ) { return str.split( sep, QString::SkipEmptyParts ); } QVariantMap Helper::findFirstHtmlTag( const QString &str, const QString &tagName, const QVariantMap &options ) { // Set/overwrite maxCount option to match only the first tag using findHtmlTags() QVariantMap _options = options; _options[ "maxCount" ] = 1; QVariantList tags = findHtmlTags( str, tagName, _options ); // Copy values of first matched tag (if any) to the result object QVariantMap result; result.insert( "found", !tags.isEmpty() ); if ( !tags.isEmpty() ) { const QVariantMap firstTag = tags.first().toMap(); result.insert( "contents", firstTag["contents"] ); result.insert( "position", firstTag["position"] ); result.insert( "endPosition", firstTag["endPosition"] ); result.insert( "attributes", firstTag["attributes"] ); result.insert( "name", firstTag["name"] ); } return result; } QVariantList Helper::findHtmlTags( const QString &str, const QString &tagName, const QVariantMap &options ) { const QVariantMap &attributes = options[ "attributes" ].toMap(); const int maxCount = options.value( "maxCount", 0 ).toInt(); const bool noContent = options.value( "noContent", false ).toBool(); const bool noNesting = options.value( "noNesting", false ).toBool(); const bool debug = options.value( "debug", false ).toBool(); const QString contentsRegExpPattern = options.value( "contentsRegExp", QString() ).toString(); const QVariantMap namePosition = options[ "namePosition" ].toMap(); int position = options.value( "position", 0 ).toInt(); const bool namePositionIsAttribute = namePosition["type"].toString().toLower().compare( QLatin1String("attribute"), Qt::CaseInsensitive ) == 0; const QString namePositionRegExpPattern = namePosition.contains("regexp") ? namePosition["regexp"].toString() : QString(); // Create regular expression that matches HTML elements with or without attributes. // Since QRegExp offers no way to retreive multiple matches of the same capture group // the whole attribute string gets matched here and then analyzed in another loop // using attributeRegExp. // Matching the attributes with all details here is required to prevent eg. having a match // end after a ">" character in a string in an attribute. const QString attributePattern = "\\w+(?:\\s*=\\s*(?:\"[^\"]*\"|'[^']*'|[^\"'>\\s]+))?"; QRegExp htmlTagRegExp( noContent ? QString("<%1((?:\\s+%2)*)(?:\\s*/)?>").arg(tagName).arg(attributePattern) : QString("<%1((?:\\s+%2)*)>").arg(tagName).arg(attributePattern), // TODO TEST does this need a "\\s*" before the ">"? // : QString("<%1((?:\\s+%2)*)>%3").arg(tagName).arg(attributePattern) // .arg(contentsRegExpPattern), Qt::CaseInsensitive ); QRegExp htmlCloseTagRegExp( QString("").arg(tagName), Qt::CaseInsensitive ); QRegExp contentsRegExp( contentsRegExpPattern, Qt::CaseInsensitive ); htmlTagRegExp.setMinimal( true ); // Match attributes with or without value, with single/double/not quoted value QRegExp attributeRegExp( "(\\w+)(?:\\s*=\\s*(?:\"([^\"]*)\"|'([^']*)'|([^\"'>\\s]+)))?", Qt::CaseInsensitive ); QVariantList foundTags; while ( (foundTags.count() < maxCount || maxCount <= 0) && (position = htmlTagRegExp.indexIn(str, position)) != -1 ) { if ( debug ) { kDebug() << "Test match at" << position << htmlTagRegExp.cap().left(500); } const QString attributeString = htmlTagRegExp.cap( 1 ); QString tagContents; // = noContent ? QString() : htmlTagRegExp.cap( 2 ); QVariantMap foundAttributes; int attributePos = 0; while ( (attributePos = attributeRegExp.indexIn(attributeString, attributePos)) != -1 ) { const int valueCap = attributeRegExp.cap(2).isEmpty() ? (attributeRegExp.cap(3).isEmpty() ? 4 : 3) : 2; foundAttributes.insert( attributeRegExp.cap(1), attributeRegExp.cap(valueCap) ); attributePos += attributeRegExp.matchedLength(); } if ( debug ) { kDebug() << "Found attributes" << foundAttributes << "in" << attributeString; } // Test if the attributes match bool attributesMatch = true; for ( QVariantMap::ConstIterator it = attributes.constBegin(); it != attributes.constEnd(); ++it ) { if ( !foundAttributes.contains(it.key()) ) { // Did not find exact attribute name, try to use it as regular expression pattern attributesMatch = false; QRegExp attributeNameRegExp( it.key(), Qt::CaseInsensitive ); foreach ( const QString &attributeName, foundAttributes.keys() ) { if ( attributeNameRegExp.indexIn(attributeName) != -1 ) { // Matched the attribute name attributesMatch = true; break; } } if ( !attributesMatch ) { if ( debug ) { kDebug() << "Did not find attribute" << it.key(); } break; } } // Attribute exists, test it's value const QString value = foundAttributes[ it.key() ].toString(); const QString valueRegExpPattern = it.value().toString(); if ( !(value.isEmpty() && valueRegExpPattern.isEmpty()) ) { QRegExp valueRegExp( valueRegExpPattern, Qt::CaseInsensitive ); if ( valueRegExp.indexIn(value) == -1 ) { // Attribute value regexp did not matched attributesMatch = false; if ( debug ) { kDebug() << "Value" << value << "did not match pattern" << valueRegExpPattern; } break; } else if ( valueRegExp.captureCount() > 0 ) { // Attribute value regexp matched, store captures foundAttributes[ it.key() ] = valueRegExp.capturedTexts(); } } } // Search for new opening HTML tags (with same tag name) before the closing HTML tag int endPosition = htmlTagRegExp.pos() + htmlTagRegExp.matchedLength(); if ( !attributesMatch ) { position = endPosition; continue; } if ( !noContent ) { if ( noNesting ) { // "noNesting" option set, simply search for next closing tag, no matter if it is // a nested tag or not const int posClosing = htmlCloseTagRegExp.indexIn( str, endPosition ); const int contentsBegin = htmlTagRegExp.pos() + htmlTagRegExp.matchedLength(); tagContents = str.mid( contentsBegin, posClosing - contentsBegin ); endPosition = htmlCloseTagRegExp.pos() + htmlCloseTagRegExp.matchedLength(); } else { // Find next closing tag, skipping nested tags. // Get string after the opening HTML tag const QString rest = str.mid( htmlTagRegExp.pos() + htmlTagRegExp.matchedLength() ); int posClosing = htmlCloseTagRegExp.indexIn( rest ); if ( posClosing == -1 ) { position = htmlTagRegExp.pos() + htmlTagRegExp.matchedLength(); if ( debug ) { kDebug() << "Closing tag" << tagName << "could not be found"; } position = endPosition; continue; } // Search for nested opening tags in between the main opening tag and the // next closing tag int posOpening = htmlTagRegExp.indexIn( rest.left(posClosing) ); while ( posOpening != -1 ) { // Found a nested tag, find the next closing tag posClosing = htmlCloseTagRegExp.indexIn( rest, posClosing + htmlCloseTagRegExp.matchedLength() ); if ( posClosing == -1 ) { position = htmlTagRegExp.pos() + htmlTagRegExp.matchedLength(); if ( debug ) { kDebug() << "Closing tag" << tagName << "could not be found"; } break; } // Search for more nested opening tags posOpening = htmlTagRegExp.indexIn( rest.left(posClosing), posOpening + htmlTagRegExp.matchedLength() ); } tagContents = rest.left( posClosing ); endPosition += htmlCloseTagRegExp.pos() + htmlCloseTagRegExp.matchedLength(); } } // Match contents, only use regular expression if one was given in the options argument if ( !contentsRegExpPattern.isEmpty() ) { if ( contentsRegExp.indexIn(tagContents) == -1 ) { if ( debug ) { kDebug() << "Did not match tag contents" << tagContents.left(500); } position = endPosition; continue; } else { // Use first matched group as contents string, if any // Otherwise use the whole match as contents string tagContents = contentsRegExp.cap( contentsRegExp.captureCount() <= 1 ? 0 : 1 ); } } else { // No regexp pattern for contents, use complete contents, but trimmed tagContents = tagContents.trimmed(); } // Construct a result object QVariantMap result; result.insert( "contents", tagContents ); result.insert( "position", position ); result.insert( "endPosition", endPosition ); result.insert( "attributes", foundAttributes ); // Find name if a "namePosition" option is given if ( !namePosition.isEmpty() ) { const QString name = getTagName( result, namePosition["type"].toString(), namePositionRegExpPattern, namePositionIsAttribute ? namePosition["name"].toString() : QString() ); result.insert( "name", name ); } if ( debug ) { kDebug() << "Found HTML tag" << tagName << "at" << position << foundAttributes; } foundTags << result; position = endPosition; } if ( debug ) { if ( foundTags.isEmpty() ) { kDebug() << "Found no" << tagName << "HTML tags in HTML" << str; } else { kDebug() << "Found" << foundTags.count() << tagName << "HTML tags"; } } return foundTags; } QString Helper::getTagName( const QVariantMap &searchResult, const QString &type, const QString ®Exp, const QString attributeName ) { const bool namePositionIsAttribute = type.toLower().compare( QLatin1String("attribute"), Qt::CaseInsensitive ) == 0; QString name = trim( namePositionIsAttribute ? searchResult["attributes"].toMap()[ attributeName ].toString() : searchResult["contents"].toString() ); if ( !regExp.isEmpty() ) { // Use "regexp" property of namePosition to match the header name QRegExp namePositionRegExp( regExp, Qt::CaseInsensitive ); if ( namePositionRegExp.indexIn(name) != -1 ) { name = namePositionRegExp.cap( qMin(1, namePositionRegExp.captureCount()) ); } } return name; } QVariantMap Helper::findNamedHtmlTags( const QString &str, const QString &tagName, const QVariantMap &options ) { QVariantMap namePosition; if ( !options.contains("namePosition") ) { namePosition[ "type" ] = "contents"; // Can be "attribute", "contents" } else { namePosition = options[ "namePosition" ].toMap(); } const bool namePositionIsAttribute = namePosition["type"].toString().toLower().compare( QLatin1String("attribute"), Qt::CaseInsensitive ) == 0; const QString namePositionRegExpPattern = namePosition.contains("regexp") ? namePosition["regexp"].toString() : QString(); const QString ambiguousNameResolution = options.contains("ambiguousNameResolution") ? options["ambiguousNameResolution"].toString().toLower() : "replace"; const bool debug = options.value( "debug", false ).toBool(); const QVariantList foundTags = findHtmlTags( str, tagName, options ); QVariantMap foundTagsMap; foreach ( const QVariant &foundTag, foundTags ) { QString name = getTagName( foundTag.toMap(), namePosition["type"].toString(), namePositionRegExpPattern, namePositionIsAttribute ? namePosition["name"].toString() : QString() ); if ( name.isEmpty() ) { if ( debug ) { kDebug() << "Empty name in" << str; } continue; } // Check if the newly found name was already found // and decide what to do based on the "ambiguousNameResolution" option if ( ambiguousNameResolution == QLatin1String("addnumber") && foundTagsMap.contains(name) ) { QRegExp rx( "(\\d+)$" ); if ( rx.indexIn(name) != -1 ) { name += QString::number( rx.cap(1).toInt() + 1 ); } else { name += "2"; } } foundTagsMap[ name ] = foundTag; // TODO Use lists here? The same name could be found multiply times } // Store list of names in the "names" property, therefore "names" should not be a found tag name if ( !foundTagsMap.contains("names") ) { foundTagsMap[ "names" ] = QVariant::fromValue( foundTagsMap.keys() ); } else if ( debug ) { kDebug() << "A tag with the name 'names' was found. Normally a property 'names' gets " "added to the object returned by this functionm, which lists all found " "names in a list."; } return foundTagsMap; } const char* Storage::LIFETIME_ENTRYNAME_SUFFIX = "__expires__"; class StoragePrivate { public: StoragePrivate( const QString &serviceProvider ) : readWriteLock(new QReadWriteLock(QReadWriteLock::Recursive)), readWriteLockPersistent(new QReadWriteLock(QReadWriteLock::Recursive)), serviceProvider(serviceProvider), lastLifetimeCheck(0), config(0) { }; ~StoragePrivate() { delete readWriteLock; delete readWriteLockPersistent; delete config; }; void readPersistentData() { // Delete already read config object if ( config ) { delete config; } config = new KConfig( ServiceProviderGlobal::cacheFileName(), KConfig::SimpleConfig ); }; KConfigGroup persistentGroup() { if ( !config ) { readPersistentData(); } return config->group( serviceProvider ).group( QLatin1String("storage") ); }; quint16 checkLength( const QByteArray &data ) { if ( data.length() > 65535 ) { kDebug() << "Data is too long, only 65535 bytes are supported" << data.length(); } return static_cast( data.length() ); }; QReadWriteLock *readWriteLock; QReadWriteLock *readWriteLockPersistent; QVariantMap data; const QString serviceProvider; uint lastLifetimeCheck; // as time_t KConfig *config; KConfigGroup lastPersistentGroup; }; Storage::Storage( const QString &serviceProviderId, QObject *parent ) : QObject(parent), d(new StoragePrivate(serviceProviderId)) { // Delete persistently stored data which lifetime has expired checkLifetime(); } Storage::~Storage() { delete d; } void Storage::write( const QVariantMap& data ) { for ( QVariantMap::ConstIterator it = data.constBegin(); it != data.constEnd(); ++it ) { write( it.key(), it.value() ); } } void Storage::write( const QString& name, const QVariant& data ) { QWriteLocker locker( d->readWriteLock ); d->data.insert( name, data ); } QVariantMap Storage::read() { QReadLocker locker( d->readWriteLock ); return d->data; } QVariant Storage::read( const QString& name, const QVariant& defaultData ) { QReadLocker locker( d->readWriteLock ); return d->data.contains(name) ? d->data[name] : defaultData; } void Storage::remove( const QString& name ) { QWriteLocker locker( d->readWriteLock ); d->data.remove( name ); } void Storage::clear() { QWriteLocker locker( d->readWriteLock ); d->data.clear(); } int Storage::lifetime( const QString& name ) { QReadLocker locker( d->readWriteLockPersistent ); return lifetime( name, d->persistentGroup() ); } int Storage::lifetime( const QString& name, const KConfigGroup& group ) { QReadLocker locker( d->readWriteLockPersistent ); return lifetimeNoLock( name, group ); } int Storage::lifetimeNoLock( const QString &name, const KConfigGroup &group ) { const uint lifetimeTime_t = group.readEntry( name + LIFETIME_ENTRYNAME_SUFFIX, 0 ); return QDateTime::currentDateTime().daysTo( QDateTime::fromTime_t(lifetimeTime_t) ); } void Storage::checkLifetime() { QWriteLocker locker( d->readWriteLockPersistent ); if ( QDateTime::currentDateTime().toTime_t() - d->lastLifetimeCheck < MIN_LIFETIME_CHECK_INTERVAL * 60 ) { // Last lifetime check was less than 15 minutes ago return; } // Try to load script features from a cache file KConfigGroup group = d->persistentGroup(); QMap< QString, QString > data = group.entryMap(); for ( QMap< QString, QString >::ConstIterator it = data.constBegin(); it != data.constEnd(); ++it ) { if ( it.key().endsWith(LIFETIME_ENTRYNAME_SUFFIX) ) { // Do not check lifetime of entries which store the lifetime of the real data entries continue; } const int remainingLifetime = lifetimeNoLock( it.key(), group ); if ( remainingLifetime <= 0 ) { // Lifetime has expired kDebug() << "Lifetime of storage data" << it.key() << "for" << d->serviceProvider << "has expired" << remainingLifetime; removePersistent( it.key(), group ); } } d->lastLifetimeCheck = QDateTime::currentDateTime().toTime_t(); } bool Storage::hasData( const QString &name ) const { QReadLocker locker( d->readWriteLock ); return d->data.contains( name ); } bool Storage::hasPersistentData( const QString &name ) const { QReadLocker locker( d->readWriteLockPersistent ); KConfigGroup group = d->persistentGroup(); return group.hasKey( name ); } QByteArray Storage::encodeData( const QVariant &data ) const { // Store the type of the variant, because it is needed to read the QVariant with the correct // type using KConfigGroup::readEntry() const uchar type = static_cast( data.type() ); if ( type >= QVariant::LastCoreType ) { kDebug() << "Invalid data type, only QVariant core types are supported" << data.type(); return QByteArray(); } // Write type into the first byte QByteArray encodedData; encodedData[0] = type; // Write data if ( data.canConvert(QVariant::ByteArray) ) { encodedData += data.toByteArray(); } else if ( data.canConvert(QVariant::String) ) { encodedData += data.toString().toUtf8(); } else { switch ( data.type() ) { case QVariant::StringList: case QVariant::List: { // Lists are stored like this (one entry after the other): // "<2 Bytes: Value length>" const QVariantList list = data.toList(); foreach ( const QVariant &item, list ) { // Encode current list item QByteArray encodedItem = encodeData( item ); // Construct a QByteArray which contains the length in two bytes (0 .. 65535) const quint16 length = d->checkLength( encodedItem ); const QByteArray baLength( (const char*)&length, sizeof(length) ); // Use 2 bytes for the length of the data, append data encodedData += baLength; encodedData += encodedItem; } break; } case QVariant::Map: { // Maps are stored like this (one entry after the other): // "<2 Bytes: Key length><2 Bytes: Value length>" const QVariantMap map = data.toMap(); for ( QVariantMap::ConstIterator it = map.constBegin(); it != map.constEnd(); ++it ) { // Encode current key and value QByteArray encodedKey = it.key().toUtf8(); QByteArray encodedValue = encodeData( it.value() ); // Construct QByteArrays which contain the lengths in two bytes each (0 .. 65535) const quint16 lengthKey = d->checkLength( encodedKey ); const quint16 lengthValue = d->checkLength( encodedValue ); const QByteArray baLengthKey( (const char*)&lengthKey, sizeof(lengthKey) ); const QByteArray baLengthValue( (const char*)&lengthValue, sizeof(lengthValue) ); // Use 2 bytes for the length of the key, append key encodedData += baLengthKey; encodedData += encodedKey; // Use 2 bytes for the length of the value, append value encodedData += baLengthValue; encodedData += encodedValue; } break; } default: kDebug() << "Cannot convert from type" << data.type(); return QByteArray(); } } return encodedData; } QVariant Storage::decodeData( const QByteArray &data ) const { const QVariant::Type type = static_cast( data[0] ); if ( type >= QVariant::LastCoreType ) { kDebug() << "Invalid encoding for data" << data; return QVariant(); } const QByteArray encodedValue = data.mid( 1 ); QVariant value( type ); value.setValue( encodedValue ); if ( value.canConvert( type ) ) { value.convert( type ); return value; } else { switch ( type ) { case QVariant::Date: // QVariant::toString() uses Qt::ISODate to convert QDate to string return QDate::fromString( value.toString(), Qt::ISODate ); case QVariant::Time: return QTime::fromString( value.toString() ); case QVariant::DateTime: // QVariant::toString() uses Qt::ISODate to convert QDateTime to string return QDateTime::fromString( value.toString(), Qt::ISODate ); case QVariant::StringList: case QVariant::List: { // Lists are stored like this (one entry after the other): // "<2 Bytes: Value length>" QVariantList decoded; QByteArray encoded = value.toByteArray(); int pos = 0; while ( pos + 2 < encoded.length() ) { const quint16 length = *reinterpret_cast( encoded.mid(pos, 2).data() ); if ( pos + 2 + length > encoded.length() ) { kDebug() << "Invalid list data" << encoded; return QVariant(); } const QByteArray encodedValue = encoded.mid( pos + 2, length ); const QVariant decodedValue = decodeData( encodedValue ); decoded << decodedValue; pos += 2 + length; } return decoded; } case QVariant::Map: { // Maps are stored like this (one entry after the other): // "<2 Bytes: Key length><2 Bytes: Value length>" QVariantMap decoded; const QByteArray encoded = value.toByteArray(); int pos = 0; while ( pos + 4 < encoded.length() ) { // Decode two bytes to quint16, this is the key length const quint16 keyLength = *reinterpret_cast( encoded.mid(pos, 2).data() ); if ( pos + 4 + keyLength > encoded.length() ) { // + 4 => 2 Bytes for keyLength + 2 Bytes for valueLength kDebug() << "Invalid map data" << encoded; return QVariant(); } // Extract key, starting after the two bytes for the key length const QString key = encoded.mid( pos + 2, keyLength ); pos += 2 + keyLength; // Decode two bytes to quint16, this is the value length const quint16 valueLength = *reinterpret_cast( encoded.mid(pos, 2).data() ); if ( pos + 2 + valueLength > encoded.length() ) { kDebug() << "Invalid map data" << encoded; return QVariant(); } // Extract and decode value, starting after the two bytes for the value length const QByteArray encodedValue = encoded.mid( pos + 2, valueLength ); const QVariant decodedValue = decodeData( encodedValue ); pos += 2 + valueLength; // Insert decoded value into the result map decoded.insert( key, decodedValue ); } return decoded; } default: kDebug() << "Cannot convert to type" << type; return QVariant(); } } } void Storage::writePersistent( const QVariantMap& data, uint lifetime ) { QWriteLocker locker( d->readWriteLockPersistent ); for ( QVariantMap::ConstIterator it = data.constBegin(); it != data.constEnd(); ++it ) { writePersistent( it.key(), it.value(), lifetime ); } } void Storage::writePersistent( const QString& name, const QVariant& data, uint lifetime ) { if ( lifetime > MAX_LIFETIME ) { lifetime = MAX_LIFETIME; } // Try to load script features from a cache file QWriteLocker locker( d->readWriteLockPersistent ); KConfigGroup group = d->persistentGroup(); group.writeEntry( name + LIFETIME_ENTRYNAME_SUFFIX, QDateTime::currentDateTime().addDays(lifetime).toTime_t() ); group.writeEntry( name, encodeData(data) ); } QVariant Storage::readPersistent( const QString& name, const QVariant& defaultData ) { // Try to load script features from a cache file QWriteLocker locker( d->readWriteLockPersistent ); const QByteArray data = d->persistentGroup().readEntry( name, QByteArray() ); return data.isEmpty() ? defaultData : decodeData(data); } void Storage::removePersistent( const QString& name, KConfigGroup& group ) { QWriteLocker locker( d->readWriteLockPersistent ); group.deleteEntry( name + LIFETIME_ENTRYNAME_SUFFIX ); group.deleteEntry( name ); } void Storage::removePersistent( const QString& name ) { // Try to load script features from a cache file QWriteLocker locker( d->readWriteLockPersistent ); KConfigGroup group = d->persistentGroup(); removePersistent( name, group ); } void Storage::clearPersistent() { // Try to load script features from a cache file QWriteLocker locker( d->readWriteLockPersistent ); d->persistentGroup().deleteGroup(); } QString Network::lastUrl() const { QMutexLocker locker( m_mutex ); return m_lastUrl; } QString Network::lastUserUrl() const { QMutexLocker locker( m_mutex ); return m_lastUserUrl; } void Network::clear() { QMutexLocker locker( m_mutex ); m_lastUrl.clear(); m_lastUserUrl.clear(); } bool Network::lastDownloadAborted() const { QMutexLocker locker( m_mutex ); return m_lastDownloadAborted; } bool Network::hasRunningRequests() const { QMutexLocker locker( m_mutex ); if ( m_synchronousRequestCount > 0 ) { // There is a synchronous request running return true; } foreach ( const NetworkRequest::Ptr &request, m_requests ) { if ( request->isRunning() ) { // Found a running asynchronous request return true; } } // No running request found return false; } QList< NetworkRequest::Ptr > Network::runningRequests() const { QMutexLocker locker( m_mutex ); QList< NetworkRequest::Ptr > requests; foreach ( const NetworkRequest::Ptr &request, m_requests ) { if ( request->isRunning() ) { requests << request; } } return requests; } int Network::runningRequestCount() const { QMutexLocker locker( m_mutex ); return runningRequests().count() + m_synchronousRequestCount; } QByteArray Network::fallbackCharset() const { QMutexLocker locker( m_mutex ); return m_fallbackCharset; } QList< TimetableData > ResultObject::data() const { QMutexLocker locker( m_mutex ); return m_timetableData; } QVariant ResultObject::data( int index, Enums::TimetableInformation information ) const { QMutexLocker locker( m_mutex ); if ( index < 0 || index >= m_timetableData.count() ) { context()->throwError( QScriptContext::RangeError, "Index out of range" ); return QVariant(); } return m_timetableData[ index ][ information ]; } bool ResultObject::hasData() const { QMutexLocker locker( m_mutex ); return !m_timetableData.isEmpty(); } int ResultObject::count() const { QMutexLocker locker( m_mutex ); return m_timetableData.count(); } ResultObject::Features ResultObject::features() const { QMutexLocker locker( m_mutex ); return m_features; } ResultObject::Hints ResultObject::hints() const { QMutexLocker locker( m_mutex ); return m_hints; } void ResultObject::clear() { QMutexLocker locker( m_mutex ); m_timetableData.clear(); } QScriptValue constructStream( QScriptContext *context, QScriptEngine *engine ) { QScriptValue argument = context->argument(0); DataStreamPrototype *object; if ( argument.instanceOf(context->callee()) ) { object = new DataStreamPrototype( qscriptvalue_cast(argument) ); } else if ( argument.isQObject() && qscriptvalue_cast(argument) ) { object = new DataStreamPrototype( qscriptvalue_cast(argument) ); } else if ( argument.isVariant() ) { const QVariant variant = argument.toVariant(); object = new DataStreamPrototype( variant.toByteArray() ); } else { return engine->undefinedValue(); } return engine->newQObject( object, QScriptEngine::ScriptOwnership ); } QScriptValue dataStreamToScript( QScriptEngine *engine, const DataStreamPrototypePtr &stream ) { return engine->newQObject( const_cast(stream), QScriptEngine::QtOwnership, QScriptEngine::PreferExistingWrapperObject ); } void dataStreamFromScript( const QScriptValue &object, DataStreamPrototypePtr &stream ) { stream = qobject_cast< DataStreamPrototype* >( object.toQObject() ); } DataStreamPrototype::DataStreamPrototype( QObject *parent ) : QObject( parent ) { } DataStreamPrototype::DataStreamPrototype( const QByteArray &byteArray, QObject *parent ) : QObject( parent ) { QBuffer *buffer = new QBuffer( const_cast(&byteArray), this ); buffer->open( QIODevice::ReadOnly ); m_dataStream = QSharedPointer< QDataStream >( new QDataStream(buffer) ); } DataStreamPrototype::DataStreamPrototype( QIODevice *device, QObject *parent ) : QObject( parent ) { if ( !device->isOpen() ) { - kWarning() << "Device not opened"; + qWarning() << "Device not opened"; } m_dataStream = QSharedPointer< QDataStream >( new QDataStream(device) ); } DataStreamPrototype::DataStreamPrototype( DataStreamPrototype *other ) : QObject(), m_dataStream(other->stream()) { } QDataStream *DataStreamPrototype::thisDataStream() const { return m_dataStream.data(); } qint8 DataStreamPrototype::readInt8() { qint8 i; thisDataStream()->operator >>( i ); return i; } quint8 DataStreamPrototype::readUInt8() { quint8 i; thisDataStream()->operator >>( i ); return i; } quint16 DataStreamPrototype::readUInt16() { quint16 i; thisDataStream()->operator >>( i ); return i; } qint32 DataStreamPrototype::readInt32() { qint32 i; thisDataStream()->operator >>( i ); return i; } qint16 DataStreamPrototype::readInt16() { qint16 i; thisDataStream()->operator >>( i ); return i; } quint32 DataStreamPrototype::readUInt32() { quint32 i; thisDataStream()->operator >>( i ); return i; } QString DataStreamPrototype::readString() { QString string; char character; while ( thisDataStream()->device()->getChar(&character) && character != 0 ) { string.append( character ); } return string; } QByteArray DataStreamPrototype::readBytes( uint byteCount ) { char *chars = new char[ byteCount ]; const uint bytesRead = thisDataStream()->readRawData( chars, byteCount ); if ( bytesRead != byteCount ) { - kWarning() << "Did not read all requested bytes, read" << bytesRead << "of" << byteCount; + qWarning() << "Did not read all requested bytes, read" << bytesRead << "of" << byteCount; } QByteArray bytes( chars ); delete[] chars; return bytes; } QByteArray DataStreamPrototype::readBytesUntilZero() { QByteArray bytes; char character; while ( thisDataStream()->device()->getChar(&character) && character != 0 ) { bytes.append( character ); } return bytes; } QString NetworkRequest::url() const { QMutexLocker locker( m_mutex ); return m_url; } QString NetworkRequest::userUrl() const { QMutexLocker locker( m_mutex ); return m_userUrl; } bool NetworkRequest::isRunning() const { QMutexLocker locker( m_mutex ); return m_reply; } bool NetworkRequest::isFinished() const { QMutexLocker locker( m_mutex ); return m_isFinished; } bool NetworkRequest::isRedirected() const { QMutexLocker locker( m_mutex ); return m_redirectUrl.isValid(); } QUrl NetworkRequest::redirectedUrl() const { QMutexLocker locker( m_mutex ); return m_redirectUrl; } QString NetworkRequest::postData() const { QMutexLocker locker( m_mutex ); return m_postData; } quint64 NetworkRequest::uncompressedSize() const { QMutexLocker locker( m_mutex ); return m_uncompressedSize; } void NetworkRequest::setUserData( const QVariant &userData ) { QMutexLocker locker( m_mutex ); m_userData = userData; } QVariant NetworkRequest::userData() const { QMutexLocker locker( m_mutex ); return m_userData; } #include "scriptapi.moc" } // namespace ScriptApi diff --git a/engine/script/scriptobjects.cpp b/engine/script/scriptobjects.cpp index dfeda38..b555adc 100644 --- a/engine/script/scriptobjects.cpp +++ b/engine/script/scriptobjects.cpp @@ -1,209 +1,209 @@ /* * Copyright 2012 Friedrich Pülz * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as * published by the Free Software Foundation; either version 2 or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ // Header #include "scriptobjects.h" // Own includes #include "script_thread.h" // KDE includes #include #include // Qt includes #include #include #include ScriptObjects::ScriptObjects() : storage(0), network(0), result(0), helper(0) { } ScriptObjects::ScriptObjects( const ScriptObjects &other ) : storage(other.storage), network(other.network), result(other.result), helper(other.helper), lastError(other.lastError) { } ScriptData::ScriptData() { } ScriptData::ScriptData( const ScriptData &scriptData ) : provider(scriptData.provider), program(scriptData.program) { } ScriptData::ScriptData( const ServiceProviderData *data, const QSharedPointer< QScriptProgram > &scriptProgram ) : provider(data ? *data : ServiceProviderData()), program(scriptProgram) { } void ScriptObjects::clear() { storage = QSharedPointer< Storage >( 0 ); helper = QSharedPointer< Helper >( 0 ); network = QSharedPointer< Network >( 0 ); result = QSharedPointer< ResultObject >( 0 ); } void ScriptObjects::createObjects( const ServiceProviderData *data, const QSharedPointer< QScriptProgram > &scriptProgram ) { createObjects( ScriptData(data, scriptProgram) ); } void ScriptObjects::createObjects( const ScriptData &data ) { if ( !storage ) { storage = QSharedPointer< Storage >( new Storage(data.provider.id()) ); } if ( !network ) { network = QSharedPointer< Network >( new Network(data.provider.fallbackCharset()) ); } if ( !result ) { result = QSharedPointer< ResultObject >( new ResultObject() ); } if ( !helper ) { helper = QSharedPointer< Helper >( new Helper(data.provider.id()) ); } } ScriptData ScriptData::fromEngine( QScriptEngine *engine, const QSharedPointer< QScriptProgram > &scriptProgram ) { ServiceProviderData *data = qobject_cast< ServiceProviderData* >( engine->globalObject().property("provider").toQObject() ); return ScriptData( data, scriptProgram ); } ScriptObjects ScriptObjects::fromEngine( QScriptEngine *engine ) { ScriptObjects objects; objects.helper = QSharedPointer< Helper >( qobject_cast< Helper* >( engine->globalObject().property("helper").toQObject() ) ); objects.network = QSharedPointer< Network >( qobject_cast< Network* >( engine->globalObject().property("network").toQObject() ) ); objects.result = QSharedPointer< ResultObject >( qobject_cast< ResultObject* >( engine->globalObject().property("result").toQObject() ) ); objects.storage = QSharedPointer< Storage >( qobject_cast< Storage* >( engine->globalObject().property("storage").toQObject() ) ); return objects; } void ScriptObjects::moveToThread( QThread *thread ) { if ( helper ) { helper->moveToThread( thread ); } if ( network ) { network->moveToThread( thread ); } if ( result ) { result->moveToThread( thread ); } if ( storage ) { storage->moveToThread( thread ); } } QThread *ScriptObjects::currentThread() const { return helper ? helper->thread() : 0; } bool ScriptObjects::attachToEngine( QScriptEngine *engine, const ScriptData &data ) { if ( !isValid() ) { kDebug() << "Attaching invalid objects" << helper << network << result << storage; } else if ( !data.program ) { kDebug() << "Attaching invalid data"; } if ( engine->isEvaluating() ) { - kWarning() << "Cannot attach objects while evaluating"; + qWarning() << "Cannot attach objects while evaluating"; return false; } // Register classes for use in the script qScriptRegisterMetaType< DataStreamPrototypePtr >( engine, dataStreamToScript, dataStreamFromScript ); qScriptRegisterMetaType< NetworkRequestPtr >( engine, networkRequestToScript, networkRequestFromScript ); const QScriptValue::PropertyFlags flags = QScriptValue::ReadOnly | QScriptValue::Undeletable; // Add a 'provider' object, clone a new ServiceProviderData object // for the case that the ScriptData instance gets deleted engine->globalObject().setProperty( "provider", engine->newQObject(data.provider.clone(engine)), flags ); // Add an include() function QScriptValue includeFunction = engine->globalObject().property("include"); if ( !includeFunction.isValid() ) { includeFunction = engine->newFunction( include, 1 ); } if ( data.program ) { QVariantHash includeData; includeData[ data.program->fileName() ] = maxIncludeLine( data.program->sourceCode() ); includeFunction.setData( qScriptValueFromValue(engine, includeData) ); } engine->globalObject().setProperty( "include", includeFunction, flags ); QScriptValue streamConstructor = engine->newFunction( constructStream ); QScriptValue streamMeta = engine->newQMetaObject( &DataStreamPrototype::staticMetaObject, streamConstructor ); engine->globalObject().setProperty( "DataStream", streamMeta, flags ); // Make the objects available to the script engine->globalObject().setProperty( "helper", helper.isNull() ? engine->undefinedValue() : engine->newQObject(helper.data()), flags ); engine->globalObject().setProperty( "network", network.isNull() ? engine->undefinedValue() : engine->newQObject(network.data()), flags ); engine->globalObject().setProperty( "storage", storage.isNull() ? engine->undefinedValue() : engine->newQObject(storage.data()), flags ); engine->globalObject().setProperty( "result", result.isNull() ? engine->undefinedValue() : engine->newQObject(result.data()), flags ); engine->globalObject().setProperty( "enums", engine->newQMetaObject(&ResultObject::staticMetaObject), flags ); engine->globalObject().setProperty( "PublicTransport", engine->newQMetaObject(&Enums::staticMetaObject), flags ); if ( !engine->globalObject().property("DataStream").isValid() ) { DataStreamPrototype *dataStream = new DataStreamPrototype( engine ); QScriptValue stream = engine->newQObject( dataStream ); QScriptValue streamConstructor = engine->newFunction( constructStream ); engine->setDefaultPrototype( qMetaTypeId(), stream ); engine->globalObject().setProperty( "DataStream", streamConstructor, flags ); } // Import extensions (from XML file,