-
Notifications
You must be signed in to change notification settings - Fork 264
Expand file tree
/
Copy pathiiif.js
More file actions
233 lines (203 loc) · 7.85 KB
/
iiif.js
File metadata and controls
233 lines (203 loc) · 7.85 KB
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
import {
all, call, put, select, takeEvery,
} from 'redux-saga/effects';
import { Utils } from 'manifesto.js';
import normalizeUrl from 'normalize-url';
import ActionTypes from '../actions/action-types';
import {
receiveManifest, receiveManifestFailure, receiveInfoResponse,
receiveInfoResponseFailure, receiveDegradedInfoResponse,
receiveSearch, receiveSearchFailure,
receiveAnnotation, receiveAnnotationFailure,
} from '../actions';
import {
getManifests,
getRequestsConfig,
getAccessTokens,
selectInfoResponse,
} from '../selectors';
/** */
function fetchWrapper(url, options, { success, degraded, failure }) {
return fetch(url, options)
.then(response => response.json().then((json) => {
if (response.status === 401) return (degraded || success)({ json, response });
if (response.ok) return success({ json, response });
return failure({ error: response.statusText, json, response });
}).catch(error => failure({ error, response })))
.catch(error => failure({ error }));
}
/** */
function* fetchIiifResource(url, options, { success, degraded, failure }) {
const { preprocessors = [], postprocessors = [] } = yield select(getRequestsConfig);
try {
const reqOptions = preprocessors.reduce((acc, f) => f(url, acc) || acc, options);
let action = yield call(fetchWrapper, url, reqOptions, { degraded, failure, success });
action = postprocessors.reduce((acc, f) => f(url, acc) || acc, action);
return action;
} catch (error) { return failure({ error }); }
}
/** */
function* fetchIiifResourceWithAuth(url, iiifResource, options, { degraded, failure, success }) {
const urlOptions = { ...options };
let tokenServiceId;
// If we have a requested IIIF resource (say, the image description from the manifest)
// we can optimistically try an appropriate access token.
//
// TODO: there might be multiple applicable access token services
if (iiifResource) {
const tokenService = yield call(getAccessTokenService, iiifResource);
tokenServiceId = tokenService && tokenService.id;
if (tokenService && tokenService.json) {
urlOptions.headers = {
Authorization: `Bearer ${tokenService.json.accessToken}`,
...options.headers,
};
}
}
const { error, json, response } = yield call(
fetchIiifResource,
url,
urlOptions,
{ failure: arg => arg, success: arg => arg },
);
// Hard error either requesting the resource or deserializing the JSON.
if (error) {
yield put(failure({
error, json, response, tokenServiceId,
}));
return;
}
const id = json['@id'] || json.id;
if (response.ok) {
if (normalizeUrl(id, { stripAuthentication: false })
=== normalizeUrl(url.replace(/info\.json$/, ''), { stripAuthentication: false })) {
yield put(success({ json, response, tokenServiceId }));
return;
}
} else if (response.status !== 401) {
yield put(failure({
error, json, response, tokenServiceId,
}));
return;
}
// Start attempting some IIIF Auth;
// First, the IIIF resource we were given may not be authoritative; check if
// it suggests a different access token service and re-enter the auth workflow
const authoritativeTokenService = yield call(getAccessTokenService, json);
if (authoritativeTokenService && authoritativeTokenService.id !== tokenServiceId) {
yield call(fetchIiifResourceWithAuth, url, json, options, { degraded, failure, success });
return;
}
// Record the response (potentially kicking off other auth flows)
yield put((degraded || success)({ json, response, tokenServiceId }));
}
// Prefer v3 API response, but v2 is acceptable or even any JSON+LD or JSON.
const MANIFEST_ACCEPT_HEADER = 'application/ld+json;q=0.9;profile="http://iiif.io/api/presentation/3/context.json", '
+ 'application/ld+json;q=0.7;profile="http://iiif.io/api/presentation/2/context.json", '
+ 'application/ls+json;q=0.5, '
+ 'application/json;q=0.2';
/** */
export function* fetchManifest({ manifestId }) {
const callbacks = {
failure: ({ error, json, response }) => receiveManifestFailure(manifestId, typeof error === 'object' ? String(error) : error),
success: ({ json, response }) => receiveManifest(manifestId, json),
};
const dispatch = yield call(
fetchIiifResource,
manifestId,
{ headers: { Accept: MANIFEST_ACCEPT_HEADER } },
callbacks,
);
yield put(dispatch);
}
/** @private */
function* getAccessTokenService(resource) {
const manifestoCompatibleResource = resource && resource.__jsonld
? resource
: { ...resource, options: {} };
const services = Utils.getServices(manifestoCompatibleResource).filter(s => s.getProfile().match(/http:\/\/iiif.io\/api\/auth\//));
if (services.length === 0) return undefined;
const accessTokens = yield select(getAccessTokens);
if (!accessTokens) return undefined;
for (let i = 0; i < services.length; i += 1) {
const authService = services[i];
const accessTokenService = Utils.getService(authService, 'http://iiif.io/api/auth/1/token')
|| Utils.getService(authService, 'http://iiif.io/api/auth/0/token');
const token = accessTokenService && accessTokens[accessTokenService.id];
if (token && token.json) return token;
}
return undefined;
}
/** @private */
export function* fetchInfoResponse({ imageResource, infoId, windowId }) {
let iiifResource = imageResource;
if (!iiifResource) {
iiifResource = yield select(selectInfoResponse, { infoId });
}
const callbacks = {
degraded: ({
json, response, tokenServiceId,
}) => receiveDegradedInfoResponse(infoId, json, response.ok, tokenServiceId, windowId),
failure: ({
error, json, response, tokenServiceId,
}) => (
receiveInfoResponseFailure(infoId, error, tokenServiceId)
),
success: ({
json, response, tokenServiceId,
}) => receiveInfoResponse(infoId, json, response.ok, tokenServiceId),
};
yield call(fetchIiifResourceWithAuth, `${infoId.replace(/\/$/, '')}/info.json`, iiifResource, {}, callbacks);
}
/** @private */
export function* fetchSearchResponse({
windowId, companionWindowId, query, searchId,
}) {
const callbacks = {
failure: ({ error, json, response }) => (
receiveSearchFailure(windowId, companionWindowId, searchId, error)
),
success: ({ json, response }) => receiveSearch(windowId, companionWindowId, searchId, json),
};
const dispatch = yield call(fetchIiifResource, searchId, {}, callbacks);
yield put(dispatch);
}
/** @private */
export function* fetchAnnotation({ targetId, annotationId }) {
const callbacks = {
failure: ({ error, json, response }) => (
receiveAnnotationFailure(targetId, annotationId, error)
),
success: ({ json, response }) => receiveAnnotation(targetId, annotationId, json),
};
const dispatch = yield call(fetchIiifResource, annotationId, {}, callbacks);
yield put(dispatch);
}
/** */
export function* fetchResourceManifest({ manifestId, manifestJson }) {
if (manifestJson) {
yield put(receiveManifest(manifestId, manifestJson));
return;
}
if (!manifestId) return;
const manifests = yield select(getManifests) || {};
if (!manifests[manifestId]) yield* fetchManifest({ manifestId });
}
/** */
export function* fetchManifests(...manifestIds) {
const manifests = yield select(getManifests);
for (let i = 0; i < manifestIds.length; i += 1) {
const manifestId = manifestIds[i];
if (!manifests[manifestId]) yield call(fetchManifest, { manifestId });
}
}
/** */
export default function* iiifSaga() {
yield all([
takeEvery(ActionTypes.REQUEST_MANIFEST, fetchManifest),
takeEvery(ActionTypes.REQUEST_INFO_RESPONSE, fetchInfoResponse),
takeEvery(ActionTypes.REQUEST_SEARCH, fetchSearchResponse),
takeEvery(ActionTypes.REQUEST_ANNOTATION, fetchAnnotation),
takeEvery(ActionTypes.ADD_RESOURCE, fetchResourceManifest),
]);
}