From b0a2422437f0c7f816eb2eb0769ef3a0e2a07d61 Mon Sep 17 00:00:00 2001 From: Siddharth Singh Date: Sun, 27 Oct 2024 07:35:29 +0530 Subject: [PATCH 01/11] add more metadata to IPFSUploader --- deno.json | 2 ++ deno.lock | 28 +++++++++++++++++++++++++ src/uploaders/IPFSUploader.ts | 39 +++++++++++++++++++++++++++++++++-- 3 files changed, 67 insertions(+), 2 deletions(-) diff --git a/deno.json b/deno.json index 0de69b95..ef4ea803 100644 --- a/deno.json +++ b/deno.json @@ -41,6 +41,7 @@ "@gfx/canvas-wasm": "jsr:@gfx/canvas-wasm@^0.4.2", "@hono/hono": "jsr:@hono/hono@^4.4.6", "@isaacs/ttlcache": "npm:@isaacs/ttlcache@^1.4.1", + "@jcayzac/image-information": "npm:@jcayzac/image-information@1.1.1", "@lambdalisue/async": "jsr:@lambdalisue/async@^2.1.1", "@negrel/webpush": "jsr:@negrel/webpush@^0.3.0", "@noble/secp256k1": "npm:@noble/secp256k1@^2.0.0", @@ -59,6 +60,7 @@ "@std/json": "jsr:@std/json@^0.223.0", "@std/media-types": "jsr:@std/media-types@^0.224.1", "@std/streams": "jsr:@std/streams@^0.223.0", + "blurhash": "npm:blurhash@2.0.5", "comlink": "npm:comlink@^4.4.1", "comlink-async-generator": "npm:comlink-async-generator@^0.0.1", "commander": "npm:commander@12.1.0", diff --git a/deno.lock b/deno.lock index c0e4711c..50d01408 100644 --- a/deno.lock +++ b/deno.lock @@ -80,12 +80,14 @@ "jsr:@std/streams@0.223": "0.223.0", "npm:@electric-sql/pglite@~0.2.8": "0.2.8", "npm:@isaacs/ttlcache@^1.4.1": "1.4.1", + "npm:@jcayzac/image-information@1.1.1": "1.1.1", "npm:@noble/hashes@^1.4.0": "1.4.0", "npm:@noble/secp256k1@2": "2.1.0", "npm:@scure/base@^1.1.6": "1.1.6", "npm:@scure/bip32@^1.4.0": "1.4.0", "npm:@scure/bip39@^1.3.0": "1.3.0", "npm:@types/node@*": "18.16.19", + "npm:blurhash@2.0.5": "2.0.5", "npm:comlink-async-generator@*": "0.0.1", "npm:comlink-async-generator@^0.0.1": "0.0.1", "npm:comlink@^4.4.1": "4.4.1", @@ -658,6 +660,12 @@ "@isaacs/ttlcache@1.4.1": { "integrity": "sha512-RQgQ4uQ+pLbqXfOmieB91ejmLwvSgv9nLx6sT6sD83s7umBypgg+OIBOBbEUiJXrfpnp9j0mRhYYdzp9uqq3lA==" }, + "@jcayzac/image-information@1.1.1": { + "integrity": "sha512-WXM5RTu3tTuAPXPx4ytbywjqTxnjBUWM1sY+7A9UPqPwQbM9V3jkY/rzo1OJ6VYSpogFdK4cyc+o9FZFZLW+nw==", + "dependencies": [ + "image-size" + ] + }, "@noble/ciphers@0.5.3": { "integrity": "sha512-B0+6IIHiqEs3BPMT0hcRmHvEj2QHOLu+uwt+tqDDeVd0oyVzh7BPrDcPjRnV1PV/5LaknXJJQvOuRGR0zQJz+w==" }, @@ -769,6 +777,9 @@ "bintrees@1.0.2": { "integrity": "sha512-VOMgTMwjAaUG580SXn3LacVgjurrbMme7ZZNYGSSV7mmtY6QQRh0Eg3pwIcntQ77DErK1L0NxkbetjcoXzVwKw==" }, + "blurhash@2.0.5": { + "integrity": "sha512-cRygWd7kGBQO3VEhPiTgq4Wc43ctsM+o46urrmPOiuAe+07fzlSB9OJVdpgDL0jPqXUVQ9ht7aq7kxOeJHRK+w==" + }, "braces@3.0.2": { "integrity": "sha512-b8um+L1RzM3WDSzvhm6gIz1yfTbBt6YTlcEKAvsmqCZZFw46z626lVj9j1yEPW33H5H+lBQpZMP1k8l+78Ha0A==", "dependencies": [ @@ -987,6 +998,15 @@ "safer-buffer" ] }, + "image-size@1.1.1": { + "integrity": "sha512-541xKlUw6jr/6gGuk92F+mYM5zaFAc5ahphvkqvNe2bQ6gVBkd6bfrmVJ2t4KDAfikAYZyIqTnktX3i6/aQDrQ==", + "dependencies": [ + "queue" + ] + }, + "inherits@2.0.4": { + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==" + }, "is-fullwidth-code-point@4.0.0": { "integrity": "sha512-O4L094N2/dZ7xqVdrXhh9r1KODPJpFms8B5sGdJLPy664AgvXsreZUyCQQNItZRDlYug4xStLjNp/sz3HvBowQ==" }, @@ -1260,6 +1280,12 @@ "punycode@2.3.1": { "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==" }, + "queue@6.0.2": { + "integrity": "sha512-iHZWu+q3IdFZFX36ro/lKBkSvfkztY5Y7HMiPlOUjhupPcG2JMfst2KKEpu5XndviX/3UhFbRngUPNKtgvtZiA==", + "dependencies": [ + "inherits" + ] + }, "restore-cursor@4.0.0": { "integrity": "sha512-I9fPXU9geO9bHOt9pHHOhOkYerIMsmVaWB0rA2AI9ERh/+x/i7MV5HKBNrg+ljO5eoPVgCcnFuRjJ9uH6I/3eg==", "dependencies": [ @@ -2104,12 +2130,14 @@ "jsr:@std/streams@0.223", "npm:@electric-sql/pglite@~0.2.8", "npm:@isaacs/ttlcache@^1.4.1", + "npm:@jcayzac/image-information@1.1.1", "npm:@noble/secp256k1@2", "npm:@scure/base@^1.1.6", "npm:comlink-async-generator@^0.0.1", "npm:comlink@^4.4.1", "npm:commander@12.1.0", "npm:entities@^4.5.0", + "npm:fast-blurhash@1.1.4", "npm:fast-stable-stringify@1", "npm:formdata-helper@0.3", "npm:hono-rate-limiter@0.3", diff --git a/src/uploaders/IPFSUploader.ts b/src/uploaders/IPFSUploader.ts index 7bf5165b..75f082e3 100644 --- a/src/uploaders/IPFSUploader.ts +++ b/src/uploaders/IPFSUploader.ts @@ -1,5 +1,11 @@ import { NUploader } from '@nostrify/nostrify'; import { z } from 'zod'; +import { probe } from '@jcayzac/image-information'; +import { Stickynotes } from '@soapbox/stickynotes'; +import { encode } from 'blurhash'; +import { encodeHex } from '@std/encoding/hex'; + +const console = new Stickynotes('ditto:ipfs:uploader'); export interface IPFSUploaderOpts { baseUrl: string; @@ -7,6 +13,19 @@ export interface IPFSUploaderOpts { fetch?: typeof fetch; } +function toByteArray(f: File): Promise { + 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); + }); +} + /** * IPFS uploader. It expects an IPFS node up and running. * It will try to connect to `http://localhost:5001` by default, @@ -36,13 +55,29 @@ export class IPFSUploader implements NUploader { }); const { Hash: cid } = IPFSUploader.schema().parse(await response.json()); - - return [ + const tags: [['url', string], ...string[][]] = [ ['url', new URL(`/ipfs/${cid}`, this.baseUrl).toString()], ['m', file.type], ['cid', cid], ['size', file.size.toString()], ]; + + try { + const buffer = await toByteArray(file); + const hash = await crypto.subtle.digest('SHA-256', buffer).then(encodeHex); + tags.push(['x', hash], ['ox', hash]); + const metadata = probe(buffer); + if (metadata) { + // sane default from https://github.com/woltapp/blurhash readme + const blurhash = encode(new Uint8ClampedArray(buffer), metadata.width, metadata.height, 4, 4); + tags.push(['blurhash', blurhash]); + tags.push(['dim', `${metadata.width}x${metadata.height}`]); + } + } catch (e) { + console.error(`Error parsing ipfs metadata: ${e}`); + } + + return tags; } async delete(cid: string, opts?: { signal?: AbortSignal }): Promise { From de4b5f55d39f0ee322ad99ea252d6233c5e469d4 Mon Sep 17 00:00:00 2001 From: Siddharth Singh Date: Sun, 27 Oct 2024 07:41:26 +0530 Subject: [PATCH 02/11] update lockfile --- deno.lock | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/deno.lock b/deno.lock index 50d01408..ccb3974a 100644 --- a/deno.lock +++ b/deno.lock @@ -2133,11 +2133,11 @@ "npm:@jcayzac/image-information@1.1.1", "npm:@noble/secp256k1@2", "npm:@scure/base@^1.1.6", + "npm:blurhash@2.0.5", "npm:comlink-async-generator@^0.0.1", "npm:comlink@^4.4.1", "npm:commander@12.1.0", "npm:entities@^4.5.0", - "npm:fast-blurhash@1.1.4", "npm:fast-stable-stringify@1", "npm:formdata-helper@0.3", "npm:hono-rate-limiter@0.3", From f5f31ce98f86c9477f086853dcee29f59ddbf534 Mon Sep 17 00:00:00 2001 From: Siddharth Singh Date: Sun, 27 Oct 2024 09:11:29 +0530 Subject: [PATCH 03/11] fix image uploads, use sharp to get image metadata instead of image-information --- deno.json | 3 +- deno.lock | 170 ++++++++++++++++++++++++++++++++-- src/uploaders/IPFSUploader.ts | 50 ++++++---- 3 files changed, 198 insertions(+), 25 deletions(-) diff --git a/deno.json b/deno.json index ef4ea803..43a33de8 100644 --- a/deno.json +++ b/deno.json @@ -41,7 +41,6 @@ "@gfx/canvas-wasm": "jsr:@gfx/canvas-wasm@^0.4.2", "@hono/hono": "jsr:@hono/hono@^4.4.6", "@isaacs/ttlcache": "npm:@isaacs/ttlcache@^1.4.1", - "@jcayzac/image-information": "npm:@jcayzac/image-information@1.1.1", "@lambdalisue/async": "jsr:@lambdalisue/async@^2.1.1", "@negrel/webpush": "jsr:@negrel/webpush@^0.3.0", "@noble/secp256k1": "npm:@noble/secp256k1@^2.0.0", @@ -69,6 +68,7 @@ "entities": "npm:entities@^4.5.0", "fast-stable-stringify": "npm:fast-stable-stringify@^1.0.0", "formdata-helper": "npm:formdata-helper@^0.3.0", + "get-pixels": "npm:get-pixels@3.3.3", "hono-rate-limiter": "npm:hono-rate-limiter@^0.3.0", "iso-639-1": "npm:iso-639-1@2.1.15", "isomorphic-dompurify": "npm:isomorphic-dompurify@^2.16.0", @@ -87,6 +87,7 @@ "postgres": "https://gitlab.com/soapbox-pub/postgres.js/-/raw/e79d7d2039446fbf7a37d4eca0d17e94a94b8b53/deno/mod.js", "prom-client": "npm:prom-client@^15.1.2", "question-deno": "https://raw.githubusercontent.com/ocpu/question-deno/10022b8e52555335aa510adb08b0a300df3cf904/mod.ts", + "sharp": "npm:sharp@^0.33.5", "tldts": "npm:tldts@^6.0.14", "tseep": "npm:tseep@^1.2.1", "type-fest": "npm:type-fest@^4.3.0", diff --git a/deno.lock b/deno.lock index ccb3974a..f7fef00f 100644 --- a/deno.lock +++ b/deno.lock @@ -36,6 +36,7 @@ "jsr:@nostrify/nostrify@~0.22.4": "0.22.4", "jsr:@nostrify/nostrify@~0.22.5": "0.22.5", "jsr:@nostrify/policies@0.33": "0.33.0", + "jsr:@nostrify/policies@0.33.1": "0.33.1", "jsr:@nostrify/policies@0.34": "0.34.0", "jsr:@nostrify/policies@0.35": "0.35.0", "jsr:@nostrify/policies@0.36": "0.36.0", @@ -80,7 +81,6 @@ "jsr:@std/streams@0.223": "0.223.0", "npm:@electric-sql/pglite@~0.2.8": "0.2.8", "npm:@isaacs/ttlcache@^1.4.1": "1.4.1", - "npm:@jcayzac/image-information@1.1.1": "1.1.1", "npm:@noble/hashes@^1.4.0": "1.4.0", "npm:@noble/secp256k1@2": "2.1.0", "npm:@scure/base@^1.1.6": "1.1.6", @@ -118,6 +118,7 @@ "npm:png-to-ico@^2.1.8": "2.1.8", "npm:postgres@3.4.4": "3.4.4", "npm:prom-client@^15.1.2": "15.1.2", + "npm:sharp@~0.33.5": "0.33.5", "npm:tldts@^6.0.14": "6.1.18", "npm:tseep@^1.2.1": "1.2.1", "npm:type-fest@^4.3.0": "4.18.2", @@ -657,15 +658,99 @@ "@electric-sql/pglite@0.2.8": { "integrity": "sha512-0wSmQu22euBRzR5ghqyIHnBH4MfwlkL5WstOrrA3KOsjEWEglvoL/gH92JajEUA6Ufei/+qbkB2hVloC/K/RxQ==" }, + "@emnapi/runtime@1.3.1": { + "integrity": "sha512-kEBmG8KyqtxJZv+ygbEim+KCGtIq1fC22Ms3S4ziXmYKm8uyoLX0MHONVKwp+9opg390VaKRNt4a7A9NwmpNhw==", + "dependencies": [ + "tslib" + ] + }, + "@img/sharp-darwin-arm64@0.33.5": { + "integrity": "sha512-UT4p+iz/2H4twwAoLCqfA9UH5pI6DggwKEGuaPy7nCVQ8ZsiY5PIcrRvD1DzuY3qYL07NtIQcWnBSY/heikIFQ==", + "dependencies": [ + "@img/sharp-libvips-darwin-arm64" + ] + }, + "@img/sharp-darwin-x64@0.33.5": { + "integrity": "sha512-fyHac4jIc1ANYGRDxtiqelIbdWkIuQaI84Mv45KvGRRxSAa7o7d1ZKAOBaYbnepLC1WqxfpimdeWfvqqSGwR2Q==", + "dependencies": [ + "@img/sharp-libvips-darwin-x64" + ] + }, + "@img/sharp-libvips-darwin-arm64@1.0.4": { + "integrity": "sha512-XblONe153h0O2zuFfTAbQYAX2JhYmDHeWikp1LM9Hul9gVPjFY427k6dFEcOL72O01QxQsWi761svJ/ev9xEDg==" + }, + "@img/sharp-libvips-darwin-x64@1.0.4": { + "integrity": "sha512-xnGR8YuZYfJGmWPvmlunFaWJsb9T/AO2ykoP3Fz/0X5XV2aoYBPkX6xqCQvUTKKiLddarLaxpzNe+b1hjeWHAQ==" + }, + "@img/sharp-libvips-linux-arm64@1.0.4": { + "integrity": "sha512-9B+taZ8DlyyqzZQnoeIvDVR/2F4EbMepXMc/NdVbkzsJbzkUjhXv/70GQJ7tdLA4YJgNP25zukcxpX2/SueNrA==" + }, + "@img/sharp-libvips-linux-arm@1.0.5": { + "integrity": "sha512-gvcC4ACAOPRNATg/ov8/MnbxFDJqf/pDePbBnuBDcjsI8PssmjoKMAz4LtLaVi+OnSb5FK/yIOamqDwGmXW32g==" + }, + "@img/sharp-libvips-linux-s390x@1.0.4": { + "integrity": "sha512-u7Wz6ntiSSgGSGcjZ55im6uvTrOxSIS8/dgoVMoiGE9I6JAfU50yH5BoDlYA1tcuGS7g/QNtetJnxA6QEsCVTA==" + }, + "@img/sharp-libvips-linux-x64@1.0.4": { + "integrity": "sha512-MmWmQ3iPFZr0Iev+BAgVMb3ZyC4KeFc3jFxnNbEPas60e1cIfevbtuyf9nDGIzOaW9PdnDciJm+wFFaTlj5xYw==" + }, + "@img/sharp-libvips-linuxmusl-arm64@1.0.4": { + "integrity": "sha512-9Ti+BbTYDcsbp4wfYib8Ctm1ilkugkA/uscUn6UXK1ldpC1JjiXbLfFZtRlBhjPZ5o1NCLiDbg8fhUPKStHoTA==" + }, + "@img/sharp-libvips-linuxmusl-x64@1.0.4": { + "integrity": "sha512-viYN1KX9m+/hGkJtvYYp+CCLgnJXwiQB39damAO7WMdKWlIhmYTfHjwSbQeUK/20vY154mwezd9HflVFM1wVSw==" + }, + "@img/sharp-linux-arm64@0.33.5": { + "integrity": "sha512-JMVv+AMRyGOHtO1RFBiJy/MBsgz0x4AWrT6QoEVVTyh1E39TrCUpTRI7mx9VksGX4awWASxqCYLCV4wBZHAYxA==", + "dependencies": [ + "@img/sharp-libvips-linux-arm64" + ] + }, + "@img/sharp-linux-arm@0.33.5": { + "integrity": "sha512-JTS1eldqZbJxjvKaAkxhZmBqPRGmxgu+qFKSInv8moZ2AmT5Yib3EQ1c6gp493HvrvV8QgdOXdyaIBrhvFhBMQ==", + "dependencies": [ + "@img/sharp-libvips-linux-arm" + ] + }, + "@img/sharp-linux-s390x@0.33.5": { + "integrity": "sha512-y/5PCd+mP4CA/sPDKl2961b+C9d+vPAveS33s6Z3zfASk2j5upL6fXVPZi7ztePZ5CuH+1kW8JtvxgbuXHRa4Q==", + "dependencies": [ + "@img/sharp-libvips-linux-s390x" + ] + }, + "@img/sharp-linux-x64@0.33.5": { + "integrity": "sha512-opC+Ok5pRNAzuvq1AG0ar+1owsu842/Ab+4qvU879ippJBHvyY5n2mxF1izXqkPYlGuP/M556uh53jRLJmzTWA==", + "dependencies": [ + "@img/sharp-libvips-linux-x64" + ] + }, + "@img/sharp-linuxmusl-arm64@0.33.5": { + "integrity": "sha512-XrHMZwGQGvJg2V/oRSUfSAfjfPxO+4DkiRh6p2AFjLQztWUuY/o8Mq0eMQVIY7HJ1CDQUJlxGGZRw1a5bqmd1g==", + "dependencies": [ + "@img/sharp-libvips-linuxmusl-arm64" + ] + }, + "@img/sharp-linuxmusl-x64@0.33.5": { + "integrity": "sha512-WT+d/cgqKkkKySYmqoZ8y3pxx7lx9vVejxW/W4DOFMYVSkErR+w7mf2u8m/y4+xHe7yY9DAXQMWQhpnMuFfScw==", + "dependencies": [ + "@img/sharp-libvips-linuxmusl-x64" + ] + }, + "@img/sharp-wasm32@0.33.5": { + "integrity": "sha512-ykUW4LVGaMcU9lu9thv85CbRMAwfeadCJHRsg2GmeRa/cJxsVY9Rbd57JcMxBkKHag5U/x7TSBpScF4U8ElVzg==", + "dependencies": [ + "@emnapi/runtime" + ] + }, + "@img/sharp-win32-ia32@0.33.5": { + "integrity": "sha512-T36PblLaTwuVJ/zw/LaH0PdZkRz5rd3SmMHX8GSmR7vtNSP5Z6bQkExdSK7xGWyxLw4sUknBuugTelgw2faBbQ==" + }, + "@img/sharp-win32-x64@0.33.5": { + "integrity": "sha512-MpY/o8/8kj+EcnxwvrP4aTJSWw/aZ7JIGR4aBeZkZw5B7/Jn+tY9/VNwtcoGmdT7GfggGIU4kygOMSbYnOrAbg==" + }, "@isaacs/ttlcache@1.4.1": { "integrity": "sha512-RQgQ4uQ+pLbqXfOmieB91ejmLwvSgv9nLx6sT6sD83s7umBypgg+OIBOBbEUiJXrfpnp9j0mRhYYdzp9uqq3lA==" }, - "@jcayzac/image-information@1.1.1": { - "integrity": "sha512-WXM5RTu3tTuAPXPx4ytbywjqTxnjBUWM1sY+7A9UPqPwQbM9V3jkY/rzo1OJ6VYSpogFdK4cyc+o9FZFZLW+nw==", - "dependencies": [ - "image-size" - ] - }, "@noble/ciphers@0.5.3": { "integrity": "sha512-B0+6IIHiqEs3BPMT0hcRmHvEj2QHOLu+uwt+tqDDeVd0oyVzh7BPrDcPjRnV1PV/5LaknXJJQvOuRGR0zQJz+w==" }, @@ -802,6 +887,29 @@ "string-width" ] }, + "color-convert@2.0.1": { + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dependencies": [ + "color-name" + ] + }, + "color-name@1.1.4": { + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==" + }, + "color-string@1.9.1": { + "integrity": "sha512-shrVawQFojnZv6xM40anx4CkoDP+fZsw/ZerEMsW/pyzsRbElpsL/DBVW7q3ExxwusdNXI3lXpuhEZkzs8p5Eg==", + "dependencies": [ + "color-name", + "simple-swizzle" + ] + }, + "color@4.2.3": { + "integrity": "sha512-1rXeuUUiGGrykh+CeBdu5Ie7OJwinCgQY0bc7GCRxy5xVHy+moaqkpL/jqQq0MtQOeYcrqEz4abc5f0KtU7W4A==", + "dependencies": [ + "color-convert", + "color-string" + ] + }, "colorette@2.0.20": { "integrity": "sha512-IfEDxwoWIjkeXL1eXcDiow4UbKjhLdq6/EuSVR9GMN7KVH3r9gQ83e73hsz1Nd1T3ijd5xv1wcWRYO+D6kCI2w==" }, @@ -865,6 +973,9 @@ "delayed-stream@1.0.0": { "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==" }, + "detect-libc@2.0.3": { + "integrity": "sha512-bwy0MGW55bG41VqxxypOsdSdGqLwXPI/focwgTYCFMbdUiBAxLg9CFzG08sz2aqzknwiX7Hkl0bQENjg8iLByw==" + }, "dom-serializer@2.0.0": { "integrity": "sha512-wIkAryiqt/nV5EQKqQpo3SToSOV9J0DnbJqwK7Wv/Trc92zIAYZ4FlMu+JPFW1DfGFt81ZTCGgDEabffXeLyJg==", "dependencies": [ @@ -1007,6 +1118,9 @@ "inherits@2.0.4": { "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==" }, + "is-arrayish@0.3.2": { + "integrity": "sha512-eVRqCvVlZbuw3GrM63ovNSNAeA1K16kaR/LRY/92w0zxQ5/1YzwblUX652i4Xs9RwAGjW9d9y6X88t8OaAJfWQ==" + }, "is-fullwidth-code-point@4.0.0": { "integrity": "sha512-O4L094N2/dZ7xqVdrXhh9r1KODPJpFms8B5sGdJLPy664AgvXsreZUyCQQNItZRDlYug4xStLjNp/sz3HvBowQ==" }, @@ -1308,6 +1422,36 @@ "xmlchars" ] }, + "semver@7.6.3": { + "integrity": "sha512-oVekP1cKtI+CTDvHWYFUcMtsK/00wmAEfyqKfNdARm8u1wNVhSgaX7A8d4UuIlUI5e84iEwOhs7ZPYRmzU9U6A==" + }, + "sharp@0.33.5": { + "integrity": "sha512-haPVm1EkS9pgvHrQ/F3Xy+hgcuMV0Wm9vfIBSiwZ05k+xgb0PkBQpGsAA/oWdDobNaZTH5ppvHtzCFbnSEwHVw==", + "dependencies": [ + "@img/sharp-darwin-arm64", + "@img/sharp-darwin-x64", + "@img/sharp-libvips-darwin-arm64", + "@img/sharp-libvips-darwin-x64", + "@img/sharp-libvips-linux-arm", + "@img/sharp-libvips-linux-arm64", + "@img/sharp-libvips-linux-s390x", + "@img/sharp-libvips-linux-x64", + "@img/sharp-libvips-linuxmusl-arm64", + "@img/sharp-libvips-linuxmusl-x64", + "@img/sharp-linux-arm", + "@img/sharp-linux-arm64", + "@img/sharp-linux-s390x", + "@img/sharp-linux-x64", + "@img/sharp-linuxmusl-arm64", + "@img/sharp-linuxmusl-x64", + "@img/sharp-wasm32", + "@img/sharp-win32-ia32", + "@img/sharp-win32-x64", + "color", + "detect-libc", + "semver" + ] + }, "shebang-command@2.0.0": { "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", "dependencies": [ @@ -1323,6 +1467,12 @@ "signal-exit@4.1.0": { "integrity": "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==" }, + "simple-swizzle@0.2.2": { + "integrity": "sha512-JA//kQgZtbuY83m+xT+tXJkmJncGMTFT+C+g2h2R9uxkYIrE2yy9sgmcLhCnw57/WSD+Eh3J97FPEDFnbXnDUg==", + "dependencies": [ + "is-arrayish" + ] + }, "slice-ansi@5.0.0": { "integrity": "sha512-FC+lgizVPfie0kkhqUScwRu1O/lF6NOgJmlCgK+/LYxDCTk8sGelYaHDhFcDN+Sn3Cv+3VSa4Byeo+IMCzpMgQ==", "dependencies": [ @@ -1411,6 +1561,9 @@ "tseep@1.2.1": { "integrity": "sha512-VFnsNcPGC4qFJ1nxbIPSjTmtRZOhlqLmtwRqtLVos8mbRHki8HO9cy9Z1e89EiWyxFmq6LBviI9TQjijxw/mEw==" }, + "tslib@2.6.2": { + "integrity": "sha512-AEYxH93jGFPn/a2iVAwW87VuUIkR1FVUKB77NwMF7nBTDkDrrT/Hpt/IrCJ0QXhW27jTBDcf5ZY7w6RiqTMw2Q==" + }, "type-fest@3.13.1": { "integrity": "sha512-tLq3bSNx+xSpwvAJnzrK0Ep5CLNWjvFTOp71URMaAEWBfRb9nnJiBoUe0tF8bI4ZFO3omgBR6NvnbzVUT3Ly4g==" }, @@ -2130,7 +2283,6 @@ "jsr:@std/streams@0.223", "npm:@electric-sql/pglite@~0.2.8", "npm:@isaacs/ttlcache@^1.4.1", - "npm:@jcayzac/image-information@1.1.1", "npm:@noble/secp256k1@2", "npm:@scure/base@^1.1.6", "npm:blurhash@2.0.5", @@ -2140,6 +2292,7 @@ "npm:entities@^4.5.0", "npm:fast-stable-stringify@1", "npm:formdata-helper@0.3", + "npm:get-pixels@3.3.3", "npm:hono-rate-limiter@0.3", "npm:iso-639-1@2.1.15", "npm:isomorphic-dompurify@^2.16.0", @@ -2156,6 +2309,7 @@ "npm:path-to-regexp@^7.1.0", "npm:png-to-ico@^2.1.8", "npm:prom-client@^15.1.2", + "npm:sharp@~0.33.5", "npm:tldts@^6.0.14", "npm:tseep@^1.2.1", "npm:type-fest@^4.3.0", diff --git a/src/uploaders/IPFSUploader.ts b/src/uploaders/IPFSUploader.ts index 75f082e3..1065ea0c 100644 --- a/src/uploaders/IPFSUploader.ts +++ b/src/uploaders/IPFSUploader.ts @@ -1,11 +1,11 @@ import { NUploader } from '@nostrify/nostrify'; import { z } from 'zod'; -import { probe } from '@jcayzac/image-information'; +import sharp from 'sharp'; import { Stickynotes } from '@soapbox/stickynotes'; import { encode } from 'blurhash'; import { encodeHex } from '@std/encoding/hex'; -const console = new Stickynotes('ditto:ipfs:uploader'); +const console = new Stickynotes('ditto:uploader:ipfs'); export interface IPFSUploaderOpts { baseUrl: string; @@ -25,6 +25,9 @@ function toByteArray(f: File): Promise { reader.readAsArrayBuffer(f); }); } +type Nip94Metadata = + & Record<'url' | 'm', string> + & Partial>; /** * IPFS uploader. It expects an IPFS node up and running. @@ -55,29 +58,44 @@ export class IPFSUploader implements NUploader { }); const { Hash: cid } = IPFSUploader.schema().parse(await response.json()); - const tags: [['url', string], ...string[][]] = [ - ['url', new URL(`/ipfs/${cid}`, this.baseUrl).toString()], - ['m', file.type], - ['cid', cid], - ['size', file.size.toString()], - ]; + const tags: Nip94Metadata = { + url: new URL(`/ipfs/${cid}`, this.baseUrl).toString(), + m: file.type, + cid, + size: file.size.toString(), + }; try { const buffer = await toByteArray(file); const hash = await crypto.subtle.digest('SHA-256', buffer).then(encodeHex); - tags.push(['x', hash], ['ox', hash]); - const metadata = probe(buffer); - if (metadata) { - // sane default from https://github.com/woltapp/blurhash readme - const blurhash = encode(new Uint8ClampedArray(buffer), metadata.width, metadata.height, 4, 4); - tags.push(['blurhash', blurhash]); - tags.push(['dim', `${metadata.width}x${metadata.height}`]); + tags.x = tags.ox = hash; + const img = sharp(buffer); + const metadata = await img.metadata(); + + if (metadata.width && metadata.height) { + tags.dim = `${metadata.width}x${metadata.height}`; + const pixels = await img + .raw() + .ensureAlpha() + .toBuffer({ resolveWithObject: true }) + .then((buf) => { + return new Uint8ClampedArray(buf.data); + }); + tags.blurhash = encode( + pixels, + metadata.width, + metadata.height, + // sane default from https://github.com/woltapp/blurhash readme + 4, + 4, + ); } } catch (e) { console.error(`Error parsing ipfs metadata: ${e}`); } - return tags; + console.debug(tags); + return Object.entries(tags) as [['url', string], ...string[][]]; } async delete(cid: string, opts?: { signal?: AbortSignal }): Promise { From ff8374103e8ec7adfa8bcc788eaeba49f41151b4 Mon Sep 17 00:00:00 2001 From: Siddharth Singh Date: Sun, 27 Oct 2024 10:00:47 +0530 Subject: [PATCH 04/11] remove unused dep --- deno.json | 1 - deno.lock | 1 - 2 files changed, 2 deletions(-) diff --git a/deno.json b/deno.json index 43a33de8..6db0fceb 100644 --- a/deno.json +++ b/deno.json @@ -68,7 +68,6 @@ "entities": "npm:entities@^4.5.0", "fast-stable-stringify": "npm:fast-stable-stringify@^1.0.0", "formdata-helper": "npm:formdata-helper@^0.3.0", - "get-pixels": "npm:get-pixels@3.3.3", "hono-rate-limiter": "npm:hono-rate-limiter@^0.3.0", "iso-639-1": "npm:iso-639-1@2.1.15", "isomorphic-dompurify": "npm:isomorphic-dompurify@^2.16.0", diff --git a/deno.lock b/deno.lock index f7fef00f..14cc1086 100644 --- a/deno.lock +++ b/deno.lock @@ -2292,7 +2292,6 @@ "npm:entities@^4.5.0", "npm:fast-stable-stringify@1", "npm:formdata-helper@0.3", - "npm:get-pixels@3.3.3", "npm:hono-rate-limiter@0.3", "npm:iso-639-1@2.1.15", "npm:isomorphic-dompurify@^2.16.0", From 713260e110c472c0cafc0a69a4f8eca7c708e9a6 Mon Sep 17 00:00:00 2001 From: Siddharth Singh Date: Sun, 27 Oct 2024 10:16:00 +0530 Subject: [PATCH 05/11] split off nip94 metadata stuff into its own file, port changes to s3uploader --- src/interfaces/Nip94Metadata.ts | 31 +++++++++++++++++ src/uploaders/IPFSUploader.ts | 61 +++------------------------------ src/uploaders/S3Uploader.ts | 13 +++---- src/utils/image-metadata.ts | 54 +++++++++++++++++++++++++++++ 4 files changed, 97 insertions(+), 62 deletions(-) create mode 100644 src/interfaces/Nip94Metadata.ts create mode 100644 src/utils/image-metadata.ts diff --git a/src/interfaces/Nip94Metadata.ts b/src/interfaces/Nip94Metadata.ts new file mode 100644 index 00000000..6069ac31 --- /dev/null +++ b/src/interfaces/Nip94Metadata.ts @@ -0,0 +1,31 @@ +/** + * Required fields of NIP-94 metadata for images. + * Contains the following fields: + * * `url` - required, the URL to of the file + * * `m` - required, the file mimetype. + */ +export type Nip94MetadataRequired = Record<'url' | 'm', string>; + +/** + * Optional fields of NIP-94 metadata for images. + * Contains the following fields: + * * `x` - sha-256 hash + * * `ox` - sha-256 hash + * * `dim` - image dimensions in ${w}x${h} format + * * `blurhash` - the blurhash for the image. useful for image previews etc + * * `cid` - the ipfs cid of the image. + */ +export type Nip94MetadataOptional = Partial>; + +/** + * NIP-94 metadata for images. + * Contains the following fields: + * * `url` - required, the URL to of the file + * * `m` - required, the file mimetype. + * * `x` - sha-256 hash + * * `ox` - sha-256 hash + * * `dim` - image dimensions in ${w}x${h} format + * * `blurhash` - the blurhash for the image. useful for image previews etc + * * `cid` - the ipfs cid of the image. + */ +export type Nip94Metadata = Nip94MetadataOptional & Nip94MetadataRequired; diff --git a/src/uploaders/IPFSUploader.ts b/src/uploaders/IPFSUploader.ts index 1065ea0c..07184016 100644 --- a/src/uploaders/IPFSUploader.ts +++ b/src/uploaders/IPFSUploader.ts @@ -1,11 +1,6 @@ import { NUploader } from '@nostrify/nostrify'; import { z } from 'zod'; -import sharp from 'sharp'; -import { Stickynotes } from '@soapbox/stickynotes'; -import { encode } from 'blurhash'; -import { encodeHex } from '@std/encoding/hex'; - -const console = new Stickynotes('ditto:uploader:ipfs'); +import { getOptionalNip94Metadata } from '@/utils/image-metadata.ts'; export interface IPFSUploaderOpts { baseUrl: string; @@ -13,22 +8,6 @@ export interface IPFSUploaderOpts { fetch?: typeof fetch; } -function toByteArray(f: File): Promise { - 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); - }); -} -type Nip94Metadata = - & Record<'url' | 'm', string> - & Partial>; - /** * IPFS uploader. It expects an IPFS node up and running. * It will try to connect to `http://localhost:5001` by default, @@ -58,44 +37,14 @@ export class IPFSUploader implements NUploader { }); const { Hash: cid } = IPFSUploader.schema().parse(await response.json()); - const tags: Nip94Metadata = { + + return Object.entries({ url: new URL(`/ipfs/${cid}`, this.baseUrl).toString(), m: file.type, cid, size: file.size.toString(), - }; - - try { - const buffer = await toByteArray(file); - const hash = await crypto.subtle.digest('SHA-256', buffer).then(encodeHex); - tags.x = tags.ox = hash; - const img = sharp(buffer); - const metadata = await img.metadata(); - - if (metadata.width && metadata.height) { - tags.dim = `${metadata.width}x${metadata.height}`; - const pixels = await img - .raw() - .ensureAlpha() - .toBuffer({ resolveWithObject: true }) - .then((buf) => { - return new Uint8ClampedArray(buf.data); - }); - tags.blurhash = encode( - pixels, - metadata.width, - metadata.height, - // sane default from https://github.com/woltapp/blurhash readme - 4, - 4, - ); - } - } catch (e) { - console.error(`Error parsing ipfs metadata: ${e}`); - } - - console.debug(tags); - return Object.entries(tags) as [['url', string], ...string[][]]; + ...await getOptionalNip94Metadata(file), + }) as [['url', string], ...string[][]]; } async delete(cid: string, opts?: { signal?: AbortSignal }): Promise { diff --git a/src/uploaders/S3Uploader.ts b/src/uploaders/S3Uploader.ts index b74796ab..2059077d 100644 --- a/src/uploaders/S3Uploader.ts +++ b/src/uploaders/S3Uploader.ts @@ -7,6 +7,7 @@ import { encodeHex } from '@std/encoding/hex'; import { extensionsByType } from '@std/media-types'; import { Conf } from '@/config.ts'; +import { getOptionalNip94Metadata } from '@/utils/image-metadata.ts'; export interface S3UploaderOpts { endPoint: string; @@ -45,12 +46,12 @@ export class S3Uploader implements NUploader { const path = (pathStyle && bucket) ? join(bucket, filename) : filename; const url = new URL(path, Conf.mediaDomain).toString(); - return [ - ['url', url], - ['m', file.type], - ['x', sha256], - ['size', file.size.toString()], - ]; + return Object.entries({ + url: url, + m: file.type, + size: file.size.toString(), + ...await getOptionalNip94Metadata(file), + }) as [['url', string], ...string[][]]; } async delete(objectName: string) { diff --git a/src/utils/image-metadata.ts b/src/utils/image-metadata.ts new file mode 100644 index 00000000..2d5e861f --- /dev/null +++ b/src/utils/image-metadata.ts @@ -0,0 +1,54 @@ +import sharp from 'sharp'; +import { encode } from 'blurhash'; +import { encodeHex } from '@std/encoding/hex'; +import type { Nip94MetadataOptional } from '@/interfaces/Nip94Metadata.ts'; +import { Stickynotes } from '@soapbox/stickynotes'; + +const console = new Stickynotes('ditto:uploaders'); + +function toByteArray(f: File): Promise { + 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 { + const tags: Nip94MetadataOptional = {}; + try { + const buffer = await toByteArray(f); + const hash = await crypto.subtle.digest('SHA-256', buffer).then(encodeHex); + tags.x = tags.ox = hash; + const img = sharp(buffer); + const metadata = await img.metadata(); + + if (metadata.width && metadata.height) { + tags.dim = `${metadata.width}x${metadata.height}`; + const pixels = await img + .raw() + .ensureAlpha() + .toBuffer({ resolveWithObject: true }) + .then((buf) => { + return new Uint8ClampedArray(buf.data); + }); + tags.blurhash = encode( + pixels, + metadata.width, + metadata.height, + // sane default from https://github.com/woltapp/blurhash readme + 4, + 4, + ); + } + } catch (e) { + console.error(`Error parsing ipfs metadata: ${e}`); + } + + return tags; +} From 57725fa9ac540bedb6fd0d333966b879da11b9d4 Mon Sep 17 00:00:00 2001 From: Siddharth Singh Date: Sun, 27 Oct 2024 10:21:53 +0530 Subject: [PATCH 06/11] neatness --- src/uploaders/S3Uploader.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/uploaders/S3Uploader.ts b/src/uploaders/S3Uploader.ts index 2059077d..771db03f 100644 --- a/src/uploaders/S3Uploader.ts +++ b/src/uploaders/S3Uploader.ts @@ -44,10 +44,9 @@ export class S3Uploader implements NUploader { const { pathStyle, bucket } = Conf.s3; const path = (pathStyle && bucket) ? join(bucket, filename) : filename; - const url = new URL(path, Conf.mediaDomain).toString(); return Object.entries({ - url: url, + url: new URL(path, Conf.mediaDomain).toString(), m: file.type, size: file.size.toString(), ...await getOptionalNip94Metadata(file), From e95441f5b94988a32292645171e9b41cfb5a3823 Mon Sep 17 00:00:00 2001 From: Siddharth Singh Date: Wed, 30 Oct 2024 11:04:19 +0530 Subject: [PATCH 07/11] revert changes to IPFSUploader and S3Uploader --- src/uploaders/IPFSUploader.ts | 14 ++++++-------- src/uploaders/S3Uploader.ts | 15 ++++++++------- 2 files changed, 14 insertions(+), 15 deletions(-) diff --git a/src/uploaders/IPFSUploader.ts b/src/uploaders/IPFSUploader.ts index 07184016..7bf5165b 100644 --- a/src/uploaders/IPFSUploader.ts +++ b/src/uploaders/IPFSUploader.ts @@ -1,6 +1,5 @@ import { NUploader } from '@nostrify/nostrify'; import { z } from 'zod'; -import { getOptionalNip94Metadata } from '@/utils/image-metadata.ts'; export interface IPFSUploaderOpts { baseUrl: string; @@ -38,13 +37,12 @@ export class IPFSUploader implements NUploader { const { Hash: cid } = IPFSUploader.schema().parse(await response.json()); - return Object.entries({ - url: new URL(`/ipfs/${cid}`, this.baseUrl).toString(), - m: file.type, - cid, - size: file.size.toString(), - ...await getOptionalNip94Metadata(file), - }) as [['url', string], ...string[][]]; + return [ + ['url', new URL(`/ipfs/${cid}`, this.baseUrl).toString()], + ['m', file.type], + ['cid', cid], + ['size', file.size.toString()], + ]; } async delete(cid: string, opts?: { signal?: AbortSignal }): Promise { diff --git a/src/uploaders/S3Uploader.ts b/src/uploaders/S3Uploader.ts index 771db03f..c784cdab 100644 --- a/src/uploaders/S3Uploader.ts +++ b/src/uploaders/S3Uploader.ts @@ -7,7 +7,6 @@ import { encodeHex } from '@std/encoding/hex'; import { extensionsByType } from '@std/media-types'; import { Conf } from '@/config.ts'; -import { getOptionalNip94Metadata } from '@/utils/image-metadata.ts'; export interface S3UploaderOpts { endPoint: string; @@ -45,12 +44,14 @@ export class S3Uploader implements NUploader { const path = (pathStyle && bucket) ? join(bucket, filename) : filename; - return Object.entries({ - url: new URL(path, Conf.mediaDomain).toString(), - m: file.type, - size: file.size.toString(), - ...await getOptionalNip94Metadata(file), - }) as [['url', string], ...string[][]]; + const url = new URL(path, Conf.mediaDomain).toString(); + + return [ + ['url', url], + ['m', file.type], + ['x', sha256], + ['size', file.size.toString()], + ]; } async delete(objectName: string) { From 38288aadb3a7bb1d6cb39f6757fd929cc82beac7 Mon Sep 17 00:00:00 2001 From: Siddharth Singh Date: Wed, 30 Oct 2024 11:06:48 +0530 Subject: [PATCH 08/11] move tag logic to upload.ts --- src/utils/image-metadata.ts | 2 +- src/utils/upload.ts | 22 ++++++++++++++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/src/utils/image-metadata.ts b/src/utils/image-metadata.ts index 2d5e861f..75b2f6ba 100644 --- a/src/utils/image-metadata.ts +++ b/src/utils/image-metadata.ts @@ -6,7 +6,7 @@ import { Stickynotes } from '@soapbox/stickynotes'; const console = new Stickynotes('ditto:uploaders'); -function toByteArray(f: File): Promise { +export function toByteArray(f: File): Promise { return new Promise((resolve, reject) => { const reader = new FileReader(); reader.addEventListener('loadend', (m) => { diff --git a/src/utils/upload.ts b/src/utils/upload.ts index 81c88c86..cadac9bc 100644 --- a/src/utils/upload.ts +++ b/src/utils/upload.ts @@ -3,6 +3,9 @@ import { HTTPException } from '@hono/hono/http-exception'; import { AppContext } from '@/app.ts'; import { Conf } from '@/config.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 { pubkey: string; @@ -30,12 +33,31 @@ export async function uploadFile( } const tags = await uploader.upload(file, { signal }); + const tagMap = tags.reduce((map, value) => map.set(value[0], value.slice(1)), new Map()); + const url = tags[0][1]; if (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 = { id: crypto.randomUUID(), url, From e96a9e4f3559d26fabe8e02009cfc114aff5a875 Mon Sep 17 00:00:00 2001 From: Siddharth Singh Date: Wed, 6 Nov 2024 12:12:27 +0530 Subject: [PATCH 09/11] replace toByteArray with Response(stream).bytes() --- src/utils/image-metadata.ts | 15 +-------------- src/utils/upload.ts | 5 +++-- 2 files changed, 4 insertions(+), 16 deletions(-) diff --git a/src/utils/image-metadata.ts b/src/utils/image-metadata.ts index 75b2f6ba..4429cc7a 100644 --- a/src/utils/image-metadata.ts +++ b/src/utils/image-metadata.ts @@ -6,23 +6,10 @@ import { Stickynotes } from '@soapbox/stickynotes'; const console = new Stickynotes('ditto:uploaders'); -export function toByteArray(f: File): Promise { - 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 { const tags: Nip94MetadataOptional = {}; 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); tags.x = tags.ox = hash; const img = sharp(buffer); diff --git a/src/utils/upload.ts b/src/utils/upload.ts index cadac9bc..9f4c90a4 100644 --- a/src/utils/upload.ts +++ b/src/utils/upload.ts @@ -3,7 +3,7 @@ import { HTTPException } from '@hono/hono/http-exception'; import { AppContext } from '@/app.ts'; import { Conf } from '@/config.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 { encodeHex } from '@std/encoding/hex'; @@ -53,7 +53,8 @@ export async function uploadFile( } } 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(['ox', hash!]); } From 721fe521426d4f58d55105bda93b0bed4d4d4c50 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Thu, 7 Nov 2024 11:09:20 -0600 Subject: [PATCH 10/11] Reorganize sharp/blurhash into upload.ts --- src/interfaces/Nip94Metadata.ts | 31 ---------------- src/uploaders/S3Uploader.ts | 1 - src/utils/image-metadata.ts | 41 --------------------- src/utils/upload.ts | 64 ++++++++++++++++++++++----------- 4 files changed, 44 insertions(+), 93 deletions(-) delete mode 100644 src/interfaces/Nip94Metadata.ts delete mode 100644 src/utils/image-metadata.ts diff --git a/src/interfaces/Nip94Metadata.ts b/src/interfaces/Nip94Metadata.ts deleted file mode 100644 index 6069ac31..00000000 --- a/src/interfaces/Nip94Metadata.ts +++ /dev/null @@ -1,31 +0,0 @@ -/** - * Required fields of NIP-94 metadata for images. - * Contains the following fields: - * * `url` - required, the URL to of the file - * * `m` - required, the file mimetype. - */ -export type Nip94MetadataRequired = Record<'url' | 'm', string>; - -/** - * Optional fields of NIP-94 metadata for images. - * Contains the following fields: - * * `x` - sha-256 hash - * * `ox` - sha-256 hash - * * `dim` - image dimensions in ${w}x${h} format - * * `blurhash` - the blurhash for the image. useful for image previews etc - * * `cid` - the ipfs cid of the image. - */ -export type Nip94MetadataOptional = Partial>; - -/** - * NIP-94 metadata for images. - * Contains the following fields: - * * `url` - required, the URL to of the file - * * `m` - required, the file mimetype. - * * `x` - sha-256 hash - * * `ox` - sha-256 hash - * * `dim` - image dimensions in ${w}x${h} format - * * `blurhash` - the blurhash for the image. useful for image previews etc - * * `cid` - the ipfs cid of the image. - */ -export type Nip94Metadata = Nip94MetadataOptional & Nip94MetadataRequired; diff --git a/src/uploaders/S3Uploader.ts b/src/uploaders/S3Uploader.ts index c784cdab..b74796ab 100644 --- a/src/uploaders/S3Uploader.ts +++ b/src/uploaders/S3Uploader.ts @@ -43,7 +43,6 @@ export class S3Uploader implements NUploader { const { pathStyle, bucket } = Conf.s3; const path = (pathStyle && bucket) ? join(bucket, filename) : filename; - const url = new URL(path, Conf.mediaDomain).toString(); return [ diff --git a/src/utils/image-metadata.ts b/src/utils/image-metadata.ts deleted file mode 100644 index 4429cc7a..00000000 --- a/src/utils/image-metadata.ts +++ /dev/null @@ -1,41 +0,0 @@ -import sharp from 'sharp'; -import { encode } from 'blurhash'; -import { encodeHex } from '@std/encoding/hex'; -import type { Nip94MetadataOptional } from '@/interfaces/Nip94Metadata.ts'; -import { Stickynotes } from '@soapbox/stickynotes'; - -const console = new Stickynotes('ditto:uploaders'); - -export async function getOptionalNip94Metadata(f: File): Promise { - const tags: Nip94MetadataOptional = {}; - try { - const buffer = await new Response(f.stream()).bytes(); - const hash = await crypto.subtle.digest('SHA-256', buffer).then(encodeHex); - tags.x = tags.ox = hash; - const img = sharp(buffer); - const metadata = await img.metadata(); - - if (metadata.width && metadata.height) { - tags.dim = `${metadata.width}x${metadata.height}`; - const pixels = await img - .raw() - .ensureAlpha() - .toBuffer({ resolveWithObject: true }) - .then((buf) => { - return new Uint8ClampedArray(buf.data); - }); - tags.blurhash = encode( - pixels, - metadata.width, - metadata.height, - // sane default from https://github.com/woltapp/blurhash readme - 4, - 4, - ); - } - } catch (e) { - console.error(`Error parsing ipfs metadata: ${e}`); - } - - return tags; -} diff --git a/src/utils/upload.ts b/src/utils/upload.ts index 9f4c90a4..df0be70b 100644 --- a/src/utils/upload.ts +++ b/src/utils/upload.ts @@ -1,11 +1,15 @@ import { HTTPException } from '@hono/hono/http-exception'; +import { Stickynotes } from '@soapbox/stickynotes'; +import { crypto } from '@std/crypto'; +import { encodeHex } from '@std/encoding/hex'; +import { encode } from 'blurhash'; +import sharp from 'sharp'; import { AppContext } from '@/app.ts'; import { Conf } from '@/config.ts'; import { DittoUpload, dittoUploads } from '@/DittoUploads.ts'; -import { getOptionalNip94Metadata } from '@/utils/image-metadata.ts'; -import type { Nip94MetadataOptional } from '@/interfaces/Nip94Metadata.ts'; -import { encodeHex } from '@std/encoding/hex'; + +const console = new Stickynotes('ditto:uploader'); interface FileMeta { pubkey: string; @@ -33,30 +37,50 @@ export async function uploadFile( } const tags = await uploader.upload(file, { signal }); - const tagMap = tags.reduce((map, value) => map.set(value[0], value.slice(1)), new Map()); - const url = tags[0][1]; if (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!]); - } + const x = tags.find(([key]) => key === 'x')?.[1]; + const m = tags.find(([key]) => key === 'm')?.[1]; + const dim = tags.find(([key]) => key === 'dim')?.[1]; + const blurhash = tags.find(([key]) => key === 'blurhash')?.[1]; + + if (!x) { + const sha256 = encodeHex(await crypto.subtle.digest('SHA-256', file.stream())); + tags.push(['x', sha256]); } - if (!tagMap.has('x') || !tagMap.has('ox')) { - const hash = metadata?.x || - await crypto.subtle.digest('SHA-256', await new Response(file.stream()).bytes()).then(encodeHex); - tags.push(['x', hash!]); - tags.push(['ox', hash!]); + + if (!m) { + tags.push(['m', file.type]); + } + + if (!blurhash || !dim) { + try { + const bytes = await new Response(file.stream()).bytes(); + const img = sharp(bytes); + + const { width, height } = await img.metadata(); + + if (!dim && (width && height)) { + tags.push(['dim', `${width}x${height}`]); + } + + if (!blurhash && (width && height)) { + const pixels = await img + .raw() + .ensureAlpha() + .toBuffer({ resolveWithObject: false }) + .then((buffer) => new Uint8ClampedArray(buffer)); + + const blurhash = encode(pixels, width, height, 4, 4); + tags.push(['blurhash', blurhash]); + } + } catch (e) { + console.error(`Error parsing image metadata: ${e}`); + } } const upload = { From f987effc15f5874461011b7547c3f2d10b12becb Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Thu, 7 Nov 2024 11:18:39 -0600 Subject: [PATCH 11/11] Make media analyze optional (disabled by default) --- src/config.ts | 7 +++++++ src/utils/upload.ts | 4 +++- 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/src/config.ts b/src/config.ts index fba65159..68175a46 100644 --- a/src/config.ts +++ b/src/config.ts @@ -201,6 +201,13 @@ class Conf { return value; } + /** + * Whether to analyze media metadata with [blurhash](https://www.npmjs.com/package/blurhash) and [sharp](https://www.npmjs.com/package/sharp). + * This is prone to security vulnerabilities, which is why it's not enabled by default. + */ + static get mediaAnalyze(): boolean { + return optionalBooleanSchema.parse(Deno.env.get('MEDIA_ANALYZE')) ?? false; + } /** Max upload size for files in number of bytes. Default 100MiB. */ static get maxUploadSize(): number { return Number(Deno.env.get('MAX_UPLOAD_SIZE') || 100 * 1024 * 1024); diff --git a/src/utils/upload.ts b/src/utils/upload.ts index df0be70b..fc5d7086 100644 --- a/src/utils/upload.ts +++ b/src/utils/upload.ts @@ -57,7 +57,9 @@ export async function uploadFile( tags.push(['m', file.type]); } - if (!blurhash || !dim) { + // If the uploader didn't already, try to get a blurhash and media dimensions. + // This requires `MEDIA_ANALYZE=true` to be configured because it comes with security tradeoffs. + if (Conf.mediaAnalyze && (!blurhash || !dim)) { try { const bytes = await new Response(file.stream()).bytes(); const img = sharp(bytes);