Page MenuHomePhabricator (Chris)

No OneTemporary

Authored By
Unknown
Size
31 KB
Referenced Files
None
Subscribers
None
diff --git a/tools/uploader/imageuploader.cpp b/tools/uploader/imageuploader.cpp
index 14806ac..57d2eff 100644
--- a/tools/uploader/imageuploader.cpp
+++ b/tools/uploader/imageuploader.cpp
@@ -1,11 +1,63 @@
#include "imageuploader.h"
#include "imguruploader.h"
-ImageUploader *ImageUploader::getNewUploader(const QString &name, const QVariantHash &options)
+#include <QSettings>
+#include "../screenshotmanager.h"
+
+ImageUploader *ImageUploader::factory(const QString &name)
{
if (name == "imgur") {
- return new ImgurUploader(options);
+ return new ImgurUploader(0);
}
return 0;
}
+
+QVariantHash ImageUploader::loadSettings(const QString &uploaderType)
+{
+ auto globalSettings = ScreenshotManager::instance()->settings();
+ globalSettings->beginGroup("upload/" + uploaderType);
+ auto keys = globalSettings->childKeys();
+
+ QVariantHash settings;
+
+ for (auto key : qAsConst(keys)) {
+ settings[key] = globalSettings->value(key);
+ }
+
+ globalSettings->endGroup();
+ return settings;
+}
+
+void ImageUploader::loadSettings()
+{
+ mSettings = loadSettings(mUploaderType);
+}
+
+void ImageUploader::saveSettings(const QString &uploaderType, const QVariantHash &settings) {
+ auto globalSettings = ScreenshotManager::instance()->settings();
+ globalSettings->beginGroup("upload/" + uploaderType);
+
+ for (auto key : settings.keys()) {
+ globalSettings->setValue(key, settings[key]);
+ }
+
+ globalSettings->endGroup();
+}
+
+void ImageUploader::saveSettings()
+{
+ saveSettings(mUploaderType, mSettings);
+}
+
+int ImageUploader::progress() const {
+ return mProgress;
+}
+
+void ImageUploader::setProgress(int progress)
+{
+ if (mProgress != progress) {
+ mProgress = progress;
+ emit progressChanged(mProgress);
+ }
+}
diff --git a/tools/uploader/imageuploader.h b/tools/uploader/imageuploader.h
index 1b125f8..21a55ea 100644
--- a/tools/uploader/imageuploader.h
+++ b/tools/uploader/imageuploader.h
@@ -1,46 +1,54 @@
#ifndef IMAGEUPLOADER_H
#define IMAGEUPLOADER_H
#include <QHash>
#include <QVariant>
class QNetworkReply;
class ImageUploader : public QObject
{
Q_OBJECT
+ Q_PROPERTY(int progress READ progress WRITE setProgress NOTIFY progressChanged)
public:
- static ImageUploader *getNewUploader(const QString &name, const QVariantHash &options = QVariantHash());
+ static ImageUploader *factory(const QString &type);
enum Error {
FileError,
NetworkError,
HostError,
+ AuthorizationError,
CancelError,
OtherError
};
Q_ENUM(Error)
public:
- inline ImageUploader(const QVariantHash &options) : QObject(0), mOptions(options), mProgress(0) {}
- QVariantHash options() const { return mOptions; }
+ inline ImageUploader(QObject *parent = 0) : QObject(parent), mProgress(0) {}
+
+ static QVariantHash loadSettings(const QString &uploaderType);
+ void loadSettings();
+
+ static void saveSettings(const QString &uploaderType, const QVariantHash &settings);
+ void saveSettings();
public slots:
virtual void upload(const QString &fileName) = 0;
virtual void cancel() = 0;
virtual void retry() = 0;
- int progress() const { return mProgress; }
- void setProgress(int progress) { mProgress = progress; }
+ int progress() const;
+ void setProgress(int progress);
signals:
- void uploaded(QString, QString, QString);
- void error(Error, QString, QString);
- void progressChange(int);
+ void uploaded(const QString &fileName, const QString &url, const QString &deleteHash); // TODO: Make last param generic
+ void error(ImageUploader::Error errorCode, const QString &errorString, const QString &fileName);
+ void progressChanged(int progress);
protected:
- QVariantHash mOptions;
int mProgress;
+ QString mUploaderType;
+ QVariantHash mSettings;
};
#endif // IMAGEUPLOADER_H
diff --git a/tools/uploader/imguruploader.cpp b/tools/uploader/imguruploader.cpp
index 86e2606..b82c6a6 100644
--- a/tools/uploader/imguruploader.cpp
+++ b/tools/uploader/imguruploader.cpp
@@ -1,114 +1,199 @@
#include "imguruploader.h"
+#include "../uploader/uploader.h"
+
#include <QNetworkAccessManager>
#include <QtNetwork>
+#include <QJsonDocument>
+#include <QJsonObject>
-ImgurUploader::ImgurUploader(const QVariantHash &options) : ImageUploader(options) {}
+ImgurUploader::ImgurUploader(QObject *parent) : ImageUploader(parent)
+{
+ mUploaderType = "imgur";
+ loadSettings();
+}
const QString ImgurUploader::clientId()
{
return QString("3ebe94c791445c1");
}
const QString ImgurUploader::clientSecret()
{
return QString("0546b05d6a80b2092dcea86c57b792c9c9faebf0");
}
+void ImgurUploader::authorize(const QString &pin, AuthorizationCallback callback)
+{
+ if (pin.isEmpty()) {
+ callback(false);
+ return;
+ }
+
+ QByteArray parameters;
+ parameters.append(QString("client_id=").toUtf8());
+ parameters.append(QUrl::toPercentEncoding(clientId()));
+ parameters.append(QString("&client_secret=").toUtf8());
+ parameters.append(QUrl::toPercentEncoding(clientSecret()));
+ parameters.append(QString("&grant_type=pin").toUtf8());
+ parameters.append(QString("&pin=").toUtf8());
+ parameters.append(QUrl::toPercentEncoding(pin));
+
+ QNetworkRequest request(QUrl("https://api.imgur.com/oauth2/token"));
+ request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
+
+ QNetworkReply *reply = Uploader::instance()->nam()->post(request, parameters);
+ authorizationReply(reply, callback);
+}
+
+void ImgurUploader::refreshAuthorization(const QString &refresh_token, AuthorizationCallback callback)
+{
+ if (refresh_token.isEmpty()) {
+ callback(false);
+ return;
+ }
+
+ QByteArray parameters;
+ parameters.append(QString("refresh_token=").toUtf8());
+ parameters.append(QUrl::toPercentEncoding(refresh_token));
+ parameters.append(QString("&client_id=").toUtf8());
+ parameters.append(QUrl::toPercentEncoding(clientId()));
+ parameters.append(QString("&client_secret=").toUtf8());
+ parameters.append(QUrl::toPercentEncoding(clientSecret()));
+ parameters.append(QString("&grant_type=refresh_token").toUtf8());
+
+ QNetworkRequest request(QUrl("https://api.imgur.com/oauth2/token"));
+ request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
+
+ QNetworkReply *reply = Uploader::instance()->nam()->post(request, parameters);
+ authorizationReply(reply, callback);
+}
+
void ImgurUploader::upload(const QString &fileName)
{
QFile *file = new QFile(fileName);
if (!file->open(QIODevice::ReadOnly)) {
emit error(ImageUploader::FileError, tr("Unable to read screenshot file"), fileName);
file->deleteLater();
return;
}
QNetworkRequest request(QUrl("https://api.imgur.com/3/image"));
request.setRawHeader("Authorization", QString("Client-ID %1").arg(clientId()).toLatin1());
QHttpMultiPart *multiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType);
- if (!mOptions.value("anonymous", true).toBool()) {
- request.setRawHeader("Authorization", QByteArray("Bearer ") + mOptions.value("access_token").toByteArray());
+ if (!mSettings.value("anonymous", true).toBool()) {
+ request.setRawHeader("Authorization", QByteArray("Bearer ") + mSettings.value("access_token").toByteArray());
- if (!mOptions.value("album").toString().isEmpty()) {
+ if (!mSettings.value("album").toString().isEmpty()) {
QHttpPart albumPart;
albumPart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"album\""));
- albumPart.setBody(mOptions.value("album").toByteArray());
+ albumPart.setBody(mSettings.value("album").toByteArray());
multiPart->append(albumPart);
}
}
QHttpPart imagePart;
imagePart.setHeader(QNetworkRequest::ContentTypeHeader, QMimeDatabase().mimeTypeForFile(fileName, QMimeDatabase::MatchExtension).name());
imagePart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"image\""));
imagePart.setBodyDevice(file);
file->setParent(multiPart);
multiPart->append(imagePart);
- QNetworkReply *reply = mOptions.value("networkManager").value<QNetworkAccessManager *>()->post(request, multiPart);
+ QNetworkReply *reply = Uploader::instance()->nam()->post(request, multiPart);
reply->setProperty("fileName", fileName);
this->setProperty("fileName", fileName);
connect(reply, SIGNAL(uploadProgress(qint64, qint64)), this, SLOT(uploadProgress(qint64, qint64)));
connect(this , SIGNAL(cancelRequest()), reply, SLOT(abort()));
connect(this , SIGNAL(cancelRequest()), reply, SLOT(deleteLater()));
+
connect(reply, SIGNAL(finished()), this, SLOT(finished()));
}
void ImgurUploader::retry()
{
+ loadSettings();
upload(property("fileName").toString());
}
void ImgurUploader::cancel()
{
emit cancelRequest();
}
void ImgurUploader::finished()
{
QNetworkReply *reply = qobject_cast<QNetworkReply *>(sender());
reply->deleteLater();
QString fileName = reply->property("fileName").toString();
if (reply->error() != QNetworkReply::NoError) {
if (reply->error() == QNetworkReply::OperationCanceledError) {
emit error(ImageUploader::CancelError, "", fileName);
} else if (reply->error() == QNetworkReply::ContentOperationNotPermittedError ||
reply->error() == QNetworkReply::AuthenticationRequiredError) {
- emit needAuthRefresh();
+
+ refreshAuthorization(mSettings["refresh_token"].toString(), [&](bool result) {
+ if (result) {
+ QTimer::singleShot(50, this, &ImgurUploader::retry);
+ } else {
+ cancel();
+ emit error(ImageUploader::AuthorizationError, tr("Imgur user authentication failed"), fileName);
+ }
+ });
} else {
emit error(ImageUploader::NetworkError, reply->errorString(), fileName);
}
return;
}
if (reply->rawHeader("X-RateLimit-Remaining") == "0") {
emit error(ImageUploader::HostError, tr("Imgur upload limit reached"), fileName);
return;
}
QJsonObject imgurResponse = QJsonDocument::fromJson(reply->readAll()).object();
if (imgurResponse.value("success").toBool() == true && imgurResponse.value("status").toInt() == 200) {
QJsonObject imageData = imgurResponse.value("data").toObject();
emit uploaded(fileName, imageData["link"].toString(), imageData["deletehash"].toString());
} else {
emit error(ImageUploader::HostError, tr("Imgur error"), fileName);
}
}
void ImgurUploader::uploadProgress(qint64 bytesReceived, qint64 bytesTotal)
{
float b = (float) bytesReceived / bytesTotal;
int p = qRound(b * 100);
setProgress(p);
- emit progressChange(p);
+}
+
+void ImgurUploader::authorizationReply(QNetworkReply *reply, AuthorizationCallback callback)
+{
+ connect(reply, &QNetworkReply::finished, [reply, callback] {
+ bool authorized = false;
+
+ const QJsonObject imgurResponse = QJsonDocument::fromJson(reply->readAll()).object();
+
+ if (!imgurResponse.isEmpty() && imgurResponse.contains("access_token")) {
+ QVariantHash newSettings;
+ newSettings["access_token"] = imgurResponse.value("access_token").toString();
+ newSettings["refresh_token"] = imgurResponse.value("refresh_token").toString();
+ newSettings["account_username"] = imgurResponse.value("account_username").toString();
+ newSettings["expires_in"] = imgurResponse.value("expires_in").toInt();
+ saveSettings("imgur", newSettings);
+
+ authorized = true;
+ }
+
+ callback(authorized);
+ });
}
diff --git a/tools/uploader/imguruploader.h b/tools/uploader/imguruploader.h
index 8f3f99f..82e916c 100644
--- a/tools/uploader/imguruploader.h
+++ b/tools/uploader/imguruploader.h
@@ -1,33 +1,40 @@
#ifndef IMGURUPLOADER_H
#define IMGURUPLOADER_H
#include <QObject>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include "imageuploader.h"
+#include <functional>
class ImgurUploader : public ImageUploader
{
Q_OBJECT
public:
- ImgurUploader(const QVariantHash &options);
+ typedef std::function<void(bool)> AuthorizationCallback;
+
+ ImgurUploader(QObject *parent);
static const QString clientId();
static const QString clientSecret();
+ static void authorize(const QString &pin, AuthorizationCallback callback);
+ static void refreshAuthorization(const QString &refresh_token, AuthorizationCallback callback);
public slots:
void upload(const QString &fileName);
void retry();
void cancel();
private slots:
void finished();
void uploadProgress(qint64 bytesReceived, qint64 bytesTotal);
signals:
void cancelRequest();
- void needAuthRefresh();
+
+private:
+ static void authorizationReply(QNetworkReply *reply, AuthorizationCallback callback);
};
#endif // IMGURUPLOADER_H
diff --git a/tools/uploader/uploader.cpp b/tools/uploader/uploader.cpp
index 25ec90e..ac64fa4 100644
--- a/tools/uploader/uploader.cpp
+++ b/tools/uploader/uploader.cpp
@@ -1,204 +1,130 @@
/*
* Copyright (C) 2016 Christian Kaiser
*
* 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; 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
#include "uploader.h"
#include "../screenshotmanager.h"
#include "imguruploader.h"
#include <QtNetwork>
#include <QSettings>
Uploader *Uploader::mInstance = 0;
Uploader::Uploader(QObject *parent) : QObject(parent), mProgress(0)
{
mNetworkAccessManager = new QNetworkAccessManager(this);
}
Uploader *Uploader::instance()
{
if (!mInstance) {
mInstance = new Uploader();
}
return mInstance;
}
int Uploader::progress() const
{
return mProgress;
}
QNetworkAccessManager *Uploader::nam()
{
return mNetworkAccessManager;
}
QString Uploader::lastUrl() const
{
return mLastUrl;
}
void Uploader::cancel()
{
mUploaders.clear();
mProgress = 0;
emit cancelAll();
}
void Uploader::upload(const QString &fileName)
{
if (fileName.isEmpty()) {
return;
}
- QVariantHash options;
- QSettings *s = ScreenshotManager::instance()->settings();
- options["type"] = "imgur";
- options["networkManager"].setValue(mNetworkAccessManager);
- options["anonymous"] = s->value("upload/imgur/anonymous", true).toBool();
- options["album"] = s->value("upload/imgur/album", "").toString();
- options["access_token"] = s->value("upload/imgur/access_token", "").toString();
- options["refresh_token"] = s->value("upload/imgur/refresh_token", "").toString();
-
- if (options["access_token"].toString().isEmpty() || options["refresh_token"].toString().isEmpty()) {
- options["anonymous"] = true;
- }
-
- ImgurUploader *uploader = new ImgurUploader(options);
-
- connect(uploader, &ImgurUploader::uploaded , this, &Uploader::uploaded);
- connect(uploader, &ImgurUploader::error , this, &Uploader::uploaderError);
- connect(uploader, &ImgurUploader::progressChange , this, &Uploader::progressChange);
- connect(uploader, &ImgurUploader::needAuthRefresh, this, &Uploader::imgurAuthRefresh);
+ ImageUploader *uploader = ImageUploader::factory("imgur");
- connect(this , SIGNAL(cancelAll()), uploader, SLOT(cancel()));
-
- uploader->upload(fileName);
- mUploaders.append(uploader);
-}
-
-void Uploader::uploaded(const QString &file, const QString &url, const QString &deleteHash)
-{
- mLastUrl = url;
- mUploaders.removeAll(qobject_cast<ImageUploader *>(sender()));
+ connect(uploader, &ImageUploader::progressChanged, this , &Uploader::progressChanged);
+ connect(this , &Uploader::cancelAll , uploader, &ImageUploader::cancel);
- if (mUploaders.isEmpty()) {
- mProgress = 0;
- }
+ connect(uploader, &ImageUploader::error, [&, uploader](ImageUploader::Error errorCode, const QString &errorString, const QString &fileName) {
+ mUploaders.removeAll(uploader);
+ uploader->deleteLater();
- sender()->deleteLater();
- emit done(file, url, deleteHash);
-}
+ mProgress = 0; // TODO: ?
-void Uploader::imgurAuthRefresh()
-{
- for (int i = 0; i < mUploaders.size(); ++i) {
- if (mUploaders[i]->options().value("type") == "imgur") {
- mUploaders[i]->cancel();
+ if (errorCode != ImageUploader::CancelError) {
+ if (errorString.isEmpty()) {
+ emit error(tr("Upload Error %1").arg(errorCode));
+ } else {
+ emit error(errorString);
+ }
}
- }
- QByteArray parameters;
- parameters.append(QString("refresh_token=").toUtf8());
- parameters.append(QUrl::toPercentEncoding(ScreenshotManager::instance()->settings()->value("upload/imgur/refresh_token").toString()));
- parameters.append(QString("&client_id=").toUtf8());
- parameters.append(QUrl::toPercentEncoding("3ebe94c791445c1"));
- parameters.append(QString("&client_secret=").toUtf8());
- parameters.append(QUrl::toPercentEncoding("0546b05d6a80b2092dcea86c57b792c9c9faebf0")); // TODO: TA.png
- parameters.append(QString("&grant_type=refresh_token").toUtf8());
+ emit done(fileName, "", "");
+ });
- QNetworkRequest request(QUrl("https://api.imgur.com/oauth2/token"));
- request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
-
- QNetworkReply *reply = Uploader::instance()->nam()->post(request, parameters);
- connect(reply, SIGNAL(finished()), this, SLOT(imgurToken()));
-}
-
-void Uploader::imgurToken()
-{
- QNetworkReply *reply = qobject_cast<QNetworkReply *>(sender());
+ connect(uploader, &ImageUploader::uploaded, [&, uploader](const QString &file, const QString &url, const QString &deleteHash) {
+ mLastUrl = url;
+ mUploaders.removeAll(uploader);
- if (reply->error() != QNetworkReply::NoError) {
- emit error(reply->errorString());
- return;
- }
-
- QJsonObject imgurResponse = QJsonDocument::fromJson(reply->readAll()).object();
-
- QSettings *s = ScreenshotManager::instance()->settings();
- s->setValue("upload/imgur/access_token" , imgurResponse["access_token"].toString());
- s->setValue("upload/imgur/refresh_token" , imgurResponse["refresh_token"].toString());
- s->setValue("upload/imgur/account_username", imgurResponse["account_username"].toString());
- s->setValue("upload/imgur/expires_in" , imgurResponse["expires_in"].toString());
-
- for (ImageUploader *uploader : qAsConst(mUploaders)) {
- if (uploader->options().value("type") == "imgur") {
- uploader->options().remove("access_token");
- uploader->options().remove("refresh_token");
-
- uploader->options().insert("access_token" , imgurResponse["access_token"].toString());
- uploader->options().insert("refresh_token", imgurResponse["refresh_token"].toString());
-
- uploader->retry();
+ if (mUploaders.isEmpty()) {
+ mProgress = 0;
}
- }
- emit imgurAuthRefreshed();
-}
+ uploader->deleteLater();
+ emit done(file, url, deleteHash);
+ });
-void Uploader::uploaderError(ImageUploader::Error code, QString errorString, QString fileName)
-{
- mUploaders.removeAll(qobject_cast<ImageUploader *>(sender()));
- sender()->deleteLater();
- mProgress = 0;
-
- if (code != ImageUploader::CancelError) {
- if (errorString.isEmpty()) {
- emit error(tr("Upload Error ") + code);
- } else {
- emit error(errorString);
- }
- }
-
- emit done(fileName, "", "");
+ uploader->upload(fileName);
+ mUploaders.append(uploader);
}
int Uploader::uploading()
{
return mUploaders.count();
}
-void Uploader::progressChange(int p)
+void Uploader::progressChanged(int p)
{
if (mUploaders.size() <= 0) {
mProgress = p;
emit progress(p);
return;
}
int totalProgress = 0;
for (int i = 0; i < mUploaders.size(); ++i) {
totalProgress += mUploaders[i]->progress();
}
mProgress = totalProgress / mUploaders.size();
emit progress(mProgress);
}
diff --git a/tools/uploader/uploader.h b/tools/uploader/uploader.h
index 65eff72..3a26864 100644
--- a/tools/uploader/uploader.h
+++ b/tools/uploader/uploader.h
@@ -1,64 +1,58 @@
/*
* Copyright (C) 2016 Christian Kaiser
*
* 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; 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
#ifndef UPLOADER_H
#define UPLOADER_H
#include <QObject>
#include <QtNetwork>
#include "imageuploader.h"
class Uploader : public QObject
{
Q_OBJECT
public:
Uploader(QObject *parent = 0);
static Uploader *instance();
QString lastUrl() const;
int progress() const;
QNetworkAccessManager *nam();
public slots:
void cancel();
- //void error(const QString &file, const QtImgur::Error e);
void upload(const QString &fileName);
- void uploaded(const QString &fileName, const QString &url, const QString &deleteHash);
- void uploaderError(ImageUploader::Error code, QString errorString, QString fileName);
int uploading();
- void progressChange(int p);
- void imgurAuthRefresh();
- void imgurToken();
+ void progressChanged(int p); //TODO: Rename
signals:
- void done(QString, QString, QString);
- void error(QString);
- void progress(int);
+ void done(const QString &fileName, const QString &url, const QString &deleteHash);
+ void error(const QString &errorString);
+ void progress(int progress);
void cancelAll();
- void imgurAuthRefreshed();
private:
static Uploader *mInstance;
QNetworkAccessManager *mNetworkAccessManager;
int mProgress;
QString mLastUrl;
QList<ImageUploader *> mUploaders;
};
#endif // UPLOADER_H
diff --git a/widgets/imguroptionswidget.cpp b/widgets/imguroptionswidget.cpp
index 0a5bb80..8b48274 100644
--- a/widgets/imguroptionswidget.cpp
+++ b/widgets/imguroptionswidget.cpp
@@ -1,178 +1,162 @@
#include <QJsonObject>
#include <QInputDialog>
#include <QNetworkReply>
#include <QDesktopServices>
#include <QMessageBox>
#include "imguroptionswidget.h"
#include "../uploader/uploader.h"
#include "../uploader/imguruploader.h"
#include "../screenshotmanager.h"
ImgurOptionsWidget::ImgurOptionsWidget(QWidget *parent) : QWidget(parent)
{
ui.setupUi(this);
- connect(Uploader::instance(), &Uploader::imgurAuthRefreshed, this, &ImgurOptionsWidget::requestAlbumList);
-
connect(ui.authButton , &QPushButton::clicked, this, &ImgurOptionsWidget::authorize);
connect(ui.refreshAlbumButton, &QPushButton::clicked, this, &ImgurOptionsWidget::requestAlbumList);
- connect(ui.authUserLabel , &QLabel::linkActivated, this, [](const QString &link) {
+ connect(ui.authUserLabel , &QLabel::linkActivated, this, [](const QString & link) {
QDesktopServices::openUrl(link);
});
}
QSettings *ImgurOptionsWidget::settings()
{
return ScreenshotManager::instance()->settings();
}
void ImgurOptionsWidget::setUser(const QString &username)
{
mCurrentUser = username;
setUpdatesEnabled(false);
if (mCurrentUser.isEmpty()) {
ui.authUserLabel->setText(tr("<i>none</i>"));
ui.albumComboBox->setEnabled(false);
ui.refreshAlbumButton->setEnabled(false);
ui.albumComboBox->clear();
ui.albumComboBox->addItem(tr("- None -"));
ui.authButton->setText(tr("Authorize"));
ui.helpLabel->setEnabled(true);
settings()->setValue("upload/imgur/access_token", "");
settings()->setValue("upload/imgur/refresh_token", "");
settings()->setValue("upload/imgur/account_username", "");
settings()->setValue("upload/imgur/expires_in", 0);
} else {
ui.authButton->setText(tr("Deauthorize"));
- ui.authUserLabel->setText("<b><a href=\"http://"+ username +".imgur.com/all/\">" + username + "</a></b>");
+ ui.authUserLabel->setText(tr("<b><a href=\"http://%1.imgur.com/all/\">%1</a></b>").arg(username));
ui.refreshAlbumButton->setEnabled(true);
ui.helpLabel->setEnabled(false);
}
setUpdatesEnabled(true);
}
void ImgurOptionsWidget::authorize()
{
if (!mCurrentUser.isEmpty()) {
setUser("");
return;
}
- QDesktopServices::openUrl(QUrl("https://api.imgur.com/oauth2/authorize?client_id=" + ImgurUploader::clientId() + "&response_type=pin")); //TODO: get the client-id from somewhere?
+ QDesktopServices::openUrl(QUrl("https://api.imgur.com/oauth2/authorize?client_id=" + ImgurUploader::clientId() + "&response_type=pin"));
bool ok;
QString pin = QInputDialog::getText(this, tr("Imgur Authorization"),
tr("Authentication PIN:"), QLineEdit::Normal,
"", &ok);
if (ok) {
- QByteArray parameters;
- parameters.append(QString("client_id=").toUtf8());
- parameters.append(QUrl::toPercentEncoding(ImgurUploader::clientId()));
- parameters.append(QString("&client_secret=").toUtf8());
- parameters.append(QUrl::toPercentEncoding(ImgurUploader::clientSecret()));
- parameters.append(QString("&grant_type=pin").toUtf8());
- parameters.append(QString("&pin=").toUtf8());
- parameters.append(QUrl::toPercentEncoding(pin));
-
- QNetworkRequest request(QUrl("https://api.imgur.com/oauth2/token"));
- request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
-
- QNetworkReply *reply = Uploader::instance()->nam()->post(request, parameters);
- connect(reply, &QNetworkReply::finished, this, [&, reply] {
+ ui.authButton->setText(tr("Authorizing.."));
+ ui.authButton->setEnabled(false);
+
+ ImgurUploader::authorize(pin, [&](bool result) {
ui.authButton->setEnabled(true);
- if (reply->error() != QNetworkReply::NoError) {
+ if (result) {
+ setUser(settings()->value("upload/imgur/account_username").toString());
+ QTimer::singleShot(0, this, &ImgurOptionsWidget::requestAlbumList);
+ } else {
QMessageBox::critical(this, tr("Imgur Authorization Error"), tr("There's been an error authorizing your account with Imgur, please try again."));
setUser("");
- return;
}
-
- QJsonObject imgurResponse = QJsonDocument::fromJson(reply->readAll()).object();
-
- settings()->setValue("upload/imgur/access_token" , imgurResponse.value("access_token").toString());
- settings()->setValue("upload/imgur/refresh_token" , imgurResponse.value("refresh_token").toString());
- settings()->setValue("upload/imgur/account_username", imgurResponse.value("account_username").toString());
- settings()->setValue("upload/imgur/expires_in" , imgurResponse.value("expires_in").toInt());
- settings()->sync();
-
- setUser(imgurResponse.value("account_username").toString());
-
- QTimer::singleShot(0, this, &ImgurOptionsWidget::requestAlbumList);
});
-
- ui.authButton->setText(tr("Authorizing.."));
- ui.authButton->setEnabled(false);
}
}
void ImgurOptionsWidget::requestAlbumList()
{
if (mCurrentUser.isEmpty()) {
return;
}
ui.refreshAlbumButton->setEnabled(true);
ui.albumComboBox->clear();
ui.albumComboBox->setEnabled(false);
ui.albumComboBox->addItem(tr("Loading album data..."));
QNetworkRequest request(QUrl::fromUserInput("https://api.imgur.com/3/account/" + mCurrentUser + "/albums/"));
request.setRawHeader("Authorization", QByteArray("Bearer ") + settings()->value("upload/imgur/access_token").toByteArray());
QNetworkReply *reply = Uploader::instance()->nam()->get(request);
connect(reply, &QNetworkReply::finished, this, [&, reply] {
- if (reply->error() != QNetworkReply::NoError) {
+ if (mCurrentUser.isEmpty()) return;
+
+ if (reply->error() != QNetworkReply::NoError)
+ {
if (reply->error() == QNetworkReply::ContentOperationNotPermittedError ||
- reply->error() == QNetworkReply::AuthenticationRequiredError) {
- Uploader::instance()->imgurAuthRefresh();
- qDebug() << "Attempting imgur auth refresh";
+ reply->error() == QNetworkReply::AuthenticationRequiredError) {
+ ImgurUploader::refreshAuthorization(settings()->value("upload/imgur/refresh_token", "").toString(), [&](bool result) {
+ if (result) {
+ QTimer::singleShot(50, this, &ImgurOptionsWidget::requestAlbumList);
+ } else {
+ setUser("");
+ }
+ });
}
ui.albumComboBox->addItem(tr("Loading failed :("));
return;
}
const QJsonObject imgurResponse = QJsonDocument::fromJson(reply->readAll()).object();
- if (imgurResponse["success"].toBool() != true || imgurResponse["status"].toInt() != 200) {
+ if (imgurResponse["success"].toBool() != true || imgurResponse["status"].toInt() != 200)
+ {
return;
}
const QJsonArray albumList = imgurResponse["data"].toArray();
setUpdatesEnabled(false);
ui.albumComboBox->clear();
ui.albumComboBox->setEnabled(true);
ui.albumComboBox->addItem(tr("- None -"), "");
ui.refreshAlbumButton->setEnabled(true);
int settingsIndex = 0;
for (auto albumValue : albumList) {
const QJsonObject album = albumValue.toObject();
QString albumVisibleTitle = album["title"].toString();
if (albumVisibleTitle.isEmpty()) {
albumVisibleTitle = tr("untitled");
}
ui.albumComboBox->addItem(albumVisibleTitle, album["id"].toString());
if (album["id"].toString() == settings()->value("upload/imgur/album").toString()) {
settingsIndex = ui.albumComboBox->count() - 1;
}
}
ui.albumComboBox->setCurrentIndex(settingsIndex);
setUpdatesEnabled(true);
});
}

File Metadata

Mime Type
text/x-diff
Expires
Tue, Jun 16, 12:27 AM (2 w, 1 d ago)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
70898
Default Alt Text
(31 KB)

Event Timeline