about summary refs log tree commit diff stats
path: root/modules/by-name/qu/qutebrowser/include/redirects.py
blob: 23456a25a0c523e7a22d6b647dafd18e8601e49a (plain) (blame)
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
# Based on the redirect scripts from here:
# - https://github.com/Phantop/dotfiles/blob/9f6256820dbb99cdf5afd373b74d93fe8b8972d7/qutebrowser/include/redirects.py
# - https://gitlab.com/jgkamat/dotfiles/-/blob/0e5f05d347079a9839cb2c7878fd81d9850928ce/qutebrowser/.config/qutebrowser/pyconfig/redirectors.py

from qutebrowser.api import interceptor, message

import operator
import typing

from PyQt6.QtCore import QUrl


def get_host(url: QUrl, base: bool = False) -> str:
    host = url.host()
    if base:
        # www.someSite.com -> someSite.com
        return ".".join(host.split(".")[-2:])
    else:
        return host


def partial(func, *part_args):
    def wrapper(*extra_args):
        return func(*part_args, *extra_args)

    return wrapper


def farside_redir(target: str, url: QUrl) -> bool:
    url.setHost("farside.link")
    url.setPath("/" + target + url.path())
    return True


# Any return value other than a literal 'False' means we redirect
REDIRECT_MAP: typing.Dict[str, typing.Callable[..., typing.Optional[bool]]] = {
    "reddit.com": operator.methodcaller("setHost", "redlib.vhack.eu"),
    # Source: https://libredirect.github.io/
    "medium.com": partial(farside_redir, "scribe"),
    "stackoverflow.com": partial(farside_redir, "anonymousoverflow"),
    "goodreads.com": partial(farside_redir, "biblioreads"),
}


def rewrite(info: interceptor.Request):
    if (
        info.resource_type != interceptor.ResourceType.main_frame
        or info.request_url.scheme() in {"data", "blob"}
    ):
        return

    url = info.request_url

    redir = REDIRECT_MAP.get(get_host(url, base=False))
    if redir is None:
        # Try again, but now only with the base host.
        redir = REDIRECT_MAP.get(get_host(url, base=True))

    if redir is not None and redir(url) is not False:
        message.info("Redirecting to " + url.toString())
        info.redirect(url)


interceptor.register(rewrite)