0
Fork 0
mirror of https://github.com/immich-app/immich.git synced 2025-03-25 02:41:37 -05:00

feat: view album shared links (#15943)

This commit is contained in:
Jason Rasmussen 2025-02-07 16:38:20 -05:00 committed by GitHub
parent c5360e78c5
commit 61b8eb85b5
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
13 changed files with 144 additions and 51 deletions

View file

@ -150,6 +150,30 @@ describe('/shared-links', () => {
); );
}); });
it('should filter on albumId', async () => {
const { status, body } = await request(app)
.get(`/shared-links?albumId=${album.id}`)
.set('Authorization', `Bearer ${user1.accessToken}`);
expect(status).toBe(200);
expect(body).toHaveLength(2);
expect(body).toEqual(
expect.arrayContaining([
expect.objectContaining({ id: linkWithAlbum.id }),
expect.objectContaining({ id: linkWithPassword.id }),
]),
);
});
it('should find 0 albums', async () => {
const { status, body } = await request(app)
.get(`/shared-links?albumId=${uuidDto.notFound}`)
.set('Authorization', `Bearer ${user1.accessToken}`);
expect(status).toBe(200);
expect(body).toHaveLength(0);
});
it('should not get shared links created by other users', async () => { it('should not get shared links created by other users', async () => {
const { status, body } = await request(app) const { status, body } = await request(app)
.get('/shared-links') .get('/shared-links')

View file

@ -127,7 +127,10 @@ class SharedLinksApi {
} }
/// Performs an HTTP 'GET /shared-links' operation and returns the [Response]. /// Performs an HTTP 'GET /shared-links' operation and returns the [Response].
Future<Response> getAllSharedLinksWithHttpInfo() async { /// Parameters:
///
/// * [String] albumId:
Future<Response> getAllSharedLinksWithHttpInfo({ String? albumId, }) async {
// ignore: prefer_const_declarations // ignore: prefer_const_declarations
final path = r'/shared-links'; final path = r'/shared-links';
@ -138,6 +141,10 @@ class SharedLinksApi {
final headerParams = <String, String>{}; final headerParams = <String, String>{};
final formParams = <String, String>{}; final formParams = <String, String>{};
if (albumId != null) {
queryParams.addAll(_queryParams('', 'albumId', albumId));
}
const contentTypes = <String>[]; const contentTypes = <String>[];
@ -152,8 +159,11 @@ class SharedLinksApi {
); );
} }
Future<List<SharedLinkResponseDto>?> getAllSharedLinks() async { /// Parameters:
final response = await getAllSharedLinksWithHttpInfo(); ///
/// * [String] albumId:
Future<List<SharedLinkResponseDto>?> getAllSharedLinks({ String? albumId, }) async {
final response = await getAllSharedLinksWithHttpInfo( albumId: albumId, );
if (response.statusCode >= HttpStatus.badRequest) { if (response.statusCode >= HttpStatus.badRequest) {
throw ApiException(response.statusCode, await _decodeBodyBytes(response)); throw ApiException(response.statusCode, await _decodeBodyBytes(response));
} }

View file

@ -5230,7 +5230,17 @@
"/shared-links": { "/shared-links": {
"get": { "get": {
"operationId": "getAllSharedLinks", "operationId": "getAllSharedLinks",
"parameters": [], "parameters": [
{
"name": "albumId",
"required": false,
"in": "query",
"schema": {
"format": "uuid",
"type": "string"
}
}
],
"responses": { "responses": {
"200": { "200": {
"content": { "content": {

View file

@ -2762,11 +2762,15 @@ export function deleteSession({ id }: {
method: "DELETE" method: "DELETE"
})); }));
} }
export function getAllSharedLinks(opts?: Oazapfts.RequestOpts) { export function getAllSharedLinks({ albumId }: {
albumId?: string;
}, opts?: Oazapfts.RequestOpts) {
return oazapfts.ok(oazapfts.fetchJson<{ return oazapfts.ok(oazapfts.fetchJson<{
status: 200; status: 200;
data: SharedLinkResponseDto[]; data: SharedLinkResponseDto[];
}>("/shared-links", { }>(`/shared-links${QS.query(QS.explode({
albumId
}))}`, {
...opts ...opts
})); }));
} }

View file

@ -9,6 +9,7 @@ import {
SharedLinkEditDto, SharedLinkEditDto,
SharedLinkPasswordDto, SharedLinkPasswordDto,
SharedLinkResponseDto, SharedLinkResponseDto,
SharedLinkSearchDto,
} from 'src/dtos/shared-link.dto'; } from 'src/dtos/shared-link.dto';
import { ImmichCookie, Permission } from 'src/enum'; import { ImmichCookie, Permission } from 'src/enum';
import { Auth, Authenticated, GetLoginDetails } from 'src/middleware/auth.guard'; import { Auth, Authenticated, GetLoginDetails } from 'src/middleware/auth.guard';
@ -24,8 +25,8 @@ export class SharedLinkController {
@Get() @Get()
@Authenticated({ permission: Permission.SHARED_LINK_READ }) @Authenticated({ permission: Permission.SHARED_LINK_READ })
getAllSharedLinks(@Auth() auth: AuthDto): Promise<SharedLinkResponseDto[]> { getAllSharedLinks(@Auth() auth: AuthDto, @Query() dto: SharedLinkSearchDto): Promise<SharedLinkResponseDto[]> {
return this.service.getAll(auth); return this.service.getAll(auth, dto);
} }
@Get('me') @Get('me')

View file

@ -7,6 +7,11 @@ import { SharedLinkEntity } from 'src/entities/shared-link.entity';
import { SharedLinkType } from 'src/enum'; import { SharedLinkType } from 'src/enum';
import { Optional, ValidateBoolean, ValidateDate, ValidateUUID } from 'src/validation'; import { Optional, ValidateBoolean, ValidateDate, ValidateUUID } from 'src/validation';
export class SharedLinkSearchDto {
@ValidateUUID({ optional: true })
albumId?: string;
}
export class SharedLinkCreateDto { export class SharedLinkCreateDto {
@IsEnum(SharedLinkType) @IsEnum(SharedLinkType)
@ApiProperty({ enum: SharedLinkType, enumName: 'SharedLinkType' }) @ApiProperty({ enum: SharedLinkType, enumName: 'SharedLinkType' })

View file

@ -4,8 +4,13 @@ import { SharedLinkEntity } from 'src/entities/shared-link.entity';
export const ISharedLinkRepository = 'ISharedLinkRepository'; export const ISharedLinkRepository = 'ISharedLinkRepository';
export type SharedLinkSearchOptions = {
userId: string;
albumId?: string;
};
export interface ISharedLinkRepository { export interface ISharedLinkRepository {
getAll(userId: string): Promise<SharedLinkEntity[]>; getAll(options: SharedLinkSearchOptions): Promise<SharedLinkEntity[]>;
get(userId: string, id: string): Promise<SharedLinkEntity | undefined>; get(userId: string, id: string): Promise<SharedLinkEntity | undefined>;
getByKey(key: Buffer): Promise<SharedLinkEntity | undefined>; getByKey(key: Buffer): Promise<SharedLinkEntity | undefined>;
create(entity: Insertable<SharedLinks> & { assetIds?: string[] }): Promise<SharedLinkEntity>; create(entity: Insertable<SharedLinks> & { assetIds?: string[] }): Promise<SharedLinkEntity>;

View file

@ -7,7 +7,7 @@ import { DB, SharedLinks } from 'src/db';
import { DummyValue, GenerateSql } from 'src/decorators'; import { DummyValue, GenerateSql } from 'src/decorators';
import { SharedLinkEntity } from 'src/entities/shared-link.entity'; import { SharedLinkEntity } from 'src/entities/shared-link.entity';
import { SharedLinkType } from 'src/enum'; import { SharedLinkType } from 'src/enum';
import { ISharedLinkRepository } from 'src/interfaces/shared-link.interface'; import { ISharedLinkRepository, SharedLinkSearchOptions } from 'src/interfaces/shared-link.interface';
@Injectable() @Injectable()
export class SharedLinkRepository implements ISharedLinkRepository { export class SharedLinkRepository implements ISharedLinkRepository {
@ -93,7 +93,7 @@ export class SharedLinkRepository implements ISharedLinkRepository {
} }
@GenerateSql({ params: [DummyValue.UUID] }) @GenerateSql({ params: [DummyValue.UUID] })
getAll(userId: string): Promise<SharedLinkEntity[]> { getAll({ userId, albumId }: SharedLinkSearchOptions): Promise<SharedLinkEntity[]> {
return this.db return this.db
.selectFrom('shared_links') .selectFrom('shared_links')
.selectAll('shared_links') .selectAll('shared_links')
@ -149,6 +149,7 @@ export class SharedLinkRepository implements ISharedLinkRepository {
) )
.select((eb) => eb.fn.toJson('album').as('album')) .select((eb) => eb.fn.toJson('album').as('album'))
.where((eb) => eb.or([eb('shared_links.type', '=', SharedLinkType.INDIVIDUAL), eb('album.id', 'is not', null)])) .where((eb) => eb.or([eb('shared_links.type', '=', SharedLinkType.INDIVIDUAL), eb('album.id', 'is not', null)]))
.$if(!!albumId, (eb) => eb.where('shared_links.albumId', '=', albumId!))
.orderBy('shared_links.createdAt', 'desc') .orderBy('shared_links.createdAt', 'desc')
.distinctOn(['shared_links.createdAt']) .distinctOn(['shared_links.createdAt'])
.execute() as unknown as Promise<SharedLinkEntity[]>; .execute() as unknown as Promise<SharedLinkEntity[]>;

View file

@ -29,11 +29,11 @@ describe(SharedLinkService.name, () => {
describe('getAll', () => { describe('getAll', () => {
it('should return all shared links for a user', async () => { it('should return all shared links for a user', async () => {
sharedLinkMock.getAll.mockResolvedValue([sharedLinkStub.expired, sharedLinkStub.valid]); sharedLinkMock.getAll.mockResolvedValue([sharedLinkStub.expired, sharedLinkStub.valid]);
await expect(sut.getAll(authStub.user1)).resolves.toEqual([ await expect(sut.getAll(authStub.user1, {})).resolves.toEqual([
sharedLinkResponseStub.expired, sharedLinkResponseStub.expired,
sharedLinkResponseStub.valid, sharedLinkResponseStub.valid,
]); ]);
expect(sharedLinkMock.getAll).toHaveBeenCalledWith(authStub.user1.user.id); expect(sharedLinkMock.getAll).toHaveBeenCalledWith({ userId: authStub.user1.user.id });
}); });
}); });

View file

@ -9,6 +9,7 @@ import {
SharedLinkEditDto, SharedLinkEditDto,
SharedLinkPasswordDto, SharedLinkPasswordDto,
SharedLinkResponseDto, SharedLinkResponseDto,
SharedLinkSearchDto,
} from 'src/dtos/shared-link.dto'; } from 'src/dtos/shared-link.dto';
import { SharedLinkEntity } from 'src/entities/shared-link.entity'; import { SharedLinkEntity } from 'src/entities/shared-link.entity';
import { Permission, SharedLinkType } from 'src/enum'; import { Permission, SharedLinkType } from 'src/enum';
@ -17,8 +18,10 @@ import { getExternalDomain, OpenGraphTags } from 'src/utils/misc';
@Injectable() @Injectable()
export class SharedLinkService extends BaseService { export class SharedLinkService extends BaseService {
async getAll(auth: AuthDto): Promise<SharedLinkResponseDto[]> { async getAll(auth: AuthDto, { albumId }: SharedLinkSearchDto): Promise<SharedLinkResponseDto[]> {
return this.sharedLinkRepository.getAll(auth.user.id).then((links) => links.map((link) => mapSharedLink(link))); return this.sharedLinkRepository
.getAll({ userId: auth.user.id, albumId })
.then((links) => links.map((link) => mapSharedLink(link)));
} }
async getMine(auth: AuthDto, dto: SharedLinkPasswordDto): Promise<SharedLinkResponseDto> { async getMine(auth: AuthDto, dto: SharedLinkPasswordDto): Promise<SharedLinkResponseDto> {

View file

@ -0,0 +1,40 @@
<script lang="ts">
import SharedLinkCopy from '$lib/components/sharedlinks-page/actions/shared-link-copy.svelte';
import { locale } from '$lib/stores/preferences.store';
import type { AlbumResponseDto, SharedLinkResponseDto } from '@immich/sdk';
import { Text } from '@immich/ui';
import { DateTime } from 'luxon';
import { t } from 'svelte-i18n';
type Props = {
album: AlbumResponseDto;
sharedLink: SharedLinkResponseDto;
};
const { album, sharedLink }: Props = $props();
</script>
<div class="flex justify-between items-center">
<div class="flex flex-col gap-1">
<Text size="small">{sharedLink.description || album.albumName}</Text>
<Text size="tiny" color="muted"
>{[
DateTime.fromISO(sharedLink.createdAt).toLocaleString(
{
month: 'long',
day: 'numeric',
year: 'numeric',
},
{ locale: $locale },
),
sharedLink.allowUpload && $t('upload'),
sharedLink.allowDownload && $t('download'),
sharedLink.showMetadata && $t('exif'),
sharedLink.password && $t('password'),
]
.filter(Boolean)
.join(' • ')}</Text
>
</div>
<SharedLinkCopy link={sharedLink} />
</div>

View file

@ -1,4 +1,5 @@
<script lang="ts"> <script lang="ts">
import AlbumSharedLink from '$lib/components/album-page/album-shared-link.svelte';
import Dropdown from '$lib/components/elements/dropdown.svelte'; import Dropdown from '$lib/components/elements/dropdown.svelte';
import Icon from '$lib/components/elements/icon.svelte'; import Icon from '$lib/components/elements/icon.svelte';
import FullScreenModal from '$lib/components/shared-components/full-screen-modal.svelte'; import FullScreenModal from '$lib/components/shared-components/full-screen-modal.svelte';
@ -12,11 +13,11 @@
type SharedLinkResponseDto, type SharedLinkResponseDto,
type UserResponseDto, type UserResponseDto,
} from '@immich/sdk'; } from '@immich/sdk';
import { mdiCheck, mdiEye, mdiLink, mdiPencil, mdiShareCircle } from '@mdi/js'; import { Button, Link, Stack, Text } from '@immich/ui';
import { mdiCheck, mdiEye, mdiLink, mdiPencil } from '@mdi/js';
import { onMount } from 'svelte'; import { onMount } from 'svelte';
import Button from '../elements/buttons/button.svelte';
import UserAvatar from '../shared-components/user-avatar.svelte';
import { t } from 'svelte-i18n'; import { t } from 'svelte-i18n';
import UserAvatar from '../shared-components/user-avatar.svelte';
interface Props { interface Props {
album: AlbumResponseDto; album: AlbumResponseDto;
@ -38,7 +39,7 @@
let sharedLinks: SharedLinkResponseDto[] = $state([]); let sharedLinks: SharedLinkResponseDto[] = $state([]);
onMount(async () => { onMount(async () => {
await getSharedLinks(); sharedLinks = await getAllSharedLinks({ albumId: album.id });
const data = await searchUsers(); const data = await searchUsers();
// remove album owner // remove album owner
@ -50,11 +51,6 @@
} }
}); });
const getSharedLinks = async () => {
const data = await getAllSharedLinks();
sharedLinks = data.filter((link) => link.album?.id === album.id);
};
const handleToggle = (user: UserResponseDto) => { const handleToggle = (user: UserResponseDto) => {
if (Object.keys(selectedUsers).includes(user.id)) { if (Object.keys(selectedUsers).includes(user.id)) {
delete selectedUsers[user.id]; delete selectedUsers[user.id];
@ -72,10 +68,10 @@
}; };
</script> </script>
<FullScreenModal title={$t('invite_to_album')} showLogo {onClose}> <FullScreenModal title={$t('share')} showLogo {onClose}>
{#if Object.keys(selectedUsers).length > 0} {#if Object.keys(selectedUsers).length > 0}
<div class="mb-2 py-2 sticky"> <div class="mb-2 py-2 sticky">
<p class="text-xs font-medium">{$t('selected').toUpperCase()}</p> <p class="text-xs font-medium">{$t('selected')}</p>
<div class="my-2"> <div class="my-2">
{#each Object.values(selectedUsers) as { user }} {#each Object.values(selectedUsers) as { user }}
{#key user.id} {#key user.id}
@ -117,7 +113,7 @@
<div class="immich-scrollbar max-h-[500px] overflow-y-auto"> <div class="immich-scrollbar max-h-[500px] overflow-y-auto">
{#if users.length > 0 && users.length !== Object.keys(selectedUsers).length} {#if users.length > 0 && users.length !== Object.keys(selectedUsers).length}
<p class="text-xs font-medium">{$t('suggestions').toUpperCase()}</p> <Text>{$t('users')}</Text>
<div class="my-2"> <div class="my-2">
{#each users as user} {#each users as user}
@ -144,9 +140,9 @@
{#if users.length > 0} {#if users.length > 0}
<div class="py-3"> <div class="py-3">
<Button <Button
size="sm" size="small"
fullwidth fullWidth
rounded="full" shape="round"
disabled={Object.keys(selectedUsers).length === 0} disabled={Object.keys(selectedUsers).length === 0}
onclick={() => onclick={() =>
onSelect(Object.values(selectedUsers).map(({ user, ...rest }) => ({ userId: user.id, ...rest })))} onSelect(Object.values(selectedUsers).map(({ user, ...rest }) => ({ userId: user.id, ...rest })))}
@ -155,26 +151,20 @@
</div> </div>
{/if} {/if}
<hr /> <hr class="my-4" />
<div id="shared-buttons" class="mt-4 flex place-content-center place-items-center justify-around"> <Stack gap={6}>
<button <div class="flex justify-between items-center">
type="button" <Text>{$t('shared_links')}</Text>
class="flex flex-col place-content-center place-items-center gap-2 hover:cursor-pointer" <Link href={AppRoute.SHARED_LINKS} class="text-sm">{$t('view_all')}</Link>
onclick={onShare} </div>
>
<Icon path={mdiLink} size={24} />
<p class="text-sm">{$t('create_link')}</p>
</button>
{#if sharedLinks.length} <Stack gap={4}>
<a {#each sharedLinks as sharedLink}
href={AppRoute.SHARED_LINKS} <AlbumSharedLink {album} {sharedLink} />
class="flex flex-col place-content-center place-items-center gap-2 hover:cursor-pointer" {/each}
> </Stack>
<Icon path={mdiShareCircle} size={24} />
<p class="text-sm">{$t('view_links')}</p> <Button leadingIcon={mdiLink} size="small" shape="round" fullWidth onclick={onShare}>{$t('create_link')}</Button>
</a> </Stack>
{/if}
</div>
</FullScreenModal> </FullScreenModal>

View file

@ -27,7 +27,7 @@
let sharedLink = $derived(sharedLinks.find(({ id }) => id === page.params.id)); let sharedLink = $derived(sharedLinks.find(({ id }) => id === page.params.id));
const refresh = async () => { const refresh = async () => {
sharedLinks = await getAllSharedLinks(); sharedLinks = await getAllSharedLinks({});
}; };
onMount(async () => { onMount(async () => {