forked from openedx/frontend-app-authoring
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrequests.js
More file actions
510 lines (479 loc) · 16.2 KB
/
requests.js
File metadata and controls
510 lines (479 loc) · 16.2 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
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
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
import { v4 as uuid4 } from 'uuid';
import { StrictDict, parseLibraryImageData, getLibraryImageAssets } from '../../../utils';
import { RequestKeys } from '../../constants/requests';
import api, { loadImages } from '../../services/cms/api';
import { actions as requestsActions } from '../requests';
import { selectors as appSelectors } from '../app';
import { selectors as videoSelectors } from '../video';
// This 'module' self-import hack enables mocking during tests.
// See src/editors/decisions/0005-internal-editor-testability-decisions.md. The whole approach to how hooks are tested
// should be re-thought and cleaned up to avoid this pattern.
// eslint-disable-next-line import/no-self-import
import * as module from './requests';
import { isLibraryKey } from '../../../../generic/key-utils';
import { createLibraryBlock } from '../../../../library-authoring/data/api';
import { acceptedImgKeys } from '../../../sharedComponents/ImageUploadModal/SelectImageModal/utils';
import { blockTypes } from '../../constants/app';
import { problemTitles } from '../../constants/problem';
// Similar to `import { actions, selectors } from '..';` but avoid circular imports:
const actions = { requests: requestsActions };
const selectors = { app: appSelectors, video: videoSelectors };
/**
* Wrapper around a network request promise, that sends actions to the redux store to
* track the state of that promise.
* Tracks the promise by requestKey, and sends an action when it is started, succeeds, or
* fails. It also accepts onSuccess and onFailure methods to be called with the output
* of failure or success of the promise.
* @param {string} requestKey - request tracking identifier
* @param {Promise} promise - api event promise
* @param {[func]} onSuccess - onSuccess method ((response) => { ... })
* @param {[func]} onFailure - onFailure method ((error) => { ... })
*/
export const networkRequest = ({
requestKey,
promise,
onSuccess,
onFailure,
}) => (dispatch) => {
dispatch(actions.requests.startRequest(requestKey));
return promise
.then((response) => {
if (onSuccess) {
onSuccess(response);
}
dispatch(actions.requests.completeRequest({ requestKey, response }));
})
.catch((error) => {
if (onFailure) {
onFailure(error);
}
dispatch(actions.requests.failRequest({ requestKey, error }));
});
};
/**
* Tracked fetchByBlockId api method.
* Tracked to the `fetchBlock` request key.
* @param {[func]} onSuccess - onSuccess method ((response) => { ... })
* @param {[func]} onFailure - onFailure method ((error) => { ... })
*/
export const fetchBlock = ({ ...rest }) => (dispatch, getState) => {
dispatch(module.networkRequest({
requestKey: RequestKeys.fetchBlock,
promise: api.fetchBlockById({
studioEndpointUrl: selectors.app.studioEndpointUrl(getState()),
blockId: selectors.app.blockId(getState()),
}),
...rest,
}));
};
/**
* Tracked fetchStudioView api method.
* Tracked to the `fetchBlock` request key.
* @param {[func]} onSuccess - onSuccess method ((response) => { ... })
* @param {[func]} onFailure - onFailure method ((error) => { ... })
*/
export const fetchStudioView = ({ ...rest }) => (dispatch, getState) => {
dispatch(module.networkRequest({
requestKey: RequestKeys.fetchStudioView,
promise: api.fetchStudioView({
studioEndpointUrl: selectors.app.studioEndpointUrl(getState()),
blockId: selectors.app.blockId(getState()),
}),
...rest,
}));
};
/**
* Tracked fetchByUnitId api method.
* Tracked to the `fetchUnit` request key.
* @param {[func]} onSuccess - onSuccess method ((response) => { ... })
* @param {[func]} onFailure - onFailure method ((error) => { ... })
*/
export const fetchUnit = ({ ...rest }) => (dispatch, getState) => {
dispatch(module.networkRequest({
requestKey: RequestKeys.fetchUnit,
promise: api.fetchByUnitId({
studioEndpointUrl: selectors.app.studioEndpointUrl(getState()),
blockId: selectors.app.blockId(getState()),
}),
...rest,
}));
};
/**
* Tracked saveBlock api method. Tracked to the `saveBlock` request key.
* @param {Object} content
* @param {[func]} onSuccess - onSuccess method ((response) => { ... })
* @param {[func]} onFailure - onFailure method ((error) => { ... })
*/
export const saveBlock = ({ content, ...rest }) => (dispatch, getState) => {
dispatch(module.networkRequest({
requestKey: RequestKeys.saveBlock,
promise: api.saveBlock({
blockId: selectors.app.blockId(getState()),
blockType: selectors.app.blockType(getState()),
learningContextId: selectors.app.learningContextId(getState()),
content,
studioEndpointUrl: selectors.app.studioEndpointUrl(getState()),
title: selectors.app.blockTitle(getState()),
}),
...rest,
}));
};
/**
* Tracked createBlock api method. Tracked to the `createBlock` request key.
* @param {[func]} onSuccess - onSuccess method ((response) => { ... })
* @param {[func]} onFailure - onFailure method ((error) => { ... })
*/
export const createBlock = ({ ...rest }) => (dispatch, getState) => {
const blockTitle = selectors.app.blockTitle(getState());
const blockType = selectors.app.blockType(getState());
// Remove any special character, a slug should be created with unicode letters, numbers, underscores or hyphens.
const cleanTitle = blockTitle?.toLowerCase().replace(/[^a-zA-Z0-9_\s-]/g, '').trim();
let definitionId;
// Validates if the title has been assigned by the user, if not a UUID is returned as the key.
if (!cleanTitle || (blockType === blockTypes.problem && problemTitles.has(blockTitle))) {
definitionId = `${uuid4()}`;
} else {
// add a short random suffix to prevent conflicting IDs.
const suffix = uuid4().split('-')[4];
definitionId = `${cleanTitle.replaceAll(/\s+/g, '-')}-${suffix}`;
}
dispatch(module.networkRequest({
requestKey: RequestKeys.createBlock,
promise: createLibraryBlock({
libraryId: selectors.app.learningContextId(getState()),
blockType,
definitionId,
}),
...rest,
}));
};
// exportend only for test
export const removeTemporalLink = (response, asset, content, resolve) => {
const imagePath = `/${response.data.asset.portableUrl}`;
const reader = new FileReader();
reader.addEventListener('load', () => {
const imageBS64 = /** @type {string} */(reader.result);
const parsedContent = typeof content === 'string' ? content.replace(imageBS64, imagePath) : { ...content, olx: content.olx.replace(imageBS64, imagePath) };
URL.revokeObjectURL(asset);
resolve(parsedContent);
});
reader.readAsDataURL(asset);
};
export const batchUploadAssets = ({ assets, content, ...rest }) => (dispatch) => {
const promises = assets.reduce((promiseChain, asset) => promiseChain
.then((parsedContent) => new Promise((resolve) => {
dispatch(module.uploadAsset({
asset,
onSuccess: (response) => removeTemporalLink(response, asset, parsedContent, resolve),
}));
})), Promise.resolve(content));
dispatch(module.networkRequest({
requestKey: RequestKeys.batchUploadAssets,
promise: promises,
...rest,
}));
};
export const uploadAsset = ({ asset, ...rest }) => (dispatch, getState) => {
const learningContextId = selectors.app.learningContextId(getState());
return dispatch(module.networkRequest({
requestKey: RequestKeys.uploadAsset,
promise: api.uploadAsset({
learningContextId,
asset,
studioEndpointUrl: selectors.app.studioEndpointUrl(getState()),
blockId: selectors.app.blockId(getState()),
}).then((resp) => {
if (isLibraryKey(learningContextId)) {
return ({
...resp,
data: { asset: parseLibraryImageData(resp.data) },
});
}
return resp;
}),
...rest,
}));
};
export const fetchImages = ({ pageNumber, ...rest }) => (dispatch, getState) => {
const learningContextId = selectors.app.learningContextId(getState());
if (isLibraryKey(learningContextId)) {
dispatch(module.networkRequest({
requestKey: RequestKeys.fetchImages,
promise: api
.fetchLibraryImages({
pageNumber,
blockId: selectors.app.blockId(getState()),
studioEndpointUrl: selectors.app.studioEndpointUrl(getState()),
learningContextId,
})
.then(({ data }) => {
const images = getLibraryImageAssets(data.files, Object.keys(acceptedImgKeys));
return { images, imageCount: Object.keys(images).length };
}),
...rest,
}));
return;
}
dispatch(module.networkRequest({
requestKey: RequestKeys.fetchImages,
promise: api
.fetchCourseImages({
pageNumber,
blockId: selectors.app.blockId(getState()),
studioEndpointUrl: selectors.app.studioEndpointUrl(getState()),
learningContextId,
})
.then(({ data }) => ({ images: loadImages(data.assets), imageCount: data.totalCount })),
...rest,
}));
};
export const fetchVideos = ({ ...rest }) => (dispatch, getState) => {
dispatch(module.networkRequest({
requestKey: RequestKeys.fetchVideos,
promise: api
.fetchVideos({
studioEndpointUrl: selectors.app.studioEndpointUrl(getState()),
learningContextId: selectors.app.learningContextId(getState()),
}),
...rest,
}));
};
export const allowThumbnailUpload = ({ ...rest }) => (dispatch, getState) => {
dispatch(module.networkRequest({
requestKey: RequestKeys.allowThumbnailUpload,
promise: api.allowThumbnailUpload({
studioEndpointUrl: selectors.app.studioEndpointUrl(getState()),
}),
...rest,
}));
};
export const uploadThumbnail = ({ thumbnail, videoId, ...rest }) => (dispatch, getState) => {
dispatch(module.networkRequest({
requestKey: RequestKeys.uploadThumbnail,
promise: api.uploadThumbnail({
studioEndpointUrl: selectors.app.studioEndpointUrl(getState()),
learningContextId: selectors.app.learningContextId(getState()),
thumbnail,
videoId,
}),
...rest,
}));
};
export const checkTranscriptsForImport = ({ videoId, youTubeId, ...rest }) => (dispatch, getState) => {
dispatch(module.networkRequest({
requestKey: RequestKeys.checkTranscriptsForImport,
promise: api.checkTranscriptsForImport({
blockId: selectors.app.blockId(getState()),
videoId,
youTubeId,
studioEndpointUrl: selectors.app.studioEndpointUrl(getState()),
}),
...rest,
}));
};
export const importTranscript = ({ youTubeId, ...rest }) => (dispatch, getState) => {
dispatch(module.networkRequest({
requestKey: RequestKeys.importTranscript,
promise: api.importTranscript({
blockId: selectors.app.blockId(getState()),
studioEndpointUrl: selectors.app.studioEndpointUrl(getState()),
youTubeId,
}),
...rest,
}));
};
export const deleteTranscript = ({ language, videoId, ...rest }) => (dispatch, getState) => {
const state = getState();
const isLibrary = selectors.app.isLibrary(state);
if (isLibrary) {
dispatch(module.networkRequest({
requestKey: RequestKeys.deleteTranscript,
promise: api.deleteTranscriptV2({
language,
videoId,
handlerUrl: selectors.video.transcriptHandlerUrl(state),
}),
...rest,
}));
} else {
dispatch(module.networkRequest({
requestKey: RequestKeys.deleteTranscript,
promise: api.deleteTranscript({
blockId: selectors.app.blockId(state),
language,
videoId,
studioEndpointUrl: selectors.app.studioEndpointUrl(state),
}),
...rest,
}));
}
};
export const uploadTranscript = ({
transcript,
videoId,
language,
...rest
}) => (dispatch, getState) => {
const state = getState();
const isLibrary = selectors.app.isLibrary(state);
if (isLibrary) {
dispatch(module.networkRequest({
requestKey: RequestKeys.uploadTranscript,
promise: api.uploadTranscriptV2({
handlerUrl: selectors.video.transcriptHandlerUrl(state),
transcript,
videoId,
language,
}),
...rest,
}));
} else {
dispatch(module.networkRequest({
requestKey: RequestKeys.uploadTranscript,
promise: api.uploadTranscript({
blockId: selectors.app.blockId(state),
transcript,
videoId,
language,
studioEndpointUrl: selectors.app.studioEndpointUrl(state),
}),
...rest,
}));
}
};
export const updateTranscriptLanguage = ({
file,
languageBeforeChange,
newLanguageCode,
videoId,
...rest
}) => (dispatch, getState) => {
const state = getState();
const isLibrary = selectors.app.isLibrary(state);
if (isLibrary) {
dispatch(module.networkRequest({
requestKey: RequestKeys.updateTranscriptLanguage,
promise: api.uploadTranscriptV2({
handlerUrl: selectors.video.transcriptHandlerUrl(state),
transcript: file,
videoId,
language: languageBeforeChange,
newLanguage: newLanguageCode,
}),
...rest,
}));
} else {
dispatch(module.networkRequest({
requestKey: RequestKeys.updateTranscriptLanguage,
promise: api.uploadTranscript({
blockId: selectors.app.blockId(state),
transcript: file,
videoId,
language: languageBeforeChange,
newLanguage: newLanguageCode,
studioEndpointUrl: selectors.app.studioEndpointUrl(state),
}),
...rest,
}));
}
};
export const getTranscriptFile = ({ language, videoId, ...rest }) => (dispatch, getState) => {
const state = getState();
const isLibrary = selectors.app.isLibrary(state);
if (isLibrary) {
dispatch(module.networkRequest({
requestKey: RequestKeys.getTranscriptFile,
promise: api.getTranscriptV2({
handlerUrl: selectors.video.transcriptHandlerUrl(state),
videoId,
language,
}),
...rest,
}));
} else {
dispatch(module.networkRequest({
requestKey: RequestKeys.getTranscriptFile,
promise: api.getTranscript({
studioEndpointUrl: selectors.app.studioEndpointUrl(state),
blockId: selectors.app.blockId(state),
videoId,
language,
}),
...rest,
}));
}
};
export const getHandlerlUrl = ({ handlerName, ...rest }) => (dispatch, getState) => {
dispatch(module.networkRequest({
requestKey: RequestKeys.getHandlerUrl,
promise: api.getHandlerUrl({
studioEndpointUrl: selectors.app.studioEndpointUrl(getState()),
blockId: selectors.app.blockId(getState()),
handlerName,
}),
...rest,
}));
};
export const fetchCourseDetails = ({ ...rest }) => (dispatch, getState) => {
dispatch(module.networkRequest({
requestKey: RequestKeys.fetchCourseDetails,
promise: api.fetchCourseDetails({
studioEndpointUrl: selectors.app.studioEndpointUrl(getState()),
learningContextId: selectors.app.learningContextId(getState()),
}),
...rest,
}));
};
export const fetchAdvancedSettings = ({ ...rest }) => (dispatch, getState) => {
dispatch(module.networkRequest({
requestKey: RequestKeys.fetchAdvancedSettings,
promise: api.fetchAdvancedSettings({
studioEndpointUrl: selectors.app.studioEndpointUrl(getState()),
learningContextId: selectors.app.learningContextId(getState()),
}),
...rest,
}));
};
export const fetchVideoFeatures = ({ ...rest }) => (dispatch, getState) => {
dispatch(module.networkRequest({
requestKey: RequestKeys.fetchVideoFeatures,
promise: api.fetchVideoFeatures({
studioEndpointUrl: selectors.app.studioEndpointUrl(getState()),
}),
...rest,
}));
};
export const uploadVideo = ({ data, ...rest }) => (dispatch, getState) => {
dispatch(module.networkRequest({
requestKey: RequestKeys.uploadVideo,
promise: api.uploadVideo({
data,
studioEndpointUrl: selectors.app.studioEndpointUrl(getState()),
learningContextId: selectors.app.learningContextId(getState()),
}),
...rest,
}));
};
export default StrictDict({
fetchBlock,
fetchStudioView,
fetchUnit,
createBlock,
saveBlock,
fetchImages,
fetchVideos,
uploadAsset,
allowThumbnailUpload,
uploadThumbnail,
deleteTranscript,
uploadTranscript,
updateTranscriptLanguage,
fetchCourseDetails,
getTranscriptFile,
checkTranscriptsForImport,
importTranscript,
fetchAdvancedSettings,
fetchVideoFeatures,
uploadVideo,
getHandlerlUrl,
});