mirror of
https://github.com/kmc7468/arkvault.git
synced 2026-02-04 08:06:56 +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/kit": "^2.49.2",
|
||||
"@sveltejs/vite-plugin-svelte": "^6.2.1",
|
||||
"@tanstack/svelte-virtual": "^3.13.15",
|
||||
"@tanstack/svelte-virtual": "^3.13.16",
|
||||
"@trpc/client": "^11.8.1",
|
||||
"@types/file-saver": "^2.0.7",
|
||||
"@types/ms": "^0.7.34",
|
||||
@@ -64,7 +64,7 @@
|
||||
"pg": "^8.16.3",
|
||||
"superjson": "^2.2.6",
|
||||
"uuid": "^13.0.0",
|
||||
"zod": "^4.3.4"
|
||||
"zod": "^4.3.5"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^22.0.0",
|
||||
|
||||
28
pnpm-lock.yaml
generated
28
pnpm-lock.yaml
generated
@@ -36,8 +36,8 @@ importers:
|
||||
specifier: ^13.0.0
|
||||
version: 13.0.0
|
||||
zod:
|
||||
specifier: ^4.3.4
|
||||
version: 4.3.4
|
||||
specifier: ^4.3.5
|
||||
version: 4.3.5
|
||||
devDependencies:
|
||||
'@eslint/compat':
|
||||
specifier: ^2.0.0
|
||||
@@ -58,8 +58,8 @@ importers:
|
||||
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))
|
||||
'@tanstack/svelte-virtual':
|
||||
specifier: ^3.13.15
|
||||
version: 3.13.15(svelte@5.46.1)
|
||||
specifier: ^3.13.16
|
||||
version: 3.13.16(svelte@5.46.1)
|
||||
'@trpc/client':
|
||||
specifier: ^11.8.1
|
||||
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
|
||||
vite: ^6.3.0 || ^7.0.0
|
||||
|
||||
'@tanstack/svelte-virtual@3.13.15':
|
||||
resolution: {integrity: sha512-3PPLI3hsyT70zSZhBkSIZXIarlN+GjFNKeKr2Wk1UR7EuEVtXgNlB/Zk0sYtaeJ4CvGvldQNakOvbdETnWAgeA==}
|
||||
'@tanstack/svelte-virtual@3.13.16':
|
||||
resolution: {integrity: sha512-LRDPRzAPTIiDjiCA9lhNlFnZRLj/XsNhzNRsT5JEA8hzcBmZw8avdYYVjydPAy0ObFJgG1zBAm9Dtvwqju36sg==}
|
||||
peerDependencies:
|
||||
svelte: ^3.48.0 || ^4.0.0 || ^5.0.0
|
||||
|
||||
'@tanstack/virtual-core@3.13.15':
|
||||
resolution: {integrity: sha512-8cG3acM2cSIm3h8WxboHARAhQAJbYUhvmadvnN8uz8aziDwrbYb9KiARni+uY2qrLh49ycn+poGoxvtIAKhjog==}
|
||||
'@tanstack/virtual-core@3.13.16':
|
||||
resolution: {integrity: sha512-njazUC8mDkrxWmyZmn/3eXrDcP8Msb3chSr4q6a65RmwdSbMlMCdnOphv6/8mLO7O3Fuza5s4M4DclmvAO5w0w==}
|
||||
|
||||
'@trpc/client@11.8.1':
|
||||
resolution: {integrity: sha512-L/SJFGanr9xGABmuDoeXR4xAdHJmsXsiF9OuH+apecJ+8sUITzVT1EPeqp0ebqA6lBhEl5pPfg3rngVhi/h60Q==}
|
||||
@@ -2025,8 +2025,8 @@ packages:
|
||||
zimmerframe@1.1.4:
|
||||
resolution: {integrity: sha512-B58NGBEoc8Y9MWWCQGl/gq9xBCe4IiKM0a2x7GZdQKOW5Exr8S1W24J6OgM1njK8xCRGvAJIL/MxXHf6SkmQKQ==}
|
||||
|
||||
zod@4.3.4:
|
||||
resolution: {integrity: sha512-Zw/uYiiyF6pUT1qmKbZziChgNPRu+ZRneAsMUDU6IwmXdWt5JwcUfy2bvLOCUtz5UniaN/Zx5aFttZYbYc7O/A==}
|
||||
zod@4.3.5:
|
||||
resolution: {integrity: sha512-k7Nwx6vuWx1IJ9Bjuf4Zt1PEllcwe7cls3VNzm4CQ1/hgtFUK2bRNG3rvnpPUhFjmqJKAKtjV576KnUkHocg/g==}
|
||||
|
||||
snapshots:
|
||||
|
||||
@@ -2389,12 +2389,12 @@ snapshots:
|
||||
transitivePeerDependencies:
|
||||
- supports-color
|
||||
|
||||
'@tanstack/svelte-virtual@3.13.15(svelte@5.46.1)':
|
||||
'@tanstack/svelte-virtual@3.13.16(svelte@5.46.1)':
|
||||
dependencies:
|
||||
'@tanstack/virtual-core': 3.13.15
|
||||
'@tanstack/virtual-core': 3.13.16
|
||||
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)':
|
||||
dependencies:
|
||||
@@ -3707,4 +3707,4 @@ snapshots:
|
||||
|
||||
zimmerframe@1.1.4: {}
|
||||
|
||||
zod@4.3.4: {}
|
||||
zod@4.3.5: {}
|
||||
|
||||
@@ -54,7 +54,7 @@
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
{#if placeholder && $virtualizer.getVirtualItems().length === 0}
|
||||
{#if placeholder && count === 0}
|
||||
{@render placeholder()}
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
<script lang="ts">
|
||||
import { browser } from "$app/environment";
|
||||
import { getFileThumbnail } from "$lib/modules/file";
|
||||
import type { SummarizedFileInfo } from "$lib/modules/filesystem";
|
||||
import { requestFileThumbnailDownload } from "$lib/services/file";
|
||||
|
||||
interface Props {
|
||||
info: SummarizedFileInfo;
|
||||
@@ -10,25 +9,16 @@
|
||||
|
||||
let { info, onclick }: Props = $props();
|
||||
|
||||
let showThumbnail = $derived(
|
||||
browser && (info.contentType.startsWith("image/") || info.contentType.startsWith("video/")),
|
||||
);
|
||||
let thumbnailPromise = $derived(
|
||||
showThumbnail ? requestFileThumbnailDownload(info.id, info.dataKey?.key) : null,
|
||||
);
|
||||
let thumbnail = $derived(getFileThumbnail(info));
|
||||
</script>
|
||||
|
||||
<button
|
||||
onclick={onclick && (() => setTimeout(() => onclick(info), 100))}
|
||||
class="aspect-square overflow-hidden rounded transition active:scale-95 active:brightness-90"
|
||||
>
|
||||
{#await thumbnailPromise}
|
||||
{#if $thumbnail}
|
||||
<img src={$thumbnail} alt={info.name} class="h-full w-full object-cover" />
|
||||
{:else}
|
||||
<div class="h-full w-full bg-gray-100"></div>
|
||||
{:then thumbnail}
|
||||
{#if thumbnail}
|
||||
<img src={thumbnail} alt={info.name} class="h-full w-full object-cover" />
|
||||
{:else}
|
||||
<div class="h-full w-full bg-gray-100"></div>
|
||||
{/if}
|
||||
{/await}
|
||||
{/if}
|
||||
</button>
|
||||
|
||||
@@ -25,7 +25,7 @@
|
||||
|
||||
let { categories, categoryMenuIcon, onCategoryClick, onCategoryMenuClick }: Props = $props();
|
||||
|
||||
let categoriesWithName = $derived(sortEntries($state.snapshot(categories)));
|
||||
let categoriesWithName = $derived(sortEntries([...categories]));
|
||||
</script>
|
||||
|
||||
{#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";
|
||||
|
||||
@@ -13,15 +13,15 @@ interface FileInfo {
|
||||
contentType: string;
|
||||
createdAt?: Date;
|
||||
lastModifiedAt: Date;
|
||||
categoryIds: number[];
|
||||
categoryIds?: number[];
|
||||
}
|
||||
|
||||
interface CategoryInfo {
|
||||
id: number;
|
||||
parentId: CategoryId;
|
||||
name: string;
|
||||
files: { id: number; isRecursive: boolean }[];
|
||||
isFileRecursive: boolean;
|
||||
files?: { id: number; isRecursive: boolean }[];
|
||||
isFileRecursive?: boolean;
|
||||
}
|
||||
|
||||
const filesystem = new Dexie("filesystem") as Dexie & {
|
||||
@@ -55,7 +55,7 @@ export const getDirectoryInfo = async (id: number) => {
|
||||
};
|
||||
|
||||
export const storeDirectoryInfo = async (directoryInfo: DirectoryInfo) => {
|
||||
await filesystem.directory.put(directoryInfo);
|
||||
await filesystem.directory.upsert(directoryInfo.id, { ...directoryInfo });
|
||||
};
|
||||
|
||||
export const deleteDirectoryInfo = async (id: number) => {
|
||||
@@ -89,13 +89,17 @@ export const bulkGetFileInfos = async (ids: number[]) => {
|
||||
};
|
||||
|
||||
export const storeFileInfo = async (fileInfo: FileInfo) => {
|
||||
await filesystem.file.put(fileInfo);
|
||||
await filesystem.file.upsert(fileInfo.id, { ...fileInfo });
|
||||
};
|
||||
|
||||
export const deleteFileInfo = async (id: number) => {
|
||||
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>) => {
|
||||
await filesystem.file
|
||||
.where({ parentId })
|
||||
@@ -112,7 +116,7 @@ export const getCategoryInfo = async (id: number) => {
|
||||
};
|
||||
|
||||
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 }) => {
|
||||
|
||||
@@ -1,15 +1,12 @@
|
||||
import { LRUCache } from "lru-cache";
|
||||
import {
|
||||
getFileCacheIndex as getFileCacheIndexFromIndexedDB,
|
||||
storeFileCacheIndex,
|
||||
deleteFileCacheIndex,
|
||||
type FileCacheIndex,
|
||||
} from "$lib/indexedDB";
|
||||
import { readFile, writeFile, deleteFile, deleteDirectory } from "$lib/modules/opfs";
|
||||
import { getThumbnailUrl } from "$lib/modules/thumbnail";
|
||||
import { readFile, writeFile, deleteFile } from "$lib/modules/opfs";
|
||||
|
||||
const fileCacheIndex = new Map<number, FileCacheIndex>();
|
||||
const loadedThumbnails = new LRUCache<number, string>({ max: 100 });
|
||||
|
||||
export const prepareFileCache = async () => {
|
||||
for (const cache of await getFileCacheIndexFromIndexedDB()) {
|
||||
@@ -51,30 +48,3 @@ export const deleteFileCache = async (fileId: number) => {
|
||||
await deleteFile(`/cache/${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 "./download.svelte";
|
||||
export * from "./thumbnail";
|
||||
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,77 +196,74 @@ export const uploadFile = async (
|
||||
});
|
||||
const state = uploadingFiles.at(-1)!;
|
||||
|
||||
return await scheduler.schedule(
|
||||
async () => file.size,
|
||||
async () => {
|
||||
state.status = "encryption-pending";
|
||||
return await scheduler.schedule(file.size, async () => {
|
||||
state.status = "encryption-pending";
|
||||
|
||||
try {
|
||||
const { fileBuffer, fileSigned } = await requestDuplicateFileScan(
|
||||
file,
|
||||
hmacSecret,
|
||||
onDuplicate,
|
||||
);
|
||||
if (!fileBuffer || !fileSigned) {
|
||||
state.status = "canceled";
|
||||
uploadingFiles = uploadingFiles.filter((file) => file !== state);
|
||||
return undefined;
|
||||
}
|
||||
try {
|
||||
const { fileBuffer, fileSigned } = await requestDuplicateFileScan(
|
||||
file,
|
||||
hmacSecret,
|
||||
onDuplicate,
|
||||
);
|
||||
if (!fileBuffer || !fileSigned) {
|
||||
state.status = "canceled";
|
||||
uploadingFiles = uploadingFiles.filter((file) => file !== state);
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const {
|
||||
dataKeyWrapped,
|
||||
dataKeyVersion,
|
||||
fileType,
|
||||
fileEncrypted,
|
||||
fileEncryptedHash,
|
||||
nameEncrypted,
|
||||
createdAtEncrypted,
|
||||
lastModifiedAtEncrypted,
|
||||
thumbnail,
|
||||
} = await encryptFile(state, file, fileBuffer, masterKey);
|
||||
const {
|
||||
dataKeyWrapped,
|
||||
dataKeyVersion,
|
||||
fileType,
|
||||
fileEncrypted,
|
||||
fileEncryptedHash,
|
||||
nameEncrypted,
|
||||
createdAtEncrypted,
|
||||
lastModifiedAtEncrypted,
|
||||
thumbnail,
|
||||
} = await encryptFile(state, file, fileBuffer, masterKey);
|
||||
|
||||
const form = new FormData();
|
||||
form.set(
|
||||
const form = new FormData();
|
||||
form.set(
|
||||
"metadata",
|
||||
JSON.stringify({
|
||||
parent: parentId,
|
||||
mekVersion: masterKey.version,
|
||||
dek: dataKeyWrapped,
|
||||
dekVersion: dataKeyVersion.toISOString(),
|
||||
hskVersion: hmacSecret.version,
|
||||
contentHmac: fileSigned,
|
||||
contentType: fileType,
|
||||
contentIv: fileEncrypted.iv,
|
||||
name: nameEncrypted.ciphertext,
|
||||
nameIv: nameEncrypted.iv,
|
||||
createdAt: createdAtEncrypted?.ciphertext,
|
||||
createdAtIv: createdAtEncrypted?.iv,
|
||||
lastModifiedAt: lastModifiedAtEncrypted.ciphertext,
|
||||
lastModifiedAtIv: lastModifiedAtEncrypted.iv,
|
||||
} satisfies FileUploadRequest),
|
||||
);
|
||||
form.set("content", new Blob([fileEncrypted.ciphertext]));
|
||||
form.set("checksum", fileEncryptedHash);
|
||||
|
||||
let thumbnailForm = null;
|
||||
if (thumbnail) {
|
||||
thumbnailForm = new FormData();
|
||||
thumbnailForm.set(
|
||||
"metadata",
|
||||
JSON.stringify({
|
||||
parent: parentId,
|
||||
mekVersion: masterKey.version,
|
||||
dek: dataKeyWrapped,
|
||||
dekVersion: dataKeyVersion.toISOString(),
|
||||
hskVersion: hmacSecret.version,
|
||||
contentHmac: fileSigned,
|
||||
contentType: fileType,
|
||||
contentIv: fileEncrypted.iv,
|
||||
name: nameEncrypted.ciphertext,
|
||||
nameIv: nameEncrypted.iv,
|
||||
createdAt: createdAtEncrypted?.ciphertext,
|
||||
createdAtIv: createdAtEncrypted?.iv,
|
||||
lastModifiedAt: lastModifiedAtEncrypted.ciphertext,
|
||||
lastModifiedAtIv: lastModifiedAtEncrypted.iv,
|
||||
} satisfies FileUploadRequest),
|
||||
contentIv: thumbnail.iv,
|
||||
} satisfies FileThumbnailUploadRequest),
|
||||
);
|
||||
form.set("content", new Blob([fileEncrypted.ciphertext]));
|
||||
form.set("checksum", fileEncryptedHash);
|
||||
|
||||
let thumbnailForm = null;
|
||||
if (thumbnail) {
|
||||
thumbnailForm = new FormData();
|
||||
thumbnailForm.set(
|
||||
"metadata",
|
||||
JSON.stringify({
|
||||
dekVersion: dataKeyVersion.toISOString(),
|
||||
contentIv: thumbnail.iv,
|
||||
} satisfies FileThumbnailUploadRequest),
|
||||
);
|
||||
thumbnailForm.set("content", new Blob([thumbnail.ciphertext]));
|
||||
}
|
||||
|
||||
const { fileId } = await requestFileUpload(state, form, thumbnailForm);
|
||||
return { fileId, fileBuffer, thumbnailBuffer: thumbnail?.plaintext };
|
||||
} catch (e) {
|
||||
state.status = "error";
|
||||
throw e;
|
||||
thumbnailForm.set("content", new Blob([thumbnail.ciphertext]));
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
const { fileId } = await requestFileUpload(state, form, thumbnailForm);
|
||||
return { fileId, fileBuffer, thumbnailBuffer: thumbnail?.plaintext };
|
||||
} catch (e) {
|
||||
state.status = "error";
|
||||
throw e;
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
@@ -1,167 +1,121 @@
|
||||
import * as IndexedDB from "$lib/indexedDB";
|
||||
import { trpc, isTRPCClientError } from "$trpc/client";
|
||||
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 fetchFromIndexedDB = async (id: CategoryId) => {
|
||||
const [category, subCategories] = await Promise.all([
|
||||
id !== "root" ? IndexedDB.getCategoryInfo(id) : undefined,
|
||||
IndexedDB.getCategoryInfos(id),
|
||||
]);
|
||||
const files = category
|
||||
? await Promise.all(
|
||||
category.files.map(async (file) => {
|
||||
const fileInfo = await IndexedDB.getFileInfo(file.id);
|
||||
return fileInfo
|
||||
? {
|
||||
id: file.id,
|
||||
contentType: fileInfo.contentType,
|
||||
name: fileInfo.name,
|
||||
createdAt: fileInfo.createdAt,
|
||||
lastModifiedAt: fileInfo.lastModifiedAt,
|
||||
isRecursive: file.isRecursive,
|
||||
}
|
||||
: undefined;
|
||||
}),
|
||||
)
|
||||
: undefined;
|
||||
|
||||
if (id === "root") {
|
||||
return {
|
||||
id,
|
||||
exists: true as const,
|
||||
subCategories,
|
||||
};
|
||||
} else if (category) {
|
||||
return {
|
||||
id,
|
||||
exists: true as const,
|
||||
name: category.name,
|
||||
subCategories,
|
||||
files: files!.filter((file) => !!file),
|
||||
isFileRecursive: category.isFileRecursive,
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
const fetchFromServer = async (id: CategoryId, masterKey: CryptoKey) => {
|
||||
try {
|
||||
const {
|
||||
metadata,
|
||||
subCategories: subCategoriesRaw,
|
||||
files: filesRaw,
|
||||
} = 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,
|
||||
parentId: id,
|
||||
name: decrypted.name,
|
||||
files: existing?.files ?? [],
|
||||
isFileRecursive: existing?.isFileRecursive ?? false,
|
||||
});
|
||||
return {
|
||||
id: category.id,
|
||||
...decrypted,
|
||||
};
|
||||
}),
|
||||
);
|
||||
|
||||
const existingFiles = filesRaw
|
||||
? await IndexedDB.bulkGetFileInfos(filesRaw.map((file) => file.id))
|
||||
: [];
|
||||
const files = filesRaw
|
||||
const cache = new FilesystemCache<CategoryId, MaybeCategoryInfo>({
|
||||
async fetchFromIndexedDB(id) {
|
||||
const [category, subCategories] = await Promise.all([
|
||||
id !== "root" ? IndexedDB.getCategoryInfo(id) : undefined,
|
||||
IndexedDB.getCategoryInfos(id),
|
||||
]);
|
||||
const files = category?.files
|
||||
? 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,
|
||||
};
|
||||
category.files.map(async (file) => {
|
||||
const fileInfo = await IndexedDB.getFileInfo(file.id);
|
||||
return fileInfo
|
||||
? {
|
||||
id: file.id,
|
||||
parentId: fileInfo.parentId,
|
||||
contentType: fileInfo.contentType,
|
||||
name: fileInfo.name,
|
||||
createdAt: fileInfo.createdAt,
|
||||
lastModifiedAt: fileInfo.lastModifiedAt,
|
||||
isRecursive: file.isRecursive,
|
||||
}
|
||||
: undefined;
|
||||
}),
|
||||
)
|
||||
: 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,
|
||||
exists: true,
|
||||
subCategories,
|
||||
};
|
||||
} else {
|
||||
} else if (category) {
|
||||
return {
|
||||
id,
|
||||
exists: true as const,
|
||||
exists: true,
|
||||
parentId: category.parentId,
|
||||
name: category.name,
|
||||
subCategories,
|
||||
files,
|
||||
...decryptedMetadata!,
|
||||
files: files?.filter((file) => !!file) ?? [],
|
||||
isFileRecursive: category.isFileRecursive ?? false,
|
||||
};
|
||||
}
|
||||
} catch (e) {
|
||||
if (isTRPCClientError(e) && e.data?.code === "NOT_FOUND") {
|
||||
await IndexedDB.deleteCategoryInfo(id as number);
|
||||
return { id, exists: false as const };
|
||||
}
|
||||
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);
|
||||
async fetchFromServer(id, cachedInfo, masterKey) {
|
||||
try {
|
||||
const category = await trpc().category.get.query({ id, recurse: true });
|
||||
const [subCategories, files, metadata] = await Promise.all([
|
||||
Promise.all(
|
||||
category.subCategories.map(async (category) => ({
|
||||
id: category.id,
|
||||
parentId: id,
|
||||
...(await decryptCategoryMetadata(category, masterKey)),
|
||||
})),
|
||||
),
|
||||
category.files &&
|
||||
Promise.all(
|
||||
category.files.map(async (file) => ({
|
||||
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 },
|
||||
);
|
||||
} catch (e) {
|
||||
if (isTRPCClientError(e) && e.data?.code === "NOT_FOUND") {
|
||||
await IndexedDB.deleteCategoryInfo(id as number);
|
||||
return { id, exists: false };
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
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,125 +1,102 @@
|
||||
import * as IndexedDB from "$lib/indexedDB";
|
||||
import { monotonicResolve } from "$lib/utils";
|
||||
import { trpc, isTRPCClientError } from "$trpc/client";
|
||||
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 fetchFromIndexedDB = async (id: DirectoryId) => {
|
||||
const [directory, subDirectories, files] = await Promise.all([
|
||||
id !== "root" ? IndexedDB.getDirectoryInfo(id) : undefined,
|
||||
IndexedDB.getDirectoryInfos(id),
|
||||
IndexedDB.getFileInfos(id),
|
||||
]);
|
||||
|
||||
if (id === "root") {
|
||||
return {
|
||||
id,
|
||||
exists: true as const,
|
||||
subDirectories,
|
||||
files,
|
||||
};
|
||||
} else if (directory) {
|
||||
return {
|
||||
id,
|
||||
exists: true as const,
|
||||
parentId: directory.parentId,
|
||||
name: directory.name,
|
||||
subDirectories,
|
||||
files,
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
const fetchFromServer = async (id: DirectoryId, masterKey: CryptoKey) => {
|
||||
try {
|
||||
const {
|
||||
metadata,
|
||||
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(
|
||||
subDirectoriesRaw.map(async (directory) => {
|
||||
const decrypted = await decryptDirectoryMetadata(directory, masterKey);
|
||||
await IndexedDB.storeDirectoryInfo({
|
||||
id: directory.id,
|
||||
parentId: id,
|
||||
name: decrypted.name,
|
||||
});
|
||||
return {
|
||||
id: directory.id,
|
||||
...decrypted,
|
||||
};
|
||||
}),
|
||||
),
|
||||
Promise.all(
|
||||
filesRaw.map(async (file, index) => {
|
||||
const decrypted = await decryptFileMetadata(file, masterKey);
|
||||
await IndexedDB.storeFileInfo({
|
||||
id: file.id,
|
||||
parentId: id,
|
||||
contentType: file.contentType,
|
||||
name: decrypted.name,
|
||||
createdAt: decrypted.createdAt,
|
||||
lastModifiedAt: decrypted.lastModifiedAt,
|
||||
categoryIds: existingFiles[index]?.categoryIds ?? [],
|
||||
});
|
||||
return {
|
||||
id: file.id,
|
||||
contentType: file.contentType,
|
||||
...decrypted,
|
||||
};
|
||||
}),
|
||||
),
|
||||
metadata ? decryptDirectoryMetadata(metadata, masterKey) : undefined,
|
||||
const cache = new FilesystemCache<DirectoryId, MaybeDirectoryInfo>({
|
||||
async fetchFromIndexedDB(id) {
|
||||
const [directory, subDirectories, files] = await Promise.all([
|
||||
id !== "root" ? IndexedDB.getDirectoryInfo(id) : undefined,
|
||||
IndexedDB.getDirectoryInfos(id),
|
||||
IndexedDB.getFileInfos(id),
|
||||
]);
|
||||
|
||||
if (id !== "root" && metadata && decryptedMetadata) {
|
||||
await IndexedDB.storeDirectoryInfo({
|
||||
id,
|
||||
parentId: metadata.parent,
|
||||
name: decryptedMetadata.name,
|
||||
});
|
||||
}
|
||||
|
||||
if (id === "root") {
|
||||
return {
|
||||
id,
|
||||
exists: true as const,
|
||||
exists: true,
|
||||
subDirectories,
|
||||
files,
|
||||
};
|
||||
} else {
|
||||
} else if (directory) {
|
||||
return {
|
||||
id,
|
||||
exists: true as const,
|
||||
parentId: metadata!.parent,
|
||||
exists: true,
|
||||
parentId: directory.parentId,
|
||||
name: directory.name,
|
||||
subDirectories,
|
||||
files,
|
||||
...decryptedMetadata!,
|
||||
};
|
||||
}
|
||||
} catch (e) {
|
||||
if (isTRPCClientError(e) && e.data?.code === "NOT_FOUND") {
|
||||
await IndexedDB.deleteDirectoryInfo(id as number);
|
||||
return { id, exists: false as const };
|
||||
},
|
||||
|
||||
async fetchFromServer(id, _cachedInfo, masterKey) {
|
||||
try {
|
||||
const directory = await trpc().directory.get.query({ id });
|
||||
const [subDirectories, files, metadata] = await Promise.all([
|
||||
Promise.all(
|
||||
directory.subDirectories.map(async (directory) => ({
|
||||
id: directory.id,
|
||||
parentId: id,
|
||||
...(await decryptDirectoryMetadata(directory, masterKey)),
|
||||
})),
|
||||
),
|
||||
Promise.all(
|
||||
directory.files.map(async (file) => ({
|
||||
id: file.id,
|
||||
parentId: id,
|
||||
contentType: file.contentType,
|
||||
...(await decryptFileMetadata(file, masterKey)),
|
||||
})),
|
||||
),
|
||||
directory.metadata && decryptDirectoryMetadata(directory.metadata, masterKey),
|
||||
]);
|
||||
|
||||
return storeToIndexedDB(
|
||||
id !== "root"
|
||||
? {
|
||||
id,
|
||||
parentId: directory.metadata!.parent,
|
||||
subDirectories,
|
||||
files,
|
||||
...metadata!,
|
||||
}
|
||||
: { id, subDirectories, files },
|
||||
);
|
||||
} catch (e) {
|
||||
if (isTRPCClientError(e) && e.data?.code === "NOT_FOUND") {
|
||||
await IndexedDB.deleteDirectoryInfo(id as number);
|
||||
return { id, exists: false as const };
|
||||
}
|
||||
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) => {
|
||||
return await cache.get(id, (isInitial, resolve) =>
|
||||
monotonicResolve(
|
||||
[isInitial && fetchFromIndexedDB(id), fetchFromServer(id, masterKey)],
|
||||
resolve,
|
||||
),
|
||||
);
|
||||
export const getDirectoryInfo = (id: DirectoryId, masterKey: CryptoKey) => {
|
||||
return cache.get(id, masterKey);
|
||||
};
|
||||
|
||||
@@ -1,175 +1,177 @@
|
||||
import * as IndexedDB from "$lib/indexedDB";
|
||||
import { monotonicResolve } from "$lib/utils";
|
||||
import { trpc, isTRPCClientError } from "$trpc/client";
|
||||
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 file = await IndexedDB.getFileInfo(id);
|
||||
const categories = 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;
|
||||
|
||||
const fetchFromIndexedDB = async (id: number) => {
|
||||
const file = await IndexedDB.getFileInfo(id);
|
||||
const categories = 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;
|
||||
|
||||
if (file) {
|
||||
return {
|
||||
id,
|
||||
exists: true as const,
|
||||
parentId: file.parentId,
|
||||
contentType: file.contentType,
|
||||
name: file.name,
|
||||
createdAt: file.createdAt,
|
||||
lastModifiedAt: file.lastModifiedAt,
|
||||
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) => {
|
||||
try {
|
||||
const { categories: categoriesRaw, ...metadata } = await trpc().file.get.query({ id });
|
||||
const [categories, decryptedMetadata] = await Promise.all([
|
||||
Promise.all(
|
||||
categoriesRaw.map(async (category) => ({
|
||||
id: category.id,
|
||||
...(await decryptCategoryMetadata(category, masterKey)),
|
||||
})),
|
||||
),
|
||||
decryptFileMetadata(metadata, masterKey),
|
||||
]);
|
||||
|
||||
await IndexedDB.storeFileInfo({
|
||||
id,
|
||||
parentId: metadata.parent,
|
||||
contentType: metadata.contentType,
|
||||
name: decryptedMetadata.name,
|
||||
createdAt: decryptedMetadata.createdAt,
|
||||
lastModifiedAt: decryptedMetadata.lastModifiedAt,
|
||||
categoryIds: categories.map((category) => category.id),
|
||||
});
|
||||
|
||||
return {
|
||||
id,
|
||||
exists: true as const,
|
||||
parentId: metadata.parent,
|
||||
contentType: metadata.contentType,
|
||||
contentIv: metadata.contentIv,
|
||||
categories,
|
||||
...decryptedMetadata,
|
||||
};
|
||||
} catch (e) {
|
||||
if (isTRPCClientError(e) && e.data?.code === "NOT_FOUND") {
|
||||
await IndexedDB.deleteFileInfo(id);
|
||||
return { id, exists: false as const };
|
||||
if (file) {
|
||||
return {
|
||||
id,
|
||||
exists: true,
|
||||
parentId: file.parentId,
|
||||
contentType: file.contentType,
|
||||
name: file.name,
|
||||
createdAt: file.createdAt,
|
||||
lastModifiedAt: file.lastModifiedAt,
|
||||
categories: categories?.filter((category) => !!category) ?? [],
|
||||
};
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
};
|
||||
},
|
||||
|
||||
const bulkFetchFromServer = async (ids: number[], masterKey: CryptoKey) => {
|
||||
const filesRaw = await trpc().file.bulkGet.query({ ids });
|
||||
const files = await Promise.all(
|
||||
filesRaw.map(async (file) => {
|
||||
const [categories, decryptedMetadata] = await Promise.all([
|
||||
async fetchFromServer(id, _cachedInfo, masterKey) {
|
||||
try {
|
||||
const file = await trpc().file.get.query({ id });
|
||||
const [categories, metadata] = await Promise.all([
|
||||
Promise.all(
|
||||
file.categories.map(async (category) => ({
|
||||
id: category.id,
|
||||
parentId: category.parent,
|
||||
...(await decryptCategoryMetadata(category, masterKey)),
|
||||
})),
|
||||
),
|
||||
decryptFileMetadata(file, 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 {
|
||||
id: file.id,
|
||||
exists: true as const,
|
||||
return storeToIndexedDB({
|
||||
id,
|
||||
parentId: file.parent,
|
||||
dataKey: metadata.dataKey,
|
||||
contentType: file.contentType,
|
||||
contentIv: file.contentIv,
|
||||
name: metadata.name,
|
||||
createdAt: metadata.createdAt,
|
||||
lastModifiedAt: metadata.lastModifiedAt,
|
||||
categories,
|
||||
...decryptedMetadata,
|
||||
};
|
||||
}),
|
||||
);
|
||||
});
|
||||
} catch (e) {
|
||||
if (isTRPCClientError(e) && e.data?.code === "NOT_FOUND") {
|
||||
await IndexedDB.deleteFileInfo(id);
|
||||
return { id, exists: false as const };
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
},
|
||||
|
||||
const existingIds = new Set(filesRaw.map(({ id }) => id));
|
||||
return new Map<number, MaybeFileInfo>([
|
||||
...files.map((file) => [file.id, file] as const),
|
||||
...ids.filter((id) => !existingIds.has(id)).map((id) => [id, { id, exists: false }] as const),
|
||||
]);
|
||||
};
|
||||
async bulkFetchFromIndexedDB(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,
|
||||
),
|
||||
);
|
||||
|
||||
export const getFileInfo = async (id: number, masterKey: CryptoKey) => {
|
||||
return await cache.get(id, (isInitial, resolve) =>
|
||||
monotonicResolve(
|
||||
[isInitial && fetchFromIndexedDB(id), fetchFromServer(id, masterKey)],
|
||||
resolve,
|
||||
),
|
||||
);
|
||||
};
|
||||
return new Map(
|
||||
files
|
||||
.filter((file) => !!file)
|
||||
.map((file, index) => [
|
||||
file.id,
|
||||
{
|
||||
...file,
|
||||
exists: true,
|
||||
categories: categories[index]?.filter((category) => !!category) ?? [],
|
||||
},
|
||||
]),
|
||||
);
|
||||
},
|
||||
|
||||
export const bulkGetFileInfo = async (ids: number[], masterKey: CryptoKey) => {
|
||||
return await cache.bulkGet(new Set(ids), (keys, resolve) =>
|
||||
monotonicResolve(
|
||||
[
|
||||
bulkFetchFromIndexedDB(
|
||||
Array.from(
|
||||
keys
|
||||
.entries()
|
||||
.filter(([, isInitial]) => isInitial)
|
||||
.map(([key]) => key),
|
||||
async bulkFetchFromServer(ids, masterKey) {
|
||||
const idsArray = [...ids.keys()];
|
||||
|
||||
const filesRaw = await trpc().file.bulkGet.query({ ids: idsArray });
|
||||
const files = await Promise.all(
|
||||
filesRaw.map(async ({ id, categories: categoriesRaw, ...metadataRaw }) => {
|
||||
const [categories, metadata] = await Promise.all([
|
||||
Promise.all(
|
||||
categoriesRaw.map(async (category) => ({
|
||||
id: category.id,
|
||||
parentId: category.parent,
|
||||
...(await decryptCategoryMetadata(category, masterKey)),
|
||||
})),
|
||||
),
|
||||
),
|
||||
bulkFetchFromServer(Array.from(keys.keys()), masterKey),
|
||||
],
|
||||
resolve,
|
||||
),
|
||||
);
|
||||
decryptFileMetadata(metadataRaw, masterKey),
|
||||
]);
|
||||
|
||||
return {
|
||||
id,
|
||||
exists: true as const,
|
||||
parentId: metadataRaw.parent,
|
||||
contentType: metadataRaw.contentType,
|
||||
contentIv: metadataRaw.contentIv,
|
||||
categories,
|
||||
...metadata,
|
||||
};
|
||||
}),
|
||||
);
|
||||
|
||||
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>([
|
||||
...bulkStoreToIndexedDB(files),
|
||||
...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 };
|
||||
};
|
||||
|
||||
const bulkStoreToIndexedDB = (infos: FileInfo[]) => {
|
||||
// TODO: Bulk Upsert
|
||||
infos.forEach((info) => {
|
||||
void IndexedDB.storeFileInfo({
|
||||
...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 getFileInfo = (id: number, masterKey: CryptoKey) => {
|
||||
return cache.get(id, masterKey);
|
||||
};
|
||||
|
||||
export const bulkGetFileInfo = (ids: number[], masterKey: CryptoKey) => {
|
||||
return cache.bulkGet(new Set(ids), masterKey);
|
||||
};
|
||||
|
||||
@@ -1,82 +1,124 @@
|
||||
import { untrack } from "svelte";
|
||||
import { unwrapDataKey, decryptString } from "$lib/modules/crypto";
|
||||
|
||||
export class FilesystemCache<K, V extends RV, RV = V> {
|
||||
private map = new Map<K, V | Promise<V>>();
|
||||
interface FilesystemCacheOptions<K, V> {
|
||||
fetchFromIndexedDB: (key: K) => Promise<V | undefined>;
|
||||
fetchFromServer: (key: K, cachedValue: V | undefined, masterKey: CryptoKey) => Promise<V>;
|
||||
bulkFetchFromIndexedDB?: (keys: Set<K>) => Promise<Map<K, V>>;
|
||||
bulkFetchFromServer?: (
|
||||
keys: Map<K, { cachedValue: V | undefined }>,
|
||||
masterKey: CryptoKey,
|
||||
) => Promise<Map<K, V>>;
|
||||
}
|
||||
|
||||
get(key: K, loader: (isInitial: boolean, resolve: (value: RV | undefined) => void) => void) {
|
||||
const info = this.map.get(key);
|
||||
if (info instanceof Promise) {
|
||||
return info;
|
||||
}
|
||||
export class FilesystemCache<K, V extends object> {
|
||||
private map = new Map<K, { value?: V; promise?: Promise<V> }>();
|
||||
|
||||
const { promise, resolve } = Promise.withResolvers<V>();
|
||||
if (!info) {
|
||||
this.map.set(key, promise);
|
||||
}
|
||||
constructor(private readonly options: FilesystemCacheOptions<K, V>) {}
|
||||
|
||||
loader(!info, (loadedInfo) => {
|
||||
if (!loadedInfo) return;
|
||||
get(key: K, masterKey: CryptoKey) {
|
||||
return untrack(() => {
|
||||
let state = this.map.get(key);
|
||||
if (state?.promise) return state.value ?? state.promise;
|
||||
|
||||
const info = this.map.get(key)!;
|
||||
if (info instanceof Promise) {
|
||||
const state = $state(loadedInfo);
|
||||
this.map.set(key, state as V);
|
||||
resolve(state as V);
|
||||
} else {
|
||||
Object.assign(info, loadedInfo);
|
||||
resolve(info);
|
||||
const { promise: newPromise, resolve } = Promise.withResolvers<V>();
|
||||
|
||||
if (!state) {
|
||||
const newState = $state({});
|
||||
state = newState;
|
||||
this.map.set(key, newState);
|
||||
}
|
||||
});
|
||||
|
||||
return info ?? promise;
|
||||
(state.value
|
||||
? Promise.resolve(state.value)
|
||||
: this.options.fetchFromIndexedDB(key).then((loadedInfo) => {
|
||||
if (loadedInfo) {
|
||||
state.value = loadedInfo;
|
||||
resolve(state.value);
|
||||
}
|
||||
return loadedInfo;
|
||||
})
|
||||
)
|
||||
.then((cachedInfo) => this.options.fetchFromServer(key, cachedInfo, masterKey))
|
||||
.then((loadedInfo) => {
|
||||
if (state.value) {
|
||||
Object.assign(state.value, loadedInfo);
|
||||
} else {
|
||||
state.value = loadedInfo;
|
||||
}
|
||||
resolve(state.value);
|
||||
})
|
||||
.finally(() => {
|
||||
state.promise = undefined;
|
||||
});
|
||||
|
||||
state.promise = newPromise;
|
||||
return state.value ?? newPromise;
|
||||
});
|
||||
}
|
||||
|
||||
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>();
|
||||
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);
|
||||
}
|
||||
});
|
||||
|
||||
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) =>
|
||||
const resolve = (loadedInfos: Map<K, V>) => {
|
||||
loadedInfos.forEach((loadedInfo, key) => {
|
||||
const info = this.map.get(key)!;
|
||||
const resolve = resolvers.get(key);
|
||||
if (info instanceof Promise) {
|
||||
const state = $state(loadedInfo);
|
||||
this.map.set(key, state as V);
|
||||
resolve?.(state as V);
|
||||
const state = this.map.get(key)!;
|
||||
if (state.value) {
|
||||
Object.assign(state.value, loadedInfo);
|
||||
} else {
|
||||
Object.assign(info, loadedInfo);
|
||||
resolve?.(info);
|
||||
state.value = loadedInfo;
|
||||
}
|
||||
}),
|
||||
);
|
||||
newPromises.get(key)!.resolve(state.value);
|
||||
});
|
||||
return loadedInfos;
|
||||
};
|
||||
|
||||
const newStates = await Promise.all(
|
||||
promises.entries().map(async ([key, promise]) => [key, await promise] as const),
|
||||
);
|
||||
return new Map([...states, ...newStates]);
|
||||
this.options.bulkFetchFromIndexedDB!(
|
||||
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!),
|
||||
);
|
||||
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 SubDirectoryInfo = Omit<LocalDirectoryInfo, "parentId" | "subDirectories" | "files">;
|
||||
export type MaybeDirectoryInfo =
|
||||
| (DirectoryInfo & { exists: true })
|
||||
| ({ id: DirectoryId; exists: false } & AllUndefined<Omit<DirectoryInfo, "id">>);
|
||||
|
||||
export type SubDirectoryInfo = Omit<LocalDirectoryInfo, "subDirectories" | "files">;
|
||||
|
||||
export interface FileInfo {
|
||||
id: number;
|
||||
parentId: DirectoryId;
|
||||
@@ -34,17 +35,19 @@ export interface FileInfo {
|
||||
name: string;
|
||||
createdAt?: 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 =
|
||||
| (FileInfo & { exists: true })
|
||||
| ({ id: number; exists: false } & AllUndefined<Omit<FileInfo, "id">>);
|
||||
|
||||
export type SummarizedFileInfo = Omit<FileInfo, "contentIv" | "categories">;
|
||||
export type CategoryFileInfo = SummarizedFileInfo & { isRecursive: boolean };
|
||||
|
||||
interface LocalCategoryInfo {
|
||||
id: number;
|
||||
parentId: DirectoryId;
|
||||
dataKey?: DataKey;
|
||||
name: string;
|
||||
subCategories: SubCategoryInfo[];
|
||||
@@ -54,6 +57,7 @@ interface LocalCategoryInfo {
|
||||
|
||||
interface RootCategoryInfo {
|
||||
id: "root";
|
||||
parentId?: undefined;
|
||||
dataKey?: undefined;
|
||||
name?: undefined;
|
||||
subCategories: SubCategoryInfo[];
|
||||
@@ -62,10 +66,12 @@ interface RootCategoryInfo {
|
||||
}
|
||||
|
||||
export type CategoryInfo = LocalCategoryInfo | RootCategoryInfo;
|
||||
export type MaybeCategoryInfo =
|
||||
| (CategoryInfo & { exists: true })
|
||||
| ({ id: CategoryId; exists: false } & AllUndefined<Omit<CategoryInfo, "id">>);
|
||||
|
||||
export type SubCategoryInfo = Omit<
|
||||
LocalCategoryInfo,
|
||||
"subCategories" | "files" | "isFileRecursive"
|
||||
>;
|
||||
export type MaybeCategoryInfo =
|
||||
| (CategoryInfo & { exists: true })
|
||||
| ({ id: CategoryId; exists: false } & AllUndefined<Omit<CategoryInfo, "id">>);
|
||||
export type FileCategoryInfo = Omit<SubCategoryInfo, "dataKey">;
|
||||
|
||||
@@ -1,39 +1,46 @@
|
||||
export class Scheduler<T = void> {
|
||||
private tasks = 0;
|
||||
private isEstimating = false;
|
||||
private memoryUsage = 0;
|
||||
private queue: (() => void)[] = [];
|
||||
|
||||
constructor(public memoryLimit = 100 * 1024 * 1024 /* 100 MiB */) {}
|
||||
constructor(public readonly memoryLimit = 100 * 1024 * 1024 /* 100 MiB */) {}
|
||||
|
||||
private next() {
|
||||
if (this.memoryUsage < this.memoryLimit) {
|
||||
this.queue.shift()?.();
|
||||
if (!this.isEstimating && this.memoryUsage < this.memoryLimit) {
|
||||
const resolve = this.queue.shift();
|
||||
if (resolve) {
|
||||
this.isEstimating = true;
|
||||
resolve();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async schedule(estimateMemoryUsage: () => Promise<number>, task: () => Promise<T>) {
|
||||
if (this.tasks++ > 0) {
|
||||
async schedule(
|
||||
estimateMemoryUsage: number | (() => number | Promise<number>),
|
||||
task: () => Promise<T>,
|
||||
) {
|
||||
if (this.isEstimating || this.memoryUsage >= this.memoryLimit) {
|
||||
await new Promise<void>((resolve) => {
|
||||
this.queue.push(resolve);
|
||||
});
|
||||
}
|
||||
|
||||
while (this.memoryUsage >= this.memoryLimit) {
|
||||
await new Promise<void>((resolve) => {
|
||||
this.queue.unshift(resolve);
|
||||
});
|
||||
} else {
|
||||
this.isEstimating = true;
|
||||
}
|
||||
|
||||
let taskMemoryUsage = 0;
|
||||
|
||||
try {
|
||||
taskMemoryUsage = await estimateMemoryUsage();
|
||||
taskMemoryUsage =
|
||||
typeof estimateMemoryUsage === "number" ? estimateMemoryUsage : await estimateMemoryUsage();
|
||||
this.memoryUsage += taskMemoryUsage;
|
||||
} finally {
|
||||
this.isEstimating = false;
|
||||
this.next();
|
||||
}
|
||||
|
||||
try {
|
||||
return await task();
|
||||
} finally {
|
||||
this.tasks--;
|
||||
this.memoryUsage -= taskMemoryUsage;
|
||||
this.next();
|
||||
}
|
||||
|
||||
@@ -39,6 +39,7 @@ export type NewFile = Omit<File, "id">;
|
||||
|
||||
interface FileCategory {
|
||||
id: number;
|
||||
parentId: CategoryId;
|
||||
mekVersion: number;
|
||||
encDek: string;
|
||||
dekVersion: Date;
|
||||
@@ -445,6 +446,7 @@ export const getFilesWithCategories = async (userId: number, fileIds: number[])
|
||||
encLastModifiedAt: file.encrypted_last_modified_at,
|
||||
categories: file.categories.map((category) => ({
|
||||
id: category.id,
|
||||
parentId: category.parent_id ?? "root",
|
||||
mekVersion: category.master_encryption_key_version,
|
||||
encDek: category.encrypted_data_encryption_key,
|
||||
dekVersion: new Date(category.data_encryption_key_version),
|
||||
@@ -548,6 +550,7 @@ export const getAllFileCategories = async (fileId: number) => {
|
||||
(category) =>
|
||||
({
|
||||
id: category.id,
|
||||
parentId: category.parent_id ?? "root",
|
||||
mekVersion: category.master_encryption_key_version,
|
||||
encDek: category.encrypted_data_encryption_key,
|
||||
dekVersion: category.data_encryption_key_version,
|
||||
|
||||
@@ -1,15 +1,11 @@
|
||||
import { getAllFileInfos } from "$lib/indexedDB/filesystem";
|
||||
import { decryptData } from "$lib/modules/crypto";
|
||||
import {
|
||||
getFileCache,
|
||||
storeFileCache,
|
||||
deleteFileCache,
|
||||
getFileThumbnailCache,
|
||||
storeFileThumbnailCache,
|
||||
deleteFileThumbnailCache,
|
||||
downloadFile,
|
||||
deleteFileThumbnailCache,
|
||||
} from "$lib/modules/file";
|
||||
import { getThumbnailUrl } from "$lib/modules/thumbnail";
|
||||
import type { FileThumbnailUploadRequest } from "$lib/server/schemas";
|
||||
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 });
|
||||
};
|
||||
|
||||
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 () => {
|
||||
let liveFiles;
|
||||
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 "./gotoStateful";
|
||||
export * from "./promise";
|
||||
export * from "./HybridPromise";
|
||||
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 { getFileDownloadState } from "$lib/modules/file";
|
||||
import { masterKeyStore } from "$lib/stores";
|
||||
import { HybridPromise } from "$lib/utils";
|
||||
import AddToCategoryBottomSheet from "./AddToCategoryBottomSheet.svelte";
|
||||
import DownloadStatus from "./DownloadStatus.svelte";
|
||||
import {
|
||||
@@ -26,8 +27,7 @@
|
||||
|
||||
let { data } = $props();
|
||||
|
||||
let infoPromise: Promise<MaybeFileInfo> | undefined = $state();
|
||||
let info: FileInfo | null = $state(null);
|
||||
let info: MaybeFileInfo | undefined = $state();
|
||||
let downloadState = $derived(getFileDownloadState(data.id));
|
||||
|
||||
let isMenuOpen = $state(false);
|
||||
@@ -65,22 +65,20 @@
|
||||
const addToCategory = async (categoryId: number) => {
|
||||
await requestFileAdditionToCategory(data.id, categoryId);
|
||||
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) => {
|
||||
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(() => {
|
||||
infoPromise = getFileInfo(data.id, $masterKeyStore?.get(1)?.key!).then((fileInfo) => {
|
||||
if (fileInfo.exists) {
|
||||
info = fileInfo;
|
||||
HybridPromise.resolve(getFileInfo(data.id, $masterKeyStore?.get(1)?.key!)).then((result) => {
|
||||
if (data.id === result.id) {
|
||||
info = result;
|
||||
}
|
||||
return fileInfo;
|
||||
});
|
||||
info = null;
|
||||
isDownloadRequested = false;
|
||||
viewerType = undefined;
|
||||
});
|
||||
@@ -111,8 +109,8 @@
|
||||
});
|
||||
|
||||
$effect(() => {
|
||||
if (info && downloadState?.status === "decrypted") {
|
||||
untrack(() => !isDownloadRequested && updateViewer(downloadState.result!, info!.contentType));
|
||||
if (info?.exists && downloadState?.status === "decrypted") {
|
||||
untrack(() => !isDownloadRequested && updateViewer(downloadState.result!, info!.contentIv!));
|
||||
}
|
||||
});
|
||||
|
||||
@@ -123,87 +121,85 @@
|
||||
<title>파일</title>
|
||||
</svelte:head>
|
||||
|
||||
{#if info}
|
||||
<TopBar title={info.name}>
|
||||
<!-- svelte-ignore a11y_no_static_element_interactions -->
|
||||
<!-- svelte-ignore a11y_click_events_have_key_events -->
|
||||
<div onclick={(e) => e.stopPropagation()}>
|
||||
<button
|
||||
onclick={() => (isMenuOpen = !isMenuOpen)}
|
||||
class="w-[2.3rem] flex-shrink-0 rounded-full p-1 active:bg-black active:bg-opacity-[0.04]"
|
||||
>
|
||||
<IconMoreVert class="text-2xl" />
|
||||
</button>
|
||||
<TopBarMenu
|
||||
bind:isOpen={isMenuOpen}
|
||||
directoryId={["category", "gallery"].includes(page.url.searchParams.get("from") ?? "")
|
||||
? info.parentId
|
||||
: undefined}
|
||||
{fileBlob}
|
||||
filename={info.name}
|
||||
/>
|
||||
</div>
|
||||
</TopBar>
|
||||
<FullscreenDiv>
|
||||
<div class="space-y-4 pb-4">
|
||||
{#if downloadState}
|
||||
<DownloadStatus state={downloadState} />
|
||||
{/if}
|
||||
{#if viewerType}
|
||||
<div class="flex w-full justify-center">
|
||||
{#snippet viewerLoading(message: string)}
|
||||
<p class="text-gray-500">{message}</p>
|
||||
{/snippet}
|
||||
<TopBar title={info?.name}>
|
||||
<!-- svelte-ignore a11y_no_static_element_interactions -->
|
||||
<!-- svelte-ignore a11y_click_events_have_key_events -->
|
||||
<div onclick={(e) => e.stopPropagation()}>
|
||||
<button
|
||||
onclick={() => (isMenuOpen = !isMenuOpen)}
|
||||
class="w-[2.3rem] flex-shrink-0 rounded-full p-1 active:bg-black active:bg-opacity-[0.04]"
|
||||
>
|
||||
<IconMoreVert class="text-2xl" />
|
||||
</button>
|
||||
<TopBarMenu
|
||||
bind:isOpen={isMenuOpen}
|
||||
directoryId={["category", "gallery"].includes(page.url.searchParams.get("from") ?? "")
|
||||
? info?.parentId
|
||||
: undefined}
|
||||
{fileBlob}
|
||||
filename={info?.name}
|
||||
/>
|
||||
</div>
|
||||
</TopBar>
|
||||
<FullscreenDiv>
|
||||
<div class="space-y-4 pb-4">
|
||||
{#if downloadState}
|
||||
<DownloadStatus state={downloadState} />
|
||||
{/if}
|
||||
{#if info && viewerType}
|
||||
<div class="flex w-full justify-center">
|
||||
{#snippet viewerLoading(message: string)}
|
||||
<p class="text-gray-500">{message}</p>
|
||||
{/snippet}
|
||||
|
||||
{#if viewerType === "image"}
|
||||
{#if fileBlobUrl}
|
||||
<img src={fileBlobUrl} alt={info.name} onerror={convertHeicToJpeg} />
|
||||
{:else}
|
||||
{@render viewerLoading("이미지를 불러오고 있어요.")}
|
||||
{/if}
|
||||
{:else if viewerType === "video"}
|
||||
{#if fileBlobUrl}
|
||||
<div class="flex flex-col space-y-2">
|
||||
<video bind:this={videoElement} src={fileBlobUrl} controls muted></video>
|
||||
<IconEntryButton
|
||||
icon={IconCamera}
|
||||
onclick={() => updateThumbnail(info?.dataKey?.key!, info?.dataKey?.version!)}
|
||||
class="w-full"
|
||||
>
|
||||
이 장면을 썸네일로 설정하기
|
||||
</IconEntryButton>
|
||||
</div>
|
||||
{:else}
|
||||
{@render viewerLoading("비디오를 불러오고 있어요.")}
|
||||
{/if}
|
||||
{#if viewerType === "image"}
|
||||
{#if fileBlobUrl}
|
||||
<img src={fileBlobUrl} alt={info.name} onerror={convertHeicToJpeg} />
|
||||
{:else}
|
||||
{@render viewerLoading("이미지를 불러오고 있어요.")}
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
<div class="space-y-2">
|
||||
<p class="text-lg font-bold">카테고리</p>
|
||||
<div class="space-y-1">
|
||||
<Categories
|
||||
categories={info.categories}
|
||||
categoryMenuIcon={IconClose}
|
||||
onCategoryClick={({ id }) => goto(`/category/${id}`)}
|
||||
onCategoryMenuClick={({ id }) => removeFromCategory(id)}
|
||||
/>
|
||||
<IconEntryButton
|
||||
icon={IconAddCircle}
|
||||
onclick={() => (isAddToCategoryBottomSheetOpen = true)}
|
||||
class="h-12 w-full"
|
||||
iconClass="text-gray-600"
|
||||
textClass="text-gray-700"
|
||||
>
|
||||
카테고리에 추가하기
|
||||
</IconEntryButton>
|
||||
</div>
|
||||
{:else if viewerType === "video"}
|
||||
{#if fileBlobUrl}
|
||||
<div class="flex flex-col space-y-2">
|
||||
<video bind:this={videoElement} src={fileBlobUrl} controls muted></video>
|
||||
<IconEntryButton
|
||||
icon={IconCamera}
|
||||
onclick={() => updateThumbnail(info?.dataKey?.key!, info?.dataKey?.version!)}
|
||||
class="w-full"
|
||||
>
|
||||
이 장면을 썸네일로 설정하기
|
||||
</IconEntryButton>
|
||||
</div>
|
||||
{:else}
|
||||
{@render viewerLoading("비디오를 불러오고 있어요.")}
|
||||
{/if}
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
<div class="space-y-2">
|
||||
<p class="text-lg font-bold">카테고리</p>
|
||||
<div class="space-y-1">
|
||||
<Categories
|
||||
categories={info?.categories ?? []}
|
||||
categoryMenuIcon={IconClose}
|
||||
onCategoryClick={({ id }) => goto(`/category/${id}`)}
|
||||
onCategoryMenuClick={({ id }) => removeFromCategory(id)}
|
||||
/>
|
||||
<IconEntryButton
|
||||
icon={IconAddCircle}
|
||||
onclick={() => (isAddToCategoryBottomSheetOpen = true)}
|
||||
class="h-12 w-full"
|
||||
iconClass="text-gray-600"
|
||||
textClass="text-gray-700"
|
||||
>
|
||||
카테고리에 추가하기
|
||||
</IconEntryButton>
|
||||
</div>
|
||||
</div>
|
||||
</FullscreenDiv>
|
||||
</div>
|
||||
</FullscreenDiv>
|
||||
|
||||
<AddToCategoryBottomSheet
|
||||
bind:isOpen={isAddToCategoryBottomSheetOpen}
|
||||
onAddToCategoryClick={addToCategory}
|
||||
/>
|
||||
{/if}
|
||||
<AddToCategoryBottomSheet
|
||||
bind:isOpen={isAddToCategoryBottomSheetOpen}
|
||||
onAddToCategoryClick={addToCategory}
|
||||
/>
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
import { CategoryCreateModal } from "$lib/components/organisms";
|
||||
import { getCategoryInfo, type MaybeCategoryInfo } from "$lib/modules/filesystem";
|
||||
import { masterKeyStore } from "$lib/stores";
|
||||
import { HybridPromise } from "$lib/utils";
|
||||
import { requestCategoryCreation } from "./service";
|
||||
|
||||
interface Props {
|
||||
@@ -13,48 +14,50 @@
|
||||
|
||||
let { onAddToCategoryClick, isOpen = $bindable() }: Props = $props();
|
||||
|
||||
let categoryInfoPromise: Promise<MaybeCategoryInfo> | undefined = $state();
|
||||
let categoryInfo: MaybeCategoryInfo | undefined = $state();
|
||||
|
||||
let isCategoryCreateModalOpen = $state(false);
|
||||
|
||||
$effect(() => {
|
||||
if (isOpen) {
|
||||
categoryInfoPromise = getCategoryInfo("root", $masterKeyStore?.get(1)?.key!);
|
||||
HybridPromise.resolve(getCategoryInfo("root", $masterKeyStore?.get(1)?.key!)).then(
|
||||
(result) => (categoryInfo = result),
|
||||
);
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
{#await categoryInfoPromise then categoryInfo}
|
||||
{#if categoryInfo?.exists}
|
||||
<BottomSheet bind:isOpen class="flex flex-col">
|
||||
<FullscreenDiv>
|
||||
<SubCategories
|
||||
class="py-4"
|
||||
info={categoryInfo}
|
||||
onSubCategoryClick={({ id }) =>
|
||||
(categoryInfoPromise = getCategoryInfo(id, $masterKeyStore?.get(1)?.key!))}
|
||||
onSubCategoryCreateClick={() => (isCategoryCreateModalOpen = true)}
|
||||
subCategoryCreatePosition="top"
|
||||
/>
|
||||
{#if categoryInfo.id !== "root"}
|
||||
<BottomDiv>
|
||||
<Button onclick={() => onAddToCategoryClick(categoryInfo.id)} class="w-full">
|
||||
이 카테고리에 추가하기
|
||||
</Button>
|
||||
</BottomDiv>
|
||||
{/if}
|
||||
</FullscreenDiv>
|
||||
</BottomSheet>
|
||||
{#if categoryInfo?.exists}
|
||||
<BottomSheet bind:isOpen class="flex flex-col">
|
||||
<FullscreenDiv>
|
||||
<SubCategories
|
||||
class="py-4"
|
||||
info={categoryInfo}
|
||||
onSubCategoryClick={({ id }) =>
|
||||
HybridPromise.resolve(getCategoryInfo(id, $masterKeyStore?.get(1)?.key!)).then(
|
||||
(result) => (categoryInfo = result),
|
||||
)}
|
||||
onSubCategoryCreateClick={() => (isCategoryCreateModalOpen = true)}
|
||||
subCategoryCreatePosition="top"
|
||||
/>
|
||||
{#if categoryInfo.id !== "root"}
|
||||
<BottomDiv>
|
||||
<Button onclick={() => onAddToCategoryClick(categoryInfo!.id as number)} class="w-full">
|
||||
{categoryInfo!.name} 카테고리에 추가하기
|
||||
</Button>
|
||||
</BottomDiv>
|
||||
{/if}
|
||||
</FullscreenDiv>
|
||||
</BottomSheet>
|
||||
{/if}
|
||||
|
||||
<CategoryCreateModal
|
||||
bind:isOpen={isCategoryCreateModalOpen}
|
||||
onCreateClick={async (name: string) => {
|
||||
if (await requestCategoryCreation(name, categoryInfo.id, $masterKeyStore?.get(1)!)) {
|
||||
categoryInfoPromise = getCategoryInfo(categoryInfo.id, $masterKeyStore?.get(1)?.key!); // TODO: FIXME
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}}
|
||||
/>
|
||||
{/if}
|
||||
{/await}
|
||||
<CategoryCreateModal
|
||||
bind:isOpen={isCategoryCreateModalOpen}
|
||||
onCreateClick={async (name: string) => {
|
||||
if (await requestCategoryCreation(name, categoryInfo!.id, $masterKeyStore?.get(1)!)) {
|
||||
void getCategoryInfo(categoryInfo!.id, $masterKeyStore?.get(1)?.key!); // TODO: FIXME
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}}
|
||||
/>
|
||||
|
||||
@@ -1,15 +1,54 @@
|
||||
<script lang="ts">
|
||||
import { onMount } from "svelte";
|
||||
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 { Gallery } from "$lib/components/organisms";
|
||||
import { bulkGetFileInfo, type MaybeFileInfo } from "$lib/modules/filesystem";
|
||||
import {
|
||||
bulkGetFileInfo,
|
||||
type MaybeFileInfo,
|
||||
type SummarizedFileInfo,
|
||||
} from "$lib/modules/filesystem";
|
||||
import { masterKeyStore } from "$lib/stores";
|
||||
import { formatDate, formatDateSortable, SortBy, sortEntries } from "$lib/utils";
|
||||
|
||||
let { data } = $props();
|
||||
|
||||
type Row =
|
||||
| { type: "header"; label: string }
|
||||
| { type: "items"; files: SummarizedFileInfo[]; isLast: boolean };
|
||||
|
||||
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 () => {
|
||||
files = Array.from((await bulkGetFileInfo(data.files, $masterKeyStore?.get(1)?.key!)).values());
|
||||
@@ -22,8 +61,37 @@
|
||||
|
||||
<TopBar title="사진 및 동영상" />
|
||||
<FullscreenDiv>
|
||||
<Gallery
|
||||
files={files.filter((file) => file?.exists)}
|
||||
onFileClick={({ id }) => goto(`/file/${id}?from=gallery`)}
|
||||
/>
|
||||
<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={() => 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>
|
||||
|
||||
@@ -1,12 +1,16 @@
|
||||
<script lang="ts">
|
||||
import { goto } from "$app/navigation";
|
||||
import { TopBar } from "$lib/components/molecules";
|
||||
import { Category, CategoryCreateModal } from "$lib/components/organisms";
|
||||
import { CheckBox, RowVirtualizer } from "$lib/components/atoms";
|
||||
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 { masterKeyStore } from "$lib/stores";
|
||||
import { HybridPromise, sortEntries } from "$lib/utils";
|
||||
import CategoryDeleteModal from "./CategoryDeleteModal.svelte";
|
||||
import CategoryMenuBottomSheet from "./CategoryMenuBottomSheet.svelte";
|
||||
import CategoryRenameModal from "./CategoryRenameModal.svelte";
|
||||
import File from "./File.svelte";
|
||||
import {
|
||||
createContext,
|
||||
requestCategoryCreation,
|
||||
@@ -15,18 +19,50 @@
|
||||
requestCategoryDeletion,
|
||||
} from "./service.svelte";
|
||||
|
||||
import IconMoreVert from "~icons/material-symbols/more-vert";
|
||||
|
||||
let { data } = $props();
|
||||
let context = createContext();
|
||||
|
||||
let infoPromise: Promise<MaybeCategoryInfo> | undefined = $state();
|
||||
let info: MaybeCategoryInfo | undefined = $state();
|
||||
|
||||
let isCategoryCreateModalOpen = $state(false);
|
||||
let isCategoryMenuBottomSheetOpen = $state(false);
|
||||
let isCategoryRenameModalOpen = $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(() => {
|
||||
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>
|
||||
|
||||
@@ -34,70 +70,98 @@
|
||||
<title>카테고리</title>
|
||||
</svelte:head>
|
||||
|
||||
{#await infoPromise then info}
|
||||
{#if info?.id !== "root"}
|
||||
<TopBar title={info?.name} />
|
||||
{/if}
|
||||
<div class="min-h-full bg-gray-100 pb-[5.5em]">
|
||||
{#if info?.exists}
|
||||
{#if info.id !== "root"}
|
||||
<TopBar title={info.name} />
|
||||
{/if}
|
||||
<div class="min-h-full bg-gray-100 pb-[5.5em]">
|
||||
<Category
|
||||
bind:isFileRecursive={info.isFileRecursive}
|
||||
{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}`)}
|
||||
onSubCategoryCreateClick={() => (isCategoryCreateModalOpen = true)}
|
||||
onSubCategoryMenuClick={(subCategory) => {
|
||||
context.selectedCategory = subCategory;
|
||||
isCategoryMenuBottomSheetOpen = true;
|
||||
}}
|
||||
/>
|
||||
<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={({ id }) => goto(`/category/${id}`)}
|
||||
onSubCategoryCreateClick={() => (isCategoryCreateModalOpen = true)}
|
||||
onSubCategoryMenuClick={(subCategory) => {
|
||||
context.selectedCategory = subCategory;
|
||||
isCategoryMenuBottomSheetOpen = true;
|
||||
}}
|
||||
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={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>
|
||||
|
||||
<CategoryCreateModal
|
||||
bind:isOpen={isCategoryCreateModalOpen}
|
||||
onCreateClick={async (name: string) => {
|
||||
if (await requestCategoryCreation(name, data.id, $masterKeyStore?.get(1)!)) {
|
||||
infoPromise = getCategoryInfo(data.id, $masterKeyStore?.get(1)?.key!); // TODO: FIXME
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}}
|
||||
/>
|
||||
|
||||
<CategoryMenuBottomSheet
|
||||
bind:isOpen={isCategoryMenuBottomSheetOpen}
|
||||
onRenameClick={() => {
|
||||
isCategoryMenuBottomSheetOpen = false;
|
||||
isCategoryRenameModalOpen = true;
|
||||
}}
|
||||
onDeleteClick={() => {
|
||||
isCategoryMenuBottomSheetOpen = false;
|
||||
isCategoryDeleteModalOpen = true;
|
||||
}}
|
||||
/>
|
||||
<CategoryRenameModal
|
||||
bind:isOpen={isCategoryRenameModalOpen}
|
||||
onRenameClick={async (newName: string) => {
|
||||
if (await requestCategoryRename(context.selectedCategory!, newName)) {
|
||||
infoPromise = getCategoryInfo(data.id, $masterKeyStore?.get(1)?.key!); // TODO: FIXME
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}}
|
||||
/>
|
||||
<CategoryDeleteModal
|
||||
bind:isOpen={isCategoryDeleteModalOpen}
|
||||
onDeleteClick={async () => {
|
||||
if (await requestCategoryDeletion(context.selectedCategory!)) {
|
||||
infoPromise = getCategoryInfo(data.id, $masterKeyStore?.get(1)?.key!); // TODO: FIXME
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}}
|
||||
/>
|
||||
{/if}
|
||||
{/await}
|
||||
</div>
|
||||
|
||||
<CategoryCreateModal
|
||||
bind:isOpen={isCategoryCreateModalOpen}
|
||||
onCreateClick={async (name: string) => {
|
||||
if (await requestCategoryCreation(name, data.id, $masterKeyStore?.get(1)!)) {
|
||||
void getCategoryInfo(data.id, $masterKeyStore?.get(1)?.key!); // TODO: FIXME
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}}
|
||||
/>
|
||||
|
||||
<CategoryMenuBottomSheet
|
||||
bind:isOpen={isCategoryMenuBottomSheetOpen}
|
||||
onRenameClick={() => {
|
||||
isCategoryMenuBottomSheetOpen = false;
|
||||
isCategoryRenameModalOpen = true;
|
||||
}}
|
||||
onDeleteClick={() => {
|
||||
isCategoryMenuBottomSheetOpen = false;
|
||||
isCategoryDeleteModalOpen = true;
|
||||
}}
|
||||
/>
|
||||
<CategoryRenameModal
|
||||
bind:isOpen={isCategoryRenameModalOpen}
|
||||
onRenameClick={async (newName: string) => {
|
||||
if (await requestCategoryRename(context.selectedCategory!, newName)) {
|
||||
void getCategoryInfo(data.id, $masterKeyStore?.get(1)?.key!); // TODO: FIXME
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}}
|
||||
/>
|
||||
<CategoryDeleteModal
|
||||
bind:isOpen={isCategoryDeleteModalOpen}
|
||||
onDeleteClick={async () => {
|
||||
if (await requestCategoryDeletion(context.selectedCategory!)) {
|
||||
void getCategoryInfo(data.id, $masterKeyStore?.get(1)?.key!); // TODO: FIXME
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}}
|
||||
/>
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
<script lang="ts">
|
||||
import { browser } from "$app/environment";
|
||||
import { ActionEntryButton } from "$lib/components/atoms";
|
||||
import { DirectoryEntryLabel } from "$lib/components/molecules";
|
||||
import { getFileThumbnail } from "$lib/modules/file";
|
||||
import type { CategoryFileInfo } from "$lib/modules/filesystem";
|
||||
import { requestFileThumbnailDownload } from "$lib/services/file";
|
||||
import type { SelectedFile } from "./service";
|
||||
import type { SelectedFile } from "./service.svelte";
|
||||
|
||||
import IconClose from "~icons/material-symbols/close";
|
||||
|
||||
@@ -16,12 +15,7 @@
|
||||
|
||||
let { info, onclick, onRemoveClick }: Props = $props();
|
||||
|
||||
let showThumbnail = $derived(
|
||||
browser && (info.contentType.startsWith("image/") || info.contentType.startsWith("video/")),
|
||||
);
|
||||
let thumbnailPromise = $derived(
|
||||
showThumbnail ? requestFileThumbnailDownload(info.id, info.dataKey?.key) : null,
|
||||
);
|
||||
let thumbnail = $derived(getFileThumbnail(info));
|
||||
</script>
|
||||
|
||||
<ActionEntryButton
|
||||
@@ -30,9 +24,5 @@
|
||||
actionButtonIcon={onRemoveClick && IconClose}
|
||||
onActionButtonClick={() => onRemoveClick?.(info)}
|
||||
>
|
||||
{#await thumbnailPromise}
|
||||
<DirectoryEntryLabel type="file" name={info.name} />
|
||||
{:then thumbnail}
|
||||
<DirectoryEntryLabel type="file" thumbnail={thumbnail ?? undefined} name={info.name} />
|
||||
{/await}
|
||||
<DirectoryEntryLabel type="file" thumbnail={$thumbnail} name={info.name} />
|
||||
</ActionEntryButton>
|
||||
@@ -5,6 +5,11 @@ import { trpc } from "$trpc/client";
|
||||
|
||||
export { requestCategoryCreation, requestFileRemovalFromCategory } from "$lib/services/category";
|
||||
|
||||
export interface SelectedFile {
|
||||
id: number;
|
||||
name: string;
|
||||
}
|
||||
|
||||
export const createContext = () => {
|
||||
const context = $state({
|
||||
selectedCategory: undefined as SelectedCategory | undefined,
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
import { TopBar } from "$lib/components/molecules";
|
||||
import { getDirectoryInfo, type MaybeDirectoryInfo } from "$lib/modules/filesystem";
|
||||
import { masterKeyStore, hmacSecretStore } from "$lib/stores";
|
||||
import { HybridPromise } from "$lib/utils";
|
||||
import DirectoryCreateModal from "./DirectoryCreateModal.svelte";
|
||||
import DirectoryEntries from "./DirectoryEntries";
|
||||
import DownloadStatusCard from "./DownloadStatusCard.svelte";
|
||||
@@ -29,7 +30,7 @@
|
||||
let { data } = $props();
|
||||
let context = createContext();
|
||||
|
||||
let infoPromise: Promise<MaybeDirectoryInfo> | undefined = $state();
|
||||
let info: MaybeDirectoryInfo | undefined = $state();
|
||||
let fileInput: HTMLInputElement | undefined = $state();
|
||||
let duplicatedFile: File | undefined = $state();
|
||||
let resolveForDuplicateFileModal: ((res: boolean) => void) | undefined = $state();
|
||||
@@ -60,7 +61,7 @@
|
||||
.then((res) => {
|
||||
if (!res) return;
|
||||
// TODO: FIXME
|
||||
infoPromise = getDirectoryInfo(data.id, $masterKeyStore?.get(1)?.key!);
|
||||
void getDirectoryInfo(data.id, $masterKeyStore?.get(1)?.key!);
|
||||
})
|
||||
.catch((e: Error) => {
|
||||
// TODO: FIXME
|
||||
@@ -78,7 +79,13 @@
|
||||
});
|
||||
|
||||
$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>
|
||||
|
||||
@@ -88,17 +95,17 @@
|
||||
|
||||
<input bind:this={fileInput} onchange={uploadFile} type="file" multiple class="hidden" />
|
||||
|
||||
{#await infoPromise then info}
|
||||
<div class="flex h-full flex-col">
|
||||
{#if showTopBar}
|
||||
<TopBar title={info?.name} class="flex-shrink-0" />
|
||||
{/if}
|
||||
{#if info?.exists}
|
||||
<div class="flex h-full flex-col">
|
||||
{#if showTopBar}
|
||||
<TopBar title={info.name} class="flex-shrink-0" />
|
||||
{/if}
|
||||
<div class={["flex flex-grow flex-col px-4 pb-4", !showTopBar && "pt-4"]}>
|
||||
<div class="flex gap-x-2">
|
||||
<UploadStatusCard onclick={() => goto("/file/uploads")} />
|
||||
<DownloadStatusCard onclick={() => goto("/file/downloads")} />
|
||||
</div>
|
||||
<div class={["flex flex-grow flex-col px-4 pb-4", !showTopBar && "pt-4"]}>
|
||||
<div class="flex gap-x-2">
|
||||
<UploadStatusCard onclick={() => goto("/file/uploads")} />
|
||||
<DownloadStatusCard onclick={() => goto("/file/downloads")} />
|
||||
</div>
|
||||
{#key info.id}
|
||||
<DirectoryEntries
|
||||
{info}
|
||||
onEntryClick={({ type, id }) => goto(`/${type}/${id}`)}
|
||||
@@ -109,85 +116,85 @@
|
||||
showParentEntry={isFromFilePage && info.parentId !== undefined}
|
||||
onParentClick={() =>
|
||||
goto(
|
||||
info.parentId === "root"
|
||||
info!.parentId === "root"
|
||||
? "/directory?from=file"
|
||||
: `/directory/${info.parentId}?from=file`,
|
||||
: `/directory/${info!.parentId}?from=file`,
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
{/key}
|
||||
</div>
|
||||
|
||||
<FloatingButton
|
||||
icon={IconAdd}
|
||||
onclick={() => {
|
||||
isEntryCreateBottomSheetOpen = true;
|
||||
}}
|
||||
class="bottom-24 right-4"
|
||||
/>
|
||||
<EntryCreateBottomSheet
|
||||
bind:isOpen={isEntryCreateBottomSheetOpen}
|
||||
onDirectoryCreateClick={() => {
|
||||
isEntryCreateBottomSheetOpen = false;
|
||||
isDirectoryCreateModalOpen = true;
|
||||
}}
|
||||
onFileUploadClick={() => {
|
||||
isEntryCreateBottomSheetOpen = false;
|
||||
fileInput?.click();
|
||||
}}
|
||||
/>
|
||||
<DirectoryCreateModal
|
||||
bind:isOpen={isDirectoryCreateModalOpen}
|
||||
onCreateClick={async (name) => {
|
||||
if (await requestDirectoryCreation(name, data.id, $masterKeyStore?.get(1)!)) {
|
||||
infoPromise = getDirectoryInfo(data.id, $masterKeyStore?.get(1)?.key!); // TODO: FIXME
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}}
|
||||
/>
|
||||
<DuplicateFileModal
|
||||
bind:isOpen={isDuplicateFileModalOpen}
|
||||
file={duplicatedFile}
|
||||
onbeforeclose={() => {
|
||||
resolveForDuplicateFileModal?.(false);
|
||||
isDuplicateFileModalOpen = false;
|
||||
}}
|
||||
onUploadClick={() => {
|
||||
resolveForDuplicateFileModal?.(true);
|
||||
isDuplicateFileModalOpen = false;
|
||||
}}
|
||||
/>
|
||||
|
||||
<EntryMenuBottomSheet
|
||||
bind:isOpen={isEntryMenuBottomSheetOpen}
|
||||
onRenameClick={() => {
|
||||
isEntryMenuBottomSheetOpen = false;
|
||||
isEntryRenameModalOpen = true;
|
||||
}}
|
||||
onDeleteClick={() => {
|
||||
isEntryMenuBottomSheetOpen = false;
|
||||
isEntryDeleteModalOpen = true;
|
||||
}}
|
||||
/>
|
||||
<EntryRenameModal
|
||||
bind:isOpen={isEntryRenameModalOpen}
|
||||
onRenameClick={async (newName: string) => {
|
||||
if (await requestEntryRename(context.selectedEntry!, newName)) {
|
||||
infoPromise = getDirectoryInfo(data.id, $masterKeyStore?.get(1)?.key!); // TODO: FIXME
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}}
|
||||
/>
|
||||
<EntryDeleteModal
|
||||
bind:isOpen={isEntryDeleteModalOpen}
|
||||
onDeleteClick={async () => {
|
||||
if (await requestEntryDeletion(context.selectedEntry!)) {
|
||||
infoPromise = getDirectoryInfo(data.id, $masterKeyStore?.get(1)?.key!); // TODO: FIXME
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}}
|
||||
/>
|
||||
{/if}
|
||||
{/await}
|
||||
</div>
|
||||
|
||||
<FloatingButton
|
||||
icon={IconAdd}
|
||||
onclick={() => {
|
||||
isEntryCreateBottomSheetOpen = true;
|
||||
}}
|
||||
class="bottom-24 right-4"
|
||||
/>
|
||||
<EntryCreateBottomSheet
|
||||
bind:isOpen={isEntryCreateBottomSheetOpen}
|
||||
onDirectoryCreateClick={() => {
|
||||
isEntryCreateBottomSheetOpen = false;
|
||||
isDirectoryCreateModalOpen = true;
|
||||
}}
|
||||
onFileUploadClick={() => {
|
||||
isEntryCreateBottomSheetOpen = false;
|
||||
fileInput?.click();
|
||||
}}
|
||||
/>
|
||||
<DirectoryCreateModal
|
||||
bind:isOpen={isDirectoryCreateModalOpen}
|
||||
onCreateClick={async (name) => {
|
||||
if (await requestDirectoryCreation(name, data.id, $masterKeyStore?.get(1)!)) {
|
||||
void getDirectoryInfo(data.id, $masterKeyStore?.get(1)?.key!); // TODO: FIXME
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}}
|
||||
/>
|
||||
<DuplicateFileModal
|
||||
bind:isOpen={isDuplicateFileModalOpen}
|
||||
file={duplicatedFile}
|
||||
onbeforeclose={() => {
|
||||
resolveForDuplicateFileModal?.(false);
|
||||
isDuplicateFileModalOpen = false;
|
||||
}}
|
||||
onUploadClick={() => {
|
||||
resolveForDuplicateFileModal?.(true);
|
||||
isDuplicateFileModalOpen = false;
|
||||
}}
|
||||
/>
|
||||
|
||||
<EntryMenuBottomSheet
|
||||
bind:isOpen={isEntryMenuBottomSheetOpen}
|
||||
onRenameClick={() => {
|
||||
isEntryMenuBottomSheetOpen = false;
|
||||
isEntryRenameModalOpen = true;
|
||||
}}
|
||||
onDeleteClick={() => {
|
||||
isEntryMenuBottomSheetOpen = false;
|
||||
isEntryDeleteModalOpen = true;
|
||||
}}
|
||||
/>
|
||||
<EntryRenameModal
|
||||
bind:isOpen={isEntryRenameModalOpen}
|
||||
onRenameClick={async (newName: string) => {
|
||||
if (await requestEntryRename(context.selectedEntry!, newName)) {
|
||||
void getDirectoryInfo(data.id, $masterKeyStore?.get(1)?.key!); // TODO: FIXME
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}}
|
||||
/>
|
||||
<EntryDeleteModal
|
||||
bind:isOpen={isEntryDeleteModalOpen}
|
||||
onDeleteClick={async () => {
|
||||
if (await requestEntryDeletion(context.selectedEntry!)) {
|
||||
void getDirectoryInfo(data.id, $masterKeyStore?.get(1)?.key!); // TODO: FIXME
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}}
|
||||
/>
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
<script lang="ts">
|
||||
import { browser } from "$app/environment";
|
||||
import { ActionEntryButton } from "$lib/components/atoms";
|
||||
import { DirectoryEntryLabel } from "$lib/components/molecules";
|
||||
import { getFileThumbnail } from "$lib/modules/file";
|
||||
import type { SummarizedFileInfo } from "$lib/modules/filesystem";
|
||||
import { requestFileThumbnailDownload } from "$lib/services/file";
|
||||
import { formatDateTime } from "$lib/utils";
|
||||
import type { SelectedEntry } from "../service.svelte";
|
||||
|
||||
@@ -17,12 +16,7 @@
|
||||
|
||||
let { info, onclick, onOpenMenuClick }: Props = $props();
|
||||
|
||||
let showThumbnail = $derived(
|
||||
browser && (info.contentType.startsWith("image/") || info.contentType.startsWith("video/")),
|
||||
);
|
||||
let thumbnailPromise = $derived(
|
||||
showThumbnail ? requestFileThumbnailDownload(info.id, info.dataKey?.key) : null,
|
||||
);
|
||||
let thumbnail = $derived(getFileThumbnail(info));
|
||||
|
||||
const action = (callback: typeof onclick) => {
|
||||
callback({ type: "file", id: info.id, dataKey: info.dataKey, name: info.name });
|
||||
@@ -35,18 +29,10 @@
|
||||
actionButtonIcon={IconMoreVert}
|
||||
onActionButtonClick={() => action(onOpenMenuClick)}
|
||||
>
|
||||
{#await thumbnailPromise}
|
||||
<DirectoryEntryLabel
|
||||
type="file"
|
||||
name={info.name}
|
||||
subtext={formatDateTime(info.createdAt ?? info.lastModifiedAt)}
|
||||
/>
|
||||
{:then thumbnail}
|
||||
<DirectoryEntryLabel
|
||||
type="file"
|
||||
thumbnail={thumbnail ?? undefined}
|
||||
name={info.name}
|
||||
subtext={formatDateTime(info.createdAt ?? info.lastModifiedAt)}
|
||||
/>
|
||||
{/await}
|
||||
<DirectoryEntryLabel
|
||||
type="file"
|
||||
thumbnail={$thumbnail}
|
||||
name={info.name}
|
||||
subtext={formatDateTime(info.createdAt ?? info.lastModifiedAt)}
|
||||
/>
|
||||
</ActionEntryButton>
|
||||
|
||||
@@ -2,22 +2,13 @@
|
||||
import { onMount } from "svelte";
|
||||
import { goto } from "$app/navigation";
|
||||
import { EntryButton, FileThumbnailButton } from "$lib/components/atoms";
|
||||
import { bulkGetFileInfo, type MaybeFileInfo } from "$lib/modules/filesystem";
|
||||
import { masterKeyStore } from "$lib/stores";
|
||||
import { type SummarizedFileInfo } from "$lib/modules/filesystem";
|
||||
import { requestFreshMediaFilesRetrieval } from "./service";
|
||||
|
||||
let mediaFiles: MaybeFileInfo[] = $state([]);
|
||||
let mediaFiles: SummarizedFileInfo[] = $state([]);
|
||||
|
||||
onMount(async () => {
|
||||
const files = await requestFreshMediaFilesRetrieval();
|
||||
mediaFiles = Array.from(
|
||||
(
|
||||
await bulkGetFileInfo(
|
||||
files.map(({ id }) => id),
|
||||
$masterKeyStore?.get(1)?.key!,
|
||||
)
|
||||
).values(),
|
||||
);
|
||||
mediaFiles = await requestFreshMediaFilesRetrieval();
|
||||
});
|
||||
</script>
|
||||
|
||||
@@ -34,9 +25,7 @@
|
||||
{#if mediaFiles.length > 0}
|
||||
<div class="grid grid-cols-4 gap-2 p-2">
|
||||
{#each mediaFiles as file (file.id)}
|
||||
{#if file.exists}
|
||||
<FileThumbnailButton info={file} onclick={({ id }) => goto(`/file/${id}`)} />
|
||||
{/if}
|
||||
<FileThumbnailButton info={file} onclick={({ id }) => goto(`/file/${id}`)} />
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
@@ -46,6 +46,7 @@ const categoryRouter = router({
|
||||
})),
|
||||
files: files?.map((file) => ({
|
||||
id: file.id,
|
||||
parent: file.parentId,
|
||||
mekVersion: file.mekVersion,
|
||||
dek: file.encDek,
|
||||
dekVersion: file.dekVersion,
|
||||
|
||||
@@ -33,6 +33,7 @@ const fileRouter = router({
|
||||
lastModifiedAtIv: file.encLastModifiedAt.iv,
|
||||
categories: categories.map((category) => ({
|
||||
id: category.id,
|
||||
parent: category.parentId,
|
||||
mekVersion: category.mekVersion,
|
||||
dek: category.encDek,
|
||||
dekVersion: category.dekVersion,
|
||||
@@ -66,6 +67,7 @@ const fileRouter = router({
|
||||
lastModifiedAtIv: file.encLastModifiedAt.iv,
|
||||
categories: file.categories.map((category) => ({
|
||||
id: category.id,
|
||||
parent: category.parentId,
|
||||
mekVersion: category.mekVersion,
|
||||
dek: category.encDek,
|
||||
dekVersion: category.dekVersion,
|
||||
|
||||
Reference in New Issue
Block a user