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
                    //.do(res => console.info(res))
40
                    .map(res => [res['meta'].total, this.parseResults(res['results']),RefineResultsUtils.parse(res['refineResults'],refineFields, "other")]);
41
    }
42
    searchOrpById (id: string , properties:EnvProperties):any {
43

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

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

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

    
53
        let link = properties.searchAPIURLLAst+"other";
54

    
55
        let url = link+"?"+"&format=json";
56
        if(params!= null && params != ''  ) {
57
            url += params;
58
        }
59
        if(refineParams!= null && refineParams != ''  ) {
60
            url += refineParams;
61
        }
62
        url += "&page="+(page-1)+"&size="+size;
63

    
64

    
65

    
66
        return this.http.get((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)): url)
67
                    .map(res => <any> res.json())
68
                    .map(res => this.parseRefineResults(id, res['refineResults']))
69
    }
70

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

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

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

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

    
89

    
90
        return this.http.get((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)): url)
91
                    .map(res => <any> res.json())
92
                    //.do(res => console.info(res))
93

    
94
                    .map(res => [res['meta'].total, this.parseResults(res['results']),RefineResultsUtils.parse(res['refineResults'],refineFields, "other")]);
95
    }
96
    advancedSearchOrps (params: string, page: number, size: number, sortBy: string, properties:EnvProperties ):any {
97
      let url = properties.searchResourcesAPIURL;
98

    
99
      var basicQuery = "(oaftype exact result) and (resulttypeid exact other)  "
100
      url += "?query=";
101
      if(params!= null && params != ''  ) {
102
        url +=" ( "+basicQuery+ " ) " +" and (" + params + ")";
103
      }else{
104
        url +=" ( "+basicQuery+ " ) ";
105
      }
106

    
107
      if(sortBy) {
108
        let sortOptions = sortBy.split(",");
109
        url += "sortBy "+sortOptions[0]+"/sort."+sortOptions[1]+" ";
110
      }
111

    
112
      url += "&page="+(page-1)+"&size="+size;
113
      url += "&format=json";
114

    
115
      return this.http.get((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)): url)
116
      .map(res => <any> res.json())
117
      //.do(res => console.info(res))
118
      .map(res => [res['meta'].total, this.parseResults(res['results'])]);
119
    }
120
    searchOrpsForEntity (params: string, page: number, size: number, properties:EnvProperties):any {
121
        let link = properties.searchAPIURLLAst;
122

    
123
        let url = link+params+"/other"+"?format=json";
124

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

    
130
    searchOrpsForDataproviders(params: string, page: number, size: number, properties:EnvProperties):any {
131
        let link = properties.searchAPIURLLAst;
132

    
133
        let url = link+params+ "&page="+(page-1)+"&size="+size + "&format=json";
134
        return this.http.get((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)): url)
135
                    .map(res => <any> res.json())
136
                    .map(res => [res['meta'].total, this.parseResults(res['results'])]);
137
    }
138

    
139
    parseResults(data: any): SearchResult[] {
140
        let results: SearchResult[] = [];
141

    
142
        let length = Array.isArray(data) ? data.length : 1;
143

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

    
147
            var result: SearchResult = new SearchResult();
148
            result.entityType = "other";
149

    
150
            result.types = new Array<string>();
151
            let types = new Set<string>();
152
            let length = Array.isArray(resData['children']['instance']) ? resData['children']['instance'].length : 1;
153

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

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

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

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

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

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

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

    
206
            if(resData['rels'].hasOwnProperty("rel")) {
207
                let relLength = Array.isArray(resData['rels']['rel']) ? resData['rels']['rel'].length : 1;
208

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

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

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

    
226
            if(resData.hasOwnProperty("creator") && resData['creator'] != null) {
227
              if(result['authors'] == undefined) {
228
                result['authors'] = new Array<string>();
229
              }
230

    
231
              let authors = resData['creator'];
232
              let length = Array.isArray(authors) ? authors.length : 1;
233

    
234
              for(let i=0; i<length; i++) {
235
                let author = Array.isArray(authors) ? authors[i] : authors;
236
                result.authors[author.rank-1] = author.content;
237
              }
238
              result.authors = result.authors.filter(function (item) {
239
                return (item != undefined);
240
              });
241
            }
242

    
243
            var date:string = (resData.dateofacceptance)+""; // transform to string in case it is an integer
244
            result.year = (date && (date).indexOf('-') !== -1)?date.split('-')[0]:date;
245
            if(!Array.isArray(resData.description)) {
246
                result.description = resData.description;
247
            } else {
248
                result.description = resData.description[0];
249
            }
250
            if(result.description && result.description.length > this.sizeOfDescription) {
251
                result.description = result.description.substring(0, this.sizeOfDescription)+"...";
252
            }
253

    
254
            result.embargoEndDate = resData.embargoenddate;
255

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

    
268
            results.push(result);
269
        }
270

    
271
        return results;
272
    }
273

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

    
288
      let countProjects = projects.length;
289

    
290
      projects[countProjects] = {
291
          "id": "", "acronym": "", "title": "",
292
          "funderShortname": "", "funderName": "",
293
          "code": ""
294
      }
295

    
296
      if(relation.title != 'unidentified') {
297
          projects[countProjects]['id'] =
298
              /*OpenaireProperties.getsearchLinkToProject() + */relation['to'].content;
299
          projects[countProjects]['acronym'] = relation.acronym;
300
          projects[countProjects]['title'] = relation.title;
301
          projects[countProjects]['code'] = relation.code;
302
      } else {
303
          projects[countProjects]['id'] = "";
304
          projects[countProjects]['acronym'] = "";
305
          projects[countProjects]['title'] = "";
306
          projects[countProjects]['code'] = "";
307
      }
308

    
309
      if(relation.hasOwnProperty("funding")) {
310
          let fundingLength = Array.isArray(relation['funding']) ? relation['funding'].length : 1;
311

    
312
          for(let z=0; z<fundingLength; z++) {
313
              let fundingData = Array.isArray(relation['funding']) ? relation['funding'][z] : relation['funding'];
314

    
315
              if(fundingData.hasOwnProperty("funder")) {
316
                  projects[countProjects]['funderShortname'] = fundingData['funder'].shortname;
317
                  projects[countProjects]['funderName'] = fundingData['funder'].name;
318
              }
319
          }
320
      }
321

    
322
      return projects;
323
    }
324

    
325
    parseRefineResults(id: string, data: any): any {
326
        var results:any = [];
327
        if(data.hasOwnProperty("resulthostingdatasource")) {
328
            let length = Array.isArray(data['resulthostingdatasource']) ? data['resulthostingdatasource'].length : 1;
329

    
330
            for(let i=0; i<length; i++) {
331
                let datasource = Array.isArray(data['resulthostingdatasource']) ? data['resulthostingdatasource'][i] : data['resulthostingdatasource'];
332

    
333
                let result: {"name": string, "id": string, "count": number} = {"name": "", "id": "", "count": 0};
334
                result['name'] = datasource.name;
335
                result['id'] = datasource.id.split("||")[0];
336
                //result['url'] = OpenaireProperties.getsearchLinkToDataProvider()+result['id'];
337
                result['count'] = datasource.count;
338

    
339
                if(result['id'] != id && result['name'] != "Unknown Repository") {
340
                    results.push(result);
341
                }
342
            }
343
        }
344
        return results;
345
    }
346

    
347
    numOfOrps(url: string, properties:EnvProperties):any {
348

    
349
      return this.http.get((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)): url)
350
                  .map(res => <any> res.json())
351
                  .map(res => res.total);
352
    }
353

    
354
    numOfEntityOrps(id: string, entity: string, properties:EnvProperties):any {
355
        var parameters = "";
356

    
357
        if(entity == "project") {
358
          parameters = "projects/"+id+"/other/count";
359
        }
360

    
361
        let url = properties.searchAPIURLLAst+parameters+"?format=json";
362

    
363
        return this.numOfOrps(url, properties);
364
    }
365

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

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