diff --git a/.gitignore b/.gitignore
index aee5d5a..557302f 100644
--- a/.gitignore
+++ b/.gitignore
@@ -4,3 +4,7 @@ data/
node_modules/
out/
.thumbnails/
+medialore.db
+medialore.db-shm
+medialore.db-wal
+tsconfig.tsbuildinfo
\ No newline at end of file
diff --git a/next.config.ts b/next.config.ts
index e4f5738..b6992cb 100644
--- a/next.config.ts
+++ b/next.config.ts
@@ -1,5 +1,7 @@
import type { NextConfig } from 'next'
-const nextConfig: NextConfig = {}
+const nextConfig: NextConfig = {
+ serverExternalPackages: ['better-sqlite3', 'sharp'],
+}
export default nextConfig
diff --git a/package-lock.json b/package-lock.json
index 1eb28a4..1a77f10 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -9,6 +9,8 @@
"version": "1.0.0",
"license": "ISC",
"dependencies": {
+ "@types/better-sqlite3": "^7.6.13",
+ "better-sqlite3": "^12.8.0",
"next": "^15.5.14",
"react": "^19.2.4",
"react-dom": "^19.2.4",
@@ -1631,6 +1633,15 @@
"tslib": "^2.4.0"
}
},
+ "node_modules/@types/better-sqlite3": {
+ "version": "7.6.13",
+ "resolved": "https://registry.npmjs.org/@types/better-sqlite3/-/better-sqlite3-7.6.13.tgz",
+ "integrity": "sha512-NMv9ASNARoKksWtsq/SHakpYAYnhBrQgGD8zkLYk/jaK8jUGn08CfEdTRgYhMypUQAfzSP8W6gNLe0q19/t4VA==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/node": "*"
+ }
+ },
"node_modules/@types/estree": {
"version": "1.0.8",
"resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.8.tgz",
@@ -1656,7 +1667,6 @@
"version": "25.5.0",
"resolved": "https://registry.npmjs.org/@types/node/-/node-25.5.0.tgz",
"integrity": "sha512-jp2P3tQMSxWugkCUKLRPVUpGaL5MVFwF8RDuSRztfwgN1wmqJeMSbKlnEtQqU8UrhTmzEmZdu2I6v2dpp7XIxw==",
- "dev": true,
"license": "MIT",
"dependencies": {
"undici-types": "~7.18.0"
@@ -2550,6 +2560,26 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/base64-js": {
+ "version": "1.5.1",
+ "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz",
+ "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/feross"
+ },
+ {
+ "type": "patreon",
+ "url": "https://www.patreon.com/feross"
+ },
+ {
+ "type": "consulting",
+ "url": "https://feross.org/support"
+ }
+ ],
+ "license": "MIT"
+ },
"node_modules/baseline-browser-mapping": {
"version": "2.10.10",
"resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.10.10.tgz",
@@ -2563,6 +2593,40 @@
"node": ">=6.0.0"
}
},
+ "node_modules/better-sqlite3": {
+ "version": "12.8.0",
+ "resolved": "https://registry.npmjs.org/better-sqlite3/-/better-sqlite3-12.8.0.tgz",
+ "integrity": "sha512-RxD2Vd96sQDjQr20kdP+F+dK/1OUNiVOl200vKBZY8u0vTwysfolF6Hq+3ZK2+h8My9YvZhHsF+RSGZW2VYrPQ==",
+ "hasInstallScript": true,
+ "license": "MIT",
+ "dependencies": {
+ "bindings": "^1.5.0",
+ "prebuild-install": "^7.1.1"
+ },
+ "engines": {
+ "node": "20.x || 22.x || 23.x || 24.x || 25.x"
+ }
+ },
+ "node_modules/bindings": {
+ "version": "1.5.0",
+ "resolved": "https://registry.npmjs.org/bindings/-/bindings-1.5.0.tgz",
+ "integrity": "sha512-p2q/t/mhvuOj/UeLlV6566GD/guowlr0hHxClI0W9m7MWYkL1F0hLo+0Aexs9HSPCtR1SXQ0TD3MMKrXZajbiQ==",
+ "license": "MIT",
+ "dependencies": {
+ "file-uri-to-path": "1.0.0"
+ }
+ },
+ "node_modules/bl": {
+ "version": "4.1.0",
+ "resolved": "https://registry.npmjs.org/bl/-/bl-4.1.0.tgz",
+ "integrity": "sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w==",
+ "license": "MIT",
+ "dependencies": {
+ "buffer": "^5.5.0",
+ "inherits": "^2.0.4",
+ "readable-stream": "^3.4.0"
+ }
+ },
"node_modules/brace-expansion": {
"version": "1.1.12",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.12.tgz",
@@ -2621,6 +2685,30 @@
"node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7"
}
},
+ "node_modules/buffer": {
+ "version": "5.7.1",
+ "resolved": "https://registry.npmjs.org/buffer/-/buffer-5.7.1.tgz",
+ "integrity": "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/feross"
+ },
+ {
+ "type": "patreon",
+ "url": "https://www.patreon.com/feross"
+ },
+ {
+ "type": "consulting",
+ "url": "https://feross.org/support"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "base64-js": "^1.3.1",
+ "ieee754": "^1.1.13"
+ }
+ },
"node_modules/call-bind": {
"version": "1.0.8",
"resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.8.tgz",
@@ -2718,6 +2806,12 @@
"url": "https://github.com/chalk/chalk?sponsor=1"
}
},
+ "node_modules/chownr": {
+ "version": "1.1.4",
+ "resolved": "https://registry.npmjs.org/chownr/-/chownr-1.1.4.tgz",
+ "integrity": "sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg==",
+ "license": "ISC"
+ },
"node_modules/client-only": {
"version": "0.0.1",
"resolved": "https://registry.npmjs.org/client-only/-/client-only-0.0.1.tgz",
@@ -2859,6 +2953,30 @@
}
}
},
+ "node_modules/decompress-response": {
+ "version": "6.0.0",
+ "resolved": "https://registry.npmjs.org/decompress-response/-/decompress-response-6.0.0.tgz",
+ "integrity": "sha512-aW35yZM6Bb/4oJlZncMH2LCoZtJXTRxES17vE3hoRiowU2kWHaJKFkSBDnDR+cm9J+9QhXmREyIfv0pji9ejCQ==",
+ "license": "MIT",
+ "dependencies": {
+ "mimic-response": "^3.1.0"
+ },
+ "engines": {
+ "node": ">=10"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/deep-extend": {
+ "version": "0.6.0",
+ "resolved": "https://registry.npmjs.org/deep-extend/-/deep-extend-0.6.0.tgz",
+ "integrity": "sha512-LOHxIOaPYdHlJRtCQfDIVZtfw/ufM8+rVj649RIHzcm/vGwQRXFt6OPqIFWsm2XEMrNIEtWR64sY1LEKD2vAOA==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=4.0.0"
+ }
+ },
"node_modules/deep-is": {
"version": "0.1.4",
"resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.4.tgz",
@@ -2953,6 +3071,15 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/end-of-stream": {
+ "version": "1.4.5",
+ "resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.5.tgz",
+ "integrity": "sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg==",
+ "license": "MIT",
+ "dependencies": {
+ "once": "^1.4.0"
+ }
+ },
"node_modules/enhanced-resolve": {
"version": "5.20.1",
"resolved": "https://registry.npmjs.org/enhanced-resolve/-/enhanced-resolve-5.20.1.tgz",
@@ -3605,6 +3732,15 @@
"node": ">=0.10.0"
}
},
+ "node_modules/expand-template": {
+ "version": "2.0.3",
+ "resolved": "https://registry.npmjs.org/expand-template/-/expand-template-2.0.3.tgz",
+ "integrity": "sha512-XYfuKMvj4O35f/pOXLObndIRvyQ+/+6AhODh+OKWj9S9498pHHn/IMszH+gt0fBCRWMNfk1ZSp5x3AifmnI2vg==",
+ "license": "(MIT OR WTFPL)",
+ "engines": {
+ "node": ">=6"
+ }
+ },
"node_modules/fast-deep-equal": {
"version": "3.1.3",
"resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz",
@@ -3679,6 +3815,12 @@
"node": ">=16.0.0"
}
},
+ "node_modules/file-uri-to-path": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/file-uri-to-path/-/file-uri-to-path-1.0.0.tgz",
+ "integrity": "sha512-0Zt+s3L7Vf1biwWZ29aARiVYLx7iMGnEUl9x33fbB/j3jR81u/O2LbqK+Bm1CDSNDKVtJ/YjwY7TUd5SkeLQLw==",
+ "license": "MIT"
+ },
"node_modules/fill-range": {
"version": "7.1.1",
"resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz",
@@ -3746,6 +3888,12 @@
"url": "https://github.com/sponsors/ljharb"
}
},
+ "node_modules/fs-constants": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/fs-constants/-/fs-constants-1.0.0.tgz",
+ "integrity": "sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow==",
+ "license": "MIT"
+ },
"node_modules/function-bind": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz",
@@ -3877,6 +4025,12 @@
"url": "https://github.com/privatenumber/get-tsconfig?sponsor=1"
}
},
+ "node_modules/github-from-package": {
+ "version": "0.0.0",
+ "resolved": "https://registry.npmjs.org/github-from-package/-/github-from-package-0.0.0.tgz",
+ "integrity": "sha512-SyHy3T1v2NUXn29OsWdxmK6RwHD+vkj3v8en8AOBZ1wBQ/hCAQ5bAQTD02kW4W9tUp/3Qh6J8r9EvntiyCmOOw==",
+ "license": "MIT"
+ },
"node_modules/glob-parent": {
"version": "6.0.2",
"resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-6.0.2.tgz",
@@ -4051,6 +4205,26 @@
"hermes-estree": "0.25.1"
}
},
+ "node_modules/ieee754": {
+ "version": "1.2.1",
+ "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz",
+ "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/feross"
+ },
+ {
+ "type": "patreon",
+ "url": "https://www.patreon.com/feross"
+ },
+ {
+ "type": "consulting",
+ "url": "https://feross.org/support"
+ }
+ ],
+ "license": "BSD-3-Clause"
+ },
"node_modules/ignore": {
"version": "5.3.2",
"resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz",
@@ -4088,6 +4262,18 @@
"node": ">=0.8.19"
}
},
+ "node_modules/inherits": {
+ "version": "2.0.4",
+ "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz",
+ "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==",
+ "license": "ISC"
+ },
+ "node_modules/ini": {
+ "version": "1.3.8",
+ "resolved": "https://registry.npmjs.org/ini/-/ini-1.3.8.tgz",
+ "integrity": "sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew==",
+ "license": "ISC"
+ },
"node_modules/internal-slot": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/internal-slot/-/internal-slot-1.1.0.tgz",
@@ -5037,6 +5223,18 @@
"node": ">=8.6"
}
},
+ "node_modules/mimic-response": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/mimic-response/-/mimic-response-3.1.0.tgz",
+ "integrity": "sha512-z0yWI+4FDrrweS8Zmt4Ej5HdJmky15+L2e6Wgn3+iK5fWzb6T3fhNFq2+MeTRb064c6Wr4N/wv0DzQTjNzHNGQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=10"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
"node_modules/minimatch": {
"version": "3.1.5",
"resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz",
@@ -5054,12 +5252,17 @@
"version": "1.2.8",
"resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz",
"integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==",
- "dev": true,
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
+ "node_modules/mkdirp-classic": {
+ "version": "0.5.3",
+ "resolved": "https://registry.npmjs.org/mkdirp-classic/-/mkdirp-classic-0.5.3.tgz",
+ "integrity": "sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A==",
+ "license": "MIT"
+ },
"node_modules/ms": {
"version": "2.1.3",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
@@ -5085,6 +5288,12 @@
"node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"
}
},
+ "node_modules/napi-build-utils": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/napi-build-utils/-/napi-build-utils-2.0.0.tgz",
+ "integrity": "sha512-GEbrYkbfF7MoNaoh2iGG84Mnf/WZfB0GdGEsM8wz7Expx/LlWf5U8t9nvJKXSp3qr5IsEbK04cBGhol/KwOsWA==",
+ "license": "MIT"
+ },
"node_modules/napi-postinstall": {
"version": "0.3.4",
"resolved": "https://registry.npmjs.org/napi-postinstall/-/napi-postinstall-0.3.4.tgz",
@@ -5188,6 +5397,18 @@
"node": "^10 || ^12 || >=14"
}
},
+ "node_modules/node-abi": {
+ "version": "3.89.0",
+ "resolved": "https://registry.npmjs.org/node-abi/-/node-abi-3.89.0.tgz",
+ "integrity": "sha512-6u9UwL0HlAl21+agMN3YAMXcKByMqwGx+pq+P76vii5f7hTPtKDp08/H9py6DY+cfDw7kQNTGEj/rly3IgbNQA==",
+ "license": "MIT",
+ "dependencies": {
+ "semver": "^7.3.5"
+ },
+ "engines": {
+ "node": ">=10"
+ }
+ },
"node_modules/node-exports-info": {
"version": "1.6.0",
"resolved": "https://registry.npmjs.org/node-exports-info/-/node-exports-info-1.6.0.tgz",
@@ -5347,6 +5568,15 @@
"url": "https://github.com/sponsors/ljharb"
}
},
+ "node_modules/once": {
+ "version": "1.4.0",
+ "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz",
+ "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==",
+ "license": "ISC",
+ "dependencies": {
+ "wrappy": "1"
+ }
+ },
"node_modules/optionator": {
"version": "0.9.4",
"resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.4.tgz",
@@ -5513,6 +5743,33 @@
"node": "^10 || ^12 || >=14"
}
},
+ "node_modules/prebuild-install": {
+ "version": "7.1.3",
+ "resolved": "https://registry.npmjs.org/prebuild-install/-/prebuild-install-7.1.3.tgz",
+ "integrity": "sha512-8Mf2cbV7x1cXPUILADGI3wuhfqWvtiLA1iclTDbFRZkgRQS0NqsPZphna9V+HyTEadheuPmjaJMsbzKQFOzLug==",
+ "deprecated": "No longer maintained. Please contact the author of the relevant native addon; alternatives are available.",
+ "license": "MIT",
+ "dependencies": {
+ "detect-libc": "^2.0.0",
+ "expand-template": "^2.0.3",
+ "github-from-package": "0.0.0",
+ "minimist": "^1.2.3",
+ "mkdirp-classic": "^0.5.3",
+ "napi-build-utils": "^2.0.0",
+ "node-abi": "^3.3.0",
+ "pump": "^3.0.0",
+ "rc": "^1.2.7",
+ "simple-get": "^4.0.0",
+ "tar-fs": "^2.0.0",
+ "tunnel-agent": "^0.6.0"
+ },
+ "bin": {
+ "prebuild-install": "bin.js"
+ },
+ "engines": {
+ "node": ">=10"
+ }
+ },
"node_modules/prelude-ls": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz",
@@ -5535,6 +5792,16 @@
"react-is": "^16.13.1"
}
},
+ "node_modules/pump": {
+ "version": "3.0.4",
+ "resolved": "https://registry.npmjs.org/pump/-/pump-3.0.4.tgz",
+ "integrity": "sha512-VS7sjc6KR7e1ukRFhQSY5LM2uBWAUPiOPa/A3mkKmiMwSmRFUITt0xuj+/lesgnCv+dPIEYlkzrcyXgquIHMcA==",
+ "license": "MIT",
+ "dependencies": {
+ "end-of-stream": "^1.1.0",
+ "once": "^1.3.1"
+ }
+ },
"node_modules/punycode": {
"version": "2.3.1",
"resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz",
@@ -5566,6 +5833,30 @@
],
"license": "MIT"
},
+ "node_modules/rc": {
+ "version": "1.2.8",
+ "resolved": "https://registry.npmjs.org/rc/-/rc-1.2.8.tgz",
+ "integrity": "sha512-y3bGgqKj3QBdxLbLkomlohkvsA8gdAiUQlSBJnBhfn+BPxg4bc62d8TcBW15wavDfgexCgccckhcZvywyQYPOw==",
+ "license": "(BSD-2-Clause OR MIT OR Apache-2.0)",
+ "dependencies": {
+ "deep-extend": "^0.6.0",
+ "ini": "~1.3.0",
+ "minimist": "^1.2.0",
+ "strip-json-comments": "~2.0.1"
+ },
+ "bin": {
+ "rc": "cli.js"
+ }
+ },
+ "node_modules/rc/node_modules/strip-json-comments": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-2.0.1.tgz",
+ "integrity": "sha512-4gB8na07fecVVkOI6Rs4e7T6NOTki5EmL7TUduTs6bu3EdnSycntVJ4re8kgZA+wx9IueI2Y11bfbgwtzuE0KQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
"node_modules/react": {
"version": "19.2.4",
"resolved": "https://registry.npmjs.org/react/-/react-19.2.4.tgz",
@@ -5594,6 +5885,20 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/readable-stream": {
+ "version": "3.6.2",
+ "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz",
+ "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==",
+ "license": "MIT",
+ "dependencies": {
+ "inherits": "^2.0.3",
+ "string_decoder": "^1.1.1",
+ "util-deprecate": "^1.0.1"
+ },
+ "engines": {
+ "node": ">= 6"
+ }
+ },
"node_modules/reflect.getprototypeof": {
"version": "1.0.10",
"resolved": "https://registry.npmjs.org/reflect.getprototypeof/-/reflect.getprototypeof-1.0.10.tgz",
@@ -5734,6 +6039,26 @@
"url": "https://github.com/sponsors/ljharb"
}
},
+ "node_modules/safe-buffer": {
+ "version": "5.2.1",
+ "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz",
+ "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/feross"
+ },
+ {
+ "type": "patreon",
+ "url": "https://www.patreon.com/feross"
+ },
+ {
+ "type": "consulting",
+ "url": "https://feross.org/support"
+ }
+ ],
+ "license": "MIT"
+ },
"node_modules/safe-push-apply": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/safe-push-apply/-/safe-push-apply-1.0.0.tgz",
@@ -5979,6 +6304,51 @@
"url": "https://github.com/sponsors/ljharb"
}
},
+ "node_modules/simple-concat": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/simple-concat/-/simple-concat-1.0.1.tgz",
+ "integrity": "sha512-cSFtAPtRhljv69IK0hTVZQ+OfE9nePi/rtJmw5UjHeVyVroEqJXP1sFztKUy1qU+xvz3u/sfYJLa947b7nAN2Q==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/feross"
+ },
+ {
+ "type": "patreon",
+ "url": "https://www.patreon.com/feross"
+ },
+ {
+ "type": "consulting",
+ "url": "https://feross.org/support"
+ }
+ ],
+ "license": "MIT"
+ },
+ "node_modules/simple-get": {
+ "version": "4.0.1",
+ "resolved": "https://registry.npmjs.org/simple-get/-/simple-get-4.0.1.tgz",
+ "integrity": "sha512-brv7p5WgH0jmQJr1ZDDfKDOSeWWg+OVypG99A/5vYGPqJ6pxiaHLy8nxtFjBA7oMa01ebA9gfh1uMCFqOuXxvA==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/feross"
+ },
+ {
+ "type": "patreon",
+ "url": "https://www.patreon.com/feross"
+ },
+ {
+ "type": "consulting",
+ "url": "https://feross.org/support"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "decompress-response": "^6.0.0",
+ "once": "^1.3.1",
+ "simple-concat": "^1.0.0"
+ }
+ },
"node_modules/source-map-js": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz",
@@ -6009,6 +6379,15 @@
"node": ">= 0.4"
}
},
+ "node_modules/string_decoder": {
+ "version": "1.3.0",
+ "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz",
+ "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==",
+ "license": "MIT",
+ "dependencies": {
+ "safe-buffer": "~5.2.0"
+ }
+ },
"node_modules/string.prototype.includes": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/string.prototype.includes/-/string.prototype.includes-2.0.1.tgz",
@@ -6215,6 +6594,34 @@
"url": "https://opencollective.com/webpack"
}
},
+ "node_modules/tar-fs": {
+ "version": "2.1.4",
+ "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.4.tgz",
+ "integrity": "sha512-mDAjwmZdh7LTT6pNleZ05Yt65HC3E+NiQzl672vQG38jIrehtJk/J3mNwIg+vShQPcLF/LV7CMnDW6vjj6sfYQ==",
+ "license": "MIT",
+ "dependencies": {
+ "chownr": "^1.1.1",
+ "mkdirp-classic": "^0.5.2",
+ "pump": "^3.0.0",
+ "tar-stream": "^2.1.4"
+ }
+ },
+ "node_modules/tar-stream": {
+ "version": "2.2.0",
+ "resolved": "https://registry.npmjs.org/tar-stream/-/tar-stream-2.2.0.tgz",
+ "integrity": "sha512-ujeqbceABgwMZxEJnk2HDY2DlnUZ+9oEcb1KzTVfYHio0UE6dG71n60d8D2I4qNvleWrrXpmjpt7vZeF1LnMZQ==",
+ "license": "MIT",
+ "dependencies": {
+ "bl": "^4.0.3",
+ "end-of-stream": "^1.4.1",
+ "fs-constants": "^1.0.0",
+ "inherits": "^2.0.3",
+ "readable-stream": "^3.1.1"
+ },
+ "engines": {
+ "node": ">=6"
+ }
+ },
"node_modules/tinyglobby": {
"version": "0.2.15",
"resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.15.tgz",
@@ -6321,6 +6728,18 @@
"integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",
"license": "0BSD"
},
+ "node_modules/tunnel-agent": {
+ "version": "0.6.0",
+ "resolved": "https://registry.npmjs.org/tunnel-agent/-/tunnel-agent-0.6.0.tgz",
+ "integrity": "sha512-McnNiV1l8RYeY8tBgEpuodCC1mLUdbSN+CYBL7kJsJNInOP8UjDDEwdk6Mw60vdLLrr5NHKZhMAOSrR2NZuQ+w==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "safe-buffer": "^5.0.1"
+ },
+ "engines": {
+ "node": "*"
+ }
+ },
"node_modules/type-check": {
"version": "0.4.0",
"resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz",
@@ -6473,7 +6892,6 @@
"version": "7.18.2",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.18.2.tgz",
"integrity": "sha512-AsuCzffGHJybSaRrmr5eHr81mwJU3kjw6M+uprWvCXiNeN9SOGwQ3Jn8jb8m3Z6izVgknn1R0FTCEAP2QrLY/w==",
- "dev": true,
"license": "MIT"
},
"node_modules/unrs-resolver": {
@@ -6552,6 +6970,12 @@
"punycode": "^2.1.0"
}
},
+ "node_modules/util-deprecate": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz",
+ "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==",
+ "license": "MIT"
+ },
"node_modules/which": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz",
@@ -6667,6 +7091,12 @@
"node": ">=0.10.0"
}
},
+ "node_modules/wrappy": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz",
+ "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==",
+ "license": "ISC"
+ },
"node_modules/yallist": {
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz",
diff --git a/package.json b/package.json
index 801492e..b25657a 100644
--- a/package.json
+++ b/package.json
@@ -12,6 +12,8 @@
"author": "",
"license": "ISC",
"dependencies": {
+ "@types/better-sqlite3": "^7.6.13",
+ "better-sqlite3": "^12.8.0",
"next": "^15.5.14",
"react": "^19.2.4",
"react-dom": "^19.2.4",
diff --git a/src/app/api/libraries/[id]/route.ts b/src/app/api/libraries/[id]/route.ts
index feef0ce..15c659b 100644
--- a/src/app/api/libraries/[id]/route.ts
+++ b/src/app/api/libraries/[id]/route.ts
@@ -1,5 +1,6 @@
import { NextRequest, NextResponse } from 'next/server'
import { getLibrary, removeLibrary } from '@/lib/libraries'
+import { removeAllAssignmentsForLibrary } from '@/lib/tags'
export async function DELETE(
_request: NextRequest,
@@ -13,5 +14,6 @@ export async function DELETE(
}
removeLibrary(id)
+ removeAllAssignmentsForLibrary(id)
return new NextResponse(null, { status: 204 })
}
diff --git a/src/app/api/tags/assignments/route.ts b/src/app/api/tags/assignments/route.ts
new file mode 100644
index 0000000..fe6944e
--- /dev/null
+++ b/src/app/api/tags/assignments/route.ts
@@ -0,0 +1,43 @@
+import { NextRequest, NextResponse } from 'next/server'
+import { getResolvedTagsForItem, addTagToItem, removeTagFromItem } from '@/lib/tags'
+
+export async function GET(request: NextRequest) {
+ try {
+ const { searchParams } = new URL(request.url)
+ const mediaKey = searchParams.get('mediaKey')
+ if (!mediaKey) {
+ return NextResponse.json({ error: 'mediaKey is required' }, { status: 400 })
+ }
+ return NextResponse.json(getResolvedTagsForItem(mediaKey))
+ } catch (err) {
+ return NextResponse.json({ error: (err as Error).message }, { status: 500 })
+ }
+}
+
+export async function POST(request: NextRequest) {
+ try {
+ const { mediaKey, tagId } = await request.json()
+ if (!mediaKey || !tagId) {
+ return NextResponse.json({ error: 'mediaKey and tagId are required' }, { status: 400 })
+ }
+ addTagToItem(mediaKey, tagId)
+ return new NextResponse(null, { status: 204 })
+ } catch (err) {
+ return NextResponse.json({ error: (err as Error).message }, { status: 400 })
+ }
+}
+
+export async function DELETE(request: NextRequest) {
+ try {
+ const { searchParams } = new URL(request.url)
+ const mediaKey = searchParams.get('mediaKey')
+ const tagId = searchParams.get('tagId')
+ if (!mediaKey || !tagId) {
+ return NextResponse.json({ error: 'mediaKey and tagId are required' }, { status: 400 })
+ }
+ removeTagFromItem(mediaKey, tagId)
+ return new NextResponse(null, { status: 204 })
+ } catch (err) {
+ return NextResponse.json({ error: (err as Error).message }, { status: 400 })
+ }
+}
diff --git a/src/app/api/tags/categories/[id]/route.ts b/src/app/api/tags/categories/[id]/route.ts
new file mode 100644
index 0000000..47123a3
--- /dev/null
+++ b/src/app/api/tags/categories/[id]/route.ts
@@ -0,0 +1,44 @@
+import { NextRequest, NextResponse } from 'next/server'
+import { updateCategory, deleteCategory, deleteCategoryForce, getTags } from '@/lib/tags'
+
+export async function PATCH(
+ request: NextRequest,
+ { params }: { params: Promise<{ id: string }> }
+) {
+ try {
+ const { id } = await params
+ const { name } = await request.json()
+ const category = updateCategory(id, name)
+ return NextResponse.json(category)
+ } catch (err) {
+ return NextResponse.json({ error: (err as Error).message }, { status: 400 })
+ }
+}
+
+export async function DELETE(
+ request: NextRequest,
+ { params }: { params: Promise<{ id: string }> }
+) {
+ try {
+ const { id } = await params
+ const { searchParams } = new URL(request.url)
+ const cascade = searchParams.get('cascade') === 'true'
+
+ if (cascade) {
+ deleteCategoryForce(id)
+ } else {
+ const tags = getTags(id)
+ if (tags.length > 0) {
+ return NextResponse.json(
+ { error: `Category has ${tags.length} tag${tags.length === 1 ? '' : 's'}.`, tagCount: tags.length },
+ { status: 409 }
+ )
+ }
+ deleteCategory(id)
+ }
+
+ return new NextResponse(null, { status: 204 })
+ } catch (err) {
+ return NextResponse.json({ error: (err as Error).message }, { status: 400 })
+ }
+}
diff --git a/src/app/api/tags/categories/route.ts b/src/app/api/tags/categories/route.ts
new file mode 100644
index 0000000..548d22a
--- /dev/null
+++ b/src/app/api/tags/categories/route.ts
@@ -0,0 +1,20 @@
+import { NextRequest, NextResponse } from 'next/server'
+import { getCategories, addCategory } from '@/lib/tags'
+
+export async function GET() {
+ try {
+ return NextResponse.json(getCategories())
+ } catch (err) {
+ return NextResponse.json({ error: (err as Error).message }, { status: 500 })
+ }
+}
+
+export async function POST(request: NextRequest) {
+ try {
+ const { name } = await request.json()
+ const category = addCategory(name)
+ return NextResponse.json(category, { status: 201 })
+ } catch (err) {
+ return NextResponse.json({ error: (err as Error).message }, { status: 400 })
+ }
+}
diff --git a/src/app/api/tags/items/[id]/route.ts b/src/app/api/tags/items/[id]/route.ts
new file mode 100644
index 0000000..0c48eab
--- /dev/null
+++ b/src/app/api/tags/items/[id]/route.ts
@@ -0,0 +1,29 @@
+import { NextRequest, NextResponse } from 'next/server'
+import { updateTag, deleteTag } from '@/lib/tags'
+
+export async function PATCH(
+ request: NextRequest,
+ { params }: { params: Promise<{ id: string }> }
+) {
+ try {
+ const { id } = await params
+ const { name } = await request.json()
+ const tag = updateTag(id, name)
+ return NextResponse.json(tag)
+ } catch (err) {
+ return NextResponse.json({ error: (err as Error).message }, { status: 400 })
+ }
+}
+
+export async function DELETE(
+ _request: NextRequest,
+ { params }: { params: Promise<{ id: string }> }
+) {
+ try {
+ const { id } = await params
+ deleteTag(id)
+ return new NextResponse(null, { status: 204 })
+ } catch (err) {
+ return NextResponse.json({ error: (err as Error).message }, { status: 400 })
+ }
+}
diff --git a/src/app/api/tags/items/route.ts b/src/app/api/tags/items/route.ts
new file mode 100644
index 0000000..1ddc6ee
--- /dev/null
+++ b/src/app/api/tags/items/route.ts
@@ -0,0 +1,25 @@
+import { NextRequest, NextResponse } from 'next/server'
+import { getTags, getTagsSortedByUsage, addTag } from '@/lib/tags'
+
+export async function GET(request: NextRequest) {
+ try {
+ const { searchParams } = new URL(request.url)
+ const categoryId = searchParams.get('categoryId') ?? undefined
+ const sort = searchParams.get('sort')
+ return NextResponse.json(
+ sort === 'usage' ? getTagsSortedByUsage(categoryId) : getTags(categoryId)
+ )
+ } catch (err) {
+ return NextResponse.json({ error: (err as Error).message }, { status: 500 })
+ }
+}
+
+export async function POST(request: NextRequest) {
+ try {
+ const { name, categoryId } = await request.json()
+ const tag = addTag(name, categoryId)
+ return NextResponse.json(tag, { status: 201 })
+ } catch (err) {
+ return NextResponse.json({ error: (err as Error).message }, { status: 400 })
+ }
+}
diff --git a/src/app/api/tags/library-assignments/route.ts b/src/app/api/tags/library-assignments/route.ts
new file mode 100644
index 0000000..c4b2c1d
--- /dev/null
+++ b/src/app/api/tags/library-assignments/route.ts
@@ -0,0 +1,8 @@
+import { getTagAssignmentsForLibrary } from '@/lib/tags'
+
+export async function GET(req: Request) {
+ const { searchParams } = new URL(req.url)
+ const libraryId = searchParams.get('libraryId')
+ if (!libraryId) return Response.json({ error: 'libraryId required' }, { status: 400 })
+ return Response.json(getTagAssignmentsForLibrary(libraryId))
+}
diff --git a/src/app/manage/layout.tsx b/src/app/manage/layout.tsx
new file mode 100644
index 0000000..78f525f
--- /dev/null
+++ b/src/app/manage/layout.tsx
@@ -0,0 +1,10 @@
+import ManageSubNav from '@/components/ManageSubNav'
+
+export default function ManageLayout({ children }: { children: React.ReactNode }) {
+ return (
+
+
+ {children}
+
+ )
+}
diff --git a/src/app/manage/tags/page.tsx b/src/app/manage/tags/page.tsx
new file mode 100644
index 0000000..2f23f7b
--- /dev/null
+++ b/src/app/manage/tags/page.tsx
@@ -0,0 +1,528 @@
+'use client'
+
+import { useEffect, useState, useRef } from 'react'
+import type { Tag, TagCategory } from '@/types'
+
+// ─── Main Page ────────────────────────────────────────────────────────────────
+
+export default function ManageTagsPage() {
+ const [categories, setCategories] = useState([])
+ const [tags, setTags] = useState([])
+ const [loading, setLoading] = useState(true)
+
+ const refresh = () => {
+ Promise.all([
+ fetch('/api/tags/categories').then((r) => r.json()),
+ fetch('/api/tags/items').then((r) => r.json()),
+ ])
+ .then(([cats, tgs]: [TagCategory[], Tag[]]) => {
+ setCategories(cats)
+ setTags(tgs)
+ setLoading(false)
+ })
+ .catch(() => setLoading(false))
+ }
+
+ useEffect(() => {
+ refresh()
+ }, [])
+
+ const tagsForCategory = (categoryId: string) => tags.filter((t) => t.categoryId === categoryId)
+
+ return (
+
+
+ Manage Tags
+
+
+ Create tag categories and tags to organize your media items.
+
+
+
+ {loading ? (
+
+ ) : categories.length === 0 ? (
+
+ No categories yet. Add one below.
+
+ ) : (
+
+ {categories.map((cat) => (
+
+ ))}
+
+ )}
+
+
+
+
+ )
+}
+
+// ─── Category Block ───────────────────────────────────────────────────────────
+
+function CategoryBlock({
+ category,
+ tags,
+ onChanged,
+}: {
+ category: TagCategory
+ tags: Tag[]
+ onChanged: () => void
+}) {
+ const [editing, setEditing] = useState(false)
+ const [editName, setEditName] = useState(category.name)
+ const [saving, setSaving] = useState(false)
+ const [confirming, setConfirming] = useState(false)
+ const [deleting, setDeleting] = useState(false)
+ const [error, setError] = useState(null)
+ const cancelRef = useRef | null>(null)
+
+ const handleRename = async (e: React.FormEvent) => {
+ e.preventDefault()
+ setError(null)
+ setSaving(true)
+ try {
+ const res = await fetch(`/api/tags/categories/${encodeURIComponent(category.id)}`, {
+ method: 'PATCH',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ name: editName }),
+ })
+ const data = await res.json()
+ if (!res.ok) { setError(data.error); setSaving(false); return }
+ setEditing(false)
+ onChanged()
+ } catch {
+ setError('Network error.')
+ }
+ setSaving(false)
+ }
+
+ const handleDeleteClick = () => {
+ if (!confirming) {
+ setConfirming(true)
+ cancelRef.current = setTimeout(() => setConfirming(false), 4000)
+ return
+ }
+ if (cancelRef.current) clearTimeout(cancelRef.current)
+ setDeleting(true)
+ const cascade = tags.length > 0
+ fetch(
+ `/api/tags/categories/${encodeURIComponent(category.id)}${cascade ? '?cascade=true' : ''}`,
+ { method: 'DELETE' }
+ )
+ .then(() => onChanged())
+ .catch(() => setDeleting(false))
+ }
+
+ const handleCancel = () => {
+ if (cancelRef.current) clearTimeout(cancelRef.current)
+ setConfirming(false)
+ }
+
+ return (
+
+ {/* Category header */}
+
+ {editing ? (
+
+ ) : (
+ <>
+
+ {category.name}
+
+ {tags.length} tag{tags.length === 1 ? '' : 's'}
+
+
+
+ {confirming && (
+
+ )}
+
+ >
+ )}
+
+
+ {error && (
+
+ {error}
+
+ )}
+
+ {/* Tags list */}
+
+ {tags.map((tag) => (
+
+ ))}
+ {tags.length === 0 && (
+
+ No tags in this category.
+
+ )}
+
+
+ {/* Add tag inline */}
+
+
+ )
+}
+
+// ─── Tag Row ──────────────────────────────────────────────────────────────────
+
+function TagRow({ tag, onChanged }: { tag: Tag; onChanged: () => void }) {
+ const [editing, setEditing] = useState(false)
+ const [editName, setEditName] = useState(tag.name)
+ const [saving, setSaving] = useState(false)
+ const [confirming, setConfirming] = useState(false)
+ const [deleting, setDeleting] = useState(false)
+ const cancelRef = useRef | null>(null)
+
+ const handleRename = async (e: React.FormEvent) => {
+ e.preventDefault()
+ setSaving(true)
+ const res = await fetch(`/api/tags/items/${encodeURIComponent(tag.id)}`, {
+ method: 'PATCH',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ name: editName }),
+ })
+ setSaving(false)
+ if (res.ok) { setEditing(false); onChanged() }
+ }
+
+ const handleDeleteClick = () => {
+ if (!confirming) {
+ setConfirming(true)
+ cancelRef.current = setTimeout(() => setConfirming(false), 4000)
+ return
+ }
+ if (cancelRef.current) clearTimeout(cancelRef.current)
+ setDeleting(true)
+ fetch(`/api/tags/items/${encodeURIComponent(tag.id)}`, { method: 'DELETE' })
+ .then(() => onChanged())
+ .catch(() => setDeleting(false))
+ }
+
+ if (editing) {
+ return (
+
+ )
+ }
+
+ return (
+
+ {tag.name}
+
+
+
+ )
+}
+
+// ─── Add Tag Form ─────────────────────────────────────────────────────────────
+
+function AddTagForm({ categoryId, onAdded }: { categoryId: string; onAdded: () => void }) {
+ const [name, setName] = useState('')
+ const [submitting, setSubmitting] = useState(false)
+ const [error, setError] = useState(null)
+
+ const handleSubmit = async (e: React.FormEvent) => {
+ e.preventDefault()
+ setError(null)
+ setSubmitting(true)
+ try {
+ const res = await fetch('/api/tags/items', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ name, categoryId }),
+ })
+ const data = await res.json()
+ if (!res.ok) { setError(data.error); setSubmitting(false); return }
+ setName('')
+ onAdded()
+ } catch {
+ setError('Network error.')
+ }
+ setSubmitting(false)
+ }
+
+ return (
+
+ )
+}
+
+// ─── Add Category Form ────────────────────────────────────────────────────────
+
+function AddCategoryForm({ onAdded }: { onAdded: () => void }) {
+ const [name, setName] = useState('')
+ const [submitting, setSubmitting] = useState(false)
+ const [error, setError] = useState(null)
+
+ const handleSubmit = async (e: React.FormEvent) => {
+ e.preventDefault()
+ setError(null)
+ setSubmitting(true)
+ try {
+ const res = await fetch('/api/tags/categories', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ name }),
+ })
+ const data = await res.json()
+ if (!res.ok) { setError(data.error); setSubmitting(false); return }
+ setName('')
+ onAdded()
+ } catch {
+ setError('Network error.')
+ }
+ setSubmitting(false)
+ }
+
+ return (
+
+ )
+}
+
+// ─── Shared helpers ───────────────────────────────────────────────────────────
+
+function Section({ title, children }: { title: string; children: React.ReactNode }) {
+ return (
+
+ )
+}
+
+function Field({ label, children }: { label: string; children: React.ReactNode }) {
+ return (
+
+
+ {children}
+
+ )
+}
+
+function LoadingRows() {
+ return (
+
+ {[70, 50, 85].map((w) => (
+
+ ))}
+
+ )
+}
diff --git a/src/components/FilterPanel.tsx b/src/components/FilterPanel.tsx
new file mode 100644
index 0000000..00cf4d2
--- /dev/null
+++ b/src/components/FilterPanel.tsx
@@ -0,0 +1,130 @@
+'use client'
+
+import { useEffect, useState } from 'react'
+import type { Tag, TagCategory } from '@/types'
+
+interface Props {
+ libraryId: string
+ assignments: Record
+ search: string
+ onSearchChange: (q: string) => void
+ selectedTagIds: Set
+ onTagToggle: (tagId: string) => void
+ refreshKey?: number
+}
+
+export default function FilterPanel({ assignments, search, onSearchChange, selectedTagIds, onTagToggle, refreshKey }: Props) {
+ const [categories, setCategories] = useState([])
+ const [tags, setTags] = useState([])
+ const [loading, setLoading] = useState(true)
+
+ useEffect(() => {
+ Promise.all([
+ fetch('/api/tags/categories').then((r) => r.json()),
+ fetch('/api/tags/items').then((r) => r.json()),
+ ])
+ .then(([cats, ts]: [TagCategory[], Tag[]]) => {
+ setCategories(cats)
+ setTags(ts)
+ })
+ .finally(() => setLoading(false))
+ }, [refreshKey])
+
+ const usedTagIds = new Set(Object.values(assignments).flat())
+ const usedTags = tags.filter((t) => usedTagIds.has(t.id))
+ const usedCategoryIds = new Set(usedTags.map((t) => t.categoryId))
+ const usedCategories = categories.filter((c) => usedCategoryIds.has(c.id))
+
+ const hasTags = usedTags.length > 0
+
+ return (
+
+ {/* Search */}
+
onSearchChange(e.target.value)}
+ className="w-full rounded-lg px-3 py-2 text-sm outline-none"
+ style={{
+ backgroundColor: 'var(--surface)',
+ border: '1px solid var(--border)',
+ color: 'var(--text-primary)',
+ }}
+ />
+
+ {/* Tag filters */}
+ {loading ? (
+
+ {[0, 1].map((i) => (
+
+
+
+ {[50, 65, 42].map((w) => (
+
+ ))}
+
+
+ ))}
+
+ ) : hasTags ? (
+
+ {usedCategories.map((cat) => {
+ const catTags = usedTags.filter((t) => t.categoryId === cat.id)
+ if (catTags.length === 0) return null
+ return (
+
+
+ {cat.name}
+
+
+ {catTags.map((tag) => {
+ const active = selectedTagIds.has(tag.id)
+ return (
+
+ )
+ })}
+
+
+ )
+ })}
+
+ ) : (
+
+ No tags defined.{' '}
+
+ Manage tags →
+
+
+ )}
+
+ )
+}
diff --git a/src/components/ManageSubNav.tsx b/src/components/ManageSubNav.tsx
new file mode 100644
index 0000000..a5dbafa
--- /dev/null
+++ b/src/components/ManageSubNav.tsx
@@ -0,0 +1,42 @@
+'use client'
+
+import Link from 'next/link'
+import { usePathname } from 'next/navigation'
+
+const TABS = [
+ { href: '/manage', label: 'Libraries' },
+ { href: '/manage/tags', label: 'Tags' },
+]
+
+export default function ManageSubNav() {
+ const pathname = usePathname()
+
+ return (
+
+ )
+}
diff --git a/src/components/games/GameDetailModal.tsx b/src/components/games/GameDetailModal.tsx
index 7bf4378..4777af5 100644
--- a/src/components/games/GameDetailModal.tsx
+++ b/src/components/games/GameDetailModal.tsx
@@ -2,14 +2,16 @@
import { useEffect, useRef } from 'react'
import type { Game } from '@/types'
+import TagSelector from '@/components/tags/TagSelector'
interface Props {
game: Game
libraryId: string
onClose: () => void
+ onTagsChanged?: () => void
}
-export default function GameDetailModal({ game, libraryId, onClose }: Props) {
+export default function GameDetailModal({ game, libraryId, onClose, onTagsChanged }: Props) {
const overlayRef = useRef(null)
useEffect(() => {
@@ -90,6 +92,14 @@ export default function GameDetailModal({ game, libraryId, onClose }: Props) {
↓
Download .zip
+
+ {/* Tags */}
+
diff --git a/src/components/games/GamesView.tsx b/src/components/games/GamesView.tsx
index 6a70cd4..9a27e8e 100644
--- a/src/components/games/GamesView.tsx
+++ b/src/components/games/GamesView.tsx
@@ -1,8 +1,9 @@
'use client'
-import { useEffect, useState } from 'react'
+import { useEffect, useState, useCallback } from 'react'
import type { Game } from '@/types'
import GameDetailModal from './GameDetailModal'
+import FilterPanel from '@/components/FilterPanel'
interface Props {
libraryId: string
@@ -13,6 +14,17 @@ export default function GamesView({ libraryId }: Props) {
const [loading, setLoading] = useState(true)
const [error, setError] = useState(null)
const [selected, setSelected] = useState(null)
+ const [search, setSearch] = useState('')
+ const [selectedTagIds, setSelectedTagIds] = useState>(new Set())
+ const [assignments, setAssignments] = useState>({})
+ const [filterRefreshKey, setFilterRefreshKey] = useState(0)
+
+ const toggleTag = (tagId: string) =>
+ setSelectedTagIds((prev) => {
+ const next = new Set(prev)
+ next.has(tagId) ? next.delete(tagId) : next.add(tagId)
+ return next
+ })
useEffect(() => {
fetch(`/api/games?libraryId=${encodeURIComponent(libraryId)}`)
@@ -27,62 +39,102 @@ export default function GamesView({ libraryId }: Props) {
})
}, [libraryId])
- if (loading) return
- if (error) return
- if (games.length === 0) return
+ const fetchAssignments = useCallback(() => {
+ fetch(`/api/tags/library-assignments?libraryId=${encodeURIComponent(libraryId)}`)
+ .then((r) => r.json())
+ .then(setAssignments)
+ .catch(() => {})
+ }, [libraryId])
+
+ useEffect(() => { fetchAssignments() }, [fetchAssignments])
+
+ const filtered = games.filter((game) => {
+ if (search && !game.title.toLowerCase().includes(search.toLowerCase())) return false
+ if (selectedTagIds.size > 0) {
+ const gameTags = assignments[`${libraryId}:${game.id}`] ?? []
+ if (![...selectedTagIds].every((id) => gameTags.includes(id))) return false
+ }
+ return true
+ })
return (
- <>
-
- {games.map((game) => (
-
- ))}
+
+
+
+
+ {loading ? (
+
+ ) : error ? (
+
+ ) : games.length === 0 ? (
+
+ ) : (
+
+ {filtered.map((game) => (
+
+ ))}
+
+ )}
- {selected && (
-
setSelected(null)} />
- )}
- >
+ {selected && (
+ setSelected(null)}
+ onTagsChanged={() => { setFilterRefreshKey((k) => k + 1); fetchAssignments() }}
+ />
+ )}
+
+
)
}
diff --git a/src/components/mixed/MixedView.tsx b/src/components/mixed/MixedView.tsx
index 7d39c7a..ee344a1 100644
--- a/src/components/mixed/MixedView.tsx
+++ b/src/components/mixed/MixedView.tsx
@@ -4,6 +4,8 @@ import { useEffect, useState, useCallback, useRef } from 'react'
import type { DirectoryListing, FileEntry } from '@/types'
import VideoPlayerModal from './VideoPlayerModal'
import ImageLightbox from './ImageLightbox'
+import TagSelector from '@/components/tags/TagSelector'
+import FilterPanel from '@/components/FilterPanel'
interface Props {
libraryId: string
@@ -15,12 +17,26 @@ type ModalState =
| { type: 'image'; url: string; name: string }
| null
+type TagPanelState = { entry: FileEntry; mediaKey: string } | null
+
export default function MixedView({ libraryId, initialPath }: Props) {
const [currentPath, setCurrentPath] = useState(initialPath)
const [listing, setListing] = useState
(null)
const [loading, setLoading] = useState(true)
const [error, setError] = useState(null)
const [modal, setModal] = useState(null)
+ const [tagPanel, setTagPanel] = useState(null)
+ const [search, setSearch] = useState('')
+ const [selectedTagIds, setSelectedTagIds] = useState>(new Set())
+ const [assignments, setAssignments] = useState>({})
+ const [filterRefreshKey, setFilterRefreshKey] = useState(0)
+
+ const toggleTag = (tagId: string) =>
+ setSelectedTagIds((prev) => {
+ const next = new Set(prev)
+ next.has(tagId) ? next.delete(tagId) : next.add(tagId)
+ return next
+ })
const loadPath = useCallback(
(path: string) => {
@@ -47,6 +63,15 @@ export default function MixedView({ libraryId, initialPath }: Props) {
loadPath(initialPath)
}, [loadPath, initialPath])
+ const fetchAssignments = useCallback(() => {
+ fetch(`/api/tags/library-assignments?libraryId=${encodeURIComponent(libraryId)}`)
+ .then((r) => r.json())
+ .then(setAssignments)
+ .catch(() => {})
+ }, [libraryId])
+
+ useEffect(() => { fetchAssignments() }, [fetchAssignments])
+
const handleEntry = (entry: FileEntry) => {
if (entry.type === 'directory') {
const newPath = currentPath ? `${currentPath}/${entry.name}` : entry.name
@@ -64,6 +89,12 @@ export default function MixedView({ libraryId, initialPath }: Props) {
}
}
+ const handleTagEntry = (entry: FileEntry) => {
+ const relativePath = currentPath ? `${currentPath}/${entry.name}` : entry.name
+ const mediaKey = `${libraryId}:${encodeURIComponent(relativePath)}`
+ setTagPanel({ entry, mediaKey })
+ }
+
const navigateUp = () => {
const parts = currentPath.split('/').filter(Boolean)
parts.pop()
@@ -75,8 +106,34 @@ export default function MixedView({ libraryId, initialPath }: Props) {
? currentPath.split('/').filter(Boolean)
: []
+ const mediaKeyFor = (entry: FileEntry) => {
+ const rel = currentPath ? `${currentPath}/${entry.name}` : entry.name
+ return `${libraryId}:${encodeURIComponent(rel)}`
+ }
+
+ const filteredEntries = (listing?.entries ?? []).filter((entry) => {
+ if (search && !entry.name.toLowerCase().includes(search.toLowerCase())) return false
+ if (selectedTagIds.size > 0 && entry.type !== 'directory') {
+ const entryTags = assignments[mediaKeyFor(entry)] ?? []
+ if (![...selectedTagIds].every((id) => entryTags.includes(id))) return false
+ }
+ return true
+ })
+
return (
- <>
+
+
+
+
+
{/* Breadcrumb */}
)}
@@ -149,11 +206,53 @@ export default function MixedView({ libraryId, initialPath }: Props) {
{modal?.type === 'image' && (
setModal(null)} />
)}
- >
+
+ {/* Tag panel */}
+ {tagPanel && (
+ { if (e.target === e.currentTarget) setTagPanel(null) }}
+ >
+
+
+
+
+ Tags
+
+
+ {tagPanel.entry.name}
+
+
+
+
+
+ { setFilterRefreshKey((k) => k + 1); fetchAssignments() }}
+ />
+
+
+
+ )}
+
+
)
}
-function EntryTile({ entry, onOpen }: { entry: FileEntry; onOpen: (e: FileEntry) => void }) {
+function EntryTile({ entry, onOpen, onTag }: { entry: FileEntry; onOpen: (e: FileEntry) => void; onTag: (e: FileEntry) => void }) {
type ImgState = 'loading' | 'loaded' | 'error'
const [imgState, setImgState] = useState(
entry.thumbnailUrl ? 'loading' : 'error'
@@ -174,9 +273,12 @@ function EntryTile({ entry, onOpen }: { entry: FileEntry; onOpen: (e: FileEntry)
const icon = isDir ? '📁' : isVideo ? '▶' : entry.mediaType === 'image' ? '🖼' : '📄'
return (
-
+
+ {/* Tag button — top-left, shown on hover */}
+
+
)
}
diff --git a/src/components/tags/TagBadge.tsx b/src/components/tags/TagBadge.tsx
new file mode 100644
index 0000000..6cb5914
--- /dev/null
+++ b/src/components/tags/TagBadge.tsx
@@ -0,0 +1,33 @@
+import type { Tag, TagCategory } from '@/types'
+
+interface Props {
+ tag: Tag
+ category?: TagCategory
+ onRemove?: () => void
+}
+
+export default function TagBadge({ tag, category, onRemove }: Props) {
+ return (
+
+ {category && (
+ {category.name}:
+ )}
+ {tag.name}
+ {onRemove && (
+
+ )}
+
+ )
+}
diff --git a/src/components/tags/TagSelector.tsx b/src/components/tags/TagSelector.tsx
new file mode 100644
index 0000000..4f03cc9
--- /dev/null
+++ b/src/components/tags/TagSelector.tsx
@@ -0,0 +1,449 @@
+'use client'
+
+import { useEffect, useState, useCallback } from 'react'
+import type { Tag, TagCategory } from '@/types'
+import TagBadge from './TagBadge'
+
+interface Props {
+ mediaKey: string
+ onTagsChanged?: () => void
+}
+
+interface AllTags {
+ categories: TagCategory[]
+ tags: Tag[]
+}
+
+export default function TagSelector({ mediaKey, onTagsChanged }: Props) {
+ const [assigned, setAssigned] = useState<{ tags: Tag[]; categories: TagCategory[] }>({
+ tags: [],
+ categories: [],
+ })
+ const [all, setAll] = useState({ categories: [], tags: [] })
+ const [loading, setLoading] = useState(true)
+ const [busy, setBusy] = useState(null)
+
+ // Per-category search text
+ const [categorySearches, setCategorySearches] = useState>({})
+
+ // Inline add-tag flow
+ const [addingTagTo, setAddingTagTo] = useState(null)
+ const [newTagName, setNewTagName] = useState('')
+ const [tagSaveError, setTagSaveError] = useState(null)
+ const [savingTag, setSavingTag] = useState(false)
+
+ // Inline add-category flow
+ const [addingCategory, setAddingCategory] = useState(false)
+ const [newCategoryName, setNewCategoryName] = useState('')
+ const [categorySaveError, setCategorySaveError] = useState(null)
+ const [savingCategory, setSavingCategory] = useState(false)
+
+ const fetchAssigned = useCallback(() => {
+ return fetch(`/api/tags/assignments?mediaKey=${encodeURIComponent(mediaKey)}`)
+ .then((r) => r.json())
+ .then((data) => setAssigned(data))
+ }, [mediaKey])
+
+ const fetchAll = useCallback(() => {
+ return Promise.all([
+ fetch('/api/tags/categories').then((r) => r.json()),
+ fetch('/api/tags/items?sort=usage').then((r) => r.json()),
+ ]).then(([categories, tags]: [TagCategory[], Tag[]]) => {
+ setAll({ categories, tags })
+ })
+ }, [])
+
+ useEffect(() => {
+ setLoading(true)
+ Promise.all([fetchAssigned(), fetchAll()]).finally(() => setLoading(false))
+ }, [fetchAssigned, fetchAll])
+
+ const isAssigned = (tagId: string) => assigned.tags.some((t) => t.id === tagId)
+
+ const toggleTag = async (tag: Tag) => {
+ if (busy) return
+ setBusy(tag.id)
+ try {
+ if (isAssigned(tag.id)) {
+ await fetch(
+ `/api/tags/assignments?mediaKey=${encodeURIComponent(mediaKey)}&tagId=${encodeURIComponent(tag.id)}`,
+ { method: 'DELETE' }
+ )
+ } else {
+ await fetch('/api/tags/assignments', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ mediaKey, tagId: tag.id }),
+ })
+ }
+ await fetchAssigned()
+ onTagsChanged?.()
+ } finally {
+ setBusy(null)
+ }
+ }
+
+ const submitAddTag = async (categoryId: string) => {
+ const name = newTagName.trim()
+ if (!name) return
+ setSavingTag(true)
+ setTagSaveError(null)
+ try {
+ const res = await fetch('/api/tags/items', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ name, categoryId }),
+ })
+ if (!res.ok) {
+ const { error } = await res.json()
+ setTagSaveError(error)
+ return
+ }
+ const newTag: Tag = await res.json()
+ setNewTagName('')
+ setAddingTagTo(null)
+ await Promise.all([
+ fetch('/api/tags/assignments', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ mediaKey, tagId: newTag.id }),
+ }),
+ fetchAll(),
+ ])
+ await fetchAssigned()
+ onTagsChanged?.()
+ } finally {
+ setSavingTag(false)
+ }
+ }
+
+ const submitAddCategory = async () => {
+ const name = newCategoryName.trim()
+ if (!name) return
+ setSavingCategory(true)
+ setCategorySaveError(null)
+ try {
+ const res = await fetch('/api/tags/categories', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ name }),
+ })
+ if (!res.ok) {
+ const { error } = await res.json()
+ setCategorySaveError(error)
+ return
+ }
+ setNewCategoryName('')
+ setAddingCategory(false)
+ await fetchAll()
+ onTagsChanged?.()
+ } finally {
+ setSavingCategory(false)
+ }
+ }
+
+ if (loading) {
+ return (
+
+ {[60, 80, 50].map((w) => (
+
+ ))}
+
+ )
+ }
+
+ const assignedCategoryMap = Object.fromEntries(assigned.categories.map((c) => [c.id, c]))
+
+ return (
+
+ {/* Assigned tags grouped by category */}
+ {assigned.tags.length > 0 && (
+
+ {(() => {
+ const groups = new Map()
+ const ungrouped: Tag[] = []
+ for (const tag of assigned.tags) {
+ if (tag.categoryId) {
+ const arr = groups.get(tag.categoryId) ?? []
+ arr.push(tag)
+ groups.set(tag.categoryId, arr)
+ } else {
+ ungrouped.push(tag)
+ }
+ }
+ return (
+ <>
+ {Array.from(groups.entries()).map(([catId, tags]) => {
+ const cat = assignedCategoryMap[catId]
+ return (
+
+ {cat?.name}:
+ {tags.map((tag) => (
+
+ {tag.name}
+
+
+ ))}
+
+ )
+ })}
+ {ungrouped.map((tag) => (
+ toggleTag(tag)} />
+ ))}
+ >
+ )
+ })()}
+
+ )}
+
+ {/* Tag picker grouped by category */}
+
+ {all.categories.map((category) => {
+ const categoryTags = all.tags.filter((t) => t.categoryId === category.id)
+ const search = categorySearches[category.id] ?? ''
+ const visibleTags = categoryTags
+ .filter((t) => !search || t.name.toLowerCase().includes(search.toLowerCase()))
+ .slice(0, 25)
+
+ return (
+
+ {/* Category header: name + search input */}
+
+
+ {category.name}
+
+ {categoryTags.length > 0 && (
+
+ setCategorySearches((prev) => ({ ...prev, [category.id]: e.target.value }))
+ }
+ className="text-xs px-1.5 py-0.5 rounded outline-none"
+ style={{
+ backgroundColor: 'var(--surface)',
+ border: '1px solid var(--border)',
+ color: 'var(--text-primary)',
+ width: 90,
+ }}
+ />
+ )}
+
+
+ {/* Tag pills + add button */}
+
+ {visibleTags.map((tag) => {
+ const active = isAssigned(tag.id)
+ const isBusy = busy === tag.id
+ return (
+
+ )
+ })}
+
+ {/* Inline add-tag form or + button */}
+ {addingTagTo === category.id ? (
+
+ {
+ setNewTagName(e.target.value)
+ setTagSaveError(null)
+ }}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter') submitAddTag(category.id)
+ if (e.key === 'Escape') {
+ setAddingTagTo(null)
+ setNewTagName('')
+ setTagSaveError(null)
+ }
+ }}
+ placeholder="tag name"
+ className="px-1.5 py-0.5 rounded text-xs outline-none"
+ style={{
+ backgroundColor: 'var(--surface)',
+ border: '1px solid var(--border)',
+ color: 'var(--text-primary)',
+ width: 90,
+ }}
+ disabled={savingTag}
+ />
+
+
+ {tagSaveError && (
+
+ {tagSaveError}
+
+ )}
+
+ ) : (
+
+ )}
+
+
+ )
+ })}
+
+ {/* Add category */}
+
+ {addingCategory ? (
+
+ {
+ setNewCategoryName(e.target.value)
+ setCategorySaveError(null)
+ }}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter') submitAddCategory()
+ if (e.key === 'Escape') {
+ setAddingCategory(false)
+ setNewCategoryName('')
+ setCategorySaveError(null)
+ }
+ }}
+ placeholder="category name"
+ className="flex-1 text-xs px-2 py-1 rounded outline-none"
+ style={{
+ backgroundColor: 'var(--surface)',
+ border: '1px solid var(--border)',
+ color: 'var(--text-primary)',
+ }}
+ disabled={savingCategory}
+ />
+
+
+ {categorySaveError && (
+
+ {categorySaveError}
+
+ )}
+
+ ) : (
+
+ )}
+
+
+
+ )
+}
diff --git a/src/lib/tags.ts b/src/lib/tags.ts
new file mode 100644
index 0000000..a794d03
--- /dev/null
+++ b/src/lib/tags.ts
@@ -0,0 +1,258 @@
+import path from 'path'
+import Database from 'better-sqlite3'
+import type { Tag, TagCategory } from '@/types'
+
+const DB_PATH = path.resolve(process.cwd(), 'medialore.db')
+
+let _db: Database.Database | null = null
+
+function getDb(): Database.Database {
+ if (_db) return _db
+ _db = new Database(DB_PATH)
+ _db.pragma('journal_mode = WAL')
+ _db.pragma('foreign_keys = ON')
+ initDb(_db)
+ return _db
+}
+
+function initDb(db: Database.Database): void {
+ db.exec(`
+ CREATE TABLE IF NOT EXISTS tag_categories (
+ id TEXT PRIMARY KEY,
+ name TEXT NOT NULL UNIQUE
+ );
+
+ CREATE TABLE IF NOT EXISTS tags (
+ id TEXT PRIMARY KEY,
+ name TEXT NOT NULL,
+ category_id TEXT NOT NULL REFERENCES tag_categories(id) ON DELETE CASCADE
+ );
+
+ CREATE UNIQUE INDEX IF NOT EXISTS tags_name_category ON tags(name, category_id);
+
+ CREATE TABLE IF NOT EXISTS media_tags (
+ media_key TEXT NOT NULL,
+ tag_id TEXT NOT NULL REFERENCES tags(id) ON DELETE CASCADE,
+ PRIMARY KEY (media_key, tag_id)
+ );
+ `)
+}
+
+function slugify(name: string): string {
+ return name
+ .toLowerCase()
+ .trim()
+ .replace(/[^a-z0-9\s-]/g, '')
+ .replace(/\s+/g, '-')
+ .replace(/-+/g, '-')
+ .replace(/^-|-$/g, '')
+}
+
+// ─── Categories ───────────────────────────────────────────────────────────────
+
+export function getCategories(): TagCategory[] {
+ const db = getDb()
+ return db.prepare('SELECT id, name FROM tag_categories ORDER BY name').all() as TagCategory[]
+}
+
+export function addCategory(name: string): TagCategory {
+ const trimmed = name.trim()
+ if (!trimmed) throw new Error('Category name is required.')
+
+ const db = getDb()
+ const baseId = slugify(trimmed) || 'category'
+ let id = baseId
+ let suffix = 2
+ while (db.prepare('SELECT 1 FROM tag_categories WHERE id = ?').get(id)) {
+ id = `${baseId}-${suffix++}`
+ }
+
+ try {
+ db.prepare('INSERT INTO tag_categories (id, name) VALUES (?, ?)').run(id, trimmed)
+ } catch {
+ throw new Error(`A category named "${trimmed}" already exists.`)
+ }
+
+ return { id, name: trimmed }
+}
+
+export function updateCategory(id: string, name: string): TagCategory {
+ const trimmed = name.trim()
+ if (!trimmed) throw new Error('Category name is required.')
+
+ const db = getDb()
+ try {
+ const result = db.prepare('UPDATE tag_categories SET name = ? WHERE id = ?').run(trimmed, id)
+ if (result.changes === 0) throw new Error(`Category not found: ${id}`)
+ } catch (err) {
+ const msg = (err as Error).message
+ if (msg.includes('UNIQUE')) throw new Error(`A category named "${trimmed}" already exists.`)
+ throw err
+ }
+
+ return { id, name: trimmed }
+}
+
+export function deleteCategory(id: string): void {
+ const db = getDb()
+ const tagCount = (
+ db.prepare('SELECT COUNT(*) as count FROM tags WHERE category_id = ?').get(id) as { count: number }
+ ).count
+
+ if (tagCount > 0) {
+ throw new Error(
+ `Category has ${tagCount} tag${tagCount === 1 ? '' : 's'}. Delete all tags first or use force delete.`
+ )
+ }
+
+ const result = db.prepare('DELETE FROM tag_categories WHERE id = ?').run(id)
+ if (result.changes === 0) throw new Error(`Category not found: ${id}`)
+}
+
+export function deleteCategoryForce(id: string): void {
+ const db = getDb()
+ // CASCADE on tags will also cascade to media_tags
+ const result = db.prepare('DELETE FROM tag_categories WHERE id = ?').run(id)
+ if (result.changes === 0) throw new Error(`Category not found: ${id}`)
+}
+
+// ─── Tags ─────────────────────────────────────────────────────────────────────
+
+export function getTags(categoryId?: string): Tag[] {
+ const db = getDb()
+ if (categoryId) {
+ return db
+ .prepare('SELECT id, name, category_id as categoryId FROM tags WHERE category_id = ? ORDER BY name')
+ .all(categoryId) as Tag[]
+ }
+ return db
+ .prepare('SELECT id, name, category_id as categoryId FROM tags ORDER BY name')
+ .all() as Tag[]
+}
+
+export function getTagsSortedByUsage(categoryId?: string): Tag[] {
+ const db = getDb()
+ const where = categoryId ? 'WHERE t.category_id = ?' : ''
+ const params = categoryId ? [categoryId] : []
+ return db
+ .prepare(
+ `SELECT t.id, t.name, t.category_id as categoryId,
+ COUNT(mt.tag_id) as use_count
+ FROM tags t
+ LEFT JOIN media_tags mt ON mt.tag_id = t.id
+ ${where}
+ GROUP BY t.id
+ ORDER BY use_count DESC, t.name ASC`
+ )
+ .all(...params) as Tag[]
+}
+
+export function addTag(name: string, categoryId: string): Tag {
+ const trimmed = name.trim()
+ if (!trimmed) throw new Error('Tag name is required.')
+
+ const db = getDb()
+
+ const category = db.prepare('SELECT 1 FROM tag_categories WHERE id = ?').get(categoryId)
+ if (!category) throw new Error(`Category not found: ${categoryId}`)
+
+ const baseId = `tag-${slugify(trimmed) || 'tag'}`
+ let id = baseId
+ let suffix = 2
+ while (db.prepare('SELECT 1 FROM tags WHERE id = ?').get(id)) {
+ id = `${baseId}-${suffix++}`
+ }
+
+ try {
+ db.prepare('INSERT INTO tags (id, name, category_id) VALUES (?, ?, ?)').run(id, trimmed, categoryId)
+ } catch {
+ throw new Error(`A tag named "${trimmed}" already exists in this category.`)
+ }
+
+ return { id, name: trimmed, categoryId }
+}
+
+export function updateTag(id: string, name: string): Tag {
+ const trimmed = name.trim()
+ if (!trimmed) throw new Error('Tag name is required.')
+
+ const db = getDb()
+
+ const existing = db
+ .prepare('SELECT id, name, category_id as categoryId FROM tags WHERE id = ?')
+ .get(id) as Tag | undefined
+ if (!existing) throw new Error(`Tag not found: ${id}`)
+
+ try {
+ db.prepare('UPDATE tags SET name = ? WHERE id = ?').run(trimmed, id)
+ } catch {
+ throw new Error(`A tag named "${trimmed}" already exists in this category.`)
+ }
+
+ return { id, name: trimmed, categoryId: existing.categoryId }
+}
+
+export function deleteTag(id: string): void {
+ const db = getDb()
+ // CASCADE removes media_tags rows automatically
+ const result = db.prepare('DELETE FROM tags WHERE id = ?').run(id)
+ if (result.changes === 0) throw new Error(`Tag not found: ${id}`)
+}
+
+// ─── Assignments ──────────────────────────────────────────────────────────────
+
+export function addTagToItem(mediaKey: string, tagId: string): void {
+ const db = getDb()
+ const tag = db.prepare('SELECT 1 FROM tags WHERE id = ?').get(tagId)
+ if (!tag) throw new Error(`Tag not found: ${tagId}`)
+ // INSERT OR IGNORE handles duplicate gracefully
+ db.prepare('INSERT OR IGNORE INTO media_tags (media_key, tag_id) VALUES (?, ?)').run(mediaKey, tagId)
+}
+
+export function removeTagFromItem(mediaKey: string, tagId: string): void {
+ const db = getDb()
+ db.prepare('DELETE FROM media_tags WHERE media_key = ? AND tag_id = ?').run(mediaKey, tagId)
+}
+
+export function getResolvedTagsForItem(mediaKey: string): { tags: Tag[]; categories: TagCategory[] } {
+ const db = getDb()
+
+ const tags = db
+ .prepare(
+ `SELECT t.id, t.name, t.category_id as categoryId
+ FROM tags t
+ JOIN media_tags mt ON mt.tag_id = t.id
+ WHERE mt.media_key = ?
+ ORDER BY t.name`
+ )
+ .all(mediaKey) as Tag[]
+
+ const categoryIds = [...new Set(tags.map((t) => t.categoryId))]
+ const categories: TagCategory[] =
+ categoryIds.length > 0
+ ? (db
+ .prepare(
+ `SELECT id, name FROM tag_categories WHERE id IN (${categoryIds.map(() => '?').join(',')}) ORDER BY name`
+ )
+ .all(...categoryIds) as TagCategory[])
+ : []
+
+ return { tags, categories }
+}
+
+export function getTagAssignmentsForLibrary(libraryId: string): Record {
+ const db = getDb()
+ const rows = db
+ .prepare('SELECT media_key, tag_id FROM media_tags WHERE media_key LIKE ?')
+ .all(`${libraryId}:%`) as { media_key: string; tag_id: string }[]
+ const result: Record = {}
+ for (const row of rows) {
+ ;(result[row.media_key] ??= []).push(row.tag_id)
+ }
+ return result
+}
+
+export function removeAllAssignmentsForLibrary(libraryId: string): void {
+ const db = getDb()
+ db.prepare("DELETE FROM media_tags WHERE media_key LIKE ?").run(`${libraryId}:%`)
+}
diff --git a/src/types/index.ts b/src/types/index.ts
index 65f6380..749df2c 100644
--- a/src/types/index.ts
+++ b/src/types/index.ts
@@ -29,3 +29,14 @@ export interface DirectoryListing {
path: string
entries: FileEntry[]
}
+
+export interface TagCategory {
+ id: string
+ name: string
+}
+
+export interface Tag {
+ id: string
+ name: string
+ categoryId: string
+}