aboutsummaryrefslogtreecommitdiff
path: root/lib/urlfilter/formats/adblockrule.cpp
blob: 60e817f2f34ae987a5db4e0aef87e68f159e6c08 (plain)
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
/*
 * This file is part of smolbote. It's copyrighted by the contributors recorded
 * in the version control history of the file, available from its original
 * location: https://neueland.iserlohn-fortress.net/gitea/aqua/smolbote
 *
 * SPDX-License-Identifier: GPL-3.0
 */

#include "adblockrule.h"
#include <QRegExp>
#include <QStringMatcher>

AdBlockRule::AdBlockRule(FilterLeaf::UrlMatchType matchType, const QString &filter, FilterLeaf::Action action)
{
    this->matchType = matchType;
    this->m_request = filter;
    this->m_isBlocking = (action == FilterLeaf::Block);
    //matcher.setPattern(filter);
    if(matchType == FilterLeaf::RegularExpressionMatch)
        regExp = new QRegExp(filter);
    else
        stringMatcher = new QStringMatcher(filter);
}

void AdBlockRule::mergeOptions(const QHash<QWebEngineUrlRequestInfo::ResourceType, bool> &options)
{
    this->resourceTypeOptions.unite(options);
}

bool AdBlockRule::match(const QUrl &requestUrl) const
{
    switch(matchType) {
    case FilterLeaf::RegularExpressionMatch:
        return (regExp->indexIn(requestUrl.toString()) != -1);
    default:
        return false;
    }
}

bool AdBlockRule::match(const QUrl &requestUrl, QWebEngineUrlRequestInfo::ResourceType type) const
{
    // if request is of the required type, or there are no types set (== apply to all requests)
    if(this->resourceTypeOptions.contains(type) || this->resourceTypeOptions.isEmpty()) {
        switch(matchType) {
        case FilterLeaf::RegularExpressionMatch:
            return (regExp->indexIn(requestUrl.toString()) != -1);
        default:
            qWarning("Match type not implemented, returning false!");
            return false;
        }
    }

    // request type is not matched
    return false;
}

std::pair<FilterLeaf::Action, QVariant> AdBlockRule::action() const
{
    if(m_isBlocking)
        return std::make_pair(FilterLeaf::Block, QVariant());
    else
        return std::make_pair(FilterLeaf::Allow, QVariant());
}