Project

General

Profile

1
import {Injectable} from '@angular/core';
2
import {Http, Response} from '@angular/http';
3
import {HttpClient} from "@angular/common/http";
4
import {Observable}     from 'rxjs';
5
import {SearchResult}     from '../utils/entities/searchResult';
6
import {RefineResultsUtils} from './servicesUtils/refineResults.class';
7

    
8

    
9

    
10
import {DOI, StringUtils} from '../utils/string-utils.class';
11
import { ParsingFunctions } from '../landingPages/landing-utils/parsingFunctions.class';
12
import{EnvProperties} from '../utils/properties/env-properties';
13
import {map} from "rxjs/operators";
14

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

    
20
    constructor(private http: HttpClient ) {}
21

    
22
    searchDatasets (params: string, refineParams:string, page: number, size: number, sortBy: string, refineFields:string[], properties:EnvProperties ):any {
23

    
24
        let link = properties.searchAPIURLLAst+"datasets";
25

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

    
38

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

    
44
    }
45
    searchDatasetById (id: string , properties:EnvProperties):any {
46

    
47
        let url = properties.searchAPIURLLAst+"datasets/"+id+"?format=json";
48
         return this.http.get((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)): url)
49
                    //.map(res => <any> res.json())
50
                    .pipe(map(res => this.parseResults(res, properties)));
51
    }
52

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

    
55
        let link = properties.searchAPIURLLAst+"datasets";
56

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

    
66

    
67

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

    
73
    searchDatasetsByDois (DOIs: string[], refineParams:string, page: number, size: number, refineFields:string[], properties:EnvProperties ):any {
74
        let link = properties.searchAPIURLLAst+"datasets";
75
        let url = link+"?";
76
        var doisParams = "";
77

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

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

    
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
                    .pipe(map(res => [res['meta'].total, this.parseResults(res['results'], properties),RefineResultsUtils.parse(res['refineResults'],refineFields, "dataset")]));
95

    
96
    }
97
    advancedSearchDatasets (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 dataset)  "
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
      .pipe(map(res => [res['meta'].total, this.parseResults(res['results'], properties)]));
119

    
120
    }
121
    searchDatasetsForEntity (params: string, page: number, size: number, properties:EnvProperties):any {
122
        let link = properties.searchAPIURLLAst;
123
        let url = link+params+"/datasets"+"?format=json";
124

    
125
        return this.http.get((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)): url)
126
                    //.map(res => <any> res.json())
127
                    .pipe(map(res => [res['meta'].total, this.parseResults(res['results'], properties)]));
128

    
129
    }
130

    
131
    searchDatasetsForDataproviders(params: string, page: number, size: number, properties:EnvProperties):any {
132
        let link = properties.searchAPIURLLAst;
133
        let url = link+params+ "&page="+(page-1)+"&size="+size + "&format=json";
134
        return this.http.get((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)): url)
135
                    //.map(res => <any> res.json())
136
                    .pipe(map(res => [res['meta'].total, this.parseResults(res['results'], properties)]));
137

    
138
    }
139

    
140
    parseResults(data: any, properties: EnvProperties): SearchResult[] {
141
        let results: SearchResult[] = [];
142

    
143
        let length = Array.isArray(data) ? data.length : 1;
144

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

    
148
            var result: SearchResult = new SearchResult();
149
            result.entityType = "dataset";
150

    
151
            result.types = new Array<string>();
152
            let types = new Set<string>();
153
            let length = Array.isArray(resData['children']['instance']) ? resData['children']['instance'].length : 1;
154

    
155
            let instance;
156
            for(let i=0; i<length; i++) {
157
              instance = Array.isArray(resData['children']['instance']) ? resData['children']['instance'][i] : resData['children']['instance'];
158
              this.parsingFunctions.parseTypes(result.types, types, instance);
159
            }
160

    
161
            if(resData['language'] && resData['language'] != null) {
162
              result.languages = new Array<string>();
163

    
164
              if(!Array.isArray(resData['language'])) {
165
                if(resData['language'].classname != "Undetermined" && resData['language'].classname) {
166
                  result.languages.push(resData['language'].classname);
167
                }
168
              } else {
169
                for(let i=0; i<resData['language'].length; i++) {
170
                  if(resData['language'][i].classname != "Undetermined" && resData['language'][i].classname) {
171
                    result.languages.push(resData['language'][i].classname);
172
                  }
173
                }
174
              }
175
            }
176
            if(resData['country'] && resData['country'] != null) {
177
              result.countriesForResults = new Array<string>();
178

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

    
192
            result['title'] = {"name": '', "accessMode": '', "sc39": ''};
193

    
194
            if(Array.isArray(resData['title'])) {
195
                result['title'].name = String(resData['title'][0].content);
196
            } else {
197
                result['title'].name = String(resData['title'].content);
198
            }
199

    
200
            //result['title'].url = OpenaireProperties.getsearchLinkToDataset();
201
            //result['title'].url += Array.isArray(data) ? data[i]['result']['header']['dri:objIdentifier'] : data['result']['header']['dri:objIdentifier'];
202
            result['id'] = Array.isArray(data) ? data[i]['result']['header']['dri:objIdentifier'] : data['result']['header']['dri:objIdentifier'];
203
            if(resData['bestaccessright'] && resData['bestaccessright'].hasOwnProperty("classid")) {
204
                result['title'].accessMode = resData['bestaccessright'].classid;
205
            }
206

    
207
            if(resData['rels'].hasOwnProperty("rel")) {
208
                let relLength = Array.isArray(resData['rels']['rel']) ? resData['rels']['rel'].length : 1;
209

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

    
213
                    if(relation.hasOwnProperty("to")) {
214
                        /*if(relation['to'].class == "hasAuthor") {
215
                          if(result['authors'] == undefined) {
216
                            result['authors'] = new Array<{"name": string, "id": string}>();
217
                          }
218

    
219
                          result['authors'].push({"name": relation.fullname, "id": relation['to'].content});
220
                        } else */if(relation['to'].class == "isProducedBy") {
221
                          result['projects'] = this.parseProjects(result['projects'], relation);
222
                        }
223
                    }
224
                }
225
            }
226

    
227
            if(resData.hasOwnProperty("creator") && resData['creator'] != null) {
228
              if(result['authors'] == undefined) {
229
                result['authors'] = new Array<{"fullName": string, "orcid": string}>();
230
              }
231

    
232
              let authors = resData['creator'];
233
              let length = Array.isArray(authors) ? authors.length : 1;
234

    
235
              for(let i=0; i<length; i++) {
236
                let author = Array.isArray(authors) ? authors[i] : authors;
237
                if(author) {
238
                  /*if (author.ORCID && author.ORCID.indexOf(properties.orcidURL) != -1) {
239
                    author.ORCID = author.ORCID.substr(properties.orcidURL.length);
240
                  }*/
241
                  result['authors'][author.rank] = {"fullName": author.content, "orcid": author.ORCID};
242
                }
243
              }
244
              result.authors = result.authors.filter(function (item) {
245
                return (item != undefined && item.fullName != undefined);
246
              });
247
            }
248

    
249
            var date:string = (resData.dateofacceptance)+""; // transform to string in case it is an integer
250
            result.year = (date && (date).indexOf('-') !== -1)?date.split('-')[0]:date;
251
            if(!Array.isArray(resData.description)) {
252
                result.description = String(resData.description);
253
            } else {
254
                result.description = String(resData.description[0]);
255
            }
256
            if(result.description && result.description.length > this.sizeOfDescription) {
257
                result.description = result.description.substring(0, this.sizeOfDescription)+"...";
258
            }
259

    
260
            result.embargoEndDate = resData.embargoenddate;
261

    
262
            if(!Array.isArray(resData.publisher)) {
263
                result.publisher = resData.publisher;
264
            } else {
265
                for(let i=0; i<resData.publisher.length; i++) {
266
                    if(result.publisher != undefined){
267
                        result.publisher += ', '+resData['publisher'][i];
268
                    } else {
269
                        result.publisher = resData['publisher'][i];
270
                    }
271
                }
272
            }
273

    
274
            results.push(result);
275
        }
276

    
277
        return results;
278
    }
279

    
280
    parseProjects(projects: { "id": string, "acronym": string, "title": string,
281
                              "funderShortname": string, "funderName": string,
282
                              "code": string }[], relation: any ) :  {
283
                              "id": string, "acronym": string, "title": string,
284
                              "funderShortname": string, "funderName": string,
285
                              "code": string }[] {
286
      if(projects == undefined) {
287
          projects = new Array<
288
              { "id": string, "acronym": string, "title": string,
289
                "funderShortname": string, "funderName": string,
290
                "code": string
291
              }>();
292
      }
293

    
294
      let countProjects = projects.length;
295

    
296
      projects[countProjects] = {
297
          "id": "", "acronym": "", "title": "",
298
          "funderShortname": "", "funderName": "",
299
          "code": ""
300
      }
301

    
302
      if(relation.title != 'unidentified') {
303
          projects[countProjects]['id'] =
304
              /*OpenaireProperties.getsearchLinkToProject() + */relation['to'].content;
305
          projects[countProjects]['acronym'] = relation.acronym;
306
          projects[countProjects]['title'] = relation.title;
307
          projects[countProjects]['code'] = relation.code;
308
      } else {
309
          projects[countProjects]['id'] = "";
310
          projects[countProjects]['acronym'] = "";
311
          projects[countProjects]['title'] = "";
312
          projects[countProjects]['code'] = "";
313
      }
314

    
315
      if(relation.hasOwnProperty("funding")) {
316
          let fundingLength = Array.isArray(relation['funding']) ? relation['funding'].length : 1;
317

    
318
          for(let z=0; z<fundingLength; z++) {
319
              let fundingData = Array.isArray(relation['funding']) ? relation['funding'][z] : relation['funding'];
320

    
321
              if(fundingData.hasOwnProperty("funder")) {
322
                  projects[countProjects]['funderShortname'] = fundingData['funder'].shortname;
323
                  projects[countProjects]['funderName'] = fundingData['funder'].name;
324
              }
325
          }
326
      }
327

    
328
      return projects;
329
    }
330

    
331
    parseRefineResults(id: string, data: any): any {
332
        var results:any = [];
333
        if(data.hasOwnProperty("resulthostingdatasource")) {
334
            let length = Array.isArray(data['resulthostingdatasource']) ? data['resulthostingdatasource'].length : 1;
335

    
336
            for(let i=0; i<length; i++) {
337
                let datasource = Array.isArray(data['resulthostingdatasource']) ? data['resulthostingdatasource'][i] : data['resulthostingdatasource'];
338

    
339
                let result: {"name": string, "id": string, "count": number} = {"name": "", "id": "", "count": 0};
340
                result['name'] = datasource.name;
341
                result['id'] = datasource.id.split("||")[0];
342
                //result['url'] = OpenaireProperties.getsearchLinkToDataProvider()+result['id'];
343
                result['count'] = datasource.count;
344

    
345
                if(result['id'] != id && result['name'] != "Unknown Repository") {
346
                    results.push(result);
347
                }
348
            }
349
        }
350
        return results;
351
    }
352

    
353
    numOfDatasets(url: string, properties:EnvProperties):any {
354

    
355
      return this.http.get((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)): url)
356
                  //.map(res => <any> res.json())
357
                  .pipe(map(res => res['total']));
358
    }
359

    
360
    numOfEntityDatasets(id: string, entity: string, properties:EnvProperties):any {
361
        var parameters = "";
362

    
363
        if(entity == "project") {
364
          parameters = "projects/"+id+"/datasets/count";
365
        } else if(entity == "organization") {
366
          parameters = "organizations/"+id+"/datasets/count";
367
        }
368

    
369
        let url = properties.searchAPIURLLAst+parameters+"?format=json";
370
        return this.numOfDatasets(url, properties);
371
    }
372

    
373
    numOfSearchDatasets(params: string, properties:EnvProperties, refineParams:string=null):any {
374
        let url = properties.searchAPIURLLAst+"datasets/count?format=json";
375

    
376
        if(params.length > 0){
377
          var DOIs:string[] = DOI.getDOIsFromString(params);
378
          var doisParams = "";
379

    
380
          for(var i =0 ;i < DOIs.length; i++){
381
            doisParams+=(doisParams.length > 0?"&":"")+'doi="'+ DOIs[i]+'"';
382
          }
383
          if(doisParams.length > 0){
384
            url += "&"+doisParams;
385
          }else{
386
            url += "&q=" + StringUtils.URIEncode(params);
387
          }
388
        }
389
        // if(params != "") {
390
        //   url += "&q=" + StringUtils.URIEncode(params);
391
        // }
392
        if(refineParams!= null && refineParams != ''  ) {
393
            url += refineParams;
394
        }
395
        return this.numOfDatasets(url, properties);
396
    }
397
}
(17-17/23)