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 {Organization} from "../../utils/result-preview/result-preview";
9

    
10
@Injectable()
11
export class ResultLandingService {
12

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

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

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

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

    
59
  getProvenanceActionVocabulary (properties: EnvProperties): any {
60
    let url = properties.vocabulariesAPI+"dnet:provenanceActions.json";
61

    
62
    return this.http.get((properties.useCache) ? (properties.cacheUrl + encodeURIComponent(url)) : url)
63
      .pipe(map(res => res['terms']))
64
      .pipe(map(res => this.parseProvenanceActionVocabulary(res, properties)));
65
  }
66

    
67
  parseProvenanceActionVocabulary(terms: any, properties: EnvProperties) {
68
    var provenanceActionVocabulary: {} = {};
69
    for(let term of terms) {
70
      provenanceActionVocabulary[term.code] = term.englishName;
71
    }
72
    return provenanceActionVocabulary;
73
  }
74

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

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

    
85
    // res
86
    this.resultLandingInfo.record = data[14];
87
    this.resultLandingInfo.resultType = data[0].resulttype.classid;
88

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

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

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

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

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

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

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

    
161
      }
162

    
163
      if(data[3].hasOwnProperty("instance")) {
164
        this.resultLandingInfo.hostedBy_collectedFrom = new Array<{"downloadName": string, "downloadUrl": string[], "collectedName": string, "collectedId": string, "accessMode": string[], "bestAccessMode": string, "type": string, "year":string}>();
165

    
166

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

    
170
        let counter = 0;
171
        let instance;
172

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

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

    
178
          this.parsingFunctions.parseTypes(this.resultLandingInfo.types, types, instance);
179

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
304
    return this.resultLandingInfo;
305
  }
306

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

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

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

    
332
    organizations.push(organization);
333
    return organizations;
334
  }
335

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

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

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

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

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

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

    
357
        }
358
      }
359
    }
360

    
361
    return bioentities;
362
  }
363

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

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

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

    
378
    let openCitation;
379

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

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

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

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

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

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