@aboutgeo/pdiiif 0.0.0-stage → 0.2.7
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/README.md +169 -2
- package/dist/__tests__/parser.test.d.ts +1 -0
- package/dist/__tests__/pdf.spec.d.ts +1 -0
- package/dist/__tests__/region.test.d.ts +1 -0
- package/dist/__tests__/setupJest.d.ts +0 -0
- package/dist/assets/optimization.worker-C8u4PFfM.js +886 -0
- package/dist/assets/optimization.worker-C8u4PFfM.js.map +1 -0
- package/dist/convert.d.ts +223 -0
- package/dist/download.d.ts +115 -0
- package/dist/iiif.d.ts +110 -0
- package/dist/index.cjs +65 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.mjs +11137 -0
- package/dist/index.mjs.map +1 -0
- package/dist/io.d.ts +75 -0
- package/dist/log.d.ts +21 -0
- package/dist/metrics.d.ts +10 -0
- package/dist/ocr.d.ts +36 -0
- package/dist/optimization.d.ts +48 -0
- package/dist/optimization.worker.d.ts +1 -0
- package/dist/pdf/annos-text.d.ts +19 -0
- package/dist/pdf/annos.d.ts +4 -0
- package/dist/pdf/common.d.ts +48 -0
- package/dist/pdf/generator.d.ts +197 -0
- package/dist/pdf/image.d.ts +34 -0
- package/dist/pdf/parser.d.ts +131 -0
- package/dist/pdf/pkzip.d.ts +23 -0
- package/dist/pdf/png.d.ts +34 -0
- package/dist/pdf/util.d.ts +18 -0
- package/dist/res/licenses.d.ts +7 -0
- package/dist/res/srgbColorspace.d.ts +2 -0
- package/dist/util.d.ts +8 -0
- package/dist/version.d.ts +2 -0
- package/package.json +149 -4
- package/src/__tests__/fixtures/deep_toc.json +2953 -0
- package/src/__tests__/fixtures/flat_toc.json +2917 -0
- package/src/__tests__/fixtures/physdim.json +294 -0
- package/src/__tests__/fixtures/region_target.json +58 -0
- package/src/__tests__/fixtures/wunder.jpg +0 -0
- package/src/__tests__/parser.test.ts +42 -0
- package/src/__tests__/pdf.spec.ts +216 -0
- package/src/__tests__/region.test.ts +194 -0
- package/src/__tests__/setupJest.ts +2 -0
- package/src/convert.ts +1098 -0
- package/src/download.ts +703 -0
- package/src/global.d.ts +10 -0
- package/src/iiif.ts +605 -0
- package/src/index.ts +7 -0
- package/src/io.ts +243 -0
- package/src/log.ts +51 -0
- package/src/metrics.ts +47 -0
- package/src/ocr.ts +176 -0
- package/src/optimization.ts +201 -0
- package/src/optimization.worker.ts +118 -0
- package/src/pdf/annos-text.ts +382 -0
- package/src/pdf/annos.ts +240 -0
- package/src/pdf/common.ts +158 -0
- package/src/pdf/generator.ts +1665 -0
- package/src/pdf/image.ts +340 -0
- package/src/pdf/parser.ts +811 -0
- package/src/pdf/pkzip.ts +228 -0
- package/src/pdf/png.ts +397 -0
- package/src/pdf/util.ts +111 -0
- package/src/res/licenses.ts +266 -0
- package/src/res/srgbColorspace.ts +405 -0
- package/src/types.d.ts +6 -0
- package/src/util.ts +55 -0
- package/src/version.ts +1 -0
package/src/download.ts
ADDED
|
@@ -0,0 +1,703 @@
|
|
|
1
|
+
/* eslint-disable @typescript-eslint/no-non-null-assertion */
|
|
2
|
+
import { Mutex } from 'async-mutex';
|
|
3
|
+
import {
|
|
4
|
+
ExternalWebResource,
|
|
5
|
+
FragmentSelector,
|
|
6
|
+
IIIFExternalWebResource,
|
|
7
|
+
ImageService,
|
|
8
|
+
ImageService3,
|
|
9
|
+
Reference,
|
|
10
|
+
Selector,
|
|
11
|
+
Service,
|
|
12
|
+
} from '@iiif/presentation-3';
|
|
13
|
+
import {
|
|
14
|
+
CanvasNormalized,
|
|
15
|
+
ManifestNormalized,
|
|
16
|
+
RangeNormalized,
|
|
17
|
+
} from '@iiif/presentation-3-normalized'
|
|
18
|
+
|
|
19
|
+
import { OcrPageWithMarkup, fetchAndParseText } from './ocr.js';
|
|
20
|
+
import metrics from './metrics.js';
|
|
21
|
+
import log from './log.js';
|
|
22
|
+
import {
|
|
23
|
+
vault,
|
|
24
|
+
isPhysicalDimensionService,
|
|
25
|
+
PhysicalDimensionService,
|
|
26
|
+
supportsScaling,
|
|
27
|
+
fetchFullImageService,
|
|
28
|
+
getCanvasAnnotations,
|
|
29
|
+
Annotation,
|
|
30
|
+
ImageInfo,
|
|
31
|
+
} from './iiif.js';
|
|
32
|
+
import { isDefined } from './util.js';
|
|
33
|
+
|
|
34
|
+
/// In absence of more detailed information (from physical dimensions service), use this resolution
|
|
35
|
+
const FALLBACK_PPI = 300;
|
|
36
|
+
|
|
37
|
+
// HTTP Accept header to make sure we get IIIFv3, if available, via content negotiation
|
|
38
|
+
// Thanks to @jcoyne:
|
|
39
|
+
// https://github.com/ProjectMirador/mirador/pull/3770/files#diff-166256fe28a89c78ada7b08488a3233671fc0511fd39d323c5cfc9433026e2a1R108-R112
|
|
40
|
+
const MANIFEST_ACCEPT_HEADER = 'application/ld+json;q=0.9;profile="http://iiif.io/api/presentation/3/context.json", '
|
|
41
|
+
+ 'application/ld+json;q=0.7;profile="http://iiif.io/api/presentation/2/context.json", '
|
|
42
|
+
+ 'application/ld+json;q=0.5, '
|
|
43
|
+
+ 'application/json;q=0.2';
|
|
44
|
+
|
|
45
|
+
/** Maps rate-limited hosts to a mutex that limits the concurrent fetching. */
|
|
46
|
+
class RateLimitingRegistry {
|
|
47
|
+
private hostMutexes = new Map<string, Mutex>();
|
|
48
|
+
private callbacks: Array<(host: string, limited: boolean) => void> = [];
|
|
49
|
+
|
|
50
|
+
getMutex(host: string): Mutex | undefined {
|
|
51
|
+
return this.hostMutexes.get(host);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
limitHost(host: string): Mutex {
|
|
55
|
+
const mutex = new Mutex();
|
|
56
|
+
this.hostMutexes.set(host, mutex);
|
|
57
|
+
this.callbacks.forEach((cb) => cb(host, true));
|
|
58
|
+
return mutex;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
unlimitHost(host: string): void {
|
|
62
|
+
this.hostMutexes.delete(host);
|
|
63
|
+
this.callbacks.forEach((cb) => cb(host, false));
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
subscribe(cb: (host: string, limited: boolean) => void): number {
|
|
67
|
+
this.callbacks.push(cb);
|
|
68
|
+
return this.callbacks.length - 1;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
unsubscribe(ticket: number) {
|
|
72
|
+
this.callbacks.splice(ticket, 1);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
isLimited(url: string): boolean {
|
|
76
|
+
return this.hostMutexes.has(new URL(url).host);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export const rateLimitRegistry = new RateLimitingRegistry();
|
|
81
|
+
|
|
82
|
+
/** A 'respectful' wrapper around `fetch` that tries to respect rate-limiting headers.
|
|
83
|
+
*
|
|
84
|
+
* Will also retry with exponential backoff in case of server errors.
|
|
85
|
+
*/
|
|
86
|
+
export async function fetchRespectfully(
|
|
87
|
+
url: string,
|
|
88
|
+
init?: RequestInit,
|
|
89
|
+
maxRetries = 3
|
|
90
|
+
): Promise<Response> {
|
|
91
|
+
const { host } = new URL(url);
|
|
92
|
+
// If the host associated with the URL is rate-limited, limit concurrency to a single
|
|
93
|
+
// fetch at a time by acquiring the mutex for the host.
|
|
94
|
+
let rateLimitMutex = rateLimitRegistry.getMutex(host);
|
|
95
|
+
let numRetries = -1;
|
|
96
|
+
let resp: Response | undefined;
|
|
97
|
+
let waitMs = 5000;
|
|
98
|
+
let lastError: unknown;
|
|
99
|
+
// If we're fetching from a rate-limited host, wait until there's no other fetch for it
|
|
100
|
+
// going on
|
|
101
|
+
const release = await rateLimitMutex?.acquire();
|
|
102
|
+
try {
|
|
103
|
+
do {
|
|
104
|
+
// Don't catch network errors, let them bubble up
|
|
105
|
+
resp = await fetch(url, init);
|
|
106
|
+
if (resp.ok) {
|
|
107
|
+
break;
|
|
108
|
+
}
|
|
109
|
+
numRetries++;
|
|
110
|
+
|
|
111
|
+
const retryAfter = resp?.headers.get('retry-after');
|
|
112
|
+
if (isDefined(retryAfter)) {
|
|
113
|
+
if (Number.isInteger(retryAfter)) {
|
|
114
|
+
waitMs = Number.parseInt(retryAfter, 10) * 1000;
|
|
115
|
+
} else {
|
|
116
|
+
const waitUntil = Date.parse(retryAfter);
|
|
117
|
+
waitMs = waitUntil - Date.now();
|
|
118
|
+
}
|
|
119
|
+
} else {
|
|
120
|
+
// Exponential backoff with a random multiplier on the base wait time
|
|
121
|
+
waitMs = Math.pow(Math.random() * 2 * waitMs, numRetries);
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
// Check if the server response has headers corresponding to the IETF `RateLimit Header Fiels for HTTP` spec draft[1]
|
|
125
|
+
// [1] https://www.ietf.org/archive/id/draft-polli-ratelimit-headers-05.html
|
|
126
|
+
const getHeaderValue = (ietfHeader: string): number | undefined => {
|
|
127
|
+
const headerVariants = [
|
|
128
|
+
ietfHeader,
|
|
129
|
+
`x-${ietfHeader}`,
|
|
130
|
+
`x-${ietfHeader.replace('ratelimit', 'rate-limit')}`,
|
|
131
|
+
];
|
|
132
|
+
return headerVariants
|
|
133
|
+
.map((header) => resp?.headers.get(header))
|
|
134
|
+
.filter(isDefined<string>)
|
|
135
|
+
.map((limit) => Number.parseInt(limit, 10))
|
|
136
|
+
.find((limit) => limit != null);
|
|
137
|
+
};
|
|
138
|
+
const limit = getHeaderValue('ratelimit-limit');
|
|
139
|
+
const remaining = getHeaderValue('ratelimit-remaining');
|
|
140
|
+
const reset = getHeaderValue('ratelimit-reset');
|
|
141
|
+
if (
|
|
142
|
+
limit !== undefined &&
|
|
143
|
+
remaining !== undefined &&
|
|
144
|
+
reset !== undefined
|
|
145
|
+
) {
|
|
146
|
+
// At this point we're pretty sure that we're being rate-limited, so let's
|
|
147
|
+
// limit concurrency from here on out.
|
|
148
|
+
rateLimitMutex = rateLimitRegistry.limitHost(host);
|
|
149
|
+
|
|
150
|
+
// We assume a sliding window implemention here
|
|
151
|
+
const secsPerQuotaUnit = reset / (limit - remaining);
|
|
152
|
+
if (remaining > 0) {
|
|
153
|
+
// If we have remaining quota units but were blocked, we wait until we have enough
|
|
154
|
+
// quota to fetch remaining*2 quota units (i.e. we assume that the units in `remaining`
|
|
155
|
+
// were not enough to fully fetch the resource)
|
|
156
|
+
waitMs = 2 * remaining * secsPerQuotaUnit * 1000;
|
|
157
|
+
} else {
|
|
158
|
+
waitMs = secsPerQuotaUnit * 1000;
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
// Add a 100ms buffer just to be safe and wait until the next attempt
|
|
163
|
+
await new Promise((resolve) => setTimeout(resolve, waitMs + 100));
|
|
164
|
+
} while (numRetries < maxRetries);
|
|
165
|
+
} finally {
|
|
166
|
+
if (rateLimitMutex) {
|
|
167
|
+
// We're being rate-limited, so wait some more so the next request doesn't
|
|
168
|
+
// encounter a server error on fetching
|
|
169
|
+
await new Promise((resolve) => setTimeout(resolve, waitMs + 100));
|
|
170
|
+
}
|
|
171
|
+
release?.();
|
|
172
|
+
}
|
|
173
|
+
if (!resp) {
|
|
174
|
+
throw lastError;
|
|
175
|
+
}
|
|
176
|
+
return resp;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/** Container for image size along with its corresponding IIIF Image API string. */
|
|
180
|
+
export type SizeInfo = {
|
|
181
|
+
iiifSize: string;
|
|
182
|
+
width: number;
|
|
183
|
+
height: number;
|
|
184
|
+
};
|
|
185
|
+
|
|
186
|
+
/** Calculate the image size to fetch, based on user constraints and available sizes
|
|
187
|
+
* in the Image API info.json response.
|
|
188
|
+
*/
|
|
189
|
+
export function getImageSize(
|
|
190
|
+
imgService: ImageService,
|
|
191
|
+
scaleFactor = 1
|
|
192
|
+
): SizeInfo {
|
|
193
|
+
let sizeStr: string;
|
|
194
|
+
const isIIIFv3 = (imgService as ImageService3).id !== undefined;
|
|
195
|
+
const maxWidth = imgService.maxWidth ?? imgService.width!;
|
|
196
|
+
let requestedWidth = Math.floor(scaleFactor * maxWidth);
|
|
197
|
+
const aspectRatio = imgService.width! / imgService.height!;
|
|
198
|
+
const supportsScaleByWh = Array.isArray(imgService.profile)
|
|
199
|
+
? imgService.profile.find(supportsScaling) !== undefined
|
|
200
|
+
: supportsScaling(imgService.profile);
|
|
201
|
+
if (scaleFactor < 1 && !supportsScaleByWh) {
|
|
202
|
+
if (imgService.sizes) {
|
|
203
|
+
// AR-compliant downscaling is not supported, find the closest available size
|
|
204
|
+
requestedWidth = Math.min(...imgService.sizes.map((dims) => Math.abs(requestedWidth - dims.width)));
|
|
205
|
+
sizeStr = `${requestedWidth},`;
|
|
206
|
+
} else {
|
|
207
|
+
// No sizes available, so we can't downscale.
|
|
208
|
+
sizeStr = `${maxWidth},`;
|
|
209
|
+
}
|
|
210
|
+
} else if (scaleFactor == 1) {
|
|
211
|
+
sizeStr =
|
|
212
|
+
isIIIFv3 || imgService.maxWidth || imgService.maxArea ? 'max' : 'full';
|
|
213
|
+
if (imgService.maxWidth) {
|
|
214
|
+
requestedWidth = imgService.maxWidth;
|
|
215
|
+
} else if (imgService.maxHeight) {
|
|
216
|
+
requestedWidth = Math.round(aspectRatio * imgService.maxHeight);
|
|
217
|
+
} else if (imgService.maxArea) {
|
|
218
|
+
const fullArea = imgService.width! * imgService.height!;
|
|
219
|
+
const scaleFactor = imgService.maxArea / fullArea;
|
|
220
|
+
requestedWidth = Math.round(scaleFactor * imgService.width!);
|
|
221
|
+
} else {
|
|
222
|
+
requestedWidth = imgService.width!;
|
|
223
|
+
}
|
|
224
|
+
} else {
|
|
225
|
+
sizeStr = `${requestedWidth},`;
|
|
226
|
+
}
|
|
227
|
+
return {
|
|
228
|
+
iiifSize: sizeStr,
|
|
229
|
+
width: requestedWidth as number,
|
|
230
|
+
height: (requestedWidth as number) / aspectRatio,
|
|
231
|
+
};
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/** A rectangle relative to the full image, all values are between 0 and 1.
|
|
235
|
+
*
|
|
236
|
+
* Relative values stay valid no matter at which size the image was fetched.
|
|
237
|
+
*/
|
|
238
|
+
export type CropRect = {
|
|
239
|
+
x: number;
|
|
240
|
+
y: number;
|
|
241
|
+
width: number;
|
|
242
|
+
height: number;
|
|
243
|
+
};
|
|
244
|
+
|
|
245
|
+
/** Convert an IIIF Image API region to a crop rectangle relative to the full image.
|
|
246
|
+
*
|
|
247
|
+
* @param region Region string (`x,y,w,h`, `pct:x,y,w,h`, `square` or `full`)
|
|
248
|
+
* @param imageWidth Width of the full image in pixels, not needed for `pct:` regions
|
|
249
|
+
* @param imageHeight Height of the full image in pixels, not needed for `pct:` regions
|
|
250
|
+
* @returns The crop rectangle, `undefined` if the region covers the whole image or if it
|
|
251
|
+
* cannot be determined because the image dimensions are unknown.
|
|
252
|
+
* @throws If the region is malformed or lies completely outside of the image.
|
|
253
|
+
*/
|
|
254
|
+
export function getCropRect(
|
|
255
|
+
region: string,
|
|
256
|
+
imageWidth?: number,
|
|
257
|
+
imageHeight?: number
|
|
258
|
+
): CropRect | undefined {
|
|
259
|
+
// Region-string helper: parse a comma-separated list of four numbers.
|
|
260
|
+
const parseFourNumbers = (str: string): number[] | undefined => {
|
|
261
|
+
const parts = str.split(',');
|
|
262
|
+
const nums = parts.map((p) => (p.trim() === '' ? NaN : Number(p)));
|
|
263
|
+
return parts.length === 4 && nums.every(Number.isFinite) ? nums : undefined;
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
const invalid = (reason: string) =>
|
|
267
|
+
new Error(`Invalid image region '${region}': ${reason}`, {
|
|
268
|
+
cause: { type: 'invalid-region' },
|
|
269
|
+
});
|
|
270
|
+
if (region === 'full') {
|
|
271
|
+
return undefined;
|
|
272
|
+
}
|
|
273
|
+
// All coordinates in percent of the full image
|
|
274
|
+
let x: number, y: number, w: number, h: number;
|
|
275
|
+
if (region.startsWith('pct:')) {
|
|
276
|
+
const pct = parseFourNumbers(region.substring(4));
|
|
277
|
+
if (!pct) {
|
|
278
|
+
throw invalid('expected four numbers');
|
|
279
|
+
}
|
|
280
|
+
[x, y, w, h] = pct.map((v) => v / 100);
|
|
281
|
+
} else {
|
|
282
|
+
if (!imageWidth || !imageHeight) {
|
|
283
|
+
log.warn(
|
|
284
|
+
`Cannot crop to region '${region}', image dimensions are unknown. Painting the whole image.`
|
|
285
|
+
);
|
|
286
|
+
return undefined;
|
|
287
|
+
}
|
|
288
|
+
if (region === 'square') {
|
|
289
|
+
const side = Math.min(imageWidth, imageHeight);
|
|
290
|
+
[x, y, w, h] = [
|
|
291
|
+
(imageWidth - side) / 2 / imageWidth,
|
|
292
|
+
(imageHeight - side) / 2 / imageHeight,
|
|
293
|
+
side / imageWidth,
|
|
294
|
+
side / imageHeight,
|
|
295
|
+
];
|
|
296
|
+
} else {
|
|
297
|
+
const px = parseFourNumbers(region);
|
|
298
|
+
if (!px) {
|
|
299
|
+
throw invalid('expected four numbers');
|
|
300
|
+
}
|
|
301
|
+
[x, y, w, h] = [
|
|
302
|
+
px[0] / imageWidth,
|
|
303
|
+
px[1] / imageHeight,
|
|
304
|
+
px[2] / imageWidth,
|
|
305
|
+
px[3] / imageHeight,
|
|
306
|
+
];
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
if (w <= 0 || h <= 0) {
|
|
310
|
+
throw invalid('width and height must be positive');
|
|
311
|
+
}
|
|
312
|
+
// Like the Image API, we only use the part of the region that lies inside the image
|
|
313
|
+
const x2 = Math.min(x + w, 1);
|
|
314
|
+
const y2 = Math.min(y + h, 1);
|
|
315
|
+
x = Math.max(x, 0);
|
|
316
|
+
y = Math.max(y, 0);
|
|
317
|
+
if (x >= x2 || y >= y2) {
|
|
318
|
+
throw invalid('region lies outside of the image');
|
|
319
|
+
}
|
|
320
|
+
if (x === 0 && y === 0 && x2 === 1 && y2 === 1) {
|
|
321
|
+
return undefined;
|
|
322
|
+
}
|
|
323
|
+
return { x, y, width: x2 - x, height: y2 - y };
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
/** Use a IIIF Physical Dimensions service to obtain the PPI for a canvas. */
|
|
327
|
+
export function getPointsPerInch(services: Service[]): number | null {
|
|
328
|
+
const physDimService = services.find(isPhysicalDimensionService) as
|
|
329
|
+
| PhysicalDimensionService
|
|
330
|
+
| undefined;
|
|
331
|
+
if (!physDimService) {
|
|
332
|
+
return null;
|
|
333
|
+
}
|
|
334
|
+
const { physicalScale, physicalUnits } = physDimService;
|
|
335
|
+
let ppi;
|
|
336
|
+
if (physicalUnits === 'in') {
|
|
337
|
+
ppi = 1 / physicalScale;
|
|
338
|
+
} else if (physicalUnits === 'mm') {
|
|
339
|
+
ppi = 25.4 / physicalScale;
|
|
340
|
+
} else if (physicalUnits === 'cm') {
|
|
341
|
+
ppi = 2.54 / physicalScale;
|
|
342
|
+
} else {
|
|
343
|
+
ppi = FALLBACK_PPI;
|
|
344
|
+
}
|
|
345
|
+
return ppi;
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
export function isImageFetchFailure(obj: CanvasImageData | ImageFetchFailure): obj is ImageFetchFailure {
|
|
349
|
+
return (obj as ImageFetchFailure).cause !== undefined;
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
/** All the data relevant for the canvas: images and text */
|
|
353
|
+
export type CanvasData = {
|
|
354
|
+
canvas: Reference<'Canvas'>;
|
|
355
|
+
text?: OcrPageWithMarkup;
|
|
356
|
+
images: CanvasImage[];
|
|
357
|
+
annotations: Annotation[];
|
|
358
|
+
ppi?: number;
|
|
359
|
+
imageFailures: ImageFetchFailure[];
|
|
360
|
+
};
|
|
361
|
+
|
|
362
|
+
export type ImageFetchFailure = ImageInfo & {
|
|
363
|
+
cause: Error | string;
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
|
|
367
|
+
/** Data and additional information for an image on a canvas. */
|
|
368
|
+
export type CanvasImage = ImageInfo & CanvasImageData;
|
|
369
|
+
|
|
370
|
+
/** Data and additional info for a canvas image, based on retrieval
|
|
371
|
+
* of external resources.
|
|
372
|
+
*/
|
|
373
|
+
export type CanvasImageData = {
|
|
374
|
+
data?: ArrayBuffer;
|
|
375
|
+
numBytes: number;
|
|
376
|
+
format: 'jpeg' | 'png';
|
|
377
|
+
corsAvailable: boolean;
|
|
378
|
+
ppi?: number;
|
|
379
|
+
nativeWidth?: number;
|
|
380
|
+
nativeHeight?: number;
|
|
381
|
+
downscaled?: boolean;
|
|
382
|
+
crop?: CropRect;
|
|
383
|
+
};
|
|
384
|
+
|
|
385
|
+
/** Options for fetching image */
|
|
386
|
+
export type FetchImageOptions = {
|
|
387
|
+
/// Factor to downscale the image by, number between 0.1 and 1
|
|
388
|
+
scaleFactor?: number;
|
|
389
|
+
/// PPI override, will be fetched from physical dimensions serivce by default
|
|
390
|
+
ppiOverride?: number;
|
|
391
|
+
// Optional signal to use for aborting the image fetching
|
|
392
|
+
abortSignal?: AbortSignal;
|
|
393
|
+
/// Only obtain the size of the image, don't fetch any data
|
|
394
|
+
sizeOnly?: boolean;
|
|
395
|
+
};
|
|
396
|
+
|
|
397
|
+
/** Download (or only determine size in bytes of) a canvas image. */
|
|
398
|
+
async function fetchCanvasImage(
|
|
399
|
+
image: IIIFExternalWebResource | ExternalWebResource,
|
|
400
|
+
{ scaleFactor, abortSignal, sizeOnly = false }: FetchImageOptions,
|
|
401
|
+
region?: string
|
|
402
|
+
): Promise<CanvasImageData | null> {
|
|
403
|
+
// NOTE: Here be dragons, who'd have thought downloading an image
|
|
404
|
+
// could be so complicated?
|
|
405
|
+
if (abortSignal?.aborted) {
|
|
406
|
+
log.debug(
|
|
407
|
+
'Abort signalled, aborting before initiating image data fetching.'
|
|
408
|
+
);
|
|
409
|
+
throw new Error('Aborted due to client request', { cause: { type: 'abort' } });
|
|
410
|
+
}
|
|
411
|
+
if (image.type !== 'Image') {
|
|
412
|
+
throw new Error(`Can only fetch image resources, got ${image.type}`);
|
|
413
|
+
}
|
|
414
|
+
let imgService: ImageService | undefined;
|
|
415
|
+
if ('service' in image) {
|
|
416
|
+
imgService = image.service?.find(
|
|
417
|
+
(s: Service): s is ImageService =>
|
|
418
|
+
((s as ImageService | undefined)?.type?.startsWith('ImageService') ??
|
|
419
|
+
false) ||
|
|
420
|
+
((s as any)?.['@type']?.startsWith('ImageService') ?? false)
|
|
421
|
+
);
|
|
422
|
+
}
|
|
423
|
+
let ppi: number | undefined;
|
|
424
|
+
let imageUrl: string;
|
|
425
|
+
let downscaled = false;
|
|
426
|
+
// Note: the current implementation leaves the cropping to the PDF
|
|
427
|
+
// generator. This simplifies the whole process and avoids problems with
|
|
428
|
+
// Level 0 services - at the expense of storing more image data in the PDF
|
|
429
|
+
// than would, strictily, be necessary (= the full image rather than just
|
|
430
|
+
// the crop)
|
|
431
|
+
let crop: CropRect | undefined;
|
|
432
|
+
if (imgService) {
|
|
433
|
+
if (!imgService.width) {
|
|
434
|
+
imgService = await fetchFullImageService(imgService);
|
|
435
|
+
}
|
|
436
|
+
const sizeInfo = getImageSize(imgService, scaleFactor);
|
|
437
|
+
imageUrl = `${imgService.id ?? imgService['@id']}/full/${sizeInfo.iiifSize
|
|
438
|
+
}/0/default.jpg`;
|
|
439
|
+
ppi = getPointsPerInch(imgService.service ?? []) ?? undefined;
|
|
440
|
+
if (ppi) {
|
|
441
|
+
ppi = ppi * (sizeInfo.width / imgService.width!);
|
|
442
|
+
}
|
|
443
|
+
if (sizeInfo.width < imgService.width!) {
|
|
444
|
+
downscaled = true;
|
|
445
|
+
}
|
|
446
|
+
} else if (image.id && ['image/jpeg', 'image/png'].indexOf(image.format ?? 'unknown') >= 0) {
|
|
447
|
+
imageUrl = image.id;
|
|
448
|
+
} else {
|
|
449
|
+
log.error(
|
|
450
|
+
`No JPEG or PNG image identifier for resource ${image.id} could be found!`
|
|
451
|
+
);
|
|
452
|
+
return null;
|
|
453
|
+
}
|
|
454
|
+
if (region) {
|
|
455
|
+
// Prefer the dimensions from the image service, they define the coordinate
|
|
456
|
+
// system of the region.
|
|
457
|
+
crop = getCropRect(
|
|
458
|
+
region,
|
|
459
|
+
imgService?.width ?? (image as { width?: number }).width,
|
|
460
|
+
imgService?.height ?? (image as { height?: number }).height
|
|
461
|
+
);
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
let data: ArrayBuffer | undefined;
|
|
465
|
+
let numBytes: number;
|
|
466
|
+
let corsAvailable = true;
|
|
467
|
+
let format: 'jpeg' | 'png' | null = null;
|
|
468
|
+
const stopMeasuring = metrics?.imageFetchDuration.startTimer({
|
|
469
|
+
iiif_host: new URL(imageUrl).host,
|
|
470
|
+
});
|
|
471
|
+
try {
|
|
472
|
+
const imgResp = await fetchRespectfully(imageUrl, {
|
|
473
|
+
method: 'GET',
|
|
474
|
+
signal: abortSignal,
|
|
475
|
+
});
|
|
476
|
+
if (imgResp.status >= 400) {
|
|
477
|
+
throw new Error(
|
|
478
|
+
`Failed to fetch page image from ${imageUrl}, server returned status ${imgResp.status}`,
|
|
479
|
+
{ cause: { type: 'http-status', status: imgResp.status } }
|
|
480
|
+
);
|
|
481
|
+
}
|
|
482
|
+
if (abortSignal?.aborted) {
|
|
483
|
+
throw new Error('Aborted due to client request', { cause: { type: 'abort' } });
|
|
484
|
+
}
|
|
485
|
+
numBytes = Number.parseInt(imgResp.headers.get('Content-Length') ?? '-1');
|
|
486
|
+
data = sizeOnly && numBytes >= 0 ? undefined : await imgResp.arrayBuffer();
|
|
487
|
+
if (imgResp.headers.get('Content-Type')?.startsWith('image/jpeg')) {
|
|
488
|
+
format = 'jpeg';
|
|
489
|
+
} else if (imgResp.headers.get('Content-Type')?.startsWith('image/png')) {
|
|
490
|
+
format = 'png';
|
|
491
|
+
} else {
|
|
492
|
+
throw new Error('Unsupported image content type', { cause: { type: 'content-type' } });
|
|
493
|
+
}
|
|
494
|
+
if (numBytes < 0) {
|
|
495
|
+
numBytes = data?.byteLength ?? -1;
|
|
496
|
+
}
|
|
497
|
+
stopMeasuring?.({
|
|
498
|
+
status: 'success',
|
|
499
|
+
limited: rateLimitRegistry.isLimited(imageUrl).toString(),
|
|
500
|
+
});
|
|
501
|
+
} catch (err) {
|
|
502
|
+
// In browsers, we can't differentiate between a 'normal' network error
|
|
503
|
+
// (like an unavailable server) and a CORS error just from the response
|
|
504
|
+
// alone, so we we use a small hack involving the DOM
|
|
505
|
+
const isCorsError = typeof document !== 'undefined' && await isImageUnavailableDueToCors(imageUrl);
|
|
506
|
+
// No CORS error or CORS error, but need data? Can't continue
|
|
507
|
+
if (!isCorsError) {
|
|
508
|
+
log.error(`Failed to fetch image data from ${imageUrl}: ${err}`);
|
|
509
|
+
stopMeasuring?.({
|
|
510
|
+
status: 'error',
|
|
511
|
+
limited: rateLimitRegistry.isLimited(imageUrl).toString(),
|
|
512
|
+
cause: err instanceof Error ? (err.cause as any).type : err
|
|
513
|
+
});
|
|
514
|
+
throw err;
|
|
515
|
+
} else if (!sizeOnly) {
|
|
516
|
+
throw new Error('Data requested, but no CORS for the image endpoint', { cause: { type: 'no-cors' } });
|
|
517
|
+
}
|
|
518
|
+
corsAvailable = false;
|
|
519
|
+
log.warn(
|
|
520
|
+
`Failed to fetch image data from ${imageUrl}: CORS headers missing!`
|
|
521
|
+
);
|
|
522
|
+
// We can get the size without CORS
|
|
523
|
+
const imgResp = await fetchRespectfully(imageUrl, {
|
|
524
|
+
method: 'GET',
|
|
525
|
+
signal: abortSignal,
|
|
526
|
+
mode: 'no-cors',
|
|
527
|
+
});
|
|
528
|
+
numBytes = Number.parseInt(imgResp.headers.get('Content-Length') ?? '-1');
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
return {
|
|
532
|
+
data,
|
|
533
|
+
ppi,
|
|
534
|
+
numBytes,
|
|
535
|
+
corsAvailable,
|
|
536
|
+
format: format!,
|
|
537
|
+
downscaled,
|
|
538
|
+
...(crop ? { crop } : {}),
|
|
539
|
+
};
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
/** Check if an image is unavailable due to missing CORS headers. */
|
|
543
|
+
async function isImageUnavailableDueToCors(imageUrl: string): Promise<boolean> {
|
|
544
|
+
const imgElem = document.createElement('img');
|
|
545
|
+
imgElem.src = imageUrl;
|
|
546
|
+
return new Promise((resolve) => {
|
|
547
|
+
// Image loads fine for element => Unavailable due to missing CORS headers
|
|
548
|
+
imgElem.onload = () => resolve(true);
|
|
549
|
+
// Image also errors when loading via element => Server can't be reached
|
|
550
|
+
imgElem.onerror = () => resolve(false);
|
|
551
|
+
});
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
/** Information about the starting canvas of a Manifet or a Range.
|
|
555
|
+
* Can point to a whole canvas or to a part of it. */
|
|
556
|
+
export type StartCanvasInfo =
|
|
557
|
+
| string
|
|
558
|
+
| {
|
|
559
|
+
id: string;
|
|
560
|
+
ppi: number; // Needed to create link in PDF
|
|
561
|
+
dimensions: { width: number; height: number };
|
|
562
|
+
position: {
|
|
563
|
+
x: number;
|
|
564
|
+
y: number;
|
|
565
|
+
width: number;
|
|
566
|
+
height: number;
|
|
567
|
+
};
|
|
568
|
+
};
|
|
569
|
+
|
|
570
|
+
/** Fetch all of the information needed for a start canvas. */
|
|
571
|
+
export async function fetchStartCanvasInfo(
|
|
572
|
+
resource: ManifestNormalized | RangeNormalized
|
|
573
|
+
): Promise<StartCanvasInfo | undefined> {
|
|
574
|
+
const startRef = resource.start;
|
|
575
|
+
if (!startRef) {
|
|
576
|
+
return;
|
|
577
|
+
}
|
|
578
|
+
let canvasId: string | undefined;
|
|
579
|
+
let fragment: string | undefined;
|
|
580
|
+
if (typeof startRef === 'string') {
|
|
581
|
+
const [ident, selectorStr] = (startRef as string).split('#xywh=');
|
|
582
|
+
if (!selectorStr) {
|
|
583
|
+
return ident;
|
|
584
|
+
}
|
|
585
|
+
canvasId = ident;
|
|
586
|
+
fragment = `xywh=${selectorStr}`;
|
|
587
|
+
} else if (startRef.type === 'SpecificResource') {
|
|
588
|
+
return startRef.id;
|
|
589
|
+
} else {
|
|
590
|
+
const selector = vault.get<Exclude<Selector, string>>(startRef.id!);
|
|
591
|
+
if (typeof selector === 'string' || selector.type !== 'FragmentSelector') {
|
|
592
|
+
log.warn(
|
|
593
|
+
`Unsupported selector type, cannot determine start canvas for ${resource.id}`
|
|
594
|
+
);
|
|
595
|
+
return;
|
|
596
|
+
}
|
|
597
|
+
const fragSel = selector as FragmentSelector;
|
|
598
|
+
if (fragSel.conformsTo !== 'http://www.w3.org/TR/media-frags/') {
|
|
599
|
+
log.warn(
|
|
600
|
+
`Unsupported selector type, cannot determine start canvas for ${resource.id} (fragment selector type was ${fragSel.conformsTo})`
|
|
601
|
+
);
|
|
602
|
+
return;
|
|
603
|
+
}
|
|
604
|
+
canvasId = fragSel.value;
|
|
605
|
+
}
|
|
606
|
+
if (!fragment || !canvasId) {
|
|
607
|
+
log.error(
|
|
608
|
+
`Couldn't parse either canvas identifier or selector for ${resource.id} start canvas.`
|
|
609
|
+
);
|
|
610
|
+
return;
|
|
611
|
+
}
|
|
612
|
+
const [selX, selY, selWidth, selHeight] = fragment
|
|
613
|
+
.substring(5)
|
|
614
|
+
.split(',')
|
|
615
|
+
.map((v) => Number.parseInt(v, 10));
|
|
616
|
+
const canvas = vault.get<CanvasNormalized>(canvasId);
|
|
617
|
+
const ppi = getPointsPerInch(canvas.service) ?? FALLBACK_PPI;
|
|
618
|
+
return {
|
|
619
|
+
id: canvasId,
|
|
620
|
+
ppi,
|
|
621
|
+
dimensions: { width: canvas.width, height: canvas.height },
|
|
622
|
+
position: {
|
|
623
|
+
x: selX,
|
|
624
|
+
y: selY,
|
|
625
|
+
width: selWidth,
|
|
626
|
+
height: selHeight,
|
|
627
|
+
},
|
|
628
|
+
};
|
|
629
|
+
}
|
|
630
|
+
|
|
631
|
+
/** Fetch all of the data associated with a canvas, including external services. */
|
|
632
|
+
export async function fetchCanvasData(
|
|
633
|
+
canvas: CanvasNormalized,
|
|
634
|
+
imageInfos: ImageInfo[],
|
|
635
|
+
{ scaleFactor, ppiOverride, abortSignal, sizeOnly = false }: FetchImageOptions
|
|
636
|
+
): Promise<CanvasData | undefined> {
|
|
637
|
+
const imagePromises = imageInfos.map(i => fetchCanvasImage(i.resource, { scaleFactor, abortSignal, sizeOnly }, i.region));
|
|
638
|
+
const results = await Promise.allSettled(imagePromises);
|
|
639
|
+
const canvasImages = results
|
|
640
|
+
.reduce((acc, x, idx) => {
|
|
641
|
+
if (x.status !== 'fulfilled' || x.value === null) {
|
|
642
|
+
return acc;
|
|
643
|
+
}
|
|
644
|
+
const imgInfo = imageInfos[idx];
|
|
645
|
+
acc.push({
|
|
646
|
+
...imgInfo,
|
|
647
|
+
...x.value,
|
|
648
|
+
// FIXME: How can we get rid of the cast?
|
|
649
|
+
} as CanvasImage);
|
|
650
|
+
return acc;
|
|
651
|
+
}, [] as CanvasImage[])
|
|
652
|
+
const failures: ImageFetchFailure[] = results
|
|
653
|
+
.filter((x): x is PromiseRejectedResult => x.status === 'rejected')
|
|
654
|
+
.map((x, idx) => {
|
|
655
|
+
const info = imageInfos[idx];
|
|
656
|
+
return {
|
|
657
|
+
...info,
|
|
658
|
+
cause: x.reason,
|
|
659
|
+
}
|
|
660
|
+
});
|
|
661
|
+
const ppi = ppiOverride;
|
|
662
|
+
if (!ppiOverride) {
|
|
663
|
+
let ppi = getPointsPerInch(canvas.service) ?? undefined;
|
|
664
|
+
if (ppi && scaleFactor) {
|
|
665
|
+
ppi = ppi * scaleFactor;
|
|
666
|
+
}
|
|
667
|
+
}
|
|
668
|
+
let text;
|
|
669
|
+
if (!sizeOnly) {
|
|
670
|
+
try {
|
|
671
|
+
text = await fetchAndParseText(canvas, undefined);
|
|
672
|
+
} catch (err) {
|
|
673
|
+
log.warn(`Failed to fetch text for canvas ${canvas.id}: ${err}`);
|
|
674
|
+
}
|
|
675
|
+
}
|
|
676
|
+
return {
|
|
677
|
+
canvas,
|
|
678
|
+
images: canvasImages,
|
|
679
|
+
imageFailures: failures,
|
|
680
|
+
ppi,
|
|
681
|
+
text,
|
|
682
|
+
annotations: getCanvasAnnotations(canvas),
|
|
683
|
+
};
|
|
684
|
+
}
|
|
685
|
+
|
|
686
|
+
/** Download the JSON data for a manifest, handling stuff like broken CORS implementations
|
|
687
|
+
* and Content-Negotiation for IIIFv3 */
|
|
688
|
+
export async function fetchManifestJson(manifestUrl: string): Promise<any> {
|
|
689
|
+
try {
|
|
690
|
+
const resp = await fetch(manifestUrl, {
|
|
691
|
+
headers: {
|
|
692
|
+
Accept: MANIFEST_ACCEPT_HEADER
|
|
693
|
+
}
|
|
694
|
+
});
|
|
695
|
+
return await resp.json();
|
|
696
|
+
} catch (err) {
|
|
697
|
+
// Check if fetching failed due to CORS by downgrading the request to a
|
|
698
|
+
// 'simple' request by removing the `Accept` header, which makes the
|
|
699
|
+
// request CORS-unsafe due to double quotes and the colon in the URL
|
|
700
|
+
const resp = await fetch(manifestUrl);
|
|
701
|
+
return await resp.json();
|
|
702
|
+
}
|
|
703
|
+
}
|