Project

General

Profile

1
import {Injectable} from '@angular/core';
2
import {HttpClient, HttpErrorResponse} from "@angular/common/http";
3
import {throwError} from 'rxjs';
4
import {PublicationInfo} from '../../utils/entities/publicationInfo';
5
import {EnvProperties} from '../../utils/properties/env-properties';
6
import {ParsingFunctions} from '../landing-utils/parsingFunctions.class';
7
import {map} from "rxjs/operators";
8

    
9
@Injectable()
10
export class PublicationService {
11

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

    
16
  public parsingFunctions: ParsingFunctions;
17
  publicationInfo: PublicationInfo;
18

    
19
  getPublicationInfo (id: string, properties:EnvProperties):any {
20
    let url = properties.searchAPIURLLAst + 'publications/' +id+"?format=json";
21
    let key = url;
22

    
23
    return this.http.get((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)): url)
24
                //.map(res => <any> res.json())
25
                .pipe(map(res => [res['result']['header']['dri:status'], res['result']['metadata']['oaf:entity'], res]))
26
                .pipe(map(res => [ res[1]['oaf:result'], //0
27
                              res[1]['oaf:result']['title'],  //1
28
                              res[1]['oaf:result']['rels']['rel'],  //2
29
                              res[1]['oaf:result']['children'], //3
30
                              res[1]['oaf:result']['pid'],  //4
31
                              res[1]['oaf:result']['journal'],  //5
32
                              res[1]['oaf:result']['language'], //6
33
                              res[1]['oaf:result']['subject'],  //7
34
                              res[1]['oaf:result']['bestaccessright'],  //8
35
                              res[1]['oaf:result']['collectedfrom'],  //9
36
                              (res[1]['extraInfo']!= undefined && res[1]['extraInfo']['citations']!= undefined)? res[1]['extraInfo']['citations']['citation']:null, //10
37
                              res[1]['oaf:result']['context'],  //11
38
                              res[0], //12
39
                              res[1]['oaf:result']['creator'],  //13
40
                              res[2], //14
41
                              res[1]['oaf:result']['country']  //15
42
                ]))
43
                .pipe(map(res => this.parsePublicationInfo(res, properties)));
44
  }
45

    
46
  private handleError (error: HttpErrorResponse) {
47
  // in a real world app, we may send the error to some remote logging infrastructure
48
  // instead of just logging it to the console
49
    console.log(error);
50
    return throwError(error  || 'Server error');
51
  }
52

    
53
  parsePublicationInfo (data: any, properties: EnvProperties):any {
54
    this.publicationInfo = new PublicationInfo();
55
    this.publicationInfo.record = data[14];
56
    if(data[0] != null) {
57
      var date:string = (data[0].dateofacceptance)+""; // transform to string in case it is an integer
58
      this.publicationInfo.date  = (date && (date).indexOf('-') !== -1)?date.split('-')[0]:date;
59
      this.publicationInfo.dateofacceptance = data[0].dateofacceptance;
60
      this.publicationInfo.publisher = data[0].publisher;
61
      if(!Array.isArray(data[0].description)) {
62
          this.publicationInfo.description = String(data[0].description);
63
      } else {
64
          this.publicationInfo.description = String(data[0].description[0]);
65
      }
66
      this.publicationInfo.embargoEndDate = data[0].embargoenddate;
67
    }
68

    
69
/*
70
    this.publicationInfo.title = {"name": "", "url": "", "accessMode": ""};
71
    if(data[0]['bestaccessright'] && data[0]['bestaccessright'].hasOwnProperty("classid")) {
72
      this.publicationInfo.title.accessMode = data[0]['bestaccessright'].classid;
73
    }
74

    
75
    if(data[1] != null) {
76
      if(Array.isArray(data[1])) {
77
        this.publicationInfo.title['name'] = data[1][0].content;
78
      } else {
79
        this.publicationInfo.title['name'] = data[1].content;
80
      }
81
    }
82
*/
83
    if(data[0]['bestaccessright'] && data[0]['bestaccessright'].hasOwnProperty("classid")) {
84
      this.publicationInfo.accessMode = data[0]['bestaccessright'].classid;
85
    }
86
    if(data[1] != null) {
87
      if(Array.isArray(data[1])) {
88
        this.publicationInfo.title = String(data[1][0].content);
89
      } else {
90
        this.publicationInfo.title = String(data[1].content);
91
      }
92
    }
93

    
94
    if(data[2] != null) {
95
      let relation;
96
      let length = Array.isArray(data[2]) ? data[2].length : 1;
97

    
98
      for(let i=0; i<length; i++) {
99
        relation = Array.isArray(data[2]) ? data[2][i] : data[2];
100
        if(relation.hasOwnProperty("to")) {
101
          if(relation['to'].class == "isProducedBy") {
102
            this.publicationInfo.fundedByProjects = this.parsingFunctions.parseFundingByProjects(this.publicationInfo.fundedByProjects, relation, this.publicationInfo.projectsProvenanceVocabulary);
103
          } else if(relation['to'].class == "isRelatedTo") {
104
            let provenanceAction: string;
105
            if(relation.provenanceaction in this.publicationInfo.researchResultsProvenanceVocabulary) {
106
              provenanceAction = this.publicationInfo.researchResultsProvenanceVocabulary[relation.provenanceaction];
107
            } else {
108
              provenanceAction = "Other";
109
            }
110

    
111
            this.publicationInfo.relatedResearchResults = this.parsingFunctions.parseRelatedResearchResults(this.publicationInfo.relatedResearchResults, relation, provenanceAction);
112
          } else if(relation['to'].class == "hasAmongTopNSimilarDocuments") {
113
            this.publicationInfo.similarResearchResults = this.parsingFunctions.parseSimilarResearchResults(this.publicationInfo.similarResearchResults, relation);
114
          } else if(relation['to'].class == "hasAuthorInstitution") {
115
            this.publicationInfo.organizations = this.parseRelatedOrganizations(this.publicationInfo.organizations, relation);
116
          }
117
        }
118
      }
119
    }
120

    
121
    if(data[3] != null) {
122
      if(data[3].hasOwnProperty("result")) {
123
        this.publicationInfo.deletedByInferenceIds = [];
124
        let length = Array.isArray(data[3]['result']) ? data[3]['result'].length : 1;
125

    
126
        for(let i=0; i<length; i++) {
127
          let result = Array.isArray(data[3]['result']) ? data[3]['result'][i] : data[3]['result'];
128
          this.publicationInfo.deletedByInferenceIds.push(result.objidentifier);
129
        }
130

    
131
      }
132

    
133
      if(data[3].hasOwnProperty("instance")) {
134
        //this.publicationInfo.collectedFrom = new Array<{"name": string, "id": string}>();
135
        //this.publicationInfo.downloadFrom = new Map<string, {"url": string[], "accessMode": string[], "bestAccessMode": string}>();
136
        //this.publicationInfo.publishedIn = new Map<string, {"url": string[], "accessMode": string[], "bestAccessMode": string}>();
137

    
138

    
139
        this.publicationInfo.hostedBy_collectedFrom = new Array<{"downloadName": string, "downloadUrl": string[], "collectedName": string, "collectedId": string, "accessMode": string[], "bestAccessMode": string, "type": string, "year":string}>();
140

    
141

    
142
        this.publicationInfo.types = new Array<string>();
143
        let types = new Set<string>();
144

    
145
        let counter = 0;
146
        let instance;
147

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

    
150
        for(let i=0; i<length; i++) {
151
          instance = Array.isArray(data[3]['instance']) ? data[3]['instance'][i] : data[3]['instance'];
152

    
153
          this.parsingFunctions.parseTypes(this.publicationInfo.types, types, instance);
154

    
155
          if(instance.hasOwnProperty("webresource")) {
156
            let url;
157
            if(!Array.isArray(instance['webresource'])) {
158
              url = instance['webresource'].url;
159
            } else{
160
              url = instance['webresource'][0].url;
161
            }
162

    
163
            /**********************************************************/
164
            if(instance.hasOwnProperty("hostedby")) {
165
              counter = this.parsingFunctions.parseHostedBy_collectedFrom(this.publicationInfo.hostedBy_collectedFrom, instance, data[0], url, counter/*, this.publicationInfo.title*/, this.publicationInfo.accessMode);
166
            }
167
            /**********************************************************/
168
          }
169
        }
170
      }
171

    
172
      if(data[3].hasOwnProperty("externalreference")) {
173
        let externalResults: [Map<string, Map<string, string>>, { "name": string, "url": string}[]] = this.parseBioentitiesAndSoftware(data[3]);
174
        this.publicationInfo.bioentities = externalResults[0];
175
        this.publicationInfo.software = externalResults[1];
176
      }
177
    }
178

    
179
    if(data[4] != null) {
180
      this.publicationInfo.identifiers = this.parsingFunctions.parseIdentifiers(data[4]);
181
    }
182

    
183
    if(data[5] != null) {
184
      this.publicationInfo.journal = {"journal": "", "issn": "", "lissn": "", "eissn": "", "issue": "", "volume": "", "start_page": "", "end_page": ""}
185

    
186
      this.publicationInfo.journal['journal'] = data[5].content;
187
      this.publicationInfo.journal['issn'] = data[5].issn;
188
      this.publicationInfo.journal['lissn'] = data[5].lissn;
189
      this.publicationInfo.journal['eissn'] = data[5].eissn;
190
      this.publicationInfo.journal['issue'] = data[5].iss;
191
      this.publicationInfo.journal['volume'] = data[5].vol;
192
      this.publicationInfo.journal['start_page'] = data[5].sp;
193
      this.publicationInfo.journal['end_page'] = data[5].ep;
194
    }
195

    
196
    if(data[6] != null) {
197
      this.publicationInfo.languages = this.parsingFunctions.parseLanguages(data[6]);
198
    }
199
    if(data[15] != null) {
200
      this.publicationInfo.countries = this.parsingFunctions.parseCountries(data[15]);
201
    }
202

    
203
    if(data[7] != null) {
204
      let subjectResults: [string[], Map<string, string[]>, Map<string, string[]>] = this.parsingFunctions.parseAllSubjects(data[7]);
205
      this.publicationInfo.subjects = subjectResults[0];
206
      this.publicationInfo.otherSubjects = subjectResults[1];
207
      this.publicationInfo.classifiedSubjects = subjectResults[2];
208
    }
209

    
210
    // if(data[8] != null) {
211
    //     this.publicationInfo.bestaccessright = data[8].classid;
212
    // }
213

    
214
    // if(data[9] != null) {
215
    //   this.publicationInfo.collectedFrom = this.parsingFunctions.parseCollectedFrom(data[9]);
216
    // }
217

    
218
    this.publicationInfo.hostedBy_collectedFrom = this.parsingFunctions.addPublisherToHostedBy_collectedFrom(
219
                this.publicationInfo.hostedBy_collectedFrom, this.publicationInfo.publisher,
220
                this.publicationInfo.journal, this.publicationInfo.identifiers/*,
221
                this.publicationInfo.title*/);
222

    
223
    if(data[10] != null) {
224
      this.publicationInfo.references = this.parsingFunctions.parseReferences(data[10]);
225
    }
226

    
227
    if(data[11] != null) {
228
      this.publicationInfo.contexts = this.parsingFunctions.parseContexts(data[11]);
229
    }
230

    
231
    if(data[12] != null && data[12] == "under curation") {
232
      this.publicationInfo.underCurationMessage = true;
233
    } else {
234
      this.publicationInfo.underCurationMessage = false;
235
    }
236

    
237
    if(data[13] != null) {
238
      if(this.publicationInfo.authors == undefined) {
239
        this.publicationInfo.authors = new Array<{"fullName": string, "orcid": string}>();
240
      }
241

    
242
      let authors = data[13];
243
      let length = Array.isArray(authors) ? authors.length : 1;
244

    
245
      for(let i=0; i<length; i++) {
246
        let author = Array.isArray(authors) ? authors[i] : authors;
247
        if(author) {
248
          /*if (author.ORCID && author.ORCID.indexOf(properties.orcidURL) != -1) {
249
            author.ORCID = author.ORCID.substr(properties.orcidURL.length);
250
          }*/
251
          this.publicationInfo['authors'][author.rank] = {"fullName": author.content, "orcid": author.ORCID};
252
        }
253
      }
254
      this.publicationInfo.authors = this.publicationInfo.authors.filter(function (item) {
255
        return (item != undefined && item.fullName != undefined);
256
      });
257
    }
258

    
259
    if(this.publicationInfo.relatedResearchResults) {
260
      let self = this;
261
      this.publicationInfo.relatedResearchResults.forEach(function (value, key, map) {
262
        self.publicationInfo.relatedResearchResults.set(key, self.parsingFunctions.sortByPercentage(value));
263
      });
264
    }
265
    this.publicationInfo.similarResearchResults = this.parsingFunctions.sortByPercentage(this.publicationInfo.similarResearchResults);
266

    
267
    return this.publicationInfo;
268
  }
269

    
270
  parseRelatedOrganizations(organizations: {"name": string, "shortname":string, "id": string, "websiteUrl": string, "country": string, "trust": number}[], relation: any):
271
                  {"name": string, "shortname":string, "id": string, "websiteUrl": string, "country": string, "trust": number}[] {
272
    if(organizations == undefined) {
273
      organizations = new Array<{
274
                  "name": string, "shortname": string,
275
                  "id": string, "websiteUrl": string,
276
                  "country": string, "trust": number}>();
277
    }
278

    
279
    let organization: { "name": string, "shortname": string,
280
                        "id": string, "websiteUrl": string,
281
                        "country": string, "trust": number
282
                      } = {
283
                        "name": "", "shortname": "",
284
                        "id": "", "websiteUrl": "",
285
                        "country": "", "trust": null
286
                      };
287

    
288
    organization.id = relation['to'].content;
289
    organization.name = relation.legalname;
290
    organization.shortname = relation.legalshortname;
291
    organization.websiteUrl = relation.websiteurl;
292
    if(relation.country) {
293
      organization.country = relation.country.classname;
294
    }
295
    if(relation.trust) {
296
      organization.trust = Math.round(relation.trust*100);
297
    }
298

    
299
    organizations.push(organization);
300
    return organizations;
301
  }
302

    
303
  parseBioentitiesAndSoftware(children: any) : [Map<string, Map<string, string>>, { "name": string, "url": string}[]] {
304
    let bioentities: Map<string, Map<string, string>>;
305
    let software: {"name": string, "url": string}[];
306

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

    
309
    let externalreference;
310
    for(let i=0; i<length; i++) {
311
      externalreference = Array.isArray(children['externalreference']) ? children['externalreference'][i] : children['externalreference'];
312

    
313
      if(externalreference.hasOwnProperty("qualifier")) {
314
        if(externalreference['qualifier'].classid == "accessionNumber") {
315

    
316
          if(bioentities == undefined) {
317
            bioentities = new Map<string, Map<string, string>>();
318
          }
319

    
320
          if(!bioentities.has(externalreference.sitename)) {
321
            bioentities.set(externalreference.sitename, new Map<string, string>());
322
          }
323
          bioentities.get(externalreference.sitename).set(externalreference.refidentifier, externalreference.url);
324

    
325
        } else if(externalreference['qualifier'].classid == "software") {
326

    
327
          if(software == undefined) {
328
            software = new Array<{"name": string, "url": string}>();
329
          }
330

    
331
          software.push({"name": externalreference.sitename, "url": externalreference.url});
332
        }
333
      }
334
    }
335

    
336
    return [bioentities, software];
337
  }
338
/*
339
  parseReferences(citations: any): {"name": string, "url": string}[] {
340
    let references = new Array<{"name": string, "url": string}>();
341

    
342
    let citation;
343
    let length = Array.isArray(citations) ? citations.length : 1;
344
    for(let i=0; i<length; i++) {
345
      citation = Array.isArray(citations) ? citations[i] : citations;
346

    
347
      let url;
348
      if(citation.hasOwnProperty("id")) {
349
        let citationId;
350
        let length1 = Array.isArray(citation['id']) ? citation['id'].length : 1;
351
        for(let j=0; j<length1; j++) {
352
          citationId = Array.isArray(citation['id']) ? citation['id'][j] : citation['id'];
353

    
354
          if(citationId.type == "pmid") {
355
            url = "http://www.ncbi.nlm.nih.gov/pubmed/"+citationId.value;
356
          }
357
        }
358
      }
359

    
360
      references[citation.position-1] = { "name": "", "url": ""};
361
      references[citation.position-1]['name'] = citation.rawText;
362
      references[citation.position-1]['url'] = url;
363
    }
364
    return references;
365
  }
366
*/
367
  getOpenCitations(id: string, properties:EnvProperties) {
368
    //https://services.openaire.eu/opencitations/getCitations?id=doajarticles::2634200c24772ee8f10232d3e184ec65
369
    let url = properties.openCitationsAPIURL+id;// "https://services.openaire.eu/opencitations/getCitations?id=" + id;
370
    let key = url;
371

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

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

    
382
    let openCitation;
383

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

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

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

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

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

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