web: handle errors during uploaded file size check

This commit is contained in:
Abdullah Atta
2024-05-04 17:02:41 +05:00
committed by Abdullah Atta
parent 8e207d787d
commit 45a552adef
3 changed files with 16 additions and 5 deletions

View File

@@ -106,9 +106,12 @@ export async function checkAttachment(hash: string) {
import("../interfaces/fs"),
({ getUploadedFileSize }) => getUploadedFileSize(hash)
);
if (size <= 0) return { failed: "File length is 0." };
if (size === 0) throw new Error("File length is 0.");
else if (size === -1) throw new Error("File verification check failed.");
} catch (e) {
return { failed: e instanceof Error ? e.message : "Unknown error." };
const reason = e instanceof Error ? e.message : "Unknown error.";
await db.attachments.markAsFailed(attachment.id, reason);
return { failed: reason };
}
return { success: true };
}

View File

@@ -189,7 +189,7 @@ async function addAttachment(
const exists = await db.attachments.attachment(hash);
if (!forceWrite && exists) {
forceWrite = (await getUploadedFileSize(hash)) <= 0;
forceWrite = (await getUploadedFileSize(hash)) === 0;
}
if (forceWrite || !exists) {

View File

@@ -49,6 +49,7 @@ import {
Output,
RequestOptions
} from "@notesnook/core/dist/interfaces";
import { logger } from "../utils/logger";
const ABYTES = 17;
const CHUNK_SIZE = 512 * 1024;
@@ -624,6 +625,13 @@ async function deleteFile(
}
}
/**
* `-1` means an error during file size
*
* `0` means file either doesn't exist or file is actually of 0 length
*
* `>0` means file is valid
*/
export async function getUploadedFileSize(filename: string) {
try {
const url = `${hosts.API_HOST}/s3?name=${filename}`;
@@ -636,8 +644,8 @@ export async function getUploadedFileSize(filename: string) {
const contentLength = parseInt(attachmentInfo.headers["content-length"]);
return isNaN(contentLength) ? 0 : contentLength;
} catch (e) {
console.error(e);
return 0;
logger.error(e, "Failed to get uploaded file size.", { filename });
return -1;
}
}