2022-12-06 22:17:53 -08:00
|
|
|
import logging
|
|
|
|
import os
|
|
|
|
|
2022-12-16 23:24:05 -08:00
|
|
|
from textwrap import indent
|
2022-12-06 22:17:53 -08:00
|
|
|
from typing import Union, List
|
|
|
|
|
2022-11-24 13:45:09 -08:00
|
|
|
from groove import db
|
2022-12-06 22:17:53 -08:00
|
|
|
from groove.editor import PlaylistEditor, EDITOR_TEMPLATE
|
2022-12-07 23:10:41 -08:00
|
|
|
from groove.exceptions import PlaylistValidationError, TrackNotFoundError
|
2022-12-06 22:17:53 -08:00
|
|
|
|
|
|
|
from slugify import slugify
|
2022-11-24 13:45:09 -08:00
|
|
|
from sqlalchemy import func, delete
|
2022-11-25 12:20:43 -08:00
|
|
|
from sqlalchemy.orm.session import Session
|
|
|
|
from sqlalchemy.engine.row import Row
|
|
|
|
from sqlalchemy.exc import NoResultFound, MultipleResultsFound
|
2022-11-24 13:45:09 -08:00
|
|
|
|
2022-12-16 23:24:05 -08:00
|
|
|
from yaml.scanner import ScannerError
|
|
|
|
|
2022-11-24 13:45:09 -08:00
|
|
|
|
|
|
|
class Playlist:
|
|
|
|
"""
|
|
|
|
CRUD operations and convenience methods for playlists.
|
|
|
|
"""
|
2022-11-25 15:40:24 -08:00
|
|
|
def __init__(self,
|
2022-12-07 18:19:38 -08:00
|
|
|
name: str,
|
2022-11-25 15:40:24 -08:00
|
|
|
session: Session,
|
2022-12-07 23:10:41 -08:00
|
|
|
slug: str = '',
|
2022-11-25 15:40:24 -08:00
|
|
|
description: str = '',
|
2022-12-02 00:21:19 -08:00
|
|
|
create_ok=True):
|
2022-11-25 12:20:43 -08:00
|
|
|
self._session = session
|
2022-11-25 15:40:24 -08:00
|
|
|
self._name = name
|
2022-12-07 23:10:41 -08:00
|
|
|
if not self._name:
|
|
|
|
raise PlaylistValidationError("Name cannot be empty.")
|
|
|
|
self._slug = slug or slugify(name)
|
2022-11-25 15:40:24 -08:00
|
|
|
self._description = description
|
2022-12-07 17:05:44 -08:00
|
|
|
self._entries = []
|
2022-12-02 00:21:19 -08:00
|
|
|
self._record = None
|
|
|
|
self._create_ok = create_ok
|
|
|
|
self._deleted = False
|
2022-12-06 22:17:53 -08:00
|
|
|
self._editor = PlaylistEditor()
|
2022-12-02 00:21:19 -08:00
|
|
|
|
|
|
|
@property
|
|
|
|
def deleted(self) -> bool:
|
|
|
|
return self._deleted
|
2022-11-24 13:45:09 -08:00
|
|
|
|
|
|
|
@property
|
2022-11-25 12:20:43 -08:00
|
|
|
def exists(self) -> bool:
|
2022-12-02 00:21:19 -08:00
|
|
|
if self.deleted:
|
2022-12-02 21:43:51 -08:00
|
|
|
logging.debug("Playlist has been deleted.")
|
2022-12-02 00:21:19 -08:00
|
|
|
return False
|
|
|
|
if not self._record:
|
2022-12-02 21:43:51 -08:00
|
|
|
if self._create_ok:
|
|
|
|
return True and self.record
|
|
|
|
return False
|
2022-12-02 00:21:19 -08:00
|
|
|
return True
|
2022-11-24 13:45:09 -08:00
|
|
|
|
2022-12-06 22:17:53 -08:00
|
|
|
@property
|
|
|
|
def editor(self):
|
|
|
|
return self._editor
|
|
|
|
|
|
|
|
@property
|
|
|
|
def name(self):
|
|
|
|
return self._name
|
|
|
|
|
|
|
|
@property
|
|
|
|
def description(self):
|
|
|
|
return self._description
|
|
|
|
|
2022-11-30 00:09:23 -08:00
|
|
|
@property
|
2022-12-07 17:05:44 -08:00
|
|
|
def info(self):
|
|
|
|
count = len(self.entries)
|
2022-12-10 10:20:30 -08:00
|
|
|
return f"{self.name}: {self.url} [{count} tracks]\n{self.description}\n"
|
2022-12-07 17:05:44 -08:00
|
|
|
|
|
|
|
@property
|
|
|
|
def url(self) -> str:
|
2022-12-31 15:16:30 -08:00
|
|
|
base = os.environ.get('BASE_URL', f"http://{os.environ['HOST']}:{os.environ['PORT']}")
|
|
|
|
return f"{base}/playlist/{self.slug}"
|
2022-11-30 00:09:23 -08:00
|
|
|
|
2022-11-24 13:45:09 -08:00
|
|
|
@property
|
2022-12-02 00:21:19 -08:00
|
|
|
def slug(self) -> str:
|
2022-11-24 13:45:09 -08:00
|
|
|
return self._slug
|
|
|
|
|
|
|
|
@property
|
2022-12-02 00:21:19 -08:00
|
|
|
def session(self) -> Session:
|
2022-11-25 12:20:43 -08:00
|
|
|
return self._session
|
2022-11-24 13:45:09 -08:00
|
|
|
|
|
|
|
@property
|
2022-12-07 23:10:41 -08:00
|
|
|
def record(self) -> Union[Row, None, bool]:
|
2022-11-25 12:20:43 -08:00
|
|
|
"""
|
|
|
|
Cache the playlist row from the database and return it. Optionally create it if it doesn't exist.
|
2022-12-07 23:10:41 -08:00
|
|
|
|
|
|
|
Returns:
|
|
|
|
None: If we've never tried to get or create the record
|
|
|
|
False: False if we've tried and failed to get the record
|
|
|
|
Row: The record as it appears in the database.
|
2022-11-25 12:20:43 -08:00
|
|
|
"""
|
2022-12-07 23:10:41 -08:00
|
|
|
if self._record is None:
|
2022-12-07 17:05:44 -08:00
|
|
|
self.get_or_create()
|
2022-11-24 13:45:09 -08:00
|
|
|
return self._record
|
|
|
|
|
|
|
|
@property
|
2022-12-07 17:05:44 -08:00
|
|
|
def entries(self) -> List:
|
2022-11-25 12:20:43 -08:00
|
|
|
"""
|
|
|
|
Cache the list of entries on this playlist and return it.
|
|
|
|
"""
|
2022-12-07 17:05:44 -08:00
|
|
|
if not self._entries:
|
|
|
|
if self.record:
|
|
|
|
query = self.session.query(
|
|
|
|
db.entry,
|
|
|
|
db.track
|
|
|
|
).filter(
|
2022-12-07 23:10:41 -08:00
|
|
|
(db.playlist.c.id == self._record.id)
|
2022-12-07 17:05:44 -08:00
|
|
|
).filter(
|
|
|
|
db.entry.c.playlist_id == db.playlist.c.id
|
|
|
|
).filter(
|
|
|
|
db.entry.c.track_id == db.track.c.id
|
|
|
|
).order_by(
|
|
|
|
db.entry.c.track
|
|
|
|
)
|
|
|
|
self._entries = query.all()
|
2022-11-24 13:45:09 -08:00
|
|
|
return self._entries
|
|
|
|
|
|
|
|
@property
|
|
|
|
def as_dict(self) -> dict:
|
|
|
|
"""
|
2022-11-25 12:20:43 -08:00
|
|
|
Return a dictionary of the playlist and its entries.
|
2022-11-24 13:45:09 -08:00
|
|
|
"""
|
2022-12-07 18:19:38 -08:00
|
|
|
playlist = {
|
|
|
|
'name': self.name,
|
|
|
|
'slug': self.slug,
|
2022-12-31 15:16:30 -08:00
|
|
|
'description': self.description,
|
|
|
|
'url': self.url
|
2022-12-07 18:19:38 -08:00
|
|
|
}
|
|
|
|
if self.record:
|
|
|
|
playlist.update(dict(self.record))
|
2022-11-24 13:45:09 -08:00
|
|
|
playlist['entries'] = [dict(entry) for entry in self.entries]
|
|
|
|
return playlist
|
|
|
|
|
2022-11-30 00:09:23 -08:00
|
|
|
@property
|
|
|
|
def as_string(self) -> str:
|
2022-12-10 10:20:30 -08:00
|
|
|
text = self.info
|
2022-12-07 17:05:44 -08:00
|
|
|
for (tracknum, entry) in enumerate(self.entries):
|
2022-12-16 23:24:05 -08:00
|
|
|
text += f" {tracknum+1:-3d}. {entry.artist} - {entry.title}\n"
|
2022-11-30 00:09:23 -08:00
|
|
|
return text
|
|
|
|
|
2022-12-06 22:17:53 -08:00
|
|
|
@property
|
|
|
|
def as_yaml(self) -> str:
|
|
|
|
template_vars = self.as_dict
|
2022-12-16 23:24:05 -08:00
|
|
|
template_vars['description'] = indent(template_vars['description'], prefix=' ')
|
2022-12-06 22:17:53 -08:00
|
|
|
template_vars['entries'] = ''
|
|
|
|
for entry in self.entries:
|
2022-12-07 17:05:44 -08:00
|
|
|
template_vars['entries'] += f' - "{entry.artist}": "{entry.title}"\n'
|
2022-12-06 22:17:53 -08:00
|
|
|
return EDITOR_TEMPLATE.format(**template_vars)
|
|
|
|
|
2022-12-02 00:21:19 -08:00
|
|
|
def _get_tracks_by_path(self, paths: List[str]) -> List:
|
|
|
|
"""
|
|
|
|
Retrieve tracks from the database that match the specified path fragments. The exceptions NoResultFound and
|
|
|
|
MultipleResultsFound are expected in the case of no matches and multiple matches, respectively.
|
|
|
|
"""
|
2022-12-07 23:10:41 -08:00
|
|
|
for path in paths:
|
|
|
|
try:
|
|
|
|
yield self.session.query(db.track).filter(
|
|
|
|
db.track.c.relpath.ilike(f"%{path}%")
|
|
|
|
).one()
|
|
|
|
except NoResultFound:
|
|
|
|
raise TrackNotFoundError(f'Could not find track for path "{path}"')
|
2022-12-02 00:21:19 -08:00
|
|
|
|
2022-12-07 17:05:44 -08:00
|
|
|
def _get_tracks_by_artist_and_title(self, entries: List[tuple]) -> List:
|
2022-12-07 23:10:41 -08:00
|
|
|
for (artist, title) in entries:
|
|
|
|
try:
|
|
|
|
yield self.session.query(db.track).filter(
|
|
|
|
db.track.c.artist == artist, db.track.c.title == title
|
|
|
|
).one()
|
|
|
|
except NoResultFound: # pragma: no cover
|
|
|
|
raise TrackNotFoundError(f'Could not find track "{artist}": "{title}"')
|
|
|
|
|
|
|
|
def _get(self):
|
|
|
|
try:
|
|
|
|
return self.session.query(db.playlist).filter(
|
|
|
|
db.playlist.c.slug == self.slug
|
2022-12-07 17:05:44 -08:00
|
|
|
).one()
|
2022-12-07 23:10:41 -08:00
|
|
|
except NoResultFound:
|
|
|
|
logging.debug(f"Could not find a playlist with slug {self.slug}.")
|
|
|
|
return False
|
|
|
|
|
|
|
|
def _insert(self, values):
|
|
|
|
stmt = db.playlist.insert(values)
|
|
|
|
results = self.session.execute(stmt)
|
|
|
|
self.session.commit()
|
|
|
|
logging.debug(f"Inserted playlist with slug {self.slug}")
|
|
|
|
return self.session.query(db.playlist).filter(
|
|
|
|
db.playlist.c.id == results.inserted_primary_key[0]
|
|
|
|
).one()
|
|
|
|
|
|
|
|
def _update(self, values):
|
|
|
|
stmt = db.playlist.update().where(
|
|
|
|
db.playlist.c.id == self._record.id
|
|
|
|
).values(values)
|
|
|
|
self.session.execute(stmt)
|
|
|
|
self.session.commit()
|
|
|
|
return self.session.query(db.playlist).filter(
|
|
|
|
db.playlist.c.id == self._record.id
|
|
|
|
).one()
|
2022-12-07 17:05:44 -08:00
|
|
|
|
2022-12-06 22:17:53 -08:00
|
|
|
def edit(self):
|
|
|
|
edits = self.editor.edit(self)
|
|
|
|
if not edits:
|
|
|
|
return
|
2022-12-16 23:24:05 -08:00
|
|
|
try:
|
|
|
|
new = Playlist.from_yaml(edits, self.session)
|
|
|
|
if new == self:
|
|
|
|
logging.debug("No changes detected.")
|
|
|
|
return
|
|
|
|
except (TypeError, ScannerError) as e:
|
|
|
|
logging.error(e)
|
|
|
|
raise PlaylistValidationError(
|
|
|
|
"An error occurred reading the input file; this is typically "
|
|
|
|
"the result of an error in the YAML structure."
|
|
|
|
)
|
|
|
|
except TrackNotFoundError as e:
|
|
|
|
logging.error(e)
|
|
|
|
raise PlaylistValidationError(
|
|
|
|
"One or more of the specified tracks "
|
|
|
|
"did not exactly match an entry in the database."
|
|
|
|
)
|
2022-12-06 22:17:53 -08:00
|
|
|
logging.debug(f"Updating {self.slug} with new edits.")
|
|
|
|
self._slug = new.slug
|
|
|
|
self._name = new.name.strip()
|
|
|
|
self._description = new.description.strip()
|
2022-12-07 17:05:44 -08:00
|
|
|
self._entries = new._entries
|
|
|
|
self.save()
|
2022-12-06 22:17:53 -08:00
|
|
|
|
2022-11-25 12:20:43 -08:00
|
|
|
def add(self, paths: List[str]) -> int:
|
|
|
|
"""
|
|
|
|
Add entries to the playlist. Each path should match one and only one track in the database (case-insensitive).
|
|
|
|
If a path doesn't match any track, or if a path matches multiple tracks, nothing is added to the playlist.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
paths (list): A list of partial paths to add.
|
2022-11-24 13:45:09 -08:00
|
|
|
|
2022-11-25 12:20:43 -08:00
|
|
|
Returns:
|
|
|
|
int: The number of tracks added.
|
|
|
|
"""
|
2022-11-25 15:40:24 -08:00
|
|
|
logging.debug(f"Attempting to add tracks matching: {paths}")
|
2022-11-25 12:20:43 -08:00
|
|
|
try:
|
2022-12-07 23:10:41 -08:00
|
|
|
return self.create_entries(list(self._get_tracks_by_path(paths)))
|
|
|
|
except NoResultFound: # pragma: no cover
|
2022-11-25 12:20:43 -08:00
|
|
|
logging.error("One or more of the specified paths do not match any tracks in the database.")
|
|
|
|
return 0
|
2022-12-07 23:10:41 -08:00
|
|
|
except MultipleResultsFound: # pragma: no cover
|
2022-11-25 12:20:43 -08:00
|
|
|
logging.error("One or more of the specified paths matches multiple tracks in the database.")
|
|
|
|
return 0
|
|
|
|
|
|
|
|
def delete(self) -> Union[int, None]:
|
|
|
|
"""
|
|
|
|
Delete a playlist and its entries from the database, then clear the cached values.
|
|
|
|
"""
|
|
|
|
if not self.record:
|
|
|
|
return None
|
2022-11-24 13:45:09 -08:00
|
|
|
plid = self.record.id
|
|
|
|
stmt = delete(db.entry).where(db.entry.c.playlist_id == plid)
|
|
|
|
logging.debug(f"Deleting entries associated with playlist {plid}: {stmt}")
|
2022-11-25 12:20:43 -08:00
|
|
|
self.session.execute(stmt)
|
2022-11-24 13:45:09 -08:00
|
|
|
stmt = delete(db.playlist).where(db.playlist.c.id == plid)
|
|
|
|
logging.debug(f"Deleting playlist {plid}: {stmt}")
|
2022-11-25 12:20:43 -08:00
|
|
|
self.session.execute(stmt)
|
|
|
|
self.session.commit()
|
|
|
|
self._record = None
|
|
|
|
self._entries = None
|
2022-12-02 00:21:19 -08:00
|
|
|
self._deleted = True
|
2022-11-24 13:45:09 -08:00
|
|
|
return plid
|
|
|
|
|
2022-12-02 00:21:19 -08:00
|
|
|
def get_or_create(self, create_ok: bool = False) -> Row:
|
2022-12-07 23:10:41 -08:00
|
|
|
if self._record is None:
|
2022-12-07 17:05:44 -08:00
|
|
|
self._record = self._get()
|
2022-12-17 18:02:12 -08:00
|
|
|
if self._record:
|
|
|
|
self._description = self._record.description
|
|
|
|
self._name = self._record.name
|
|
|
|
self._slug = self._record.slug
|
2022-12-07 23:10:41 -08:00
|
|
|
if not self._record:
|
|
|
|
if self.deleted:
|
|
|
|
raise PlaylistValidationError("Object has been deleted.")
|
|
|
|
if self._create_ok or create_ok:
|
|
|
|
self.save()
|
2022-12-06 22:17:53 -08:00
|
|
|
|
|
|
|
def save(self) -> Row:
|
|
|
|
values = {
|
|
|
|
'slug': self.slug,
|
|
|
|
'name': self.name,
|
|
|
|
'description': self.description
|
|
|
|
}
|
2022-12-07 18:19:38 -08:00
|
|
|
if not self.name:
|
|
|
|
raise PlaylistValidationError("This playlist has no name.")
|
|
|
|
if not self.slug:
|
|
|
|
raise PlaylistValidationError("This playlist has no slug.")
|
2022-12-07 17:05:44 -08:00
|
|
|
self._record = self._update(values) if self._record else self._insert(values)
|
|
|
|
logging.debug(f"Saved playlist {self._record.id} with slug {self._record.slug}")
|
|
|
|
self.save_entries()
|
|
|
|
|
|
|
|
def save_entries(self):
|
|
|
|
plid = self.record.id
|
|
|
|
stmt = delete(db.entry).where(db.entry.c.playlist_id == plid)
|
2022-12-07 18:19:38 -08:00
|
|
|
logging.debug(f"Deleting stale entries associated with playlist {plid}: {stmt}")
|
2022-12-07 17:05:44 -08:00
|
|
|
self.session.execute(stmt)
|
|
|
|
return self.create_entries(self.entries)
|
2022-12-06 22:17:53 -08:00
|
|
|
|
2022-11-30 00:09:23 -08:00
|
|
|
def create_entries(self, tracks: List[Row]) -> int:
|
2022-11-25 12:20:43 -08:00
|
|
|
"""
|
|
|
|
Append a list of tracks to a playlist by populating the entries table with records referencing the playlist and
|
|
|
|
the specified tracks.
|
2022-11-24 13:45:09 -08:00
|
|
|
|
2022-11-25 12:20:43 -08:00
|
|
|
Args:
|
|
|
|
tracks (list): A list of Row objects from the track table.
|
2022-11-24 13:45:09 -08:00
|
|
|
|
2022-11-25 12:20:43 -08:00
|
|
|
Returns:
|
|
|
|
int: The number of tracks added.
|
|
|
|
"""
|
2022-12-07 18:19:38 -08:00
|
|
|
if not tracks:
|
|
|
|
tracks = self.entries
|
|
|
|
if not tracks:
|
|
|
|
return 0
|
2022-12-02 00:21:19 -08:00
|
|
|
maxtrack = self.session.query(func.max(db.entry.c.track)).filter_by(
|
|
|
|
playlist_id=self.record.id
|
|
|
|
).one()[0] or 0
|
|
|
|
|
2022-11-25 12:20:43 -08:00
|
|
|
self.session.execute(
|
2022-11-24 13:45:09 -08:00
|
|
|
db.entry.insert(),
|
|
|
|
[
|
|
|
|
{'playlist_id': self.record.id, 'track_id': obj.id, 'track': idx}
|
|
|
|
for (idx, obj) in enumerate(tracks, start=maxtrack+1)
|
|
|
|
]
|
|
|
|
)
|
2022-11-25 12:20:43 -08:00
|
|
|
self.session.commit()
|
2022-11-25 15:40:24 -08:00
|
|
|
self._entries = None
|
2022-11-24 13:45:09 -08:00
|
|
|
return len(tracks)
|
|
|
|
|
2022-12-07 18:19:38 -08:00
|
|
|
@classmethod
|
|
|
|
def by_slug(cls, slug, session):
|
|
|
|
try:
|
|
|
|
row = session.query(db.playlist).filter(
|
|
|
|
db.playlist.c.slug == slug
|
|
|
|
).one()
|
|
|
|
except NoResultFound as ex:
|
|
|
|
logging.error(f"Could not locate an existing playlist with slug {slug}.")
|
|
|
|
raise ex
|
|
|
|
return cls.from_row(row, session)
|
|
|
|
|
2022-11-25 15:40:24 -08:00
|
|
|
@classmethod
|
|
|
|
def from_row(cls, row, session):
|
2022-12-07 18:19:38 -08:00
|
|
|
pl = Playlist(
|
|
|
|
slug=row.slug,
|
|
|
|
name=row.name,
|
|
|
|
description=row.description,
|
|
|
|
session=session
|
|
|
|
)
|
2022-11-25 15:40:24 -08:00
|
|
|
pl._record = row
|
|
|
|
return pl
|
|
|
|
|
2022-12-06 22:17:53 -08:00
|
|
|
@classmethod
|
2022-12-07 23:10:41 -08:00
|
|
|
def from_yaml(cls, source, session, create_ok=False):
|
2022-12-06 22:17:53 -08:00
|
|
|
try:
|
|
|
|
name = list(source.keys())[0].strip()
|
|
|
|
description = (source[name]['description'] or '').strip()
|
2022-12-07 17:05:44 -08:00
|
|
|
pl = Playlist(
|
2022-12-06 22:17:53 -08:00
|
|
|
slug=slugify(name),
|
|
|
|
name=name,
|
|
|
|
description=description,
|
|
|
|
session=session,
|
2022-12-07 23:10:41 -08:00
|
|
|
create_ok=create_ok
|
2022-12-06 22:17:53 -08:00
|
|
|
)
|
2022-12-16 23:24:05 -08:00
|
|
|
if not source[name]['entries']:
|
|
|
|
pl._entries = []
|
|
|
|
else:
|
|
|
|
pl._entries = list(pl._get_tracks_by_artist_and_title(entries=[
|
|
|
|
list(entry.items())[0] for entry in source[name]['entries']
|
|
|
|
]))
|
|
|
|
except (IndexError, KeyError, AttributeError):
|
2022-12-07 23:10:41 -08:00
|
|
|
raise PlaylistValidationError("The specified source was not a valid playlist.")
|
2022-12-07 17:05:44 -08:00
|
|
|
return pl
|
|
|
|
|
2022-12-06 22:17:53 -08:00
|
|
|
def __eq__(self, obj):
|
2022-12-07 17:05:44 -08:00
|
|
|
logging.debug(f"Comparing obj to self:\n{obj.as_string}\n--\n{self.as_string}")
|
|
|
|
return obj.as_string == self.as_string
|
2022-12-06 22:17:53 -08:00
|
|
|
for key in ('slug', 'name', 'description'):
|
|
|
|
if getattr(obj, key) != getattr(self, key):
|
|
|
|
logging.debug(f"{key}: {getattr(obj, key)} != {getattr(self, key)}")
|
|
|
|
return False
|
|
|
|
return True
|
|
|
|
|
2022-11-25 15:40:24 -08:00
|
|
|
def __repr__(self):
|
2022-11-30 00:09:23 -08:00
|
|
|
return self.as_string
|