Project

General

Profile

1
import {Injectable} from '@angular/core';
2
import {HttpClient, HttpErrorResponse} from "@angular/common/http";
3
import {throwError} from 'rxjs';
4
import {ResultLandingInfo} from '../../utils/entities/resultLandingInfo';
5
import {EnvProperties} from '../../utils/properties/env-properties';
6
import {ParsingFunctions} from '../landing-utils/parsingFunctions.class';
7
import {map} from "rxjs/operators";
8
import {HostedByCollectedFrom, Organization} from "../../utils/result-preview/result-preview";
9
import {Dates, Identifier} from "../../utils/string-utils.class";
10
import {properties} from "../../../../environments/environment";
11

    
12
@Injectable()
13
export class ResultLandingService {
14

    
15
  constructor(private http: HttpClient ) {
16
    this.parsingFunctions = new ParsingFunctions();
17
  }
18

    
19
  public parsingFunctions: ParsingFunctions;
20
  resultLandingInfo: ResultLandingInfo;
21

    
22
  private buildResultLandingInfoUrl(id: string, identifier: Identifier, type: string): string {
23
    if (id) {
24
      let url = properties.searchAPIURLLAst;
25
      if (type === 'publication') {
26
        url += 'publications/';
27
      } else if (type === 'dataset') {
28
        url += 'datasets/';
29
      } else if (type === 'software') {
30
        url += 'software/';
31
      } else if (type === 'orp' || type === 'other') {
32
        url += 'other/';
33
      } else if (type === 'result') {
34
        url += 'results/';
35
      }
36
      url += id + '?format=json';
37
      return url;
38
    } else if (identifier) {
39
      // pid = "10.3389/fphys.2014.00466";
40
      let url = properties.searchAPIURLLAst + "resources2";
41
      url += "?pid="+encodeURIComponent(identifier.id) + "&pidtype=" + identifier.class + "&type=";
42
      if (type === 'publication') {
43
        url += 'publications';
44
      } else if (type === 'dataset') {
45
        url += 'datasets';
46
      } else if (type === 'software') {
47
        url += 'software';
48
      } else if (type === 'orp') {
49
        url += 'other';
50
      } else if (type === 'result') {
51
        url += 'results';
52
      }
53
      url += "&format=json";
54
      return url;
55
    }
56
  }
57

    
58
  getResultLandingInfo (id: string, identifier: Identifier, type: string, provenanceActionVocabulary: any, properties: EnvProperties): any {
59
    let url: string = this.buildResultLandingInfoUrl(id, identifier, type);
60

    
61
    let finalUrl: string = (properties.useCache) ? (properties.cacheUrl + encodeURIComponent(url)) : url;
62
    return this.http.get(finalUrl)
63
      .pipe(map(res => {
64
        if(!id && identifier) {
65
          if(!res['results'] || res['results'].length == 0) {
66
            throw new HttpErrorResponse({
67
              status: 404,
68
              statusText: "Not found",
69
              url: finalUrl,
70
              error: "Http failure response for "+finalUrl+": 404 Not Found"
71
            });
72
          }
73
          return res['results'][0];
74
        } else {
75
          return res;
76
        }
77
      }))
78
      .pipe(map(res => [res['result']['header']['dri:status'], res['result']['metadata']['oaf:entity'], res]))
79
      .pipe(map(res => [
80
        res[1]['oaf:result'],                 // 0
81
        res[1]['oaf:result']['title'],        // 1
82
        res[1]['oaf:result']['rels']['rel'],  // 2
83
        res[1]['oaf:result']['children'],     // 3
84
        res[1]['oaf:result']['pid'],          // 4
85
        res[1]['oaf:result']['journal'],      // 5
86
        res[1]['oaf:result']['language'],     // 6
87
        res[1]['oaf:result']['subject'],      // 7
88
        res[1]['oaf:result']['context'],      // 8
89
        res[1]['oaf:result']['creator'],      // 9
90
        res[1]['oaf:result']['country'] ,     // 10
91
        res[1]['oaf:result']['programmingLanguage'],              // 11 - software
92
        //res[1]['oaf:result']['resulttype'],
93
        (res[1]['extraInfo'] !== undefined && res[1]['extraInfo']['citations'] !== undefined)
94
          ? res[1]['extraInfo']['citations']['citation'] : null,  // 12
95
        res[0],                               // 13
96
        res[2]                                // 14
97
      ]))
98
      .pipe(map(res => this.parseResultLandingInfo(res, provenanceActionVocabulary, properties)));
99
  }
100

    
101
  // getProvenanceActionVocabulary (properties: EnvProperties): any {
102
  //   let url = properties.vocabulariesAPI+"dnet:provenanceActions.json";
103
  //
104
  //   return this.http.get((properties.useCache) ? (properties.cacheUrl + encodeURIComponent(url)) : url)
105
  //     .pipe(map(res => res['terms']))
106
  //     .pipe(map(res => this.parseProvenanceActionVocabulary(res, properties)));
107
  // }
108
  //
109
  // parseProvenanceActionVocabulary(terms: any, properties: EnvProperties) {
110
  //   var provenanceActionVocabulary: {} = {};
111
  //   for(let term of terms) {
112
  //     provenanceActionVocabulary[term.code] = term.englishName;
113
  //   }
114
  //   return provenanceActionVocabulary;
115
  // }
116

    
117
  private handleError (error: HttpErrorResponse) {
118
    // in a real world app, we may send the error to some remote logging infrastructure
119
    // instead of just logging it to the console
120
    console.log(error);
121
    return throwError(error  || 'Server error');
122
  }
123

    
124
  parseResultLandingInfo (data: any, provenanceActionVocabulary: any, properties: EnvProperties): any {
125
    this.resultLandingInfo = new ResultLandingInfo();
126

    
127
    // res
128
    this.resultLandingInfo.record = data[14];
129
    this.resultLandingInfo.objIdentifier = data[14]["result"]["header"]["dri:objIdentifier"];
130
    this.resultLandingInfo.relcanId = ParsingFunctions.parseRelCanonicalId(this.resultLandingInfo.record, "result");
131
    this.resultLandingInfo.resultType = data[0].resulttype.classid;
132

    
133
    // res['result']['metadata']['oaf:entity']['oaf:result']
134
    if (data[0] != null) {
135
      let date: string = (data[0].dateofacceptance ? data[0].dateofacceptance : '') + ''; // transform to string in case it is an integer
136
      this.resultLandingInfo.date  = (date && (date).indexOf('-') !== -1) ? date.split('-')[0] : date;
137
      this.resultLandingInfo.dateofacceptance = data[0].dateofacceptance?Dates.getDate(data[0].dateofacceptance):null;
138
      this.resultLandingInfo.publisher = data[0].publisher;
139
      if(!Array.isArray(data[0].description)) {
140
        //this.resultLandingInfo.description = String(data[0].description);
141
        this.resultLandingInfo.description = (data[0] && data[0].description) ? String(data[0].description) : "";
142
      } else {
143
        //this.resultLandingInfo.description = String(data[0].description[0]);
144
        this.resultLandingInfo.description = (data[0] && data[0].description[0]) ? String(data[0].description[0]) : "";
145
      }
146
      this.resultLandingInfo.embargoEndDate = data[0].embargoenddate?Dates.getDate(data[0].embargoenddate):null;
147
    }
148

    
149
    if(data[0]['bestaccessright'] && data[0]['bestaccessright'].hasOwnProperty("classname")) {
150
      this.resultLandingInfo.accessMode = data[0]['bestaccessright'].classname;
151
    }
152
    // res['result']['metadata']['oaf:entity']['oaf:result']['title']
153
    if(data[1] != null) {
154
      if(Array.isArray(data[1])) {
155
        for(let i=0; i<data[1].length; i++) {
156
          if(data[1][i] && data[1][i].content) {
157
            if(!this.resultLandingInfo.title || data[1][i].classid == "main title") {
158
              this.resultLandingInfo.title = String(data[1][i].content);
159
            }
160
            if(data[1][i].classid == "main title") {
161
              break;
162
            }
163
          }
164
        }
165
        if(!this.resultLandingInfo.title) {
166
          this.resultLandingInfo.title = "";
167
        }
168
        // this.resultLandingInfo.title = (data[1][0] && data[1][0].content) ? String(data[1][0].content) : "";
169
        if(data[1][1].classid === 'subtitle') {
170
          this.resultLandingInfo.subtitle = (data[1][1] && data[1][1].content) ? String(data[1][1].content) : "";
171
        }
172
      } else {
173
        this.resultLandingInfo.title = (data[1] && data[1].content) ? String(data[1].content) : "";
174
      }
175
    }
176

    
177
    // res['result']['metadata']['oaf:entity']['oaf:result']['rels']['rel']
178
    if(data[2] != null) {
179
      let relation;
180
      let length = Array.isArray(data[2]) ? data[2].length : 1;
181

    
182
      for(let i=0; i<length; i++) {
183
        relation = Array.isArray(data[2]) ? data[2][i] : data[2];
184
        if(relation.hasOwnProperty("to")) {
185
          if(relation['to'].class == "isProducedBy") {
186
            this.resultLandingInfo.fundedByProjects = this.parsingFunctions.parseFundingByProjects(this.resultLandingInfo.fundedByProjects, relation, provenanceActionVocabulary);
187
          } else if(relation['to'].class == "isRelatedTo") {
188
            let provenanceAction: string = "";
189
            if(provenanceActionVocabulary != null && relation.provenanceaction in provenanceActionVocabulary) {
190
              provenanceAction = provenanceActionVocabulary[relation.provenanceaction];
191
            }
192

    
193
            this.resultLandingInfo.relatedResearchResults = this.parsingFunctions.parseRelatedResearchResults(this.resultLandingInfo.relatedResearchResults, relation, provenanceAction);
194
          } else if(relation['to'].class == "hasAmongTopNSimilarDocuments") {
195
            this.resultLandingInfo.similarResearchResults = this.parsingFunctions.parseSimilarResearchResults(this.resultLandingInfo.similarResearchResults, relation);
196
          } else if(relation['to'].class == "hasAuthorInstitution") {
197
            this.resultLandingInfo.organizations = this.parseRelatedOrganizations(this.resultLandingInfo.organizations, relation);
198
          } else if(relation['to'].class == "isSupplementedBy") {
199
            this.resultLandingInfo.supplementaryResearchResults = this.parsingFunctions.parseSupplementaryResearchResults(this.resultLandingInfo.supplementaryResearchResults, relation);
200
          } else if(relation['to'].class == "isSupplementTo") {
201
            this.resultLandingInfo.supplementedByResearchResults = this.parsingFunctions.parseSupplementedByResearchResults(this.resultLandingInfo.supplementedByResearchResults, relation);
202
          }
203
        }
204
      }
205
    }
206

    
207
    // res['result']['metadata']['oaf:entity']['oaf:result']['children']
208
    if(data[3] != null) {
209
      if(data[3].hasOwnProperty("result")) {
210
        this.resultLandingInfo.deletedByInferenceIds = [];
211
        let length = Array.isArray(data[3]['result']) ? data[3]['result'].length : 1;
212

    
213
        for(let i=0; i<length; i++) {
214
          let result = Array.isArray(data[3]['result']) ? data[3]['result'][i] : data[3]['result'];
215
          this.resultLandingInfo.deletedByInferenceIds.push(result.objidentifier);
216
        }
217

    
218
      }
219

    
220
      if(data[3].hasOwnProperty("instance")) {
221
        this.resultLandingInfo.hostedBy_collectedFrom = new Array<HostedByCollectedFrom>();
222

    
223

    
224
        this.resultLandingInfo.types = new Array<string>();
225
        let types = new Set<string>();
226

    
227
        let counter = 0;
228
        let instance;
229

    
230
        let length = Array.isArray(data[3]['instance']) ? data[3]['instance'].length : 1;
231

    
232
        for(let i=0; i<length; i++) {
233
          instance = Array.isArray(data[3]['instance']) ? data[3]['instance'][i] : data[3]['instance'];
234

    
235
          this.parsingFunctions.parseTypes(this.resultLandingInfo.types, types, instance);
236

    
237
          if(instance.hasOwnProperty("webresource")) {
238
            let url;
239
            if(!Array.isArray(instance['webresource'])) {
240
              url = instance['webresource'].url;
241
            } else{
242
              url = instance['webresource'][0].url;
243
            }
244

    
245
            /**********************************************************/
246
            if(instance.hasOwnProperty("hostedby")) {
247
              counter = this.parsingFunctions.parseHostedBy_collectedFrom(this.resultLandingInfo.hostedBy_collectedFrom, instance, data[0], url, counter/*, this.resultLandingInfo.title*/, this.resultLandingInfo.accessMode);
248
            }
249
            /**********************************************************/
250
          }
251
        }
252
        /* Order Download from via openness*/
253
        this.resultLandingInfo.hostedBy_collectedFrom.sort((a, b) => {
254
          if(a.bestAccessMode && a.bestAccessMode.toLowerCase() === 'open access') {
255
            return -1;
256
          } else if(b.bestAccessMode && b.bestAccessMode.toLowerCase() === 'open access') {
257
            return 1;
258
          } else if(!a.bestAccessMode || a.bestAccessMode.toLowerCase() !== 'not available') {
259
            return 1;
260
          } else if(!b.bestAccessMode || b.bestAccessMode.toLowerCase() !== 'not available') {
261
            return -1;
262
          } else {
263
            return 0;
264
          }
265
        });
266
      }
267

    
268
      if(data[3].hasOwnProperty("externalreference")) {
269
        let externalResults: Map<string, Map<string, string>> = this.parseBioentitiesAndSoftware(data[3]);
270
        this.resultLandingInfo.bioentities = externalResults;
271
      }
272
    }
273

    
274
    // res['result']['metadata']['oaf:entity']['oaf:result']['pid']
275
    if(data[4] != null) {
276
      this.resultLandingInfo.identifiers = this.parsingFunctions.parseIdentifiers(data[4]);
277
    }
278

    
279
    // res['result']['metadata']['oaf:entity']['oaf:result']['journal']
280
    if(data[5] != null) {
281
      this.resultLandingInfo.journal = {"journal": "", "issn": "", "lissn": "", "eissn": "", "issue": "", "volume": "", "start_page": "", "end_page": ""}
282

    
283
      this.resultLandingInfo.journal['journal'] = data[5].content;
284
      this.resultLandingInfo.journal['issn'] = data[5].issn;
285
      this.resultLandingInfo.journal['lissn'] = data[5].lissn;
286
      this.resultLandingInfo.journal['eissn'] = data[5].eissn;
287
      this.resultLandingInfo.journal['issue'] = data[5].iss;
288
      this.resultLandingInfo.journal['volume'] = data[5].vol;
289
      this.resultLandingInfo.journal['start_page'] = data[5].sp;
290
      this.resultLandingInfo.journal['end_page'] = data[5].ep;
291
    }
292

    
293
    // res['result']['metadata']['oaf:entity']['oaf:result']['language']
294
    if(data[6] != null) {
295
      this.resultLandingInfo.languages = this.parsingFunctions.parseLanguages(data[6]);
296
      // let languagesAndCodes: string[][] = this.parsingFunctions.parseLanguages(data[6]);
297
      // this.resultLandingInfo.languages = languagesAndCodes[0];
298
      // this.resultLandingInfo.languageCodes = languagesAndCodes[1];
299
    }
300

    
301
    // res['result']['metadata']['oaf:entity']['oaf:result']['country']
302
    if(data[10] != null) {
303
      this.resultLandingInfo.countries = this.parsingFunctions.parseCountries(data[10]);
304
    }
305

    
306
    // res['result']['metadata']['oaf:entity']['oaf:result']['subject']
307
    if(data[7] != null) {
308
      let subjectResults: [string[], Map<string, string[]>, Map<string, string[]>] = this.parsingFunctions.parseAllSubjects(data[7]);
309
      this.resultLandingInfo.subjects = subjectResults[0];
310
      this.resultLandingInfo.otherSubjects = subjectResults[1];
311
      this.resultLandingInfo.classifiedSubjects = subjectResults[2];
312
    }
313

    
314
    this.resultLandingInfo.hostedBy_collectedFrom = this.parsingFunctions.addPublisherToHostedBy_collectedFrom(
315
      this.resultLandingInfo.hostedBy_collectedFrom, this.resultLandingInfo.publisher,
316
      this.resultLandingInfo.journal, this.resultLandingInfo.identifiers);
317

    
318
    // res['result']['metadata']['oaf:entity']['oaf:result']['programmingLanguage']
319
    if(data[11] != null) {
320
      this.resultLandingInfo.programmingLanguages = this.parsingFunctions.parseProgrammingLanguages(data[11]);
321
    }
322

    
323
    // res['result']['metadata']['oaf:entity']['extraInfo']['citations']['citation']
324
    if(data[12] != null) {
325
      this.resultLandingInfo.references = this.parsingFunctions.parseReferences(data[12]);
326
    }
327

    
328
    // res['result']['metadata']['oaf:entity']['oaf:result']['context']
329
    if(data[8] != null) {
330
      this.resultLandingInfo.contexts = this.parsingFunctions.parseContexts(data[8]);
331
    }
332

    
333
    // res['result']['header']['dri:status']
334
    if(data[13] != null && data[13] == "under curation") {
335
      this.resultLandingInfo.underCurationMessage = true;
336
    } else {
337
      this.resultLandingInfo.underCurationMessage = false;
338
    }
339

    
340
    // res['result']['metadata']['oaf:entity']['oaf:result']['creator']
341
    if(data[9] != null) {
342
      if(this.resultLandingInfo.authors == undefined) {
343
        this.resultLandingInfo.authors = new Array<{"fullName": string, "orcid": string, "orcid_pending": string}>();
344
      }
345

    
346
      let authors = data[9];
347
      let length = Array.isArray(authors) ? authors.length : 1;
348

    
349
      for(let i=0; i<length; i++) {
350
        let author = Array.isArray(authors) ? authors[i] : authors;
351
        if(author) {
352
          if(author.orcid) {
353
            author.orcid = author.orcid.toUpperCase();
354
          }
355
          if(author.orcid_pending) {
356
            author.orcid_pending = author.orcid_pending.toUpperCase();
357
          }
358
          this.resultLandingInfo['authors'][author.rank] = {"fullName": author.content, "orcid": author.orcid, "orcid_pending": author.orcid_pending};
359
        }
360
      }
361
      this.resultLandingInfo.authors = this.resultLandingInfo.authors.filter(function (item) {
362
        return (item != undefined && item.fullName != undefined);
363
      });
364
    }
365
    this.resultLandingInfo.relatedResearchResults = this.parsingFunctions.sortByPercentage(this.resultLandingInfo.relatedResearchResults);
366
    this.resultLandingInfo.similarResearchResults = this.parsingFunctions.sortByPercentage(this.resultLandingInfo.similarResearchResults);
367
    this.resultLandingInfo.supplementaryResearchResults = this.parsingFunctions.sortByPercentage(this.resultLandingInfo.supplementaryResearchResults);
368
    this.resultLandingInfo.supplementedByResearchResults = this.parsingFunctions.sortByPercentage(this.resultLandingInfo.supplementedByResearchResults);
369

    
370
    return this.resultLandingInfo;
371
  }
372

    
373
  parseRelatedOrganizations(organizations: Organization[], relation: any): Organization[] {
374
    if(organizations == undefined) {
375
      organizations = []
376
    }
377

    
378
    let organization: { "name": string, "shortname": string,
379
      "id": string, "websiteUrl": string,
380
      "country": string, "trust": number
381
    } = {
382
      name: "", shortname: "",
383
      id: "", websiteUrl: "",
384
      country: "", trust: null
385
    };
386

    
387
    organization.id = relation['to'].content;
388
    organization.name = relation.legalname;
389
    organization.shortname = relation.legalshortname;
390
    organization.websiteUrl = relation.websiteurl;
391
    if(relation.country) {
392
      organization.country = relation.country.classname;
393
    }
394
    if(relation.trust) {
395
      organization.trust = Math.round(relation.trust*100);
396
    }
397

    
398
    organizations.push(organization);
399
    return organizations;
400
  }
401

    
402
  parseBioentitiesAndSoftware(children: any) : Map<string, Map<string, string>> {
403
    let bioentities: Map<string, Map<string, string>>;
404

    
405
    let length = Array.isArray(children['externalreference']) ? children['externalreference'].length : 1;
406

    
407
    let externalreference;
408
    for(let i=0; i<length; i++) {
409
      externalreference = Array.isArray(children['externalreference']) ? children['externalreference'][i] : children['externalreference'];
410

    
411
      if(externalreference.hasOwnProperty("qualifier")) {
412
        if(externalreference['qualifier'].classid == "accessionNumber") {
413

    
414
          if(bioentities == undefined) {
415
            bioentities = new Map<string, Map<string, string>>();
416
          }
417

    
418
          if(!bioentities.has(externalreference.sitename)) {
419
            bioentities.set(externalreference.sitename, new Map<string, string>());
420
          }
421
          bioentities.get(externalreference.sitename).set(externalreference.refidentifier, externalreference.url);
422

    
423
        }
424
      }
425
    }
426

    
427
    return bioentities;
428
  }
429

    
430
  getOpenCitations(id: string, properties:EnvProperties) {
431
    //https://services.openaire.eu/opencitations/getCitations?id=doajarticles::2634200c24772ee8f10232d3e184ec65
432
    let url = properties.openCitationsAPIURL+id;// "https://services.openaire.eu/opencitations/getCitations?id=" + id;
433
    let key = url;
434

    
435
    //return this.http.get((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)): url)
436
    return this.http.get(url)
437
      .pipe(map(res => [res['total'], this.parseOpenCitations(res['results'])]));
438
  }
439

    
440
  parseOpenCitations(openCitations: any): {"url": string, "title": string, "year": string, "doi": string, "authors": string[]}[] {
441
    //title, doi, authors
442
    let citations = new Array<{"url": string, "title": string, "year": string, "doi": string, "authors": string[]}>();
443

    
444
    let openCitation;
445

    
446
    let length = Array.isArray(openCitations) ? openCitations.length : 1;
447
    for(let i=0; i<length; i++) {
448
      openCitation = Array.isArray(openCitations) ? openCitations[i] : openCitations;
449

    
450
      let citation: {"url": string, "title": string,  "year": string, "doi": string, "authors": string[]} = {"url": "", "title": "", "year": "", "doi": "", "authors": []};
451

    
452
      if(openCitation && openCitation.id) {
453
        citation.url = openCitation.id;
454
        citation.title = openCitation.title;
455
        //citation.type = openCitation.type;
456
        citation.year = (openCitation.pubDate && (openCitation.pubDate).indexOf('-') !== -1)?openCitation.pubDate.split('-')[0]:openCitation.pubDate;
457
        citation.doi = openCitation.doi;
458

    
459
        let authorsLength = Array.isArray(openCitation.authors) ? openCitation.authors.length : 1;
460
        for(let i=0; i<authorsLength; i++) {
461
          let author = Array.isArray(openCitation.authors) ? openCitation.authors[i] : openCitation.authors;
462

    
463
          if(author) {
464
            let lastFirstName: string = "";
465
            if(author.lastName) {
466
              lastFirstName = author.lastName;
467
            }
468
            if(author.lastName && author.firstName) {
469
              lastFirstName += ", ";
470
            }
471
            if(author.firstName) {
472
              lastFirstName += author.firstName;
473
            }
474

    
475
            if(lastFirstName) {
476
              citation.authors.push(lastFirstName);
477
            }
478
          }
479
        }
480
        citations.push(citation);
481
      }
482
    }
483
    return citations;
484
  }
485

    
486
  getEnermapsDetails(id: string) {
487
    let url = properties.enermapsURL+"/api/datasets_full?shared_id=eq."+id;
488
    return this.http.get((properties.useLongCache)? (properties.cacheUrl+encodeURIComponent(url)): url)
489
    // return this.http.get(url)
490
      .pipe(map(res => this.parseEnermapsDetails(res)));
491
  }
492

    
493
  parseEnermapsDetails(response: any) {
494
    let details = Array.isArray(response) ? response[0] : response;
495
    let metadata = (details && details.metadata) ? details.metadata : null;
496

    
497
    let entries = [];
498
    let keys = metadata ? Object.keys(metadata) : null;
499
    for(let key of keys) {
500
      if(key != "shared_id" && key && metadata[key]) {
501
        entries.push([key, metadata[key]]);
502
      }
503
    }
504
    return entries;
505
  }
506
}
(4-4/4)