File uploading

This commit is contained in:
2026-10-29 17:59:34 -03:00
parent ec9bdb8e8e
commit b65d8efad8
18 changed files with 686 additions and 51 deletions
+110 -19
View File
@@ -1,35 +1,113 @@
import { useSignal, useSignalEffect } from "@preact/signals";
import { Signal, useSignal, useSignalEffect } from "@preact/signals";
import HubFileList, { type HubFile } from "@/islands/HubFileList.tsx";
import HubUpload from "@/islands/HubUpload.tsx";
import HubUpload, { type UploadState } from "@/islands/HubUpload.tsx";
import { post_json } from "@/src/client.ts";
import { decrypt_metadata, encrypt_file } from "@/src/file_crypto.ts";
import type { FileEntry } from "@/src/files.ts";
import { list_files, upload_file } from "@/src/files_api.ts";
import { load_master_key } from "@/src/key_store.ts";
import { type GetKeyResponse, verify_key_check } from "@/src/keys.ts";
function has_files(event: DragEvent) {
return event.dataTransfer?.types.includes("Files") ?? false;
}
export default function Hub() {
async function to_hub_file(master_key: CryptoKey, entry: FileEntry): Promise<HubFile> {
const metadata = await decrypt_metadata(master_key, entry.metadata).catch(() => null);
return { id: entry.id, uploaded_at: entry.date_created, stored_size: entry.size, metadata };
}
interface HubProps {
page: Signal<string>;
}
export default function Hub(props: HubProps) {
const master_key = useSignal<CryptoKey | null>(null);
const load_error = useSignal("");
const pending = useSignal<File[]>([]);
const files = useSignal<HubFile[]>([]);
const upload_state = useSignal<UploadState | null>(null);
const upload_error = useSignal("");
const dragging = useSignal(false);
function add_files(new_files: File[]) {
pending.value = [...pending.value, ...new_files];
async function load() {
const code = localStorage.getItem("code");
if (!code) {
props.page.value = "askcode";
return;
}
const account = await post_json<GetKeyResponse>("/api/get_key", { code });
if (!account.ok) {
load_error.value = account.error;
return;
}
const key = await load_master_key(account.data.user_id).catch(() => undefined);
const key_check = account.data.key_check;
if (!key || !key_check || !(await verify_key_check(key, key_check))) {
props.page.value = "keysnew";
return;
}
const list = await list_files();
if (!list.ok) {
load_error.value = list.error;
return;
}
files.value = await Promise.all(list.data.map((entry) => to_hub_file(key, entry)));
master_key.value = key;
}
// TODO: encrypt with the master key and upload, the list only lives in memory until the API exists
function upload() {
const uploaded_at = Date.now();
const uploaded = pending.value.map((file): HubFile => ({
id: crypto.randomUUID(),
name: file.name,
size: file.size,
uploaded_at,
blob: file,
}));
files.value = [...uploaded.reverse(), ...files.value];
pending.value = [];
function add_files(new_files: File[]) {
if (!upload_state.value) {
upload_error.value = "";
pending.value = [...pending.value, ...new_files];
}
}
async function upload() {
const key = master_key.value;
if (!key || upload_state.value) {
return;
}
const queue = pending.value;
const controller = new AbortController();
upload_error.value = "";
for (const [index, file] of queue.entries()) {
const state = { file, index, count: queue.length, progress: null, controller };
upload_state.value = state;
try {
const encrypted = await encrypt_file(key, file);
if (controller.signal.aborted) {
break;
}
const result = await upload_file(encrypted, (ratio) => {
upload_state.value = { ...state, progress: ratio };
}, controller.signal);
if (!result.ok) {
if (!controller.signal.aborted) {
upload_error.value = `Couldn't upload ${file.name}: ${result.error}`;
}
break;
}
files.value = [await to_hub_file(key, result.data), ...files.value];
pending.value = pending.value.filter((pending_file) => pending_file !== file);
} catch (err) {
upload_error.value = `Couldn't upload ${file.name}: ${err instanceof Error ? err.message : err}`;
break;
}
}
upload_state.value = null;
}
useSignalEffect(() => {
load();
});
// Files can be dropped anywhere on the page, not only on the upload area
useSignalEffect(() => {
function drag_over(event: DragEvent) {
@@ -64,10 +142,23 @@ export default function Hub() {
};
});
if (!master_key.value) {
return load_error.value
? <p role="alert" class="text-center text-error-600 dark:text-error-400">{load_error.value}</p>
: <p class="text-center text-gray-800 dark:text-gray-400">Loading...</p>;
}
return (
<div class="flex flex-col gap-6 md:h-[38rem] md:flex-row md:gap-8">
<div class="flex flex-col gap-6 md:h-152 md:flex-row md:gap-8">
<div class="flex min-h-0 flex-col md:w-1/2">
<HubUpload pending={pending} dragging={dragging.value} on_add={add_files} on_upload={upload} />
<HubUpload
pending={pending}
upload_state={upload_state.value}
error={upload_error.value}
dragging={dragging.value}
on_add={add_files}
on_upload={upload}
/>
</div>
<div class="flex min-h-0 flex-col md:w-1/2">
<HubFileList files={files} />
+67 -20
View File
@@ -1,17 +1,19 @@
import { Signal } from "@preact/signals";
import { Signal, useSignal } from "@preact/signals";
import Button from "@/components/Button.tsx";
import FileInfo from "@/components/FileInfo.tsx";
import { CloseIcon, DownloadIcon } from "@/components/Icons.tsx";
import type { FileMetadata } from "@/src/file_crypto.ts";
import { download_blob } from "@/src/files.ts";
import { delete_file, download_file } from "@/src/files_api.ts";
export interface HubFile {
id: string;
name: string;
size: number;
uploaded_at: number;
// TODO: replace with fetching and decrypting from the server once uploads exist
blob: Blob;
uploaded_at: string;
// Size of the encrypted file, shown when the metadata can't be read
stored_size: number;
// null when it can't be decrypted with this key
metadata: FileMetadata | null;
}
const DATE_FORMAT = new Intl.DateTimeFormat(undefined, { dateStyle: "medium" });
@@ -21,8 +23,42 @@ interface HubFileListProps {
}
export default function HubFileList(props: HubFileListProps) {
const busy = useSignal<{ id: string; action: "download" | "delete" } | null>(null);
const error = useSignal("");
async function run(file: HubFile, action: "download" | "delete", fn: () => Promise<void>) {
if (busy.value) {
return;
}
busy.value = { id: file.id, action };
error.value = "";
try {
await fn();
} catch (err) {
error.value = err instanceof Error ? err.message : String(err);
} finally {
busy.value = null;
}
}
function download(file: HubFile) {
const metadata = file.metadata;
if (metadata) {
run(file, "download", async () => download_blob(await download_file(file.id, metadata), metadata.name));
}
}
function remove(file: HubFile) {
props.files.value = props.files.value.filter((other) => other.id !== file.id);
if (!confirm(`Delete "${file.metadata?.name ?? "this file"}"? This can't be undone.`)) {
return;
}
run(file, "delete", async () => {
const result = await delete_file(file.id);
if (!result.ok && result.status !== 404) {
throw new Error(result.error);
}
props.files.value = props.files.value.filter((other) => other.id !== file.id);
});
}
if (props.files.value.length === 0) {
@@ -42,6 +78,7 @@ export default function HubFileList(props: HubFileListProps) {
Your files{" "}
<span class="font-normal text-gray-500 dark:text-gray-400">({props.files.value.length})</span>
</h1>
{error.value && <p role="alert" class="pb-2 text-error-600 dark:text-error-400">{error.value}</p>}
<ul class="-mx-2 flex min-h-0 flex-col gap-4 overflow-y-auto p-2">
{props.files.value.map((file) => (
<li
@@ -49,30 +86,40 @@ export default function HubFileList(props: HubFileListProps) {
class="flex flex-col rounded bg-white p-4 shadow-light dark:border dark:border-gray-700 dark:bg-gray-900"
>
<FileInfo
name={file.name}
size={file.size}
detail={DATE_FORMAT.format(file.uploaded_at)}
name={file.metadata?.name ?? "Unreadable file"}
size={file.metadata?.size ?? file.stored_size}
detail={file.metadata
? DATE_FORMAT.format(new Date(file.uploaded_at))
: "Can't be decrypted with your key"}
action={
<Button
variant="link"
class="flex-none self-start p-1 text-gray-500 hover:text-gray-700 focus:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200 dark:focus:text-gray-200"
title="Delete"
aria-label={`Delete ${file.name}`}
aria-label={`Delete ${file.metadata?.name ?? "unreadable file"}`}
disabled={busy.value !== null}
onClick={() => remove(file)}
>
<CloseIcon class="size-3.5" />
</Button>
}
/>
<hr class="my-4 w-full border-gray-200 dark:border-gray-700" />
<Button
variant="link"
class="flex items-center gap-2 self-start"
onClick={() => download_blob(file.blob, file.name)}
>
<DownloadIcon class="h-4 w-3" />
Download
</Button>
{file.metadata && (
<>
<hr class="my-4 w-full border-gray-200 dark:border-gray-700" />
<Button
variant="link"
class="flex items-center gap-2 self-start"
disabled={busy.value !== null}
onClick={() => download(file)}
>
<DownloadIcon class="h-4 w-3" />
{busy.value?.id === file.id && busy.value.action === "download"
? "Downloading..."
: "Download"}
</Button>
</>
)}
</li>
))}
</ul>
+45
View File
@@ -24,8 +24,45 @@ function FilePicker(props: FilePickerProps) {
return <input type="file" multiple class="sr-only" onChange={change} />;
}
export interface UploadState {
file: File;
index: number;
count: number;
// null while the file is being encrypted
progress: number | null;
controller: AbortController;
}
interface UploadingProps {
state: UploadState;
}
function Uploading({ state }: UploadingProps) {
const percent = Math.round((state.progress ?? 0) * 100);
return (
<div class="flex w-full flex-col rounded bg-white p-4 shadow-light dark:border dark:border-gray-700 dark:bg-gray-900">
<FileInfo
name={state.file.name}
size={state.file.size}
detail={state.count > 1 ? `${state.index + 1} of ${state.count}` : undefined}
/>
<p class="mt-4 text-sm font-medium text-primary-600 dark:text-primary-400">
{state.progress === null ? "Encrypting..." : `Uploading ${percent}%`}
</p>
<progress
class="my-3 h-1 w-full appearance-none overflow-hidden rounded bg-gray-200 dark:bg-gray-700 [&::-moz-progress-bar]:bg-primary-500 [&::-webkit-progress-bar]:bg-gray-200 dark:[&::-webkit-progress-bar]:bg-gray-700 [&::-webkit-progress-value]:bg-primary-500"
max={100}
value={state.progress === null ? undefined : percent}
/>
<Button variant="link" class="self-end" onClick={() => state.controller.abort()}>Cancel</Button>
</div>
);
}
interface HubUploadProps {
pending: Signal<File[]>;
upload_state: UploadState | null;
error: string;
dragging: boolean;
on_add: (files: File[]) => void;
on_upload: () => void;
@@ -38,6 +75,12 @@ export default function HubUpload(props: HubUploadProps) {
props.pending.value = props.pending.value.filter((pending_file) => pending_file !== file);
}
if (props.upload_state) {
return <Uploading state={props.upload_state} />;
}
const error = props.error && <p role="alert" class="mt-4 text-error-600 dark:text-error-400">{props.error}</p>;
if (props.pending.value.length === 0) {
return (
<label
@@ -54,6 +97,7 @@ export default function HubUpload(props: HubUploadProps) {
<p class="mx-12 my-6 max-w-sm text-center text-sm leading-loose text-gray-500 dark:text-gray-400">
Files are encrypted in this browser before they're uploaded, the server never sees what's inside.
</p>
{error}
</label>
);
}
@@ -100,6 +144,7 @@ export default function HubUpload(props: HubUploadProps) {
</p>
</div>
<Button variant="primary" class="mt-4 flex-none" onClick={props.on_upload}>Upload</Button>
{error}
</div>
);
}
+1 -1
View File
@@ -12,7 +12,7 @@ export default function MainIsland() {
} else if (page.value === "keysnew") {
return <KeysNew page={page} />;
} else if (page.value === "hub") {
return <Hub />;
return <Hub page={page} />;
} else {
return "Error";
}