Browse Source

Revise string literal usage

PR #16703.
adaptive-webui-19844
Chocobo1 3 years ago committed by GitHub
parent
commit
4ca6de2b54
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 40
      src/app/application.cpp
  2. 2
      src/app/applicationinstancemanager.cpp
  3. 66
      src/app/cmdoptions.cpp
  4. 12
      src/app/main.cpp
  5. 4
      src/app/qtlocalpeer/qtlocalpeer.cpp
  6. 2
      src/app/qtlocalpeer/qtlockedfile_win.cpp
  7. 14
      src/app/stacktrace_win.h
  8. 28
      src/app/upgrade.cpp
  9. 2
      src/base/asyncfilestorage.cpp
  10. 18
      src/base/bittorrent/bencoderesumedatastorage.cpp
  11. 6
      src/base/bittorrent/categoryoptions.cpp
  12. 4
      src/base/bittorrent/common.h
  13. 41
      src/base/bittorrent/dbresumedatastorage.cpp
  14. 7
      src/base/bittorrent/filterparserthread.cpp
  15. 11
      src/base/bittorrent/magneturi.cpp
  16. 4
      src/base/bittorrent/peeraddress.cpp
  17. 38
      src/base/bittorrent/peerinfo.cpp
  18. 58
      src/base/bittorrent/session.cpp
  19. 4
      src/base/bittorrent/statistics.cpp
  20. 8
      src/base/bittorrent/torrentimpl.cpp
  21. 4
      src/base/http/connection.cpp
  22. 18
      src/base/http/httperror.cpp
  23. 8
      src/base/http/requestparser.cpp
  24. 5
      src/base/http/responsebuilder.h
  25. 8
      src/base/http/responsegenerator.cpp
  26. 2
      src/base/http/types.h
  27. 2
      src/base/net/downloadmanager.cpp
  28. 2
      src/base/net/geoipmanager.cpp
  29. 10
      src/base/net/proxyconfigurationmanager.cpp
  30. 28
      src/base/path.cpp
  31. 8
      src/base/profile_p.cpp
  32. 17
      src/base/rss/rss_article.cpp
  33. 8
      src/base/rss/rss_autodownloader.cpp
  34. 38
      src/base/rss/rss_autodownloadrule.cpp
  35. 30
      src/base/rss/rss_feed.cpp
  36. 68
      src/base/rss/rss_parser.cpp
  37. 10
      src/base/rss/rss_session.cpp
  38. 18
      src/base/search/searchpluginmanager.cpp
  39. 2
      src/base/settingvalue.h
  40. 44
      src/base/torrentfileswatcher.cpp
  41. 14
      src/base/utils/fs.cpp
  42. 5
      src/base/utils/fs.h
  43. 4
      src/base/utils/misc.cpp
  44. 4
      src/base/utils/net.cpp
  45. 9
      src/base/utils/version.h
  46. 2
      src/webui/api/appcontroller.cpp
  47. 6
      src/webui/api/authcontroller.cpp
  48. 32
      src/webui/api/logcontroller.cpp
  49. 12
      src/webui/api/searchcontroller.cpp
  50. 40
      src/webui/api/serialize/serialize_torrent.cpp
  51. 26
      src/webui/api/synccontroller.cpp
  52. 16
      src/webui/api/torrentscontroller.cpp
  53. 4
      src/webui/api/transfercontroller.cpp
  54. 79
      src/webui/webapplication.cpp
  55. 5
      src/webui/webapplication.h

40
src/app/application.cpp

@ -104,10 +104,10 @@ namespace
#define SETTINGS_KEY(name) "Application/" name #define SETTINGS_KEY(name) "Application/" name
#define FILELOGGER_SETTINGS_KEY(name) (SETTINGS_KEY("FileLogger/") name) #define FILELOGGER_SETTINGS_KEY(name) (SETTINGS_KEY("FileLogger/") name)
const QString LOG_FOLDER = QStringLiteral("logs"); const QString LOG_FOLDER = u"logs"_qs;
const QChar PARAMS_SEPARATOR = QLatin1Char('|'); const QChar PARAMS_SEPARATOR = u'|';
const Path DEFAULT_PORTABLE_MODE_PROFILE_DIR {QStringLiteral("profile")}; const Path DEFAULT_PORTABLE_MODE_PROFILE_DIR {u"profile"_qs};
const int MIN_FILELOG_SIZE = 1024; // 1KiB const int MIN_FILELOG_SIZE = 1024; // 1KiB
const int MAX_FILELOG_SIZE = 1000 * 1024 * 1024; // 1000MiB const int MAX_FILELOG_SIZE = 1000 * 1024 * 1024; // 1000MiB
@ -337,7 +337,7 @@ void Application::runExternalProgram(const BitTorrent::Torrent *torrent) const
for (int i = (program.length() - 2); i >= 0; --i) for (int i = (program.length() - 2); i >= 0; --i)
{ {
if (program[i] != QLatin1Char('%')) if (program[i] != u'%')
continue; continue;
const ushort specifier = program[i + 1].unicode(); const ushort specifier = program[i + 1].unicode();
@ -361,13 +361,13 @@ void Application::runExternalProgram(const BitTorrent::Torrent *torrent) const
#endif #endif
break; break;
case u'G': case u'G':
program.replace(i, 2, torrent->tags().join(QLatin1String(","))); program.replace(i, 2, torrent->tags().join(u","_qs));
break; break;
case u'I': case u'I':
program.replace(i, 2, (torrent->infoHash().v1().isValid() ? torrent->infoHash().v1().toString() : QLatin1String("-"))); program.replace(i, 2, (torrent->infoHash().v1().isValid() ? torrent->infoHash().v1().toString() : u"-"_qs));
break; break;
case u'J': case u'J':
program.replace(i, 2, (torrent->infoHash().v2().isValid() ? torrent->infoHash().v2().toString() : QLatin1String("-"))); program.replace(i, 2, (torrent->infoHash().v2().isValid() ? torrent->infoHash().v2().toString() : u"-"_qs));
break; break;
case u'K': case u'K':
program.replace(i, 2, torrent->id().toString()); program.replace(i, 2, torrent->id().toString());
@ -563,43 +563,43 @@ void Application::processParams(const QStringList &params)
// Process strings indicating options specified by the user. // Process strings indicating options specified by the user.
if (param.startsWith(QLatin1String("@savePath="))) if (param.startsWith(u"@savePath="))
{ {
torrentParams.savePath = Path(param.mid(10)); torrentParams.savePath = Path(param.mid(10));
continue; continue;
} }
if (param.startsWith(QLatin1String("@addPaused="))) if (param.startsWith(u"@addPaused="))
{ {
torrentParams.addPaused = (QStringView(param).mid(11).toInt() != 0); torrentParams.addPaused = (QStringView(param).mid(11).toInt() != 0);
continue; continue;
} }
if (param == QLatin1String("@skipChecking")) if (param == u"@skipChecking")
{ {
torrentParams.skipChecking = true; torrentParams.skipChecking = true;
continue; continue;
} }
if (param.startsWith(QLatin1String("@category="))) if (param.startsWith(u"@category="))
{ {
torrentParams.category = param.mid(10); torrentParams.category = param.mid(10);
continue; continue;
} }
if (param == QLatin1String("@sequential")) if (param == u"@sequential")
{ {
torrentParams.sequential = true; torrentParams.sequential = true;
continue; continue;
} }
if (param == QLatin1String("@firstLastPiecePriority")) if (param == u"@firstLastPiecePriority")
{ {
torrentParams.firstLastPiecePriority = true; torrentParams.firstLastPiecePriority = true;
continue; continue;
} }
if (param.startsWith(QLatin1String("@skipDialog="))) if (param.startsWith(u"@skipDialog="))
{ {
skipTorrentDialog = (QStringView(param).mid(12).toInt() != 0); skipTorrentDialog = (QStringView(param).mid(12).toInt() != 0);
continue; continue;
@ -671,9 +671,9 @@ int Application::exec(const QStringList &params)
#ifndef DISABLE_WEBUI #ifndef DISABLE_WEBUI
const Preferences *pref = Preferences::instance(); const Preferences *pref = Preferences::instance();
const auto scheme = QString::fromLatin1(pref->isWebUiHttpsEnabled() ? "https" : "http"); const auto scheme = pref->isWebUiHttpsEnabled() ? u"https"_qs : u"http"_qs;
const auto url = QString::fromLatin1("%1://localhost:%2\n").arg(scheme, QString::number(pref->getWebUiPort())); const auto url = u"%1://localhost:%2\n"_qs.arg(scheme, QString::number(pref->getWebUiPort()));
const QString mesg = QString::fromLatin1("\n******** %1 ********\n").arg(tr("Information")) const QString mesg = u"\n******** %1 ********\n"_qs.arg(tr("Information"))
+ tr("To control qBittorrent, access the WebUI at: %1").arg(url); + tr("To control qBittorrent, access the WebUI at: %1").arg(url);
printf("%s\n", qUtf8Printable(mesg)); printf("%s\n", qUtf8Printable(mesg));
@ -740,15 +740,15 @@ void Application::initializeTranslation()
// Load translation // Load translation
const QString localeStr = pref->getLocale(); const QString localeStr = pref->getLocale();
if (m_qtTranslator.load(QLatin1String("qtbase_") + localeStr, QLibraryInfo::location(QLibraryInfo::TranslationsPath)) || if (m_qtTranslator.load((u"qtbase_" + localeStr), QLibraryInfo::location(QLibraryInfo::TranslationsPath)) ||
m_qtTranslator.load(QLatin1String("qt_") + localeStr, QLibraryInfo::location(QLibraryInfo::TranslationsPath))) m_qtTranslator.load((u"qt_" + localeStr), QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
qDebug("Qt %s locale recognized, using translation.", qUtf8Printable(localeStr)); qDebug("Qt %s locale recognized, using translation.", qUtf8Printable(localeStr));
else else
qDebug("Qt %s locale unrecognized, using default (en).", qUtf8Printable(localeStr)); qDebug("Qt %s locale unrecognized, using default (en).", qUtf8Printable(localeStr));
installTranslator(&m_qtTranslator); installTranslator(&m_qtTranslator);
if (m_translator.load(QLatin1String(":/lang/qbittorrent_") + localeStr)) if (m_translator.load(u":/lang/qbittorrent_" + localeStr))
qDebug("%s locale recognized, using translation.", qUtf8Printable(localeStr)); qDebug("%s locale recognized, using translation.", qUtf8Printable(localeStr));
else else
qDebug("%s locale unrecognized, using default (en).", qUtf8Printable(localeStr)); qDebug("%s locale unrecognized, using default (en).", qUtf8Printable(localeStr));

2
src/app/applicationinstancemanager.cpp

@ -48,7 +48,7 @@ ApplicationInstanceManager::ApplicationInstanceManager(const Path &instancePath,
connect(m_peer, &QtLocalPeer::messageReceived, this, &ApplicationInstanceManager::messageReceived); connect(m_peer, &QtLocalPeer::messageReceived, this, &ApplicationInstanceManager::messageReceived);
#ifdef Q_OS_WIN #ifdef Q_OS_WIN
const QString sharedMemoryKey = instancePath.data() + QLatin1String("/shared-memory"); const QString sharedMemoryKey = instancePath.data() + u"/shared-memory";
auto sharedMem = new QSharedMemory(sharedMemoryKey, this); auto sharedMem = new QSharedMemory(sharedMemoryKey, this);
if (m_isFirstInstance) if (m_isFirstInstance)
{ {

66
src/app/cmdoptions.cpp

@ -67,12 +67,12 @@ namespace
QString fullParameter() const QString fullParameter() const
{ {
return QLatin1String("--") + QLatin1String(m_name); return u"--" + QString::fromLatin1(m_name);
} }
QString shortcutParameter() const QString shortcutParameter() const
{ {
return QLatin1String("-") + QLatin1Char(m_shortcut); return u"-" + QChar::fromLatin1(m_shortcut);
} }
bool hasShortcut() const bool hasShortcut() const
@ -82,8 +82,8 @@ namespace
QString envVarName() const QString envVarName() const
{ {
return QLatin1String("QBT_") return u"QBT_"
+ QString::fromLatin1(m_name).toUpper().replace(QLatin1Char('-'), QLatin1Char('_')); + QString::fromLatin1(m_name).toUpper().replace(u'-', u'_');
} }
public: public:
@ -121,14 +121,14 @@ namespace
{ {
QString val = env.value(envVarName()); QString val = env.value(envVarName());
// we accept "1" and "true" (upper or lower cased) as boolean 'true' values // we accept "1" and "true" (upper or lower cased) as boolean 'true' values
return ((val == QLatin1String("1")) || (val.toUpper() == QLatin1String("TRUE"))); return ((val == u"1") || (val.toUpper() == u"TRUE"));
} }
QString usage() const QString usage() const
{ {
QString res; QString res;
if (hasShortcut()) if (hasShortcut())
res += shortcutParameter() + QLatin1String(" | "); res += shortcutParameter() + u" | ";
res += fullParameter(); res += fullParameter();
return padUsageText(res); return padUsageText(res);
} }
@ -155,29 +155,29 @@ namespace
QString value(const QString &arg) const QString value(const QString &arg) const
{ {
QStringList parts = arg.split(QLatin1Char('=')); QStringList parts = arg.split(u'=');
if (parts.size() == 2) if (parts.size() == 2)
return Utils::String::unquote(parts[1], QLatin1String("'\"")); return Utils::String::unquote(parts[1], u"'\""_qs);
throw CommandLineParameterError(QObject::tr("Parameter '%1' must follow syntax '%1=%2'", throw CommandLineParameterError(QObject::tr("Parameter '%1' must follow syntax '%1=%2'",
"e.g. Parameter '--webui-port' must follow syntax '--webui-port=value'") "e.g. Parameter '--webui-port' must follow syntax '--webui-port=value'")
.arg(fullParameter(), QLatin1String("<value>"))); .arg(fullParameter(), u"<value>"_qs));
} }
QString value(const QProcessEnvironment &env, const QString &defaultValue = {}) const QString value(const QProcessEnvironment &env, const QString &defaultValue = {}) const
{ {
QString val = env.value(envVarName()); QString val = env.value(envVarName());
return val.isEmpty() ? defaultValue : Utils::String::unquote(val, QLatin1String("'\"")); return val.isEmpty() ? defaultValue : Utils::String::unquote(val, u"'\""_qs);
} }
QString usage(const QString &valueName) const QString usage(const QString &valueName) const
{ {
return padUsageText(parameterAssignment() + QLatin1Char('<') + valueName + QLatin1Char('>')); return padUsageText(parameterAssignment() + u'<' + valueName + u'>');
} }
private: private:
QString parameterAssignment() const QString parameterAssignment() const
{ {
return fullParameter() + QLatin1Char('='); return fullParameter() + u'=';
} }
}; };
@ -206,7 +206,7 @@ namespace
if (!ok) if (!ok)
throw CommandLineParameterError(QObject::tr("Parameter '%1' must follow syntax '%1=%2'", throw CommandLineParameterError(QObject::tr("Parameter '%1' must follow syntax '%1=%2'",
"e.g. Parameter '--webui-port' must follow syntax '--webui-port=<value>'") "e.g. Parameter '--webui-port' must follow syntax '--webui-port=<value>'")
.arg(fullParameter(), QLatin1String("<integer value>"))); .arg(fullParameter(), u"<integer value>"_qs));
return res; return res;
} }
@ -245,18 +245,18 @@ namespace
bool operator==(const QString &arg) const bool operator==(const QString &arg) const
{ {
QStringList parts = arg.split(QLatin1Char('=')); QStringList parts = arg.split(u'=');
return parts[0] == fullParameter(); return parts[0] == fullParameter();
} }
QString usage() const QString usage() const
{ {
return padUsageText(fullParameter() + QLatin1String("=<true|false>")); return padUsageText(fullParameter() + u"=<true|false>");
} }
std::optional<bool> value(const QString &arg) const std::optional<bool> value(const QString &arg) const
{ {
QStringList parts = arg.split(QLatin1Char('=')); QStringList parts = arg.split(u'=');
if (parts.size() == 1) if (parts.size() == 1)
{ {
@ -266,11 +266,11 @@ namespace
{ {
QString val = parts[1]; QString val = parts[1];
if ((val.toUpper() == QLatin1String("TRUE")) || (val == QLatin1String("1"))) if ((val.toUpper() == u"TRUE") || (val == u"1"))
{ {
return true; return true;
} }
if ((val.toUpper() == QLatin1String("FALSE")) || (val == QLatin1String("0"))) if ((val.toUpper() == u"FALSE") || (val == u"0"))
{ {
return false; return false;
} }
@ -279,7 +279,7 @@ namespace
throw CommandLineParameterError(QObject::tr("Parameter '%1' must follow syntax '%1=%2'", throw CommandLineParameterError(QObject::tr("Parameter '%1' must follow syntax '%1=%2'",
"e.g. Parameter '--add-paused' must follow syntax " "e.g. Parameter '--add-paused' must follow syntax "
"'--add-paused=<true|false>'") "'--add-paused=<true|false>'")
.arg(fullParameter(), QLatin1String("<true|false>"))); .arg(fullParameter(), u"<true|false>"_qs));
} }
std::optional<bool> value(const QProcessEnvironment &env) const std::optional<bool> value(const QProcessEnvironment &env) const
@ -290,21 +290,21 @@ namespace
{ {
return m_defaultValue; return m_defaultValue;
} }
if (val == QLatin1String("-1")) if (val == u"-1")
{ {
return std::nullopt; return std::nullopt;
} }
if ((val.toUpper() == QLatin1String("TRUE")) || (val == QLatin1String("1"))) if ((val.toUpper() == u"TRUE") || (val == u"1"))
{ {
return true; return true;
} }
if ((val.toUpper() == QLatin1String("FALSE")) || (val == QLatin1String("0"))) if ((val.toUpper() == u"FALSE") || (val == u"0"))
{ {
return false; return false;
} }
qDebug() << QObject::tr("Expected %1 in environment variable '%2', but got '%3'") qDebug() << QObject::tr("Expected %1 in environment variable '%2', but got '%3'")
.arg(QLatin1String("true|false"), envVarName(), val); .arg(u"true|false"_qs, envVarName(), val);
return std::nullopt; return std::nullopt;
} }
@ -372,25 +372,25 @@ QStringList QBtCommandLineParameters::paramList() const
// torrent paths or URLs. // torrent paths or URLs.
if (!savePath.isEmpty()) if (!savePath.isEmpty())
result.append(QLatin1String("@savePath=") + savePath.data()); result.append(u"@savePath=" + savePath.data());
if (addPaused.has_value()) if (addPaused.has_value())
result.append(*addPaused ? QLatin1String {"@addPaused=1"} : QLatin1String {"@addPaused=0"}); result.append(*addPaused ? u"@addPaused=1"_qs : u"@addPaused=0"_qs);
if (skipChecking) if (skipChecking)
result.append(QLatin1String("@skipChecking")); result.append(u"@skipChecking"_qs);
if (!category.isEmpty()) if (!category.isEmpty())
result.append(QLatin1String("@category=") + category); result.append(u"@category=" + category);
if (sequential) if (sequential)
result.append(QLatin1String("@sequential")); result.append(u"@sequential"_qs);
if (firstLastPiecePriority) if (firstLastPiecePriority)
result.append(QLatin1String("@firstLastPiecePriority")); result.append(u"@firstLastPiecePriority"_qs);
if (skipDialog.has_value()) if (skipDialog.has_value())
result.append(*skipDialog ? QLatin1String {"@skipDialog=1"} : QLatin1String {"@skipDialog=0"}); result.append(*skipDialog ? u"@skipDialog=1"_qs : u"@skipDialog=0"_qs);
result += torrents; result += torrents;
return result; return result;
@ -423,7 +423,7 @@ QBtCommandLineParameters parseCommandLine(const QStringList &args)
result.webUiPort = WEBUI_PORT_OPTION.value(arg); result.webUiPort = WEBUI_PORT_OPTION.value(arg);
if ((result.webUiPort < 1) || (result.webUiPort > 65535)) if ((result.webUiPort < 1) || (result.webUiPort > 65535))
throw CommandLineParameterError(QObject::tr("%1 must specify a valid port (1 to 65535).") throw CommandLineParameterError(QObject::tr("%1 must specify a valid port (1 to 65535).")
.arg(QLatin1String("--webui-port"))); .arg(u"--webui-port"_qs));
} }
#ifndef DISABLE_GUI #ifndef DISABLE_GUI
else if (arg == NO_SPLASH_OPTION) else if (arg == NO_SPLASH_OPTION)
@ -527,7 +527,7 @@ QString makeUsage(const QString &prgName)
QString indentation = QString(USAGE_INDENTATION, u' '); QString indentation = QString(USAGE_INDENTATION, u' ');
stream << QObject::tr("Usage:") << '\n' stream << QObject::tr("Usage:") << '\n'
<< indentation << prgName << QLatin1String(" [options] [(<filename> | <url>)...]") << '\n' << indentation << prgName << u" [options] [(<filename> | <url>)...]"_qs << '\n'
<< QObject::tr("Options:") << '\n' << QObject::tr("Options:") << '\n'
#if !defined(Q_OS_WIN) || defined(DISABLE_GUI) #if !defined(Q_OS_WIN) || defined(DISABLE_GUI)
@ -573,7 +573,7 @@ QString makeUsage(const QString &prgName)
"'parameter-name', environment variable name is 'QBT_PARAMETER_NAME' (in upper " "'parameter-name', environment variable name is 'QBT_PARAMETER_NAME' (in upper "
"case, '-' replaced with '_'). To pass flag values, set the variable to '1' or " "case, '-' replaced with '_'). To pass flag values, set the variable to '1' or "
"'TRUE'. For example, to disable the splash screen: "), 0) << "\n" "'TRUE'. For example, to disable the splash screen: "), 0) << "\n"
<< QLatin1String("QBT_NO_SPLASH=1 ") << prgName << '\n' << u"QBT_NO_SPLASH=1 "_qs << prgName << '\n'
<< wrapText(QObject::tr("Command line parameters take precedence over environment variables"), 0) << '\n'; << wrapText(QObject::tr("Command line parameters take precedence over environment variables"), 0) << '\n';
return text; return text;

12
src/app/main.cpp

@ -165,7 +165,7 @@ int main(int argc, char *argv[])
return EXIT_SUCCESS; return EXIT_SUCCESS;
} }
throw CommandLineParameterError(QObject::tr("%1 must be the single command line parameter.") throw CommandLineParameterError(QObject::tr("%1 must be the single command line parameter.")
.arg(QLatin1String("-v (or --version)"))); .arg(u"-v (or --version)"_qs));
} }
#endif #endif
if (params.showHelp) if (params.showHelp)
@ -176,7 +176,7 @@ int main(int argc, char *argv[])
return EXIT_SUCCESS; return EXIT_SUCCESS;
} }
throw CommandLineParameterError(QObject::tr("%1 must be the single command line parameter.") throw CommandLineParameterError(QObject::tr("%1 must be the single command line parameter.")
.arg(QLatin1String("-h (or --help)"))); .arg(u"-h (or --help)"_qs));
} }
const bool firstTimeUser = !Preferences::instance()->getAcceptedLegal(); const bool firstTimeUser = !Preferences::instance()->getAcceptedLegal();
@ -208,7 +208,7 @@ int main(int argc, char *argv[])
if (params.shouldDaemonize) if (params.shouldDaemonize)
{ {
throw CommandLineParameterError(QObject::tr("You cannot use %1: qBittorrent is already running for this user.") throw CommandLineParameterError(QObject::tr("You cannot use %1: qBittorrent is already running for this user.")
.arg(QLatin1String("-d (or --daemon)"))); .arg(u"-d (or --daemon)"_qs));
} }
else else
#endif #endif
@ -362,7 +362,7 @@ void sigAbnormalHandler(int signum)
#if defined Q_OS_WIN && !defined DISABLE_GUI #if defined Q_OS_WIN && !defined DISABLE_GUI
StacktraceDialog dlg; // unsafe StacktraceDialog dlg; // unsafe
dlg.setStacktraceString(QLatin1String(sigName), straceWin::getBacktrace()); dlg.setStacktraceString(QString::fromLatin1(sigName), straceWin::getBacktrace());
dlg.exec(); dlg.exec();
#endif #endif
@ -397,7 +397,7 @@ void displayBadArgMessage(const QString &message)
const QString help = QObject::tr("Run application with -h option to read about command line parameters."); const QString help = QObject::tr("Run application with -h option to read about command line parameters.");
#if defined(Q_OS_WIN) && !defined(DISABLE_GUI) #if defined(Q_OS_WIN) && !defined(DISABLE_GUI)
QMessageBox msgBox(QMessageBox::Critical, QObject::tr("Bad command line"), QMessageBox msgBox(QMessageBox::Critical, QObject::tr("Bad command line"),
message + QLatin1Char('\n') + help, QMessageBox::Ok); (message + u'\n' + help), QMessageBox::Ok);
msgBox.show(); // Need to be shown or to moveToCenter does not work msgBox.show(); // Need to be shown or to moveToCenter does not work
msgBox.move(Utils::Gui::screenCenter(&msgBox)); msgBox.move(Utils::Gui::screenCenter(&msgBox));
msgBox.exec(); msgBox.exec();
@ -415,7 +415,7 @@ bool userAgreesWithLegalNotice()
Q_ASSERT(!pref->getAcceptedLegal()); Q_ASSERT(!pref->getAcceptedLegal());
#ifdef DISABLE_GUI #ifdef DISABLE_GUI
const QString eula = QString::fromLatin1("\n*** %1 ***\n").arg(QObject::tr("Legal Notice")) const QString eula = u"\n*** %1 ***\n"_qs.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.") + u"\n\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("No further notices will be issued.") + u"\n\n"
+ QObject::tr("Press %1 key to accept and continue...").arg(u"'y'"_qs) + u'\n'; + QObject::tr("Press %1 key to accept and continue...").arg(u"'y'"_qs) + u'\n';

4
src/app/qtlocalpeer/qtlocalpeer.cpp

@ -94,12 +94,12 @@ const char ACK[] = "ack";
QtLocalPeer::QtLocalPeer(const QString &path, QObject *parent) QtLocalPeer::QtLocalPeer(const QString &path, QObject *parent)
: QObject(parent) : QObject(parent)
, m_socketName(path + QLatin1String("/ipc-socket")) , m_socketName(path + u"/ipc-socket")
, m_server(new QLocalServer(this)) , m_server(new QLocalServer(this))
{ {
m_server->setSocketOptions(QLocalServer::UserAccessOption); m_server->setSocketOptions(QLocalServer::UserAccessOption);
m_lockFile.setFileName(path + QLatin1String("/lockfile")); m_lockFile.setFileName(path + u"/lockfile");
m_lockFile.open(QIODevice::ReadWrite); m_lockFile.open(QIODevice::ReadWrite);
} }

2
src/app/qtlocalpeer/qtlockedfile_win.cpp

@ -80,7 +80,7 @@ Qt::HANDLE QtLockedFile::getMutexHandle(const int idx, const bool doCreate)
if (m_mutexName.isEmpty()) if (m_mutexName.isEmpty())
{ {
QFileInfo fi(*this); QFileInfo fi(*this);
m_mutexName = QString::fromLatin1("QtLockedFile mutex ") + fi.absoluteFilePath().toLower(); m_mutexName = u"QtLockedFile mutex " + fi.absoluteFilePath().toLower();
} }
QString mname = m_mutexName; QString mname = m_mutexName;

14
src/app/stacktrace_win.h

@ -97,8 +97,8 @@ BOOL CALLBACK straceWin::EnumModulesCB(LPCSTR ModuleName, DWORD64 BaseOfDll, PVO
mod.SizeOfStruct = sizeof(IMAGEHLP_MODULE64); mod.SizeOfStruct = sizeof(IMAGEHLP_MODULE64);
if(SymGetModuleInfo64(context->hProcess, BaseOfDll, &mod)) if(SymGetModuleInfo64(context->hProcess, BaseOfDll, &mod))
{ {
QString moduleBase = QString::fromLatin1("0x%1").arg(BaseOfDll, 16, 16, QLatin1Char('0')); QString moduleBase = u"0x%1"_qs.arg(BaseOfDll, 16, 16, QChar(u'0'));
QString line = QString::fromLatin1("%1 %2 Image: %3") QString line = u"%1 %2 Image: %3"_qs
.arg(QString::fromUtf8(mod.ModuleName), -25) .arg(QString::fromUtf8(mod.ModuleName), -25)
.arg(moduleBase, -13) .arg(moduleBase, -13)
.arg(QString::fromUtf8(mod.LoadedImageName)); .arg(QString::fromUtf8(mod.LoadedImageName));
@ -107,7 +107,7 @@ BOOL CALLBACK straceWin::EnumModulesCB(LPCSTR ModuleName, DWORD64 BaseOfDll, PVO
const auto pdbName = QString::fromUtf8(mod.LoadedPdbName); const auto pdbName = QString::fromUtf8(mod.LoadedPdbName);
if(!pdbName.isEmpty()) if(!pdbName.isEmpty())
{ {
QString line2 = QString::fromLatin1("%1 %2") QString line2 = u"%1 %2"_qs
.arg(u""_qs, 35) .arg(u""_qs, 35)
.arg(pdbName); .arg(pdbName);
context->stream << line2 << '\n'; context->stream << line2 << '\n';
@ -173,7 +173,7 @@ QString straceWin::getSourcePathAndLineNumber(HANDLE hProcess, DWORD64 addr)
} }
#endif #endif
#endif #endif
return QString::fromLatin1("%1 : %2").arg(path).arg(line.LineNumber); return u"%1 : %2"_qs.arg(path).arg(line.LineNumber);
} }
return QString(); return QString();
@ -311,7 +311,7 @@ const QString straceWin::getBacktrace()
} }
else else
{ {
funcName = QString::fromLatin1("0x%1").arg(ihsf.InstructionOffset, 8, 16, QLatin1Char('0')); funcName = u"0x%1"_qs.arg(ihsf.InstructionOffset, 8, 16, QChar(u'0'));
} }
SymSetContext(hProcess, &ihsf, NULL); SymSetContext(hProcess, &ihsf, NULL);
#ifndef __MINGW32__ #ifndef __MINGW32__
@ -319,7 +319,7 @@ const QString straceWin::getBacktrace()
SymEnumSymbols(hProcess, 0, NULL, EnumSymbolsCB, (PVOID)&params); SymEnumSymbols(hProcess, 0, NULL, EnumSymbolsCB, (PVOID)&params);
#endif #endif
QString insOffset = QString::fromLatin1("0x%1").arg(ihsf.InstructionOffset, 16, 16, QLatin1Char('0')); QString insOffset = u"0x%1"_qs.arg(ihsf.InstructionOffset, 16, 16, QChar(u'0'));
auto formatLine = u"#%1 %2 %3 %4"_qs; auto formatLine = u"#%1 %2 %3 %4"_qs;
#ifndef __MINGW32__ #ifndef __MINGW32__
formatLine += u"(%5)"_qs; formatLine += u"(%5)"_qs;
@ -333,7 +333,7 @@ const QString straceWin::getBacktrace()
.arg(params.join(u", ")); .arg(params.join(u", "));
if (!sourceFile.isEmpty()) if (!sourceFile.isEmpty())
debugLine += QString::fromLatin1("[ %1 ]").arg(sourceFile); debugLine += u"[ %1 ]"_qs.arg(sourceFile);
#else #else
; ;
#endif #endif

28
src/app/upgrade.cpp

@ -74,18 +74,18 @@ namespace
}; };
const Path configPath = specialFolderLocation(SpecialFolder::Config); const Path configPath = specialFolderLocation(SpecialFolder::Config);
migrate(QLatin1String("Preferences/WebUI/HTTPS/Certificate") migrate(u"Preferences/WebUI/HTTPS/Certificate"_qs
, QLatin1String("Preferences/WebUI/HTTPS/CertificatePath") , u"Preferences/WebUI/HTTPS/CertificatePath"_qs
, (configPath / Path(u"WebUICertificate.crt"_qs))); , (configPath / Path(u"WebUICertificate.crt"_qs)));
migrate(QLatin1String("Preferences/WebUI/HTTPS/Key") migrate(u"Preferences/WebUI/HTTPS/Key"_qs
, QLatin1String("Preferences/WebUI/HTTPS/KeyPath") , u"Preferences/WebUI/HTTPS/KeyPath"_qs
, (configPath / Path(u"WebUIPrivateKey.pem"_qs))); , (configPath / Path(u"WebUIPrivateKey.pem"_qs)));
} }
void upgradeTorrentContentLayout() void upgradeTorrentContentLayout()
{ {
const QString oldKey {QLatin1String {"BitTorrent/Session/CreateTorrentSubfolder"}}; const QString oldKey = u"BitTorrent/Session/CreateTorrentSubfolder"_qs;
const QString newKey {QLatin1String {"BitTorrent/Session/TorrentContentLayout"}}; const QString newKey = u"BitTorrent/Session/TorrentContentLayout"_qs;
SettingsStorage *settingsStorage {SettingsStorage::instance()}; SettingsStorage *settingsStorage {SettingsStorage::instance()};
const auto oldData {settingsStorage->loadValue<QVariant>(oldKey)}; const auto oldData {settingsStorage->loadValue<QVariant>(oldKey)};
@ -104,8 +104,8 @@ namespace
void upgradeListenPortSettings() void upgradeListenPortSettings()
{ {
const auto oldKey = QString::fromLatin1("BitTorrent/Session/UseRandomPort"); const auto oldKey = u"BitTorrent/Session/UseRandomPort"_qs;
const auto newKey = QString::fromLatin1("Preferences/Connection/PortRangeMin"); const auto newKey = u"Preferences/Connection/PortRangeMin"_qs;
auto *settingsStorage = SettingsStorage::instance(); auto *settingsStorage = SettingsStorage::instance();
if (settingsStorage->hasKey(oldKey)) if (settingsStorage->hasKey(oldKey))
@ -120,7 +120,7 @@ namespace
void upgradeSchedulerDaysSettings() void upgradeSchedulerDaysSettings()
{ {
auto *settingsStorage = SettingsStorage::instance(); auto *settingsStorage = SettingsStorage::instance();
const auto key = QString::fromLatin1("Preferences/Scheduler/days"); const auto key = u"Preferences/Scheduler/days"_qs;
const auto value = settingsStorage->loadValue<QString>(key); const auto value = settingsStorage->loadValue<QString>(key);
bool ok = false; bool ok = false;
@ -172,7 +172,7 @@ namespace
void upgradeDNSServiceSettings() void upgradeDNSServiceSettings()
{ {
auto *settingsStorage = SettingsStorage::instance(); auto *settingsStorage = SettingsStorage::instance();
const auto key = QString::fromLatin1("Preferences/DynDNS/Service"); const auto key = u"Preferences/DynDNS/Service"_qs;
const auto value = settingsStorage->loadValue<QString>(key); const auto value = settingsStorage->loadValue<QString>(key);
bool ok = false; bool ok = false;
@ -203,7 +203,7 @@ namespace
void upgradeTrayIconStyleSettings() void upgradeTrayIconStyleSettings()
{ {
auto *settingsStorage = SettingsStorage::instance(); auto *settingsStorage = SettingsStorage::instance();
const auto key = QString::fromLatin1("Preferences/Advanced/TrayIconStyle"); const auto key = u"Preferences/Advanced/TrayIconStyle"_qs;
const auto value = settingsStorage->loadValue<QString>(key); const auto value = settingsStorage->loadValue<QString>(key);
bool ok = false; bool ok = false;
@ -332,7 +332,7 @@ namespace
void migrateProxySettingsEnum() void migrateProxySettingsEnum()
{ {
auto *settingsStorage = SettingsStorage::instance(); auto *settingsStorage = SettingsStorage::instance();
const auto key = QString::fromLatin1("Network/Proxy/Type"); const auto key = u"Network/Proxy/Type"_qs;
const auto value = settingsStorage->loadValue<QString>(key); const auto value = settingsStorage->loadValue<QString>(key);
bool ok = false; bool ok = false;
@ -400,7 +400,7 @@ bool upgrade(const bool /*ask*/)
void setCurrentMigrationVersion() void setCurrentMigrationVersion()
{ {
SettingsStorage::instance()->storeValue(QLatin1String(MIGRATION_VERSION_KEY), MIGRATION_VERSION); SettingsStorage::instance()->storeValue(QString::fromLatin1(MIGRATION_VERSION_KEY), MIGRATION_VERSION);
} }
void handleChangedDefaults(const DefaultPreferencesMode mode) void handleChangedDefaults(const DefaultPreferencesMode mode)
@ -414,7 +414,7 @@ void handleChangedDefaults(const DefaultPreferencesMode mode)
const DefaultValue changedDefaults[] = const DefaultValue changedDefaults[] =
{ {
{QLatin1String {"BitTorrent/Session/QueueingSystemEnabled"}, true, false} {u"BitTorrent/Session/QueueingSystemEnabled"_qs, true, false}
}; };
auto *settingsStorage = SettingsStorage::instance(); auto *settingsStorage = SettingsStorage::instance();

2
src/base/asyncfilestorage.cpp

@ -37,7 +37,7 @@
AsyncFileStorage::AsyncFileStorage(const Path &storageFolderPath, QObject *parent) AsyncFileStorage::AsyncFileStorage(const Path &storageFolderPath, QObject *parent)
: QObject(parent) : QObject(parent)
, m_storageDir(storageFolderPath) , m_storageDir(storageFolderPath)
, m_lockFile((m_storageDir / Path(QStringLiteral("storage.lock"))).data()) , m_lockFile((m_storageDir / Path(u"storage.lock"_qs)).data())
{ {
Q_ASSERT(m_storageDir.isAbsolute()); Q_ASSERT(m_storageDir.isAbsolute());

18
src/base/bittorrent/bencoderesumedatastorage.cpp

@ -103,8 +103,8 @@ BitTorrent::BencodeResumeDataStorage::BencodeResumeDataStorage(const Path &path,
.arg(m_resumeDataPath.toString())); .arg(m_resumeDataPath.toString()));
} }
const QRegularExpression filenamePattern {QLatin1String("^([A-Fa-f0-9]{40})\\.fastresume$")}; const QRegularExpression filenamePattern {u"^([A-Fa-f0-9]{40})\\.fastresume$"_qs};
const QStringList filenames = QDir(m_resumeDataPath.data()).entryList(QStringList(QLatin1String("*.fastresume")), QDir::Files, QDir::Unsorted); const QStringList filenames = QDir(m_resumeDataPath.data()).entryList(QStringList(u"*.fastresume"_qs), QDir::Files, QDir::Unsorted);
m_registeredTorrents.reserve(filenames.size()); m_registeredTorrents.reserve(filenames.size());
for (const QString &filename : filenames) for (const QString &filename : filenames)
@ -137,8 +137,8 @@ QVector<BitTorrent::TorrentID> BitTorrent::BencodeResumeDataStorage::registeredT
std::optional<BitTorrent::LoadTorrentParams> BitTorrent::BencodeResumeDataStorage::load(const TorrentID &id) const std::optional<BitTorrent::LoadTorrentParams> BitTorrent::BencodeResumeDataStorage::load(const TorrentID &id) const
{ {
const QString idString = id.toString(); const QString idString = id.toString();
const Path fastresumePath = m_resumeDataPath / Path(idString + QLatin1String(".fastresume")); const Path fastresumePath = m_resumeDataPath / Path(idString + u".fastresume");
const Path torrentFilePath = m_resumeDataPath / Path(idString + QLatin1String(".torrent")); const Path torrentFilePath = m_resumeDataPath / Path(idString + u".torrent");
QFile resumeDataFile {fastresumePath.data()}; QFile resumeDataFile {fastresumePath.data()};
if (!resumeDataFile.open(QIODevice::ReadOnly)) if (!resumeDataFile.open(QIODevice::ReadOnly))
@ -284,7 +284,7 @@ void BitTorrent::BencodeResumeDataStorage::loadQueue(const Path &queueFilename)
if (queueFile.open(QFile::ReadOnly)) if (queueFile.open(QFile::ReadOnly))
{ {
const QRegularExpression hashPattern {QLatin1String("^([A-Fa-f0-9]{40})$")}; const QRegularExpression hashPattern {u"^([A-Fa-f0-9]{40})$"_qs};
QString line; QString line;
int start = 0; int start = 0;
while (!(line = QString::fromLatin1(queueFile.readLine().trimmed())).isEmpty()) while (!(line = QString::fromLatin1(queueFile.readLine().trimmed())).isEmpty())
@ -353,7 +353,7 @@ void BitTorrent::BencodeResumeDataStorage::Worker::store(const TorrentID &id, co
metadataDict.insert(dataDict.extract("created by")); metadataDict.insert(dataDict.extract("created by"));
metadataDict.insert(dataDict.extract("comment")); metadataDict.insert(dataDict.extract("comment"));
const Path torrentFilepath = m_resumeDataDir / Path(QString::fromLatin1("%1.torrent").arg(id.toString())); const Path torrentFilepath = m_resumeDataDir / Path(u"%1.torrent"_qs.arg(id.toString()));
const nonstd::expected<void, QString> result = Utils::IO::saveToFile(torrentFilepath, metadata); const nonstd::expected<void, QString> result = Utils::IO::saveToFile(torrentFilepath, metadata);
if (!result) if (!result)
{ {
@ -378,7 +378,7 @@ void BitTorrent::BencodeResumeDataStorage::Worker::store(const TorrentID &id, co
data["qBt-downloadPath"] = Profile::instance()->toPortablePath(resumeData.downloadPath).data().toStdString(); data["qBt-downloadPath"] = Profile::instance()->toPortablePath(resumeData.downloadPath).data().toStdString();
} }
const Path resumeFilepath = m_resumeDataDir / Path(QString::fromLatin1("%1.fastresume").arg(id.toString())); const Path resumeFilepath = m_resumeDataDir / Path(u"%1.fastresume"_qs.arg(id.toString()));
const nonstd::expected<void, QString> result = Utils::IO::saveToFile(resumeFilepath, data); const nonstd::expected<void, QString> result = Utils::IO::saveToFile(resumeFilepath, data);
if (!result) if (!result)
{ {
@ -389,10 +389,10 @@ void BitTorrent::BencodeResumeDataStorage::Worker::store(const TorrentID &id, co
void BitTorrent::BencodeResumeDataStorage::Worker::remove(const TorrentID &id) const void BitTorrent::BencodeResumeDataStorage::Worker::remove(const TorrentID &id) const
{ {
const Path resumeFilename {QString::fromLatin1("%1.fastresume").arg(id.toString())}; const Path resumeFilename {u"%1.fastresume"_qs.arg(id.toString())};
Utils::Fs::removeFile(m_resumeDataDir / resumeFilename); Utils::Fs::removeFile(m_resumeDataDir / resumeFilename);
const Path torrentFilename {QString::fromLatin1("%1.torrent").arg(id.toString())}; const Path torrentFilename {u"%1.torrent"_qs.arg(id.toString())};
Utils::Fs::removeFile(m_resumeDataDir / torrentFilename); Utils::Fs::removeFile(m_resumeDataDir / torrentFilename);
} }

6
src/base/bittorrent/categoryoptions.cpp

@ -31,8 +31,10 @@
#include <QJsonObject> #include <QJsonObject>
#include <QJsonValue> #include <QJsonValue>
const QString OPTION_SAVEPATH {QStringLiteral("save_path")}; #include "base/global.h"
const QString OPTION_DOWNLOADPATH {QStringLiteral("download_path")};
const QString OPTION_SAVEPATH = u"save_path"_qs;
const QString OPTION_DOWNLOADPATH = u"download_path"_qs;
BitTorrent::CategoryOptions BitTorrent::CategoryOptions::fromJSON(const QJsonObject &jsonObj) BitTorrent::CategoryOptions BitTorrent::CategoryOptions::fromJSON(const QJsonObject &jsonObj)
{ {

4
src/base/bittorrent/common.h

@ -30,4 +30,6 @@
#include <QString> #include <QString>
inline const QString QB_EXT {QStringLiteral(".!qB")}; #include "base/global.h"
inline const QString QB_EXT = u".!qB"_qs;

41
src/base/bittorrent/dbresumedatastorage.cpp

@ -75,7 +75,7 @@ namespace
Column makeColumn(const char *columnName) Column makeColumn(const char *columnName)
{ {
return {QLatin1String(columnName), (QLatin1Char(':') + QLatin1String(columnName))}; return {QString::fromLatin1(columnName), (u':' + QString::fromLatin1(columnName))};
} }
const Column DB_COLUMN_ID = makeColumn("id"); const Column DB_COLUMN_ID = makeColumn("id");
@ -105,14 +105,14 @@ namespace
QString quoted(const QString &name) QString quoted(const QString &name)
{ {
const QLatin1Char quote {'`'}; const QChar quote = u'`';
return (quote + name + quote); return (quote + name + quote);
} }
QString makeCreateTableStatement(const QString &tableName, const QStringList &items) QString makeCreateTableStatement(const QString &tableName, const QStringList &items)
{ {
return QString::fromLatin1("CREATE TABLE %1 (%2)").arg(quoted(tableName), items.join(QLatin1Char(','))); return u"CREATE TABLE %1 (%2)"_qs.arg(quoted(tableName), items.join(u','));
} }
std::pair<QString, QString> joinColumns(const QVector<Column> &columns) std::pair<QString, QString> joinColumns(const QVector<Column> &columns)
@ -131,8 +131,8 @@ namespace
values.reserve(valuesSize); values.reserve(valuesSize);
for (const Column &column : columns) for (const Column &column : columns)
{ {
names.append(quoted(column.name) + QLatin1Char(',')); names.append(quoted(column.name) + u',');
values.append(column.placeholder + QLatin1Char(',')); values.append(column.placeholder + u',');
} }
names.chop(1); names.chop(1);
values.chop(1); values.chop(1);
@ -143,27 +143,27 @@ namespace
QString makeInsertStatement(const QString &tableName, const QVector<Column> &columns) QString makeInsertStatement(const QString &tableName, const QVector<Column> &columns)
{ {
const auto [names, values] = joinColumns(columns); const auto [names, values] = joinColumns(columns);
return QString::fromLatin1("INSERT INTO %1 (%2) VALUES (%3)") return u"INSERT INTO %1 (%2) VALUES (%3)"_qs
.arg(quoted(tableName), names, values); .arg(quoted(tableName), names, values);
} }
QString makeUpdateStatement(const QString &tableName, const QVector<Column> &columns) QString makeUpdateStatement(const QString &tableName, const QVector<Column> &columns)
{ {
const auto [names, values] = joinColumns(columns); const auto [names, values] = joinColumns(columns);
return QString::fromLatin1("UPDATE %1 SET (%2) = (%3)") return u"UPDATE %1 SET (%2) = (%3)"_qs
.arg(quoted(tableName), names, values); .arg(quoted(tableName), names, values);
} }
QString makeOnConflictUpdateStatement(const Column &constraint, const QVector<Column> &columns) QString makeOnConflictUpdateStatement(const Column &constraint, const QVector<Column> &columns)
{ {
const auto [names, values] = joinColumns(columns); const auto [names, values] = joinColumns(columns);
return QString::fromLatin1(" ON CONFLICT (%1) DO UPDATE SET (%2) = (%3)") return u" ON CONFLICT (%1) DO UPDATE SET (%2) = (%3)"_qs
.arg(quoted(constraint.name), names, values); .arg(quoted(constraint.name), names, values);
} }
QString makeColumnDefinition(const Column &column, const char *definition) QString makeColumnDefinition(const Column &column, const char *definition)
{ {
return QString::fromLatin1("%1 %2").arg(quoted(column.name), QLatin1String(definition)); return u"%1 %2"_qs.arg(quoted(column.name), QString::fromLatin1(definition));
} }
} }
@ -195,7 +195,7 @@ BitTorrent::DBResumeDataStorage::DBResumeDataStorage(const Path &dbPath, QObject
{ {
const bool needCreateDB = !dbPath.exists(); const bool needCreateDB = !dbPath.exists();
auto db = QSqlDatabase::addDatabase(QLatin1String("QSQLITE"), DB_CONNECTION_NAME); auto db = QSqlDatabase::addDatabase(u"QSQLITE"_qs, DB_CONNECTION_NAME);
db.setDatabaseName(dbPath.data()); db.setDatabaseName(dbPath.data());
if (!db.open()) if (!db.open())
throw RuntimeError(db.lastError().text()); throw RuntimeError(db.lastError().text());
@ -211,7 +211,7 @@ BitTorrent::DBResumeDataStorage::DBResumeDataStorage(const Path &dbPath, QObject
updateDBFromVersion1(); updateDBFromVersion1();
} }
m_asyncWorker = new Worker(dbPath, QLatin1String("ResumeDataStorageWorker")); m_asyncWorker = new Worker(dbPath, u"ResumeDataStorageWorker"_qs);
m_asyncWorker->moveToThread(m_ioThread); m_asyncWorker->moveToThread(m_ioThread);
connect(m_ioThread, &QThread::finished, m_asyncWorker, &QObject::deleteLater); connect(m_ioThread, &QThread::finished, m_asyncWorker, &QObject::deleteLater);
m_ioThread->start(); m_ioThread->start();
@ -244,7 +244,7 @@ BitTorrent::DBResumeDataStorage::~DBResumeDataStorage()
QVector<BitTorrent::TorrentID> BitTorrent::DBResumeDataStorage::registeredTorrents() const QVector<BitTorrent::TorrentID> BitTorrent::DBResumeDataStorage::registeredTorrents() const
{ {
const auto selectTorrentIDStatement = QString::fromLatin1("SELECT %1 FROM %2 ORDER BY %3;") const auto selectTorrentIDStatement = u"SELECT %1 FROM %2 ORDER BY %3;"_qs
.arg(quoted(DB_COLUMN_TORRENT_ID.name), quoted(DB_TABLE_TORRENTS), quoted(DB_COLUMN_QUEUE_POSITION.name)); .arg(quoted(DB_COLUMN_TORRENT_ID.name), quoted(DB_TABLE_TORRENTS), quoted(DB_COLUMN_QUEUE_POSITION.name));
auto db = QSqlDatabase::database(DB_CONNECTION_NAME); auto db = QSqlDatabase::database(DB_CONNECTION_NAME);
@ -263,8 +263,7 @@ QVector<BitTorrent::TorrentID> BitTorrent::DBResumeDataStorage::registeredTorren
std::optional<BitTorrent::LoadTorrentParams> BitTorrent::DBResumeDataStorage::load(const TorrentID &id) const std::optional<BitTorrent::LoadTorrentParams> BitTorrent::DBResumeDataStorage::load(const TorrentID &id) const
{ {
const QString selectTorrentStatement = const QString selectTorrentStatement = u"SELECT * FROM %1 WHERE %2 = %3;"_qs
QString(QLatin1String("SELECT * FROM %1 WHERE %2 = %3;"))
.arg(quoted(DB_TABLE_TORRENTS), quoted(DB_COLUMN_TORRENT_ID.name), DB_COLUMN_TORRENT_ID.placeholder); .arg(quoted(DB_TABLE_TORRENTS), quoted(DB_COLUMN_TORRENT_ID.name), DB_COLUMN_TORRENT_ID.placeholder);
auto db = QSqlDatabase::database(DB_CONNECTION_NAME); auto db = QSqlDatabase::database(DB_CONNECTION_NAME);
@ -295,7 +294,7 @@ std::optional<BitTorrent::LoadTorrentParams> BitTorrent::DBResumeDataStorage::lo
const QString tagsData = query.value(DB_COLUMN_TAGS.name).toString(); const QString tagsData = query.value(DB_COLUMN_TAGS.name).toString();
if (!tagsData.isEmpty()) if (!tagsData.isEmpty())
{ {
const QStringList tagList = tagsData.split(QLatin1Char(',')); const QStringList tagList = tagsData.split(u',');
resumeData.tags.insert(tagList.cbegin(), tagList.cend()); resumeData.tags.insert(tagList.cbegin(), tagList.cend());
} }
resumeData.hasSeedStatus = query.value(DB_COLUMN_HAS_SEED_STATUS.name).toBool(); resumeData.hasSeedStatus = query.value(DB_COLUMN_HAS_SEED_STATUS.name).toBool();
@ -361,7 +360,7 @@ void BitTorrent::DBResumeDataStorage::storeQueue(const QVector<TorrentID> &queue
int BitTorrent::DBResumeDataStorage::currentDBVersion() const int BitTorrent::DBResumeDataStorage::currentDBVersion() const
{ {
const auto selectDBVersionStatement = QString::fromLatin1("SELECT %1 FROM %2 WHERE %3 = %4;") const auto selectDBVersionStatement = u"SELECT %1 FROM %2 WHERE %3 = %4;"_qs
.arg(quoted(DB_COLUMN_VALUE.name), quoted(DB_TABLE_META), quoted(DB_COLUMN_NAME.name), DB_COLUMN_NAME.placeholder); .arg(quoted(DB_COLUMN_VALUE.name), quoted(DB_TABLE_META), quoted(DB_COLUMN_NAME.name), DB_COLUMN_NAME.placeholder);
auto db = QSqlDatabase::database(DB_CONNECTION_NAME); auto db = QSqlDatabase::database(DB_CONNECTION_NAME);
@ -459,7 +458,7 @@ void BitTorrent::DBResumeDataStorage::updateDBFromVersion1() const
try try
{ {
const auto alterTableTorrentsQuery = QString::fromLatin1("ALTER TABLE %1 ADD %2") const auto alterTableTorrentsQuery = u"ALTER TABLE %1 ADD %2"_qs
.arg(quoted(DB_TABLE_TORRENTS), makeColumnDefinition(DB_COLUMN_DOWNLOAD_PATH, "TEXT")); .arg(quoted(DB_TABLE_TORRENTS), makeColumnDefinition(DB_COLUMN_DOWNLOAD_PATH, "TEXT"));
if (!query.exec(alterTableTorrentsQuery)) if (!query.exec(alterTableTorrentsQuery))
throw RuntimeError(query.lastError().text()); throw RuntimeError(query.lastError().text());
@ -492,7 +491,7 @@ BitTorrent::DBResumeDataStorage::Worker::Worker(const Path &dbPath, const QStrin
void BitTorrent::DBResumeDataStorage::Worker::openDatabase() const void BitTorrent::DBResumeDataStorage::Worker::openDatabase() const
{ {
auto db = QSqlDatabase::addDatabase(QLatin1String("QSQLITE"), m_connectionName); auto db = QSqlDatabase::addDatabase(u"QSQLITE"_qs, m_connectionName);
db.setDatabaseName(m_path.data()); db.setDatabaseName(m_path.data());
if (!db.open()) if (!db.open())
throw RuntimeError(db.lastError().text()); throw RuntimeError(db.lastError().text());
@ -592,7 +591,7 @@ void BitTorrent::DBResumeDataStorage::Worker::store(const TorrentID &id, const L
query.bindValue(DB_COLUMN_NAME.placeholder, resumeData.name); query.bindValue(DB_COLUMN_NAME.placeholder, resumeData.name);
query.bindValue(DB_COLUMN_CATEGORY.placeholder, resumeData.category); query.bindValue(DB_COLUMN_CATEGORY.placeholder, resumeData.category);
query.bindValue(DB_COLUMN_TAGS.placeholder, (resumeData.tags.isEmpty() query.bindValue(DB_COLUMN_TAGS.placeholder, (resumeData.tags.isEmpty()
? QVariant(QVariant::String) : resumeData.tags.join(QLatin1String(",")))); ? QVariant(QVariant::String) : resumeData.tags.join(u","_qs)));
query.bindValue(DB_COLUMN_CONTENT_LAYOUT.placeholder, Utils::String::fromEnum(resumeData.contentLayout)); query.bindValue(DB_COLUMN_CONTENT_LAYOUT.placeholder, Utils::String::fromEnum(resumeData.contentLayout));
query.bindValue(DB_COLUMN_RATIO_LIMIT.placeholder, static_cast<int>(resumeData.ratioLimit * 1000)); query.bindValue(DB_COLUMN_RATIO_LIMIT.placeholder, static_cast<int>(resumeData.ratioLimit * 1000));
query.bindValue(DB_COLUMN_SEEDING_TIME_LIMIT.placeholder, resumeData.seedingTimeLimit); query.bindValue(DB_COLUMN_SEEDING_TIME_LIMIT.placeholder, resumeData.seedingTimeLimit);
@ -623,7 +622,7 @@ void BitTorrent::DBResumeDataStorage::Worker::store(const TorrentID &id, const L
void BitTorrent::DBResumeDataStorage::Worker::remove(const TorrentID &id) const void BitTorrent::DBResumeDataStorage::Worker::remove(const TorrentID &id) const
{ {
const auto deleteTorrentStatement = QString::fromLatin1("DELETE FROM %1 WHERE %2 = %3;") const auto deleteTorrentStatement = u"DELETE FROM %1 WHERE %2 = %3;"_qs
.arg(quoted(DB_TABLE_TORRENTS), quoted(DB_COLUMN_TORRENT_ID.name), DB_COLUMN_TORRENT_ID.placeholder); .arg(quoted(DB_TABLE_TORRENTS), quoted(DB_COLUMN_TORRENT_ID.name), DB_COLUMN_TORRENT_ID.placeholder);
auto db = QSqlDatabase::database(m_connectionName); auto db = QSqlDatabase::database(m_connectionName);
@ -647,7 +646,7 @@ void BitTorrent::DBResumeDataStorage::Worker::remove(const TorrentID &id) const
void BitTorrent::DBResumeDataStorage::Worker::storeQueue(const QVector<TorrentID> &queue) const void BitTorrent::DBResumeDataStorage::Worker::storeQueue(const QVector<TorrentID> &queue) const
{ {
const auto updateQueuePosStatement = QString::fromLatin1("UPDATE %1 SET %2 = %3 WHERE %4 = %5;") const auto updateQueuePosStatement = u"UPDATE %1 SET %2 = %3 WHERE %4 = %5;"_qs
.arg(quoted(DB_TABLE_TORRENTS), quoted(DB_COLUMN_QUEUE_POSITION.name), DB_COLUMN_QUEUE_POSITION.placeholder .arg(quoted(DB_TABLE_TORRENTS), quoted(DB_COLUMN_QUEUE_POSITION.name), DB_COLUMN_QUEUE_POSITION.placeholder
, quoted(DB_COLUMN_TORRENT_ID.name), DB_COLUMN_TORRENT_ID.placeholder); , quoted(DB_COLUMN_TORRENT_ID.name), DB_COLUMN_TORRENT_ID.placeholder);

7
src/base/bittorrent/filterparserthread.cpp

@ -35,6 +35,7 @@
#include <QDataStream> #include <QDataStream>
#include <QFile> #include <QFile>
#include "base/global.h"
#include "base/logger.h" #include "base/logger.h"
namespace namespace
@ -617,17 +618,17 @@ void FilterParserThread::run()
{ {
qDebug("Processing filter file"); qDebug("Processing filter file");
int ruleCount = 0; int ruleCount = 0;
if (m_filePath.hasExtension(QLatin1String(".p2p"))) if (m_filePath.hasExtension(u".p2p"_qs))
{ {
// PeerGuardian p2p file // PeerGuardian p2p file
ruleCount = parseP2PFilterFile(); ruleCount = parseP2PFilterFile();
} }
else if (m_filePath.hasExtension(QLatin1String(".p2b"))) else if (m_filePath.hasExtension(u".p2b"_qs))
{ {
// PeerGuardian p2b file // PeerGuardian p2b file
ruleCount = parseP2BFilterFile(); ruleCount = parseP2BFilterFile();
} }
else if (m_filePath.hasExtension(QLatin1String(".dat"))) else if (m_filePath.hasExtension(u".dat"_qs))
{ {
// eMule DAT format // eMule DAT format
ruleCount = parseDATFilterFile(); ruleCount = parseDATFilterFile();

11
src/base/bittorrent/magneturi.cpp

@ -35,6 +35,7 @@
#include <QRegularExpression> #include <QRegularExpression>
#include "base/global.h"
#include "infohash.h" #include "infohash.h"
namespace namespace
@ -52,9 +53,9 @@ namespace
const int V1_BASE32_SIZE = SHA1Hash::length() * 1.6; const int V1_BASE32_SIZE = SHA1Hash::length() * 1.6;
return ((((string.size() == V1_HEX_SIZE)) return ((((string.size() == V1_HEX_SIZE))
&& !string.contains(QRegularExpression(QLatin1String("[^0-9A-Fa-f]")))) && !string.contains(QRegularExpression(u"[^0-9A-Fa-f]"_qs)))
|| ((string.size() == V1_BASE32_SIZE) || ((string.size() == V1_BASE32_SIZE)
&& !string.contains(QRegularExpression(QLatin1String("[^2-7A-Za-z]"))))); && !string.contains(QRegularExpression(u"[^2-7A-Za-z]"_qs))));
} }
bool isV2Hash(const QString &string) bool isV2Hash(const QString &string)
@ -65,7 +66,7 @@ namespace
const int V2_HEX_SIZE = SHA256Hash::length() * 2; const int V2_HEX_SIZE = SHA256Hash::length() * 2;
return (string.size() == V2_HEX_SIZE) return (string.size() == V2_HEX_SIZE)
&& !string.contains(QRegularExpression(QLatin1String("[^0-9A-Fa-f]"))); && !string.contains(QRegularExpression(u"[^0-9A-Fa-f]"_qs));
} }
} }
@ -80,9 +81,9 @@ MagnetUri::MagnetUri(const QString &source)
if (source.isEmpty()) return; if (source.isEmpty()) return;
if (isV2Hash(source)) if (isV2Hash(source))
m_url = QString::fromLatin1("magnet:?xt=urn:btmh:1220") + source; // 0x12 0x20 is the "multihash format" tag for the SHA-256 hashing scheme. m_url = u"magnet:?xt=urn:btmh:1220" + source; // 0x12 0x20 is the "multihash format" tag for the SHA-256 hashing scheme.
else if (isV1Hash(source)) else if (isV1Hash(source))
m_url = QString::fromLatin1("magnet:?xt=urn:btih:") + source; m_url = u"magnet:?xt=urn:btih:" + source;
lt::error_code ec; lt::error_code ec;
lt::parse_magnet_uri(m_url.toStdString(), m_addTorrentParams, ec); lt::parse_magnet_uri(m_url.toStdString(), m_addTorrentParams, ec);

4
src/base/bittorrent/peeraddress.cpp

@ -36,9 +36,9 @@ PeerAddress PeerAddress::parse(const QStringView address)
{ {
QList<QStringView> ipPort; QList<QStringView> ipPort;
if (address.startsWith(u'[') && address.contains(QLatin1String("]:"))) if (address.startsWith(u'[') && address.contains(u"]:"))
{ // IPv6 { // IPv6
ipPort = address.split(QString::fromLatin1("]:")); ipPort = address.split(u"]:");
ipPort[0] = ipPort[0].mid(1); // chop '[' ipPort[0] = ipPort[0].mid(1); // chop '['
} }
else if (address.contains(u':')) else if (address.contains(u':'))

38
src/base/bittorrent/peerinfo.cpp

@ -217,8 +217,8 @@ QString PeerInfo::connectionType() const
return C_UTP; return C_UTP;
return (m_nativeInfo.connection_type == lt::peer_info::standard_bittorrent) return (m_nativeInfo.connection_type == lt::peer_info::standard_bittorrent)
? QLatin1String {"BT"} ? u"BT"_qs
: QLatin1String {"Web"}; : u"Web"_qs;
} }
qreal PeerInfo::calcRelevance(const Torrent *torrent) const qreal PeerInfo::calcRelevance(const Torrent *torrent) const
@ -242,8 +242,8 @@ void PeerInfo::determineFlags()
{ {
const auto updateFlags = [this](const QChar specifier, const QString &explanation) const auto updateFlags = [this](const QChar specifier, const QString &explanation)
{ {
m_flags += (specifier + QLatin1Char(' ')); m_flags += (specifier + u' ');
m_flagsDescription += QString::fromLatin1("%1 = %2\n").arg(specifier, explanation); m_flagsDescription += u"%1 = %2\n"_qs.arg(specifier, explanation);
}; };
if (isInteresting()) if (isInteresting())
@ -251,12 +251,12 @@ void PeerInfo::determineFlags()
if (isRemoteChocked()) if (isRemoteChocked())
{ {
// d = Your client wants to download, but peer doesn't want to send (interested and choked) // d = Your client wants to download, but peer doesn't want to send (interested and choked)
updateFlags(QLatin1Char('d'), tr("Interested (local) and choked (peer)")); updateFlags(u'd', tr("Interested (local) and choked (peer)"));
} }
else else
{ {
// D = Currently downloading (interested and not choked) // D = Currently downloading (interested and not choked)
updateFlags(QLatin1Char('D'), tr("Interested (local) and unchoked (peer)")); updateFlags(u'D', tr("Interested (local) and unchoked (peer)"));
} }
} }
@ -265,58 +265,58 @@ void PeerInfo::determineFlags()
if (isChocked()) if (isChocked())
{ {
// u = Peer wants your client to upload, but your client doesn't want to (interested and choked) // u = Peer wants your client to upload, but your client doesn't want to (interested and choked)
updateFlags(QLatin1Char('u'), tr("Interested (peer) and choked (local)")); updateFlags(u'u', tr("Interested (peer) and choked (local)"));
} }
else else
{ {
// U = Currently uploading (interested and not choked) // U = Currently uploading (interested and not choked)
updateFlags(QLatin1Char('U'), tr("Interested (peer) and unchoked (local)")); updateFlags(u'U', tr("Interested (peer) and unchoked (local)"));
} }
} }
// K = Peer is unchoking your client, but your client is not interested // K = Peer is unchoking your client, but your client is not interested
if (!isRemoteChocked() && !isInteresting()) if (!isRemoteChocked() && !isInteresting())
updateFlags(QLatin1Char('K'), tr("Not interested (local) and unchoked (peer)")); updateFlags(u'K', tr("Not interested (local) and unchoked (peer)"));
// ? = Your client unchoked the peer but the peer is not interested // ? = Your client unchoked the peer but the peer is not interested
if (!isChocked() && !isRemoteInterested()) if (!isChocked() && !isRemoteInterested())
updateFlags(QLatin1Char('?'), tr("Not interested (peer) and unchoked (local)")); updateFlags(u'?', tr("Not interested (peer) and unchoked (local)"));
// O = Optimistic unchoke // O = Optimistic unchoke
if (optimisticUnchoke()) if (optimisticUnchoke())
updateFlags(QLatin1Char('O'), tr("Optimistic unchoke")); updateFlags(u'O', tr("Optimistic unchoke"));
// S = Peer is snubbed // S = Peer is snubbed
if (isSnubbed()) if (isSnubbed())
updateFlags(QLatin1Char('S'), tr("Peer snubbed")); updateFlags(u'S', tr("Peer snubbed"));
// I = Peer is an incoming connection // I = Peer is an incoming connection
if (!isLocalConnection()) if (!isLocalConnection())
updateFlags(QLatin1Char('I'), tr("Incoming connection")); updateFlags(u'I', tr("Incoming connection"));
// H = Peer was obtained through DHT // H = Peer was obtained through DHT
if (fromDHT()) if (fromDHT())
updateFlags(QLatin1Char('H'), tr("Peer from DHT")); updateFlags(u'H', tr("Peer from DHT"));
// X = Peer was included in peerlists obtained through Peer Exchange (PEX) // X = Peer was included in peerlists obtained through Peer Exchange (PEX)
if (fromPeX()) if (fromPeX())
updateFlags(QLatin1Char('X'), tr("Peer from PEX")); updateFlags(u'X', tr("Peer from PEX"));
// L = Peer is local // L = Peer is local
if (fromLSD()) if (fromLSD())
updateFlags(QLatin1Char('L'), tr("Peer from LSD")); updateFlags(u'L', tr("Peer from LSD"));
// E = Peer is using Protocol Encryption (all traffic) // E = Peer is using Protocol Encryption (all traffic)
if (isRC4Encrypted()) if (isRC4Encrypted())
updateFlags(QLatin1Char('E'), tr("Encrypted traffic")); updateFlags(u'E', tr("Encrypted traffic"));
// e = Peer is using Protocol Encryption (handshake) // e = Peer is using Protocol Encryption (handshake)
if (isPlaintextEncrypted()) if (isPlaintextEncrypted())
updateFlags(QLatin1Char('e'), tr("Encrypted handshake")); updateFlags(u'e', tr("Encrypted handshake"));
// P = Peer is using uTorrent uTP // P = Peer is using uTorrent uTP
if (useUTPSocket()) if (useUTPSocket())
updateFlags(QLatin1Char('P'), C_UTP); updateFlags(u'P', C_UTP);
m_flags.chop(1); m_flags.chop(1);
m_flagsDescription.chop(1); m_flagsDescription.chop(1);

58
src/base/bittorrent/session.cpp

@ -186,33 +186,33 @@ namespace
{ {
#ifdef QBT_USES_LIBTORRENT2 #ifdef QBT_USES_LIBTORRENT2
case lt::socket_type_t::http: case lt::socket_type_t::http:
return QLatin1String("HTTP"); return u"HTTP"_qs;
case lt::socket_type_t::http_ssl: case lt::socket_type_t::http_ssl:
return QLatin1String("HTTP_SSL"); return u"HTTP_SSL"_qs;
#endif #endif
case lt::socket_type_t::i2p: case lt::socket_type_t::i2p:
return QLatin1String("I2P"); return u"I2P"_qs;
case lt::socket_type_t::socks5: case lt::socket_type_t::socks5:
return QLatin1String("SOCKS5"); return u"SOCKS5"_qs;
#ifdef QBT_USES_LIBTORRENT2 #ifdef QBT_USES_LIBTORRENT2
case lt::socket_type_t::socks5_ssl: case lt::socket_type_t::socks5_ssl:
return QLatin1String("SOCKS5_SSL"); return u"SOCKS5_SSL"_qs;
#endif #endif
case lt::socket_type_t::tcp: case lt::socket_type_t::tcp:
return QLatin1String("TCP"); return u"TCP"_qs;
case lt::socket_type_t::tcp_ssl: case lt::socket_type_t::tcp_ssl:
return QLatin1String("TCP_SSL"); return u"TCP_SSL"_qs;
#ifdef QBT_USES_LIBTORRENT2 #ifdef QBT_USES_LIBTORRENT2
case lt::socket_type_t::utp: case lt::socket_type_t::utp:
return QLatin1String("UTP"); return u"UTP"_qs;
#else #else
case lt::socket_type_t::udp: case lt::socket_type_t::udp:
return QLatin1String("UDP"); return u"UDP"_qs;
#endif #endif
case lt::socket_type_t::utp_ssl: case lt::socket_type_t::utp_ssl:
return QLatin1String("UTP_SSL"); return u"UTP_SSL"_qs;
} }
return QLatin1String("INVALID"); return u"INVALID"_qs;
} }
QString toString(const lt::address &address) QString toString(const lt::address &address)
@ -1523,7 +1523,7 @@ void Session::configureNetworkInterfaces(lt::settings_pack &settingsPack)
endpoints << ((isIPv6 ? (u'[' + ip + u']') : ip) + portString); endpoints << ((isIPv6 ? (u'[' + ip + u']') : ip) + portString);
if ((ip != QLatin1String("0.0.0.0")) && (ip != QLatin1String("::"))) if ((ip != u"0.0.0.0") && (ip != u"::"))
outgoingInterfaces << ip; outgoingInterfaces << ip;
} }
else else
@ -1709,23 +1709,23 @@ void Session::processShareLimits()
if (m_maxRatioAction == Remove) if (m_maxRatioAction == Remove)
{ {
LogMsg(QString::fromLatin1("%1 %2 %3").arg(description, tr("Removed torrent."), torrentName)); LogMsg(u"%1 %2 %3"_qs.arg(description, tr("Removed torrent."), torrentName));
deleteTorrent(torrent->id()); deleteTorrent(torrent->id());
} }
else if (m_maxRatioAction == DeleteFiles) else if (m_maxRatioAction == DeleteFiles)
{ {
LogMsg(QString::fromLatin1("%1 %2 %3").arg(description, tr("Removed torrent and deleted its content."), torrentName)); LogMsg(u"%1 %2 %3"_qs.arg(description, tr("Removed torrent and deleted its content."), torrentName));
deleteTorrent(torrent->id(), DeleteTorrentAndFiles); deleteTorrent(torrent->id(), DeleteTorrentAndFiles);
} }
else if ((m_maxRatioAction == Pause) && !torrent->isPaused()) else if ((m_maxRatioAction == Pause) && !torrent->isPaused())
{ {
torrent->pause(); torrent->pause();
LogMsg(QString::fromLatin1("%1 %2 %3").arg(description, tr("Torrent paused."), torrentName)); LogMsg(u"%1 %2 %3"_qs.arg(description, tr("Torrent paused."), torrentName));
} }
else if ((m_maxRatioAction == EnableSuperSeeding) && !torrent->isPaused() && !torrent->superSeeding()) else if ((m_maxRatioAction == EnableSuperSeeding) && !torrent->isPaused() && !torrent->superSeeding())
{ {
torrent->setSuperSeeding(true); torrent->setSuperSeeding(true);
LogMsg(QString::fromLatin1("%1 %2 %3").arg(description, tr("Super seeding enabled."), torrentName)); LogMsg(u"%1 %2 %3"_qs.arg(description, tr("Super seeding enabled."), torrentName));
} }
continue; continue;
@ -1752,23 +1752,23 @@ void Session::processShareLimits()
if (m_maxRatioAction == Remove) if (m_maxRatioAction == Remove)
{ {
LogMsg(QString::fromLatin1("%1 %2 %3").arg(description, tr("Removed torrent."), torrentName)); LogMsg(u"%1 %2 %3"_qs.arg(description, tr("Removed torrent."), torrentName));
deleteTorrent(torrent->id()); deleteTorrent(torrent->id());
} }
else if (m_maxRatioAction == DeleteFiles) else if (m_maxRatioAction == DeleteFiles)
{ {
LogMsg(QString::fromLatin1("%1 %2 %3").arg(description, tr("Removed torrent and deleted its content."), torrentName)); LogMsg(u"%1 %2 %3"_qs.arg(description, tr("Removed torrent and deleted its content."), torrentName));
deleteTorrent(torrent->id(), DeleteTorrentAndFiles); deleteTorrent(torrent->id(), DeleteTorrentAndFiles);
} }
else if ((m_maxRatioAction == Pause) && !torrent->isPaused()) else if ((m_maxRatioAction == Pause) && !torrent->isPaused())
{ {
torrent->pause(); torrent->pause();
LogMsg(QString::fromLatin1("%1 %2 %3").arg(description, tr("Torrent paused."), torrentName)); LogMsg(u"%1 %2 %3"_qs.arg(description, tr("Torrent paused."), torrentName));
} }
else if ((m_maxRatioAction == EnableSuperSeeding) && !torrent->isPaused() && !torrent->superSeeding()) else if ((m_maxRatioAction == EnableSuperSeeding) && !torrent->isPaused() && !torrent->superSeeding())
{ {
torrent->setSuperSeeding(true); torrent->setSuperSeeding(true);
LogMsg(QString::fromLatin1("%1 %2 %3").arg(description, tr("Super seeding enabled."), torrentName)); LogMsg(u"%1 %2 %3"_qs.arg(description, tr("Super seeding enabled."), torrentName));
} }
} }
} }
@ -2448,13 +2448,13 @@ void Session::exportTorrentFile(const TorrentInfo &torrentInfo, const Path &fold
return; return;
const QString validName = Utils::Fs::toValidFileName(baseName); const QString validName = Utils::Fs::toValidFileName(baseName);
QString torrentExportFilename = QString::fromLatin1("%1.torrent").arg(validName); QString torrentExportFilename = u"%1.torrent"_qs.arg(validName);
Path newTorrentPath = folderPath / Path(torrentExportFilename); Path newTorrentPath = folderPath / Path(torrentExportFilename);
int counter = 0; int counter = 0;
while (newTorrentPath.exists()) while (newTorrentPath.exists())
{ {
// Append number to torrent name to make it unique // Append number to torrent name to make it unique
torrentExportFilename = QString::fromLatin1("%1 %2.torrent").arg(validName).arg(++counter); torrentExportFilename = u"%1 %2.torrent"_qs.arg(validName).arg(++counter);
newTorrentPath = folderPath / Path(torrentExportFilename); newTorrentPath = folderPath / Path(torrentExportFilename);
} }
@ -2626,8 +2626,8 @@ QStringList Session::getListeningIPs() const
const QString ifaceName = networkInterface(); const QString ifaceName = networkInterface();
const QString ifaceAddr = networkInterfaceAddress(); const QString ifaceAddr = networkInterfaceAddress();
const QHostAddress configuredAddr(ifaceAddr); const QHostAddress configuredAddr(ifaceAddr);
const bool allIPv4 = (ifaceAddr == QLatin1String("0.0.0.0")); // Means All IPv4 addresses const bool allIPv4 = (ifaceAddr == u"0.0.0.0"); // Means All IPv4 addresses
const bool allIPv6 = (ifaceAddr == QLatin1String("::")); // Means All IPv6 addresses const bool allIPv6 = (ifaceAddr == u"::"); // Means All IPv6 addresses
if (!ifaceAddr.isEmpty() && !allIPv4 && !allIPv6 && configuredAddr.isNull()) if (!ifaceAddr.isEmpty() && !allIPv4 && !allIPv6 && configuredAddr.isNull())
{ {
@ -2643,13 +2643,13 @@ QStringList Session::getListeningIPs() const
if (ifaceName.isEmpty()) if (ifaceName.isEmpty())
{ {
if (ifaceAddr.isEmpty()) if (ifaceAddr.isEmpty())
return {QLatin1String("0.0.0.0"), QLatin1String("::")}; // Indicates all interfaces + all addresses (aka default) return {u"0.0.0.0"_qs, u"::"_qs}; // Indicates all interfaces + all addresses (aka default)
if (allIPv4) if (allIPv4)
return {QLatin1String("0.0.0.0")}; return {u"0.0.0.0"_qs};
if (allIPv6) if (allIPv6)
return {QLatin1String("::")}; return {u"::"_qs};
} }
const auto checkAndAddIP = [allIPv4, allIPv6, &IPs](const QHostAddress &addr, const QHostAddress &match) const auto checkAndAddIP = [allIPv4, allIPv6, &IPs](const QHostAddress &addr, const QHostAddress &match)
@ -4160,7 +4160,7 @@ void Session::handleTorrentFinished(TorrentImpl *const torrent)
// Check if there are torrent files inside // Check if there are torrent files inside
for (const Path &torrentRelpath : asConst(torrent->filePaths())) for (const Path &torrentRelpath : asConst(torrent->filePaths()))
{ {
if (torrentRelpath.hasExtension(QLatin1String(".torrent"))) if (torrentRelpath.hasExtension(u".torrent"_qs))
{ {
qDebug("Found possible recursive torrent download."); qDebug("Found possible recursive torrent download.");
const Path torrentFullpath = torrent->actualStorageLocation() / torrentRelpath; const Path torrentFullpath = torrent->actualStorageLocation() / torrentRelpath;
@ -4458,7 +4458,7 @@ void Session::recursiveTorrentDownload(const TorrentID &id)
for (const Path &torrentRelpath : asConst(torrent->filePaths())) for (const Path &torrentRelpath : asConst(torrent->filePaths()))
{ {
if (torrentRelpath.hasExtension(QLatin1String(".torrent"))) if (torrentRelpath.hasExtension(u".torrent"_qs))
{ {
LogMsg(tr("Recursive download .torrent file within torrent. Source torrent: \"%1\". File: \"%2\"") LogMsg(tr("Recursive download .torrent file within torrent. Source torrent: \"%1\". File: \"%2\"")
.arg(torrent->name(), torrentRelpath.toString())); .arg(torrent->name(), torrentRelpath.toString()));

4
src/base/bittorrent/statistics.cpp

@ -93,7 +93,7 @@ void Statistics::save() const
if (!m_dirty || ((now - m_lastWrite) < SAVE_INTERVAL)) if (!m_dirty || ((now - m_lastWrite) < SAVE_INTERVAL))
return; return;
SettingsPtr s = Profile::instance()->applicationSettings(QLatin1String("qBittorrent-data")); SettingsPtr s = Profile::instance()->applicationSettings(u"qBittorrent-data"_qs);
QVariantHash v; QVariantHash v;
v.insert(u"AlltimeDL"_qs, m_alltimeDL + m_sessionDL); v.insert(u"AlltimeDL"_qs, m_alltimeDL + m_sessionDL);
v.insert(u"AlltimeUL"_qs, m_alltimeUL + m_sessionUL); v.insert(u"AlltimeUL"_qs, m_alltimeUL + m_sessionUL);
@ -104,7 +104,7 @@ void Statistics::save() const
void Statistics::load() void Statistics::load()
{ {
const SettingsPtr s = Profile::instance()->applicationSettings(QLatin1String("qBittorrent-data")); const SettingsPtr s = Profile::instance()->applicationSettings(u"qBittorrent-data"_qs);
const QVariantHash v = s->value(u"Stats/AllStats"_qs).toHash(); const QVariantHash v = s->value(u"Stats/AllStats"_qs).toHash();
m_alltimeDL = v[u"AlltimeDL"_qs].toULongLong(); m_alltimeDL = v[u"AlltimeDL"_qs].toULongLong();

8
src/base/bittorrent/torrentimpl.cpp

@ -317,7 +317,7 @@ TorrentImpl::TorrentImpl(Session *session, lt::session *nativeSession
const Path filepath = filePath(i); const Path filepath = filePath(i);
// Move "unwanted" files back to their original folder // Move "unwanted" files back to their original folder
const Path parentRelPath = filepath.parentPath(); const Path parentRelPath = filepath.parentPath();
if (parentRelPath.filename() == QLatin1String(".unwanted")) if (parentRelPath.filename() == u".unwanted")
{ {
const QString oldName = filepath.filename(); const QString oldName = filepath.filename();
const Path newRelPath = parentRelPath.parentPath(); const Path newRelPath = parentRelPath.parentPath();
@ -1050,10 +1050,8 @@ QString TorrentImpl::error() const
if (m_nativeStatus.flags & lt::torrent_flags::upload_mode) if (m_nativeStatus.flags & lt::torrent_flags::upload_mode)
{ {
const QString writeErrorStr = tr("Couldn't write to file."); return tr("Couldn't write to file. Reason: \"%1\". Torrent is now in \"upload only\" mode.")
const QString uploadModeStr = tr("Torrent is now in \"upload only\" mode."); .arg(QString::fromLocal8Bit(m_lastFileError.error.message().c_str()));
const QString errorMessage = tr("Reason:") + QLatin1Char(' ') + QString::fromLocal8Bit(m_lastFileError.error.message().c_str());
return QString::fromLatin1("%1 %2 %3").arg(writeErrorStr, errorMessage, uploadModeStr);
} }
return {}; return {};

4
src/base/http/connection.cpp

@ -176,11 +176,11 @@ bool Connection::acceptsGzipEncoding(QString codings)
if (list.isEmpty()) if (list.isEmpty())
return false; return false;
const bool canGzip = isCodingAvailable(list, QString::fromLatin1("gzip")); const bool canGzip = isCodingAvailable(list, u"gzip"_qs);
if (canGzip) if (canGzip)
return true; return true;
const bool canAny = isCodingAvailable(list, QString::fromLatin1("*")); const bool canAny = isCodingAvailable(list, u"*"_qs);
if (canAny) if (canAny)
return true; return true;

18
src/base/http/httperror.cpp

@ -28,6 +28,8 @@
#include "httperror.h" #include "httperror.h"
#include "base/global.h"
HTTPError::HTTPError(const int statusCode, const QString &statusText, const QString &message) HTTPError::HTTPError(const int statusCode, const QString &statusText, const QString &message)
: RuntimeError {message} : RuntimeError {message}
, m_statusCode {statusCode} , m_statusCode {statusCode}
@ -46,41 +48,41 @@ QString HTTPError::statusText() const
} }
BadRequestHTTPError::BadRequestHTTPError(const QString &message) BadRequestHTTPError::BadRequestHTTPError(const QString &message)
: HTTPError(400, QLatin1String("Bad Request"), message) : HTTPError(400, u"Bad Request"_qs, message)
{ {
} }
UnauthorizedHTTPError::UnauthorizedHTTPError(const QString &message) UnauthorizedHTTPError::UnauthorizedHTTPError(const QString &message)
: HTTPError(401, QLatin1String("Unauthorized"), message) : HTTPError(401, u"Unauthorized"_qs, message)
{ {
} }
ForbiddenHTTPError::ForbiddenHTTPError(const QString &message) ForbiddenHTTPError::ForbiddenHTTPError(const QString &message)
: HTTPError(403, QLatin1String("Forbidden"), message) : HTTPError(403, u"Forbidden"_qs, message)
{ {
} }
NotFoundHTTPError::NotFoundHTTPError(const QString &message) NotFoundHTTPError::NotFoundHTTPError(const QString &message)
: HTTPError(404, QLatin1String("Not Found"), message) : HTTPError(404, u"Not Found"_qs, message)
{ {
} }
MethodNotAllowedHTTPError::MethodNotAllowedHTTPError(const QString &message) MethodNotAllowedHTTPError::MethodNotAllowedHTTPError(const QString &message)
: HTTPError(405, QLatin1String("Method Not Allowed"), message) : HTTPError(405, u"Method Not Allowed"_qs, message)
{ {
} }
ConflictHTTPError::ConflictHTTPError(const QString &message) ConflictHTTPError::ConflictHTTPError(const QString &message)
: HTTPError(409, QLatin1String("Conflict"), message) : HTTPError(409, u"Conflict"_qs, message)
{ {
} }
UnsupportedMediaTypeHTTPError::UnsupportedMediaTypeHTTPError(const QString &message) UnsupportedMediaTypeHTTPError::UnsupportedMediaTypeHTTPError(const QString &message)
: HTTPError(415, QLatin1String("Unsupported Media Type"), message) : HTTPError(415, u"Unsupported Media Type"_qs, message)
{ {
} }
InternalServerErrorHTTPError::InternalServerErrorHTTPError(const QString &message) InternalServerErrorHTTPError::InternalServerErrorHTTPError(const QString &message)
: HTTPError(500, QLatin1String("Internal Server Error"), message) : HTTPError(500, u"Internal Server Error"_qs, message)
{ {
} }

8
src/base/http/requestparser.cpp

@ -193,7 +193,7 @@ bool RequestParser::parseRequestLine(const QString &line)
{ {
// [rfc7230] 3.1.1. Request Line // [rfc7230] 3.1.1. Request Line
const QRegularExpression re(QLatin1String("^([A-Z]+)\\s+(\\S+)\\s+HTTP\\/(\\d\\.\\d)$")); const QRegularExpression re(u"^([A-Z]+)\\s+(\\S+)\\s+HTTP\\/(\\d\\.\\d)$"_qs);
const QRegularExpressionMatch match = re.match(line); const QRegularExpressionMatch match = re.match(line);
if (!match.hasMatch()) if (!match.hasMatch())
@ -268,7 +268,7 @@ bool RequestParser::parsePostMessage(const QByteArray &data)
// [rfc2046] 5.1.1. Common Syntax // [rfc2046] 5.1.1. Common Syntax
// find boundary delimiter // find boundary delimiter
const QLatin1String boundaryFieldName("boundary="); const QString boundaryFieldName = u"boundary="_qs;
const int idx = contentType.indexOf(boundaryFieldName); const int idx = contentType.indexOf(boundaryFieldName);
if (idx < 0) if (idx < 0)
{ {
@ -347,8 +347,8 @@ bool RequestParser::parseFormData(const QByteArray &data)
} }
// pick data // pick data
const QLatin1String filename("filename"); const QString filename = u"filename"_qs;
const QLatin1String name("name"); const QString name = u"name"_qs;
if (headersMap.contains(filename)) if (headersMap.contains(filename))
{ {

5
src/base/http/responsebuilder.h

@ -28,6 +28,9 @@
#pragma once #pragma once
#include <QString>
#include "base/global.h"
#include "types.h" #include "types.h"
namespace Http namespace Http
@ -35,7 +38,7 @@ namespace Http
class ResponseBuilder class ResponseBuilder
{ {
public: public:
void status(uint code = 200, const QString &text = QLatin1String("OK")); void status(uint code = 200, const QString &text = u"OK"_qs);
void setHeader(const Header &header); void setHeader(const Header &header);
void print(const QString &text, const QString &type = CONTENT_TYPE_HTML); void print(const QString &text, const QString &type = CONTENT_TYPE_HTML);
void print(const QByteArray &data, const QString &type = CONTENT_TYPE_HTML); void print(const QByteArray &data, const QString &type = CONTENT_TYPE_HTML);

8
src/base/http/responsegenerator.cpp

@ -74,13 +74,13 @@ QString Http::httpDate()
// [RFC 7231] 7.1.1.1. Date/Time Formats // [RFC 7231] 7.1.1.1. Date/Time Formats
// example: "Sun, 06 Nov 1994 08:49:37 GMT" // example: "Sun, 06 Nov 1994 08:49:37 GMT"
return QLocale::c().toString(QDateTime::currentDateTimeUtc(), QLatin1String("ddd, dd MMM yyyy HH:mm:ss")) return QLocale::c().toString(QDateTime::currentDateTimeUtc(), u"ddd, dd MMM yyyy HH:mm:ss"_qs)
.append(QLatin1String(" GMT")); .append(u" GMT");
} }
void Http::compressContent(Response &response) void Http::compressContent(Response &response)
{ {
if (response.headers.value(HEADER_CONTENT_ENCODING) != QLatin1String("gzip")) if (response.headers.value(HEADER_CONTENT_ENCODING) != u"gzip")
return; return;
response.headers.remove(HEADER_CONTENT_ENCODING); response.headers.remove(HEADER_CONTENT_ENCODING);
@ -106,5 +106,5 @@ void Http::compressContent(Response &response)
return; return;
response.content = compressedData; response.content = compressedData;
response.headers[HEADER_CONTENT_ENCODING] = QLatin1String("gzip"); response.headers[HEADER_CONTENT_ENCODING] = u"gzip"_qs;
} }

2
src/base/http/types.h

@ -123,7 +123,7 @@ namespace Http
HeaderMap headers; HeaderMap headers;
QByteArray content; QByteArray content;
Response(uint code = 200, const QString &text = QLatin1String("OK")) Response(uint code = 200, const QString &text = u"OK"_qs)
: status {code, text} : status {code, text}
{ {
} }

2
src/base/net/downloadmanager.cpp

@ -226,7 +226,7 @@ bool Net::DownloadManager::hasSupportedScheme(const QString &url)
const QStringList schemes = instance()->m_networkManager.supportedSchemes(); const QStringList schemes = instance()->m_networkManager.supportedSchemes();
return std::any_of(schemes.cbegin(), schemes.cend(), [&url](const QString &scheme) return std::any_of(schemes.cbegin(), schemes.cend(), [&url](const QString &scheme)
{ {
return url.startsWith((scheme + QLatin1Char(':')), Qt::CaseInsensitive); return url.startsWith((scheme + u':'), Qt::CaseInsensitive);
}); });
} }

2
src/base/net/geoipmanager.cpp

@ -43,7 +43,7 @@
#include "downloadmanager.h" #include "downloadmanager.h"
#include "geoipdatabase.h" #include "geoipdatabase.h"
const QString DATABASE_URL = QStringLiteral("https://download.db-ip.com/free/dbip-country-lite-%1.mmdb.gz"); const QString DATABASE_URL = u"https://download.db-ip.com/free/dbip-country-lite-%1.mmdb.gz"_qs;
const QString GEODB_FOLDER = u"GeoDB"_qs; const QString GEODB_FOLDER = u"GeoDB"_qs;
const QString GEODB_FILENAME = u"dbip-country-lite.mmdb"_qs; const QString GEODB_FILENAME = u"dbip-country-lite.mmdb"_qs;

10
src/base/net/proxyconfigurationmanager.cpp

@ -60,7 +60,7 @@ ProxyConfigurationManager::ProxyConfigurationManager(QObject *parent)
m_config.type = m_storeProxyType.get(ProxyType::None); m_config.type = m_storeProxyType.get(ProxyType::None);
if ((m_config.type < ProxyType::None) || (m_config.type > ProxyType::SOCKS4)) if ((m_config.type < ProxyType::None) || (m_config.type > ProxyType::SOCKS4))
m_config.type = ProxyType::None; m_config.type = ProxyType::None;
m_config.ip = m_storeProxyIP.get(QLatin1String("0.0.0.0")); m_config.ip = m_storeProxyIP.get(u"0.0.0.0"_qs);
m_config.port = m_storeProxyPort.get(8080); m_config.port = m_storeProxyPort.get(8080);
m_config.username = m_storeProxyUsername; m_config.username = m_storeProxyUsername;
m_config.password = m_storeProxyPassword; m_config.password = m_storeProxyPassword;
@ -130,17 +130,17 @@ void ProxyConfigurationManager::configureProxy()
switch (m_config.type) switch (m_config.type)
{ {
case ProxyType::HTTP_PW: case ProxyType::HTTP_PW:
proxyStrHTTP = QString::fromLatin1("http://%1:%2@%3:%4").arg(m_config.username proxyStrHTTP = u"http://%1:%2@%3:%4"_qs.arg(m_config.username
, m_config.password, m_config.ip, QString::number(m_config.port)); , m_config.password, m_config.ip, QString::number(m_config.port));
break; break;
case ProxyType::HTTP: case ProxyType::HTTP:
proxyStrHTTP = QString::fromLatin1("http://%1:%2").arg(m_config.ip, QString::number(m_config.port)); proxyStrHTTP = u"http://%1:%2"_qs.arg(m_config.ip, QString::number(m_config.port));
break; break;
case ProxyType::SOCKS5: case ProxyType::SOCKS5:
proxyStrSOCK = QString::fromLatin1("%1:%2").arg(m_config.ip, QString::number(m_config.port)); proxyStrSOCK = u"%1:%2"_qs.arg(m_config.ip, QString::number(m_config.port));
break; break;
case ProxyType::SOCKS5_PW: case ProxyType::SOCKS5_PW:
proxyStrSOCK = QString::fromLatin1("%1:%2@%3:%4").arg(m_config.username proxyStrSOCK = u"%1:%2@%3:%4"_qs.arg(m_config.username
, m_config.password, m_config.ip, QString::number(m_config.port)); , m_config.password, m_config.ip, QString::number(m_config.port));
break; break;
default: default:

28
src/base/path.cpp

@ -38,6 +38,8 @@
#include <QMimeDatabase> #include <QMimeDatabase>
#include <QRegularExpression> #include <QRegularExpression>
#include "base/global.h"
#if defined(Q_OS_WIN) #if defined(Q_OS_WIN)
const Qt::CaseSensitivity CASE_SENSITIVITY = Qt::CaseInsensitive; const Qt::CaseSensitivity CASE_SENSITIVITY = Qt::CaseInsensitive;
#else #else
@ -74,11 +76,11 @@ bool Path::isValid() const
return false; return false;
#if defined(Q_OS_WIN) #if defined(Q_OS_WIN)
const QRegularExpression regex {QLatin1String("[:?\"*<>|]")}; const QRegularExpression regex {u"[:?\"*<>|]"_qs};
#elif defined(Q_OS_MACOS) #elif defined(Q_OS_MACOS)
const QRegularExpression regex {QLatin1String("[\\0:]")}; const QRegularExpression regex {u"[\\0:]"_qs};
#else #else
const QRegularExpression regex {QLatin1String("[\\0]")}; const QRegularExpression regex {u"[\\0]"_qs};
#endif #endif
return !m_pathStr.contains(regex); return !m_pathStr.contains(regex);
} }
@ -105,24 +107,24 @@ bool Path::exists() const
Path Path::rootItem() const Path Path::rootItem() const
{ {
const int slashIndex = m_pathStr.indexOf(QLatin1Char('/')); const int slashIndex = m_pathStr.indexOf(u'/');
if (slashIndex < 0) if (slashIndex < 0)
return *this; return *this;
if (slashIndex == 0) // *nix absolute path if (slashIndex == 0) // *nix absolute path
return createUnchecked(QLatin1String("/")); return createUnchecked(u"/"_qs);
return createUnchecked(m_pathStr.left(slashIndex)); return createUnchecked(m_pathStr.left(slashIndex));
} }
Path Path::parentPath() const Path Path::parentPath() const
{ {
const int slashIndex = m_pathStr.lastIndexOf(QLatin1Char('/')); const int slashIndex = m_pathStr.lastIndexOf(u'/');
if (slashIndex == -1) if (slashIndex == -1)
return {}; return {};
if (slashIndex == 0) // *nix absolute path if (slashIndex == 0) // *nix absolute path
return (m_pathStr.size() == 1) ? Path() : createUnchecked(QLatin1String("/")); return (m_pathStr.size() == 1) ? Path() : createUnchecked(u"/"_qs);
return createUnchecked(m_pathStr.left(slashIndex)); return createUnchecked(m_pathStr.left(slashIndex));
} }
@ -140,17 +142,17 @@ QString Path::extension() const
{ {
const QString suffix = QMimeDatabase().suffixForFileName(m_pathStr); const QString suffix = QMimeDatabase().suffixForFileName(m_pathStr);
if (!suffix.isEmpty()) if (!suffix.isEmpty())
return (QLatin1String(".") + suffix); return (u"." + suffix);
const int slashIndex = m_pathStr.lastIndexOf(QLatin1Char('/')); const int slashIndex = m_pathStr.lastIndexOf(u'/');
const auto filename = QStringView(m_pathStr).mid(slashIndex + 1); const auto filename = QStringView(m_pathStr).mid(slashIndex + 1);
const int dotIndex = filename.lastIndexOf(QLatin1Char('.'), -2); const int dotIndex = filename.lastIndexOf(u'.', -2);
return ((dotIndex == -1) ? QString() : filename.mid(dotIndex).toString()); return ((dotIndex == -1) ? QString() : filename.mid(dotIndex).toString());
} }
bool Path::hasExtension(const QString &ext) const bool Path::hasExtension(const QString &ext) const
{ {
Q_ASSERT(ext.startsWith(QLatin1Char('.')) && (ext.size() >= 2)); Q_ASSERT(ext.startsWith(u'.') && (ext.size() >= 2));
return m_pathStr.endsWith(ext, Qt::CaseInsensitive); return m_pathStr.endsWith(ext, Qt::CaseInsensitive);
} }
@ -160,7 +162,7 @@ bool Path::hasAncestor(const Path &other) const
if (other.isEmpty() || (m_pathStr.size() <= other.m_pathStr.size())) if (other.isEmpty() || (m_pathStr.size() <= other.m_pathStr.size()))
return false; return false;
return (m_pathStr[other.m_pathStr.size()] == QLatin1Char('/')) return (m_pathStr[other.m_pathStr.size()] == u'/')
&& m_pathStr.startsWith(other.m_pathStr, CASE_SENSITIVITY); && m_pathStr.startsWith(other.m_pathStr, CASE_SENSITIVITY);
} }
@ -300,7 +302,7 @@ Path operator/(const Path &lhs, const Path &rhs)
if (lhs.isEmpty()) if (lhs.isEmpty())
return rhs; return rhs;
return Path(lhs.m_pathStr + QLatin1Char('/') + rhs.m_pathStr); return Path(lhs.m_pathStr + u'/' + rhs.m_pathStr);
} }
Path operator+(const Path &lhs, const QString &rhs) Path operator+(const Path &lhs, const QString &rhs)

8
src/base/profile_p.cpp

@ -46,7 +46,7 @@ QString Private::Profile::configurationName() const
QString Private::Profile::configurationSuffix() const QString Private::Profile::configurationSuffix() const
{ {
return (m_configurationName.isEmpty() ? QString() : QLatin1Char('_') + m_configurationName); return (m_configurationName.isEmpty() ? QString() : (u'_' + m_configurationName));
} }
QString Private::Profile::profileName() const QString Private::Profile::profileName() const
@ -172,11 +172,11 @@ SettingsPtr Private::CustomProfile::applicationSettings(const QString &name) con
{ {
// here we force QSettings::IniFormat format always because we need it to be portable across platforms // here we force QSettings::IniFormat format always because we need it to be portable across platforms
#if defined(Q_OS_WIN) || defined(Q_OS_MACOS) #if defined(Q_OS_WIN) || defined(Q_OS_MACOS)
const char CONF_FILE_EXTENSION[] = ".ini"; const auto CONF_FILE_EXTENSION = u".ini"_qs;
#else #else
const char CONF_FILE_EXTENSION[] = ".conf"; const auto CONF_FILE_EXTENSION = u".conf"_qs;
#endif #endif
const Path settingsFilePath = configLocation() / Path(name + QLatin1String(CONF_FILE_EXTENSION)); const Path settingsFilePath = configLocation() / Path(name + CONF_FILE_EXTENSION);
return SettingsPtr(new QSettings(settingsFilePath.data(), QSettings::IniFormat)); return SettingsPtr(new QSettings(settingsFilePath.data(), QSettings::IniFormat));
} }

17
src/base/rss/rss_article.cpp

@ -33,6 +33,7 @@
#include <QJsonObject> #include <QJsonObject>
#include <QVariant> #include <QVariant>
#include "base/global.h"
#include "rss_feed.h" #include "rss_feed.h"
using namespace RSS; using namespace RSS;
@ -50,14 +51,14 @@ namespace
} }
} }
const QString Article::KeyId(QStringLiteral("id")); const QString Article::KeyId = u"id"_qs;
const QString Article::KeyDate(QStringLiteral("date")); const QString Article::KeyDate = u"date"_qs;
const QString Article::KeyTitle(QStringLiteral("title")); const QString Article::KeyTitle = u"title"_qs;
const QString Article::KeyAuthor(QStringLiteral("author")); const QString Article::KeyAuthor = u"author"_qs;
const QString Article::KeyDescription(QStringLiteral("description")); const QString Article::KeyDescription = u"description"_qs;
const QString Article::KeyTorrentURL(QStringLiteral("torrentURL")); const QString Article::KeyTorrentURL = u"torrentURL"_qs;
const QString Article::KeyLink(QStringLiteral("link")); const QString Article::KeyLink = u"link"_qs;
const QString Article::KeyIsRead(QStringLiteral("isRead")); const QString Article::KeyIsRead = u"isRead"_qs;
Article::Article(Feed *feed, const QVariantHash &varHash) Article::Article(Feed *feed, const QVariantHash &varHash)
: QObject(feed) : QObject(feed)

8
src/base/rss/rss_autodownloader.cpp

@ -58,8 +58,8 @@ struct ProcessingJob
QVariantHash articleData; QVariantHash articleData;
}; };
const QString CONF_FOLDER_NAME {QStringLiteral("rss")}; const QString CONF_FOLDER_NAME = u"rss"_qs;
const QString RULES_FILE_NAME {QStringLiteral("download_rules.json")}; const QString RULES_FILE_NAME = u"download_rules.json"_qs;
namespace namespace
{ {
@ -441,8 +441,8 @@ void AutoDownloader::loadRules(const QByteArray &data)
void AutoDownloader::loadRulesLegacy() void AutoDownloader::loadRulesLegacy()
{ {
const SettingsPtr settings = Profile::instance()->applicationSettings(QStringLiteral("qBittorrent-rss")); const SettingsPtr settings = Profile::instance()->applicationSettings(u"qBittorrent-rss"_qs);
const QVariantHash rules = settings->value(QStringLiteral("download_rules")).toHash(); const QVariantHash rules = settings->value(u"download_rules"_qs).toHash();
for (const QVariant &ruleVar : rules) for (const QVariant &ruleVar : rules)
{ {
const auto rule = AutoDownloadRule::fromLegacyDict(ruleVar.toHash()); const auto rule = AutoDownloadRule::fromLegacyDict(ruleVar.toHash());

38
src/base/rss/rss_autodownloadrule.cpp

@ -101,22 +101,22 @@ namespace
} }
} }
const QString Str_Name(QStringLiteral("name")); const QString Str_Name = u"name"_qs;
const QString Str_Enabled(QStringLiteral("enabled")); const QString Str_Enabled = u"enabled"_qs;
const QString Str_UseRegex(QStringLiteral("useRegex")); const QString Str_UseRegex = u"useRegex"_qs;
const QString Str_MustContain(QStringLiteral("mustContain")); const QString Str_MustContain = u"mustContain"_qs;
const QString Str_MustNotContain(QStringLiteral("mustNotContain")); const QString Str_MustNotContain = u"mustNotContain"_qs;
const QString Str_EpisodeFilter(QStringLiteral("episodeFilter")); const QString Str_EpisodeFilter = u"episodeFilter"_qs;
const QString Str_AffectedFeeds(QStringLiteral("affectedFeeds")); const QString Str_AffectedFeeds = u"affectedFeeds"_qs;
const QString Str_SavePath(QStringLiteral("savePath")); const QString Str_SavePath = u"savePath"_qs;
const QString Str_AssignedCategory(QStringLiteral("assignedCategory")); const QString Str_AssignedCategory = u"assignedCategory"_qs;
const QString Str_LastMatch(QStringLiteral("lastMatch")); const QString Str_LastMatch = u"lastMatch"_qs;
const QString Str_IgnoreDays(QStringLiteral("ignoreDays")); const QString Str_IgnoreDays = u"ignoreDays"_qs;
const QString Str_AddPaused(QStringLiteral("addPaused")); const QString Str_AddPaused = u"addPaused"_qs;
const QString Str_CreateSubfolder(QStringLiteral("createSubfolder")); const QString Str_CreateSubfolder = u"createSubfolder"_qs;
const QString Str_ContentLayout(QStringLiteral("torrentContentLayout")); const QString Str_ContentLayout = u"torrentContentLayout"_qs;
const QString Str_SmartFilter(QStringLiteral("smartFilter")); const QString Str_SmartFilter = u"smartFilter"_qs;
const QString Str_PreviouslyMatched(QStringLiteral("previouslyMatchedEpisodes")); const QString Str_PreviouslyMatched = u"previouslyMatchedEpisodes"_qs;
namespace RSS namespace RSS
{ {
@ -346,7 +346,7 @@ bool AutoDownloadRule::matchesEpisodeFilterExpression(const QString &articleTitl
} }
else else
{ // Single number { // Single number
const QString expStr {QString::fromLatin1("\\b(?:s0?%1[ -_\\.]?e0?%2|%1x0?%2)(?:\\D|\\b)").arg(season, episode)}; const QString expStr {u"\\b(?:s0?%1[ -_\\.]?e0?%2|%1x0?%2)(?:\\D|\\b)"_qs.arg(season, episode)};
if (cachedRegex(expStr).match(articleTitle).hasMatch()) if (cachedRegex(expStr).match(articleTitle).hasMatch())
return true; return true;
} }
@ -391,8 +391,8 @@ bool AutoDownloadRule::matchesSmartEpisodeFilter(const QString &articleTitle) co
// so we don't download those // so we don't download those
if (isRepack && isProper) if (isRepack && isProper)
{ {
m_dataPtr->lastComputedEpisodes.append(episodeStr + QLatin1String("-REPACK")); m_dataPtr->lastComputedEpisodes.append(episodeStr + u"-REPACK");
m_dataPtr->lastComputedEpisodes.append(episodeStr + QLatin1String("-PROPER")); m_dataPtr->lastComputedEpisodes.append(episodeStr + u"-PROPER");
} }
} }

30
src/base/rss/rss_feed.cpp

@ -51,13 +51,13 @@
#include "rss_parser.h" #include "rss_parser.h"
#include "rss_session.h" #include "rss_session.h"
const QString KEY_UID(QStringLiteral("uid")); const QString KEY_UID = u"uid"_qs;
const QString KEY_URL(QStringLiteral("url")); const QString KEY_URL = u"url"_qs;
const QString KEY_TITLE(QStringLiteral("title")); const QString KEY_TITLE = u"title"_qs;
const QString KEY_LASTBUILDDATE(QStringLiteral("lastBuildDate")); const QString KEY_LASTBUILDDATE = u"lastBuildDate"_qs;
const QString KEY_ISLOADING(QStringLiteral("isLoading")); const QString KEY_ISLOADING = u"isLoading"_qs;
const QString KEY_HASERROR(QStringLiteral("hasError")); const QString KEY_HASERROR = u"hasError"_qs;
const QString KEY_ARTICLES(QStringLiteral("articles")); const QString KEY_ARTICLES = u"articles"_qs;
using namespace RSS; using namespace RSS;
@ -68,16 +68,16 @@ Feed::Feed(const QUuid &uid, const QString &url, const QString &path, Session *s
, m_url(url) , m_url(url)
{ {
const auto uidHex = QString::fromLatin1(m_uid.toRfc4122().toHex()); const auto uidHex = QString::fromLatin1(m_uid.toRfc4122().toHex());
m_dataFileName = Path(uidHex + QLatin1String(".json")); m_dataFileName = Path(uidHex + u".json");
// Move to new file naming scheme (since v4.1.2) // Move to new file naming scheme (since v4.1.2)
const QString legacyFilename = Utils::Fs::toValidFileName(m_url, QLatin1String("_")) + QLatin1String(".json"); const QString legacyFilename = Utils::Fs::toValidFileName(m_url, u"_"_qs) + u".json";
const Path storageDir = m_session->dataFileStorage()->storageDir(); const Path storageDir = m_session->dataFileStorage()->storageDir();
const Path dataFilePath = storageDir / m_dataFileName; const Path dataFilePath = storageDir / m_dataFileName;
if (!dataFilePath.exists()) if (!dataFilePath.exists())
Utils::Fs::renameFile((storageDir / Path(legacyFilename)), dataFilePath); Utils::Fs::renameFile((storageDir / Path(legacyFilename)), dataFilePath);
m_iconPath = storageDir / Path(uidHex + QLatin1String(".ico")); m_iconPath = storageDir / Path(uidHex + u".ico");
m_parser = new Private::Parser(m_lastBuildDate); m_parser = new Private::Parser(m_lastBuildDate);
m_parser->moveToThread(m_session->workingThread()); m_parser->moveToThread(m_session->workingThread());
@ -323,16 +323,16 @@ void Feed::loadArticles(const QByteArray &data)
void Feed::loadArticlesLegacy() void Feed::loadArticlesLegacy()
{ {
const SettingsPtr qBTRSSFeeds = Profile::instance()->applicationSettings(QStringLiteral("qBittorrent-rss-feeds")); const SettingsPtr qBTRSSFeeds = Profile::instance()->applicationSettings(u"qBittorrent-rss-feeds"_qs);
const QVariantHash allOldItems = qBTRSSFeeds->value(u"old_items"_qs).toHash(); const QVariantHash allOldItems = qBTRSSFeeds->value(u"old_items"_qs).toHash();
for (const QVariant &var : asConst(allOldItems.value(m_url).toList())) for (const QVariant &var : asConst(allOldItems.value(m_url).toList()))
{ {
auto hash = var.toHash(); auto hash = var.toHash();
// update legacy keys // update legacy keys
hash[Article::KeyLink] = hash.take(QLatin1String("news_link")); hash[Article::KeyLink] = hash.take(u"news_link"_qs);
hash[Article::KeyTorrentURL] = hash.take(QLatin1String("torrent_url")); hash[Article::KeyTorrentURL] = hash.take(u"torrent_url"_qs);
hash[Article::KeyIsRead] = hash.take(QLatin1String("read")); hash[Article::KeyIsRead] = hash.take(u"read"_qs);
try try
{ {
auto article = new Article(this, hash); auto article = new Article(this, hash);
@ -425,7 +425,7 @@ void Feed::downloadIcon()
// Download the RSS Feed icon // Download the RSS Feed icon
// XXX: This works for most sites but it is not perfect // XXX: This works for most sites but it is not perfect
const QUrl url(m_url); const QUrl url(m_url);
const auto iconUrl = QString::fromLatin1("%1://%2/favicon.ico").arg(url.scheme(), url.host()); const auto iconUrl = u"%1://%2/favicon.ico"_qs.arg(url.scheme(), url.host());
Net::DownloadManager::instance()->download( Net::DownloadManager::instance()->download(
Net::DownloadRequest(iconUrl).saveToFile(true).destFileName(m_iconPath) Net::DownloadRequest(iconUrl).saveToFile(true).destFileName(m_iconPath)
, this, &Feed::handleIconDownloadFinished); , this, &Feed::handleIconDownloadFinished);

68
src/base/rss/rss_parser.cpp

@ -399,8 +399,8 @@ namespace
{ {
// Check that if date has '-' separators, both separators are '-'. // Check that if date has '-' separators, both separators are '-'.
parts = rxMatch.capturedTexts(); parts = rxMatch.capturedTexts();
const bool h1 = (parts[3] == QLatin1String("-")); const bool h1 = (parts[3] == u"-");
const bool h2 = (parts[5] == QLatin1String("-")); const bool h2 = (parts[5] == u"-");
if (h1 != h2) if (h1 != h2)
return QDateTime::currentDateTime(); return QDateTime::currentDateTime();
} }
@ -476,7 +476,7 @@ namespace
if (!ok[0] || !ok[1] || offsetMin > 59) if (!ok[0] || !ok[1] || offsetMin > 59)
return {}; return {};
offset += offsetMin * 60; offset += offsetMin * 60;
negOffset = (parts[1] == QLatin1String("-")); negOffset = (parts[1] == u"-");
if (negOffset) if (negOffset)
offset = -offset; offset = -offset;
} }
@ -564,12 +564,12 @@ void Parser::parse_impl(const QByteArray &feedData)
while (xml.readNextStartElement()) while (xml.readNextStartElement())
{ {
if (xml.name() == QLatin1String("rss")) if (xml.name() == u"rss")
{ {
// Find channels // Find channels
while (xml.readNextStartElement()) while (xml.readNextStartElement())
{ {
if (xml.name() == QLatin1String("channel")) if (xml.name() == u"channel")
{ {
parseRSSChannel(xml); parseRSSChannel(xml);
foundChannel = true; foundChannel = true;
@ -581,7 +581,7 @@ void Parser::parse_impl(const QByteArray &feedData)
} }
break; break;
} }
if (xml.name() == QLatin1String("feed")) if (xml.name() == u"feed")
{ // Atom feed { // Atom feed
parseAtomChannel(xml); parseAtomChannel(xml);
foundChannel = true; foundChannel = true;
@ -618,43 +618,43 @@ void Parser::parseRssArticle(QXmlStreamReader &xml)
xml.readNext(); xml.readNext();
const QString name(xml.name().toString()); const QString name(xml.name().toString());
if (xml.isEndElement() && (name == QLatin1String("item"))) if (xml.isEndElement() && (name == u"item"))
break; break;
if (xml.isStartElement()) if (xml.isStartElement())
{ {
if (name == QLatin1String("title")) if (name == u"title")
{ {
article[Article::KeyTitle] = xml.readElementText().trimmed(); article[Article::KeyTitle] = xml.readElementText().trimmed();
} }
else if (name == QLatin1String("enclosure")) else if (name == u"enclosure")
{ {
if (xml.attributes().value(u"type"_qs) == QLatin1String("application/x-bittorrent")) if (xml.attributes().value(u"type"_qs) == u"application/x-bittorrent")
article[Article::KeyTorrentURL] = xml.attributes().value(QLatin1String("url")).toString(); article[Article::KeyTorrentURL] = xml.attributes().value(u"url"_qs).toString();
else if (xml.attributes().value(u"type"_qs).isEmpty()) else if (xml.attributes().value(u"type"_qs).isEmpty())
altTorrentUrl = xml.attributes().value(QLatin1String("url")).toString(); altTorrentUrl = xml.attributes().value(u"url"_qs).toString();
} }
else if (name == QLatin1String("link")) else if (name == u"link")
{ {
const QString text {xml.readElementText().trimmed()}; const QString text {xml.readElementText().trimmed()};
if (text.startsWith(QLatin1String("magnet:"), Qt::CaseInsensitive)) if (text.startsWith(u"magnet:", Qt::CaseInsensitive))
article[Article::KeyTorrentURL] = text; // magnet link instead of a news URL article[Article::KeyTorrentURL] = text; // magnet link instead of a news URL
else else
article[Article::KeyLink] = text; article[Article::KeyLink] = text;
} }
else if (name == QLatin1String("description")) else if (name == u"description")
{ {
article[Article::KeyDescription] = xml.readElementText(QXmlStreamReader::IncludeChildElements); article[Article::KeyDescription] = xml.readElementText(QXmlStreamReader::IncludeChildElements);
} }
else if (name == QLatin1String("pubDate")) else if (name == u"pubDate")
{ {
article[Article::KeyDate] = parseDate(xml.readElementText().trimmed()); article[Article::KeyDate] = parseDate(xml.readElementText().trimmed());
} }
else if (name == QLatin1String("author")) else if (name == u"author")
{ {
article[Article::KeyAuthor] = xml.readElementText().trimmed(); article[Article::KeyAuthor] = xml.readElementText().trimmed();
} }
else if (name == QLatin1String("guid")) else if (name == u"guid")
{ {
article[Article::KeyId] = xml.readElementText().trimmed(); article[Article::KeyId] = xml.readElementText().trimmed();
} }
@ -679,11 +679,11 @@ void Parser::parseRSSChannel(QXmlStreamReader &xml)
if (xml.isStartElement()) if (xml.isStartElement())
{ {
if (xml.name() == QLatin1String("title")) if (xml.name() == u"title")
{ {
m_result.title = xml.readElementText(); m_result.title = xml.readElementText();
} }
else if (xml.name() == QLatin1String("lastBuildDate")) else if (xml.name() == u"lastBuildDate")
{ {
const QString lastBuildDate = xml.readElementText(); const QString lastBuildDate = xml.readElementText();
if (!lastBuildDate.isEmpty()) if (!lastBuildDate.isEmpty())
@ -696,7 +696,7 @@ void Parser::parseRSSChannel(QXmlStreamReader &xml)
m_result.lastBuildDate = lastBuildDate; m_result.lastBuildDate = lastBuildDate;
} }
} }
else if (xml.name() == QLatin1String("item")) else if (xml.name() == u"item")
{ {
parseRssArticle(xml); parseRssArticle(xml);
} }
@ -714,22 +714,22 @@ void Parser::parseAtomArticle(QXmlStreamReader &xml)
xml.readNext(); xml.readNext();
const QString name(xml.name().toString()); const QString name(xml.name().toString());
if (xml.isEndElement() && (name == QLatin1String("entry"))) if (xml.isEndElement() && (name == u"entry"))
break; break;
if (xml.isStartElement()) if (xml.isStartElement())
{ {
if (name == QLatin1String("title")) if (name == u"title")
{ {
article[Article::KeyTitle] = xml.readElementText().trimmed(); article[Article::KeyTitle] = xml.readElementText().trimmed();
} }
else if (name == QLatin1String("link")) else if (name == u"link")
{ {
const QString link = (xml.attributes().isEmpty() const QString link = (xml.attributes().isEmpty()
? xml.readElementText().trimmed() ? xml.readElementText().trimmed()
: xml.attributes().value(QLatin1String("href")).toString()); : xml.attributes().value(u"href"_qs).toString());
if (link.startsWith(QLatin1String("magnet:"), Qt::CaseInsensitive)) if (link.startsWith(u"magnet:", Qt::CaseInsensitive))
article[Article::KeyTorrentURL] = link; // magnet link instead of a news URL article[Article::KeyTorrentURL] = link; // magnet link instead of a news URL
else else
// Atom feeds can have relative links, work around this and // Atom feeds can have relative links, work around this and
@ -738,7 +738,7 @@ void Parser::parseAtomArticle(QXmlStreamReader &xml)
article[Article::KeyLink] = (m_baseUrl.isEmpty() ? link : m_baseUrl + link); article[Article::KeyLink] = (m_baseUrl.isEmpty() ? link : m_baseUrl + link);
} }
else if ((name == QLatin1String("summary")) || (name == QLatin1String("content"))) else if ((name == u"summary") || (name == u"content"))
{ {
if (doubleContent) if (doubleContent)
{ // Duplicate content -> ignore { // Duplicate content -> ignore
@ -755,23 +755,23 @@ void Parser::parseAtomArticle(QXmlStreamReader &xml)
doubleContent = true; doubleContent = true;
} }
} }
else if (name == QLatin1String("updated")) else if (name == u"updated")
{ {
// ATOM uses standard compliant date, don't do fancy stuff // ATOM uses standard compliant date, don't do fancy stuff
const QDateTime articleDate = QDateTime::fromString(xml.readElementText().trimmed(), Qt::ISODate); const QDateTime articleDate = QDateTime::fromString(xml.readElementText().trimmed(), Qt::ISODate);
article[Article::KeyDate] = (articleDate.isValid() ? articleDate : QDateTime::currentDateTime()); article[Article::KeyDate] = (articleDate.isValid() ? articleDate : QDateTime::currentDateTime());
} }
else if (name == QLatin1String("author")) else if (name == u"author")
{ {
while (xml.readNextStartElement()) while (xml.readNextStartElement())
{ {
if (xml.name() == QLatin1String("name")) if (xml.name() == u"name")
article[Article::KeyAuthor] = xml.readElementText().trimmed(); article[Article::KeyAuthor] = xml.readElementText().trimmed();
else else
xml.skipCurrentElement(); xml.skipCurrentElement();
} }
} }
else if (name == QLatin1String("id")) else if (name == u"id")
{ {
article[Article::KeyId] = xml.readElementText().trimmed(); article[Article::KeyId] = xml.readElementText().trimmed();
} }
@ -795,11 +795,11 @@ void Parser::parseAtomChannel(QXmlStreamReader &xml)
if (xml.isStartElement()) if (xml.isStartElement())
{ {
if (xml.name() == QLatin1String("title")) if (xml.name() == u"title")
{ {
m_result.title = xml.readElementText(); m_result.title = xml.readElementText();
} }
else if (xml.name() == QLatin1String("updated")) else if (xml.name() == u"updated")
{ {
const QString lastBuildDate = xml.readElementText(); const QString lastBuildDate = xml.readElementText();
if (!lastBuildDate.isEmpty()) if (!lastBuildDate.isEmpty())
@ -812,7 +812,7 @@ void Parser::parseAtomChannel(QXmlStreamReader &xml)
m_result.lastBuildDate = lastBuildDate; m_result.lastBuildDate = lastBuildDate;
} }
} }
else if (xml.name() == QLatin1String("entry")) else if (xml.name() == u"entry")
{ {
parseAtomArticle(xml); parseAtomArticle(xml);
} }

10
src/base/rss/rss_session.cpp

@ -49,9 +49,9 @@
#include "rss_item.h" #include "rss_item.h"
const int MsecsPerMin = 60000; const int MsecsPerMin = 60000;
const QString CONF_FOLDER_NAME(QStringLiteral("rss")); const QString CONF_FOLDER_NAME = u"rss"_qs;
const QString DATA_FOLDER_NAME(QStringLiteral("rss/articles")); const QString DATA_FOLDER_NAME = u"rss/articles"_qs;
const QString FEEDS_FILE_NAME(QStringLiteral("feeds.json")); const QString FEEDS_FILE_NAME = u"feeds.json"_qs;
using namespace RSS; using namespace RSS;
@ -326,7 +326,7 @@ void Session::loadFolder(const QJsonObject &jsonObj, Folder *folder)
else else
{ {
LogMsg(tr("Couldn't load RSS item. Item: \"%1\". Invalid data format.") LogMsg(tr("Couldn't load RSS item. Item: \"%1\". Invalid data format.")
.arg(QString::fromLatin1("%1\\%2").arg(folder->path(), key)), Log::WARNING); .arg(u"%1\\%2"_qs.arg(folder->path(), key)), Log::WARNING);
} }
} }
@ -347,7 +347,7 @@ void Session::loadLegacy()
uint i = 0; uint i = 0;
for (QString legacyPath : legacyFeedPaths) for (QString legacyPath : legacyFeedPaths)
{ {
if (Item::PathSeparator == QString(legacyPath[0])) if (Item::PathSeparator == legacyPath[0])
legacyPath.remove(0, 1); legacyPath.remove(0, 1);
const QString parentFolderPath = Item::parentPath(legacyPath); const QString parentFolderPath = Item::parentPath(legacyPath);
const QString feedUrl = Item::relativeName(legacyPath); const QString feedUrl = Item::relativeName(legacyPath);

18
src/base/search/searchpluginmanager.cpp

@ -64,7 +64,7 @@ namespace
for (const Path &dir : asConst(dirs)) for (const Path &dir : asConst(dirs))
{ {
// python 3: remove "__pycache__" folders // python 3: remove "__pycache__" folders
if (dir.filename() == QLatin1String("__pycache__")) if (dir.filename() == u"__pycache__")
{ {
Utils::Fs::removeDirRecursively(dir); Utils::Fs::removeDirRecursively(dir);
continue; continue;
@ -75,7 +75,7 @@ namespace
for (const QString &file : files) for (const QString &file : files)
{ {
const Path path {file}; const Path path {file};
if (path.hasExtension(QLatin1String(".pyc"))) if (path.hasExtension(u".pyc"_qs))
Utils::Fs::removeFile(path); Utils::Fs::removeFile(path);
} }
} }
@ -85,7 +85,7 @@ namespace
QPointer<SearchPluginManager> SearchPluginManager::m_instance = nullptr; QPointer<SearchPluginManager> SearchPluginManager::m_instance = nullptr;
SearchPluginManager::SearchPluginManager() SearchPluginManager::SearchPluginManager()
: m_updateUrl(QLatin1String("http://searchplugins.qbittorrent.org/nova3/engines/")) : m_updateUrl(u"http://searchplugins.qbittorrent.org/nova3/engines/"_qs)
{ {
Q_ASSERT(!m_instance); // only one instance is allowed Q_ASSERT(!m_instance); // only one instance is allowed
m_instance = this; m_instance = this;
@ -195,7 +195,7 @@ void SearchPluginManager::enablePlugin(const QString &name, const bool enabled)
// Updates shipped plugin // Updates shipped plugin
void SearchPluginManager::updatePlugin(const QString &name) void SearchPluginManager::updatePlugin(const QString &name)
{ {
installPlugin(QString::fromLatin1("%1%2.py").arg(m_updateUrl, name)); installPlugin(u"%1%2.py"_qs.arg(m_updateUrl, name));
} }
// Install or update plugin from file or url // Install or update plugin from file or url
@ -289,7 +289,7 @@ bool SearchPluginManager::uninstallPlugin(const QString &name)
// remove it from hard drive // remove it from hard drive
const Path pluginsPath = pluginsLocation(); const Path pluginsPath = pluginsLocation();
const QStringList filters {name + QLatin1String(".*")}; const QStringList filters {name + u".*"};
const QStringList files = QDir(pluginsPath.data()).entryList(filters, QDir::Files, QDir::Unsorted); const QStringList files = QDir(pluginsPath.data()).entryList(filters, QDir::Files, QDir::Unsorted);
for (const QString &file : files) for (const QString &file : files)
Utils::Fs::removeFile(pluginsPath / Path(file)); Utils::Fs::removeFile(pluginsPath / Path(file));
@ -305,14 +305,14 @@ void SearchPluginManager::updateIconPath(PluginInfo *const plugin)
if (!plugin) return; if (!plugin) return;
const Path pluginsPath = pluginsLocation(); const Path pluginsPath = pluginsLocation();
Path iconPath = pluginsPath / Path(plugin->name + QLatin1String(".png")); Path iconPath = pluginsPath / Path(plugin->name + u".png");
if (iconPath.exists()) if (iconPath.exists())
{ {
plugin->iconPath = iconPath; plugin->iconPath = iconPath;
} }
else else
{ {
iconPath = pluginsPath / Path(plugin->name + QLatin1String(".ico")); iconPath = pluginsPath / Path(plugin->name + u".ico");
if (iconPath.exists()) if (iconPath.exists())
plugin->iconPath = iconPath; plugin->iconPath = iconPath;
} }
@ -452,7 +452,7 @@ void SearchPluginManager::update()
QProcess nova; QProcess nova;
nova.setProcessEnvironment(QProcessEnvironment::systemEnvironment()); nova.setProcessEnvironment(QProcessEnvironment::systemEnvironment());
const QStringList params {(engineLocation() / Path(u"/nova2.py"_qs)).toString(), QLatin1String("--capabilities")}; const QStringList params {(engineLocation() / Path(u"/nova2.py"_qs)).toString(), u"--capabilities"_qs};
nova.start(Utils::ForeignApps::pythonInfo().executableName, params, QIODevice::ReadOnly); nova.start(Utils::ForeignApps::pythonInfo().executableName, params, QIODevice::ReadOnly);
nova.waitForFinished(); nova.waitForFinished();
@ -563,7 +563,7 @@ bool SearchPluginManager::isUpdateNeeded(const QString &pluginName, const Plugin
Path SearchPluginManager::pluginPath(const QString &name) Path SearchPluginManager::pluginPath(const QString &name)
{ {
return (pluginsLocation() / Path(name + QLatin1String(".py"))); return (pluginsLocation() / Path(name + u".py"));
} }
PluginVersion SearchPluginManager::getPluginVersion(const Path &filePath) PluginVersion SearchPluginManager::getPluginVersion(const Path &filePath)

2
src/base/settingvalue.h

@ -39,7 +39,7 @@ class SettingValue
{ {
public: public:
explicit SettingValue(const char *keyName) explicit SettingValue(const char *keyName)
: m_keyName {QLatin1String {keyName}} : m_keyName {QString::fromLatin1(keyName)}
{ {
} }

44
src/base/torrentfileswatcher.cpp

@ -66,25 +66,25 @@ using namespace std::chrono_literals;
const std::chrono::duration WATCH_INTERVAL = 10s; const std::chrono::duration WATCH_INTERVAL = 10s;
const int MAX_FAILED_RETRIES = 5; const int MAX_FAILED_RETRIES = 5;
const QString CONF_FILE_NAME {QStringLiteral("watched_folders.json")}; const QString CONF_FILE_NAME = u"watched_folders.json"_qs;
const QString OPTION_ADDTORRENTPARAMS {QStringLiteral("add_torrent_params")}; const QString OPTION_ADDTORRENTPARAMS = u"add_torrent_params"_qs;
const QString OPTION_RECURSIVE {QStringLiteral("recursive")}; const QString OPTION_RECURSIVE = u"recursive"_qs;
const QString PARAM_CATEGORY {QStringLiteral("category")}; const QString PARAM_CATEGORY = u"category"_qs;
const QString PARAM_TAGS {QStringLiteral("tags")}; const QString PARAM_TAGS = u"tags"_qs;
const QString PARAM_SAVEPATH {QStringLiteral("save_path")}; const QString PARAM_SAVEPATH = u"save_path"_qs;
const QString PARAM_USEDOWNLOADPATH {QStringLiteral("use_download_path")}; const QString PARAM_USEDOWNLOADPATH = u"use_download_path"_qs;
const QString PARAM_DOWNLOADPATH {QStringLiteral("download_path")}; const QString PARAM_DOWNLOADPATH = u"download_path"_qs;
const QString PARAM_OPERATINGMODE {QStringLiteral("operating_mode")}; const QString PARAM_OPERATINGMODE = u"operating_mode"_qs;
const QString PARAM_STOPPED {QStringLiteral("stopped")}; const QString PARAM_STOPPED = u"stopped"_qs;
const QString PARAM_SKIPCHECKING {QStringLiteral("skip_checking")}; const QString PARAM_SKIPCHECKING = u"skip_checking"_qs;
const QString PARAM_CONTENTLAYOUT {QStringLiteral("content_layout")}; const QString PARAM_CONTENTLAYOUT = u"content_layout"_qs;
const QString PARAM_AUTOTMM {QStringLiteral("use_auto_tmm")}; const QString PARAM_AUTOTMM = u"use_auto_tmm"_qs;
const QString PARAM_UPLOADLIMIT {QStringLiteral("upload_limit")}; const QString PARAM_UPLOADLIMIT = u"upload_limit"_qs;
const QString PARAM_DOWNLOADLIMIT {QStringLiteral("download_limit")}; const QString PARAM_DOWNLOADLIMIT = u"download_limit"_qs;
const QString PARAM_SEEDINGTIMELIMIT {QStringLiteral("seeding_time_limit")}; const QString PARAM_SEEDINGTIMELIMIT = u"seeding_time_limit"_qs;
const QString PARAM_RATIOLIMIT {QStringLiteral("ratio_limit")}; const QString PARAM_RATIOLIMIT = u"ratio_limit"_qs;
namespace namespace
{ {
@ -509,7 +509,7 @@ void TorrentFilesWatcher::Worker::processFolder(const Path &path, const Path &wa
if (useAutoTMM) if (useAutoTMM)
{ {
addTorrentParams.category = addTorrentParams.category.isEmpty() addTorrentParams.category = addTorrentParams.category.isEmpty()
? subdirPath.data() : (addTorrentParams.category + QLatin1Char('/') + subdirPath.data()); ? subdirPath.data() : (addTorrentParams.category + u'/' + subdirPath.data());
} }
else else
{ {
@ -517,7 +517,7 @@ void TorrentFilesWatcher::Worker::processFolder(const Path &path, const Path &wa
} }
} }
if (filePath.hasExtension(QLatin1String(".magnet"))) if (filePath.hasExtension(u".magnet"_qs))
{ {
QFile file {filePath.data()}; QFile file {filePath.data()};
if (file.open(QIODevice::ReadOnly | QIODevice::Text)) if (file.open(QIODevice::ReadOnly | QIODevice::Text))
@ -587,7 +587,7 @@ void TorrentFilesWatcher::Worker::processFailedTorrents()
if (useAutoTMM) if (useAutoTMM)
{ {
addTorrentParams.category = addTorrentParams.category.isEmpty() addTorrentParams.category = addTorrentParams.category.isEmpty()
? subdirPath.data() : (addTorrentParams.category + QLatin1Char('/') + subdirPath.data()); ? subdirPath.data() : (addTorrentParams.category + u'/' + subdirPath.data());
} }
else else
{ {

14
src/base/utils/fs.cpp

@ -80,12 +80,12 @@ bool Utils::Fs::smartRemoveEmptyFolderTree(const Path &path)
const QStringList deleteFilesList = const QStringList deleteFilesList =
{ {
// Windows // Windows
QLatin1String("Thumbs.db"), u"Thumbs.db"_qs,
QLatin1String("desktop.ini"), u"desktop.ini"_qs,
// Linux // Linux
QLatin1String(".directory"), u".directory"_qs,
// Mac OS // Mac OS
QLatin1String(".DS_Store") u".DS_Store"_qs
}; };
// travel from the deepest folder and remove anything unwanted on the way out. // travel from the deepest folder and remove anything unwanted on the way out.
@ -182,7 +182,7 @@ bool Utils::Fs::sameFiles(const Path &path1, const Path &path2)
QString Utils::Fs::toValidFileName(const QString &name, const QString &pad) QString Utils::Fs::toValidFileName(const QString &name, const QString &pad)
{ {
const QRegularExpression regex {QLatin1String("[\\\\/:?\"*<>|]+")}; const QRegularExpression regex {u"[\\\\/:?\"*<>|]+"_qs};
QString validName = name.trimmed(); QString validName = name.trimmed();
validName.replace(regex, pad); validName.replace(regex, pad);
@ -192,7 +192,7 @@ QString Utils::Fs::toValidFileName(const QString &name, const QString &pad)
Path Utils::Fs::toValidPath(const QString &name, const QString &pad) Path Utils::Fs::toValidPath(const QString &name, const QString &pad)
{ {
const QRegularExpression regex {QLatin1String("[:?\"*<>|]+")}; const QRegularExpression regex {u"[:?\"*<>|]+"_qs};
QString validPathStr = name; QString validPathStr = name;
validPathStr.replace(regex, pad); validPathStr.replace(regex, pad);
@ -238,7 +238,7 @@ bool Utils::Fs::isNetworkFileSystem(const Path &path)
return false; return false;
return (::GetDriveTypeW(volumePath.get()) == DRIVE_REMOTE); return (::GetDriveTypeW(volumePath.get()) == DRIVE_REMOTE);
#else #else
const QString file = path.toString() + QLatin1String("/."); const QString file = (path.toString() + u"/.");
struct statfs buf {}; struct statfs buf {};
if (statfs(file.toLocal8Bit().constData(), &buf) != 0) if (statfs(file.toLocal8Bit().constData(), &buf) != 0)
return false; return false;

5
src/base/utils/fs.h

@ -35,6 +35,7 @@
#include <QString> #include <QString>
#include "base/global.h"
#include "base/pathfwd.h" #include "base/pathfwd.h"
class QDateTime; class QDateTime;
@ -52,8 +53,8 @@ namespace Utils::Fs
QDateTime lastModified(const Path &path); QDateTime lastModified(const Path &path);
bool sameFiles(const Path &path1, const Path &path2); bool sameFiles(const Path &path1, const Path &path2);
QString toValidFileName(const QString &name, const QString &pad = QLatin1String(" ")); QString toValidFileName(const QString &name, const QString &pad = u" "_qs);
Path toValidPath(const QString &name, const QString &pad = QLatin1String(" ")); Path toValidPath(const QString &name, const QString &pad = u" "_qs);
Path toCanonicalPath(const Path &path); Path toCanonicalPath(const Path &path);
bool copyFile(const Path &from, const Path &to); bool copyFile(const Path &from, const Path &to);

4
src/base/utils/misc.cpp

@ -298,8 +298,8 @@ bool Utils::Misc::isPreviewable(const Path &filePath)
{ {
const QString mime = QMimeDatabase().mimeTypeForFile(filePath.data(), QMimeDatabase::MatchExtension).name(); const QString mime = QMimeDatabase().mimeTypeForFile(filePath.data(), QMimeDatabase::MatchExtension).name();
if (mime.startsWith(QLatin1String("audio"), Qt::CaseInsensitive) if (mime.startsWith(u"audio", Qt::CaseInsensitive)
|| mime.startsWith(QLatin1String("video"), Qt::CaseInsensitive)) || mime.startsWith(u"video", Qt::CaseInsensitive))
{ {
return true; return true;
} }

4
src/base/utils/net.cpp

@ -36,6 +36,8 @@
#include <QString> #include <QString>
#include <QVector> #include <QVector>
#include "base/global.h"
namespace Utils namespace Utils
{ {
namespace Net namespace Net
@ -65,7 +67,7 @@ namespace Utils
{ {
return (addr == QHostAddress::LocalHost) return (addr == QHostAddress::LocalHost)
|| (addr == QHostAddress::LocalHostIPv6) || (addr == QHostAddress::LocalHostIPv6)
|| (addr == QHostAddress(QLatin1String("::ffff:127.0.0.1"))); || (addr == QHostAddress(u"::ffff:127.0.0.1"_qs));
} }
bool isIPInRange(const QHostAddress &addr, const QVector<Subnet> &subnets) bool isIPInRange(const QHostAddress &addr, const QVector<Subnet> &subnets)

9
src/base/utils/version.h

@ -34,6 +34,7 @@
#include <QString> #include <QString>
#include "base/exceptions.h" #include "base/exceptions.h"
#include "base/global.h"
namespace Utils namespace Utils
{ {
@ -63,7 +64,7 @@ namespace Utils
* @throws RuntimeError if parsing fails * @throws RuntimeError if parsing fails
*/ */
Version(const QString &version) Version(const QString &version)
: Version {version.split(QLatin1Char('.'))} : Version {version.split(u'.')}
{ {
} }
@ -119,7 +120,7 @@ namespace Utils
QString res = QString::number((*this)[0]); QString res = QString::number((*this)[0]);
for (std::size_t i = 1; i <= lastSignificantIndex; ++i) for (std::size_t i = 1; i <= lastSignificantIndex; ++i)
res += QLatin1Char('.') + QString::number((*this)[i]); res += (u'.' + QString::number((*this)[i]));
return res; return res;
} }
@ -162,7 +163,7 @@ namespace Utils
if ((static_cast<std::size_t>(versionParts.size()) > N) if ((static_cast<std::size_t>(versionParts.size()) > N)
|| (static_cast<std::size_t>(versionParts.size()) < Mandatory)) || (static_cast<std::size_t>(versionParts.size()) < Mandatory))
{ {
throw RuntimeError(QLatin1String("Incorrect number of version components")); throw RuntimeError(u"Incorrect number of version components"_qs);
} }
bool ok = false; bool ok = false;
@ -171,7 +172,7 @@ namespace Utils
{ {
res[i] = static_cast<T>(versionParts[static_cast<typename StringsList::size_type>(i)].toInt(&ok)); res[i] = static_cast<T>(versionParts[static_cast<typename StringsList::size_type>(i)].toInt(&ok));
if (!ok) if (!ok)
throw RuntimeError(QLatin1String("Can not parse version component")); throw RuntimeError(u"Can not parse version component"_qs);
} }
return res; return res;
} }

2
src/webui/api/appcontroller.cpp

@ -637,7 +637,7 @@ void AppController::setPreferencesAction()
if (pref->getLocale() != locale) if (pref->getLocale() != locale)
{ {
auto *translator = new QTranslator; auto *translator = new QTranslator;
if (translator->load(QLatin1String(":/lang/qbittorrent_") + locale)) if (translator->load(u":/lang/qbittorrent_"_qs + locale))
{ {
qDebug("%s locale recognized, using translation.", qUtf8Printable(locale)); qDebug("%s locale recognized, using translation.", qUtf8Printable(locale));
} }

6
src/webui/api/authcontroller.cpp

@ -41,7 +41,7 @@ void AuthController::loginAction()
{ {
if (sessionManager()->session()) if (sessionManager()->session())
{ {
setResult(QLatin1String("Ok.")); setResult(u"Ok."_qs);
return; return;
} }
@ -70,14 +70,14 @@ void AuthController::loginAction()
m_clientFailedLogins.remove(clientAddr); m_clientFailedLogins.remove(clientAddr);
sessionManager()->sessionStart(); sessionManager()->sessionStart();
setResult(QLatin1String("Ok.")); setResult(u"Ok."_qs);
LogMsg(tr("WebAPI login success. IP: %1").arg(clientAddr)); LogMsg(tr("WebAPI login success. IP: %1").arg(clientAddr));
} }
else else
{ {
if (Preferences::instance()->getWebUIMaxAuthFailCount() > 0) if (Preferences::instance()->getWebUIMaxAuthFailCount() > 0)
increaseFailedAttempts(); increaseFailedAttempts();
setResult(QLatin1String("Fails.")); setResult(u"Fails."_qs);
LogMsg(tr("WebAPI login failure. Reason: invalid credentials, attempt count: %1, IP: %2, username: %3") LogMsg(tr("WebAPI login failure. Reason: invalid credentials, attempt count: %1, IP: %2, username: %3")
.arg(QString::number(failedAttemptsCount()), clientAddr, usernameFromWeb) .arg(QString::number(failedAttemptsCount()), clientAddr, usernameFromWeb)
, Log::WARNING); , Log::WARNING);

32
src/webui/api/logcontroller.cpp

@ -36,13 +36,13 @@
#include "base/logger.h" #include "base/logger.h"
#include "base/utils/string.h" #include "base/utils/string.h"
const char KEY_LOG_ID[] = "id"; const QString KEY_LOG_ID = u"id"_qs;
const char KEY_LOG_TIMESTAMP[] = "timestamp"; const QString KEY_LOG_TIMESTAMP = u"timestamp"_qs;
const char KEY_LOG_MSG_TYPE[] = "type"; const QString KEY_LOG_MSG_TYPE = u"type"_qs;
const char KEY_LOG_MSG_MESSAGE[] = "message"; const QString KEY_LOG_MSG_MESSAGE = u"message"_qs;
const char KEY_LOG_PEER_IP[] = "ip"; const QString KEY_LOG_PEER_IP = u"ip"_qs;
const char KEY_LOG_PEER_BLOCKED[] = "blocked"; const QString KEY_LOG_PEER_BLOCKED = u"blocked"_qs;
const char KEY_LOG_PEER_REASON[] = "reason"; const QString KEY_LOG_PEER_REASON = u"reason"_qs;
// Returns the log in JSON format. // Returns the log in JSON format.
// The return value is an array of dictionaries. // The return value is an array of dictionaries.
@ -84,10 +84,10 @@ void LogController::mainAction()
msgList.append(QJsonObject msgList.append(QJsonObject
{ {
{QLatin1String(KEY_LOG_ID), msg.id}, {KEY_LOG_ID, msg.id},
{QLatin1String(KEY_LOG_TIMESTAMP), msg.timestamp}, {KEY_LOG_TIMESTAMP, msg.timestamp},
{QLatin1String(KEY_LOG_MSG_TYPE), msg.type}, {KEY_LOG_MSG_TYPE, msg.type},
{QLatin1String(KEY_LOG_MSG_MESSAGE), msg.message} {KEY_LOG_MSG_MESSAGE, msg.message}
}); });
} }
@ -118,11 +118,11 @@ void LogController::peersAction()
{ {
peerList.append(QJsonObject peerList.append(QJsonObject
{ {
{QLatin1String(KEY_LOG_ID), peer.id}, {KEY_LOG_ID, peer.id},
{QLatin1String(KEY_LOG_TIMESTAMP), peer.timestamp}, {KEY_LOG_TIMESTAMP, peer.timestamp},
{QLatin1String(KEY_LOG_PEER_IP), peer.ip}, {KEY_LOG_PEER_IP, peer.ip},
{QLatin1String(KEY_LOG_PEER_BLOCKED), peer.blocked}, {KEY_LOG_PEER_BLOCKED, peer.blocked},
{QLatin1String(KEY_LOG_PEER_REASON), peer.reason} {KEY_LOG_PEER_REASON, peer.reason}
}); });
} }

12
src/webui/api/searchcontroller.cpp

@ -50,8 +50,8 @@ using SearchHandlerDict = QMap<int, SearchHandlerPtr>;
namespace namespace
{ {
const QLatin1String ACTIVE_SEARCHES("activeSearches"); const QString ACTIVE_SEARCHES = u"activeSearches"_qs;
const QLatin1String SEARCH_HANDLERS("searchHandlers"); const QString SEARCH_HANDLERS = u"searchHandlers"_qs;
void removeActiveSearch(ISession *session, const int id) void removeActiveSearch(ISession *session, const int id)
{ {
@ -72,8 +72,8 @@ namespace
{ {
QJsonArray categoriesInfo QJsonArray categoriesInfo
{QJsonObject { {QJsonObject {
{QLatin1String("id"), u"all"_qs}, {u"id"_qs, u"all"_qs},
{QLatin1String("name"), SearchPluginManager::categoryFullName(u"all"_qs)} {u"name"_qs, SearchPluginManager::categoryFullName(u"all"_qs)}
}}; }};
categories.sort(Qt::CaseInsensitive); categories.sort(Qt::CaseInsensitive);
@ -81,8 +81,8 @@ namespace
{ {
categoriesInfo << QJsonObject categoriesInfo << QJsonObject
{ {
{QLatin1String("id"), category}, {u"id"_qs, category},
{QLatin1String("name"), SearchPluginManager::categoryFullName(category)} {u"name"_qs, SearchPluginManager::categoryFullName(category)}
}; };
} }

40
src/webui/api/serialize/serialize_torrent.cpp

@ -45,43 +45,43 @@ namespace
switch (state) switch (state)
{ {
case BitTorrent::TorrentState::Error: case BitTorrent::TorrentState::Error:
return QLatin1String("error"); return u"error"_qs;
case BitTorrent::TorrentState::MissingFiles: case BitTorrent::TorrentState::MissingFiles:
return QLatin1String("missingFiles"); return u"missingFiles"_qs;
case BitTorrent::TorrentState::Uploading: case BitTorrent::TorrentState::Uploading:
return QLatin1String("uploading"); return u"uploading"_qs;
case BitTorrent::TorrentState::PausedUploading: case BitTorrent::TorrentState::PausedUploading:
return QLatin1String("pausedUP"); return u"pausedUP"_qs;
case BitTorrent::TorrentState::QueuedUploading: case BitTorrent::TorrentState::QueuedUploading:
return QLatin1String("queuedUP"); return u"queuedUP"_qs;
case BitTorrent::TorrentState::StalledUploading: case BitTorrent::TorrentState::StalledUploading:
return QLatin1String("stalledUP"); return u"stalledUP"_qs;
case BitTorrent::TorrentState::CheckingUploading: case BitTorrent::TorrentState::CheckingUploading:
return QLatin1String("checkingUP"); return u"checkingUP"_qs;
case BitTorrent::TorrentState::ForcedUploading: case BitTorrent::TorrentState::ForcedUploading:
return QLatin1String("forcedUP"); return u"forcedUP"_qs;
case BitTorrent::TorrentState::Downloading: case BitTorrent::TorrentState::Downloading:
return QLatin1String("downloading"); return u"downloading"_qs;
case BitTorrent::TorrentState::DownloadingMetadata: case BitTorrent::TorrentState::DownloadingMetadata:
return QLatin1String("metaDL"); return u"metaDL"_qs;
case BitTorrent::TorrentState::ForcedDownloadingMetadata: case BitTorrent::TorrentState::ForcedDownloadingMetadata:
return QLatin1String("forcedMetaDL"); return u"forcedMetaDL"_qs;
case BitTorrent::TorrentState::PausedDownloading: case BitTorrent::TorrentState::PausedDownloading:
return QLatin1String("pausedDL"); return u"pausedDL"_qs;
case BitTorrent::TorrentState::QueuedDownloading: case BitTorrent::TorrentState::QueuedDownloading:
return QLatin1String("queuedDL"); return u"queuedDL"_qs;
case BitTorrent::TorrentState::StalledDownloading: case BitTorrent::TorrentState::StalledDownloading:
return QLatin1String("stalledDL"); return u"stalledDL"_qs;
case BitTorrent::TorrentState::CheckingDownloading: case BitTorrent::TorrentState::CheckingDownloading:
return QLatin1String("checkingDL"); return u"checkingDL"_qs;
case BitTorrent::TorrentState::ForcedDownloading: case BitTorrent::TorrentState::ForcedDownloading:
return QLatin1String("forcedDL"); return u"forcedDL"_qs;
case BitTorrent::TorrentState::CheckingResumeData: case BitTorrent::TorrentState::CheckingResumeData:
return QLatin1String("checkingResumeData"); return u"checkingResumeData"_qs;
case BitTorrent::TorrentState::Moving: case BitTorrent::TorrentState::Moving:
return QLatin1String("moving"); return u"moving"_qs;
default: default:
return QLatin1String("unknown"); return u"unknown"_qs;
} }
} }
} }
@ -128,7 +128,7 @@ QVariantMap serialize(const BitTorrent::Torrent &torrent)
{KEY_TORRENT_FIRST_LAST_PIECE_PRIO, torrent.hasFirstLastPiecePriority()}, {KEY_TORRENT_FIRST_LAST_PIECE_PRIO, torrent.hasFirstLastPiecePriority()},
{KEY_TORRENT_CATEGORY, torrent.category()}, {KEY_TORRENT_CATEGORY, torrent.category()},
{KEY_TORRENT_TAGS, torrent.tags().join(QLatin1String(", "))}, {KEY_TORRENT_TAGS, torrent.tags().join(u", "_qs)},
{KEY_TORRENT_SUPER_SEEDING, torrent.superSeeding()}, {KEY_TORRENT_SUPER_SEEDING, torrent.superSeeding()},
{KEY_TORRENT_FORCE_START, torrent.isForced()}, {KEY_TORRENT_FORCE_START, torrent.isForced()},
{KEY_TORRENT_SAVE_PATH, torrent.savePath().toString()}, {KEY_TORRENT_SAVE_PATH, torrent.savePath().toString()},

26
src/webui/api/synccontroller.cpp

@ -140,10 +140,10 @@ namespace
map[KEY_TRANSFER_WRITE_CACHE_OVERLOAD] = ((sessionStatus.diskWriteQueue > 0) && (sessionStatus.peersCount > 0)) map[KEY_TRANSFER_WRITE_CACHE_OVERLOAD] = ((sessionStatus.diskWriteQueue > 0) && (sessionStatus.peersCount > 0))
? Utils::String::fromDouble((100. * sessionStatus.diskWriteQueue / sessionStatus.peersCount), 2) ? Utils::String::fromDouble((100. * sessionStatus.diskWriteQueue / sessionStatus.peersCount), 2)
: QLatin1String("0"); : u"0"_qs;
map[KEY_TRANSFER_READ_CACHE_OVERLOAD] = ((sessionStatus.diskReadQueue > 0) && (sessionStatus.peersCount > 0)) map[KEY_TRANSFER_READ_CACHE_OVERLOAD] = ((sessionStatus.diskReadQueue > 0) && (sessionStatus.peersCount > 0))
? Utils::String::fromDouble((100. * sessionStatus.diskReadQueue / sessionStatus.peersCount), 2) ? Utils::String::fromDouble((100. * sessionStatus.diskReadQueue / sessionStatus.peersCount), 2)
: QLatin1String("0"); : u"0"_qs;
map[KEY_TRANSFER_QUEUED_IO_JOBS] = cacheStatus.jobQueueLength; map[KEY_TRANSFER_QUEUED_IO_JOBS] = cacheStatus.jobQueueLength;
map[KEY_TRANSFER_AVERAGE_TIME_QUEUE] = cacheStatus.averageJobTime; map[KEY_TRANSFER_AVERAGE_TIME_QUEUE] = cacheStatus.averageJobTime;
@ -456,8 +456,8 @@ void SyncController::maindataAction()
QVariantMap data; QVariantMap data;
QVariantMap lastResponse = sessionManager()->session()->getData(QLatin1String("syncMainDataLastResponse")).toMap(); QVariantMap lastResponse = sessionManager()->session()->getData(u"syncMainDataLastResponse"_qs).toMap();
QVariantMap lastAcceptedResponse = sessionManager()->session()->getData(QLatin1String("syncMainDataLastAcceptedResponse")).toMap(); QVariantMap lastAcceptedResponse = sessionManager()->session()->getData(u"syncMainDataLastAcceptedResponse"_qs).toMap();
QVariantHash torrents; QVariantHash torrents;
QHash<QString, QStringList> trackers; QHash<QString, QStringList> trackers;
@ -504,8 +504,8 @@ void SyncController::maindataAction()
const BitTorrent::CategoryOptions categoryOptions = session->categoryOptions(categoryName); const BitTorrent::CategoryOptions categoryOptions = session->categoryOptions(categoryName);
QJsonObject category = categoryOptions.toJSON(); QJsonObject category = categoryOptions.toJSON();
// adjust it to be compatible with exisitng WebAPI // adjust it to be compatible with exisitng WebAPI
category[QLatin1String("savePath")] = category.take(QLatin1String("save_path")); category[u"savePath"_qs] = category.take(u"save_path"_qs);
category.insert(QLatin1String("name"), categoryName); category.insert(u"name"_qs, categoryName);
categories[categoryName] = category.toVariantMap(); categories[categoryName] = category.toVariantMap();
} }
data[u"categories"_qs] = categories; data[u"categories"_qs] = categories;
@ -532,8 +532,8 @@ void SyncController::maindataAction()
const int acceptedResponseId {params()[u"rid"_qs].toInt()}; const int acceptedResponseId {params()[u"rid"_qs].toInt()};
setResult(QJsonObject::fromVariantMap(generateSyncData(acceptedResponseId, data, lastAcceptedResponse, lastResponse))); setResult(QJsonObject::fromVariantMap(generateSyncData(acceptedResponseId, data, lastAcceptedResponse, lastResponse)));
sessionManager()->session()->setData(QLatin1String("syncMainDataLastResponse"), lastResponse); sessionManager()->session()->setData(u"syncMainDataLastResponse"_qs, lastResponse);
sessionManager()->session()->setData(QLatin1String("syncMainDataLastAcceptedResponse"), lastAcceptedResponse); sessionManager()->session()->setData(u"syncMainDataLastAcceptedResponse"_qs, lastAcceptedResponse);
} }
// GET param: // GET param:
@ -541,8 +541,8 @@ void SyncController::maindataAction()
// - rid (int): last response id // - rid (int): last response id
void SyncController::torrentPeersAction() void SyncController::torrentPeersAction()
{ {
auto lastResponse = sessionManager()->session()->getData(QLatin1String("syncTorrentPeersLastResponse")).toMap(); auto lastResponse = sessionManager()->session()->getData(u"syncTorrentPeersLastResponse"_qs).toMap();
auto lastAcceptedResponse = sessionManager()->session()->getData(QLatin1String("syncTorrentPeersLastAcceptedResponse")).toMap(); auto lastAcceptedResponse = sessionManager()->session()->getData(u"syncTorrentPeersLastAcceptedResponse"_qs).toMap();
const auto id = BitTorrent::TorrentID::fromString(params()[u"hash"_qs]); const auto id = BitTorrent::TorrentID::fromString(params()[u"hash"_qs]);
const BitTorrent::Torrent *torrent = BitTorrent::Session::instance()->findTorrent(id); const BitTorrent::Torrent *torrent = BitTorrent::Session::instance()->findTorrent(id);
@ -585,7 +585,7 @@ void SyncController::torrentPeersAction()
filesForPiece.reserve(filePaths.size()); filesForPiece.reserve(filePaths.size());
for (const Path &filePath : filePaths) for (const Path &filePath : filePaths)
filesForPiece.append(filePath.toString()); filesForPiece.append(filePath.toString());
peer.insert(KEY_PEER_FILES, filesForPiece.join(QLatin1Char('\n'))); peer.insert(KEY_PEER_FILES, filesForPiece.join(u'\n'));
} }
if (resolvePeerCountries) if (resolvePeerCountries)
@ -601,8 +601,8 @@ void SyncController::torrentPeersAction()
const int acceptedResponseId {params()[u"rid"_qs].toInt()}; const int acceptedResponseId {params()[u"rid"_qs].toInt()};
setResult(QJsonObject::fromVariantMap(generateSyncData(acceptedResponseId, data, lastAcceptedResponse, lastResponse))); setResult(QJsonObject::fromVariantMap(generateSyncData(acceptedResponseId, data, lastAcceptedResponse, lastResponse)));
sessionManager()->session()->setData(QLatin1String("syncTorrentPeersLastResponse"), lastResponse); sessionManager()->session()->setData(u"syncTorrentPeersLastResponse"_qs, lastResponse);
sessionManager()->session()->setData(QLatin1String("syncTorrentPeersLastAcceptedResponse"), lastAcceptedResponse); sessionManager()->session()->setData(u"syncTorrentPeersLastAcceptedResponse"_qs, lastAcceptedResponse);
} }
qint64 SyncController::getFreeDiskSpace() qint64 SyncController::getFreeDiskSpace()

16
src/webui/api/torrentscontroller.cpp

@ -123,7 +123,7 @@ namespace
void applyToTorrents(const QStringList &idList, const std::function<void (BitTorrent::Torrent *torrent)> &func) void applyToTorrents(const QStringList &idList, const std::function<void (BitTorrent::Torrent *torrent)> &func)
{ {
if ((idList.size() == 1) && (idList[0] == QLatin1String("all"))) if ((idList.size() == 1) && (idList[0] == u"all"))
{ {
for (BitTorrent::Torrent *const torrent : asConst(BitTorrent::Session::instance()->torrents())) for (BitTorrent::Torrent *const torrent : asConst(BitTorrent::Session::instance()->torrents()))
func(torrent); func(torrent);
@ -264,8 +264,8 @@ namespace
void TorrentsController::infoAction() void TorrentsController::infoAction()
{ {
const QString filter {params()[u"filter"_qs]}; const QString filter {params()[u"filter"_qs]};
const std::optional<QString> category = getOptionalString(params(), QLatin1String("category")); const std::optional<QString> category = getOptionalString(params(), u"category"_qs);
const std::optional<QString> tag = getOptionalString(params(), QLatin1String("tag")); const std::optional<QString> tag = getOptionalString(params(), u"tag"_qs);
const QString sortedColumn {params()[u"sort"_qs]}; const QString sortedColumn {params()[u"sort"_qs]};
const bool reverse {parseBool(params()[u"reverse"_qs]).value_or(false)}; const bool reverse {parseBool(params()[u"reverse"_qs]).value_or(false)};
int limit {params()[u"limit"_qs].toInt()}; int limit {params()[u"limit"_qs].toInt()};
@ -537,7 +537,7 @@ void TorrentsController::filesAction()
const int filesCount = torrent->filesCount(); const int filesCount = torrent->filesCount();
QVector<int> fileIndexes; QVector<int> fileIndexes;
const auto idxIt = params().constFind(QLatin1String("indexes")); const auto idxIt = params().constFind(u"indexes"_qs);
if (idxIt != params().cend()) if (idxIt != params().cend())
{ {
const QStringList indexStrings = idxIt.value().split(u'|'); const QStringList indexStrings = idxIt.value().split(u'|');
@ -730,9 +730,9 @@ void TorrentsController::addAction()
} }
if (partialSuccess) if (partialSuccess)
setResult(QLatin1String("Ok.")); setResult(u"Ok."_qs);
else else
setResult(QLatin1String("Fails.")); setResult(u"Fails."_qs);
} }
void TorrentsController::addTrackersAction() void TorrentsController::addTrackersAction()
@ -1293,8 +1293,8 @@ void TorrentsController::categoriesAction()
const BitTorrent::CategoryOptions categoryOptions = session->categoryOptions(categoryName); const BitTorrent::CategoryOptions categoryOptions = session->categoryOptions(categoryName);
QJsonObject category = categoryOptions.toJSON(); QJsonObject category = categoryOptions.toJSON();
// adjust it to be compatible with exisitng WebAPI // adjust it to be compatible with exisitng WebAPI
category[QLatin1String("savePath")] = category.take(QLatin1String("save_path")); category[u"savePath"_qs] = category.take(u"save_path"_qs);
category.insert(QLatin1String("name"), categoryName); category.insert(u"name"_qs, categoryName);
categories[categoryName] = category; categories[categoryName] = category;
} }

4
src/webui/api/transfercontroller.cpp

@ -71,9 +71,9 @@ void TransferController::infoAction()
dict[KEY_TRANSFER_UPRATELIMIT] = BitTorrent::Session::instance()->uploadSpeedLimit(); dict[KEY_TRANSFER_UPRATELIMIT] = BitTorrent::Session::instance()->uploadSpeedLimit();
dict[KEY_TRANSFER_DHT_NODES] = static_cast<qint64>(sessionStatus.dhtNodes); dict[KEY_TRANSFER_DHT_NODES] = static_cast<qint64>(sessionStatus.dhtNodes);
if (!BitTorrent::Session::instance()->isListening()) if (!BitTorrent::Session::instance()->isListening())
dict[KEY_TRANSFER_CONNECTION_STATUS] = QLatin1String("disconnected"); dict[KEY_TRANSFER_CONNECTION_STATUS] = u"disconnected"_qs;
else else
dict[KEY_TRANSFER_CONNECTION_STATUS] = QLatin1String(sessionStatus.hasIncomingConnections ? "connected" : "firewalled"); dict[KEY_TRANSFER_CONNECTION_STATUS] = sessionStatus.hasIncomingConnections ? u"connected"_qs : u"firewalled"_qs;
setResult(dict); setResult(dict);
} }

79
src/webui/webapplication.cpp

@ -65,10 +65,10 @@
const int MAX_ALLOWED_FILESIZE = 10 * 1024 * 1024; const int MAX_ALLOWED_FILESIZE = 10 * 1024 * 1024;
const auto C_SID = QByteArrayLiteral("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 PATH_PREFIX_ICONS = u"/icons/"_qs;
const QString WWW_FOLDER {QStringLiteral(":/www")}; const QString WWW_FOLDER = u":/www"_qs;
const QString PUBLIC_FOLDER {QStringLiteral("/public")}; const QString PUBLIC_FOLDER = u"/public"_qs;
const QString PRIVATE_FOLDER {QStringLiteral("/private")}; const QString PRIVATE_FOLDER = u"/private"_qs;
namespace namespace
{ {
@ -93,8 +93,8 @@ namespace
QUrl urlFromHostHeader(const QString &hostHeader) QUrl urlFromHostHeader(const QString &hostHeader)
{ {
if (!hostHeader.contains(QLatin1String("://"))) if (!hostHeader.contains(u"://"))
return {QLatin1String("http://") + hostHeader}; return {u"http://"_qs + hostHeader};
return hostHeader; return hostHeader;
} }
@ -102,17 +102,17 @@ namespace
{ {
contentType = contentType.toLower(); contentType = contentType.toLower();
if (contentType.startsWith(QLatin1String("image/"))) if (contentType.startsWith(u"image/"))
return QLatin1String("private, max-age=604800"); // 1 week return u"private, max-age=604800"_qs; // 1 week
if ((contentType == Http::CONTENT_TYPE_CSS) if ((contentType == Http::CONTENT_TYPE_CSS)
|| (contentType == Http::CONTENT_TYPE_JS)) || (contentType == Http::CONTENT_TYPE_JS))
{ {
// short interval in case of program update // short interval in case of program update
return QLatin1String("private, max-age=43200"); // 12 hrs return u"private, max-age=43200"_qs; // 12 hrs
} }
return QLatin1String("no-store"); return u"no-store"_qs;
} }
} }
@ -120,16 +120,16 @@ WebApplication::WebApplication(QObject *parent)
: QObject(parent) : QObject(parent)
, m_cacheID {QString::number(Utils::Random::rand(), 36)} , m_cacheID {QString::number(Utils::Random::rand(), 36)}
{ {
registerAPIController(QLatin1String("app"), new AppController(this, this)); registerAPIController(u"app"_qs, new AppController(this, this));
registerAPIController(QLatin1String("auth"), new AuthController(this, this)); registerAPIController(u"auth"_qs, new AuthController(this, this));
registerAPIController(QLatin1String("log"), new LogController(this, this)); registerAPIController(u"log"_qs, new LogController(this, this));
registerAPIController(QLatin1String("rss"), new RSSController(this, this)); registerAPIController(u"rss"_qs, new RSSController(this, this));
registerAPIController(QLatin1String("search"), new SearchController(this, this)); registerAPIController(u"search"_qs, new SearchController(this, this));
registerAPIController(QLatin1String("sync"), new SyncController(this, this)); registerAPIController(u"sync"_qs, new SyncController(this, this));
registerAPIController(QLatin1String("torrents"), new TorrentsController(this, this)); registerAPIController(u"torrents"_qs, new TorrentsController(this, this));
registerAPIController(QLatin1String("transfer"), new TransferController(this, this)); registerAPIController(u"transfer"_qs, new TransferController(this, this));
declarePublicAPI(QLatin1String("auth/login")); declarePublicAPI(u"auth/login"_qs);
configure(); configure();
connect(Preferences::instance(), &Preferences::changed, this, &WebApplication::configure); connect(Preferences::instance(), &Preferences::changed, this, &WebApplication::configure);
@ -157,12 +157,9 @@ void WebApplication::sendWebUIFile()
} }
} }
const QString path const QString path = (request().path != u"/")
{
(request().path != QLatin1String("/")
? request().path ? request().path
: QLatin1String("/index.html")) : u"/index.html"_qs;
};
Path localPath = m_rootFolder Path localPath = m_rootFolder
/ Path(session() ? PRIVATE_FOLDER : PUBLIC_FOLDER) / Path(session() ? PRIVATE_FOLDER : PUBLIC_FOLDER)
@ -231,8 +228,8 @@ void WebApplication::translateDocument(QString &data) const
found = false; // no more translatable strings found = false; // no more translatable strings
} }
data.replace(QLatin1String("${LANG}"), m_currentLocale.left(2)); data.replace(u"${LANG}"_qs, m_currentLocale.left(2));
data.replace(QLatin1String("${CACHEID}"), m_cacheID); data.replace(u"${CACHEID}"_qs, m_cacheID);
} }
} }
@ -260,8 +257,8 @@ void WebApplication::doProcessRequest()
return; return;
} }
const QString action = match.captured(QLatin1String("action")); const QString action = match.captured(u"action"_qs);
const QString scope = match.captured(QLatin1String("scope")); const QString scope = match.captured(u"scope"_qs);
APIController *controller = m_apiControllers.value(scope); APIController *controller = m_apiControllers.value(scope);
if (!controller) if (!controller)
@ -358,22 +355,22 @@ void WebApplication::configure()
m_isHttpsEnabled = pref->isWebUiHttpsEnabled(); m_isHttpsEnabled = pref->isWebUiHttpsEnabled();
m_prebuiltHeaders.clear(); m_prebuiltHeaders.clear();
m_prebuiltHeaders.push_back({Http::HEADER_X_XSS_PROTECTION, QLatin1String("1; mode=block")}); m_prebuiltHeaders.push_back({Http::HEADER_X_XSS_PROTECTION, u"1; mode=block"_qs});
m_prebuiltHeaders.push_back({Http::HEADER_X_CONTENT_TYPE_OPTIONS, QLatin1String("nosniff")}); m_prebuiltHeaders.push_back({Http::HEADER_X_CONTENT_TYPE_OPTIONS, u"nosniff"_qs});
if (!m_isAltUIUsed) if (!m_isAltUIUsed)
m_prebuiltHeaders.push_back({Http::HEADER_REFERRER_POLICY, QLatin1String("same-origin")}); m_prebuiltHeaders.push_back({Http::HEADER_REFERRER_POLICY, u"same-origin"_qs});
const bool isClickjackingProtectionEnabled = pref->isWebUiClickjackingProtectionEnabled(); const bool isClickjackingProtectionEnabled = pref->isWebUiClickjackingProtectionEnabled();
if (isClickjackingProtectionEnabled) if (isClickjackingProtectionEnabled)
m_prebuiltHeaders.push_back({Http::HEADER_X_FRAME_OPTIONS, QLatin1String("SAMEORIGIN")}); m_prebuiltHeaders.push_back({Http::HEADER_X_FRAME_OPTIONS, u"SAMEORIGIN"_qs});
const QString contentSecurityPolicy = const QString contentSecurityPolicy =
(m_isAltUIUsed (m_isAltUIUsed
? QLatin1String("") ? QString()
: QLatin1String("default-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; script-src 'self' 'unsafe-inline'; object-src 'none'; form-action 'self';")) : u"default-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; script-src 'self' 'unsafe-inline'; object-src 'none'; form-action 'self';"_qs)
+ (isClickjackingProtectionEnabled ? QLatin1String(" frame-ancestors 'self';") : QLatin1String("")) + (isClickjackingProtectionEnabled ? u" frame-ancestors 'self';"_qs : QString())
+ (m_isHttpsEnabled ? QLatin1String(" upgrade-insecure-requests;") : QLatin1String("")); + (m_isHttpsEnabled ? u" upgrade-insecure-requests;"_qs : QString());
if (!contentSecurityPolicy.isEmpty()) if (!contentSecurityPolicy.isEmpty())
m_prebuiltHeaders.push_back({Http::HEADER_CONTENT_SECURITY_POLICY, contentSecurityPolicy}); m_prebuiltHeaders.push_back({Http::HEADER_CONTENT_SECURITY_POLICY, contentSecurityPolicy});
@ -461,7 +458,7 @@ void WebApplication::sendFile(const Path &path)
file.close(); file.close();
const QMimeType mimeType = QMimeDatabase().mimeTypeForFileNameAndData(path.data(), data); const QMimeType mimeType = QMimeDatabase().mimeTypeForFileNameAndData(path.data(), data);
const bool isTranslatable = mimeType.inherits(QLatin1String("text/plain")); const bool isTranslatable = mimeType.inherits(u"text/plain"_qs);
// Translate the file // Translate the file
if (isTranslatable) if (isTranslatable)
@ -533,7 +530,7 @@ void WebApplication::sessionInitialize()
{ {
Q_ASSERT(!m_currentSession); Q_ASSERT(!m_currentSession);
const QString sessionId {parseCookie(m_request.headers.value(QLatin1String("cookie"))).value(QString::fromLatin1(C_SID))}; const QString sessionId {parseCookie(m_request.headers.value(u"cookie"_qs)).value(QString::fromLatin1(C_SID))};
// TODO: Additional session check // TODO: Additional session check
@ -590,7 +587,7 @@ bool WebApplication::isAuthNeeded()
bool WebApplication::isPublicAPI(const QString &scope, const QString &action) const bool WebApplication::isPublicAPI(const QString &scope, const QString &action) const
{ {
return m_publicAPIs.contains(QString::fromLatin1("%1/%2").arg(scope, action)); return m_publicAPIs.contains(u"%1/%2"_qs.arg(scope, action));
} }
void WebApplication::sessionStart() void WebApplication::sessionStart()
@ -615,7 +612,7 @@ void WebApplication::sessionStart()
QNetworkCookie cookie(C_SID, m_currentSession->id().toUtf8()); QNetworkCookie cookie(C_SID, m_currentSession->id().toUtf8());
cookie.setHttpOnly(true); cookie.setHttpOnly(true);
cookie.setSecure(m_isSecureCookieEnabled && m_isHttpsEnabled); cookie.setSecure(m_isSecureCookieEnabled && m_isHttpsEnabled);
cookie.setPath(QLatin1String("/")); cookie.setPath(u"/"_qs);
QByteArray cookieRawForm = cookie.toRawForm(); QByteArray cookieRawForm = cookie.toRawForm();
if (m_isCSRFProtectionEnabled) if (m_isCSRFProtectionEnabled)
cookieRawForm.append("; SameSite=Strict"); cookieRawForm.append("; SameSite=Strict");
@ -627,7 +624,7 @@ void WebApplication::sessionEnd()
Q_ASSERT(m_currentSession); Q_ASSERT(m_currentSession);
QNetworkCookie cookie(C_SID); QNetworkCookie cookie(C_SID);
cookie.setPath(QLatin1String("/")); cookie.setPath(u"/"_qs);
cookie.setExpirationDate(QDateTime::currentDateTime().addDays(-1)); cookie.setExpirationDate(QDateTime::currentDateTime().addDays(-1));
delete m_sessions.take(m_currentSession->id()); delete m_sessions.take(m_currentSession->id());

5
src/webui/webapplication.h

@ -36,13 +36,14 @@
#include <QSet> #include <QSet>
#include <QTranslator> #include <QTranslator>
#include "api/isessionmanager.h" #include "base/global.h"
#include "base/http/irequesthandler.h" #include "base/http/irequesthandler.h"
#include "base/http/responsebuilder.h" #include "base/http/responsebuilder.h"
#include "base/http/types.h" #include "base/http/types.h"
#include "base/path.h" #include "base/path.h"
#include "base/utils/net.h" #include "base/utils/net.h"
#include "base/utils/version.h" #include "base/utils/version.h"
#include "api/isessionmanager.h"
inline const Utils::Version<int, 3, 2> API_VERSION {2, 8, 9}; inline const Utils::Version<int, 3, 2> API_VERSION {2, 8, 9};
@ -127,7 +128,7 @@ private:
QHash<QString, QString> m_params; QHash<QString, QString> m_params;
const QString m_cacheID; const QString m_cacheID;
const QRegularExpression m_apiPathPattern {QLatin1String("^/api/v2/(?<scope>[A-Za-z_][A-Za-z_0-9]*)/(?<action>[A-Za-z_][A-Za-z_0-9]*)$")}; const QRegularExpression m_apiPathPattern {u"^/api/v2/(?<scope>[A-Za-z_][A-Za-z_0-9]*)/(?<action>[A-Za-z_][A-Za-z_0-9]*)$"_qs};
QHash<QString, APIController *> m_apiControllers; QHash<QString, APIController *> m_apiControllers;
QSet<QString> m_publicAPIs; QSet<QString> m_publicAPIs;

Loading…
Cancel
Save