Aberrant/aberrant.py

66 lines
1.7 KiB
Python

#!/usr/bin/env python3
"""
The primary module for serving the Aberrant application.
"""
import json
import jinja2
import aiohttp_jinja2
from aiohttp import web, WSMsgType
from aiohttp_jinja2 import render_template
import config
import events
import rtorrent
app = web.Application()
app.on_shutdown.append(rtorrent.stop_watch)
aiohttp_jinja2.setup(app, loader=jinja2.FileSystemLoader('templates'))
rtorrent.init()
routes = web.RouteTableDef()
@routes.get(config.prefix + "/", name='index')
async def index(request):
"""The index page."""
torrents = rtorrent.get_active()
tracker_stats = rtorrent.get_stats()
return render_template("index.html", request, locals())
@routes.get(config.prefix + "/get_active_torrents", name='active-torrents')
async def get_active_torrents(request):
"""Returns all active torrents formatted as JSON."""
data = [vars(t) for t in rtorrent.get_active()]
return web.json_response(data)
@routes.get(config.prefix + '/ws', name='ws')
async def websocket_handler(request):
"""The websocket endpoint."""
ws = web.WebSocketResponse()
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
app.router.add_routes(routes)
if __name__ == "__main__":
aiohttp.web.run_app(app, host='0.0.0.0', port=5250)