Project

General

Profile

« Previous | Next » 

Revision 61411

[Library | Trunk]: Delete angular 11 branch

View differences:

modules/uoa-services-library/branches/angular-11/ng-openaire-library/ng-package.json
1
{
2
  "$schema": "./node_modules/ng-packagr/ng-package.schema.json",
3
  "lib": {
4
    "entryFile": "public_api.ts"
5
  }
6
}
modules/uoa-services-library/branches/angular-11/ng-openaire-library/tslint.json
1
{
2
  "rulesDirectory": [
3
    "node_modules/codelyzer"
4
  ],
5
  "rules": {
6
    "arrow-return-shorthand": true,
7
    "callable-types": true,
8
    "class-name": true,
9
    "comment-format": [
10
      true,
11
      "check-space"
12
    ],
13
    "curly": true,
14
    "deprecation": {
15
      "severity": "warn"
16
    },
17
    "eofline": true,
18
    "forin": true,
19
    "import-blacklist": [
20
      true,
21
      "rxjs/Rx",
22
      "rxjs/operators"
23
    ],
24
    "import-spacing": true,
25
    "indent": [
26
      true,
27
      "spaces"
28
    ],
29
    "interface-over-type-literal": true,
30
    "label-position": true,
31
    "max-line-length": [
32
      true,
33
      140
34
    ],
35
    "member-access": false,
36
    "member-ordering": [
37
      true,
38
      {
39
        "order": [
40
          "static-field",
41
          "instance-field",
42
          "static-method",
43
          "instance-method"
44
        ]
45
      }
46
    ],
47
    "no-arg": true,
48
    "no-bitwise": true,
49
    "no-console": [
50
      true,
51
      "debug",
52
      "info",
53
      "time",
54
      "timeEnd",
55
      "trace"
56
    ],
57
    "no-construct": true,
58
    "no-debugger": true,
59
    "no-duplicate-super": true,
60
    "no-empty": false,
61
    "no-empty-interface": true,
62
    "no-eval": true,
63
    "no-inferrable-types": [
64
      true,
65
      "ignore-params"
66
    ],
67
    "no-misused-new": true,
68
    "no-non-null-assertion": true,
69
    "no-shadowed-variable": true,
70
    "no-string-literal": false,
71
    "no-string-throw": true,
72
    "no-switch-case-fall-through": true,
73
    "no-trailing-whitespace": true,
74
    "no-unnecessary-initializer": true,
75
    "no-unused-expression": true,
76
    "no-use-before-declare": true,
77
    "no-var-keyword": true,
78
    "object-literal-sort-keys": false,
79
    "one-line": [
80
      true,
81
      "check-open-brace",
82
      "check-catch",
83
      "check-else",
84
      "check-whitespace"
85
    ],
86
    "prefer-const": true,
87
    "quotemark": [
88
      true,
89
      "single"
90
    ],
91
    "radix": true,
92
    "semicolon": [
93
      true,
94
      "always"
95
    ],
96
    "triple-equals": [
97
      true,
98
      "allow-null-check"
99
    ],
100
    "typedef-whitespace": [
101
      true,
102
      {
103
        "call-signature": "nospace",
104
        "index-signature": "nospace",
105
        "parameter": "nospace",
106
        "property-declaration": "nospace",
107
        "variable-declaration": "nospace"
108
      }
109
    ],
110
    "typeof-compare": true,
111
    "unified-signatures": true,
112
    "variable-name": false,
113
    "whitespace": [
114
      true,
115
      "check-branch",
116
      "check-decl",
117
      "check-operator",
118
      "check-separator",
119
      "check-type"
120
    ],
121
    "directive-selector": [
122
      true,
123
      "attribute",
124
      "app",
125
      "camelCase"
126
    ],
127
    "component-selector": [
128
      true,
129
      "element",
130
      "app",
131
      "kebab-case"
132
    ],
133
    "no-output-on-prefix": true,
134
    "use-input-property-decorator": true,
135
    "use-output-property-decorator": true,
136
    "use-host-property-decorator": true,
137
    "no-input-rename": true,
138
    "no-output-rename": true,
139
    "use-life-cycle-interface": true,
140
    "use-pipe-transform-interface": true,
141
    "component-class-suffix": true,
142
    "directive-class-suffix": true
143
  }
144
}
modules/uoa-services-library/branches/angular-11/ng-openaire-library/src/main.server.ts
1
export { AppServerModule } from './app/app.server.module';
modules/uoa-services-library/branches/angular-11/ng-openaire-library/src/app/cache-interceptor.service.ts
1
import { Injectable, Inject, PLATFORM_ID } from '@angular/core';
2
import { HttpInterceptor, HttpRequest, HttpHandler } from '@angular/common/http';
3
import { TransferState } from '@angular/platform-browser';
4
import { properties } from "../../environments/environment";
5

  
6
@Injectable({
7
  providedIn: 'root'
8
})
9
export class CacheInterceptorService implements HttpInterceptor {
10
  cachingRequests = [
11
    // Remove 2 following lines when bug with hidden refine filters is solved.
12
    "/resources2/?format=json&refine=true&fields=resultbestaccessright&fields=relfunder&fields=relfundinglevel0_id&fields=relproject&fields=instancetypename&fields=resultlanguagename&fields=community&fields=resulthostingdatasource&fields=country&&fq=resultbestaccessright exact \"Open Access\"&type=results&page=0&size=0",
13
    "/resources2/?format=json&refine=true&fields=funder&fields=fundinglevel0_id&fields=projectstartyear&fields=projectendyear&fields=projectecsc39&&type=projects&page=0&size=0",
14

  
15
    "/resources2/?format=json&refine=true&fields=resultbestaccessright&fields=relfunder&fields=instancetypename&fields=resultlanguagename&fields=community&fields=resulthostingdatasource&fields=country&&type=results&page=0&size=0",
16
    "/resources2/?format=json&refine=true&fields=resultbestaccessright&fields=relfunder&fields=relfundinglevel0_id&fields=relproject&fields=instancetypename&fields=resultlanguagename&fields=community&fields=resulthostingdatasource&fields=country&&fq=resultbestaccessright%20exact%20%22Open%20Access%22&fq=relfunder%20exact%20%22ec__________%3A%3AEC%7C%7CEuropean%20Commission%7C%7CEC%22&type=results&page=0&size=0",
17

  
18
    "/resources2/?format=json&refine=true&fields=resultbestaccessright&fields=relfunder&fields=instancetypename&fields=resultlanguagename&fields=community&fields=resulthostingdatasource&fields=country&&fq=resultbestaccessright%20exact%20%22Open%20Access%22&type=results&page=0&size=0",
19
    "/resources2/?format=json&refine=true&fields=resultbestaccessright&fields=relfunder&fields=instancetypename&fields=resultlanguagename&fields=community&fields=resulthostingdatasource&fields=country&&fq=resultbestaccessright exact \"Open Access\"&type=results&page=0&size=0",
20
    "/resources2/?format=json&refine=true&fields=funder&fields=projectstartyear&fields=projectendyear&fields=projectecsc39&&type=projects&page=0&size=0",
21
    "/resources2/?format=json&refine=true&fields=datasourcetypeuiname&fields=datasourceodlanguages&fields=datasourceodcontenttypes&fields=datasourcecompatibilityname&fields=country&fields=collectedfromname&&type=datasources&page=0&size=0",
22
    "/resources2/?format=json&query= ( (reldatasourcecompatibilityid exact driver or reldatasourcecompatibilityid exact driver-openaire2.0 or reldatasourcecompatibilityid exact openaire2.0 or reldatasourcecompatibilityid exact openaire3.0 or reldatasourcecompatibilityid exact openaire4.0 or reldatasourcecompatibilityid exact openaire-cris_1.1 or reldatasourcecompatibilityid exact openaire2.0_data or reldatasourcecompatibilityid exact hostedBy or relproject=*) ) &refine=true&fields=country&&type=organizations&page=0&size=0",
23

  
24
    "/projects/?format=json&refine=true&page=1&size=0&fields=funder",
25

  
26
    "/resources/?format=json&query=( oaftype exact datasource  )&refine=true&fields=datasourcetypeuiname&fields=country&fields=datasourceodsubjects&fields=datasourceodcontenttypes&fields=datasourcecompatibilityname&&type=datasources&page=0&size=0",
27

  
28
    "/search/v2/api/datasources/count?format=json", "/search/v2/api/publications/count?format=json", "/search/v2/api/datasets/count?format=json", "/search/v2/api/software/count?format=json", "/search/v2/api/other/count?format=json",
29
    "relresulttype%3Dpublication"
30
  ];
31

  
32

  
33
  constructor(private transferState: TransferState, @Inject(PLATFORM_ID) private platformId: any) {}
34

  
35
  public intercept(request: HttpRequest<any>, next: HttpHandler): any {
36
    // console.debug(new Date());
37

  
38
    if(this.checkForCachedRequests(request.url)) {
39
      const dupReq = request.clone({url: properties.cacheUrl + encodeURIComponent(request.url)});
40
      return next.handle(dupReq);
41
    } else {
42
      return next.handle(request);
43
    }
44
  }
45

  
46
  public checkForCachedRequests(url){
47
    if(url.indexOf("refine=true") !== -1 || url.indexOf("/count?format=json") !== -1 || url.indexOf("relresulttype%3Dpublication") !== -1) {
48
      return this.cachingRequests.some(partUrl => (url.indexOf(partUrl) !== -1));
49
    }
50
    return false;
51
  }
52

  
53
}
modules/uoa-services-library/branches/angular-11/ng-openaire-library/src/app/services/searchOrganizations.service.ts
1
import {Injectable} from '@angular/core';
2
import {HttpClient} from "@angular/common/http";
3

  
4

  
5

  
6
import {SearchResult}     from '../utils/entities/searchResult';
7
import {RefineResultsUtils} from './servicesUtils/refineResults.class';
8
import{EnvProperties} from '../utils/properties/env-properties';
9
import {StringUtils} from '../utils/string-utils.class';
10
import {map} from "rxjs/operators";
11
import {ParsingFunctions} from "../landingPages/landing-utils/parsingFunctions.class";
12

  
13
@Injectable()
14
export class SearchOrganizationsService {
15

  
16
    constructor(private http: HttpClient ) {}
17

  
18
    parseResultsForDeposit(data: any): {"name": string, "id": string}[] {
19
        let results: {"name": string, "id": string}[] = [];
20

  
21
        let length = Array.isArray(data) ? data.length : 1;
22

  
23
        for(let i=0; i<length; i++) {
24
            let name: string = '';
25
            let id: string = '';
26
            let resData = Array.isArray(data) ? data[i]['result']['metadata']['oaf:entity']['oaf:organization'] : data['result']['metadata']['oaf:entity']['oaf:organization'];
27
            name = resData.legalname;
28
            if(name == '') {
29
                name = resData.legalshortname;
30
            }
31

  
32
            id = Array.isArray(data) ? data[i]['result']['header']['dri:objIdentifier'] : data['result']['header']['dri:objIdentifier'];
33

  
34
            results.push({"name": name, "id": id});
35
        }
36
        return results;
37
    }
38

  
39
    searchOrganizations (params: string, refineParams:string, page: number, size: number, refineFields:string[] , properties:EnvProperties):any {
40

  
41

  
42
        let link = properties.searchAPIURLLAst+"organizations";
43

  
44
        let url = link+"?";
45
        if(params!= null && params != ''  ) {
46
            url += params;
47
        }
48
        if(refineParams!= null && refineParams != ''  ) {
49
            url += refineParams;
50
        }
51
        url += "&page="+(page-1)+"&size="+size + "&format=json";
52

  
53

  
54
        return this.http.get((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)): url)
55
                    //.map(res => <any> res.json())
56
                    .pipe(map(res => [res['meta'].total, this.parseResults(res['results']),RefineResultsUtils.parse(res['refineResults'],refineFields, "organization")]));
57
    }
58
    advancedSearchOrganizations (params: string, page: number, size: number, properties:EnvProperties, refineParams:string=null,  refineFields:string[] =null, refineQuery:string = null   ):any {
59
    // &type=organizations
60
      let url = properties.searchAPIURLLAst+"resources2/?format=json";
61
      var basicQuery = "(reldatasourcecompatibilityid exact driver or reldatasourcecompatibilityid exact driver-openaire2.0 or " +
62
                "reldatasourcecompatibilityid exact openaire2.0 or reldatasourcecompatibilityid exact openaire3.0 or reldatasourcecompatibilityid exact openaire4.0 or " +
63
                "reldatasourcecompatibilityid exact openaire-cris_1.1 or " +
64
                "reldatasourcecompatibilityid exact openaire2.0_data or reldatasourcecompatibilityid exact hostedBy or relproject=*)";
65

  
66
      url += "&query=";
67
      if(params!= null && params != ''  ) {
68
        url +=" ( "+basicQuery+ " ) " +" and (" + params + ")";
69
      }else{
70
        url +=" ( "+basicQuery+ " ) ";
71
      }
72
        if(refineParams!= null && refineParams != ''  ) {
73
            url += refineParams;
74
        }
75
        if(refineQuery) {
76
            url += "&" + refineQuery;
77
        }
78
      url += "&page="+(page-1)+"&size="+size;
79

  
80
      return this.http.get((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)): url)
81
      //.map(res => <any> res.json())
82

  
83
      .pipe(map(res => [res['meta'].total, this.parseResults(res['results']),RefineResultsUtils.parse(res['refineResults'],refineFields, "organization")]));
84
    }
85
    parseResults(data: any): SearchResult[] {
86
        let results: SearchResult[] = [];
87

  
88
        let length = Array.isArray(data) ? data.length : 1;
89

  
90
        for(let i=0; i<length; i++) {
91
             let resData = Array.isArray(data) ? data[i]['result']['metadata']['oaf:entity']['oaf:organization'] : data['result']['metadata']['oaf:entity']['oaf:organization'];
92

  
93
            var result: SearchResult = new SearchResult();
94

  
95
            result['title'] = {"name": '', "accessMode": '', "sc39": ''};
96

  
97
            result['title'].name = resData.legalshortname;
98
            if(!result['title'].name || result['title'].name == '') {
99
                result['title'].name = resData.legalname;
100
            }
101

  
102
            //result['title'].url = OpenaireProperties.getsearchLinkToOrganization();
103
            //result['title'].url += Array.isArray(data) ? data[i]['result']['header']['dri:objIdentifier'] : data['result']['header']['dri:objIdentifier'];
104
            result['id'] = Array.isArray(data) ? data[i]['result']['header']['dri:objIdentifier'] : data['result']['header']['dri:objIdentifier'];
105
            let canId = ParsingFunctions.parseRelCanonicalId(Array.isArray(data) ? data[i] : data, "organization");
106
            if(canId){
107
                result['id'] = canId;
108
            }
109
            if(resData['rels'].hasOwnProperty("rel")) {
110
                let relLength = Array.isArray(resData['rels']['rel']) ? resData['rels']['rel'].length : 1;
111

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

  
115
                    if(relation.hasOwnProperty("to")) {
116
                        if(relation['to'].class == "isParticipant") {
117
                            if(result['projects'] == undefined) {
118
                                result['projects'] = new Array<
119
                                    { "id": string, "acronym": string, "title": string,
120
                                      "funderShortname": string, "funderName": string,
121
                                      "code": string
122
                                    }>();
123
                            }
124

  
125
                            let countProjects = result['projects'].length;
126

  
127
                            result['projects'][countProjects] = {
128
                                "id": "", "acronym": "", "title": "",
129
                                "funderShortname": "", "funderName": "",
130
                                "code": ""
131
                            }
132

  
133
                            if(relation.title != 'unidentified') {
134
                                result['projects'][countProjects]['id'] =
135
                                    /*OpenaireProperties.getsearchLinkToProject() + */relation['to'].content;
136
                                result['projects'][countProjects]['acronym'] = relation.acronym;
137
                                result['projects'][countProjects]['title'] = relation.title;
138
                                result['projects'][countProjects]['code'] = relation.code;
139
                            } else {
140
                                result['projects'][countProjects]['id'] = "";
141
                                result['projects'][countProjects]['acronym'] = "";
142
                                result['projects'][countProjects]['title'] = "";
143
                                result['projects'][countProjects]['code'] = "";
144
                            }
145

  
146
                            if(relation.hasOwnProperty("funding")) {
147
                                let fundingLength = Array.isArray(relation['funding']) ? relation['funding'].length : 1;
148

  
149
                                for(let z=0; z<fundingLength; z++) {
150
                                    let fundingData = Array.isArray(relation['funding']) ? relation['funding'][z] : relation['funding'];
151

  
152
                                    if(fundingData.hasOwnProperty("funder")) {
153
                                        result['projects'][countProjects]['funderShortname'] = fundingData['funder'].shortname;
154
                                        result['projects'][countProjects]['funderName'] = fundingData['funder'].name;
155
                                    }
156
                                }
157
                            }
158

  
159
                        }
160
                    }
161
                }
162
            }
163

  
164
            if(resData.country.hasOwnProperty("classname")) {
165
                result.country = resData.country.classname;
166
            }
167

  
168
            results.push(result);
169
        }
170

  
171
        return results;
172
    }
173

  
174
    numOfOrganizations(url: string, properties:EnvProperties ): any {
175

  
176
      return this.http.get((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)): url)
177
                  //.map(res => <any> res.json())
178
                  .pipe(map(res => res['total']));
179
    }
180

  
181
    numOfEntityOrganizations(id: string, entity: string, properties:EnvProperties ):any {
182
        // currently not used - if used fix entity comparison below
183
        var parameters: string = "";
184
        if(entity == "organization") {
185
          parameters = "organizations/"+id+"/organizations/count";
186
        }
187

  
188
        let url = properties.searchAPIURLLAst+parameters+"?format=json";
189
        return this.numOfOrganizations(url, properties);
190
    }
191

  
192
    numOfSearchOrganizations(params: string, properties:EnvProperties, refineParams:string=null ):any {
193
        let url = properties.searchAPIURLLAst+"organizations/count?format=json";
194
        if(params != "") {
195
          url += "&q=" + StringUtils.URIEncode(params);
196
        }
197
        if(refineParams!= null && refineParams != ''  ) {
198
            url += refineParams;
199
        }
200
        return this.numOfOrganizations(url, properties);
201
    }
202

  
203
    numOfSearchOrganizations2(params: string, properties:EnvProperties, refineParams:string=null ):any {
204
        let url = properties.searchAPIURLLAst+"resources2/?format=json&size=0&type=organizations";
205
        var basicQuery = "(reldatasourcecompatibilityid exact driver or reldatasourcecompatibilityid exact driver-openaire2.0 or " +
206
          "reldatasourcecompatibilityid exact openaire2.0 or reldatasourcecompatibilityid exact openaire3.0 or reldatasourcecompatibilityid exact openaire4.0 or " +
207
          "reldatasourcecompatibilityid exact openaire-cris_1.1 or " +
208
          "reldatasourcecompatibilityid exact openaire2.0_data or reldatasourcecompatibilityid exact hostedBy or relproject=*)";
209

  
210
        url += "&query=";
211
        if(params!= null && params != ''  ) {
212
            url +=" ( "+basicQuery+ " ) " +" and (" + params + ")";
213
        }else{
214
            url +=" ( "+basicQuery+ " ) ";
215
        }
216
        if(refineParams!= null && refineParams != ''  ) {
217
            url += refineParams;
218
        }
219
        return this.http.get((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)): url)
220
          .pipe(map(res => res['meta']['total']));
221
    }
222
}
modules/uoa-services-library/branches/angular-11/ng-openaire-library/src/app/services/layout.service.ts
1
import {Injectable} from '@angular/core';
2
import {HttpClient, HttpErrorResponse} from '@angular/common/http';
3
import {Observable, throwError} from 'rxjs';
4
import {CustomOptions} from './servicesUtils/customOptions.class';
5
import {CustomizationOptions, Layout} from '../connect/community/CustomizationOptions';
6
import {EnvProperties} from "../utils/properties/env-properties";
7

  
8
@Injectable()
9
export class LayoutService {
10
    constructor(private http: HttpClient) {
11
    }
12

  
13
    static removeNulls(obj) {
14
        const isArray = obj instanceof Array;
15
        for (let k in obj) {
16
            if (obj[k] === null || obj[k] === '') {
17
                isArray ? obj.splice(k, 1) : delete obj[k];
18
            } else if (typeof obj[k] === 'object') {
19
                LayoutService.removeNulls(obj[k]);
20
            }
21
        }
22
    }
23

  
24
    saveLayout(properties: EnvProperties, pid: string, layout: Layout): Observable<Layout> {
25
        LayoutService.removeNulls(layout);
26
        return this.http.post<Layout>(properties.adminToolsAPIURL + '/' + properties.adminToolsPortalType + '/'
27
          + pid + '/layout', layout, CustomOptions.getAuthOptionsWithBody());
28
    }
29

  
30
    getLayout(properties: EnvProperties, pid: string): Observable<Layout> {
31
        return this.http.get<Layout>(properties.adminToolsAPIURL+"/" + properties.adminToolsPortalType + '/'
32
          + pid + '/layout');
33
    }
34

  
35
    mockLayout(): any {
36
        return this.http.get('./assets/customizationOptions.json') ;
37

  
38
    }
39

  
40
    private handleError(error: HttpErrorResponse) {
41
        // in a real world app, we may send the error to some remote logging infrastructure
42
        // instead of just logging it to the console
43
        console.error(error);
44
        return throwError(error.error || 'Server error');
45
    }
46
}
modules/uoa-services-library/branches/angular-11/ng-openaire-library/src/app/services/dataProvidersService.module.ts
1
import { NgModule}            from '@angular/core';
2
import { CommonModule }        from '@angular/common';
3
import { FormsModule }         from '@angular/forms';
4

  
5
import {SearchDataprovidersService} from './searchDataproviders.service';
6

  
7

  
8
@NgModule({
9
  imports: [
10
    CommonModule, FormsModule
11
  ],
12
  declarations: [
13
  ],
14
  providers:[
15
  SearchDataprovidersService
16
],
17
  exports: [
18
    ]
19
})
20
export class DataProvidersServiceModule { }
modules/uoa-services-library/branches/angular-11/ng-openaire-library/src/app/services/searchProjects.service.ts
1
import {Injectable} from '@angular/core';
2
import {HttpClient} from "@angular/common/http";
3

  
4

  
5

  
6
import {SearchResult}     from '../utils/entities/searchResult';
7
import {RefineResultsUtils} from './servicesUtils/refineResults.class';
8
import{EnvProperties} from '../utils/properties/env-properties';
9
import {StringUtils} from '../utils/string-utils.class';
10
import {map} from "rxjs/operators";
11
@Injectable()
12
export class SearchProjectsService {
13
    private sizeOfDescription: number = 270;
14

  
15
    constructor(private http: HttpClient ) {}
16

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

  
19
        let link = properties.searchAPIURLLAst+"projects";
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
        console.log(url)
31
        return this.http.get((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)): url)
32
                    //.map(res => <any> res.json())
33
                    .pipe(map(res => [res['meta'].total, this.parseResults(res['results']),RefineResultsUtils.parse(res['refineResults'],refineFields, "project")]));
34
    }
35
    getProjectsforDataProvider (datasourceId: string, page: number, size: number, properties:EnvProperties  ):any {
36
      let url = properties.searchResourcesAPIURL;
37
      var basicQuery = "(oaftype exact project) "
38
      url += "?query=";
39
      if(datasourceId!= null && datasourceId != ''  ) {
40
        url +=" ( "+basicQuery+ " ) " +" and (collectedfromdatasourceid exact \"" + datasourceId + "\" or resulthostingdatasourceid exact \""+ datasourceId + "\")";
41
      }else{
42
        url +=" ( "+basicQuery+ " ) ";
43
      }
44

  
45
      url += "&page="+(page-1)+"&size="+size;
46
      url += "&format=json";
47

  
48
      return this.http.get((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)): url)
49
      //.map(res => <any> res.json())
50
      .pipe(map(res => [res['meta'].total, this.parseResults(res['results'])]));
51
    }
52
    advancedSearchProjects (params: string, page: number, size: number, properties:EnvProperties, refineParams:string=null,  refineFields:string[] =null, refineQuery:string = null  ):any {
53
    // &type=projects
54
      let url = properties.searchAPIURLLAst+"resources2/?format=json";
55
      // var basicQuery = "(oaftype exact project) "
56
      // url += "?query=";
57
      if(params!= null && params != ''  ) {
58
        url +="&query=(" + params + ")";
59
      }
60
      // else{
61
      //   url +=" ( "+basicQuery+ " ) ";
62
      // }
63
      if(refineParams!= null && refineParams != ''  ) {
64
        url += refineParams;
65
      }
66
      if(refineQuery) {
67
        url += "&" + refineQuery;
68
      }
69
      url += "&page="+(page-1)+"&size="+size;
70
      // url += "&format=json";
71
      return this.http.get((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)): url)
72
      //.map(res => <any> res.json())
73
      .pipe(map(res => [res['meta'].total, this.parseResults(res['results']), RefineResultsUtils.parse(res['refineResults'],refineFields, "project")]));
74
    }
75
    
76
    getProjectsForOrganizations (organizationId: string, filterquery: string, page: number, size: number, refineFields:string[] , properties:EnvProperties  ):any {
77
      let url = properties.searchResourcesAPIURL;
78
      var basicQuery = "(oaftype exact project) "
79
      url += "?query=";
80
      if(filterquery!= null && filterquery != ''  ) {
81
        url +="( ( "+basicQuery+ " )  and (relorganizationid exact \"" + organizationId + "\")"+"  " + filterquery + ")";
82
      }else{
83
        url +=" (( "+basicQuery+ " ) " +" and (relorganizationid exact \"" + organizationId + "\"))";
84
      }
85
      if(refineFields!= null && refineFields.length > 0 ) {
86
        url +="&refine=true";
87
        for(let i=0; i< refineFields.length ; i++ ){
88
          url +="&fields="+refineFields[i];
89
        }
90
      }
91
      url += "&page="+(page-1)+"&size="+size;
92
      url += "&format=json";
93

  
94
      return this.http.get((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)): url)
95
                  //.map(res => <any> res.json())
96
                  .pipe(map(res => [res['meta'].total, this.parseResults(res['results']),RefineResultsUtils.parse(res['refineResults'],refineFields, "project")]));
97
    }
98
    getFunders(properties:EnvProperties ):any {
99
       let url = properties.searchAPIURLLAst+"projects?refine=true&fields=funder&size=0"+ "&format=json";
100

  
101
       return this.http.get((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)): url)
102
                   //.map(res => <any> res.json())
103
                   .pipe(map(res => [res['meta'].total, res['refineResults']['funder']]));
104

  
105

  
106
      }
107

  
108
      searchForProjectsObs(keyword:string, funderId:string, properties:EnvProperties ):any {
109
         let url = 'search?action=search&sTransformer=projects_openaire&query='+
110
         '%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';
111

  
112
         return this.http.get((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)): url).toPromise()
113
                    .then(request =>{
114
                      //return (request.json().response.results)?request.json().response.results.result:request.json().response.result;
115
                      return (request['response'].results)?request['response'].results.result:request['response'].result;
116

  
117
                    }) ;
118
        }
119
    parseResults(data: any): SearchResult[] {
120
        let results: SearchResult[] = [];
121

  
122
        let length = Array.isArray(data) ? data.length : 1;
123

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

  
127
            var result: SearchResult = new SearchResult();
128
            result.openAccessMandatePublications = (resData['oamandatepublications'])?true:false;
129
            result.openAccessMandateDatasets = (resData['ecarticle29_3'])?true:false;
130
            result['title'] = {"name": '', "accessMode": '', "sc39": ''};
131
            // if(resData['acronym'] != undefined && resData['acronym'] != "") {
132
            //     result['title'].name = resData['acronym'] + " - ";
133
            // }
134
            if(Array.isArray(resData['title'])) {
135
                result['title'].name += resData['title'][0];
136
            } else {
137
                result['title'].name += resData['title'];
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
            result.acronym = resData['acronym'];
149
            result.code = resData['code'];
150

  
151
            result.budget = resData.totalcost;//"10000";
152
            result.contribution = resData.fundedamount;//"200100";
153
            result.currency = resData.currency;//"EUR";
154

  
155
            result.id = Array.isArray(data) ? data[i]['result']['header']['dri:objIdentifier'] : data['result']['header']['dri:objIdentifier'];
156

  
157
            if(!Array.isArray(resData['summary'])) {
158
              result.description = (resData['summary']) ? String(resData['summary']) : "";
159
            } else {
160
              result.description = (resData['summary'][0]) ? String(resData['summary'][0]) : "";
161
            }
162

  
163
            if (result.description && result.description.length > this.sizeOfDescription) {
164
              result.description = result.description.substring(0, this.sizeOfDescription) + "...";
165
            }
166

  
167
            if(resData['rels'].hasOwnProperty("rel")) {
168
                let relLength = Array.isArray(resData['rels']['rel']) ? resData['rels']['rel'].length : 1;
169

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

  
173
                    if(relation.hasOwnProperty("to")) {
174
                         if(relation['to'].class == "hasParticipant") {
175
                            if(result['organizations'] == undefined) {
176
                                result['organizations'] = new Array<
177
                                    { "name": string, "id": string}>();
178
                            }
179

  
180
                            let countOrganizations = result['organizations'].length;
181

  
182
                            result['organizations'][countOrganizations] = { "name": "", "id": "" }
183

  
184
                            result['organizations'][countOrganizations]['id'] =
185
                                /*OpenaireProperties.getsearchLinkToOrganization() + */relation['to'].content;
186
                            if(relation.legalshortname) {
187
                              result['organizations'][countOrganizations]['name'] = relation.legalshortname;
188
                            } else {
189
                              result['organizations'][countOrganizations]['name'] = relation.legalname;
190
                            }
191
                            if(!result['organizations'][countOrganizations]['name']) {
192
                              result['organizations'][countOrganizations]['name'] = "[no title available]";
193
                            }
194
                        }
195
                    }
196
                }
197
            }
198
            if(resData.hasOwnProperty("fundingtree")) {
199
              /*let funderSet: Set<string>;
200
              if(result['funders'] == undefined) {
201
                  result['funders'] = new Array<
202
                      {"funderShortname": string, "funderName": string}>();
203
                  funderSet = new Set<string>();
204
              }
205

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

  
208
                for(let z=0; z<fundingLength; z++) {
209
                    let fundingData = Array.isArray(resData['fundingtree']) ? resData['fundingtree'][z] : resData['fundingtree'];
210
                    if(fundingData.hasOwnProperty("funder")) {
211
                        if(!funderSet.has(fundingData['funder'].shortname)) {
212
                          let countFunders = result['funders'].length;
213

  
214
                          result['funders'][countFunders] =   {"funderShortname": "", "funderName": ""};
215
                          result['funders'][countFunders]['funderShortname'] = fundingData['funder'].shortname;
216
                          result['funders'][countFunders]['funderName'] = fundingData['funder'].name;
217
                          funderSet.add(fundingData['funder'].shortname);
218
                        }
219
                    }
220
                }*/
221
                let fundingLength = Array.isArray(resData['fundingtree']) ? resData['fundingtree'].length : 1;
222

  
223
                for(let z=0; z<fundingLength; z++) {
224
                  let fundingData = Array.isArray(resData['fundingtree']) ? resData['fundingtree'][z] : resData['fundingtree'];
225
                  if(fundingData.hasOwnProperty("funder")) {
226
                    result['funderShortname'] = fundingData['funder'].shortname;
227
                    result['funderId'] = fundingData['funder'].id;
228
                    result['jurisdiction'] = (fundingData['funder']['id']['jurisdiction'] )?fundingData['funder']['id']['jurisdiction']:"";
229

  
230
                    if(fundingData['funding_level_2']){
231
                      result['fundingLevel0'] = (fundingData['funding_level_2'] && fundingData['funding_level_2']['parent'] &&
232
                       fundingData['funding_level_2']['parent']['funding_level_1'] && fundingData['funding_level_2']['parent']['funding_level_1']['parent']
233
                     && fundingData['funding_level_2']['parent']['funding_level_1']['parent']['funding_level_0'])?
234
                      fundingData['funding_level_2']['parent']['funding_level_1']['parent']['funding_level_0']['name']:"";
235
                    }else if(fundingData['funding_level_1']){
236
                      result['fundingLevel0'] = (fundingData['funding_level_1'] && fundingData['funding_level_1']['parent'] && fundingData['funding_level_1']['parent']['funding_level_0'])?
237
                      fundingData['funding_level_1']['parent']['funding_level_0']['name']:"";
238
                    }else if(fundingData['funding_level_0']){
239
                      result['fundingLevel0'] = (fundingData['funding_level_0']  )?fundingData['funding_level_0']['name']:"";
240
                    }else {
241
                      result['fundingLevel0']="";
242
                    }
243
                    break;
244
                  }
245
                }
246
            }
247
            if(resData.hasOwnProperty("startdate")) {
248
              result.startYear = resData.startdate.split('-')[0];
249
            }
250
            if(resData.hasOwnProperty("enddate")) {
251
              result.endYear = resData.enddate.split('-')[0];
252
            }
253

  
254
            results.push(result);
255
        }
256

  
257
        return results;
258
    }
259

  
260
    numOfProjects(url: string, properties:EnvProperties ):any {
261

  
262
      return this.http.get((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)): url)
263
                  //.map(res => <any> res.json())
264
                  .pipe(map(res => res['total']));
265
    }
266

  
267
    numOfEntityProjects(id: string, entity: string, properties:EnvProperties ):any {
268
        //let url = properties.searchAPIURLLAst+params+(params.indexOf("?") == -1 ?"?":"&")+"format=json";
269
        var parameters: string = "";
270
        if(entity == "organization") {
271
          parameters = "organizations/"+id+"/projects/count";
272
        }
273

  
274
        let url = properties.searchAPIURLLAst+parameters+ "?format=json";
275

  
276
        return this.numOfProjects(url, properties);
277
    }
278

  
279
    numOfSearchProjects(params: string, properties:EnvProperties, refineParams:string=null ):any {
280
        let url = properties.searchAPIURLLAst+"projects/count?format=json";
281
        if(params != "") {
282
          url += "&q=" + StringUtils.URIEncode(params);
283
        }
284
      if(refineParams!= null && refineParams != ''  ) {
285
        url += refineParams;
286
      }
287
        return this.numOfProjects(url, properties);
288
    }
289
    numOfSearchProjects2(params: string, properties:EnvProperties, refineParams:string=null ):any {
290
      let url = properties.searchAPIURLLAst+"resources2/?format=json&size=0&type=projects";
291
      if(params != "") {
292
        url += "&query=" + params;
293
      }
294
      if(refineParams!= null && refineParams != ''  ) {
295
        url += refineParams;
296
      }
297
      return this.http.get((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)): url)
298
        .pipe(map(res => res['meta']['total']));
299
    }
300
}
modules/uoa-services-library/branches/angular-11/ng-openaire-library/src/app/services/localStorage.service.ts
1
import {Inject, Injectable, PLATFORM_ID} from "@angular/core";
2
import {BehaviorSubject, Observable} from "rxjs";
3
import {isPlatformBrowser} from "@angular/common";
4

  
5
@Injectable({
6
  providedIn: "root"
7
})
8
export class LocalStorageService {
9

  
10
  private communityDirectLink: BehaviorSubject<boolean>;
11

  
12
  constructor(@Inject(PLATFORM_ID) private platformId: string) {
13
    if(isPlatformBrowser(this.platformId)) {
14
      let item = localStorage.getItem('directLink');
15
      if(item !== null) {
16
        this.communityDirectLink = new BehaviorSubject<boolean>(item == 'true');
17
      } else {
18
        this.communityDirectLink = new BehaviorSubject<boolean>(false);
19
      }
20
    } else this.communityDirectLink = new BehaviorSubject<boolean>(true);
21
  }
22

  
23
  public setCommunityDirectLink(value: string) {
24
    this.communityDirectLink.next(Boolean(value).valueOf());
25
    localStorage.setItem('directLink', value);
26
  }
27

  
28
  public get(): Observable<boolean> {
29
    return this.communityDirectLink.asObservable();
30
  }
31
}
modules/uoa-services-library/branches/angular-11/ng-openaire-library/src/app/services/servicesUtils/refineResults.class.ts
1

  
2
import { Filter, Value} from '../../searchPages/searchUtils/searchHelperClasses.class';
3
import { SearchFields, FieldDetails} from '../../utils/properties/searchFields';
4

  
5

  
6
export class RefineResultsUtils {
7

  
8

  
9
   public static parse (data, fields:string[], entityType:string, usedBy: string="search"):Filter[] {
10
         // var data = this.json.refineReuslts;
11

  
12
         var searchFields:SearchFields = new SearchFields();
13
         var filters:Filter[] = [];
14
         if(data && fields){
15
           for(let j=0; j<fields.length; j++) {
16

  
17
             var filter:Filter = new Filter();
18
             filter.title = searchFields.getFieldName(fields[j],entityType);
19
             filter.filterId = fields[j];
20
             filter.originalFilterId = fields[j];
21
             filter.filterType = searchFields.getFieldFilterType(fields[j], entityType, usedBy);
22
             filter.filterOperator = searchFields.getFieldOperator(fields[j]);
23
             filter.radioValue = "";
24
             //console.info("filter.title: "+filter.title+" filter.filterType: "+filter.filterType);
25

  
26
             let field = data[fields[j]];
27
             if(field){
28
               for(let i=0; i<field.length; i++) {
29
                 var value:Value = new Value();
30
                 value.name = field[i].name;
31
                 value.name =this.removePartAfterCharacters(value,"||");
32
                 value.number = field[i].count;
33
                 value.id = field[i].id;
34
                 if(RefineResultsUtils.includeValue(value)){
35
                   filter.values.push(value);
36
                 }
37

  
38

  
39
             }
40

  
41
               filters.push(filter);
42
           }
43
       }
44
     }
45
       return filters;
46
   }
47
   private static includeValue (field):boolean {
48
     if( !field || !field.name || field.name == "unidentified" || field.name == "Undetermined" ){
49
       return false;
50

  
51
     }
52
     return true;
53
   }
54
   private static removePartAfterCharacters(field, characters):string {
55
     if( field.name.indexOf(characters) !=-1){
56
       return field.name.split(characters)[0];
57

  
58
     }
59
     return field.name;
60
   }
61
   public static inParenthesisThePartAfterCharacters(field, characters):string {
62
     if( field.name.indexOf(characters) !=-1){
63
       return field.name.split(characters)[0]+" ("+field.name.split(characters)[1]+")";
64

  
65
     }
66
     return field.name;
67
   }
68
  public static keepPartAfterCharacters(name, characters):string {
69
    if( name.indexOf(characters) !=-1){
70
      return name.split(characters)[1];
71
    }
72
    return name;
73
  }
74
  }
modules/uoa-services-library/branches/angular-11/ng-openaire-library/src/app/services/servicesUtils/customOptions.class.ts
1
import {COOKIE} from '../../login/utils/helper.class';
2
import {HttpHeaders} from "@angular/common/http";
3

  
4

  
5
export class CustomOptions {
6
  
7
  public static registryOptions(): {} {
8
      return {
9
        headers: new HttpHeaders({
10
          'Content-Type': 'application/json',
11
        }), withCredentials: true
12
      };
13
    }
14

  
15
  public static getAuthOptionsWithBody():{} {
16
    return {
17
      headers: new HttpHeaders({
18
        'Content-Type': 'application/json',
19
        'X-XSRF-TOKEN': COOKIE.getCookie(COOKIE.cookieName_id)?COOKIE.getCookie(COOKIE.cookieName_id):''
20
      }), withCredentials: true
21
    };
22
  }
23

  
24
  public static getAuthOptions():{} {
25
    const httpOptions = {
26
      headers: new HttpHeaders({
27
        'X-XSRF-TOKEN': (COOKIE.getCookie(COOKIE.cookieName_id))?COOKIE.getCookie(COOKIE.cookieName_id):''
28
      }), withCredentials: true
29
    };
30
    return httpOptions;
31
  }
32

  
33
}
modules/uoa-services-library/branches/angular-11/ng-openaire-library/src/app/services/user-registry.service.ts
1
import {Injectable} from '@angular/core';
2
import {HttpClient} from '@angular/common/http';
3
import {Observable} from 'rxjs';
4
import {properties} from '../../../environments/environment';
5
import {CustomOptions} from './servicesUtils/customOptions.class';
6
import {map} from 'rxjs/operators';
7

  
8
@Injectable({
9
  providedIn: 'root'
10
})
11
export class UserRegistryService {
12

  
13
  constructor(private http: HttpClient) {
14
  }
15
  
16
  public createRole(type: string, id: string, role): Observable<any[]> {
17
    return this.http.post<any>(properties.registryUrl + 'createRole', role,
18
      CustomOptions.registryOptions()).pipe(map((response: any) => response.response));
19
  }
20
  
21
  public getMembersCount(type: string, id: string): Observable<any> {
22
    return this.http.get(properties.registryUrl + encodeURIComponent(type) + '/' + encodeURIComponent(id) + '/members/count');
23
  }
24

  
25
  public subscribeTo(type: string, id: string): Observable<any> {
26
    return this.http.post(properties.registryUrl + 'subscribe/' + encodeURIComponent(type) + '/' + encodeURIComponent(id),
27
      null, CustomOptions.registryOptions());
28
  }
29

  
30
  public unsubscribeFrom(type: string, id: string): Observable<any> {
31
    return this.http.post(properties.registryUrl + 'unsubscribe/' + encodeURIComponent(type) + '/' + encodeURIComponent(id),
32
      null, CustomOptions.registryOptions());
33
  }
34

  
35
  public remove(type: string, id: string, email: string, role: "member" | "manager" = "manager"): Observable<any> {
36
    return this.http.delete<any>(properties.registryUrl +
37
      encodeURIComponent(type) + '/' + encodeURIComponent(id) + '/' + role + '/' + encodeURIComponent(email), CustomOptions.registryOptions());
38
  }
39
  
40
  public invite(type: string, id: string, details: any, role: "member" | "manager" = "manager"): Observable<any[]> {
41
    return this.http.post<any>(properties.registryUrl + 'invite/' +
42
      encodeURIComponent(type) + '/' + encodeURIComponent(id) + '/' + role, details,
43
      CustomOptions.registryOptions()).pipe(map((response: any) => response.response));
44
  }
45
  
46
  public verify(id: string, code: string, role: "member" | "manager" = "manager"): Observable<any> {
47
    return this.http.post<any>(properties.registryUrl + 'verification/' + role + '/' + encodeURIComponent(id), code, CustomOptions.registryOptions());
48
  }
49

  
50
  public getInvitation(id: string): Observable<any> {
51
    return this.http.get<any>(properties.registryUrl + 'verification/' + encodeURIComponent(id), CustomOptions.registryOptions())
52
      .pipe(map((response: any) => response.response));
53
  }
54

  
55
  public deleteVerification(id: string): Observable<any> {
56
    return this.http.delete<any>(properties.registryUrl + 'verification/' + encodeURIComponent(id), CustomOptions.registryOptions());
57
  }
58

  
59
  public getActiveEmail(type: string, id: string, role: "member" | "manager" = "manager"): Observable<any[]> {
60
    return this.http.get<any>(properties.registryUrl + encodeURIComponent(type) + '/' + encodeURIComponent(id) + "/" + role + 's/email',
61
      CustomOptions.registryOptions()).pipe(map((response:any) => response.response));
62
  }
63
  
64
  public getActiveNames(type: string, id: string, role: "member" | "manager" = "manager"): Observable<any[]> {
65
    return this.http.get<any>(properties.registryUrl + encodeURIComponent(type) + '/' + encodeURIComponent(id) + "/" + role + 's/',
66
      CustomOptions.registryOptions()).pipe(map((response:any) => response.response));
67
  }
68
  
69
  public getPending(type: string, id: string, role: "member" | "manager" = "manager"): Observable<any[]> {
70
    return this.http.get<any>(properties.registryUrl + 'invite/' + encodeURIComponent(type) + '/' + encodeURIComponent(id) + "/" + role + 's/',
71
      CustomOptions.registryOptions()).pipe(map((response: any) => response.response));
72
  }
73
  
74
  public cancelInvitation(type: string, id: string, email: string, role: "member" | "manager" = "manager"): Observable<any> {
75
    return this.http.delete<any>(properties.registryUrl + 'invite/' +
76
      encodeURIComponent(type) + '/' + encodeURIComponent(id) + '/' + role + '/' + encodeURIComponent(email),
77
      CustomOptions.registryOptions());
78
  }
79
}
modules/uoa-services-library/branches/angular-11/ng-openaire-library/src/app/services/clear-cache.service.ts
1
import {Injectable} from "@angular/core";
2
import {HttpClient} from "@angular/common/http";
3
import {properties} from "../../../environments/environment";
4

  
5
@Injectable({
6
  providedIn: 'root'
7
})
8
export class ClearCacheService {
9

  
10
  constructor(private http: HttpClient) {}
11

  
12
  clearCache(message: string = null) {
13
    this.http.get(properties.deleteCacheUrl).subscribe(
14
        res => console.log((message ? message+": " : "") + "Cache cleared!"),
15
        err => console.log((message ? message+": " : "") + "Cache could not be cleared ", err)
16
      );
17
  }
18
}
modules/uoa-services-library/branches/angular-11/ng-openaire-library/src/app/services/user-management.service.ts
1
import {Injectable} from '@angular/core';
2
import {HttpClient} from '@angular/common/http';
3
import {BehaviorSubject, from, Observable, of} from "rxjs";
4
import {COOKIE, Session, User} from "../login/utils/helper.class";
5
import {map} from "rxjs/operators";
6
import {NavigationEnd, Router} from "@angular/router";
7
import {properties} from "../../../environments/environment";
8
import {StringUtils} from "../utils/string-utils.class";
9

  
10
@Injectable({
11
  providedIn: 'root'
12
})
13
export class UserManagementService{
14
  
15
  private getUserInfoSubject: BehaviorSubject<User> = new BehaviorSubject<User>(null);
16
  public fixRedirectURL: string = null;
17
  private readonly promise: Promise<User>;
18
  sub;
19
  routeSub;
20
  
21
  constructor(private http: HttpClient,
22
              private router: Router) {
23
    this.promise = new Promise<any>((resolve => {
24
      this.updateUserInfo(resolve);
25
    }));
26
    this.routeSub = this.router.events.subscribe(event => {
27
      if (event instanceof NavigationEnd) {
28
        const token = COOKIE.getCookie('AccessToken');
29
        if (!token && this.getUserInfoSubject.getValue() !== null) {
30
          this.getUserInfoSubject.next(null);
31
        }
32
      }
33
    });
34
  }
35

  
36
  clearSubscriptions() {
37
    if(this.routeSub){
38
      this.routeSub.unsubscribe();
39
    }
40
    if(this.sub){
41
      this.sub.unsubscribe();
42
    }
43
  }
44
  
45
  public getUserInfo(subject: boolean = true): Observable<User> {
46
    if (subject) {
47
      return this.getUserInfoSubject.asObservable();
48
    } else {
49
      return from(this.getUserInfoAsync());
50
    }
51
  }
52
  
53
  public updateUserInfo(resolve: Function = null) {
54
    const token = COOKIE.getCookie('AccessToken');
55
    if (!token) {
56
      this.getUserInfoSubject.next(null);
57
      if(resolve) {
58
        resolve();
59
      }
60
    } else {
61
     this.sub = this.http.get<User>(properties.userInfoUrl + token).pipe(map(userInfo => {
62
        return this.parseUserInfo(userInfo);
63
      })).subscribe(user => {
64
        this.getUserInfoSubject.next(user);
65
        if(resolve) {
66
          resolve();
67
        }
68
      }, error => {
69
       this.getUserInfoSubject.next(null);
70
       if(resolve) {
71
         resolve();
72
       }
73
     });
74
    }
75
  }
76
  
77
  private async getUserInfoAsync(): Promise<User> {
78
    await this.promise;
79
    if(this.sub){
80
      this.sub.unsubscribe();
81
    }
82
    return this.getUserInfoSubject.getValue();
83
  }
84
  
85
  private parseUserInfo(info: any) {
86
    const user: User = new User();
87
    user.id = (info.sub && info.sub.indexOf('@')) ? info.sub.substring(0, info.sub.indexOf('@')) : info.sub;
88
    user.firstname = (info.given_name) ? info.given_name : "";
89
    user.lastname = (info.family_name) ? info.family_name : "";
90
    user.email = info.email.toLowerCase(); // TODO remove, is a quick fix
91
    user.fullname = (info.name) ? info.name : "";
92
    if (user.fullname == "") {
93
      if (user.firstname != "") {
94
        user.fullname += user.firstname;
95
      }
96
      if (user.lastname != "") {
97
        user.fullname += user.lastname;
98
      }
99
      if (user.fullname == "") { //fullname is still empty set a default
100
        user.fullname = "Anonymous user";
101
      }
102
    }
103
    user.role = [];
104
    if (info.roles) {
105
      info.roles.forEach(role => {
106
        user.role.push(role);
107
      });
108
    }else{
109
      if (info.edu_person_entitlements) {
110
        user.role = info.edu_person_entitlements;
111
      }
112
    }
113
    user.expirationDate = info.exp_date;
114
    return user;
115
  }
116
  
117
  public setRedirectUrl(url: string = null) {
118
    if(url) {
119
      let parts = url.split('?');
120
      let path = properties.baseLink + parts[0];
121
      let params = null;
122
      if (parts.length == 2) {
123
        params = parts[1];
124
      }
125
      let hash = path.indexOf("#");
126
      let fragment = (hash !== -1)?path.slice(hash + 1):null;
127
      if(fragment) {
128
        path = path.slice(0, hash);
129
      } else {
130
        fragment = "";
131
      }
132
      if(!path.includes('/reload')) {
133
        Session.setReloadUrl(location.protocol + "//" + location.host, path, params, fragment);
134
      }
135
    } else {
136
      Session.setReloadUrl(location.protocol + "//" + location.host, location.pathname, location.search, location.hash);
137
    }
138
  }
139
  
140
  public login() {
141
    if(this.fixRedirectURL) {
142
      this.setRedirectUrl(this.fixRedirectURL);
143
    } else {
144
      this.setRedirectUrl();
145
    }
146
    window.location.href = properties.loginUrl;
147
  }
148
  
149
  public logout() {
150
    this.setRedirectUrl();
151
    Session.removeUser();
152
    if (properties.logoutUrl.includes('openid_logout')) {
153
      window.location.href = properties.logoutUrl;
154
    } else {
155
      window.location.href = properties.logoutUrl + StringUtils.URIEncode(location.href);
156
    }
157
  }
158
}
modules/uoa-services-library/branches/angular-11/ng-openaire-library/src/app/services/adminToolService.module.ts
1
import { NgModule } from '@angular/core';
2
import { CommonModule } from '@angular/common';
3
import {HelpContentService} from "./help-content.service";
4

  
5

  
6
@NgModule({
7
  imports: [
8
    CommonModule,
9
  ],
10
  declarations:[ ],
11
  providers: [HelpContentService],
12

  
13

  
14
})
15
export class AdminToolServiceModule { }
modules/uoa-services-library/branches/angular-11/ng-openaire-library/src/app/services/searchDataproviders.service.ts
1
import {Injectable} from '@angular/core';
2
import {HttpClient} from "@angular/common/http";
3
import {SearchResult}     from '../utils/entities/searchResult';
4
import {RefineResultsUtils} from './servicesUtils/refineResults.class';
5

  
6

  
7

  
8
import {StringUtils} from '../utils/string-utils.class';
9
import{EnvProperties} from '../utils/properties/env-properties';
10
import {map} from "rxjs/operators";
11

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

  
16
    constructor(private http: HttpClient ) {}
17

  
18
    searchDataproviders (params: string, refineParams:string, page: number, size: number, refineFields:string[], properties:EnvProperties, usedBy: string="search" ):any {
19
        let link = properties.searchAPIURLLAst+"datasources";
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((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)): url)
32
                    //.map(res => <any> res.json())
33
                    //.do(res => console.info(res))
34
                    .pipe(map(res => [res['meta'].total, this.parseResults(res['results']),RefineResultsUtils.parse(res['refineResults'],refineFields, "datasource", usedBy)]));
35
    }
36
    //((oaftype exact datasource) and(collectedfromdatasourceid exact "openaire____::47ce9e9f4fad46e732cff06419ecaabb"))
37
    advancedSearchDataproviders (params: string, page: number, size: number, properties: EnvProperties, refineParams:string=null,  refineFields:string[] =null, refineQuery:string = null, depositQuery:boolean = false  ):any {
38
      let url =  properties.searchAPIURLLAst+"resources"+(depositQuery?'':2)+"/?format=json";
39

  
40
      if(params!= null && params != ''  ) {
41
        url +="&query=(" + params + ")";
42

  
43
      }
44
      if(refineParams!= null && refineParams != ''  ) {
45
        url += refineParams;
46
      }
47
      if(refineQuery) {
48
        url += "&" + refineQuery;
49
      }
50
      url += "&page="+(page-1)+"&size="+size;
51

  
52
      return this.http.get((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)): url)
53
      //.map(res => <any> res.json())
54
      //.do(res => console.info(res))
55
      .pipe(map(res => [res['meta'].total, this.parseResults(res['results']), RefineResultsUtils.parse(res['refineResults'],refineFields, "datasource")]));
56
    }
57

  
58
    searchCompatibleDataprovidersTable ( properties:EnvProperties):any {
59
      let size: number = 0;
60
      let url: string= properties.searchResourcesAPIURL;
61
      url += '?query=((oaftype exact datasource) not(datasourcecompatibilityid = UNKNOWN) not(datasourcecompatibilityid = notCompatible) not(datasourcetypeuiid = other) not(datasourcetypeuiid exact "pubsrepository::journal") not(datasourcetypeuiid exact "aggregator::pubsrepository::journals"))';
62
      url += "&page=0&size=0&format=json";
63

  
64

  
65

  
66
      return this.http.get((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)): url)
67
                      //.map(res => <any> res.json())
68
                      .pipe(map(res => res['meta'].total));
69
    }
70

  
71
    searchCompatibleDataproviders (params: string,refineParams:string, page: number, size: number, refineFields:string[], properties:EnvProperties ):any {
72
      let url: string = properties.searchResourcesAPIURL;
73
      url += '?query=((oaftype exact datasource) not(datasourcecompatibilityid = UNKNOWN) not(datasourcecompatibilityid = notCompatible) not(datasourcetypeuiid = other) not(datasourcetypeuiid exact "pubsrepository::journal") not(datasourcetypeuiid exact "aggregator::pubsrepository::journals"))';
74
      if(params!= null && params != ''  ) {
75
        url += params;
76
      }
77
      if(refineParams!= null && refineParams != ''  ) {
78
        url += refineParams;
79
      }
80
      url += "&page="+(page-1)+"&size="+size+"&format=json";
81

  
82
      return this.http.get((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)): url)
83
      //.map(res => <any> res.json())
84
      //.do(res => console.info(res))
85
      .pipe(map(res => [res['meta'].total, this.parseResults(res['results']),RefineResultsUtils.parse(res['refineResults'],refineFields, "datasource")]));
86
    }
87

  
88
    searchEntityRegistriesTable (properties:EnvProperties):any {
89
      let size: number = 0;
90
      let url: string= properties.searchResourcesAPIURL;
91
      url += "?query=((oaftype exact datasource) and(datasourcetypeuiid = other))";
92
      url += "&page=0&size=0&format=json";
93

  
94

  
95

  
96
      return this.http.get((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)): url)
97
                      //.map(res => <any> res.json())
98
                      .pipe(map(res => res['meta'].total));
99
    }
100

  
101
    searchEntityRegistries (params: string,refineParams:string, page: number, size: number, refineFields:string[], properties:EnvProperties ):any {
102
      let url = properties.searchResourcesAPIURL;
103
      url += "?query=((oaftype exact datasource) and(datasourcetypeuiid = other))";
104
      if(params!= null && params != ''  ) {
105
        url += params;
106
      }
107
      if(refineParams!= null && refineParams != ''  ) {
108
        url += refineParams;
109
      }
110
      url += "&page="+(page-1)+"&size="+size+"&format=json";
111

  
112
      return this.http.get((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)): url)
113
      //.map(res => <any> res.json())
114
      //.do(res => console.info(res))
115
      .pipe(map(res => [res['meta'].total, this.parseResults(res['results']),RefineResultsUtils.parse(res['refineResults'],refineFields, "datasource")]));
116
    }
117

  
118
    searchJournalsTable ( properties:EnvProperties):any {
119
      let size: number = 0;
120
      let url: string= properties.searchResourcesAPIURL;
121
      url += '?query=((oaftype exact datasource) not(datasourcecompatibilityid = UNKNOWN) not(datasourcecompatibilityid = notCompatible) and (datasourcetypeuiid exact "pubsrepository::journal" or datasourcetypeuiid exact "aggregator::pubsrepository::journals" ))';
122
      url += "&page=0&size=0&format=json";
123

  
124
      return this.http.get((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)): url)//.map(res => <any> res.json())
125
                        .pipe(map(res => res['meta'].total));
126
    }
127

  
128
    searchJournals (params: string,refineParams:string, page: number, size: number, refineFields:string[] , properties:EnvProperties):any {
129
      let url: string = properties.searchResourcesAPIURL;
130
      //url += "?query=((oaftype exact datasource) not(datasourcecompatibilityid = UNKNOWN) not(datasourcecompatibilityid = notCompatible) not(datasourcetypeuiid = other))"
131
      url += '?query=((oaftype exact datasource) not(datasourcecompatibilityid = UNKNOWN) not(datasourcecompatibilityid = notCompatible) and (datasourcetypeuiid exact "pubsrepository::journal" or datasourcetypeuiid exact "aggregator::pubsrepository::journals" ))';
132

  
133
      if(params!= null && params != ''  ) {
134
        url += params;
135
      }
136
      if(refineParams!= null && refineParams != ''  ) {
137
        url += refineParams;
138
      }
139
      url += "&page="+(page-1)+"&size="+size+"&format=json";
140

  
141
      return this.http.get((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)): url)
142
      //.map(res => <any> res.json())
143
      //.do(res => console.info(res))
144
      .pipe(map(res => [res['meta'].total, this.parseResults(res['results']),RefineResultsUtils.parse(res['refineResults'],refineFields, "datasource")]));
145
    }
146

  
147
    searchDataprovidersForDeposit (id: string,type:string, page: number, size: number, properties:EnvProperties):any {
148
        let link = properties.searchResourcesAPIURL;
149
        var compatibilities = "";
150
        if(type == "Research Data"){
151
          //compatibilities = " and (datasourcecompatibilityid <> UNKNOWN) and (datasourcecompatibilityid = openaire2.0_data)"
152
          compatibilities = " and (datasourcecompatibilityid = openaire2.0_data)";
153
        }else if(type == "Publications"){
154
          //compatibilities = " and (datasourcecompatibilityid <> UNKNOWN) and (datasourcecompatibilityid <> openaire2.0_data)"
155
          compatibilities = " and (datasourcecompatibilityid <> openaire2.0_data)";
156
        }
157
        let url = link+"?query=(((deletedbyinference = false) AND (oaftype exact datasource)) "+((compatibilities && compatibilities.length > 0)?" "+compatibilities+" ":"")+") and (relorganizationid exact \""+id+"\")";
158
        url += "&page="+(page-1)+"&size="+size+"&format=json";
159

  
160

  
161
        return this.http.get((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)): url)
162
                    //.map(res => <any> res.json())
163
                    .pipe(map(res => [res['meta'].total, this.parseResults(res['results'])]));
164
    }
165

  
166
    searchDataprovidersForDepositSearch(params: string, refineParams:string, page: number, size: number, refineFields:string[], properties:EnvProperties, usedBy: string="search" ):any {
167
    let link = properties.searchResourcesAPIURL;
168
      let url = link+"?query=((deletedbyinference = false) AND (oaftype exact datasource)) "+params;
169
      if(refineParams!= null && refineParams != ''  ) {
170
        url += refineParams;
171
      }
172
      url += "&page="+(page-1)+"&size="+size+"&format=json";
173

  
174
      return this.http.get((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)): url)
175
                      .pipe(map(res => [res['meta'].total, this.parseResults(res['results']), RefineResultsUtils.parse(res['refineResults'],
176
                                              refineFields, "datasource", usedBy)]));
177
  }
178

  
179
    searchDataProvidersBySubjects(keyword:string, type:string, page: number, size: number, properties:EnvProperties):any {
180
      let link = properties.searchResourcesAPIURL;
181
      var compatibilities = "";
182
      if(type == "Research Data"){
183
        compatibilities = " and (datasourcecompatibilityid <> UNKNOWN) and (datasourcecompatibilityid = openaire2.0_data)"
184
      }else if(type == "Publications"){
185
        compatibilities = " and (datasourcecompatibilityid <> UNKNOWN) and (datasourcecompatibilityid <> openaire2.0_data)"
186
      }
187
      let url = link+"?query=(((deletedbyinference = false) AND (oaftype exact datasource)) "+((compatibilities && compatibilities.length > 0)?" "+
188
      compatibilities+" ":"")+") "+
189
      " and (datasourcesubject all "+'"'+keyword+'"'+") " ;
190
      url += "&page="+(page-1)+"&size="+size+"&format=json";
191

  
192

  
193
      return this.http.get((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)): url)
194
                  //.map(res => <any> res.json())
195
                  .pipe(map(res => [res['meta'].total, this.parseResults(res['results'])]));
196

  
197
    }
198

  
199
    getDataProvidersforEntityRegistry(datasourceId: string, page: number, size: number , properties:EnvProperties):any {
200
      let url = properties.searchResourcesAPIURL;
201
      var basicQuery = "(oaftype exact datasource) "
202
      url += "?query=";
203
      if(datasourceId!= null && datasourceId != ''  ) {
204
        url +=" ( "+basicQuery+ " ) " +" and (collectedfromdatasourceid exact \"" + datasourceId + "\" or resulthostingdatasourceid exact \""+ datasourceId + "\")";
205
      }else{
206
        url +=" ( "+basicQuery+ " ) ";
207
      }
208

  
209
      url += "&page="+(page-1)+"&size="+size+"&format=json";
210

  
211
      return this.http.get((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)): url)
212
      //.map(res => <any> res.json())
213
      .pipe(map(res => [res['meta'].total, this.parseResults(res['results'])]));
214
    }
215
    searchDataprovidersForEntity (params: string, page: number, size: number, properties:EnvProperties):any {
216
        let link = properties.searchAPIURLLAst;
217
        let url = link+params+"/datasources?format=json";
218

  
219
        return this.http.get((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)): url)
220
                    //.map(res => <any> res.json())
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff