Pyrite/database.py
2025-01-15 12:48:45 -05:00

51 lines
1.3 KiB
Python

#!/usr/bin/env python3
"""
Contains helper functions for accessing the database.
"""
import os
from urllib import parse
import config
async def get_random_track(request):
"""Selects a random track."""
async with request.app.state.db_pool.acquire() as conn:
track = await conn.fetchrow(
"SELECT * FROM track ORDER BY random() LIMIT 1"
)
track = dict(track)
fpath = track.pop('filepath')
art256 = os.path.join(os.path.dirname(fpath), 'folder-256x256.jpg')
art64 = os.path.join(os.path.dirname(fpath), 'folder-64x64.jpg')
track['source'] = convert_filepath(fpath)
track['artwork'] = [{
'src': convert_filepath(art256),
'sizes': '256x256',
'type': 'image/jpeg'
}, {
'src': convert_filepath(art64),
'sizes': '64x64',
'type': 'image/jpeg'
}
]
return track
async def get_artists(request):
"""Returns all artists in the database."""
async with request.app.state.db_pool.acquire() as conn:
artists = await conn.fetch(
"SELECT DISTINCT albumartist FROM track ORDER BY albumartist"
)
artists = [a['albumartist'] for a in artists]
return artists
def convert_filepath(path):
"""Convert a filepath to a URL."""
path = os.path.relpath(path, config.music_dir)
path = config.server_homepage + '/library/' + path
#path = parse.quote(path)
return path