Project

General

Profile

1
import {Injectable} from '@angular/core';
2
import {Http, Response} from '@angular/http';
3
import {Observable}     from 'rxjs/Observable';
4
import 'rxjs/add/observable/of';
5
import 'rxjs/add/operator/do';
6
import 'rxjs/add/operator/share';
7
import {   } from '../shared/cache.service';
8
import {OpenaireProperties} from '../utils/properties/openaireProperties';
9
import {SearchResult}     from '../utils/entities/searchResult';
10
import {RefineResultsUtils} from './servicesUtils/refineResults.class';
11

    
12
@Injectable()
13
export class SearchProjectsService {
14
    private sizeOfDescription: number = 270;
15

    
16
    constructor(private http: Http ) {}
17

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

    
20
        console.info("In searchProjects");
21

    
22
        let link = OpenaireProperties.getSearchAPIURLLast()+"projects";
23

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

    
33

    
34
        return this.http.get((OpenaireProperties.isCacheEnabled())? (OpenaireProperties.getCacheUrl()+encodeURIComponent(url)): url)
35
                    .map(res => <any> res.json())
36
                    //.do(res => console.info(res))
37
                    .map(res => [res['meta'].total, this.parseResults(res['results']),RefineResultsUtils.parse(res['refineResults'],refineFields, "project")]);
38
    }
39
    getProjectsforDataProvider (datasourceId: string, page: number, size: number ):any {
40
      let url = OpenaireProperties.getSearchResourcesAPIURL();
41
      var basicQuery = "(oaftype exact project) "
42
      url += "?query=";
43
      if(datasourceId!= null && datasourceId != ''  ) {
44
        url +=" ( "+basicQuery+ " ) " +" and (collectedfromdatasourceid exact \"" + datasourceId + "\")";
45
      }else{
46
        url +=" ( "+basicQuery+ " ) ";
47
      }
48

    
49
      url += "&page="+(page-1)+"&size="+size;
50
      url += "&format=json";
51

    
52
      return this.http.get((OpenaireProperties.isCacheEnabled())? (OpenaireProperties.getCacheUrl()+encodeURIComponent(url)): url)
53
      .map(res => <any> res.json())
54
      .map(res => [res['meta'].total, this.parseResults(res['results'])]);
55
    }
56
    advancedSearchProjects (params: string, page: number, size: number ):any {
57
      let url = OpenaireProperties.getSearchResourcesAPIURL();
58
      var basicQuery = "(oaftype exact project) "
59
      url += "?query=";
60
      if(params!= null && params != ''  ) {
61
        url +=" ( "+basicQuery+ " ) " +" and (" + params + ")";
62
      }else{
63
        url +=" ( "+basicQuery+ " ) ";
64
      }
65

    
66
      url += "&page="+(page-1)+"&size="+size;
67
      url += "&format=json";
68
      return this.http.get((OpenaireProperties.isCacheEnabled())? (OpenaireProperties.getCacheUrl()+encodeURIComponent(url)): url)
69
      .map(res => <any> res.json())
70
      //.do(res => console.info(res))
71
      .map(res => [res['meta'].total, this.parseResults(res['results'])]);
72
    }
73
    getProjectsForOrganizations (organizationId: string, filterquery: string, page: number, size: number, refineFields:string[]  ):any {
74
      let url = OpenaireProperties.getSearchResourcesAPIURL();
75
      var basicQuery = "(oaftype exact project) "
76
      url += "?query=";
77
      if(filterquery!= null && filterquery != ''  ) {
78
        url +="( ( "+basicQuery+ " )  and (relorganizationid exact \"" + organizationId + "\")"+"  " + filterquery + ")";
79
      }else{
80
        url +=" (( "+basicQuery+ " ) " +" and (relorganizationid exact \"" + organizationId + "\"))";
81
      }
82
      if(refineFields!= null && refineFields.length > 0 ) {
83
        url +="&refine=true";
84
        for(let i=0; i< refineFields.length ; i++ ){
85
          url +="&fields="+refineFields[i];
86
        }
87
      }
88
      url += "&page="+(page-1)+"&size="+size;
89
      url += "&format=json";
90

    
91
      return this.http.get((OpenaireProperties.isCacheEnabled())? (OpenaireProperties.getCacheUrl()+encodeURIComponent(url)): url)
92
                  .map(res => <any> res.json())
93
                  //.do(res => console.info(res))
94
                  .map(res => [res['meta'].total, this.parseResults(res['results']),RefineResultsUtils.parse(res['refineResults'],refineFields, "project")]);
95
    }
96
    getFunders():any {
97
       let url = OpenaireProperties.getSearchAPIURLLast()+"projects?refine=true&fields=funder&size=0"+ "&format=json";;
98

    
99
       return this.http.get((OpenaireProperties.isCacheEnabled())? (OpenaireProperties.getCacheUrl()+encodeURIComponent(url)): url)
100
                   .map(res => <any> res.json())
101
                   .map(res => [res['meta'].total, res['refineResults']['funder']]);
102

    
103

    
104
      }
105

    
106
      searchForProjectsObs(keyword:string, funderId:string):any {
107
         let url = 'search?action=search&sTransformer=projects_openaire&query='+
108
         '%28oaftype+exact+project%29+and+%28%28projecttitle+%3D+%22'+keyword+'%22%29+or+%28projectacronym+%3D+%22'+keyword+'%22%29+or+%28projectcode+%3D+%22'+keyword+'%22%29%29+and+%28funder+exact+'+funderId+'%29&size=10&locale=en_GB&format=json';
109

    
110
         return this.http.get((OpenaireProperties.isCacheEnabled())? (OpenaireProperties.getCacheUrl()+encodeURIComponent(url)): url).toPromise()
111
                    .then(request =>{
112
                      return (request.json().response.results)?request.json().response.results.result:request.json().response.result;
113

    
114
                }) ;
115
        }
116
    parseResults(data: any): SearchResult[] {
117
        let results: SearchResult[] = [];
118

    
119
        let length = Array.isArray(data) ? data.length : 1;
120

    
121
        for(let i=0; i<length; i++) {
122
            let resData = Array.isArray(data) ? data[i]['result']['metadata']['oaf:entity']['oaf:project'] : data['result']['metadata']['oaf:entity']['oaf:project'];
123

    
124
            var result: SearchResult = new SearchResult();
125

    
126
            result['title'] = {"name": '', "accessMode": '', "sc39": ''};
127
            if(resData['acronym'] != undefined && resData['acronym'] != "") {
128
                result['title'].name = resData['acronym'] + " - ";
129
            }
130
            if(Array.isArray(resData['title'])) {
131
                // resData['title'][0].hasOwnProperty("content") {
132
                    result['title'].name += resData['title'][0];
133
                // }
134
            } else {
135
                // resData['title'].hasOwnProperty("content") {
136
                    result['title'].name += resData['title'];
137
                // }
138
            }
139

    
140
            if(result['title'].name != '') {
141
                result['title'].name += " ("+resData['code']+")"
142
            }
143

    
144
            if(resData['ecsc39'] == true) {
145
                result['title'].sc39 = "sc39";
146
            }
147

    
148

    
149

    
150
            // if(resData['title'].hasOwnProperty("content")) {
151
            //     result['title'].name = resData['title'].content;
152
            // }
153
            //result['title'].url = OpenaireProperties.getsearchLinkToProject();
154
            //result['title'].url += Array.isArray(data) ? data[i]['result']['header']['dri:objIdentifier'] : data['result']['header']['dri:objIdentifier'];
155
            result['id'] = Array.isArray(data) ? data[i]['result']['header']['dri:objIdentifier'] : data['result']['header']['dri:objIdentifier'];
156

    
157
            if(resData['rels'].hasOwnProperty("rel")) {
158
                let relLength = Array.isArray(resData['rels']['rel']) ? resData['rels']['rel'].length : 1;
159

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

    
163
                    if(relation.hasOwnProperty("to")) {
164
                         if(relation['to'].class == "hasParticipant") {
165
                            if(result['organizations'] == undefined) {
166
                                result['organizations'] = new Array<
167
                                    { "name": string, "id": string}>();
168
                            }
169

    
170
                            let countOrganizations = result['organizations'].length;
171

    
172
                            result['organizations'][countOrganizations] = { "name": "", "id": "" }
173

    
174
                            result['organizations'][countOrganizations]['id'] =
175
                                /*OpenaireProperties.getsearchLinkToOrganization() + */relation['to'].content;
176
                            if(relation.legalshortname) {
177
                              result['organizations'][countOrganizations]['name'] = relation.legalshortname;
178
                            } else {
179
                              result['organizations'][countOrganizations]['name'] = relation.legalname;
180
                            }
181
                        }
182
                    }
183
                }
184
            }
185
            if(resData.hasOwnProperty("fundingtree")) {
186
              if(result['funders'] == undefined) {
187
                  result['funders'] = new Array<
188
                      {"funderShortname": string, "funderName": string}>();
189
              }
190

    
191
                let fundingLength = Array.isArray(resData['fundingtree']) ? resData['fundingtree'].length : 1;
192

    
193
                for(let z=0; z<fundingLength; z++) {
194
                    let fundingData = Array.isArray(resData['fundingtree']) ? resData['fundingtree'][z] : resData['fundingtree'];
195
                      let countFunders = result['funders'].length;
196
                    if(fundingData.hasOwnProperty("funder")) {
197
                        result['funders'][countFunders] =   {"funderShortname": "", "funderName": ""};
198
                        result['funders'][countFunders]['funderShortname'] = fundingData['funder'].shortname;
199
                        result['funders'][countFunders]['funderName'] = fundingData['funder'].name;
200
                    }
201
                }
202
            }
203
            if(resData.hasOwnProperty("startdate")) {
204
              result.startYear = resData.startdate.split('-')[0];
205
            }
206
            if(resData.hasOwnProperty("enddate")) {
207
              result.endYear = resData.enddate.split('-')[0];
208
            }
209

    
210
            results.push(result);
211
        }
212

    
213
        return results;
214
    }
215

    
216
    numOfProjects(url: string):any {
217

    
218
      return this.http.get((OpenaireProperties.isCacheEnabled())? (OpenaireProperties.getCacheUrl()+encodeURIComponent(url)): url)
219
                  .map(res => <any> res.json())
220
                  .map(res => res.total);
221
    }
222

    
223
    numOfEntityProjects(id: string, entity: string):any {
224
        //let url = OpenaireProperties.getSearchAPIURLLast()+params+(params.indexOf("?") == -1 ?"?":"&")+"format=json";
225
        var parameters: string = "";
226
        if(entity == "organization") {
227
          parameters = "organizations/"+id+"/projects/count";
228
        }
229

    
230
        let url = OpenaireProperties.getSearchAPIURLLast()+parameters+ "?format=json";
231

    
232
        return this.numOfProjects(url);
233
    }
234

    
235
    numOfSearchProjects(params: string):any {
236
        let url = OpenaireProperties.getSearchAPIURLLast()+"projects/count?format=json";
237
        if(params != "") {
238
          url += "&q=" + params;
239
        }
240
        return this.numOfProjects(url);
241
    }
242
}
(16-16/19)