Scorch/scorch.py

88 lines
2.1 KiB
Python
Raw Permalink Normal View History

2020-05-07 15:31:49 -04:00
#!/usr/bin/env python3
"""
A music streaming application.
"""
2020-06-15 09:57:23 -04:00
import json
2020-05-11 12:41:26 -04:00
import asyncio
2020-06-03 15:50:49 -04:00
import aiohttp
2020-05-11 12:41:26 -04:00
from aiohttp import web, WSMsgType
2020-05-07 15:31:49 -04:00
import jinja2
import aiohttp_jinja2
from aiohttp_jinja2 import render_template
import uvloop
2020-06-03 15:50:49 -04:00
import asyncpg
2020-05-07 15:31:49 -04:00
import config
2020-06-15 09:57:23 -04:00
import events
2020-06-03 15:50:49 -04:00
import database
2020-05-07 15:31:49 -04:00
import buckler_aiohttp
uvloop.install()
routes = web.RouteTableDef()
@routes.get('/', name='index')
async def index(request):
"""The index page."""
2020-06-03 15:50:49 -04:00
async with request.app['pool'].acquire() as conn:
2020-06-15 09:57:23 -04:00
artists = await conn.fetch(
2020-06-03 15:50:49 -04:00
"SELECT DISTINCT albumartist FROM track ORDER BY albumartist ASC")
2020-06-15 09:57:23 -04:00
artists = [record['albumartist'] for record in artists]
return render_template('index.html', request, locals())
2020-05-07 15:31:49 -04:00
2020-05-11 12:41:26 -04:00
@routes.get('/ws', name='ws')
async def websocket_handler(request):
"""The websocket endpoint."""
ws = web.WebSocketResponse(heartbeat=30)
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:
break
2020-06-15 09:57:23 -04:00
try:
data = json.loads(msg.data)
except json.JSONDecodeError:
break
2020-05-11 12:41:26 -04:00
2020-06-15 09:57:23 -04:00
event = data.get('event')
if not event or event not in events.events.keys():
break
await events.events[event](request, ws, data.get('data'))
2020-05-11 12:41:26 -04:00
await ws.close()
return ws
2020-05-07 15:31:49 -04:00
async def init_app():
"""Initializes the application."""
app = web.Application(middlewares=[buckler_aiohttp.buckler_session])
aiohttp_jinja2.setup(
app,
trim_blocks=True,
lstrip_blocks=True,
undefined=jinja2.StrictUndefined,
loader=jinja2.FileSystemLoader('templates'),
)
2020-06-03 15:50:49 -04:00
app['pool'] = await asyncpg.create_pool(**config.db)
async with app['pool'].acquire() as conn:
with open('scorch.sql', 'r') as file:
await conn.execute(file.read())
2020-05-07 15:31:49 -04:00
app.router.add_routes(routes)
app_wrap = web.Application()
app_wrap.add_subapp(config.url_prefix, app)
return app_wrap
if __name__ == "__main__":
2020-06-03 15:50:49 -04:00
import sys
if len(sys.argv) > 1:
asyncio.run(database.build_library(config.music_dir))
#app = asyncio.run(init_app())
#aiohttp.web.run_app(app, host='0.0.0.0', port=5500)