BlueGit

timfa filemanager

Add async thumbnail cache worker and lazy icon loading

timfa Tim Falken · pushed by timfa

Authored 2026-05-04 · 6 months ago

Hash
2b1312d772d154e21983ed40d270fdc7290f88a6
Parent
52509ea9
10 files changed +1235 −85
.github/technical-reference.md +21 −6
@@ -1,8 +1,16 @@
1 1 # Technical Reference
2 2
3 3 ## server/index.js
4 - start() - Initialises DB/keys, loads config, starts HTTP server (config.port) and optional HTTPS server (config.httpsPort + config.tlsCert + config.tlsKey). Both share the same Express app.
5 - shutdown(opts, ...servers) - Graceful teardown: closes DB, closes all provided http/https Server instances, and exits with configurable code after drain/timeout.
4 - start() - Initialises DB/keys, starts HTTP/HTTPS servers, and starts the background thumbnail cache loop.
5 - shutdown(opts, ...servers) - Graceful teardown: stops thumbnail loop, closes DB/servers, exits with configurable code after drain/timeout.
6
7 ## server/thumbnail-cache.js
8 - syncThumbnailCacheOnce() - Mirrors configured roots into public/thumbs and generates 99x99-max WebP thumbnails for image files; removes stale thumbnails and updates manifest hashes.
9 - startThumbnailCacheLoop() - Schedules cache sync runs 5 seconds after boot and 5 seconds after each run completes.
10 - stopThumbnailCacheLoop() - Stops scheduled background cache sync runs.
11 - getCachedThumbnailInfo(sourceFile) - Returns cached thumbnail path/content-type when present; null when not ready.
12 - getThumbPathForSourceFile(sourceFile) - Maps an absolute source file path to its mirrored cache thumbnail path.
13 - getThumbRelPathForSourceFile(sourceFile) - Returns public-relative thumbnail path used in manifest entries.
6 14
7 15 ## server/db.js
8 16 - initDb() - Initializes SQLite schema for users, file metadata, and auth_sessions (idle timeout/revocation support).
@@ -32,6 +40,7 @@
32 40 ## server/routes/files.js
33 41 - GET /api/files/roots - Returns readable roots with display label (alias when configured), originalName, and path.
34 42 - POST /api/files/root-alias - Sets a display-only alias for an exact configured root path (no filesystem rename).
43 - GET /api/files/thumbnail - Serves cache-only thumbnail images for authorized files; returns 404 while cache is not ready.
35 44
36 45 ## public/app.js
37 46 - showApp() - Reveals app shell; keeps sidebar folded by default on mobile and shows folder overview sidebar on desktop.
@@ -45,10 +54,16 @@
45 54 - showConfirm(title, message) - In-page confirm dialog; returns Promise<boolean>. Use instead of window.confirm().
46 55 - showPrompt(title, message, defaultValue) - In-page text-input dialog; returns Promise<string|null>. Use instead of window.prompt().
47 56 - showOverwrite(filename) - In-page overwrite-decision dialog for file conflicts; returns Promise<'yes'|'no'|'all'|'none'>.
48 - loadThumbnails() - Loads per-file image thumbnails into file SVG icons after grid rendering.
49 - loadOneThumbnail(iconEl) - Injects clipped in-icon thumbnails: real previews for image/video/text where feasible and generated badges for other file types.
50 - getThumbnailKind(name) - Classifies files into thumbnail strategy buckets (image/video/text/audio/pdf/badge).
51 - buildThumbnailSource(item, blob, kind) - Produces thumbnail image source (blob URL/data URL) for icon injection.
57 - loadThumbnails() - Registers visible file icons for lazy thumbnail loading; retries missing cache thumbnails during incremental refresh.
58 - loadOneThumbnail(iconEl) - Loads thumbnails from server cache endpoint for images, text snapshots for text files, and badges for other files.
59 - getThumbnailKind(name) - Classifies files into image/text/badge thumbnail strategies.
60 - observeThumbnailIcon(iconEl) - Defers thumbnail fetch work until file icons are near/in the viewport.
61 - disconnectThumbnailObserver() - Clears active IntersectionObserver when the grid is rebuilt.
62 - buildThumbnailSource(item, blob, kind) - Produces thumbnail image source (data/blob URL) for icon injection.
63
64 ## tests/thumbnail-cache.test.js
65 - thumbnail cache worker / creates cached thumbnail with dimensions smaller than 100px - Verifies cached image generation and manifest write.
66 - thumbnail cache worker / removes cached thumbnail when source file is deleted - Verifies stale thumbnail cleanup behavior.
52 67 - detectCodeLanguage(name, mime) - Determines preview language for text/script files by MIME and extension.
53 68 - prettyPrintCode(raw, lang) - Best-effort formatter for JSON/markup/script previews before rendering.
54 69 - highlightCode(raw, lang) - Escapes and syntax-highlights preview text into HTML spans.
@@ -1,8 +1,16 @@
1# Technical Reference
1# Technical Reference
2
2
3## server/index.js
3## server/index.js
4- start() - Initialises DB/keys, loads config, starts HTTP server (config.port) and optional HTTPS server (config.httpsPort + config.tlsCert + config.tlsKey). Both share the same Express app.
4- start() - Initialises DB/keys, starts HTTP/HTTPS servers, and starts the background thumbnail cache loop.
5- shutdown(opts, ...servers) - Graceful teardown: closes DB, closes all provided http/https Server instances, and exits with configurable code after drain/timeout.
5- shutdown(opts, ...servers) - Graceful teardown: stops thumbnail loop, closes DB/servers, exits with configurable code after drain/timeout.
6
7## server/thumbnail-cache.js
8- syncThumbnailCacheOnce() - Mirrors configured roots into public/thumbs and generates 99x99-max WebP thumbnails for image files; removes stale thumbnails and updates manifest hashes.
9- startThumbnailCacheLoop() - Schedules cache sync runs 5 seconds after boot and 5 seconds after each run completes.
10- stopThumbnailCacheLoop() - Stops scheduled background cache sync runs.
11- getCachedThumbnailInfo(sourceFile) - Returns cached thumbnail path/content-type when present; null when not ready.
12- getThumbPathForSourceFile(sourceFile) - Maps an absolute source file path to its mirrored cache thumbnail path.
13- getThumbRelPathForSourceFile(sourceFile) - Returns public-relative thumbnail path used in manifest entries.
6
14
7## server/db.js
15## server/db.js
8- initDb() - Initializes SQLite schema for users, file metadata, and auth_sessions (idle timeout/revocation support).
16- initDb() - Initializes SQLite schema for users, file metadata, and auth_sessions (idle timeout/revocation support).
@@ -32,6 +40,7 @@
32## server/routes/files.js
40## server/routes/files.js
33- GET /api/files/roots - Returns readable roots with display label (alias when configured), originalName, and path.
41- GET /api/files/roots - Returns readable roots with display label (alias when configured), originalName, and path.
34- POST /api/files/root-alias - Sets a display-only alias for an exact configured root path (no filesystem rename).
42- POST /api/files/root-alias - Sets a display-only alias for an exact configured root path (no filesystem rename).
43- GET /api/files/thumbnail - Serves cache-only thumbnail images for authorized files; returns 404 while cache is not ready.
35
44
36## public/app.js
45## public/app.js
37- showApp() - Reveals app shell; keeps sidebar folded by default on mobile and shows folder overview sidebar on desktop.
46- showApp() - Reveals app shell; keeps sidebar folded by default on mobile and shows folder overview sidebar on desktop.
@@ -45,10 +54,16 @@
45- showConfirm(title, message) - In-page confirm dialog; returns Promise<boolean>. Use instead of window.confirm().
54- showConfirm(title, message) - In-page confirm dialog; returns Promise<boolean>. Use instead of window.confirm().
46- showPrompt(title, message, defaultValue) - In-page text-input dialog; returns Promise<string|null>. Use instead of window.prompt().
55- showPrompt(title, message, defaultValue) - In-page text-input dialog; returns Promise<string|null>. Use instead of window.prompt().
47- showOverwrite(filename) - In-page overwrite-decision dialog for file conflicts; returns Promise<'yes'|'no'|'all'|'none'>.
56- showOverwrite(filename) - In-page overwrite-decision dialog for file conflicts; returns Promise<'yes'|'no'|'all'|'none'>.
48- loadThumbnails() - Loads per-file image thumbnails into file SVG icons after grid rendering.
57- loadThumbnails() - Registers visible file icons for lazy thumbnail loading; retries missing cache thumbnails during incremental refresh.
49- loadOneThumbnail(iconEl) - Injects clipped in-icon thumbnails: real previews for image/video/text where feasible and generated badges for other file types.
58- loadOneThumbnail(iconEl) - Loads thumbnails from server cache endpoint for images, text snapshots for text files, and badges for other files.
50- getThumbnailKind(name) - Classifies files into thumbnail strategy buckets (image/video/text/audio/pdf/badge).
59- getThumbnailKind(name) - Classifies files into image/text/badge thumbnail strategies.
51- buildThumbnailSource(item, blob, kind) - Produces thumbnail image source (blob URL/data URL) for icon injection.
60- observeThumbnailIcon(iconEl) - Defers thumbnail fetch work until file icons are near/in the viewport.
61- disconnectThumbnailObserver() - Clears active IntersectionObserver when the grid is rebuilt.
62- buildThumbnailSource(item, blob, kind) - Produces thumbnail image source (data/blob URL) for icon injection.
63
64## tests/thumbnail-cache.test.js
65- thumbnail cache worker / creates cached thumbnail with dimensions smaller than 100px - Verifies cached image generation and manifest write.
66- thumbnail cache worker / removes cached thumbnail when source file is deleted - Verifies stale thumbnail cleanup behavior.
52- detectCodeLanguage(name, mime) - Determines preview language for text/script files by MIME and extension.
67- detectCodeLanguage(name, mime) - Determines preview language for text/script files by MIME and extension.
53- prettyPrintCode(raw, lang) - Best-effort formatter for JSON/markup/script previews before rendering.
68- prettyPrintCode(raw, lang) - Best-effort formatter for JSON/markup/script previews before rendering.
54- highlightCode(raw, lang) - Escapes and syntax-highlights preview text into HTML spans.
69- highlightCode(raw, lang) - Escapes and syntax-highlights preview text into HTML spans.
.github/tests.md +10 −0
@@ -42,6 +42,16 @@
42 42 - `GET /api/files/roots returns alias label and original name`
43 43 - `POST /api/files/root-alias stores alias without renaming filesystem path`
44 44 - `POST /api/files/root-alias rejects non-root paths`
45 - `GET /api/files/thumbnail`
46 - `returns 404 while cached thumbnail is not ready`
47 - `serves cached thumbnail file when available`
48
49 ---
50
51 ## `test/thumbnail-cache.test.js`
52 - `thumbnail cache worker`
53 - `creates cached thumbnail with dimensions smaller than 100px`
54 - `removes cached thumbnail when source file is deleted`
45 55
46 56 ---
47 57
@@ -42,6 +42,16 @@
42- `GET /api/files/roots returns alias label and original name`
42- `GET /api/files/roots returns alias label and original name`
43- `POST /api/files/root-alias stores alias without renaming filesystem path`
43- `POST /api/files/root-alias stores alias without renaming filesystem path`
44- `POST /api/files/root-alias rejects non-root paths`
44- `POST /api/files/root-alias rejects non-root paths`
45- `GET /api/files/thumbnail`
46- `returns 404 while cached thumbnail is not ready`
47- `serves cached thumbnail file when available`
48
49---
50
51## `test/thumbnail-cache.test.js`
52- `thumbnail cache worker`
53- `creates cached thumbnail with dimensions smaller than 100px`
54- `removes cached thumbnail when source file is deleted`
45
55
46---
56---
47
57
package-lock.json +575 −0
@@ -15,6 +15,7 @@
15 15 "jsonwebtoken": "^9.0.2",
16 16 "multer": "^1.4.5-lts.1",
17 17 "node-sqlite3-wasm": "^0.8.10",
18 "sharp": "^0.34.5",
18 19 "uuid": "^9.0.0"
19 20 },
20 21 "devDependencies": {
@@ -683,6 +684,529 @@
683 684 "node": ">=18"
684 685 }
685 686 },
687 "node_modules/@emnapi/runtime": {
688 "version": "1.10.0",
689 "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.10.0.tgz",
690 "integrity": "sha512-ewvYlk86xUoGI0zQRNq/mC+16R1QeDlKQy21Ki3oSYXNgLb45GV1P6A0M+/s6nyCuNDqe5VpaY84BzXGwVbwFA==",
691 "license": "MIT",
692 "optional": true,
693 "dependencies": {
694 "tslib": "^2.4.0"
695 }
696 },
697 "node_modules/@img/colour": {
698 "version": "1.1.0",
699 "resolved": "https://registry.npmjs.org/@img/colour/-/colour-1.1.0.tgz",
700 "integrity": "sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ==",
701 "license": "MIT",
702 "engines": {
703 "node": ">=18"
704 }
705 },
706 "node_modules/@img/sharp-darwin-arm64": {
707 "version": "0.34.5",
708 "resolved": "https://registry.npmjs.org/@img/sharp-darwin-arm64/-/sharp-darwin-arm64-0.34.5.tgz",
709 "integrity": "sha512-imtQ3WMJXbMY4fxb/Ndp6HBTNVtWCUI0WdobyheGf5+ad6xX8VIDO8u2xE4qc/fr08CKG/7dDseFtn6M6g/r3w==",
710 "cpu": [
711 "arm64"
712 ],
713 "license": "Apache-2.0",
714 "optional": true,
715 "os": [
716 "darwin"
717 ],
718 "engines": {
719 "node": "^18.17.0 || ^20.3.0 || >=21.0.0"
720 },
721 "funding": {
722 "url": "https://opencollective.com/libvips"
723 },
724 "optionalDependencies": {
725 "@img/sharp-libvips-darwin-arm64": "1.2.4"
726 }
727 },
728 "node_modules/@img/sharp-darwin-x64": {
729 "version": "0.34.5",
730 "resolved": "https://registry.npmjs.org/@img/sharp-darwin-x64/-/sharp-darwin-x64-0.34.5.tgz",
731 "integrity": "sha512-YNEFAF/4KQ/PeW0N+r+aVVsoIY0/qxxikF2SWdp+NRkmMB7y9LBZAVqQ4yhGCm/H3H270OSykqmQMKLBhBJDEw==",
732 "cpu": [
733 "x64"
734 ],
735 "license": "Apache-2.0",
736 "optional": true,
737 "os": [
738 "darwin"
739 ],
740 "engines": {
741 "node": "^18.17.0 || ^20.3.0 || >=21.0.0"
742 },
743 "funding": {
744 "url": "https://opencollective.com/libvips"
745 },
746 "optionalDependencies": {
747 "@img/sharp-libvips-darwin-x64": "1.2.4"
748 }
749 },
750 "node_modules/@img/sharp-libvips-darwin-arm64": {
751 "version": "1.2.4",
752 "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-arm64/-/sharp-libvips-darwin-arm64-1.2.4.tgz",
753 "integrity": "sha512-zqjjo7RatFfFoP0MkQ51jfuFZBnVE2pRiaydKJ1G/rHZvnsrHAOcQALIi9sA5co5xenQdTugCvtb1cuf78Vf4g==",
754 "cpu": [
755 "arm64"
756 ],
757 "license": "LGPL-3.0-or-later",
758 "optional": true,
759 "os": [
760 "darwin"
761 ],
762 "funding": {
763 "url": "https://opencollective.com/libvips"
764 }
765 },
766 "node_modules/@img/sharp-libvips-darwin-x64": {
767 "version": "1.2.4",
768 "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-x64/-/sharp-libvips-darwin-x64-1.2.4.tgz",
769 "integrity": "sha512-1IOd5xfVhlGwX+zXv2N93k0yMONvUlANylbJw1eTah8K/Jtpi15KC+WSiaX/nBmbm2HxRM1gZ0nSdjSsrZbGKg==",
770 "cpu": [
771 "x64"
772 ],
773 "license": "LGPL-3.0-or-later",
774 "optional": true,
775 "os": [
776 "darwin"
777 ],
778 "funding": {
779 "url": "https://opencollective.com/libvips"
780 }
781 },
782 "node_modules/@img/sharp-libvips-linux-arm": {
783 "version": "1.2.4",
784 "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm/-/sharp-libvips-linux-arm-1.2.4.tgz",
785 "integrity": "sha512-bFI7xcKFELdiNCVov8e44Ia4u2byA+l3XtsAj+Q8tfCwO6BQ8iDojYdvoPMqsKDkuoOo+X6HZA0s0q11ANMQ8A==",
786 "cpu": [
787 "arm"
788 ],
789 "libc": [
790 "glibc"
791 ],
792 "license": "LGPL-3.0-or-later",
793 "optional": true,
794 "os": [
795 "linux"
796 ],
797 "funding": {
798 "url": "https://opencollective.com/libvips"
799 }
800 },
801 "node_modules/@img/sharp-libvips-linux-arm64": {
802 "version": "1.2.4",
803 "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm64/-/sharp-libvips-linux-arm64-1.2.4.tgz",
804 "integrity": "sha512-excjX8DfsIcJ10x1Kzr4RcWe1edC9PquDRRPx3YVCvQv+U5p7Yin2s32ftzikXojb1PIFc/9Mt28/y+iRklkrw==",
805 "cpu": [
806 "arm64"
807 ],
808 "libc": [
809 "glibc"
810 ],
811 "license": "LGPL-3.0-or-later",
812 "optional": true,
813 "os": [
814 "linux"
815 ],
816 "funding": {
817 "url": "https://opencollective.com/libvips"
818 }
819 },
820 "node_modules/@img/sharp-libvips-linux-ppc64": {
821 "version": "1.2.4",
822 "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-ppc64/-/sharp-libvips-linux-ppc64-1.2.4.tgz",
823 "integrity": "sha512-FMuvGijLDYG6lW+b/UvyilUWu5Ayu+3r2d1S8notiGCIyYU/76eig1UfMmkZ7vwgOrzKzlQbFSuQfgm7GYUPpA==",
824 "cpu": [
825 "ppc64"
826 ],
827 "libc": [
828 "glibc"
829 ],
830 "license": "LGPL-3.0-or-later",
831 "optional": true,
832 "os": [
833 "linux"
834 ],
835 "funding": {
836 "url": "https://opencollective.com/libvips"
837 }
838 },
839 "node_modules/@img/sharp-libvips-linux-riscv64": {
840 "version": "1.2.4",
841 "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-riscv64/-/sharp-libvips-linux-riscv64-1.2.4.tgz",
842 "integrity": "sha512-oVDbcR4zUC0ce82teubSm+x6ETixtKZBh/qbREIOcI3cULzDyb18Sr/Wcyx7NRQeQzOiHTNbZFF1UwPS2scyGA==",
843 "cpu": [
844 "riscv64"
845 ],
846 "libc": [
847 "glibc"
848 ],
849 "license": "LGPL-3.0-or-later",
850 "optional": true,
851 "os": [
852 "linux"
853 ],
854 "funding": {
855 "url": "https://opencollective.com/libvips"
856 }
857 },
858 "node_modules/@img/sharp-libvips-linux-s390x": {
859 "version": "1.2.4",
860 "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-s390x/-/sharp-libvips-linux-s390x-1.2.4.tgz",
861 "integrity": "sha512-qmp9VrzgPgMoGZyPvrQHqk02uyjA0/QrTO26Tqk6l4ZV0MPWIW6LTkqOIov+J1yEu7MbFQaDpwdwJKhbJvuRxQ==",
862 "cpu": [
863 "s390x"
864 ],
865 "libc": [
866 "glibc"
867 ],
868 "license": "LGPL-3.0-or-later",
869 "optional": true,
870 "os": [
871 "linux"
872 ],
873 "funding": {
874 "url": "https://opencollective.com/libvips"
875 }
876 },
877 "node_modules/@img/sharp-libvips-linux-x64": {
878 "version": "1.2.4",
879 "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-x64/-/sharp-libvips-linux-x64-1.2.4.tgz",
880 "integrity": "sha512-tJxiiLsmHc9Ax1bz3oaOYBURTXGIRDODBqhveVHonrHJ9/+k89qbLl0bcJns+e4t4rvaNBxaEZsFtSfAdquPrw==",
881 "cpu": [
882 "x64"
883 ],
884 "libc": [
885 "glibc"
886 ],
887 "license": "LGPL-3.0-or-later",
888 "optional": true,
889 "os": [
890 "linux"
891 ],
892 "funding": {
893 "url": "https://opencollective.com/libvips"
894 }
895 },
896 "node_modules/@img/sharp-libvips-linuxmusl-arm64": {
897 "version": "1.2.4",
898 "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-arm64/-/sharp-libvips-linuxmusl-arm64-1.2.4.tgz",
899 "integrity": "sha512-FVQHuwx1IIuNow9QAbYUzJ+En8KcVm9Lk5+uGUQJHaZmMECZmOlix9HnH7n1TRkXMS0pGxIJokIVB9SuqZGGXw==",
900 "cpu": [
901 "arm64"
902 ],
903 "libc": [
904 "musl"
905 ],
906 "license": "LGPL-3.0-or-later",
907 "optional": true,
908 "os": [
909 "linux"
910 ],
911 "funding": {
912 "url": "https://opencollective.com/libvips"
913 }
914 },
915 "node_modules/@img/sharp-libvips-linuxmusl-x64": {
916 "version": "1.2.4",
917 "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-x64/-/sharp-libvips-linuxmusl-x64-1.2.4.tgz",
918 "integrity": "sha512-+LpyBk7L44ZIXwz/VYfglaX/okxezESc6UxDSoyo2Ks6Jxc4Y7sGjpgU9s4PMgqgjj1gZCylTieNamqA1MF7Dg==",
919 "cpu": [
920 "x64"
921 ],
922 "libc": [
923 "musl"
924 ],
925 "license": "LGPL-3.0-or-later",
926 "optional": true,
927 "os": [
928 "linux"
929 ],
930 "funding": {
931 "url": "https://opencollective.com/libvips"
932 }
933 },
934 "node_modules/@img/sharp-linux-arm": {
935 "version": "0.34.5",
936 "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm/-/sharp-linux-arm-0.34.5.tgz",
937 "integrity": "sha512-9dLqsvwtg1uuXBGZKsxem9595+ujv0sJ6Vi8wcTANSFpwV/GONat5eCkzQo/1O6zRIkh0m/8+5BjrRr7jDUSZw==",
938 "cpu": [
939 "arm"
940 ],
941 "libc": [
942 "glibc"
943 ],
944 "license": "Apache-2.0",
945 "optional": true,
946 "os": [
947 "linux"
948 ],
949 "engines": {
950 "node": "^18.17.0 || ^20.3.0 || >=21.0.0"
951 },
952 "funding": {
953 "url": "https://opencollective.com/libvips"
954 },
955 "optionalDependencies": {
956 "@img/sharp-libvips-linux-arm": "1.2.4"
957 }
958 },
959 "node_modules/@img/sharp-linux-arm64": {
960 "version": "0.34.5",
961 "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm64/-/sharp-linux-arm64-0.34.5.tgz",
962 "integrity": "sha512-bKQzaJRY/bkPOXyKx5EVup7qkaojECG6NLYswgktOZjaXecSAeCWiZwwiFf3/Y+O1HrauiE3FVsGxFg8c24rZg==",
963 "cpu": [
964 "arm64"
965 ],
966 "libc": [
967 "glibc"
968 ],
969 "license": "Apache-2.0",
970 "optional": true,
971 "os": [
972 "linux"
973 ],
974 "engines": {
975 "node": "^18.17.0 || ^20.3.0 || >=21.0.0"
976 },
977 "funding": {
978 "url": "https://opencollective.com/libvips"
979 },
980 "optionalDependencies": {
981 "@img/sharp-libvips-linux-arm64": "1.2.4"
982 }
983 },
984 "node_modules/@img/sharp-linux-ppc64": {
985 "version": "0.34.5",
986 "resolved": "https://registry.npmjs.org/@img/sharp-linux-ppc64/-/sharp-linux-ppc64-0.34.5.tgz",
987 "integrity": "sha512-7zznwNaqW6YtsfrGGDA6BRkISKAAE1Jo0QdpNYXNMHu2+0dTrPflTLNkpc8l7MUP5M16ZJcUvysVWWrMefZquA==",
988 "cpu": [
989 "ppc64"
990 ],
991 "libc": [
992 "glibc"
993 ],
994 "license": "Apache-2.0",
995 "optional": true,
996 "os": [
997 "linux"
998 ],
999 "engines": {
1000 "node": "^18.17.0 || ^20.3.0 || >=21.0.0"
1001 },
1002 "funding": {
1003 "url": "https://opencollective.com/libvips"
1004 },
1005 "optionalDependencies": {
1006 "@img/sharp-libvips-linux-ppc64": "1.2.4"
1007 }
1008 },
1009 "node_modules/@img/sharp-linux-riscv64": {
1010 "version": "0.34.5",
1011 "resolved": "https://registry.npmjs.org/@img/sharp-linux-riscv64/-/sharp-linux-riscv64-0.34.5.tgz",
1012 "integrity": "sha512-51gJuLPTKa7piYPaVs8GmByo7/U7/7TZOq+cnXJIHZKavIRHAP77e3N2HEl3dgiqdD/w0yUfiJnII77PuDDFdw==",
1013 "cpu": [
1014 "riscv64"
1015 ],
1016 "libc": [
1017 "glibc"
1018 ],
1019 "license": "Apache-2.0",
1020 "optional": true,
1021 "os": [
1022 "linux"
1023 ],
1024 "engines": {
1025 "node": "^18.17.0 || ^20.3.0 || >=21.0.0"
1026 },
1027 "funding": {
1028 "url": "https://opencollective.com/libvips"
1029 },
1030 "optionalDependencies": {
1031 "@img/sharp-libvips-linux-riscv64": "1.2.4"
1032 }
1033 },
1034 "node_modules/@img/sharp-linux-s390x": {
1035 "version": "0.34.5",
1036 "resolved": "https://registry.npmjs.org/@img/sharp-linux-s390x/-/sharp-linux-s390x-0.34.5.tgz",
1037 "integrity": "sha512-nQtCk0PdKfho3eC5MrbQoigJ2gd1CgddUMkabUj+rBevs8tZ2cULOx46E7oyX+04WGfABgIwmMC0VqieTiR4jg==",
1038 "cpu": [
1039 "s390x"
1040 ],
1041 "libc": [
1042 "glibc"
1043 ],
1044 "license": "Apache-2.0",
1045 "optional": true,
1046 "os": [
1047 "linux"
1048 ],
1049 "engines": {
1050 "node": "^18.17.0 || ^20.3.0 || >=21.0.0"
1051 },
1052 "funding": {
1053 "url": "https://opencollective.com/libvips"
1054 },
1055 "optionalDependencies": {
1056 "@img/sharp-libvips-linux-s390x": "1.2.4"
1057 }
1058 },
1059 "node_modules/@img/sharp-linux-x64": {
1060 "version": "0.34.5",
1061 "resolved": "https://registry.npmjs.org/@img/sharp-linux-x64/-/sharp-linux-x64-0.34.5.tgz",
1062 "integrity": "sha512-MEzd8HPKxVxVenwAa+JRPwEC7QFjoPWuS5NZnBt6B3pu7EG2Ge0id1oLHZpPJdn3OQK+BQDiw9zStiHBTJQQQQ==",
1063 "cpu": [
1064 "x64"
1065 ],
1066 "libc": [
1067 "glibc"
1068 ],
1069 "license": "Apache-2.0",
1070 "optional": true,
1071 "os": [
1072 "linux"
1073 ],
1074 "engines": {
1075 "node": "^18.17.0 || ^20.3.0 || >=21.0.0"
1076 },
1077 "funding": {
1078 "url": "https://opencollective.com/libvips"
1079 },
1080 "optionalDependencies": {
1081 "@img/sharp-libvips-linux-x64": "1.2.4"
1082 }
1083 },
1084 "node_modules/@img/sharp-linuxmusl-arm64": {
1085 "version": "0.34.5",
1086 "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-arm64/-/sharp-linuxmusl-arm64-0.34.5.tgz",
1087 "integrity": "sha512-fprJR6GtRsMt6Kyfq44IsChVZeGN97gTD331weR1ex1c1rypDEABN6Tm2xa1wE6lYb5DdEnk03NZPqA7Id21yg==",
1088 "cpu": [
1089 "arm64"
1090 ],
1091 "libc": [
1092 "musl"
1093 ],
1094 "license": "Apache-2.0",
1095 "optional": true,
1096 "os": [
1097 "linux"
1098 ],
1099 "engines": {
1100 "node": "^18.17.0 || ^20.3.0 || >=21.0.0"
1101 },
1102 "funding": {
1103 "url": "https://opencollective.com/libvips"
1104 },
1105 "optionalDependencies": {
1106 "@img/sharp-libvips-linuxmusl-arm64": "1.2.4"
1107 }
1108 },
1109 "node_modules/@img/sharp-linuxmusl-x64": {
1110 "version": "0.34.5",
1111 "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-x64/-/sharp-linuxmusl-x64-0.34.5.tgz",
1112 "integrity": "sha512-Jg8wNT1MUzIvhBFxViqrEhWDGzqymo3sV7z7ZsaWbZNDLXRJZoRGrjulp60YYtV4wfY8VIKcWidjojlLcWrd8Q==",
1113 "cpu": [
1114 "x64"
1115 ],
1116 "libc": [
1117 "musl"
1118 ],
1119 "license": "Apache-2.0",
1120 "optional": true,
1121 "os": [
1122 "linux"
1123 ],
1124 "engines": {
1125 "node": "^18.17.0 || ^20.3.0 || >=21.0.0"
1126 },
1127 "funding": {
1128 "url": "https://opencollective.com/libvips"
1129 },
1130 "optionalDependencies": {
1131 "@img/sharp-libvips-linuxmusl-x64": "1.2.4"
1132 }
1133 },
1134 "node_modules/@img/sharp-wasm32": {
1135 "version": "0.34.5",
1136 "resolved": "https://registry.npmjs.org/@img/sharp-wasm32/-/sharp-wasm32-0.34.5.tgz",
1137 "integrity": "sha512-OdWTEiVkY2PHwqkbBI8frFxQQFekHaSSkUIJkwzclWZe64O1X4UlUjqqqLaPbUpMOQk6FBu/HtlGXNblIs0huw==",
1138 "cpu": [
1139 "wasm32"
1140 ],
1141 "license": "Apache-2.0 AND LGPL-3.0-or-later AND MIT",
1142 "optional": true,
1143 "dependencies": {
1144 "@emnapi/runtime": "^1.7.0"
1145 },
1146 "engines": {
1147 "node": "^18.17.0 || ^20.3.0 || >=21.0.0"
1148 },
1149 "funding": {
1150 "url": "https://opencollective.com/libvips"
1151 }
1152 },
1153 "node_modules/@img/sharp-win32-arm64": {
1154 "version": "0.34.5",
1155 "resolved": "https://registry.npmjs.org/@img/sharp-win32-arm64/-/sharp-win32-arm64-0.34.5.tgz",
1156 "integrity": "sha512-WQ3AgWCWYSb2yt+IG8mnC6Jdk9Whs7O0gxphblsLvdhSpSTtmu69ZG1Gkb6NuvxsNACwiPV6cNSZNzt0KPsw7g==",
1157 "cpu": [
1158 "arm64"
1159 ],
1160 "license": "Apache-2.0 AND LGPL-3.0-or-later",
1161 "optional": true,
1162 "os": [
1163 "win32"
1164 ],
1165 "engines": {
1166 "node": "^18.17.0 || ^20.3.0 || >=21.0.0"
1167 },
1168 "funding": {
1169 "url": "https://opencollective.com/libvips"
1170 }
1171 },
1172 "node_modules/@img/sharp-win32-ia32": {
1173 "version": "0.34.5",
1174 "resolved": "https://registry.npmjs.org/@img/sharp-win32-ia32/-/sharp-win32-ia32-0.34.5.tgz",
1175 "integrity": "sha512-FV9m/7NmeCmSHDD5j4+4pNI8Cp3aW+JvLoXcTUo0IqyjSfAZJ8dIUmijx1qaJsIiU+Hosw6xM5KijAWRJCSgNg==",
1176 "cpu": [
1177 "ia32"
1178 ],
1179 "license": "Apache-2.0 AND LGPL-3.0-or-later",
1180 "optional": true,
1181 "os": [
1182 "win32"
1183 ],
1184 "engines": {
1185 "node": "^18.17.0 || ^20.3.0 || >=21.0.0"
1186 },
1187 "funding": {
1188 "url": "https://opencollective.com/libvips"
1189 }
1190 },
1191 "node_modules/@img/sharp-win32-x64": {
1192 "version": "0.34.5",
1193 "resolved": "https://registry.npmjs.org/@img/sharp-win32-x64/-/sharp-win32-x64-0.34.5.tgz",
1194 "integrity": "sha512-+29YMsqY2/9eFEiW93eqWnuLcWcufowXewwSNIT6UwZdUUCrM3oFjMWH/Z6/TMmb4hlFenmfAVbpWeup2jryCw==",
1195 "cpu": [
1196 "x64"
1197 ],
1198 "license": "Apache-2.0 AND LGPL-3.0-or-later",
1199 "optional": true,
1200 "os": [
1201 "win32"
1202 ],
1203 "engines": {
1204 "node": "^18.17.0 || ^20.3.0 || >=21.0.0"
1205 },
1206 "funding": {
1207 "url": "https://opencollective.com/libvips"
1208 }
1209 },
686 1210 "node_modules/@istanbuljs/load-nyc-config": {
687 1211 "version": "1.1.0",
688 1212 "resolved": "https://registry.npmjs.org/@istanbuljs/load-nyc-config/-/load-nyc-config-1.1.0.tgz",
@@ -5822,6 +6346,50 @@
5822 6346 "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==",
5823 6347 "license": "ISC"
5824 6348 },
6349 "node_modules/sharp": {
6350 "version": "0.34.5",
6351 "resolved": "https://registry.npmjs.org/sharp/-/sharp-0.34.5.tgz",
6352 "integrity": "sha512-Ou9I5Ft9WNcCbXrU9cMgPBcCK8LiwLqcbywW3t4oDV37n1pzpuNLsYiAV8eODnjbtQlSDwZ2cUEeQz4E54Hltg==",
6353 "hasInstallScript": true,
6354 "license": "Apache-2.0",
6355 "dependencies": {
6356 "@img/colour": "^1.0.0",
6357 "detect-libc": "^2.1.2",
6358 "semver": "^7.7.3"
6359 },
6360 "engines": {
6361 "node": "^18.17.0 || ^20.3.0 || >=21.0.0"
6362 },
6363 "funding": {
6364 "url": "https://opencollective.com/libvips"
6365 },
6366 "optionalDependencies": {
6367 "@img/sharp-darwin-arm64": "0.34.5",
6368 "@img/sharp-darwin-x64": "0.34.5",
6369 "@img/sharp-libvips-darwin-arm64": "1.2.4",
6370 "@img/sharp-libvips-darwin-x64": "1.2.4",
6371 "@img/sharp-libvips-linux-arm": "1.2.4",
6372 "@img/sharp-libvips-linux-arm64": "1.2.4",
6373 "@img/sharp-libvips-linux-ppc64": "1.2.4",
6374 "@img/sharp-libvips-linux-riscv64": "1.2.4",
6375 "@img/sharp-libvips-linux-s390x": "1.2.4",
6376 "@img/sharp-libvips-linux-x64": "1.2.4",
6377 "@img/sharp-libvips-linuxmusl-arm64": "1.2.4",
6378 "@img/sharp-libvips-linuxmusl-x64": "1.2.4",
6379 "@img/sharp-linux-arm": "0.34.5",
6380 "@img/sharp-linux-arm64": "0.34.5",
6381 "@img/sharp-linux-ppc64": "0.34.5",
6382 "@img/sharp-linux-riscv64": "0.34.5",
6383 "@img/sharp-linux-s390x": "0.34.5",
6384 "@img/sharp-linux-x64": "0.34.5",
6385 "@img/sharp-linuxmusl-arm64": "0.34.5",
6386 "@img/sharp-linuxmusl-x64": "0.34.5",
6387 "@img/sharp-wasm32": "0.34.5",
6388 "@img/sharp-win32-arm64": "0.34.5",
6389 "@img/sharp-win32-ia32": "0.34.5",
6390 "@img/sharp-win32-x64": "0.34.5"
6391 }
6392 },
5825 6393 "node_modules/shebang-command": {
5826 6394 "version": "2.0.0",
5827 6395 "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz",
@@ -6224,6 +6792,13 @@
6224 6792 "integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==",
6225 6793 "license": "MIT"
6226 6794 },
6795 "node_modules/tslib": {
6796 "version": "2.8.1",
6797 "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",
6798 "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",
6799 "license": "0BSD",
6800 "optional": true
6801 },
6227 6802 "node_modules/type-detect": {
6228 6803 "version": "4.0.8",
6229 6804 "resolved": "https://registry.npmjs.org/type-detect/-/type-detect-4.0.8.tgz",
@@ -15,6 +15,7 @@
15 "jsonwebtoken": "^9.0.2",
15 "jsonwebtoken": "^9.0.2",
16 "multer": "^1.4.5-lts.1",
16 "multer": "^1.4.5-lts.1",
17 "node-sqlite3-wasm": "^0.8.10",
17 "node-sqlite3-wasm": "^0.8.10",
18 "sharp": "^0.34.5",
18 "uuid": "^9.0.0"
19 "uuid": "^9.0.0"
19 },
20 },
20 "devDependencies": {
21 "devDependencies": {
@@ -683,6 +684,529 @@
683 "node": ">=18"
684 "node": ">=18"
684 }
685 }
685 },
686 },
687 "node_modules/@emnapi/runtime": {
688 "version": "1.10.0",
689 "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.10.0.tgz",
690 "integrity": "sha512-ewvYlk86xUoGI0zQRNq/mC+16R1QeDlKQy21Ki3oSYXNgLb45GV1P6A0M+/s6nyCuNDqe5VpaY84BzXGwVbwFA==",
691 "license": "MIT",
692 "optional": true,
693 "dependencies": {
694 "tslib": "^2.4.0"
695 }
696 },
697 "node_modules/@img/colour": {
698 "version": "1.1.0",
699 "resolved": "https://registry.npmjs.org/@img/colour/-/colour-1.1.0.tgz",
700 "integrity": "sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ==",
701 "license": "MIT",
702 "engines": {
703 "node": ">=18"
704 }
705 },
706 "node_modules/@img/sharp-darwin-arm64": {
707 "version": "0.34.5",
708 "resolved": "https://registry.npmjs.org/@img/sharp-darwin-arm64/-/sharp-darwin-arm64-0.34.5.tgz",
709 "integrity": "sha512-imtQ3WMJXbMY4fxb/Ndp6HBTNVtWCUI0WdobyheGf5+ad6xX8VIDO8u2xE4qc/fr08CKG/7dDseFtn6M6g/r3w==",
710 "cpu": [
711 "arm64"
712 ],
713 "license": "Apache-2.0",
714 "optional": true,
715 "os": [
716 "darwin"
717 ],
718 "engines": {
719 "node": "^18.17.0 || ^20.3.0 || >=21.0.0"
720 },
721 "funding": {
722 "url": "https://opencollective.com/libvips"
723 },
724 "optionalDependencies": {
725 "@img/sharp-libvips-darwin-arm64": "1.2.4"
726 }
727 },
728 "node_modules/@img/sharp-darwin-x64": {
729 "version": "0.34.5",
730 "resolved": "https://registry.npmjs.org/@img/sharp-darwin-x64/-/sharp-darwin-x64-0.34.5.tgz",
731 "integrity": "sha512-YNEFAF/4KQ/PeW0N+r+aVVsoIY0/qxxikF2SWdp+NRkmMB7y9LBZAVqQ4yhGCm/H3H270OSykqmQMKLBhBJDEw==",
732 "cpu": [
733 "x64"
734 ],
735 "license": "Apache-2.0",
736 "optional": true,
737 "os": [
738 "darwin"
739 ],
740 "engines": {
741 "node": "^18.17.0 || ^20.3.0 || >=21.0.0"
742 },
743 "funding": {
744 "url": "https://opencollective.com/libvips"
745 },
746 "optionalDependencies": {
747 "@img/sharp-libvips-darwin-x64": "1.2.4"
748 }
749 },
750 "node_modules/@img/sharp-libvips-darwin-arm64": {
751 "version": "1.2.4",
752 "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-arm64/-/sharp-libvips-darwin-arm64-1.2.4.tgz",
753 "integrity": "sha512-zqjjo7RatFfFoP0MkQ51jfuFZBnVE2pRiaydKJ1G/rHZvnsrHAOcQALIi9sA5co5xenQdTugCvtb1cuf78Vf4g==",
754 "cpu": [
755 "arm64"
756 ],
757 "license": "LGPL-3.0-or-later",
758 "optional": true,
759 "os": [
760 "darwin"
761 ],
762 "funding": {
763 "url": "https://opencollective.com/libvips"
764 }
765 },
766 "node_modules/@img/sharp-libvips-darwin-x64": {
767 "version": "1.2.4",
768 "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-x64/-/sharp-libvips-darwin-x64-1.2.4.tgz",
769 "integrity": "sha512-1IOd5xfVhlGwX+zXv2N93k0yMONvUlANylbJw1eTah8K/Jtpi15KC+WSiaX/nBmbm2HxRM1gZ0nSdjSsrZbGKg==",
770 "cpu": [
771 "x64"
772 ],
773 "license": "LGPL-3.0-or-later",
774 "optional": true,
775 "os": [
776 "darwin"
777 ],
778 "funding": {
779 "url": "https://opencollective.com/libvips"
780 }
781 },
782 "node_modules/@img/sharp-libvips-linux-arm": {
783 "version": "1.2.4",
784 "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm/-/sharp-libvips-linux-arm-1.2.4.tgz",
785 "integrity": "sha512-bFI7xcKFELdiNCVov8e44Ia4u2byA+l3XtsAj+Q8tfCwO6BQ8iDojYdvoPMqsKDkuoOo+X6HZA0s0q11ANMQ8A==",
786 "cpu": [
787 "arm"
788 ],
789 "libc": [
790 "glibc"
791 ],
792 "license": "LGPL-3.0-or-later",
793 "optional": true,
794 "os": [
795 "linux"
796 ],
797 "funding": {
798 "url": "https://opencollective.com/libvips"
799 }
800 },
801 "node_modules/@img/sharp-libvips-linux-arm64": {
802 "version": "1.2.4",
803 "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm64/-/sharp-libvips-linux-arm64-1.2.4.tgz",
804 "integrity": "sha512-excjX8DfsIcJ10x1Kzr4RcWe1edC9PquDRRPx3YVCvQv+U5p7Yin2s32ftzikXojb1PIFc/9Mt28/y+iRklkrw==",
805 "cpu": [
806 "arm64"
807 ],
808 "libc": [
809 "glibc"
810 ],
811 "license": "LGPL-3.0-or-later",
812 "optional": true,
813 "os": [
814 "linux"
815 ],
816 "funding": {
817 "url": "https://opencollective.com/libvips"
818 }
819 },
820 "node_modules/@img/sharp-libvips-linux-ppc64": {
821 "version": "1.2.4",
822 "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-ppc64/-/sharp-libvips-linux-ppc64-1.2.4.tgz",
823 "integrity": "sha512-FMuvGijLDYG6lW+b/UvyilUWu5Ayu+3r2d1S8notiGCIyYU/76eig1UfMmkZ7vwgOrzKzlQbFSuQfgm7GYUPpA==",
824 "cpu": [
825 "ppc64"
826 ],
827 "libc": [
828 "glibc"
829 ],
830 "license": "LGPL-3.0-or-later",
831 "optional": true,
832 "os": [
833 "linux"
834 ],
835 "funding": {
836 "url": "https://opencollective.com/libvips"
837 }
838 },
839 "node_modules/@img/sharp-libvips-linux-riscv64": {
840 "version": "1.2.4",
841 "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-riscv64/-/sharp-libvips-linux-riscv64-1.2.4.tgz",
842 "integrity": "sha512-oVDbcR4zUC0ce82teubSm+x6ETixtKZBh/qbREIOcI3cULzDyb18Sr/Wcyx7NRQeQzOiHTNbZFF1UwPS2scyGA==",
843 "cpu": [
844 "riscv64"
845 ],
846 "libc": [
847 "glibc"
848 ],
849 "license": "LGPL-3.0-or-later",
850 "optional": true,
851 "os": [
852 "linux"
853 ],
854 "funding": {
855 "url": "https://opencollective.com/libvips"
856 }
857 },
858 "node_modules/@img/sharp-libvips-linux-s390x": {
859 "version": "1.2.4",
860 "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-s390x/-/sharp-libvips-linux-s390x-1.2.4.tgz",
861 "integrity": "sha512-qmp9VrzgPgMoGZyPvrQHqk02uyjA0/QrTO26Tqk6l4ZV0MPWIW6LTkqOIov+J1yEu7MbFQaDpwdwJKhbJvuRxQ==",
862 "cpu": [
863 "s390x"
864 ],
865 "libc": [
866 "glibc"
867 ],
868 "license": "LGPL-3.0-or-later",
869 "optional": true,
870 "os": [
871 "linux"
872 ],
873 "funding": {
874 "url": "https://opencollective.com/libvips"
875 }
876 },
877 "node_modules/@img/sharp-libvips-linux-x64": {
878 "version": "1.2.4",
879 "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-x64/-/sharp-libvips-linux-x64-1.2.4.tgz",
880 "integrity": "sha512-tJxiiLsmHc9Ax1bz3oaOYBURTXGIRDODBqhveVHonrHJ9/+k89qbLl0bcJns+e4t4rvaNBxaEZsFtSfAdquPrw==",
881 "cpu": [
882 "x64"
883 ],
884 "libc": [
885 "glibc"
886 ],
887 "license": "LGPL-3.0-or-later",
888 "optional": true,
889 "os": [
890 "linux"
891 ],
892 "funding": {
893 "url": "https://opencollective.com/libvips"
894 }
895 },
896 "node_modules/@img/sharp-libvips-linuxmusl-arm64": {
897 "version": "1.2.4",
898 "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-arm64/-/sharp-libvips-linuxmusl-arm64-1.2.4.tgz",
899 "integrity": "sha512-FVQHuwx1IIuNow9QAbYUzJ+En8KcVm9Lk5+uGUQJHaZmMECZmOlix9HnH7n1TRkXMS0pGxIJokIVB9SuqZGGXw==",
900 "cpu": [
901 "arm64"
902 ],
903 "libc": [
904 "musl"
905 ],
906 "license": "LGPL-3.0-or-later",
907 "optional": true,
908 "os": [
909 "linux"
910 ],
911 "funding": {
912 "url": "https://opencollective.com/libvips"
913 }
914 },
915 "node_modules/@img/sharp-libvips-linuxmusl-x64": {
916 "version": "1.2.4",
917 "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-x64/-/sharp-libvips-linuxmusl-x64-1.2.4.tgz",
918 "integrity": "sha512-+LpyBk7L44ZIXwz/VYfglaX/okxezESc6UxDSoyo2Ks6Jxc4Y7sGjpgU9s4PMgqgjj1gZCylTieNamqA1MF7Dg==",
919 "cpu": [
920 "x64"
921 ],
922 "libc": [
923 "musl"
924 ],
925 "license": "LGPL-3.0-or-later",
926 "optional": true,
927 "os": [
928 "linux"
929 ],
930 "funding": {
931 "url": "https://opencollective.com/libvips"
932 }
933 },
934 "node_modules/@img/sharp-linux-arm": {
935 "version": "0.34.5",
936 "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm/-/sharp-linux-arm-0.34.5.tgz",
937 "integrity": "sha512-9dLqsvwtg1uuXBGZKsxem9595+ujv0sJ6Vi8wcTANSFpwV/GONat5eCkzQo/1O6zRIkh0m/8+5BjrRr7jDUSZw==",
938 "cpu": [
939 "arm"
940 ],
941 "libc": [
942 "glibc"
943 ],
944 "license": "Apache-2.0",
945 "optional": true,
946 "os": [
947 "linux"
948 ],
949 "engines": {
950 "node": "^18.17.0 || ^20.3.0 || >=21.0.0"
951 },
952 "funding": {
953 "url": "https://opencollective.com/libvips"
954 },
955 "optionalDependencies": {
956 "@img/sharp-libvips-linux-arm": "1.2.4"
957 }
958 },
959 "node_modules/@img/sharp-linux-arm64": {
960 "version": "0.34.5",
961 "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm64/-/sharp-linux-arm64-0.34.5.tgz",
962 "integrity": "sha512-bKQzaJRY/bkPOXyKx5EVup7qkaojECG6NLYswgktOZjaXecSAeCWiZwwiFf3/Y+O1HrauiE3FVsGxFg8c24rZg==",
963 "cpu": [
964 "arm64"
965 ],
966 "libc": [
967 "glibc"
968 ],
969 "license": "Apache-2.0",
970 "optional": true,
971 "os": [
972 "linux"
973 ],
974 "engines": {
975 "node": "^18.17.0 || ^20.3.0 || >=21.0.0"
976 },
977 "funding": {
978 "url": "https://opencollective.com/libvips"
979 },
980 "optionalDependencies": {
981 "@img/sharp-libvips-linux-arm64": "1.2.4"
982 }
983 },
984 "node_modules/@img/sharp-linux-ppc64": {
985 "version": "0.34.5",
986 "resolved": "https://registry.npmjs.org/@img/sharp-linux-ppc64/-/sharp-linux-ppc64-0.34.5.tgz",
987 "integrity": "sha512-7zznwNaqW6YtsfrGGDA6BRkISKAAE1Jo0QdpNYXNMHu2+0dTrPflTLNkpc8l7MUP5M16ZJcUvysVWWrMefZquA==",
988 "cpu": [
989 "ppc64"
990 ],
991 "libc": [
992 "glibc"
993 ],
994 "license": "Apache-2.0",
995 "optional": true,
996 "os": [
997 "linux"
998 ],
999 "engines": {
1000 "node": "^18.17.0 || ^20.3.0 || >=21.0.0"
1001 },
1002 "funding": {
1003 "url": "https://opencollective.com/libvips"
1004 },
1005 "optionalDependencies": {
1006 "@img/sharp-libvips-linux-ppc64": "1.2.4"
1007 }
1008 },
1009 "node_modules/@img/sharp-linux-riscv64": {
1010 "version": "0.34.5",
1011 "resolved": "https://registry.npmjs.org/@img/sharp-linux-riscv64/-/sharp-linux-riscv64-0.34.5.tgz",
1012 "integrity": "sha512-51gJuLPTKa7piYPaVs8GmByo7/U7/7TZOq+cnXJIHZKavIRHAP77e3N2HEl3dgiqdD/w0yUfiJnII77PuDDFdw==",
1013 "cpu": [
1014 "riscv64"
1015 ],
1016 "libc": [
1017 "glibc"
1018 ],
1019 "license": "Apache-2.0",
1020 "optional": true,
1021 "os": [
1022 "linux"
1023 ],
1024 "engines": {
1025 "node": "^18.17.0 || ^20.3.0 || >=21.0.0"
1026 },
1027 "funding": {
1028 "url": "https://opencollective.com/libvips"
1029 },
1030 "optionalDependencies": {
1031 "@img/sharp-libvips-linux-riscv64": "1.2.4"
1032 }
1033 },
1034 "node_modules/@img/sharp-linux-s390x": {
1035 "version": "0.34.5",
1036 "resolved": "https://registry.npmjs.org/@img/sharp-linux-s390x/-/sharp-linux-s390x-0.34.5.tgz",
1037 "integrity": "sha512-nQtCk0PdKfho3eC5MrbQoigJ2gd1CgddUMkabUj+rBevs8tZ2cULOx46E7oyX+04WGfABgIwmMC0VqieTiR4jg==",
1038 "cpu": [
1039 "s390x"
1040 ],
1041 "libc": [
1042 "glibc"
1043 ],
1044 "license": "Apache-2.0",
1045 "optional": true,
1046 "os": [
1047 "linux"
1048 ],
1049 "engines": {
1050 "node": "^18.17.0 || ^20.3.0 || >=21.0.0"
1051 },
1052 "funding": {
1053 "url": "https://opencollective.com/libvips"
1054 },
1055 "optionalDependencies": {
1056 "@img/sharp-libvips-linux-s390x": "1.2.4"
1057 }
1058 },
1059 "node_modules/@img/sharp-linux-x64": {
1060 "version": "0.34.5",
1061 "resolved": "https://registry.npmjs.org/@img/sharp-linux-x64/-/sharp-linux-x64-0.34.5.tgz",
1062 "integrity": "sha512-MEzd8HPKxVxVenwAa+JRPwEC7QFjoPWuS5NZnBt6B3pu7EG2Ge0id1oLHZpPJdn3OQK+BQDiw9zStiHBTJQQQQ==",
1063 "cpu": [
1064 "x64"
1065 ],
1066 "libc": [
1067 "glibc"
1068 ],
1069 "license": "Apache-2.0",
1070 "optional": true,
1071 "os": [
1072 "linux"
1073 ],
1074 "engines": {
1075 "node": "^18.17.0 || ^20.3.0 || >=21.0.0"
1076 },
1077 "funding": {
1078 "url": "https://opencollective.com/libvips"
1079 },
1080 "optionalDependencies": {
1081 "@img/sharp-libvips-linux-x64": "1.2.4"
1082 }
1083 },
1084 "node_modules/@img/sharp-linuxmusl-arm64": {
1085 "version": "0.34.5",
1086 "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-arm64/-/sharp-linuxmusl-arm64-0.34.5.tgz",
1087 "integrity": "sha512-fprJR6GtRsMt6Kyfq44IsChVZeGN97gTD331weR1ex1c1rypDEABN6Tm2xa1wE6lYb5DdEnk03NZPqA7Id21yg==",
1088 "cpu": [
1089 "arm64"
1090 ],
1091 "libc": [
1092 "musl"
1093 ],
1094 "license": "Apache-2.0",
1095 "optional": true,
1096 "os": [
1097 "linux"
1098 ],
1099 "engines": {
1100 "node": "^18.17.0 || ^20.3.0 || >=21.0.0"
1101 },
1102 "funding": {
1103 "url": "https://opencollective.com/libvips"
1104 },
1105 "optionalDependencies": {
1106 "@img/sharp-libvips-linuxmusl-arm64": "1.2.4"
1107 }
1108 },
1109 "node_modules/@img/sharp-linuxmusl-x64": {
1110 "version": "0.34.5",
1111 "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-x64/-/sharp-linuxmusl-x64-0.34.5.tgz",
1112 "integrity": "sha512-Jg8wNT1MUzIvhBFxViqrEhWDGzqymo3sV7z7ZsaWbZNDLXRJZoRGrjulp60YYtV4wfY8VIKcWidjojlLcWrd8Q==",
1113 "cpu": [
1114 "x64"
1115 ],
1116 "libc": [
1117 "musl"
1118 ],
1119 "license": "Apache-2.0",
1120 "optional": true,
1121 "os": [
1122 "linux"
1123 ],
1124 "engines": {
1125 "node": "^18.17.0 || ^20.3.0 || >=21.0.0"
1126 },
1127 "funding": {
1128 "url": "https://opencollective.com/libvips"
1129 },
1130 "optionalDependencies": {
1131 "@img/sharp-libvips-linuxmusl-x64": "1.2.4"
1132 }
1133 },
1134 "node_modules/@img/sharp-wasm32": {
1135 "version": "0.34.5",
1136 "resolved": "https://registry.npmjs.org/@img/sharp-wasm32/-/sharp-wasm32-0.34.5.tgz",
1137 "integrity": "sha512-OdWTEiVkY2PHwqkbBI8frFxQQFekHaSSkUIJkwzclWZe64O1X4UlUjqqqLaPbUpMOQk6FBu/HtlGXNblIs0huw==",
1138 "cpu": [
1139 "wasm32"
1140 ],
1141 "license": "Apache-2.0 AND LGPL-3.0-or-later AND MIT",
1142 "optional": true,
1143 "dependencies": {
1144 "@emnapi/runtime": "^1.7.0"
1145 },
1146 "engines": {
1147 "node": "^18.17.0 || ^20.3.0 || >=21.0.0"
1148 },
1149 "funding": {
1150 "url": "https://opencollective.com/libvips"
1151 }
1152 },
1153 "node_modules/@img/sharp-win32-arm64": {
1154 "version": "0.34.5",
1155 "resolved": "https://registry.npmjs.org/@img/sharp-win32-arm64/-/sharp-win32-arm64-0.34.5.tgz",
1156 "integrity": "sha512-WQ3AgWCWYSb2yt+IG8mnC6Jdk9Whs7O0gxphblsLvdhSpSTtmu69ZG1Gkb6NuvxsNACwiPV6cNSZNzt0KPsw7g==",
1157 "cpu": [
1158 "arm64"
1159 ],
1160 "license": "Apache-2.0 AND LGPL-3.0-or-later",
1161 "optional": true,
1162 "os": [
1163 "win32"
1164 ],
1165 "engines": {
1166 "node": "^18.17.0 || ^20.3.0 || >=21.0.0"
1167 },
1168 "funding": {
1169 "url": "https://opencollective.com/libvips"
1170 }
1171 },
1172 "node_modules/@img/sharp-win32-ia32": {
1173 "version": "0.34.5",
1174 "resolved": "https://registry.npmjs.org/@img/sharp-win32-ia32/-/sharp-win32-ia32-0.34.5.tgz",
1175 "integrity": "sha512-FV9m/7NmeCmSHDD5j4+4pNI8Cp3aW+JvLoXcTUo0IqyjSfAZJ8dIUmijx1qaJsIiU+Hosw6xM5KijAWRJCSgNg==",
1176 "cpu": [
1177 "ia32"
1178 ],
1179 "license": "Apache-2.0 AND LGPL-3.0-or-later",
1180 "optional": true,
1181 "os": [
1182 "win32"
1183 ],
1184 "engines": {
1185 "node": "^18.17.0 || ^20.3.0 || >=21.0.0"
1186 },
1187 "funding": {
1188 "url": "https://opencollective.com/libvips"
1189 }
1190 },
1191 "node_modules/@img/sharp-win32-x64": {
1192 "version": "0.34.5",
1193 "resolved": "https://registry.npmjs.org/@img/sharp-win32-x64/-/sharp-win32-x64-0.34.5.tgz",
1194 "integrity": "sha512-+29YMsqY2/9eFEiW93eqWnuLcWcufowXewwSNIT6UwZdUUCrM3oFjMWH/Z6/TMmb4hlFenmfAVbpWeup2jryCw==",
1195 "cpu": [
1196 "x64"
1197 ],
1198 "license": "Apache-2.0 AND LGPL-3.0-or-later",
1199 "optional": true,
1200 "os": [
1201 "win32"
1202 ],
1203 "engines": {
1204 "node": "^18.17.0 || ^20.3.0 || >=21.0.0"
1205 },
1206 "funding": {
1207 "url": "https://opencollective.com/libvips"
1208 }
1209 },
686 "node_modules/@istanbuljs/load-nyc-config": {
1210 "node_modules/@istanbuljs/load-nyc-config": {
687 "version": "1.1.0",
1211 "version": "1.1.0",
688 "resolved": "https://registry.npmjs.org/@istanbuljs/load-nyc-config/-/load-nyc-config-1.1.0.tgz",
1212 "resolved": "https://registry.npmjs.org/@istanbuljs/load-nyc-config/-/load-nyc-config-1.1.0.tgz",
@@ -5822,6 +6346,50 @@
5822 "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==",
6346 "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==",
5823 "license": "ISC"
6347 "license": "ISC"
5824 },
6348 },
6349 "node_modules/sharp": {
6350 "version": "0.34.5",
6351 "resolved": "https://registry.npmjs.org/sharp/-/sharp-0.34.5.tgz",
6352 "integrity": "sha512-Ou9I5Ft9WNcCbXrU9cMgPBcCK8LiwLqcbywW3t4oDV37n1pzpuNLsYiAV8eODnjbtQlSDwZ2cUEeQz4E54Hltg==",
6353 "hasInstallScript": true,
6354 "license": "Apache-2.0",
6355 "dependencies": {
6356 "@img/colour": "^1.0.0",
6357 "detect-libc": "^2.1.2",
6358 "semver": "^7.7.3"
6359 },
6360 "engines": {
6361 "node": "^18.17.0 || ^20.3.0 || >=21.0.0"
6362 },
6363 "funding": {
6364 "url": "https://opencollective.com/libvips"
6365 },
6366 "optionalDependencies": {
6367 "@img/sharp-darwin-arm64": "0.34.5",
6368 "@img/sharp-darwin-x64": "0.34.5",
6369 "@img/sharp-libvips-darwin-arm64": "1.2.4",
6370 "@img/sharp-libvips-darwin-x64": "1.2.4",
6371 "@img/sharp-libvips-linux-arm": "1.2.4",
6372 "@img/sharp-libvips-linux-arm64": "1.2.4",
6373 "@img/sharp-libvips-linux-ppc64": "1.2.4",
6374 "@img/sharp-libvips-linux-riscv64": "1.2.4",
6375 "@img/sharp-libvips-linux-s390x": "1.2.4",
6376 "@img/sharp-libvips-linux-x64": "1.2.4",
6377 "@img/sharp-libvips-linuxmusl-arm64": "1.2.4",
6378 "@img/sharp-libvips-linuxmusl-x64": "1.2.4",
6379 "@img/sharp-linux-arm": "0.34.5",
6380 "@img/sharp-linux-arm64": "0.34.5",
6381 "@img/sharp-linux-ppc64": "0.34.5",
6382 "@img/sharp-linux-riscv64": "0.34.5",
6383 "@img/sharp-linux-s390x": "0.34.5",
6384 "@img/sharp-linux-x64": "0.34.5",
6385 "@img/sharp-linuxmusl-arm64": "0.34.5",
6386 "@img/sharp-linuxmusl-x64": "0.34.5",
6387 "@img/sharp-wasm32": "0.34.5",
6388 "@img/sharp-win32-arm64": "0.34.5",
6389 "@img/sharp-win32-ia32": "0.34.5",
6390 "@img/sharp-win32-x64": "0.34.5"
6391 }
6392 },
5825 "node_modules/shebang-command": {
6393 "node_modules/shebang-command": {
5826 "version": "2.0.0",
6394 "version": "2.0.0",
5827 "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz",
6395 "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz",
@@ -6224,6 +6792,13 @@
6224 "integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==",
6792 "integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==",
6225 "license": "MIT"
6793 "license": "MIT"
6226 },
6794 },
6795 "node_modules/tslib": {
6796 "version": "2.8.1",
6797 "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",
6798 "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",
6799 "license": "0BSD",
6800 "optional": true
6801 },
6227 "node_modules/type-detect": {
6802 "node_modules/type-detect": {
6228 "version": "4.0.8",
6803 "version": "4.0.8",
6229 "resolved": "https://registry.npmjs.org/type-detect/-/type-detect-4.0.8.tgz",
6804 "resolved": "https://registry.npmjs.org/type-detect/-/type-detect-4.0.8.tgz",
package.json +1 −0
@@ -15,6 +15,7 @@
15 15 "jsonwebtoken": "^9.0.2",
16 16 "multer": "^1.4.5-lts.1",
17 17 "node-sqlite3-wasm": "^0.8.10",
18 "sharp": "^0.34.5",
18 19 "uuid": "^9.0.0"
19 20 },
20 21 "jest": {
@@ -15,6 +15,7 @@
15 "jsonwebtoken": "^9.0.2",
15 "jsonwebtoken": "^9.0.2",
16 "multer": "^1.4.5-lts.1",
16 "multer": "^1.4.5-lts.1",
17 "node-sqlite3-wasm": "^0.8.10",
17 "node-sqlite3-wasm": "^0.8.10",
18 "sharp": "^0.34.5",
18 "uuid": "^9.0.0"
19 "uuid": "^9.0.0"
19 },
20 },
20 "jest": {
21 "jest": {
public/app.js +69 −79
@@ -43,6 +43,7 @@ const STATE = {
43 43 uploadInProgress: false,
44 44 // Blob URLs for thumbnail previews — revoked on each grid rebuild
45 45 thumbnailUrls: [],
46 thumbnailObserver: null,
46 47
47 48 // Preview overlay state
48 49 previewObjectUrl: null,
@@ -58,6 +59,7 @@ const CLIENT_BINDING_KEY = 'filemanager.client-binding-id.v1';
58 59 const MOBILE_BREAKPOINT_QUERY = '(max-width: 600px)';
59 60 const MOBILE_LONG_PRESS_MS = 420;
60 61 const MOBILE_LONG_PRESS_MOVE_THRESHOLD = 10;
62 const THUMB_OBSERVER_ROOT_MARGIN = '120px';
61 63
62 64 // ───────────────────────────────────────────────────────────────────────────
63 65 // CRYPTO HELPERS (Web Crypto API)
@@ -850,6 +852,10 @@ async function incrementalRefreshCurrentDir ()
850 852 }
851 853 }
852 854 }
855 else
856 {
857 loadThumbnails();
858 }
853 859
854 860 await refreshFolderStats();
855 861 }
@@ -879,6 +885,7 @@ function stopAutoRefresh ()
879 885
880 886 function renderFileGrid ()
881 887 {
888 disconnectThumbnailObserver();
882 889 revokeThumbnails();
883 890 const grid = document.getElementById('file-grid');
884 891 grid.innerHTML = '';
@@ -2536,21 +2543,24 @@ function revokeThumbnails ()
2536 2543 STATE.thumbnailUrls = [];
2537 2544 }
2538 2545
2546 function disconnectThumbnailObserver ()
2547 {
2548 if (!STATE.thumbnailObserver) return;
2549 STATE.thumbnailObserver.disconnect();
2550 STATE.thumbnailObserver = null;
2551 }
2552
2539 2553 function getThumbnailKind (name)
2540 2554 {
2541 2555 const ext = extOf(name || '');
2542 2556 if (IMAGE_EXTS.has(ext)) return 'image';
2543 if (VIDEO_EXTS.has(ext)) return 'video';
2544 2557 if (CODE_EXTS.has(ext)) return 'text';
2545 if (AUDIO_EXTS.has(ext)) return 'audio';
2546 if (ext === 'pdf') return 'pdf';
2547 2558 return 'badge';
2548 2559 }
2549 2560
2550 2561 function maxThumbBytesForKind (kind)
2551 2562 {
2552 2563 if (kind === 'image') return 15 * 1024 * 1024;
2553 if (kind === 'video') return 25 * 1024 * 1024;
2554 2564 if (kind === 'text') return 1024 * 1024;
2555 2565 return 0;
2556 2566 }
@@ -2627,9 +2637,7 @@ function badgeThumbnailDataUrl (name, kind)
2627 2637 if (!ctx) return null;
2628 2638
2629 2639 const ext = (extOf(name || '') || 'file').toUpperCase().slice(0, 5);
2630 const color = kind === 'audio' ? '#c084fc'
2631 : kind === 'pdf' ? '#f97316'
2632 : '#5b7fff';
2640 const color = '#5b7fff';
2633 2641
2634 2642 ctx.fillStyle = '#111826';
2635 2643 ctx.fillRect(0, 0, 160, 200);
@@ -2649,74 +2657,38 @@ function badgeThumbnailDataUrl (name, kind)
2649 2657 return canvas.toDataURL('image/png');
2650 2658 }
2651 2659
2652 async function videoThumbnailDataUrl (blob)
2660 async function buildThumbnailSource (item, blob, kind)
2653 2661 {
2654 const src = URL.createObjectURL(blob);
2655 try
2656 {
2657 const video = document.createElement('video');
2658 video.src = src;
2659 video.muted = true;
2660 video.preload = 'metadata';
2661
2662 await new Promise((resolve, reject) =>
2663 {
2664 const fail = () => reject(new Error('video load failed'));
2665 video.addEventListener('error', fail, { once: true });
2666 video.addEventListener('loadeddata', resolve, { once: true });
2667 });
2662 if (kind === 'text') return textThumbnailDataUrl(await blob.text());
2663 return badgeThumbnailDataUrl(item.name, kind);
2664 }
2668 2665
2669 const targetTime = Number.isFinite(video.duration) && video.duration > 1 ? 1 : 0;
2670 await new Promise((resolve) =>
2671 {
2672 video.currentTime = targetTime;
2673 video.addEventListener('seeked', resolve, { once: true });
2674 });
2666 function observeThumbnailIcon (iconEl)
2667 {
2668 if (!iconEl || !iconEl.isConnected) return;
2669 if (iconEl.dataset.thumbReady === '1') return;
2675 2670
2676 const canvas = document.createElement('canvas');
2677 canvas.width = 160;
2678 canvas.height = 200;
2679 const ctx = canvas.getContext('2d');
2680 if (!ctx) return null;
2681
2682 ctx.fillStyle = '#0d111a';
2683 ctx.fillRect(0, 0, canvas.width, canvas.height);
2684 const rw = video.videoWidth || 1;
2685 const rh = video.videoHeight || 1;
2686 const scale = Math.max(canvas.width / rw, canvas.height / rh);
2687 const dw = rw * scale;
2688 const dh = rh * scale;
2689 ctx.drawImage(video, (canvas.width - dw) / 2, (canvas.height - dh) / 2, dw, dh);
2690
2691 // subtle play badge
2692 ctx.fillStyle = 'rgba(0,0,0,0.45)';
2693 ctx.beginPath();
2694 ctx.arc(80, 100, 18, 0, Math.PI * 2);
2695 ctx.fill();
2696 ctx.fillStyle = '#ffffff';
2697 ctx.beginPath();
2698 ctx.moveTo(75, 90);
2699 ctx.lineTo(75, 110);
2700 ctx.lineTo(90, 100);
2701 ctx.closePath();
2702 ctx.fill();
2703
2704 return canvas.toDataURL('image/png');
2705 } catch
2671 if (!('IntersectionObserver' in window))
2706 2672 {
2707 return null;
2708 } finally
2673 void loadOneThumbnail(iconEl);
2674 return;
2675 }
2676
2677 if (!STATE.thumbnailObserver)
2709 2678 {
2710 URL.revokeObjectURL(src);
2679 STATE.thumbnailObserver = new IntersectionObserver((entries) =>
2680 {
2681 for (const entry of entries)
2682 {
2683 if (!entry.isIntersecting) continue;
2684 const icon = entry.target;
2685 STATE.thumbnailObserver.unobserve(icon);
2686 void loadOneThumbnail(icon);
2687 }
2688 }, { root: null, rootMargin: THUMB_OBSERVER_ROOT_MARGIN, threshold: 0.01 });
2711 2689 }
2712 }
2713 2690
2714 async function buildThumbnailSource (item, blob, kind)
2715 {
2716 if (kind === 'image') return URL.createObjectURL(blob);
2717 if (kind === 'video') return await videoThumbnailDataUrl(blob);
2718 if (kind === 'text') return textThumbnailDataUrl(await blob.text());
2719 return badgeThumbnailDataUrl(item.name, kind);
2691 STATE.thumbnailObserver.observe(iconEl);
2720 2692 }
2721 2693
2722 2694 async function loadThumbnails ()
@@ -2724,16 +2696,10 @@ async function loadThumbnails ()
2724 2696 const icons = Array.from(document.querySelectorAll('.icon[data-preview-path]'));
2725 2697 if (!icons.length) return;
2726 2698
2727 const queue = [...icons];
2728 async function worker ()
2699 for (const icon of icons)
2729 2700 {
2730 while (queue.length)
2731 {
2732 await loadOneThumbnail(queue.shift());
2733 }
2701 observeThumbnailIcon(icon);
2734 2702 }
2735 // Four concurrent fetches — keeps the Pi's network from flooding
2736 await Promise.all(Array.from({ length: Math.min(4, icons.length) }, worker));
2737 2703 }
2738 2704
2739 2705 async function loadOneThumbnail (iconEl)
@@ -2747,10 +2713,35 @@ async function loadOneThumbnail (iconEl)
2747 2713 const kind = getThumbnailKind(item.name);
2748 2714 let srcUrl = null;
2749 2715
2750 if (kind === 'badge' || kind === 'audio' || kind === 'pdf')
2716 if (kind === 'badge')
2751 2717 {
2752 2718 srcUrl = badgeThumbnailDataUrl(item.name, kind);
2753 } else
2719 }
2720 else if (kind === 'image')
2721 {
2722 const url = `/api/files/thumbnail?file=${encodeURIComponent(filePath)}`;
2723
2724 let res;
2725 try
2726 {
2727 res = await fetch(url, {
2728 headers: {
2729 Authorization: `Bearer ${STATE.token}`,
2730 'X-Fp': getFingerprint(),
2731 },
2732 });
2733 } catch
2734 {
2735 return;
2736 }
2737
2738 if (!res.ok || !iconEl.isConnected) return;
2739
2740 const blob = await res.blob();
2741 srcUrl = URL.createObjectURL(blob);
2742 STATE.thumbnailUrls.push(srcUrl);
2743 }
2744 else
2754 2745 {
2755 2746 const maxBytes = maxThumbBytesForKind(kind);
2756 2747 if (maxBytes > 0 && typeof item.size === 'number' && item.size > maxBytes)
@@ -2774,7 +2765,6 @@ async function loadOneThumbnail (iconEl)
2774 2765
2775 2766 const blob = await res.blob();
2776 2767 srcUrl = await buildThumbnailSource(item, blob, kind);
2777 if (kind === 'image' && srcUrl) STATE.thumbnailUrls.push(srcUrl);
2778 2768 }
2779 2769 }
2780 2770 if (!srcUrl || !iconEl.isConnected) return;
@@ -43,6 +43,7 @@ const STATE = {
43 uploadInProgress: false,
43 uploadInProgress: false,
44 // Blob URLs for thumbnail previews — revoked on each grid rebuild
44 // Blob URLs for thumbnail previews — revoked on each grid rebuild
45 thumbnailUrls: [],
45 thumbnailUrls: [],
46 thumbnailObserver: null,
46
47
47 // Preview overlay state
48 // Preview overlay state
48 previewObjectUrl: null,
49 previewObjectUrl: null,
@@ -58,6 +59,7 @@ const CLIENT_BINDING_KEY = 'filemanager.client-binding-id.v1';
58const MOBILE_BREAKPOINT_QUERY = '(max-width: 600px)';
59const MOBILE_BREAKPOINT_QUERY = '(max-width: 600px)';
59const MOBILE_LONG_PRESS_MS = 420;
60const MOBILE_LONG_PRESS_MS = 420;
60const MOBILE_LONG_PRESS_MOVE_THRESHOLD = 10;
61const MOBILE_LONG_PRESS_MOVE_THRESHOLD = 10;
62const THUMB_OBSERVER_ROOT_MARGIN = '120px';
61
63
62// ───────────────────────────────────────────────────────────────────────────
64// ───────────────────────────────────────────────────────────────────────────
63// CRYPTO HELPERS (Web Crypto API)
65// CRYPTO HELPERS (Web Crypto API)
@@ -850,6 +852,10 @@ async function incrementalRefreshCurrentDir ()
850 }
852 }
851 }
853 }
852 }
854 }
855 else
856 {
857 loadThumbnails();
858 }
853
859
854 await refreshFolderStats();
860 await refreshFolderStats();
855}
861}
@@ -879,6 +885,7 @@ function stopAutoRefresh ()
879
885
880function renderFileGrid ()
886function renderFileGrid ()
881{
887{
888 disconnectThumbnailObserver();
882 revokeThumbnails();
889 revokeThumbnails();
883 const grid = document.getElementById('file-grid');
890 const grid = document.getElementById('file-grid');
884 grid.innerHTML = '';
891 grid.innerHTML = '';
@@ -2536,21 +2543,24 @@ function revokeThumbnails ()
2536 STATE.thumbnailUrls = [];
2543 STATE.thumbnailUrls = [];
2537}
2544}
2538
2545
2546function disconnectThumbnailObserver ()
2547{
2548 if (!STATE.thumbnailObserver) return;
2549 STATE.thumbnailObserver.disconnect();
2550 STATE.thumbnailObserver = null;
2551}
2552
2539function getThumbnailKind (name)
2553function getThumbnailKind (name)
2540{
2554{
2541 const ext = extOf(name || '');
2555 const ext = extOf(name || '');
2542 if (IMAGE_EXTS.has(ext)) return 'image';
2556 if (IMAGE_EXTS.has(ext)) return 'image';
2543 if (VIDEO_EXTS.has(ext)) return 'video';
2544 if (CODE_EXTS.has(ext)) return 'text';
2557 if (CODE_EXTS.has(ext)) return 'text';
2545 if (AUDIO_EXTS.has(ext)) return 'audio';
2546 if (ext === 'pdf') return 'pdf';
2547 return 'badge';
2558 return 'badge';
2548}
2559}
2549
2560
2550function maxThumbBytesForKind (kind)
2561function maxThumbBytesForKind (kind)
2551{
2562{
2552 if (kind === 'image') return 15 * 1024 * 1024;
2563 if (kind === 'image') return 15 * 1024 * 1024;
2553 if (kind === 'video') return 25 * 1024 * 1024;
2554 if (kind === 'text') return 1024 * 1024;
2564 if (kind === 'text') return 1024 * 1024;
2555 return 0;
2565 return 0;
2556}
2566}
@@ -2627,9 +2637,7 @@ function badgeThumbnailDataUrl (name, kind)
2627 if (!ctx) return null;
2637 if (!ctx) return null;
2628
2638
2629 const ext = (extOf(name || '') || 'file').toUpperCase().slice(0, 5);
2639 const ext = (extOf(name || '') || 'file').toUpperCase().slice(0, 5);
2630 const color = kind === 'audio' ? '#c084fc'
2640 const color = '#5b7fff';
2631 : kind === 'pdf' ? '#f97316'
2632 : '#5b7fff';
2633
2641
2634 ctx.fillStyle = '#111826';
2642 ctx.fillStyle = '#111826';
2635 ctx.fillRect(0, 0, 160, 200);
2643 ctx.fillRect(0, 0, 160, 200);
@@ -2649,74 +2657,38 @@ function badgeThumbnailDataUrl (name, kind)
2649 return canvas.toDataURL('image/png');
2657 return canvas.toDataURL('image/png');
2650}
2658}
2651
2659
2652async function videoThumbnailDataUrl (blob)
2660async function buildThumbnailSource (item, blob, kind)
2653{
2661{
2654 const src = URL.createObjectURL(blob);
2662 if (kind === 'text') return textThumbnailDataUrl(await blob.text());
2655 try
2663 return badgeThumbnailDataUrl(item.name, kind);
2656 {
2664}
2657 const video = document.createElement('video');
2658 video.src = src;
2659 video.muted = true;
2660 video.preload = 'metadata';
2661
2662 await new Promise((resolve, reject) =>
2663 {
2664 const fail = () => reject(new Error('video load failed'));
2665 video.addEventListener('error', fail, { once: true });
2666 video.addEventListener('loadeddata', resolve, { once: true });
2667 });
2668
2665
2669 const targetTime = Number.isFinite(video.duration) && video.duration > 1 ? 1 : 0;
2666function observeThumbnailIcon (iconEl)
2670 await new Promise((resolve) =>
2667{
2671 {
2668 if (!iconEl || !iconEl.isConnected) return;
2672 video.currentTime = targetTime;
2669 if (iconEl.dataset.thumbReady === '1') return;
2673 video.addEventListener('seeked', resolve, { once: true });
2674 });
2675
2670
2676 const canvas = document.createElement('canvas');
2671 if (!('IntersectionObserver' in window))
2677 canvas.width = 160;
2678 canvas.height = 200;
2679 const ctx = canvas.getContext('2d');
2680 if (!ctx) return null;
2681
2682 ctx.fillStyle = '#0d111a';
2683 ctx.fillRect(0, 0, canvas.width, canvas.height);
2684 const rw = video.videoWidth || 1;
2685 const rh = video.videoHeight || 1;
2686 const scale = Math.max(canvas.width / rw, canvas.height / rh);
2687 const dw = rw * scale;
2688 const dh = rh * scale;
2689 ctx.drawImage(video, (canvas.width - dw) / 2, (canvas.height - dh) / 2, dw, dh);
2690
2691 // subtle play badge
2692 ctx.fillStyle = 'rgba(0,0,0,0.45)';
2693 ctx.beginPath();
2694 ctx.arc(80, 100, 18, 0, Math.PI * 2);
2695 ctx.fill();
2696 ctx.fillStyle = '#ffffff';
2697 ctx.beginPath();
2698 ctx.moveTo(75, 90);
2699 ctx.lineTo(75, 110);
2700 ctx.lineTo(90, 100);
2701 ctx.closePath();
2702 ctx.fill();
2703
2704 return canvas.toDataURL('image/png');
2705 } catch
2706 {
2672 {
2707 return null;
2673 void loadOneThumbnail(iconEl);
2708 } finally
2674 return;
2675 }
2676
2677 if (!STATE.thumbnailObserver)
2709 {
2678 {
2710 URL.revokeObjectURL(src);
2679 STATE.thumbnailObserver = new IntersectionObserver((entries) =>
2680 {
2681 for (const entry of entries)
2682 {
2683 if (!entry.isIntersecting) continue;
2684 const icon = entry.target;
2685 STATE.thumbnailObserver.unobserve(icon);
2686 void loadOneThumbnail(icon);
2687 }
2688 }, { root: null, rootMargin: THUMB_OBSERVER_ROOT_MARGIN, threshold: 0.01 });
2711 }
2689 }
2712}
2713
2690
2714async function buildThumbnailSource (item, blob, kind)
2691 STATE.thumbnailObserver.observe(iconEl);
2715{
2716 if (kind === 'image') return URL.createObjectURL(blob);
2717 if (kind === 'video') return await videoThumbnailDataUrl(blob);
2718 if (kind === 'text') return textThumbnailDataUrl(await blob.text());
2719 return badgeThumbnailDataUrl(item.name, kind);
2720}
2692}
2721
2693
2722async function loadThumbnails ()
2694async function loadThumbnails ()
@@ -2724,16 +2696,10 @@ async function loadThumbnails ()
2724 const icons = Array.from(document.querySelectorAll('.icon[data-preview-path]'));
2696 const icons = Array.from(document.querySelectorAll('.icon[data-preview-path]'));
2725 if (!icons.length) return;
2697 if (!icons.length) return;
2726
2698
2727 const queue = [...icons];
2699 for (const icon of icons)
2728 async function worker ()
2729 {
2700 {
2730 while (queue.length)
2701 observeThumbnailIcon(icon);
2731 {
2732 await loadOneThumbnail(queue.shift());
2733 }
2734 }
2702 }
2735 // Four concurrent fetches — keeps the Pi's network from flooding
2736 await Promise.all(Array.from({ length: Math.min(4, icons.length) }, worker));
2737}
2703}
2738
2704
2739async function loadOneThumbnail (iconEl)
2705async function loadOneThumbnail (iconEl)
@@ -2747,10 +2713,35 @@ async function loadOneThumbnail (iconEl)
2747 const kind = getThumbnailKind(item.name);
2713 const kind = getThumbnailKind(item.name);
2748 let srcUrl = null;
2714 let srcUrl = null;
2749
2715
2750 if (kind === 'badge' || kind === 'audio' || kind === 'pdf')
2716 if (kind === 'badge')
2751 {
2717 {
2752 srcUrl = badgeThumbnailDataUrl(item.name, kind);
2718 srcUrl = badgeThumbnailDataUrl(item.name, kind);
2753 } else
2719 }
2720 else if (kind === 'image')
2721 {
2722 const url = `/api/files/thumbnail?file=${encodeURIComponent(filePath)}`;
2723
2724 let res;
2725 try
2726 {
2727 res = await fetch(url, {
2728 headers: {
2729 Authorization: `Bearer ${STATE.token}`,
2730 'X-Fp': getFingerprint(),
2731 },
2732 });
2733 } catch
2734 {
2735 return;
2736 }
2737
2738 if (!res.ok || !iconEl.isConnected) return;
2739
2740 const blob = await res.blob();
2741 srcUrl = URL.createObjectURL(blob);
2742 STATE.thumbnailUrls.push(srcUrl);
2743 }
2744 else
2754 {
2745 {
2755 const maxBytes = maxThumbBytesForKind(kind);
2746 const maxBytes = maxThumbBytesForKind(kind);
2756 if (maxBytes > 0 && typeof item.size === 'number' && item.size > maxBytes)
2747 if (maxBytes > 0 && typeof item.size === 'number' && item.size > maxBytes)
@@ -2774,7 +2765,6 @@ async function loadOneThumbnail (iconEl)
2774
2765
2775 const blob = await res.blob();
2766 const blob = await res.blob();
2776 srcUrl = await buildThumbnailSource(item, blob, kind);
2767 srcUrl = await buildThumbnailSource(item, blob, kind);
2777 if (kind === 'image' && srcUrl) STATE.thumbnailUrls.push(srcUrl);
2778 }
2768 }
2779 }
2769 }
2780 if (!srcUrl || !iconEl.isConnected) return;
2770 if (!srcUrl || !iconEl.isConnected) return;
server/index.js +5 −0
@@ -8,6 +8,7 @@ const https = require('https');
8 8 const { initDb, closeDb } = require('./db');
9 9 const { ensureServerKeys } = require('./crypto');
10 10 const { loadConfig } = require('./config');
11 const { startThumbnailCacheLoop, stopThumbnailCacheLoop } = require('./thumbnail-cache');
11 12 const authRoutes = require('./routes/auth');
12 13 const filesRoutes = require('./routes/files');
13 14 const adminRoutes = require('./routes/admin');
@@ -35,6 +36,8 @@ function shutdown (opts = {}, ...servers)
35 36 if (active.length === 0 || active[0].__isShuttingDown) return;
36 37 active.forEach(s => { s.__isShuttingDown = true; });
37 38
39 stopThumbnailCacheLoop();
40
38 41 // Close DB first so file locks are released as early as possible.
39 42 closeDb();
40 43
@@ -92,6 +95,8 @@ function start ()
92 95 const shutdownAll = () => shutdown({}, httpServer, httpsServer);
93 96 const shutdownForRestart = () => shutdown({ exitCode: 1 }, httpServer, httpsServer);
94 97
98 startThumbnailCacheLoop();
99
95 100 // Give the admin route access to the server handle for graceful shutdown.
96 101 app.set('server', httpServer);
97 102 app.set('shutdown', shutdownAll);
@@ -8,6 +8,7 @@ const https = require('https');
8const { initDb, closeDb } = require('./db');
8const { initDb, closeDb } = require('./db');
9const { ensureServerKeys } = require('./crypto');
9const { ensureServerKeys } = require('./crypto');
10const { loadConfig } = require('./config');
10const { loadConfig } = require('./config');
11const { startThumbnailCacheLoop, stopThumbnailCacheLoop } = require('./thumbnail-cache');
11const authRoutes = require('./routes/auth');
12const authRoutes = require('./routes/auth');
12const filesRoutes = require('./routes/files');
13const filesRoutes = require('./routes/files');
13const adminRoutes = require('./routes/admin');
14const adminRoutes = require('./routes/admin');
@@ -35,6 +36,8 @@ function shutdown (opts = {}, ...servers)
35 if (active.length === 0 || active[0].__isShuttingDown) return;
36 if (active.length === 0 || active[0].__isShuttingDown) return;
36 active.forEach(s => { s.__isShuttingDown = true; });
37 active.forEach(s => { s.__isShuttingDown = true; });
37
38
39 stopThumbnailCacheLoop();
40
38 // Close DB first so file locks are released as early as possible.
41 // Close DB first so file locks are released as early as possible.
39 closeDb();
42 closeDb();
40
43
@@ -92,6 +95,8 @@ function start ()
92 const shutdownAll = () => shutdown({}, httpServer, httpsServer);
95 const shutdownAll = () => shutdown({}, httpServer, httpsServer);
93 const shutdownForRestart = () => shutdown({ exitCode: 1 }, httpServer, httpsServer);
96 const shutdownForRestart = () => shutdown({ exitCode: 1 }, httpServer, httpsServer);
94
97
98 startThumbnailCacheLoop();
99
95 // Give the admin route access to the server handle for graceful shutdown.
100 // Give the admin route access to the server handle for graceful shutdown.
96 app.set('server', httpServer);
101 app.set('server', httpServer);
97 app.set('shutdown', shutdownAll);
102 app.set('shutdown', shutdownAll);
server/routes/files.js +33 −0
@@ -9,6 +9,7 @@ const router = express.Router();
9 9 const { getDb } = require('../db');
10 10 const { loadConfig, saveConfig, getEffectivePaths, getAllowedRoot } = require('../config');
11 11 const { requireAuth } = require('../auth');
12 const { getCachedThumbnailInfo } = require('../thumbnail-cache');
12 13
13 14 // ---------------------------------------------------------------------------
14 15 // Multer storage — files are written directly to the target directory
@@ -400,6 +401,38 @@ router.get('/download', requireAuth, (req, res) =>
400 401 res.download(file, path.basename(file));
401 402 });
402 403
404 // ---------------------------------------------------------------------------
405 // GET /api/files/thumbnail?file=<absolute-path>
406 // Returns a pre-generated cached thumbnail if present.
407 // ---------------------------------------------------------------------------
408 router.get('/thumbnail', requireAuth, async (req, res) =>
409 {
410 const file = req.query.file;
411 if (!file) return res.status(400).json({ error: 'file is required.' });
412
413 const roots = effectivePaths();
414 const info = resolveRoot(file, roots);
415 if (!info || !canRead(req.user, info.label))
416 {
417 return res.status(403).json({ error: 'Access denied.' });
418 }
419
420 if (!fs.existsSync(file) || fs.statSync(file).isDirectory())
421 {
422 return res.status(404).json({ error: 'File not found.' });
423 }
424
425 const thumb = await getCachedThumbnailInfo(file);
426 if (!thumb)
427 {
428 return res.status(404).json({ error: 'Thumbnail not ready.' });
429 }
430
431 res.type(thumb.contentType);
432 res.set('Cache-Control', 'private, max-age=10');
433 res.sendFile(thumb.thumbPath);
434 });
435
403 436 // ---------------------------------------------------------------------------
404 437 // POST /api/files/upload?dir=<absolute-path>
405 438 // Accepts multipart file upload.
@@ -9,6 +9,7 @@ const router = express.Router();
9const { getDb } = require('../db');
9const { getDb } = require('../db');
10const { loadConfig, saveConfig, getEffectivePaths, getAllowedRoot } = require('../config');
10const { loadConfig, saveConfig, getEffectivePaths, getAllowedRoot } = require('../config');
11const { requireAuth } = require('../auth');
11const { requireAuth } = require('../auth');
12const { getCachedThumbnailInfo } = require('../thumbnail-cache');
12
13
13// ---------------------------------------------------------------------------
14// ---------------------------------------------------------------------------
14// Multer storage — files are written directly to the target directory
15// Multer storage — files are written directly to the target directory
@@ -400,6 +401,38 @@ router.get('/download', requireAuth, (req, res) =>
400 res.download(file, path.basename(file));
401 res.download(file, path.basename(file));
401});
402});
402
403
404// ---------------------------------------------------------------------------
405// GET /api/files/thumbnail?file=<absolute-path>
406// Returns a pre-generated cached thumbnail if present.
407// ---------------------------------------------------------------------------
408router.get('/thumbnail', requireAuth, async (req, res) =>
409{
410 const file = req.query.file;
411 if (!file) return res.status(400).json({ error: 'file is required.' });
412
413 const roots = effectivePaths();
414 const info = resolveRoot(file, roots);
415 if (!info || !canRead(req.user, info.label))
416 {
417 return res.status(403).json({ error: 'Access denied.' });
418 }
419
420 if (!fs.existsSync(file) || fs.statSync(file).isDirectory())
421 {
422 return res.status(404).json({ error: 'File not found.' });
423 }
424
425 const thumb = await getCachedThumbnailInfo(file);
426 if (!thumb)
427 {
428 return res.status(404).json({ error: 'Thumbnail not ready.' });
429 }
430
431 res.type(thumb.contentType);
432 res.set('Cache-Control', 'private, max-age=10');
433 res.sendFile(thumb.thumbPath);
434});
435
403// ---------------------------------------------------------------------------
436// ---------------------------------------------------------------------------
404// POST /api/files/upload?dir=<absolute-path>
437// POST /api/files/upload?dir=<absolute-path>
405// Accepts multipart file upload.
438// Accepts multipart file upload.
server/thumbnail-cache.js added +366 −0
@@ -0,0 +1,366 @@
1 'use strict';
2
3 const fs = require('fs');
4 const path = require('path');
5 const crypto = require('crypto');
6 const sharp = require('sharp');
7
8 const { loadConfig, getEffectivePaths } = require('./config');
9
10 const PUBLIC_DIR = path.resolve(process.env.FILEMANAGER_PUBLIC_DIR || path.join(__dirname, '../public'));
11 const THUMBS_DIR = path.resolve(process.env.FILEMANAGER_THUMBS_DIR || path.join(PUBLIC_DIR, 'thumbs'));
12 const MANIFEST_PATH = path.join(THUMBS_DIR, '.manifest.json');
13 const LOOP_DELAY_MS = 5000;
14
15 const IMAGE_EXTS = new Set([
16 'jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp', 'tif', 'tiff', 'avif',
17 ]);
18
19 let loopTimer = null;
20 let loopStarted = false;
21
22 function toPosix (p)
23 {
24 return String(p || '').split(path.sep).join('/');
25 }
26
27 function rootSegmentsForSourcePath (sourcePath)
28 {
29 const resolved = path.resolve(sourcePath);
30 const stripped = resolved
31 .replace(/^\\+/, '')
32 .replace(/^\/+/, '')
33 .replace(/^([A-Za-z]):/, '$1');
34
35 return stripped
36 .split(/[\\/]+/)
37 .filter(Boolean)
38 .map(seg => seg.replace(/:/g, '_'));
39 }
40
41 function getThumbDirForSourceDir (sourceDir)
42 {
43 return path.join(THUMBS_DIR, ...rootSegmentsForSourcePath(sourceDir));
44 }
45
46 function getThumbPathForSourceFile (sourceFile)
47 {
48 const source = path.resolve(sourceFile);
49 return path.join(THUMBS_DIR, ...rootSegmentsForSourcePath(source)) + '.webp';
50 }
51
52 function getThumbRelPathForSourceFile (sourceFile)
53 {
54 return toPosix(path.relative(PUBLIC_DIR, getThumbPathForSourceFile(sourceFile)));
55 }
56
57 function isImagePath (filePath)
58 {
59 const ext = path.extname(filePath).slice(1).toLowerCase();
60 return IMAGE_EXTS.has(ext);
61 }
62
63 async function exists (target)
64 {
65 try
66 {
67 await fs.promises.access(target, fs.constants.F_OK);
68 return true;
69 } catch
70 {
71 return false;
72 }
73 }
74
75 async function ensureDir (dirPath)
76 {
77 await fs.promises.mkdir(dirPath, { recursive: true });
78 }
79
80 async function readManifest ()
81 {
82 try
83 {
84 const raw = await fs.promises.readFile(MANIFEST_PATH, 'utf8');
85 const parsed = JSON.parse(raw);
86 if (parsed && typeof parsed === 'object' && parsed.files && typeof parsed.files === 'object')
87 {
88 return parsed;
89 }
90 } catch
91 {
92 // Missing or malformed manifests are treated as empty.
93 }
94 return { version: 1, files: {} };
95 }
96
97 async function writeManifest (manifest)
98 {
99 const payload = JSON.stringify(manifest, null, 2);
100 const tmp = MANIFEST_PATH + '.tmp';
101 await fs.promises.writeFile(tmp, payload, 'utf8');
102 await fs.promises.rename(tmp, MANIFEST_PATH);
103 }
104
105 function sha256File (target)
106 {
107 return new Promise((resolve, reject) =>
108 {
109 const hash = crypto.createHash('sha256');
110 const stream = fs.createReadStream(target);
111 stream.on('error', reject);
112 stream.on('data', chunk => hash.update(chunk));
113 stream.on('end', () => resolve(hash.digest('hex')));
114 });
115 }
116
117 async function walkDir (dirPath, onDir, onFile)
118 {
119 await onDir(dirPath);
120
121 let entries = [];
122 try
123 {
124 entries = await fs.promises.readdir(dirPath, { withFileTypes: true });
125 } catch
126 {
127 return;
128 }
129
130 for (const entry of entries)
131 {
132 const full = path.join(dirPath, entry.name);
133 if (entry.isDirectory())
134 {
135 await walkDir(full, onDir, onFile);
136 continue;
137 }
138 if (entry.isFile())
139 {
140 await onFile(full);
141 }
142 }
143 }
144
145 async function removeFileIfExists (target)
146 {
147 try
148 {
149 await fs.promises.unlink(target);
150 } catch (err)
151 {
152 if (err && err.code !== 'ENOENT') throw err;
153 }
154 }
155
156 async function pruneThumbTree (dirPath, keepFiles)
157 {
158 let entries = [];
159 try
160 {
161 entries = await fs.promises.readdir(dirPath, { withFileTypes: true });
162 } catch
163 {
164 return;
165 }
166
167 for (const entry of entries)
168 {
169 const full = path.join(dirPath, entry.name);
170 if (entry.isDirectory())
171 {
172 await pruneThumbTree(full, keepFiles);
173 continue;
174 }
175
176 if (full === MANIFEST_PATH || full === MANIFEST_PATH + '.tmp') continue;
177 if (!keepFiles.has(path.resolve(full)))
178 {
179 await removeFileIfExists(full);
180 }
181 }
182
183 // Never remove the root thumbs directory.
184 if (path.resolve(dirPath) === path.resolve(THUMBS_DIR)) return;
185
186 try
187 {
188 const leftovers = await fs.promises.readdir(dirPath);
189 if (leftovers.length === 0) await fs.promises.rmdir(dirPath);
190 } catch
191 {
192 // Ignore races while pruning.
193 }
194 }
195
196 async function generateImageThumb (sourceFile, thumbPath)
197 {
198 await ensureDir(path.dirname(thumbPath));
199 await sharp(sourceFile)
200 .rotate()
201 .resize({ width: 99, height: 99, fit: 'inside', withoutEnlargement: true })
202 .webp({ quality: 80 })
203 .toFile(thumbPath);
204 }
205
206 function effectiveRoots ()
207 {
208 return getEffectivePaths(loadConfig().paths || []);
209 }
210
211 async function syncThumbnailCacheOnce ()
212 {
213 await ensureDir(THUMBS_DIR);
214
215 const prevManifest = await readManifest();
216 const nextManifest = { version: 1, files: {} };
217 const keepThumbFiles = new Set();
218 const roots = effectiveRoots();
219
220 for (const root of roots)
221 {
222 const resolvedRoot = path.resolve(root);
223 if (!(await exists(resolvedRoot))) continue;
224
225 await walkDir(
226 resolvedRoot,
227 async (dirPath) =>
228 {
229 await ensureDir(getThumbDirForSourceDir(dirPath));
230 },
231 async (filePath) =>
232 {
233 if (!isImagePath(filePath)) return;
234
235 let stat;
236 try
237 {
238 stat = await fs.promises.stat(filePath);
239 } catch
240 {
241 return;
242 }
243
244 const thumbPath = getThumbPathForSourceFile(filePath);
245 const thumbRelPath = getThumbRelPathForSourceFile(filePath);
246 keepThumbFiles.add(path.resolve(thumbPath));
247
248 const prev = prevManifest.files[filePath];
249 const unchangedByStat =
250 prev &&
251 Number(prev.size) === Number(stat.size) &&
252 Number(prev.mtimeMs) === Number(stat.mtimeMs) &&
253 prev.thumbRelPath === thumbRelPath;
254
255 if (unchangedByStat && await exists(thumbPath))
256 {
257 nextManifest.files[filePath] = prev;
258 return;
259 }
260
261 let sha256;
262 try
263 {
264 sha256 = await sha256File(filePath);
265 } catch
266 {
267 return;
268 }
269
270 const unchangedByHash = prev && prev.sha256 === sha256 && await exists(thumbPath);
271 if (!unchangedByHash)
272 {
273 try
274 {
275 await generateImageThumb(filePath, thumbPath);
276 } catch
277 {
278 return;
279 }
280 }
281
282 nextManifest.files[filePath] = {
283 sha256,
284 size: stat.size,
285 mtimeMs: stat.mtimeMs,
286 thumbRelPath,
287 };
288 },
289 );
290 }
291
292 for (const [sourcePath, oldMeta] of Object.entries(prevManifest.files || {}))
293 {
294 if (nextManifest.files[sourcePath]) continue;
295 const oldThumbRel = oldMeta && oldMeta.thumbRelPath;
296 if (!oldThumbRel) continue;
297 const oldThumbPath = path.resolve(path.join(PUBLIC_DIR, oldThumbRel));
298 await removeFileIfExists(oldThumbPath);
299 }
300
301 await pruneThumbTree(THUMBS_DIR, keepThumbFiles);
302 await writeManifest(nextManifest);
303
304 return {
305 rootsScanned: roots.length,
306 cachedCount: Object.keys(nextManifest.files).length,
307 };
308 }
309
310 function scheduleNextRun (delayMs)
311 {
312 loopTimer = setTimeout(async () =>
313 {
314 loopTimer = null;
315 try
316 {
317 await syncThumbnailCacheOnce();
318 }
319 catch (err)
320 {
321 console.error('[thumb-cache] sync failed:', err && err.message ? err.message : err);
322 }
323 finally
324 {
325 if (loopStarted) scheduleNextRun(LOOP_DELAY_MS);
326 }
327 }, delayMs);
328
329 if (loopTimer && typeof loopTimer.unref === 'function') loopTimer.unref();
330 }
331
332 function startThumbnailCacheLoop ()
333 {
334 if (loopStarted) return;
335 loopStarted = true;
336 scheduleNextRun(LOOP_DELAY_MS);
337 }
338
339 function stopThumbnailCacheLoop ()
340 {
341 loopStarted = false;
342 if (loopTimer)
343 {
344 clearTimeout(loopTimer);
345 loopTimer = null;
346 }
347 }
348
349 async function getCachedThumbnailInfo (sourceFile)
350 {
351 const thumbPath = getThumbPathForSourceFile(sourceFile);
352 if (!(await exists(thumbPath))) return null;
353 return {
354 thumbPath,
355 contentType: 'image/webp',
356 };
357 }
358
359 module.exports = {
360 getCachedThumbnailInfo,
361 getThumbPathForSourceFile,
362 getThumbRelPathForSourceFile,
363 startThumbnailCacheLoop,
364 stopThumbnailCacheLoop,
365 syncThumbnailCacheOnce,
366 };
@@ -0,0 +1,366 @@
1'use strict';
2
3const fs = require('fs');
4const path = require('path');
5const crypto = require('crypto');
6const sharp = require('sharp');
7
8const { loadConfig, getEffectivePaths } = require('./config');
9
10const PUBLIC_DIR = path.resolve(process.env.FILEMANAGER_PUBLIC_DIR || path.join(__dirname, '../public'));
11const THUMBS_DIR = path.resolve(process.env.FILEMANAGER_THUMBS_DIR || path.join(PUBLIC_DIR, 'thumbs'));
12const MANIFEST_PATH = path.join(THUMBS_DIR, '.manifest.json');
13const LOOP_DELAY_MS = 5000;
14
15const IMAGE_EXTS = new Set([
16 'jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp', 'tif', 'tiff', 'avif',
17]);
18
19let loopTimer = null;
20let loopStarted = false;
21
22function toPosix (p)
23{
24 return String(p || '').split(path.sep).join('/');
25}
26
27function rootSegmentsForSourcePath (sourcePath)
28{
29 const resolved = path.resolve(sourcePath);
30 const stripped = resolved
31 .replace(/^\\+/, '')
32 .replace(/^\/+/, '')
33 .replace(/^([A-Za-z]):/, '$1');
34
35 return stripped
36 .split(/[\\/]+/)
37 .filter(Boolean)
38 .map(seg => seg.replace(/:/g, '_'));
39}
40
41function getThumbDirForSourceDir (sourceDir)
42{
43 return path.join(THUMBS_DIR, ...rootSegmentsForSourcePath(sourceDir));
44}
45
46function getThumbPathForSourceFile (sourceFile)
47{
48 const source = path.resolve(sourceFile);
49 return path.join(THUMBS_DIR, ...rootSegmentsForSourcePath(source)) + '.webp';
50}
51
52function getThumbRelPathForSourceFile (sourceFile)
53{
54 return toPosix(path.relative(PUBLIC_DIR, getThumbPathForSourceFile(sourceFile)));
55}
56
57function isImagePath (filePath)
58{
59 const ext = path.extname(filePath).slice(1).toLowerCase();
60 return IMAGE_EXTS.has(ext);
61}
62
63async function exists (target)
64{
65 try
66 {
67 await fs.promises.access(target, fs.constants.F_OK);
68 return true;
69 } catch
70 {
71 return false;
72 }
73}
74
75async function ensureDir (dirPath)
76{
77 await fs.promises.mkdir(dirPath, { recursive: true });
78}
79
80async function readManifest ()
81{
82 try
83 {
84 const raw = await fs.promises.readFile(MANIFEST_PATH, 'utf8');
85 const parsed = JSON.parse(raw);
86 if (parsed && typeof parsed === 'object' && parsed.files && typeof parsed.files === 'object')
87 {
88 return parsed;
89 }
90 } catch
91 {
92 // Missing or malformed manifests are treated as empty.
93 }
94 return { version: 1, files: {} };
95}
96
97async function writeManifest (manifest)
98{
99 const payload = JSON.stringify(manifest, null, 2);
100 const tmp = MANIFEST_PATH + '.tmp';
101 await fs.promises.writeFile(tmp, payload, 'utf8');
102 await fs.promises.rename(tmp, MANIFEST_PATH);
103}
104
105function sha256File (target)
106{
107 return new Promise((resolve, reject) =>
108 {
109 const hash = crypto.createHash('sha256');
110 const stream = fs.createReadStream(target);
111 stream.on('error', reject);
112 stream.on('data', chunk => hash.update(chunk));
113 stream.on('end', () => resolve(hash.digest('hex')));
114 });
115}
116
117async function walkDir (dirPath, onDir, onFile)
118{
119 await onDir(dirPath);
120
121 let entries = [];
122 try
123 {
124 entries = await fs.promises.readdir(dirPath, { withFileTypes: true });
125 } catch
126 {
127 return;
128 }
129
130 for (const entry of entries)
131 {
132 const full = path.join(dirPath, entry.name);
133 if (entry.isDirectory())
134 {
135 await walkDir(full, onDir, onFile);
136 continue;
137 }
138 if (entry.isFile())
139 {
140 await onFile(full);
141 }
142 }
143}
144
145async function removeFileIfExists (target)
146{
147 try
148 {
149 await fs.promises.unlink(target);
150 } catch (err)
151 {
152 if (err && err.code !== 'ENOENT') throw err;
153 }
154}
155
156async function pruneThumbTree (dirPath, keepFiles)
157{
158 let entries = [];
159 try
160 {
161 entries = await fs.promises.readdir(dirPath, { withFileTypes: true });
162 } catch
163 {
164 return;
165 }
166
167 for (const entry of entries)
168 {
169 const full = path.join(dirPath, entry.name);
170 if (entry.isDirectory())
171 {
172 await pruneThumbTree(full, keepFiles);
173 continue;
174 }
175
176 if (full === MANIFEST_PATH || full === MANIFEST_PATH + '.tmp') continue;
177 if (!keepFiles.has(path.resolve(full)))
178 {
179 await removeFileIfExists(full);
180 }
181 }
182
183 // Never remove the root thumbs directory.
184 if (path.resolve(dirPath) === path.resolve(THUMBS_DIR)) return;
185
186 try
187 {
188 const leftovers = await fs.promises.readdir(dirPath);
189 if (leftovers.length === 0) await fs.promises.rmdir(dirPath);
190 } catch
191 {
192 // Ignore races while pruning.
193 }
194}
195
196async function generateImageThumb (sourceFile, thumbPath)
197{
198 await ensureDir(path.dirname(thumbPath));
199 await sharp(sourceFile)
200 .rotate()
201 .resize({ width: 99, height: 99, fit: 'inside', withoutEnlargement: true })
202 .webp({ quality: 80 })
203 .toFile(thumbPath);
204}
205
206function effectiveRoots ()
207{
208 return getEffectivePaths(loadConfig().paths || []);
209}
210
211async function syncThumbnailCacheOnce ()
212{
213 await ensureDir(THUMBS_DIR);
214
215 const prevManifest = await readManifest();
216 const nextManifest = { version: 1, files: {} };
217 const keepThumbFiles = new Set();
218 const roots = effectiveRoots();
219
220 for (const root of roots)
221 {
222 const resolvedRoot = path.resolve(root);
223 if (!(await exists(resolvedRoot))) continue;
224
225 await walkDir(
226 resolvedRoot,
227 async (dirPath) =>
228 {
229 await ensureDir(getThumbDirForSourceDir(dirPath));
230 },
231 async (filePath) =>
232 {
233 if (!isImagePath(filePath)) return;
234
235 let stat;
236 try
237 {
238 stat = await fs.promises.stat(filePath);
239 } catch
240 {
241 return;
242 }
243
244 const thumbPath = getThumbPathForSourceFile(filePath);
245 const thumbRelPath = getThumbRelPathForSourceFile(filePath);
246 keepThumbFiles.add(path.resolve(thumbPath));
247
248 const prev = prevManifest.files[filePath];
249 const unchangedByStat =
250 prev &&
251 Number(prev.size) === Number(stat.size) &&
252 Number(prev.mtimeMs) === Number(stat.mtimeMs) &&
253 prev.thumbRelPath === thumbRelPath;
254
255 if (unchangedByStat && await exists(thumbPath))
256 {
257 nextManifest.files[filePath] = prev;
258 return;
259 }
260
261 let sha256;
262 try
263 {
264 sha256 = await sha256File(filePath);
265 } catch
266 {
267 return;
268 }
269
270 const unchangedByHash = prev && prev.sha256 === sha256 && await exists(thumbPath);
271 if (!unchangedByHash)
272 {
273 try
274 {
275 await generateImageThumb(filePath, thumbPath);
276 } catch
277 {
278 return;
279 }
280 }
281
282 nextManifest.files[filePath] = {
283 sha256,
284 size: stat.size,
285 mtimeMs: stat.mtimeMs,
286 thumbRelPath,
287 };
288 },
289 );
290 }
291
292 for (const [sourcePath, oldMeta] of Object.entries(prevManifest.files || {}))
293 {
294 if (nextManifest.files[sourcePath]) continue;
295 const oldThumbRel = oldMeta && oldMeta.thumbRelPath;
296 if (!oldThumbRel) continue;
297 const oldThumbPath = path.resolve(path.join(PUBLIC_DIR, oldThumbRel));
298 await removeFileIfExists(oldThumbPath);
299 }
300
301 await pruneThumbTree(THUMBS_DIR, keepThumbFiles);
302 await writeManifest(nextManifest);
303
304 return {
305 rootsScanned: roots.length,
306 cachedCount: Object.keys(nextManifest.files).length,
307 };
308}
309
310function scheduleNextRun (delayMs)
311{
312 loopTimer = setTimeout(async () =>
313 {
314 loopTimer = null;
315 try
316 {
317 await syncThumbnailCacheOnce();
318 }
319 catch (err)
320 {
321 console.error('[thumb-cache] sync failed:', err && err.message ? err.message : err);
322 }
323 finally
324 {
325 if (loopStarted) scheduleNextRun(LOOP_DELAY_MS);
326 }
327 }, delayMs);
328
329 if (loopTimer && typeof loopTimer.unref === 'function') loopTimer.unref();
330}
331
332function startThumbnailCacheLoop ()
333{
334 if (loopStarted) return;
335 loopStarted = true;
336 scheduleNextRun(LOOP_DELAY_MS);
337}
338
339function stopThumbnailCacheLoop ()
340{
341 loopStarted = false;
342 if (loopTimer)
343 {
344 clearTimeout(loopTimer);
345 loopTimer = null;
346 }
347}
348
349async function getCachedThumbnailInfo (sourceFile)
350{
351 const thumbPath = getThumbPathForSourceFile(sourceFile);
352 if (!(await exists(thumbPath))) return null;
353 return {
354 thumbPath,
355 contentType: 'image/webp',
356 };
357}
358
359module.exports = {
360 getCachedThumbnailInfo,
361 getThumbPathForSourceFile,
362 getThumbRelPathForSourceFile,
363 startThumbnailCacheLoop,
364 stopThumbnailCacheLoop,
365 syncThumbnailCacheOnce,
366};
tests/files.routes.test.js +56 −0
@@ -10,6 +10,7 @@ const { once } = require('events');
10 10 let mockPaths = [];
11 11 let mockRootAliases = {};
12 12 let mockUser = { username: 'admin', isAdmin: true, permissions: {} };
13 let mockThumbPath = null;
13 14
14 15 jest.mock('../server/db', () =>
15 16 {
@@ -57,6 +58,14 @@ jest.mock('../server/auth', () => ({
57 58 requireAuth: (req, res, next) => { req.user = mockUser; next(); },
58 59 }));
59 60
61 jest.mock('../server/thumbnail-cache', () => ({
62 getCachedThumbnailInfo: async () =>
63 {
64 if (!mockThumbPath) return null;
65 return { thumbPath: mockThumbPath, contentType: 'image/webp' };
66 },
67 }));
68
60 69 const filesRoutes = require('../server/routes/files');
61 70 const { getDb } = require('../server/db');
62 71
@@ -95,6 +104,7 @@ beforeEach(() =>
95 104 fs.mkdirSync(rootDir, { recursive: true });
96 105 mockRootAliases = {};
97 106 mockUser = { username: 'admin', isAdmin: true, permissions: {} };
107 mockThumbPath = null;
98 108 const db = getDb();
99 109 db.prepare('DELETE FROM file_meta').run([]);
100 110 });
@@ -122,6 +132,25 @@ function req (method, routePath, body)
122 132 });
123 133 }
124 134
135 function reqRaw (method, routePath)
136 {
137 return new Promise((resolve, reject) =>
138 {
139 const request = http.request(baseUrl + routePath, { method }, res =>
140 {
141 const chunks = [];
142 res.on('data', chunk => chunks.push(Buffer.from(chunk)));
143 res.on('end', () => resolve({
144 status: res.statusCode,
145 headers: res.headers,
146 body: Buffer.concat(chunks),
147 }));
148 });
149 request.on('error', reject);
150 request.end();
151 });
152 }
153
125 154 describe('POST /api/files/move', () =>
126 155 {
127 156 test('moves a file into another folder and rewrites metadata', async () =>
@@ -236,3 +265,30 @@ describe('root alias endpoints', () =>
236 265 expect(status).toBe(400);
237 266 });
238 267 });
268
269 describe('GET /api/files/thumbnail', () =>
270 {
271 test('returns 404 while cached thumbnail is not ready', async () =>
272 {
273 const source = path.join(rootDir, 'photo.jpg');
274 fs.writeFileSync(source, 'not-an-image');
275
276 const { status, body } = await req('GET', `/api/files/thumbnail?file=${encodeURIComponent(source)}`);
277 expect(status).toBe(404);
278 expect(body.error).toMatch(/not ready/i);
279 });
280
281 test('serves cached thumbnail file when available', async () =>
282 {
283 const source = path.join(rootDir, 'photo.jpg');
284 const thumb = path.join(rootDir, 'photo-thumb.webp');
285 fs.writeFileSync(source, 'not-an-image');
286 fs.writeFileSync(thumb, 'webp-bytes');
287 mockThumbPath = thumb;
288
289 const response = await reqRaw('GET', `/api/files/thumbnail?file=${encodeURIComponent(source)}`);
290 expect(response.status).toBe(200);
291 expect(String(response.headers['content-type'] || '')).toContain('image/webp');
292 expect(response.body.toString('utf8')).toBe('webp-bytes');
293 });
294 });
@@ -10,6 +10,7 @@ const { once } = require('events');
10let mockPaths = [];
10let mockPaths = [];
11let mockRootAliases = {};
11let mockRootAliases = {};
12let mockUser = { username: 'admin', isAdmin: true, permissions: {} };
12let mockUser = { username: 'admin', isAdmin: true, permissions: {} };
13let mockThumbPath = null;
13
14
14jest.mock('../server/db', () =>
15jest.mock('../server/db', () =>
15{
16{
@@ -57,6 +58,14 @@ jest.mock('../server/auth', () => ({
57 requireAuth: (req, res, next) => { req.user = mockUser; next(); },
58 requireAuth: (req, res, next) => { req.user = mockUser; next(); },
58}));
59}));
59
60
61jest.mock('../server/thumbnail-cache', () => ({
62 getCachedThumbnailInfo: async () =>
63 {
64 if (!mockThumbPath) return null;
65 return { thumbPath: mockThumbPath, contentType: 'image/webp' };
66 },
67}));
68
60const filesRoutes = require('../server/routes/files');
69const filesRoutes = require('../server/routes/files');
61const { getDb } = require('../server/db');
70const { getDb } = require('../server/db');
62
71
@@ -95,6 +104,7 @@ beforeEach(() =>
95 fs.mkdirSync(rootDir, { recursive: true });
104 fs.mkdirSync(rootDir, { recursive: true });
96 mockRootAliases = {};
105 mockRootAliases = {};
97 mockUser = { username: 'admin', isAdmin: true, permissions: {} };
106 mockUser = { username: 'admin', isAdmin: true, permissions: {} };
107 mockThumbPath = null;
98 const db = getDb();
108 const db = getDb();
99 db.prepare('DELETE FROM file_meta').run([]);
109 db.prepare('DELETE FROM file_meta').run([]);
100});
110});
@@ -122,6 +132,25 @@ function req (method, routePath, body)
122 });
132 });
123}
133}
124
134
135function reqRaw (method, routePath)
136{
137 return new Promise((resolve, reject) =>
138 {
139 const request = http.request(baseUrl + routePath, { method }, res =>
140 {
141 const chunks = [];
142 res.on('data', chunk => chunks.push(Buffer.from(chunk)));
143 res.on('end', () => resolve({
144 status: res.statusCode,
145 headers: res.headers,
146 body: Buffer.concat(chunks),
147 }));
148 });
149 request.on('error', reject);
150 request.end();
151 });
152}
153
125describe('POST /api/files/move', () =>
154describe('POST /api/files/move', () =>
126{
155{
127 test('moves a file into another folder and rewrites metadata', async () =>
156 test('moves a file into another folder and rewrites metadata', async () =>
@@ -236,3 +265,30 @@ describe('root alias endpoints', () =>
236 expect(status).toBe(400);
265 expect(status).toBe(400);
237 });
266 });
238});
267});
268
269describe('GET /api/files/thumbnail', () =>
270{
271 test('returns 404 while cached thumbnail is not ready', async () =>
272 {
273 const source = path.join(rootDir, 'photo.jpg');
274 fs.writeFileSync(source, 'not-an-image');
275
276 const { status, body } = await req('GET', `/api/files/thumbnail?file=${encodeURIComponent(source)}`);
277 expect(status).toBe(404);
278 expect(body.error).toMatch(/not ready/i);
279 });
280
281 test('serves cached thumbnail file when available', async () =>
282 {
283 const source = path.join(rootDir, 'photo.jpg');
284 const thumb = path.join(rootDir, 'photo-thumb.webp');
285 fs.writeFileSync(source, 'not-an-image');
286 fs.writeFileSync(thumb, 'webp-bytes');
287 mockThumbPath = thumb;
288
289 const response = await reqRaw('GET', `/api/files/thumbnail?file=${encodeURIComponent(source)}`);
290 expect(response.status).toBe(200);
291 expect(String(response.headers['content-type'] || '')).toContain('image/webp');
292 expect(response.body.toString('utf8')).toBe('webp-bytes');
293 });
294});
tests/thumbnail-cache.test.js added +99 −0
@@ -0,0 +1,99 @@
1 'use strict';
2
3 const fs = require('fs');
4 const os = require('os');
5 const path = require('path');
6 const sharp = require('sharp');
7
8 let mockPaths = [];
9
10 jest.mock('../server/config', () => ({
11 loadConfig: () => ({ paths: [...mockPaths] }),
12 getEffectivePaths: (paths) => paths,
13 }));
14
15 async function writeTinyPng (target)
16 {
17 await sharp({
18 create: {
19 width: 400,
20 height: 240,
21 channels: 3,
22 background: { r: 120, g: 180, b: 220 },
23 },
24 }).png().toFile(target);
25 }
26
27 describe('thumbnail cache worker', () =>
28 {
29 let tempDir;
30 let publicDir;
31 let thumbsDir;
32 let sourceRoot;
33
34 function loadModule ()
35 {
36 jest.resetModules();
37 return require('../server/thumbnail-cache');
38 }
39
40 beforeEach(() =>
41 {
42 tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'filemanager-thumb-cache-'));
43 publicDir = path.join(tempDir, 'public');
44 thumbsDir = path.join(publicDir, 'thumbs');
45 sourceRoot = path.join(tempDir, 'root');
46
47 fs.mkdirSync(publicDir, { recursive: true });
48 fs.mkdirSync(sourceRoot, { recursive: true });
49
50 process.env.FILEMANAGER_PUBLIC_DIR = publicDir;
51 process.env.FILEMANAGER_THUMBS_DIR = thumbsDir;
52 mockPaths = [sourceRoot];
53 });
54
55 afterEach(() =>
56 {
57 delete process.env.FILEMANAGER_PUBLIC_DIR;
58 delete process.env.FILEMANAGER_THUMBS_DIR;
59 mockPaths = [];
60 fs.rmSync(tempDir, { recursive: true, force: true });
61 });
62
63 test('creates cached thumbnail with dimensions smaller than 100px', async () =>
64 {
65 const mod = loadModule();
66 const imagePath = path.join(sourceRoot, 'photos', 'sample.png');
67 fs.mkdirSync(path.dirname(imagePath), { recursive: true });
68 await writeTinyPng(imagePath);
69
70 await mod.syncThumbnailCacheOnce();
71
72 const thumbPath = mod.getThumbPathForSourceFile(imagePath);
73 expect(fs.existsSync(thumbPath)).toBe(true);
74
75 const meta = await sharp(thumbPath).metadata();
76 expect(meta.width).toBeLessThan(100);
77 expect(meta.height).toBeLessThan(100);
78
79 const manifestPath = path.join(thumbsDir, '.manifest.json');
80 const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));
81 expect(manifest.files[imagePath]).toBeTruthy();
82 });
83
84 test('removes cached thumbnail when source file is deleted', async () =>
85 {
86 const mod = loadModule();
87 const imagePath = path.join(sourceRoot, 'sample.png');
88 await writeTinyPng(imagePath);
89
90 await mod.syncThumbnailCacheOnce();
91 const thumbPath = mod.getThumbPathForSourceFile(imagePath);
92 expect(fs.existsSync(thumbPath)).toBe(true);
93
94 fs.unlinkSync(imagePath);
95 await mod.syncThumbnailCacheOnce();
96
97 expect(fs.existsSync(thumbPath)).toBe(false);
98 });
99 });
@@ -0,0 +1,99 @@
1'use strict';
2
3const fs = require('fs');
4const os = require('os');
5const path = require('path');
6const sharp = require('sharp');
7
8let mockPaths = [];
9
10jest.mock('../server/config', () => ({
11 loadConfig: () => ({ paths: [...mockPaths] }),
12 getEffectivePaths: (paths) => paths,
13}));
14
15async function writeTinyPng (target)
16{
17 await sharp({
18 create: {
19 width: 400,
20 height: 240,
21 channels: 3,
22 background: { r: 120, g: 180, b: 220 },
23 },
24 }).png().toFile(target);
25}
26
27describe('thumbnail cache worker', () =>
28{
29 let tempDir;
30 let publicDir;
31 let thumbsDir;
32 let sourceRoot;
33
34 function loadModule ()
35 {
36 jest.resetModules();
37 return require('../server/thumbnail-cache');
38 }
39
40 beforeEach(() =>
41 {
42 tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'filemanager-thumb-cache-'));
43 publicDir = path.join(tempDir, 'public');
44 thumbsDir = path.join(publicDir, 'thumbs');
45 sourceRoot = path.join(tempDir, 'root');
46
47 fs.mkdirSync(publicDir, { recursive: true });
48 fs.mkdirSync(sourceRoot, { recursive: true });
49
50 process.env.FILEMANAGER_PUBLIC_DIR = publicDir;
51 process.env.FILEMANAGER_THUMBS_DIR = thumbsDir;
52 mockPaths = [sourceRoot];
53 });
54
55 afterEach(() =>
56 {
57 delete process.env.FILEMANAGER_PUBLIC_DIR;
58 delete process.env.FILEMANAGER_THUMBS_DIR;
59 mockPaths = [];
60 fs.rmSync(tempDir, { recursive: true, force: true });
61 });
62
63 test('creates cached thumbnail with dimensions smaller than 100px', async () =>
64 {
65 const mod = loadModule();
66 const imagePath = path.join(sourceRoot, 'photos', 'sample.png');
67 fs.mkdirSync(path.dirname(imagePath), { recursive: true });
68 await writeTinyPng(imagePath);
69
70 await mod.syncThumbnailCacheOnce();
71
72 const thumbPath = mod.getThumbPathForSourceFile(imagePath);
73 expect(fs.existsSync(thumbPath)).toBe(true);
74
75 const meta = await sharp(thumbPath).metadata();
76 expect(meta.width).toBeLessThan(100);
77 expect(meta.height).toBeLessThan(100);
78
79 const manifestPath = path.join(thumbsDir, '.manifest.json');
80 const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));
81 expect(manifest.files[imagePath]).toBeTruthy();
82 });
83
84 test('removes cached thumbnail when source file is deleted', async () =>
85 {
86 const mod = loadModule();
87 const imagePath = path.join(sourceRoot, 'sample.png');
88 await writeTinyPng(imagePath);
89
90 await mod.syncThumbnailCacheOnce();
91 const thumbPath = mod.getThumbPathForSourceFile(imagePath);
92 expect(fs.existsSync(thumbPath)).toBe(true);
93
94 fs.unlinkSync(imagePath);
95 await mod.syncThumbnailCacheOnce();
96
97 expect(fs.existsSync(thumbPath)).toBe(false);
98 });
99});