paws/paws/routes.py
2020-01-13 08:10:48 -05:00

109 lines
2.6 KiB
Python

import os
import sys
import asyncio
import aiohttp
import aiohttp_jinja2
import jinja2_markdown
from jinja2 import select_autoescape, FileSystemLoader
from ipaddress import ip_address as address
from urllib.parse import urlparse
from .config import PAWSCONFIG, VERSION, script_path, logging
from .functions import color
from . import middleware
def webserver():
from . import views
web = aiohttp.web.Application(middlewares=[
middleware.http_filter,
middleware.http_signatures,
middleware.http_redirect
])
async def global_vars(request):
return {
'VERSION': VERSION,
'len': len,
'urlparse': urlparse,
'lighten': color().lighten,
'darken': color().darken,
'saturate': color().saturate,
'desaturate': color().desaturate,
'rgba': color().rgba
}
aiohttp_jinja2.setup(web,
loader=FileSystemLoader(script_path),
autoescape=select_autoescape(['html', 'css']),
extensions=[jinja2_markdown.MarkdownExtension],
context_processors=[global_vars],
lstrip_blocks=True,
trim_blocks=True
)
web.add_routes([
aiohttp.web.route('*', '/', views.heck),
aiohttp.web.route('*', '/@{user}', views.heck),
aiohttp.web.route('*', '/@{user}/{post}', views.heck),
aiohttp.web.route('*', '/@{user}/{post}/activity', views.heck),
aiohttp.web.route('*', '/users/{user}', views.heck),
aiohttp.web.route('*', '/users/{user}/{post}', views.heck),
aiohttp.web.route('*', '/users/{user}/{post}/activity', views.heck)
])
return web
async def start_webserver():
app = webserver()
runner = aiohttp.web.AppRunner(app, access_log_format='%{X-Real-Ip}i "%r" %s %b "%{User-Agent}i"')
await runner.setup()
listen = PAWSCONFIG['host']
port = PAWSCONFIG['port']
if listen.startswith('unix:'):
if sys.platform != 'win32':
sock_listen = listen.replace('unix:', '')
logging.info(f'Starting webserver at socket: {sock_listen}')
site = aiohttp.web.UnixSite(runner, sock_listen)
else:
logging.error('Windows cannot use unix sockets. Use an IP address instead. Exiting...')
sys.exit()
else:
try:
address(listen)
except ValueError:
logging.warning('Invalid IP address. Listening on "0.0.0.0" instead.')
listen = '127.0.0.1'
try:
int(port)
except ValueError:
logging.warning('Invalid port. Using 3621 instead.')
port = 3621
logging.info(f'Starting webserver at address: {listen}:{port}')
site = aiohttp.web.TCPSite(runner, listen, port)
await site.start()
def main():
try:
loop = asyncio.get_event_loop()
asyncio.ensure_future(start_webserver())
loop.run_forever()
except KeyboardInterrupt:
logging.info('Bye!')