Compare commits

...

8 Commits

Author SHA1 Message Date
Jason Rasmussen 5abe4e2bd7 feat: asset file apis 2026-02-04 16:02:37 -05:00
Alex e9f8521a50 fix: date time picker text color in dark mode (#25883) 2026-02-04 18:45:56 +00:00
Michel Heusschen 6bd60270b4 fix: correctly sync shared link download with metadata toggle (#25885) 2026-02-04 12:38:42 -05:00
Michel Heusschen 5a6fd7af06 fix: close tag modal after tagging assets (#25884) 2026-02-04 12:35:00 -05:00
Jason Rasmussen 6cdebdd3b3 fix(server): deleting stacked assets (#25874)
* fix(server): deleting stacked assets

* fix: log a warning when removing an empty directory fails
2026-02-04 17:33:37 +00:00
Jason Rasmussen 9dddccd831 fix: null validation (#25891) 2026-02-04 12:27:52 -05:00
Min Idzelis 440b3b4c6f chore: move devcontainer specific tasks to devcontainer.json (#25881)
refactor: move devcontainer specific tasks to devcontainer.json
2026-02-03 23:04:09 -05:00
Jason Rasmussen 3ea65f8d27 fix: album dto docs (#25873) 2026-02-03 21:05:18 +00:00
57 changed files with 1881 additions and 298 deletions
+75 -1
View File
@@ -26,7 +26,81 @@
"vitest.explorer",
"ms-playwright.playwright",
"ms-azuretools.vscode-docker"
]
],
"settings": {
"tasks": {
"version": "2.0.0",
"tasks": [
{
"label": "Fix Permissions, Install Dependencies",
"type": "shell",
"command": "[ -f /immich-devcontainer/container-start.sh ] && /immich-devcontainer/container-start.sh || exit 0",
"isBackground": true,
"presentation": {
"echo": true,
"reveal": "always",
"focus": false,
"panel": "dedicated",
"showReuseMessage": true,
"clear": false,
"group": "Devcontainer tasks",
"close": true
},
"runOptions": {
"runOn": "default"
},
"problemMatcher": []
},
{
"label": "Immich API Server (Nest)",
"dependsOn": ["Fix Permissions, Install Dependencies"],
"type": "shell",
"command": "[ -f /immich-devcontainer/container-start-backend.sh ] && /immich-devcontainer/container-start-backend.sh || exit 0",
"isBackground": true,
"presentation": {
"echo": true,
"reveal": "always",
"focus": false,
"panel": "dedicated",
"showReuseMessage": true,
"clear": false,
"group": "Devcontainer tasks",
"close": true
},
"runOptions": {
"runOn": "folderOpen"
},
"problemMatcher": []
},
{
"label": "Immich Web Server (Vite)",
"dependsOn": ["Fix Permissions, Install Dependencies"],
"type": "shell",
"command": "[ -f /immich-devcontainer/container-start-frontend.sh ] && /immich-devcontainer/container-start-frontend.sh || exit 0",
"isBackground": true,
"presentation": {
"echo": true,
"reveal": "always",
"focus": false,
"panel": "dedicated",
"showReuseMessage": true,
"clear": false,
"group": "Devcontainer tasks",
"close": true
},
"runOptions": {
"runOn": "folderOpen"
},
"problemMatcher": []
},
{
"label": "Build Immich CLI",
"type": "shell",
"command": "pnpm --filter cli build:dev"
}
]
}
}
}
},
"features": {
-80
View File
@@ -1,80 +0,0 @@
{
"version": "2.0.0",
"tasks": [
{
"label": "Fix Permissions, Install Dependencies",
"type": "shell",
"command": "[ -f /immich-devcontainer/container-start.sh ] && /immich-devcontainer/container-start.sh || exit 0",
"isBackground": true,
"presentation": {
"echo": true,
"reveal": "always",
"focus": false,
"panel": "dedicated",
"showReuseMessage": true,
"clear": false,
"group": "Devcontainer tasks",
"close": true
},
"runOptions": {
"runOn": "default"
},
"problemMatcher": []
},
{
"label": "Immich API Server (Nest)",
"dependsOn": ["Fix Permissions, Install Dependencies"],
"type": "shell",
"command": "[ -f /immich-devcontainer/container-start-backend.sh ] && /immich-devcontainer/container-start-backend.sh || exit 0",
"isBackground": true,
"presentation": {
"echo": true,
"reveal": "always",
"focus": false,
"panel": "dedicated",
"showReuseMessage": true,
"clear": false,
"group": "Devcontainer tasks",
"close": true
},
"runOptions": {
"runOn": "default"
},
"problemMatcher": []
},
{
"label": "Immich Web Server (Vite)",
"dependsOn": ["Fix Permissions, Install Dependencies"],
"type": "shell",
"command": "[ -f /immich-devcontainer/container-start-frontend.sh ] && /immich-devcontainer/container-start-frontend.sh || exit 0",
"isBackground": true,
"presentation": {
"echo": true,
"reveal": "always",
"focus": false,
"panel": "dedicated",
"showReuseMessage": true,
"clear": false,
"group": "Devcontainer tasks",
"close": true
},
"runOptions": {
"runOn": "default"
},
"problemMatcher": []
},
{
"label": "Immich Server and Web",
"dependsOn": ["Immich Web Server (Vite)", "Immich API Server (Nest)"],
"runOptions": {
"runOn": "folderOpen"
},
"problemMatcher": []
},
{
"label": "Build Immich CLI",
"type": "shell",
"command": "pnpm --filter cli build:dev"
}
]
}
+6
View File
@@ -95,6 +95,10 @@ Class | Method | HTTP request | Description
*AlbumsApi* | [**removeUserFromAlbum**](doc//AlbumsApi.md#removeuserfromalbum) | **DELETE** /albums/{id}/user/{userId} | Remove user from album
*AlbumsApi* | [**updateAlbumInfo**](doc//AlbumsApi.md#updatealbuminfo) | **PATCH** /albums/{id} | Update an album
*AlbumsApi* | [**updateAlbumUser**](doc//AlbumsApi.md#updatealbumuser) | **PUT** /albums/{id}/user/{userId} | Update user role
*AssetFilesApi* | [**deleteAssetFile**](doc//AssetFilesApi.md#deleteassetfile) | **DELETE** /asset-files/{id} | Delete an asset file
*AssetFilesApi* | [**downloadAssetFile**](doc//AssetFilesApi.md#downloadassetfile) | **GET** /asset-files/{id}/download | Download an asset file
*AssetFilesApi* | [**getAssetFile**](doc//AssetFilesApi.md#getassetfile) | **GET** /asset-files/{id} | Retrieve an asset file
*AssetFilesApi* | [**searchAssetFiles**](doc//AssetFilesApi.md#searchassetfiles) | **GET** /asset-files | Retrieve an asset file
*AssetsApi* | [**checkBulkUpload**](doc//AssetsApi.md#checkbulkupload) | **POST** /assets/bulk-upload-check | Check bulk upload
*AssetsApi* | [**checkExistingAssets**](doc//AssetsApi.md#checkexistingassets) | **POST** /assets/exist | Check existing assets
*AssetsApi* | [**copyAsset**](doc//AssetsApi.md#copyasset) | **PUT** /assets/copy | Copy asset
@@ -369,6 +373,8 @@ Class | Method | HTTP request | Description
- [AssetFaceUpdateDto](doc//AssetFaceUpdateDto.md)
- [AssetFaceUpdateItem](doc//AssetFaceUpdateItem.md)
- [AssetFaceWithoutPersonResponseDto](doc//AssetFaceWithoutPersonResponseDto.md)
- [AssetFileResponseDto](doc//AssetFileResponseDto.md)
- [AssetFileType](doc//AssetFileType.md)
- [AssetFullSyncDto](doc//AssetFullSyncDto.md)
- [AssetIdsDto](doc//AssetIdsDto.md)
- [AssetIdsResponseDto](doc//AssetIdsResponseDto.md)
+3
View File
@@ -33,6 +33,7 @@ part 'auth/http_bearer_auth.dart';
part 'api/api_keys_api.dart';
part 'api/activities_api.dart';
part 'api/albums_api.dart';
part 'api/asset_files_api.dart';
part 'api/assets_api.dart';
part 'api/authentication_api.dart';
part 'api/authentication_admin_api.dart';
@@ -109,6 +110,8 @@ part 'model/asset_face_response_dto.dart';
part 'model/asset_face_update_dto.dart';
part 'model/asset_face_update_item.dart';
part 'model/asset_face_without_person_response_dto.dart';
part 'model/asset_file_response_dto.dart';
part 'model/asset_file_type.dart';
part 'model/asset_full_sync_dto.dart';
part 'model/asset_ids_dto.dart';
part 'model/asset_ids_response_dto.dart';
+2 -2
View File
@@ -473,7 +473,7 @@ class AlbumsApi {
/// Filter albums containing this asset ID (ignores shared parameter)
///
/// * [bool] shared:
/// Filter by shared status: true = only shared, false = only own, undefined = all
/// Filter by shared status: true = only shared, false = not shared, undefined = all owned albums
Future<Response> getAllAlbumsWithHttpInfo({ String? assetId, bool? shared, }) async {
// ignore: prefer_const_declarations
final apiPath = r'/albums';
@@ -516,7 +516,7 @@ class AlbumsApi {
/// Filter albums containing this asset ID (ignores shared parameter)
///
/// * [bool] shared:
/// Filter by shared status: true = only shared, false = only own, undefined = all
/// Filter by shared status: true = only shared, false = not shared, undefined = all owned albums
Future<List<AlbumResponseDto>?> getAllAlbums({ String? assetId, bool? shared, }) async {
final response = await getAllAlbumsWithHttpInfo( assetId: assetId, shared: shared, );
if (response.statusCode >= HttpStatus.badRequest) {
+271
View File
@@ -0,0 +1,271 @@
//
// AUTO-GENERATED FILE, DO NOT MODIFY!
//
// @dart=2.18
// ignore_for_file: unused_element, unused_import
// ignore_for_file: always_put_required_named_parameters_first
// ignore_for_file: constant_identifier_names
// ignore_for_file: lines_longer_than_80_chars
part of openapi.api;
class AssetFilesApi {
AssetFilesApi([ApiClient? apiClient]) : apiClient = apiClient ?? defaultApiClient;
final ApiClient apiClient;
/// Delete an asset file
///
/// Delete a file and remove it from the database.
///
/// Note: This method returns the HTTP [Response].
///
/// Parameters:
///
/// * [String] id (required):
Future<Response> deleteAssetFileWithHttpInfo(String id,) async {
// ignore: prefer_const_declarations
final apiPath = r'/asset-files/{id}'
.replaceAll('{id}', id);
// ignore: prefer_final_locals
Object? postBody;
final queryParams = <QueryParam>[];
final headerParams = <String, String>{};
final formParams = <String, String>{};
const contentTypes = <String>[];
return apiClient.invokeAPI(
apiPath,
'DELETE',
queryParams,
postBody,
headerParams,
formParams,
contentTypes.isEmpty ? null : contentTypes.first,
);
}
/// Delete an asset file
///
/// Delete a file and remove it from the database.
///
/// Parameters:
///
/// * [String] id (required):
Future<void> deleteAssetFile(String id,) async {
final response = await deleteAssetFileWithHttpInfo(id,);
if (response.statusCode >= HttpStatus.badRequest) {
throw ApiException(response.statusCode, await _decodeBodyBytes(response));
}
}
/// Download an asset file
///
/// Serve the contents of a specific asset file.
///
/// Note: This method returns the HTTP [Response].
///
/// Parameters:
///
/// * [String] id (required):
Future<Response> downloadAssetFileWithHttpInfo(String id,) async {
// ignore: prefer_const_declarations
final apiPath = r'/asset-files/{id}/download'
.replaceAll('{id}', id);
// ignore: prefer_final_locals
Object? postBody;
final queryParams = <QueryParam>[];
final headerParams = <String, String>{};
final formParams = <String, String>{};
const contentTypes = <String>[];
return apiClient.invokeAPI(
apiPath,
'GET',
queryParams,
postBody,
headerParams,
formParams,
contentTypes.isEmpty ? null : contentTypes.first,
);
}
/// Download an asset file
///
/// Serve the contents of a specific asset file.
///
/// Parameters:
///
/// * [String] id (required):
Future<MultipartFile?> downloadAssetFile(String id,) async {
final response = await downloadAssetFileWithHttpInfo(id,);
if (response.statusCode >= HttpStatus.badRequest) {
throw ApiException(response.statusCode, await _decodeBodyBytes(response));
}
// When a remote server returns no body with a status of 204, we shall not decode it.
// At the time of writing this, `dart:convert` will throw an "Unexpected end of input"
// FormatException when trying to decode an empty string.
if (response.body.isNotEmpty && response.statusCode != HttpStatus.noContent) {
return await apiClient.deserializeAsync(await _decodeBodyBytes(response), 'MultipartFile',) as MultipartFile;
}
return null;
}
/// Retrieve an asset file
///
/// Returns a metadata about a specific asset file.
///
/// Note: This method returns the HTTP [Response].
///
/// Parameters:
///
/// * [String] id (required):
Future<Response> getAssetFileWithHttpInfo(String id,) async {
// ignore: prefer_const_declarations
final apiPath = r'/asset-files/{id}'
.replaceAll('{id}', id);
// ignore: prefer_final_locals
Object? postBody;
final queryParams = <QueryParam>[];
final headerParams = <String, String>{};
final formParams = <String, String>{};
const contentTypes = <String>[];
return apiClient.invokeAPI(
apiPath,
'GET',
queryParams,
postBody,
headerParams,
formParams,
contentTypes.isEmpty ? null : contentTypes.first,
);
}
/// Retrieve an asset file
///
/// Returns a metadata about a specific asset file.
///
/// Parameters:
///
/// * [String] id (required):
Future<AssetFileResponseDto?> getAssetFile(String id,) async {
final response = await getAssetFileWithHttpInfo(id,);
if (response.statusCode >= HttpStatus.badRequest) {
throw ApiException(response.statusCode, await _decodeBodyBytes(response));
}
// When a remote server returns no body with a status of 204, we shall not decode it.
// At the time of writing this, `dart:convert` will throw an "Unexpected end of input"
// FormatException when trying to decode an empty string.
if (response.body.isNotEmpty && response.statusCode != HttpStatus.noContent) {
return await apiClient.deserializeAsync(await _decodeBodyBytes(response), 'AssetFileResponseDto',) as AssetFileResponseDto;
}
return null;
}
/// Retrieve an asset file
///
/// Returns a metadata about a specific asset file.
///
/// Note: This method returns the HTTP [Response].
///
/// Parameters:
///
/// * [String] assetId (required):
/// Asset ID to filter files by
///
/// * [bool] isEdited:
/// The file was generated from an edit
///
/// * [bool] isProgressive:
/// The file is a progressively encoded JPEG
///
/// * [AssetFileType] type:
/// Filter by type of file
Future<Response> searchAssetFilesWithHttpInfo(String assetId, { bool? isEdited, bool? isProgressive, AssetFileType? type, }) async {
// ignore: prefer_const_declarations
final apiPath = r'/asset-files';
// ignore: prefer_final_locals
Object? postBody;
final queryParams = <QueryParam>[];
final headerParams = <String, String>{};
final formParams = <String, String>{};
queryParams.addAll(_queryParams('', 'assetId', assetId));
if (isEdited != null) {
queryParams.addAll(_queryParams('', 'isEdited', isEdited));
}
if (isProgressive != null) {
queryParams.addAll(_queryParams('', 'isProgressive', isProgressive));
}
if (type != null) {
queryParams.addAll(_queryParams('', 'type', type));
}
const contentTypes = <String>[];
return apiClient.invokeAPI(
apiPath,
'GET',
queryParams,
postBody,
headerParams,
formParams,
contentTypes.isEmpty ? null : contentTypes.first,
);
}
/// Retrieve an asset file
///
/// Returns a metadata about a specific asset file.
///
/// Parameters:
///
/// * [String] assetId (required):
/// Asset ID to filter files by
///
/// * [bool] isEdited:
/// The file was generated from an edit
///
/// * [bool] isProgressive:
/// The file is a progressively encoded JPEG
///
/// * [AssetFileType] type:
/// Filter by type of file
Future<List<AssetFileResponseDto>?> searchAssetFiles(String assetId, { bool? isEdited, bool? isProgressive, AssetFileType? type, }) async {
final response = await searchAssetFilesWithHttpInfo(assetId, isEdited: isEdited, isProgressive: isProgressive, type: type, );
if (response.statusCode >= HttpStatus.badRequest) {
throw ApiException(response.statusCode, await _decodeBodyBytes(response));
}
// When a remote server returns no body with a status of 204, we shall not decode it.
// At the time of writing this, `dart:convert` will throw an "Unexpected end of input"
// FormatException when trying to decode an empty string.
if (response.body.isNotEmpty && response.statusCode != HttpStatus.noContent) {
final responseBody = await _decodeBodyBytes(response);
return (await apiClient.deserializeAsync(responseBody, 'List<AssetFileResponseDto>') as List)
.cast<AssetFileResponseDto>()
.toList(growable: false);
}
return null;
}
}
+4
View File
@@ -264,6 +264,10 @@ class ApiClient {
return AssetFaceUpdateItem.fromJson(value);
case 'AssetFaceWithoutPersonResponseDto':
return AssetFaceWithoutPersonResponseDto.fromJson(value);
case 'AssetFileResponseDto':
return AssetFileResponseDto.fromJson(value);
case 'AssetFileType':
return AssetFileTypeTypeTransformer().decode(value);
case 'AssetFullSyncDto':
return AssetFullSyncDto.fromJson(value);
case 'AssetIdsDto':
+3
View File
@@ -61,6 +61,9 @@ String parameterToString(dynamic value) {
if (value is AssetEditAction) {
return AssetEditActionTypeTransformer().encode(value).toString();
}
if (value is AssetFileType) {
return AssetFileTypeTypeTransformer().encode(value).toString();
}
if (value is AssetJobName) {
return AssetJobNameTypeTransformer().encode(value).toString();
}
+1 -1
View File
@@ -53,7 +53,7 @@ class AssetBulkUpdateDto {
///
String? description;
/// Duplicate asset ID
/// Duplicate ID
String? duplicateId;
/// Asset IDs to update
+154
View File
@@ -0,0 +1,154 @@
//
// AUTO-GENERATED FILE, DO NOT MODIFY!
//
// @dart=2.18
// ignore_for_file: unused_element, unused_import
// ignore_for_file: always_put_required_named_parameters_first
// ignore_for_file: constant_identifier_names
// ignore_for_file: lines_longer_than_80_chars
part of openapi.api;
class AssetFileResponseDto {
/// Returns a new [AssetFileResponseDto] instance.
AssetFileResponseDto({
required this.createdAt,
required this.id,
required this.isEdited,
required this.isProgressive,
required this.path,
required this.type,
required this.updatedAt,
});
/// Creation date
DateTime createdAt;
/// Asset file ID
String id;
/// The file was generated from an edit
bool isEdited;
/// The file is a progressively encoded JPEG
bool isProgressive;
/// File path
String path;
/// Type of file
AssetFileType type;
/// Update date
DateTime updatedAt;
@override
bool operator ==(Object other) => identical(this, other) || other is AssetFileResponseDto &&
other.createdAt == createdAt &&
other.id == id &&
other.isEdited == isEdited &&
other.isProgressive == isProgressive &&
other.path == path &&
other.type == type &&
other.updatedAt == updatedAt;
@override
int get hashCode =>
// ignore: unnecessary_parenthesis
(createdAt.hashCode) +
(id.hashCode) +
(isEdited.hashCode) +
(isProgressive.hashCode) +
(path.hashCode) +
(type.hashCode) +
(updatedAt.hashCode);
@override
String toString() => 'AssetFileResponseDto[createdAt=$createdAt, id=$id, isEdited=$isEdited, isProgressive=$isProgressive, path=$path, type=$type, updatedAt=$updatedAt]';
Map<String, dynamic> toJson() {
final json = <String, dynamic>{};
json[r'createdAt'] = this.createdAt.toUtc().toIso8601String();
json[r'id'] = this.id;
json[r'isEdited'] = this.isEdited;
json[r'isProgressive'] = this.isProgressive;
json[r'path'] = this.path;
json[r'type'] = this.type;
json[r'updatedAt'] = this.updatedAt.toUtc().toIso8601String();
return json;
}
/// Returns a new [AssetFileResponseDto] instance and imports its values from
/// [value] if it's a [Map], null otherwise.
// ignore: prefer_constructors_over_static_methods
static AssetFileResponseDto? fromJson(dynamic value) {
upgradeDto(value, "AssetFileResponseDto");
if (value is Map) {
final json = value.cast<String, dynamic>();
return AssetFileResponseDto(
createdAt: mapDateTime(json, r'createdAt', r'')!,
id: mapValueOfType<String>(json, r'id')!,
isEdited: mapValueOfType<bool>(json, r'isEdited')!,
isProgressive: mapValueOfType<bool>(json, r'isProgressive')!,
path: mapValueOfType<String>(json, r'path')!,
type: AssetFileType.fromJson(json[r'type'])!,
updatedAt: mapDateTime(json, r'updatedAt', r'')!,
);
}
return null;
}
static List<AssetFileResponseDto> listFromJson(dynamic json, {bool growable = false,}) {
final result = <AssetFileResponseDto>[];
if (json is List && json.isNotEmpty) {
for (final row in json) {
final value = AssetFileResponseDto.fromJson(row);
if (value != null) {
result.add(value);
}
}
}
return result.toList(growable: growable);
}
static Map<String, AssetFileResponseDto> mapFromJson(dynamic json) {
final map = <String, AssetFileResponseDto>{};
if (json is Map && json.isNotEmpty) {
json = json.cast<String, dynamic>(); // ignore: parameter_assignments
for (final entry in json.entries) {
final value = AssetFileResponseDto.fromJson(entry.value);
if (value != null) {
map[entry.key] = value;
}
}
}
return map;
}
// maps a json object with a list of AssetFileResponseDto-objects as value to a dart map
static Map<String, List<AssetFileResponseDto>> mapListFromJson(dynamic json, {bool growable = false,}) {
final map = <String, List<AssetFileResponseDto>>{};
if (json is Map && json.isNotEmpty) {
// ignore: parameter_assignments
json = json.cast<String, dynamic>();
for (final entry in json.entries) {
map[entry.key] = AssetFileResponseDto.listFromJson(entry.value, growable: growable,);
}
}
return map;
}
/// The list of required keys that must be present in a JSON.
static const requiredKeys = <String>{
'createdAt',
'id',
'isEdited',
'isProgressive',
'path',
'type',
'updatedAt',
};
}
+91
View File
@@ -0,0 +1,91 @@
//
// AUTO-GENERATED FILE, DO NOT MODIFY!
//
// @dart=2.18
// ignore_for_file: unused_element, unused_import
// ignore_for_file: always_put_required_named_parameters_first
// ignore_for_file: constant_identifier_names
// ignore_for_file: lines_longer_than_80_chars
part of openapi.api;
class AssetFileType {
/// Instantiate a new enum with the provided [value].
const AssetFileType._(this.value);
/// The underlying value of this enum member.
final String value;
@override
String toString() => value;
String toJson() => value;
static const fullsize = AssetFileType._(r'fullsize');
static const preview = AssetFileType._(r'preview');
static const thumbnail = AssetFileType._(r'thumbnail');
static const sidecar = AssetFileType._(r'sidecar');
/// List of all possible values in this [enum][AssetFileType].
static const values = <AssetFileType>[
fullsize,
preview,
thumbnail,
sidecar,
];
static AssetFileType? fromJson(dynamic value) => AssetFileTypeTypeTransformer().decode(value);
static List<AssetFileType> listFromJson(dynamic json, {bool growable = false,}) {
final result = <AssetFileType>[];
if (json is List && json.isNotEmpty) {
for (final row in json) {
final value = AssetFileType.fromJson(row);
if (value != null) {
result.add(value);
}
}
}
return result.toList(growable: growable);
}
}
/// Transformation class that can [encode] an instance of [AssetFileType] to String,
/// and [decode] dynamic data back to [AssetFileType].
class AssetFileTypeTypeTransformer {
factory AssetFileTypeTypeTransformer() => _instance ??= const AssetFileTypeTypeTransformer._();
const AssetFileTypeTypeTransformer._();
String encode(AssetFileType data) => data.value;
/// Decodes a [dynamic value][data] to a AssetFileType.
///
/// If [allowNull] is true and the [dynamic value][data] cannot be decoded successfully,
/// then null is returned. However, if [allowNull] is false and the [dynamic value][data]
/// cannot be decoded successfully, then an [UnimplementedError] is thrown.
///
/// The [allowNull] is very handy when an API changes and a new enum value is added or removed,
/// and users are still using an old app with the old code.
AssetFileType? decode(dynamic data, {bool allowNull = true}) {
if (data != null) {
switch (data) {
case r'fullsize': return AssetFileType.fullsize;
case r'preview': return AssetFileType.preview;
case r'thumbnail': return AssetFileType.thumbnail;
case r'sidecar': return AssetFileType.sidecar;
default:
if (!allowNull) {
throw ArgumentError('Unknown enum value to decode: $data');
}
}
}
return null;
}
/// Singleton [AssetFileTypeTypeTransformer] instance.
static AssetFileTypeTypeTransformer? _instance;
}
+9
View File
@@ -44,6 +44,9 @@ class Permission {
static const assetPeriodReplace = Permission._(r'asset.replace');
static const assetPeriodCopy = Permission._(r'asset.copy');
static const assetPeriodDerive = Permission._(r'asset.derive');
static const assetFilePeriodRead = Permission._(r'assetFile.read');
static const assetFilePeriodDelete = Permission._(r'assetFile.delete');
static const assetFilePeriodDownload = Permission._(r'assetFile.download');
static const assetPeriodEditPeriodGet = Permission._(r'asset.edit.get');
static const assetPeriodEditPeriodCreate = Permission._(r'asset.edit.create');
static const assetPeriodEditPeriodDelete = Permission._(r'asset.edit.delete');
@@ -203,6 +206,9 @@ class Permission {
assetPeriodReplace,
assetPeriodCopy,
assetPeriodDerive,
assetFilePeriodRead,
assetFilePeriodDelete,
assetFilePeriodDownload,
assetPeriodEditPeriodGet,
assetPeriodEditPeriodCreate,
assetPeriodEditPeriodDelete,
@@ -397,6 +403,9 @@ class PermissionTypeTransformer {
case r'asset.replace': return Permission.assetPeriodReplace;
case r'asset.copy': return Permission.assetPeriodCopy;
case r'asset.derive': return Permission.assetPeriodDerive;
case r'assetFile.read': return Permission.assetFilePeriodRead;
case r'assetFile.delete': return Permission.assetFilePeriodDelete;
case r'assetFile.download': return Permission.assetFilePeriodDownload;
case r'asset.edit.get': return Permission.assetPeriodEditPeriodGet;
case r'asset.edit.create': return Permission.assetPeriodEditPeriodCreate;
case r'asset.edit.delete': return Permission.assetPeriodEditPeriodDelete;
+13 -1
View File
@@ -19,6 +19,7 @@ class UserAdminCreateDto {
required this.name,
this.notify,
required this.password,
this.pinCode,
this.quotaSizeInBytes,
this.shouldChangePassword,
this.storageLabel,
@@ -54,6 +55,9 @@ class UserAdminCreateDto {
/// User password
String password;
/// PIN code
String? pinCode;
/// Storage quota in bytes
///
/// Minimum value: 0
@@ -79,6 +83,7 @@ class UserAdminCreateDto {
other.name == name &&
other.notify == notify &&
other.password == password &&
other.pinCode == pinCode &&
other.quotaSizeInBytes == quotaSizeInBytes &&
other.shouldChangePassword == shouldChangePassword &&
other.storageLabel == storageLabel;
@@ -92,12 +97,13 @@ class UserAdminCreateDto {
(name.hashCode) +
(notify == null ? 0 : notify!.hashCode) +
(password.hashCode) +
(pinCode == null ? 0 : pinCode!.hashCode) +
(quotaSizeInBytes == null ? 0 : quotaSizeInBytes!.hashCode) +
(shouldChangePassword == null ? 0 : shouldChangePassword!.hashCode) +
(storageLabel == null ? 0 : storageLabel!.hashCode);
@override
String toString() => 'UserAdminCreateDto[avatarColor=$avatarColor, email=$email, isAdmin=$isAdmin, name=$name, notify=$notify, password=$password, quotaSizeInBytes=$quotaSizeInBytes, shouldChangePassword=$shouldChangePassword, storageLabel=$storageLabel]';
String toString() => 'UserAdminCreateDto[avatarColor=$avatarColor, email=$email, isAdmin=$isAdmin, name=$name, notify=$notify, password=$password, pinCode=$pinCode, quotaSizeInBytes=$quotaSizeInBytes, shouldChangePassword=$shouldChangePassword, storageLabel=$storageLabel]';
Map<String, dynamic> toJson() {
final json = <String, dynamic>{};
@@ -119,6 +125,11 @@ class UserAdminCreateDto {
// json[r'notify'] = null;
}
json[r'password'] = this.password;
if (this.pinCode != null) {
json[r'pinCode'] = this.pinCode;
} else {
// json[r'pinCode'] = null;
}
if (this.quotaSizeInBytes != null) {
json[r'quotaSizeInBytes'] = this.quotaSizeInBytes;
} else {
@@ -152,6 +163,7 @@ class UserAdminCreateDto {
name: mapValueOfType<String>(json, r'name')!,
notify: mapValueOfType<bool>(json, r'notify'),
password: mapValueOfType<String>(json, r'password')!,
pinCode: mapValueOfType<String>(json, r'pinCode'),
quotaSizeInBytes: mapValueOfType<int>(json, r'quotaSizeInBytes'),
shouldChangePassword: mapValueOfType<bool>(json, r'shouldChangePassword'),
storageLabel: mapValueOfType<String>(json, r'storageLabel'),
+321 -2
View File
@@ -1618,7 +1618,7 @@
"name": "shared",
"required": false,
"in": "query",
"description": "Filter by shared status: true = only shared, false = only own, undefined = all",
"description": "Filter by shared status: true = only shared, false = not shared, undefined = all owned albums",
"schema": {
"type": "boolean"
}
@@ -2760,6 +2760,253 @@
"x-immich-state": "Stable"
}
},
"/asset-files": {
"get": {
"description": "Returns a metadata about a specific asset file.",
"operationId": "searchAssetFiles",
"parameters": [
{
"name": "assetId",
"required": true,
"in": "query",
"description": "Asset ID to filter files by",
"schema": {
"format": "uuid",
"type": "string"
}
},
{
"name": "isEdited",
"required": false,
"in": "query",
"description": "The file was generated from an edit",
"schema": {
"type": "boolean"
}
},
{
"name": "isProgressive",
"required": false,
"in": "query",
"description": "The file is a progressively encoded JPEG",
"schema": {
"type": "boolean"
}
},
{
"name": "type",
"required": false,
"in": "query",
"description": "Filter by type of file",
"schema": {
"$ref": "#/components/schemas/AssetFileType"
}
}
],
"responses": {
"200": {
"content": {
"application/json": {
"schema": {
"items": {
"$ref": "#/components/schemas/AssetFileResponseDto"
},
"type": "array"
}
}
},
"description": ""
}
},
"security": [
{
"bearer": []
},
{
"cookie": []
},
{
"api_key": []
}
],
"summary": "Retrieve an asset file",
"tags": [
"Asset files"
],
"x-immich-history": [
{
"version": "v2.6.0",
"state": "Added"
},
{
"version": "v2.6.0",
"state": "Beta"
}
],
"x-immich-permission": "assetFile.read",
"x-immich-state": "Beta"
}
},
"/asset-files/{id}": {
"delete": {
"description": "Delete a file and remove it from the database.",
"operationId": "deleteAssetFile",
"parameters": [
{
"name": "id",
"required": true,
"in": "path",
"schema": {
"format": "uuid",
"type": "string"
}
}
],
"responses": {
"204": {
"description": ""
}
},
"security": [
{
"bearer": []
},
{
"cookie": []
},
{
"api_key": []
}
],
"summary": "Delete an asset file",
"tags": [
"Asset files"
],
"x-immich-history": [
{
"version": "v2.6.0",
"state": "Added"
},
{
"version": "v2.6.0",
"state": "Beta"
}
],
"x-immich-permission": "assetFile.delete",
"x-immich-state": "Beta"
},
"get": {
"description": "Returns a metadata about a specific asset file.",
"operationId": "getAssetFile",
"parameters": [
{
"name": "id",
"required": true,
"in": "path",
"schema": {
"format": "uuid",
"type": "string"
}
}
],
"responses": {
"200": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/AssetFileResponseDto"
}
}
},
"description": ""
}
},
"security": [
{
"bearer": []
},
{
"cookie": []
},
{
"api_key": []
}
],
"summary": "Retrieve an asset file",
"tags": [
"Asset files"
],
"x-immich-history": [
{
"version": "v2.6.0",
"state": "Added"
},
{
"version": "v2.6.0",
"state": "Beta"
}
],
"x-immich-permission": "assetFile.read",
"x-immich-state": "Beta"
}
},
"/asset-files/{id}/download": {
"get": {
"description": "Serve the contents of a specific asset file.",
"operationId": "downloadAssetFile",
"parameters": [
{
"name": "id",
"required": true,
"in": "path",
"schema": {
"format": "uuid",
"type": "string"
}
}
],
"responses": {
"200": {
"content": {
"application/octet-stream": {
"schema": {
"format": "binary",
"type": "string"
}
}
},
"description": ""
}
},
"security": [
{
"bearer": []
},
{
"cookie": []
},
{
"api_key": []
}
],
"summary": "Download an asset file",
"tags": [
"Asset files"
],
"x-immich-history": [
{
"version": "v2.6.0",
"state": "Added"
},
{
"version": "v2.6.0",
"state": "Beta"
}
],
"x-immich-permission": "assetFile.download",
"x-immich-state": "Beta"
}
},
"/assets": {
"delete": {
"description": "Deletes multiple assets at the same time.",
@@ -15077,6 +15324,10 @@
"name": "Assets",
"description": "An asset is an image or video that has been uploaded to Immich."
},
{
"name": "Asset files",
"description": "An asset file is a file associated with an asset, including edited versions, thumbnails, etc."
},
{
"name": "Authentication",
"description": "Endpoints related to user authentication, including OAuth."
@@ -15760,7 +16011,7 @@
"type": "string"
},
"duplicateId": {
"description": "Duplicate asset ID",
"description": "Duplicate ID",
"nullable": true,
"type": "string"
},
@@ -16320,6 +16571,63 @@
],
"type": "object"
},
"AssetFileResponseDto": {
"properties": {
"createdAt": {
"description": "Creation date",
"format": "date-time",
"type": "string"
},
"id": {
"description": "Asset file ID",
"type": "string"
},
"isEdited": {
"description": "The file was generated from an edit",
"type": "boolean"
},
"isProgressive": {
"description": "The file is a progressively encoded JPEG",
"type": "boolean"
},
"path": {
"description": "File path",
"type": "string"
},
"type": {
"allOf": [
{
"$ref": "#/components/schemas/AssetFileType"
}
],
"description": "Type of file"
},
"updatedAt": {
"description": "Update date",
"format": "date-time",
"type": "string"
}
},
"required": [
"createdAt",
"id",
"isEdited",
"isProgressive",
"path",
"type",
"updatedAt"
],
"type": "object"
},
"AssetFileType": {
"enum": [
"fullsize",
"preview",
"thumbnail",
"sidecar"
],
"type": "string"
},
"AssetFullSyncDto": {
"properties": {
"lastId": {
@@ -19038,6 +19346,7 @@
"format": "uuid",
"type": "string"
},
"minItems": 1,
"type": "array"
}
},
@@ -19128,6 +19437,7 @@
"format": "uuid",
"type": "string"
},
"minItems": 1,
"type": "array"
},
"readAt": {
@@ -19518,6 +19828,9 @@
"asset.replace",
"asset.copy",
"asset.derive",
"assetFile.read",
"assetFile.delete",
"assetFile.download",
"asset.edit.get",
"asset.edit.create",
"asset.edit.delete",
@@ -25069,6 +25382,12 @@
"description": "User password",
"type": "string"
},
"pinCode": {
"description": "PIN code",
"example": "123456",
"nullable": true,
"type": "string"
},
"quotaSizeInBytes": {
"description": "Storage quota in bytes",
"format": "int64",
+86 -1
View File
@@ -233,6 +233,8 @@ export type UserAdminCreateDto = {
notify?: boolean;
/** User password */
password: string;
/** PIN code */
pinCode?: string | null;
/** Storage quota in bytes */
quotaSizeInBytes?: number | null;
/** Require password change on next login */
@@ -771,6 +773,22 @@ export type ApiKeyUpdateDto = {
/** List of permissions */
permissions?: Permission[];
};
export type AssetFileResponseDto = {
/** Creation date */
createdAt: string;
/** Asset file ID */
id: string;
/** The file was generated from an edit */
isEdited: boolean;
/** The file is a progressively encoded JPEG */
isProgressive: boolean;
/** File path */
path: string;
/** Type of file */
"type": AssetFileType;
/** Update date */
updatedAt: string;
};
export type AssetBulkDeleteDto = {
/** Force delete even if in use */
force?: boolean;
@@ -822,7 +840,7 @@ export type AssetBulkUpdateDto = {
dateTimeRelative?: number;
/** Asset description */
description?: string;
/** Duplicate asset ID */
/** Duplicate ID */
duplicateId?: string | null;
/** Asset IDs to update */
ids: string[];
@@ -3885,6 +3903,64 @@ export function updateApiKey({ id, apiKeyUpdateDto }: {
body: apiKeyUpdateDto
})));
}
/**
* Retrieve an asset file
*/
export function searchAssetFiles({ assetId, isEdited, isProgressive, $type }: {
assetId: string;
isEdited?: boolean;
isProgressive?: boolean;
$type?: AssetFileType;
}, opts?: Oazapfts.RequestOpts) {
return oazapfts.ok(oazapfts.fetchJson<{
status: 200;
data: AssetFileResponseDto[];
}>(`/asset-files${QS.query(QS.explode({
assetId,
isEdited,
isProgressive,
"type": $type
}))}`, {
...opts
}));
}
/**
* Delete an asset file
*/
export function deleteAssetFile({ id }: {
id: string;
}, opts?: Oazapfts.RequestOpts) {
return oazapfts.ok(oazapfts.fetchText(`/asset-files/${encodeURIComponent(id)}`, {
...opts,
method: "DELETE"
}));
}
/**
* Retrieve an asset file
*/
export function getAssetFile({ id }: {
id: string;
}, opts?: Oazapfts.RequestOpts) {
return oazapfts.ok(oazapfts.fetchJson<{
status: 200;
data: AssetFileResponseDto;
}>(`/asset-files/${encodeURIComponent(id)}`, {
...opts
}));
}
/**
* Download an asset file
*/
export function downloadAssetFile({ id }: {
id: string;
}, opts?: Oazapfts.RequestOpts) {
return oazapfts.ok(oazapfts.fetchBlob<{
status: 200;
data: Blob;
}>(`/asset-files/${encodeURIComponent(id)}/download`, {
...opts
}));
}
/**
* Delete assets
*/
@@ -6860,6 +6936,9 @@ export enum Permission {
AssetReplace = "asset.replace",
AssetCopy = "asset.copy",
AssetDerive = "asset.derive",
AssetFileRead = "assetFile.read",
AssetFileDelete = "assetFile.delete",
AssetFileDownload = "assetFile.download",
AssetEditGet = "asset.edit.get",
AssetEditCreate = "asset.edit.create",
AssetEditDelete = "asset.edit.delete",
@@ -6996,6 +7075,12 @@ export enum Permission {
AdminSessionRead = "adminSession.read",
AdminAuthUnlinkAll = "adminAuth.unlinkAll"
}
export enum AssetFileType {
Fullsize = "fullsize",
Preview = "preview",
Thumbnail = "thumbnail",
Sidecar = "sidecar"
}
export enum AssetMediaStatus {
Created = "created",
Replaced = "replaced",
+1
View File
@@ -139,6 +139,7 @@ export const endpointTags: Record<ApiTag, string> = {
[ApiTag.Albums]: 'An album is a collection of assets that can be shared with other users or via shared links.',
[ApiTag.ApiKeys]: 'An api key can be used to programmatically access the Immich API.',
[ApiTag.Assets]: 'An asset is an image or video that has been uploaded to Immich.',
[ApiTag.AssetFiles]: 'An asset file is a file associated with an asset, including edited versions, thumbnails, etc.',
[ApiTag.Authentication]: 'Endpoints related to user authentication, including OAuth.',
[ApiTag.AuthenticationAdmin]: 'Administrative endpoints related to authentication.',
[ApiTag.DatabaseBackups]: 'Manage backups of the Immich database.',
@@ -0,0 +1,72 @@
import { Controller, Delete, Get, HttpCode, HttpStatus, Next, Param, Query, Res } from '@nestjs/common';
import { ApiTags } from '@nestjs/swagger';
import { NextFunction, Response } from 'express';
import { Endpoint, HistoryBuilder } from 'src/decorators';
import { AssetFileResponseDto, AssetFileSearchDto } from 'src/dtos/asset-file.dto';
import { AuthDto } from 'src/dtos/auth.dto';
import { ApiTag, Permission } from 'src/enum';
import { Auth, Authenticated, FileResponse } from 'src/middleware/auth.guard';
import { LoggingRepository } from 'src/repositories/logging.repository';
import { AssetFileService } from 'src/services/asset-file.service';
import { sendFile } from 'src/utils/file';
import { UUIDParamDto } from 'src/validation';
@ApiTags(ApiTag.AssetFiles)
@Controller('asset-files')
export class AssetFilesController {
constructor(
private service: AssetFileService,
private logger: LoggingRepository,
) {}
@Get()
@Authenticated({ permission: Permission.AssetFileRead })
@Endpoint({
summary: 'Retrieve an asset file',
description: 'Returns a metadata about a specific asset file.',
history: new HistoryBuilder().added('v2.6.0').beta('v2.6.0'),
})
searchAssetFiles(@Auth() auth: AuthDto, @Query() dto: AssetFileSearchDto): Promise<AssetFileResponseDto[]> {
return this.service.search(auth, dto);
}
@Get(':id')
@Authenticated({ permission: Permission.AssetFileRead })
@Endpoint({
summary: 'Retrieve an asset file',
description: 'Returns a metadata about a specific asset file.',
history: new HistoryBuilder().added('v2.6.0').beta('v2.6.0'),
})
getAssetFile(@Auth() auth: AuthDto, @Param() { id }: UUIDParamDto): Promise<AssetFileResponseDto> {
return this.service.get(auth, id);
}
@Delete(':id')
@Authenticated({ permission: Permission.AssetFileDelete })
@HttpCode(HttpStatus.NO_CONTENT)
@Endpoint({
summary: 'Delete an asset file',
description: 'Delete a file and remove it from the database.',
history: new HistoryBuilder().added('v2.6.0').beta('v2.6.0'),
})
deleteAssetFile(@Auth() auth: AuthDto, @Param() { id }: UUIDParamDto): Promise<void> {
return this.service.delete(auth, id);
}
@Get(':id/download')
@FileResponse()
@Authenticated({ permission: Permission.AssetFileDownload })
@Endpoint({
summary: 'Download an asset file',
description: 'Serve the contents of a specific asset file.',
history: new HistoryBuilder().added('v2.6.0').beta('v2.6.0'),
})
async downloadAssetFile(
@Auth() auth: AuthDto,
@Param() { id }: UUIDParamDto,
@Res() res: Response,
@Next() next: NextFunction,
) {
await sendFile(res, next, () => this.service.download(auth, id), this.logger);
}
}
@@ -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', () => {
+2
View File
@@ -2,6 +2,7 @@ import { ActivityController } from 'src/controllers/activity.controller';
import { AlbumController } from 'src/controllers/album.controller';
import { ApiKeyController } from 'src/controllers/api-key.controller';
import { AppController } from 'src/controllers/app.controller';
import { AssetFilesController } from 'src/controllers/asset-file.controller';
import { AssetMediaController } from 'src/controllers/asset-media.controller';
import { AssetController } from 'src/controllers/asset.controller';
import { AuthAdminController } from 'src/controllers/auth-admin.controller';
@@ -44,6 +45,7 @@ export const controllers = [
AlbumController,
AppController,
AssetController,
AssetFilesController,
AssetMediaController,
AuthController,
AuthAdminController,
@@ -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 }));
});
});
});
@@ -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 }));
});
});
});
@@ -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', () => {
@@ -0,0 +1,34 @@
import { SharedLinkController } from 'src/controllers/shared-link.controller';
import { SharedLinkType } from 'src/enum';
import { SharedLinkService } from 'src/services/shared-link.service';
import request from 'supertest';
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 }));
});
});
});
@@ -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 }));
});
});
});
@@ -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 }));
});
});
});
@@ -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', () => {
+1 -1
View File
@@ -102,7 +102,7 @@ export class UpdateAlbumDto {
export class GetAlbumsDto {
@ValidateBoolean({
optional: true,
description: 'Filter by shared status: true = only shared, false = only own, undefined = all',
description: 'Filter by shared status: true = only shared, false = not shared, undefined = all owned albums',
})
shared?: boolean;
+54
View File
@@ -0,0 +1,54 @@
import { ApiProperty } from '@nestjs/swagger';
import { Selectable } from 'kysely';
import { AssetFileType } from 'src/enum';
import { AssetFileTable } from 'src/schema/tables/asset-file.table';
import { ValidateBoolean, ValidateEnum, ValidateUUID } from 'src/validation';
export class AssetFileSearchDto {
@ValidateUUID({ description: 'Asset ID to filter files by' })
assetId!: string;
@ValidateEnum({ enum: AssetFileType, name: 'AssetFileType', optional: true, description: 'Filter by type of file' })
type?: AssetFileType;
@ValidateBoolean({ optional: true, description: 'The file was generated from an edit' })
isEdited?: boolean;
@ValidateBoolean({ optional: true, description: 'The file is a progressively encoded JPEG' })
isProgressive?: boolean;
}
export class AssetFileResponseDto {
@ApiProperty({ description: 'Asset file ID' })
id!: string;
@ApiProperty({ description: 'Creation date', format: 'date-time' })
createdAt!: Date;
@ApiProperty({ description: 'Update date', format: 'date-time' })
updatedAt!: Date;
@ValidateEnum({ enum: AssetFileType, name: 'AssetFileType', description: 'Type of file' })
type!: AssetFileType;
@ApiProperty({ description: 'File path' })
path!: string;
@ApiProperty({ description: 'The file was generated from an edit' })
isEdited!: boolean;
@ApiProperty({ description: 'The file is a progressively encoded JPEG' })
isProgressive!: boolean;
}
export const mapAssetFile = (file: Selectable<AssetFileTable>): AssetFileResponseDto => {
return {
id: file.id,
// assetId: file.assetId,
createdAt: file.createdAt,
updatedAt: file.updatedAt,
type: file.type,
path: file.path,
isEdited: file.isEdited,
isProgressive: file.isProgressive,
};
};
+1 -2
View File
@@ -73,8 +73,7 @@ export class AssetBulkUpdateDto extends UpdateAssetBase {
@ValidateUUID({ each: true, description: 'Asset IDs to update' })
ids!: string[];
@ApiProperty({ description: 'Duplicate asset ID' })
@Optional()
@ValidateString({ optional: true, nullable: true, description: 'Duplicate ID' })
duplicateId?: string | null;
@ApiProperty({ description: 'Relative time offset in seconds' })
+10 -11
View File
@@ -1,7 +1,7 @@
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import { IsString } from 'class-validator';
import { ArrayMinSize, IsString } from 'class-validator';
import { NotificationLevel, NotificationType } from 'src/enum';
import { Optional, ValidateBoolean, ValidateDate, ValidateEnum, ValidateUUID } from 'src/validation';
import { Optional, ValidateBoolean, ValidateDate, ValidateEnum, ValidateString, ValidateUUID } from 'src/validation';
export class TestEmailResponseDto {
@ApiProperty({ description: 'Email message ID' })
@@ -75,20 +75,17 @@ export class NotificationCreateDto {
@ValidateEnum({ enum: NotificationType, name: 'NotificationType', optional: true, description: 'Notification type' })
type?: NotificationType;
@ApiProperty({ description: 'Notification title' })
@IsString()
@ValidateString({ description: 'Notification title' })
title!: string;
@ApiPropertyOptional({ description: 'Notification description' })
@IsString()
@Optional({ nullable: true })
@ValidateString({ optional: true, nullable: true, description: 'Notification description' })
description?: string | null;
@ApiPropertyOptional({ description: 'Additional notification data' })
@Optional({ nullable: true })
data?: any;
@ValidateDate({ optional: true, description: 'Date when notification was read' })
@ValidateDate({ optional: true, nullable: true, description: 'Date when notification was read' })
readAt?: Date | null;
@ValidateUUID({ description: 'User ID to send notification to' })
@@ -96,20 +93,22 @@ export class NotificationCreateDto {
}
export class NotificationUpdateDto {
@ValidateDate({ optional: true, description: 'Date when notification was read' })
@ValidateDate({ optional: true, nullable: true, description: 'Date when notification was read' })
readAt?: Date | null;
}
export class NotificationUpdateAllDto {
@ValidateUUID({ each: true, optional: true, description: 'Notification IDs to update' })
@ValidateUUID({ each: true, description: 'Notification IDs to update' })
@ArrayMinSize(1)
ids!: string[];
@ValidateDate({ optional: true, description: 'Date when notifications were read' })
@ValidateDate({ optional: true, nullable: true, description: 'Date when notifications were read' })
readAt?: Date | null;
}
export class NotificationDeleteAllDto {
@ValidateUUID({ each: true, description: 'Notification IDs to delete' })
@ArrayMinSize(1)
ids!: string[];
}
+1 -1
View File
@@ -44,7 +44,7 @@ export class SharedLinkCreateDto {
@IsString()
slug?: string | null;
@ValidateDate({ optional: true, description: 'Expiration date' })
@ValidateDate({ optional: true, nullable: true, description: 'Expiration date' })
expiresAt?: Date | null = null;
@ValidateBoolean({ optional: true, description: 'Allow uploads' })
+2 -2
View File
@@ -9,7 +9,7 @@ export class TagCreateDto {
@IsNotEmpty()
name!: string;
@ValidateUUID({ optional: true, description: 'Parent tag ID' })
@ValidateUUID({ nullable: true, optional: true, description: 'Parent tag ID' })
parentId?: string | null;
@ApiPropertyOptional({ description: 'Tag color (hex)' })
@@ -20,7 +20,7 @@ export class TagCreateDto {
export class TagUpdateDto {
@ApiPropertyOptional({ description: 'Tag color (hex)' })
@Optional({ emptyToNull: true })
@Optional({ nullable: true, emptyToNull: true })
@ValidateHexColor()
color?: string | null;
}
+26 -4
View File
@@ -26,7 +26,13 @@ export class UserUpdateMeDto {
@IsNotEmpty()
name?: string;
@ValidateEnum({ enum: UserAvatarColor, name: 'UserAvatarColor', optional: true, description: 'Avatar color' })
@ValidateEnum({
enum: UserAvatarColor,
name: 'UserAvatarColor',
optional: true,
nullable: true,
description: 'Avatar color',
})
avatarColor?: UserAvatarColor | null;
}
@@ -96,9 +102,19 @@ export class UserAdminCreateDto {
@IsString()
name!: string;
@ValidateEnum({ enum: UserAvatarColor, name: 'UserAvatarColor', optional: true, description: 'Avatar color' })
@ValidateEnum({
enum: UserAvatarColor,
name: 'UserAvatarColor',
optional: true,
nullable: true,
description: 'Avatar color',
})
avatarColor?: UserAvatarColor | null;
@ApiPropertyOptional({ description: 'PIN code' })
@PinCode({ optional: true, nullable: true, emptyToNull: true })
pinCode?: string | null;
@ApiPropertyOptional({ description: 'Storage label' })
@Optional({ nullable: true })
@IsString()
@@ -135,7 +151,7 @@ export class UserAdminUpdateDto {
password?: string;
@ApiPropertyOptional({ description: 'PIN code' })
@PinCode({ optional: true, emptyToNull: true })
@PinCode({ optional: true, nullable: true, emptyToNull: true })
pinCode?: string | null;
@ApiPropertyOptional({ description: 'User name' })
@@ -144,7 +160,13 @@ export class UserAdminUpdateDto {
@IsNotEmpty()
name?: string;
@ValidateEnum({ enum: UserAvatarColor, name: 'UserAvatarColor', optional: true, description: 'Avatar color' })
@ValidateEnum({
enum: UserAvatarColor,
name: 'UserAvatarColor',
optional: true,
nullable: true,
description: 'Avatar color',
})
avatarColor?: UserAvatarColor | null;
@ApiPropertyOptional({ description: 'Storage label' })
+5
View File
@@ -108,6 +108,10 @@ export enum Permission {
AssetCopy = 'asset.copy',
AssetDerive = 'asset.derive',
AssetFileRead = 'assetFile.read',
AssetFileDelete = 'assetFile.delete',
AssetFileDownload = 'assetFile.download',
AssetEditGet = 'asset.edit.get',
AssetEditCreate = 'asset.edit.create',
AssetEditDelete = 'asset.edit.delete',
@@ -852,6 +856,7 @@ export enum ApiTag {
Authentication = 'Authentication',
AuthenticationAdmin = 'Authentication (admin)',
Assets = 'Assets',
AssetFiles = 'Asset files',
DatabaseBackups = 'Database Backups (admin)',
Deprecated = 'Deprecated',
Download = 'Download',
+21 -35
View File
@@ -430,30 +430,6 @@ select
"asset"."originalPath",
"asset"."isOffline",
to_json("asset_exif") as "exifInfo",
(
select
coalesce(json_agg(agg), '[]')
from
(
select
"asset_face".*,
"person" as "person"
from
"asset_face"
left join lateral (
select
"person".*
from
"person"
where
"asset_face"."personId" = "person"."id"
) as "person" on true
where
"asset_face"."assetId" = "asset"."id"
and "asset_face"."deletedAt" is null
and "asset_face"."isVisible" is true
) as agg
) as "faces",
(
select
coalesce(json_agg(agg), '[]')
@@ -470,27 +446,37 @@ select
"asset_file"."assetId" = "asset"."id"
) as agg
) as "files",
to_json("stacked_assets") as "stack"
to_json("stack_result") as "stack"
from
"asset"
left join "asset_exif" on "asset"."id" = "asset_exif"."assetId"
left join "stack" on "stack"."id" = "asset"."stackId"
left join lateral (
select
"stack"."id",
"stack"."primaryAssetId",
array_agg("stacked") as "assets"
(
select
coalesce(json_agg(agg), '[]')
from
(
select
"stack_asset"."id"
from
"asset" as "stack_asset"
where
"stack_asset"."stackId" = "stack"."id"
and "stack_asset"."id" != "stack"."primaryAssetId"
and "stack_asset"."visibility" = $1
and "stack_asset"."status" != $2
) as agg
) as "assets"
from
"asset" as "stacked"
"stack"
where
"stacked"."deletedAt" is not null
and "stacked"."visibility" = $1
and "stacked"."stackId" = "stack"."id"
group by
"stack"."id"
) as "stacked_assets" on "stack"."id" is not null
"stack"."id" = "asset"."stackId"
) as "stack_result" on true
where
"asset"."id" = $2
"asset"."id" = $3
-- AssetJobRepository.streamForVideoConversion
select
@@ -265,6 +265,28 @@ class AssetAccess {
}
}
class AssetFileAccess {
constructor(private db: Kysely<DB>) {}
@GenerateSql({ params: [DummyValue.UUID, DummyValue.UUID_SET] })
@ChunkedSet({ paramIndex: 1 })
async checkOwnerAccess(userId: string, fileIds: Set<string>, hasElevatedPermission: boolean | undefined) {
if (fileIds.size === 0) {
return new Set<string>();
}
return this.db
.selectFrom('asset_file')
.select('asset_file.id')
.innerJoin('asset', 'asset.id', 'asset_file.assetId')
.$if(!hasElevatedPermission, (eb) => eb.where('asset.visibility', '!=', AssetVisibility.Locked))
.where('asset.ownerId', '=', userId)
.where('asset_file.id', 'in', [...fileIds])
.execute()
.then((files) => new Set(files.map(({ id }) => id)));
}
}
class AuthDeviceAccess {
constructor(private db: Kysely<DB>) {}
@@ -487,6 +509,7 @@ export class AccessRepository {
activity: ActivityAccess;
album: AlbumAccess;
asset: AssetAccess;
assetFile: AssetFileAccess;
authDevice: AuthDeviceAccess;
memory: MemoryAccess;
notification: NotificationAccess;
@@ -502,6 +525,7 @@ export class AccessRepository {
this.activity = new ActivityAccess(db);
this.album = new AlbumAccess(db);
this.asset = new AssetAccess(db);
this.assetFile = new AssetFileAccess(db);
this.authDevice = new AuthDeviceAccess(db);
this.memory = new MemoryAccess(db);
this.notification = new NotificationAccess(db);
@@ -0,0 +1,30 @@
import { Injectable } from '@nestjs/common';
import { Kysely } from 'kysely';
import { InjectKysely } from 'nestjs-kysely';
import { AssetFileSearchDto } from 'src/dtos/asset-file.dto';
import { DB } from 'src/schema';
@Injectable()
export class AssetFileRepository {
constructor(@InjectKysely() private db: Kysely<DB>) {}
get(id: string) {
return this.db.selectFrom('asset_file').where('id', '=', id).selectAll().executeTakeFirst();
}
getByAssetId(dto: AssetFileSearchDto) {
return this.db
.selectFrom('asset_file')
.where('assetId', '=', dto.assetId)
.$if(dto.type !== undefined, (qb) => qb.where('type', '=', dto.type!))
.$if(dto.isEdited !== undefined, (qb) => qb.where('isEdited', '=', dto.isEdited!))
.$if(dto.isProgressive !== undefined, (qb) => qb.where('isProgressive', '=', dto.isProgressive!))
.selectAll()
.execute();
}
async delete(id: string): Promise<boolean> {
const { numDeletedRows } = await this.db.deleteFrom('asset_file').where('id', '=', id).executeTakeFirst();
return Number(numDeletedRows) === 1;
}
}
+21 -16
View File
@@ -1,10 +1,10 @@
import { Injectable } from '@nestjs/common';
import { Kysely } from 'kysely';
import { Kysely, sql } from 'kysely';
import { jsonArrayFrom } from 'kysely/helpers/postgres';
import { InjectKysely } from 'nestjs-kysely';
import { Asset, columns } from 'src/database';
import { columns } from 'src/database';
import { DummyValue, GenerateSql } from 'src/decorators';
import { AssetFileType, AssetType, AssetVisibility } from 'src/enum';
import { AssetFileType, AssetStatus, AssetType, AssetVisibility } from 'src/enum';
import { DB } from 'src/schema';
import {
anyUuid,
@@ -15,7 +15,6 @@ import {
withExif,
withExifInner,
withFaces,
withFacesAndPeople,
withFilePath,
withFiles,
} from 'src/utils/database';
@@ -269,23 +268,29 @@ export class AssetJobRepository {
'asset.isOffline',
])
.$call(withExif)
.select(withFacesAndPeople)
.select(withFiles)
.leftJoin('stack', 'stack.id', 'asset.stackId')
.leftJoinLateral(
(eb) =>
eb
.selectFrom('asset as stacked')
.select(['stack.id', 'stack.primaryAssetId'])
.select((eb) => eb.fn<Asset[]>('array_agg', [eb.table('stacked')]).as('assets'))
.where('stacked.deletedAt', 'is not', null)
.where('stacked.visibility', '=', AssetVisibility.Timeline)
.whereRef('stacked.stackId', '=', 'stack.id')
.groupBy('stack.id')
.as('stacked_assets'),
(join) => join.on('stack.id', 'is not', null),
.selectFrom('stack')
.whereRef('stack.id', '=', 'asset.stackId')
.select((eb) => [
'stack.id',
'stack.primaryAssetId',
jsonArrayFrom(
eb
.selectFrom('asset as stack_asset')
.select(['stack_asset.id'])
.whereRef('stack_asset.stackId', '=', 'stack.id')
.whereRef('stack_asset.id', '!=', 'stack.primaryAssetId')
.where('stack_asset.visibility', '=', sql.val(AssetVisibility.Timeline))
.where('stack_asset.status', '!=', sql.val(AssetStatus.Deleted)),
).as('assets'),
])
.as('stack_result'),
(join) => join.onTrue(),
)
.select((eb) => toJson(eb, 'stacked_assets').as('stack'))
.select((eb) => toJson(eb, 'stack_result').as('stack'))
.where('asset.id', '=', id)
.executeTakeFirst();
}
+2
View File
@@ -5,6 +5,7 @@ import { AlbumRepository } from 'src/repositories/album.repository';
import { ApiKeyRepository } from 'src/repositories/api-key.repository';
import { AppRepository } from 'src/repositories/app.repository';
import { AssetEditRepository } from 'src/repositories/asset-edit.repository';
import { AssetFileRepository } from 'src/repositories/asset-file.repository';
import { AssetJobRepository } from 'src/repositories/asset-job.repository';
import { AssetRepository } from 'src/repositories/asset.repository';
import { AuditRepository } from 'src/repositories/audit.repository';
@@ -61,6 +62,7 @@ export const repositories = [
AppRepository,
AssetRepository,
AssetEditRepository,
AssetFileRepository,
AssetJobRepository,
ConfigRepository,
CronRepository,
@@ -152,7 +152,7 @@ export class StorageRepository {
}
async unlinkDir(folder: string, options: { recursive?: boolean; force?: boolean }) {
await fs.rm(folder, options);
await fs.rm(folder, { ...options, maxRetries: 5, retryDelay: 100 });
}
async removeEmptyDirs(directory: string, self: boolean = false) {
@@ -168,7 +168,13 @@ export class StorageRepository {
if (self) {
const updated = await fs.readdir(directory);
if (updated.length === 0) {
await fs.rmdir(directory);
try {
await fs.rmdir(directory);
} catch (error: Error | any) {
if (error.code !== 'ENOTEMPTY') {
this.logger.warn(`Attempted to remove directory, but failed: ${error}`);
}
}
}
}
}
+48
View File
@@ -0,0 +1,48 @@
import { BadRequestException, Injectable } from '@nestjs/common';
import { AssetFileResponseDto, AssetFileSearchDto, mapAssetFile } from 'src/dtos/asset-file.dto';
import { AuthDto } from 'src/dtos/auth.dto';
import { CacheControl, Permission } from 'src/enum';
import { BaseService } from 'src/services/base.service';
import { getFilenameExtension, getFileNameWithoutExtension, ImmichFileResponse } from 'src/utils/file';
import { mimeTypes } from 'src/utils/mime-types';
@Injectable()
export class AssetFileService extends BaseService {
async search(auth: AuthDto, dto: AssetFileSearchDto): Promise<AssetFileResponseDto[]> {
await this.requireAccess({ auth, permission: Permission.AssetRead, ids: [dto.assetId] });
const files = await this.assetFileRepository.getByAssetId(dto);
return files.map((file) => mapAssetFile(file));
}
async get(auth: AuthDto, id: string): Promise<AssetFileResponseDto> {
await this.requireAccess({ auth, permission: Permission.AssetFileRead, ids: [id] });
const file = await this.findOrFail(id);
return mapAssetFile(file);
}
async download(auth: AuthDto, id: string) {
await this.requireAccess({ auth, permission: Permission.AssetFileDownload, ids: [id] });
const file = await this.findOrFail(id);
return new ImmichFileResponse({
path: file.path,
fileName: getFileNameWithoutExtension(file.path) + getFilenameExtension(file.path),
contentType: mimeTypes.lookup(file.path),
cacheControl: CacheControl.PrivateWithCache,
});
}
async delete(auth: AuthDto, id: string) {
await this.requireAccess({ auth, permission: Permission.AssetFileDelete, ids: [id] });
await this.assetFileRepository.delete(id);
}
private async findOrFail(id: string) {
const file = await this.assetFileRepository.get(id);
if (!file) {
throw new BadRequestException('Asset file not found');
}
return file;
}
}
+12 -23
View File
@@ -8,7 +8,6 @@ import { AssetStats } from 'src/repositories/asset.repository';
import { AssetService } from 'src/services/asset.service';
import { assetStub } from 'test/fixtures/asset.stub';
import { authStub } from 'test/fixtures/auth.stub';
import { faceStub } from 'test/fixtures/face.stub';
import { userStub } from 'test/fixtures/user.stub';
import { factory } from 'test/small.factory';
import { makeStream, newTestService, ServiceMocks } from 'test/utils';
@@ -565,12 +564,11 @@ describe(AssetService.name, () => {
});
describe('handleAssetDeletion', () => {
it('should remove faces', async () => {
const assetWithFace = { ...assetStub.image, faces: [faceStub.face1, faceStub.mergeFace1] };
it('should clean up files', async () => {
const asset = assetStub.image;
mocks.assetJob.getForAssetDeletion.mockResolvedValue(asset);
mocks.assetJob.getForAssetDeletion.mockResolvedValue(assetWithFace);
await sut.handleAssetDeletion({ id: assetWithFace.id, deleteOnDisk: true });
await sut.handleAssetDeletion({ id: asset.id, deleteOnDisk: true });
expect(mocks.job.queue.mock.calls).toEqual([
[
@@ -581,38 +579,29 @@ describe(AssetService.name, () => {
'/uploads/user-id/webp/path.ext',
'/uploads/user-id/thumbs/path.jpg',
'/uploads/user-id/fullsize/path.webp',
assetWithFace.originalPath,
asset.originalPath,
],
},
},
],
]);
expect(mocks.asset.remove).toHaveBeenCalledWith(assetWithFace);
});
it('should update stack primary asset if deleted asset was primary asset in a stack', async () => {
mocks.stack.update.mockResolvedValue(factory.stack() as any);
mocks.assetJob.getForAssetDeletion.mockResolvedValue(assetStub.primaryImage);
await sut.handleAssetDeletion({ id: assetStub.primaryImage.id, deleteOnDisk: true });
expect(mocks.stack.update).toHaveBeenCalledWith('stack-1', {
id: 'stack-1',
primaryAssetId: 'stack-child-asset-1',
});
expect(mocks.asset.remove).toHaveBeenCalledWith(asset);
});
it('should delete the entire stack if deleted asset was the primary asset and the stack would only contain one asset afterwards', async () => {
mocks.stack.delete.mockResolvedValue();
mocks.assetJob.getForAssetDeletion.mockResolvedValue({
...assetStub.primaryImage,
stack: { ...assetStub.primaryImage.stack, assets: assetStub.primaryImage.stack!.assets.slice(0, 2) },
stack: {
id: 'stack-id',
primaryAssetId: assetStub.primaryImage.id,
assets: [{ id: 'one-asset' }],
},
});
await sut.handleAssetDeletion({ id: assetStub.primaryImage.id, deleteOnDisk: true });
expect(mocks.stack.delete).toHaveBeenCalledWith('stack-1');
expect(mocks.stack.delete).toHaveBeenCalledWith('stack-id');
});
it('should delete a live photo', async () => {
+4 -3
View File
@@ -327,10 +327,11 @@ export class AssetService extends BaseService {
return JobStatus.Failed;
}
// Replace the parent of the stack children with a new asset
// replace the parent of the stack children with a new asset
if (asset.stack?.primaryAssetId === id) {
const stackAssetIds = asset.stack?.assets.map((a) => a.id) ?? [];
if (stackAssetIds.length > 2) {
// this only includes timeline visible assets and excludes the primary asset
const stackAssetIds = asset.stack.assets.map((a) => a.id);
if (stackAssetIds.length >= 2) {
const newPrimaryAssetId = stackAssetIds.find((a) => a !== id)!;
await this.stackRepository.update(asset.stack.id, {
id: asset.stack.id,
+2
View File
@@ -12,6 +12,7 @@ import { AlbumRepository } from 'src/repositories/album.repository';
import { ApiKeyRepository } from 'src/repositories/api-key.repository';
import { AppRepository } from 'src/repositories/app.repository';
import { AssetEditRepository } from 'src/repositories/asset-edit.repository';
import { AssetFileRepository } from 'src/repositories/asset-file.repository';
import { AssetJobRepository } from 'src/repositories/asset-job.repository';
import { AssetRepository } from 'src/repositories/asset.repository';
import { AuditRepository } from 'src/repositories/audit.repository';
@@ -130,6 +131,7 @@ export class BaseService {
protected appRepository: AppRepository,
protected assetRepository: AssetRepository,
protected assetEditRepository: AssetEditRepository,
protected assetFileRepository: AssetFileRepository,
protected assetJobRepository: AssetJobRepository,
protected auditRepository: AuditRepository,
protected configRepository: ConfigRepository,
+2
View File
@@ -2,6 +2,7 @@ import { ActivityService } from 'src/services/activity.service';
import { AlbumService } from 'src/services/album.service';
import { ApiKeyService } from 'src/services/api-key.service';
import { ApiService } from 'src/services/api.service';
import { AssetFileService } from 'src/services/asset-file.service';
import { AssetMediaService } from 'src/services/asset-media.service';
import { AssetService } from 'src/services/asset.service';
import { AuditService } from 'src/services/audit.service';
@@ -55,6 +56,7 @@ export const services = [
ApiService,
AssetMediaService,
AssetService,
AssetFileService,
AuditService,
AuthService,
AuthAdminService,
+9
View File
@@ -131,6 +131,10 @@ const checkOtherAccess = async (access: AccessRepository, request: OtherAccessRe
return setUnion(isOwner, isPartner);
}
case Permission.AssetFileDownload: {
return access.assetFile.checkOwnerAccess(auth.user.id, ids, auth.session?.hasElevatedPermission);
}
case Permission.AssetView: {
const isOwner = await access.asset.checkOwnerAccess(auth.user.id, ids, auth.session?.hasElevatedPermission);
const isAlbum = await access.asset.checkAlbumAccess(auth.user.id, setDifference(ids, isOwner));
@@ -169,6 +173,11 @@ const checkOtherAccess = async (access: AccessRepository, request: OtherAccessRe
return await access.asset.checkOwnerAccess(auth.user.id, ids, auth.session?.hasElevatedPermission);
}
case Permission.AssetFileRead:
case Permission.AssetFileDelete: {
return await access.assetFile.checkOwnerAccess(auth.user.id, ids, auth.session?.hasElevatedPermission);
}
case Permission.AlbumRead: {
const isOwner = await access.album.checkOwnerAccess(auth.user.id, ids);
const isShared = await access.album.checkSharedAlbumAccess(
+21 -22
View File
@@ -232,19 +232,20 @@ export const ValidateHexColor = () => {
return applyDecorators(...decorators);
};
type DateOptions = { optional?: boolean; nullable?: boolean; format?: 'date' | 'date-time' };
type DateOptions = OptionalOptions & { optional?: boolean; format?: 'date' | 'date-time' };
export const ValidateDate = (options?: DateOptions & ApiPropertyOptions) => {
const { optional, nullable, format, ...apiPropertyOptions } = {
optional: false,
nullable: false,
format: 'date-time',
...options,
};
const {
optional,
nullable = false,
emptyToNull = false,
format = 'date-time',
...apiPropertyOptions
} = options || {};
const decorators = [
return applyDecorators(
ApiProperty({ format, ...apiPropertyOptions }),
IsDate(),
optional ? Optional({ nullable: true }) : IsNotEmpty(),
optional ? Optional({ nullable, emptyToNull }) : IsNotEmpty(),
Transform(({ key, value }) => {
if (value === null || value === undefined) {
return value;
@@ -256,19 +257,17 @@ export const ValidateDate = (options?: DateOptions & ApiPropertyOptions) => {
return new Date(value as string);
}),
];
if (optional) {
decorators.push(Optional({ nullable }));
}
return applyDecorators(...decorators);
);
};
type StringOptions = { optional?: boolean; nullable?: boolean; trim?: boolean };
type StringOptions = OptionalOptions & { optional?: boolean; trim?: boolean };
export const ValidateString = (options?: StringOptions & ApiPropertyOptions) => {
const { optional, nullable, trim, ...apiPropertyOptions } = options || {};
const decorators = [ApiProperty(apiPropertyOptions), IsString(), optional ? Optional({ nullable }) : IsNotEmpty()];
const { optional, nullable, emptyToNull, trim, ...apiPropertyOptions } = options || {};
const decorators = [
ApiProperty(apiPropertyOptions),
IsString(),
optional ? Optional({ nullable, emptyToNull }) : IsNotEmpty(),
];
if (trim) {
decorators.push(Transform(({ value }: { value: string }) => value?.trim()));
@@ -277,9 +276,9 @@ export const ValidateString = (options?: StringOptions & ApiPropertyOptions) =>
return applyDecorators(...decorators);
};
type BooleanOptions = { optional?: boolean; nullable?: boolean };
type BooleanOptions = OptionalOptions & { optional?: boolean };
export const ValidateBoolean = (options?: BooleanOptions & PropertyOptions) => {
const { optional, nullable, ...apiPropertyOptions } = options || {};
const { optional, nullable, emptyToNull, ...apiPropertyOptions } = options || {};
const decorators = [
Property(apiPropertyOptions),
IsBoolean(),
@@ -291,7 +290,7 @@ export const ValidateBoolean = (options?: BooleanOptions & PropertyOptions) => {
}
return value;
}),
optional ? Optional({ nullable }) : IsNotEmpty(),
optional ? Optional({ nullable, emptyToNull }) : IsNotEmpty(),
];
return applyDecorators(...decorators);
+2
View File
@@ -20,6 +20,7 @@ import { ActivityRepository } from 'src/repositories/activity.repository';
import { AlbumUserRepository } from 'src/repositories/album-user.repository';
import { AlbumRepository } from 'src/repositories/album.repository';
import { AssetEditRepository } from 'src/repositories/asset-edit.repository';
import { AssetFileRepository } from 'src/repositories/asset-file.repository';
import { AssetJobRepository } from 'src/repositories/asset-job.repository';
import { AssetRepository } from 'src/repositories/asset.repository';
import { ConfigRepository } from 'src/repositories/config.repository';
@@ -386,6 +387,7 @@ const newRealRepository = <T>(key: ClassConstructor<T>, db: Kysely<DB>): T => {
case ActivityRepository:
case AssetRepository:
case AssetEditRepository:
case AssetFileRepository:
case AssetJobRepository:
case MemoryRepository:
case NotificationRepository:
@@ -1,5 +1,5 @@
import { Kysely } from 'kysely';
import { AssetFileType, AssetMetadataKey, JobName, SharedLinkType } from 'src/enum';
import { AssetFileType, AssetMetadataKey, AssetStatus, JobName, SharedLinkType } from 'src/enum';
import { AccessRepository } from 'src/repositories/access.repository';
import { AlbumRepository } from 'src/repositories/album.repository';
import { AssetJobRepository } from 'src/repositories/asset-job.repository';
@@ -246,6 +246,66 @@ describe(AssetService.name, () => {
});
});
it('should delete a stacked primary asset (2 assets)', async () => {
const { sut, ctx } = setup();
ctx.getMock(EventRepository).emit.mockResolvedValue();
ctx.getMock(JobRepository).queue.mockResolvedValue();
const { user } = await ctx.newUser();
const { asset: asset1 } = await ctx.newAsset({ ownerId: user.id });
const { asset: asset2 } = await ctx.newAsset({ ownerId: user.id });
const { stack, result } = await ctx.newStack({ ownerId: user.id }, [asset1.id, asset2.id]);
const stackRepo = ctx.get(StackRepository);
expect(result).toMatchObject({ primaryAssetId: asset1.id });
await sut.handleAssetDeletion({ id: asset1.id, deleteOnDisk: true });
// stack is deleted as well
await expect(stackRepo.getById(stack.id)).resolves.toBe(undefined);
});
it('should delete a stacked primary asset (3 assets)', async () => {
const { sut, ctx } = setup();
ctx.getMock(EventRepository).emit.mockResolvedValue();
ctx.getMock(JobRepository).queue.mockResolvedValue();
const { user } = await ctx.newUser();
const { asset: asset1 } = await ctx.newAsset({ ownerId: user.id });
const { asset: asset2 } = await ctx.newAsset({ ownerId: user.id });
const { asset: asset3 } = await ctx.newAsset({ ownerId: user.id });
const { stack, result } = await ctx.newStack({ ownerId: user.id }, [asset1.id, asset2.id, asset3.id]);
expect(result).toMatchObject({ primaryAssetId: asset1.id });
await sut.handleAssetDeletion({ id: asset1.id, deleteOnDisk: true });
// new primary asset is picked
await expect(ctx.get(StackRepository).getById(stack.id)).resolves.toMatchObject({ primaryAssetId: asset2.id });
});
it('should delete a stacked primary asset (3 trashed assets)', async () => {
const { sut, ctx } = setup();
ctx.getMock(EventRepository).emit.mockResolvedValue();
ctx.getMock(JobRepository).queue.mockResolvedValue();
const { user } = await ctx.newUser();
const { asset: asset1 } = await ctx.newAsset({ ownerId: user.id });
const { asset: asset2 } = await ctx.newAsset({ ownerId: user.id });
const { asset: asset3 } = await ctx.newAsset({ ownerId: user.id });
const { stack, result } = await ctx.newStack({ ownerId: user.id }, [asset1.id, asset2.id, asset3.id]);
await ctx.get(AssetRepository).updateAll([asset1.id, asset2.id, asset3.id], {
deletedAt: new Date(),
status: AssetStatus.Deleted,
});
expect(result).toMatchObject({ primaryAssetId: asset1.id });
await sut.handleAssetDeletion({ id: asset1.id, deleteOnDisk: true });
// stack is deleted as well
await expect(ctx.get(StackRepository).getById(stack.id)).resolves.toBe(undefined);
});
it('should not delete offline assets', async () => {
const { sut, ctx } = setup();
ctx.getMock(EventRepository).emit.mockResolvedValue();
+4
View File
@@ -21,6 +21,7 @@ import { AlbumRepository } from 'src/repositories/album.repository';
import { ApiKeyRepository } from 'src/repositories/api-key.repository';
import { AppRepository } from 'src/repositories/app.repository';
import { AssetEditRepository } from 'src/repositories/asset-edit.repository';
import { AssetFileRepository } from 'src/repositories/asset-file.repository';
import { AssetJobRepository } from 'src/repositories/asset-job.repository';
import { AssetRepository } from 'src/repositories/asset.repository';
import { AuditRepository } from 'src/repositories/audit.repository';
@@ -218,6 +219,7 @@ export type ServiceOverrides = {
audit: AuditRepository;
asset: AssetRepository;
assetEdit: AssetEditRepository;
assetFile: AssetFileRepository;
assetJob: AssetJobRepository;
config: ConfigRepository;
cron: CronRepository;
@@ -292,6 +294,7 @@ export const getMocks = () => {
albumUser: automock(AlbumUserRepository),
asset: newAssetRepositoryMock(),
assetEdit: automock(AssetEditRepository),
assetFile: automock(AssetFileRepository),
assetJob: automock(AssetJobRepository),
app: automock(AppRepository, { strict: false }),
config: newConfigRepositoryMock(),
@@ -360,6 +363,7 @@ export const newTestService = <T extends BaseService>(
overrides.app || (mocks.app as As<AppRepository>),
overrides.asset || (mocks.asset as As<AssetRepository>),
overrides.assetEdit || (mocks.assetEdit as As<AssetEditRepository>),
overrides.assetFile || (mocks.assetFile as As<AssetFileRepository>),
overrides.assetJob || (mocks.assetJob as As<AssetJobRepository>),
overrides.audit || (mocks.audit as As<AuditRepository>),
overrides.config || (mocks.config as As<ConfigRepository> as ConfigRepository),
@@ -0,0 +1,34 @@
import { render } from '@testing-library/svelte';
import userEvent from '@testing-library/user-event';
import SharedLinkFormFields from './SharedLinkFormFields.svelte';
describe('SharedLinkFormFields component', () => {
const isChecked = (element: Element) =>
element instanceof HTMLInputElement ? element.checked : element.getAttribute('aria-checked') === 'true';
it('turns downloads off when metadata is disabled', async () => {
const { container } = render(SharedLinkFormFields, {
props: {
slug: '',
password: '',
description: '',
allowDownload: true,
allowUpload: false,
showMetadata: true,
expiresAt: null,
},
});
const user = userEvent.setup();
const switches = Array.from(container.querySelectorAll('[role="switch"], input[type="checkbox"]'));
expect(switches).toHaveLength(3);
const [showMetadataSwitch, allowDownloadSwitch] = switches;
expect(isChecked(allowDownloadSwitch)).toBe(true);
await user.click(showMetadataSwitch);
expect(isChecked(showMetadataSwitch)).toBe(false);
expect(isChecked(allowDownloadSwitch)).toBe(false);
});
});
@@ -0,0 +1,65 @@
<script lang="ts">
import SharedLinkExpiration from '$lib/components/SharedLinkExpiration.svelte';
import { Field, Input, PasswordInput, Switch, Text } from '@immich/ui';
import { t } from 'svelte-i18n';
type Props = {
slug: string;
password: string;
description: string;
allowDownload: boolean;
allowUpload: boolean;
showMetadata: boolean;
expiresAt: string | null;
createdAt?: string;
};
let {
slug = $bindable(),
password = $bindable(),
description = $bindable(),
allowDownload = $bindable(),
allowUpload = $bindable(),
showMetadata = $bindable(),
expiresAt = $bindable(),
createdAt,
}: Props = $props();
$effect(() => {
if (!showMetadata && allowDownload) {
allowDownload = false;
}
});
</script>
<div class="flex flex-col gap-4 mt-4">
<div>
<Field label={$t('custom_url')} description={$t('shared_link_custom_url_description')}>
<Input bind:value={slug} autocomplete="off" />
</Field>
{#if slug}
<Text size="tiny" color="muted" class="pt-2 break-all">/s/{encodeURIComponent(slug)}</Text>
{/if}
</div>
<Field label={$t('password')} description={$t('shared_link_password_description')}>
<PasswordInput bind:value={password} autocomplete="new-password" />
</Field>
<Field label={$t('description')}>
<Input bind:value={description} autocomplete="off" />
</Field>
<SharedLinkExpiration {createdAt} bind:expiresAt />
<Field label={$t('show_metadata')}>
<Switch bind:checked={showMetadata} />
</Field>
<Field label={$t('allow_public_user_to_download')} disabled={!showMetadata}>
<Switch bind:checked={allowDownload} />
</Field>
<Field label={$t('allow_public_user_to_upload')}>
<Switch bind:checked={allowUpload} />
</Field>
</div>
@@ -59,12 +59,7 @@
size="small"
>
<Label for="datetime" class="block mb-1">{$t('date_and_time')}</Label>
<DateInput
class="immich-form-input text-gray-700 w-full mb-2"
id="datetime"
type="datetime-local"
bind:value={selectedDate}
/>
<DateInput class="immich-form-input w-full mb-2" id="datetime" type="datetime-local" bind:value={selectedDate} />
{#if timezoneInput}
<div class="w-full">
<Combobox bind:selectedOption label={$t('timezone')} options={timezones} placeholder={$t('search_timezone')} />
@@ -77,11 +77,7 @@
</Field>
{#if showRelative}
<Label for="relativedatetime" class="block mb-1">{$t('offset')}</Label>
<DurationInput
class="immich-form-input w-full text-gray-700 mb-2"
id="relativedatetime"
bind:value={selectedDuration}
/>
<DurationInput class="immich-form-input w-full mb-2" id="relativedatetime" bind:value={selectedDuration} />
{:else}
<Label for="datetime" class="block mb-1">{$t('date_and_time')}</Label>
<DateInput class="immich-form-input w-full mb-2" id="datetime" type="datetime-local" bind:value={selectedDate} />
+2 -1
View File
@@ -33,6 +33,7 @@
const updatedIds = await tagAssets({ tagIds: [...selectedIds], assetIds, showNotification: false });
eventManager.emit('AssetsTag', updatedIds);
onClose();
};
const handleSelect = async (option?: ComboBoxOption) => {
@@ -81,7 +82,7 @@
{#if tag}
<div class="flex group transition-all">
<span
class="inline-block h-min whitespace-nowrap ps-3 pe-1 group-hover:ps-3 py-1 text-center align-baseline leading-none text-gray-100 dark:text-immich-dark-gray bg-primary roudned-s-full hover:bg-immich-primary/80 dark:hover:bg-immich-dark-primary/80 transition-all"
class="inline-block h-min whitespace-nowrap ps-3 pe-1 group-hover:ps-3 py-1 text-center align-baseline leading-none text-gray-100 dark:text-immich-dark-gray bg-primary rounded-s-full hover:bg-immich-primary/80 dark:hover:bg-immich-dark-primary/80 transition-all"
>
<p class="text-sm">
{tag.value}
+11 -40
View File
@@ -1,8 +1,8 @@
<script lang="ts">
import SharedLinkExpiration from '$lib/components/SharedLinkExpiration.svelte';
import SharedLinkFormFields from '$lib/components/SharedLinkFormFields.svelte';
import { handleCreateSharedLink } from '$lib/services/shared-link.service';
import { SharedLinkType } from '@immich/sdk';
import { Field, FormModal, Input, PasswordInput, Switch, Text } from '@immich/ui';
import { FormModal } from '@immich/ui';
import { mdiLink } from '@mdi/js';
import { t } from 'svelte-i18n';
@@ -24,12 +24,6 @@
let type = $derived(albumId ? SharedLinkType.Album : SharedLinkType.Individual);
$effect(() => {
if (!showMetadata) {
allowDownload = false;
}
});
const onSubmit = async () => {
const success = await handleCreateSharedLink({
type,
@@ -65,36 +59,13 @@
<div>{$t('create_link_to_share_description')}</div>
{/if}
<div class="flex flex-col gap-4 mt-4">
<div>
<Field label={$t('custom_url')} description={$t('shared_link_custom_url_description')}>
<Input bind:value={slug} autocomplete="off" />
</Field>
{#if slug}
<Text size="tiny" color="muted" class="pt-2 break-all">/s/{encodeURIComponent(slug)}</Text>
{/if}
</div>
<Field label={$t('password')} description={$t('shared_link_password_description')}>
<PasswordInput bind:value={password} autocomplete="new-password" />
</Field>
<Field label={$t('description')}>
<Input bind:value={description} autocomplete="off" />
</Field>
<SharedLinkExpiration bind:expiresAt />
<Field label={$t('show_metadata')}>
<Switch bind:checked={showMetadata} />
</Field>
<Field label={$t('allow_public_user_to_download')} disabled={!showMetadata}>
<Switch bind:checked={allowDownload} />
</Field>
<Field label={$t('allow_public_user_to_upload')}>
<Switch bind:checked={allowUpload} />
</Field>
</div>
<SharedLinkFormFields
bind:slug
bind:password
bind:description
bind:allowDownload
bind:allowUpload
bind:showMetadata
bind:expiresAt
/>
</FormModal>
@@ -1,10 +1,10 @@
<script lang="ts">
import { goto } from '$app/navigation';
import SharedLinkExpiration from '$lib/components/SharedLinkExpiration.svelte';
import SharedLinkFormFields from '$lib/components/SharedLinkFormFields.svelte';
import { Route } from '$lib/route';
import { handleUpdateSharedLink } from '$lib/services/shared-link.service';
import { SharedLinkType } from '@immich/sdk';
import { Field, FormModal, Input, PasswordInput, Switch, Text } from '@immich/ui';
import { FormModal } from '@immich/ui';
import { mdiLink } from '@mdi/js';
import { t } from 'svelte-i18n';
import type { PageData } from './$types';
@@ -61,36 +61,14 @@
</div>
{/if}
<div class="flex flex-col gap-4 mt-4">
<div>
<Field label={$t('custom_url')} description={$t('shared_link_custom_url_description')}>
<Input bind:value={slug} autocomplete="off" />
</Field>
{#if slug}
<Text size="tiny" color="muted" class="pt-2">/s/{encodeURIComponent(slug)}</Text>
{/if}
</div>
<Field label={$t('password')} description={$t('shared_link_password_description')}>
<PasswordInput bind:value={password} autocomplete="new-password" />
</Field>
<Field label={$t('description')}>
<Input bind:value={description} autocomplete="off" />
</Field>
<SharedLinkExpiration createdAt={sharedLink.createdAt} bind:expiresAt />
<Field label={$t('show_metadata')}>
<Switch bind:checked={showMetadata} />
</Field>
<Field label={$t('allow_public_user_to_download')} disabled={!showMetadata}>
<Switch bind:checked={allowDownload} />
</Field>
<Field label={$t('allow_public_user_to_upload')}>
<Switch bind:checked={allowUpload} />
</Field>
</div>
<SharedLinkFormFields
bind:slug
bind:password
bind:description
bind:allowDownload
bind:allowUpload
bind:showMetadata
bind:expiresAt
createdAt={sharedLink.createdAt}
/>
</FormModal>