SillyTavern/public/scripts/extensions/assets/index.js

321 lines
13 KiB
JavaScript
Raw Normal View History

/*
TODO:
*/
2023-10-10 01:51:09 +02:00
//const DEBUG_TONY_SAMA_FORK_MODE = true
2023-12-02 19:04:51 +01:00
import { getRequestHeaders, callPopup } from '../../../script.js';
import { deleteExtension, extensionNames, installExtension, renderExtensionTemplate } from '../../extensions.js';
import { getStringHash, isValidUrl } from '../../utils.js';
export { MODULE_NAME };
2023-10-18 23:26:00 +02:00
const MODULE_NAME = 'assets';
2023-12-02 19:04:51 +01:00
const DEBUG_PREFIX = '<Assets module> ';
2023-10-16 01:09:43 +02:00
let previewAudio = null;
2023-12-02 20:11:06 +01:00
let ASSETS_JSON_URL = 'https://raw.githubusercontent.com/SillyTavern/SillyTavern-Content/main/index.json';
// DBG
//if (DEBUG_TONY_SAMA_FORK_MODE)
// ASSETS_JSON_URL = "https://raw.githubusercontent.com/Tony-sama/SillyTavern-Content/main/index.json"
let availableAssets = {};
let currentAssets = {};
//#############################//
// Extension UI and Settings //
//#############################//
function downloadAssetsList(url) {
2023-08-24 20:59:26 +02:00
updateCurrentAssets().then(function () {
2023-12-02 19:04:51 +01:00
fetch(url, { cache: 'no-cache' })
2023-08-24 20:59:26 +02:00
.then(response => response.json())
.then(json => {
2023-08-24 20:59:26 +02:00
availableAssets = {};
2023-12-02 19:04:51 +01:00
$('#assets_menu').empty();
2023-08-24 20:59:26 +02:00
2023-12-02 19:04:51 +01:00
console.debug(DEBUG_PREFIX, 'Received assets dictionary', json);
2023-08-24 20:59:26 +02:00
for (const i of json) {
//console.log(DEBUG_PREFIX,i)
2023-12-02 19:04:51 +01:00
if (availableAssets[i['type']] === undefined)
availableAssets[i['type']] = [];
2023-08-24 20:59:26 +02:00
2023-12-02 19:04:51 +01:00
availableAssets[i['type']].push(i);
2023-08-24 20:59:26 +02:00
}
2023-12-02 19:04:51 +01:00
console.debug(DEBUG_PREFIX, 'Updated available assets to', availableAssets);
2023-10-09 16:21:12 +02:00
// First extensions, then everything else
const assetTypes = Object.keys(availableAssets).sort((a, b) => (a === 'extension') ? -1 : (b === 'extension') ? 1 : 0);
2023-08-24 20:59:26 +02:00
2023-10-09 16:21:12 +02:00
for (const assetType of assetTypes) {
2023-12-02 19:04:51 +01:00
let assetTypeMenu = $('<div />', { id: 'assets_audio_ambient_div', class: 'assets-list-div' });
2023-12-02 20:11:06 +01:00
assetTypeMenu.append(`<h3>${assetType}</h3>`);
2023-10-27 12:07:56 +02:00
if (assetType == 'extension') {
assetTypeMenu.append(`
<div class="assets-list-git">
To download extensions from this page, you need to have <a href="https://git-scm.com/downloads" target="_blank">Git</a> installed.
</div>`);
}
2023-08-24 20:59:26 +02:00
for (const i in availableAssets[assetType]) {
const asset = availableAssets[assetType][i];
const elemId = `assets_install_${assetType}_${i}`;
2023-12-02 20:11:06 +01:00
let element = $('<button />', { id: elemId, type: 'button', class: 'asset-download-button menu_button' });
2023-12-02 19:04:51 +01:00
const label = $('<i class="fa-fw fa-solid fa-download fa-xl"></i>');
2023-08-24 20:59:26 +02:00
element.append(label);
//if (DEBUG_TONY_SAMA_FORK_MODE)
2023-10-10 01:51:09 +02:00
// asset["url"] = asset["url"].replace("https://github.com/SillyTavern/","https://github.com/Tony-sama/"); // DBG
2023-08-24 20:59:26 +02:00
2023-12-02 19:04:51 +01:00
console.debug(DEBUG_PREFIX, 'Checking asset', asset['id'], asset['url']);
2023-08-24 20:59:26 +02:00
const assetInstall = async function () {
2023-12-02 19:04:51 +01:00
element.off('click');
label.removeClass('fa-download');
this.classList.add('asset-download-button-loading');
2023-12-02 19:04:51 +01:00
await installAsset(asset['url'], assetType, asset['id']);
label.addClass('fa-check');
this.classList.remove('asset-download-button-loading');
2023-12-02 19:04:51 +01:00
element.on('click', assetDelete);
element.on('mouseenter', function () {
label.removeClass('fa-check');
label.addClass('fa-trash');
label.addClass('redOverlayGlow');
}).on('mouseleave', function () {
label.addClass('fa-check');
label.removeClass('fa-trash');
label.removeClass('redOverlayGlow');
});
};
2023-10-18 23:26:00 +02:00
const assetDelete = async function () {
2023-12-02 19:04:51 +01:00
element.off('click');
await deleteAsset(assetType, asset['id']);
label.removeClass('fa-check');
label.removeClass('redOverlayGlow');
label.removeClass('fa-trash');
label.addClass('fa-download');
element.off('mouseenter').off('mouseleave');
element.on('click', assetInstall);
2023-12-02 20:11:06 +01:00
};
2023-12-02 19:04:51 +01:00
if (isAssetInstalled(assetType, asset['id'])) {
console.debug(DEBUG_PREFIX, 'installed, checked');
label.toggleClass('fa-download');
label.toggleClass('fa-check');
element.on('click', assetDelete);
element.on('mouseenter', function () {
label.removeClass('fa-check');
label.addClass('fa-trash');
label.addClass('redOverlayGlow');
}).on('mouseleave', function () {
label.addClass('fa-check');
label.removeClass('fa-trash');
label.removeClass('redOverlayGlow');
});
2023-08-24 20:59:26 +02:00
}
else {
2023-12-02 20:11:06 +01:00
console.debug(DEBUG_PREFIX, 'not installed, unchecked');
2023-12-02 19:04:51 +01:00
element.prop('checked', false);
element.on('click', assetInstall);
2023-08-24 20:59:26 +02:00
}
2023-12-02 20:11:06 +01:00
console.debug(DEBUG_PREFIX, 'Created element for ', asset['id']);
2023-08-24 20:59:26 +02:00
2023-12-02 19:04:51 +01:00
const displayName = DOMPurify.sanitize(asset['name'] || asset['id']);
const description = DOMPurify.sanitize(asset['description'] || '');
const url = isValidUrl(asset['url']) ? asset['url'] : '';
2023-10-16 01:09:43 +02:00
const previewIcon = assetType == 'extension' ? 'fa-arrow-up-right-from-square' : 'fa-headphones-simple';
2023-12-02 19:04:51 +01:00
$('<i></i>')
2023-08-24 20:59:26 +02:00
.append(element)
2023-10-16 00:39:08 +02:00
.append(`<div class="flex-container flexFlowColumn">
<span class="flex-container alignitemscenter">
<b>${displayName}</b>
2023-10-16 01:09:43 +02:00
<a class="asset_preview" href="${url}" target="_blank" title="Preview in browser">
<i class="fa-solid fa-sm ${previewIcon}"></i>
2023-10-16 00:39:08 +02:00
</a>
</span>
<span>${description}</span>
</div>`)
2023-08-24 20:59:26 +02:00
.appendTo(assetTypeMenu);
}
2023-12-02 19:04:51 +01:00
assetTypeMenu.appendTo('#assets_menu');
2023-10-16 01:09:43 +02:00
assetTypeMenu.on('click', 'a.asset_preview', previewAsset);
}
2023-12-02 19:04:51 +01:00
$('#assets_menu').show();
2023-08-24 20:59:26 +02:00
})
.catch((error) => {
console.error(error);
2023-12-02 19:04:51 +01:00
toastr.error('Problem with assets URL', DEBUG_PREFIX + 'Cannot get assets list');
$('#assets-connect-button').addClass('fa-plug-circle-exclamation');
$('#assets-connect-button').addClass('redOverlayGlow');
2023-08-24 20:59:26 +02:00
});
});
}
2023-10-16 01:09:43 +02:00
function previewAsset(e) {
const href = $(this).attr('href');
const audioExtensions = ['.mp3', '.ogg', '.wav'];
if (audioExtensions.some(ext => href.endsWith(ext))) {
e.preventDefault();
if (previewAudio) {
previewAudio.pause();
if (previewAudio.src === href) {
previewAudio = null;
return;
}
}
previewAudio = new Audio(href);
previewAudio.play();
return;
}
}
2023-08-24 20:59:26 +02:00
function isAssetInstalled(assetType, filename) {
let assetList = currentAssets[assetType];
if (assetType == 'extension') {
2023-12-02 19:04:51 +01:00
const thirdPartyMarker = 'third-party/';
assetList = extensionNames.filter(x => x.startsWith(thirdPartyMarker)).map(x => x.replace(thirdPartyMarker, ''));
}
for (const i of assetList) {
//console.debug(DEBUG_PREFIX,i,filename)
2023-08-24 20:59:26 +02:00
if (i.includes(filename))
return true;
}
return false;
}
async function installAsset(url, assetType, filename) {
2023-12-02 19:04:51 +01:00
console.debug(DEBUG_PREFIX, 'Downloading ', url);
const category = assetType;
try {
if (category === 'extension') {
2023-12-02 20:11:06 +01:00
console.debug(DEBUG_PREFIX, 'Installing extension ', url);
await installExtension(url);
2023-12-02 20:11:06 +01:00
console.debug(DEBUG_PREFIX, 'Extension installed.');
return;
}
2023-08-24 20:59:26 +02:00
const body = { url, category, filename };
const result = await fetch('/api/assets/download', {
method: 'POST',
headers: getRequestHeaders(),
2023-08-24 20:59:26 +02:00
body: JSON.stringify(body),
cache: 'no-cache',
});
2023-08-24 20:59:26 +02:00
if (result.ok) {
2023-12-02 20:11:06 +01:00
console.debug(DEBUG_PREFIX, 'Download success.');
}
}
catch (err) {
console.log(err);
return [];
}
}
async function deleteAsset(assetType, filename) {
2023-12-02 19:04:51 +01:00
console.debug(DEBUG_PREFIX, 'Deleting ', assetType, filename);
const category = assetType;
try {
if (category === 'extension') {
2023-12-02 20:11:06 +01:00
console.debug(DEBUG_PREFIX, 'Deleting extension ', filename);
await deleteExtension(filename);
2023-12-02 20:11:06 +01:00
console.debug(DEBUG_PREFIX, 'Extension deleted.');
}
const body = { category, filename };
const result = await fetch('/api/assets/delete', {
method: 'POST',
headers: getRequestHeaders(),
body: JSON.stringify(body),
cache: 'no-cache',
});
if (result.ok) {
2023-12-02 20:11:06 +01:00
console.debug(DEBUG_PREFIX, 'Deletion success.');
}
}
catch (err) {
console.log(err);
return [];
}
}
//#############################//
// API Calls //
//#############################//
async function updateCurrentAssets() {
2023-12-02 20:11:06 +01:00
console.debug(DEBUG_PREFIX, 'Checking installed assets...');
try {
2023-12-02 19:04:51 +01:00
const result = await fetch('/api/assets/get', {
method: 'POST',
headers: getRequestHeaders(),
});
currentAssets = result.ok ? (await result.json()) : {};
}
catch (err) {
console.log(err);
}
2023-12-02 20:11:06 +01:00
console.debug(DEBUG_PREFIX, 'Current assets found:', currentAssets);
}
//#############################//
// Extension load //
//#############################//
// This function is called when the extension is loaded
jQuery(async () => {
// This is an example of loading HTML from a file
2023-10-18 23:26:00 +02:00
const windowHtml = $(renderExtensionTemplate(MODULE_NAME, 'window', {}));
2023-08-24 01:02:34 +02:00
const assetsJsonUrl = windowHtml.find('#assets-json-url-field');
assetsJsonUrl.val(ASSETS_JSON_URL);
2023-08-24 01:02:34 +02:00
const connectButton = windowHtml.find('#assets-connect-button');
2023-12-02 19:04:51 +01:00
connectButton.on('click', async function () {
2023-10-18 23:26:00 +02:00
const url = String(assetsJsonUrl.val());
const rememberKey = `Assets_SkipConfirm_${getStringHash(url)}`;
const skipConfirm = localStorage.getItem(rememberKey) === 'true';
const template = renderExtensionTemplate(MODULE_NAME, 'confirm', { url });
const confirmation = skipConfirm || await callPopup(template, 'confirm');
if (confirmation) {
try {
2023-10-18 23:26:00 +02:00
if (!skipConfirm) {
const rememberValue = Boolean($('#assets-remember').prop('checked'));
localStorage.setItem(rememberKey, String(rememberValue));
}
2023-12-02 19:04:51 +01:00
console.debug(DEBUG_PREFIX, 'Confimation, loading assets...');
2023-10-18 23:26:00 +02:00
downloadAssetsList(url);
2023-12-02 19:04:51 +01:00
connectButton.removeClass('fa-plug-circle-exclamation');
connectButton.removeClass('redOverlayGlow');
connectButton.addClass('fa-plug-circle-check');
} catch (error) {
console.error('Error:', error);
2023-10-18 23:26:00 +02:00
toastr.error(`Cannot get assets list from ${url}`);
2023-12-02 19:04:51 +01:00
connectButton.removeClass('fa-plug-circle-check');
connectButton.addClass('fa-plug-circle-exclamation');
connectButton.removeClass('redOverlayGlow');
}
}
else {
2023-12-02 19:04:51 +01:00
console.debug(DEBUG_PREFIX, 'Connection refused by user');
}
});
$('#extensions_settings').append(windowHtml);
2023-08-24 20:59:26 +02:00
});