52 lines
1.6 KiB
Python
52 lines
1.6 KiB
Python
from beets.ui import print_
|
|
from beets.dbcore import FieldQuery
|
|
from beets.dbcore.query import SlowFieldSort
|
|
|
|
from .labels import LABELS_FIELD_NAME
|
|
|
|
import json
|
|
|
|
playlist_config = {}
|
|
|
|
def initialize_playlists(playlists):
|
|
for playlist in playlists:
|
|
pl_name = playlist["name"]
|
|
query = [playlist["query"], ",", f"label:{pl_name}"]
|
|
playlist_config[pl_name] = query
|
|
|
|
def valid_playlist(playlist_name):
|
|
return playlist_name in playlist_config
|
|
|
|
def expand_playlist_query(playlist_name):
|
|
print(playlist_config[playlist_name])
|
|
return playlist_config[playlist_name]
|
|
|
|
class PlaylistValueSort(SlowFieldSort):
|
|
def __init__(self, field, ascending=True, case_insensitive=True):
|
|
super().__init__(field, ascending, case_insensitive)
|
|
|
|
self.playlist_key = field[len("playlist:"):]
|
|
|
|
def sort(self, objs):
|
|
def key(obj):
|
|
labels_json = obj.get(LABELS_FIELD_NAME, None)
|
|
|
|
if not labels_json:
|
|
# No labels, return minimum value for sorting
|
|
return float('-inf') if self.ascending else float('inf')
|
|
|
|
labels = json.loads(labels_json)
|
|
|
|
if self.playlist_key in labels:
|
|
return labels[self.playlist_key]
|
|
|
|
matching_labels = \
|
|
[label for label in labels
|
|
if label in playlist_config[self.playlist_key]]
|
|
|
|
if len(matching_labels) == 0:
|
|
return float('-inf') if self.ascending else float('inf')
|
|
|
|
return sum([labels[label] for label in matching_labels])
|
|
|
|
return sorted(objs, key=key, reverse=not self.ascending)
|