emmental/curds/playlist/__init__.py

118 lines
2.5 KiB
Python

# Copyright 2019 (c) Anna Schumaker.
from . import library
from . import playlist
from . import root
from .. import data
from .. import notify
from .. import trak
import random
import threading
Current = [ ]
Library = library.LibraryPlaylist
Lock = threading.Lock()
Root = None
Track = None
def current():
with Lock:
return Current[0]
def lookup(name):
with Lock:
return Root.lookup(name)
def next():
global Track
with Lock:
orig = Current[0]
Track = orig.next()
while Track == None and len(Current) > 1:
Current.pop(0)
Track = Current[0].next()
if len(Current[0]) == 0 and len(Current) > 1:
Current.pop(0)
if orig != Current[0]:
orig.changed()
Current[0].changed()
Root.lookup("Previous").add(Track)
return Track
def peek(n):
res = [ ]
with Lock:
state = random.getstate()
for pl in Current:
tracks = pl.peek(n)
res += tracks
if (n := n - len(tracks)) == 0:
break
random.setstate(state)
return res
def previous():
global Track
with Lock:
Track = Root.lookup("Previous").next()
return Track
def select(plist):
with Lock:
orig = Current[0]
if plist == Root.lookup("Collection"):
Current.clear()
elif plist == Root.lookup("Previous"):
return
elif plist in Current:
Current.remove(plist)
Current.insert(0, plist)
orig.changed()
plist.changed()
def save():
with Lock:
with data.DataFile("playlists.pickle", data.WRITE) as f:
path = Track.path if Track != None else None
f.pickle([ Root, path, Current ])
def load():
global Current
global Root
global Track
with data.DataFile("playlists.pickle", data.READ) as f:
if f.exists():
[ Root, path, Current ] = f.unpickle()
Track = trak.lookup(path)
if Root == None:
Root = root.PlaylistRoot()
Track = None
Current = [ Root.lookup("Collection") ]
init()
def reset():
global Current
global Track
Root.reset()
Track = None
Current = [ Root.lookup("Collection") ]
library.reset()
init()
def init():
global Starred
global UpNext
Starred = Root.lookup("Playlists").lookup("Starred")
UpNext = Root.lookup("Up Next")
notify.register("save-playlists", save, idle=True)
notify.register("save-data", save)