Invidious-quic-proxy/main.py

84 lines
2.5 KiB
Python
Raw Normal View History

2021-05-21 18:31:59 +00:00
import pathlib
import logging
2021-05-23 13:58:31 +00:00
import argparse
import asyncio
2021-05-21 18:31:59 +00:00
import pytomlpp
import appdirs
from multidict import CIMultiDict
from aiohttp import web
import quicclient
APP_NAME = "QUICProxy"
2021-05-23 14:03:32 +00:00
APP_AUTHOR = "iv-org"
2021-05-21 18:31:59 +00:00
CONFIG_DIRECTORY = pathlib.Path(f"{appdirs.user_config_dir(APP_NAME, APP_AUTHOR)}")
CONFIG_DIRECTORY.mkdir(parents=True, exist_ok=True)
CONFIG_FILE = pathlib.Path(f"{appdirs.user_config_dir(APP_NAME, APP_AUTHOR)}/config.toml")
CONFIG_FILE.touch(exist_ok=True)
with open(f"{CONFIG_FILE}") as config:
config = pytomlpp.loads(config.read())
if not config:
2021-06-05 15:57:28 +00:00
config = {"listen": "0.0.0.0:7192", "open_connections": 5}
2021-05-21 18:31:59 +00:00
routes = web.RouteTableDef()
2021-05-23 13:58:31 +00:00
def process_cli_args():
# Taken from https://stackoverflow.com/a/20663028
parser = argparse.ArgumentParser()
parser.add_argument(
'-d', '--debug',
help="Print lots of debugging statements",
action="store_const", dest="loglevel", const=logging.DEBUG,
default=logging.WARNING,
)
parser.add_argument(
'-v', '--verbose',
help="Be verbose",
action="store_const", dest="loglevel", const=logging.INFO,
)
args = parser.parse_args()
logging.basicConfig(level=args.loglevel)
2021-05-21 18:31:59 +00:00
@routes.post("/")
async def post(request):
arguments = await request.json()
post_data = str(arguments.get("data", ""))
post_data = post_data if post_data else None
2021-05-21 18:31:59 +00:00
method = arguments["method"]
# Create heders
intermediate_header_processing = [(k, v) for k, v in arguments.get("headers", {}).items()]
processed_headers = CIMultiDict(intermediate_header_processing)
packaged_request = quicclient.InvidiousRequest(url=arguments["url"], method=method, headers=processed_headers,
content=post_data)
result = {}
await request_processor.requests_to_do.put([packaged_request, result])
await packaged_request.completed.wait()
2021-05-21 18:31:59 +00:00
if result["headers"][":status"] == "304":
return web.Response(body=b"", headers=result["headers"], status=304)
else:
return web.Response(body=result["response"], headers=result["headers"])
async def main():
[asyncio.create_task(request_processor.request_worker()) for _ in range(config.get("open_connections", 5))]
app = web.Application()
app.add_routes(routes)
return app
request_processor = quicclient.RequestProcessor()
2021-05-21 18:31:59 +00:00
if __name__ == '__main__':
2021-05-23 13:58:31 +00:00
process_cli_args()
2021-06-05 15:57:28 +00:00
address, port = config.get("listen", "0.0.0.0:7912").split(":")
web.run_app(main(), port=port, host=address)