save filename with subdir in history

This commit is contained in:
Niklas 2019-05-16 00:29:05 +02:00
parent 7347c9bf42
commit 963b22d0dc
18 changed files with 130 additions and 74 deletions

View File

@ -31,7 +31,7 @@ Additionally, on Linux, you require:
* XCB * XCB
* XCB xfixes * XCB xfixes
* XCB cursor * XCB cursor
* libnotify * Notifications Daemon with org.freedesktop.notifications DBus support (like dunst)
Despite the name implying so, this project does not depend on the KDE API at all. Despite the name implying so, this project does not depend on the KDE API at all.

View File

@ -5,16 +5,17 @@
#include <QNetworkRequest> #include <QNetworkRequest>
#include <thread> #include <thread>
#include <logs/requestlogging.hpp> #include <logs/requestlogging.hpp>
#include <logs/screenshotfile.h>
QNetworkAccessManager ioutils::networkManager; QNetworkAccessManager ioutils::networkManager;
void ioutils::addLogEntry(QNetworkReply* reply, QByteArray data, QString result, QString filename) { void ioutils::addLogEntry(QNetworkReply* reply, QByteArray data, QString result, ScreenshotFile sf) {
requestlogging::RequestContext ctx; requestlogging::RequestContext ctx;
ctx.reply = reply; ctx.reply = reply;
ctx.response = data; ctx.response = data;
ctx.result = result; ctx.result = result;
ctx.filename = filename; ctx.screenshotFile = sf;
requestlogging::addEntry(ctx); requestlogging::addEntry(ctx);
} }

View File

@ -6,10 +6,11 @@
#include <QNetworkAccessManager> #include <QNetworkAccessManager>
#include <QUrl> #include <QUrl>
#include <functional> #include <functional>
#include <logs/screenshotfile.h>
namespace ioutils { namespace ioutils {
extern QNetworkAccessManager networkManager; extern QNetworkAccessManager networkManager;
void addLogEntry(QNetworkReply* reply, QByteArray data, QString result, QString filename); void addLogEntry(QNetworkReply* reply, QByteArray data, QString result, ScreenshotFile sf);
void getJson(QUrl target, void getJson(QUrl target,
QList<QPair<QString, QString>> headers, QList<QPair<QString, QString>> headers,
std::function<void(QJsonDocument, QByteArray, QNetworkReply *)> callback); std::function<void(QJsonDocument, QByteArray, QNetworkReply *)> callback);

View File

@ -2,6 +2,7 @@
#include <QDateTime> #include <QDateTime>
#include <mainwindow.hpp> #include <mainwindow.hpp>
#include <io/ioutils.hpp> #include <io/ioutils.hpp>
#include <logs/screenshotfile.h>
#include <utils.hpp> #include <utils.hpp>
#include "mainwindow.hpp" #include "mainwindow.hpp"
@ -37,10 +38,13 @@ void requestlogging::addEntry(RequestContext context) {
responseFile.write("\n\n" + context.response); responseFile.write("\n\n" + context.response);
responseFile.close(); responseFile.close();
ScreenshotFile sf = context.screenshotFile;
QTextStream(&requestFile) << ioutils::methodString(context.reply->operation()) << " " // $type QTextStream(&requestFile) << ioutils::methodString(context.reply->operation()) << " " // $type
<< context.reply->url().toString().replace(" ", "%20") << " " // $url << context.reply->url().toString().replace(" ", "%20") << " " // $url
<< context.result.replace(" ", "%20") << " " // $result << context.result.replace(" ", "%20") << " " // $result
<< context.filename.replace(" ", "_") << " " // $filename << sf.getSubfolder().replace(" ", "_") << " " // $subfolder
<< sf.getFilename().replace(" ", "_") << " " // $filename
<< context.reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt() << " " // $status << context.reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt() << " " // $status
<< timeNow.replace(" ", "_") << endl << timeNow.replace(" ", "_") << endl
<< flush; // $time << flush; // $time
@ -48,7 +52,7 @@ void requestlogging::addEntry(RequestContext context) {
MainWindow::inst()->addResponse( MainWindow::inst()->addResponse(
context.reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), context.reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(),
context.filename, sf,
context.result, context.result,
context.reply->url().toString(), context.reply->url().toString(),
timeNow.replace("_", " ")); timeNow.replace("_", " "));
@ -66,14 +70,18 @@ QList<LoggedRequest> requestlogging::getRequests() {
while ((line = requestFile.readLine()).size() != 0) { while ((line = requestFile.readLine()).size() != 0) {
LoggedRequest r; LoggedRequest r;
QTextStream stream(&line); QTextStream stream(&line);
ScreenshotFile sf;
stream >> r.type; stream >> r.type;
stream >> r.url; stream >> r.url;
stream >> r.result; stream >> r.result;
stream >> r.filename; stream >> sf.subfolder;
stream >> sf.filename;
stream >> r.responseCode; stream >> r.responseCode;
stream >> r.time; stream >> r.time;
r.time = r.time.replace("_", " "); r.time = r.time.replace("_", " ");
r.filename = r.filename.replace("_", " "); sf.subfolder = sf.subfolder.replace("_", " ");
sf.filename = sf.filename.replace("_", " ");
r.screenshotFile = sf;
ret.append(r); ret.append(r);
} }

View File

@ -5,13 +5,13 @@
#include <QNetworkReply> #include <QNetworkReply>
#include <QString> #include <QString>
#include <settings.hpp> #include <settings.hpp>
#include <logs/screenshotfile.h>
namespace requestlogging { namespace requestlogging {
struct RequestContext { struct RequestContext {
QByteArray response; QByteArray response;
QNetworkReply *reply; QNetworkReply *reply;
QString filename; ScreenshotFile screenshotFile;
QString result; QString result;
}; };
@ -22,8 +22,8 @@ namespace requestlogging {
QString getUrl() { QString getUrl() {
return url; return url;
} }
QString getFilename() { ScreenshotFile getScreenshotFile() {
return filename; return screenshotFile;
} }
QString getType() { QString getType() {
return type; return type;
@ -43,7 +43,7 @@ namespace requestlogging {
private: private:
QString url; QString url;
QString filename; ScreenshotFile screenshotFile;
QString result; QString result;
QString type; QString type;
QString time; QString time;

26
src/logs/screenshotfile.h Normal file
View File

@ -0,0 +1,26 @@
#ifndef SCREENSHOTFILE_H
#define SCREENSHOTFILE_H
#include <QByteArray>
#include <QNetworkReply>
#include <QString>
#include <settings.hpp>
#include <QFile>
class ScreenshotFile {
public:
QString getSubfolder() {
return subfolder;
}
QString getFilename() {
return filename;
}
QString subfolder;
QString filename;
};
#endif // SCREENSHOTFILE_H

View File

@ -26,6 +26,7 @@
#include "io/ioutils.hpp" #include "io/ioutils.hpp"
#include <monospacetextdialog.hpp> #include <monospacetextdialog.hpp>
#include <clipboard/clipboardcopy.hpp> #include <clipboard/clipboardcopy.hpp>
#include <logs/screenshotfile.h>
MainWindow *MainWindow::instance; MainWindow *MainWindow::instance;
@ -143,7 +144,7 @@ MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWi
QList<LoggedRequest> requests = requestlogging::getRequests(); QList<LoggedRequest> requests = requestlogging::getRequests();
for (LoggedRequest req : requests) { for (LoggedRequest req : requests) {
addResponse(req.getResponseCode(), req.getFilename(), req.getResult(), req.getUrl(), req.getTime()); addResponse(req.getResponseCode(), req.getScreenshotFile(), req.getResult(), req.getUrl(), req.getTime());
} }
} }
@ -293,9 +294,9 @@ void MainWindow::setTrayIcon(QIcon icon) {
tray->setIcon(icon); tray->setIcon(icon);
} }
void MainWindow::addResponse(int httpCode, QString filename, QString result, QString url, QString time) { void MainWindow::addResponse(int httpCode, ScreenshotFile sf, QString result, QString url, QString time) {
QString httpStatus = ioutils::httpString(httpCode); QString httpStatus = ioutils::httpString(httpCode);
QTreeWidgetItem* tw = new QTreeWidgetItem({ QString::number(httpCode) + " " + httpStatus, filename, result, url, time + " UTC" }); QTreeWidgetItem* tw = new QTreeWidgetItem({ QString::number(httpCode) + " " + httpStatus, sf.getSubfolder() + QDir::separator() + sf.getFilename(), result, url, time + " UTC" });
if(httpCode >= 200 && httpCode < 300) { if(httpCode >= 200 && httpCode < 300) {
tw->setIcon(0, *(new QIcon(":/icons/checked.png"))); tw->setIcon(0, *(new QIcon(":/icons/checked.png")));
@ -304,4 +305,4 @@ void MainWindow::addResponse(int httpCode, QString filename, QString result, QSt
} }
ui->treeWidget->insertTopLevelItem(0, tw); ui->treeWidget->insertTopLevelItem(0, tw);
} }

View File

@ -9,6 +9,7 @@
#include <recording/recordingcontroller.hpp> #include <recording/recordingcontroller.hpp>
#include <uploaders/uploader.hpp> #include <uploaders/uploader.hpp>
#include <logs/screenshotfile.h>
namespace Ui { namespace Ui {
class MainWindow; class MainWindow;
@ -39,7 +40,7 @@ public:
~MainWindow(); ~MainWindow();
bool valid(); bool valid();
void setTrayIcon(QIcon icon); void setTrayIcon(QIcon icon);
void addResponse(int httpCode, QString filename, QString result, QString url, QString time); void addResponse(int httpCode, ScreenshotFile sf, QString result, QString url, QString time);
RecordingController *controller = new RecordingController; RecordingController *controller = new RecordingController;
QSystemTrayIcon *tray; QSystemTrayIcon *tray;

View File

@ -127,7 +127,8 @@ HEADERS += mainwindow.hpp \
screenoverlay/screenoverlaysettings.hpp \ screenoverlay/screenoverlaysettings.hpp \
logger.hpp \ logger.hpp \
clipboard/clipboardcopy.hpp \ clipboard/clipboardcopy.hpp \
systemnotification.h systemnotification.h \
logs/screenshotfile.h
nopkg { nopkg {
# win32 { # win32 {

View File

@ -12,6 +12,7 @@
#include <formatter.hpp> #include <formatter.hpp>
#include <io/ioutils.hpp> #include <io/ioutils.hpp>
#include <notifications.hpp> #include <notifications.hpp>
#include <logs/screenshotfile.h>
using formats::normalFormatFromName; using formats::normalFormatFromName;
using formats::normalFormatMIME; using formats::normalFormatMIME;
@ -208,7 +209,7 @@ QString parsePathspec(QJsonDocument &response, QString &pathspec) {
return ""; return "";
} }
void CustomUploader::parseResult(QNetworkReply *r, QJsonDocument result, QByteArray data, QString returnPathspec, QString name, QString filename) { void CustomUploader::parseResult(QNetworkReply *r, QJsonDocument result, QByteArray data, QString returnPathspec, QString name, ScreenshotFile sf) {
if (result.isObject()) { if (result.isObject()) {
QString url QString url
= formatter::format(urlPrepend, "") + parsePathspec(result, returnPathspec) + formatter::format(urlAppend, ""); = formatter::format(urlPrepend, "") + parsePathspec(result, returnPathspec) + formatter::format(urlAppend, "");
@ -216,22 +217,22 @@ void CustomUploader::parseResult(QNetworkReply *r, QJsonDocument result, QByteAr
if (!url.isEmpty()) { if (!url.isEmpty()) {
QApplication::clipboard()->setText(url); QApplication::clipboard()->setText(url);
notifications::notify(tr("KShare Custom Uploader ") + name, tr("Copied upload link to clipboard!")); notifications::notify(tr("KShare Custom Uploader ") + name, tr("Copied upload link to clipboard!"));
ioutils::addLogEntry(r, data, url, filename); ioutils::addLogEntry(r, data, url, sf);
} else { } else {
notifications::notify(tr("KShare Custom Uploader ") + name, tr("Upload done, but result empty!")); notifications::notify(tr("KShare Custom Uploader ") + name, tr("Upload done, but result empty!"));
QApplication::clipboard()->setText(data); QApplication::clipboard()->setText(data);
ioutils::addLogEntry(r, data, "", filename); ioutils::addLogEntry(r, data, "", sf);
} }
} else { } else {
notifications::playSound(notifications::Sound::ERROR); notifications::playSound(notifications::Sound::ERROR);
notifications::notify(tr("KShare Custom Uploader ") + name, notifications::notify(tr("KShare Custom Uploader ") + name,
tr("Upload done, but result is not JSON Object! Result in clipboard.")); tr("Upload done, but result is not JSON Object! Result in clipboard."));
QApplication::clipboard()->setText(data); QApplication::clipboard()->setText(data);
ioutils::addLogEntry(r, data, "", filename); ioutils::addLogEntry(r, data, "", sf);
} }
} }
QByteArray substituteArgs(QByteArray arr, QString format, QString filename, QByteArray imgData = QByteArray()) { QByteArray substituteArgs(QByteArray arr, QString format, ScreenshotFile sf, QByteArray imgData = QByteArray()) {
QString mime = normalFormatMIME(normalFormatFromName(format)); QString mime = normalFormatMIME(normalFormatFromName(format));
if (mime.isEmpty()) mime = recordingFormatMIME(recordingFormatFromName(format)); if (mime.isEmpty()) mime = recordingFormatMIME(recordingFormatFromName(format));
if (arr.startsWith("/") && arr.endsWith("/")) { if (arr.startsWith("/") && arr.endsWith("/")) {
@ -241,7 +242,7 @@ QByteArray substituteArgs(QByteArray arr, QString format, QString filename, QByt
{ { "format", format.toLower() }, { "FORMAT", format }, { "contenttype", mime } }) { { "format", format.toLower() }, { "FORMAT", format }, { "contenttype", mime } })
.toUtf8(); .toUtf8();
QByteArray fA = filename.toLocal8Bit(); QByteArray fA = sf.getFilename().toLocal8Bit();
arr.replace("%filename", fA.data()); arr.replace("%filename", fA.data());
if (imgData.isNull()) return arr; if (imgData.isNull()) return arr;
@ -251,17 +252,17 @@ QByteArray substituteArgs(QByteArray arr, QString format, QString filename, QByt
} }
QJsonObject recurseAndReplace(QJsonObject &body, QByteArray &data, QString format, QString filename) { QJsonObject recurseAndReplace(QJsonObject &body, QByteArray &data, QString format, ScreenshotFile sf) {
QJsonObject o; QJsonObject o;
for (QString s : body.keys()) { for (QString s : body.keys()) {
QJsonValue v = body[s]; QJsonValue v = body[s];
if (v.isObject()) { if (v.isObject()) {
QJsonObject vo = v.toObject(); QJsonObject vo = v.toObject();
o.insert(s, recurseAndReplace(vo, data, format, filename)); o.insert(s, recurseAndReplace(vo, data, format, sf));
} else if (v.isString()) { } else if (v.isString()) {
QString str = v.toString(); QString str = v.toString();
if (str.startsWith("/") && str.endsWith("/")) { if (str.startsWith("/") && str.endsWith("/")) {
o.insert(s, QString::fromUtf8(substituteArgs(str.toUtf8(), format, filename, data))); o.insert(s, QString::fromUtf8(substituteArgs(str.toUtf8(), format, sf, data)));
} else } else
o.insert(s, v); o.insert(s, v);
} else } else
@ -270,7 +271,7 @@ QJsonObject recurseAndReplace(QJsonObject &body, QByteArray &data, QString forma
return o; return o;
} }
void CustomUploader::doUpload(QByteArray imgData, QString format, QString filename) { void CustomUploader::doUpload(QByteArray imgData, QString format, ScreenshotFile sf) {
auto h = getHeaders(headers, format, this->rFormat); auto h = getHeaders(headers, format, this->rFormat);
QByteArray data; QByteArray data;
if (base64) imgData = imgData.toBase64(QByteArray::Base64UrlEncoding); if (base64) imgData = imgData.toBase64(QByteArray::Base64UrlEncoding);
@ -281,10 +282,10 @@ void CustomUploader::doUpload(QByteArray imgData, QString format, QString filena
} break; } break;
case RequestFormat::JSON: { case RequestFormat::JSON: {
if (body.isString()) { if (body.isString()) {
data = substituteArgs(body.toString().toUtf8(), format, filename, imgData); data = substituteArgs(body.toString().toUtf8(), format, sf, imgData);
} else { } else {
QJsonObject vo = body.toObject(); QJsonObject vo = body.toObject();
data = QJsonDocument::fromVariant(recurseAndReplace(vo, imgData, format, filename).toVariantMap()).toJson(); data = QJsonDocument::fromVariant(recurseAndReplace(vo, imgData, format, sf).toVariantMap()).toJson();
} }
} break; } break;
case RequestFormat::X_WWW_FORM_URLENCODED: { case RequestFormat::X_WWW_FORM_URLENCODED: {
@ -292,7 +293,7 @@ void CustomUploader::doUpload(QByteArray imgData, QString format, QString filena
for (QString key : body.keys()) { for (QString key : body.keys()) {
QJsonValue val = body[key]; QJsonValue val = body[key];
if (val.isString()) { if (val.isString()) {
data.append(QUrl::toPercentEncoding(key)).append('=').append(substituteArgs(val.toString().toUtf8(), format, filename, imgData)); data.append(QUrl::toPercentEncoding(key)).append('=').append(substituteArgs(val.toString().toUtf8(), format, sf, imgData));
} else { } else {
if (!data.isEmpty()) data.append('&'); if (!data.isEmpty()) data.append('&');
data.append(QUrl::toPercentEncoding(key)) data.append(QUrl::toPercentEncoding(key))
@ -311,7 +312,7 @@ void CustomUploader::doUpload(QByteArray imgData, QString format, QString filena
QHttpPart part; QHttpPart part;
QJsonValue bd = valo["body"]; QJsonValue bd = valo["body"];
if (bd.isString()) { if (bd.isString()) {
QByteArray body = substituteArgs(bd.toString().toUtf8(), format, filename, imgData); QByteArray body = substituteArgs(bd.toString().toUtf8(), format, sf, imgData);
QByteArray *bodyHeap = new QByteArray; QByteArray *bodyHeap = new QByteArray;
body.swap(*bodyHeap); body.swap(*bodyHeap);
QBuffer *buffer = new QBuffer(bodyHeap); QBuffer *buffer = new QBuffer(bodyHeap);
@ -321,7 +322,7 @@ void CustomUploader::doUpload(QByteArray imgData, QString format, QString filena
arraysToDelete.append(bodyHeap); arraysToDelete.append(bodyHeap);
} else { } else {
auto bdo = bd.toObject(); auto bdo = bd.toObject();
QJsonObject result = recurseAndReplace(bdo, imgData, format, filename); QJsonObject result = recurseAndReplace(bdo, imgData, format, sf);
part.setBody(QJsonDocument::fromVariant(result.toVariantMap()).toJson()); part.setBody(QJsonDocument::fromVariant(result.toVariantMap()).toJson());
} }
QByteArray cdh("form-data"); QByteArray cdh("form-data");
@ -329,11 +330,11 @@ void CustomUploader::doUpload(QByteArray imgData, QString format, QString filena
if (headerVal.startsWith("__")) { if (headerVal.startsWith("__")) {
headerVal = headerVal.mid(2); headerVal = headerVal.mid(2);
QByteArray str = valo["__" + headerVal].toString().toUtf8(); QByteArray str = valo["__" + headerVal].toString().toUtf8();
if (str.startsWith("/") && str.endsWith("/")) str = substituteArgs(str, format, filename); if (str.startsWith("/") && str.endsWith("/")) str = substituteArgs(str, format, sf);
part.setRawHeader(headerVal.toLatin1(), str); part.setRawHeader(headerVal.toLatin1(), str);
} else if (headerVal != "body") } else if (headerVal != "body")
cdh += "; " + headerVal + "=\"" cdh += "; " + headerVal + "=\""
+ substituteArgs(valo[headerVal].toString().toUtf8(), format, filename).replace("\"", "\\\"") + "\""; + substituteArgs(valo[headerVal].toString().toUtf8(), format, sf).replace("\"", "\\\"") + "\"";
} }
part.setHeader(QNetworkRequest::ContentDispositionHeader, cdh); part.setHeader(QNetworkRequest::ContentDispositionHeader, cdh);
multipart->append(part); multipart->append(part);
@ -342,8 +343,8 @@ void CustomUploader::doUpload(QByteArray imgData, QString format, QString filena
case HttpMethod::POST: case HttpMethod::POST:
if (returnPathspec == "|") { if (returnPathspec == "|") {
ioutils::postMultipartData(target, h, multipart, ioutils::postMultipartData(target, h, multipart,
[&, buffersToDelete, arraysToDelete, filename](QByteArray result, QNetworkReply *r) { [&, buffersToDelete, arraysToDelete, sf](QByteArray result, QNetworkReply *r) {
ioutils::addLogEntry(r, result, QString::fromUtf8(result), filename); ioutils::addLogEntry(r, result, QString::fromUtf8(result), sf);
QApplication::clipboard()->setText(QString::fromUtf8(result)); QApplication::clipboard()->setText(QString::fromUtf8(result));
for (auto buffer : buffersToDelete) buffer->deleteLater(); for (auto buffer : buffersToDelete) buffer->deleteLater();
for (auto arr : arraysToDelete) delete arr; for (auto arr : arraysToDelete) delete arr;
@ -353,10 +354,10 @@ void CustomUploader::doUpload(QByteArray imgData, QString format, QString filena
}); });
} else { } else {
ioutils::postMultipart(target, h, multipart, ioutils::postMultipart(target, h, multipart,
[&, buffersToDelete, arraysToDelete, filename](QJsonDocument result, QByteArray data, QNetworkReply *r) { [&, buffersToDelete, arraysToDelete, sf](QJsonDocument result, QByteArray data, QNetworkReply *r) {
for (auto buffer : buffersToDelete) buffer->deleteLater(); for (auto buffer : buffersToDelete) buffer->deleteLater();
for (auto arr : arraysToDelete) delete arr; for (auto arr : arraysToDelete) delete arr;
parseResult(r, result, data, returnPathspec, name(), filename); parseResult(r, result, data, returnPathspec, name(), sf);
}); });
} }
break; break;
@ -372,15 +373,15 @@ void CustomUploader::doUpload(QByteArray imgData, QString format, QString filena
switch (method) { switch (method) {
case HttpMethod::POST: case HttpMethod::POST:
if (returnPathspec == "|") { if (returnPathspec == "|") {
ioutils::postData(target, h, data, [&, filename](QByteArray result, QNetworkReply *r) { ioutils::postData(target, h, data, [&, sf](QByteArray result, QNetworkReply *r) {
ioutils::addLogEntry(r, result, QString::fromUtf8(result), filename); ioutils::addLogEntry(r, result, QString::fromUtf8(result), sf);
QApplication::clipboard()->setText(QString::fromUtf8(result)); QApplication::clipboard()->setText(QString::fromUtf8(result));
notifications::playSound(notifications::Sound::SUCCESS); notifications::playSound(notifications::Sound::SUCCESS);
notifications::notify(tr("KShare Custom Uploader ") + name(), tr("Copied upload result to clipboard!")); notifications::notify(tr("KShare Custom Uploader ") + name(), tr("Copied upload result to clipboard!"));
}); });
} else { } else {
ioutils::postJson(target, h, data, [&, filename](QJsonDocument result, QByteArray data, QNetworkReply *r) { ioutils::postJson(target, h, data, [&, sf](QJsonDocument result, QByteArray data, QNetworkReply *r) {
parseResult(r, result, data, returnPathspec, name(), filename); parseResult(r, result, data, returnPathspec, name(), sf);
}); });
} }
break; break;

View File

@ -7,6 +7,7 @@
#include <QMap> #include <QMap>
#include <QUrl> #include <QUrl>
#include <QNetworkReply> #include <QNetworkReply>
#include <logs/screenshotfile.h>
enum class HttpMethod { POST }; enum class HttpMethod { POST };
@ -19,7 +20,7 @@ public:
CustomUploader(QString absFilePath); CustomUploader(QString absFilePath);
QString name(); QString name();
QString description(); QString description();
void doUpload(QByteArray imgData, QString format, QString filename); void doUpload(QByteArray imgData, QString format, ScreenshotFile sf);
private: private:
double limit = -1; double limit = -1;
@ -33,7 +34,7 @@ private:
bool base64 = false; bool base64 = false;
QString returnPathspec; QString returnPathspec;
QString urlPrepend, urlAppend; QString urlPrepend, urlAppend;
void parseResult(QNetworkReply *r, QJsonDocument result, QByteArray data, QString returnPathspec, QString name, QString filename); void parseResult(QNetworkReply *r, QJsonDocument result, QByteArray data, QString returnPathspec, QString name, ScreenshotFile sf);
}; };
#endif // CUSTOMUPLOADER_HPP #endif // CUSTOMUPLOADER_HPP

View File

@ -6,8 +6,9 @@
#include <formats.hpp> #include <formats.hpp>
#include <notifications.hpp> #include <notifications.hpp>
#include <QString> #include <QString>
#include <logs/screenshotfile.h>
void ClipboardUploader::doUpload(QByteArray imgData, QString format, QString filename) { void ClipboardUploader::doUpload(QByteArray imgData, QString format, ScreenshotFile sf) {
auto f = formats::recordingFormatFromName(format); auto f = formats::recordingFormatFromName(format);
if (f != formats::Recording::None) { if (f != formats::Recording::None) {
auto data = new QMimeData(); auto data = new QMimeData();

View File

@ -4,6 +4,7 @@
#include <QApplication> #include <QApplication>
#include <QPixmap> #include <QPixmap>
#include <uploaders/uploader.hpp> #include <uploaders/uploader.hpp>
#include <logs/screenshotfile.h>
class ClipboardUploader : public Uploader { class ClipboardUploader : public Uploader {
Q_DECLARE_TR_FUNCTIONS(ClipboardUploader) Q_DECLARE_TR_FUNCTIONS(ClipboardUploader)
@ -15,7 +16,7 @@ public:
return "Copies the image to clipboard"; return "Copies the image to clipboard";
} }
void doUpload(QByteArray imgData, QString format, QString filename); void doUpload(QByteArray imgData, QString format, ScreenshotFile sf);
}; };
#endif // CLIPBOARDUPLOADER_HPP #endif // CLIPBOARDUPLOADER_HPP

View File

@ -11,6 +11,7 @@
#include <notifications.hpp> #include <notifications.hpp>
#include <settings.hpp> #include <settings.hpp>
#include <utils.hpp> #include <utils.hpp>
#include <logs/screenshotfile.h>
struct SegfaultWorkaround { // I'm a scrub for doing this struct SegfaultWorkaround { // I'm a scrub for doing this
SegfaultWorkaround(QByteArray a, ImgurUploader *u, QString m) : byteArray(), dis(u), mime(m) { SegfaultWorkaround(QByteArray a, ImgurUploader *u, QString m) : byteArray(), dis(u), mime(m) {
@ -25,14 +26,15 @@ struct SegfaultWorkaround { // I'm a scrub for doing this
QUrl("https://api.imgur.com/oauth2/token"), QUrl("https://api.imgur.com/oauth2/token"),
QList<QPair<QString, QString>>({ QPair<QString, QString>("Content-Type", "applicaton/json") }), QList<QPair<QString, QString>>({ QPair<QString, QString>("Content-Type", "applicaton/json") }),
QJsonDocument::fromVariant(object.toVariantMap()).toJson(), [&](QJsonDocument response, QByteArray, QNetworkReply *r) { QJsonDocument::fromVariant(object.toVariantMap()).toJson(), [&](QJsonDocument response, QByteArray, QNetworkReply *r) {
ScreenshotFile sf;
qDebug() << response; qDebug() << response;
if (r->error() != QNetworkReply::NoError || !response.isObject()) { if (r->error() != QNetworkReply::NoError || !response.isObject()) {
dis->handleSend(QStringLiteral("Client-ID 8a98f183fc895da"), mime, byteArray); dis->handleSend(QStringLiteral("Client-ID 8a98f183fc895da"), mime, byteArray, sf);
return; return;
} }
QJsonObject res = response.object(); QJsonObject res = response.object();
if (res.value("success").toBool()) { if (res.value("success").toBool()) {
dis->handleSend(QStringLiteral("Client-ID 8a98f183fc895da"), mime, byteArray); dis->handleSend(QStringLiteral("Client-ID 8a98f183fc895da"), mime, byteArray, sf);
return; return;
} }
@ -41,7 +43,7 @@ struct SegfaultWorkaround { // I'm a scrub for doing this
settings::settings().setValue("imgur/refresh", res["refresh_token"].toString()); settings::settings().setValue("imgur/refresh", res["refresh_token"].toString());
settings::settings().setValue("imgur/access", token); settings::settings().setValue("imgur/access", token);
dis->handleSend(token.prepend("Bearer "), mime, byteArray); dis->handleSend(token.prepend("Bearer "), mime, byteArray, sf);
QScopedPointer<SegfaultWorkaround>(this); QScopedPointer<SegfaultWorkaround>(this);
}); });
} }
@ -52,7 +54,7 @@ private:
QString mime; QString mime;
}; // I feel terrible for making this. I am sorry, reader }; // I feel terrible for making this. I am sorry, reader
void ImgurUploader::doUpload(QByteArray byteArray, QString format, QString filename) { void ImgurUploader::doUpload(QByteArray byteArray, QString format, ScreenshotFile sf) {
if (byteArray.size() > 1e+7) { if (byteArray.size() > 1e+7) {
notifications::notify(tr("KShare imgur Uploader"), tr("Failed upload! Image too big")); notifications::notify(tr("KShare imgur Uploader"), tr("Failed upload! Image too big"));
return; return;
@ -69,32 +71,32 @@ void ImgurUploader::doUpload(QByteArray byteArray, QString format, QString filen
if (QDateTime::currentDateTimeUtc() > expireTime) { if (QDateTime::currentDateTimeUtc() > expireTime) {
new SegfaultWorkaround(byteArray, this, mime); new SegfaultWorkaround(byteArray, this, mime);
} else } else
handleSend("Bearer " + settings::settings().value("imgur/access").toString(), mime, byteArray, filename); handleSend("Bearer " + settings::settings().value("imgur/access").toString(), mime, byteArray, sf);
} else } else
handleSend(QStringLiteral("Client-ID 8a98f183fc895da"), mime, byteArray, filename); handleSend(QStringLiteral("Client-ID 8a98f183fc895da"), mime, byteArray, sf);
} }
void ImgurUploader::showSettings() { void ImgurUploader::showSettings() {
(new ImgurSettingsDialog())->show(); (new ImgurSettingsDialog())->show();
} }
void ImgurUploader::handleSend(QString auth, QString mime, QByteArray byteArray, QString filename) { void ImgurUploader::handleSend(QString auth, QString mime, QByteArray byteArray, ScreenshotFile sf) {
ioutils::postJson(QUrl("https://api.imgur.com/3/image"), ioutils::postJson(QUrl("https://api.imgur.com/3/image"),
QList<QPair<QString, QString>>() << QPair<QString, QString>("Content-Type", mime.toUtf8()) QList<QPair<QString, QString>>() << QPair<QString, QString>("Content-Type", mime.toUtf8())
<< QPair<QString, QString>("Authorization", auth), << QPair<QString, QString>("Authorization", auth),
byteArray, [byteArray, this, mime, filename](QJsonDocument res, QByteArray data, QNetworkReply *r) { byteArray, [byteArray, this, mime, sf](QJsonDocument res, QByteArray data, QNetworkReply *r) {
QString result = res.object()["data"].toObject()["link"].toString(); QString result = res.object()["data"].toObject()["link"].toString();
if (r->error() == QNetworkReply::ContentAccessDenied) { if (r->error() == QNetworkReply::ContentAccessDenied) {
new SegfaultWorkaround(byteArray, this, mime); new SegfaultWorkaround(byteArray, this, mime);
return; return;
} }
if (!result.isEmpty()) { if (!result.isEmpty()) {
ioutils::addLogEntry(r, data, result, filename); ioutils::addLogEntry(r, data, result, sf);
utils::toClipboard(result); utils::toClipboard(result);
notifications::notify(tr("KShare imgur Uploader"), tr("Uploaded to imgur!")); notifications::notify(tr("KShare imgur Uploader"), tr("Uploaded to imgur!"));
notifications::playSound(notifications::Sound::SUCCESS); notifications::playSound(notifications::Sound::SUCCESS);
} else { } else {
ioutils::addLogEntry(r, data, result, filename); ioutils::addLogEntry(r, data, result, sf);
notifications::notify(tr("KShare imgur Uploader "), notifications::notify(tr("KShare imgur Uploader "),
QString(tr("Failed upload! imgur said: HTTP %1: %2")) QString(tr("Failed upload! imgur said: HTTP %1: %2"))
.arg(r->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt()) .arg(r->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt())
@ -103,7 +105,3 @@ void ImgurUploader::handleSend(QString auth, QString mime, QByteArray byteArray,
} }
}); });
} }
void ImgurUploader::handleSend(QString auth, QString mime, QByteArray byteArray) {
handleSend(auth, mime, byteArray);
}

View File

@ -3,6 +3,7 @@
#include "../uploader.hpp" #include "../uploader.hpp"
#include <QApplication> #include <QApplication>
#include <logs/screenshotfile.h>
class ImgurUploader : public Uploader { class ImgurUploader : public Uploader {
Q_DECLARE_TR_FUNCTIONS(ImgurUploader) Q_DECLARE_TR_FUNCTIONS(ImgurUploader)
@ -15,12 +16,11 @@ public:
QString description() override { QString description() override {
return "imgur.com uploader"; return "imgur.com uploader";
} }
void doUpload(QByteArray byteArray, QString, QString filename) override; void doUpload(QByteArray byteArray, QString, ScreenshotFile sf) override;
void showSettings() override; void showSettings() override;
private: private:
void handleSend(QString auth, QString mime, QByteArray byteArray, QString filename); void handleSend(QString auth, QString mime, QByteArray byteArray, ScreenshotFile sf);
void handleSend(QString auth, QString mime, QByteArray byteArray);
}; };
#endif // IMGURUPLOADER_HPP #endif // IMGURUPLOADER_HPP

View File

@ -3,10 +3,11 @@
#include <QPixmap> #include <QPixmap>
#include <QString> #include <QString>
#include <logs/screenshotfile.h>
class Uploader { class Uploader {
public: public:
virtual void doUpload(QByteArray imgData, QString format, QString filename) = 0; virtual void doUpload(QByteArray imgData, QString format, ScreenshotFile sf) = 0;
virtual QString name() = 0; virtual QString name() = 0;
virtual QString description() = 0; virtual QString description() = 0;
virtual void showSettings() { virtual void showSettings() {

View File

@ -14,6 +14,7 @@
#include <notifications.hpp> #include <notifications.hpp>
#include <settings.hpp> #include <settings.hpp>
#include "mainwindow.hpp" #include "mainwindow.hpp"
#include <logs/screenshotfile.h>
UploaderSingleton::UploaderSingleton() : QObject() { UploaderSingleton::UploaderSingleton() : QObject() {
updateSaveSettings(); updateSaveSettings();
@ -73,8 +74,7 @@ void UploaderSingleton::upload(QPixmap pixmap) {
notifications::playSound(notifications::Sound::CAPTURE); notifications::playSound(notifications::Sound::CAPTURE);
pixmap.save(file, format.toLocal8Bit().constData(), settings::settings().value("imageQuality", -1).toInt()); pixmap.save(file, format.toLocal8Bit().constData(), settings::settings().value("imageQuality", -1).toInt());
file->seek(0); file->seek(0);
QFileInfo fileInfo(file->fileName()); u->doUpload(file->readAll(), format, getScreenshotFile(*file));
u->doUpload(file->readAll(), format, fileInfo.fileName());
} else } else
notifications::notify(tr("KShare - Failed to save picture"), file->errorString(), QSystemTrayIcon::Warning); notifications::notify(tr("KShare - Failed to save picture"), file->errorString(), QSystemTrayIcon::Warning);
delete file; delete file;
@ -96,9 +96,8 @@ void UploaderSingleton::upload(QByteArray img, QString format) {
file->write(img); file->write(img);
file->close(); file->close();
} }
QFileInfo fileInfo(file->fileName()); uploaders.value(uploader)->doUpload(img, format, getScreenshotFile(*file));
delete file; delete file;
uploaders.value(uploader)->doUpload(img, format, fileInfo.fileName());
} }
void UploaderSingleton::upload(QFile &img, QString format) { void UploaderSingleton::upload(QFile &img, QString format) {
@ -108,9 +107,8 @@ void UploaderSingleton::upload(QFile &img, QString format) {
formatter::format(settings::settings().value("fileFormat", "Screenshot %(yyyy-MM-dd HH-mm-ss)date.%ext").toString(), formatter::format(settings::settings().value("fileFormat", "Screenshot %(yyyy-MM-dd HH-mm-ss)date.%ext").toString(),
format.toLower())))) { format.toLower())))) {
notifications::playSound(notifications::Sound::CAPTURE); notifications::playSound(notifications::Sound::CAPTURE);
QFileInfo fileInfo(img.fileName());
if (img.open(QFile::ReadWrite)) if (img.open(QFile::ReadWrite))
uploaders.value(uploader)->doUpload(img.readAll(), format, fileInfo.fileName()); uploaders.value(uploader)->doUpload(img.readAll(), format, getScreenshotFile(img));
else else
notifications::notify(tr("KShare - Failed to save picture"), img.errorString(), QSystemTrayIcon::Warning); notifications::notify(tr("KShare - Failed to save picture"), img.errorString(), QSystemTrayIcon::Warning);
} else } else
@ -120,9 +118,8 @@ void UploaderSingleton::upload(QFile &img, QString format) {
void UploaderSingleton::upload(QFile &img) { void UploaderSingleton::upload(QFile &img) {
updateSaveSettings(); updateSaveSettings();
if (img.size() <= 0) return; if (img.size() <= 0) return;
QFileInfo fileInfo(img.fileName());
if (img.open(QFile::ReadWrite)) if (img.open(QFile::ReadWrite))
uploaders.value(uploader)->doUpload(img.readAll(), "", fileInfo.fileName()); uploaders.value(uploader)->doUpload(img.readAll(), "", getScreenshotFile(img));
else else
notifications::notify(tr("KShare - Failed to open File"), img.errorString(), QSystemTrayIcon::Warning); notifications::notify(tr("KShare - Failed to open File"), img.errorString(), QSystemTrayIcon::Warning);
} }
@ -159,6 +156,18 @@ QString UploaderSingleton::currentUploader() {
return uploader; return uploader;
} }
QString UploaderSingleton::getFormattedSubfolder() {
return formatter::format(settings::settings().value("folderFormat", "%(yyyy-MM)date").toString(), "");
}
ScreenshotFile UploaderSingleton::getScreenshotFile(QFile &f) {
ScreenshotFile sf;
sf.subfolder = getFormattedSubfolder();
QFileInfo fi(f);
sf.filename = fi.fileName();
return sf;
}
void UploaderSingleton::updateSaveSettings() { void UploaderSingleton::updateSaveSettings() {
switch (settings::settings().value("saveLocation", 1).toInt()) { switch (settings::settings().value("saveLocation", 1).toInt()) {
case 0: case 0:
@ -180,6 +189,8 @@ void UploaderSingleton::updateSaveSettings() {
break; break;
} }
saveDir = QDir(saveDir.absolutePath() + QDir::separator() + getFormattedSubfolder());
if (!saveDir.exists()) { if (!saveDir.exists()) {
if (!saveDir.mkpath(".")) { if (!saveDir.mkpath(".")) {
qFatal("Could not create the path %s to store images in!", saveDir.absolutePath().toLocal8Bit().constData()); qFatal("Could not create the path %s to store images in!", saveDir.absolutePath().toLocal8Bit().constData());

View File

@ -4,6 +4,7 @@
#include "uploader.hpp" #include "uploader.hpp"
#include <QDir> #include <QDir>
#include <QMap> #include <QMap>
#include <logs/screenshotfile.h>
class UploaderSingleton : public QObject { class UploaderSingleton : public QObject {
Q_OBJECT Q_OBJECT
@ -31,6 +32,8 @@ signals:
private: private:
void updateSaveSettings(); void updateSaveSettings();
QString getFormattedSubfolder();
ScreenshotFile getScreenshotFile(QFile &f);
QDir saveDir; QDir saveDir;
bool saveImages = true; bool saveImages = true;
QMap<QString, Uploader *> uploaders; QMap<QString, Uploader *> uploaders;