Project

General

Profile

1

    
2
import {Injectable} from '@angular/core';
3
import {Http, Response} from '@angular/http';
4
import {HttpClient, HttpErrorResponse} from "@angular/common/http";
5
import {Observable, throwError} from 'rxjs';
6
import {PublicationInfo} from '../../utils/entities/publicationInfo';
7
import {DeletedByInferenceResult} from '../../utils/entities/deletedByInferenceResult';
8

    
9

    
10

    
11

    
12
import{EnvProperties} from '../../utils/properties/env-properties';
13

    
14

    
15
import { ParsingFunctions } from '../landing-utils/parsingFunctions.class';
16
import {map} from "rxjs/operators";
17

    
18
@Injectable()
19
export class PublicationService {
20

    
21
  constructor(private http: HttpClient ) {
22
    this.parsingFunctions = new ParsingFunctions();
23
  }
24

    
25
  public parsingFunctions: ParsingFunctions;
26
  publicationInfo: PublicationInfo;
27

    
28
  getPublicationInfo (id: string, properties:EnvProperties):any {
29
    let url = properties.searchAPIURLLAst + 'publications/' +id+"?format=json";
30
    let key = url;
31

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

    
55
  private handleError (error: HttpErrorResponse) {
56
  // in a real world app, we may send the error to some remote logging infrastructure
57
  // instead of just logging it to the console
58
    console.log(error);
59
    return throwError(error  || 'Server error');
60
  }
61

    
62
  parsePublicationInfo (data: any, properties: EnvProperties):any {
63
    this.publicationInfo = new PublicationInfo();
64
    this.publicationInfo.record = data[14];
65
    if(data[0] != null) {
66
      var date:string = (data[0].dateofacceptance)+""; // transform to string in case it is an integer
67
      this.publicationInfo.date  = (date && (date).indexOf('-') !== -1)?date.split('-')[0]:date;
68
      this.publicationInfo.dateofacceptance = data[0].dateofacceptance;
69
      this.publicationInfo.publisher = data[0].publisher;
70
      if(!Array.isArray(data[0].description)) {
71
          this.publicationInfo.description = String(data[0].description);
72
      } else {
73
          this.publicationInfo.description = String(data[0].description[0]);
74
      }
75
      this.publicationInfo.embargoEndDate = data[0].embargoenddate;
76
    }
77

    
78
/*
79
    this.publicationInfo.title = {"name": "", "url": "", "accessMode": ""};
80
    if(data[0]['bestaccessright'] && data[0]['bestaccessright'].hasOwnProperty("classid")) {
81
      this.publicationInfo.title.accessMode = data[0]['bestaccessright'].classid;
82
    }
83

    
84
    if(data[1] != null) {
85
      if(Array.isArray(data[1])) {
86
        this.publicationInfo.title['name'] = data[1][0].content;
87
      } else {
88
        this.publicationInfo.title['name'] = data[1].content;
89
      }
90
    }
91
*/
92
    if(data[0]['bestaccessright'] && data[0]['bestaccessright'].hasOwnProperty("classid")) {
93
      this.publicationInfo.accessMode = data[0]['bestaccessright'].classid;
94
    }
95
    if(data[1] != null) {
96
      if(Array.isArray(data[1])) {
97
        this.publicationInfo.title = String(data[1][0].content);
98
      } else {
99
        this.publicationInfo.title = String(data[1].content);
100
      }
101
    }
102

    
103
    if(data[2] != null) {
104
      let relation;
105
      let length = Array.isArray(data[2]) ? data[2].length : 1;
106

    
107
      for(let i=0; i<length; i++) {
108
        relation = Array.isArray(data[2]) ? data[2][i] : data[2];
109
        if(relation.hasOwnProperty("to")) {
110
          if(relation['to'].class == "isProducedBy") {
111
            this.publicationInfo.fundedByProjects = this.parsingFunctions.parseFundingByProjects(this.publicationInfo.fundedByProjects, relation, this.publicationInfo.projectsProvenanceVocabulary);
112
          } else if(relation['to'].class == "isRelatedTo") {
113
            let provenanceAction: string;
114
            if(relation.provenanceaction in this.publicationInfo.researchResultsProvenanceVocabulary) {
115
              provenanceAction = this.publicationInfo.researchResultsProvenanceVocabulary[relation.provenanceaction];
116
            } else {
117
              provenanceAction = "Other";
118
            }
119

    
120
            this.publicationInfo.relatedResearchResults = this.parsingFunctions.parseRelatedResearchResults(this.publicationInfo.relatedResearchResults, relation, provenanceAction);
121
          } else if(relation['to'].class == "hasAmongTopNSimilarDocuments") {
122
            this.publicationInfo.similarResearchResults = this.parsingFunctions.parseSimilarResearchResults(this.publicationInfo.similarResearchResults, relation);
123
          } else if(relation['to'].class == "hasAuthorInstitution") {
124
            this.publicationInfo.organizations = this.parseRelatedOrganizations(this.publicationInfo.organizations, relation);
125
          }
126
        }
127
      }
128
    }
129

    
130
    if(data[3] != null) {
131
      if(data[3].hasOwnProperty("result")) {
132
        this.publicationInfo.deletedByInferenceIds = [];
133
        let length = Array.isArray(data[3]['result']) ? data[3]['result'].length : 1;
134

    
135
        for(let i=0; i<length; i++) {
136
          let result = Array.isArray(data[3]['result']) ? data[3]['result'][i] : data[3]['result'];
137
          this.publicationInfo.deletedByInferenceIds.push(result.objidentifier);
138
        }
139

    
140
      }
141

    
142
      if(data[3].hasOwnProperty("instance")) {
143
        //this.publicationInfo.collectedFrom = new Array<{"name": string, "id": string}>();
144
        //this.publicationInfo.downloadFrom = new Map<string, {"url": string[], "accessMode": string[], "bestAccessMode": string}>();
145
        //this.publicationInfo.publishedIn = new Map<string, {"url": string[], "accessMode": string[], "bestAccessMode": string}>();
146

    
147

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

    
150

    
151
        this.publicationInfo.types = new Array<string>();
152
        let types = new Set<string>();
153

    
154
        let counter = 0;
155
        let instance;
156

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

    
159
        for(let i=0; i<length; i++) {
160
          instance = Array.isArray(data[3]['instance']) ? data[3]['instance'][i] : data[3]['instance'];
161

    
162
          this.parsingFunctions.parseTypes(this.publicationInfo.types, types, instance);
163

    
164
          if(instance.hasOwnProperty("webresource")) {
165
            let url;
166
            if(!Array.isArray(instance['webresource'])) {
167
              url = instance['webresource'].url;
168
            } else{
169
              url = instance['webresource'][0].url;
170
            }
171

    
172
            /**********************************************************/
173
            if(instance.hasOwnProperty("hostedby")) {
174
              counter = this.parsingFunctions.parseHostedBy_collectedFrom(this.publicationInfo.hostedBy_collectedFrom, instance, data[0], url, counter/*, this.publicationInfo.title*/, this.publicationInfo.accessMode);
175
            }
176
            /**********************************************************/
177
          }
178
        }
179
      }
180

    
181
      if(data[3].hasOwnProperty("externalreference")) {
182
        let externalResults: [Map<string, Map<string, string>>, { "name": string, "url": string}[]] = this.parseBioentitiesAndSoftware(data[3]);
183
        this.publicationInfo.bioentities = externalResults[0];
184
        this.publicationInfo.software = externalResults[1];
185
      }
186
    }
187

    
188
    if(data[4] != null) {
189
      this.publicationInfo.identifiers = this.parsingFunctions.parseIdentifiers(data[4]);
190
    }
191

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

    
195
      this.publicationInfo.journal['journal'] = data[5].content;
196
      this.publicationInfo.journal['issn'] = data[5].issn;
197
      this.publicationInfo.journal['lissn'] = data[5].lissn;
198
      this.publicationInfo.journal['eissn'] = data[5].eissn;
199
      this.publicationInfo.journal['issue'] = data[5].iss;
200
      this.publicationInfo.journal['volume'] = data[5].vol;
201
      this.publicationInfo.journal['start_page'] = data[5].sp;
202
      this.publicationInfo.journal['end_page'] = data[5].ep;
203
    }
204

    
205
    if(data[6] != null) {
206
      this.publicationInfo.languages = this.parsingFunctions.parseLanguages(data[6]);
207
    }
208
    if(data[15] != null) {
209
      this.publicationInfo.countries = this.parsingFunctions.parseCountries(data[15]);
210
    }
211

    
212
    if(data[7] != null) {
213
      let subjectResults: [string[], Map<string, string[]>, Map<string, string[]>] = this.parsingFunctions.parseAllSubjects(data[7]);
214
      this.publicationInfo.subjects = subjectResults[0];
215
      this.publicationInfo.otherSubjects = subjectResults[1];
216
      this.publicationInfo.classifiedSubjects = subjectResults[2];
217
    }
218

    
219
    // if(data[8] != null) {
220
    //     this.publicationInfo.bestaccessright = data[8].classid;
221
    // }
222

    
223
    // if(data[9] != null) {
224
    //   this.publicationInfo.collectedFrom = this.parsingFunctions.parseCollectedFrom(data[9]);
225
    // }
226

    
227
    this.publicationInfo.hostedBy_collectedFrom = this.parsingFunctions.addPublisherToHostedBy_collectedFrom(
228
                this.publicationInfo.hostedBy_collectedFrom, this.publicationInfo.publisher,
229
                this.publicationInfo.journal, this.publicationInfo.identifiers/*,
230
                this.publicationInfo.title*/);
231

    
232
    if(data[10] != null) {
233
      this.publicationInfo.references = this.parsingFunctions.parseReferences(data[10]);
234
    }
235

    
236
    if(data[11] != null) {
237
      this.publicationInfo.contexts = this.parsingFunctions.parseContexts(data[11]);
238
    }
239

    
240
    if(data[12] != null && data[12] == "under curation") {
241
      this.publicationInfo.underCurationMessage = true;
242
    } else {
243
      this.publicationInfo.underCurationMessage = false;
244
    }
245

    
246
    if(data[13] != null) {
247
      if(this.publicationInfo.authors == undefined) {
248
        this.publicationInfo.authors = new Array<{"fullName": string, "orcid": string}>();
249
      }
250

    
251
      let authors = data[13];
252
      let length = Array.isArray(authors) ? authors.length : 1;
253

    
254
      for(let i=0; i<length; i++) {
255
        let author = Array.isArray(authors) ? authors[i] : authors;
256
        if(author) {
257
          /*if (author.ORCID && author.ORCID.indexOf(properties.orcidURL) != -1) {
258
            author.ORCID = author.ORCID.substr(properties.orcidURL.length);
259
          }*/
260
          this.publicationInfo['authors'][author.rank] = {"fullName": author.content, "orcid": author.ORCID};
261
        }
262
      }
263
      this.publicationInfo.authors = this.publicationInfo.authors.filter(function (item) {
264
        return (item != undefined && item.fullName != undefined);
265
      });
266
    }
267

    
268
    if(this.publicationInfo.relatedResearchResults) {
269
      let self = this;
270
      this.publicationInfo.relatedResearchResults.forEach(function (value, key, map) {
271
        self.publicationInfo.relatedResearchResults.set(key, self.parsingFunctions.sortByPercentage(value));
272
      });
273
    }
274
    this.publicationInfo.similarResearchResults = this.parsingFunctions.sortByPercentage(this.publicationInfo.similarResearchResults);
275

    
276
    return this.publicationInfo;
277
  }
278

    
279
  parseRelatedOrganizations(organizations: {"name": string, "shortname":string, "id": string, "websiteUrl": string, "country": string, "trust": number}[], relation: any):
280
                  {"name": string, "shortname":string, "id": string, "websiteUrl": string, "country": string, "trust": number}[] {
281
    if(organizations == undefined) {
282
      organizations = new Array<{
283
                  "name": string, "shortname": string,
284
                  "id": string, "websiteUrl": string,
285
                  "country": string, "trust": number}>();
286
    }
287

    
288
    let organization: { "name": string, "shortname": string,
289
                        "id": string, "websiteUrl": string,
290
                        "country": string, "trust": number
291
                      } = {
292
                        "name": "", "shortname": "",
293
                        "id": "", "websiteUrl": "",
294
                        "country": "", "trust": null
295
                      };
296

    
297
    organization.id = relation['to'].content;
298
    organization.name = relation.legalname;
299
    organization.shortname = relation.legalshortname;
300
    organization.websiteUrl = relation.websiteurl;
301
    if(relation.country) {
302
      organization.country = relation.country.classname;
303
    }
304
    if(relation.trust) {
305
      organization.trust = Math.round(relation.trust*100);
306
    }
307

    
308
    organizations.push(organization);
309
    return organizations;
310
  }
311

    
312
  parseBioentitiesAndSoftware(children: any) : [Map<string, Map<string, string>>, { "name": string, "url": string}[]] {
313
    let bioentities: Map<string, Map<string, string>>;
314
    let software: {"name": string, "url": string}[];
315

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

    
318
    let externalreference;
319
    for(let i=0; i<length; i++) {
320
      externalreference = Array.isArray(children['externalreference']) ? children['externalreference'][i] : children['externalreference'];
321

    
322
      if(externalreference.hasOwnProperty("qualifier")) {
323
        if(externalreference['qualifier'].classid == "accessionNumber") {
324

    
325
          if(bioentities == undefined) {
326
            bioentities = new Map<string, Map<string, string>>();
327
          }
328

    
329
          if(!bioentities.has(externalreference.sitename)) {
330
            bioentities.set(externalreference.sitename, new Map<string, string>());
331
          }
332
          bioentities.get(externalreference.sitename).set(externalreference.refidentifier, externalreference.url);
333

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

    
336
          if(software == undefined) {
337
            software = new Array<{"name": string, "url": string}>();
338
          }
339

    
340
          software.push({"name": externalreference.sitename, "url": externalreference.url});
341
        }
342
      }
343
    }
344

    
345
    return [bioentities, software];
346
  }
347
/*
348
  parseReferences(citations: any): {"name": string, "url": string}[] {
349
    let references = new Array<{"name": string, "url": string}>();
350

    
351
    let citation;
352
    let length = Array.isArray(citations) ? citations.length : 1;
353
    for(let i=0; i<length; i++) {
354
      citation = Array.isArray(citations) ? citations[i] : citations;
355

    
356
      let url;
357
      if(citation.hasOwnProperty("id")) {
358
        let citationId;
359
        let length1 = Array.isArray(citation['id']) ? citation['id'].length : 1;
360
        for(let j=0; j<length1; j++) {
361
          citationId = Array.isArray(citation['id']) ? citation['id'][j] : citation['id'];
362

    
363
          if(citationId.type == "pmid") {
364
            url = "http://www.ncbi.nlm.nih.gov/pubmed/"+citationId.value;
365
          }
366
        }
367
      }
368

    
369
      references[citation.position-1] = { "name": "", "url": ""};
370
      references[citation.position-1]['name'] = citation.rawText;
371
      references[citation.position-1]['url'] = url;
372
    }
373
    return references;
374
  }
375
*/
376
  getOpenCitations(id: string, properties:EnvProperties) {
377
    //https://services.openaire.eu/opencitations/getCitations?id=doajarticles::2634200c24772ee8f10232d3e184ec65
378
    let url = properties.openCitationsAPIURL+id;// "https://services.openaire.eu/opencitations/getCitations?id=" + id;
379
    let key = url;
380

    
381
    //return this.http.get((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)): url)
382
    return this.http.get(url)
383
                //.map(res => <any> res.json())
384
                .pipe(map(res => [res['total'], this.parseOpenCitations(res['results'])]));
385
  }
386

    
387
  parseOpenCitations(openCitations: any): {"url": string, "title": string, "year": string, "doi": string, "authors": string[]}[] {
388
    //title, doi, authors
389
    let citations = new Array<{"url": string, "title": string, "year": string, "doi": string, "authors": string[]}>();
390

    
391
    let openCitation;
392

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

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

    
399
      if(openCitation && openCitation.id) {
400
        citation.url = openCitation.id;
401
        citation.title = openCitation.title;
402
        //citation.type = openCitation.type;
403
        citation.year = (openCitation.pubDate && (openCitation.pubDate).indexOf('-') !== -1)?openCitation.pubDate.split('-')[0]:openCitation.pubDate;
404
        citation.doi = openCitation.doi;
405

    
406
        let authorsLength = Array.isArray(openCitation.authors) ? openCitation.authors.length : 1;
407
        for(let i=0; i<authorsLength; i++) {
408
          let author = Array.isArray(openCitation.authors) ? openCitation.authors[i] : openCitation.authors;
409

    
410
          if(author) {
411
            let lastFirstName: string = "";
412
            if(author.lastName) {
413
              lastFirstName = author.lastName;
414
            }
415
            if(author.lastName && author.firstName) {
416
              lastFirstName += ", ";
417
            }
418
            if(author.firstName) {
419
              lastFirstName += author.firstName;
420
            }
421

    
422
            if(lastFirstName) {
423
              citation.authors.push(lastFirstName);
424
            }
425
          }
426
        }
427
        citations.push(citation);
428
      }
429
    }
430
    return citations;
431
  }
432
}
(5-5/5)