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 ):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

    
92
      if(sortBy) {
93
        let sortOptions = sortBy.split(",");
94
        url += "sortBy "+sortOptions[0]+"/sort."+sortOptions[1]+" ";
95
      }
96

    
97
      url += "&page="+(page-1)+"&size="+size;
98
      url += "&format=json";
99

    
100
      return this.http.get((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)): url)
101
      .pipe(map(res => [res['meta'].total, this.parseResults(resultType, res['results'], properties)]));
102
    }
103

    
104
    searchResultForEntity (resultType:string, params: string, page: number, size: number, properties:EnvProperties):any {
105
        let link = properties.searchAPIURLLAst;
106
        let url = link+params+"/"+this.getEntityName(resultType,true)+ "?format=json";
107
        url += "&page="+(page-1)+"&size="+size;
108

    
109
        return this.http.get((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)): url)
110
                    .pipe(map(res => [res['meta'].total, this.parseResults(resultType, res['results'], properties)]));
111
    }
112
//???? why different from above?
113
    searchForDataproviders(resultType:string, params: string, page: number, size: number, properties:EnvProperties):any {
114
        let link = properties.searchAPIURLLAst;
115
        let url = link+params+ "&page="+(page-1)+"&size="+size + "&format=json";
116
        return this.http.get((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)): url)
117
                    .pipe(map(res => [res['meta'].total, this.parseResults(resultType, res['results'], properties)]));
118
    }
119

    
120
    parseResults(resultType:string, data: any, properties: EnvProperties): SearchResult[] {
121
        let results: SearchResult[] = [];
122

    
123
        let length = Array.isArray(data) ? data.length : 1;
124

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

    
128
            var result: SearchResult = new SearchResult();
129
            result.entityType = resultType;
130

    
131
            result.types = new Array<string>();
132
            let types = new Set<string>();
133

    
134
            let instance;
135
            let length = Array.isArray(resData['children']['instance']) ? resData['children']['instance'].length : 1;
136

    
137
            for(let i=0; i<length; i++) {
138
              instance = Array.isArray(resData['children']['instance']) ? resData['children']['instance'][i] : resData['children']['instance'];
139
              this.parsingFunctions.parseTypes(result.types, types, instance);
140
            }
141

    
142
            if(resData['programmingLanguage'] && resData['programmingLanguage'] != null) {
143
              result.programmingLanguages = new Array<string>();
144

    
145
              if(!Array.isArray(resData['programmingLanguage'])) {
146
                if(resData['programmingLanguage'].classname != "Undetermined" && resData['programmingLanguage'].classname) {
147
                  result.programmingLanguages.push(resData['programmingLanguage'].classname);
148
                }
149
              } else {
150
                for(let i=0; i<resData['programmingLanguage'].length; i++) {
151
                  if(resData['programmingLanguage'][i].classname != "Undetermined" && resData['programmingLanguage'][i].classname) {
152
                    result.programmingLanguages.push(resData['programmingLanguage'][i].classname);
153
                  }
154
                }
155
              }
156
            }
157

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

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

    
174
            if(resData['country'] && resData['country'] != null) {
175
              result.countriesForResults = new Array<string>();
176

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

    
190
            result['title'] = {"name": '', "accessMode": '', "sc39": ''};
191

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

    
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 == "isProducedBy") {
211
                            result['projects'] = this.parseProjects(result['projects'], relation);
212
                        }
213
                    }
214
                }
215
            }
216

    
217
            if(resData.hasOwnProperty("creator") && resData['creator'] != null) {
218
              if(result['authors'] == undefined) {
219
                result['authors'] = new Array<{"fullName": string, "orcid": string}>();
220
              }
221

    
222
              let authors = resData['creator'];
223
              let length = Array.isArray(authors) ? authors.length : 1;
224

    
225
              for(let i=0; i<length; i++) {
226
                let author = Array.isArray(authors) ? authors[i] : authors;
227
                if(author) {
228
                  result['authors'][author.rank] = {"fullName": author.content, "orcid": author.ORCID};
229
                }
230
              }
231
              result.authors = result.authors.filter(function (item) {
232
                return (item != undefined && item.fullName != undefined);
233
              });
234
            }
235

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

    
239
            if(!Array.isArray(resData.description)) {
240
                result.description = String(resData.description);
241
            } else {
242
                result.description = String(resData.description[0]);
243
            }
244

    
245
            if(result.description && result.description.length > this.sizeOfDescription) {
246
                result.description = result.description.substring(0, this.sizeOfDescription) + "...";
247
            }
248

    
249

    
250
            result.embargoEndDate = resData.embargoenddate;
251

    
252
            if(!Array.isArray(resData.publisher)) {
253
              result.publisher = resData.publisher;
254
            } else {
255
              for(let i=0; i<resData.publisher.length; i++) {
256
                if(result.publisher != undefined){
257
                  result.publisher += ', '+resData['publisher'][i];
258
                } else {
259
                  result.publisher = resData['publisher'][i];
260
                }
261
              }
262
            }
263

    
264
            results.push(result);
265
        }
266

    
267
        return results;
268
    }
269

    
270
    parseProjects(projects: { "id": string, "acronym": string, "title": string,
271
                              "funderShortname": string, "funderName": string,
272
                              "code": string }[], relation: any ) :  {
273
                              "id": string, "acronym": string, "title": string,
274
                              "funderShortname": string, "funderName": string,
275
                              "code": string }[] {
276
      if(projects == undefined) {
277
          projects = new Array<
278
              { "id": string, "acronym": string, "title": string,
279
                "funderShortname": string, "funderName": string,
280
                "code": string
281
              }>();
282
      }
283

    
284
      let countProjects = projects.length;
285

    
286
      projects[countProjects] = {
287
          "id": "", "acronym": "", "title": "",
288
          "funderShortname": "", "funderName": "",
289
          "code": ""
290
      };
291

    
292
      if(relation.title != 'unidentified') {
293
          projects[countProjects]['id'] = relation['to'].content;
294
          projects[countProjects]['acronym'] = relation.acronym;
295
          projects[countProjects]['title'] = relation.title;
296
          projects[countProjects]['code'] = relation.code;
297
      } else {
298
          projects[countProjects]['id'] = "";
299
          projects[countProjects]['acronym'] = "";
300
          projects[countProjects]['title'] = "";
301
          projects[countProjects]['code'] = "";
302
      }
303

    
304
      if(relation.hasOwnProperty("funding")) {
305
          let fundingLength = Array.isArray(relation['funding']) ? relation['funding'].length : 1;
306

    
307
          for(let z=0; z<fundingLength; z++) {
308
              let fundingData = Array.isArray(relation['funding']) ? relation['funding'][z] : relation['funding'];
309

    
310
              if(fundingData.hasOwnProperty("funder")) {
311
                  projects[countProjects]['funderShortname'] = fundingData['funder'].shortname;
312
                  projects[countProjects]['funderName'] = fundingData['funder'].name;
313
              }
314
          }
315
      }
316

    
317
      return projects;
318
    }
319
    parseRefineResults(id: string, data: any): any {
320
        var results:any = [];
321
        if(data.hasOwnProperty("resulthostingdatasource")) {
322
            let length = Array.isArray(data['resulthostingdatasource']) ? data['resulthostingdatasource'].length : 1;
323

    
324
            for(let i=0; i<length; i++) {
325
                let datasource = Array.isArray(data['resulthostingdatasource']) ? data['resulthostingdatasource'][i] : data['resulthostingdatasource'];
326

    
327
                let result: {"name": string, "id": string, "count": number} = {"name": "", "id": "", "count": 0};
328
                result['name'] = datasource.name;
329
                result['id'] = datasource.id.split("||")[0];
330
                result['count'] = datasource.count;
331

    
332
                if(result['id'] != id && result['name'] != "Unknown Repository") {
333
                    results.push(result);
334
                }
335
            }
336
        }
337
        return results;
338
    }
339

    
340
    private numOfResults(url: string, properties:EnvProperties): any {
341
      return this.http.get((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)): url)
342
                  .pipe(map(res => res['total']));
343
    }
344

    
345
    numOfEntityResults(resultType:string, id: string, entity: string, properties:EnvProperties):any {
346
        var parameters: string = "";
347
        parameters = this.getEntityName(entity, true) + "/"+id+"/"+this.getEntityName(resultType, true)+"/count";
348
        let url = properties.searchAPIURLLAst+parameters+"?format=json";
349
        return this.numOfResults(url , properties);
350
    }
351

    
352
    numOfSearchResults(resultType:string, params: string, properties:EnvProperties, refineParams:string=null):any {
353
        let url = properties.searchAPIURLLAst+this.getEntityName(resultType, true)+"/count?format=json";
354
        if(params.length > 0){
355
          var DOIs:string[] = DOI.getDOIsFromString(params);
356
          var doisParams = "";
357

    
358
          for(var i =0 ;i < DOIs.length; i++){
359
            doisParams+=(doisParams.length > 0?"&":"")+'doi="'+ DOIs[i]+'"';
360
          }
361
          if(doisParams.length > 0){
362
            url += "&"+doisParams;
363
          }else{
364
            url += "&q=" + StringUtils.URIEncode(params);
365
          }
366
        }
367

    
368
        if(refineParams!= null && refineParams != ''  ) {
369
            url += refineParams;
370
        }
371
        return this.numOfResults(url, properties);
372
    }
373

    
374
    countTotalResults(resultType:string,  properties:EnvProperties, refineParams:string=null):any {
375
      let url = properties.searchAPIURLLAst+this.getEntityName(resultType, true)+"/count?format=json"+refineParams;
376
      return this.numOfResults(url, properties);
377
    }
378
/*
379
    private quote(word: any): string {
380
        return '"'+word+'"';
381
    }
382
*/
383

    
384
    private getEntityName (entityType:string, plural:boolean){
385
      if(entityType == "publication" ||entityType == "dataset" || entityType == "organization" || entityType == "datasource" || entityType == "project" ){
386
        if(plural){
387
          return entityType+ "s";
388
        }else{
389
          return entityType;
390
        }
391
      }else{
392
        return entityType;
393
      }
394
    }
395
}
(16-16/19)