Add WebAPI/WebUI for managing cookies

Closes #21125.
PR #21340.
This commit is contained in:
Thomas Piccirello 2024-09-30 05:13:25 -04:00 committed by GitHub
parent 10eb921d70
commit 6bbb7b71cd
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
10 changed files with 285 additions and 29 deletions

View file

@ -41,6 +41,7 @@
#include <QJsonArray> #include <QJsonArray>
#include <QJsonDocument> #include <QJsonDocument>
#include <QJsonObject> #include <QJsonObject>
#include <QNetworkCookie>
#include <QNetworkInterface> #include <QNetworkInterface>
#include <QRegularExpression> #include <QRegularExpression>
#include <QStringList> #include <QStringList>
@ -50,6 +51,7 @@
#include "base/bittorrent/session.h" #include "base/bittorrent/session.h"
#include "base/global.h" #include "base/global.h"
#include "base/interfaces/iapplication.h" #include "base/interfaces/iapplication.h"
#include "base/net/downloadmanager.h"
#include "base/net/portforwarder.h" #include "base/net/portforwarder.h"
#include "base/net/proxyconfigurationmanager.h" #include "base/net/proxyconfigurationmanager.h"
#include "base/path.h" #include "base/path.h"
@ -58,6 +60,7 @@
#include "base/rss/rss_session.h" #include "base/rss/rss_session.h"
#include "base/torrentfileguard.h" #include "base/torrentfileguard.h"
#include "base/torrentfileswatcher.h" #include "base/torrentfileswatcher.h"
#include "base/utils/datetime.h"
#include "base/utils/fs.h" #include "base/utils/fs.h"
#include "base/utils/misc.h" #include "base/utils/misc.h"
#include "base/utils/net.h" #include "base/utils/net.h"
@ -69,6 +72,12 @@
using namespace std::chrono_literals; using namespace std::chrono_literals;
const QString KEY_COOKIE_NAME = u"name"_s;
const QString KEY_COOKIE_DOMAIN = u"domain"_s;
const QString KEY_COOKIE_PATH = u"path"_s;
const QString KEY_COOKIE_VALUE = u"value"_s;
const QString KEY_COOKIE_EXPIRATION_DATE = u"expirationDate"_s;
void AppController::webapiVersionAction() void AppController::webapiVersionAction()
{ {
setResult(API_VERSION.toString()); setResult(API_VERSION.toString());
@ -1187,6 +1196,63 @@ void AppController::getDirectoryContentAction()
setResult(ret); setResult(ret);
} }
void AppController::cookiesAction()
{
const QList<QNetworkCookie> cookies = Net::DownloadManager::instance()->allCookies();
QJsonArray ret;
for (const QNetworkCookie &cookie : cookies)
{
ret << QJsonObject {
{KEY_COOKIE_NAME, QString::fromLatin1(cookie.name())},
{KEY_COOKIE_DOMAIN, cookie.domain()},
{KEY_COOKIE_PATH, cookie.path()},
{KEY_COOKIE_VALUE, QString::fromLatin1(cookie.value())},
{KEY_COOKIE_EXPIRATION_DATE, Utils::DateTime::toSecsSinceEpoch(cookie.expirationDate())},
};
}
setResult(ret);
}
void AppController::setCookiesAction()
{
requireParams({u"cookies"_s});
const QString cookiesParam {params()[u"cookies"_s].trimmed()};
QJsonParseError jsonError;
const auto cookiesJsonDocument = QJsonDocument::fromJson(cookiesParam.toUtf8(), &jsonError);
if (jsonError.error != QJsonParseError::NoError)
throw APIError(APIErrorType::BadParams, jsonError.errorString());
if (!cookiesJsonDocument.isArray())
throw APIError(APIErrorType::BadParams, tr("cookies must be array"));
const QJsonArray cookiesJsonArr = cookiesJsonDocument.array();
QList<QNetworkCookie> cookies;
cookies.reserve(cookiesJsonArr.size());
for (const QJsonValue &jsonVal : cookiesJsonArr)
{
if (!jsonVal.isObject())
throw APIError(APIErrorType::BadParams);
QNetworkCookie cookie;
const QJsonObject jsonObj = jsonVal.toObject();
if (jsonObj.contains(KEY_COOKIE_NAME))
cookie.setName(jsonObj.value(KEY_COOKIE_NAME).toString().toLatin1());
if (jsonObj.contains(KEY_COOKIE_DOMAIN))
cookie.setDomain(jsonObj.value(KEY_COOKIE_DOMAIN).toString());
if (jsonObj.contains(KEY_COOKIE_PATH))
cookie.setPath(jsonObj.value(KEY_COOKIE_PATH).toString());
if (jsonObj.contains(KEY_COOKIE_VALUE))
cookie.setValue(jsonObj.value(KEY_COOKIE_VALUE).toString().toUtf8());
if (jsonObj.contains(KEY_COOKIE_EXPIRATION_DATE))
cookie.setExpirationDate(QDateTime::fromSecsSinceEpoch(jsonObj.value(KEY_COOKIE_EXPIRATION_DATE).toInteger()));
cookies << cookie;
}
Net::DownloadManager::instance()->setAllCookies(cookies);
}
void AppController::networkInterfaceListAction() void AppController::networkInterfaceListAction()
{ {
QJsonArray ifaceList; QJsonArray ifaceList;

View file

@ -50,6 +50,8 @@ private slots:
void defaultSavePathAction(); void defaultSavePathAction();
void sendTestEmailAction(); void sendTestEmailAction();
void getDirectoryContentAction(); void getDirectoryContentAction();
void cookiesAction();
void setCookiesAction();
void networkInterfaceListAction(); void networkInterfaceListAction();
void networkInterfaceAddressListAction(); void networkInterfaceAddressListAction();

View file

@ -34,7 +34,6 @@
#include <QJsonArray> #include <QJsonArray>
#include <QJsonObject> #include <QJsonObject>
#include <QList> #include <QList>
#include <QNetworkCookie>
#include <QRegularExpression> #include <QRegularExpression>
#include <QUrl> #include <QUrl>
@ -53,7 +52,6 @@
#include "base/interfaces/iapplication.h" #include "base/interfaces/iapplication.h"
#include "base/global.h" #include "base/global.h"
#include "base/logger.h" #include "base/logger.h"
#include "base/net/downloadmanager.h"
#include "base/torrentfilter.h" #include "base/torrentfilter.h"
#include "base/utils/datetime.h" #include "base/utils/datetime.h"
#include "base/utils/fs.h" #include "base/utils/fs.h"
@ -787,7 +785,6 @@ void TorrentsController::pieceStatesAction()
void TorrentsController::addAction() void TorrentsController::addAction()
{ {
const QString urls = params()[u"urls"_s]; const QString urls = params()[u"urls"_s];
const QString cookie = params()[u"cookie"_s];
const bool skipChecking = parseBool(params()[u"skip_checking"_s]).value_or(false); const bool skipChecking = parseBool(params()[u"skip_checking"_s]).value_or(false);
const bool seqDownload = parseBool(params()[u"sequentialDownload"_s]).value_or(false); const bool seqDownload = parseBool(params()[u"sequentialDownload"_s]).value_or(false);
@ -818,23 +815,6 @@ void TorrentsController::addAction()
? Utils::String::toEnum(contentLayoutParam, BitTorrent::TorrentContentLayout::Original) ? Utils::String::toEnum(contentLayoutParam, BitTorrent::TorrentContentLayout::Original)
: std::optional<BitTorrent::TorrentContentLayout> {}); : std::optional<BitTorrent::TorrentContentLayout> {});
QList<QNetworkCookie> cookies;
if (!cookie.isEmpty())
{
const QStringList cookiesStr = cookie.split(u"; "_s);
for (QString cookieStr : cookiesStr)
{
cookieStr = cookieStr.trimmed();
int index = cookieStr.indexOf(u'=');
if (index > 1)
{
QByteArray name = cookieStr.left(index).toLatin1();
QByteArray value = cookieStr.right(cookieStr.length() - index - 1).toLatin1();
cookies += QNetworkCookie(name, value);
}
}
}
const BitTorrent::AddTorrentParams addTorrentParams const BitTorrent::AddTorrentParams addTorrentParams
{ {
// TODO: Check if destination actually exists // TODO: Check if destination actually exists
@ -875,7 +855,6 @@ void TorrentsController::addAction()
url = url.trimmed(); url = url.trimmed();
if (!url.isEmpty()) if (!url.isEmpty())
{ {
Net::DownloadManager::instance()->setCookiesFromUrl(cookies, QUrl::fromEncoded(url.toUtf8()));
partialSuccess |= app()->addTorrentManager()->addTorrent(url, addTorrentParams); partialSuccess |= app()->addTorrentManager()->addTorrent(url, addTorrentParams);
} }
} }

View file

@ -152,6 +152,7 @@ private:
{ {
// <<controller name, action name>, HTTP method> // <<controller name, action name>, HTTP method>
{{u"app"_s, u"sendTestEmail"_s}, Http::METHOD_POST}, {{u"app"_s, u"sendTestEmail"_s}, Http::METHOD_POST},
{{u"app"_s, u"setCookies"_s}, Http::METHOD_POST},
{{u"app"_s, u"setPreferences"_s}, Http::METHOD_POST}, {{u"app"_s, u"setPreferences"_s}, Http::METHOD_POST},
{{u"app"_s, u"shutdown"_s}, Http::METHOD_POST}, {{u"app"_s, u"shutdown"_s}, Http::METHOD_POST},
{{u"auth"_s, u"login"_s}, Http::METHOD_POST}, {{u"auth"_s, u"login"_s}, Http::METHOD_POST},

View file

@ -44,14 +44,6 @@
<input type="text" id="savepath" name="savepath" class="pathDirectory" style="width: 16em;"> <input type="text" id="savepath" name="savepath" class="pathDirectory" style="width: 16em;">
</td> </td>
</tr> </tr>
<tr>
<td>
<label for="cookie">QBT_TR(Cookie:)QBT_TR[CONTEXT=HttpServer]</label>
</td>
<td>
<input type="text" id="cookie" name="cookie" style="width: 16em;">
</td>
</tr>
<tr> <tr>
<td> <td>
<label for="rename">QBT_TR(Rename torrent)QBT_TR[CONTEXT=HttpServer]</label> <label for="rename">QBT_TR(Rename torrent)QBT_TR[CONTEXT=HttpServer]</label>

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 5.1 KiB

View file

@ -94,6 +94,7 @@
<ul> <ul>
<li><a id="preferencesLink"><img class="MyMenuIcon" src="images/configure.svg" alt="QBT_TR(Options...)QBT_TR[CONTEXT=MainWindow]" width="16" height="16">QBT_TR(Options...)QBT_TR[CONTEXT=MainWindow]</a></li> <li><a id="preferencesLink"><img class="MyMenuIcon" src="images/configure.svg" alt="QBT_TR(Options...)QBT_TR[CONTEXT=MainWindow]" width="16" height="16">QBT_TR(Options...)QBT_TR[CONTEXT=MainWindow]</a></li>
<li><a id="registerMagnetHandlerLink"><img class="MyMenuIcon" src="images/torrent-magnet.svg" alt="QBT_TR(Register to handle magnet links...)QBT_TR[CONTEXT=HttpServer]" width="16" height="16">QBT_TR(Register to handle magnet links...)QBT_TR[CONTEXT=HttpServer]</a></li> <li><a id="registerMagnetHandlerLink"><img class="MyMenuIcon" src="images/torrent-magnet.svg" alt="QBT_TR(Register to handle magnet links...)QBT_TR[CONTEXT=HttpServer]" width="16" height="16">QBT_TR(Register to handle magnet links...)QBT_TR[CONTEXT=HttpServer]</a></li>
<li><a id="manageCookiesLink"><img class="MyMenuIcon" src="images/browser-cookies.svg" alt="QBT_TR(Manage Cookies...)QBT_TR[CONTEXT=MainWindow]" width="16" height="16">QBT_TR(Manage Cookies...)QBT_TR[CONTEXT=MainWindow]</a></li>
</ul> </ul>
</li> </li>
<li> <li>

View file

@ -239,6 +239,27 @@ const initializeWindows = function() {
}); });
}); });
addClickEvent("manageCookies", (e) => {
e.preventDefault();
e.stopPropagation();
const id = "cookiesPage";
new MochaUI.Window({
id: id,
title: "QBT_TR(Manage Cookies)QBT_TR[CONTEXT=CookiesDialog]",
loadMethod: "xhr",
contentURL: new URI("views/cookies.html").toString(),
maximizable: false,
paddingVertical: 0,
paddingHorizontal: 0,
width: loadWindowWidth(id, 900),
height: loadWindowHeight(id, 400),
onResize: function() {
saveWindowSize(id);
}
});
});
addClickEvent("upload", (e) => { addClickEvent("upload", (e) => {
e.preventDefault(); e.preventDefault();
e.stopPropagation(); e.stopPropagation();

View file

@ -0,0 +1,191 @@
<style>
#manageCookiesContainer {
margin: 10px;
.buttonContainer {
text-align: center;
margin-top: 1em;
}
}
#manageCookiesTable {
tbody {
td input {
width: 140px;
}
td.expDate input {
width: 190px;
}
}
thead td {
width: 150px;
.expDate {
width: 200px;
}
.actionColumn {
width: 30px;
}
}
.removeCookie,
.addCookie {
height: 16px;
width: 16px;
padding-left: 10px;
vertical-align: middle;
cursor: pointer;
}
}
</style>
<div id="manageCookiesContainer">
<table id="manageCookiesTable">
<thead>
<tr>
<td class="domain">QBT_TR(Domain)QBT_TR[CONTEXT=CookiesDialog]</td>
<td class="path">QBT_TR(Path)QBT_TR[CONTEXT=CookiesDialog]</td>
<td class="name">QBT_TR(Name)QBT_TR[CONTEXT=CookiesDialog]</td>
<td class="value">QBT_TR(Value)QBT_TR[CONTEXT=CookiesDialog]</td>
<td class="expDate">QBT_TR(Expiration Date)QBT_TR[CONTEXT=CookiesDialog]</td>
<td class="actionColumn"></td>
</tr>
</thead>
<tbody>
<tr class="invisible newRow">
<td class="domain"><input type="text" aria-label="QBT_TR(Domain)QBT_TR[CONTEXT=CookiesDialog]" autocomplete="off" autocorrect="off" autocapitalize="none"></td>
<td class="path"><input type="text" aria-label="QBT_TR(Path)QBT_TR[CONTEXT=CookiesDialog]" autocomplete="off" autocorrect="off" autocapitalize="none"></td>
<td class="name"><input type="text" aria-label="QBT_TR(Name)QBT_TR[CONTEXT=CookiesDialog]" autocomplete="off" autocorrect="off" autocapitalize="none"></td>
<td class="value"><input type="text" aria-label="QBT_TR(Value)QBT_TR[CONTEXT=CookiesDialog]" autocomplete="off" autocorrect="off" autocapitalize="none"></td>
<td class="expDate"><input type="datetime-local" aria-label="QBT_TR(Expiration Date)QBT_TR[CONTEXT=CookiesDialog]"></td>
<td><img class="removeCookie" src="images/list-remove.svg" alt="QBT_TR(Remove)QBT_TR[CONTEXT=CookiesDialog]"></td>
</tr>
</tbody>
<tfoot>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td><img class="addCookie" src="images/list-add.svg" alt="QBT_TR(Add Cookie)QBT_TR[CONTEXT=CookiesDialog]"></td>
</tr>
</tfoot>
</table>
<div class="buttonContainer">
<button type="button" id="saveButton">QBT_TR(Save)QBT_TR[CONTEXT=HttpServer]</button>
</div>
</div>
<script>
"use strict";
window.qBittorrent ??= {};
window.qBittorrent.ManageCookies ??= (() => {
const exports = () => {
return {
setup: setup
};
};
const addCookie = function() {
const newRow = document.querySelector("#manageCookiesTable tr.newRow").cloneNode(true);
newRow.querySelector(".removeCookie").addEventListener("click", (event) => {
deleteCookie(event.target);
});
newRow.classList.remove("invisible");
document.querySelector("#manageCookiesTable tbody").append(newRow);
return newRow;
};
const deleteCookie = function(element) {
element.closest("tr").destroy();
};
const save = function() {
const rows = [...document.querySelectorAll("#manageCookiesTable tbody tr")].filter(e => !e.hasClass("invisible"));
const cookies = rows.map(row => {
const expDateValue = row.querySelector("td.expDate input").valueAsNumber;
// remove ms from string
const expDate = Number.isInteger(expDateValue) ? Number(String(expDateValue).slice(0, -3)) : 0;
return {
domain: row.querySelector("td.domain input").value,
path: row.querySelector("td.path input").value,
name: row.querySelector("td.name input").value,
value: row.querySelector("td.value input").value,
expirationDate: expDate,
};
});
new Request({
url: "api/v2/app/setCookies",
method: "post",
noCache: true,
data: {
cookies: JSON.stringify(cookies)
},
onFailure: (response) => {
let error = "Unable to save cookies";
if (response?.responseText)
error += `: ${response.responseText}`;
alert(error);
},
onSuccess: (response) => {
window.qBittorrent.Client.closeWindow("cookiesPage");
}
}).send();
};
const loadCookies = function() {
new Request.JSON({
url: "api/v2/app/cookies",
method: "get",
onFailure: (response) => {
let error = "Unable to load cookies";
if (response?.responseText)
error += `: ${response.responseText}`;
alert(error);
},
onSuccess: (response) => {
for (const cookie of response) {
const row = addCookie();
row.querySelector("td.domain input").value = cookie.domain;
row.querySelector("td.path input").value = cookie.path;
row.querySelector("td.name input").value = cookie.name;
row.querySelector("td.value input").value = cookie.value;
if (cookie.expirationDate > 0) {
// remove seconds + milliseconds, if any, to ensure seconds aren't displayed in input field
const date = new Date(cookie.expirationDate * 1000);
date.setSeconds(0);
date.setMilliseconds(0);
row.querySelector("td.expDate input").valueAsNumber = date.getTime();
}
}
}
}).send();
};
const setup = function() {
loadCookies();
document.querySelector(".addCookie").addEventListener("click", (event) => {
addCookie();
});
document.querySelector("#saveButton").addEventListener("click", (event) => {
save();
});
};
return exports();
})();
Object.freeze(window.qBittorrent.ManageCookies);
window.qBittorrent.ManageCookies.setup();
</script>

View file

@ -25,6 +25,7 @@
<file>private/images/application-rss.svg</file> <file>private/images/application-rss.svg</file>
<file>private/images/application-url.svg</file> <file>private/images/application-url.svg</file>
<file>private/images/arrow-right.gif</file> <file>private/images/arrow-right.gif</file>
<file>private/images/browser-cookies.svg</file>
<file>private/images/checked-completed.svg</file> <file>private/images/checked-completed.svg</file>
<file>private/images/collapse.svg</file> <file>private/images/collapse.svg</file>
<file>private/images/configure.svg</file> <file>private/images/configure.svg</file>
@ -424,6 +425,7 @@
<file>private/views/aboutToolbar.html</file> <file>private/views/aboutToolbar.html</file>
<file>private/views/confirmdeletion.html</file> <file>private/views/confirmdeletion.html</file>
<file>private/views/confirmRecheck.html</file> <file>private/views/confirmRecheck.html</file>
<file>private/views/cookies.html</file>
<file>private/views/filters.html</file> <file>private/views/filters.html</file>
<file>private/views/installsearchplugin.html</file> <file>private/views/installsearchplugin.html</file>
<file>private/views/log.html</file> <file>private/views/log.html</file>