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
+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);
}
}