diff --git a/cmake/Modules/MacroQbtCommonConfig.cmake b/cmake/Modules/MacroQbtCommonConfig.cmake index 7fc02848995..377df16c75b 100644 --- a/cmake/Modules/MacroQbtCommonConfig.cmake +++ b/cmake/Modules/MacroQbtCommonConfig.cmake @@ -18,6 +18,7 @@ macro(qbt_common_config) target_compile_definitions(qbt_common_cfg INTERFACE QT_DISABLE_DEPRECATED_BEFORE=0x050f02 + QT_NO_CAST_FROM_ASCII QT_NO_CAST_TO_ASCII QT_NO_CAST_FROM_BYTEARRAY QT_USE_QSTRINGBUILDER diff --git a/src/app/application.cpp b/src/app/application.cpp index 8a8d8737db9..84461b5779a 100644 --- a/src/app/application.cpp +++ b/src/app/application.cpp @@ -44,6 +44,7 @@ #endif #include +#include #include #include #include @@ -326,7 +327,7 @@ void Application::runExternalProgram(const BitTorrent::Torrent *torrent) const #if defined(Q_OS_WIN) const auto chopPathSep = [](const QString &str) -> QString { - if (str.endsWith('\\')) + if (str.endsWith(u'\\')) return str.mid(0, (str.length() -1)); return str; }; @@ -677,11 +678,11 @@ int Application::exec(const QStringList ¶ms) + tr("To control qBittorrent, access the WebUI at: %1").arg(url); printf("%s\n", qUtf8Printable(mesg)); - if (pref->getWebUIPassword() == "ARQ77eY1NUZaQsuDHbIMCA==:0WMRkYTUWVT9wVvdDtHAjU9b3b7uB8NR1Gur2hmQCvCDpm39Q+PsJRJPaCU51dEiz+dTzh8qbPsL8WkFljQYFQ==") + if (pref->getWebUIPassword() == QByteArrayLiteral("ARQ77eY1NUZaQsuDHbIMCA==:0WMRkYTUWVT9wVvdDtHAjU9b3b7uB8NR1Gur2hmQCvCDpm39Q+PsJRJPaCU51dEiz+dTzh8qbPsL8WkFljQYFQ==")) { - const QString warning = tr("The Web UI administrator username is: %1").arg(pref->getWebUiUsername()) + '\n' - + tr("The Web UI administrator password has not been changed from the default: %1").arg("adminadmin") + '\n' - + tr("This is a security risk, please change your password in program preferences.") + '\n'; + const QString warning = tr("The Web UI administrator username is: %1").arg(pref->getWebUiUsername()) + u'\n' + + tr("The Web UI administrator password has not been changed from the default: %1").arg(u"adminadmin"_qs) + u'\n' + + tr("This is a security risk, please change your password in program preferences.") + u'\n'; printf("%s", qUtf8Printable(warning)); } #endif // DISABLE_WEBUI diff --git a/src/app/main.cpp b/src/app/main.cpp index 49d265405d5..64a5fdd3851 100644 --- a/src/app/main.cpp +++ b/src/app/main.cpp @@ -179,10 +179,6 @@ int main(int argc, char *argv[]) .arg(QLatin1String("-h (or --help)"))); } - // Set environment variable - if (!qputenv("QBITTORRENT", QBT_VERSION)) - fprintf(stderr, "Couldn't set environment variable...\n"); - const bool firstTimeUser = !Preferences::instance()->getAcceptedLegal(); if (firstTimeUser) { @@ -420,9 +416,9 @@ bool userAgreesWithLegalNotice() #ifdef DISABLE_GUI const QString eula = QString::fromLatin1("\n*** %1 ***\n").arg(QObject::tr("Legal Notice")) - + QObject::tr("qBittorrent is a file sharing program. When you run a torrent, its data will be made available to others by means of upload. Any content you share is your sole responsibility.") + "\n\n" - + QObject::tr("No further notices will be issued.") + "\n\n" - + QObject::tr("Press %1 key to accept and continue...").arg("'y'") + '\n'; + + QObject::tr("qBittorrent is a file sharing program. When you run a torrent, its data will be made available to others by means of upload. Any content you share is your sole responsibility.") + u"\n\n" + + QObject::tr("No further notices will be issued.") + u"\n\n" + + QObject::tr("Press %1 key to accept and continue...").arg(u"'y'"_qs) + u'\n'; printf("%s", qUtf8Printable(eula)); const char ret = getchar(); // Read pressed key diff --git a/src/app/stacktrace_win.h b/src/app/stacktrace_win.h index 7a92d54b15d..c4d9e13a968 100644 --- a/src/app/stacktrace_win.h +++ b/src/app/stacktrace_win.h @@ -31,6 +31,8 @@ #include #endif +#include "base/global.h" + namespace straceWin { void loadHelpStackFrame(IMAGEHLP_STACK_FRAME&, const STACKFRAME64&); @@ -50,7 +52,7 @@ namespace straceWin #ifdef __MINGW32__ void straceWin::demangle(QString& str) { - char const* inStr = qPrintable("_" + str); // Really need that underline or demangling will fail + char const* inStr = qPrintable(u"_" + str); // Really need that underline or demangling will fail int status = 0; size_t outSz = 0; char* demangled_name = abi::__cxa_demangle(inStr, 0, &outSz, &status); @@ -75,7 +77,7 @@ BOOL CALLBACK straceWin::EnumSymbolsCB(PSYMBOL_INFO symInfo, ULONG size, PVOID u Q_UNUSED(size) auto params = static_cast(user); if (symInfo->Flags & SYMFLAG_PARAMETER) - params->append(symInfo->Name); + params->append(QString::fromUtf8(symInfo->Name)); return TRUE; } @@ -97,16 +99,16 @@ BOOL CALLBACK straceWin::EnumModulesCB(LPCSTR ModuleName, DWORD64 BaseOfDll, PVO { QString moduleBase = QString::fromLatin1("0x%1").arg(BaseOfDll, 16, 16, QLatin1Char('0')); QString line = QString::fromLatin1("%1 %2 Image: %3") - .arg(mod.ModuleName, -25) + .arg(QString::fromUtf8(mod.ModuleName), -25) .arg(moduleBase, -13) - .arg(mod.LoadedImageName); + .arg(QString::fromUtf8(mod.LoadedImageName)); context->stream << line << '\n'; - QString pdbName(mod.LoadedPdbName); + const auto pdbName = QString::fromUtf8(mod.LoadedPdbName); if(!pdbName.isEmpty()) { QString line2 = QString::fromLatin1("%1 %2") - .arg("", 35) + .arg(u""_qs, 35) .arg(pdbName); context->stream << line2 << '\n'; } @@ -119,7 +121,7 @@ BOOL CALLBACK straceWin::EnumModulesCB(LPCSTR ModuleName, DWORD64 BaseOfDll, PVO * Cuts off leading 'dir' path from 'file' path, otherwise leaves it unchanged * returns true if 'dir' is an ancestor of 'file', otherwise - false */ -bool straceWin::makeRelativePath(const QString& dir, QString& file) +bool straceWin::makeRelativePath(const QString &dir, QString &file) { QString d = QDir::toNativeSeparators(QDir(dir).absolutePath()); QString f = QDir::toNativeSeparators(QFileInfo(file).absoluteFilePath()); @@ -148,7 +150,7 @@ QString straceWin::getSourcePathAndLineNumber(HANDLE hProcess, DWORD64 addr) if (SymGetLineFromAddr64(hProcess, addr, &dwDisplacement, &line)) { - QString path(line.FileName); + auto path = QString::fromUtf8(line.FileName); #if defined STACKTRACE_WIN_PROJECT_PATH || defined STACKTRACE_WIN_MAKEFILE_PATH @@ -159,14 +161,14 @@ QString straceWin::getSourcePathAndLineNumber(HANDLE hProcess, DWORD64 addr) bool success = false; #ifdef STACKTRACE_WIN_PROJECT_PATH - QString projectPath(STACKTRACE_WIN_STRING(STACKTRACE_WIN_PROJECT_PATH)); + const auto projectPath = QStringLiteral(STACKTRACE_WIN_STRING(STACKTRACE_WIN_PROJECT_PATH)); success = makeRelativePath(projectPath, path); #endif #ifdef STACKTRACE_WIN_MAKEFILE_PATH if (!success) { - QString targetPath(STACKTRACE_WIN_STRING(STACKTRACE_WIN_MAKEFILE_PATH)); + const auto targetPath = QStringLiteral(STACKTRACE_WIN_STRING(STACKTRACE_WIN_MAKEFILE_PATH)); makeRelativePath(targetPath, path); } #endif @@ -285,11 +287,11 @@ const QString straceWin::getBacktrace() if(StackFrame.AddrPC.Offset != 0) { // Valid frame. - QString fileName("???"); + auto fileName = u"???"_qs; if(SymGetModuleInfo64(hProcess, ihsf.InstructionOffset, &mod)) { - fileName = QString(mod.ImageName); - int slashPos = fileName.lastIndexOf('\\'); + fileName = QString::fromUtf8(mod.ImageName); + int slashPos = fileName.lastIndexOf(u'\\'); if(slashPos != -1) fileName = fileName.mid(slashPos + 1); } @@ -297,7 +299,7 @@ const QString straceWin::getBacktrace() QString sourceFile; if(SymFromAddr(hProcess, ihsf.InstructionOffset, &dwDisplacement, pSymbol)) { - funcName = QString(pSymbol->Name); + funcName = QString::fromUtf8(pSymbol->Name); #ifdef __MINGW32__ demangle(funcName); #endif @@ -317,9 +319,9 @@ const QString straceWin::getBacktrace() #endif QString insOffset = QString::fromLatin1("0x%1").arg(ihsf.InstructionOffset, 16, 16, QLatin1Char('0')); - QString formatLine = "#%1 %2 %3 %4"; + auto formatLine = u"#%1 %2 %3 %4"_qs; #ifndef __MINGW32__ - formatLine += "(%5)"; + formatLine += u"(%5)"_qs; #endif QString debugLine = formatLine .arg(i, 3, 10) @@ -327,7 +329,7 @@ const QString straceWin::getBacktrace() .arg(insOffset, -11) .arg(funcName) #ifndef __MINGW32__ - .arg(params.join(", ")); + .arg(params.join(u", ")); if (!sourceFile.isEmpty()) debugLine += QString::fromLatin1("[ %1 ]").arg(sourceFile); diff --git a/src/app/stacktracedialog.cpp b/src/app/stacktracedialog.cpp index 265dfa26340..5072738d417 100644 --- a/src/app/stacktracedialog.cpp +++ b/src/app/stacktracedialog.cpp @@ -50,7 +50,7 @@ StacktraceDialog::~StacktraceDialog() void StacktraceDialog::setStacktraceString(const QString &sigName, const QString &trace) { // try to call Qt function as less as possible - const QString htmlStr = QString( + const QString htmlStr = QStringLiteral( "

" "qBittorrent has crashed" "

" diff --git a/src/base/bittorrent/session.cpp b/src/base/bittorrent/session.cpp index 914ec9273b5..858e5f2a80a 100644 --- a/src/base/bittorrent/session.cpp +++ b/src/base/bittorrent/session.cpp @@ -3170,7 +3170,7 @@ void Session::setOSMemoryPriority(const OSMemoryPriority priority) void Session::applyOSMemoryPriority() const { using SETPROCESSINFORMATION = BOOL (WINAPI *)(HANDLE, PROCESS_INFORMATION_CLASS, LPVOID, DWORD); - const auto setProcessInformation = Utils::Misc::loadWinAPI("Kernel32.dll", "SetProcessInformation"); + const auto setProcessInformation = Utils::Misc::loadWinAPI(u"Kernel32.dll"_qs, "SetProcessInformation"); if (!setProcessInformation) // only available on Windows >= 8 return; diff --git a/src/base/utils/foreignapps.cpp b/src/base/utils/foreignapps.cpp index cbe6f68e653..10e4e924507 100644 --- a/src/base/utils/foreignapps.cpp +++ b/src/base/utils/foreignapps.cpp @@ -186,7 +186,7 @@ namespace bool found = false; while (!found && !versions.empty()) { - const QString version = versions.takeLast() + "\\InstallPath"; + const QString version = versions.takeLast() + u"\\InstallPath"; LPWSTR lpSubkey = new WCHAR[version.size() + 1]; version.toWCharArray(lpSubkey); lpSubkey[version.size()] = 0; @@ -205,15 +205,15 @@ namespace { const QDir baseDir {path}; - if (baseDir.exists("python3.exe")) + if (baseDir.exists(u"python3.exe"_qs)) { found = true; - path = baseDir.filePath("python3.exe"); + path = baseDir.filePath(u"python3.exe"_qs); } - else if (baseDir.exists("python.exe")) + else if (baseDir.exists(u"python.exe"_qs)) { found = true; - path = baseDir.filePath("python.exe"); + path = baseDir.filePath(u"python.exe"_qs); } } } @@ -243,14 +243,14 @@ namespace return path; // Fallback: Detect python from default locations - const QFileInfoList dirs = QDir("C:/").entryInfoList({"Python*"}, QDir::Dirs, (QDir::Name | QDir::Reversed)); + const QFileInfoList dirs = QDir(u"C:/"_qs).entryInfoList({u"Python*"_qs}, QDir::Dirs, (QDir::Name | QDir::Reversed)); for (const QFileInfo &info : dirs) { - const QString py3Path {info.absolutePath() + "/python3.exe"}; + const QString py3Path {info.absolutePath() + u"/python3.exe"}; if (QFile::exists(py3Path)) return py3Path; - const QString pyPath {info.absolutePath() + "/python.exe"}; + const QString pyPath {info.absolutePath() + u"/python.exe"}; if (QFile::exists(pyPath)) return pyPath; } diff --git a/src/base/utils/misc.h b/src/base/utils/misc.h index f2ad163623b..a1513a96509 100644 --- a/src/base/utils/misc.h +++ b/src/base/utils/misc.h @@ -93,8 +93,8 @@ namespace Utils::Misc T loadWinAPI(const QString &source, const char *funcName) { QString path = windowsSystemPath(); - if (!path.endsWith('\\')) - path += '\\'; + if (!path.endsWith(u'\\')) + path += u'\\'; path += source; diff --git a/src/base/utils/random.cpp b/src/base/utils/random.cpp index 77d4a2dec71..b4fc2175644 100644 --- a/src/base/utils/random.cpp +++ b/src/base/utils/random.cpp @@ -43,7 +43,8 @@ #include -#include "misc.h" +#include "base/global.h" +#include "base/utils/misc.h" namespace { @@ -55,7 +56,7 @@ namespace using result_type = uint32_t; RandomLayer() - : m_rtlGenRandom {Utils::Misc::loadWinAPI("Advapi32.dll", "SystemFunction036")} + : m_rtlGenRandom {Utils::Misc::loadWinAPI(u"Advapi32.dll"_qs, "SystemFunction036")} { if (!m_rtlGenRandom) qFatal("Failed to load RtlGenRandom()"); diff --git a/src/gui/mainwindow.cpp b/src/gui/mainwindow.cpp index b90677090f9..db2884e9665 100644 --- a/src/gui/mainwindow.cpp +++ b/src/gui/mainwindow.cpp @@ -1604,7 +1604,7 @@ void MainWindow::reloadSessionStats() } else if (!MacUtils::badgeLabelText().isEmpty()) { - MacUtils::setBadgeLabelText(""); + MacUtils::setBadgeLabelText({}); } #else if (m_systrayIcon) @@ -1905,8 +1905,8 @@ void MainWindow::handleUpdateCheckFinished(ProgramUpdater *updater, const bool i const QString newVersion = updater->getNewVersion(); if (!newVersion.isEmpty()) { - const QString msg {tr("A new version is available.") + "
" - + tr("Do you want to download %1?").arg(newVersion) + "

" + const QString msg {tr("A new version is available.") + u"
" + + tr("Do you want to download %1?").arg(newVersion) + u"

" + QString::fromLatin1("%1").arg(tr("Open changelog..."))}; auto *msgBox = new QMessageBox {QMessageBox::Question, tr("qBittorrent Update Available"), msg , (QMessageBox::Yes | QMessageBox::No), this}; @@ -2082,9 +2082,9 @@ void MainWindow::installPython() setCursor(QCursor(Qt::WaitCursor)); // Download python #ifdef QBT_APP_64BIT - const QString installerURL = "https://www.python.org/ftp/python/3.8.10/python-3.8.10-amd64.exe"; + const auto installerURL = u"https://www.python.org/ftp/python/3.8.10/python-3.8.10-amd64.exe"_qs; #else - const QString installerURL = "https://www.python.org/ftp/python/3.8.10/python-3.8.10.exe"; + const auto installerURL = u"https://www.python.org/ftp/python/3.8.10/python-3.8.10.exe"_qs; #endif Net::DownloadManager::instance()->download( Net::DownloadRequest(installerURL).saveToFile(true) @@ -2109,7 +2109,7 @@ void MainWindow::pythonDownloadFinished(const Net::DownloadResult &result) const Path exePath = result.filePath + ".exe"; Utils::Fs::renameFile(result.filePath, exePath); - installer.start(exePath.toString(), {"/passive"}); + installer.start(exePath.toString(), {u"/passive"_qs}); // Wait for setup to complete installer.waitForFinished(10 * 60 * 1000); diff --git a/src/gui/programupdater.cpp b/src/gui/programupdater.cpp index 317509ed960..535b3c321ac 100644 --- a/src/gui/programupdater.cpp +++ b/src/gui/programupdater.cpp @@ -43,6 +43,7 @@ #include #endif +#include "base/global.h" #include "base/net/downloadmanager.h" #include "base/utils/version.h" #include "base/version.h" @@ -79,7 +80,7 @@ void ProgramUpdater::checkForUpdates() const // Don't change this User-Agent. In case our updater goes haywire, // the filehost can identify it and contact us. Net::DownloadManager::instance()->download( - Net::DownloadRequest(RSS_URL).userAgent("qBittorrent/" QBT_VERSION_2 " ProgramUpdater (www.qbittorrent.org)") + Net::DownloadRequest(RSS_URL).userAgent(QStringLiteral("qBittorrent/" QBT_VERSION_2 " ProgramUpdater (www.qbittorrent.org)")) , this, &ProgramUpdater::rssDownloadFinished); } @@ -108,11 +109,11 @@ void ProgramUpdater::rssDownloadFinished(const Net::DownloadResult &result) }; #ifdef Q_OS_MACOS - const QString OS_TYPE {"Mac OS X"}; + const QString OS_TYPE = u"Mac OS X"_qs; #elif defined(Q_OS_WIN) - const QString OS_TYPE {(::IsWindows7OrGreater() - && QSysInfo::currentCpuArchitecture().endsWith("64")) - ? "Windows x64" : "Windows"}; + const QString OS_TYPE = (::IsWindows7OrGreater() && QSysInfo::currentCpuArchitecture().endsWith(u"64")) + ? u"Windows x64"_qs + : u"Windows"_qs; #endif bool inItem = false; diff --git a/src/gui/progressbarpainter.cpp b/src/gui/progressbarpainter.cpp index 7b0f5623e46..ea0fc1aba1a 100644 --- a/src/gui/progressbarpainter.cpp +++ b/src/gui/progressbarpainter.cpp @@ -37,10 +37,12 @@ #include #endif +#include "base/global.h" + ProgressBarPainter::ProgressBarPainter() { #if (defined(Q_OS_WIN) || defined(Q_OS_MACOS)) - auto *fusionStyle = new QProxyStyle {"fusion"}; + auto *fusionStyle = new QProxyStyle {u"fusion"_qs}; fusionStyle->setParent(&m_dummyProgressBar); m_dummyProgressBar.setStyle(fusionStyle); #endif diff --git a/src/gui/transferlistmodel.cpp b/src/gui/transferlistmodel.cpp index eb74e75eba3..8b051125495 100644 --- a/src/gui/transferlistmodel.cpp +++ b/src/gui/transferlistmodel.cpp @@ -168,7 +168,7 @@ QVariant TransferListModel::headerData(int section, Qt::Orientation orientation, { switch (section) { - case TR_QUEUE_POSITION: return u'#'; + case TR_QUEUE_POSITION: return QChar(u'#'); case TR_NAME: return tr("Name", "i.e: torrent name"); case TR_SIZE: return tr("Size", "i.e: torrent size"); case TR_PROGRESS: return tr("Progress", "% Done"); diff --git a/src/src.pro b/src/src.pro index 2728e6d5f68..48114fe17f4 100644 --- a/src/src.pro +++ b/src/src.pro @@ -57,6 +57,7 @@ include(../version.pri) # Qt defines DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x050f02 +DEFINES += QT_NO_CAST_FROM_ASCII DEFINES += QT_NO_CAST_TO_ASCII DEFINES += QT_NO_CAST_FROM_BYTEARRAY DEFINES += QT_USE_QSTRINGBUILDER diff --git a/src/webui/api/appcontroller.cpp b/src/webui/api/appcontroller.cpp index 258b5bd9322..4a383347b66 100644 --- a/src/webui/api/appcontroller.cpp +++ b/src/webui/api/appcontroller.cpp @@ -68,19 +68,19 @@ void AppController::webapiVersionAction() void AppController::versionAction() { - setResult(QBT_VERSION); + setResult(QStringLiteral(QBT_VERSION)); } void AppController::buildInfoAction() { const QJsonObject versions = { - {"qt", QT_VERSION_STR}, - {"libtorrent", Utils::Misc::libtorrentVersionString()}, - {"boost", Utils::Misc::boostVersionString()}, - {"openssl", Utils::Misc::opensslVersionString()}, - {"zlib", Utils::Misc::zlibVersionString()}, - {"bitness", (QT_POINTER_SIZE * 8)} + {u"qt"_qs, QStringLiteral(QT_VERSION_STR)}, + {u"libtorrent"_qs, Utils::Misc::libtorrentVersionString()}, + {u"boost"_qs, Utils::Misc::boostVersionString()}, + {u"openssl"_qs, Utils::Misc::opensslVersionString()}, + {u"zlib"_qs, Utils::Misc::zlibVersionString()}, + {u"bitness"_qs, (QT_POINTER_SIZE * 8)} }; setResult(versions); } @@ -104,22 +104,22 @@ void AppController::preferencesAction() // Downloads // When adding a torrent - data["torrent_content_layout"] = Utils::String::fromEnum(session->torrentContentLayout()); - data["start_paused_enabled"] = session->isAddTorrentPaused(); - data["auto_delete_mode"] = static_cast(TorrentFileGuard::autoDeleteMode()); - data["preallocate_all"] = session->isPreallocationEnabled(); - data["incomplete_files_ext"] = session->isAppendExtensionEnabled(); + data[u"torrent_content_layout"_qs] = Utils::String::fromEnum(session->torrentContentLayout()); + data[u"start_paused_enabled"_qs] = session->isAddTorrentPaused(); + data[u"auto_delete_mode"_qs] = static_cast(TorrentFileGuard::autoDeleteMode()); + data[u"preallocate_all"_qs] = session->isPreallocationEnabled(); + data[u"incomplete_files_ext"_qs] = session->isAppendExtensionEnabled(); // Saving Management - data["auto_tmm_enabled"] = !session->isAutoTMMDisabledByDefault(); - data["torrent_changed_tmm_enabled"] = !session->isDisableAutoTMMWhenCategoryChanged(); - data["save_path_changed_tmm_enabled"] = !session->isDisableAutoTMMWhenDefaultSavePathChanged(); - data["category_changed_tmm_enabled"] = !session->isDisableAutoTMMWhenCategorySavePathChanged(); - data["save_path"] = session->savePath().toString(); - data["temp_path_enabled"] = session->isDownloadPathEnabled(); - data["temp_path"] = session->downloadPath().toString(); - data["use_category_paths_in_manual_mode"] = session->useCategoryPathsInManualMode(); - data["export_dir"] = session->torrentExportDirectory().toString(); - data["export_dir_fin"] = session->finishedTorrentExportDirectory().toString(); + data[u"auto_tmm_enabled"_qs] = !session->isAutoTMMDisabledByDefault(); + data[u"torrent_changed_tmm_enabled"_qs] = !session->isDisableAutoTMMWhenCategoryChanged(); + data[u"save_path_changed_tmm_enabled"_qs] = !session->isDisableAutoTMMWhenDefaultSavePathChanged(); + data[u"category_changed_tmm_enabled"_qs] = !session->isDisableAutoTMMWhenCategorySavePathChanged(); + data[u"save_path"_qs] = session->savePath().toString(); + data[u"temp_path_enabled"_qs] = session->isDownloadPathEnabled(); + data[u"temp_path"_qs] = session->downloadPath().toString(); + data[u"use_category_paths_in_manual_mode"_qs] = session->useCategoryPathsInManualMode(); + data[u"export_dir"_qs] = session->torrentExportDirectory().toString(); + data[u"export_dir_fin"_qs] = session->finishedTorrentExportDirectory().toString(); // TODO: The following code is deprecated. Delete it once replaced by updated API method. // === BEGIN DEPRECATED CODE === // @@ -137,293 +137,293 @@ void AppController::preferencesAction() else nativeDirs.insert(watchedFolder.toString(), params.savePath.toString()); } - data["scan_dirs"] = nativeDirs; + data[u"scan_dirs"_qs] = nativeDirs; // === END DEPRECATED CODE === // // Email notification upon download completion - data["mail_notification_enabled"] = pref->isMailNotificationEnabled(); - data["mail_notification_sender"] = pref->getMailNotificationSender(); - data["mail_notification_email"] = pref->getMailNotificationEmail(); - data["mail_notification_smtp"] = pref->getMailNotificationSMTP(); - data["mail_notification_ssl_enabled"] = pref->getMailNotificationSMTPSSL(); - data["mail_notification_auth_enabled"] = pref->getMailNotificationSMTPAuth(); - data["mail_notification_username"] = pref->getMailNotificationSMTPUsername(); - data["mail_notification_password"] = pref->getMailNotificationSMTPPassword(); + data[u"mail_notification_enabled"_qs] = pref->isMailNotificationEnabled(); + data[u"mail_notification_sender"_qs] = pref->getMailNotificationSender(); + data[u"mail_notification_email"_qs] = pref->getMailNotificationEmail(); + data[u"mail_notification_smtp"_qs] = pref->getMailNotificationSMTP(); + data[u"mail_notification_ssl_enabled"_qs] = pref->getMailNotificationSMTPSSL(); + data[u"mail_notification_auth_enabled"_qs] = pref->getMailNotificationSMTPAuth(); + data[u"mail_notification_username"_qs] = pref->getMailNotificationSMTPUsername(); + data[u"mail_notification_password"_qs] = pref->getMailNotificationSMTPPassword(); // Run an external program on torrent completion - data["autorun_enabled"] = pref->isAutoRunEnabled(); - data["autorun_program"] = pref->getAutoRunProgram(); + data[u"autorun_enabled"_qs] = pref->isAutoRunEnabled(); + data[u"autorun_program"_qs] = pref->getAutoRunProgram(); // Connection // Listening Port - data["listen_port"] = session->port(); - data["random_port"] = (session->port() == 0); // deprecated - data["upnp"] = Net::PortForwarder::instance()->isEnabled(); + data[u"listen_port"_qs] = session->port(); + data[u"random_port"_qs] = (session->port() == 0); // deprecated + data[u"upnp"_qs] = Net::PortForwarder::instance()->isEnabled(); // Connections Limits - data["max_connec"] = session->maxConnections(); - data["max_connec_per_torrent"] = session->maxConnectionsPerTorrent(); - data["max_uploads"] = session->maxUploads(); - data["max_uploads_per_torrent"] = session->maxUploadsPerTorrent(); + data[u"max_connec"_qs] = session->maxConnections(); + data[u"max_connec_per_torrent"_qs] = session->maxConnectionsPerTorrent(); + data[u"max_uploads"_qs] = session->maxUploads(); + data[u"max_uploads_per_torrent"_qs] = session->maxUploadsPerTorrent(); // Proxy Server const auto *proxyManager = Net::ProxyConfigurationManager::instance(); Net::ProxyConfiguration proxyConf = proxyManager->proxyConfiguration(); - data["proxy_type"] = static_cast(proxyConf.type); - data["proxy_ip"] = proxyConf.ip; - data["proxy_port"] = proxyConf.port; - data["proxy_auth_enabled"] = proxyManager->isAuthenticationRequired(); // deprecated - data["proxy_username"] = proxyConf.username; - data["proxy_password"] = proxyConf.password; + data[u"proxy_type"_qs] = static_cast(proxyConf.type); + data[u"proxy_ip"_qs] = proxyConf.ip; + data[u"proxy_port"_qs] = proxyConf.port; + data[u"proxy_auth_enabled"_qs] = proxyManager->isAuthenticationRequired(); // deprecated + data[u"proxy_username"_qs] = proxyConf.username; + data[u"proxy_password"_qs] = proxyConf.password; - data["proxy_peer_connections"] = session->isProxyPeerConnectionsEnabled(); - data["proxy_torrents_only"] = proxyManager->isProxyOnlyForTorrents(); + data[u"proxy_peer_connections"_qs] = session->isProxyPeerConnectionsEnabled(); + data[u"proxy_torrents_only"_qs] = proxyManager->isProxyOnlyForTorrents(); // IP Filtering - data["ip_filter_enabled"] = session->isIPFilteringEnabled(); - data["ip_filter_path"] = session->IPFilterFile().toString(); - data["ip_filter_trackers"] = session->isTrackerFilteringEnabled(); - data["banned_IPs"] = session->bannedIPs().join('\n'); + data[u"ip_filter_enabled"_qs] = session->isIPFilteringEnabled(); + data[u"ip_filter_path"_qs] = session->IPFilterFile().toString(); + data[u"ip_filter_trackers"_qs] = session->isTrackerFilteringEnabled(); + data[u"banned_IPs"_qs] = session->bannedIPs().join(u'\n'); // Speed // Global Rate Limits - data["dl_limit"] = session->globalDownloadSpeedLimit(); - data["up_limit"] = session->globalUploadSpeedLimit(); - data["alt_dl_limit"] = session->altGlobalDownloadSpeedLimit(); - data["alt_up_limit"] = session->altGlobalUploadSpeedLimit(); - data["bittorrent_protocol"] = static_cast(session->btProtocol()); - data["limit_utp_rate"] = session->isUTPRateLimited(); - data["limit_tcp_overhead"] = session->includeOverheadInLimits(); - data["limit_lan_peers"] = !session->ignoreLimitsOnLAN(); + data[u"dl_limit"_qs] = session->globalDownloadSpeedLimit(); + data[u"up_limit"_qs] = session->globalUploadSpeedLimit(); + data[u"alt_dl_limit"_qs] = session->altGlobalDownloadSpeedLimit(); + data[u"alt_up_limit"_qs] = session->altGlobalUploadSpeedLimit(); + data[u"bittorrent_protocol"_qs] = static_cast(session->btProtocol()); + data[u"limit_utp_rate"_qs] = session->isUTPRateLimited(); + data[u"limit_tcp_overhead"_qs] = session->includeOverheadInLimits(); + data[u"limit_lan_peers"_qs] = !session->ignoreLimitsOnLAN(); // Scheduling - data["scheduler_enabled"] = session->isBandwidthSchedulerEnabled(); + data[u"scheduler_enabled"_qs] = session->isBandwidthSchedulerEnabled(); const QTime start_time = pref->getSchedulerStartTime(); - data["schedule_from_hour"] = start_time.hour(); - data["schedule_from_min"] = start_time.minute(); + data[u"schedule_from_hour"_qs] = start_time.hour(); + data[u"schedule_from_min"_qs] = start_time.minute(); const QTime end_time = pref->getSchedulerEndTime(); - data["schedule_to_hour"] = end_time.hour(); - data["schedule_to_min"] = end_time.minute(); - data["scheduler_days"] = static_cast(pref->getSchedulerDays()); + data[u"schedule_to_hour"_qs] = end_time.hour(); + data[u"schedule_to_min"_qs] = end_time.minute(); + data[u"scheduler_days"_qs] = static_cast(pref->getSchedulerDays()); // Bittorrent // Privacy - data["dht"] = session->isDHTEnabled(); - data["pex"] = session->isPeXEnabled(); - data["lsd"] = session->isLSDEnabled(); - data["encryption"] = session->encryption(); - data["anonymous_mode"] = session->isAnonymousModeEnabled(); + data[u"dht"_qs] = session->isDHTEnabled(); + data[u"pex"_qs] = session->isPeXEnabled(); + data[u"lsd"_qs] = session->isLSDEnabled(); + data[u"encryption"_qs] = session->encryption(); + data[u"anonymous_mode"_qs] = session->isAnonymousModeEnabled(); // Max active checking torrents - data["max_active_checking_torrents"] = session->maxActiveCheckingTorrents(); + data[u"max_active_checking_torrents"_qs] = session->maxActiveCheckingTorrents(); // Torrent Queueing - data["queueing_enabled"] = session->isQueueingSystemEnabled(); - data["max_active_downloads"] = session->maxActiveDownloads(); - data["max_active_torrents"] = session->maxActiveTorrents(); - data["max_active_uploads"] = session->maxActiveUploads(); - data["dont_count_slow_torrents"] = session->ignoreSlowTorrentsForQueueing(); - data["slow_torrent_dl_rate_threshold"] = session->downloadRateForSlowTorrents(); - data["slow_torrent_ul_rate_threshold"] = session->uploadRateForSlowTorrents(); - data["slow_torrent_inactive_timer"] = session->slowTorrentsInactivityTimer(); + data[u"queueing_enabled"_qs] = session->isQueueingSystemEnabled(); + data[u"max_active_downloads"_qs] = session->maxActiveDownloads(); + data[u"max_active_torrents"_qs] = session->maxActiveTorrents(); + data[u"max_active_uploads"_qs] = session->maxActiveUploads(); + data[u"dont_count_slow_torrents"_qs] = session->ignoreSlowTorrentsForQueueing(); + data[u"slow_torrent_dl_rate_threshold"_qs] = session->downloadRateForSlowTorrents(); + data[u"slow_torrent_ul_rate_threshold"_qs] = session->uploadRateForSlowTorrents(); + data[u"slow_torrent_inactive_timer"_qs] = session->slowTorrentsInactivityTimer(); // Share Ratio Limiting - data["max_ratio_enabled"] = (session->globalMaxRatio() >= 0.); - data["max_ratio"] = session->globalMaxRatio(); - data["max_seeding_time_enabled"] = (session->globalMaxSeedingMinutes() >= 0.); - data["max_seeding_time"] = session->globalMaxSeedingMinutes(); - data["max_ratio_act"] = session->maxRatioAction(); + data[u"max_ratio_enabled"_qs] = (session->globalMaxRatio() >= 0.); + data[u"max_ratio"_qs] = session->globalMaxRatio(); + data[u"max_seeding_time_enabled"_qs] = (session->globalMaxSeedingMinutes() >= 0.); + data[u"max_seeding_time"_qs] = session->globalMaxSeedingMinutes(); + data[u"max_ratio_act"_qs] = session->maxRatioAction(); // Add trackers - data["add_trackers_enabled"] = session->isAddTrackersEnabled(); - data["add_trackers"] = session->additionalTrackers(); + data[u"add_trackers_enabled"_qs] = session->isAddTrackersEnabled(); + data[u"add_trackers"_qs] = session->additionalTrackers(); // Web UI // Language - data["locale"] = pref->getLocale(); - data["performance_warning"] = session->isPerformanceWarningEnabled(); + data[u"locale"_qs] = pref->getLocale(); + data[u"performance_warning"_qs] = session->isPerformanceWarningEnabled(); // HTTP Server - data["web_ui_domain_list"] = pref->getServerDomains(); - data["web_ui_address"] = pref->getWebUiAddress(); - data["web_ui_port"] = pref->getWebUiPort(); - data["web_ui_upnp"] = pref->useUPnPForWebUIPort(); - data["use_https"] = pref->isWebUiHttpsEnabled(); - data["web_ui_https_cert_path"] = pref->getWebUIHttpsCertificatePath().toString(); - data["web_ui_https_key_path"] = pref->getWebUIHttpsKeyPath().toString(); + data[u"web_ui_domain_list"_qs] = pref->getServerDomains(); + data[u"web_ui_address"_qs] = pref->getWebUiAddress(); + data[u"web_ui_port"_qs] = pref->getWebUiPort(); + data[u"web_ui_upnp"_qs] = pref->useUPnPForWebUIPort(); + data[u"use_https"_qs] = pref->isWebUiHttpsEnabled(); + data[u"web_ui_https_cert_path"_qs] = pref->getWebUIHttpsCertificatePath().toString(); + data[u"web_ui_https_key_path"_qs] = pref->getWebUIHttpsKeyPath().toString(); // Authentication - data["web_ui_username"] = pref->getWebUiUsername(); - data["bypass_local_auth"] = !pref->isWebUiLocalAuthEnabled(); - data["bypass_auth_subnet_whitelist_enabled"] = pref->isWebUiAuthSubnetWhitelistEnabled(); + data[u"web_ui_username"_qs] = pref->getWebUiUsername(); + data[u"bypass_local_auth"_qs] = !pref->isWebUiLocalAuthEnabled(); + data[u"bypass_auth_subnet_whitelist_enabled"_qs] = pref->isWebUiAuthSubnetWhitelistEnabled(); QStringList authSubnetWhitelistStringList; for (const Utils::Net::Subnet &subnet : asConst(pref->getWebUiAuthSubnetWhitelist())) authSubnetWhitelistStringList << Utils::Net::subnetToString(subnet); - data["bypass_auth_subnet_whitelist"] = authSubnetWhitelistStringList.join('\n'); - data["web_ui_max_auth_fail_count"] = pref->getWebUIMaxAuthFailCount(); - data["web_ui_ban_duration"] = static_cast(pref->getWebUIBanDuration().count()); - data["web_ui_session_timeout"] = pref->getWebUISessionTimeout(); + data[u"bypass_auth_subnet_whitelist"_qs] = authSubnetWhitelistStringList.join(u'\n'); + data[u"web_ui_max_auth_fail_count"_qs] = pref->getWebUIMaxAuthFailCount(); + data[u"web_ui_ban_duration"_qs] = static_cast(pref->getWebUIBanDuration().count()); + data[u"web_ui_session_timeout"_qs] = pref->getWebUISessionTimeout(); // Use alternative Web UI - data["alternative_webui_enabled"] = pref->isAltWebUiEnabled(); - data["alternative_webui_path"] = pref->getWebUiRootFolder().toString(); + data[u"alternative_webui_enabled"_qs] = pref->isAltWebUiEnabled(); + data[u"alternative_webui_path"_qs] = pref->getWebUiRootFolder().toString(); // Security - data["web_ui_clickjacking_protection_enabled"] = pref->isWebUiClickjackingProtectionEnabled(); - data["web_ui_csrf_protection_enabled"] = pref->isWebUiCSRFProtectionEnabled(); - data["web_ui_secure_cookie_enabled"] = pref->isWebUiSecureCookieEnabled(); - data["web_ui_host_header_validation_enabled"] = pref->isWebUIHostHeaderValidationEnabled(); + data[u"web_ui_clickjacking_protection_enabled"_qs] = pref->isWebUiClickjackingProtectionEnabled(); + data[u"web_ui_csrf_protection_enabled"_qs] = pref->isWebUiCSRFProtectionEnabled(); + data[u"web_ui_secure_cookie_enabled"_qs] = pref->isWebUiSecureCookieEnabled(); + data[u"web_ui_host_header_validation_enabled"_qs] = pref->isWebUIHostHeaderValidationEnabled(); // Custom HTTP headers - data["web_ui_use_custom_http_headers_enabled"] = pref->isWebUICustomHTTPHeadersEnabled(); - data["web_ui_custom_http_headers"] = pref->getWebUICustomHTTPHeaders(); + data[u"web_ui_use_custom_http_headers_enabled"_qs] = pref->isWebUICustomHTTPHeadersEnabled(); + data[u"web_ui_custom_http_headers"_qs] = pref->getWebUICustomHTTPHeaders(); // Reverse proxy - data["web_ui_reverse_proxy_enabled"] = pref->isWebUIReverseProxySupportEnabled(); - data["web_ui_reverse_proxies_list"] = pref->getWebUITrustedReverseProxiesList(); + data[u"web_ui_reverse_proxy_enabled"_qs] = pref->isWebUIReverseProxySupportEnabled(); + data[u"web_ui_reverse_proxies_list"_qs] = pref->getWebUITrustedReverseProxiesList(); // Update my dynamic domain name - data["dyndns_enabled"] = pref->isDynDNSEnabled(); - data["dyndns_service"] = static_cast(pref->getDynDNSService()); - data["dyndns_username"] = pref->getDynDNSUsername(); - data["dyndns_password"] = pref->getDynDNSPassword(); - data["dyndns_domain"] = pref->getDynDomainName(); + data[u"dyndns_enabled"_qs] = pref->isDynDNSEnabled(); + data[u"dyndns_service"_qs] = static_cast(pref->getDynDNSService()); + data[u"dyndns_username"_qs] = pref->getDynDNSUsername(); + data[u"dyndns_password"_qs] = pref->getDynDNSPassword(); + data[u"dyndns_domain"_qs] = pref->getDynDomainName(); // RSS settings - data["rss_refresh_interval"] = RSS::Session::instance()->refreshInterval(); - data["rss_max_articles_per_feed"] = RSS::Session::instance()->maxArticlesPerFeed(); - data["rss_processing_enabled"] = RSS::Session::instance()->isProcessingEnabled(); - data["rss_auto_downloading_enabled"] = RSS::AutoDownloader::instance()->isProcessingEnabled(); - data["rss_download_repack_proper_episodes"] = RSS::AutoDownloader::instance()->downloadRepacks(); - data["rss_smart_episode_filters"] = RSS::AutoDownloader::instance()->smartEpisodeFilters().join('\n'); + data[u"rss_refresh_interval"_qs] = RSS::Session::instance()->refreshInterval(); + data[u"rss_max_articles_per_feed"_qs] = RSS::Session::instance()->maxArticlesPerFeed(); + data[u"rss_processing_enabled"_qs] = RSS::Session::instance()->isProcessingEnabled(); + data[u"rss_auto_downloading_enabled"_qs] = RSS::AutoDownloader::instance()->isProcessingEnabled(); + data[u"rss_download_repack_proper_episodes"_qs] = RSS::AutoDownloader::instance()->downloadRepacks(); + data[u"rss_smart_episode_filters"_qs] = RSS::AutoDownloader::instance()->smartEpisodeFilters().join(u'\n'); // Advanced settings // qBitorrent preferences // Current network interface - data["current_network_interface"] = session->networkInterface(); + data[u"current_network_interface"_qs] = session->networkInterface(); // Current network interface address - data["current_interface_address"] = BitTorrent::Session::instance()->networkInterfaceAddress(); + data[u"current_interface_address"_qs] = BitTorrent::Session::instance()->networkInterfaceAddress(); // Save resume data interval - data["save_resume_data_interval"] = session->saveResumeDataInterval(); + data[u"save_resume_data_interval"_qs] = session->saveResumeDataInterval(); // Recheck completed torrents - data["recheck_completed_torrents"] = pref->recheckTorrentsOnCompletion(); + data[u"recheck_completed_torrents"_qs] = pref->recheckTorrentsOnCompletion(); // Resolve peer countries - data["resolve_peer_countries"] = pref->resolvePeerCountries(); + data[u"resolve_peer_countries"_qs] = pref->resolvePeerCountries(); // Reannounce to all trackers when ip/port changed - data["reannounce_when_address_changed"] = session->isReannounceWhenAddressChangedEnabled(); + data[u"reannounce_when_address_changed"_qs] = session->isReannounceWhenAddressChangedEnabled(); // libtorrent preferences // Async IO threads - data["async_io_threads"] = session->asyncIOThreads(); + data[u"async_io_threads"_qs] = session->asyncIOThreads(); // Hashing threads - data["hashing_threads"] = session->hashingThreads(); + data[u"hashing_threads"_qs] = session->hashingThreads(); // File pool size - data["file_pool_size"] = session->filePoolSize(); + data[u"file_pool_size"_qs] = session->filePoolSize(); // Checking memory usage - data["checking_memory_use"] = session->checkingMemUsage(); + data[u"checking_memory_use"_qs] = session->checkingMemUsage(); // Disk write cache - data["disk_cache"] = session->diskCacheSize(); - data["disk_cache_ttl"] = session->diskCacheTTL(); + data[u"disk_cache"_qs] = session->diskCacheSize(); + data[u"disk_cache_ttl"_qs] = session->diskCacheTTL(); // Disk queue size - data["disk_queue_size"] = session->diskQueueSize(); + data[u"disk_queue_size"_qs] = session->diskQueueSize(); // Enable OS cache - data["enable_os_cache"] = session->useOSCache(); + data[u"enable_os_cache"_qs] = session->useOSCache(); // Coalesce reads & writes - data["enable_coalesce_read_write"] = session->isCoalesceReadWriteEnabled(); + data[u"enable_coalesce_read_write"_qs] = session->isCoalesceReadWriteEnabled(); // Piece Extent Affinity - data["enable_piece_extent_affinity"] = session->usePieceExtentAffinity(); + data[u"enable_piece_extent_affinity"_qs] = session->usePieceExtentAffinity(); // Suggest mode - data["enable_upload_suggestions"] = session->isSuggestModeEnabled(); + data[u"enable_upload_suggestions"_qs] = session->isSuggestModeEnabled(); // Send buffer watermark - data["send_buffer_watermark"] = session->sendBufferWatermark(); - data["send_buffer_low_watermark"] = session->sendBufferLowWatermark(); - data["send_buffer_watermark_factor"] = session->sendBufferWatermarkFactor(); + data[u"send_buffer_watermark"_qs] = session->sendBufferWatermark(); + data[u"send_buffer_low_watermark"_qs] = session->sendBufferLowWatermark(); + data[u"send_buffer_watermark_factor"_qs] = session->sendBufferWatermarkFactor(); // Outgoing connections per second - data["connection_speed"] = session->connectionSpeed(); + data[u"connection_speed"_qs] = session->connectionSpeed(); // Socket listen backlog size - data["socket_backlog_size"] = session->socketBacklogSize(); + data[u"socket_backlog_size"_qs] = session->socketBacklogSize(); // Outgoing ports - data["outgoing_ports_min"] = session->outgoingPortsMin(); - data["outgoing_ports_max"] = session->outgoingPortsMax(); + data[u"outgoing_ports_min"_qs] = session->outgoingPortsMin(); + data[u"outgoing_ports_max"_qs] = session->outgoingPortsMax(); // UPnP lease duration - data["upnp_lease_duration"] = session->UPnPLeaseDuration(); + data[u"upnp_lease_duration"_qs] = session->UPnPLeaseDuration(); // Type of service - data["peer_tos"] = session->peerToS(); + data[u"peer_tos"_qs] = session->peerToS(); // uTP-TCP mixed mode - data["utp_tcp_mixed_mode"] = static_cast(session->utpMixedMode()); + data[u"utp_tcp_mixed_mode"_qs] = static_cast(session->utpMixedMode()); // Support internationalized domain name (IDN) - data["idn_support_enabled"] = session->isIDNSupportEnabled(); + data[u"idn_support_enabled"_qs] = session->isIDNSupportEnabled(); // Multiple connections per IP - data["enable_multi_connections_from_same_ip"] = session->multiConnectionsPerIpEnabled(); + data[u"enable_multi_connections_from_same_ip"_qs] = session->multiConnectionsPerIpEnabled(); // Validate HTTPS tracker certificate - data["validate_https_tracker_certificate"] = session->validateHTTPSTrackerCertificate(); + data[u"validate_https_tracker_certificate"_qs] = session->validateHTTPSTrackerCertificate(); // SSRF mitigation - data["ssrf_mitigation"] = session->isSSRFMitigationEnabled(); + data[u"ssrf_mitigation"_qs] = session->isSSRFMitigationEnabled(); // Disallow connection to peers on privileged ports - data["block_peers_on_privileged_ports"] = session->blockPeersOnPrivilegedPorts(); + data[u"block_peers_on_privileged_ports"_qs] = session->blockPeersOnPrivilegedPorts(); // Embedded tracker - data["enable_embedded_tracker"] = session->isTrackerEnabled(); - data["embedded_tracker_port"] = pref->getTrackerPort(); + data[u"enable_embedded_tracker"_qs] = session->isTrackerEnabled(); + data[u"embedded_tracker_port"_qs] = pref->getTrackerPort(); // Choking algorithm - data["upload_slots_behavior"] = static_cast(session->chokingAlgorithm()); + data[u"upload_slots_behavior"_qs] = static_cast(session->chokingAlgorithm()); // Seed choking algorithm - data["upload_choking_algorithm"] = static_cast(session->seedChokingAlgorithm()); + data[u"upload_choking_algorithm"_qs] = static_cast(session->seedChokingAlgorithm()); // Announce - data["announce_to_all_trackers"] = session->announceToAllTrackers(); - data["announce_to_all_tiers"] = session->announceToAllTiers(); - data["announce_ip"] = session->announceIP(); - data["max_concurrent_http_announces"] = session->maxConcurrentHTTPAnnounces(); - data["stop_tracker_timeout"] = session->stopTrackerTimeout(); + data[u"announce_to_all_trackers"_qs] = session->announceToAllTrackers(); + data[u"announce_to_all_tiers"_qs] = session->announceToAllTiers(); + data[u"announce_ip"_qs] = session->announceIP(); + data[u"max_concurrent_http_announces"_qs] = session->maxConcurrentHTTPAnnounces(); + data[u"stop_tracker_timeout"_qs] = session->stopTrackerTimeout(); // Peer Turnover - data["peer_turnover"] = session->peerTurnover(); - data["peer_turnover_cutoff"] = session->peerTurnoverCutoff(); - data["peer_turnover_interval"] = session->peerTurnoverInterval(); + data[u"peer_turnover"_qs] = session->peerTurnover(); + data[u"peer_turnover_cutoff"_qs] = session->peerTurnoverCutoff(); + data[u"peer_turnover_interval"_qs] = session->peerTurnoverInterval(); // Maximum outstanding requests to a single peer - data["request_queue_size"] = session->requestQueueSize(); + data[u"request_queue_size"_qs] = session->requestQueueSize(); setResult(data); } void AppController::setPreferencesAction() { - requireParams({"json"}); + requireParams({u"json"_qs}); auto *pref = Preferences::instance(); auto *session = BitTorrent::Session::instance(); - const QVariantHash m = QJsonDocument::fromJson(params()["json"].toUtf8()).toVariant().toHash(); + const QVariantHash m = QJsonDocument::fromJson(params()[u"json"_qs].toUtf8()).toVariant().toHash(); QVariantHash::ConstIterator it; - const auto hasKey = [&it, &m](const char *key) -> bool + const auto hasKey = [&it, &m](const QString &key) -> bool { - it = m.find(QLatin1String(key)); + it = m.find(key); return (it != m.constEnd()); }; // Downloads // When adding a torrent - if (hasKey("torrent_content_layout")) + if (hasKey(u"torrent_content_layout"_qs)) session->setTorrentContentLayout(Utils::String::toEnum(it.value().toString(), BitTorrent::TorrentContentLayout::Original)); - if (hasKey("start_paused_enabled")) + if (hasKey(u"start_paused_enabled"_qs)) session->setAddTorrentPaused(it.value().toBool()); - if (hasKey("auto_delete_mode")) + if (hasKey(u"auto_delete_mode"_qs)) TorrentFileGuard::setAutoDeleteMode(static_cast(it.value().toInt())); - if (hasKey("preallocate_all")) + if (hasKey(u"preallocate_all"_qs)) session->setPreallocationEnabled(it.value().toBool()); - if (hasKey("incomplete_files_ext")) + if (hasKey(u"incomplete_files_ext"_qs)) session->setAppendExtensionEnabled(it.value().toBool()); // Saving Management - if (hasKey("auto_tmm_enabled")) + if (hasKey(u"auto_tmm_enabled"_qs)) session->setAutoTMMDisabledByDefault(!it.value().toBool()); - if (hasKey("torrent_changed_tmm_enabled")) + if (hasKey(u"torrent_changed_tmm_enabled"_qs)) session->setDisableAutoTMMWhenCategoryChanged(!it.value().toBool()); - if (hasKey("save_path_changed_tmm_enabled")) + if (hasKey(u"save_path_changed_tmm_enabled"_qs)) session->setDisableAutoTMMWhenDefaultSavePathChanged(!it.value().toBool()); - if (hasKey("category_changed_tmm_enabled")) + if (hasKey(u"category_changed_tmm_enabled"_qs)) session->setDisableAutoTMMWhenCategorySavePathChanged(!it.value().toBool()); - if (hasKey("save_path")) + if (hasKey(u"save_path"_qs)) session->setSavePath(Path(it.value().toString())); - if (hasKey("temp_path_enabled")) + if (hasKey(u"temp_path_enabled"_qs)) session->setDownloadPathEnabled(it.value().toBool()); - if (hasKey("temp_path")) + if (hasKey(u"temp_path"_qs)) session->setDownloadPath(Path(it.value().toString())); - if (hasKey("use_category_paths_in_manual_mode")) + if (hasKey(u"use_category_paths_in_manual_mode"_qs)) session->setUseCategoryPathsInManualMode(it.value().toBool()); - if (hasKey("export_dir")) + if (hasKey(u"export_dir"_qs)) session->setTorrentExportDirectory(Path(it.value().toString())); - if (hasKey("export_dir_fin")) + if (hasKey(u"export_dir_fin"_qs)) session->setFinishedTorrentExportDirectory(Path(it.value().toString())); // TODO: The following code is deprecated. Delete it once replaced by updated API method. // === BEGIN DEPRECATED CODE === // - if (hasKey("scan_dirs")) + if (hasKey(u"scan_dirs"_qs)) { PathList scanDirs; TorrentFilesWatcher *fsWatcher = TorrentFilesWatcher::instance(); @@ -472,166 +472,166 @@ void AppController::setPreferencesAction() // === END DEPRECATED CODE === // // Email notification upon download completion - if (hasKey("mail_notification_enabled")) + if (hasKey(u"mail_notification_enabled"_qs)) pref->setMailNotificationEnabled(it.value().toBool()); - if (hasKey("mail_notification_sender")) + if (hasKey(u"mail_notification_sender"_qs)) pref->setMailNotificationSender(it.value().toString()); - if (hasKey("mail_notification_email")) + if (hasKey(u"mail_notification_email"_qs)) pref->setMailNotificationEmail(it.value().toString()); - if (hasKey("mail_notification_smtp")) + if (hasKey(u"mail_notification_smtp"_qs)) pref->setMailNotificationSMTP(it.value().toString()); - if (hasKey("mail_notification_ssl_enabled")) + if (hasKey(u"mail_notification_ssl_enabled"_qs)) pref->setMailNotificationSMTPSSL(it.value().toBool()); - if (hasKey("mail_notification_auth_enabled")) + if (hasKey(u"mail_notification_auth_enabled"_qs)) pref->setMailNotificationSMTPAuth(it.value().toBool()); - if (hasKey("mail_notification_username")) + if (hasKey(u"mail_notification_username"_qs)) pref->setMailNotificationSMTPUsername(it.value().toString()); - if (hasKey("mail_notification_password")) + if (hasKey(u"mail_notification_password"_qs)) pref->setMailNotificationSMTPPassword(it.value().toString()); // Run an external program on torrent completion - if (hasKey("autorun_enabled")) + if (hasKey(u"autorun_enabled"_qs)) pref->setAutoRunEnabled(it.value().toBool()); - if (hasKey("autorun_program")) + if (hasKey(u"autorun_program"_qs)) pref->setAutoRunProgram(it.value().toString()); // Connection // Listening Port - if (hasKey("random_port") && it.value().toBool()) // deprecated + if (hasKey(u"random_port"_qs) && it.value().toBool()) // deprecated { session->setPort(0); } - else if (hasKey("listen_port")) + else if (hasKey(u"listen_port"_qs)) { session->setPort(it.value().toInt()); } - if (hasKey("upnp")) + if (hasKey(u"upnp"_qs)) Net::PortForwarder::instance()->setEnabled(it.value().toBool()); // Connections Limits - if (hasKey("max_connec")) + if (hasKey(u"max_connec"_qs)) session->setMaxConnections(it.value().toInt()); - if (hasKey("max_connec_per_torrent")) + if (hasKey(u"max_connec_per_torrent"_qs)) session->setMaxConnectionsPerTorrent(it.value().toInt()); - if (hasKey("max_uploads")) + if (hasKey(u"max_uploads"_qs)) session->setMaxUploads(it.value().toInt()); - if (hasKey("max_uploads_per_torrent")) + if (hasKey(u"max_uploads_per_torrent"_qs)) session->setMaxUploadsPerTorrent(it.value().toInt()); // Proxy Server auto proxyManager = Net::ProxyConfigurationManager::instance(); Net::ProxyConfiguration proxyConf = proxyManager->proxyConfiguration(); - if (hasKey("proxy_type")) + if (hasKey(u"proxy_type"_qs)) proxyConf.type = static_cast(it.value().toInt()); - if (hasKey("proxy_ip")) + if (hasKey(u"proxy_ip"_qs)) proxyConf.ip = it.value().toString(); - if (hasKey("proxy_port")) + if (hasKey(u"proxy_port"_qs)) proxyConf.port = it.value().toUInt(); - if (hasKey("proxy_username")) + if (hasKey(u"proxy_username"_qs)) proxyConf.username = it.value().toString(); - if (hasKey("proxy_password")) + if (hasKey(u"proxy_password"_qs)) proxyConf.password = it.value().toString(); proxyManager->setProxyConfiguration(proxyConf); - if (hasKey("proxy_peer_connections")) + if (hasKey(u"proxy_peer_connections"_qs)) session->setProxyPeerConnectionsEnabled(it.value().toBool()); - if (hasKey("proxy_torrents_only")) + if (hasKey(u"proxy_torrents_only"_qs)) proxyManager->setProxyOnlyForTorrents(it.value().toBool()); // IP Filtering - if (hasKey("ip_filter_enabled")) + if (hasKey(u"ip_filter_enabled"_qs)) session->setIPFilteringEnabled(it.value().toBool()); - if (hasKey("ip_filter_path")) + if (hasKey(u"ip_filter_path"_qs)) session->setIPFilterFile(Path(it.value().toString())); - if (hasKey("ip_filter_trackers")) + if (hasKey(u"ip_filter_trackers"_qs)) session->setTrackerFilteringEnabled(it.value().toBool()); - if (hasKey("banned_IPs")) - session->setBannedIPs(it.value().toString().split('\n', Qt::SkipEmptyParts)); + if (hasKey(u"banned_IPs"_qs)) + session->setBannedIPs(it.value().toString().split(u'\n', Qt::SkipEmptyParts)); // Speed // Global Rate Limits - if (hasKey("dl_limit")) + if (hasKey(u"dl_limit"_qs)) session->setGlobalDownloadSpeedLimit(it.value().toInt()); - if (hasKey("up_limit")) + if (hasKey(u"up_limit"_qs)) session->setGlobalUploadSpeedLimit(it.value().toInt()); - if (hasKey("alt_dl_limit")) + if (hasKey(u"alt_dl_limit"_qs)) session->setAltGlobalDownloadSpeedLimit(it.value().toInt()); - if (hasKey("alt_up_limit")) + if (hasKey(u"alt_up_limit"_qs)) session->setAltGlobalUploadSpeedLimit(it.value().toInt()); - if (hasKey("bittorrent_protocol")) + if (hasKey(u"bittorrent_protocol"_qs)) session->setBTProtocol(static_cast(it.value().toInt())); - if (hasKey("limit_utp_rate")) + if (hasKey(u"limit_utp_rate"_qs)) session->setUTPRateLimited(it.value().toBool()); - if (hasKey("limit_tcp_overhead")) + if (hasKey(u"limit_tcp_overhead"_qs)) session->setIncludeOverheadInLimits(it.value().toBool()); - if (hasKey("limit_lan_peers")) + if (hasKey(u"limit_lan_peers"_qs)) session->setIgnoreLimitsOnLAN(!it.value().toBool()); // Scheduling - if (hasKey("scheduler_enabled")) + if (hasKey(u"scheduler_enabled"_qs)) session->setBandwidthSchedulerEnabled(it.value().toBool()); - if (m.contains("schedule_from_hour") && m.contains("schedule_from_min")) - pref->setSchedulerStartTime(QTime(m["schedule_from_hour"].toInt(), m["schedule_from_min"].toInt())); - if (m.contains("schedule_to_hour") && m.contains("schedule_to_min")) - pref->setSchedulerEndTime(QTime(m["schedule_to_hour"].toInt(), m["schedule_to_min"].toInt())); - if (hasKey("scheduler_days")) + if (m.contains(u"schedule_from_hour"_qs) && m.contains(u"schedule_from_min"_qs)) + pref->setSchedulerStartTime(QTime(m[u"schedule_from_hour"_qs].toInt(), m[u"schedule_from_min"_qs].toInt())); + if (m.contains(u"schedule_to_hour"_qs) && m.contains(u"schedule_to_min"_qs)) + pref->setSchedulerEndTime(QTime(m[u"schedule_to_hour"_qs].toInt(), m[u"schedule_to_min"_qs].toInt())); + if (hasKey(u"scheduler_days"_qs)) pref->setSchedulerDays(static_cast(it.value().toInt())); // Bittorrent // Privacy - if (hasKey("dht")) + if (hasKey(u"dht"_qs)) session->setDHTEnabled(it.value().toBool()); - if (hasKey("pex")) + if (hasKey(u"pex"_qs)) session->setPeXEnabled(it.value().toBool()); - if (hasKey("lsd")) + if (hasKey(u"lsd"_qs)) session->setLSDEnabled(it.value().toBool()); - if (hasKey("encryption")) + if (hasKey(u"encryption"_qs)) session->setEncryption(it.value().toInt()); - if (hasKey("anonymous_mode")) + if (hasKey(u"anonymous_mode"_qs)) session->setAnonymousModeEnabled(it.value().toBool()); // Max active checking torrents - if (hasKey("max_active_checking_torrents")) + if (hasKey(u"max_active_checking_torrents"_qs)) session->setMaxActiveCheckingTorrents(it.value().toInt()); // Torrent Queueing - if (hasKey("queueing_enabled")) + if (hasKey(u"queueing_enabled"_qs)) session->setQueueingSystemEnabled(it.value().toBool()); - if (hasKey("max_active_downloads")) + if (hasKey(u"max_active_downloads"_qs)) session->setMaxActiveDownloads(it.value().toInt()); - if (hasKey("max_active_torrents")) + if (hasKey(u"max_active_torrents"_qs)) session->setMaxActiveTorrents(it.value().toInt()); - if (hasKey("max_active_uploads")) + if (hasKey(u"max_active_uploads"_qs)) session->setMaxActiveUploads(it.value().toInt()); - if (hasKey("dont_count_slow_torrents")) + if (hasKey(u"dont_count_slow_torrents"_qs)) session->setIgnoreSlowTorrentsForQueueing(it.value().toBool()); - if (hasKey("slow_torrent_dl_rate_threshold")) + if (hasKey(u"slow_torrent_dl_rate_threshold"_qs)) session->setDownloadRateForSlowTorrents(it.value().toInt()); - if (hasKey("slow_torrent_ul_rate_threshold")) + if (hasKey(u"slow_torrent_ul_rate_threshold"_qs)) session->setUploadRateForSlowTorrents(it.value().toInt()); - if (hasKey("slow_torrent_inactive_timer")) + if (hasKey(u"slow_torrent_inactive_timer"_qs)) session->setSlowTorrentsInactivityTimer(it.value().toInt()); // Share Ratio Limiting - if (hasKey("max_ratio_enabled")) + if (hasKey(u"max_ratio_enabled"_qs)) { if (it.value().toBool()) - session->setGlobalMaxRatio(m["max_ratio"].toReal()); + session->setGlobalMaxRatio(m[u"max_ratio"_qs].toReal()); else session->setGlobalMaxRatio(-1); } - if (hasKey("max_seeding_time_enabled")) + if (hasKey(u"max_seeding_time_enabled"_qs)) { if (it.value().toBool()) - session->setGlobalMaxSeedingMinutes(m["max_seeding_time"].toInt()); + session->setGlobalMaxSeedingMinutes(m[u"max_seeding_time"_qs].toInt()); else session->setGlobalMaxSeedingMinutes(-1); } - if (hasKey("max_ratio_act")) + if (hasKey(u"max_ratio_act"_qs)) session->setMaxRatioAction(static_cast(it.value().toInt())); // Add trackers - if (hasKey("add_trackers_enabled")) + if (hasKey(u"add_trackers_enabled"_qs)) session->setAddTrackersEnabled(it.value().toBool()); - if (hasKey("add_trackers")) + if (hasKey(u"add_trackers"_qs)) session->setAdditionalTrackers(it.value().toString()); // Web UI // Language - if (hasKey("locale")) + if (hasKey(u"locale"_qs)) { QString locale = it.value().toString(); if (pref->getLocale() != locale) @@ -650,96 +650,96 @@ void AppController::setPreferencesAction() pref->setLocale(locale); } } - if (hasKey("performance_warning")) + if (hasKey(u"performance_warning"_qs)) session->setPerformanceWarningEnabled(it.value().toBool()); // HTTP Server - if (hasKey("web_ui_domain_list")) + if (hasKey(u"web_ui_domain_list"_qs)) pref->setServerDomains(it.value().toString()); - if (hasKey("web_ui_address")) + if (hasKey(u"web_ui_address"_qs)) pref->setWebUiAddress(it.value().toString()); - if (hasKey("web_ui_port")) + if (hasKey(u"web_ui_port"_qs)) pref->setWebUiPort(it.value().toUInt()); - if (hasKey("web_ui_upnp")) + if (hasKey(u"web_ui_upnp"_qs)) pref->setUPnPForWebUIPort(it.value().toBool()); - if (hasKey("use_https")) + if (hasKey(u"use_https"_qs)) pref->setWebUiHttpsEnabled(it.value().toBool()); - if (hasKey("web_ui_https_cert_path")) + if (hasKey(u"web_ui_https_cert_path"_qs)) pref->setWebUIHttpsCertificatePath(Path(it.value().toString())); - if (hasKey("web_ui_https_key_path")) + if (hasKey(u"web_ui_https_key_path"_qs)) pref->setWebUIHttpsKeyPath(Path(it.value().toString())); // Authentication - if (hasKey("web_ui_username")) + if (hasKey(u"web_ui_username"_qs)) pref->setWebUiUsername(it.value().toString()); - if (hasKey("web_ui_password")) + if (hasKey(u"web_ui_password"_qs)) pref->setWebUIPassword(Utils::Password::PBKDF2::generate(it.value().toByteArray())); - if (hasKey("bypass_local_auth")) + if (hasKey(u"bypass_local_auth"_qs)) pref->setWebUiLocalAuthEnabled(!it.value().toBool()); - if (hasKey("bypass_auth_subnet_whitelist_enabled")) + if (hasKey(u"bypass_auth_subnet_whitelist_enabled"_qs)) pref->setWebUiAuthSubnetWhitelistEnabled(it.value().toBool()); - if (hasKey("bypass_auth_subnet_whitelist")) + if (hasKey(u"bypass_auth_subnet_whitelist"_qs)) { // recognize new lines and commas as delimiters - pref->setWebUiAuthSubnetWhitelist(it.value().toString().split(QRegularExpression("\n|,"), Qt::SkipEmptyParts)); + pref->setWebUiAuthSubnetWhitelist(it.value().toString().split(QRegularExpression(u"\n|,"_qs), Qt::SkipEmptyParts)); } - if (hasKey("web_ui_max_auth_fail_count")) + if (hasKey(u"web_ui_max_auth_fail_count"_qs)) pref->setWebUIMaxAuthFailCount(it.value().toInt()); - if (hasKey("web_ui_ban_duration")) + if (hasKey(u"web_ui_ban_duration"_qs)) pref->setWebUIBanDuration(std::chrono::seconds {it.value().toInt()}); - if (hasKey("web_ui_session_timeout")) + if (hasKey(u"web_ui_session_timeout"_qs)) pref->setWebUISessionTimeout(it.value().toInt()); // Use alternative Web UI - if (hasKey("alternative_webui_enabled")) + if (hasKey(u"alternative_webui_enabled"_qs)) pref->setAltWebUiEnabled(it.value().toBool()); - if (hasKey("alternative_webui_path")) + if (hasKey(u"alternative_webui_path"_qs)) pref->setWebUiRootFolder(Path(it.value().toString())); // Security - if (hasKey("web_ui_clickjacking_protection_enabled")) + if (hasKey(u"web_ui_clickjacking_protection_enabled"_qs)) pref->setWebUiClickjackingProtectionEnabled(it.value().toBool()); - if (hasKey("web_ui_csrf_protection_enabled")) + if (hasKey(u"web_ui_csrf_protection_enabled"_qs)) pref->setWebUiCSRFProtectionEnabled(it.value().toBool()); - if (hasKey("web_ui_secure_cookie_enabled")) + if (hasKey(u"web_ui_secure_cookie_enabled"_qs)) pref->setWebUiSecureCookieEnabled(it.value().toBool()); - if (hasKey("web_ui_host_header_validation_enabled")) + if (hasKey(u"web_ui_host_header_validation_enabled"_qs)) pref->setWebUIHostHeaderValidationEnabled(it.value().toBool()); // Custom HTTP headers - if (hasKey("web_ui_use_custom_http_headers_enabled")) + if (hasKey(u"web_ui_use_custom_http_headers_enabled"_qs)) pref->setWebUICustomHTTPHeadersEnabled(it.value().toBool()); - if (hasKey("web_ui_custom_http_headers")) + if (hasKey(u"web_ui_custom_http_headers"_qs)) pref->setWebUICustomHTTPHeaders(it.value().toString()); // Reverse proxy - if (hasKey("web_ui_reverse_proxy_enabled")) + if (hasKey(u"web_ui_reverse_proxy_enabled"_qs)) pref->setWebUIReverseProxySupportEnabled(it.value().toBool()); - if (hasKey("web_ui_reverse_proxies_list")) + if (hasKey(u"web_ui_reverse_proxies_list"_qs)) pref->setWebUITrustedReverseProxiesList(it.value().toString()); // Update my dynamic domain name - if (hasKey("dyndns_enabled")) + if (hasKey(u"dyndns_enabled"_qs)) pref->setDynDNSEnabled(it.value().toBool()); - if (hasKey("dyndns_service")) + if (hasKey(u"dyndns_service"_qs)) pref->setDynDNSService(static_cast(it.value().toInt())); - if (hasKey("dyndns_username")) + if (hasKey(u"dyndns_username"_qs)) pref->setDynDNSUsername(it.value().toString()); - if (hasKey("dyndns_password")) + if (hasKey(u"dyndns_password"_qs)) pref->setDynDNSPassword(it.value().toString()); - if (hasKey("dyndns_domain")) + if (hasKey(u"dyndns_domain"_qs)) pref->setDynDomainName(it.value().toString()); - if (hasKey("rss_refresh_interval")) + if (hasKey(u"rss_refresh_interval"_qs)) RSS::Session::instance()->setRefreshInterval(it.value().toInt()); - if (hasKey("rss_max_articles_per_feed")) + if (hasKey(u"rss_max_articles_per_feed"_qs)) RSS::Session::instance()->setMaxArticlesPerFeed(it.value().toInt()); - if (hasKey("rss_processing_enabled")) + if (hasKey(u"rss_processing_enabled"_qs)) RSS::Session::instance()->setProcessingEnabled(it.value().toBool()); - if (hasKey("rss_auto_downloading_enabled")) + if (hasKey(u"rss_auto_downloading_enabled"_qs)) RSS::AutoDownloader::instance()->setProcessingEnabled(it.value().toBool()); - if (hasKey("rss_download_repack_proper_episodes")) + if (hasKey(u"rss_download_repack_proper_episodes"_qs)) RSS::AutoDownloader::instance()->setDownloadRepacks(it.value().toBool()); - if (hasKey("rss_smart_episode_filters")) - RSS::AutoDownloader::instance()->setSmartEpisodeFilters(it.value().toString().split('\n')); + if (hasKey(u"rss_smart_episode_filters"_qs)) + RSS::AutoDownloader::instance()->setSmartEpisodeFilters(it.value().toString().split(u'\n')); // Advanced settings // qBittorrent preferences // Current network interface - if (hasKey("current_network_interface")) + if (hasKey(u"current_network_interface"_qs)) { const QString ifaceValue {it.value().toString()}; @@ -754,133 +754,133 @@ void AppController::setPreferencesAction() session->setNetworkInterfaceName(ifaceName); } // Current network interface address - if (hasKey("current_interface_address")) + if (hasKey(u"current_interface_address"_qs)) { const QHostAddress ifaceAddress {it.value().toString().trimmed()}; session->setNetworkInterfaceAddress(ifaceAddress.isNull() ? QString {} : ifaceAddress.toString()); } // Save resume data interval - if (hasKey("save_resume_data_interval")) + if (hasKey(u"save_resume_data_interval"_qs)) session->setSaveResumeDataInterval(it.value().toInt()); // Recheck completed torrents - if (hasKey("recheck_completed_torrents")) + if (hasKey(u"recheck_completed_torrents"_qs)) pref->recheckTorrentsOnCompletion(it.value().toBool()); // Resolve peer countries - if (hasKey("resolve_peer_countries")) + if (hasKey(u"resolve_peer_countries"_qs)) pref->resolvePeerCountries(it.value().toBool()); // Reannounce to all trackers when ip/port changed - if (hasKey("reannounce_when_address_changed")) + if (hasKey(u"reannounce_when_address_changed"_qs)) session->setReannounceWhenAddressChangedEnabled(it.value().toBool()); // libtorrent preferences // Async IO threads - if (hasKey("async_io_threads")) + if (hasKey(u"async_io_threads"_qs)) session->setAsyncIOThreads(it.value().toInt()); // Hashing threads - if (hasKey("hashing_threads")) + if (hasKey(u"hashing_threads"_qs)) session->setHashingThreads(it.value().toInt()); // File pool size - if (hasKey("file_pool_size")) + if (hasKey(u"file_pool_size"_qs)) session->setFilePoolSize(it.value().toInt()); // Checking Memory Usage - if (hasKey("checking_memory_use")) + if (hasKey(u"checking_memory_use"_qs)) session->setCheckingMemUsage(it.value().toInt()); // Disk write cache - if (hasKey("disk_cache")) + if (hasKey(u"disk_cache"_qs)) session->setDiskCacheSize(it.value().toInt()); - if (hasKey("disk_cache_ttl")) + if (hasKey(u"disk_cache_ttl"_qs)) session->setDiskCacheTTL(it.value().toInt()); // Disk queue size - if (hasKey("disk_queue_size")) + if (hasKey(u"disk_queue_size"_qs)) session->setDiskQueueSize(it.value().toLongLong()); // Enable OS cache - if (hasKey("enable_os_cache")) + if (hasKey(u"enable_os_cache"_qs)) session->setUseOSCache(it.value().toBool()); // Coalesce reads & writes - if (hasKey("enable_coalesce_read_write")) + if (hasKey(u"enable_coalesce_read_write"_qs)) session->setCoalesceReadWriteEnabled(it.value().toBool()); // Piece extent affinity - if (hasKey("enable_piece_extent_affinity")) + if (hasKey(u"enable_piece_extent_affinity"_qs)) session->setPieceExtentAffinity(it.value().toBool()); // Suggest mode - if (hasKey("enable_upload_suggestions")) + if (hasKey(u"enable_upload_suggestions"_qs)) session->setSuggestMode(it.value().toBool()); // Send buffer watermark - if (hasKey("send_buffer_watermark")) + if (hasKey(u"send_buffer_watermark"_qs)) session->setSendBufferWatermark(it.value().toInt()); - if (hasKey("send_buffer_low_watermark")) + if (hasKey(u"send_buffer_low_watermark"_qs)) session->setSendBufferLowWatermark(it.value().toInt()); - if (hasKey("send_buffer_watermark_factor")) + if (hasKey(u"send_buffer_watermark_factor"_qs)) session->setSendBufferWatermarkFactor(it.value().toInt()); // Outgoing connections per second - if (hasKey("connection_speed")) + if (hasKey(u"connection_speed"_qs)) session->setConnectionSpeed(it.value().toInt()); // Socket listen backlog size - if (hasKey("socket_backlog_size")) + if (hasKey(u"socket_backlog_size"_qs)) session->setSocketBacklogSize(it.value().toInt()); // Outgoing ports - if (hasKey("outgoing_ports_min")) + if (hasKey(u"outgoing_ports_min"_qs)) session->setOutgoingPortsMin(it.value().toInt()); - if (hasKey("outgoing_ports_max")) + if (hasKey(u"outgoing_ports_max"_qs)) session->setOutgoingPortsMax(it.value().toInt()); // UPnP lease duration - if (hasKey("upnp_lease_duration")) + if (hasKey(u"upnp_lease_duration"_qs)) session->setUPnPLeaseDuration(it.value().toInt()); // Type of service - if (hasKey("peer_tos")) + if (hasKey(u"peer_tos"_qs)) session->setPeerToS(it.value().toInt()); // uTP-TCP mixed mode - if (hasKey("utp_tcp_mixed_mode")) + if (hasKey(u"utp_tcp_mixed_mode"_qs)) session->setUtpMixedMode(static_cast(it.value().toInt())); // Support internationalized domain name (IDN) - if (hasKey("idn_support_enabled")) + if (hasKey(u"idn_support_enabled"_qs)) session->setIDNSupportEnabled(it.value().toBool()); // Multiple connections per IP - if (hasKey("enable_multi_connections_from_same_ip")) + if (hasKey(u"enable_multi_connections_from_same_ip"_qs)) session->setMultiConnectionsPerIpEnabled(it.value().toBool()); // Validate HTTPS tracker certificate - if (hasKey("validate_https_tracker_certificate")) + if (hasKey(u"validate_https_tracker_certificate"_qs)) session->setValidateHTTPSTrackerCertificate(it.value().toBool()); // SSRF mitigation - if (hasKey("ssrf_mitigation")) + if (hasKey(u"ssrf_mitigation"_qs)) session->setSSRFMitigationEnabled(it.value().toBool()); // Disallow connection to peers on privileged ports - if (hasKey("block_peers_on_privileged_ports")) + if (hasKey(u"block_peers_on_privileged_ports"_qs)) session->setBlockPeersOnPrivilegedPorts(it.value().toBool()); // Embedded tracker - if (hasKey("embedded_tracker_port")) + if (hasKey(u"embedded_tracker_port"_qs)) pref->setTrackerPort(it.value().toInt()); - if (hasKey("enable_embedded_tracker")) + if (hasKey(u"enable_embedded_tracker"_qs)) session->setTrackerEnabled(it.value().toBool()); // Choking algorithm - if (hasKey("upload_slots_behavior")) + if (hasKey(u"upload_slots_behavior"_qs)) session->setChokingAlgorithm(static_cast(it.value().toInt())); // Seed choking algorithm - if (hasKey("upload_choking_algorithm")) + if (hasKey(u"upload_choking_algorithm"_qs)) session->setSeedChokingAlgorithm(static_cast(it.value().toInt())); // Announce - if (hasKey("announce_to_all_trackers")) + if (hasKey(u"announce_to_all_trackers"_qs)) session->setAnnounceToAllTrackers(it.value().toBool()); - if (hasKey("announce_to_all_tiers")) + if (hasKey(u"announce_to_all_tiers"_qs)) session->setAnnounceToAllTiers(it.value().toBool()); - if (hasKey("announce_ip")) + if (hasKey(u"announce_ip"_qs)) { const QHostAddress announceAddr {it.value().toString().trimmed()}; session->setAnnounceIP(announceAddr.isNull() ? QString {} : announceAddr.toString()); } - if (hasKey("max_concurrent_http_announces")) + if (hasKey(u"max_concurrent_http_announces"_qs)) session->setMaxConcurrentHTTPAnnounces(it.value().toInt()); - if (hasKey("stop_tracker_timeout")) + if (hasKey(u"stop_tracker_timeout"_qs)) session->setStopTrackerTimeout(it.value().toInt()); // Peer Turnover - if (hasKey("peer_turnover")) + if (hasKey(u"peer_turnover"_qs)) session->setPeerTurnover(it.value().toInt()); - if (hasKey("peer_turnover_cutoff")) + if (hasKey(u"peer_turnover_cutoff"_qs)) session->setPeerTurnoverCutoff(it.value().toInt()); - if (hasKey("peer_turnover_interval")) + if (hasKey(u"peer_turnover_interval"_qs)) session->setPeerTurnoverInterval(it.value().toInt()); // Maximum outstanding requests to a single peer - if (hasKey("request_queue_size")) + if (hasKey(u"request_queue_size"_qs)) session->setRequestQueueSize(it.value().toInt()); // Save preferences @@ -901,8 +901,8 @@ void AppController::networkInterfaceListAction() { ifaceList.append(QJsonObject { - {"name", iface.humanReadableName()}, - {"value", iface.name()} + {u"name"_qs, iface.humanReadableName()}, + {u"value"_qs, iface.name()} }); } } @@ -912,9 +912,9 @@ void AppController::networkInterfaceListAction() void AppController::networkInterfaceAddressListAction() { - requireParams({"iface"}); + requireParams({u"iface"_qs}); - const QString ifaceName = params().value("iface"); + const QString ifaceName = params().value(u"iface"_qs); QJsonArray addressList; const auto appendAddress = [&addressList](const QHostAddress &addr) diff --git a/src/webui/api/authcontroller.cpp b/src/webui/api/authcontroller.cpp index 5dd63f8dd72..ccbd0453a31 100644 --- a/src/webui/api/authcontroller.cpp +++ b/src/webui/api/authcontroller.cpp @@ -30,6 +30,7 @@ #include +#include "base/global.h" #include "base/logger.h" #include "base/preferences.h" #include "base/utils/password.h" @@ -45,8 +46,8 @@ void AuthController::loginAction() } const QString clientAddr {sessionManager()->clientId()}; - const QString usernameFromWeb {params()["username"]}; - const QString passwordFromWeb {params()["password"]}; + const QString usernameFromWeb {params()[u"username"_qs]}; + const QString passwordFromWeb {params()[u"password"_qs]}; if (isBanned()) { diff --git a/src/webui/api/logcontroller.cpp b/src/webui/api/logcontroller.cpp index 90e752c7f57..b6a49f92ff1 100644 --- a/src/webui/api/logcontroller.cpp +++ b/src/webui/api/logcontroller.cpp @@ -61,13 +61,13 @@ void LogController::mainAction() { using Utils::String::parseBool; - const bool isNormal = parseBool(params()["normal"]).value_or(true); - const bool isInfo = parseBool(params()["info"]).value_or(true); - const bool isWarning = parseBool(params()["warning"]).value_or(true); - const bool isCritical = parseBool(params()["critical"]).value_or(true); + const bool isNormal = parseBool(params()[u"normal"_qs]).value_or(true); + const bool isInfo = parseBool(params()[u"info"_qs]).value_or(true); + const bool isWarning = parseBool(params()[u"warning"_qs]).value_or(true); + const bool isCritical = parseBool(params()[u"critical"_qs]).value_or(true); bool ok = false; - int lastKnownId = params()["last_known_id"].toInt(&ok); + int lastKnownId = params()[u"last_known_id"_qs].toInt(&ok); if (!ok) lastKnownId = -1; @@ -107,7 +107,7 @@ void LogController::mainAction() void LogController::peersAction() { bool ok = false; - int lastKnownId = params()["last_known_id"].toInt(&ok); + int lastKnownId = params()[u"last_known_id"_qs].toInt(&ok); if (!ok) lastKnownId = -1; diff --git a/src/webui/api/rsscontroller.cpp b/src/webui/api/rsscontroller.cpp index f0a16a8d79d..321020cfd34 100644 --- a/src/webui/api/rsscontroller.cpp +++ b/src/webui/api/rsscontroller.cpp @@ -47,9 +47,9 @@ using Utils::String::parseBool; void RSSController::addFolderAction() { - requireParams({"path"}); + requireParams({u"path"_qs}); - const QString path = params()["path"].trimmed(); + const QString path = params()[u"path"_qs].trimmed(); const nonstd::expected result = RSS::Session::instance()->addFolder(path); if (!result) throw APIError(APIErrorType::Conflict, result.error()); @@ -57,10 +57,10 @@ void RSSController::addFolderAction() void RSSController::addFeedAction() { - requireParams({"url", "path"}); + requireParams({u"url"_qs, u"path"_qs}); - const QString url = params()["url"].trimmed(); - const QString path = params()["path"].trimmed(); + const QString url = params()[u"url"_qs].trimmed(); + const QString path = params()[u"path"_qs].trimmed(); const nonstd::expected result = RSS::Session::instance()->addFeed(url, (path.isEmpty() ? url : path)); if (!result) throw APIError(APIErrorType::Conflict, result.error()); @@ -68,9 +68,9 @@ void RSSController::addFeedAction() void RSSController::removeItemAction() { - requireParams({"path"}); + requireParams({u"path"_qs}); - const QString path = params()["path"].trimmed(); + const QString path = params()[u"path"_qs].trimmed(); const nonstd::expected result = RSS::Session::instance()->removeItem(path); if (!result) throw APIError(APIErrorType::Conflict, result.error()); @@ -78,10 +78,10 @@ void RSSController::removeItemAction() void RSSController::moveItemAction() { - requireParams({"itemPath", "destPath"}); + requireParams({u"itemPath"_qs, u"destPath"_qs}); - const QString itemPath = params()["itemPath"].trimmed(); - const QString destPath = params()["destPath"].trimmed(); + const QString itemPath = params()[u"itemPath"_qs].trimmed(); + const QString destPath = params()[u"destPath"_qs].trimmed(); const nonstd::expected result = RSS::Session::instance()->moveItem(itemPath, destPath); if (!result) throw APIError(APIErrorType::Conflict, result.error()); @@ -89,7 +89,7 @@ void RSSController::moveItemAction() void RSSController::itemsAction() { - const bool withData {parseBool(params()["withData"]).value_or(false)}; + const bool withData {parseBool(params()[u"withData"_qs]).value_or(false)}; const auto jsonVal = RSS::Session::instance()->rootFolder()->toJsonValue(withData); setResult(jsonVal.toObject()); @@ -97,10 +97,10 @@ void RSSController::itemsAction() void RSSController::markAsReadAction() { - requireParams({"itemPath"}); + requireParams({u"itemPath"_qs}); - const QString itemPath {params()["itemPath"]}; - const QString articleId {params()["articleId"]}; + const QString itemPath {params()[u"itemPath"_qs]}; + const QString articleId {params()[u"articleId"_qs]}; RSS::Item *item = RSS::Session::instance()->itemByPath(itemPath); if (!item) return; @@ -123,9 +123,9 @@ void RSSController::markAsReadAction() void RSSController::refreshItemAction() { - requireParams({"itemPath"}); + requireParams({u"itemPath"_qs}); - const QString itemPath {params()["itemPath"]}; + const QString itemPath {params()[u"itemPath"_qs]}; RSS::Item *item = RSS::Session::instance()->itemByPath(itemPath); if (item) item->refresh(); @@ -133,10 +133,10 @@ void RSSController::refreshItemAction() void RSSController::setRuleAction() { - requireParams({"ruleName", "ruleDef"}); + requireParams({u"ruleName"_qs, u"ruleDef"_qs}); - const QString ruleName {params()["ruleName"].trimmed()}; - const QByteArray ruleDef {params()["ruleDef"].trimmed().toUtf8()}; + const QString ruleName {params()[u"ruleName"_qs].trimmed()}; + const QByteArray ruleDef {params()[u"ruleDef"_qs].trimmed().toUtf8()}; const auto jsonObj = QJsonDocument::fromJson(ruleDef).object(); RSS::AutoDownloader::instance()->insertRule(RSS::AutoDownloadRule::fromJsonObject(jsonObj, ruleName)); @@ -144,19 +144,19 @@ void RSSController::setRuleAction() void RSSController::renameRuleAction() { - requireParams({"ruleName", "newRuleName"}); + requireParams({u"ruleName"_qs, u"newRuleName"_qs}); - const QString ruleName {params()["ruleName"].trimmed()}; - const QString newRuleName {params()["newRuleName"].trimmed()}; + const QString ruleName {params()[u"ruleName"_qs].trimmed()}; + const QString newRuleName {params()[u"newRuleName"_qs].trimmed()}; RSS::AutoDownloader::instance()->renameRule(ruleName, newRuleName); } void RSSController::removeRuleAction() { - requireParams({"ruleName"}); + requireParams({u"ruleName"_qs}); - const QString ruleName {params()["ruleName"].trimmed()}; + const QString ruleName {params()[u"ruleName"_qs].trimmed()}; RSS::AutoDownloader::instance()->removeRule(ruleName); } @@ -172,9 +172,9 @@ void RSSController::rulesAction() void RSSController::matchingArticlesAction() { - requireParams({"ruleName"}); + requireParams({u"ruleName"_qs}); - const QString ruleName {params()["ruleName"]}; + const QString ruleName {params()[u"ruleName"_qs]}; const RSS::AutoDownloadRule rule = RSS::AutoDownloader::instance()->ruleByName(ruleName); QJsonObject jsonObj; diff --git a/src/webui/api/searchcontroller.cpp b/src/webui/api/searchcontroller.cpp index 7ef495da689..4ae78f2c211 100644 --- a/src/webui/api/searchcontroller.cpp +++ b/src/webui/api/searchcontroller.cpp @@ -72,8 +72,8 @@ namespace { QJsonArray categoriesInfo {QJsonObject { - {QLatin1String("id"), "all"}, - {QLatin1String("name"), SearchPluginManager::categoryFullName("all")} + {QLatin1String("id"), u"all"_qs}, + {QLatin1String("name"), SearchPluginManager::categoryFullName(u"all"_qs)} }}; categories.sort(Qt::CaseInsensitive); @@ -92,22 +92,22 @@ namespace void SearchController::startAction() { - requireParams({"pattern", "category", "plugins"}); + requireParams({u"pattern"_qs, u"category"_qs, u"plugins"_qs}); if (!Utils::ForeignApps::pythonInfo().isValid()) throw APIError(APIErrorType::Conflict, tr("Python must be installed to use the Search Engine.")); - const QString pattern = params()["pattern"].trimmed(); - const QString category = params()["category"].trimmed(); - const QStringList plugins = params()["plugins"].split('|'); + const QString pattern = params()[u"pattern"_qs].trimmed(); + const QString category = params()[u"category"_qs].trimmed(); + const QStringList plugins = params()[u"plugins"_qs].split(u'|'); QStringList pluginsToUse; if (plugins.size() == 1) { const QString pluginsLower = plugins[0].toLower(); - if (pluginsLower == "all") + if (pluginsLower == u"all") pluginsToUse = SearchPluginManager::instance()->allPlugins(); - else if ((pluginsLower == "enabled") || (pluginsLower == "multi")) + else if ((pluginsLower == u"enabled") || (pluginsLower == u"multi")) pluginsToUse = SearchPluginManager::instance()->enabledPlugins(); else pluginsToUse << plugins; @@ -134,15 +134,15 @@ void SearchController::startAction() activeSearches.insert(id); session->setData(ACTIVE_SEARCHES, QVariant::fromValue(activeSearches)); - const QJsonObject result = {{"id", id}}; + const QJsonObject result = {{u"id"_qs, id}}; setResult(result); } void SearchController::stopAction() { - requireParams({"id"}); + requireParams({u"id"_qs}); - const int id = params()["id"].toInt(); + const int id = params()[u"id"_qs].toInt(); ISession *const session = sessionManager()->session(); const auto searchHandlers = session->getData(SEARCH_HANDLERS); @@ -160,7 +160,7 @@ void SearchController::stopAction() void SearchController::statusAction() { - const int id = params()["id"].toInt(); + const int id = params()[u"id"_qs].toInt(); const auto searchHandlers = sessionManager()->session()->getData(SEARCH_HANDLERS); if ((id != 0) && !searchHandlers.contains(id)) @@ -174,9 +174,9 @@ void SearchController::statusAction() const SearchHandlerPtr searchHandler = searchHandlers[searchId]; statusArray << QJsonObject { - {"id", searchId}, - {"status", searchHandler->isActive() ? "Running" : "Stopped"}, - {"total", searchHandler->results().size()} + {u"id"_qs, searchId}, + {u"status"_qs, searchHandler->isActive() ? u"Running"_qs : u"Stopped"_qs}, + {u"total"_qs, searchHandler->results().size()} }; } @@ -185,11 +185,11 @@ void SearchController::statusAction() void SearchController::resultsAction() { - requireParams({"id"}); + requireParams({u"id"_qs}); - const int id = params()["id"].toInt(); - int limit = params()["limit"].toInt(); - int offset = params()["offset"].toInt(); + const int id = params()[u"id"_qs].toInt(); + int limit = params()[u"limit"_qs].toInt(); + int offset = params()[u"offset"_qs].toInt(); const auto searchHandlers = sessionManager()->session()->getData(SEARCH_HANDLERS); if (!searchHandlers.contains(id)) @@ -218,9 +218,9 @@ void SearchController::resultsAction() void SearchController::deleteAction() { - requireParams({"id"}); + requireParams({u"id"_qs}); - const int id = params()["id"].toInt(); + const int id = params()[u"id"_qs].toInt(); ISession *const session = sessionManager()->session(); auto searchHandlers = session->getData(SEARCH_HANDLERS); @@ -243,28 +243,28 @@ void SearchController::pluginsAction() void SearchController::installPluginAction() { - requireParams({"sources"}); + requireParams({u"sources"_qs}); - const QStringList sources = params()["sources"].split('|'); + const QStringList sources = params()[u"sources"_qs].split(u'|'); for (const QString &source : sources) SearchPluginManager::instance()->installPlugin(source); } void SearchController::uninstallPluginAction() { - requireParams({"names"}); + requireParams({u"names"_qs}); - const QStringList names = params()["names"].split('|'); + const QStringList names = params()[u"names"_qs].split(u'|'); for (const QString &name : names) SearchPluginManager::instance()->uninstallPlugin(name.trimmed()); } void SearchController::enablePluginAction() { - requireParams({"names", "enable"}); + requireParams({u"names"_qs, u"enable"_qs}); - const QStringList names = params()["names"].split('|'); - const bool enable = Utils::String::parseBool(params()["enable"].trimmed()).value_or(false); + const QStringList names = params()[u"names"_qs].split(u'|'); + const bool enable = Utils::String::parseBool(params()[u"enable"_qs].trimmed()).value_or(false); for (const QString &name : names) SearchPluginManager::instance()->enablePlugin(name.trimmed(), enable); @@ -344,21 +344,21 @@ QJsonObject SearchController::getResults(const QList &searchResult { searchResultsArray << QJsonObject { - {"fileName", searchResult.fileName}, - {"fileUrl", searchResult.fileUrl}, - {"fileSize", searchResult.fileSize}, - {"nbSeeders", searchResult.nbSeeders}, - {"nbLeechers", searchResult.nbLeechers}, - {"siteUrl", searchResult.siteUrl}, - {"descrLink", searchResult.descrLink} + {u"fileName"_qs, searchResult.fileName}, + {u"fileUrl"_qs, searchResult.fileUrl}, + {u"fileSize"_qs, searchResult.fileSize}, + {u"nbSeeders"_qs, searchResult.nbSeeders}, + {u"nbLeechers"_qs, searchResult.nbLeechers}, + {u"siteUrl"_qs, searchResult.siteUrl}, + {u"descrLink"_qs, searchResult.descrLink} }; } const QJsonObject result = { - {"status", isSearchActive ? "Running" : "Stopped"}, - {"results", searchResultsArray}, - {"total", totalResults} + {u"status"_qs, isSearchActive ? u"Running"_qs : u"Stopped"_qs}, + {u"results"_qs, searchResultsArray}, + {u"total"_qs, totalResults} }; return result; @@ -387,12 +387,12 @@ QJsonArray SearchController::getPluginsInfo(const QStringList &plugins) const pluginsArray << QJsonObject { - {"name", pluginInfo->name}, - {"version", QString(pluginInfo->version)}, - {"fullName", pluginInfo->fullName}, - {"url", pluginInfo->url}, - {"supportedCategories", getPluginCategories(pluginInfo->supportedCategories)}, - {"enabled", pluginInfo->enabled} + {u"name"_qs, pluginInfo->name}, + {u"version"_qs, QString(pluginInfo->version)}, + {u"fullName"_qs, pluginInfo->fullName}, + {u"url"_qs, pluginInfo->url}, + {u"supportedCategories"_qs, getPluginCategories(pluginInfo->supportedCategories)}, + {u"enabled"_qs, pluginInfo->enabled} }; } diff --git a/src/webui/api/serialize/serialize_torrent.h b/src/webui/api/serialize/serialize_torrent.h index 54d50f616fd..09d93aefcdc 100644 --- a/src/webui/api/serialize/serialize_torrent.h +++ b/src/webui/api/serialize/serialize_torrent.h @@ -30,6 +30,8 @@ #include +#include "base/global.h" + namespace BitTorrent { class Torrent; @@ -37,54 +39,54 @@ namespace BitTorrent // Torrent keys // TODO: Rename it to `id`. -inline const char KEY_TORRENT_ID[] = "hash"; -inline const char KEY_TORRENT_INFOHASHV1[] = "infohash_v1"; -inline const char KEY_TORRENT_INFOHASHV2[] = "infohash_v2"; -inline const char KEY_TORRENT_NAME[] = "name"; -inline const char KEY_TORRENT_MAGNET_URI[] = "magnet_uri"; -inline const char KEY_TORRENT_SIZE[] = "size"; -inline const char KEY_TORRENT_PROGRESS[] = "progress"; -inline const char KEY_TORRENT_DLSPEED[] = "dlspeed"; -inline const char KEY_TORRENT_UPSPEED[] = "upspeed"; -inline const char KEY_TORRENT_QUEUE_POSITION[] = "priority"; -inline const char KEY_TORRENT_SEEDS[] = "num_seeds"; -inline const char KEY_TORRENT_NUM_COMPLETE[] = "num_complete"; -inline const char KEY_TORRENT_LEECHS[] = "num_leechs"; -inline const char KEY_TORRENT_NUM_INCOMPLETE[] = "num_incomplete"; -inline const char KEY_TORRENT_RATIO[] = "ratio"; -inline const char KEY_TORRENT_ETA[] = "eta"; -inline const char KEY_TORRENT_STATE[] = "state"; -inline const char KEY_TORRENT_SEQUENTIAL_DOWNLOAD[] = "seq_dl"; -inline const char KEY_TORRENT_FIRST_LAST_PIECE_PRIO[] = "f_l_piece_prio"; -inline const char KEY_TORRENT_CATEGORY[] = "category"; -inline const char KEY_TORRENT_TAGS[] = "tags"; -inline const char KEY_TORRENT_SUPER_SEEDING[] = "super_seeding"; -inline const char KEY_TORRENT_FORCE_START[] = "force_start"; -inline const char KEY_TORRENT_SAVE_PATH[] = "save_path"; -inline const char KEY_TORRENT_DOWNLOAD_PATH[] = "download_path"; -inline const char KEY_TORRENT_CONTENT_PATH[] = "content_path"; -inline const char KEY_TORRENT_ADDED_ON[] = "added_on"; -inline const char KEY_TORRENT_COMPLETION_ON[] = "completion_on"; -inline const char KEY_TORRENT_TRACKER[] = "tracker"; -inline const char KEY_TORRENT_TRACKERS_COUNT[] = "trackers_count"; -inline const char KEY_TORRENT_DL_LIMIT[] = "dl_limit"; -inline const char KEY_TORRENT_UP_LIMIT[] = "up_limit"; -inline const char KEY_TORRENT_AMOUNT_DOWNLOADED[] = "downloaded"; -inline const char KEY_TORRENT_AMOUNT_UPLOADED[] = "uploaded"; -inline const char KEY_TORRENT_AMOUNT_DOWNLOADED_SESSION[] = "downloaded_session"; -inline const char KEY_TORRENT_AMOUNT_UPLOADED_SESSION[] = "uploaded_session"; -inline const char KEY_TORRENT_AMOUNT_LEFT[] = "amount_left"; -inline const char KEY_TORRENT_AMOUNT_COMPLETED[] = "completed"; -inline const char KEY_TORRENT_MAX_RATIO[] = "max_ratio"; -inline const char KEY_TORRENT_MAX_SEEDING_TIME[] = "max_seeding_time"; -inline const char KEY_TORRENT_RATIO_LIMIT[] = "ratio_limit"; -inline const char KEY_TORRENT_SEEDING_TIME_LIMIT[] = "seeding_time_limit"; -inline const char KEY_TORRENT_LAST_SEEN_COMPLETE_TIME[] = "seen_complete"; -inline const char KEY_TORRENT_LAST_ACTIVITY_TIME[] = "last_activity"; -inline const char KEY_TORRENT_TOTAL_SIZE[] = "total_size"; -inline const char KEY_TORRENT_AUTO_TORRENT_MANAGEMENT[] = "auto_tmm"; -inline const char KEY_TORRENT_TIME_ACTIVE[] = "time_active"; -inline const char KEY_TORRENT_SEEDING_TIME[] = "seeding_time"; -inline const char KEY_TORRENT_AVAILABILITY[] = "availability"; +inline const QString KEY_TORRENT_ID = u"hash"_qs; +inline const QString KEY_TORRENT_INFOHASHV1 = u"infohash_v1"_qs; +inline const QString KEY_TORRENT_INFOHASHV2 = u"infohash_v2"_qs; +inline const QString KEY_TORRENT_NAME = u"name"_qs; +inline const QString KEY_TORRENT_MAGNET_URI = u"magnet_uri"_qs; +inline const QString KEY_TORRENT_SIZE = u"size"_qs; +inline const QString KEY_TORRENT_PROGRESS = u"progress"_qs; +inline const QString KEY_TORRENT_DLSPEED = u"dlspeed"_qs; +inline const QString KEY_TORRENT_UPSPEED = u"upspeed"_qs; +inline const QString KEY_TORRENT_QUEUE_POSITION = u"priority"_qs; +inline const QString KEY_TORRENT_SEEDS = u"num_seeds"_qs; +inline const QString KEY_TORRENT_NUM_COMPLETE = u"num_complete"_qs; +inline const QString KEY_TORRENT_LEECHS = u"num_leechs"_qs; +inline const QString KEY_TORRENT_NUM_INCOMPLETE = u"num_incomplete"_qs; +inline const QString KEY_TORRENT_RATIO = u"ratio"_qs; +inline const QString KEY_TORRENT_ETA = u"eta"_qs; +inline const QString KEY_TORRENT_STATE = u"state"_qs; +inline const QString KEY_TORRENT_SEQUENTIAL_DOWNLOAD = u"seq_dl"_qs; +inline const QString KEY_TORRENT_FIRST_LAST_PIECE_PRIO = u"f_l_piece_prio"_qs; +inline const QString KEY_TORRENT_CATEGORY = u"category"_qs; +inline const QString KEY_TORRENT_TAGS = u"tags"_qs; +inline const QString KEY_TORRENT_SUPER_SEEDING = u"super_seeding"_qs; +inline const QString KEY_TORRENT_FORCE_START = u"force_start"_qs; +inline const QString KEY_TORRENT_SAVE_PATH = u"save_path"_qs; +inline const QString KEY_TORRENT_DOWNLOAD_PATH = u"download_path"_qs; +inline const QString KEY_TORRENT_CONTENT_PATH = u"content_path"_qs; +inline const QString KEY_TORRENT_ADDED_ON = u"added_on"_qs; +inline const QString KEY_TORRENT_COMPLETION_ON = u"completion_on"_qs; +inline const QString KEY_TORRENT_TRACKER = u"tracker"_qs; +inline const QString KEY_TORRENT_TRACKERS_COUNT = u"trackers_count"_qs; +inline const QString KEY_TORRENT_DL_LIMIT = u"dl_limit"_qs; +inline const QString KEY_TORRENT_UP_LIMIT = u"up_limit"_qs; +inline const QString KEY_TORRENT_AMOUNT_DOWNLOADED = u"downloaded"_qs; +inline const QString KEY_TORRENT_AMOUNT_UPLOADED = u"uploaded"_qs; +inline const QString KEY_TORRENT_AMOUNT_DOWNLOADED_SESSION = u"downloaded_session"_qs; +inline const QString KEY_TORRENT_AMOUNT_UPLOADED_SESSION = u"uploaded_session"_qs; +inline const QString KEY_TORRENT_AMOUNT_LEFT = u"amount_left"_qs; +inline const QString KEY_TORRENT_AMOUNT_COMPLETED = u"completed"_qs; +inline const QString KEY_TORRENT_MAX_RATIO = u"max_ratio"_qs; +inline const QString KEY_TORRENT_MAX_SEEDING_TIME = u"max_seeding_time"_qs; +inline const QString KEY_TORRENT_RATIO_LIMIT = u"ratio_limit"_qs; +inline const QString KEY_TORRENT_SEEDING_TIME_LIMIT = u"seeding_time_limit"_qs; +inline const QString KEY_TORRENT_LAST_SEEN_COMPLETE_TIME = u"seen_complete"_qs; +inline const QString KEY_TORRENT_LAST_ACTIVITY_TIME = u"last_activity"_qs; +inline const QString KEY_TORRENT_TOTAL_SIZE = u"total_size"_qs; +inline const QString KEY_TORRENT_AUTO_TORRENT_MANAGEMENT = u"auto_tmm"_qs; +inline const QString KEY_TORRENT_TIME_ACTIVE = u"time_active"_qs; +inline const QString KEY_TORRENT_SEEDING_TIME = u"seeding_time"_qs; +inline const QString KEY_TORRENT_AVAILABILITY = u"availability"_qs; QVariantMap serialize(const BitTorrent::Torrent &torrent); diff --git a/src/webui/api/synccontroller.cpp b/src/webui/api/synccontroller.cpp index 480d15f9a1d..c0c645d8bb6 100644 --- a/src/webui/api/synccontroller.cpp +++ b/src/webui/api/synccontroller.cpp @@ -54,58 +54,58 @@ namespace const int FREEDISKSPACE_CHECK_TIMEOUT = 30000; // Sync main data keys - const char KEY_SYNC_MAINDATA_QUEUEING[] = "queueing"; - const char KEY_SYNC_MAINDATA_REFRESH_INTERVAL[] = "refresh_interval"; - const char KEY_SYNC_MAINDATA_USE_ALT_SPEED_LIMITS[] = "use_alt_speed_limits"; + const QString KEY_SYNC_MAINDATA_QUEUEING = u"queueing"_qs; + const QString KEY_SYNC_MAINDATA_REFRESH_INTERVAL = u"refresh_interval"_qs; + const QString KEY_SYNC_MAINDATA_USE_ALT_SPEED_LIMITS = u"use_alt_speed_limits"_qs; // Sync torrent peers keys - const char KEY_SYNC_TORRENT_PEERS_SHOW_FLAGS[] = "show_flags"; + const QString KEY_SYNC_TORRENT_PEERS_SHOW_FLAGS = u"show_flags"_qs; // Peer keys - const char KEY_PEER_CLIENT[] = "client"; - const char KEY_PEER_CONNECTION_TYPE[] = "connection"; - const char KEY_PEER_COUNTRY[] = "country"; - const char KEY_PEER_COUNTRY_CODE[] = "country_code"; - const char KEY_PEER_DOWN_SPEED[] = "dl_speed"; - const char KEY_PEER_FILES[] = "files"; - const char KEY_PEER_FLAGS[] = "flags"; - const char KEY_PEER_FLAGS_DESCRIPTION[] = "flags_desc"; - const char KEY_PEER_IP[] = "ip"; - const char KEY_PEER_PORT[] = "port"; - const char KEY_PEER_PROGRESS[] = "progress"; - const char KEY_PEER_RELEVANCE[] = "relevance"; - const char KEY_PEER_TOT_DOWN[] = "downloaded"; - const char KEY_PEER_TOT_UP[] = "uploaded"; - const char KEY_PEER_UP_SPEED[] = "up_speed"; + const QString KEY_PEER_CLIENT = u"client"_qs; + const QString KEY_PEER_CONNECTION_TYPE = u"connection"_qs; + const QString KEY_PEER_COUNTRY = u"country"_qs; + const QString KEY_PEER_COUNTRY_CODE = u"country_code"_qs; + const QString KEY_PEER_DOWN_SPEED = u"dl_speed"_qs; + const QString KEY_PEER_FILES = u"files"_qs; + const QString KEY_PEER_FLAGS = u"flags"_qs; + const QString KEY_PEER_FLAGS_DESCRIPTION = u"flags_desc"_qs; + const QString KEY_PEER_IP = u"ip"_qs; + const QString KEY_PEER_PORT = u"port"_qs; + const QString KEY_PEER_PROGRESS = u"progress"_qs; + const QString KEY_PEER_RELEVANCE = u"relevance"_qs; + const QString KEY_PEER_TOT_DOWN = u"downloaded"_qs; + const QString KEY_PEER_TOT_UP = u"uploaded"_qs; + const QString KEY_PEER_UP_SPEED = u"up_speed"_qs; // TransferInfo keys - const char KEY_TRANSFER_CONNECTION_STATUS[] = "connection_status"; - const char KEY_TRANSFER_DHT_NODES[] = "dht_nodes"; - const char KEY_TRANSFER_DLDATA[] = "dl_info_data"; - const char KEY_TRANSFER_DLRATELIMIT[] = "dl_rate_limit"; - const char KEY_TRANSFER_DLSPEED[] = "dl_info_speed"; - const char KEY_TRANSFER_FREESPACEONDISK[] = "free_space_on_disk"; - const char KEY_TRANSFER_UPDATA[] = "up_info_data"; - const char KEY_TRANSFER_UPRATELIMIT[] = "up_rate_limit"; - const char KEY_TRANSFER_UPSPEED[] = "up_info_speed"; + const QString KEY_TRANSFER_CONNECTION_STATUS = u"connection_status"_qs; + const QString KEY_TRANSFER_DHT_NODES = u"dht_nodes"_qs; + const QString KEY_TRANSFER_DLDATA = u"dl_info_data"_qs; + const QString KEY_TRANSFER_DLRATELIMIT = u"dl_rate_limit"_qs; + const QString KEY_TRANSFER_DLSPEED = u"dl_info_speed"_qs; + const QString KEY_TRANSFER_FREESPACEONDISK = u"free_space_on_disk"_qs; + const QString KEY_TRANSFER_UPDATA = u"up_info_data"_qs; + const QString KEY_TRANSFER_UPRATELIMIT = u"up_rate_limit"_qs; + const QString KEY_TRANSFER_UPSPEED = u"up_info_speed"_qs; // Statistics keys - const char KEY_TRANSFER_ALLTIME_DL[] = "alltime_dl"; - const char KEY_TRANSFER_ALLTIME_UL[] = "alltime_ul"; - const char KEY_TRANSFER_AVERAGE_TIME_QUEUE[] = "average_time_queue"; - const char KEY_TRANSFER_GLOBAL_RATIO[] = "global_ratio"; - const char KEY_TRANSFER_QUEUED_IO_JOBS[] = "queued_io_jobs"; - const char KEY_TRANSFER_READ_CACHE_HITS[] = "read_cache_hits"; - const char KEY_TRANSFER_READ_CACHE_OVERLOAD[] = "read_cache_overload"; - const char KEY_TRANSFER_TOTAL_BUFFERS_SIZE[] = "total_buffers_size"; - const char KEY_TRANSFER_TOTAL_PEER_CONNECTIONS[] = "total_peer_connections"; - const char KEY_TRANSFER_TOTAL_QUEUED_SIZE[] = "total_queued_size"; - const char KEY_TRANSFER_TOTAL_WASTE_SESSION[] = "total_wasted_session"; - const char KEY_TRANSFER_WRITE_CACHE_OVERLOAD[] = "write_cache_overload"; - - const char KEY_FULL_UPDATE[] = "full_update"; - const char KEY_RESPONSE_ID[] = "rid"; - const char KEY_SUFFIX_REMOVED[] = "_removed"; + const QString KEY_TRANSFER_ALLTIME_DL = u"alltime_dl"_qs; + const QString KEY_TRANSFER_ALLTIME_UL = u"alltime_ul"_qs; + const QString KEY_TRANSFER_AVERAGE_TIME_QUEUE = u"average_time_queue"_qs; + const QString KEY_TRANSFER_GLOBAL_RATIO = u"global_ratio"_qs; + const QString KEY_TRANSFER_QUEUED_IO_JOBS = u"queued_io_jobs"_qs; + const QString KEY_TRANSFER_READ_CACHE_HITS = u"read_cache_hits"_qs; + const QString KEY_TRANSFER_READ_CACHE_OVERLOAD = u"read_cache_overload"_qs; + const QString KEY_TRANSFER_TOTAL_BUFFERS_SIZE = u"total_buffers_size"_qs; + const QString KEY_TRANSFER_TOTAL_PEER_CONNECTIONS = u"total_peer_connections"_qs; + const QString KEY_TRANSFER_TOTAL_QUEUED_SIZE = u"total_queued_size"_qs; + const QString KEY_TRANSFER_TOTAL_WASTE_SESSION = u"total_wasted_session"_qs; + const QString KEY_TRANSFER_WRITE_CACHE_OVERLOAD = u"write_cache_overload"_qs; + + const QString KEY_FULL_UPDATE = u"full_update"_qs; + const QString KEY_RESPONSE_ID = u"rid"_qs; + const QString KEY_SUFFIX_REMOVED = u"_removed"_qs; void processMap(const QVariantMap &prevData, const QVariantMap &data, QVariantMap &syncData); void processHash(QVariantHash prevData, const QVariantHash &data, QVariantMap &syncData, QVariantList &removedItems); @@ -131,11 +131,11 @@ namespace map[KEY_TRANSFER_ALLTIME_DL] = atd; map[KEY_TRANSFER_ALLTIME_UL] = atu; map[KEY_TRANSFER_TOTAL_WASTE_SESSION] = sessionStatus.totalWasted; - map[KEY_TRANSFER_GLOBAL_RATIO] = ((atd > 0) && (atu > 0)) ? Utils::String::fromDouble(static_cast(atu) / atd, 2) : "-"; + map[KEY_TRANSFER_GLOBAL_RATIO] = ((atd > 0) && (atu > 0)) ? Utils::String::fromDouble(static_cast(atu) / atd, 2) : u"-"_qs; map[KEY_TRANSFER_TOTAL_PEER_CONNECTIONS] = sessionStatus.peersCount; const qreal readRatio = cacheStatus.readRatio; // TODO: remove when LIBTORRENT_VERSION_NUM >= 20000 - map[KEY_TRANSFER_READ_CACHE_HITS] = (readRatio > 0) ? Utils::String::fromDouble(100 * readRatio, 2) : "0"; + map[KEY_TRANSFER_READ_CACHE_HITS] = (readRatio > 0) ? Utils::String::fromDouble(100 * readRatio, 2) : u"0"_qs; map[KEY_TRANSFER_TOTAL_BUFFERS_SIZE] = cacheStatus.totalUsedBuffers * 16 * 1024; map[KEY_TRANSFER_WRITE_CACHE_OVERLOAD] = ((sessionStatus.diskWriteQueue > 0) && (sessionStatus.peersCount > 0)) @@ -151,8 +151,8 @@ namespace map[KEY_TRANSFER_DHT_NODES] = sessionStatus.dhtNodes; map[KEY_TRANSFER_CONNECTION_STATUS] = session->isListening() - ? (sessionStatus.hasIncomingConnections ? "connected" : "firewalled") - : "disconnected"; + ? (sessionStatus.hasIncomingConnections ? u"connected"_qs : u"firewalled"_qs) + : u"disconnected"_qs; return map; } @@ -470,7 +470,7 @@ void SyncController::maindataAction() // Calculated last activity time can differ from actual value by up to 10 seconds (this is a libtorrent issue). // So we don't need unnecessary updates of last activity time in response. - const auto iterTorrents = lastResponse.find("torrents"); + const auto iterTorrents = lastResponse.find(u"torrents"_qs); if (iterTorrents != lastResponse.end()) { const QVariantHash lastResponseTorrents = iterTorrents->toHash(); @@ -495,7 +495,7 @@ void SyncController::maindataAction() torrents[torrentID.toString()] = map; } - data["torrents"] = torrents; + data[u"torrents"_qs] = torrents; QVariantHash categories; const QStringList categoriesList = session->categories(); @@ -508,28 +508,28 @@ void SyncController::maindataAction() category.insert(QLatin1String("name"), categoryName); categories[categoryName] = category.toVariantMap(); } - data["categories"] = categories; + data[u"categories"_qs] = categories; QVariantList tags; for (const QString &tag : asConst(session->tags())) tags << tag; - data["tags"] = tags; + data[u"tags"_qs] = tags; QVariantHash trackersHash; for (auto i = trackers.constBegin(); i != trackers.constEnd(); ++i) { trackersHash[i.key()] = i.value(); } - data["trackers"] = trackersHash; + data[u"trackers"_qs] = trackersHash; QVariantMap serverState = getTransferInfo(); serverState[KEY_TRANSFER_FREESPACEONDISK] = getFreeDiskSpace(); serverState[KEY_SYNC_MAINDATA_QUEUEING] = session->isQueueingSystemEnabled(); serverState[KEY_SYNC_MAINDATA_USE_ALT_SPEED_LIMITS] = session->isAltGlobalSpeedLimitEnabled(); serverState[KEY_SYNC_MAINDATA_REFRESH_INTERVAL] = session->refreshInterval(); - data["server_state"] = serverState; + data[u"server_state"_qs] = serverState; - const int acceptedResponseId {params()["rid"].toInt()}; + const int acceptedResponseId {params()[u"rid"_qs].toInt()}; setResult(QJsonObject::fromVariantMap(generateSyncData(acceptedResponseId, data, lastAcceptedResponse, lastResponse))); sessionManager()->session()->setData(QLatin1String("syncMainDataLastResponse"), lastResponse); @@ -544,7 +544,7 @@ void SyncController::torrentPeersAction() auto lastResponse = sessionManager()->session()->getData(QLatin1String("syncTorrentPeersLastResponse")).toMap(); auto lastAcceptedResponse = sessionManager()->session()->getData(QLatin1String("syncTorrentPeersLastAcceptedResponse")).toMap(); - const auto id = BitTorrent::TorrentID::fromString(params()["hash"]); + const auto id = BitTorrent::TorrentID::fromString(params()[u"hash"_qs]); const BitTorrent::Torrent *torrent = BitTorrent::Session::instance()->findTorrent(id); if (!torrent) throw APIError(APIErrorType::NotFound); @@ -596,9 +596,9 @@ void SyncController::torrentPeersAction() peers[pi.address().toString()] = peer; } - data["peers"] = peers; + data[u"peers"_qs] = peers; - const int acceptedResponseId {params()["rid"].toInt()}; + const int acceptedResponseId {params()[u"rid"_qs].toInt()}; setResult(QJsonObject::fromVariantMap(generateSyncData(acceptedResponseId, data, lastAcceptedResponse, lastResponse))); sessionManager()->session()->setData(QLatin1String("syncTorrentPeersLastResponse"), lastResponse); diff --git a/src/webui/api/torrentscontroller.cpp b/src/webui/api/torrentscontroller.cpp index 267623b0307..7d6cb2165d7 100644 --- a/src/webui/api/torrentscontroller.cpp +++ b/src/webui/api/torrentscontroller.cpp @@ -57,63 +57,63 @@ #include "serialize/serialize_torrent.h" // Tracker keys -const char KEY_TRACKER_URL[] = "url"; -const char KEY_TRACKER_STATUS[] = "status"; -const char KEY_TRACKER_TIER[] = "tier"; -const char KEY_TRACKER_MSG[] = "msg"; -const char KEY_TRACKER_PEERS_COUNT[] = "num_peers"; -const char KEY_TRACKER_SEEDS_COUNT[] = "num_seeds"; -const char KEY_TRACKER_LEECHES_COUNT[] = "num_leeches"; -const char KEY_TRACKER_DOWNLOADED_COUNT[] = "num_downloaded"; +const QString KEY_TRACKER_URL = u"url"_qs; +const QString KEY_TRACKER_STATUS = u"status"_qs; +const QString KEY_TRACKER_TIER = u"tier"_qs; +const QString KEY_TRACKER_MSG = u"msg"_qs; +const QString KEY_TRACKER_PEERS_COUNT = u"num_peers"_qs; +const QString KEY_TRACKER_SEEDS_COUNT = u"num_seeds"_qs; +const QString KEY_TRACKER_LEECHES_COUNT = u"num_leeches"_qs; +const QString KEY_TRACKER_DOWNLOADED_COUNT = u"num_downloaded"_qs; // Web seed keys -const char KEY_WEBSEED_URL[] = "url"; +const QString KEY_WEBSEED_URL = u"url"_qs; // Torrent keys (Properties) -const char KEY_PROP_TIME_ELAPSED[] = "time_elapsed"; -const char KEY_PROP_SEEDING_TIME[] = "seeding_time"; -const char KEY_PROP_ETA[] = "eta"; -const char KEY_PROP_CONNECT_COUNT[] = "nb_connections"; -const char KEY_PROP_CONNECT_COUNT_LIMIT[] = "nb_connections_limit"; -const char KEY_PROP_DOWNLOADED[] = "total_downloaded"; -const char KEY_PROP_DOWNLOADED_SESSION[] = "total_downloaded_session"; -const char KEY_PROP_UPLOADED[] = "total_uploaded"; -const char KEY_PROP_UPLOADED_SESSION[] = "total_uploaded_session"; -const char KEY_PROP_DL_SPEED[] = "dl_speed"; -const char KEY_PROP_DL_SPEED_AVG[] = "dl_speed_avg"; -const char KEY_PROP_UP_SPEED[] = "up_speed"; -const char KEY_PROP_UP_SPEED_AVG[] = "up_speed_avg"; -const char KEY_PROP_DL_LIMIT[] = "dl_limit"; -const char KEY_PROP_UP_LIMIT[] = "up_limit"; -const char KEY_PROP_WASTED[] = "total_wasted"; -const char KEY_PROP_SEEDS[] = "seeds"; -const char KEY_PROP_SEEDS_TOTAL[] = "seeds_total"; -const char KEY_PROP_PEERS[] = "peers"; -const char KEY_PROP_PEERS_TOTAL[] = "peers_total"; -const char KEY_PROP_RATIO[] = "share_ratio"; -const char KEY_PROP_REANNOUNCE[] = "reannounce"; -const char KEY_PROP_TOTAL_SIZE[] = "total_size"; -const char KEY_PROP_PIECES_NUM[] = "pieces_num"; -const char KEY_PROP_PIECE_SIZE[] = "piece_size"; -const char KEY_PROP_PIECES_HAVE[] = "pieces_have"; -const char KEY_PROP_CREATED_BY[] = "created_by"; -const char KEY_PROP_LAST_SEEN[] = "last_seen"; -const char KEY_PROP_ADDITION_DATE[] = "addition_date"; -const char KEY_PROP_COMPLETION_DATE[] = "completion_date"; -const char KEY_PROP_CREATION_DATE[] = "creation_date"; -const char KEY_PROP_SAVE_PATH[] = "save_path"; -const char KEY_PROP_DOWNLOAD_PATH[] = "download_path"; -const char KEY_PROP_COMMENT[] = "comment"; +const QString KEY_PROP_TIME_ELAPSED = u"time_elapsed"_qs; +const QString KEY_PROP_SEEDING_TIME = u"seeding_time"_qs; +const QString KEY_PROP_ETA = u"eta"_qs; +const QString KEY_PROP_CONNECT_COUNT = u"nb_connections"_qs; +const QString KEY_PROP_CONNECT_COUNT_LIMIT = u"nb_connections_limit"_qs; +const QString KEY_PROP_DOWNLOADED = u"total_downloaded"_qs; +const QString KEY_PROP_DOWNLOADED_SESSION = u"total_downloaded_session"_qs; +const QString KEY_PROP_UPLOADED = u"total_uploaded"_qs; +const QString KEY_PROP_UPLOADED_SESSION = u"total_uploaded_session"_qs; +const QString KEY_PROP_DL_SPEED = u"dl_speed"_qs; +const QString KEY_PROP_DL_SPEED_AVG = u"dl_speed_avg"_qs; +const QString KEY_PROP_UP_SPEED = u"up_speed"_qs; +const QString KEY_PROP_UP_SPEED_AVG = u"up_speed_avg"_qs; +const QString KEY_PROP_DL_LIMIT = u"dl_limit"_qs; +const QString KEY_PROP_UP_LIMIT = u"up_limit"_qs; +const QString KEY_PROP_WASTED = u"total_wasted"_qs; +const QString KEY_PROP_SEEDS = u"seeds"_qs; +const QString KEY_PROP_SEEDS_TOTAL = u"seeds_total"_qs; +const QString KEY_PROP_PEERS = u"peers"_qs; +const QString KEY_PROP_PEERS_TOTAL = u"peers_total"_qs; +const QString KEY_PROP_RATIO = u"share_ratio"_qs; +const QString KEY_PROP_REANNOUNCE = u"reannounce"_qs; +const QString KEY_PROP_TOTAL_SIZE = u"total_size"_qs; +const QString KEY_PROP_PIECES_NUM = u"pieces_num"_qs; +const QString KEY_PROP_PIECE_SIZE = u"piece_size"_qs; +const QString KEY_PROP_PIECES_HAVE = u"pieces_have"_qs; +const QString KEY_PROP_CREATED_BY = u"created_by"_qs; +const QString KEY_PROP_LAST_SEEN = u"last_seen"_qs; +const QString KEY_PROP_ADDITION_DATE = u"addition_date"_qs; +const QString KEY_PROP_COMPLETION_DATE = u"completion_date"_qs; +const QString KEY_PROP_CREATION_DATE = u"creation_date"_qs; +const QString KEY_PROP_SAVE_PATH = u"save_path"_qs; +const QString KEY_PROP_DOWNLOAD_PATH = u"download_path"_qs; +const QString KEY_PROP_COMMENT = u"comment"_qs; // File keys -const char KEY_FILE_INDEX[] = "index"; -const char KEY_FILE_NAME[] = "name"; -const char KEY_FILE_SIZE[] = "size"; -const char KEY_FILE_PROGRESS[] = "progress"; -const char KEY_FILE_PRIORITY[] = "priority"; -const char KEY_FILE_IS_SEED[] = "is_seed"; -const char KEY_FILE_PIECE_RANGE[] = "piece_range"; -const char KEY_FILE_AVAILABILITY[] = "availability"; +const QString KEY_FILE_INDEX = u"index"_qs; +const QString KEY_FILE_NAME = u"name"_qs; +const QString KEY_FILE_SIZE = u"size"_qs; +const QString KEY_FILE_PROGRESS = u"progress"_qs; +const QString KEY_FILE_PRIORITY = u"priority"_qs; +const QString KEY_FILE_IS_SEED = u"is_seed"_qs; +const QString KEY_FILE_PIECE_RANGE = u"piece_range"_qs; +const QString KEY_FILE_AVAILABILITY = u"availability"_qs; namespace { @@ -184,9 +184,9 @@ namespace const QJsonObject dht { - {KEY_TRACKER_URL, "** [DHT] **"}, + {KEY_TRACKER_URL, u"** [DHT] **"_qs}, {KEY_TRACKER_TIER, -1}, - {KEY_TRACKER_MSG, (isTorrentPrivate ? privateMsg : "")}, + {KEY_TRACKER_MSG, (isTorrentPrivate ? privateMsg : u""_qs)}, {KEY_TRACKER_STATUS, ((BitTorrent::Session::instance()->isDHTEnabled() && !isTorrentPrivate) ? working : disabled)}, {KEY_TRACKER_PEERS_COUNT, 0}, {KEY_TRACKER_DOWNLOADED_COUNT, 0}, @@ -196,9 +196,9 @@ namespace const QJsonObject pex { - {KEY_TRACKER_URL, "** [PeX] **"}, + {KEY_TRACKER_URL, u"** [PeX] **"_qs}, {KEY_TRACKER_TIER, -1}, - {KEY_TRACKER_MSG, (isTorrentPrivate ? privateMsg : "")}, + {KEY_TRACKER_MSG, (isTorrentPrivate ? privateMsg : u""_qs)}, {KEY_TRACKER_STATUS, ((BitTorrent::Session::instance()->isPeXEnabled() && !isTorrentPrivate) ? working : disabled)}, {KEY_TRACKER_PEERS_COUNT, 0}, {KEY_TRACKER_DOWNLOADED_COUNT, 0}, @@ -208,9 +208,9 @@ namespace const QJsonObject lsd { - {KEY_TRACKER_URL, "** [LSD] **"}, + {KEY_TRACKER_URL, u"** [LSD] **"_qs}, {KEY_TRACKER_TIER, -1}, - {KEY_TRACKER_MSG, (isTorrentPrivate ? privateMsg : "")}, + {KEY_TRACKER_MSG, (isTorrentPrivate ? privateMsg : u""_qs)}, {KEY_TRACKER_STATUS, ((BitTorrent::Session::instance()->isLSDEnabled() && !isTorrentPrivate) ? working : disabled)}, {KEY_TRACKER_PEERS_COUNT, 0}, {KEY_TRACKER_DOWNLOADED_COUNT, 0}, @@ -263,14 +263,14 @@ namespace // - offset (int): set offset (if less than 0 - offset from end) void TorrentsController::infoAction() { - const QString filter {params()["filter"]}; + const QString filter {params()[u"filter"_qs]}; const std::optional category = getOptionalString(params(), QLatin1String("category")); const std::optional tag = getOptionalString(params(), QLatin1String("tag")); - const QString sortedColumn {params()["sort"]}; - const bool reverse {parseBool(params()["reverse"]).value_or(false)}; - int limit {params()["limit"].toInt()}; - int offset {params()["offset"].toInt()}; - const QStringList hashes {params()["hashes"].split('|', Qt::SkipEmptyParts)}; + const QString sortedColumn {params()[u"sort"_qs]}; + const bool reverse {parseBool(params()[u"reverse"_qs]).value_or(false)}; + int limit {params()[u"limit"_qs].toInt()}; + int offset {params()[u"offset"_qs].toInt()}; + const QStringList hashes {params()[u"hashes"_qs].split(u'|', Qt::SkipEmptyParts)}; std::optional idSet; if (!hashes.isEmpty()) @@ -389,9 +389,9 @@ void TorrentsController::infoAction() // - "comment": Torrent comment void TorrentsController::propertiesAction() { - requireParams({"hash"}); + requireParams({u"hash"_qs}); - const auto id = BitTorrent::TorrentID::fromString(params()["hash"]); + const auto id = BitTorrent::TorrentID::fromString(params()[u"hash"_qs]); BitTorrent::Torrent *const torrent = BitTorrent::Session::instance()->findTorrent(id); if (!torrent) throw APIError(APIErrorType::NotFound); @@ -463,9 +463,9 @@ void TorrentsController::propertiesAction() // - "msg": Tracker message (last) void TorrentsController::trackersAction() { - requireParams({"hash"}); + requireParams({u"hash"_qs}); - const auto id = BitTorrent::TorrentID::fromString(params()["hash"]); + const auto id = BitTorrent::TorrentID::fromString(params()[u"hash"_qs]); const BitTorrent::Torrent *const torrent = BitTorrent::Session::instance()->findTorrent(id); if (!torrent) throw APIError(APIErrorType::NotFound); @@ -496,9 +496,9 @@ void TorrentsController::trackersAction() // - "url": Web seed URL void TorrentsController::webseedsAction() { - requireParams({"hash"}); + requireParams({u"hash"_qs}); - const auto id = BitTorrent::TorrentID::fromString(params()["hash"]); + const auto id = BitTorrent::TorrentID::fromString(params()[u"hash"_qs]); BitTorrent::Torrent *const torrent = BitTorrent::Session::instance()->findTorrent(id); if (!torrent) throw APIError(APIErrorType::NotFound); @@ -528,9 +528,9 @@ void TorrentsController::webseedsAction() // and the second number is the ending piece index (inclusive) void TorrentsController::filesAction() { - requireParams({"hash"}); + requireParams({u"hash"_qs}); - const auto id = BitTorrent::TorrentID::fromString(params()["hash"]); + const auto id = BitTorrent::TorrentID::fromString(params()[u"hash"_qs]); const BitTorrent::Torrent *const torrent = BitTorrent::Session::instance()->findTorrent(id); if (!torrent) throw APIError(APIErrorType::NotFound); @@ -540,7 +540,7 @@ void TorrentsController::filesAction() const auto idxIt = params().constFind(QLatin1String("indexes")); if (idxIt != params().cend()) { - const QStringList indexStrings = idxIt.value().split('|'); + const QStringList indexStrings = idxIt.value().split(u'|'); fileIndexes.reserve(indexStrings.size()); std::transform(indexStrings.cbegin(), indexStrings.cend(), std::back_inserter(fileIndexes) , [&filesCount](const QString &indexString) -> int @@ -597,9 +597,9 @@ void TorrentsController::filesAction() // The return value is a JSON-formatted array of strings (hex strings). void TorrentsController::pieceHashesAction() { - requireParams({"hash"}); + requireParams({u"hash"_qs}); - const auto id = BitTorrent::TorrentID::fromString(params()["hash"]); + const auto id = BitTorrent::TorrentID::fromString(params()[u"hash"_qs]); BitTorrent::Torrent *const torrent = BitTorrent::Session::instance()->findTorrent(id); if (!torrent) throw APIError(APIErrorType::NotFound); @@ -609,7 +609,7 @@ void TorrentsController::pieceHashesAction() { const QVector hashes = torrent->info().pieceHashes(); for (const QByteArray &hash : hashes) - pieceHashes.append(QString(hash.toHex())); + pieceHashes.append(QString::fromLatin1(hash.toHex())); } setResult(pieceHashes); @@ -622,9 +622,9 @@ void TorrentsController::pieceHashesAction() // 2: piece already downloaded void TorrentsController::pieceStatesAction() { - requireParams({"hash"}); + requireParams({u"hash"_qs}); - const auto id = BitTorrent::TorrentID::fromString(params()["hash"]); + const auto id = BitTorrent::TorrentID::fromString(params()[u"hash"_qs]); BitTorrent::Torrent *const torrent = BitTorrent::Session::instance()->findTorrent(id); if (!torrent) throw APIError(APIErrorType::NotFound); @@ -646,26 +646,26 @@ void TorrentsController::pieceStatesAction() void TorrentsController::addAction() { - const QString urls = params()["urls"]; - const QString cookie = params()["cookie"]; - - const bool skipChecking = parseBool(params()["skip_checking"]).value_or(false); - const bool seqDownload = parseBool(params()["sequentialDownload"]).value_or(false); - const bool firstLastPiece = parseBool(params()["firstLastPiecePrio"]).value_or(false); - const std::optional addPaused = parseBool(params()["paused"]); - const QString savepath = params()["savepath"].trimmed(); - const QString downloadPath = params()["downloadPath"].trimmed(); - const std::optional useDownloadPath = parseBool(params()["useDownloadPath"]); - const QString category = params()["category"]; - const QStringList tags = params()["tags"].split(',', Qt::SkipEmptyParts); - const QString torrentName = params()["rename"].trimmed(); - const int upLimit = parseInt(params()["upLimit"]).value_or(-1); - const int dlLimit = parseInt(params()["dlLimit"]).value_or(-1); - const double ratioLimit = parseDouble(params()["ratioLimit"]).value_or(BitTorrent::Torrent::USE_GLOBAL_RATIO); - const int seedingTimeLimit = parseInt(params()["seedingTimeLimit"]).value_or(BitTorrent::Torrent::USE_GLOBAL_SEEDING_TIME); - const std::optional autoTMM = parseBool(params()["autoTMM"]); - - const QString contentLayoutParam = params()["contentLayout"]; + const QString urls = params()[u"urls"_qs]; + const QString cookie = params()[u"cookie"_qs]; + + const bool skipChecking = parseBool(params()[u"skip_checking"_qs]).value_or(false); + const bool seqDownload = parseBool(params()[u"sequentialDownload"_qs]).value_or(false); + const bool firstLastPiece = parseBool(params()[u"firstLastPiecePrio"_qs]).value_or(false); + const std::optional addPaused = parseBool(params()[u"paused"_qs]); + const QString savepath = params()[u"savepath"_qs].trimmed(); + const QString downloadPath = params()[u"downloadPath"_qs].trimmed(); + const std::optional useDownloadPath = parseBool(params()[u"useDownloadPath"_qs]); + const QString category = params()[u"category"_qs]; + const QStringList tags = params()[u"tags"_qs].split(u',', Qt::SkipEmptyParts); + const QString torrentName = params()[u"rename"_qs].trimmed(); + const int upLimit = parseInt(params()[u"upLimit"_qs]).value_or(-1); + const int dlLimit = parseInt(params()[u"dlLimit"_qs]).value_or(-1); + const double ratioLimit = parseDouble(params()[u"ratioLimit"_qs]).value_or(BitTorrent::Torrent::USE_GLOBAL_RATIO); + const int seedingTimeLimit = parseInt(params()[u"seedingTimeLimit"_qs]).value_or(BitTorrent::Torrent::USE_GLOBAL_SEEDING_TIME); + const std::optional autoTMM = parseBool(params()[u"autoTMM"_qs]); + + const QString contentLayoutParam = params()[u"contentLayout"_qs]; const std::optional contentLayout = (!contentLayoutParam.isEmpty() ? Utils::String::toEnum(contentLayoutParam, BitTorrent::TorrentContentLayout::Original) : std::optional {}); @@ -673,11 +673,11 @@ void TorrentsController::addAction() QList cookies; if (!cookie.isEmpty()) { - const QStringList cookiesStr = cookie.split("; "); + const QStringList cookiesStr = cookie.split(u"; "_qs); for (QString cookieStr : cookiesStr) { cookieStr = cookieStr.trimmed(); - int index = cookieStr.indexOf('='); + int index = cookieStr.indexOf(u'='); if (index > 1) { QByteArray name = cookieStr.left(index).toLatin1(); @@ -707,7 +707,7 @@ void TorrentsController::addAction() addTorrentParams.useAutoTMM = autoTMM; bool partialSuccess = false; - for (QString url : asConst(urls.split('\n'))) + for (QString url : asConst(urls.split(u'\n'))) { url = url.trimmed(); if (!url.isEmpty()) @@ -737,15 +737,15 @@ void TorrentsController::addAction() void TorrentsController::addTrackersAction() { - requireParams({"hash", "urls"}); + requireParams({u"hash"_qs, u"urls"_qs}); - const auto id = BitTorrent::TorrentID::fromString(params()["hash"]); + const auto id = BitTorrent::TorrentID::fromString(params()[u"hash"_qs]); BitTorrent::Torrent *const torrent = BitTorrent::Session::instance()->findTorrent(id); if (!torrent) throw APIError(APIErrorType::NotFound); QVector trackers; - for (const QString &urlStr : asConst(params()["urls"].split('\n'))) + for (const QString &urlStr : asConst(params()[u"urls"_qs].split(u'\n'))) { const QUrl url {urlStr.trimmed()}; if (url.isValid()) @@ -756,11 +756,11 @@ void TorrentsController::addTrackersAction() void TorrentsController::editTrackerAction() { - requireParams({"hash", "origUrl", "newUrl"}); + requireParams({u"hash"_qs, u"origUrl"_qs, u"newUrl"_qs}); - const auto id = BitTorrent::TorrentID::fromString(params()["hash"]); - const QString origUrl = params()["origUrl"]; - const QString newUrl = params()["newUrl"]; + const auto id = BitTorrent::TorrentID::fromString(params()[u"hash"_qs]); + const QString origUrl = params()[u"origUrl"_qs]; + const QString newUrl = params()[u"newUrl"_qs]; BitTorrent::Torrent *const torrent = BitTorrent::Session::instance()->findTorrent(id); if (!torrent) @@ -771,7 +771,7 @@ void TorrentsController::editTrackerAction() if (origTrackerUrl == newTrackerUrl) return; if (!newTrackerUrl.isValid()) - throw APIError(APIErrorType::BadParams, "New tracker URL is invalid"); + throw APIError(APIErrorType::BadParams, u"New tracker URL is invalid"_qs); QVector trackers = torrent->trackers(); bool match = false; @@ -779,7 +779,7 @@ void TorrentsController::editTrackerAction() { const QUrl trackerUrl(tracker.url); if (trackerUrl == newTrackerUrl) - throw APIError(APIErrorType::Conflict, "New tracker URL already exists"); + throw APIError(APIErrorType::Conflict, u"New tracker URL already exists"_qs); if (trackerUrl == origTrackerUrl) { match = true; @@ -787,7 +787,7 @@ void TorrentsController::editTrackerAction() } } if (!match) - throw APIError(APIErrorType::Conflict, "Tracker not found"); + throw APIError(APIErrorType::Conflict, u"Tracker not found"_qs); torrent->replaceTrackers(trackers); @@ -797,14 +797,14 @@ void TorrentsController::editTrackerAction() void TorrentsController::removeTrackersAction() { - requireParams({"hash", "urls"}); + requireParams({u"hash"_qs, u"urls"_qs}); - const auto id = BitTorrent::TorrentID::fromString(params()["hash"]); + const auto id = BitTorrent::TorrentID::fromString(params()[u"hash"_qs]); BitTorrent::Torrent *const torrent = BitTorrent::Session::instance()->findTorrent(id); if (!torrent) throw APIError(APIErrorType::NotFound); - const QStringList urls = params()["urls"].split('|'); + const QStringList urls = params()[u"urls"_qs].split(u'|'); const QVector trackers = torrent->trackers(); QVector remainingTrackers; @@ -816,7 +816,7 @@ void TorrentsController::removeTrackersAction() } if (remainingTrackers.size() == trackers.size()) - throw APIError(APIErrorType::Conflict, "No trackers were removed"); + throw APIError(APIErrorType::Conflict, u"No trackers were removed"_qs); torrent->replaceTrackers(remainingTrackers); @@ -826,10 +826,10 @@ void TorrentsController::removeTrackersAction() void TorrentsController::addPeersAction() { - requireParams({"hashes", "peers"}); + requireParams({u"hashes"_qs, u"peers"_qs}); - const QStringList hashes = params()["hashes"].split('|'); - const QStringList peers = params()["peers"].split('|'); + const QStringList hashes = params()[u"hashes"_qs].split(u'|'); + const QStringList peers = params()[u"peers"_qs].split(u'|'); QVector peerList; peerList.reserve(peers.size()); @@ -841,7 +841,7 @@ void TorrentsController::addPeersAction() } if (peerList.isEmpty()) - throw APIError(APIErrorType::BadParams, "No valid peers were specified"); + throw APIError(APIErrorType::BadParams, u"No valid peers were specified"_qs); QJsonObject results; @@ -854,8 +854,8 @@ void TorrentsController::addPeersAction() results[torrent->id().toString()] = QJsonObject { - {"added", peersAdded}, - {"failed", (peers.size() - peersAdded)} + {u"added"_qs, peersAdded}, + {u"failed"_qs, (peers.size() - peersAdded)} }; }); @@ -864,27 +864,27 @@ void TorrentsController::addPeersAction() void TorrentsController::pauseAction() { - requireParams({"hashes"}); + requireParams({u"hashes"_qs}); - const QStringList hashes = params()["hashes"].split('|'); + const QStringList hashes = params()[u"hashes"_qs].split(u'|'); applyToTorrents(hashes, [](BitTorrent::Torrent *const torrent) { torrent->pause(); }); } void TorrentsController::resumeAction() { - requireParams({"hashes"}); + requireParams({u"hashes"_qs}); - const QStringList idStrings = params()["hashes"].split('|'); + const QStringList idStrings = params()[u"hashes"_qs].split(u'|'); applyToTorrents(idStrings, [](BitTorrent::Torrent *const torrent) { torrent->resume(); }); } void TorrentsController::filePrioAction() { - requireParams({"hash", "id", "priority"}); + requireParams({u"hash"_qs, u"id"_qs, u"priority"_qs}); - const auto id = BitTorrent::TorrentID::fromString(params()["hash"]); + const auto id = BitTorrent::TorrentID::fromString(params()[u"hash"_qs]); bool ok = false; - const auto priority = static_cast(params()["priority"].toInt(&ok)); + const auto priority = static_cast(params()[u"priority"_qs].toInt(&ok)); if (!ok) throw APIError(APIErrorType::BadParams, tr("Priority must be an integer")); @@ -900,7 +900,7 @@ void TorrentsController::filePrioAction() const int filesCount = torrent->filesCount(); QVector priorities = torrent->filePriorities(); bool priorityChanged = false; - for (const QString &fileID : params()["id"].split('|')) + for (const QString &fileID : params()[u"id"_qs].split(u'|')) { const int id = fileID.toInt(&ok); if (!ok) @@ -921,9 +921,9 @@ void TorrentsController::filePrioAction() void TorrentsController::uploadLimitAction() { - requireParams({"hashes"}); + requireParams({u"hashes"_qs}); - const QStringList idList {params()["hashes"].split('|')}; + const QStringList idList {params()[u"hashes"_qs].split(u'|')}; QJsonObject map; for (const QString &id : idList) { @@ -939,9 +939,9 @@ void TorrentsController::uploadLimitAction() void TorrentsController::downloadLimitAction() { - requireParams({"hashes"}); + requireParams({u"hashes"_qs}); - const QStringList idList {params()["hashes"].split('|')}; + const QStringList idList {params()[u"hashes"_qs].split(u'|')}; QJsonObject map; for (const QString &id : idList) { @@ -957,35 +957,35 @@ void TorrentsController::downloadLimitAction() void TorrentsController::setUploadLimitAction() { - requireParams({"hashes", "limit"}); + requireParams({u"hashes"_qs, u"limit"_qs}); - qlonglong limit = params()["limit"].toLongLong(); + qlonglong limit = params()[u"limit"_qs].toLongLong(); if (limit == 0) limit = -1; - const QStringList hashes {params()["hashes"].split('|')}; + const QStringList hashes {params()[u"hashes"_qs].split(u'|')}; applyToTorrents(hashes, [limit](BitTorrent::Torrent *const torrent) { torrent->setUploadLimit(limit); }); } void TorrentsController::setDownloadLimitAction() { - requireParams({"hashes", "limit"}); + requireParams({u"hashes"_qs, u"limit"_qs}); - qlonglong limit = params()["limit"].toLongLong(); + qlonglong limit = params()[u"limit"_qs].toLongLong(); if (limit == 0) limit = -1; - const QStringList hashes {params()["hashes"].split('|')}; + const QStringList hashes {params()[u"hashes"_qs].split(u'|')}; applyToTorrents(hashes, [limit](BitTorrent::Torrent *const torrent) { torrent->setDownloadLimit(limit); }); } void TorrentsController::setShareLimitsAction() { - requireParams({"hashes", "ratioLimit", "seedingTimeLimit"}); + requireParams({u"hashes"_qs, u"ratioLimit"_qs, u"seedingTimeLimit"_qs}); - const qreal ratioLimit = params()["ratioLimit"].toDouble(); - const qlonglong seedingTimeLimit = params()["seedingTimeLimit"].toLongLong(); - const QStringList hashes = params()["hashes"].split('|'); + const qreal ratioLimit = params()[u"ratioLimit"_qs].toDouble(); + const qlonglong seedingTimeLimit = params()[u"seedingTimeLimit"_qs].toLongLong(); + const QStringList hashes = params()[u"hashes"_qs].split(u'|'); applyToTorrents(hashes, [ratioLimit, seedingTimeLimit](BitTorrent::Torrent *const torrent) { @@ -996,35 +996,35 @@ void TorrentsController::setShareLimitsAction() void TorrentsController::toggleSequentialDownloadAction() { - requireParams({"hashes"}); + requireParams({u"hashes"_qs}); - const QStringList hashes {params()["hashes"].split('|')}; + const QStringList hashes {params()[u"hashes"_qs].split(u'|')}; applyToTorrents(hashes, [](BitTorrent::Torrent *const torrent) { torrent->toggleSequentialDownload(); }); } void TorrentsController::toggleFirstLastPiecePrioAction() { - requireParams({"hashes"}); + requireParams({u"hashes"_qs}); - const QStringList hashes {params()["hashes"].split('|')}; + const QStringList hashes {params()[u"hashes"_qs].split(u'|')}; applyToTorrents(hashes, [](BitTorrent::Torrent *const torrent) { torrent->toggleFirstLastPiecePriority(); }); } void TorrentsController::setSuperSeedingAction() { - requireParams({"hashes", "value"}); + requireParams({u"hashes"_qs, u"value"_qs}); - const bool value {parseBool(params()["value"]).value_or(false)}; - const QStringList hashes {params()["hashes"].split('|')}; + const bool value {parseBool(params()[u"value"_qs]).value_or(false)}; + const QStringList hashes {params()[u"hashes"_qs].split(u'|')}; applyToTorrents(hashes, [value](BitTorrent::Torrent *const torrent) { torrent->setSuperSeeding(value); }); } void TorrentsController::setForceStartAction() { - requireParams({"hashes", "value"}); + requireParams({u"hashes"_qs, u"value"_qs}); - const bool value {parseBool(params()["value"]).value_or(false)}; - const QStringList hashes {params()["hashes"].split('|')}; + const bool value {parseBool(params()[u"value"_qs]).value_or(false)}; + const QStringList hashes {params()[u"hashes"_qs].split(u'|')}; applyToTorrents(hashes, [value](BitTorrent::Torrent *const torrent) { torrent->resume(value ? BitTorrent::TorrentOperatingMode::Forced : BitTorrent::TorrentOperatingMode::AutoManaged); @@ -1033,10 +1033,10 @@ void TorrentsController::setForceStartAction() void TorrentsController::deleteAction() { - requireParams({"hashes", "deleteFiles"}); + requireParams({u"hashes"_qs, u"deleteFiles"_qs}); - const QStringList hashes {params()["hashes"].split('|')}; - const DeleteOption deleteOption = parseBool(params()["deleteFiles"]).value_or(false) + const QStringList hashes {params()[u"hashes"_qs].split(u'|')}; + const DeleteOption deleteOption = parseBool(params()[u"deleteFiles"_qs]).value_or(false) ? DeleteTorrentAndFiles : DeleteTorrent; applyToTorrents(hashes, [deleteOption](const BitTorrent::Torrent *torrent) { @@ -1046,54 +1046,54 @@ void TorrentsController::deleteAction() void TorrentsController::increasePrioAction() { - requireParams({"hashes"}); + requireParams({u"hashes"_qs}); if (!BitTorrent::Session::instance()->isQueueingSystemEnabled()) throw APIError(APIErrorType::Conflict, tr("Torrent queueing must be enabled")); - const QStringList hashes {params()["hashes"].split('|')}; + const QStringList hashes {params()[u"hashes"_qs].split(u'|')}; BitTorrent::Session::instance()->increaseTorrentsQueuePos(toTorrentIDs(hashes)); } void TorrentsController::decreasePrioAction() { - requireParams({"hashes"}); + requireParams({u"hashes"_qs}); if (!BitTorrent::Session::instance()->isQueueingSystemEnabled()) throw APIError(APIErrorType::Conflict, tr("Torrent queueing must be enabled")); - const QStringList hashes {params()["hashes"].split('|')}; + const QStringList hashes {params()[u"hashes"_qs].split(u'|')}; BitTorrent::Session::instance()->decreaseTorrentsQueuePos(toTorrentIDs(hashes)); } void TorrentsController::topPrioAction() { - requireParams({"hashes"}); + requireParams({u"hashes"_qs}); if (!BitTorrent::Session::instance()->isQueueingSystemEnabled()) throw APIError(APIErrorType::Conflict, tr("Torrent queueing must be enabled")); - const QStringList hashes {params()["hashes"].split('|')}; + const QStringList hashes {params()[u"hashes"_qs].split(u'|')}; BitTorrent::Session::instance()->topTorrentsQueuePos(toTorrentIDs(hashes)); } void TorrentsController::bottomPrioAction() { - requireParams({"hashes"}); + requireParams({u"hashes"_qs}); if (!BitTorrent::Session::instance()->isQueueingSystemEnabled()) throw APIError(APIErrorType::Conflict, tr("Torrent queueing must be enabled")); - const QStringList hashes {params()["hashes"].split('|')}; + const QStringList hashes {params()[u"hashes"_qs].split(u'|')}; BitTorrent::Session::instance()->bottomTorrentsQueuePos(toTorrentIDs(hashes)); } void TorrentsController::setLocationAction() { - requireParams({"hashes", "location"}); + requireParams({u"hashes"_qs, u"location"_qs}); - const QStringList hashes {params()["hashes"].split('|')}; - const Path newLocation {params()["location"].trimmed()}; + const QStringList hashes {params()[u"hashes"_qs].split(u'|')}; + const Path newLocation {params()[u"location"_qs].trimmed()}; if (newLocation.isEmpty()) throw APIError(APIErrorType::BadParams, tr("Save path cannot be empty")); @@ -1117,10 +1117,10 @@ void TorrentsController::setLocationAction() void TorrentsController::setSavePathAction() { - requireParams({"id", "path"}); + requireParams({u"id"_qs, u"path"_qs}); - const QStringList ids {params()["id"].split('|')}; - const Path newPath {params()["path"]}; + const QStringList ids {params()[u"id"_qs].split(u'|')}; + const Path newPath {params()[u"path"_qs]}; if (newPath.isEmpty()) throw APIError(APIErrorType::BadParams, tr("Save path cannot be empty")); @@ -1142,10 +1142,10 @@ void TorrentsController::setSavePathAction() void TorrentsController::setDownloadPathAction() { - requireParams({"id", "path"}); + requireParams({u"id"_qs, u"path"_qs}); - const QStringList ids {params()["id"].split('|')}; - const Path newPath {params()["path"]}; + const QStringList ids {params()[u"id"_qs].split(u'|')}; + const Path newPath {params()[u"path"_qs]}; if (!newPath.isEmpty()) { @@ -1167,10 +1167,10 @@ void TorrentsController::setDownloadPathAction() void TorrentsController::renameAction() { - requireParams({"hash", "name"}); + requireParams({u"hash"_qs, u"name"_qs}); - const auto id = BitTorrent::TorrentID::fromString(params()["hash"]); - QString name = params()["name"].trimmed(); + const auto id = BitTorrent::TorrentID::fromString(params()[u"hash"_qs]); + QString name = params()[u"name"_qs].trimmed(); if (name.isEmpty()) throw APIError(APIErrorType::Conflict, tr("Incorrect torrent name")); @@ -1179,16 +1179,16 @@ void TorrentsController::renameAction() if (!torrent) throw APIError(APIErrorType::NotFound); - name.replace(QRegularExpression("\r?\n|\r"), " "); + name.replace(QRegularExpression(u"\r?\n|\r"_qs), u" "_qs); torrent->setName(name); } void TorrentsController::setAutoManagementAction() { - requireParams({"hashes", "enable"}); + requireParams({u"hashes"_qs, u"enable"_qs}); - const QStringList hashes {params()["hashes"].split('|')}; - const bool isEnabled {parseBool(params()["enable"]).value_or(false)}; + const QStringList hashes {params()[u"hashes"_qs].split(u'|')}; + const bool isEnabled {parseBool(params()[u"enable"_qs]).value_or(false)}; applyToTorrents(hashes, [isEnabled](BitTorrent::Torrent *const torrent) { @@ -1198,26 +1198,26 @@ void TorrentsController::setAutoManagementAction() void TorrentsController::recheckAction() { - requireParams({"hashes"}); + requireParams({u"hashes"_qs}); - const QStringList hashes {params()["hashes"].split('|')}; + const QStringList hashes {params()[u"hashes"_qs].split(u'|')}; applyToTorrents(hashes, [](BitTorrent::Torrent *const torrent) { torrent->forceRecheck(); }); } void TorrentsController::reannounceAction() { - requireParams({"hashes"}); + requireParams({u"hashes"_qs}); - const QStringList hashes {params()["hashes"].split('|')}; + const QStringList hashes {params()[u"hashes"_qs].split(u'|')}; applyToTorrents(hashes, [](BitTorrent::Torrent *const torrent) { torrent->forceReannounce(); }); } void TorrentsController::setCategoryAction() { - requireParams({"hashes", "category"}); + requireParams({u"hashes"_qs, u"category"_qs}); - const QStringList hashes {params()["hashes"].split('|')}; - const QString category {params()["category"]}; + const QStringList hashes {params()[u"hashes"_qs].split(u'|')}; + const QString category {params()[u"category"_qs]}; applyToTorrents(hashes, [category](BitTorrent::Torrent *const torrent) { @@ -1228,22 +1228,22 @@ void TorrentsController::setCategoryAction() void TorrentsController::createCategoryAction() { - requireParams({"category"}); + requireParams({u"category"_qs}); - const QString category = params()["category"]; + const QString category = params()[u"category"_qs]; if (category.isEmpty()) throw APIError(APIErrorType::BadParams, tr("Category cannot be empty")); if (!BitTorrent::Session::isValidCategoryName(category)) throw APIError(APIErrorType::Conflict, tr("Incorrect category name")); - const Path savePath {params()["savePath"]}; - const auto useDownloadPath = parseBool(params()["downloadPathEnabled"]); + const Path savePath {params()[u"savePath"_qs]}; + const auto useDownloadPath = parseBool(params()[u"downloadPathEnabled"_qs]); BitTorrent::CategoryOptions categoryOptions; categoryOptions.savePath = savePath; if (useDownloadPath.has_value()) { - const Path downloadPath {params()["downloadPath"]}; + const Path downloadPath {params()[u"downloadPath"_qs]}; categoryOptions.downloadPath = {useDownloadPath.value(), downloadPath}; } @@ -1253,19 +1253,19 @@ void TorrentsController::createCategoryAction() void TorrentsController::editCategoryAction() { - requireParams({"category", "savePath"}); + requireParams({u"category"_qs, u"savePath"_qs}); - const QString category = params()["category"]; + const QString category = params()[u"category"_qs]; if (category.isEmpty()) throw APIError(APIErrorType::BadParams, tr("Category cannot be empty")); - const Path savePath {params()["savePath"]}; - const auto useDownloadPath = parseBool(params()["downloadPathEnabled"]); + const Path savePath {params()[u"savePath"_qs]}; + const auto useDownloadPath = parseBool(params()[u"downloadPathEnabled"_qs]); BitTorrent::CategoryOptions categoryOptions; categoryOptions.savePath = savePath; if (useDownloadPath.has_value()) { - const Path downloadPath {params()["downloadPath"]}; + const Path downloadPath {params()[u"downloadPath"_qs]}; categoryOptions.downloadPath = {useDownloadPath.value(), downloadPath}; } @@ -1275,9 +1275,9 @@ void TorrentsController::editCategoryAction() void TorrentsController::removeCategoriesAction() { - requireParams({"categories"}); + requireParams({u"categories"_qs}); - const QStringList categories {params()["categories"].split('\n')}; + const QStringList categories {params()[u"categories"_qs].split(u'\n')}; for (const QString &category : categories) BitTorrent::Session::instance()->removeCategory(category); } @@ -1303,10 +1303,10 @@ void TorrentsController::categoriesAction() void TorrentsController::addTagsAction() { - requireParams({"hashes", "tags"}); + requireParams({u"hashes"_qs, u"tags"_qs}); - const QStringList hashes {params()["hashes"].split('|')}; - const QStringList tags {params()["tags"].split(',', Qt::SkipEmptyParts)}; + const QStringList hashes {params()[u"hashes"_qs].split(u'|')}; + const QStringList tags {params()[u"tags"_qs].split(u',', Qt::SkipEmptyParts)}; for (const QString &tag : tags) { @@ -1320,10 +1320,10 @@ void TorrentsController::addTagsAction() void TorrentsController::removeTagsAction() { - requireParams({"hashes"}); + requireParams({u"hashes"_qs}); - const QStringList hashes {params()["hashes"].split('|')}; - const QStringList tags {params()["tags"].split(',', Qt::SkipEmptyParts)}; + const QStringList hashes {params()[u"hashes"_qs].split(u'|')}; + const QStringList tags {params()[u"tags"_qs].split(u',', Qt::SkipEmptyParts)}; for (const QString &tag : tags) { @@ -1345,9 +1345,9 @@ void TorrentsController::removeTagsAction() void TorrentsController::createTagsAction() { - requireParams({"tags"}); + requireParams({u"tags"_qs}); - const QStringList tags {params()["tags"].split(',', Qt::SkipEmptyParts)}; + const QStringList tags {params()[u"tags"_qs].split(u',', Qt::SkipEmptyParts)}; for (const QString &tag : tags) BitTorrent::Session::instance()->addTag(tag.trimmed()); @@ -1355,9 +1355,9 @@ void TorrentsController::createTagsAction() void TorrentsController::deleteTagsAction() { - requireParams({"tags"}); + requireParams({u"tags"_qs}); - const QStringList tags {params()["tags"].split(',', Qt::SkipEmptyParts)}; + const QStringList tags {params()[u"tags"_qs].split(u',', Qt::SkipEmptyParts)}; for (const QString &tag : tags) BitTorrent::Session::instance()->removeTag(tag.trimmed()); } @@ -1372,15 +1372,15 @@ void TorrentsController::tagsAction() void TorrentsController::renameFileAction() { - requireParams({"hash", "oldPath", "newPath"}); + requireParams({u"hash"_qs, u"oldPath"_qs, u"newPath"_qs}); - const auto id = BitTorrent::TorrentID::fromString(params()["hash"]); + const auto id = BitTorrent::TorrentID::fromString(params()[u"hash"_qs]); BitTorrent::Torrent *const torrent = BitTorrent::Session::instance()->findTorrent(id); if (!torrent) throw APIError(APIErrorType::NotFound); - const Path oldPath {params()["oldPath"]}; - const Path newPath {params()["newPath"]}; + const Path oldPath {params()[u"oldPath"_qs]}; + const Path newPath {params()[u"newPath"_qs]}; try { @@ -1394,15 +1394,15 @@ void TorrentsController::renameFileAction() void TorrentsController::renameFolderAction() { - requireParams({"hash", "oldPath", "newPath"}); + requireParams({u"hash"_qs, u"oldPath"_qs, u"newPath"_qs}); - const auto id = BitTorrent::TorrentID::fromString(params()["hash"]); + const auto id = BitTorrent::TorrentID::fromString(params()[u"hash"_qs]); BitTorrent::Torrent *const torrent = BitTorrent::Session::instance()->findTorrent(id); if (!torrent) throw APIError(APIErrorType::NotFound); - const Path oldPath {params()["oldPath"]}; - const Path newPath {params()["newPath"]}; + const Path oldPath {params()[u"oldPath"_qs]}; + const Path newPath {params()[u"newPath"_qs]}; try { diff --git a/src/webui/api/transfercontroller.cpp b/src/webui/api/transfercontroller.cpp index 852baa43774..121b50b24c9 100644 --- a/src/webui/api/transfercontroller.cpp +++ b/src/webui/api/transfercontroller.cpp @@ -37,14 +37,14 @@ #include "base/global.h" #include "apierror.h" -const char KEY_TRANSFER_DLSPEED[] = "dl_info_speed"; -const char KEY_TRANSFER_DLDATA[] = "dl_info_data"; -const char KEY_TRANSFER_DLRATELIMIT[] = "dl_rate_limit"; -const char KEY_TRANSFER_UPSPEED[] = "up_info_speed"; -const char KEY_TRANSFER_UPDATA[] = "up_info_data"; -const char KEY_TRANSFER_UPRATELIMIT[] = "up_rate_limit"; -const char KEY_TRANSFER_DHT_NODES[] = "dht_nodes"; -const char KEY_TRANSFER_CONNECTION_STATUS[] = "connection_status"; +const QString KEY_TRANSFER_DLSPEED = u"dl_info_speed"_qs; +const QString KEY_TRANSFER_DLDATA = u"dl_info_data"_qs; +const QString KEY_TRANSFER_DLRATELIMIT = u"dl_rate_limit"_qs; +const QString KEY_TRANSFER_UPSPEED = u"up_info_speed"_qs; +const QString KEY_TRANSFER_UPDATA = u"up_info_data"_qs; +const QString KEY_TRANSFER_UPRATELIMIT = u"up_rate_limit"_qs; +const QString KEY_TRANSFER_DHT_NODES = u"dht_nodes"_qs; +const QString KEY_TRANSFER_CONNECTION_STATUS = u"connection_status"_qs; // Returns the global transfer information in JSON format. // The return value is a JSON-formatted dictionary. @@ -90,8 +90,8 @@ void TransferController::downloadLimitAction() void TransferController::setUploadLimitAction() { - requireParams({"limit"}); - qlonglong limit = params()["limit"].toLongLong(); + requireParams({u"limit"_qs}); + qlonglong limit = params()[u"limit"_qs].toLongLong(); if (limit == 0) limit = -1; BitTorrent::Session::instance()->setUploadSpeedLimit(limit); @@ -99,8 +99,8 @@ void TransferController::setUploadLimitAction() void TransferController::setDownloadLimitAction() { - requireParams({"limit"}); - qlonglong limit = params()["limit"].toLongLong(); + requireParams({u"limit"_qs}); + qlonglong limit = params()[u"limit"_qs].toLongLong(); if (limit == 0) limit = -1; BitTorrent::Session::instance()->setDownloadSpeedLimit(limit); @@ -119,9 +119,9 @@ void TransferController::speedLimitsModeAction() void TransferController::banPeersAction() { - requireParams({"peers"}); + requireParams({u"peers"_qs}); - const QStringList peers = params()["peers"].split('|'); + const QStringList peers = params()[u"peers"_qs].split(u'|'); for (const QString &peer : peers) { const BitTorrent::PeerAddress addr = BitTorrent::PeerAddress::parse(peer.trimmed()); diff --git a/src/webui/webapplication.cpp b/src/webui/webapplication.cpp index 9596412a027..160ec42700d 100644 --- a/src/webui/webapplication.cpp +++ b/src/webui/webapplication.cpp @@ -63,7 +63,7 @@ #include "api/transfercontroller.h" const int MAX_ALLOWED_FILESIZE = 10 * 1024 * 1024; -const char C_SID[] = "SID"; // name of session id cookie +const auto C_SID = QByteArrayLiteral("SID"); // name of session id cookie const QString PATH_PREFIX_ICONS {QStringLiteral("/icons/")}; const QString WWW_FOLDER {QStringLiteral(":/www")}; @@ -80,7 +80,7 @@ namespace for (const auto &cookie : cookies) { - const int idx = cookie.indexOf('='); + const int idx = cookie.indexOf(u'='); if (idx < 0) continue; @@ -143,8 +143,8 @@ WebApplication::~WebApplication() void WebApplication::sendWebUIFile() { - const QStringList pathItems {request().path.split('/', Qt::SkipEmptyParts)}; - if (pathItems.contains(".") || pathItems.contains("..")) + const QStringList pathItems {request().path.split(u'/', Qt::SkipEmptyParts)}; + if (pathItems.contains(u".") || pathItems.contains(u"..")) throw InternalServerErrorHTTPError(); if (!m_isAltUIUsed) @@ -178,7 +178,7 @@ void WebApplication::sendWebUIFile() #ifdef Q_OS_UNIX if (!Utils::Fs::isRegularFile(localPath)) { - status(500, "Internal Server Error"); + status(500, u"Internal Server Error"_qs); print(tr("Unacceptable file type, only regular file is allowed."), Http::CONTENT_TYPE_TXT); return; } @@ -199,7 +199,7 @@ void WebApplication::sendWebUIFile() void WebApplication::translateDocument(QString &data) const { - const QRegularExpression regex("QBT_TR\\((([^\\)]|\\)(?!QBT_TR))+)\\)QBT_TR\\[CONTEXT=([a-zA-Z_][a-zA-Z0-9_]*)\\]"); + const QRegularExpression regex(u"QBT_TR\\((([^\\)]|\\)(?!QBT_TR))+)\\)QBT_TR\\[CONTEXT=([a-zA-Z_][a-zA-Z0-9_]*)\\]"_qs); int i = 0; bool found = true; @@ -220,8 +220,8 @@ void WebApplication::translateDocument(QString &data) const QString translation = loadedText.isEmpty() ? sourceText : loadedText; // Use HTML code for quotes to prevent issues with JS - translation.replace('\'', "'"); - translation.replace('\"', """); + translation.replace(u'\'', u"'"_qs); + translation.replace(u'\"', u"""_qs); data.replace(i, regexMatch.capturedLength(), translation); i += translation.length(); @@ -349,7 +349,7 @@ void WebApplication::configure() m_authSubnetWhitelist = pref->getWebUiAuthSubnetWhitelist(); m_sessionTimeout = pref->getWebUISessionTimeout(); - m_domainList = pref->getServerDomains().split(';', Qt::SkipEmptyParts); + m_domainList = pref->getServerDomains().split(u';', Qt::SkipEmptyParts); std::for_each(m_domainList.begin(), m_domainList.end(), [](QString &entry) { entry = entry.trimmed(); }); m_isCSRFProtectionEnabled = pref->isWebUiCSRFProtectionEnabled(); @@ -384,7 +384,7 @@ void WebApplication::configure() for (const QStringView line : customHeaderLines) { - const int idx = line.indexOf(':'); + const int idx = line.indexOf(u':'); if (idx < 0) { // require separator `:` to be present even if `value` field can be empty @@ -403,7 +403,7 @@ void WebApplication::configure() { m_trustedReverseProxyList.clear(); - const QStringList proxyList = pref->getWebUITrustedReverseProxiesList().split(';', Qt::SkipEmptyParts); + const QStringList proxyList = pref->getWebUITrustedReverseProxiesList().split(u';', Qt::SkipEmptyParts); for (const QString &proxy : proxyList) { @@ -466,7 +466,7 @@ void WebApplication::sendFile(const Path &path) // Translate the file if (isTranslatable) { - QString dataStr {data}; + auto dataStr = QString::fromUtf8(data); translateDocument(dataStr); data = dataStr.toUtf8(); @@ -533,7 +533,7 @@ void WebApplication::sessionInitialize() { Q_ASSERT(!m_currentSession); - const QString sessionId {parseCookie(m_request.headers.value(QLatin1String("cookie"))).value(C_SID)}; + const QString sessionId {parseCookie(m_request.headers.value(QLatin1String("cookie"))).value(QString::fromLatin1(C_SID))}; // TODO: Additional session check @@ -572,7 +572,7 @@ QString WebApplication::generateSid() const const quint32 tmp[] = {Utils::Random::rand(), Utils::Random::rand(), Utils::Random::rand() , Utils::Random::rand(), Utils::Random::rand(), Utils::Random::rand()}; - sid = QByteArray::fromRawData(reinterpret_cast(tmp), sizeof(tmp)).toBase64(); + sid = QString::fromLatin1(QByteArray::fromRawData(reinterpret_cast(tmp), sizeof(tmp)).toBase64()); } while (m_sessions.contains(sid)); @@ -619,7 +619,7 @@ void WebApplication::sessionStart() QByteArray cookieRawForm = cookie.toRawForm(); if (m_isCSRFProtectionEnabled) cookieRawForm.append("; SameSite=Strict"); - setHeader({Http::HEADER_SET_COOKIE, cookieRawForm}); + setHeader({Http::HEADER_SET_COOKIE, QString::fromLatin1(cookieRawForm)}); } void WebApplication::sessionEnd() @@ -633,7 +633,7 @@ void WebApplication::sessionEnd() delete m_sessions.take(m_currentSession->id()); m_currentSession = nullptr; - setHeader({Http::HEADER_SET_COOKIE, cookie.toRawForm()}); + setHeader({Http::HEADER_SET_COOKIE, QString::fromLatin1(cookie.toRawForm())}); } bool WebApplication::isCrossSiteRequest(const Http::Request &request) const @@ -733,7 +733,7 @@ QHostAddress WebApplication::resolveClientAddress() const if (!forwardedFor.isEmpty()) { // client address is the 1st global IP in X-Forwarded-For or, if none available, the 1st IP in the list - const QStringList remoteIpList = forwardedFor.split(',', Qt::SkipEmptyParts); + const QStringList remoteIpList = forwardedFor.split(u',', Qt::SkipEmptyParts); if (!remoteIpList.isEmpty()) { diff --git a/src/webui/webui.cpp b/src/webui/webui.cpp index 7813d997d6c..3134d000a06 100644 --- a/src/webui/webui.cpp +++ b/src/webui/webui.cpp @@ -112,7 +112,7 @@ void WebUI::configure() if (!m_httpServer->isListening()) { - const auto address = (serverAddressString == "*" || serverAddressString.isEmpty()) + const auto address = ((serverAddressString == u"*") || serverAddressString.isEmpty()) ? QHostAddress::Any : QHostAddress(serverAddressString); bool success = m_httpServer->listen(address, m_port); if (success)