report more errors toa dblock dialog

This commit is contained in:
Martin Rotter 2022-09-20 09:39:07 +02:00
parent 2143e5e685
commit 3d482fdbe2
5 changed files with 81 additions and 98 deletions

View File

@ -24,7 +24,7 @@
<url type="donation">https://github.com/sponsors/martinrotter</url> <url type="donation">https://github.com/sponsors/martinrotter</url>
<content_rating type="oars-1.1" /> <content_rating type="oars-1.1" />
<releases> <releases>
<release version="4.2.4" date="2022-09-19"/> <release version="4.2.4" date="2022-09-20"/>
</releases> </releases>
<content_rating type="oars-1.0"> <content_rating type="oars-1.0">
<content_attribute id="violence-cartoon">none</content_attribute> <content_attribute id="violence-cartoon">none</content_attribute>

View File

@ -17,8 +17,7 @@
#include <QMessageBox> #include <QMessageBox>
#include <QTimer> #include <QTimer>
AdBlockDialog::AdBlockDialog(QWidget* parent) AdBlockDialog::AdBlockDialog(QWidget* parent) : QDialog(parent), m_manager(qApp->web()->adBlock()), m_loaded(false) {
: QDialog(parent), m_manager(qApp->web()->adBlock()), m_loaded(false) {
m_ui.setupUi(this); m_ui.setupUi(this);
m_ui.m_cbEnable->setChecked(m_manager->isEnabled()); m_ui.m_cbEnable->setChecked(m_manager->isEnabled());
@ -57,9 +56,7 @@ void AdBlockDialog::saveOnClose() {
} }
} }
catch (const ApplicationException& ex) { catch (const ApplicationException& ex) {
qCriticalNN << LOGSEC_ADBLOCK qCriticalNN << LOGSEC_ADBLOCK << "Failed to enable AdBlock, error:" << QUOTE_W_SPACE_DOT(ex.message());
<< "Failed to enable AdBlock, error:"
<< QUOTE_W_SPACE_DOT(ex.message());
MsgBox::show(this, MsgBox::show(this,
QMessageBox::Icon::Critical, QMessageBox::Icon::Critical,
@ -81,19 +78,18 @@ void AdBlockDialog::enableAdBlock(bool enable) {
m_manager->setEnabled(enable); m_manager->setEnabled(enable);
} }
catch (const ApplicationException& ex) { catch (const ApplicationException& ex) {
qCriticalNN << LOGSEC_ADBLOCK qCriticalNN << LOGSEC_ADBLOCK << "Test of configuration failed:" << QUOTE_W_SPACE_DOT(ex.message());
<< "Test of configuration failed:"
<< QUOTE_W_SPACE_DOT(ex.message());
m_ui.m_lblTestResult->setStatus(WidgetWithStatus::StatusType::Error, m_ui.m_lblTestResult->setStatus(WidgetWithStatus::StatusType::Error,
tr("There is error, check application log for more details and " tr("There is error, check application log for more details and "
"head to online documentation. Also make sure that Node.js is installed." "head to online documentation. Also make sure that Node.js is installed."
"\n\nError: %1").arg(ex.message()), "\n\nError: %1")
.arg(ex.message()),
tr("ERROR!")); tr("ERROR!"));
} }
} }
void AdBlockDialog::onAdBlockEnabledChanged(bool enabled) { void AdBlockDialog::onAdBlockEnabledChanged(bool enabled, const QString& message) {
m_ui.m_cbEnable->setChecked(enabled); m_ui.m_cbEnable->setChecked(enabled);
if (enabled) { if (enabled) {
@ -101,6 +97,9 @@ void AdBlockDialog::onAdBlockEnabledChanged(bool enabled) {
tr("It seems your AdBlock runs fine, but wait few seconds to be sure."), tr("It seems your AdBlock runs fine, but wait few seconds to be sure."),
tr("OK!")); tr("OK!"));
} }
else if (!message.isEmpty()) {
m_ui.m_lblTestResult->setStatus(WidgetWithStatus::StatusType::Warning, message, message);
}
else { else {
m_ui.m_lblTestResult->setStatus(WidgetWithStatus::StatusType::Information, m_ui.m_lblTestResult->setStatus(WidgetWithStatus::StatusType::Information,
tr("No additional info."), tr("No additional info."),

View File

@ -21,7 +21,7 @@ class AdBlockDialog : public QDialog {
private slots: private slots:
void saveOnClose(); void saveOnClose();
void enableAdBlock(bool enable); void enableAdBlock(bool enable);
void onAdBlockEnabledChanged(bool enabled); void onAdBlockEnabledChanged(bool enabled, const QString &message);
void onAdBlockProcessTerminated(); void onAdBlockProcessTerminated();
private: private:

View File

@ -30,9 +30,9 @@
AdBlockManager::AdBlockManager(QObject* parent) AdBlockManager::AdBlockManager(QObject* parent)
: QObject(parent), m_loaded(false), m_enabled(false), m_installing(false), : QObject(parent), m_loaded(false), m_enabled(false), m_installing(false),
#if defined(USE_WEBENGINE) #if defined(USE_WEBENGINE)
m_interceptor(new AdBlockUrlInterceptor(this)), m_interceptor(new AdBlockUrlInterceptor(this)),
#endif #endif
m_serverProcess(nullptr), m_cacheBlocks({}) { m_serverProcess(nullptr), m_cacheBlocks({}) {
m_adblockIcon = new AdBlockIcon(this); m_adblockIcon = new AdBlockIcon(this);
m_adblockIcon->setObjectName(QSL("m_adblockIconAction")); m_adblockIcon->setObjectName(QSL("m_adblockIconAction"));
m_unifiedFiltersFile = qApp->userDataFolder() + QDir::separator() + QSL("adblock-unified-filters.txt"); m_unifiedFiltersFile = qApp->userDataFolder() + QDir::separator() + QSL("adblock-unified-filters.txt");
@ -47,23 +47,21 @@ AdBlockManager::~AdBlockManager() {
BlockingResult AdBlockManager::block(const AdblockRequestInfo& request) { BlockingResult AdBlockManager::block(const AdblockRequestInfo& request) {
if (!isEnabled()) { if (!isEnabled()) {
return { false }; return {false};
} }
const QString url_string = request.requestUrl().toEncoded().toLower(); const QString url_string = request.requestUrl().toEncoded().toLower();
const QString firstparty_url_string = request.firstPartyUrl().toEncoded().toLower(); const QString firstparty_url_string = request.firstPartyUrl().toEncoded().toLower();
const QString url_scheme = request.requestUrl().scheme().toLower(); const QString url_scheme = request.requestUrl().scheme().toLower();
const QPair<QString, QString> url_pair = { firstparty_url_string, url_string }; const QPair<QString, QString> url_pair = {firstparty_url_string, url_string};
const QString url_type = request.resourceType(); const QString url_type = request.resourceType();
if (!canRunOnScheme(url_scheme)) { if (!canRunOnScheme(url_scheme)) {
return { false }; return {false};
} }
else { else {
if (m_cacheBlocks.contains(url_pair)) { if (m_cacheBlocks.contains(url_pair)) {
qDebugNN << LOGSEC_ADBLOCK qDebugNN << LOGSEC_ADBLOCK << "Found blocking data in cache, URL:" << QUOTE_W_SPACE_DOT(url_pair);
<< "Found blocking data in cache, URL:"
<< QUOTE_W_SPACE_DOT(url_pair);
return m_cacheBlocks.value(url_pair); return m_cacheBlocks.value(url_pair);
} }
@ -74,21 +72,18 @@ BlockingResult AdBlockManager::block(const AdblockRequestInfo& request) {
m_cacheBlocks.insert(url_pair, result); m_cacheBlocks.insert(url_pair, result);
qDebugNN << LOGSEC_ADBLOCK qDebugNN << LOGSEC_ADBLOCK << "Inserted blocking data to cache for:" << QUOTE_W_SPACE_DOT(url_pair);
<< "Inserted blocking data to cache for:"
<< QUOTE_W_SPACE_DOT(url_pair);
return result; return result;
} }
catch (const ApplicationException& ex) { catch (const ApplicationException& ex) {
qCriticalNN << LOGSEC_ADBLOCK qCriticalNN << LOGSEC_ADBLOCK
<< "HTTP error when calling server for blocking rules:" << "HTTP error when calling server for blocking rules:" << QUOTE_W_SPACE_DOT(ex.message());
<< QUOTE_W_SPACE_DOT(ex.message()); return {false};
return { false };
} }
} }
else { else {
return { false }; return {false};
} }
} }
} }
@ -111,7 +106,7 @@ void AdBlockManager::setEnabled(bool enabled) {
if (m_enabled) { if (m_enabled) {
if (!m_installing) { if (!m_installing) {
m_installing = true; m_installing = true;
qApp->nodejs()->installUpdatePackages({ { QSL(CLIQZ_ADBLOCKED_PACKAGE), QSL(CLIQZ_ADBLOCKED_VERSION) } }); qApp->nodejs()->installUpdatePackages({{QSL(CLIQZ_ADBLOCKED_PACKAGE), QSL(CLIQZ_ADBLOCKED_VERSION)}});
} }
} }
else { else {
@ -128,7 +123,7 @@ bool AdBlockManager::canRunOnScheme(const QString& scheme) const {
} }
QString AdBlockManager::elementHidingRulesForDomain(const QUrl& url) const { QString AdBlockManager::elementHidingRulesForDomain(const QUrl& url) const {
if (m_serverProcess != nullptr && m_serverProcess->state() == QProcess::ProcessState::Running) { if (m_serverProcess != nullptr && m_serverProcess->state() == QProcess::ProcessState::Running) {
try { try {
auto result = askServerForCosmeticRules(url.toString()); auto result = askServerForCosmeticRules(url.toString());
@ -136,8 +131,7 @@ QString AdBlockManager::elementHidingRulesForDomain(const QUrl& url) const {
} }
catch (const ApplicationException& ex) { catch (const ApplicationException& ex) {
qCriticalNN << LOGSEC_ADBLOCK qCriticalNN << LOGSEC_ADBLOCK
<< "HTTP error when calling server for cosmetic rules:" << "HTTP error when calling server for cosmetic rules:" << QUOTE_W_SPACE_DOT(ex.message());
<< QUOTE_W_SPACE_DOT(ex.message());
return {}; return {};
} }
} }
@ -198,12 +192,10 @@ void AdBlockManager::onPackageReady(const QList<NodeJs::PackageMetadata>& pkgs,
updateUnifiedFiltersFileAndStartServer(); updateUnifiedFiltersFileAndStartServer();
} }
catch (const ApplicationException& ex) { catch (const ApplicationException& ex) {
qCriticalNN << LOGSEC_ADBLOCK qCriticalNN << LOGSEC_ADBLOCK << "Failed to setup filters and start server:" << QUOTE_W_SPACE_DOT(ex.message());
<< "Failed to setup filters and start server:"
<< QUOTE_W_SPACE_DOT(ex.message());
m_enabled = false; m_enabled = false;
emit enabledChanged(m_enabled); emit enabledChanged(m_enabled, tr("Failed to setup filters and start server: %1.").arg(ex.message()));
} }
} }
} }
@ -228,52 +220,46 @@ void AdBlockManager::onServerProcessFinished(int exit_code, QProcess::ExitStatus
Q_UNUSED(exit_status) Q_UNUSED(exit_status)
killServer(); killServer();
qCriticalNN << LOGSEC_ADBLOCK qCriticalNN << LOGSEC_ADBLOCK << "Process exited with exit code" << QUOTE_W_SPACE(exit_code)
<< "Process exited with exit code"
<< QUOTE_W_SPACE(exit_code)
<< "so check application log for more details."; << "so check application log for more details.";
m_enabled = false; m_enabled = false;
emit processTerminated(); emit processTerminated();
} }
BlockingResult AdBlockManager::askServerIfBlocked(const QString& fp_url, const QString& url, const QString& url_type) const { BlockingResult AdBlockManager::askServerIfBlocked(const QString& fp_url,
const QString& url,
const QString& url_type) const {
QJsonObject req_obj; QJsonObject req_obj;
QByteArray out; QByteArray out;
QElapsedTimer tmr; QElapsedTimer tmr;
req_obj[QSL("fp_url")] = fp_url; req_obj[QSL("fp_url")] = fp_url;
req_obj[QSL("url")] = url; req_obj[QSL("url")] = url;
req_obj[QSL("url_type")] = url_type, req_obj[QSL("url_type")] = url_type, req_obj[QSL("filter")] = true;
req_obj[QSL("filter")] = true;
tmr.start(); tmr.start();
auto network_res = NetworkFactory::performNetworkOperation(QSL("http://%1:%2").arg(QHostAddress(QHostAddress::SpecialAddress::LocalHost).toString(), auto network_res =
QString::number(ADBLOCK_SERVER_PORT)), NetworkFactory::performNetworkOperation(QSL("http://%1:%2")
500, .arg(QHostAddress(QHostAddress::SpecialAddress::LocalHost).toString(),
QJsonDocument(req_obj).toJson(), QString::number(ADBLOCK_SERVER_PORT)),
out, 500,
QNetworkAccessManager::Operation::PostOperation, QJsonDocument(req_obj).toJson(),
{ { out,
QSL(HTTP_HEADERS_CONTENT_TYPE).toLocal8Bit(), QNetworkAccessManager::Operation::PostOperation,
QSL("application/json").toLocal8Bit() } }); {{QSL(HTTP_HEADERS_CONTENT_TYPE).toLocal8Bit(),
QSL("application/json").toLocal8Bit()}});
if (network_res.m_networkError == QNetworkReply::NetworkError::NoError) { if (network_res.m_networkError == QNetworkReply::NetworkError::NoError) {
qDebugNN << LOGSEC_ADBLOCK qDebugNN << LOGSEC_ADBLOCK << "Query for blocking info to server took " << tmr.elapsed() << " ms.";
<< "Query for blocking info to server took "
<< tmr.elapsed()
<< " ms.";
QJsonObject out_obj = QJsonDocument::fromJson(out).object(); QJsonObject out_obj = QJsonDocument::fromJson(out).object();
bool blocking = out_obj[QSL("filter")].toObject()[QSL("match")].toBool(); bool blocking = out_obj[QSL("filter")].toObject()[QSL("match")].toBool();
return { return {blocking,
blocking, blocking ? out_obj[QSL("filter")].toObject()[QSL("filter")].toObject()[QSL("filter")].toString()
blocking : QString()};
? out_obj[QSL("filter")].toObject()[QSL("filter")].toObject()[QSL("filter")].toString()
: QString()
};
} }
else { else {
throw NetworkException(network_res.m_networkError); throw NetworkException(network_res.m_networkError);
@ -290,21 +276,19 @@ QString AdBlockManager::askServerForCosmeticRules(const QString& url) const {
tmr.start(); tmr.start();
auto network_res = NetworkFactory::performNetworkOperation(QSL("http://%1:%2").arg(QHostAddress(QHostAddress::SpecialAddress::LocalHost).toString(), auto network_res =
QString::number(ADBLOCK_SERVER_PORT)), NetworkFactory::performNetworkOperation(QSL("http://%1:%2")
500, .arg(QHostAddress(QHostAddress::SpecialAddress::LocalHost).toString(),
QJsonDocument(req_obj).toJson(), QString::number(ADBLOCK_SERVER_PORT)),
out, 500,
QNetworkAccessManager::Operation::PostOperation, QJsonDocument(req_obj).toJson(),
{ { out,
QSL(HTTP_HEADERS_CONTENT_TYPE).toLocal8Bit(), QNetworkAccessManager::Operation::PostOperation,
QSL("application/json").toLocal8Bit() } }); {{QSL(HTTP_HEADERS_CONTENT_TYPE).toLocal8Bit(),
QSL("application/json").toLocal8Bit()}});
if (network_res.m_networkError == QNetworkReply::NetworkError::NoError) { if (network_res.m_networkError == QNetworkReply::NetworkError::NoError) {
qDebugNN << LOGSEC_ADBLOCK qDebugNN << LOGSEC_ADBLOCK << "Query for cosmetic rules to server took " << tmr.elapsed() << " ms.";
<< "Query for cosmetic rules to server took "
<< tmr.elapsed()
<< " ms.";
QJsonObject out_obj = QJsonDocument::fromJson(out).object(); QJsonObject out_obj = QJsonDocument::fromJson(out).object();
@ -316,9 +300,9 @@ QString AdBlockManager::askServerForCosmeticRules(const QString& url) const {
} }
QProcess* AdBlockManager::startServer(int port) { QProcess* AdBlockManager::startServer(int port) {
QString temp_server = QDir::toNativeSeparators(IOFactory::getSystemFolder(QStandardPaths::StandardLocation::TempLocation)) + QString temp_server =
QDir::separator() + QDir::toNativeSeparators(IOFactory::getSystemFolder(QStandardPaths::StandardLocation::TempLocation)) +
QSL("adblock-server.js"); QDir::separator() + QSL("adblock-server.js");
if (!IOFactory::copyFile(QSL(":/scripts/adblock/adblock-server.js"), temp_server)) { if (!IOFactory::copyFile(QSL(":/scripts/adblock/adblock-server.js"), temp_server)) {
qWarningNN << LOGSEC_ADBLOCK << "Failed to copy server file to TEMP."; qWarningNN << LOGSEC_ADBLOCK << "Failed to copy server file to TEMP.";
@ -328,12 +312,14 @@ QProcess* AdBlockManager::startServer(int port) {
proc->setProcessChannelMode(QProcess::ProcessChannelMode::ForwardedErrorChannel); proc->setProcessChannelMode(QProcess::ProcessChannelMode::ForwardedErrorChannel);
connect(proc, QOverload<int, QProcess::ExitStatus>::of(&QProcess::finished), this, &AdBlockManager::onServerProcessFinished); connect(proc,
QOverload<int, QProcess::ExitStatus>::of(&QProcess::finished),
this,
&AdBlockManager::onServerProcessFinished);
qApp->nodejs()->runScript(proc, QDir::toNativeSeparators(temp_server), { qApp->nodejs()->runScript(proc,
QString::number(port), QDir::toNativeSeparators(temp_server),
QDir::toNativeSeparators(m_unifiedFiltersFile) {QString::number(port), QDir::toNativeSeparators(m_unifiedFiltersFile)});
});
qDebugNN << LOGSEC_ADBLOCK << "Attempting to start AdBlock server."; qDebugNN << LOGSEC_ADBLOCK << "Attempting to start AdBlock server.";
return proc; return proc;
@ -341,8 +327,10 @@ QProcess* AdBlockManager::startServer(int port) {
void AdBlockManager::killServer() { void AdBlockManager::killServer() {
if (m_serverProcess != nullptr) { if (m_serverProcess != nullptr) {
disconnect(m_serverProcess, QOverload<int, QProcess::ExitStatus>::of(&QProcess::finished), disconnect(m_serverProcess,
this, &AdBlockManager::onServerProcessFinished); QOverload<int, QProcess::ExitStatus>::of(&QProcess::finished),
this,
&AdBlockManager::onServerProcessFinished);
if (m_serverProcess->state() == QProcess::ProcessState::Running) { if (m_serverProcess->state() == QProcess::ProcessState::Running) {
m_serverProcess->kill(); m_serverProcess->kill();
@ -381,9 +369,7 @@ void AdBlockManager::updateUnifiedFiltersFileAndStartServer() {
unified_contents = unified_contents.append(QString::fromUtf8(out)); unified_contents = unified_contents.append(QString::fromUtf8(out));
unified_contents = unified_contents.append('\n'); unified_contents = unified_contents.append('\n');
qDebugNN << LOGSEC_ADBLOCK qDebugNN << LOGSEC_ADBLOCK << "Downloaded filter list from" << QUOTE_W_SPACE_DOT(filter_list_url);
<< "Downloaded filter list from"
<< QUOTE_W_SPACE_DOT(filter_list_url);
} }
else { else {
throw NetworkException(res.m_networkError, tr("failed to download filter list '%1'").arg(filter_list_url)); throw NetworkException(res.m_networkError, tr("failed to download filter list '%1'").arg(filter_list_url));
@ -394,8 +380,7 @@ void AdBlockManager::updateUnifiedFiltersFileAndStartServer() {
// Save. // Save.
m_unifiedFiltersFile = IOFactory::getSystemFolder(QStandardPaths::StandardLocation::TempLocation) + m_unifiedFiltersFile = IOFactory::getSystemFolder(QStandardPaths::StandardLocation::TempLocation) +
QDir::separator() + QDir::separator() + QSL("adblock.filters");
QSL("adblock.filters");
IOFactory::writeFile(m_unifiedFiltersFile, unified_contents.toUtf8()); IOFactory::writeFile(m_unifiedFiltersFile, unified_contents.toUtf8());

View File

@ -19,18 +19,17 @@ class AdBlockUrlInterceptor;
class AdBlockIcon; class AdBlockIcon;
struct BlockingResult { struct BlockingResult {
bool m_blocked; bool m_blocked;
QString m_blockedByFilter; QString m_blockedByFilter;
BlockingResult() : m_blocked(false), m_blockedByFilter(QString()) {} BlockingResult() : m_blocked(false), m_blockedByFilter(QString()) {}
BlockingResult(bool blocked, QString blocked_by_filter = {})
: m_blocked(blocked), m_blockedByFilter(std::move(blocked_by_filter)) {}
BlockingResult(bool blocked, QString blocked_by_filter = {})
: m_blocked(blocked), m_blockedByFilter(std::move(blocked_by_filter)) {}
}; };
class AdBlockManager : public QObject { class AdBlockManager : public QObject {
Q_OBJECT Q_OBJECT
public: public:
explicit AdBlockManager(QObject* parent = nullptr); explicit AdBlockManager(QObject* parent = nullptr);
@ -43,8 +42,8 @@ class AdBlockManager : public QObject {
// //
// If the process fails then signal // If the process fails then signal
// processTerminated() is thrown. // processTerminated() is thrown.
// If AdBlock is switched on/off peacefully then signal // If AdBlock is switched on/off then signal
// enabledChanged(bool) is thrown. // enabledChanged(bool, QString) is thrown.
void setEnabled(bool enabled); void setEnabled(bool enabled);
bool isEnabled() const; bool isEnabled() const;
@ -67,7 +66,7 @@ class AdBlockManager : public QObject {
void showDialog(); void showDialog();
signals: signals:
void enabledChanged(bool enabled); void enabledChanged(bool enabled, QString error = {});
void processTerminated(); void processTerminated();
private slots: private slots: