radio-bullshit/next_song.py

56 lines
1.8 KiB
Python
Raw Normal View History

2021-06-15 21:27:04 +00:00
#!/usr/bin/env python3
2021-11-25 17:49:58 +00:00
from json.decoder import JSONDecodeError
2021-06-05 22:34:59 +00:00
import random, glob, os, json
if __name__ == "__main__":
songs_folder = "/songs"
jingles_folder = "/jingles"
2021-06-15 21:27:04 +00:00
air_support_folder = "/air-support"
2021-06-05 22:34:59 +00:00
2021-06-15 21:27:04 +00:00
def get_air_support():
return random.choice(glob.glob(f"{air_support_folder}/*.ogg"))
2021-11-25 17:49:58 +00:00
def create_state_from_scratch() -> dict:
state = {"current_song_type": "jingle"}
with open(f"{songs_folder}/state.json", "w") as f:
json.dump(state, f, indent=4)
return state
2021-06-15 21:27:04 +00:00
# state loading
if not os.path.isfile(f"{songs_folder}/state.json"):
2021-06-05 22:34:59 +00:00
# create state file if it doesnt exist
with open(f"{songs_folder}/state.json", "w") as f:
2021-11-25 17:49:58 +00:00
state = create_state_from_scratch()
2021-06-05 22:34:59 +00:00
else:
2021-11-25 17:49:58 +00:00
try:
with open(f"{songs_folder}/state.json") as f:
state = json.load(f)
except JSONDecodeError:
# if file doesnt exist, we recreate a state on the disk
state = create_state_from_scratch()
2021-06-05 22:34:59 +00:00
2021-06-15 21:27:04 +00:00
# song choice
2021-06-05 22:34:59 +00:00
if state["current_song_type"] == "song":
state["current_song_type"] = "jingle"
2021-06-15 21:27:04 +00:00
try:
print(random.choice(glob.glob(f"{jingles_folder}/*.ogg")))
except IndexError:
print(get_air_support())
2021-06-05 22:34:59 +00:00
elif state["current_song_type"] == "jingle":
state["current_song_type"] = "song"
2021-06-15 21:27:04 +00:00
try:
print(random.choice(glob.glob(f"{songs_folder}/*.ogg")))
except IndexError:
print(get_air_support())
2021-06-05 22:34:59 +00:00
else:
2021-06-15 21:27:04 +00:00
# should not happen
# resiliency mode
print(get_air_support())
state = {"current_song_type": "jingle"}
2021-06-05 22:44:09 +00:00
2021-06-15 21:27:04 +00:00
# state saving
with open(f"{songs_folder}/state.json", "w") as f:
2021-06-05 22:44:09 +00:00
json.dump(state, f, indent=4)