aboutsummaryrefslogtreecommitdiff
path: root/src/hydrilla/proxy/web_ui/root.py
blob: ed030d23915aecfe5f204c448b573804e7d72d40 (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
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
# SPDX-License-Identifier: GPL-3.0-or-later

# Proxy web UI root.
#
# This file is part of Hydrilla&Haketilo.
#
# Copyright (C) 2022 Wojtek Kosior
#
# 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 <https://www.gnu.org/licenses/>.
#
#
# I, Wojtek Kosior, thereby promise not to sue for violation of this
# file's license. Although I request that you do not make use of this
# code in a proprietary program, I am not going to enforce this in
# court.

"""
.....
"""

# Enable using with Python 3.7.
from __future__ import annotations

import typing as t

from threading import Lock
from urllib.parse import urlparse

import jinja2
import flask
import werkzeug

from ...translations import translation as make_translation
from ... import item_infos
from .. import state as st
from .. import http_messages
from . import options
from . import rules
from . import repos
from . import items
from . import prompts
from . import _app


def authenticate_by_referrer() -> t.Optional[werkzeug.Response]:
    if flask.request.method == 'GET':
        return None

    parsed_url = urlparse(flask.request.referrer)
    if parsed_url.netloc == 'hkt.mitm.it':
        return None

    flask.abort(403)


def get_current_endpoint() -> t.Optional[str]:
    endpoint = flask.request.endpoint
    assert endpoint is not None
    return endpoint


class WebUIAppImpl(_app.WebUIApp):
    def __init__(self):
        super().__init__(__name__)

        self.jinja_options = {
            **self.jinja_options,
            'loader':        jinja2.PackageLoader(__package__),
            'autoescape':    jinja2.select_autoescape(['html.jinja']),
            'lstrip_blocks': True,
            'extensions': [
                *self.jinja_options.get('extensions', []),
                'jinja2.ext.i18n',
                'jinja2.ext.do'
            ]
        }

        self.jinja_env.globals['get_current_endpoint'] = get_current_endpoint
        self.jinja_env.globals['EnabledStatus']        = st.EnabledStatus
        self.jinja_env.globals['FrozenStatus']         = st.FrozenStatus
        self.jinja_env.globals['InstalledStatus']      = st.InstalledStatus
        self.jinja_env.globals['ActiveStatus']         = st.ActiveStatus
        self.jinja_env.globals['ItemType']             = item_infos.ItemType
        self.jinja_env.globals['MappingUseMode']       = st.MappingUseMode

        self.before_request(authenticate_by_referrer)

        for blueprint in [rules.bp, repos.bp, items.bp, prompts.bp, options.bp]:
            self.register_blueprint(blueprint)

# Flask app is not thread-safe and has to be accompanied by an ugly lock. This
# can cause slow requests to block other requests, so we might need a better
# workaround at some later point.
app      = WebUIAppImpl()
app_lock = Lock()


@app.route('/')
def home() -> str:
    return flask.render_template('index.html.jinja')


def process_request(
        request_info: http_messages.RequestInfo,
        state: st.HaketiloState
) -> http_messages.ProducedResponse:
    path = '/'.join(('', *request_info.url.path_segments))
    if (request_info.url.has_trailing_slash):
        path += '/'

    with app_lock:
        app._haketilo_state = state

        app.jinja_env.install_gettext_translations(make_translation())

        flask_response = app.test_client().open(
            path         = path,
            base_url     = 'https://hkt.mitm.it',
            method       = request_info.method,
            query_string = request_info.url.query,
            headers      = [*request_info.headers.items()],
            data         = request_info.body
        )

        headers_bytes = [
            (key.encode(), val.encode())
            for key, val
            in flask_response.headers
        ]

        return http_messages.ProducedResponse(
            status_code = flask_response.status_code,
            headers     = headers_bytes,
            body        = flask_response.data
        )