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 { ParsingFunctions } from '../landingPages/landing-utils/parsingFunctions.class';
10
import{EnvProperties} from '../utils/properties/env-properties';
11
import {StringUtils} from '../utils/string-utils.class';
12
@Injectable()
13
export class SearchSoftwareService {
14
    private sizeOfDescription: number = 270;
15
    public parsingFunctions: ParsingFunctions = new ParsingFunctions();
16

    
17
    constructor(private http: Http ) {}
18

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

    
21
        let link = properties.searchAPIURLLAst+"software";
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

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

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

    
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+"software";
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
        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
    searchSoftwareByDois (DOIs: string[], refineParams:string, page: number, size: number, refineFields:string[], properties:EnvProperties ):any {
71
        let link = properties.searchAPIURLLAst+"software";
72
        let url = link+"?";
73
        var doisParams = "";
74

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

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

    
87

    
88
        return this.http.get((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)): url)
89
                    .map(res => <any> res.json())
90
                    //.do(res => console.info(res))
91
                    .map(res => [res['meta'].total, this.parseResults(res['results']),RefineResultsUtils.parse(res['refineResults'],refineFields, "software")]);
92
    }
93
    advancedSearchSoftware (params: string, page: number, size: number, sortBy: string, properties:EnvProperties ):any {
94
      let url = properties.searchResourcesAPIURL;
95
      var basicQuery = "(oaftype exact result) and (resulttypeid exact software)  "
96
      url += "?query=";
97
      if(params!= null && params != ''  ) {
98
        url +=" ( "+basicQuery+ " ) " +" and (" + params + ")";
99
      }else{
100
        url +=" ( "+basicQuery+ " ) ";
101
      }
102

    
103
      if(sortBy) {
104
        let sortOptions = sortBy.split(",");
105
        url += "sortBy "+sortOptions[0]+"/sort."+sortOptions[1]+" ";
106
      }
107

    
108
      url += "&page="+(page-1)+"&size="+size;
109
      url += "&format=json";
110

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

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

    
125
    searchSoftwareForDataproviders(params: string, page: number, size: number, properties:EnvProperties):any {
126
        let link = properties.searchAPIURLLAst;
127
        let url = link+params+ "&page="+(page-1)+"&size="+size + "&format=json";
128

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

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

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

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

    
142
            var result: SearchResult = new SearchResult();
143
            result.entityType = "software";
144

    
145
            result.types = new Array<string>();
146
            let types = new Set<string>();
147

    
148
            let instance;
149
            let length = Array.isArray(resData['children']['instance']) ? resData['children']['instance'].length : 1;
150

    
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['programmingLanguage'] && resData['programmingLanguage'] != null) {
157
              result.programmingLanguages = new Array<string>();
158

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

    
172
            if(resData['language'] && resData['language'] != null) {
173
              result.languages = new Array<string>();
174

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

    
188
            if(resData['country'] && resData['country'] != null) {
189
              result.countriesForResults = new Array<string>();
190

    
191
              if(!Array.isArray(resData['country'])) {
192
                if(resData['country'].classname != "Undetermined" && resData['country'].classname) {
193
                  result.countriesForResults.push(resData['country'].classname);
194
                }
195
              } else {
196
                for(let i=0; i<resData['country'].length; i++) {
197
                  if(resData['country'][i].classname != "Undetermined" && resData['country'][i].classname) {
198
                    result.countriesForResults.push(resData['country'][i].classname);
199
                  }
200
                }
201
              }
202
            }
203
            result['title'] = {"name": '', "accessMode": '', "sc39": ''};
204

    
205
            if(Array.isArray(resData['title'])) {
206
                result['title'].name = resData['title'][0].content;
207
            } else {
208
                result['title'].name = resData['title'].content;
209
            }
210

    
211
            //result['title'].url = OpenaireProperties.getsearchLinkToSoftware();
212
            //result['title'].url += Array.isArray(data) ? data[i]['result']['header']['dri:objIdentifier'] : data['result']['header']['dri:objIdentifier'];
213
            result['id'] = Array.isArray(data) ? data[i]['result']['header']['dri:objIdentifier'] : data['result']['header']['dri:objIdentifier'];
214
            if(resData['bestaccessright'] && resData['bestaccessright'] && resData['bestaccessright'].hasOwnProperty("classid")) {
215
                result['title'].accessMode = resData['bestaccessright'].classid;
216
            }
217

    
218
            if(resData['rels'].hasOwnProperty("rel")) {
219
                let relLength = Array.isArray(resData['rels']['rel']) ? resData['rels']['rel'].length : 1;
220

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

    
224
                    if(relation.hasOwnProperty("to")) {
225
                        /*if(relation['to'].class == "hasAuthor") {
226
                          if(result['authors'] == undefined) {
227
                            result['authors'] = new Array<{"name": string, "id": string}>();
228
                          }
229

    
230
                          result['authors'].push({"name": relation.fullname, "id": relation['to'].content});
231
                        } else */if(relation['to'].class == "isProducedBy") {
232
                          result['projects'] = this.parseProjects(result['projects'], relation);
233
                        }
234
                    }
235
                }
236
            }
237

    
238
            if(resData.hasOwnProperty("creator") && resData['creator'] != null) {
239
              if(result['authors'] == undefined) {
240
                result['authors'] = new Array<string>();
241
              }
242

    
243
              let authors = resData['creator'];
244
              let length = Array.isArray(authors) ? authors.length : 1;
245

    
246
              for(let i=0; i<length; i++) {
247
                let author = Array.isArray(authors) ? authors[i] : authors;
248
                result.authors[author.rank-1] = author.content;
249
              }
250
              result.authors = result.authors.filter(function (item) {
251
                return (item != undefined);
252
              });
253
            }
254

    
255
            var date:string = (resData.dateofacceptance)+""; // transform to string in case it is an integer
256
            result.year = (date && (date).indexOf('-') !== -1)?date.split('-')[0]:date;
257
            if(!Array.isArray(resData.description)) {
258
                result.description = resData.description;
259
            } else {
260
                result.description = resData.description[0];
261
            }
262
            if(result.description && result.description.length > this.sizeOfDescription) {
263
                result.description = result.description.substring(0, this.sizeOfDescription)+"...";
264
            }
265

    
266
            result.embargoEndDate = resData.embargoenddate;
267

    
268
            if(!Array.isArray(resData.publisher)) {
269
                result.publisher = resData.publisher;
270
            } else {
271
                for(let i=0; i<resData.publisher.length; i++) {
272
                    if(result.publisher != undefined){
273
                        result.publisher += ', '+resData['publisher'][i];
274
                    } else {
275
                        result.publisher = resData['publisher'][i];
276
                    }
277
                }
278
            }
279

    
280
            results.push(result);
281
        }
282

    
283
        return results;
284
    }
285

    
286
    parseProjects(projects: { "id": string, "acronym": string, "title": string,
287
                              "funderShortname": string, "funderName": string,
288
                              "code": string }[], relation: any ) :  {
289
                              "id": string, "acronym": string, "title": string,
290
                              "funderShortname": string, "funderName": string,
291
                              "code": string }[] {
292
      if(projects == undefined) {
293
          projects = new Array<
294
              { "id": string, "acronym": string, "title": string,
295
                "funderShortname": string, "funderName": string,
296
                "code": string
297
              }>();
298
      }
299

    
300
      let countProjects = projects.length;
301

    
302
      projects[countProjects] = {
303
          "id": "", "acronym": "", "title": "",
304
          "funderShortname": "", "funderName": "",
305
          "code": ""
306
      }
307

    
308
      if(relation.title != 'unidentified') {
309
          projects[countProjects]['id'] =
310
              /*OpenaireProperties.getsearchLinkToProject() + */relation['to'].content;
311
          projects[countProjects]['acronym'] = relation.acronym;
312
          projects[countProjects]['title'] = relation.title;
313
          projects[countProjects]['code'] = relation.code;
314
      } else {
315
          projects[countProjects]['id'] = "";
316
          projects[countProjects]['acronym'] = "";
317
          projects[countProjects]['title'] = "";
318
          projects[countProjects]['code'] = "";
319
      }
320

    
321
      if(relation.hasOwnProperty("funding")) {
322
          let fundingLength = Array.isArray(relation['funding']) ? relation['funding'].length : 1;
323

    
324
          for(let z=0; z<fundingLength; z++) {
325
              let fundingData = Array.isArray(relation['funding']) ? relation['funding'][z] : relation['funding'];
326

    
327
              if(fundingData.hasOwnProperty("funder")) {
328
                  projects[countProjects]['funderShortname'] = fundingData['funder'].shortname;
329
                  projects[countProjects]['funderName'] = fundingData['funder'].name;
330
              }
331
          }
332
      }
333

    
334
      return projects;
335
    }
336

    
337
    parseRefineResults(id: string, data: any): any {
338
        var results:any = [];
339
        if(data.hasOwnProperty("resulthostingdatasource")) {
340
            let length = Array.isArray(data['resulthostingdatasource']) ? data['resulthostingdatasource'].length : 1;
341

    
342
            for(let i=0; i<length; i++) {
343
                let datasource = Array.isArray(data['resulthostingdatasource']) ? data['resulthostingdatasource'][i] : data['resulthostingdatasource'];
344

    
345
                let result: {"name": string, "id": string, "count": number} = {"name": "", "id": "", "count": 0};
346
                result['name'] = datasource.name;
347
                result['id'] = datasource.id.split("||")[0];
348
                //result['url'] = OpenaireProperties.getsearchLinkToDataProvider()+result['id'];
349
                result['count'] = datasource.count;
350

    
351
                if(result['id'] != id && result['name'] != "Unknown Repository") {
352
                    results.push(result);
353
                }
354
            }
355
        }
356
        return results;
357
    }
358

    
359
    numOfSoftware(url: string, properties:EnvProperties):any {
360

    
361
      return this.http.get((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)): url)
362
                  .map(res => <any> res.json())
363
                  .map(res => res.total);
364
    }
365

    
366
    numOfEntitySoftware(id: string, entity: string, properties:EnvProperties):any {
367
        var parameters = "";
368

    
369
        if(entity == "project") {
370
          parameters = "projects/"+id+"/software/count";
371
        }
372

    
373
        let url = properties.searchAPIURLLAst+parameters+"?format=json";
374
        return this.numOfSoftware(url, properties);
375
    }
376

    
377
    numOfSearchSoftware(params: string, properties:EnvProperties, refineParams:string=null):any {
378
        let url = properties.searchAPIURLLAst+"software/count?format=json";
379
        if(params != "") {
380
          url += "&q=" + StringUtils.URIEncode(params);
381
        }
382
        if(refineParams!= null && refineParams != ''  ) {
383
            url += refineParams;
384
        }
385
        return this.numOfSoftware(url, properties);
386
    }
387
}
(20-20/21)