diff --git a/src/app/applicationcontroller.cpp b/src/app/applicationcontroller.cpp index 46ed595..4dacf2b 100644 --- a/src/app/applicationcontroller.cpp +++ b/src/app/applicationcontroller.cpp @@ -1,382 +1,418 @@ /* Copyright (C) 2018 Volker Krause 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 of the License, 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 Library General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . */ #include "applicationcontroller.h" #include "logging.h" #include "pkpassmanager.h" #include "reservationmanager.h" #include #include #include #include #include #include #include #include #include #include +#include +#include +#include #include #include #ifdef Q_OS_ANDROID #include #include #else #include #include #endif using namespace KItinerary; #ifdef Q_OS_ANDROID static void importReservation(JNIEnv *env, jobject that, jstring data) { Q_UNUSED(that); ApplicationController::instance()->importData(env->GetStringUTFChars(data, 0)); } static const JNINativeMethod methods[] = { {"importReservation", "(Ljava/lang/String;)V", (void*)importReservation} }; Q_DECL_EXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void*) { static bool initialized = false; if (initialized) return JNI_VERSION_1_6; initialized = true; JNIEnv *env = nullptr; if (vm->GetEnv((void**)&env, JNI_VERSION_1_4) != JNI_OK) { qCWarning(Log) << "Failed to get JNI environment."; return -1; } jclass cls = env->FindClass("org/kde/itinerary/Activity"); if (env->RegisterNatives(cls, methods, sizeof(methods) / sizeof(JNINativeMethod)) < 0) { qCWarning(Log) << "Failed to register native functions."; return -1; } return JNI_VERSION_1_4; } #endif ApplicationController* ApplicationController::s_instance = nullptr; ApplicationController::ApplicationController(QObject* parent) : QObject(parent) #ifdef Q_OS_ANDROID , m_activityResultReceiver(this) #endif { s_instance = this; connect(QGuiApplication::clipboard(), &QClipboard::dataChanged, this, &ApplicationController::clipboardContentChanged); } ApplicationController::~ApplicationController() { s_instance = nullptr; } ApplicationController* ApplicationController::instance() { return s_instance; } void ApplicationController::setReservationManager(ReservationManager* resMgr) { m_resMgr = resMgr; } void ApplicationController::setPkPassManager(PkPassManager* pkPassMgr) { m_pkPassMgr = pkPassMgr; } void ApplicationController::showOnMap(const QVariant &place) { if (place.isNull()) { return; } const auto geo = JsonLdDocument::readProperty(place, "geo").value(); const auto addr = JsonLdDocument::readProperty(place, "address").value(); #ifdef Q_OS_ANDROID QString intentUri; if (geo.isValid()) { intentUri = QLatin1String("geo:") + QString::number(geo.latitude()) + QLatin1Char(',') + QString::number(geo.longitude()); } else if (!addr.isEmpty()) { intentUri = QLatin1String("geo:0,0?q=") + addr.streetAddress() + QLatin1String(", ") + addr.postalCode() + QLatin1Char(' ') + addr.addressLocality() + QLatin1String(", ") + addr.addressCountry(); } else { return; } const auto activity = QtAndroid::androidActivity(); if (activity.isValid()) { activity.callMethod("launchViewIntentFromUri", "(Ljava/lang/String;)V", QAndroidJniObject::fromString(intentUri).object()); } #else if (geo.isValid()) { // zoom out further from airports, they are larger and you usually want to go further away from them const auto zoom = place.userType() == qMetaTypeId() ? 12 : 17; QUrl url; url.setScheme(QStringLiteral("https")); url.setHost(QStringLiteral("www.openstreetmap.org")); url.setPath(QStringLiteral("/")); const QString fragment = QLatin1String("map=") + QString::number(zoom) + QLatin1Char('/') + QString::number(geo.latitude()) + QLatin1Char('/') + QString::number(geo.longitude()); url.setFragment(fragment); QDesktopServices::openUrl(url); return; } if (!addr.isEmpty()) { QUrl url; url.setScheme(QStringLiteral("https")); url.setHost(QStringLiteral("www.openstreetmap.org")); url.setPath(QStringLiteral("/search")); const QString queryString = addr.streetAddress() + QLatin1String(", ") + addr.postalCode() + QLatin1Char(' ') + addr.addressLocality() + QLatin1String(", ") + addr.addressCountry(); QUrlQuery query; query.addQueryItem(QStringLiteral("query"), queryString); url.setQuery(query); QDesktopServices::openUrl(url); } #endif } bool ApplicationController::canNavigateTo(const QVariant& place) { if (place.isNull()) { return false; } if (JsonLdDocument::readProperty(place, "geo").value().isValid()) { return true; } #ifdef Q_OS_ANDROID return !JsonLdDocument::readProperty(place, "address").value().isEmpty(); #else return false; #endif } void ApplicationController::navigateTo(const QVariant& place) { if (place.isNull()) { return; } #ifdef Q_OS_ANDROID const auto geo = JsonLdDocument::readProperty(place, "geo").value(); const auto addr = JsonLdDocument::readProperty(place, "address").value(); QString intentUri; if (geo.isValid()) { intentUri = QLatin1String("google.navigation:q=") + QString::number(geo.latitude()) + QLatin1Char(',') + QString::number(geo.longitude()); } else if (!addr.isEmpty()) { intentUri = QLatin1String("google.navigation:q=") + addr.streetAddress() + QLatin1String(", ") + addr.postalCode() + QLatin1Char(' ') + addr.addressLocality() + QLatin1String(", ") + addr.addressCountry(); } else { return; } const auto activity = QtAndroid::androidActivity(); if (activity.isValid()) { activity.callMethod("launchViewIntentFromUri", "(Ljava/lang/String;)V", QAndroidJniObject::fromString(intentUri).object()); } #else if (m_pendingNavigation) { return; } if (!m_positionSource) { m_positionSource = QGeoPositionInfoSource::createDefaultSource(this); if (!m_positionSource) { qWarning() << "no geo position info source available"; return; } } if (m_positionSource->lastKnownPosition().isValid()) { navigateTo(m_positionSource->lastKnownPosition(), place); } else { m_pendingNavigation = connect(m_positionSource, &QGeoPositionInfoSource::positionUpdated, this, [this, place](const QGeoPositionInfo &pos) { navigateTo(pos, place); }); m_positionSource->requestUpdate(); } #endif } #ifndef Q_OS_ANDROID void ApplicationController::navigateTo(const QGeoPositionInfo &from, const QVariant &to) { qDebug() << from.coordinate() << from.isValid(); disconnect(m_pendingNavigation); if (!from.isValid()) { return; } const auto geo = JsonLdDocument::readProperty(to, "geo").value(); if (geo.isValid()) { QUrl url; url.setScheme(QStringLiteral("https")); url.setHost(QStringLiteral("www.openstreetmap.org")); url.setPath(QStringLiteral("/directions")); QUrlQuery query; query.addQueryItem(QLatin1String("route"), QString::number(from.coordinate().latitude()) + QLatin1Char(',') + QString::number(from.coordinate().longitude()) + QLatin1Char(';') + QString::number(geo.latitude()) + QLatin1Char(',') + QString::number(geo.longitude())); url.setQuery(query); QDesktopServices::openUrl(url); return; } } #endif static bool isPkPassFile(const QUrl &url) { if (url.isLocalFile()) { QFile f(url.toLocalFile()); if (f.open(QFile::ReadOnly)) { char buffer[4]; if (f.read(buffer, sizeof(buffer)) != sizeof(buffer)) { return false; } return buffer[0] == 'P' && buffer[1] == 'K' && buffer[2] == 0x03 && buffer[3] == 0x04; } } return url.fileName().endsWith(QLatin1String(".pkpass")); } #ifdef Q_OS_ANDROID void ApplicationController::importFromIntent(const QAndroidJniObject &intent) { if (!intent.isValid()) { return; } const auto uri = intent.callObjectMethod("getData", "()Landroid/net/Uri;"); if (!uri.isValid()) { return; } const auto scheme = uri.callObjectMethod("getScheme", "()Ljava/lang/String;"); qCDebug(Log) << uri.callObjectMethod("toString", "()Ljava/lang/String;").toString(); if (scheme.toString() == QLatin1String("content")) { const auto tmpFile = QtAndroid::androidActivity().callObjectMethod("receiveContent", "(Landroid/net/Uri;)Ljava/lang/String;", uri.object()); const auto tmpUrl = QUrl::fromLocalFile(tmpFile.toString()); if (isPkPassFile(tmpUrl)) { m_pkPassMgr->importPassFromTempFile(tmpUrl); } else { m_resMgr->importReservation(tmpUrl); } } else if (scheme.toString() == QLatin1String("file")) { const auto uriStr = uri.callObjectMethod("toString", "()Ljava/lang/String;"); importLocalFile(QUrl(uriStr.toString())); } else { const auto uriStr = uri.callObjectMethod("toString", "()Ljava/lang/String;"); qCWarning(Log) << "Unknown intent URI:" << uriStr.toString(); } } void ApplicationController::ActivityResultReceiver::handleActivityResult(int receiverRequestCode, int resultCode, const QAndroidJniObject &intent) { qCDebug(Log) << receiverRequestCode << resultCode; m_controller->importFromIntent(intent); } #endif void ApplicationController::showImportFileDialog() { #ifdef Q_OS_ANDROID const auto ACTION_OPEN_DOCUMENT = QAndroidJniObject::getStaticObjectField("android/content/Intent", "ACTION_OPEN_DOCUMENT"); QAndroidJniObject intent("android/content/Intent", "(Ljava/lang/String;)V", ACTION_OPEN_DOCUMENT.object()); const auto CATEGORY_OPENABLE = QAndroidJniObject::getStaticObjectField("android/content/Intent", "CATEGORY_OPENABLE"); intent.callObjectMethod("addCategory", "(Ljava/lang/String;)Landroid/content/Intent;", CATEGORY_OPENABLE.object()); intent.callObjectMethod("setType", "(Ljava/lang/String;)Landroid/content/Intent;", QAndroidJniObject::fromString(QStringLiteral("*/*")).object()); QtAndroid::startActivity(intent, 0, &m_activityResultReceiver); #endif } void ApplicationController::importFromClipboard() { if (QGuiApplication::clipboard()->mimeData()->hasUrls()) { const auto urls = QGuiApplication::clipboard()->mimeData()->urls(); for (const auto url : urls) - importLocalFile(url); + importFromUrl(url); } if (QGuiApplication::clipboard()->mimeData()->hasText()) { const auto content = QGuiApplication::clipboard()->text(); const auto data = IataBcbpParser::parse(content, QDate::currentDate()); ExtractorPostprocessor postproc; postproc.process(data); for (const auto &res : postproc.result()) m_resMgr->addReservation(res); return; } } +void ApplicationController::importFromUrl(const QUrl &url) +{ + qCDebug(Log) << url; + + if (url.isLocalFile()) { + importLocalFile(url); + return; + } + + if (url.scheme().startsWith(QLatin1String("http"))) { + if (!m_nam ) { + m_nam = new QNetworkAccessManager(this); + } + auto reqUrl(url); + reqUrl.setScheme(QLatin1String("https")); + QNetworkRequest req(reqUrl); + req.setAttribute(QNetworkRequest::RedirectPolicyAttribute, QNetworkRequest::NoLessSafeRedirectPolicy); + auto reply = m_nam->get(req); + connect(reply, &QNetworkReply::finished, this, [this, reply]() { + if (reply->error() != QNetworkReply::NoError) { + qCDebug(Log) << reply->url() << reply->errorString(); + return; + } + importData(reply->readAll()); + }); + return; + } + + qCDebug(Log) << "Unhandled URL type:" << url; +} + void ApplicationController::importLocalFile(const QUrl &url) { + qCDebug(Log) << url; if (isPkPassFile(url)) { m_pkPassMgr->importPass(url); } else { m_resMgr->importReservation(url); } } void ApplicationController::importData(const QByteArray &data) { + qCDebug(Log); m_resMgr->importReservation(data); } void ApplicationController::checkCalendar() { #ifdef Q_OS_ANDROID const auto activity = QtAndroid::androidActivity(); if (activity.isValid()) { activity.callMethod("checkCalendar"); } #endif } bool ApplicationController::hasClipboardContent() const { return QGuiApplication::clipboard()->mimeData()->hasText() || QGuiApplication::clipboard()->mimeData()->hasUrls(); } diff --git a/src/app/applicationcontroller.h b/src/app/applicationcontroller.h index fafbe34..d3cd343 100644 --- a/src/app/applicationcontroller.h +++ b/src/app/applicationcontroller.h @@ -1,91 +1,95 @@ /* Copyright (C) 2018 Volker Krause 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 of the License, 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 Library General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . */ #ifndef APPLICATIONCONTROLLER_H #define APPLICATIONCONTROLLER_H #include #ifdef Q_OS_ANDROID #include #endif class PkPassManager; class ReservationManager; class QGeoPositionInfo; class QGeoPositionInfoSource; +class QNetworkAccessManager; class ApplicationController : public QObject { Q_OBJECT Q_PROPERTY(bool hasClipboardContent READ hasClipboardContent NOTIFY clipboardContentChanged) public: explicit ApplicationController(QObject *parent = nullptr); ~ApplicationController(); void setReservationManager(ReservationManager *resMgr); void setPkPassManager(PkPassManager *pkPassMgr); // navigation Q_INVOKABLE void showOnMap(const QVariant &place); Q_INVOKABLE bool canNavigateTo(const QVariant &place); Q_INVOKABLE void navigateTo(const QVariant &place); // data import Q_INVOKABLE void showImportFileDialog(); Q_INVOKABLE void importFromClipboard(); + Q_INVOKABLE void importFromUrl(const QUrl &url); #ifdef Q_OS_ANDROID void importFromIntent(const QAndroidJniObject &intent); #endif - void importLocalFile(const QUrl &url); void importData(const QByteArray &data); Q_INVOKABLE void checkCalendar(); static ApplicationController* instance(); bool hasClipboardContent() const; signals: void clipboardContentChanged(); private: + void importLocalFile(const QUrl &url); + static ApplicationController *s_instance; ReservationManager *m_resMgr = nullptr; PkPassManager *m_pkPassMgr = nullptr; + QNetworkAccessManager *m_nam = nullptr; #ifndef Q_OS_ANDROID void navigateTo(const QGeoPositionInfo &from, const QVariant &to); QGeoPositionInfoSource *m_positionSource = nullptr; QMetaObject::Connection m_pendingNavigation; #else class ActivityResultReceiver : public QAndroidActivityResultReceiver { public: explicit inline ActivityResultReceiver(ApplicationController *controller) : m_controller(controller) {} void handleActivityResult(int receiverRequestCode, int resultCode, const QAndroidJniObject &intent) override; private: ApplicationController *m_controller; }; ActivityResultReceiver m_activityResultReceiver; #endif }; #endif // APPLICATIONCONTROLLER_H diff --git a/src/app/main.cpp b/src/app/main.cpp index 4d38ad1..9f6256d 100644 --- a/src/app/main.cpp +++ b/src/app/main.cpp @@ -1,184 +1,190 @@ /* Copyright (C) 2018 Volker Krause 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 of the License, 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 Library General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . */ #include "itinerary_version.h" #include "logging.h" #include "applicationcontroller.h" #include "countryinformation.h" #include "countrymodel.h" #include "localizer.h" #include "pkpassmanager.h" #include "timelinemodel.h" #include "pkpassimageprovider.h" #include "reservationmanager.h" #include "settings.h" #include "tickettokenmodel.h" #include "util.h" #include "weatherforecastmodel.h" #include #include #include #include #include #include #ifndef Q_OS_ANDROID #include #endif #include #include #include #include #ifdef Q_OS_ANDROID #include #include #else #include #endif #include #include #include #include #include #include void handleViewIntent(ApplicationController *appController) { #ifdef Q_OS_ANDROID // handle opened files const auto activity = QtAndroid::androidActivity(); if (!activity.isValid()) return; const auto intent = activity.callObjectMethod("getIntent", "()Landroid/content/Intent;"); appController->importFromIntent(intent); #else Q_UNUSED(appController); #endif } +void handlePositionalArguments(ApplicationController *appController, const QStringList &args) +{ + for (const auto &file : args) { + const auto localUrl = QUrl::fromLocalFile(file); + if (QFile::exists(localUrl.toLocalFile())) + appController->importFromUrl(localUrl); + else + appController->importFromUrl(QUrl::fromUserInput(file)); + } +} #ifdef Q_OS_ANDROID Q_DECL_EXPORT #endif int main(int argc, char **argv) { QCoreApplication::setApplicationName(QStringLiteral("kde-itinerary")); QCoreApplication::setOrganizationName(QStringLiteral("KDE")); QCoreApplication::setOrganizationDomain(QStringLiteral("kde.org")); QCoreApplication::setApplicationVersion(QStringLiteral(ITINERARY_VERSION_STRING)); QGuiApplication::setApplicationDisplayName(i18n("KDE Itinerary")); QGuiApplication::setAttribute(Qt::AA_EnableHighDpiScaling); QGuiApplication::setAttribute(Qt::AA_UseHighDpiPixmaps); #ifdef Q_OS_ANDROID QGuiApplication app(argc, argv); #else QApplication app(argc, argv); // for native file dialogs #endif QGuiApplication::setWindowIcon(QIcon::fromTheme(QStringLiteral("map-globe"))); QCommandLineParser parser; parser.addHelpOption(); parser.addVersionOption(); parser.addPositionalArgument(QStringLiteral("file"), i18n("PkPass or JSON-LD file to import.")); parser.process(app); #ifndef Q_OS_ANDROID KDBusService service(KDBusService::Unique); #endif Settings settings; PkPassManager passMgr; ReservationManager resMgr; resMgr.setPkPassManager(&passMgr); ApplicationController appController; appController.setReservationManager(&resMgr); appController.setPkPassManager(&passMgr); #ifndef Q_OS_ANDROID QObject::connect(&service, &KDBusService::activateRequested, [&parser, &appController](const QStringList &args, const QString &workingDir) { qCDebug(Log) << "remote activation" << args << workingDir; if (!args.isEmpty()) { QDir::setCurrent(workingDir); parser.parse(args); - for (const auto &file : parser.positionalArguments()) { - appController.importLocalFile(QUrl::fromLocalFile(file)); - } + handlePositionalArguments(&appController, parser.positionalArguments()); } if (!QGuiApplication::allWindows().isEmpty()) { QGuiApplication::allWindows().at(0)->requestActivate(); } }); #endif TimelineModel timelineModel; timelineModel.setHomeCountryIsoCode(settings.homeCountryIsoCode()); timelineModel.setReservationManager(&resMgr); QObject::connect(&settings, &Settings::homeCountryIsoCodeChanged, &timelineModel, &TimelineModel::setHomeCountryIsoCode); WeatherForecastManager weatherForecastMgr; weatherForecastMgr.setAllowNetworkAccess(settings.weatherForecastEnabled()); QObject::connect(&settings, &Settings::weatherForecastEnabledChanged, &weatherForecastMgr, &WeatherForecastManager::setAllowNetworkAccess); timelineModel.setWeatherForecastManager(&weatherForecastMgr); qmlRegisterUncreatableType("org.kde.pkpass", 1, 0, "Barcode", {}); qmlRegisterUncreatableType("org.kde.pkpass", 1, 0, "Field", {}); qmlRegisterUncreatableType("org.kde.pkpass", 1, 0, "Pass", {}); qRegisterMetaType(); qmlRegisterUncreatableType("org.kde.kitinerary", 1, 0, "Ticket", {}); qmlRegisterUncreatableMetaObject(KItinerary::KnowledgeDb::staticMetaObject, "org.kde.kitinerary", 1, 0, "KnowledgeDb", {}); qmlRegisterUncreatableType("org.kde.itinerary", 1, 0, "CountryInformation", {}); qmlRegisterType("org.kde.itinerary", 1, 0, "CountryModel"); qmlRegisterSingletonType("org.kde.itinerary", 1, 0, "Localizer", [](QQmlEngine*, QJSEngine*) -> QObject*{ return new Localizer; }); qmlRegisterType("org.kde.itinerary", 1, 0, "TicketTokenModel"); qmlRegisterUncreatableType("org.kde.itinerary", 1, 0, "TimelineModel", {}); qmlRegisterSingletonType("org.kde.itinerary", 1, 0, "Util", [](QQmlEngine*, QJSEngine*) -> QObject*{ return new Util; }); qmlRegisterType("org.kde.itinerary", 1, 0, "WeatherForecastModel"); QQmlApplicationEngine engine; engine.addImageProvider(QStringLiteral("org.kde.pkpass"), new PkPassImageProvider(&passMgr)); engine.rootContext()->setContextObject(new KLocalizedContext(&engine)); engine.rootContext()->setContextProperty(QStringLiteral("_pkpassManager"), &passMgr); engine.rootContext()->setContextProperty(QStringLiteral("_reservationManager"), &resMgr); engine.rootContext()->setContextProperty(QStringLiteral("_timelineModel"), &timelineModel); engine.rootContext()->setContextProperty(QStringLiteral("_appController"), &appController); engine.rootContext()->setContextProperty(QStringLiteral("_settings"), &settings); engine.rootContext()->setContextProperty(QStringLiteral("_weatherForecastManager"), &weatherForecastMgr); engine.load(QStringLiteral("qrc:/main.qml")); - for (const auto &file : parser.positionalArguments()) { - appController.importLocalFile(QUrl::fromLocalFile(file)); - } + handlePositionalArguments(&appController, parser.positionalArguments()); handleViewIntent(&appController); return app.exec(); }