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(resultType, 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
            /////////////////////////// Athena Code ///////////////////////////
172
            if(resData['pid']) {
173
              for(let i=0; i<resData['pid'].length; i++){
174
                if(resData['pid'][i].classid == 'doi'){
175
                  if(resData['pid'][i].content != '' && resData['pid'][i].content != null){
176
                    result.DOI = resData['pid'][i].content.replace("https://doi.org/","");
177
                    break;
178
                  }
179
                }
180
              }
181
            }
182
            /////////////////////////// Athena Code ///////////////////////////
183
            if(resData['programmingLanguage'] && resData['programmingLanguage'] != null) {
184
              result.programmingLanguages = new Array<string>();
185

    
186
              if(!Array.isArray(resData['programmingLanguage'])) {
187
                if(resData['programmingLanguage'].classname != "Undetermined" && resData['programmingLanguage'].classname) {
188
                  result.programmingLanguages.push(resData['programmingLanguage'].classname);
189
                }
190
              } else {
191
                for(let i=0; i<resData['programmingLanguage'].length; i++) {
192
                  if(resData['programmingLanguage'][i].classname != "Undetermined" && resData['programmingLanguage'][i].classname) {
193
                    result.programmingLanguages.push(resData['programmingLanguage'][i].classname);
194
                  }
195
                }
196
              }
197
            }
198

    
199
            if(resData['language'] && resData['language'] != null) {
200
              result.languages = new Array<string>();
201

    
202
              if(!Array.isArray(resData['language'])) {
203
                if(resData['language'].classname != "Undetermined" && resData['language'].classname) {
204
                  result.languages.push(resData['language'].classname);
205
                }
206
              } else {
207
                for(let i=0; i<resData['language'].length; i++) {
208
                  if(resData['language'][i].classname != "Undetermined" && resData['language'][i].classname) {
209
                    result.languages.push(resData['language'][i].classname);
210
                  }
211
                }
212
              }
213
            }
214

    
215
            if(resData['country'] && resData['country'] != null) {
216
              result.countriesForResults = new Array<string>();
217

    
218
              if(!Array.isArray(resData['country'])) {
219
                if(resData['country'].classname != "Undetermined" && resData['country'].classname) {
220
                  result.countriesForResults.push(resData['country'].classname);
221
                }
222
              } else {
223
                for(let i=0; i<resData['country'].length; i++) {
224
                  if(resData['country'][i].classname != "Undetermined" && resData['country'][i].classname) {
225
                    result.countriesForResults.push(resData['country'][i].classname);
226
                  }
227
                }
228
              }
229
            }
230

    
231
            result['title'] = {"name": '', "accessMode": '', "sc39": ''};
232

    
233
            if(Array.isArray(resData['title'])) {
234
                result['title'].name = (resData['title'][0] && resData['title'][0].content) ? String(resData['title'][0].content) : "";
235
            } else {
236
                result['title'].name = (resData['title'] && resData['title'].content) ? String(resData['title'].content) : "";
237
            }
238

    
239
            result['id'] = Array.isArray(data) ? data[i]['result']['header']['dri:objIdentifier'] : data['result']['header']['dri:objIdentifier'];
240
            if(resData['bestaccessright'] && resData['bestaccessright'].hasOwnProperty("classname")) {
241
                result['title'].accessMode = resData['bestaccessright'].classname;
242
            }
243
            if(resData['rels'].hasOwnProperty("rel")) {
244
                let relLength = Array.isArray(resData['rels']['rel']) ? resData['rels']['rel'].length : 1;
245

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

    
249
                    if(relation.hasOwnProperty("to")) {
250
                        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<{"fullName": string, "orcid": 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
                if(author) {
268
                  result['authors'][author.rank] = {"fullName": author.content, "orcid": author.ORCID};
269
                }
270
              }
271
              result.authors = result.authors.filter(function (item) {
272
                return (item != undefined && item.fullName != undefined);
273
              });
274
            }
275

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

    
279
            if(!Array.isArray(resData.description)) {
280
                result.description = (resData.description) ? String(resData.description) : "";
281
            } else {
282
                result.description = (resData.description[0]) ? String(resData.description[0]) : "";
283
            }
284

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

    
289
            if(resData.embargoenddate && resData.embargoenddate != '') {
290
              result.embargoEndDate = new Date(resData.embargoenddate);
291
            }
292

    
293
            if(!Array.isArray(resData.publisher)) {
294
              result.publisher = resData.publisher;
295
            } else {
296
              for(let i=0; i<resData.publisher.length; i++) {
297
                if(result.publisher != undefined){
298
                  result.publisher += ', '+resData['publisher'][i];
299
                } else {
300
                  result.publisher = resData['publisher'][i];
301
                }
302
              }
303
            }
304

    
305
            results.push(result);
306
        }
307

    
308
        return results;
309
    }
310

    
311
    parseProjects(projects: { "id": string, "acronym": string, "title": string,
312
                              "funderShortname": string, "funderName": string,
313
                              "code": string }[], relation: any ) :  {
314
                              "id": string, "acronym": string, "title": string,
315
                              "funderShortname": string, "funderName": string,
316
                              "code": string }[] {
317
      if(projects == undefined) {
318
          projects = new Array<
319
              { "id": string, "acronym": string, "title": string,
320
                "funderShortname": string, "funderName": string,
321
                "code": string
322
              }>();
323
      }
324

    
325
      let countProjects = projects.length;
326

    
327
      projects[countProjects] = {
328
          "id": "", "acronym": "", "title": "",
329
          "funderShortname": "", "funderName": "",
330
          "code": ""
331
      };
332

    
333
      if(relation.title != 'unidentified') {
334
          projects[countProjects]['id'] = relation['to'].content;
335
          projects[countProjects]['acronym'] = relation.acronym;
336
          projects[countProjects]['title'] = relation.title;
337
          projects[countProjects]['code'] = relation.code;
338
      } else {
339
          projects[countProjects]['id'] = "";
340
          projects[countProjects]['acronym'] = "";
341
          projects[countProjects]['title'] = "";
342
          projects[countProjects]['code'] = "";
343
      }
344

    
345
      if(relation.hasOwnProperty("funding")) {
346
          let fundingLength = Array.isArray(relation['funding']) ? relation['funding'].length : 1;
347

    
348
          for(let z=0; z<fundingLength; z++) {
349
              let fundingData = Array.isArray(relation['funding']) ? relation['funding'][z] : relation['funding'];
350

    
351
              if(fundingData.hasOwnProperty("funder")) {
352
                  projects[countProjects]['funderShortname'] = fundingData['funder'].shortname;
353
                  projects[countProjects]['funderName'] = fundingData['funder'].name;
354
              }
355
          }
356
      }
357

    
358
      return projects;
359
    }
360
    parseRefineResults(id: string, data: any): any {
361
        var results:any = [];
362
        if(data.hasOwnProperty("resulthostingdatasource")) {
363
            let length = Array.isArray(data['resulthostingdatasource']) ? data['resulthostingdatasource'].length : 1;
364

    
365
            for(let i=0; i<length; i++) {
366
                let datasource = Array.isArray(data['resulthostingdatasource']) ? data['resulthostingdatasource'][i] : data['resulthostingdatasource'];
367

    
368
                let result: {"name": string, "id": string, "count": number} = {"name": "", "id": "", "count": 0};
369
                result['name'] = datasource.name;
370
                result['id'] = datasource.id.split("||")[0];
371
                result['count'] = datasource.count;
372

    
373
                if(result['id'] != id && result['name'] != "Unknown Repository") {
374
                    results.push(result);
375
                }
376
            }
377
        }
378
        return results;
379
    }
380

    
381
    private numOfResults(url: string, properties:EnvProperties): any {
382
      return this.http.get((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)): url)
383
                  .pipe(map(res => res['total']));
384
    }
385

    
386
    numOfEntityResults(resultType:string, id: string, entity: string, properties:EnvProperties):any {
387
        var parameters: string = "";
388
        parameters = this.getEntityName(entity, true) + "/"+id+"/"+this.getEntityName(resultType, true)+"/count";
389
        let url = properties.searchAPIURLLAst+parameters+"?format=json";
390
        return this.numOfResults(url , properties);
391
    }
392
  numOfResearchOutcomes( params: string, properties:EnvProperties, refineParams:string=null):any {
393
    let url = properties.searchAPIURLLAst+"resources2/?format=json&size=0&type=results";
394
    if(params.length > 0){
395
      // var DOIs:string[] = DOI.getDOIsFromString(params);
396
      // var doisParams = "";
397
      //
398
      // for(var i =0 ;i < DOIs.length; i++){
399
      //   doisParams+=(doisParams.length > 0?"&":"")+'doi="'+ DOIs[i]+'"';
400
      // }
401
      // if(doisParams.length > 0){
402
      //   url += "&"+doisParams;
403
      // }else{
404
      //   url += "&query=" + StringUtils.URIEncode(params);
405
      // }
406
      url += "&query=" + params;
407
    }
408

    
409
    if(refineParams!= null && refineParams != ''  ) {
410
      url += refineParams;
411
    }
412
    return this.http.get((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)): url)
413
      .pipe(map(res => res['meta']['total']));
414
  }
415
    numOfSearchResults(resultType:string, params: string, properties:EnvProperties, refineParams:string=null):any {
416
        let url = properties.searchAPIURLLAst+this.getEntityName(resultType, true)+"/count?format=json";
417
        if(params.length > 0){
418
          var DOIs:string[] = DOI.getDOIsFromString(params);
419
          var doisParams = "";
420

    
421
          for(var i =0 ;i < DOIs.length; i++){
422
            doisParams+=(doisParams.length > 0?"&":"")+'doi="'+ DOIs[i]+'"';
423
          }
424
          if(doisParams.length > 0){
425
            url += "&"+doisParams;
426
          }else{
427
            url += "&q=" + StringUtils.URIEncode(params);
428
          }
429
        }
430

    
431
        if(refineParams!= null && refineParams != ''  ) {
432
            url += refineParams;
433
        }
434
        return this.numOfResults(url, properties);
435
    }
436
  numOfSearchResultsLinkedToPub(resultType:string, properties:EnvProperties):any {
437
    let url = properties.searchAPIURLLAst+"resources?query="+encodeURIComponent("( (oaftype exact result) and (resulttypeid exact "+resultType+") and (relresulttype=publication)  )")+"&page=0&size=0&format=json";
438
    return this.http.get((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)): url)
439
      .pipe(map(res => res['meta']['total']));
440
  }
441

    
442
    countTotalResults(resultType:string,  properties:EnvProperties, refineParams:string=null):any {
443
      let url = properties.searchAPIURLLAst+this.getEntityName(resultType, true)+"/count?format=json"+refineParams;
444
      return this.numOfResults(url, properties);
445
    }
446
/*
447
    private quote(word: any): string {
448
        return '"'+word+'"';
449
    }
450
*/
451

    
452
    private getEntityName (entityType:string, plural:boolean){
453
      if(entityType == "publication" ||entityType == "dataset" || entityType == "organization" || entityType == "datasource" || entityType == "project" ){
454
        if(plural){
455
          return entityType+ "s";
456
        }else{
457
          return entityType;
458
        }
459
      }else{
460
        return entityType;
461
      }
462
    }
463
}
(18-18/21)