[ADF-5426] Remove compatibility layer from Lib (#7110)

* remove compatibility step 1

* remove compatibility step 2

* remove compatibility step 3

* remove compatibility step 4

* remove compatibility step 5
This commit is contained in:
Eugenio Romano
2021-08-04 17:31:35 +02:00
committed by GitHub
parent 5d5b582e32
commit f30b20cc46
113 changed files with 1375 additions and 2348 deletions

View File

@@ -16,15 +16,7 @@
*/
import { Injectable } from '@angular/core';
import {
ContentApi,
Core,
Activiti,
SearchApi,
Node,
GroupsApi,
AlfrescoApiCompatibility, AlfrescoApiConfig, AspectsApi, TypesApi
} from '@alfresco/js-api';
import { Node, AlfrescoApi, AlfrescoApiConfig } from '@alfresco/js-api';
import { AppConfigService, AppConfigValues } from '../app-config/app-config.service';
import { Subject, ReplaySubject } from 'rxjs';
import { OauthConfigModel } from '../models/oauth-config.model';
@@ -43,72 +35,16 @@ export class AlfrescoApiService {
alfrescoApiInitialized: ReplaySubject<boolean> = new ReplaySubject(1);
protected alfrescoApi: AlfrescoApiCompatibility;
protected alfrescoApi: AlfrescoApi;
lastConfig: AlfrescoApiConfig;
private excludedErrorUrl: string[] = ['api/enterprise/system/properties'];
getInstance(): AlfrescoApiCompatibility {
getInstance(): AlfrescoApi {
return this.alfrescoApi;
}
get taskApi(): Activiti.TaskApi {
return this.getInstance().activiti.taskApi;
}
get contentApi(): ContentApi {
return this.getInstance().content;
}
get nodesApi(): Core.NodesApi {
return this.getInstance().nodes;
}
get renditionsApi(): Core.RenditionsApi {
return this.getInstance().core.renditionsApi;
}
get sharedLinksApi(): Core.SharedlinksApi {
return this.getInstance().core.sharedlinksApi;
}
get sitesApi(): Core.SitesApi {
return this.getInstance().core.sitesApi;
}
get favoritesApi(): Core.FavoritesApi {
return this.getInstance().core.favoritesApi;
}
get peopleApi(): Core.PeopleApi {
return this.getInstance().core.peopleApi;
}
get searchApi(): SearchApi {
return this.getInstance().search.searchApi;
}
get versionsApi(): Core.VersionsApi {
return this.getInstance().core.versionsApi;
}
get classesApi(): Core.ClassesApi {
return this.getInstance().core.classesApi;
}
get groupsApi(): GroupsApi {
return new GroupsApi(this.getInstance());
}
get aspectsApi(): AspectsApi {
return new AspectsApi(this.getInstance());
}
get typesApi(): TypesApi {
return new TypesApi(this.getInstance());
}
constructor(
protected appConfig: AppConfigService,
protected storageService: StorageService) {
@@ -148,10 +84,10 @@ export class AlfrescoApiService {
if (this.alfrescoApi && this.isDifferentConfig(this.lastConfig, config)) {
this.lastConfig = config;
this.alfrescoApi.configureJsApi(config);
this.alfrescoApi.setConfig(config);
} else {
this.lastConfig = config;
this.alfrescoApi = new AlfrescoApiCompatibility(config);
this.alfrescoApi = new AlfrescoApi(config);
}
}

View File

@@ -16,7 +16,7 @@
*/
import { Injectable } from '@angular/core';
import { AppDefinitionRepresentation } from '@alfresco/js-api';
import { RuntimeAppDefinitionsApi, AppDefinitionRepresentation } from '@alfresco/js-api';
import { Observable, from, throwError } from 'rxjs';
import { AlfrescoApiService } from './alfresco-api.service';
import { LogService } from './log.service';
@@ -27,8 +27,11 @@ import { map, catchError } from 'rxjs/operators';
})
export class AppsProcessService {
appsApi: RuntimeAppDefinitionsApi;
constructor(private apiService: AlfrescoApiService,
private logService: LogService) {
this.appsApi = new RuntimeAppDefinitionsApi(this.apiService.getInstance());
}
/**
@@ -36,7 +39,7 @@ export class AppsProcessService {
* @returns The list of deployed apps
*/
getDeployedApplications(): Observable<AppDefinitionRepresentation[]> {
return from(this.apiService.getInstance().activiti.appsApi.getAppDefinitions())
return from(this.appsApi.getAppDefinitions())
.pipe(
map((response: any) => <AppDefinitionRepresentation[]> response.data),
catchError((err) => this.handleError(err))
@@ -49,7 +52,7 @@ export class AppsProcessService {
* @returns The list of deployed apps
*/
getDeployedApplicationsByName(name: string): Observable<AppDefinitionRepresentation> {
return from(this.apiService.getInstance().activiti.appsApi.getAppDefinitions())
return from(this.appsApi.getAppDefinitions())
.pipe(
map((response: any) => <AppDefinitionRepresentation> response.data.find((app) => app.name === name)),
catchError((err) => this.handleError(err))
@@ -62,7 +65,7 @@ export class AppsProcessService {
* @returns Details of the app
*/
getApplicationDetailsById(appId: number): Observable<AppDefinitionRepresentation> {
return from(this.apiService.getInstance().activiti.appsApi.getAppDefinitions())
return from(this.appsApi.getAppDefinitions())
.pipe(
map((response: any) => response.data.find((app) => app.id === appId)),
catchError((err) => this.handleError(err))

View File

@@ -22,7 +22,6 @@ import { CookieService } from './cookie.service';
import { AppConfigService } from '../app-config/app-config.service';
import { setupTestBed } from '../testing/setup-test-bed';
import { CoreTestingModule } from '../testing/core.testing.module';
import { UserRepresentation } from '@alfresco/js-api';
import { TranslateModule } from '@ngx-translate/core';
declare let jasmine: any;
@@ -189,7 +188,7 @@ describe('AuthenticationService', () => {
});
it('[ECM] should return true if kerberos configured', () => {
appConfigService.config.auth.withCredentials = true ;
appConfigService.config.auth.withCredentials = true;
expect(authService.isLoggedInWith('ECM')).toBe(true);
expect(authService.isLoggedIn()).toBe(true);
@@ -313,17 +312,6 @@ describe('AuthenticationService', () => {
expect(authService.isALLProvider()).toBe(false);
});
it('[BPM] should be able to retrieve current logged in user', (done) => {
spyOn(apiService.getInstance().activiti.profileApi, 'getProfile').and.returnValue(
Promise.resolve((<UserRepresentation> {
email: 'fake-email'
})));
authService.getBpmLoggedUser().subscribe((fakeUser) => {
expect(fakeUser.email).toBe('fake-email');
done();
});
});
});
describe('remember me', () => {
@@ -368,7 +356,8 @@ describe('AuthenticationService', () => {
it('[ECM] should not save the remember me cookie after failed login', (done) => {
const disposableLogin = authService.login('fake-username', 'fake-password').subscribe(
() => {},
() => {
},
() => {
expect(cookie['ALFRESCO_REMEMBER_ME']).toBeUndefined();
disposableLogin.unsubscribe();
@@ -425,7 +414,8 @@ describe('AuthenticationService', () => {
it('[ALL] should return login fail if only ECM call fail', (done) => {
const disposableLogin = authService.login('fake-username', 'fake-password').subscribe(
() => {},
() => {
},
() => {
expect(authService.isLoggedIn()).toBe(false, 'isLoggedIn');
expect(authService.getTicketEcm()).toBe(null, 'getTicketEcm');
@@ -447,7 +437,8 @@ describe('AuthenticationService', () => {
it('[ALL] should return login fail if only BPM call fail', (done) => {
const disposableLogin = authService.login('fake-username', 'fake-password').subscribe(
() => {},
() => {
},
() => {
expect(authService.isLoggedIn()).toBe(false);
expect(authService.getTicketEcm()).toBe(null);
@@ -470,7 +461,8 @@ describe('AuthenticationService', () => {
it('[ALL] should return ticket undefined when the credentials are wrong', (done) => {
const disposableLogin = authService.login('fake-username', 'fake-password').subscribe(
() => {},
() => {
},
() => {
expect(authService.isLoggedIn()).toBe(false);
expect(authService.getTicketEcm()).toBe(null);

View File

@@ -22,7 +22,7 @@ import { CookieService } from './cookie.service';
import { LogService } from './log.service';
import { RedirectionModel } from '../models/redirection.model';
import { AppConfigService, AppConfigValues } from '../app-config/app-config.service';
import { UserRepresentation } from '@alfresco/js-api';
import { UserProfileApi, UserRepresentation } from '@alfresco/js-api';
import { map, catchError, tap } from 'rxjs/operators';
import { HttpHeaders } from '@angular/common/http';
import { JwtHelperService } from './jwt-helper.service';
@@ -48,6 +48,8 @@ export class AuthenticationService {
*/
onLogout: ReplaySubject<any> = new ReplaySubject<any>(1);
private profileApi: UserProfileApi;
constructor(
private appConfig: AppConfigService,
private storageService: StorageService,
@@ -55,7 +57,10 @@ export class AuthenticationService {
private cookie: CookieService,
private logService: LogService) {
this.alfrescoApi.alfrescoApiInitialized.subscribe(() => {
this.alfrescoApi.getInstance().reply('logged-in', () => this.onLogin.next());
this.alfrescoApi.getInstance().reply('logged-in', () => {
this.profileApi = new UserProfileApi(alfrescoApi.getInstance());
this.onLogin.next();
});
});
}
@@ -295,7 +300,7 @@ export class AuthenticationService {
* @returns User information
*/
getBpmLoggedUser(): Observable<UserRepresentation> {
return from(this.alfrescoApi.getInstance().activiti.profileApi.getProfile());
return from(this.profileApi.getProfile());
}
private hasValidRedirection(provider: string): boolean {

View File

@@ -21,7 +21,7 @@ import { AlfrescoApiService } from './alfresco-api.service';
import { LogService } from './log.service';
import { BpmUserModel } from '../models/bpm-user.model';
import { map, catchError } from 'rxjs/operators';
import { UserRepresentation } from '@alfresco/js-api';
import { UserProfileApi, UserRepresentation } from '@alfresco/js-api';
/**
*
@@ -33,8 +33,11 @@ import { UserRepresentation } from '@alfresco/js-api';
})
export class BpmUserService {
private profileApi: UserProfileApi;
constructor(private apiService: AlfrescoApiService,
private logService: LogService) {
this.profileApi = new UserProfileApi(this.apiService.getInstance());
}
/**
@@ -42,7 +45,7 @@ export class BpmUserService {
* @returns User information object
*/
getCurrentUserInfo(): Observable<BpmUserModel> {
return from(this.apiService.getInstance().activiti.profileApi.getProfile())
return from(this.profileApi.getProfile())
.pipe(
map((userRepresentation: UserRepresentation) => {
return new BpmUserModel(userRepresentation);
@@ -56,7 +59,7 @@ export class BpmUserService {
* @returns URL string
*/
getCurrentUserProfileImage(): string {
return this.apiService.getInstance().activiti.profileApi.getProfilePictureUrl();
return this.profileApi.getProfilePictureUrl();
}
/**

View File

@@ -21,15 +21,18 @@ import { CommentModel } from '../models/comment.model';
import { AlfrescoApiService } from '../services/alfresco-api.service';
import { LogService } from '../services/log.service';
import { map, catchError } from 'rxjs/operators';
import { CommentEntry } from '@alfresco/js-api';
import { CommentEntry, CommentsApi } from '@alfresco/js-api';
@Injectable({
providedIn: 'root'
})
export class CommentContentService {
private commentsApi: CommentsApi;
constructor(private apiService: AlfrescoApiService,
private logService: LogService) {
this.commentsApi = new CommentsApi(this.apiService.getInstance());
}
/**
@@ -39,7 +42,7 @@ export class CommentContentService {
* @returns Details of the comment added
*/
addNodeComment(nodeId: string, message: string): Observable<CommentModel> {
return from(this.apiService.getInstance().core.commentsApi.addComment(nodeId, {content: message}))
return from(this.commentsApi.createComment(nodeId, {content: message}))
.pipe(
map((response: CommentEntry) => {
return new CommentModel({
@@ -59,7 +62,7 @@ export class CommentContentService {
* @returns Details for each comment
*/
getNodeComments(nodeId: string): Observable<CommentModel[]> {
return from(this.apiService.getInstance().core.commentsApi.getComments(nodeId))
return from(this.commentsApi.listComments(nodeId))
.pipe(
map((response) => {
const comments: CommentModel[] = [];

View File

@@ -20,7 +20,6 @@ import { CommentModel } from '../models/comment.model';
import { fakeProcessComment, fakeTasksComment, fakeUser1 } from '../mock/comment-process-service.mock';
import { CommentProcessService } from './comment-process.service';
import { setupTestBed } from '../testing/setup-test-bed';
import { AlfrescoApiService } from './alfresco-api.service';
import { CoreTestingModule } from '../testing/core.testing.module';
import { TranslateModule } from '@ngx-translate/core';
@@ -29,7 +28,6 @@ declare let jasmine: any;
describe('Comment ProcessService Service', () => {
let service: CommentProcessService;
let alfrescoApi: any;
setupTestBed({
imports: [
@@ -40,7 +38,6 @@ describe('Comment ProcessService Service', () => {
beforeEach(() => {
service = TestBed.inject(CommentProcessService);
alfrescoApi = TestBed.inject(AlfrescoApiService).getInstance();
});
beforeEach(() => {
@@ -60,7 +57,7 @@ describe('Comment ProcessService Service', () => {
let getProcessInstanceComments: jasmine.Spy;
beforeEach(() => {
getProcessInstanceComments = spyOn(alfrescoApi.activiti.commentsApi, 'getProcessInstanceComments')
getProcessInstanceComments = spyOn(service['commentsApi'], 'getProcessInstanceComments')
.and
.returnValue(Promise.resolve({data: [fakeProcessComment, fakeProcessComment]}));
});
@@ -108,7 +105,7 @@ describe('Comment ProcessService Service', () => {
let addProcessInstanceComment: jasmine.Spy;
beforeEach(() => {
addProcessInstanceComment = spyOn(alfrescoApi.activiti.commentsApi, 'addProcessInstanceComment')
addProcessInstanceComment = spyOn(service['commentsApi'], 'addProcessInstanceComment')
.and
.returnValue(Promise.resolve(fakeProcessComment));
});

View File

@@ -22,14 +22,18 @@ import { UserProcessModel } from '../models/user-process.model';
import { AlfrescoApiService } from './alfresco-api.service';
import { LogService } from './log.service';
import { map, catchError } from 'rxjs/operators';
import { ActivitiCommentsApi } from '@alfresco/js-api';
@Injectable({
providedIn: 'root'
})
export class CommentProcessService {
private commentsApi: ActivitiCommentsApi;
constructor(private apiService: AlfrescoApiService,
private logService: LogService) {
this.commentsApi = new ActivitiCommentsApi(this.apiService.getInstance());
}
/**
@@ -39,7 +43,7 @@ export class CommentProcessService {
* @returns Details about the comment
*/
addTaskComment(taskId: string, message: string): Observable<CommentModel> {
return from(this.apiService.getInstance().activiti.taskApi.addTaskComment({ message: message }, taskId))
return from(this.commentsApi.addTaskComment({ message: message }, taskId))
.pipe(
map((response) => {
return new CommentModel({
@@ -59,7 +63,7 @@ export class CommentProcessService {
* @returns Details for each comment
*/
getTaskComments(taskId: string): Observable<CommentModel[]> {
return from(this.apiService.getInstance().activiti.taskApi.getTaskComments(taskId))
return from(this.commentsApi.getTaskComments(taskId))
.pipe(
map((response) => {
const comments: CommentModel[] = [];
@@ -84,7 +88,7 @@ export class CommentProcessService {
* @returns Details for each comment
*/
getProcessInstanceComments(processInstanceId: string): Observable<CommentModel[]> {
return from(this.apiService.getInstance().activiti.commentsApi.getProcessInstanceComments(processInstanceId))
return from(this.commentsApi.getProcessInstanceComments(processInstanceId))
.pipe(
map((response) => {
const comments: CommentModel[] = [];
@@ -111,7 +115,7 @@ export class CommentProcessService {
*/
addProcessInstanceComment(processInstanceId: string, message: string): Observable<CommentModel> {
return from(
this.apiService.getInstance().activiti.commentsApi.addProcessInstanceComment({ message: message }, processInstanceId)
this.commentsApi.addProcessInstanceComment({ message: message }, processInstanceId)
).pipe(
map((response) => {
return new CommentModel({

View File

@@ -17,7 +17,7 @@
import { Injectable } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';
import { ContentApi, MinimalNode, Node, NodeEntry } from '@alfresco/js-api';
import { ContentApi, MinimalNode, Node, NodeEntry, NodesApi } from '@alfresco/js-api';
import { Observable, Subject, from, throwError } from 'rxjs';
import { FolderCreatedEvent } from '../events/folder-created.event';
import { AlfrescoApiService } from './alfresco-api.service';
@@ -38,12 +38,17 @@ export class ContentService {
folderCreate: Subject<MinimalNode> = new Subject<MinimalNode>();
folderEdit: Subject<MinimalNode> = new Subject<MinimalNode>();
private contentApi: ContentApi;
private nodesApi: NodesApi;
constructor(public authService: AuthenticationService,
public apiService: AlfrescoApiService,
private logService: LogService,
private sanitizer: DomSanitizer,
private downloadService: DownloadService,
private thumbnailService: ThumbnailService) {
this.contentApi = new ContentApi(apiService.getInstance());
this.nodesApi = new NodesApi(apiService.getInstance());
}
/**
@@ -56,26 +61,6 @@ export class ContentService {
this.downloadService.downloadBlob(blob, fileName);
}
/**
* @deprecated in 3.2.0, use DownloadService instead.
* Invokes content download for a data array with a file name.
* @param data Data to download.
* @param fileName Name of the resulting file.
*/
downloadData(data: any, fileName: string): void {
this.downloadService.downloadData(data, fileName);
}
/**
* @deprecated in 3.2.0, use DownloadService instead.
* Invokes content download for a JSON object with a file name.
* @param json JSON object to download.
* @param fileName Name of the resulting file.
*/
downloadJSON(json: any, fileName: string): void {
this.downloadService.downloadJSON(json, fileName);
}
/**
* Creates a trusted object URL from the Blob.
* WARNING: calling this method with untrusted user data exposes your application to XSS security risks!
@@ -87,10 +72,6 @@ export class ContentService {
return <string> this.sanitizer.bypassSecurityTrustUrl(url);
}
private get contentApi(): ContentApi {
return this.apiService.getInstance().content;
}
/**
* @deprecated in 3.2.0, use ThumbnailService instead.
* Gets a thumbnail URL for the given document node.
@@ -132,7 +113,7 @@ export class ContentService {
* @returns Content data
*/
getNodeContent(nodeId: string): Observable<any> {
return from(this.apiService.getInstance().core.nodesApi.getFileContent(nodeId))
return from(this.nodesApi.getNodeContent(nodeId))
.pipe(
catchError((err: any) => this.handleError(err))
);
@@ -145,7 +126,7 @@ export class ContentService {
* @returns Details of the folder
*/
getNode(nodeId: string, opts?: any): Observable<NodeEntry> {
return from(this.apiService.getInstance().nodes.getNode(nodeId, opts));
return from(this.nodesApi.getNode(nodeId, opts));
}
/**
@@ -159,13 +140,13 @@ export class ContentService {
let hasPermissions = false;
userId = userId ?? this.authService.getEcmUsername();
const permissions = [ ...(node.permissions?.locallySet || []), ...(node.permissions?.inherited || []) ]
.filter((currentPermission) => currentPermission.authorityId === userId);
const permissions = [...(node.permissions?.locallySet || []), ...(node.permissions?.inherited || [])]
.filter((currentPermission) => currentPermission.authorityId === userId);
if (permissions.length) {
if (permission && permission.startsWith('!')) {
hasPermissions = permissions.find((currentPermission) => currentPermission.name === permission.replace('!', '')) ? false : true;
hasPermissions = !permissions.find((currentPermission) => currentPermission.name === permission.replace('!', ''));
} else {
hasPermissions = permissions.find((currentPermission) => currentPermission.name === permission) ? true : false;
hasPermissions = !!permissions.find((currentPermission) => currentPermission.name === permission);
}
} else {
@@ -193,9 +174,9 @@ export class ContentService {
if (node && node.allowableOperations) {
if (allowableOperation && allowableOperation.startsWith('!')) {
hasAllowableOperations = node.allowableOperations.find((currentOperation) => currentOperation === allowableOperation.replace('!', '')) ? false : true;
hasAllowableOperations = !node.allowableOperations.find((currentOperation) => currentOperation === allowableOperation.replace('!', ''));
} else {
hasAllowableOperations = node.allowableOperations.find((currentOperation) => currentOperation === allowableOperation) ? true : false;
hasAllowableOperations = !!node.allowableOperations.find((currentOperation) => currentOperation === allowableOperation);
}
} else {

View File

@@ -18,7 +18,7 @@
import { Injectable } from '@angular/core';
import { Observable, from, of } from 'rxjs';
import { NodePaging } from '@alfresco/js-api';
import { NodePaging, NodesApi, TrashcanApi } from '@alfresco/js-api';
import { AlfrescoApiService } from './alfresco-api.service';
import { UserPreferencesService } from './user-preferences.service';
import { catchError } from 'rxjs/operators';
@@ -27,13 +27,16 @@ import { catchError } from 'rxjs/operators';
providedIn: 'root'
})
export class DeletedNodesApiService {
nodesApi: NodesApi;
trashcanApi: TrashcanApi;
constructor(
private apiService: AlfrescoApiService,
private preferences: UserPreferencesService
) {}
private get nodesApi() {
return this.apiService.getInstance().core.nodesApi;
) {
this.nodesApi = new NodesApi(this.apiService.getInstance());
this.trashcanApi = new TrashcanApi(this.apiService.getInstance());
}
/**
@@ -48,7 +51,7 @@ export class DeletedNodesApiService {
skipCount: 0
};
const queryOptions = Object.assign(defaultOptions, options);
const promise = this.nodesApi.getDeletedNodes(queryOptions);
const promise = this.trashcanApi.listDeletedNodes(queryOptions);
return from(promise).pipe(
catchError((err) => of(err))

View File

@@ -1,258 +0,0 @@
/*!
* @license
* Copyright 2019 Alfresco Software, Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { TestBed } from '@angular/core/testing';
import { BpmProductVersionModel, EcmProductVersionModel } from '../models/product-version.model';
import { DiscoveryApiService } from './discovery-api.service';
import { AlfrescoApiService } from './alfresco-api.service';
import { AuthenticationService } from './authentication.service';
import { setupTestBed } from '../testing/setup-test-bed';
import { CoreTestingModule } from '../testing/core.testing.module';
import { DiscoveryEntry, SystemPropertiesRepresentation } from '@alfresco/js-api';
import { TranslateModule } from '@ngx-translate/core';
import { of } from 'rxjs';
const fakeEcmDiscoveryResponse = new DiscoveryEntry({
entry: {
repository: {
edition: 'FAKE',
version: {
major: '5',
minor: '2',
patch: '0',
hotfix: '0',
schema: 999999,
label: 'r134899-b26',
display: '5.2.0.0 (r134899-b26) schema 10005'
},
license: {
issuedAt: '2017-06-22T10:56:45.796+0000',
expiresAt: '2017-07-22T00:00:00.000+0000',
remainingDays: 4,
holder: 'Trial User',
mode: 'ENTERPRISE',
entitlements: {
isClusterEnabled: false,
isCryptodocEnabled: false
}
},
status: {
isReadOnly: false,
isAuditEnabled: true,
isQuickShareEnabled: true,
isThumbnailGenerationEnabled: true
},
modules: [
{
id: 'alfresco-fake-services',
title: 'Alfresco Share Services AMP',
description: 'Module to be applied to alfresco.war, containing APIs for Alfresco Share',
version: '5.2.0',
installDate: '2017-03-07T08:48:14.161+0000',
installState: 'INSTALLED',
versionMin: '5.1',
versionMax: '999'
},
{
id: 'alfresco-trashcan-fake',
title: 'alfresco-trashcan-cleaner project',
description: 'The Alfresco Trash Can Cleaner (Alfresco Module)',
version: '2.2',
installState: 'UNKNOWN',
versionMin: '0',
versionMax: '999'
}
]
}
}
});
const fakeBPMDiscoveryResponse: any = {
revisionVersion: '2',
edition: 'SUPER FAKE EDITION',
type: 'bpmSuite',
majorVersion: '1',
minorVersion: '6'
};
const fakeBPMDiscoverySystemPropertyResponse = new SystemPropertiesRepresentation({
allowInvolveByEmail: true,
disableJavaScriptEventsInFormEditor: false,
logoutDisabled: false,
authConfiguration: {
authUrl: 'fakeAuthUrl',
realm: 'fakeRealm',
clientId: 'fakeClient',
useBrowserLogout: true
}
});
describe('Discovery Api Service', () => {
let service: DiscoveryApiService;
let apiService: AlfrescoApiService;
let authenticationService: AuthenticationService;
describe('Basic auth', () => {
setupTestBed({
imports: [TranslateModule.forRoot(), CoreTestingModule]
});
beforeEach(() => {
service = TestBed.inject(DiscoveryApiService);
apiService = TestBed.inject(AlfrescoApiService);
});
describe('For ECM', () => {
it('Should retrieve the info about the product for ECM', done => {
spyOn(apiService.getInstance().discovery.discoveryApi, 'getRepositoryInformation')
.and.returnValue(Promise.resolve(fakeEcmDiscoveryResponse));
service.getEcmProductInfo()
.subscribe((data: EcmProductVersionModel) => {
expect(data).not.toBeNull();
expect(data.edition).toBe('FAKE');
expect(data.version.schema).toBe(999999);
expect(data.license.isClusterEnabled).toBeFalsy();
expect(data.status.isQuickShareEnabled).toBeTruthy();
expect(data.modules.length).toBe(2);
expect(data.modules[0].id).toBe('alfresco-fake-services');
expect(data.modules[1].id).toBe('alfresco-trashcan-fake');
done();
});
});
it('getEcmProductInfo catch errors call', done => {
spyOn(apiService.getInstance().discovery.discoveryApi, 'getRepositoryInformation')
.and.returnValue(Promise.reject({ status: 403 }));
service.getEcmProductInfo().subscribe(
() => {},
() => {
done();
}
);
});
});
describe('For BPM', () => {
it('Should retrieve the info about the product for BPM', done => {
spyOn(apiService.getInstance().activiti.aboutApi, 'getAppVersion')
.and.returnValue(Promise.resolve(fakeBPMDiscoveryResponse));
service.getBpmProductInfo().subscribe((data: BpmProductVersionModel) => {
expect(data).not.toBeNull();
expect(data.edition).toBe('SUPER FAKE EDITION');
expect(data.revisionVersion).toBe('2');
expect(data.type).toBe('bpmSuite');
done();
});
});
it('getBpmProductInfo catch errors call', done => {
spyOn(apiService.getInstance().activiti.aboutApi, 'getAppVersion')
.and.returnValue(Promise.reject({ status: 403 }));
service.getBpmProductInfo().subscribe(
() => {},
() => {
done();
}
);
});
it('Should retrieve the system properties for BPM', done => {
spyOn(apiService.getInstance().activiti.systemPropertiesApi, 'getProperties')
.and.returnValue(Promise.resolve(fakeBPMDiscoverySystemPropertyResponse));
service.getBPMSystemProperties().subscribe((data: SystemPropertiesRepresentation) => {
expect(data).not.toBeNull();
expect(data.allowInvolveByEmail).toBe(true);
expect(data.disableJavaScriptEventsInFormEditor).toBe(false);
expect(data.logoutDisabled).toBe(false);
expect(data.authConfiguration.authUrl).toBe('fakeAuthUrl');
expect(data.authConfiguration.realm).toBe('fakeRealm');
expect(data.authConfiguration.clientId).toBe('fakeClient');
expect(data.authConfiguration.useBrowserLogout).toBe(true);
done();
});
});
it('Should retrieve the system properties for BPM', done => {
spyOn(
apiService.getInstance().activiti.systemPropertiesApi,
'getProperties'
).and.returnValue(
Promise.reject({
error: {
response: {
statusCode: 404,
statusText: 'Not Found'
}
}
})
);
service.getBPMSystemProperties().subscribe(
() => {
fail('expected an error, bpm not running');
},
error => {
expect(error.response.statusCode).toEqual(404);
expect(error.response.statusText).toEqual('Not Found');
done();
}
);
});
});
});
describe('OnLogin Event', () => {
setupTestBed({
imports: [
TranslateModule.forRoot(),
CoreTestingModule
]
});
beforeEach(() => {
service = TestBed.inject(DiscoveryApiService);
apiService = TestBed.inject(AlfrescoApiService);
authenticationService = TestBed.inject(AuthenticationService);
});
it('Should retrieve the info about the product on login/refresh the application', done => {
spyOn(apiService.getInstance(), 'isEcmLoggedIn').and.returnValue(true);
spyOn(service, 'getEcmProductInfo').and.returnValue(of(new EcmProductVersionModel(fakeEcmDiscoveryResponse)));
const subscription = service.ecmProductInfo$.subscribe(
(data: EcmProductVersionModel) => {
expect(data).not.toBeNull();
expect(data.edition).toBe('FAKE');
expect(data.version.schema).toBe(999999);
expect(data.license.isClusterEnabled).toBeFalsy();
expect(data.status.isQuickShareEnabled).toBeTruthy();
expect(data.modules.length).toBe(2);
expect(data.modules[0].id).toBe('alfresco-fake-services');
expect(data.modules[1].id).toBe('alfresco-trashcan-fake');
subscription.unsubscribe();
done();
}
);
authenticationService.onLogin.next('<token>');
});
});
});

View File

@@ -20,7 +20,7 @@ import { from, Observable, throwError, Subject } from 'rxjs';
import { BpmProductVersionModel, EcmProductVersionModel } from '../models/product-version.model';
import { AlfrescoApiService } from './alfresco-api.service';
import { catchError, map, switchMap, filter, take } from 'rxjs/operators';
import { Activiti, SystemPropertiesRepresentation } from '@alfresco/js-api';
import { AboutApi, DiscoveryApi, SystemPropertiesApi, SystemPropertiesRepresentation } from '@alfresco/js-api';
import { AuthenticationService } from './authentication.service';
@Injectable({
@@ -51,7 +51,9 @@ export class DiscoveryApiService {
* @returns ProductVersionModel containing product details
*/
public getEcmProductInfo(): Observable<EcmProductVersionModel> {
return from(this.apiService.getInstance().discovery.discoveryApi.getRepositoryInformation())
const discoveryApi = new DiscoveryApi(this.apiService.getInstance());
return from(discoveryApi.getRepositoryInformation())
.pipe(
map((res) => new EcmProductVersionModel(res)),
catchError((err) => throwError(err))
@@ -63,19 +65,19 @@ export class DiscoveryApiService {
* @returns ProductVersionModel containing product details
*/
public getBpmProductInfo(): Observable<BpmProductVersionModel> {
return from(this.apiService.getInstance().activiti.aboutApi.getAppVersion())
const aboutApi = new AboutApi(this.apiService.getInstance());
return from(aboutApi.getAppVersion())
.pipe(
map((res) => new BpmProductVersionModel(res)),
catchError((err) => throwError(err))
);
}
private get systemPropertiesApi(): Activiti.SystemPropertiesApi {
return this.apiService.getInstance().activiti.systemPropertiesApi;
}
public getBPMSystemProperties(): Observable<SystemPropertiesRepresentation> {
return from(this.systemPropertiesApi.getProperties())
const systemPropertiesApi = new SystemPropertiesApi(this.apiService.getInstance());
return from(systemPropertiesApi.getProperties())
.pipe(
map((res) => {
if ('string' === typeof (res)) {

View File

@@ -15,7 +15,7 @@
* limitations under the License.
*/
import { NodeEntry, DownloadEntry, DownloadBodyCreate } from '@alfresco/js-api';
import { DownloadEntry, DownloadBodyCreate, DownloadsApi } from '@alfresco/js-api';
import { Injectable } from '@angular/core';
import { Observable, from, throwError } from 'rxjs';
import { LogService } from './log.service';
@@ -27,8 +27,11 @@ import { catchError } from 'rxjs/operators';
})
export class DownloadZipService {
downloadsApi: DownloadsApi;
constructor(private apiService: AlfrescoApiService,
private logService: LogService) {
this.downloadsApi = new DownloadsApi(this.apiService.getInstance());
}
/**
@@ -37,37 +40,18 @@ export class DownloadZipService {
* @returns Status object for the download
*/
createDownload(payload: DownloadBodyCreate): Observable<DownloadEntry> {
return from(this.apiService.getInstance().core.downloadsApi.createDownload(payload)).pipe(
return from(this.downloadsApi.createDownload(payload)).pipe(
catchError((err) => this.handleError(err))
);
}
/**
* Gets a content URL for the given node.
* @param nodeId Node to get URL for.
* @param attachment Toggles whether to retrieve content as an attachment for download
* @returns URL string
*/
getContentUrl(nodeId: string, attachment?: boolean): string {
return this.apiService.getInstance().content.getContentUrl(nodeId, attachment);
}
/**
* Gets a Node via its node ID.
* @param nodeId ID of the target node
* @returns Details of the node
*/
getNode(nodeId: string): Observable<NodeEntry> {
return from(this.apiService.getInstance().core.nodesApi.getNode(nodeId));
}
/**
* Gets status information for a download node.
* @param downloadId ID of the download node
* @returns Status object for the download
*/
getDownload(downloadId: string): Observable<DownloadEntry> {
return from(this.apiService.getInstance().core.downloadsApi.getDownload(downloadId));
return from(this.downloadsApi.getDownload(downloadId));
}
/**
@@ -75,7 +59,7 @@ export class DownloadZipService {
* @param downloadId ID of the target download node
*/
cancelDownload(downloadId: string) {
this.apiService.getInstance().core.downloadsApi.cancelDownload(downloadId);
this.downloadsApi.cancelDownload(downloadId);
}
private handleError(error: any) {

View File

@@ -16,7 +16,7 @@
*/
import { Injectable } from '@angular/core';
import { NodePaging } from '@alfresco/js-api';
import { FavoritesApi, NodePaging, FavoritePaging } from '@alfresco/js-api';
import { Observable, from, of } from 'rxjs';
import { AlfrescoApiService } from './alfresco-api.service';
import { UserPreferencesService } from './user-preferences.service';
@@ -27,6 +27,8 @@ import { catchError } from 'rxjs/operators';
})
export class FavoritesApiService {
private favoritesApi: FavoritesApi;
static remapEntry({ entry }: any): any {
entry.properties = {
'cm:title': entry.title,
@@ -36,11 +38,17 @@ export class FavoritesApiService {
return { entry };
}
remapFavoritesData(data: any = {}): NodePaging {
const list = (data.list || {});
const pagination = (list.pagination || {});
constructor(
private apiService: AlfrescoApiService,
private preferences: UserPreferencesService
) {
this.favoritesApi = new FavoritesApi(this.apiService.getInstance());
}
remapFavoritesData(data: FavoritePaging = {}): NodePaging {
const pagination = (data?.list?.pagination || {});
const entries: any[] = this
.remapFavoriteEntries(list.entries || []);
.remapFavoriteEntries(data?.list?.entries || []);
return <NodePaging> {
list: { entries, pagination }
@@ -49,22 +57,13 @@ export class FavoritesApiService {
remapFavoriteEntries(entries: any[]) {
return entries
.map(({ entry: { target }}: any) => ({
.map(({ entry: { target } }: any) => ({
entry: target.file || target.folder
}))
.filter(({ entry }) => (!!entry))
.map(FavoritesApiService.remapEntry);
}
constructor(
private apiService: AlfrescoApiService,
private preferences: UserPreferencesService
) {}
private get favoritesApi() {
return this.apiService.getInstance().core.favoritesApi;
}
/**
* Gets the favorites for a user.
* @param personId ID of the user
@@ -76,11 +75,11 @@ export class FavoritesApiService {
maxItems: this.preferences.paginationSize,
skipCount: 0,
where: '(EXISTS(target/file) OR EXISTS(target/folder))',
include: [ 'properties', 'allowableOperations' ]
include: ['properties', 'allowableOperations']
};
const queryOptions = Object.assign(defaultOptions, options);
const promise = this.favoritesApi
.getFavorites(personId, queryOptions)
.listFavorites(personId, queryOptions)
.then(this.remapFavoritesData);
return from(promise).pipe(

View File

@@ -33,10 +33,7 @@ export class LockService {
let isLocked = false;
if (this.hasLockConfigured(node)) {
if (this.isReadOnlyLock(node)) {
isLocked = true;
if (this.isLockExpired(node)) {
isLocked = false;
}
isLocked = !this.isLockExpired(node);
} else if (this.isLockOwnerAllowed(node)) {
isLocked = this.alfrescoApiService.getInstance().getEcmUsername() !== node.properties['cm:lockOwner'].id;
if (this.isLockExpired(node)) {

View File

@@ -1,164 +0,0 @@
/*!
* @license
* Copyright 2019 Alfresco Software, Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { TestBed } from '@angular/core/testing';
import { NodesApiService } from './nodes-api.service';
import { setupTestBed } from '../testing/setup-test-bed';
import { AlfrescoApiService } from './alfresco-api.service';
import { NodeMetadata } from '../models/node-metadata.model';
import { CoreTestingModule } from '../testing/core.testing.module';
import { TranslateModule } from '@ngx-translate/core';
describe('NodesApiService', () => {
let service: NodesApiService;
let apiService: AlfrescoApiService;
const MODEL_NAMESPACE = 'activitiForms';
const responseBody = {
entry: {
id: '111-222-33-44-1123',
nodeType: 'typeTest',
properties: {
test: 'test',
testdata: 'testdata'
}
}
};
const mockSpy: any = {
core: {
nodesApi: {
getNode: jasmine.createSpy('getNode'),
getNodeChildren: jasmine.createSpy('getNodeChildren'),
addNode: jasmine.createSpy('addNode')
}
},
isEcmLoggedIn() {
return false;
},
reply: jasmine.createSpy('reply')
};
setupTestBed({
imports: [
TranslateModule.forRoot(),
CoreTestingModule
]
});
beforeEach(() => {
service = TestBed.inject(NodesApiService);
apiService = TestBed.inject(AlfrescoApiService);
spyOn(apiService, 'getInstance').and.returnValue(mockSpy);
});
afterEach(() => {
mockSpy.core.nodesApi.getNode.calls.reset();
mockSpy.core.nodesApi.getNodeChildren.calls.reset();
mockSpy.core.nodesApi.addNode.calls.reset();
});
it('Should return the node information', (done) => {
mockSpy.core.nodesApi.getNode.and.returnValue(Promise.resolve(responseBody));
service.getNode('-nodeid-').subscribe((result) => {
const args = [
'-nodeid-',
{ 'include': ['path', 'properties', 'allowableOperations', 'permissions'] }
];
expect(mockSpy.core.nodesApi.getNode.calls.mostRecent().args).toEqual(args);
expect(result).toEqual(<any> responseBody.entry);
done();
});
});
it('Should return the node child information', (done) => {
const fakeNodeList = {
list: {
entries: [
{ entry: { id: 'fake-node-id', name: 'fake-node-name', isFolder: true } },
{ entry: { id: 'fake-file-id', name: 'fake-file-name', isFolder: false } }
]
}
};
mockSpy.core.nodesApi.getNodeChildren.and.returnValue(Promise.resolve(fakeNodeList));
service.getNodeChildren('-nodeid-', {}).subscribe((result) => {
const args = [
'-nodeid-',
{
'include': ['path', 'properties', 'allowableOperations', 'permissions'],
maxItems: 25,
skipCount: 0
}
];
expect(mockSpy.core.nodesApi.getNodeChildren.calls.mostRecent().args).toEqual(args);
expect(result).toBe(<any> fakeNodeList);
done();
});
});
it('Should fetch and node metadata', (done) => {
mockSpy.core.nodesApi.getNode.and.returnValue(Promise.resolve(responseBody));
service.getNodeMetadata('-nodeid-').subscribe((result) => {
const node = new NodeMetadata({
test: 'test',
testdata: 'testdata'
}, 'typeTest');
expect(result).toEqual(node);
done();
});
});
it('Should create a node with metadata', (done) => {
const data = {
test: 'test',
testdata: 'testdata'
};
mockSpy.core.nodesApi.addNode.and.returnValue(Promise.resolve(responseBody));
service.createNodeMetadata('typeTest', MODEL_NAMESPACE, data, '/Sites/swsdp/documentLibrary', 'testNode').subscribe((response) => {
const args = [
'-root-',
{
'name': 'testNode',
'nodeType': 'typeTest',
'properties': {
'activitiForms:test': 'test',
'activitiForms:testdata': 'testdata'
},
'relativePath': '/Sites/swsdp/documentLibrary'
},
{}
];
expect(mockSpy.core.nodesApi.addNode.calls.mostRecent().args).toEqual(args);
expect(response).toBe(<any> responseBody);
done();
});
});
it('Should create a random name node with metadata', (done) => {
const uuidRegex = /[0-9a-z]{8}-[0-9a-z]{4}-4[0-9a-z]{3}-[0-9a-z]{4}-[0-9a-z]{12}/;
mockSpy.core.nodesApi.addNode.and.returnValue(Promise.resolve(responseBody));
service.createNodeMetadata('typeTest', MODEL_NAMESPACE, {}, '/Sites/swsdp/documentLibrary').subscribe(() => {
expect(mockSpy.core.nodesApi.addNode.calls.mostRecent().args[0]).toEqual('-root-');
expect(uuidRegex.test(mockSpy.core.nodesApi.addNode.calls.mostRecent().args[1].name)).toBe(true);
done();
});
});
});

View File

@@ -16,7 +16,7 @@
*/
import { Injectable } from '@angular/core';
import { MinimalNode, NodeEntry, NodePaging } from '@alfresco/js-api';
import { MinimalNode, NodeEntry, NodePaging, NodesApi, TrashcanApi } from '@alfresco/js-api';
import { from, Observable, throwError } from 'rxjs';
import { AlfrescoApiService } from './alfresco-api.service';
import { UserPreferencesService } from './user-preferences.service';
@@ -28,11 +28,13 @@ import { NodeMetadata } from '../models/node-metadata.model';
})
export class NodesApiService {
constructor(private api: AlfrescoApiService,
private preferences: UserPreferencesService) {}
private nodesApi: NodesApi;
private trashcanApi: TrashcanApi;
private get nodesApi() {
return this.api.getInstance().core.nodesApi;
constructor(private apiService: AlfrescoApiService,
private preferences: UserPreferencesService) {
this.nodesApi = new NodesApi(this.apiService.getInstance());
this.trashcanApi = new TrashcanApi(this.apiService.getInstance());
}
private getEntryFromEntity(entity: NodeEntry) {
@@ -47,7 +49,7 @@ export class NodesApiService {
*/
getNode(nodeId: string, options: any = {}): Observable<MinimalNode> {
const defaults = {
include: [ 'path', 'properties', 'allowableOperations', 'permissions' ]
include: ['path', 'properties', 'allowableOperations', 'permissions']
};
const queryOptions = Object.assign(defaults, options);
@@ -67,11 +69,11 @@ export class NodesApiService {
const defaults = {
maxItems: this.preferences.paginationSize,
skipCount: 0,
include: [ 'path', 'properties', 'allowableOperations', 'permissions' ]
include: ['path', 'properties', 'allowableOperations', 'permissions']
};
const queryOptions = Object.assign(defaults, options);
return from(this.nodesApi.getNodeChildren(nodeId, queryOptions)).pipe(
return from(this.nodesApi.listNodeChildren(nodeId, queryOptions)).pipe(
catchError((err) => throwError(err))
);
}
@@ -84,7 +86,7 @@ export class NodesApiService {
* @returns Details of the new node
*/
createNode(parentNodeId: string, nodeBody: any, options: any = {}): Observable<MinimalNode> {
return from(this.nodesApi.addNode(parentNodeId, nodeBody, options)).pipe(
return from(this.nodesApi.createNode(parentNodeId, nodeBody, options)).pipe(
map(this.getEntryFromEntity),
catchError((err) => throwError(err))
);
@@ -111,12 +113,12 @@ export class NodesApiService {
*/
updateNode(nodeId: string, nodeBody: any, options: any = {}): Observable<MinimalNode> {
const defaults = {
include: [ 'path', 'properties', 'allowableOperations', 'permissions', 'definition' ]
include: ['path', 'properties', 'allowableOperations', 'permissions', 'definition']
};
const queryOptions = Object.assign(defaults, options);
return from(this.nodesApi.updateNode(nodeId, nodeBody, queryOptions)).pipe(
map(this.getEntryFromEntity),
map(this.getEntryFromEntity),
catchError((err) => throwError(err))
);
}
@@ -139,7 +141,7 @@ export class NodesApiService {
* @returns Details of the restored node
*/
restoreNode(nodeId: string): Observable<MinimalNode> {
return from(this.nodesApi.restoreNode(nodeId)).pipe(
return from(this.trashcanApi.restoreDeletedNode(nodeId)).pipe(
map(this.getEntryFromEntity),
catchError((err) => throwError(err))
);
@@ -190,7 +192,7 @@ export class NodesApiService {
properties: properties,
relativePath: path
};
return from(this.nodesApi.addNode('-root-', body, {}));
return from(this.nodesApi.createNode('-root-', body, {}));
}
private generateUuid() {

View File

@@ -1,96 +0,0 @@
/*!
* @license
* Copyright 2019 Alfresco Software, Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { TestBed } from '@angular/core/testing';
import { setupTestBed } from '../testing/setup-test-bed';
import { AppConfigService } from '../app-config/app-config.service';
import { PageTitleService } from './page-title.service';
import { TranslationService } from './translation.service';
import { Title } from '@angular/platform-browser';
import { CoreModule } from '../core.module';
import { TranslateModule } from '@ngx-translate/core';
describe('PageTitleService', () => {
let titleService: Title;
let translationService: TranslationService;
let pageTitleService: PageTitleService;
let appConfigService: AppConfigService;
let titleServiceSpy: jasmine.Spy;
setupTestBed({
imports: [
TranslateModule.forRoot(),
CoreModule.forRoot()
]
});
beforeEach(() => {
titleService = TestBed.inject(Title);
pageTitleService = TestBed.inject(PageTitleService);
translationService = TestBed.inject(TranslationService);
appConfigService = TestBed.inject(AppConfigService);
titleServiceSpy = spyOn(titleService, 'setTitle').and.callThrough();
appConfigService.config.application.name = 'My application';
});
it('should set default application name', () => {
appConfigService.config.application = {};
pageTitleService.setTitle();
expect(titleServiceSpy).toHaveBeenCalledWith('Alfresco ADF Application');
});
it('should set only the application name', () => {
pageTitleService.setTitle();
expect(titleServiceSpy).toHaveBeenCalledWith('My application');
});
it('should append application name to the title', () => {
pageTitleService.setTitle('My page');
expect(titleServiceSpy).toHaveBeenCalledWith('My page - My application');
});
it('should update title on language change', () => {
// cspell: disable-next
spyOn(translationService, 'instant').and.returnValues('hello', 'привет');
pageTitleService.setTitle('key');
expect(titleServiceSpy).toHaveBeenCalledWith('hello - My application');
(<any> titleService).setTitle.calls.reset();
translationService.translate.onLangChange.next(<any> {});
// cspell: disable-next
expect(titleServiceSpy).toHaveBeenCalledWith('привет - My application');
});
it('should update title on new content download', () => {
// cspell: disable-next
spyOn(translationService, 'instant').and.returnValues('hello', 'привет');
pageTitleService.setTitle('key');
expect(titleServiceSpy).toHaveBeenCalledWith('hello - My application');
(<any> titleService).setTitle.calls.reset();
translationService.translate.onTranslationChange.next(<any> {});
// cspell: disable-next
expect(titleServiceSpy).toHaveBeenCalledWith('привет - My application');
});
});

View File

@@ -47,7 +47,7 @@ describe('PeopleContentService', () => {
});
it('should be able to fetch person details based on id', (done) => {
spyOn(service.peopleApi, 'getPerson').and.returnValue(Promise.resolve(new PersonEntry({ entry: fakeEcmUser })));
spyOn(service['peopleApi'], 'getPerson').and.returnValue(Promise.resolve(new PersonEntry({ entry: fakeEcmUser })));
service.getPerson('fake-id').subscribe((person) => {
expect(person.entry.id).toEqual('fake-id');
expect(person.entry.email).toEqual('fakeEcm@ecmUser.com');
@@ -56,7 +56,7 @@ describe('PeopleContentService', () => {
});
it('calls getPerson api method by an id', (done) => {
const getPersonSpy = spyOn(service.peopleApi, 'getPerson').and.returnValue(Promise.resolve(null));
const getPersonSpy = spyOn(service['peopleApi'], 'getPerson').and.returnValue(Promise.resolve(null));
service.getPerson('fake-id').subscribe(() => {
expect(getPersonSpy).toHaveBeenCalledWith('fake-id');
done();
@@ -64,7 +64,7 @@ describe('PeopleContentService', () => {
});
it('calls getPerson api method with "-me-"', (done) => {
const getPersonSpy = spyOn(service.peopleApi, 'getPerson').and.returnValue(Promise.resolve(null));
const getPersonSpy = spyOn(service['peopleApi'], 'getPerson').and.returnValue(Promise.resolve(null));
service.getPerson('-me-').subscribe(() => {
expect(getPersonSpy).toHaveBeenCalledWith('-me-');
done();
@@ -72,7 +72,7 @@ describe('PeopleContentService', () => {
});
it('should be able to list people', (done) => {
spyOn(service.peopleApi, 'listPeople').and.returnValue(Promise.resolve(fakeEcmUserList));
spyOn(service['peopleApi'], 'listPeople').and.returnValue(Promise.resolve(fakeEcmUserList));
service.listPeople().subscribe((response: PeopleContentQueryResponse) => {
const people = response.entries, pagination = response.pagination;
expect(people).toBeDefined();
@@ -87,7 +87,7 @@ describe('PeopleContentService', () => {
});
it('should call listPeople api method', (done) => {
const listPeopleSpy = spyOn(service.peopleApi, 'listPeople').and.returnValue(Promise.resolve(fakeEcmUserList));
const listPeopleSpy = spyOn(service['peopleApi'], 'listPeople').and.returnValue(Promise.resolve(fakeEcmUserList));
service.listPeople().subscribe(() => {
expect(listPeopleSpy).toHaveBeenCalled();
done();
@@ -95,7 +95,7 @@ describe('PeopleContentService', () => {
});
it('should call listPeople api with requested sorting params', async () => {
const listPeopleSpy = spyOn(service.peopleApi, 'listPeople').and.returnValue(Promise.resolve(fakeEcmUserList));
const listPeopleSpy = spyOn(service['peopleApi'], 'listPeople').and.returnValue(Promise.resolve(fakeEcmUserList));
const requestQueryParams: PeopleContentQueryRequestModel = { skipCount: 10, maxItems: 20, sorting: { orderBy: 'firstName', direction: 'asc' } };
const expectedValue = { skipCount: 10, maxItems: 20, orderBy: ['firstName ASC'] };
@@ -105,7 +105,7 @@ describe('PeopleContentService', () => {
});
it('should not call listPeople api with sorting params if sorting is not defined', async () => {
const listPeopleSpy = spyOn(service.peopleApi, 'listPeople').and.returnValue(Promise.resolve(fakeEcmUserList));
const listPeopleSpy = spyOn(service['peopleApi'], 'listPeople').and.returnValue(Promise.resolve(fakeEcmUserList));
const requestQueryParams: PeopleContentQueryRequestModel = { skipCount: 10, maxItems: 20, sorting: undefined };
const expectedValue = { skipCount: 10, maxItems: 20 };
@@ -115,7 +115,7 @@ describe('PeopleContentService', () => {
});
it('should be able to create new person', (done) => {
spyOn(service.peopleApi, 'createPerson').and.returnValue(Promise.resolve(new PersonEntry({ entry: fakeEcmUser })));
spyOn(service['peopleApi'], 'createPerson').and.returnValue(Promise.resolve(new PersonEntry({ entry: fakeEcmUser })));
service.createPerson(createNewPersonMock).subscribe((person) => {
expect(person.id).toEqual('fake-id');
expect(person.email).toEqual('fakeEcm@ecmUser.com');
@@ -124,7 +124,7 @@ describe('PeopleContentService', () => {
});
it('should be able to call createPerson api with new person details', (done) => {
const createPersonSpy = spyOn(service.peopleApi, 'createPerson').and.returnValue(Promise.resolve(new PersonEntry({ entry: fakeEcmUser })));
const createPersonSpy = spyOn(service['peopleApi'], 'createPerson').and.returnValue(Promise.resolve(new PersonEntry({ entry: fakeEcmUser })));
service.createPerson(createNewPersonMock).subscribe((person) => {
expect(person.id).toEqual('fake-id');
expect(person.email).toEqual('fakeEcm@ecmUser.com');
@@ -134,7 +134,7 @@ describe('PeopleContentService', () => {
});
it('should be able to throw an error if createPerson api failed', (done) => {
const createPersonSpy = spyOn(service.peopleApi, 'createPerson').and.returnValue(Promise.reject({ message: 'failed to create new person' }));
const createPersonSpy = spyOn(service['peopleApi'], 'createPerson').and.returnValue(Promise.reject({ message: 'failed to create new person' }));
const logErrorSpy = spyOn(logService, 'error');
service.createPerson(createNewPersonMock).subscribe(
() => {},
@@ -147,7 +147,7 @@ describe('PeopleContentService', () => {
});
it('Should make the api call to check if the user is a content admin only once', async () => {
const getCurrentPersonSpy = spyOn(service.peopleApi, 'getPerson').and.returnValue(Promise.resolve(getFakeUserWithContentAdminCapability()));
const getCurrentPersonSpy = spyOn(service['peopleApi'], 'getPerson').and.returnValue(Promise.resolve(getFakeUserWithContentAdminCapability()));
expect(await service.isContentAdmin()).toBe(true);
expect(getCurrentPersonSpy.calls.count()).toEqual(1);

View File

@@ -50,12 +50,10 @@ export class PeopleContentService {
private hasContentAdminRole: boolean = false;
hasCheckedIsContentAdmin: boolean = false;
private _peopleApi: PeopleApi;
private peopleApi: PeopleApi;
constructor(private apiService: AlfrescoApiService, private logService: LogService) {}
get peopleApi() {
return this._peopleApi || (this._peopleApi = new PeopleApi(this.apiService.getInstance()));
constructor(private apiService: AlfrescoApiService, private logService: LogService) {
this.peopleApi = new PeopleApi(this.apiService.getInstance());
}
/**

View File

@@ -21,14 +21,20 @@ import { UserProcessModel } from '../models/user-process.model';
import { AlfrescoApiService } from './alfresco-api.service';
import { LogService } from './log.service';
import { catchError, map } from 'rxjs/operators';
import { TaskActionsApi, UsersApi, ResultListDataRepresentationLightUserRepresentation } from '@alfresco/js-api';
@Injectable({
providedIn: 'root'
})
export class PeopleProcessService {
constructor(private alfrescoJsApi: AlfrescoApiService,
private taskActionsApi: TaskActionsApi;
private userApi: UsersApi;
constructor(private apiService: AlfrescoApiService,
private logService: LogService) {
this.taskActionsApi = new TaskActionsApi(this.apiService.getInstance());
this.userApi = new UsersApi(this.apiService.getInstance());
}
/**
@@ -62,7 +68,7 @@ export class PeopleProcessService {
* @returns Empty response when the update completes
*/
involveUserWithTask(taskId: string, idToInvolve: string): Observable<UserProcessModel[]> {
const node = {userId: idToInvolve};
const node = { userId: idToInvolve };
return from(this.involveUserToTaskApi(taskId, node))
.pipe(
catchError((err) => this.handleError(err))
@@ -76,27 +82,27 @@ export class PeopleProcessService {
* @returns Empty response when the update completes
*/
removeInvolvedUser(taskId: string, idToRemove: string): Observable<UserProcessModel[]> {
const node = {userId: idToRemove};
const node = { userId: idToRemove };
return from(this.removeInvolvedUserFromTaskApi(taskId, node))
.pipe(
catchError((err) => this.handleError(err))
);
}
private getWorkflowUserApi(options: any) {
return this.alfrescoJsApi.getInstance().activiti.usersWorkflowApi.getUsers(options);
private getWorkflowUserApi(options: any): Promise<ResultListDataRepresentationLightUserRepresentation> {
return this.userApi.getUsers(options);
}
private involveUserToTaskApi(taskId: string, node: any) {
return this.alfrescoJsApi.getInstance().activiti.taskActionsApi.involveUser(taskId, node);
return this.taskActionsApi.involveUser(taskId, node);
}
private removeInvolvedUserFromTaskApi(taskId: string, node: any) {
return this.alfrescoJsApi.getInstance().activiti.taskActionsApi.removeInvolvedUser(taskId, node);
return this.taskActionsApi.removeInvolvedUser(taskId, node);
}
private getUserProfileImageApi(userId: string): string {
return this.alfrescoJsApi.getInstance().activiti.userApi.getUserProfilePictureUrl(userId);
return this.userApi.getUserProfilePictureUrl(userId);
}
/**

View File

@@ -16,7 +16,7 @@
*/
import { Injectable } from '@angular/core';
import { RenditionEntry, RenditionPaging } from '@alfresco/js-api';
import { RenditionEntry, RenditionPaging, RenditionsApi, ContentApi } from '@alfresco/js-api';
import { Observable, from, interval, empty } from 'rxjs';
import { AlfrescoApiService } from './alfresco-api.service';
import { concatMap, switchMap, takeWhile, map } from 'rxjs/operators';
@@ -26,7 +26,12 @@ import { concatMap, switchMap, takeWhile, map } from 'rxjs/operators';
})
export class RenditionsService {
private renditionsApi: RenditionsApi;
private contentApi: ContentApi;
constructor(private apiService: AlfrescoApiService) {
this.renditionsApi = new RenditionsApi(this.apiService.getInstance());
this.contentApi = new ContentApi(this.apiService.getInstance());
}
/**
@@ -35,7 +40,7 @@ export class RenditionsService {
* @returns Information object for the rendition
*/
getAvailableRenditionForNode(nodeId: string): Observable<RenditionEntry> {
return from(this.apiService.renditionsApi.getRenditions(nodeId)).pipe(
return from(this.renditionsApi.listRenditions(nodeId)).pipe(
map((availableRenditions: RenditionPaging) => {
const renditionsAvailable: RenditionEntry[] = availableRenditions.list.entries.filter(
(rendition) => (rendition.entry.id === 'pdf' || rendition.entry.id === 'imgpreview'));
@@ -53,7 +58,7 @@ export class RenditionsService {
return this.getAvailableRenditionForNode(nodeId).pipe(
map((rendition: RenditionEntry) => {
if (rendition.entry.status !== 'CREATED') {
return from(this.apiService.renditionsApi.createRendition(nodeId, { id: rendition.entry.id }));
return from(this.renditionsApi.createRendition(nodeId, { id: rendition.entry.id }));
} else {
return empty();
}
@@ -114,7 +119,7 @@ export class RenditionsService {
* @returns URL string
*/
getRenditionUrl(nodeId: string, encoding: string): string {
return this.apiService.contentApi.getRenditionUrl(nodeId, encoding);
return this.contentApi.getRenditionUrl(nodeId, encoding);
}
/**
@@ -124,7 +129,7 @@ export class RenditionsService {
* @returns Information object about the rendition
*/
getRendition(nodeId: string, encoding: string): Observable<RenditionEntry> {
return from(this.apiService.renditionsApi.getRendition(nodeId, encoding));
return from(this.renditionsApi.getRendition(nodeId, encoding));
}
/**
@@ -133,7 +138,7 @@ export class RenditionsService {
* @returns Paged list of rendition details
*/
getRenditionsListByNodeId(nodeId: string): Observable<RenditionPaging> {
return from(this.apiService.renditionsApi.getRenditions(nodeId));
return from(this.renditionsApi.listRenditions(nodeId));
}
/**
@@ -143,7 +148,7 @@ export class RenditionsService {
* @returns Null response to indicate completion
*/
createRendition(nodeId: string, encoding: string): Observable<{}> {
return from(this.apiService.renditionsApi.createRendition(nodeId, { id: encoding }));
return from(this.renditionsApi.createRendition(nodeId, { id: encoding }));
}
/**

View File

@@ -16,17 +16,15 @@
*/
import { TestBed } from '@angular/core/testing';
import { searchMockApi, mockError, fakeSearch } from '../mock/search.service.mock';
import { mockError, fakeSearch } from '../mock/search.service.mock';
import { SearchService } from './search.service';
import { setupTestBed } from '../testing/setup-test-bed';
import { AlfrescoApiService } from './alfresco-api.service';
import { CoreTestingModule } from '../testing/core.testing.module';
import { TranslateModule } from '@ngx-translate/core';
describe('SearchService', () => {
let service: SearchService;
let apiService: AlfrescoApiService;
setupTestBed({
imports: [
@@ -37,16 +35,14 @@ describe('SearchService', () => {
beforeEach(() => {
service = TestBed.inject(SearchService);
apiService = TestBed.inject(AlfrescoApiService);
spyOn(apiService, 'getInstance').and.returnValue(searchMockApi);
});
it('should call search API with no additional options', (done) => {
const searchTerm = 'searchTerm63688';
spyOn(searchMockApi.core.queriesApi, 'findNodes').and.returnValue(Promise.resolve(fakeSearch));
spyOn(service.queriesApi, 'findNodes').and.returnValue(Promise.resolve(fakeSearch));
service.getNodeQueryResults(searchTerm).subscribe(
() => {
expect(searchMockApi.core.queriesApi.findNodes).toHaveBeenCalledWith(searchTerm, undefined);
expect(service.queriesApi.findNodes).toHaveBeenCalledWith(searchTerm, undefined);
done();
}
);
@@ -58,16 +54,17 @@ describe('SearchService', () => {
rootNodeId: '-root-',
nodeType: 'cm:content'
};
spyOn(searchMockApi.core.queriesApi, 'findNodes').and.returnValue(Promise.resolve(fakeSearch));
spyOn(service.queriesApi, 'findNodes').and.returnValue(Promise.resolve(fakeSearch));
service.getNodeQueryResults(searchTerm, options).subscribe(
() => {
expect(searchMockApi.core.queriesApi.findNodes).toHaveBeenCalledWith(searchTerm, options);
expect(service.queriesApi.findNodes).toHaveBeenCalledWith(searchTerm, options);
done();
}
);
});
it('should return search results returned from the API', (done) => {
spyOn(service.queriesApi, 'findNodes').and.returnValue(Promise.resolve(fakeSearch));
service.getNodeQueryResults('').subscribe(
(res: any) => {
expect(res).toBeDefined();
@@ -78,7 +75,7 @@ describe('SearchService', () => {
});
it('should notify errors returned from the API', (done) => {
spyOn(searchMockApi.core.queriesApi, 'findNodes').and.returnValue(Promise.reject(mockError));
spyOn(service.queriesApi, 'findNodes').and.returnValue(Promise.reject(mockError));
service.getNodeQueryResults('').subscribe(
() => {},
(res: any) => {

View File

@@ -16,7 +16,7 @@
*/
import { Injectable } from '@angular/core';
import { NodePaging, QueryBody, ResultSetPaging } from '@alfresco/js-api';
import { NodePaging, QueriesApi, QueryBody, ResultSetPaging, SearchApi } from '@alfresco/js-api';
import { Observable, Subject, from, throwError } from 'rxjs';
import { AlfrescoApiService } from './alfresco-api.service';
import { SearchConfigurationService } from './search-configuration.service';
@@ -27,9 +27,14 @@ import { SearchConfigurationService } from './search-configuration.service';
export class SearchService {
dataLoaded: Subject<ResultSetPaging> = new Subject();
queriesApi: QueriesApi;
searchApi: SearchApi;
constructor(private apiService: AlfrescoApiService,
private searchConfigurationService: SearchConfigurationService) {}
private searchConfigurationService: SearchConfigurationService) {
this.queriesApi = new QueriesApi(this.apiService.getInstance());
this.searchApi = new SearchApi(this.apiService.getInstance());
}
/**
* Gets a list of nodes that match the given search criteria.
@@ -38,7 +43,7 @@ export class SearchService {
* @returns List of nodes resulting from the search
*/
getNodeQueryResults(term: string, options?: SearchOptions): Observable<NodePaging> {
const promise = this.apiService.getInstance().core.queriesApi.findNodes(term, options);
const promise = this.queriesApi.findNodes(term, options);
promise.then((nodePaging: NodePaging) => {
this.dataLoaded.next(nodePaging);
@@ -56,7 +61,7 @@ export class SearchService {
*/
search(searchTerm: string, maxResults: number, skipCount: number): Observable<ResultSetPaging> {
const searchQuery = Object.assign(this.searchConfigurationService.generateQueryBody(searchTerm, maxResults, skipCount));
const promise = this.apiService.getInstance().search.searchApi.search(searchQuery);
const promise = this.searchApi.search(searchQuery);
promise.then((nodePaging: NodePaging) => {
this.dataLoaded.next(nodePaging);
@@ -71,7 +76,7 @@ export class SearchService {
* @returns List of search results
*/
searchByQueryBody(queryBody: QueryBody): Observable<ResultSetPaging> {
const promise = this.apiService.getInstance().search.searchApi.search(queryBody);
const promise = this.searchApi.search(queryBody);
promise.then((nodePaging: NodePaging) => {
this.dataLoaded.next(nodePaging);

View File

@@ -16,7 +16,7 @@
*/
import { Injectable } from '@angular/core';
import { NodePaging, SharedLinkEntry } from '@alfresco/js-api';
import { NodePaging, SharedLinkEntry, SharedlinksApi } from '@alfresco/js-api';
import { Observable, from, of, Subject } from 'rxjs';
import { AlfrescoApiService } from './alfresco-api.service';
import { UserPreferencesService } from './user-preferences.service';
@@ -28,13 +28,11 @@ import { catchError } from 'rxjs/operators';
export class SharedLinksApiService {
error = new Subject<{ statusCode: number, message: string }>();
private sharedLinksApi: SharedlinksApi;
constructor(private apiService: AlfrescoApiService,
private preferences: UserPreferencesService) {
}
private get sharedLinksApi() {
return this.apiService.getInstance().core.sharedlinksApi;
this.sharedLinksApi = new SharedlinksApi(this.apiService.getInstance());
}
/**
@@ -49,7 +47,7 @@ export class SharedLinksApiService {
include: ['properties', 'allowableOperations']
};
const queryOptions = Object.assign({}, defaultOptions, options);
const promise = this.sharedLinksApi.findSharedLinks(queryOptions);
const promise = this.sharedLinksApi.listSharedLinks(queryOptions);
return from(promise).pipe(
catchError((err) => of(err))
@@ -63,7 +61,7 @@ export class SharedLinksApiService {
* @returns The shared link just created
*/
createSharedLinks(nodeId: string, options: any = {}): Observable<SharedLinkEntry> {
const promise = this.sharedLinksApi.addSharedLink({ nodeId: nodeId }, options);
const promise = this.sharedLinksApi.createSharedLink({ nodeId: nodeId }, options);
return from(promise).pipe(
catchError((err) => of(err))

View File

@@ -40,10 +40,10 @@ import { LogService } from './log.service';
})
export class SitesService {
sitesApi: SitesApi;
private sitesApi: SitesApi;
constructor(private apiService: AlfrescoApiService, private logService: LogService) {
this.sitesApi = new SitesApi(apiService.getInstance());
this.sitesApi = new SitesApi(this.apiService.getInstance());
}
/**

View File

@@ -19,13 +19,11 @@ import { TestBed } from '@angular/core/testing';
import { ThumbnailService } from './thumbnail.service';
import { setupTestBed } from '../testing/setup-test-bed';
import { CoreTestingModule } from '../testing/core.testing.module';
import { AlfrescoApiService } from './alfresco-api.service';
import { TranslateModule } from '@ngx-translate/core';
describe('ThumbnailService', () => {
let service: ThumbnailService;
let apiService: AlfrescoApiService;
setupTestBed({
imports: [
@@ -36,7 +34,6 @@ describe('ThumbnailService', () => {
beforeEach(() => {
service = TestBed.inject(ThumbnailService);
apiService = TestBed.inject(AlfrescoApiService);
});
it('should return the correct icon for a plain text file', () => {
@@ -56,7 +53,7 @@ describe('ThumbnailService', () => {
});
it('should return the thumbnail URL for a content item', () => {
spyOn(apiService.contentApi, 'getDocumentThumbnailUrl').and.returnValue('/fake-thumbnail.png');
spyOn(service['contentApi'], 'getDocumentThumbnailUrl').and.returnValue('/fake-thumbnail.png');
expect(service.getDocumentThumbnailUrl('some-id')).toContain('/fake-thumbnail.png');
});
});

View File

@@ -20,7 +20,7 @@ import { Injectable } from '@angular/core';
import { MatIconRegistry } from '@angular/material/icon';
import { DomSanitizer } from '@angular/platform-browser';
import { AlfrescoApiService } from './alfresco-api.service';
import { NodeEntry } from '@alfresco/js-api';
import { ContentApi, NodeEntry } from '@alfresco/js-api';
@Injectable({
providedIn: 'root'
@@ -116,7 +116,7 @@ export class ThumbnailService {
'video/x-ms-asf': './assets/images/ft_ic_video.svg',
'video/x-ms-wmv': './assets/images/ft_ic_video.svg',
'video/x-msvideo': './assets/images/ft_ic_video.svg',
'video/x-rad-screenplay': './assets/images/ft_ic_video.svg',
'video/x-rad-screenplay': './assets/images/ft_ic_video.svg',
'video/x-sgi-movie': './assets/images/ft_ic_video.svg',
'video/x-matroska': './assets/images/ft_ic_video.svg',
'audio/mpeg': './assets/images/ft_ic_audio.svg',
@@ -164,7 +164,10 @@ export class ThumbnailService {
'task': './assets/images/task.svg'
};
private contentApi: ContentApi;
constructor(protected apiService: AlfrescoApiService, matIconRegistry: MatIconRegistry, sanitizer: DomSanitizer) {
this.contentApi = new ContentApi(apiService.getInstance());
Object.keys(this.mimeTypeIcons).forEach((key) => {
const url = sanitizer.bypassSecurityTrustResourceUrl(this.mimeTypeIcons[key]);
@@ -192,7 +195,7 @@ export class ThumbnailService {
nodeId = node.entry.id;
}
resultUrl = this.apiService.contentApi.getDocumentThumbnailUrl(nodeId, attachment, ticket);
resultUrl = this.contentApi.getDocumentThumbnailUrl(nodeId, attachment, ticket);
}
return resultUrl || this.DEFAULT_ICON;

View File

@@ -21,7 +21,6 @@ import { FileModel, FileUploadOptions, FileUploadStatus } from '../models/file.m
import { AppConfigModule } from '../app-config/app-config.module';
import { UploadService } from './upload.service';
import { AppConfigService } from '../app-config/app-config.service';
import { AlfrescoApiService } from './alfresco-api.service';
import { setupTestBed } from '../testing/setup-test-bed';
import { CoreTestingModule } from '../testing/core.testing.module';
@@ -35,7 +34,6 @@ declare let jasmine: any;
describe('UploadService', () => {
let service: UploadService;
let alfrescoApiService: AlfrescoApiService;
const mockProductInfo = new BehaviorSubject<EcmProductVersionModel>(null);
setupTestBed({
@@ -75,7 +73,6 @@ describe('UploadService', () => {
};
service = TestBed.inject(UploadService);
alfrescoApiService = TestBed.inject(AlfrescoApiService);
service.queue = [];
service.activeTask = null;
jasmine.Ajax.install();
@@ -309,7 +306,7 @@ describe('UploadService', () => {
});
it('If newVersion is set, name should be a param', () => {
const uploadFileSpy = spyOn(alfrescoApiService.getInstance().upload, 'uploadFile').and.callThrough();
const uploadFileSpy = spyOn(service['uploadApi'], 'uploadFile').and.callThrough();
const emitter = new EventEmitter();
@@ -359,7 +356,7 @@ describe('UploadService', () => {
});
it('should append to the request the extra upload options', () => {
const uploadFileSpy = spyOn(alfrescoApiService.getInstance().upload, 'uploadFile').and.callThrough();
const uploadFileSpy = spyOn(service['uploadApi'], 'uploadFile').and.callThrough();
const emitter = new EventEmitter();
const filesFake = new FileModel(
@@ -477,7 +474,7 @@ describe('UploadService', () => {
it('Should not pass rendition if it is disabled', () => {
mockProductInfo.next({ status: { isThumbnailGenerationEnabled: false } } as EcmProductVersionModel);
const uploadFileSpy = spyOn(alfrescoApiService.getInstance().upload, 'uploadFile').and.callThrough();
const uploadFileSpy = spyOn(service['uploadApi'], 'uploadFile').and.callThrough();
const emitter = new EventEmitter();
const filesFake = new FileModel(<File> { name: 'fake-name', size: 10 }, {

View File

@@ -29,6 +29,7 @@ import { FileModel, FileUploadProgress, FileUploadStatus } from '../models/file.
import { AlfrescoApiService } from './alfresco-api.service';
import { DiscoveryApiService } from './discovery-api.service';
import { filter } from 'rxjs/operators';
import { NodesApi, UploadApi, VersionsApi } from '@alfresco/js-api';
const MIN_CANCELLABLE_FILE_SIZE = 1000000;
const MAX_CANCELLABLE_FILE_PERCENTAGE = 50;
@@ -53,29 +54,19 @@ export class UploadService {
queueChanged: Subject<FileModel[]> = new Subject<FileModel[]>();
fileUpload: Subject<FileUploadEvent> = new Subject<FileUploadEvent>();
fileUploadStarting: Subject<FileUploadEvent> = new Subject<
FileUploadEvent
>();
fileUploadCancelled: Subject<FileUploadEvent> = new Subject<
FileUploadEvent
>();
fileUploadProgress: Subject<FileUploadEvent> = new Subject<
FileUploadEvent
>();
fileUploadAborted: Subject<FileUploadEvent> = new Subject<
FileUploadEvent
>();
fileUploadError: Subject<FileUploadErrorEvent> = new Subject<
FileUploadErrorEvent
>();
fileUploadComplete: Subject<FileUploadCompleteEvent> = new Subject<
FileUploadCompleteEvent
>();
fileUploadDeleted: Subject<FileUploadDeleteEvent> = new Subject<
FileUploadDeleteEvent
>();
fileUploadStarting: Subject<FileUploadEvent> = new Subject<FileUploadEvent>();
fileUploadCancelled: Subject<FileUploadEvent> = new Subject<FileUploadEvent>();
fileUploadProgress: Subject<FileUploadEvent> = new Subject<FileUploadEvent>();
fileUploadAborted: Subject<FileUploadEvent> = new Subject<FileUploadEvent>();
fileUploadError: Subject<FileUploadErrorEvent> = new Subject<FileUploadErrorEvent>();
fileUploadComplete: Subject<FileUploadCompleteEvent> = new Subject<FileUploadCompleteEvent>();
fileUploadDeleted: Subject<FileUploadDeleteEvent> = new Subject<FileUploadDeleteEvent>();
fileDeleted: Subject<string> = new Subject<string>();
private uploadApi: UploadApi;
private nodesApi: NodesApi;
private versionsApi: VersionsApi;
constructor(
protected apiService: AlfrescoApiService,
private appConfigService: AppConfigService,
@@ -85,6 +76,10 @@ export class UploadService {
.subscribe(({ status }) => {
this.isThumbnailGenerationEnabled = status.isThumbnailGenerationEnabled;
});
this.uploadApi = new UploadApi(apiService.getInstance());
this.nodesApi = new NodesApi(apiService.getInstance());
this.versionsApi = new VersionsApi(apiService.getInstance());
}
/**
@@ -255,19 +250,15 @@ export class UploadService {
}
if (file.id) {
return this.apiService
.getInstance()
.node.updateNodeContent(file.id, file.file, opts);
return this.nodesApi.updateNodeContent(file.id, <any> file.file, opts);
} else {
return this.apiService
.getInstance()
.upload.uploadFile(
file.file,
file.options.path,
file.options.parentId,
file.options,
opts
);
return this.uploadApi.uploadFile(
file.file,
file.options.path,
file.options.parentId,
file.options,
opts
);
}
}
@@ -307,7 +298,8 @@ export class UploadService {
}
}
})
.catch(() => {});
.catch(() => {
});
return promise;
}
@@ -420,16 +412,12 @@ export class UploadService {
}
private deleteAbortedNode(nodeId: string) {
this.apiService
.getInstance()
.core.nodesApi.deleteNode(nodeId, { permanent: true })
this.nodesApi.deleteNode(nodeId, { permanent: true })
.then(() => (this.abortedFile = undefined));
}
private deleteAbortedNodeVersion(nodeId: string, versionId: string) {
this.apiService
.getInstance()
.core.versionsApi.deleteVersion(nodeId, versionId)
this.versionsApi.deleteVersion(nodeId, versionId)
.then(() => (this.abortedFile = undefined));
}