Project

General

Profile

1 50169 argiro.kok
import {Injectable} from '@angular/core';
2
import {Http, Response} from '@angular/http';
3 55964 argiro.kok
import {HttpClient, HttpErrorResponse} from "@angular/common/http";
4
import {Observable, throwError} from 'rxjs';
5 50169 argiro.kok
import {AutoCompleteValue} from '../../searchPages/searchUtils/searchHelperClasses.class';
6 55964 argiro.kok
7
8
9 50586 argiro.kok
import{EnvProperties} from '../properties/env-properties';
10 50169 argiro.kok
11
import {StringUtils} from '../string-utils.class';
12 55964 argiro.kok
import {catchError, map} from "rxjs/operators";
13 50169 argiro.kok
@Injectable()
14
export class EntitiesSearchService {
15
    public ready:boolean = false;
16 55964 argiro.kok
    constructor(private http: HttpClient ) {}
17 50169 argiro.kok
18 50586 argiro.kok
    searchProjectsByFunder(keyword:string, funderId:string, properties:EnvProperties ):any {
19 50169 argiro.kok
      this.ready = false;
20 50586 argiro.kok
      let url = properties.searchResourcesAPIURL;
21 54775 konstantin
      //console.log("Funder is " + funderId);
22 50169 argiro.kok
      url = url+"?query=(oaftype exact project and deletedbyinference=false) ";
23
      if(keyword!= null && keyword != ''  ) {
24
        url +=  'and ((projectcode_nt exact "'+keyword+'" )or('+keyword+')) ' ;
25
        url+=((funderId && funderId.length > 0 )?("&fq=funder exact " + '"'+funderId+ '"'):"");
26
      }
27
28
      url += "&page=0&size=10";
29
      url += "&format=json";
30 54775 konstantin
      //console.log("URL " + url);
31 50586 argiro.kok
      // let url =  properties.searchAPIURLLAst+"projects?"+((keyword && keyword.length > 0)?("q=" +keyword):"")+((funderId && funderId.length > 0 )?"&fq=funder exact " + '"'+funderId+ '"':"")+"&size=10&page=0&format=json";
32
      return this.http.get((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)): url).toPromise()
33 50169 argiro.kok
      .then(request =>
34
        {
35 55964 argiro.kok
          //request = request.json().results;
36
          request = request['results'];
37 50169 argiro.kok
          this.ready = true;
38
          return this.parse(request,"oaf:project","project");
39
        }).catch((ex) => {
40
          console.error('An error occured', ex);
41
          return  [{id:'-2',label:'Error'}];;
42
        });
43
      }
44 50586 argiro.kok
      searchByDepositType(keyword:string, DepositType:string, properties:EnvProperties ):any {
45 50169 argiro.kok
        this.ready = false;
46
47 50586 argiro.kok
        let link = properties.searchResourcesAPIURL;
48 50169 argiro.kok
49
        let url = link+"?query=";
50
        if(keyword!= null && keyword != ''  ) {
51 54755 konstantin
          /*url += "((oaftype exact organization and deletedbyinference=false and "+
52 52016 argiro.kok
            "(reldatasourcecompatibilityid=driver or reldatasourcecompatibilityid=driver-openaire2.0 or reldatasourcecompatibilityid=openaire2.0 or reldatasourcecompatibilityid=openaire3.0 or reldatasourcecompatibilityid=openaire2.0_data or reldatasourcecompatibilityid=hostedBy or relprojectid=* or reldatasourcecompatibilityid = native))"+
53 50169 argiro.kok
            " and ((organizationlegalname all "+'"'+keyword+'"'+") or (organizationlegalshortname all "+'"'+keyword+'"'+")) " +
54
            // "and " + this.quote(params) + " " +
55 54755 konstantin
            "and (collectedfrom exact "+StringUtils.quote(StringUtils.URIEncode(DepositType))+")) "*/
56 50169 argiro.kok
57 54755 konstantin
            // in search there is this filter:
58
            //reldatasourcecompatibilityid exact driver or reldatasourcecompatibilityid exact driver-openaire2.0 or reldatasourcecompatibilityid exact openaire2.0 or reldatasourcecompatibilityid exact openaire3.0 or reldatasourcecompatibilityid exact openaire2.0_data or reldatasourcecompatibilityid exact hostedBy or relproject=*
59
60
61
          //url += "((oaftype exact organization and deletedbyinference=false )"+
62
          url += "((oaftype exact organization and deletedbyinference=false and"+
63
            "(reldatasourcecompatibilityid=driver or reldatasourcecompatibilityid=driver-openaire2.0 or reldatasourcecompatibilityid=openaire2.0 or reldatasourcecompatibilityid=openaire3.0 or reldatasourcecompatibilityid=openaire2.0_data or reldatasourcecompatibilityid=hostedBy or relprojectid=* or reldatasourcecompatibilityid = native))"+
64
            " and ((organizationlegalname all "+'"'+keyword+'"'+") or (organizationlegalshortname all "+'"'+keyword+'"'+")) " +
65
            // "and " + this.quote(params) + " " +
66
            //"and (collectedfrom exact "+StringUtils.quote(StringUtils.URIEncode(DepositType))+")) "
67
            ")";
68 50169 argiro.kok
        }
69
70
        url += "&page=0&size=10";
71
        url += "&format=json";
72
73 50586 argiro.kok
        // let url =  properties.searchAPIURLLAst+"projects?"+((keyword && keyword.length > 0)?("q=" +keyword):"")+((funderId && funderId.length > 0 )?"&fq=funderid exact " + '"'+funderId+ '"':"")+"&size=10&page=0&format=json";
74
        return this.http.get((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)): url).toPromise()
75 50169 argiro.kok
        .then(request =>
76
          {
77 55964 argiro.kok
            //request = request.json().results;
78
            request = request['results'];
79 54775 konstantin
            //console.log(request);
80 50169 argiro.kok
            this.ready = true;
81
            return this.parse(request,"oaf:organization","organization");
82
          }).catch((ex) => {
83
            console.error('An error occured', ex);
84
            return  [{id:'-2',label:'Error'}];;
85
          });
86
        }
87
88 50586 argiro.kok
    searchByType(keyword:string,type:string, properties:EnvProperties ){
89 50169 argiro.kok
       if (type == "project"){
90 50586 argiro.kok
         return  this.searchEntity(keyword,"projects","oaf:project","project", properties);
91 50169 argiro.kok
      }else if (type == "dataset"){
92 50586 argiro.kok
        return  this.searchEntity(keyword,"datasets","oaf:result","dataset", properties);
93 50169 argiro.kok
      }else if (type == "datasource" || type == "hostedBy" || type== "collectedFrom"){
94 50586 argiro.kok
        return  this.searchEntity(keyword,"datasources","oaf:datasource","datasource", properties);
95 50169 argiro.kok
      }else if (type == "publication"){
96 50586 argiro.kok
        return  this.searchEntity(keyword,"publications","oaf:result","publication", properties);
97 50169 argiro.kok
      }else if (type == "organization"){
98 50586 argiro.kok
        return  this.searchEntity(keyword,"organizations","oaf:organization","organization", properties);
99 50169 argiro.kok
100
      }
101
102
    }
103 50586 argiro.kok
    fetchByType(id:string,type:string, properties:EnvProperties ){
104 50169 argiro.kok
       if (type == "project"){
105 50586 argiro.kok
         return  this.fetchEntity(id,"projects","oaf:project","project", properties);
106 50169 argiro.kok
      }else if (type == "dataset"){
107 50586 argiro.kok
        return  this.fetchEntity(id,"datasets","oaf:result","dataset", properties);
108 50169 argiro.kok
      }else if (type == "datasource"  || type == "hostedBy" || type== "collectedFrom"){
109 50586 argiro.kok
        return  this.fetchEntity(id,"datasources","oaf:datasource","datasource", properties);
110 50169 argiro.kok
      }else if (type == "publication"){
111 50586 argiro.kok
        return  this.fetchEntity(id,"publications","oaf:result","publication", properties);
112 50169 argiro.kok
      }else if (type == "organization"){
113 50586 argiro.kok
        return  this.fetchEntity(id,"organizations","oaf:organization","organization", properties);
114 50169 argiro.kok
115
      }
116
117
    }
118 50586 argiro.kok
private searchEntity (keyword: string,APIname:string,oafEntityType:string, type:string, properties:EnvProperties ):any {
119
      let link = properties.searchAPIURLLAst+APIname;
120
      return this.search(link,keyword,oafEntityType,type, properties)
121 50169 argiro.kok
122
}
123 50586 argiro.kok
private fetchEntity (id: string,APIname:string,oafEntityType:string, type:string, properties:EnvProperties ):any {
124
    let link = properties.searchAPIURLLAst+APIname;
125
    return this.fetch(link,id,oafEntityType,type, properties)
126 50169 argiro.kok
}
127 50586 argiro.kok
private fetch (link,id,oafEntityType,type, properties:EnvProperties ){
128 50169 argiro.kok
  this.ready = false;
129
  let url = link+"/"+id+"?format=json";
130 50586 argiro.kok
  return this.http.get((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)): url)
131 55964 argiro.kok
    //.map(request => <any> request.json())
132 50169 argiro.kok
    // .do(res => console.info(res))
133 55964 argiro.kok
    .pipe(map(request => {
134 50169 argiro.kok
      this.ready = true;
135
      return this.parse(request,oafEntityType,type);
136 55964 argiro.kok
    }))
137
    .pipe(catchError((ex) => {
138 50169 argiro.kok
      console.error('An error occured', ex);
139
      return  [{id:'-2',label:'Error'}];;
140 55964 argiro.kok
    }));
141 50169 argiro.kok
142
}
143 50586 argiro.kok
    private search (link,keyword,oafEntityType,type, properties:EnvProperties ){
144 50169 argiro.kok
      this.ready = false;
145
      let url = link+"?";
146
      if(keyword!= null && keyword != ''  ) {
147 54746 konstantin
          if(type=="project") {
148
            //name, title, acronym, grantid
149
            url += "fq="+'(projectcode_nt="'+keyword+'" ) or (fundershortname='+'"'+keyword+ '"'+') or (projectacronym="'+keyword+'" ) or (projecttitle="'+keyword+'")';
150
          } else if(type=="organization") {
151
            //name fields
152
            url += "fq="+'(organizationlegalname="'+keyword+'" ) or (organizationlegalshortname='+'"'+keyword+ '")';
153
          } else {
154
            url += "q="+ keyword;
155
          }
156 50169 argiro.kok
      }
157
158
      url += "&page=0&size="+10+"&format=json";
159 50586 argiro.kok
      return this.http.get((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)): url).toPromise()
160 50169 argiro.kok
                 .then(request =>
161
                   {
162 55964 argiro.kok
                     //request = request.json().results;
163
                     request = request['results'];
164 50169 argiro.kok
                     this.ready = true;
165
                     return this.parse(request,oafEntityType,type);
166
                   }).catch((ex) => {
167
                     console.error('An error occured', ex);
168
                     return [{id:'-2',label:'Error'}];
169
                   });
170
171
172
    }
173
174
    private parse(data: any,oafEntityType:string, type:string){
175
      var array:any =[]
176
      let length = Array.isArray(data) ? data.length : 1;
177
178
      for(let i=0; i<length; i++) {
179
            let resData = Array.isArray(data) ? data[i]['result']['metadata']['oaf:entity'][oafEntityType] : data['result']['metadata']['oaf:entity'][oafEntityType];
180
181
            var value:any={} ;
182
            if(resData['title']){
183
              if(Array.isArray(resData['title'])) {
184
                    value.label = resData['title'][0];
185
              } else {
186
                    value.label = resData['title'];
187
              }
188
              if(oafEntityType=="oaf:result"){
189
                value.label = value.label.content;
190
                value.result = resData;
191
              }
192
            }else if(resData["fullname"]){
193
              if(Array.isArray(resData["fullname"])) {
194
                    value.label = resData["fullname"][0];
195
              } else {
196
                    value.label = resData["fullname"];
197
              }
198
            }else if(resData["legalname"]){
199
200
              if(Array.isArray(resData["legalname"])) {
201
                    value.label = resData["legalname"][0];
202
              } else {
203
                    value.label = resData["legalname"];
204
              }
205 54461 argiro.kok
              if(resData["legalshortname"]){
206 50169 argiro.kok
207 54461 argiro.kok
                if(Array.isArray(resData["legalshortname"])) {
208
                      value.label += " (" + resData["legalshortname"][0] +")";
209
                } else {
210
                      value.label += " (" +  resData["legalshortname"] +")";
211
                }
212
              }
213
214 50169 argiro.kok
            }else if(resData["officialname"]){
215
216
              if(Array.isArray(resData["officialname"])) {
217
                    value.label = resData["officialname"][0];
218
              } else {
219
                    value.label = resData["officialname"];
220
              }
221
            }
222
223
           value.id = Array.isArray(data) ? data[i]['result']['header']['dri:objIdentifier'] : data['result']['header']['dri:objIdentifier'];
224
225
             if(type=="project"){
226
                  value.projectAcronym = resData['acronym'];
227
                  value.projectName = value.label;
228
                  value.endDate = null;
229
                  value.startDate = null;
230
                  value.funderId = "";
231
                  value.funderName = "";
232
                  value.jurisdiction = "";
233
                  value.fundingLevel0 = "";
234
                  value.code =  resData['code'];
235
236
                  if(resData['fundingtree'] && resData['fundingtree']['funder']){
237
                    value.funderId = (resData['fundingtree']['funder']['id'] )?resData['fundingtree']['funder']['id']:"";
238
                    value.funderName = (resData['fundingtree']['funder']['shortname'] )?resData['fundingtree']['funder']['shortname']:"";
239
                    value.jurisdiction = (resData['fundingtree']['funder']['jurisdiction'] )?resData['fundingtree']['funder']['jurisdiction']:"";
240
                    if(resData['fundingtree']['funding_level_2']){
241
                      value.fundingLevel0 = (resData['fundingtree']['funding_level_2'] && resData['fundingtree']['funding_level_2']['parent'] &&
242
                       resData['fundingtree']['funding_level_2']['parent']['funding_level_1'] && resData['fundingtree']['funding_level_2']['parent']['funding_level_1']['parent']
243
                     && resData['fundingtree']['funding_level_2']['parent']['funding_level_1']['parent']['funding_level_0'])?
244
                      resData['fundingtree']['funding_level_2']['parent']['funding_level_1']['parent']['funding_level_0']['name']:"";
245
                    }else if(resData['fundingtree']['funding_level_1']){
246
                      value.fundingLevel0 = (resData['fundingtree']['funding_level_1'] && resData['fundingtree']['funding_level_1']['parent'] && resData['fundingtree']['funding_level_1']['parent']['funding_level_0'])?
247
                      resData['fundingtree']['funding_level_1']['parent']['funding_level_0']['name']:"";
248
                    }else if(resData['fundingtree']['funding_level_0']){
249
                      value.fundingLevel0 = (resData['fundingtree']['funding_level_0']  )?resData['fundingtree']['funding_level_0']['name']:"";
250
                    }else {
251
                      value.fundingLevel0="";
252
                    }
253
                  }
254
255
                  if(resData.hasOwnProperty("startdate")) {
256
                    value.startDate = resData.startdate.split('-')[0];
257
                  }
258
                  if(resData.hasOwnProperty("enddate")) {
259
                    value.endDate = resData.enddate.split('-')[0];
260
                  }
261
262
             }
263
            //  console.info("add:"+value.label+"   "+value.id);
264
265
              array.push(value);
266
        }
267
        if(array.length == 0){
268
          array.push({id:'-1',label:'No results found'});
269
        }
270 54775 konstantin
        //console.info("Parsing results.... Size:"+array.length);
271 50169 argiro.kok
272
        return array;
273
    }
274
275 55964 argiro.kok
    private handleError (error: HttpErrorResponse) {
276 50169 argiro.kok
      // in a real world app, we may send the error to some remote logging infrastructure
277
      // instead of just logging it to the console
278
      console.log(error);
279 55964 argiro.kok
      return throwError(error  || 'Server error');
280 50169 argiro.kok
    }
281
}