/
Utils.ts
472 lines (369 loc) · 18.1 KB
/
Utils.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
import { AnnotationMotivation, ExternalResourceType } from "@iiif/vocabulary/dist-commonjs/";
import { Directory } from "./Directory";
import { dirname, extname } from "path";
import { IConfigJSON } from "./IConfigJSON";
import { join, basename } from "path";
import { promise as glob } from "glob-promise";
import { TypeFormat } from "./TypeFormat";
import chalk from "chalk";
import config from "./config.json";
import ffprobe from "ffprobe";
import ffprobeStatic from "ffprobe-static";
import fs from "fs";
import isURL from "is-url";
import Jimp from "jimp";
import jsonfile from "jsonfile";
import labelBoilerplate from "./boilerplate/label.json";
import thumbnailBoilerplate from "./boilerplate/thumbnail.json";
import urljoin from "url-join";
import yaml from "js-yaml";
export class Utils {
private static _config: IConfigJSON = config;
public static compare(a: string, b: string): number {
const collator: Intl.Collator = new Intl.Collator(undefined, {numeric: true, sensitivity: 'base'});
return collator.compare(a, b);
}
public static normaliseType(type: string): string {
type = type.toLowerCase();
if (type.indexOf(':') !== -1) {
const split: string[] = type.split(':');
return split[1];
}
return type;
}
public static getTypeByExtension(motivation: string, extension: string): string | null {
motivation = Utils.normaliseType(motivation);
const m: any = this._config.annotation.motivations[motivation];
if (m) {
if (m[extension] && m[extension].length) {
return m[extension][0].type;
}
}
return null;
}
public static getFormatByExtension(motivation: string, extension: string): string | null {
motivation = Utils.normaliseType(motivation);
const m: any = this._config.annotation.motivations[motivation];
if (m) {
if (m[extension] && m[extension].length) {
return m[extension][0].format;
}
}
return null;
}
public static getFormatByExtensionAndType(motivation: string, extension: string, type: string): string | null {
motivation = Utils.normaliseType(motivation);
const m: any = this._config.annotation.motivations[motivation];
if (m) {
if (m[extension] && m[extension].length) {
const typeformats: TypeFormat[] = m[extension];
for (let i = 0; i < typeformats.length; i++) {
const typeformat: TypeFormat = typeformats[i];
if (typeformat.type === type) {
return typeformat.format;
}
}
}
}
return null;
}
public static getTypeByFormat(motivation: string, format: string): string | null {
motivation = Utils.normaliseType(motivation);
const m: any = this._config.annotation.motivations[motivation];
if (m) {
for (const extension in m) {
const typeformats: TypeFormat[] = m[extension];
for (let i = 0; i < typeformats.length; i++) {
const typeformat: TypeFormat = typeformats[i];
if (typeformat.format === format) {
return typeformat.type;
}
}
}
}
return null;
}
public static getFormatByType(motivation: string, type: string): string | null {
motivation = Utils.normaliseType(motivation);
const m: any = this._config.annotation.motivations[motivation];
// only able to categorically say there's a matching format
// if there's a single extension with a single type
if (m) {
if (Object.keys(m).length === 1) {
const typeformats: TypeFormat[] = m[Object.keys(m)[0]];
if (typeformats.length === 1) {
return typeformats[0].format;
}
}
}
return null;
}
public static timeout(ms: number): Promise<void> {
return new Promise(resolve => setTimeout(resolve, ms));
}
public static cloneJson (json: any): any {
return JSON.parse(JSON.stringify(json));
}
public static formatMetadata(metadata: any): any {
const formattedMetadata: any[] = [];
for (let key in metadata) {
if (metadata.hasOwnProperty(key)) {
const value: string = metadata[key];
const item: any = {};
item.label = Utils.getLabel(key);
item.value = Utils.getLabel(value);
formattedMetadata.push(item);
}
}
return formattedMetadata;
}
// If filePath is:
// C://Users/edsilv/github/edsilv/biiif-workshop/collection/_abyssinian/thumb.jpeg
// and 'collection' has been replaced by the top-level virtual name 'virtualname'
// it should return:
// C://Users/edsilv/github/edsilv/biiif-workshop/virtualname/_abyssinian/thumb.jpeg
// virtual names are needed when using dat or ipfs ids as the root directory.
public static getVirtualFilePath(filePath: string, directory: Directory): string {
// walk up directory parents building the realPath and virtualPath array as we go.
// at the top level directory, use the real name for realPath and the virtual name for virtualPath.
// reverse the arrays and join with a '/'.
// replace the realPath section of filePath with virtualPath.
let realPath: string[] = [basename(filePath)];
let virtualPath: string[] = [basename(filePath)];
while(directory) {
const realName: string = basename(directory.directoryPath);
const virtualName: string = directory.virtualName || realName;
realPath.push(realName);
virtualPath.push(virtualName);
directory = directory.parentDirectory;
}
realPath = realPath.reverse();
virtualPath = virtualPath.reverse();
const realPathString: string = realPath.join('/');
const virtualPathString: string = virtualPath.join('/');
filePath = Utils.normaliseFilePath(filePath);
filePath = filePath.replace(realPathString, virtualPathString);
return filePath;
}
public static isJsonFile(path: string): boolean {
return extname(path) === '.json';
}
public static isDirectory(path: string): boolean {
return fs.lstatSync(path).isDirectory();
}
public static async getThumbnail(json: any, directory: Directory, filePath?: string): Promise<void> {
let fp: string = filePath || directory.directoryPath;
fp = Utils.normaliseFilePath(fp);
const thumbnailPattern: string = fp + '/thumb.*';
const thumbnails: string[] = await glob(thumbnailPattern);
if (thumbnails.length) {
// there's alrady a thumbnail in the directory, add it to the canvas
console.log(chalk.green('found thumbnail for: ') + fp);
let thumbnail: string = thumbnails[0];
const thumbnailJson: any = Utils.cloneJson(thumbnailBoilerplate);
thumbnailJson[0].id = Utils.mergePaths(directory.url, Utils.getVirtualFilePath(thumbnail, directory));
json.thumbnail = thumbnailJson;
} else if (directory.generateThumbs) {
// there isn't a thumbnail in the directory, so we'll need to generate it.
// if debugging: jimp item.getitem is not a function
// generate thumbnail
if (json.items && json.items.length && json.items[0].items) {
// find an annotation with a painting motivation of type image.
const items: any[] = json.items[0].items;
for (let i = 0; i < items.length; i++) {
const item: any = items[i];
const body: any = item.body;
if (body && item.motivation === Utils.normaliseType(AnnotationMotivation.PAINTING)) {
// is it an image? (without an info.json)
if (body.type.toLowerCase() === ExternalResourceType.IMAGE && !Utils.isJsonFile(body.id)) {
let imageName: string = body.id.substr(body.id.lastIndexOf('/'));
if (imageName.includes('#')) {
imageName = imageName.substr(0, imageName.lastIndexOf('#'));
}
const imagePath: string = Utils.normaliseFilePath(join(fp, imageName));
let pathToThumb: string = Utils.normaliseFilePath(join(dirname(imagePath), 'thumb.'));
// todo: this currently assumes that the image to generate a thumb from is within the directory,
// but it may be in an assets folder and painted by a custom annotation.
// see canvas-with-dimensions-manifest.js
if (this._config.settings.jimpEnabled && await Utils.fileExists(imagePath)) {
const image: any = await Jimp.read(imagePath);
const thumb: any = image.clone();
// write image buffer to disk for testing
// image.getBuffer(Jimp.AUTO, (err, buffer) => {
// const arrBuffer = [...buffer];
// const pathToBuffer: string = imagePath.substr(0, imagePath.lastIndexOf('/')) + '/buffer.txt';
// fs.writeFile(pathToBuffer, arrBuffer);
// });
//thumb.cover(this._config.thumbnails.width, this._config.thumbnails.height);
thumb.resize(this._config.thumbnails.width, Jimp.AUTO);
pathToThumb += image.getExtension();
// a thumbnail may already exist at this path (when generating from a flat collection of images)
const thumbExists: boolean = await Utils.fileExists(pathToThumb);
if (!thumbExists) {
thumb.write(pathToThumb, () => {
console.log(chalk.green('generated thumbnail for: ') + fp);
});
} else {
console.log(chalk.green('found thumbnail for: ') + fp);
}
} else {
// placeholder img path
pathToThumb += "jpeg";
}
const thumbnailJson: any = Utils.cloneJson(thumbnailBoilerplate);
const virtualPath: string = Utils.getVirtualFilePath(pathToThumb, directory);
const mergedPath: string = Utils.mergePaths(directory.url, virtualPath);
thumbnailJson[0].id = mergedPath;
json.thumbnail = thumbnailJson;
}
}
}
}
}
}
public static getLabel(value: string): any {
const labelJson: any = Utils.cloneJson(labelBoilerplate);
labelJson['@none'].push(value);
return labelJson;
}
public static async getFileDimensions(type: string, file: string, canvasJson: any, annotationJson: any): Promise<void> {
console.log(chalk.green('getting file dimensions for: ') + file);
if (!Utils.isJsonFile(file)) {
switch (type.toLowerCase()) {
// if it's an image, get the width and height and add to the annotation body and canvas
case ExternalResourceType.IMAGE :
const image: any = await Jimp.read(file);
const width: number = image.bitmap.width;
const height: number = image.bitmap.height;
canvasJson.width = Math.max(canvasJson.width || 0, width);
canvasJson.height = Math.max(canvasJson.height || 0, height);
annotationJson.body.width = width;
annotationJson.body.height = height;
break;
// if it's a sound, get the duration and add to the canvas
case ExternalResourceType.SOUND :
case ExternalResourceType.VIDEO :
try {
const info: any = await ffprobe(file, { path: ffprobeStatic.path });
if (info && info.streams && info.streams.length) {
const duration: number = Number(info.streams[0].duration);
canvasJson.duration = duration;
}
} catch {
console.warn(`ffprobe couldn't load ${file}`);
}
break;
}
}
}
/*
merge these two example paths:
url: http://test.com/collection/manifest
filePath: c:/user/documents/collection/manifest/_canvas/thumb.png
into: http://test.com/collection/manifest/_canvas/thumb.png
*/
public static mergePaths(url: URL, filePath: string): string {
// split the url (minus origin) and filePath into arrays
// ['collection', 'manifest']
// ['c:', 'user', 'documents', 'collection', 'manifest', '_canvas', 'thumb.jpg']
// walk backwards through the filePath array adding to the newPath array until the last item of the url array is found.
// then while the next url item matches the next filePath item, add it to newPath.
// the final path is the url origin plus a reversed newPath joined with a '/'
let origin = url.origin;
if (url.protocol === 'dat:') {
origin = 'dat://';
}
const urlParts = Utils.getUrlParts(url);
filePath = Utils.normaliseFilePath(filePath);
const fileParts: string[] = filePath.split('/');
let newPath: string[] = [];
// if there's a single root folder and none of the file path matches
if (urlParts.length === 1 && !fileParts.includes(urlParts[0])) {
newPath.push(fileParts[fileParts.length - 1]);
newPath.push(urlParts[0]);
} else {
for (let f = fileParts.length - 1; f >= 0; f--) {
const filePart: string = fileParts[f];
newPath.push(filePart);
if (filePart === urlParts[urlParts.length - 1]) {
if (urlParts.length > 1) {
for (let u = urlParts.length - 2; u >= 0; u--) {
f--;
if (fileParts[f] === urlParts[u]) {
newPath.push(fileParts[f]);
} else {
newPath.push(urlParts[u]);
}
}
}
break;
}
}
}
let id: string = urljoin(origin, ...newPath.reverse());
return id;
}
public static normaliseFilePath(filePath: string): string {
return filePath.replace(/\\/g, '/').replace(/\/\//g, '/');
}
public static getUrlParts(url: URL): string[] {
let origin: string = url.origin;
let urlParts: string[];
let href: string = url.href;
if (href.endsWith('/')) {
href = href.slice(0, -1);
}
if (url.protocol === 'dat:') {
origin = 'dat://';
urlParts = href.replace(origin, '').split('/');
} else {
urlParts = href.replace(origin + '/', '').split('/');
}
return urlParts;
}
public static async readJson(path: string): Promise<string> {
return new Promise<string>((resolve, reject) => {
jsonfile.readFile(path, (err, json) => {
if (err) reject(err);
else resolve(json);
});
});
}
public static async writeJson(path: string, json: string): Promise<void> {
return new Promise<void>((resolve, reject) => {
fs.writeFile(path, json, (err) => {
if (err) reject(err);
else resolve();
});
});
}
public static async readYml(path: string): Promise<string> {
return new Promise<string>((resolve, reject) => {
fs.readFile(path, (err, fileBuffer) => {
if (err) {
reject(err);
} else {
const yml: string = yaml.safeLoad(fileBuffer)
resolve(yml);
}
});
});
}
public static async fileExists(path: string): Promise<boolean> {
return new Promise<boolean>((resolve, reject) => {
const exists: boolean = fs.existsSync(path);
resolve(exists)
});
}
public static async hasManifestsYml(path: string): Promise<boolean> {
return new Promise<boolean>((resolve, reject) => {
const manifestsPath: string = join(path, 'manifests.yml');
Utils.fileExists(manifestsPath).then((exists) => {
resolve(exists);
});
});
}
public static isURL(path: string): boolean {
return isURL(path);
}
}