Aberrant/aberrant.py

92 lines
2.0 KiB
Python
Raw Normal View History

2019-01-16 09:33:36 -05:00
#!/usr/bin/env python3
"""
The primary module for serving the Aberrant application.
"""
2019-09-01 16:48:45 -04:00
import json
2020-09-23 09:04:27 -04:00
import asyncio
2019-09-01 16:48:45 -04:00
2019-09-01 14:44:54 -04:00
import jinja2
import aiohttp_jinja2
from aiohttp import web, WSMsgType
from aiohttp_jinja2 import render_template
2019-01-16 09:33:36 -05:00
2019-09-01 14:44:54 -04:00
import config
2019-09-01 16:48:45 -04:00
import events
2019-01-16 12:49:42 -05:00
import rtorrent
2019-09-28 04:05:45 -04:00
import buckler_aiohttp
2019-01-16 12:49:42 -05:00
2019-01-16 09:33:36 -05:00
2019-09-01 14:44:54 -04:00
routes = web.RouteTableDef()
2020-09-23 09:04:27 -04:00
@routes.get('/', name='index')
2019-09-01 16:48:45 -04:00
async def index(request):
2019-01-16 09:33:36 -05:00
"""The index page."""
2019-01-16 12:49:42 -05:00
torrents = rtorrent.get_active()
2019-02-18 10:32:19 -05:00
tracker_stats = rtorrent.get_stats()
2019-09-01 14:44:54 -04:00
return render_template("index.html", request, locals())
2019-01-16 12:49:42 -05:00
2019-09-01 14:44:54 -04:00
2020-09-23 09:04:27 -04:00
@routes.get('/ws', name='ws')
2019-09-01 16:48:45 -04:00
async def websocket_handler(request):
"""The websocket endpoint."""
2019-11-15 23:27:45 -05:00
ws = web.WebSocketResponse(heartbeat=30)
2019-09-01 16:48:45 -04:00
ws_ready = ws.can_prepare(request)
if not ws_ready.ok:
return web.Response(text="Cannot start websocket.")
await ws.prepare(request)
async for msg in ws:
if msg.type == WSMsgType.TEXT:
try:
data = json.loads(msg.data)
except json.JSONDecodeError:
continue
event = data.get('event')
if not event or event not in events.events.keys():
continue
await events.events[event](ws, data.get('data'))
else: # TODO: handle differnt message types properly
break
await ws.close()
return ws
2019-11-15 23:27:45 -05:00
2020-09-23 09:04:27 -04:00
async def watcher_loop():
try:
while True:
await rtorrent.update_torrents()
await asyncio.sleep(10)
except asyncio.CancelledError:
return
async def start_background_tasks(app):
rtorrent.init()
app['watcher'] = asyncio.create_task(watcher_loop())
async def cleanup_background_tasks(app):
app['watcher'].cancel()
await app['watcher']
async def init_app():
"""Initializes the application."""
app = web.Application(middlewares=[buckler_aiohttp.buckler_session])
aiohttp_jinja2.setup(app, loader=jinja2.FileSystemLoader('templates'))
app.on_startup.append(start_background_tasks)
app.on_cleanup.append(cleanup_background_tasks)
app.router.add_routes(routes)
app_wrap = web.Application()
app_wrap.add_subapp(config.url_prefix, app)
return app_wrap
2019-02-15 10:01:33 -05:00
2019-01-16 09:33:36 -05:00
if __name__ == "__main__":
2020-09-23 09:04:27 -04:00
app = init_app()
web.run_app(app, host='0.0.0.0', port=5250)