format files

This commit is contained in:
maxDorninger
2025-08-30 21:53:00 +02:00
parent 18c0b38c8d
commit e4b8596468
31 changed files with 2055 additions and 2114 deletions

View File

@@ -1,102 +1,100 @@
<script lang="ts">
import {Button} from '$lib/components/ui/button/index.js';
import {env} from '$env/dynamic/public';
import * as Card from '$lib/components/ui/card/index.js';
import {ImageOff} from 'lucide-svelte';
import {goto} from '$app/navigation';
import {base} from '$app/paths';
import type {MetaDataProviderSearchResult} from '$lib/types.js';
import {SvelteURLSearchParams} from 'svelte/reactivity';
import type {components} from "$lib/api/api";
import client from "$lib/api";
import { Button } from '$lib/components/ui/button/index.js';
import * as Card from '$lib/components/ui/card/index.js';
import { ImageOff } from 'lucide-svelte';
import { goto } from '$app/navigation';
import { base } from '$app/paths';
import type { components } from '$lib/api/api';
import client from '$lib/api';
const apiUrl = env.PUBLIC_API_URL;
let loading = $state(false);
let errorMessage = $state<string | null>(null);
let {result, isShow = true}: { result: components['schemas']['MetaDataProviderSearchResult']; isShow: boolean } =
$props();
console.log('Add Show Card Result: ', result);
let loading = $state(false);
let errorMessage = $state<string | null>(null);
let {
result,
isShow = true
}: { result: components['schemas']['MetaDataProviderSearchResult']; isShow: boolean } = $props();
console.log('Add Show Card Result: ', result);
async function addMedia() {
loading = true;
let data;
if (isShow) {
const response = await client.POST("/api/v1/tv/shows", {
params: {
query: {
show_id: result.external_id,
metadata_provider: result.metadata_provider as "tmdb" | "tvdb"
}
}
});
data = response.data;
} else {
const response = await client.POST("/api/v1/movies", {
params: {
query: {
movie_id: result.external_id,
metadata_provider: result.metadata_provider as "tmdb" | "tvdb"
}
}
});
data = response.data;
}
await goto(`${base}/dashboard/${isShow ? 'tv' : 'movies'}/` + data?.id);
loading = false;
}
async function addMedia() {
loading = true;
let data;
if (isShow) {
const response = await client.POST('/api/v1/tv/shows', {
params: {
query: {
show_id: result.external_id,
metadata_provider: result.metadata_provider as 'tmdb' | 'tvdb'
}
}
});
data = response.data;
} else {
const response = await client.POST('/api/v1/movies', {
params: {
query: {
movie_id: result.external_id,
metadata_provider: result.metadata_provider as 'tmdb' | 'tvdb'
}
}
});
data = response.data;
}
await goto(`${base}/dashboard/${isShow ? 'tv' : 'movies'}/` + data?.id);
loading = false;
}
</script>
<Card.Root class="col-span-full flex h-full flex-col overflow-x-hidden sm:col-span-1">
<Card.Header>
<Card.Title class="flex h-12 items-center leading-tight">
{result.name}
{#if result.year != null}
({result.year})
{/if}
</Card.Title>
<Card.Description class="truncate"
>{result.overview !== '' ? result.overview : 'No overview available'}</Card.Description
>
</Card.Header>
<Card.Content class="flex flex-1 items-center justify-center">
{#if result.poster_path != null}
<img
class="h-full w-full rounded-lg object-contain"
src={result.poster_path}
alt="{result.name}'s Poster Image"
/>
{:else}
<div class="flex h-full w-full items-center justify-center">
<ImageOff class="h-12 w-12 text-gray-400"/>
</div>
{/if}
</Card.Content>
<Card.Footer class="bg-card flex flex-col items-start gap-2 rounded-b-lg border-t p-4">
<Button
class="w-full font-semibold"
disabled={result.added || loading}
onclick={() => addMedia()}
>
{#if loading}
<span class="animate-pulse">Loading...</span>
{:else}
{result.added ? 'Show already exists' : `Add ${isShow ? 'Show' : 'Movie'}`}
{/if}
</Button>
<div class="flex w-full items-center gap-2">
{#if result.vote_average != null}
<Card.Header>
<Card.Title class="flex h-12 items-center leading-tight">
{result.name}
{#if result.year != null}
({result.year})
{/if}
</Card.Title>
<Card.Description class="truncate"
>{result.overview !== '' ? result.overview : 'No overview available'}</Card.Description
>
</Card.Header>
<Card.Content class="flex flex-1 items-center justify-center">
{#if result.poster_path != null}
<img
class="h-full w-full rounded-lg object-contain"
src={result.poster_path}
alt="{result.name}'s Poster Image"
/>
{:else}
<div class="flex h-full w-full items-center justify-center">
<ImageOff class="h-12 w-12 text-gray-400" />
</div>
{/if}
</Card.Content>
<Card.Footer class="bg-card flex flex-col items-start gap-2 rounded-b-lg border-t p-4">
<Button
class="w-full font-semibold"
disabled={result.added || loading}
onclick={() => addMedia()}
>
{#if loading}
<span class="animate-pulse">Loading...</span>
{:else}
{result.added ? 'Show already exists' : `Add ${isShow ? 'Show' : 'Movie'}`}
{/if}
</Button>
<div class="flex w-full items-center gap-2">
{#if result.vote_average != null}
<span class="flex items-center text-sm font-medium text-yellow-600">
<svg class="mr-1 h-4 w-4 text-yellow-400" fill="currentColor" viewBox="0 0 20 20"
><path
d="M10 15l-5.878 3.09 1.122-6.545L.488 6.91l6.561-.955L10 0l2.951 5.955 6.561.955-4.756 4.635 1.122 6.545z"
/></svg
>
><path
d="M10 15l-5.878 3.09 1.122-6.545L.488 6.91l6.561-.955L10 0l2.951 5.955 6.561.955-4.756 4.635 1.122 6.545z"
/></svg
>
Rating: {Math.round(result.vote_average)}/10
</span>
{/if}
</div>
{#if errorMessage}
<p class="w-full rounded bg-red-50 px-2 py-1 text-xs text-red-500">{errorMessage}</p>
{/if}
</Card.Footer>
{/if}
</div>
{#if errorMessage}
<p class="w-full rounded bg-red-50 px-2 py-1 text-xs text-red-500">{errorMessage}</p>
{/if}
</Card.Footer>
</Card.Root>

View File

@@ -1,162 +1,160 @@
<script lang="ts">
import {env} from '$env/dynamic/public';
import {Button, buttonVariants} from '$lib/components/ui/button/index.js';
import {Input} from '$lib/components/ui/input';
import {Label} from '$lib/components/ui/label';
import {toast} from 'svelte-sonner';
import {Badge} from '$lib/components/ui/badge/index.js';
import {SvelteURLSearchParams} from 'svelte/reactivity';
import { Button, buttonVariants } from '$lib/components/ui/button/index.js';
import { Input } from '$lib/components/ui/input';
import { Label } from '$lib/components/ui/label';
import { toast } from 'svelte-sonner';
import { Badge } from '$lib/components/ui/badge/index.js';
import type {PublicIndexerQueryResult} from '$lib/types.js';
import {getFullyQualifiedMediaName} from '$lib/utils';
import {LoaderCircle} from 'lucide-svelte';
import * as Dialog from '$lib/components/ui/dialog/index.js';
import * as Tabs from '$lib/components/ui/tabs/index.js';
import * as Select from '$lib/components/ui/select/index.js';
import * as Table from '$lib/components/ui/table/index.js';
import client from "$lib/api";
import type {components} from "$lib/api/api";
import { getFullyQualifiedMediaName } from '$lib/utils';
import { LoaderCircle } from 'lucide-svelte';
import * as Dialog from '$lib/components/ui/dialog/index.js';
import * as Tabs from '$lib/components/ui/tabs/index.js';
import * as Select from '$lib/components/ui/select/index.js';
import * as Table from '$lib/components/ui/table/index.js';
import client from '$lib/api';
import type { components } from '$lib/api/api';
const apiUrl = env.PUBLIC_API_URL;
let {movie} = $props();
let dialogueState = $state(false);
let torrents: components["schemas"]["PublicIndexerQueryResult"][] = $state([]);
let isLoadingTorrents: boolean = $state(false);
let torrentsError: string | null = $state(null);
let queryOverride: string = $state('');
let filePathSuffix: string = $state('');
let { movie } = $props();
let dialogueState = $state(false);
let torrents: components['schemas']['PublicIndexerQueryResult'][] = $state([]);
let isLoadingTorrents: boolean = $state(false);
let torrentsError: string | null = $state(null);
let queryOverride: string = $state('');
let filePathSuffix: string = $state('');
async function downloadTorrent(result_id: string) {
const {data, response} = await client.POST(`/api/v1/movies/{movie_id}/torrents`, {
params: {
path: {
movie_id: movie.id
},
query: {
public_indexer_result_id: result_id,
override_file_path_suffix: filePathSuffix === '' ? undefined : filePathSuffix
}
}
})
if (response.status === 409) {
const errorMessage = `There already is a Movie File using the Filepath Suffix '${filePathSuffix}'. Try again with a different Filepath Suffix.`;
console.warn(errorMessage);
torrentsError = errorMessage;
if (dialogueState) toast.info(errorMessage);
return [];
} else if (!response.ok) {
const errorMessage = `Failed to download torrent for movie ${movie.id}: ${response.statusText}`;
console.error(errorMessage);
torrentsError = errorMessage;
toast.error(errorMessage);
return false;
} else {
console.log('Downloading torrent:', data);
toast.success('Torrent download started successfully!');
async function downloadTorrent(result_id: string) {
const { data, response } = await client.POST(`/api/v1/movies/{movie_id}/torrents`, {
params: {
path: {
movie_id: movie.id
},
query: {
public_indexer_result_id: result_id,
override_file_path_suffix: filePathSuffix === '' ? undefined : filePathSuffix
}
}
});
if (response.status === 409) {
const errorMessage = `There already is a Movie File using the Filepath Suffix '${filePathSuffix}'. Try again with a different Filepath Suffix.`;
console.warn(errorMessage);
torrentsError = errorMessage;
if (dialogueState) toast.info(errorMessage);
return [];
} else if (!response.ok) {
const errorMessage = `Failed to download torrent for movie ${movie.id}: ${response.statusText}`;
console.error(errorMessage);
torrentsError = errorMessage;
toast.error(errorMessage);
return false;
} else {
console.log('Downloading torrent:', data);
toast.success('Torrent download started successfully!');
return true;
}
}
return true;
}
}
async function getTorrents(override: boolean = false): Promise<components["schemas"]["PublicIndexerQueryResult"][]> {
isLoadingTorrents = true;
torrentsError = null;
torrents = [];
let {response, data} = await client.GET('/api/v1/movies/{movie_id}/torrents',{
params: {
query: {
search_query_override: override ? queryOverride : undefined
},
path: {
movie_id: movie.id
}
}
})
data = data as components["schemas"]["PublicIndexerQueryResult"][];
isLoadingTorrents = false;
async function getTorrents(
override: boolean = false
): Promise<components['schemas']['PublicIndexerQueryResult'][]> {
isLoadingTorrents = true;
torrentsError = null;
torrents = [];
let { response, data } = await client.GET('/api/v1/movies/{movie_id}/torrents', {
params: {
query: {
search_query_override: override ? queryOverride : undefined
},
path: {
movie_id: movie.id
}
}
});
data = data as components['schemas']['PublicIndexerQueryResult'][];
isLoadingTorrents = false;
if (!response.ok) {
const errorMessage = `Failed to fetch torrents for movie ${movie.id}: ${response.statusText}`;
torrentsError = errorMessage;
if (dialogueState) toast.error(errorMessage);
return [];
}
if (!response.ok) {
const errorMessage = `Failed to fetch torrents for movie ${movie.id}: ${response.statusText}`;
torrentsError = errorMessage;
if (dialogueState) toast.error(errorMessage);
return [];
}
if (dialogueState) {
if (data.length > 0) {
toast.success(`Found ${data.length} torrents.`);
} else {
toast.info('No torrents found for your query.');
}
}
return data;
}
if (dialogueState) {
if (data.length > 0) {
toast.success(`Found ${data.length} torrents.`);
} else {
toast.info('No torrents found for your query.');
}
}
return data;
}
$effect(() => {
if (movie?.id) {
getTorrents().then((fetchedTorrents) => {
if (!isLoadingTorrents) {
torrents = fetchedTorrents;
} else if (fetchedTorrents.length > 0 || torrentsError) {
torrents = fetchedTorrents;
}
});
}
});
$effect(() => {
if (movie?.id) {
getTorrents().then((fetchedTorrents) => {
if (!isLoadingTorrents) {
torrents = fetchedTorrents;
} else if (fetchedTorrents.length > 0 || torrentsError) {
torrents = fetchedTorrents;
}
});
}
});
</script>
{#snippet saveDirectoryPreview(movie: components["schemas"]["Movie"], filePathSuffix: string)}
/{getFullyQualifiedMediaName(movie)} [{movie.metadata_provider}id-{movie.external_id}
]/{movie.name}{filePathSuffix === '' ? '' : ' - ' + filePathSuffix}.mkv
{#snippet saveDirectoryPreview(movie: components['schemas']['Movie'], filePathSuffix: string)}
/{getFullyQualifiedMediaName(movie)} [{movie.metadata_provider}id-{movie.external_id}
]/{movie.name}{filePathSuffix === '' ? '' : ' - ' + filePathSuffix}.mkv
{/snippet}
<Dialog.Root bind:open={dialogueState}>
<Dialog.Trigger class={buttonVariants({ variant: 'default' })}>Download Movie</Dialog.Trigger>
<Dialog.Content class="max-h-[90vh] w-fit min-w-[80vw] overflow-y-auto">
<Dialog.Header>
<Dialog.Title>Download a Movie</Dialog.Title>
<Dialog.Description>
Search and download torrents for a specific season or season packs.
</Dialog.Description>
</Dialog.Header>
<Tabs.Root class="w-full" value="basic">
<Tabs.List>
<Tabs.Trigger value="basic">Standard Mode</Tabs.Trigger>
<Tabs.Trigger value="advanced">Advanced Mode</Tabs.Trigger>
</Tabs.List>
<Tabs.Content value="basic">
<div class="grid w-full items-center gap-1.5">
<Label for="file-suffix">Filepath suffix</Label>
<Select.Root bind:value={filePathSuffix} type="single">
<Select.Trigger class="w-[180px]">{filePathSuffix}</Select.Trigger>
<Select.Content>
<Select.Item value="">None</Select.Item>
<Select.Item value="2160P">2160p</Select.Item>
<Select.Item value="1080P">1080p</Select.Item>
<Select.Item value="720P">720p</Select.Item>
<Select.Item value="480P">480p</Select.Item>
<Select.Item value="360P">360p</Select.Item>
</Select.Content>
</Select.Root>
<p class="text-muted-foreground text-sm">
This is necessary to differentiate between versions of the same movie, for example a
1080p and a 4K version.
</p>
<Label for="file-suffix-display"
>The files will be saved in the following directory:</Label
>
<p class="text-muted-foreground text-sm" id="file-suffix-display">
{@render saveDirectoryPreview(movie, filePathSuffix)}
</p>
</div>
</Tabs.Content>
<Tabs.Content value="advanced">
<div class="grid w-full items-center gap-1.5">
<Label for="query-override">Enter a custom query</Label>
<div class="flex w-full max-w-sm items-center space-x-2">
<Input bind:value={queryOverride} id="query-override" type="text"/>
<Button
onclick={async () => {
<Dialog.Trigger class={buttonVariants({ variant: 'default' })}>Download Movie</Dialog.Trigger>
<Dialog.Content class="max-h-[90vh] w-fit min-w-[80vw] overflow-y-auto">
<Dialog.Header>
<Dialog.Title>Download a Movie</Dialog.Title>
<Dialog.Description>
Search and download torrents for a specific season or season packs.
</Dialog.Description>
</Dialog.Header>
<Tabs.Root class="w-full" value="basic">
<Tabs.List>
<Tabs.Trigger value="basic">Standard Mode</Tabs.Trigger>
<Tabs.Trigger value="advanced">Advanced Mode</Tabs.Trigger>
</Tabs.List>
<Tabs.Content value="basic">
<div class="grid w-full items-center gap-1.5">
<Label for="file-suffix">Filepath suffix</Label>
<Select.Root bind:value={filePathSuffix} type="single">
<Select.Trigger class="w-[180px]">{filePathSuffix}</Select.Trigger>
<Select.Content>
<Select.Item value="">None</Select.Item>
<Select.Item value="2160P">2160p</Select.Item>
<Select.Item value="1080P">1080p</Select.Item>
<Select.Item value="720P">720p</Select.Item>
<Select.Item value="480P">480p</Select.Item>
<Select.Item value="360P">360p</Select.Item>
</Select.Content>
</Select.Root>
<p class="text-muted-foreground text-sm">
This is necessary to differentiate between versions of the same movie, for example a
1080p and a 4K version.
</p>
<Label for="file-suffix-display"
>The files will be saved in the following directory:</Label
>
<p class="text-muted-foreground text-sm" id="file-suffix-display">
{@render saveDirectoryPreview(movie, filePathSuffix)}
</p>
</div>
</Tabs.Content>
<Tabs.Content value="advanced">
<div class="grid w-full items-center gap-1.5">
<Label for="query-override">Enter a custom query</Label>
<div class="flex w-full max-w-sm items-center space-x-2">
<Input bind:value={queryOverride} id="query-override" type="text" />
<Button
onclick={async () => {
isLoadingTorrents = true;
torrentsError = null;
torrents = [];
@@ -168,90 +166,90 @@
isLoadingTorrents = false;
}
}}
variant="secondary"
>
Search
</Button>
</div>
<p class="text-muted-foreground text-sm">
The custom query will override the default search string like "A Minecraft Movie
(2025)".
</p>
<Label for="file-suffix">Filepath suffix</Label>
<Input
bind:value={filePathSuffix}
class="max-w-sm"
id="file-suffix"
placeholder="1080P"
type="text"
/>
<p class="text-muted-foreground text-sm">
This is necessary to differentiate between versions of the same movie, for example a
1080p and a 4K version.
</p>
variant="secondary"
>
Search
</Button>
</div>
<p class="text-muted-foreground text-sm">
The custom query will override the default search string like "A Minecraft Movie
(2025)".
</p>
<Label for="file-suffix">Filepath suffix</Label>
<Input
bind:value={filePathSuffix}
class="max-w-sm"
id="file-suffix"
placeholder="1080P"
type="text"
/>
<p class="text-muted-foreground text-sm">
This is necessary to differentiate between versions of the same movie, for example a
1080p and a 4K version.
</p>
<Label for="file-suffix-display"
>The files will be saved in the following directory:</Label
>
<p class="text-muted-foreground text-sm" id="file-suffix-display">
{@render saveDirectoryPreview(movie, filePathSuffix)}
</p>
</div>
</Tabs.Content>
</Tabs.Root>
<div class="mt-4 items-center">
{#if isLoadingTorrents}
<div class="flex w-full max-w-sm items-center space-x-2">
<LoaderCircle class="animate-spin"/>
<p>Loading torrents...</p>
</div>
{:else if torrentsError}
<p class="text-red-500">Error: {torrentsError}</p>
{:else if torrents.length > 0}
<h3 class="mb-2 text-lg font-semibold">Found Torrents:</h3>
<div class="overflow-y-auto rounded-md border p-2">
<Table.Root>
<Table.Header>
<Table.Row>
<Table.Head>Title</Table.Head>
<Table.Head>Size</Table.Head>
<Table.Head>Seeders</Table.Head>
<Table.Head>Score</Table.Head>
<Table.Head>Indexer Flags</Table.Head>
<Table.Head class="text-right">Actions</Table.Head>
</Table.Row>
</Table.Header>
<Table.Body>
{#each torrents as torrent (torrent.id)}
<Table.Row>
<Table.Cell class="max-w-[300px] font-medium">{torrent.title}</Table.Cell>
<Table.Cell>{(torrent.size / 1024 / 1024 / 1024).toFixed(2)}GB</Table.Cell>
<Table.Cell>{torrent.seeders}</Table.Cell>
<Table.Cell>{torrent.score}</Table.Cell>
<Table.Cell>
{#each torrent.flags as flag (flag)}
<Badge variant="outline">{flag}</Badge>
{/each}
</Table.Cell>
<Table.Cell class="text-right">
<Button
size="sm"
variant="outline"
onclick={() => {
<Label for="file-suffix-display"
>The files will be saved in the following directory:</Label
>
<p class="text-muted-foreground text-sm" id="file-suffix-display">
{@render saveDirectoryPreview(movie, filePathSuffix)}
</p>
</div>
</Tabs.Content>
</Tabs.Root>
<div class="mt-4 items-center">
{#if isLoadingTorrents}
<div class="flex w-full max-w-sm items-center space-x-2">
<LoaderCircle class="animate-spin" />
<p>Loading torrents...</p>
</div>
{:else if torrentsError}
<p class="text-red-500">Error: {torrentsError}</p>
{:else if torrents.length > 0}
<h3 class="mb-2 text-lg font-semibold">Found Torrents:</h3>
<div class="overflow-y-auto rounded-md border p-2">
<Table.Root>
<Table.Header>
<Table.Row>
<Table.Head>Title</Table.Head>
<Table.Head>Size</Table.Head>
<Table.Head>Seeders</Table.Head>
<Table.Head>Score</Table.Head>
<Table.Head>Indexer Flags</Table.Head>
<Table.Head class="text-right">Actions</Table.Head>
</Table.Row>
</Table.Header>
<Table.Body>
{#each torrents as torrent (torrent.id)}
<Table.Row>
<Table.Cell class="max-w-[300px] font-medium">{torrent.title}</Table.Cell>
<Table.Cell>{(torrent.size / 1024 / 1024 / 1024).toFixed(2)}GB</Table.Cell>
<Table.Cell>{torrent.seeders}</Table.Cell>
<Table.Cell>{torrent.score}</Table.Cell>
<Table.Cell>
{#each torrent.flags as flag (flag)}
<Badge variant="outline">{flag}</Badge>
{/each}
</Table.Cell>
<Table.Cell class="text-right">
<Button
size="sm"
variant="outline"
onclick={() => {
downloadTorrent(torrent.id);
}}
>
Download
</Button>
</Table.Cell>
</Table.Row>
{/each}
</Table.Body>
</Table.Root>
</div>
{:else}
<p>No torrents found!</p>
{/if}
</div>
</Dialog.Content>
>
Download
</Button>
</Table.Cell>
</Table.Row>
{/each}
</Table.Body>
</Table.Root>
</div>
{:else}
<p>No torrents found!</p>
{/if}
</div>
</Dialog.Content>
</Dialog.Root>

View File

@@ -92,10 +92,7 @@
}
</script>
{#snippet saveDirectoryPreview(
show: components['schemas']['Show'],
filePathSuffix: string
)}
{#snippet saveDirectoryPreview(show: components['schemas']['Show'], filePathSuffix: string)}
/{getFullyQualifiedMediaName(show)} [{show.metadata_provider}id-{show.external_id}]/ Season XX/{show.name}
SXXEXX {filePathSuffix === '' ? '' : ' - ' + filePathSuffix}.mkv
{/snippet}

View File

@@ -1,126 +1,122 @@
<script lang="ts">
import {Button} from '$lib/components/ui/button/index.js';
import * as Command from '$lib/components/ui/command/index.js';
import * as Popover from '$lib/components/ui/popover/index.js';
import {cn} from '$lib/utils.js';
import {tick} from 'svelte';
import {CheckIcon, ChevronsUpDownIcon} from 'lucide-svelte';
import type {LibraryItem, PublicMovie, PublicShow} from '$lib/types.js';
import {onMount} from 'svelte';
import {env} from '$env/dynamic/public';
import {toast} from 'svelte-sonner';
import {SvelteURLSearchParams} from 'svelte/reactivity';
import client from "$lib/api";
import type {components} from "$lib/api/api";
import { Button } from '$lib/components/ui/button/index.js';
import * as Command from '$lib/components/ui/command/index.js';
import * as Popover from '$lib/components/ui/popover/index.js';
import { cn } from '$lib/utils.js';
import { tick } from 'svelte';
import { CheckIcon, ChevronsUpDownIcon } from 'lucide-svelte';
import type { PublicMovie, PublicShow } from '$lib/types.js';
import { onMount } from 'svelte';
import { toast } from 'svelte-sonner';
import client from '$lib/api';
import type { components } from '$lib/api/api';
const apiUrl = env.PUBLIC_API_URL;
let {
media,
mediaType
}: {
media: PublicShow | PublicMovie;
mediaType: 'tv' | 'movie';
} = $props();
let {
media,
mediaType
}: {
media: PublicShow | PublicMovie;
mediaType: 'tv' | 'movie';
} = $props();
let open = $state(false);
let value = $derived(media.library === '' ? 'Default' : media.library);
let libraries: components['schemas']['LibraryItem'][] = $state([]);
let triggerRef: HTMLButtonElement = $state(null!);
const selectedLabel: string = $derived(
libraries.find((item) => item.name === value)?.name ?? 'Default'
);
onMount(async () => {
const tvLibraries = await client.GET('/api/v1/tv/shows/libraries');
const movieLibraries = await client.GET('/api/v1/movies/libraries');
let open = $state(false);
let value = $derived(media.library === '' ? 'Default' : media.library);
let libraries: components["schemas"]["LibraryItem"][] = $state([]);
let triggerRef: HTMLButtonElement = $state(null!);
const selectedLabel: string = $derived(
libraries.find((item) => item.name === value)?.name ?? 'Default'
);
onMount(async () => {
const tvLibraries = await client.GET("/api/v1/tv/shows/libraries");
const movieLibraries = await client.GET("/api/v1/movies/libraries");
if (mediaType === 'tv') {
libraries = tvLibraries.data;
} else {
libraries = movieLibraries.data;
}
if (mediaType === "tv"){
libraries = tvLibraries.data
}else{
libraries = movieLibraries.data
}
if (!value && libraries.length > 0) {
value = 'Default';
}
libraries.push({
name: 'Default',
path: 'Default'
} as components['schemas']['LibraryItem']);
});
if (!value && libraries.length > 0) {
value = 'Default';
}
libraries.push({
name: 'Default',
path: 'Default'
} as components["schemas"]["LibraryItem"]);
});
async function handleSelect() {
open = false;
await tick();
triggerRef.focus();
let response;
if (mediaType === 'tv') {
response = await client.POST('/api/v1/tv/shows/{show_id}/library', {
params: {
path: { show_id: media.id },
query: { library: selectedLabel }
}
});
} else {
response = await client.POST('/api/v1/movies/{movie_id}/library', {
params: {
path: { movie_id: media.id },
query: { library: selectedLabel }
}
});
}
if (response.error) {
toast.error('Failed to update library');
} else {
toast.success(`Library updated to ${selectedLabel}`);
media.library = selectedLabel;
}
}
async function handleSelect() {
open = false;
await tick();
triggerRef.focus();
const endpoint =
mediaType === 'tv' ? `/tv/shows/${media.id}/library` : `/movies/${media.id}/library`;
const urlParams = new SvelteURLSearchParams();
urlParams.append('library', selectedLabel);
const urlString = `${apiUrl}${endpoint}?${urlParams.toString()}`;
try {
const response = await fetch(urlString, {
method: 'POST',
credentials: 'include'
});
if (response.ok) {
toast.success(`Library updated to ${selectedLabel}`);
media.library = selectedLabel;
} else {
const errorText = await response.text();
toast.error(`Failed to update library: ${errorText}`);
}
} catch (error) {
toast.error('Error updating library.');
console.error(error);
}
}
function closeAndFocusTrigger() {
open = false;
tick().then(() => {
triggerRef.focus();
});
}
function closeAndFocusTrigger() {
open = false;
tick().then(() => {
triggerRef.focus();
});
}
</script>
<Popover.Root bind:open>
<Popover.Trigger bind:ref={triggerRef}>
{#snippet child({props})}
<Button
{...props}
variant="outline"
class="w-[200px] justify-between"
role="combobox"
aria-expanded={open}
>
Select Library
<ChevronsUpDownIcon class="opacity-50"/>
</Button>
{/snippet}
</Popover.Trigger>
<Popover.Content class="w-[200px] p-0">
<Command.Root>
<Command.Input placeholder="Search library..."/>
<Command.List>
<Command.Empty>No library found.</Command.Empty>
<Command.Group value="libraries">
{#each libraries as item (item.name)}
<Command.Item
value={item.name}
onSelect={() => {
<Popover.Trigger bind:ref={triggerRef}>
{#snippet child({ props })}
<Button
{...props}
variant="outline"
class="w-[200px] justify-between"
role="combobox"
aria-expanded={open}
>
Select Library
<ChevronsUpDownIcon class="opacity-50" />
</Button>
{/snippet}
</Popover.Trigger>
<Popover.Content class="w-[200px] p-0">
<Command.Root>
<Command.Input placeholder="Search library..." />
<Command.List>
<Command.Empty>No library found.</Command.Empty>
<Command.Group value="libraries">
{#each libraries as item (item.name)}
<Command.Item
value={item.name}
onSelect={() => {
value = item.name;
handleSelect();
closeAndFocusTrigger();
}}
>
<CheckIcon class={cn(value !== item.name && 'text-transparent')}/>
{item.name}
</Command.Item>
{/each}
</Command.Group>
</Command.List>
</Command.Root>
</Popover.Content>
>
<CheckIcon class={cn(value !== item.name && 'text-transparent')} />
{item.name}
</Command.Item>
{/each}
</Command.Group>
</Command.List>
</Command.Root>
</Popover.Content>
</Popover.Root>

View File

@@ -1,151 +1,146 @@
<script lang="ts">
import {Button} from '$lib/components/ui/button/index.js';
import * as Card from '$lib/components/ui/card/index.js';
import {Input} from '$lib/components/ui/input/index.js';
import {Label} from '$lib/components/ui/label/index.js';
import {goto} from '$app/navigation';
import {env} from '$env/dynamic/public';
import {toast} from 'svelte-sonner';
import {base} from '$app/paths';
import * as Alert from '$lib/components/ui/alert/index.js';
import AlertCircleIcon from '@lucide/svelte/icons/alert-circle';
import LoadingBar from '$lib/components/loading-bar.svelte';
import {SvelteURLSearchParams} from 'svelte/reactivity';
import client from "$lib/api";
import type {components} from "$lib/api/api";
import { Button } from '$lib/components/ui/button/index.js';
import * as Card from '$lib/components/ui/card/index.js';
import { Input } from '$lib/components/ui/input/index.js';
import { Label } from '$lib/components/ui/label/index.js';
import { goto } from '$app/navigation';
import { toast } from 'svelte-sonner';
import { base } from '$app/paths';
import * as Alert from '$lib/components/ui/alert/index.js';
import AlertCircleIcon from '@lucide/svelte/icons/alert-circle';
import LoadingBar from '$lib/components/loading-bar.svelte';
import client from '$lib/api';
const apiUrl = env.PUBLIC_API_URL;
let {
oauthProvider
}: {
oauthProvider: {
oauth_name: string;
};
} = $props();
let {
oauthProvider
}: {
oauthProvider: {
oauth_name: string;
};
} = $props();
let email = $state('');
let password = $state('');
let errorMessage = $state('');
let isLoading = $state(false);
let email = $state('');
let password = $state('');
let errorMessage = $state('');
let isLoading = $state(false);
async function handleLogin(event: Event) {
event.preventDefault();
async function handleLogin(event: Event) {
event.preventDefault();
isLoading = true;
errorMessage = '';
isLoading = true;
errorMessage = '';
const { response } = await client.POST('/api/v1/auth/cookie/login', {
requestBody: {
content: {
'application/x-www-form-urlencoded': {
username: email,
password: password
}
}
}
});
isLoading = false;
const {response} = await client.POST('/api/v1/auth/cookie/login', {
requestBody: {
content: {
'application/x-www-form-urlencoded': {
username: email,
password: password
}
}
},
});
isLoading = false;
if (response.ok) {
console.log('Login successful!');
console.log('Received User Data: ', response);
errorMessage = 'Login successful! Redirecting...';
toast.success(errorMessage);
goto(base + '/dashboard');
} else {
let errorText = await response.text();
try {
const errorData = JSON.parse(errorText);
errorMessage = errorData.message || 'Login failed. Please check your credentials.';
} catch {
errorMessage = errorText || 'Login failed. Please check your credentials.';
}
toast.error(errorMessage);
console.error('Login failed:', response.status, errorText);
}
}
if (response.ok) {
console.log('Login successful!');
console.log('Received User Data: ', response);
errorMessage = 'Login successful! Redirecting...';
toast.success(errorMessage);
goto(base + '/dashboard');
} else {
let errorText = await response.text();
try {
const errorData = JSON.parse(errorText);
errorMessage = errorData.message || 'Login failed. Please check your credentials.';
} catch {
errorMessage = errorText || 'Login failed. Please check your credentials.';
}
toast.error(errorMessage);
console.error('Login failed:', response.status, errorText);
}
}
async function handleOauth() {
const {response, data, error} = await client.GET("/api/v1/auth/cookie/OpenID/authorize", {
params: {
query: {
scopes: 'email'
}
}
});
if (response.ok) {
window.location = data.authorization_url;
} else {
toast.error(data);
}
}
async function handleOauth() {
const { response, data } = await client.GET('/api/v1/auth/cookie/OpenID/authorize', {
params: {
query: {
scopes: 'email'
}
}
});
if (response.ok) {
window.location = data.authorization_url;
} else {
toast.error(data);
}
}
</script>
<Card.Root class="mx-auto max-w-sm">
<Card.Header>
<Card.Title class="text-2xl">Login</Card.Title>
<Card.Description>Enter your email below to log in to your account</Card.Description>
</Card.Header>
<Card.Content>
<form class="grid gap-4" onsubmit={handleLogin}>
<div class="grid gap-2">
<Label for="email">Email</Label>
<Input
autocomplete="email"
bind:value={email}
id="email"
placeholder="m@example.com"
required
type="email"
/>
</div>
<div class="grid gap-2">
<div class="flex items-center">
<Label for="password">Password</Label>
<a class="ml-auto inline-block text-sm underline" href="{base}/login/forgot-password">
Forgot your password?
</a>
</div>
<Input
autocomplete="current-password"
bind:value={password}
id="password"
required
type="password"
/>
</div>
<Card.Header>
<Card.Title class="text-2xl">Login</Card.Title>
<Card.Description>Enter your email below to log in to your account</Card.Description>
</Card.Header>
<Card.Content>
<form class="grid gap-4" onsubmit={handleLogin}>
<div class="grid gap-2">
<Label for="email">Email</Label>
<Input
autocomplete="email"
bind:value={email}
id="email"
placeholder="m@example.com"
required
type="email"
/>
</div>
<div class="grid gap-2">
<div class="flex items-center">
<Label for="password">Password</Label>
<a class="ml-auto inline-block text-sm underline" href="{base}/login/forgot-password">
Forgot your password?
</a>
</div>
<Input
autocomplete="current-password"
bind:value={password}
id="password"
required
type="password"
/>
</div>
{#if errorMessage}
<Alert.Root variant="destructive">
<AlertCircleIcon class="size-4"/>
<Alert.Title>Error</Alert.Title>
<Alert.Description>{errorMessage}</Alert.Description>
</Alert.Root>
{/if}
{#if isLoading}
<LoadingBar/>
{/if}
<Button class="w-full" disabled={isLoading} type="submit">Login</Button>
</form>
{#await oauthProvider}
<LoadingBar/>
{:then result}
{#if result.oauth_name != null}
<div
class="after:border-border relative mt-2 text-center text-sm after:absolute after:inset-0 after:top-1/2 after:z-0 after:flex after:items-center after:border-t"
>
{#if errorMessage}
<Alert.Root variant="destructive">
<AlertCircleIcon class="size-4" />
<Alert.Title>Error</Alert.Title>
<Alert.Description>{errorMessage}</Alert.Description>
</Alert.Root>
{/if}
{#if isLoading}
<LoadingBar />
{/if}
<Button class="w-full" disabled={isLoading} type="submit">Login</Button>
</form>
{#await oauthProvider}
<LoadingBar />
{:then result}
{#if result.oauth_name != null}
<div
class="after:border-border relative mt-2 text-center text-sm after:absolute after:inset-0 after:top-1/2 after:z-0 after:flex after:items-center after:border-t"
>
<span class="bg-background text-muted-foreground relative z-10 px-2">
Or continue with
</span>
</div>
<Button class="mt-2 w-full" onclick={() => handleOauth()} variant="outline"
>Login with {result.oauth_name}</Button
>
{/if}
{/await}
<div class="mt-4 text-center text-sm">
<Button href="{base}/login/signup/" variant="link">Don't have an account? Sign up</Button>
</div>
</Card.Content>
</div>
<Button class="mt-2 w-full" onclick={() => handleOauth()} variant="outline"
>Login with {result.oauth_name}</Button
>
{/if}
{/await}
<div class="mt-4 text-center text-sm">
<Button href="{base}/login/signup/" variant="link">Don't have an account? Sign up</Button>
</div>
</Card.Content>
</Card.Root>

View File

@@ -1,11 +1,10 @@
<script lang="ts">
import type { MetaDataProviderSearchResult } from '$lib/types';
import AddMediaCard from '$lib/components/add-media-card.svelte';
import { Skeleton } from '$lib/components/ui/skeleton';
import { Button } from '$lib/components/ui/button';
import { ChevronRight } from 'lucide-svelte';
import { base } from '$app/paths';
import type {components} from "$lib/api/api";
import type { components } from '$lib/api/api';
let {
media,

View File

@@ -1,118 +1,115 @@
<script lang="ts">
import {env} from '$env/dynamic/public';
import {Button, buttonVariants} from '$lib/components/ui/button/index.js';
import * as Dialog from '$lib/components/ui/dialog/index.js';
import {Label} from '$lib/components/ui/label';
import * as Select from '$lib/components/ui/select/index.js';
import LoaderCircle from '@lucide/svelte/icons/loader-circle';
import type {PublicMovie, Quality} from '$lib/types.js';
import {getFullyQualifiedMediaName, getTorrentQualityString} from '$lib/utils.js';
import {toast} from 'svelte-sonner';
import client from "$lib/api";
import { Button, buttonVariants } from '$lib/components/ui/button/index.js';
import * as Dialog from '$lib/components/ui/dialog/index.js';
import { Label } from '$lib/components/ui/label';
import * as Select from '$lib/components/ui/select/index.js';
import LoaderCircle from '@lucide/svelte/icons/loader-circle';
import type { PublicMovie, Quality } from '$lib/types.js';
import { getFullyQualifiedMediaName, getTorrentQualityString } from '$lib/utils.js';
import { toast } from 'svelte-sonner';
import client from '$lib/api';
const apiUrl = env.PUBLIC_API_URL;
let {movie}: { movie: PublicMovie } = $props();
let dialogOpen = $state(false);
let minQuality = $state<string | undefined>(undefined);
let wantedQuality = $state<string | undefined>(undefined);
let isSubmittingRequest = $state(false);
let submitRequestError = $state<string | null>(null);
let { movie }: { movie: PublicMovie } = $props();
let dialogOpen = $state(false);
let minQuality = $state<string | undefined>(undefined);
let wantedQuality = $state<string | undefined>(undefined);
let isSubmittingRequest = $state(false);
let submitRequestError = $state<string | null>(null);
const qualityValues: Quality[] = [1, 2, 3, 4];
let qualityOptions = $derived(
qualityValues.map((q) => ({value: q.toString(), label: getTorrentQualityString(q)}))
);
let isFormInvalid = $derived(
!minQuality || !wantedQuality || parseInt(wantedQuality) > parseInt(minQuality)
);
const qualityValues: Quality[] = [1, 2, 3, 4];
let qualityOptions = $derived(
qualityValues.map((q) => ({ value: q.toString(), label: getTorrentQualityString(q) }))
);
let isFormInvalid = $derived(
!minQuality || !wantedQuality || parseInt(wantedQuality) > parseInt(minQuality)
);
async function handleRequestMovie() {
isSubmittingRequest = true;
submitRequestError = null;
const {response} = await client.POST("/api/v1/movies/requests", {
body: {
movie_id: movie.id,
min_quality: parseInt(minQuality!),
wanted_quality: parseInt(wantedQuality!)
}
}
)
isSubmittingRequest = false;
async function handleRequestMovie() {
isSubmittingRequest = true;
submitRequestError = null;
const { response } = await client.POST('/api/v1/movies/requests', {
body: {
movie_id: movie.id,
min_quality: parseInt(minQuality!),
wanted_quality: parseInt(wantedQuality!)
}
});
isSubmittingRequest = false;
if (response.ok) {
dialogOpen = false;
minQuality = undefined;
wantedQuality = undefined;
toast.success('Movie request submitted successfully!');
} else {
toast.error("Failed to submit request");
}
}
if (response.ok) {
dialogOpen = false;
minQuality = undefined;
wantedQuality = undefined;
toast.success('Movie request submitted successfully!');
} else {
toast.error('Failed to submit request');
}
}
</script>
<Dialog.Root bind:open={dialogOpen}>
<Dialog.Trigger
class={buttonVariants({ variant: 'default' })}
onclick={() => {
<Dialog.Trigger
class={buttonVariants({ variant: 'default' })}
onclick={() => {
dialogOpen = true;
}}
>
Request Movie
</Dialog.Trigger>
<Dialog.Content class="max-h-[90vh] w-fit min-w-[clamp(300px,50vw,600px)] overflow-y-auto">
<Dialog.Header>
<Dialog.Title>Request {getFullyQualifiedMediaName(movie)}</Dialog.Title>
<Dialog.Description>Select desired qualities to submit a request.</Dialog.Description>
</Dialog.Header>
<div class="grid gap-4 py-4">
<!-- Min Quality Select -->
<div class="grid grid-cols-[1fr_3fr] items-center gap-4 md:grid-cols-[100px_1fr]">
<Label class="text-right" for="min-quality">Min Quality</Label>
<Select.Root bind:value={minQuality} type="single">
<Select.Trigger class="w-full" id="min-quality">
{minQuality ? getTorrentQualityString(parseInt(minQuality)) : 'Select Minimum Quality'}
</Select.Trigger>
<Select.Content>
{#each qualityOptions as option (option.value)}
<Select.Item value={option.value}>{option.label}</Select.Item>
{/each}
</Select.Content>
</Select.Root>
</div>
>
Request Movie
</Dialog.Trigger>
<Dialog.Content class="max-h-[90vh] w-fit min-w-[clamp(300px,50vw,600px)] overflow-y-auto">
<Dialog.Header>
<Dialog.Title>Request {getFullyQualifiedMediaName(movie)}</Dialog.Title>
<Dialog.Description>Select desired qualities to submit a request.</Dialog.Description>
</Dialog.Header>
<div class="grid gap-4 py-4">
<!-- Min Quality Select -->
<div class="grid grid-cols-[1fr_3fr] items-center gap-4 md:grid-cols-[100px_1fr]">
<Label class="text-right" for="min-quality">Min Quality</Label>
<Select.Root bind:value={minQuality} type="single">
<Select.Trigger class="w-full" id="min-quality">
{minQuality ? getTorrentQualityString(parseInt(minQuality)) : 'Select Minimum Quality'}
</Select.Trigger>
<Select.Content>
{#each qualityOptions as option (option.value)}
<Select.Item value={option.value}>{option.label}</Select.Item>
{/each}
</Select.Content>
</Select.Root>
</div>
<!-- Wanted Quality Select -->
<div class="grid grid-cols-[1fr_3fr] items-center gap-4 md:grid-cols-[100px_1fr]">
<Label class="text-right" for="wanted-quality">Wanted Quality</Label>
<Select.Root bind:value={wantedQuality} type="single">
<Select.Trigger class="w-full" id="wanted-quality">
{wantedQuality
? getTorrentQualityString(parseInt(wantedQuality))
: 'Select Wanted Quality'}
</Select.Trigger>
<Select.Content>
{#each qualityOptions as option (option.value)}
<Select.Item value={option.value}>{option.label}</Select.Item>
{/each}
</Select.Content>
</Select.Root>
</div>
<!-- Wanted Quality Select -->
<div class="grid grid-cols-[1fr_3fr] items-center gap-4 md:grid-cols-[100px_1fr]">
<Label class="text-right" for="wanted-quality">Wanted Quality</Label>
<Select.Root bind:value={wantedQuality} type="single">
<Select.Trigger class="w-full" id="wanted-quality">
{wantedQuality
? getTorrentQualityString(parseInt(wantedQuality))
: 'Select Wanted Quality'}
</Select.Trigger>
<Select.Content>
{#each qualityOptions as option (option.value)}
<Select.Item value={option.value}>{option.label}</Select.Item>
{/each}
</Select.Content>
</Select.Root>
</div>
{#if submitRequestError}
<p class="col-span-full text-center text-sm text-red-500">{submitRequestError}</p>
{/if}
</div>
<Dialog.Footer>
<Button disabled={isSubmittingRequest} onclick={() => (dialogOpen = false)} variant="outline"
>Cancel
</Button>
<Button disabled={isFormInvalid || isSubmittingRequest} onclick={handleRequestMovie}>
{#if isSubmittingRequest}
<LoaderCircle class="mr-2 h-4 w-4 animate-spin"/>
Submitting...
{:else}
Submit Request
{/if}
</Button>
</Dialog.Footer>
</Dialog.Content>
{#if submitRequestError}
<p class="col-span-full text-center text-sm text-red-500">{submitRequestError}</p>
{/if}
</div>
<Dialog.Footer>
<Button disabled={isSubmittingRequest} onclick={() => (dialogOpen = false)} variant="outline"
>Cancel
</Button>
<Button disabled={isFormInvalid || isSubmittingRequest} onclick={handleRequestMovie}>
{#if isSubmittingRequest}
<LoaderCircle class="mr-2 h-4 w-4 animate-spin" />
Submitting...
{:else}
Submit Request
{/if}
</Button>
</Dialog.Footer>
</Dialog.Content>
</Dialog.Root>

View File

@@ -1,16 +1,14 @@
<script lang="ts">
import { env } from '$env/dynamic/public';
import { Button, buttonVariants } from '$lib/components/ui/button/index.js';
import * as Dialog from '$lib/components/ui/dialog/index.js';
import { Label } from '$lib/components/ui/label';
import * as Select from '$lib/components/ui/select/index.js';
import LoaderCircle from '@lucide/svelte/icons/loader-circle';
import type { CreateSeasonRequest, PublicShow, Quality } from '$lib/types.js';
import type { PublicShow, Quality } from '$lib/types.js';
import { getFullyQualifiedMediaName, getTorrentQualityString } from '$lib/utils.js';
import { toast } from 'svelte-sonner';
import client from "$lib/api";
import client from '$lib/api';
const apiUrl = env.PUBLIC_API_URL;
let { show }: { show: PublicShow } = $props();
let dialogOpen = $state(false);
@@ -37,7 +35,7 @@
submitRequestError = null;
for (const id of selectedSeasonsIds) {
const { response, error } = await client.POST("/api/v1/tv/seasons/requests", {
const { response, error } = await client.POST('/api/v1/tv/seasons/requests', {
body: {
season_id: id,
min_quality: parseInt(minQuality!) as Quality,
@@ -46,7 +44,7 @@
});
if (!response.ok) {
toast.error("Failed to submit request: " + error);
toast.error('Failed to submit request: ' + error);
submitRequestError = `Failed to submit request for season ID ${id}: ${error}`;
}
}

View File

@@ -1,201 +1,202 @@
<script lang="ts">
import {getFullyQualifiedMediaName, getTorrentQualityString} from '$lib/utils.js';
import type {MovieRequest, SeasonRequest, User} from '$lib/types.js';
import CheckmarkX from '$lib/components/checkmark-x.svelte';
import * as Table from '$lib/components/ui/table/index.js';
import {getContext} from 'svelte';
import {Button} from '$lib/components/ui/button/index.js';
import {env} from '$env/dynamic/public';
import {toast} from 'svelte-sonner';
import {goto} from '$app/navigation';
import {base} from '$app/paths';
import client from "$lib/api";
import { getFullyQualifiedMediaName, getTorrentQualityString } from '$lib/utils.js';
import type { MovieRequest, SeasonRequest, User } from '$lib/types.js';
import CheckmarkX from '$lib/components/checkmark-x.svelte';
import * as Table from '$lib/components/ui/table/index.js';
import { getContext } from 'svelte';
import { Button } from '$lib/components/ui/button/index.js';
import { toast } from 'svelte-sonner';
import { goto } from '$app/navigation';
import { base } from '$app/paths';
import client from '$lib/api';
const apiUrl = env.PUBLIC_API_URL;
let {
requests,
filter = () => true,
isShow = true
}: {
requests: (SeasonRequest | MovieRequest)[];
filter?: (request: SeasonRequest | MovieRequest) => boolean;
isShow: boolean;
} = $props();
const user: () => User = getContext('user');
let {
requests,
filter = () => true,
isShow = true
}: {
requests: (SeasonRequest | MovieRequest)[];
filter?: (request: SeasonRequest | MovieRequest) => boolean;
isShow: boolean;
} = $props();
const user: () => User = getContext('user');
async function approveRequest(requestId: string, currentAuthorizedStatus: boolean) {
let response;
if (!isShow) {
const data = await client.PATCH("/api/v1/tv/seasons/requests/{season_request_id}", {
params: {
path: {
season_request_id: requestId,
},
query: {
authorized_status: !currentAuthorizedStatus
}
}
});
response = data.response
} else {
const data = await client.PATCH("/api/v1/movies/requests/{movie_request_id}", {
params: {
path: {
movie_request_id: requestId,
},
query: {
authorized_status: !currentAuthorizedStatus,
}
}
});
response = data.response
}
if (response.ok) {
const requestIndex = requests.findIndex((r) => r.id === requestId);
if (requestIndex !== -1) {
let newAuthorizedStatus = !currentAuthorizedStatus;
requests[requestIndex]!.authorized = newAuthorizedStatus;
requests[requestIndex]!.authorized_by = newAuthorizedStatus ? user() : undefined;
}
toast.success(
`Request ${!currentAuthorizedStatus ? 'approved' : 'unapproved'} successfully.`
);
} else {
const errorText = await response.text();
console.error(`Failed to update request status ${response.statusText}`, errorText);
toast.error(`Failed to update request status: ${response.statusText}`);
}
async function approveRequest(requestId: string, currentAuthorizedStatus: boolean) {
let response;
if (!isShow) {
const data = await client.PATCH('/api/v1/tv/seasons/requests/{season_request_id}', {
params: {
path: {
season_request_id: requestId
},
query: {
authorized_status: !currentAuthorizedStatus
}
}
});
response = data.response;
} else {
const data = await client.PATCH('/api/v1/movies/requests/{movie_request_id}', {
params: {
path: {
movie_request_id: requestId
},
query: {
authorized_status: !currentAuthorizedStatus
}
}
});
response = data.response;
}
if (response.ok) {
const requestIndex = requests.findIndex((r) => r.id === requestId);
if (requestIndex !== -1) {
let newAuthorizedStatus = !currentAuthorizedStatus;
requests[requestIndex]!.authorized = newAuthorizedStatus;
requests[requestIndex]!.authorized_by = newAuthorizedStatus ? user() : undefined;
}
toast.success(
`Request ${!currentAuthorizedStatus ? 'approved' : 'unapproved'} successfully.`
);
} else {
const errorText = await response.text();
console.error(`Failed to update request status ${response.statusText}`, errorText);
toast.error(`Failed to update request status: ${response.statusText}`);
}
}
}
async function deleteRequest(requestId: string) {
if (!window.confirm('Are you sure you want to delete this season request? This action cannot be undone.')) {
return;
}
let response;
if (isShow) {
const data = await client.DELETE("/api/v1/tv/seasons/requests/{request_id}", {
params: {
path: {
request_id: requestId,
}
}
})
response = data.response
} else {
const data = await client.DELETE("/api/v1/movies/requests/{movie_request_id}", {
params: {
path: {
movie_request_id: requestId
}
}
});
response = data.response
}
if (response.ok) {
// remove the request from the list
const index = requests.findIndex((r) => r.id === requestId);
if (index > -1) {
requests.splice(index, 1);
}
toast.success('Request deleted successfully');
} else {
console.error(`Failed to delete request ${response.statusText}`, await response.text());
toast.error('Failed to delete request');
}
}
async function deleteRequest(requestId: string) {
if (
!window.confirm(
'Are you sure you want to delete this season request? This action cannot be undone.'
)
) {
return;
}
let response;
if (isShow) {
const data = await client.DELETE('/api/v1/tv/seasons/requests/{request_id}', {
params: {
path: {
request_id: requestId
}
}
});
response = data.response;
} else {
const data = await client.DELETE('/api/v1/movies/requests/{movie_request_id}', {
params: {
path: {
movie_request_id: requestId
}
}
});
response = data.response;
}
if (response.ok) {
// remove the request from the list
const index = requests.findIndex((r) => r.id === requestId);
if (index > -1) {
requests.splice(index, 1);
}
toast.success('Request deleted successfully');
} else {
console.error(`Failed to delete request ${response.statusText}`, await response.text());
toast.error('Failed to delete request');
}
}
</script>
<Table.Root>
<Table.Caption>A list of all requests.</Table.Caption>
<Table.Header>
<Table.Row>
<Table.Head>{isShow ? 'Show' : 'Movie'}</Table.Head>
{#if isShow}
<Table.Head>Season</Table.Head>
{/if}
<Table.Head>Minimum Quality</Table.Head>
<Table.Head>Wanted Quality</Table.Head>
<Table.Head>Requested by</Table.Head>
<Table.Head>Approved</Table.Head>
<Table.Head>Approved by</Table.Head>
<Table.Head>Actions</Table.Head>
</Table.Row>
</Table.Header>
<Table.Body>
{#each requests as request (request.id)}
{#if filter(request)}
<Table.Row>
<Table.Cell>
{#if isShow}
{getFullyQualifiedMediaName((request as SeasonRequest).show)}
{:else}
{getFullyQualifiedMediaName((request as MovieRequest).movie)}
{/if}
</Table.Cell>
{#if isShow}
<Table.Cell>
{(request as SeasonRequest).season.number}
</Table.Cell>
{/if}
<Table.Cell>
{getTorrentQualityString(request.min_quality)}
</Table.Cell>
<Table.Cell>
{getTorrentQualityString(request.wanted_quality)}
</Table.Cell>
<Table.Cell>
{request.requested_by?.email ?? 'N/A'}
</Table.Cell>
<Table.Cell>
<CheckmarkX state={request.authorized}/>
</Table.Cell>
<Table.Cell>
{request.authorized_by?.email ?? 'N/A'}
</Table.Cell>
<!-- TODO: ADD DIALOGUE TO MODIFY REQUEST -->
<Table.Cell class="flex max-w-[150px] flex-col gap-1">
{#if user().is_superuser}
<Button
class=""
size="sm"
onclick={() => approveRequest(request.id, request.authorized)}
>
{request.authorized ? 'Unapprove' : 'Approve'}
</Button>
{#if isShow}
<Button
class=""
size="sm"
variant="outline"
onclick={() => goto(base + '/dashboard/tv/' + (request as SeasonRequest).show.id)}
>
Download manually
</Button>
{:else}
<Button
class=""
size="sm"
variant="outline"
onclick={() =>
<Table.Caption>A list of all requests.</Table.Caption>
<Table.Header>
<Table.Row>
<Table.Head>{isShow ? 'Show' : 'Movie'}</Table.Head>
{#if isShow}
<Table.Head>Season</Table.Head>
{/if}
<Table.Head>Minimum Quality</Table.Head>
<Table.Head>Wanted Quality</Table.Head>
<Table.Head>Requested by</Table.Head>
<Table.Head>Approved</Table.Head>
<Table.Head>Approved by</Table.Head>
<Table.Head>Actions</Table.Head>
</Table.Row>
</Table.Header>
<Table.Body>
{#each requests as request (request.id)}
{#if filter(request)}
<Table.Row>
<Table.Cell>
{#if isShow}
{getFullyQualifiedMediaName((request as SeasonRequest).show)}
{:else}
{getFullyQualifiedMediaName((request as MovieRequest).movie)}
{/if}
</Table.Cell>
{#if isShow}
<Table.Cell>
{(request as SeasonRequest).season.number}
</Table.Cell>
{/if}
<Table.Cell>
{getTorrentQualityString(request.min_quality)}
</Table.Cell>
<Table.Cell>
{getTorrentQualityString(request.wanted_quality)}
</Table.Cell>
<Table.Cell>
{request.requested_by?.email ?? 'N/A'}
</Table.Cell>
<Table.Cell>
<CheckmarkX state={request.authorized} />
</Table.Cell>
<Table.Cell>
{request.authorized_by?.email ?? 'N/A'}
</Table.Cell>
<!-- TODO: ADD DIALOGUE TO MODIFY REQUEST -->
<Table.Cell class="flex max-w-[150px] flex-col gap-1">
{#if user().is_superuser}
<Button
class=""
size="sm"
onclick={() => approveRequest(request.id, request.authorized)}
>
{request.authorized ? 'Unapprove' : 'Approve'}
</Button>
{#if isShow}
<Button
class=""
size="sm"
variant="outline"
onclick={() => goto(base + '/dashboard/tv/' + (request as SeasonRequest).show.id)}
>
Download manually
</Button>
{:else}
<Button
class=""
size="sm"
variant="outline"
onclick={() =>
goto(base + '/dashboard/movies/' + (request as MovieRequest).movie.id)}
>
Download manually
</Button>
{/if}
{/if}
{#if user().is_superuser || user().id === request.requested_by?.id}
<Button variant="destructive" size="sm" onclick={() => deleteRequest(request.id)}
>Delete
</Button>
{/if}
</Table.Cell>
</Table.Row>
{/if}
{:else}
<Table.Row>
<Table.Cell colspan={8} class="text-center">There are currently no requests.</Table.Cell>
</Table.Row>
{/each}
</Table.Body>
>
Download manually
</Button>
{/if}
{/if}
{#if user().is_superuser || user().id === request.requested_by?.id}
<Button variant="destructive" size="sm" onclick={() => deleteRequest(request.id)}
>Delete
</Button>
{/if}
</Table.Cell>
</Table.Row>
{/if}
{:else}
<Table.Row>
<Table.Cell colspan={8} class="text-center">There are currently no requests.</Table.Cell>
</Table.Row>
{/each}
</Table.Body>
</Table.Root>

View File

@@ -1,152 +1,148 @@
<script lang="ts">
import {Button} from '$lib/components/ui/button/index.js';
import * as Card from '$lib/components/ui/card/index.js';
import {Input} from '$lib/components/ui/input/index.js';
import {Label} from '$lib/components/ui/label/index.js';
import {env} from '$env/dynamic/public';
import {toast} from 'svelte-sonner';
import * as Alert from '$lib/components/ui/alert/index.js';
import AlertCircleIcon from '@lucide/svelte/icons/alert-circle';
import LoadingBar from '$lib/components/loading-bar.svelte';
import CheckCircle2Icon from '@lucide/svelte/icons/check-circle-2';
import {base} from '$app/paths';
import client from "$lib/api";
import { Button } from '$lib/components/ui/button/index.js';
import * as Card from '$lib/components/ui/card/index.js';
import { Input } from '$lib/components/ui/input/index.js';
import { Label } from '$lib/components/ui/label/index.js';
import { toast } from 'svelte-sonner';
import * as Alert from '$lib/components/ui/alert/index.js';
import AlertCircleIcon from '@lucide/svelte/icons/alert-circle';
import LoadingBar from '$lib/components/loading-bar.svelte';
import CheckCircle2Icon from '@lucide/svelte/icons/check-circle-2';
import { base } from '$app/paths';
import client from '$lib/api';
const apiUrl = env.PUBLIC_API_URL;
let email = $state('');
let password = $state('');
let errorMessage = $state('');
let successMessage = $state('');
let isLoading = $state(false);
let confirmPassword = $state('');
let {
oauthProvider
}: {
oauthProvider: {
oauth_name: string;
};
} = $props();
let email = $state('');
let password = $state('');
let errorMessage = $state('');
let successMessage = $state('');
let isLoading = $state(false);
let confirmPassword = $state('');
let {
oauthProvider
}: {
oauthProvider: {
oauth_name: string;
};
} = $props();
async function handleSignup(event: Event) {
event.preventDefault();
async function handleSignup(event: Event) {
event.preventDefault();
isLoading = true;
errorMessage = '';
successMessage = '';
const { response } = await client.POST('/api/v1/auth/register', {
body: {
email: email,
password: password
}
});
isLoading = false;
isLoading = true;
errorMessage = '';
successMessage = '';
const {response} = await client.POST("/api/v1/auth/register", {
body: {
email: email,
password: password
}
});
isLoading = false;
if (response.ok) {
successMessage = 'Registration successful! Please login.';
toast.success(successMessage);
} else {
toast.error('Registration failed');
}
}
if (response.ok) {
successMessage = 'Registration successful! Please login.';
toast.success(successMessage);
} else {
toast.error("Registration failed");
}
}
async function handleOauth() {
const {response, data, error} = await client.GET("/api/v1/auth/cookie/OpenID/authorize", {
params: {
query: {
scopes: 'email'
}
}
});
if (response.ok) {
window.location = data.authorization_url;
} else {
toast.error(error);
}
}
async function handleOauth() {
const { response, data, error } = await client.GET('/api/v1/auth/cookie/OpenID/authorize', {
params: {
query: {
scopes: 'email'
}
}
});
if (response.ok) {
window.location = data.authorization_url;
} else {
toast.error(error);
}
}
</script>
<Card.Root class="mx-auto max-w-sm">
<Card.Header>
<Card.Title class="text-xl">Sign Up</Card.Title>
<Card.Description>Enter your information to create an account</Card.Description>
</Card.Header>
<Card.Content>
<form class="grid gap-4" onsubmit={handleSignup}>
<div class="grid gap-2">
<Label for="email">Email</Label>
<Input
autocomplete="email"
bind:value={email}
id="email"
placeholder="m@example.com"
required
type="email"
/>
</div>
<div class="grid gap-2">
<Label for="password">Password</Label>
<Input
autocomplete="new-password"
bind:value={password}
id="password"
required
type="password"
/>
</div>
<div class="grid gap-2">
<Label for="password">Confirm Password</Label>
<Input
autocomplete="new-password"
bind:value={confirmPassword}
id="confirm-password"
required
type="password"
/>
</div>
{#if errorMessage}
<Alert.Root variant="destructive">
<AlertCircleIcon class="size-4"/>
<Alert.Title>Error</Alert.Title>
<Alert.Description>{errorMessage}</Alert.Description>
</Alert.Root>
{/if}
{#if successMessage}
<Alert.Root variant="default">
<CheckCircle2Icon class="size-4"/>
<Alert.Title>Success</Alert.Title>
<Alert.Description>{successMessage}</Alert.Description>
</Alert.Root>
{/if}
{#if isLoading}
<LoadingBar/>
{/if}
<Button
class="w-full"
disabled={isLoading || password !== confirmPassword || password === ''}
type="submit">Create an account
</Button
>
</form>
{#await oauthProvider}
<LoadingBar/>
{:then result}
{#if result.oauth_name != null}
<div
class="after:border-border relative mt-2 text-center text-sm after:absolute after:inset-0 after:top-1/2 after:z-0 after:flex after:items-center after:border-t"
>
<Card.Header>
<Card.Title class="text-xl">Sign Up</Card.Title>
<Card.Description>Enter your information to create an account</Card.Description>
</Card.Header>
<Card.Content>
<form class="grid gap-4" onsubmit={handleSignup}>
<div class="grid gap-2">
<Label for="email">Email</Label>
<Input
autocomplete="email"
bind:value={email}
id="email"
placeholder="m@example.com"
required
type="email"
/>
</div>
<div class="grid gap-2">
<Label for="password">Password</Label>
<Input
autocomplete="new-password"
bind:value={password}
id="password"
required
type="password"
/>
</div>
<div class="grid gap-2">
<Label for="password">Confirm Password</Label>
<Input
autocomplete="new-password"
bind:value={confirmPassword}
id="confirm-password"
required
type="password"
/>
</div>
{#if errorMessage}
<Alert.Root variant="destructive">
<AlertCircleIcon class="size-4" />
<Alert.Title>Error</Alert.Title>
<Alert.Description>{errorMessage}</Alert.Description>
</Alert.Root>
{/if}
{#if successMessage}
<Alert.Root variant="default">
<CheckCircle2Icon class="size-4" />
<Alert.Title>Success</Alert.Title>
<Alert.Description>{successMessage}</Alert.Description>
</Alert.Root>
{/if}
{#if isLoading}
<LoadingBar />
{/if}
<Button
class="w-full"
disabled={isLoading || password !== confirmPassword || password === ''}
type="submit"
>Create an account
</Button>
</form>
{#await oauthProvider}
<LoadingBar />
{:then result}
{#if result.oauth_name != null}
<div
class="after:border-border relative mt-2 text-center text-sm after:absolute after:inset-0 after:top-1/2 after:z-0 after:flex after:items-center after:border-t"
>
<span class="bg-background text-muted-foreground relative z-10 px-2">
Or continue with
</span>
</div>
<Button class="mt-2 w-full" onclick={() => handleOauth()} variant="outline"
>Login with {result.oauth_name}</Button
>
{/if}
{/await}
<div class="mt-4 text-center text-sm">
<Button href="{base}/login/" variant="link">Already have an account? Login</Button>
</div>
</Card.Content>
</div>
<Button class="mt-2 w-full" onclick={() => handleOauth()} variant="outline"
>Login with {result.oauth_name}</Button
>
{/if}
{/await}
<div class="mt-4 text-center text-sm">
<Button href="{base}/login/" variant="link">Already have an account? Login</Button>
</div>
</Card.Content>
</Card.Root>

View File

@@ -3,7 +3,6 @@
import CheckmarkX from '$lib/components/checkmark-x.svelte';
import * as Table from '$lib/components/ui/table/index.js';
import { Button } from '$lib/components/ui/button/index.js';
import { env } from '$env/dynamic/public';
import { toast } from 'svelte-sonner';
import * as Dialog from '$lib/components/ui/dialog/index.js';
import { Label } from '$lib/components/ui/label/index.js';
@@ -11,7 +10,6 @@
import { Input } from '$lib/components/ui/input/index.js';
import { invalidateAll } from '$app/navigation';
import client from '$lib/api';
const apiUrl = env.PUBLIC_API_URL;
let { users }: { users: User[] } = $props();
let sortedUsers = $derived(users.sort((a, b) => a.email.localeCompare(b.email)));
let selectedUser: User | null = $state(null);
@@ -21,7 +19,7 @@
async function saveUser() {
if (!selectedUser) return;
const {data} = await client.PATCH("/api/v1/users/{id}", {
const { error } = await client.PATCH('/api/v1/users/{id}', {
params: {
query: {
id: selectedUser.id
@@ -34,13 +32,18 @@
...(newPassword !== '' && { password: newPassword }),
...(newEmail !== '' && { email: newEmail })
}
})
toast.success(`User ${selectedUser.email} updated successfully.`);
dialogOpen = false;
selectedUser = null;
newPassword = '';
newEmail = '';
await invalidateAll();
});
if (error) {
toast.error(`Failed to update user ${selectedUser.email}: ${error}`);
} else {
toast.success(`User ${selectedUser.email} updated successfully.`);
dialogOpen = false;
selectedUser = null;
newPassword = '';
newEmail = '';
await invalidateAll();
}
}
</script>

View File

@@ -1,75 +1,72 @@
<script lang="ts">
import {Button} from '$lib/components/ui/button/index.js';
import {env} from '$env/dynamic/public';
import {toast} from 'svelte-sonner';
import * as Dialog from '$lib/components/ui/dialog/index.js';
import {Label} from '$lib/components/ui/label/index.js';
import {Input} from '$lib/components/ui/input/index.js';
import client from "$lib/api";
import { Button } from '$lib/components/ui/button/index.js';
import { toast } from 'svelte-sonner';
import * as Dialog from '$lib/components/ui/dialog/index.js';
import { Label } from '$lib/components/ui/label/index.js';
import { Input } from '$lib/components/ui/input/index.js';
import client from '$lib/api';
const apiUrl = env.PUBLIC_API_URL;
let newPassword: string = $state('');
let newEmail: string = $state('');
let dialogOpen = $state(false);
let newPassword: string = $state('');
let newEmail: string = $state('');
let dialogOpen = $state(false);
async function saveUser() {
const {error} = await client.PATCH("/api/v1/users/me", {
body: {
...(newPassword !== '' && {password: newPassword}),
...(newEmail !== '' && {email: newEmail})
}
});
if (error) {
toast.error(`Failed to update user`);
} else {
toast.success(`Updated details successfully.`);
dialogOpen = false;
}
newPassword = '';
newEmail = '';
}
async function saveUser() {
const { error } = await client.PATCH('/api/v1/users/me', {
body: {
...(newPassword !== '' && { password: newPassword }),
...(newEmail !== '' && { email: newEmail })
}
});
if (error) {
toast.error(`Failed to update user`);
} else {
toast.success(`Updated details successfully.`);
dialogOpen = false;
}
newPassword = '';
newEmail = '';
}
</script>
<Dialog.Root bind:open={dialogOpen}>
<Dialog.Trigger>
<Button class="w-full" onclick={() => (dialogOpen = true)} variant="outline">
Edit my details
</Button>
</Dialog.Trigger>
<Dialog.Content class="w-full max-w-[600px] rounded-lg p-6 shadow-lg">
<Dialog.Header>
<Dialog.Title class="mb-1 text-xl font-semibold">Edit User Details</Dialog.Title>
<Dialog.Description class="mb-4 text-sm">
Change your email or password. Leave fields empty to not change them.
</Dialog.Description>
</Dialog.Header>
<div class="space-y-6">
<!-- Email -->
<div>
<Label class="mb-1 block text-sm font-medium" for="email">Email</Label>
<Input
bind:value={newEmail}
class="w-full"
id="email"
placeholder="Keep empty to not change the email"
type="email"
/>
</div>
<!-- Password -->
<div>
<Label class="mb-1 block text-sm font-medium" for="password">Password</Label>
<Input
bind:value={newPassword}
class="w-full"
id="password"
placeholder="Keep empty to not change the password"
type="password"
/>
</div>
</div>
<div class="mt-8 flex justify-end gap-2">
<Button onclick={() => saveUser()} variant="destructive">Save</Button>
</div>
</Dialog.Content>
<Dialog.Trigger>
<Button class="w-full" onclick={() => (dialogOpen = true)} variant="outline">
Edit my details
</Button>
</Dialog.Trigger>
<Dialog.Content class="w-full max-w-[600px] rounded-lg p-6 shadow-lg">
<Dialog.Header>
<Dialog.Title class="mb-1 text-xl font-semibold">Edit User Details</Dialog.Title>
<Dialog.Description class="mb-4 text-sm">
Change your email or password. Leave fields empty to not change them.
</Dialog.Description>
</Dialog.Header>
<div class="space-y-6">
<!-- Email -->
<div>
<Label class="mb-1 block text-sm font-medium" for="email">Email</Label>
<Input
bind:value={newEmail}
class="w-full"
id="email"
placeholder="Keep empty to not change the email"
type="email"
/>
</div>
<!-- Password -->
<div>
<Label class="mb-1 block text-sm font-medium" for="password">Password</Label>
<Input
bind:value={newPassword}
class="w-full"
id="password"
placeholder="Keep empty to not change the password"
type="password"
/>
</div>
</div>
<div class="mt-8 flex justify-end gap-2">
<Button onclick={() => saveUser()} variant="destructive">Save</Button>
</div>
</Dialog.Content>
</Dialog.Root>