replace toByteArray with Response(stream).bytes()

This commit is contained in:
Siddharth Singh 2024-11-06 12:12:27 +05:30
parent 38288aadb3
commit e96a9e4f35
No known key found for this signature in database
2 changed files with 4 additions and 16 deletions

View file

@ -6,23 +6,10 @@ import { Stickynotes } from '@soapbox/stickynotes';
const console = new Stickynotes('ditto:uploaders'); const console = new Stickynotes('ditto:uploaders');
export function toByteArray(f: File): Promise<Uint8Array> {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.addEventListener('loadend', (m) => {
if (m?.target?.result instanceof ArrayBuffer) {
resolve(new Uint8Array(m.target.result));
} else reject('Error loading file: readAsArrayBufferFailed');
});
reader.addEventListener('error', (e) => reject(e));
reader.readAsArrayBuffer(f);
});
}
export async function getOptionalNip94Metadata(f: File): Promise<Nip94MetadataOptional> { export async function getOptionalNip94Metadata(f: File): Promise<Nip94MetadataOptional> {
const tags: Nip94MetadataOptional = {}; const tags: Nip94MetadataOptional = {};
try { try {
const buffer = await toByteArray(f); const buffer = await new Response(f.stream()).bytes();
const hash = await crypto.subtle.digest('SHA-256', buffer).then(encodeHex); const hash = await crypto.subtle.digest('SHA-256', buffer).then(encodeHex);
tags.x = tags.ox = hash; tags.x = tags.ox = hash;
const img = sharp(buffer); const img = sharp(buffer);

View file

@ -3,7 +3,7 @@ import { HTTPException } from '@hono/hono/http-exception';
import { AppContext } from '@/app.ts'; import { AppContext } from '@/app.ts';
import { Conf } from '@/config.ts'; import { Conf } from '@/config.ts';
import { DittoUpload, dittoUploads } from '@/DittoUploads.ts'; import { DittoUpload, dittoUploads } from '@/DittoUploads.ts';
import { getOptionalNip94Metadata, toByteArray } from '@/utils/image-metadata.ts'; import { getOptionalNip94Metadata } from '@/utils/image-metadata.ts';
import type { Nip94MetadataOptional } from '@/interfaces/Nip94Metadata.ts'; import type { Nip94MetadataOptional } from '@/interfaces/Nip94Metadata.ts';
import { encodeHex } from '@std/encoding/hex'; import { encodeHex } from '@std/encoding/hex';
@ -53,7 +53,8 @@ export async function uploadFile(
} }
} }
if (!tagMap.has('x') || !tagMap.has('ox')) { if (!tagMap.has('x') || !tagMap.has('ox')) {
const hash = metadata?.x || await crypto.subtle.digest('SHA-256', await toByteArray(file)).then(encodeHex); const hash = metadata?.x ||
await crypto.subtle.digest('SHA-256', await new Response(file.stream()).bytes()).then(encodeHex);
tags.push(['x', hash!]); tags.push(['x', hash!]);
tags.push(['ox', hash!]); tags.push(['ox', hash!]);
} }