#!/usr/bin/env python3 """ WebSocket events. """ import os import types from urllib import parse import config async def select_artist(request, ws, data): """Select an artist.""" artist = data.get('artist', '') async with request.app['pool'].acquire() as conn: albums = await conn.fetch( "SELECT DISTINCT album, date FROM track " "WHERE albumartist = $1 ORDER BY date ASC", data.get('artist', '')) albums = [dict(record) for record in albums] ret = {'event': 'artist_albums', 'ok': True, 'data': albums} await ws.send_json(ret) async def select_album(request, ws, data): """Select an album.""" artist = data.get('artist', '') album = data.get('album', '') async with request.app['pool'].acquire() as conn: tracks = await conn.fetch( "SELECT DISTINCT discnumber, tracknumber, title FROM track " "WHERE albumartist = $1 AND album = $2 " "ORDER BY discnumber ASC, tracknumber ASC", artist, album) tracks = [dict(record) for record in tracks] ret = {'event': 'album_tracks', 'ok': True, 'data': tracks} await ws.send_json(ret) async def select_track(request, ws, data): """Select a track.""" artist = data.get('artist', '') album = data.get('album', '') discnumber = data.get('discnumber', '') tracknumber = data.get('tracknumber', '') async with request.app['pool'].acquire() as conn: track = await conn.fetchrow( "SELECT * FROM track " "WHERE albumartist = $1 AND album = $2 " "AND discnumber = $3 AND tracknumber = $4", artist, album, discnumber, tracknumber) track = dict(track) fpath = track.pop('filepath') track.pop('last_modified') fpath = config.static_prefix + os.path.relpath(fpath, config.music_dir) fpath = fpath.replace('flac', 'opus') fpath = parse.quote(fpath) track['url'] = fpath ret = {'event': 'track', 'ok': True, 'data': track} await ws.send_json(ret) async def random_track(request, ws, data): """Select a random track.""" async with request.app['pool'].acquire() as conn: track = await conn.fetchrow( "SELECT * FROM TRACK ORDER BY random() LIMIT 1") track = dict(track) fpath = track.pop('filepath') track.pop('last_modified') fpath = config.static_prefix + os.path.relpath(fpath, config.music_dir) fpath = fpath.replace('flac', 'opus') fpath = parse.quote(fpath) track['url'] = fpath ret = {'event': 'track', 'ok': True, 'data': track} await ws.send_json(ret) events = {} for obj in dir(): if type(locals()[obj]) == types.FunctionType: events[locals()[obj].__name__] = locals()[obj]