Project

General

Profile

1

    
2
import {Injectable} from '@angular/core';
3
import {Http, Response} from '@angular/http';
4
import {Observable}     from 'rxjs/Observable';
5
import {PublicationInfo} from '../../utils/entities/publicationInfo';
6
import 'rxjs/add/observable/of';
7
import 'rxjs/add/operator/do';
8
import 'rxjs/add/operator/share';
9
import 'rxjs/add/operator/map';
10
import{EnvProperties} from '../../utils/properties/env-properties';
11

    
12

    
13
import { ParsingFunctions } from '../landing-utils/parsingFunctions.class';
14

    
15
@Injectable()
16
export class PublicationService {
17

    
18
  constructor(private http: Http ) {
19
    this.parsingFunctions = new ParsingFunctions();
20
  }
21

    
22
  public parsingFunctions: ParsingFunctions;
23
  publicationInfo: PublicationInfo;
24

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

    
29
    return this.http.get((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)): url)
30
                .map(res => <any> res.json())
31
                .map(res => [res['result']['header']['dri:status'], res['result']['metadata']['oaf:entity'], res])
32
                .map(res => [ res[1]['oaf:result'],
33
                              res[1]['oaf:result']['title'],
34
                              res[1]['oaf:result']['rels']['rel'],
35
                              res[1]['oaf:result']['children'],
36
                              res[1]['oaf:result']['pid'],
37
                              res[1]['oaf:result']['journal'],
38
                              res[1]['oaf:result']['language'],
39
                              res[1]['oaf:result']['subject'],
40
                              res[1]['oaf:result']['bestaccessright'],
41
                              res[1]['oaf:result']['collectedfrom'],
42
                              (res[1]['extraInfo']!= undefined && res[1]['extraInfo']['citations']!= undefined)? res[1]['extraInfo']['citations']['citation']:null,
43
                              res[1]['oaf:result']['context'],
44
                              res[0],
45
                              res[1]['oaf:result']['creator'],
46
                              res[2],
47
                              res[1]['oaf:result']['country'],
48
                ])
49
                .map(res => this.parsePublicationInfo(res));
50
  }
51

    
52
  private handleError (error: Response) {
53
  // in a real world app, we may send the error to some remote logging infrastructure
54
  // instead of just logging it to the console
55
    console.log(error);
56
    return Observable.throw(error  || 'Server error');
57
  }
58

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

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

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

    
100
    if(data[2] != null) {
101
      let relation;
102
      let length = Array.isArray(data[2]) ? data[2].length : 1;
103

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

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

    
127
    if(data[3] != null) {
128
      if(data[3].hasOwnProperty("instance")) {
129
        //this.publicationInfo.collectedFrom = new Array<{"name": string, "id": string}>();
130
        //this.publicationInfo.downloadFrom = new Map<string, {"url": string[], "accessMode": string[], "bestAccessMode": string}>();
131
        //this.publicationInfo.publishedIn = new Map<string, {"url": string[], "accessMode": string[], "bestAccessMode": string}>();
132

    
133

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

    
136

    
137
        this.publicationInfo.types = new Array<string>();
138
        let types = new Set<string>();
139

    
140
        let counter = 0;
141
        let instance;
142

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

    
145
        for(let i=0; i<length; i++) {
146
          instance = Array.isArray(data[3]['instance']) ? data[3]['instance'][i] : data[3]['instance'];
147

    
148
          this.parsingFunctions.parseTypes(this.publicationInfo.types, types, instance);
149

    
150
          if(instance.hasOwnProperty("webresource")) {
151
            let url;
152
            if(!Array.isArray(instance['webresource'])) {
153
              url = instance['webresource'].url;
154
            } else{
155
              url = instance['webresource'][0].url;
156
            }
157

    
158
            /**********************************************************/
159
            if(instance.hasOwnProperty("hostedby")) {
160
              counter = this.parsingFunctions.parseHostedBy_collectedFrom(this.publicationInfo.hostedBy_collectedFrom, instance, data[0], url, counter/*, this.publicationInfo.title*/, this.publicationInfo.accessMode);
161
            }
162
            /**********************************************************/
163
          }
164
        }
165
      }
166

    
167
      if(data[3].hasOwnProperty("externalreference")) {
168
        let externalResults: [Map<string, Map<string, string>>, { "name": string, "url": string}[]] = this.parseBioentitiesAndSoftware(data[3]);
169
        this.publicationInfo.bioentities = externalResults[0];
170
        this.publicationInfo.software = externalResults[1];
171
      }
172
    }
173

    
174
    if(data[4] != null) {
175
      this.publicationInfo.identifiers = this.parsingFunctions.parseIdentifiers(data[4]);
176
    }
177

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

    
181
      this.publicationInfo.journal['journal'] = data[5].content;
182
      this.publicationInfo.journal['issn'] = data[5].issn;
183
      this.publicationInfo.journal['lissn'] = data[5].lissn;
184
      this.publicationInfo.journal['eissn'] = data[5].eissn;
185
      this.publicationInfo.journal['issue'] = data[5].iss;
186
      this.publicationInfo.journal['volume'] = data[5].vol;
187
      this.publicationInfo.journal['start_page'] = data[5].sp;
188
      this.publicationInfo.journal['end_page'] = data[5].ep;
189
    }
190

    
191
    if(data[6] != null) {
192
      this.publicationInfo.languages = this.parsingFunctions.parseLanguages(data[6]);
193
    }
194
    if(data[15] != null) {
195
      this.publicationInfo.countries = this.parsingFunctions.parseCountries(data[15]);
196
    }
197

    
198
    if(data[7] != null) {
199
      let subjectResults: [string[], Map<string, string[]>, Map<string, string[]>] = this.parsingFunctions.parseAllSubjects(data[7]);
200
      this.publicationInfo.subjects = subjectResults[0];
201
      this.publicationInfo.otherSubjects = subjectResults[1];
202
      this.publicationInfo.classifiedSubjects = subjectResults[2];
203
    }
204

    
205
    // if(data[8] != null) {
206
    //     this.publicationInfo.bestaccessright = data[8].classid;
207
    // }
208

    
209
    // if(data[9] != null) {
210
    //   this.publicationInfo.collectedFrom = this.parsingFunctions.parseCollectedFrom(data[9]);
211
    // }
212

    
213
    this.publicationInfo.hostedBy_collectedFrom = this.parsingFunctions.addPublisherToHostedBy_collectedFrom(
214
                this.publicationInfo.hostedBy_collectedFrom, this.publicationInfo.publisher,
215
                this.publicationInfo.journal, this.publicationInfo.identifiers/*,
216
                this.publicationInfo.title*/);
217

    
218
    if(data[10] != null) {
219
      this.publicationInfo.references = this.parseReferences(data[10]);
220
    }
221

    
222
    if(data[11] != null) {
223
      this.publicationInfo.contexts = this.parsingFunctions.parseContexts(data[11]);
224
    }
225

    
226
    if(data[12] != null && data[12] == "under curation") {
227
      this.publicationInfo.underCurationMessage = true;
228
    } else {
229
      this.publicationInfo.underCurationMessage = false;
230
    }
231

    
232
    if(data[13] != null) {
233
      if(this.publicationInfo.authors == undefined) {
234
        this.publicationInfo.authors = new Array<string>();
235
      }
236

    
237
      let authors = data[13];
238
      let length = Array.isArray(authors) ? authors.length : 1;
239

    
240
      for(let i=0; i<length; i++) {
241
        let author = Array.isArray(authors) ? authors[i] : authors;
242
        this.publicationInfo.authors[author.rank] = author.content;
243
      }
244
      this.publicationInfo.authors = this.publicationInfo.authors.filter(function (item) {
245
        return (item != undefined);
246
      });
247
    }
248

    
249
    if(this.publicationInfo.relatedResearchResults) {
250
      let self = this;
251
      this.publicationInfo.relatedResearchResults.forEach(function (value, key, map) {
252
        self.publicationInfo.relatedResearchResults.set(key, self.parsingFunctions.sortByPercentage(value));
253
      });
254
    }
255
    this.publicationInfo.similarResearchResults = this.parsingFunctions.sortByPercentage(this.publicationInfo.similarResearchResults);
256

    
257
    return this.publicationInfo;
258
  }
259

    
260
  parseRelatedOrganizations(organizations: {"name": string, "shortname":string, "id": string, "websiteUrl": string, "country": string, "trust": number}[], relation: any):
261
                  {"name": string, "shortname":string, "id": string, "websiteUrl": string, "country": string, "trust": number}[] {
262
    if(organizations == undefined) {
263
      organizations = new Array<{
264
                  "name": string, "shortname": string,
265
                  "id": string, "websiteUrl": string,
266
                  "country": string, "trust": number}>();
267
    }
268

    
269
    let organization: { "name": string, "shortname": string,
270
                        "id": string, "websiteUrl": string,
271
                        "country": string, "trust": number
272
                      } = {
273
                        "name": "", "shortname": "",
274
                        "id": "", "websiteUrl": "",
275
                        "country": "", "trust": null
276
                      };
277

    
278
    organization.id = relation['to'].content;
279
    organization.name = relation.legalname;
280
    organization.shortname = relation.legalshortname;
281
    organization.websiteUrl = relation.websiteurl;
282
    if(relation.country) {
283
      organization.country = relation.country.classname;
284
    }
285
    if(relation.trust) {
286
      organization.trust = Math.round(relation.trust*100);
287
    }
288

    
289
    organizations.push(organization);
290
    return organizations;
291
  }
292

    
293
  parseBioentitiesAndSoftware(children: any) : [Map<string, Map<string, string>>, { "name": string, "url": string}[]] {
294
    let bioentities: Map<string, Map<string, string>>;
295
    let software: {"name": string, "url": string}[];
296

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

    
299
    let externalreference;
300
    for(let i=0; i<length; i++) {
301
      externalreference = Array.isArray(children['externalreference']) ? children['externalreference'][i] : children['externalreference'];
302

    
303
      if(externalreference.hasOwnProperty("qualifier")) {
304
        if(externalreference['qualifier'].classid == "accessionNumber") {
305

    
306
          if(bioentities == undefined) {
307
            bioentities = new Map<string, Map<string, string>>();
308
          }
309

    
310
          if(!bioentities.has(externalreference.sitename)) {
311
            bioentities.set(externalreference.sitename, new Map<string, string>());
312
          }
313
          bioentities.get(externalreference.sitename).set(externalreference.refidentifier, externalreference.url);
314

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

    
317
          if(software == undefined) {
318
            software = new Array<{"name": string, "url": string}>();
319
          }
320

    
321
          software.push({"name": externalreference.sitename, "url": externalreference.url});
322
        }
323
      }
324
    }
325

    
326
    return [bioentities, software];
327
  }
328

    
329
  parseReferences(citations: any): {"name": string, "url": string}[] {
330
    let references = new Array<{"name": string, "url": string}>();
331

    
332
    let citation;
333
    let length = Array.isArray(citations) ? citations.length : 1;
334
    for(let i=0; i<length; i++) {
335
      citation = Array.isArray(citations) ? citations[i] : citations;
336

    
337
      let url;
338
      if(citation.hasOwnProperty("id")) {
339
        let citationId;
340
        let length1 = Array.isArray(citation['id']) ? citation['id'].length : 1;
341
        for(let j=0; j<length1; j++) {
342
          citationId = Array.isArray(citation['id']) ? citation['id'][j] : citation['id'];
343

    
344
          if(citationId.type == "pmid") {
345
            url = "http://www.ncbi.nlm.nih.gov/pubmed/"+citationId.value;
346
          }
347
        }
348
      }
349

    
350
      references[citation.position-1] = { "name": "", "url": ""};
351
      references[citation.position-1]['name'] = citation.rawText;
352
      references[citation.position-1]['url'] = url;
353
    }
354
    return references;
355
  }
356

    
357
  getOpenCitations(id: string, properties:EnvProperties) {
358
    //https://services.openaire.eu/opencitations/getCitations?id=doajarticles::2634200c24772ee8f10232d3e184ec65
359
    let url = properties.openCitationsAPIURL+id;// "https://services.openaire.eu/opencitations/getCitations?id=" + id;
360
    let key = url;
361

    
362
    //return this.http.get((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)): url)
363
    return this.http.get(url)
364
                .map(res => <any> res.json())
365
                .map(res => [res['total'], this.parseOpenCitations(res['results'])]);
366
  }
367

    
368
  parseOpenCitations(openCitations: any): {"url": string, "title": string, "year": string, "doi": string, "authors": string[]}[] {
369
    //title, doi, authors
370
    let citations = new Array<{"url": string, "title": string, "year": string, "doi": string, "authors": string[]}>();
371

    
372
    let openCitation;
373

    
374
    let length = Array.isArray(openCitations) ? openCitations.length : 1;
375
    for(let i=0; i<length; i++) {
376
      openCitation = Array.isArray(openCitations) ? openCitations[i] : openCitations;
377

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

    
380
      if(openCitation) {
381
        citation.url = openCitation.id;
382
        citation.title = openCitation.title;
383
        //citation.type = openCitation.type;
384
        citation.year = (openCitation.pubDate && (openCitation.pubDate).indexOf('-') !== -1)?openCitation.pubDate.split('-')[0]:openCitation.pubDate;
385
        citation.doi = openCitation.doi;
386

    
387
        let authorsLength = Array.isArray(openCitation.authors) ? openCitation.authors.length : 1;
388
        for(let i=0; i<authorsLength; i++) {
389
          let author = Array.isArray(openCitation.authors) ? openCitation.authors[i] : openCitation.authors;
390
          let lastFirstName: string = "";
391
          if(author.lastName) {
392
            lastFirstName = author.lastName;
393
          }
394
          if(author.lastName && author.firstName) {
395
            lastFirstName += ", ";
396
          }
397
          if(author.firstName) {
398
            lastFirstName += author.firstName;
399
          }
400

    
401
          if(lastFirstName) {
402
            citation.authors.push(lastFirstName);
403
          }
404
        }
405
        citations.push(citation);
406
      }
407
    }
408
    return citations;
409
  }
410
}
(5-5/5)