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
import { CacheService  } from '../shared/cache.service';
8

    
9
import {OpenaireProperties} from '../utils/properties/openaireProperties';
10
import {SearchResult}     from '../utils/entities/searchResult';
11
import {RefineResultsUtils} from './servicesUtils/refineResults.class';
12

    
13
@Injectable()
14
export class SearchPublicationsService {
15
    private sizeOfDescription: number = 270;
16

    
17
    constructor(private http: Http, public _cache: CacheService) {}
18

    
19
    searchPublications (params: string, refineParams:string, page: number, size: number, refineFields:string[] ):any {
20
        let link = OpenaireProperties.getSearchAPIURLLast()+"publications";
21

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

    
31
        let key = url;
32
        if (this._cache.has(key)) {
33
          return Observable.of(this._cache.get(key)).map(res => [res['meta'].total, this.parseResults(res['results']),RefineResultsUtils.parse(res['refineResults'],refineFields, "publication")]);
34
        }
35

    
36
        return this.http.get(url)
37
                    .map(res => <any> res.json())
38
                    // .do(res => console.info(res))
39
                    .do(res => {
40
                      this._cache.set(key, res);
41
                    })
42
                    .map(res => [res['meta'].total, this.parseResults(res['results']),RefineResultsUtils.parse(res['refineResults'],refineFields, "publication")]);
43
    }
44
    searchPublicationById (id: string ):any {
45

    
46
        let url = OpenaireProperties.getSearchAPIURLLast()+"publications/"+id+"?format=json";
47
        let key =url+"-searchById";
48
        if (this._cache.has(key)) {
49
          return Observable.of(this._cache.get(key)).map(res => this.parseResults(res));
50
        }
51
        return this.http.get(url)
52
                    .map(res => <any> res.json())
53
                    .do(res => {
54
                      this._cache.set(key, res);
55
                    })
56
                    .map(res =>  this.parseResults(res));
57
    }
58

    
59
    searchAggregators (id: string, params: string, refineParams:string, page: number, size: number ):any {
60

    
61
        let link = OpenaireProperties.getSearchAPIURLLast()+"publications";
62

    
63
        let url = link+"?"+"&format=json";
64
        if(params!= null && params != ''  ) {
65
            url += params;
66
        }
67
        if(refineParams!= null && refineParams != ''  ) {
68
            url += refineParams;
69
        }
70
        url += "&page="+(page-1)+"&size="+size;
71

    
72
        let key = url;
73
        if (this._cache.has(key)) {
74
          return Observable.of(this._cache.get(key)).map(res => this.parseRefineResults(id, res['refineResults']));
75
        }
76

    
77
        return this.http.get(url)
78
                    .map(res => <any> res.json())
79
                    .do(res => {
80
                      this._cache.set(key, res);
81
                    })
82
                    .map(res => this.parseRefineResults(id, res['refineResults']));
83
    }
84

    
85
    searchPublicationsByDois (DOIs: string[], refineParams:string, page: number, size: number, refineFields:string[] ):any {
86

    
87
        let link = OpenaireProperties.getSearchAPIURLLast()+"publications";
88

    
89
        let url = link+"?"+"&format=json&";
90
        var doisParams = "";
91

    
92
        for(var i =0 ;i < DOIs.length; i++){
93
          doisParams+=(doisParams.length > 0?"&":"")+'doi="'+ DOIs[i]+'"';
94
        }
95
        if(doisParams.length > 0){
96
          url +="&"+doisParams;
97

    
98
        }
99
        if(refineParams!= null && refineParams != ''  ) {
100
            url += refineParams;
101
        }
102
        url += "&page="+(page-1)+"&size="+size;
103

    
104
        let key = url;
105
        if (this._cache.has(key)) {
106
          return Observable.of(this._cache.get(key)).map(res => [res['meta'].total, this.parseResults(res['results']),RefineResultsUtils.parse(res['refineResults'],refineFields, "publication")]);
107
        }
108

    
109
        return this.http.get(url)
110
                    .map(res => <any> res.json())
111
                    //.do(res => console.info(res))
112
                    .do(res => {
113
                      this._cache.set(key, res);
114
                    })
115
                    .map(res => [res['meta'].total, this.parseResults(res['results']),RefineResultsUtils.parse(res['refineResults'],refineFields, "publication")]);
116
    }
117

    
118
    advancedSearchPublications (params: string, page: number, size: number ):any {
119
      let url = OpenaireProperties.getSearchResourcesAPIURL();
120
      var basicQuery = "(oaftype exact result) and (resulttypeid exact publication) ";
121
      url += "?query=";
122
      if(params!= null && params != ''  ) {
123
        url +=" ( "+basicQuery+ " ) " +" and (" + params + ")";
124
      }else{
125
        url +=" ( "+basicQuery+ " ) ";
126
      }
127

    
128
      url += "&page="+(page-1)+"&size="+size;
129
      url += "&format=json";
130
      let key = url;
131
      if (this._cache.has(key)) {
132
        return Observable.of(this._cache.get(key)).map(res => [res['meta'].total, this.parseResults(res['results'])]);
133
      }
134
      return this.http.get(url)
135
      .map(res => <any> res.json())
136
      //.do(res => console.info(res))
137
      .do(res => {
138
        this._cache.set(key, res);
139
      })
140
      .map(res => [res['meta'].total, this.parseResults(res['results'])]);
141
    }
142
    searchPublicationsForEntity (params: string, page: number, size: number):any {
143
        let link = OpenaireProperties.getSearchAPIURLLast();
144
        let url = link+params+"/publications"+ "?format=json";
145
        url += "&page="+(page-1)+"&size="+size;
146

    
147
        let key = url;
148
        if (this._cache.has(key)) {
149
          return Observable.of(this._cache.get(key)).map(res => [res['meta'].total, this.parseResults(res['results'])]);
150
        }
151

    
152
        return this.http.get(url)
153
                    .map(res => <any> res.json())
154
                    .do(res => {
155
                      this._cache.set(key, res);
156
                    })
157
                    .map(res => [res['meta'].total, this.parseResults(res['results'])]);
158
    }
159

    
160
    searchPublicationsForDataproviders(params: string, page: number, size: number):any {
161
        let link = OpenaireProperties.getSearchAPIURLLast();
162
        let url = link+params+ "&page="+(page-1)+"&size="+size + "&format=json";
163
        let key = url;
164
        if (this._cache.has(key)) {
165
          return Observable.of(this._cache.get(key)).map(res => [res['meta'].total, this.parseResults(res['results'])]);
166
        }
167
        return this.http.get(url)
168
                    .map(res => <any> res.json())
169
                    .do(res => {
170
                      this._cache.set(key, res);
171
                    })
172
                    .map(res => [res['meta'].total, this.parseResults(res['results'])]);
173
    }
174
/*
175
	searchPublicationsCSV (params: string, refineParams:string, page: number, size: number):any {
176

    
177
        let link = OpenaireProperties.getSearchAPIURLLast()+"publications";
178

    
179
        let url = link+"?";
180
        if(params!= null && params != ''  ) {
181
            url += params;
182
        }
183
        if(refineParams!= null && refineParams != ''  ) {
184
            url += refineParams;
185
        }
186
        url += "&page="+(page-1)+"&size="+size+ "&format=json";
187

    
188
        let key = url;
189
        if (this._cache.has(key)) {
190
          return Observable.of(this._cache.get(key)).map(res => this.parseResultsCSV(res['results']));
191
        }
192

    
193
        return this.http.get(url)
194
                    .map(res => <any> res.json())
195
                    //.do(res => console.info(res))
196
                    .do(res => {
197
                      this._cache.set(key, res);
198
                    })
199
                    .map(res => this.parseResultsCSV(res['results']));
200
    }
201
*/
202

    
203
    parseResults(data: any): SearchResult[] {
204
        let results: SearchResult[] = [];
205

    
206
        let length = Array.isArray(data) ? data.length : 1;
207

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

    
211
            var result: SearchResult = new SearchResult();
212

    
213
            result['title'] = {"name": '', "accessMode": '', "sc39": ''};
214

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

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

    
232
            if(resData['rels'].hasOwnProperty("rel")) {
233
                let relLength = Array.isArray(resData['rels']['rel']) ? resData['rels']['rel'].length : 1;
234

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

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

    
244
                            result['authors'].push({"name": relation.fullname, "id": /*OpenaireProperties.getsearchLinkToPerson()+*/relation['to'].content});
245
                        } else if(relation['to'].class == "isProducedBy") {
246
                            result['projects'] = this.parseProjects(result['projects'], relation);
247
                        }
248
                    }
249
                }
250
            }
251
            var date:string = (resData.dateofacceptance)+""; // transform to string in case it is an integer
252
            result.year = (date && (date).indexOf('-') !== -1)?date.split('-')[0]:date;
253

    
254
            if(!Array.isArray(resData.description)) {
255
                result.description = resData.description;
256
            } else {
257
                result.description = resData.description[0];
258
            }
259

    
260
            if(result.description.length > this.sizeOfDescription) {
261
                result.description = result.description.substring(0, this.sizeOfDescription) + "...";
262
            }
263

    
264

    
265
            result.embargoEndDate = resData.embargoenddate;
266

    
267
            results.push(result);
268
        }
269

    
270
        return results;
271
    }
272

    
273
    parseProjects(projects: { "id": string, "acronym": string, "title": string,
274
                              "funderShortname": string, "funderName": string,
275
                              "code": string }[], relation: any ) :  {
276
                              "id": string, "acronym": string, "title": string,
277
                              "funderShortname": string, "funderName": string,
278
                              "code": string }[] {
279
      if(projects == undefined) {
280
          projects = new Array<
281
              { "id": string, "acronym": string, "title": string,
282
                "funderShortname": string, "funderName": string,
283
                "code": string
284
              }>();
285
      }
286

    
287
      let countProjects = projects.length;
288

    
289
      projects[countProjects] = {
290
          "id": "", "acronym": "", "title": "",
291
          "funderShortname": "", "funderName": "",
292
          "code": ""
293
      }
294

    
295
      if(relation.title != 'unidentified') {
296
          projects[countProjects]['id'] =
297
              /*OpenaireProperties.getsearchLinkToProject() + */relation['to'].content;
298
          projects[countProjects]['acronym'] = relation.acronym;
299
          projects[countProjects]['title'] = relation.title;
300
          projects[countProjects]['code'] = relation.code;
301
      } else {
302
          projects[countProjects]['id'] = "";
303
          projects[countProjects]['acronym'] = "";
304
          projects[countProjects]['title'] = "";
305
          projects[countProjects]['code'] = "";
306
      }
307

    
308
      if(relation.hasOwnProperty("funding")) {
309
          let fundingLength = Array.isArray(relation['funding']) ? relation['funding'].length : 1;
310

    
311
          for(let z=0; z<fundingLength; z++) {
312
              let fundingData = Array.isArray(relation['funding']) ? relation['funding'][z] : relation['funding'];
313

    
314
              if(fundingData.hasOwnProperty("funder")) {
315
                  projects[countProjects]['funderShortname'] = fundingData['funder'].shortname;
316
                  projects[countProjects]['funderName'] = fundingData['funder'].name;
317
              }
318
          }
319
      }
320

    
321
      return projects;
322
    }
323
/*
324
    parseResultsCSV(data: any): any {
325
        let results: any = [];
326

    
327

    
328
        let length = Array.isArray(data) ? data.length : 1;
329

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

    
333
            var result: any = [];
334

    
335
            if(Array.isArray(resData['title'])) {
336
                result.push(this.quote(resData['title'][0].content));
337
            } else {
338
                result.push(this.quote(resData['title'].content));
339
            }
340

    
341
            var authors: string[] = [];
342
            var projects: string[] = [];
343
            var funder: string = "";
344
            if(resData['rels'].hasOwnProperty("rel")) {
345
                let relLength = Array.isArray(resData['rels']['rel']) ? resData['rels']['rel'].length : 1;
346

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

    
350
                    if(relation.hasOwnProperty("to")) {
351
                        if(relation['to'].class == "hasAuthor") {
352
                            authors.push(relation.fullname);
353
                        } else if(relation['to'].class == "isProducedBy") {
354
                            if(relation.code != "") {
355
                                projects.push(relation.title+" ("+relation.code+")");
356
                            } else {
357
                                projects.push(relation.title);
358
                            }
359

    
360
                            if(relation.hasOwnProperty("funding")) {
361
                                let fundingLength = Array.isArray(relation['funding']) ? relation['funding'].length : 1;
362

    
363
                                for(let z=0; z<fundingLength; z++) {
364
                                    let fundingData = Array.isArray(relation['funding']) ? relation['funding'][z] : relation['funding'];
365

    
366
                                    if(fundingData.hasOwnProperty("funder")) {
367
                                        funder = fundingData['funder'].shortname;
368
                                    }
369
                                }
370
                            }
371

    
372
                        }
373
                    }
374
                }
375
                result.push(this.quote(authors));
376
                var year: string = "";
377
                if(resData.hasOwnProperty("dateofacceptance")) {
378
                    year = resData.dateofacceptance;
379
                }
380
                result.push(year);
381
                var id:string = Array.isArray(data) ? data[i]['result']['header']['dri:objIdentifier'] : data['result']['header']['dri:objIdentifier'];
382
                result.push(this.quote(id));
383
                result.push(funder);
384
                result.push(this.quote(projects));
385
            } else {
386
                result.push(this.quote(''));
387
                var year: string = "";
388
                if(resData.hasOwnProperty("dateofacceptance")) {
389
                    year = resData.dateofacceptance;
390
                }
391
                result.push(year);
392
                var id:string = Array.isArray(data) ? data[i]['result']['header']['dri:objIdentifier'] : data['result']['header']['dri:objIdentifier'];
393
                result.push(this.quote(id));
394
                result.push(funder);
395
                result.push("");
396
            }
397

    
398

    
399
            //result.push(resData.embargoenddate);
400

    
401
            if(resData['bestlicense'].hasOwnProperty("classid")) {
402
                result.push(this.quote(resData['bestlicense'].classid));
403
            } else {
404
                result.push("");
405
            }
406

    
407
            results.push(result);
408
        }
409

    
410
        return results;
411
    }
412
*/
413
    parseRefineResults(id: string, data: any): any {
414
        var results:any = [];
415
        if(data.hasOwnProperty("resulthostingdatasource")) {
416
            let length = Array.isArray(data['resulthostingdatasource']) ? data['resulthostingdatasource'].length : 1;
417

    
418
            for(let i=0; i<length; i++) {
419
                let datasource = Array.isArray(data['resulthostingdatasource']) ? data['resulthostingdatasource'][i] : data['resulthostingdatasource'];
420

    
421
                let result: {"name": string, "id": string, "count": number} = {"name": "", "id": "", "count": 0};
422
                result['name'] = datasource.name;
423
                result['id'] = datasource.id.split("||")[0];
424
                //result['url'] = OpenaireProperties.getsearchLinkToDataProvider()+result['id'];
425
                result['count'] = datasource.count;
426

    
427
                if(result['id'] != id && result['name'] != "Unknown Repository") {
428
                    results.push(result);
429
                }
430
            }
431
        }
432
        return results;
433
    }
434

    
435
    numOfPublications(url: string): any {
436
      let key = url;
437
      if (this._cache.has(key)) {
438
        return Observable.of(this._cache.get(key));
439
      }
440
      return this.http.get(url)
441
                  .map(res => <any> res.json())
442
                  .map(res => res.total)
443
                  .do(res => {
444
                    this._cache.set(key, res);
445
                  });
446
    }
447

    
448
    numOfEntityPublications(id: string, entity: string):any {
449
        var parameters: string = "";
450
        if(entity == "project") {
451
          parameters = "projects/"+id+"/publications/count";
452
        }
453
        let url = OpenaireProperties.getSearchAPIURLLast()+parameters+"?format=json";
454
        return this.numOfPublications(url);
455
    }
456

    
457
    numOfSearchPublications(params: string):any {
458
        let url = OpenaireProperties.getSearchAPIURLLast()+"publications/count?format=json";
459
        if(params != "") {
460
          url += "&q=" + params;
461
        }
462
        return this.numOfPublications(url);
463
    }
464
/*
465
    private quote(word: any): string {
466
        return '"'+word+'"';
467
    }
468
*/
469
}
(18-18/18)