File indexing completed on 2024-05-19 04:59:17

0001 /* ============================================================
0002 * KDEFrameworksIntegration - KDE support plugin for Falkon
0003 * Copyright (C) 2018 David Rosca <nowrep@gmail.com>
0004 *
0005 * This program is free software: you can redistribute it and/or modify
0006 * it under the terms of the GNU General Public License as published by
0007 * the Free Software Foundation, either version 3 of the License, or
0008 * (at your option) any later version.
0009 *
0010 * This program is distributed in the hope that it will be useful,
0011 * but WITHOUT ANY WARRANTY; without even the implied warranty of
0012 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
0013 * GNU General Public License for more details.
0014 *
0015 * You should have received a copy of the GNU General Public License
0016 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
0017 * ============================================================ */
0018 #include "kioschemehandler.h"
0019 
0020 #include <QBuffer>
0021 #include <QPointer>
0022 #include <QNetworkReply>
0023 #include <QWebEngineUrlRequestJob>
0024 
0025 #include <kio_version.h>
0026 
0027 #include <QNetworkAccessManager>
0028 Q_GLOBAL_STATIC_WITH_ARGS(QNetworkAccessManager, s_knam, (nullptr))
0029 
0030 KIOSchemeHandler::KIOSchemeHandler(const QString &protocol, QObject *parent)
0031     : QWebEngineUrlSchemeHandler(parent)
0032     , m_protocol(protocol)
0033 {
0034 }
0035 
0036 QString KIOSchemeHandler::protocol() const
0037 {
0038     return m_protocol;
0039 }
0040 
0041 void KIOSchemeHandler::requestStarted(QWebEngineUrlRequestJob *job)
0042 {
0043     if (job->requestMethod() != QByteArray("GET")) {
0044         qWarning() << "Unsupported method" << job->requestMethod();
0045         job->fail(QWebEngineUrlRequestJob::RequestFailed);
0046         return;
0047     }
0048 
0049     QPointer<QWebEngineUrlRequestJob> jobPtr = job;
0050     QNetworkReply *reply = s_knam()->get(QNetworkRequest(job->requestUrl()));
0051     connect(reply, &QNetworkReply::finished, this, [=]() {
0052         if (!jobPtr) {
0053             reply->deleteLater();
0054             return;
0055         }
0056         if (reply->error() != QNetworkReply::NoError) {
0057             reply->deleteLater();
0058             qWarning() << "Error:" << reply->errorString();
0059             job->fail(QWebEngineUrlRequestJob::RequestFailed);
0060         } else {
0061             reply->setParent(job);
0062             job->reply(reply->header(QNetworkRequest::ContentTypeHeader).toByteArray(), reply);
0063         }
0064     });
0065 }