mirror of
https://github.com/kmc7468/arkvault.git
synced 2026-02-04 08:06:56 +00:00
Compare commits
20 Commits
3fc29cf8db
...
v0.6.0
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
90ac5ba4c3 | ||
|
|
0d13d3baef | ||
|
|
576d41da7f | ||
|
|
9eb67d5877 | ||
|
|
a9da8435cb | ||
|
|
3e98e3d591 | ||
|
|
27a46bcc2e | ||
|
|
a1f30ee154 | ||
|
|
6d02178c69 | ||
|
|
ed21a9cd31 | ||
|
|
b7a7536461 | ||
|
|
3eb7411438 | ||
|
|
c9d4b10356 | ||
|
|
d94d14cf83 | ||
|
|
dfffa004ac | ||
|
|
0cd55a413d | ||
|
|
361d966a59 | ||
|
|
aef43b8bfa | ||
|
|
7f128cccf6 | ||
|
|
a198e5f6dc |
@@ -1,21 +1,24 @@
|
||||
import prettier from "eslint-config-prettier";
|
||||
import js from "@eslint/js";
|
||||
import { includeIgnoreFile } from "@eslint/compat";
|
||||
import js from "@eslint/js";
|
||||
import { defineConfig } from "eslint/config";
|
||||
import prettier from "eslint-config-prettier";
|
||||
import svelte from "eslint-plugin-svelte";
|
||||
import tailwind from "eslint-plugin-tailwindcss";
|
||||
import globals from "globals";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import ts from "typescript-eslint";
|
||||
import { fileURLToPath } from "url";
|
||||
import svelteConfig from "./svelte.config.js";
|
||||
|
||||
const gitignorePath = fileURLToPath(new URL("./.gitignore", import.meta.url));
|
||||
|
||||
export default ts.config(
|
||||
export default defineConfig(
|
||||
includeIgnoreFile(gitignorePath),
|
||||
js.configs.recommended,
|
||||
...ts.configs.recommended,
|
||||
...svelte.configs["flat/recommended"],
|
||||
...svelte.configs.recommended,
|
||||
...tailwind.configs["flat/recommended"],
|
||||
prettier,
|
||||
...svelte.configs["flat/prettier"],
|
||||
...svelte.configs.prettier,
|
||||
{
|
||||
languageOptions: {
|
||||
globals: {
|
||||
@@ -23,13 +26,18 @@ export default ts.config(
|
||||
...globals.node,
|
||||
},
|
||||
},
|
||||
rules: {
|
||||
"no-undef": "off",
|
||||
},
|
||||
},
|
||||
{
|
||||
files: ["**/*.svelte"],
|
||||
|
||||
files: ["**/*.svelte", "**/*.svelte.ts", "**/*.svelte.js"],
|
||||
languageOptions: {
|
||||
parserOptions: {
|
||||
projectService: true,
|
||||
extraFileExtensions: [".svelte"],
|
||||
parser: ts.parser,
|
||||
svelteConfig,
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "arkvault",
|
||||
"private": true,
|
||||
"version": "0.5.1",
|
||||
"version": "0.6.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite dev",
|
||||
@@ -16,11 +16,12 @@
|
||||
"db:migrate": "kysely migrate"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/compat": "^1.4.1",
|
||||
"@eslint/compat": "^2.0.0",
|
||||
"@iconify-json/material-symbols": "^1.2.50",
|
||||
"@sveltejs/adapter-node": "^5.4.0",
|
||||
"@sveltejs/kit": "^2.49.2",
|
||||
"@sveltejs/vite-plugin-svelte": "^6.2.1",
|
||||
"@tanstack/svelte-virtual": "^3.13.13",
|
||||
"@trpc/client": "^11.8.1",
|
||||
"@types/file-saver": "^2.0.7",
|
||||
"@types/ms": "^0.7.34",
|
||||
|
||||
40
pnpm-lock.yaml
generated
40
pnpm-lock.yaml
generated
@@ -40,8 +40,8 @@ importers:
|
||||
version: 4.2.1
|
||||
devDependencies:
|
||||
'@eslint/compat':
|
||||
specifier: ^1.4.1
|
||||
version: 1.4.1(eslint@9.39.2(jiti@1.21.7))
|
||||
specifier: ^2.0.0
|
||||
version: 2.0.0(eslint@9.39.2(jiti@1.21.7))
|
||||
'@iconify-json/material-symbols':
|
||||
specifier: ^1.2.50
|
||||
version: 1.2.50
|
||||
@@ -54,6 +54,9 @@ importers:
|
||||
'@sveltejs/vite-plugin-svelte':
|
||||
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.13
|
||||
version: 3.13.13(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)
|
||||
@@ -323,9 +326,9 @@ packages:
|
||||
resolution: {integrity: sha512-EriSTlt5OC9/7SXkRSCAhfSxxoSUgBm33OH+IkwbdpgoqsSsUg7y3uh+IICI/Qg4BBWr3U2i39RpmycbxMq4ew==}
|
||||
engines: {node: ^12.0.0 || ^14.0.0 || >=16.0.0}
|
||||
|
||||
'@eslint/compat@1.4.1':
|
||||
resolution: {integrity: sha512-cfO82V9zxxGBxcQDr1lfaYB7wykTa0b00mGa36FrJl7iTFd0Z2cHfEYuxcBRP/iNijCsWsEkA+jzT8hGYmv33w==}
|
||||
engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}
|
||||
'@eslint/compat@2.0.0':
|
||||
resolution: {integrity: sha512-T9AfE1G1uv4wwq94ozgTGio5EUQBqAVe1X9qsQtSNVEYW6j3hvtZVm8Smr4qL1qDPFg+lOB2cL5RxTRMzq4CTA==}
|
||||
engines: {node: ^20.19.0 || ^22.13.0 || >=24}
|
||||
peerDependencies:
|
||||
eslint: ^8.40 || 9
|
||||
peerDependenciesMeta:
|
||||
@@ -344,6 +347,10 @@ packages:
|
||||
resolution: {integrity: sha512-yL/sLrpmtDaFEiUj1osRP4TI2MDz1AddJL+jZ7KSqvBuliN4xqYY54IfdN8qD8Toa6g1iloph1fxQNkjOxrrpQ==}
|
||||
engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}
|
||||
|
||||
'@eslint/core@1.0.0':
|
||||
resolution: {integrity: sha512-PRfWP+8FOldvbApr6xL7mNCw4cJcSTq4GA7tYbgq15mRb0kWKO/wEB2jr+uwjFH3sZvEZneZyCUGTxsv4Sahyw==}
|
||||
engines: {node: ^20.19.0 || ^22.13.0 || >=24}
|
||||
|
||||
'@eslint/eslintrc@3.3.3':
|
||||
resolution: {integrity: sha512-Kr+LPIUVKz2qkx1HAMH8q1q6azbqBAsXJUxBl/ODDuVPX45Z9DfwB8tPjTi6nNZ8BuM3nbJxC5zCAg5elnBUTQ==}
|
||||
engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}
|
||||
@@ -610,6 +617,14 @@ packages:
|
||||
svelte: ^5.0.0
|
||||
vite: ^6.3.0 || ^7.0.0
|
||||
|
||||
'@tanstack/svelte-virtual@3.13.13':
|
||||
resolution: {integrity: sha512-VDOvbRw3R+XBQdFodEJ4E7AOmEyo3Bmr4zL4DLVnJ0fxICdbvY5F5t8zSwJ4f7lqjckXi0yKFzY8WBtjaNbsGQ==}
|
||||
peerDependencies:
|
||||
svelte: ^3.48.0 || ^4.0.0 || ^5.0.0
|
||||
|
||||
'@tanstack/virtual-core@3.13.13':
|
||||
resolution: {integrity: sha512-uQFoSdKKf5S8k51W5t7b2qpfkyIbdHMzAn+AMQvHPxKUPeo1SsGaA4JRISQT87jm28b7z8OEqPcg1IOZagQHcA==}
|
||||
|
||||
'@trpc/client@11.8.1':
|
||||
resolution: {integrity: sha512-L/SJFGanr9xGABmuDoeXR4xAdHJmsXsiF9OuH+apecJ+8sUITzVT1EPeqp0ebqA6lBhEl5pPfg3rngVhi/h60Q==}
|
||||
peerDependencies:
|
||||
@@ -2106,9 +2121,9 @@ snapshots:
|
||||
|
||||
'@eslint-community/regexpp@4.12.2': {}
|
||||
|
||||
'@eslint/compat@1.4.1(eslint@9.39.2(jiti@1.21.7))':
|
||||
'@eslint/compat@2.0.0(eslint@9.39.2(jiti@1.21.7))':
|
||||
dependencies:
|
||||
'@eslint/core': 0.17.0
|
||||
'@eslint/core': 1.0.0
|
||||
optionalDependencies:
|
||||
eslint: 9.39.2(jiti@1.21.7)
|
||||
|
||||
@@ -2128,6 +2143,10 @@ snapshots:
|
||||
dependencies:
|
||||
'@types/json-schema': 7.0.15
|
||||
|
||||
'@eslint/core@1.0.0':
|
||||
dependencies:
|
||||
'@types/json-schema': 7.0.15
|
||||
|
||||
'@eslint/eslintrc@3.3.3':
|
||||
dependencies:
|
||||
ajv: 6.12.6
|
||||
@@ -2367,6 +2386,13 @@ snapshots:
|
||||
transitivePeerDependencies:
|
||||
- supports-color
|
||||
|
||||
'@tanstack/svelte-virtual@3.13.13(svelte@5.46.1)':
|
||||
dependencies:
|
||||
'@tanstack/virtual-core': 3.13.13
|
||||
svelte: 5.46.1
|
||||
|
||||
'@tanstack/virtual-core@3.13.13': {}
|
||||
|
||||
'@trpc/client@11.8.1(@trpc/server@11.8.1(typescript@5.9.3))(typescript@5.9.3)':
|
||||
dependencies:
|
||||
'@trpc/server': 11.8.1(typescript@5.9.3)
|
||||
|
||||
42
src/lib/components/atoms/buttons/FileThumbnailButton.svelte
Normal file
42
src/lib/components/atoms/buttons/FileThumbnailButton.svelte
Normal file
@@ -0,0 +1,42 @@
|
||||
<script lang="ts">
|
||||
import type { Writable } from "svelte/store";
|
||||
import type { FileInfo } from "$lib/modules/filesystem";
|
||||
import { requestFileThumbnailDownload } from "$lib/services/file";
|
||||
|
||||
interface Props {
|
||||
info: Writable<FileInfo | null>;
|
||||
onclick?: (file: FileInfo) => void;
|
||||
}
|
||||
|
||||
let { info, onclick }: Props = $props();
|
||||
|
||||
let thumbnail: string | undefined = $state();
|
||||
|
||||
$effect(() => {
|
||||
if ($info) {
|
||||
requestFileThumbnailDownload($info.id, $info.dataKey)
|
||||
.then((thumbnailUrl) => {
|
||||
thumbnail = thumbnailUrl ?? undefined;
|
||||
})
|
||||
.catch(() => {
|
||||
// TODO: Error Handling
|
||||
thumbnail = undefined;
|
||||
});
|
||||
} else {
|
||||
thumbnail = undefined;
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
{#if $info}
|
||||
<button
|
||||
onclick={() => onclick?.($info)}
|
||||
class="aspect-square overflow-hidden rounded transition active:scale-95 active:brightness-90"
|
||||
>
|
||||
{#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}
|
||||
</button>
|
||||
{/if}
|
||||
@@ -1,5 +1,6 @@
|
||||
export { default as ActionEntryButton } from "./ActionEntryButton.svelte";
|
||||
export { default as Button } from "./Button.svelte";
|
||||
export { default as EntryButton } from "./EntryButton.svelte";
|
||||
export { default as FileThumbnailButton } from "./FileThumbnailButton.svelte";
|
||||
export { default as FloatingButton } from "./FloatingButton.svelte";
|
||||
export { default as TextButton } from "./TextButton.svelte";
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
import type { SvelteHTMLElements } from "svelte/elements";
|
||||
import { get, type Writable } from "svelte/store";
|
||||
import type { CategoryInfo } from "$lib/modules/filesystem";
|
||||
import { SortBy, sortEntries } from "$lib/modules/util";
|
||||
import { SortBy, sortEntries } from "$lib/utils";
|
||||
import Category from "./Category.svelte";
|
||||
import type { SelectedCategory } from "./service";
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
import { IconLabel } from "$lib/components/molecules";
|
||||
|
||||
import IconFolder from "~icons/material-symbols/folder";
|
||||
import IconDriveFolderUpload from "~icons/material-symbols/drive-folder-upload";
|
||||
import IconDraft from "~icons/material-symbols/draft";
|
||||
|
||||
interface Props {
|
||||
@@ -11,7 +12,7 @@
|
||||
subtext?: string;
|
||||
textClass?: ClassValue;
|
||||
thumbnail?: string;
|
||||
type: "directory" | "file";
|
||||
type: "directory" | "parent-directory" | "file";
|
||||
}
|
||||
|
||||
let {
|
||||
@@ -30,6 +31,8 @@
|
||||
<img src={thumbnail} alt={name} loading="lazy" class="aspect-square rounded object-cover" />
|
||||
{:else if type === "directory"}
|
||||
<IconFolder />
|
||||
{:else if type === "parent-directory"}
|
||||
<IconDriveFolderUpload class="text-yellow-500" />
|
||||
{:else}
|
||||
<IconDraft class="text-blue-400" />
|
||||
{/if}
|
||||
|
||||
@@ -4,8 +4,8 @@
|
||||
import { CheckBox } from "$lib/components/atoms";
|
||||
import { SubCategories, type SelectedCategory } from "$lib/components/molecules";
|
||||
import { getFileInfo, type FileInfo, type CategoryInfo } from "$lib/modules/filesystem";
|
||||
import { SortBy, sortEntries } from "$lib/modules/util";
|
||||
import { masterKeyStore } from "$lib/stores";
|
||||
import { SortBy, sortEntries } from "$lib/utils";
|
||||
import File from "./File.svelte";
|
||||
import type { SelectedFile } from "./service";
|
||||
|
||||
|
||||
148
src/lib/components/organisms/Gallery.svelte
Normal file
148
src/lib/components/organisms/Gallery.svelte
Normal file
@@ -0,0 +1,148 @@
|
||||
<script lang="ts">
|
||||
import { createWindowVirtualizer } from "@tanstack/svelte-virtual";
|
||||
import { untrack } from "svelte";
|
||||
import { get, type Writable } from "svelte/store";
|
||||
import { FileThumbnailButton } from "$lib/components/atoms";
|
||||
import type { FileInfo } from "$lib/modules/filesystem";
|
||||
import { formatDate, formatDateSortable, SortBy, sortEntries } from "$lib/utils";
|
||||
|
||||
interface Props {
|
||||
files: Writable<FileInfo | null>[];
|
||||
onFileClick?: (file: FileInfo) => void;
|
||||
}
|
||||
|
||||
let { files, onFileClick }: Props = $props();
|
||||
|
||||
type FileEntry =
|
||||
| { date?: undefined; contentType?: undefined; info: Writable<FileInfo | null> }
|
||||
| { date: Date; contentType: string; info: Writable<FileInfo | null> };
|
||||
type Row =
|
||||
| { type: "header"; key: string; label: string }
|
||||
| { type: "items"; key: string; items: FileEntry[] };
|
||||
|
||||
let filesWithDate: FileEntry[] = $state([]);
|
||||
let rows: Row[] = $state([]);
|
||||
let listElement: HTMLDivElement | undefined = $state();
|
||||
|
||||
const virtualizer = createWindowVirtualizer({
|
||||
count: 0,
|
||||
getItemKey: (index) => rows[index]!.key,
|
||||
estimateSize: () => 1000, // TODO
|
||||
});
|
||||
|
||||
const measureRow = (node: HTMLElement) => {
|
||||
$virtualizer.measureElement(node);
|
||||
return {
|
||||
update: () => $virtualizer.measureElement(node),
|
||||
};
|
||||
};
|
||||
|
||||
$effect(() => {
|
||||
filesWithDate = files.map((file) => {
|
||||
const info = get(file);
|
||||
if (info) {
|
||||
return {
|
||||
date: info.createdAt ?? info.lastModifiedAt,
|
||||
contentType: info.contentType,
|
||||
info: file,
|
||||
};
|
||||
} else {
|
||||
return { info: file };
|
||||
}
|
||||
});
|
||||
|
||||
const buildRows = () => {
|
||||
const map = new Map<string, FileEntry[]>();
|
||||
|
||||
for (const file of filesWithDate) {
|
||||
if (
|
||||
!file.date ||
|
||||
!(file.contentType.startsWith("image/") || file.contentType.startsWith("video/"))
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const date = formatDateSortable(file.date);
|
||||
const entries = map.get(date) ?? [];
|
||||
entries.push(file);
|
||||
map.set(date, entries);
|
||||
}
|
||||
|
||||
const newRows: Row[] = [];
|
||||
const sortedDates = Array.from(map.keys()).sort((a, b) => b.localeCompare(a));
|
||||
for (const date of sortedDates) {
|
||||
const entries = map.get(date)!;
|
||||
sortEntries(entries, SortBy.DATE_DESC);
|
||||
|
||||
newRows.push({
|
||||
type: "header",
|
||||
key: `header-${date}`,
|
||||
label: formatDate(entries[0]!.date!),
|
||||
});
|
||||
newRows.push({
|
||||
type: "items",
|
||||
key: `items-${date}`,
|
||||
items: entries,
|
||||
});
|
||||
}
|
||||
|
||||
rows = newRows;
|
||||
$virtualizer.setOptions({ count: rows.length });
|
||||
};
|
||||
return untrack(() => {
|
||||
buildRows();
|
||||
|
||||
const unsubscribes = filesWithDate.map((file) =>
|
||||
file.info.subscribe((value) => {
|
||||
const newDate = value?.createdAt ?? value?.lastModifiedAt;
|
||||
const newContentType = value?.contentType;
|
||||
if (file.date?.getTime() === newDate?.getTime() && file.contentType === newContentType) {
|
||||
return;
|
||||
}
|
||||
|
||||
file.date = newDate;
|
||||
file.contentType = newContentType;
|
||||
buildRows();
|
||||
}),
|
||||
);
|
||||
return () => unsubscribes.forEach((unsubscribe) => unsubscribe());
|
||||
});
|
||||
});
|
||||
</script>
|
||||
|
||||
<div bind:this={listElement} class="relative flex flex-grow flex-col">
|
||||
<div style="height: {$virtualizer.getTotalSize()}px;">
|
||||
{#each $virtualizer.getVirtualItems() as virtualRow (virtualRow.key)}
|
||||
{@const row = rows[virtualRow.index]!}
|
||||
<div
|
||||
use:measureRow
|
||||
data-index={virtualRow.index}
|
||||
class="absolute left-0 top-0 w-full"
|
||||
style="transform: translateY({virtualRow.start}px);"
|
||||
>
|
||||
{#if row.type === "header"}
|
||||
<p class="pb-2 font-medium">{row.label}</p>
|
||||
{:else}
|
||||
<div class="grid grid-cols-4 gap-1 pb-4">
|
||||
{#each row.items as { info }}
|
||||
<FileThumbnailButton {info} onclick={onFileClick} />
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
{#if $virtualizer.getVirtualItems().length === 0}
|
||||
<div class="flex h-full flex-grow items-center justify-center">
|
||||
<p class="text-gray-500">
|
||||
{#if files.length === 0}
|
||||
업로드된 파일이 없어요.
|
||||
{:else if filesWithDate.length === 0}
|
||||
파일 목록을 불러오고 있어요.
|
||||
{:else}
|
||||
사진 또는 동영상이 없어요.
|
||||
{/if}
|
||||
</p>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
@@ -1,3 +1,4 @@
|
||||
export * from "./Category";
|
||||
export { default as Category } from "./Category";
|
||||
export { default as Gallery } from "./Gallery.svelte";
|
||||
export * from "./modals";
|
||||
|
||||
@@ -1,11 +0,0 @@
|
||||
export const callGetApi = async (input: RequestInfo, fetchInternal = fetch) => {
|
||||
return await fetchInternal(input);
|
||||
};
|
||||
|
||||
export const callPostApi = async <T>(input: RequestInfo, payload?: T, fetchInternal = fetch) => {
|
||||
return await fetchInternal(input, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: payload ? JSON.stringify(payload) : undefined,
|
||||
});
|
||||
};
|
||||
@@ -1,2 +0,0 @@
|
||||
export * from "./callApi";
|
||||
export * from "./gotoStateful";
|
||||
@@ -23,15 +23,14 @@ import {
|
||||
type HmacSecret,
|
||||
type FileUploadStatus,
|
||||
} from "$lib/stores";
|
||||
import { useTRPC } from "$trpc/client";
|
||||
import { trpc } from "$trpc/client";
|
||||
|
||||
const requestDuplicateFileScan = limitFunction(
|
||||
async (file: File, hmacSecret: HmacSecret, onDuplicate: () => Promise<boolean>) => {
|
||||
const trpc = useTRPC();
|
||||
const fileBuffer = await file.arrayBuffer();
|
||||
const fileSigned = encodeToBase64(await signMessageHmac(fileBuffer, hmacSecret.secret));
|
||||
|
||||
const files = await trpc.file.listByHash.query({
|
||||
const files = await trpc().file.listByHash.query({
|
||||
hskVersion: hmacSecret.version,
|
||||
contentHmac: fileSigned,
|
||||
});
|
||||
|
||||
@@ -18,11 +18,12 @@ import {
|
||||
type CategoryId,
|
||||
} from "$lib/indexedDB";
|
||||
import { unwrapDataKey, decryptString } from "$lib/modules/crypto";
|
||||
import { useTRPC } from "$trpc/client";
|
||||
import { trpc } from "$trpc/client";
|
||||
|
||||
export type DirectoryInfo =
|
||||
| {
|
||||
id: "root";
|
||||
parentId?: undefined;
|
||||
dataKey?: undefined;
|
||||
dataKeyVersion?: undefined;
|
||||
name?: undefined;
|
||||
@@ -31,6 +32,7 @@ export type DirectoryInfo =
|
||||
}
|
||||
| {
|
||||
id: number;
|
||||
parentId: DirectoryId;
|
||||
dataKey?: CryptoKey;
|
||||
dataKeyVersion?: Date;
|
||||
name: string;
|
||||
@@ -40,6 +42,7 @@ export type DirectoryInfo =
|
||||
|
||||
export interface FileInfo {
|
||||
id: number;
|
||||
parentId: DirectoryId;
|
||||
dataKey?: CryptoKey;
|
||||
dataKeyVersion?: Date;
|
||||
contentType: string;
|
||||
@@ -92,7 +95,13 @@ const fetchDirectoryInfoFromIndexedDB = async (
|
||||
info.set({ id, subDirectoryIds, fileIds });
|
||||
} else {
|
||||
if (!directory) return;
|
||||
info.set({ id, name: directory.name, subDirectoryIds, fileIds });
|
||||
info.set({
|
||||
id,
|
||||
parentId: directory.parentId,
|
||||
name: directory.name,
|
||||
subDirectoryIds,
|
||||
fileIds,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
@@ -101,10 +110,9 @@ const fetchDirectoryInfoFromServer = async (
|
||||
info: Writable<DirectoryInfo | null>,
|
||||
masterKey: CryptoKey,
|
||||
) => {
|
||||
const trpc = useTRPC();
|
||||
let data;
|
||||
try {
|
||||
data = await trpc.directory.get.query({ id });
|
||||
data = await trpc().directory.get.query({ id });
|
||||
} catch (e) {
|
||||
if (e instanceof TRPCClientError && e.data?.code === "NOT_FOUND") {
|
||||
info.set(null);
|
||||
@@ -124,6 +132,7 @@ const fetchDirectoryInfoFromServer = async (
|
||||
|
||||
info.set({
|
||||
id,
|
||||
parentId: metadata!.parent,
|
||||
dataKey,
|
||||
dataKeyVersion: new Date(metadata!.dekVersion),
|
||||
name,
|
||||
@@ -174,10 +183,9 @@ const fetchFileInfoFromServer = async (
|
||||
info: Writable<FileInfo | null>,
|
||||
masterKey: CryptoKey,
|
||||
) => {
|
||||
const trpc = useTRPC();
|
||||
let metadata;
|
||||
try {
|
||||
metadata = await trpc.file.get.query({ id });
|
||||
metadata = await trpc().file.get.query({ id });
|
||||
} catch (e) {
|
||||
if (e instanceof TRPCClientError && e.data?.code === "NOT_FOUND") {
|
||||
info.set(null);
|
||||
@@ -201,6 +209,7 @@ const fetchFileInfoFromServer = async (
|
||||
|
||||
info.set({
|
||||
id,
|
||||
parentId: metadata.parent,
|
||||
dataKey,
|
||||
dataKeyVersion: new Date(metadata.dekVersion),
|
||||
contentType: metadata.contentType,
|
||||
@@ -270,10 +279,9 @@ const fetchCategoryInfoFromServer = async (
|
||||
info: Writable<CategoryInfo | null>,
|
||||
masterKey: CryptoKey,
|
||||
) => {
|
||||
const trpc = useTRPC();
|
||||
let data;
|
||||
try {
|
||||
data = await trpc.category.get.query({ id });
|
||||
data = await trpc().category.get.query({ id });
|
||||
} catch (e) {
|
||||
if (e instanceof TRPCClientError && e.data?.code === "NOT_FOUND") {
|
||||
info.set(null);
|
||||
@@ -293,7 +301,7 @@ const fetchCategoryInfoFromServer = async (
|
||||
|
||||
let files;
|
||||
try {
|
||||
files = await trpc.category.files.query({ id, recurse: true });
|
||||
files = await trpc().category.files.query({ id, recurse: true });
|
||||
} catch {
|
||||
throw new Error("Failed to fetch category files");
|
||||
}
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { error, redirect, type Handle } from "@sveltejs/kit";
|
||||
import env from "$lib/server/loadenv";
|
||||
import { authenticate, AuthenticationError } from "$lib/server/modules/auth";
|
||||
import { cookieOptions, authenticate, AuthenticationError } from "$lib/server/modules/auth";
|
||||
|
||||
export const authenticateMiddleware: Handle = async ({ event, resolve }) => {
|
||||
try {
|
||||
@@ -11,12 +10,7 @@ export const authenticateMiddleware: Handle = async ({ event, resolve }) => {
|
||||
|
||||
const { ip, userAgent } = event.locals;
|
||||
event.locals.session = await authenticate(sessionIdSigned, ip, userAgent);
|
||||
event.cookies.set("sessionId", sessionIdSigned, {
|
||||
path: "/",
|
||||
maxAge: env.session.exp / 1000,
|
||||
secure: true,
|
||||
sameSite: "strict",
|
||||
});
|
||||
event.cookies.set("sessionId", sessionIdSigned, cookieOptions);
|
||||
} catch (e) {
|
||||
if (e instanceof AuthenticationError) {
|
||||
const { pathname, search } = event.url;
|
||||
|
||||
@@ -1,11 +1,9 @@
|
||||
import { error } from "@sveltejs/kit";
|
||||
import { getUserClient } from "$lib/server/db/client";
|
||||
import { IntegrityError } from "$lib/server/db/error";
|
||||
import { createSession, refreshSession } from "$lib/server/db/session";
|
||||
import { ClientRepo, SessionRepo, IntegrityError } from "$lib/server/db";
|
||||
import env from "$lib/server/loadenv";
|
||||
import { issueSessionId, verifySessionId } from "$lib/server/modules/crypto";
|
||||
import { verifySessionId } from "$lib/server/modules/crypto";
|
||||
|
||||
interface Session {
|
||||
export interface Session {
|
||||
sessionId: string;
|
||||
userId: number;
|
||||
clientId?: number;
|
||||
@@ -42,11 +40,12 @@ export class AuthorizationError extends Error {
|
||||
}
|
||||
}
|
||||
|
||||
export const startSession = async (userId: number, ip: string, userAgent: string) => {
|
||||
const { sessionId, sessionIdSigned } = await issueSessionId(32, env.session.secret);
|
||||
await createSession(userId, sessionId, ip, userAgent);
|
||||
return sessionIdSigned;
|
||||
};
|
||||
export const cookieOptions = {
|
||||
path: "/",
|
||||
maxAge: env.session.exp / 1000,
|
||||
secure: true,
|
||||
sameSite: "strict",
|
||||
} as const;
|
||||
|
||||
export const authenticate = async (sessionIdSigned: string, ip: string, userAgent: string) => {
|
||||
const sessionId = verifySessionId(sessionIdSigned, env.session.secret);
|
||||
@@ -55,7 +54,7 @@ export const authenticate = async (sessionIdSigned: string, ip: string, userAgen
|
||||
}
|
||||
|
||||
try {
|
||||
const { userId, clientId } = await refreshSession(sessionId, ip, userAgent);
|
||||
const { userId, clientId } = await SessionRepo.refreshSession(sessionId, ip, userAgent);
|
||||
return {
|
||||
id: sessionId,
|
||||
userId,
|
||||
@@ -96,7 +95,7 @@ export const authorizeInternal = async (
|
||||
if (!clientId) {
|
||||
throw new AuthorizationError(403, "Forbidden");
|
||||
}
|
||||
const userClient = await getUserClient(userId, clientId);
|
||||
const userClient = await ClientRepo.getUserClient(userId, clientId);
|
||||
if (!userClient) {
|
||||
throw new AuthorizationError(500, "Invalid session id");
|
||||
} else if (userClient.state !== "pending") {
|
||||
@@ -108,7 +107,7 @@ export const authorizeInternal = async (
|
||||
if (!clientId) {
|
||||
throw new AuthorizationError(403, "Forbidden");
|
||||
}
|
||||
const userClient = await getUserClient(userId, clientId);
|
||||
const userClient = await ClientRepo.getUserClient(userId, clientId);
|
||||
if (!userClient) {
|
||||
throw new AuthorizationError(500, "Invalid session id");
|
||||
} else if (userClient.state !== "active") {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { TRPCClientError } from "@trpc/client";
|
||||
import { encodeToBase64, decryptChallenge, signMessageRSA } from "$lib/modules/crypto";
|
||||
import { useTRPC } from "$trpc/client";
|
||||
import { trpc } from "$trpc/client";
|
||||
|
||||
export const requestSessionUpgrade = async (
|
||||
encryptKeyBase64: string,
|
||||
@@ -9,10 +9,9 @@ export const requestSessionUpgrade = async (
|
||||
signKey: CryptoKey,
|
||||
force = false,
|
||||
) => {
|
||||
const trpc = useTRPC();
|
||||
let id, challenge;
|
||||
try {
|
||||
({ id, challenge } = await trpc.auth.upgradeSession.mutate({
|
||||
({ id, challenge } = await trpc().auth.upgrade.mutate({
|
||||
encPubKey: encryptKeyBase64,
|
||||
sigPubKey: verifyKeyBase64,
|
||||
}));
|
||||
@@ -26,7 +25,7 @@ export const requestSessionUpgrade = async (
|
||||
const answerSig = await signMessageRSA(answer, signKey);
|
||||
|
||||
try {
|
||||
await trpc.auth.verifySessionUpgrade.mutate({
|
||||
await trpc().auth.verifyUpgrade.mutate({
|
||||
id,
|
||||
answerSig: encodeToBase64(answerSig),
|
||||
force,
|
||||
@@ -42,9 +41,8 @@ export const requestSessionUpgrade = async (
|
||||
};
|
||||
|
||||
export const requestLogout = async () => {
|
||||
const trpc = useTRPC();
|
||||
try {
|
||||
await trpc.auth.logout.mutate();
|
||||
await trpc().auth.logout.mutate();
|
||||
return true;
|
||||
} catch {
|
||||
// TODO: Error Handling
|
||||
|
||||
@@ -1,18 +1,17 @@
|
||||
import { generateDataKey, wrapDataKey, encryptString } from "$lib/modules/crypto";
|
||||
import type { MasterKey } from "$lib/stores";
|
||||
import { useTRPC } from "$trpc/client";
|
||||
import { trpc } from "$trpc/client";
|
||||
|
||||
export const requestCategoryCreation = async (
|
||||
name: string,
|
||||
parentId: "root" | number,
|
||||
masterKey: MasterKey,
|
||||
) => {
|
||||
const trpc = useTRPC();
|
||||
const { dataKey, dataKeyVersion } = await generateDataKey();
|
||||
const nameEncrypted = await encryptString(name, dataKey);
|
||||
|
||||
try {
|
||||
await trpc.category.create.mutate({
|
||||
await trpc().category.create.mutate({
|
||||
parent: parentId,
|
||||
mekVersion: masterKey.version,
|
||||
dek: await wrapDataKey(dataKey, masterKey.key),
|
||||
@@ -28,10 +27,8 @@ export const requestCategoryCreation = async (
|
||||
};
|
||||
|
||||
export const requestFileRemovalFromCategory = async (fileId: number, categoryId: number) => {
|
||||
const trpc = useTRPC();
|
||||
|
||||
try {
|
||||
await trpc.category.removeFile.mutate({ id: categoryId, file: fileId });
|
||||
await trpc().category.removeFile.mutate({ id: categoryId, file: fileId });
|
||||
return true;
|
||||
} catch {
|
||||
// TODO: Error Handling
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { callGetApi } from "$lib/hooks";
|
||||
import { getAllFileInfos } from "$lib/indexedDB/filesystem";
|
||||
import { decryptData } from "$lib/modules/crypto";
|
||||
import {
|
||||
@@ -12,7 +11,7 @@ import {
|
||||
} from "$lib/modules/file";
|
||||
import { getThumbnailUrl } from "$lib/modules/thumbnail";
|
||||
import type { FileThumbnailUploadRequest } from "$lib/server/schemas";
|
||||
import { useTRPC } from "$trpc/client";
|
||||
import { trpc } from "$trpc/client";
|
||||
|
||||
export const requestFileDownload = async (
|
||||
fileId: number,
|
||||
@@ -49,17 +48,16 @@ export const requestFileThumbnailDownload = async (fileId: number, dataKey?: Cry
|
||||
const cache = await getFileThumbnailCache(fileId);
|
||||
if (cache || !dataKey) return cache;
|
||||
|
||||
const trpc = useTRPC();
|
||||
let thumbnailInfo;
|
||||
try {
|
||||
thumbnailInfo = await trpc.file.thumbnail.query({ id: fileId });
|
||||
thumbnailInfo = await trpc().file.thumbnail.query({ id: fileId });
|
||||
} catch {
|
||||
// TODO: Error Handling
|
||||
return null;
|
||||
}
|
||||
const { contentIv: thumbnailEncryptedIv } = thumbnailInfo;
|
||||
|
||||
const res = await callGetApi(`/api/file/${fileId}/thumbnail/download`);
|
||||
const res = await fetch(`/api/file/${fileId}/thumbnail/download`);
|
||||
if (!res.ok) return null;
|
||||
|
||||
const thumbnailEncrypted = await res.arrayBuffer();
|
||||
@@ -70,10 +68,9 @@ export const requestFileThumbnailDownload = async (fileId: number, dataKey?: Cry
|
||||
};
|
||||
|
||||
export const requestDeletedFilesCleanup = async () => {
|
||||
const trpc = useTRPC();
|
||||
let liveFiles;
|
||||
try {
|
||||
liveFiles = await trpc.file.list.query();
|
||||
liveFiles = await trpc().file.list.query();
|
||||
} catch {
|
||||
// TODO: Error Handling
|
||||
return;
|
||||
|
||||
@@ -11,7 +11,7 @@ import {
|
||||
} from "$lib/modules/crypto";
|
||||
import { requestSessionUpgrade } from "$lib/services/auth";
|
||||
import { masterKeyStore, type ClientKeys } from "$lib/stores";
|
||||
import { useTRPC } from "$trpc/client";
|
||||
import { trpc } from "$trpc/client";
|
||||
|
||||
export const requestClientRegistration = async (
|
||||
encryptKeyBase64: string,
|
||||
@@ -19,16 +19,14 @@ export const requestClientRegistration = async (
|
||||
verifyKeyBase64: string,
|
||||
signKey: CryptoKey,
|
||||
) => {
|
||||
const trpc = useTRPC();
|
||||
|
||||
try {
|
||||
const { id, challenge } = await trpc.client.register.mutate({
|
||||
const { id, challenge } = await trpc().client.register.mutate({
|
||||
encPubKey: encryptKeyBase64,
|
||||
sigPubKey: verifyKeyBase64,
|
||||
});
|
||||
const answer = await decryptChallenge(challenge, decryptKey);
|
||||
const answerSig = await signMessageRSA(answer, signKey);
|
||||
await trpc.client.verify.mutate({
|
||||
await trpc().client.verify.mutate({
|
||||
id,
|
||||
answerSig: encodeToBase64(answerSig),
|
||||
});
|
||||
@@ -69,11 +67,9 @@ export const requestClientRegistrationAndSessionUpgrade = async (
|
||||
};
|
||||
|
||||
export const requestMasterKeyDownload = async (decryptKey: CryptoKey, verifyKey: CryptoKey) => {
|
||||
const trpc = useTRPC();
|
||||
|
||||
let masterKeysWrapped;
|
||||
try {
|
||||
masterKeysWrapped = await trpc.mek.list.query();
|
||||
masterKeysWrapped = await trpc().mek.list.query();
|
||||
} catch {
|
||||
// TODO: Error Handling
|
||||
return false;
|
||||
@@ -110,10 +106,8 @@ export const requestInitialMasterKeyAndHmacSecretRegistration = async (
|
||||
hmacSecretWrapped: string,
|
||||
signKey: CryptoKey,
|
||||
) => {
|
||||
const trpc = useTRPC();
|
||||
|
||||
try {
|
||||
await trpc.mek.registerInitial.mutate({
|
||||
await trpc().mek.registerInitial.mutate({
|
||||
mek: masterKeyWrapped,
|
||||
mekSig: await signMasterKeyWrapped(masterKeyWrapped, 1, signKey),
|
||||
});
|
||||
@@ -129,7 +123,7 @@ export const requestInitialMasterKeyAndHmacSecretRegistration = async (
|
||||
}
|
||||
|
||||
try {
|
||||
await trpc.hsk.registerInitial.mutate({
|
||||
await trpc().hsk.registerInitial.mutate({
|
||||
mekVersion: 1,
|
||||
hsk: hmacSecretWrapped,
|
||||
});
|
||||
|
||||
@@ -7,6 +7,13 @@ export const formatDate = (date: Date) => {
|
||||
return `${year}. ${month}. ${day}.`;
|
||||
};
|
||||
|
||||
export const formatDateSortable = (date: Date) => {
|
||||
const year = date.getFullYear();
|
||||
const month = pad2(date.getMonth() + 1);
|
||||
const day = pad2(date.getDate());
|
||||
return `${year}${month}${day}`;
|
||||
};
|
||||
|
||||
export const formatDateTime = (date: Date) => {
|
||||
const dateFormatted = formatDate(date);
|
||||
const hours = date.getHours();
|
||||
@@ -32,32 +39,3 @@ export const truncateString = (str: string, maxLength = 20) => {
|
||||
if (str.length <= maxLength) return str;
|
||||
return `${str.slice(0, maxLength)}...`;
|
||||
};
|
||||
|
||||
export enum SortBy {
|
||||
NAME_ASC,
|
||||
NAME_DESC,
|
||||
}
|
||||
|
||||
type SortFunc = (a?: string, b?: string) => number;
|
||||
|
||||
const collator = new Intl.Collator(undefined, { numeric: true, sensitivity: "base" });
|
||||
|
||||
const sortByNameAsc: SortFunc = (a, b) => {
|
||||
if (a && b) return collator.compare(a, b);
|
||||
if (a) return -1;
|
||||
if (b) return 1;
|
||||
return 0;
|
||||
};
|
||||
|
||||
const sortByNameDesc: SortFunc = (a, b) => -sortByNameAsc(a, b);
|
||||
|
||||
export const sortEntries = <T extends { name?: string }>(entries: T[], sortBy: SortBy) => {
|
||||
let sortFunc: SortFunc;
|
||||
if (sortBy === SortBy.NAME_ASC) {
|
||||
sortFunc = sortByNameAsc;
|
||||
} else {
|
||||
sortFunc = sortByNameDesc;
|
||||
}
|
||||
|
||||
entries.sort((a, b) => sortFunc(a.name, b.name));
|
||||
};
|
||||
3
src/lib/utils/index.ts
Normal file
3
src/lib/utils/index.ts
Normal file
@@ -0,0 +1,3 @@
|
||||
export * from "./format";
|
||||
export * from "./gotoStateful";
|
||||
export * from "./sort";
|
||||
57
src/lib/utils/sort.ts
Normal file
57
src/lib/utils/sort.ts
Normal file
@@ -0,0 +1,57 @@
|
||||
interface SortEntry {
|
||||
name?: string;
|
||||
date?: Date;
|
||||
}
|
||||
|
||||
export enum SortBy {
|
||||
NAME_ASC,
|
||||
NAME_DESC,
|
||||
DATE_ASC,
|
||||
DATE_DESC,
|
||||
}
|
||||
|
||||
type SortFunc = (a: SortEntry, b: SortEntry) => number;
|
||||
|
||||
const collator = new Intl.Collator(undefined, { numeric: true, sensitivity: "base" });
|
||||
|
||||
const sortByNameAsc: SortFunc = ({ name: a }, { name: b }) => {
|
||||
if (a && b) return collator.compare(a, b);
|
||||
if (a) return -1;
|
||||
if (b) return 1;
|
||||
return 0;
|
||||
};
|
||||
|
||||
const sortByNameDesc: SortFunc = (a, b) => -sortByNameAsc(a, b);
|
||||
|
||||
const sortByDateAsc: SortFunc = ({ date: a }, { date: b }) => {
|
||||
if (a && b) return a.getTime() - b.getTime();
|
||||
if (a) return -1;
|
||||
if (b) return 1;
|
||||
return 0;
|
||||
};
|
||||
|
||||
const sortByDateDesc: SortFunc = (a, b) => -sortByDateAsc(a, b);
|
||||
|
||||
export const sortEntries = <T extends SortEntry>(entries: T[], sortBy: SortBy) => {
|
||||
let sortFunc: SortFunc;
|
||||
|
||||
switch (sortBy) {
|
||||
case SortBy.NAME_ASC:
|
||||
sortFunc = sortByNameAsc;
|
||||
break;
|
||||
case SortBy.NAME_DESC:
|
||||
sortFunc = sortByNameDesc;
|
||||
break;
|
||||
case SortBy.DATE_ASC:
|
||||
sortFunc = sortByDateAsc;
|
||||
break;
|
||||
case SortBy.DATE_DESC:
|
||||
sortFunc = sortByDateDesc;
|
||||
break;
|
||||
default:
|
||||
const exhaustive: never = sortBy;
|
||||
sortFunc = exhaustive;
|
||||
}
|
||||
|
||||
entries.sort(sortFunc);
|
||||
};
|
||||
@@ -1,10 +1,8 @@
|
||||
import { useTRPC } from "$trpc/client";
|
||||
import { trpc } from "$trpc/client";
|
||||
|
||||
export const requestPasswordChange = async (oldPassword: string, newPassword: string) => {
|
||||
const trpc = useTRPC();
|
||||
|
||||
try {
|
||||
await trpc.auth.changePassword.mutate({ oldPassword, newPassword });
|
||||
await trpc().auth.changePassword.mutate({ oldPassword, newPassword });
|
||||
return true;
|
||||
} catch {
|
||||
// TODO: Error Handling
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useTRPC } from "$trpc/client";
|
||||
import { trpc } from "$trpc/client";
|
||||
|
||||
export { requestLogout } from "$lib/services/auth";
|
||||
export { requestDeletedFilesCleanup } from "$lib/services/file";
|
||||
@@ -8,10 +8,8 @@ export {
|
||||
} from "$lib/services/key";
|
||||
|
||||
export const requestLogin = async (email: string, password: string) => {
|
||||
const trpc = useTRPC();
|
||||
|
||||
try {
|
||||
await trpc.auth.login.mutate({ email, password });
|
||||
await trpc().auth.login.mutate({ email, password });
|
||||
return true;
|
||||
} catch {
|
||||
// TODO: Error Handling
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
import { untrack } from "svelte";
|
||||
import { get, type Writable } from "svelte/store";
|
||||
import { goto } from "$app/navigation";
|
||||
import { page } from "$app/state";
|
||||
import { FullscreenDiv } from "$lib/components/atoms";
|
||||
import { Categories, IconEntryButton, TopBar } from "$lib/components/molecules";
|
||||
import {
|
||||
@@ -21,7 +22,9 @@
|
||||
requestThumbnailUpload,
|
||||
requestFileAdditionToCategory,
|
||||
} from "./service";
|
||||
import TopBarMenu from "./TopBarMenu.svelte";
|
||||
|
||||
import IconMoreVert from "~icons/material-symbols/more-vert";
|
||||
import IconCamera from "~icons/material-symbols/camera";
|
||||
import IconClose from "~icons/material-symbols/close";
|
||||
import IconAddCircle from "~icons/material-symbols/add-circle";
|
||||
@@ -31,6 +34,7 @@
|
||||
let info: Writable<FileInfo | null> | undefined = $state();
|
||||
let categories: Writable<CategoryInfo | null>[] = $state([]);
|
||||
|
||||
let isMenuOpen = $state(false);
|
||||
let isAddToCategoryBottomSheetOpen = $state(false);
|
||||
|
||||
let downloadStatus = $derived(
|
||||
@@ -42,30 +46,26 @@
|
||||
|
||||
let isDownloadRequested = $state(false);
|
||||
let viewerType: "image" | "video" | undefined = $state();
|
||||
let fileBlob: Blob | undefined = $state();
|
||||
let fileBlobUrl: string | undefined = $state();
|
||||
let heicBlob: Blob | undefined = $state();
|
||||
let videoElement: HTMLVideoElement | undefined = $state();
|
||||
|
||||
const updateViewer = async (buffer: ArrayBuffer, contentType: string) => {
|
||||
const fileBlob = new Blob([buffer], { type: contentType });
|
||||
if (viewerType) {
|
||||
fileBlobUrl = URL.createObjectURL(fileBlob);
|
||||
heicBlob = contentType === "image/heic" ? fileBlob : undefined;
|
||||
}
|
||||
fileBlob = new Blob([buffer], { type: contentType });
|
||||
fileBlobUrl = URL.createObjectURL(fileBlob);
|
||||
return fileBlob;
|
||||
};
|
||||
|
||||
const convertHeicToJpeg = async () => {
|
||||
if (!heicBlob) return;
|
||||
if (fileBlob?.type !== "image/heic") return;
|
||||
|
||||
URL.revokeObjectURL(fileBlobUrl!);
|
||||
fileBlobUrl = undefined;
|
||||
|
||||
const { default: heic2any } = await import("heic2any");
|
||||
fileBlobUrl = URL.createObjectURL(
|
||||
(await heic2any({ blob: heicBlob, toType: "image/jpeg" })) as Blob,
|
||||
(await heic2any({ blob: fileBlob, toType: "image/jpeg" })) as Blob,
|
||||
);
|
||||
heicBlob = undefined;
|
||||
};
|
||||
|
||||
const updateThumbnail = async (dataKey: CryptoKey, dataKeyVersion: Date) => {
|
||||
@@ -133,7 +133,24 @@
|
||||
<title>파일</title>
|
||||
</svelte:head>
|
||||
|
||||
<TopBar title={$info?.name} />
|
||||
<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={page.url.searchParams.get("from") === "category" ? $info?.parentId : undefined}
|
||||
{fileBlob}
|
||||
filename={$info?.name}
|
||||
/>
|
||||
</div>
|
||||
</TopBar>
|
||||
<FullscreenDiv>
|
||||
<div class="space-y-4 pb-4">
|
||||
<DownloadStatus status={downloadStatus} />
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<script lang="ts">
|
||||
import type { Writable } from "svelte/store";
|
||||
import { formatNetworkSpeed } from "$lib/modules/util";
|
||||
import { isFileDownloading, type FileDownloadStatus } from "$lib/stores";
|
||||
import { formatNetworkSpeed } from "$lib/utils";
|
||||
|
||||
interface Props {
|
||||
status?: Writable<FileDownloadStatus>;
|
||||
|
||||
59
src/routes/(fullscreen)/file/[id]/TopBarMenu.svelte
Normal file
59
src/routes/(fullscreen)/file/[id]/TopBarMenu.svelte
Normal file
@@ -0,0 +1,59 @@
|
||||
<script lang="ts">
|
||||
import FileSaver from "file-saver";
|
||||
import type { Component } from "svelte";
|
||||
import type { SvelteHTMLElements } from "svelte/elements";
|
||||
import { fly } from "svelte/transition";
|
||||
import { goto } from "$app/navigation";
|
||||
|
||||
import IconFolderOpen from "~icons/material-symbols/folder-open";
|
||||
import IconCloudDownload from "~icons/material-symbols/cloud-download";
|
||||
|
||||
interface Props {
|
||||
directoryId?: "root" | number;
|
||||
fileBlob?: Blob;
|
||||
filename?: string;
|
||||
isOpen: boolean;
|
||||
}
|
||||
|
||||
let { directoryId, fileBlob, filename, isOpen = $bindable() }: Props = $props();
|
||||
</script>
|
||||
|
||||
<svelte:window onclick={() => (isOpen = false)} />
|
||||
|
||||
{#if isOpen && (directoryId || fileBlob)}
|
||||
<div
|
||||
class="absolute right-2 top-full z-20 space-y-1 rounded-lg bg-white px-1 py-2 shadow-2xl"
|
||||
transition:fly={{ y: -8, duration: 200 }}
|
||||
>
|
||||
<p class="px-3 pt-2 text-sm font-semibold text-gray-600">더보기</p>
|
||||
<div class="flex flex-col">
|
||||
{#snippet menuButton(
|
||||
Icon: Component<SvelteHTMLElements["svg"]>,
|
||||
text: string,
|
||||
onclick: () => void,
|
||||
)}
|
||||
<button {onclick} class="rounded-xl active:bg-gray-100">
|
||||
<div
|
||||
class="flex items-center gap-x-3 px-3 py-2 text-lg text-gray-700 transition active:scale-95"
|
||||
>
|
||||
<Icon />
|
||||
<p class="font-medium">{text}</p>
|
||||
</div>
|
||||
</button>
|
||||
{/snippet}
|
||||
|
||||
{#if directoryId}
|
||||
{@render menuButton(IconFolderOpen, "폴더에서 보기", () =>
|
||||
goto(
|
||||
directoryId === "root" ? "/directory?from=file" : `/directory/${directoryId}?from=file`,
|
||||
),
|
||||
)}
|
||||
{/if}
|
||||
{#if fileBlob}
|
||||
{@render menuButton(IconCloudDownload, "다운로드", () => {
|
||||
FileSaver.saveAs(fileBlob, filename);
|
||||
})}
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
@@ -1,7 +1,7 @@
|
||||
import { encryptData } from "$lib/modules/crypto";
|
||||
import { storeFileThumbnailCache } from "$lib/modules/file";
|
||||
import { requestFileThumbnailUpload } from "$lib/services/file";
|
||||
import { useTRPC } from "$trpc/client";
|
||||
import { trpc } from "$trpc/client";
|
||||
|
||||
export { requestCategoryCreation, requestFileRemovalFromCategory } from "$lib/services/category";
|
||||
export { requestFileDownload } from "$lib/services/file";
|
||||
@@ -22,10 +22,8 @@ export const requestThumbnailUpload = async (
|
||||
};
|
||||
|
||||
export const requestFileAdditionToCategory = async (fileId: number, categoryId: number) => {
|
||||
const trpc = useTRPC();
|
||||
|
||||
try {
|
||||
await trpc.category.addFile.mutate({ id: categoryId, file: fileId });
|
||||
await trpc().category.addFile.mutate({ id: categoryId, file: fileId });
|
||||
return true;
|
||||
} catch {
|
||||
// TODO: Error Handling
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
<script lang="ts">
|
||||
import { get, type Writable } from "svelte/store";
|
||||
import { getFileInfo, type FileInfo } from "$lib/modules/filesystem";
|
||||
import { formatNetworkSpeed } from "$lib/modules/util";
|
||||
import { masterKeyStore, type FileDownloadStatus } from "$lib/stores";
|
||||
import { formatNetworkSpeed } from "$lib/utils";
|
||||
|
||||
import IconCloud from "~icons/material-symbols/cloud";
|
||||
import IconCloudDownload from "~icons/material-symbols/cloud-download";
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<script lang="ts">
|
||||
import type { Writable } from "svelte/store";
|
||||
import { formatNetworkSpeed } from "$lib/modules/util";
|
||||
import type { FileUploadStatus } from "$lib/stores";
|
||||
import { formatNetworkSpeed } from "$lib/utils";
|
||||
|
||||
import IconPending from "~icons/material-symbols/pending";
|
||||
import IconLockClock from "~icons/material-symbols/lock-clock";
|
||||
|
||||
26
src/routes/(fullscreen)/gallery/+page.svelte
Normal file
26
src/routes/(fullscreen)/gallery/+page.svelte
Normal file
@@ -0,0 +1,26 @@
|
||||
<script lang="ts">
|
||||
import type { Writable } from "svelte/store";
|
||||
import { goto } from "$app/navigation";
|
||||
import { FullscreenDiv } from "$lib/components/atoms";
|
||||
import { TopBar } from "$lib/components/molecules";
|
||||
import { Gallery } from "$lib/components/organisms";
|
||||
import { getFileInfo, type FileInfo } from "$lib/modules/filesystem";
|
||||
import { masterKeyStore } from "$lib/stores";
|
||||
|
||||
let { data } = $props();
|
||||
|
||||
let files: Writable<FileInfo | null>[] = $state([]);
|
||||
|
||||
$effect(() => {
|
||||
files = data.files.map((file) => getFileInfo(file, $masterKeyStore?.get(1)?.key!));
|
||||
});
|
||||
</script>
|
||||
|
||||
<svelte:head>
|
||||
<title>사진 및 동영상</title>
|
||||
</svelte:head>
|
||||
|
||||
<TopBar title="사진 및 동영상" />
|
||||
<FullscreenDiv>
|
||||
<Gallery {files} onFileClick={({ id }) => goto(`/file/${id}`)} />
|
||||
</FullscreenDiv>
|
||||
7
src/routes/(fullscreen)/gallery/+page.ts
Normal file
7
src/routes/(fullscreen)/gallery/+page.ts
Normal file
@@ -0,0 +1,7 @@
|
||||
import { trpc } from "$trpc/client";
|
||||
import type { PageLoad } from "./$types";
|
||||
|
||||
export const load: PageLoad = async ({ fetch }) => {
|
||||
const files = await trpc(fetch).file.list.query();
|
||||
return { files };
|
||||
};
|
||||
@@ -1,5 +1,5 @@
|
||||
import { error } from "@sveltejs/kit";
|
||||
import { keyExportState } from "$lib/hooks/gotoStateful";
|
||||
import { keyExportState } from "$lib/utils";
|
||||
import type { PageLoad } from "./$types";
|
||||
|
||||
export const load: PageLoad = async () => {
|
||||
|
||||
@@ -4,9 +4,9 @@
|
||||
import { BottomDiv, Button, FullscreenDiv, TextButton } from "$lib/components/atoms";
|
||||
import { TitledDiv } from "$lib/components/molecules";
|
||||
import { ForceLoginModal } from "$lib/components/organisms";
|
||||
import { gotoStateful } from "$lib/hooks";
|
||||
import { storeClientKeys } from "$lib/modules/key";
|
||||
import { clientKeyStore } from "$lib/stores";
|
||||
import { gotoStateful } from "$lib/utils";
|
||||
import Order from "./Order.svelte";
|
||||
import {
|
||||
generateClientKeys,
|
||||
|
||||
@@ -6,8 +6,8 @@
|
||||
import type { FileCacheIndex } from "$lib/indexedDB";
|
||||
import { getFileCacheIndex, deleteFileCache as doDeleteFileCache } from "$lib/modules/file";
|
||||
import { getFileInfo, type FileInfo } from "$lib/modules/filesystem";
|
||||
import { formatFileSize } from "$lib/modules/util";
|
||||
import { masterKeyStore } from "$lib/stores";
|
||||
import { formatFileSize } from "$lib/utils";
|
||||
import File from "./File.svelte";
|
||||
|
||||
interface FileCache {
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
import type { Writable } from "svelte/store";
|
||||
import type { FileCacheIndex } from "$lib/indexedDB";
|
||||
import type { FileInfo } from "$lib/modules/filesystem";
|
||||
import { formatDate, formatFileSize } from "$lib/modules/util";
|
||||
import { formatDate, formatFileSize } from "$lib/utils";
|
||||
|
||||
import IconDraft from "~icons/material-symbols/draft";
|
||||
import IconScanDelete from "~icons/material-symbols/scan-delete";
|
||||
|
||||
@@ -1,14 +1,7 @@
|
||||
import { error } from "@sveltejs/kit";
|
||||
import { useTRPC } from "$trpc/client";
|
||||
import { trpc } from "$trpc/client";
|
||||
import type { PageLoad } from "./$types";
|
||||
|
||||
export const load: PageLoad = async ({ fetch }) => {
|
||||
const trpc = useTRPC(fetch);
|
||||
|
||||
try {
|
||||
const files = await trpc.file.listWithoutThumbnail.query();
|
||||
return { files };
|
||||
} catch {
|
||||
error(500, "Internal server error");
|
||||
}
|
||||
const files = await trpc(fetch).file.listWithoutThumbnail.query();
|
||||
return { files };
|
||||
};
|
||||
|
||||
@@ -14,7 +14,7 @@
|
||||
import { ActionEntryButton } from "$lib/components/atoms";
|
||||
import { DirectoryEntryLabel } from "$lib/components/molecules";
|
||||
import type { FileInfo } from "$lib/modules/filesystem";
|
||||
import { formatDateTime } from "$lib/modules/util";
|
||||
import { formatDateTime } from "$lib/utils";
|
||||
import type { GenerationStatus } from "./service.svelte";
|
||||
|
||||
import IconCamera from "~icons/material-symbols/camera";
|
||||
|
||||
@@ -22,7 +22,7 @@
|
||||
<AdaptiveDiv class="flex justify-evenly px-4 py-2">
|
||||
{#each pages as { path, label, icon: Icon }}
|
||||
<button
|
||||
onclick={() => goto(path)}
|
||||
onclick={() => goto(path, { replaceState: true })}
|
||||
class={[
|
||||
"w-16 active:rounded-xl active:bg-gray-100",
|
||||
!page.url.pathname.startsWith(path) && "text-gray-600",
|
||||
|
||||
@@ -58,7 +58,7 @@
|
||||
<Category
|
||||
bind:isFileRecursive
|
||||
info={$info}
|
||||
onFileClick={({ id }) => goto(`/file/${id}`)}
|
||||
onFileClick={({ id }) => goto(`/file/${id}?from=category`)}
|
||||
onFileRemoveClick={async ({ id }) => {
|
||||
await requestFileRemovalFromCategory(id, data.id as number);
|
||||
info = getCategoryInfo(data.id, $masterKeyStore?.get(1)?.key!); // TODO: FIXME
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<script lang="ts">
|
||||
import { ActionModal } from "$lib/components/molecules";
|
||||
import { truncateString } from "$lib/modules/util";
|
||||
import { truncateString } from "$lib/utils";
|
||||
import { useContext } from "./service.svelte";
|
||||
|
||||
interface Props {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { getContext, setContext } from "svelte";
|
||||
import { encryptString } from "$lib/modules/crypto";
|
||||
import type { SelectedCategory } from "$lib/components/molecules";
|
||||
import { useTRPC } from "$trpc/client";
|
||||
import { trpc } from "$trpc/client";
|
||||
|
||||
export { requestCategoryCreation, requestFileRemovalFromCategory } from "$lib/services/category";
|
||||
|
||||
@@ -17,11 +17,10 @@ export const useContext = () => {
|
||||
};
|
||||
|
||||
export const requestCategoryRename = async (category: SelectedCategory, newName: string) => {
|
||||
const trpc = useTRPC();
|
||||
const newNameEncrypted = await encryptString(newName, category.dataKey);
|
||||
|
||||
try {
|
||||
await trpc.category.rename.mutate({
|
||||
await trpc().category.rename.mutate({
|
||||
id: category.id,
|
||||
dekVersion: category.dataKeyVersion,
|
||||
name: newNameEncrypted.ciphertext,
|
||||
@@ -35,10 +34,8 @@ export const requestCategoryRename = async (category: SelectedCategory, newName:
|
||||
};
|
||||
|
||||
export const requestCategoryDeletion = async (category: SelectedCategory) => {
|
||||
const trpc = useTRPC();
|
||||
|
||||
try {
|
||||
await trpc.category.delete.mutate({ id: category.id });
|
||||
await trpc().category.delete.mutate({ id: category.id });
|
||||
return true;
|
||||
} catch {
|
||||
// TODO: Error Handling
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
import { onMount } from "svelte";
|
||||
import type { Writable } from "svelte/store";
|
||||
import { goto } from "$app/navigation";
|
||||
import { page } from "$app/state";
|
||||
import { FloatingButton } from "$lib/components/atoms";
|
||||
import { TopBar } from "$lib/components/molecules";
|
||||
import { getDirectoryInfo, type DirectoryInfo } from "$lib/modules/filesystem";
|
||||
@@ -42,6 +43,9 @@
|
||||
let isEntryRenameModalOpen = $state(false);
|
||||
let isEntryDeleteModalOpen = $state(false);
|
||||
|
||||
let isFromFilePage = $derived(page.url.searchParams.get("from") === "file");
|
||||
let showTopBar = $derived(data.id !== "root" || isFromFilePage);
|
||||
|
||||
const uploadFile = () => {
|
||||
const files = fileInput?.files;
|
||||
if (!files || files.length === 0) return;
|
||||
@@ -86,11 +90,11 @@
|
||||
<input bind:this={fileInput} onchange={uploadFile} type="file" multiple class="hidden" />
|
||||
|
||||
<div class="flex h-full flex-col">
|
||||
{#if data.id !== "root"}
|
||||
{#if showTopBar}
|
||||
<TopBar title={$info?.name} class="flex-shrink-0" />
|
||||
{/if}
|
||||
{#if $info}
|
||||
<div class={["flex flex-grow flex-col px-4 pb-4", data.id === "root" && "pt-4"]}>
|
||||
<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")} />
|
||||
@@ -103,6 +107,13 @@
|
||||
context.selectedEntry = entry;
|
||||
isEntryMenuBottomSheetOpen = true;
|
||||
}}
|
||||
showParentEntry={isFromFilePage && $info.parentId !== undefined}
|
||||
onParentClick={() =>
|
||||
goto(
|
||||
$info.parentId === "root"
|
||||
? "/directory?from=file"
|
||||
: `/directory/${$info.parentId}?from=file`,
|
||||
)}
|
||||
/>
|
||||
{/key}
|
||||
</div>
|
||||
|
||||
@@ -1,19 +1,21 @@
|
||||
<script lang="ts">
|
||||
import { untrack } from "svelte";
|
||||
import { get, type Writable } from "svelte/store";
|
||||
import { ActionEntryButton } from "$lib/components/atoms";
|
||||
import { DirectoryEntryLabel } from "$lib/components/molecules";
|
||||
import {
|
||||
getDirectoryInfo,
|
||||
getFileInfo,
|
||||
type DirectoryInfo,
|
||||
type FileInfo,
|
||||
} from "$lib/modules/filesystem";
|
||||
import { SortBy, sortEntries } from "$lib/modules/util";
|
||||
import {
|
||||
fileUploadStatusStore,
|
||||
isFileUploading,
|
||||
masterKeyStore,
|
||||
type FileUploadStatus,
|
||||
} from "$lib/stores";
|
||||
import { SortBy, sortEntries } from "$lib/utils";
|
||||
import File from "./File.svelte";
|
||||
import SubDirectory from "./SubDirectory.svelte";
|
||||
import UploadingFile from "./UploadingFile.svelte";
|
||||
@@ -23,10 +25,19 @@
|
||||
info: DirectoryInfo;
|
||||
onEntryClick: (entry: SelectedEntry) => void;
|
||||
onEntryMenuClick: (entry: SelectedEntry) => void;
|
||||
onParentClick?: () => void;
|
||||
showParentEntry?: boolean;
|
||||
sortBy?: SortBy;
|
||||
}
|
||||
|
||||
let { info, onEntryClick, onEntryMenuClick, sortBy = SortBy.NAME_ASC }: Props = $props();
|
||||
let {
|
||||
info,
|
||||
onEntryClick,
|
||||
onEntryMenuClick,
|
||||
onParentClick,
|
||||
showParentEntry = false,
|
||||
sortBy = SortBy.NAME_ASC,
|
||||
}: Props = $props();
|
||||
|
||||
interface DirectoryEntry {
|
||||
name?: string;
|
||||
@@ -106,8 +117,13 @@
|
||||
});
|
||||
</script>
|
||||
|
||||
{#if subDirectories.length + files.length > 0}
|
||||
{#if subDirectories.length + files.length > 0 || showParentEntry}
|
||||
<div class="space-y-1 pb-[4.5rem]">
|
||||
{#if showParentEntry}
|
||||
<ActionEntryButton class="h-14" onclick={onParentClick}>
|
||||
<DirectoryEntryLabel type="parent-directory" name=".." />
|
||||
</ActionEntryButton>
|
||||
{/if}
|
||||
{#each subDirectories as { info }}
|
||||
<SubDirectory {info} onclick={onEntryClick} onOpenMenuClick={onEntryMenuClick} />
|
||||
{/each}
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
import { ActionEntryButton } from "$lib/components/atoms";
|
||||
import { DirectoryEntryLabel } from "$lib/components/molecules";
|
||||
import type { FileInfo } from "$lib/modules/filesystem";
|
||||
import { formatDateTime } from "$lib/modules/util";
|
||||
import { formatDateTime } from "$lib/utils";
|
||||
import { requestFileThumbnailDownload } from "./service";
|
||||
import type { SelectedEntry } from "../service.svelte";
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<script lang="ts">
|
||||
import type { Writable } from "svelte/store";
|
||||
import { formatNetworkSpeed } from "$lib/modules/util";
|
||||
import { isFileUploading, type FileUploadStatus } from "$lib/stores";
|
||||
import { formatNetworkSpeed } from "$lib/utils";
|
||||
|
||||
import IconDraft from "~icons/material-symbols/draft";
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<script lang="ts">
|
||||
import { ActionModal } from "$lib/components/molecules";
|
||||
import { truncateString } from "$lib/modules/util";
|
||||
import { truncateString } from "$lib/utils";
|
||||
|
||||
interface Props {
|
||||
file: File | undefined;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<script lang="ts">
|
||||
import { ActionModal } from "$lib/components/molecules";
|
||||
import { truncateString } from "$lib/modules/util";
|
||||
import { truncateString } from "$lib/utils";
|
||||
import { useContext } from "./service.svelte";
|
||||
|
||||
interface Props {
|
||||
|
||||
@@ -9,7 +9,7 @@ import {
|
||||
uploadFile,
|
||||
} from "$lib/modules/file";
|
||||
import { hmacSecretStore, type MasterKey, type HmacSecret } from "$lib/stores";
|
||||
import { useTRPC } from "$trpc/client";
|
||||
import { trpc } from "$trpc/client";
|
||||
|
||||
export interface SelectedEntry {
|
||||
type: "directory" | "file";
|
||||
@@ -33,11 +33,9 @@ export const useContext = () => {
|
||||
export const requestHmacSecretDownload = async (masterKey: CryptoKey) => {
|
||||
// TODO: MEK rotation
|
||||
|
||||
const trpc = useTRPC();
|
||||
|
||||
let hmacSecretsWrapped;
|
||||
try {
|
||||
hmacSecretsWrapped = await trpc.hsk.list.query();
|
||||
hmacSecretsWrapped = await trpc().hsk.list.query();
|
||||
} catch {
|
||||
// TODO: Error Handling
|
||||
return false;
|
||||
@@ -61,12 +59,11 @@ export const requestDirectoryCreation = async (
|
||||
parentId: "root" | number,
|
||||
masterKey: MasterKey,
|
||||
) => {
|
||||
const trpc = useTRPC();
|
||||
const { dataKey, dataKeyVersion } = await generateDataKey();
|
||||
const nameEncrypted = await encryptString(name, dataKey);
|
||||
|
||||
try {
|
||||
await trpc.directory.create.mutate({
|
||||
await trpc().directory.create.mutate({
|
||||
parent: parentId,
|
||||
mekVersion: masterKey.version,
|
||||
dek: await wrapDataKey(dataKey, masterKey.key),
|
||||
@@ -100,19 +97,18 @@ export const requestFileUpload = async (
|
||||
};
|
||||
|
||||
export const requestEntryRename = async (entry: SelectedEntry, newName: string) => {
|
||||
const trpc = useTRPC();
|
||||
const newNameEncrypted = await encryptString(newName, entry.dataKey);
|
||||
|
||||
try {
|
||||
if (entry.type === "directory") {
|
||||
await trpc.directory.rename.mutate({
|
||||
await trpc().directory.rename.mutate({
|
||||
id: entry.id,
|
||||
dekVersion: entry.dataKeyVersion,
|
||||
name: newNameEncrypted.ciphertext,
|
||||
nameIv: newNameEncrypted.iv,
|
||||
});
|
||||
} else {
|
||||
await trpc.file.rename.mutate({
|
||||
await trpc().file.rename.mutate({
|
||||
id: entry.id,
|
||||
dekVersion: entry.dataKeyVersion,
|
||||
name: newNameEncrypted.ciphertext,
|
||||
@@ -127,11 +123,9 @@ export const requestEntryRename = async (entry: SelectedEntry, newName: string)
|
||||
};
|
||||
|
||||
export const requestEntryDeletion = async (entry: SelectedEntry) => {
|
||||
const trpc = useTRPC();
|
||||
|
||||
try {
|
||||
if (entry.type === "directory") {
|
||||
const { deletedFiles } = await trpc.directory.delete.mutate({ id: entry.id });
|
||||
const { deletedFiles } = await trpc().directory.delete.mutate({ id: entry.id });
|
||||
await Promise.all(
|
||||
deletedFiles.flatMap((fileId) => [
|
||||
deleteFileCache(fileId),
|
||||
@@ -139,7 +133,7 @@ export const requestEntryDeletion = async (entry: SelectedEntry) => {
|
||||
]),
|
||||
);
|
||||
} else {
|
||||
await trpc.file.delete.mutate({ id: entry.id });
|
||||
await trpc().file.delete.mutate({ id: entry.id });
|
||||
await Promise.all([deleteFileCache(entry.id), deleteFileThumbnailCache(entry.id)]);
|
||||
}
|
||||
return true;
|
||||
|
||||
@@ -1,3 +1,34 @@
|
||||
<div class="flex h-full items-center justify-center p-4">
|
||||
<p class="text-gray-500">아직 개발 중이에요.</p>
|
||||
<script lang="ts">
|
||||
import type { Writable } from "svelte/store";
|
||||
import { goto } from "$app/navigation";
|
||||
import { EntryButton, FileThumbnailButton } from "$lib/components/atoms";
|
||||
import { getFileInfo, type FileInfo } from "$lib/modules/filesystem";
|
||||
import { masterKeyStore } from "$lib/stores";
|
||||
import { requestFreshMediaFilesRetrieval } from "./service";
|
||||
|
||||
let mediaFiles: Writable<FileInfo | null>[] = $state([]);
|
||||
|
||||
$effect(() => {
|
||||
requestFreshMediaFilesRetrieval().then((files) => {
|
||||
mediaFiles = files.map(({ id }) => getFileInfo(id, $masterKeyStore?.get(1)?.key!));
|
||||
});
|
||||
});
|
||||
</script>
|
||||
|
||||
<svelte:head>
|
||||
<title>홈</title>
|
||||
</svelte:head>
|
||||
|
||||
<div class="min-h-full space-y-4 bg-gray-100 px-4 pb-[5.5em] pt-4">
|
||||
<p class="px-2 text-2xl font-bold text-gray-800">ArkVault</p>
|
||||
<div class="space-y-2 rounded-xl bg-white px-2 pb-4 pt-2">
|
||||
<EntryButton onclick={() => goto("/gallery")} class="w-full">
|
||||
<p class="text-left font-semibold">사진 및 동영상</p>
|
||||
</EntryButton>
|
||||
<div class="grid grid-cols-4 gap-2 px-2">
|
||||
{#each mediaFiles as file}
|
||||
<FileThumbnailButton info={file} onclick={({ id }) => goto(`/file/${id}`)} />
|
||||
{/each}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
14
src/routes/(main)/home/service.ts
Normal file
14
src/routes/(main)/home/service.ts
Normal file
@@ -0,0 +1,14 @@
|
||||
import { getAllFileInfos } from "$lib/indexedDB";
|
||||
|
||||
export const requestFreshMediaFilesRetrieval = async (limit = 8) => {
|
||||
const files = await getAllFileInfos();
|
||||
files.sort(
|
||||
(a, b) =>
|
||||
(b.createdAt ?? b.lastModifiedAt).getTime() - (a.createdAt ?? a.lastModifiedAt).getTime(),
|
||||
);
|
||||
return files
|
||||
.filter(
|
||||
({ contentType }) => contentType.startsWith("image/") || contentType.startsWith("video/"),
|
||||
)
|
||||
.slice(0, limit);
|
||||
};
|
||||
@@ -1,14 +1,7 @@
|
||||
import { error } from "@sveltejs/kit";
|
||||
import { useTRPC } from "$trpc/client";
|
||||
import { trpc } from "$trpc/client";
|
||||
import type { PageLoad } from "./$types";
|
||||
|
||||
export const load: PageLoad = async ({ fetch }) => {
|
||||
const trpc = useTRPC(fetch);
|
||||
|
||||
try {
|
||||
const { nickname } = await trpc.user.get.query();
|
||||
return { nickname };
|
||||
} catch {
|
||||
error(500, "Internal server error");
|
||||
}
|
||||
const { nickname } = await trpc(fetch).user.get.query();
|
||||
return { nickname };
|
||||
};
|
||||
|
||||
@@ -8,6 +8,7 @@ const createClient = (fetch: typeof globalThis.fetch) =>
|
||||
links: [
|
||||
httpBatchLink({
|
||||
url: "/api/trpc",
|
||||
maxURLLength: 4096,
|
||||
transformer: superjson,
|
||||
fetch,
|
||||
}),
|
||||
@@ -16,7 +17,7 @@ const createClient = (fetch: typeof globalThis.fetch) =>
|
||||
|
||||
let browserClient: ReturnType<typeof createClient>;
|
||||
|
||||
export const useTRPC = (fetch = globalThis.fetch) => {
|
||||
export const trpc = (fetch = globalThis.fetch) => {
|
||||
const client = browserClient ?? createClient(fetch);
|
||||
if (browser) {
|
||||
browserClient ??= client;
|
||||
|
||||
@@ -3,11 +3,10 @@ import { initTRPC, TRPCError } from "@trpc/server";
|
||||
import superjson from "superjson";
|
||||
import { authorizeMiddleware, authorizeClientMiddleware } from "./middlewares/authorize";
|
||||
|
||||
export const createContext = (event: RequestEvent) => event;
|
||||
export type Context = Awaited<ReturnType<typeof createContext>>;
|
||||
|
||||
export const createContext = (event: RequestEvent) => event;
|
||||
export const t = initTRPC.context<Context>().create({ transformer: superjson });
|
||||
|
||||
export const router = t.router;
|
||||
export const publicProcedure = t.procedure;
|
||||
|
||||
|
||||
@@ -3,51 +3,39 @@ import argon2 from "argon2";
|
||||
import { z } from "zod";
|
||||
import { ClientRepo, SessionRepo, UserRepo, IntegrityError } from "$lib/server/db";
|
||||
import env from "$lib/server/loadenv";
|
||||
import { startSession } from "$lib/server/modules/auth";
|
||||
import { generateChallenge, verifySignature } from "$lib/server/modules/crypto";
|
||||
import { publicProcedure, roleProcedure, router } from "../init.server";
|
||||
|
||||
const hashPassword = async (password: string) => {
|
||||
return await argon2.hash(password);
|
||||
};
|
||||
|
||||
const verifyPassword = async (hash: string, password: string) => {
|
||||
return await argon2.verify(hash, password);
|
||||
};
|
||||
import { cookieOptions } from "$lib/server/modules/auth";
|
||||
import { generateChallenge, verifySignature, issueSessionId } from "$lib/server/modules/crypto";
|
||||
import { router, publicProcedure, roleProcedure } from "../init.server";
|
||||
|
||||
const authRouter = router({
|
||||
login: publicProcedure
|
||||
.input(
|
||||
z.object({
|
||||
email: z.email(),
|
||||
password: z.string().trim().nonempty(),
|
||||
password: z.string().nonempty(),
|
||||
}),
|
||||
)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const user = await UserRepo.getUserByEmail(input.email);
|
||||
if (!user || !(await verifyPassword(user.password, input.password))) {
|
||||
if (!user || !(await argon2.verify(user.password, input.password))) {
|
||||
throw new TRPCError({ code: "UNAUTHORIZED", message: "Invalid email or password" });
|
||||
}
|
||||
|
||||
const sessionIdSigned = await startSession(user.id, ctx.locals.ip, ctx.locals.userAgent);
|
||||
ctx.cookies.set("sessionId", sessionIdSigned, {
|
||||
path: "/",
|
||||
maxAge: env.session.exp / 1000,
|
||||
secure: true,
|
||||
sameSite: "strict",
|
||||
});
|
||||
const { sessionId, sessionIdSigned } = await issueSessionId(32, env.session.secret);
|
||||
await SessionRepo.createSession(user.id, sessionId, ctx.locals.ip, ctx.locals.userAgent);
|
||||
ctx.cookies.set("sessionId", sessionIdSigned, cookieOptions);
|
||||
}),
|
||||
|
||||
logout: roleProcedure["any"].mutation(async ({ ctx }) => {
|
||||
await SessionRepo.deleteSession(ctx.session.sessionId);
|
||||
ctx.cookies.delete("sessionId", { path: "/" });
|
||||
ctx.cookies.delete("sessionId", cookieOptions);
|
||||
}),
|
||||
|
||||
changePassword: roleProcedure["any"]
|
||||
.input(
|
||||
z.object({
|
||||
oldPassword: z.string().trim().nonempty(),
|
||||
newPassword: z.string().trim().nonempty(),
|
||||
oldPassword: z.string().nonempty(),
|
||||
newPassword: z.string().nonempty(),
|
||||
}),
|
||||
)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
@@ -60,15 +48,15 @@ const authRouter = router({
|
||||
const user = await UserRepo.getUser(ctx.session.userId);
|
||||
if (!user) {
|
||||
throw new TRPCError({ code: "INTERNAL_SERVER_ERROR", message: "Invalid session id" });
|
||||
} else if (!(await verifyPassword(user.password, input.oldPassword))) {
|
||||
} else if (!(await argon2.verify(user.password, input.oldPassword))) {
|
||||
throw new TRPCError({ code: "FORBIDDEN", message: "Invalid password" });
|
||||
}
|
||||
|
||||
await UserRepo.setUserPassword(ctx.session.userId, await hashPassword(input.newPassword));
|
||||
await UserRepo.setUserPassword(ctx.session.userId, await argon2.hash(input.newPassword));
|
||||
await SessionRepo.deleteAllOtherSessions(ctx.session.userId, ctx.session.sessionId);
|
||||
}),
|
||||
|
||||
upgradeSession: roleProcedure["notClient"]
|
||||
upgrade: roleProcedure["notClient"]
|
||||
.input(
|
||||
z.object({
|
||||
encPubKey: z.base64().nonempty(),
|
||||
@@ -94,10 +82,11 @@ const authRouter = router({
|
||||
ctx.locals.ip,
|
||||
new Date(Date.now() + env.challenge.sessionUpgradeExp),
|
||||
);
|
||||
|
||||
return { id, challenge: challenge.toString("base64") };
|
||||
}),
|
||||
|
||||
verifySessionUpgrade: roleProcedure["notClient"]
|
||||
verifyUpgrade: roleProcedure["notClient"]
|
||||
.input(
|
||||
z.object({
|
||||
id: z.int().positive(),
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { TRPCError } from "@trpc/server";
|
||||
import { z } from "zod";
|
||||
import { ClientRepo, IntegrityError } from "$lib/server/db";
|
||||
import { verifyPubKey, verifySignature, generateChallenge } from "$lib/server/modules/crypto";
|
||||
import env from "$lib/server/loadenv";
|
||||
import { verifyPubKey, verifySignature, generateChallenge } from "$lib/server/modules/crypto";
|
||||
import { router, roleProcedure } from "../init.server";
|
||||
|
||||
const createUserClientChallenge = async (
|
||||
@@ -19,6 +19,7 @@ const createUserClientChallenge = async (
|
||||
ip,
|
||||
new Date(Date.now() + env.challenge.userClientExp),
|
||||
);
|
||||
|
||||
return { id, challenge: challenge.toString("base64") };
|
||||
};
|
||||
|
||||
|
||||
@@ -108,11 +108,13 @@ const directoryRouter = router({
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
try {
|
||||
const files = await FileRepo.unregisterDirectory(ctx.session.userId, input.id);
|
||||
files.forEach(({ path, thumbnailPath }) => {
|
||||
safeUnlink(path); // Intended
|
||||
safeUnlink(thumbnailPath); // Intended
|
||||
});
|
||||
return { deletedFiles: files.map(({ id }) => id) };
|
||||
return {
|
||||
deletedFiles: files.map((file) => {
|
||||
safeUnlink(file.path); // Intended
|
||||
safeUnlink(file.thumbnailPath); // Intended
|
||||
return file.id;
|
||||
}),
|
||||
};
|
||||
} catch (e) {
|
||||
if (e instanceof IntegrityError && e.message === "Directory not found") {
|
||||
throw new TRPCError({ code: "NOT_FOUND", message: "Invalid directory id" });
|
||||
|
||||
@@ -115,6 +115,7 @@ const fileRouter = router({
|
||||
if (!thumbnail) {
|
||||
throw new TRPCError({ code: "NOT_FOUND", message: "File or its thumbnail not found" });
|
||||
}
|
||||
|
||||
return { updatedAt: thumbnail.updatedAt, contentIv: thumbnail.encContentIv };
|
||||
}),
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user