diff --git a/.github/scripts/docker_saved_places_test.js b/.github/scripts/docker_saved_places_test.js index 1a28436a..96ec7187 100644 --- a/.github/scripts/docker_saved_places_test.js +++ b/.github/scripts/docker_saved_places_test.js @@ -1,7 +1,9 @@ -// node .github/scripts/docker_saved_places_test.js — a deleted folder or removed container still named in userprefs.cfg no longer -// moves a saved folder on the Docker page (npm ci in this folder first) +// node .github/scripts/docker_saved_places_test.js — where the Docker page puts saved folders: stale userprefs.cfg entries do not move +// them, and after sync_order.php (asked for once per load) regroups the file, the page draws its rows in its order (npm ci here first) 'use strict'; -const { drawDocker, check, done } = require('./preview_pages_harness.js'); +const fs = require('fs'); +const path = require('path'); +const { drawDocker, phpServer, check, done } = require('./preview_pages_harness.js'); const same = (a, b) => JSON.stringify(a) === JSON.stringify(b); const folder = (name, containers = [], regex = '') => ({ name, containers, regex }); @@ -65,5 +67,121 @@ const folder = (name, containers = [], regex = '') => ({ name, containers, regex check('the generated orders do place folders, with and without unsaved rows above them', shapes.folders > 50 && shapes.unsaved > 50 && shapes.both > 20, shapes); check('200 generated orders with nothing stale place every folder where they did before', differ.length === 0, differ.slice(0, 2)); } + // The real sync_order.php on a saved userprefs.cfg: its answers, the file after one sync, and after a second + const synced = (folders, containers, prefs) => { + const php = phpServer('userprefs-sync', { containers }); + try { + const dockerMan = path.join(path.dirname(php.config), 'dockerMan'); + const file = path.join(dockerMan, 'userprefs.cfg'); + fs.writeFileSync(path.join(php.config, 'docker.json'), JSON.stringify(folders)); + fs.writeFileSync(path.join(dockerMan, 'dockerMan.cfg'), `autostart-file="${path.join(dockerMan, 'unraid-autostart')}"\n`); + fs.writeFileSync(file, prefs.map((n, i) => `${i}="${n}"\n`).join('')); + const read = () => fs.readFileSync(file, 'utf8').split('\n').filter(Boolean).map((l) => l.replace(/^\d+="(.*)"$/, '$1')); + const first = php.server('sync_order.php', 'POST', { type: 'docker' }); + const after = read(); + return { answers: [first, php.server('sync_order.php', 'POST', { type: 'docker' })], after, again: read() }; + } finally { php.cleanup(); } + }; + const drawnFrom = async (folders, containers, prefs) => { const page = await drawDocker({ folders, containers, prefs }); await page.draw(); return page; }; + for (const [what, folders, containers, prefs] of [ + ['a folder member it lacks', { f: folder('F', ['x', 'y']) }, ['a', 'b', 'x', 'y'], ['a', 'folder-f', 'x', 'b']], + ['a member saved away from its folder', { f: folder('F', ['x', 'y']) }, ['a', 'b', 'x', 'y'], ['y', 'a', 'folder-f', 'x', 'b']], + ['a member moved to another folder', { f: folder('F', ['x']), g: folder('G', ['w', 'y']) }, ['w', 'x', 'y'], ['folder-f', 'x', 'y', 'folder-g', 'w']], + ['members saved before their folder', { f: folder('F', ['x', 'y']) }, ['a', 'x', 'y'], ['x', 'folder-f', 'a']], + ['a regex folder', { r: folder('Rx', [], '^web') }, ['web1', 'web2', 'db'], ['web2', 'folder-r', 'db', 'web1']], + ]) { + const r = synced(folders, containers, prefs); + const [was, now] = [(await drawnFrom(folders, containers, prefs)).drawn(), (await drawnFrom(folders, containers, r.after)).drawn()]; + check(`${what}: the sync regroups userprefs.cfg, and the page draws the same from it`, r.answers[0] === '{"success":true}' && !same(r.after, prefs) && same(was, now), { answers: r.answers, after: r.after, was, now }); + } + { + // A regex folder saved while empty; web1, installed since, joins it by regex + const r = synced({ f: folder('F', [], '^web') }, ['a', 'web1', 'b'], ['a', 'folder-f', 'b']); + check('a folder with none of its members saved yet gets them after its entry', same(r.after, ['a', 'folder-f', 'web1', 'b']), r); + } + // The real read_membership.php: container => folder name. `json` is docker.json as written, its key order kept + const membershipOf = (folders, containers, prefs, json = JSON.stringify(folders)) => { + const php = phpServer('membership', { containers }); + try { + fs.writeFileSync(path.join(php.config, 'docker.json'), json); + if (prefs.length) fs.writeFileSync(path.join(path.dirname(php.config), 'dockerMan', 'userprefs.cfg'), prefs.map((n, i) => `${i}="${n}"\n`).join('')); + return JSON.parse(php.server('read_membership.php', 'GET', { type: 'docker' })).membership; + } finally { php.cleanup(); } + }; + { + const web = (name) => folder(name, [], '^web'); + for (const [what, folders, containers, prefs, owner, json] of [ + ['the folder userprefs.cfg names first', { a: web('A'), b: web('B') }, ['web1', 'loose'], ['folder-b', 'loose', 'folder-a'], 'b'], + ['of folders it does not name, an index-like id first', { x: web('X'), 7: web('Seven') }, ['web1', 'loose'], ['loose'], '7', + `{"x":${JSON.stringify(web('X'))},"7":${JSON.stringify(web('Seven'))}}`], + ['with nothing saved, the folder first A-Z', { z: web('Zulu'), a: web('Alpha') }, ['web1'], [], 'a'], + ]) { + const page = await drawnFrom(folders, containers, prefs); + const map = membershipOf(folders, containers, prefs, json); + check(`two folders' regexes match a container: ${what} gets it, on the page and in read_membership.php`, + same(page.members(owner), ['web1']) && map?.web1 === folders[owner].name, { members: Object.keys(folders).map((id) => [id, page.members(id)]), map }); + } + const r = synced({ a: web('A'), b: web('B') }, ['web1', 'loose'], ['folder-b', 'loose', 'folder-a', 'web1']); + check('and the sync moves it beside the folder the page draws it in', same(r.after, ['folder-b', 'web1', 'loose', 'folder-a']), r); + } + { + // Generated folders (a container listed in one folder at most) and saved orders, with stale and unsaved entries + let seed = 20261116; + const rnd = (n) => { seed = (Math.imul(seed, 1103515245) + 12345) & 0x7fffffff; return (seed >>> 8) % n; }; + const shuffle = (a) => { for (let i = a.length - 1; i > 0; i--) { const j = rnd(i + 1); [a[i], a[j]] = [a[j], a[i]]; } return a; }; + const off = [], apart = [], unstable = [], refused = []; + let changed = 0, overlaps = 0; + for (let n = 0; n < 120; n++) { + const containers = shuffle(['a', 'b', 'c', 'web1', 'web2', 'x', 'y']).slice(0, 3 + rnd(5)); + const nf = 1 + rnd(3); + const folders = Object.fromEntries(Array.from({ length: nf }, (_, i) => [`f${i}`, folder(`F${i}`, [], rnd(3) === 0 ? '^web' : '')])); + for (const c of containers) { const i = rnd(nf * 2); if (i < nf) folders[`f${i}`].containers.push(c); } + const entries = containers.concat(Object.keys(folders).map((k) => `folder-${k}`)); + if (rnd(4) === 0) entries.push('ghost'); + const prefs = shuffle(entries).filter(() => rnd(5) > 0); + if (!prefs.length) continue; + overlaps += Object.values(folders).filter((f) => f.regex).length > 1 && containers.some((c) => c.startsWith('web')); + const r = synced(folders, containers, prefs); + if (r.answers.some((a) => a !== '{"success":true}')) { refused.push({ folders, prefs, r }); continue; } + changed += !same(r.after, prefs); + if (!same(r.after, r.again)) unstable.push({ folders, containers, prefs, r }); + const page = await drawnFrom(folders, containers, r.after); + const inFolder = new Set(Object.keys(folders).flatMap((id) => page.members(id))); + const shown = (e) => (e.startsWith('folder-') && folders[e.slice(7)]) || (containers.includes(e) && !inFolder.has(e)); + // Unraid puts a name the file lacks first; docker.js puts each folder it lacks on top, the last in docker.json first + const want = Object.keys(folders).map((id) => `folder-${id}`).filter((e) => !r.after.includes(e)).reverse() + .concat(containers.filter((c) => !r.after.includes(c) && !inFolder.has(c)), r.after.filter(shown)); + if (!same(page.rows(), want)) off.push({ folders, containers, after: r.after, rows: page.rows(), want }); + // Members of a folder the file has no entry for stay where they were saved + const unsaved = new Set(Object.keys(folders).filter((id) => !r.after.includes(`folder-${id}`)).flatMap((id) => page.members(id))); + const named = r.after.filter((e) => containers.includes(e) && !unsaved.has(e)); + if (!same(named, page.drawn().filter((e) => named.includes(e)))) apart.push({ folders, containers, after: r.after, drawn: page.drawn() }); + } + check('the sync regroups over a quarter of the generated orders, and every sync answers success', changed > 30 && refused.length === 0, { changed, refused: refused.slice(0, 2) }); + check('a second sync leaves userprefs.cfg as the first wrote it', unstable.length === 0, unstable.slice(0, 2)); + check('after the sync the page draws its rows in the order userprefs.cfg names them', off.length === 0, { count: off.length, first: off.slice(0, 2) }); + check('and userprefs.cfg names its containers in the order the page draws them, folders whose regexes match one container among them', + apart.length === 0 && overlaps > 10, { overlaps, count: apart.length, first: apart.slice(0, 2) }); + } + { + const syncs = (page) => page.posts.filter((r) => r.url.endsWith('/sync_order.php')).map((r) => r.data); + const saved = { folders: { f: folder('F', ['m']) }, containers: ['a', 'm'], prefs: ['folder-f', 'a'] }; + const page = await drawDocker(saved); + await page.draw(); + await page.draw(); + check('a page with folders and a saved order asks for one sync, not one per list rebuild', same(syncs(page), [{ type: 'docker' }]), page.posts); + for (const [what, setup] of [['nothing saved', { ...saved, prefs: [] }], ['no folders', { ...saved, folders: {} }], + ['no folder holds a container', { ...saved, containers: ['a'] }]]) { + const quiet = await drawDocker(setup); + await quiet.draw(); + check(`${what}: no sync is asked for`, syncs(quiet).length === 0, quiet.posts); + } + const refused = await drawDocker(saved); + const banners = []; + refused.p.w.fv3ShowBanner = (text) => { banners.push(text); }; + refused.failing.add('sync_order.php'); + await refused.draw(); + check('a refused sync shows the start-order banner with the reason', same(banners, ['The Docker start order could not be updated: refused by the test']), banners); + } done(); })(); diff --git a/.github/scripts/page_order_test.php b/.github/scripts/page_order_test.php index 58b8ce4b..edab0144 100644 --- a/.github/scripts/page_order_test.php +++ b/.github/scripts/page_order_test.php @@ -75,6 +75,7 @@ class DockerUpdate {} $GLOBALS['fv3tDown'] = $names === null; $setPrefs($cfg); @unlink("$configDir/docker.json"); + @unlink("$configDir/order-docker.json"); @unlink($fv3tAutostart); if ($folders !== null) file_put_contents("$configDir/docker.json", json_encode((object)$folders)); if ($autostart !== null) file_put_contents($fv3tAutostart, is_array($autostart) ? implode("\n", $autostart) . "\n" : $autostart); @@ -90,6 +91,12 @@ class DockerUpdate {} $GLOBALS['fv3tDown'] = false; } }; +// $sync's run, answering with userprefs.cfg as the run left it (null = no file) in place of the autostart file +$syncPrefs = function (?array $folders, array $names, ?string $cfg, ?callable $break = null) use ($sync, $fv3DockerManDir): array { + [$answer] = $sync($folders, $names, $cfg, null, $break); + $file = "$fv3DockerManDir/userprefs.cfg"; + return [$answer, file_exists($file) ? file_get_contents($file) : null]; +}; // updateAutostartConfig() as the Autostart tab calls it, with the folder config as given $autostartSave = function (string $mode, string $foldersJson, array $waits = [], bool $readOnly = false) use ($setPrefs, $configDir, $fv3tAutostart): array { $GLOBALS['fv3tNames'] = ['a', 'b']; @@ -204,11 +211,18 @@ class DockerUpdate {} ['folder-a', 'folder-b', 'folder-m', 'plex', 'folder-z']], ['no userprefs.cfg: a look-alike of a folder member keeps its own A-Z place', $order(['f' => $folder('F', ['10'])], ['10', '1e1', '0first'], []), ['0first', '1e1', '10', 'folder-f']], - ['read_membership.php: an explicit entry beats a label (s1), a label places a loose container (mid), the first folder whose regex matches wins (r1, y1)', - $membership(null), [1, '200', ['alpha' => 'Dup', 'mid' => 'Zulu', 'n1' => 'Numbers', 'o1' => 'Old', 'r1' => 'Rex', 'r2' => 'Rex', 's1' => 'Seven', 'y1' => 'Yankee', 'y2' => 'Yankee', 'z1' => 'Zulu', 'z2' => 'Zulu']]], - ['and its answer does not depend on userprefs.cfg: the saved order, a reversed one, a file cut off mid-save', + ['two folders\' regexes match a container: the folder userprefs.cfg names first takes it, as the page draws it', + $order(['a' => $folder('A', [], '^web'), 'b' => $folder('B', [], '^web')], ['web1', 'loose'], ['folder-b', 'loose', 'folder-a']), + ['web1', 'folder-b', 'loose', 'folder-a']], + ['folders userprefs.cfg does not name take theirs in JS key order, an index-like id first', + $order(['x' => $folder('X', [], '^web'), '7' => $folder('Seven', [], '^web')], ['web1', 'loose'], ['loose']), ['folder-x', 'web1', 'folder-7', 'loose']], + ['no userprefs.cfg: the folder first A-Z takes a container two regexes match', + $order(['z' => $folder('Zulu', [], '^web'), 'a' => $folder('Alpha', [], '^web')], ['web1'], []), ['web1', 'folder-a', 'folder-z']], + ['read_membership.php: an explicit entry beats a label (s1), a label places a loose container (mid); with nothing saved the folder first A-Z whose regex matches wins (Dup: r1, y1)', + $membership(null), [1, '200', ['alpha' => 'Dup', 'mid' => 'Zulu', 'n1' => 'Numbers', 'o1' => 'Old', 'r1' => 'Dup', 'r2' => 'Dup', 's1' => 'Seven', 'y1' => 'Dup', 'y2' => 'Dup', 'z1' => 'Zulu', 'z2' => 'Zulu']]], + ['with a saved order, the folders it names win first, then the rest (Rex, Yankee before Dup); a file cut off mid-save reads as nothing saved, as on the page', [$membership($userprefs($fixture['prefs'])), $membership($userprefs(array_reverse($fixture['containers']))), $membership($cutOff)], - array_fill(0, 3, $membership(null))], + [...array_fill(0, 2, [1, '200', ['alpha' => 'Dup', 'mid' => 'Zulu', 'n1' => 'Numbers', 'o1' => 'Old', 'r1' => 'Rex', 'r2' => 'Rex', 's1' => 'Seven', 'y1' => 'Yankee', 'y2' => 'Yankee', 'z1' => 'Zulu', 'z2' => 'Zulu']]), $membership(null)]], ['autostart lines follow the order and keep their wait value', fv3_reorder_autostart(['a 5', 'b', 'c 10'], ['c', 'folder-f', 'a', 'a']), ['c 10', 'a 5', 'b']], ['a line the order does not name stays after the others, in file order', @@ -248,23 +262,68 @@ class DockerUpdate {} $sync([], ['b', 'a', 'c'], $cutOff, ['c', 'ghost', 'b 5', 'a']), ["Unraid's saved Docker order (userprefs.cfg) could not be read", ['c', 'ghost', 'b 5', 'a']]], ['an empty userprefs.cfg writes A-Z, as no userprefs.cfg does', $sync([], ['b', 'a', 'c'], '', ['c', 'b 5', 'a']), [null, ['a', 'b 5', 'c']]], + ['userprefs.cfg: a folder member it lacks is saved right after its folder, in the folder\'s order', + $syncPrefs(['f' => $folder('F', ['x', 'y'])], ['a', 'b', 'x', 'y'], $userprefs(['a', 'folder-f', 'x', 'b'])), [null, $userprefs(['a', 'folder-f', 'x', 'y', 'b'])]], + ['userprefs.cfg: a member saved away from its folder moves to it', + $syncPrefs(['f' => $folder('F', ['x', 'y'])], ['a', 'b', 'x', 'y'], $userprefs(['y', 'a', 'folder-f', 'x', 'b'])), [null, $userprefs(['a', 'folder-f', 'x', 'y', 'b'])]], + ['userprefs.cfg: a member moved to another folder follows it', + $syncPrefs(['f' => $folder('F', ['x']), 'g' => $folder('G', ['w', 'y'])], ['w', 'x', 'y'], $userprefs(['folder-f', 'x', 'y', 'folder-g', 'w'])), [null, $userprefs(['folder-f', 'x', 'folder-g', 'w', 'y'])]], + ['userprefs.cfg: members saved before their folder, as FV3\'s own writers save them, stay before it', + $syncPrefs(['f' => $folder('F', ['x', 'y'])], ['a', 'x', 'y'], $userprefs(['x', 'folder-f', 'a'])), [null, $userprefs(['x', 'y', 'folder-f', 'a'])]], + ['userprefs.cfg: a regex folder\'s members keep the saved order, on their side of its entry', + $syncPrefs(['r' => $folder('Rx', [], '^web')], ['web1', 'web2', 'db'], $userprefs(['web2', 'folder-r', 'db', 'web1'])), [null, $userprefs(['web2', 'web1', 'folder-r', 'db'])]], + ['userprefs.cfg: a folder with none of its members saved yet, as after an install, gets them after its entry', + $syncPrefs(['f' => $folder('F', ['x'])], ['a', 'x'], $userprefs(['folder-f', 'a'])), [null, $userprefs(['folder-f', 'x', 'a'])]], + ['userprefs.cfg: a folder it has no entry for leaves its members where they are', + $syncPrefs(['f' => $folder('F', ['x', 'y'])], ['a', 'x', 'y'], $userprefs(['x', 'a', 'y'])), [null, $userprefs(['x', 'a', 'y'])]], + ['userprefs.cfg: an entry Docker does not have keeps its place', + $syncPrefs(['f' => $folder('F', ['x'])], ['a', 'x'], $userprefs(['ghost', 'folder-f', 'a', 'x'])), [null, $userprefs(['ghost', 'folder-f', 'x', 'a'])]], + ['userprefs.cfg: none is not created, so Unraid keeps its A-Z order', + $syncPrefs(['f' => $folder('F', ['x'])], ['a', 'x'], null), [null, null]], + ['userprefs.cfg: an empty one stays empty', + $syncPrefs(['f' => $folder('F', ['x'])], ['a', 'x'], ''), [null, '']], + ['userprefs.cfg: one already in place is not written again, its numbering kept', + $syncPrefs(['f' => $folder('F', ['x', 'y'])], ['x', 'y'], "0=\"folder-f\"\n2=\"x\"\n5=\"y\"\n"), [null, "0=\"folder-f\"\n2=\"x\"\n5=\"y\"\n"]], + ['userprefs.cfg: the fixture\'s saved order is already in place', + $syncPrefs($fixture['folders'], $fixture['containers'], $userprefs($fixture['prefs'])), [null, $userprefs($fixture['prefs'])]], + ['userprefs.cfg: custom and off modes regroup it too, and leave the autostart file to their own rule', + array_map(fn($mode) => [...$sync(['f' => $folder('F', ['x'])], ['a', 'x'], $userprefs(['x', 'a', 'folder-f']), ['x', 'a'], + fn() => file_put_contents("$configDir/autostart.json", json_encode(['mode' => $mode, 'sequence' => ['a', 'x']]))), file_get_contents("$fv3DockerManDir/userprefs.cfg")], ['custom', 'off']), + [[null, ['a', 'x'], $userprefs(['a', 'folder-f', 'x'])], [null, ['x', 'a'], $userprefs(['a', 'folder-f', 'x'])]]], + ['userprefs.cfg: a name that cannot be written back (a quote another tool saved) leaves it as it is, and is reported', + $syncPrefs(['f' => $folder('F', ['x'])], ['x'], "0=\"x\"\n1=\"a\\\"b\"\n2=\"folder-f\"\n"), + ["Unraid's saved Docker order (userprefs.cfg) holds a name that cannot be written back", "0=\"x\"\n1=\"a\\\"b\"\n2=\"folder-f\"\n"]], + ['userprefs.cfg: an order saved while the sync worked it out is kept as it is', + (function () use ($setPrefs, $userprefs, $folder, $fv3DockerManDir) { + $read = ['x', 'b', 'folder-f']; + $setPrefs($userprefs(['folder-f', 'x', 'b'])); + return [fv3_sync_user_prefs($read, fv3_compute_folder_membership(['f' => $folder('F', ['x'])], ['b', 'x'], [], $read)), file_get_contents("$fv3DockerManDir/userprefs.cfg")]; + })(), [null, $userprefs(['folder-f', 'x', 'b'])]], + ['userprefs.cfg: FV3\'s order snapshot, which the heal restores from after a reinstall, is saved with it', + [$syncPrefs(['f' => $folder('F', ['x'])], ['a', 'x'], $userprefs(['x', 'a', 'folder-f']))[1], fv3_export_order_snapshot('docker')['entries'] ?? null], + [$userprefs(['a', 'folder-f', 'x']), ['a', 'folder-f', 'x']]], + ['userprefs.cfg: a cut-off one is left as it is, and reported', + $syncPrefs(['f' => $folder('F', ['x'])], ['a', 'x'], $cutOff), ["Unraid's saved Docker order (userprefs.cfg) could not be read", $cutOff]], + ['userprefs.cfg: the start order worked out from it is the same before and after the update (the page: docker_saved_places_test.js)', + $order(['f' => $folder('F', ['x', 'y'])], ['a', 'b', 'x', 'y'], fv3_parse_user_prefs($syncPrefs(['f' => $folder('F', ['x', 'y'])], ['a', 'b', 'x', 'y'], $userprefs(['y', 'a', 'folder-f', 'b']))[1])), + $order(['f' => $folder('F', ['x', 'y'])], ['a', 'b', 'x', 'y'], ['y', 'a', 'folder-f', 'b'])], ['no containers, or Docker not running (Unraid\'s client answers an empty list): nothing is written, nothing is reported', $sync([], [], null, ['b', 'a']), [null, ['b', 'a']]], ['a container list with an unnamed entry: nothing is written, and it is reported', $sync([], ['a', ''], null, ['b', 'a']), ["Docker's container list could not be read", ['b', 'a']]], ['a failed label read: nothing is written, and it is reported', $sync([], ['a', 'b'], null, ['b', 'a'], function () { $GLOBALS['fv3tLabelsDown'] = true; }), ['the container labels could not be read', ['b', 'a']]], - ['custom mode does not read the folder config, so a damaged one does not stop it', + ['custom mode still writes its sequence when a damaged folder config stops the userprefs.cfg update, and says so', $sync([], ['a', 'b'], null, ['b', 'a'], function () use ($configDir) { file_put_contents("$configDir/docker.json", '{'); file_put_contents("$configDir/autostart.json", '{"mode":"custom","sequence":["a","b"]}'); - }), [null, ['a', 'b']]], + }), ['the folder config could not be read', ['a', 'b']]], ['a missing plugin config folder (deleted by hand under an open tab) is "no folders", not a failure: the sync runs and reports nothing', [$syncWithoutConfigDir(['b', 'a']), $syncWithoutConfigDir([]), is_dir($configDir)], [[null, ['a', 'b']], [null, ['b', 'a']], true]], ['a damaged folder config is reported', $sync([], ['a', 'b'], null, ['b', 'a'], fn() => file_put_contents("$configDir/docker.json", '{')), ['the folder config could not be read', ['b', 'a']]], - ['autostart mode off reads nothing and reports nothing', - $sync([], ['a', 'b'], $cutOff, ['b', 'a'], fn() => file_put_contents("$configDir/autostart.json", '{"mode":"off"}')), [null, ['b', 'a']]], + ['autostart mode off leaves the autostart file as it is, and reports a userprefs.cfg it cannot read', + $sync([], ['a', 'b'], $cutOff, ['b', 'a'], fn() => file_put_contents("$configDir/autostart.json", '{"mode":"off"}')), ["Unraid's saved Docker order (userprefs.cfg) could not be read", ['b', 'a']]], ['custom mode writes its saved sequence, the rest after it in file order', $sync([], ['a', 'b', 'c'], null, ['b 5', 'a', 'ghost', 'c'], fn() => file_put_contents("$configDir/autostart.json", '{"mode":"custom","sequence":["c","a"]}')), [null, ['c', 'a', 'b 5']]], ['custom mode: a file already in its sequence is not written again', @@ -319,6 +378,16 @@ class DockerUpdate {} [['success' => true, 'mode' => 'off', 'sequence' => [], 'warning' => 'the wait edits could not be written to the autostart file'], ['success' => true, 'mode' => 'folder', 'sequence' => [], 'warning' => 'the wait edits could not be written to the autostart file; the autostart file could not be written'], ['success' => true, 'mode' => 'off', 'sequence' => []], ['b', 'a 30']]]; + $cases[] = ['userprefs.cfg: a failed write is reported, and the autostart file is still put in order', + (function () use ($sync, $folder, $userprefs, $fv3DockerManDir) { + try { return $sync(['f' => $folder('F', ['x'])], ['a', 'b', 'x'], $userprefs(['b', 'folder-f', 'a', 'x']), ['a', 'x', 'b'], fn() => chmod($fv3DockerManDir, 0555)); } + finally { chmod($fv3DockerManDir, 0755); } + })(), ["Unraid's saved Docker order (userprefs.cfg) could not be updated", ['b', 'x', 'a']]]; + $cases[] = ['userprefs.cfg and the autostart file both not written: both are reported', + (function () use ($sync, $folder, $userprefs, $fv3DockerManDir, $fv3tAutostart) { + try { return $sync(['f' => $folder('F', ['x'])], ['a', 'b', 'x'], $userprefs(['b', 'folder-f', 'a', 'x']), ['a', 'x', 'b'], function () use ($fv3DockerManDir, $fv3tAutostart) { chmod($fv3DockerManDir, 0555); chmod($fv3tAutostart, 0444); }); } + finally { chmod($fv3DockerManDir, 0755); } + })(), ["Unraid's saved Docker order (userprefs.cfg) could not be updated; the autostart file could not be written", ['a', 'x', 'b']]]; $cases[] = ['custom mode reports it too', $sync([], ['a', 'b'], null, ['b', 'a'], function () use ($configDir, $fv3tAutostart) { file_put_contents("$configDir/autostart.json", '{"mode":"custom","sequence":["a","b"]}'); chmod($fv3tAutostart, 0444); }), ['the autostart file could not be written', ['b', 'a']]]; } @@ -398,10 +467,10 @@ class DockerUpdate {} }; $cases[] = ['folder import, no saved order: the new folders first in the file\'s order, each after its members, then the rest A-Z', $importOrder(null, ['n2', 'n1'], ['a', 'b', 'c']), ['200', true, null, null, $userprefs(['folder-n2', 'b', 'folder-n1', 'c', 'a', 'folder-old'])]]; -$cases[] = ['folder import, a saved order: the new folders go on top in the file\'s order, the saved entries after them as they were', - $importOrder($keep, ['n2', 'n1'], ['a', 'b', 'c']), ['200', true, null, null, $userprefs(['folder-n2', 'folder-n1', 'alpha', 'zed'])]]; -$cases[] = ['folder import, a saved order that already places one of them: that one keeps its place, an id with no folder is not written', - $importOrder($userprefs(['alpha', 'folder-n1', 'zed']), ['n2', 'n1', 'ghost'], ['a', 'b', 'c']), ['200', true, null, null, $userprefs(['folder-n2', 'alpha', 'folder-n1', 'zed'])]]; +$cases[] = ['folder import, a saved order: the new folders go on top in the file\'s order with their members, the saved entries after them as they were', + $importOrder($keep, ['n2', 'n1'], ['a', 'b', 'c']), ['200', true, null, null, $userprefs(['folder-n2', 'folder-n1', 'b', 'alpha', 'zed'])]]; +$cases[] = ['folder import, a saved order that already places one of them: that one keeps its place with its member, an id with no folder is not written', + $importOrder($userprefs(['alpha', 'folder-n1', 'zed']), ['n2', 'n1', 'ghost'], ['a', 'b', 'c']), ['200', true, null, null, $userprefs(['folder-n2', 'alpha', 'folder-n1', 'b', 'zed'])]]; $cases[] = ['folder import, a saved order holding a list line: said, and left as it was', $importOrder("0=\"a\"\n1[]=\"b\"\n", ['n1'], ['a', 'b']), ['200', true, "Unraid's saved Docker order (userprefs.cfg) could not be read", "Unraid's saved Docker order (userprefs.cfg) could not be read", "0=\"a\"\n1[]=\"b\"\n"]]; $cases[] = ['folder import, a saved order and a folder config that will not parse: said, and the order left as it was', diff --git a/src/folder.view3/usr/local/emhttp/plugins/folder.view3/FolderView3.page b/src/folder.view3/usr/local/emhttp/plugins/folder.view3/FolderView3.page index 20a6ec3f..fa3ecf0b 100644 --- a/src/folder.view3/usr/local/emhttp/plugins/folder.view3/FolderView3.page +++ b/src/folder.view3/usr/local/emhttp/plugins/folder.view3/FolderView3.page @@ -599,7 +599,7 @@ require_once('/usr/local/emhttp/plugins/folder.view3/langs/script.php'); @@ -608,7 +608,7 @@ require_once('/usr/local/emhttp/plugins/folder.view3/langs/script.php');
-

Folder-based keeps today's behaviour: the container start order follows your folder layout on the Docker page. Custom sequence uses the order below instead — it cuts across folders and overrides the Docker page order, and survives reboots. Off hands the start order fully back to Unraid; FolderView3 stops writing it entirely.

+

Folder-based keeps today's behaviour: the container start order follows your folder layout on the Docker page. Custom sequence uses the order below instead — it cuts across folders and overrides the Docker page order, and survives reboots. Off hands the start order back to Unraid: containers start in the autostart file's order, which Unraid re-sorts to the Docker page's order when you reorder containers or switch one's autostart there; FolderView3 stops reordering that file.

diff --git a/src/folder.view3/usr/local/emhttp/plugins/folder.view3/langs/de.json b/src/folder.view3/usr/local/emhttp/plugins/folder.view3/langs/de.json index dbad2037..ef254cc8 100644 --- a/src/folder.view3/usr/local/emhttp/plugins/folder.view3/langs/de.json +++ b/src/folder.view3/usr/local/emhttp/plugins/folder.view3/langs/de.json @@ -331,7 +331,7 @@ "autostart-mode": "Startreihenfolge-Modus:", "autostart-mode-folder": "Ordnerbasiert (Standard)", "autostart-mode-custom": "Eigene Reihenfolge", - "autostart-mode-off": "Aus (FolderView3 schreibt die Startreihenfolge nie)", + "autostart-mode-off": "Aus (FolderView3 ordnet die Autostart-Datei nie um)", "autostart-sequence": "Startreihenfolge", "autostart-not-started": "Kein Autostart", "autostart-col-container": "Container", @@ -355,7 +355,7 @@ "dashboard-animation-tooltip": "Aktiviert eine sanfte Gleitanimation beim Auf- und Zuklappen von Ordnern im Dashboard.", "default-preview-tooltip": "Standard-Vorschaustil für neue Ordner. Einzelne Ordner können dies in ihren Einstellungen überschreiben.", "default-update-column-tooltip": "Blendet die Aktualisierungsspalte \"Version\" für alle Ordnerzeilen aus und schafft so horizontalen Platz.", - "autostart-mode-tooltip": "Ordnerbasiert behält das bisherige Verhalten bei: Die Startreihenfolge der Container folgt deiner Ordneranordnung auf der Docker-Seite. Eigene Reihenfolge verwendet stattdessen die Reihenfolge unten — sie gilt ordnerübergreifend, überschreibt die Reihenfolge der Docker-Seite und bleibt nach einem Neustart erhalten. Aus überlässt die Startreihenfolge vollständig Unraid; FolderView3 schreibt sie dann überhaupt nicht mehr.", + "autostart-mode-tooltip": "Ordnerbasiert behält das bisherige Verhalten bei: Die Startreihenfolge der Container folgt deiner Ordneranordnung auf der Docker-Seite. Eigene Reihenfolge verwendet stattdessen die Reihenfolge unten — sie gilt ordnerübergreifend, überschreibt die Reihenfolge der Docker-Seite und bleibt nach einem Neustart erhalten. Aus überlässt die Startreihenfolge Unraid: Container starten in der Reihenfolge der Autostart-Datei, die Unraid nach der Reihenfolge der Docker-Seite neu sortiert, wenn du dort Container umordnest oder ihren Autostart umschaltest; FolderView3 ordnet diese Datei dann nicht mehr um.", "docker-only": "Nur Docker", "preview-text-width-placeholder": "z. B. 80px, 6rem (leer = keine Begrenzung)", "autostart-sequence-hint": "Ziehe Zeilen oder gib eine Positionsnummer ein, um die globale Startreihenfolge festzulegen (oben startet zuerst). Warten ist die Pause in Sekunden, nachdem dieser Container gestartet ist. Nur bearbeitbar, solange der Startreihenfolge-Modus auf Eigene Reihenfolge steht; Änderungen gelten nach Anwenden.", diff --git a/src/folder.view3/usr/local/emhttp/plugins/folder.view3/langs/en.json b/src/folder.view3/usr/local/emhttp/plugins/folder.view3/langs/en.json index 9556ea3a..52625d16 100644 --- a/src/folder.view3/usr/local/emhttp/plugins/folder.view3/langs/en.json +++ b/src/folder.view3/usr/local/emhttp/plugins/folder.view3/langs/en.json @@ -331,7 +331,7 @@ "autostart-mode": "Start order mode:", "autostart-mode-folder": "Folder-based (default)", "autostart-mode-custom": "Custom sequence", - "autostart-mode-off": "Off (FolderView3 never writes the start order)", + "autostart-mode-off": "Off (FolderView3 never reorders the autostart file)", "autostart-sequence": "Startup sequence", "autostart-not-started": "Not autostarted", "autostart-col-container": "Container", @@ -355,7 +355,7 @@ "dashboard-animation-tooltip": "Enables a smooth slide animation when expanding or collapsing folders on the Dashboard.", "default-preview-tooltip": "Default preview style for new folders. Individual folders can override this in their settings.", "default-update-column-tooltip": "Hides the \"Version\" update column for all folder rows, freeing up horizontal space.", - "autostart-mode-tooltip": "Folder-based keeps today's behaviour: the container start order follows your folder layout on the Docker page. Custom sequence uses the order below instead — it cuts across folders and overrides the Docker page order, and survives reboots. Off hands the start order fully back to Unraid; FolderView3 stops writing it entirely.", + "autostart-mode-tooltip": "Folder-based keeps today's behaviour: the container start order follows your folder layout on the Docker page. Custom sequence uses the order below instead — it cuts across folders and overrides the Docker page order, and survives reboots. Off hands the start order back to Unraid: containers start in the autostart file's order, which Unraid re-sorts to the Docker page's order when you reorder containers or switch one's autostart there; FolderView3 stops reordering that file.", "docker-only": "Docker only", "preview-text-width-placeholder": "e.g. 80px, 6rem (blank = no limit)", "autostart-sequence-hint": "Drag rows or type a position number to set the global start order (top starts first). Wait is the pause in seconds after that container starts. Editable only while Start order mode is set to Custom sequence; changes apply on Apply.", diff --git a/src/folder.view3/usr/local/emhttp/plugins/folder.view3/langs/es.json b/src/folder.view3/usr/local/emhttp/plugins/folder.view3/langs/es.json index 6953d964..f45a36b3 100644 --- a/src/folder.view3/usr/local/emhttp/plugins/folder.view3/langs/es.json +++ b/src/folder.view3/usr/local/emhttp/plugins/folder.view3/langs/es.json @@ -331,7 +331,7 @@ "autostart-mode": "Modo de orden de arranque:", "autostart-mode-folder": "Según carpetas (predeterminado)", "autostart-mode-custom": "Secuencia personalizada", - "autostart-mode-off": "Desactivado (FolderView3 nunca escribe el orden de arranque)", + "autostart-mode-off": "Desactivado (FolderView3 nunca reordena el archivo de autoarranque)", "autostart-sequence": "Secuencia de arranque", "autostart-not-started": "Sin autoarranque", "autostart-col-container": "Contenedor", @@ -355,7 +355,7 @@ "dashboard-animation-tooltip": "Activa una animación de deslizamiento suave al expandir o contraer carpetas en el panel de control.", "default-preview-tooltip": "Estilo de vista previa predeterminado para las carpetas nuevas. Cada carpeta puede cambiarlo en su configuración.", "default-update-column-tooltip": "Oculta la columna de actualización \"Versión\" en todas las filas de carpeta y libera espacio horizontal.", - "autostart-mode-tooltip": "Según carpetas mantiene el comportamiento actual: el orden de arranque de los contenedores sigue la disposición de tus carpetas en la página de Docker. Secuencia personalizada usa en su lugar el orden de abajo: abarca todas las carpetas, prevalece sobre el orden de la página de Docker y se conserva tras reiniciar. Desactivado devuelve el orden de arranque por completo a Unraid; FolderView3 deja de escribirlo.", + "autostart-mode-tooltip": "Según carpetas mantiene el comportamiento actual: el orden de arranque de los contenedores sigue la disposición de tus carpetas en la página de Docker. Secuencia personalizada usa en su lugar el orden de abajo: abarca todas las carpetas, prevalece sobre el orden de la página de Docker y se conserva tras reiniciar. Desactivado devuelve el orden de arranque a Unraid: los contenedores arrancan en el orden del archivo de autoarranque, que Unraid reordena según la página de Docker cuando reordenas allí los contenedores o cambias su autoarranque; FolderView3 deja de reordenar ese archivo.", "docker-only": "Solo Docker", "preview-text-width-placeholder": "p. ej. 80px, 6rem (vacío = sin límite)", "autostart-sequence-hint": "Arrastra las filas o escribe un número de posición para fijar el orden de arranque global (la de arriba arranca primero). Espera es la pausa en segundos tras arrancar ese contenedor. Solo se puede editar mientras el modo de orden de arranque sea Secuencia personalizada; los cambios se aplican con Aplicar.", diff --git a/src/folder.view3/usr/local/emhttp/plugins/folder.view3/langs/fr.json b/src/folder.view3/usr/local/emhttp/plugins/folder.view3/langs/fr.json index 1c2a74cd..1a2ca10e 100644 --- a/src/folder.view3/usr/local/emhttp/plugins/folder.view3/langs/fr.json +++ b/src/folder.view3/usr/local/emhttp/plugins/folder.view3/langs/fr.json @@ -331,7 +331,7 @@ "autostart-mode": "Mode d'ordre de démarrage :", "autostart-mode-folder": "Basé sur les dossiers (par défaut)", "autostart-mode-custom": "Séquence personnalisée", - "autostart-mode-off": "Désactivé (FolderView3 n'écrit jamais l'ordre de démarrage)", + "autostart-mode-off": "Désactivé (FolderView3 ne réordonne jamais le fichier de démarrage automatique)", "autostart-sequence": "Séquence de démarrage", "autostart-not-started": "Sans démarrage auto", "autostart-col-container": "Conteneur", @@ -355,7 +355,7 @@ "dashboard-animation-tooltip": "Active une animation de glissement fluide lors du déploiement ou de la réduction des dossiers sur le tableau de bord.", "default-preview-tooltip": "Style d'aperçu par défaut des nouveaux dossiers. Chaque dossier peut le remplacer dans ses paramètres.", "default-update-column-tooltip": "Masque la colonne de mise à jour \"Version\" pour toutes les lignes de dossier, ce qui libère de l'espace horizontal.", - "autostart-mode-tooltip": "Basé sur les dossiers conserve le comportement actuel : l'ordre de démarrage des conteneurs suit la disposition de vos dossiers sur la page Docker. Séquence personnalisée utilise plutôt l'ordre ci-dessous — il s'applique à travers les dossiers, remplace l'ordre de la page Docker et survit aux redémarrages. Désactivé rend entièrement l'ordre de démarrage à Unraid ; FolderView3 cesse complètement de l'écrire.", + "autostart-mode-tooltip": "Basé sur les dossiers conserve le comportement actuel : l'ordre de démarrage des conteneurs suit la disposition de vos dossiers sur la page Docker. Séquence personnalisée utilise plutôt l'ordre ci-dessous — il s'applique à travers les dossiers, remplace l'ordre de la page Docker et survit aux redémarrages. Désactivé rend l'ordre de démarrage à Unraid : les conteneurs démarrent dans l'ordre du fichier de démarrage automatique, qu'Unraid retrie selon l'ordre de la page Docker quand vous y réordonnez des conteneurs ou changez leur démarrage automatique ; FolderView3 cesse de réordonner ce fichier.", "docker-only": "Docker seulement", "preview-text-width-placeholder": "ex. 80px, 6rem (vide = aucune limite)", "autostart-sequence-hint": "Faites glisser les lignes ou saisissez un numéro de position pour définir l'ordre de démarrage global (le haut démarre en premier). Attente est la pause en secondes après le démarrage de ce conteneur. Modifiable uniquement lorsque le mode d'ordre de démarrage est Séquence personnalisée ; les changements s'appliquent avec Appliquer.", diff --git a/src/folder.view3/usr/local/emhttp/plugins/folder.view3/langs/it.json b/src/folder.view3/usr/local/emhttp/plugins/folder.view3/langs/it.json index 6c621946..d99cd3e6 100644 --- a/src/folder.view3/usr/local/emhttp/plugins/folder.view3/langs/it.json +++ b/src/folder.view3/usr/local/emhttp/plugins/folder.view3/langs/it.json @@ -331,7 +331,7 @@ "autostart-mode": "Modalità ordine di avvio:", "autostart-mode-folder": "In base alle cartelle (predefinito)", "autostart-mode-custom": "Sequenza personalizzata", - "autostart-mode-off": "Disattivato (FolderView3 non scrive mai l'ordine di avvio)", + "autostart-mode-off": "Disattivato (FolderView3 non riordina mai il file di avvio automatico)", "autostart-sequence": "Sequenza di avvio", "autostart-not-started": "Senza avvio automatico", "autostart-col-container": "Container", @@ -355,7 +355,7 @@ "dashboard-animation-tooltip": "Attiva un'animazione di scorrimento fluida quando si espandono o comprimono le cartelle nella dashboard.", "default-preview-tooltip": "Stile di anteprima predefinito per le nuove cartelle. Ogni cartella può sovrascriverlo nelle proprie impostazioni.", "default-update-column-tooltip": "Nasconde la colonna di aggiornamento \"Versione\" per tutte le righe delle cartelle, liberando spazio orizzontale.", - "autostart-mode-tooltip": "In base alle cartelle mantiene il comportamento attuale: l'ordine di avvio dei container segue la disposizione delle cartelle nella pagina Docker. Sequenza personalizzata usa invece l'ordine qui sotto — vale per tutte le cartelle, sovrascrive l'ordine della pagina Docker e resta valido dopo un riavvio. Disattivato restituisce completamente l'ordine di avvio a Unraid; FolderView3 smette del tutto di scriverlo.", + "autostart-mode-tooltip": "In base alle cartelle mantiene il comportamento attuale: l'ordine di avvio dei container segue la disposizione delle cartelle nella pagina Docker. Sequenza personalizzata usa invece l'ordine qui sotto — vale per tutte le cartelle, sovrascrive l'ordine della pagina Docker e resta valido dopo un riavvio. Disattivato restituisce l'ordine di avvio a Unraid: i container si avviano nell'ordine del file di avvio automatico, che Unraid riordina secondo la pagina Docker quando vi riordini i container o cambi il loro avvio automatico; FolderView3 smette di riordinare quel file.", "docker-only": "Solo Docker", "preview-text-width-placeholder": "es. 80px, 6rem (vuoto = nessun limite)", "autostart-sequence-hint": "Trascina le righe o digita un numero di posizione per impostare l'ordine di avvio globale (in alto parte per primo). Attesa è la pausa in secondi dopo l'avvio di quel container. Modificabile solo quando la modalità ordine di avvio è Sequenza personalizzata; le modifiche si applicano con Applica.", diff --git a/src/folder.view3/usr/local/emhttp/plugins/folder.view3/langs/pl.json b/src/folder.view3/usr/local/emhttp/plugins/folder.view3/langs/pl.json index c0dc44f9..dd932298 100644 --- a/src/folder.view3/usr/local/emhttp/plugins/folder.view3/langs/pl.json +++ b/src/folder.view3/usr/local/emhttp/plugins/folder.view3/langs/pl.json @@ -331,7 +331,7 @@ "autostart-mode": "Tryb kolejności startu:", "autostart-mode-folder": "Wg folderów (domyślnie)", "autostart-mode-custom": "Własna kolejność", - "autostart-mode-off": "Wyłączone (FolderView3 nigdy nie zapisuje kolejności startu)", + "autostart-mode-off": "Wyłączone (FolderView3 nigdy nie zmienia kolejności w pliku autostartu)", "autostart-sequence": "Kolejność startu", "autostart-not-started": "Bez autostartu", "autostart-col-container": "Kontener", @@ -355,7 +355,7 @@ "dashboard-animation-tooltip": "Włącza płynną animację przesuwania przy rozwijaniu i zwijaniu folderów na Dashboardzie.", "default-preview-tooltip": "Domyślny styl podglądu dla nowych folderów. Poszczególne foldery mogą to zmienić w swoich ustawieniach.", "default-update-column-tooltip": "Ukrywa kolumnę aktualizacji \"Wersja\" we wszystkich wierszach folderów, zwalniając miejsce w poziomie.", - "autostart-mode-tooltip": "Wg folderów zachowuje dotychczasowe działanie: kolejność uruchamiania kontenerów wynika z układu folderów na stronie Docker. Własna kolejność używa zamiast tego kolejności poniżej — obejmuje wszystkie foldery, zastępuje kolejność ze strony Docker i przetrwa ponowne uruchomienie. Wyłączone oddaje kolejność uruchamiania w całości Unraid; FolderView3 całkowicie przestaje ją zapisywać.", + "autostart-mode-tooltip": "Wg folderów zachowuje dotychczasowe działanie: kolejność uruchamiania kontenerów wynika z układu folderów na stronie Docker. Własna kolejność używa zamiast tego kolejności poniżej — obejmuje wszystkie foldery, zastępuje kolejność ze strony Docker i przetrwa ponowne uruchomienie. Wyłączone oddaje kolejność uruchamiania Unraid: kontenery startują w kolejności pliku autostartu, który Unraid sortuje według strony Docker, gdy zmienisz tam kolejność kontenerów lub przełączysz ich autostart; FolderView3 przestaje zmieniać kolejność w tym pliku.", "docker-only": "Tylko Docker", "preview-text-width-placeholder": "np. 80px, 6rem (puste = bez limitu)", "autostart-sequence-hint": "Przeciągnij wiersze lub wpisz numer pozycji, aby ustawić globalną kolejność uruchamiania (górny startuje pierwszy). Oczekiwanie to przerwa w sekundach po uruchomieniu danego kontenera. Edycja jest możliwa tylko, gdy tryb kolejności startu to Własna kolejność; zmiany obowiązują po kliknięciu Zastosuj.", diff --git a/src/folder.view3/usr/local/emhttp/plugins/folder.view3/langs/zh.json b/src/folder.view3/usr/local/emhttp/plugins/folder.view3/langs/zh.json index 6d40bb79..744e7467 100644 --- a/src/folder.view3/usr/local/emhttp/plugins/folder.view3/langs/zh.json +++ b/src/folder.view3/usr/local/emhttp/plugins/folder.view3/langs/zh.json @@ -331,7 +331,7 @@ "autostart-mode": "启动顺序模式:", "autostart-mode-folder": "按文件夹(默认)", "autostart-mode-custom": "自定义顺序", - "autostart-mode-off": "关闭(FolderView3 不再写入启动顺序)", + "autostart-mode-off": "关闭(FolderView3 从不重新排列自动启动文件)", "autostart-sequence": "启动顺序", "autostart-not-started": "未自动启动", "autostart-col-container": "容器", @@ -355,7 +355,7 @@ "dashboard-animation-tooltip": "在仪表板上展开或折叠文件夹时启用平滑的滑动动画。", "default-preview-tooltip": "新文件夹的默认预览样式。各个文件夹可以在其设置中覆盖此项。", "default-update-column-tooltip": "隐藏所有文件夹行的“版本”更新栏,腾出水平空间。", - "autostart-mode-tooltip": "按文件夹保持现有行为:容器的启动顺序跟随 Docker 页面上的文件夹布局。自定义顺序改用下方的顺序——它跨越文件夹,覆盖 Docker 页面的顺序,并在重启后保留。关闭则将启动顺序完全交还给 Unraid;FolderView3 将完全停止写入它。", + "autostart-mode-tooltip": "按文件夹保持现有行为:容器的启动顺序跟随 Docker 页面上的文件夹布局。自定义顺序改用下方的顺序——它跨越文件夹,覆盖 Docker 页面的顺序,并在重启后保留。关闭则将启动顺序交还给 Unraid:容器按自动启动文件的顺序启动;当你在 Docker 页面调整容器顺序或切换其自动启动时,Unraid 会按该页面的顺序重新排列此文件;FolderView3 将停止重新排列该文件。", "docker-only": "仅 Docker", "preview-text-width-placeholder": "例如 80px、6rem(留空 = 不限制)", "autostart-sequence-hint": "拖动行或输入位置编号来设置全局启动顺序(最上面的最先启动)。等待是该容器启动后暂停的秒数。仅当启动顺序模式设为自定义顺序时才可编辑;点击应用后生效。", diff --git a/src/folder.view3/usr/local/emhttp/plugins/folder.view3/scripts/docker.js b/src/folder.view3/usr/local/emhttp/plugins/folder.view3/scripts/docker.js index c48fb954..7ad2597c 100644 --- a/src/folder.view3/usr/local/emhttp/plugins/folder.view3/scripts/docker.js +++ b/src/folder.view3/usr/local/emhttp/plugins/folder.view3/scripts/docker.js @@ -13,6 +13,7 @@ let folderobserverConfig = { let folderReq = []; const fv3Folders = fv3FolderData(); let fv3RemeasureWidths = false; +let fv3OrderSyncAsked = false; // Folder rendering — orchestrate (createFolders) and per-folder build (createFolder) const createFolders = async () => { @@ -219,6 +220,8 @@ const createFolders = async () => { globalFolders = foldersDone; fv3Debug('createFolders', 'Assigned foldersDone to globalFolders:', {...globalFolders}); + fv3SyncOrderOnce(unraidOrder, globalFolders); + requestAnimationFrame(() => fv3SyncPreviewHeights('docker_listview_mode')); fv3SyncOrganizer(globalFolders); @@ -1336,12 +1339,25 @@ $(document).ajaxComplete((event, jqXHR, settings) => { && data.indexOf('names=') !== -1; if (isAutostartToggle || isOrderSave) { fv3Debug('autostartSync', 'Rebuilding autostart after Unraid event', {url, sample: data.slice(0, 80)}); - // a refused sync leaves the start order stale: fv3ShowBanner shows the same message once until it is closed - $.post('/plugins/folder.view3/server/sync_order.php', {type: 'docker'}) - .fail((err) => fv3ShowBanner(fv3I18nOr('autostart-sync-failed', 'The Docker start order could not be updated: $1', fv3FailReason(err)))); + fv3SyncDockerOrder(); } }); +// Runs syncContainerOrder() (sync_order.php). A refused sync leaves the start order stale: fv3ShowBanner shows the same message +// once until it is closed +function fv3SyncDockerOrder() { + return $.post('/plugins/folder.view3/server/sync_order.php', {type: 'docker'}) + .fail((err) => fv3ShowBanner(fv3I18nOr('autostart-sync-failed', 'The Docker start order could not be updated: $1', fv3FailReason(err)))); +} + +// A container that joined a folder by regex or label stays missing from userprefs.cfg until a sync: one per page load, when a +// folder holds a container. With nothing saved there is nothing to regroup: the sync never creates userprefs.cfg +function fv3SyncOrderOnce(saved, folders) { + if (fv3OrderSyncAsked || !saved.length || !Object.values(folders).some((f) => Object.keys(f.containers ?? {}).length)) return; + fv3OrderSyncAsked = true; + fv3SyncDockerOrder(); +} + // checkAll shows "checking..." in every version cell until its loadlist's reply, and a measure before then caps the // labels at that text — so the rebuild from that reply drops the cache (not here, while the cells still read it). $(document).ajaxComplete((event, jqXHR, settings) => { diff --git a/src/folder.view3/usr/local/emhttp/plugins/folder.view3/server/lib.php b/src/folder.view3/usr/local/emhttp/plugins/folder.view3/server/lib.php index a34941c2..7cb65a14 100644 --- a/src/folder.view3/usr/local/emhttp/plugins/folder.view3/server/lib.php +++ b/src/folder.view3/usr/local/emhttp/plugins/folder.view3/server/lib.php @@ -715,9 +715,26 @@ function fv3_live_order(array $names, array $prefs): array { return array_merge($saved, array_values(array_filter($names, function($n) use ($saved) { return !in_array($n, $saved, true); }))); } + // The order docker.js createFolders() draws folders in: the folders userprefs.cfg names, in its order, then the rest in JS key + // order; with nothing saved, A-Z by name + function fv3_folder_walk_order(array $folders, array $prefs): array { + $ids = fv3_js_key_order(array_keys($folders)); + if (!$prefs) { + $name = fn($id) => $folders[$id]['name'] !== '' ? $folders[$id]['name'] : "folder-$id"; + usort($ids, fn($a, $b) => fv3_name_cmp($name($a), $name($b))); + return $ids; + } + $saved = []; + foreach ($prefs as $entry) { + if (str_starts_with($entry, 'folder-') && array_key_exists(substr($entry, 7), $folders)) $saved[] = substr($entry, 7); + } + return array_values(array_unique(array_merge($saved, $ids))); + } + // Effective membership — explicit > label > regex (issues #46/#55). Single source of // truth shared by syncContainerOrder and read_membership.php (issue #61). - // $prefs orders each folder's regex and label members as the Docker page lists them (fv3_live_order) + // $prefs orders each folder's regex and label members as the Docker page lists them (fv3_live_order), and the folders as the + // page draws them, so a container two folders' regexes match goes to the one the page shows it in function fv3_compute_folder_membership(array $folders, array $allContainerNames, array $ctLabels, array $prefs = []): array { $live = fv3_live_order($allContainerNames, $prefs); // One malformed entry is dropped or filled in, not allowed to abort every folder's sync @@ -737,7 +754,8 @@ function fv3_compute_folder_membership(array $folders, array $allContainerNames, foreach ($ctLabels as $ctName => $ctLabel) { if (isset($folderNameSet[$ctLabel])) { $explicitAssigned[] = (string)$ctName; } } - foreach ($folders as $folderId => $folder) { + foreach (fv3_folder_walk_order($folders, $prefs) as $folderId) { + $folder = $folders[$folderId]; $members = $folder['containers'] ?? []; // is_string + trim, not empty(): empty("0") is true in PHP, so a regex of "0" was // silently dropped while docker.js applied it. The type check mirrors docker.js and @@ -856,6 +874,53 @@ function fv3_page_order(array $membership, array $allContainerNames, array $pref return array_merge($new, $loose, $placed); } + // $prefs with each folder's members together in its order, on the side of its entry a neighbour shows (a drag: after, FV3's writers: + // before; after by default). A folder with no entry, and every other entry, stay as they are + function fv3_prefs_with_folder_members(array $prefs, array $membership): array { + $blocks = []; + foreach ($membership['containers'] as $placeholder => $members) { + $at = array_search($placeholder, $prefs, true); + if ($at === false || !$members) continue; + $after = isset($prefs[$at + 1]) && in_array($prefs[$at + 1], $members, true); + $before = !$after && $at > 0 && in_array($prefs[$at - 1], $members, true); + $blocks[$placeholder] = ['members' => $members, 'before' => $before]; + } + if (!$blocks) return $prefs; + $moved = array_merge(...array_column($blocks, 'members')); + $out = []; + foreach ($prefs as $entry) { + if (in_array($entry, $moved, true)) continue; + if (!isset($blocks[$entry])) { $out[] = $entry; continue; } + ['members' => $members, 'before' => $before] = $blocks[$entry]; + unset($blocks[$entry]); // a repeated entry for the same folder keeps its place, its members come once + array_push($out, ...($before ? [...$members, $entry] : [$entry, ...$members])); + } + return $out; + } + + // Keeps userprefs.cfg's containers with their folders, so what reads it (Unraid's Start all and autostart sort, other plugins) + // follows the page. Only a saved order is changed: creating one switches Unraid off its A-Z order (#112). Returns why it failed + function fv3_sync_user_prefs(array $prefs, array $membership): ?string { + global $fv3DockerManDir; + if (!$prefs) return null; + $updated = fv3_prefs_with_folder_members($prefs, $membership); + if ($updated === $prefs) return null; + $updated = fv3_sanitize_order_entries($updated); + if ($updated === null) return "Unraid's saved Docker order (userprefs.cfg) holds a name that cannot be written back"; + // Stock UserPrefs writes take no lock: an order saved since the read above is kept as it is + $now = fv3_docker_prefs(); + if ($now === null) return "Unraid's saved Docker order (userprefs.cfg) could not be read"; + if ($now !== $prefs) { fv3_debug_log("fv3_sync_user_prefs: userprefs.cfg changed meanwhile, left as it is"); return null; } + if (!fv3_write_user_prefs("$fv3DockerManDir/userprefs.cfg", $updated)) { + fv3_debug_log("fv3_sync_user_prefs: userprefs.cfg could not be written"); + return "Unraid's saved Docker order (userprefs.cfg) could not be updated"; + } + // FV3's own copy, which the heal restores from after a reinstall + if (!saveOrderSnapshot('docker', $updated)) fv3_error_log('fv3_sync_user_prefs', 'the order snapshot could not be written'); + fv3_debug_log("fv3_sync_user_prefs: wrote userprefs.cfg with " . count($updated) . " entries"); + return null; + } + // Autostart lines ("name" or "name delay") in $order's sequence, each once; lines $order does not name follow, in file order function fv3_reorder_autostart(array $lines, array $order): array { $byName = []; @@ -867,68 +932,65 @@ function fv3_reorder_autostart(array $lines, array $order): array { return array_merge($ordered, array_values($byName)); } - // Returns why the autostart file could not be put in order (a file or a Docker read it needs failed), else null. - // Folder mode only logs an empty container list: a server with no containers, or with Docker off, has nothing to report + // Returns why userprefs.cfg or the autostart file could not be put in order (a file or a Docker read it needs failed), else null. + // An empty container list is only logged: a server with no containers, or with Docker off, has nothing to report function syncContainerOrder(string $type): ?string { - // Rewrites the autostart file to match what FV3 renders on screen — top-to-bottom, - // folder members left-to-right in their editor-chosen order. Render order comes from - // userprefs.cfg when it exists (saved by a drag-reorder or an import), A-Z otherwise. - global $configDir; fv3_debug_log("syncContainerOrder called for type: $type"); - $stop = function (string $why): string { fv3_debug_log("syncContainerOrder: $why, aborting before write"); return $why; }; - if ($type !== 'docker') { return null; } $autostartMode = readAutostartConfig()['mode']; - // 'off' = FV3 never writes the autostart file — pure stock Unraid behaviour - if ($autostartMode === 'off') { fv3_debug_log("syncContainerOrder: autostart mode off, skipping"); return null; } - $dockerClient = new DockerClient(); $ctNames = fv3_read_container_names($dockerClient); - $allContainerNames = $ctNames['names']; - // Prune below only on a complete, fully-named container list — a degraded Docker read must not wipe autostart entries (#214) - $ctListComplete = $ctNames['complete']; - - // 'custom' = the Autostart tab's saved sequence overrides folder-derived order entirely - if ($autostartMode === 'custom') { - return fv3_apply_custom_autostart($allContainerNames, $ctListComplete); - } - + // 'custom' = the Autostart tab's saved sequence orders the autostart file; 'off' = FV3 never reorders it + $failed = array_filter([ + $autostartMode === 'custom' ? fv3_apply_custom_autostart($ctNames['names'], $ctNames['complete']) : null, + ...fv3_sync_page_order($dockerClient, $ctNames, $autostartMode === 'folder'), + ]); + return $failed ? implode('; ', $failed) : null; + } - // Folder-derived order needs the WHOLE list: containers missing from a partial read are - // skipped by the order walk and land appended at the end, silently reordering the file. - // Custom mode above is exempt — its order comes from the saved sequence, not this list. - if (!$ctListComplete) { - if ($ctNames['empty']) { fv3_debug_log("syncContainerOrder: no containers, nothing to sync"); return null; } + // Puts a saved userprefs.cfg's containers with their folders and, with $autostart, the autostart file in the order FV3 renders: + // top to bottom, folder members in their editor order. Returns why each part could not be done, [] when all went through + function fv3_sync_page_order(DockerClient $dockerClient, array $ctNames, bool $autostart): array { + global $configDir; + $stop = function (string $why): array { fv3_debug_log("syncContainerOrder: $why, aborting before write"); return [$why]; }; + $allContainerNames = $ctNames['names']; + // The page's order needs the WHOLE list: a container missing from a partial read would be put out of place in either file + if (!$ctNames['complete']) { + if ($ctNames['empty']) { fv3_debug_log("syncContainerOrder: no containers, nothing to sync"); return []; } return $stop("Docker's container list could not be read"); } // No docker.json, or no config folder at all (deleted by hand under an open tab), is "no folders": never a stop $folders = fv3_read_json_strict("$configDir/docker.json"); - // Corrupt folder config must not rewrite the autostart file as if no folders exist + // Corrupt folder config must not be read as no folders if ($folders === null) { return $stop('the folder config could not be read'); } $ctLabels = fv3_read_container_labels($dockerClient, $allContainerNames); - // Fail closed: without label claims the order below would write label-assigned - // containers back out as unassigned — the same hazard $ctListComplete guards above. + // Fail closed: without label claims, label-assigned containers would be written back out as unassigned if ($ctLabels === null) { return $stop('the container labels could not be read'); } $prefs = fv3_docker_prefs(); - // The page's order cannot be worked out then, so the file stays as it is + // The page's order cannot be worked out then, so both files stay as they are if ($prefs === null) { return $stop("Unraid's saved Docker order (userprefs.cfg) could not be read"); } - $newOrder = fv3_page_order(fv3_compute_folder_membership($folders, $allContainerNames, $ctLabels, $prefs), $allContainerNames, $prefs); - fv3_debug_log("syncContainerOrder: computed newOrder with " . count($newOrder) . " entries (" . ($prefs ? 'userprefs.cfg' : 'A-Z, no userprefs.cfg') . ")"); + $membership = fv3_compute_folder_membership($folders, $allContainerNames, $ctLabels, $prefs); + // Each file is put in order on its own: one that fails does not hold the other back + return array_values(array_filter([ + fv3_sync_user_prefs($prefs, $membership), + $autostart ? fv3_sync_autostart_order(fv3_page_order($membership, $allContainerNames, $prefs), $allContainerNames) : null, + ])); + } - // Rewrite autostart file in $newOrder sequence; userprefs.cfg is not touched here + // The autostart file's lines in $order's sequence, entries for removed containers dropped ($names must be Docker's whole list, + // #214). Returns why it could not be put in order, else null + function fv3_sync_autostart_order(array $order, array $names): ?string { $autoStartFile = fv3_autostart_file(); - if (file_exists($autoStartFile)) { - $rawLines = fv3_read_autostart_lines($autoStartFile); - if ($rawLines === null) { return $stop('the autostart file could not be read'); } - $autoStartLines = fv3_prune_stale_autostart($rawLines, $allContainerNames, $ctListComplete); - $newAutoStart = fv3_reorder_autostart($autoStartLines, $newOrder); - if ($newAutoStart === $rawLines) { fv3_debug_log("syncContainerOrder: autostart file already in order"); return null; } - if (@file_put_contents($autoStartFile, implode("\n", $newAutoStart) . "\n", LOCK_EX) === false) { return $stop('the autostart file could not be written'); } - fv3_debug_log("syncContainerOrder: wrote autostart file with " . count($newAutoStart) . " entries"); - } + if (!file_exists($autoStartFile)) return null; + $rawLines = fv3_read_autostart_lines($autoStartFile); + if ($rawLines === null) return 'the autostart file could not be read'; + $newAutoStart = fv3_reorder_autostart(fv3_prune_stale_autostart($rawLines, $names, true), $order); + if ($newAutoStart === $rawLines) { fv3_debug_log("syncContainerOrder: autostart file already in order"); return null; } + if (@file_put_contents($autoStartFile, implode("\n", $newAutoStart) . "\n", LOCK_EX) === false) return 'the autostart file could not be written'; + fv3_debug_log("syncContainerOrder: wrote autostart file with " . count($newAutoStart) . " entries"); return null; } diff --git a/src/folder.view3/usr/local/emhttp/plugins/folder.view3/server/read_membership.php b/src/folder.view3/usr/local/emhttp/plugins/folder.view3/server/read_membership.php index ab7fa68d..1e3cc838 100644 --- a/src/folder.view3/usr/local/emhttp/plugins/folder.view3/server/read_membership.php +++ b/src/folder.view3/usr/local/emhttp/plugins/folder.view3/server/read_membership.php @@ -41,8 +41,8 @@ echo json_encode(['error' => 'container label read unavailable']); exit; } - // The map does not depend on the saved order (page_order_test.php), so userprefs.cfg is not read here - $m = fv3_compute_folder_membership($folders, $allContainerNames, $ctLabels); + // The saved order as the page reads it (readUserPrefs: unreadable = nothing saved) decides who gets a container two folders' regexes match + $m = fv3_compute_folder_membership($folders, $allContainerNames, $ctLabels, fv3_docker_prefs() ?? []); $out = []; foreach ($m['containers'] as $placeholder => $members) { foreach ($members as $ct) { $out[$ct] = $m['names'][$placeholder]; }