merge main

This commit is contained in:
Ben McCann
2026-03-29 09:33:19 -07:00
2621 changed files with 246878 additions and 69315 deletions
+1 -1
View File
@@ -1 +1 @@
24.11.0
24.14.0
+27 -2
View File
@@ -1,4 +1,4 @@
FROM ghcr.io/immich-app/base-server-dev:202510281104@sha256:e2f94c2e92cbae5982b014e610ff29731c0fbcb4bf69022c7fe27594e40c9f83 AS builder
FROM ghcr.io/immich-app/base-server-dev:202603251709@sha256:2bf3053c732fcb87ec90c3c614632ac44847423468ccc57fd935bff771828d9d AS builder
ENV COREPACK_ENABLE_DOWNLOAD_PROMPT=0 \
CI=1 \
COREPACK_HOME=/tmp \
@@ -48,7 +48,30 @@ RUN --mount=type=cache,id=pnpm-cli,target=/buildcache/pnpm-store \
pnpm --filter @immich/sdk --filter @immich/cli build && \
pnpm --filter @immich/cli --prod --no-optional deploy /output/cli-pruned
FROM ghcr.io/immich-app/base-server-prod:202510281104@sha256:84f8f3eb4cfafc5e624235f7db703e1222fd60831bef1d488d8d8cad2be5023d
FROM builder AS plugins
ARG TARGETPLATFORM
COPY --from=ghcr.io/jdx/mise:2026.3.12@sha256:0210678cbf58413806531a27adb2c7daf1c37238e56e8f7ea381d73521571775 /usr/local/bin/mise /usr/local/bin/mise
WORKDIR /usr/src/app
COPY ./plugins/mise.toml ./plugins/
ENV MISE_TRUSTED_CONFIG_PATHS=/usr/src/app/plugins/mise.toml
ENV MISE_DATA_DIR=/buildcache/mise
RUN --mount=type=cache,id=mise-tools-${TARGETPLATFORM},target=/buildcache/mise \
mise install --cd plugins
COPY ./plugins ./plugins/
# Build plugins
RUN --mount=type=cache,id=pnpm-plugins,target=/buildcache/pnpm-store \
--mount=type=bind,source=package.json,target=package.json \
--mount=type=bind,source=.pnpmfile.cjs,target=.pnpmfile.cjs \
--mount=type=bind,source=pnpm-lock.yaml,target=pnpm-lock.yaml \
--mount=type=bind,source=pnpm-workspace.yaml,target=pnpm-workspace.yaml \
--mount=type=cache,id=mise-tools-${TARGETPLATFORM},target=/buildcache/mise \
cd plugins && mise run build
FROM ghcr.io/immich-app/base-server-prod:202603251709@sha256:17de30977ff87aa06758a56ad7f10d6b5c97bf9dab76e4ec4177a2a8d1b2b5f3
WORKDIR /usr/src/app
ENV NODE_ENV=production \
@@ -58,6 +81,8 @@ ENV NODE_ENV=production \
COPY --from=server /output/server-pruned ./server
COPY --from=web /usr/src/app/web/build /build/www
COPY --from=cli /output/cli-pruned ./cli
COPY --from=plugins /usr/src/app/plugins/dist /build/corePlugin/dist
COPY --from=plugins /usr/src/app/plugins/manifest.json /build/corePlugin/manifest.json
RUN ln -s ../../cli/bin/immich server/bin/immich
COPY LICENSE /licenses/LICENSE.txt
COPY LICENSE /LICENSE
+24 -26
View File
@@ -1,21 +1,21 @@
# dev build
FROM ghcr.io/immich-app/base-server-dev:202510281104@sha256:e2f94c2e92cbae5982b014e610ff29731c0fbcb4bf69022c7fe27594e40c9f83 AS dev
FROM ghcr.io/immich-app/base-server-dev:202603251709@sha256:2bf3053c732fcb87ec90c3c614632ac44847423468ccc57fd935bff771828d9d AS dev
ENV COREPACK_ENABLE_DOWNLOAD_PROMPT=0 \
CI=1 \
COREPACK_HOME=/tmp
COREPACK_HOME=/tmp \
PNPM_HOME=/buildcache/pnpm-store
RUN npm install --global corepack@latest && \
corepack enable pnpm && \
echo "devdir=/buildcache/node-gyp" >> /usr/local/etc/npmrc && \
echo "store-dir=/buildcache/pnpm-store" >> /usr/local/etc/npmrc && \
echo "devdir=/buildcache/node-gyp" >> /usr/local/etc/npmrc
echo "cache-dir=/buildcache/pnpm-cache" >> /usr/local/etc/npmrc && \
echo "# Retry configuration - default is 2" >> /usr/local/etc/npmrc && \
echo "fetch-retries=5" >> /usr/local/etc/npmrc && \
mkdir -p /buildcache/pnpm-store /buildcache/pnpm-cache /buildcache/node-gyp && \
chmod -R o+rw /buildcache
COPY ./package* ./pnpm* .pnpmfile.cjs /tmp/create-dep-cache/
COPY ./web/package* ./web/pnpm* /tmp/create-dep-cache/web/
COPY ./server/package* ./server/pnpm* /tmp/create-dep-cache/server/
COPY ./open-api/typescript-sdk/package* ./open-api/typescript-sdk/pnpm* /tmp/create-dep-cache/open-api/typescript-sdk/
WORKDIR /tmp/create-dep-cache
RUN pnpm fetch && rm -rf /tmp/create-dep-cache && chmod -R o+rw /buildcache
WORKDIR /usr/src/app
ENV PATH="${PATH}:/usr/src/app/server/bin:/usr/src/app/web/bin" \
@@ -27,16 +27,14 @@ ENTRYPOINT ["tini", "--", "/bin/bash", "-c"]
FROM dev AS dev-container-server
RUN apt-get update --allow-releaseinfo-change && \
apt-get install sudo inetutils-ping openjdk-21-jre-headless \
apt-get install inetutils-ping openjdk-21-jre-headless \
vim nano curl \
-y --no-install-recommends --fix-missing
RUN usermod -aG sudo node && \
echo "node ALL=(ALL) NOPASSWD: ALL" >> /etc/sudoers && \
mkdir -p /workspaces/immich
RUN mkdir -p /workspaces && \
ln -s /usr/src/app /workspaces/immich
RUN chown node:node -R /workspaces
COPY --chown=node:node --chmod=755 ../.devcontainer/server/*.sh /immich-devcontainer/
COPY --chmod=755 ../.devcontainer/server/*.sh /immich-devcontainer/
WORKDIR /workspaces/immich
@@ -44,18 +42,18 @@ FROM dev-container-server AS dev-container-mobile
USER root
# Enable multiarch for arm64 if necessary
RUN if [ "$(dpkg --print-architecture)" = "arm64" ]; then \
dpkg --add-architecture amd64 && \
apt-get update && \
apt-get install -y --no-install-recommends \
gnupg \
qemu-user-static \
libc6:amd64 \
libstdc++6:amd64 \
libgcc1:amd64; \
dpkg --add-architecture amd64 && \
apt-get update && \
apt-get install -y --no-install-recommends \
gnupg \
qemu-user-static \
libc6:amd64 \
libstdc++6:amd64 \
libgcc1:amd64; \
else \
apt-get update && \
apt-get install -y --no-install-recommends \
gnupg; \
apt-get update && \
apt-get install -y --no-install-recommends \
gnupg; \
fi
# Flutter SDK
+1 -1
View File
@@ -1,6 +1,6 @@
#!/usr/bin/env bash
if [ "$IMMICH_ENV" != "development" ]; then
if [[ "$IMMICH_ENV" == "production" ]]; then
echo "This command can only be run in development environments"
exit 1
fi
+28 -11
View File
@@ -1,13 +1,26 @@
#!/usr/bin/env bash
echo "Initializing Immich $IMMICH_SOURCE_REF"
# TODO: Update to mimalloc v3 when verified memory isn't released issue is fixed
# lib_path="/usr/lib/$(arch)-linux-gnu/libmimalloc.so.3"
# if [ -f "$lib_path" ]; then
# export LD_PRELOAD="$lib_path"
# else
# echo "skipping libmimalloc - path not found $lib_path"
# fi
# Quiet mode suppresses informational output (enabled for immich-admin)
QUIET=false
if [ "$1" = "immich-admin" ]; then
QUIET=true
fi
# Helper function that only logs when not in quiet mode
log_message() {
if [ "$QUIET" = "false" ]; then
echo "$@"
fi
}
log_message "Initializing Immich $IMMICH_SOURCE_REF"
lib_path="/usr/lib/$(arch)-linux-gnu/libmimalloc.so.3"
if [ -f "$lib_path" ]; then
export LD_PRELOAD="$lib_path"
else
echo "skipping libmimalloc - path not found $lib_path"
fi
export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:/usr/lib/jellyfin-ffmpeg/lib"
SERVER_HOME="$(readlink -f "$(dirname "$0")/..")"
@@ -30,16 +43,20 @@ read_file_and_export "DB_PASSWORD_FILE" "DB_PASSWORD"
read_file_and_export "REDIS_PASSWORD_FILE" "REDIS_PASSWORD"
if CPU_CORES="${CPU_CORES:=$(get-cpus.sh 2>/dev/null)}"; then
echo "Detected CPU Cores: $CPU_CORES"
log_message "Detected CPU Cores: $CPU_CORES"
if [ "$CPU_CORES" -gt 4 ]; then
export UV_THREADPOOL_SIZE=$CPU_CORES
fi
else
echo "skipping get-cpus.sh - not found in PATH or failed: using default UV_THREADPOOL_SIZE"
log_message "skipping get-cpus.sh - not found in PATH or failed: using default UV_THREADPOOL_SIZE"
fi
if [ -f "${SERVER_HOME}/dist/main.js" ]; then
exec node "${SERVER_HOME}/dist/main.js" "$@"
if [ "$QUIET" = "true" ]; then
exec node --no-warnings "${SERVER_HOME}/dist/main.js" "$@"
else
exec node "${SERVER_HOME}/dist/main.js" "$@"
fi
else
echo "Error: ${SERVER_HOME}/dist/main.js not found"
if [ "$IMMICH_ENV" = "development" ]; then
+21
View File
@@ -0,0 +1,21 @@
{
"contentSecurityPolicy": {
"directives": {
"default-src": ["'self'"],
"script-src": ["'self'", "'wasm-unsafe-eval", "'unsafe-inline'", "https://www.gstatic.com"],
"style-src": ["'self'", "'unsafe-inline'"],
"img-src": ["'self'", "'data:'", "'blob:'"],
"connect-src": [
"'self'",
"blob:",
"https://pay.futo.org",
"https://static.immich.cloud",
"https://tiles.immich.cloud"
],
"worker-src": ["'self'", "blob:"],
"frame-src": ["'none'"],
"object-src": ["'none'"],
"base-uri": ["'self'"]
}
}
}
+66
View File
@@ -0,0 +1,66 @@
[tasks.install]
run = "pnpm install --filter immich --frozen-lockfile"
[tasks.build]
env._.path = "./node_modules/.bin"
run = "nest build"
[tasks.test]
env._.path = "./node_modules/.bin"
run = "vitest --config test/vitest.config.mjs"
[tasks."test-medium"]
env._.path = "./node_modules/.bin"
run = "vitest --config test/vitest.config.medium.mjs"
[tasks.format]
env._.path = "./node_modules/.bin"
run = "prettier --check ."
[tasks."format-fix"]
env._.path = "./node_modules/.bin"
run = "prettier --write ."
[tasks.lint]
env._.path = "./node_modules/.bin"
run = "eslint \"src/**/*.ts\" \"test/**/*.ts\" --max-warnings 0"
[tasks."lint-fix"]
run = { task = "lint --fix" }
[tasks.check]
env._.path = "./node_modules/.bin"
run = "tsc --noEmit"
[tasks.sql]
run = "node ./dist/bin/sync-open-api.js"
[tasks."open-api"]
run = "node ./dist/bin/sync-open-api.js"
[tasks.migrations]
run = "node ./dist/bin/migrations.js"
description = "Run database migration commands (create, generate, run, debug, or query)"
[tasks."schema-drop"]
run = { task = "migrations query 'DROP schema public cascade; CREATE schema public;'" }
[tasks."schema-reset"]
run = [
{ task = ":schema-drop" },
{ task = "migrations run" },
]
[tasks."email-dev"]
env._.path = "./node_modules/.bin"
run = "email dev -p 3050 --dir src/emails"
[tasks.checklist]
run = [
{ task = ":install" },
{ task = ":format" },
{ task = ":lint" },
{ task = ":check" },
{ task = ":test-medium --run" },
{ task = ":test --run" },
]
+50 -37
View File
@@ -1,39 +1,46 @@
{
"name": "immich",
"version": "2.2.3",
"version": "2.6.3",
"description": "",
"author": "",
"private": true,
"license": "GNU Affero General Public License version 3",
"files": [
"bin",
"dist",
"helmet.json"
],
"scripts": {
"build": "nest build",
"format": "prettier --check .",
"format:fix": "prettier --write .",
"start": "npm run start:dev",
"format": "prettier --cache --check .",
"format:fix": "prettier --cache --write --list-different .",
"start": "pnpm run start:dev",
"nest": "nest",
"start:dev": "nest start --watch --",
"start:debug": "nest start --debug 0.0.0.0:9230 --watch --",
"lint": "eslint \"src/**/*.ts\" \"test/**/*.ts\" --max-warnings 0",
"lint:fix": "npm run lint -- --fix",
"lint:fix": "pnpm run lint --fix",
"check": "tsc --noEmit",
"check:code": "npm run format && npm run lint && npm run check",
"check:all": "npm run check:code && npm run test:cov",
"check:code": "pnpm run format && pnpm run lint && pnpm run check",
"check:all": "pnpm run check:code && pnpm run test:cov",
"test": "vitest --config test/vitest.config.mjs",
"test:cov": "vitest --config test/vitest.config.mjs --coverage",
"test:medium": "vitest --config test/vitest.config.medium.mjs",
"typeorm": "typeorm",
"lifecycle": "node ./dist/utils/lifecycle.js",
"migrations:debug": "node ./dist/bin/migrations.js debug",
"migrations:generate": "node ./dist/bin/migrations.js generate",
"migrations:create": "node ./dist/bin/migrations.js create",
"migrations:run": "node ./dist/bin/migrations.js run",
"schema:drop": "node ./dist/bin/migrations.js query 'DROP schema public cascade; CREATE schema public;'",
"schema:reset": "npm run schema:drop && npm run migrations:run",
"migrations:debug": "sql-tools -u ${DB_URL:-postgres://postgres:postgres@localhost:5432/immich} migrations generate --debug",
"migrations:generate": "sql-tools -u ${DB_URL:-postgres://postgres:postgres@localhost:5432/immich} migrations generate",
"migrations:create": "sql-tools -u ${DB_URL:-postgres://postgres:postgres@localhost:5432/immich} migrations create",
"migrations:run": "sql-tools -u ${DB_URL:-postgres://postgres:postgres@localhost:5432/immich} migrations run",
"migrations:revert": "sql-tools -u ${DB_URL:-postgres://postgres:postgres@localhost:5432/immich} migrations revert",
"schema:drop": "sql-tools -u ${DB_URL:-postgres://postgres:postgres@localhost:5432/immich} query 'DROP schema public cascade; CREATE schema public;'",
"schema:reset": "pnpm run schema:drop && pnpm run migrations:run",
"sync:open-api": "node ./dist/bin/sync-open-api.js",
"sync:sql": "node ./dist/bin/sync-sql.js",
"email:dev": "email dev -p 3050 --dir src/emails"
},
"dependencies": {
"@extism/extism": "2.0.0-rc13",
"@immich/sql-tools": "^0.3.2",
"@nestjs/bullmq": "^11.0.1",
"@nestjs/common": "^11.0.4",
"@nestjs/core": "^11.0.4",
@@ -44,18 +51,19 @@
"@nestjs/websockets": "^11.0.4",
"@opentelemetry/api": "^1.9.0",
"@opentelemetry/context-async-hooks": "^2.0.0",
"@opentelemetry/exporter-prometheus": "^0.207.0",
"@opentelemetry/instrumentation-http": "^0.207.0",
"@opentelemetry/instrumentation-ioredis": "^0.55.0",
"@opentelemetry/instrumentation-nestjs-core": "^0.54.0",
"@opentelemetry/instrumentation-pg": "^0.60.0",
"@opentelemetry/exporter-prometheus": "^0.213.0",
"@opentelemetry/instrumentation-http": "^0.213.0",
"@opentelemetry/instrumentation-ioredis": "^0.61.0",
"@opentelemetry/instrumentation-nestjs-core": "^0.59.0",
"@opentelemetry/instrumentation-pg": "^0.65.0",
"@opentelemetry/resources": "^2.0.1",
"@opentelemetry/sdk-metrics": "^2.0.1",
"@opentelemetry/sdk-node": "^0.207.0",
"@opentelemetry/sdk-node": "^0.213.0",
"@opentelemetry/semantic-conventions": "^1.34.0",
"@react-email/components": "^0.5.0",
"@react-email/render": "^1.1.2",
"@socket.io/redis-adapter": "^8.3.0",
"ajv": "^8.17.1",
"archiver": "^7.0.0",
"async-lock": "^1.4.0",
"bcrypt": "^6.0.0",
@@ -63,21 +71,24 @@
"bullmq": "^5.51.0",
"chokidar": "^4.0.3",
"class-transformer": "^0.5.1",
"class-validator": "^0.14.0",
"class-validator": "^0.15.0",
"compression": "^1.8.0",
"cookie": "^1.0.2",
"cookie-parser": "^1.4.7",
"cron": "4.3.3",
"exiftool-vendored": "^31.1.0",
"cron": "4.4.0",
"exiftool-vendored": "^35.0.0",
"express": "^5.1.0",
"fast-glob": "^3.3.2",
"fluent-ffmpeg": "^2.1.2",
"geo-tz": "^8.0.0",
"handlebars": "^4.7.8",
"helmet": "^8.1.0",
"i18n-iso-countries": "^7.6.0",
"ioredis": "^5.8.2",
"jose": "^5.10.0",
"js-yaml": "^4.1.0",
"kysely": "0.28.2",
"jsonwebtoken": "^9.0.2",
"kysely": "0.28.14",
"kysely-postgres-js": "^3.0.0",
"lodash": "^4.17.21",
"luxon": "^3.4.2",
@@ -92,7 +103,7 @@
"pg": "^8.11.3",
"pg-connection-string": "^2.9.1",
"picomatch": "^4.0.2",
"postgres": "3.4.7",
"postgres": "3.4.8",
"react": "^19.0.0",
"react-dom": "^19.0.0",
"react-email": "^4.0.0",
@@ -101,23 +112,24 @@
"sanitize-filename": "^1.6.3",
"sanitize-html": "^2.14.0",
"semver": "^7.6.2",
"sharp": "^0.34.4",
"sharp": "^0.34.5",
"sirv": "^3.0.0",
"socket.io": "^4.8.1",
"structured-headers": "^2.0.2",
"tailwindcss-preset-email": "^1.4.0",
"thumbhash": "^0.1.1",
"transformation-matrix": "^3.1.0",
"ua-parser-js": "^2.0.0",
"uuid": "^11.1.0",
"validator": "^13.12.0"
},
"devDependencies": {
"@eslint/js": "^9.8.0",
"@eslint/js": "^10.0.0",
"@nestjs/cli": "^11.0.2",
"@nestjs/schematics": "^11.0.0",
"@nestjs/testing": "^11.0.4",
"@swc/core": "^1.4.14",
"@types/archiver": "^6.0.0",
"@types/archiver": "^7.0.0",
"@types/async-lock": "^1.4.2",
"@types/bcrypt": "^6.0.0",
"@types/body-parser": "^1.19.6",
@@ -126,11 +138,12 @@
"@types/express": "^5.0.0",
"@types/fluent-ffmpeg": "^2.1.21",
"@types/js-yaml": "^4.0.9",
"@types/jsonwebtoken": "^9.0.10",
"@types/lodash": "^4.14.197",
"@types/luxon": "^3.6.2",
"@types/mock-fs": "^4.13.1",
"@types/multer": "^2.0.0",
"@types/node": "^22.18.13",
"@types/node": "^24.12.0",
"@types/nodemailer": "^7.0.0",
"@types/picomatch": "^4.0.0",
"@types/pngjs": "^6.0.5",
@@ -141,15 +154,15 @@
"@types/ua-parser-js": "^0.7.36",
"@types/validator": "^13.15.2",
"@vitest/coverage-v8": "^3.0.0",
"eslint": "^9.14.0",
"eslint": "^10.0.0",
"eslint-config-prettier": "^10.1.8",
"eslint-plugin-prettier": "^5.1.3",
"eslint-plugin-unicorn": "^60.0.0",
"globals": "^16.0.0",
"eslint-plugin-unicorn": "^63.0.0",
"globals": "^17.0.0",
"mock-fs": "^5.2.0",
"node-gyp": "^11.2.0",
"node-gyp": "^12.0.0",
"pngjs": "^7.0.0",
"prettier": "^3.0.2",
"prettier": "^3.7.4",
"prettier-plugin-organize-imports": "^4.0.0",
"sql-formatter": "^15.0.0",
"supertest": "^7.1.0",
@@ -158,13 +171,13 @@
"typescript": "^5.9.2",
"typescript-eslint": "^8.28.0",
"unplugin-swc": "^1.4.5",
"vite-tsconfig-paths": "^5.0.0",
"vite-tsconfig-paths": "^6.0.0",
"vitest": "^3.0.0"
},
"volta": {
"node": "24.11.0"
"node": "24.14.0"
},
"overrides": {
"sharp": "^0.34.4"
"sharp": "^0.34.5"
}
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+94
View File
@@ -0,0 +1,94 @@
import { NestExpressApplication } from '@nestjs/platform-express';
import { json } from 'body-parser';
import compression from 'compression';
import cookieParser from 'cookie-parser';
import helmetMiddleware from 'helmet';
import { existsSync } from 'node:fs';
import sirv from 'sirv';
import { IMMICH_SERVER_START, excludePaths, serverVersion } from 'src/constants';
import { MaintenanceWorkerService } from 'src/maintenance/maintenance-worker.service';
import { WebSocketAdapter } from 'src/middleware/websocket.adapter';
import { ConfigRepository } from 'src/repositories/config.repository';
import { LoggingRepository } from 'src/repositories/logging.repository';
import { bootstrapTelemetry } from 'src/repositories/telemetry.repository';
import { ApiService } from 'src/services/api.service';
import { useSwagger } from 'src/utils/misc';
export function configureTelemetry() {
const { telemetry } = new ConfigRepository().getEnv();
if (telemetry.metrics.size > 0) {
bootstrapTelemetry(telemetry.apiPort);
}
}
export async function configureExpress(
app: NestExpressApplication,
{
permitSwaggerWrite = true,
ssr,
}: {
/**
* Whether to allow swagger module to write to the specs.json
* This is not desirable when the API is not available
* @default true
*/
permitSwaggerWrite?: boolean;
/**
* Service to use for server-side rendering
*/
ssr: typeof ApiService | typeof MaintenanceWorkerService;
},
) {
const configRepository = app.get(ConfigRepository);
const { environment, host, port, helmet, resourcePaths, network } = configRepository.getEnv();
const logger = await app.resolve(LoggingRepository);
logger.setContext('Bootstrap');
app.useLogger(logger);
app.set('trust proxy', ['loopback', ...network.trustedProxies]);
app.set('etag', 'strong');
if (helmet.config) {
app.use(helmetMiddleware(helmet.config));
logger.log('Initialized helmet middleware');
}
app.use(cookieParser());
app.use(json({ limit: '10mb' }));
if (configRepository.isDev()) {
app.enableCors();
}
app.setGlobalPrefix('api', { exclude: excludePaths });
app.useWebSocketAdapter(new WebSocketAdapter(app));
useSwagger(app, { write: configRepository.isDev() && permitSwaggerWrite });
if (existsSync(resourcePaths.web.root)) {
// copied from https://github.com/sveltejs/kit/blob/679b5989fe62e3964b9a73b712d7b41831aa1f07/packages/adapter-node/src/handler.js#L46
// provides serving of precompressed assets and caching of immutable assets
app.use(
sirv(resourcePaths.web.root, {
etag: true,
gzip: true,
brotli: true,
extensions: [],
setHeaders: (res, pathname) => {
if (pathname.startsWith(`/_app/immutable`) && res.statusCode === 200) {
res.setHeader('cache-control', 'public,max-age=31536000,immutable');
}
},
}),
);
}
app.use(app.get(ssr).ssr(excludePaths));
app.use(compression());
const server = await (host ? app.listen(port, host) : app.listen(port));
server.requestTimeout = 24 * 60 * 60 * 1000;
logger.log(`${IMMICH_SERVER_START} on ${await app.getUrl()} [v${serverVersion}] [${environment}] `);
}
+65 -18
View File
@@ -9,54 +9,66 @@ import { commandsAndQuestions } from 'src/commands';
import { IWorker } from 'src/constants';
import { controllers } from 'src/controllers';
import { ImmichWorker } from 'src/enum';
import { MaintenanceAuthGuard } from 'src/maintenance/maintenance-auth.guard';
import { MaintenanceHealthRepository } from 'src/maintenance/maintenance-health.repository';
import { MaintenanceWebsocketRepository } from 'src/maintenance/maintenance-websocket.repository';
import { MaintenanceWorkerController } from 'src/maintenance/maintenance-worker.controller';
import { MaintenanceWorkerService } from 'src/maintenance/maintenance-worker.service';
import { AuthGuard } from 'src/middleware/auth.guard';
import { ErrorInterceptor } from 'src/middleware/error.interceptor';
import { FileUploadInterceptor } from 'src/middleware/file-upload.interceptor';
import { GlobalExceptionFilter } from 'src/middleware/global-exception.filter';
import { LoggingInterceptor } from 'src/middleware/logging.interceptor';
import { repositories } from 'src/repositories';
import { AppRepository } from 'src/repositories/app.repository';
import { ConfigRepository } from 'src/repositories/config.repository';
import { DatabaseRepository } from 'src/repositories/database.repository';
import { EventRepository } from 'src/repositories/event.repository';
import { LoggingRepository } from 'src/repositories/logging.repository';
import { ProcessRepository } from 'src/repositories/process.repository';
import { StorageRepository } from 'src/repositories/storage.repository';
import { SystemMetadataRepository } from 'src/repositories/system-metadata.repository';
import { teardownTelemetry, TelemetryRepository } from 'src/repositories/telemetry.repository';
import { UserRepository } from 'src/repositories/user.repository';
import { WebsocketRepository } from 'src/repositories/websocket.repository';
import { services } from 'src/services';
import { AuthService } from 'src/services/auth.service';
import { CliService } from 'src/services/cli.service';
import { JobService } from 'src/services/job.service';
import { DatabaseBackupService } from 'src/services/database-backup.service';
import { QueueService } from 'src/services/queue.service';
import { getKyselyConfig } from 'src/utils/database';
const common = [...repositories, ...services, GlobalExceptionFilter];
export const middleware = [
FileUploadInterceptor,
const commonMiddleware = [
{ provide: APP_FILTER, useClass: GlobalExceptionFilter },
{ provide: APP_PIPE, useValue: new ValidationPipe({ transform: true, whitelist: true }) },
{ provide: APP_INTERCEPTOR, useClass: LoggingInterceptor },
{ provide: APP_INTERCEPTOR, useClass: ErrorInterceptor },
{ provide: APP_GUARD, useClass: AuthGuard },
];
const apiMiddleware = [FileUploadInterceptor, ...commonMiddleware, { provide: APP_GUARD, useClass: AuthGuard }];
const configRepository = new ConfigRepository();
const { bull, cls, database, otel } = configRepository.getEnv();
const imports = [
BullModule.forRoot(bull.config),
BullModule.registerQueue(...bull.queues),
const commonImports = [
ClsModule.forRoot(cls.config),
OpenTelemetryModule.forRoot(otel),
KyselyModule.forRoot(getKyselyConfig(database.config)),
OpenTelemetryModule.forRoot(otel),
];
class BaseModule implements OnModuleInit, OnModuleDestroy {
const bullImports = [BullModule.forRoot(bull.config), BullModule.registerQueue(...bull.queues)];
export class BaseModule implements OnModuleInit, OnModuleDestroy {
constructor(
@Inject(IWorker) private worker: ImmichWorker,
logger: LoggingRepository,
private eventRepository: EventRepository,
private websocketRepository: WebsocketRepository,
private jobService: JobService,
private telemetryRepository: TelemetryRepository,
private authService: AuthService,
private eventRepository: EventRepository,
private queueService: QueueService,
private telemetryRepository: TelemetryRepository,
private websocketRepository: WebsocketRepository,
) {
logger.setAppName(this.worker);
}
@@ -64,7 +76,7 @@ class BaseModule implements OnModuleInit, OnModuleDestroy {
async onModuleInit() {
this.telemetryRepository.setup({ repositories });
this.jobService.setServices(services);
this.queueService.setServices(services);
this.websocketRepository.setAuthFn(async (client) =>
this.authService.authenticate({
@@ -85,20 +97,55 @@ class BaseModule implements OnModuleInit, OnModuleDestroy {
}
@Module({
imports: [...imports, ScheduleModule.forRoot()],
imports: [...bullImports, ...commonImports, ScheduleModule.forRoot()],
controllers: [...controllers],
providers: [...common, ...middleware, { provide: IWorker, useValue: ImmichWorker.Api }],
providers: [...common, ...apiMiddleware, { provide: IWorker, useValue: ImmichWorker.Api }],
})
export class ApiModule extends BaseModule {}
@Module({
imports: [...imports],
imports: [...commonImports],
controllers: [MaintenanceWorkerController],
providers: [
ConfigRepository,
LoggingRepository,
StorageRepository,
ProcessRepository,
DatabaseRepository,
UserRepository,
SystemMetadataRepository,
AppRepository,
MaintenanceHealthRepository,
MaintenanceWebsocketRepository,
DatabaseBackupService,
MaintenanceWorkerService,
...commonMiddleware,
{ provide: APP_GUARD, useClass: MaintenanceAuthGuard },
{ provide: IWorker, useValue: ImmichWorker.Maintenance },
],
})
export class MaintenanceModule {
constructor(
@Inject(IWorker) private worker: ImmichWorker,
logger: LoggingRepository,
private maintenanceWorkerService: MaintenanceWorkerService,
) {
logger.setAppName(this.worker);
}
async onModuleInit() {
await this.maintenanceWorkerService.init();
}
}
@Module({
imports: [...bullImports, ...commonImports],
providers: [...common, { provide: IWorker, useValue: ImmichWorker.Microservices }, SchedulerRegistry],
})
export class MicroservicesModule extends BaseModule {}
@Module({
imports: [...imports],
imports: [...bullImports, ...commonImports],
providers: [...common, ...commandsAndQuestions, SchedulerRegistry],
})
export class ImmichAdminModule implements OnModuleDestroy {
-159
View File
@@ -1,159 +0,0 @@
#!/usr/bin/env node
process.env.DB_URL = process.env.DB_URL || 'postgres://postgres:postgres@localhost:5432/immich';
import { Kysely, sql } from 'kysely';
import { mkdirSync, writeFileSync } from 'node:fs';
import { basename, dirname, extname, join } from 'node:path';
import postgres from 'postgres';
import { ConfigRepository } from 'src/repositories/config.repository';
import { DatabaseRepository } from 'src/repositories/database.repository';
import { LoggingRepository } from 'src/repositories/logging.repository';
import 'src/schema';
import { schemaDiff, schemaFromCode, schemaFromDatabase } from 'src/sql-tools';
import { asPostgresConnectionConfig, getKyselyConfig } from 'src/utils/database';
const main = async () => {
const command = process.argv[2];
const path = process.argv[3] || 'src/Migration';
switch (command) {
case 'debug': {
await debug();
return;
}
case 'run': {
await runMigrations();
return;
}
case 'query': {
const query = process.argv[3];
await runQuery(query);
return;
}
case 'create': {
create(path, [], []);
return;
}
case 'generate': {
await generate(path);
return;
}
default: {
console.log(`Usage:
node dist/bin/migrations.js create <name>
node dist/bin/migrations.js generate <name>
node dist/bin/migrations.js run
`);
}
}
};
const getDatabaseClient = () => {
const configRepository = new ConfigRepository();
const { database } = configRepository.getEnv();
return new Kysely<any>(getKyselyConfig(database.config));
};
const runQuery = async (query: string) => {
const db = getDatabaseClient();
await sql.raw(query).execute(db);
await db.destroy();
};
const runMigrations = async () => {
const configRepository = new ConfigRepository();
const logger = LoggingRepository.create();
const db = getDatabaseClient();
const databaseRepository = new DatabaseRepository(db, logger, configRepository);
await databaseRepository.runMigrations();
await db.destroy();
};
const debug = async () => {
const { up } = await compare();
const upSql = '-- UP\n' + up.asSql({ comments: true }).join('\n');
// const downSql = '-- DOWN\n' + down.asSql({ comments: true }).join('\n');
writeFileSync('./migrations.sql', upSql + '\n\n');
console.log('Wrote migrations.sql');
};
const generate = async (path: string) => {
const { up, down } = await compare();
if (up.items.length === 0) {
console.log('No changes detected');
return;
}
create(path, up.asSql(), down.asSql());
};
const create = (path: string, up: string[], down: string[]) => {
const timestamp = Date.now();
const name = basename(path, extname(path));
const filename = `${timestamp}-${name}.ts`;
const folder = dirname(path);
const fullPath = join(folder, filename);
mkdirSync(folder, { recursive: true });
writeFileSync(fullPath, asMigration({ up, down }));
console.log(`Wrote ${fullPath}`);
};
const compare = async () => {
const configRepository = new ConfigRepository();
const { database } = configRepository.getEnv();
const db = postgres(asPostgresConnectionConfig(database.config));
const source = schemaFromCode({ overrides: true, namingStrategy: 'default' });
const target = await schemaFromDatabase(db, {});
console.log(source.warnings.join('\n'));
const up = schemaDiff(source, target, {
tables: { ignoreExtra: true },
functions: { ignoreExtra: false },
parameters: { ignoreExtra: true },
});
const down = schemaDiff(target, source, {
tables: { ignoreExtra: false, ignoreMissing: true },
functions: { ignoreExtra: false },
extensions: { ignoreMissing: true },
parameters: { ignoreMissing: true },
});
return { up, down };
};
type MigrationProps = {
up: string[];
down: string[];
};
const asMigration = ({ up, down }: MigrationProps) => {
const upSql = up.map((sql) => ` await sql\`${sql}\`.execute(db);`).join('\n');
const downSql = down.map((sql) => ` await sql\`${sql}\`.execute(db);`).join('\n');
return `import { Kysely, sql } from 'kysely';
export async function up(db: Kysely<any>): Promise<void> {
${upSql}
}
export async function down(db: Kysely<any>): Promise<void> {
${downSql}
}
`;
};
main()
.then(() => {
process.exit(0);
})
.catch((error) => {
console.error(error);
console.log('Something went wrong');
process.exit(1);
});
+5
View File
@@ -1,5 +1,6 @@
import { GrantAdminCommand, PromptEmailQuestion, RevokeAdminCommand } from 'src/commands/grant-admin';
import { ListUsersCommand } from 'src/commands/list-users.command';
import { DisableMaintenanceModeCommand, EnableMaintenanceModeCommand } from 'src/commands/maintenance-mode';
import {
ChangeMediaLocationCommand,
PromptConfirmMoveQuestions,
@@ -8,6 +9,7 @@ import {
import { DisableOAuthLogin, EnableOAuthLogin } from 'src/commands/oauth-login';
import { DisablePasswordLoginCommand, EnablePasswordLoginCommand } from 'src/commands/password-login';
import { PromptPasswordQuestions, ResetAdminPasswordCommand } from 'src/commands/reset-admin-password.command';
import { SchemaCheck } from 'src/commands/schema-check';
import { VersionCommand } from 'src/commands/version.command';
export const commandsAndQuestions = [
@@ -16,6 +18,8 @@ export const commandsAndQuestions = [
PromptEmailQuestion,
EnablePasswordLoginCommand,
DisablePasswordLoginCommand,
EnableMaintenanceModeCommand,
DisableMaintenanceModeCommand,
EnableOAuthLogin,
DisableOAuthLogin,
ListUsersCommand,
@@ -25,4 +29,5 @@ export const commandsAndQuestions = [
ChangeMediaLocationCommand,
PromptMediaLocationQuestions,
PromptConfirmMoveQuestions,
SchemaCheck,
];
+37
View File
@@ -0,0 +1,37 @@
import { Command, CommandRunner } from 'nest-commander';
import { CliService } from 'src/services/cli.service';
@Command({
name: 'enable-maintenance-mode',
description: 'Enable maintenance mode or regenerate the maintenance token',
})
export class EnableMaintenanceModeCommand extends CommandRunner {
constructor(private service: CliService) {
super();
}
async run(): Promise<void> {
const { authUrl, alreadyEnabled } = await this.service.enableMaintenanceMode();
console.info(alreadyEnabled ? 'The server is already in maintenance mode!' : 'Maintenance mode has been enabled.');
console.info(`\nLog in using the following URL:\n${authUrl}`);
}
}
@Command({
name: 'disable-maintenance-mode',
description: 'Disable maintenance mode',
})
export class DisableMaintenanceModeCommand extends CommandRunner {
constructor(private service: CliService) {
super();
}
async run(): Promise<void> {
const { alreadyDisabled } = await this.service.disableMaintenanceMode();
console.log(
alreadyDisabled ? 'The server is already out of maintenance mode!' : 'Maintenance mode has been disabled.',
);
}
}
+60
View File
@@ -0,0 +1,60 @@
import { asHuman } from '@immich/sql-tools';
import { Command, CommandRunner } from 'nest-commander';
import { ErrorMessages } from 'src/constants';
import { CliService } from 'src/services/cli.service';
@Command({
name: 'schema-check',
description: 'Verify database migrations and check for schema drift',
})
export class SchemaCheck extends CommandRunner {
constructor(private service: CliService) {
super();
}
async run(): Promise<void> {
try {
const { migrations, drift } = await this.service.schemaReport();
if (migrations.every((item) => item.status === 'applied')) {
console.log('Migrations are up to date');
} else {
console.log('Migration issues detected:');
for (const migration of migrations) {
switch (migration.status) {
case 'deleted': {
console.log(` - ${migration.name} was applied, but the file no longer exists on disk`);
break;
}
case 'missing': {
console.log(` - ${migration.name} exists, but has not been applied to the database`);
break;
}
}
}
}
if (drift.items.length === 0) {
console.log('\nNo schema drift detected');
} else {
console.log(`\n${ErrorMessages.SchemaDrift}`);
for (const item of drift.items) {
console.log(` - ${item.type}: ` + asHuman(item));
}
console.log(`
The below SQL is automatically generated and may be helpful for resolving drift. ** Use at your own risk! **
\`\`\`sql
${drift.asSql().join('\n')}
\`\`\`
`);
}
} catch (error) {
console.error(error);
console.error('Unable to debug migrations');
}
}
}
+8 -3
View File
@@ -15,7 +15,7 @@ import {
} from 'src/enum';
import { ConcurrentQueueName, FullsizeImageOptions, ImageOptions } from 'src/types';
export interface SystemConfig {
export type SystemConfig = {
backup: {
database: {
enabled: boolean;
@@ -191,7 +191,7 @@ export interface SystemConfig {
user: {
deleteDelay: number;
};
}
};
export type MachineLearningConfig = SystemConfig['machineLearning'];
@@ -213,7 +213,7 @@ export const defaults = Object.freeze<SystemConfig>({
targetVideoCodec: VideoCodec.H264,
acceptedVideoCodecs: [VideoCodec.H264],
targetAudioCodec: AudioCodec.Aac,
acceptedAudioCodecs: [AudioCodec.Aac, AudioCodec.Mp3, AudioCodec.LibOpus],
acceptedAudioCodecs: [AudioCodec.Aac, AudioCodec.Mp3, AudioCodec.Opus],
acceptedContainers: [VideoContainer.Mov, VideoContainer.Ogg, VideoContainer.Webm],
targetResolution: '720',
maxBitrate: '0',
@@ -242,6 +242,8 @@ export const defaults = Object.freeze<SystemConfig>({
[QueueName.VideoConversion]: { concurrency: 1 },
[QueueName.Notification]: { concurrency: 5 },
[QueueName.Ocr]: { concurrency: 1 },
[QueueName.Workflow]: { concurrency: 5 },
[QueueName.Editor]: { concurrency: 2 },
},
logging: {
enabled: true,
@@ -324,11 +326,13 @@ export const defaults = Object.freeze<SystemConfig>({
format: ImageFormat.Webp,
size: 250,
quality: 80,
progressive: false,
},
preview: {
format: ImageFormat.Jpeg,
size: 1440,
quality: 80,
progressive: false,
},
colorspace: Colorspace.P3,
extractEmbedded: false,
@@ -336,6 +340,7 @@ export const defaults = Object.freeze<SystemConfig>({
enabled: false,
format: ImageFormat.Jpeg,
quality: 80,
progressive: false,
},
},
newVersionCheck: {
+80 -7
View File
@@ -2,18 +2,22 @@ import { Duration } from 'luxon';
import { readFileSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { SemVer } from 'semver';
import { DatabaseExtension, ExifOrientation, VectorIndex } from 'src/enum';
import { ApiTag, AudioCodec, DatabaseExtension, ExifOrientation, VectorIndex } from 'src/enum';
export const IMMICH_SERVER_START = 'Immich Server is listening';
export const ErrorMessages = {
InconsistentMediaLocation:
'Detected an inconsistent media location. For more information, see https://docs.immich.app/errors#inconsistent-media-location',
SchemaDrift: `Detected schema drift. For more information, see https://docs.immich.app/errors#schema-drift`,
TypeOrmUpgrade: 'Invalid upgrade path. For more information, see https://docs.immich.app/errors/#typeorm-upgrade',
};
export const POSTGRES_VERSION_RANGE = '>=14.0.0';
export const VECTORCHORD_VERSION_RANGE = '>=0.3 <0.6';
export const VECTORCHORD_VERSION_RANGE = '>=0.3 <2';
export const VECTORS_VERSION_RANGE = '>=0.2 <0.4';
export const VECTOR_VERSION_RANGE = '>=0.5 <1';
export const NEXT_RELEASE = 'NEXT_RELEASE';
export const LIFECYCLE_EXTENSION = 'x-immich-lifecycle';
export const DEPRECATED_IN_PREFIX = 'This property was deprecated in ';
export const ADDED_IN_PREFIX = 'This property was added in ';
export const JOBS_ASSET_PAGINATION_SIZE = 1000;
export const JOBS_LIBRARY_PAGINATION_SIZE = 10_000;
@@ -138,3 +142,72 @@ export const ORIENTATION_TO_SHARP_ROTATION: Record<ExifOrientation, SharpRotatio
[ExifOrientation.MirrorHorizontalRotate90CW]: { angle: 90, flip: true },
[ExifOrientation.Rotate270CW]: { angle: 270 },
} as const;
export const endpointTags: Record<ApiTag, string> = {
[ApiTag.Activities]: 'An activity is a like or a comment made by a user on an asset or album.',
[ApiTag.Albums]: 'An album is a collection of assets that can be shared with other users or via shared links.',
[ApiTag.ApiKeys]: 'An api key can be used to programmatically access the Immich API.',
[ApiTag.Assets]: 'An asset is an image or video that has been uploaded to Immich.',
[ApiTag.Authentication]: 'Endpoints related to user authentication, including OAuth.',
[ApiTag.AuthenticationAdmin]: 'Administrative endpoints related to authentication.',
[ApiTag.DatabaseBackups]: 'Manage backups of the Immich database.',
[ApiTag.Deprecated]: 'Deprecated endpoints that are planned for removal in the next major release.',
[ApiTag.Download]: 'Endpoints for downloading assets or collections of assets.',
[ApiTag.Duplicates]: 'Endpoints for managing and identifying duplicate assets.',
[ApiTag.Faces]:
'A face is a detected human face within an asset, which can be associated with a person. Faces are normally detected via machine learning, but can also be created via manually.',
[ApiTag.Jobs]:
'Queues and background jobs are used for processing tasks asynchronously. Queues can be paused and resumed as needed.',
[ApiTag.Libraries]:
'An external library is made up of input file paths or expressions that are scanned for asset files. Discovered files are automatically imported. Assets much be unique within a library, but can be duplicated across libraries. Each user has a default upload library, and can have one or more external libraries.',
[ApiTag.Maintenance]: 'Maintenance mode allows you to put Immich in a read-only state to perform various operations.',
[ApiTag.Map]:
'Map endpoints include supplemental functionality related to geolocation, such as reverse geocoding and retrieving map markers for assets with geolocation data.',
[ApiTag.Memories]:
'A memory is a specialized collection of assets with dedicated viewing implementations in the web and mobile clients. A memory includes fields related to visibility and are automatically generated per user via a background job.',
[ApiTag.Notifications]:
'A notification is a specialized message sent to users to inform them of important events. Currently, these notifications are only shown in the Immich web application.',
[ApiTag.NotificationsAdmin]: 'Notification administrative endpoints.',
[ApiTag.Partners]: 'A partner is a link with another user that allows sharing of assets between two users.',
[ApiTag.People]:
'A person is a collection of faces, which can be favorited and named. A person can also be merged into another person. People are automatically created via the face recognition job.',
[ApiTag.Plugins]:
'A plugin is an installed module that makes filters and actions available for the workflow feature.',
[ApiTag.Queues]:
'Queues and background jobs are used for processing tasks asynchronously. Queues can be paused and resumed as needed.',
[ApiTag.Search]:
'Endpoints related to searching assets via text, smart search, optical character recognition (OCR), and other filters like person, album, and other metadata. Search endpoints usually support pagination and sorting.',
[ApiTag.Server]:
'Information about the current server deployment, including version and build information, available features, supported media types, and more.',
[ApiTag.Sessions]:
'A session represents an authenticated login session for a user. Sessions also appear in the web application as "Authorized devices".',
[ApiTag.SharedLinks]:
'A shared link is a public url that provides access to a specific album, asset, or collection of assets. A shared link can be protected with a password, include a specific slug, allow or disallow downloads, and optionally include an expiration date.',
[ApiTag.Stacks]:
'A stack is a group of related assets. One asset is the "primary" asset, and the rest are "child" assets. On the main timeline, stack parents are included by default, while child assets are hidden.',
[ApiTag.Sync]: 'A collection of endpoints for the new mobile synchronization implementation.',
[ApiTag.SystemConfig]: 'Endpoints to view, modify, and validate the system configuration settings.',
[ApiTag.SystemMetadata]:
'Endpoints to view, modify, and validate the system metadata, which includes information about things like admin onboarding status.',
[ApiTag.Tags]:
'A tag is a user-defined label that can be applied to assets for organizational purposes. Tags can also be hierarchical, allowing for parent-child relationships between tags.',
[ApiTag.Timeline]:
'Specialized endpoints related to the timeline implementation used in the web application. External applications or tools should not use or rely on these endpoints, as they are subject to change without notice.',
[ApiTag.Trash]:
'Endpoints for managing the trash can, which includes assets that have been discarded. Items in the trash are automatically deleted after a configured amount of time.',
[ApiTag.UsersAdmin]:
'Administrative endpoints for managing users, including creating, updating, deleting, and restoring users. Also includes endpoints for resetting passwords and PIN codes.',
[ApiTag.Users]:
'Endpoints for viewing and updating the current users, including product key information, profile picture data, onboarding progress, and more.',
[ApiTag.Views]: 'Endpoints for specialized views, such as the folder view.',
[ApiTag.Workflows]:
'A workflow is a set of actions that run whenever a triggering event occurs. Workflows also can include filters to further limit execution.',
};
export const AUDIO_ENCODER: Record<AudioCodec, string> = {
[AudioCodec.Aac]: 'aac',
[AudioCodec.Mp3]: 'mp3',
[AudioCodec.Libopus]: 'libopus',
[AudioCodec.Opus]: 'libopus',
[AudioCodec.PcmS16le]: 'pcm_s16le',
};
+24 -2
View File
@@ -1,6 +1,7 @@
import { Body, Controller, Delete, Get, HttpCode, HttpStatus, Param, Post, Query, Res } from '@nestjs/common';
import { ApiTags } from '@nestjs/swagger';
import { Response } from 'express';
import { Endpoint, HistoryBuilder } from 'src/decorators';
import {
ActivityCreateDto,
ActivityDto,
@@ -9,24 +10,35 @@ import {
ActivityStatisticsResponseDto,
} from 'src/dtos/activity.dto';
import { AuthDto } from 'src/dtos/auth.dto';
import { Permission } from 'src/enum';
import { ApiTag, Permission } from 'src/enum';
import { Auth, Authenticated } from 'src/middleware/auth.guard';
import { ActivityService } from 'src/services/activity.service';
import { UUIDParamDto } from 'src/validation';
@ApiTags('Activities')
@ApiTags(ApiTag.Activities)
@Controller('activities')
export class ActivityController {
constructor(private service: ActivityService) {}
@Get()
@Authenticated({ permission: Permission.ActivityRead })
@Endpoint({
summary: 'List all activities',
description:
'Returns a list of activities for the selected asset or album. The activities are returned in sorted order, with the oldest activities appearing first.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
getActivities(@Auth() auth: AuthDto, @Query() dto: ActivitySearchDto): Promise<ActivityResponseDto[]> {
return this.service.getAll(auth, dto);
}
@Post()
@Authenticated({ permission: Permission.ActivityCreate })
@Endpoint({
summary: 'Create an activity',
description: 'Create a like or a comment for an album, or an asset in an album.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
async createActivity(
@Auth() auth: AuthDto,
@Body() dto: ActivityCreateDto,
@@ -41,6 +53,11 @@ export class ActivityController {
@Get('statistics')
@Authenticated({ permission: Permission.ActivityStatistics })
@Endpoint({
summary: 'Retrieve activity statistics',
description: 'Returns the number of likes and comments for a given album or asset in an album.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
getActivityStatistics(@Auth() auth: AuthDto, @Query() dto: ActivityDto): Promise<ActivityStatisticsResponseDto> {
return this.service.getStatistics(auth, dto);
}
@@ -48,6 +65,11 @@ export class ActivityController {
@Delete(':id')
@Authenticated({ permission: Permission.ActivityDelete })
@HttpCode(HttpStatus.NO_CONTENT)
@Endpoint({
summary: 'Delete an activity',
description: 'Removes a like or comment from a given album or asset in an album.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
deleteActivity(@Auth() auth: AuthDto, @Param() { id }: UUIDParamDto): Promise<void> {
return this.service.delete(auth, id);
}
+65 -2
View File
@@ -1,5 +1,6 @@
import { Body, Controller, Delete, Get, HttpCode, HttpStatus, Param, Patch, Post, Put, Query } from '@nestjs/common';
import { ApiTags } from '@nestjs/swagger';
import { Endpoint, HistoryBuilder } from 'src/decorators';
import {
AddUsersDto,
AlbumInfoDto,
@@ -14,36 +15,56 @@ import {
} from 'src/dtos/album.dto';
import { BulkIdResponseDto, BulkIdsDto } from 'src/dtos/asset-ids.response.dto';
import { AuthDto } from 'src/dtos/auth.dto';
import { Permission } from 'src/enum';
import { ApiTag, Permission } from 'src/enum';
import { Auth, Authenticated } from 'src/middleware/auth.guard';
import { AlbumService } from 'src/services/album.service';
import { ParseMeUUIDPipe, UUIDParamDto } from 'src/validation';
@ApiTags('Albums')
@ApiTags(ApiTag.Albums)
@Controller('albums')
export class AlbumController {
constructor(private service: AlbumService) {}
@Get()
@Authenticated({ permission: Permission.AlbumRead })
@Endpoint({
summary: 'List all albums',
description: 'Retrieve a list of albums available to the authenticated user.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
getAllAlbums(@Auth() auth: AuthDto, @Query() query: GetAlbumsDto): Promise<AlbumResponseDto[]> {
return this.service.getAll(auth, query);
}
@Post()
@Authenticated({ permission: Permission.AlbumCreate })
@Endpoint({
summary: 'Create an album',
description: 'Create a new album. The album can also be created with initial users and assets.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
createAlbum(@Auth() auth: AuthDto, @Body() dto: CreateAlbumDto): Promise<AlbumResponseDto> {
return this.service.create(auth, dto);
}
@Get('statistics')
@Authenticated({ permission: Permission.AlbumStatistics })
@Endpoint({
summary: 'Retrieve album statistics',
description: 'Returns statistics about the albums available to the authenticated user.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
getAlbumStatistics(@Auth() auth: AuthDto): Promise<AlbumStatisticsResponseDto> {
return this.service.getStatistics(auth);
}
@Authenticated({ permission: Permission.AlbumRead, sharedLink: true })
@Get(':id')
@Endpoint({
summary: 'Retrieve an album',
description: 'Retrieve information about a specific album by its ID.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
getAlbumInfo(
@Auth() auth: AuthDto,
@Param() { id }: UUIDParamDto,
@@ -54,6 +75,12 @@ export class AlbumController {
@Patch(':id')
@Authenticated({ permission: Permission.AlbumUpdate })
@Endpoint({
summary: 'Update an album',
description:
'Update the information of a specific album by its ID. This endpoint can be used to update the album name, description, sort order, etc. However, it is not used to add or remove assets or users from the album.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
updateAlbumInfo(
@Auth() auth: AuthDto,
@Param() { id }: UUIDParamDto,
@@ -65,12 +92,23 @@ export class AlbumController {
@Delete(':id')
@Authenticated({ permission: Permission.AlbumDelete })
@HttpCode(HttpStatus.NO_CONTENT)
@Endpoint({
summary: 'Delete an album',
description:
'Delete a specific album by its ID. Note the album is initially trashed and then immediately scheduled for deletion, but relies on a background job to complete the process.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
deleteAlbum(@Auth() auth: AuthDto, @Param() { id }: UUIDParamDto) {
return this.service.delete(auth, id);
}
@Put(':id/assets')
@Authenticated({ permission: Permission.AlbumAssetCreate, sharedLink: true })
@Endpoint({
summary: 'Add assets to an album',
description: 'Add multiple assets to a specific album by its ID.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
addAssetsToAlbum(
@Auth() auth: AuthDto,
@Param() { id }: UUIDParamDto,
@@ -81,12 +119,22 @@ export class AlbumController {
@Put('assets')
@Authenticated({ permission: Permission.AlbumAssetCreate, sharedLink: true })
@Endpoint({
summary: 'Add assets to albums',
description: 'Send a list of asset IDs and album IDs to add each asset to each album.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
addAssetsToAlbums(@Auth() auth: AuthDto, @Body() dto: AlbumsAddAssetsDto): Promise<AlbumsAddAssetsResponseDto> {
return this.service.addAssetsToAlbums(auth, dto);
}
@Delete(':id/assets')
@Authenticated({ permission: Permission.AlbumAssetDelete })
@Endpoint({
summary: 'Remove assets from an album',
description: 'Remove multiple assets from a specific album by its ID.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
removeAssetFromAlbum(
@Auth() auth: AuthDto,
@Body() dto: BulkIdsDto,
@@ -97,6 +145,11 @@ export class AlbumController {
@Put(':id/users')
@Authenticated({ permission: Permission.AlbumUserCreate })
@Endpoint({
summary: 'Share album with users',
description: 'Share an album with multiple users. Each user can be given a specific role in the album.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
addUsersToAlbum(
@Auth() auth: AuthDto,
@Param() { id }: UUIDParamDto,
@@ -108,6 +161,11 @@ export class AlbumController {
@Put(':id/user/:userId')
@Authenticated({ permission: Permission.AlbumUserUpdate })
@HttpCode(HttpStatus.NO_CONTENT)
@Endpoint({
summary: 'Update user role',
description: 'Change the role for a specific user in a specific album.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
updateAlbumUser(
@Auth() auth: AuthDto,
@Param() { id }: UUIDParamDto,
@@ -120,6 +178,11 @@ export class AlbumController {
@Delete(':id/user/:userId')
@Authenticated({ permission: Permission.AlbumUserDelete })
@HttpCode(HttpStatus.NO_CONTENT)
@Endpoint({
summary: 'Remove user from album',
description: 'Remove a user from an album. Use an ID of "me" to leave a shared album.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
removeUserFromAlbum(
@Auth() auth: AuthDto,
@Param() { id }: UUIDParamDto,
+33 -2
View File
@@ -1,43 +1,69 @@
import { Body, Controller, Delete, Get, HttpCode, HttpStatus, Param, Post, Put } from '@nestjs/common';
import { ApiTags } from '@nestjs/swagger';
import { Endpoint, HistoryBuilder } from 'src/decorators';
import { APIKeyCreateDto, APIKeyCreateResponseDto, APIKeyResponseDto, APIKeyUpdateDto } from 'src/dtos/api-key.dto';
import { AuthDto } from 'src/dtos/auth.dto';
import { Permission } from 'src/enum';
import { ApiTag, Permission } from 'src/enum';
import { Auth, Authenticated } from 'src/middleware/auth.guard';
import { ApiKeyService } from 'src/services/api-key.service';
import { UUIDParamDto } from 'src/validation';
@ApiTags('API Keys')
@ApiTags(ApiTag.ApiKeys)
@Controller('api-keys')
export class ApiKeyController {
constructor(private service: ApiKeyService) {}
@Post()
@Authenticated({ permission: Permission.ApiKeyCreate })
@Endpoint({
summary: 'Create an API key',
description: 'Creates a new API key. It will be limited to the permissions specified.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
createApiKey(@Auth() auth: AuthDto, @Body() dto: APIKeyCreateDto): Promise<APIKeyCreateResponseDto> {
return this.service.create(auth, dto);
}
@Get()
@Authenticated({ permission: Permission.ApiKeyRead })
@Endpoint({
summary: 'List all API keys',
description: 'Retrieve all API keys of the current user.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
getApiKeys(@Auth() auth: AuthDto): Promise<APIKeyResponseDto[]> {
return this.service.getAll(auth);
}
@Get('me')
@Authenticated({ permission: false })
@Endpoint({
summary: 'Retrieve the current API key',
description: 'Retrieve the API key that is used to access this endpoint.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
async getMyApiKey(@Auth() auth: AuthDto): Promise<APIKeyResponseDto> {
return this.service.getMine(auth);
}
@Get(':id')
@Authenticated({ permission: Permission.ApiKeyRead })
@Endpoint({
summary: 'Retrieve an API key',
description: 'Retrieve an API key by its ID. The current user must own this API key.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
getApiKey(@Auth() auth: AuthDto, @Param() { id }: UUIDParamDto): Promise<APIKeyResponseDto> {
return this.service.getById(auth, id);
}
@Put(':id')
@Authenticated({ permission: Permission.ApiKeyUpdate })
@Endpoint({
summary: 'Update an API key',
description: 'Updates the name and permissions of an API key by its ID. The current user must own this API key.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
updateApiKey(
@Auth() auth: AuthDto,
@Param() { id }: UUIDParamDto,
@@ -49,6 +75,11 @@ export class ApiKeyController {
@Delete(':id')
@Authenticated({ permission: Permission.ApiKeyDelete })
@HttpCode(HttpStatus.NO_CONTENT)
@Endpoint({
summary: 'Delete an API key',
description: 'Deletes an API key identified by its ID. The current user must own this API key.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
deleteApiKey(@Auth() auth: AuthDto, @Param() { id }: UUIDParamDto): Promise<void> {
return this.service.delete(auth, id);
}
@@ -85,19 +85,6 @@ describe(AssetMediaController.name, () => {
expect(body).toEqual(factory.responses.badRequest(['metadata must be valid JSON']));
});
it('should validate iCloudId is a string', async () => {
const { status, body } = await request(ctx.getHttpServer())
.post('/assets')
.attach('assetData', assetData, filename)
.field({
...makeUploadDto(),
metadata: JSON.stringify([{ key: AssetMetadataKey.MobileApp, value: { iCloudId: 123 } }]),
});
expect(status).toBe(400);
expect(body).toEqual(factory.responses.badRequest(['metadata.0.value.iCloudId must be a string']));
});
it('should require `deviceAssetId`', async () => {
const { status, body } = await request(ctx.getHttpServer())
.post('/assets')
@@ -15,9 +15,9 @@ import {
UploadedFiles,
UseInterceptors,
} from '@nestjs/common';
import { ApiBody, ApiConsumes, ApiHeader, ApiOperation, ApiTags } from '@nestjs/swagger';
import { ApiBody, ApiConsumes, ApiHeader, ApiResponse, ApiTags } from '@nestjs/swagger';
import { NextFunction, Request, Response } from 'express';
import { EndpointLifecycle } from 'src/decorators';
import { Endpoint, HistoryBuilder } from 'src/decorators';
import {
AssetBulkUploadCheckResponseDto,
AssetMediaResponseDto,
@@ -33,8 +33,9 @@ import {
CheckExistingAssetsDto,
UploadFieldName,
} from 'src/dtos/asset-media.dto';
import { AssetDownloadOriginalDto } from 'src/dtos/asset.dto';
import { AuthDto } from 'src/dtos/auth.dto';
import { ImmichHeader, Permission, RouteKey } from 'src/enum';
import { ApiTag, ImmichHeader, Permission, RouteKey } from 'src/enum';
import { AssetUploadInterceptor } from 'src/middleware/asset-upload.interceptor';
import { Auth, Authenticated, FileResponse } from 'src/middleware/auth.guard';
import { FileUploadInterceptor, getFiles } from 'src/middleware/file-upload.interceptor';
@@ -44,7 +45,7 @@ import { UploadFiles } from 'src/types';
import { ImmichFileResponse, sendFile } from 'src/utils/file';
import { FileNotEmptyValidator, UUIDParamDto } from 'src/validation';
@ApiTags('Assets')
@ApiTags(ApiTag.Assets)
@Controller(RouteKey.Asset)
export class AssetMediaController {
constructor(
@@ -53,6 +54,7 @@ export class AssetMediaController {
) {}
@Post()
@Authenticated({ permission: Permission.AssetUpload, sharedLink: true })
@UseInterceptors(AssetUploadInterceptor, FileUploadInterceptor)
@ApiConsumes('multipart/form-data')
@ApiHeader({
@@ -61,7 +63,21 @@ export class AssetMediaController {
required: false,
})
@ApiBody({ description: 'Asset Upload Information', type: AssetMediaCreateDto })
@Authenticated({ permission: Permission.AssetUpload, sharedLink: true })
@ApiResponse({
status: 200,
description: 'Asset is a duplicate',
type: AssetMediaResponseDto,
})
@ApiResponse({
status: 201,
description: 'Asset uploaded successfully',
type: AssetMediaResponseDto,
})
@Endpoint({
summary: 'Upload asset',
description: 'Uploads a new asset to the server.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
async uploadAsset(
@Auth() auth: AuthDto,
@UploadedFiles(new ParseFilePipe({ validators: [new FileNotEmptyValidator(['assetData'])] })) files: UploadFiles,
@@ -81,26 +97,33 @@ export class AssetMediaController {
@Get(':id/original')
@FileResponse()
@Authenticated({ permission: Permission.AssetDownload, sharedLink: true })
@Endpoint({
summary: 'Download original asset',
description: 'Downloads the original file of the specified asset.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
async downloadAsset(
@Auth() auth: AuthDto,
@Param() { id }: UUIDParamDto,
@Query() dto: AssetDownloadOriginalDto,
@Res() res: Response,
@Next() next: NextFunction,
) {
await sendFile(res, next, () => this.service.downloadOriginal(auth, id), this.logger);
await sendFile(res, next, () => this.service.downloadOriginal(auth, id, dto), this.logger);
}
/**
* Replace the asset with new file, without changing its id
*/
@Put(':id/original')
@UseInterceptors(FileUploadInterceptor)
@ApiConsumes('multipart/form-data')
@EndpointLifecycle({
addedAt: 'v1.106.0',
deprecatedAt: 'v1.142.0',
summary: 'replaceAsset',
description: 'Replace the asset with new file, without changing its id',
@ApiResponse({
status: 200,
description: 'Asset replaced successfully',
type: AssetMediaResponseDto,
})
@Endpoint({
summary: 'Replace asset',
description: 'Replace the asset with new file, without changing its id.',
history: new HistoryBuilder().added('v1').deprecated('v1', { replacementId: 'copyAsset' }),
})
@Authenticated({ permission: Permission.AssetReplace, sharedLink: true })
async replaceAsset(
@@ -122,6 +145,12 @@ export class AssetMediaController {
@Get(':id/thumbnail')
@FileResponse()
@Authenticated({ permission: Permission.AssetView, sharedLink: true })
@Endpoint({
summary: 'View asset thumbnail',
description:
'Retrieve the thumbnail image for the specified asset. Viewing the fullsize thumbnail might redirect to downloadAsset, which requires a different permission.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
async viewAsset(
@Auth() auth: AuthDto,
@Param() { id }: UUIDParamDto,
@@ -159,6 +188,11 @@ export class AssetMediaController {
@Get(':id/video/playback')
@FileResponse()
@Authenticated({ permission: Permission.AssetView, sharedLink: true })
@Endpoint({
summary: 'Play asset video',
description: 'Streams the video file for the specified asset. This endpoint also supports byte range requests.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
async playAssetVideo(
@Auth() auth: AuthDto,
@Param() { id }: UUIDParamDto,
@@ -168,14 +202,12 @@ export class AssetMediaController {
await sendFile(res, next, () => this.service.playbackVideo(auth, id), this.logger);
}
/**
* Checks if multiple assets exist on the server and returns all existing - used by background backup
*/
@Post('exist')
@Authenticated()
@ApiOperation({
summary: 'checkExistingAssets',
@Authenticated({ permission: Permission.AssetUpload })
@Endpoint({
summary: 'Check existing assets',
description: 'Checks if multiple assets exist on the server and returns all existing - used by background backup',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
@HttpCode(HttpStatus.OK)
checkExistingAssets(
@@ -185,14 +217,12 @@ export class AssetMediaController {
return this.service.checkExistingAssets(auth, dto);
}
/**
* Checks if assets exist by checksums
*/
@Post('bulk-upload-check')
@Authenticated({ permission: Permission.AssetUpload })
@ApiOperation({
summary: 'checkBulkUpload',
description: 'Checks if assets exist by checksums',
@Endpoint({
summary: 'Check bulk upload',
description: 'Determine which assets have already been uploaded to the server based on their SHA1 checksums.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
@HttpCode(HttpStatus.OK)
checkBulkUpload(
+191 -16
View File
@@ -24,6 +24,34 @@ describe(AssetController.name, () => {
await request(ctx.getHttpServer()).put(`/assets`);
expect(ctx.authenticate).toHaveBeenCalled();
});
it('should require a valid uuid', async () => {
const { status, body } = await request(ctx.getHttpServer())
.put(`/assets`)
.send({ ids: ['123'] });
expect(status).toBe(400);
expect(body).toEqual(factory.responses.badRequest(['each value in ids must be a UUID']));
});
it('should require duplicateId to be a string', async () => {
const id = factory.uuid();
const { status, body } = await request(ctx.getHttpServer())
.put(`/assets`)
.send({ ids: [id], duplicateId: true });
expect(status).toBe(400);
expect(body).toEqual(factory.responses.badRequest(['duplicateId must be a string']));
});
it('should accept a null duplicateId', async () => {
const id = factory.uuid();
await request(ctx.getHttpServer())
.put(`/assets`)
.send({ ids: [id], duplicateId: null });
expect(service.updateAll).toHaveBeenCalledWith(undefined, expect.objectContaining({ duplicateId: null }));
});
});
describe('DELETE /assets', () => {
@@ -79,6 +107,74 @@ describe(AssetController.name, () => {
});
});
describe('PUT /assets/metadata', () => {
it('should be an authenticated route', async () => {
await request(ctx.getHttpServer()).put(`/assets/metadata`);
expect(ctx.authenticate).toHaveBeenCalled();
});
it('should require a valid assetId', async () => {
const { status, body } = await request(ctx.getHttpServer())
.put('/assets/metadata')
.send({ items: [{ assetId: '123', key: 'test', value: {} }] });
expect(status).toBe(400);
expect(body).toEqual(factory.responses.badRequest(expect.arrayContaining(['items.0.assetId must be a UUID'])));
});
it('should require a key', async () => {
const { status, body } = await request(ctx.getHttpServer())
.put('/assets/metadata')
.send({ items: [{ assetId: factory.uuid(), value: {} }] });
expect(status).toBe(400);
expect(body).toEqual(
factory.responses.badRequest(
expect.arrayContaining(['items.0.key must be a string', 'items.0.key should not be empty']),
),
);
});
it('should work', async () => {
const { status } = await request(ctx.getHttpServer())
.put('/assets/metadata')
.send({ items: [{ assetId: factory.uuid(), key: AssetMetadataKey.MobileApp, value: { iCloudId: '123' } }] });
expect(status).toBe(200);
});
});
describe('DELETE /assets/metadata', () => {
it('should be an authenticated route', async () => {
await request(ctx.getHttpServer()).delete(`/assets/metadata`);
expect(ctx.authenticate).toHaveBeenCalled();
});
it('should require a valid assetId', async () => {
const { status, body } = await request(ctx.getHttpServer())
.delete('/assets/metadata')
.send({ items: [{ assetId: '123', key: 'test' }] });
expect(status).toBe(400);
expect(body).toEqual(factory.responses.badRequest(expect.arrayContaining(['items.0.assetId must be a UUID'])));
});
it('should require a key', async () => {
const { status, body } = await request(ctx.getHttpServer())
.delete('/assets/metadata')
.send({ items: [{ assetId: factory.uuid() }] });
expect(status).toBe(400);
expect(body).toEqual(
factory.responses.badRequest(
expect.arrayContaining(['items.0.key must be a string', 'items.0.key should not be empty']),
),
);
});
it('should work', async () => {
const { status } = await request(ctx.getHttpServer())
.delete('/assets/metadata')
.send({ items: [{ assetId: factory.uuid(), key: AssetMetadataKey.MobileApp }] });
expect(status).toBe(204);
});
});
describe('PUT /assets/:id', () => {
it('should be an authenticated route', async () => {
await request(ctx.getHttpServer()).get(`/assets/123`);
@@ -111,12 +207,28 @@ describe(AssetController.name, () => {
});
it('should reject invalid rating', async () => {
for (const test of [{ rating: 7 }, { rating: 3.5 }, { rating: null }]) {
for (const test of [{ rating: 7 }, { rating: 3.5 }, { rating: -2 }]) {
const { status, body } = await request(ctx.getHttpServer()).put(`/assets/${factory.uuid()}`).send(test);
expect(status).toBe(400);
expect(body).toEqual(factory.responses.badRequest());
}
});
it('should convert rating 0 to null', async () => {
const assetId = factory.uuid();
const { status } = await request(ctx.getHttpServer()).put(`/assets/${assetId}`).send({ rating: 0 });
expect(service.update).toHaveBeenCalledWith(undefined, assetId, { rating: null });
expect(status).toBe(200);
});
it('should leave correct ratings as-is', async () => {
const assetId = factory.uuid();
for (const test of [{ rating: -1 }, { rating: 1 }, { rating: 5 }]) {
const { status } = await request(ctx.getHttpServer()).put(`/assets/${assetId}`).send(test);
expect(service.update).toHaveBeenCalledWith(undefined, assetId, test);
expect(status).toBe(200);
}
});
});
describe('GET /assets/statistics', () => {
@@ -169,12 +281,10 @@ describe(AssetController.name, () => {
it('should require each item to have a valid key', async () => {
const { status, body } = await request(ctx.getHttpServer())
.put(`/assets/${factory.uuid()}/metadata`)
.send({ items: [{ key: 'someKey' }] });
.send({ items: [{ value: { some: 'value' } }] });
expect(status).toBe(400);
expect(body).toEqual(
factory.responses.badRequest(
expect.arrayContaining([expect.stringContaining('items.0.key must be one of the following values')]),
),
factory.responses.badRequest(['items.0.key must be a string', 'items.0.key should not be empty']),
);
});
@@ -224,16 +334,89 @@ describe(AssetController.name, () => {
expect(status).toBe(400);
expect(body).toEqual(factory.responses.badRequest(expect.arrayContaining(['id must be a UUID'])));
});
});
describe('PUT /assets/:id/edits', () => {
it('should be an authenticated route', async () => {
await request(ctx.getHttpServer()).put(`/assets/${factory.uuid()}/edits`).send({ edits: [] });
expect(ctx.authenticate).toHaveBeenCalled();
});
it('should accept valid edits and pass to service correctly', async () => {
const edits = [
{
action: 'crop',
parameters: {
x: 0,
y: 0,
width: 100,
height: 100,
},
},
];
const assetId = factory.uuid();
const { status } = await request(ctx.getHttpServer()).put(`/assets/${assetId}/edits`).send({
edits,
});
expect(service.editAsset).toHaveBeenCalledWith(undefined, assetId, { edits });
expect(status).toBe(200);
});
it('should require a valid id', async () => {
const { status, body } = await request(ctx.getHttpServer())
.put(`/assets/123/edits`)
.send({
edits: [
{
action: 'crop',
parameters: {
x: 0,
y: 0,
width: 100,
height: 100,
},
},
],
});
expect(status).toBe(400);
expect(body).toEqual(factory.responses.badRequest(expect.arrayContaining(['id must be a UUID'])));
});
it('should check the action and parameters discriminator', async () => {
const { status, body } = await request(ctx.getHttpServer())
.put(`/assets/${factory.uuid()}/edits`)
.send({
edits: [
{
action: 'rotate',
parameters: {
x: 0,
y: 0,
width: 100,
height: 100,
},
},
],
});
it('should require a valid key', async () => {
const { status, body } = await request(ctx.getHttpServer()).get(`/assets/${factory.uuid()}/metadata/invalid`);
expect(status).toBe(400);
expect(body).toEqual(
factory.responses.badRequest(
expect.arrayContaining([expect.stringContaining('key must be one of the following value')]),
expect.arrayContaining([expect.stringContaining('parameters.angle must be one of the following values')]),
),
);
});
it('should require at least one edit', async () => {
const { status, body } = await request(ctx.getHttpServer())
.put(`/assets/${factory.uuid()}/edits`)
.send({ edits: [] });
expect(status).toBe(400);
expect(body).toEqual(factory.responses.badRequest(['edits must contain at least 1 elements']));
});
});
describe('DELETE /assets/:id/metadata/:key', () => {
@@ -247,13 +430,5 @@ describe(AssetController.name, () => {
expect(status).toBe(400);
expect(body).toEqual(factory.responses.badRequest(['id must be a UUID']));
});
it('should require a valid key', async () => {
const { status, body } = await request(ctx.getHttpServer()).delete(`/assets/${factory.uuid()}/metadata/invalid`);
expect(status).toBe(400);
expect(body).toEqual(
factory.responses.badRequest([expect.stringContaining('key must be one of the following values')]),
);
});
});
});
+141 -11
View File
@@ -1,12 +1,15 @@
import { Body, Controller, Delete, Get, HttpCode, HttpStatus, Param, Post, Put, Query } from '@nestjs/common';
import { ApiOperation, ApiTags } from '@nestjs/swagger';
import { EndpointLifecycle } from 'src/decorators';
import { ApiTags } from '@nestjs/swagger';
import { Endpoint, HistoryBuilder } from 'src/decorators';
import { AssetResponseDto } from 'src/dtos/asset-response.dto';
import {
AssetBulkDeleteDto,
AssetBulkUpdateDto,
AssetCopyDto,
AssetJobsDto,
AssetMetadataBulkDeleteDto,
AssetMetadataBulkResponseDto,
AssetMetadataBulkUpsertDto,
AssetMetadataResponseDto,
AssetMetadataRouteParams,
AssetMetadataUpsertDto,
@@ -17,31 +20,34 @@ import {
UpdateAssetDto,
} from 'src/dtos/asset.dto';
import { AuthDto } from 'src/dtos/auth.dto';
import { AssetEditsCreateDto, AssetEditsResponseDto } from 'src/dtos/editing.dto';
import { AssetOcrResponseDto } from 'src/dtos/ocr.dto';
import { Permission, RouteKey } from 'src/enum';
import { ApiTag, Permission, RouteKey } from 'src/enum';
import { Auth, Authenticated } from 'src/middleware/auth.guard';
import { AssetService } from 'src/services/asset.service';
import { UUIDParamDto } from 'src/validation';
@ApiTags('Assets')
@ApiTags(ApiTag.Assets)
@Controller(RouteKey.Asset)
export class AssetController {
constructor(private service: AssetService) {}
@Get('random')
@Authenticated({ permission: Permission.AssetRead })
@EndpointLifecycle({ deprecatedAt: 'v1.116.0' })
@Endpoint({
summary: 'Get random assets',
description: 'Retrieve a specified number of random assets for the authenticated user.',
history: new HistoryBuilder().added('v1').deprecated('v1', { replacementId: 'searchAssets' }),
})
getRandom(@Auth() auth: AuthDto, @Query() dto: RandomAssetsDto): Promise<AssetResponseDto[]> {
return this.service.getRandom(auth, dto.count ?? 1);
}
/**
* Get all asset of a device that are in the database, ID only.
*/
@Get('/device/:deviceId')
@ApiOperation({
summary: 'getAllUserAssetsByDeviceId',
@Endpoint({
summary: 'Retrieve assets by device ID',
description: 'Get all asset of a device that are in the database, ID only.',
history: new HistoryBuilder().added('v1').deprecated('v2'),
})
@Authenticated()
getAllUserAssetsByDeviceId(@Auth() auth: AuthDto, @Param() { deviceId }: DeviceIdDto) {
@@ -50,13 +56,23 @@ export class AssetController {
@Get('statistics')
@Authenticated({ permission: Permission.AssetStatistics })
@Endpoint({
summary: 'Get asset statistics',
description: 'Retrieve various statistics about the assets owned by the authenticated user.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
getAssetStatistics(@Auth() auth: AuthDto, @Query() dto: AssetStatsDto): Promise<AssetStatsResponseDto> {
return this.service.getStatistics(auth, dto);
}
@Post('jobs')
@Authenticated()
@Authenticated({ permission: Permission.JobCreate })
@HttpCode(HttpStatus.NO_CONTENT)
@Endpoint({
summary: 'Run an asset job',
description: 'Run a specific job on a set of assets.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
runAssetJobs(@Auth() auth: AuthDto, @Body() dto: AssetJobsDto): Promise<void> {
return this.service.run(auth, dto);
}
@@ -64,6 +80,11 @@ export class AssetController {
@Put()
@Authenticated({ permission: Permission.AssetUpdate })
@HttpCode(HttpStatus.NO_CONTENT)
@Endpoint({
summary: 'Update assets',
description: 'Updates multiple assets at the same time.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
updateAssets(@Auth() auth: AuthDto, @Body() dto: AssetBulkUpdateDto): Promise<void> {
return this.service.updateAll(auth, dto);
}
@@ -71,12 +92,22 @@ export class AssetController {
@Delete()
@Authenticated({ permission: Permission.AssetDelete })
@HttpCode(HttpStatus.NO_CONTENT)
@Endpoint({
summary: 'Delete assets',
description: 'Deletes multiple assets at the same time.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
deleteAssets(@Auth() auth: AuthDto, @Body() dto: AssetBulkDeleteDto): Promise<void> {
return this.service.deleteAll(auth, dto);
}
@Get(':id')
@Authenticated({ permission: Permission.AssetRead, sharedLink: true })
@Endpoint({
summary: 'Retrieve an asset',
description: 'Retrieve detailed information about a specific asset.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
getAssetInfo(@Auth() auth: AuthDto, @Param() { id }: UUIDParamDto): Promise<AssetResponseDto> {
return this.service.get(auth, id) as Promise<AssetResponseDto>;
}
@@ -84,12 +115,48 @@ export class AssetController {
@Put('copy')
@Authenticated({ permission: Permission.AssetCopy })
@HttpCode(HttpStatus.NO_CONTENT)
@Endpoint({
summary: 'Copy asset',
description: 'Copy asset information like albums, tags, etc. from one asset to another.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
copyAsset(@Auth() auth: AuthDto, @Body() dto: AssetCopyDto): Promise<void> {
return this.service.copy(auth, dto);
}
@Put('metadata')
@Authenticated({ permission: Permission.AssetUpdate })
@Endpoint({
summary: 'Upsert asset metadata',
description: 'Upsert metadata key-value pairs for multiple assets.',
history: new HistoryBuilder().added('v1').beta('v2.5.0'),
})
updateBulkAssetMetadata(
@Auth() auth: AuthDto,
@Body() dto: AssetMetadataBulkUpsertDto,
): Promise<AssetMetadataBulkResponseDto[]> {
return this.service.upsertBulkMetadata(auth, dto);
}
@Delete('metadata')
@Authenticated({ permission: Permission.AssetUpdate })
@HttpCode(HttpStatus.NO_CONTENT)
@Endpoint({
summary: 'Delete asset metadata',
description: 'Delete metadata key-value pairs for multiple assets.',
history: new HistoryBuilder().added('v1').beta('v2.5.0'),
})
deleteBulkAssetMetadata(@Auth() auth: AuthDto, @Body() dto: AssetMetadataBulkDeleteDto): Promise<void> {
return this.service.deleteBulkMetadata(auth, dto);
}
@Put(':id')
@Authenticated({ permission: Permission.AssetUpdate })
@Endpoint({
summary: 'Update an asset',
description: 'Update information of a specific asset.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
updateAsset(
@Auth() auth: AuthDto,
@Param() { id }: UUIDParamDto,
@@ -100,18 +167,33 @@ export class AssetController {
@Get(':id/metadata')
@Authenticated({ permission: Permission.AssetRead })
@Endpoint({
summary: 'Get asset metadata',
description: 'Retrieve all metadata key-value pairs associated with the specified asset.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
getAssetMetadata(@Auth() auth: AuthDto, @Param() { id }: UUIDParamDto): Promise<AssetMetadataResponseDto[]> {
return this.service.getMetadata(auth, id);
}
@Get(':id/ocr')
@Authenticated({ permission: Permission.AssetRead })
@Endpoint({
summary: 'Retrieve asset OCR data',
description: 'Retrieve all OCR (Optical Character Recognition) data associated with the specified asset.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
getAssetOcr(@Auth() auth: AuthDto, @Param() { id }: UUIDParamDto): Promise<AssetOcrResponseDto[]> {
return this.service.getOcr(auth, id);
}
@Put(':id/metadata')
@Authenticated({ permission: Permission.AssetUpdate })
@Endpoint({
summary: 'Update asset metadata',
description: 'Update or add metadata key-value pairs for the specified asset.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
updateAssetMetadata(
@Auth() auth: AuthDto,
@Param() { id }: UUIDParamDto,
@@ -122,6 +204,11 @@ export class AssetController {
@Get(':id/metadata/:key')
@Authenticated({ permission: Permission.AssetRead })
@Endpoint({
summary: 'Retrieve asset metadata by key',
description: 'Retrieve the value of a specific metadata key associated with the specified asset.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
getAssetMetadataByKey(
@Auth() auth: AuthDto,
@Param() { id, key }: AssetMetadataRouteParams,
@@ -132,7 +219,50 @@ export class AssetController {
@Delete(':id/metadata/:key')
@Authenticated({ permission: Permission.AssetUpdate })
@HttpCode(HttpStatus.NO_CONTENT)
@Endpoint({
summary: 'Delete asset metadata by key',
description: 'Delete a specific metadata key-value pair associated with the specified asset.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
deleteAssetMetadata(@Auth() auth: AuthDto, @Param() { id, key }: AssetMetadataRouteParams): Promise<void> {
return this.service.deleteMetadataByKey(auth, id, key);
}
@Get(':id/edits')
@Authenticated({ permission: Permission.AssetEditGet })
@Endpoint({
summary: 'Retrieve edits for an existing asset',
description: 'Retrieve a series of edit actions (crop, rotate, mirror) associated with the specified asset.',
history: new HistoryBuilder().added('v2.5.0').beta('v2.5.0'),
})
getAssetEdits(@Auth() auth: AuthDto, @Param() { id }: UUIDParamDto): Promise<AssetEditsResponseDto> {
return this.service.getAssetEdits(auth, id);
}
@Put(':id/edits')
@Authenticated({ permission: Permission.AssetEditCreate })
@Endpoint({
summary: 'Apply edits to an existing asset',
description: 'Apply a series of edit actions (crop, rotate, mirror) to the specified asset.',
history: new HistoryBuilder().added('v2.5.0').beta('v2.5.0'),
})
editAsset(
@Auth() auth: AuthDto,
@Param() { id }: UUIDParamDto,
@Body() dto: AssetEditsCreateDto,
): Promise<AssetEditsResponseDto> {
return this.service.editAsset(auth, id, dto);
}
@Delete(':id/edits')
@Authenticated({ permission: Permission.AssetEditDelete })
@HttpCode(HttpStatus.NO_CONTENT)
@Endpoint({
summary: 'Remove edits from an existing asset',
description: 'Removes all edit actions (crop, rotate, mirror) associated with the specified asset.',
history: new HistoryBuilder().added('v2.5.0').beta('v2.5.0'),
})
removeAssetEdits(@Auth() auth: AuthDto, @Param() { id }: UUIDParamDto): Promise<void> {
return this.service.removeAssetEdits(auth, id);
}
}
@@ -1,17 +1,23 @@
import { Controller, HttpCode, HttpStatus, Post } from '@nestjs/common';
import { ApiTags } from '@nestjs/swagger';
import { Endpoint, HistoryBuilder } from 'src/decorators';
import { AuthDto } from 'src/dtos/auth.dto';
import { Permission } from 'src/enum';
import { ApiTag, Permission } from 'src/enum';
import { Auth, Authenticated } from 'src/middleware/auth.guard';
import { AuthAdminService } from 'src/services/auth-admin.service';
@ApiTags('Auth (admin)')
@ApiTags(ApiTag.AuthenticationAdmin)
@Controller('admin/auth')
export class AuthAdminController {
constructor(private service: AuthAdminService) {}
@Post('unlink-all')
@Authenticated({ permission: Permission.AdminAuthUnlinkAll, admin: true })
@HttpCode(HttpStatus.NO_CONTENT)
@Endpoint({
summary: 'Unlink all OAuth accounts',
description: 'Unlinks all OAuth accounts associated with user accounts in the system.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
unlinkAllOAuthAccountsAdmin(@Auth() auth: AuthDto): Promise<void> {
return this.service.unlinkAll(auth);
}
+59 -2
View File
@@ -1,6 +1,7 @@
import { Body, Controller, Delete, Get, HttpCode, HttpStatus, Post, Put, Req, Res } from '@nestjs/common';
import { ApiTags } from '@nestjs/swagger';
import { Request, Response } from 'express';
import { Endpoint, HistoryBuilder } from 'src/decorators';
import {
AuthDto,
AuthStatusResponseDto,
@@ -16,17 +17,22 @@ import {
ValidateAccessTokenResponseDto,
} from 'src/dtos/auth.dto';
import { UserAdminResponseDto } from 'src/dtos/user.dto';
import { AuthType, ImmichCookie, Permission } from 'src/enum';
import { ApiTag, AuthType, ImmichCookie, Permission } from 'src/enum';
import { Auth, Authenticated, GetLoginDetails } from 'src/middleware/auth.guard';
import { AuthService, LoginDetails } from 'src/services/auth.service';
import { respondWithCookie, respondWithoutCookie } from 'src/utils/response';
@ApiTags('Authentication')
@ApiTags(ApiTag.Authentication)
@Controller('auth')
export class AuthController {
constructor(private service: AuthService) {}
@Post('login')
@Endpoint({
summary: 'Login',
description: 'Login with username and password and receive a session token.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
async login(
@Res({ passthrough: true }) res: Response,
@Body() loginCredential: LoginCredentialDto,
@@ -44,11 +50,21 @@ export class AuthController {
}
@Post('admin-sign-up')
@Endpoint({
summary: 'Register admin',
description: 'Create the first admin user in the system.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
signUpAdmin(@Body() dto: SignUpDto): Promise<UserAdminResponseDto> {
return this.service.adminSignUp(dto);
}
@Post('validateToken')
@Endpoint({
summary: 'Validate access token',
description: 'Validate the current authorization method is still valid.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
@Authenticated({ permission: false })
@HttpCode(HttpStatus.OK)
validateAccessToken(): ValidateAccessTokenResponseDto {
@@ -58,6 +74,11 @@ export class AuthController {
@Post('change-password')
@Authenticated({ permission: Permission.AuthChangePassword })
@HttpCode(HttpStatus.OK)
@Endpoint({
summary: 'Change password',
description: 'Change the password of the current user.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
changePassword(@Auth() auth: AuthDto, @Body() dto: ChangePasswordDto): Promise<UserAdminResponseDto> {
return this.service.changePassword(auth, dto);
}
@@ -65,6 +86,11 @@ export class AuthController {
@Post('logout')
@Authenticated()
@HttpCode(HttpStatus.OK)
@Endpoint({
summary: 'Logout',
description: 'Logout the current user and invalidate the session token.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
async logout(
@Req() request: Request,
@Res({ passthrough: true }) res: Response,
@@ -82,6 +108,12 @@ export class AuthController {
@Get('status')
@Authenticated()
@Endpoint({
summary: 'Retrieve auth status',
description:
'Get information about the current session, including whether the user has a password, and if the session can access locked assets.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
getAuthStatus(@Auth() auth: AuthDto): Promise<AuthStatusResponseDto> {
return this.service.getAuthStatus(auth);
}
@@ -89,6 +121,11 @@ export class AuthController {
@Post('pin-code')
@Authenticated({ permission: Permission.PinCodeCreate })
@HttpCode(HttpStatus.NO_CONTENT)
@Endpoint({
summary: 'Setup pin code',
description: 'Setup a new pin code for the current user.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
setupPinCode(@Auth() auth: AuthDto, @Body() dto: PinCodeSetupDto): Promise<void> {
return this.service.setupPinCode(auth, dto);
}
@@ -96,6 +133,11 @@ export class AuthController {
@Put('pin-code')
@Authenticated({ permission: Permission.PinCodeUpdate })
@HttpCode(HttpStatus.NO_CONTENT)
@Endpoint({
summary: 'Change pin code',
description: 'Change the pin code for the current user.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
async changePinCode(@Auth() auth: AuthDto, @Body() dto: PinCodeChangeDto): Promise<void> {
return this.service.changePinCode(auth, dto);
}
@@ -103,6 +145,11 @@ export class AuthController {
@Delete('pin-code')
@Authenticated({ permission: Permission.PinCodeDelete })
@HttpCode(HttpStatus.NO_CONTENT)
@Endpoint({
summary: 'Reset pin code',
description: 'Reset the pin code for the current user by providing the account password',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
async resetPinCode(@Auth() auth: AuthDto, @Body() dto: PinCodeResetDto): Promise<void> {
return this.service.resetPinCode(auth, dto);
}
@@ -110,12 +157,22 @@ export class AuthController {
@Post('session/unlock')
@Authenticated()
@HttpCode(HttpStatus.NO_CONTENT)
@Endpoint({
summary: 'Unlock auth session',
description: 'Temporarily grant the session elevated access to locked assets by providing the correct PIN code.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
async unlockAuthSession(@Auth() auth: AuthDto, @Body() dto: SessionUnlockDto): Promise<void> {
return this.service.unlockSession(auth, dto);
}
@Post('session/lock')
@Authenticated()
@Endpoint({
summary: 'Lock auth session',
description: 'Remove elevated access to locked assets from the current session.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
@HttpCode(HttpStatus.NO_CONTENT)
async lockAuthSession(@Auth() auth: AuthDto): Promise<void> {
return this.service.lockSession(auth);
@@ -0,0 +1,101 @@
import { Body, Controller, Delete, Get, Next, Param, Post, Res, UploadedFile, UseInterceptors } from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import { ApiBody, ApiConsumes, ApiTags } from '@nestjs/swagger';
import { NextFunction, Response } from 'express';
import { Endpoint, HistoryBuilder } from 'src/decorators';
import {
DatabaseBackupDeleteDto,
DatabaseBackupListResponseDto,
DatabaseBackupUploadDto,
} from 'src/dtos/database-backup.dto';
import { ApiTag, ImmichCookie, Permission } from 'src/enum';
import { Authenticated, FileResponse, GetLoginDetails } from 'src/middleware/auth.guard';
import { LoggingRepository } from 'src/repositories/logging.repository';
import { LoginDetails } from 'src/services/auth.service';
import { DatabaseBackupService } from 'src/services/database-backup.service';
import { MaintenanceService } from 'src/services/maintenance.service';
import { sendFile } from 'src/utils/file';
import { respondWithCookie } from 'src/utils/response';
import { FilenameParamDto } from 'src/validation';
@ApiTags(ApiTag.DatabaseBackups)
@Controller('admin/database-backups')
export class DatabaseBackupController {
constructor(
private logger: LoggingRepository,
private service: DatabaseBackupService,
private maintenanceService: MaintenanceService,
) {}
@Get()
@Endpoint({
summary: 'List database backups',
description: 'Get the list of the successful and failed backups',
history: new HistoryBuilder().added('v2.5.0').alpha('v2.5.0'),
})
@Authenticated({ permission: Permission.Maintenance, admin: true })
listDatabaseBackups(): Promise<DatabaseBackupListResponseDto> {
return this.service.listBackups();
}
@Get(':filename')
@FileResponse()
@Endpoint({
summary: 'Download database backup',
description: 'Downloads the database backup file',
history: new HistoryBuilder().added('v2.5.0').alpha('v2.5.0'),
})
@Authenticated({ permission: Permission.BackupDownload, admin: true })
async downloadDatabaseBackup(
@Param() { filename }: FilenameParamDto,
@Res() res: Response,
@Next() next: NextFunction,
): Promise<void> {
await sendFile(res, next, () => this.service.downloadBackup(filename), this.logger);
}
@Delete()
@Endpoint({
summary: 'Delete database backup',
description: 'Delete a backup by its filename',
history: new HistoryBuilder().added('v2.5.0').alpha('v2.5.0'),
})
@Authenticated({ permission: Permission.BackupDelete, admin: true })
async deleteDatabaseBackup(@Body() dto: DatabaseBackupDeleteDto): Promise<void> {
return this.service.deleteBackup(dto.backups);
}
@Post('start-restore')
@Endpoint({
summary: 'Start database backup restore flow',
description: 'Put Immich into maintenance mode to restore a backup (Immich must not be configured)',
history: new HistoryBuilder().added('v2.5.0').alpha('v2.5.0'),
})
async startDatabaseRestoreFlow(
@GetLoginDetails() loginDetails: LoginDetails,
@Res({ passthrough: true }) res: Response,
): Promise<void> {
const { jwt } = await this.maintenanceService.startRestoreFlow();
return respondWithCookie(res, undefined, {
isSecure: loginDetails.isSecure,
values: [{ key: ImmichCookie.MaintenanceToken, value: jwt }],
});
}
@Post('upload')
@Authenticated({ permission: Permission.BackupUpload, admin: true })
@ApiConsumes('multipart/form-data')
@ApiBody({ description: 'Backup Upload', type: DatabaseBackupUploadDto })
@Endpoint({
summary: 'Upload database backup',
description: 'Uploads .sql/.sql.gz file to restore backup from',
history: new HistoryBuilder().added('v2.5.0').alpha('v2.5.0'),
})
@UseInterceptors(FileInterceptor('file'))
uploadDatabaseBackup(
@UploadedFile()
file: Express.Multer.File,
): Promise<void> {
return this.service.uploadBackup(file);
}
}
+17 -5
View File
@@ -1,20 +1,26 @@
import { Body, Controller, HttpCode, HttpStatus, Post, StreamableFile } from '@nestjs/common';
import { ApiTags } from '@nestjs/swagger';
import { AssetIdsDto } from 'src/dtos/asset.dto';
import { Endpoint, HistoryBuilder } from 'src/decorators';
import { AuthDto } from 'src/dtos/auth.dto';
import { DownloadInfoDto, DownloadResponseDto } from 'src/dtos/download.dto';
import { Permission } from 'src/enum';
import { DownloadArchiveDto, DownloadInfoDto, DownloadResponseDto } from 'src/dtos/download.dto';
import { ApiTag, Permission } from 'src/enum';
import { Auth, Authenticated, FileResponse } from 'src/middleware/auth.guard';
import { DownloadService } from 'src/services/download.service';
import { asStreamableFile } from 'src/utils/file';
@ApiTags('Download')
@ApiTags(ApiTag.Download)
@Controller('download')
export class DownloadController {
constructor(private service: DownloadService) {}
@Post('info')
@Authenticated({ permission: Permission.AssetDownload, sharedLink: true })
@Endpoint({
summary: 'Retrieve download information',
description:
'Retrieve information about how to request a download for the specified assets or album. The response includes groups of assets that can be downloaded together.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
getDownloadInfo(@Auth() auth: AuthDto, @Body() dto: DownloadInfoDto): Promise<DownloadResponseDto> {
return this.service.getDownloadInfo(auth, dto);
}
@@ -23,7 +29,13 @@ export class DownloadController {
@Authenticated({ permission: Permission.AssetDownload, sharedLink: true })
@FileResponse()
@HttpCode(HttpStatus.OK)
downloadArchive(@Auth() auth: AuthDto, @Body() dto: AssetIdsDto): Promise<StreamableFile> {
@Endpoint({
summary: 'Download asset archive',
description:
'Download a ZIP archive containing the specified assets. The assets must have been previously requested via the "getDownloadInfo" endpoint.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
downloadArchive(@Auth() auth: AuthDto, @Body() dto: DownloadArchiveDto): Promise<StreamableFile> {
return this.service.downloadArchive(auth, dto).then(asStreamableFile);
}
}
@@ -0,0 +1,47 @@
import { DuplicateController } from 'src/controllers/duplicate.controller';
import { DuplicateService } from 'src/services/duplicate.service';
import request from 'supertest';
import { factory } from 'test/small.factory';
import { ControllerContext, controllerSetup, mockBaseService } from 'test/utils';
describe(DuplicateController.name, () => {
let ctx: ControllerContext;
const service = mockBaseService(DuplicateService);
beforeAll(async () => {
ctx = await controllerSetup(DuplicateController, [{ provide: DuplicateService, useValue: service }]);
return () => ctx.close();
});
beforeEach(() => {
service.resetAllMocks();
ctx.reset();
});
describe('GET /duplicates', () => {
it('should be an authenticated route', async () => {
await request(ctx.getHttpServer()).get('/duplicates');
expect(ctx.authenticate).toHaveBeenCalled();
});
});
describe('DELETE /duplicates', () => {
it('should be an authenticated route', async () => {
await request(ctx.getHttpServer()).delete('/duplicates');
expect(ctx.authenticate).toHaveBeenCalled();
});
});
describe('DELETE /duplicates/:id', () => {
it('should be an authenticated route', async () => {
await request(ctx.getHttpServer()).delete(`/duplicates/${factory.uuid()}`);
expect(ctx.authenticate).toHaveBeenCalled();
});
it('should require a valid uuid', async () => {
const { status, body } = await request(ctx.getHttpServer()).delete(`/duplicates/123`);
expect(status).toBe(400);
expect(body).toEqual(factory.responses.badRequest(['id must be a UUID']));
});
});
});
+33 -5
View File
@@ -1,20 +1,26 @@
import { Body, Controller, Delete, Get, HttpCode, HttpStatus, Param } from '@nestjs/common';
import { Body, Controller, Delete, Get, HttpCode, HttpStatus, Param, Post } from '@nestjs/common';
import { ApiTags } from '@nestjs/swagger';
import { BulkIdsDto } from 'src/dtos/asset-ids.response.dto';
import { Endpoint, HistoryBuilder } from 'src/decorators';
import { BulkIdResponseDto, BulkIdsDto } from 'src/dtos/asset-ids.response.dto';
import { AuthDto } from 'src/dtos/auth.dto';
import { DuplicateResponseDto } from 'src/dtos/duplicate.dto';
import { Permission } from 'src/enum';
import { DuplicateResolveDto, DuplicateResponseDto } from 'src/dtos/duplicate.dto';
import { ApiTag, Permission } from 'src/enum';
import { Auth, Authenticated } from 'src/middleware/auth.guard';
import { DuplicateService } from 'src/services/duplicate.service';
import { UUIDParamDto } from 'src/validation';
@ApiTags('Duplicates')
@ApiTags(ApiTag.Duplicates)
@Controller('duplicates')
export class DuplicateController {
constructor(private service: DuplicateService) {}
@Get()
@Authenticated({ permission: Permission.DuplicateRead })
@Endpoint({
summary: 'Retrieve duplicates',
description: 'Retrieve a list of duplicate assets available to the authenticated user.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
getAssetDuplicates(@Auth() auth: AuthDto): Promise<DuplicateResponseDto[]> {
return this.service.getDuplicates(auth);
}
@@ -22,6 +28,11 @@ export class DuplicateController {
@Delete()
@Authenticated({ permission: Permission.DuplicateDelete })
@HttpCode(HttpStatus.NO_CONTENT)
@Endpoint({
summary: 'Delete duplicates',
description: 'Delete multiple duplicate assets specified by their IDs.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
deleteDuplicates(@Auth() auth: AuthDto, @Body() dto: BulkIdsDto): Promise<void> {
return this.service.deleteAll(auth, dto);
}
@@ -29,7 +40,24 @@ export class DuplicateController {
@Delete(':id')
@Authenticated({ permission: Permission.DuplicateDelete })
@HttpCode(HttpStatus.NO_CONTENT)
@Endpoint({
summary: 'Delete a duplicate',
description: 'Delete a single duplicate asset specified by its ID.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
deleteDuplicate(@Auth() auth: AuthDto, @Param() { id }: UUIDParamDto): Promise<void> {
return this.service.delete(auth, id);
}
@Post('resolve')
@HttpCode(HttpStatus.OK)
@Authenticated({ permission: Permission.DuplicateDelete })
@Endpoint({
summary: 'Resolve duplicate groups',
description: 'Resolve duplicate groups by synchronizing metadata across assets and deleting/trashing duplicates.',
history: new HistoryBuilder().added('v3.0.0').alpha('v3.0.0'),
})
resolveDuplicates(@Auth() auth: AuthDto, @Body() dto: DuplicateResolveDto): Promise<BulkIdResponseDto[]> {
return this.service.resolve(auth, dto);
}
}
+24 -2
View File
@@ -1,5 +1,6 @@
import { Body, Controller, Delete, Get, HttpCode, HttpStatus, Param, Post, Put, Query } from '@nestjs/common';
import { ApiTags } from '@nestjs/swagger';
import { Endpoint, HistoryBuilder } from 'src/decorators';
import { AuthDto } from 'src/dtos/auth.dto';
import {
AssetFaceCreateDto,
@@ -8,30 +9,46 @@ import {
FaceDto,
PersonResponseDto,
} from 'src/dtos/person.dto';
import { Permission } from 'src/enum';
import { ApiTag, Permission } from 'src/enum';
import { Auth, Authenticated } from 'src/middleware/auth.guard';
import { PersonService } from 'src/services/person.service';
import { UUIDParamDto } from 'src/validation';
@ApiTags('Faces')
@ApiTags(ApiTag.Faces)
@Controller('faces')
export class FaceController {
constructor(private service: PersonService) {}
@Post()
@Authenticated({ permission: Permission.FaceCreate })
@Endpoint({
summary: 'Create a face',
description:
'Create a new face that has not been discovered by facial recognition. The content of the bounding box is considered a face.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
createFace(@Auth() auth: AuthDto, @Body() dto: AssetFaceCreateDto) {
return this.service.createFace(auth, dto);
}
@Get()
@Authenticated({ permission: Permission.FaceRead })
@Endpoint({
summary: 'Retrieve faces for asset',
description: 'Retrieve all faces belonging to an asset.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
getFaces(@Auth() auth: AuthDto, @Query() dto: FaceDto): Promise<AssetFaceResponseDto[]> {
return this.service.getFacesById(auth, dto);
}
@Put(':id')
@Authenticated({ permission: Permission.FaceUpdate })
@Endpoint({
summary: 'Re-assign a face to another person',
description: 'Re-assign the face provided in the body to the person identified by the id in the path parameter.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
reassignFacesById(
@Auth() auth: AuthDto,
@Param() { id }: UUIDParamDto,
@@ -43,6 +60,11 @@ export class FaceController {
@Delete(':id')
@Authenticated({ permission: Permission.FaceDelete })
@HttpCode(HttpStatus.NO_CONTENT)
@Endpoint({
summary: 'Delete a face',
description: 'Delete a face identified by the id. Optionally can be force deleted.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
deleteFace(@Auth() auth: AuthDto, @Param() { id }: UUIDParamDto, @Body() dto: AssetFaceDeleteDto): Promise<void> {
return this.service.deleteFace(auth, id, dto);
}
+10
View File
@@ -7,11 +7,13 @@ import { AssetUploadController } from 'src/controllers/asset-upload.controller';
import { AssetController } from 'src/controllers/asset.controller';
import { AuthAdminController } from 'src/controllers/auth-admin.controller';
import { AuthController } from 'src/controllers/auth.controller';
import { DatabaseBackupController } from 'src/controllers/database-backup.controller';
import { DownloadController } from 'src/controllers/download.controller';
import { DuplicateController } from 'src/controllers/duplicate.controller';
import { FaceController } from 'src/controllers/face.controller';
import { JobController } from 'src/controllers/job.controller';
import { LibraryController } from 'src/controllers/library.controller';
import { MaintenanceController } from 'src/controllers/maintenance.controller';
import { MapController } from 'src/controllers/map.controller';
import { MemoryController } from 'src/controllers/memory.controller';
import { NotificationAdminController } from 'src/controllers/notification-admin.controller';
@@ -19,6 +21,8 @@ import { NotificationController } from 'src/controllers/notification.controller'
import { OAuthController } from 'src/controllers/oauth.controller';
import { PartnerController } from 'src/controllers/partner.controller';
import { PersonController } from 'src/controllers/person.controller';
import { PluginController } from 'src/controllers/plugin.controller';
import { QueueController } from 'src/controllers/queue.controller';
import { SearchController } from 'src/controllers/search.controller';
import { ServerController } from 'src/controllers/server.controller';
import { SessionController } from 'src/controllers/session.controller';
@@ -33,6 +37,7 @@ import { TrashController } from 'src/controllers/trash.controller';
import { UserAdminController } from 'src/controllers/user-admin.controller';
import { UserController } from 'src/controllers/user.controller';
import { ViewController } from 'src/controllers/view.controller';
import { WorkflowController } from 'src/controllers/workflow.controller';
export const controllers = [
ApiKeyController,
@@ -44,11 +49,13 @@ export const controllers = [
AssetUploadController,
AuthController,
AuthAdminController,
DatabaseBackupController,
DownloadController,
DuplicateController,
FaceController,
JobController,
LibraryController,
MaintenanceController,
MapController,
MemoryController,
NotificationController,
@@ -56,6 +63,8 @@ export const controllers = [
OAuthController,
PartnerController,
PersonController,
PluginController,
QueueController,
SearchController,
ServerController,
SessionController,
@@ -70,4 +79,5 @@ export const controllers = [
UserAdminController,
UserController,
ViewController,
WorkflowController,
];
+38 -10
View File
@@ -1,31 +1,59 @@
import { Body, Controller, Get, HttpCode, HttpStatus, Param, Post, Put } from '@nestjs/common';
import { ApiTags } from '@nestjs/swagger';
import { AllJobStatusResponseDto, JobCommandDto, JobCreateDto, JobIdParamDto, JobStatusDto } from 'src/dtos/job.dto';
import { Permission } from 'src/enum';
import { Authenticated } from 'src/middleware/auth.guard';
import { Endpoint, HistoryBuilder } from 'src/decorators';
import { AuthDto } from 'src/dtos/auth.dto';
import { JobCreateDto } from 'src/dtos/job.dto';
import { QueueResponseLegacyDto, QueuesResponseLegacyDto } from 'src/dtos/queue-legacy.dto';
import { QueueCommandDto, QueueNameParamDto } from 'src/dtos/queue.dto';
import { ApiTag, Permission } from 'src/enum';
import { Auth, Authenticated } from 'src/middleware/auth.guard';
import { JobService } from 'src/services/job.service';
import { QueueService } from 'src/services/queue.service';
@ApiTags('Jobs')
@ApiTags(ApiTag.Jobs)
@Controller('jobs')
export class JobController {
constructor(private service: JobService) {}
constructor(
private service: JobService,
private queueService: QueueService,
) {}
@Get()
@Authenticated({ permission: Permission.JobRead, admin: true })
getAllJobsStatus(): Promise<AllJobStatusResponseDto> {
return this.service.getAllJobsStatus();
@Endpoint({
summary: 'Retrieve queue counts and status',
description: 'Retrieve the counts of the current queue, as well as the current status.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2').deprecated('v2.4.0'),
})
getQueuesLegacy(@Auth() auth: AuthDto): Promise<QueuesResponseLegacyDto> {
return this.queueService.getAllLegacy(auth);
}
@Post()
@Authenticated({ permission: Permission.JobCreate, admin: true })
@HttpCode(HttpStatus.NO_CONTENT)
@Endpoint({
summary: 'Create a manual job',
description:
'Run a specific job. Most jobs are queued automatically, but this endpoint allows for manual creation of a handful of jobs, including various cleanup tasks, as well as creating a new database backup.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
createJob(@Body() dto: JobCreateDto): Promise<void> {
return this.service.create(dto);
}
@Put(':id')
@Put(':name')
@Authenticated({ permission: Permission.JobCreate, admin: true })
sendJobCommand(@Param() { id }: JobIdParamDto, @Body() dto: JobCommandDto): Promise<JobStatusDto> {
return this.service.handleCommand(id, dto);
@Endpoint({
summary: 'Run jobs',
description:
'Queue all assets for a specific job type. Defaults to only queueing assets that have not yet been processed, but the force command can be used to re-process all assets.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2').deprecated('v2.4.0'),
})
runQueueCommandLegacy(
@Param() { name }: QueueNameParamDto,
@Body() dto: QueueCommandDto,
): Promise<QueueResponseLegacyDto> {
return this.queueService.runCommandLegacy(name, dto);
}
}
+44 -2
View File
@@ -1,5 +1,6 @@
import { Body, Controller, Delete, Get, HttpCode, HttpStatus, Param, Post, Put } from '@nestjs/common';
import { ApiTags } from '@nestjs/swagger';
import { Endpoint, HistoryBuilder } from 'src/decorators';
import {
CreateLibraryDto,
LibraryResponseDto,
@@ -8,36 +9,56 @@ import {
ValidateLibraryDto,
ValidateLibraryResponseDto,
} from 'src/dtos/library.dto';
import { Permission } from 'src/enum';
import { ApiTag, Permission } from 'src/enum';
import { Authenticated } from 'src/middleware/auth.guard';
import { LibraryService } from 'src/services/library.service';
import { UUIDParamDto } from 'src/validation';
@ApiTags('Libraries')
@ApiTags(ApiTag.Libraries)
@Controller('libraries')
export class LibraryController {
constructor(private service: LibraryService) {}
@Get()
@Authenticated({ permission: Permission.LibraryRead, admin: true })
@Endpoint({
summary: 'Retrieve libraries',
description: 'Retrieve a list of external libraries.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
getAllLibraries(): Promise<LibraryResponseDto[]> {
return this.service.getAll();
}
@Post()
@Authenticated({ permission: Permission.LibraryCreate, admin: true })
@Endpoint({
summary: 'Create a library',
description: 'Create a new external library.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
createLibrary(@Body() dto: CreateLibraryDto): Promise<LibraryResponseDto> {
return this.service.create(dto);
}
@Get(':id')
@Authenticated({ permission: Permission.LibraryRead, admin: true })
@Endpoint({
summary: 'Retrieve a library',
description: 'Retrieve an external library by its ID.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
getLibrary(@Param() { id }: UUIDParamDto): Promise<LibraryResponseDto> {
return this.service.get(id);
}
@Put(':id')
@Authenticated({ permission: Permission.LibraryUpdate, admin: true })
@Endpoint({
summary: 'Update a library',
description: 'Update an existing external library.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
updateLibrary(@Param() { id }: UUIDParamDto, @Body() dto: UpdateLibraryDto): Promise<LibraryResponseDto> {
return this.service.update(id, dto);
}
@@ -45,6 +66,11 @@ export class LibraryController {
@Delete(':id')
@Authenticated({ permission: Permission.LibraryDelete, admin: true })
@HttpCode(HttpStatus.NO_CONTENT)
@Endpoint({
summary: 'Delete a library',
description: 'Delete an external library by its ID.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
deleteLibrary(@Param() { id }: UUIDParamDto): Promise<void> {
return this.service.delete(id);
}
@@ -52,6 +78,11 @@ export class LibraryController {
@Post(':id/validate')
@Authenticated({ admin: true })
@HttpCode(HttpStatus.OK)
@Endpoint({
summary: 'Validate library settings',
description: 'Validate the settings of an external library.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
// TODO: change endpoint to validate current settings instead
validate(@Param() { id }: UUIDParamDto, @Body() dto: ValidateLibraryDto): Promise<ValidateLibraryResponseDto> {
return this.service.validate(id, dto);
@@ -59,6 +90,12 @@ export class LibraryController {
@Get(':id/statistics')
@Authenticated({ permission: Permission.LibraryStatistics, admin: true })
@Endpoint({
summary: 'Retrieve library statistics',
description:
'Retrieve statistics for a specific external library, including number of videos, images, and storage usage.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
getLibraryStatistics(@Param() { id }: UUIDParamDto): Promise<LibraryStatsResponseDto> {
return this.service.getStatistics(id);
}
@@ -66,6 +103,11 @@ export class LibraryController {
@Post(':id/scan')
@Authenticated({ permission: Permission.LibraryUpdate, admin: true })
@HttpCode(HttpStatus.NO_CONTENT)
@Endpoint({
summary: 'Scan a library',
description: 'Queue a scan for the external library to find and import new assets.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
scanLibrary(@Param() { id }: UUIDParamDto): Promise<void> {
return this.service.queueScan(id);
}
@@ -0,0 +1,39 @@
import { MaintenanceController } from 'src/controllers/maintenance.controller';
import { MaintenanceAction } from 'src/enum';
import { MaintenanceService } from 'src/services/maintenance.service';
import request from 'supertest';
import { errorDto } from 'test/medium/responses';
import { ControllerContext, controllerSetup, mockBaseService } from 'test/utils';
describe(MaintenanceController.name, () => {
let ctx: ControllerContext;
const service = mockBaseService(MaintenanceService);
beforeAll(async () => {
ctx = await controllerSetup(MaintenanceController, [{ provide: MaintenanceService, useValue: service }]);
return () => ctx.close();
});
beforeEach(() => {
service.resetAllMocks();
ctx.reset();
});
describe('POST /admin/maintenance', () => {
it('should be an authenticated route', async () => {
await request(ctx.getHttpServer()).post('/admin/maintenance').send();
expect(ctx.authenticate).toHaveBeenCalled();
});
it('should require a backup file when action is restore', async () => {
const { status, body } = await request(ctx.getHttpServer()).post('/admin/maintenance').send({
action: MaintenanceAction.RestoreDatabase,
});
expect(status).toBe(400);
expect(body).toEqual(
errorDto.badRequest(['restoreBackupFilename must be a string', 'restoreBackupFilename should not be empty']),
);
expect(ctx.authenticate).toHaveBeenCalled();
});
});
});
@@ -0,0 +1,76 @@
import { BadRequestException, Body, Controller, Get, Post, Res } from '@nestjs/common';
import { ApiTags } from '@nestjs/swagger';
import { Response } from 'express';
import { Endpoint, HistoryBuilder } from 'src/decorators';
import { AuthDto } from 'src/dtos/auth.dto';
import {
MaintenanceAuthDto,
MaintenanceDetectInstallResponseDto,
MaintenanceLoginDto,
MaintenanceStatusResponseDto,
SetMaintenanceModeDto,
} from 'src/dtos/maintenance.dto';
import { ApiTag, ImmichCookie, MaintenanceAction, Permission } from 'src/enum';
import { Auth, Authenticated, GetLoginDetails } from 'src/middleware/auth.guard';
import { LoginDetails } from 'src/services/auth.service';
import { MaintenanceService } from 'src/services/maintenance.service';
import { respondWithCookie } from 'src/utils/response';
@ApiTags(ApiTag.Maintenance)
@Controller('admin/maintenance')
export class MaintenanceController {
constructor(private service: MaintenanceService) {}
@Get('status')
@Endpoint({
summary: 'Get maintenance mode status',
description: 'Fetch information about the currently running maintenance action.',
history: new HistoryBuilder().added('v2.5.0').alpha('v2.5.0'),
})
getMaintenanceStatus(): MaintenanceStatusResponseDto {
return this.service.getMaintenanceStatus();
}
@Get('detect-install')
@Endpoint({
summary: 'Detect existing install',
description: 'Collect integrity checks and other heuristics about local data.',
history: new HistoryBuilder().added('v2.5.0').alpha('v2.5.0'),
})
@Authenticated({ permission: Permission.Maintenance, admin: true })
detectPriorInstall(): Promise<MaintenanceDetectInstallResponseDto> {
return this.service.detectPriorInstall();
}
@Post('login')
@Endpoint({
summary: 'Log into maintenance mode',
description: 'Login with maintenance token or cookie to receive current information and perform further actions.',
history: new HistoryBuilder().added('v2.3.0').alpha('v2.3.0'),
})
maintenanceLogin(@Body() _dto: MaintenanceLoginDto): MaintenanceAuthDto {
throw new BadRequestException('Not in maintenance mode');
}
@Post()
@Endpoint({
summary: 'Set maintenance mode',
description: 'Put Immich into or take it out of maintenance mode',
history: new HistoryBuilder().added('v2.3.0').alpha('v2.3.0'),
})
@Authenticated({ permission: Permission.Maintenance, admin: true })
async setMaintenanceMode(
@Auth() auth: AuthDto,
@Body() dto: SetMaintenanceModeDto,
@GetLoginDetails() loginDetails: LoginDetails,
@Res({ passthrough: true }) res: Response,
): Promise<void> {
if (dto.action !== MaintenanceAction.End) {
const { jwt } = await this.service.startMaintenance(dto, auth.user.name);
return respondWithCookie(res, undefined, {
isSecure: loginDetails.isSecure,
values: [{ key: ImmichCookie.MaintenanceToken, value: jwt }],
});
}
}
}
+15 -3
View File
@@ -1,5 +1,6 @@
import { Controller, Get, HttpCode, HttpStatus, Query } from '@nestjs/common';
import { ApiTags } from '@nestjs/swagger';
import { Endpoint, HistoryBuilder } from 'src/decorators';
import { AuthDto } from 'src/dtos/auth.dto';
import {
MapMarkerDto,
@@ -7,23 +8,34 @@ import {
MapReverseGeocodeDto,
MapReverseGeocodeResponseDto,
} from 'src/dtos/map.dto';
import { ApiTag, Permission } from 'src/enum';
import { Auth, Authenticated } from 'src/middleware/auth.guard';
import { MapService } from 'src/services/map.service';
@ApiTags('Map')
@ApiTags(ApiTag.Map)
@Controller('map')
export class MapController {
constructor(private service: MapService) {}
@Get('markers')
@Authenticated()
@Authenticated({ permission: Permission.MapRead })
@Endpoint({
summary: 'Retrieve map markers',
description: 'Retrieve a list of latitude and longitude coordinates for every asset with location data.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
getMapMarkers(@Auth() auth: AuthDto, @Query() options: MapMarkerDto): Promise<MapMarkerResponseDto[]> {
return this.service.getMapMarkers(auth, options);
}
@Authenticated()
@Get('reverse-geocode')
@Authenticated({ permission: Permission.MapSearch })
@HttpCode(HttpStatus.OK)
@Endpoint({
summary: 'Reverse geocode coordinates',
description: 'Retrieve location information (e.g., city, country) for given latitude and longitude coordinates.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
reverseGeocode(@Query() dto: MapReverseGeocodeDto): Promise<MapReverseGeocodeResponseDto[]> {
return this.service.reverseGeocode(dto);
}
@@ -24,6 +24,11 @@ describe(MemoryController.name, () => {
await request(ctx.getHttpServer()).get('/memories');
expect(ctx.authenticate).toHaveBeenCalled();
});
it('should not require any parameters', async () => {
await request(ctx.getHttpServer()).get('/memories').query({});
expect(service.search).toHaveBeenCalled();
});
});
describe('POST /memories', () => {
@@ -46,6 +51,20 @@ describe(MemoryController.name, () => {
errorDto.badRequest(['data.year must be a positive number', 'data.year must be an integer number']),
);
});
it('should accept showAt and hideAt', async () => {
const { status } = await request(ctx.getHttpServer())
.post('/memories')
.send({
type: 'on_this_day',
data: { year: 2020 },
memoryAt: new Date(2021).toISOString(),
showAt: new Date(2022).toISOString(),
hideAt: new Date(2023).toISOString(),
});
expect(status).toBe(201);
});
});
describe('GET /memories/statistics', () => {
+45 -2
View File
@@ -1,5 +1,6 @@
import { Body, Controller, Delete, Get, HttpCode, HttpStatus, Param, Post, Put, Query } from '@nestjs/common';
import { ApiTags } from '@nestjs/swagger';
import { Endpoint, HistoryBuilder } from 'src/decorators';
import { BulkIdResponseDto, BulkIdsDto } from 'src/dtos/asset-ids.response.dto';
import { AuthDto } from 'src/dtos/auth.dto';
import {
@@ -9,42 +10,69 @@ import {
MemoryStatisticsResponseDto,
MemoryUpdateDto,
} from 'src/dtos/memory.dto';
import { Permission } from 'src/enum';
import { ApiTag, Permission } from 'src/enum';
import { Auth, Authenticated } from 'src/middleware/auth.guard';
import { MemoryService } from 'src/services/memory.service';
import { UUIDParamDto } from 'src/validation';
@ApiTags('Memories')
@ApiTags(ApiTag.Memories)
@Controller('memories')
export class MemoryController {
constructor(private service: MemoryService) {}
@Get()
@Authenticated({ permission: Permission.MemoryRead })
@Endpoint({
summary: 'Retrieve memories',
description:
'Retrieve a list of memories. Memories are sorted descending by creation date by default, although they can also be sorted in ascending order, or randomly.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
searchMemories(@Auth() auth: AuthDto, @Query() dto: MemorySearchDto): Promise<MemoryResponseDto[]> {
return this.service.search(auth, dto);
}
@Post()
@Authenticated({ permission: Permission.MemoryCreate })
@Endpoint({
summary: 'Create a memory',
description:
'Create a new memory by providing a name, description, and a list of asset IDs to include in the memory.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
createMemory(@Auth() auth: AuthDto, @Body() dto: MemoryCreateDto): Promise<MemoryResponseDto> {
return this.service.create(auth, dto);
}
@Get('statistics')
@Authenticated({ permission: Permission.MemoryStatistics })
@Endpoint({
summary: 'Retrieve memories statistics',
description: 'Retrieve statistics about memories, such as total count and other relevant metrics.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
memoriesStatistics(@Auth() auth: AuthDto, @Query() dto: MemorySearchDto): Promise<MemoryStatisticsResponseDto> {
return this.service.statistics(auth, dto);
}
@Get(':id')
@Authenticated({ permission: Permission.MemoryRead })
@Endpoint({
summary: 'Retrieve a memory',
description: 'Retrieve a specific memory by its ID.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
getMemory(@Auth() auth: AuthDto, @Param() { id }: UUIDParamDto): Promise<MemoryResponseDto> {
return this.service.get(auth, id);
}
@Put(':id')
@Authenticated({ permission: Permission.MemoryUpdate })
@Endpoint({
summary: 'Update a memory',
description: 'Update an existing memory by its ID.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
updateMemory(
@Auth() auth: AuthDto,
@Param() { id }: UUIDParamDto,
@@ -56,12 +84,22 @@ export class MemoryController {
@Delete(':id')
@Authenticated({ permission: Permission.MemoryDelete })
@HttpCode(HttpStatus.NO_CONTENT)
@Endpoint({
summary: 'Delete a memory',
description: 'Delete a specific memory by its ID.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
deleteMemory(@Auth() auth: AuthDto, @Param() { id }: UUIDParamDto): Promise<void> {
return this.service.remove(auth, id);
}
@Put(':id/assets')
@Authenticated({ permission: Permission.MemoryAssetCreate })
@Endpoint({
summary: 'Add assets to a memory',
description: 'Add a list of asset IDs to a specific memory.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
addMemoryAssets(
@Auth() auth: AuthDto,
@Param() { id }: UUIDParamDto,
@@ -73,6 +111,11 @@ export class MemoryController {
@Delete(':id/assets')
@Authenticated({ permission: Permission.MemoryAssetDelete })
@HttpCode(HttpStatus.OK)
@Endpoint({
summary: 'Remove assets from a memory',
description: 'Remove a list of asset IDs from a specific memory.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
removeMemoryAssets(
@Auth() auth: AuthDto,
@Body() dto: BulkIdsDto,
@@ -0,0 +1,36 @@
import { NotificationAdminController } from 'src/controllers/notification-admin.controller';
import { NotificationAdminService } from 'src/services/notification-admin.service';
import request from 'supertest';
import { factory } from 'test/small.factory';
import { ControllerContext, controllerSetup, mockBaseService } from 'test/utils';
describe(NotificationAdminController.name, () => {
let ctx: ControllerContext;
const service = mockBaseService(NotificationAdminService);
beforeAll(async () => {
ctx = await controllerSetup(NotificationAdminController, [
{ provide: NotificationAdminService, useValue: service },
]);
return () => ctx.close();
});
beforeEach(() => {
service.resetAllMocks();
ctx.reset();
});
describe('POST /admin/notifications', () => {
it('should be an authenticated route', async () => {
await request(ctx.getHttpServer()).post('/admin/notifications');
expect(ctx.authenticate).toHaveBeenCalled();
});
it('should accept a null readAt', async () => {
await request(ctx.getHttpServer())
.post(`/admin/notifications`)
.send({ title: 'Test', userId: factory.uuid(), readAt: null });
expect(service.create).toHaveBeenCalledWith(undefined, expect.objectContaining({ readAt: null }));
});
});
});
@@ -1,5 +1,6 @@
import { Body, Controller, HttpCode, HttpStatus, Param, Post } from '@nestjs/common';
import { ApiTags } from '@nestjs/swagger';
import { Endpoint, HistoryBuilder } from 'src/decorators';
import { AuthDto } from 'src/dtos/auth.dto';
import {
NotificationCreateDto,
@@ -9,17 +10,23 @@ import {
TestEmailResponseDto,
} from 'src/dtos/notification.dto';
import { SystemConfigSmtpDto } from 'src/dtos/system-config.dto';
import { ApiTag } from 'src/enum';
import { Auth, Authenticated } from 'src/middleware/auth.guard';
import { EmailTemplate } from 'src/repositories/email.repository';
import { NotificationAdminService } from 'src/services/notification-admin.service';
@ApiTags('Notifications (Admin)')
@ApiTags(ApiTag.NotificationsAdmin)
@Controller('admin/notifications')
export class NotificationAdminController {
constructor(private service: NotificationAdminService) {}
@Post()
@Authenticated({ admin: true })
@Endpoint({
summary: 'Create a notification',
description: 'Create a new notification for a specific user.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
createNotification(@Auth() auth: AuthDto, @Body() dto: NotificationCreateDto): Promise<NotificationDto> {
return this.service.create(auth, dto);
}
@@ -27,6 +34,11 @@ export class NotificationAdminController {
@Post('test-email')
@Authenticated({ admin: true })
@HttpCode(HttpStatus.OK)
@Endpoint({
summary: 'Send test email',
description: 'Send a test email using the provided SMTP configuration.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
sendTestEmailAdmin(@Auth() auth: AuthDto, @Body() dto: SystemConfigSmtpDto): Promise<TestEmailResponseDto> {
return this.service.sendTestEmail(auth.user.id, dto);
}
@@ -34,6 +46,11 @@ export class NotificationAdminController {
@Post('templates/:name')
@Authenticated({ admin: true })
@HttpCode(HttpStatus.OK)
@Endpoint({
summary: 'Render email template',
description: 'Retrieve a preview of the provided email template.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
getNotificationTemplateAdmin(
@Auth() auth: AuthDto,
@Param('name') name: EmailTemplate,
@@ -37,9 +37,33 @@ describe(NotificationController.name, () => {
describe('PUT /notifications', () => {
it('should be an authenticated route', async () => {
await request(ctx.getHttpServer()).get('/notifications');
await request(ctx.getHttpServer()).put('/notifications');
expect(ctx.authenticate).toHaveBeenCalled();
});
describe('ids', () => {
it('should require a list', async () => {
const { status, body } = await request(ctx.getHttpServer()).put(`/notifications`).send({ ids: true });
expect(status).toBe(400);
expect(body).toEqual(errorDto.badRequest(expect.arrayContaining(['ids must be an array'])));
});
it('should require uuids', async () => {
const { status, body } = await request(ctx.getHttpServer())
.put(`/notifications`)
.send({ ids: [true] });
expect(status).toBe(400);
expect(body).toEqual(errorDto.badRequest(['each value in ids must be a UUID']));
});
it('should accept valid uuids', async () => {
const id = factory.uuid();
await request(ctx.getHttpServer())
.put(`/notifications`)
.send({ ids: [id] });
expect(service.updateAll).toHaveBeenCalledWith(undefined, expect.objectContaining({ ids: [id] }));
});
});
});
describe('GET /notifications/:id', () => {
@@ -60,5 +84,11 @@ describe(NotificationController.name, () => {
await request(ctx.getHttpServer()).put(`/notifications/${factory.uuid()}`).send({ readAt: factory.date() });
expect(ctx.authenticate).toHaveBeenCalled();
});
it('should accept a null readAt', async () => {
const id = factory.uuid();
await request(ctx.getHttpServer()).put(`/notifications/${id}`).send({ readAt: null });
expect(service.update).toHaveBeenCalledWith(undefined, id, expect.objectContaining({ readAt: null }));
});
});
});
@@ -1,5 +1,6 @@
import { Body, Controller, Delete, Get, HttpCode, HttpStatus, Param, Put, Query } from '@nestjs/common';
import { ApiTags } from '@nestjs/swagger';
import { Endpoint, HistoryBuilder } from 'src/decorators';
import { AuthDto } from 'src/dtos/auth.dto';
import {
NotificationDeleteAllDto,
@@ -8,18 +9,23 @@ import {
NotificationUpdateAllDto,
NotificationUpdateDto,
} from 'src/dtos/notification.dto';
import { Permission } from 'src/enum';
import { ApiTag, Permission } from 'src/enum';
import { Auth, Authenticated } from 'src/middleware/auth.guard';
import { NotificationService } from 'src/services/notification.service';
import { UUIDParamDto } from 'src/validation';
@ApiTags('Notifications')
@ApiTags(ApiTag.Notifications)
@Controller('notifications')
export class NotificationController {
constructor(private service: NotificationService) {}
@Get()
@Authenticated({ permission: Permission.NotificationRead })
@Endpoint({
summary: 'Retrieve notifications',
description: 'Retrieve a list of notifications.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
getNotifications(@Auth() auth: AuthDto, @Query() dto: NotificationSearchDto): Promise<NotificationDto[]> {
return this.service.search(auth, dto);
}
@@ -27,6 +33,11 @@ export class NotificationController {
@Put()
@Authenticated({ permission: Permission.NotificationUpdate })
@HttpCode(HttpStatus.NO_CONTENT)
@Endpoint({
summary: 'Update notifications',
description: 'Update a list of notifications. Allows to bulk-set the read status of notifications.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
updateNotifications(@Auth() auth: AuthDto, @Body() dto: NotificationUpdateAllDto): Promise<void> {
return this.service.updateAll(auth, dto);
}
@@ -34,18 +45,33 @@ export class NotificationController {
@Delete()
@Authenticated({ permission: Permission.NotificationDelete })
@HttpCode(HttpStatus.NO_CONTENT)
@Endpoint({
summary: 'Delete notifications',
description: 'Delete a list of notifications at once.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
deleteNotifications(@Auth() auth: AuthDto, @Body() dto: NotificationDeleteAllDto): Promise<void> {
return this.service.deleteAll(auth, dto);
}
@Get(':id')
@Authenticated({ permission: Permission.NotificationRead })
@Endpoint({
summary: 'Get a notification',
description: 'Retrieve a specific notification identified by id.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
getNotification(@Auth() auth: AuthDto, @Param() { id }: UUIDParamDto): Promise<NotificationDto> {
return this.service.get(auth, id);
}
@Put(':id')
@Authenticated({ permission: Permission.NotificationUpdate })
@Endpoint({
summary: 'Update a notification',
description: 'Update a specific notification to set its read status.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
updateNotification(
@Auth() auth: AuthDto,
@Param() { id }: UUIDParamDto,
@@ -57,6 +83,11 @@ export class NotificationController {
@Delete(':id')
@Authenticated({ permission: Permission.NotificationDelete })
@HttpCode(HttpStatus.NO_CONTENT)
@Endpoint({
summary: 'Delete a notification',
description: 'Delete a specific notification.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
deleteNotification(@Auth() auth: AuthDto, @Param() { id }: UUIDParamDto): Promise<void> {
return this.service.delete(auth, id);
}
+29 -2
View File
@@ -1,6 +1,7 @@
import { Body, Controller, Get, HttpCode, HttpStatus, Post, Redirect, Req, Res } from '@nestjs/common';
import { ApiTags } from '@nestjs/swagger';
import { Request, Response } from 'express';
import { Endpoint, HistoryBuilder } from 'src/decorators';
import {
AuthDto,
LoginResponseDto,
@@ -9,18 +10,24 @@ import {
OAuthConfigDto,
} from 'src/dtos/auth.dto';
import { UserAdminResponseDto } from 'src/dtos/user.dto';
import { AuthType, ImmichCookie } from 'src/enum';
import { ApiTag, AuthType, ImmichCookie } from 'src/enum';
import { Auth, Authenticated, GetLoginDetails } from 'src/middleware/auth.guard';
import { AuthService, LoginDetails } from 'src/services/auth.service';
import { respondWithCookie } from 'src/utils/response';
@ApiTags('OAuth')
@ApiTags(ApiTag.Authentication)
@Controller('oauth')
export class OAuthController {
constructor(private service: AuthService) {}
@Get('mobile-redirect')
@Redirect()
@Endpoint({
summary: 'Redirect OAuth to mobile',
description:
'Requests to this URL are automatically forwarded to the mobile app, and is used in some cases for OAuth redirecting.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
redirectOAuthToMobile(@Req() request: Request) {
return {
url: this.service.getMobileRedirect(request.url),
@@ -29,6 +36,11 @@ export class OAuthController {
}
@Post('authorize')
@Endpoint({
summary: 'Start OAuth',
description: 'Initiate the OAuth authorization process.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
async startOAuth(
@Body() dto: OAuthConfigDto,
@Res({ passthrough: true }) res: Response,
@@ -49,6 +61,11 @@ export class OAuthController {
}
@Post('callback')
@Endpoint({
summary: 'Finish OAuth',
description: 'Complete the OAuth authorization process by exchanging the authorization code for a session token.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
async finishOAuth(
@Req() request: Request,
@Res({ passthrough: true }) res: Response,
@@ -71,6 +88,11 @@ export class OAuthController {
@Post('link')
@Authenticated()
@HttpCode(HttpStatus.OK)
@Endpoint({
summary: 'Link OAuth account',
description: 'Link an OAuth account to the authenticated user.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
linkOAuthAccount(
@Req() request: Request,
@Auth() auth: AuthDto,
@@ -82,6 +104,11 @@ export class OAuthController {
@Post('unlink')
@Authenticated()
@HttpCode(HttpStatus.OK)
@Endpoint({
summary: 'Unlink OAuth account',
description: 'Unlink the OAuth account from the authenticated user.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
unlinkOAuthAccount(@Auth() auth: AuthDto): Promise<UserAdminResponseDto> {
return this.service.unlink(auth);
}
+28 -4
View File
@@ -1,32 +1,46 @@
import { Body, Controller, Delete, Get, HttpCode, HttpStatus, Param, Post, Put, Query } from '@nestjs/common';
import { ApiTags } from '@nestjs/swagger';
import { EndpointLifecycle } from 'src/decorators';
import { Endpoint, HistoryBuilder } from 'src/decorators';
import { AuthDto } from 'src/dtos/auth.dto';
import { PartnerCreateDto, PartnerResponseDto, PartnerSearchDto, PartnerUpdateDto } from 'src/dtos/partner.dto';
import { Permission } from 'src/enum';
import { ApiTag, Permission } from 'src/enum';
import { Auth, Authenticated } from 'src/middleware/auth.guard';
import { PartnerService } from 'src/services/partner.service';
import { UUIDParamDto } from 'src/validation';
@ApiTags('Partners')
@ApiTags(ApiTag.Partners)
@Controller('partners')
export class PartnerController {
constructor(private service: PartnerService) {}
@Get()
@Authenticated({ permission: Permission.PartnerRead })
@Endpoint({
summary: 'Retrieve partners',
description: 'Retrieve a list of partners with whom assets are shared.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
getPartners(@Auth() auth: AuthDto, @Query() dto: PartnerSearchDto): Promise<PartnerResponseDto[]> {
return this.service.search(auth, dto);
}
@Post()
@Authenticated({ permission: Permission.PartnerCreate })
@Endpoint({
summary: 'Create a partner',
description: 'Create a new partner to share assets with.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
createPartner(@Auth() auth: AuthDto, @Body() dto: PartnerCreateDto): Promise<PartnerResponseDto> {
return this.service.create(auth, dto);
}
@Post(':id')
@EndpointLifecycle({ deprecatedAt: 'v1.141.0' })
@Endpoint({
summary: 'Create a partner',
description: 'Create a new partner to share assets with.',
history: new HistoryBuilder().added('v1').deprecated('v1', { replacementId: 'createPartner' }),
})
@Authenticated({ permission: Permission.PartnerCreate })
createPartnerDeprecated(@Auth() auth: AuthDto, @Param() { id }: UUIDParamDto): Promise<PartnerResponseDto> {
return this.service.create(auth, { sharedWithId: id });
@@ -34,6 +48,11 @@ export class PartnerController {
@Put(':id')
@Authenticated({ permission: Permission.PartnerUpdate })
@Endpoint({
summary: 'Update a partner',
description: "Specify whether a partner's assets should appear in the user's timeline.",
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
updatePartner(
@Auth() auth: AuthDto,
@Param() { id }: UUIDParamDto,
@@ -45,6 +64,11 @@ export class PartnerController {
@Delete(':id')
@Authenticated({ permission: Permission.PartnerDelete })
@HttpCode(HttpStatus.NO_CONTENT)
@Endpoint({
summary: 'Remove a partner',
description: 'Stop sharing assets with a partner.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
removePartner(@Auth() auth: AuthDto, @Param() { id }: UUIDParamDto): Promise<void> {
return this.service.remove(auth, id);
}
@@ -58,6 +58,11 @@ describe(PersonController.name, () => {
await request(ctx.getHttpServer()).post('/people').send({ birthDate: '' });
expect(service.create).toHaveBeenCalledWith(undefined, { birthDate: null });
});
it('should map an empty color to null', async () => {
await request(ctx.getHttpServer()).post('/people').send({ color: '' });
expect(service.create).toHaveBeenCalledWith(undefined, { color: null });
});
});
describe('DELETE /people', () => {
+58 -2
View File
@@ -14,6 +14,7 @@ import {
} from '@nestjs/common';
import { ApiTags } from '@nestjs/swagger';
import { NextFunction, Response } from 'express';
import { Endpoint, HistoryBuilder } from 'src/decorators';
import { BulkIdResponseDto, BulkIdsDto } from 'src/dtos/asset-ids.response.dto';
import { AuthDto } from 'src/dtos/auth.dto';
import {
@@ -27,14 +28,14 @@ import {
PersonStatisticsResponseDto,
PersonUpdateDto,
} from 'src/dtos/person.dto';
import { Permission } from 'src/enum';
import { ApiTag, Permission } from 'src/enum';
import { Auth, Authenticated, FileResponse } from 'src/middleware/auth.guard';
import { LoggingRepository } from 'src/repositories/logging.repository';
import { PersonService } from 'src/services/person.service';
import { sendFile } from 'src/utils/file';
import { UUIDParamDto } from 'src/validation';
@ApiTags('People')
@ApiTags(ApiTag.People)
@Controller('people')
export class PersonController {
constructor(
@@ -46,18 +47,33 @@ export class PersonController {
@Get()
@Authenticated({ permission: Permission.PersonRead })
@Endpoint({
summary: 'Get all people',
description: 'Retrieve a list of all people.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
getAllPeople(@Auth() auth: AuthDto, @Query() options: PersonSearchDto): Promise<PeopleResponseDto> {
return this.service.getAll(auth, options);
}
@Post()
@Authenticated({ permission: Permission.PersonCreate })
@Endpoint({
summary: 'Create a person',
description: 'Create a new person that can have multiple faces assigned to them.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
createPerson(@Auth() auth: AuthDto, @Body() dto: PersonCreateDto): Promise<PersonResponseDto> {
return this.service.create(auth, dto);
}
@Put()
@Authenticated({ permission: Permission.PersonUpdate })
@Endpoint({
summary: 'Update people',
description: 'Bulk update multiple people at once.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
updatePeople(@Auth() auth: AuthDto, @Body() dto: PeopleUpdateDto): Promise<BulkIdResponseDto[]> {
return this.service.updateAll(auth, dto);
}
@@ -65,18 +81,33 @@ export class PersonController {
@Delete()
@Authenticated({ permission: Permission.PersonDelete })
@HttpCode(HttpStatus.NO_CONTENT)
@Endpoint({
summary: 'Delete people',
description: 'Bulk delete a list of people at once.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
deletePeople(@Auth() auth: AuthDto, @Body() dto: BulkIdsDto): Promise<void> {
return this.service.deleteAll(auth, dto);
}
@Get(':id')
@Authenticated({ permission: Permission.PersonRead })
@Endpoint({
summary: 'Get a person',
description: 'Retrieve a person by id.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
getPerson(@Auth() auth: AuthDto, @Param() { id }: UUIDParamDto): Promise<PersonResponseDto> {
return this.service.getById(auth, id);
}
@Put(':id')
@Authenticated({ permission: Permission.PersonUpdate })
@Endpoint({
summary: 'Update person',
description: 'Update an individual person.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
updatePerson(
@Auth() auth: AuthDto,
@Param() { id }: UUIDParamDto,
@@ -88,12 +119,22 @@ export class PersonController {
@Delete(':id')
@Authenticated({ permission: Permission.PersonDelete })
@HttpCode(HttpStatus.NO_CONTENT)
@Endpoint({
summary: 'Delete person',
description: 'Delete an individual person.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
deletePerson(@Auth() auth: AuthDto, @Param() { id }: UUIDParamDto): Promise<void> {
return this.service.delete(auth, id);
}
@Get(':id/statistics')
@Authenticated({ permission: Permission.PersonStatistics })
@Endpoint({
summary: 'Get person statistics',
description: 'Retrieve statistics about a specific person.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
getPersonStatistics(@Auth() auth: AuthDto, @Param() { id }: UUIDParamDto): Promise<PersonStatisticsResponseDto> {
return this.service.getStatistics(auth, id);
}
@@ -101,6 +142,11 @@ export class PersonController {
@Get(':id/thumbnail')
@FileResponse()
@Authenticated({ permission: Permission.PersonRead })
@Endpoint({
summary: 'Get person thumbnail',
description: 'Retrieve the thumbnail file for a person.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
async getPersonThumbnail(
@Res() res: Response,
@Next() next: NextFunction,
@@ -112,6 +158,11 @@ export class PersonController {
@Put(':id/reassign')
@Authenticated({ permission: Permission.PersonReassign })
@Endpoint({
summary: 'Reassign faces',
description: 'Bulk reassign a list of faces to a different person.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
reassignFaces(
@Auth() auth: AuthDto,
@Param() { id }: UUIDParamDto,
@@ -123,6 +174,11 @@ export class PersonController {
@Post(':id/merge')
@Authenticated({ permission: Permission.PersonMerge })
@HttpCode(HttpStatus.OK)
@Endpoint({
summary: 'Merge people',
description: 'Merge a list of people into the person specified in the path parameter.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
mergePerson(
@Auth() auth: AuthDto,
@Param() { id }: UUIDParamDto,
@@ -0,0 +1,47 @@
import { Controller, Get, Param } from '@nestjs/common';
import { ApiTags } from '@nestjs/swagger';
import { Endpoint, HistoryBuilder } from 'src/decorators';
import { PluginResponseDto, PluginTriggerResponseDto } from 'src/dtos/plugin.dto';
import { Permission } from 'src/enum';
import { Authenticated } from 'src/middleware/auth.guard';
import { PluginService } from 'src/services/plugin.service';
import { UUIDParamDto } from 'src/validation';
@ApiTags('Plugins')
@Controller('plugins')
export class PluginController {
constructor(private service: PluginService) {}
@Get('triggers')
@Authenticated({ permission: Permission.PluginRead })
@Endpoint({
summary: 'List all plugin triggers',
description: 'Retrieve a list of all available plugin triggers.',
history: new HistoryBuilder().added('v2.3.0').alpha('v2.3.0'),
})
getPluginTriggers(): PluginTriggerResponseDto[] {
return this.service.getTriggers();
}
@Get()
@Authenticated({ permission: Permission.PluginRead })
@Endpoint({
summary: 'List all plugins',
description: 'Retrieve a list of plugins available to the authenticated user.',
history: new HistoryBuilder().added('v2.3.0').alpha('v2.3.0'),
})
getPlugins(): Promise<PluginResponseDto[]> {
return this.service.getAll();
}
@Get(':id')
@Authenticated({ permission: Permission.PluginRead })
@Endpoint({
summary: 'Retrieve a plugin',
description: 'Retrieve information about a specific plugin by its ID.',
history: new HistoryBuilder().added('v2.3.0').alpha('v2.3.0'),
})
getPlugin(@Param() { id }: UUIDParamDto): Promise<PluginResponseDto> {
return this.service.get(id);
}
}
@@ -0,0 +1,85 @@
import { Body, Controller, Delete, Get, HttpCode, HttpStatus, Param, Put, Query } from '@nestjs/common';
import { ApiTags } from '@nestjs/swagger';
import { Endpoint, HistoryBuilder } from 'src/decorators';
import { AuthDto } from 'src/dtos/auth.dto';
import {
QueueDeleteDto,
QueueJobResponseDto,
QueueJobSearchDto,
QueueNameParamDto,
QueueResponseDto,
QueueUpdateDto,
} from 'src/dtos/queue.dto';
import { ApiTag, Permission } from 'src/enum';
import { Auth, Authenticated } from 'src/middleware/auth.guard';
import { QueueService } from 'src/services/queue.service';
@ApiTags(ApiTag.Queues)
@Controller('queues')
export class QueueController {
constructor(private service: QueueService) {}
@Get()
@Authenticated({ permission: Permission.QueueRead, admin: true })
@Endpoint({
summary: 'List all queues',
description: 'Retrieves a list of queues.',
history: new HistoryBuilder().added('v2.4.0').alpha('v2.4.0'),
})
getQueues(@Auth() auth: AuthDto): Promise<QueueResponseDto[]> {
return this.service.getAll(auth);
}
@Get(':name')
@Authenticated({ permission: Permission.QueueRead, admin: true })
@Endpoint({
summary: 'Retrieve a queue',
description: 'Retrieves a specific queue by its name.',
history: new HistoryBuilder().added('v2.4.0').alpha('v2.4.0'),
})
getQueue(@Auth() auth: AuthDto, @Param() { name }: QueueNameParamDto): Promise<QueueResponseDto> {
return this.service.get(auth, name);
}
@Put(':name')
@Authenticated({ permission: Permission.QueueUpdate, admin: true })
@Endpoint({
summary: 'Update a queue',
description: 'Change the paused status of a specific queue.',
history: new HistoryBuilder().added('v2.4.0').alpha('v2.4.0'),
})
updateQueue(
@Auth() auth: AuthDto,
@Param() { name }: QueueNameParamDto,
@Body() dto: QueueUpdateDto,
): Promise<QueueResponseDto> {
return this.service.update(auth, name, dto);
}
@Get(':name/jobs')
@Authenticated({ permission: Permission.QueueJobRead, admin: true })
@Endpoint({
summary: 'Retrieve queue jobs',
description: 'Retrieves a list of queue jobs from the specified queue.',
history: new HistoryBuilder().added('v2.4.0').alpha('v2.4.0'),
})
getQueueJobs(
@Auth() auth: AuthDto,
@Param() { name }: QueueNameParamDto,
@Query() dto: QueueJobSearchDto,
): Promise<QueueJobResponseDto[]> {
return this.service.searchJobs(auth, name, dto);
}
@Delete(':name/jobs')
@Authenticated({ permission: Permission.QueueJobDelete, admin: true })
@HttpCode(HttpStatus.NO_CONTENT)
@Endpoint({
summary: 'Empty a queue',
description: 'Removes all jobs from the specified queue.',
history: new HistoryBuilder().added('v2.4.0').alpha('v2.4.0'),
})
emptyQueue(@Auth() auth: AuthDto, @Param() { name }: QueueNameParamDto, @Body() dto: QueueDeleteDto): Promise<void> {
return this.service.emptyQueue(auth, name, dto);
}
}
+55 -2
View File
@@ -1,5 +1,6 @@
import { Body, Controller, Get, HttpCode, HttpStatus, Post, Query } from '@nestjs/common';
import { ApiTags } from '@nestjs/swagger';
import { Endpoint, HistoryBuilder } from 'src/decorators';
import { AssetResponseDto } from 'src/dtos/asset-response.dto';
import { AuthDto } from 'src/dtos/auth.dto';
import { PersonResponseDto } from 'src/dtos/person.dto';
@@ -17,11 +18,11 @@ import {
SmartSearchDto,
StatisticsSearchDto,
} from 'src/dtos/search.dto';
import { Permission } from 'src/enum';
import { ApiTag, Permission } from 'src/enum';
import { Auth, Authenticated } from 'src/middleware/auth.guard';
import { SearchService } from 'src/services/search.service';
@ApiTags('Search')
@ApiTags(ApiTag.Search)
@Controller('search')
export class SearchController {
constructor(private service: SearchService) {}
@@ -29,6 +30,11 @@ export class SearchController {
@Post('metadata')
@Authenticated({ permission: Permission.AssetRead })
@HttpCode(HttpStatus.OK)
@Endpoint({
summary: 'Search assets by metadata',
description: 'Search for assets based on various metadata criteria.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
searchAssets(@Auth() auth: AuthDto, @Body() dto: MetadataSearchDto): Promise<SearchResponseDto> {
return this.service.searchMetadata(auth, dto);
}
@@ -36,6 +42,11 @@ export class SearchController {
@Post('statistics')
@Authenticated({ permission: Permission.AssetStatistics })
@HttpCode(HttpStatus.OK)
@Endpoint({
summary: 'Search asset statistics',
description: 'Retrieve statistical data about assets based on search criteria, such as the total matching count.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
searchAssetStatistics(@Auth() auth: AuthDto, @Body() dto: StatisticsSearchDto): Promise<SearchStatisticsResponseDto> {
return this.service.searchStatistics(auth, dto);
}
@@ -43,6 +54,11 @@ export class SearchController {
@Post('random')
@Authenticated({ permission: Permission.AssetRead })
@HttpCode(HttpStatus.OK)
@Endpoint({
summary: 'Search random assets',
description: 'Retrieve a random selection of assets based on the provided criteria.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
searchRandom(@Auth() auth: AuthDto, @Body() dto: RandomSearchDto): Promise<AssetResponseDto[]> {
return this.service.searchRandom(auth, dto);
}
@@ -50,6 +66,11 @@ export class SearchController {
@Post('large-assets')
@Authenticated({ permission: Permission.AssetRead })
@HttpCode(HttpStatus.OK)
@Endpoint({
summary: 'Search large assets',
description: 'Search for assets that are considered large based on specified criteria.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
searchLargeAssets(@Auth() auth: AuthDto, @Query() dto: LargeAssetSearchDto): Promise<AssetResponseDto[]> {
return this.service.searchLargeAssets(auth, dto);
}
@@ -57,36 +78,68 @@ export class SearchController {
@Post('smart')
@Authenticated({ permission: Permission.AssetRead })
@HttpCode(HttpStatus.OK)
@Endpoint({
summary: 'Smart asset search',
description: 'Perform a smart search for assets by using machine learning vectors to determine relevance.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
searchSmart(@Auth() auth: AuthDto, @Body() dto: SmartSearchDto): Promise<SearchResponseDto> {
return this.service.searchSmart(auth, dto);
}
@Get('explore')
@Authenticated({ permission: Permission.AssetRead })
@Endpoint({
summary: 'Retrieve explore data',
description: 'Retrieve data for the explore section, such as popular people and places.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
getExploreData(@Auth() auth: AuthDto): Promise<SearchExploreResponseDto[]> {
return this.service.getExploreData(auth);
}
@Get('person')
@Authenticated({ permission: Permission.PersonRead })
@Endpoint({
summary: 'Search people',
description: 'Search for people by name.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
searchPerson(@Auth() auth: AuthDto, @Query() dto: SearchPeopleDto): Promise<PersonResponseDto[]> {
return this.service.searchPerson(auth, dto);
}
@Get('places')
@Authenticated({ permission: Permission.AssetRead })
@Endpoint({
summary: 'Search places',
description: 'Search for places by name.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
searchPlaces(@Query() dto: SearchPlacesDto): Promise<PlacesResponseDto[]> {
return this.service.searchPlaces(dto);
}
@Get('cities')
@Authenticated({ permission: Permission.AssetRead })
@Endpoint({
summary: 'Retrieve assets by city',
description:
'Retrieve a list of assets with each asset belonging to a different city. This endpoint is used on the places pages to show a single thumbnail for each city the user has assets in.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
getAssetsByCity(@Auth() auth: AuthDto): Promise<AssetResponseDto[]> {
return this.service.getAssetsByCity(auth);
}
@Get('suggestions')
@Authenticated({ permission: Permission.AssetRead })
@Endpoint({
summary: 'Retrieve search suggestions',
description:
'Retrieve search suggestions based on partial input. This endpoint is used for typeahead search features.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
getSearchSuggestions(@Auth() auth: AuthDto, @Query() dto: SearchSuggestionRequestDto): Promise<string[]> {
// TODO fix open api generation to indicate that results can be nullable
return this.service.getSearchSuggestions(auth, dto) as Promise<string[]>;
+78 -2
View File
@@ -1,5 +1,6 @@
import { Body, Controller, Delete, Get, HttpCode, HttpStatus, Put } from '@nestjs/common';
import { ApiNotFoundResponse, ApiTags } from '@nestjs/swagger';
import { Endpoint, HistoryBuilder } from 'src/decorators';
import { LicenseKeyDto, LicenseResponseDto } from 'src/dtos/license.dto';
import {
ServerAboutResponseDto,
@@ -15,13 +16,13 @@ import {
ServerVersionResponseDto,
} from 'src/dtos/server.dto';
import { VersionCheckStateResponseDto } from 'src/dtos/system-metadata.dto';
import { Permission } from 'src/enum';
import { ApiTag, Permission } from 'src/enum';
import { Authenticated } from 'src/middleware/auth.guard';
import { ServerService } from 'src/services/server.service';
import { SystemMetadataService } from 'src/services/system-metadata.service';
import { VersionService } from 'src/services/version.service';
@ApiTags('Server')
@ApiTags(ApiTag.Server)
@Controller('server')
export class ServerController {
constructor(
@@ -32,59 +33,114 @@ export class ServerController {
@Get('about')
@Authenticated({ permission: Permission.ServerAbout })
@Endpoint({
summary: 'Get server information',
description: 'Retrieve a list of information about the server.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
getAboutInfo(): Promise<ServerAboutResponseDto> {
return this.service.getAboutInfo();
}
@Get('apk-links')
@Authenticated({ permission: Permission.ServerApkLinks })
@Endpoint({
summary: 'Get APK links',
description: 'Retrieve links to the APKs for the current server version.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
getApkLinks(): ServerApkLinksDto {
return this.service.getApkLinks();
}
@Get('storage')
@Authenticated({ permission: Permission.ServerStorage })
@Endpoint({
summary: 'Get storage',
description: 'Retrieve the current storage utilization information of the server.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
getStorage(): Promise<ServerStorageResponseDto> {
return this.service.getStorage();
}
@Get('ping')
@Endpoint({
summary: 'Ping',
description: 'Pong',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
pingServer(): ServerPingResponse {
return this.service.ping();
}
@Get('version')
@Endpoint({
summary: 'Get server version',
description: 'Retrieve the current server version in semantic versioning (semver) format.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
getServerVersion(): ServerVersionResponseDto {
return this.versionService.getVersion();
}
@Get('version-history')
@Endpoint({
summary: 'Get version history',
description: 'Retrieve a list of past versions the server has been on.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
getVersionHistory(): Promise<ServerVersionHistoryResponseDto[]> {
return this.versionService.getVersionHistory();
}
@Get('features')
@Endpoint({
summary: 'Get features',
description: 'Retrieve available features supported by this server.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
getServerFeatures(): Promise<ServerFeaturesDto> {
return this.service.getFeatures();
}
@Get('theme')
@Endpoint({
summary: 'Get theme',
description: 'Retrieve the custom CSS, if existent.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
getTheme(): Promise<ServerThemeDto> {
return this.service.getTheme();
}
@Get('config')
@Endpoint({
summary: 'Get config',
description: 'Retrieve the current server configuration.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
getServerConfig(): Promise<ServerConfigDto> {
return this.service.getSystemConfig();
}
@Get('statistics')
@Authenticated({ permission: Permission.ServerStatistics, admin: true })
@Endpoint({
summary: 'Get statistics',
description: 'Retrieve statistics about the entire Immich instance such as asset counts.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
getServerStatistics(): Promise<ServerStatsResponseDto> {
return this.service.getStatistics();
}
@Get('media-types')
@Endpoint({
summary: 'Get supported media types',
description: 'Retrieve all media types supported by the server.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
getSupportedMediaTypes(): ServerMediaTypesResponseDto {
return this.service.getSupportedMediaTypes();
}
@@ -92,12 +148,22 @@ export class ServerController {
@Get('license')
@Authenticated({ permission: Permission.ServerLicenseRead, admin: true })
@ApiNotFoundResponse()
@Endpoint({
summary: 'Get product key',
description: 'Retrieve information about whether the server currently has a product key registered.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
getServerLicense(): Promise<LicenseResponseDto> {
return this.service.getLicense();
}
@Put('license')
@Authenticated({ permission: Permission.ServerLicenseUpdate, admin: true })
@Endpoint({
summary: 'Set server product key',
description: 'Validate and set the server product key if successful.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
setServerLicense(@Body() license: LicenseKeyDto): Promise<LicenseResponseDto> {
return this.service.setLicense(license);
}
@@ -105,12 +171,22 @@ export class ServerController {
@Delete('license')
@Authenticated({ permission: Permission.ServerLicenseDelete, admin: true })
@HttpCode(HttpStatus.NO_CONTENT)
@Endpoint({
summary: 'Delete server product key',
description: 'Delete the currently set server product key.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
deleteServerLicense(): Promise<void> {
return this.service.deleteLicense();
}
@Get('version-check')
@Authenticated({ permission: Permission.ServerVersionCheck })
@Endpoint({
summary: 'Get version check status',
description: 'Retrieve information about the last time the version check ran.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
getVersionCheck(): Promise<VersionCheckStateResponseDto> {
return this.systemMetadataService.getVersionCheckState();
}
+33 -2
View File
@@ -1,25 +1,36 @@
import { Body, Controller, Delete, Get, HttpCode, HttpStatus, Param, Post, Put } from '@nestjs/common';
import { ApiTags } from '@nestjs/swagger';
import { Endpoint, HistoryBuilder } from 'src/decorators';
import { AuthDto } from 'src/dtos/auth.dto';
import { SessionCreateDto, SessionCreateResponseDto, SessionResponseDto, SessionUpdateDto } from 'src/dtos/session.dto';
import { Permission } from 'src/enum';
import { ApiTag, Permission } from 'src/enum';
import { Auth, Authenticated } from 'src/middleware/auth.guard';
import { SessionService } from 'src/services/session.service';
import { UUIDParamDto } from 'src/validation';
@ApiTags('Sessions')
@ApiTags(ApiTag.Sessions)
@Controller('sessions')
export class SessionController {
constructor(private service: SessionService) {}
@Post()
@Authenticated({ permission: Permission.SessionCreate })
@Endpoint({
summary: 'Create a session',
description: 'Create a session as a child to the current session. This endpoint is used for casting.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
createSession(@Auth() auth: AuthDto, @Body() dto: SessionCreateDto): Promise<SessionCreateResponseDto> {
return this.service.create(auth, dto);
}
@Get()
@Authenticated({ permission: Permission.SessionRead })
@Endpoint({
summary: 'Retrieve sessions',
description: 'Retrieve a list of sessions for the user.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
getSessions(@Auth() auth: AuthDto): Promise<SessionResponseDto[]> {
return this.service.getAll(auth);
}
@@ -27,12 +38,22 @@ export class SessionController {
@Delete()
@Authenticated({ permission: Permission.SessionDelete })
@HttpCode(HttpStatus.NO_CONTENT)
@Endpoint({
summary: 'Delete all sessions',
description: 'Delete all sessions for the user. This will not delete the current session.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
deleteAllSessions(@Auth() auth: AuthDto): Promise<void> {
return this.service.deleteAll(auth);
}
@Put(':id')
@Authenticated({ permission: Permission.SessionUpdate })
@Endpoint({
summary: 'Update a session',
description: 'Update a specific session identified by id.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
updateSession(
@Auth() auth: AuthDto,
@Param() { id }: UUIDParamDto,
@@ -44,6 +65,11 @@ export class SessionController {
@Delete(':id')
@Authenticated({ permission: Permission.SessionDelete })
@HttpCode(HttpStatus.NO_CONTENT)
@Endpoint({
summary: 'Delete a session',
description: 'Delete a specific session by id.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
deleteSession(@Auth() auth: AuthDto, @Param() { id }: UUIDParamDto): Promise<void> {
return this.service.delete(auth, id);
}
@@ -51,6 +77,11 @@ export class SessionController {
@Post(':id/lock')
@Authenticated({ permission: Permission.SessionLock })
@HttpCode(HttpStatus.NO_CONTENT)
@Endpoint({
summary: 'Lock a session',
description: 'Lock a specific session by id.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
lockSession(@Auth() auth: AuthDto, @Param() { id }: UUIDParamDto): Promise<void> {
return this.service.lock(auth, id);
}
@@ -0,0 +1,47 @@
import { SharedLinkController } from 'src/controllers/shared-link.controller';
import { Permission, SharedLinkType } from 'src/enum';
import { SharedLinkService } from 'src/services/shared-link.service';
import request from 'supertest';
import { factory } from 'test/small.factory';
import { ControllerContext, controllerSetup, mockBaseService } from 'test/utils';
describe(SharedLinkController.name, () => {
let ctx: ControllerContext;
const service = mockBaseService(SharedLinkService);
beforeAll(async () => {
ctx = await controllerSetup(SharedLinkController, [{ provide: SharedLinkService, useValue: service }]);
return () => ctx.close();
});
beforeEach(() => {
service.resetAllMocks();
ctx.reset();
});
describe('POST /shared-links', () => {
it('should be an authenticated route', async () => {
await request(ctx.getHttpServer()).post('/shared-links');
expect(ctx.authenticate).toHaveBeenCalled();
});
it('should allow an null expiresAt', async () => {
await request(ctx.getHttpServer())
.post('/shared-links')
.send({ expiresAt: null, type: SharedLinkType.Individual });
expect(service.create).toHaveBeenCalledWith(undefined, expect.objectContaining({ expiresAt: null }));
});
});
describe('DELETE /shared-links/:id/assets', () => {
it('should require shared link update permission', async () => {
await request(ctx.getHttpServer()).delete(`/shared-links/${factory.uuid()}/assets`).send({ assetIds: [] });
expect(ctx.authenticate).toHaveBeenCalledWith(
expect.objectContaining({
metadata: expect.objectContaining({ permission: Permission.SharedLinkUpdate, sharedLinkRoute: false }),
}),
);
});
});
});
@@ -15,68 +15,134 @@ import {
} from '@nestjs/common';
import { ApiTags } from '@nestjs/swagger';
import { Request, Response } from 'express';
import { Endpoint, HistoryBuilder } from 'src/decorators';
import { AssetIdsResponseDto } from 'src/dtos/asset-ids.response.dto';
import { AssetIdsDto } from 'src/dtos/asset.dto';
import { AuthDto } from 'src/dtos/auth.dto';
import {
SharedLinkCreateDto,
SharedLinkEditDto,
SharedLinkLoginDto,
SharedLinkPasswordDto,
SharedLinkResponseDto,
SharedLinkSearchDto,
} from 'src/dtos/shared-link.dto';
import { ImmichCookie, Permission } from 'src/enum';
import { ApiTag, ImmichCookie, Permission } from 'src/enum';
import { Auth, Authenticated, GetLoginDetails } from 'src/middleware/auth.guard';
import { LoggingRepository } from 'src/repositories/logging.repository';
import { LoginDetails } from 'src/services/auth.service';
import { SharedLinkService } from 'src/services/shared-link.service';
import { respondWithCookie } from 'src/utils/response';
import { UUIDParamDto } from 'src/validation';
@ApiTags('Shared Links')
const getAuthTokens = (cookies: Record<string, string> | undefined) => {
return cookies?.[ImmichCookie.SharedLinkToken]?.split(',') || [];
};
const merge = (cookies: Record<string, string> | undefined, token: string) => {
const authTokens = getAuthTokens(cookies);
if (!authTokens.includes(token)) {
authTokens.push(token);
}
return authTokens.join(',');
};
@ApiTags(ApiTag.SharedLinks)
@Controller('shared-links')
export class SharedLinkController {
constructor(private service: SharedLinkService) {}
constructor(
private service: SharedLinkService,
private logger: LoggingRepository,
) {}
@Get()
@Authenticated({ permission: Permission.SharedLinkRead })
@Endpoint({
summary: 'Retrieve all shared links',
description: 'Retrieve a list of all shared links.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
getAllSharedLinks(@Auth() auth: AuthDto, @Query() dto: SharedLinkSearchDto): Promise<SharedLinkResponseDto[]> {
return this.service.getAll(auth, dto);
}
@Get('me')
@Post('login')
@Authenticated({ sharedLink: true })
async getMySharedLink(
@Endpoint({
summary: 'Shared link login',
description: 'Login to a password protected shared link',
history: new HistoryBuilder().added('v2.6.0').beta('v2.6.0'),
})
async sharedLinkLogin(
@Auth() auth: AuthDto,
@Query() dto: SharedLinkPasswordDto,
@Req() request: Request,
@Body() dto: SharedLinkLoginDto,
@Req() req: Request,
@Res({ passthrough: true }) res: Response,
@GetLoginDetails() loginDetails: LoginDetails,
): Promise<SharedLinkResponseDto> {
const sharedLinkToken = request.cookies?.[ImmichCookie.SharedLinkToken];
if (sharedLinkToken) {
dto.token = sharedLinkToken;
}
const body = await this.service.getMine(auth, dto);
return respondWithCookie(res, body, {
const { sharedLink, token } = await this.service.login(auth, dto);
return respondWithCookie(res, sharedLink, {
isSecure: loginDetails.isSecure,
values: body.token ? [{ key: ImmichCookie.SharedLinkToken, value: body.token }] : [],
values: [{ key: ImmichCookie.SharedLinkToken, value: merge(req.cookies, token) }],
});
}
@Get('me')
@Authenticated({ sharedLink: true })
@Endpoint({
summary: 'Retrieve current shared link',
description: 'Retrieve the current shared link associated with authentication method.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
async getMySharedLink(
@Auth() auth: AuthDto,
@Query() dto: SharedLinkPasswordDto,
@Req() req: Request,
@Res({ passthrough: true }) res: Response,
@GetLoginDetails() loginDetails: LoginDetails,
): Promise<SharedLinkResponseDto> {
if (dto.password) {
this.logger.deprecate(
'Passing shared link password via query parameters is deprecated and will be removed in the next major release. Please use POST /shared-links/login instead.',
);
return this.sharedLinkLogin(auth, { password: dto.password }, req, res, loginDetails);
}
return this.service.getMine(auth, getAuthTokens(req.cookies));
}
@Get(':id')
@Authenticated({ permission: Permission.SharedLinkRead })
@Endpoint({
summary: 'Retrieve a shared link',
description: 'Retrieve a specific shared link by its ID.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
getSharedLinkById(@Auth() auth: AuthDto, @Param() { id }: UUIDParamDto): Promise<SharedLinkResponseDto> {
return this.service.get(auth, id);
}
@Post()
@Authenticated({ permission: Permission.SharedLinkCreate })
@Endpoint({
summary: 'Create a shared link',
description: 'Create a new shared link.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
createSharedLink(@Auth() auth: AuthDto, @Body() dto: SharedLinkCreateDto) {
return this.service.create(auth, dto);
}
@Patch(':id')
@Authenticated({ permission: Permission.SharedLinkUpdate })
@Endpoint({
summary: 'Update a shared link',
description: 'Update an existing shared link by its ID.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
updateSharedLink(
@Auth() auth: AuthDto,
@Param() { id }: UUIDParamDto,
@@ -88,12 +154,23 @@ export class SharedLinkController {
@Delete(':id')
@Authenticated({ permission: Permission.SharedLinkDelete })
@HttpCode(HttpStatus.NO_CONTENT)
@Endpoint({
summary: 'Delete a shared link',
description: 'Delete a specific shared link by its ID.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
removeSharedLink(@Auth() auth: AuthDto, @Param() { id }: UUIDParamDto): Promise<void> {
return this.service.remove(auth, id);
}
@Put(':id/assets')
@Authenticated({ sharedLink: true })
@Endpoint({
summary: 'Add assets to a shared link',
description:
'Add assets to a specific shared link by its ID. This endpoint is only relevant for shared link of type individual.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
addSharedLinkAssets(
@Auth() auth: AuthDto,
@Param() { id }: UUIDParamDto,
@@ -103,7 +180,13 @@ export class SharedLinkController {
}
@Delete(':id/assets')
@Authenticated({ sharedLink: true })
@Authenticated({ permission: Permission.SharedLinkUpdate })
@Endpoint({
summary: 'Remove assets from a shared link',
description:
'Remove assets from a specific shared link by its ID. This endpoint is only relevant for shared link of type individual.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
removeSharedLinkAssets(
@Auth() auth: AuthDto,
@Param() { id }: UUIDParamDto,
+39 -2
View File
@@ -1,26 +1,38 @@
import { Body, Controller, Delete, Get, HttpCode, HttpStatus, Param, Post, Put, Query } from '@nestjs/common';
import { ApiTags } from '@nestjs/swagger';
import { Endpoint, HistoryBuilder } from 'src/decorators';
import { BulkIdsDto } from 'src/dtos/asset-ids.response.dto';
import { AuthDto } from 'src/dtos/auth.dto';
import { StackCreateDto, StackResponseDto, StackSearchDto, StackUpdateDto } from 'src/dtos/stack.dto';
import { Permission } from 'src/enum';
import { ApiTag, Permission } from 'src/enum';
import { Auth, Authenticated } from 'src/middleware/auth.guard';
import { StackService } from 'src/services/stack.service';
import { UUIDAssetIDParamDto, UUIDParamDto } from 'src/validation';
@ApiTags('Stacks')
@ApiTags(ApiTag.Stacks)
@Controller('stacks')
export class StackController {
constructor(private service: StackService) {}
@Get()
@Authenticated({ permission: Permission.StackRead })
@Endpoint({
summary: 'Retrieve stacks',
description: 'Retrieve a list of stacks.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
searchStacks(@Auth() auth: AuthDto, @Query() query: StackSearchDto): Promise<StackResponseDto[]> {
return this.service.search(auth, query);
}
@Post()
@Authenticated({ permission: Permission.StackCreate })
@Endpoint({
summary: 'Create a stack',
description:
'Create a new stack by providing a name and a list of asset IDs to include in the stack. If any of the provided asset IDs are primary assets of an existing stack, the existing stack will be merged into the newly created stack.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
createStack(@Auth() auth: AuthDto, @Body() dto: StackCreateDto): Promise<StackResponseDto> {
return this.service.create(auth, dto);
}
@@ -28,18 +40,33 @@ export class StackController {
@Delete()
@Authenticated({ permission: Permission.StackDelete })
@HttpCode(HttpStatus.NO_CONTENT)
@Endpoint({
summary: 'Delete stacks',
description: 'Delete multiple stacks by providing a list of stack IDs.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
deleteStacks(@Auth() auth: AuthDto, @Body() dto: BulkIdsDto): Promise<void> {
return this.service.deleteAll(auth, dto);
}
@Get(':id')
@Authenticated({ permission: Permission.StackRead })
@Endpoint({
summary: 'Retrieve a stack',
description: 'Retrieve a specific stack by its ID.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
getStack(@Auth() auth: AuthDto, @Param() { id }: UUIDParamDto): Promise<StackResponseDto> {
return this.service.get(auth, id);
}
@Put(':id')
@Authenticated({ permission: Permission.StackUpdate })
@Endpoint({
summary: 'Update a stack',
description: 'Update an existing stack by its ID.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
updateStack(
@Auth() auth: AuthDto,
@Param() { id }: UUIDParamDto,
@@ -51,6 +78,11 @@ export class StackController {
@Delete(':id')
@Authenticated({ permission: Permission.StackDelete })
@HttpCode(HttpStatus.NO_CONTENT)
@Endpoint({
summary: 'Delete a stack',
description: 'Delete a specific stack by its ID.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
deleteStack(@Auth() auth: AuthDto, @Param() { id }: UUIDParamDto): Promise<void> {
return this.service.delete(auth, id);
}
@@ -58,6 +90,11 @@ export class StackController {
@Delete(':id/assets/:assetId')
@Authenticated({ permission: Permission.StackUpdate })
@HttpCode(HttpStatus.NO_CONTENT)
@Endpoint({
summary: 'Remove an asset from a stack',
description: 'Remove a specific asset from a stack by providing the stack ID and asset ID.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
removeAssetFromStack(@Auth() auth: AuthDto, @Param() dto: UUIDAssetIDParamDto): Promise<void> {
return this.service.removeAsset(auth, dto);
}
+35 -2
View File
@@ -1,6 +1,7 @@
import { Body, Controller, Delete, Get, Header, HttpCode, HttpStatus, Post, Res } from '@nestjs/common';
import { ApiTags } from '@nestjs/swagger';
import { Response } from 'express';
import { Endpoint, HistoryBuilder } from 'src/decorators';
import { AssetResponseDto } from 'src/dtos/asset-response.dto';
import { AuthDto } from 'src/dtos/auth.dto';
import {
@@ -12,12 +13,12 @@ import {
SyncAckSetDto,
SyncStreamDto,
} from 'src/dtos/sync.dto';
import { Permission } from 'src/enum';
import { ApiTag, Permission } from 'src/enum';
import { Auth, Authenticated } from 'src/middleware/auth.guard';
import { GlobalExceptionFilter } from 'src/middleware/global-exception.filter';
import { SyncService } from 'src/services/sync.service';
@ApiTags('Sync')
@ApiTags(ApiTag.Sync)
@Controller('sync')
export class SyncController {
constructor(
@@ -28,6 +29,11 @@ export class SyncController {
@Post('full-sync')
@Authenticated()
@HttpCode(HttpStatus.OK)
@Endpoint({
summary: 'Get full sync for user',
description: 'Retrieve all assets for a full synchronization for the authenticated user.',
history: new HistoryBuilder().added('v1').deprecated('v2'),
})
getFullSyncForUser(@Auth() auth: AuthDto, @Body() dto: AssetFullSyncDto): Promise<AssetResponseDto[]> {
return this.service.getFullSync(auth, dto);
}
@@ -35,6 +41,11 @@ export class SyncController {
@Post('delta-sync')
@Authenticated()
@HttpCode(HttpStatus.OK)
@Endpoint({
summary: 'Get delta sync for user',
description: 'Retrieve changed assets since the last sync for the authenticated user.',
history: new HistoryBuilder().added('v1').deprecated('v2'),
})
getDeltaSync(@Auth() auth: AuthDto, @Body() dto: AssetDeltaSyncDto): Promise<AssetDeltaSyncResponseDto> {
return this.service.getDeltaSync(auth, dto);
}
@@ -43,6 +54,12 @@ export class SyncController {
@Authenticated({ permission: Permission.SyncStream })
@Header('Content-Type', 'application/jsonlines+json')
@HttpCode(HttpStatus.OK)
@Endpoint({
summary: 'Stream sync changes',
description:
'Retrieve a JSON lines streamed response of changes for synchronization. This endpoint is used by the mobile app to efficiently stay up to date with changes.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
async getSyncStream(@Auth() auth: AuthDto, @Res() res: Response, @Body() dto: SyncStreamDto) {
try {
await this.service.stream(auth, res, dto);
@@ -54,6 +71,11 @@ export class SyncController {
@Get('ack')
@Authenticated({ permission: Permission.SyncCheckpointRead })
@Endpoint({
summary: 'Retrieve acknowledgements',
description: 'Retrieve the synchronization acknowledgments for the current session.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
getSyncAck(@Auth() auth: AuthDto): Promise<SyncAckDto[]> {
return this.service.getAcks(auth);
}
@@ -61,6 +83,12 @@ export class SyncController {
@Post('ack')
@Authenticated({ permission: Permission.SyncCheckpointUpdate })
@HttpCode(HttpStatus.NO_CONTENT)
@Endpoint({
summary: 'Acknowledge changes',
description:
'Send a list of synchronization acknowledgements to confirm that the latest changes have been received.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
sendSyncAck(@Auth() auth: AuthDto, @Body() dto: SyncAckSetDto) {
return this.service.setAcks(auth, dto);
}
@@ -68,6 +96,11 @@ export class SyncController {
@Delete('ack')
@Authenticated({ permission: Permission.SyncCheckpointDelete })
@HttpCode(HttpStatus.NO_CONTENT)
@Endpoint({
summary: 'Delete acknowledgements',
description: 'Delete specific synchronization acknowledgments.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
deleteSyncAck(@Auth() auth: AuthDto, @Body() dto: SyncAckDeleteDto): Promise<void> {
return this.service.deleteAcks(auth, dto);
}
@@ -70,5 +70,33 @@ describe(SystemConfigController.name, () => {
expect(body).toEqual(errorDto.badRequest(['nightlyTasks.databaseCleanup must be a boolean value']));
});
});
describe('image', () => {
it('should accept config without optional progressive property', async () => {
const config = _.cloneDeep(defaults);
delete config.image.thumbnail.progressive;
delete config.image.preview.progressive;
delete config.image.fullsize.progressive;
const { status } = await request(ctx.getHttpServer()).put('/system-config').send(config);
expect(status).toBe(200);
});
it('should accept config with progressive set to true', async () => {
const config = _.cloneDeep(defaults);
config.image.thumbnail.progressive = true;
config.image.preview.progressive = true;
config.image.fullsize.progressive = true;
const { status } = await request(ctx.getHttpServer()).put('/system-config').send(config);
expect(status).toBe(200);
});
it('should reject invalid progressive value', async () => {
const config = _.cloneDeep(defaults);
(config.image.thumbnail.progressive as any) = 'invalid';
const { status, body } = await request(ctx.getHttpServer()).put('/system-config').send(config);
expect(status).toBe(400);
expect(body).toEqual(errorDto.badRequest(['image.thumbnail.progressive must be a boolean value']));
});
});
});
});
@@ -1,12 +1,13 @@
import { Body, Controller, Get, Put } from '@nestjs/common';
import { ApiTags } from '@nestjs/swagger';
import { Endpoint, HistoryBuilder } from 'src/decorators';
import { SystemConfigDto, SystemConfigTemplateStorageOptionDto } from 'src/dtos/system-config.dto';
import { Permission } from 'src/enum';
import { ApiTag, Permission } from 'src/enum';
import { Authenticated } from 'src/middleware/auth.guard';
import { StorageTemplateService } from 'src/services/storage-template.service';
import { SystemConfigService } from 'src/services/system-config.service';
@ApiTags('System Config')
@ApiTags(ApiTag.SystemConfig)
@Controller('system-config')
export class SystemConfigController {
constructor(
@@ -16,24 +17,44 @@ export class SystemConfigController {
@Get()
@Authenticated({ permission: Permission.SystemConfigRead, admin: true })
@Endpoint({
summary: 'Get system configuration',
description: 'Retrieve the current system configuration.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
getConfig(): Promise<SystemConfigDto> {
return this.service.getSystemConfig();
}
@Get('defaults')
@Authenticated({ permission: Permission.SystemConfigRead, admin: true })
@Endpoint({
summary: 'Get system configuration defaults',
description: 'Retrieve the default values for the system configuration.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
getConfigDefaults(): SystemConfigDto {
return this.service.getDefaults();
}
@Put()
@Authenticated({ permission: Permission.SystemConfigUpdate, admin: true })
@Endpoint({
summary: 'Update system configuration',
description: 'Update the system configuration with a new system configuration.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
updateConfig(@Body() dto: SystemConfigDto): Promise<SystemConfigDto> {
return this.service.updateSystemConfig(dto);
}
@Get('storage-template-options')
@Authenticated({ permission: Permission.SystemConfigRead, admin: true })
@Endpoint({
summary: 'Get storage template options',
description: 'Retrieve exemplary storage template options.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
getStorageTemplateOptions(): SystemConfigTemplateStorageOptionDto {
return this.storageTemplateService.getStorageTemplateOptions();
}
@@ -1,21 +1,27 @@
import { Body, Controller, Get, HttpCode, HttpStatus, Post } from '@nestjs/common';
import { ApiTags } from '@nestjs/swagger';
import { Endpoint, HistoryBuilder } from 'src/decorators';
import {
AdminOnboardingUpdateDto,
ReverseGeocodingStateResponseDto,
VersionCheckStateResponseDto,
} from 'src/dtos/system-metadata.dto';
import { Permission } from 'src/enum';
import { ApiTag, Permission } from 'src/enum';
import { Authenticated } from 'src/middleware/auth.guard';
import { SystemMetadataService } from 'src/services/system-metadata.service';
@ApiTags('System Metadata')
@ApiTags(ApiTag.SystemMetadata)
@Controller('system-metadata')
export class SystemMetadataController {
constructor(private service: SystemMetadataService) {}
@Get('admin-onboarding')
@Authenticated({ permission: Permission.SystemMetadataRead, admin: true })
@Endpoint({
summary: 'Retrieve admin onboarding',
description: 'Retrieve the current admin onboarding status.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
getAdminOnboarding(): Promise<AdminOnboardingUpdateDto> {
return this.service.getAdminOnboarding();
}
@@ -23,18 +29,33 @@ export class SystemMetadataController {
@Post('admin-onboarding')
@Authenticated({ permission: Permission.SystemMetadataUpdate, admin: true })
@HttpCode(HttpStatus.NO_CONTENT)
@Endpoint({
summary: 'Update admin onboarding',
description: 'Update the admin onboarding status.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
updateAdminOnboarding(@Body() dto: AdminOnboardingUpdateDto): Promise<void> {
return this.service.updateAdminOnboarding(dto);
}
@Get('reverse-geocoding-state')
@Authenticated({ permission: Permission.SystemMetadataRead, admin: true })
@Endpoint({
summary: 'Retrieve reverse geocoding state',
description: 'Retrieve the current state of the reverse geocoding import.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
getReverseGeocodingState(): Promise<ReverseGeocodingStateResponseDto> {
return this.service.getReverseGeocodingState();
}
@Get('version-check-state')
@Authenticated({ permission: Permission.SystemMetadataRead, admin: true })
@Endpoint({
summary: 'Retrieve version check state',
description: 'Retrieve the current state of the version check process.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
getVersionCheckState(): Promise<VersionCheckStateResponseDto> {
return this.service.getVersionCheckState();
}
@@ -0,0 +1,73 @@
import { TagController } from 'src/controllers/tag.controller';
import { TagService } from 'src/services/tag.service';
import request from 'supertest';
import { errorDto } from 'test/medium/responses';
import { factory } from 'test/small.factory';
import { ControllerContext, controllerSetup, mockBaseService } from 'test/utils';
describe(TagController.name, () => {
let ctx: ControllerContext;
const service = mockBaseService(TagService);
beforeAll(async () => {
ctx = await controllerSetup(TagController, [{ provide: TagService, useValue: service }]);
return () => ctx.close();
});
beforeEach(() => {
service.resetAllMocks();
ctx.reset();
});
describe('GET /tags', () => {
it('should be an authenticated route', async () => {
await request(ctx.getHttpServer()).get('/tags');
expect(ctx.authenticate).toHaveBeenCalled();
});
});
describe('POST /tags', () => {
it('should be an authenticated route', async () => {
await request(ctx.getHttpServer()).post('/tags');
expect(ctx.authenticate).toHaveBeenCalled();
});
it('should a null parentId', async () => {
await request(ctx.getHttpServer()).post(`/tags`).send({ name: 'tag', parentId: null });
expect(service.create).toHaveBeenCalledWith(undefined, expect.objectContaining({ parentId: null }));
});
});
describe('PUT /tags', () => {
it('should be an authenticated route', async () => {
await request(ctx.getHttpServer()).put('/tags');
expect(ctx.authenticate).toHaveBeenCalled();
});
});
describe('GET /tags/:id', () => {
it('should be an authenticated route', async () => {
await request(ctx.getHttpServer()).get(`/tags/${factory.uuid()}`);
expect(ctx.authenticate).toHaveBeenCalled();
});
it('should require a valid uuid', async () => {
const { status, body } = await request(ctx.getHttpServer()).get(`/tags/123`);
expect(status).toBe(400);
expect(body).toEqual(errorDto.badRequest([expect.stringContaining('id must be a UUID')]));
});
});
describe('PUT /tags/:id', () => {
it('should be an authenticated route', async () => {
await request(ctx.getHttpServer()).put(`/tags/${factory.uuid()}`);
expect(ctx.authenticate).toHaveBeenCalled();
});
it('should allow setting a null color via an empty string', async () => {
const id = factory.uuid();
await request(ctx.getHttpServer()).put(`/tags/${id}`).send({ color: '' });
expect(service.update).toHaveBeenCalledWith(undefined, id, expect.objectContaining({ color: null }));
});
});
});
+48 -2
View File
@@ -1,5 +1,6 @@
import { Body, Controller, Delete, Get, HttpCode, HttpStatus, Param, Post, Put } from '@nestjs/common';
import { ApiTags } from '@nestjs/swagger';
import { Endpoint, HistoryBuilder } from 'src/decorators';
import { BulkIdResponseDto, BulkIdsDto } from 'src/dtos/asset-ids.response.dto';
import { AuthDto } from 'src/dtos/auth.dto';
import {
@@ -10,48 +11,78 @@ import {
TagUpdateDto,
TagUpsertDto,
} from 'src/dtos/tag.dto';
import { Permission } from 'src/enum';
import { ApiTag, Permission } from 'src/enum';
import { Auth, Authenticated } from 'src/middleware/auth.guard';
import { TagService } from 'src/services/tag.service';
import { UUIDParamDto } from 'src/validation';
@ApiTags('Tags')
@ApiTags(ApiTag.Tags)
@Controller('tags')
export class TagController {
constructor(private service: TagService) {}
@Post()
@Authenticated({ permission: Permission.TagCreate })
@Endpoint({
summary: 'Create a tag',
description: 'Create a new tag by providing a name and optional color.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
createTag(@Auth() auth: AuthDto, @Body() dto: TagCreateDto): Promise<TagResponseDto> {
return this.service.create(auth, dto);
}
@Get()
@Authenticated({ permission: Permission.TagRead })
@Endpoint({
summary: 'Retrieve tags',
description: 'Retrieve a list of all tags.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
getAllTags(@Auth() auth: AuthDto): Promise<TagResponseDto[]> {
return this.service.getAll(auth);
}
@Put()
@Authenticated({ permission: Permission.TagCreate })
@Endpoint({
summary: 'Upsert tags',
description: 'Create or update multiple tags in a single request.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
upsertTags(@Auth() auth: AuthDto, @Body() dto: TagUpsertDto): Promise<TagResponseDto[]> {
return this.service.upsert(auth, dto);
}
@Put('assets')
@Authenticated({ permission: Permission.TagAsset })
@Endpoint({
summary: 'Tag assets',
description: 'Add multiple tags to multiple assets in a single request.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
bulkTagAssets(@Auth() auth: AuthDto, @Body() dto: TagBulkAssetsDto): Promise<TagBulkAssetsResponseDto> {
return this.service.bulkTagAssets(auth, dto);
}
@Get(':id')
@Authenticated({ permission: Permission.TagRead })
@Endpoint({
summary: 'Retrieve a tag',
description: 'Retrieve a specific tag by its ID.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
getTagById(@Auth() auth: AuthDto, @Param() { id }: UUIDParamDto): Promise<TagResponseDto> {
return this.service.get(auth, id);
}
@Put(':id')
@Authenticated({ permission: Permission.TagUpdate })
@Endpoint({
summary: 'Update a tag',
description: 'Update an existing tag identified by its ID.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
updateTag(@Auth() auth: AuthDto, @Param() { id }: UUIDParamDto, @Body() dto: TagUpdateDto): Promise<TagResponseDto> {
return this.service.update(auth, id, dto);
}
@@ -59,12 +90,22 @@ export class TagController {
@Delete(':id')
@Authenticated({ permission: Permission.TagDelete })
@HttpCode(HttpStatus.NO_CONTENT)
@Endpoint({
summary: 'Delete a tag',
description: 'Delete a specific tag by its ID.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
deleteTag(@Auth() auth: AuthDto, @Param() { id }: UUIDParamDto): Promise<void> {
return this.service.remove(auth, id);
}
@Put(':id/assets')
@Authenticated({ permission: Permission.TagAsset })
@Endpoint({
summary: 'Tag assets',
description: 'Add a tag to all the specified assets.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
tagAssets(
@Auth() auth: AuthDto,
@Param() { id }: UUIDParamDto,
@@ -75,6 +116,11 @@ export class TagController {
@Delete(':id/assets')
@Authenticated({ permission: Permission.TagAsset })
@Endpoint({
summary: 'Untag assets',
description: 'Remove a tag from all the specified assets.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
untagAssets(
@Auth() auth: AuthDto,
@Body() dto: BulkIdsDto,
+13 -2
View File
@@ -1,18 +1,24 @@
import { Controller, Get, Header, Query } from '@nestjs/common';
import { ApiOkResponse, ApiTags } from '@nestjs/swagger';
import { Endpoint, HistoryBuilder } from 'src/decorators';
import { AuthDto } from 'src/dtos/auth.dto';
import { TimeBucketAssetDto, TimeBucketAssetResponseDto, TimeBucketDto } from 'src/dtos/time-bucket.dto';
import { Permission } from 'src/enum';
import { ApiTag, Permission } from 'src/enum';
import { Auth, Authenticated } from 'src/middleware/auth.guard';
import { TimelineService } from 'src/services/timeline.service';
@ApiTags('Timeline')
@ApiTags(ApiTag.Timeline)
@Controller('timeline')
export class TimelineController {
constructor(private service: TimelineService) {}
@Get('buckets')
@Authenticated({ permission: Permission.AssetRead, sharedLink: true })
@Endpoint({
summary: 'Get time buckets',
description: 'Retrieve a list of all minimal time buckets.',
history: new HistoryBuilder().added('v1').internal('v1'),
})
getTimeBuckets(@Auth() auth: AuthDto, @Query() dto: TimeBucketDto) {
return this.service.getTimeBuckets(auth, dto);
}
@@ -21,6 +27,11 @@ export class TimelineController {
@Authenticated({ permission: Permission.AssetRead, sharedLink: true })
@ApiOkResponse({ type: TimeBucketAssetResponseDto })
@Header('Content-Type', 'application/json')
@Endpoint({
summary: 'Get time bucket',
description: 'Retrieve a string of all asset ids in a given time bucket.',
history: new HistoryBuilder().added('v1').internal('v1'),
})
getTimeBucket(@Auth() auth: AuthDto, @Query() dto: TimeBucketAssetDto) {
return this.service.getTimeBucket(auth, dto);
}
+18 -2
View File
@@ -1,13 +1,14 @@
import { Body, Controller, HttpCode, HttpStatus, Post } from '@nestjs/common';
import { ApiTags } from '@nestjs/swagger';
import { Endpoint, HistoryBuilder } from 'src/decorators';
import { BulkIdsDto } from 'src/dtos/asset-ids.response.dto';
import { AuthDto } from 'src/dtos/auth.dto';
import { TrashResponseDto } from 'src/dtos/trash.dto';
import { Permission } from 'src/enum';
import { ApiTag, Permission } from 'src/enum';
import { Auth, Authenticated } from 'src/middleware/auth.guard';
import { TrashService } from 'src/services/trash.service';
@ApiTags('Trash')
@ApiTags(ApiTag.Trash)
@Controller('trash')
export class TrashController {
constructor(private service: TrashService) {}
@@ -15,6 +16,11 @@ export class TrashController {
@Post('empty')
@Authenticated({ permission: Permission.AssetDelete })
@HttpCode(HttpStatus.OK)
@Endpoint({
summary: 'Empty trash',
description: 'Permanently delete all items in the trash.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
emptyTrash(@Auth() auth: AuthDto): Promise<TrashResponseDto> {
return this.service.empty(auth);
}
@@ -22,6 +28,11 @@ export class TrashController {
@Post('restore')
@Authenticated({ permission: Permission.AssetDelete })
@HttpCode(HttpStatus.OK)
@Endpoint({
summary: 'Restore trash',
description: 'Restore all items in the trash.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
restoreTrash(@Auth() auth: AuthDto): Promise<TrashResponseDto> {
return this.service.restore(auth);
}
@@ -29,6 +40,11 @@ export class TrashController {
@Post('restore/assets')
@Authenticated({ permission: Permission.AssetDelete })
@HttpCode(HttpStatus.OK)
@Endpoint({
summary: 'Restore assets',
description: 'Restore specific assets from the trash.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
restoreAssets(@Auth() auth: AuthDto, @Body() dto: BulkIdsDto): Promise<TrashResponseDto> {
return this.service.restoreAssets(auth, dto);
}
@@ -31,12 +31,55 @@ describe(UserAdminController.name, () => {
});
});
describe('PUT /admin/users/:id', () => {
it('should be an authenticated route', async () => {
await request(ctx.getHttpServer()).put(`/admin/users/${factory.uuid()}`);
expect(ctx.authenticate).toHaveBeenCalled();
});
});
describe('POST /admin/users', () => {
it('should be an authenticated route', async () => {
await request(ctx.getHttpServer()).post('/admin/users');
expect(ctx.authenticate).toHaveBeenCalled();
});
it('should allow a null pinCode', async () => {
await request(ctx.getHttpServer()).post(`/admin/users`).send({
name: 'Test user',
email: 'test@immich.cloud',
password: 'password',
pinCode: null,
});
expect(service.create).toHaveBeenCalledWith(expect.objectContaining({ pinCode: null }));
});
it('should allow a null avatarColor', async () => {
await request(ctx.getHttpServer()).post(`/admin/users`).send({
name: 'Test user',
email: 'test@immich.cloud',
password: 'password',
avatarColor: null,
});
expect(service.create).toHaveBeenCalledWith(expect.objectContaining({ avatarColor: null }));
});
it(`should `, async () => {
const dto: UserAdminCreateDto = {
email: 'user@immich.app',
password: 'test',
name: 'Test User',
quotaSizeInBytes: 1.2,
};
const { status, body } = await request(ctx.getHttpServer())
.post(`/admin/users`)
.set('Authorization', `Bearer token`)
.send(dto);
expect(status).toBe(400);
expect(body).toEqual(errorDto.badRequest(expect.arrayContaining(['quotaSizeInBytes must be an integer number'])));
});
it(`should not allow decimal quota`, async () => {
const dto: UserAdminCreateDto = {
email: 'user@immich.app',
@@ -75,5 +118,17 @@ describe(UserAdminController.name, () => {
expect(status).toBe(400);
expect(body).toEqual(errorDto.badRequest(expect.arrayContaining(['quotaSizeInBytes must be an integer number'])));
});
it('should allow a null pinCode', async () => {
const id = factory.uuid();
await request(ctx.getHttpServer()).put(`/admin/users/${id}`).send({ pinCode: null });
expect(service.update).toHaveBeenCalledWith(undefined, id, expect.objectContaining({ pinCode: null }));
});
it('should allow a null avatarColor', async () => {
const id = factory.uuid();
await request(ctx.getHttpServer()).put(`/admin/users/${id}`).send({ avatarColor: null });
expect(service.update).toHaveBeenCalledWith(undefined, id, expect.objectContaining({ avatarColor: null }));
});
});
});
@@ -1,5 +1,6 @@
import { Body, Controller, Delete, Get, HttpCode, HttpStatus, Param, Post, Put, Query } from '@nestjs/common';
import { ApiTags } from '@nestjs/swagger';
import { Endpoint, HistoryBuilder } from 'src/decorators';
import { AssetStatsDto, AssetStatsResponseDto } from 'src/dtos/asset.dto';
import { AuthDto } from 'src/dtos/auth.dto';
import { SessionResponseDto } from 'src/dtos/session.dto';
@@ -11,36 +12,56 @@ import {
UserAdminSearchDto,
UserAdminUpdateDto,
} from 'src/dtos/user.dto';
import { Permission } from 'src/enum';
import { ApiTag, Permission } from 'src/enum';
import { Auth, Authenticated } from 'src/middleware/auth.guard';
import { UserAdminService } from 'src/services/user-admin.service';
import { UUIDParamDto } from 'src/validation';
@ApiTags('Users (admin)')
@ApiTags(ApiTag.UsersAdmin)
@Controller('admin/users')
export class UserAdminController {
constructor(private service: UserAdminService) {}
@Get()
@Authenticated({ permission: Permission.AdminUserRead, admin: true })
@Endpoint({
summary: 'Search users',
description: 'Search for users.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
searchUsersAdmin(@Auth() auth: AuthDto, @Query() dto: UserAdminSearchDto): Promise<UserAdminResponseDto[]> {
return this.service.search(auth, dto);
}
@Post()
@Authenticated({ permission: Permission.AdminUserCreate, admin: true })
@Endpoint({
summary: 'Create a user',
description: 'Create a new user.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
createUserAdmin(@Body() createUserDto: UserAdminCreateDto): Promise<UserAdminResponseDto> {
return this.service.create(createUserDto);
}
@Get(':id')
@Authenticated({ permission: Permission.AdminUserRead, admin: true })
@Endpoint({
summary: 'Retrieve a user',
description: 'Retrieve a specific user by their ID.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
getUserAdmin(@Auth() auth: AuthDto, @Param() { id }: UUIDParamDto): Promise<UserAdminResponseDto> {
return this.service.get(auth, id);
}
@Put(':id')
@Authenticated({ permission: Permission.AdminUserUpdate, admin: true })
@Endpoint({
summary: 'Update a user',
description: 'Update an existing user.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
updateUserAdmin(
@Auth() auth: AuthDto,
@Param() { id }: UUIDParamDto,
@@ -51,6 +72,11 @@ export class UserAdminController {
@Delete(':id')
@Authenticated({ permission: Permission.AdminUserDelete, admin: true })
@Endpoint({
summary: 'Delete a user',
description: 'Delete a user.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
deleteUserAdmin(
@Auth() auth: AuthDto,
@Param() { id }: UUIDParamDto,
@@ -61,12 +87,22 @@ export class UserAdminController {
@Get(':id/sessions')
@Authenticated({ permission: Permission.AdminSessionRead, admin: true })
@Endpoint({
summary: 'Retrieve user sessions',
description: 'Retrieve all sessions for a specific user.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
getUserSessionsAdmin(@Auth() auth: AuthDto, @Param() { id }: UUIDParamDto): Promise<SessionResponseDto[]> {
return this.service.getSessions(auth, id);
}
@Get(':id/statistics')
@Authenticated({ permission: Permission.AdminUserRead, admin: true })
@Endpoint({
summary: 'Retrieve user statistics',
description: 'Retrieve asset statistics for a specific user.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
getUserStatisticsAdmin(
@Auth() auth: AuthDto,
@Param() { id }: UUIDParamDto,
@@ -77,12 +113,22 @@ export class UserAdminController {
@Get(':id/preferences')
@Authenticated({ permission: Permission.AdminUserRead, admin: true })
@Endpoint({
summary: 'Retrieve user preferences',
description: 'Retrieve the preferences of a specific user.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
getUserPreferencesAdmin(@Auth() auth: AuthDto, @Param() { id }: UUIDParamDto): Promise<UserPreferencesResponseDto> {
return this.service.getPreferences(auth, id);
}
@Put(':id/preferences')
@Authenticated({ permission: Permission.AdminUserUpdate, admin: true })
@Endpoint({
summary: 'Update user preferences',
description: 'Update the preferences of a specific user.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
updateUserPreferencesAdmin(
@Auth() auth: AuthDto,
@Param() { id }: UUIDParamDto,
@@ -94,6 +140,11 @@ export class UserAdminController {
@Post(':id/restore')
@Authenticated({ permission: Permission.AdminUserDelete, admin: true })
@HttpCode(HttpStatus.OK)
@Endpoint({
summary: 'Restore a deleted user',
description: 'Restore a previously deleted user.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
restoreUserAdmin(@Auth() auth: AuthDto, @Param() { id }: UUIDParamDto): Promise<UserAdminResponseDto> {
return this.service.restore(auth, id);
}
@@ -54,6 +54,14 @@ describe(UserController.name, () => {
expect(body).toEqual(errorDto.badRequest());
});
}
it('should allow an empty avatarColor', async () => {
await request(ctx.getHttpServer())
.put(`/users/me`)
.set('Authorization', `Bearer token`)
.send({ avatarColor: null });
expect(service.updateMe).toHaveBeenCalledWith(undefined, expect.objectContaining({ avatarColor: null }));
});
});
describe('GET /users/:id', () => {
+78 -2
View File
@@ -15,13 +15,14 @@ import {
} from '@nestjs/common';
import { ApiBody, ApiConsumes, ApiTags } from '@nestjs/swagger';
import { NextFunction, Response } from 'express';
import { Endpoint, HistoryBuilder } from 'src/decorators';
import { AuthDto } from 'src/dtos/auth.dto';
import { LicenseKeyDto, LicenseResponseDto } from 'src/dtos/license.dto';
import { OnboardingDto, OnboardingResponseDto } from 'src/dtos/onboarding.dto';
import { UserPreferencesResponseDto, UserPreferencesUpdateDto } from 'src/dtos/user-preferences.dto';
import { CreateProfileImageDto, CreateProfileImageResponseDto } from 'src/dtos/user-profile.dto';
import { UserAdminResponseDto, UserResponseDto, UserUpdateMeDto } from 'src/dtos/user.dto';
import { Permission, RouteKey } from 'src/enum';
import { ApiTag, Permission, RouteKey } from 'src/enum';
import { Auth, Authenticated, FileResponse } from 'src/middleware/auth.guard';
import { FileUploadInterceptor } from 'src/middleware/file-upload.interceptor';
import { LoggingRepository } from 'src/repositories/logging.repository';
@@ -29,7 +30,7 @@ import { UserService } from 'src/services/user.service';
import { sendFile } from 'src/utils/file';
import { UUIDParamDto } from 'src/validation';
@ApiTags('Users')
@ApiTags(ApiTag.Users)
@Controller(RouteKey.User)
export class UserController {
constructor(
@@ -39,30 +40,55 @@ export class UserController {
@Get()
@Authenticated({ permission: Permission.UserRead })
@Endpoint({
summary: 'Get all users',
description: 'Retrieve a list of all users on the server.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
searchUsers(@Auth() auth: AuthDto): Promise<UserResponseDto[]> {
return this.service.search(auth);
}
@Get('me')
@Authenticated({ permission: Permission.UserRead })
@Endpoint({
summary: 'Get current user',
description: 'Retrieve information about the user making the API request.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
getMyUser(@Auth() auth: AuthDto): Promise<UserAdminResponseDto> {
return this.service.getMe(auth);
}
@Put('me')
@Authenticated({ permission: Permission.UserUpdate })
@Endpoint({
summary: 'Update current user',
description: 'Update the current user making teh API request.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
updateMyUser(@Auth() auth: AuthDto, @Body() dto: UserUpdateMeDto): Promise<UserAdminResponseDto> {
return this.service.updateMe(auth, dto);
}
@Get('me/preferences')
@Authenticated({ permission: Permission.UserPreferenceRead })
@Endpoint({
summary: 'Get my preferences',
description: 'Retrieve the preferences for the current user.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
getMyPreferences(@Auth() auth: AuthDto): Promise<UserPreferencesResponseDto> {
return this.service.getMyPreferences(auth);
}
@Put('me/preferences')
@Authenticated({ permission: Permission.UserPreferenceUpdate })
@Endpoint({
summary: 'Update my preferences',
description: 'Update the preferences of the current user.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
updateMyPreferences(
@Auth() auth: AuthDto,
@Body() dto: UserPreferencesUpdateDto,
@@ -72,12 +98,22 @@ export class UserController {
@Get('me/license')
@Authenticated({ permission: Permission.UserLicenseRead })
@Endpoint({
summary: 'Retrieve user product key',
description: 'Retrieve information about whether the current user has a registered product key.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
getUserLicense(@Auth() auth: AuthDto): Promise<LicenseResponseDto> {
return this.service.getLicense(auth);
}
@Put('me/license')
@Authenticated({ permission: Permission.UserLicenseUpdate })
@Endpoint({
summary: 'Set user product key',
description: 'Register a product key for the current user.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
async setUserLicense(@Auth() auth: AuthDto, @Body() license: LicenseKeyDto): Promise<LicenseResponseDto> {
return this.service.setLicense(auth, license);
}
@@ -85,18 +121,33 @@ export class UserController {
@Delete('me/license')
@Authenticated({ permission: Permission.UserLicenseDelete })
@HttpCode(HttpStatus.NO_CONTENT)
@Endpoint({
summary: 'Delete user product key',
description: 'Delete the registered product key for the current user.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
async deleteUserLicense(@Auth() auth: AuthDto): Promise<void> {
await this.service.deleteLicense(auth);
}
@Get('me/onboarding')
@Authenticated({ permission: Permission.UserOnboardingRead })
@Endpoint({
summary: 'Retrieve user onboarding',
description: 'Retrieve the onboarding status of the current user.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
getUserOnboarding(@Auth() auth: AuthDto): Promise<OnboardingResponseDto> {
return this.service.getOnboarding(auth);
}
@Put('me/onboarding')
@Authenticated({ permission: Permission.UserOnboardingUpdate })
@Endpoint({
summary: 'Update user onboarding',
description: 'Update the onboarding status of the current user.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
async setUserOnboarding(@Auth() auth: AuthDto, @Body() Onboarding: OnboardingDto): Promise<OnboardingResponseDto> {
return this.service.setOnboarding(auth, Onboarding);
}
@@ -104,12 +155,22 @@ export class UserController {
@Delete('me/onboarding')
@Authenticated({ permission: Permission.UserOnboardingDelete })
@HttpCode(HttpStatus.NO_CONTENT)
@Endpoint({
summary: 'Delete user onboarding',
description: 'Delete the onboarding status of the current user.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
async deleteUserOnboarding(@Auth() auth: AuthDto): Promise<void> {
await this.service.deleteOnboarding(auth);
}
@Get(':id')
@Authenticated({ permission: Permission.UserRead })
@Endpoint({
summary: 'Retrieve a user',
description: 'Retrieve a specific user by their ID.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
getUser(@Param() { id }: UUIDParamDto): Promise<UserResponseDto> {
return this.service.get(id);
}
@@ -119,6 +180,11 @@ export class UserController {
@UseInterceptors(FileUploadInterceptor)
@ApiConsumes('multipart/form-data')
@ApiBody({ description: 'A new avatar for the user', type: CreateProfileImageDto })
@Endpoint({
summary: 'Create user profile image',
description: 'Upload and set a new profile image for the current user.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
createProfileImage(
@Auth() auth: AuthDto,
@UploadedFile() fileInfo: Express.Multer.File,
@@ -129,6 +195,11 @@ export class UserController {
@Delete('profile-image')
@Authenticated({ permission: Permission.UserProfileImageDelete })
@HttpCode(HttpStatus.NO_CONTENT)
@Endpoint({
summary: 'Delete user profile image',
description: 'Delete the profile image of the current user.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
deleteProfileImage(@Auth() auth: AuthDto): Promise<void> {
return this.service.deleteProfileImage(auth);
}
@@ -136,6 +207,11 @@ export class UserController {
@Get(':id/profile-image')
@FileResponse()
@Authenticated({ permission: Permission.UserProfileImageRead })
@Endpoint({
summary: 'Retrieve user profile image',
description: 'Retrieve the profile image file for a user.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
async getProfileImage(@Res() res: Response, @Next() next: NextFunction, @Param() { id }: UUIDParamDto) {
await sendFile(res, next, () => this.service.getProfileImage(id), this.logger);
}
+15 -3
View File
@@ -1,23 +1,35 @@
import { Controller, Get, Query } from '@nestjs/common';
import { ApiTags } from '@nestjs/swagger';
import { Endpoint, HistoryBuilder } from 'src/decorators';
import { AssetResponseDto } from 'src/dtos/asset-response.dto';
import { AuthDto } from 'src/dtos/auth.dto';
import { ApiTag, Permission } from 'src/enum';
import { Auth, Authenticated } from 'src/middleware/auth.guard';
import { ViewService } from 'src/services/view.service';
@ApiTags('View')
@ApiTags(ApiTag.Views)
@Controller('view')
export class ViewController {
constructor(private service: ViewService) {}
@Get('folder/unique-paths')
@Authenticated()
@Authenticated({ permission: Permission.FolderRead })
@Endpoint({
summary: 'Retrieve unique paths',
description: 'Retrieve a list of unique folder paths from asset original paths.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
getUniqueOriginalPaths(@Auth() auth: AuthDto): Promise<string[]> {
return this.service.getUniqueOriginalPaths(auth);
}
@Get('folder')
@Authenticated()
@Authenticated({ permission: Permission.FolderRead })
@Endpoint({
summary: 'Retrieve assets by original path',
description: 'Retrieve assets that are children of a specific folder.',
history: new HistoryBuilder().added('v1').beta('v1').stable('v2'),
})
getAssetsByOriginalPath(@Auth() auth: AuthDto, @Query('path') path: string): Promise<AssetResponseDto[]> {
return this.service.getAssetsByOriginalPath(auth, path);
}
@@ -0,0 +1,76 @@
import { Body, Controller, Delete, Get, HttpCode, HttpStatus, Param, Post, Put } from '@nestjs/common';
import { ApiTags } from '@nestjs/swagger';
import { Endpoint, HistoryBuilder } from 'src/decorators';
import { AuthDto } from 'src/dtos/auth.dto';
import { WorkflowCreateDto, WorkflowResponseDto, WorkflowUpdateDto } from 'src/dtos/workflow.dto';
import { Permission } from 'src/enum';
import { Auth, Authenticated } from 'src/middleware/auth.guard';
import { WorkflowService } from 'src/services/workflow.service';
import { UUIDParamDto } from 'src/validation';
@ApiTags('Workflows')
@Controller('workflows')
export class WorkflowController {
constructor(private service: WorkflowService) {}
@Post()
@Authenticated({ permission: Permission.WorkflowCreate })
@Endpoint({
summary: 'Create a workflow',
description: 'Create a new workflow, the workflow can also be created with empty filters and actions.',
history: new HistoryBuilder().added('v2.3.0').alpha('v2.3.0'),
})
createWorkflow(@Auth() auth: AuthDto, @Body() dto: WorkflowCreateDto): Promise<WorkflowResponseDto> {
return this.service.create(auth, dto);
}
@Get()
@Authenticated({ permission: Permission.WorkflowRead })
@Endpoint({
summary: 'List all workflows',
description: 'Retrieve a list of workflows available to the authenticated user.',
history: new HistoryBuilder().added('v2.3.0').alpha('v2.3.0'),
})
getWorkflows(@Auth() auth: AuthDto): Promise<WorkflowResponseDto[]> {
return this.service.getAll(auth);
}
@Get(':id')
@Authenticated({ permission: Permission.WorkflowRead })
@Endpoint({
summary: 'Retrieve a workflow',
description: 'Retrieve information about a specific workflow by its ID.',
history: new HistoryBuilder().added('v2.3.0').alpha('v2.3.0'),
})
getWorkflow(@Auth() auth: AuthDto, @Param() { id }: UUIDParamDto): Promise<WorkflowResponseDto> {
return this.service.get(auth, id);
}
@Put(':id')
@Authenticated({ permission: Permission.WorkflowUpdate })
@Endpoint({
summary: 'Update a workflow',
description:
'Update the information of a specific workflow by its ID. This endpoint can be used to update the workflow name, description, trigger type, filters and actions order, etc.',
history: new HistoryBuilder().added('v2.3.0').alpha('v2.3.0'),
})
updateWorkflow(
@Auth() auth: AuthDto,
@Param() { id }: UUIDParamDto,
@Body() dto: WorkflowUpdateDto,
): Promise<WorkflowResponseDto> {
return this.service.update(auth, id, dto);
}
@Delete(':id')
@Authenticated({ permission: Permission.WorkflowDelete })
@HttpCode(HttpStatus.NO_CONTENT)
@Endpoint({
summary: 'Delete a workflow',
description: 'Delete a workflow by its ID.',
history: new HistoryBuilder().added('v2.3.0').alpha('v2.3.0'),
})
deleteWorkflow(@Auth() auth: AuthDto, @Param() { id }: UUIDParamDto): Promise<void> {
return this.service.delete(auth, id);
}
}
-2
View File
@@ -2,8 +2,6 @@ import { StorageCore } from 'src/cores/storage.core';
import { vitest } from 'vitest';
vitest.mock('src/constants', () => ({
ADDED_IN_PREFIX: 'This property was added in ',
DEPRECATED_IN_PREFIX: 'This property was deprecated in ',
IWorker: 'IWorker',
}));
+31 -25
View File
@@ -1,7 +1,15 @@
import { randomUUID } from 'node:crypto';
import { dirname, join, resolve } from 'node:path';
import { StorageAsset } from 'src/database';
import { AssetFileType, AssetPathType, ImageFormat, PathType, PersonPathType, StorageFolder } from 'src/enum';
import {
AssetFileType,
AssetPathType,
ImageFormat,
PathType,
PersonPathType,
RawExtractedFormat,
StorageFolder,
} from 'src/enum';
import { AssetRepository } from 'src/repositories/asset.repository';
import { ConfigRepository } from 'src/repositories/config.repository';
import { CryptoRepository } from 'src/repositories/crypto.repository';
@@ -24,11 +32,10 @@ export interface MoveRequest {
};
}
export type GeneratedImageType = AssetPathType.Preview | AssetPathType.Thumbnail | AssetPathType.FullSize;
export type GeneratedAssetType = GeneratedImageType | AssetPathType.EncodedVideo;
export type ThumbnailPathEntity = { id: string; ownerId: string };
export type ImagePathOptions = { fileType: AssetFileType; format: ImageFormat | RawExtractedFormat; isEdited: boolean };
let instance: StorageCore | null;
let mediaLocation: string | undefined;
@@ -105,8 +112,12 @@ export class StorageCore {
return StorageCore.getNestedPath(StorageFolder.Thumbnails, person.ownerId, `${person.id}.jpeg`);
}
static getImagePath(asset: ThumbnailPathEntity, type: GeneratedImageType, format: 'jpeg' | 'webp') {
return StorageCore.getNestedPath(StorageFolder.Thumbnails, asset.ownerId, `${asset.id}-${type}.${format}`);
static getImagePath(asset: ThumbnailPathEntity, { fileType, format, isEdited }: ImagePathOptions) {
return StorageCore.getNestedPath(
StorageFolder.Thumbnails,
asset.ownerId,
`${asset.id}_${fileType}${isEdited ? '_edited' : ''}.${format}`,
);
}
static getEncodedVideoPath(asset: ThumbnailPathEntity) {
@@ -131,22 +142,23 @@ export class StorageCore {
return normalizedPath.startsWith(normalizedAppMediaLocation);
}
async moveAssetImage(asset: StorageAsset, pathType: GeneratedImageType, format: ImageFormat) {
async moveAssetImage(asset: StorageAsset, fileType: AssetFileType, format: ImageFormat) {
const { id: entityId, files } = asset;
const oldFile = getAssetFile(files, pathType);
const oldFile = getAssetFile(files, fileType, { isEdited: false });
return this.moveFile({
entityId,
pathType,
pathType: fileType,
oldPath: oldFile?.path || null,
newPath: StorageCore.getImagePath(asset, pathType, format),
newPath: StorageCore.getImagePath(asset, { fileType, format, isEdited: false }),
});
}
async moveAssetVideo(asset: StorageAsset) {
const encodedVideoFile = getAssetFile(asset.files, AssetFileType.EncodedVideo, { isEdited: false });
return this.moveFile({
entityId: asset.id,
pathType: AssetPathType.EncodedVideo,
oldPath: asset.encodedVideoPath,
oldPath: encodedVideoFile?.path || null,
newPath: StorageCore.getEncodedVideoPath(asset),
});
}
@@ -292,21 +304,15 @@ export class StorageCore {
case AssetPathType.Original: {
return this.assetRepository.update({ id, originalPath: newPath });
}
case AssetPathType.FullSize: {
return this.assetRepository.upsertFile({ assetId: id, type: AssetFileType.FullSize, path: newPath });
}
case AssetPathType.Preview: {
return this.assetRepository.upsertFile({ assetId: id, type: AssetFileType.Preview, path: newPath });
}
case AssetPathType.Thumbnail: {
return this.assetRepository.upsertFile({ assetId: id, type: AssetFileType.Thumbnail, path: newPath });
}
case AssetPathType.EncodedVideo: {
return this.assetRepository.update({ id, encodedVideoPath: newPath });
}
case AssetPathType.Sidecar: {
return this.assetRepository.update({ id, sidecarPath: newPath });
case AssetFileType.FullSize:
case AssetFileType.EncodedVideo:
case AssetFileType.Thumbnail:
case AssetFileType.Preview:
case AssetFileType.Sidecar: {
return this.assetRepository.upsertFile({ assetId: id, type: pathType as AssetFileType, path: newPath });
}
case PersonPathType.Face: {
return this.personRepository.update({ id, thumbnailPath: newPath });
}
+110 -34
View File
@@ -1,12 +1,15 @@
import { Selectable } from 'kysely';
import { Selectable, ShallowDehydrateObject } from 'kysely';
import { MapAsset } from 'src/dtos/asset-response.dto';
import {
AlbumUserRole,
AssetFileType,
AssetType,
AssetVisibility,
ChecksumAlgorithm,
MemoryType,
Permission,
PluginContext,
PluginTriggerType,
SharedLinkType,
SourceType,
UserAvatarColor,
@@ -14,7 +17,11 @@ import {
} from 'src/enum';
import { AlbumTable } from 'src/schema/tables/album.table';
import { AssetExifTable } from 'src/schema/tables/asset-exif.table';
import { AssetTable } from 'src/schema/tables/asset.table';
import { PluginActionTable, PluginFilterTable, PluginTable } from 'src/schema/tables/plugin.table';
import { WorkflowActionTable, WorkflowFilterTable, WorkflowTable } from 'src/schema/tables/workflow.table';
import { UserMetadataItem } from 'src/types';
import type { ActionConfig, FilterConfig, JSONSchema } from 'src/types/plugin-schema.types';
export type AuthUser = {
id: string;
@@ -26,7 +33,7 @@ export type AuthUser = {
};
export type AlbumUser = {
user: User;
user: ShallowDehydrateObject<User>;
role: AlbumUserRole;
};
@@ -34,6 +41,7 @@ export type AssetFile = {
id: string;
type: AssetFileType;
path: string;
isEdited: boolean;
};
export type Library = {
@@ -61,7 +69,7 @@ export type Activity = {
updatedAt: Date;
albumId: string;
userId: string;
user: User;
user: ShallowDehydrateObject<User>;
assetId: string | null;
comment: string | null;
isLiked: boolean;
@@ -99,12 +107,13 @@ export type Memory = {
data: object;
ownerId: string;
isSaved: boolean;
assets: MapAsset[];
assets: ShallowDehydrateObject<MapAsset>[];
};
export type Asset = {
id: string;
checksum: Buffer<ArrayBufferLike>;
checksumAlgorithm: ChecksumAlgorithm;
deviceAssetId: string;
deviceId: string;
fileCreatedAt: Date;
@@ -117,7 +126,6 @@ export type Asset = {
originalFileName: string;
originalPath: string;
ownerId: string;
sidecarPath: string | null;
type: AssetType;
};
@@ -148,22 +156,14 @@ export type StorageAsset = {
id: string;
ownerId: string;
files: AssetFile[];
encodedVideoPath: string | null;
};
export type SidecarWriteAsset = {
id: string;
sidecarPath: string | null;
originalPath: string;
tags: Array<{ value: string }>;
};
export type Stack = {
id: string;
primaryAssetId: string;
owner?: User;
owner?: ShallowDehydrateObject<User>;
ownerId: string;
assets: MapAsset[];
assets: ShallowDehydrateObject<MapAsset>[];
assetCount?: number;
};
@@ -171,6 +171,7 @@ export type AuthSharedLink = {
id: string;
expiresAt: Date | null;
userId: string;
albumId: string | null;
showExif: boolean;
allowUpload: boolean;
allowDownload: boolean;
@@ -179,11 +180,11 @@ export type AuthSharedLink = {
export type SharedLink = {
id: string;
album?: Album | null;
album?: ShallowDehydrateObject<Album> | null;
albumId: string | null;
allowDownload: boolean;
allowUpload: boolean;
assets: MapAsset[];
assets: ShallowDehydrateObject<MapAsset>[];
createdAt: Date;
description: string | null;
expiresAt: Date | null;
@@ -196,8 +197,8 @@ export type SharedLink = {
};
export type Album = Selectable<AlbumTable> & {
owner: User;
assets: MapAsset[];
owner: ShallowDehydrateObject<User>;
assets: ShallowDehydrateObject<Selectable<AssetTable>>[];
};
export type AuthSession = {
@@ -207,9 +208,9 @@ export type AuthSession = {
export type Partner = {
sharedById: string;
sharedBy: User;
sharedBy: ShallowDehydrateObject<User>;
sharedWithId: string;
sharedWith: User;
sharedWith: ShallowDehydrateObject<User>;
createdAt: Date;
createId: string;
updatedAt: Date;
@@ -243,7 +244,7 @@ export type Session = {
isPendingSyncReset: boolean;
};
export type Exif = Omit<Selectable<AssetExifTable>, 'updatedAt' | 'updateId'>;
export type Exif = Omit<Selectable<AssetExifTable>, 'updatedAt' | 'updateId' | 'lockedProperties'>;
export type Person = {
createdAt: Date;
@@ -272,9 +273,49 @@ export type AssetFace = {
imageWidth: number;
personId: string | null;
sourceType: SourceType;
person?: Person | null;
person?: ShallowDehydrateObject<Person> | null;
updatedAt: Date;
updateId: string;
isVisible: boolean;
};
export type Plugin = Selectable<PluginTable>;
export type PluginFilter = Selectable<PluginFilterTable> & {
methodName: string;
title: string;
description: string;
supportedContexts: PluginContext[];
schema: JSONSchema | null;
};
export type PluginAction = Selectable<PluginActionTable> & {
methodName: string;
title: string;
description: string;
supportedContexts: PluginContext[];
schema: JSONSchema | null;
};
export type Workflow = Selectable<WorkflowTable> & {
triggerType: PluginTriggerType;
name: string | null;
description: string;
enabled: boolean;
};
export type WorkflowFilter = Selectable<WorkflowFilterTable> & {
workflowId: string;
pluginFilterId: string;
filterConfig: FilterConfig | null;
order: number;
};
export type WorkflowAction = Selectable<WorkflowActionTable> & {
workflowId: string;
pluginActionId: string;
actionConfig: ActionConfig | null;
order: number;
};
const userColumns = ['id', 'name', 'email', 'avatarColor', 'profileImagePath', 'profileChangedAt'] as const;
@@ -291,6 +332,7 @@ export const columns = {
asset: [
'asset.id',
'asset.checksum',
'asset.checksumAlgorithm',
'asset.deviceAssetId',
'asset.deviceId',
'asset.fileCreatedAt',
@@ -303,22 +345,23 @@ export const columns = {
'asset.originalFileName',
'asset.originalPath',
'asset.ownerId',
'asset.sidecarPath',
'asset.type',
'asset.width',
'asset.height',
'asset.isEdited',
],
assetFiles: ['asset_file.id', 'asset_file.path', 'asset_file.type', 'asset_file.isEdited'],
assetFilesForThumbnail: [
'asset_file.id',
'asset_file.path',
'asset_file.type',
'asset_file.isEdited',
'asset_file.isProgressive',
'asset_file.isTransparent',
],
assetFiles: ['asset_file.id', 'asset_file.path', 'asset_file.type'],
authUser: ['user.id', 'user.name', 'user.email', 'user.isAdmin', 'user.quotaUsageInBytes', 'user.quotaSizeInBytes'],
authApiKey: ['api_key.id', 'api_key.permissions'],
authSession: ['session.id', 'session.updatedAt', 'session.pinExpiresAt', 'session.appVersion'],
authSharedLink: [
'shared_link.id',
'shared_link.userId',
'shared_link.expiresAt',
'shared_link.showExif',
'shared_link.allowUpload',
'shared_link.allowDownload',
'shared_link.password',
],
user: userColumns,
userWithPrefix: userWithPrefixColumns,
userAdmin: [
@@ -355,6 +398,9 @@ export const columns = {
'asset.livePhotoVideoId',
'asset.stackId',
'asset.libraryId',
'asset.width',
'asset.height',
'asset.isEdited',
],
syncAlbumUser: ['album_user.albumId as albumId', 'album_user.userId as userId', 'album_user.role'],
syncStack: ['stack.id', 'stack.createdAt', 'stack.updatedAt', 'stack.primaryAssetId', 'stack.ownerId'],
@@ -387,6 +433,13 @@ export const columns = {
'asset_exif.rating',
'asset_exif.fps',
],
syncAssetEdit: [
'asset_edit.id',
'asset_edit.assetId',
'asset_edit.sequence',
'asset_edit.action',
'asset_edit.parameters',
],
exif: [
'asset_exif.assetId',
'asset_exif.autoStackId',
@@ -416,6 +469,29 @@ export const columns = {
'asset_exif.projectionType',
'asset_exif.rating',
'asset_exif.state',
'asset_exif.tags',
'asset_exif.timeZone',
],
plugin: [
'plugin.id as id',
'plugin.name as name',
'plugin.title as title',
'plugin.description as description',
'plugin.author as author',
'plugin.version as version',
'plugin.wasmPath as wasmPath',
'plugin.createdAt as createdAt',
'plugin.updatedAt as updatedAt',
],
} as const;
export type LockableProperty = (typeof lockableProperties)[number];
export const lockableProperties = [
'description',
'dateTimeOriginal',
'latitude',
'longitude',
'rating',
'timeZone',
'tags',
] as const;
+113 -31
View File
@@ -1,11 +1,10 @@
import { BeforeUpdateTrigger, Column, ColumnOptions } from '@immich/sql-tools';
import { SetMetadata, applyDecorators } from '@nestjs/common';
import { ApiExtension, ApiOperation, ApiOperationOptions, ApiProperty, ApiTags } from '@nestjs/swagger';
import { ApiOperation, ApiOperationOptions, ApiProperty, ApiPropertyOptions, ApiTags } from '@nestjs/swagger';
import _ from 'lodash';
import { ADDED_IN_PREFIX, DEPRECATED_IN_PREFIX, LIFECYCLE_EXTENSION } from 'src/constants';
import { ImmichWorker, JobName, MetadataKey, QueueName } from 'src/enum';
import { ApiCustomExtension, ApiTag, ImmichWorker, JobName, MetadataKey, QueueName } from 'src/enum';
import { EmitEvent } from 'src/repositories/event.repository';
import { immich_uuid_v7, updated_at } from 'src/schema/functions';
import { BeforeUpdateTrigger, Column, ColumnOptions } from 'src/sql-tools';
import { setUnion } from 'src/utils/set';
const GeneratedUuidV7Column = (options: Omit<ColumnOptions, 'type' | 'default' | 'nullable'> = {}) =>
@@ -153,39 +152,122 @@ export type JobConfig = {
};
export const OnJob = (config: JobConfig) => SetMetadata(MetadataKey.JobConfig, config);
type LifecycleRelease = 'NEXT_RELEASE' | string;
type LifecycleMetadata = {
addedAt?: LifecycleRelease;
deprecatedAt?: LifecycleRelease;
};
type EndpointOptions = ApiOperationOptions & { history?: HistoryBuilder };
export const Endpoint = ({ history, ...options }: EndpointOptions) => {
const decorators: MethodDecorator[] = [];
const extensions = history?.getExtensions() ?? {};
export const EndpointLifecycle = ({
addedAt,
deprecatedAt,
description,
...options
}: LifecycleMetadata & ApiOperationOptions) => {
const decorators: MethodDecorator[] = [ApiExtension(LIFECYCLE_EXTENSION, { addedAt, deprecatedAt })];
if (deprecatedAt) {
decorators.push(
ApiTags('Deprecated'),
ApiOperation({
deprecated: true,
description: DEPRECATED_IN_PREFIX + deprecatedAt + (description ? `. ${description}` : ''),
...options,
}),
);
if (!extensions[ApiCustomExtension.History]) {
console.log(`Missing history for endpoint: ${options.summary}`);
}
if (history?.isDeprecated()) {
options.deprecated = true;
decorators.push(ApiTags(ApiTag.Deprecated));
}
decorators.push(ApiOperation({ ...options, ...extensions }));
return applyDecorators(...decorators);
};
export const PropertyLifecycle = ({ addedAt, deprecatedAt }: LifecycleMetadata) => {
const decorators: PropertyDecorator[] = [];
decorators.push(ApiProperty({ description: ADDED_IN_PREFIX + addedAt }));
if (deprecatedAt) {
decorators.push(ApiProperty({ deprecated: true, description: DEPRECATED_IN_PREFIX + deprecatedAt }));
export type PropertyOptions = ApiPropertyOptions & { history?: HistoryBuilder };
export const Property = ({ history, ...options }: PropertyOptions) => {
const extensions = history?.getExtensions() ?? {};
if (history?.isDeprecated()) {
options.deprecated = true;
}
return applyDecorators(...decorators);
return ApiProperty({ ...options, ...extensions });
};
type HistoryEntry = {
version: string;
state: ApiState | 'Added' | 'Updated';
description?: string;
replacementId?: string;
};
type DeprecatedOptions = {
/** replacement operationId */
replacementId?: string;
};
type CustomExtensions = {
[ApiCustomExtension.State]?: ApiState;
[ApiCustomExtension.History]?: HistoryEntry[];
};
enum ApiState {
'Stable' = 'Stable',
'Alpha' = 'Alpha',
'Beta' = 'Beta',
'Internal' = 'Internal',
'Deprecated' = 'Deprecated',
}
export class HistoryBuilder {
private hasDeprecated = false;
private items: HistoryEntry[] = [];
added(version: string, description?: string) {
return this.push({ version, state: 'Added', description });
}
updated(version: string, description: string) {
return this.push({ version, state: 'Updated', description });
}
alpha(version: string) {
return this.push({ version, state: ApiState.Alpha });
}
beta(version: string) {
return this.push({ version, state: ApiState.Beta });
}
internal(version: string) {
return this.push({ version, state: ApiState.Internal });
}
stable(version: string) {
return this.push({ version, state: ApiState.Stable });
}
deprecated(version: string, options?: DeprecatedOptions) {
const { replacementId } = options || {};
this.hasDeprecated = true;
return this.push({ version, state: ApiState.Deprecated, replacementId });
}
isDeprecated(): boolean {
return this.hasDeprecated;
}
getExtensions() {
const extensions: CustomExtensions = {};
if (this.items.length > 0) {
extensions[ApiCustomExtension.History] = this.items;
}
for (const item of this.items.toReversed()) {
if (item.state === 'Added' || item.state === 'Updated') {
continue;
}
extensions[ApiCustomExtension.State] = item.state;
break;
}
return extensions;
}
private push(item: HistoryEntry) {
if (!item.version.startsWith('v')) {
throw new Error(`Version string must start with 'v': received '${JSON.stringify(item)}'`);
}
this.items.push(item);
return this;
}
}
+17 -10
View File
@@ -1,4 +1,4 @@
import { ApiProperty } from '@nestjs/swagger';
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import { IsNotEmpty, IsString, ValidateIf } from 'class-validator';
import { Activity } from 'src/database';
import { mapUser, UserResponseDto } from 'src/dtos/user.dto';
@@ -17,48 +17,55 @@ export enum ReactionLevel {
export type MaybeDuplicate<T> = { duplicate: boolean; value: T };
export class ActivityResponseDto {
@ApiProperty({ description: 'Activity ID' })
id!: string;
@ApiProperty({ description: 'Creation date', format: 'date-time' })
createdAt!: Date;
@ValidateEnum({ enum: ReactionType, name: 'ReactionType' })
@ValidateEnum({ enum: ReactionType, name: 'ReactionType', description: 'Activity type' })
type!: ReactionType;
// Description lives on schema to avoid duplication
@ApiProperty({ description: undefined })
user!: UserResponseDto;
@ApiProperty({ description: 'Asset ID (if activity is for an asset)' })
assetId!: string | null;
@ApiPropertyOptional({ description: 'Comment text (for comment activities)' })
comment?: string | null;
}
export class ActivityStatisticsResponseDto {
@ApiProperty({ type: 'integer' })
@ApiProperty({ type: 'integer', description: 'Number of comments' })
comments!: number;
@ApiProperty({ type: 'integer' })
@ApiProperty({ type: 'integer', description: 'Number of likes' })
likes!: number;
}
export class ActivityDto {
@ValidateUUID()
@ValidateUUID({ description: 'Album ID' })
albumId!: string;
@ValidateUUID({ optional: true })
@ValidateUUID({ optional: true, description: 'Asset ID (if activity is for an asset)' })
assetId?: string;
}
export class ActivitySearchDto extends ActivityDto {
@ValidateEnum({ enum: ReactionType, name: 'ReactionType', optional: true })
@ValidateEnum({ enum: ReactionType, name: 'ReactionType', description: 'Filter by activity type', optional: true })
type?: ReactionType;
@ValidateEnum({ enum: ReactionLevel, name: 'ReactionLevel', optional: true })
@ValidateEnum({ enum: ReactionLevel, name: 'ReactionLevel', description: 'Filter by activity level', optional: true })
level?: ReactionLevel;
@ValidateUUID({ optional: true })
@ValidateUUID({ optional: true, description: 'Filter by user ID' })
userId?: string;
}
const isComment = (dto: ActivityCreateDto) => dto.type === ReactionType.COMMENT;
export class ActivityCreateDto extends ActivityDto {
@ValidateEnum({ enum: ReactionType, name: 'ReactionType' })
@ValidateEnum({ enum: ReactionType, name: 'ReactionType', description: 'Activity type (like or comment)' })
type!: ReactionType;
@ApiPropertyOptional({ description: 'Comment text (required if type is comment)' })
@ValidateIf(isComment)
@IsNotEmpty()
@IsString()
+12 -5
View File
@@ -1,15 +1,22 @@
import { mapAlbum } from 'src/dtos/album.dto';
import { albumStub } from 'test/fixtures/album.stub';
import { AlbumFactory } from 'test/factories/album.factory';
import { getForAlbum } from 'test/mappers';
describe('mapAlbum', () => {
it('should set start and end dates', () => {
const dto = mapAlbum(albumStub.twoAssets, false);
expect(dto.startDate).toEqual(new Date('2020-12-31T23:59:00.000Z'));
expect(dto.endDate).toEqual(new Date('2025-01-01T01:02:03.456Z'));
const startDate = new Date('2023-02-22T05:06:29.716Z');
const endDate = new Date('2025-01-01T01:02:03.456Z');
const album = AlbumFactory.from()
.asset({ localDateTime: endDate }, (builder) => builder.exif())
.asset({ localDateTime: startDate }, (builder) => builder.exif())
.build();
const dto = mapAlbum(getForAlbum(album), false);
expect(dto.startDate).toEqual(startDate.toISOString());
expect(dto.endDate).toEqual(endDate.toISOString());
});
it('should not set start and end dates for empty assets', () => {
const dto = mapAlbum(albumStub.empty, false);
const dto = mapAlbum(getForAlbum(AlbumFactory.create()), false);
expect(dto.startDate).toBeUndefined();
expect(dto.endDate).toBeUndefined();
});
+85 -53
View File
@@ -1,173 +1,201 @@
import { ApiProperty } from '@nestjs/swagger';
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import { Type } from 'class-transformer';
import { ArrayNotEmpty, IsArray, IsString, ValidateNested } from 'class-validator';
import { ShallowDehydrateObject } from 'kysely';
import _ from 'lodash';
import { AlbumUser, AuthSharedLink, User } from 'src/database';
import { BulkIdErrorReason } from 'src/dtos/asset-ids.response.dto';
import { AssetResponseDto, MapAsset, mapAsset } from 'src/dtos/asset-response.dto';
import { AuthDto } from 'src/dtos/auth.dto';
import { UserResponseDto, mapUser } from 'src/dtos/user.dto';
import { mapUser, UserResponseDto } from 'src/dtos/user.dto';
import { AlbumUserRole, AssetOrder } from 'src/enum';
import { MaybeDehydrated } from 'src/types';
import { asDateString } from 'src/utils/date';
import { Optional, ValidateBoolean, ValidateEnum, ValidateUUID } from 'src/validation';
export class AlbumInfoDto {
@ValidateBoolean({ optional: true })
@ValidateBoolean({ optional: true, description: 'Exclude assets from response' })
withoutAssets?: boolean;
}
export class AlbumUserAddDto {
@ValidateUUID()
@ValidateUUID({ description: 'User ID' })
userId!: string;
@ValidateEnum({ enum: AlbumUserRole, name: 'AlbumUserRole', default: AlbumUserRole.Editor })
@ValidateEnum({
enum: AlbumUserRole,
name: 'AlbumUserRole',
description: 'Album user role',
default: AlbumUserRole.Editor,
})
role?: AlbumUserRole;
}
export class AddUsersDto {
@ApiProperty({ description: 'Album users to add' })
@ArrayNotEmpty()
albumUsers!: AlbumUserAddDto[];
}
export class AlbumUserCreateDto {
@ValidateUUID()
@ValidateUUID({ description: 'User ID' })
userId!: string;
@ValidateEnum({ enum: AlbumUserRole, name: 'AlbumUserRole' })
@ValidateEnum({ enum: AlbumUserRole, name: 'AlbumUserRole', description: 'Album user role' })
role!: AlbumUserRole;
}
export class CreateAlbumDto {
@ApiProperty({ description: 'Album name' })
@IsString()
@ApiProperty()
albumName!: string;
@ApiPropertyOptional({ description: 'Album description' })
@IsString()
@Optional()
description?: string;
@ApiPropertyOptional({ description: 'Album users' })
@Optional()
@IsArray()
@ValidateNested({ each: true })
@Type(() => AlbumUserCreateDto)
albumUsers?: AlbumUserCreateDto[];
@ValidateUUID({ optional: true, each: true })
@ValidateUUID({ optional: true, each: true, description: 'Initial asset IDs' })
assetIds?: string[];
}
export class AlbumsAddAssetsDto {
@ValidateUUID({ each: true })
@ValidateUUID({ each: true, description: 'Album IDs' })
albumIds!: string[];
@ValidateUUID({ each: true })
@ValidateUUID({ each: true, description: 'Asset IDs' })
assetIds!: string[];
}
export class AlbumsAddAssetsResponseDto {
@ApiProperty({ description: 'Operation success' })
success!: boolean;
@ValidateEnum({ enum: BulkIdErrorReason, name: 'BulkIdErrorReason', optional: true })
@ValidateEnum({ enum: BulkIdErrorReason, name: 'BulkIdErrorReason', description: 'Error reason', optional: true })
error?: BulkIdErrorReason;
}
export class UpdateAlbumDto {
@ApiPropertyOptional({ description: 'Album name' })
@Optional()
@IsString()
albumName?: string;
@ApiPropertyOptional({ description: 'Album description' })
@Optional()
@IsString()
description?: string;
@ValidateUUID({ optional: true })
@ValidateUUID({ optional: true, description: 'Album thumbnail asset ID' })
albumThumbnailAssetId?: string;
@ValidateBoolean({ optional: true })
@ValidateBoolean({ optional: true, description: 'Enable activity feed' })
isActivityEnabled?: boolean;
@ValidateEnum({ enum: AssetOrder, name: 'AssetOrder', optional: true })
@ValidateEnum({ enum: AssetOrder, name: 'AssetOrder', description: 'Asset sort order', optional: true })
order?: AssetOrder;
}
export class GetAlbumsDto {
@ValidateBoolean({ optional: true })
/**
* true: only shared albums
* false: only non-shared own albums
* undefined: shared and owned albums
*/
@ValidateBoolean({
optional: true,
description: 'Filter by shared status: true = only shared, false = not shared, undefined = all owned albums',
})
shared?: boolean;
/**
* Only returns albums that contain the asset
* Ignores the shared parameter
* undefined: get all albums
*/
@ValidateUUID({ optional: true })
@ValidateUUID({ optional: true, description: 'Filter albums containing this asset ID (ignores shared parameter)' })
assetId?: string;
}
export class AlbumStatisticsResponseDto {
@ApiProperty({ type: 'integer' })
@ApiProperty({ type: 'integer', description: 'Number of owned albums' })
owned!: number;
@ApiProperty({ type: 'integer' })
@ApiProperty({ type: 'integer', description: 'Number of shared albums' })
shared!: number;
@ApiProperty({ type: 'integer' })
@ApiProperty({ type: 'integer', description: 'Number of non-shared albums' })
notShared!: number;
}
export class UpdateAlbumUserDto {
@ValidateEnum({ enum: AlbumUserRole, name: 'AlbumUserRole' })
@ValidateEnum({ enum: AlbumUserRole, name: 'AlbumUserRole', description: 'Album user role' })
role!: AlbumUserRole;
}
export class AlbumUserResponseDto {
// Description lives on schema to avoid duplication
@ApiProperty({ description: undefined })
user!: UserResponseDto;
@ValidateEnum({ enum: AlbumUserRole, name: 'AlbumUserRole' })
@ValidateEnum({ enum: AlbumUserRole, name: 'AlbumUserRole', description: 'Album user role' })
role!: AlbumUserRole;
}
export class ContributorCountResponseDto {
@ApiProperty()
@ApiProperty({ description: 'User ID' })
userId!: string;
@ApiProperty({ type: 'integer' })
@ApiProperty({ type: 'integer', description: 'Number of assets contributed' })
assetCount!: number;
}
export class AlbumResponseDto {
@ApiProperty({ description: 'Album ID' })
id!: string;
@ApiProperty({ description: 'Owner user ID' })
ownerId!: string;
@ApiProperty({ description: 'Album name' })
albumName!: string;
@ApiProperty({ description: 'Album description' })
description!: string;
createdAt!: Date;
updatedAt!: Date;
@ApiProperty({ description: 'Creation date', format: 'date-time' })
createdAt!: string;
@ApiProperty({ description: 'Last update date', format: 'date-time' })
updatedAt!: string;
@ApiProperty({ description: 'Thumbnail asset ID' })
albumThumbnailAssetId!: string | null;
@ApiProperty({ description: 'Is shared album' })
shared!: boolean;
// Description lives on schema to avoid duplication
@ApiProperty({ description: undefined })
albumUsers!: AlbumUserResponseDto[];
@ApiProperty({ description: 'Has shared link' })
hasSharedLink!: boolean;
// Description lives on schema to avoid duplication
@ApiProperty({ description: undefined })
assets!: AssetResponseDto[];
// Description lives on schema to avoid duplication
@ApiProperty({ description: undefined })
owner!: UserResponseDto;
@ApiProperty({ type: 'integer' })
@ApiProperty({ type: 'integer', description: 'Number of assets' })
assetCount!: number;
lastModifiedAssetTimestamp?: Date;
startDate?: Date;
endDate?: Date;
@ApiPropertyOptional({ description: 'Last modified asset timestamp', format: 'date-time' })
lastModifiedAssetTimestamp?: string;
@ApiPropertyOptional({ description: 'Start date (earliest asset)', format: 'date-time' })
startDate?: string;
@ApiPropertyOptional({ description: 'End date (latest asset)', format: 'date-time' })
endDate?: string;
@ApiProperty({ description: 'Activity feed enabled' })
isActivityEnabled!: boolean;
@ValidateEnum({ enum: AssetOrder, name: 'AssetOrder', optional: true })
@ValidateEnum({ enum: AssetOrder, name: 'AssetOrder', description: 'Asset sort order', optional: true })
order?: AssetOrder;
// Optional per-user contribution counts for shared albums
// Description lives on schema to avoid duplication
@ApiPropertyOptional({ description: undefined })
@Type(() => ContributorCountResponseDto)
@ApiProperty({ type: [ContributorCountResponseDto], required: false })
contributorCounts?: ContributorCountResponseDto[];
}
export type MapAlbumDto = {
albumUsers?: AlbumUser[];
assets?: MapAsset[];
sharedLinks?: AuthSharedLink[];
assets?: ShallowDehydrateObject<MapAsset>[];
sharedLinks?: ShallowDehydrateObject<AuthSharedLink>[];
albumName: string;
description: string;
albumThumbnailAssetId: string | null;
@@ -175,12 +203,16 @@ export type MapAlbumDto = {
updatedAt: Date;
id: string;
ownerId: string;
owner: User;
owner: ShallowDehydrateObject<User>;
isActivityEnabled: boolean;
order: AssetOrder;
};
export const mapAlbum = (entity: MapAlbumDto, withAssets: boolean, auth?: AuthDto): AlbumResponseDto => {
export const mapAlbum = (
entity: MaybeDehydrated<MapAlbumDto>,
withAssets: boolean,
auth?: AuthDto,
): AlbumResponseDto => {
const albumUsers: AlbumUserResponseDto[] = [];
if (entity.albumUsers) {
@@ -211,16 +243,16 @@ export const mapAlbum = (entity: MapAlbumDto, withAssets: boolean, auth?: AuthDt
albumName: entity.albumName,
description: entity.description,
albumThumbnailAssetId: entity.albumThumbnailAssetId,
createdAt: entity.createdAt,
updatedAt: entity.updatedAt,
createdAt: asDateString(entity.createdAt),
updatedAt: asDateString(entity.updatedAt),
id: entity.id,
ownerId: entity.ownerId,
owner: mapUser(entity.owner),
albumUsers: albumUsersSorted,
shared: hasSharedUser || hasSharedLink,
hasSharedLink,
startDate,
endDate,
startDate: asDateString(startDate),
endDate: asDateString(endDate),
assets: (withAssets ? assets : []).map((asset) => mapAsset(asset, { auth })),
assetCount: entity.assets?.length || 0,
isActivityEnabled: entity.isActivityEnabled,
@@ -228,5 +260,5 @@ export const mapAlbum = (entity: MapAlbumDto, withAssets: boolean, auth?: AuthDt
};
};
export const mapAlbumWithAssets = (entity: MapAlbumDto) => mapAlbum(entity, true);
export const mapAlbumWithoutAssets = (entity: MapAlbumDto) => mapAlbum(entity, false);
export const mapAlbumWithAssets = (entity: MaybeDehydrated<MapAlbumDto>) => mapAlbum(entity, true);
export const mapAlbumWithoutAssets = (entity: MaybeDehydrated<MapAlbumDto>) => mapAlbum(entity, false);
+25 -8
View File
@@ -1,38 +1,55 @@
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import { ArrayMinSize, IsNotEmpty, IsString } from 'class-validator';
import { Permission } from 'src/enum';
import { Optional, ValidateEnum } from 'src/validation';
export class APIKeyCreateDto {
@ApiPropertyOptional({ description: 'API key name' })
@IsString()
@IsNotEmpty()
@Optional()
name?: string;
@ValidateEnum({ enum: Permission, name: 'Permission', each: true })
@ValidateEnum({ enum: Permission, name: 'Permission', each: true, description: 'List of permissions' })
@ArrayMinSize(1)
permissions!: Permission[];
}
export class APIKeyUpdateDto {
@ApiPropertyOptional({ description: 'API key name' })
@Optional()
@IsString()
@IsNotEmpty()
name?: string;
@ValidateEnum({ enum: Permission, name: 'Permission', each: true, optional: true })
@ValidateEnum({
enum: Permission,
name: 'Permission',
description: 'List of permissions',
each: true,
optional: true,
})
@ArrayMinSize(1)
permissions?: Permission[];
}
export class APIKeyCreateResponseDto {
secret!: string;
apiKey!: APIKeyResponseDto;
}
export class APIKeyResponseDto {
@ApiProperty({ description: 'API key ID' })
id!: string;
@ApiProperty({ description: 'API key name' })
name!: string;
@ApiProperty({ description: 'Creation date' })
createdAt!: Date;
@ApiProperty({ description: 'Last update date' })
updatedAt!: Date;
@ValidateEnum({ enum: Permission, name: 'Permission', each: true })
@ValidateEnum({ enum: Permission, name: 'Permission', each: true, description: 'List of permissions' })
permissions!: Permission[];
}
export class APIKeyCreateResponseDto {
@ApiProperty({ description: 'API key secret (only shown once)' })
secret!: string;
// Description lives on schema to avoid duplication
@ApiProperty({ description: undefined })
apiKey!: APIKeyResponseDto;
}
+10 -1
View File
@@ -1,3 +1,4 @@
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import { ValidateUUID } from 'src/validation';
/** @deprecated Use `BulkIdResponseDto` instead */
@@ -9,8 +10,11 @@ export enum AssetIdErrorReason {
/** @deprecated Use `BulkIdResponseDto` instead */
export class AssetIdsResponseDto {
@ApiProperty({ description: 'Asset ID' })
assetId!: string;
@ApiProperty({ description: 'Whether operation succeeded' })
success!: boolean;
@ApiPropertyOptional({ description: 'Error reason if failed', enum: AssetIdErrorReason })
error?: AssetIdErrorReason;
}
@@ -19,15 +23,20 @@ export enum BulkIdErrorReason {
NO_PERMISSION = 'no_permission',
NOT_FOUND = 'not_found',
UNKNOWN = 'unknown',
VALIDATION = 'validation',
}
export class BulkIdsDto {
@ValidateUUID({ each: true })
@ValidateUUID({ each: true, description: 'IDs to process' })
ids!: string[];
}
export class BulkIdResponseDto {
@ApiProperty({ description: 'ID' })
id!: string;
@ApiProperty({ description: 'Whether operation succeeded' })
success!: boolean;
@ApiPropertyOptional({ description: 'Error reason if failed', enum: BulkIdErrorReason })
error?: BulkIdErrorReason;
errorMessage?: string;
}
+10 -1
View File
@@ -1,3 +1,4 @@
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import { ValidateEnum } from 'src/validation';
export enum AssetMediaStatus {
@@ -6,8 +7,9 @@ export enum AssetMediaStatus {
DUPLICATE = 'duplicate',
}
export class AssetMediaResponseDto {
@ValidateEnum({ enum: AssetMediaStatus, name: 'AssetMediaStatus' })
@ValidateEnum({ enum: AssetMediaStatus, name: 'AssetMediaStatus', description: 'Upload status' })
status!: AssetMediaStatus;
@ApiProperty({ description: 'Asset media ID' })
id!: string;
}
@@ -22,17 +24,24 @@ export enum AssetRejectReason {
}
export class AssetBulkUploadCheckResult {
@ApiProperty({ description: 'Asset ID' })
id!: string;
@ApiProperty({ description: 'Upload action', enum: AssetUploadAction })
action!: AssetUploadAction;
@ApiPropertyOptional({ description: 'Rejection reason if rejected', enum: AssetRejectReason })
reason?: AssetRejectReason;
@ApiPropertyOptional({ description: 'Existing asset ID if duplicate' })
assetId?: string;
@ApiPropertyOptional({ description: 'Whether existing asset is trashed' })
isTrashed?: boolean;
}
export class AssetBulkUploadCheckResponseDto {
@ApiProperty({ description: 'Upload check results' })
results!: AssetBulkUploadCheckResult[];
}
export class CheckExistingAssetsResponseDto {
@ApiProperty({ description: 'Existing asset IDs' })
existingIds!: string[];
}
+24 -11
View File
@@ -1,5 +1,5 @@
import { BadRequestException } from '@nestjs/common';
import { ApiProperty } from '@nestjs/swagger';
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import { plainToInstance, Transform, Type } from 'class-transformer';
import { ArrayNotEmpty, IsArray, IsNotEmpty, IsString, ValidateNested } from 'class-validator';
import { AssetMetadataUpsertItemDto } from 'src/dtos/asset.dto';
@@ -7,6 +7,7 @@ import { AssetVisibility } from 'src/enum';
import { Optional, ValidateBoolean, ValidateDate, ValidateEnum, ValidateUUID } from 'src/validation';
export enum AssetMediaSize {
Original = 'original',
/**
* An full-sized image extracted/converted from non-web-friendly formats like RAW/HIF.
* or otherwise the original image itself.
@@ -17,8 +18,11 @@ export enum AssetMediaSize {
}
export class AssetMediaOptionsDto {
@ValidateEnum({ enum: AssetMediaSize, name: 'AssetMediaSize', optional: true })
@ValidateEnum({ enum: AssetMediaSize, name: 'AssetMediaSize', description: 'Asset media size', optional: true })
size?: AssetMediaSize;
@ValidateBoolean({ optional: true, description: 'Return edited asset if available', default: false })
edited?: boolean;
}
export enum UploadFieldName {
@@ -28,44 +32,49 @@ export enum UploadFieldName {
}
class AssetMediaBase {
@ApiProperty({ description: 'Device asset ID' })
@IsNotEmpty()
@IsString()
deviceAssetId!: string;
@ApiProperty({ description: 'Device ID' })
@IsNotEmpty()
@IsString()
deviceId!: string;
@ValidateDate()
@ValidateDate({ description: 'File creation date' })
fileCreatedAt!: Date;
@ValidateDate()
@ValidateDate({ description: 'File modification date' })
fileModifiedAt!: Date;
@ApiPropertyOptional({ description: 'Duration (for videos)' })
@Optional()
@IsString()
duration?: string;
@ApiPropertyOptional({ description: 'Filename' })
@Optional()
@IsString()
filename?: string;
// The properties below are added to correctly generate the API docs
// and client SDKs. Validation should be handled in the controller.
@ApiProperty({ type: 'string', format: 'binary' })
@ApiProperty({ type: 'string', format: 'binary', description: 'Asset file data' })
[UploadFieldName.ASSET_DATA]!: any;
}
export class AssetMediaCreateDto extends AssetMediaBase {
@ValidateBoolean({ optional: true })
@ValidateBoolean({ optional: true, description: 'Mark as favorite' })
isFavorite?: boolean;
@ValidateEnum({ enum: AssetVisibility, name: 'AssetVisibility', optional: true })
@ValidateEnum({ enum: AssetVisibility, name: 'AssetVisibility', description: 'Asset visibility', optional: true })
visibility?: AssetVisibility;
@ValidateUUID({ optional: true })
@ValidateUUID({ optional: true, description: 'Live photo video ID' })
livePhotoVideoId?: string;
@ApiPropertyOptional({ description: 'Asset metadata items' })
@Transform(({ value }) => {
try {
const json = JSON.parse(value);
@@ -78,26 +87,28 @@ export class AssetMediaCreateDto extends AssetMediaBase {
@Optional()
@ValidateNested({ each: true })
@IsArray()
metadata!: AssetMetadataUpsertItemDto[];
metadata?: AssetMetadataUpsertItemDto[];
@ApiProperty({ type: 'string', format: 'binary', required: false })
@ApiProperty({ type: 'string', format: 'binary', required: false, description: 'Sidecar file data' })
[UploadFieldName.SIDECAR_DATA]?: any;
}
export class AssetMediaReplaceDto extends AssetMediaBase {}
export class AssetBulkUploadCheckItem {
@ApiProperty({ description: 'Asset ID' })
@IsString()
@IsNotEmpty()
id!: string;
/** base64 or hex encoded sha1 hash */
@ApiProperty({ description: 'Base64 or hex encoded SHA1 hash' })
@IsString()
@IsNotEmpty()
checksum!: string;
}
export class AssetBulkUploadCheckDto {
@ApiProperty({ description: 'Assets to check' })
@IsArray()
@ValidateNested({ each: true })
@Type(() => AssetBulkUploadCheckItem)
@@ -105,11 +116,13 @@ export class AssetBulkUploadCheckDto {
}
export class CheckExistingAssetsDto {
@ApiProperty({ description: 'Device asset IDs to check' })
@ArrayNotEmpty()
@IsString({ each: true })
@IsNotEmpty({ each: true })
deviceAssetIds!: string[];
@ApiProperty({ description: 'Device ID' })
@IsNotEmpty()
deviceId!: string;
}
+192
View File
@@ -0,0 +1,192 @@
import { mapAsset } from 'src/dtos/asset-response.dto';
import { AssetEditAction } from 'src/dtos/editing.dto';
import { AssetFaceFactory } from 'test/factories/asset-face.factory';
import { AssetFactory } from 'test/factories/asset.factory';
import { PersonFactory } from 'test/factories/person.factory';
import { getForAsset } from 'test/mappers';
describe('mapAsset', () => {
describe('peopleWithFaces', () => {
it('should transform all faces when a person has multiple faces in the same image', () => {
const person = PersonFactory.create();
const face1 = {
boundingBoxX1: 100,
boundingBoxY1: 100,
boundingBoxX2: 200,
boundingBoxY2: 200,
imageWidth: 1000,
imageHeight: 800,
};
const face2 = {
boundingBoxX1: 300,
boundingBoxY1: 400,
boundingBoxX2: 400,
boundingBoxY2: 500,
imageWidth: 1000,
imageHeight: 800,
};
const asset = AssetFactory.from()
.face(face1, (builder) => builder.person(person))
.face(face2, (builder) => builder.person(person))
.exif({ exifImageWidth: 1000, exifImageHeight: 800 })
.edit({
action: AssetEditAction.Crop,
parameters: {
width: 1512,
height: 1152,
x: 216,
y: 1512,
},
})
.build();
const result = mapAsset(getForAsset(asset));
expect(result.people).toBeDefined();
expect(result.people).toHaveLength(1);
expect(result.people![0].faces).toHaveLength(2);
// Verify that both faces have been transformed (bounding boxes adjusted for crop)
const firstFace = result.people![0].faces[0];
const secondFace = result.people![0].faces[1];
// After crop (x: 216, y: 1512), the coordinates should be adjusted
// Faces outside the crop area will be clamped
expect(firstFace.boundingBoxX1).toBe(-116); // 100 - 216 = -116
expect(firstFace.boundingBoxY1).toBe(-1412); // 100 - 1512 = -1412
expect(firstFace.boundingBoxX2).toBe(-16); // 200 - 216 = -16
expect(firstFace.boundingBoxY2).toBe(-1312); // 200 - 1512 = -1312
expect(secondFace.boundingBoxX1).toBe(84); // 300 - 216
expect(secondFace.boundingBoxY1).toBe(-1112); // 400 - 1512 = -1112
expect(secondFace.boundingBoxX2).toBe(184); // 400 - 216
expect(secondFace.boundingBoxY2).toBe(-1012); // 500 - 1512 = -1012
});
it('should transform unassigned faces with edits and dimensions', () => {
const unassignedFace = AssetFaceFactory.create({
boundingBoxX1: 100,
boundingBoxY1: 100,
boundingBoxX2: 200,
boundingBoxY2: 200,
imageWidth: 1000,
imageHeight: 800,
});
const asset = AssetFactory.from()
.face(unassignedFace)
.exif({ exifImageWidth: 1000, exifImageHeight: 800 })
.edit({ action: AssetEditAction.Crop, parameters: { x: 50, y: 50, width: 500, height: 400 } })
.build();
const result = mapAsset(getForAsset(asset));
expect(result.unassignedFaces).toBeDefined();
expect(result.unassignedFaces).toHaveLength(1);
// Verify that unassigned face has been transformed
const face = result.unassignedFaces![0];
expect(face.boundingBoxX1).toBe(50); // 100 - 50
expect(face.boundingBoxY1).toBe(50); // 100 - 50
expect(face.boundingBoxX2).toBe(150); // 200 - 50
expect(face.boundingBoxY2).toBe(150); // 200 - 50
});
it('should handle multiple people each with multiple faces', () => {
const person1Face1 = {
boundingBoxX1: 100,
boundingBoxY1: 100,
boundingBoxX2: 200,
boundingBoxY2: 200,
imageWidth: 1000,
imageHeight: 800,
};
const person1Face2 = {
boundingBoxX1: 300,
boundingBoxY1: 300,
boundingBoxX2: 400,
boundingBoxY2: 400,
imageWidth: 1000,
imageHeight: 800,
};
const person2Face1 = {
boundingBoxX1: 500,
boundingBoxY1: 100,
boundingBoxX2: 600,
boundingBoxY2: 200,
imageWidth: 1000,
imageHeight: 800,
};
const person = PersonFactory.create({ id: 'person-1' });
const asset = AssetFactory.from()
.face(person1Face1, (builder) => builder.person(person))
.face(person1Face2, (builder) => builder.person(person))
.face(person2Face1, (builder) => builder.person({ id: 'person-2' }))
.exif({ exifImageWidth: 1000, exifImageHeight: 800 })
.build();
const result = mapAsset(getForAsset(asset));
expect(result.people).toBeDefined();
expect(result.people).toHaveLength(2);
const person1 = result.people!.find((p) => p.id === 'person-1');
const person2 = result.people!.find((p) => p.id === 'person-2');
expect(person1).toBeDefined();
expect(person1!.faces).toHaveLength(2);
// No edits, so coordinates should be unchanged
expect(person1!.faces[0].boundingBoxX1).toBe(100);
expect(person1!.faces[0].boundingBoxY1).toBe(100);
expect(person1!.faces[1].boundingBoxX1).toBe(300);
expect(person1!.faces[1].boundingBoxY1).toBe(300);
expect(person2).toBeDefined();
expect(person2!.faces).toHaveLength(1);
expect(person2!.faces[0].boundingBoxX1).toBe(500);
expect(person2!.faces[0].boundingBoxY1).toBe(100);
});
it('should combine faces of the same person into a single entry', () => {
const face1 = {
boundingBoxX1: 100,
boundingBoxY1: 100,
boundingBoxX2: 200,
boundingBoxY2: 200,
imageWidth: 1000,
imageHeight: 800,
};
const face2 = {
boundingBoxX1: 300,
boundingBoxY1: 300,
boundingBoxX2: 400,
boundingBoxY2: 400,
imageWidth: 1000,
imageHeight: 800,
};
const person = PersonFactory.create();
const asset = AssetFactory.from()
.face(face1, (builder) => builder.person(person))
.face(face2, (builder) => builder.person(person))
.exif({ exifImageWidth: 1000, exifImageHeight: 800 })
.build();
const result = mapAsset(getForAsset(asset));
expect(result.people).toBeDefined();
expect(result.people).toHaveLength(1);
expect(result.people![0].id).toBe(person.id);
expect(result.people![0].faces).toHaveLength(2);
});
});
});
+117 -48
View File
@@ -1,8 +1,9 @@
import { ApiProperty } from '@nestjs/swagger';
import { Selectable } from 'kysely';
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import { Selectable, ShallowDehydrateObject } from 'kysely';
import { AssetFace, AssetFile, Exif, Stack, Tag, User } from 'src/database';
import { PropertyLifecycle } from 'src/decorators';
import { HistoryBuilder, Property } from 'src/decorators';
import { AuthDto } from 'src/dtos/auth.dto';
import { AssetEditActionItem } from 'src/dtos/editing.dto';
import { ExifResponseDto, mapExif } from 'src/dtos/exif.dto';
import {
AssetFaceWithoutPersonResponseDto,
@@ -12,16 +13,25 @@ import {
} from 'src/dtos/person.dto';
import { TagResponseDto, mapTag } from 'src/dtos/tag.dto';
import { UserResponseDto, mapUser } from 'src/dtos/user.dto';
import { AssetStatus, AssetType, AssetVisibility } from 'src/enum';
import { AssetStatus, AssetType, AssetVisibility, ChecksumAlgorithm } from 'src/enum';
import { ImageDimensions, MaybeDehydrated } from 'src/types';
import { getDimensions } from 'src/utils/asset.util';
import { hexOrBufferToBase64 } from 'src/utils/bytes';
import { asDateString } from 'src/utils/date';
import { mimeTypes } from 'src/utils/mime-types';
import { ValidateEnum } from 'src/validation';
import { ValidateEnum, ValidateUUID } from 'src/validation';
export class SanitizedAssetResponseDto {
@ApiProperty({ description: 'Asset ID' })
id!: string;
@ValidateEnum({ enum: AssetType, name: 'AssetTypeEnum' })
@ValidateEnum({ enum: AssetType, name: 'AssetTypeEnum', description: 'Asset type' })
type!: AssetType;
@ApiProperty({
description:
'Thumbhash for thumbnail generation (base64) also used as the c query param for thumbnail cache busting.',
})
thumbhash!: string | null;
@ApiPropertyOptional({ description: 'Original MIME type' })
originalMimeType?: string;
@ApiProperty({
type: 'string',
@@ -30,10 +40,17 @@ export class SanitizedAssetResponseDto {
'The local date and time when the photo/video was taken, derived from EXIF metadata. This represents the photographer\'s local time regardless of timezone, stored as a timezone-agnostic timestamp. Used for timeline grouping by "local" days and months.',
example: '2024-01-15T14:30:00.000Z',
})
localDateTime!: Date;
localDateTime!: string;
@ApiProperty({ description: 'Video duration (for videos)' })
duration!: string;
@ApiPropertyOptional({ description: 'Live photo video ID' })
livePhotoVideoId?: string | null;
@ApiProperty({ description: 'Whether asset has metadata' })
hasMetadata!: boolean;
@ApiProperty({ description: 'Asset width' })
width!: number | null;
@ApiProperty({ description: 'Asset height' })
height!: number | null;
}
export class AssetResponseDto extends SanitizedAssetResponseDto {
@@ -43,14 +60,25 @@ export class AssetResponseDto extends SanitizedAssetResponseDto {
description: 'The UTC timestamp when the asset was originally uploaded to Immich.',
example: '2024-01-15T20:30:00.000Z',
})
createdAt!: Date;
createdAt!: string;
@ApiProperty({ description: 'Device asset ID' })
deviceAssetId!: string;
@ApiProperty({ description: 'Device ID' })
deviceId!: string;
@ApiProperty({ description: 'Owner user ID' })
ownerId!: string;
// Description lives on schema to avoid duplication
@ApiPropertyOptional({ description: undefined })
owner?: UserResponseDto;
@PropertyLifecycle({ deprecatedAt: 'v1.106.0' })
@ValidateUUID({
nullable: true,
description: 'Library ID',
history: new HistoryBuilder().added('v1').deprecated('v1'),
})
libraryId?: string | null;
@ApiProperty({ description: 'Original file path' })
originalPath!: string;
@ApiProperty({ description: 'Original file name' })
originalFileName!: string;
@ApiProperty({
type: 'string',
@@ -59,7 +87,7 @@ export class AssetResponseDto extends SanitizedAssetResponseDto {
'The actual UTC timestamp when the file was created/captured, preserving timezone information. This is the authoritative timestamp for chronological sorting within timeline groups. Combined with timezone data, this can be used to determine the exact moment the photo was taken.',
example: '2024-01-15T19:30:00.000Z',
})
fileCreatedAt!: Date;
fileCreatedAt!: string;
@ApiProperty({
type: 'string',
format: 'date-time',
@@ -67,7 +95,7 @@ export class AssetResponseDto extends SanitizedAssetResponseDto {
'The UTC timestamp when the file was last modified on the filesystem. This reflects the last time the physical file was changed, which may be different from when the photo was originally taken.',
example: '2024-01-16T10:15:00.000Z',
})
fileModifiedAt!: Date;
fileModifiedAt!: string;
@ApiProperty({
type: 'string',
format: 'date-time',
@@ -75,24 +103,41 @@ export class AssetResponseDto extends SanitizedAssetResponseDto {
'The UTC timestamp when the asset record was last updated in the database. This is automatically maintained by the database and reflects when any field in the asset was last modified.',
example: '2024-01-16T12:45:30.000Z',
})
updatedAt!: Date;
updatedAt!: string;
@ApiProperty({ description: 'Is favorite' })
isFavorite!: boolean;
@ApiProperty({ description: 'Is archived' })
isArchived!: boolean;
@ApiProperty({ description: 'Is trashed' })
isTrashed!: boolean;
@ApiProperty({ description: 'Is offline' })
isOffline!: boolean;
@ValidateEnum({ enum: AssetVisibility, name: 'AssetVisibility' })
@ValidateEnum({ enum: AssetVisibility, name: 'AssetVisibility', description: 'Asset visibility' })
visibility!: AssetVisibility;
// Description lives on schema to avoid duplication
@ApiPropertyOptional({ description: undefined })
exifInfo?: ExifResponseDto;
// Description lives on schema to avoid duplication
@ApiPropertyOptional({ description: undefined })
tags?: TagResponseDto[];
// Description lives on schema to avoid duplication
@ApiPropertyOptional({ description: undefined })
people?: PersonWithFacesResponseDto[];
// Description lives on schema to avoid duplication
@ApiPropertyOptional({ description: undefined })
unassignedFaces?: AssetFaceWithoutPersonResponseDto[];
/**base64 encoded sha1 hash */
@ApiProperty({ description: 'Base64 encoded SHA1 hash' })
checksum!: string;
// Description lives on schema to avoid duplication
@ApiPropertyOptional({ description: undefined })
stack?: AssetStackResponseDto | null;
@ApiPropertyOptional({ description: 'Duplicate group ID' })
duplicateId?: string | null;
@PropertyLifecycle({ deprecatedAt: 'v1.113.0' })
@Property({ description: 'Is resized', history: new HistoryBuilder().added('v1').deprecated('v1.113.0') })
resized?: boolean;
@Property({ description: 'Is edited', history: new HistoryBuilder().added('v2.5.0').beta('v2.5.0') })
isEdited!: boolean;
}
export type MapAsset = {
@@ -103,16 +148,17 @@ export type MapAsset = {
updateId: string;
status: AssetStatus;
checksum: Buffer<ArrayBufferLike>;
checksumAlgorithm: ChecksumAlgorithm;
deviceAssetId: string;
deviceId: string;
duplicateId: string | null;
duration: string | null;
encodedVideoPath: string | null;
exifInfo?: Selectable<Exif> | null;
faces?: AssetFace[];
edits?: ShallowDehydrateObject<AssetEditActionItem>[];
exifInfo?: ShallowDehydrateObject<Selectable<Exif>> | null;
faces?: ShallowDehydrateObject<AssetFace>[];
fileCreatedAt: Date;
fileModifiedAt: Date;
files?: AssetFile[];
files?: ShallowDehydrateObject<AssetFile>[];
isExternal: boolean;
isFavorite: boolean;
isOffline: boolean;
@@ -122,22 +168,26 @@ export type MapAsset = {
localDateTime: Date;
originalFileName: string;
originalPath: string;
owner?: User | null;
owner?: ShallowDehydrateObject<User> | null;
ownerId: string;
sidecarPath: string | null;
stack?: Stack | null;
stack?: (ShallowDehydrateObject<Stack> & { assets: Stack['assets'] }) | null;
stackId: string | null;
tags?: Tag[];
tags?: ShallowDehydrateObject<Tag>[];
thumbhash: Buffer<ArrayBufferLike> | null;
type: AssetType;
width: number | null;
height: number | null;
isEdited: boolean;
};
export class AssetStackResponseDto {
@ApiProperty({ description: 'Stack ID' })
id!: string;
@ApiProperty({ description: 'Primary asset ID' })
primaryAssetId!: string;
@ApiProperty({ type: 'integer' })
@ApiProperty({ type: 'integer', description: 'Number of assets in stack' })
assetCount!: number;
}
@@ -147,23 +197,33 @@ export type AssetMapOptions = {
auth?: AuthDto;
};
// TODO: this is inefficient
const peopleWithFaces = (faces?: AssetFace[]): PersonWithFacesResponseDto[] => {
const result: PersonWithFacesResponseDto[] = [];
if (faces) {
for (const face of faces) {
if (face.person) {
const existingPersonEntry = result.find((item) => item.id === face.person!.id);
if (existingPersonEntry) {
existingPersonEntry.faces.push(face);
} else {
result.push({ ...mapPerson(face.person!), faces: [mapFacesWithoutPerson(face)] });
}
}
}
const peopleWithFaces = (
faces?: MaybeDehydrated<AssetFace>[],
edits?: AssetEditActionItem[],
assetDimensions?: ImageDimensions,
): PersonWithFacesResponseDto[] => {
if (!faces) {
return [];
}
return result;
const peopleFaces: Map<string, PersonWithFacesResponseDto> = new Map();
for (const face of faces) {
if (!face.person) {
continue;
}
if (!peopleFaces.has(face.person.id)) {
peopleFaces.set(face.person.id, {
...mapPerson(face.person),
faces: [],
});
}
const mappedFace = mapFacesWithoutPerson(face, edits, assetDimensions);
peopleFaces.get(face.person.id)!.faces.push(mappedFace);
}
return [...peopleFaces.values()];
};
const mapStack = (entity: { stack?: Stack | null }) => {
@@ -178,7 +238,7 @@ const mapStack = (entity: { stack?: Stack | null }) => {
};
};
export function mapAsset(entity: MapAsset, options: AssetMapOptions = {}): AssetResponseDto {
export function mapAsset(entity: MaybeDehydrated<MapAsset>, options: AssetMapOptions = {}): AssetResponseDto {
const { stripMetadata = false, withStack = false } = options;
if (stripMetadata) {
@@ -187,17 +247,21 @@ export function mapAsset(entity: MapAsset, options: AssetMapOptions = {}): Asset
type: entity.type,
originalMimeType: mimeTypes.lookup(entity.originalFileName),
thumbhash: entity.thumbhash ? hexOrBufferToBase64(entity.thumbhash) : null,
localDateTime: entity.localDateTime,
localDateTime: asDateString(entity.localDateTime),
duration: entity.duration ?? '0:00:00.00000',
livePhotoVideoId: entity.livePhotoVideoId,
hasMetadata: false,
width: entity.width,
height: entity.height,
};
return sanitizedAssetResponse as AssetResponseDto;
}
const assetDimensions = entity.exifInfo ? getDimensions(entity.exifInfo) : undefined;
return {
id: entity.id,
createdAt: entity.createdAt,
createdAt: asDateString(entity.createdAt),
deviceAssetId: entity.deviceAssetId,
ownerId: entity.ownerId,
owner: entity.owner ? mapUser(entity.owner) : undefined,
@@ -208,10 +272,10 @@ export function mapAsset(entity: MapAsset, options: AssetMapOptions = {}): Asset
originalFileName: entity.originalFileName,
originalMimeType: mimeTypes.lookup(entity.originalFileName),
thumbhash: entity.thumbhash ? hexOrBufferToBase64(entity.thumbhash) : null,
fileCreatedAt: entity.fileCreatedAt,
fileModifiedAt: entity.fileModifiedAt,
localDateTime: entity.localDateTime,
updatedAt: entity.updatedAt,
fileCreatedAt: asDateString(entity.fileCreatedAt),
fileModifiedAt: asDateString(entity.fileModifiedAt),
localDateTime: asDateString(entity.localDateTime),
updatedAt: asDateString(entity.updatedAt),
isFavorite: options.auth?.user.id === entity.ownerId && entity.isFavorite,
isArchived: entity.visibility === AssetVisibility.Archive,
isTrashed: !!entity.deletedAt,
@@ -220,13 +284,18 @@ export function mapAsset(entity: MapAsset, options: AssetMapOptions = {}): Asset
exifInfo: entity.exifInfo ? mapExif(entity.exifInfo) : undefined,
livePhotoVideoId: entity.livePhotoVideoId,
tags: entity.tags?.map((tag) => mapTag(tag)),
people: peopleWithFaces(entity.faces),
unassignedFaces: entity.faces?.filter((face) => !face.person).map((a) => mapFacesWithoutPerson(a)),
people: peopleWithFaces(entity.faces, entity.edits, assetDimensions),
unassignedFaces: entity.faces
?.filter((face) => !face.person)
.map((face) => mapFacesWithoutPerson(face, entity.edits, assetDimensions)),
checksum: hexOrBufferToBase64(entity.checksum)!,
stack: withStack ? mapStack(entity) : undefined,
isOffline: entity.isOffline,
hasMetadata: true,
duplicateId: entity.duplicateId,
resized: true,
width: entity.width,
height: entity.height,
isEdited: entity.isEdited,
};
}
+102 -51
View File
@@ -1,5 +1,5 @@
import { ApiProperty } from '@nestjs/swagger';
import { Type } from 'class-transformer';
import { Transform, Type } from 'class-transformer';
import {
IsArray,
IsDateString,
@@ -16,13 +16,14 @@ import {
ValidateIf,
ValidateNested,
} from 'class-validator';
import { HistoryBuilder, Property } from 'src/decorators';
import { BulkIdsDto } from 'src/dtos/asset-ids.response.dto';
import { AssetMetadataKey, AssetType, AssetVisibility } from 'src/enum';
import { AssetType, AssetVisibility } from 'src/enum';
import { AssetStats } from 'src/repositories/asset.repository';
import { AssetMetadata, AssetMetadataItem } from 'src/types';
import { IsNotSiblingOf, Optional, ValidateBoolean, ValidateEnum, ValidateUUID } from 'src/validation';
import { IsNotSiblingOf, Optional, ValidateBoolean, ValidateEnum, ValidateString, ValidateUUID } from 'src/validation';
export class DeviceIdDto {
@ApiProperty({ description: 'Device ID' })
@IsNotEmpty()
@IsString()
deviceId!: string;
@@ -33,49 +34,63 @@ const hasGPS = (o: { latitude: undefined; longitude: undefined }) =>
const ValidateGPS = () => ValidateIf(hasGPS);
export class UpdateAssetBase {
@ValidateBoolean({ optional: true })
@ValidateBoolean({ optional: true, description: 'Mark as favorite' })
isFavorite?: boolean;
@ValidateEnum({ enum: AssetVisibility, name: 'AssetVisibility', optional: true })
@ValidateEnum({ enum: AssetVisibility, name: 'AssetVisibility', optional: true, description: 'Asset visibility' })
visibility?: AssetVisibility;
@ApiProperty({ description: 'Original date and time' })
@Optional()
@IsDateString()
dateTimeOriginal?: string;
@ApiProperty({ description: 'Latitude coordinate' })
@ValidateGPS()
@IsLatitude()
@IsNotEmpty()
latitude?: number;
@ApiProperty({ description: 'Longitude coordinate' })
@ValidateGPS()
@IsLongitude()
@IsNotEmpty()
longitude?: number;
@Optional()
@Property({
description: 'Rating in range [1-5], or null for unrated',
history: new HistoryBuilder()
.added('v1')
.stable('v2')
.updated('v2.6.0', 'Using -1 as a rating is deprecated and will be removed in the next major version.'),
})
@Optional({ nullable: true })
@IsInt()
@Max(5)
@Min(-1)
rating?: number;
@Transform(({ value }) => (value === 0 ? null : value))
rating?: number | null;
@ApiProperty({ description: 'Asset description' })
@Optional()
@IsString()
description?: string;
}
export class AssetBulkUpdateDto extends UpdateAssetBase {
@ValidateUUID({ each: true })
@ValidateUUID({ each: true, description: 'Asset IDs to update' })
ids!: string[];
@Optional()
@ValidateString({ optional: true, nullable: true, description: 'Duplicate ID' })
duplicateId?: string | null;
@ApiProperty({ description: 'Relative time offset in seconds' })
@IsNotSiblingOf(['dateTimeOriginal'])
@Optional()
@IsInt()
dateTimeRelative?: number;
@ApiProperty({ description: 'Time zone (IANA timezone)' })
@IsNotSiblingOf(['dateTimeOriginal'])
@IsTimeZone()
@Optional()
@@ -83,11 +98,12 @@ export class AssetBulkUpdateDto extends UpdateAssetBase {
}
export class UpdateAssetDto extends UpdateAssetBase {
@ValidateUUID({ optional: true, nullable: true })
@ValidateUUID({ optional: true, nullable: true, description: 'Live photo video ID' })
livePhotoVideoId?: string | null;
}
export class RandomAssetsDto {
@ApiProperty({ description: 'Number of random assets to return' })
@Optional()
@IsInt()
@IsPositive()
@@ -96,12 +112,12 @@ export class RandomAssetsDto {
}
export class AssetBulkDeleteDto extends BulkIdsDto {
@ValidateBoolean({ optional: true })
@ValidateBoolean({ optional: true, description: 'Force delete even if in use' })
force?: boolean;
}
export class AssetIdsDto {
@ValidateUUID({ each: true })
@ValidateUUID({ each: true, description: 'Asset IDs' })
assetIds!: string[];
}
@@ -113,102 +129,137 @@ export enum AssetJobName {
}
export class AssetJobsDto extends AssetIdsDto {
@ValidateEnum({ enum: AssetJobName, name: 'AssetJobName' })
@ValidateEnum({ enum: AssetJobName, name: 'AssetJobName', description: 'Job name' })
name!: AssetJobName;
}
export class AssetStatsDto {
@ValidateEnum({ enum: AssetVisibility, name: 'AssetVisibility', optional: true })
@ValidateEnum({ enum: AssetVisibility, name: 'AssetVisibility', description: 'Filter by visibility', optional: true })
visibility?: AssetVisibility;
@ValidateBoolean({ optional: true })
@ValidateBoolean({ optional: true, description: 'Filter by favorite status' })
isFavorite?: boolean;
@ValidateBoolean({ optional: true })
@ValidateBoolean({ optional: true, description: 'Filter by trash status' })
isTrashed?: boolean;
}
export class AssetStatsResponseDto {
@ApiProperty({ type: 'integer' })
@ApiProperty({ description: 'Number of images', type: 'integer' })
images!: number;
@ApiProperty({ type: 'integer' })
@ApiProperty({ description: 'Number of videos', type: 'integer' })
videos!: number;
@ApiProperty({ type: 'integer' })
@ApiProperty({ description: 'Total number of assets', type: 'integer' })
total!: number;
}
export class AssetMetadataRouteParams {
@ValidateUUID()
@ValidateUUID({ description: 'Asset ID' })
id!: string;
@ValidateEnum({ enum: AssetMetadataKey, name: 'AssetMetadataKey' })
key!: AssetMetadataKey;
@ValidateString({ description: 'Metadata key' })
key!: string;
}
export class AssetMetadataUpsertDto {
@ApiProperty({ description: 'Metadata items to upsert' })
@IsArray()
@ValidateNested({ each: true })
@Type(() => AssetMetadataUpsertItemDto)
items!: AssetMetadataUpsertItemDto[];
}
export class AssetMetadataUpsertItemDto implements AssetMetadataItem {
@ValidateEnum({ enum: AssetMetadataKey, name: 'AssetMetadataKey' })
key!: AssetMetadataKey;
export class AssetMetadataUpsertItemDto {
@ValidateString({ description: 'Metadata key' })
key!: string;
@ApiProperty({ description: 'Metadata value (object)' })
@IsObject()
@ValidateNested()
@Type((options) => {
switch (options?.object.key) {
case AssetMetadataKey.MobileApp: {
return AssetMetadataMobileAppDto;
}
default: {
return Object;
}
}
})
value!: AssetMetadata[AssetMetadataKey];
value!: object;
}
export class AssetMetadataMobileAppDto {
@IsString()
@Optional()
iCloudId?: string;
export class AssetMetadataBulkUpsertDto {
@ApiProperty({ description: 'Metadata items to upsert' })
@IsArray()
@ValidateNested({ each: true })
@Type(() => AssetMetadataBulkUpsertItemDto)
items!: AssetMetadataBulkUpsertItemDto[];
}
export class AssetMetadataBulkUpsertItemDto {
@ValidateUUID({ description: 'Asset ID' })
assetId!: string;
@ValidateString({ description: 'Metadata key' })
key!: string;
@ApiProperty({ description: 'Metadata value (object)' })
@IsObject()
value!: object;
}
export class AssetMetadataBulkDeleteDto {
@ApiProperty({ description: 'Metadata items to delete' })
@IsArray()
@ValidateNested({ each: true })
@Type(() => AssetMetadataBulkDeleteItemDto)
items!: AssetMetadataBulkDeleteItemDto[];
}
export class AssetMetadataBulkDeleteItemDto {
@ValidateUUID({ description: 'Asset ID' })
assetId!: string;
@ValidateString({ description: 'Metadata key' })
key!: string;
}
export class AssetMetadataResponseDto {
@ValidateEnum({ enum: AssetMetadataKey, name: 'AssetMetadataKey' })
key!: AssetMetadataKey;
@ValidateString({ description: 'Metadata key' })
key!: string;
@ApiProperty({ description: 'Metadata value (object)' })
value!: object;
@ApiProperty({ description: 'Last update date' })
updatedAt!: Date;
}
export class AssetMetadataBulkResponseDto extends AssetMetadataResponseDto {
@ApiProperty({ description: 'Asset ID' })
assetId!: string;
}
export class AssetCopyDto {
@ValidateUUID()
@ValidateUUID({ description: 'Source asset ID' })
sourceId!: string;
@ValidateUUID()
@ValidateUUID({ description: 'Target asset ID' })
targetId!: string;
@ValidateBoolean({ optional: true, default: true })
@ValidateBoolean({ optional: true, description: 'Copy shared links', default: true })
sharedLinks?: boolean;
@ValidateBoolean({ optional: true, default: true })
@ValidateBoolean({ optional: true, description: 'Copy album associations', default: true })
albums?: boolean;
@ValidateBoolean({ optional: true, default: true })
@ValidateBoolean({ optional: true, description: 'Copy sidecar file', default: true })
sidecar?: boolean;
@ValidateBoolean({ optional: true, default: true })
@ValidateBoolean({ optional: true, description: 'Copy stack association', default: true })
stack?: boolean;
@ValidateBoolean({ optional: true, default: true })
@ValidateBoolean({ optional: true, description: 'Copy favorite status', default: true })
favorite?: boolean;
}
export class AssetDownloadOriginalDto {
@ValidateBoolean({ optional: true, description: 'Return edited asset if available', default: false })
edited?: boolean;
}
export const mapStats = (stats: AssetStats): AssetStatsResponseDto => {
return {
images: stats[AssetType.Image],
+38 -8
View File
@@ -1,4 +1,4 @@
import { ApiProperty } from '@nestjs/swagger';
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import { Transform } from 'class-transformer';
import { IsEmail, IsNotEmpty, IsString, MinLength } from 'class-validator';
import { AuthApiKey, AuthSession, AuthSharedLink, AuthUser, UserAdmin } from 'src/database';
@@ -12,34 +12,46 @@ export type CookieResponse = {
};
export class AuthDto {
@ApiProperty({ description: 'Authenticated user' })
user!: AuthUser;
@ApiPropertyOptional({ description: 'API key (if authenticated via API key)' })
apiKey?: AuthApiKey;
@ApiPropertyOptional({ description: 'Shared link (if authenticated via shared link)' })
sharedLink?: AuthSharedLink;
@ApiPropertyOptional({ description: 'Session (if authenticated via session)' })
session?: AuthSession;
}
export class LoginCredentialDto {
@ApiProperty({ example: 'testuser@email.com', description: 'User email' })
@IsEmail({ require_tld: false })
@Transform(toEmail)
@IsNotEmpty()
@ApiProperty({ example: 'testuser@email.com' })
email!: string;
@ApiProperty({ example: 'password', description: 'User password' })
@IsString()
@IsNotEmpty()
@ApiProperty({ example: 'password' })
password!: string;
}
export class LoginResponseDto {
@ApiProperty({ description: 'Access token' })
accessToken!: string;
@ApiProperty({ description: 'User ID' })
userId!: string;
@ApiProperty({ description: 'User email' })
userEmail!: string;
@ApiProperty({ description: 'User name' })
name!: string;
@ApiProperty({ description: 'Profile image path' })
profileImagePath!: string;
@ApiProperty({ description: 'Is admin user' })
isAdmin!: boolean;
@ApiProperty({ description: 'Should change password' })
shouldChangePassword!: boolean;
@ApiProperty({ description: 'Is onboarded' })
isOnboarded!: boolean;
}
@@ -61,42 +73,47 @@ export function mapLoginResponse(entity: UserAdmin, accessToken: string): LoginR
}
export class LogoutResponseDto {
@ApiProperty({ description: 'Logout successful' })
successful!: boolean;
@ApiProperty({ description: 'Redirect URI' })
redirectUri!: string;
}
export class SignUpDto extends LoginCredentialDto {
@ApiProperty({ example: 'Admin', description: 'User name' })
@IsString()
@IsNotEmpty()
@ApiProperty({ example: 'Admin' })
name!: string;
}
export class ChangePasswordDto {
@ApiProperty({ example: 'password', description: 'Current password' })
@IsString()
@IsNotEmpty()
@ApiProperty({ example: 'password' })
password!: string;
@ApiProperty({ example: 'password', description: 'New password (min 8 characters)' })
@IsString()
@IsNotEmpty()
@MinLength(8)
@ApiProperty({ example: 'password' })
newPassword!: string;
@ValidateBoolean({ optional: true, default: false })
@ValidateBoolean({ optional: true, default: false, description: 'Invalidate all other sessions' })
invalidateSessions?: boolean;
}
export class PinCodeSetupDto {
@ApiProperty({ description: 'PIN code (4-6 digits)' })
@PinCode()
pinCode!: string;
}
export class PinCodeResetDto {
@ApiPropertyOptional({ description: 'New PIN code (4-6 digits)' })
@PinCode({ optional: true })
pinCode?: string;
@ApiPropertyOptional({ description: 'User password (required if PIN code is not provided)' })
@Optional()
@IsString()
@IsNotEmpty()
@@ -106,51 +123,64 @@ export class PinCodeResetDto {
export class SessionUnlockDto extends PinCodeResetDto {}
export class PinCodeChangeDto extends PinCodeResetDto {
@ApiProperty({ description: 'New PIN code (4-6 digits)' })
@PinCode()
newPinCode!: string;
}
export class ValidateAccessTokenResponseDto {
@ApiProperty({ description: 'Authentication status' })
authStatus!: boolean;
}
export class OAuthCallbackDto {
@ApiProperty({ description: 'OAuth callback URL' })
@IsNotEmpty()
@IsString()
@ApiProperty()
url!: string;
@ApiPropertyOptional({ description: 'OAuth state parameter' })
@Optional()
@IsString()
state?: string;
@ApiPropertyOptional({ description: 'OAuth code verifier (PKCE)' })
@Optional()
@IsString()
codeVerifier?: string;
}
export class OAuthConfigDto {
@ApiProperty({ description: 'OAuth redirect URI' })
@IsNotEmpty()
@IsString()
redirectUri!: string;
@ApiPropertyOptional({ description: 'OAuth state parameter' })
@Optional()
@IsString()
state?: string;
@ApiPropertyOptional({ description: 'OAuth code challenge (PKCE)' })
@Optional()
@IsString()
codeChallenge?: string;
}
export class OAuthAuthorizeResponseDto {
@ApiProperty({ description: 'OAuth authorization URL' })
url!: string;
}
export class AuthStatusResponseDto {
@ApiProperty({ description: 'Has PIN code set' })
pinCode!: boolean;
@ApiProperty({ description: 'Has password set' })
password!: boolean;
@ApiProperty({ description: 'Is elevated session' })
isElevated!: boolean;
@ApiPropertyOptional({ description: 'Session expiration date' })
expiresAt?: string;
@ApiPropertyOptional({ description: 'PIN expiration date' })
pinExpiresAt?: string;
}
+25
View File
@@ -0,0 +1,25 @@
import { ApiProperty } from '@nestjs/swagger';
import { IsLatitude, IsLongitude } from 'class-validator';
import { IsGreaterThanOrEqualTo } from 'src/validation';
export class BBoxDto {
@ApiProperty({ format: 'double', description: 'West longitude (-180 to 180)' })
@IsLongitude()
west!: number;
@ApiProperty({ format: 'double', description: 'South latitude (-90 to 90)' })
@IsLatitude()
south!: number;
@ApiProperty({
format: 'double',
description: 'East longitude (-180 to 180). May be less than west when crossing the antimeridian.',
})
@IsLongitude()
east!: number;
@ApiProperty({ format: 'double', description: 'North latitude (-90 to 90). Must be >= south.' })
@IsLatitude()
@IsGreaterThanOrEqualTo('south')
north!: number;
}
+21
View File
@@ -0,0 +1,21 @@
import { ApiProperty } from '@nestjs/swagger';
import { IsString } from 'class-validator';
export class DatabaseBackupDto {
filename!: string;
filesize!: number;
}
export class DatabaseBackupListResponseDto {
backups!: DatabaseBackupDto[];
}
export class DatabaseBackupUploadDto {
@ApiProperty({ type: 'string', format: 'binary', required: false })
file?: any;
}
export class DatabaseBackupDeleteDto {
@IsString({ each: true })
backups!: string[];
}
+16 -8
View File
@@ -1,32 +1,40 @@
import { ApiProperty } from '@nestjs/swagger';
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import { IsInt, IsPositive } from 'class-validator';
import { Optional, ValidateUUID } from 'src/validation';
import { AssetIdsDto } from 'src/dtos/asset.dto';
import { Optional, ValidateBoolean, ValidateUUID } from 'src/validation';
export class DownloadInfoDto {
@ValidateUUID({ each: true, optional: true })
@ValidateUUID({ each: true, optional: true, description: 'Asset IDs to download' })
assetIds?: string[];
@ValidateUUID({ optional: true })
@ValidateUUID({ optional: true, description: 'Album ID to download' })
albumId?: string;
@ValidateUUID({ optional: true })
@ValidateUUID({ optional: true, description: 'User ID to download assets from' })
userId?: string;
@ApiPropertyOptional({ type: 'integer', description: 'Archive size limit in bytes' })
@IsInt()
@IsPositive()
@Optional()
@ApiProperty({ type: 'integer' })
archiveSize?: number;
}
export class DownloadResponseDto {
@ApiProperty({ type: 'integer' })
@ApiProperty({ type: 'integer', description: 'Total size in bytes' })
totalSize!: number;
@ApiProperty({ description: 'Archive information' })
archives!: DownloadArchiveInfo[];
}
export class DownloadArchiveInfo {
@ApiProperty({ type: 'integer' })
@ApiProperty({ type: 'integer', description: 'Archive size in bytes' })
size!: number;
@ApiProperty({ description: 'Asset IDs in this archive' })
assetIds!: string[];
}
export class DownloadArchiveDto extends AssetIdsDto {
@ValidateBoolean({ optional: true, description: 'Download edited asset if available' })
edited?: boolean;
}
+29
View File
@@ -1,6 +1,35 @@
import { ApiProperty } from '@nestjs/swagger';
import { Type } from 'class-transformer';
import { ArrayMinSize, IsArray, ValidateNested } from 'class-validator';
import { AssetResponseDto } from 'src/dtos/asset-response.dto';
import { ValidateUUID } from 'src/validation';
export class DuplicateResponseDto {
@ApiProperty({ description: 'Duplicate group ID' })
duplicateId!: string;
@ApiProperty({ description: 'Duplicate assets' })
assets!: AssetResponseDto[];
@ValidateUUID({ each: true, description: 'Suggested asset IDs to keep based on file size and EXIF data' })
suggestedKeepAssetIds!: string[];
}
export class DuplicateResolveGroupDto {
@ValidateUUID()
duplicateId!: string;
@ValidateUUID({ each: true, description: 'Asset IDs to keep' })
keepAssetIds!: string[];
@ValidateUUID({ each: true, description: 'Asset IDs to trash or delete' })
trashAssetIds!: string[];
}
export class DuplicateResolveDto {
@ApiProperty({ description: 'List of duplicate groups to resolve' })
@ValidateNested({ each: true })
@IsArray()
@Type(() => DuplicateResolveGroupDto)
@ArrayMinSize(1)
groups!: DuplicateResolveGroupDto[];
}
+111
View File
@@ -0,0 +1,111 @@
import { ApiExtraModels, ApiProperty, getSchemaPath } from '@nestjs/swagger';
import { Type } from 'class-transformer';
import { ArrayMinSize, IsEnum, IsInt, Min, ValidateNested } from 'class-validator';
import { IsAxisAlignedRotation, IsUniqueEditActions, ValidateEnum, ValidateUUID } from 'src/validation';
export enum AssetEditAction {
Crop = 'crop',
Rotate = 'rotate',
Mirror = 'mirror',
}
export enum MirrorAxis {
Horizontal = 'horizontal',
Vertical = 'vertical',
}
export class CropParameters {
@IsInt()
@Min(0)
@ApiProperty({ description: 'Top-Left X coordinate of crop' })
x!: number;
@IsInt()
@Min(0)
@ApiProperty({ description: 'Top-Left Y coordinate of crop' })
y!: number;
@IsInt()
@Min(1)
@ApiProperty({ description: 'Width of the crop' })
width!: number;
@IsInt()
@Min(1)
@ApiProperty({ description: 'Height of the crop' })
height!: number;
}
export class RotateParameters {
@IsAxisAlignedRotation()
@ApiProperty({ description: 'Rotation angle in degrees' })
angle!: number;
}
export class MirrorParameters {
@IsEnum(MirrorAxis)
@ApiProperty({ enum: MirrorAxis, enumName: 'MirrorAxis', description: 'Axis to mirror along' })
axis!: MirrorAxis;
}
export type AssetEditParameters = CropParameters | RotateParameters | MirrorParameters;
export type AssetEditActionItem =
| {
action: AssetEditAction.Crop;
parameters: CropParameters;
}
| {
action: AssetEditAction.Rotate;
parameters: RotateParameters;
}
| {
action: AssetEditAction.Mirror;
parameters: MirrorParameters;
};
@ApiExtraModels(CropParameters, RotateParameters, MirrorParameters)
export class AssetEditActionItemDto {
@ValidateEnum({ name: 'AssetEditAction', enum: AssetEditAction, description: 'Type of edit action to perform' })
action!: AssetEditAction;
@ApiProperty({
description: 'List of edit actions to apply (crop, rotate, or mirror)',
anyOf: [CropParameters, RotateParameters, MirrorParameters].map((type) => ({
$ref: getSchemaPath(type),
})),
})
@ValidateNested()
@Type((options) => actionParameterMap[options?.object.action as keyof AssetEditActionParameter])
parameters!: AssetEditActionItem['parameters'];
}
export class AssetEditActionItemResponseDto extends AssetEditActionItemDto {
@ValidateUUID()
id!: string;
}
export type AssetEditActionParameter = typeof actionParameterMap;
const actionParameterMap = {
[AssetEditAction.Crop]: CropParameters,
[AssetEditAction.Rotate]: RotateParameters,
[AssetEditAction.Mirror]: MirrorParameters,
};
export class AssetEditsCreateDto {
@ArrayMinSize(1)
@IsUniqueEditActions()
@ValidateNested({ each: true })
@Type(() => AssetEditActionItemDto)
@ApiProperty({ description: 'List of edit actions to apply (crop, rotate, or mirror)' })
edits!: AssetEditActionItemDto[];
}
export class AssetEditsResponseDto {
@ValidateUUID({ description: 'Asset ID these edits belong to' })
assetId!: string;
@ApiProperty({
description: 'List of edit actions applied to the asset',
})
edits!: AssetEditActionItemResponseDto[];
}
+28 -1
View File
@@ -1,8 +1,17 @@
import { Transform, Type } from 'class-transformer';
import { IsEnum, IsInt, IsString, Matches } from 'class-validator';
import { DatabaseSslMode, ImmichEnvironment, LogLevel } from 'src/enum';
import { ImmichEnvironment, LogFormat, LogLevel } from 'src/enum';
import { IsIPRange, Optional, ValidateBoolean } from 'src/validation';
// TODO import from sql-tools once the swagger plugin supports external enums
enum DatabaseSslMode {
Disable = 'disable',
Allow = 'allow',
Prefer = 'prefer',
Require = 'require',
VerifyFull = 'verify-full',
}
export class EnvDto {
@IsInt()
@Optional()
@@ -33,6 +42,10 @@ export class EnvDto {
@Optional()
IMMICH_CONFIG_FILE?: string;
@IsString()
@Optional()
IMMICH_HELMET_FILE?: string;
@IsEnum(ImmichEnvironment)
@Optional()
IMMICH_ENV?: ImmichEnvironment;
@@ -48,6 +61,10 @@ export class EnvDto {
@Optional()
IMMICH_LOG_LEVEL?: LogLevel;
@IsEnum(LogFormat)
@Optional()
IMMICH_LOG_FORMAT?: LogFormat;
@Optional()
@Matches(/^\//, { message: 'IMMICH_MEDIA_LOCATION must be an absolute path' })
IMMICH_MEDIA_LOCATION?: string;
@@ -57,6 +74,13 @@ export class EnvDto {
@Type(() => Number)
IMMICH_MICROSERVICES_METRICS_PORT?: number;
@ValidateBoolean({ optional: true })
IMMICH_ALLOW_EXTERNAL_PLUGINS?: boolean;
@Optional()
@Matches(/^\//, { message: 'IMMICH_PLUGINS_INSTALL_FOLDER must be an absolute path' })
IMMICH_PLUGINS_INSTALL_FOLDER?: string;
@IsInt()
@Optional()
@Type(() => Number)
@@ -106,6 +130,9 @@ export class EnvDto {
@Optional()
IMMICH_THIRD_PARTY_SUPPORT_URL?: string;
@ValidateBoolean({ optional: true })
IMMICH_ALLOW_SETUP?: boolean;
@IsIPRange({ requireCIDR: false }, { each: true })
@Transform(({ value }) =>
value && typeof value === 'string'
+31 -8
View File
@@ -1,34 +1,57 @@
import { ApiProperty } from '@nestjs/swagger';
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import { Exif } from 'src/database';
import { MaybeDehydrated } from 'src/types';
import { asDateString } from 'src/utils/date';
export class ExifResponseDto {
@ApiPropertyOptional({ description: 'Camera make' })
make?: string | null = null;
@ApiPropertyOptional({ description: 'Camera model' })
model?: string | null = null;
@ApiPropertyOptional({ type: 'number', description: 'Image width in pixels' })
exifImageWidth?: number | null = null;
@ApiPropertyOptional({ type: 'number', description: 'Image height in pixels' })
exifImageHeight?: number | null = null;
@ApiProperty({ type: 'integer', format: 'int64' })
@ApiProperty({ type: 'integer', format: 'int64', description: 'File size in bytes' })
fileSizeInByte?: number | null = null;
@ApiPropertyOptional({ description: 'Image orientation' })
orientation?: string | null = null;
dateTimeOriginal?: Date | null = null;
modifyDate?: Date | null = null;
@ApiPropertyOptional({ description: 'Original date/time', format: 'date-time' })
dateTimeOriginal?: string | null = null;
@ApiPropertyOptional({ description: 'Modification date/time', format: 'date-time' })
modifyDate?: string | null = null;
@ApiPropertyOptional({ description: 'Time zone' })
timeZone?: string | null = null;
@ApiPropertyOptional({ description: 'Lens model' })
lensModel?: string | null = null;
@ApiPropertyOptional({ type: 'number', description: 'F-number (aperture)' })
fNumber?: number | null = null;
@ApiPropertyOptional({ type: 'number', description: 'Focal length in mm' })
focalLength?: number | null = null;
@ApiPropertyOptional({ type: 'number', description: 'ISO sensitivity' })
iso?: number | null = null;
@ApiPropertyOptional({ description: 'Exposure time' })
exposureTime?: string | null = null;
@ApiPropertyOptional({ type: 'number', description: 'GPS latitude' })
latitude?: number | null = null;
@ApiPropertyOptional({ type: 'number', description: 'GPS longitude' })
longitude?: number | null = null;
@ApiPropertyOptional({ description: 'City name' })
city?: string | null = null;
@ApiPropertyOptional({ description: 'State/province name' })
state?: string | null = null;
@ApiPropertyOptional({ description: 'Country name' })
country?: string | null = null;
@ApiPropertyOptional({ description: 'Image description' })
description?: string | null = null;
@ApiPropertyOptional({ description: 'Projection type' })
projectionType?: string | null = null;
@ApiPropertyOptional({ type: 'number', description: 'Rating' })
rating?: number | null = null;
}
export function mapExif(entity: Exif): ExifResponseDto {
export function mapExif(entity: MaybeDehydrated<Exif>): ExifResponseDto {
return {
make: entity.make,
model: entity.model,
@@ -36,8 +59,8 @@ export function mapExif(entity: Exif): ExifResponseDto {
exifImageHeight: entity.exifImageHeight,
fileSizeInByte: entity.fileSizeInByte ? Number.parseInt(entity.fileSizeInByte.toString()) : null,
orientation: entity.orientation,
dateTimeOriginal: entity.dateTimeOriginal,
modifyDate: entity.modifyDate,
dateTimeOriginal: asDateString(entity.dateTimeOriginal),
modifyDate: asDateString(entity.modifyDate),
timeZone: entity.timeZone,
lensModel: entity.lensModel,
fNumber: entity.fNumber,
@@ -59,7 +82,7 @@ export function mapSanitizedExif(entity: Exif): ExifResponseDto {
return {
fileSizeInByte: entity.fileSizeInByte ? Number.parseInt(entity.fileSizeInByte.toString()) : null,
orientation: entity.orientation,
dateTimeOriginal: entity.dateTimeOriginal,
dateTimeOriginal: asDateString(entity.dateTimeOriginal),
timeZone: entity.timeZone,
projectionType: entity.projectionType,
exifImageWidth: entity.exifImageWidth,
+3 -95
View File
@@ -1,99 +1,7 @@
import { ApiProperty } from '@nestjs/swagger';
import { JobCommand, ManualJobName, QueueName } from 'src/enum';
import { ValidateBoolean, ValidateEnum } from 'src/validation';
export class JobIdParamDto {
@ValidateEnum({ enum: QueueName, name: 'JobName' })
id!: QueueName;
}
export class JobCommandDto {
@ValidateEnum({ enum: JobCommand, name: 'JobCommand' })
command!: JobCommand;
@ValidateBoolean({ optional: true })
force?: boolean; // TODO: this uses undefined as a third state, which should be refactored to be more explicit
}
import { ManualJobName } from 'src/enum';
import { ValidateEnum } from 'src/validation';
export class JobCreateDto {
@ValidateEnum({ enum: ManualJobName, name: 'ManualJobName' })
@ValidateEnum({ enum: ManualJobName, name: 'ManualJobName', description: 'Job name' })
name!: ManualJobName;
}
export class JobCountsDto {
@ApiProperty({ type: 'integer' })
active!: number;
@ApiProperty({ type: 'integer' })
completed!: number;
@ApiProperty({ type: 'integer' })
failed!: number;
@ApiProperty({ type: 'integer' })
delayed!: number;
@ApiProperty({ type: 'integer' })
waiting!: number;
@ApiProperty({ type: 'integer' })
paused!: number;
}
export class QueueStatusDto {
isActive!: boolean;
isPaused!: boolean;
}
export class JobStatusDto {
@ApiProperty({ type: JobCountsDto })
jobCounts!: JobCountsDto;
@ApiProperty({ type: QueueStatusDto })
queueStatus!: QueueStatusDto;
}
export class AllJobStatusResponseDto implements Record<QueueName, JobStatusDto> {
@ApiProperty({ type: JobStatusDto })
[QueueName.ThumbnailGeneration]!: JobStatusDto;
@ApiProperty({ type: JobStatusDto })
[QueueName.MetadataExtraction]!: JobStatusDto;
@ApiProperty({ type: JobStatusDto })
[QueueName.VideoConversion]!: JobStatusDto;
@ApiProperty({ type: JobStatusDto })
[QueueName.SmartSearch]!: JobStatusDto;
@ApiProperty({ type: JobStatusDto })
[QueueName.StorageTemplateMigration]!: JobStatusDto;
@ApiProperty({ type: JobStatusDto })
[QueueName.Migration]!: JobStatusDto;
@ApiProperty({ type: JobStatusDto })
[QueueName.BackgroundTask]!: JobStatusDto;
@ApiProperty({ type: JobStatusDto })
[QueueName.Search]!: JobStatusDto;
@ApiProperty({ type: JobStatusDto })
[QueueName.DuplicateDetection]!: JobStatusDto;
@ApiProperty({ type: JobStatusDto })
[QueueName.FaceDetection]!: JobStatusDto;
@ApiProperty({ type: JobStatusDto })
[QueueName.FacialRecognition]!: JobStatusDto;
@ApiProperty({ type: JobStatusDto })
[QueueName.Sidecar]!: JobStatusDto;
@ApiProperty({ type: JobStatusDto })
[QueueName.Library]!: JobStatusDto;
@ApiProperty({ type: JobStatusDto })
[QueueName.Notification]!: JobStatusDto;
@ApiProperty({ type: JobStatusDto })
[QueueName.BackupDatabase]!: JobStatusDto;
@ApiProperty({ type: JobStatusDto })
[QueueName.Ocr]!: JobStatusDto;
}
+28 -8
View File
@@ -1,17 +1,19 @@
import { ApiProperty } from '@nestjs/swagger';
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import { ArrayMaxSize, ArrayUnique, IsNotEmpty, IsString } from 'class-validator';
import { Library } from 'src/database';
import { Optional, ValidateUUID } from 'src/validation';
export class CreateLibraryDto {
@ValidateUUID()
@ValidateUUID({ description: 'Owner user ID' })
ownerId!: string;
@ApiPropertyOptional({ description: 'Library name' })
@IsString()
@Optional()
@IsNotEmpty()
name?: string;
@ApiPropertyOptional({ description: 'Import paths (max 128)' })
@Optional()
@IsString({ each: true })
@IsNotEmpty({ each: true })
@@ -19,6 +21,7 @@ export class CreateLibraryDto {
@ArrayMaxSize(128)
importPaths?: string[];
@ApiPropertyOptional({ description: 'Exclusion patterns (max 128)' })
@Optional()
@IsString({ each: true })
@IsNotEmpty({ each: true })
@@ -28,11 +31,13 @@ export class CreateLibraryDto {
}
export class UpdateLibraryDto {
@ApiPropertyOptional({ description: 'Library name' })
@Optional()
@IsString()
@IsNotEmpty()
name?: string;
@ApiPropertyOptional({ description: 'Import paths (max 128)' })
@Optional()
@IsString({ each: true })
@IsNotEmpty({ each: true })
@@ -40,6 +45,7 @@ export class UpdateLibraryDto {
@ArrayMaxSize(128)
importPaths?: string[];
@ApiPropertyOptional({ description: 'Exclusion patterns (max 128)' })
@Optional()
@IsNotEmpty({ each: true })
@IsString({ each: true })
@@ -59,6 +65,7 @@ export interface WalkOptionsDto extends CrawlOptionsDto {
}
export class ValidateLibraryDto {
@ApiPropertyOptional({ description: 'Import paths to validate (max 128)' })
@Optional()
@IsString({ each: true })
@IsNotEmpty({ each: true })
@@ -66,6 +73,7 @@ export class ValidateLibraryDto {
@ArrayMaxSize(128)
importPaths?: string[];
@ApiPropertyOptional({ description: 'Exclusion patterns (max 128)' })
@Optional()
@IsNotEmpty({ each: true })
@IsString({ each: true })
@@ -75,48 +83,60 @@ export class ValidateLibraryDto {
}
export class ValidateLibraryResponseDto {
@ApiPropertyOptional({ description: 'Validation results for import paths' })
importPaths?: ValidateLibraryImportPathResponseDto[];
}
export class ValidateLibraryImportPathResponseDto {
@ApiProperty({ description: 'Import path' })
importPath!: string;
@ApiProperty({ description: 'Is valid' })
isValid: boolean = false;
@ApiPropertyOptional({ description: 'Validation message' })
message?: string;
}
export class LibrarySearchDto {
@ValidateUUID({ optional: true })
@ValidateUUID({ optional: true, description: 'Filter by user ID' })
userId?: string;
}
export class LibraryResponseDto {
@ApiProperty({ description: 'Library ID' })
id!: string;
@ApiProperty({ description: 'Owner user ID' })
ownerId!: string;
@ApiProperty({ description: 'Library name' })
name!: string;
@ApiProperty({ type: 'integer' })
@ApiProperty({ type: 'integer', description: 'Number of assets' })
assetCount!: number;
@ApiProperty({ description: 'Import paths' })
importPaths!: string[];
@ApiProperty({ description: 'Exclusion patterns' })
exclusionPatterns!: string[];
@ApiProperty({ description: 'Creation date' })
createdAt!: Date;
@ApiProperty({ description: 'Last update date' })
updatedAt!: Date;
@ApiProperty({ description: 'Last refresh date' })
refreshedAt!: Date | null;
}
export class LibraryStatsResponseDto {
@ApiProperty({ type: 'integer' })
@ApiProperty({ type: 'integer', description: 'Number of photos' })
photos = 0;
@ApiProperty({ type: 'integer' })
@ApiProperty({ type: 'integer', description: 'Number of videos' })
videos = 0;
@ApiProperty({ type: 'integer' })
@ApiProperty({ type: 'integer', description: 'Total number of assets' })
total = 0;
@ApiProperty({ type: 'integer', format: 'int64' })
@ApiProperty({ type: 'integer', format: 'int64', description: 'Storage usage in bytes' })
usage = 0;
}
+4
View File
@@ -1,16 +1,20 @@
import { ApiProperty } from '@nestjs/swagger';
import { IsNotEmpty, IsString, Matches } from 'class-validator';
export class LicenseKeyDto {
@ApiProperty({ description: 'License key (format: IM(SV|CL)(-XXXX){8})' })
@IsString()
@IsNotEmpty()
@Matches(/IM(SV|CL)(-[\dA-Za-z]{4}){8}/)
licenseKey!: string;
@ApiProperty({ description: 'Activation key' })
@IsString()
@IsNotEmpty()
activationKey!: string;
}
export class LicenseResponseDto extends LicenseKeyDto {
@ApiProperty({ description: 'Activation date' })
activatedAt!: Date;
}
+49
View File
@@ -0,0 +1,49 @@
import { ApiProperty } from '@nestjs/swagger';
import { ValidateIf } from 'class-validator';
import { MaintenanceAction, StorageFolder } from 'src/enum';
import { ValidateBoolean, ValidateEnum, ValidateString } from 'src/validation';
export class SetMaintenanceModeDto {
@ValidateEnum({ enum: MaintenanceAction, name: 'MaintenanceAction', description: 'Maintenance action' })
action!: MaintenanceAction;
@ValidateIf((o) => o.action === MaintenanceAction.RestoreDatabase)
@ValidateString({ description: 'Restore backup filename' })
restoreBackupFilename?: string;
}
export class MaintenanceLoginDto {
@ValidateString({ optional: true, description: 'Maintenance token' })
token?: string;
}
export class MaintenanceAuthDto {
@ApiProperty({ description: 'Maintenance username' })
username!: string;
}
export class MaintenanceStatusResponseDto {
active!: boolean;
@ValidateEnum({ enum: MaintenanceAction, name: 'MaintenanceAction', description: 'Maintenance action' })
action!: MaintenanceAction;
progress?: number;
task?: string;
error?: string;
}
export class MaintenanceDetectInstallStorageFolderDto {
@ValidateEnum({ enum: StorageFolder, name: 'StorageFolder', description: 'Storage folder' })
folder!: StorageFolder;
@ValidateBoolean({ description: 'Whether the folder is readable' })
readable!: boolean;
@ValidateBoolean({ description: 'Whether the folder is writable' })
writable!: boolean;
@ApiProperty({ description: 'Number of files in the folder' })
files!: number;
}
export class MaintenanceDetectInstallResponseDto {
storage!: MaintenanceDetectInstallStorageFolderDto[];
}
+17 -17
View File
@@ -4,64 +4,64 @@ import { IsLatitude, IsLongitude } from 'class-validator';
import { ValidateBoolean, ValidateDate } from 'src/validation';
export class MapReverseGeocodeDto {
@ApiProperty({ format: 'double' })
@ApiProperty({ format: 'double', description: 'Latitude (-90 to 90)' })
@Type(() => Number)
@IsLatitude({ message: ({ property }) => `${property} must be a number between -90 and 90` })
lat!: number;
@ApiProperty({ format: 'double' })
@ApiProperty({ format: 'double', description: 'Longitude (-180 to 180)' })
@Type(() => Number)
@IsLongitude({ message: ({ property }) => `${property} must be a number between -180 and 180` })
lon!: number;
}
export class MapReverseGeocodeResponseDto {
@ApiProperty()
@ApiProperty({ description: 'City name' })
city!: string | null;
@ApiProperty()
@ApiProperty({ description: 'State/Province name' })
state!: string | null;
@ApiProperty()
@ApiProperty({ description: 'Country name' })
country!: string | null;
}
export class MapMarkerDto {
@ValidateBoolean({ optional: true })
@ValidateBoolean({ optional: true, description: 'Filter by archived status' })
isArchived?: boolean;
@ValidateBoolean({ optional: true })
@ValidateBoolean({ optional: true, description: 'Filter by favorite status' })
isFavorite?: boolean;
@ValidateDate({ optional: true })
@ValidateDate({ optional: true, description: 'Filter assets created after this date' })
fileCreatedAfter?: Date;
@ValidateDate({ optional: true })
@ValidateDate({ optional: true, description: 'Filter assets created before this date' })
fileCreatedBefore?: Date;
@ValidateBoolean({ optional: true })
@ValidateBoolean({ optional: true, description: 'Include partner assets' })
withPartners?: boolean;
@ValidateBoolean({ optional: true })
@ValidateBoolean({ optional: true, description: 'Include shared album assets' })
withSharedAlbums?: boolean;
}
export class MapMarkerResponseDto {
@ApiProperty()
@ApiProperty({ description: 'Asset ID' })
id!: string;
@ApiProperty({ format: 'double' })
@ApiProperty({ format: 'double', description: 'Latitude' })
lat!: number;
@ApiProperty({ format: 'double' })
@ApiProperty({ format: 'double', description: 'Longitude' })
lon!: number;
@ApiProperty()
@ApiProperty({ description: 'City name' })
city!: string | null;
@ApiProperty()
@ApiProperty({ description: 'State/Province name' })
state!: string | null;
@ApiProperty()
@ApiProperty({ description: 'Country name' })
country!: string | null;
}
+56 -14
View File
@@ -2,34 +2,46 @@ import { ApiProperty } from '@nestjs/swagger';
import { Type } from 'class-transformer';
import { IsInt, IsObject, IsPositive, ValidateNested } from 'class-validator';
import { Memory } from 'src/database';
import { HistoryBuilder } from 'src/decorators';
import { AssetResponseDto, mapAsset } from 'src/dtos/asset-response.dto';
import { AuthDto } from 'src/dtos/auth.dto';
import { MemoryType } from 'src/enum';
import { ValidateBoolean, ValidateDate, ValidateEnum, ValidateUUID } from 'src/validation';
import { AssetOrderWithRandom, MemoryType } from 'src/enum';
import { Optional, ValidateBoolean, ValidateDate, ValidateEnum, ValidateUUID } from 'src/validation';
class MemoryBaseDto {
@ValidateBoolean({ optional: true })
@ValidateBoolean({ optional: true, description: 'Is memory saved' })
isSaved?: boolean;
@ValidateDate({ optional: true })
@ValidateDate({ optional: true, description: 'Date when memory was seen' })
seenAt?: Date;
}
export class MemorySearchDto {
@ValidateEnum({ enum: MemoryType, name: 'MemoryType', optional: true })
@ValidateEnum({ enum: MemoryType, name: 'MemoryType', description: 'Memory type', optional: true })
type?: MemoryType;
@ValidateDate({ optional: true })
@ValidateDate({ optional: true, description: 'Filter by date' })
for?: Date;
@ValidateBoolean({ optional: true })
@ValidateBoolean({ optional: true, description: 'Include trashed memories' })
isTrashed?: boolean;
@ValidateBoolean({ optional: true })
@ValidateBoolean({ optional: true, description: 'Filter by saved status' })
isSaved?: boolean;
@IsInt()
@IsPositive()
@Type(() => Number)
@Optional()
@ApiProperty({ type: 'integer', description: 'Number of memories to return' })
size?: number;
@ValidateEnum({ enum: AssetOrderWithRandom, name: 'MemorySearchOrder', description: 'Sort order', optional: true })
order?: AssetOrderWithRandom;
}
class OnThisDayDto {
@ApiProperty({ type: 'number', description: 'Year for on this day memory', minimum: 1 })
@IsInt()
@IsPositive()
year!: number;
@@ -38,14 +50,16 @@ class OnThisDayDto {
type MemoryData = OnThisDayDto;
export class MemoryUpdateDto extends MemoryBaseDto {
@ValidateDate({ optional: true })
@ValidateDate({ optional: true, description: 'Memory date' })
memoryAt?: Date;
}
export class MemoryCreateDto extends MemoryBaseDto {
@ValidateEnum({ enum: MemoryType, name: 'MemoryType' })
@ValidateEnum({ enum: MemoryType, name: 'MemoryType', description: 'Memory type' })
type!: MemoryType;
// Description lives on schema to avoid duplication
@ApiProperty({ description: undefined })
@IsObject()
@ValidateNested()
@Type((options) => {
@@ -61,32 +75,60 @@ export class MemoryCreateDto extends MemoryBaseDto {
})
data!: MemoryData;
@ValidateDate()
@ValidateDate({ description: 'Memory date' })
memoryAt!: Date;
@ValidateUUID({ optional: true, each: true })
@ValidateDate({
optional: true,
description: 'Date when memory should be shown',
history: new HistoryBuilder().added('v2.6.0').stable('v2.6.0'),
})
showAt?: Date;
@ValidateDate({
optional: true,
description: 'Date when memory should be hidden',
history: new HistoryBuilder().added('v2.6.0').stable('v2.6.0'),
})
hideAt?: Date;
@ValidateUUID({ optional: true, each: true, description: 'Asset IDs to associate with memory' })
assetIds?: string[];
}
export class MemoryStatisticsResponseDto {
@ApiProperty({ type: 'integer' })
@ApiProperty({ type: 'integer', description: 'Total number of memories' })
total!: number;
}
export class MemoryResponseDto {
@ApiProperty({ description: 'Memory ID' })
id!: string;
@ValidateDate({ description: 'Creation date' })
createdAt!: Date;
@ValidateDate({ description: 'Last update date' })
updatedAt!: Date;
@ValidateDate({ optional: true, description: 'Deletion date' })
deletedAt?: Date;
@ValidateDate({ description: 'Memory date' })
memoryAt!: Date;
@ValidateDate({ optional: true, description: 'Date when memory was seen' })
seenAt?: Date;
@ValidateDate({ optional: true, description: 'Date when memory should be shown' })
showAt?: Date;
@ValidateDate({ optional: true, description: 'Date when memory should be hidden' })
hideAt?: Date;
@ApiProperty({ description: 'Owner user ID' })
ownerId!: string;
@ValidateEnum({ enum: MemoryType, name: 'MemoryType' })
@ValidateEnum({ enum: MemoryType, name: 'MemoryType', description: 'Memory type' })
type!: MemoryType;
// Description lives on schema to avoid duplication
@ApiProperty({ description: undefined })
data!: MemoryData;
@ApiProperty({ description: 'Is memory saved' })
isSaved!: boolean;
// Description lives on schema to avoid duplication
@ApiProperty({ description: undefined })
assets!: AssetResponseDto[];
}
+21 -8
View File
@@ -4,11 +4,12 @@ import { IsNotEmpty, IsNumber, IsString, Max, Min } from 'class-validator';
import { ValidateBoolean } from 'src/validation';
export class TaskConfig {
@ValidateBoolean()
@ValidateBoolean({ description: 'Whether the task is enabled' })
enabled!: boolean;
}
export class ModelConfig extends TaskConfig {
@ApiProperty({ description: 'Name of the model to use' })
@IsString()
@IsNotEmpty()
modelName!: string;
@@ -21,7 +22,11 @@ export class DuplicateDetectionConfig extends TaskConfig {
@Min(0.001)
@Max(0.1)
@Type(() => Number)
@ApiProperty({ type: 'number', format: 'double' })
@ApiProperty({
type: 'number',
format: 'double',
description: 'Maximum distance threshold for duplicate detection',
})
maxDistance!: number;
}
@@ -30,20 +35,24 @@ export class FacialRecognitionConfig extends ModelConfig {
@Min(0.1)
@Max(1)
@Type(() => Number)
@ApiProperty({ type: 'number', format: 'double' })
@ApiProperty({ type: 'number', format: 'double', description: 'Minimum confidence score for face detection' })
minScore!: number;
@IsNumber()
@Min(0.1)
@Max(2)
@Type(() => Number)
@ApiProperty({ type: 'number', format: 'double' })
@ApiProperty({
type: 'number',
format: 'double',
description: 'Maximum distance threshold for face recognition',
})
maxDistance!: number;
@IsNumber()
@Min(1)
@Type(() => Number)
@ApiProperty({ type: 'integer' })
@ApiProperty({ type: 'integer', description: 'Minimum number of faces required for recognition' })
minFaces!: number;
}
@@ -51,20 +60,24 @@ export class OcrConfig extends ModelConfig {
@IsNumber()
@Min(1)
@Type(() => Number)
@ApiProperty({ type: 'integer' })
@ApiProperty({ type: 'integer', description: 'Maximum resolution for OCR processing' })
maxResolution!: number;
@IsNumber()
@Min(0.1)
@Max(1)
@Type(() => Number)
@ApiProperty({ type: 'number', format: 'double' })
@ApiProperty({ type: 'number', format: 'double', description: 'Minimum confidence score for text detection' })
minDetectionScore!: number;
@IsNumber()
@Min(0.1)
@Max(1)
@Type(() => Number)
@ApiProperty({ type: 'number', format: 'double' })
@ApiProperty({
type: 'number',
format: 'double',
description: 'Minimum confidence score for text recognition',
})
minRecognitionScore!: number;
}
+48 -20
View File
@@ -1,86 +1,114 @@
import { IsString } from 'class-validator';
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import { ArrayMinSize, IsString } from 'class-validator';
import { NotificationLevel, NotificationType } from 'src/enum';
import { Optional, ValidateBoolean, ValidateDate, ValidateEnum, ValidateUUID } from 'src/validation';
import { Optional, ValidateBoolean, ValidateDate, ValidateEnum, ValidateString, ValidateUUID } from 'src/validation';
export class TestEmailResponseDto {
@ApiProperty({ description: 'Email message ID' })
messageId!: string;
}
export class TemplateResponseDto {
@ApiProperty({ description: 'Template name' })
name!: string;
@ApiProperty({ description: 'Template HTML content' })
html!: string;
}
export class TemplateDto {
@ApiProperty({ description: 'Template name' })
@IsString()
template!: string;
}
export class NotificationDto {
@ApiProperty({ description: 'Notification ID' })
id!: string;
@ValidateDate()
@ValidateDate({ description: 'Creation date' })
createdAt!: Date;
@ValidateEnum({ enum: NotificationLevel, name: 'NotificationLevel' })
@ValidateEnum({ enum: NotificationLevel, name: 'NotificationLevel', description: 'Notification level' })
level!: NotificationLevel;
@ValidateEnum({ enum: NotificationType, name: 'NotificationType' })
@ValidateEnum({ enum: NotificationType, name: 'NotificationType', description: 'Notification type' })
type!: NotificationType;
@ApiProperty({ description: 'Notification title' })
title!: string;
@ApiPropertyOptional({ description: 'Notification description' })
description?: string;
@ApiPropertyOptional({ description: 'Additional notification data' })
data?: any;
@ApiPropertyOptional({ description: 'Date when notification was read', format: 'date-time' })
readAt?: Date;
}
export class NotificationSearchDto {
@ValidateUUID({ optional: true })
@ValidateUUID({ optional: true, description: 'Filter by notification ID' })
id?: string;
@ValidateEnum({ enum: NotificationLevel, name: 'NotificationLevel', optional: true })
@ValidateEnum({
enum: NotificationLevel,
name: 'NotificationLevel',
optional: true,
description: 'Filter by notification level',
})
level?: NotificationLevel;
@ValidateEnum({ enum: NotificationType, name: 'NotificationType', optional: true })
@ValidateEnum({
enum: NotificationType,
name: 'NotificationType',
optional: true,
description: 'Filter by notification type',
})
type?: NotificationType;
@ValidateBoolean({ optional: true })
@ValidateBoolean({ optional: true, description: 'Filter by unread status' })
unread?: boolean;
}
export class NotificationCreateDto {
@ValidateEnum({ enum: NotificationLevel, name: 'NotificationLevel', optional: true })
@ValidateEnum({
enum: NotificationLevel,
name: 'NotificationLevel',
optional: true,
description: 'Notification level',
})
level?: NotificationLevel;
@ValidateEnum({ enum: NotificationType, name: 'NotificationType', optional: true })
@ValidateEnum({ enum: NotificationType, name: 'NotificationType', optional: true, description: 'Notification type' })
type?: NotificationType;
@IsString()
@ValidateString({ description: 'Notification title' })
title!: string;
@IsString()
@Optional({ nullable: true })
@ValidateString({ optional: true, nullable: true, description: 'Notification description' })
description?: string | null;
@ApiPropertyOptional({ description: 'Additional notification data' })
@Optional({ nullable: true })
data?: any;
@ValidateDate({ optional: true, nullable: true })
@ValidateDate({ optional: true, nullable: true, description: 'Date when notification was read' })
readAt?: Date | null;
@ValidateUUID()
@ValidateUUID({ description: 'User ID to send notification to' })
userId!: string;
}
export class NotificationUpdateDto {
@ValidateDate({ optional: true, nullable: true })
@ValidateDate({ optional: true, nullable: true, description: 'Date when notification was read' })
readAt?: Date | null;
}
export class NotificationUpdateAllDto {
@ValidateUUID({ each: true, optional: true })
@ValidateUUID({ each: true, description: 'Notification IDs to update' })
@ArrayMinSize(1)
ids!: string[];
@ValidateDate({ optional: true, nullable: true })
@ValidateDate({ optional: true, nullable: true, description: 'Date when notifications were read' })
readAt?: Date | null;
}
export class NotificationDeleteAllDto {
@ValidateUUID({ each: true })
@ValidateUUID({ each: true, description: 'Notification IDs to delete' })
@ArrayMinSize(1)
ids!: string[];
}

Some files were not shown because too many files have changed in this diff Show More