soundboard/lookup_sounds.py
2025-09-20 20:06:01 +10:00

105 lines
3.1 KiB
Python

import glob
import json
import magic
import tempfile
import shutil
from pathlib import Path
from config import Config
from base64 import b64decode
class Sounds:
def __init__(self):
self.sounds = list()
self.config = Config.load("~/.config/soundboard.ini")
def load_sounds(self):
self.sounds = list()
files = glob.glob(f"{self.config.application_basedir}/sounds/*.json")
for sound in files:
with open(sound, "r") as f:
d = json.load(f)
s = Sound(d.get("filename"), d.get("name"), d.get("route"))
print(f"Registering sound: {s.name}")
self.sounds.append(s)
def lookup(self, route):
for s in self.sounds:
if s.route == route:
return s
return None
def add(self, name, route, filename, mp3_file):
if self.lookup(route) is not None:
return (False, "Route already exists")
# Check if name clashes
json_path = f"{self.config.application_basedir}/sounds/{route}.json"
if Path(f"{json_path}").exists():
return (False, f"JSON file exists: {route}.json")
# Check if the file already exists
mp3_filepath = f"{self.config.application_basedir}{filename}"
if Path(mp3_filepath).exists():
return (False, f"MP3 file exists on disk: {filename}")
# Check if the file is actually an MP3
try:
mp3_decoded = b64decode(mp3_file)
except Exception as e:
return (False, e)
mp3_temp = tempfile.NamedTemporaryFile(
mode="w+b",
buffering=0,
encoding=None,
newline=None,
prefix="mp3tmp_",
dir="tmp",
)
mp3_temp.write(mp3_decoded)
m = magic.open(magic.MAGIC_MIME)
m.load()
if m.file(mp3_temp.name) != "audio/mpeg":
return (False, "File is not of type mp3")
# Save the mp3 file to disk
shutil.copy2(mp3_temp.name, mp3_filepath)
mp3_temp.close()
# Generate the JSON file
# Save the JSON file to disk
with open(json_path, "w") as f:
json.dump({"name": name, "filename": filename, "route": route}, f)
# Reload all the sounds
self.load_sounds()
return (True, "Successfully added sound")
def list(self):
return "<p/> ".join([sound.name for sound in self.sounds])
class Sound:
def __init__(self, filename, name, route):
self.filename = filename
self.name = name
self.route = route
def json(self):
data = {
"filename": self.filename,
"name": self.name,
"route": self.route,
}
return data
def save(self):
config = Config.load("~/.config/soundboard.ini")
path = Path(f"{config.application_basedir}/sounds/{self.route}.json")
if not path.exists():
with open(
f"{config.application_basedir}/sounds/{self.route}.json", "w"
) as f:
json.dump(self.json(), f)
else:
print(f"Sound already exists with name {self.route}")