mirror of
https://github.com/kmc7468/arkvault.git
synced 2026-02-04 16:16:55 +00:00
Compare commits
14 Commits
cf0f8fe0b9
...
v0.7.0
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3906ec4371 | ||
|
|
5d130204a6 | ||
|
|
4997b1f38c | ||
|
|
1d3704bfad | ||
|
|
ae1d34fc6b | ||
|
|
f10a0a2da3 | ||
|
|
0eb1d29259 | ||
|
|
90ac5ba4c3 | ||
|
|
dfffa004ac | ||
|
|
0cd55a413d | ||
|
|
361d966a59 | ||
|
|
aef43b8bfa | ||
|
|
7f128cccf6 | ||
|
|
a198e5f6dc |
@@ -22,7 +22,7 @@
|
|||||||
"@sveltejs/adapter-node": "^5.4.0",
|
"@sveltejs/adapter-node": "^5.4.0",
|
||||||
"@sveltejs/kit": "^2.49.2",
|
"@sveltejs/kit": "^2.49.2",
|
||||||
"@sveltejs/vite-plugin-svelte": "^6.2.1",
|
"@sveltejs/vite-plugin-svelte": "^6.2.1",
|
||||||
"@tanstack/svelte-virtual": "^3.13.15",
|
"@tanstack/svelte-virtual": "^3.13.16",
|
||||||
"@trpc/client": "^11.8.1",
|
"@trpc/client": "^11.8.1",
|
||||||
"@types/file-saver": "^2.0.7",
|
"@types/file-saver": "^2.0.7",
|
||||||
"@types/ms": "^0.7.34",
|
"@types/ms": "^0.7.34",
|
||||||
@@ -64,7 +64,7 @@
|
|||||||
"pg": "^8.16.3",
|
"pg": "^8.16.3",
|
||||||
"superjson": "^2.2.6",
|
"superjson": "^2.2.6",
|
||||||
"uuid": "^13.0.0",
|
"uuid": "^13.0.0",
|
||||||
"zod": "^4.3.4"
|
"zod": "^4.3.5"
|
||||||
},
|
},
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": "^22.0.0",
|
"node": "^22.0.0",
|
||||||
|
|||||||
28
pnpm-lock.yaml
generated
28
pnpm-lock.yaml
generated
@@ -36,8 +36,8 @@ importers:
|
|||||||
specifier: ^13.0.0
|
specifier: ^13.0.0
|
||||||
version: 13.0.0
|
version: 13.0.0
|
||||||
zod:
|
zod:
|
||||||
specifier: ^4.3.4
|
specifier: ^4.3.5
|
||||||
version: 4.3.4
|
version: 4.3.5
|
||||||
devDependencies:
|
devDependencies:
|
||||||
'@eslint/compat':
|
'@eslint/compat':
|
||||||
specifier: ^2.0.0
|
specifier: ^2.0.0
|
||||||
@@ -58,8 +58,8 @@ importers:
|
|||||||
specifier: ^6.2.1
|
specifier: ^6.2.1
|
||||||
version: 6.2.1(svelte@5.46.1)(vite@7.3.0(@types/node@25.0.3)(jiti@1.21.7)(yaml@2.8.0))
|
version: 6.2.1(svelte@5.46.1)(vite@7.3.0(@types/node@25.0.3)(jiti@1.21.7)(yaml@2.8.0))
|
||||||
'@tanstack/svelte-virtual':
|
'@tanstack/svelte-virtual':
|
||||||
specifier: ^3.13.15
|
specifier: ^3.13.16
|
||||||
version: 3.13.15(svelte@5.46.1)
|
version: 3.13.16(svelte@5.46.1)
|
||||||
'@trpc/client':
|
'@trpc/client':
|
||||||
specifier: ^11.8.1
|
specifier: ^11.8.1
|
||||||
version: 11.8.1(@trpc/server@11.8.1(typescript@5.9.3))(typescript@5.9.3)
|
version: 11.8.1(@trpc/server@11.8.1(typescript@5.9.3))(typescript@5.9.3)
|
||||||
@@ -620,13 +620,13 @@ packages:
|
|||||||
svelte: ^5.0.0
|
svelte: ^5.0.0
|
||||||
vite: ^6.3.0 || ^7.0.0
|
vite: ^6.3.0 || ^7.0.0
|
||||||
|
|
||||||
'@tanstack/svelte-virtual@3.13.15':
|
'@tanstack/svelte-virtual@3.13.16':
|
||||||
resolution: {integrity: sha512-3PPLI3hsyT70zSZhBkSIZXIarlN+GjFNKeKr2Wk1UR7EuEVtXgNlB/Zk0sYtaeJ4CvGvldQNakOvbdETnWAgeA==}
|
resolution: {integrity: sha512-LRDPRzAPTIiDjiCA9lhNlFnZRLj/XsNhzNRsT5JEA8hzcBmZw8avdYYVjydPAy0ObFJgG1zBAm9Dtvwqju36sg==}
|
||||||
peerDependencies:
|
peerDependencies:
|
||||||
svelte: ^3.48.0 || ^4.0.0 || ^5.0.0
|
svelte: ^3.48.0 || ^4.0.0 || ^5.0.0
|
||||||
|
|
||||||
'@tanstack/virtual-core@3.13.15':
|
'@tanstack/virtual-core@3.13.16':
|
||||||
resolution: {integrity: sha512-8cG3acM2cSIm3h8WxboHARAhQAJbYUhvmadvnN8uz8aziDwrbYb9KiARni+uY2qrLh49ycn+poGoxvtIAKhjog==}
|
resolution: {integrity: sha512-njazUC8mDkrxWmyZmn/3eXrDcP8Msb3chSr4q6a65RmwdSbMlMCdnOphv6/8mLO7O3Fuza5s4M4DclmvAO5w0w==}
|
||||||
|
|
||||||
'@trpc/client@11.8.1':
|
'@trpc/client@11.8.1':
|
||||||
resolution: {integrity: sha512-L/SJFGanr9xGABmuDoeXR4xAdHJmsXsiF9OuH+apecJ+8sUITzVT1EPeqp0ebqA6lBhEl5pPfg3rngVhi/h60Q==}
|
resolution: {integrity: sha512-L/SJFGanr9xGABmuDoeXR4xAdHJmsXsiF9OuH+apecJ+8sUITzVT1EPeqp0ebqA6lBhEl5pPfg3rngVhi/h60Q==}
|
||||||
@@ -2025,8 +2025,8 @@ packages:
|
|||||||
zimmerframe@1.1.4:
|
zimmerframe@1.1.4:
|
||||||
resolution: {integrity: sha512-B58NGBEoc8Y9MWWCQGl/gq9xBCe4IiKM0a2x7GZdQKOW5Exr8S1W24J6OgM1njK8xCRGvAJIL/MxXHf6SkmQKQ==}
|
resolution: {integrity: sha512-B58NGBEoc8Y9MWWCQGl/gq9xBCe4IiKM0a2x7GZdQKOW5Exr8S1W24J6OgM1njK8xCRGvAJIL/MxXHf6SkmQKQ==}
|
||||||
|
|
||||||
zod@4.3.4:
|
zod@4.3.5:
|
||||||
resolution: {integrity: sha512-Zw/uYiiyF6pUT1qmKbZziChgNPRu+ZRneAsMUDU6IwmXdWt5JwcUfy2bvLOCUtz5UniaN/Zx5aFttZYbYc7O/A==}
|
resolution: {integrity: sha512-k7Nwx6vuWx1IJ9Bjuf4Zt1PEllcwe7cls3VNzm4CQ1/hgtFUK2bRNG3rvnpPUhFjmqJKAKtjV576KnUkHocg/g==}
|
||||||
|
|
||||||
snapshots:
|
snapshots:
|
||||||
|
|
||||||
@@ -2389,12 +2389,12 @@ snapshots:
|
|||||||
transitivePeerDependencies:
|
transitivePeerDependencies:
|
||||||
- supports-color
|
- supports-color
|
||||||
|
|
||||||
'@tanstack/svelte-virtual@3.13.15(svelte@5.46.1)':
|
'@tanstack/svelte-virtual@3.13.16(svelte@5.46.1)':
|
||||||
dependencies:
|
dependencies:
|
||||||
'@tanstack/virtual-core': 3.13.15
|
'@tanstack/virtual-core': 3.13.16
|
||||||
svelte: 5.46.1
|
svelte: 5.46.1
|
||||||
|
|
||||||
'@tanstack/virtual-core@3.13.15': {}
|
'@tanstack/virtual-core@3.13.16': {}
|
||||||
|
|
||||||
'@trpc/client@11.8.1(@trpc/server@11.8.1(typescript@5.9.3))(typescript@5.9.3)':
|
'@trpc/client@11.8.1(@trpc/server@11.8.1(typescript@5.9.3))(typescript@5.9.3)':
|
||||||
dependencies:
|
dependencies:
|
||||||
@@ -3707,4 +3707,4 @@ snapshots:
|
|||||||
|
|
||||||
zimmerframe@1.1.4: {}
|
zimmerframe@1.1.4: {}
|
||||||
|
|
||||||
zod@4.3.4: {}
|
zod@4.3.5: {}
|
||||||
|
|||||||
@@ -54,7 +54,7 @@
|
|||||||
</div>
|
</div>
|
||||||
{/each}
|
{/each}
|
||||||
</div>
|
</div>
|
||||||
{#if placeholder && $virtualizer.getVirtualItems().length === 0}
|
{#if placeholder && count === 0}
|
||||||
{@render placeholder()}
|
{@render placeholder()}
|
||||||
{/if}
|
{/if}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import { browser } from "$app/environment";
|
import { getFileThumbnail } from "$lib/modules/file";
|
||||||
import type { SummarizedFileInfo } from "$lib/modules/filesystem";
|
import type { SummarizedFileInfo } from "$lib/modules/filesystem";
|
||||||
import { requestFileThumbnailDownload } from "$lib/services/file";
|
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
info: SummarizedFileInfo;
|
info: SummarizedFileInfo;
|
||||||
@@ -10,25 +9,16 @@
|
|||||||
|
|
||||||
let { info, onclick }: Props = $props();
|
let { info, onclick }: Props = $props();
|
||||||
|
|
||||||
let showThumbnail = $derived(
|
let thumbnail = $derived(getFileThumbnail(info));
|
||||||
browser && (info.contentType.startsWith("image/") || info.contentType.startsWith("video/")),
|
|
||||||
);
|
|
||||||
let thumbnailPromise = $derived(
|
|
||||||
showThumbnail ? requestFileThumbnailDownload(info.id, info.dataKey?.key) : null,
|
|
||||||
);
|
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<button
|
<button
|
||||||
onclick={onclick && (() => setTimeout(() => onclick(info), 100))}
|
onclick={onclick && (() => setTimeout(() => onclick(info), 100))}
|
||||||
class="aspect-square overflow-hidden rounded transition active:scale-95 active:brightness-90"
|
class="aspect-square overflow-hidden rounded transition active:scale-95 active:brightness-90"
|
||||||
>
|
>
|
||||||
{#await thumbnailPromise}
|
{#if $thumbnail}
|
||||||
<div class="h-full w-full bg-gray-100"></div>
|
<img src={$thumbnail} alt={info.name} class="h-full w-full object-cover" />
|
||||||
{:then thumbnail}
|
|
||||||
{#if thumbnail}
|
|
||||||
<img src={thumbnail} alt={info.name} class="h-full w-full object-cover" />
|
|
||||||
{:else}
|
{:else}
|
||||||
<div class="h-full w-full bg-gray-100"></div>
|
<div class="h-full w-full bg-gray-100"></div>
|
||||||
{/if}
|
{/if}
|
||||||
{/await}
|
|
||||||
</button>
|
</button>
|
||||||
|
|||||||
@@ -25,7 +25,7 @@
|
|||||||
|
|
||||||
let { categories, categoryMenuIcon, onCategoryClick, onCategoryMenuClick }: Props = $props();
|
let { categories, categoryMenuIcon, onCategoryClick, onCategoryMenuClick }: Props = $props();
|
||||||
|
|
||||||
let categoriesWithName = $derived(sortEntries($state.snapshot(categories)));
|
let categoriesWithName = $derived(sortEntries([...categories]));
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
{#if categoriesWithName.length > 0}
|
{#if categoriesWithName.length > 0}
|
||||||
|
|||||||
@@ -1,93 +0,0 @@
|
|||||||
<script lang="ts">
|
|
||||||
import { CheckBox, RowVirtualizer } from "$lib/components/atoms";
|
|
||||||
import { SubCategories, type SelectedCategory } from "$lib/components/molecules";
|
|
||||||
import { updateCategoryInfo } from "$lib/indexedDB";
|
|
||||||
import type { CategoryInfo } from "$lib/modules/filesystem";
|
|
||||||
import { sortEntries } from "$lib/utils";
|
|
||||||
import File from "./File.svelte";
|
|
||||||
import type { SelectedFile } from "./service";
|
|
||||||
|
|
||||||
import IconMoreVert from "~icons/material-symbols/more-vert";
|
|
||||||
|
|
||||||
interface Props {
|
|
||||||
info: CategoryInfo;
|
|
||||||
isFileRecursive: boolean | undefined;
|
|
||||||
onFileClick: (file: SelectedFile) => void;
|
|
||||||
onFileRemoveClick: (file: SelectedFile) => void;
|
|
||||||
onSubCategoryClick: (subCategory: SelectedCategory) => void;
|
|
||||||
onSubCategoryCreateClick: () => void;
|
|
||||||
onSubCategoryMenuClick: (subCategory: SelectedCategory) => void;
|
|
||||||
}
|
|
||||||
|
|
||||||
let {
|
|
||||||
info,
|
|
||||||
onFileClick,
|
|
||||||
onFileRemoveClick,
|
|
||||||
onSubCategoryClick,
|
|
||||||
onSubCategoryCreateClick,
|
|
||||||
onSubCategoryMenuClick,
|
|
||||||
isFileRecursive = $bindable(),
|
|
||||||
}: Props = $props();
|
|
||||||
|
|
||||||
let lastCategoryId = $state<CategoryInfo["id"] | undefined>();
|
|
||||||
let lastIsFileRecursive = $state<boolean | undefined>();
|
|
||||||
|
|
||||||
let files = $derived(
|
|
||||||
sortEntries(
|
|
||||||
info.files
|
|
||||||
?.map((file) => ({ name: file.name, details: file }))
|
|
||||||
.filter(({ details }) => isFileRecursive || !details.isRecursive) ?? [],
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
$effect(() => {
|
|
||||||
if (info.id === "root" || isFileRecursive === undefined) return;
|
|
||||||
if (lastCategoryId !== info.id) {
|
|
||||||
lastCategoryId = info.id;
|
|
||||||
lastIsFileRecursive = isFileRecursive;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (lastIsFileRecursive === isFileRecursive) return;
|
|
||||||
|
|
||||||
lastIsFileRecursive = isFileRecursive;
|
|
||||||
void updateCategoryInfo(info.id, { isFileRecursive });
|
|
||||||
});
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<div class="space-y-4">
|
|
||||||
<div class="space-y-4 bg-white p-4">
|
|
||||||
{#if info.id !== "root"}
|
|
||||||
<p class="text-lg font-bold text-gray-800">하위 카테고리</p>
|
|
||||||
{/if}
|
|
||||||
<SubCategories
|
|
||||||
{info}
|
|
||||||
{onSubCategoryClick}
|
|
||||||
{onSubCategoryCreateClick}
|
|
||||||
{onSubCategoryMenuClick}
|
|
||||||
subCategoryMenuIcon={IconMoreVert}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
{#if info.id !== "root"}
|
|
||||||
<div class="space-y-4 bg-white p-4">
|
|
||||||
<div class="flex items-center justify-between">
|
|
||||||
<p class="text-lg font-bold text-gray-800">파일</p>
|
|
||||||
<CheckBox bind:checked={isFileRecursive}>
|
|
||||||
<p class="font-medium">하위 카테고리의 파일</p>
|
|
||||||
</CheckBox>
|
|
||||||
</div>
|
|
||||||
<RowVirtualizer count={files.length} itemHeight={() => 48} itemGap={4}>
|
|
||||||
{#snippet item(index)}
|
|
||||||
{@const { details } = files[index]!}
|
|
||||||
<File
|
|
||||||
info={details}
|
|
||||||
onclick={onFileClick}
|
|
||||||
onRemoveClick={!details.isRecursive ? onFileRemoveClick : undefined}
|
|
||||||
/>
|
|
||||||
{/snippet}
|
|
||||||
{#snippet placeholder()}
|
|
||||||
<p class="text-center text-gray-500">이 카테고리에 추가된 파일이 없어요.</p>
|
|
||||||
{/snippet}
|
|
||||||
</RowVirtualizer>
|
|
||||||
</div>
|
|
||||||
{/if}
|
|
||||||
</div>
|
|
||||||
@@ -1,2 +0,0 @@
|
|||||||
export { default } from "./Category.svelte";
|
|
||||||
export * from "./service";
|
|
||||||
@@ -1,4 +0,0 @@
|
|||||||
export interface SelectedFile {
|
|
||||||
id: number;
|
|
||||||
name: string;
|
|
||||||
}
|
|
||||||
@@ -1,78 +0,0 @@
|
|||||||
<script lang="ts">
|
|
||||||
import { FileThumbnailButton, RowVirtualizer } from "$lib/components/atoms";
|
|
||||||
import type { SummarizedFileInfo } from "$lib/modules/filesystem";
|
|
||||||
import { formatDate, formatDateSortable, SortBy, sortEntries } from "$lib/utils";
|
|
||||||
|
|
||||||
interface Props {
|
|
||||||
files: SummarizedFileInfo[];
|
|
||||||
onFileClick?: (file: SummarizedFileInfo) => void;
|
|
||||||
}
|
|
||||||
|
|
||||||
let { files, onFileClick }: Props = $props();
|
|
||||||
|
|
||||||
type Row =
|
|
||||||
| { type: "header"; label: string }
|
|
||||||
| { type: "items"; files: SummarizedFileInfo[]; isLast: boolean };
|
|
||||||
|
|
||||||
let rows = $derived.by(() => {
|
|
||||||
const groups = Map.groupBy(
|
|
||||||
files.filter(
|
|
||||||
(file) => file.contentType.startsWith("image/") || file.contentType.startsWith("video/"),
|
|
||||||
),
|
|
||||||
(file) => formatDateSortable(file.createdAt ?? file.lastModifiedAt),
|
|
||||||
);
|
|
||||||
return Array.from(groups.entries())
|
|
||||||
.sort(([dateA], [dateB]) => dateB.localeCompare(dateA))
|
|
||||||
.flatMap(([, entries]) => {
|
|
||||||
const sortedEntries = [...entries];
|
|
||||||
sortEntries(sortedEntries, SortBy.DATE_DESC);
|
|
||||||
|
|
||||||
return [
|
|
||||||
{
|
|
||||||
type: "header",
|
|
||||||
label: formatDate(sortedEntries[0]!.createdAt ?? sortedEntries[0]!.lastModifiedAt),
|
|
||||||
},
|
|
||||||
...Array.from({ length: Math.ceil(sortedEntries.length / 4) }, (_, i) => {
|
|
||||||
const start = i * 4;
|
|
||||||
const end = start + 4;
|
|
||||||
return {
|
|
||||||
type: "items" as const,
|
|
||||||
files: sortedEntries.slice(start, end),
|
|
||||||
isLast: end >= sortedEntries.length,
|
|
||||||
};
|
|
||||||
}),
|
|
||||||
] satisfies Row[];
|
|
||||||
});
|
|
||||||
});
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<RowVirtualizer
|
|
||||||
count={rows.length}
|
|
||||||
itemHeight={(index) =>
|
|
||||||
rows[index]!.type === "header" ? 28 : 181 + (rows[index]!.isLast ? 16 : 4)}
|
|
||||||
class="flex flex-grow flex-col"
|
|
||||||
>
|
|
||||||
{#snippet item(index)}
|
|
||||||
{@const row = rows[index]!}
|
|
||||||
{#if row.type === "header"}
|
|
||||||
<p class="pb-2 text-sm font-medium">{row.label}</p>
|
|
||||||
{:else}
|
|
||||||
<div class={["grid grid-cols-4 gap-x-1", row.isLast ? "pb-4" : "pb-1"]}>
|
|
||||||
{#each row.files as file (file.id)}
|
|
||||||
<FileThumbnailButton info={file} onclick={onFileClick} />
|
|
||||||
{/each}
|
|
||||||
</div>
|
|
||||||
{/if}
|
|
||||||
{/snippet}
|
|
||||||
{#snippet placeholder()}
|
|
||||||
<div class="flex h-full flex-grow items-center justify-center">
|
|
||||||
<p class="text-gray-500">
|
|
||||||
{#if files.length === 0}
|
|
||||||
업로드된 파일이 없어요.
|
|
||||||
{:else}
|
|
||||||
사진 또는 동영상이 없어요.
|
|
||||||
{/if}
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
{/snippet}
|
|
||||||
</RowVirtualizer>
|
|
||||||
@@ -1,4 +1 @@
|
|||||||
export * from "./Category";
|
|
||||||
export { default as Category } from "./Category";
|
|
||||||
export { default as Gallery } from "./Gallery.svelte";
|
|
||||||
export * from "./modals";
|
export * from "./modals";
|
||||||
|
|||||||
@@ -13,15 +13,15 @@ interface FileInfo {
|
|||||||
contentType: string;
|
contentType: string;
|
||||||
createdAt?: Date;
|
createdAt?: Date;
|
||||||
lastModifiedAt: Date;
|
lastModifiedAt: Date;
|
||||||
categoryIds: number[];
|
categoryIds?: number[];
|
||||||
}
|
}
|
||||||
|
|
||||||
interface CategoryInfo {
|
interface CategoryInfo {
|
||||||
id: number;
|
id: number;
|
||||||
parentId: CategoryId;
|
parentId: CategoryId;
|
||||||
name: string;
|
name: string;
|
||||||
files: { id: number; isRecursive: boolean }[];
|
files?: { id: number; isRecursive: boolean }[];
|
||||||
isFileRecursive: boolean;
|
isFileRecursive?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
const filesystem = new Dexie("filesystem") as Dexie & {
|
const filesystem = new Dexie("filesystem") as Dexie & {
|
||||||
@@ -55,7 +55,7 @@ export const getDirectoryInfo = async (id: number) => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
export const storeDirectoryInfo = async (directoryInfo: DirectoryInfo) => {
|
export const storeDirectoryInfo = async (directoryInfo: DirectoryInfo) => {
|
||||||
await filesystem.directory.put(directoryInfo);
|
await filesystem.directory.upsert(directoryInfo.id, { ...directoryInfo });
|
||||||
};
|
};
|
||||||
|
|
||||||
export const deleteDirectoryInfo = async (id: number) => {
|
export const deleteDirectoryInfo = async (id: number) => {
|
||||||
@@ -89,13 +89,17 @@ export const bulkGetFileInfos = async (ids: number[]) => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
export const storeFileInfo = async (fileInfo: FileInfo) => {
|
export const storeFileInfo = async (fileInfo: FileInfo) => {
|
||||||
await filesystem.file.put(fileInfo);
|
await filesystem.file.upsert(fileInfo.id, { ...fileInfo });
|
||||||
};
|
};
|
||||||
|
|
||||||
export const deleteFileInfo = async (id: number) => {
|
export const deleteFileInfo = async (id: number) => {
|
||||||
await filesystem.file.delete(id);
|
await filesystem.file.delete(id);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export const bulkDeleteFileInfos = async (ids: number[]) => {
|
||||||
|
await filesystem.file.bulkDelete(ids);
|
||||||
|
};
|
||||||
|
|
||||||
export const deleteDanglingFileInfos = async (parentId: DirectoryId, validIds: Set<number>) => {
|
export const deleteDanglingFileInfos = async (parentId: DirectoryId, validIds: Set<number>) => {
|
||||||
await filesystem.file
|
await filesystem.file
|
||||||
.where({ parentId })
|
.where({ parentId })
|
||||||
@@ -112,7 +116,7 @@ export const getCategoryInfo = async (id: number) => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
export const storeCategoryInfo = async (categoryInfo: CategoryInfo) => {
|
export const storeCategoryInfo = async (categoryInfo: CategoryInfo) => {
|
||||||
await filesystem.category.put(categoryInfo);
|
await filesystem.category.upsert(categoryInfo.id, { ...categoryInfo });
|
||||||
};
|
};
|
||||||
|
|
||||||
export const updateCategoryInfo = async (id: number, changes: { isFileRecursive?: boolean }) => {
|
export const updateCategoryInfo = async (id: number, changes: { isFileRecursive?: boolean }) => {
|
||||||
|
|||||||
@@ -1,15 +1,12 @@
|
|||||||
import { LRUCache } from "lru-cache";
|
|
||||||
import {
|
import {
|
||||||
getFileCacheIndex as getFileCacheIndexFromIndexedDB,
|
getFileCacheIndex as getFileCacheIndexFromIndexedDB,
|
||||||
storeFileCacheIndex,
|
storeFileCacheIndex,
|
||||||
deleteFileCacheIndex,
|
deleteFileCacheIndex,
|
||||||
type FileCacheIndex,
|
type FileCacheIndex,
|
||||||
} from "$lib/indexedDB";
|
} from "$lib/indexedDB";
|
||||||
import { readFile, writeFile, deleteFile, deleteDirectory } from "$lib/modules/opfs";
|
import { readFile, writeFile, deleteFile } from "$lib/modules/opfs";
|
||||||
import { getThumbnailUrl } from "$lib/modules/thumbnail";
|
|
||||||
|
|
||||||
const fileCacheIndex = new Map<number, FileCacheIndex>();
|
const fileCacheIndex = new Map<number, FileCacheIndex>();
|
||||||
const loadedThumbnails = new LRUCache<number, string>({ max: 100 });
|
|
||||||
|
|
||||||
export const prepareFileCache = async () => {
|
export const prepareFileCache = async () => {
|
||||||
for (const cache of await getFileCacheIndexFromIndexedDB()) {
|
for (const cache of await getFileCacheIndexFromIndexedDB()) {
|
||||||
@@ -51,30 +48,3 @@ export const deleteFileCache = async (fileId: number) => {
|
|||||||
await deleteFile(`/cache/${fileId}`);
|
await deleteFile(`/cache/${fileId}`);
|
||||||
await deleteFileCacheIndex(fileId);
|
await deleteFileCacheIndex(fileId);
|
||||||
};
|
};
|
||||||
|
|
||||||
export const getFileThumbnailCache = async (fileId: number) => {
|
|
||||||
const thumbnail = loadedThumbnails.get(fileId);
|
|
||||||
if (thumbnail) return thumbnail;
|
|
||||||
|
|
||||||
const thumbnailBuffer = await readFile(`/thumbnail/file/${fileId}`);
|
|
||||||
if (!thumbnailBuffer) return null;
|
|
||||||
|
|
||||||
const thumbnailUrl = getThumbnailUrl(thumbnailBuffer);
|
|
||||||
loadedThumbnails.set(fileId, thumbnailUrl);
|
|
||||||
return thumbnailUrl;
|
|
||||||
};
|
|
||||||
|
|
||||||
export const storeFileThumbnailCache = async (fileId: number, thumbnailBuffer: ArrayBuffer) => {
|
|
||||||
await writeFile(`/thumbnail/file/${fileId}`, thumbnailBuffer);
|
|
||||||
loadedThumbnails.set(fileId, getThumbnailUrl(thumbnailBuffer));
|
|
||||||
};
|
|
||||||
|
|
||||||
export const deleteFileThumbnailCache = async (fileId: number) => {
|
|
||||||
loadedThumbnails.delete(fileId);
|
|
||||||
await deleteFile(`/thumbnail/file/${fileId}`);
|
|
||||||
};
|
|
||||||
|
|
||||||
export const deleteAllFileThumbnailCaches = async () => {
|
|
||||||
loadedThumbnails.clear();
|
|
||||||
await deleteDirectory("/thumbnail/file");
|
|
||||||
};
|
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
export * from "./cache";
|
export * from "./cache";
|
||||||
export * from "./download.svelte";
|
export * from "./download.svelte";
|
||||||
|
export * from "./thumbnail";
|
||||||
export * from "./upload.svelte";
|
export * from "./upload.svelte";
|
||||||
|
|||||||
90
src/lib/modules/file/thumbnail.ts
Normal file
90
src/lib/modules/file/thumbnail.ts
Normal file
@@ -0,0 +1,90 @@
|
|||||||
|
import { LRUCache } from "lru-cache";
|
||||||
|
import { writable, type Writable } from "svelte/store";
|
||||||
|
import { browser } from "$app/environment";
|
||||||
|
import { decryptData } from "$lib/modules/crypto";
|
||||||
|
import type { SummarizedFileInfo } from "$lib/modules/filesystem";
|
||||||
|
import { readFile, writeFile, deleteFile, deleteDirectory } from "$lib/modules/opfs";
|
||||||
|
import { getThumbnailUrl } from "$lib/modules/thumbnail";
|
||||||
|
import { isTRPCClientError, trpc } from "$trpc/client";
|
||||||
|
|
||||||
|
const loadedThumbnails = new LRUCache<number, Writable<string>>({ max: 100 });
|
||||||
|
const loadingThumbnails = new Map<number, Writable<string | undefined>>();
|
||||||
|
|
||||||
|
const fetchFromOpfs = async (fileId: number) => {
|
||||||
|
const thumbnailBuffer = await readFile(`/thumbnail/file/${fileId}`);
|
||||||
|
if (thumbnailBuffer) {
|
||||||
|
return getThumbnailUrl(thumbnailBuffer);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const fetchFromServer = async (fileId: number, dataKey: CryptoKey) => {
|
||||||
|
try {
|
||||||
|
const [thumbnailEncrypted, { contentIv: thumbnailEncryptedIv }] = await Promise.all([
|
||||||
|
fetch(`/api/file/${fileId}/thumbnail/download`),
|
||||||
|
trpc().file.thumbnail.query({ id: fileId }),
|
||||||
|
]);
|
||||||
|
const thumbnailBuffer = await decryptData(
|
||||||
|
await thumbnailEncrypted.arrayBuffer(),
|
||||||
|
thumbnailEncryptedIv,
|
||||||
|
dataKey,
|
||||||
|
);
|
||||||
|
|
||||||
|
void writeFile(`/thumbnail/file/${fileId}`, thumbnailBuffer);
|
||||||
|
return getThumbnailUrl(thumbnailBuffer);
|
||||||
|
} catch (e) {
|
||||||
|
if (isTRPCClientError(e) && e.data?.code === "NOT_FOUND") {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
throw e;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
export const getFileThumbnail = (file: SummarizedFileInfo) => {
|
||||||
|
if (
|
||||||
|
!browser ||
|
||||||
|
!(file.contentType.startsWith("image/") || file.contentType.startsWith("video/"))
|
||||||
|
) {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
const thumbnail = loadedThumbnails.get(file.id);
|
||||||
|
if (thumbnail) return thumbnail;
|
||||||
|
|
||||||
|
let loadingThumbnail = loadingThumbnails.get(file.id);
|
||||||
|
if (loadingThumbnail) return loadingThumbnail;
|
||||||
|
|
||||||
|
loadingThumbnail = writable(undefined);
|
||||||
|
loadingThumbnails.set(file.id, loadingThumbnail);
|
||||||
|
|
||||||
|
fetchFromOpfs(file.id)
|
||||||
|
.then((thumbnail) => thumbnail ?? (file.dataKey && fetchFromServer(file.id, file.dataKey.key)))
|
||||||
|
.then((thumbnail) => {
|
||||||
|
if (thumbnail) {
|
||||||
|
loadingThumbnail.set(thumbnail);
|
||||||
|
loadedThumbnails.set(file.id, loadingThumbnail as Writable<string>);
|
||||||
|
}
|
||||||
|
loadingThumbnails.delete(file.id);
|
||||||
|
});
|
||||||
|
return loadingThumbnail;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const storeFileThumbnailCache = async (fileId: number, thumbnailBuffer: ArrayBuffer) => {
|
||||||
|
await writeFile(`/thumbnail/file/${fileId}`, thumbnailBuffer);
|
||||||
|
|
||||||
|
const oldThumbnail = loadedThumbnails.get(fileId);
|
||||||
|
if (oldThumbnail) {
|
||||||
|
oldThumbnail.set(getThumbnailUrl(thumbnailBuffer));
|
||||||
|
} else {
|
||||||
|
loadedThumbnails.set(fileId, writable(getThumbnailUrl(thumbnailBuffer)));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
export const deleteFileThumbnailCache = async (fileId: number) => {
|
||||||
|
loadedThumbnails.delete(fileId);
|
||||||
|
await deleteFile(`/thumbnail/file/${fileId}`);
|
||||||
|
};
|
||||||
|
|
||||||
|
export const deleteAllFileThumbnailCaches = async () => {
|
||||||
|
loadedThumbnails.clear();
|
||||||
|
await deleteDirectory(`/thumbnail/file`);
|
||||||
|
};
|
||||||
@@ -196,9 +196,7 @@ export const uploadFile = async (
|
|||||||
});
|
});
|
||||||
const state = uploadingFiles.at(-1)!;
|
const state = uploadingFiles.at(-1)!;
|
||||||
|
|
||||||
return await scheduler.schedule(
|
return await scheduler.schedule(file.size, async () => {
|
||||||
async () => file.size,
|
|
||||||
async () => {
|
|
||||||
state.status = "encryption-pending";
|
state.status = "encryption-pending";
|
||||||
|
|
||||||
try {
|
try {
|
||||||
@@ -267,6 +265,5 @@ export const uploadFile = async (
|
|||||||
state.status = "error";
|
state.status = "error";
|
||||||
throw e;
|
throw e;
|
||||||
}
|
}
|
||||||
},
|
});
|
||||||
);
|
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,22 +1,22 @@
|
|||||||
import * as IndexedDB from "$lib/indexedDB";
|
import * as IndexedDB from "$lib/indexedDB";
|
||||||
import { trpc, isTRPCClientError } from "$trpc/client";
|
import { trpc, isTRPCClientError } from "$trpc/client";
|
||||||
import { FilesystemCache, decryptFileMetadata, decryptCategoryMetadata } from "./internal.svelte";
|
import { FilesystemCache, decryptFileMetadata, decryptCategoryMetadata } from "./internal.svelte";
|
||||||
import type { MaybeCategoryInfo } from "./types";
|
import type { CategoryInfo, MaybeCategoryInfo } from "./types";
|
||||||
|
|
||||||
const cache = new FilesystemCache<CategoryId, MaybeCategoryInfo, Partial<MaybeCategoryInfo>>();
|
const cache = new FilesystemCache<CategoryId, MaybeCategoryInfo>({
|
||||||
|
async fetchFromIndexedDB(id) {
|
||||||
const fetchFromIndexedDB = async (id: CategoryId) => {
|
|
||||||
const [category, subCategories] = await Promise.all([
|
const [category, subCategories] = await Promise.all([
|
||||||
id !== "root" ? IndexedDB.getCategoryInfo(id) : undefined,
|
id !== "root" ? IndexedDB.getCategoryInfo(id) : undefined,
|
||||||
IndexedDB.getCategoryInfos(id),
|
IndexedDB.getCategoryInfos(id),
|
||||||
]);
|
]);
|
||||||
const files = category
|
const files = category?.files
|
||||||
? await Promise.all(
|
? await Promise.all(
|
||||||
category.files.map(async (file) => {
|
category.files.map(async (file) => {
|
||||||
const fileInfo = await IndexedDB.getFileInfo(file.id);
|
const fileInfo = await IndexedDB.getFileInfo(file.id);
|
||||||
return fileInfo
|
return fileInfo
|
||||||
? {
|
? {
|
||||||
id: file.id,
|
id: file.id,
|
||||||
|
parentId: fileInfo.parentId,
|
||||||
contentType: fileInfo.contentType,
|
contentType: fileInfo.contentType,
|
||||||
name: fileInfo.name,
|
name: fileInfo.name,
|
||||||
createdAt: fileInfo.createdAt,
|
createdAt: fileInfo.createdAt,
|
||||||
@@ -31,137 +31,91 @@ const fetchFromIndexedDB = async (id: CategoryId) => {
|
|||||||
if (id === "root") {
|
if (id === "root") {
|
||||||
return {
|
return {
|
||||||
id,
|
id,
|
||||||
exists: true as const,
|
exists: true,
|
||||||
subCategories,
|
subCategories,
|
||||||
};
|
};
|
||||||
} else if (category) {
|
} else if (category) {
|
||||||
return {
|
return {
|
||||||
id,
|
id,
|
||||||
exists: true as const,
|
exists: true,
|
||||||
|
parentId: category.parentId,
|
||||||
name: category.name,
|
name: category.name,
|
||||||
subCategories,
|
subCategories,
|
||||||
files: files!.filter((file) => !!file),
|
files: files?.filter((file) => !!file) ?? [],
|
||||||
isFileRecursive: category.isFileRecursive,
|
isFileRecursive: category.isFileRecursive ?? false,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
};
|
},
|
||||||
|
|
||||||
const fetchFromServer = async (id: CategoryId, masterKey: CryptoKey) => {
|
async fetchFromServer(id, cachedInfo, masterKey) {
|
||||||
try {
|
try {
|
||||||
const {
|
const category = await trpc().category.get.query({ id, recurse: true });
|
||||||
metadata,
|
const [subCategories, files, metadata] = await Promise.all([
|
||||||
subCategories: subCategoriesRaw,
|
Promise.all(
|
||||||
files: filesRaw,
|
category.subCategories.map(async (category) => ({
|
||||||
} = await trpc().category.get.query({ id, recurse: true });
|
|
||||||
|
|
||||||
void IndexedDB.deleteDanglingCategoryInfos(id, new Set(subCategoriesRaw.map(({ id }) => id)));
|
|
||||||
|
|
||||||
const subCategories = await Promise.all(
|
|
||||||
subCategoriesRaw.map(async (category) => {
|
|
||||||
const decrypted = await decryptCategoryMetadata(category, masterKey);
|
|
||||||
const existing = await IndexedDB.getCategoryInfo(category.id);
|
|
||||||
await IndexedDB.storeCategoryInfo({
|
|
||||||
id: category.id,
|
id: category.id,
|
||||||
parentId: id,
|
parentId: id,
|
||||||
name: decrypted.name,
|
...(await decryptCategoryMetadata(category, masterKey)),
|
||||||
files: existing?.files ?? [],
|
})),
|
||||||
isFileRecursive: existing?.isFileRecursive ?? false,
|
),
|
||||||
});
|
category.files &&
|
||||||
return {
|
Promise.all(
|
||||||
id: category.id,
|
category.files.map(async (file) => ({
|
||||||
...decrypted,
|
id: file.id,
|
||||||
};
|
parentId: file.parent,
|
||||||
}),
|
contentType: file.contentType,
|
||||||
|
isRecursive: file.isRecursive,
|
||||||
|
...(await decryptFileMetadata(file, masterKey)),
|
||||||
|
})),
|
||||||
|
),
|
||||||
|
category.metadata && decryptCategoryMetadata(category.metadata, masterKey),
|
||||||
|
]);
|
||||||
|
|
||||||
|
return storeToIndexedDB(
|
||||||
|
id !== "root"
|
||||||
|
? {
|
||||||
|
id,
|
||||||
|
parentId: category.metadata!.parent,
|
||||||
|
subCategories,
|
||||||
|
files: files!,
|
||||||
|
isFileRecursive: cachedInfo?.isFileRecursive ?? false,
|
||||||
|
...metadata!,
|
||||||
|
}
|
||||||
|
: { id, subCategories },
|
||||||
);
|
);
|
||||||
|
|
||||||
const existingFiles = filesRaw
|
|
||||||
? await IndexedDB.bulkGetFileInfos(filesRaw.map((file) => file.id))
|
|
||||||
: [];
|
|
||||||
const files = filesRaw
|
|
||||||
? await Promise.all(
|
|
||||||
filesRaw.map(async (file, index) => {
|
|
||||||
const decrypted = await decryptFileMetadata(file, masterKey);
|
|
||||||
const existing = existingFiles[index];
|
|
||||||
if (existing) {
|
|
||||||
const categoryIds = file.isRecursive
|
|
||||||
? existing.categoryIds
|
|
||||||
: Array.from(new Set([...existing.categoryIds, id as number]));
|
|
||||||
await IndexedDB.storeFileInfo({
|
|
||||||
id: file.id,
|
|
||||||
parentId: existing.parentId,
|
|
||||||
contentType: file.contentType,
|
|
||||||
name: decrypted.name,
|
|
||||||
createdAt: decrypted.createdAt,
|
|
||||||
lastModifiedAt: decrypted.lastModifiedAt,
|
|
||||||
categoryIds,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
return {
|
|
||||||
id: file.id,
|
|
||||||
contentType: file.contentType,
|
|
||||||
isRecursive: file.isRecursive,
|
|
||||||
...decrypted,
|
|
||||||
};
|
|
||||||
}),
|
|
||||||
)
|
|
||||||
: undefined;
|
|
||||||
|
|
||||||
const decryptedMetadata = metadata
|
|
||||||
? await decryptCategoryMetadata(metadata, masterKey)
|
|
||||||
: undefined;
|
|
||||||
if (id !== "root" && metadata && decryptedMetadata) {
|
|
||||||
const existingCategory = await IndexedDB.getCategoryInfo(id);
|
|
||||||
await IndexedDB.storeCategoryInfo({
|
|
||||||
id: id as number,
|
|
||||||
parentId: metadata.parent,
|
|
||||||
name: decryptedMetadata.name,
|
|
||||||
files:
|
|
||||||
files?.map((file) => ({
|
|
||||||
id: file.id,
|
|
||||||
isRecursive: file.isRecursive,
|
|
||||||
})) ??
|
|
||||||
existingCategory?.files ??
|
|
||||||
[],
|
|
||||||
isFileRecursive: existingCategory?.isFileRecursive ?? false,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
if (id === "root") {
|
|
||||||
return {
|
|
||||||
id,
|
|
||||||
exists: true as const,
|
|
||||||
subCategories,
|
|
||||||
};
|
|
||||||
} else {
|
|
||||||
return {
|
|
||||||
id,
|
|
||||||
exists: true as const,
|
|
||||||
subCategories,
|
|
||||||
files,
|
|
||||||
...decryptedMetadata!,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
if (isTRPCClientError(e) && e.data?.code === "NOT_FOUND") {
|
if (isTRPCClientError(e) && e.data?.code === "NOT_FOUND") {
|
||||||
await IndexedDB.deleteCategoryInfo(id as number);
|
await IndexedDB.deleteCategoryInfo(id as number);
|
||||||
return { id, exists: false as const };
|
return { id, exists: false };
|
||||||
}
|
}
|
||||||
throw e;
|
throw e;
|
||||||
}
|
}
|
||||||
};
|
},
|
||||||
|
|
||||||
export const getCategoryInfo = async (id: CategoryId, masterKey: CryptoKey) => {
|
|
||||||
return await cache.get(id, async (isInitial, resolve) => {
|
|
||||||
if (isInitial) {
|
|
||||||
const info = await fetchFromIndexedDB(id);
|
|
||||||
if (info) {
|
|
||||||
resolve(info);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const info = await fetchFromServer(id, masterKey);
|
|
||||||
if (info) {
|
|
||||||
resolve(info);
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const storeToIndexedDB = (info: CategoryInfo) => {
|
||||||
|
if (info.id !== "root") {
|
||||||
|
void IndexedDB.storeCategoryInfo(info);
|
||||||
|
|
||||||
|
// TODO: Bulk Upsert
|
||||||
|
new Map(info.files.map((file) => [file.id, file])).forEach((file) => {
|
||||||
|
void IndexedDB.storeFileInfo(file);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// TODO: Bulk Upsert
|
||||||
|
info.subCategories.forEach((category) => {
|
||||||
|
void IndexedDB.storeCategoryInfo(category);
|
||||||
|
});
|
||||||
|
|
||||||
|
void IndexedDB.deleteDanglingCategoryInfos(
|
||||||
|
info.id,
|
||||||
|
new Set(info.subCategories.map(({ id }) => id)),
|
||||||
|
);
|
||||||
|
|
||||||
|
return { ...info, exists: true as const };
|
||||||
|
};
|
||||||
|
|
||||||
|
export const getCategoryInfo = (id: CategoryId, masterKey: CryptoKey) => {
|
||||||
|
return cache.get(id, masterKey);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,12 +1,10 @@
|
|||||||
import * as IndexedDB from "$lib/indexedDB";
|
import * as IndexedDB from "$lib/indexedDB";
|
||||||
import { monotonicResolve } from "$lib/utils";
|
|
||||||
import { trpc, isTRPCClientError } from "$trpc/client";
|
import { trpc, isTRPCClientError } from "$trpc/client";
|
||||||
import { FilesystemCache, decryptDirectoryMetadata, decryptFileMetadata } from "./internal.svelte";
|
import { FilesystemCache, decryptDirectoryMetadata, decryptFileMetadata } from "./internal.svelte";
|
||||||
import type { MaybeDirectoryInfo } from "./types";
|
import type { DirectoryInfo, MaybeDirectoryInfo } from "./types";
|
||||||
|
|
||||||
const cache = new FilesystemCache<DirectoryId, MaybeDirectoryInfo>();
|
const cache = new FilesystemCache<DirectoryId, MaybeDirectoryInfo>({
|
||||||
|
async fetchFromIndexedDB(id) {
|
||||||
const fetchFromIndexedDB = async (id: DirectoryId) => {
|
|
||||||
const [directory, subDirectories, files] = await Promise.all([
|
const [directory, subDirectories, files] = await Promise.all([
|
||||||
id !== "root" ? IndexedDB.getDirectoryInfo(id) : undefined,
|
id !== "root" ? IndexedDB.getDirectoryInfo(id) : undefined,
|
||||||
IndexedDB.getDirectoryInfos(id),
|
IndexedDB.getDirectoryInfos(id),
|
||||||
@@ -16,96 +14,55 @@ const fetchFromIndexedDB = async (id: DirectoryId) => {
|
|||||||
if (id === "root") {
|
if (id === "root") {
|
||||||
return {
|
return {
|
||||||
id,
|
id,
|
||||||
exists: true as const,
|
exists: true,
|
||||||
subDirectories,
|
subDirectories,
|
||||||
files,
|
files,
|
||||||
};
|
};
|
||||||
} else if (directory) {
|
} else if (directory) {
|
||||||
return {
|
return {
|
||||||
id,
|
id,
|
||||||
exists: true as const,
|
exists: true,
|
||||||
parentId: directory.parentId,
|
parentId: directory.parentId,
|
||||||
name: directory.name,
|
name: directory.name,
|
||||||
subDirectories,
|
subDirectories,
|
||||||
files,
|
files,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
};
|
},
|
||||||
|
|
||||||
const fetchFromServer = async (id: DirectoryId, masterKey: CryptoKey) => {
|
async fetchFromServer(id, _cachedInfo, masterKey) {
|
||||||
try {
|
try {
|
||||||
const {
|
const directory = await trpc().directory.get.query({ id });
|
||||||
metadata,
|
const [subDirectories, files, metadata] = await Promise.all([
|
||||||
subDirectories: subDirectoriesRaw,
|
|
||||||
files: filesRaw,
|
|
||||||
} = await trpc().directory.get.query({ id });
|
|
||||||
|
|
||||||
void IndexedDB.deleteDanglingDirectoryInfos(id, new Set(subDirectoriesRaw.map(({ id }) => id)));
|
|
||||||
void IndexedDB.deleteDanglingFileInfos(id, new Set(filesRaw.map(({ id }) => id)));
|
|
||||||
|
|
||||||
const existingFiles = await IndexedDB.bulkGetFileInfos(filesRaw.map((file) => file.id));
|
|
||||||
const [subDirectories, files, decryptedMetadata] = await Promise.all([
|
|
||||||
Promise.all(
|
Promise.all(
|
||||||
subDirectoriesRaw.map(async (directory) => {
|
directory.subDirectories.map(async (directory) => ({
|
||||||
const decrypted = await decryptDirectoryMetadata(directory, masterKey);
|
|
||||||
await IndexedDB.storeDirectoryInfo({
|
|
||||||
id: directory.id,
|
id: directory.id,
|
||||||
parentId: id,
|
parentId: id,
|
||||||
name: decrypted.name,
|
...(await decryptDirectoryMetadata(directory, masterKey)),
|
||||||
});
|
})),
|
||||||
return {
|
|
||||||
id: directory.id,
|
|
||||||
...decrypted,
|
|
||||||
};
|
|
||||||
}),
|
|
||||||
),
|
),
|
||||||
Promise.all(
|
Promise.all(
|
||||||
filesRaw.map(async (file, index) => {
|
directory.files.map(async (file) => ({
|
||||||
const decrypted = await decryptFileMetadata(file, masterKey);
|
|
||||||
await IndexedDB.storeFileInfo({
|
|
||||||
id: file.id,
|
id: file.id,
|
||||||
parentId: id,
|
parentId: id,
|
||||||
contentType: file.contentType,
|
contentType: file.contentType,
|
||||||
name: decrypted.name,
|
...(await decryptFileMetadata(file, masterKey)),
|
||||||
createdAt: decrypted.createdAt,
|
})),
|
||||||
lastModifiedAt: decrypted.lastModifiedAt,
|
|
||||||
categoryIds: existingFiles[index]?.categoryIds ?? [],
|
|
||||||
});
|
|
||||||
return {
|
|
||||||
id: file.id,
|
|
||||||
contentType: file.contentType,
|
|
||||||
...decrypted,
|
|
||||||
};
|
|
||||||
}),
|
|
||||||
),
|
),
|
||||||
metadata ? decryptDirectoryMetadata(metadata, masterKey) : undefined,
|
directory.metadata && decryptDirectoryMetadata(directory.metadata, masterKey),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
if (id !== "root" && metadata && decryptedMetadata) {
|
return storeToIndexedDB(
|
||||||
await IndexedDB.storeDirectoryInfo({
|
id !== "root"
|
||||||
|
? {
|
||||||
id,
|
id,
|
||||||
parentId: metadata.parent,
|
parentId: directory.metadata!.parent,
|
||||||
name: decryptedMetadata.name,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
if (id === "root") {
|
|
||||||
return {
|
|
||||||
id,
|
|
||||||
exists: true as const,
|
|
||||||
subDirectories,
|
subDirectories,
|
||||||
files,
|
files,
|
||||||
};
|
...metadata!,
|
||||||
} else {
|
|
||||||
return {
|
|
||||||
id,
|
|
||||||
exists: true as const,
|
|
||||||
parentId: metadata!.parent,
|
|
||||||
subDirectories,
|
|
||||||
files,
|
|
||||||
...decryptedMetadata!,
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
: { id, subDirectories, files },
|
||||||
|
);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
if (isTRPCClientError(e) && e.data?.code === "NOT_FOUND") {
|
if (isTRPCClientError(e) && e.data?.code === "NOT_FOUND") {
|
||||||
await IndexedDB.deleteDirectoryInfo(id as number);
|
await IndexedDB.deleteDirectoryInfo(id as number);
|
||||||
@@ -113,13 +70,33 @@ const fetchFromServer = async (id: DirectoryId, masterKey: CryptoKey) => {
|
|||||||
}
|
}
|
||||||
throw e;
|
throw e;
|
||||||
}
|
}
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const storeToIndexedDB = (info: DirectoryInfo) => {
|
||||||
|
if (info.id !== "root") {
|
||||||
|
void IndexedDB.storeDirectoryInfo(info);
|
||||||
|
}
|
||||||
|
|
||||||
|
// TODO: Bulk Upsert
|
||||||
|
info.subDirectories.forEach((subDirectory) => {
|
||||||
|
void IndexedDB.storeDirectoryInfo(subDirectory);
|
||||||
|
});
|
||||||
|
|
||||||
|
// TODO: Bulk Upsert
|
||||||
|
info.files.forEach((file) => {
|
||||||
|
void IndexedDB.storeFileInfo(file);
|
||||||
|
});
|
||||||
|
|
||||||
|
void IndexedDB.deleteDanglingDirectoryInfos(
|
||||||
|
info.id,
|
||||||
|
new Set(info.subDirectories.map(({ id }) => id)),
|
||||||
|
);
|
||||||
|
void IndexedDB.deleteDanglingFileInfos(info.id, new Set(info.files.map(({ id }) => id)));
|
||||||
|
|
||||||
|
return { ...info, exists: true as const };
|
||||||
};
|
};
|
||||||
|
|
||||||
export const getDirectoryInfo = async (id: DirectoryId, masterKey: CryptoKey) => {
|
export const getDirectoryInfo = (id: DirectoryId, masterKey: CryptoKey) => {
|
||||||
return await cache.get(id, (isInitial, resolve) =>
|
return cache.get(id, masterKey);
|
||||||
monotonicResolve(
|
|
||||||
[isInitial && fetchFromIndexedDB(id), fetchFromServer(id, masterKey)],
|
|
||||||
resolve,
|
|
||||||
),
|
|
||||||
);
|
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,18 +1,18 @@
|
|||||||
import * as IndexedDB from "$lib/indexedDB";
|
import * as IndexedDB from "$lib/indexedDB";
|
||||||
import { monotonicResolve } from "$lib/utils";
|
|
||||||
import { trpc, isTRPCClientError } from "$trpc/client";
|
import { trpc, isTRPCClientError } from "$trpc/client";
|
||||||
import { FilesystemCache, decryptFileMetadata, decryptCategoryMetadata } from "./internal.svelte";
|
import { FilesystemCache, decryptFileMetadata, decryptCategoryMetadata } from "./internal.svelte";
|
||||||
import type { MaybeFileInfo } from "./types";
|
import type { FileInfo, MaybeFileInfo } from "./types";
|
||||||
|
|
||||||
const cache = new FilesystemCache<number, MaybeFileInfo>();
|
const cache = new FilesystemCache<number, MaybeFileInfo>({
|
||||||
|
async fetchFromIndexedDB(id) {
|
||||||
const fetchFromIndexedDB = async (id: number) => {
|
|
||||||
const file = await IndexedDB.getFileInfo(id);
|
const file = await IndexedDB.getFileInfo(id);
|
||||||
const categories = file
|
const categories = file?.categoryIds
|
||||||
? await Promise.all(
|
? await Promise.all(
|
||||||
file.categoryIds.map(async (categoryId) => {
|
file.categoryIds.map(async (categoryId) => {
|
||||||
const category = await IndexedDB.getCategoryInfo(categoryId);
|
const category = await IndexedDB.getCategoryInfo(categoryId);
|
||||||
return category ? { id: category.id, name: category.name } : undefined;
|
return category
|
||||||
|
? { id: category.id, parentId: category.parentId, name: category.name }
|
||||||
|
: undefined;
|
||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
: undefined;
|
: undefined;
|
||||||
@@ -20,81 +20,42 @@ const fetchFromIndexedDB = async (id: number) => {
|
|||||||
if (file) {
|
if (file) {
|
||||||
return {
|
return {
|
||||||
id,
|
id,
|
||||||
exists: true as const,
|
exists: true,
|
||||||
parentId: file.parentId,
|
parentId: file.parentId,
|
||||||
contentType: file.contentType,
|
contentType: file.contentType,
|
||||||
name: file.name,
|
name: file.name,
|
||||||
createdAt: file.createdAt,
|
createdAt: file.createdAt,
|
||||||
lastModifiedAt: file.lastModifiedAt,
|
lastModifiedAt: file.lastModifiedAt,
|
||||||
categories: categories!.filter((category) => !!category),
|
categories: categories?.filter((category) => !!category) ?? [],
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
};
|
|
||||||
|
|
||||||
const bulkFetchFromIndexedDB = async (ids: number[]) => {
|
|
||||||
const files = await IndexedDB.bulkGetFileInfos(ids);
|
|
||||||
const categories = await Promise.all(
|
|
||||||
files.map(async (file) =>
|
|
||||||
file
|
|
||||||
? await Promise.all(
|
|
||||||
file.categoryIds.map(async (categoryId) => {
|
|
||||||
const category = await IndexedDB.getCategoryInfo(categoryId);
|
|
||||||
return category ? { id: category.id, name: category.name } : undefined;
|
|
||||||
}),
|
|
||||||
)
|
|
||||||
: undefined,
|
|
||||||
),
|
|
||||||
);
|
|
||||||
return new Map(
|
|
||||||
files
|
|
||||||
.map((file, index) =>
|
|
||||||
file
|
|
||||||
? ([
|
|
||||||
file.id,
|
|
||||||
{
|
|
||||||
...file,
|
|
||||||
exists: true,
|
|
||||||
categories: categories[index]!.filter((category) => !!category),
|
|
||||||
},
|
},
|
||||||
] as const)
|
|
||||||
: undefined,
|
|
||||||
)
|
|
||||||
.filter((file) => !!file),
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
const fetchFromServer = async (id: number, masterKey: CryptoKey) => {
|
async fetchFromServer(id, _cachedInfo, masterKey) {
|
||||||
try {
|
try {
|
||||||
const { categories: categoriesRaw, ...metadata } = await trpc().file.get.query({ id });
|
const file = await trpc().file.get.query({ id });
|
||||||
const [categories, decryptedMetadata] = await Promise.all([
|
const [categories, metadata] = await Promise.all([
|
||||||
Promise.all(
|
Promise.all(
|
||||||
categoriesRaw.map(async (category) => ({
|
file.categories.map(async (category) => ({
|
||||||
id: category.id,
|
id: category.id,
|
||||||
|
parentId: category.parent,
|
||||||
...(await decryptCategoryMetadata(category, masterKey)),
|
...(await decryptCategoryMetadata(category, masterKey)),
|
||||||
})),
|
})),
|
||||||
),
|
),
|
||||||
decryptFileMetadata(metadata, masterKey),
|
decryptFileMetadata(file, masterKey),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
await IndexedDB.storeFileInfo({
|
return storeToIndexedDB({
|
||||||
id,
|
id,
|
||||||
parentId: metadata.parent,
|
parentId: file.parent,
|
||||||
contentType: metadata.contentType,
|
dataKey: metadata.dataKey,
|
||||||
name: decryptedMetadata.name,
|
contentType: file.contentType,
|
||||||
createdAt: decryptedMetadata.createdAt,
|
contentIv: file.contentIv,
|
||||||
lastModifiedAt: decryptedMetadata.lastModifiedAt,
|
name: metadata.name,
|
||||||
categoryIds: categories.map((category) => category.id),
|
createdAt: metadata.createdAt,
|
||||||
});
|
lastModifiedAt: metadata.lastModifiedAt,
|
||||||
|
|
||||||
return {
|
|
||||||
id,
|
|
||||||
exists: true as const,
|
|
||||||
parentId: metadata.parent,
|
|
||||||
contentType: metadata.contentType,
|
|
||||||
contentIv: metadata.contentIv,
|
|
||||||
categories,
|
categories,
|
||||||
...decryptedMetadata,
|
});
|
||||||
};
|
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
if (isTRPCClientError(e) && e.data?.code === "NOT_FOUND") {
|
if (isTRPCClientError(e) && e.data?.code === "NOT_FOUND") {
|
||||||
await IndexedDB.deleteFileInfo(id);
|
await IndexedDB.deleteFileInfo(id);
|
||||||
@@ -102,74 +63,115 @@ const fetchFromServer = async (id: number, masterKey: CryptoKey) => {
|
|||||||
}
|
}
|
||||||
throw e;
|
throw e;
|
||||||
}
|
}
|
||||||
};
|
},
|
||||||
|
|
||||||
const bulkFetchFromServer = async (ids: number[], masterKey: CryptoKey) => {
|
async bulkFetchFromIndexedDB(ids) {
|
||||||
const filesRaw = await trpc().file.bulkGet.query({ ids });
|
const files = await IndexedDB.bulkGetFileInfos([...ids]);
|
||||||
|
const categories = await Promise.all(
|
||||||
|
files.map(async (file) =>
|
||||||
|
file?.categoryIds
|
||||||
|
? await Promise.all(
|
||||||
|
file.categoryIds.map(async (categoryId) => {
|
||||||
|
const category = await IndexedDB.getCategoryInfo(categoryId);
|
||||||
|
return category
|
||||||
|
? { id: category.id, parentId: category.parentId, name: category.name }
|
||||||
|
: undefined;
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
: undefined,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
return new Map(
|
||||||
|
files
|
||||||
|
.filter((file) => !!file)
|
||||||
|
.map((file, index) => [
|
||||||
|
file.id,
|
||||||
|
{
|
||||||
|
...file,
|
||||||
|
exists: true,
|
||||||
|
categories: categories[index]?.filter((category) => !!category) ?? [],
|
||||||
|
},
|
||||||
|
]),
|
||||||
|
);
|
||||||
|
},
|
||||||
|
|
||||||
|
async bulkFetchFromServer(ids, masterKey) {
|
||||||
|
const idsArray = [...ids.keys()];
|
||||||
|
|
||||||
|
const filesRaw = await trpc().file.bulkGet.query({ ids: idsArray });
|
||||||
const files = await Promise.all(
|
const files = await Promise.all(
|
||||||
filesRaw.map(async (file) => {
|
filesRaw.map(async ({ id, categories: categoriesRaw, ...metadataRaw }) => {
|
||||||
const [categories, decryptedMetadata] = await Promise.all([
|
const [categories, metadata] = await Promise.all([
|
||||||
Promise.all(
|
Promise.all(
|
||||||
file.categories.map(async (category) => ({
|
categoriesRaw.map(async (category) => ({
|
||||||
id: category.id,
|
id: category.id,
|
||||||
|
parentId: category.parent,
|
||||||
...(await decryptCategoryMetadata(category, masterKey)),
|
...(await decryptCategoryMetadata(category, masterKey)),
|
||||||
})),
|
})),
|
||||||
),
|
),
|
||||||
decryptFileMetadata(file, masterKey),
|
decryptFileMetadata(metadataRaw, masterKey),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
await IndexedDB.storeFileInfo({
|
|
||||||
id: file.id,
|
|
||||||
parentId: file.parent,
|
|
||||||
contentType: file.contentType,
|
|
||||||
name: decryptedMetadata.name,
|
|
||||||
createdAt: decryptedMetadata.createdAt,
|
|
||||||
lastModifiedAt: decryptedMetadata.lastModifiedAt,
|
|
||||||
categoryIds: categories.map((category) => category.id),
|
|
||||||
});
|
|
||||||
return {
|
return {
|
||||||
id: file.id,
|
id,
|
||||||
exists: true as const,
|
exists: true as const,
|
||||||
parentId: file.parent,
|
parentId: metadataRaw.parent,
|
||||||
contentType: file.contentType,
|
contentType: metadataRaw.contentType,
|
||||||
contentIv: file.contentIv,
|
contentIv: metadataRaw.contentIv,
|
||||||
categories,
|
categories,
|
||||||
...decryptedMetadata,
|
...metadata,
|
||||||
};
|
};
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
const existingIds = new Set(filesRaw.map(({ id }) => id));
|
const existingIds = new Set(filesRaw.map(({ id }) => id));
|
||||||
|
const deletedIds = idsArray.filter((id) => !existingIds.has(id));
|
||||||
|
|
||||||
|
void IndexedDB.bulkDeleteFileInfos(deletedIds);
|
||||||
return new Map<number, MaybeFileInfo>([
|
return new Map<number, MaybeFileInfo>([
|
||||||
...files.map((file) => [file.id, file] as const),
|
...bulkStoreToIndexedDB(files),
|
||||||
...ids.filter((id) => !existingIds.has(id)).map((id) => [id, { id, exists: false }] as const),
|
...deletedIds.map((id) => [id, { id, exists: false }] as const),
|
||||||
]);
|
]);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const storeToIndexedDB = (info: FileInfo) => {
|
||||||
|
void IndexedDB.storeFileInfo({
|
||||||
|
...info,
|
||||||
|
categoryIds: info.categories.map(({ id }) => id),
|
||||||
|
});
|
||||||
|
|
||||||
|
info.categories.forEach((category) => {
|
||||||
|
void IndexedDB.storeCategoryInfo(category);
|
||||||
|
});
|
||||||
|
|
||||||
|
return { ...info, exists: true as const };
|
||||||
};
|
};
|
||||||
|
|
||||||
export const getFileInfo = async (id: number, masterKey: CryptoKey) => {
|
const bulkStoreToIndexedDB = (infos: FileInfo[]) => {
|
||||||
return await cache.get(id, (isInitial, resolve) =>
|
// TODO: Bulk Upsert
|
||||||
monotonicResolve(
|
infos.forEach((info) => {
|
||||||
[isInitial && fetchFromIndexedDB(id), fetchFromServer(id, masterKey)],
|
void IndexedDB.storeFileInfo({
|
||||||
resolve,
|
...info,
|
||||||
),
|
categoryIds: info.categories.map(({ id }) => id),
|
||||||
);
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// TODO: Bulk Upsert
|
||||||
|
new Map(
|
||||||
|
infos.flatMap(({ categories }) => categories).map((category) => [category.id, category]),
|
||||||
|
).forEach((category) => {
|
||||||
|
void IndexedDB.storeCategoryInfo(category);
|
||||||
|
});
|
||||||
|
|
||||||
|
return infos.map((info) => [info.id, { ...info, exists: true }] as const);
|
||||||
};
|
};
|
||||||
|
|
||||||
export const bulkGetFileInfo = async (ids: number[], masterKey: CryptoKey) => {
|
export const getFileInfo = (id: number, masterKey: CryptoKey) => {
|
||||||
return await cache.bulkGet(new Set(ids), (keys, resolve) =>
|
return cache.get(id, masterKey);
|
||||||
monotonicResolve(
|
};
|
||||||
[
|
|
||||||
bulkFetchFromIndexedDB(
|
export const bulkGetFileInfo = (ids: number[], masterKey: CryptoKey) => {
|
||||||
Array.from(
|
return cache.bulkGet(new Set(ids), masterKey);
|
||||||
keys
|
|
||||||
.entries()
|
|
||||||
.filter(([, isInitial]) => isInitial)
|
|
||||||
.map(([key]) => key),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
bulkFetchFromServer(Array.from(keys.keys()), masterKey),
|
|
||||||
],
|
|
||||||
resolve,
|
|
||||||
),
|
|
||||||
);
|
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,82 +1,124 @@
|
|||||||
|
import { untrack } from "svelte";
|
||||||
import { unwrapDataKey, decryptString } from "$lib/modules/crypto";
|
import { unwrapDataKey, decryptString } from "$lib/modules/crypto";
|
||||||
|
|
||||||
export class FilesystemCache<K, V extends RV, RV = V> {
|
interface FilesystemCacheOptions<K, V> {
|
||||||
private map = new Map<K, V | Promise<V>>();
|
fetchFromIndexedDB: (key: K) => Promise<V | undefined>;
|
||||||
|
fetchFromServer: (key: K, cachedValue: V | undefined, masterKey: CryptoKey) => Promise<V>;
|
||||||
get(key: K, loader: (isInitial: boolean, resolve: (value: RV | undefined) => void) => void) {
|
bulkFetchFromIndexedDB?: (keys: Set<K>) => Promise<Map<K, V>>;
|
||||||
const info = this.map.get(key);
|
bulkFetchFromServer?: (
|
||||||
if (info instanceof Promise) {
|
keys: Map<K, { cachedValue: V | undefined }>,
|
||||||
return info;
|
masterKey: CryptoKey,
|
||||||
|
) => Promise<Map<K, V>>;
|
||||||
}
|
}
|
||||||
|
|
||||||
const { promise, resolve } = Promise.withResolvers<V>();
|
export class FilesystemCache<K, V extends object> {
|
||||||
if (!info) {
|
private map = new Map<K, { value?: V; promise?: Promise<V> }>();
|
||||||
this.map.set(key, promise);
|
|
||||||
|
constructor(private readonly options: FilesystemCacheOptions<K, V>) {}
|
||||||
|
|
||||||
|
get(key: K, masterKey: CryptoKey) {
|
||||||
|
return untrack(() => {
|
||||||
|
let state = this.map.get(key);
|
||||||
|
if (state?.promise) return state.value ?? state.promise;
|
||||||
|
|
||||||
|
const { promise: newPromise, resolve } = Promise.withResolvers<V>();
|
||||||
|
|
||||||
|
if (!state) {
|
||||||
|
const newState = $state({});
|
||||||
|
state = newState;
|
||||||
|
this.map.set(key, newState);
|
||||||
}
|
}
|
||||||
|
|
||||||
loader(!info, (loadedInfo) => {
|
(state.value
|
||||||
if (!loadedInfo) return;
|
? Promise.resolve(state.value)
|
||||||
|
: this.options.fetchFromIndexedDB(key).then((loadedInfo) => {
|
||||||
const info = this.map.get(key)!;
|
if (loadedInfo) {
|
||||||
if (info instanceof Promise) {
|
state.value = loadedInfo;
|
||||||
const state = $state(loadedInfo);
|
resolve(state.value);
|
||||||
this.map.set(key, state as V);
|
}
|
||||||
resolve(state as V);
|
return loadedInfo;
|
||||||
|
})
|
||||||
|
)
|
||||||
|
.then((cachedInfo) => this.options.fetchFromServer(key, cachedInfo, masterKey))
|
||||||
|
.then((loadedInfo) => {
|
||||||
|
if (state.value) {
|
||||||
|
Object.assign(state.value, loadedInfo);
|
||||||
} else {
|
} else {
|
||||||
Object.assign(info, loadedInfo);
|
state.value = loadedInfo;
|
||||||
resolve(info);
|
}
|
||||||
|
resolve(state.value);
|
||||||
|
})
|
||||||
|
.finally(() => {
|
||||||
|
state.promise = undefined;
|
||||||
|
});
|
||||||
|
|
||||||
|
state.promise = newPromise;
|
||||||
|
return state.value ?? newPromise;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
bulkGet(keys: Set<K>, masterKey: CryptoKey) {
|
||||||
|
return untrack(() => {
|
||||||
|
const newPromises = new Map(
|
||||||
|
keys
|
||||||
|
.keys()
|
||||||
|
.filter((key) => this.map.get(key)?.promise === undefined)
|
||||||
|
.map((key) => [key, Promise.withResolvers<V>()]),
|
||||||
|
);
|
||||||
|
newPromises.forEach(({ promise }, key) => {
|
||||||
|
const state = this.map.get(key);
|
||||||
|
if (state) {
|
||||||
|
state.promise = promise;
|
||||||
|
} else {
|
||||||
|
const newState = $state({ promise });
|
||||||
|
this.map.set(key, newState);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
return info ?? promise;
|
const resolve = (loadedInfos: Map<K, V>) => {
|
||||||
}
|
|
||||||
|
|
||||||
async bulkGet(
|
|
||||||
keys: Set<K>,
|
|
||||||
loader: (keys: Map<K, boolean>, resolve: (values: Map<K, RV>) => void) => void,
|
|
||||||
) {
|
|
||||||
const states = new Map<K, V>();
|
|
||||||
const promises = new Map<K, Promise<V>>();
|
|
||||||
const resolvers = new Map<K, (value: V) => void>();
|
|
||||||
|
|
||||||
keys.forEach((key) => {
|
|
||||||
const info = this.map.get(key);
|
|
||||||
if (info instanceof Promise) {
|
|
||||||
promises.set(key, info);
|
|
||||||
} else if (info) {
|
|
||||||
states.set(key, info);
|
|
||||||
} else {
|
|
||||||
const { promise, resolve } = Promise.withResolvers<V>();
|
|
||||||
this.map.set(key, promise);
|
|
||||||
promises.set(key, promise);
|
|
||||||
resolvers.set(key, resolve);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
loader(
|
|
||||||
new Map([
|
|
||||||
...states.keys().map((key) => [key, false] as const),
|
|
||||||
...resolvers.keys().map((key) => [key, true] as const),
|
|
||||||
]),
|
|
||||||
(loadedInfos) =>
|
|
||||||
loadedInfos.forEach((loadedInfo, key) => {
|
loadedInfos.forEach((loadedInfo, key) => {
|
||||||
const info = this.map.get(key)!;
|
const state = this.map.get(key)!;
|
||||||
const resolve = resolvers.get(key);
|
if (state.value) {
|
||||||
if (info instanceof Promise) {
|
Object.assign(state.value, loadedInfo);
|
||||||
const state = $state(loadedInfo);
|
|
||||||
this.map.set(key, state as V);
|
|
||||||
resolve?.(state as V);
|
|
||||||
} else {
|
} else {
|
||||||
Object.assign(info, loadedInfo);
|
state.value = loadedInfo;
|
||||||
resolve?.(info);
|
|
||||||
}
|
}
|
||||||
}),
|
newPromises.get(key)!.resolve(state.value);
|
||||||
);
|
});
|
||||||
|
return loadedInfos;
|
||||||
|
};
|
||||||
|
|
||||||
const newStates = await Promise.all(
|
this.options.bulkFetchFromIndexedDB!(
|
||||||
promises.entries().map(async ([key, promise]) => [key, await promise] as const),
|
new Set(newPromises.keys().filter((key) => this.map.get(key)!.value === undefined)),
|
||||||
|
)
|
||||||
|
.then(resolve)
|
||||||
|
.then(() =>
|
||||||
|
this.options.bulkFetchFromServer!(
|
||||||
|
new Map(
|
||||||
|
newPromises.keys().map((key) => [key, { cachedValue: this.map.get(key)!.value }]),
|
||||||
|
),
|
||||||
|
masterKey,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.then(resolve)
|
||||||
|
.finally(() => {
|
||||||
|
newPromises.forEach((_, key) => {
|
||||||
|
this.map.get(key)!.promise = undefined;
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
const bottleneckPromises = Array.from(
|
||||||
|
keys
|
||||||
|
.keys()
|
||||||
|
.filter((key) => this.map.get(key)!.value === undefined)
|
||||||
|
.map((key) => this.map.get(key)!.promise!),
|
||||||
);
|
);
|
||||||
return new Map([...states, ...newStates]);
|
const makeResult = () =>
|
||||||
|
new Map(keys.keys().map((key) => [key, this.map.get(key)!.value!] as const));
|
||||||
|
return bottleneckPromises.length > 0
|
||||||
|
? Promise.all(bottleneckPromises).then(makeResult)
|
||||||
|
: makeResult();
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -20,11 +20,12 @@ interface RootDirectoryInfo {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export type DirectoryInfo = LocalDirectoryInfo | RootDirectoryInfo;
|
export type DirectoryInfo = LocalDirectoryInfo | RootDirectoryInfo;
|
||||||
export type SubDirectoryInfo = Omit<LocalDirectoryInfo, "parentId" | "subDirectories" | "files">;
|
|
||||||
export type MaybeDirectoryInfo =
|
export type MaybeDirectoryInfo =
|
||||||
| (DirectoryInfo & { exists: true })
|
| (DirectoryInfo & { exists: true })
|
||||||
| ({ id: DirectoryId; exists: false } & AllUndefined<Omit<DirectoryInfo, "id">>);
|
| ({ id: DirectoryId; exists: false } & AllUndefined<Omit<DirectoryInfo, "id">>);
|
||||||
|
|
||||||
|
export type SubDirectoryInfo = Omit<LocalDirectoryInfo, "subDirectories" | "files">;
|
||||||
|
|
||||||
export interface FileInfo {
|
export interface FileInfo {
|
||||||
id: number;
|
id: number;
|
||||||
parentId: DirectoryId;
|
parentId: DirectoryId;
|
||||||
@@ -34,17 +35,19 @@ export interface FileInfo {
|
|||||||
name: string;
|
name: string;
|
||||||
createdAt?: Date;
|
createdAt?: Date;
|
||||||
lastModifiedAt: Date;
|
lastModifiedAt: Date;
|
||||||
categories: { id: number; name: string }[];
|
categories: FileCategoryInfo[];
|
||||||
}
|
}
|
||||||
|
|
||||||
export type SummarizedFileInfo = Omit<FileInfo, "parentId" | "contentIv" | "categories">;
|
|
||||||
export type CategoryFileInfo = SummarizedFileInfo & { isRecursive: boolean };
|
|
||||||
export type MaybeFileInfo =
|
export type MaybeFileInfo =
|
||||||
| (FileInfo & { exists: true })
|
| (FileInfo & { exists: true })
|
||||||
| ({ id: number; exists: false } & AllUndefined<Omit<FileInfo, "id">>);
|
| ({ id: number; exists: false } & AllUndefined<Omit<FileInfo, "id">>);
|
||||||
|
|
||||||
|
export type SummarizedFileInfo = Omit<FileInfo, "contentIv" | "categories">;
|
||||||
|
export type CategoryFileInfo = SummarizedFileInfo & { isRecursive: boolean };
|
||||||
|
|
||||||
interface LocalCategoryInfo {
|
interface LocalCategoryInfo {
|
||||||
id: number;
|
id: number;
|
||||||
|
parentId: DirectoryId;
|
||||||
dataKey?: DataKey;
|
dataKey?: DataKey;
|
||||||
name: string;
|
name: string;
|
||||||
subCategories: SubCategoryInfo[];
|
subCategories: SubCategoryInfo[];
|
||||||
@@ -54,6 +57,7 @@ interface LocalCategoryInfo {
|
|||||||
|
|
||||||
interface RootCategoryInfo {
|
interface RootCategoryInfo {
|
||||||
id: "root";
|
id: "root";
|
||||||
|
parentId?: undefined;
|
||||||
dataKey?: undefined;
|
dataKey?: undefined;
|
||||||
name?: undefined;
|
name?: undefined;
|
||||||
subCategories: SubCategoryInfo[];
|
subCategories: SubCategoryInfo[];
|
||||||
@@ -62,10 +66,12 @@ interface RootCategoryInfo {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export type CategoryInfo = LocalCategoryInfo | RootCategoryInfo;
|
export type CategoryInfo = LocalCategoryInfo | RootCategoryInfo;
|
||||||
|
export type MaybeCategoryInfo =
|
||||||
|
| (CategoryInfo & { exists: true })
|
||||||
|
| ({ id: CategoryId; exists: false } & AllUndefined<Omit<CategoryInfo, "id">>);
|
||||||
|
|
||||||
export type SubCategoryInfo = Omit<
|
export type SubCategoryInfo = Omit<
|
||||||
LocalCategoryInfo,
|
LocalCategoryInfo,
|
||||||
"subCategories" | "files" | "isFileRecursive"
|
"subCategories" | "files" | "isFileRecursive"
|
||||||
>;
|
>;
|
||||||
export type MaybeCategoryInfo =
|
export type FileCategoryInfo = Omit<SubCategoryInfo, "dataKey">;
|
||||||
| (CategoryInfo & { exists: true })
|
|
||||||
| ({ id: CategoryId; exists: false } & AllUndefined<Omit<CategoryInfo, "id">>);
|
|
||||||
|
|||||||
@@ -1,39 +1,46 @@
|
|||||||
export class Scheduler<T = void> {
|
export class Scheduler<T = void> {
|
||||||
private tasks = 0;
|
private isEstimating = false;
|
||||||
private memoryUsage = 0;
|
private memoryUsage = 0;
|
||||||
private queue: (() => void)[] = [];
|
private queue: (() => void)[] = [];
|
||||||
|
|
||||||
constructor(public memoryLimit = 100 * 1024 * 1024 /* 100 MiB */) {}
|
constructor(public readonly memoryLimit = 100 * 1024 * 1024 /* 100 MiB */) {}
|
||||||
|
|
||||||
private next() {
|
private next() {
|
||||||
if (this.memoryUsage < this.memoryLimit) {
|
if (!this.isEstimating && this.memoryUsage < this.memoryLimit) {
|
||||||
this.queue.shift()?.();
|
const resolve = this.queue.shift();
|
||||||
|
if (resolve) {
|
||||||
|
this.isEstimating = true;
|
||||||
|
resolve();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async schedule(estimateMemoryUsage: () => Promise<number>, task: () => Promise<T>) {
|
async schedule(
|
||||||
if (this.tasks++ > 0) {
|
estimateMemoryUsage: number | (() => number | Promise<number>),
|
||||||
|
task: () => Promise<T>,
|
||||||
|
) {
|
||||||
|
if (this.isEstimating || this.memoryUsage >= this.memoryLimit) {
|
||||||
await new Promise<void>((resolve) => {
|
await new Promise<void>((resolve) => {
|
||||||
this.queue.push(resolve);
|
this.queue.push(resolve);
|
||||||
});
|
});
|
||||||
}
|
} else {
|
||||||
|
this.isEstimating = true;
|
||||||
while (this.memoryUsage >= this.memoryLimit) {
|
|
||||||
await new Promise<void>((resolve) => {
|
|
||||||
this.queue.unshift(resolve);
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
let taskMemoryUsage = 0;
|
let taskMemoryUsage = 0;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
taskMemoryUsage = await estimateMemoryUsage();
|
taskMemoryUsage =
|
||||||
|
typeof estimateMemoryUsage === "number" ? estimateMemoryUsage : await estimateMemoryUsage();
|
||||||
this.memoryUsage += taskMemoryUsage;
|
this.memoryUsage += taskMemoryUsage;
|
||||||
|
} finally {
|
||||||
|
this.isEstimating = false;
|
||||||
this.next();
|
this.next();
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
return await task();
|
return await task();
|
||||||
} finally {
|
} finally {
|
||||||
this.tasks--;
|
|
||||||
this.memoryUsage -= taskMemoryUsage;
|
this.memoryUsage -= taskMemoryUsage;
|
||||||
this.next();
|
this.next();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -39,6 +39,7 @@ export type NewFile = Omit<File, "id">;
|
|||||||
|
|
||||||
interface FileCategory {
|
interface FileCategory {
|
||||||
id: number;
|
id: number;
|
||||||
|
parentId: CategoryId;
|
||||||
mekVersion: number;
|
mekVersion: number;
|
||||||
encDek: string;
|
encDek: string;
|
||||||
dekVersion: Date;
|
dekVersion: Date;
|
||||||
@@ -445,6 +446,7 @@ export const getFilesWithCategories = async (userId: number, fileIds: number[])
|
|||||||
encLastModifiedAt: file.encrypted_last_modified_at,
|
encLastModifiedAt: file.encrypted_last_modified_at,
|
||||||
categories: file.categories.map((category) => ({
|
categories: file.categories.map((category) => ({
|
||||||
id: category.id,
|
id: category.id,
|
||||||
|
parentId: category.parent_id ?? "root",
|
||||||
mekVersion: category.master_encryption_key_version,
|
mekVersion: category.master_encryption_key_version,
|
||||||
encDek: category.encrypted_data_encryption_key,
|
encDek: category.encrypted_data_encryption_key,
|
||||||
dekVersion: new Date(category.data_encryption_key_version),
|
dekVersion: new Date(category.data_encryption_key_version),
|
||||||
@@ -548,6 +550,7 @@ export const getAllFileCategories = async (fileId: number) => {
|
|||||||
(category) =>
|
(category) =>
|
||||||
({
|
({
|
||||||
id: category.id,
|
id: category.id,
|
||||||
|
parentId: category.parent_id ?? "root",
|
||||||
mekVersion: category.master_encryption_key_version,
|
mekVersion: category.master_encryption_key_version,
|
||||||
encDek: category.encrypted_data_encryption_key,
|
encDek: category.encrypted_data_encryption_key,
|
||||||
dekVersion: category.data_encryption_key_version,
|
dekVersion: category.data_encryption_key_version,
|
||||||
|
|||||||
@@ -1,15 +1,11 @@
|
|||||||
import { getAllFileInfos } from "$lib/indexedDB/filesystem";
|
import { getAllFileInfos } from "$lib/indexedDB/filesystem";
|
||||||
import { decryptData } from "$lib/modules/crypto";
|
|
||||||
import {
|
import {
|
||||||
getFileCache,
|
getFileCache,
|
||||||
storeFileCache,
|
storeFileCache,
|
||||||
deleteFileCache,
|
deleteFileCache,
|
||||||
getFileThumbnailCache,
|
|
||||||
storeFileThumbnailCache,
|
|
||||||
deleteFileThumbnailCache,
|
|
||||||
downloadFile,
|
downloadFile,
|
||||||
|
deleteFileThumbnailCache,
|
||||||
} from "$lib/modules/file";
|
} from "$lib/modules/file";
|
||||||
import { getThumbnailUrl } from "$lib/modules/thumbnail";
|
|
||||||
import type { FileThumbnailUploadRequest } from "$lib/server/schemas";
|
import type { FileThumbnailUploadRequest } from "$lib/server/schemas";
|
||||||
import { trpc } from "$trpc/client";
|
import { trpc } from "$trpc/client";
|
||||||
|
|
||||||
@@ -44,29 +40,6 @@ export const requestFileThumbnailUpload = async (
|
|||||||
return await fetch(`/api/file/${fileId}/thumbnail/upload`, { method: "POST", body: form });
|
return await fetch(`/api/file/${fileId}/thumbnail/upload`, { method: "POST", body: form });
|
||||||
};
|
};
|
||||||
|
|
||||||
export const requestFileThumbnailDownload = async (fileId: number, dataKey?: CryptoKey) => {
|
|
||||||
const cache = await getFileThumbnailCache(fileId);
|
|
||||||
if (cache || !dataKey) return cache;
|
|
||||||
|
|
||||||
let thumbnailInfo;
|
|
||||||
try {
|
|
||||||
thumbnailInfo = await trpc().file.thumbnail.query({ id: fileId });
|
|
||||||
} catch {
|
|
||||||
// TODO: Error Handling
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
const { contentIv: thumbnailEncryptedIv } = thumbnailInfo;
|
|
||||||
|
|
||||||
const res = await fetch(`/api/file/${fileId}/thumbnail/download`);
|
|
||||||
if (!res.ok) return null;
|
|
||||||
|
|
||||||
const thumbnailEncrypted = await res.arrayBuffer();
|
|
||||||
const thumbnailBuffer = await decryptData(thumbnailEncrypted, thumbnailEncryptedIv, dataKey);
|
|
||||||
|
|
||||||
storeFileThumbnailCache(fileId, thumbnailBuffer); // Intended
|
|
||||||
return getThumbnailUrl(thumbnailBuffer);
|
|
||||||
};
|
|
||||||
|
|
||||||
export const requestDeletedFilesCleanup = async () => {
|
export const requestDeletedFilesCleanup = async () => {
|
||||||
let liveFiles;
|
let liveFiles;
|
||||||
try {
|
try {
|
||||||
|
|||||||
93
src/lib/utils/HybridPromise.ts
Normal file
93
src/lib/utils/HybridPromise.ts
Normal file
@@ -0,0 +1,93 @@
|
|||||||
|
type MaybePromise<T> = T | Promise<T> | HybridPromise<T>;
|
||||||
|
|
||||||
|
type HybridPromiseState<T> =
|
||||||
|
| { mode: "sync"; status: "fulfilled"; value: T }
|
||||||
|
| { mode: "sync"; status: "rejected"; reason: unknown }
|
||||||
|
| { mode: "async"; promise: Promise<T> };
|
||||||
|
|
||||||
|
export class HybridPromise<T> implements PromiseLike<T> {
|
||||||
|
private isConsumed = false;
|
||||||
|
|
||||||
|
private constructor(private readonly state: HybridPromiseState<T>) {
|
||||||
|
if (state.mode === "sync" && state.status === "rejected") {
|
||||||
|
queueMicrotask(() => {
|
||||||
|
if (!this.isConsumed) {
|
||||||
|
throw state.reason;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
isSync(): boolean {
|
||||||
|
return this.state.mode === "sync";
|
||||||
|
}
|
||||||
|
|
||||||
|
toPromise(): Promise<T> {
|
||||||
|
this.isConsumed = true;
|
||||||
|
|
||||||
|
if (this.state.mode === "async") return this.state.promise;
|
||||||
|
return this.state.status === "fulfilled"
|
||||||
|
? Promise.resolve(this.state.value)
|
||||||
|
: Promise.reject(this.state.reason);
|
||||||
|
}
|
||||||
|
|
||||||
|
static resolve<T>(value: MaybePromise<T>): HybridPromise<T> {
|
||||||
|
if (value instanceof HybridPromise) return value;
|
||||||
|
return new HybridPromise(
|
||||||
|
value instanceof Promise
|
||||||
|
? { mode: "async", promise: value }
|
||||||
|
: { mode: "sync", status: "fulfilled", value },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
static reject<T = never>(reason?: unknown): HybridPromise<T> {
|
||||||
|
return new HybridPromise({ mode: "sync", status: "rejected", reason });
|
||||||
|
}
|
||||||
|
|
||||||
|
then<TResult1 = T, TResult2 = never>(
|
||||||
|
onfulfilled?: ((value: T) => MaybePromise<TResult1>) | null | undefined,
|
||||||
|
onrejected?: ((reason: unknown) => MaybePromise<TResult2>) | null | undefined,
|
||||||
|
): HybridPromise<TResult1 | TResult2> {
|
||||||
|
this.isConsumed = true;
|
||||||
|
|
||||||
|
if (this.state.mode === "async") {
|
||||||
|
return new HybridPromise({
|
||||||
|
mode: "async",
|
||||||
|
promise: this.state.promise.then(onfulfilled, onrejected) as any,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
if (this.state.status === "fulfilled") {
|
||||||
|
if (!onfulfilled) return HybridPromise.resolve(this.state.value as any);
|
||||||
|
return HybridPromise.resolve(onfulfilled(this.state.value));
|
||||||
|
} else {
|
||||||
|
if (!onrejected) return HybridPromise.reject(this.state.reason);
|
||||||
|
return HybridPromise.resolve(onrejected(this.state.reason));
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
return HybridPromise.reject(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
catch<TResult = never>(
|
||||||
|
onrejected?: ((reason: unknown) => MaybePromise<TResult>) | null | undefined,
|
||||||
|
): HybridPromise<T | TResult> {
|
||||||
|
return this.then<T, TResult>(null, onrejected);
|
||||||
|
}
|
||||||
|
|
||||||
|
finally(onfinally?: (() => void) | null | undefined): HybridPromise<T> {
|
||||||
|
this.isConsumed = true;
|
||||||
|
|
||||||
|
if (this.state.mode === "async") {
|
||||||
|
return new HybridPromise({ mode: "async", promise: this.state.promise.finally(onfinally) });
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
onfinally?.();
|
||||||
|
return new HybridPromise(this.state);
|
||||||
|
} catch (e) {
|
||||||
|
return HybridPromise.reject(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
export * from "./format";
|
export * from "./format";
|
||||||
export * from "./gotoStateful";
|
export * from "./gotoStateful";
|
||||||
export * from "./promise";
|
export * from "./HybridPromise";
|
||||||
export * from "./sort";
|
export * from "./sort";
|
||||||
|
|||||||
@@ -1,16 +0,0 @@
|
|||||||
export const monotonicResolve = <T>(
|
|
||||||
promises: (Promise<T> | false)[],
|
|
||||||
callback: (value: T) => void,
|
|
||||||
) => {
|
|
||||||
let latestResolvedIndex = -1;
|
|
||||||
promises
|
|
||||||
.filter((promise) => !!promise)
|
|
||||||
.forEach((promise, index) => {
|
|
||||||
promise.then((value) => {
|
|
||||||
if (index > latestResolvedIndex) {
|
|
||||||
latestResolvedIndex = index;
|
|
||||||
callback(value);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
});
|
|
||||||
};
|
|
||||||
@@ -9,6 +9,7 @@
|
|||||||
import { captureVideoThumbnail } from "$lib/modules/thumbnail";
|
import { captureVideoThumbnail } from "$lib/modules/thumbnail";
|
||||||
import { getFileDownloadState } from "$lib/modules/file";
|
import { getFileDownloadState } from "$lib/modules/file";
|
||||||
import { masterKeyStore } from "$lib/stores";
|
import { masterKeyStore } from "$lib/stores";
|
||||||
|
import { HybridPromise } from "$lib/utils";
|
||||||
import AddToCategoryBottomSheet from "./AddToCategoryBottomSheet.svelte";
|
import AddToCategoryBottomSheet from "./AddToCategoryBottomSheet.svelte";
|
||||||
import DownloadStatus from "./DownloadStatus.svelte";
|
import DownloadStatus from "./DownloadStatus.svelte";
|
||||||
import {
|
import {
|
||||||
@@ -26,8 +27,7 @@
|
|||||||
|
|
||||||
let { data } = $props();
|
let { data } = $props();
|
||||||
|
|
||||||
let infoPromise: Promise<MaybeFileInfo> | undefined = $state();
|
let info: MaybeFileInfo | undefined = $state();
|
||||||
let info: FileInfo | null = $state(null);
|
|
||||||
let downloadState = $derived(getFileDownloadState(data.id));
|
let downloadState = $derived(getFileDownloadState(data.id));
|
||||||
|
|
||||||
let isMenuOpen = $state(false);
|
let isMenuOpen = $state(false);
|
||||||
@@ -65,22 +65,20 @@
|
|||||||
const addToCategory = async (categoryId: number) => {
|
const addToCategory = async (categoryId: number) => {
|
||||||
await requestFileAdditionToCategory(data.id, categoryId);
|
await requestFileAdditionToCategory(data.id, categoryId);
|
||||||
isAddToCategoryBottomSheetOpen = false;
|
isAddToCategoryBottomSheetOpen = false;
|
||||||
infoPromise = getFileInfo(data.id, $masterKeyStore?.get(1)?.key!); // TODO: FIXME
|
void getFileInfo(data.id, $masterKeyStore?.get(1)?.key!); // TODO: FIXME
|
||||||
};
|
};
|
||||||
|
|
||||||
const removeFromCategory = async (categoryId: number) => {
|
const removeFromCategory = async (categoryId: number) => {
|
||||||
await requestFileRemovalFromCategory(data.id, categoryId);
|
await requestFileRemovalFromCategory(data.id, categoryId);
|
||||||
infoPromise = getFileInfo(data.id, $masterKeyStore?.get(1)?.key!); // TODO: FIXME
|
void getFileInfo(data.id, $masterKeyStore?.get(1)?.key!); // TODO: FIXME
|
||||||
};
|
};
|
||||||
|
|
||||||
$effect(() => {
|
$effect(() => {
|
||||||
infoPromise = getFileInfo(data.id, $masterKeyStore?.get(1)?.key!).then((fileInfo) => {
|
HybridPromise.resolve(getFileInfo(data.id, $masterKeyStore?.get(1)?.key!)).then((result) => {
|
||||||
if (fileInfo.exists) {
|
if (data.id === result.id) {
|
||||||
info = fileInfo;
|
info = result;
|
||||||
}
|
}
|
||||||
return fileInfo;
|
|
||||||
});
|
});
|
||||||
info = null;
|
|
||||||
isDownloadRequested = false;
|
isDownloadRequested = false;
|
||||||
viewerType = undefined;
|
viewerType = undefined;
|
||||||
});
|
});
|
||||||
@@ -111,8 +109,8 @@
|
|||||||
});
|
});
|
||||||
|
|
||||||
$effect(() => {
|
$effect(() => {
|
||||||
if (info && downloadState?.status === "decrypted") {
|
if (info?.exists && downloadState?.status === "decrypted") {
|
||||||
untrack(() => !isDownloadRequested && updateViewer(downloadState.result!, info!.contentType));
|
untrack(() => !isDownloadRequested && updateViewer(downloadState.result!, info!.contentIv!));
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -123,8 +121,7 @@
|
|||||||
<title>파일</title>
|
<title>파일</title>
|
||||||
</svelte:head>
|
</svelte:head>
|
||||||
|
|
||||||
{#if info}
|
<TopBar title={info?.name}>
|
||||||
<TopBar title={info.name}>
|
|
||||||
<!-- svelte-ignore a11y_no_static_element_interactions -->
|
<!-- svelte-ignore a11y_no_static_element_interactions -->
|
||||||
<!-- svelte-ignore a11y_click_events_have_key_events -->
|
<!-- svelte-ignore a11y_click_events_have_key_events -->
|
||||||
<div onclick={(e) => e.stopPropagation()}>
|
<div onclick={(e) => e.stopPropagation()}>
|
||||||
@@ -137,10 +134,10 @@
|
|||||||
<TopBarMenu
|
<TopBarMenu
|
||||||
bind:isOpen={isMenuOpen}
|
bind:isOpen={isMenuOpen}
|
||||||
directoryId={["category", "gallery"].includes(page.url.searchParams.get("from") ?? "")
|
directoryId={["category", "gallery"].includes(page.url.searchParams.get("from") ?? "")
|
||||||
? info.parentId
|
? info?.parentId
|
||||||
: undefined}
|
: undefined}
|
||||||
{fileBlob}
|
{fileBlob}
|
||||||
filename={info.name}
|
filename={info?.name}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
</TopBar>
|
</TopBar>
|
||||||
@@ -149,7 +146,7 @@
|
|||||||
{#if downloadState}
|
{#if downloadState}
|
||||||
<DownloadStatus state={downloadState} />
|
<DownloadStatus state={downloadState} />
|
||||||
{/if}
|
{/if}
|
||||||
{#if viewerType}
|
{#if info && viewerType}
|
||||||
<div class="flex w-full justify-center">
|
<div class="flex w-full justify-center">
|
||||||
{#snippet viewerLoading(message: string)}
|
{#snippet viewerLoading(message: string)}
|
||||||
<p class="text-gray-500">{message}</p>
|
<p class="text-gray-500">{message}</p>
|
||||||
@@ -183,7 +180,7 @@
|
|||||||
<p class="text-lg font-bold">카테고리</p>
|
<p class="text-lg font-bold">카테고리</p>
|
||||||
<div class="space-y-1">
|
<div class="space-y-1">
|
||||||
<Categories
|
<Categories
|
||||||
categories={info.categories}
|
categories={info?.categories ?? []}
|
||||||
categoryMenuIcon={IconClose}
|
categoryMenuIcon={IconClose}
|
||||||
onCategoryClick={({ id }) => goto(`/category/${id}`)}
|
onCategoryClick={({ id }) => goto(`/category/${id}`)}
|
||||||
onCategoryMenuClick={({ id }) => removeFromCategory(id)}
|
onCategoryMenuClick={({ id }) => removeFromCategory(id)}
|
||||||
@@ -206,4 +203,3 @@
|
|||||||
bind:isOpen={isAddToCategoryBottomSheetOpen}
|
bind:isOpen={isAddToCategoryBottomSheetOpen}
|
||||||
onAddToCategoryClick={addToCategory}
|
onAddToCategoryClick={addToCategory}
|
||||||
/>
|
/>
|
||||||
{/if}
|
|
||||||
|
|||||||
@@ -4,6 +4,7 @@
|
|||||||
import { CategoryCreateModal } from "$lib/components/organisms";
|
import { CategoryCreateModal } from "$lib/components/organisms";
|
||||||
import { getCategoryInfo, type MaybeCategoryInfo } from "$lib/modules/filesystem";
|
import { getCategoryInfo, type MaybeCategoryInfo } from "$lib/modules/filesystem";
|
||||||
import { masterKeyStore } from "$lib/stores";
|
import { masterKeyStore } from "$lib/stores";
|
||||||
|
import { HybridPromise } from "$lib/utils";
|
||||||
import { requestCategoryCreation } from "./service";
|
import { requestCategoryCreation } from "./service";
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
@@ -13,18 +14,19 @@
|
|||||||
|
|
||||||
let { onAddToCategoryClick, isOpen = $bindable() }: Props = $props();
|
let { onAddToCategoryClick, isOpen = $bindable() }: Props = $props();
|
||||||
|
|
||||||
let categoryInfoPromise: Promise<MaybeCategoryInfo> | undefined = $state();
|
let categoryInfo: MaybeCategoryInfo | undefined = $state();
|
||||||
|
|
||||||
let isCategoryCreateModalOpen = $state(false);
|
let isCategoryCreateModalOpen = $state(false);
|
||||||
|
|
||||||
$effect(() => {
|
$effect(() => {
|
||||||
if (isOpen) {
|
if (isOpen) {
|
||||||
categoryInfoPromise = getCategoryInfo("root", $masterKeyStore?.get(1)?.key!);
|
HybridPromise.resolve(getCategoryInfo("root", $masterKeyStore?.get(1)?.key!)).then(
|
||||||
|
(result) => (categoryInfo = result),
|
||||||
|
);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
{#await categoryInfoPromise then categoryInfo}
|
|
||||||
{#if categoryInfo?.exists}
|
{#if categoryInfo?.exists}
|
||||||
<BottomSheet bind:isOpen class="flex flex-col">
|
<BottomSheet bind:isOpen class="flex flex-col">
|
||||||
<FullscreenDiv>
|
<FullscreenDiv>
|
||||||
@@ -32,29 +34,30 @@
|
|||||||
class="py-4"
|
class="py-4"
|
||||||
info={categoryInfo}
|
info={categoryInfo}
|
||||||
onSubCategoryClick={({ id }) =>
|
onSubCategoryClick={({ id }) =>
|
||||||
(categoryInfoPromise = getCategoryInfo(id, $masterKeyStore?.get(1)?.key!))}
|
HybridPromise.resolve(getCategoryInfo(id, $masterKeyStore?.get(1)?.key!)).then(
|
||||||
|
(result) => (categoryInfo = result),
|
||||||
|
)}
|
||||||
onSubCategoryCreateClick={() => (isCategoryCreateModalOpen = true)}
|
onSubCategoryCreateClick={() => (isCategoryCreateModalOpen = true)}
|
||||||
subCategoryCreatePosition="top"
|
subCategoryCreatePosition="top"
|
||||||
/>
|
/>
|
||||||
{#if categoryInfo.id !== "root"}
|
{#if categoryInfo.id !== "root"}
|
||||||
<BottomDiv>
|
<BottomDiv>
|
||||||
<Button onclick={() => onAddToCategoryClick(categoryInfo.id)} class="w-full">
|
<Button onclick={() => onAddToCategoryClick(categoryInfo!.id as number)} class="w-full">
|
||||||
이 카테고리에 추가하기
|
{categoryInfo!.name} 카테고리에 추가하기
|
||||||
</Button>
|
</Button>
|
||||||
</BottomDiv>
|
</BottomDiv>
|
||||||
{/if}
|
{/if}
|
||||||
</FullscreenDiv>
|
</FullscreenDiv>
|
||||||
</BottomSheet>
|
</BottomSheet>
|
||||||
|
{/if}
|
||||||
|
|
||||||
<CategoryCreateModal
|
<CategoryCreateModal
|
||||||
bind:isOpen={isCategoryCreateModalOpen}
|
bind:isOpen={isCategoryCreateModalOpen}
|
||||||
onCreateClick={async (name: string) => {
|
onCreateClick={async (name: string) => {
|
||||||
if (await requestCategoryCreation(name, categoryInfo.id, $masterKeyStore?.get(1)!)) {
|
if (await requestCategoryCreation(name, categoryInfo!.id, $masterKeyStore?.get(1)!)) {
|
||||||
categoryInfoPromise = getCategoryInfo(categoryInfo.id, $masterKeyStore?.get(1)?.key!); // TODO: FIXME
|
void getCategoryInfo(categoryInfo!.id, $masterKeyStore?.get(1)?.key!); // TODO: FIXME
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
return false;
|
return false;
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
{/if}
|
|
||||||
{/await}
|
|
||||||
|
|||||||
@@ -1,15 +1,54 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import { onMount } from "svelte";
|
import { onMount } from "svelte";
|
||||||
import { goto } from "$app/navigation";
|
import { goto } from "$app/navigation";
|
||||||
import { FullscreenDiv } from "$lib/components/atoms";
|
import { FileThumbnailButton, FullscreenDiv, RowVirtualizer } from "$lib/components/atoms";
|
||||||
import { TopBar } from "$lib/components/molecules";
|
import { TopBar } from "$lib/components/molecules";
|
||||||
import { Gallery } from "$lib/components/organisms";
|
import {
|
||||||
import { bulkGetFileInfo, type MaybeFileInfo } from "$lib/modules/filesystem";
|
bulkGetFileInfo,
|
||||||
|
type MaybeFileInfo,
|
||||||
|
type SummarizedFileInfo,
|
||||||
|
} from "$lib/modules/filesystem";
|
||||||
import { masterKeyStore } from "$lib/stores";
|
import { masterKeyStore } from "$lib/stores";
|
||||||
|
import { formatDate, formatDateSortable, SortBy, sortEntries } from "$lib/utils";
|
||||||
|
|
||||||
let { data } = $props();
|
let { data } = $props();
|
||||||
|
|
||||||
|
type Row =
|
||||||
|
| { type: "header"; label: string }
|
||||||
|
| { type: "items"; files: SummarizedFileInfo[]; isLast: boolean };
|
||||||
|
|
||||||
let files: MaybeFileInfo[] = $state([]);
|
let files: MaybeFileInfo[] = $state([]);
|
||||||
|
let rows: Row[] = $derived.by(() => {
|
||||||
|
const groups = Map.groupBy(
|
||||||
|
files
|
||||||
|
.filter((file) => file.exists)
|
||||||
|
.filter(
|
||||||
|
(file) => file.contentType.startsWith("image/") || file.contentType.startsWith("video/"),
|
||||||
|
)
|
||||||
|
.map((file) => ({ ...file, date: file.createdAt ?? file.lastModifiedAt })),
|
||||||
|
(file) => formatDateSortable(file.date),
|
||||||
|
);
|
||||||
|
return Array.from(groups.entries())
|
||||||
|
.sort(([dateA], [dateB]) => dateB.localeCompare(dateA))
|
||||||
|
.flatMap(([, entries]) => {
|
||||||
|
const sortedEntries = sortEntries([...entries], SortBy.DATE_DESC);
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
type: "header",
|
||||||
|
label: formatDate(sortedEntries[0]!.date),
|
||||||
|
},
|
||||||
|
...Array.from({ length: Math.ceil(sortedEntries.length / 4) }, (_, i) => {
|
||||||
|
const start = i * 4;
|
||||||
|
const end = start + 4;
|
||||||
|
return {
|
||||||
|
type: "items" as const,
|
||||||
|
files: sortedEntries.slice(start, end),
|
||||||
|
isLast: end >= sortedEntries.length,
|
||||||
|
};
|
||||||
|
}),
|
||||||
|
];
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
onMount(async () => {
|
onMount(async () => {
|
||||||
files = Array.from((await bulkGetFileInfo(data.files, $masterKeyStore?.get(1)?.key!)).values());
|
files = Array.from((await bulkGetFileInfo(data.files, $masterKeyStore?.get(1)?.key!)).values());
|
||||||
@@ -22,8 +61,37 @@
|
|||||||
|
|
||||||
<TopBar title="사진 및 동영상" />
|
<TopBar title="사진 및 동영상" />
|
||||||
<FullscreenDiv>
|
<FullscreenDiv>
|
||||||
<Gallery
|
<RowVirtualizer
|
||||||
files={files.filter((file) => file?.exists)}
|
count={rows.length}
|
||||||
onFileClick={({ id }) => goto(`/file/${id}?from=gallery`)}
|
itemHeight={(index) =>
|
||||||
|
rows[index]!.type === "header" ? 28 : 181 + (rows[index]!.isLast ? 16 : 4)}
|
||||||
|
class="flex flex-grow flex-col"
|
||||||
|
>
|
||||||
|
{#snippet item(index)}
|
||||||
|
{@const row = rows[index]!}
|
||||||
|
{#if row.type === "header"}
|
||||||
|
<p class="pb-2 text-sm font-medium">{row.label}</p>
|
||||||
|
{:else}
|
||||||
|
<div class={["grid grid-cols-4 gap-x-1", row.isLast ? "pb-4" : "pb-1"]}>
|
||||||
|
{#each row.files as file (file.id)}
|
||||||
|
<FileThumbnailButton
|
||||||
|
info={file}
|
||||||
|
onclick={() => goto(`/file/${file.id}?from=gallery`)}
|
||||||
/>
|
/>
|
||||||
|
{/each}
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
{/snippet}
|
||||||
|
{#snippet placeholder()}
|
||||||
|
<div class="flex h-full flex-grow items-center justify-center">
|
||||||
|
<p class="text-gray-500">
|
||||||
|
{#if files.length === 0}
|
||||||
|
업로드된 파일이 없어요.
|
||||||
|
{:else}
|
||||||
|
사진 또는 동영상이 없어요.
|
||||||
|
{/if}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
{/snippet}
|
||||||
|
</RowVirtualizer>
|
||||||
</FullscreenDiv>
|
</FullscreenDiv>
|
||||||
|
|||||||
@@ -1,12 +1,16 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import { goto } from "$app/navigation";
|
import { goto } from "$app/navigation";
|
||||||
import { TopBar } from "$lib/components/molecules";
|
import { CheckBox, RowVirtualizer } from "$lib/components/atoms";
|
||||||
import { Category, CategoryCreateModal } from "$lib/components/organisms";
|
import { SubCategories, TopBar } from "$lib/components/molecules";
|
||||||
|
import { CategoryCreateModal } from "$lib/components/organisms";
|
||||||
|
import { updateCategoryInfo } from "$lib/indexedDB";
|
||||||
import { getCategoryInfo, type MaybeCategoryInfo } from "$lib/modules/filesystem";
|
import { getCategoryInfo, type MaybeCategoryInfo } from "$lib/modules/filesystem";
|
||||||
import { masterKeyStore } from "$lib/stores";
|
import { masterKeyStore } from "$lib/stores";
|
||||||
|
import { HybridPromise, sortEntries } from "$lib/utils";
|
||||||
import CategoryDeleteModal from "./CategoryDeleteModal.svelte";
|
import CategoryDeleteModal from "./CategoryDeleteModal.svelte";
|
||||||
import CategoryMenuBottomSheet from "./CategoryMenuBottomSheet.svelte";
|
import CategoryMenuBottomSheet from "./CategoryMenuBottomSheet.svelte";
|
||||||
import CategoryRenameModal from "./CategoryRenameModal.svelte";
|
import CategoryRenameModal from "./CategoryRenameModal.svelte";
|
||||||
|
import File from "./File.svelte";
|
||||||
import {
|
import {
|
||||||
createContext,
|
createContext,
|
||||||
requestCategoryCreation,
|
requestCategoryCreation,
|
||||||
@@ -15,18 +19,50 @@
|
|||||||
requestCategoryDeletion,
|
requestCategoryDeletion,
|
||||||
} from "./service.svelte";
|
} from "./service.svelte";
|
||||||
|
|
||||||
|
import IconMoreVert from "~icons/material-symbols/more-vert";
|
||||||
|
|
||||||
let { data } = $props();
|
let { data } = $props();
|
||||||
let context = createContext();
|
let context = createContext();
|
||||||
|
|
||||||
let infoPromise: Promise<MaybeCategoryInfo> | undefined = $state();
|
let info: MaybeCategoryInfo | undefined = $state();
|
||||||
|
|
||||||
let isCategoryCreateModalOpen = $state(false);
|
let isCategoryCreateModalOpen = $state(false);
|
||||||
let isCategoryMenuBottomSheetOpen = $state(false);
|
let isCategoryMenuBottomSheetOpen = $state(false);
|
||||||
let isCategoryRenameModalOpen = $state(false);
|
let isCategoryRenameModalOpen = $state(false);
|
||||||
let isCategoryDeleteModalOpen = $state(false);
|
let isCategoryDeleteModalOpen = $state(false);
|
||||||
|
|
||||||
|
let lastCategoryId: CategoryId | undefined = $state();
|
||||||
|
let lastIsFileRecursive: boolean | undefined = $state();
|
||||||
|
|
||||||
|
let files = $derived(
|
||||||
|
sortEntries(
|
||||||
|
info?.files
|
||||||
|
?.map((file) => ({ name: file.name, details: file }))
|
||||||
|
.filter(({ details }) => info?.isFileRecursive || !details.isRecursive) ?? [],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
$effect(() => {
|
$effect(() => {
|
||||||
infoPromise = getCategoryInfo(data.id, $masterKeyStore?.get(1)?.key!);
|
if (!info || info.id === "root" || info.isFileRecursive === undefined) return;
|
||||||
|
if (lastCategoryId !== info.id) {
|
||||||
|
lastCategoryId = info.id;
|
||||||
|
lastIsFileRecursive = info.isFileRecursive;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (lastIsFileRecursive === info.isFileRecursive) return;
|
||||||
|
|
||||||
|
lastIsFileRecursive = info.isFileRecursive;
|
||||||
|
void updateCategoryInfo(info.id, { isFileRecursive: info.isFileRecursive });
|
||||||
|
});
|
||||||
|
|
||||||
|
$effect(() => {
|
||||||
|
HybridPromise.resolve(getCategoryInfo(data.id, $masterKeyStore?.get(1)?.key!)).then(
|
||||||
|
(result) => {
|
||||||
|
if (data.id === result.id) {
|
||||||
|
info = result;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
});
|
});
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
@@ -34,34 +70,64 @@
|
|||||||
<title>카테고리</title>
|
<title>카테고리</title>
|
||||||
</svelte:head>
|
</svelte:head>
|
||||||
|
|
||||||
{#await infoPromise then info}
|
{#if info?.id !== "root"}
|
||||||
{#if info?.exists}
|
<TopBar title={info?.name} />
|
||||||
{#if info.id !== "root"}
|
|
||||||
<TopBar title={info.name} />
|
|
||||||
{/if}
|
{/if}
|
||||||
<div class="min-h-full bg-gray-100 pb-[5.5em]">
|
<div class="min-h-full bg-gray-100 pb-[5.5em]">
|
||||||
<Category
|
{#if info?.exists}
|
||||||
bind:isFileRecursive={info.isFileRecursive}
|
<div class="space-y-4">
|
||||||
|
<div class="space-y-4 bg-white p-4">
|
||||||
|
{#if info.id !== "root"}
|
||||||
|
<p class="text-lg font-bold text-gray-800">하위 카테고리</p>
|
||||||
|
{/if}
|
||||||
|
<SubCategories
|
||||||
{info}
|
{info}
|
||||||
onFileClick={({ id }) => goto(`/file/${id}?from=category`)}
|
|
||||||
onFileRemoveClick={async ({ id }) => {
|
|
||||||
await requestFileRemovalFromCategory(id, data.id as number);
|
|
||||||
infoPromise = getCategoryInfo(data.id, $masterKeyStore?.get(1)?.key!); // TODO: FIXME
|
|
||||||
}}
|
|
||||||
onSubCategoryClick={({ id }) => goto(`/category/${id}`)}
|
onSubCategoryClick={({ id }) => goto(`/category/${id}`)}
|
||||||
onSubCategoryCreateClick={() => (isCategoryCreateModalOpen = true)}
|
onSubCategoryCreateClick={() => (isCategoryCreateModalOpen = true)}
|
||||||
onSubCategoryMenuClick={(subCategory) => {
|
onSubCategoryMenuClick={(subCategory) => {
|
||||||
context.selectedCategory = subCategory;
|
context.selectedCategory = subCategory;
|
||||||
isCategoryMenuBottomSheetOpen = true;
|
isCategoryMenuBottomSheetOpen = true;
|
||||||
}}
|
}}
|
||||||
|
subCategoryMenuIcon={IconMoreVert}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
{#if info.id !== "root"}
|
||||||
|
<div class="space-y-4 bg-white p-4">
|
||||||
|
<div class="flex items-center justify-between">
|
||||||
|
<p class="text-lg font-bold text-gray-800">파일</p>
|
||||||
|
<CheckBox bind:checked={info.isFileRecursive}>
|
||||||
|
<p class="font-medium">하위 카테고리의 파일</p>
|
||||||
|
</CheckBox>
|
||||||
|
</div>
|
||||||
|
<RowVirtualizer count={files.length} itemHeight={() => 48} itemGap={4}>
|
||||||
|
{#snippet item(index)}
|
||||||
|
{@const { details } = files[index]!}
|
||||||
|
<File
|
||||||
|
info={details}
|
||||||
|
onclick={({ id }) => goto(`/file/${id}?from=category`)}
|
||||||
|
onRemoveClick={!details.isRecursive
|
||||||
|
? async ({ id }) => {
|
||||||
|
await requestFileRemovalFromCategory(id, data.id as number);
|
||||||
|
void getCategoryInfo(data.id, $masterKeyStore?.get(1)?.key!); // TODO: FIXME
|
||||||
|
}
|
||||||
|
: undefined}
|
||||||
|
/>
|
||||||
|
{/snippet}
|
||||||
|
{#snippet placeholder()}
|
||||||
|
<p class="text-center text-gray-500">이 카테고리에 추가된 파일이 없어요.</p>
|
||||||
|
{/snippet}
|
||||||
|
</RowVirtualizer>
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
|
||||||
<CategoryCreateModal
|
<CategoryCreateModal
|
||||||
bind:isOpen={isCategoryCreateModalOpen}
|
bind:isOpen={isCategoryCreateModalOpen}
|
||||||
onCreateClick={async (name: string) => {
|
onCreateClick={async (name: string) => {
|
||||||
if (await requestCategoryCreation(name, data.id, $masterKeyStore?.get(1)!)) {
|
if (await requestCategoryCreation(name, data.id, $masterKeyStore?.get(1)!)) {
|
||||||
infoPromise = getCategoryInfo(data.id, $masterKeyStore?.get(1)?.key!); // TODO: FIXME
|
void getCategoryInfo(data.id, $masterKeyStore?.get(1)?.key!); // TODO: FIXME
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
return false;
|
return false;
|
||||||
@@ -83,7 +149,7 @@
|
|||||||
bind:isOpen={isCategoryRenameModalOpen}
|
bind:isOpen={isCategoryRenameModalOpen}
|
||||||
onRenameClick={async (newName: string) => {
|
onRenameClick={async (newName: string) => {
|
||||||
if (await requestCategoryRename(context.selectedCategory!, newName)) {
|
if (await requestCategoryRename(context.selectedCategory!, newName)) {
|
||||||
infoPromise = getCategoryInfo(data.id, $masterKeyStore?.get(1)?.key!); // TODO: FIXME
|
void getCategoryInfo(data.id, $masterKeyStore?.get(1)?.key!); // TODO: FIXME
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
return false;
|
return false;
|
||||||
@@ -93,11 +159,9 @@
|
|||||||
bind:isOpen={isCategoryDeleteModalOpen}
|
bind:isOpen={isCategoryDeleteModalOpen}
|
||||||
onDeleteClick={async () => {
|
onDeleteClick={async () => {
|
||||||
if (await requestCategoryDeletion(context.selectedCategory!)) {
|
if (await requestCategoryDeletion(context.selectedCategory!)) {
|
||||||
infoPromise = getCategoryInfo(data.id, $masterKeyStore?.get(1)?.key!); // TODO: FIXME
|
void getCategoryInfo(data.id, $masterKeyStore?.get(1)?.key!); // TODO: FIXME
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
return false;
|
return false;
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
{/if}
|
|
||||||
{/await}
|
|
||||||
|
|||||||
@@ -1,10 +1,9 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import { browser } from "$app/environment";
|
|
||||||
import { ActionEntryButton } from "$lib/components/atoms";
|
import { ActionEntryButton } from "$lib/components/atoms";
|
||||||
import { DirectoryEntryLabel } from "$lib/components/molecules";
|
import { DirectoryEntryLabel } from "$lib/components/molecules";
|
||||||
|
import { getFileThumbnail } from "$lib/modules/file";
|
||||||
import type { CategoryFileInfo } from "$lib/modules/filesystem";
|
import type { CategoryFileInfo } from "$lib/modules/filesystem";
|
||||||
import { requestFileThumbnailDownload } from "$lib/services/file";
|
import type { SelectedFile } from "./service.svelte";
|
||||||
import type { SelectedFile } from "./service";
|
|
||||||
|
|
||||||
import IconClose from "~icons/material-symbols/close";
|
import IconClose from "~icons/material-symbols/close";
|
||||||
|
|
||||||
@@ -16,12 +15,7 @@
|
|||||||
|
|
||||||
let { info, onclick, onRemoveClick }: Props = $props();
|
let { info, onclick, onRemoveClick }: Props = $props();
|
||||||
|
|
||||||
let showThumbnail = $derived(
|
let thumbnail = $derived(getFileThumbnail(info));
|
||||||
browser && (info.contentType.startsWith("image/") || info.contentType.startsWith("video/")),
|
|
||||||
);
|
|
||||||
let thumbnailPromise = $derived(
|
|
||||||
showThumbnail ? requestFileThumbnailDownload(info.id, info.dataKey?.key) : null,
|
|
||||||
);
|
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<ActionEntryButton
|
<ActionEntryButton
|
||||||
@@ -30,9 +24,5 @@
|
|||||||
actionButtonIcon={onRemoveClick && IconClose}
|
actionButtonIcon={onRemoveClick && IconClose}
|
||||||
onActionButtonClick={() => onRemoveClick?.(info)}
|
onActionButtonClick={() => onRemoveClick?.(info)}
|
||||||
>
|
>
|
||||||
{#await thumbnailPromise}
|
<DirectoryEntryLabel type="file" thumbnail={$thumbnail} name={info.name} />
|
||||||
<DirectoryEntryLabel type="file" name={info.name} />
|
|
||||||
{:then thumbnail}
|
|
||||||
<DirectoryEntryLabel type="file" thumbnail={thumbnail ?? undefined} name={info.name} />
|
|
||||||
{/await}
|
|
||||||
</ActionEntryButton>
|
</ActionEntryButton>
|
||||||
@@ -5,6 +5,11 @@ import { trpc } from "$trpc/client";
|
|||||||
|
|
||||||
export { requestCategoryCreation, requestFileRemovalFromCategory } from "$lib/services/category";
|
export { requestCategoryCreation, requestFileRemovalFromCategory } from "$lib/services/category";
|
||||||
|
|
||||||
|
export interface SelectedFile {
|
||||||
|
id: number;
|
||||||
|
name: string;
|
||||||
|
}
|
||||||
|
|
||||||
export const createContext = () => {
|
export const createContext = () => {
|
||||||
const context = $state({
|
const context = $state({
|
||||||
selectedCategory: undefined as SelectedCategory | undefined,
|
selectedCategory: undefined as SelectedCategory | undefined,
|
||||||
|
|||||||
@@ -6,6 +6,7 @@
|
|||||||
import { TopBar } from "$lib/components/molecules";
|
import { TopBar } from "$lib/components/molecules";
|
||||||
import { getDirectoryInfo, type MaybeDirectoryInfo } from "$lib/modules/filesystem";
|
import { getDirectoryInfo, type MaybeDirectoryInfo } from "$lib/modules/filesystem";
|
||||||
import { masterKeyStore, hmacSecretStore } from "$lib/stores";
|
import { masterKeyStore, hmacSecretStore } from "$lib/stores";
|
||||||
|
import { HybridPromise } from "$lib/utils";
|
||||||
import DirectoryCreateModal from "./DirectoryCreateModal.svelte";
|
import DirectoryCreateModal from "./DirectoryCreateModal.svelte";
|
||||||
import DirectoryEntries from "./DirectoryEntries";
|
import DirectoryEntries from "./DirectoryEntries";
|
||||||
import DownloadStatusCard from "./DownloadStatusCard.svelte";
|
import DownloadStatusCard from "./DownloadStatusCard.svelte";
|
||||||
@@ -29,7 +30,7 @@
|
|||||||
let { data } = $props();
|
let { data } = $props();
|
||||||
let context = createContext();
|
let context = createContext();
|
||||||
|
|
||||||
let infoPromise: Promise<MaybeDirectoryInfo> | undefined = $state();
|
let info: MaybeDirectoryInfo | undefined = $state();
|
||||||
let fileInput: HTMLInputElement | undefined = $state();
|
let fileInput: HTMLInputElement | undefined = $state();
|
||||||
let duplicatedFile: File | undefined = $state();
|
let duplicatedFile: File | undefined = $state();
|
||||||
let resolveForDuplicateFileModal: ((res: boolean) => void) | undefined = $state();
|
let resolveForDuplicateFileModal: ((res: boolean) => void) | undefined = $state();
|
||||||
@@ -60,7 +61,7 @@
|
|||||||
.then((res) => {
|
.then((res) => {
|
||||||
if (!res) return;
|
if (!res) return;
|
||||||
// TODO: FIXME
|
// TODO: FIXME
|
||||||
infoPromise = getDirectoryInfo(data.id, $masterKeyStore?.get(1)?.key!);
|
void getDirectoryInfo(data.id, $masterKeyStore?.get(1)?.key!);
|
||||||
})
|
})
|
||||||
.catch((e: Error) => {
|
.catch((e: Error) => {
|
||||||
// TODO: FIXME
|
// TODO: FIXME
|
||||||
@@ -78,7 +79,13 @@
|
|||||||
});
|
});
|
||||||
|
|
||||||
$effect(() => {
|
$effect(() => {
|
||||||
infoPromise = getDirectoryInfo(data.id, $masterKeyStore?.get(1)?.key!);
|
HybridPromise.resolve(getDirectoryInfo(data.id, $masterKeyStore?.get(1)?.key!)).then(
|
||||||
|
(result) => {
|
||||||
|
if (data.id === result.id) {
|
||||||
|
info = result;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
});
|
});
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
@@ -88,17 +95,17 @@
|
|||||||
|
|
||||||
<input bind:this={fileInput} onchange={uploadFile} type="file" multiple class="hidden" />
|
<input bind:this={fileInput} onchange={uploadFile} type="file" multiple class="hidden" />
|
||||||
|
|
||||||
{#await infoPromise then info}
|
|
||||||
{#if info?.exists}
|
|
||||||
<div class="flex h-full flex-col">
|
<div class="flex h-full flex-col">
|
||||||
{#if showTopBar}
|
{#if showTopBar}
|
||||||
<TopBar title={info.name} class="flex-shrink-0" />
|
<TopBar title={info?.name} class="flex-shrink-0" />
|
||||||
{/if}
|
{/if}
|
||||||
|
{#if info?.exists}
|
||||||
<div class={["flex flex-grow flex-col px-4 pb-4", !showTopBar && "pt-4"]}>
|
<div class={["flex flex-grow flex-col px-4 pb-4", !showTopBar && "pt-4"]}>
|
||||||
<div class="flex gap-x-2">
|
<div class="flex gap-x-2">
|
||||||
<UploadStatusCard onclick={() => goto("/file/uploads")} />
|
<UploadStatusCard onclick={() => goto("/file/uploads")} />
|
||||||
<DownloadStatusCard onclick={() => goto("/file/downloads")} />
|
<DownloadStatusCard onclick={() => goto("/file/downloads")} />
|
||||||
</div>
|
</div>
|
||||||
|
{#key info.id}
|
||||||
<DirectoryEntries
|
<DirectoryEntries
|
||||||
{info}
|
{info}
|
||||||
onEntryClick={({ type, id }) => goto(`/${type}/${id}`)}
|
onEntryClick={({ type, id }) => goto(`/${type}/${id}`)}
|
||||||
@@ -109,12 +116,14 @@
|
|||||||
showParentEntry={isFromFilePage && info.parentId !== undefined}
|
showParentEntry={isFromFilePage && info.parentId !== undefined}
|
||||||
onParentClick={() =>
|
onParentClick={() =>
|
||||||
goto(
|
goto(
|
||||||
info.parentId === "root"
|
info!.parentId === "root"
|
||||||
? "/directory?from=file"
|
? "/directory?from=file"
|
||||||
: `/directory/${info.parentId}?from=file`,
|
: `/directory/${info!.parentId}?from=file`,
|
||||||
)}
|
)}
|
||||||
/>
|
/>
|
||||||
|
{/key}
|
||||||
</div>
|
</div>
|
||||||
|
{/if}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<FloatingButton
|
<FloatingButton
|
||||||
@@ -139,7 +148,7 @@
|
|||||||
bind:isOpen={isDirectoryCreateModalOpen}
|
bind:isOpen={isDirectoryCreateModalOpen}
|
||||||
onCreateClick={async (name) => {
|
onCreateClick={async (name) => {
|
||||||
if (await requestDirectoryCreation(name, data.id, $masterKeyStore?.get(1)!)) {
|
if (await requestDirectoryCreation(name, data.id, $masterKeyStore?.get(1)!)) {
|
||||||
infoPromise = getDirectoryInfo(data.id, $masterKeyStore?.get(1)?.key!); // TODO: FIXME
|
void getDirectoryInfo(data.id, $masterKeyStore?.get(1)?.key!); // TODO: FIXME
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
return false;
|
return false;
|
||||||
@@ -173,7 +182,7 @@
|
|||||||
bind:isOpen={isEntryRenameModalOpen}
|
bind:isOpen={isEntryRenameModalOpen}
|
||||||
onRenameClick={async (newName: string) => {
|
onRenameClick={async (newName: string) => {
|
||||||
if (await requestEntryRename(context.selectedEntry!, newName)) {
|
if (await requestEntryRename(context.selectedEntry!, newName)) {
|
||||||
infoPromise = getDirectoryInfo(data.id, $masterKeyStore?.get(1)?.key!); // TODO: FIXME
|
void getDirectoryInfo(data.id, $masterKeyStore?.get(1)?.key!); // TODO: FIXME
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
return false;
|
return false;
|
||||||
@@ -183,11 +192,9 @@
|
|||||||
bind:isOpen={isEntryDeleteModalOpen}
|
bind:isOpen={isEntryDeleteModalOpen}
|
||||||
onDeleteClick={async () => {
|
onDeleteClick={async () => {
|
||||||
if (await requestEntryDeletion(context.selectedEntry!)) {
|
if (await requestEntryDeletion(context.selectedEntry!)) {
|
||||||
infoPromise = getDirectoryInfo(data.id, $masterKeyStore?.get(1)?.key!); // TODO: FIXME
|
void getDirectoryInfo(data.id, $masterKeyStore?.get(1)?.key!); // TODO: FIXME
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
return false;
|
return false;
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
{/if}
|
|
||||||
{/await}
|
|
||||||
|
|||||||
@@ -1,9 +1,8 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import { browser } from "$app/environment";
|
|
||||||
import { ActionEntryButton } from "$lib/components/atoms";
|
import { ActionEntryButton } from "$lib/components/atoms";
|
||||||
import { DirectoryEntryLabel } from "$lib/components/molecules";
|
import { DirectoryEntryLabel } from "$lib/components/molecules";
|
||||||
|
import { getFileThumbnail } from "$lib/modules/file";
|
||||||
import type { SummarizedFileInfo } from "$lib/modules/filesystem";
|
import type { SummarizedFileInfo } from "$lib/modules/filesystem";
|
||||||
import { requestFileThumbnailDownload } from "$lib/services/file";
|
|
||||||
import { formatDateTime } from "$lib/utils";
|
import { formatDateTime } from "$lib/utils";
|
||||||
import type { SelectedEntry } from "../service.svelte";
|
import type { SelectedEntry } from "../service.svelte";
|
||||||
|
|
||||||
@@ -17,12 +16,7 @@
|
|||||||
|
|
||||||
let { info, onclick, onOpenMenuClick }: Props = $props();
|
let { info, onclick, onOpenMenuClick }: Props = $props();
|
||||||
|
|
||||||
let showThumbnail = $derived(
|
let thumbnail = $derived(getFileThumbnail(info));
|
||||||
browser && (info.contentType.startsWith("image/") || info.contentType.startsWith("video/")),
|
|
||||||
);
|
|
||||||
let thumbnailPromise = $derived(
|
|
||||||
showThumbnail ? requestFileThumbnailDownload(info.id, info.dataKey?.key) : null,
|
|
||||||
);
|
|
||||||
|
|
||||||
const action = (callback: typeof onclick) => {
|
const action = (callback: typeof onclick) => {
|
||||||
callback({ type: "file", id: info.id, dataKey: info.dataKey, name: info.name });
|
callback({ type: "file", id: info.id, dataKey: info.dataKey, name: info.name });
|
||||||
@@ -35,18 +29,10 @@
|
|||||||
actionButtonIcon={IconMoreVert}
|
actionButtonIcon={IconMoreVert}
|
||||||
onActionButtonClick={() => action(onOpenMenuClick)}
|
onActionButtonClick={() => action(onOpenMenuClick)}
|
||||||
>
|
>
|
||||||
{#await thumbnailPromise}
|
|
||||||
<DirectoryEntryLabel
|
<DirectoryEntryLabel
|
||||||
type="file"
|
type="file"
|
||||||
|
thumbnail={$thumbnail}
|
||||||
name={info.name}
|
name={info.name}
|
||||||
subtext={formatDateTime(info.createdAt ?? info.lastModifiedAt)}
|
subtext={formatDateTime(info.createdAt ?? info.lastModifiedAt)}
|
||||||
/>
|
/>
|
||||||
{:then thumbnail}
|
|
||||||
<DirectoryEntryLabel
|
|
||||||
type="file"
|
|
||||||
thumbnail={thumbnail ?? undefined}
|
|
||||||
name={info.name}
|
|
||||||
subtext={formatDateTime(info.createdAt ?? info.lastModifiedAt)}
|
|
||||||
/>
|
|
||||||
{/await}
|
|
||||||
</ActionEntryButton>
|
</ActionEntryButton>
|
||||||
|
|||||||
@@ -2,22 +2,13 @@
|
|||||||
import { onMount } from "svelte";
|
import { onMount } from "svelte";
|
||||||
import { goto } from "$app/navigation";
|
import { goto } from "$app/navigation";
|
||||||
import { EntryButton, FileThumbnailButton } from "$lib/components/atoms";
|
import { EntryButton, FileThumbnailButton } from "$lib/components/atoms";
|
||||||
import { bulkGetFileInfo, type MaybeFileInfo } from "$lib/modules/filesystem";
|
import { type SummarizedFileInfo } from "$lib/modules/filesystem";
|
||||||
import { masterKeyStore } from "$lib/stores";
|
|
||||||
import { requestFreshMediaFilesRetrieval } from "./service";
|
import { requestFreshMediaFilesRetrieval } from "./service";
|
||||||
|
|
||||||
let mediaFiles: MaybeFileInfo[] = $state([]);
|
let mediaFiles: SummarizedFileInfo[] = $state([]);
|
||||||
|
|
||||||
onMount(async () => {
|
onMount(async () => {
|
||||||
const files = await requestFreshMediaFilesRetrieval();
|
mediaFiles = await requestFreshMediaFilesRetrieval();
|
||||||
mediaFiles = Array.from(
|
|
||||||
(
|
|
||||||
await bulkGetFileInfo(
|
|
||||||
files.map(({ id }) => id),
|
|
||||||
$masterKeyStore?.get(1)?.key!,
|
|
||||||
)
|
|
||||||
).values(),
|
|
||||||
);
|
|
||||||
});
|
});
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
@@ -34,9 +25,7 @@
|
|||||||
{#if mediaFiles.length > 0}
|
{#if mediaFiles.length > 0}
|
||||||
<div class="grid grid-cols-4 gap-2 p-2">
|
<div class="grid grid-cols-4 gap-2 p-2">
|
||||||
{#each mediaFiles as file (file.id)}
|
{#each mediaFiles as file (file.id)}
|
||||||
{#if file.exists}
|
|
||||||
<FileThumbnailButton info={file} onclick={({ id }) => goto(`/file/${id}`)} />
|
<FileThumbnailButton info={file} onclick={({ id }) => goto(`/file/${id}`)} />
|
||||||
{/if}
|
|
||||||
{/each}
|
{/each}
|
||||||
</div>
|
</div>
|
||||||
{/if}
|
{/if}
|
||||||
|
|||||||
@@ -46,6 +46,7 @@ const categoryRouter = router({
|
|||||||
})),
|
})),
|
||||||
files: files?.map((file) => ({
|
files: files?.map((file) => ({
|
||||||
id: file.id,
|
id: file.id,
|
||||||
|
parent: file.parentId,
|
||||||
mekVersion: file.mekVersion,
|
mekVersion: file.mekVersion,
|
||||||
dek: file.encDek,
|
dek: file.encDek,
|
||||||
dekVersion: file.dekVersion,
|
dekVersion: file.dekVersion,
|
||||||
|
|||||||
@@ -33,6 +33,7 @@ const fileRouter = router({
|
|||||||
lastModifiedAtIv: file.encLastModifiedAt.iv,
|
lastModifiedAtIv: file.encLastModifiedAt.iv,
|
||||||
categories: categories.map((category) => ({
|
categories: categories.map((category) => ({
|
||||||
id: category.id,
|
id: category.id,
|
||||||
|
parent: category.parentId,
|
||||||
mekVersion: category.mekVersion,
|
mekVersion: category.mekVersion,
|
||||||
dek: category.encDek,
|
dek: category.encDek,
|
||||||
dekVersion: category.dekVersion,
|
dekVersion: category.dekVersion,
|
||||||
@@ -66,6 +67,7 @@ const fileRouter = router({
|
|||||||
lastModifiedAtIv: file.encLastModifiedAt.iv,
|
lastModifiedAtIv: file.encLastModifiedAt.iv,
|
||||||
categories: file.categories.map((category) => ({
|
categories: file.categories.map((category) => ({
|
||||||
id: category.id,
|
id: category.id,
|
||||||
|
parent: category.parentId,
|
||||||
mekVersion: category.mekVersion,
|
mekVersion: category.mekVersion,
|
||||||
dek: category.encDek,
|
dek: category.encDek,
|
||||||
dekVersion: category.dekVersion,
|
dekVersion: category.dekVersion,
|
||||||
|
|||||||
Reference in New Issue
Block a user