Project

General

Profile

1
import {Injectable} from '@angular/core';
2
import {Http, Response} from '@angular/http';
3
import {Observable}     from 'rxjs/Observable';
4
import {OpenaireProperties} from '../utils/properties/openaireProperties';
5
import {SearchResult}     from '../utils/entities/searchResult';
6
import {RefineResultsUtils} from './servicesUtils/refineResults.class';
7
import 'rxjs/add/observable/of';
8
import 'rxjs/add/operator/do';
9
import 'rxjs/add/operator/share';
10
import { CacheService  } from '../shared/cache.service';
11
@Injectable()
12
export class SearchSoftwareService {
13
    private sizeOfDescription: number = 270;
14

    
15
    constructor(private http: Http, public _cache: CacheService) {}
16

    
17
    searchSoftware (params: string, refineParams:string, page: number, size: number, refineFields:string[] ):any {
18

    
19
        let link = OpenaireProperties.getSearchAPIURLLast()+"software";
20

    
21
        let url = link+"?";
22
        if(params!= null && params != ''  ) {
23
            url += params;
24
        }
25
        if(refineParams!= null && refineParams != ''  ) {
26
            url += refineParams;
27
        }
28
        url += "&page="+ (page-1) +"&size="+size+"&format=json";
29

    
30
        let key = url;
31
        if (this._cache.has(key)) {
32
          return Observable.of(this._cache.get(key)).map(res => [res['meta'].total, this.parseResults(res['results']),RefineResultsUtils.parse(res['refineResults'],refineFields, "software")]);
33
        }
34
        return this.http.get(url)
35
                    .map(res => <any> res.json())
36
                    //.do(res => console.info(res))
37
                    .do(res => {
38
                      this._cache.set(key, res);
39
                    })
40
                    .map(res => [res['meta'].total, this.parseResults(res['results']),RefineResultsUtils.parse(res['refineResults'],refineFields, "software")]);
41
    }
42
    searchSoftwareById (id: string ):any {
43

    
44
        let url = OpenaireProperties.getSearchAPIURLLast()+"software/"+id+"?format=json";
45
        let key = url+"-searchById";
46
        if (this._cache.has(key)) {
47
          return Observable.of(this._cache.get(key)).map(res =>  this.parseResults(res));
48
        }
49

    
50
        return this.http.get(url)
51
                    .map(res => <any> res.json())
52
                    .do(res => {
53
                      this._cache.set(key, res);
54
                    })
55
                    .map(res => this.parseResults(res));
56
    }
57

    
58
    searchAggregators (id: string, params: string, refineParams:string, page: number, size: number ):any {
59

    
60
        let link = OpenaireProperties.getSearchAPIURLLast()+"software";
61

    
62
        let url = link+"?"+"&format=json";
63
        if(params!= null && params != ''  ) {
64
            url += params;
65
        }
66
        if(refineParams!= null && refineParams != ''  ) {
67
            url += refineParams;
68
        }
69
        url += "&page="+(page-1)+"&size="+size;
70

    
71
        let key = url;
72
        if (this._cache.has(key)) {
73
          return Observable.of(this._cache.get(key)).map(res => this.parseRefineResults(id, res['refineResults']));
74
        }
75

    
76
        return this.http.get(url)
77
                    .map(res => <any> res.json())
78
                    .do(res => {
79
                      this._cache.set(key, res);
80
                    })
81
                    .map(res => this.parseRefineResults(id, res['refineResults']))
82
    }
83

    
84
    searchSoftwareByDois (DOIs: string[], refineParams:string, page: number, size: number, refineFields:string[] ):any {
85
        let link = OpenaireProperties.getSearchAPIURLLast()+"software";
86
        let url = link+"?";
87
        var doisParams = "";
88

    
89
        for(var i =0 ;i < DOIs.length; i++){
90
          doisParams+=(doisParams.length > 0?"&":"")+'doi="'+ DOIs[i]+'"';
91
        }
92
        if(doisParams.length > 0){
93
          url += "&"+doisParams;
94

    
95
        }
96
        if(refineParams!= null && refineParams != ''  ) {
97
            url += refineParams;
98
        }
99
        url += "&page="+ (page-1) +"&size="+size+"&format=json";
100

    
101
        let key = url;
102
        if (this._cache.has(key)) {
103
          return Observable.of(this._cache.get(key)).map(res => [res['meta'].total, this.parseResults(res['results']),RefineResultsUtils.parse(res['refineResults'],refineFields, "software")]);
104
        }
105
        return this.http.get(url)
106
                    .map(res => <any> res.json())
107
                    //.do(res => console.info(res))
108
                    .do(res => {
109
                      this._cache.set(key, res);
110
                    })
111
                    .map(res => [res['meta'].total, this.parseResults(res['results']),RefineResultsUtils.parse(res['refineResults'],refineFields, "software")]);
112
    }
113
    advancedSearchSoftware (params: string, page: number, size: number ):any {
114
      let url = OpenaireProperties.getSearchResourcesAPIURL();
115
      var basicQuery = "(oaftype exact result) and (resulttypeid exact software)  "
116
      url += "?query=";
117
      if(params!= null && params != ''  ) {
118
        url +=" ( "+basicQuery+ " ) " +" and (" + params + ")";
119
      }else{
120
        url +=" ( "+basicQuery+ " ) ";
121
      }
122

    
123
      url += "&page="+(page-1)+"&size="+size;
124
      url += "&format=json";
125
      let key = url;
126
      if (this._cache.has(key)) {
127
        return Observable.of(this._cache.get(key));
128
      }
129
      return this.http.get(url)
130
      .map(res => <any> res.json())
131
      //.do(res => console.info(res))
132
      .map(res => [res['meta'].total, this.parseResults(res['results'])])
133
      .do(res => {
134
        this._cache.set(key, res);
135
      });
136
    }
137
    searchSoftwareForEntity (params: string, page: number, size: number):any {
138
        let link = OpenaireProperties.getSearchAPIURLLast();
139
        let url = link+params+"/software"+"?format=json";
140
        let key = url;
141
        if (this._cache.has(key)) {
142
          return Observable.of(this._cache.get(key)).map(res => [res['meta'].total, this.parseResults(res['results'])]);
143
        }
144
        return this.http.get(url)
145
                    .map(res => <any> res.json())
146
                    .do(res => {
147
                      this._cache.set(key, res);
148
                    })
149
                    .map(res => [res['meta'].total, this.parseResults(res['results'])]);
150
    }
151

    
152
    searchSoftwareForDataproviders(params: string, page: number, size: number):any {
153
        let link = OpenaireProperties.getSearchAPIURLLast();
154
        let url = link+params+ "&page="+(page-1)+"&size="+size + "&format=json";
155
        let key = url;
156
        if (this._cache.has(key)) {
157
          return Observable.of(this._cache.get(key)).map(res => [res['meta'].total, this.parseResults(res['results'])]);
158
        }
159
        return this.http.get(url)
160
                    .map(res => <any> res.json())
161
                    .do(res => {
162
                      this._cache.set(key, res);
163
                    })
164
                    .map(res => [res['meta'].total, this.parseResults(res['results'])]);
165
    }
166

    
167
    parseResults(data: any): SearchResult[] {
168
        let results: SearchResult[] = [];
169

    
170
        let length = Array.isArray(data) ? data.length : 1;
171

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

    
175
            var result: SearchResult = new SearchResult();
176

    
177
            result['title'] = {"name": '', "accessMode": '', "sc39": ''};
178

    
179
            if(Array.isArray(resData['title'])) {
180
                result['title'].name = resData['title'][0].content;
181
            } else {
182
                result['title'].name = resData['title'].content;
183
            }
184

    
185
            //result['title'].url = OpenaireProperties.getsearchLinkToSoftware();
186
            //result['title'].url += Array.isArray(data) ? data[i]['result']['header']['dri:objIdentifier'] : data['result']['header']['dri:objIdentifier'];
187
            result['id'] = Array.isArray(data) ? data[i]['result']['header']['dri:objIdentifier'] : data['result']['header']['dri:objIdentifier'];
188
            if(resData['bestaccessright'].hasOwnProperty("classid")) {
189
                result['title'].accessMode = resData['bestaccessright'].classid;
190
            }
191

    
192
            if(resData['rels'].hasOwnProperty("rel")) {
193
                let relLength = Array.isArray(resData['rels']['rel']) ? resData['rels']['rel'].length : 1;
194

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

    
198
                    if(relation.hasOwnProperty("to")) {
199
                        if(relation['to'].class == "hasAuthor") {
200
                          if(result['authors'] == undefined) {
201
                            result['authors'] = new Array<{"name": string, "id": string}>();
202
                          }
203

    
204
                          result['authors'].push({"name": relation.fullname, "id": relation['to'].content});
205
                        } else if(relation['to'].class == "isProducedBy") {
206
                          result['projects'] = this.parseProjects(result['projects'], relation);
207
                        }
208
                    }
209
                }
210
            }
211

    
212
            var date:string = (resData.dateofacceptance)+""; // transform to string in case it is an integer
213
            result.year = (date && (date).indexOf('-') !== -1)?date.split('-')[0]:date;
214
            if(!Array.isArray(resData.description)) {
215
                result.description = resData.description;
216
            } else {
217
                result.description = resData.description[0];
218
            }
219
            if(result.description.length > this.sizeOfDescription) {
220
                result.description = result.description.substring(0, this.sizeOfDescription)+"...";
221
            }
222

    
223
            result.embargoEndDate = resData.embargoenddate;
224

    
225
            if(!Array.isArray(resData.publisher)) {
226
                result.publisher = resData.publisher;
227
            } else {
228
                for(let i=0; i<resData.publisher.length; i++) {
229
                    if(result.publisher != undefined){
230
                        result.publisher += ', '+resData['publisher'][i];
231
                    } else {
232
                        result.publisher = resData['publisher'][i];
233
                    }
234
                }
235
            }
236

    
237
            results.push(result);
238
        }
239

    
240
        return results;
241
    }
242

    
243
    parseProjects(projects: { "id": string, "acronym": string, "title": string,
244
                              "funderShortname": string, "funderName": string,
245
                              "code": string }[], relation: any ) :  {
246
                              "id": string, "acronym": string, "title": string,
247
                              "funderShortname": string, "funderName": string,
248
                              "code": string }[] {
249
      if(projects == undefined) {
250
          projects = new Array<
251
              { "id": string, "acronym": string, "title": string,
252
                "funderShortname": string, "funderName": string,
253
                "code": string
254
              }>();
255
      }
256

    
257
      let countProjects = projects.length;
258

    
259
      projects[countProjects] = {
260
          "id": "", "acronym": "", "title": "",
261
          "funderShortname": "", "funderName": "",
262
          "code": ""
263
      }
264

    
265
      if(relation.title != 'unidentified') {
266
          projects[countProjects]['id'] =
267
              /*OpenaireProperties.getsearchLinkToProject() + */relation['to'].content;
268
          projects[countProjects]['acronym'] = relation.acronym;
269
          projects[countProjects]['title'] = relation.title;
270
          projects[countProjects]['code'] = relation.code;
271
      } else {
272
          projects[countProjects]['id'] = "";
273
          projects[countProjects]['acronym'] = "";
274
          projects[countProjects]['title'] = "";
275
          projects[countProjects]['code'] = "";
276
      }
277

    
278
      if(relation.hasOwnProperty("funding")) {
279
          let fundingLength = Array.isArray(relation['funding']) ? relation['funding'].length : 1;
280

    
281
          for(let z=0; z<fundingLength; z++) {
282
              let fundingData = Array.isArray(relation['funding']) ? relation['funding'][z] : relation['funding'];
283

    
284
              if(fundingData.hasOwnProperty("funder")) {
285
                  projects[countProjects]['funderShortname'] = fundingData['funder'].shortname;
286
                  projects[countProjects]['funderName'] = fundingData['funder'].name;
287
              }
288
          }
289
      }
290

    
291
      return projects;
292
    }
293

    
294
    parseRefineResults(id: string, data: any): any {
295
        var results:any = [];
296
        if(data.hasOwnProperty("resulthostingdatasource")) {
297
            let length = Array.isArray(data['resulthostingdatasource']) ? data['resulthostingdatasource'].length : 1;
298

    
299
            for(let i=0; i<length; i++) {
300
                let datasource = Array.isArray(data['resulthostingdatasource']) ? data['resulthostingdatasource'][i] : data['resulthostingdatasource'];
301

    
302
                let result: {"name": string, "id": string, "count": number} = {"name": "", "id": "", "count": 0};
303
                result['name'] = datasource.name;
304
                result['id'] = datasource.id.split("||")[0];
305
                //result['url'] = OpenaireProperties.getsearchLinkToDataProvider()+result['id'];
306
                result['count'] = datasource.count;
307

    
308
                if(result['id'] != id && result['name'] != "Unknown Repository") {
309
                    results.push(result);
310
                }
311
            }
312
        }
313
        return results;
314
    }
315

    
316
    numOfSoftware(url: string):any {
317
      let key = url;
318
      if (this._cache.has(key)) {
319
        return Observable.of(this._cache.get(key));
320
      }
321
      return this.http.get(url)
322
                  .map(res => <any> res.json())
323
                  .map(res => res.total)
324
                  .do(res => {
325
                    this._cache.set(key, res);
326
                  });
327
    }
328

    
329
    numOfEntitySoftware(id: string, entity: string):any {
330
        var parameters = "";
331

    
332
        if(entity == "project") {
333
          parameters = "projects/"+id+"/software/count";
334
        }
335

    
336
        let url = OpenaireProperties.getSearchAPIURLLast()+parameters+"?format=json";
337
        return this.numOfSoftware(url);
338
    }
339

    
340
    numOfSearchSoftware(params: string):any {
341
        let url = OpenaireProperties.getSearchAPIURLLast()+"software/count?format=json";
342
        if(params != "") {
343
          url += "&q=" + params;
344
        }
345
        return this.numOfSoftware(url);
346
    }
347
}
(19-19/20)