diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index e1ea781..d57528b 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -7,28 +7,35 @@ on: jobs: build: - runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + include: + - platform: linux/amd64 + runner: ubuntu-24.04 + - platform: linux/arm64 + runner: ubuntu-24.04-arm + runs-on: ${{ matrix.runner }} permissions: - contents: write + contents: read packages: write steps: - - uses: actions/checkout@v3 + - name: Prepare platform pair + run: | + platform=${{ matrix.platform }} + echo "PLATFORM_PAIR=${platform//\//-}" >> $GITHUB_ENV + + - uses: actions/checkout@v6 - name: Extract version from tag id: version run: echo "VERSION=${GITHUB_REF_NAME#v}" >> $GITHUB_OUTPUT - uses: docker/metadata-action@v5 - name: Docker meta id: meta with: - images: | - ghcr.io/${{ github.repository }} - tags: | - type=raw,value=latest - type=semver,pattern={{major}}.{{minor}}.{{patch}} - type=raw,value=${{ github.ref_name }} + images: ghcr.io/${{ github.repository }} - uses: docker/setup-buildx-action@v3 @@ -38,19 +45,73 @@ jobs: username: ${{ github.actor }} password: ${{ secrets.GITHUB_TOKEN }} - - name: Build and push - uses: docker/build-push-action@v6 + - name: Build and push by digest + id: build + uses: docker/build-push-action@v7 with: context: . - platforms: linux/amd64,linux/arm64 - push: true - tags: ${{ steps.meta.outputs.tags }} + platforms: ${{ matrix.platform }} labels: ${{ steps.meta.outputs.labels }} - cache-from: type=gha - cache-to: type=gha,mode=max + outputs: type=image,name=ghcr.io/${{ github.repository }},push-by-digest=true,name-canonical=true,push=true + cache-from: type=gha,scope=${{ env.PLATFORM_PAIR }} + cache-to: type=gha,mode=max,scope=${{ env.PLATFORM_PAIR }} build-args: | VERSION=${{ steps.version.outputs.VERSION }} + - name: Export digest + run: | + mkdir -p ${{ runner.temp }}/digests + digest="${{ steps.build.outputs.digest }}" + touch "${{ runner.temp }}/digests/${digest#sha256:}" + + - uses: actions/upload-artifact@v4 + with: + name: digests-${{ env.PLATFORM_PAIR }} + path: ${{ runner.temp }}/digests/* + if-no-files-found: error + retention-days: 1 + + merge: + runs-on: ubuntu-24.04 + needs: build + permissions: + contents: write + packages: write + + steps: + - uses: actions/download-artifact@v4 + with: + path: ${{ runner.temp }}/digests + pattern: digests-* + merge-multiple: true + + - uses: docker/setup-buildx-action@v3 + + - uses: docker/login-action@v3 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - uses: docker/metadata-action@v5 + id: meta + with: + images: ghcr.io/${{ github.repository }} + tags: | + type=raw,value=latest + type=semver,pattern={{major}}.{{minor}}.{{patch}} + type=raw,value=${{ github.ref_name }} + + - name: Create manifest list and push + working-directory: ${{ runner.temp }}/digests + run: | + docker buildx imagetools create $(jq -cr '.tags | map("-t " + .) | join(" ")' <<< "$DOCKER_METADATA_OUTPUT_JSON") \ + $(printf 'ghcr.io/${{ github.repository }}@sha256:%s ' *) + + - name: Inspect image + run: | + docker buildx imagetools inspect ghcr.io/${{ github.repository }}:${{ steps.meta.outputs.version }} + - name: Create GitHub Release uses: softprops/action-gh-release@v2 with: diff --git a/README.md b/README.md index 52d4cc5..33e7196 100644 --- a/README.md +++ b/README.md @@ -2,6 +2,9 @@ A unofficial immich client to provide better tools to organize and manage your immich account. Building it to speed up your workflows in Immich to organize your people and albums. +> [!IMPORTANT] +> **Immich v3.0 compatibility:** Power Tools **v0.22.0 and above require Immich 3.0 or newer**. + [Watch Demo Video here](https://www.loom.com/embed/13aa90d8ab2e4acab0993bdc8703a750?sid=71498690-b745-473f-b239-a7bdbe6efc21) [![Immich Power Tools](./screenshots/screenshot-1.png)](https://www.loom.com/embed/13aa90d8ab2e4acab0993bdc8703a750?sid=71498690-b745-473f-b239-a7bdbe6efc21) diff --git a/bun.lock b/bun.lock index 9e17343..975810e 100644 --- a/bun.lock +++ b/bun.lock @@ -39,6 +39,7 @@ "@xyflow/react": "^12.10.2", "ai": "^6.0.146", "axios": "^1.14.0", + "bs58": "^6.0.0", "chrono-node": "^1.4.9", "class-variance-authority": "^0.7.1", "clsx": "^2.1.1", @@ -52,19 +53,20 @@ "jsonwebtoken": "^9.0.3", "leaflet": "^1.9.4", "leaflet.heat": "^0.2.0", + "libsodium-wrappers-sumo": "^0.8.2", "lucide-react": "^0.428.0", "next": "15.5.14", "next-themes": "^0.3.0", "node-cron": "3.0.3", "pg": "^8.20.0", "qs": "^6.15.0", + "rc-mentions": "^2.20.0", "react": "19.2.4", "react-autosuggest": "^10.1.0", "react-day-picker": "9.0.8", "react-dom": "19.2.4", "react-hot-toast": "^2.6.0", "react-leaflet": "^4.2.1", - "react-mentions": "^4.4.10", "react-photo-album": "^3.5.1", "react-window": "^1.8.11", "recharts": "^2.15.4", @@ -80,12 +82,12 @@ "@types/jsonwebtoken": "^9.0.10", "@types/leaflet": "^1.9.21", "@types/leaflet.heat": "^0.2.5", + "@types/libsodium-wrappers-sumo": "^0.8.2", "@types/node": "^20.19.39", "@types/node-cron": "3.0.11", "@types/pg": "^8.20.0", "@types/react": "19.2.14", "@types/react-dom": "19.2.3", - "@types/react-mentions": "^4.4.1", "autoprefixer": "^10.4.27", "drizzle-kit": "^0.31.10", "eslint": "^9.39.4", @@ -117,7 +119,7 @@ "@babel/parser": ["@babel/parser@7.24.1", "", { "bin": "./bin/babel-parser.js" }, "sha512-Zo9c7N3xdOIQrNip7Lc9wvRPzlRtovHVE4lkz8WEDr7uYh/GMQhSiIgFxGIArRHYdJE5kxtZjAf8rT0xhdLCzg=="], - "@babel/runtime": ["@babel/runtime@7.4.5", "", { "dependencies": { "regenerator-runtime": "^0.13.2" } }, "sha512-TuI4qpWZP6lGOGIuGWtp9sPluqYICmbk8T/1vpSysqJxRPkudh/ofFWyqdcMsDf2s7KvDL4/YHgKyvcS3g9CJQ=="], + "@babel/runtime": ["@babel/runtime@7.29.2", "", {}, "sha512-JiDShH45zKHWyGe4ZNVRrCjBz8Nh9TMmZG1kh4QTK8hCBTWBi8Da+i7s1fJw7/lYpM4ccepSNfqzZ/QvABBi5g=="], "@drizzle-team/brocli": ["@drizzle-team/brocli@0.10.2", "", {}, "sha512-z33Il7l5dKjUgGULTqBsQBQwckHh5AbIuxhdsIxDDiZAzBOrZO6q9ogcWC65kU382AfynTfgNumVcNIjuIua6w=="], @@ -459,6 +461,10 @@ "@radix-ui/rect": ["@radix-ui/rect@1.1.1", "", {}, "sha512-HPwpGIzkl28mWyZqG52jiqDJ12waP11Pa1lGoiyUkIEuMLBP0oeK/C89esbXrxsky5we7dfd8U58nm0SgAWpVw=="], + "@rc-component/portal": ["@rc-component/portal@1.1.2", "", { "dependencies": { "@babel/runtime": "^7.18.0", "classnames": "^2.3.2", "rc-util": "^5.24.4" }, "peerDependencies": { "react": ">=16.9.0", "react-dom": ">=16.9.0" } }, "sha512-6f813C0IsasTZms08kfA8kPAGxbbkYToa8ALaiDIGGECU4i9hj8Plgbx0sNJDrey3EtHO30hmdaxtT0138xZcg=="], + + "@rc-component/trigger": ["@rc-component/trigger@2.3.1", "", { "dependencies": { "@babel/runtime": "^7.23.2", "@rc-component/portal": "^1.1.0", "classnames": "^2.3.2", "rc-motion": "^2.0.0", "rc-resize-observer": "^1.3.1", "rc-util": "^5.44.0" }, "peerDependencies": { "react": ">=16.9.0", "react-dom": ">=16.9.0" } }, "sha512-ORENF39PeXTzM+gQEshuk460Z8N4+6DkjpxlpE7Q3gYy1iBpLrx0FOJz3h62ryrJZ/3zCAUIkT1Pb/8hHWpb3A=="], + "@react-leaflet/core": ["@react-leaflet/core@2.1.0", "", { "peerDependencies": { "leaflet": "^1.9.0", "react": "^18.0.0", "react-dom": "^18.0.0" } }, "sha512-Qk7Pfu8BSarKGqILj4x7bCSZ1pjuAPZ+qmRwH5S7mDS91VSbVVsJSrW4qA+GPrro8t69gFYVMWb1Zc4yFmPiVg=="], "@remotion/bundler": ["@remotion/bundler@4.0.232", "", { "dependencies": { "@remotion/studio": "4.0.232", "@remotion/studio-shared": "4.0.232", "css-loader": "5.2.7", "esbuild": "0.18.6", "react-refresh": "0.9.0", "remotion": "4.0.232", "source-map": "0.7.3", "style-loader": "2.0.0", "webpack": "5.96.1" }, "peerDependencies": { "react": ">=16.8.0", "react-dom": ">=16.8.0" } }, "sha512-9Z4O+D2g6cJWFsLsvOy9VOfhgrEZ8YppkuMmE4WJKgh+8r1VpwWcmWp8U/3izCNdB6njI2RVlOUBUxZX0yG94w=="], @@ -561,6 +567,8 @@ "@types/leaflet.heat": ["@types/leaflet.heat@0.2.5", "", { "dependencies": { "@types/leaflet": "^1.9" } }, "sha512-wmDePJPn2vhW9BScsWTV4pSfWayhdDwXuWIQzUuaJkvk5DCHsYsIegTD7tybo38E/0mxpuWODKV/LhsxPESWJg=="], + "@types/libsodium-wrappers-sumo": ["@types/libsodium-wrappers-sumo@0.8.2", "", { "dependencies": { "libsodium-wrappers-sumo": "*" } }, "sha512-uFOBpg/r21hExVlh2ty8YpDfSR+Yy3Jn8XS4+SSjitbhTxdYq+pBz/49XRxyUFe8SzqujHf/Wu0/O4d+FUtNfQ=="], + "@types/ms": ["@types/ms@2.1.0", "", {}, "sha512-GsCCIZDE/p3i96vtEqx+7dBUGXrc7zeSK3wwPHIaRThS+9OhWIXRqzs4d6k1SVU8g91DrNRWxWUGhp5KXQb2VA=="], "@types/node": ["@types/node@20.19.39", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-orrrD74MBUyK8jOAD/r0+lfa1I2MO6I+vAkmAWzMYbCcgrN4lCrmK52gRFQq/JRxfYPfonkr4b0jcY7Olqdqbw=="], @@ -579,8 +587,6 @@ "@types/react-dom": ["@types/react-dom@19.2.3", "", { "peerDependencies": { "@types/react": "^19.2.0" } }, "sha512-jp2L/eY6fn+KgVVQAOqYItbF0VY/YApe5Mz2F0aykSO8gx31bYCZyvSeYxCHKvzHG5eZjc+zyaS5BrBWya2+kQ=="], - "@types/react-mentions": ["@types/react-mentions@4.4.1", "", { "dependencies": { "@types/react": "*" } }, "sha512-65QdcZYkGe2I4GnOLY2OhlXCGz/Csd8NhytwE5r59CoFeYafMltAE/WqFB/Y6SoPU8LvF7EyUrq6Rxrf0Kzxkg=="], - "@types/react-window": ["@types/react-window@1.8.8", "", { "dependencies": { "@types/react": "*" } }, "sha512-8Ls660bHR1AUA2kuRvVG9D/4XpRC6wjAaPT9dil7Ckc76eP9TKWZwwmgfq8Q1LANX3QNDnoU4Zp48A3w+zK69Q=="], "@types/ws": ["@types/ws@8.18.1", "", { "dependencies": { "@types/node": "*" } }, "sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg=="], @@ -749,6 +755,8 @@ "balanced-match": ["balanced-match@1.0.2", "", {}, "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw=="], + "base-x": ["base-x@5.0.1", "", {}, "sha512-M7uio8Zt++eg3jPj+rHMfCC+IuygQHHCOU+IYsVtik6FWjuYpVt/+MRKcgsAMHh8mMFAwnB+Bs+mTrFiXjMzKg=="], + "baseline-browser-mapping": ["baseline-browser-mapping@2.10.15", "", { "bin": { "baseline-browser-mapping": "dist/cli.cjs" } }, "sha512-1nfKCq9wuAZFTkA2ey/3OXXx7GzFjLdkTiFVNwlJ9WqdI706CZRIhEqjuwanjMIja+84jDLa9rcyZDPDiVkASQ=="], "big.js": ["big.js@5.2.2", "", {}, "sha512-vyL2OymJxmarO8gxMr0mhChsO9QGwhynfuu4+MHTAW6czfq9humCB7rKpUjDd9YUiDPU4mzpyupFSvOClAwbmQ=="], @@ -761,6 +769,8 @@ "browserslist": ["browserslist@4.28.2", "", { "dependencies": { "baseline-browser-mapping": "^2.10.12", "caniuse-lite": "^1.0.30001782", "electron-to-chromium": "^1.5.328", "node-releases": "^2.0.36", "update-browserslist-db": "^1.2.3" }, "bin": { "browserslist": "cli.js" } }, "sha512-48xSriZYYg+8qXna9kwqjIVzuQxi+KYWp2+5nCYnYKPTr0LvD89Jqk2Or5ogxz0NUMfIjhh2lIUX/LyX9B4oIg=="], + "bs58": ["bs58@6.0.0", "", { "dependencies": { "base-x": "^5.0.0" } }, "sha512-PD0wEnEYg6ijszw/u8s+iI3H17cTymlrwkKhDhPZq+Sokl3AU4htyBFTjAeNAlCCmg0f53g6ih3jATyCKftTfw=="], + "buffer-crc32": ["buffer-crc32@0.2.13", "", {}, "sha512-VO9Ht/+p3SN7SKWqcrgEzjGbRSJYTx+Q1pTQC0wrWqHx0vpJraQ6GtHx8tvcg1rlK1byhU5gccxgOgj7B0TDkQ=="], "buffer-equal-constant-time": ["buffer-equal-constant-time@1.0.1", "", {}, "sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA=="], @@ -791,6 +801,8 @@ "classcat": ["classcat@5.0.5", "", {}, "sha512-JhZUT7JFcQy/EzW605k/ktHtncoo9vnyW/2GspNYwFlN1C/WmjuV/xtS04e9SOkL2sTdw0VAZ2UGCcQ9lR6p6w=="], + "classnames": ["classnames@2.5.1", "", {}, "sha512-saHYOzhIQs6wy2sVxTM6bUDsQO4F50V9RQ22qBpEdCW+I+/Wmke2HOl6lS6dTpdxVhb88/I6+Hs+438c3lfUow=="], + "client-only": ["client-only@0.0.1", "", {}, "sha512-IV3Ou0jSMzZrd3pZ48nLkT9DA7Ag1pnPzaiQhpW7c3RbcqqzvzzVu+L8gfqMp/8IM2MQtSiqaCxrrcfu8I8rMA=="], "clsx": ["clsx@2.1.1", "", {}, "sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA=="], @@ -1105,8 +1117,6 @@ "internmap": ["internmap@2.0.3", "", {}, "sha512-5Hh7Y1wQbvY5ooGgPbDaL5iYLAPzMTUrjMulskHLH6wnv/A+1q5rgEaiuqEjB+oxGXIVZs1FF+R/KPN3ZSQYYg=="], - "invariant": ["invariant@2.2.4", "", { "dependencies": { "loose-envify": "^1.0.0" } }, "sha512-phJfQVBuaJM5raOpJjSfkiD6BpbCE4Ns//LaXl6wGYtUBY83nWS6Rf9tXm2e8VaK60JEjYldbPif/A2B1C2gNA=="], - "is-array-buffer": ["is-array-buffer@3.0.5", "", { "dependencies": { "call-bind": "^1.0.8", "call-bound": "^1.0.3", "get-intrinsic": "^1.2.6" } }, "sha512-DDfANUiiG2wC1qawP66qlTugJeL5HyzMpfr8lLK+jMQirGzNod0B12cFB/9q838Ru27sBwfw78/rdoU7RERz6A=="], "is-async-function": ["is-async-function@2.1.1", "", { "dependencies": { "async-function": "^1.0.0", "call-bound": "^1.0.3", "get-proto": "^1.0.1", "has-tostringtag": "^1.0.2", "safe-regex-test": "^1.1.0" } }, "sha512-9dgM/cZBnNvjzaMYHVoxxfPj2QXt22Ev7SuuPrs+xav0ukGB0S6d4ydZdEiM48kLx5kDV+QBPrpVnFyefL8kkQ=="], @@ -1217,6 +1227,10 @@ "levn": ["levn@0.4.1", "", { "dependencies": { "prelude-ls": "^1.2.1", "type-check": "~0.4.0" } }, "sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ=="], + "libsodium-sumo": ["libsodium-sumo@0.8.2", "", {}, "sha512-uMgnjphJ717jLN+jFG1HUgNrK/gOVVfaO1DGZ1Ig/fKLKLVhvaH/sM1I1v784JFvmkJDaczDpi7xSYC4Jvdo1Q=="], + + "libsodium-wrappers-sumo": ["libsodium-wrappers-sumo@0.8.2", "", { "dependencies": { "libsodium-sumo": "^0.8.0" } }, "sha512-wd1xAY++Kr6VMikSaa4EPRAHJmFvNlGWiiwU3Jh3GR1zRYF3/I3vy/wYsr4k3LVsNzwb9sqfEQ4LdVQ6zEebyQ=="], + "libsql": ["libsql@0.5.29", "", { "dependencies": { "@neon-rs/load": "^0.0.4", "detect-libc": "2.0.2" }, "optionalDependencies": { "@libsql/darwin-arm64": "0.5.29", "@libsql/darwin-x64": "0.5.29", "@libsql/linux-arm-gnueabihf": "0.5.29", "@libsql/linux-arm-musleabihf": "0.5.29", "@libsql/linux-arm64-gnu": "0.5.29", "@libsql/linux-arm64-musl": "0.5.29", "@libsql/linux-x64-gnu": "0.5.29", "@libsql/linux-x64-musl": "0.5.29", "@libsql/win32-x64-msvc": "0.5.29" }, "os": [ "linux", "win32", "darwin", ], "cpu": [ "arm", "x64", "arm64", ] }, "sha512-8lMP8iMgiBzzoNbAPQ59qdVcj6UaE/Vnm+fiwX4doX4Narook0a4GPKWBEv+CR8a1OwbfkgL18uBfBjWdF0Fzg=="], "lilconfig": ["lilconfig@3.1.3", "", {}, "sha512-/vlFKAoH5Cgt3Ie+JLhRbwOsCQePABiU3tJ1egGvyQ+33R/vcwM2Zl2QR/LzjsBeItPt3oSVXapn+m4nQDvpzw=="], @@ -1431,6 +1445,22 @@ "queue-microtask": ["queue-microtask@1.2.3", "", {}, "sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A=="], + "rc-input": ["rc-input@1.8.0", "", { "dependencies": { "@babel/runtime": "^7.11.1", "classnames": "^2.2.1", "rc-util": "^5.18.1" }, "peerDependencies": { "react": ">=16.0.0", "react-dom": ">=16.0.0" } }, "sha512-KXvaTbX+7ha8a/k+eg6SYRVERK0NddX8QX7a7AnRvUa/rEH0CNMlpcBzBkhI0wp2C8C4HlMoYl8TImSN+fuHKA=="], + + "rc-mentions": ["rc-mentions@2.20.0", "", { "dependencies": { "@babel/runtime": "^7.22.5", "@rc-component/trigger": "^2.0.0", "classnames": "^2.2.6", "rc-input": "~1.8.0", "rc-menu": "~9.16.0", "rc-textarea": "~1.10.0", "rc-util": "^5.34.1" }, "peerDependencies": { "react": ">=16.9.0", "react-dom": ">=16.9.0" } }, "sha512-w8HCMZEh3f0nR8ZEd466ATqmXFCMGMN5UFCzEUL0bM/nGw/wOS2GgRzKBcm19K++jDyuWCOJOdgcKGXU3fXfbQ=="], + + "rc-menu": ["rc-menu@9.16.1", "", { "dependencies": { "@babel/runtime": "^7.10.1", "@rc-component/trigger": "^2.0.0", "classnames": "2.x", "rc-motion": "^2.4.3", "rc-overflow": "^1.3.1", "rc-util": "^5.27.0" }, "peerDependencies": { "react": ">=16.9.0", "react-dom": ">=16.9.0" } }, "sha512-ghHx6/6Dvp+fw8CJhDUHFHDJ84hJE3BXNCzSgLdmNiFErWSOaZNsihDAsKq9ByTALo/xkNIwtDFGIl6r+RPXBg=="], + + "rc-motion": ["rc-motion@2.9.5", "", { "dependencies": { "@babel/runtime": "^7.11.1", "classnames": "^2.2.1", "rc-util": "^5.44.0" }, "peerDependencies": { "react": ">=16.9.0", "react-dom": ">=16.9.0" } }, "sha512-w+XTUrfh7ArbYEd2582uDrEhmBHwK1ZENJiSJVb7uRxdE7qJSYjbO2eksRXmndqyKqKoYPc9ClpPh5242mV1vA=="], + + "rc-overflow": ["rc-overflow@1.5.0", "", { "dependencies": { "@babel/runtime": "^7.11.1", "classnames": "^2.2.1", "rc-resize-observer": "^1.0.0", "rc-util": "^5.37.0" }, "peerDependencies": { "react": ">=16.9.0", "react-dom": ">=16.9.0" } }, "sha512-Lm/v9h0LymeUYJf0x39OveU52InkdRXqnn2aYXfWmo8WdOonIKB2kfau+GF0fWq6jPgtdO9yMqveGcK6aIhJmg=="], + + "rc-resize-observer": ["rc-resize-observer@1.4.3", "", { "dependencies": { "@babel/runtime": "^7.20.7", "classnames": "^2.2.1", "rc-util": "^5.44.1", "resize-observer-polyfill": "^1.5.1" }, "peerDependencies": { "react": ">=16.9.0", "react-dom": ">=16.9.0" } }, "sha512-YZLjUbyIWox8E9i9C3Tm7ia+W7euPItNWSPX5sCcQTYbnwDb5uNpnLHQCG1f22oZWUhLw4Mv2tFmeWe68CDQRQ=="], + + "rc-textarea": ["rc-textarea@1.10.2", "", { "dependencies": { "@babel/runtime": "^7.10.1", "classnames": "^2.2.1", "rc-input": "~1.8.0", "rc-resize-observer": "^1.0.0", "rc-util": "^5.27.0" }, "peerDependencies": { "react": ">=16.9.0", "react-dom": ">=16.9.0" } }, "sha512-HfaeXiaSlpiSp0I/pvWpecFEHpVysZ9tpDLNkxQbMvMz6gsr7aVZ7FpWP9kt4t7DB+jJXesYS0us1uPZnlRnwQ=="], + + "rc-util": ["rc-util@5.44.4", "", { "dependencies": { "@babel/runtime": "^7.18.3", "react-is": "^18.2.0" }, "peerDependencies": { "react": ">=16.9.0", "react-dom": ">=16.9.0" } }, "sha512-resueRJzmHG9Q6rI/DfK6Kdv9/Lfls05vzMs1Sk3M2P+3cJa+MakaZyWY8IPfehVuhPJFKrIY1IK4GqbiaiY5w=="], + "react": ["react@19.2.4", "", {}, "sha512-9nfp2hYpCwOjAN+8TZFGhtWEwgvWHXqESH8qT89AT/lWklpLON22Lc8pEtnpsZz7VmawabSU0gCjnj8aC0euHQ=="], "react-autosuggest": ["react-autosuggest@10.1.0", "", { "dependencies": { "es6-promise": "^4.2.8", "prop-types": "^15.7.2", "react-themeable": "^1.1.0", "section-iterator": "^2.0.0", "shallow-equal": "^1.2.1" }, "peerDependencies": { "react": ">=16.3.0" } }, "sha512-/azBHmc6z/31s/lBf6irxPf/7eejQdR0IqnZUzjdSibtlS8+Rw/R79pgDAo6Ft5QqCUTyEQ+f0FhL+1olDQ8OA=="], @@ -1445,8 +1475,6 @@ "react-leaflet": ["react-leaflet@4.2.1", "", { "dependencies": { "@react-leaflet/core": "^2.1.0" }, "peerDependencies": { "leaflet": "^1.9.0", "react": "^18.0.0", "react-dom": "^18.0.0" } }, "sha512-p9chkvhcKrWn/H/1FFeVSqLdReGwn2qmiobOQGO3BifX+/vV/39qhY8dGqbdcPh1e6jxh/QHriLXr7a4eLFK4Q=="], - "react-mentions": ["react-mentions@4.4.10", "", { "dependencies": { "@babel/runtime": "7.4.5", "invariant": "^2.2.4", "prop-types": "^15.5.8", "substyle": "^9.1.0" }, "peerDependencies": { "react": ">=16.8.3", "react-dom": ">=16.8.3" } }, "sha512-JHiQlgF1oSZR7VYPjq32wy97z1w1oE4x10EuhKjPr4WUKhVzG1uFQhQjKqjQkbVqJrmahf+ldgBTv36NrkpKpA=="], - "react-photo-album": ["react-photo-album@3.5.1", "", { "peerDependencies": { "@types/react": "^18 || ^19", "react": "^18 || ^19" }, "optionalPeers": ["@types/react"] }, "sha512-g1uFG+loxdIb8eIOGnrh/71Ao80+XWV+NLfluY9qDDTbS76m+X1K6dpfNtsx1xKr9aw5N1ornkFTWpfyqOoD5Q=="], "react-refresh": ["react-refresh@0.9.0", "", {}, "sha512-Gvzk7OZpiqKSkxsQvO/mbTN1poglhmAV7gR/DdIrRrSMXraRQQlfikRJOr3Nb9GTMPC5kof948Zy6jJZIFtDvQ=="], @@ -1477,14 +1505,14 @@ "reflect.getprototypeof": ["reflect.getprototypeof@1.0.10", "", { "dependencies": { "call-bind": "^1.0.8", "define-properties": "^1.2.1", "es-abstract": "^1.23.9", "es-errors": "^1.3.0", "es-object-atoms": "^1.0.0", "get-intrinsic": "^1.2.7", "get-proto": "^1.0.1", "which-builtin-type": "^1.2.1" } }, "sha512-00o4I+DVrefhv+nX0ulyi3biSHCPDe+yLv5o/p6d/UVlirijB8E16FtfwSAi4g3tcqrQ4lRAqQSoFEZJehYEcw=="], - "regenerator-runtime": ["regenerator-runtime@0.13.11", "", {}, "sha512-kY1AZVr2Ra+t+piVaJ4gxaFaReZVH40AKNo7UCX6W+dEwBo/2oZJzqfuN1qLq1oL45o56cPaTXELwrTh8Fpggg=="], - "regexp.prototype.flags": ["regexp.prototype.flags@1.5.4", "", { "dependencies": { "call-bind": "^1.0.8", "define-properties": "^1.2.1", "es-errors": "^1.3.0", "get-proto": "^1.0.1", "gopd": "^1.2.0", "set-function-name": "^2.0.2" } }, "sha512-dYqgNSZbDwkaJ2ceRd9ojCGjBq+mOm9LmtXnAnEGyHhN/5R7iDW2TRw3h+o/jCFxus3P2LfWIIiwowAjANm7IA=="], "remotion": ["remotion@4.0.232", "", { "peerDependencies": { "react": ">=16.8.0", "react-dom": ">=16.8.0" } }, "sha512-tuWZ5kQckqDL8/Zq1xLeUF+Bed1dN1sZeJ5nNbO0aBw1ETXNVrlJeobzt72lZDKZ+coU8k7sPWrIq65td1y9Gg=="], "require-from-string": ["require-from-string@2.0.2", "", {}, "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw=="], + "resize-observer-polyfill": ["resize-observer-polyfill@1.5.1", "", {}, "sha512-LwZrotdHOo12nQuZlHEmtuXdqGoOD0OhaxopaNFxWzInpEgaLWoVuAMbTzixuosCx2nEG58ngzW3vxdWoxIgdg=="], + "resolve": ["resolve@1.22.11", "", { "dependencies": { "is-core-module": "^2.16.1", "path-parse": "^1.0.7", "supports-preserve-symlinks-flag": "^1.0.0" }, "bin": { "resolve": "bin/resolve" } }, "sha512-RfqAvLnMl313r7c9oclB1HhUEAezcpLjz95wFH4LVuhk9JF/r22qmVP9AMmOU4vMX7Q8pN8jwNg/CSpdFnMjTQ=="], "resolve-from": ["resolve-from@4.0.0", "", {}, "sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g=="], @@ -1577,8 +1605,6 @@ "styled-jsx": ["styled-jsx@5.1.6", "", { "dependencies": { "client-only": "0.0.1" }, "peerDependencies": { "react": ">= 16.8.0 || 17.x.x || ^18.0.0-0 || ^19.0.0-0" } }, "sha512-qSVyDTeMotdvQYoHWLNGwRFJHC+i+ZvdBRYosOFgC+Wg1vx4frN2/RG/NA7SYqqvKNLf39P2LSRA2pu6n0XYZA=="], - "substyle": ["substyle@9.4.1", "", { "dependencies": { "@babel/runtime": "^7.3.4", "invariant": "^2.2.4" }, "peerDependencies": { "react": ">=16.8.3" } }, "sha512-VOngeq/W1/UkxiGzeqVvDbGDPM8XgUyJVWjrqeh+GgKqspEPiLYndK+XRcsKUHM5Muz/++1ctJ1QCF/OqRiKWA=="], - "sucrase": ["sucrase@3.35.1", "", { "dependencies": { "@jridgewell/gen-mapping": "^0.3.2", "commander": "^4.0.0", "lines-and-columns": "^1.1.6", "mz": "^2.7.0", "pirates": "^4.0.1", "tinyglobby": "^0.2.11", "ts-interface-checker": "^0.1.9" }, "bin": { "sucrase": "bin/sucrase", "sucrase-node": "bin/sucrase-node" } }, "sha512-DhuTmvZWux4H1UOnWMB3sk0sbaCVOoQZjv8u1rDoTV0HTdGem9hkAZtl4JZy8P2z4Bg0nT+YMeOFyVr4zcG5Tw=="], "supports-color": ["supports-color@7.2.0", "", { "dependencies": { "has-flag": "^4.0.0" } }, "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw=="], @@ -1763,8 +1789,6 @@ "css-loader/semver": ["semver@7.7.4", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA=="], - "dom-helpers/@babel/runtime": ["@babel/runtime@7.29.2", "", {}, "sha512-JiDShH45zKHWyGe4ZNVRrCjBz8Nh9TMmZG1kh4QTK8hCBTWBi8Da+i7s1fJw7/lYpM4ccepSNfqzZ/QvABBi5g=="], - "eslint-import-resolver-node/debug": ["debug@3.2.7", "", { "dependencies": { "ms": "^2.1.1" } }, "sha512-CFjzYYAi4ThfiQvizrFQevTTXHtnCqWfe7x1AhgEscTz6ZbLbfoLRLPugTQyBth6f8ZERVUSyWHFD/7Wu4t1XQ=="], "eslint-import-resolver-node/resolve": ["resolve@2.0.0-next.6", "", { "dependencies": { "es-errors": "^1.3.0", "is-core-module": "^2.16.1", "node-exports-info": "^1.6.0", "object-keys": "^1.1.1", "path-parse": "^1.0.7", "supports-preserve-symlinks-flag": "^1.0.0" }, "bin": { "resolve": "bin/resolve" } }, "sha512-3JmVl5hMGtJ3kMmB3zi3DL25KfkCEyy3Tw7Gmw7z5w8M9WlwoPFnIvwChzu1+cF3iaK3sp18hhPz8ANeimdJfA=="], @@ -1799,10 +1823,6 @@ "react-themeable/object-assign": ["object-assign@3.0.0", "", {}, "sha512-jHP15vXVGeVh1HuaA2wY6lxk+whK/x4KBG88VXeRma7CCun7iGD5qPc4eYykQ9sdQvg8jkwFKsSxHln2ybW3xQ=="], - "react-transition-group/@babel/runtime": ["@babel/runtime@7.29.2", "", {}, "sha512-JiDShH45zKHWyGe4ZNVRrCjBz8Nh9TMmZG1kh4QTK8hCBTWBi8Da+i7s1fJw7/lYpM4ccepSNfqzZ/QvABBi5g=="], - - "react-window/@babel/runtime": ["@babel/runtime@7.29.2", "", {}, "sha512-JiDShH45zKHWyGe4ZNVRrCjBz8Nh9TMmZG1kh4QTK8hCBTWBi8Da+i7s1fJw7/lYpM4ccepSNfqzZ/QvABBi5g=="], - "recast/source-map": ["source-map@0.6.1", "", {}, "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g=="], "sass/chokidar": ["chokidar@4.0.3", "", { "dependencies": { "readdirp": "^4.0.1" } }, "sha512-Qgzu8kfBvo+cA4962jnP1KkS6Dop5NS6g7R5LFYJr4b8Ub94PPQXUksCw9PvXoeXPRRddRNC5C1JQUR2SMGtnA=="], @@ -1813,8 +1833,6 @@ "source-map-support/source-map": ["source-map@0.6.1", "", {}, "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g=="], - "substyle/@babel/runtime": ["@babel/runtime@7.29.2", "", {}, "sha512-JiDShH45zKHWyGe4ZNVRrCjBz8Nh9TMmZG1kh4QTK8hCBTWBi8Da+i7s1fJw7/lYpM4ccepSNfqzZ/QvABBi5g=="], - "terser/commander": ["commander@2.20.3", "", {}, "sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ=="], "terser-webpack-plugin/schema-utils": ["schema-utils@4.3.3", "", { "dependencies": { "@types/json-schema": "^7.0.9", "ajv": "^8.9.0", "ajv-formats": "^2.1.1", "ajv-keywords": "^5.1.0" } }, "sha512-eflK8wEtyOE6+hsaRVPxvUKYCpRgzLqDTb8krvAsRIwOGlHoSgYLgBXoubGgLd2fT41/OUYdb48v4k4WWHQurA=="], @@ -1929,8 +1947,6 @@ "ajv-formats/ajv/json-schema-traverse": ["json-schema-traverse@1.0.0", "", {}, "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug=="], - "cmdk/@radix-ui/react-dialog/@babel/runtime": ["@babel/runtime@7.29.2", "", {}, "sha512-JiDShH45zKHWyGe4ZNVRrCjBz8Nh9TMmZG1kh4QTK8hCBTWBi8Da+i7s1fJw7/lYpM4ccepSNfqzZ/QvABBi5g=="], - "cmdk/@radix-ui/react-dialog/@radix-ui/primitive": ["@radix-ui/primitive@1.0.1", "", { "dependencies": { "@babel/runtime": "^7.13.10" } }, "sha512-yQ8oGX2GVsEYMWGxcovu1uGWPCxV5BFfeeYxqPmuAzUyLT9qmaMXSAhXpb0WrspIeqYzdJpkh2vHModJPgRIaw=="], "cmdk/@radix-ui/react-dialog/@radix-ui/react-compose-refs": ["@radix-ui/react-compose-refs@1.0.1", "", { "dependencies": { "@babel/runtime": "^7.13.10" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0" }, "optionalPeers": ["@types/react"] }, "sha512-fDSBgd44FKHa1FRMU59qBMPFcl2PZE+2nmqunj+BWFyYYjnhIDWL2ItDs3rrbJDQOtzt5nIebLCQc4QRfz6LJw=="], @@ -1955,8 +1971,6 @@ "cmdk/@radix-ui/react-dialog/react-remove-scroll": ["react-remove-scroll@2.5.5", "", { "dependencies": { "react-remove-scroll-bar": "^2.3.3", "react-style-singleton": "^2.2.1", "tslib": "^2.1.0", "use-callback-ref": "^1.3.0", "use-sidecar": "^1.1.2" }, "peerDependencies": { "@types/react": "^16.8.0 || ^17.0.0 || ^18.0.0", "react": "^16.8.0 || ^17.0.0 || ^18.0.0" }, "optionalPeers": ["@types/react"] }, "sha512-ImKhrzJJsyXJfBZ4bzu8Bwpka14c/fQt0k+cyFp/PBhTfyDnU5hjOtM4AG/0AMyy8oKzOTR0lDgJIM7pYXI0kw=="], - "cmdk/@radix-ui/react-primitive/@babel/runtime": ["@babel/runtime@7.29.2", "", {}, "sha512-JiDShH45zKHWyGe4ZNVRrCjBz8Nh9TMmZG1kh4QTK8hCBTWBi8Da+i7s1fJw7/lYpM4ccepSNfqzZ/QvABBi5g=="], - "cmdk/@radix-ui/react-primitive/@radix-ui/react-slot": ["@radix-ui/react-slot@1.0.2", "", { "dependencies": { "@babel/runtime": "^7.13.10", "@radix-ui/react-compose-refs": "1.0.1" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0" }, "optionalPeers": ["@types/react"] }, "sha512-YeTpuq4deV+6DusvVUW4ivBgnkHwECUu0BiN43L5UCDFgdhsRUWAghhTF5MbvNTPzmiFOx90asDSUjWuCNapwg=="], "cross-fetch/node-fetch/whatwg-url": ["whatwg-url@5.0.0", "", { "dependencies": { "tr46": "~0.0.3", "webidl-conversions": "^3.0.0" } }, "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw=="], diff --git a/package.json b/package.json index 757748a..7fbb851 100644 --- a/package.json +++ b/package.json @@ -51,6 +51,7 @@ "@xyflow/react": "^12.10.2", "ai": "^6.0.146", "axios": "^1.14.0", + "bs58": "^6.0.0", "chrono-node": "^1.4.9", "class-variance-authority": "^0.7.1", "clsx": "^2.1.1", @@ -64,19 +65,20 @@ "jsonwebtoken": "^9.0.3", "leaflet": "^1.9.4", "leaflet.heat": "^0.2.0", + "libsodium-wrappers-sumo": "^0.8.2", "lucide-react": "^0.428.0", "next": "15.5.14", "next-themes": "^0.3.0", "node-cron": "3.0.3", "pg": "^8.20.0", "qs": "^6.15.0", + "rc-mentions": "^2.20.0", "react": "19.2.4", "react-autosuggest": "^10.1.0", "react-day-picker": "9.0.8", "react-dom": "19.2.4", "react-hot-toast": "^2.6.0", "react-leaflet": "^4.2.1", - "react-mentions": "^4.4.10", "react-photo-album": "^3.5.1", "react-window": "^1.8.11", "recharts": "^2.15.4", @@ -92,12 +94,12 @@ "@types/jsonwebtoken": "^9.0.10", "@types/leaflet": "^1.9.21", "@types/leaflet.heat": "^0.2.5", + "@types/libsodium-wrappers-sumo": "^0.8.2", "@types/node": "^20.19.39", "@types/node-cron": "3.0.11", "@types/pg": "^8.20.0", "@types/react": "19.2.14", "@types/react-dom": "19.2.3", - "@types/react-mentions": "^4.4.1", "autoprefixer": "^10.4.27", "drizzle-kit": "^0.31.10", "eslint": "^9.39.4", diff --git a/src/components/albums/AlbumTableColumns.tsx b/src/components/albums/AlbumTableColumns.tsx index 2109247..7ed9bb6 100644 --- a/src/components/albums/AlbumTableColumns.tsx +++ b/src/components/albums/AlbumTableColumns.tsx @@ -2,7 +2,7 @@ import { ColumnDef } from "@tanstack/react-table" import { IAlbum } from "@/types/album" import { Button } from "@/components/ui/button" import { Checkbox } from "@/components/ui/checkbox" -import { ArrowUpDown, MoreHorizontal, Calendar, Camera, Users, HardDrive } from "lucide-react" +import { ArrowUpDown, MoreHorizontal, Calendar, Camera, Users, HardDrive, ImageOff } from "lucide-react" import { DropdownMenu, DropdownMenuContent, @@ -48,15 +48,21 @@ export const albumColumns: ColumnDef[] = [ const album = row.original return (
- + {album.albumThumbnailAssetId ? ( + + ) : ( +
+ +
+ )}
) }, @@ -164,16 +170,20 @@ export const albumColumns: ColumnDef[] = [ }, cell: ({ row }) => { const album = row.original - const numberOfDays = differenceInDays(album.lastPhotoDate, album.firstPhotoDate) - + const numberOfDays = (album.firstPhotoDate && album.lastPhotoDate) + ? differenceInDays(album.lastPhotoDate, album.firstPhotoDate) + : null + return (
{album.firstPhotoDate ? formatDate(album.firstPhotoDate.toString(), 'MMM d, yyyy') : ''} - {album.lastPhotoDate ? formatDate(album.lastPhotoDate.toString(), 'MMM d, yyyy') : ''}
-
- {numberOfDays === 0 ? '1 day' : `${numberOfDays.toLocaleString()} days`} -
+ {numberOfDays !== null && ( +
+ {numberOfDays === 0 ? '1 day' : `${numberOfDays.toLocaleString()} days`} +
+ )}
) }, diff --git a/src/components/albums/list/AlbumThumbnail.tsx b/src/components/albums/list/AlbumThumbnail.tsx index af70d22..45dbb0e 100644 --- a/src/components/albums/list/AlbumThumbnail.tsx +++ b/src/components/albums/list/AlbumThumbnail.tsx @@ -8,7 +8,7 @@ import { IAlbum } from '@/types/album'; import { formatDate } from '@/helpers/date.helper'; import { Checkbox } from '@/components/ui/checkbox'; import { differenceInDays } from 'date-fns'; -import { Calendar, Camera } from 'lucide-react'; +import { Calendar, Camera, ImageOff } from 'lucide-react'; interface IAlbumThumbnailProps { album: IAlbum; @@ -18,6 +18,9 @@ interface IAlbumThumbnailProps { export default function AlbumThumbnail({ album, onSelect, selected }: IAlbumThumbnailProps) { const numberOfDays = useMemo(() => { + if (!album.firstPhotoDate || !album.lastPhotoDate) { + return null; + } return differenceInDays(album.lastPhotoDate, album.firstPhotoDate); }, [album.firstPhotoDate, album.lastPhotoDate]); @@ -29,16 +32,27 @@ export default function AlbumThumbnail({ album, onSelect, selected }: IAlbumThum return (
-

- {numberOfDays === 0 ? '1 day' : `${numberOfDays.toLocaleString() } days`} -

+ {numberOfDays !== null && ( +

+ {numberOfDays === 0 ? '1 day' : `${numberOfDays.toLocaleString() } days`} +

+ )}
diff --git a/src/components/analytics/exif/AssetHeatMap.tsx b/src/components/analytics/exif/AssetHeatMap.tsx index 1418185..3b06679 100644 --- a/src/components/analytics/exif/AssetHeatMap.tsx +++ b/src/components/analytics/exif/AssetHeatMap.tsx @@ -1,13 +1,16 @@ -import React, { useEffect, useState } from "react"; +import React, { useEffect, useMemo, useState } from "react"; import { getHeatMapData } from "@/handlers/api/analytics.handler"; import { useConfig } from "@/contexts/ConfigContext"; import { Tooltip } from "@/components/ui/tooltip"; +import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"; type HeatMapEntry = { date: string; count: number; }; +const ROLLING = "rolling" as const; + const COLOR_SCALE = [ "bg-zinc-100 dark:bg-zinc-800/60", "bg-emerald-200 dark:bg-emerald-900/70", @@ -25,29 +28,39 @@ export default function AssetHeatMap() { const [heatMapData, setHeatMapData] = useState([]); const [loading, setLoading] = useState(false); const [weeksPerMonth, setWeeksPerMonth] = useState([]); + const [availableYears, setAvailableYears] = useState([]); + const [selection, setSelection] = useState(ROLLING); - const fetchHeatMapData = async () => { + const fetchHeatMapData = async (sel: typeof ROLLING | number) => { setLoading(true); try { - const data = await getHeatMapData(); - setHeatMapData(formatHeatMapData(data)); + const resp = await getHeatMapData(sel === ROLLING ? undefined : sel); + setAvailableYears(resp.availableYears ?? []); + setHeatMapData(formatHeatMapData(resp.data)); } finally { setLoading(false); } }; useEffect(() => { - fetchHeatMapData(); - }, []); + fetchHeatMapData(selection); + }, [selection]); - const currentDate = new Date(); - const months: string[] = []; - - for (let i = 0; i < 12; i++) { - months.push(currentDate.toLocaleString("default", { month: "short" })); - currentDate.setMonth(currentDate.getMonth() - 1); - } - months.reverse(); + const months = useMemo(() => { + if (selection === ROLLING) { + const cursor = new Date(); + const out: string[] = []; + for (let i = 0; i < 12; i++) { + out.push(cursor.toLocaleString("default", { month: "short" })); + cursor.setMonth(cursor.getMonth() - 1); + } + return out.reverse(); + } + // Calendar year: Jan-Dec in order. + return Array.from({ length: 12 }, (_, i) => + new Date(selection, i, 1).toLocaleString("default", { month: "short" }) + ); + }, [selection]); const flattenedData = heatMapData.flat(); const minCount = Math.min(...flattenedData.map((entry) => entry.count)); @@ -106,6 +119,24 @@ export default function AssetHeatMap() { return (
+
+ +
diff --git a/src/components/find/FindInput.tsx b/src/components/find/FindInput.tsx index fa75919..b5a8ed2 100644 --- a/src/components/find/FindInput.tsx +++ b/src/components/find/FindInput.tsx @@ -1,50 +1,106 @@ -import React, { useState } from 'react' -import inputStyle from './findInputStyle' -import { MentionsInput, Mention } from 'react-mentions' -import { searchPeople } from '@/handlers/api/people.handler'; -import mentionStyle from './findMentionStyle'; +import React from 'react' +import Mentions from 'rc-mentions' +import { listPeople, searchPeople } from '@/handlers/api/people.handler' +import { ArrowRight, Loader2, Search, X } from 'lucide-react' +import { cn } from '@/lib/utils' interface FindInputProps { onSearch: (query: string) => void; value: string; onChange: (value: string) => void; + loading?: boolean; } -export default function FindInput({ onSearch, value, onChange }: FindInputProps) { +export default function FindInput({ onSearch, value, onChange, loading }: FindInputProps) { + const [options, setOptions] = React.useState<{ value: string; label: string }[]>([]) + const [focused, setFocused] = React.useState(false) + const nameToIdRef = React.useRef>({}) - const handleSearchPeople = async (e: any, callback: any) => { - if (!e.length) return []; - return searchPeople(e).then((people) => people.map((person: any) => ({ - id: person.id, - display: person.name, - }))).then((people) => callback(people)); + const handleMentionSearch = async (text: string, prefix: string) => { + if (prefix !== '@') { + setOptions([]) + return + } + const people = text.length + ? await searchPeople(text) + : await listPeople({ page: 1, perPage: 50, sort: 'assetCount', sortOrder: 'desc' }).then((r) => r.people) + people.forEach((person: any) => { + if (person.name) nameToIdRef.current[person.name] = person.id + }) + setOptions( + people + .filter((person: any) => person.name) + .map((person: any) => ({ + value: person.name, + label: person.name, + })) + ) + } + + const handleClear = () => { + onChange('') + } + + const buildQueryWithIds = (displayValue: string) => { + let query = displayValue + for (const [name, id] of Object.entries(nameToIdRef.current)) { + query = query.replaceAll(`@${name}`, `@${id}`) + } + return query + } + + const handleSubmit = () => { + if (value.trim()) { + onSearch(buildQueryWithIds(value)) + } + } + + const handleKeyDown = (e: React.KeyboardEvent) => { + if (e.key === 'Enter') { + e.preventDefault() + handleSubmit() + } } return ( - { - if (e.key === 'Enter') { - onSearch(value); - } - }} - onChange={(e) => onChange(e.target.value)}> - ( -
- {highlightedDisplay.display} -
- )} +
+ + setFocused(true)} + onBlur={() => setFocused(false)} + options={options} + rows={1} /> - + {value && !loading && ( + + )} + +
) } diff --git a/src/components/find/findInputStyle.ts b/src/components/find/findInputStyle.ts deleted file mode 100644 index 4d44afe..0000000 --- a/src/components/find/findInputStyle.ts +++ /dev/null @@ -1,45 +0,0 @@ -const findInputStyle = { - control: { - backgroundColor: 'hsl(var(--input))', - fontSize: 20, - fontWeight: 'normal', - outline: 'none', - borderRadius: '15px', - - }, - - '&singleLine': { - // display: 'inline-block', - width: '100%', - - highlighter: { - padding: '10px 15px', - border: 'none', - outline: 'none', - }, - input: { - padding: '10px 15px', - border: 'none', - outline: 'none', - }, - }, - - suggestions: { - - list: { - backgroundColor: 'hsl(var(--background))', - fontSize: 14, - border: '1px solid hsl(var(--border))', - overflow: 'hidden', - }, - item: { - padding: '5px 15px', - border: 'none', - '&focused': { - backgroundColor: 'hsl(var(--chart-2))', - }, - }, - }, -} - -export default findInputStyle; \ No newline at end of file diff --git a/src/components/find/findMentionStyle.ts b/src/components/find/findMentionStyle.ts deleted file mode 100644 index 7dc4486..0000000 --- a/src/components/find/findMentionStyle.ts +++ /dev/null @@ -1,6 +0,0 @@ -const mentionStyle: React.CSSProperties = { - backgroundColor: 'hsla(var(--chart-2) / 0.3)', - position: 'relative', -} - -export default mentionStyle; \ No newline at end of file diff --git a/src/components/people/PeopleFilters.tsx b/src/components/people/PeopleFilters.tsx index c3ab871..d0db79c 100644 --- a/src/components/people/PeopleFilters.tsx +++ b/src/components/people/PeopleFilters.tsx @@ -23,19 +23,24 @@ export function PeopleFilters() { const { updateContext, page, maximumAssetCount, type = "all", query = "", visibility = "all" } = filters; const handleChange = (data: Partial) => { - updateContext(data); + // Any filter change other than an explicit page navigation must reset + // pagination: without this, typing a name while on page 2 keeps page=2 + // and the now-smaller result set returns nothing until the user clicks + // back to page 1 manually. + const nextData = "page" in data ? data : { ...data, page: 1 }; + updateContext(nextData); router.push({ pathname: router.pathname, query: { ...router.query, - ...data, - page: data.page || undefined, - type: data.type || undefined, - visibility: data.visibility || undefined, - query: data.query || undefined, - maximumAssetCount: data.maximumAssetCount || undefined, - sort: data.sort || undefined, - sortOrder: data.sortOrder || undefined, + ...nextData, + page: nextData.page || undefined, + type: nextData.type || undefined, + visibility: nextData.visibility || undefined, + query: nextData.query || undefined, + maximumAssetCount: nextData.maximumAssetCount || undefined, + sort: nextData.sort || undefined, + sortOrder: nextData.sortOrder || undefined, }, }); } @@ -109,10 +114,11 @@ export function PeopleFilters() { - diff --git a/src/components/shared/AssetGrid.tsx b/src/components/shared/AssetGrid.tsx index c21a349..160d52d 100644 --- a/src/components/shared/AssetGrid.tsx +++ b/src/components/shared/AssetGrid.tsx @@ -120,14 +120,6 @@ const AssetGrid = forwardRef(({ assets, isInternal }), [assets, selectedIds, updateContext]); - const handleClick = (index: number, asset: AssetPhoto, event: React.MouseEvent) => { - if (selectedIds.length > 0) { - handleSelect(index, asset, event); - } else { - setIndex(index); - } - } - const handleSelect = (_idx: number, asset: AssetPhoto, event: React.MouseEvent) => { event.stopPropagation(); @@ -157,6 +149,14 @@ const AssetGrid = forwardRef(({ assets, isInternal } }; + const handleClick = (index: number, asset: AssetPhoto, event: React.MouseEvent) => { + if (selectable && (event.metaKey || event.ctrlKey || selectedIds.length > 0)) { + handleSelect(index, asset, event); + } else { + setIndex(index); + } + } + const slides = useMemo(() => { return assets.filter((asset) => !deletedIds.has(asset.id)).map((asset) => ({ ...asset, @@ -214,6 +214,9 @@ const AssetGrid = forwardRef(({ assets, isInternal photo={context.photo} width={context.width} height={context.height} + selectable={selectable} + onSelect={(event) => handleSelect(context.index, context.photo, event)} + selectionMode={selectable && selectedIds.length > 0} /> ); }; diff --git a/src/components/shared/ResponsiveVirtualizedAssetGrid.tsx b/src/components/shared/ResponsiveVirtualizedAssetGrid.tsx index 4c971f2..ed21a71 100644 --- a/src/components/shared/ResponsiveVirtualizedAssetGrid.tsx +++ b/src/components/shared/ResponsiveVirtualizedAssetGrid.tsx @@ -112,14 +112,6 @@ const ResponsiveVirtualizedAssetGrid = forwardRef) => { - if (selectedIds.length > 0) { - handleSelect(index, asset, event); - } else { - setIndex(index); - } - }, [selectedIds]); - const handleSelect = useCallback((_idx: number, asset: IAsset, event: React.MouseEvent) => { event.stopPropagation(); const isPresent = selectedIds.includes(asset.id); @@ -146,6 +138,14 @@ const ResponsiveVirtualizedAssetGrid = forwardRef) => { + if (selectable && (event.metaKey || event.ctrlKey || selectedIds.length > 0)) { + handleSelect(index, asset, event); + } else { + setIndex(index); + } + }, [selectedIds, selectable, handleSelect]); + const handleEsc = useCallback((event: KeyboardEvent) => { if (event.key === "Escape") { updateContext({ selectedIds: [] }); @@ -200,11 +200,15 @@ const ResponsiveVirtualizedAssetGrid = forwardRef { + e.stopPropagation(); + handleSelect(assetIndex, asset, e); + }} /> )} diff --git a/src/components/shared/VirtualizedAssetGrid.tsx b/src/components/shared/VirtualizedAssetGrid.tsx index add29f4..57837b4 100644 --- a/src/components/shared/VirtualizedAssetGrid.tsx +++ b/src/components/shared/VirtualizedAssetGrid.tsx @@ -76,14 +76,6 @@ const VirtualizedAssetGrid = forwardRef) => { - if (selectedIds.length > 0) { - handleSelect(index, asset, event); - } else { - setIndex(index); - } - }, [selectedIds]); - const handleSelect = useCallback((_idx: number, asset: IAsset, event: React.MouseEvent) => { event.stopPropagation(); const isPresent = selectedIds.includes(asset.id); @@ -110,6 +102,14 @@ const VirtualizedAssetGrid = forwardRef) => { + if (selectable && (event.metaKey || event.ctrlKey || selectedIds.length > 0)) { + handleSelect(index, asset, event); + } else { + setIndex(index); + } + }, [selectedIds, selectable, handleSelect]); + const handleEsc = useCallback((event: KeyboardEvent) => { if (event.key === "Escape") { updateContext({ selectedIds: [] }); @@ -166,11 +166,15 @@ const VirtualizedAssetGrid = forwardRef { + e.stopPropagation(); + handleSelect(assetIndex, asset, e); + }} /> )} diff --git a/src/components/ui/lazy-grid-image.tsx b/src/components/ui/lazy-grid-image.tsx index 015fc33..4751fa5 100644 --- a/src/components/ui/lazy-grid-image.tsx +++ b/src/components/ui/lazy-grid-image.tsx @@ -1,6 +1,7 @@ /* eslint-disable @next/next/no-img-element */ import { humanizeDuration } from '@/helpers/string.helper' import { PlayIcon } from '@radix-ui/react-icons' +import { CircleCheck } from 'lucide-react' import React, { useEffect } from 'react' import type { RenderImageProps } from 'react-photo-album' import type { AssetPhoto } from '../shared/AssetGrid' @@ -10,15 +11,19 @@ interface LazyGridImageProps { photo: AssetPhoto; width: number; height: number; + selectable?: boolean; + onSelect?: (event: React.MouseEvent) => void; + /** When true, dim non-selected siblings so the selected set is visible in dense grids. */ + selectionMode?: boolean; } -export default function LazyGridImage({ imageProps, photo, width, height }: LazyGridImageProps) { +export default function LazyGridImage({ imageProps, photo, width, height, selectable, onSelect, selectionMode = false }: LazyGridImageProps) { const [isVisible, setIsVisible] = React.useState(false) const imageRef = React.useRef(null) const setupObserver = () => { const observer = new IntersectionObserver((entries) => { - + entries.forEach((entry) => { if (entry.isIntersecting) { setIsVisible(true) @@ -44,13 +49,35 @@ export default function LazyGridImage({ imageProps, photo, width, height }: Lazy
) + const dim = selectionMode && !photo.isSelected ? 'opacity-60' : ''; + return ( -
+
{imageProps.alt {photo.isVideo &&
{!!photo.duration && {humanizeDuration(photo.duration)}}
} + {selectable && ( +
{ + e.stopPropagation(); + onSelect?.(e); + }} + > +
+ +
+
+ )}
) } diff --git a/src/components/workflows/NodePalette.tsx b/src/components/workflows/NodePalette.tsx index 4ffc7c4..632db56 100644 --- a/src/components/workflows/NodePalette.tsx +++ b/src/components/workflows/NodePalette.tsx @@ -27,6 +27,7 @@ const actionItems: PaletteItem[] = [ { type: "action", subType: "unfavorite", label: "Unfavorite", icon: HeartOff, color: "text-purple-500" }, { type: "action", subType: "archive", label: "Archive", icon: Archive, color: "text-purple-500" }, { type: "action", subType: "tag", label: "Add Tag", icon: Tag, color: "text-purple-500" }, + { type: "action", subType: "remove_tag", label: "Remove Tag", icon: Tag, color: "text-purple-500" }, ]; function PaletteGroup({ title, items }: { title: string; items: PaletteItem[] }) { diff --git a/src/components/workflows/config/ActionConfig.tsx b/src/components/workflows/config/ActionConfig.tsx index 09a62cc..cc15cb0 100644 --- a/src/components/workflows/config/ActionConfig.tsx +++ b/src/components/workflows/config/ActionConfig.tsx @@ -115,7 +115,7 @@ export default function ActionConfig({ subType, config, onChange }: ActionConfig ); } - if (subType === "tag") { + if (subType === "tag" || subType === "remove_tag") { return (
@@ -125,6 +125,9 @@ export default function ActionConfig({ subType, config, onChange }: ActionConfig value={config.tagName || ""} onChange={(e) => onChange({ ...config, tagName: e.target.value })} /> + {subType === "remove_tag" && ( +

Removes this tag from matched assets. If the tag doesn't exist, nothing happens.

+ )}
); } diff --git a/src/components/workflows/config/ConditionEditor.tsx b/src/components/workflows/config/ConditionEditor.tsx index 084e63b..7b5f7ce 100644 --- a/src/components/workflows/config/ConditionEditor.tsx +++ b/src/components/workflows/config/ConditionEditor.tsx @@ -4,8 +4,9 @@ import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@ import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"; import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList } from "@/components/ui/command"; import { ICondition, ConditionType } from "@/types/workflow"; -import { Plus, X, Check } from "lucide-react"; +import { Plus, X, Check, Tag } from "lucide-react"; import { listPeople } from "@/handlers/api/people.handler"; +import { listTags, ITag } from "@/handlers/api/tag.handler"; import { IPerson } from "@/types/person"; import { PERSON_THUBNAIL_PATH } from "@/config/routes"; import { useEffect, useState } from "react"; @@ -14,6 +15,7 @@ import { cn } from "@/lib/utils"; const conditionTypeLabels: Record = { person: "Person", person_unnamed: "Unnamed People", + tag: "Tag", city: "City", state: "State", country: "Country", @@ -27,8 +29,14 @@ const conditionTypeLabels: Record = { asset_type: "Asset Type", iso_range: "ISO Range", focal_length: "Focal Length", + resolution: "Resolution", rating: "Rating", is_favorited: "Favorited", + file_size: "File Size", + filename: "File Name / Path", + file_extension: "File Extension", + face_count: "Face Count", + time_of_day: "Time of Day", not_in_album: "Not in Any Album", not_in_specific_album: "Not in Specific Album", }; @@ -124,6 +132,95 @@ function PersonPicker({ selectedIds, onChange }: PersonPickerProps) { ); } +interface TagPickerProps { + selectedIds: string[]; + onChange: (tagIds: string[], tagValues: string[]) => void; +} + +function TagPicker({ selectedIds, onChange }: TagPickerProps) { + const [open, setOpen] = useState(false); + const [tags, setTags] = useState([]); + const [loading, setLoading] = useState(false); + + useEffect(() => { + setLoading(true); + listTags() + .then((res) => setTags(res.tags)) + .finally(() => setLoading(false)); + }, []); + + const selectedSet = new Set(selectedIds || []); + const selectedTags = tags.filter((t) => selectedSet.has(t.id)); + + const toggleTag = (tag: ITag) => { + let nextIds: string[]; + let nextValues: string[]; + if (selectedSet.has(tag.id)) { + nextIds = selectedIds.filter((id) => id !== tag.id); + nextValues = selectedTags.filter((t) => t.id !== tag.id).map((t) => t.value); + } else { + nextIds = [...selectedIds, tag.id]; + nextValues = [...selectedTags.map((t) => t.value), tag.value]; + } + onChange(nextIds, nextValues); + }; + + return ( +
+ {/* Selected tag chips */} + {selectedTags.length > 0 && ( +
+ {selectedTags.map((t) => ( + + ))} +
+ )} + + {/* Picker */} + + + + + + + + + {loading ? "Loading..." : "No tags found."} + + {tags.map((tag) => ( + toggleTag(tag)} + className="flex items-center gap-2" + > + + {tag.value} + + + ))} + + + + + +
+ ); +} + interface ConditionEditorProps { conditions: ICondition[]; onChange: (conditions: ICondition[]) => void; @@ -192,6 +289,25 @@ function ConditionFields({ condition, onChange }: { condition: ICondition; onCha onChange({ ...condition, max: parseInt(e.target.value) || undefined })} />
); + case "resolution": { + const unit = (condition.metric || "megapixels") === "megapixels" ? "MP" : "px"; + return ( +
+ +
+ onChange({ ...condition, min: e.target.value === "" ? undefined : parseFloat(e.target.value) })} /> + onChange({ ...condition, max: e.target.value === "" ? undefined : parseFloat(e.target.value) })} /> +
+
+ ); + } case "is_favorited": return ( ); + case "file_size": + return ( +
+ onChange({ ...condition, min: e.target.value === "" ? undefined : parseFloat(e.target.value) })} /> + onChange({ ...condition, max: e.target.value === "" ? undefined : parseFloat(e.target.value) })} /> +
+ ); + case "filename": + return ( +
+
+ + +
+ onChange({ ...condition, text: e.target.value })} /> +
+ ); + case "file_extension": + return ( +
+ + onChange({ ...condition, extensions: e.target.value })} /> +
+ ); + case "face_count": + return ( +
+ onChange({ ...condition, min: e.target.value === "" ? undefined : parseInt(e.target.value) })} /> + onChange({ ...condition, max: e.target.value === "" ? undefined : parseInt(e.target.value) })} /> + faces +
+ ); + case "time_of_day": + return ( +
+
+ From + onChange({ ...condition, fromHour: e.target.value === "" ? undefined : parseInt(e.target.value) })} /> + to + onChange({ ...condition, toHour: e.target.value === "" ? undefined : parseInt(e.target.value) })} /> + h +
+

Hours 0–23; From > To wraps past midnight (e.g. 22 to 5).

+
+ ); case "person": return (
@@ -219,6 +400,24 @@ function ConditionFields({ condition, onChange }: { condition: ICondition; onCha />
); + case "tag": + return ( +
+ + onChange({ ...condition, tagIds, tagValues })} + /> +

Selected tags also match their child tags.

+
+ ); case "geo_radius": return (
diff --git a/src/components/workflows/nodes/ActionNode.tsx b/src/components/workflows/nodes/ActionNode.tsx index fea2f50..08f937e 100644 --- a/src/components/workflows/nodes/ActionNode.tsx +++ b/src/components/workflows/nodes/ActionNode.tsx @@ -9,6 +9,7 @@ const actionIcons: Record = { unfavorite: HeartOff, archive: Archive, tag: Tag, + remove_tag: Tag, }; const actionLabels: Record = { @@ -19,6 +20,7 @@ const actionLabels: Record = { unfavorite: "Unfavorite", archive: "Archive", tag: "Add Tag", + remove_tag: "Remove Tag", }; export default function ActionNode({ data, selected }: NodeProps) { @@ -42,7 +44,7 @@ export default function ActionNode({ data, selected }: NodeProps) { {(subType === "add_to_album" || subType === "remove_from_album") && config.albumName && (

{config.albumName}

)} - {subType === "tag" && config.tagName && ( + {(subType === "tag" || subType === "remove_tag") && config.tagName && (

{config.tagName}

)}
diff --git a/src/components/workflows/nodes/conditionSummary.ts b/src/components/workflows/nodes/conditionSummary.ts index 5cc441c..872a868 100644 --- a/src/components/workflows/nodes/conditionSummary.ts +++ b/src/components/workflows/nodes/conditionSummary.ts @@ -3,6 +3,7 @@ import { ICondition, ConditionType } from "@/types/workflow"; const conditionTypeLabels: Record = { person: "Person", person_unnamed: "Unnamed People", + tag: "Tag", city: "City", state: "State", country: "Country", @@ -16,8 +17,14 @@ const conditionTypeLabels: Record = { asset_type: "Asset Type", iso_range: "ISO Range", focal_length: "Focal Length", + resolution: "Resolution", rating: "Rating", is_favorited: "Favorited", + file_size: "File Size", + filename: "File Name / Path", + file_extension: "Extension", + face_count: "Faces", + time_of_day: "Time of Day", not_in_album: "Not in Any Album", not_in_specific_album: "Not in Specific Album", }; @@ -45,6 +52,13 @@ export function formatConditionSummary(c: ICondition): string { } case "person_unnamed": return label; + case "tag": { + const values: string[] = c.tagValues || []; + const match = matchLabels[c.match] || c.match || "any of"; + if (values.length === 0) return `${label}: (none selected)`; + const valueStr = values.length <= 2 ? values.join(", ") : `${values[0]}, ${values[1]} +${values.length - 2}`; + return `${label} ${match}: ${valueStr}`; + } case "city": case "state": case "country": { @@ -95,8 +109,44 @@ export function formatConditionSummary(c: ICondition): string { if (c.max != null) return `${label}: ≤${c.max}`; return label; } + case "resolution": { + const metricNames: Record = { megapixels: "MP", short_edge: "short edge", long_edge: "long edge" }; + const metric = c.metric || "megapixels"; + const unit = metric === "megapixels" ? "MP" : "px"; + const name = metric === "megapixels" ? "" : `${metricNames[metric]} `; + if (c.min != null && c.max != null) return `${label}: ${name}${c.min}–${c.max}${unit}`; + if (c.min != null) return `${label}: ${name}≥${c.min}${unit}`; + if (c.max != null) return `${label}: ${name}≤${c.max}${unit}`; + return label; + } case "is_favorited": return c.value === false ? "Not Favorited" : "Favorited"; + case "file_size": { + if (c.min != null && c.max != null) return `${label}: ${c.min}–${c.max}MB`; + if (c.min != null) return `${label}: ≥${c.min}MB`; + if (c.max != null) return `${label}: ≤${c.max}MB`; + return label; + } + case "filename": { + if (!c.text) return label; + const field = c.field === "path" ? "Path" : "Name"; + const matchNames: Record = { contains: "contains", not_contains: "doesn't contain", starts_with: "starts with", ends_with: "ends with" }; + return `${field} ${matchNames[c.match] || "contains"}: ${c.text}`; + } + case "file_extension": { + if (!c.extensions) return label; + return `${label} ${c.match === "not_in" ? "none of" : "any of"}: ${c.extensions}`; + } + case "face_count": { + if (c.min != null && c.max != null) return c.min === c.max ? `${label}: ${c.min}` : `${label}: ${c.min}–${c.max}`; + if (c.min != null) return `${label}: ≥${c.min}`; + if (c.max != null) return `${label}: ≤${c.max}`; + return label; + } + case "time_of_day": { + if (c.fromHour == null || c.toHour == null) return label; + return `${label}: ${c.fromHour}:00–${c.toHour}:59`; + } case "not_in_album": return label; case "not_in_specific_album": diff --git a/src/config/db.ts b/src/config/db.ts index f39e4e1..c3b1e0d 100644 --- a/src/config/db.ts +++ b/src/config/db.ts @@ -26,6 +26,40 @@ class DatabaseConnectionError extends Error { this.error = error; } } + +const getRootCause = (error: any): any => { + let current = error; + while (current?.cause) current = current.cause; + return current; +}; + +const describePgError = (error: any): string => { + const root = getRootCause(error); + const target = `${ENV.DB_HOST || '?'}:${ENV.DB_PORT || '?'}`; + const code = root?.code as string | undefined; + + switch (code) { + case 'ENOTFOUND': + return `Cannot resolve database host "${ENV.DB_HOST}". Check DB_HOST and that the power-tools container is on the same Docker network as the Immich Postgres container (use the container name, e.g. "immich_postgres").`; + case 'ECONNREFUSED': + return `Connection refused at ${target}. The host is reachable but nothing is listening on that port — check DB_PORT and that Postgres is running.`; + case 'ETIMEDOUT': + case 'EHOSTUNREACH': + case 'ENETUNREACH': + return `Cannot reach ${target} (${code}). Likely a network/firewall issue or the wrong DB_HOST for this container.`; + case '28P01': + return `Password authentication failed for user "${ENV.DB_USERNAME}". Check DB_PASSWORD (and ensure no extra quotes/spaces in .env).`; + case '28000': + return `Authentication failed for user "${ENV.DB_USERNAME}" at ${target}. Check DB_USERNAME and pg_hba rules.`; + case '3D000': + return `Database "${ENV.DB_DATABASE_NAME}" does not exist on ${target}. Check DB_DATABASE_NAME.`; + case '57P03': + return `Postgres at ${target} is starting up and not yet ready to accept connections.`; + default: + return `${root?.message || error?.message || 'Unknown error'}${code ? ` (code: ${code})` : ''} — target ${target}, user "${ENV.DB_USERNAME}", db "${ENV.DB_DATABASE_NAME}".`; + } +}; + export const connectDB = async (db: NodePgDatabase) => { try { const missingKeys = findMissingKeys(ENV, ['DB_USERNAME', 'DB_PASSWORD', 'DB_HOST', 'DB_PORT', 'DB_DATABASE_NAME']); @@ -38,7 +72,17 @@ export const connectDB = async (db: NodePgDatabase) => { return await db.execute(sql`SELECT 1`); // Execute a simple query } } catch (error: any) { - throw new DatabaseConnectionError(error.message, "Database connection failed"); + if (error instanceof APIError) throw error; + const root = getRootCause(error); + console.error('[db] connection failed:', { + code: root?.code, + message: root?.message, + host: ENV.DB_HOST, + port: ENV.DB_PORT, + user: ENV.DB_USERNAME, + database: ENV.DB_DATABASE_NAME, + }); + throw new DatabaseConnectionError(describePgError(error), "Database connection failed"); } } diff --git a/src/config/permissions.ts b/src/config/permissions.ts new file mode 100644 index 0000000..cdbdd66 --- /dev/null +++ b/src/config/permissions.ts @@ -0,0 +1,30 @@ +export interface Permission { + name: string; + description: string; +} + +export const IMPORT_PERMISSIONS: Permission[] = [ + { name: "asset.read", description: "Check for existing assets" }, + { name: "asset.upload", description: "Upload new assets" }, + { name: "album.read", description: "Read album data" }, + { name: "album.create", description: "Create new albums" }, + { name: "album.update", description: "Update album metadata" }, + { name: "albumAsset.create", description: "Add assets to albums" }, + { name: "tag.create", description: "Tag imported assets" }, + { name: "tag.asset", description: "Assign tags to assets" }, +]; + +export const WORKFLOW_PERMISSIONS: Permission[] = [ + { name: "asset.read", description: "Query and filter assets" }, + { name: "asset.update", description: "Favorite, archive, update metadata" }, + { name: "album.read", description: "Read album data" }, + { name: "album.create", description: "Create new albums" }, + { name: "album.update", description: "Update album metadata" }, + { name: "albumAsset.create", description: "Add assets to albums" }, + { name: "albumAsset.delete", description: "Remove assets from albums" }, + { name: "tag.create", description: "Create tags" }, + { name: "tag.asset", description: "Assign tags to assets" }, +]; + +export const getPermissionNames = (permissions: Permission[]): string[] => + permissions.map((p) => p.name); diff --git a/src/config/routes.ts b/src/config/routes.ts index 1c82744..5111d13 100644 --- a/src/config/routes.ts +++ b/src/config/routes.ts @@ -7,6 +7,7 @@ export const LOGOUT_PATH = BASE_API_ENDPOINT + "/users/logout"; export const LIST_PEOPLE_PATH = BASE_API_ENDPOINT + "/people/list"; +export const LIST_TAGS_PATH = BASE_API_ENDPOINT + "/tags"; export const SEARCH_PEOPLE_PATH = BASE_PROXY_ENDPOINT + "/search/person"; export const SIMILAR_FACES_PATH = (id: string) => BASE_API_ENDPOINT + "/people/" + id + "/similar-faces"; export const PERSON_THUBNAIL_PATH = (id: string) => BASE_PROXY_ENDPOINT + "/thumbnail/" + id; diff --git a/src/db/schema/importJobs.schema.ts b/src/db/schema/importJobs.schema.ts index 259f16d..9630ec1 100644 --- a/src/db/schema/importJobs.schema.ts +++ b/src/db/schema/importJobs.schema.ts @@ -4,7 +4,7 @@ import { randomUUID } from "crypto"; export const importJobs = sqliteTable("import_jobs", { id: text("id").primaryKey().$defaultFn(() => randomUUID()), userId: text("user_id").notNull(), - platform: text("platform").notNull(), // 'immich' | 'nextcloud' | 'photoprism' + platform: text("platform").notNull(), // 'immich' | 'nextcloud' | 'ente' | 'photoprism' status: text("status").notNull().default("pending"), // pending | processing | completed | failed url: text("url").notNull(), // base URL of source urlConfig: text("url_config").notNull().default("{}"), // JSON: auth/connection (key, token, etc.) diff --git a/src/handlers/api/analytics.handler.ts b/src/handlers/api/analytics.handler.ts index 605792e..523c7bb 100644 --- a/src/handlers/api/analytics.handler.ts +++ b/src/handlers/api/analytics.handler.ts @@ -16,8 +16,15 @@ export const getLivePhotoStatistics = async () => { return API.get(LIVE_PHOTO_STATISTICS); } -export const getHeatMapData = async () => { - return API.get(HEATMAP_DATA); +export interface IHeatMapResponse { + data: Array<{ date: string; count: number }>; + year: number | null; + availableYears: number[]; +} + +export const getHeatMapData = async (year?: number): Promise => { + const params = year ? { year: String(year) } : {}; + return API.get(HEATMAP_DATA, params); } export const getPeopleNamesStatistics = async () => { diff --git a/src/handlers/api/tag.handler.ts b/src/handlers/api/tag.handler.ts new file mode 100644 index 0000000..0f62fce --- /dev/null +++ b/src/handlers/api/tag.handler.ts @@ -0,0 +1,13 @@ +import { LIST_TAGS_PATH } from "@/config/routes"; +import API from "@/lib/api"; + +export interface ITag { + id: string; + value: string; + color: string | null; + parentId: string | null; +} + +export const listTags = (): Promise<{ tags: ITag[] }> => { + return API.get(LIST_TAGS_PATH); +}; diff --git a/src/handlers/serverUtils/user.utils.ts b/src/handlers/serverUtils/user.utils.ts index 6756e1a..93282e0 100644 --- a/src/handlers/serverUtils/user.utils.ts +++ b/src/handlers/serverUtils/user.utils.ts @@ -6,6 +6,24 @@ import { getCookie } from "@/lib/cookie" import { NextApiRequest } from "next" +const describeFetchError = (error: any, url: string): string => { + let current = error; + while (current?.cause) current = current.cause; + const code = current?.code as string | undefined; + switch (code) { + case 'ENOTFOUND': + return `Cannot resolve host for ${url}. Check IMMICH_URL — from inside this container, an IP on the host network may not be reachable; prefer the Immich container name (e.g. http://immich_server:2283).`; + case 'ECONNREFUSED': + return `Connection refused at ${url}. Check that the Immich server is running and that IMMICH_URL points to its internal port (default 2283).`; + case 'ETIMEDOUT': + case 'EHOSTUNREACH': + case 'ENETUNREACH': + return `Cannot reach Immich API at ${url} (${code}). Likely the power-tools container is not on the same network as the Immich server.`; + default: + return `Failed to connect to Immich API at ${url}: ${current?.message || error?.message || 'Unknown error'}${code ? ` (${code})` : ''}`; + } +}; + export const getCurrentUserFromAPIKey = () => { if (!ENV.IMMICH_URL || !ENV.IMMICH_API_KEY) return null; @@ -32,8 +50,9 @@ export const getCurrentUserFromAPIKey = () => { if (error instanceof APIError) { throw error; } + console.error('[immich-api] connect failed:', { url: ENV.IMMICH_URL, message: error?.message, cause: error?.cause }); throw new APIError({ - message: "Failed to connect to Immich API: " + ENV.IMMICH_URL, + message: describeFetchError(error, ENV.IMMICH_URL), status: 500, }); }) @@ -51,8 +70,9 @@ export const getCurrentUserFromAccessToken = (token: string) => { } return null }).catch((error) => { + console.error('[immich-api] connect failed:', { url: ENV.IMMICH_URL, message: error?.message, cause: error?.cause }); throw new APIError({ - message: "Failed to connect to Immich API: " + ENV.IMMICH_URL, + message: describeFetchError(error, ENV.IMMICH_URL), status: 500, }); }) diff --git a/src/helpers/ai.helper.ts b/src/helpers/ai.helper.ts index c4ecf92..3930bed 100644 --- a/src/helpers/ai.helper.ts +++ b/src/helpers/ai.helper.ts @@ -67,10 +67,11 @@ const getOpenAICompatibleModel = () => { }; export const parseFindQuery = async (query: string): Promise => { + const today = new Date().toISOString().split("T")[0]; const prompt = [ `Parse the following query and return extracted filters as JSON: ${query}.`, "Do not include any information that is not intentionally provided in the query.", - `Today's date is ${new Date().toISOString().split("T")[0]}.`, + `Today's date is ${today}. Use it ONLY to resolve relative expressions like "last week" or "yesterday" that APPEAR IN THE QUERY. If no date-related word is in the query, DO NOT return takenAfter or takenBefore.`, "Dates must be in YYYY-MM-DD format.", "Return ONLY valid JSON object with keys: query, personIds, city, country, state, size, model, takenAfter, takenBefore, type.", "Do not use null values. Omit a key when it is not present in the query.", @@ -81,10 +82,9 @@ export const parseFindQuery = async (query: string): Promise => { model: getOpenAICompatibleModel(), prompt, output: Output.object({ - name:"json", + name: "json", schema: responseSchema, }), - }); const parsedResponse = JSON.parse(text) as FindQuery; @@ -94,9 +94,18 @@ export const parseFindQuery = async (query: string): Promise => { delete parsedResponse.type; } } - const cleanedResponse = { - ...parsedResponse - }; - return removeNullOrUndefinedProperties(cleanedResponse) as any as FindQuery; + // Guardrail against a common LLM failure mode: small-to-medium models + // (qwen2.5:7b, Gemini flash, etc.) often echo the prompt's "today" date as + // `takenAfter` even when the query has no date. A date in the future can + // never match a photo, so drop any takenAfter/takenBefore that is today or + // later — this keeps the filter purely corrective without guessing intent. + if (parsedResponse.takenAfter && parsedResponse.takenAfter >= today) { + delete parsedResponse.takenAfter; + } + if (parsedResponse.takenBefore && parsedResponse.takenBefore > today) { + delete parsedResponse.takenBefore; + } + + return removeNullOrUndefinedProperties(parsedResponse) as any as FindQuery; }; diff --git a/src/helpers/string.helper.ts b/src/helpers/string.helper.ts index 28e77e4..db06d16 100644 --- a/src/helpers/string.helper.ts +++ b/src/helpers/string.helper.ts @@ -7,6 +7,9 @@ export const pluralize = (number: number, word: string, pluralWord: string) => { } export const humanizeBytes = (bytes: number) => { + if (!bytes || isNaN(bytes)) { + return `0 bytes` + } if (bytes < 1024) { return `${bytes} bytes` } @@ -19,22 +22,23 @@ export const humanizeBytes = (bytes: number) => { return `${(bytes / (1024 * 1024 * 1024)).toFixed(1)} GB` } -export const humanizeDuration = (duration: string) => { - if (!duration) { +export const humanizeDuration = (duration: string | number | null | undefined) => { + if (duration === null || duration === undefined || duration === '') { return null; } - // Example input : 00:00:04.350 - const [hours, minutes, seconds] = duration.split(':').map(Number); - const totalSeconds = Math.round(hours * 3600 + minutes * 60 + seconds); + const ms = Number(duration); + if (isNaN(ms)) { + return null; + } + const totalSeconds = Math.round(ms / 1000); if (totalSeconds < 60) { return `${totalSeconds}s`; } + const hours = Math.floor(totalSeconds / 3600); + const minutes = Math.floor((totalSeconds % 3600) / 60); if (totalSeconds < 3600) { - // Show only minutes - return `${Math.round(minutes)}m`; + return `${minutes}m`; } - - - return `${Math.round(hours)}h ${Math.round(minutes)}m`; + return `${hours}h ${minutes}m`; } diff --git a/src/lib/workflow/actionExecutor.ts b/src/lib/workflow/actionExecutor.ts index 3625a93..1801071 100644 --- a/src/lib/workflow/actionExecutor.ts +++ b/src/lib/workflow/actionExecutor.ts @@ -6,7 +6,7 @@ import { exif } from "@/schema"; import { assets } from "@/schema/assets.schema"; import { person } from "@/schema/person.schema"; import { assetFaces } from "@/schema/assetFaces.schema"; -import { eq, and, inArray, sql, desc } from "drizzle-orm"; +import { eq, and, inArray, desc } from "drizzle-orm"; import { IUser } from "@/types/user"; import { getUserHeaders } from "@/helpers/user.helper"; @@ -28,6 +28,16 @@ async function getWorkflowApiKey(ownerId: string): Promise { return row?.value || null; } +// Immich bulk endpoints are called in batches so large asset sets don't +// produce oversized request bodies. +const API_BATCH_SIZE = 1000; + +async function immichFetchBatched(path: string, method: string, ids: string[], extraBody: Record, user: IUser): Promise { + for (let i = 0; i < ids.length; i += API_BATCH_SIZE) { + await immichFetch(path, method, { ...extraBody, ids: ids.slice(i, i + API_BATCH_SIZE) }, user); + } +} + async function immichFetch(path: string, method: string, body: any, user: IUser): Promise { const workflowApiKey = await getWorkflowApiKey(user.id); @@ -136,51 +146,71 @@ export async function executeAction( switch (subType) { case "create_album": { const albumName = await resolveTemplate(config.nameTemplate || "Auto Album", assetIds); - const album = await immichFetch("/albums", "POST", { albumName, assetIds }, user); + const album = await immichFetch("/albums", "POST", { albumName, assetIds: assetIds.slice(0, API_BATCH_SIZE) }, user); + if (assetIds.length > API_BATCH_SIZE) { + await immichFetchBatched(`/albums/${album.id}/assets`, "PUT", assetIds.slice(API_BATCH_SIZE), {}, user); + } return { action: "create_album", assetsProcessed: assetIds.length, albumId: album.id, albumName }; } case "add_to_album": { if (!config.albumId) throw new Error("Album ID is required for add_to_album"); - await immichFetch(`/albums/${config.albumId}/assets`, "PUT", { ids: assetIds }, user); + await immichFetchBatched(`/albums/${config.albumId}/assets`, "PUT", assetIds, {}, user); return { action: "add_to_album", assetsProcessed: assetIds.length, albumId: config.albumId }; } case "remove_from_album": { if (!config.albumId) throw new Error("Album ID is required for remove_from_album"); - await immichFetch(`/albums/${config.albumId}/assets`, "DELETE", { ids: assetIds }, user); + await immichFetchBatched(`/albums/${config.albumId}/assets`, "DELETE", assetIds, {}, user); return { action: "remove_from_album", assetsProcessed: assetIds.length, albumId: config.albumId }; } case "favorite": { - await immichFetch("/assets", "PUT", { ids: assetIds, isFavorite: true }, user); + await immichFetchBatched("/assets", "PUT", assetIds, { isFavorite: true }, user); return { action: "favorite", assetsProcessed: assetIds.length }; } case "unfavorite": { - await immichFetch("/assets", "PUT", { ids: assetIds, isFavorite: false }, user); + await immichFetchBatched("/assets", "PUT", assetIds, { isFavorite: false }, user); return { action: "unfavorite", assetsProcessed: assetIds.length }; } case "archive": { - await immichFetch("/assets", "PUT", { ids: assetIds, isArchived: true }, user); + await immichFetchBatched("/assets", "PUT", assetIds, { visibility: "archive" }, user); return { action: "archive", assetsProcessed: assetIds.length }; } case "tag": { if (!config.tagName) throw new Error("Tag name is required"); - // Tags API may vary by Immich version — try the standard approach try { // Create or get tag - const tag = await immichFetch("/tags", "POST", { name: config.tagName, type: "OBJECT" }, user); + const tag = await immichFetch("/tags", "POST", { name: config.tagName }, user); // Tag assets - await immichFetch(`/tags/${tag.id}/assets`, "PUT", { ids: assetIds }, user); + await immichFetchBatched(`/tags/${tag.id}/assets`, "PUT", assetIds, {}, user); return { action: "tag", assetsProcessed: assetIds.length }; } catch (e: any) { return { action: "tag", assetsProcessed: 0, error: e.message }; } } + case "remove_tag": { + if (!config.tagName) throw new Error("Tag name is required"); + try { + // Look up the tag via Immich's API (same source of truth the "tag" + // action creates/gets from) without creating it — removing a tag + // that doesn't exist is a no-op, not an error. + const tags = await immichFetch("/tags", "GET", undefined, user); + const tag = Array.isArray(tags) ? tags.find((t: any) => t.value === config.tagName) : undefined; + if (!tag) { + return { action: "remove_tag", assetsProcessed: 0 }; + } + await immichFetch(`/tags/${tag.id}/assets`, "DELETE", { ids: assetIds }, user); + return { action: "remove_tag", assetsProcessed: assetIds.length }; + } catch (e: any) { + return { action: "remove_tag", assetsProcessed: 0, error: e.message }; + } + } + default: return { action: subType, assetsProcessed: 0, error: `Unknown action: ${subType}` }; } diff --git a/src/lib/workflow/conditionBuilder.ts b/src/lib/workflow/conditionBuilder.ts index e695515..b52f1a1 100644 --- a/src/lib/workflow/conditionBuilder.ts +++ b/src/lib/workflow/conditionBuilder.ts @@ -92,6 +92,78 @@ function buildSingleCondition(c: ICondition): SQL | undefined { return parts.length > 0 ? and(...parts)! : undefined; } + case "resolution": { + // Short/long edge are orientation-agnostic; megapixels = width × height / 1e6. + const metric = c.metric || "megapixels"; + const value = + metric === "short_edge" + ? sql`LEAST(${exif.exifImageWidth}, ${exif.exifImageHeight})` + : metric === "long_edge" + ? sql`GREATEST(${exif.exifImageWidth}, ${exif.exifImageHeight})` + : sql`(${exif.exifImageWidth}::bigint * ${exif.exifImageHeight}) / 1000000.0`; + const parts: SQL[] = []; + if (c.min !== undefined && c.min !== null) parts.push(sql`${value} >= ${c.min}`); + if (c.max !== undefined && c.max !== null) parts.push(sql`${value} <= ${c.max}`); + return parts.length > 0 ? and(...parts)! : undefined; + } + + case "file_size": { + // min/max in megabytes (fractional allowed) + const parts: SQL[] = []; + if (c.min !== undefined && c.min !== null) parts.push(sql`${exif.fileSizeInByte} >= ${Math.round(c.min * 1048576)}`); + if (c.max !== undefined && c.max !== null) parts.push(sql`${exif.fileSizeInByte} <= ${Math.round(c.max * 1048576)}`); + return parts.length > 0 ? and(...parts)! : undefined; + } + + case "filename": { + if (!c.text) return undefined; + const column = c.field === "path" ? assets.originalPath : assets.originalFileName; + // Escape LIKE wildcards so user text is matched literally + const escaped = c.text.replace(/([\\%_])/g, "\\$1"); + const match = c.match || "contains"; + const pattern = + match === "starts_with" ? `${escaped}%` + : match === "ends_with" ? `%${escaped}` + : `%${escaped}%`; + return match === "not_contains" + ? sql`${column} NOT ILIKE ${pattern}` + : sql`${column} ILIKE ${pattern}`; + } + + case "file_extension": { + const raw: string = c.extensions || ""; + const exts = raw + .split(",") + .map((e: string) => e.trim().replace(/^\./, "").toLowerCase()) + .filter(Boolean); + if (exts.length === 0) return undefined; + // Extension = text after the last dot; files without one never match either mode + const extExpr = sql`lower(substring(${assets.originalFileName} from '\\.([^.]+)$'))`; + const list = exts.map((e: string) => `'${e.replace(/'/g, "''")}'`).join(","); + return c.match === "not_in" + ? sql`${extExpr} NOT IN (${sql.raw(list)})` + : sql`${extExpr} IN (${sql.raw(list)})`; + } + + case "face_count": { + const faceCount = sql`(SELECT count(*) FROM "asset_face" af WHERE af."assetId" = ${assets.id} AND af."deletedAt" IS NULL AND af."isVisible" = true)`; + const parts: SQL[] = []; + if (c.min !== undefined && c.min !== null) parts.push(sql`${faceCount} >= ${c.min}`); + if (c.max !== undefined && c.max !== null) parts.push(sql`${faceCount} <= ${c.max}`); + return parts.length > 0 ? and(...parts)! : undefined; + } + + case "time_of_day": { + if (c.fromHour == null || c.toHour == null) return undefined; + // localDateTime holds the capture wall-clock time, so no timezone math needed + const hour = sql`EXTRACT(HOUR FROM ${assets.localDateTime})`; + if (c.fromHour <= c.toHour) { + return sql`${hour} BETWEEN ${c.fromHour} AND ${c.toHour}`; + } + // From > To wraps past midnight, e.g. 22–5 = evening through early morning + return sql`(${hour} >= ${c.fromHour} OR ${hour} <= ${c.toHour})`; + } + case "person": { const ids: string[] = c.personIds || (c.personId ? [c.personId] : []); if (ids.length === 0) return undefined; @@ -117,6 +189,36 @@ function buildSingleCondition(c: ICondition): SQL | undefined { return sql`EXISTS (SELECT 1 FROM "asset_face" af WHERE af."assetId" = ${assets.id} AND af."personId" IN (${sql.raw(idList)}))`; } + case "tag": { + const ids: string[] = c.tagIds || []; + if (ids.length === 0) return undefined; + + // A selected tag also matches assets tagged with any of its child tags + // (tag_closure holds the hierarchy, including self-references). + const descendants = (tagId: string) => + sql`(SELECT tc."id_descendant" FROM "tag_closure" tc WHERE tc."id_ancestor" = ${tagId})`; + + if (c.match === "not_contains") { + // Asset must not carry ANY of these tags (or their children) + const checks = ids.map((tid: string) => + sql`NOT EXISTS (SELECT 1 FROM "tag_asset" ta WHERE ta."assetId" = ${assets.id} AND (ta."tagId" = ${tid} OR ta."tagId" IN ${descendants(tid)}))` + ); + return and(...checks)!; + } + + if (c.match === "contains_all") { + // Asset must carry ALL of these tags (or their children) + const checks = ids.map((tid: string) => + sql`EXISTS (SELECT 1 FROM "tag_asset" ta WHERE ta."assetId" = ${assets.id} AND (ta."tagId" = ${tid} OR ta."tagId" IN ${descendants(tid)}))` + ); + return and(...checks)!; + } + + // contains_any (default) — asset carries at least one of these tags (or their children) + const idParams = sql.join(ids.map((id: string) => sql`${id}`), sql`, `); + return sql`EXISTS (SELECT 1 FROM "tag_asset" ta WHERE ta."assetId" = ${assets.id} AND (ta."tagId" IN (${idParams}) OR ta."tagId" IN (SELECT tc."id_descendant" FROM "tag_closure" tc WHERE tc."id_ancestor" IN (${idParams}))))`; + } + case "person_unnamed": if (c.match === "no_unnamed") { return sql`NOT EXISTS (SELECT 1 FROM "asset_face" af JOIN "person" p ON af."personId" = p.id WHERE af."assetId" = ${assets.id} AND (p.name = '' OR p.name IS NULL))`; diff --git a/src/lib/workflow/engine.ts b/src/lib/workflow/engine.ts index e49683f..4289c08 100644 --- a/src/lib/workflow/engine.ts +++ b/src/lib/workflow/engine.ts @@ -3,7 +3,7 @@ import { db } from "@/config/db"; import { workflows, workflowNodes, workflowEdges, workflowRuns, workflowProcessedAssets } from "@/db/schema/workflows.schema"; import { assets } from "@/schema/assets.schema"; import { exif } from "@/schema"; -import { eq, and, desc, gte, isNull, inArray, sql, ne } from "drizzle-orm"; +import { eq, and, desc, gt, gte, isNull, inArray, sql, ne, SQL } from "drizzle-orm"; import { buildConditions } from "./conditionBuilder"; import { executeAction } from "./actionExecutor"; import { IUser } from "@/types/user"; @@ -19,6 +19,53 @@ function logError(runId: string, ...args: any[]) { console.error(`${PREFIX} [run:${runId.slice(0, 8)}]`, ...args); } +const QUERY_BATCH_SIZE = 5000; + +// Keyset-paginate an asset query so large libraries aren't silently truncated. +// fetchBatch must ORDER BY assets.id and apply gt(assets.id, afterId) when given. +async function fetchAllBatches( + fetchBatch: (afterId: string | null, limit: number) => Promise, +): Promise { + const all: T[] = []; + let cursor: string | null = null; + for (;;) { + const batch = await fetchBatch(cursor, QUERY_BATCH_SIZE); + all.push(...batch); + if (batch.length < QUERY_BATCH_SIZE) break; + cursor = batch[batch.length - 1].id; + } + return all; +} + +// Evaluate condition clauses against an incoming asset set (chunked to keep +// IN-lists bounded), or against the whole library when scopeIds is null. +async function queryConditionMatches(whereClauses: SQL[], scopeIds: string[] | null): Promise { + if (scopeIds !== null) { + const matched: string[] = []; + for (let i = 0; i < scopeIds.length; i += QUERY_BATCH_SIZE) { + const chunk = scopeIds.slice(i, i + QUERY_BATCH_SIZE); + const rows = await db + .selectDistinctOn([assets.id], { id: assets.id }) + .from(assets) + .leftJoin(exif, eq(assets.id, exif.assetId)) + .where(and(...whereClauses, inArray(assets.id, chunk))); + matched.push(...rows.map((r) => r.id)); + } + return matched; + } + + const rows = await fetchAllBatches((afterId, limit) => + db + .selectDistinctOn([assets.id], { id: assets.id }) + .from(assets) + .leftJoin(exif, eq(assets.id, exif.assetId)) + .where(and(...whereClauses, ...(afterId ? [gt(assets.id, afterId)] : []))) + .orderBy(assets.id) + .limit(limit) + ); + return rows.map((r) => r.id); +} + async function resolveAssetTrigger( subType: string, workflowId: string, @@ -80,21 +127,27 @@ async function resolveAssetTrigger( let candidateIds: string[]; if (subType === "new_asset") { - const rows = await db - .selectDistinctOn([assets.id], { id: assets.id }) - .from(assets) - .where(and(...baseConditions, gte(assets.createdAt, sinceDate))) - .limit(10000); + const rows = await fetchAllBatches((afterId, limit) => + db + .selectDistinctOn([assets.id], { id: assets.id }) + .from(assets) + .where(and(...baseConditions, gte(assets.createdAt, sinceDate), ...(afterId ? [gt(assets.id, afterId)] : []))) + .orderBy(assets.id) + .limit(limit) + ); const totalCandidates = rows.length; // For new_asset: skip any asset we've ever processed candidateIds = rows.map((r) => r.id).filter((id) => !processedMap?.has(id)); log(runId, `Trigger [new_asset]: ${totalCandidates} candidates, ${totalCandidates - candidateIds.length} already processed, ${candidateIds.length} remaining`); } else if (subType === "asset_updated") { - const rows = await db - .selectDistinctOn([assets.id], { id: assets.id, updatedAt: assets.updatedAt }) - .from(assets) - .where(and(...baseConditions, gte(assets.updatedAt, sinceDate))) - .limit(10000); + const rows = await fetchAllBatches((afterId, limit) => + db + .selectDistinctOn([assets.id], { id: assets.id, updatedAt: assets.updatedAt }) + .from(assets) + .where(and(...baseConditions, gte(assets.updatedAt, sinceDate), ...(afterId ? [gt(assets.id, afterId)] : []))) + .orderBy(assets.id) + .limit(limit) + ); const totalCandidates = rows.length; // For asset_updated: only skip if we processed it AFTER its current updatedAt candidateIds = rows @@ -107,11 +160,14 @@ async function resolveAssetTrigger( log(runId, `Trigger [asset_updated]: ${totalCandidates} candidates, ${totalCandidates - candidateIds.length} skipped (not updated since processing), ${candidateIds.length} remaining`); } else { // all_assets — no dedup - const rows = await db - .selectDistinctOn([assets.id], { id: assets.id }) - .from(assets) - .where(and(...baseConditions)) - .limit(10000); + const rows = await fetchAllBatches((afterId, limit) => + db + .selectDistinctOn([assets.id], { id: assets.id }) + .from(assets) + .where(and(...baseConditions, ...(afterId ? [gt(assets.id, afterId)] : []))) + .orderBy(assets.id) + .limit(limit) + ); log(runId, `Trigger [all_assets]: ${rows.length} assets found`); return rows.map((r) => r.id); } @@ -244,19 +300,8 @@ export async function executeWorkflow( const whereClauses = buildConditions(conditions, user.id); - // Scope to incoming assets if available - if (assetIds !== null && assetIds.length > 0) { - whereClauses.push(inArray(assets.id, assetIds)); - } - - const matchedRows = await db - .selectDistinctOn([assets.id], { id: assets.id }) - .from(assets) - .leftJoin(exif, eq(assets.id, exif.assetId)) - .where(and(...whereClauses)) - .limit(10000); - - const matchedIds = matchedRows.map((r) => r.id); + // Scoped to incoming assets (chunked) when available + const matchedIds = await queryConditionMatches(whereClauses, assetIds); const matchedSet = new Set(matchedIds); let trueIds = matchedIds; @@ -298,19 +343,8 @@ export async function executeWorkflow( const whereClauses = buildConditions(c.conditions || [], user.id); - // Scope to remaining assets if available - if (remaining !== null && remaining.length > 0) { - whereClauses.push(inArray(assets.id, remaining)); - } - - const matchedRows = await db - .selectDistinctOn([assets.id], { id: assets.id }) - .from(assets) - .leftJoin(exif, eq(assets.id, exif.assetId)) - .where(and(...whereClauses)) - .limit(10000); - - const matchedIds = matchedRows.map((r) => r.id); + // Scoped to remaining assets (chunked) when available + const matchedIds = await queryConditionMatches(whereClauses, remaining); const matchedSet = new Set(matchedIds); let caseIds: string[]; diff --git a/src/pages/api/albums/[id]/assets.ts b/src/pages/api/albums/[id]/assets.ts index 2c0e683..17327af 100644 --- a/src/pages/api/albums/[id]/assets.ts +++ b/src/pages/api/albums/[id]/assets.ts @@ -29,7 +29,6 @@ export default async function handler( } const dbAssets = await db.selectDistinctOn([assets.id], { id: assets.id, - deviceId: assets.deviceId, type: assets.type, originalPath: assets.originalPath, isFavorite: assets.isFavorite, diff --git a/src/pages/api/albums/[id]/info.ts b/src/pages/api/albums/[id]/info.ts index e0fb466..c9dc209 100644 --- a/src/pages/api/albums/[id]/info.ts +++ b/src/pages/api/albums/[id]/info.ts @@ -7,6 +7,7 @@ import { albums } from "@/schema/albums.schema"; import { count, eq, min, max, sql, and } from "drizzle-orm"; import { assets } from "@/schema/assets.schema"; import { albumsAssetsAssets } from "@/schema/albumAssetsAssets.schema"; +import { albumUsers } from "@/schema/albumUsers.schema"; import { assetFaces, exif, person } from "@/schema"; export default async function handler( @@ -31,12 +32,13 @@ export default async function handler( faceCount: count(sql`DISTINCT ${person.id}`), // Ensure unique personId }) .from(albums) + .innerJoin(albumUsers, and(eq(albums.id, albumUsers.albumId), eq(albumUsers.role, "owner"))) .leftJoin(albumsAssetsAssets, eq(albums.id, albumsAssetsAssets.albumId)) .leftJoin(assets, eq(albumsAssetsAssets.assetId, assets.id)) .leftJoin(exif, and(eq(assets.id, exif.assetId), eq(assets.visibility, "timeline"))) .leftJoin(assetFaces, eq(assets.id, assetFaces.assetId)) .leftJoin(person, and(eq(assetFaces.personId, person.id), eq(person.isHidden, false))) - .where(and(eq(albums.ownerId, currentUser.id), eq(albums.id, id))) + .where(and(eq(albumUsers.userId, currentUser.id), eq(albums.id, id))) .groupBy(albums.id) .limit(1); diff --git a/src/pages/api/albums/[id]/people.ts b/src/pages/api/albums/[id]/people.ts index b39c3db..364af31 100644 --- a/src/pages/api/albums/[id]/people.ts +++ b/src/pages/api/albums/[id]/people.ts @@ -7,6 +7,7 @@ import { albums } from "@/schema/albums.schema"; import { count, desc, eq, and, isNotNull } from "drizzle-orm"; import { assets } from "@/schema/assets.schema"; import { albumsAssetsAssets } from "@/schema/albumAssetsAssets.schema"; +import { albumUsers } from "@/schema/albumUsers.schema"; import { assetFaces, person } from "@/schema"; export default async function handler( @@ -26,11 +27,12 @@ export default async function handler( numberOfPhotos: count(assets.id), }) .from(albums) + .innerJoin(albumUsers, and(eq(albums.id, albumUsers.albumId), eq(albumUsers.role, "owner"))) .leftJoin(albumsAssetsAssets, eq(albums.id, albumsAssetsAssets.albumId)) .leftJoin(assets, eq(albumsAssetsAssets.assetId, assets.id)) .leftJoin(assetFaces, eq(assets.id, assetFaces.assetId)) .leftJoin(person, and(eq(assetFaces.personId, person.id), eq(person.isHidden, false))) - .where(and(eq(albums.ownerId, currentUser.id), eq(albums.id, id), isNotNull(person.id))) + .where(and(eq(albumUsers.userId, currentUser.id), eq(albums.id, id), isNotNull(person.id))) .orderBy(desc(person.name)) .groupBy(person.id); diff --git a/src/pages/api/albums/list.ts b/src/pages/api/albums/list.ts index 4eb2f17..275b375 100644 --- a/src/pages/api/albums/list.ts +++ b/src/pages/api/albums/list.ts @@ -7,6 +7,7 @@ import { albums } from "@/schema/albums.schema"; import { count, desc, eq, min, max, sql, and, sum, isNotNull } from "drizzle-orm"; import { assets } from "@/schema/assets.schema"; import { albumsAssetsAssets } from "@/schema/albumAssetsAssets.schema"; +import { albumUsers } from "@/schema/albumUsers.schema"; import { assetFaces, exif, person } from "@/schema"; import { IAlbum } from "@/types/album"; @@ -63,12 +64,13 @@ export default async function handler( size: sum(exif.fileSizeInByte), order: albums.order, isActivityEnabled: albums.isActivityEnabled, - ownerId: albums.ownerId, + ownerId: albumUsers.userId, description: albums.description, lastModifiedAssetTimestamp: max(exif.dateTimeOriginal), faceCount: count(sql`DISTINCT ${assetFaces.personId}`), // Ensure unique personId }) .from(albums) + .innerJoin(albumUsers, and(eq(albums.id, albumUsers.albumId), eq(albumUsers.role, "owner"))) .leftJoin(albumsAssetsAssets, eq(albums.id, albumsAssetsAssets.albumId)) .leftJoin(assets, and( eq(albumsAssetsAssets.assetId, assets.id), @@ -78,8 +80,8 @@ export default async function handler( .leftJoin(exif, eq(assets.id, exif.assetId)) .leftJoin(assetFaces, eq(assets.id, assetFaces.assetId)) .leftJoin(person, and(eq(assetFaces.personId, person.id), eq(person.isHidden, false))) - .where(eq(albums.ownerId, currentUser.id)) - .groupBy(albums.id) + .where(eq(albumUsers.userId, currentUser.id)) + .groupBy(albums.id, albumUsers.userId) .orderBy(desc(albums.createdAt)); const sortedAlbums = sortAlbums(dbAlbums as IAlbum[], sortBy, sortOrder); diff --git a/src/pages/api/albums/merge.ts b/src/pages/api/albums/merge.ts index 45e56ab..979c2fe 100644 --- a/src/pages/api/albums/merge.ts +++ b/src/pages/api/albums/merge.ts @@ -5,6 +5,7 @@ import { getCurrentUser } from "@/handlers/serverUtils/user.utils"; import API from "@/lib/api"; import { albumsAssetsAssets } from "@/schema/albumAssetsAssets.schema"; import { albums } from "@/schema/albums.schema"; +import { albumUsers } from "@/schema/albumUsers.schema"; import { and, eq, inArray } from "drizzle-orm"; import { NextApiRequest, NextApiResponse } from "next"; @@ -35,11 +36,16 @@ export default async function handler( }); } + const ownedAlbumIds = db + .select({ albumId: albumUsers.albumId }) + .from(albumUsers) + .where(and(eq(albumUsers.userId, currentUser.id), eq(albumUsers.role, "owner"))); + const primaryAlbum = await db .select() .from(albums) .where( - and(eq(albums.id, primaryAlbumId), eq(albums.ownerId, currentUser.id)) + and(eq(albums.id, primaryAlbumId), inArray(albums.id, ownedAlbumIds)) ) .limit(1); @@ -51,7 +57,7 @@ export default async function handler( const secondaryAlbums = await db .select() .from(albums) - .where(and(inArray(albums.id, secondaryAlbumIds), eq(albums.ownerId, currentUser.id))); + .where(and(inArray(albums.id, secondaryAlbumIds), inArray(albums.id, ownedAlbumIds))); if (secondaryAlbums.length === 0) { diff --git a/src/pages/api/analytics/statistics/heatmap.tsx b/src/pages/api/analytics/statistics/heatmap.tsx index d330b1a..c502720 100644 --- a/src/pages/api/analytics/statistics/heatmap.tsx +++ b/src/pages/api/analytics/statistics/heatmap.tsx @@ -1,69 +1,101 @@ // Next.js API route support: https://nextjs.org/docs/api-routes/introduction import { db } from "@/config/db"; import { getCurrentUser } from "@/handlers/serverUtils/user.utils"; -import { assets, exif } from "@/schema"; -import { and, count, desc, eq, gte, isNotNull, ne, sql, } from "drizzle-orm"; +import { assets } from "@/schema"; +import { and, between, eq, gte, sql } from "drizzle-orm"; +import { count } from "drizzle-orm"; import type { NextApiRequest, NextApiResponse } from "next"; -// Helper function to format date as YYYY-MM-DD function formatDate(date: Date) { - return date.toISOString().split('T')[0]; + return date.toISOString().split("T")[0]; } -function fillMissingDates(data: any[]) { - const today = new Date(); +/** + * Fill gaps in a date-indexed series so the heatmap always has 365ish cells + * drawn, even for dates with zero photos. + * + * - No `year` → 12-month rolling window ending today (legacy behaviour). + * - `year` given → fill every day of that calendar year. + */ +function fillMissingDates(data: Array<{ date: string; count: number }>, year?: number) { + const existing = new Map(data.map((d) => [d.date, d])); - // Set the start date as one year ago, excluding the current month in the previous year - const oneYearAgo = new Date(today.getFullYear() - 1, today.getMonth() + 1, 1); // First day of the next month last year + let start: Date; + let end: Date; + if (year) { + start = new Date(Date.UTC(year, 0, 1)); + end = new Date(Date.UTC(year, 11, 31)); + } else { + end = new Date(); + start = new Date(end.getFullYear() - 1, end.getMonth() + 1, 1); + } - const existingDates = new Set(data.map(item => item.date)); - - const filledData = []; - - // Iterate from today to one year ago, but skip the current month from last year - for (let d = new Date(today); d >= oneYearAgo; d.setDate(d.getDate() - 1)) { - const dateStr = formatDate(d); - - // Skip dates in the current month of the previous year - if (d.getFullYear() === today.getFullYear() - 1 && d.getMonth() === today.getMonth()) { - continue; - } - - if (existingDates.has(dateStr)) { - filledData.push(data.find(item => item.date === dateStr)); - } else { - filledData.push({ date: dateStr, count: 0 }); - } + const filled: Array<{ date: string; count: number }> = []; + for (let d = new Date(start); d <= end; d.setUTCDate(d.getUTCDate() + 1)) { + // Legacy quirk preserved: skip days that land in the repeating "current + // month" of the previous year in the rolling 12-month window, so the + // heatmap isn't double-counted on the seam. + if (!year && d.getFullYear() === end.getFullYear() - 1 && d.getMonth() === end.getMonth()) { + continue; } - - // Sort the filled data in descending order - filledData.sort((a, b) => a.date.localeCompare(b.date)); - return filledData; + const key = formatDate(d); + filled.push(existing.get(key) ?? { date: key, count: 0 }); + } + filled.sort((a, b) => a.date.localeCompare(b.date)); + return filled; } -export default async function handler( - req: NextApiRequest, - res: NextApiResponse -) { - try { - const currentUser = await getCurrentUser(req); - const dataFromDB = await db.select({ - date: sql`DATE(${assets.fileCreatedAt})`.as('date'), - count: count(), +export default async function handler(req: NextApiRequest, res: NextApiResponse) { + try { + const currentUser = await getCurrentUser(req); + if (!currentUser) return res.status(401).json({ message: "Unauthorized" }); + + const rawYear = (req.query.year as string | undefined)?.trim(); + const year = + rawYear && /^\d{4}$/.test(rawYear) ? Number.parseInt(rawYear, 10) : undefined; + + // Range clause: either a whole calendar year, or the legacy 12-month rolling window. + const rangeClause = year + ? between( + assets.fileCreatedAt, + sql`${`${year}-01-01`}::timestamptz`, + sql`${`${year}-12-31 23:59:59`}::timestamptz` + ) + : gte(assets.fileCreatedAt, sql`CURRENT_DATE - INTERVAL '1 YEAR'`); + + const [dataFromDB, yearsRaw] = await Promise.all([ + db + .select({ + date: sql`TO_CHAR(DATE(${assets.fileCreatedAt}), 'YYYY-MM-DD')`.as("date"), + count: count(), }) - .from(assets) - .where( - and( - eq(assets.ownerId, currentUser.id), - gte(assets.fileCreatedAt, sql`CURRENT_DATE - INTERVAL '1 YEAR'`)) - ) - .groupBy(sql`DATE(${assets.fileCreatedAt})`) - .orderBy(sql`DATE(${assets.fileCreatedAt}) DESC`) - const updatedData = fillMissingDates(dataFromDB); - return res.status(200).json(updatedData); - } catch (error: any) { - res.status(500).json({ - error: error?.message, - }); - } + .from(assets) + .where(and(eq(assets.ownerId, currentUser.id), rangeClause)) + .groupBy(sql`DATE(${assets.fileCreatedAt})`) + .orderBy(sql`DATE(${assets.fileCreatedAt}) DESC`), + // Distinct years the user has assets for, for the UI year selector. + db + .select({ + year: sql`EXTRACT(YEAR FROM ${assets.fileCreatedAt})::int`.as("year"), + }) + .from(assets) + .where(eq(assets.ownerId, currentUser.id)) + .groupBy(sql`EXTRACT(YEAR FROM ${assets.fileCreatedAt})`) + .orderBy(sql`EXTRACT(YEAR FROM ${assets.fileCreatedAt}) DESC`), + ]); + + const filled = fillMissingDates( + (dataFromDB as Array<{ date: string; count: number }>), + year + ); + + return res.status(200).json({ + data: filled, + year: year ?? null, + availableYears: (yearsRaw as Array<{ year: number }>).map((r) => r.year).filter(Boolean), + }); + } catch (error: any) { + console.error(error); + return res.status(500).json({ error: error?.message }); + } } diff --git a/src/pages/api/assets/albums-by-assets.ts b/src/pages/api/assets/albums-by-assets.ts index 3573a9a..511c76f 100644 --- a/src/pages/api/assets/albums-by-assets.ts +++ b/src/pages/api/assets/albums-by-assets.ts @@ -3,8 +3,17 @@ import { db } from "@/config/db"; import { getCurrentUser } from "@/handlers/serverUtils/user.utils"; import { albums } from "@/schema/albums.schema"; import { albumsAssetsAssets } from "@/schema/albumAssetsAssets.schema"; +import { albumUsers } from "@/schema/albumUsers.schema"; import { eq, inArray, and } from "drizzle-orm"; +export const config = { + api: { + bodyParser: { + sizeLimit: "10mb", + }, + }, +}; + export default async function handler( req: NextApiRequest, res: NextApiResponse @@ -31,10 +40,11 @@ export default async function handler( }) .from(albumsAssetsAssets) .innerJoin(albums, eq(albumsAssetsAssets.albumId, albums.id)) + .innerJoin(albumUsers, and(eq(albumUsers.albumId, albums.id), eq(albumUsers.role, "owner"))) .where( and( inArray(albumsAssetsAssets.assetId, assetIds), - eq(albums.ownerId, currentUser.id) + eq(albumUsers.userId, currentUser.id) ) ); diff --git a/src/pages/api/assets/empty-videos.ts b/src/pages/api/assets/empty-videos.ts index 4a7b62d..46d4fbd 100644 --- a/src/pages/api/assets/empty-videos.ts +++ b/src/pages/api/assets/empty-videos.ts @@ -39,19 +39,11 @@ export default async function handler( } - const durationExpr = sql` - ( - CAST(SUBSTRING(${assets.duration}, 1, 2) AS DECIMAL) * 3600 + - CAST(SUBSTRING(${assets.duration}, 4, 2) AS DECIMAL) * 60 + - CAST(SUBSTRING(${assets.duration}, 7, 2) AS DECIMAL) + - CAST(SUBSTRING(${assets.duration}, 10, 3) AS DECIMAL) / 1000 - ) -`; + const durationExpr = sql`(${assets.duration}::decimal / 1000)`; const dbAssets = await db .selectDistinctOn([assets.id], { id: assets.id, - deviceId: assets.deviceId, type: assets.type, originalPath: assets.originalPath, isFavorite: assets.isFavorite, diff --git a/src/pages/api/assets/missing-location-assets.ts b/src/pages/api/assets/missing-location-assets.ts index e7bd342..09105a4 100644 --- a/src/pages/api/assets/missing-location-assets.ts +++ b/src/pages/api/assets/missing-location-assets.ts @@ -15,7 +15,6 @@ const getRowsByDates = async (startDateDate: Date, endDateDate: Date, currentUse return db .select({ id: assets.id, - deviceId: assets.deviceId, type: assets.type, originalPath: assets.originalPath, isFavorite: assets.isFavorite, @@ -46,7 +45,6 @@ const getRowsByDates = async (startDateDate: Date, endDateDate: Date, currentUse const getRowsByAlbums = async (currentUser: IUser, albumId: string) => { return db.select({ id: assets.id, - deviceId: assets.deviceId, type: assets.type, originalPath: assets.originalPath, isFavorite: assets.isFavorite, diff --git a/src/pages/api/assets/orphan-finder.ts b/src/pages/api/assets/orphan-finder.ts index 55c3e82..ffd682b 100644 --- a/src/pages/api/assets/orphan-finder.ts +++ b/src/pages/api/assets/orphan-finder.ts @@ -67,7 +67,6 @@ export default async function handler( const dbAssets = await db .selectDistinctOn([assets.id], { id: assets.id, - deviceId: assets.deviceId, type: assets.type, originalPath: assets.originalPath, isFavorite: assets.isFavorite, diff --git a/src/pages/api/find/search.ts b/src/pages/api/find/search.ts index e5fead7..a28217e 100644 --- a/src/pages/api/find/search.ts +++ b/src/pages/api/find/search.ts @@ -4,6 +4,7 @@ import { ASSET_VIDEO_PATH } from "@/config/routes"; import { getCurrentUser } from "@/handlers/serverUtils/user.utils"; import { cleanUpAsset, isFlipped } from "@/helpers/asset.helper"; import { parseFindQuery } from "@/helpers/ai.helper"; +import { getUserHeaders } from "@/helpers/user.helper"; import { person } from "@/schema"; import { Person } from "@/schema/person.schema"; import { inArray } from "drizzle-orm"; @@ -16,6 +17,9 @@ export default async function search( try { const { query } = req.body; const currentUser = await getCurrentUser(req); + if (!currentUser) { + return res.status(403).json({ message: "Not authenticated" }); + } const parsedQuery = await parseFindQuery(query as string); const { personIds } = parsedQuery; @@ -32,10 +36,7 @@ export default async function search( return fetch(url, { method: "POST", body: JSON.stringify({ ...parsedQuery, withExif: true }), - headers: { - "Content-Type": "application/json", - Authorization: `Bearer ${currentUser?.accessToken}`, - }, + headers: getUserHeaders(currentUser, { "Content-Type": "application/json" }), }) .then((response) => { if (response.status !== 200) { diff --git a/src/pages/api/import-shared.ts b/src/pages/api/import-shared.ts index c2238a3..81620c1 100644 --- a/src/pages/api/import-shared.ts +++ b/src/pages/api/import-shared.ts @@ -1,5 +1,6 @@ import type { NextApiRequest, NextApiResponse } from "next"; import { detectNextcloud, checkPasswordProtection, listNextcloudFiles } from "./import-shared/nextcloud"; +import { detectEnte, fetchEnteAlbum } from "./import-shared/ente"; interface IAlbumContributorCount { userId: string; @@ -11,28 +12,10 @@ interface ImmichOwner { email?: string | null; } -interface ImmichExifInfo { - city?: string | null; - state?: string | null; - country?: string | null; - description?: string | null; - fileSizeInByte?: number | null; -} - -interface ImmichAsset { - id: string; - originalFileName: string; - type: string; - fileCreatedAt?: string | null; - localDateTime?: string | null; - thumbhash?: string | null; - exifInfo?: ImmichExifInfo | null; -} - interface ImmichAlbumResponse { albumName: string; assetCount?: number; - owner?: ImmichOwner | null; + albumUsers?: { user: ImmichOwner; role: string }[]; description?: string | null; startDate?: string | null; endDate?: string | null; @@ -41,7 +24,6 @@ interface ImmichAlbumResponse { lastModifiedAssetTimestamp?: string | null; order?: string | null; contributorCounts?: IAlbumContributorCount[]; - assets: ImmichAsset[]; } interface ImmichSharedLinkResponse { @@ -58,7 +40,7 @@ interface ImmichSharedLinkResponse { interface IImportSharedAsset { id: string; - originalFileName: string; + originalFileName?: string; type: string; fileCreatedAt?: string | null; localDateTime?: string | null; @@ -66,6 +48,19 @@ interface IImportSharedAsset { location?: string | null; thumbhash?: string | null; fileSizeInByte?: number | null; + // Ente-specific encryption artifacts (optional) + enteFileKey?: string; + enteFileDecryptionHeader?: string; + enteThumbnailDecryptionHeader?: string; +} + +interface ITimeBucketAssets { + id: string[]; + fileCreatedAt: string[]; + isImage: boolean[]; + thumbhash: (string | null)[]; + city?: (string | null)[]; + country?: (string | null)[]; } interface IImportSharedAlbum { @@ -84,7 +79,7 @@ interface IImportSharedAlbum { } interface IImportSharedResponse { - platform: "immich" | "nextcloud"; + platform: "immich" | "nextcloud" | "ente"; link: string; origin: string; key: string; @@ -98,6 +93,9 @@ interface IImportSharedResponse { showMetadata?: boolean; }; album: IImportSharedAlbum | null; + // Ente-specific (optional) + enteApiBase?: string; + enteAlbumKey?: string; } const respondWithError = (res: NextApiResponse, status: number, message: string) => { @@ -122,13 +120,39 @@ const parseSharedLink = (link: string) => { } }; -const buildLocationString = (exif?: ImmichExifInfo | null) => { - if (!exif) { - return null; +const enumerateAlbumAssets = async ( + origin: string, + albumId: string, + authQuery: string +): Promise => { + const buckets = await fetchJson<{ timeBucket: string }[]>( + `${origin}/api/timeline/buckets?albumId=${albumId}&${authQuery}` + ); + + const assets: IImportSharedAsset[] = []; + for (const bucket of buckets) { + const columns = await fetchJson( + `${origin}/api/timeline/bucket?albumId=${albumId}&timeBucket=${encodeURIComponent(bucket.timeBucket)}&${authQuery}` + ); + const count = columns.id?.length ?? 0; + for (let i = 0; i < count; i++) { + const city = columns.city?.[i] ?? null; + const country = columns.country?.[i] ?? null; + const location = [city, country].filter(Boolean).join(", ") || null; + const fileCreatedAt = columns.fileCreatedAt?.[i] ?? null; + assets.push({ + id: columns.id[i], + type: columns.isImage?.[i] === false ? "VIDEO" : "IMAGE", + fileCreatedAt, + localDateTime: fileCreatedAt, + description: null, + location, + thumbhash: columns.thumbhash?.[i] ?? null, + fileSizeInByte: null, + }); + } } - const parts = [exif.city, exif.state, exif.country] - .filter((value): value is string => !!value && value.trim().length > 0); - return parts.length > 0 ? parts.join(", ") : null; + return assets; }; const fetchJson = async (url: string) => { @@ -246,10 +270,90 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse) } } + // ── Ente flow ── + const ente = detectEnte(link); + if (ente) { + try { + const result = await fetchEnteAlbum(link); + + const assets: IImportSharedAsset[] = result.files.map((f) => ({ + id: f.id, + originalFileName: f.title, + type: f.type, + fileCreatedAt: f.creationTime + ? new Date(f.creationTime / 1000).toISOString() + : null, + localDateTime: f.modificationTime + ? new Date(f.modificationTime / 1000).toISOString() + : null, + description: null, + location: null, + thumbhash: null, + fileSizeInByte: f.fileSize ?? null, + enteFileKey: f.fileKey, + enteFileDecryptionHeader: f.fileDecryptionHeader, + enteThumbnailDecryptionHeader: f.thumbnailDecryptionHeader, + })); + + const dates = result.files + .map((f) => f.creationTime) + .filter((t) => t > 0); + const startDate = + dates.length > 0 + ? new Date(Math.min(...dates) / 1000).toISOString() + : null; + const endDate = + dates.length > 0 + ? new Date(Math.max(...dates) / 1000).toISOString() + : null; + + const responseBody: IImportSharedResponse = { + platform: "ente", + link: link.trim(), + origin: result.apiBase, + key: result.token, + sharedLink: { + id: result.token, + type: "ALBUM", + createdAt: new Date().toISOString(), + expiresAt: null, + allowUpload: false, + allowDownload: true, + showMetadata: true, + }, + album: { + albumName: result.albumName, + assetCount: assets.length, + owner: null, + description: null, + startDate, + endDate, + shared: true, + hasSharedLink: true, + lastModifiedAssetTimestamp: endDate, + order: null, + contributorCounts: [], + assets, + }, + enteApiBase: result.apiBase, + enteAlbumKey: result.albumKeyB58, + }; + + return res.status(200).json(responseBody); + } catch (error: any) { + console.error("Ente import shared error", error); + return respondWithError( + res, + 500, + error?.message ?? "Failed to fetch Ente album" + ); + } + } + // ── Immich flow ── const parsed = parseSharedLink(link); if (!parsed) { - return respondWithError(res, 400, "Invalid share link. Supported: Immich or Nextcloud share URLs."); + return respondWithError(res, 400, "Invalid share link. Supported: Immich, Nextcloud, or Ente share URLs."); } const authQuery = password @@ -266,25 +370,15 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse) if (albumId) { const album = await fetchJson( - `${parsed.origin}/api/albums/${albumId}?${authQuery}&withoutAssets=false` + `${parsed.origin}/api/albums/${albumId}?${authQuery}` ); - const assets = (album.assets || []).map((asset) => ({ - id: asset.id, - originalFileName: asset.originalFileName, - type: asset.type, - fileCreatedAt: asset.fileCreatedAt ?? null, - localDateTime: asset.localDateTime ?? null, - description: asset.exifInfo?.description ?? null, - location: buildLocationString(asset.exifInfo), - thumbhash: asset.thumbhash ?? null, - fileSizeInByte: asset.exifInfo?.fileSizeInByte ?? null, - } satisfies IImportSharedAsset)); + const assets = await enumerateAlbumAssets(parsed.origin, albumId, authQuery); albumResult = { albumName: album.albumName, assetCount: album.assetCount ?? assets.length, - owner: album.owner ?? null, + owner: album.albumUsers?.[0]?.user ?? null, description: album.description ?? null, startDate: album.startDate ?? null, endDate: album.endDate ?? null, diff --git a/src/pages/api/import-shared/ente.ts b/src/pages/api/import-shared/ente.ts new file mode 100644 index 0000000..37ccf24 --- /dev/null +++ b/src/pages/api/import-shared/ente.ts @@ -0,0 +1,328 @@ +import _sodium from "libsodium-wrappers-sumo"; +import bs58 from "bs58"; +import { inferAssetTypeFromName } from "./helpers"; + +// ── Types ──────────────────────────────────────────────────────────────────── + +export interface EnteDetection { + apiBase: string; + token: string; + albumKeyB58: string; + albumKey: Uint8Array; +} + +export interface EnteDecryptedFile { + id: string; + title: string; + type: "IMAGE" | "VIDEO"; + creationTime: number; + modificationTime: number; + fileSize?: number; + fileKey: string; // base64 + fileDecryptionHeader: string; // base64 + thumbnailDecryptionHeader: string; // base64 +} + +export interface EnteAlbumResult { + albumName: string; + apiBase: string; + token: string; + albumKeyB58: string; + files: EnteDecryptedFile[]; +} + +interface EnteCollectionResponse { + collection: { + id: number; + encryptedKey: string; + keyDecryptionNonce: string; + encryptedName: string; + nameDecryptionNonce: string; + publicURLs?: Array<{ + enableDownload?: boolean; + enableCollect?: boolean; + }>; + }; +} + +interface EnteDiffFile { + id: number; + encryptedKey: string; + keyDecryptionNonce: string; + file: { decryptionHeader: string; size: number }; + thumbnail: { decryptionHeader: string; size: number }; + metadata: { + encryptedData: string; + decryptionHeader: string; + size: number; + }; + isDeleted: boolean; + updationTime: number; + info?: { fileSize?: number; thumbSize?: number }; +} + +interface EnteDiffResponse { + diff: EnteDiffFile[]; + hasMore: boolean; +} + +// ── Crypto ─────────────────────────────────────────────────────────────────── + +let sodiumReady: typeof _sodium | null = null; + +const initSodium = async (): Promise => { + if (sodiumReady) return sodiumReady; + await _sodium.ready; + sodiumReady = _sodium; + return _sodium; +}; + +export const decryptSecretBox = async ( + ciphertext_b64: string, + nonce_b64: string, + key: Uint8Array +): Promise => { + const sodium = await initSodium(); + const ciphertext = sodium.from_base64(ciphertext_b64, sodium.base64_variants.ORIGINAL); + const nonce = sodium.from_base64(nonce_b64, sodium.base64_variants.ORIGINAL); + return sodium.crypto_secretbox_open_easy(ciphertext, nonce, key); +}; + +const PLAIN_CHUNK = 4 * 1024 * 1024; // 4 MiB + +export const decryptSecretStream = async ( + encryptedData: Buffer | Uint8Array, + header_b64: string, + key: Uint8Array +): Promise => { + const sodium = await initSodium(); + const header = sodium.from_base64(header_b64, sodium.base64_variants.ORIGINAL); + const ABYTES = sodium.crypto_secretstream_xchacha20poly1305_ABYTES; + const ENC_CHUNK = PLAIN_CHUNK + ABYTES; + + const state = sodium.crypto_secretstream_xchacha20poly1305_init_pull(header, key); + const out: Uint8Array[] = []; + let offset = 0; + const total = encryptedData.length; + + while (offset < total) { + const end = Math.min(offset + ENC_CHUNK, total); + const chunk = encryptedData.subarray(offset, end); + const result = sodium.crypto_secretstream_xchacha20poly1305_pull(state, chunk, null); + if (!result) throw new Error("Decryption failed: invalid secretstream chunk"); + out.push(result.message); + offset = end; + } + + return Buffer.concat(out); +}; + +// ── URL Detection ──────────────────────────────────────────────────────────── + +/** + * Detect if a URL is an Ente public album link. + * Format: https://albums.ente.io/?t=TOKEN#BASE58KEY + * Or self-hosted: https://albums.example.com/?t=TOKEN#BASE58KEY + */ +export const detectEnte = (url: string): EnteDetection | null => { + const trimmed = url.trim(); + + // Extract fragment from raw string (new URL strips it) + const hashIdx = trimmed.indexOf("#"); + if (hashIdx < 0) return null; + const fragment = trimmed.substring(hashIdx + 1); + if (!fragment) return null; + + // Parse the part before the fragment + let parsed: URL; + try { + parsed = new URL(trimmed.substring(0, hashIdx)); + } catch { + return null; + } + + const token = parsed.searchParams.get("t"); + if (!token) return null; + + // Validate base58 key + let albumKey: Uint8Array; + try { + albumKey = bs58.decode(fragment); + if (albumKey.length !== 32) return null; // XSalsa20-Poly1305 key must be 32 bytes + } catch { + return null; + } + + const apiBase = resolveApiBase(parsed); + + return { apiBase, token, albumKeyB58: fragment, albumKey }; +}; + +const resolveApiBase = (parsed: URL): string => { + if (parsed.hostname === "albums.ente.io") { + return "https://api.ente.io"; + } + // Self-hosted: replace "albums." prefix with "api." if present + if (parsed.hostname.startsWith("albums.")) { + const rest = parsed.hostname.substring("albums.".length); + return `${parsed.protocol}//api.${rest}`; + } + // Fallback: same origin + return parsed.origin; +}; + +// ── Ente API Client ────────────────────────────────────────────────────────── + +const enteHeaders = (token: string): Record => ({ + "X-Auth-Access-Token": token, + Accept: "application/json", +}); + +const getCollectionInfo = async ( + apiBase: string, + token: string +): Promise => { + const resp = await fetch(`${apiBase}/public-collection/info`, { + headers: enteHeaders(token), + timeout: 10_000, + } as RequestInit); + if (!resp.ok) { + throw new Error(`Ente API /public-collection/info failed (status ${resp.status})`); + } + return resp.json(); +}; + +const getCollectionFiles = async ( + apiBase: string, + token: string +): Promise => { + const files: EnteDiffFile[] = []; + let sinceTime = 0; + + while (true) { + const resp = await fetch( + `${apiBase}/public-collection/diff?sinceTime=${sinceTime}`, + { headers: enteHeaders(token), timeout: 15_000 } as RequestInit + ); + if (!resp.ok) { + throw new Error(`Ente API /public-collection/diff failed (status ${resp.status})`); + } + const data: EnteDiffResponse = await resp.json(); + const batch = data.diff.filter((f) => !f.isDeleted); + files.push(...batch); + + if (!data.hasMore) break; + sinceTime = Math.max(...data.diff.map((f) => f.updationTime)); + } + + return files; +}; + +/** + * Get the presigned download URL for an Ente file or thumbnail. + * The API returns a 307 redirect — we capture the Location header. + * Note: Ente uses "preview" (not "thumbnail") for the thumbnail endpoint. + */ +export const getFileRedirectUrl = async ( + apiBase: string, + token: string, + fileId: string | number, + kind: "download" | "preview" +): Promise => { + const resp = await fetch( + `${apiBase}/public-collection/files/${kind}/${fileId}`, + { + headers: enteHeaders(token), + redirect: "manual", + timeout: 15_000, + } as RequestInit + ); + + if (resp.status >= 301 && resp.status <= 308) { + const location = resp.headers.get("Location"); + if (location) return location; + } + + if (resp.ok) return resp.url; + + throw new Error( + `Ente API files/${kind}/${fileId} failed (status ${resp.status})` + ); +}; + +// ── High-level Orchestrator ────────────────────────────────────────────────── + +/** + * Fetch and decrypt an Ente shared album. + * Returns decrypted album name, file metadata, and encryption artifacts for later download. + */ +export const fetchEnteAlbum = async (url: string): Promise => { + const detection = detectEnte(url); + if (!detection) throw new Error("Invalid Ente album URL"); + + const { apiBase, token, albumKey, albumKeyB58 } = detection; + const sodium = await initSodium(); + + // Fetch collection info & decrypt album name + const info = await getCollectionInfo(apiBase, token); + const collection = info.collection; + + let albumName = "Ente Album"; + try { + const nameBytes = await decryptSecretBox( + collection.encryptedName, + collection.nameDecryptionNonce, + albumKey + ); + albumName = sodium.to_string(nameBytes); + } catch { + // Album name decryption failed — use default + } + + // Fetch all files + const rawFiles = await getCollectionFiles(apiBase, token); + + // Decrypt metadata for each file + const files: EnteDecryptedFile[] = []; + + for (const file of rawFiles) { + try { + // Decrypt per-file key using album key + const fileKey = await decryptSecretBox( + file.encryptedKey, + file.keyDecryptionNonce, + albumKey + ); + + // Decrypt metadata using file key + secretstream + const metadataBuffer = await decryptSecretStream( + Buffer.from(file.metadata.encryptedData, "base64"), + file.metadata.decryptionHeader, + fileKey + ); + const metadata = JSON.parse(metadataBuffer.toString("utf-8")); + + const title: string = metadata.title || `file_${file.id}`; + const fileType: number = metadata.fileType ?? 0; // 0=image, 1=video + const type: "IMAGE" | "VIDEO" = + fileType === 1 ? "VIDEO" : inferAssetTypeFromName(title) === "VIDEO" ? "VIDEO" : "IMAGE"; + + files.push({ + id: String(file.id), + title, + type, + creationTime: metadata.creationTime ?? 0, + modificationTime: metadata.modificationTime ?? metadata.creationTime ?? 0, + fileSize: file.info?.fileSize, + fileKey: sodium.to_base64(fileKey, sodium.base64_variants.ORIGINAL), + fileDecryptionHeader: file.file.decryptionHeader, + thumbnailDecryptionHeader: file.thumbnail.decryptionHeader, + }); + } catch (err) { + console.warn(`[Ente] Failed to decrypt metadata for file ${file.id}:`, err); + // Skip files we can't decrypt + } + } + + return { albumName, apiBase, token, albumKeyB58, files }; +}; diff --git a/src/pages/api/import-shared/helpers.ts b/src/pages/api/import-shared/helpers.ts index 8f4968f..36f6919 100644 --- a/src/pages/api/import-shared/helpers.ts +++ b/src/pages/api/import-shared/helpers.ts @@ -174,7 +174,6 @@ export const uploadAssetBuffer = async ( payload: DownloadedAssetPayload, uploadHeaders: HeadersRecord, jsonHeaders: HeadersRecord, - deviceAssetId: string, tagId?: string ): Promise => { const fileType = asset.type ?? inferAssetTypeFromName(payload.fileName); @@ -187,14 +186,11 @@ export const uploadAssetBuffer = async ( const modifiedAt = asset.localDateTime ?? asset.fileCreatedAt ?? createdAt; const formData = new FormData(); - formData.set("deviceAssetId", deviceAssetId); - formData.set("deviceId", DEVICE_ID); formData.set("fileCreatedAt", createdAt); formData.set("fileModifiedAt", modifiedAt); formData.set("fileType", fileType); - formData.set("duration", asset.duration ?? "0:00:00.000000"); formData.set("assetData", blob, resolvedFileName); - if (asset.isArchived) formData.set("isArchived", String(asset.isArchived)); + if (asset.isArchived) formData.set("visibility", "archive"); if (asset.isFavorite) formData.set("isFavorite", String(asset.isFavorite)); const uploadResponse = await fetch(`${ENV.IMMICH_URL}/api/assets`, { @@ -222,6 +218,52 @@ export const uploadAssetBuffer = async ( return uploadedId; }; +export const fetchSourceAssetChecksum = async ( + origin: string, + assetId: string, + key: string +): Promise => { + try { + const res = await fetch( + `${origin}/api/assets/${assetId}?key=${encodeURIComponent(key)}`, + { headers: { accept: "application/json" } } + ); + if (!res.ok) return null; + const data = await res.json().catch(() => null); + return typeof data?.checksum === "string" ? data.checksum : null; + } catch { + return null; + } +}; + +export const findExistingAssetIds = async ( + targetJsonHeaders: HeadersRecord, + items: { id: string; checksum: string }[] +): Promise> => { + const existing = new Set(); + if (items.length === 0) return existing; + try { + const res = await fetch(`${ENV.IMMICH_URL}/api/assets/bulk-upload-check`, { + method: "POST", + headers: targetJsonHeaders, + body: JSON.stringify({ assets: items }), + }); + if (!res.ok) { + console.warn(`[import] bulk-upload-check failed (status ${res.status})`); + return existing; + } + const data = await res.json().catch(() => ({})); + for (const result of data?.results ?? []) { + if (result?.action === "reject" && result?.reason === "duplicate" && typeof result?.id === "string") { + existing.add(result.id); + } + } + } catch (error) { + console.warn("[import] bulk-upload-check error", error); + } + return existing; +}; + export const tagAssetWithPowerTools = async ( tagId: string, assetId: string, diff --git a/src/pages/api/import-shared/thumbnail.ts b/src/pages/api/import-shared/thumbnail.ts index ae120c6..349fc7d 100644 --- a/src/pages/api/import-shared/thumbnail.ts +++ b/src/pages/api/import-shared/thumbnail.ts @@ -1,4 +1,6 @@ import type { NextApiRequest, NextApiResponse } from "next"; +import { getFileRedirectUrl, decryptSecretStream, decryptSecretBox } from "./ente"; +import _sodium from "libsodium-wrappers-sumo"; const respondWithError = (res: NextApiResponse, status: number, message: string) => { return res.status(status).json({ error: message }); @@ -59,6 +61,32 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse) } try { + // ── Ente: encrypted thumbnails ── + if (params.platform === "ente") { + const enteFileKey = typeof req.query.enteFileKey === "string" ? req.query.enteFileKey : ""; + const enteThumbnailHeader = typeof req.query.enteThumbnailHeader === "string" ? req.query.enteThumbnailHeader : ""; + const apiBase = typeof req.query.apiBase === "string" ? req.query.apiBase : params.origin; + + if (!enteFileKey || !enteThumbnailHeader) { + return respondWithError(res, 400, "Missing Ente encryption params (enteFileKey, enteThumbnailHeader)"); + } + + await _sodium.ready; + const fileKeyBytes = _sodium.from_base64(enteFileKey, _sodium.base64_variants.ORIGINAL); + + const redirectUrl = await getFileRedirectUrl(apiBase, params.key, params.assetId, "preview"); + const encryptedResp = await fetch(redirectUrl); + if (!encryptedResp.ok) { + return respondWithError(res, encryptedResp.status, "Failed to fetch Ente thumbnail"); + } + const encrypted = Buffer.from(await encryptedResp.arrayBuffer()); + const decrypted = await decryptSecretStream(encrypted, enteThumbnailHeader, fileKeyBytes); + + res.setHeader("Content-Type", "image/jpeg"); + res.setHeader("Cache-Control", "public, max-age=300"); + return res.status(200).send(decrypted); + } + let targetUrl: string; if (params.platform === "nextcloud") { diff --git a/src/pages/api/import-shared/upload-all.ts b/src/pages/api/import-shared/upload-all.ts index 0790d71..4b3f293 100644 --- a/src/pages/api/import-shared/upload-all.ts +++ b/src/pages/api/import-shared/upload-all.ts @@ -6,6 +6,8 @@ import { HeadersRecord, ensurePowerToolsTag, tagAssetWithPowerTools, + fetchSourceAssetChecksum, + findExistingAssetIds, } from "./helpers"; interface ISharedAssetPayload { @@ -43,10 +45,8 @@ interface DownloadedAssetPayload { contentType: string | null; } -const DEVICE_ID = "immich-power-tools"; const ALLOWED_ASSET_TYPES = new Set(["IMAGE", "VIDEO"]); const CONCURRENT_TRANSFERS = 4; -const makeDeviceAssetId = (assetId: string) => `shared-${assetId}`; const respondWithError = (res: NextApiResponse, status: number, message: string) => { return res.status(status).json({ error: message }); @@ -316,16 +316,13 @@ const uploadAssetBuffer = async ( const modifiedAt = asset.localDateTime ?? asset.fileCreatedAt ?? createdAt; const formData = new FormData(); - formData.set("deviceAssetId", makeDeviceAssetId(asset.id)); - formData.set("deviceId", DEVICE_ID); formData.set("fileCreatedAt", createdAt); formData.set("fileModifiedAt", modifiedAt); formData.set("fileType", fileType); - formData.set("duration", asset.duration ?? "0:00:00.000000"); formData.set("assetData", blob, resolvedFileName); if (asset.isArchived) { - formData.set("isArchived", String(asset.isArchived)); + formData.set("visibility", "archive"); } if (asset.isFavorite) { formData.set("isFavorite", String(asset.isFavorite)); @@ -390,46 +387,12 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse) "Content-Type": "application/json", }; - const deviceAssetIds: string[] = []; - const deviceAssetIdLookup = new Map(); + const checkItems: { id: string; checksum: string }[] = []; for (const asset of uploadableAssets) { - const deviceAssetId = makeDeviceAssetId(asset.id); - deviceAssetIds.push(deviceAssetId); - deviceAssetIdLookup.set(deviceAssetId.toLowerCase(), asset.id); - } - - const existingAssetIds = new Set(); - if (deviceAssetIds.length > 0) { - try { - const checkResponse = await fetch(`${ENV.IMMICH_URL}/api/assets/exist`, { - method: "POST", - headers: jsonHeadersWithContentType, - body: JSON.stringify({ - deviceAssetIds, - deviceId: DEVICE_ID, - }), - }); - - if (checkResponse.ok) { - const existPayload = await checkResponse.json().catch(() => ({})); - const existingIds: string[] = existPayload?.existingIds ?? []; - for (const deviceAssetId of existingIds) { - if (typeof deviceAssetId !== "string") { - continue; - } - const normalizedId = deviceAssetId.toLowerCase(); - const matchedAssetId = deviceAssetIdLookup.get(normalizedId); - if (matchedAssetId) { - existingAssetIds.add(matchedAssetId); - } - } - } else { - console.warn(`Failed to check existing assets before import (status ${checkResponse.status})`); - } - } catch (error) { - console.warn("Unable to check existing assets before import", error); - } + const checksum = await fetchSourceAssetChecksum(origin, asset.id, key); + if (checksum) checkItems.push({ id: asset.id, checksum }); } + const existingAssetIds = await findExistingAssetIds(jsonHeadersWithContentType, checkItems); const assetsToImport = uploadableAssets.filter((asset) => !existingAssetIds.has(asset.id)); const skippedAssetIds = uploadableAssets diff --git a/src/pages/api/import-shared/upload.ts b/src/pages/api/import-shared/upload.ts index 0732731..7fb36f5 100644 --- a/src/pages/api/import-shared/upload.ts +++ b/src/pages/api/import-shared/upload.ts @@ -117,16 +117,13 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse) const modifiedAt = asset.localDateTime ?? asset.fileCreatedAt ?? createdAt; const formData = new FormData(); - formData.set("deviceAssetId", `shared-${params.assetId}`); - formData.set("deviceId", "immich-power-tools"); formData.set("fileCreatedAt", createdAt); formData.set("fileModifiedAt", modifiedAt); formData.set("fileType", asset.type ?? "IMAGE"); - formData.set("duration", asset.duration ?? "0:00:00.000000"); formData.set("assetData", assetBlob, fileName); if (asset.isArchived) { - formData.set("isArchived", asset.isArchived.toString()); + formData.set("visibility", "archive"); } if (asset.isFavorite) { formData.set("isFavorite", asset.isFavorite.toString()); diff --git a/src/pages/api/import-shared/video.ts b/src/pages/api/import-shared/video.ts index 876db05..c1a64be 100644 --- a/src/pages/api/import-shared/video.ts +++ b/src/pages/api/import-shared/video.ts @@ -56,6 +56,11 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse) } try { + // Ente videos are encrypted — full decryption for preview is too expensive + if (params.platform === "ente") { + return respondWithError(res, 501, "Video preview is not available for Ente imports"); + } + let targetUrl: string; let fetchHeaders: Record; diff --git a/src/pages/api/settings/generate-import-api-key.ts b/src/pages/api/settings/generate-import-api-key.ts index df97ea5..24f46cc 100644 --- a/src/pages/api/settings/generate-import-api-key.ts +++ b/src/pages/api/settings/generate-import-api-key.ts @@ -5,17 +5,10 @@ import { getCurrentUser } from "@/handlers/serverUtils/user.utils"; import { getUserHeaders } from "@/helpers/user.helper"; import { and, eq } from "drizzle-orm"; import { NextApiRequest, NextApiResponse } from "next"; +import { IMPORT_PERMISSIONS, getPermissionNames } from "@/config/permissions"; export const IMPORT_API_KEY_SETTING = "import_api_key"; const IMPORT_KEY_NAME = "Power Tools Import Key"; -const IMPORT_PERMISSIONS = [ - "asset.read", - "asset.upload", - "album.read", - "album.create", - "album.update", - "tag.create", -]; export default async function handler(req: NextApiRequest, res: NextApiResponse) { if (req.method !== "POST") return res.status(405).json({ message: "Method not allowed" }); @@ -26,7 +19,7 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse) const immichRes = await fetch(`${ENV.IMMICH_URL}/api/api-keys`, { method: "POST", headers: getUserHeaders(currentUser, { "Content-Type": "application/json" }), - body: JSON.stringify({ name: IMPORT_KEY_NAME, permissions: IMPORT_PERMISSIONS }), + body: JSON.stringify({ name: IMPORT_KEY_NAME, permissions: getPermissionNames(IMPORT_PERMISSIONS) }), }); if (!immichRes.ok) { diff --git a/src/pages/api/settings/generate-workflow-api-key.ts b/src/pages/api/settings/generate-workflow-api-key.ts index e5cdd8f..7053631 100644 --- a/src/pages/api/settings/generate-workflow-api-key.ts +++ b/src/pages/api/settings/generate-workflow-api-key.ts @@ -5,17 +5,10 @@ import { getCurrentUser } from "@/handlers/serverUtils/user.utils"; import { getUserHeaders } from "@/helpers/user.helper"; import { and, eq } from "drizzle-orm"; import { NextApiRequest, NextApiResponse } from "next"; +import { WORKFLOW_PERMISSIONS, getPermissionNames } from "@/config/permissions"; const WORKFLOW_API_KEY_SETTING = "workflow_api_key"; const WORKFLOW_KEY_NAME = "Power Tools Workflow Key"; -const WORKFLOW_PERMISSIONS = [ - "asset.read", - "asset.update", - "album.read", - "album.create", - "album.update", - "tag.create", -]; export default async function handler(req: NextApiRequest, res: NextApiResponse) { if (req.method !== "POST") return res.status(405).json({ message: "Method not allowed" }); @@ -27,7 +20,7 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse) const immichRes = await fetch(`${ENV.IMMICH_URL}/api/api-keys`, { method: "POST", headers: getUserHeaders(currentUser, { "Content-Type": "application/json" }), - body: JSON.stringify({ name: WORKFLOW_KEY_NAME, permissions: WORKFLOW_PERMISSIONS }), + body: JSON.stringify({ name: WORKFLOW_KEY_NAME, permissions: getPermissionNames(WORKFLOW_PERMISSIONS) }), }); if (!immichRes.ok) { diff --git a/src/pages/api/settings/validate-api-key.ts b/src/pages/api/settings/validate-api-key.ts index 8f7c2aa..98eea94 100644 --- a/src/pages/api/settings/validate-api-key.ts +++ b/src/pages/api/settings/validate-api-key.ts @@ -1,14 +1,7 @@ import { ENV } from "@/config/environment"; import { getCurrentUser } from "@/handlers/serverUtils/user.utils"; import { NextApiRequest, NextApiResponse } from "next"; - -const REQUIRED_PERMISSIONS = [ - "asset.read", - "asset.update", - "album.create", - "album.update", - "tag.create", -]; +import { WORKFLOW_PERMISSIONS, getPermissionNames } from "@/config/permissions"; export default async function handler(req: NextApiRequest, res: NextApiResponse) { if (req.method !== "POST") return res.status(405).json({ message: "Method not allowed" }); @@ -16,16 +9,17 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse) const currentUser = await getCurrentUser(req); if (!currentUser) return res.status(401).json({ message: "Unauthorized" }); - const { apiKey } = req.body; + const { apiKey, requiredPermissions } = req.body; if (!apiKey) return res.status(400).json({ message: "apiKey is required" }); + const REQUIRED_PERMISSIONS: string[] = Array.isArray(requiredPermissions) ? requiredPermissions : getPermissionNames(WORKFLOW_PERMISSIONS); + try { - // Validate by calling Immich's auth endpoint with the key - const authRes = await fetch(`${ENV.IMMICH_URL}/api/users/me`, { + const keyRes = await fetch(`${ENV.IMMICH_URL}/api/api-keys/me`, { headers: { "x-api-key": apiKey }, }); - if (!authRes.ok) { + if (!keyRes.ok) { return res.status(200).json({ valid: false, error: "Invalid API key — could not authenticate with Immich", @@ -34,57 +28,13 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse) }); } - // Get the API key details to check permissions - const keysRes = await fetch(`${ENV.IMMICH_URL}/api/api-keys`, { - headers: { "x-api-key": apiKey }, - }); - - if (!keysRes.ok) { - // Can authenticate but can't list keys — might be a full-access key - return res.status(200).json({ - valid: true, - error: null, - permissions: ["all (could not verify individual permissions)"], - missing: [], - }); - } - - const keys = await keysRes.json(); - - // Find the key being used — it's the one that matches our request - // Immich doesn't directly tell us which key is in use, so check all permissions across all keys - // The safest check: try to access endpoints that require each permission - const permissionChecks = await Promise.all([ - // asset.read — try searching assets - fetch(`${ENV.IMMICH_URL}/api/assets?take=1`, { - headers: { "x-api-key": apiKey }, - }).then((r) => ({ permission: "asset.read", granted: r.ok })), - - // asset.update — try a dry validation (we just check if the endpoint doesn't 403) - fetch(`${ENV.IMMICH_URL}/api/assets`, { - method: "PUT", - headers: { "x-api-key": apiKey, "Content-Type": "application/json" }, - body: JSON.stringify({ ids: [], isFavorite: true }), - }).then((r) => ({ permission: "asset.update", granted: r.status !== 403 })), - - // album.create — check via OPTIONS or a minimal request - fetch(`${ENV.IMMICH_URL}/api/albums`, { - headers: { "x-api-key": apiKey }, - }).then((r) => ({ permission: "album.create", granted: r.ok })), - - // album.update — same endpoint access implies read+write - fetch(`${ENV.IMMICH_URL}/api/albums`, { - headers: { "x-api-key": apiKey }, - }).then((r) => ({ permission: "album.update", granted: r.ok })), - - // tag.create - fetch(`${ENV.IMMICH_URL}/api/tags`, { - headers: { "x-api-key": apiKey }, - }).then((r) => ({ permission: "tag.create", granted: r.ok || r.status !== 403 })), - ]); - - const granted = permissionChecks.filter((p) => p.granted).map((p) => p.permission); - const missing = REQUIRED_PERMISSIONS.filter((p) => !granted.includes(p)); + const keyData = await keyRes.json(); + const granted: string[] = keyData.permissions ?? []; + // A key created with the "All" checkbox reports its permissions as ["all"], + // which grants every permission without listing them individually. + const missing = granted.includes("all") + ? [] + : REQUIRED_PERMISSIONS.filter((p) => !granted.includes(p)); return res.status(200).json({ valid: missing.length === 0, diff --git a/src/pages/api/share-link/[token]/assets.ts b/src/pages/api/share-link/[token]/assets.ts index a458a71..bfbc939 100644 --- a/src/pages/api/share-link/[token]/assets.ts +++ b/src/pages/api/share-link/[token]/assets.ts @@ -56,7 +56,6 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse) const dbAssets = await db.select({ id: assets.id, - deviceId: assets.deviceId, type: assets.type, originalPath: assets.originalPath, isFavorite: assets.isFavorite, @@ -92,7 +91,7 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse) return { ...asset, localDateTime: new Date(asset.localDateTime), - duration: asset.duration ? parseInt(asset.duration) : 0, + duration: asset.duration ?? 0, exifImageWidth: (isFlipped(asset.orientation) ? asset.exifImageHeight : asset.exifImageWidth) ?? 0, exifImageHeight: (isFlipped(asset.orientation) ? asset.exifImageWidth : asset.exifImageHeight) ?? 0, dateTimeOriginal: new Date(asset.dateTimeOriginal || new Date()).toISOString(), diff --git a/src/pages/api/tags/index.ts b/src/pages/api/tags/index.ts new file mode 100644 index 0000000..42e37c3 --- /dev/null +++ b/src/pages/api/tags/index.ts @@ -0,0 +1,30 @@ +import { db } from "@/config/db"; +import { getCurrentUser } from "@/handlers/serverUtils/user.utils"; +import { tags } from "@/schema"; +import { asc, eq } from "drizzle-orm"; +import type { NextApiRequest, NextApiResponse } from "next"; + +export default async function handler( + req: NextApiRequest, + res: NextApiResponse +) { + try { + const currentUser = await getCurrentUser(req); + if (!currentUser) return res.status(401).json({ message: "Unauthorized" }); + + const rows = await db + .select({ + id: tags.id, + value: tags.value, + color: tags.color, + parentId: tags.parentId, + }) + .from(tags) + .where(eq(tags.userId, currentUser.id)) + .orderBy(asc(tags.value)); + + return res.status(200).json({ tags: rows }); + } catch (error: any) { + res.status(500).json({ error: error?.message }); + } +} diff --git a/src/pages/api/validate-permissions.ts b/src/pages/api/validate-permissions.ts index 37959f9..7e65f89 100644 --- a/src/pages/api/validate-permissions.ts +++ b/src/pages/api/validate-permissions.ts @@ -19,10 +19,12 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse) // Test asset upload permission by calling a no-op endpoint try { - const response = await fetch(`${ENV.IMMICH_URL}/api/assets/exist`, { + const response = await fetch(`${ENV.IMMICH_URL}/api/assets/bulk-upload-check`, { method: "POST", headers, - body: JSON.stringify({ deviceAssetIds: ["permission-check"], deviceId: "immich-power-tools-check" }), + body: JSON.stringify({ + assets: [{ id: "permission-check", checksum: "0000000000000000000000000000000000000000" }], + }), }); result.canUpload = response.ok; } catch { diff --git a/src/pages/assets/import-shared.tsx b/src/pages/assets/import-shared.tsx index 14c4301..1292a6f 100644 --- a/src/pages/assets/import-shared.tsx +++ b/src/pages/assets/import-shared.tsx @@ -22,14 +22,7 @@ import PageLayout from "@/components/layouts/PageLayout"; import Header from "@/components/shared/Header"; import ApiKeyGate from "@/components/shared/ApiKeyGate"; -const IMPORT_PERMISSIONS = [ - { name: "asset.read", description: "Check for existing assets" }, - { name: "asset.upload", description: "Upload new assets" }, - { name: "album.read", description: "Read album data" }, - { name: "album.create", description: "Create new albums" }, - { name: "album.update", description: "Add assets to albums" }, - { name: "tag.create", description: "Tag imported assets" }, -]; +import { IMPORT_PERMISSIONS } from "@/config/permissions"; import { Button } from "@/components/ui/button"; import { Checkbox } from "@/components/ui/checkbox"; import { Input } from "@/components/ui/input"; @@ -73,6 +66,10 @@ interface IImportSharedAsset { duration?: string | null; isFavorite?: boolean; isArchived?: boolean; + // Ente-specific encryption artifacts (optional) + enteFileKey?: string; + enteFileDecryptionHeader?: string; + enteThumbnailDecryptionHeader?: string; } interface IImportSharedAlbum { @@ -94,7 +91,7 @@ interface IImportSharedAlbum { } interface IImportSharedResponse { - platform: "immich" | "nextcloud"; + platform: "immich" | "nextcloud" | "ente"; link: string; origin: string; key: string; @@ -108,6 +105,9 @@ interface IImportSharedResponse { showMetadata?: boolean; }; album: IImportSharedAlbum | null; + // Ente-specific (optional) + enteApiBase?: string; + enteAlbumKey?: string; } const formatDate = (value?: string | null) => { @@ -347,6 +347,11 @@ export default function ImportSharedPage() { platform: sharedData.platform, }); if (asset.thumbhash) params.set("thumbhash", asset.thumbhash); + if (sharedData.platform === "ente") { + if (asset.enteFileKey) params.set("enteFileKey", asset.enteFileKey); + if (asset.enteThumbnailDecryptionHeader) params.set("enteThumbnailHeader", asset.enteThumbnailDecryptionHeader); + if (sharedData.enteApiBase) params.set("apiBase", sharedData.enteApiBase); + } return `/api/import-shared/thumbnail?${params.toString()}`; }; @@ -375,6 +380,11 @@ export default function ImportSharedPage() { platform: sharedData.platform, }); if (asset.thumbhash) params.set("thumbhash", asset.thumbhash); + if (sharedData.platform === "ente") { + if (asset.enteFileKey) params.set("enteFileKey", asset.enteFileKey); + if (asset.enteThumbnailDecryptionHeader) params.set("enteThumbnailHeader", asset.enteThumbnailDecryptionHeader); + if (sharedData.enteApiBase) params.set("apiBase", sharedData.enteApiBase); + } return `/api/import-shared/thumbnail?${params.toString()}`; }; @@ -407,10 +417,15 @@ export default function ImportSharedPage() { setImportAllLoading(true); try { const isNextcloud = sharedData.platform === "nextcloud"; + const isEnte = sharedData.platform === "ente"; const urlConfig: Record = { key: sharedData.key }; if (isNextcloud && shareLinkPassword) { urlConfig.password = shareLinkPassword; } + if (isEnte) { + if (sharedData.enteApiBase) urlConfig.apiBase = sharedData.enteApiBase; + if (sharedData.enteAlbumKey) urlConfig.albumKey = sharedData.enteAlbumKey; + } const job = await createImportJob({ platform: sharedData.platform, @@ -427,6 +442,11 @@ export default function ImportSharedPage() { isFavorite: asset.isFavorite ?? false, isArchived: asset.isArchived ?? false, ...(isNextcloud ? { relativePath: asset.id } : {}), + ...(isEnte ? { + enteFileKey: asset.enteFileKey ?? null, + enteFileDecryptionHeader: asset.enteFileDecryptionHeader ?? null, + enteThumbnailDecryptionHeader: asset.enteThumbnailDecryptionHeader ?? null, + } : {}), })), }); setActiveJobId(job.jobId); @@ -501,7 +521,7 @@ export default function ImportSharedPage() {

Import a shared album

- Paste a public shared link from Immich or Nextcloud to import its assets into your Immich instance. + Paste a public shared link from Immich, Nextcloud, or Ente to import its assets into your Immich instance.

@@ -518,7 +538,7 @@ export default function ImportSharedPage() { setShareLinkPassword(""); } }} - placeholder="Immich or Nextcloud share URL" + placeholder="Immich, Nextcloud, or Ente share URL" type="url" required className="pl-9" @@ -717,7 +737,7 @@ export default function ImportSharedPage() { : "hover:opacity-90" }`} onClick={() => { - if (isVideoAsset) { + if (isVideoAsset && sharedData?.platform !== "ente") { setActiveImageAsset(null); setActiveVideoAsset(asset); setPreviewLoading(false); @@ -758,8 +778,8 @@ export default function ImportSharedPage() { />
- {/* Video play indicator */} - {isVideoAsset && ( + {/* Video play indicator (hidden for Ente — no video preview) */} + {isVideoAsset && sharedData?.platform !== "ente" && (
diff --git a/src/pages/find/index.tsx b/src/pages/find/index.tsx index 0518064..053db33 100644 --- a/src/pages/find/index.tsx +++ b/src/pages/find/index.tsx @@ -51,6 +51,7 @@ export default function FindPage() { const { toast } = useToast(); // Initialize toast const { aiEnabled } = useConfig(); const [query, setQuery] = useState(''); + const [searchedQuery, setSearchedQuery] = useState(''); const [loading, setLoading] = useState(false); const [filters, setFilters] = useState({}); const [error, setError] = useState(null); @@ -92,7 +93,9 @@ export default function FindPage() { }, [filters]); const handleSearch = (query: string) => { + if (!query.trim()) return; setQuery(query); + setSearchedQuery(query); setLoading(true); setError(null); // Clear previous errors findAssets(query) @@ -193,7 +196,7 @@ export default function FindPage() {
) } - else if (query.length === 0) { + else if (searchedQuery.length === 0) { return (
@@ -209,7 +212,10 @@ export default function FindPage() { variant="outline" size="sm" className="text-xs" - onClick={() => handleSearch(suggestion.query)} + onClick={() => { + setQuery(suggestion.query); + handleSearch(suggestion.query); + }} > {suggestion.label} @@ -279,6 +285,7 @@ export default function FindPage() { value={query} onChange={setQuery} onSearch={handleSearch} + loading={loading} />
{/* renderContent now includes the Provider */} diff --git a/src/pages/settings/index.tsx b/src/pages/settings/index.tsx index 164f1bd..a19eccf 100644 --- a/src/pages/settings/index.tsx +++ b/src/pages/settings/index.tsx @@ -12,6 +12,7 @@ import toast from "react-hot-toast"; import API from "@/lib/api"; import { useConfig } from "@/contexts/ConfigContext"; import Link from "next/link"; +import { WORKFLOW_PERMISSIONS } from "@/config/permissions"; function ConnectionStatus({ label, url, icon: Icon }: { label: string; url: string; icon: any }) { return ( @@ -50,6 +51,9 @@ export default function SettingsPage() { const [showImportApiKey, setShowImportApiKey] = useState(false); const [importApiKeySaved, setImportApiKeySaved] = useState(false); const [generatingImportKey, setGeneratingImportKey] = useState(false); + const [importValidationResult, setImportValidationResult] = useState<{ + valid: boolean; error: string | null; permissions: string[]; missing: string[]; + } | null>(null); const fetchWorkflowApiKey = async () => { try { @@ -71,14 +75,45 @@ export default function SettingsPage() { } }; + const IMPORT_REQUIRED_PERMISSIONS = ["asset.read", "asset.upload", "album.read", "album.create", "album.update", "tag.create", "tag.asset"]; + const saveImportApiKey = async () => { + if (!importApiKey.trim()) { + setImportApiKeyLoading(true); + try { + await API.put("/api/settings/kv/import_api_key", { value: "" }); + setImportApiKeySaved(false); + setImportValidationResult(null); + toast.success("Import API key cleared"); + } catch { + toast.error("Failed to clear import API key"); + } + setImportApiKeyLoading(false); + return; + } + setImportApiKeyLoading(true); + setImportValidationResult(null); + toast("Validating API key..."); + try { + const result = await API.post("/api/settings/validate-api-key", { + apiKey: importApiKey, + requiredPermissions: IMPORT_REQUIRED_PERMISSIONS, + }); + setImportValidationResult(result); + + if (!result.valid) { + toast.error(result.error || "API key validation failed"); + setImportApiKeyLoading(false); + return; + } + await API.put("/api/settings/kv/import_api_key", { value: importApiKey.trim() }); - setImportApiKeySaved(!!importApiKey.trim()); - toast.success(importApiKey.trim() ? "Import API key saved" : "Import API key cleared"); + setImportApiKeySaved(true); + toast.success("API key validated and saved"); } catch { - toast.error("Failed to save import API key"); + toast.error("Failed to validate API key"); } setImportApiKeyLoading(false); }; @@ -235,8 +270,8 @@ export default function SettingsPage() { )} {!validationResult && (
- {["asset.read", "asset.update", "album.create", "album.update", "tag.create"].map((p) => ( - {p} + {WORKFLOW_PERMISSIONS.map((p) => ( + {p.name} ))}
)} @@ -294,18 +329,46 @@ export default function SettingsPage() { {importApiKeyLoading ? "Saving..." : "Save"}
-
- {["asset.read", "asset.upload", "album.read", "album.create", "album.update", "tag.create"].map((p) => ( - {p} - ))} -
+ {importValidationResult && ( +
+
+ {importValidationResult.valid ? ( + <>All permissions verified + ) : ( + <>{importValidationResult.error} + )} +
+
+ {IMPORT_REQUIRED_PERMISSIONS.map((p) => { + const granted = importValidationResult.permissions.includes(p); + const missing = importValidationResult.missing.includes(p); + return ( + + {granted ? "✓" : "✗"} {p} + + ); + })} +
+
+ )} + {!importValidationResult && ( +
+ {IMPORT_REQUIRED_PERMISSIONS.map((p) => ( + {p} + ))} +
+ )}