forked from DSpace/dspace-angular
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathitem-bitstreams.service.ts
More file actions
571 lines (507 loc) · 19.8 KB
/
Copy pathitem-bitstreams.service.ts
File metadata and controls
571 lines (507 loc) · 19.8 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
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
import { Injectable } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';
import { MoveOperation } from 'fast-json-patch';
import {
BehaviorSubject,
Observable,
zip as observableZip,
} from 'rxjs';
import {
map,
switchMap,
take,
tap,
} from 'rxjs/operators';
import { getBitstreamDownloadRoute } from '../../../app-routing-paths';
import { DSONameService } from '../../../core/breadcrumbs/dso-name.service';
import { BitstreamDataService } from '../../../core/data/bitstream-data.service';
import { BundleDataService } from '../../../core/data/bundle-data.service';
import { MAX_PAGE_SIZE } from '../../../core/data/find-list-options.model';
import { FieldChangeType } from '../../../core/data/object-updates/field-change-type.model';
import { FieldUpdate } from '../../../core/data/object-updates/field-update.model';
import { FieldUpdates } from '../../../core/data/object-updates/field-updates.model';
import { ObjectUpdatesService } from '../../../core/data/object-updates/object-updates.service';
import { RemoteData } from '../../../core/data/remote-data';
import { RequestService } from '../../../core/data/request.service';
import { Bitstream } from '../../../core/shared/bitstream.model';
import { BitstreamFormat } from '../../../core/shared/bitstream-format.model';
import { Bundle } from '../../../core/shared/bundle.model';
import { NoContent } from '../../../core/shared/NoContent.model';
import {
getFirstCompletedRemoteData,
getFirstSucceededRemoteDataPayload,
} from '../../../core/shared/operators';
import {
hasNoValue,
hasValue,
} from '../../../shared/empty.util';
import { LiveRegionService } from '../../../shared/live-region/live-region.service';
import { NotificationsService } from '../../../shared/notifications/notifications.service';
import { PaginationComponentOptions } from '../../../shared/pagination/pagination-component-options.model';
import { ResponsiveColumnSizes } from '../../../shared/responsive-table-sizes/responsive-column-sizes';
import { ResponsiveTableSizes } from '../../../shared/responsive-table-sizes/responsive-table-sizes';
export const MOVE_KEY = 'item.edit.bitstreams.notifications.move';
/**
* Interface storing all the information necessary to create a row in the bitstream edit table
*/
export interface BitstreamTableEntry {
/**
* The bitstream
*/
bitstream: Bitstream,
/**
* The uuid of the Bitstream
*/
id: string,
/**
* The name of the Bitstream
*/
name: string,
/**
* The name of the Bitstream with all whitespace removed
*/
nameStripped: string,
/**
* The description of the Bitstream
*/
description: string,
/**
* Observable emitting the Format of the Bitstream
*/
format: Observable<BitstreamFormat>,
/**
* The download url of the Bitstream
*/
downloadUrl: string,
}
/**
* Interface storing information necessary to highlight and reorder the selected bitstream entry
*/
export interface SelectedBitstreamTableEntry {
/**
* The selected entry
*/
bitstream: BitstreamTableEntry,
/**
* The bundle the bitstream belongs to
*/
bundle: Bundle,
/**
* The total number of bitstreams in the bundle
*/
bundleSize: number,
/**
* The original position of the bitstream within the bundle.
*/
originalPosition: number,
/**
* The current position of the bitstream within the bundle.
*/
currentPosition: number,
}
/**
* Interface storing data regarding a change in selected bitstream
*/
export interface SelectionAction {
/**
* The different types of actions:
* - Selected: Bitstream was selected
* - Moved: Bitstream was moved
* - Cleared: Selection was cleared, bitstream remains at its current position
* - Cancelled: Selection was cancelled, bitstream returns to its original position
*/
action: 'Selected' | 'Moved' | 'Cleared' | 'Cancelled'
/**
* The table entry to which the selection action applies
*/
selectedEntry: SelectedBitstreamTableEntry,
}
/**
* This service handles the selection and updating of the bitstreams and their order on the
* 'Edit Item' -> 'Bitstreams' page.
*/
@Injectable(
{ providedIn: 'root' },
)
export class ItemBitstreamsService {
/**
* BehaviorSubject which emits every time the selected bitstream changes.
*/
protected selectionAction$: BehaviorSubject<SelectionAction> = new BehaviorSubject(null);
protected isPerformingMoveRequest: BehaviorSubject<boolean> = new BehaviorSubject(false);
constructor(
protected notificationsService: NotificationsService,
protected translateService: TranslateService,
protected objectUpdatesService: ObjectUpdatesService,
protected bitstreamService: BitstreamDataService,
protected bundleService: BundleDataService,
protected dsoNameService: DSONameService,
protected requestService: RequestService,
protected liveRegionService: LiveRegionService,
) {
}
/**
* Returns the observable emitting the selection actions
*/
getSelectionAction$(): Observable<SelectionAction> {
return this.selectionAction$;
}
/**
* Returns the latest selection action
*/
getSelectionAction(): SelectionAction {
const action = this.selectionAction$.value;
if (hasNoValue(action)) {
return null;
}
return Object.assign({}, action);
}
/**
* Returns true if there currently is a selected bitstream
*/
hasSelectedBitstream(): boolean {
const selectionAction = this.getSelectionAction();
if (hasNoValue(selectionAction)) {
return false;
}
const action = selectionAction.action;
return action === 'Selected' || action === 'Moved';
}
/**
* Returns a copy of the currently selected bitstream
*/
getSelectedBitstream(): SelectedBitstreamTableEntry {
if (!this.hasSelectedBitstream()) {
return null;
}
const selectionAction = this.getSelectionAction();
return Object.assign({}, selectionAction.selectedEntry);
}
/**
* Select the provided entry
*/
selectBitstreamEntry(entry: SelectedBitstreamTableEntry) {
if (hasValue(entry) && entry.bitstream !== this.getSelectedBitstream()?.bitstream) {
this.announceSelect(entry.bitstream.name);
this.updateSelectionAction({ action: 'Selected', selectedEntry: entry });
}
}
/**
* Makes the {@link selectionAction$} observable emit the provided {@link SelectedBitstreamTableEntry}.
* @protected
*/
protected updateSelectionAction(action: SelectionAction) {
this.selectionAction$.next(action);
}
/**
* Unselects the selected bitstream. Does nothing if no bitstream is selected.
*/
clearSelection() {
const selected = this.getSelectedBitstream();
if (hasValue(selected)) {
this.updateSelectionAction({ action: 'Cleared', selectedEntry: selected });
this.announceClear(selected.bitstream.name);
if (selected.currentPosition !== selected.originalPosition) {
this.displaySuccessNotification(MOVE_KEY);
}
}
}
/**
* Returns the currently selected bitstream to its original position and unselects the bitstream.
* Does nothing if no bitstream is selected.
*/
cancelSelection() {
const selected = this.getSelectedBitstream();
if (hasNoValue(selected) || this.getPerformingMoveRequest()) {
return;
}
const originalPosition = selected.originalPosition;
const currentPosition = selected.currentPosition;
// If the selected bitstream has not moved, there is no need to return it to its original position
if (currentPosition === originalPosition) {
this.announceClear(selected.bitstream.name);
this.updateSelectionAction({ action: 'Cleared', selectedEntry: selected });
} else {
this.announceCancel(selected.bitstream.name, originalPosition);
this.performBitstreamMoveRequest(selected.bundle, currentPosition, originalPosition);
this.updateSelectionAction({ action: 'Cancelled', selectedEntry: selected });
}
}
/**
* Moves the selected bitstream one position up in the bundle. Does nothing if no bitstream is selected or the
* selected bitstream already is at the beginning of the bundle.
*/
moveSelectedBitstreamUp() {
const selected = this.getSelectedBitstream();
if (hasNoValue(selected) || this.getPerformingMoveRequest()) {
return;
}
const originalPosition = selected.currentPosition;
if (originalPosition > 0) {
const newPosition = originalPosition - 1;
selected.currentPosition = newPosition;
const onRequestCompleted = () => {
this.announceMove(selected.bitstream.name, newPosition);
};
this.performBitstreamMoveRequest(selected.bundle, originalPosition, newPosition, onRequestCompleted);
this.updateSelectionAction({ action: 'Moved', selectedEntry: selected });
}
}
/**
* Moves the selected bitstream one position down in the bundle. Does nothing if no bitstream is selected or the
* selected bitstream already is at the end of the bundle.
*/
moveSelectedBitstreamDown() {
const selected = this.getSelectedBitstream();
if (hasNoValue(selected) || this.getPerformingMoveRequest()) {
return;
}
const originalPosition = selected.currentPosition;
if (originalPosition < selected.bundleSize - 1) {
const newPosition = originalPosition + 1;
selected.currentPosition = newPosition;
const onRequestCompleted = () => {
this.announceMove(selected.bitstream.name, newPosition);
};
this.performBitstreamMoveRequest(selected.bundle, originalPosition, newPosition, onRequestCompleted);
this.updateSelectionAction({ action: 'Moved', selectedEntry: selected });
}
}
/**
* Sends out a Move Patch request to the REST API, display notifications,
* refresh the bundle's cache (so the lists can properly reload)
* @param bundle The bundle to send patch requests to
* @param fromIndex The index to move from
* @param toIndex The index to move to
* @param finish Optional: Function to execute once the response has been received
*/
performBitstreamMoveRequest(bundle: Bundle, fromIndex: number, toIndex: number, finish?: () => void) {
if (this.getPerformingMoveRequest()) {
console.warn('Attempted to perform move request while previous request has not completed yet');
return;
}
const moveOperation: MoveOperation = {
op: 'move',
from: `/_links/bitstreams/${fromIndex}/href`,
path: `/_links/bitstreams/${toIndex}/href`,
};
this.announceLoading();
this.isPerformingMoveRequest.next(true);
this.bundleService.patch(bundle, [moveOperation]).pipe(
getFirstCompletedRemoteData(),
tap((response: RemoteData<Bundle>) => this.displayFailedResponseNotifications(MOVE_KEY, [response])),
switchMap(() => this.requestService.setStaleByHrefSubstring(bundle.self)),
take(1),
).subscribe(() => {
this.isPerformingMoveRequest.next(false);
finish?.();
});
}
/**
* Whether the service currently is processing a 'move' request
*/
getPerformingMoveRequest(): boolean {
return this.isPerformingMoveRequest.value;
}
/**
* Returns an observable which emits when the service starts, or ends, processing a 'move' request
*/
getPerformingMoveRequest$(): Observable<boolean> {
return this.isPerformingMoveRequest;
}
/**
* Returns the pagination options to use when fetching the bundles
*/
getInitialBundlesPaginationOptions(): PaginationComponentOptions {
return Object.assign(new PaginationComponentOptions(), {
id: 'bundles-pagination-options',
currentPage: 1,
pageSize: MAX_PAGE_SIZE,
});
}
/**
* Returns the initial pagination options to use when fetching the bitstreams
* @param bundleName The name of the bundle, will be as pagination id.
*/
getInitialBitstreamsPaginationOptions(bundleName: string): PaginationComponentOptions {
return Object.assign(new PaginationComponentOptions(),{
id: bundleName, // This might behave unexpectedly if the item contains two bundles with the same name
currentPage: 1,
pageSize: 10,
});
}
/**
* Returns the {@link ResponsiveTableSizes} for use in the columns of the edit bitstreams table
*/
getColumnSizes(): ResponsiveTableSizes {
return new ResponsiveTableSizes([
// Name column
new ResponsiveColumnSizes(3, 3, 3, 3, 3),
// Description column
new ResponsiveColumnSizes(3, 3, 3, 3, 3),
// Format column
new ResponsiveColumnSizes(2, 2, 2, 2, 2),
// Actions column
new ResponsiveColumnSizes(2, 2, 2, 2, 2),
// Store synchronization column
new ResponsiveColumnSizes(2, 2, 2, 2, 2),
]);
}
/**
* Display notifications
* - Error notification for each failed response with their message
* - Success notification in case there's at least one successful response
* @param key The i18n key for the notification messages
* @param responses The returned responses to display notifications for
*/
displayNotifications(key: string, responses: RemoteData<any>[]) {
this.displayFailedResponseNotifications(key, responses);
this.displaySuccessFulResponseNotifications(key, responses);
}
/**
* Display an error notification for each failed response with their message
* @param key The i18n key for the notification messages
* @param responses The returned responses to display notifications for
*/
displayFailedResponseNotifications(key: string, responses: RemoteData<any>[]) {
const failedResponses = responses.filter((response: RemoteData<Bundle>) => hasValue(response) && response.hasFailed);
failedResponses.forEach((response: RemoteData<Bundle>) => {
this.displayErrorNotification(key, response.errorMessage);
});
}
/**
* Display an error notification with the provided key and message
* @param key The i18n key for the notification messages
* @param errorMessage The error message to display
*/
displayErrorNotification(key: string, errorMessage: string) {
this.notificationsService.error(this.translateService.instant(`${key}.failed.title`), errorMessage);
}
/**
* Display a success notification in case there's at least one successful response
* @param key The i18n key for the notification messages
* @param responses The returned responses to display notifications for
*/
displaySuccessFulResponseNotifications(key: string, responses: RemoteData<any>[]) {
const successfulResponses = responses.filter((response: RemoteData<Bundle>) => hasValue(response) && response.hasSucceeded);
if (successfulResponses.length > 0) {
this.displaySuccessNotification(key);
}
}
/**
* Display a success notification with the provided key
* @param key The i18n key for the notification messages
*/
displaySuccessNotification(key: string) {
this.notificationsService.success(this.translateService.instant(`${key}.saved.title`), this.translateService.instant(`${key}.saved.content`));
}
/**
* Removes the bitstreams marked for deletion from the Bundles emitted by the provided observable.
* @param bundles$
*/
removeMarkedBitstreams(bundles$: Observable<Bundle[]>): Observable<RemoteData<NoContent>> {
const bundlesOnce$ = bundles$.pipe(take(1));
// Fetch all removed bitstreams from the object update service
const removedBitstreams$ = bundlesOnce$.pipe(
switchMap((bundles: Bundle[]) => observableZip(
...bundles.map((bundle: Bundle) => this.objectUpdatesService.getFieldUpdates(bundle.self, [], true)),
)),
map((fieldUpdates: FieldUpdates[]) => ([] as FieldUpdate[]).concat(
...fieldUpdates.map((updates: FieldUpdates) => Object.values(updates).filter((fieldUpdate: FieldUpdate) => fieldUpdate.changeType === FieldChangeType.REMOVE)),
)),
map((fieldUpdates: FieldUpdate[]) => fieldUpdates.map((fieldUpdate: FieldUpdate) => fieldUpdate.field)),
);
// Send out delete requests for all deleted bitstreams
return removedBitstreams$.pipe(
take(1),
switchMap((removedBitstreams: Bitstream[]) => {
return this.bitstreamService.removeMultiple(removedBitstreams);
}),
);
}
/**
* Creates an array of {@link BitstreamTableEntry}s from an array of {@link Bitstream}s
* @param bitstreams The bitstreams array to map to table entries
*/
mapBitstreamsToTableEntries(bitstreams: Bitstream[]): BitstreamTableEntry[] {
return bitstreams.map((bitstream) => {
const name = this.dsoNameService.getName(bitstream);
return {
bitstream: bitstream,
id: bitstream.uuid,
name: name,
nameStripped: this.nameToHeader(name),
description: bitstream.firstMetadataValue('dc.description'),
format: bitstream.format.pipe(getFirstSucceededRemoteDataPayload()),
downloadUrl: getBitstreamDownloadRoute(bitstream),
};
});
}
/**
* Returns a string appropriate to be used as header ID
* @param name
*/
nameToHeader(name: string): string {
// Whitespace is stripped from the Bitstream names for accessibility reasons.
// To make it clear which headers are relevant for a specific field in the table, the 'headers' attribute is used to
// refer to specific headers. The Bitstream's name is used as header ID for the row containing information regarding
// that bitstream. As the 'headers' attribute contains a space-separated string of header IDs, the Bitstream's header
// ID can not contain spaces itself.
return this.stripWhiteSpace(name);
}
/**
* Returns a string equal to the input string with all whitespace removed.
* @param str
*/
stripWhiteSpace(str: string): string {
// '/\s+/g' matches all occurrences of any amount of whitespace characters
return str.replace(/\s+/g, '');
}
/**
* Adds a message to the live region mentioning that the bitstream with the provided name was selected.
* @param bitstreamName The name of the bitstream that was selected.
*/
announceSelect(bitstreamName: string) {
const message = this.translateService.instant('item.edit.bitstreams.edit.live.select',
{ bitstream: bitstreamName });
this.liveRegionService.addMessage(message);
}
/**
* Adds a message to the live region mentioning that the bitstream with the provided name was moved to the provided
* position.
* @param bitstreamName The name of the bitstream that moved.
* @param toPosition The zero-indexed position that the bitstream moved to.
*/
announceMove(bitstreamName: string, toPosition: number) {
const message = this.translateService.instant('item.edit.bitstreams.edit.live.move',
{ bitstream: bitstreamName, toIndex: toPosition + 1 });
this.liveRegionService.addMessage(message);
}
/**
* Adds a message to the live region mentioning that the bitstream with the provided name is no longer selected and
* was returned to the provided position.
* @param bitstreamName The name of the bitstream that is no longer selected
* @param toPosition The zero-indexed position the bitstream returned to.
*/
announceCancel(bitstreamName: string, toPosition: number) {
const message = this.translateService.instant('item.edit.bitstreams.edit.live.cancel',
{ bitstream: bitstreamName, toIndex: toPosition + 1 });
this.liveRegionService.addMessage(message);
}
/**
* Adds a message to the live region mentioning that the bitstream with the provided name is no longer selected.
* @param bitstreamName The name of the bitstream that is no longer selected.
*/
announceClear(bitstreamName: string) {
const message = this.translateService.instant('item.edit.bitstreams.edit.live.clear',
{ bitstream: bitstreamName });
this.liveRegionService.addMessage(message);
}
/**
* Adds a message to the live region mentioning that the
*/
announceLoading() {
const message = this.translateService.instant('item.edit.bitstreams.edit.live.loading');
this.liveRegionService.addMessage(message);
}
}