/* ============================================================================= * B03_FileInput_Fingerprint.ts * 파일 지문 — 같은 파일을 다시 올리는지 **전송 전에** 가린다. * * 라이다 원본은 1.7GB가 넘어 한 번 올리는 데 몇 분이 걸린다. 같은 파일을 다시 고른 경우 * 그 시간을 통째로 버리게 되므로, 올리기 전에 서버에 "이 파일 이미 있어?"를 물어본다. * * 전체를 읽어 지문을 만들면 가장 정확하지만 1.7GB를 다 읽어야 한다. 그래서 **크기 + 앞·중간· * 끝 8MB**만 읽어 지문을 만든다(2026-08-08 사용자 결정). 24MB만 읽으므로 1~2초면 끝나고, * 자리를 앞·중간·끝으로 흩어 놓아 "머리말만 같은 파일"도 걸러진다. * * 한계: 크기가 같고 세 구간까지 같은데 그 사이만 다른 파일은 같다고 볼 수 있다. 현실에서는 * 사실상 생기지 않지만, 완벽이 필요해지면 전체 읽기로 바꾸면 된다(파일당 10~30초). * ========================================================================== */ /** 지문에 쓰는 구간 크기(8MB). 앞·중간·끝에서 이만큼씩 읽는다. */ const SAMPLE_BYTES = 8 * 1024 * 1024; function toHex(buffer: ArrayBuffer): string { return [...new Uint8Array(buffer)].map((byte) => byte.toString(16).padStart(2, "0")).join(""); } /** * 파일 지문을 만든다. 브라우저가 지원하지 않으면(보안 컨텍스트가 아니면) `null` — * 그때는 지문 없이 그냥 올린다(애매하면 올리는 쪽이 안전하다). */ export async function fileFingerprint(file: File): Promise { if (!crypto?.subtle) return null; try { const middleStart = Math.max(0, Math.floor(file.size / 2) - Math.floor(SAMPLE_BYTES / 2)); const parts = [ file.slice(0, Math.min(SAMPLE_BYTES, file.size)), file.slice(middleStart, Math.min(middleStart + SAMPLE_BYTES, file.size)), file.slice(Math.max(0, file.size - SAMPLE_BYTES)), ]; const chunks = await Promise.all(parts.map((part) => part.arrayBuffer())); const total = chunks.reduce((sum, chunk) => sum + chunk.byteLength, 0); // 크기를 함께 섞는다 — 구간이 같아도 길이가 다르면 다른 파일이다. const header = new TextEncoder().encode(`${file.size}:`); const merged = new Uint8Array(header.byteLength + total); merged.set(header, 0); let offset = header.byteLength; for (const chunk of chunks) { merged.set(new Uint8Array(chunk), offset); offset += chunk.byteLength; } return toHex(await crypto.subtle.digest("SHA-256", merged)); } catch { return null; } }