Project

General

Profile

1
import {Injectable, OnDestroy} 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 {Dates, 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

    
19

    
20
    search (resultType:string, params: string, refineParams:string, page: number, size: number, sortBy: string, refineFields:string[] , properties:EnvProperties):any {
21
        let link = properties.searchAPIURLLAst+this.getEntityName(resultType,true);
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
        return this.http.get((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)): url)
36
                    .pipe(map(res => [res['meta'].total, this.parseResults(resultType, res['results'], properties),RefineResultsUtils.parse(res['refineResults'],refineFields, "publication")]));
37
    }
38

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

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

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

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

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

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

    
65
        let url = link+"?"+"&format=json&";
66
        var doisParams = "";
67

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

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

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

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

    
104
      url += "&page="+(page-1)+"&size="+size;
105
      url += "&format=json";
106

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

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

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

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

    
139
        //let url = link+"/resources2?format=json&query="+params+" sortBy resultdateofacceptance/sort.descending&type="+this.getEntityName(resultType,true);
140

    
141
        let url = link+"/"+this.getEntityName(resultType,true);
142
        url += "?format=json";
143
        url += "&fq="+params;
144
        url += "&sortBy=resultdateofacceptance,descending";
145
        url += "&page="+(page-1)+"&size="+size;
146

    
147
        return this.http.get((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)): url)
148
                    .pipe(map(res => [res['meta'].total, this.parseResults(resultType, res['results'], properties)]));
149
    }
150
//???? why different from above?
151
    searchForDataproviders(resultType:string, params: string, page: number, size: number, properties:EnvProperties):any {
152
        let link = properties.searchAPIURLLAst;
153
        let url = link+params;
154
        url += "&sortBy=resultdateofacceptance,descending";
155
        url += "&page="+(page-1)+"&size="+size + "&format=json";
156
        return this.http.get((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)): url)
157
                    .pipe(map(res => [res['meta'].total, this.parseResults(resultType, res['results'], properties)]));
158
    }
159

    
160
    parseResults(resultType:string, data: any, properties: EnvProperties): SearchResult[] {
161
        let results: SearchResult[] = [];
162

    
163
        let length = Array.isArray(data) ? data.length : 1;
164

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

    
168
            var result: SearchResult = new SearchResult();
169
            if(resData['resulttype']) {
170
              result.entityType = resData['resulttype']['classname'];
171
            } else {
172
              result.entityType = resultType;
173
            }
174
            result.types = new Array<string>();
175
            let types = new Set<string>();
176

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

    
180
            for(let i=0; i<length; i++) {
181
              instance = Array.isArray(resData['children']['instance']) ? resData['children']['instance'][i] : resData['children']['instance'];
182
              this.parsingFunctions.parseTypes(result.types, types, instance);
183
            }
184
            /////////////////////////// Athena Code ///////////////////////////
185
            if(resData['pid']) {
186
              if(!Array.isArray(resData['pid'])) {
187
                if(resData['pid'].classid && resData['pid'].classid == 'doi'){
188
                  if(resData['pid'].content != '' && resData['pid'].content != null){
189
                    result.DOIs.push(resData['pid'].content.replace("https://doi.org/",""));
190
                  }
191
                }
192
              } else {
193
                for(let i=0; i<resData['pid'].length; i++){
194
                  if(resData['pid'][i].classid == 'doi'){
195
                    if(resData['pid'][i].content != '' && resData['pid'][i].content != null){
196
                      result.DOIs.push(resData['pid'][i].content.replace("https://doi.org/",""));
197
                    }
198
                  }
199
                }
200
              }
201
            }
202
            /////////////////////////// Athena Code ///////////////////////////
203
            if(resData['programmingLanguage'] && resData['programmingLanguage'] != null) {
204
              result.programmingLanguages = new Array<string>();
205

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

    
219
            if(resData['language'] && resData['language'] != null) {
220
              result.languages = new Array<string>();
221

    
222
              if(!Array.isArray(resData['language'])) {
223
                if(resData['language'].classname != "Undetermined" && resData['language'].classname) {
224
                  result.languages.push(resData['language'].classname);
225
                }
226
              } else {
227
                for(let i=0; i<resData['language'].length; i++) {
228
                  if(resData['language'][i].classname != "Undetermined" && resData['language'][i].classname) {
229
                    result.languages.push(resData['language'][i].classname);
230
                  }
231
                }
232
              }
233
            }
234

    
235
            if(resData['country'] && resData['country'] != null) {
236
              result.countriesForResults = new Array<string>();
237

    
238
              if(!Array.isArray(resData['country'])) {
239
                if(resData['country'].classname != "Undetermined" && resData['country'].classname) {
240
                  result.countriesForResults.push(resData['country'].classname);
241
                }
242
              } else {
243
                for(let i=0; i<resData['country'].length; i++) {
244
                  if(resData['country'][i].classname != "Undetermined" && resData['country'][i].classname) {
245
                    result.countriesForResults.push(resData['country'][i].classname);
246
                  }
247
                }
248
              }
249
            }
250

    
251
            result['title'] = {"name": '', "accessMode": '', "sc39": ''};
252

    
253
            if(Array.isArray(resData['title'])) {
254
                result['title'].name = (resData['title'][0] && resData['title'][0].content) ? String(resData['title'][0].content) : "";
255
            } else {
256
                result['title'].name = (resData['title'] && resData['title'].content) ? String(resData['title'].content) : "";
257
            }
258

    
259
            result['id'] = Array.isArray(data) ? data[i]['result']['header']['dri:objIdentifier'] : data['result']['header']['dri:objIdentifier'];
260
            if(resData['bestaccessright'] && resData['bestaccessright'].hasOwnProperty("classname")) {
261
                result['title'].accessMode = resData['bestaccessright'].classname;
262
            }
263
            if(resData['rels'].hasOwnProperty("rel")) {
264
                let relLength = Array.isArray(resData['rels']['rel']) ? resData['rels']['rel'].length : 1;
265

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

    
269
                    if(relation.hasOwnProperty("to")) {
270
                        if(relation['to'].class == "isProducedBy") {
271
                            result['projects'] = this.parseProjects(result['projects'], relation);
272
                        }
273
                    }
274
                }
275
            }
276

    
277
            if(resData.hasOwnProperty("creator") && resData['creator'] != null) {
278
              if(result['authors'] == undefined) {
279
                result['authors'] = new Array<{"fullName": string, "orcid": string}>();
280
              }
281

    
282
              let authors = resData['creator'];
283
              let length = Array.isArray(authors) ? authors.length : 1;
284

    
285
              for(let i=0; i<length; i++) {
286
                let author = Array.isArray(authors) ? authors[i] : authors;
287
                if(author) {
288
                  result['authors'][author.rank] = {"fullName": author.content, "orcid": author.orcid};
289
                }
290
              }
291
              result.authors = result.authors.filter(function (item) {
292
                return (item != undefined && item.fullName != undefined);
293
              });
294
            }
295

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

    
299
            if(!Array.isArray(resData.description)) {
300
                result.description = (resData.description) ? String(resData.description) : "";
301
            } else {
302
                result.description = (resData.description[0]) ? String(resData.description[0]) : "";
303
            }
304

    
305
            if(result.description && result.description.length > this.sizeOfDescription) {
306
                result.description = result.description.substring(0, this.sizeOfDescription) + "...";
307
            }
308

    
309
            if(resData.embargoenddate && resData.embargoenddate != '') {
310
              result.embargoEndDate = Dates.getDate(resData.embargoenddate);
311
            }
312

    
313
            if(!Array.isArray(resData.publisher)) {
314
              result.publisher = resData.publisher;
315
            } else {
316
              for(let i=0; i<resData.publisher.length; i++) {
317
                if(result.publisher != undefined){
318
                  result.publisher += ', '+resData['publisher'][i];
319
                } else {
320
                  result.publisher = resData['publisher'][i];
321
                }
322
              }
323
            }
324

    
325
            results.push(result);
326
        }
327

    
328
        return results;
329
    }
330

    
331
    parseProjects(projects: { "id": string, "acronym": string, "title": string,
332
                              "funderShortname": string, "funderName": string,
333
                              "code": string }[], relation: any ) :  {
334
                              "id": string, "acronym": string, "title": string,
335
                              "funderShortname": string, "funderName": string,
336
                              "code": string }[] {
337
      if(projects == undefined) {
338
          projects = new Array<
339
              { "id": string, "acronym": string, "title": string,
340
                "funderShortname": string, "funderName": string,
341
                "code": string
342
              }>();
343
      }
344

    
345
      let countProjects = projects.length;
346

    
347
      projects[countProjects] = {
348
          "id": "", "acronym": "", "title": "",
349
          "funderShortname": "", "funderName": "",
350
          "code": ""
351
      };
352

    
353
      if(relation.title != 'unidentified') {
354
          projects[countProjects]['id'] = relation['to'].content;
355
          projects[countProjects]['acronym'] = relation.acronym;
356
          projects[countProjects]['title'] = relation.title;
357
          projects[countProjects]['code'] = relation.code;
358
      } else {
359
          projects[countProjects]['id'] = "";
360
          projects[countProjects]['acronym'] = "";
361
          projects[countProjects]['title'] = "";
362
          projects[countProjects]['code'] = "";
363
      }
364

    
365
      if(relation.hasOwnProperty("funding")) {
366
          let fundingLength = Array.isArray(relation['funding']) ? relation['funding'].length : 1;
367

    
368
          for(let z=0; z<fundingLength; z++) {
369
              let fundingData = Array.isArray(relation['funding']) ? relation['funding'][z] : relation['funding'];
370

    
371
              if(fundingData.hasOwnProperty("funder")) {
372
                  projects[countProjects]['funderShortname'] = fundingData['funder'].shortname;
373
                  projects[countProjects]['funderName'] = fundingData['funder'].name;
374
              }
375
          }
376
      }
377

    
378
      return projects;
379
    }
380
    parseRefineResults(id: string, data: any): any {
381
        var results:any = [];
382
        if(data.hasOwnProperty("resulthostingdatasource")) {
383
            let length = Array.isArray(data['resulthostingdatasource']) ? data['resulthostingdatasource'].length : 1;
384

    
385
            for(let i=0; i<length; i++) {
386
                let datasource = Array.isArray(data['resulthostingdatasource']) ? data['resulthostingdatasource'][i] : data['resulthostingdatasource'];
387

    
388
                let result: {"name": string, "id": string, "count": number} = {"name": "", "id": "", "count": 0};
389
                result['name'] = datasource.name;
390
                result['id'] = datasource.id.split("||")[0];
391
                result['count'] = datasource.count;
392

    
393
                if(result['id'] != id && result['name'] != "Unknown Repository") {
394
                    results.push(result);
395
                }
396
            }
397
        }
398
        return results;
399
    }
400

    
401
    private numOfResults(url: string, properties:EnvProperties): any {
402
      return this.http.get((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)): url)
403
                  .pipe(map(res => res['total']));
404
    }
405

    
406
    numOfEntityResults(resultType:string, id: string, entity: string, properties:EnvProperties):any {
407
        var parameters: string = "";
408
        parameters = this.getEntityName(entity, true) + "/"+id+"/"+this.getEntityName(resultType, true)+"/count";
409
        let url = properties.searchAPIURLLAst+parameters+"?format=json";
410
        return this.numOfResults(url , properties);
411
    }
412
  numOfResearchOutcomes( params: string, properties:EnvProperties, refineParams:string=null):any {
413
    let url = properties.searchAPIURLLAst+"resources2/?format=json&size=0&type=results";
414
    if(params.length > 0){
415
      // var DOIs:string[] = DOI.getDOIsFromString(params);
416
      // var doisParams = "";
417
      //
418
      // for(var i =0 ;i < DOIs.length; i++){
419
      //   doisParams+=(doisParams.length > 0?"&":"")+'doi="'+ DOIs[i]+'"';
420
      // }
421
      // if(doisParams.length > 0){
422
      //   url += "&"+doisParams;
423
      // }else{
424
      //   url += "&query=" + StringUtils.URIEncode(params);
425
      // }
426
      url += "&query=" + params;
427
    }
428

    
429
    if(refineParams!= null && refineParams != ''  ) {
430
      url += refineParams;
431
    }
432
    return this.http.get((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)): url)
433
      .pipe(map(res => res['meta']['total']));
434
  }
435
    numOfSearchResults(resultType:string, params: string, properties:EnvProperties, refineParams:string=null):any {
436
        let url = properties.searchAPIURLLAst+this.getEntityName(resultType, true)+"/count?format=json";
437
        if(params.length > 0){
438
          var DOIs:string[] = DOI.getDOIsFromString(params);
439
          var doisParams = "";
440

    
441
          for(var i =0 ;i < DOIs.length; i++){
442
            doisParams+=(doisParams.length > 0?"&":"")+'doi="'+ DOIs[i]+'"';
443
          }
444
          if(doisParams.length > 0){
445
            url += "&"+doisParams;
446
          }else{
447
            url += "&q=" + StringUtils.URIEncode(params);
448
          }
449
        }
450

    
451
        if(refineParams!= null && refineParams != ''  ) {
452
            url += refineParams;
453
        }
454
        return this.numOfResults(url, properties);
455
    }
456
  numOfSearchResultsLinkedToPub(resultType:string, properties:EnvProperties):any {
457
    let url = properties.searchAPIURLLAst+"resources?query="+encodeURIComponent("( (oaftype exact result) and (resulttypeid exact "+resultType+") and (relresulttype=publication)  )")+"&page=0&size=0&format=json";
458
    return this.http.get((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)): url)
459
      .pipe(map(res => res['meta']['total']));
460
  }
461

    
462
    countTotalResults(resultType:string,  properties:EnvProperties, refineParams:string=null):any {
463
      let url = properties.searchAPIURLLAst+this.getEntityName(resultType, true)+"/count?format=json"+refineParams;
464
      return this.numOfResults(url, properties);
465
    }
466
/*
467
    private quote(word: any): string {
468
        return '"'+word+'"';
469
    }
470
*/
471

    
472
    private getEntityName (entityType:string, plural:boolean){
473
      if(entityType == "publication" ||entityType == "dataset" || entityType == "organization" || entityType == "datasource" || entityType == "project" ){
474
        if(plural){
475
          return entityType+ "s";
476
        }else{
477
          return entityType;
478
        }
479
      }else{
480
        return entityType;
481
      }
482
    }
483
}
(19-19/23)