Reformat code.

This commit is contained in:
Cohee 2023-08-24 21:59:26 +03:00
parent 43e70c9df1
commit cd24de3c2e
3 changed files with 188 additions and 197 deletions

View File

@ -4,13 +4,11 @@ TODO:
*/ */
//const DEBUG_TONY_SAMA_FORK_MODE = false //const DEBUG_TONY_SAMA_FORK_MODE = false
import { saveSettingsDebounced, getRequestHeaders, callPopup } from "../../../script.js"; import { getRequestHeaders, callPopup } from "../../../script.js";
import { getContext, getApiUrl, extension_settings, doExtrasFetch, ModuleWorkerWrapper, modules } from "../../extensions.js";
export { MODULE_NAME }; export { MODULE_NAME };
const MODULE_NAME = 'Assets'; const MODULE_NAME = 'Assets';
const DEBUG_PREFIX = "<Assets module> "; const DEBUG_PREFIX = "<Assets module> ";
const UPDATE_INTERVAL = 1000;
let ASSETS_JSON_URL = "https://raw.githubusercontent.com/SillyTavern/SillyTavern-Content/main/index.json" let ASSETS_JSON_URL = "https://raw.githubusercontent.com/SillyTavern/SillyTavern-Content/main/index.json"
const extensionName = "assets"; const extensionName = "assets";
@ -30,83 +28,83 @@ const defaultSettings = {
} }
function downloadAssetsList(url) { function downloadAssetsList(url) {
updateCurrentAssets().then(function(){ updateCurrentAssets().then(function () {
fetch(url) fetch(url)
.then(response => response.json()) .then(response => response.json())
.then(json => { .then(json => {
availableAssets = {};
$("#assets_menu").empty();
console.debug(DEBUG_PREFIX,"Received assets dictionary", json); availableAssets = {};
$("#assets_menu").empty();
for(const i of json){ console.debug(DEBUG_PREFIX, "Received assets dictionary", json);
//console.log(DEBUG_PREFIX,i)
if (availableAssets[i["type"]] === undefined)
availableAssets[i["type"]] = [];
availableAssets[i["type"]].push(i);
}
console.debug(DEBUG_PREFIX,"Updated available assets to",availableAssets); for (const i of json) {
//console.log(DEBUG_PREFIX,i)
if (availableAssets[i["type"]] === undefined)
availableAssets[i["type"]] = [];
for (const assetType in availableAssets) { availableAssets[i["type"]].push(i);
let assetTypeMenu = $('<div />', {id:"assets_audio_ambient_div", class:"assets-list-div"});
assetTypeMenu.append(`<h3>${assetType}</h3>`)
for (const i in availableAssets[assetType]) {
const asset = availableAssets[assetType][i];
const elemId = `assets_install_${assetType}_${i}`;
let element = $('<button />', { id:elemId, type:"button", class:"asset-download-button menu_button"})
const label = $("<i class=\"fa-solid fa-download fa-xl\"></i>");
element.append(label);
//if (DEBUG_TONY_SAMA_FORK_MODE)
// assetUrl = assetUrl.replace("https://github.com/SillyTavern/","https://github.com/Tony-sama/"); // DBG
console.debug(DEBUG_PREFIX,"Checking asset",asset["id"], asset["url"]);
if (isAssetInstalled(assetType, asset["id"])) {
console.debug(DEBUG_PREFIX,"installed, checked");
label.toggleClass("fa-download");
label.toggleClass("fa-check");
}
else {
console.debug(DEBUG_PREFIX,"not installed, unchecked")
element.prop("checked",false);
element.on("click", async function(){
element.off("click");
label.toggleClass("fa-download");
this.classList.toggle('asset-download-button-loading');
await installAsset(asset["url"], assetType, asset["id"]);
label.toggleClass("fa-check");
this.classList.toggle('asset-download-button-loading');
})
}
console.debug(DEBUG_PREFIX,"Created element for BGM",asset["id"])
$(`<i></i>`)
.append(element)
.append(`<span>${asset["id"]}</span>`)
.appendTo(assetTypeMenu);
} }
assetTypeMenu.appendTo("#assets_menu");
}
$("#assets_menu").show(); console.debug(DEBUG_PREFIX, "Updated available assets to", availableAssets);
})
.catch((error) => { for (const assetType in availableAssets) {
console.error(error); let assetTypeMenu = $('<div />', { id: "assets_audio_ambient_div", class: "assets-list-div" });
toastr.error("Problem with assets URL",DEBUG_PREFIX+"Cannot get assets list"); assetTypeMenu.append(`<h3>${assetType}</h3>`)
$('#assets-connect-button').addClass("fa-plug-circle-xmark"); for (const i in availableAssets[assetType]) {
}); const asset = availableAssets[assetType][i];
const elemId = `assets_install_${assetType}_${i}`;
let element = $('<button />', { id: elemId, type: "button", class: "asset-download-button menu_button" })
const label = $("<i class=\"fa-solid fa-download fa-xl\"></i>");
element.append(label);
//if (DEBUG_TONY_SAMA_FORK_MODE)
// assetUrl = assetUrl.replace("https://github.com/SillyTavern/","https://github.com/Tony-sama/"); // DBG
console.debug(DEBUG_PREFIX, "Checking asset", asset["id"], asset["url"]);
if (isAssetInstalled(assetType, asset["id"])) {
console.debug(DEBUG_PREFIX, "installed, checked");
label.toggleClass("fa-download");
label.toggleClass("fa-check");
}
else {
console.debug(DEBUG_PREFIX, "not installed, unchecked")
element.prop("checked", false);
element.on("click", async function () {
element.off("click");
label.toggleClass("fa-download");
this.classList.toggle('asset-download-button-loading');
await installAsset(asset["url"], assetType, asset["id"]);
label.toggleClass("fa-check");
this.classList.toggle('asset-download-button-loading');
})
}
console.debug(DEBUG_PREFIX, "Created element for BGM", asset["id"])
$(`<i></i>`)
.append(element)
.append(`<span>${asset["id"]}</span>`)
.appendTo(assetTypeMenu);
}
assetTypeMenu.appendTo("#assets_menu");
}
$("#assets_menu").show();
})
.catch((error) => {
console.error(error);
toastr.error("Problem with assets URL", DEBUG_PREFIX + "Cannot get assets list");
$('#assets-connect-button').addClass("fa-plug-circle-xmark");
});
}); });
} }
function isAssetInstalled(assetType,filename) { function isAssetInstalled(assetType, filename) {
for(const i of currentAssets[assetType]){ for (const i of currentAssets[assetType]) {
//console.debug(DEBUG_PREFIX,i,filename) //console.debug(DEBUG_PREFIX,i,filename)
if(i.includes(filename)) if (i.includes(filename))
return true; return true;
} }
@ -114,15 +112,18 @@ function isAssetInstalled(assetType,filename) {
} }
async function installAsset(url, assetType, filename) { async function installAsset(url, assetType, filename) {
console.debug(DEBUG_PREFIX,"Downloading ",url); console.debug(DEBUG_PREFIX, "Downloading ", url);
const category = assetType; const category = assetType;
try { try {
const result = await fetch(`/asset_download?url=${url}&category=${category}&filename=${filename}`, { const body = { url, category, filename };
const result = await fetch('/asset_download', {
method: 'POST', method: 'POST',
headers: getRequestHeaders(), headers: getRequestHeaders(),
body: JSON.stringify(body),
cache: 'no-cache',
}); });
if(result.ok) { if (result.ok) {
console.debug(DEBUG_PREFIX,"Download success.") console.debug(DEBUG_PREFIX, "Download success.")
} }
} }
catch (err) { catch (err) {
@ -136,7 +137,7 @@ async function installAsset(url, assetType, filename) {
//#############################// //#############################//
async function updateCurrentAssets() { async function updateCurrentAssets() {
console.debug(DEBUG_PREFIX,"Checking installed assets...") console.debug(DEBUG_PREFIX, "Checking installed assets...")
try { try {
const result = await fetch(`/get_assets`, { const result = await fetch(`/get_assets`, {
method: 'POST', method: 'POST',
@ -147,7 +148,7 @@ async function updateCurrentAssets() {
catch (err) { catch (err) {
console.log(err); console.log(err);
} }
console.debug(DEBUG_PREFIX,"Current assets found:",currentAssets) console.debug(DEBUG_PREFIX, "Current assets found:", currentAssets)
} }
@ -164,11 +165,11 @@ jQuery(async () => {
assetsJsonUrl.val(ASSETS_JSON_URL); assetsJsonUrl.val(ASSETS_JSON_URL);
const connectButton = windowHtml.find('#assets-connect-button'); const connectButton = windowHtml.find('#assets-connect-button');
connectButton.on("click", async function(){ connectButton.on("click", async function () {
const confirmation = await callPopup(`Are you sure you want to connect to '${assetsJsonUrl.val()}'?`, 'confirm') const confirmation = await callPopup(`Are you sure you want to connect to '${assetsJsonUrl.val()}'?`, 'confirm')
if (confirmation) { if (confirmation) {
try { try {
console.debug(DEBUG_PREFIX,"Confimation, loading assets..."); console.debug(DEBUG_PREFIX, "Confimation, loading assets...");
downloadAssetsList(assetsJsonUrl.val()); downloadAssetsList(assetsJsonUrl.val());
connectButton.removeClass("fa-plug"); connectButton.removeClass("fa-plug");
connectButton.removeClass("fa-plug-circle-xmark"); connectButton.removeClass("fa-plug-circle-xmark");
@ -182,9 +183,9 @@ jQuery(async () => {
} }
} }
else { else {
console.debug(DEBUG_PREFIX,"Connection refused by user"); console.debug(DEBUG_PREFIX, "Connection refused by user");
} }
}); });
$('#extensions_settings').append(windowHtml); $('#extensions_settings').append(windowHtml);
}); });

View File

@ -11,7 +11,7 @@ Ideas:
import { saveSettingsDebounced, getRequestHeaders } from "../../../script.js"; import { saveSettingsDebounced, getRequestHeaders } from "../../../script.js";
import { getContext, extension_settings, ModuleWorkerWrapper } from "../../extensions.js"; import { getContext, extension_settings, ModuleWorkerWrapper } from "../../extensions.js";
import {isDataURL} from "../../utils.js"; import { isDataURL } from "../../utils.js";
export { MODULE_NAME }; export { MODULE_NAME };
const extensionName = "audio"; const extensionName = "audio";
@ -96,7 +96,7 @@ function loadSettings() {
$("#audio_character_bgm_volume_slider").val(extension_settings.audio.bgm_volume); $("#audio_character_bgm_volume_slider").val(extension_settings.audio.bgm_volume);
$("#audio_ambient_volume_slider").val(extension_settings.audio.ambient_volume); $("#audio_ambient_volume_slider").val(extension_settings.audio.ambient_volume);
if (extension_settings.audio.bgm_muted) { if (extension_settings.audio.bgm_muted) {
$("#audio_character_bgm_mute_icon").toggleClass("fa-volume-high"); $("#audio_character_bgm_mute_icon").toggleClass("fa-volume-high");
$("#audio_character_bgm_mute_icon").toggleClass("fa-volume-mute"); $("#audio_character_bgm_mute_icon").toggleClass("fa-volume-mute");
@ -146,7 +146,7 @@ async function onAmbientMuteClick() {
async function onBGMVolumeChange() { async function onBGMVolumeChange() {
extension_settings.audio.bgm_volume = ~~($("#audio_character_bgm_volume_slider").val()); extension_settings.audio.bgm_volume = ~~($("#audio_character_bgm_volume_slider").val());
$("#audio_character_bgm").prop("volume",extension_settings.audio.bgm_volume * 0.01); $("#audio_character_bgm").prop("volume", extension_settings.audio.bgm_volume * 0.01);
$("#audio_character_bgm_volume").text(extension_settings.audio.bgm_volume); $("#audio_character_bgm_volume").text(extension_settings.audio.bgm_volume);
saveSettingsDebounced(); saveSettingsDebounced();
//console.debug(DEBUG_PREFIX,"UPDATED BGM MAX TO",extension_settings.audio.bgm_volume); //console.debug(DEBUG_PREFIX,"UPDATED BGM MAX TO",extension_settings.audio.bgm_volume);
@ -154,7 +154,7 @@ async function onBGMVolumeChange() {
async function onAmbientVolumeChange() { async function onAmbientVolumeChange() {
extension_settings.audio.ambient_volume = ~~($("#audio_ambient_volume_slider").val()); extension_settings.audio.ambient_volume = ~~($("#audio_ambient_volume_slider").val());
$("#audio_ambient").prop("volume",extension_settings.audio.ambient_volume * 0.01); $("#audio_ambient").prop("volume", extension_settings.audio.ambient_volume * 0.01);
$("#audio_ambient_volume").text(extension_settings.audio.ambient_volume); $("#audio_ambient_volume").text(extension_settings.audio.ambient_volume);
saveSettingsDebounced(); saveSettingsDebounced();
//console.debug(DEBUG_PREFIX,"UPDATED Ambient MAX TO",extension_settings.audio.ambient_volume); //console.debug(DEBUG_PREFIX,"UPDATED Ambient MAX TO",extension_settings.audio.ambient_volume);
@ -164,7 +164,7 @@ async function onBGMCooldownInput() {
extension_settings.audio.bgm_cooldown = ~~($("#audio_bgm_cooldown").val()); extension_settings.audio.bgm_cooldown = ~~($("#audio_bgm_cooldown").val());
cooldownBGM = extension_settings.audio.bgm_cooldown * 1000; cooldownBGM = extension_settings.audio.bgm_cooldown * 1000;
saveSettingsDebounced(); saveSettingsDebounced();
console.debug(DEBUG_PREFIX,"UPDATED BGM cooldown to",extension_settings.audio.bgm_cooldown); console.debug(DEBUG_PREFIX, "UPDATED BGM cooldown to", extension_settings.audio.bgm_cooldown);
} }
//#############################// //#############################//
@ -172,15 +172,15 @@ async function onBGMCooldownInput() {
//#############################// //#############################//
async function getAssetsList(type) { async function getAssetsList(type) {
console.debug(DEBUG_PREFIX, "getting assets of type",type); console.debug(DEBUG_PREFIX, "getting assets of type", type);
try { try {
const result = await fetch(`/get_assets`, { const result = await fetch(`/get_assets`, {
method: 'POST', method: 'POST',
headers: getRequestHeaders(), headers: getRequestHeaders(),
}); });
const assets = result.ok ? (await result.json()) : {type:[]}; const assets = result.ok ? (await result.json()) : { type: [] };
console.debug(DEBUG_PREFIX, "Found assets:",assets); console.debug(DEBUG_PREFIX, "Found assets:", assets);
return assets[type]; return assets[type];
} }
catch (err) { catch (err) {
@ -222,21 +222,21 @@ async function moduleWorker() {
if (moduleEnabled) { if (moduleEnabled) {
if(cooldownBGM > 0) if (cooldownBGM > 0)
cooldownBGM -= UPDATE_INTERVAL; cooldownBGM -= UPDATE_INTERVAL;
if (fallback_BGMS == null){ if (fallback_BGMS == null) {
console.debug(DEBUG_PREFIX,"Updating audio bgm assets..."); console.debug(DEBUG_PREFIX, "Updating audio bgm assets...");
fallback_BGMS = await getAssetsList(ASSETS_BGM_FOLDER); fallback_BGMS = await getAssetsList(ASSETS_BGM_FOLDER);
fallback_BGMS = fallback_BGMS.filter((filename) => filename != ".placeholder") fallback_BGMS = fallback_BGMS.filter((filename) => filename != ".placeholder")
console.debug(DEBUG_PREFIX,"Detected assets:",fallback_BGMS); console.debug(DEBUG_PREFIX, "Detected assets:", fallback_BGMS);
} }
if (ambients == null){ if (ambients == null) {
console.debug(DEBUG_PREFIX,"Updating audio ambient assets..."); console.debug(DEBUG_PREFIX, "Updating audio ambient assets...");
ambients = await getAssetsList(ASSETS_AMBIENT_FOLDER); ambients = await getAssetsList(ASSETS_AMBIENT_FOLDER);
ambients = ambients.filter((filename) => filename != ".placeholder") ambients = ambients.filter((filename) => filename != ".placeholder")
console.debug(DEBUG_PREFIX,"Detected assets:",ambients); console.debug(DEBUG_PREFIX, "Detected assets:", ambients);
} }
// 1) Update ambient audio // 1) Update ambient audio
@ -244,19 +244,18 @@ async function moduleWorker() {
let newBackground = $("#bg1").css("background-image"); let newBackground = $("#bg1").css("background-image");
const custom_background = getContext()["chatMetadata"]["custom_background"]; const custom_background = getContext()["chatMetadata"]["custom_background"];
if(custom_background !== undefined) if (custom_background !== undefined)
newBackground = custom_background newBackground = custom_background
if (!isDataURL(newBackground)) if (!isDataURL(newBackground)) {
{ newBackground = newBackground.substring(newBackground.lastIndexOf("/") + 1).replace(/\.[^/.]+$/, "").replaceAll("%20", "-").replaceAll(" ", "-"); // remove path and spaces
newBackground = newBackground.substring(newBackground.lastIndexOf("/")+1).replace(/\.[^/.]+$/, "").replaceAll("%20","-").replaceAll(" ","-"); // remove path and spaces
//console.debug(DEBUG_PREFIX,"Current backgroung:",newBackground); //console.debug(DEBUG_PREFIX,"Current backgroung:",newBackground);
if (currentBackground !== newBackground) { if (currentBackground !== newBackground) {
currentBackground = newBackground; currentBackground = newBackground;
console.debug(DEBUG_PREFIX,"Changing ambient audio for",currentBackground); console.debug(DEBUG_PREFIX, "Changing ambient audio for", currentBackground);
updateAmbient(); updateAmbient();
} }
} }
@ -282,7 +281,7 @@ async function moduleWorker() {
await loadCharacterBGM(newCharacter); await loadCharacterBGM(newCharacter);
currentExpressionBGM = FALLBACK_EXPRESSION; currentExpressionBGM = FALLBACK_EXPRESSION;
//currentCharacterBGM = newCharacter; //currentCharacterBGM = newCharacter;
//updateBGM(); //updateBGM();
//cooldownBGM = BGM_UPDATE_COOLDOWN; //cooldownBGM = BGM_UPDATE_COOLDOWN;
return; return;
@ -295,8 +294,8 @@ async function moduleWorker() {
await updateBGM(); await updateBGM();
cooldownBGM = extension_settings.audio.bgm_cooldown * 1000; cooldownBGM = extension_settings.audio.bgm_cooldown * 1000;
} }
catch(error){ catch (error) {
console.debug(DEBUG_PREFIX,"Error while trying to update BGM character, will try again"); console.debug(DEBUG_PREFIX, "Error while trying to update BGM character, will try again");
currentCharacterBGM = null currentCharacterBGM = null
} }
return; return;
@ -306,7 +305,7 @@ async function moduleWorker() {
// 1.3) Same character but different expression // 1.3) Same character but different expression
if (currentExpressionBGM !== newExpression) { if (currentExpressionBGM !== newExpression) {
// Check cooldown // Check cooldown
if (cooldownBGM > 0) { if (cooldownBGM > 0) {
//console.debug(DEBUG_PREFIX,"(SOLO) BGM switch on cooldown:",cooldownBGM); //console.debug(DEBUG_PREFIX,"(SOLO) BGM switch on cooldown:",cooldownBGM);
@ -317,10 +316,10 @@ async function moduleWorker() {
await updateBGM(); await updateBGM();
cooldownBGM = extension_settings.audio.bgm_cooldown * 1000; cooldownBGM = extension_settings.audio.bgm_cooldown * 1000;
currentExpressionBGM = newExpression; currentExpressionBGM = newExpression;
console.debug(DEBUG_PREFIX,"(SOLO) Updated current character expression to",currentExpressionBGM,"cooldown",cooldownBGM); console.debug(DEBUG_PREFIX, "(SOLO) Updated current character expression to", currentExpressionBGM, "cooldown", cooldownBGM);
} }
catch(error){ catch (error) {
console.debug(DEBUG_PREFIX,"Error while trying to update BGM expression, will try again"); console.debug(DEBUG_PREFIX, "Error while trying to update BGM expression, will try again");
currentCharacterBGM = null currentCharacterBGM = null
} }
return; return;
@ -331,9 +330,9 @@ async function moduleWorker() {
// 2) Update BGM (group chat) // 2) Update BGM (group chat)
// ----------------------------- // -----------------------------
newCharacter = context.chat[context.chat.length-1].name; newCharacter = context.chat[context.chat.length - 1].name;
const userName = context.name1; const userName = context.name1;
if (newCharacter !== undefined && newCharacter != userName) { if (newCharacter !== undefined && newCharacter != userName) {
//console.log(DEBUG_PREFIX,"GROUP CHAT MODE"); // DBG //console.log(DEBUG_PREFIX,"GROUP CHAT MODE"); // DBG
@ -351,17 +350,17 @@ async function moduleWorker() {
//console.debug(DEBUG_PREFIX,"(GROUP) BGM switch on cooldown:",cooldownBGM); //console.debug(DEBUG_PREFIX,"(GROUP) BGM switch on cooldown:",cooldownBGM);
return; return;
} }
try { try {
currentCharacterBGM = newCharacter; currentCharacterBGM = newCharacter;
await updateBGM(); await updateBGM();
cooldownBGM = extension_settings.audio.bgm_cooldown * 1000; cooldownBGM = extension_settings.audio.bgm_cooldown * 1000;
currentCharacterBGM = newCharacter; currentCharacterBGM = newCharacter;
currentExpressionBGM = FALLBACK_EXPRESSION; currentExpressionBGM = FALLBACK_EXPRESSION;
console.debug(DEBUG_PREFIX,"(GROUP) Updated current character BGM to",currentExpressionBGM,"cooldown",cooldownBGM); console.debug(DEBUG_PREFIX, "(GROUP) Updated current character BGM to", currentExpressionBGM, "cooldown", cooldownBGM);
} }
catch(error){ catch (error) {
console.debug(DEBUG_PREFIX,"Error while trying to update BGM group, will try again"); console.debug(DEBUG_PREFIX, "Error while trying to update BGM group, will try again");
currentCharacterBGM = null currentCharacterBGM = null
} }
return; return;
@ -372,7 +371,7 @@ async function moduleWorker() {
// 1.3) Same character but different expression // 1.3) Same character but different expression
if (currentExpressionBGM !== newExpression) { if (currentExpressionBGM !== newExpression) {
// Check cooldown // Check cooldown
if (cooldownBGM > 0) { if (cooldownBGM > 0) {
console.debug(DEBUG_PREFIX,"BGM switch on cooldown:",cooldownBGM); console.debug(DEBUG_PREFIX,"BGM switch on cooldown:",cooldownBGM);
@ -389,44 +388,44 @@ async function moduleWorker() {
return;*/ return;*/
} }
// Case 3: Same character/expression or BGM switch on cooldown keep playing same BGM // Case 3: Same character/expression or BGM switch on cooldown keep playing same BGM
//console.debug(DEBUG_PREFIX,"Nothing to do for",currentCharacterBGM, newCharacter, currentExpressionBGM, cooldownBGM); //console.debug(DEBUG_PREFIX,"Nothing to do for",currentCharacterBGM, newCharacter, currentExpressionBGM, cooldownBGM);
} }
} }
async function loadCharacterBGM(newCharacter) { async function loadCharacterBGM(newCharacter) {
console.debug(DEBUG_PREFIX,"New character detected, loading BGM folder of",newCharacter); console.debug(DEBUG_PREFIX, "New character detected, loading BGM folder of", newCharacter);
// 1.1) First time character appear, load its music folder // 1.1) First time character appear, load its music folder
const audio_file_paths = await getCharacterBgmList(newCharacter); const audio_file_paths = await getCharacterBgmList(newCharacter);
//console.debug(DEBUG_PREFIX, "Recieved", audio_file_paths); //console.debug(DEBUG_PREFIX, "Recieved", audio_file_paths);
// Initialise expression/files mapping // Initialise expression/files mapping
characterMusics[newCharacter] = {}; characterMusics[newCharacter] = {};
for(const e of DEFAULT_EXPRESSIONS) for (const e of DEFAULT_EXPRESSIONS)
characterMusics[newCharacter][e] = []; characterMusics[newCharacter][e] = [];
for(const i of audio_file_paths) { for (const i of audio_file_paths) {
//console.debug(DEBUG_PREFIX,"File found:",i); //console.debug(DEBUG_PREFIX,"File found:",i);
for(const e of DEFAULT_EXPRESSIONS) for (const e of DEFAULT_EXPRESSIONS)
if (i.includes(e)) if (i.includes(e))
characterMusics[newCharacter][e].push(i); characterMusics[newCharacter][e].push(i);
} }
console.debug(DEBUG_PREFIX,"Updated BGM map of",newCharacter,"to",characterMusics[newCharacter]); console.debug(DEBUG_PREFIX, "Updated BGM map of", newCharacter, "to", characterMusics[newCharacter]);
} }
function getNewExpression() { function getNewExpression() {
let newExpression; let newExpression;
// HACK: use sprite file name as expression detection // HACK: use sprite file name as expression detection
if (!$(SPRITE_DOM_ID).length) { if (!$(SPRITE_DOM_ID).length) {
console.error(DEBUG_PREFIX,"ERROR: expression sprite does not exist, cannot extract expression from ",SPRITE_DOM_ID) console.error(DEBUG_PREFIX, "ERROR: expression sprite does not exist, cannot extract expression from ", SPRITE_DOM_ID)
return FALLBACK_EXPRESSION; return FALLBACK_EXPRESSION;
} }
const spriteFile = $("#expression-image").attr("src"); const spriteFile = $("#expression-image").attr("src");
newExpression = spriteFile.substring(spriteFile.lastIndexOf("/")+1).replace(/\.[^/.]+$/, ""); newExpression = spriteFile.substring(spriteFile.lastIndexOf("/") + 1).replace(/\.[^/.]+$/, "");
// //
// No sprite to detect expression // No sprite to detect expression
@ -436,7 +435,7 @@ function getNewExpression() {
} }
if (!DEFAULT_EXPRESSIONS.includes(newExpression)) { if (!DEFAULT_EXPRESSIONS.includes(newExpression)) {
console.info(DEBUG_PREFIX,"Warning:",newExpression," is not a handled expression, expected one of",FALLBACK_EXPRESSION); console.info(DEBUG_PREFIX, "Warning:", newExpression, " is not a handled expression, expected one of", FALLBACK_EXPRESSION);
return FALLBACK_EXPRESSION; return FALLBACK_EXPRESSION;
} }
@ -446,54 +445,54 @@ function getNewExpression() {
async function updateBGM() { async function updateBGM() {
let audio_files = characterMusics[currentCharacterBGM][currentExpressionBGM];// Try char expression BGM let audio_files = characterMusics[currentCharacterBGM][currentExpressionBGM];// Try char expression BGM
if (audio_files === undefined || audio_files.length == 0) { if (audio_files === undefined || audio_files.length == 0) {
console.debug(DEBUG_PREFIX,"No BGM for", currentCharacterBGM,currentExpressionBGM); console.debug(DEBUG_PREFIX, "No BGM for", currentCharacterBGM, currentExpressionBGM);
audio_files = characterMusics[currentCharacterBGM][FALLBACK_EXPRESSION]; // Try char FALLBACK BGM audio_files = characterMusics[currentCharacterBGM][FALLBACK_EXPRESSION]; // Try char FALLBACK BGM
if (audio_files === undefined || audio_files.length == 0) { if (audio_files === undefined || audio_files.length == 0) {
console.debug(DEBUG_PREFIX,"No default BGM for",currentCharacterBGM,FALLBACK_EXPRESSION, "switch to ST BGM"); console.debug(DEBUG_PREFIX, "No default BGM for", currentCharacterBGM, FALLBACK_EXPRESSION, "switch to ST BGM");
audio_files = fallback_BGMS; // ST FALLBACK BGM audio_files = fallback_BGMS; // ST FALLBACK BGM
if(audio_files.length == 0) { if (audio_files.length == 0) {
console.debug(DEBUG_PREFIX,"No default BGM file found, bgm folder may be empty."); console.debug(DEBUG_PREFIX, "No default BGM file found, bgm folder may be empty.");
return; return;
} }
} }
} }
const audio_file_path = audio_files[Math.floor(Math.random() * audio_files.length)]; const audio_file_path = audio_files[Math.floor(Math.random() * audio_files.length)];
console.log(DEBUG_PREFIX,"Updating BGM"); console.log(DEBUG_PREFIX, "Updating BGM");
console.log(DEBUG_PREFIX,"Checking file",audio_file_path); console.log(DEBUG_PREFIX, "Checking file", audio_file_path);
try { try {
const response = await fetch(audio_file_path); const response = await fetch(audio_file_path);
if (!response.ok) { if (!response.ok) {
console.log(DEBUG_PREFIX,"File not found!") console.log(DEBUG_PREFIX, "File not found!")
} }
else { else {
console.log(DEBUG_PREFIX,"Switching BGM to",currentExpressionBGM) console.log(DEBUG_PREFIX, "Switching BGM to", currentExpressionBGM)
const audio = $("#audio_character_bgm"); const audio = $("#audio_character_bgm");
if (audio.attr("src") == audio_file_path) { if (audio.attr("src") == audio_file_path) {
console.log(DEBUG_PREFIX,"Already playing, ignored"); console.log(DEBUG_PREFIX, "Already playing, ignored");
return; return;
} }
audio.animate({volume: 0.0}, 2000, function() { audio.animate({ volume: 0.0 }, 2000, function () {
audio.attr("src",audio_file_path); audio.attr("src", audio_file_path);
audio[0].play(); audio[0].play();
audio.volume = extension_settings.audio.bgm_volume * 0.01; audio.volume = extension_settings.audio.bgm_volume * 0.01;
audio.animate({volume: extension_settings.audio.bgm_volume * 0.01}, 2000); audio.animate({ volume: extension_settings.audio.bgm_volume * 0.01 }, 2000);
}) })
} }
} catch(error) { } catch (error) {
console.log(DEBUG_PREFIX,"Error while trying to fetch",audio_file_path,":",error); console.log(DEBUG_PREFIX, "Error while trying to fetch", audio_file_path, ":", error);
} }
} }
async function updateAmbient() { async function updateAmbient() {
let audio_file_path = null; let audio_file_path = null;
for(const i of ambients) { for (const i of ambients) {
console.debug(i) console.debug(i)
if (i.includes(currentBackground)) { if (i.includes(currentBackground)) {
audio_file_path = i; audio_file_path = i;
@ -502,23 +501,23 @@ async function updateAmbient() {
} }
if (audio_file_path === null) { if (audio_file_path === null) {
console.debug(DEBUG_PREFIX,"No ambient file found for background",currentBackground); console.debug(DEBUG_PREFIX, "No ambient file found for background", currentBackground);
const audio = $("#audio_ambient"); const audio = $("#audio_ambient");
audio.attr("src",""); audio.attr("src", "");
audio[0].pause(); audio[0].pause();
return; return;
} }
//const audio_file_path = AMBIENT_FOLDER+currentBackground+".mp3"; //const audio_file_path = AMBIENT_FOLDER+currentBackground+".mp3";
console.log(DEBUG_PREFIX,"Updating ambient"); console.log(DEBUG_PREFIX, "Updating ambient");
console.log(DEBUG_PREFIX,"Checking file",audio_file_path); console.log(DEBUG_PREFIX, "Checking file", audio_file_path);
const audio = $("#audio_ambient"); const audio = $("#audio_ambient");
audio.animate({volume: 0.0}, 2000, function() { audio.animate({ volume: 0.0 }, 2000, function () {
audio.attr("src",audio_file_path); audio.attr("src", audio_file_path);
audio[0].play(); audio[0].play();
audio.volume = extension_settings.audio.ambient_volume * 0.01; audio.volume = extension_settings.audio.ambient_volume * 0.01;
audio.animate({volume: extension_settings.audio.ambient_volume * 0.01}, 2000); audio.animate({ volume: extension_settings.audio.ambient_volume * 0.01 }, 2000);
}); });
} }
@ -533,14 +532,14 @@ jQuery(async () => {
$('#extensions_settings').append(windowHtml); $('#extensions_settings').append(windowHtml);
loadSettings(); loadSettings();
$("#audio_character_bgm").attr("loop",true); $("#audio_character_bgm").attr("loop", true);
$("#audio_ambient").attr("loop",true); $("#audio_ambient").attr("loop", true);
$("#audio_character_bgm").hide(); $("#audio_character_bgm").hide();
$("#audio_ambient").hide(); $("#audio_ambient").hide();
$("#audio_character_bgm_mute").on("click",onBGMMuteClick); $("#audio_character_bgm_mute").on("click", onBGMMuteClick);
$("#audio_character_ambient_mute").on("click",onAmbientMuteClick); $("#audio_character_ambient_mute").on("click", onAmbientMuteClick);
$("#audio_enabled").on("click", onEnabledClick); $("#audio_enabled").on("click", onEnabledClick);
$("#audio_character_bgm_volume_slider").on("input", onBGMVolumeChange); $("#audio_character_bgm_volume_slider").on("input", onBGMVolumeChange);
@ -549,8 +548,8 @@ jQuery(async () => {
$("#audio_bgm_cooldown").on("input", onBGMCooldownInput); $("#audio_bgm_cooldown").on("input", onBGMCooldownInput);
// DBG // DBG
$("#audio_debug").on("click",function() { $("#audio_debug").on("click", function () {
if($("#audio_debug").is(':checked')) { if ($("#audio_debug").is(':checked')) {
$("#audio_character_bgm").show(); $("#audio_character_bgm").show();
$("#audio_ambient").show(); $("#audio_ambient").show();
} }
@ -564,4 +563,4 @@ jQuery(async () => {
const wrapper = new ModuleWorkerWrapper(moduleWorker); const wrapper = new ModuleWorkerWrapper(moduleWorker);
setInterval(wrapper.update.bind(wrapper), UPDATE_INTERVAL); setInterval(wrapper.update.bind(wrapper), UPDATE_INTERVAL);
moduleWorker(); moduleWorker();
}); });

View File

@ -5022,20 +5022,20 @@ app.post('/get_assets', jsonParser, async (request, response) => {
try { try {
if (fs.existsSync(folderPath) && fs.statSync(folderPath).isDirectory()) { if (fs.existsSync(folderPath) && fs.statSync(folderPath).isDirectory()) {
const folders = fs.readdirSync(folderPath) const folders = fs.readdirSync(folderPath)
.filter(filename => { .filter(filename => {
return fs.statSync(path.join(folderPath,filename)).isDirectory(); return fs.statSync(path.join(folderPath, filename)).isDirectory();
}); });
for (const folder of folders) { for (const folder of folders) {
if (folder == "temp") if (folder == "temp")
continue; continue;
const files = fs.readdirSync(path.join(folderPath,folder)) const files = fs.readdirSync(path.join(folderPath, folder))
.filter(filename => { .filter(filename => {
return filename != ".placeholder"; return filename != ".placeholder";
}); });
output[folder] = []; output[folder] = [];
for (const file of files){ for (const file of files) {
output[folder].push(path.join("assets",folder,file)); output[folder].push(path.join("assets", folder, file));
} }
} }
} }
@ -5057,18 +5057,16 @@ app.post('/get_assets', jsonParser, async (request, response) => {
* @returns {void} * @returns {void}
*/ */
app.post('/asset_download', jsonParser, async (request, response) => { app.post('/asset_download', jsonParser, async (request, response) => {
const fs = require('fs');
const { Readable } = require('stream'); const { Readable } = require('stream');
const { finished } = require('stream/promises'); const { finished } = require('stream/promises');
const path = require("path"); const url = request.body.url;
const url = request.query.url; const inputCategory = request.body.category;
const inputCategory = request.query.category; const inputFilename = sanitize(request.body.filename);
const inputFilename = request.query.filename; const validCategories = ["bgm", "ambient"]
const validCategories = ["bgm","ambient"]
// Check category // Check category
let category = null let category = null
for(i of validCategories) for (i of validCategories)
if (i == inputCategory) if (i == inputCategory)
category = i category = i
@ -5091,7 +5089,7 @@ app.post('/asset_download', jsonParser, async (request, response) => {
const safe_input = path.normalize(inputFilename).replace(/^(\.\.(\/|\\|$))+/, ''); const safe_input = path.normalize(inputFilename).replace(/^(\.\.(\/|\\|$))+/, '');
const temp_path = path.join(directories.assets, "temp", safe_input) const temp_path = path.join(directories.assets, "temp", safe_input)
const file_path = path.join(directories.assets, category, safe_input) const file_path = path.join(directories.assets, category, safe_input)
console.debug("Request received to download", url,"to",file_path); console.debug("Request received to download", url, "to", file_path);
try { try {
// Download to temp // Download to temp
@ -5111,21 +5109,17 @@ app.post('/asset_download', jsonParser, async (request, response) => {
await downloadFile(url, temp_path); await downloadFile(url, temp_path);
// Move into asset place // Move into asset place
console.debug("Download finished, moving file from",temp_path,"to",file_path); console.debug("Download finished, moving file from", temp_path, "to", file_path);
fs.rename(temp_path,file_path, (err) => { fs.renameSync(temp_path, file_path);
if (err) throw err;
console.log('Rename complete!');
});
response.sendStatus(200); response.sendStatus(200);
} }
catch(error) { catch (error) {
console.log(error); console.log(error);
response.sendStatus(500); response.sendStatus(500);
} }
}); });
/////////////////////////////// ///////////////////////////////
/** /**
* HTTP POST handler function to retrieve a character background music list. * HTTP POST handler function to retrieve a character background music list.
@ -5136,13 +5130,13 @@ app.post('/asset_download', jsonParser, async (request, response) => {
* @returns {void} * @returns {void}
*/ */
app.post('/get_character_assets_list', jsonParser, async (request, response) => { app.post('/get_character_assets_list', jsonParser, async (request, response) => {
const name = request.query.name; const name = sanitize(request.query.name);
const inputCategory = request.query.category; const inputCategory = request.query.category;
const validCategories = ["bgm","ambient"] const validCategories = ["bgm", "ambient"]
// Check category // Check category
let category = null let category = null
for(i of validCategories) for (i of validCategories)
if (i == inputCategory) if (i == inputCategory)
category = i category = i
@ -5157,13 +5151,13 @@ app.post('/get_character_assets_list', jsonParser, async (request, response) =>
try { try {
if (fs.existsSync(folderPath) && fs.statSync(folderPath).isDirectory()) { if (fs.existsSync(folderPath) && fs.statSync(folderPath).isDirectory()) {
const files = fs.readdirSync(folderPath) const files = fs.readdirSync(folderPath)
.filter(filename => { .filter(filename => {
return filename != ".placeholder"; return filename != ".placeholder";
}); });
for (i of files) for (i of files)
output.push(`/characters/${name}/${category}/${i}`); output.push(`/characters/${name}/${category}/${i}`);
} }
return response.send(output); return response.send(output);
} }
@ -5171,7 +5165,4 @@ app.post('/get_character_assets_list', jsonParser, async (request, response) =>
console.log(err); console.log(err);
return response.sendStatus(500); return response.sendStatus(500);
} }
finally { });
}
});