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, sortBy: string, 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
        if(sortBy) {
33
          url += "&sortBy=" + sortBy;
34
        }
35
        url += "&page="+(page-1)+"&size="+size+"&format=json";
36

    
37

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

    
45
        let url = properties.searchAPIURLLAst+"publications/"+id+"?format=json";
46

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

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

    
54
        let link = properties.searchAPIURLLAst+"publications";
55

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

    
65

    
66

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

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

    
74
        let link = properties.searchAPIURLLAst+"publications";
75

    
76
        let url = link+"?"+"&format=json&";
77
        var doisParams = "";
78

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

    
85
        }
86
        if(refineParams!= null && refineParams != ''  ) {
87
            url += refineParams;
88
        }
89
        url += "&page="+(page-1)+"&size="+size;
90

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

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

    
107
      if(sortBy) {
108
        let sortOptions = sortBy.split(",");
109
        url += "sortBy "+sortOptions[0]+"/sort."+sortOptions[1]+" ";
110
      }
111

    
112
      url += "&page="+(page-1)+"&size="+size;
113
      url += "&format=json";
114

    
115
      return this.http.get((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)): url)
116
      .map(res => <any> res.json())
117
      //.do(res => console.info(res))
118

    
119
      .map(res => [res['meta'].total, this.parseResults(res['results'])]);
120
    }
121
    searchPublicationsForEntity (params: string, page: number, size: number, properties:EnvProperties):any {
122
        let link = properties.searchAPIURLLAst;
123
        let url = link+params+"/publications"+ "?format=json";
124
        url += "&page="+(page-1)+"&size="+size;
125

    
126

    
127

    
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
    searchPublicationsForDataproviders(params: string, page: number, size: number, properties:EnvProperties):any {
134
        let link = properties.searchAPIURLLAst;
135
        let url = link+params+ "&page="+(page-1)+"&size="+size + "&format=json";
136
        return this.http.get((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)): url)
137
                    .map(res => <any> res.json())
138
                    .map(res => [res['meta'].total, this.parseResults(res['results'])]);
139
    }
140
/*
141
	searchPublicationsCSV (params: string, refineParams:string, page: number, size: number):any {
142

    
143
        let link = properties.searchAPIURLLAst+"publications";
144

    
145
        let url = link+"?";
146
        if(params!= null && params != ''  ) {
147
            url += params;
148
        }
149
        if(refineParams!= null && refineParams != ''  ) {
150
            url += refineParams;
151
        }
152
        url += "&page="+(page-1)+"&size="+size+ "&format=json";
153

    
154

    
155

    
156
        return this.http.get((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)): url)
157
                    .map(res => <any> res.json())
158
                    //.do(res => console.info(res))
159

    
160
                    .map(res => this.parseResultsCSV(res['results']));
161
    }
162
*/
163

    
164
    parseResults(data: any): SearchResult[] {
165
        let results: SearchResult[] = [];
166

    
167
        let length = Array.isArray(data) ? data.length : 1;
168

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

    
172
            var result: SearchResult = new SearchResult();
173
            result.entityType = "publication";
174

    
175
            result.types = new Array<string>();
176
            let types = new Set<string>();
177

    
178
            let instance;
179
            let length = Array.isArray(resData['children']['instance']) ? resData['children']['instance'].length : 1;
180

    
181
            for(let i=0; i<length; i++) {
182
              instance = Array.isArray(resData['children']['instance']) ? resData['children']['instance'][i] : resData['children']['instance'];
183
              this.parsingFunctions.parseTypes(result.types, types, instance);
184
            }
185

    
186
            if(resData['language'] && resData['language'] != null) {
187
              result.languages = new Array<string>();
188

    
189
              if(!Array.isArray(resData['language'])) {
190
                if(resData['language'].classname != "Undetermined" && resData['language'].classname) {
191
                  result.languages.push(resData['language'].classname);
192
                }
193
              } else {
194
                for(let i=0; i<resData['language'].length; i++) {
195
                  if(resData['language'][i].classname != "Undetermined" && resData['language'][i].classname) {
196
                    result.languages.push(resData['language'][i].classname);
197
                  }
198
                }
199
              }
200
            }
201

    
202
            if(resData['country'] && resData['country'] != null) {
203
              result.countriesForResults = new Array<string>();
204

    
205
              if(!Array.isArray(resData['country'])) {
206
                if(resData['country'].classname != "Undetermined" && resData['country'].classname) {
207
                  result.countriesForResults.push(resData['country'].classname);
208
                }
209
              } else {
210
                for(let i=0; i<resData['country'].length; i++) {
211
                  if(resData['country'][i].classname != "Undetermined" && resData['country'][i].classname) {
212
                    result.countriesForResults.push(resData['country'][i].classname);
213
                  }
214
                }
215
              }
216
            }
217

    
218
            result['title'] = {"name": '', "accessMode": '', "sc39": ''};
219

    
220
            if(Array.isArray(resData['title'])) {
221
                // resData['title'][0].hasOwnProperty("content") {
222
                    result['title'].name = resData['title'][0].content;
223
                // }
224
            } else {
225
                // resData['title'].hasOwnProperty("content") {
226
                    result['title'].name = resData['title'].content;
227
                // }
228
            }
229

    
230
            //result['title'].url = OpenaireProperties.getsearchLinkToPublication();
231
            //result['title'].url += Array.isArray(data) ? data[i]['result']['header']['dri:objIdentifier'] : data['result']['header']['dri:objIdentifier'];
232
            result['id'] = Array.isArray(data) ? data[i]['result']['header']['dri:objIdentifier'] : data['result']['header']['dri:objIdentifier'];
233
            if(resData['bestaccessright'] && resData['bestaccessright'].hasOwnProperty("classid")) {
234
                result['title'].accessMode = resData['bestaccessright'].classid;
235
            }
236

    
237
            if(resData['rels'].hasOwnProperty("rel")) {
238
                let relLength = Array.isArray(resData['rels']['rel']) ? resData['rels']['rel'].length : 1;
239

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

    
243
                    if(relation.hasOwnProperty("to")) {
244
                        /*if(relation['to'].class == "hasAuthor") {
245
                            if(result['authors'] == undefined) {
246
                                result['authors'] = new Array<{"name": string, "id": string}>();
247
                            }
248

    
249
                            result['authors'].push({"name": relation.fullname, "id": relation['to'].content});
250
                        } else */if(relation['to'].class == "isProducedBy") {
251
                            result['projects'] = this.parseProjects(result['projects'], relation);
252
                        }
253
                    }
254
                }
255
            }
256

    
257
            if(resData.hasOwnProperty("creator") && resData['creator'] != null) {
258
              if(result['authors'] == undefined) {
259
                result['authors'] = new Array<string>();
260
              }
261

    
262
              let authors = resData['creator'];
263
              let length = Array.isArray(authors) ? authors.length : 1;
264

    
265
              for(let i=0; i<length; i++) {
266
                let author = Array.isArray(authors) ? authors[i] : authors;
267
                result.authors[author.rank-1] = author.content;
268
              }
269
              result.authors = result.authors.filter(function (item) {
270
                return (item != undefined);
271
              });
272
            }
273

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

    
277
            if(!Array.isArray(resData.description)) {
278
                result.description = resData.description;
279
            } else {
280
                result.description = resData.description[0];
281
            }
282

    
283
            if(result.description && result.description.length > this.sizeOfDescription) {
284
                result.description = result.description.substring(0, this.sizeOfDescription) + "...";
285
            }
286

    
287

    
288
            result.embargoEndDate = resData.embargoenddate;
289

    
290
            results.push(result);
291
        }
292

    
293
        return results;
294
    }
295

    
296
    parseProjects(projects: { "id": string, "acronym": string, "title": string,
297
                              "funderShortname": string, "funderName": string,
298
                              "code": string }[], relation: any ) :  {
299
                              "id": string, "acronym": string, "title": string,
300
                              "funderShortname": string, "funderName": string,
301
                              "code": string }[] {
302
      if(projects == undefined) {
303
          projects = new Array<
304
              { "id": string, "acronym": string, "title": string,
305
                "funderShortname": string, "funderName": string,
306
                "code": string
307
              }>();
308
      }
309

    
310
      let countProjects = projects.length;
311

    
312
      projects[countProjects] = {
313
          "id": "", "acronym": "", "title": "",
314
          "funderShortname": "", "funderName": "",
315
          "code": ""
316
      }
317

    
318
      if(relation.title != 'unidentified') {
319
          projects[countProjects]['id'] =
320
              /*OpenaireProperties.getsearchLinkToProject() + */relation['to'].content;
321
          projects[countProjects]['acronym'] = relation.acronym;
322
          projects[countProjects]['title'] = relation.title;
323
          projects[countProjects]['code'] = relation.code;
324
      } else {
325
          projects[countProjects]['id'] = "";
326
          projects[countProjects]['acronym'] = "";
327
          projects[countProjects]['title'] = "";
328
          projects[countProjects]['code'] = "";
329
      }
330

    
331
      if(relation.hasOwnProperty("funding")) {
332
          let fundingLength = Array.isArray(relation['funding']) ? relation['funding'].length : 1;
333

    
334
          for(let z=0; z<fundingLength; z++) {
335
              let fundingData = Array.isArray(relation['funding']) ? relation['funding'][z] : relation['funding'];
336

    
337
              if(fundingData.hasOwnProperty("funder")) {
338
                  projects[countProjects]['funderShortname'] = fundingData['funder'].shortname;
339
                  projects[countProjects]['funderName'] = fundingData['funder'].name;
340
              }
341
          }
342
      }
343

    
344
      return projects;
345
    }
346
/*
347
    parseResultsCSV(data: any): any {
348
        let results: any = [];
349

    
350

    
351
        let length = Array.isArray(data) ? data.length : 1;
352

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

    
356
            var result: any = [];
357

    
358
            if(Array.isArray(resData['title'])) {
359
                result.push(this.quote(resData['title'][0].content));
360
            } else {
361
                result.push(this.quote(resData['title'].content));
362
            }
363

    
364
            var authors: string[] = [];
365
            var projects: string[] = [];
366
            var funder: string = "";
367
            if(resData['rels'].hasOwnProperty("rel")) {
368
                let relLength = Array.isArray(resData['rels']['rel']) ? resData['rels']['rel'].length : 1;
369

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

    
373
                    if(relation.hasOwnProperty("to")) {
374
                        if(relation['to'].class == "hasAuthor") {
375
                            authors.push(relation.fullname);
376
                        } else if(relation['to'].class == "isProducedBy") {
377
                            if(relation.code != "") {
378
                                projects.push(relation.title+" ("+relation.code+")");
379
                            } else {
380
                                projects.push(relation.title);
381
                            }
382

    
383
                            if(relation.hasOwnProperty("funding")) {
384
                                let fundingLength = Array.isArray(relation['funding']) ? relation['funding'].length : 1;
385

    
386
                                for(let z=0; z<fundingLength; z++) {
387
                                    let fundingData = Array.isArray(relation['funding']) ? relation['funding'][z] : relation['funding'];
388

    
389
                                    if(fundingData.hasOwnProperty("funder")) {
390
                                        funder = fundingData['funder'].shortname;
391
                                    }
392
                                }
393
                            }
394

    
395
                        }
396
                    }
397
                }
398
                result.push(this.quote(authors));
399
                var year: string = "";
400
                if(resData.hasOwnProperty("dateofacceptance")) {
401
                    year = resData.dateofacceptance;
402
                }
403
                result.push(year);
404
                var id:string = Array.isArray(data) ? data[i]['result']['header']['dri:objIdentifier'] : data['result']['header']['dri:objIdentifier'];
405
                result.push(this.quote(id));
406
                result.push(funder);
407
                result.push(this.quote(projects));
408
            } else {
409
                result.push(this.quote(''));
410
                var year: string = "";
411
                if(resData.hasOwnProperty("dateofacceptance")) {
412
                    year = resData.dateofacceptance;
413
                }
414
                result.push(year);
415
                var id:string = Array.isArray(data) ? data[i]['result']['header']['dri:objIdentifier'] : data['result']['header']['dri:objIdentifier'];
416
                result.push(this.quote(id));
417
                result.push(funder);
418
                result.push("");
419
            }
420

    
421

    
422
            //result.push(resData.embargoenddate);
423

    
424
            if(resData['bestaccessright'].hasOwnProperty("classid")) {
425
                result.push(this.quote(resData['bestaccessright'].classid));
426
            } else {
427
                result.push("");
428
            }
429

    
430
            results.push(result);
431
        }
432

    
433
        return results;
434
    }
435
*/
436
    parseRefineResults(id: string, data: any): any {
437
        var results:any = [];
438
        if(data.hasOwnProperty("resulthostingdatasource")) {
439
            let length = Array.isArray(data['resulthostingdatasource']) ? data['resulthostingdatasource'].length : 1;
440

    
441
            for(let i=0; i<length; i++) {
442
                let datasource = Array.isArray(data['resulthostingdatasource']) ? data['resulthostingdatasource'][i] : data['resulthostingdatasource'];
443

    
444
                let result: {"name": string, "id": string, "count": number} = {"name": "", "id": "", "count": 0};
445
                result['name'] = datasource.name;
446
                result['id'] = datasource.id.split("||")[0];
447
                //result['url'] = OpenaireProperties.getsearchLinkToDataProvider()+result['id'];
448
                result['count'] = datasource.count;
449

    
450
                if(result['id'] != id && result['name'] != "Unknown Repository") {
451
                    results.push(result);
452
                }
453
            }
454
        }
455
        return results;
456
    }
457

    
458
    numOfPublications(url: string, properties:EnvProperties): any {
459

    
460
      return this.http.get((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)): url)
461
                  .map(res => <any> res.json())
462
                  .map(res => res.total);
463
    }
464

    
465
    numOfEntityPublications(id: string, entity: string, properties:EnvProperties):any {
466
        var parameters: string = "";
467
        if(entity == "project") {
468
          parameters = "projects/"+id+"/publications/count";
469
        } else if(entity == "organization") {
470
          parameters = "organizations/"+id+"/publications/count";
471
        }
472
        let url = properties.searchAPIURLLAst+parameters+"?format=json";
473
        return this.numOfPublications(url, properties);
474
    }
475

    
476
    numOfSearchPublications(params: string, properties:EnvProperties, refineParams:string=null):any {
477
        let url = properties.searchAPIURLLAst+"publications/count?format=json";
478
        if(params != "") {
479
          url += "&q=" + StringUtils.URIEncode(params);
480
        }
481
        if(refineParams!= null && refineParams != ''  ) {
482
            url += refineParams;
483
        }
484
        return this.numOfPublications(url, properties);
485
    }
486
/*
487
    private quote(word: any): string {
488
        return '"'+word+'"';
489
    }
490
*/
491
}
(19-19/21)