Skip to content

Commit

Permalink
Merge pull request #44 from EMERALD0874/dev
Browse files Browse the repository at this point in the history
fix up user vars and implement global dfl
  • Loading branch information
beebls authored Jun 24, 2023
2 parents 251f8c7 + 176d81e commit 9b7dc04
Show file tree
Hide file tree
Showing 11 changed files with 221 additions and 216 deletions.
1 change: 1 addition & 0 deletions .prettierrc
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
{
"singleQuote": false,
"tabWidth": 2,
"printWidth": 100,
"semi": true,
"trailingComma": "es5",
"bracketSameLine": false
Expand Down
51 changes: 25 additions & 26 deletions audio_remoteinstall.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
import asyncio, json, tempfile, os
from audio_utils import Result, Log
from audio_utils import AUDIO_LOADER_VERSION, DECKY_HOME
import aiohttp
import asyncio, tempfile, os, zipfile, aiohttp
from audio_utils import Result, Log, get_pack_path, AUDIO_LOADER_VERSION

async def run(command : str) -> str:
proc = await asyncio.create_subprocess_shell(command,
Expand All @@ -20,41 +18,42 @@ async def install(id : str, base_url : str) -> Result:

url = f"{base_url}themes/{id}"

try:
async with aiohttp.ClientSession(connector=aiohttp.TCPConnector(verify_ssl=False)) as session:
async with aiohttp.ClientSession(headers={"User-Agent": f"SDH-AudioLoader/{AUDIO_LOADER_VERSION}"}, connector=aiohttp.TCPConnector(verify_ssl=False)) as session:
try:
async with session.get(url) as resp:
if resp.status != 200:
raise Exception(f"Invalid status code {resp.status}")

data = await resp.json()
except Exception as e:
return Result(False, str(e))

if (data["manifestVersion"] > AUDIO_LOADER_VERSION):
raise Exception("Manifest version of entry is unsupported by this version of Audio Loader")
except Exception as e:
return Result(False, str(e))

download_url = f"{base_url}blobs/{data['download']['id']}"
tempDir = tempfile.TemporaryDirectory()
if (data["manifestVersion"] > AUDIO_LOADER_VERSION):
raise Exception("Manifest version of themedb entry is unsupported by this version of AudioLoader")

Log(f"Downloading {download_url} to {tempDir.name}...")
themeZipPath = os.path.join(tempDir.name, 'theme.zip')
try:
await run(f"curl \"{download_url}\" -L -o \"{themeZipPath}\"")
except Exception as e:
return Result(False, str(e))
download_url = f"{base_url}blobs/{data['download']['id']}"
tempDir = tempfile.TemporaryDirectory()

Log(f"Downloading {download_url} to {tempDir.name}...")
themeZipPath = os.path.join(tempDir.name, 'pack.zip')
try:
async with session.get(download_url) as resp:
if resp.status != 200:
raise Exception(f"Got {resp.status} code from '{download_url}'")

with open(themeZipPath, "wb") as out:
out.write(await resp.read())

except Exception as e:
return Result(False, str(e))

Log(f"Unzipping {themeZipPath}")
try:
await run(f"unzip -o \"{themeZipPath}\" -d \"{DECKY_HOME}/sounds\"")
with zipfile.ZipFile(themeZipPath, 'r') as zip:
zip.extractall(get_pack_path())
except Exception as e:
return Result(False, str(e))

tempDir.cleanup()

# for x in data["dependencies"]:
# if x["name"] in local_themes:
# continue

# await install(x["id"], base_url, local_themes)

return Result(True)
33 changes: 31 additions & 2 deletions audio_utils.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,43 @@
import os
from logging import getLogger
import platform

Logger = getLogger("AUDIO_LOADER")
AUDIO_LOADER_VERSION = 2
AUDIO_LOADER_VERSION = 3
HOME = os.getenv("HOME")
if not HOME:
HOME = os.path.expanduser("~")
PLATFORM_WIN = platform.system() == "Windows"
DECKY_HOME = os.environ["DECKY_HOME"] # /home/user/homebrew
DECKY_USER_HOME = os.environ["DECKY_USER_HOME"] # /home/user
DECKY_USER = os.getenv("DECKY_USER")

def Log(text : str):
Logger.info(f"[AUDIO_LOADER] {text}")

def get_user_home() -> str:
return HOME

def get_pack_path() -> str:
return os.path.join(DECKY_HOME, "sounds")

def get_steam_path() -> str:
if PLATFORM_WIN:
try:
import winreg
conn = winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE)
key = winreg.OpenKey(conn, "SOFTWARE\\Wow6432Node\\Valve\\Steam")
val, type = winreg.QueryValueEx(key, "InstallPath")
if type != winreg.REG_SZ:
raise Exception(f"Expected type {winreg.REG_SZ}, got {type}")

Log(f"Got win steam install path: '{val}'")
return val
except Exception as e:
return "C:\\Program Files (x86)\\Steam" # Taking a guess here
else:
return f"{get_user_home()}/.local/share/Steam"

class Result:
def __init__(self, success : bool, message : str = "Success"):
self.success = success
Expand All @@ -25,7 +54,7 @@ def to_dict(self):
return {"success": self.success, "message": self.message}

def store_path() -> str:
return os.path.join(DECKY_HOME, "sounds", "STORE")
return os.path.join(get_pack_path(), "STORE")

def store_reads() -> dict:
path = store_path()
Expand Down
21 changes: 13 additions & 8 deletions main.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

sys.path.append(os.path.dirname(__file__))

from audio_utils import store_read as util_store_read, store_write as util_store_write, AUDIO_LOADER_VERSION, DECKY_HOME, DECKY_USER_HOME
from audio_utils import store_read as util_store_read, store_write as util_store_write, get_steam_path, get_pack_path, AUDIO_LOADER_VERSION, DECKY_HOME, DECKY_USER_HOME
from audio_remoteinstall import install

starter_config_data = {
Expand Down Expand Up @@ -68,13 +68,18 @@ def __init__(self, packPath : str, json : dict, truncatedPackPath: str):
self.mappings = json["mappings"] if ("mappings" in json) else {}
self.music = bool(json["music"]) if ("music" in json) else False
self.id = json["id"] if ("id" in json) else self.name


if (AUDIO_LOADER_VERSION < self.require):
raise Exception("Audio Loader - {} requires Audio Loader version {} but only version {} is installed".format(self.name, self.require, AUDIO_LOADER_VERSION))

self.packPath = packPath
self.truncatedPackPath = truncatedPackPath

self.has_intro = False
if (self.music == True):
self.has_intro = "intro_music.mp3" in self.mappings or os.path.exists(os.path.join(packPath, "intro_music.mp3"))

async def delete(self) -> Result:
try:
shutil.rmtree(self.packPath)
Expand All @@ -92,6 +97,7 @@ def to_dict(self) -> dict:
"ignore": self.ignore,
"mappings": self.mappings,
"music": self.music,
"hasIntro": self.has_intro,
"packPath": self.packPath,
"truncatedPackPath": self.truncatedPackPath,
"id": self.id
Expand All @@ -111,7 +117,7 @@ async def download_theme_from_url(self, id : str, url : str) -> dict:
return (await install(id, url)).to_dict()

async def get_config(self) -> object:
configPath = f"{DECKY_HOME}/sounds/config.json"
configPath = os.path.join(get_pack_path(), 'config.json')

Log("Audio Loader - Fetching config file at {}".format(configPath))
if (os.path.exists(configPath)):
Expand All @@ -122,7 +128,7 @@ async def get_config(self) -> object:
return data

async def set_config(self, configObj: object):
configPath = f"{DECKY_HOME}/sounds/config.json"
configPath = os.path.join(get_pack_path(), 'config.json')

Log("Audio Loader - Setting config file at {}".format(configPath))
if (os.path.exists(configPath)):
Expand Down Expand Up @@ -189,19 +195,18 @@ async def store_write(self, key : str, val : str) -> dict:
return Result(True).to_dict()

async def _load(self):
packsPath = f"{DECKY_HOME}/sounds"
symlinkPath = f"{DECKY_USER_HOME}/.local/share/Steam/steamui/sounds_custom"
packsPath = get_pack_path()

configPath = f"{DECKY_HOME}/sounds/config.json"
configPath = os.path.join(get_pack_path(), 'config.json')

Log("Audio Loader - Finding sound packs...")
self.soundPacks = []

if (not os.path.exists(packsPath)):
await create_folder(packsPath)

if (not os.path.exists(symlinkPath)):
await create_symlink(packsPath, symlinkPath)
if (not os.path.exists(os.path.join(get_steam_path(), 'steamui', 'sounds_custom'))):
await create_symlink(get_pack_path(), os.path.join(get_steam_path(), 'steamui', 'sounds_custom'))

if (not os.path.exists(configPath)):
await create_config(configPath)
Expand Down
14 changes: 7 additions & 7 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@
},
"dependencies": {
"@types/lodash": "^4.14.191",
"decky-frontend-lib": "^3.21.0",
"decky-frontend-lib": "^3.21.1",
"lodash": "^4.17.21",
"react-icons": "^4.4.0"
},
Expand Down
8 changes: 2 additions & 6 deletions rollup.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,17 +26,13 @@ export default defineConfig({
styles(),
],
context: "window",
external: [
"react",
"react-dom",
// "decky-frontend-lib"
],
external: ["react", "react-dom", "decky-frontend-lib"],
output: {
file: "dist/index.js",
globals: {
react: "SP_REACT",
"react-dom": "SP_REACTDOM",
// "decky-frontend-lib": "DFL",
"decky-frontend-lib": "DFL",
},
format: "iife",
exports: "default",
Expand Down
93 changes: 93 additions & 0 deletions src/audioPlayers/changeMenuMusic.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
import { Mappings, Pack } from "../classes";

function findMapping(origFileName: string, mappings: Mappings | undefined): string {
if (mappings && Object.keys(mappings || {}).includes(origFileName)) {
const randIndex = Math.trunc(Math.random() * mappings[origFileName].length);
return mappings[origFileName][randIndex];
}
return origFileName;
}

function createFullPath(fileName: string, truncatedPackPath: string | undefined) {
return `/sounds_custom/${truncatedPackPath || "error"}/${fileName}`;
}

export function changeMenuMusic(
newMusic: string,
menuMusic: HTMLAudioElement | null,
setGlobalState: (key: string, value: any) => void,
gamesRunning: any,
soundPacks: Pack[],
musicVolume: number
) {
setGlobalState("selectedMusic", newMusic);

// Stops the old music
if (menuMusic !== null) {
menuMusic.pause();
menuMusic.currentTime = 0;
setGlobalState("menuMusic", null);
}

// Start the new one, if the user selected a music at all
if (newMusic !== "None" && gamesRunning.length === 0) {
const currentPack = soundPacks.find((e) => e.name === newMusic);

const musicFilePath = createFullPath(
findMapping("menu_music.mp3", currentPack?.mappings),
currentPack?.truncatedPackPath
);
const introFilePath = createFullPath(
findMapping("intro_music.mp3", currentPack?.mappings),
currentPack?.truncatedPackPath
);

let newMenuMusic: HTMLAudioElement;

// If there is an intro, it must play that, and add an onended listener to change to the normal music
// If there's no intro, it can just go straight to playAndLoopMenuMusic()
if (currentPack?.hasIntro) {
function handleIntroEnd() {
newMenuMusic.currentTime = 0;
newMenuMusic.src = musicFilePath;
newMenuMusic.onended = null;
playAndLoopMenuMusic();
}
newMenuMusic = new Audio(introFilePath);
newMenuMusic.onended = handleIntroEnd;
newMenuMusic.volume = musicVolume;
newMenuMusic.play();
createWindowObject(newMenuMusic);
} else {
newMenuMusic = new Audio(musicFilePath);
playAndLoopMenuMusic();
}

function playAndLoopMenuMusic(wasFromIntro: boolean = false) {
newMenuMusic.play();
newMenuMusic.loop = true;
// If someone has changed the volume before the intro ended, this would overwrite it with the original as this function does not have up to date data
if (!wasFromIntro) {
newMenuMusic.volume = musicVolume;
}
createWindowObject(newMenuMusic);
}

// Self explanatory, just extracted it to a function so that I can run it once on the intro, and once on the menu music
// TODO: Not actually sure if it needs to be set the 2nd time
function createWindowObject(menuMusic: HTMLAudioElement) {
const setVolume = (value: number) => {
menuMusic.volume = value;
};
// @ts-ignore
window.AUDIOLOADER_MENUMUSIC = {
play: menuMusic.play.bind(menuMusic),
pause: menuMusic.pause.bind(menuMusic),
origVolume: menuMusic.volume,
// @ts-ignore
setVolume: setVolume.bind(this),
};
setGlobalState("menuMusic", menuMusic);
}
}
}
1 change: 1 addition & 0 deletions src/audioPlayers/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from "./changeMenuMusic";
5 changes: 4 additions & 1 deletion src/classes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ export interface Pack {
packPath: string; // This contains the full path from root to the pack
truncatedPackPath: string; // This is the relative path from ~/homebrew/sounds
music: boolean;
hasIntro: boolean;
id: string;
}

Expand Down Expand Up @@ -58,7 +59,9 @@ export type DeckSound =
| "steam_chatroom_notification.m4a"
| "ui_steam_message_old_smooth.m4a"
| "ui_steam_smoother_friend_join.m4a"
| "ui_steam_smoother_friend_online.m4a";
| "ui_steam_smoother_friend_online.m4a"
| "menu_music.mp3"
| "intro_music.mp3";

export type Mappings =
| {
Expand Down
Loading

0 comments on commit 9b7dc04

Please sign in to comment.