aboutsummaryrefslogtreecommitdiff
path: root/plugins/HostlistFilter/filterlist.h
blob: a0fa6f755be902db8679b05cb022b6079708690f (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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
/*
 * 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://library.iserlohn-fortress.net/aqua/smolbote.git
 *
 * SPDX-License-Identifier: GPL-3.0
 */

#ifndef SMOLBOTE_HOSTLIST_FILTERLIST
#define SMOLBOTE_HOSTLIST_FILTERLIST

#include <QHash>
#include <smolbote/filterinterface.hpp>

namespace Hostlist
{

void parseRule(const QString &line, QStringList &blocked, QHash<QString, QString> &redirected);

class Filterlist final : public FilterList
{
public:
    Filterlist() = default;
    Filterlist(const Filterlist &) = delete;
    Filterlist &operator=(const Filterlist &) = delete;
    ~Filterlist() = default;

    enum Match {
        NotFound,
        Block,
        Redirect
    };

    [[nodiscard]] Match findMatch(QUrl &url) const
    {
        const auto domain = url.host();

        if(blocked.contains(domain))
            return Block;

        const auto iter = redirected.find(domain);
        if(iter != redirected.end()) {
            url.setHost(iter.value());
            return Redirect;
        }

        return NotFound;
    }

    [[nodiscard]] auto count() const
    {
        return blocked.size() + redirected.size();
    }

    [[nodiscard]] bool filter(QWebEngineUrlRequestInfo &info) const
    {
        auto url = info.requestUrl();
        switch(findMatch(url)) {
        case NotFound:
            return false;
        case Block:
            info.block(true);
            return true;
        case Redirect:
            info.block(false);
            info.redirect(url);
            return true;
        }
    }

    [[nodiscard]] bool isUpToDate() const
    {
        return true;
    }

    bool load(QIODevice &device);

private:
    QStringList blocked;
    QHash<QString, QString> redirected;
};
} // namespace Hostlist

#endif // SMOLBOTE_HOSTLIST_FILTERLIST