@xyo-network/image-thumbnail-plugin 2.75.14 → 2.75.16
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/docs.json +4026 -3124
- package/dist/node/Plugin.d.cts +4 -4
- package/dist/node/Plugin.d.mts +4 -4
- package/dist/node/Plugin.d.ts +4 -4
- package/dist/node/Witness/Config.d.cts +1 -1
- package/dist/node/Witness/Config.d.cts.map +1 -1
- package/dist/node/Witness/Config.d.mts +1 -1
- package/dist/node/Witness/Config.d.mts.map +1 -1
- package/dist/node/Witness/Config.d.ts +1 -1
- package/dist/node/Witness/Config.d.ts.map +1 -1
- package/dist/node/Witness/Params.d.cts +2 -2
- package/dist/node/Witness/Params.d.cts.map +1 -1
- package/dist/node/Witness/Params.d.mts +2 -2
- package/dist/node/Witness/Params.d.mts.map +1 -1
- package/dist/node/Witness/Params.d.ts +2 -2
- package/dist/node/Witness/Params.d.ts.map +1 -1
- package/dist/node/Witness/Witness.d.cts +1 -1
- package/dist/node/Witness/Witness.d.cts.map +1 -1
- package/dist/node/Witness/Witness.d.mts +1 -1
- package/dist/node/Witness/Witness.d.mts.map +1 -1
- package/dist/node/Witness/Witness.d.ts +1 -1
- package/dist/node/Witness/Witness.d.ts.map +1 -1
- package/dist/node/index.js +2 -2
- package/dist/node/index.js.map +1 -1
- package/dist/node/index.mjs +1 -1
- package/dist/node/index.mjs.map +1 -1
- package/package.json +21 -20
- package/src/Witness/Config.ts +1 -1
- package/src/Witness/Params.ts +2 -2
- package/src/Witness/Witness.ts +1 -1
- package/dist/node/Plugin.js +0 -357
- package/dist/node/Plugin.js.map +0 -1
- package/dist/node/Plugin.mjs +0 -322
- package/dist/node/Plugin.mjs.map +0 -1
- package/dist/node/Witness/Config.js +0 -32
- package/dist/node/Witness/Config.js.map +0 -1
- package/dist/node/Witness/Config.mjs +0 -7
- package/dist/node/Witness/Config.mjs.map +0 -1
- package/dist/node/Witness/Params.js +0 -19
- package/dist/node/Witness/Params.js.map +0 -1
- package/dist/node/Witness/Params.mjs +0 -1
- package/dist/node/Witness/Params.mjs.map +0 -1
- package/dist/node/Witness/Witness.js +0 -336
- package/dist/node/Witness/Witness.js.map +0 -1
- package/dist/node/Witness/Witness.mjs +0 -301
- package/dist/node/Witness/Witness.mjs.map +0 -1
- package/dist/node/Witness/ffmpeg/fluent/getVideoFrameAsImageFluent.js +0 -77
- package/dist/node/Witness/ffmpeg/fluent/getVideoFrameAsImageFluent.js.map +0 -1
- package/dist/node/Witness/ffmpeg/fluent/getVideoFrameAsImageFluent.mjs +0 -42
- package/dist/node/Witness/ffmpeg/fluent/getVideoFrameAsImageFluent.mjs.map +0 -1
- package/dist/node/Witness/ffmpeg/fluent/index.js +0 -79
- package/dist/node/Witness/ffmpeg/fluent/index.js.map +0 -1
- package/dist/node/Witness/ffmpeg/fluent/index.mjs +0 -42
- package/dist/node/Witness/ffmpeg/fluent/index.mjs.map +0 -1
- package/dist/node/Witness/ffmpeg/index.js +0 -109
- package/dist/node/Witness/ffmpeg/index.js.map +0 -1
- package/dist/node/Witness/ffmpeg/index.mjs +0 -70
- package/dist/node/Witness/ffmpeg/index.mjs.map +0 -1
- package/dist/node/Witness/ffmpeg/spawn/executeFfmpeg.js +0 -48
- package/dist/node/Witness/ffmpeg/spawn/executeFfmpeg.js.map +0 -1
- package/dist/node/Witness/ffmpeg/spawn/executeFfmpeg.mjs +0 -23
- package/dist/node/Witness/ffmpeg/spawn/executeFfmpeg.mjs.map +0 -1
- package/dist/node/Witness/ffmpeg/spawn/getVideoFrameAsImage.js +0 -56
- package/dist/node/Witness/ffmpeg/spawn/getVideoFrameAsImage.js.map +0 -1
- package/dist/node/Witness/ffmpeg/spawn/getVideoFrameAsImage.mjs +0 -29
- package/dist/node/Witness/ffmpeg/spawn/getVideoFrameAsImage.mjs.map +0 -1
- package/dist/node/Witness/ffmpeg/spawn/index.js +0 -58
- package/dist/node/Witness/ffmpeg/spawn/index.js.map +0 -1
- package/dist/node/Witness/ffmpeg/spawn/index.mjs +0 -30
- package/dist/node/Witness/ffmpeg/spawn/index.mjs.map +0 -1
- package/dist/node/Witness/index.js +0 -340
- package/dist/node/Witness/index.js.map +0 -1
- package/dist/node/Witness/index.mjs +0 -302
- package/dist/node/Witness/index.mjs.map +0 -1
|
@@ -1,336 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
var __create = Object.create;
|
|
3
|
-
var __defProp = Object.defineProperty;
|
|
4
|
-
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
-
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
-
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
-
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
-
var __export = (target, all) => {
|
|
9
|
-
for (var name in all)
|
|
10
|
-
__defProp(target, name, { get: all[name], enumerable: true });
|
|
11
|
-
};
|
|
12
|
-
var __copyProps = (to, from, except, desc) => {
|
|
13
|
-
if (from && typeof from === "object" || typeof from === "function") {
|
|
14
|
-
for (let key of __getOwnPropNames(from))
|
|
15
|
-
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
16
|
-
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
17
|
-
}
|
|
18
|
-
return to;
|
|
19
|
-
};
|
|
20
|
-
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
21
|
-
// If the importer is in node compatibility mode or this is not an ESM
|
|
22
|
-
// file that has been converted to a CommonJS file using a Babel-
|
|
23
|
-
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
24
|
-
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
25
|
-
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
26
|
-
mod
|
|
27
|
-
));
|
|
28
|
-
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
29
|
-
|
|
30
|
-
// src/Witness/Witness.ts
|
|
31
|
-
var Witness_exports = {};
|
|
32
|
-
__export(Witness_exports, {
|
|
33
|
-
ImageThumbnailWitness: () => ImageThumbnailWitness
|
|
34
|
-
});
|
|
35
|
-
module.exports = __toCommonJS(Witness_exports);
|
|
36
|
-
var import_node_dns = require("dns");
|
|
37
|
-
var import_lodash = require("@xylabs/lodash");
|
|
38
|
-
var import_url = require("@xylabs/url");
|
|
39
|
-
var import_axios = require("@xyo-network/axios");
|
|
40
|
-
var import_core2 = require("@xyo-network/core");
|
|
41
|
-
var import_image_thumbnail_payload_plugin2 = require("@xyo-network/image-thumbnail-payload-plugin");
|
|
42
|
-
var import_url_payload_plugin = require("@xyo-network/url-payload-plugin");
|
|
43
|
-
var import_witness = require("@xyo-network/witness");
|
|
44
|
-
var import_async_mutex = require("async-mutex");
|
|
45
|
-
var import_file_type = __toESM(require("file-type"));
|
|
46
|
-
var import_gm = __toESM(require("gm"));
|
|
47
|
-
var import_hasbin = __toESM(require("hasbin"));
|
|
48
|
-
var import_hash_wasm = require("hash-wasm");
|
|
49
|
-
var import_sha = __toESM(require("sha.js"));
|
|
50
|
-
var import_url_parse = __toESM(require("url-parse"));
|
|
51
|
-
|
|
52
|
-
// src/Witness/Config.ts
|
|
53
|
-
var import_image_thumbnail_payload_plugin = require("@xyo-network/image-thumbnail-payload-plugin");
|
|
54
|
-
var ImageThumbnailWitnessConfigSchema = `${import_image_thumbnail_payload_plugin.ImageThumbnailSchema}.witness.config`;
|
|
55
|
-
|
|
56
|
-
// src/Witness/ffmpeg/fluent/getVideoFrameAsImageFluent.ts
|
|
57
|
-
var import_core = require("@xyo-network/core");
|
|
58
|
-
var import_fluent_ffmpeg = __toESM(require("fluent-ffmpeg"));
|
|
59
|
-
var import_promises = require("fs/promises");
|
|
60
|
-
var import_os = require("os");
|
|
61
|
-
var import_stream = require("stream");
|
|
62
|
-
var FfmpegOutputStream = class extends import_stream.Writable {
|
|
63
|
-
chunks = [];
|
|
64
|
-
constructor(options) {
|
|
65
|
-
super(options);
|
|
66
|
-
}
|
|
67
|
-
_write(chunk, _encoding, callback) {
|
|
68
|
-
this.chunks.push(chunk);
|
|
69
|
-
callback();
|
|
70
|
-
}
|
|
71
|
-
/**
|
|
72
|
-
* Collects the output from ffmpeg into a buffer.
|
|
73
|
-
* @returns A buffer containing the concatenated
|
|
74
|
-
* output from ffmpeg.
|
|
75
|
-
*/
|
|
76
|
-
toBuffer = () => Buffer.concat(this.chunks);
|
|
77
|
-
};
|
|
78
|
-
var getVideoFrameAsImageFluent = async (videoBuffer) => {
|
|
79
|
-
const tmpFile = `/${(0, import_os.tmpdir)()}/${(0, import_core.uuid)()}`;
|
|
80
|
-
try {
|
|
81
|
-
await (0, import_promises.writeFile)(tmpFile, videoBuffer, { encoding: "binary" });
|
|
82
|
-
const imageBuffer = await new Promise((resolve, reject) => {
|
|
83
|
-
const ffmpegOutput = new FfmpegOutputStream();
|
|
84
|
-
(0, import_fluent_ffmpeg.default)().on("error", (err) => reject(err.message)).on("end", () => resolve(ffmpegOutput.toBuffer())).input(tmpFile).takeFrames(1).withNoAudio().outputOptions("-f image2pipe").videoCodec("png").pipe(ffmpegOutput);
|
|
85
|
-
});
|
|
86
|
-
return imageBuffer;
|
|
87
|
-
} finally {
|
|
88
|
-
try {
|
|
89
|
-
await (0, import_promises.unlink)(tmpFile);
|
|
90
|
-
} catch {
|
|
91
|
-
}
|
|
92
|
-
}
|
|
93
|
-
};
|
|
94
|
-
|
|
95
|
-
// src/Witness/Witness.ts
|
|
96
|
-
var gm = import_gm.default.subClass({ imageMagick: "7+" });
|
|
97
|
-
var ImageThumbnailWitness = class _ImageThumbnailWitness extends import_witness.AbstractWitness {
|
|
98
|
-
static configSchemas = [ImageThumbnailWitnessConfigSchema];
|
|
99
|
-
_semaphore = new import_async_mutex.Semaphore(this.maxAsyncProcesses);
|
|
100
|
-
get encoding() {
|
|
101
|
-
return this.config.encoding ?? "PNG";
|
|
102
|
-
}
|
|
103
|
-
get height() {
|
|
104
|
-
return this.config.height ?? 128;
|
|
105
|
-
}
|
|
106
|
-
get ipfGateway() {
|
|
107
|
-
return this.config.ipfsGateway ?? "5d7b6582.beta.decentralnetworkservices.com";
|
|
108
|
-
}
|
|
109
|
-
get maxAsyncProcesses() {
|
|
110
|
-
return this.config.maxAsyncProcesses ?? 2;
|
|
111
|
-
}
|
|
112
|
-
get quality() {
|
|
113
|
-
return this.config.quality ?? 50;
|
|
114
|
-
}
|
|
115
|
-
get width() {
|
|
116
|
-
return this.config.width ?? 128;
|
|
117
|
-
}
|
|
118
|
-
static async binaryToSha256(data) {
|
|
119
|
-
await import_core2.PayloadHasher.wasmInitialized;
|
|
120
|
-
if (import_core2.PayloadHasher.wasmSupport.canUseWasm) {
|
|
121
|
-
try {
|
|
122
|
-
return await (0, import_hash_wasm.sha256)(data);
|
|
123
|
-
} catch (ex) {
|
|
124
|
-
import_core2.PayloadHasher.wasmSupport.allowWasm = false;
|
|
125
|
-
}
|
|
126
|
-
}
|
|
127
|
-
return (0, import_sha.default)("sha256").update(data).digest().toString();
|
|
128
|
-
}
|
|
129
|
-
static bufferFromDataUrl(url) {
|
|
130
|
-
if (url.startsWith("data:image")) {
|
|
131
|
-
const data = url.split(",")[1];
|
|
132
|
-
if (data) {
|
|
133
|
-
return Buffer.from(Uint8Array.from(atob(data), (c) => c.charCodeAt(0)));
|
|
134
|
-
} else {
|
|
135
|
-
const error = {
|
|
136
|
-
message: "Invalid data Url",
|
|
137
|
-
name: "ImageThumbnailWitnessError",
|
|
138
|
-
url
|
|
139
|
-
};
|
|
140
|
-
throw error;
|
|
141
|
-
}
|
|
142
|
-
}
|
|
143
|
-
}
|
|
144
|
-
/**
|
|
145
|
-
* Returns the equivalent IPFS gateway URL for the supplied URL.
|
|
146
|
-
* @param urlToCheck The URL to check
|
|
147
|
-
* @returns If the supplied URL is an IPFS URL, it converts the URL to the
|
|
148
|
-
* equivalent IPFS gateway URL. Otherwise, returns the original URL.
|
|
149
|
-
*/
|
|
150
|
-
checkIpfsUrl(urlToCheck) {
|
|
151
|
-
const url = new import_url.URL(urlToCheck);
|
|
152
|
-
let protocol = url.protocol;
|
|
153
|
-
let host = url.host;
|
|
154
|
-
let path = url.pathname;
|
|
155
|
-
const query = url.search;
|
|
156
|
-
if (protocol === "ipfs:") {
|
|
157
|
-
protocol = "https:";
|
|
158
|
-
host = this.ipfGateway;
|
|
159
|
-
path = url.host === "ipfs" ? `ipfs${path}` : `ipfs/${url.host}${path}`;
|
|
160
|
-
const root = `${protocol}//${host}/${path}`;
|
|
161
|
-
return (query == null ? void 0 : query.length) > 0 ? `${root}?${query}` : root;
|
|
162
|
-
} else {
|
|
163
|
-
return urlToCheck;
|
|
164
|
-
}
|
|
165
|
-
}
|
|
166
|
-
async observeHandler(payloads = []) {
|
|
167
|
-
if (!import_hasbin.default.sync("magick")) {
|
|
168
|
-
throw Error("ImageMagick is required for this witness");
|
|
169
|
-
}
|
|
170
|
-
const urlPayloads = payloads.filter((payload) => payload.schema === import_url_payload_plugin.UrlSchema);
|
|
171
|
-
return await this._semaphore.runExclusive(
|
|
172
|
-
async () => (0, import_lodash.compact)(
|
|
173
|
-
await Promise.all(
|
|
174
|
-
urlPayloads.map(async ({ url }) => {
|
|
175
|
-
let result;
|
|
176
|
-
const dataBuffer = _ImageThumbnailWitness.bufferFromDataUrl(url);
|
|
177
|
-
if (dataBuffer) {
|
|
178
|
-
result = {
|
|
179
|
-
schema: import_image_thumbnail_payload_plugin2.ImageThumbnailSchema,
|
|
180
|
-
sourceHash: await _ImageThumbnailWitness.binaryToSha256(dataBuffer),
|
|
181
|
-
sourceUrl: url,
|
|
182
|
-
url
|
|
183
|
-
};
|
|
184
|
-
} else {
|
|
185
|
-
const mutatedUrl = this.checkIpfsUrl(url);
|
|
186
|
-
result = await this.fromHttp(mutatedUrl, url);
|
|
187
|
-
}
|
|
188
|
-
return result;
|
|
189
|
-
})
|
|
190
|
-
)
|
|
191
|
-
)
|
|
192
|
-
);
|
|
193
|
-
}
|
|
194
|
-
async createThumbnailDataUrl(sourceBuffer, encoding) {
|
|
195
|
-
const thumb = await new Promise((resolve, reject) => {
|
|
196
|
-
gm(sourceBuffer).quality(this.quality).resize(this.width, this.height).flatten().toBuffer(encoding ?? this.encoding, (error, buffer) => {
|
|
197
|
-
if (error) {
|
|
198
|
-
reject(error);
|
|
199
|
-
} else {
|
|
200
|
-
resolve(buffer);
|
|
201
|
-
}
|
|
202
|
-
});
|
|
203
|
-
});
|
|
204
|
-
return `data:image/png;base64,${thumb.toString("base64")}`;
|
|
205
|
-
}
|
|
206
|
-
/**
|
|
207
|
-
* Creates an image thumbnail from a video.
|
|
208
|
-
* @param videoBuffer The input video buffer.
|
|
209
|
-
* @returns An buffer containing an image thumbnail for the video.
|
|
210
|
-
*/
|
|
211
|
-
async createThumbnailFromVideo(videoBuffer) {
|
|
212
|
-
const imageBuffer = await getVideoFrameAsImageFluent(videoBuffer);
|
|
213
|
-
return this.createThumbnailDataUrl(imageBuffer);
|
|
214
|
-
}
|
|
215
|
-
// eslint-disable-next-line complexity
|
|
216
|
-
async fromHttp(url, sourceUrl) {
|
|
217
|
-
var _a, _b, _c, _d, _e, _f, _g;
|
|
218
|
-
let response;
|
|
219
|
-
let dnsResult;
|
|
220
|
-
try {
|
|
221
|
-
const urlObj = new import_url_parse.default(url);
|
|
222
|
-
dnsResult = await import_node_dns.promises.resolve(urlObj.host);
|
|
223
|
-
} catch (ex) {
|
|
224
|
-
const error = ex;
|
|
225
|
-
const result2 = {
|
|
226
|
-
http: {
|
|
227
|
-
dnsError: error.code
|
|
228
|
-
},
|
|
229
|
-
schema: import_image_thumbnail_payload_plugin2.ImageThumbnailSchema,
|
|
230
|
-
sourceUrl: sourceUrl ?? url
|
|
231
|
-
};
|
|
232
|
-
return result2;
|
|
233
|
-
}
|
|
234
|
-
try {
|
|
235
|
-
response = await import_axios.axios.get(url, {
|
|
236
|
-
responseType: "arraybuffer"
|
|
237
|
-
});
|
|
238
|
-
} catch (ex) {
|
|
239
|
-
const axiosError = ex;
|
|
240
|
-
if (axiosError.isAxiosError) {
|
|
241
|
-
const result2 = {
|
|
242
|
-
http: {
|
|
243
|
-
ipAddress: dnsResult[0],
|
|
244
|
-
status: (_a = axiosError == null ? void 0 : axiosError.response) == null ? void 0 : _a.status
|
|
245
|
-
},
|
|
246
|
-
schema: import_image_thumbnail_payload_plugin2.ImageThumbnailSchema,
|
|
247
|
-
sourceUrl: sourceUrl ?? url
|
|
248
|
-
};
|
|
249
|
-
return result2;
|
|
250
|
-
} else {
|
|
251
|
-
throw ex;
|
|
252
|
-
}
|
|
253
|
-
}
|
|
254
|
-
const result = {
|
|
255
|
-
http: {
|
|
256
|
-
status: response.status
|
|
257
|
-
},
|
|
258
|
-
schema: import_image_thumbnail_payload_plugin2.ImageThumbnailSchema,
|
|
259
|
-
sourceUrl: sourceUrl ?? url
|
|
260
|
-
};
|
|
261
|
-
if (response.status >= 200 && response.status < 300) {
|
|
262
|
-
const contentType = (_b = response.headers["content-type"]) == null ? void 0 : _b.toString();
|
|
263
|
-
const [mediaType, fileType] = (contentType == null ? void 0 : contentType.split("/")) ?? ["", ""];
|
|
264
|
-
result.mime = result.mime ?? {};
|
|
265
|
-
result.mime.returned = mediaType;
|
|
266
|
-
const sourceBuffer = Buffer.from(response.data, "binary");
|
|
267
|
-
try {
|
|
268
|
-
result.mime.detected = await import_file_type.default.fromBuffer(sourceBuffer);
|
|
269
|
-
} catch (ex) {
|
|
270
|
-
const error = ex;
|
|
271
|
-
(_c = this.logger) == null ? void 0 : _c.error(`FileType error: ${error.message}`);
|
|
272
|
-
}
|
|
273
|
-
const processImage = async (encoding2) => {
|
|
274
|
-
result.sourceHash = await _ImageThumbnailWitness.binaryToSha256(sourceBuffer);
|
|
275
|
-
result.url = await this.createThumbnailDataUrl(sourceBuffer, encoding2);
|
|
276
|
-
};
|
|
277
|
-
const processVideo = async () => {
|
|
278
|
-
if (import_hasbin.default.sync("ffmpeg")) {
|
|
279
|
-
result.sourceHash = await _ImageThumbnailWitness.binaryToSha256(sourceBuffer);
|
|
280
|
-
result.url = await this.createThumbnailFromVideo(sourceBuffer);
|
|
281
|
-
} else {
|
|
282
|
-
result.mime = result.mime ?? {};
|
|
283
|
-
result.mime.invalid = true;
|
|
284
|
-
}
|
|
285
|
-
};
|
|
286
|
-
let encoding = "PNG";
|
|
287
|
-
switch (fileType.toUpperCase()) {
|
|
288
|
-
case "GIF":
|
|
289
|
-
encoding = "GIF";
|
|
290
|
-
break;
|
|
291
|
-
case "JPG":
|
|
292
|
-
case "JPEG":
|
|
293
|
-
encoding = "JPG";
|
|
294
|
-
break;
|
|
295
|
-
}
|
|
296
|
-
switch (mediaType) {
|
|
297
|
-
case "image": {
|
|
298
|
-
await processImage(encoding);
|
|
299
|
-
result.mime.type = mediaType;
|
|
300
|
-
break;
|
|
301
|
-
}
|
|
302
|
-
case "video": {
|
|
303
|
-
await processVideo();
|
|
304
|
-
result.mime.type = mediaType;
|
|
305
|
-
break;
|
|
306
|
-
}
|
|
307
|
-
default: {
|
|
308
|
-
const [detectedMediaType] = ((_e = (_d = result.mime.detected) == null ? void 0 : _d.mime) == null ? void 0 : _e.split("/")) ?? ["", ""];
|
|
309
|
-
switch (detectedMediaType) {
|
|
310
|
-
case "image": {
|
|
311
|
-
await processImage();
|
|
312
|
-
result.mime.type = (_f = result.mime.detected) == null ? void 0 : _f.mime;
|
|
313
|
-
break;
|
|
314
|
-
}
|
|
315
|
-
case "video": {
|
|
316
|
-
await processVideo();
|
|
317
|
-
result.mime.type = (_g = result.mime.detected) == null ? void 0 : _g.mime;
|
|
318
|
-
break;
|
|
319
|
-
}
|
|
320
|
-
default: {
|
|
321
|
-
result.mime.invalid = true;
|
|
322
|
-
break;
|
|
323
|
-
}
|
|
324
|
-
}
|
|
325
|
-
break;
|
|
326
|
-
}
|
|
327
|
-
}
|
|
328
|
-
}
|
|
329
|
-
return result;
|
|
330
|
-
}
|
|
331
|
-
};
|
|
332
|
-
// Annotate the CommonJS export names for ESM import in node:
|
|
333
|
-
0 && (module.exports = {
|
|
334
|
-
ImageThumbnailWitness
|
|
335
|
-
});
|
|
336
|
-
//# sourceMappingURL=Witness.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/Witness/Witness.ts","../../../src/Witness/Config.ts","../../../src/Witness/ffmpeg/fluent/getVideoFrameAsImageFluent.ts"],"sourcesContent":["/* eslint-disable max-statements */\nimport { promises as dnsPromises } from 'node:dns'\n\nimport { compact } from '@xylabs/lodash'\nimport { URL } from '@xylabs/url'\nimport { axios, AxiosError, AxiosResponse } from '@xyo-network/axios'\nimport { PayloadHasher } from '@xyo-network/core'\nimport { ImageThumbnail, ImageThumbnailSchema } from '@xyo-network/image-thumbnail-payload-plugin'\nimport { UrlPayload, UrlSchema } from '@xyo-network/url-payload-plugin'\nimport { AbstractWitness } from '@xyo-network/witness'\nimport { Semaphore } from 'async-mutex'\nimport FileType from 'file-type'\nimport graphicsMagick from 'gm'\nimport hasbin from 'hasbin'\nimport { sha256 } from 'hash-wasm'\nimport shajs from 'sha.js'\nimport Url from 'url-parse'\n\nimport { ImageThumbnailEncoding, ImageThumbnailWitnessConfigSchema } from './Config'\nimport { getVideoFrameAsImageFluent } from './ffmpeg'\nimport { ImageThumbnailWitnessParams } from './Params'\n\n//TODO: Break this into two Witnesses?\n\n// setFfmpegPath(ffmpegPath)\n\n// eslint-disable-next-line import/no-named-as-default-member\nconst gm = graphicsMagick.subClass({ imageMagick: '7+' })\n\nexport interface ImageThumbnailWitnessError extends Error {\n name: 'ImageThumbnailWitnessError'\n url: string\n}\n\nexport interface DnsError extends Error {\n code: string\n}\n\nexport class ImageThumbnailWitness<TParams extends ImageThumbnailWitnessParams = ImageThumbnailWitnessParams> extends AbstractWitness<TParams> {\n static override configSchemas = [ImageThumbnailWitnessConfigSchema]\n\n private _semaphore = new Semaphore(this.maxAsyncProcesses)\n\n get encoding() {\n return this.config.encoding ?? 'PNG'\n }\n\n get height() {\n return this.config.height ?? 128\n }\n\n get ipfGateway() {\n return this.config.ipfsGateway ?? '5d7b6582.beta.decentralnetworkservices.com'\n }\n\n get maxAsyncProcesses() {\n return this.config.maxAsyncProcesses ?? 2\n }\n\n get quality() {\n return this.config.quality ?? 50\n }\n\n get width() {\n return this.config.width ?? 128\n }\n\n private static async binaryToSha256(data: Uint8Array) {\n await PayloadHasher.wasmInitialized\n if (PayloadHasher.wasmSupport.canUseWasm) {\n try {\n return await sha256(data)\n } catch (ex) {\n PayloadHasher.wasmSupport.allowWasm = false\n }\n }\n\n return shajs('sha256').update(data).digest().toString()\n }\n\n private static bufferFromDataUrl(url: string): Buffer | undefined {\n if (url.startsWith('data:image')) {\n const data = url.split(',')[1]\n if (data) {\n return Buffer.from(Uint8Array.from(atob(data), (c) => c.charCodeAt(0)))\n } else {\n const error: ImageThumbnailWitnessError = {\n message: 'Invalid data Url',\n name: 'ImageThumbnailWitnessError',\n url,\n }\n throw error\n }\n }\n }\n\n /**\n * Returns the equivalent IPFS gateway URL for the supplied URL.\n * @param urlToCheck The URL to check\n * @returns If the supplied URL is an IPFS URL, it converts the URL to the\n * equivalent IPFS gateway URL. Otherwise, returns the original URL.\n */\n checkIpfsUrl(urlToCheck: string) {\n const url = new URL(urlToCheck)\n let protocol = url.protocol\n let host = url.host\n let path = url.pathname\n const query = url.search\n if (protocol === 'ipfs:') {\n protocol = 'https:'\n host = this.ipfGateway\n path = url.host === 'ipfs' ? `ipfs${path}` : `ipfs/${url.host}${path}`\n const root = `${protocol}//${host}/${path}`\n return query?.length > 0 ? `${root}?${query}` : root\n } else {\n return urlToCheck\n }\n }\n\n protected override async observeHandler(payloads: UrlPayload[] = []): Promise<ImageThumbnail[]> {\n // eslint-disable-next-line import/no-named-as-default-member\n if (!hasbin.sync('magick')) {\n throw Error('ImageMagick is required for this witness')\n }\n const urlPayloads = payloads.filter((payload) => payload.schema === UrlSchema)\n return await this._semaphore.runExclusive(async () =>\n compact(\n await Promise.all(\n urlPayloads.map<Promise<ImageThumbnail>>(async ({ url }) => {\n let result: ImageThumbnail\n\n //if it is a data URL, return a Buffer\n const dataBuffer = ImageThumbnailWitness.bufferFromDataUrl(url)\n\n if (dataBuffer) {\n result = {\n schema: ImageThumbnailSchema,\n sourceHash: await ImageThumbnailWitness.binaryToSha256(dataBuffer),\n sourceUrl: url,\n url,\n }\n } else {\n //if it is ipfs, go through cloud flair\n const mutatedUrl = this.checkIpfsUrl(url)\n result = await this.fromHttp(mutatedUrl, url)\n }\n return result\n }),\n ),\n ),\n )\n }\n\n private async createThumbnailDataUrl(sourceBuffer: Buffer, encoding?: ImageThumbnailEncoding) {\n const thumb = await new Promise<Buffer>((resolve, reject) => {\n gm(sourceBuffer)\n .quality(this.quality)\n .resize(this.width, this.height)\n .flatten()\n .toBuffer(encoding ?? this.encoding, (error, buffer) => {\n if (error) {\n reject(error)\n } else {\n resolve(buffer)\n }\n })\n })\n return `data:image/png;base64,${thumb.toString('base64')}`\n }\n\n /**\n * Creates an image thumbnail from a video.\n * @param videoBuffer The input video buffer.\n * @returns An buffer containing an image thumbnail for the video.\n */\n private async createThumbnailFromVideo(videoBuffer: Buffer) {\n const imageBuffer = await getVideoFrameAsImageFluent(videoBuffer)\n return this.createThumbnailDataUrl(imageBuffer)\n }\n\n // eslint-disable-next-line complexity\n private async fromHttp(url: string, sourceUrl?: string): Promise<ImageThumbnail> {\n let response: AxiosResponse\n let dnsResult: string[]\n try {\n const urlObj = new Url(url)\n dnsResult = await dnsPromises.resolve(urlObj.host)\n // console.log(`dnsResult: ${JSON.stringify(dnsResult, null, 2)}`)\n } catch (ex) {\n const error = ex as DnsError\n const result: ImageThumbnail = {\n http: {\n dnsError: error.code,\n },\n schema: ImageThumbnailSchema,\n sourceUrl: sourceUrl ?? url,\n }\n return result\n }\n try {\n response = await axios.get(url, {\n responseType: 'arraybuffer',\n })\n } catch (ex) {\n const axiosError = ex as AxiosError\n if (axiosError.isAxiosError) {\n //selectively pick fields from AxiosError\n const result: ImageThumbnail = {\n http: {\n ipAddress: dnsResult[0],\n status: axiosError?.response?.status,\n },\n schema: ImageThumbnailSchema,\n sourceUrl: sourceUrl ?? url,\n }\n return result\n } else {\n throw ex\n }\n }\n\n const result: ImageThumbnail = {\n http: {\n status: response.status,\n },\n schema: ImageThumbnailSchema,\n sourceUrl: sourceUrl ?? url,\n }\n\n if (response.status >= 200 && response.status < 300) {\n const contentType: string | undefined = response.headers['content-type']?.toString()\n const [mediaType, fileType] = contentType?.split('/') ?? ['', '']\n result.mime = result.mime ?? {}\n result.mime.returned = mediaType\n const sourceBuffer = Buffer.from(response.data, 'binary')\n\n try {\n result.mime.detected = await FileType.fromBuffer(sourceBuffer)\n } catch (ex) {\n const error = ex as Error\n this.logger?.error(`FileType error: ${error.message}`)\n }\n\n const processImage = async (encoding?: ImageThumbnailEncoding) => {\n result.sourceHash = await ImageThumbnailWitness.binaryToSha256(sourceBuffer)\n result.url = await this.createThumbnailDataUrl(sourceBuffer, encoding)\n }\n\n const processVideo = async () => {\n // Gracefully handle the case where ffmpeg is not installed.\n // eslint-disable-next-line import/no-named-as-default-member\n if (hasbin.sync('ffmpeg')) {\n result.sourceHash = await ImageThumbnailWitness.binaryToSha256(sourceBuffer)\n result.url = await this.createThumbnailFromVideo(sourceBuffer)\n } else {\n result.mime = result.mime ?? {}\n result.mime.invalid = true\n }\n }\n\n let encoding: ImageThumbnailEncoding = 'PNG'\n\n switch (fileType.toUpperCase()) {\n case 'GIF':\n encoding = 'GIF'\n break\n case 'JPG':\n case 'JPEG':\n encoding = 'JPG'\n break\n }\n\n switch (mediaType) {\n case 'image': {\n await processImage(encoding)\n result.mime.type = mediaType\n break\n }\n case 'video': {\n await processVideo()\n result.mime.type = mediaType\n break\n }\n default: {\n const [detectedMediaType] = result.mime.detected?.mime?.split('/') ?? ['', '']\n switch (detectedMediaType) {\n case 'image': {\n await processImage()\n result.mime.type = result.mime.detected?.mime\n break\n }\n case 'video': {\n await processVideo()\n result.mime.type = result.mime.detected?.mime\n break\n }\n default: {\n result.mime.invalid = true\n break\n }\n }\n break\n }\n }\n }\n return result\n }\n}\n","import { ImageThumbnailSchema } from '@xyo-network/image-thumbnail-payload-plugin'\nimport { WitnessConfig } from '@xyo-network/witness'\n\nexport const ImageThumbnailWitnessConfigSchema = `${ImageThumbnailSchema}.witness.config` as const\nexport type ImageThumbnailWitnessConfigSchema = typeof ImageThumbnailWitnessConfigSchema\n\nexport type ImageThumbnailEncoding = 'PNG' | 'JPG' | 'GIF'\n\nexport type ImageThumbnailWitnessConfig = WitnessConfig<{\n encoding?: ImageThumbnailEncoding\n height?: number\n ipfsGateway?: string\n maxAsyncProcesses?: number\n maxCacheBytes?: number\n maxCacheEntries?: number\n quality?: number\n schema: ImageThumbnailWitnessConfigSchema\n width?: number\n}>\n","import { uuid } from '@xyo-network/core'\nimport ffmpeg from 'fluent-ffmpeg'\nimport { unlink, writeFile } from 'fs/promises'\nimport { tmpdir } from 'os'\nimport { Writable, WritableOptions } from 'stream'\n\n/**\n * A Writable stream that collects output from ffmpeg.\n */\nclass FfmpegOutputStream extends Writable {\n private readonly chunks: Uint8Array[] = []\n\n constructor(options?: WritableOptions) {\n super(options)\n }\n\n override _write(chunk: never, _encoding: BufferEncoding, callback: (error?: Error | null) => void): void {\n this.chunks.push(chunk)\n callback()\n }\n\n /**\n * Collects the output from ffmpeg into a buffer.\n * @returns A buffer containing the concatenated\n * output from ffmpeg.\n */\n toBuffer = () => Buffer.concat(this.chunks)\n}\n\n/**\n * Execute FFmpeg using fluent API with provided input buffer and video thumbnail image.\n * @param videoBuffer Input video buffer.\n * @returns Output buffer containing the video thumbnail image.\n */\nexport const getVideoFrameAsImageFluent = async (videoBuffer: Buffer) => {\n // Get a temp file name\n const tmpFile = `/${tmpdir()}/${uuid()}`\n try {\n // Write videoBuffer to temp file for use as input to ffmpeg to\n // avoid issues with ffmpeg inferring premature EOF from buffer\n // passed via stdin (happens when ffmpeg is trying to infer\n // input video format)\n await writeFile(tmpFile, videoBuffer, { encoding: 'binary' })\n const imageBuffer = await new Promise<Buffer>((resolve, reject) => {\n // Create a Writable stream to collect PNG output from ffmpeg\n const ffmpegOutput = new FfmpegOutputStream()\n // Execute ffmpeg using fluent API\n ffmpeg()\n // NOTE: Uncomment to debug CLI args to ffmpeg\n // .on('start', (commandLine) => console.log('Spawned Ffmpeg with command: ' + commandLine))\n .on('error', (err) => reject(err.message))\n // Listen for the 'end' event to combine the output into a buffer holding the PNG image\n .on('end', () => resolve(ffmpegOutput.toBuffer()))\n .input(tmpFile) // Use temp file as input\n .takeFrames(1) // Only take 1st video frame\n .withNoAudio() // Don't include audio\n .outputOptions('-f image2pipe') // Write output to stdout\n .videoCodec('png') // Force PNG output\n // Start processing and direct ffmpeg stdout to writable stream\n .pipe(ffmpegOutput)\n })\n return imageBuffer\n } finally {\n // Cleanup temp file\n try {\n await unlink(tmpFile)\n } catch {\n // No error here since file doesn't exist\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AACA,sBAAwC;AAExC,oBAAwB;AACxB,iBAAoB;AACpB,mBAAiD;AACjD,IAAAA,eAA8B;AAC9B,IAAAC,yCAAqD;AACrD,gCAAsC;AACtC,qBAAgC;AAChC,yBAA0B;AAC1B,uBAAqB;AACrB,gBAA2B;AAC3B,oBAAmB;AACnB,uBAAuB;AACvB,iBAAkB;AAClB,uBAAgB;;;AChBhB,4CAAqC;AAG9B,IAAM,oCAAoC,GAAG,0DAAoB;;;ACHxE,kBAAqB;AACrB,2BAAmB;AACnB,sBAAkC;AAClC,gBAAuB;AACvB,oBAA0C;AAK1C,IAAM,qBAAN,cAAiC,uBAAS;AAAA,EACvB,SAAuB,CAAC;AAAA,EAEzC,YAAY,SAA2B;AACrC,UAAM,OAAO;AAAA,EACf;AAAA,EAES,OAAO,OAAc,WAA2B,UAAgD;AACvG,SAAK,OAAO,KAAK,KAAK;AAC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aAAa;AACnB,qBAAO,KAAK,QAAO,YAAO,KAAK,aAAZ,mBAAsB;AACzC;AAAA,YACF;AAAA,YACA,SAAS;AACP,qBAAO,KAAK,UAAU;AACtB;AAAA,YACF;AAAA,UACF;AACA;AAAA,QACF;AAAA,MACF;AAAA,IACF;AACA,WAAO;AAAA,EACT;AACF;","names":["import_core","import_image_thumbnail_payload_plugin","ffmpeg","graphicsMagick","shajs","hasbin","Url","dnsPromises","result","FileType","encoding"]}
|
|
@@ -1,301 +0,0 @@
|
|
|
1
|
-
// src/Witness/Witness.ts
|
|
2
|
-
import { promises as dnsPromises } from "node:dns";
|
|
3
|
-
import { compact } from "@xylabs/lodash";
|
|
4
|
-
import { URL } from "@xylabs/url";
|
|
5
|
-
import { axios } from "@xyo-network/axios";
|
|
6
|
-
import { PayloadHasher } from "@xyo-network/core";
|
|
7
|
-
import { ImageThumbnailSchema as ImageThumbnailSchema2 } from "@xyo-network/image-thumbnail-payload-plugin";
|
|
8
|
-
import { UrlSchema } from "@xyo-network/url-payload-plugin";
|
|
9
|
-
import { AbstractWitness } from "@xyo-network/witness";
|
|
10
|
-
import { Semaphore } from "async-mutex";
|
|
11
|
-
import FileType from "file-type";
|
|
12
|
-
import graphicsMagick from "gm";
|
|
13
|
-
import hasbin from "hasbin";
|
|
14
|
-
import { sha256 } from "hash-wasm";
|
|
15
|
-
import shajs from "sha.js";
|
|
16
|
-
import Url from "url-parse";
|
|
17
|
-
|
|
18
|
-
// src/Witness/Config.ts
|
|
19
|
-
import { ImageThumbnailSchema } from "@xyo-network/image-thumbnail-payload-plugin";
|
|
20
|
-
var ImageThumbnailWitnessConfigSchema = `${ImageThumbnailSchema}.witness.config`;
|
|
21
|
-
|
|
22
|
-
// src/Witness/ffmpeg/fluent/getVideoFrameAsImageFluent.ts
|
|
23
|
-
import { uuid } from "@xyo-network/core";
|
|
24
|
-
import ffmpeg from "fluent-ffmpeg";
|
|
25
|
-
import { unlink, writeFile } from "fs/promises";
|
|
26
|
-
import { tmpdir } from "os";
|
|
27
|
-
import { Writable } from "stream";
|
|
28
|
-
var FfmpegOutputStream = class extends Writable {
|
|
29
|
-
chunks = [];
|
|
30
|
-
constructor(options) {
|
|
31
|
-
super(options);
|
|
32
|
-
}
|
|
33
|
-
_write(chunk, _encoding, callback) {
|
|
34
|
-
this.chunks.push(chunk);
|
|
35
|
-
callback();
|
|
36
|
-
}
|
|
37
|
-
/**
|
|
38
|
-
* Collects the output from ffmpeg into a buffer.
|
|
39
|
-
* @returns A buffer containing the concatenated
|
|
40
|
-
* output from ffmpeg.
|
|
41
|
-
*/
|
|
42
|
-
toBuffer = () => Buffer.concat(this.chunks);
|
|
43
|
-
};
|
|
44
|
-
var getVideoFrameAsImageFluent = async (videoBuffer) => {
|
|
45
|
-
const tmpFile = `/${tmpdir()}/${uuid()}`;
|
|
46
|
-
try {
|
|
47
|
-
await writeFile(tmpFile, videoBuffer, { encoding: "binary" });
|
|
48
|
-
const imageBuffer = await new Promise((resolve, reject) => {
|
|
49
|
-
const ffmpegOutput = new FfmpegOutputStream();
|
|
50
|
-
ffmpeg().on("error", (err) => reject(err.message)).on("end", () => resolve(ffmpegOutput.toBuffer())).input(tmpFile).takeFrames(1).withNoAudio().outputOptions("-f image2pipe").videoCodec("png").pipe(ffmpegOutput);
|
|
51
|
-
});
|
|
52
|
-
return imageBuffer;
|
|
53
|
-
} finally {
|
|
54
|
-
try {
|
|
55
|
-
await unlink(tmpFile);
|
|
56
|
-
} catch {
|
|
57
|
-
}
|
|
58
|
-
}
|
|
59
|
-
};
|
|
60
|
-
|
|
61
|
-
// src/Witness/Witness.ts
|
|
62
|
-
var gm = graphicsMagick.subClass({ imageMagick: "7+" });
|
|
63
|
-
var ImageThumbnailWitness = class _ImageThumbnailWitness extends AbstractWitness {
|
|
64
|
-
static configSchemas = [ImageThumbnailWitnessConfigSchema];
|
|
65
|
-
_semaphore = new Semaphore(this.maxAsyncProcesses);
|
|
66
|
-
get encoding() {
|
|
67
|
-
return this.config.encoding ?? "PNG";
|
|
68
|
-
}
|
|
69
|
-
get height() {
|
|
70
|
-
return this.config.height ?? 128;
|
|
71
|
-
}
|
|
72
|
-
get ipfGateway() {
|
|
73
|
-
return this.config.ipfsGateway ?? "5d7b6582.beta.decentralnetworkservices.com";
|
|
74
|
-
}
|
|
75
|
-
get maxAsyncProcesses() {
|
|
76
|
-
return this.config.maxAsyncProcesses ?? 2;
|
|
77
|
-
}
|
|
78
|
-
get quality() {
|
|
79
|
-
return this.config.quality ?? 50;
|
|
80
|
-
}
|
|
81
|
-
get width() {
|
|
82
|
-
return this.config.width ?? 128;
|
|
83
|
-
}
|
|
84
|
-
static async binaryToSha256(data) {
|
|
85
|
-
await PayloadHasher.wasmInitialized;
|
|
86
|
-
if (PayloadHasher.wasmSupport.canUseWasm) {
|
|
87
|
-
try {
|
|
88
|
-
return await sha256(data);
|
|
89
|
-
} catch (ex) {
|
|
90
|
-
PayloadHasher.wasmSupport.allowWasm = false;
|
|
91
|
-
}
|
|
92
|
-
}
|
|
93
|
-
return shajs("sha256").update(data).digest().toString();
|
|
94
|
-
}
|
|
95
|
-
static bufferFromDataUrl(url) {
|
|
96
|
-
if (url.startsWith("data:image")) {
|
|
97
|
-
const data = url.split(",")[1];
|
|
98
|
-
if (data) {
|
|
99
|
-
return Buffer.from(Uint8Array.from(atob(data), (c) => c.charCodeAt(0)));
|
|
100
|
-
} else {
|
|
101
|
-
const error = {
|
|
102
|
-
message: "Invalid data Url",
|
|
103
|
-
name: "ImageThumbnailWitnessError",
|
|
104
|
-
url
|
|
105
|
-
};
|
|
106
|
-
throw error;
|
|
107
|
-
}
|
|
108
|
-
}
|
|
109
|
-
}
|
|
110
|
-
/**
|
|
111
|
-
* Returns the equivalent IPFS gateway URL for the supplied URL.
|
|
112
|
-
* @param urlToCheck The URL to check
|
|
113
|
-
* @returns If the supplied URL is an IPFS URL, it converts the URL to the
|
|
114
|
-
* equivalent IPFS gateway URL. Otherwise, returns the original URL.
|
|
115
|
-
*/
|
|
116
|
-
checkIpfsUrl(urlToCheck) {
|
|
117
|
-
const url = new URL(urlToCheck);
|
|
118
|
-
let protocol = url.protocol;
|
|
119
|
-
let host = url.host;
|
|
120
|
-
let path = url.pathname;
|
|
121
|
-
const query = url.search;
|
|
122
|
-
if (protocol === "ipfs:") {
|
|
123
|
-
protocol = "https:";
|
|
124
|
-
host = this.ipfGateway;
|
|
125
|
-
path = url.host === "ipfs" ? `ipfs${path}` : `ipfs/${url.host}${path}`;
|
|
126
|
-
const root = `${protocol}//${host}/${path}`;
|
|
127
|
-
return (query == null ? void 0 : query.length) > 0 ? `${root}?${query}` : root;
|
|
128
|
-
} else {
|
|
129
|
-
return urlToCheck;
|
|
130
|
-
}
|
|
131
|
-
}
|
|
132
|
-
async observeHandler(payloads = []) {
|
|
133
|
-
if (!hasbin.sync("magick")) {
|
|
134
|
-
throw Error("ImageMagick is required for this witness");
|
|
135
|
-
}
|
|
136
|
-
const urlPayloads = payloads.filter((payload) => payload.schema === UrlSchema);
|
|
137
|
-
return await this._semaphore.runExclusive(
|
|
138
|
-
async () => compact(
|
|
139
|
-
await Promise.all(
|
|
140
|
-
urlPayloads.map(async ({ url }) => {
|
|
141
|
-
let result;
|
|
142
|
-
const dataBuffer = _ImageThumbnailWitness.bufferFromDataUrl(url);
|
|
143
|
-
if (dataBuffer) {
|
|
144
|
-
result = {
|
|
145
|
-
schema: ImageThumbnailSchema2,
|
|
146
|
-
sourceHash: await _ImageThumbnailWitness.binaryToSha256(dataBuffer),
|
|
147
|
-
sourceUrl: url,
|
|
148
|
-
url
|
|
149
|
-
};
|
|
150
|
-
} else {
|
|
151
|
-
const mutatedUrl = this.checkIpfsUrl(url);
|
|
152
|
-
result = await this.fromHttp(mutatedUrl, url);
|
|
153
|
-
}
|
|
154
|
-
return result;
|
|
155
|
-
})
|
|
156
|
-
)
|
|
157
|
-
)
|
|
158
|
-
);
|
|
159
|
-
}
|
|
160
|
-
async createThumbnailDataUrl(sourceBuffer, encoding) {
|
|
161
|
-
const thumb = await new Promise((resolve, reject) => {
|
|
162
|
-
gm(sourceBuffer).quality(this.quality).resize(this.width, this.height).flatten().toBuffer(encoding ?? this.encoding, (error, buffer) => {
|
|
163
|
-
if (error) {
|
|
164
|
-
reject(error);
|
|
165
|
-
} else {
|
|
166
|
-
resolve(buffer);
|
|
167
|
-
}
|
|
168
|
-
});
|
|
169
|
-
});
|
|
170
|
-
return `data:image/png;base64,${thumb.toString("base64")}`;
|
|
171
|
-
}
|
|
172
|
-
/**
|
|
173
|
-
* Creates an image thumbnail from a video.
|
|
174
|
-
* @param videoBuffer The input video buffer.
|
|
175
|
-
* @returns An buffer containing an image thumbnail for the video.
|
|
176
|
-
*/
|
|
177
|
-
async createThumbnailFromVideo(videoBuffer) {
|
|
178
|
-
const imageBuffer = await getVideoFrameAsImageFluent(videoBuffer);
|
|
179
|
-
return this.createThumbnailDataUrl(imageBuffer);
|
|
180
|
-
}
|
|
181
|
-
// eslint-disable-next-line complexity
|
|
182
|
-
async fromHttp(url, sourceUrl) {
|
|
183
|
-
var _a, _b, _c, _d, _e, _f, _g;
|
|
184
|
-
let response;
|
|
185
|
-
let dnsResult;
|
|
186
|
-
try {
|
|
187
|
-
const urlObj = new Url(url);
|
|
188
|
-
dnsResult = await dnsPromises.resolve(urlObj.host);
|
|
189
|
-
} catch (ex) {
|
|
190
|
-
const error = ex;
|
|
191
|
-
const result2 = {
|
|
192
|
-
http: {
|
|
193
|
-
dnsError: error.code
|
|
194
|
-
},
|
|
195
|
-
schema: ImageThumbnailSchema2,
|
|
196
|
-
sourceUrl: sourceUrl ?? url
|
|
197
|
-
};
|
|
198
|
-
return result2;
|
|
199
|
-
}
|
|
200
|
-
try {
|
|
201
|
-
response = await axios.get(url, {
|
|
202
|
-
responseType: "arraybuffer"
|
|
203
|
-
});
|
|
204
|
-
} catch (ex) {
|
|
205
|
-
const axiosError = ex;
|
|
206
|
-
if (axiosError.isAxiosError) {
|
|
207
|
-
const result2 = {
|
|
208
|
-
http: {
|
|
209
|
-
ipAddress: dnsResult[0],
|
|
210
|
-
status: (_a = axiosError == null ? void 0 : axiosError.response) == null ? void 0 : _a.status
|
|
211
|
-
},
|
|
212
|
-
schema: ImageThumbnailSchema2,
|
|
213
|
-
sourceUrl: sourceUrl ?? url
|
|
214
|
-
};
|
|
215
|
-
return result2;
|
|
216
|
-
} else {
|
|
217
|
-
throw ex;
|
|
218
|
-
}
|
|
219
|
-
}
|
|
220
|
-
const result = {
|
|
221
|
-
http: {
|
|
222
|
-
status: response.status
|
|
223
|
-
},
|
|
224
|
-
schema: ImageThumbnailSchema2,
|
|
225
|
-
sourceUrl: sourceUrl ?? url
|
|
226
|
-
};
|
|
227
|
-
if (response.status >= 200 && response.status < 300) {
|
|
228
|
-
const contentType = (_b = response.headers["content-type"]) == null ? void 0 : _b.toString();
|
|
229
|
-
const [mediaType, fileType] = (contentType == null ? void 0 : contentType.split("/")) ?? ["", ""];
|
|
230
|
-
result.mime = result.mime ?? {};
|
|
231
|
-
result.mime.returned = mediaType;
|
|
232
|
-
const sourceBuffer = Buffer.from(response.data, "binary");
|
|
233
|
-
try {
|
|
234
|
-
result.mime.detected = await FileType.fromBuffer(sourceBuffer);
|
|
235
|
-
} catch (ex) {
|
|
236
|
-
const error = ex;
|
|
237
|
-
(_c = this.logger) == null ? void 0 : _c.error(`FileType error: ${error.message}`);
|
|
238
|
-
}
|
|
239
|
-
const processImage = async (encoding2) => {
|
|
240
|
-
result.sourceHash = await _ImageThumbnailWitness.binaryToSha256(sourceBuffer);
|
|
241
|
-
result.url = await this.createThumbnailDataUrl(sourceBuffer, encoding2);
|
|
242
|
-
};
|
|
243
|
-
const processVideo = async () => {
|
|
244
|
-
if (hasbin.sync("ffmpeg")) {
|
|
245
|
-
result.sourceHash = await _ImageThumbnailWitness.binaryToSha256(sourceBuffer);
|
|
246
|
-
result.url = await this.createThumbnailFromVideo(sourceBuffer);
|
|
247
|
-
} else {
|
|
248
|
-
result.mime = result.mime ?? {};
|
|
249
|
-
result.mime.invalid = true;
|
|
250
|
-
}
|
|
251
|
-
};
|
|
252
|
-
let encoding = "PNG";
|
|
253
|
-
switch (fileType.toUpperCase()) {
|
|
254
|
-
case "GIF":
|
|
255
|
-
encoding = "GIF";
|
|
256
|
-
break;
|
|
257
|
-
case "JPG":
|
|
258
|
-
case "JPEG":
|
|
259
|
-
encoding = "JPG";
|
|
260
|
-
break;
|
|
261
|
-
}
|
|
262
|
-
switch (mediaType) {
|
|
263
|
-
case "image": {
|
|
264
|
-
await processImage(encoding);
|
|
265
|
-
result.mime.type = mediaType;
|
|
266
|
-
break;
|
|
267
|
-
}
|
|
268
|
-
case "video": {
|
|
269
|
-
await processVideo();
|
|
270
|
-
result.mime.type = mediaType;
|
|
271
|
-
break;
|
|
272
|
-
}
|
|
273
|
-
default: {
|
|
274
|
-
const [detectedMediaType] = ((_e = (_d = result.mime.detected) == null ? void 0 : _d.mime) == null ? void 0 : _e.split("/")) ?? ["", ""];
|
|
275
|
-
switch (detectedMediaType) {
|
|
276
|
-
case "image": {
|
|
277
|
-
await processImage();
|
|
278
|
-
result.mime.type = (_f = result.mime.detected) == null ? void 0 : _f.mime;
|
|
279
|
-
break;
|
|
280
|
-
}
|
|
281
|
-
case "video": {
|
|
282
|
-
await processVideo();
|
|
283
|
-
result.mime.type = (_g = result.mime.detected) == null ? void 0 : _g.mime;
|
|
284
|
-
break;
|
|
285
|
-
}
|
|
286
|
-
default: {
|
|
287
|
-
result.mime.invalid = true;
|
|
288
|
-
break;
|
|
289
|
-
}
|
|
290
|
-
}
|
|
291
|
-
break;
|
|
292
|
-
}
|
|
293
|
-
}
|
|
294
|
-
}
|
|
295
|
-
return result;
|
|
296
|
-
}
|
|
297
|
-
};
|
|
298
|
-
export {
|
|
299
|
-
ImageThumbnailWitness
|
|
300
|
-
};
|
|
301
|
-
//# sourceMappingURL=Witness.mjs.map
|