Project

General

Profile

1
import {Injectable} from '@angular/core';
2
import {Http, Response} from '@angular/http';
3
import {Observable}     from 'rxjs/Observable';
4
import {SearchResult}     from '../utils/entities/searchResult';
5
import {RefineResultsUtils} from './servicesUtils/refineResults.class';
6
import 'rxjs/add/observable/of';
7
import 'rxjs/add/operator/do';
8
import 'rxjs/add/operator/share';
9
import {StringUtils} from '../utils/string-utils.class';
10
import { ParsingFunctions } from '../landingPages/landing-utils/parsingFunctions.class';
11
import{EnvProperties} from '../utils/properties/env-properties';
12

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

    
18
    constructor(private http: Http ) {}
19

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

    
22
        let link = properties.searchAPIURLLAst+"other";
23

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

    
36

    
37
        return this.http.get((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)): url)
38
                    .map(res => <any> res.json())
39
                    .map(res => [res['meta'].total, this.parseResults(res['results']),RefineResultsUtils.parse(res['refineResults'],refineFields, "other")]);
40
    }
41
    searchOrpById (id: string , properties:EnvProperties):any {
42

    
43
        let url = properties.searchAPIURLLAst+"other/"+id+"?format=json";
44

    
45
         return this.http.get((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)): url)
46
                    .map(res => <any> res.json())
47
                    .map(res => this.parseResults(res));
48
    }
49

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

    
52
        let link = properties.searchAPIURLLAst+"other";
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
                    .map(res => this.parseRefineResults(id, res['refineResults']))
68
    }
69

    
70
    searchOrpsByDois (DOIs: string[], refineParams:string, page: number, size: number, refineFields:string[], properties:EnvProperties ):any {
71
        let link = properties.searchAPIURLLAst+"other";
72

    
73
        let url = link+"?";
74
        var doisParams = "";
75

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

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

    
88

    
89
        return this.http.get((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)): url)
90
                    .map(res => <any> res.json())
91
                    .map(res => [res['meta'].total, this.parseResults(res['results']),RefineResultsUtils.parse(res['refineResults'],refineFields, "other")]);
92
    }
93
    advancedSearchOrps (params: string, page: number, size: number, sortBy: string, properties:EnvProperties ):any {
94
      let url = properties.searchResourcesAPIURL;
95

    
96
      var basicQuery = "(oaftype exact result) and (resulttypeid exact other)  "
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
      .map(res => [res['meta'].total, this.parseResults(res['results'])]);
115
    }
116
    searchOrpsForEntity (params: string, page: number, size: number, properties:EnvProperties):any {
117
        let link = properties.searchAPIURLLAst;
118

    
119
        let url = link+params+"/other"+"?format=json";
120

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

    
126
    searchOrpsForDataproviders(params: string, page: number, size: number, properties:EnvProperties):any {
127
        let link = properties.searchAPIURLLAst;
128

    
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
                    .map(res => [res['meta'].total, this.parseResults(res['results'])]);
133
    }
134

    
135
    parseResults(data: any): SearchResult[] {
136
        let results: SearchResult[] = [];
137

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

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

    
143
            var result: SearchResult = new SearchResult();
144
            result.entityType = "other";
145

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
230
              for(let i=0; i<length; i++) {
231
                let author = Array.isArray(authors) ? authors[i] : authors;
232
                result.authors[author.rank] = author.content;
233
              }
234
              result.authors = result.authors.filter(function (item) {
235
                return (item != undefined);
236
              });
237
            }
238

    
239
            var date:string = (resData.dateofacceptance)+""; // transform to string in case it is an integer
240
            result.year = (date && (date).indexOf('-') !== -1)?date.split('-')[0]:date;
241
            if(!Array.isArray(resData.description)) {
242
                result.description = resData.description;
243
            } else {
244
                result.description = resData.description[0];
245
            }
246
            if(result.description && result.description.length > this.sizeOfDescription) {
247
                result.description = result.description.substring(0, this.sizeOfDescription)+"...";
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'] =
294
              /*OpenaireProperties.getsearchLinkToProject() + */relation['to'].content;
295
          projects[countProjects]['acronym'] = relation.acronym;
296
          projects[countProjects]['title'] = relation.title;
297
          projects[countProjects]['code'] = relation.code;
298
      } else {
299
          projects[countProjects]['id'] = "";
300
          projects[countProjects]['acronym'] = "";
301
          projects[countProjects]['title'] = "";
302
          projects[countProjects]['code'] = "";
303
      }
304

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

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

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

    
318
      return projects;
319
    }
320

    
321
    parseRefineResults(id: string, data: any): any {
322
        var results:any = [];
323
        if(data.hasOwnProperty("resulthostingdatasource")) {
324
            let length = Array.isArray(data['resulthostingdatasource']) ? data['resulthostingdatasource'].length : 1;
325

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

    
329
                let result: {"name": string, "id": string, "count": number} = {"name": "", "id": "", "count": 0};
330
                result['name'] = datasource.name;
331
                result['id'] = datasource.id.split("||")[0];
332
                //result['url'] = OpenaireProperties.getsearchLinkToDataProvider()+result['id'];
333
                result['count'] = datasource.count;
334

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

    
343
    numOfOrps(url: string, properties:EnvProperties):any {
344

    
345
      return this.http.get((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)): url)
346
                  .map(res => <any> res.json())
347
                  .map(res => res.total);
348
    }
349

    
350
    numOfEntityOrps(id: string, entity: string, properties:EnvProperties):any {
351
        var parameters = "";
352

    
353
        if(entity == "project") {
354
          parameters = "projects/"+id+"/other/count";
355
        }
356

    
357
        let url = properties.searchAPIURLLAst+parameters+"?format=json";
358

    
359
        return this.numOfOrps(url, properties);
360
    }
361

    
362
    numOfSearchOrps(params: string, properties:EnvProperties, refineParams:string=null):any {
363
        let url = properties.searchAPIURLLAst+"other/count?format=json";
364

    
365
        if(params != "") {
366
          url += "&q=" + StringUtils.URIEncode(params);
367
        }
368
        if(refineParams!= null && refineParams != ''  ) {
369
            url += refineParams;
370
        }
371
        return this.numOfOrps(url, properties);
372
    }
373
}
(17-17/21)