Project

General

Profile

1
import {Injectable} from '@angular/core';
2
import {Http, Response} from '@angular/http';
3
import {Observable}     from 'rxjs/Observable';
4
import 'rxjs/add/observable/of';
5
import 'rxjs/add/operator/do';
6
import 'rxjs/add/operator/share';
7

    
8
import {SearchResult}     from '../utils/entities/searchResult';
9
import {RefineResultsUtils} from './servicesUtils/refineResults.class';
10
import {StringUtils} from '../utils/string-utils.class';
11
import { ParsingFunctions } from '../landingPages/landing-utils/parsingFunctions.class';
12
import{EnvProperties} from '../utils/properties/env-properties';
13

    
14

    
15
@Injectable()
16
export class SearchPublicationsService {
17
    private sizeOfDescription: number = 270;
18
    public parsingFunctions: ParsingFunctions = new ParsingFunctions();
19

    
20
    constructor(private http: Http ) {}
21

    
22
    searchPublications (params: string, refineParams:string, page: number, size: number, refineFields:string[] , properties:EnvProperties):any {
23
        let link = properties.searchAPIURLLAst+"publications";
24

    
25
        let url = link+"?";
26
        if(params!= null && params != ''  ) {
27
            url += params;
28
        }
29
        if(refineParams!= null && refineParams != ''  ) {
30
            url += refineParams;
31
        }
32
        url += "&page="+(page-1)+"&size="+size+"&format=json";
33

    
34

    
35
        return this.http.get((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)): url)
36
                    .map(res => <any> res.json())
37
                    // .do(res => console.info(res))
38
                    .map(res => [res['meta'].total, this.parseResults(res['results']),RefineResultsUtils.parse(res['refineResults'],refineFields, "publication")]);
39
    }
40
    searchPublicationById (id: string, properties:EnvProperties ):any {
41

    
42
        let url = properties.searchAPIURLLAst+"publications/"+id+"?format=json";
43

    
44
        return this.http.get((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)): url)
45
                    .map(res => <any> res.json())
46
                    .map(res =>  this.parseResults(res));
47
    }
48

    
49
    searchAggregators (id: string, params: string, refineParams:string, page: number, size: number, properties:EnvProperties ):any {
50

    
51
        let link = properties.searchAPIURLLAst+"publications";
52

    
53
        let url = link+"?"+"&format=json";
54
        if(params!= null && params != ''  ) {
55
            url += params;
56
        }
57
        if(refineParams!= null && refineParams != ''  ) {
58
            url += refineParams;
59
        }
60
        url += "&page="+(page-1)+"&size="+size;
61

    
62

    
63

    
64
        return this.http.get((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)): url)
65
                    .map(res => <any> res.json())
66
                    .map(res => this.parseRefineResults(id, res['refineResults']));
67
    }
68

    
69
    searchPublicationsByDois (DOIs: string[], refineParams:string, page: number, size: number, refineFields:string[], properties:EnvProperties ):any {
70

    
71
        let link = properties.searchAPIURLLAst+"publications";
72

    
73
        let url = link+"?"+"&format=json&";
74
        var doisParams = "";
75

    
76
        for(var i =0 ;i < DOIs.length; i++){
77
          doisParams+=(doisParams.length > 0?"&":"")+'doi="'+ DOIs[i]+'"';
78
        }
79
        if(doisParams.length > 0){
80
          url +="&"+doisParams;
81

    
82
        }
83
        if(refineParams!= null && refineParams != ''  ) {
84
            url += refineParams;
85
        }
86
        url += "&page="+(page-1)+"&size="+size;
87

    
88
        return this.http.get((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)): url)
89
                    .map(res => <any> res.json())
90
                    //.do(res => console.info(res))
91
                    .map(res => [res['meta'].total, this.parseResults(res['results']),RefineResultsUtils.parse(res['refineResults'],refineFields, "publication")]);
92
    }
93

    
94
    advancedSearchPublications (params: string, page: number, size: number, properties:EnvProperties ):any {
95
      let url = properties.searchResourcesAPIURL;
96
      var basicQuery = "(oaftype exact result) and (resulttypeid exact publication) ";
97
      url += "?query=";
98
      if(params!= null && params != ''  ) {
99
        url +=" ( "+basicQuery+ " ) " +" and (" + params + ")";
100
      }else{
101
        url +=" ( "+basicQuery+ " ) ";
102
      }
103

    
104
      url += "&page="+(page-1)+"&size="+size;
105
      url += "&format=json";
106

    
107
      return this.http.get((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)): url)
108
      .map(res => <any> res.json())
109
      //.do(res => console.info(res))
110

    
111
      .map(res => [res['meta'].total, this.parseResults(res['results'])]);
112
    }
113
    searchPublicationsForEntity (params: string, page: number, size: number, properties:EnvProperties):any {
114
        let link = properties.searchAPIURLLAst;
115
        let url = link+params+"/publications"+ "?format=json";
116
        url += "&page="+(page-1)+"&size="+size;
117

    
118

    
119

    
120
        return this.http.get((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)): url)
121
                    .map(res => <any> res.json())
122
                    .map(res => [res['meta'].total, this.parseResults(res['results'])]);
123
    }
124

    
125
    searchPublicationsForDataproviders(params: string, page: number, size: number, properties:EnvProperties):any {
126
        let link = properties.searchAPIURLLAst;
127
        let url = link+params+ "&page="+(page-1)+"&size="+size + "&format=json";
128
        return this.http.get((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)): url)
129
                    .map(res => <any> res.json())
130
                    .map(res => [res['meta'].total, this.parseResults(res['results'])]);
131
    }
132
/*
133
	searchPublicationsCSV (params: string, refineParams:string, page: number, size: number):any {
134

    
135
        let link = properties.searchAPIURLLAst+"publications";
136

    
137
        let url = link+"?";
138
        if(params!= null && params != ''  ) {
139
            url += params;
140
        }
141
        if(refineParams!= null && refineParams != ''  ) {
142
            url += refineParams;
143
        }
144
        url += "&page="+(page-1)+"&size="+size+ "&format=json";
145

    
146

    
147

    
148
        return this.http.get((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)): url)
149
                    .map(res => <any> res.json())
150
                    //.do(res => console.info(res))
151

    
152
                    .map(res => this.parseResultsCSV(res['results']));
153
    }
154
*/
155

    
156
    parseResults(data: any): SearchResult[] {
157
        let results: SearchResult[] = [];
158

    
159
        let length = Array.isArray(data) ? data.length : 1;
160

    
161
        for(let i=0; i<length; i++) {
162
            let resData = Array.isArray(data) ? data[i]['result']['metadata']['oaf:entity']['oaf:result'] : data['result']['metadata']['oaf:entity']['oaf:result'];
163

    
164
            var result: SearchResult = new SearchResult();
165
            result.entityType = "publication";
166

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

    
170
            let instance;
171
            let length = Array.isArray(resData['children']['instance']) ? resData['children']['instance'].length : 1;
172

    
173
            for(let i=0; i<length; i++) {
174
              instance = Array.isArray(resData['children']['instance']) ? resData['children']['instance'][i] : resData['children']['instance'];
175
              this.parsingFunctions.parseTypes(result.types, types, instance);
176
            }
177

    
178
            if(resData['language'] && resData['language'] != null) {
179
              result.languages = new Array<string>();
180

    
181
              if(!Array.isArray(resData['language'])) {
182
                if(resData['language'].classname != "Undetermined" && resData['language'].classname) {
183
                  result.languages.push(resData['language'].classname);
184
                }
185
              } else {
186
                for(let i=0; i<resData['language'].length; i++) {
187
                  if(resData['language'][i].classname != "Undetermined" && resData['language'][i].classname) {
188
                    result.languages.push(resData['language'][i].classname);
189
                  }
190
                }
191
              }
192
            }
193

    
194
            if(resData['country'] && resData['country'] != null) {
195
              result.countriesForResults = new Array<string>();
196

    
197
              if(!Array.isArray(resData['country'])) {
198
                if(resData['country'].classname != "Undetermined" && resData['country'].classname) {
199
                  result.countriesForResults.push(resData['country'].classname);
200
                }
201
              } else {
202
                for(let i=0; i<resData['country'].length; i++) {
203
                  if(resData['country'][i].classname != "Undetermined" && resData['country'][i].classname) {
204
                    result.countriesForResults.push(resData['country'][i].classname);
205
                  }
206
                }
207
              }
208
            }
209

    
210
            result['title'] = {"name": '', "accessMode": '', "sc39": ''};
211

    
212
            if(Array.isArray(resData['title'])) {
213
                // resData['title'][0].hasOwnProperty("content") {
214
                    result['title'].name = resData['title'][0].content;
215
                // }
216
            } else {
217
                // resData['title'].hasOwnProperty("content") {
218
                    result['title'].name = resData['title'].content;
219
                // }
220
            }
221

    
222
            //result['title'].url = OpenaireProperties.getsearchLinkToPublication();
223
            //result['title'].url += Array.isArray(data) ? data[i]['result']['header']['dri:objIdentifier'] : data['result']['header']['dri:objIdentifier'];
224
            result['id'] = Array.isArray(data) ? data[i]['result']['header']['dri:objIdentifier'] : data['result']['header']['dri:objIdentifier'];
225
            if(resData['bestaccessright'] && resData['bestaccessright'].hasOwnProperty("classid")) {
226
                result['title'].accessMode = resData['bestaccessright'].classid;
227
            }
228

    
229
            if(resData['rels'].hasOwnProperty("rel")) {
230
                let relLength = Array.isArray(resData['rels']['rel']) ? resData['rels']['rel'].length : 1;
231

    
232
                for(let j=0; j<relLength; j++) {
233
                    let relation = Array.isArray(resData['rels']['rel']) ? resData['rels']['rel'][j] : resData['rels']['rel'];
234

    
235
                    if(relation.hasOwnProperty("to")) {
236
                        /*if(relation['to'].class == "hasAuthor") {
237
                            if(result['authors'] == undefined) {
238
                                result['authors'] = new Array<{"name": string, "id": string}>();
239
                            }
240

    
241
                            result['authors'].push({"name": relation.fullname, "id": relation['to'].content});
242
                        } else */if(relation['to'].class == "isProducedBy") {
243
                            result['projects'] = this.parseProjects(result['projects'], relation);
244
                        }
245
                    }
246
                }
247
            }
248

    
249
            if(resData.hasOwnProperty("creator") && resData['creator'] != null) {
250
              if(result['authors'] == undefined) {
251
                result['authors'] = new Array<string>();
252
              }
253

    
254
              let authors = resData['creator'];
255
              let length = Array.isArray(authors) ? authors.length : 1;
256

    
257
              for(let i=0; i<length; i++) {
258
                let author = Array.isArray(authors) ? authors[i] : authors;
259
                result.authors[author.rank-1] = author.content;
260
              }
261
              result.authors = result.authors.filter(function (item) {
262
                return (item != undefined);
263
              });
264
            }
265

    
266
            var date:string = (resData.dateofacceptance)+""; // transform to string in case it is an integer
267
            result.year = (date && (date).indexOf('-') !== -1)?date.split('-')[0]:date;
268

    
269
            if(!Array.isArray(resData.description)) {
270
                result.description = resData.description;
271
            } else {
272
                result.description = resData.description[0];
273
            }
274

    
275
            if(result.description && result.description.length > this.sizeOfDescription) {
276
                result.description = result.description.substring(0, this.sizeOfDescription) + "...";
277
            }
278

    
279

    
280
            result.embargoEndDate = resData.embargoenddate;
281

    
282
            results.push(result);
283
        }
284

    
285
        return results;
286
    }
287

    
288
    parseProjects(projects: { "id": string, "acronym": string, "title": string,
289
                              "funderShortname": string, "funderName": string,
290
                              "code": string }[], relation: any ) :  {
291
                              "id": string, "acronym": string, "title": string,
292
                              "funderShortname": string, "funderName": string,
293
                              "code": string }[] {
294
      if(projects == undefined) {
295
          projects = new Array<
296
              { "id": string, "acronym": string, "title": string,
297
                "funderShortname": string, "funderName": string,
298
                "code": string
299
              }>();
300
      }
301

    
302
      let countProjects = projects.length;
303

    
304
      projects[countProjects] = {
305
          "id": "", "acronym": "", "title": "",
306
          "funderShortname": "", "funderName": "",
307
          "code": ""
308
      }
309

    
310
      if(relation.title != 'unidentified') {
311
          projects[countProjects]['id'] =
312
              /*OpenaireProperties.getsearchLinkToProject() + */relation['to'].content;
313
          projects[countProjects]['acronym'] = relation.acronym;
314
          projects[countProjects]['title'] = relation.title;
315
          projects[countProjects]['code'] = relation.code;
316
      } else {
317
          projects[countProjects]['id'] = "";
318
          projects[countProjects]['acronym'] = "";
319
          projects[countProjects]['title'] = "";
320
          projects[countProjects]['code'] = "";
321
      }
322

    
323
      if(relation.hasOwnProperty("funding")) {
324
          let fundingLength = Array.isArray(relation['funding']) ? relation['funding'].length : 1;
325

    
326
          for(let z=0; z<fundingLength; z++) {
327
              let fundingData = Array.isArray(relation['funding']) ? relation['funding'][z] : relation['funding'];
328

    
329
              if(fundingData.hasOwnProperty("funder")) {
330
                  projects[countProjects]['funderShortname'] = fundingData['funder'].shortname;
331
                  projects[countProjects]['funderName'] = fundingData['funder'].name;
332
              }
333
          }
334
      }
335

    
336
      return projects;
337
    }
338
/*
339
    parseResultsCSV(data: any): any {
340
        let results: any = [];
341

    
342

    
343
        let length = Array.isArray(data) ? data.length : 1;
344

    
345
        for(let i=0; i<length; i++) {
346
            let resData = Array.isArray(data) ? data[i]['result']['metadata']['oaf:entity']['oaf:result'] : data['result']['metadata']['oaf:entity']['oaf:result'];
347

    
348
            var result: any = [];
349

    
350
            if(Array.isArray(resData['title'])) {
351
                result.push(this.quote(resData['title'][0].content));
352
            } else {
353
                result.push(this.quote(resData['title'].content));
354
            }
355

    
356
            var authors: string[] = [];
357
            var projects: string[] = [];
358
            var funder: string = "";
359
            if(resData['rels'].hasOwnProperty("rel")) {
360
                let relLength = Array.isArray(resData['rels']['rel']) ? resData['rels']['rel'].length : 1;
361

    
362
                for(let j=0; j<relLength; j++) {
363
                    let relation = Array.isArray(resData['rels']['rel']) ? resData['rels']['rel'][j] : resData['rels']['rel'];
364

    
365
                    if(relation.hasOwnProperty("to")) {
366
                        if(relation['to'].class == "hasAuthor") {
367
                            authors.push(relation.fullname);
368
                        } else if(relation['to'].class == "isProducedBy") {
369
                            if(relation.code != "") {
370
                                projects.push(relation.title+" ("+relation.code+")");
371
                            } else {
372
                                projects.push(relation.title);
373
                            }
374

    
375
                            if(relation.hasOwnProperty("funding")) {
376
                                let fundingLength = Array.isArray(relation['funding']) ? relation['funding'].length : 1;
377

    
378
                                for(let z=0; z<fundingLength; z++) {
379
                                    let fundingData = Array.isArray(relation['funding']) ? relation['funding'][z] : relation['funding'];
380

    
381
                                    if(fundingData.hasOwnProperty("funder")) {
382
                                        funder = fundingData['funder'].shortname;
383
                                    }
384
                                }
385
                            }
386

    
387
                        }
388
                    }
389
                }
390
                result.push(this.quote(authors));
391
                var year: string = "";
392
                if(resData.hasOwnProperty("dateofacceptance")) {
393
                    year = resData.dateofacceptance;
394
                }
395
                result.push(year);
396
                var id:string = Array.isArray(data) ? data[i]['result']['header']['dri:objIdentifier'] : data['result']['header']['dri:objIdentifier'];
397
                result.push(this.quote(id));
398
                result.push(funder);
399
                result.push(this.quote(projects));
400
            } else {
401
                result.push(this.quote(''));
402
                var year: string = "";
403
                if(resData.hasOwnProperty("dateofacceptance")) {
404
                    year = resData.dateofacceptance;
405
                }
406
                result.push(year);
407
                var id:string = Array.isArray(data) ? data[i]['result']['header']['dri:objIdentifier'] : data['result']['header']['dri:objIdentifier'];
408
                result.push(this.quote(id));
409
                result.push(funder);
410
                result.push("");
411
            }
412

    
413

    
414
            //result.push(resData.embargoenddate);
415

    
416
            if(resData['bestaccessright'].hasOwnProperty("classid")) {
417
                result.push(this.quote(resData['bestaccessright'].classid));
418
            } else {
419
                result.push("");
420
            }
421

    
422
            results.push(result);
423
        }
424

    
425
        return results;
426
    }
427
*/
428
    parseRefineResults(id: string, data: any): any {
429
        var results:any = [];
430
        if(data.hasOwnProperty("resulthostingdatasource")) {
431
            let length = Array.isArray(data['resulthostingdatasource']) ? data['resulthostingdatasource'].length : 1;
432

    
433
            for(let i=0; i<length; i++) {
434
                let datasource = Array.isArray(data['resulthostingdatasource']) ? data['resulthostingdatasource'][i] : data['resulthostingdatasource'];
435

    
436
                let result: {"name": string, "id": string, "count": number} = {"name": "", "id": "", "count": 0};
437
                result['name'] = datasource.name;
438
                result['id'] = datasource.id.split("||")[0];
439
                //result['url'] = OpenaireProperties.getsearchLinkToDataProvider()+result['id'];
440
                result['count'] = datasource.count;
441

    
442
                if(result['id'] != id && result['name'] != "Unknown Repository") {
443
                    results.push(result);
444
                }
445
            }
446
        }
447
        return results;
448
    }
449

    
450
    numOfPublications(url: string, properties:EnvProperties): any {
451

    
452
      return this.http.get((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)): url)
453
                  .map(res => <any> res.json())
454
                  .map(res => res.total);
455
    }
456

    
457
    numOfEntityPublications(id: string, entity: string, properties:EnvProperties):any {
458
        var parameters: string = "";
459
        if(entity == "project") {
460
          parameters = "projects/"+id+"/publications/count";
461
        } else if(entity == "organization") {
462
          parameters = "organizations/"+id+"/publications/count";
463
        }
464
        let url = properties.searchAPIURLLAst+parameters+"?format=json";
465
        return this.numOfPublications(url, properties);
466
    }
467

    
468
    numOfSearchPublications(params: string, properties:EnvProperties, refineParams:string=null):any {
469
        let url = properties.searchAPIURLLAst+"publications/count?format=json";
470
        if(params != "") {
471
          url += "&q=" + StringUtils.URIEncode(params);
472
        }
473
        if(refineParams!= null && refineParams != ''  ) {
474
            url += refineParams;
475
        }
476
        return this.numOfPublications(url, properties);
477
    }
478
/*
479
    private quote(word: any): string {
480
        return '"'+word+'"';
481
    }
482
*/
483
}
(19-19/21)