Files
jukebox_maker/web/templates/settings.html

411 lines
14 KiB
HTML

{{define "content"}}
<form id="settingsForm" onsubmit="saveSettings(event)">
<section class="panel">
<h2>Copy Sources</h2>
<div class="panel-body">
<div class="form-hint">Add one or more root folders with source files. After that, expand each root and enable or disable individual nested folders with checkboxes.</div>
</div>
<div class="btn-row">
<button type="button" class="button-primary" onclick="addSourceRoot()">Add source folder</button>
<button type="button" class="button-secondary button-sm" onclick="reloadAllSourceTrees()">Refresh trees</button>
</div>
<div class="source-list">
<div class="source-tree" id="sourceTree">
<div class="text-muted source-tree-empty">No source folders added yet.</div>
</div>
</div>
</section>
<section class="panel">
<h2>Copy Settings</h2>
<div class="form-body">
<div class="form-group">
<label class="form-label" for="reserveGB">Reserved free space on disk (GB)</label>
<input class="form-input" type="number" id="reserveGB" min="0" max="1000" step="0.5" value="2">
<span class="form-hint">Copying will stop when free space falls below this value.</span>
</div>
<div class="form-group">
<label class="form-label" for="fileSelectMode">Files to copy</label>
<select class="form-select" id="fileSelectMode" style="width:auto;max-width:420px">
<option value="new">Only new files not copied to this disk before</option>
<option value="all">All matching files</option>
</select>
<span class="form-hint">The new-only mode skips files already copied to this disk, even if they were later removed.</span>
</div>
<div class="form-group">
<label class="form-label" for="destFolder">Destination folder on disk</label>
<input class="form-input" type="text" id="destFolder" placeholder="media" style="width:200px">
<span class="form-hint">Files will be copied into this subfolder while preserving the selected source structure. The disk root and <code>.jukebox</code> are never allowed here.</span>
</div>
<div class="form-group">
<label class="form-label" for="overwriteMode">Default write mode</label>
<select class="form-select" id="overwriteMode" style="width:auto;max-width:420px">
<option value="skip">Keep existing files</option>
<option value="delete">Replace destination folder contents</option>
</select>
<span class="form-hint">This is used for automatic copy runs. Manual dashboard actions can override it.</span>
</div>
</div>
</section>
<section class="panel">
<h2>Automation</h2>
<div class="form-body">
<div class="form-group">
<label style="display:flex;align-items:center;gap:8px;cursor:pointer">
<input type="checkbox" id="autoCopy" style="width:15px;height:15px;accent-color:var(--accent)">
<span class="form-label" style="margin:0">Automatic copy</span>
</label>
<span class="form-hint">Start copying automatically when a known disk is detected.</span>
</div>
</div>
</section>
<div style="display:flex;gap:8px;margin-bottom:24px">
<button type="submit" class="button-primary">Save settings</button>
<button type="button" class="button-secondary" onclick="loadSettings()">Reset</button>
</div>
</form>
<script>
const sourceTree = new Map();
const expandedNodes = new Set();
const loadingNodes = new Set();
let sourceRoots = [];
let sourceConfig = {};
function escapeHTML(value) {
return String(value || '').replace(/[&<>"']/g, (char) => ({
'&': '&amp;',
'<': '&lt;',
'>': '&gt;',
'"': '&quot;',
"'": '&#39;'
}[char]));
}
function pathSegments(path) {
return String(path || '').split(/[\\/]+/).filter(Boolean);
}
function nodeName(path) {
const parts = pathSegments(path);
return parts.length ? parts[parts.length - 1] : path;
}
function normalizeComparePath(path) {
return String(path || '').replace(/\\/g, '/').replace(/\/+$/, '').toLowerCase();
}
function isSamePath(a, b) {
return normalizeComparePath(a) === normalizeComparePath(b);
}
function isPathWithin(base, candidate) {
const baseNorm = normalizeComparePath(base);
const candidateNorm = normalizeComparePath(candidate);
return candidateNorm === baseNorm || candidateNorm.startsWith(baseNorm + '/');
}
function parentPath(path) {
const value = String(path || '').replace(/[\\/]+$/, '');
const slash = Math.max(value.lastIndexOf('/'), value.lastIndexOf('\\'));
if (slash < 0) return '';
if (slash === 2 && /^[A-Za-z]:/.test(value)) return value.slice(0, slash + 1);
if (slash === 0) return value.slice(0, 1);
return value.slice(0, slash);
}
function relativeDepth(root, path) {
if (isSamePath(root, path)) return 0;
const rootParts = pathSegments(root);
const pathParts = pathSegments(path);
return Math.max(0, pathParts.length - rootParts.length);
}
function effectiveSourceState(path) {
let current = path;
while (true) {
if (Object.prototype.hasOwnProperty.call(sourceConfig, current)) {
return sourceConfig[current];
}
current = parentPath(current);
if (!current) return true;
}
}
function collectSourcesForSave() {
const items = [];
const seen = new Set();
sourceRoots.forEach((root) => {
items.push({ path: root, enabled: effectiveSourceState(root), root: true });
seen.add(normalizeComparePath(root));
});
Object.entries(sourceConfig).forEach(([path, enabled]) => {
const key = normalizeComparePath(path);
if (seen.has(key)) return;
items.push({ path, enabled, root: false });
});
return items.sort((a, b) => a.path.localeCompare(b.path));
}
async function pickFolder() {
const response = await fetch('/api/system/pick-folder', { method: 'POST' });
const payload = await response.json();
if (!response.ok) {
throw new Error(payload.error || 'Failed to choose folder');
}
return payload.path || '';
}
async function loadSourceChildren(path) {
if (!path || loadingNodes.has(path)) return;
loadingNodes.add(path);
renderSources();
try {
const response = await fetch('/api/sources?path=' + encodeURIComponent(path));
if (!response.ok) return;
const payload = await response.json();
sourceTree.set(path, payload.items || []);
} catch (error) {
} finally {
loadingNodes.delete(path);
renderSources();
}
}
async function ensureExpanded(path) {
expandedNodes.add(path);
if (!sourceTree.has(path)) {
await loadSourceChildren(path);
return;
}
renderSources();
}
function toggleSource(path, checked) {
sourceConfig[path] = checked;
renderSources();
}
function removeRoot(path) {
sourceRoots = sourceRoots.filter((root) => !isSamePath(root, path));
sourceTree.delete(path);
expandedNodes.delete(path);
loadingNodes.delete(path);
Object.keys(sourceConfig).forEach((key) => {
if (isPathWithin(path, key)) {
delete sourceConfig[key];
}
});
renderSources();
}
async function addSourceRoot() {
try {
const path = await pickFolder();
if (!path) return;
if (sourceRoots.some((root) => isSamePath(root, path))) {
toast('This source folder is already added', 'error');
return;
}
sourceRoots.push(path);
sourceRoots.sort((a, b) => a.localeCompare(b));
sourceConfig[path] = true;
expandedNodes.add(path);
await loadSourceChildren(path);
} catch (error) {
toast(error.message || 'Failed to choose folder', 'error');
}
}
async function reloadAllSourceTrees() {
const roots = [...sourceRoots];
sourceTree.clear();
for (const root of roots) {
if (expandedNodes.has(root)) {
await loadSourceChildren(root);
}
}
renderSources();
}
function renderSourceNodes(root, parentPathValue) {
const items = sourceTree.get(parentPathValue) || [];
return items.map((item) => {
const checked = effectiveSourceState(item.path);
const expanded = expandedNodes.has(item.path);
const childrenKnown = sourceTree.has(item.path);
const children = childrenKnown ? sourceTree.get(item.path) : [];
const hasChildren = !childrenKnown || children.length > 0;
const pad = 16 + (relativeDepth(root, item.path) + 1) * 20;
return `
<div class="source-node">
<div class="source-row" style="padding-left:${pad}px">
<button
type="button"
class="source-toggle ${hasChildren ? '' : 'source-toggle-empty'}"
data-action="toggle-expand"
data-path="${escapeHTML(item.path)}"
${hasChildren ? '' : 'tabindex="-1" aria-hidden="true"'}
>${expanded ? '▾' : '▸'}</button>
<input class="source-check" type="checkbox" data-action="toggle-check" data-path="${escapeHTML(item.path)}" ${checked ? 'checked' : ''}>
<div class="source-label">
<span class="source-item-name">${escapeHTML(item.name)}</span>
<span class="source-item-path">${escapeHTML(item.path)}</span>
</div>
</div>
${expanded && loadingNodes.has(item.path) ? '<div class="source-loading">Loading...</div>' : ''}
${expanded && childrenKnown && children.length ? `<div class="source-children">${renderSourceNodes(root, item.path)}</div>` : ''}
</div>
`;
}).join('');
}
function renderSources() {
const el = document.getElementById('sourceTree');
if (!sourceRoots.length) {
el.innerHTML = '<div class="text-muted source-tree-empty">No source folders added yet.</div>';
return;
}
el.innerHTML = sourceRoots.map((root) => {
const checked = effectiveSourceState(root);
const expanded = expandedNodes.has(root);
const childrenKnown = sourceTree.has(root);
const children = childrenKnown ? sourceTree.get(root) : [];
const hasChildren = !childrenKnown || children.length > 0;
return `
<div class="source-root-card">
<div class="source-row source-root-row">
<button
type="button"
class="source-toggle ${hasChildren ? '' : 'source-toggle-empty'}"
data-action="toggle-expand"
data-path="${escapeHTML(root)}"
${hasChildren ? '' : 'tabindex="-1" aria-hidden="true"'}
>${expanded ? '▾' : '▸'}</button>
<input class="source-check" type="checkbox" data-action="toggle-check" data-path="${escapeHTML(root)}" ${checked ? 'checked' : ''}>
<div class="source-label">
<div class="source-root-title">
<span class="source-item-name">${escapeHTML(nodeName(root))}</span>
<span class="source-root-badge">Root</span>
</div>
<span class="source-item-path">${escapeHTML(root)}</span>
</div>
<button type="button" class="button-secondary button-sm" data-action="remove-root" data-path="${escapeHTML(root)}">Remove</button>
</div>
${expanded && loadingNodes.has(root) ? '<div class="source-loading">Loading...</div>' : ''}
${expanded && childrenKnown && children.length ? `<div class="source-children">${renderSourceNodes(root, root)}</div>` : ''}
</div>
`;
}).join('');
}
function deriveRootsFromSources(sources) {
const explicitRoots = sources.filter((source) => source.root).map((source) => source.path);
if (explicitRoots.length) {
return explicitRoots;
}
return sources
.map((source) => source.path)
.filter((path, index, all) => !all.some((other, otherIndex) => otherIndex !== index && isPathWithin(other, path) && !isSamePath(other, path)));
}
async function loadSettings() {
try {
const r = await fetch('/api/config');
if (!r.ok) return;
const cfg = await r.json();
document.getElementById('reserveGB').value = cfg.reserve_free_gb ?? 2;
document.getElementById('destFolder').value = cfg.dest_folder || 'media';
document.getElementById('fileSelectMode').value = cfg.file_select_mode || 'new';
document.getElementById('overwriteMode').value = cfg.overwrite_mode || 'skip';
document.getElementById('autoCopy').checked = !!cfg.auto_copy;
sourceConfig = {};
(cfg.sources || []).forEach((source) => {
sourceConfig[source.path] = !!source.enabled;
});
sourceRoots = deriveRootsFromSources(cfg.sources || []).sort((a, b) => a.localeCompare(b));
expandedNodes.clear();
sourceTree.clear();
await reloadAllSourceTrees();
} catch (error) {}
}
async function saveSettings(event) {
event.preventDefault();
const body = {
reserve_free_gb: parseFloat(document.getElementById('reserveGB').value) || 2,
dest_folder: document.getElementById('destFolder').value.trim() || 'media',
file_select_mode: document.getElementById('fileSelectMode').value,
overwrite_mode: document.getElementById('overwriteMode').value,
auto_copy: document.getElementById('autoCopy').checked,
sources: collectSourcesForSave(),
};
try {
const response = await fetch('/api/config', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
});
if (response.ok) {
toast('Settings saved', 'ok');
await loadSettings();
return;
}
const payload = await response.json();
toast(payload.error || 'Failed to save settings', 'error');
} catch (error) {
toast('Network error', 'error');
}
}
document.getElementById('sourceTree').addEventListener('click', async (event) => {
const button = event.target.closest('button[data-action]');
if (!button) return;
const action = button.dataset.action;
const path = button.dataset.path;
if (action === 'toggle-expand') {
if (expandedNodes.has(path)) {
expandedNodes.delete(path);
renderSources();
return;
}
await ensureExpanded(path);
}
if (action === 'remove-root') {
removeRoot(path);
}
});
document.getElementById('sourceTree').addEventListener('change', (event) => {
const checkbox = event.target.closest('[data-action="toggle-check"]');
if (!checkbox) return;
toggleSource(checkbox.dataset.path, checkbox.checked);
});
loadSettings();
</script>
{{end}}