파일 다운로드 스케쥴링 및 진행률 표시 기능 구현

This commit is contained in:
static
2025-01-18 08:20:09 +09:00
parent 620d174e9b
commit bde090c464
7 changed files with 214 additions and 73 deletions

View File

@@ -0,0 +1,84 @@
import axios from "axios";
import { limitFunction } from "p-limit";
import { writable, type Writable } from "svelte/store";
import { decryptData } from "$lib/modules/crypto";
import { fileDownloadStatusStore, type FileDownloadStatus } from "$lib/stores";
const requestFileDownload = limitFunction(
async (status: Writable<FileDownloadStatus>, id: number) => {
status.update((value) => {
value.status = "downloading";
return value;
});
const res = await axios.get(`/api/file/${id}/download`, {
responseType: "arraybuffer",
onDownloadProgress: ({ progress, rate, estimated }) => {
status.update((value) => {
value.progress = progress;
value.rate = rate;
value.estimated = estimated;
return value;
});
},
});
const fileEncrypted: ArrayBuffer = res.data;
status.update((value) => {
value.status = "decryption-pending";
return value;
});
return fileEncrypted;
},
{ concurrency: 1 },
);
const decryptFile = limitFunction(
async (
status: Writable<FileDownloadStatus>,
fileEncrypted: ArrayBuffer,
fileEncryptedIv: string,
dataKey: CryptoKey,
) => {
status.update((value) => {
value.status = "decrypting";
return value;
});
const fileBuffer = await decryptData(fileEncrypted, fileEncryptedIv, dataKey);
status.update((value) => {
value.status = "decrypted";
value.result = fileBuffer;
return value;
});
return fileBuffer;
},
{ concurrency: 4 },
);
export const downloadFile = async (id: number, fileEncryptedIv: string, dataKey: CryptoKey) => {
const status = writable<FileDownloadStatus>({
id,
status: "download-pending",
});
fileDownloadStatusStore.update((value) => {
value.push(status);
return value;
});
try {
return await decryptFile(
status,
await requestFileDownload(status, id),
fileEncryptedIv,
dataKey,
);
} catch (e) {
status.update((value) => {
value.status = "error";
return value;
});
throw e;
}
};

View File

@@ -1,2 +1,3 @@
export * from "./cache";
export * from "./download";
export * from "./upload";

View File

@@ -120,7 +120,7 @@ const encryptFile = limitFunction(
{ concurrency: 4 },
);
const uploadFileInternal = limitFunction(
const requestFileUpload = limitFunction(
async (status: Writable<FileUploadStatus>, form: FormData) => {
status.update((value) => {
value.status = "uploading";
@@ -209,7 +209,7 @@ export const uploadFile = async (
);
form.set("content", new Blob([fileEncrypted.ciphertext]));
await uploadFileInternal(status, form);
await requestFileUpload(status, form);
return true;
} catch (e) {
status.update((value) => {

View File

@@ -15,4 +15,22 @@ export interface FileUploadStatus {
estimated?: number;
}
export interface FileDownloadStatus {
id: number;
status:
| "download-pending"
| "downloading"
| "decryption-pending"
| "decrypting"
| "decrypted"
| "canceled"
| "error";
progress?: number;
rate?: number;
estimated?: number;
result?: ArrayBuffer;
}
export const fileUploadStatusStore = writable<Writable<FileUploadStatus>[]>([]);
export const fileDownloadStatusStore = writable<Writable<FileDownloadStatus>[]>([]);

View File

@@ -1,66 +1,84 @@
<script lang="ts">
import FileSaver from "file-saver";
import { untrack } from "svelte";
import type { Writable } from "svelte/store";
import { get, type Writable } from "svelte/store";
import { TopBar } from "$lib/components";
import { getFileInfo, type FileInfo } from "$lib/modules/filesystem";
import { masterKeyStore } from "$lib/stores";
import { fileDownloadStatusStore, masterKeyStore } from "$lib/stores";
import DownloadStatus from "./DownloadStatus.svelte";
import { requestFileDownload } from "./service";
type ContentType = "image" | "video";
let { data } = $props();
let info: Writable<FileInfo | null> | undefined = $state();
let isDownloaded = $state(false);
let content: Blob | undefined = $state();
let contentUrl: string | undefined = $state();
let contentType: ContentType | undefined = $state();
const downloadStatus = $derived(
$fileDownloadStatusStore.find((statusStore) => {
const status = get(statusStore);
return (
status.id === data.id &&
(status.status === "download-pending" ||
status.status === "downloading" ||
status.status === "decryption-pending" ||
status.status === "decrypting")
);
}),
);
let isDownloadRequested = $state(false);
let viewerType: "image" | "video" | undefined = $state();
let fileBlobUrl: string | undefined = $state();
const updateViewer = async (info: FileInfo, buffer: ArrayBuffer) => {
const contentType = info.contentType;
if (contentType.startsWith("image")) {
viewerType = "image";
} else if (contentType.startsWith("video")) {
viewerType = "video";
}
const fileBlob = new Blob([buffer], { type: contentType });
if (contentType === "image/heic") {
const { default: heic2any } = await import("heic2any");
fileBlobUrl = URL.createObjectURL(
(await heic2any({ blob: fileBlob, toType: "image/jpeg" })) as Blob,
);
} else if (viewerType) {
fileBlobUrl = URL.createObjectURL(fileBlob);
}
return fileBlob;
};
$effect(() => {
info = getFileInfo(data.id, $masterKeyStore?.get(1)?.key!);
isDownloaded = false;
content = undefined;
contentType = undefined;
isDownloadRequested = false;
viewerType = undefined;
});
$effect(() => {
if ($info?.contentIv && $info?.dataKey && !isDownloaded) {
if ($info && $info.dataKey && $info.contentIv) {
untrack(() => {
isDownloaded = true;
if ($info.contentType.startsWith("image")) {
contentType = "image";
} else if ($info.contentType.startsWith("video")) {
contentType = "video";
}
requestFileDownload(data.id, $info.contentIv!, $info.dataKey!).then(async (res) => {
content = new Blob([res], { type: $info.contentType });
if (content.type === "image/heic" || content.type === "image/heif") {
const { default: heic2any } = await import("heic2any");
contentUrl = URL.createObjectURL(
(await heic2any({ blob: content, toType: "image/jpeg" })) as Blob,
);
} else if (contentType) {
contentUrl = URL.createObjectURL(content);
} else {
FileSaver.saveAs(content, $info.name);
if (!downloadStatus && !isDownloadRequested) {
isDownloadRequested = true;
requestFileDownload(data.id, $info.contentIv!, $info.dataKey!).then(async (buffer) => {
const blob = await updateViewer($info, buffer);
if (!viewerType) {
FileSaver.saveAs(blob, $info.name);
}
});
}
});
}
});
$effect(() => {
return () => {
if (contentUrl) {
URL.revokeObjectURL(contentUrl);
if ($info && $downloadStatus?.status === "decrypted") {
untrack(() => !isDownloadRequested && updateViewer($info, $downloadStatus.result!));
}
};
});
$effect(() => () => fileBlobUrl && URL.revokeObjectURL(fileBlobUrl));
</script>
<svelte:head>
@@ -69,23 +87,24 @@
<div class="flex h-full flex-col">
<TopBar title={$info?.name} />
<div class="mb-4 flex w-full flex-grow flex-col items-center">
<DownloadStatus info={downloadStatus} />
<div class="flex w-full flex-grow flex-col items-center pb-4">
{#snippet viewerLoading(message: string)}
<div class="flex flex-grow items-center justify-center">
<p class="text-gray-500">{message}</p>
</div>
{/snippet}
{#if $info && contentType === "image"}
{#if contentUrl}
<img src={contentUrl} alt={$info.name} />
{#if $info && viewerType === "image"}
{#if fileBlobUrl}
<img src={fileBlobUrl} alt={$info.name} />
{:else}
{@render viewerLoading("이미지를 불러오고 있어요.")}
{/if}
{:else if contentType === "video"}
{#if contentUrl}
{:else if viewerType === "video"}
{#if fileBlobUrl}
<!-- svelte-ignore a11y_media_has_caption -->
<video src={contentUrl} controls></video>
<video src={fileBlobUrl} controls></video>
{:else}
{@render viewerLoading("비디오를 불러오고 있어요.")}
{/if}

View File

@@ -0,0 +1,32 @@
<script lang="ts">
import type { Writable } from "svelte/store";
import type { FileDownloadStatus } from "$lib/stores";
import { formatDownloadProgress, formatDownloadRate } from "./service";
interface Props {
info?: Writable<FileDownloadStatus>;
}
let { info }: Props = $props();
</script>
{#if $info && $info.status !== "decrypted" && $info.status !== "canceled" && $info.status !== "error"}
<div class="flex w-full flex-col rounded-xl bg-gray-100 p-3">
<p class="font-medium">
{#if $info.status === "download-pending"}
다운로드를 기다리는 중
{:else if $info.status === "downloading"}
다운로드하는 중
{:else if $info.status === "decryption-pending"}
복호화를 기다리는 중
{:else if $info.status === "decrypting"}
복호화하는 중
{/if}
</p>
<p class="text-xs">
{#if $info.status === "downloading"}
전송됨 {formatDownloadProgress($info.progress)} · {formatDownloadRate($info.rate)}
{/if}
</p>
</div>
{/if}

View File

@@ -1,5 +1,5 @@
import { getFileCache, storeFileCache } from "$lib/modules/file";
import { decryptData } from "$lib/modules/crypto";
import { getFileCache, storeFileCache, downloadFile } from "$lib/modules/file";
import { formatFileSize } from "$lib/modules/util";
export const requestFileDownload = async (
fileId: number,
@@ -9,28 +9,15 @@ export const requestFileDownload = async (
const cache = await getFileCache(fileId);
if (cache) return cache;
return new Promise<ArrayBuffer>((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.responseType = "arraybuffer";
xhr.addEventListener("load", async () => {
if (xhr.status !== 200) {
reject(new Error("Failed to download file"));
return;
}
const fileDecrypted = await decryptData(
xhr.response as ArrayBuffer,
fileEncryptedIv,
dataKey,
);
resolve(fileDecrypted);
await storeFileCache(fileId, fileDecrypted);
});
// TODO: Progress, ...
xhr.open("GET", `/api/file/${fileId}/download`);
xhr.send();
});
const fileBuffer = await downloadFile(fileId, fileEncryptedIv, dataKey);
storeFileCache(fileId, fileBuffer); // Intended
return fileBuffer;
};
export const formatDownloadProgress = (progress?: number) => {
return `${Math.floor((progress ?? 0) * 100)}%`;
};
export const formatDownloadRate = (rate?: number) => {
return `${formatFileSize((rate ?? 0) / 8)}/s`;
};