music-assistant-server

1.9 KBPY
helpers.py
1.9 KB56 lines • python
1"""Helper functions for Radio Paradise provider."""
2
3import time
4from typing import Any
5
6
7def get_current_block_position(block_data: dict[str, Any]) -> int:
8    """Calculate current playback position within a Radio Paradise block.
9
10    :param block_data: Block data containing sched_time_millis.
11    """
12    current_time_ms = int(time.time() * 1000)
13    sched_time = int(block_data.get("sched_time_millis", current_time_ms))
14    return current_time_ms - sched_time
15
16
17def find_current_song(
18    songs: dict[str, dict[str, Any]], current_time_ms: int
19) -> dict[str, Any] | None:
20    """Find which song should currently be playing based on elapsed time.
21
22    :param songs: Dictionary of songs from Radio Paradise block data.
23    :param current_time_ms: Current position in milliseconds within the block.
24    """
25    sorted_keys = sorted(songs.keys(), key=int)
26
27    for song_key in sorted_keys:
28        song = songs[song_key]
29        song_start = int(song.get("elapsed", 0))
30        song_duration = int(song.get("duration", 0))
31        song_end = song_start + song_duration
32
33        if song_start <= current_time_ms < song_end:
34            return song
35
36    # If no exact match, return first song
37    first_song = songs.get("0")
38    return first_song if first_song is not None else None
39
40
41def get_next_song(songs: dict[str, Any], current_song: dict[str, Any]) -> dict[str, Any] | None:
42    """Get the next song that will play after the current song.
43
44    :param songs: Dictionary of songs from Radio Paradise block data.
45    :param current_song: The currently playing song dictionary.
46    """
47    current_event = current_song.get("event")
48    current_elapsed = int(current_song.get("elapsed", 0))
49    sorted_keys = sorted(songs.keys(), key=int)
50
51    for song_key in sorted_keys:
52        song: dict[str, Any] = songs[song_key]
53        if song.get("event") != current_event and int(song.get("elapsed", 0)) > current_elapsed:
54            return song
55    return None
56