Project

General

Profile

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

    
6

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

    
12
@Injectable()
13
export class SearchDatasetsService {
14
    private sizeOfDescription: number = 270;
15
    public parsingFunctions: ParsingFunctions = new ParsingFunctions();
16

    
17
    constructor(private http: HttpClient ) {}
18

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

    
21
        let link = properties.searchAPIURLLAst+"datasets";
22

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

    
35

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

    
41
    }
42
    searchDatasetById (id: string , properties:EnvProperties):any {
43

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

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

    
52
        let link = properties.searchAPIURLLAst+"datasets";
53

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

    
63

    
64

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

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

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

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

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

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

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

    
109
      url += "&page="+(page-1)+"&size="+size;
110
      url += "&format=json";
111

    
112
      return this.http.get((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)): url)
113
      //.map(res => <any> res.json())
114
      //.do(res => console.info(res))
115
      .pipe(map(res => [res['meta'].total, this.parseResults(res['results'], properties)]));
116
    }
117
    searchDatasetsForEntity (params: string, page: number, size: number, properties:EnvProperties):any {
118
        let link = properties.searchAPIURLLAst;
119
        let url = link+params+"/datasets"+"?format=json";
120

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

    
125
    }
126

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

    
134
    }
135

    
136
    parseResults(data: any, properties: EnvProperties): SearchResult[] {
137
        let results: SearchResult[] = [];
138

    
139
        let length = Array.isArray(data) ? data.length : 1;
140

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

    
144
            var result: SearchResult = new SearchResult();
145
            result.entityType = "dataset";
146

    
147
            result.types = new Array<string>();
148
            let types = new Set<string>();
149
            let length = Array.isArray(resData['children']['instance']) ? resData['children']['instance'].length : 1;
150

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

    
157
            if(resData['language'] && resData['language'] != null) {
158
              result.languages = new Array<string>();
159

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

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

    
188
            result['title'] = {"name": '', "accessMode": '', "sc39": ''};
189

    
190
            if(Array.isArray(resData['title'])) {
191
                result['title'].name = String(resData['title'][0].content);
192
            } else {
193
                result['title'].name = String(resData['title'].content);
194
            }
195

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

    
203
            if(resData['rels'].hasOwnProperty("rel")) {
204
                let relLength = Array.isArray(resData['rels']['rel']) ? resData['rels']['rel'].length : 1;
205

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

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

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

    
223
            if(resData.hasOwnProperty("creator") && resData['creator'] != null) {
224
              if(result['authors'] == undefined) {
225
                result['authors'] = new Array<{"fullName": string, "orcid": string}>();
226
              }
227

    
228
              let authors = resData['creator'];
229
              let length = Array.isArray(authors) ? authors.length : 1;
230

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

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

    
256
            result.embargoEndDate = resData.embargoenddate;
257

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

    
270
            results.push(result);
271
        }
272

    
273
        return results;
274
    }
275

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

    
290
      let countProjects = projects.length;
291

    
292
      projects[countProjects] = {
293
          "id": "", "acronym": "", "title": "",
294
          "funderShortname": "", "funderName": "",
295
          "code": ""
296
      }
297

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

    
311
      if(relation.hasOwnProperty("funding")) {
312
          let fundingLength = Array.isArray(relation['funding']) ? relation['funding'].length : 1;
313

    
314
          for(let z=0; z<fundingLength; z++) {
315
              let fundingData = Array.isArray(relation['funding']) ? relation['funding'][z] : relation['funding'];
316

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

    
324
      return projects;
325
    }
326

    
327
    parseRefineResults(id: string, data: any): any {
328
        var results:any = [];
329
        if(data.hasOwnProperty("resulthostingdatasource")) {
330
            let length = Array.isArray(data['resulthostingdatasource']) ? data['resulthostingdatasource'].length : 1;
331

    
332
            for(let i=0; i<length; i++) {
333
                let datasource = Array.isArray(data['resulthostingdatasource']) ? data['resulthostingdatasource'][i] : data['resulthostingdatasource'];
334

    
335
                let result: {"name": string, "id": string, "count": number} = {"name": "", "id": "", "count": 0};
336
                result['name'] = datasource.name;
337
                result['id'] = datasource.id.split("||")[0];
338
                //result['url'] = OpenaireProperties.getsearchLinkToDataProvider()+result['id'];
339
                result['count'] = datasource.count;
340

    
341
                if(result['id'] != id && result['name'] != "Unknown Repository") {
342
                    results.push(result);
343
                }
344
            }
345
        }
346
        return results;
347
    }
348

    
349
    numOfDatasets(url: string, properties:EnvProperties):any {
350

    
351
      return this.http.get((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)): url)
352
                  //.map(res => <any> res.json())
353
                  .pipe(map(res => res['total']));
354
    }
355

    
356
    numOfEntityDatasets(id: string, entity: string, properties:EnvProperties):any {
357
        var parameters = "";
358

    
359
        if(entity == "project") {
360
          parameters = "projects/"+id+"/datasets/count";
361
        } else if(entity == "organization") {
362
          parameters = "organizations/"+id+"/datasets/count";
363
        }
364

    
365
        let url = properties.searchAPIURLLAst+parameters+"?format=json";
366
        return this.numOfDatasets(url, properties);
367
    }
368

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

    
372
        if(params.length > 0){
373
          var DOIs:string[] = DOI.getDOIsFromString(params);
374
          var doisParams = "";
375

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