Project

General

Profile

1 49720 argiro.kok
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 {   } from '../shared/cache.service';
11
@Injectable()
12
export class SearchDatasetsService {
13
    private sizeOfDescription: number = 270;
14
15
    constructor(private http: Http ) {}
16
17
    searchDatasets (params: string, refineParams:string, page: number, size: number, refineFields:string[] ):any {
18
19
        let link = OpenaireProperties.getSearchAPIURLLast()+"datasets";
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
31
        return this.http.get((OpenaireProperties.isCacheEnabled())? (OpenaireProperties.getCacheUrl()+encodeURIComponent(url)): url)
32
                    .map(res => <any> res.json())
33
                    //.do(res => console.info(res))
34
                    .map(res => [res['meta'].total, this.parseResults(res['results']),RefineResultsUtils.parse(res['refineResults'],refineFields, "dataset")]);
35
    }
36
    searchDatasetById (id: string ):any {
37
38
        let url = OpenaireProperties.getSearchAPIURLLast()+"datasets/"+id+"?format=json";
39
         return this.http.get((OpenaireProperties.isCacheEnabled())? (OpenaireProperties.getCacheUrl()+encodeURIComponent(url)): url)
40
                    .map(res => <any> res.json())
41
                    .map(res => this.parseResults(res));
42
    }
43
44
    searchAggregators (id: string, params: string, refineParams:string, page: number, size: number ):any {
45
46
        let link = OpenaireProperties.getSearchAPIURLLast()+"datasets";
47
48
        let url = link+"?"+"&format=json";
49
        if(params!= null && params != ''  ) {
50
            url += params;
51
        }
52
        if(refineParams!= null && refineParams != ''  ) {
53
            url += refineParams;
54
        }
55
        url += "&page="+(page-1)+"&size="+size;
56
57
58
59
        return this.http.get((OpenaireProperties.isCacheEnabled())? (OpenaireProperties.getCacheUrl()+encodeURIComponent(url)): url)
60
                    .map(res => <any> res.json())
61
                    .map(res => this.parseRefineResults(id, res['refineResults']))
62
    }
63
64
    searchDatasetsByDois (DOIs: string[], refineParams:string, page: number, size: number, refineFields:string[] ):any {
65
        let link = OpenaireProperties.getSearchAPIURLLast()+"datasets";
66
        let url = link+"?";
67
        var doisParams = "";
68
69
        for(var i =0 ;i < DOIs.length; i++){
70
          doisParams+=(doisParams.length > 0?"&":"")+'doi="'+ DOIs[i]+'"';
71
        }
72
        if(doisParams.length > 0){
73
          url += "&"+doisParams;
74
75
        }
76
        if(refineParams!= null && refineParams != ''  ) {
77
            url += refineParams;
78
        }
79
        url += "&page="+ (page-1) +"&size="+size+"&format=json";
80
81
82
        return this.http.get((OpenaireProperties.isCacheEnabled())? (OpenaireProperties.getCacheUrl()+encodeURIComponent(url)): url)
83
                    .map(res => <any> res.json())
84
                    //.do(res => console.info(res))
85
86
                    .map(res => [res['meta'].total, this.parseResults(res['results']),RefineResultsUtils.parse(res['refineResults'],refineFields, "dataset")]);
87
    }
88
    advancedSearchDatasets (params: string, page: number, size: number ):any {
89
      let url = OpenaireProperties.getSearchResourcesAPIURL();
90
      var basicQuery = "(oaftype exact result) and (resulttypeid exact dataset)  "
91
      url += "?query=";
92
      if(params!= null && params != ''  ) {
93
        url +=" ( "+basicQuery+ " ) " +" and (" + params + ")";
94
      }else{
95
        url +=" ( "+basicQuery+ " ) ";
96
      }
97
98
      url += "&page="+(page-1)+"&size="+size;
99
      url += "&format=json";
100
101
      return this.http.get((OpenaireProperties.isCacheEnabled())? (OpenaireProperties.getCacheUrl()+encodeURIComponent(url)): url)
102
      .map(res => <any> res.json())
103
      //.do(res => console.info(res))
104
      .map(res => [res['meta'].total, this.parseResults(res['results'])]);
105
    }
106
    searchDatasetsForEntity (params: string, page: number, size: number):any {
107
        let link = OpenaireProperties.getSearchAPIURLLast();
108
        let url = link+params+"/datasets"+"?format=json";
109
110
        return this.http.get((OpenaireProperties.isCacheEnabled())? (OpenaireProperties.getCacheUrl()+encodeURIComponent(url)): url)
111
                    .map(res => <any> res.json())
112
                    .map(res => [res['meta'].total, this.parseResults(res['results'])]);
113
    }
114
115
    searchDatasetsForDataproviders(params: string, page: number, size: number):any {
116
        let link = OpenaireProperties.getSearchAPIURLLast();
117
        let url = link+params+ "&page="+(page-1)+"&size="+size + "&format=json";
118
        return this.http.get((OpenaireProperties.isCacheEnabled())? (OpenaireProperties.getCacheUrl()+encodeURIComponent(url)): url)
119
                    .map(res => <any> res.json())
120
                    .map(res => [res['meta'].total, this.parseResults(res['results'])]);
121
    }
122
123
    parseResults(data: any): SearchResult[] {
124
        let results: SearchResult[] = [];
125
126
        let length = Array.isArray(data) ? data.length : 1;
127
128
        for(let i=0; i<length; i++) {
129
            let resData = Array.isArray(data) ? data[i]['result']['metadata']['oaf:entity']['oaf:result'] : data['result']['metadata']['oaf:entity']['oaf:result'];
130
131
            var result: SearchResult = new SearchResult();
132
133
            result['title'] = {"name": '', "accessMode": '', "sc39": ''};
134
135
            if(Array.isArray(resData['title'])) {
136
                result['title'].name = resData['title'][0].content;
137
            } else {
138
                result['title'].name = resData['title'].content;
139
            }
140
141
            //result['title'].url = OpenaireProperties.getsearchLinkToDataset();
142
            //result['title'].url += Array.isArray(data) ? data[i]['result']['header']['dri:objIdentifier'] : data['result']['header']['dri:objIdentifier'];
143
            result['id'] = Array.isArray(data) ? data[i]['result']['header']['dri:objIdentifier'] : data['result']['header']['dri:objIdentifier'];
144
            if(resData['bestaccessright'].hasOwnProperty("classid")) {
145
                result['title'].accessMode = resData['bestaccessright'].classid;
146
            }
147
148
            if(resData['rels'].hasOwnProperty("rel")) {
149
                let relLength = Array.isArray(resData['rels']['rel']) ? resData['rels']['rel'].length : 1;
150
151
                for(let j=0; j<relLength; j++) {
152
                    let relation = Array.isArray(resData['rels']['rel']) ? resData['rels']['rel'][j] : resData['rels']['rel'];
153
154
                    if(relation.hasOwnProperty("to")) {
155
                        /*if(relation['to'].class == "hasAuthor") {
156
                          if(result['authors'] == undefined) {
157
                            result['authors'] = new Array<{"name": string, "id": string}>();
158
                          }
159
160
                          result['authors'].push({"name": relation.fullname, "id": relation['to'].content});
161
                        } else */if(relation['to'].class == "isProducedBy") {
162
                          result['projects'] = this.parseProjects(result['projects'], relation);
163
                        }
164
                    }
165
                }
166
            }
167
168
            if(resData.hasOwnProperty("creator") && resData['creator'] != null) {
169
              if(result['authors'] == undefined) {
170
                result['authors'] = new Array<string>();
171
              }
172
173
              let authors = resData['creator'];
174
              let length = Array.isArray(authors) ? authors.length : 1;
175
176
              for(let i=0; i<length; i++) {
177
                let author = Array.isArray(authors) ? authors[i] : authors;
178
                result.authors[author.rank-1] = author.content;
179
              }
180
              result.authors = result.authors.filter(function (item) {
181
                return (item != undefined);
182
              });
183
            }
184
185
            var date:string = (resData.dateofacceptance)+""; // transform to string in case it is an integer
186
            result.year = (date && (date).indexOf('-') !== -1)?date.split('-')[0]:date;
187
            if(!Array.isArray(resData.description)) {
188
                result.description = resData.description;
189
            } else {
190
                result.description = resData.description[0];
191
            }
192
            if(result.description.length > this.sizeOfDescription) {
193
                result.description = result.description.substring(0, this.sizeOfDescription)+"...";
194
            }
195
196
            result.embargoEndDate = resData.embargoenddate;
197
198
            if(!Array.isArray(resData.publisher)) {
199
                result.publisher = resData.publisher;
200
            } else {
201
                for(let i=0; i<resData.publisher.length; i++) {
202
                    if(result.publisher != undefined){
203
                        result.publisher += ', '+resData['publisher'][i];
204
                    } else {
205
                        result.publisher = resData['publisher'][i];
206
                    }
207
                }
208
            }
209
210
            results.push(result);
211
        }
212
213
        return results;
214
    }
215
216
    parseProjects(projects: { "id": string, "acronym": string, "title": string,
217
                              "funderShortname": string, "funderName": string,
218
                              "code": string }[], relation: any ) :  {
219
                              "id": string, "acronym": string, "title": string,
220
                              "funderShortname": string, "funderName": string,
221
                              "code": string }[] {
222
      if(projects == undefined) {
223
          projects = new Array<
224
              { "id": string, "acronym": string, "title": string,
225
                "funderShortname": string, "funderName": string,
226
                "code": string
227
              }>();
228
      }
229
230
      let countProjects = projects.length;
231
232
      projects[countProjects] = {
233
          "id": "", "acronym": "", "title": "",
234
          "funderShortname": "", "funderName": "",
235
          "code": ""
236
      }
237
238
      if(relation.title != 'unidentified') {
239
          projects[countProjects]['id'] =
240
              /*OpenaireProperties.getsearchLinkToProject() + */relation['to'].content;
241
          projects[countProjects]['acronym'] = relation.acronym;
242
          projects[countProjects]['title'] = relation.title;
243
          projects[countProjects]['code'] = relation.code;
244
      } else {
245
          projects[countProjects]['id'] = "";
246
          projects[countProjects]['acronym'] = "";
247
          projects[countProjects]['title'] = "";
248
          projects[countProjects]['code'] = "";
249
      }
250
251
      if(relation.hasOwnProperty("funding")) {
252
          let fundingLength = Array.isArray(relation['funding']) ? relation['funding'].length : 1;
253
254
          for(let z=0; z<fundingLength; z++) {
255
              let fundingData = Array.isArray(relation['funding']) ? relation['funding'][z] : relation['funding'];
256
257
              if(fundingData.hasOwnProperty("funder")) {
258
                  projects[countProjects]['funderShortname'] = fundingData['funder'].shortname;
259
                  projects[countProjects]['funderName'] = fundingData['funder'].name;
260
              }
261
          }
262
      }
263
264
      return projects;
265
    }
266
267
    parseRefineResults(id: string, data: any): any {
268
        var results:any = [];
269
        if(data.hasOwnProperty("resulthostingdatasource")) {
270
            let length = Array.isArray(data['resulthostingdatasource']) ? data['resulthostingdatasource'].length : 1;
271
272
            for(let i=0; i<length; i++) {
273
                let datasource = Array.isArray(data['resulthostingdatasource']) ? data['resulthostingdatasource'][i] : data['resulthostingdatasource'];
274
275
                let result: {"name": string, "id": string, "count": number} = {"name": "", "id": "", "count": 0};
276
                result['name'] = datasource.name;
277
                result['id'] = datasource.id.split("||")[0];
278
                //result['url'] = OpenaireProperties.getsearchLinkToDataProvider()+result['id'];
279
                result['count'] = datasource.count;
280
281
                if(result['id'] != id && result['name'] != "Unknown Repository") {
282
                    results.push(result);
283
                }
284
            }
285
        }
286
        return results;
287
    }
288
289
    numOfDatasets(url: string):any {
290
291
      return this.http.get((OpenaireProperties.isCacheEnabled())? (OpenaireProperties.getCacheUrl()+encodeURIComponent(url)): url)
292
                  .map(res => <any> res.json())
293
                  .map(res => res.total);
294
    }
295
296
    numOfEntityDatasets(id: string, entity: string):any {
297
        var parameters = "";
298
299
        if(entity == "project") {
300
          parameters = "projects/"+id+"/datasets/count";
301
        }
302
303
        let url = OpenaireProperties.getSearchAPIURLLast()+parameters+"?format=json";
304
        return this.numOfDatasets(url);
305
    }
306
307
    numOfSearchDatasets(params: string):any {
308
        let url = OpenaireProperties.getSearchAPIURLLast()+"datasets/count?format=json";
309
        if(params != "") {
310
          url += "&q=" + params;
311
        }
312
        return this.numOfDatasets(url);
313
    }
314
}