forked from DSpace/dspace-angular
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmetadata.service.ts
More file actions
568 lines (496 loc) · 19.1 KB
/
Copy pathmetadata.service.ts
File metadata and controls
568 lines (496 loc) · 19.1 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
import { Injectable, Inject } from '@angular/core';
import { Meta, MetaDefinition, Title } from '@angular/platform-browser';
import { ActivatedRoute, NavigationEnd, Router } from '@angular/router';
import { TranslateService } from '@ngx-translate/core';
import {
BehaviorSubject,
combineLatest,
Observable,
of as observableOf,
concat as observableConcat,
EMPTY
} from 'rxjs';
import { filter, map, switchMap, take, mergeMap } from 'rxjs/operators';
import { hasNoValue, hasValue, isNotEmpty } from '../../shared/empty.util';
import { DSONameService } from '../breadcrumbs/dso-name.service';
import { BitstreamDataService } from '../data/bitstream-data.service';
import { BitstreamFormatDataService } from '../data/bitstream-format-data.service';
import { RemoteData } from '../data/remote-data';
import { BitstreamFormat } from '../shared/bitstream-format.model';
import { Bitstream } from '../shared/bitstream.model';
import { DSpaceObject } from '../shared/dspace-object.model';
import { Item } from '../shared/item.model';
import {
getFirstCompletedRemoteData,
getFirstSucceededRemoteDataPayload
} from '../shared/operators';
import { RootDataService } from '../data/root-data.service';
import { getBitstreamDownloadRoute } from '../../app-routing-paths';
import { BundleDataService } from '../data/bundle-data.service';
import { followLink } from '../../shared/utils/follow-link-config.model';
import { Bundle } from '../shared/bundle.model';
import { PaginatedList } from '../data/paginated-list.model';
import { URLCombiner } from '../url-combiner/url-combiner';
import { HardRedirectService } from '../services/hard-redirect.service';
import { MetaTagState } from './meta-tag.reducer';
import { createSelector, select, Store } from '@ngrx/store';
import { AddMetaTagAction, ClearMetaTagAction } from './meta-tag.actions';
import { coreSelector } from '../core.selectors';
import { CoreState } from '../core-state.model';
import { AuthorizationDataService } from '../data/feature-authorization/authorization-data.service';
import { getDownloadableBitstream } from '../shared/bitstream.operators';
import { APP_CONFIG, AppConfig } from '../../../config/app-config.interface';
import { FindListOptions } from '../data/find-list-options.model';
/**
* The base selector function to select the metaTag section in the store
*/
const metaTagSelector = createSelector(
coreSelector,
(state: CoreState) => state.metaTag
);
/**
* Selector function to select the tags in use from the MetaTagState
*/
const tagsInUseSelector =
createSelector(
metaTagSelector,
(state: MetaTagState) => state.tagsInUse,
);
@Injectable()
export class MetadataService {
private currentObject: BehaviorSubject<DSpaceObject> = new BehaviorSubject<DSpaceObject>(undefined);
/**
* When generating the citation_pdf_url meta tag for Items with more than one Bitstream (and no primary Bitstream),
* the first Bitstream to match one of the following MIME types is selected.
* See {@linkcode getFirstAllowedFormatBitstreamLink}
* @private
*/
private readonly CITATION_PDF_URL_MIMETYPES = [
'application/pdf', // .pdf
'application/postscript', // .ps
'application/msword', // .doc
'application/vnd.openxmlformats-officedocument.wordprocessingml.document', // .docx
'application/rtf', // .rtf
'application/epub+zip', // .epub
];
constructor(
private router: Router,
private translate: TranslateService,
private meta: Meta,
private title: Title,
private dsoNameService: DSONameService,
private bundleDataService: BundleDataService,
private bitstreamDataService: BitstreamDataService,
private bitstreamFormatDataService: BitstreamFormatDataService,
private rootService: RootDataService,
private store: Store<CoreState>,
private hardRedirectService: HardRedirectService,
@Inject(APP_CONFIG) private appConfig: AppConfig,
private authorizationService: AuthorizationDataService
) {
}
public listenForRouteChange(): void {
// This never changes, set it only once
this.setGenerator();
this.router.events.pipe(
filter((event) => event instanceof NavigationEnd),
map(() => this.router.routerState.root),
map((route: ActivatedRoute) => {
route = this.getCurrentRoute(route);
return { params: route.params, data: route.data };
})).subscribe((routeInfo: any) => {
this.processRouteChange(routeInfo);
});
}
private processRouteChange(routeInfo: any): void {
this.clearMetaTags();
if (hasValue(routeInfo.data.value.dso) && hasValue(routeInfo.data.value.dso.payload)) {
this.currentObject.next(routeInfo.data.value.dso.payload);
this.setDSOMetaTags();
}
if (routeInfo.data.value.title) {
const titlePrefix = this.translate.get('repository.title.prefix');
const title = this.translate.get(routeInfo.data.value.title, routeInfo.data.value);
combineLatest([titlePrefix, title]).pipe(take(1)).subscribe(([translatedTitlePrefix, translatedTitle]: [string, string]) => {
this.addMetaTag('title', translatedTitlePrefix + translatedTitle);
this.title.setTitle(translatedTitlePrefix + ' - ' + translatedTitle);
});
}
if (routeInfo.data.value.description) {
this.translate.get(routeInfo.data.value.description).pipe(take(1)).subscribe((translatedDescription: string) => {
this.addMetaTag('description', translatedDescription);
});
}
}
private getCurrentRoute(route: ActivatedRoute): ActivatedRoute {
while (route.firstChild) {
route = route.firstChild;
}
return route;
}
private setDSOMetaTags(): void {
this.setTitleTag();
this.setDescriptionTag();
this.setCitationTitleTag();
this.setCitationAuthorTags();
this.setCitationPublicationDateTag();
this.setCitationISSNTag();
this.setCitationISBNTag();
this.setCitationLanguageTag();
this.setCitationKeywordsTag();
this.setCitationAbstractUrlTag();
this.setCitationDoiTag();
this.setCitationPdfUrlTag();
this.setCitationPublisherTag();
if (this.isDissertation()) {
this.setCitationDissertationNameTag();
}
// added to be equivalent to clarin
this.setCitationDateTag();
this.setDatasetKeywordsTag();
this.setDatasetLicenseTag();
this.setDatasetUrlTag();
this.setDatasetCitationTag();
this.setDatasetIdentifierTag();
this.setDatasetCreatorTag();
//
// this.setCitationJournalTitleTag();
// this.setCitationVolumeTag();
// this.setCitationIssueTag();
// this.setCitationFirstPageTag();
// this.setCitationLastPageTag();
// this.setCitationPMIDTag();
// this.setCitationFullTextTag();
// this.setCitationConferenceTag();
// this.setCitationPatentCountryTag();
// this.setCitationPatentNumberTag();
}
/**
* Add <meta name="title" ... > to the <head>
*/
private setTitleTag(): void {
const value = this.dsoNameService.getName(this.currentObject.getValue());
this.addMetaTag('title', value);
this.title.setTitle(value);
}
/**
* Add <meta name="description" ... > to the <head>
*/
private setDescriptionTag(): void {
// TODO: truncate abstract
const value = this.getMetaTagValue('dc.description.abstract');
this.addMetaTag('description', value);
}
/**
* Add <meta name="citation_title" ... > to the <head>
*/
private setCitationTitleTag(): void {
const value = this.getMetaTagValue('dc.title');
this.addMetaTag('citation_title', value);
}
/**
* Add <meta name="citation_author" ... > to the <head>
*/
private setCitationAuthorTags(): void {
const values: string = this.getFirstMetaTagValue(['dc.author', 'dc.contributor.author', 'dc.creator']);
this.addMetaTag('citation_author', values);
}
/**
* Add <meta name="citation_publication_date" ... > to the <head>
*/
private setCitationPublicationDateTag(): void {
const value = this.getFirstMetaTagValue(['dc.date.copyright', 'dc.date.issued', 'dc.date.available', 'dc.date.accessioned']);
this.addMetaTag('citation_publication_date', value);
}
/**
* Add <meta name="citation_issn" ... > to the <head>
*/
private setCitationISSNTag(): void {
const value = this.getMetaTagValue('dc.identifier.issn');
this.addMetaTag('citation_issn', value);
}
/**
* Add <meta name="citation_isbn" ... > to the <head>
*/
private setCitationISBNTag(): void {
const value = this.getMetaTagValue('dc.identifier.isbn');
this.addMetaTag('citation_isbn', value);
}
/**
* Add <meta name="citation_language" ... > to the <head>
*/
private setCitationLanguageTag(): void {
const value = this.getFirstMetaTagValue(['dc.language.iso', 'dc.language']);
this.addMetaTag('citation_language', value);
}
/**
* Add <meta name="citation_dissertation_name" ... > to the <head>
*/
private setCitationDissertationNameTag(): void {
if (this.isDissertation()) {
const value = this.getMetaTagValue('dc.title');
this.addMetaTag('citation_dissertation_name', value);
}
}
/**
* Add dc.publisher to the <head>. The tag name depends on the item type.
*/
private setCitationPublisherTag(): void {
const value = this.getMetaTagValue('dc.publisher');
if (this.isDissertation()) {
this.addMetaTag('citation_dissertation_institution', value);
} else if (this.isTechReport()) {
this.addMetaTag('citation_technical_report_institution', value);
} else {
this.addMetaTag('citation_publisher', value);
}
}
/**
* Add <meta name="citation_keywords" ... > to the <head>
*/
private setCitationKeywordsTag(): void {
const value = this.getMetaTagValues(['dc.subject', 'dc.type']).join('; ');
this.addMetaTag('citation_keywords', value);
}
/**
* Add <meta name="citation_abstract_html_url" ... > to the <head>
*/
private setCitationAbstractUrlTag(): void {
if (this.currentObject.value instanceof Item) {
let url = this.getMetaTagValue('dc.identifier.uri');
if (hasNoValue(url)) {
url = new URLCombiner(this.hardRedirectService.getCurrentOrigin(), this.router.url).toString();
}
this.addMetaTag('citation_abstract_html_url', url);
}
}
private setCitationDateTag(): void {
const value = this.getMetaTagValue('dc.date.issued');
this.addMetaTag('citation_date', value);
}
private setDatasetKeywordsTag(): void {
const value = this.getMetaTagValue('dc.subject');
this.addMetaTag('dataset_keywords', value);
}
private setDatasetLicenseTag(): void {
const value = this.getMetaTagValue('dc.rights.uri');
this.addMetaTag('dataset_license', value);
}
private setDatasetUrlTag(): void {
const value = this.getMetaTagValue('dc.identifier.uri');
this.addMetaTag('dataset_url', value);
}
private setDatasetCitationTag(): void {
const value = this.getMetaTagValue('dc.relation.isreferencedby');
this.addMetaTag('dataset_citation', value);
}
private setDatasetIdentifierTag(): void {
const value = this.getMetaTagValue('dc.identifier.uri');
this.addMetaTag('dataset_identifier', value);
}
private setDatasetCreatorTag(): void {
const value = this.getMetaTagValue('dc.contributor.author');
this.addMetaTag('dataset_creator', value);
}
/**
* Add <meta name="citation_doi" ... > to the <head>
*/
private setCitationDoiTag(): void {
if (this.currentObject.value instanceof Item) {
let doi = this.getMetaTagValue('dc.identifier.doi');
if (hasValue(doi)) {
this.addMetaTag('citation_doi', doi);
}
}
}
/**
* Add <meta name="citation_pdf_url" ... > to the <head>
*/
private setCitationPdfUrlTag(): void {
if (this.currentObject.value instanceof Item) {
const item = this.currentObject.value as Item;
// Retrieve the ORIGINAL bundle for the item
this.bundleDataService.findByItemAndName(
item,
'ORIGINAL',
true,
true,
new FindListOptions(),
followLink('primaryBitstream'),
followLink('bitstreams', {
findListOptions: {
// limit the number of bitstreams used to find the citation pdf url to the number
// shown by default on an item page
elementsPerPage: this.appConfig.item.bitstream.pageSize
}
}, followLink('format')),
).pipe(
getFirstSucceededRemoteDataPayload(),
switchMap((bundle: Bundle) =>
// First try the primary bitstream
bundle.primaryBitstream.pipe(
getFirstCompletedRemoteData(),
map((rd: RemoteData<Bitstream>) => {
if (hasValue(rd.payload)) {
return rd.payload;
} else {
return null;
}
}),
getDownloadableBitstream(this.authorizationService),
// return the bundle as well so we can use it again if there's no primary bitstream
map((bitstream: Bitstream) => [bundle, bitstream])
)
),
switchMap(([bundle, primaryBitstream]: [Bundle, Bitstream]) => {
if (hasValue(primaryBitstream)) {
// If there was a downloadable primary bitstream, emit its link
return [getBitstreamDownloadRoute(primaryBitstream)];
} else {
// Otherwise consider the regular bitstreams in the bundle
return bundle.bitstreams.pipe(
getFirstCompletedRemoteData(),
switchMap((bitstreamRd: RemoteData<PaginatedList<Bitstream>>) => {
if (hasValue(bitstreamRd.payload) && bitstreamRd.payload.totalElements === 1) {
// If there's only one bitstream in the bundle, emit its link if its downloadable
return this.getBitLinkIfDownloadable(bitstreamRd.payload.page[0], bitstreamRd);
} else {
// Otherwise check all bitstreams to see if one matches the format whitelist
return this.getFirstAllowedFormatBitstreamLink(bitstreamRd);
}
})
);
}
}),
take(1)
).subscribe((link: string) => {
// Use the found link to set the <meta> tag
this.addMetaTag(
'citation_pdf_url',
new URLCombiner(this.hardRedirectService.getCurrentOrigin(), link).toString()
);
});
}
}
getBitLinkIfDownloadable(bitstream: Bitstream, bitstreamRd: RemoteData<PaginatedList<Bitstream>>): Observable<string> {
return observableOf(bitstream).pipe(
getDownloadableBitstream(this.authorizationService),
switchMap((bit: Bitstream) => {
if (hasValue(bit)) {
return [getBitstreamDownloadRoute(bit)];
} else {
// Otherwise check all bitstreams to see if one matches the format whitelist
return this.getFirstAllowedFormatBitstreamLink(bitstreamRd);
}
})
);
}
/**
* For Items with more than one Bitstream (and no primary Bitstream), link to the first Bitstream
* with a MIME type.
*
* Note this will only check the current page (page size determined item.bitstream.pageSize in the
* config) of bitstreams for performance reasons.
* See https://github.com/DSpace/DSpace/issues/8648 for more info
*
* included in {@linkcode CITATION_PDF_URL_MIMETYPES}
* @param bitstreamRd
* @private
*/
private getFirstAllowedFormatBitstreamLink(bitstreamRd: RemoteData<PaginatedList<Bitstream>>): Observable<string> {
if (hasValue(bitstreamRd.payload) && isNotEmpty(bitstreamRd.payload.page)) {
// Retrieve the formats of all bitstreams in the page sequentially
return observableConcat(
...bitstreamRd.payload.page.map((bitstream: Bitstream) => bitstream.format.pipe(
getFirstSucceededRemoteDataPayload(),
// Keep the original bitstream, because it, not the format, is what we'll need
// for the link at the end
map((format: BitstreamFormat) => [bitstream, format])
))
).pipe(
// Verify that the bitstream is downloadable
mergeMap(([bitstream, format]: [Bitstream, BitstreamFormat]) => observableOf(bitstream).pipe(
getDownloadableBitstream(this.authorizationService),
map((bit: Bitstream) => [bit, format])
)),
// Filter out only pairs with whitelisted formats and non-null bitstreams, null from download check
filter(([bitstream, format]: [Bitstream, BitstreamFormat]) =>
hasValue(format) && hasValue(bitstream) && this.CITATION_PDF_URL_MIMETYPES.includes(format.mimetype)),
// We only need 1
take(1),
// Emit the link of the match
// tap((v) => console.log('result', v)),
map(([bitstream, ]: [Bitstream, BitstreamFormat]) => getBitstreamDownloadRoute(bitstream))
);
} else {
return EMPTY;
}
}
/**
* Add <meta name="Generator" ... > to the <head> containing the current DSpace version
*/
private setGenerator(): void {
this.rootService.findRoot().pipe(getFirstSucceededRemoteDataPayload()).subscribe((root) => {
this.meta.addTag({ name: 'Generator', content: root.dspaceVersion });
});
}
private hasType(value: string): boolean {
return this.currentObject.value.hasMetadata('dc.type', { value: value, ignoreCase: true });
}
/**
* Returns true if this._item is a dissertation
*
* @returns {boolean}
* true if this._item has a dc.type equal to 'Thesis'
*/
private isDissertation(): boolean {
return this.hasType('thesis');
}
/**
* Returns true if this._item is a technical report
*
* @returns {boolean}
* true if this._item has a dc.type equal to 'Technical Report'
*/
private isTechReport(): boolean {
return this.hasType('technical report');
}
private getMetaTagValue(key: string): string {
return this.currentObject.value.firstMetadataValue(key);
}
private getFirstMetaTagValue(keys: string[]): string {
return this.currentObject.value.firstMetadataValue(keys);
}
private getMetaTagValuesAndCombine(key: string): string {
return this.getMetaTagValues([key]).join('; ');
}
private getMetaTagValues(keys: string[]): string[] {
return this.currentObject.value.allMetadataValues(keys);
}
private addMetaTag(name: string, content: string): void {
if (content) {
const tag = { name, content } as MetaDefinition;
this.meta.addTag(tag);
this.storeTag(name);
}
}
private addMetaTags(name: string, content: string[]): void {
for (const value of content) {
this.addMetaTag(name, value);
}
}
private storeTag(key: string): void {
this.store.dispatch(new AddMetaTagAction(key));
}
public clearMetaTags() {
this.store.pipe(
select(tagsInUseSelector),
take(1)
).subscribe((tagsInUse: string[]) => {
for (const name of tagsInUse) {
this.meta.removeTag('name=\'' + name + '\'');
}
this.store.dispatch(new ClearMetaTagAction());
});
}
}