Aberrant/aberrant.py

66 lines
1.7 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
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-01 14:44:54 -04:00
app = web.Application()
app.on_shutdown.append(rtorrent.stop_watch)
aiohttp_jinja2.setup(app, loader=jinja2.FileSystemLoader('templates'))
2019-02-14 15:00:21 -05:00
rtorrent.init()
2019-01-16 09:33:36 -05:00
2019-09-01 14:44:54 -04:00
routes = web.RouteTableDef()
@routes.get(config.prefix + "/", 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
@routes.get(config.prefix + "/get_active_torrents", name='active-torrents')
2019-09-01 16:48:45 -04:00
async def get_active_torrents(request):
2019-02-15 10:01:33 -05:00
"""Returns all active torrents formatted as JSON."""
2019-09-01 14:44:54 -04:00
data = [vars(t) for t in rtorrent.get_active()]
return web.json_response(data)
2019-09-01 16:48:45 -04:00
@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
2019-09-01 14:44:54 -04:00
app.router.add_routes(routes)
2019-02-15 10:01:33 -05:00
2019-01-16 09:33:36 -05:00
if __name__ == "__main__":
2019-09-01 14:44:54 -04:00
aiohttp.web.run_app(app, host='0.0.0.0', port=5250)