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') {
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="+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.relcanId = ParsingFunctions.parseRelCanonicalId(this.resultLandingInfo.record, "result");
130
    this.resultLandingInfo.resultType = data[0].resulttype.classid;
131

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

    
148
    if(data[0]['bestaccessright'] && data[0]['bestaccessright'].hasOwnProperty("classname")) {
149
      this.resultLandingInfo.accessMode = data[0]['bestaccessright'].classname;
150
    }
151
    // res['result']['metadata']['oaf:entity']['oaf:result']['title']
152
    if(data[1] != null) {
153
      if(Array.isArray(data[1])) {
154
        this.resultLandingInfo.title = (data[1][0] && data[1][0].content) ? String(data[1][0].content) : "";
155
        if(data[1][1].classid === 'subtitle') {
156
          this.resultLandingInfo.subtitle = (data[1][1] && data[1][1].content) ? String(data[1][1].content) : "";
157
        }
158
      } else {
159
        this.resultLandingInfo.title = (data[1] && data[1].content) ? String(data[1].content) : "";
160
      }
161
    }
162

    
163
    // res['result']['metadata']['oaf:entity']['oaf:result']['rels']['rel']
164
    if(data[2] != null) {
165
      let relation;
166
      let length = Array.isArray(data[2]) ? data[2].length : 1;
167

    
168
      for(let i=0; i<length; i++) {
169
        relation = Array.isArray(data[2]) ? data[2][i] : data[2];
170
        if(relation.hasOwnProperty("to")) {
171
          if(relation['to'].class == "isProducedBy") {
172
            this.resultLandingInfo.fundedByProjects = this.parsingFunctions.parseFundingByProjects(this.resultLandingInfo.fundedByProjects, relation, provenanceActionVocabulary);
173
          } else if(relation['to'].class == "isRelatedTo") {
174
            let provenanceAction: string = "";
175
            if(provenanceActionVocabulary != null && relation.provenanceaction in provenanceActionVocabulary) {
176
              provenanceAction = provenanceActionVocabulary[relation.provenanceaction];
177
            }
178

    
179
            this.resultLandingInfo.relatedResearchResults = this.parsingFunctions.parseRelatedResearchResults(this.resultLandingInfo.relatedResearchResults, relation, provenanceAction);
180
          } else if(relation['to'].class == "hasAmongTopNSimilarDocuments") {
181
            this.resultLandingInfo.similarResearchResults = this.parsingFunctions.parseSimilarResearchResults(this.resultLandingInfo.similarResearchResults, relation);
182
          } else if(relation['to'].class == "hasAuthorInstitution") {
183
            this.resultLandingInfo.organizations = this.parseRelatedOrganizations(this.resultLandingInfo.organizations, relation);
184
          } else if(relation['to'].class == "isSupplementedBy") {
185
            this.resultLandingInfo.supplementaryResearchResults = this.parsingFunctions.parseSupplementaryResearchResults(this.resultLandingInfo.supplementaryResearchResults, relation);
186
          } else if(relation['to'].class == "isSupplementTo") {
187
            this.resultLandingInfo.supplementedByResearchResults = this.parsingFunctions.parseSupplementedByResearchResults(this.resultLandingInfo.supplementedByResearchResults, relation);
188
          }
189
        }
190
      }
191
    }
192

    
193
    // res['result']['metadata']['oaf:entity']['oaf:result']['children']
194
    if(data[3] != null) {
195
      if(data[3].hasOwnProperty("result")) {
196
        this.resultLandingInfo.deletedByInferenceIds = [];
197
        let length = Array.isArray(data[3]['result']) ? data[3]['result'].length : 1;
198

    
199
        for(let i=0; i<length; i++) {
200
          let result = Array.isArray(data[3]['result']) ? data[3]['result'][i] : data[3]['result'];
201
          this.resultLandingInfo.deletedByInferenceIds.push(result.objidentifier);
202
        }
203

    
204
      }
205

    
206
      if(data[3].hasOwnProperty("instance")) {
207
        this.resultLandingInfo.hostedBy_collectedFrom = new Array<HostedByCollectedFrom>();
208

    
209

    
210
        this.resultLandingInfo.types = new Array<string>();
211
        let types = new Set<string>();
212

    
213
        let counter = 0;
214
        let instance;
215

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

    
218
        for(let i=0; i<length; i++) {
219
          instance = Array.isArray(data[3]['instance']) ? data[3]['instance'][i] : data[3]['instance'];
220

    
221
          this.parsingFunctions.parseTypes(this.resultLandingInfo.types, types, instance);
222

    
223
          if(instance.hasOwnProperty("webresource")) {
224
            let url;
225
            if(!Array.isArray(instance['webresource'])) {
226
              url = instance['webresource'].url;
227
            } else{
228
              url = instance['webresource'][0].url;
229
            }
230

    
231
            /**********************************************************/
232
            if(instance.hasOwnProperty("hostedby")) {
233
              counter = this.parsingFunctions.parseHostedBy_collectedFrom(this.resultLandingInfo.hostedBy_collectedFrom, instance, data[0], url, counter/*, this.resultLandingInfo.title*/, this.resultLandingInfo.accessMode);
234
            }
235
            /**********************************************************/
236
          }
237
        }
238
        /* Order Download from via openness*/
239
        this.resultLandingInfo.hostedBy_collectedFrom.sort((a, b) => {
240
          if(a.bestAccessMode && a.bestAccessMode.toLowerCase() === 'open access') {
241
            return -1;
242
          } else if(b.bestAccessMode && b.bestAccessMode.toLowerCase() === 'open access') {
243
            return 1;
244
          } else if(!a.bestAccessMode || a.bestAccessMode.toLowerCase() !== 'not available') {
245
            return 1;
246
          } else if(!b.bestAccessMode || b.bestAccessMode.toLowerCase() !== 'not available') {
247
            return -1;
248
          } else {
249
            return 0;
250
          }
251
        });
252
      }
253

    
254
      if(data[3].hasOwnProperty("externalreference")) {
255
        let externalResults: Map<string, Map<string, string>> = this.parseBioentitiesAndSoftware(data[3]);
256
        this.resultLandingInfo.bioentities = externalResults;
257
      }
258
    }
259

    
260
    // res['result']['metadata']['oaf:entity']['oaf:result']['pid']
261
    if(data[4] != null) {
262
      this.resultLandingInfo.identifiers = this.parsingFunctions.parseIdentifiers(data[4]);
263
    }
264

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

    
269
      this.resultLandingInfo.journal['journal'] = data[5].content;
270
      this.resultLandingInfo.journal['issn'] = data[5].issn;
271
      this.resultLandingInfo.journal['lissn'] = data[5].lissn;
272
      this.resultLandingInfo.journal['eissn'] = data[5].eissn;
273
      this.resultLandingInfo.journal['issue'] = data[5].iss;
274
      this.resultLandingInfo.journal['volume'] = data[5].vol;
275
      this.resultLandingInfo.journal['start_page'] = data[5].sp;
276
      this.resultLandingInfo.journal['end_page'] = data[5].ep;
277
    }
278

    
279
    // res['result']['metadata']['oaf:entity']['oaf:result']['language']
280
    if(data[6] != null) {
281
      this.resultLandingInfo.languages = this.parsingFunctions.parseLanguages(data[6]);
282
      // let languagesAndCodes: string[][] = this.parsingFunctions.parseLanguages(data[6]);
283
      // this.resultLandingInfo.languages = languagesAndCodes[0];
284
      // this.resultLandingInfo.languageCodes = languagesAndCodes[1];
285
    }
286

    
287
    // res['result']['metadata']['oaf:entity']['oaf:result']['country']
288
    if(data[10] != null) {
289
      this.resultLandingInfo.countries = this.parsingFunctions.parseCountries(data[10]);
290
    }
291

    
292
    // res['result']['metadata']['oaf:entity']['oaf:result']['subject']
293
    if(data[7] != null) {
294
      let subjectResults: [string[], Map<string, string[]>, Map<string, string[]>] = this.parsingFunctions.parseAllSubjects(data[7]);
295
      this.resultLandingInfo.subjects = subjectResults[0];
296
      this.resultLandingInfo.otherSubjects = subjectResults[1];
297
      this.resultLandingInfo.classifiedSubjects = subjectResults[2];
298
    }
299

    
300
    this.resultLandingInfo.hostedBy_collectedFrom = this.parsingFunctions.addPublisherToHostedBy_collectedFrom(
301
      this.resultLandingInfo.hostedBy_collectedFrom, this.resultLandingInfo.publisher,
302
      this.resultLandingInfo.journal, this.resultLandingInfo.identifiers);
303

    
304
    // res['result']['metadata']['oaf:entity']['oaf:result']['programmingLanguage']
305
    if(data[11] != null) {
306
      this.resultLandingInfo.programmingLanguages = this.parsingFunctions.parseProgrammingLanguages(data[11]);
307
    }
308

    
309
    // res['result']['metadata']['oaf:entity']['extraInfo']['citations']['citation']
310
    if(data[12] != null) {
311
      this.resultLandingInfo.references = this.parsingFunctions.parseReferences(data[12]);
312
    }
313

    
314
    // res['result']['metadata']['oaf:entity']['oaf:result']['context']
315
    if(data[8] != null) {
316
      this.resultLandingInfo.contexts = this.parsingFunctions.parseContexts(data[8]);
317
    }
318

    
319
    // res['result']['header']['dri:status']
320
    if(data[13] != null && data[13] == "under curation") {
321
      this.resultLandingInfo.underCurationMessage = true;
322
    } else {
323
      this.resultLandingInfo.underCurationMessage = false;
324
    }
325

    
326
    // res['result']['metadata']['oaf:entity']['oaf:result']['creator']
327
    if(data[9] != null) {
328
      if(this.resultLandingInfo.authors == undefined) {
329
        this.resultLandingInfo.authors = new Array<{"fullName": string, "orcid": string}>();
330
      }
331

    
332
      let authors = data[9];
333
      let length = Array.isArray(authors) ? authors.length : 1;
334

    
335
      for(let i=0; i<length; i++) {
336
        let author = Array.isArray(authors) ? authors[i] : authors;
337
        if(author) {
338
          this.resultLandingInfo['authors'][author.rank] = {"fullName": author.content, "orcid": author.orcid};
339
        }
340
      }
341
      this.resultLandingInfo.authors = this.resultLandingInfo.authors.filter(function (item) {
342
        return (item != undefined && item.fullName != undefined);
343
      });
344
    }
345
    this.resultLandingInfo.relatedResearchResults = this.parsingFunctions.sortByPercentage(this.resultLandingInfo.relatedResearchResults);
346
    this.resultLandingInfo.similarResearchResults = this.parsingFunctions.sortByPercentage(this.resultLandingInfo.similarResearchResults);
347
    this.resultLandingInfo.supplementaryResearchResults = this.parsingFunctions.sortByPercentage(this.resultLandingInfo.supplementaryResearchResults);
348
    this.resultLandingInfo.supplementedByResearchResults = this.parsingFunctions.sortByPercentage(this.resultLandingInfo.supplementedByResearchResults);
349

    
350
    return this.resultLandingInfo;
351
  }
352

    
353
  parseRelatedOrganizations(organizations: Organization[], relation: any): Organization[] {
354
    if(organizations == undefined) {
355
      organizations = []
356
    }
357

    
358
    let organization: { "name": string, "shortname": string,
359
      "id": string, "websiteUrl": string,
360
      "country": string, "trust": number
361
    } = {
362
      name: "", shortname: "",
363
      id: "", websiteUrl: "",
364
      country: "", trust: null
365
    };
366

    
367
    organization.id = relation['to'].content;
368
    organization.name = relation.legalname;
369
    organization.shortname = relation.legalshortname;
370
    organization.websiteUrl = relation.websiteurl;
371
    if(relation.country) {
372
      organization.country = relation.country.classname;
373
    }
374
    if(relation.trust) {
375
      organization.trust = Math.round(relation.trust*100);
376
    }
377

    
378
    organizations.push(organization);
379
    return organizations;
380
  }
381

    
382
  parseBioentitiesAndSoftware(children: any) : Map<string, Map<string, string>> {
383
    let bioentities: Map<string, Map<string, string>>;
384

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

    
387
    let externalreference;
388
    for(let i=0; i<length; i++) {
389
      externalreference = Array.isArray(children['externalreference']) ? children['externalreference'][i] : children['externalreference'];
390

    
391
      if(externalreference.hasOwnProperty("qualifier")) {
392
        if(externalreference['qualifier'].classid == "accessionNumber") {
393

    
394
          if(bioentities == undefined) {
395
            bioentities = new Map<string, Map<string, string>>();
396
          }
397

    
398
          if(!bioentities.has(externalreference.sitename)) {
399
            bioentities.set(externalreference.sitename, new Map<string, string>());
400
          }
401
          bioentities.get(externalreference.sitename).set(externalreference.refidentifier, externalreference.url);
402

    
403
        }
404
      }
405
    }
406

    
407
    return bioentities;
408
  }
409

    
410
  getOpenCitations(id: string, properties:EnvProperties) {
411
    //https://services.openaire.eu/opencitations/getCitations?id=doajarticles::2634200c24772ee8f10232d3e184ec65
412
    let url = properties.openCitationsAPIURL+id;// "https://services.openaire.eu/opencitations/getCitations?id=" + id;
413
    let key = url;
414

    
415
    //return this.http.get((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)): url)
416
    return this.http.get(url)
417
      .pipe(map(res => [res['total'], this.parseOpenCitations(res['results'])]));
418
  }
419

    
420
  parseOpenCitations(openCitations: any): {"url": string, "title": string, "year": string, "doi": string, "authors": string[]}[] {
421
    //title, doi, authors
422
    let citations = new Array<{"url": string, "title": string, "year": string, "doi": string, "authors": string[]}>();
423

    
424
    let openCitation;
425

    
426
    let length = Array.isArray(openCitations) ? openCitations.length : 1;
427
    for(let i=0; i<length; i++) {
428
      openCitation = Array.isArray(openCitations) ? openCitations[i] : openCitations;
429

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

    
432
      if(openCitation && openCitation.id) {
433
        citation.url = openCitation.id;
434
        citation.title = openCitation.title;
435
        //citation.type = openCitation.type;
436
        citation.year = (openCitation.pubDate && (openCitation.pubDate).indexOf('-') !== -1)?openCitation.pubDate.split('-')[0]:openCitation.pubDate;
437
        citation.doi = openCitation.doi;
438

    
439
        let authorsLength = Array.isArray(openCitation.authors) ? openCitation.authors.length : 1;
440
        for(let i=0; i<authorsLength; i++) {
441
          let author = Array.isArray(openCitation.authors) ? openCitation.authors[i] : openCitation.authors;
442

    
443
          if(author) {
444
            let lastFirstName: string = "";
445
            if(author.lastName) {
446
              lastFirstName = author.lastName;
447
            }
448
            if(author.lastName && author.firstName) {
449
              lastFirstName += ", ";
450
            }
451
            if(author.firstName) {
452
              lastFirstName += author.firstName;
453
            }
454

    
455
            if(lastFirstName) {
456
              citation.authors.push(lastFirstName);
457
            }
458
          }
459
        }
460
        citations.push(citation);
461
      }
462
    }
463
    return citations;
464
  }
465
}
(4-4/4)