move tag logic to upload.ts

This commit is contained in:
Siddharth Singh 2024-10-30 11:06:48 +05:30
parent e95441f5b9
commit 38288aadb3
No known key found for this signature in database
2 changed files with 23 additions and 1 deletions

View file

@ -6,7 +6,7 @@ import { Stickynotes } from '@soapbox/stickynotes';
const console = new Stickynotes('ditto:uploaders'); const console = new Stickynotes('ditto:uploaders');
function toByteArray(f: File): Promise<Uint8Array> { export function toByteArray(f: File): Promise<Uint8Array> {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const reader = new FileReader(); const reader = new FileReader();
reader.addEventListener('loadend', (m) => { reader.addEventListener('loadend', (m) => {

View file

@ -3,6 +3,9 @@ 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 type { Nip94MetadataOptional } from '@/interfaces/Nip94Metadata.ts';
import { encodeHex } from '@std/encoding/hex';
interface FileMeta { interface FileMeta {
pubkey: string; pubkey: string;
@ -30,12 +33,31 @@ export async function uploadFile(
} }
const tags = await uploader.upload(file, { signal }); const tags = await uploader.upload(file, { signal });
const tagMap = tags.reduce((map, value) => map.set(value[0], value.slice(1)), new Map<string, string[]>());
const url = tags[0][1]; const url = tags[0][1];
if (description) { if (description) {
tags.push(['alt', description]); tags.push(['alt', description]);
} }
let metadata: Nip94MetadataOptional | undefined;
if (!tagMap.has('dim')) {
// blurhash needs us to call sharp() anyway to decode the image data.
// all getOptionalNip94Metadata does is call these in sequence, plus
// one extra sha256 which is whatever (and actually does come in handy later.)
metadata ??= await getOptionalNip94Metadata(file);
tags.push(['dim', metadata.dim!]);
if (!tagMap.has('blurhash')) {
tags.push(['blurhash', metadata.blurhash!]);
}
}
if (!tagMap.has('x') || !tagMap.has('ox')) {
const hash = metadata?.x || await crypto.subtle.digest('SHA-256', await toByteArray(file)).then(encodeHex);
tags.push(['x', hash!]);
tags.push(['ox', hash!]);
}
const upload = { const upload = {
id: crypto.randomUUID(), id: crypto.randomUUID(),
url, url,