Assets extension, factorised using the received json type to organise the assets in the UI/folders.

This commit is contained in:
Tony Ribeiro
2023-08-23 05:10:55 +02:00
parent 8e38229ed4
commit 13dac1f4d3
5 changed files with 89 additions and 177 deletions

View File

@ -16,15 +16,8 @@ let ASSETS_JSON_URL = "https://raw.githubusercontent.com/SillyTavern/SillyTavern
// DBG // DBG
//if (DEBUG_TONY_SAMA_FORK_MODE) //if (DEBUG_TONY_SAMA_FORK_MODE)
// ASSETS_JSON_URL = "https://raw.githubusercontent.com/Tony-sama/SillyTavern-Content/main/index.json" // ASSETS_JSON_URL = "https://raw.githubusercontent.com/Tony-sama/SillyTavern-Content/main/index.json"
let availableAssets = {};
let assetDictFormat = { let currentAssets = {};
"audio":{
"ambient": [],
"bgm":[],
}};
let availableAssets = JSON.parse(JSON.stringify(assetDictFormat));
let currentAssets = JSON.parse(JSON.stringify(assetDictFormat));
//#############################// //#############################//
// Extension UI and Settings // // Extension UI and Settings //
@ -41,89 +34,51 @@ function loadSettings() {
console.debug(DEBUG_PREFIX,"Received assets dictionary", json); console.debug(DEBUG_PREFIX,"Received assets dictionary", json);
for(const i of json){ for(const i of json){
console.log(DEBUG_PREFIX,i) //console.log(DEBUG_PREFIX,i)
if (i["type"] == "ambient"){ if (availableAssets[i["type"]] === undefined)
availableAssets["audio"]["ambient"].push(i); availableAssets[i["type"]] = [];
}
if (i["type"] == "bgm"){ availableAssets[i["type"]].push(i);
availableAssets["audio"]["bgm"].push(i);
}
} }
console.debug(DEBUG_PREFIX,"Updated available assets to",availableAssets); console.debug(DEBUG_PREFIX,"Updated available assets to",availableAssets);
// Audio for (const assetType in availableAssets) {
let assetTypeMenu = $('<div />', {id:"assets_audio_ambient_div", class:"assets-list-div"});
// Ambient assetTypeMenu.append(`<h3>${assetType}</h3>`)
for(const i in availableAssets["audio"]["ambient"]) { for (const i in availableAssets[assetType]) {
const assetId = availableAssets["audio"]["ambient"][i]["id"] const asset = availableAssets[assetType][i];
let assetUrl = availableAssets["audio"]["ambient"][i]["url"] const elemId = `assets_install_${assetType}_${i}`;
const elemId = `assets_install_ambient_${i}`; let element = $('<input />', { type: 'checkbox', id: elemId})
let element = $('<input />', { type: 'checkbox', id: elemId})
//if (DEBUG_TONY_SAMA_FORK_MODE)
//if (DEBUG_TONY_SAMA_FORK_MODE) // assetUrl = assetUrl.replace("https://github.com/SillyTavern/","https://github.com/Tony-sama/"); // DBG
// assetUrl = assetUrl.replace("https://github.com/SillyTavern/","https://github.com/Tony-sama/"); // DBG
console.debug(DEBUG_PREFIX,"Checking asset",asset["id"], asset["url"]);
console.debug(DEBUG_PREFIX,"Checking asset",assetId, assetUrl);
if (isAssetInstalled(assetType, asset["id"])) {
if (isAmbientInstalled(assetId)) { console.debug(DEBUG_PREFIX,"installed, checked")
console.debug(DEBUG_PREFIX,"installed, checked")
element.prop("disabled",true);
element.prop("checked",true);
}
else {
console.debug(DEBUG_PREFIX,"not installed, unchecked")
element.prop("checked",false);
element.on("click", function(){
installAmbient(assetUrl,assetId);
element.prop("disabled",true); element.prop("disabled",true);
element.off("click"); element.prop("checked",true);
}) }
else {
console.debug(DEBUG_PREFIX,"not installed, unchecked")
element.prop("checked",false);
element.on("click", function(){
installAsset(asset["url"], assetType, asset["id"]);
element.prop("disabled",true);
element.off("click");
})
}
console.debug(DEBUG_PREFIX,"Created element for BGM",asset["id"])
$(`<i></i>`)
.append(element)
.append(`<p>${asset["id"]}</p>`)
.appendTo(assetTypeMenu);
} }
assetTypeMenu.appendTo("#assets_menu");
console.debug(DEBUG_PREFIX,"Created element for BGM",assetId)
$(`<i></i>`)
.append(element)
.append(`<p>${assetId}</p>`)
.appendTo("#assets_audio_ambient_div");
}
// BGM
for(const i in availableAssets["audio"]["bgm"]) {
const assetId = availableAssets["audio"]["bgm"][i]["id"]
let assetUrl = availableAssets["audio"]["bgm"][i]["url"]
const elemId = `assets_install_bgm_${i}`;
let element = $('<input />', { type: 'checkbox', id: elemId})
//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",assetId, assetUrl);
if (isBgmInstalled(assetId)) {
console.debug(DEBUG_PREFIX,"installed, checked")
element.prop("disabled",true);
element.prop("checked",true);
}
else {
console.debug(DEBUG_PREFIX,"not installed, unchecked")
element.prop("checked",false);
element.on("click", function(){
installBgm(assetUrl,assetId);
element.prop("disabled",true);
element.off("click");
})
}
console.debug(DEBUG_PREFIX,"Created element for BGM",assetId)
$(`<i></i>`)
.append(element)
.append(`<p>${assetId}</p>`)
.appendTo("#assets_audio_bgm_div");
} }
}); });
}); });
@ -139,15 +94,6 @@ $(document).ready(function () {
<div class="inline-drawer-icon fa-solid fa-circle-chevron-down down"></div> <div class="inline-drawer-icon fa-solid fa-circle-chevron-down down"></div>
</div> </div>
<div class="inline-drawer-content" id="assets_menu"> <div class="inline-drawer-content" id="assets_menu">
<div id="assets_audio_div">
<h3>Audio</h3>
<h4>Ambient</h4>
<div id="assets_audio_ambient_div" class="assets-list-div">
</div>
<h4>BGM</h4>
<div id="assets_audio_bgm_div" class="assets-list-div">
</div>
</div>
</div> </div>
</div> </div>
</div> </div>
@ -164,9 +110,9 @@ $(document).ready(function () {
//moduleWorker(); //moduleWorker();
}) })
function isAmbientInstalled(filename) { function isAssetInstalled(assetType,filename) {
for(const i of currentAssets["audio"]["ambient"]){ 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;
} }
@ -174,37 +120,13 @@ function isAmbientInstalled(filename) {
return false; return false;
} }
function isBgmInstalled(filename) { async function installAsset(url, assetType, filename) {
for(const i of currentAssets["audio"]["bgm"]){
console.debug(DEBUG_PREFIX,i,filename)
if(i.includes(filename))
return true;
}
return false;
}
async function installAmbient(url, filename) {
console.debug(DEBUG_PREFIX,"Downloading ",url); console.debug(DEBUG_PREFIX,"Downloading ",url);
const save_path = "public/assets/audio/ambient/"+filename; const save_path = "public/assets/"+assetType+"/"+filename;
try { try {
const result = await fetch(`/asset_download?url=${url}&save_path=${save_path}`); const result = await fetch(`/asset_download?url=${url}&save_path=${save_path}`);
let musics = result.ok ? (await result.json()) : []; let assets = result.ok ? (await result.json()) : [];
return musics; return assets;
}
catch (err) {
console.log(err);
return [];
}
}
async function installBgm(url, filename) {
console.debug(DEBUG_PREFIX,"Downloading ",url);
const save_path = "public/assets/audio/bgm/"+filename;
try {
const result = await fetch(`/asset_download?url=${url}&save_path=${save_path}`);
let musics = result.ok ? (await result.json()) : [];
return musics;
} }
catch (err) { catch (err) {
console.log(err); console.log(err);
@ -218,42 +140,16 @@ async function installBgm(url, filename) {
async function updateCurrentAssets() { async function updateCurrentAssets() {
console.debug(DEBUG_PREFIX,"Checking installed assets...") console.debug(DEBUG_PREFIX,"Checking installed assets...")
let assetList try {
// Check Ambient list const result = await fetch(`/get_assets`);
assetList = await getAmbientList(); currentAssets = result.ok ? (await result.json()) : {};
currentAssets["audio"]["ambient"] = assetList; }
catch (err) {
// Check BGM list console.log(err);
assetList = await getBgmList(); }
currentAssets["audio"]["bgm"] = assetList;
console.debug(DEBUG_PREFIX,"Current assets found:",currentAssets) console.debug(DEBUG_PREFIX,"Current assets found:",currentAssets)
} }
async function getAmbientList() {
try {
const result = await fetch(`/get_default_ambient_list`);
let musics = result.ok ? (await result.json()) : [];
return musics;
}
catch (err) {
console.log(err);
return [];
}
}
async function getBgmList() {
try {
const result = await fetch(`/get_default_bgm_list`);
let musics = result.ok ? (await result.json()) : [];
return musics;
}
catch (err) {
console.log(err);
return [];
}
}
//#############################// //#############################//
// Module Worker // // Module Worker //

View File

@ -17,8 +17,8 @@ const MODULE_NAME = 'Audio';
const DEBUG_PREFIX = "<Audio module> "; const DEBUG_PREFIX = "<Audio module> ";
const UPDATE_INTERVAL = 1000; const UPDATE_INTERVAL = 1000;
const ASSETS_BGM_FOLDER = "audio/bgm"; const ASSETS_BGM_FOLDER = "bgm";
const ASSETS_AMBIENT_FOLDER = "audio/ambient"; const ASSETS_AMBIENT_FOLDER = "ambient";
const CHARACTER_BGM_FOLDER = "bgm" const CHARACTER_BGM_FOLDER = "bgm"
const FALLBACK_EXPRESSION = "neutral"; const FALLBACK_EXPRESSION = "neutral";
@ -106,6 +106,8 @@ function loadSettings() {
} }
$("#audio_bgm_cooldown").val(extension_settings.audio.bgm_cooldown); $("#audio_bgm_cooldown").val(extension_settings.audio.bgm_cooldown);
$("#audio_debug_div").hide(); // DBG
} }
async function onEnabledClick() { async function onEnabledClick() {
@ -176,10 +178,12 @@ $(document).ready(function () {
<input type="checkbox" id="audio_enabled" name="audio_enabled"> <input type="checkbox" id="audio_enabled" name="audio_enabled">
<small>Enabled</small> <small>Enabled</small>
</label> </label>
<label class="checkbox_label" for="audio_debug"> <div id="audio_debug_div">
<input type="checkbox" id="audio_debug" name="audio_debug"> <label class="checkbox_label" for="audio_debug">
<small>Debug</small> <input type="checkbox" id="audio_debug" name="audio_debug">
</label> <small>Debug</small>
</label>
</div>
</div> </div>
<div> <div>
<div> <div>
@ -253,13 +257,14 @@ $(document).ready(function () {
// API Calls // // API Calls //
//#############################// //#############################//
async function getAssetsList(folderPath) { async function getAssetsList(type) {
console.debug(DEBUG_PREFIX, "getting files from",folderPath); console.debug(DEBUG_PREFIX, "getting assets of type",type);
try { try {
const result = await fetch(`/get_assets_list?folderPath=${folderPath}`); const result = await fetch(`/get_assets`);
let file_paths = result.ok ? (await result.json()) : []; const assets = result.ok ? (await result.json()) : {type:[]};
return file_paths; console.debug(DEBUG_PREFIX, "Found assets:",assets);
return assets[type];
} }
catch (err) { catch (err) {
console.log(err); console.log(err);
@ -553,6 +558,9 @@ 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");
audio.attr("src","");
audio[0].pause();
return; return;
} }

View File

@ -4943,20 +4943,28 @@ app.post('/delete_extension', jsonParser, async (request, response) => {
* *
* @returns {void} * @returns {void}
*/ */
app.get('/get_assets_list', jsonParser, function (request, response) { app.get('/get_assets', jsonParser, function (request, response) {
const folderPath = path.join(directories.assets,request.query.folderPath); const folderPath = path.join(directories.assets);
let output = [] let output = {}
//console.info("Checking files into",folderPath); //console.info("Checking files into",folderPath);
try { try {
if (fs.existsSync(folderPath) && fs.statSync(folderPath).isDirectory()) { if (fs.existsSync(folderPath) && fs.statSync(folderPath).isDirectory()) {
const files = fs.readdirSync(folderPath) const folders = fs.readdirSync(folderPath)
.filter(filename => { .filter(filename => {
return filename != ".placeholder"; return fs.statSync(path.join(folderPath,filename)).isDirectory();
}); });
for (i of files) for (const folder of folders) {
output.push(`/assets/${request.query.folderPath}/${i}`); const files = fs.readdirSync(path.join(folderPath,folder))
.filter(filename => {
return filename != ".placeholder";
});
output[folder] = [];
for (const file of files){
output[folder].push(path.join("assets",folder,file));
}
}
} }
} }
catch (err) { catch (err) {