File: adblockmanager.cpp

package info (click to toggle)
qupzilla 1.8.9~dfsg1-3.1
  • links: PTS
  • area: main
  • in suites: stretch
  • size: 26,128 kB
  • ctags: 6,656
  • sloc: cpp: 59,925; sh: 206; xml: 94; makefile: 27
file content (404 lines) | stat: -rw-r--r-- 11,291 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
/* ============================================================
* QupZilla - WebKit based browser
* Copyright (C) 2010-2014  David Rosca <nowrep@gmail.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program.  If not, see <http://www.gnu.org/licenses/>.
* ============================================================ */
#include "adblockmanager.h"
#include "adblockdialog.h"
#include "adblockmatcher.h"
#include "adblocksubscription.h"
#include "adblockblockednetworkreply.h"
#include "datapaths.h"
#include "mainapplication.h"
#include "webpage.h"
#include "qztools.h"
#include "networkmanager.h"
#include "browserwindow.h"
#include "settings.h"

#include <QDateTime>
#include <QTextStream>
#include <QDir>
#include <QTimer>

//#define ADBLOCK_DEBUG

#ifdef ADBLOCK_DEBUG
#include <QElapsedTimer>
#endif

Q_GLOBAL_STATIC(AdBlockManager, qz_adblock_manager)

AdBlockManager::AdBlockManager(QObject* parent)
    : QObject(parent)
    , m_loaded(false)
    , m_enabled(true)
    , m_useLimitedEasyList(true)
    , m_matcher(new AdBlockMatcher(this))
{
    load();
}

AdBlockManager::~AdBlockManager()
{
    qDeleteAll(m_subscriptions);
}

AdBlockManager* AdBlockManager::instance()
{
    return qz_adblock_manager();
}

void AdBlockManager::setEnabled(bool enabled)
{
    if (m_enabled == enabled) {
        return;
    }

    m_enabled = enabled;
    emit enabledChanged(enabled);

    Settings settings;
    settings.beginGroup("AdBlock");
    settings.setValue("enabled", m_enabled);
    settings.endGroup();

    load();
    mApp->reloadUserStyleSheet();
}

QList<AdBlockSubscription*> AdBlockManager::subscriptions() const
{
    return m_subscriptions;
}

QNetworkReply* AdBlockManager::block(const QNetworkRequest &request)
{
#ifdef ADBLOCK_DEBUG
    QElapsedTimer timer;
    timer.start();
#endif
    const QString urlString = request.url().toEncoded().toLower();
    const QString urlDomain = request.url().host().toLower();
    const QString urlScheme = request.url().scheme().toLower();

    if (!isEnabled() || !canRunOnScheme(urlScheme))
        return 0;

    const AdBlockRule* blockedRule = m_matcher->match(request, urlDomain, urlString);

    if (blockedRule) {
        QVariant v = request.attribute((QNetworkRequest::Attribute)(QNetworkRequest::User + 100));
        WebPage* webPage = static_cast<WebPage*>(v.value<void*>());
        if (WebPage::isPointerSafeToUse(webPage)) {
            if (!canBeBlocked(webPage->url())) {
                return 0;
            }

            webPage->addAdBlockRule(blockedRule, request.url());
        }

        AdBlockBlockedNetworkReply* reply = new AdBlockBlockedNetworkReply(blockedRule, this);
        reply->setRequest(request);

#ifdef ADBLOCK_DEBUG
        qDebug() << "BLOCKED: " << timer.elapsed() << blockedRule->filter() << request.url();
#endif

        return reply;
    }

#ifdef ADBLOCK_DEBUG
    qDebug() << timer.elapsed() << request.url();
#endif

    return 0;
}

QStringList AdBlockManager::disabledRules() const
{
    return m_disabledRules;
}

void AdBlockManager::addDisabledRule(const QString &filter)
{
    m_disabledRules.append(filter);
}

void AdBlockManager::removeDisabledRule(const QString &filter)
{
    m_disabledRules.removeOne(filter);
}

AdBlockSubscription* AdBlockManager::addSubscription(const QString &title, const QString &url)
{
    if (title.isEmpty() || url.isEmpty()) {
        return 0;
    }

    QString fileName = QzTools::filterCharsFromFilename(title.toLower()) + ".txt";
    QString filePath = QzTools::ensureUniqueFilename(DataPaths::currentProfilePath() + "/adblock/" + fileName);

    QByteArray data = QString("Title: %1\nUrl: %2\n[Adblock Plus 1.1.1]").arg(title, url).toLatin1();

    QFile file(filePath);
    if (!file.open(QFile::WriteOnly | QFile::Truncate)) {
        qWarning() << "AdBlockManager: Cannot write to file" << filePath;
        return 0;
    }

    file.write(data);
    file.close();

    AdBlockSubscription* subscription = new AdBlockSubscription(title, this);
    subscription->setUrl(QUrl(url));
    subscription->setFilePath(filePath);
    subscription->loadSubscription(m_disabledRules);

    m_subscriptions.insert(m_subscriptions.count() - 1, subscription);

    return subscription;
}

bool AdBlockManager::removeSubscription(AdBlockSubscription* subscription)
{
    if (!m_subscriptions.contains(subscription) || !subscription->canBeRemoved()) {
        return false;
    }

    QFile(subscription->filePath()).remove();
    m_subscriptions.removeOne(subscription);

    delete subscription;
    return true;
}

AdBlockCustomList* AdBlockManager::customList() const
{
    foreach (AdBlockSubscription* subscription, m_subscriptions) {
        AdBlockCustomList* list = qobject_cast<AdBlockCustomList*>(subscription);

        if (list) {
            return list;
        }
    }

    return 0;
}

void AdBlockManager::load()
{
    if (m_loaded) {
        return;
    }

#ifdef ADBLOCK_DEBUG
    QElapsedTimer timer;
    timer.start();
#endif

    Settings settings;
    settings.beginGroup("AdBlock");
    m_enabled = settings.value("enabled", m_enabled).toBool();
    m_useLimitedEasyList = settings.value("useLimitedEasyList", m_useLimitedEasyList).toBool();
    m_disabledRules = settings.value("disabledRules", QStringList()).toStringList();
    QDateTime lastUpdate = settings.value("lastUpdate", QDateTime()).toDateTime();
    settings.endGroup();

    if (!m_enabled) {
        return;
    }

    QDir adblockDir(DataPaths::currentProfilePath() + "/adblock");
    // Create if neccessary
    if (!adblockDir.exists()) {
        QDir(DataPaths::currentProfilePath()).mkdir("adblock");
    }

    foreach (const QString &fileName, adblockDir.entryList(QStringList("*.txt"), QDir::Files)) {
        if (fileName == QLatin1String("customlist.txt")) {
            continue;
        }

        const QString absolutePath = adblockDir.absoluteFilePath(fileName);
        QFile file(absolutePath);
        if (!file.open(QFile::ReadOnly)) {
            continue;
        }

        QTextStream textStream(&file);
        textStream.setCodec("UTF-8");
        QString title = textStream.readLine(1024).remove(QLatin1String("Title: "));
        QUrl url = QUrl(textStream.readLine(1024).remove(QLatin1String("Url: ")));

        if (title.isEmpty() || !url.isValid()) {
            qWarning() << "AdBlockManager: Invalid subscription file" << absolutePath;
            continue;
        }

        AdBlockSubscription* subscription = new AdBlockSubscription(title, this);
        subscription->setUrl(url);
        subscription->setFilePath(absolutePath);

        m_subscriptions.append(subscription);
    }

    // Prepend EasyList if subscriptions are empty
    if (m_subscriptions.isEmpty()) {
        AdBlockSubscription* easyList = new AdBlockSubscription(tr("EasyList"), this);
        easyList->setUrl(QUrl(ADBLOCK_EASYLIST_URL));
        easyList->setFilePath(DataPaths::currentProfilePath() + QLatin1String("/adblock/easylist.txt"));

        m_subscriptions.prepend(easyList);
    }

    // Append CustomList
    AdBlockCustomList* customList = new AdBlockCustomList(this);
    m_subscriptions.append(customList);

    // Load all subscriptions
    foreach (AdBlockSubscription* subscription, m_subscriptions) {
        subscription->loadSubscription(m_disabledRules);

        connect(subscription, SIGNAL(subscriptionUpdated()), mApp, SLOT(reloadUserStyleSheet()));
        connect(subscription, SIGNAL(subscriptionChanged()), m_matcher, SLOT(update()));
    }

    if (lastUpdate.addDays(5) < QDateTime::currentDateTime()) {
        QTimer::singleShot(1000 * 60, this, SLOT(updateAllSubscriptions()));
    }

#ifdef ADBLOCK_DEBUG
    qDebug() << "AdBlock loaded in" << timer.elapsed();
#endif

    m_matcher->update();
    m_loaded = true;
}

void AdBlockManager::updateAllSubscriptions()
{
    foreach (AdBlockSubscription* subscription, m_subscriptions) {
        subscription->updateSubscription();
    }

    Settings settings;
    settings.beginGroup("AdBlock");
    settings.setValue("lastUpdate", QDateTime::currentDateTime());
    settings.endGroup();
}

void AdBlockManager::save()
{
    if (!m_loaded) {
        return;
    }

    foreach (AdBlockSubscription* subscription, m_subscriptions) {
        subscription->saveSubscription();
    }

    Settings settings;
    settings.beginGroup("AdBlock");
    settings.setValue("enabled", m_enabled);
    settings.setValue("useLimitedEasyList", m_useLimitedEasyList);
    settings.setValue("disabledRules", m_disabledRules);
    settings.endGroup();
}

bool AdBlockManager::isEnabled() const
{
    return m_enabled;
}

bool AdBlockManager::canRunOnScheme(const QString &scheme) const
{
    return !(scheme == QLatin1String("file") || scheme == QLatin1String("qrc")
             || scheme == QLatin1String("qupzilla") || scheme == QLatin1String("data")
             || scheme == QLatin1String("abp"));
}

bool AdBlockManager::useLimitedEasyList() const
{
    return m_useLimitedEasyList;
}

void AdBlockManager::setUseLimitedEasyList(bool useLimited)
{
    m_useLimitedEasyList = useLimited;

    foreach (AdBlockSubscription* subscription, m_subscriptions) {
        if (subscription->url() == QUrl(ADBLOCK_EASYLIST_URL)) {
            subscription->updateSubscription();
        }
    }
}

bool AdBlockManager::canBeBlocked(const QUrl &url) const
{
    return !m_matcher->adBlockDisabledForUrl(url);
}

QString AdBlockManager::elementHidingRules() const
{
    return m_matcher->elementHidingRules();
}

QString AdBlockManager::elementHidingRulesForDomain(const QUrl &url) const
{
    if (!isEnabled() || !canRunOnScheme(url.scheme()) || !canBeBlocked(url))
        return QString();

    // Acid3 doesn't like the way element hiding rules are embedded into page
    if (url.host() == QLatin1String("acid3.acidtests.org"))
        return QString();

    return m_matcher->elementHidingRulesForDomain(url.host());
}

AdBlockSubscription* AdBlockManager::subscriptionByName(const QString &name) const
{
    foreach (AdBlockSubscription* subscription, m_subscriptions) {
        if (subscription->title() == name) {
            return subscription;
        }
    }

    return 0;
}

AdBlockDialog* AdBlockManager::showDialog()
{
    if (!m_adBlockDialog) {
        m_adBlockDialog = new AdBlockDialog;
    }

    m_adBlockDialog.data()->show();
    m_adBlockDialog.data()->raise();
    m_adBlockDialog.data()->activateWindow();

    return m_adBlockDialog.data();
}

void AdBlockManager::showRule()
{
    if (QAction* action = qobject_cast<QAction*>(sender())) {
        const AdBlockRule* rule = static_cast<const AdBlockRule*>(action->data().value<void*>());

        if (rule) {
            showDialog()->showRule(rule);
        }
    }
}