52 lines
1.6 KiB
Python
52 lines
1.6 KiB
Python
import jsonfile
|
|
import youtube
|
|
|
|
MUSIC_FILE = "music.json"
|
|
|
|
|
|
def load_playlist() -> tuple[dict, list[str]]:
|
|
data = jsonfile.load(MUSIC_FILE)
|
|
return data, data.setdefault("videos", [])
|
|
|
|
|
|
def list_songs() -> list[str]:
|
|
_, videos = load_playlist()
|
|
return [youtube.video_id(video) or video for video in videos]
|
|
|
|
|
|
def find_index(videos: list[str], identifier: str) -> int | None:
|
|
return next((index for index, video in enumerate(videos) if youtube.video_id(video) == identifier), None)
|
|
|
|
|
|
def add_song(text: str) -> str:
|
|
identifier = youtube.video_id(text)
|
|
if not identifier:
|
|
raise ValueError(f"{text} is not a YouTube link or video ID")
|
|
data, videos = load_playlist()
|
|
if find_index(videos, identifier) is not None:
|
|
raise ValueError(f"{identifier} is already in the playlist")
|
|
videos.append(youtube.watch_url(identifier))
|
|
jsonfile.save(MUSIC_FILE, data)
|
|
return identifier
|
|
|
|
|
|
def remove_song(identifier: str) -> None:
|
|
data, videos = load_playlist()
|
|
index = find_index(videos, identifier)
|
|
if index is None:
|
|
raise ValueError(f"{identifier} is not in the playlist")
|
|
videos.pop(index)
|
|
jsonfile.save(MUSIC_FILE, data)
|
|
|
|
|
|
def move_song(identifier: str, step: int) -> None:
|
|
data, videos = load_playlist()
|
|
index = find_index(videos, identifier)
|
|
if index is None:
|
|
raise ValueError(f"{identifier} is not in the playlist")
|
|
target = index + step
|
|
if not 0 <= target < len(videos):
|
|
return
|
|
videos[index], videos[target] = videos[target], videos[index]
|
|
jsonfile.save(MUSIC_FILE, data)
|