Merge pull request #1290 from Trial97/refactor/NetActions

Refactor ImgurUpload
This commit is contained in:
Alexandru Ionut Tripon 2023-10-21 12:32:16 +01:00 committed by GitHub
commit 2c4af7e793
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
9 changed files with 225 additions and 174 deletions

View File

@ -139,6 +139,7 @@ set(NET_SOURCES
net/HeaderProxy.h
net/RawHeaderProxy.h
net/ApiHeaderProxy.h
net/StaticHeaderProxy.h
net/ApiDownload.h
net/ApiDownload.cpp
net/ApiUpload.cpp

View File

@ -48,6 +48,7 @@
#include "FileSystem.h"
#include "net/ApiDownload.h"
#include "net/ChecksumValidator.h"
#include "net/Download.h"
#include "Application.h"

View File

@ -112,6 +112,8 @@ void NetRequest::executeTask()
m_last_progress_bytes = 0;
QNetworkReply* rep = getReply(request);
if (rep == nullptr) // it failed
return;
m_reply.reset(rep);
connect(rep, &QNetworkReply::downloadProgress, this, &NetRequest::downloadProgress);
connect(rep, &QNetworkReply::finished, this, &NetRequest::downloadFinished);

View File

@ -0,0 +1,39 @@
// SPDX-License-Identifier: GPL-3.0-only
/*
* Prism Launcher - Minecraft Launcher
* Copyright (C) 2023 Rachel Powers <508861+Ryex@users.noreply.github.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* 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 General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
*/
#pragma once
#include "net/HeaderProxy.h"
namespace Net {
class StaticHeaderProxy : public HeaderProxy {
public:
StaticHeaderProxy(QList<HeaderPair> hdrs = {}) : HeaderProxy(), m_hdrs(hdrs){};
virtual ~StaticHeaderProxy() = default;
public:
virtual QList<HeaderPair> headers(const QNetworkRequest&) const override { return m_hdrs; };
void setHeaders(QList<HeaderPair> hdrs) { m_hdrs = hdrs; };
private:
QList<HeaderPair> m_hdrs;
};
} // namespace Net

View File

@ -39,87 +39,76 @@
#include <QDebug>
#include <QJsonDocument>
#include <QJsonObject>
#include <QList>
#include <QNetworkRequest>
#include <QStringList>
#include <QUrl>
#include <memory>
#include "Application.h"
#include "BuildConfig.h"
#include "net/StaticHeaderProxy.h"
ImgurAlbumCreation::ImgurAlbumCreation(QList<ScreenShot::Ptr> screenshots) : NetAction(), m_screenshots(screenshots)
Net::NetRequest::Ptr ImgurAlbumCreation::make(std::shared_ptr<ImgurAlbumCreation::Result> output, QList<ScreenShot::Ptr> screenshots)
{
m_url = BuildConfig.IMGUR_BASE_URL + "album.json";
m_state = State::Inactive;
auto up = makeShared<ImgurAlbumCreation>();
up->m_url = BuildConfig.IMGUR_BASE_URL + "album.json";
up->m_sink.reset(new Sink(output));
up->m_screenshots = screenshots;
return up;
}
void ImgurAlbumCreation::executeTask()
QNetworkReply* ImgurAlbumCreation::getReply(QNetworkRequest& request)
{
m_state = State::Running;
QNetworkRequest request(m_url);
request.setHeader(QNetworkRequest::UserAgentHeader, APPLICATION->getUserAgentUncached().toUtf8());
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
request.setRawHeader("Authorization", QString("Client-ID %1").arg(BuildConfig.IMGUR_CLIENT_ID).toStdString().c_str());
request.setRawHeader("Accept", "application/json");
QStringList hashes;
for (auto shot : m_screenshots) {
hashes.append(shot->m_imgurDeleteHash);
}
const QByteArray data = "deletehashes=" + hashes.join(',').toUtf8() + "&title=Minecraft%20Screenshots&privacy=hidden";
return m_network->post(request, data);
};
QNetworkReply* rep = APPLICATION->network()->post(request, data);
m_reply.reset(rep);
connect(rep, &QNetworkReply::uploadProgress, this, &ImgurAlbumCreation::downloadProgress);
connect(rep, &QNetworkReply::finished, this, &ImgurAlbumCreation::downloadFinished);
#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0) // QNetworkReply::errorOccurred added in 5.15
connect(rep, &QNetworkReply::errorOccurred, this, &ImgurAlbumCreation::downloadError);
#else
connect(rep, QOverload<QNetworkReply::NetworkError>::of(&QNetworkReply::error), this, &ImgurAlbumCreation::downloadError);
#endif
connect(rep, &QNetworkReply::sslErrors, this, &ImgurAlbumCreation::sslErrors);
void ImgurAlbumCreation::init()
{
qDebug() << "Setting up imgur upload";
auto api_headers = new Net::StaticHeaderProxy(
QList<Net::HeaderPair>{ { "Content-Type", "application/x-www-form-urlencoded" },
{ "Authorization", QString("Client-ID %1").arg(BuildConfig.IMGUR_CLIENT_ID).toStdString().c_str() },
{ "Accept", "application/json" } });
addHeaderProxy(api_headers);
}
void ImgurAlbumCreation::downloadError([[maybe_unused]] QNetworkReply::NetworkError error)
auto ImgurAlbumCreation::Sink::init(QNetworkRequest& request) -> Task::State
{
qDebug() << m_reply->errorString();
m_state = State::Failed;
m_output.clear();
return Task::State::Running;
};
auto ImgurAlbumCreation::Sink::write(QByteArray& data) -> Task::State
{
m_output.append(data);
return Task::State::Running;
}
void ImgurAlbumCreation::downloadFinished()
auto ImgurAlbumCreation::Sink::abort() -> Task::State
{
m_output.clear();
return Task::State::Failed;
}
auto ImgurAlbumCreation::Sink::finalize(QNetworkReply&) -> Task::State
{
if (m_state != State::Failed) {
QByteArray data = m_reply->readAll();
m_reply.reset();
QJsonParseError jsonError;
QJsonDocument doc = QJsonDocument::fromJson(data, &jsonError);
QJsonDocument doc = QJsonDocument::fromJson(m_output, &jsonError);
if (jsonError.error != QJsonParseError::NoError) {
qDebug() << jsonError.errorString();
emitFailed();
return;
return Task::State::Failed;
}
auto object = doc.object();
if (!object.value("success").toBool()) {
qDebug() << doc.toJson();
emitFailed();
return;
return Task::State::Failed;
}
m_deleteHash = object.value("data").toObject().value("deletehash").toString();
m_id = object.value("data").toObject().value("id").toString();
m_state = State::Succeeded;
emit succeeded();
return;
} else {
qDebug() << m_reply->readAll();
m_reply.reset();
emitFailed();
return;
}
}
void ImgurAlbumCreation::downloadProgress(qint64 bytesReceived, qint64 bytesTotal)
{
setProgress(bytesReceived, bytesTotal);
emit progress(bytesReceived, bytesTotal);
m_result->deleteHash = object.value("data").toObject().value("deletehash").toString();
m_result->id = object.value("data").toObject().value("id").toString();
return Task::State::Succeeded;
}

View File

@ -36,34 +36,39 @@
#pragma once
#include "Screenshot.h"
#include "net/NetAction.h"
#include "net/NetRequest.h"
typedef shared_qobject_ptr<class ImgurAlbumCreation> ImgurAlbumCreationPtr;
class ImgurAlbumCreation : public NetAction {
class ImgurAlbumCreation : public Net::NetRequest {
public:
explicit ImgurAlbumCreation(QList<ScreenShot::Ptr> screenshots);
static ImgurAlbumCreationPtr make(QList<ScreenShot::Ptr> screenshots)
{
return ImgurAlbumCreationPtr(new ImgurAlbumCreation(screenshots));
}
virtual ~ImgurAlbumCreation() = default;
QString deleteHash() const { return m_deleteHash; }
QString id() const { return m_id; }
struct Result {
QString deleteHash;
QString id;
};
void init() override{};
class Sink : public Net::Sink {
public:
Sink(std::shared_ptr<Result> res) : m_result(res){};
virtual ~Sink() = default;
protected slots:
void downloadProgress(qint64 bytesReceived, qint64 bytesTotal) override;
void downloadError(QNetworkReply::NetworkError error) override;
void downloadFinished() override;
void downloadReadyRead() override {}
public:
auto init(QNetworkRequest& request) -> Task::State override;
auto write(QByteArray& data) -> Task::State override;
auto abort() -> Task::State override;
auto finalize(QNetworkReply& reply) -> Task::State override;
auto hasLocalData() -> bool override { return false; }
public slots:
void executeTask() override;
private:
std::shared_ptr<Result> m_result;
QByteArray m_output;
};
static NetRequest::Ptr make(std::shared_ptr<Result> output, QList<ScreenShot::Ptr> screenshots);
QNetworkReply* getReply(QNetworkRequest& request) override;
void init() override;
private:
QList<ScreenShot::Ptr> m_screenshots;
QString m_deleteHash;
QString m_id;
};

View File

@ -35,8 +35,8 @@
*/
#include "ImgurUpload.h"
#include "Application.h"
#include "BuildConfig.h"
#include "net/StaticHeaderProxy.h"
#include <QDebug>
#include <QFile>
@ -47,104 +47,84 @@
#include <QNetworkRequest>
#include <QUrl>
ImgurUpload::ImgurUpload(ScreenShot::Ptr shot) : NetAction(), m_shot(shot)
void ImgurUpload::init()
{
m_url = BuildConfig.IMGUR_BASE_URL + "upload.json";
m_state = State::Inactive;
qDebug() << "Setting up imgur upload";
auto api_headers = new Net::StaticHeaderProxy(
QList<Net::HeaderPair>{ { "Authorization", QString("Client-ID %1").arg(BuildConfig.IMGUR_CLIENT_ID).toStdString().c_str() },
{ "Accept", "application/json" } });
addHeaderProxy(api_headers);
}
void ImgurUpload::executeTask()
QNetworkReply* ImgurUpload::getReply(QNetworkRequest& request)
{
finished = false;
m_state = Task::State::Running;
QNetworkRequest request(m_url);
request.setHeader(QNetworkRequest::UserAgentHeader, APPLICATION->getUserAgentUncached().toUtf8());
request.setRawHeader("Authorization", QString("Client-ID %1").arg(BuildConfig.IMGUR_CLIENT_ID).toStdString().c_str());
request.setRawHeader("Accept", "application/json");
auto file = new QFile(m_fileInfo.absoluteFilePath());
QFile f(m_shot->m_file.absoluteFilePath());
if (!f.open(QFile::ReadOnly)) {
if (!file->open(QFile::ReadOnly)) {
emitFailed();
return;
return nullptr;
}
QHttpMultiPart* multipart = new QHttpMultiPart(QHttpMultiPart::FormDataType);
file->setParent(multipart);
QHttpPart filePart;
filePart.setBody(f.readAll().toBase64());
filePart.setBodyDevice(file);
filePart.setHeader(QNetworkRequest::ContentTypeHeader, "image/png");
filePart.setHeader(QNetworkRequest::ContentDispositionHeader, "form-data; name=\"image\"");
multipart->append(filePart);
QHttpPart typePart;
typePart.setHeader(QNetworkRequest::ContentDispositionHeader, "form-data; name=\"type\"");
typePart.setBody("base64");
typePart.setBody("file");
multipart->append(typePart);
QHttpPart namePart;
namePart.setHeader(QNetworkRequest::ContentDispositionHeader, "form-data; name=\"name\"");
namePart.setBody(m_shot->m_file.baseName().toUtf8());
namePart.setBody(m_fileInfo.baseName().toUtf8());
multipart->append(namePart);
QNetworkReply* rep = m_network->post(request, multipart);
return m_network->post(request, multipart);
};
m_reply.reset(rep);
connect(rep, &QNetworkReply::uploadProgress, this, &ImgurUpload::downloadProgress);
connect(rep, &QNetworkReply::finished, this, &ImgurUpload::downloadFinished);
#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0) // QNetworkReply::errorOccurred added in 5.15
connect(rep, &QNetworkReply::errorOccurred, this, &ImgurUpload::downloadError);
#else
connect(rep, QOverload<QNetworkReply::NetworkError>::of(&QNetworkReply::error), this, &ImgurUpload::downloadError);
#endif
connect(rep, &QNetworkReply::sslErrors, this, &ImgurUpload::sslErrors);
}
void ImgurUpload::downloadError([[maybe_unused]] QNetworkReply::NetworkError error)
auto ImgurUpload::Sink::init(QNetworkRequest& request) -> Task::State
{
qCritical() << "ImgurUpload failed with error" << m_reply->errorString() << "Server reply:\n" << m_reply->readAll();
if (finished) {
qCritical() << "Double finished ImgurUpload!";
return;
}
m_state = Task::State::Failed;
finished = true;
m_reply.reset();
emitFailed();
m_output.clear();
return Task::State::Running;
};
auto ImgurUpload::Sink::write(QByteArray& data) -> Task::State
{
m_output.append(data);
return Task::State::Running;
}
void ImgurUpload::downloadFinished()
auto ImgurUpload::Sink::abort() -> Task::State
{
if (finished) {
qCritical() << "Double finished ImgurUpload!";
return;
m_output.clear();
return Task::State::Failed;
}
QByteArray data = m_reply->readAll();
m_reply.reset();
auto ImgurUpload::Sink::finalize(QNetworkReply&) -> Task::State
{
QJsonParseError jsonError;
QJsonDocument doc = QJsonDocument::fromJson(data, &jsonError);
QJsonDocument doc = QJsonDocument::fromJson(m_output, &jsonError);
if (jsonError.error != QJsonParseError::NoError) {
qDebug() << "imgur server did not reply with JSON" << jsonError.errorString();
finished = true;
m_reply.reset();
emitFailed();
return;
return Task::State::Failed;
}
auto object = doc.object();
if (!object.value("success").toBool()) {
qDebug() << "Screenshot upload not successful:" << doc.toJson();
finished = true;
m_reply.reset();
emitFailed();
return;
return Task::State::Failed;
}
m_shot->m_imgurId = object.value("data").toObject().value("id").toString();
m_shot->m_url = object.value("data").toObject().value("link").toString();
m_shot->m_imgurDeleteHash = object.value("data").toObject().value("deletehash").toString();
m_state = Task::State::Succeeded;
finished = true;
emit succeeded();
return;
return Task::State::Succeeded;
}
void ImgurUpload::downloadProgress(qint64 bytesReceived, qint64 bytesTotal)
Net::NetRequest::Ptr ImgurUpload::make(ScreenShot::Ptr m_shot)
{
setProgress(bytesReceived, bytesTotal);
emit progress(bytesReceived, bytesTotal);
auto up = makeShared<ImgurUpload>(m_shot->m_file);
up->m_url = std::move(BuildConfig.IMGUR_BASE_URL + "upload.json");
up->m_sink.reset(new Sink(m_shot));
return up;
}

View File

@ -35,27 +35,36 @@
#pragma once
#include <QFileInfo>
#include "Screenshot.h"
#include "net/NetAction.h"
#include "net/NetRequest.h"
class ImgurUpload : public NetAction {
class ImgurUpload : public Net::NetRequest {
public:
using Ptr = shared_qobject_ptr<ImgurUpload>;
class Sink : public Net::Sink {
public:
Sink(ScreenShot::Ptr shot) : m_shot(shot){};
virtual ~Sink() = default;
explicit ImgurUpload(ScreenShot::Ptr shot);
static Ptr make(ScreenShot::Ptr shot) { return Ptr(new ImgurUpload(shot)); }
void init() override{};
protected slots:
void downloadProgress(qint64 bytesReceived, qint64 bytesTotal) override;
void downloadError(QNetworkReply::NetworkError error) override;
void downloadFinished() override;
void downloadReadyRead() override {}
public slots:
void executeTask() override;
public:
auto init(QNetworkRequest& request) -> Task::State override;
auto write(QByteArray& data) -> Task::State override;
auto abort() -> Task::State override;
auto finalize(QNetworkReply& reply) -> Task::State override;
auto hasLocalData() -> bool override { return false; }
private:
ScreenShot::Ptr m_shot;
bool finished = true;
QByteArray m_output;
};
ImgurUpload(QFileInfo info) : m_fileInfo(info) {}
virtual ~ImgurUpload() = default;
static NetRequest::Ptr make(ScreenShot::Ptr m_shot);
void init() override;
private:
virtual QNetworkReply* getReply(QNetworkRequest&) override;
const QFileInfo m_fileInfo;
};

View File

@ -383,20 +383,31 @@ void ScreenshotsPage::on_actionUpload_triggered()
QList<ScreenShot::Ptr> uploaded;
auto job = NetJob::Ptr(new NetJob("Screenshot Upload", APPLICATION->network()));
ProgressDialog dialog(this);
dialog.setSkipButton(true, tr("Abort"));
if (selection.size() < 2) {
auto item = selection.at(0);
auto info = m_model->fileInfo(item);
auto screenshot = std::make_shared<ScreenShot>(info);
job->addNetAction(ImgurUpload::make(screenshot));
m_uploadActive = true;
ProgressDialog dialog(this);
connect(job.get(), &Task::failed, [this](QString reason) {
CustomMessageBox::selectable(this, tr("Failed to upload screenshots!"), reason, QMessageBox::Critical)->show();
});
connect(job.get(), &Task::aborted, [this] {
CustomMessageBox::selectable(this, tr("Screenshots upload aborted"), tr("The task has been aborted by the user."),
QMessageBox::Information)
->show();
});
if (dialog.execWithTask(job.get()) != QDialog::Accepted) {
CustomMessageBox::selectable(this, tr("Failed to upload screenshots!"), tr("Unknown error"), QMessageBox::Warning)->exec();
} else {
m_uploadActive = true;
if (dialog.execWithTask(job.get()) == QDialog::Accepted) {
auto link = screenshot->m_url;
QClipboard* clipboard = QApplication::clipboard();
qDebug() << "ImgurUpload link" << link;
clipboard->setText(link);
CustomMessageBox::selectable(
this, tr("Upload finished"),
@ -417,23 +428,37 @@ void ScreenshotsPage::on_actionUpload_triggered()
}
SequentialTask task;
auto albumTask = NetJob::Ptr(new NetJob("Imgur Album Creation", APPLICATION->network()));
auto imgurAlbum = ImgurAlbumCreation::make(uploaded);
auto imgurResult = std::make_shared<ImgurAlbumCreation::Result>();
auto imgurAlbum = ImgurAlbumCreation::make(imgurResult, uploaded);
albumTask->addNetAction(imgurAlbum);
task.addTask(job);
task.addTask(albumTask);
connect(&task, &Task::failed, [this](QString reason) {
CustomMessageBox::selectable(this, tr("Failed to upload screenshots!"), reason, QMessageBox::Critical)->show();
});
connect(&task, &Task::aborted, [this] {
CustomMessageBox::selectable(this, tr("Screenshots upload aborted"), tr("The task has been aborted by the user."),
QMessageBox::Information)
->show();
});
m_uploadActive = true;
ProgressDialog prog(this);
if (prog.execWithTask(&task) != QDialog::Accepted) {
if (dialog.execWithTask(&task) == QDialog::Accepted) {
if (imgurResult->id.isEmpty()) {
CustomMessageBox::selectable(this, tr("Failed to upload screenshots!"), tr("Unknown error"), QMessageBox::Warning)->exec();
} else {
auto link = QString("https://imgur.com/a/%1").arg(imgurAlbum->id());
auto link = QString("https://imgur.com/a/%1").arg(imgurResult->id);
qDebug() << "ImgurUpload link" << link;
QClipboard* clipboard = QApplication::clipboard();
clipboard->setText(link);
CustomMessageBox::selectable(this, tr("Upload finished"),
CustomMessageBox::selectable(
this, tr("Upload finished"),
tr("The <a href=\"%1\">link to the uploaded album</a> has been placed in your clipboard.").arg(link),
QMessageBox::Information)
->exec();
}
}
m_uploadActive = false;
}