feat: user preferences for archive download size (#10296)

* feat: user preferences for archive download size

* chore: open api

* chore: clean up

---------

Co-authored-by: Jason Rasmussen <jrasm91@gmail.com>
This commit is contained in:
Daniel Dietzler 2024-06-14 17:27:12 +02:00 committed by GitHub
parent 596412cb8f
commit dddc06c3b2
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
19 changed files with 201 additions and 22 deletions

View file

@ -250,18 +250,23 @@ describe('/admin/users', () => {
.set('Authorization', `Bearer ${admin.accessToken}`); .set('Authorization', `Bearer ${admin.accessToken}`);
expect(status).toBe(200); expect(status).toBe(200);
expect(body).toEqual({ expect(body).toMatchObject({ avatar: { color: 'orange' } });
avatar: { color: 'orange' },
memories: { enabled: false },
emailNotifications: { enabled: true, albumInvite: true, albumUpdate: true },
});
const after = await getUserPreferencesAdmin({ id: admin.userId }, { headers: asBearerAuth(admin.accessToken) }); const after = await getUserPreferencesAdmin({ id: admin.userId }, { headers: asBearerAuth(admin.accessToken) });
expect(after).toEqual({ expect(after).toMatchObject({ avatar: { color: 'orange' } });
avatar: { color: 'orange' },
memories: { enabled: false },
emailNotifications: { enabled: true, albumInvite: true, albumUpdate: true },
}); });
it('should update download archive size', async () => {
const { status, body } = await request(app)
.put(`/admin/users/${admin.userId}/preferences`)
.send({ download: { archiveSize: 1_234_567 } })
.set('Authorization', `Bearer ${admin.accessToken}`);
expect(status).toBe(200);
expect(body).toMatchObject({ download: { archiveSize: 1_234_567 } });
const after = await getUserPreferencesAdmin({ id: admin.userId }, { headers: asBearerAuth(admin.accessToken) });
expect(after).toMatchObject({ download: { archiveSize: 1_234_567 } });
}); });
}); });

View file

@ -173,6 +173,45 @@ describe('/users', () => {
const after = await getMyPreferences({ headers: asBearerAuth(admin.accessToken) }); const after = await getMyPreferences({ headers: asBearerAuth(admin.accessToken) });
expect(after).toMatchObject({ memories: { enabled: false } }); expect(after).toMatchObject({ memories: { enabled: false } });
}); });
it('should update avatar color', async () => {
const { status, body } = await request(app)
.put(`/users/me/preferences`)
.send({ avatar: { color: 'blue' } })
.set('Authorization', `Bearer ${admin.accessToken}`);
expect(status).toBe(200);
expect(body).toMatchObject({ avatar: { color: 'blue' } });
const after = await getMyPreferences({ headers: asBearerAuth(admin.accessToken) });
expect(after).toMatchObject({ avatar: { color: 'blue' } });
});
it('should require an integer for download archive size', async () => {
const { status, body } = await request(app)
.put(`/users/me/preferences`)
.send({ download: { archiveSize: 1_234_567.89 } })
.set('Authorization', `Bearer ${admin.accessToken}`);
expect(status).toBe(400);
expect(body).toEqual(errorDto.badRequest(['download.archiveSize must be an integer number']));
});
it('should update download archive size', async () => {
const before = await getMyPreferences({ headers: asBearerAuth(admin.accessToken) });
expect(before).toMatchObject({ download: { archiveSize: 4 * 2 ** 30 } });
const { status, body } = await request(app)
.put(`/users/me/preferences`)
.send({ download: { archiveSize: 1_234_567 } })
.set('Authorization', `Bearer ${admin.accessToken}`);
expect(status).toBe(200);
expect(body).toMatchObject({ download: { archiveSize: 1_234_567 } });
const after = await getMyPreferences({ headers: asBearerAuth(admin.accessToken) });
expect(after).toMatchObject({ download: { archiveSize: 1_234_567 } });
});
}); });
describe('GET /users/:id', () => { describe('GET /users/:id', () => {

BIN
mobile/openapi/README.md generated

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View file

@ -8125,6 +8125,17 @@
}, },
"type": "object" "type": "object"
}, },
"DownloadResponse": {
"properties": {
"archiveSize": {
"type": "integer"
}
},
"required": [
"archiveSize"
],
"type": "object"
},
"DownloadResponseDto": { "DownloadResponseDto": {
"properties": { "properties": {
"archives": { "archives": {
@ -8143,6 +8154,15 @@
], ],
"type": "object" "type": "object"
}, },
"DownloadUpdate": {
"properties": {
"archiveSize": {
"minimum": 1,
"type": "integer"
}
},
"type": "object"
},
"DuplicateDetectionConfig": { "DuplicateDetectionConfig": {
"properties": { "properties": {
"enabled": { "enabled": {
@ -11255,6 +11275,9 @@
"avatar": { "avatar": {
"$ref": "#/components/schemas/AvatarResponse" "$ref": "#/components/schemas/AvatarResponse"
}, },
"download": {
"$ref": "#/components/schemas/DownloadResponse"
},
"emailNotifications": { "emailNotifications": {
"$ref": "#/components/schemas/EmailNotificationsResponse" "$ref": "#/components/schemas/EmailNotificationsResponse"
}, },
@ -11264,6 +11287,7 @@
}, },
"required": [ "required": [
"avatar", "avatar",
"download",
"emailNotifications", "emailNotifications",
"memories" "memories"
], ],
@ -11274,6 +11298,9 @@
"avatar": { "avatar": {
"$ref": "#/components/schemas/AvatarUpdate" "$ref": "#/components/schemas/AvatarUpdate"
}, },
"download": {
"$ref": "#/components/schemas/DownloadUpdate"
},
"emailNotifications": { "emailNotifications": {
"$ref": "#/components/schemas/EmailNotificationsUpdate" "$ref": "#/components/schemas/EmailNotificationsUpdate"
}, },

View file

@ -78,6 +78,9 @@ export type UserAdminUpdateDto = {
export type AvatarResponse = { export type AvatarResponse = {
color: UserAvatarColor; color: UserAvatarColor;
}; };
export type DownloadResponse = {
archiveSize: number;
};
export type EmailNotificationsResponse = { export type EmailNotificationsResponse = {
albumInvite: boolean; albumInvite: boolean;
albumUpdate: boolean; albumUpdate: boolean;
@ -88,12 +91,16 @@ export type MemoryResponse = {
}; };
export type UserPreferencesResponseDto = { export type UserPreferencesResponseDto = {
avatar: AvatarResponse; avatar: AvatarResponse;
download: DownloadResponse;
emailNotifications: EmailNotificationsResponse; emailNotifications: EmailNotificationsResponse;
memories: MemoryResponse; memories: MemoryResponse;
}; };
export type AvatarUpdate = { export type AvatarUpdate = {
color?: UserAvatarColor; color?: UserAvatarColor;
}; };
export type DownloadUpdate = {
archiveSize?: number;
};
export type EmailNotificationsUpdate = { export type EmailNotificationsUpdate = {
albumInvite?: boolean; albumInvite?: boolean;
albumUpdate?: boolean; albumUpdate?: boolean;
@ -104,6 +111,7 @@ export type MemoryUpdate = {
}; };
export type UserPreferencesUpdateDto = { export type UserPreferencesUpdateDto = {
avatar?: AvatarUpdate; avatar?: AvatarUpdate;
download?: DownloadUpdate;
emailNotifications?: EmailNotificationsUpdate; emailNotifications?: EmailNotificationsUpdate;
memories?: MemoryUpdate; memories?: MemoryUpdate;
}; };

View file

@ -1,6 +1,6 @@
import { ApiProperty } from '@nestjs/swagger'; import { ApiProperty } from '@nestjs/swagger';
import { Type } from 'class-transformer'; import { Type } from 'class-transformer';
import { IsEnum, ValidateNested } from 'class-validator'; import { IsEnum, IsInt, IsPositive, ValidateNested } from 'class-validator';
import { UserAvatarColor, UserPreferences } from 'src/entities/user-metadata.entity'; import { UserAvatarColor, UserPreferences } from 'src/entities/user-metadata.entity';
import { Optional, ValidateBoolean } from 'src/validation'; import { Optional, ValidateBoolean } from 'src/validation';
@ -27,6 +27,14 @@ class EmailNotificationsUpdate {
albumUpdate?: boolean; albumUpdate?: boolean;
} }
class DownloadUpdate {
@Optional()
@IsInt()
@IsPositive()
@ApiProperty({ type: 'integer' })
archiveSize?: number;
}
export class UserPreferencesUpdateDto { export class UserPreferencesUpdateDto {
@Optional() @Optional()
@ValidateNested() @ValidateNested()
@ -42,6 +50,11 @@ export class UserPreferencesUpdateDto {
@ValidateNested() @ValidateNested()
@Type(() => EmailNotificationsUpdate) @Type(() => EmailNotificationsUpdate)
emailNotifications?: EmailNotificationsUpdate; emailNotifications?: EmailNotificationsUpdate;
@Optional()
@ValidateNested()
@Type(() => DownloadUpdate)
download?: DownloadUpdate;
} }
class AvatarResponse { class AvatarResponse {
@ -59,10 +72,16 @@ class EmailNotificationsResponse {
albumUpdate!: boolean; albumUpdate!: boolean;
} }
class DownloadResponse {
@ApiProperty({ type: 'integer' })
archiveSize!: number;
}
export class UserPreferencesResponseDto implements UserPreferences { export class UserPreferencesResponseDto implements UserPreferences {
memories!: MemoryResponse; memories!: MemoryResponse;
avatar!: AvatarResponse; avatar!: AvatarResponse;
emailNotifications!: EmailNotificationsResponse; emailNotifications!: EmailNotificationsResponse;
download!: DownloadResponse;
} }
export const mapPreferences = (preferences: UserPreferences): UserPreferencesResponseDto => { export const mapPreferences = (preferences: UserPreferences): UserPreferencesResponseDto => {

View file

@ -1,4 +1,5 @@
import { UserEntity } from 'src/entities/user.entity'; import { UserEntity } from 'src/entities/user.entity';
import { HumanReadableSize } from 'src/utils/bytes';
import { Column, DeepPartial, Entity, ManyToOne, PrimaryColumn } from 'typeorm'; import { Column, DeepPartial, Entity, ManyToOne, PrimaryColumn } from 'typeorm';
@Entity('user_metadata') @Entity('user_metadata')
@ -41,6 +42,9 @@ export interface UserPreferences {
albumInvite: boolean; albumInvite: boolean;
albumUpdate: boolean; albumUpdate: boolean;
}; };
download: {
archiveSize: number;
};
} }
export const getDefaultPreferences = (user: { email: string }): UserPreferences => { export const getDefaultPreferences = (user: { email: string }): UserPreferences => {
@ -61,6 +65,9 @@ export const getDefaultPreferences = (user: { email: string }): UserPreferences
albumInvite: true, albumInvite: true,
albumUpdate: true, albumUpdate: true,
}, },
download: {
archiveSize: HumanReadableSize.GiB * 4,
},
}; };
}; };

View file

@ -0,0 +1,51 @@
<script lang="ts">
import {
notificationController,
NotificationType,
} from '$lib/components/shared-components/notification/notification';
import { updateMyPreferences } from '@immich/sdk';
import { fade } from 'svelte/transition';
import { handleError } from '../../utils/handle-error';
import { preferences } from '$lib/stores/user.store';
import Button from '../elements/buttons/button.svelte';
import { t } from 'svelte-i18n';
import SettingInputField, {
SettingInputFieldType,
} from '$lib/components/shared-components/settings/setting-input-field.svelte';
import { convertFromBytes, convertToBytes } from '$lib/utils/byte-converter';
let archiveSize = convertFromBytes($preferences?.download?.archiveSize || 4, 'GiB');
const handleSave = async () => {
try {
const dto = { download: { archiveSize: Math.floor(convertToBytes(archiveSize, 'GiB')) } };
const newPreferences = await updateMyPreferences({ userPreferencesUpdateDto: dto });
$preferences = newPreferences;
notificationController.show({ message: $t('saved_settings'), type: NotificationType.Info });
} catch (error) {
handleError(error, $t('errors.unable_to_update_settings'));
}
};
</script>
<section class="my-4">
<div in:fade={{ duration: 500 }}>
<form autocomplete="off" on:submit|preventDefault>
<div class="ml-4 mt-4 flex flex-col gap-4">
<div class="ml-4">
<SettingInputField
inputType={SettingInputFieldType.NUMBER}
label={$t('archive_size')}
desc={$t('archive_size_description')}
bind:value={archiveSize}
/>
</div>
<div class="flex justify-end">
<Button type="submit" size="sm" on:click={() => handleSave()}>{$t('save')}</Button>
</div>
</div>
</form>
</div>
</section>

View file

@ -17,6 +17,7 @@
import UserProfileSettings from './user-profile-settings.svelte'; import UserProfileSettings from './user-profile-settings.svelte';
import NotificationsSettings from '$lib/components/user-settings-page/notifications-settings.svelte'; import NotificationsSettings from '$lib/components/user-settings-page/notifications-settings.svelte';
import { t } from 'svelte-i18n'; import { t } from 'svelte-i18n';
import DownloadSettings from '$lib/components/user-settings-page/download-settings.svelte';
export let keys: ApiKeyResponseDto[] = []; export let keys: ApiKeyResponseDto[] = [];
export let sessions: SessionResponseDto[] = []; export let sessions: SessionResponseDto[] = [];
@ -43,6 +44,14 @@
<DeviceList bind:devices={sessions} /> <DeviceList bind:devices={sessions} />
</SettingAccordion> </SettingAccordion>
<SettingAccordion
key="download-settings"
title={$t('download_settings')}
subtitle={$t('download_settings_description')}
>
<DownloadSettings />
</SettingAccordion>
<SettingAccordion key="memories" title={$t('memories')} subtitle={$t('memories_setting_description')}> <SettingAccordion key="memories" title={$t('memories')} subtitle={$t('memories_setting_description')}>
<MemoriesSettings /> <MemoriesSettings />
</SettingAccordion> </SettingAccordion>

View file

@ -312,6 +312,8 @@
"appears_in": "Appears in", "appears_in": "Appears in",
"archive": "Archive", "archive": "Archive",
"archive_or_unarchive_photo": "Archive or unarchive photo", "archive_or_unarchive_photo": "Archive or unarchive photo",
"archive_size": "Archive Size",
"archive_size_description": "Configure the archive size for downloads (in GiB)",
"archived": "Archived", "archived": "Archived",
"asset_offline": "Asset offline", "asset_offline": "Asset offline",
"assets": "Assets", "assets": "Assets",
@ -413,6 +415,8 @@
"display_original_photos_setting_description": "Prefer to display the original photo when viewing an asset rather than thumbnails when the original asset is web-compatible. This may result in slower photo display speeds.", "display_original_photos_setting_description": "Prefer to display the original photo when viewing an asset rather than thumbnails when the original asset is web-compatible. This may result in slower photo display speeds.",
"done": "Done", "done": "Done",
"download": "Download", "download": "Download",
"download_settings": "Download",
"download_settings_description": "Manage settings related to asset download",
"downloading": "Downloading", "downloading": "Downloading",
"duplicates": "Duplicates", "duplicates": "Duplicates",
"duration": "Duration", "duration": "Duration",

View file

@ -301,3 +301,12 @@ export const handlePromiseError = <T>(promise: Promise<T>): void => {
export const s = (count: number) => (count === 1 ? '' : 's'); export const s = (count: number) => (count === 1 ? '' : 's');
export const memoryLaneTitle = (yearsAgo: number) => `${yearsAgo} year${s(yearsAgo)} ago`; export const memoryLaneTitle = (yearsAgo: number) => `${yearsAgo} year${s(yearsAgo)} ago`;
export const withError = async <T>(fn: () => Promise<T>): Promise<[undefined, T] | [unknown, undefined]> => {
try {
const result = await fn();
return [undefined, result];
} catch (error) {
return [error, undefined];
}
};

View file

@ -5,7 +5,8 @@ import type { AssetInteractionStore } from '$lib/stores/asset-interaction.store'
import { assetViewingStore } from '$lib/stores/asset-viewing.store'; import { assetViewingStore } from '$lib/stores/asset-viewing.store';
import { BucketPosition, isSelectingAllAssets, type AssetStore } from '$lib/stores/assets.store'; import { BucketPosition, isSelectingAllAssets, type AssetStore } from '$lib/stores/assets.store';
import { downloadManager } from '$lib/stores/download'; import { downloadManager } from '$lib/stores/download';
import { downloadRequest, getKey, s } from '$lib/utils'; import { preferences } from '$lib/stores/user.store';
import { downloadRequest, getKey, s, withError } from '$lib/utils';
import { createAlbum } from '$lib/utils/album-utils'; import { createAlbum } from '$lib/utils/album-utils';
import { asByteUnitString } from '$lib/utils/byte-units'; import { asByteUnitString } from '$lib/utils/byte-units';
import { encodeHTMLSpecialChars } from '$lib/utils/string-utils'; import { encodeHTMLSpecialChars } from '$lib/utils/string-utils';
@ -20,7 +21,6 @@ import {
type AssetResponseDto, type AssetResponseDto,
type AssetTypeEnum, type AssetTypeEnum,
type DownloadInfoDto, type DownloadInfoDto,
type DownloadResponseDto,
type UserResponseDto, type UserResponseDto,
} from '@immich/sdk'; } from '@immich/sdk';
import { DateTime } from 'luxon'; import { DateTime } from 'luxon';
@ -94,18 +94,19 @@ export const downloadBlob = (data: Blob, filename: string) => {
URL.revokeObjectURL(url); URL.revokeObjectURL(url);
}; };
export const downloadArchive = async (fileName: string, options: DownloadInfoDto) => { export const downloadArchive = async (fileName: string, options: Omit<DownloadInfoDto, 'archiveSize'>) => {
let downloadInfo: DownloadResponseDto | null = null; const $preferences = get(preferences);
const dto = { ...options, archiveSize: $preferences.download.archiveSize };
try { const [error, downloadInfo] = await withError(() => getDownloadInfo({ downloadInfoDto: dto, key: getKey() }));
downloadInfo = await getDownloadInfo({ downloadInfoDto: options, key: getKey() }); if (error) {
} catch (error) {
handleError(error, 'Unable to download files'); handleError(error, 'Unable to download files');
return; return;
} }
// TODO: prompt for big download if (!downloadInfo) {
// const total = downloadInfo.totalSize; return;
}
for (let index = 0; index < downloadInfo.archives.length; index++) { for (let index = 0; index < downloadInfo.archives.length; index++) {
const archive = downloadInfo.archives[index]; const archive = downloadInfo.archives[index];

View file

@ -7,7 +7,7 @@
* @param unit unit to convert from * @param unit unit to convert from
* @returns bytes (number) * @returns bytes (number)
*/ */
export function convertToBytes(size: number, unit: string): number { export function convertToBytes(size: number, unit: 'GiB'): number {
let bytes = 0; let bytes = 0;
if (unit === 'GiB') { if (unit === 'GiB') {
@ -26,7 +26,7 @@ export function convertToBytes(size: number, unit: string): number {
* @param unit unit to convert to * @param unit unit to convert to
* @returns bytes (number) * @returns bytes (number)
*/ */
export function convertFromBytes(bytes: number, unit: string): number { export function convertFromBytes(bytes: number, unit: 'GiB'): number {
let size = 0; let size = 0;
if (unit === 'GiB') { if (unit === 'GiB') {