diff --git a/engine/gtfs/gtfsdatabase.cpp b/engine/gtfs/gtfsdatabase.cpp index da5cf48..82e24ca 100644 --- a/engine/gtfs/gtfsdatabase.cpp +++ b/engine/gtfs/gtfsdatabase.cpp @@ -1,374 +1,374 @@ /* * 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 "gtfsdatabase.h" #include #include #include #include #include #include #include #include #include #include QString GtfsDatabase::databasePath( const QString &providerName ) { - const QString dir = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + QLatin1Char('/') + "plasma_engine_publictransport/gtfs/"); + const QString dir = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + QLatin1Char('/') + "plasma_engine_publictransport/gtfs/"; return dir + providerName + ".sqlite"; } bool GtfsDatabase::initDatabase( const QString &providerName, QString *errorText ) { QSqlDatabase db = QSqlDatabase::database( providerName ); if ( !db.isValid() ) { db = QSqlDatabase::addDatabase( "QSQLITE", providerName ); if ( !db.isValid() ) { kDebug() << "Error adding a QSQLITE database" << db.lastError(); *errorText = "Error adding a QSQLITE database " + db.lastError().text(); return false; } db.setDatabaseName( databasePath(providerName) ); if ( !db.open() ) { kDebug() << "Error opening the database connection" << db.lastError(); *errorText = "Error opening the database connection " + db.lastError().text(); return false; } } return true; } bool GtfsDatabase::createDatabaseTables( QString *errorText, QSqlDatabase database ) { QSqlQuery query( database ); kDebug() << "Create tables"; // Create table for "agency.txt" TODO agency_id only referenced from routes => merge tables? query.prepare( "CREATE TABLE IF NOT EXISTS agency (" "agency_id INTEGER UNIQUE PRIMARY KEY, " // (optional for gtfs with a single agency) "agency_name VARCHAR(256) NOT NULL, " // (required) The name of the agency "agency_url VARCHAR(512) NOT NULL, " // (required) URL of the transit agency "agency_timezone VARCHAR(256), " // (required, if NULL, the default timezone from the accesor XML is used, from -tag) Timezone name, see http://en.wikipedia.org/wiki/List_of_tz_zones "agency_lang VARCHAR(2), " // (optional) A two-letter ISO 639-1 code for the primary language used by this transit agency "agency_phone VARCHAR(64)" // (optional) A single voice telephone number for the agency (can contain punctuation marks) // "agency_fare_url VARCHAR(512)" // (optional) URL of a website about fares of the transit agency (found in TriMet's GTFS data) ")" ); if( !query.exec() ) { kDebug() << "Error creating 'agency' table:" << query.lastError(); *errorText = "Error creating 'agency' table: " + query.lastError().text(); return false; } // Create table for "routes.txt" // Values for the "route_type" field: // 0 - Tram, Streetcar, Light rail. Any light rail or street level system within a metropolitan area. // 1 - Subway, Metro. Any underground rail system within a metropolitan area. // 2 - Rail. Used for intercity or long-distance travel. // 3 - Bus. Used for short- and long-distance bus routes. // 4 - Ferry. Used for short- and long-distance boat service. // 5 - Cable car. Used for street-level cable cars where the cable runs beneath the car. // 6 - Gondola, Suspended cable car. Typically used for aerial cable cars where the car is suspended from the cable. // 7 - Funicular. Any rail system designed for steep inclines. query.prepare( "CREATE TABLE IF NOT EXISTS routes (" "route_id INTEGER UNIQUE PRIMARY KEY NOT NULL, " // (required) "agency_id INTEGER, " // (optional) Defines an agency for the route "route_short_name VARCHAR(128), " // (required) The short name of a route (can be an empty (NULL in DB) string, then route_long_name is used) "route_long_name VARCHAR(256), " // (required) The long name of a route (can be an empty (NULL in DB) string, then route_short_name is used) "route_desc VARCHAR(256), " // (optional) Additional information "route_type INTEGER NOT NULL, " // (required) The type of transportation used on a route (see above) "route_url VARCHAR(512), " // (optional) URL of a web page about a particular route "route_color VARCHAR(6), " // (optional) The (background) color for a route as a six-character hexadecimal number, eg. 00FFFF, default is white "route_text_color VARCHAR(6), " // (optional) The text color for a route as a six-character hexadecimal number, eg. 00FFFF, default is black "FOREIGN KEY(agency_id) REFERENCES agency(agency_id)" ")" ); if( !query.exec() ) { kDebug() << "Error creating 'routes' table:" << query.lastError(); *errorText = "Error creating 'routes' table: " + query.lastError().text(); return false; } // Create table for "stops.txt" query.prepare( "CREATE TABLE IF NOT EXISTS stops (" "stop_id INTEGER UNIQUE PRIMARY KEY NOT NULL, " // (required) "stop_code VARCHAR(30), " // (optional) Makes stops uniquely identifyable by passengers "stop_name VARCHAR(256) NOT NULL, " // (required) The name of the stop "stop_desc VARCHAR(256), " // (optional) Additional information "stop_lat REAL NOT NULL, " // (required) The WGS 84 latitude of the stop "stop_lon REAL NOT NULL, " // (required) The WGS 84 longitude of the stop from -180 to 180 "zone_id INTEGER, " // (optional) The fare zone ID for a stop => fare_rules.txt "stop_url VARCHAR(512), " // (optional) URL of a web page about a particular stop "location_type TINYINT, " // (optional) "1": Station (with one or more stops), "0" or NULL: Stop "direction VARCHAR(30), " // (optional) "position VARCHAR(30), " // TODO "parent_station INTEGER, " // (optional) stop_id of a parent station (with location_type == 1) "min_fare_id INTEGER, " // TODO "max_fare_id INTEGER" ");" ); if( !query.exec() ) { kDebug() << "Error creating 'stops' table:" << query.lastError() << query.lastQuery(); *errorText = "Error creating 'stops' table: " + query.lastError().text(); return false; } query.prepare( "CREATE INDEX IF NOT EXISTS stops_stop_name_id ON stops(stop_id, stop_name);" ); if( !query.exec() ) { kDebug() << "Error creating index for 'stop_name' in 'stops' table:" << query.lastError() << query.lastQuery(); *errorText = "Error creating index for 'stop_name' in 'stops' table: " + query.lastError().text(); return false; } // Not used // // Create table for "shapes.txt" // query.prepare( "CREATE TABLE IF NOT EXISTS shapes (" // "shape_id INTEGER UNIQUE PRIMARY KEY NOT NULL, " // (required) // "shape_pt_lat REAL NOT NULL, " // (required) The WGS 84 latitude of a point in a shape // "shape_pt_lon REAL NOT NULL, " // (required) The WGS 84 longitude of a point in a shape from -180 to 180 // "shape_pt_sequence INTEGER NOT NULL, " // (required) Associates the latitude and longitude of a shape point with its sequence order along the shape // "shape_dist_traveled REAL" // (optional) If used, positions a shape point as a distance traveled along a shape from the first shape point // ")" ); // if( !query.exec() ) { // kDebug() << "Error creating 'shapes' table:" << query.lastError(); // return false; // } // Create table for "trips.txt" query.prepare( "CREATE TABLE IF NOT EXISTS trips (" "trip_id INTEGER UNIQUE PRIMARY KEY NOT NULL, " // (required) TODO trip_id only referenced from (small) frequencies and (big) stop_times => merge? "route_id INTEGER NOT NULL, " // (required) Uniquely identifies a route (routes.txt) "service_id INTEGER NOT NULL, " // (required) Uniquely identifies a set of dates when service is available for one or more routes (in "calendar" or "calendar_dates") "trip_headsign VARCHAR(256), " // (optional) The text that appears on a sign that identifies the trip's destination to passengers "trip_short_name VARCHAR(256), " // (optional) The text that appears in schedules and sign boards to identify the trip to passengers "direction_id TINYINT, " // (optional) A binary value to distinguish between bi-directional trips with the same route_id "block_id INTEGER, " // (optional) Identifies the block to which the trip belongs. A block consists of two or more sequential trips made using the same vehicle, where a passenger can transfer from one trip to the next just by staying in the vehicle. "shape_id INTEGER, " // (optional) Uniquely identifies a shape (shapes.txt) "FOREIGN KEY(route_id) REFERENCES routes(route_id), " "FOREIGN KEY(shape_id) REFERENCES shapes(shape_id)" ")" ); if( !query.exec() ) { kDebug() << "Error creating 'trips' table:" << query.lastError(); *errorText = "Error creating 'trips' table: " + query.lastError().text(); return false; } // Create table for "stop_times.txt" query.prepare( "CREATE TABLE IF NOT EXISTS stop_times (" "trip_id INTEGER NOT NULL, " // (required) Uniquely identifies a trip (trips.txt) "arrival_time INTEGER NOT NULL, " // (required) Specifies the arrival time at a specific stop for a specific trip on a route, HH:MM:SS or H:MM:SS, can be > 23:59:59 for times on the next day, eg. for trips that span with multiple dates "departure_time INTEGER NOT NULL, " // (required) Specifies the departure time from a specific stop for a specific trip on a route, HH:MM:SS or H:MM:SS, can be > 23:59:59 for times on the next day, eg. for trips that span with multiple dates "stop_id INTEGER NOT NULL, " // (required) Uniquely identifies a stop (with location_type == 0, if used) "stop_sequence INTEGER NOT NULL, " // (required) Identifies the order of the stops for a particular trip "stop_headsign VARCHAR(256), " // (optional) The text that appears on a sign that identifies the trip's destination to passengers. Used to override the default trip_headsign when the headsign changes between stops. "pickup_type TINYINT, " // (optional) Indicates whether passengers are picked up at a stop as part of the normal schedule or whether a pickup at the stop is not available, 0: Regularly scheduled pickup, 1: No pickup available, 2: Must phone agency to arrange pickup, 3: Must coordinate with driver to arrange pickup, default is 0 "drop_off_type TINYINT, " // (optional) Indicates whether passengers are dropped off at a stop as part of the normal schedule or whether a drop off at the stop is not available, 0: Regularly scheduled drop off, 1: No drop off available, 2: Must phone agency to arrange drop off, 3: Must coordinate with driver to arrange drop off, default is 0 "shape_dist_traveled TINYINT, " // (optional) If used, positions a stop as a distance from the first shape point (same unit as in shapes.txt) "FOREIGN KEY(trip_id) REFERENCES trips(trip_id), " "FOREIGN KEY(stop_id) REFERENCES stops(stop_id), " "PRIMARY KEY(stop_id, departure_time, trip_id)" // makes inserts slow.. ");" ); if( !query.exec() ) { kDebug() << "Error creating 'stop_times' table:" << query.lastError(); *errorText = "Error creating 'stop_times' table: " + query.lastError().text(); return false; } // Create an index to quickly access trip information sorted by stop_sequence, // eg. for route stop lists for departures query.prepare( "CREATE INDEX IF NOT EXISTS stop_times_trip ON stop_times(trip_id, stop_sequence, stop_id);" ); if( !query.exec() ) { kDebug() << "Error creating index for 'trip_id' in 'stop_times' table:" << query.lastError(); *errorText = "Error creating index for 'trip_id' in 'stop_times' table: " + query.lastError().text(); return false; } // Create table for "calendar.txt" (exceptions in "calendar_dates.txt") query.prepare( "CREATE TABLE IF NOT EXISTS calendar (" "service_id INTEGER UNIQUE PRIMARY KEY NOT NULL, " // (required) Uiquely identifies a set of dates when service is available for one or more routes "weekdays VARCHAR(7) NOT NULL, " // (required) Combines GTFS fields monday-sunday into a string of '1' (available at that weekday) and '0' (not available) "start_date VARCHAR(8) NOT NULL, " // (required) Contains the start date for the service, in yyyyMMdd format "end_date VARCHAR(8) NOT NULL" // (required) Contains the end date for the service, in yyyyMMdd format ")" ); if( !query.exec() ) { kDebug() << "Error creating 'calendar' table:" << query.lastError(); *errorText = "Error creating 'calendar' table: " + query.lastError().text(); return false; } // Create table for "calendar_dates.txt" query.prepare( "CREATE TABLE IF NOT EXISTS calendar_dates (" "service_id INTEGER NOT NULL, " // (required) Uiquely identifies a set of dates when a service exception is available for one or more routes, Each (service_id, date) pair can only appear once in "calendar_dates", if the a service_id value appears in both "calendar" and "calendar_dates", the information in "calendar_dates" modifies the service information specified in "calendar", referenced by "trips" "date VARCHAR(8) NOT NULL, " // (required) Specifies a particular date when service availability is different than the norm, in yyyyMMdd format "exception_type TINYINT NOT NULL, " // (required) Indicates whether service is available on the date specified in the date field (1: The service has been added for the date, 2: The service has been removed) "PRIMARY KEY(service_id, date)" ")" ); if( !query.exec() ) { kDebug() << "Error creating 'calendar_dates' table:" << query.lastError(); *errorText = "Error creating 'calendar_dates' table: " + query.lastError().text(); return false; } // Create table for "fare_attributes.txt" query.prepare( "CREATE TABLE IF NOT EXISTS fare_attributes (" "fare_id INTEGER UNIQUE PRIMARY KEY NOT NULL, " // (required) Uniquely identifies a fare class "price DECIMAL(5,2) NOT NULL, " // (required) The fare price, in the unit specified by currency_type "currency_type VARCHAR(3) NOT NULL, " // (required) Defines the currency used to pay the fare, ISO 4217 alphabetical currency code, see http://www.iso.org/iso/en/prods-services/popstds/currencycodeslist.html "payment_method TINYINT NOT NULL, " // (required) Indicates when the fare must be paid (0: paid on board, 1: must be paid before boarding) "transfers TINYINT, " // (required in fare_attributes.txt, but may be empty => use NULL here) Specifies the number of transfers permitted on this fare (0: no transfers permitted on this fare, 1: passenger may transfer once, 2: passenger may transfer twice, (empty): Unlimited transfers are permitted) "transfer_duration INTEGER" // (optional) Specifies the length of time in seconds before a transfer expires ")" ); if( !query.exec() ) { kDebug() << "Error creating 'fare_attributes' table:" << query.lastError(); *errorText = "Error creating 'fare_attributes' table: " + query.lastError().text(); return false; } // Create table for "fare_rules.txt" query.prepare( "CREATE TABLE IF NOT EXISTS fare_rules (" "fare_id INTEGER NOT NULL, " // (required) Uniquely identifies a fare class "route_id INTEGER, " // (optional) Associates the fare ID with a route "origin_id INTEGER, " // (optional) Associates the fare ID with an origin zone ID "destination_id INTEGER, " // (optional) Associates the fare ID with a destination zone ID "contains_id INTEGER, " // (optional) Associates the fare ID with a zone ID (intermediate zone) "FOREIGN KEY(fare_id) REFERENCES fare_attributes(fare_id), " "FOREIGN KEY(route_id) REFERENCES routes(route_id), " "FOREIGN KEY(origin_id) REFERENCES stops(zone_id), " "FOREIGN KEY(destination_id) REFERENCES stops(zone_id), " "FOREIGN KEY(contains_id) REFERENCES stops(zone_id)" ")" ); if( !query.exec() ) { kDebug() << "Error creating 'fare_rules' table:" << query.lastError(); *errorText = "Error creating 'fare_rules' table: " + query.lastError().text(); return false; } // Create table for "frequencies.txt" query.prepare( "CREATE TABLE IF NOT EXISTS frequencies (" "trip_id INTEGER PRIMARY KEY NOT NULL, " // (required) Identifies a trip on which the specified frequency of service applies "start_time INTEGER NOT NULL, " // (required) Specifies the time at which service begins with the specified frequency, HH:MM:SS or H:MM:SS, can be > 23:59:59 for times on the next day, eg. for trips that span with multiple dates "end_time INTEGER NOT NULL, " // (required) Indicates the time at which service changes to a different frequency (or ceases) at the first stop in the trip, HH:MM:SS or H:MM:SS, can be > 23:59:59 for times on the next day, eg. for trips that span with multiple dates "headway_secs INTEGER NOT NULL, " // (required) Indicates the time between departures from the same stop (headway) for this trip type, during the time interval specified by start_time and end_time, in seconds "FOREIGN KEY(trip_id) REFERENCES trips(trip_id)" ")" ); if( !query.exec() ) { kDebug() << "Error creating 'frequencies' table:" << query.lastError(); *errorText = "Error creating 'frequencies' table: " + query.lastError().text(); return false; } // Create table for "transfers.txt" query.prepare( "CREATE TABLE IF NOT EXISTS transfers (" "from_stop_id INTEGER NOT NULL, " // (required) Identifies a stop or station where a connection between routes begins "to_stop_id INTEGER NOT NULL, " // (required) Identifies a stop or station where a connection between routes ends "transfer_type INTEGER NOT NULL, " // (required) Specifies the type of connection for the specified (from_stop_id, to_stop_id) pair (0 or empty: This is a recommended transfer point between two routes, 1: This is a timed transfer point between two routes. The departing vehicle is expected to wait for the arriving one, with sufficient time for a passenger to transfer between routes, 2: This transfer requires a minimum amount of time between arrival and departure to ensure a connection. The time required to transfer is specified by min_transfer_time, 3: Transfers are not possible between routes at this location) "min_transfer_time INTEGER, " // (optional) When a connection between routes requires an amount of time between arrival and departure (transfer_type=2), the min_transfer_time field defines the amount of time that must be available in an itinerary to permit a transfer between routes at these stops. The min_transfer_time must be sufficient to permit a typical rider to move between the two stops, including buffer time to allow for schedule variance on each route, in seconds "FOREIGN KEY(from_stop_id) REFERENCES stops(stop_id), " "FOREIGN KEY(to_stop_id) REFERENCES stops(stop_id)" ")" ); if( !query.exec() ) { kDebug() << "Error creating 'transfers' table:" << query.lastError(); *errorText = "Error creating 'transfers' table: " + query.lastError().text(); return false; } return true; } QVariant GtfsDatabase::convertFieldValue( const QByteArray &fieldValue, FieldType type ) { if ( fieldValue.isEmpty() ) { return QVariant(); } switch ( type ) { case Integer: return fieldValue.toInt(); case Double: return fieldValue.toDouble(); case Date: case Url: return fieldValue; case HashId: return qHash( fieldValue ); // Use the hash to convert string IDs case SecondsSinceMidnight: { // May contain hour values >= 24 (for times the next day), which is no valid QTime // Convert valid time format 'h:mm:ss' to 'hh:mm:ss' const QByteArray timeString = fieldValue.length() == 7 ? '0' + fieldValue : fieldValue; return timeString.left(2).toInt() * 60 * 60 + timeString.mid(3, 2).toInt() * 60 + timeString.right(2).toInt(); } case Color: { const QString trimmed = fieldValue.trimmed(); return trimmed.isEmpty() ? Qt::transparent : QColor('#' + trimmed); } case String: default: // TODO Make camel case if everything is upper case? return QString::fromUtf8( fieldValue ); } } GtfsDatabase::FieldType GtfsDatabase::typeOfField( const QString &fieldName ) { if ( fieldName == QLatin1String("min_transfer_time") || fieldName == QLatin1String("transfer_type") || fieldName == QLatin1String("headway_secs") || fieldName == QLatin1String("transfer_duration") || fieldName == QLatin1String("transfers") || fieldName == QLatin1String("payment_method") || fieldName == QLatin1String("exception_type") || fieldName == QLatin1String("shape_dist_traveled") || fieldName == QLatin1String("drop_off_type") || fieldName == QLatin1String("pickup_type") || fieldName == QLatin1String("stop_sequence") || fieldName == QLatin1String("shape_pt_sequence") || fieldName == QLatin1String("parent_station") || fieldName == QLatin1String("location_type") || fieldName == QLatin1String("route_type") ) { return Integer; } else if ( fieldName.endsWith("_id") ) { return HashId; } else if ( fieldName == QLatin1String("start_time") || fieldName == QLatin1String("end_time") || fieldName == QLatin1String("arrival_time") || fieldName == QLatin1String("departure_time") ) { return SecondsSinceMidnight; // A time stored as INTEGER } else if ( fieldName == QLatin1String("date") || fieldName == QLatin1String("startDate") || fieldName == QLatin1String("endDate") ) { return Date; } else if ( fieldName.endsWith(QLatin1String("_lat")) || fieldName.endsWith(QLatin1String("_lon")) || fieldName == QLatin1String("price") ) { return Double; } else if ( fieldName.endsWith(QLatin1String("_url")) ) { return Url; } else if ( fieldName.endsWith(QLatin1String("_color")) ) { return Color; } else { return String; } } diff --git a/engine/gtfs/gtfsimporter.cpp b/engine/gtfs/gtfsimporter.cpp index eacb4a1..c306281 100644 --- a/engine/gtfs/gtfsimporter.cpp +++ b/engine/gtfs/gtfsimporter.cpp @@ -1,790 +1,791 @@ /* * 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 #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) ) { 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()) ); 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] != '"' ) { 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 ) { qWarning() << "Header contains" << expectedFieldCount << "fields, but a line was read " "with only" << fieldValues->count() << "field values. Using empty/default values:"; 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 f156819..6bbbbeb 100644 --- a/engine/gtfs/gtfsservice.cpp +++ b/engine/gtfs/gtfsservice.cpp @@ -1,676 +1,677 @@ /* * 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 #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 ) { 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()) ) { 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() ) { 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 { qWarning() << "Operation" << operation << "not supported"; return 0; } } diff --git a/engine/publictransportdataengine.cpp b/engine/publictransportdataengine.cpp index 610575c..813909f 100644 --- a/engine/publictransportdataengine.cpp +++ b/engine/publictransportdataengine.cpp @@ -1,2751 +1,2751 @@ /* * 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 - -#include -#include +#include +#include +#include +#include // Qt includes #include #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 = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + QLatin1Char('/') + installationSubDirectory ); + const QString saveDir = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + QLatin1Char('/') + 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 = QStandardPaths::locateAll(QStandardPaths::GenericDataLocation, 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") ) { 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() ) { 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() ) { 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 { 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: 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 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 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() { QVariantMap erroneousProvidersMap; const QLatin1String name = sourceTypeKeyword( ErroneousServiceProvidersSource ); foreach(QString key, m_erroneousProviders.keys()) erroneousProvidersMap[key] = m_erroneousProviders[key]; setData( name, erroneousProvidersMap ); 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 ) { 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") ); 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: 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() ) { 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() ) { 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 ) { 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 ) { 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 ) { 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 ) { 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 ) { 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 ) { qWarning() << "Bad value for 'longitude' in source name:" << parameterValue; } } else if ( parameterName == QLatin1String("latitude") ) { stopRequest->setLatitude( parameterValue.toFloat(&ok) ); if ( !ok ) { qWarning() << "Bad value for 'latitude' in source name:" << parameterValue; } } else if ( parameterName == QLatin1String("distance") ) { stopRequest->setDistance( parameterValue.toInt(&ok) ); if ( !ok ) { qWarning() << "Bad value for 'distance' in source name:" << parameterValue; } } else { qWarning() << "Unknown argument" << parameterName; } } else { 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 ) { 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()) ) { 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()) ) { 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 ) { qWarning() << "Internal error: Not a JourneyRequest object but parseMode is" << parseMode; return false; } if ( journeyRequest->stop().isEmpty() && journeyRequest->stopId().isEmpty() ) { qWarning() << "No stop ID or name for the origin stop in data source name" << name; return false; } if ( journeyRequest->targetStop().isEmpty() && journeyRequest->targetStopId().isEmpty() ) { 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) ) { 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 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 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) ) { 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 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 ) { 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) ) { qWarning() << "Data source already removed" << nonAmbiguousName; return; } TimetableDataSource *dataSource = dynamic_cast< TimetableDataSource* >( m_dataSources[nonAmbiguousName] ); if ( !dataSource ) { 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 { qWarning() << "Timetable item" << additionalDataRequest->itemNumber() << "not found in data source" << request->sourceName() << "additional data error discarded"; } } else { 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) ) { 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 ) { 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) ) { 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 ) { 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 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 ) { qWarning() << "Internal error: Invalid pointer to the data source stored"; return -1; } const QDateTime time = sourceUpdateTime( dataSource, updateFlags ); return qMax( -1, int( 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()) ) { 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") ) { 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: 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 1dbbf1d..1182b19 100644 --- a/engine/script/script_thread.cpp +++ b/engine/script/script_thread.cpp @@ -1,908 +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 - #include // Qt includes #include #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 = QStandardPaths::locate(QStandardPaths::GenericDataLocation, subDirectory + fileName ); // Check if the script was already included QStringList includedFiles = engine->globalObject().property( "includedFiles" ).toVariant().toStringList(); if ( includedFiles.contains(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 ) { 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() ) { 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/script_thread.h b/engine/script/script_thread.h index 19ce6af..8e14e52 100644 --- a/engine/script/script_thread.h +++ b/engine/script/script_thread.h @@ -1,351 +1,351 @@ /* * 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. */ /** @file * @brief This file contains a thread which executes service provider plugin scripts. * * @author Friedrich Pülz */ #ifndef SCRIPTTHREAD_HEADER #define SCRIPTTHREAD_HEADER // Own includes #include "enums.h" #include "scriptapi.h" #include "scriptobjects.h" #include "serviceproviderdata.h" // KDE includes -#include // Base class +#include // Qt includes #include // Base class #include class QMutex; class AbstractRequest; class DepartureRequest; class ArrivalRequest; class JourneyRequest; class StopSuggestionRequest; class StopsByGeoPositionRequest; class AdditionalDataRequest; class MoreItemsRequest; class ServiceProviderData; namespace ScriptApi { class Storage; class Network; class Helper; class ResultObject; } class QScriptProgram; class QScriptEngine; class QEventLoop; using namespace ScriptApi; /** @brief Stores information about a departure/arrival/journey/stop suggestion. */ typedef QHash TimetableData; typedef NetworkRequest* NetworkRequestPtr; QScriptValue networkRequestToScript( QScriptEngine *engine, const NetworkRequestPtr &request ); void networkRequestFromScript( const QScriptValue &object, NetworkRequestPtr &request ); bool importExtension( QScriptEngine *engine, const QString &extension ); /** * @brief Script function to include external script files. * * Calls to this function need to be the first statements in the global context of the script file, * otherwise an exception gets thrown. It expects one argument, the name of the file to be included, * without it's path. The file needs to be in the same directory as the main script. * If the file is already included this function does nothing. A list of included files gets stored * in the engine's global object, in the "includedFiles" property, as QStringList. * @see maxIncludeLine() **/ QScriptValue include( QScriptContext *context, QScriptEngine *engine ); /** @brief Get the maximum line number for valid include() calls in @p program. */ quint16 maxIncludeLine( const QString &program ); /** * @brief A QScriptEngineAgent that signals when a script finishes. * * After a function exit the agent waits a little bit and checks if the script is still executing * using QScriptEngineAgent::isEvaluating(). **/ class ScriptAgent : public QObject, public QScriptEngineAgent { Q_OBJECT public: /** @brief Creates a new ScriptAgent instance. */ ScriptAgent( QScriptEngine* engine = 0, QObject *parent = 0 ); /** Overwritten to get noticed when a script might have finished. */ virtual void functionExit( qint64 scriptId, const QScriptValue& returnValue ); signals: /** @brief Emitted, when the script is no longer running */ void scriptFinished(); protected slots: void checkExecution(); }; /** @brief Implements the script function 'importExtension()'. */ bool importExtension( QScriptEngine *engine, const QString &extension ); /** * @brief Executes a script. **/ class ScriptJob : public ThreadWeaver::Job { Q_OBJECT public: /** * @brief Creates a new ScriptJob. * * @param script The script to executes. * @param data Information about the service provider. * @param scriptStorage The shared Storage object. **/ explicit ScriptJob( const ScriptData &data, const QSharedPointer< Storage > &scriptStorage, QObject* parent = 0 ); /** @brief Destructor. */ virtual ~ScriptJob(); /** @brief Abort the job. */ virtual void requestAbort(); /** @brief Overwritten from ThreadWeaver::Job to return whether or not the job was successful. */ virtual bool success() const; /** @brief Return the number of items which are already published. */ int publishedItems() const; /** @brief Return a string describing the error, if success() returns false. */ QString errorString() const; /** @brief Return the URL of the last finished request. */ QString lastDownloadUrl() const; /** @brief Return an URL for the last finished request that should be shown to users. */ QString lastUserUrl() const; /** @brief Get the data source name associated with this job. */ QString sourceName() const; /** @brief Return a copy of the object containing inforamtion about the request of this job. */ const AbstractRequest *cloneRequest() const; signals: /** @brief Signals ready TimetableData items. */ void departuresReady( const QList &departures, ResultObject::Features features, ResultObject::Hints hints, const QString &url, const GlobalTimetableInfo &globalInfo, const DepartureRequest &request, bool couldNeedForcedUpdate = false ); /** @brief Signals ready TimetableData items. */ void arrivalsReady( const QList &arrivals, ResultObject::Features features, ResultObject::Hints hints, const QString &url, const GlobalTimetableInfo &globalInfo, const ArrivalRequest &request, bool couldNeedForcedUpdate = false ); /** @brief Signals ready TimetableData items. */ void journeysReady( const QList &journeys, ResultObject::Features features, ResultObject::Hints hints, const QString &url, const GlobalTimetableInfo &globalInfo, const JourneyRequest &request, bool couldNeedForcedUpdate = false ); /** @brief Signals ready TimetableData items. */ void stopSuggestionsReady( const QList &stops, ResultObject::Features features, ResultObject::Hints hints, const QString &url, const GlobalTimetableInfo &globalInfo, const StopSuggestionRequest &request, bool couldNeedForcedUpdate = false ); /** @brief Signals ready additional data for a TimetableData item. */ void additionalDataReady( const TimetableData &data, ResultObject::Features features, ResultObject::Hints hints, const QString &url, const GlobalTimetableInfo &globalInfo, const AdditionalDataRequest &request, bool couldNeedForcedUpdate = false ); protected slots: /** @brief Handle the ResultObject::publish() signal by emitting dataReady(). */ void publish(); protected: /** @brief Perform the job. */ virtual void run(); /** @brief Return a pointer to the object containing information about the request of this job. */ virtual const AbstractRequest* request() const = 0; /** @brief Load @p script into the engine and insert some objects/functions. */ bool loadScript( const QSharedPointer< QScriptProgram > &script ); bool waitFor( QObject *sender, const char *signal, WaitForType type, int *timeout ); bool hasDataToBePublished() const; void handleError( const QString &errorMessage ); void cleanup(); QScriptEngine *m_engine; QMutex *m_mutex; ScriptData m_data; ScriptObjects m_objects; QEventLoop *m_eventLoop; int m_published; bool m_quit; bool m_success; QString m_errorString; QString m_lastUrl; QString m_lastUserUrl; }; class DepartureJobPrivate; class DepartureJob : public ScriptJob { Q_OBJECT public: explicit DepartureJob( const ScriptData &data, const QSharedPointer< Storage > &scriptStorage, const DepartureRequest& request, QObject* parent = 0); virtual ~DepartureJob(); protected: virtual const AbstractRequest *request() const; private: const DepartureJobPrivate *d; }; class ArrivalJobPrivate; class ArrivalJob : public ScriptJob { Q_OBJECT public: explicit ArrivalJob( const ScriptData &data, const QSharedPointer< Storage > &scriptStorage, const ArrivalRequest& request, QObject* parent = 0); virtual ~ArrivalJob(); protected: virtual const AbstractRequest* request() const; private: const ArrivalJobPrivate *d; }; class JourneyJobPrivate; class JourneyJob : public ScriptJob { Q_OBJECT public: explicit JourneyJob( const ScriptData &data, const QSharedPointer< Storage > &scriptStorage, const JourneyRequest& request, QObject* parent = 0); virtual ~JourneyJob(); protected: virtual const AbstractRequest* request() const; private: const JourneyJobPrivate *d; }; class StopSuggestionsJobPrivate; class StopSuggestionsJob : public ScriptJob { Q_OBJECT public: explicit StopSuggestionsJob( const ScriptData &data, const QSharedPointer< Storage > &scriptStorage, const StopSuggestionRequest& request, QObject* parent = 0); virtual ~StopSuggestionsJob(); protected: virtual const AbstractRequest* request() const; private: const StopSuggestionsJobPrivate *d; }; class StopsByGeoPositionJobPrivate; class StopsByGeoPositionJob : public ScriptJob { Q_OBJECT public: explicit StopsByGeoPositionJob( const ScriptData &data, const QSharedPointer< Storage > &scriptStorage, const StopsByGeoPositionRequest& request, QObject* parent = 0); virtual ~StopsByGeoPositionJob(); protected: virtual const AbstractRequest* request() const; private: const StopsByGeoPositionJobPrivate *d; }; class AdditionalDataJobPrivate; class AdditionalDataJob : public ScriptJob { Q_OBJECT public: explicit AdditionalDataJob( const ScriptData &data, const QSharedPointer< Storage > &scriptStorage, const AdditionalDataRequest& request, QObject* parent = 0); virtual ~AdditionalDataJob(); protected: virtual const AbstractRequest* request() const; private: const AdditionalDataJobPrivate *d; }; class MoreItemsJobPrivate; class MoreItemsJob : public ScriptJob { Q_OBJECT public: explicit MoreItemsJob( const ScriptData &data, const QSharedPointer< Storage > &scriptStorage, const MoreItemsRequest& request, QObject* parent = 0); virtual ~MoreItemsJob(); protected: virtual const AbstractRequest* request() const; private: const MoreItemsJobPrivate *d; }; #endif // Multiple inclusion guard diff --git a/engine/script/scriptapi.cpp b/engine/script/scriptapi.cpp index dee991f..7c2d392 100644 --- a/engine/script/scriptapi.cpp +++ b/engine/script/scriptapi.cpp @@ -1,2381 +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 // Qt includes #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include // Other includes #include #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->lock(); 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->unlock(); emit aborted( timedOut ); emit finished( QByteArray(), true, i18nc("@info/plain", "The request was aborted"), -1, 0, url, userData ); } void NetworkRequest::slotReadyRead() { m_mutex->lock(); if ( !m_reply ) { // Prevent crashes on exit m_mutex->unlock(); 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() ) { qWarning() << "Error downloading" << m_url << m_reply->errorString(); } m_mutex->unlock(); 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 ) { 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 { 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->lock(); if ( !m_reply ) { // Prevent crashes on exit m_mutex->unlock(); qWarning() << "Reply object already deleted, aborted?"; return; } if ( m_reply->attribute(QNetworkRequest::RedirectionTargetAttribute).isValid() ) { if ( m_redirectUrl.isValid() ) { 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->unlock(); 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() ) { 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() ) { 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->unlock(); emit finished( data, hasError, errorString, statusCode, size, url, userData ); } void NetworkRequest::started( QNetworkReply* reply, int timeout ) { m_mutex->lock(); if ( !m_network ) { qWarning() << "Can't decode, no m_network given..."; m_mutex->unlock(); 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->unlock(); 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() ) { 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->lock(); m_lastDownloadAborted = false; m_mutex->unlock(); 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->lock(); const QDateTime timestamp = QDateTime::currentDateTime(); m_requests.removeOne( sharedRequest ); m_finishedRequests << sharedRequest; m_mutex->unlock(); 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->lock(); QNetworkReply *reply = m_manager->get( *request->request() ); m_lastUrl = newUrl.toString(); m_mutex->unlock(); request->started( reply ); DEBUG_NETWORK("Redirected to" << newUrl); emit requestRedirected( sharedRequest, newUrl ); } void Network::slotRequestAborted() { m_mutex->lock(); if ( m_quit ) { m_mutex->unlock(); return; } NetworkRequest *request = qobject_cast< NetworkRequest* >( sender() ); NetworkRequest::Ptr sharedRequest = getSharedRequest( request ); if ( !sharedRequest ) { 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->unlock(); 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->lock(); QNetworkReply *reply = m_manager->get( *request->request() ); m_lastUrl = request->url(); m_lastUserUrl = request->userUrl(); m_mutex->unlock(); request->started( reply, timeout ); } void Network::head( NetworkRequest* request, int timeout ) { if ( !checkRequest(request) ) { return; } // Create a head request m_mutex->lock(); QNetworkReply *reply = m_manager->head( *request->request() ); m_lastUrl = request->url(); m_lastUserUrl = request->userUrl(); m_mutex->unlock(); request->started( reply, timeout ); } void Network::post( NetworkRequest* request, int timeout ) { if ( !checkRequest(request) ) { return; } // Create a head request m_mutex->lock(); QNetworkReply *reply = m_manager->post( *request->request(), request->postDataByteArray() ); m_lastUrl = request->url(); m_lastUserUrl = request->userUrl(); m_mutex->unlock(); 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->lock(); QNetworkReply *reply = m_manager->get( request ); ++m_synchronousRequestCount; m_lastUrl = url; m_lastUserUrl = userUrl.isEmpty() ? url : userUrl; m_lastDownloadAborted = false; m_mutex->unlock(); 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() ) { 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 = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + QLatin1Char('/') + "plasma_engine_publictransport" -); + QString logFileName = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + QLatin1Char('/') + "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->lock(); 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 ) { 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->unlock(); emit invalidDataReceived( info, message, context()->parentContext(), count, item ); m_mutex->lock(); continue; } else if ( value.isNull() ) { // Null value received, simply leave the data empty continue; } else if ( !value.isValid() ) { 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->unlock(); emit invalidDataReceived( info, message, context()->parentContext(), count, item ); m_mutex->lock(); continue; } else if ( info == Enums::TypeOfVehicle && static_cast(value.toInt()) == Enums::InvalidVehicleType && Global::vehicleTypeFromString(value.toString()) == Enums::InvalidVehicleType ) { 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->unlock(); emit invalidDataReceived( info, message, context()->parentContext(), count, item ); m_mutex->lock(); } 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->unlock(); emit invalidDataReceived( info, message, context()->parentContext(), count, item ); m_mutex->lock(); } } } else if ( info == Enums::JourneyNewsUrl ) { QString url = value.toString(); if ( url.startsWith('/') ) { // Prepend provider URL to relative URLs qWarning() << "Prepending provider URL to relative JourneyNewsUrls is not implemented"; // url.prepend( m_ ); TODO } } else if ( info == Enums::JourneyNewsOther ) { // DEPRECATED 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->unlock(); emit publish(); } else { m_mutex->unlock(); } } 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() ) { 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 ) { 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/serviceproviderscript.cpp b/engine/script/serviceproviderscript.cpp index 358a4fb..147373d 100644 --- a/engine/script/serviceproviderscript.cpp +++ b/engine/script/serviceproviderscript.cpp @@ -1,689 +1,689 @@ /* * 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 "serviceproviderscript.h" // Own includes #include "scriptapi.h" #include "script_thread.h" #include "serviceproviderglobal.h" #include "serviceproviderdata.h" #include "serviceprovidertestdata.h" #include "departureinfo.h" #include "request.h" // KDE includes -#include #include #include +#include #include -#include #include +#include // Qt includes -#include #include -#include -#include #include #include +#include +#include +#include #include -#include #include +#include #include const char *ServiceProviderScript::SCRIPT_FUNCTION_FEATURES = "features"; const char *ServiceProviderScript::SCRIPT_FUNCTION_GETTIMETABLE = "getTimetable"; const char *ServiceProviderScript::SCRIPT_FUNCTION_GETJOURNEYS = "getJourneys"; const char *ServiceProviderScript::SCRIPT_FUNCTION_GETSTOPSUGGESTIONS = "getStopSuggestions"; const char *ServiceProviderScript::SCRIPT_FUNCTION_GETADDITIONALDATA = "getAdditionalData"; ServiceProviderScript::ServiceProviderScript( const ServiceProviderData *data, QObject *parent, const QSharedPointer &cache ) : ServiceProvider(data, parent), m_scriptStorage(QSharedPointer(new Storage(data->id()))) { m_scriptState = WaitingForScriptUsage; m_scriptFeatures = readScriptFeatures( cache.isNull() ? ServiceProviderGlobal::cache() : cache ); qRegisterMetaType< QList >( "QList" ); qRegisterMetaType< TimetableData >( "TimetableData" ); qRegisterMetaType< QList >( "QList" ); qRegisterMetaType< GlobalTimetableInfo >( "GlobalTimetableInfo" ); qRegisterMetaType< ParseDocumentMode >( "ParseDocumentMode" ); qRegisterMetaType< NetworkRequest* >( "NetworkRequest*" ); qRegisterMetaType< NetworkRequest::Ptr >( "NetworkRequest::Ptr" ); qRegisterMetaType< QIODevice* >( "QIODevice*" ); qRegisterMetaType< DataStreamPrototype* >( "DataStreamPrototype*" ); qRegisterMetaType< ResultObject::Features >( "ResultObject::Features" ); // TEST, now done using Q_DECLARE_METATYPE? qRegisterMetaType< ResultObject::Hints >( "ResultObject::Hints" ); } ServiceProviderScript::~ServiceProviderScript() { abortAllRequests(); } void ServiceProviderScript::abortAllRequests() { // Abort all running jobs and wait for them to finish for proper cleanup foreach ( ScriptJob *job, m_runningJobs ) { kDebug() << "Abort job" << job; // Create an event loop to wait for the job to finish, // quit the loop when the done() signal gets emitted by the job QEventLoop loop; connect( job, SIGNAL(done(ThreadWeaver::Job*)), &loop, SLOT(quit()) ); // Disconnect all slots connected to the job and then abort it disconnect( job, 0, this, 0 ); job->requestAbort(); // Wait for the job to get aborted if ( !job->isFinished() ) { // The job is not finished, wait for it, maximally one second QTimer::singleShot( 1000, &loop, SLOT(quit()) ); loop.exec(); } // The job has finished or the timeout was reached if ( !job->isFinished() ) { // The job is still not finished, the timeout was reached before qWarning() << "Job not aborted before timeout, delete it" << job; } job->deleteLater(); } m_runningJobs.clear(); } QStringList ServiceProviderScript::allowedExtensions() { return QStringList() << "kross" << "qt" << "qt.core" << "qt.xml"; } bool ServiceProviderScript::lazyLoadScript() { // Read script QFile scriptFile( m_data->scriptFileName() ); if ( !scriptFile.open(QIODevice::ReadOnly) ) { kDebug() << "Script could not be opened for reading" << m_data->scriptFileName() << scriptFile.errorString(); return false; } const QByteArray ba = scriptFile.readAll(); scriptFile.close(); const QString scriptContents = QString::fromUtf8( ba ); // Initialize the script m_scriptData = ScriptData( m_data, QSharedPointer< QScriptProgram >( new QScriptProgram(scriptContents, m_data->scriptFileName())) ); return true; } bool ServiceProviderScript::runTests( QString *errorMessage ) const { if ( !QFile::exists(m_data->scriptFileName()) ) { if ( errorMessage ) { *errorMessage = i18nc("@info/plain", "Script file not found: %1", m_data->scriptFileName()); } return false; } QFile scriptFile( m_data->scriptFileName() ); if ( !scriptFile.open(QIODevice::ReadOnly) ) { if ( errorMessage ) { *errorMessage = i18nc("@info/plain", "Could not open script file: %1", m_data->scriptFileName()); } return false; } QTextStream stream( &scriptFile ); const QString program = stream.readAll(); scriptFile.close(); if ( program.isEmpty() ) { if ( errorMessage ) { *errorMessage = i18nc("@info/plain", "Script file is empty: %1", m_data->scriptFileName()); } return false; } const QScriptSyntaxCheckResult syntax = QScriptEngine::checkSyntax( program ); if ( syntax.state() != QScriptSyntaxCheckResult::Valid ) { if ( errorMessage ) { *errorMessage = i18nc("@info/plain", "Syntax error in script file, line %1: %2", syntax.errorLineNumber(), syntax.errorMessage().isEmpty() ? i18nc("@info/plain", "Syntax error") : syntax.errorMessage()); } return false; } // No errors found return true; } bool ServiceProviderScript::isTestResultUnchanged( const QString &providerId, const QSharedPointer< KConfig > &cache ) { const KConfigGroup providerGroup = cache->group( providerId ); if ( !providerGroup.hasGroup("script") ) { // Not a scripted provider or modified time not stored yet return true; } // Check if included files have been marked as modified since the cache was last updated const KConfigGroup providerScriptGroup = providerGroup.group( "script" ); const bool includesUpToDate = providerScriptGroup.readEntry( "includesUpToDate", false ); if ( !includesUpToDate ) { // An included file was modified return false; } // Check if the script file was modified since the cache was last updated const QDateTime scriptModifiedTime = providerScriptGroup.readEntry("modifiedTime", QDateTime()); const QString scriptFilePath = providerScriptGroup.readEntry( "scriptFileName", QString() ); const QFileInfo scriptFileInfo( scriptFilePath ); if ( scriptFileInfo.lastModified() != scriptModifiedTime ) { kDebug() << "Script was modified:" << scriptFileInfo.fileName(); return false; } // Check all included files and update "includesUpToDate" fields in using providers if ( checkIncludedFiles(cache, providerId) ) { // An included file of the provider was modified return false; } return true; } bool ServiceProviderScript::isTestResultUnchanged( const QSharedPointer &cache ) const { return isTestResultUnchanged( id(), cache ); } QList ServiceProviderScript::readScriptFeatures( const QSharedPointer &cache ) { // Check if the script file was modified since the cache was last updated KConfigGroup providerGroup = cache->group( m_data->id() ); if ( providerGroup.hasGroup("script") && isTestResultUnchanged(cache) && providerGroup.hasKey("features") ) { // Return feature list stored in the cache bool ok; QStringList featureStrings = providerGroup.readEntry("features", QStringList()); featureStrings.removeOne("(none)"); QList features = ServiceProviderGlobal::featuresFromFeatureStrings( featureStrings, &ok ); if ( ok ) { // The stored feature list only contains valid strings return features; } else { qWarning() << "Invalid feature string stored for provider" << m_data->id(); } } // No actual cached information about the service provider kDebug() << "No up-to-date cache information for service provider" << m_data->id(); QList features; QStringList includedFiles; bool ok = lazyLoadScript(); QString errorMessage; if ( !ok ) { errorMessage = i18nc("@info/plain", "Cannot open script file %1", m_data->scriptFileName()); } else { // Create script engine QScriptEngine engine; foreach ( const QString &import, m_data->scriptExtensions() ) { if ( !importExtension(&engine, import) ) { ok = false; errorMessage = i18nc("@info/plain", "Cannot import script extension %1", import); break; } } if ( ok ) { ScriptObjects objects; objects.createObjects( m_scriptData ); objects.attachToEngine( &engine, m_scriptData ); engine.evaluate( *m_scriptData.program ); QVariantList result; if ( !engine.hasUncaughtException() ) { result = engine.globalObject().property( SCRIPT_FUNCTION_FEATURES ).call().toVariant().toList(); } if ( engine.hasUncaughtException() ) { kDebug() << "Error in the script" << engine.uncaughtExceptionLineNumber() << engine.uncaughtException().toString(); kDebug() << "Backtrace:" << engine.uncaughtExceptionBacktrace().join("\n"); ok = false; errorMessage = i18nc("@info/plain", "Uncaught exception in script " "%1, line %2: %3", QFileInfo(QScriptContextInfo(engine.currentContext()).fileName()).fileName(), engine.uncaughtExceptionLineNumber(), engine.uncaughtException().toString()); } else { includedFiles = engine.globalObject().property( "includedFiles" ) .toVariant().toStringList(); // Test if specific functions exist in the script if ( engine.globalObject().property(SCRIPT_FUNCTION_GETSTOPSUGGESTIONS).isValid() ) { features << Enums::ProvidesStopSuggestions; } if ( engine.globalObject().property(SCRIPT_FUNCTION_GETJOURNEYS).isValid() ) { features << Enums::ProvidesJourneys; } if ( engine.globalObject().property(SCRIPT_FUNCTION_GETADDITIONALDATA).isValid() ) { features << Enums::ProvidesAdditionalData; } // Test if features() script function is available if ( !engine.globalObject().property(SCRIPT_FUNCTION_FEATURES).isValid() ) { kDebug() << "The script has no" << SCRIPT_FUNCTION_FEATURES << "function"; } else { // Use values returned by features() script functions // to get additional features of the service provider foreach ( const QVariant &value, result ) { features << static_cast( value.toInt() ); } } } } } // Update script modified time in cache KConfigGroup scriptGroup = providerGroup.group( "script" ); scriptGroup.writeEntry( "scriptFileName", m_data->scriptFileName() ); scriptGroup.writeEntry( "modifiedTime", QFileInfo(m_data->scriptFileName()).lastModified() ); // Remove provider from cached data for include file(s) no longer used by the provider KConfigGroup globalScriptGroup = cache->group( "script" ); const QStringList globalScriptGroupNames = globalScriptGroup.groupList(); foreach ( const QString &globalScriptGroupName, globalScriptGroupNames ) { if ( !globalScriptGroupName.startsWith(QLatin1String("include_")) ) { continue; } QString includedFile = globalScriptGroupName; includedFile.remove( 0, 8 ); // Remove "include_" from beginning const QFileInfo fileInfo( includedFile ); KConfigGroup includeFileGroup = globalScriptGroup.group( "include_" + fileInfo.filePath() ); QStringList usingProviders = includeFileGroup.readEntry( "usingProviders", QStringList() ); if ( usingProviders.contains(m_data->id()) && !includedFiles.contains(includedFile) ) { // This provider is marked as using the include file, but it no longer uses that file usingProviders.removeOne( m_data->id() ); includeFileGroup.writeEntry( "usingProviders", usingProviders ); } } // Check if included file(s) were modified foreach ( const QString &includedFile, includedFiles ) { // Add this provider to the list of providers using the current include file const QFileInfo fileInfo( includedFile ); KConfigGroup includeFileGroup = globalScriptGroup.group( "include_" + fileInfo.filePath() ); QStringList usingProviders = includeFileGroup.readEntry( "usingProviders", QStringList() ); if ( !usingProviders.contains(m_data->id()) ) { usingProviders << m_data->id(); includeFileGroup.writeEntry( "usingProviders", usingProviders ); } // Check if the include file was modified checkIncludedFile( cache, fileInfo ); } // Update modified times of included files scriptGroup.writeEntry( "includesUpToDate", true ); // Was just updated // Set error in default cache group if ( !ok ) { ServiceProviderTestData newTestData = ServiceProviderTestData::read( id(), cache ); newTestData.setSubTypeTestStatus( ServiceProviderTestData::Failed, errorMessage ); newTestData.write( id(), cache ); } return features; } bool ServiceProviderScript::checkIncludedFile( const QSharedPointer &cache, const QFileInfo &fileInfo, const QString &providerId ) { // Use a config group in the global script group for each included file. // It stores the last modified time and a list of IDs of providers using the include file KConfigGroup globalScriptGroup = cache->group( "script" ); KConfigGroup includeFileGroup = globalScriptGroup.group( "include_" + fileInfo.filePath() ); const QDateTime lastModified = includeFileGroup.readEntry( "modifiedTime", QDateTime() ); // Update "includesUpToDate" field of using providers, if the include file was modified if ( lastModified != fileInfo.lastModified() ) { // The include file was modified, update all using providers (later). // isTestResultUnchanged() returns false if "includesUpToDate" is false const QStringList usingProviders = includeFileGroup.readEntry( "usingProviders", QStringList() ); foreach ( const QString &usingProvider, usingProviders ) { if ( cache->hasGroup(usingProvider) ) { KConfigGroup usingProviderScriptGroup = cache->group( usingProvider ).group( "script" ); usingProviderScriptGroup.writeEntry( "includesUpToDate", false ); } } includeFileGroup.writeEntry( "modifiedTime", fileInfo.lastModified() ); return providerId.isEmpty() || usingProviders.contains(providerId); } else { return false; } } bool ServiceProviderScript::checkIncludedFiles( const QSharedPointer &cache, const QString &providerId ) { bool modified = false; KConfigGroup globalScriptGroup = cache->group( "script" ); const QStringList globalScriptGroups = globalScriptGroup.groupList(); foreach ( const QString &globalScriptGroup, globalScriptGroups ) { if ( !globalScriptGroup.startsWith(QLatin1String("include_")) ) { continue; } QString includedFile = globalScriptGroup; includedFile.remove( 0, 8 ); // Remove "include_" from beginning const QFileInfo fileInfo( includedFile ); if ( checkIncludedFile(cache, fileInfo, providerId) ) { // The include file was modified and is used by this provider modified = true; } } return modified; } QList ServiceProviderScript::features() const { return m_scriptFeatures; } void ServiceProviderScript::departuresReady( const QList &data, ResultObject::Features features, ResultObject::Hints hints, const QString &url, const GlobalTimetableInfo &globalInfo, const DepartureRequest &request, bool couldNeedForcedUpdate ) { // TODO use hints if ( data.isEmpty() ) { kDebug() << "The script didn't find any departures" << request.sourceName(); emit requestFailed( this, ErrorParsingFailed, i18n("Error while parsing the departure document."), url, &request ); } else { // Create PublicTransportInfo objects for new data and combine with already published data PublicTransportInfoList newResults; ResultObject::dataList( data, &newResults, request.parseMode(), m_data->defaultVehicleType(), &globalInfo, features, hints ); PublicTransportInfoList results = (m_publishedData[request.sourceName()] << newResults); DepartureInfoList departures; foreach( const PublicTransportInfoPtr &info, results ) { departures << info.dynamicCast(); } emit departuresReceived( this, url, departures, globalInfo, request ); if ( couldNeedForcedUpdate ) { emit forceUpdate(); } } } void ServiceProviderScript::arrivalsReady( const QList< TimetableData > &data, ResultObject::Features features, ResultObject::Hints hints, const QString &url, const GlobalTimetableInfo &globalInfo, const ArrivalRequest &request, bool couldNeedForcedUpdate ) { // TODO use hints if ( data.isEmpty() ) { kDebug() << "The script didn't find any arrivals" << request.sourceName(); emit requestFailed( this, ErrorParsingFailed, i18n("Error while parsing the arrival document."), url, &request ); } else { // Create PublicTransportInfo objects for new data and combine with already published data PublicTransportInfoList newResults; ResultObject::dataList( data, &newResults, request.parseMode(), m_data->defaultVehicleType(), &globalInfo, features, hints ); PublicTransportInfoList results = (m_publishedData[request.sourceName()] << newResults); ArrivalInfoList arrivals; foreach( const PublicTransportInfoPtr &info, results ) { arrivals << info.dynamicCast(); } emit arrivalsReceived( this, url, arrivals, globalInfo, request ); if ( couldNeedForcedUpdate ) { emit forceUpdate(); } } } void ServiceProviderScript::journeysReady( const QList &data, ResultObject::Features features, ResultObject::Hints hints, const QString &url, const GlobalTimetableInfo &globalInfo, const JourneyRequest &request, bool couldNeedForcedUpdate ) { Q_UNUSED( couldNeedForcedUpdate ); // TODO use hints if ( data.isEmpty() ) { kDebug() << "The script didn't find any journeys" << request.sourceName(); emit requestFailed( this, ErrorParsingFailed, i18n("Error while parsing the journey document."), url, &request ); } else { // Create PublicTransportInfo objects for new data and combine with already published data PublicTransportInfoList newResults; ResultObject::dataList( data, &newResults, request.parseMode(), m_data->defaultVehicleType(), &globalInfo, features, hints ); PublicTransportInfoList results = (m_publishedData[request.sourceName()] << newResults); JourneyInfoList journeys; foreach( const PublicTransportInfoPtr &info, results ) { journeys << info.dynamicCast(); } emit journeysReceived( this, url, journeys, globalInfo, request ); } } void ServiceProviderScript::stopSuggestionsReady( const QList &data, ResultObject::Features features, ResultObject::Hints hints, const QString &url, const GlobalTimetableInfo &globalInfo, const StopSuggestionRequest &request, bool couldNeedForcedUpdate ) { Q_UNUSED( couldNeedForcedUpdate ); // TODO use hints kDebug() << "Received" << data.count() << "items"; // Create PublicTransportInfo objects for new data and combine with already published data PublicTransportInfoList newResults; ResultObject::dataList( data, &newResults, request.parseMode(), m_data->defaultVehicleType(), &globalInfo, features, hints ); PublicTransportInfoList results( m_publishedData[request.sourceName()] << newResults ); kDebug() << "Results:" << results; StopInfoList stops; foreach( const PublicTransportInfoPtr &info, results ) { stops << info.dynamicCast(); } emit stopsReceived( this, url, stops, request ); } void ServiceProviderScript::additionalDataReady( const TimetableData &data, ResultObject::Features features, ResultObject::Hints hints, const QString &url, const GlobalTimetableInfo &globalInfo, const AdditionalDataRequest &request, bool couldNeedForcedUpdate ) { Q_UNUSED( features ); Q_UNUSED( hints ); Q_UNUSED( globalInfo ); Q_UNUSED( couldNeedForcedUpdate ); if ( data.isEmpty() ) { kDebug() << "The script didn't find any new data" << request.sourceName(); emit requestFailed( this, ErrorParsingFailed, i18nc("@info/plain", "No additional data found."), url, &request ); } else { emit additionalDataReceived( this, url, data, request ); } } void ServiceProviderScript::jobStarted( ThreadWeaver::Job* job ) { ScriptJob *scriptJob = qobject_cast< ScriptJob* >( job ); Q_ASSERT( scriptJob ); // Warn if there is published data for the request, // but not for additional data requests because they point to existing departure data sources. // There may be multiple AdditionalDataJob requests for the same data source but different // timetable items in the source. const QString sourceName = scriptJob->sourceName(); if ( !qobject_cast(scriptJob) && m_publishedData.contains(sourceName) && !m_publishedData[sourceName].isEmpty() ) { qWarning() << "Data source already exists for job" << scriptJob << sourceName; } } void ServiceProviderScript::jobDone( ThreadWeaver::Job* job ) { ScriptJob *scriptJob = qobject_cast< ScriptJob* >( job ); Q_ASSERT( scriptJob ); m_publishedData.remove( scriptJob->sourceName() ); m_runningJobs.removeOne( scriptJob ); scriptJob->deleteLater(); } void ServiceProviderScript::jobFailed( ThreadWeaver::Job* job ) { ScriptJob *scriptJob = qobject_cast< ScriptJob* >( job ); Q_ASSERT( scriptJob ); emit requestFailed( this, ErrorParsingFailed, scriptJob->errorString(), scriptJob->lastDownloadUrl(), scriptJob->cloneRequest() ); } void ServiceProviderScript::requestDepartures( const DepartureRequest &request ) { if ( lazyLoadScript() ) { DepartureJob *job = new DepartureJob( m_scriptData, m_scriptStorage, request, this ); connect( job, SIGNAL(departuresReady(QList,ResultObject::Features,ResultObject::Hints,QString,GlobalTimetableInfo,DepartureRequest,bool)), this, SLOT(departuresReady(QList,ResultObject::Features,ResultObject::Hints,QString,GlobalTimetableInfo,DepartureRequest,bool)) ); enqueue( job ); } } void ServiceProviderScript::requestArrivals( const ArrivalRequest &request ) { if ( lazyLoadScript() ) { ArrivalJob *job = new ArrivalJob( m_scriptData, m_scriptStorage, request, this ); connect( job, SIGNAL(arrivalsReady(QList,ResultObject::Features,ResultObject::Hints,QString,GlobalTimetableInfo,ArrivalRequest,bool)), this, SLOT(arrivalsReady(QList,ResultObject::Features,ResultObject::Hints,QString,GlobalTimetableInfo,ArrivalRequest,bool)) ); enqueue( job ); } } void ServiceProviderScript::requestJourneys( const JourneyRequest &request ) { if ( lazyLoadScript() ) { JourneyJob *job = new JourneyJob( m_scriptData, m_scriptStorage, request, this ); connect( job, SIGNAL(journeysReady(QList,ResultObject::Features,ResultObject::Hints,QString,GlobalTimetableInfo,JourneyRequest,bool)), this, SLOT(journeysReady(QList,ResultObject::Features,ResultObject::Hints,QString,GlobalTimetableInfo,JourneyRequest,bool)) ); enqueue( job ); } } void ServiceProviderScript::requestStopSuggestions( const StopSuggestionRequest &request ) { if ( lazyLoadScript() ) { StopSuggestionsJob *job = new StopSuggestionsJob( m_scriptData, m_scriptStorage, request, this ); connect( job, SIGNAL(stopSuggestionsReady(QList,ResultObject::Features,ResultObject::Hints,QString,GlobalTimetableInfo,StopSuggestionRequest,bool)), this, SLOT(stopSuggestionsReady(QList,ResultObject::Features,ResultObject::Hints,QString,GlobalTimetableInfo,StopSuggestionRequest,bool)) ); enqueue( job ); } } void ServiceProviderScript::requestStopsByGeoPosition( const StopsByGeoPositionRequest &request ) { if ( lazyLoadScript() ) { StopsByGeoPositionJob *job = new StopsByGeoPositionJob( m_scriptData, m_scriptStorage, request, this ); connect( job, SIGNAL(stopSuggestionsReady(QList,ResultObject::Features,ResultObject::Hints,QString,GlobalTimetableInfo,StopSuggestionRequest,bool)), this, SLOT(stopSuggestionsReady(QList,ResultObject::Features,ResultObject::Hints,QString,GlobalTimetableInfo,StopSuggestionRequest,bool)) ); enqueue( job ); } } void ServiceProviderScript::requestAdditionalData( const AdditionalDataRequest &request ) { if ( lazyLoadScript() ) { AdditionalDataJob *job = new AdditionalDataJob( m_scriptData, m_scriptStorage, request, this ); connect( job, SIGNAL(additionalDataReady(TimetableData,ResultObject::Features,ResultObject::Hints,QString,GlobalTimetableInfo,AdditionalDataRequest,bool)), this, SLOT(additionalDataReady(TimetableData,ResultObject::Features,ResultObject::Hints,QString,GlobalTimetableInfo,AdditionalDataRequest,bool)) ); enqueue( job ); } } void ServiceProviderScript::requestMoreItems( const MoreItemsRequest &moreItemsRequest ) { if ( lazyLoadScript() ) { // Create a MoreItemsJob and connect ready signals for more departures/arrivals/journeys MoreItemsJob *job = new MoreItemsJob( m_scriptData, m_scriptStorage, moreItemsRequest, this ); connect( job, SIGNAL(departuresReady(QList,ResultObject::Features,ResultObject::Hints,QString,GlobalTimetableInfo,DepartureRequest,bool)), this, SLOT(departuresReady(QList,ResultObject::Features,ResultObject::Hints,QString,GlobalTimetableInfo,DepartureRequest,bool)) ); connect( job, SIGNAL(arrivalsReady(QList,ResultObject::Features,ResultObject::Hints,QString,GlobalTimetableInfo,ArrivalRequest,bool)), this, SLOT(arrivalsReady(QList,ResultObject::Features,ResultObject::Hints,QString,GlobalTimetableInfo,ArrivalRequest,bool)) ); connect( job, SIGNAL(journeysReady(QList,ResultObject::Features,ResultObject::Hints,QString,GlobalTimetableInfo,JourneyRequest,bool)), this, SLOT(journeysReady(QList,ResultObject::Features,ResultObject::Hints,QString,GlobalTimetableInfo,JourneyRequest,bool)) ); enqueue( job ); } } void ServiceProviderScript::enqueue( ScriptJob *job ) { m_runningJobs << job; connect( job, SIGNAL(started(ThreadWeaver::Job*)), this, SLOT(jobStarted(ThreadWeaver::Job*)) ); connect( job, SIGNAL(done(ThreadWeaver::Job*)), this, SLOT(jobDone(ThreadWeaver::Job*)) ); connect( job, SIGNAL(failed(ThreadWeaver::Job*)), this, SLOT(jobFailed(ThreadWeaver::Job*)) ); ThreadWeaver::Weaver::instance()->enqueue( job ); } void ServiceProviderScript::import( const QString &import, QScriptEngine *engine ) { engine->importExtension( import ); } int ServiceProviderScript::minFetchWait( UpdateFlags updateFlags ) const { // If an update was requested manually wait minimally one minute, // otherwise wait minimally 15 minutes between automatic updates return qMax( updateFlags.testFlag(UpdateWasRequestedManually) ? 60 : 15 * 60, ServiceProvider::minFetchWait() ); } diff --git a/engine/serviceproviderdata.cpp b/engine/serviceproviderdata.cpp index 6614d0e..bc1bbbe 100644 --- a/engine/serviceproviderdata.cpp +++ b/engine/serviceproviderdata.cpp @@ -1,373 +1,374 @@ /* * 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 "serviceproviderdata.h" #include "serviceproviderglobal.h" // KDE includes #include #include #include +#include #include // Qt includes #include class ChangelogEntryGreaterThan { public: inline bool operator()( const ChangelogEntry& l, const ChangelogEntry& r ) const { int comparison = ServiceProviderData::compareVersions( l.version, r.version ); if ( comparison == 0 ) { // Versions are equal, compare authors return l.author.compare( r.author, Qt::CaseInsensitive ) < 0; } else { // If comparison is 1, the left version is bigger than the right one, // if it is -1, the right one is bigger return comparison > 0; } }; }; ServiceProviderData::ServiceProviderData( const Enums::ServiceProviderType& type, const QString& id, QObject *parent ) : QObject(parent) { m_serviceProviderType = type; m_id = id; m_version = "1.0"; // Initial version of new provider plugins m_fileFormatVersion = "1.1"; // Current version of the file structure of the .pts-file m_useSeparateCityValue = false; m_onlyUseCitiesInList = false; m_defaultVehicleType = Enums::UnknownVehicleType; m_minFetchWait = 0; m_sampleLongitude = m_sampleLatitude = 0.0; } ServiceProviderData::ServiceProviderData( const Enums::ServiceProviderType &type, const QString &id, const QHash< QString, QString > &names, const QHash< QString, QString >& descriptions, const QString &version, const QString &fileVersion, bool useSeparateCityValue, bool onlyUseCitiesInList, const QString &url, const QString &shortUrl, int minFetchWait, const QString &author, const QString &email, Enums::VehicleType defaultVehicleType, const QList< ChangelogEntry >& changelog, const QStringList &cities, const QHash< QString, QString >& cityNameToValueReplacementHash, QObject *parent ) : QObject(parent) { m_serviceProviderType = type; m_id = id; m_name = names; m_description = descriptions; m_version = version; m_fileFormatVersion = fileVersion; m_useSeparateCityValue = useSeparateCityValue; m_onlyUseCitiesInList = onlyUseCitiesInList; m_url = url; m_shortUrl = shortUrl; m_minFetchWait = minFetchWait; m_author = author; m_email = email; m_defaultVehicleType = defaultVehicleType; m_changelog = changelog; m_cities = cities; m_hashCityNameToValue = cityNameToValueReplacementHash; m_sampleLongitude = m_sampleLatitude = 0.0; } ServiceProviderData::ServiceProviderData( const ServiceProviderData &data, QObject *parent ) : QObject(parent) { // Use assignment operator for initialization operator=( data ); } ServiceProviderData::~ServiceProviderData() { } ServiceProviderData &ServiceProviderData::operator=( const ServiceProviderData &data ) { m_serviceProviderType = data.m_serviceProviderType; m_id = data.m_id; m_name = data.m_name; m_description = data.m_description; m_version = data.m_version; m_fileFormatVersion = data.m_fileFormatVersion; m_useSeparateCityValue = data.m_useSeparateCityValue; m_onlyUseCitiesInList = data.m_onlyUseCitiesInList; m_url = data.m_url; m_shortUrl = data.m_shortUrl; m_minFetchWait = data.m_minFetchWait; m_author = data.m_author; m_shortAuthor = data.m_shortAuthor; m_email = data.m_email; m_defaultVehicleType = data.m_defaultVehicleType; m_changelog = data.m_changelog; m_country = data.m_country; m_cities = data.m_cities; m_credit = data.m_credit; m_hashCityNameToValue = data.m_hashCityNameToValue; m_fileName = data.m_fileName; m_charsetForUrlEncoding = data.m_charsetForUrlEncoding; m_fallbackCharset = data.m_fallbackCharset; m_sampleStopNames = data.m_sampleStopNames; m_sampleCity = data.m_sampleCity; m_sampleLongitude = data.m_sampleLongitude; m_sampleLatitude = data.m_sampleLatitude; m_notes = data.m_notes; // For ScriptedProvider m_scriptFileName = data.m_scriptFileName; m_scriptExtensions = data.m_scriptExtensions; // For GtfsProvider m_feedUrl = data.m_feedUrl; m_tripUpdatesUrl = data.m_tripUpdatesUrl; m_alertsUrl = data.m_alertsUrl; m_timeZone = data.m_timeZone; return *this; } bool ServiceProviderData::operator ==( const ServiceProviderData &data ) const { return m_serviceProviderType == data.m_serviceProviderType && m_id == data.m_id && m_name == data.m_name && m_description == data.m_description && m_version == data.m_version && m_fileFormatVersion == data.m_fileFormatVersion && m_useSeparateCityValue == data.m_useSeparateCityValue && m_onlyUseCitiesInList == data.m_onlyUseCitiesInList && m_url == data.m_url && m_shortUrl == data.m_shortUrl && m_minFetchWait == data.m_minFetchWait && m_author == data.m_author && m_shortAuthor == data.m_shortAuthor && m_email == data.m_email && m_defaultVehicleType == data.m_defaultVehicleType && m_changelog == data.m_changelog && m_country == data.m_country && m_cities == data.m_cities && m_credit == data.m_credit && m_hashCityNameToValue == data.m_hashCityNameToValue && m_fileName == data.m_fileName && m_charsetForUrlEncoding == data.m_charsetForUrlEncoding && m_fallbackCharset == data.m_fallbackCharset && m_sampleStopNames == data.m_sampleStopNames && m_sampleCity == data.m_sampleCity && m_sampleLongitude == data.m_sampleLongitude && m_sampleLatitude == data.m_sampleLatitude && m_notes == data.m_notes && // For ScriptedProvider m_scriptFileName == data.m_scriptFileName && m_scriptExtensions == data.m_scriptExtensions && // For GtfsProvider m_feedUrl == data.m_feedUrl && m_tripUpdatesUrl == data.m_tripUpdatesUrl && m_alertsUrl == data.m_alertsUrl && m_timeZone == data.m_timeZone; } void ServiceProviderData::finish() { // Generate a short URL if none is given if ( m_shortUrl.isEmpty() ) { m_shortUrl = shortUrlFromUrl( m_url ); } // Generate a short author name if none is given if ( m_shortAuthor.isEmpty() && !m_author.isEmpty() ) { m_shortAuthor = shortAuthorFromAuthor( m_author ); } // Use script author as author of the change entry if no one else was set for ( int i = 0; i < m_changelog.count(); ++i ) { if ( m_changelog[i].author.isEmpty() ) { m_changelog[i].author = m_shortAuthor; } } qStableSort( m_changelog.begin(), m_changelog.end(), ChangelogEntryGreaterThan() ); } QString ServiceProviderData::typeString() const { return ServiceProviderGlobal::typeToString( m_serviceProviderType ); } QString ServiceProviderData::typeName( ) const { return ServiceProviderGlobal::typeName( m_serviceProviderType ); } int ServiceProviderData::versionNumberFromString( const QString &version, int *startPos ) { bool ok; int versionNumber; int nextPointPos = version.indexOf( '.', *startPos ); if ( nextPointPos <= 0 ) { // No point found in version after startPos, get last number until the end of the string versionNumber = version.mid( *startPos ).toInt( &ok ); *startPos = -1; } else { // Found a point after startPos in version, extract the number from version versionNumber = version.mid( *startPos, nextPointPos - *startPos ).toInt( &ok ); *startPos = nextPointPos + 1; } if ( ok ) { return versionNumber; } else { kDebug() << "Version is invalid:" << version; return -1; } } int ServiceProviderData::compareVersions( const QString &version1, const QString &version2 ) { int pos1 = 0; int pos2 = 0; forever { int versionNumber1 = versionNumberFromString( version1, &pos1 ); int versionNumber2 = versionNumberFromString( version2, &pos2 ); if ( versionNumber1 < 0 || versionNumber2 < 0 ) { // Invalid version strings return 0; } if ( versionNumber1 < versionNumber2 ) { return -1; // Version 1 is smaller than version 2 } else if ( versionNumber1 > versionNumber2 ) { return 1; // Version 1 is bigger than version 2 } if ( pos1 == -1 && pos2 == -1 ) { return 0; // No more version numbers in both version } else if ( pos1 == -1 ) { return -1; // No more version numbers in version1, but in version2, which is therefore bigger } else if ( pos2 == -1 ) { return 1; // No more version numbers in version2, but in version1, which is therefore bigger } // pos1 and pos2 are both >= 0 here, // they are set behind the '.' after the just read version numbers, // this makes the next iteration read the next version number } return 0; } QString ServiceProviderData::shortUrlFromUrl( const QString &url ) { QString shortUrl = QUrl( url ).toString( QUrl::RemoveScheme | QUrl::RemovePort | QUrl::RemovePath | QUrl::RemoveQuery | QUrl::RemoveFragment | QUrl::StripTrailingSlash ); while ( shortUrl.startsWith('/') ) { shortUrl = shortUrl.mid( 1 ); } return shortUrl; } QString ServiceProviderData::shortAuthorFromAuthor( const QString &authorName ) { const QStringList names = authorName.toLower().split( ' ', QString::SkipEmptyParts ); if ( !names.isEmpty() ) { // Add first character of all prenames QString shortAuthor; for ( int i = 0; i < names.count() - 1; ++i ) { shortAuthor += names[i][0]; } // Add family name completely shortAuthor += names.last(); return shortAuthor.replace( QString::fromUtf8("ü"), QLatin1String("ue") ) .replace( QString::fromUtf8("ö"), QLatin1String("oe") ) .replace( QString::fromUtf8("ä"), QLatin1String("ae") ) .replace( QString::fromUtf8("Ü"), QLatin1String("Ue") ) .replace( QString::fromUtf8("Ö"), QLatin1String("Oe") ) .replace( QString::fromUtf8("Ä"), QLatin1String("Ae") ) .replace( QString::fromUtf8("ß"), QLatin1String("ss") ); } else { return QString(); } } QString ServiceProviderData::name() const { const QString lang = KGlobal::locale()->country(); return m_name.contains(lang) ? m_name[lang] : m_name["en"]; } QString ServiceProviderData::description() const { const QString lang = KGlobal::locale()->country(); return m_description.contains(lang) ? m_description[lang] : m_description["en"]; } QString ServiceProviderData::notes() const { return m_notes; } void ServiceProviderData::setUrl( const QString &url, const QString &shortUrl ) { m_url = url; m_shortUrl = shortUrl.isEmpty() ? shortUrlFromUrl(url) : shortUrl; } void ServiceProviderData::setAuthor( const QString& author, const QString &shortAuthor, const QString &email ) { m_author = author; m_shortAuthor = shortAuthor; m_email = email; } void ServiceProviderData::setFileName(const QString& fileName) { m_fileName = KStandardDirs::realFilePath( fileName ); } QString ServiceProviderData::mapCityNameToValue( const QString &city ) const { if ( m_hashCityNameToValue.contains( city.toLower() ) ) { return m_hashCityNameToValue[city.toLower()]; } else { return city; } } QString ServiceProviderData::changelogString() const { QString changelog; foreach ( const ChangelogEntry &entry, m_changelog ) { if ( !changelog.isEmpty() ) { changelog.append( '\n' ); } changelog.append( entry.version ); if ( !entry.author.isEmpty() ) { changelog.append( " (" + entry.author + ')' ); } changelog.append( ": " + entry.description ); } return changelog; } diff --git a/engine/serviceproviderdatareader.cpp b/engine/serviceproviderdatareader.cpp index f328826..0c8e1b4 100644 --- a/engine/serviceproviderdatareader.cpp +++ b/engine/serviceproviderdatareader.cpp @@ -1,571 +1,572 @@ /* * 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 "serviceproviderdatareader.h" // Own includes #include "config.h" #include "serviceprovider.h" #include "serviceproviderdata.h" #include "serviceproviderglobal.h" #include "script/serviceproviderscript.h" #include "global.h" // KDE includes #include +#include #include #include #include // Qt includes #include #include ServiceProviderData *ServiceProviderDataReader::read( const QString &providerId, QString *errorMessage, QString *comments ) { QString filePath; QString country = "international"; QString _serviceProviderId = providerId; if ( _serviceProviderId.isEmpty() ) { // No service provider ID given, use the default one for the users country country = KGlobal::locale()->country(); // Try to find the XML filename of the default accessor for [country] filePath = ServiceProviderGlobal::defaultProviderForLocation( country ); if ( filePath.isEmpty() ) { return 0; } // Extract service provider ID from filename _serviceProviderId = ServiceProviderGlobal::idFromFileName( filePath ); kDebug() << "No service provider ID given, using the default one for country" << country << "which is" << _serviceProviderId; } else { foreach ( const QString &extension, ServiceProviderGlobal::fileExtensions() ) { filePath = KStandardDirs::locate( "data", ServiceProviderGlobal::installationSubDirectory() + _serviceProviderId + '.' + extension ); if ( !filePath.isEmpty() ) { break; } } if ( filePath.isEmpty() ) { kDebug() << "Could not find a service provider plugin XML named" << _serviceProviderId; if ( errorMessage ) { *errorMessage = i18nc("@info/plain", "Could not find a service provider " "plugin with the ID %1", _serviceProviderId); } return 0; } // Get country code from filename QRegExp rx( "^([^_]+)" ); if ( rx.indexIn(_serviceProviderId) != -1 && KGlobal::locale()->allCountriesList().contains(rx.cap()) ) { country = rx.cap(); } } QFile file( filePath ); ServiceProviderDataReader reader; ServiceProviderData *data = reader.read( &file, providerId, filePath, country, ServiceProviderDataReader::OnlyReadCorrectFiles, 0, comments ); if ( !data && errorMessage ) { *errorMessage = i18nc("@info/plain", "Error in line %1: %2", reader.lineNumber(), reader.errorString()); } return data; } ServiceProviderData *ServiceProviderDataReader::read( QIODevice *device, const QString &fileName, ErrorAcceptance errorAcceptance, QObject *parent, QString *comments, QString *errorMessage ) { const QString serviceProvider = ServiceProviderGlobal::idFromFileName( fileName ); // Get country code from filename QString country; QRegExp rx( "^([^_]+)" ); if ( rx.indexIn(serviceProvider) != -1 && KGlobal::locale()->allCountriesList().contains(rx.cap()) ) { country = rx.cap(); } else { country = "international"; } return read( device, serviceProvider, fileName, country, errorAcceptance, parent, comments, errorMessage ); } bool ServiceProviderDataReader::handleError( const QString &errorMessage, ErrorAcceptance errorAcceptance, QString *errorMessageOutput ) { if ( errorMessageOutput ) { *errorMessageOutput = errorMessage; } if ( errorAcceptance == OnlyReadCorrectFiles ) { raiseError( errorMessage ); return false; } else { return true; } } ServiceProviderData* ServiceProviderDataReader::read( QIODevice* device, const QString &serviceProvider, const QString &fileName, const QString &country, ErrorAcceptance errorAcceptance, QObject *parent, QString *comments, QString *errorMessage ) { Q_ASSERT( device ); bool closeAfterRead; // Only close after reading if it wasn't open before if ( (closeAfterRead = !device->isOpen()) && !device->open(QIODevice::ReadOnly) ) { if ( !handleError("Couldn't read the file \"" + fileName + "\".", errorAcceptance, errorMessage) ) { return 0; } } setDevice( device ); ServiceProviderData *data = 0; while ( !atEnd() ) { readNext(); if ( isComment() ) { if ( comments ) { addComments( comments, text() ); } } else if ( isStartElement() ) { if ( name().compare("serviceProvider", Qt::CaseInsensitive) != 0 ) { if ( !handleError(QString("Wrong root element for %1, should be , " "is <%2>.").arg(serviceProvider, name().toString()), errorAcceptance, errorMessage) ) { return 0; } } else if ( attributes().value("fileVersion") != QLatin1String("1.1") ) { const QString message = QString("Service provider plugin format version '%1' " "specified by %2 is not supported. Currently only 1.1 is supported. " "Please make sure the plugin complies with that version and update the " "'fileVersion' attribute of the root tag.") .arg(attributes().value("fileVersion").toString(), serviceProvider); if ( !handleError(message, errorAcceptance, errorMessage) ) { return 0; } } data = readProviderData( serviceProvider, fileName, country, errorAcceptance, parent, comments, errorMessage ); break; } } if ( comments ) { while ( !atEnd() ) { readNext(); if ( isComment() ) { addComments( comments, text() ); } } } if ( closeAfterRead ) { device->close(); } if ( error() != NoError ) { kDebug() << "Error reading provider" << serviceProvider << errorString(); } return error() == NoError && data ? data : 0; } void ServiceProviderDataReader::readUnknownElement( QString *comments ) { Q_ASSERT( isStartElement() ); if ( comments ) { addComments( comments, readStartElementString(), false ); } while ( !atEnd() ) { TokenType type = readNext(); switch ( type ) { case EndElement: if ( comments ) { addComments( comments, QString("").arg(name().toString()), false ); } return; case Comment: case Characters: case EntityReference: if ( comments ) { addComments( comments, text(), false ); } break; case StartElement: readUnknownElement( comments ); break; default: break; } } } QString ServiceProviderDataReader::readStartElementString() const { QString elementString( '<' ); elementString.append( name() ); const QXmlStreamAttributes attr = attributes(); for ( QXmlStreamAttributes::ConstIterator it = attr.constBegin(); it != attr.constEnd(); ++it ) { elementString.append( QString(" %1=\"%2\"") .arg(it->name().toString(), it->value().toString()) ); } elementString.append( '>' ); return elementString; } void ServiceProviderDataReader::addComments( QString *comments, const QString &newComments, bool newLine ) { if ( newComments.isEmpty() ) { return; } if ( newLine && !comments->isEmpty() ) { comments->append( '\n' ); } comments->append( newComments ); } ServiceProviderData *ServiceProviderDataReader::readProviderData( const QString &serviceProviderId, const QString &fileName, const QString &country, ErrorAcceptance errorAcceptance, QObject *parent, QString *comments, QString *errorMessage ) { const QString lang = KGlobal::locale()->country(); QString langRead, url, shortUrl; QHash names, descriptions; Enums::ServiceProviderType serviceProviderType; QString serviceProviderTypeString; const QString fileVersion = attributes().value("fileVersion").toString(); if ( attributes().hasAttribute(QLatin1String("type")) ) { serviceProviderTypeString = attributes().value( QLatin1String("type") ).toString(); serviceProviderType = ServiceProviderGlobal::typeFromString( serviceProviderTypeString ); if ( serviceProviderType == Enums::InvalidProvider && errorAcceptance == OnlyReadCorrectFiles ) { if ( !handleError(QString("The service provider type %1 used for %2 is invalid. " "Currently there are two values allowed: Script or GTFS.") .arg(serviceProviderTypeString, serviceProviderId), errorAcceptance, errorMessage) ) { return 0; } return 0; } } else { // No provider type in the XML file, use a default one #ifdef BUILD_PROVIDER_TYPE_SCRIPT serviceProviderType = Enums::ScriptedProvider; serviceProviderTypeString = ServiceProviderGlobal::typeToString( serviceProviderType ); #else #ifdef BUILD_PROVIDER_TYPE_GTFS serviceProviderType = Enums::GtfsProvider; serviceProviderTypeString = ServiceProviderGlobal::typeToString( serviceProviderType ); #else kFatal() << "Internal error: No known provider type is supported, " "tried ScriptedProvider and GtfsProvider"; #endif #endif qWarning() << "No provider type in the provider plugin file, using default type" << ServiceProviderGlobal::typeName(serviceProviderType); } ServiceProviderData *serviceProviderData = new ServiceProviderData( serviceProviderType, serviceProviderId, parent ); serviceProviderData->setFileName( fileName ); serviceProviderData->setCountry( country ); serviceProviderData->setFileFormatVersion( fileVersion ); if ( attributes().hasAttribute(QLatin1String("version")) ) { serviceProviderData->setVersion( attributes().value(QLatin1String("version")).toString() ); } while ( !atEnd() ) { readNext(); if ( isEndElement() && name().compare(QLatin1String("serviceProvider"), Qt::CaseInsensitive) == 0 ) { break; } if ( isComment() ) { if ( comments ) { addComments( comments, text() ); } } else if ( isStartElement() ) { if ( name().compare(QLatin1String("name"), Qt::CaseInsensitive) == 0 ) { const QString nameRead = readLocalizedTextElement( &langRead ); names[ langRead ] = nameRead; } else if ( name().compare(QLatin1String("description"), Qt::CaseInsensitive) == 0 ) { const QString descriptionRead = readLocalizedTextElement( &langRead ); descriptions[ langRead ] = descriptionRead; } else if ( name().compare(QLatin1String("author"), Qt::CaseInsensitive) == 0 ) { QString authorName, shortName, authorEmail; readAuthor( &authorName, &shortName, &authorEmail ); serviceProviderData->setAuthor( authorName, shortName, authorEmail ); } else if ( name().compare(QLatin1String("cities"), Qt::CaseInsensitive) == 0 ) { QStringList cities; QHash cityNameReplacements; readCities( &cities, &cityNameReplacements ); serviceProviderData->setCities( cities ); serviceProviderData->setCityNameToValueReplacementHash( cityNameReplacements ); } else if ( name().compare(QLatin1String("useSeperateCityValue"), Qt::CaseInsensitive) == 0 ) { serviceProviderData->setUseSeparateCityValue( readBooleanElement() ); } else if ( name().compare(QLatin1String("onlyUseCitiesInList"), Qt::CaseInsensitive) == 0 ) { serviceProviderData->setOnlyUseCitiesInList( readBooleanElement() ); } else if ( name().compare(QLatin1String("defaultVehicleType"), Qt::CaseInsensitive) == 0 ) { serviceProviderData->setDefaultVehicleType( Global::vehicleTypeFromString(readElementText()) ); } else if ( name().compare(QLatin1String("url"), Qt::CaseInsensitive) == 0 ) { url = readElementText(); } else if ( name().compare(QLatin1String("shortUrl"), Qt::CaseInsensitive) == 0 ) { shortUrl = readElementText(); } else if ( name().compare(QLatin1String("minFetchWait"), Qt::CaseInsensitive) == 0 ) { serviceProviderData->setMinFetchWait( readElementText().toInt() ); } else if ( name().compare(QLatin1String("charsetForUrlEncoding"), Qt::CaseInsensitive) == 0 ) { serviceProviderData->setCharsetForUrlEncoding( readElementText().toAscii() ); } else if ( name().compare(QLatin1String("fallbackCharset"), Qt::CaseInsensitive) == 0 ) { serviceProviderData->setFallbackCharset( readElementText().toAscii() ); // TODO Implement as attributes in the url tags? } else if ( name().compare(QLatin1String("changelog"), Qt::CaseInsensitive) == 0 ) { serviceProviderData->setChangelog( readChangelog() ); } else if ( name().compare(QLatin1String("credit"), Qt::CaseInsensitive) == 0 ) { serviceProviderData->setCredit( readElementText() ); #ifdef BUILD_PROVIDER_TYPE_GTFS } else if ( name().compare("feedUrl", Qt::CaseInsensitive) == 0 ) { serviceProviderData->setFeedUrl( readElementText() ); } else if ( name().compare("realtimeTripUpdateUrl", Qt::CaseInsensitive) == 0 ) { serviceProviderData->setRealtimeTripUpdateUrl( readElementText() ); } else if ( name().compare("realtimeAlertsUrl", Qt::CaseInsensitive) == 0 ) { serviceProviderData->setRealtimeAlertsUrl( readElementText() ); } else if ( name().compare("timeZone", Qt::CaseInsensitive) == 0 ) { serviceProviderData->setTimeZone( readElementText() ); #endif #ifdef BUILD_PROVIDER_TYPE_SCRIPT } else if ( serviceProviderType == Enums::ScriptedProvider && name().compare(QLatin1String("script"), Qt::CaseInsensitive) == 0 ) { const QStringList extensions = attributes().value( QLatin1String("extensions") ) .toString().split( ',', QString::SkipEmptyParts ); const QString scriptFile = QFileInfo( fileName ).path() + '/' + readElementText(); if ( !QFile::exists(scriptFile) ) { if ( !handleError(QString("The script file %1 referenced by the service " "provider plugin %2 was not found") .arg(scriptFile, serviceProviderId), errorAcceptance, errorMessage) ) { delete serviceProviderData; return 0; } } serviceProviderData->setScriptFile( scriptFile, extensions ); #endif } else if ( name().compare(QLatin1String("samples"), Qt::CaseInsensitive) == 0 ) { QStringList stops; QString city; qreal longitude, latitude; readSamples( &stops, &city, &longitude, &latitude ); serviceProviderData->setSampleStops( stops ); serviceProviderData->setSampleCity( city ); serviceProviderData->setSampleCoordinates( longitude, latitude ); } else if ( name().compare(QLatin1String("notes"), Qt::CaseInsensitive) == 0 ) { serviceProviderData->setNotes( readElementText() ); } else { readUnknownElement( comments ); } } } if ( url.isEmpty() ) { qWarning() << "No tag in service provider plugin XML"; } serviceProviderData->setNames( names ); serviceProviderData->setDescriptions( descriptions ); serviceProviderData->setUrl( url, shortUrl ); serviceProviderData->finish(); return serviceProviderData; } QString ServiceProviderDataReader::readLocalizedTextElement( QString *lang ) { if ( attributes().hasAttribute(QLatin1String("lang")) ) { *lang = attributes().value(QLatin1String("lang")).toString(); } else { *lang = "en"; } return readElementText(); } bool ServiceProviderDataReader::readBooleanElement() { const QString content = readElementText().trimmed(); if ( content.compare( "true", Qt::CaseInsensitive ) == 0 || content == QLatin1String("1") ) { return true; } else { return false; } } void ServiceProviderDataReader::readAuthor( QString *fullname, QString *shortName, QString *email, QString *comments ) { while ( !atEnd() ) { readNext(); if ( isEndElement() && name().compare( "author", Qt::CaseInsensitive ) == 0 ) { break; } if ( isComment() ) { if ( comments ) { addComments( comments, text() ); } } else if ( isStartElement() ) { if ( name().compare(QLatin1String("fullName"), Qt::CaseInsensitive) == 0 ) { *fullname = readElementText().trimmed(); } else if ( name().compare(QLatin1String("short"), Qt::CaseInsensitive) == 0 ) { *shortName = readElementText().trimmed(); } else if ( name().compare(QLatin1String("email"), Qt::CaseInsensitive) == 0 ) { *email = readElementText().trimmed(); } else { readUnknownElement(); } } } } void ServiceProviderDataReader::readCities( QStringList *cities, QHash< QString, QString > *cityNameReplacements, QString *comments ) { while ( !atEnd() ) { readNext(); if ( isEndElement() && name().compare(QLatin1String("cities"), Qt::CaseInsensitive) == 0 ) { break; } if ( isComment() ) { if ( comments ) { addComments( comments, text() ); } } else if ( isStartElement() ) { if ( name().compare(QLatin1String("city"), Qt::CaseInsensitive ) == 0 ) { if ( attributes().hasAttribute(QLatin1String("replaceWith")) ) { QString replacement = attributes().value(QLatin1String("replaceWith")).toString().toLower(); QString city = readElementText(); cityNameReplacements->insert( city.toLower(), replacement ); cities->append( city ); } else { QString city = readElementText(); cities->append( city ); } } else { readUnknownElement(); } } } } void ServiceProviderDataReader::readSamples( QStringList *stops, QString *city, qreal *longitude, qreal *latitude, QString *comments ) { while ( !atEnd() ) { readNext(); if ( isEndElement() && name().compare(QLatin1String("samples"), Qt::CaseInsensitive) == 0 ) { break; } if ( isComment() ) { if ( comments ) { addComments( comments, text() ); } } else if ( isStartElement() ) { if ( name().compare(QLatin1String("stop"), Qt::CaseInsensitive ) == 0 ) { stops->append( readElementText() ); } else if ( name().compare(QLatin1String("city"), Qt::CaseInsensitive ) == 0 ) { *city = readElementText(); } else if ( name().compare(QLatin1String("longitude"), Qt::CaseInsensitive ) == 0 ) { *longitude = readElementText().toDouble(); } else if ( name().compare(QLatin1String("latitude"), Qt::CaseInsensitive ) == 0 ) { *latitude = readElementText().toDouble(); } else { readUnknownElement(); } } } } QList ServiceProviderDataReader::readChangelog( QString *comments ) { QList changelog; while ( !atEnd() ) { readNext(); if ( isEndElement() && name().compare("changelog", Qt::CaseInsensitive) == 0 ) { break; } if ( isComment() ) { if ( comments ) { addComments( comments, text() ); } } else if ( isStartElement() ) { if ( name().compare("entry", Qt::CaseInsensitive) == 0 ) { ChangelogEntry currentEntry; if ( attributes().hasAttribute(QLatin1String("version")) ) { currentEntry.version = attributes().value( QLatin1String("version") ).toString(); } else if ( attributes().hasAttribute(QLatin1String("since")) ) { // DEPRECATED currentEntry.version = attributes().value( QLatin1String("since") ).toString(); } if( attributes().hasAttribute(QLatin1String("releasedWith")) ) { currentEntry.engineVersion = attributes().value( QLatin1String("releasedWith") ).toString(); } else if ( attributes().hasAttribute(QLatin1String("engineVersion")) ) { // DEPRECATED currentEntry.engineVersion = attributes().value( QLatin1String("engineVersion") ).toString(); } if ( attributes().hasAttribute(QLatin1String("author")) ) { currentEntry.author = attributes().value( QLatin1String("author") ).toString(); } currentEntry.description = readElementText(); changelog.append( currentEntry ); } else { readUnknownElement(); } } } return changelog; } diff --git a/engine/serviceproviderglobal.cpp b/engine/serviceproviderglobal.cpp index 3aef95d..b6ef1f1 100644 --- a/engine/serviceproviderglobal.cpp +++ b/engine/serviceproviderglobal.cpp @@ -1,385 +1,383 @@ /* * 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 "serviceproviderglobal.h" // Own includes #include "config.h" // KDE includes -#include -#include #include +#include #include -#include +#include #include // Qt includes #include #include #include QList< Enums::ServiceProviderType > ServiceProviderGlobal::availableProviderTypes() { QList< Enums::ServiceProviderType > types; #ifdef BUILD_PROVIDER_TYPE_SCRIPT types << Enums::ScriptedProvider; #endif #ifdef BUILD_PROVIDER_TYPE_GTFS types << Enums::GtfsProvider; #endif return types; } bool ServiceProviderGlobal::isProviderTypeAvailable( Enums::ServiceProviderType type ) { switch ( type ) { case Enums::ScriptedProvider: #ifdef BUILD_PROVIDER_TYPE_SCRIPT return true; #else return false; #endif case Enums::GtfsProvider: #ifdef BUILD_PROVIDER_TYPE_GTFS return true; #else return false; #endif case Enums::InvalidProvider: default: return false; } } QString ServiceProviderGlobal::defaultProviderForLocation( const QString &location ) { QStringList locationProviders; const QString subDirectory = installationSubDirectory(); foreach ( const QString &pattern, filePatterns() ) { locationProviders << KGlobal::dirs()->findAllResources( "data", subDirectory + location + '_' + pattern ); } if ( locationProviders.isEmpty() ) { qWarning() << "Couldn't find any providers for location" << location; return QString(); } // Simply return first found provider as default provider return locationProviders.first(); } QString ServiceProviderGlobal::cacheFileName() { - return QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + QLatin1Char('/') + "plasma_engine_publictransport/") - .append( QLatin1String("datacache") ); + return KGlobal::dirs()->saveLocation("data", "plasma_engine_publictransport/").append( QLatin1String("datacache") ); } QSharedPointer< KConfig > ServiceProviderGlobal::cache() { return QSharedPointer< KConfig >( new KConfig(cacheFileName(), KConfig::SimpleConfig) ); } void ServiceProviderGlobal::cleanupCache( const QSharedPointer< KConfig > &_cache ) { QSharedPointer< KConfig > cache = _cache.isNull() ? ServiceProviderGlobal::cache() : _cache; const QStringList installedProviderPaths = ServiceProviderGlobal::installedProviders(); QStringList installedProviderIDs; foreach ( const QString &installedProviderPath, installedProviderPaths ) { installedProviderIDs << idFromFileName( installedProviderPath ); } foreach ( const QString &group, cache->groupList() ) { if ( group != QLatin1String("script") && group != QLatin1String("gtfs") && !installedProviderIDs.contains(group) ) { // Found a group for a provider that is no longer installed kDebug() << "Cleanup cache data for no longer installed provider" << group; clearCache( group, cache, false ); } } cache->sync(); } void ServiceProviderGlobal::clearCache( const QString &providerId, const QSharedPointer< KConfig > &_cache, bool syncCache ) { QSharedPointer< KConfig > cache = _cache.isNull() ? ServiceProviderGlobal::cache() : _cache; if ( !cache->hasGroup(providerId) ) { // No data cached for the provider return; } // Remove all data for the provider from the cache cache->deleteGroup( providerId ); // Remove provider from "usingProviders" lists for included script files KConfigGroup globalScriptGroup = cache->group( "script" ); const QStringList globalScriptGroupNames = globalScriptGroup.groupList(); foreach ( const QString &globalScriptGroupName, globalScriptGroupNames ) { if ( !globalScriptGroupName.startsWith(QLatin1String("include_")) ) { continue; } // Check if the provider to remove from the cache is listed as using the current include KConfigGroup includeFileGroup = globalScriptGroup.group( globalScriptGroupName ); QStringList usingProviders = includeFileGroup.readEntry( "usingProviders", QStringList() ); if ( usingProviders.contains(providerId) ) { // Remove provider from the list of providers using the current include script file usingProviders.removeOne( providerId ); includeFileGroup.writeEntry( "usingProviders", usingProviders ); } } if ( syncCache ) { cache->sync(); } } QString ServiceProviderGlobal::idFromFileName( const QString &serviceProviderFileName ) { // Get the service provider substring from the XML filename, ie. "/path/to/xml/.pts/xml" return QFileInfo( serviceProviderFileName ).baseName(); } QString ServiceProviderGlobal::fileNameFromId( const QString &serviceProviderId ) { const QString subDirectory = installationSubDirectory(); foreach ( const QString &extension, fileExtensions() ) { const QString fileName = KStandardDirs::locate( "data", subDirectory + serviceProviderId + '.' + extension ); if ( !fileName.isEmpty() ) { return fileName; } } // File not found kDebug() << "No service provider plugin found with this ID:" << serviceProviderId; return QString(); } Enums::ServiceProviderType ServiceProviderGlobal::typeFromString( const QString &serviceProviderType ) { QString s = serviceProviderType.toLower(); if ( s == QLatin1String("script") || s == QLatin1String("html") ) // DEPRECATED { return Enums::ScriptedProvider; } else if ( s == QLatin1String("gtfs") ) { return Enums::GtfsProvider; } else { return Enums::InvalidProvider; } } QString ServiceProviderGlobal::typeToString( Enums::ServiceProviderType type ) { switch ( type ) { case Enums::ScriptedProvider: return "script"; case Enums::GtfsProvider: return "gtfs"; case Enums::InvalidProvider: default: return "invalid"; } } QString ServiceProviderGlobal::typeName( Enums::ServiceProviderType type, ProviderTypeNameOptions options ) { QString name; switch ( type ) { case Enums::ScriptedProvider: name = i18nc("@info/plain Name of a service provider plugin type", "Scripted"); break; case Enums::GtfsProvider: name = i18nc("@info/plain Name of a service provider plugin type", "GTFS"); break; case Enums::InvalidProvider: default: qWarning() << "Invalid provider type" << type; return i18nc("@info/plain Name of the invalid service provider plugin type", "Invalid"); } // Append "(unsupported)" if the engine gets build without support for the provider type if ( options == AppendHintForUnsupportedProviderTypes && !isProviderTypeAvailable(type) ) { name += ' ' + i18nc("@info/plain Gets appended to service provider plugin type names, " "if the engine gets build without support for that type", "(unsupported)"); } return name; } QStringList ServiceProviderGlobal::filePatterns() { const KMimeType::Ptr mimeType = KMimeType::mimeType("application/x-publictransport-serviceprovider"); if ( mimeType.isNull() ) { qWarning() << "The application/x-publictransport-serviceprovider mime type was not found!"; qWarning() << "No provider plugins will get loaded."; kDebug() << "Solution: Make sure 'serviceproviderplugin.xml' is installed correctly " "and run kbuildsycoca4."; return QStringList(); } else { return mimeType->patterns(); } } QStringList ServiceProviderGlobal::fileExtensions() { QStringList extensions = filePatterns(); for ( QStringList::Iterator it = extensions.begin(); it != extensions.end(); ++it ) { const int pos = it->lastIndexOf( '.' ); if ( pos == -1 || pos == it->length() - 1 ) { qWarning() << "Could not extract file extension from mime type pattern!\n" "Check the \"application/x-publictransport-serviceprovider\" mime type."; continue; } // Cut away everything but the file name extension *it = it->mid( pos + 1 ); } return extensions; } QStringList ServiceProviderGlobal::installedProviders() { QStringList providers; const QString subDirectory = installationSubDirectory(); foreach ( const QString &pattern, filePatterns() ) { providers << QStandardPaths::locateAll(QStandardPaths::GenericDataLocation, subDirectory + pattern ); } return providers; } bool ServiceProviderGlobal::isProviderInstalled( const QString &providerId ) { const QString subDirectory = installationSubDirectory(); foreach ( const QString &extension, fileExtensions() ) { const QString providerFile = KStandardDirs::locate( "data", subDirectory + providerId + '.' + extension ); if ( !providerFile.isEmpty() ) { // Found the provider plugin source file in an installation directory return true; } } // Provider is not installed return false; } bool ServiceProviderGlobal::isSourceFileModified( const QString &providerId, const QSharedPointer &cache ) { // Check if the script file was modified since the cache was last updated const KConfigGroup group = cache->group( providerId ); const QDateTime modifiedTime = group.readEntry( "modifiedTime", QDateTime() ); const QString fileName = fileNameFromId( providerId ); return fileName.isEmpty() ? true : QFileInfo(fileName).lastModified() != modifiedTime; } QString ServiceProviderGlobal::featureName( Enums::ProviderFeature feature ) { switch ( feature ) { case Enums::ProvidesDepartures: return i18nc("@info/plain A short string indicating support for departure from a stop", "Departures"); case Enums::ProvidesArrivals: return i18nc("@info/plain A short string indicating support for arrivals to a stop.", "Arrivals"); case Enums::ProvidesJourneys: return i18nc("@info/plain A short string indicating support for journeys", "Journey search"); case Enums::ProvidesAdditionalData: return i18nc("@info/plain A short string indicating support for additional data", "Get additional data later"); case Enums::ProvidesDelays: return i18nc("@info/plain A short string indicating that delay information can be provided", "Delays"); case Enums::ProvidesNews: return i18nc("@info/plain A short string indicating that news about timetable items can be provided", "News"); case Enums::ProvidesPlatform: return i18nc("@info/plain A short string indicating that platform information can be provided", "Platform"); case Enums::ProvidesStopSuggestions: return i18nc("@info/plain A short string indicating support for stop suggestions", "Stop suggestions"); case Enums::ProvidesStopsByGeoPosition: return i18nc("@info/plain A short string indicating support for querying stops by geo position", "Stops by geolocation"); case Enums::ProvidesStopID: return i18nc("@info/plain A short string indicating that stop IDs can be provided", "Stop ID"); case Enums::ProvidesStopGeoPosition: return i18nc("@info/plain A short string indicating that stop geographical positions can be provided", "Stop geolocation"); case Enums::ProvidesPricing: return i18nc("@info/plain A short string indicating that pricing information can be provided", "Pricing"); case Enums::ProvidesRouteInformation: return i18nc("@info/plain A short string indicating that route information can be provided", "Route information"); case Enums::ProvidesMoreJourneys: return i18nc("@info/plain A short string indicating that earlier later journeys can be " "provided for existing journey data sources", "Get earlier/later journeys"); default: qWarning() << "Unexpected feature value" << feature; return QString(); } } QStringList ServiceProviderGlobal::featureNames( const QList &features ) { QStringList names; foreach ( Enums::ProviderFeature feature, features ) { names << featureName( feature ); } return names; } QStringList ServiceProviderGlobal::featureStrings( const QList &features ) { QStringList names; foreach ( Enums::ProviderFeature feature, features ) { names << Enums::toString( feature ); } return names; } QList< Enums::ProviderFeature > ServiceProviderGlobal::featuresFromFeatureStrings( const QStringList &featureNames, bool *ok ) { QList< Enums::ProviderFeature > features; if ( ok ) *ok = true; foreach ( const QString &featureName, featureNames ) { Enums::ProviderFeature feature = Enums::stringToFeature( featureName.toAscii().data() ); if ( feature == Enums::InvalidProviderFeature ) { if ( ok ) *ok = false; } else { features << feature; } } return features; } diff --git a/engine/serviceproviderglobal.h b/engine/serviceproviderglobal.h index aa727a5..4d3a60b 100644 --- a/engine/serviceproviderglobal.h +++ b/engine/serviceproviderglobal.h @@ -1,162 +1,164 @@ /* * 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. */ #ifndef SERVICEPROVIDERGLOBAL_HEADER #define SERVICEPROVIDERGLOBAL_HEADER // Own includes #include "enums.h" +// KDE includes +#include +#include + // Qt includes #include - -class KConfig; -class KConfigGroup; +#include /** @brief Provides static functions for service providers. */ class ServiceProviderGlobal { public: /** @brief Options for the provider type name. */ enum ProviderTypeNameOptions { ProviderTypeNameWithoutUnsupportedHint, /**< Only use the provider type name. */ AppendHintForUnsupportedProviderTypes /**< Append a hint to the provider type name * if the engine was build without support for that provider type. */ }; /** * @brief Get a list of available service provider types. * The engine can be built without support for some provider types. * @note InvalidProvider is never contained in the list. * @see isProviderTypeAvailable() **/ static QList< Enums::ServiceProviderType > availableProviderTypes(); /** * @brief Whether or not the given provider @p type is available. * The engine can be built without support for some provider types. * @note If @p type is InvalidProvider this always returns false. * @see availableProviderTypes() **/ static bool isProviderTypeAvailable( Enums::ServiceProviderType type ); /** @brief Get the ServiceProviderType enumerable for the given string. */ static Enums::ServiceProviderType typeFromString( const QString &serviceProviderType ); /** @brief Get a string for the given @p type, not to be displayed to users, all lower case. */ static QString typeToString( Enums::ServiceProviderType type ); /** @brief Get the name for the given @p type, translated, to be displayed to users. */ static QString typeName( Enums::ServiceProviderType type, ProviderTypeNameOptions options = AppendHintForUnsupportedProviderTypes ); /** @brief Get a localized name for @p feature. */ static QString featureName( Enums::ProviderFeature feature ); /** @brief Get a list of localized names for @p features. */ static QStringList featureNames( const QList &features ); /** @brief Get a list of strings for @p features, using Enums::toString(). */ static QStringList featureStrings( const QList &features ); /** @brief Get a list of provider feature enumerables from a list of feature strings. */ static QList featuresFromFeatureStrings( const QStringList &featureNames, bool *ok = 0 ); /** @brief Get the service provider ID for the given service provider plugin file name. */ static QString idFromFileName( const QString &serviceProviderPluginFileName ); /** @brief Get the service provider plugin file name for the given service provider ID. */ static QString fileNameFromId( const QString &serviceProviderId ); /** @brief Get the file path of the default service provider XML for the given @p location. */ static QString defaultProviderForLocation( const QString &location ); /** * @brief Whether or not the provider source file (.pts) was modified. * * @param providerId The ID of the provider to test for modifications. * @param cache A shared pointer to the provider cache, see cache(). * @return @c True, if the provider source file was modified since the last provider test * for @p providerId, @c false otherwise. **/ static bool isSourceFileModified( const QString &providerId, const QSharedPointer &cache ); /** * @brief Get a shared pointer to the cache object for provider plugin information. * * The cache can be used by provider plugins to store information about themselves that * might take some time to get if not stored. For example a network request might be needed to * get the information. * KConfig gets used to read from / write to the cache file. * * @note Each provider should only write to it's group, the name of that group is the provider * ID. Classes derived from ServiceProvider should write their own data to a subgroup. * @see cacheFileName() **/ static QSharedPointer cache(); /** * @brief Get the name of the cache file. * @see cache() **/ static QString cacheFileName(); /** @brief Cleanup the cache from old entries for no longer installed providers. */ static void cleanupCache( const QSharedPointer &cache = QSharedPointer() ); /** * @brief Clear all values for the provider with the given @p providerId from the @p cache. * * Should be called when a provider was uninstalled. **/ static void clearCache( const QString &providerId, const QSharedPointer &cache = QSharedPointer(), bool syncCache = true ); /** @brief Get the sub directory for service provider plugins for the data engine. */ static QString installationSubDirectory() { return "plasma_engine_publictransport/serviceProviders/"; }; /** * @brief Get all patterns for service provider plugin files for the data engine. * The patterns are retrieved from the "application-x-publictransport-serviceprovider" mime type. **/ static QStringList filePatterns(); /** * @brief Get all extensions for service provider plugin files for the data engine. * The file name extensions are retrieved from the "application-x-publictransport-serviceprovider" * mime type file patterns. **/ static QStringList fileExtensions(); /** * @brief Get the file paths of all installed service provider plugins. * If invalid provider plugins are installed, they also get returned here. **/ static QStringList installedProviders(); /** * @brief Wether or not the provider with the given @p providerId is installed. **/ static bool isProviderInstalled( const QString &providerId ); }; #endif // Multiple inclusion guard