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
import {DOI, StringUtils} from '../utils/string-utils.class';
6
import {ParsingFunctions} from '../landingPages/landing-utils/parsingFunctions.class';
7
import {EnvProperties} from '../utils/properties/env-properties';
8
import {map} from "rxjs/operators";
9

    
10

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

    
16
    constructor(private http: HttpClient ) {}
17

    
18
    search (resultType:string, params: string, refineParams:string, page: number, size: number, sortBy: string, refineFields:string[] , properties:EnvProperties):any {
19
        let link = properties.searchAPIURLLAst+this.getEntityName(resultType,true);
20

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

    
33
        return this.http.get((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)): url)
34
                    .pipe(map(res => [res['meta'].total, this.parseResults('ss', res['results'], properties),RefineResultsUtils.parse(res['refineResults'],refineFields, "publication")]));
35
    }
36

    
37
    searchById (resultType:string, id: string, properties:EnvProperties ):any {
38
        let url = properties.searchAPIURLLAst+this.getEntityName(resultType,true) +"/"+id+"?format=json";
39

    
40
        return this.http.get((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)): url)
41
                    .pipe(map(res =>  this.parseResults(resultType, res, properties)));
42
    }
43

    
44
    searchAggregators (resultType:string, id: string, params: string, refineParams:string, page: number, size: number, properties:EnvProperties ):any {
45
        let link = properties.searchAPIURLLAst+this.getEntityName(resultType,true);
46

    
47
        let url = link+"?"+"&format=json";
48
        if(params!= null && params != ''  ) {
49
            url += params;
50
        }
51
        if(refineParams!= null && refineParams != ''  ) {
52
            url += refineParams;
53
        }
54
        url += "&page="+(page-1)+"&size="+size;
55

    
56
        return this.http.get((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)): url)
57
                    .pipe(map(res => this.parseRefineResults(id, res['refineResults'])));
58
    }
59

    
60
    searchByListOfDOI (resultType:string, DOIs: string[], refineParams:string, page: number, size: number, refineFields:string[], properties:EnvProperties ):any {
61
        let link = properties.searchAPIURLLAst+ this.getEntityName(resultType,true);
62

    
63
        let url = link+"?"+"&format=json&";
64
        var doisParams = "";
65

    
66
        for(var i =0 ;i < DOIs.length; i++){
67
          doisParams+=(doisParams.length > 0?"&":"")+'doi="'+ DOIs[i]+'"';
68
        }
69
        if(doisParams.length > 0){
70
          url +="&"+doisParams;
71

    
72
        }
73
        if(refineParams!= null && refineParams != ''  ) {
74
            url += refineParams;
75
        }
76
        url += "&page="+(page-1)+"&size="+size;
77

    
78
        return this.http.get((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)): url)
79
                    .pipe(map(res => [res['meta'].total, this.parseResults(resultType, res['results'], properties),RefineResultsUtils.parse(res['refineResults'],refineFields, "publication")]));
80
    }
81

    
82
    advancedSearch (resultType:string, params: string, page: number, size: number, sortBy: string, properties:EnvProperties, refineParams:string=null,  refineFields:string[] =null, refineQuery:string = null ):any {
83
      let url = properties.searchResourcesAPIURL;
84
      var basicQuery = "(oaftype exact result) and (resulttypeid exact "+this.getEntityName(resultType,false) + ") ";
85
      url += "?query=";
86
      if(params!= null && params != ''  ) {
87
        url +=" ( "+basicQuery+ " ) " +" and (" + params + ")";
88
      }else{
89
        url +=" ( "+basicQuery+ " ) ";
90
      }
91
      if(refineParams!= null && refineParams != ''  ) {
92
        url += refineParams;
93
      }
94
      if(sortBy) {
95
        let sortOptions = sortBy.split(",");
96
        url += "sortBy "+sortOptions[0]+"/sort."+sortOptions[1]+" ";
97
      }
98
      if(refineQuery) {
99
        url += "&" + refineQuery;
100
      }
101

    
102
      url += "&page="+(page-1)+"&size="+size;
103
      url += "&format=json";
104

    
105
      return this.http.get((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)): url)
106
      .pipe(map(res => [res['meta'].total, this.parseResults(resultType, res['results'], properties),RefineResultsUtils.parse(res['refineResults'],refineFields, "publication")]));
107
    }
108
  advancedSearchResults (resultType:string, params: string, page: number, size: number, sortBy: string, properties:EnvProperties, refineParams:string=null,  refineFields:string[] =null, refineQuery:string = null ):any {
109
    let url = properties.searchAPIURLLAst+"resources2/?format=json";
110
    if(params!= null && params != ''  ) {
111
      url +="&query=(" + params + ")";
112
    }
113
    if(sortBy) {
114
      let sortOptions = sortBy.split(",");
115
      url += (params ? " " : "&query=(*) ")+"sortBy "+sortOptions[0]+"/sort."+sortOptions[1]+(params ? " " : " ");
116
    }
117
    if(refineParams!= null && refineParams != ''  ) {
118
      url += refineParams;
119
    }
120
    if(refineQuery) {
121
      url += "&" + refineQuery;
122
    }
123

    
124
    url += "&page="+(page-1)+"&size="+size;
125
    // url += "&format=json";
126

    
127
    return this.http.get((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)): url)
128
      .pipe(map(res => [res['meta'].total, this.parseResults(resultType, res['results'], properties),RefineResultsUtils.parse(res['refineResults'],refineFields, "publication")]));
129
  }
130

    
131
    searchResultForEntity (resultType:string, params: string, page: number, size: number, properties:EnvProperties):any {
132
        let link = properties.searchAPIURLLAst;
133
        let url = link+params+"/"+this.getEntityName(resultType,true)+ "?format=json";
134
        url += "&page="+(page-1)+"&size="+size;
135

    
136
        return this.http.get((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)): url)
137
                    .pipe(map(res => [res['meta'].total, this.parseResults(resultType, res['results'], properties)]));
138
    }
139
//???? why different from above?
140
    searchForDataproviders(resultType:string, params: string, page: number, size: number, properties:EnvProperties):any {
141
        let link = properties.searchAPIURLLAst;
142
        let url = link+params+ "&page="+(page-1)+"&size="+size + "&format=json";
143
        return this.http.get((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)): url)
144
                    .pipe(map(res => [res['meta'].total, this.parseResults(resultType, res['results'], properties)]));
145
    }
146

    
147
    parseResults(resultType:string, data: any, properties: EnvProperties): SearchResult[] {
148
        let results: SearchResult[] = [];
149

    
150
        let length = Array.isArray(data) ? data.length : 1;
151

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

    
155
            var result: SearchResult = new SearchResult();
156
            if(resData['resulttype']) {
157
              result.entityType = resData['resulttype']['classname'];
158
            } else {
159
              result.entityType = resultType;
160
            }
161
            result.types = new Array<string>();
162
            let types = new Set<string>();
163

    
164
            let instance;
165
            let length = Array.isArray(resData['children']['instance']) ? resData['children']['instance'].length : 1;
166

    
167
            for(let i=0; i<length; i++) {
168
              instance = Array.isArray(resData['children']['instance']) ? resData['children']['instance'][i] : resData['children']['instance'];
169
              this.parsingFunctions.parseTypes(result.types, types, instance);
170
            }
171

    
172
            if(resData['programmingLanguage'] && resData['programmingLanguage'] != null) {
173
              result.programmingLanguages = new Array<string>();
174

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

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

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

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

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

    
220
            result['title'] = {"name": '', "accessMode": '', "sc39": ''};
221

    
222
            if(Array.isArray(resData['title'])) {
223
                result['title'].name = (resData['title'][0] && resData['title'][0].content) ? String(resData['title'][0].content) : "";
224
            } else {
225
                result['title'].name = (resData['title'] && resData['title'].content) ? String(resData['title'].content) : "";
226
            }
227

    
228
            result['id'] = Array.isArray(data) ? data[i]['result']['header']['dri:objIdentifier'] : data['result']['header']['dri:objIdentifier'];
229
            if(resData['bestaccessright'] && resData['bestaccessright'].hasOwnProperty("classname")) {
230
                result['title'].accessMode = resData['bestaccessright'].classname;
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 == "isProducedBy") {
240
                            result['projects'] = this.parseProjects(result['projects'], relation);
241
                        }
242
                    }
243
                }
244
            }
245

    
246
            if(resData.hasOwnProperty("creator") && resData['creator'] != null) {
247
              if(result['authors'] == undefined) {
248
                result['authors'] = new Array<{"fullName": string, "orcid": string}>();
249
              }
250

    
251
              let authors = resData['creator'];
252
              let length = Array.isArray(authors) ? authors.length : 1;
253

    
254
              for(let i=0; i<length; i++) {
255
                let author = Array.isArray(authors) ? authors[i] : authors;
256
                if(author) {
257
                  result['authors'][author.rank] = {"fullName": author.content, "orcid": author.ORCID};
258
                }
259
              }
260
              result.authors = result.authors.filter(function (item) {
261
                return (item != undefined && item.fullName != undefined);
262
              });
263
            }
264

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

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

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

    
278
            if(resData.embargoenddate && resData.embargoenddate != '') {
279
              result.embargoEndDate = new Date(resData.embargoenddate);
280
            }
281

    
282
            if(!Array.isArray(resData.publisher)) {
283
              result.publisher = resData.publisher;
284
            } else {
285
              for(let i=0; i<resData.publisher.length; i++) {
286
                if(result.publisher != undefined){
287
                  result.publisher += ', '+resData['publisher'][i];
288
                } else {
289
                  result.publisher = resData['publisher'][i];
290
                }
291
              }
292
            }
293

    
294
            results.push(result);
295
        }
296

    
297
        return results;
298
    }
299

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

    
314
      let countProjects = projects.length;
315

    
316
      projects[countProjects] = {
317
          "id": "", "acronym": "", "title": "",
318
          "funderShortname": "", "funderName": "",
319
          "code": ""
320
      };
321

    
322
      if(relation.title != 'unidentified') {
323
          projects[countProjects]['id'] = relation['to'].content;
324
          projects[countProjects]['acronym'] = relation.acronym;
325
          projects[countProjects]['title'] = relation.title;
326
          projects[countProjects]['code'] = relation.code;
327
      } else {
328
          projects[countProjects]['id'] = "";
329
          projects[countProjects]['acronym'] = "";
330
          projects[countProjects]['title'] = "";
331
          projects[countProjects]['code'] = "";
332
      }
333

    
334
      if(relation.hasOwnProperty("funding")) {
335
          let fundingLength = Array.isArray(relation['funding']) ? relation['funding'].length : 1;
336

    
337
          for(let z=0; z<fundingLength; z++) {
338
              let fundingData = Array.isArray(relation['funding']) ? relation['funding'][z] : relation['funding'];
339

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

    
347
      return projects;
348
    }
349
    parseRefineResults(id: string, data: any): any {
350
        var results:any = [];
351
        if(data.hasOwnProperty("resulthostingdatasource")) {
352
            let length = Array.isArray(data['resulthostingdatasource']) ? data['resulthostingdatasource'].length : 1;
353

    
354
            for(let i=0; i<length; i++) {
355
                let datasource = Array.isArray(data['resulthostingdatasource']) ? data['resulthostingdatasource'][i] : data['resulthostingdatasource'];
356

    
357
                let result: {"name": string, "id": string, "count": number} = {"name": "", "id": "", "count": 0};
358
                result['name'] = datasource.name;
359
                result['id'] = datasource.id.split("||")[0];
360
                result['count'] = datasource.count;
361

    
362
                if(result['id'] != id && result['name'] != "Unknown Repository") {
363
                    results.push(result);
364
                }
365
            }
366
        }
367
        return results;
368
    }
369

    
370
    private numOfResults(url: string, properties:EnvProperties): any {
371
      return this.http.get((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)): url)
372
                  .pipe(map(res => res['total']));
373
    }
374

    
375
    numOfEntityResults(resultType:string, id: string, entity: string, properties:EnvProperties):any {
376
        var parameters: string = "";
377
        parameters = this.getEntityName(entity, true) + "/"+id+"/"+this.getEntityName(resultType, true)+"/count";
378
        let url = properties.searchAPIURLLAst+parameters+"?format=json";
379
        return this.numOfResults(url , properties);
380
    }
381
  numOfResearchOutcomes( params: string, properties:EnvProperties, refineParams:string=null):any {
382
    let url = properties.searchAPIURLLAst+"resources2/?format=json&size=0&type=publications&type=datasets&type=software&type=other";
383
    if(params.length > 0){
384
      var DOIs:string[] = DOI.getDOIsFromString(params);
385
      var doisParams = "";
386

    
387
      for(var i =0 ;i < DOIs.length; i++){
388
        doisParams+=(doisParams.length > 0?"&":"")+'doi="'+ DOIs[i]+'"';
389
      }
390
      if(doisParams.length > 0){
391
        url += "&"+doisParams;
392
      }else{
393
        url += "&q=" + StringUtils.URIEncode(params);
394
      }
395
    }
396

    
397
    if(refineParams!= null && refineParams != ''  ) {
398
      url += refineParams;
399
    }
400
    return this.http.get((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)): url)
401
      .pipe(map(res => res['meta']['total']));
402
  }
403
    numOfSearchResults(resultType:string, params: string, properties:EnvProperties, refineParams:string=null):any {
404
        let url = properties.searchAPIURLLAst+this.getEntityName(resultType, true)+"/count?format=json";
405
        if(params.length > 0){
406
          var DOIs:string[] = DOI.getDOIsFromString(params);
407
          var doisParams = "";
408

    
409
          for(var i =0 ;i < DOIs.length; i++){
410
            doisParams+=(doisParams.length > 0?"&":"")+'doi="'+ DOIs[i]+'"';
411
          }
412
          if(doisParams.length > 0){
413
            url += "&"+doisParams;
414
          }else{
415
            url += "&q=" + StringUtils.URIEncode(params);
416
          }
417
        }
418

    
419
        if(refineParams!= null && refineParams != ''  ) {
420
            url += refineParams;
421
        }
422
        return this.numOfResults(url, properties);
423
    }
424
  numOfSearchResultsLinkedToPub(resultType:string, properties:EnvProperties):any {
425
    let url = properties.searchAPIURLLAst+"resources?query="+encodeURIComponent("( (oaftype exact result) and (resulttypeid exact "+resultType+") and (relresulttype=publication)  )")+"&page=0&size=0&format=json";
426
    return this.http.get((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)): url)
427
      .pipe(map(res => res['meta']['total']));
428
  }
429

    
430
    countTotalResults(resultType:string,  properties:EnvProperties, refineParams:string=null):any {
431
      let url = properties.searchAPIURLLAst+this.getEntityName(resultType, true)+"/count?format=json"+refineParams;
432
      return this.numOfResults(url, properties);
433
    }
434
/*
435
    private quote(word: any): string {
436
        return '"'+word+'"';
437
    }
438
*/
439

    
440
    private getEntityName (entityType:string, plural:boolean){
441
      if(entityType == "publication" ||entityType == "dataset" || entityType == "organization" || entityType == "datasource" || entityType == "project" ){
442
        if(plural){
443
          return entityType+ "s";
444
        }else{
445
          return entityType;
446
        }
447
      }else{
448
        return entityType;
449
      }
450
    }
451
}
(18-18/21)