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, tap} from "rxjs/operators";
8
import {HostedByCollectedFrom, Organization} from "../../utils/result-preview/result-preview";
9
import {Dates} from "../../utils/string-utils.class";
10

    
11
@Injectable()
12
export class ResultLandingService {
13

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

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

    
21
  getResultLandingInfo (id: string, type: string, provenanceActionVocabulary: any, properties: EnvProperties): any {
22
    let url = properties.searchAPIURLLAst;
23
    if (type === 'publication') {
24
      url += 'publications/';
25
    } else if (type === 'dataset') {
26
      url += 'datasets/';
27
    } else if (type === 'software') {
28
      url += 'software/';
29
    } else if (type === 'orp') {
30
      url += 'other/';
31
    } else if (type === 'result') {
32
      url += 'results/';
33
    }
34
    url += id + '?format=json';
35

    
36
    return this.http.get((properties.useCache) ? (properties.cacheUrl + encodeURIComponent(url)) : url)
37
      .pipe(map(res => [res['result']['header']['dri:status'], res['result']['metadata']['oaf:entity'], res]))
38
      .pipe(map(res => [
39
        res[1]['oaf:result'],                 // 0
40
        res[1]['oaf:result']['title'],        // 1
41
        res[1]['oaf:result']['rels']['rel'],  // 2
42
        res[1]['oaf:result']['children'],     // 3
43
        res[1]['oaf:result']['pid'],          // 4
44
        res[1]['oaf:result']['journal'],      // 5
45
        res[1]['oaf:result']['language'],     // 6
46
        res[1]['oaf:result']['subject'],      // 7
47
        res[1]['oaf:result']['context'],      // 8
48
        res[1]['oaf:result']['creator'],      // 9
49
        res[1]['oaf:result']['country'] ,     // 10
50
        res[1]['oaf:result']['programmingLanguage'],              // 11 - software
51
        //res[1]['oaf:result']['resulttype'],
52
        (res[1]['extraInfo'] !== undefined && res[1]['extraInfo']['citations'] !== undefined)
53
          ? res[1]['extraInfo']['citations']['citation'] : null,  // 12
54
        res[0],                               // 13
55
        res[2]                                // 14
56
      ]))
57
      .pipe(map(res => this.parseResultLandingInfo(res, provenanceActionVocabulary, properties)));
58
  }
59

    
60
  // getProvenanceActionVocabulary (properties: EnvProperties): any {
61
  //   let url = properties.vocabulariesAPI+"dnet:provenanceActions.json";
62
  //
63
  //   return this.http.get((properties.useCache) ? (properties.cacheUrl + encodeURIComponent(url)) : url)
64
  //     .pipe(map(res => res['terms']))
65
  //     .pipe(map(res => this.parseProvenanceActionVocabulary(res, properties)));
66
  // }
67
  //
68
  // parseProvenanceActionVocabulary(terms: any, properties: EnvProperties) {
69
  //   var provenanceActionVocabulary: {} = {};
70
  //   for(let term of terms) {
71
  //     provenanceActionVocabulary[term.code] = term.englishName;
72
  //   }
73
  //   return provenanceActionVocabulary;
74
  // }
75

    
76
  private handleError (error: HttpErrorResponse) {
77
    // in a real world app, we may send the error to some remote logging infrastructure
78
    // instead of just logging it to the console
79
    console.log(error);
80
    return throwError(error  || 'Server error');
81
  }
82

    
83
  parseResultLandingInfo (data: any, provenanceActionVocabulary: any, properties: EnvProperties): any {
84
    this.resultLandingInfo = new ResultLandingInfo();
85

    
86
    // res
87
    this.resultLandingInfo.record = data[14];
88
    this.resultLandingInfo.relcanId = ParsingFunctions.parseRelCanonicalId(this.resultLandingInfo.record, "result");
89
    this.resultLandingInfo.resultType = data[0].resulttype.classid;
90

    
91
    // res['result']['metadata']['oaf:entity']['oaf:result']
92
    if (data[0] != null) {
93
      let date: string = (data[0].dateofacceptance ? data[0].dateofacceptance : '') + ''; // transform to string in case it is an integer
94
      this.resultLandingInfo.date  = (date && (date).indexOf('-') !== -1) ? date.split('-')[0] : date;
95
      this.resultLandingInfo.dateofacceptance = data[0].dateofacceptance?Dates.getDate(data[0].dateofacceptance):null;
96
      this.resultLandingInfo.publisher = data[0].publisher;
97
      if(!Array.isArray(data[0].description)) {
98
        //this.resultLandingInfo.description = String(data[0].description);
99
        this.resultLandingInfo.description = (data[0] && data[0].description) ? String(data[0].description) : "";
100
      } else {
101
        //this.resultLandingInfo.description = String(data[0].description[0]);
102
        this.resultLandingInfo.description = (data[0] && data[0].description[0]) ? String(data[0].description[0]) : "";
103
      }
104
      this.resultLandingInfo.embargoEndDate = data[0].embargoenddate?Dates.getDate(data[0].embargoenddate):null;
105
    }
106

    
107
    if(data[0]['bestaccessright'] && data[0]['bestaccessright'].hasOwnProperty("classname")) {
108
      this.resultLandingInfo.accessMode = data[0]['bestaccessright'].classname;
109
    }
110
    // res['result']['metadata']['oaf:entity']['oaf:result']['title']
111
    if(data[1] != null) {
112
      if(Array.isArray(data[1])) {
113
        this.resultLandingInfo.title = (data[1][0] && data[1][0].content) ? String(data[1][0].content) : "";
114
        if(data[1][1].classid === 'subtitle') {
115
          this.resultLandingInfo.subtitle = (data[1][1] && data[1][1].content) ? String(data[1][1].content) : "";
116
        }
117
      } else {
118
        this.resultLandingInfo.title = (data[1] && data[1].content) ? String(data[1].content) : "";
119
      }
120
    }
121

    
122
    // res['result']['metadata']['oaf:entity']['oaf:result']['rels']['rel']
123
    if(data[2] != null) {
124
      let relation;
125
      let length = Array.isArray(data[2]) ? data[2].length : 1;
126

    
127
      for(let i=0; i<length; i++) {
128
        relation = Array.isArray(data[2]) ? data[2][i] : data[2];
129
        if(relation.hasOwnProperty("to")) {
130
          if(relation['to'].class == "isProducedBy") {
131
            this.resultLandingInfo.fundedByProjects = this.parsingFunctions.parseFundingByProjects(this.resultLandingInfo.fundedByProjects, relation, provenanceActionVocabulary);
132
          } else if(relation['to'].class == "isRelatedTo") {
133
            let provenanceAction: string = "";
134
            if(provenanceActionVocabulary != null && relation.provenanceaction in provenanceActionVocabulary) {
135
              provenanceAction = provenanceActionVocabulary[relation.provenanceaction];
136
            }
137

    
138
            this.resultLandingInfo.relatedResearchResults = this.parsingFunctions.parseRelatedResearchResults(this.resultLandingInfo.relatedResearchResults, relation, provenanceAction);
139
          } else if(relation['to'].class == "hasAmongTopNSimilarDocuments") {
140
            this.resultLandingInfo.similarResearchResults = this.parsingFunctions.parseSimilarResearchResults(this.resultLandingInfo.similarResearchResults, relation);
141
          } else if(relation['to'].class == "hasAuthorInstitution") {
142
            this.resultLandingInfo.organizations = this.parseRelatedOrganizations(this.resultLandingInfo.organizations, relation);
143
          } else if(relation['to'].class == "isSupplementedBy") {
144
            this.resultLandingInfo.supplementaryResearchResults = this.parsingFunctions.parseSupplementaryResearchResults(this.resultLandingInfo.supplementaryResearchResults, relation);
145
          } else if(relation['to'].class == "isSupplementTo") {
146
            this.resultLandingInfo.supplementedByResearchResults = this.parsingFunctions.parseSupplementedByResearchResults(this.resultLandingInfo.supplementedByResearchResults, relation);
147
          }
148
        }
149
      }
150
    }
151

    
152
    // res['result']['metadata']['oaf:entity']['oaf:result']['children']
153
    if(data[3] != null) {
154
      if(data[3].hasOwnProperty("result")) {
155
        this.resultLandingInfo.deletedByInferenceIds = [];
156
        let length = Array.isArray(data[3]['result']) ? data[3]['result'].length : 1;
157

    
158
        for(let i=0; i<length; i++) {
159
          let result = Array.isArray(data[3]['result']) ? data[3]['result'][i] : data[3]['result'];
160
          this.resultLandingInfo.deletedByInferenceIds.push(result.objidentifier);
161
        }
162

    
163
      }
164

    
165
      if(data[3].hasOwnProperty("instance")) {
166
        this.resultLandingInfo.hostedBy_collectedFrom = new Array<HostedByCollectedFrom>();
167

    
168

    
169
        this.resultLandingInfo.types = new Array<string>();
170
        let types = new Set<string>();
171

    
172
        let counter = 0;
173
        let instance;
174

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

    
177
        for(let i=0; i<length; i++) {
178
          instance = Array.isArray(data[3]['instance']) ? data[3]['instance'][i] : data[3]['instance'];
179

    
180
          this.parsingFunctions.parseTypes(this.resultLandingInfo.types, types, instance);
181

    
182
          if(instance.hasOwnProperty("webresource")) {
183
            let url;
184
            if(!Array.isArray(instance['webresource'])) {
185
              url = instance['webresource'].url;
186
            } else{
187
              url = instance['webresource'][0].url;
188
            }
189

    
190
            /**********************************************************/
191
            if(instance.hasOwnProperty("hostedby")) {
192
              counter = this.parsingFunctions.parseHostedBy_collectedFrom(this.resultLandingInfo.hostedBy_collectedFrom, instance, data[0], url, counter/*, this.resultLandingInfo.title*/, this.resultLandingInfo.accessMode);
193
            }
194
            /**********************************************************/
195
          }
196
        }
197
        /* Order Download from via openness*/
198
        this.resultLandingInfo.hostedBy_collectedFrom.sort((a, b) => {
199
          if(a.bestAccessMode && a.bestAccessMode.toLowerCase() === 'open access') {
200
            return -1;
201
          } else if(b.bestAccessMode && b.bestAccessMode.toLowerCase() === 'open access') {
202
            return 1;
203
          } else if(!a.bestAccessMode || a.bestAccessMode.toLowerCase() !== 'not available') {
204
            return 1;
205
          } else if(!b.bestAccessMode || b.bestAccessMode.toLowerCase() !== 'not available') {
206
            return -1;
207
          } else {
208
            return 0;
209
          }
210
        });
211
      }
212

    
213
      if(data[3].hasOwnProperty("externalreference")) {
214
        let externalResults: Map<string, Map<string, string>> = this.parseBioentitiesAndSoftware(data[3]);
215
        this.resultLandingInfo.bioentities = externalResults;
216
      }
217
    }
218

    
219
    // res['result']['metadata']['oaf:entity']['oaf:result']['pid']
220
    if(data[4] != null) {
221
      this.resultLandingInfo.identifiers = this.parsingFunctions.parseIdentifiers(data[4]);
222
    }
223

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

    
228
      this.resultLandingInfo.journal['journal'] = data[5].content;
229
      this.resultLandingInfo.journal['issn'] = data[5].issn;
230
      this.resultLandingInfo.journal['lissn'] = data[5].lissn;
231
      this.resultLandingInfo.journal['eissn'] = data[5].eissn;
232
      this.resultLandingInfo.journal['issue'] = data[5].iss;
233
      this.resultLandingInfo.journal['volume'] = data[5].vol;
234
      this.resultLandingInfo.journal['start_page'] = data[5].sp;
235
      this.resultLandingInfo.journal['end_page'] = data[5].ep;
236
    }
237

    
238
    // res['result']['metadata']['oaf:entity']['oaf:result']['language']
239
    if(data[6] != null) {
240
      this.resultLandingInfo.languages = this.parsingFunctions.parseLanguages(data[6]);
241
    }
242

    
243
    // res['result']['metadata']['oaf:entity']['oaf:result']['country']
244
    if(data[10] != null) {
245
      this.resultLandingInfo.countries = this.parsingFunctions.parseCountries(data[10]);
246
    }
247

    
248
    // res['result']['metadata']['oaf:entity']['oaf:result']['subject']
249
    if(data[7] != null) {
250
      let subjectResults: [string[], Map<string, string[]>, Map<string, string[]>] = this.parsingFunctions.parseAllSubjects(data[7]);
251
      this.resultLandingInfo.subjects = subjectResults[0];
252
      this.resultLandingInfo.otherSubjects = subjectResults[1];
253
      this.resultLandingInfo.classifiedSubjects = subjectResults[2];
254
    }
255

    
256
    this.resultLandingInfo.hostedBy_collectedFrom = this.parsingFunctions.addPublisherToHostedBy_collectedFrom(
257
      this.resultLandingInfo.hostedBy_collectedFrom, this.resultLandingInfo.publisher,
258
      this.resultLandingInfo.journal, this.resultLandingInfo.identifiers);
259

    
260
    // res['result']['metadata']['oaf:entity']['oaf:result']['programmingLanguage']
261
    if(data[11] != null) {
262
      this.resultLandingInfo.programmingLanguages = this.parsingFunctions.parseProgrammingLanguages(data[11]);
263
    }
264

    
265
    // res['result']['metadata']['oaf:entity']['extraInfo']['citations']['citation']
266
    if(data[12] != null) {
267
      this.resultLandingInfo.references = this.parsingFunctions.parseReferences(data[12]);
268
    }
269

    
270
    // res['result']['metadata']['oaf:entity']['oaf:result']['context']
271
    if(data[8] != null) {
272
      this.resultLandingInfo.contexts = this.parsingFunctions.parseContexts(data[8]);
273
    }
274

    
275
    // res['result']['header']['dri:status']
276
    if(data[13] != null && data[13] == "under curation") {
277
      this.resultLandingInfo.underCurationMessage = true;
278
    } else {
279
      this.resultLandingInfo.underCurationMessage = false;
280
    }
281

    
282
    // res['result']['metadata']['oaf:entity']['oaf:result']['creator']
283
    if(data[9] != null) {
284
      if(this.resultLandingInfo.authors == undefined) {
285
        this.resultLandingInfo.authors = new Array<{"fullName": string, "orcid": string}>();
286
      }
287

    
288
      let authors = data[9];
289
      let length = Array.isArray(authors) ? authors.length : 1;
290

    
291
      for(let i=0; i<length; i++) {
292
        let author = Array.isArray(authors) ? authors[i] : authors;
293
        if(author) {
294
          this.resultLandingInfo['authors'][author.rank] = {"fullName": author.content, "orcid": author.orcid};
295
        }
296
      }
297
      this.resultLandingInfo.authors = this.resultLandingInfo.authors.filter(function (item) {
298
        return (item != undefined && item.fullName != undefined);
299
      });
300
    }
301
    this.resultLandingInfo.relatedResearchResults = this.parsingFunctions.sortByPercentage(this.resultLandingInfo.relatedResearchResults);
302
    this.resultLandingInfo.similarResearchResults = this.parsingFunctions.sortByPercentage(this.resultLandingInfo.similarResearchResults);
303
    this.resultLandingInfo.supplementaryResearchResults = this.parsingFunctions.sortByPercentage(this.resultLandingInfo.supplementaryResearchResults);
304
    this.resultLandingInfo.supplementedByResearchResults = this.parsingFunctions.sortByPercentage(this.resultLandingInfo.supplementedByResearchResults);
305

    
306
    return this.resultLandingInfo;
307
  }
308

    
309
  parseRelatedOrganizations(organizations: Organization[], relation: any): Organization[] {
310
    if(organizations == undefined) {
311
      organizations = []
312
    }
313

    
314
    let organization: { "name": string, "shortname": string,
315
      "id": string, "websiteUrl": string,
316
      "country": string, "trust": number
317
    } = {
318
      name: "", shortname: "",
319
      id: "", websiteUrl: "",
320
      country: "", trust: null
321
    };
322

    
323
    organization.id = relation['to'].content;
324
    organization.name = relation.legalname;
325
    organization.shortname = relation.legalshortname;
326
    organization.websiteUrl = relation.websiteurl;
327
    if(relation.country) {
328
      organization.country = relation.country.classname;
329
    }
330
    if(relation.trust) {
331
      organization.trust = Math.round(relation.trust*100);
332
    }
333

    
334
    organizations.push(organization);
335
    return organizations;
336
  }
337

    
338
  parseBioentitiesAndSoftware(children: any) : Map<string, Map<string, string>> {
339
    let bioentities: Map<string, Map<string, string>>;
340

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

    
343
    let externalreference;
344
    for(let i=0; i<length; i++) {
345
      externalreference = Array.isArray(children['externalreference']) ? children['externalreference'][i] : children['externalreference'];
346

    
347
      if(externalreference.hasOwnProperty("qualifier")) {
348
        if(externalreference['qualifier'].classid == "accessionNumber") {
349

    
350
          if(bioentities == undefined) {
351
            bioentities = new Map<string, Map<string, string>>();
352
          }
353

    
354
          if(!bioentities.has(externalreference.sitename)) {
355
            bioentities.set(externalreference.sitename, new Map<string, string>());
356
          }
357
          bioentities.get(externalreference.sitename).set(externalreference.refidentifier, externalreference.url);
358

    
359
        }
360
      }
361
    }
362

    
363
    return bioentities;
364
  }
365

    
366
  getOpenCitations(id: string, properties:EnvProperties) {
367
    //https://services.openaire.eu/opencitations/getCitations?id=doajarticles::2634200c24772ee8f10232d3e184ec65
368
    let url = properties.openCitationsAPIURL+id;// "https://services.openaire.eu/opencitations/getCitations?id=" + id;
369
    let key = url;
370

    
371
    //return this.http.get((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)): url)
372
    return this.http.get(url)
373
      .pipe(map(res => [res['total'], this.parseOpenCitations(res['results'])]));
374
  }
375

    
376
  parseOpenCitations(openCitations: any): {"url": string, "title": string, "year": string, "doi": string, "authors": string[]}[] {
377
    //title, doi, authors
378
    let citations = new Array<{"url": string, "title": string, "year": string, "doi": string, "authors": string[]}>();
379

    
380
    let openCitation;
381

    
382
    let length = Array.isArray(openCitations) ? openCitations.length : 1;
383
    for(let i=0; i<length; i++) {
384
      openCitation = Array.isArray(openCitations) ? openCitations[i] : openCitations;
385

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

    
388
      if(openCitation && openCitation.id) {
389
        citation.url = openCitation.id;
390
        citation.title = openCitation.title;
391
        //citation.type = openCitation.type;
392
        citation.year = (openCitation.pubDate && (openCitation.pubDate).indexOf('-') !== -1)?openCitation.pubDate.split('-')[0]:openCitation.pubDate;
393
        citation.doi = openCitation.doi;
394

    
395
        let authorsLength = Array.isArray(openCitation.authors) ? openCitation.authors.length : 1;
396
        for(let i=0; i<authorsLength; i++) {
397
          let author = Array.isArray(openCitation.authors) ? openCitation.authors[i] : openCitation.authors;
398

    
399
          if(author) {
400
            let lastFirstName: string = "";
401
            if(author.lastName) {
402
              lastFirstName = author.lastName;
403
            }
404
            if(author.lastName && author.firstName) {
405
              lastFirstName += ", ";
406
            }
407
            if(author.firstName) {
408
              lastFirstName += author.firstName;
409
            }
410

    
411
            if(lastFirstName) {
412
              citation.authors.push(lastFirstName);
413
            }
414
          }
415
        }
416
        citations.push(citation);
417
      }
418
    }
419
    return citations;
420
  }
421
}
(4-4/4)