Merge branch 'feature_screenshots' into integration_json_and_tools

Conflicts:
	logic/net/URLConstants.h

Resolve issues with multiple definitions of URL constants by moving them to their own object file.
This commit is contained in:
Petr Mrázek 2014-02-25 01:52:58 +01:00
commit acff155624
23 changed files with 969 additions and 170 deletions

View File

@ -308,6 +308,8 @@ gui/dialogs/AccountSelectDialog.h
gui/dialogs/AccountSelectDialog.cpp gui/dialogs/AccountSelectDialog.cpp
gui/dialogs/UpdateDialog.h gui/dialogs/UpdateDialog.h
gui/dialogs/UpdateDialog.cpp gui/dialogs/UpdateDialog.cpp
gui/dialogs/ScreenshotDialog.h
gui/dialogs/ScreenshotDialog.cpp
# GUI - widgets # GUI - widgets
gui/widgets/Common.h gui/widgets/Common.h
@ -370,6 +372,7 @@ logic/net/HttpMetaCache.cpp
logic/net/PasteUpload.h logic/net/PasteUpload.h
logic/net/PasteUpload.cpp logic/net/PasteUpload.cpp
logic/net/URLConstants.h logic/net/URLConstants.h
logic/net/URLConstants.cpp
# Yggdrasil login stuff # Yggdrasil login stuff
logic/auth/AuthSession.h logic/auth/AuthSession.h
@ -463,6 +466,16 @@ logic/lists/JavaVersionList.cpp
logic/lists/LiteLoaderVersionList.h logic/lists/LiteLoaderVersionList.h
logic/lists/LiteLoaderVersionList.cpp logic/lists/LiteLoaderVersionList.cpp
# the screenshots feature
logic/screenshots/Screenshot.h
logic/screenshots/Screenshot.cpp
logic/screenshots/ScreenshotList.h
logic/screenshots/ScreenshotList.cpp
logic/screenshots/ImgurUpload.h
logic/screenshots/ImgurUpload.cpp
logic/screenshots/ImgurAlbumCreation.h
logic/screenshots/ImgurAlbumCreation.cpp
# Icons # Icons
logic/icons/MMCIcon.h logic/icons/MMCIcon.h
logic/icons/MMCIcon.cpp logic/icons/MMCIcon.cpp
@ -539,6 +552,7 @@ gui/dialogs/AccountListDialog.ui
gui/dialogs/AccountSelectDialog.ui gui/dialogs/AccountSelectDialog.ui
gui/dialogs/EditAccountDialog.ui gui/dialogs/EditAccountDialog.ui
gui/dialogs/UpdateDialog.ui gui/dialogs/UpdateDialog.ui
gui/dialogs/ScreenshotDialog.ui
# Widgets/other # Widgets/other
gui/widgets/MCModInfoFrame.ui gui/widgets/MCModInfoFrame.ui

View File

@ -42,6 +42,8 @@ ConsoleWindow::ConsoleWindow(MinecraftProcess *mcproc, QWidget *parent)
connect(mcproc, SIGNAL(launch_failed(BaseInstance *)), this, connect(mcproc, SIGNAL(launch_failed(BaseInstance *)), this,
SLOT(onLaunchFailed(BaseInstance *))); SLOT(onLaunchFailed(BaseInstance *)));
connect(ui->btnScreenshots, &QPushButton::clicked, this, &ConsoleWindow::uploadScreenshots);
restoreState( restoreState(
QByteArray::fromBase64(MMC->settings()->get("ConsoleWindowState").toByteArray())); QByteArray::fromBase64(MMC->settings()->get("ConsoleWindowState").toByteArray()));
restoreGeometry( restoreGeometry(
@ -52,6 +54,7 @@ ConsoleWindow::ConsoleWindow(MinecraftProcess *mcproc, QWidget *parent)
auto icon = MMC->icons()->getIcon(iconKey); auto icon = MMC->icons()->getIcon(iconKey);
setWindowIcon(icon); setWindowIcon(icon);
m_trayIcon = new QSystemTrayIcon(icon, this); m_trayIcon = new QSystemTrayIcon(icon, this);
// TODO add screenshot upload as a menu item in the tray icon
QString consoleTitle = tr("Console window for ") + name; QString consoleTitle = tr("Console window for ") + name;
m_trayIcon->setToolTip(consoleTitle); m_trayIcon->setToolTip(consoleTitle);
setWindowTitle(consoleTitle); setWindowTitle(consoleTitle);

View File

@ -51,6 +51,7 @@ private:
signals: signals:
void isClosing(); void isClosing();
void uploadScreenshots();
public public
slots: slots:

View File

@ -49,6 +49,13 @@
</property> </property>
</widget> </widget>
</item> </item>
<item>
<widget class="QPushButton" name="btnScreenshots">
<property name="text">
<string>Manage Screenshots</string>
</property>
</widget>
</item>
<item> <item>
<spacer name="horizontalSpacer"> <spacer name="horizontalSpacer">
<property name="orientation"> <property name="orientation">

View File

@ -44,7 +44,6 @@
#include "gui/Platform.h" #include "gui/Platform.h"
#include "gui/widgets/LabeledToolButton.h" #include "gui/widgets/LabeledToolButton.h"
#include "gui/dialogs/SettingsDialog.h" #include "gui/dialogs/SettingsDialog.h"
@ -62,6 +61,7 @@
#include "gui/dialogs/AccountSelectDialog.h" #include "gui/dialogs/AccountSelectDialog.h"
#include "gui/dialogs/UpdateDialog.h" #include "gui/dialogs/UpdateDialog.h"
#include "gui/dialogs/EditAccountDialog.h" #include "gui/dialogs/EditAccountDialog.h"
#include "gui/dialogs/ScreenshotDialog.h"
#include "gui/ConsoleWindow.h" #include "gui/ConsoleWindow.h"
@ -81,6 +81,7 @@
#include "logic/status/StatusChecker.h" #include "logic/status/StatusChecker.h"
#include "logic/net/URLConstants.h" #include "logic/net/URLConstants.h"
#include "logic/net/NetJob.h"
#include "logic/BaseInstance.h" #include "logic/BaseInstance.h"
#include "logic/InstanceFactory.h" #include "logic/InstanceFactory.h"
@ -146,7 +147,6 @@ MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWi
{ {
view = new GroupView(ui->centralWidget); view = new GroupView(ui->centralWidget);
view->setSelectionMode(QAbstractItemView::SingleSelection); view->setSelectionMode(QAbstractItemView::SingleSelection);
// view->setCategoryDrawer(drawer); // view->setCategoryDrawer(drawer);
// view->setCollapsibleBlocks(true); // view->setCollapsibleBlocks(true);
@ -1284,6 +1284,7 @@ void MainWindow::launchInstance(BaseInstance *instance, AuthSessionPtr session,
console = new ConsoleWindow(proc); console = new ConsoleWindow(proc);
connect(console, SIGNAL(isClosing()), this, SLOT(instanceEnded())); connect(console, SIGNAL(isClosing()), this, SLOT(instanceEnded()));
connect(console, &ConsoleWindow::uploadScreenshots, this, &MainWindow::on_actionScreenshots_triggered);
proc->setLogin(session); proc->setLogin(session);
proc->arm(); proc->arm();
@ -1600,3 +1601,25 @@ void MainWindow::checkSetDefaultJava()
MMC->settings()->set("JavaPath", QString("java")); MMC->settings()->set("JavaPath", QString("java"));
} }
} }
void MainWindow::on_actionScreenshots_triggered()
{
if (!m_selectedInstance)
return;
ScreenshotList *list = new ScreenshotList(m_selectedInstance);
Task *task = list->load();
ProgressDialog prog(this);
prog.exec(task);
if (!task->successful())
{
CustomMessageBox::selectable(this, tr("Failed to load screenshots!"),
task->failReason(), QMessageBox::Warning)->exec();
return;
}
ScreenshotDialog dialog(list, this);
if (dialog.exec() == ScreenshotDialog::Accepted)
{
CustomMessageBox::selectable(this, tr("Done uploading!"), dialog.message(),
QMessageBox::Information)->exec();
}
}

View File

@ -139,7 +139,9 @@ slots:
// called when an icon is changed in the icon model. // called when an icon is changed in the icon model.
void iconUpdated(QString); void iconUpdated(QString);
void showInstanceContextMenu(const QPoint&); void showInstanceContextMenu(const QPoint &);
void on_actionScreenshots_triggered();
void updateToolsMenu(); void updateToolsMenu();
@ -174,7 +176,7 @@ slots:
/*! /*!
* Runs the DownloadUpdateTask and installs updates. * Runs the DownloadUpdateTask and installs updates.
*/ */
void downloadUpdates(QString repo, int versionId, bool installOnExit=false); void downloadUpdates(QString repo, int versionId, bool installOnExit = false);
protected: protected:
bool eventFilter(QObject *obj, QEvent *ev); bool eventFilter(QObject *obj, QEvent *ev);
@ -191,7 +193,7 @@ private:
ConsoleWindow *console; ConsoleWindow *console;
LabeledToolButton *renameButton; LabeledToolButton *renameButton;
QToolButton *changeIconButton; QToolButton *changeIconButton;
QToolButton* newsLabel; QToolButton *newsLabel;
BaseInstance *m_selectedInstance; BaseInstance *m_selectedInstance;
QString m_currentInstIcon; QString m_currentInstIcon;

View File

@ -112,6 +112,8 @@
<addaction name="actionEditInstNotes"/> <addaction name="actionEditInstNotes"/>
<addaction name="actionChangeInstGroup"/> <addaction name="actionChangeInstGroup"/>
<addaction name="separator"/> <addaction name="separator"/>
<addaction name="actionScreenshots"/>
<addaction name="separator"/>
<addaction name="actionInstanceSettings"/> <addaction name="actionInstanceSettings"/>
<addaction name="actionChangeInstMCVersion"/> <addaction name="actionChangeInstMCVersion"/>
<addaction name="actionChangeInstLWJGLVersion"/> <addaction name="actionChangeInstLWJGLVersion"/>
@ -528,6 +530,14 @@
<string>Launch the selected instance.</string> <string>Launch the selected instance.</string>
</property> </property>
</action> </action>
<action name="actionScreenshots">
<property name="text">
<string>Manage Screenshots</string>
</property>
<property name="toolTip">
<string>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;View and upload screenshots for this instance&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
</property>
</action>
</widget> </widget>
<layoutdefault spacing="6" margin="11"/> <layoutdefault spacing="6" margin="11"/>
<resources> <resources>

View File

@ -28,6 +28,7 @@ QMessageBox *selectable(QWidget *parent, const QString &title, const QString &te
messageBox->setDefaultButton(defaultButton); messageBox->setDefaultButton(defaultButton);
messageBox->setTextInteractionFlags(Qt::TextSelectableByMouse); messageBox->setTextInteractionFlags(Qt::TextSelectableByMouse);
messageBox->setIcon(icon); messageBox->setIcon(icon);
messageBox->setTextInteractionFlags(Qt::TextBrowserInteraction);
return messageBox; return messageBox;
} }

View File

@ -0,0 +1,78 @@
#include "ScreenshotDialog.h"
#include "ui_ScreenshotDialog.h"
#include <QModelIndex>
#include <QMutableListIterator>
#include "ProgressDialog.h"
#include "CustomMessageBox.h"
#include "logic/net/NetJob.h"
#include "logic/screenshots/ImgurUpload.h"
#include "logic/screenshots/ImgurAlbumCreation.h"
#include "logic/tasks/SequentialTask.h"
ScreenshotDialog::ScreenshotDialog(ScreenshotList *list, QWidget *parent)
: QDialog(parent), ui(new Ui::ScreenshotDialog), m_list(list)
{
ui->setupUi(this);
ui->listView->setModel(m_list);
}
ScreenshotDialog::~ScreenshotDialog()
{
delete ui;
}
QString ScreenshotDialog::message() const
{
return tr("<a href=\"https://imgur.com/a/%1\">Visit album</a><br/>Delete hash: %2 (save "
"this if you want to be able to edit/delete the album)")
.arg(m_imgurAlbum->id(), m_imgurAlbum->deleteHash());
}
QList<ScreenshotPtr> ScreenshotDialog::selected() const
{
QList<ScreenshotPtr> list;
QList<ScreenshotPtr> first = m_list->screenshots();
for (QModelIndex index : ui->listView->selectionModel()->selectedRows())
{
list.append(first.at(index.row()));
}
return list;
}
void ScreenshotDialog::on_uploadBtn_clicked()
{
m_uploaded = selected();
if (m_uploaded.isEmpty())
{
done(NothingDone);
return;
}
SequentialTask *task = new SequentialTask(this);
NetJob *job = new NetJob("Screenshot Upload");
for (auto shot : m_uploaded)
{
job->addNetAction(ImgurUpload::make(shot));
}
NetJob *albumTask = new NetJob("Imgur Album Creation");
albumTask->addNetAction(m_imgurAlbum = ImgurAlbumCreation::make(m_uploaded));
task->addTask(NetJobPtr(job));
task->addTask(NetJobPtr(albumTask));
ProgressDialog prog(this);
if (prog.exec(task) == QDialog::Accepted)
{
accept();
}
else
{
CustomMessageBox::selectable(this, tr("Failed to upload screenshots!"),
tr("Unknown error"), QMessageBox::Warning)->exec();
reject();
}
}
void ScreenshotDialog::on_deleteBtn_clicked()
{
m_list->deleteSelected(this);
}

View File

@ -0,0 +1,40 @@
#pragma once
#include <QDialog>
#include "logic/screenshots/ScreenshotList.h"
class ImgurAlbumCreation;
namespace Ui
{
class ScreenshotDialog;
}
class ScreenshotDialog : public QDialog
{
Q_OBJECT
public:
explicit ScreenshotDialog(ScreenshotList *list, QWidget *parent = 0);
~ScreenshotDialog();
enum
{
NothingDone = 0x42
};
QString message() const;
QList<ScreenshotPtr> selected() const;
private
slots:
void on_uploadBtn_clicked();
void on_deleteBtn_clicked();
private:
Ui::ScreenshotDialog *ui;
ScreenshotList *m_list;
QList<ScreenshotPtr> m_uploaded;
std::shared_ptr<ImgurAlbumCreation> m_imgurAlbum;
};

View File

@ -0,0 +1,110 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>ScreenshotDialog</class>
<widget class="QDialog" name="ScreenshotDialog">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>470</width>
<height>300</height>
</rect>
</property>
<property name="windowTitle">
<string>Screenshot Manager</string>
</property>
<property name="windowIcon">
<iconset resource="../../resources/multimc/multimc.qrc">
<normaloff>:/icons/multimc/scalable/apps/multimc.svg</normaloff>:/icons/multimc/scalable/apps/multimc.svg</iconset>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="QListView" name="listView">
<property name="selectionMode">
<enum>QAbstractItemView::ExtendedSelection</enum>
</property>
<property name="selectionBehavior">
<enum>QAbstractItemView::SelectItems</enum>
</property>
<property name="iconSize">
<size>
<width>120</width>
<height>90</height>
</size>
</property>
<property name="flow">
<enum>QListView::LeftToRight</enum>
</property>
<property name="isWrapping" stdset="0">
<bool>true</bool>
</property>
<property name="resizeMode">
<enum>QListView::Adjust</enum>
</property>
<property name="viewMode">
<enum>QListView::IconMode</enum>
</property>
</widget>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout">
<item>
<widget class="QPushButton" name="uploadBtn">
<property name="text">
<string>Upload</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="deleteBtn">
<property name="text">
<string>Delete</string>
</property>
</widget>
</item>
<item>
<spacer name="horizontalSpacer">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>40</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
<item>
<widget class="QPushButton" name="closeBtn">
<property name="text">
<string>Close</string>
</property>
</widget>
</item>
</layout>
</item>
</layout>
</widget>
<resources>
<include location="../../resources/multimc/multimc.qrc"/>
</resources>
<connections>
<connection>
<sender>closeBtn</sender>
<signal>clicked()</signal>
<receiver>ScreenshotDialog</receiver>
<slot>reject()</slot>
<hints>
<hint type="sourcelabel">
<x>315</x>
<y>272</y>
</hint>
<hint type="destinationlabel">
<x>271</x>
<y>258</y>
</hint>
</hints>
</connection>
</connections>
</ui>

View File

@ -0,0 +1,19 @@
#include "URLConstants.h"
namespace URLConstants
{
const QString AWS_DOWNLOAD_BASE("s3.amazonaws.com/Minecraft.Download/");
const QString AWS_DOWNLOAD_VERSIONS(AWS_DOWNLOAD_BASE + "versions/");
const QString AWS_DOWNLOAD_LIBRARIES(AWS_DOWNLOAD_BASE + "libraries/");
const QString AWS_DOWNLOAD_INDEXES(AWS_DOWNLOAD_BASE + "indexes/");
const QString ASSETS_BASE("assets.minecraft.net/");
const QString RESOURCE_BASE("resources.download.minecraft.net/");
const QString LIBRARY_BASE("libraries.minecraft.net/");
const QString SKINS_BASE("skins.minecraft.net/MinecraftSkins/");
const QString AUTH_BASE("authserver.mojang.com/");
const QString FORGE_LEGACY_URL("http://files.minecraftforge.net/minecraftforge/json");
const QString FORGE_GRADLE_URL("http://files.minecraftforge.net/maven/net/minecraftforge/forge/json");
const QString MOJANG_STATUS_URL("http://status.mojang.com/check");
const QString MOJANG_STATUS_NEWS_URL("http://status.mojang.com/news");
const QString LITELOADER_URL("http://dl.liteloader.com/versions/versions.json");
const QString IMGUR_BASE_URL("https://api.imgur.com/3/");
}

View File

@ -19,19 +19,19 @@
namespace URLConstants namespace URLConstants
{ {
const QString AWS_DOWNLOAD_BASE("s3.amazonaws.com/Minecraft.Download/"); extern const QString AWS_DOWNLOAD_BASE;
const QString AWS_DOWNLOAD_VERSIONS(AWS_DOWNLOAD_BASE + "versions/"); extern const QString AWS_DOWNLOAD_VERSIONS;
const QString AWS_DOWNLOAD_LIBRARIES(AWS_DOWNLOAD_BASE + "libraries/"); extern const QString AWS_DOWNLOAD_LIBRARIES;
const QString AWS_DOWNLOAD_INDEXES(AWS_DOWNLOAD_BASE + "indexes/"); extern const QString AWS_DOWNLOAD_INDEXES;
const QString ASSETS_BASE("assets.minecraft.net/"); extern const QString ASSETS_BASE;
//const QString MCN_BASE("sonicrules.org/mcnweb.py"); extern const QString RESOURCE_BASE;
const QString RESOURCE_BASE("resources.download.minecraft.net/"); extern const QString LIBRARY_BASE;
const QString LIBRARY_BASE("libraries.minecraft.net/"); extern const QString SKINS_BASE;
const QString SKINS_BASE("skins.minecraft.net/MinecraftSkins/"); extern const QString AUTH_BASE;
const QString AUTH_BASE("authserver.mojang.com/"); extern const QString FORGE_LEGACY_URL;
const QString FORGE_LEGACY_URL("http://files.minecraftforge.net/minecraftforge/json"); extern const QString FORGE_GRADLE_URL;
const QString FORGE_GRADLE_URL("http://files.minecraftforge.net/maven/net/minecraftforge/forge/json"); extern const QString MOJANG_STATUS_URL;
const QString MOJANG_STATUS_URL("http://status.mojang.com/check"); extern const QString MOJANG_STATUS_NEWS_URL;
const QString MOJANG_STATUS_NEWS_URL("http://status.mojang.com/news"); extern const QString LITELOADER_URL;
const QString LITELOADER_URL("http://dl.liteloader.com/versions/versions.json"); extern const QString IMGUR_BASE_URL;
} }

View File

@ -0,0 +1,90 @@
#include "ImgurAlbumCreation.h"
#include <QNetworkRequest>
#include <QJsonDocument>
#include <QJsonObject>
#include <QUrl>
#include "logic/screenshots//ScreenshotList.h"
#include "logic/net/URLConstants.h"
#include "MultiMC.h"
#include "logger/QsLog.h"
ImgurAlbumCreation::ImgurAlbumCreation(QList<ScreenshotPtr> screenshots) : NetAction(), m_screenshots(screenshots)
{
m_url = URLConstants::IMGUR_BASE_URL + "album.json";
m_status = Job_NotStarted;
}
void ImgurAlbumCreation::start()
{
m_status = Job_InProgress;
QNetworkRequest request(m_url);
request.setHeader(QNetworkRequest::UserAgentHeader, "MultiMC/5.0 (Uncached)");
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
request.setRawHeader("Authorization", "Client-ID 5b97b0713fba4a3");
request.setRawHeader("Accept", "application/json");
QStringList ids;
for (auto shot : m_screenshots)
{
ids.append(shot->imgurId);
}
const QByteArray data = "ids=" + ids.join(',').toUtf8() + "&title=Minecraft%20Screenshots&privacy=hidden";
auto worker = MMC->qnam();
QNetworkReply *rep = worker->post(request, data);
m_reply = std::shared_ptr<QNetworkReply>(rep);
connect(rep, &QNetworkReply::uploadProgress, this, &ImgurAlbumCreation::downloadProgress);
connect(rep, &QNetworkReply::finished, this, &ImgurAlbumCreation::downloadFinished);
connect(rep, SIGNAL(error(QNetworkReply::NetworkError)),
SLOT(downloadError(QNetworkReply::NetworkError)));
}
void ImgurAlbumCreation::downloadError(QNetworkReply::NetworkError error)
{
QLOG_DEBUG() << m_reply->errorString();
m_status = Job_Failed;
}
void ImgurAlbumCreation::downloadFinished()
{
if (m_status != Job_Failed)
{
QByteArray data = m_reply->readAll();
m_reply.reset();
QJsonParseError jsonError;
QJsonDocument doc = QJsonDocument::fromJson(data, &jsonError);
if (jsonError.error != QJsonParseError::NoError)
{
QLOG_DEBUG() << jsonError.errorString();
emit failed(m_index_within_job);
return;
}
auto object = doc.object();
if (!object.value("success").toBool())
{
QLOG_DEBUG() << doc.toJson();
emit failed(m_index_within_job);
return;
}
m_deleteHash = object.value("data").toObject().value("deletehash").toString();
m_id = object.value("data").toObject().value("id").toString();
m_status = Job_Finished;
emit succeeded(m_index_within_job);
return;
}
else
{
QLOG_DEBUG() << m_reply->readAll();
m_reply.reset();
emit failed(m_index_within_job);
return;
}
}
void ImgurAlbumCreation::downloadProgress(qint64 bytesReceived, qint64 bytesTotal)
{
m_total_progress = bytesTotal;
m_progress = bytesReceived;
emit progress(m_index_within_job, bytesReceived, bytesTotal);
}

View File

@ -0,0 +1,42 @@
#pragma once
#include "logic/net/NetAction.h"
#include "Screenshot.h"
typedef std::shared_ptr<class ImgurAlbumCreation> ImgurAlbumCreationPtr;
class ImgurAlbumCreation : public NetAction
{
public:
explicit ImgurAlbumCreation(QList<ScreenshotPtr> screenshots);
static ImgurAlbumCreationPtr make(QList<ScreenshotPtr> screenshots)
{
return ImgurAlbumCreationPtr(new ImgurAlbumCreation(screenshots));
}
QString deleteHash() const
{
return m_deleteHash;
}
QString id() const
{
return m_id;
}
protected
slots:
virtual void downloadProgress(qint64 bytesReceived, qint64 bytesTotal);
virtual void downloadError(QNetworkReply::NetworkError error);
virtual void downloadFinished();
virtual void downloadReadyRead()
{
}
public
slots:
virtual void start();
private:
QList<ScreenshotPtr> m_screenshots;
QString m_deleteHash;
QString m_id;
};

View File

@ -0,0 +1,106 @@
#include "ImgurUpload.h"
#include <QNetworkRequest>
#include <QHttpMultiPart>
#include <QJsonDocument>
#include <QJsonObject>
#include <QHttpPart>
#include <QFile>
#include <QUrl>
#include "logic/screenshots/ScreenshotList.h"
#include "logic/net/URLConstants.h"
#include "MultiMC.h"
#include "logger/QsLog.h"
ImgurUpload::ImgurUpload(ScreenshotPtr shot) : NetAction(), m_shot(shot)
{
m_url = URLConstants::IMGUR_BASE_URL + "upload.json";
m_status = Job_NotStarted;
}
void ImgurUpload::start()
{
m_status = Job_InProgress;
QNetworkRequest request(m_url);
request.setHeader(QNetworkRequest::UserAgentHeader, "MultiMC/5.0 (Uncached)");
request.setRawHeader("Authorization", "Client-ID 5b97b0713fba4a3");
request.setRawHeader("Accept", "application/json");
QFile f(m_shot->file);
if (!f.open(QFile::ReadOnly))
{
emit failed(m_index_within_job);
return;
}
QHttpMultiPart *multipart = new QHttpMultiPart(QHttpMultiPart::FormDataType);
QHttpPart filePart;
filePart.setBody(f.readAll().toBase64());
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");
multipart->append(typePart);
QHttpPart namePart;
namePart.setHeader(QNetworkRequest::ContentDispositionHeader, "form-data; name=\"name\"");
namePart.setBody(m_shot->timestamp.toString(Qt::ISODate).toUtf8());
multipart->append(namePart);
auto worker = MMC->qnam();
QNetworkReply *rep = worker->post(request, multipart);
m_reply = std::shared_ptr<QNetworkReply>(rep);
connect(rep, &QNetworkReply::uploadProgress, this, &ImgurUpload::downloadProgress);
connect(rep, &QNetworkReply::finished, this, &ImgurUpload::downloadFinished);
connect(rep, SIGNAL(error(QNetworkReply::NetworkError)),
SLOT(downloadError(QNetworkReply::NetworkError)));
}
void ImgurUpload::downloadError(QNetworkReply::NetworkError error)
{
QLOG_DEBUG() << m_reply->errorString();
m_status = Job_Failed;
}
void ImgurUpload::downloadFinished()
{
if (m_status != Job_Failed)
{
QByteArray data = m_reply->readAll();
m_reply.reset();
QJsonParseError jsonError;
QJsonDocument doc = QJsonDocument::fromJson(data, &jsonError);
if (jsonError.error != QJsonParseError::NoError)
{
QLOG_DEBUG() << jsonError.errorString();
emit failed(m_index_within_job);
return;
}
auto object = doc.object();
if (!object.value("success").toBool())
{
QLOG_DEBUG() << doc.toJson();
emit failed(m_index_within_job);
return;
}
m_shot->imgurId = object.value("data").toObject().value("id").toString();
m_shot->url = object.value("data").toObject().value("link").toString();
m_status = Job_Finished;
emit succeeded(m_index_within_job);
return;
}
else
{
QLOG_DEBUG() << m_reply->readAll();
m_reply.reset();
emit failed(m_index_within_job);
return;
}
}
void ImgurUpload::downloadProgress(qint64 bytesReceived, qint64 bytesTotal)
{
m_total_progress = bytesTotal;
m_progress = bytesReceived;
emit progress(m_index_within_job, bytesReceived, bytesTotal);
}

View File

@ -0,0 +1,30 @@
#pragma once
#include "logic/net/NetAction.h"
#include "Screenshot.h"
typedef std::shared_ptr<class ImgurUpload> ImgurUploadPtr;
class ImgurUpload : public NetAction
{
public:
explicit ImgurUpload(ScreenshotPtr shot);
static ImgurUploadPtr make(ScreenshotPtr shot)
{
return ImgurUploadPtr(new ImgurUpload(shot));
}
protected
slots:
virtual void downloadProgress(qint64 bytesReceived, qint64 bytesTotal);
virtual void downloadError(QNetworkReply::NetworkError error);
virtual void downloadFinished();
virtual void downloadReadyRead()
{
}
public
slots:
virtual void start();
private:
ScreenshotPtr m_shot;
};

View File

@ -0,0 +1,14 @@
#include "Screenshot.h"
#include <QImage>
#include <QIcon>
QIcon ScreenShot::getImage()
{
if(!imageloaded)
{
QImage image(file);
QImage thumbnail = image.scaledToWidth(256, Qt::SmoothTransformation);
m_image = QIcon(QPixmap::fromImage(thumbnail));
imageloaded = true;
}
return m_image;
}

View File

@ -0,0 +1,19 @@
#pragma once
#include <QDateTime>
#include <QString>
#include <memory>
#include <QIcon>
struct ScreenShot
{
QIcon getImage();
QIcon m_image;
bool imageloaded = false;
QDateTime timestamp;
QString file;
QString url;
QString imgurId;
};
typedef std::shared_ptr<ScreenShot> ScreenshotPtr;

View File

@ -0,0 +1,113 @@
#include "ScreenshotList.h"
#include "gui/dialogs/ScreenshotDialog.h"
#include <QDir>
#include <QIcon>
#include <QList>
#include "gui/dialogs/ProgressDialog.h"
#include "gui/dialogs/CustomMessageBox.h"
ScreenshotList::ScreenshotList(BaseInstance *instance, QObject *parent)
: QAbstractListModel(parent), m_instance(instance)
{
}
int ScreenshotList::rowCount(const QModelIndex &) const
{
return m_screenshots.size();
}
QVariant ScreenshotList::data(const QModelIndex &index, int role) const
{
if (index.row() >= m_screenshots.size() || index.row() < 0)
return QVariant();
switch (role)
{
case Qt::DecorationRole:
return m_screenshots.at(index.row())->getImage();
case Qt::DisplayRole:
return m_screenshots.at(index.row())->timestamp.toString("yyyy-MM-dd HH:mm:ss");
case Qt::ToolTipRole:
return m_screenshots.at(index.row())->timestamp.toString("yyyy-MM-dd HH:mm:ss");
case Qt::TextAlignmentRole:
return (int)(Qt::AlignHCenter | Qt::AlignVCenter);
default:
return QVariant();
}
}
QVariant ScreenshotList::headerData(int section, Qt::Orientation orientation, int role) const
{
return QVariant();
}
Qt::ItemFlags ScreenshotList::flags(const QModelIndex &index) const
{
return Qt::ItemIsSelectable | Qt::ItemIsEnabled;
}
Task *ScreenshotList::load()
{
return new ScreenshotLoadTask(this);
}
ScreenshotLoadTask::ScreenshotLoadTask(ScreenshotList *list) : m_list(list)
{
}
ScreenshotLoadTask::~ScreenshotLoadTask()
{
}
void ScreenshotLoadTask::executeTask()
{
auto dir = QDir(m_list->instance()->minecraftRoot());
if (!dir.cd("screenshots"))
{
emitFailed("Selected instance does not have any screenshots!");
return;
}
dir.setNameFilters(QStringList() << "*.png");
this->m_results.clear();
for (auto file : dir.entryList())
{
ScreenShot *shot = new ScreenShot();
shot->timestamp = QDateTime::fromString(file, "yyyy-MM-dd_HH.mm.ss.png");
shot->file = dir.absoluteFilePath(file);
m_results.append(ScreenshotPtr(shot));
}
m_list->loadShots(m_results);
emitSucceeded();
}
void ScreenshotList::deleteSelected(ScreenshotDialog *dialog)
{
auto screens = dialog->selected();
if (screens.isEmpty())
{
return;
}
beginResetModel();
QList<std::shared_ptr<ScreenShot>>::const_iterator it;
for (it = screens.cbegin(); it != screens.cend(); it++)
{
auto shot = *it;
if (!QFile(shot->file).remove())
{
CustomMessageBox::selectable(dialog, tr("Error!"),
tr("Failed to delete screenshots!"),
QMessageBox::Warning)->exec();
break;
}
}
ProgressDialog refresh(dialog);
Task *t = load();
if (refresh.exec(t) != QDialog::Accepted)
{
CustomMessageBox::selectable(dialog, tr("Error!"),
tr("Unable to refresh list: %1").arg(t->failReason()),
QMessageBox::Warning)->exec();
}
endResetModel();
}

View File

@ -0,0 +1,70 @@
#pragma once
#include <QAbstractListModel>
#include "logic/BaseInstance.h"
#include "logic/tasks/Task.h"
#include "Screenshot.h"
class ScreenshotList : public QAbstractListModel
{
Q_OBJECT
public:
ScreenshotList(BaseInstance *instance, QObject *parent = 0);
QVariant data(const QModelIndex &index, int role) const;
QVariant headerData(int section, Qt::Orientation orientation, int role) const;
int rowCount(const QModelIndex &parent) const;
Qt::ItemFlags flags(const QModelIndex &index) const;
Task *load();
void loadShots(QList<ScreenshotPtr> shots)
{
m_screenshots = shots;
}
QList<ScreenshotPtr> screenshots() const
{
return m_screenshots;
}
BaseInstance *instance() const
{
return m_instance;
}
void deleteSelected(class ScreenshotDialog *dialog);
signals:
public
slots:
private:
QList<ScreenshotPtr> m_screenshots;
BaseInstance *m_instance;
};
class ScreenshotLoadTask : public Task
{
Q_OBJECT
public:
explicit ScreenshotLoadTask(ScreenshotList *list);
~ScreenshotLoadTask();
QList<ScreenshotPtr> screenShots() const
{
return m_results;
}
protected:
virtual void executeTask();
private:
ScreenshotList *m_list;
QList<ScreenshotPtr> m_results;
};

View File

@ -28,7 +28,7 @@ void SequentialTask::getProgress(qint64 &current, qint64 &total)
} }
} }
void SequentialTask::addTask(std::shared_ptr<Task> task) void SequentialTask::addTask(std::shared_ptr<ProgressProvider> task)
{ {
m_queue.append(task); m_queue.append(task);
} }
@ -43,7 +43,7 @@ void SequentialTask::startNext()
{ {
if (m_currentIndex != -1) if (m_currentIndex != -1)
{ {
std::shared_ptr<Task> previous = m_queue[m_currentIndex]; std::shared_ptr<ProgressProvider> previous = m_queue[m_currentIndex];
disconnect(previous.get(), 0, this, 0); disconnect(previous.get(), 0, this, 0);
} }
m_currentIndex++; m_currentIndex++;
@ -52,7 +52,7 @@ void SequentialTask::startNext()
emitSucceeded(); emitSucceeded();
return; return;
} }
std::shared_ptr<Task> next = m_queue[m_currentIndex]; std::shared_ptr<ProgressProvider> next = m_queue[m_currentIndex];
connect(next.get(), SIGNAL(failed(QString)), this, SLOT(subTaskFailed(QString))); connect(next.get(), SIGNAL(failed(QString)), this, SLOT(subTaskFailed(QString)));
connect(next.get(), SIGNAL(status(QString)), this, SLOT(subTaskStatus(QString))); connect(next.get(), SIGNAL(status(QString)), this, SLOT(subTaskStatus(QString)));
connect(next.get(), SIGNAL(progress(qint64,qint64)), this, SLOT(subTaskProgress())); connect(next.get(), SIGNAL(progress(qint64,qint64)), this, SLOT(subTaskProgress()));
@ -73,5 +73,12 @@ void SequentialTask::subTaskProgress()
{ {
qint64 current, total; qint64 current, total;
getProgress(current, total); getProgress(current, total);
if (total == 0)
{
setProgress(0);
}
else
{
setProgress(100 * current / total); setProgress(100 * current / total);
}
} }

View File

@ -14,7 +14,7 @@ public:
virtual QString getStatus() const; virtual QString getStatus() const;
virtual void getProgress(qint64 &current, qint64 &total); virtual void getProgress(qint64 &current, qint64 &total);
void addTask(std::shared_ptr<Task> task); void addTask(std::shared_ptr<ProgressProvider> task);
protected: protected:
void executeTask(); void executeTask();
@ -27,6 +27,6 @@ slots:
void subTaskProgress(); void subTaskProgress();
private: private:
QQueue<std::shared_ptr<Task> > m_queue; QQueue<std::shared_ptr<ProgressProvider> > m_queue;
int m_currentIndex; int m_currentIndex;
}; };