From 0ee19d2ede4e6eec2e2514a7f97e9db7e67170b2 Mon Sep 17 00:00:00 2001 From: valadaptive Date: Fri, 15 Dec 2023 05:43:27 -0500 Subject: [PATCH] Set background client-side --- Dockerfile | 3 +- default/bg_load.css | 1 - docker/docker-entrypoint.sh | 5 --- post-install.js | 26 ++++++++++++++- public/index.html | 1 - public/script.js | 9 +++++- public/scripts/backgrounds.js | 59 +++++++++++++++++------------------ public/scripts/horde.js | 2 +- server.js | 1 - src/endpoints/backgrounds.js | 12 ------- 10 files changed, 64 insertions(+), 55 deletions(-) delete mode 100644 default/bg_load.css diff --git a/Dockerfile b/Dockerfile index 0f4e6c0be..7e58a1817 100644 --- a/Dockerfile +++ b/Dockerfile @@ -31,10 +31,9 @@ RUN \ echo "*** Create symbolic links to config directory ***" && \ for R in $RESOURCES; do ln -s "../config/$R" "public/$R"; done || true && \ \ - rm -f "config.yaml" "public/settings.json" "public/css/bg_load.css" || true && \ + rm -f "config.yaml" "public/settings.json" || true && \ ln -s "./config/config.yaml" "config.yaml" || true && \ ln -s "../config/settings.json" "public/settings.json" || true && \ - ln -s "../../config/bg_load.css" "public/css/bg_load.css" || true && \ mkdir "config" || true # Cleanup unnecessary files diff --git a/default/bg_load.css b/default/bg_load.css deleted file mode 100644 index 3470a163f..000000000 --- a/default/bg_load.css +++ /dev/null @@ -1 +0,0 @@ -#bg1 {background-image: url(../backgrounds/__transparent.png);} diff --git a/docker/docker-entrypoint.sh b/docker/docker-entrypoint.sh index 8f0cdf86e..bafbdaf62 100644 --- a/docker/docker-entrypoint.sh +++ b/docker/docker-entrypoint.sh @@ -19,11 +19,6 @@ if [ ! -e "config/settings.json" ]; then cp -r "default/settings.json" "config/settings.json" fi -if [ ! -e "config/bg_load.css" ]; then - echo "Resource not found, copying from defaults: bg_load.css" - cp -r "default/bg_load.css" "config/bg_load.css" -fi - CONFIG_FILE="config.yaml" echo "Starting with the following config:" diff --git a/post-install.js b/post-install.js index 33ee9a2ba..51d303c8c 100644 --- a/post-install.js +++ b/post-install.js @@ -107,7 +107,6 @@ function addMissingConfigValues() { function createDefaultFiles() { const files = { settings: './public/settings.json', - bg_load: './public/css/bg_load.css', config: './config.yaml', user: './public/css/user.css', }; @@ -168,6 +167,29 @@ function copyWasmFiles() { } } +/** + * Moves the custom background into settings.json. + */ +function migrateBackground() { + if (!fs.existsSync('./public/css/bg_load.css')) return; + + const bgCSS = fs.readFileSync('./public/css/bg_load.css', 'utf-8'); + const bgMatch = /url\('([^']*)'\)/.exec(bgCSS); + if (!bgMatch) return; + const bgFilename = bgMatch[1].replace('../backgrounds/', ''); + + const settings = fs.readFileSync('./public/settings.json', 'utf-8'); + const settingsJSON = JSON.parse(settings); + if (Object.hasOwn(settingsJSON, 'background')) { + console.log(color.yellow('Both bg_load.css and the "background" setting exist. Please delete bg_load.css manually.')); + return; + } + + settingsJSON.background = { file: bgFilename, url: `url('backgrounds/${bgFilename}')` }; + fs.writeFileSync('./public/settings.json', JSON.stringify(settingsJSON, null, 4)); + fs.rmSync('./public/css/bg_load.css'); +} + try { // 0. Convert config.conf to config.yaml convertConfig(); @@ -177,6 +199,8 @@ try { copyWasmFiles(); // 3. Add missing config values addMissingConfigValues(); + // 4. Migrate bg_load.css to settings.json + migrateBackground(); } catch (error) { console.error(error); } diff --git a/public/index.html b/public/index.html index 54fcf1a47..b0d21d081 100644 --- a/public/index.html +++ b/public/index.html @@ -61,7 +61,6 @@ - diff --git a/public/script.js b/public/script.js index 9d35eec7f..dbdfcf9ff 100644 --- a/public/script.js +++ b/public/script.js @@ -187,7 +187,7 @@ import { import { applyLocale, initLocales } from './scripts/i18n.js'; import { getFriendlyTokenizerName, getTokenCount, getTokenizerModel, initTokenizers, saveTokenCache } from './scripts/tokenizers.js'; import { createPersona, initPersonas, selectCurrentPersona, setPersonaDescription } from './scripts/personas.js'; -import { getBackgrounds, initBackgrounds } from './scripts/backgrounds.js'; +import { getBackgrounds, initBackgrounds, loadBackgroundSettings, background_settings } from './scripts/backgrounds.js'; import { hideLoader, showLoader } from './scripts/loader.js'; import { BulkEditOverlay, CharacterContextMenu } from './scripts/BulkEditOverlay.js'; import { loadMancerModels } from './scripts/mancer-settings.js'; @@ -5674,6 +5674,9 @@ async function getSettings() { // Load character tags loadTagsSettings(settings); + // Load background + loadBackgroundSettings(settings); + // Allow subscribers to mutate settings eventSource.emit(event_types.SETTINGS_LOADED_AFTER, settings); @@ -5756,6 +5759,9 @@ async function saveSettings(type) { console.warn('Settings not ready, aborting save'); return; } + + console.log(background_settings); + //console.log('Entering settings with name1 = '+name1); return jQuery.ajax({ @@ -5785,6 +5791,7 @@ async function saveSettings(type) { nai_settings: nai_settings, kai_settings: kai_settings, oai_settings: oai_settings, + background: background_settings, }, null, 4), beforeSend: function () { }, cache: false, diff --git a/public/scripts/backgrounds.js b/public/scripts/backgrounds.js index 70465122e..e462cb8f7 100644 --- a/public/scripts/backgrounds.js +++ b/public/scripts/backgrounds.js @@ -1,4 +1,4 @@ -import { callPopup, chat_metadata, eventSource, event_types, generateQuietPrompt, getCurrentChatId, getRequestHeaders, getThumbnailUrl } from '../script.js'; +import { callPopup, chat_metadata, eventSource, event_types, generateQuietPrompt, getCurrentChatId, getRequestHeaders, getThumbnailUrl, saveSettingsDebounced } from '../script.js'; import { saveMetadataDebounced } from './extensions.js'; import { registerSlashCommand } from './slash-commands.js'; import { stringFormat } from './utils.js'; @@ -6,6 +6,19 @@ import { stringFormat } from './utils.js'; const BG_METADATA_KEY = 'custom_background'; const LIST_METADATA_KEY = 'chat_backgrounds'; +export let background_settings = { + name: '__transparent.png', + url: generateUrlParameter('__transparent.png', false), +}; + +export function loadBackgroundSettings(settings) { + let backgroundSettings = settings.background; + if (!backgroundSettings || !backgroundSettings.name || !backgroundSettings.url) { + backgroundSettings = background_settings; + } + setBackground(backgroundSettings.name, backgroundSettings.url); +} + /** * Sets the background for the current chat and adds it to the list of custom backgrounds. * @param {{url: string, path:string}} backgroundInfo @@ -141,9 +154,8 @@ function onSelectBackgroundClick() { saveBackgroundMetadata(relativeBgImage); setCustomBackground(); highlightLockedBackground(); - } else { - highlightLockedBackground(); } + highlightLockedBackground(); const customBg = window.getComputedStyle(document.getElementById('bg_custom')).backgroundImage; @@ -157,8 +169,7 @@ function onSelectBackgroundClick() { // Fetching to browser memory to reduce flicker fetch(backgroundUrl).then(() => { - $('#bg1').css('background-image', relativeBgImage); - setBackground(bgFile); + setBackground(bgFile, relativeBgImage); }).catch(() => { console.log('Background could not be set: ' + backgroundUrl); }); @@ -333,7 +344,7 @@ export async function getBackgrounds() { '': '', }), }); - if (response.ok === true) { + if (response.ok) { const getData = await response.json(); //background = getData; //console.log(getData.length); @@ -346,7 +357,7 @@ export async function getBackgrounds() { } /** - * Gets the URL of the background + * Gets the CSS URL of the background * @param {Element} block * @returns {string} URL of the background */ @@ -354,6 +365,10 @@ function getUrlParameter(block) { return $(block).closest('.bg_example').data('url'); } +function generateUrlParameter(bg, isCustom) { + return isCustom ? `url("${encodeURI(bg)}")` : `url("${getBackgroundPath(bg)}")`; +} + /** * Instantiates a background template * @param {string} bg Path to background @@ -363,7 +378,7 @@ function getUrlParameter(block) { function getBackgroundFromTemplate(bg, isCustom) { const template = $('#background_template .bg_example').clone(); const thumbPath = isCustom ? bg : getThumbnailUrl('bg', bg); - const url = isCustom ? `url("${encodeURI(bg)}")` : `url("${getBackgroundPath(bg)}")`; + const url = generateUrlParameter(bg, isCustom); const title = isCustom ? bg.split('/').pop() : bg; const friendlyTitle = title.slice(0, title.lastIndexOf('.')); template.attr('title', title); @@ -375,26 +390,11 @@ function getBackgroundFromTemplate(bg, isCustom) { return template; } -async function setBackground(bg) { - jQuery.ajax({ - type: 'POST', // - url: '/api/backgrounds/set', // - data: JSON.stringify({ - bg: bg, - }), - beforeSend: function () { - - }, - cache: false, - dataType: 'json', - contentType: 'application/json', - //processData: false, - success: function (html) { }, - error: function (jqXHR, exception) { - console.log(exception); - console.log(jqXHR); - }, - }); +async function setBackground(bg, url) { + $('#bg1').css('background-image', url); + background_settings.name = bg; + background_settings.url = url; + saveSettingsDebounced(); } async function delBackground(bg) { @@ -435,8 +435,7 @@ function uploadBackground(formData) { contentType: false, processData: false, success: async function (bg) { - setBackground(bg); - $('#bg1').css('background-image', `url("${getBackgroundPath(bg)}"`); + setBackground(bg, generateUrlParameter(bg, false)); await getBackgrounds(); highlightNewBackground(bg); }, diff --git a/public/scripts/horde.js b/public/scripts/horde.js index fbf6bf0d4..21153f087 100644 --- a/public/scripts/horde.js +++ b/public/scripts/horde.js @@ -41,7 +41,7 @@ const getRequestArgs = () => ({ }, }); -async function getWorkers() { +async function getWorkers(workerType) { const response = await fetch('https://horde.koboldai.net/api/v2/workers?type=text', getRequestArgs()); const data = await response.json(); return data; diff --git a/server.js b/server.js index 43420d14b..57b95ed28 100644 --- a/server.js +++ b/server.js @@ -544,7 +544,6 @@ redirect('/updatestats', '/api/stats/update'); // Redirect deprecated backgrounds API endpoints redirect('/getbackgrounds', '/api/backgrounds/all'); -redirect('/setbackground', '/api/backgrounds/set'); redirect('/delbackground', '/api/backgrounds/delete'); redirect('/renamebackground', '/api/backgrounds/rename'); redirect('/downloadbackground', '/api/backgrounds/upload'); // yes, the downloadbackground endpoint actually uploads one diff --git a/src/endpoints/backgrounds.js b/src/endpoints/backgrounds.js index 73c84cb20..ffcaed559 100644 --- a/src/endpoints/backgrounds.js +++ b/src/endpoints/backgrounds.js @@ -2,7 +2,6 @@ const fs = require('fs'); const path = require('path'); const express = require('express'); const sanitize = require('sanitize-filename'); -const writeFileAtomicSync = require('write-file-atomic').sync; const { jsonParser, urlencodedParser } = require('../express-common'); const { DIRECTORIES, UPLOADS_PATH } = require('../constants'); @@ -17,17 +16,6 @@ router.post('/all', jsonParser, function (request, response) { }); -router.post('/set', jsonParser, function (request, response) { - try { - const bg = `#bg1 {background-image: url('../backgrounds/${request.body.bg}');}`; - writeFileAtomicSync('public/css/bg_load.css', bg, 'utf8'); - response.send({ result: 'ok' }); - } catch (err) { - console.log(err); - response.send(err); - } -}); - router.post('/delete', jsonParser, function (request, response) { if (!request.body) return response.sendStatus(400);