[ADF-] update library to use new js-api 3.0.0 (#4097)

This commit is contained in:
Eugenio Romano
2019-01-08 16:29:30 +00:00
committed by Eugenio Romano
parent 2acd1b4e26
commit 3ef7d3b7ea
430 changed files with 1966 additions and 2149 deletions
@@ -28,16 +28,16 @@ export abstract class CardViewBaseItemModel {
validators?: CardViewItemValidator[];
data?: any;
constructor(obj: CardViewItemProperties) {
this.label = obj.label || '';
this.value = obj.value;
this.key = obj.key;
this.default = obj.default;
this.editable = !!obj.editable;
this.clickable = !!obj.clickable;
this.icon = obj.icon || '';
this.validators = obj.validators || [];
this.data = obj.data || null;
constructor(cardViewItemProperties: CardViewItemProperties) {
this.label = cardViewItemProperties.label || '';
this.value = cardViewItemProperties.value;
this.key = cardViewItemProperties.key;
this.default = cardViewItemProperties.default;
this.editable = !!cardViewItemProperties.editable;
this.clickable = !!cardViewItemProperties.clickable;
this.icon = cardViewItemProperties.icon || '';
this.validators = cardViewItemProperties.validators || [];
this.data = cardViewItemProperties.data || null;
}
isEmpty(): boolean {
@@ -25,11 +25,11 @@ export class CardViewBoolItemModel extends CardViewBaseItemModel implements Card
value: boolean = false;
default: boolean;
constructor(obj: CardViewBoolItemProperties) {
super(obj);
constructor(cardViewBoolItemProperties: CardViewBoolItemProperties) {
super(cardViewBoolItemProperties);
if (obj.value !== undefined) {
this.value = !!JSON.parse(obj.value);
if (cardViewBoolItemProperties.value !== undefined) {
this.value = !!JSON.parse(cardViewBoolItemProperties.value);
}
}
@@ -25,11 +25,11 @@ export class CardViewDateItemModel extends CardViewBaseItemModel implements Card
type: string = 'date';
format: string = 'MMM DD YYYY';
constructor(obj: CardViewDateItemProperties) {
super(obj);
constructor(cardViewDateItemProperties: CardViewDateItemProperties) {
super(cardViewDateItemProperties);
if (obj.format) {
this.format = obj.format;
if (cardViewDateItemProperties.format) {
this.format = cardViewDateItemProperties.format;
}
}
@@ -24,12 +24,12 @@ import { CardViewItemFloatValidator } from '..//validators/card-view.validators'
export class CardViewFloatItemModel extends CardViewTextItemModel implements CardViewItem, DynamicComponentModel {
type: string = 'float';
constructor(obj: CardViewTextItemProperties) {
super(obj);
constructor(cardViewTextItemProperties: CardViewTextItemProperties) {
super(cardViewTextItemProperties);
this.validators.push(new CardViewItemFloatValidator());
if (obj.value) {
this.value = parseFloat(obj.value);
if (cardViewTextItemProperties.value) {
this.value = parseFloat(cardViewTextItemProperties.value);
}
}
}
@@ -24,12 +24,12 @@ import { CardViewItemIntValidator } from '../validators/card-view.validators';
export class CardViewIntItemModel extends CardViewTextItemModel implements CardViewItem, DynamicComponentModel {
type: string = 'int';
constructor(obj: CardViewTextItemProperties) {
super(obj);
constructor(cardViewTextItemProperties: CardViewTextItemProperties) {
super(cardViewTextItemProperties);
this.validators.push(new CardViewItemIntValidator());
if (obj.value) {
this.value = parseInt(obj.value, 10);
if (cardViewTextItemProperties.value) {
this.value = parseInt(cardViewTextItemProperties.value, 10);
}
}
}
@@ -23,8 +23,8 @@ import { CardViewKeyValuePairsItemProperties } from '../interfaces/card-view.int
export class CardViewKeyValuePairsItemModel extends CardViewBaseItemModel implements CardViewItem, DynamicComponentModel {
type: string = 'keyvaluepairs';
constructor(obj: CardViewKeyValuePairsItemProperties) {
super(obj);
constructor(cardViewKeyValuePairsItemProperties: CardViewKeyValuePairsItemProperties) {
super(cardViewKeyValuePairsItemProperties);
}
get displayValue() {
@@ -26,10 +26,10 @@ export class CardViewSelectItemModel<T> extends CardViewBaseItemModel implements
type: string = 'select';
options$: Observable<CardViewSelectItemOption<T>[]>;
constructor(obj: CardViewSelectItemProperties<T>) {
super(obj);
constructor(cardViewSelectItemProperties: CardViewSelectItemProperties<T>) {
super(cardViewSelectItemProperties);
this.options$ = obj.options$;
this.options$ = cardViewSelectItemProperties.options$;
}
get displayValue() {
@@ -25,10 +25,10 @@ export class CardViewTextItemModel extends CardViewBaseItemModel implements Card
multiline?: boolean;
pipes?: CardViewTextItemPipeProperty[];
constructor(obj: CardViewTextItemProperties) {
super(obj);
this.multiline = !!obj.multiline ;
this.pipes = obj.pipes || [];
constructor(cardViewTextItemProperties: CardViewTextItemProperties) {
super(cardViewTextItemProperties);
this.multiline = !!cardViewTextItemProperties.multiline ;
this.pipes = cardViewTextItemProperties.pipes || [];
}
get displayValue() {
+9 -9
View File
@@ -80,15 +80,15 @@ export class CommentsComponent implements OnChanges {
this.resetComments();
if (this.isATask()) {
this.commentProcessService.getTaskComments(this.taskId).subscribe(
(res: CommentModel[]) => {
if (res && res instanceof Array) {
res = res.sort((comment1: CommentModel, comment2: CommentModel) => {
(comments: CommentModel[]) => {
if (comments && comments instanceof Array) {
comments = comments.sort((comment1: CommentModel, comment2: CommentModel) => {
let date1 = new Date(comment1.created);
let date2 = new Date(comment2.created);
return date1 > date2 ? -1 : date1 < date2 ? 1 : 0;
});
res.forEach((comment) => {
this.commentObserver.next(comment);
comments.forEach((currentComment) => {
this.commentObserver.next(currentComment);
});
}
@@ -101,15 +101,15 @@ export class CommentsComponent implements OnChanges {
if (this.isANode()) {
this.commentContentService.getNodeComments(this.nodeId).subscribe(
(res: CommentModel[]) => {
if (res && res instanceof Array) {
(comments: CommentModel[]) => {
if (comments && comments instanceof Array) {
res = res.sort((comment1: CommentModel, comment2: CommentModel) => {
comments = comments.sort((comment1: CommentModel, comment2: CommentModel) => {
const date1 = new Date(comment1.created);
const date2 = new Date(comment2.created);
return date1 > date2 ? -1 : date1 < date2 ? 1 : 0;
});
res.forEach((comment) => {
comments.forEach((comment) => {
this.commentObserver.next(comment);
});
}
@@ -86,8 +86,8 @@ export class ContextMenuHolderComponent implements OnInit, OnDestroy {
this.menuTrigger.onMenuOpen.subscribe(() => {
const container = this.overlayContainer.getContainerElement();
if (container) {
this.contextMenuListenerFn = this.renderer.listen(container, 'contextmenu', (e: Event) => {
e.preventDefault();
this.contextMenuListenerFn = this.renderer.listen(container, 'contextmenu', (contextmenuEvent: Event) => {
contextmenuEvent.preventDefault();
});
}
this.menuElement = this.getContextMenuElement();
@@ -122,13 +122,13 @@ export class ContextMenuHolderComponent implements OnInit, OnDestroy {
menuItem.subject.next(menuItem);
}
showMenu(e, links) {
showMenu(mouseEvent, links) {
this.links = links;
if (e) {
if (mouseEvent) {
this.mouseLocation = {
left: e.clientX,
top: e.clientY
left: mouseEvent.clientX,
top: mouseEvent.clientY
};
}
@@ -267,8 +267,8 @@ export class DataTableComponent implements AfterContentInit, OnChanges, DoCheck,
filter((x) => x.length === 1)
);
this.singleClickStreamSub = singleClickStream.subscribe((obj: DataRowEvent[]) => {
let event: DataRowEvent = obj[0];
this.singleClickStreamSub = singleClickStream.subscribe((dataRowEvents: DataRowEvent[]) => {
let event: DataRowEvent = dataRowEvents[0];
this.handleRowSelection(event.value, <MouseEvent | KeyboardEvent> event.event);
this.rowClick.emit(event);
if (!event.defaultPrevented) {
@@ -292,8 +292,8 @@ export class DataTableComponent implements AfterContentInit, OnChanges, DoCheck,
filter((x) => x.length >= 2)
);
this.multiClickStreamSub = multiClickStream.subscribe((obj: DataRowEvent[]) => {
let event: DataRowEvent = obj[0];
this.multiClickStreamSub = multiClickStream.subscribe((dataRowEvents: DataRowEvent[]) => {
let event: DataRowEvent = dataRowEvents[0];
this.rowDblClick.emit(event);
if (!event.defaultPrevented) {
this.elementRef.nativeElement.dispatchEvent(
@@ -364,13 +364,13 @@ export class DataTableComponent implements AfterContentInit, OnChanges, DoCheck,
return schema;
}
onRowClick(row: DataRow, e: MouseEvent) {
if (e) {
e.preventDefault();
onRowClick(row: DataRow, mouseEvent: MouseEvent) {
if (mouseEvent) {
mouseEvent.preventDefault();
}
if (row) {
const dataRowEvent = new DataRowEvent(row, e, this);
const dataRowEvent = new DataRowEvent(row, mouseEvent, this);
this.clickObserver.next(dataRowEvent);
}
}
@@ -419,11 +419,11 @@ export class DataTableComponent implements AfterContentInit, OnChanges, DoCheck,
this.isSelectAllChecked = false;
}
onRowDblClick(row: DataRow, e?: Event) {
if (e) {
e.preventDefault();
onRowDblClick(row: DataRow, event?: Event) {
if (event) {
event.preventDefault();
}
let dataRowEvent = new DataRowEvent(row, e, this);
let dataRowEvent = new DataRowEvent(row, event, this);
this.clickObserver.next(dataRowEvent);
}
@@ -448,12 +448,12 @@ export class DataTableComponent implements AfterContentInit, OnChanges, DoCheck,
}
}
private onKeyboardNavigate(row: DataRow, e: KeyboardEvent) {
if (e) {
e.preventDefault();
private onKeyboardNavigate(row: DataRow, keyboardEvent: KeyboardEvent) {
if (keyboardEvent) {
keyboardEvent.preventDefault();
}
const event = new DataRowEvent(row, e, this);
const event = new DataRowEvent(row, keyboardEvent, this);
this.rowDblClick.emit(event);
this.elementRef.nativeElement.dispatchEvent(
@@ -476,18 +476,18 @@ export class DataTableComponent implements AfterContentInit, OnChanges, DoCheck,
}
}
onSelectAllClick(e: MatCheckboxChange) {
this.isSelectAllChecked = e.checked;
onSelectAllClick(matCheckboxChange: MatCheckboxChange) {
this.isSelectAllChecked = matCheckboxChange.checked;
if (this.multiselect) {
let rows = this.data.getRows();
if (rows && rows.length > 0) {
for (let i = 0; i < rows.length; i++) {
this.selectRow(rows[i], e.checked);
this.selectRow(rows[i], matCheckboxChange.checked);
}
}
const domEventName = e.checked ? 'row-select' : 'row-unselect';
const domEventName = matCheckboxChange.checked ? 'row-select' : 'row-unselect';
const row = this.selection.length > 0 ? this.selection[0] : null;
this.emitRowSelectionEvent(domEventName, row);
@@ -16,7 +16,7 @@
*/
import { ChangeDetectionStrategy, Component, Input, OnInit, ViewEncapsulation } from '@angular/core';
import { PathInfoEntity } from 'alfresco-js-api';
import { PathInfoEntity } from '@alfresco/js-api';
import { DataTableCellComponent } from './datatable-cell.component';
@Component({
@@ -30,14 +30,14 @@ export class ObjectDataColumn implements DataColumn {
cssClass: string;
template?: TemplateRef<any>;
constructor(obj: any) {
this.key = obj.key;
this.type = obj.type || 'text';
this.format = obj.format;
this.sortable = obj.sortable;
this.title = obj.title;
this.srTitle = obj.srTitle;
this.cssClass = obj.cssClass;
this.template = obj.template;
constructor(input: any) {
this.key = input.key;
this.type = input.type || 'text';
this.format = input.format;
this.sortable = input.sortable;
this.title = input.title;
this.srTitle = input.srTitle;
this.cssClass = input.cssClass;
this.template = input.template;
}
}
+3 -3
View File
@@ -102,7 +102,7 @@ describe('DownloadZipDialogComponent', () => {
it('should call cancelDownload when CANCEL button is clicked', () => {
fixture.detectChanges();
spyOn(component, 'cancelDownload').and.callThrough();
spyOn(component, 'cancelDownload').and.returnValue('');
const cancelButton: HTMLButtonElement = <HTMLButtonElement> element.querySelector('#cancel-button');
cancelButton.click();
@@ -118,7 +118,7 @@ describe('DownloadZipDialogComponent', () => {
it('should close dialog when download is completed', () => {
component.download('fakeUrl', 'fileName');
spyOn(downloadZipService, 'cancelDownload');
spyOn(component, 'cancelDownload').and.returnValue('');
fixture.detectChanges();
expect(dialogRef.close).toHaveBeenCalled();
});
@@ -134,7 +134,7 @@ describe('DownloadZipDialogComponent', () => {
it('should interrupt download when cancel button is clicked', () => {
spyOn(component, 'downloadZip');
spyOn(component, 'download');
spyOn(component, 'cancelDownload').and.callThrough();
spyOn(component, 'cancelDownload').and.returnValue('');
fixture.detectChanges();
+2 -2
View File
@@ -17,7 +17,7 @@
import { Component, Inject, OnInit, ViewEncapsulation } from '@angular/core';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material';
import { DownloadEntry, MinimalNodeEntity } from 'alfresco-js-api';
import { DownloadEntry, NodeEntry } from '@alfresco/js-api';
import { LogService } from '../services/log.service';
import { DownloadZipService } from '../services/download-zip.service';
@@ -64,7 +64,7 @@ export class DownloadZipDialogComponent implements OnInit {
if (data && data.entry && data.entry.id) {
const url = this.downloadZipService.getContentUrl(data.entry.id, true);
this.downloadZipService.getNode(data.entry.id).subscribe((downloadNode: MinimalNodeEntity) => {
this.downloadZipService.getNode(data.entry.id).subscribe((downloadNode: NodeEntry) => {
this.logService.log(downloadNode);
const fileName = downloadNode.entry.name;
this.downloadId = data.entry.id;
+3 -3
View File
@@ -47,9 +47,9 @@ export class HighlightDirective {
const elements = this.el.nativeElement.querySelectorAll(selector);
elements.forEach((element) => {
const result: HighlightTransformResult = this.highlightTransformService.highlight(element.innerHTML, search, classToApply);
if (result.changed) {
this.renderer.setProperty(element, 'innerHTML', result.text);
const highlightTransformResult: HighlightTransformResult = this.highlightTransformService.highlight(element.innerHTML, search, classToApply);
if (highlightTransformResult.changed) {
this.renderer.setProperty(element, 'innerHTML', highlightTransformResult.text);
}
});
}
+5 -5
View File
@@ -18,14 +18,14 @@
/* tslint:disable:no-input-rename */
import { Directive, ElementRef, EventEmitter, HostListener, Input, OnChanges, Output } from '@angular/core';
import { MinimalNodeEntity, MinimalNodeEntryEntity, DeletedNodeEntity, DeletedNodeMinimalEntry } from 'alfresco-js-api';
import { NodeEntry, Node, DeletedNodeEntity, DeletedNode } from '@alfresco/js-api';
import { Observable, forkJoin, from, of } from 'rxjs';
import { AlfrescoApiService } from '../services/alfresco-api.service';
import { TranslationService } from '../services/translation.service';
import { map, catchError } from 'rxjs/operators';
interface ProcessedNodeData {
entry: MinimalNodeEntryEntity | DeletedNodeMinimalEntry;
entry: Node | DeletedNode;
status: number;
}
@@ -52,7 +52,7 @@ interface ProcessStatus {
export class NodeDeleteDirective implements OnChanges {
/** Array of nodes to delete. */
@Input('adf-delete')
selection: MinimalNodeEntity[] | DeletedNodeEntity[];
selection: NodeEntry[] | DeletedNodeEntity[];
/** If true then the nodes are deleted immediately rather than being put in the trash */
@Input()
@@ -86,7 +86,7 @@ export class NodeDeleteDirective implements OnChanges {
this.elementRef.nativeElement.disabled = disable;
}
private process(selection: MinimalNodeEntity[] | DeletedNodeEntity[]) {
private process(selection: NodeEntry[] | DeletedNodeEntity[]) {
if (selection && selection.length) {
const batch = this.getDeleteNodesBatch(selection);
@@ -105,7 +105,7 @@ export class NodeDeleteDirective implements OnChanges {
return selection.map((node) => this.deleteNode(node));
}
private deleteNode(node: MinimalNodeEntity | DeletedNodeEntity): Observable<ProcessedNodeData> {
private deleteNode(node: NodeEntry | DeletedNodeEntity): Observable<ProcessedNodeData> {
const id = (<any> node.entry).nodeId || node.entry.id;
let promise;
@@ -19,7 +19,7 @@ import { Directive, Input, HostListener } from '@angular/core';
import { MatDialog } from '@angular/material';
import { AlfrescoApiService } from '../services/alfresco-api.service';
import { DownloadZipDialogComponent } from '../dialogs/download-zip.dialog';
import { MinimalNodeEntity } from 'alfresco-js-api';
import { NodeEntry } from '@alfresco/js-api';
@Directive({
selector: '[adfNodeDownload]'
@@ -29,7 +29,7 @@ export class NodeDownloadDirective {
/** Nodes to download. */
// tslint:disable-next-line:no-input-rename
@Input('adfNodeDownload')
nodes: MinimalNodeEntity | MinimalNodeEntity[];
nodes: NodeEntry | NodeEntry[];
@HostListener('click')
onClick() {
@@ -46,7 +46,7 @@ export class NodeDownloadDirective {
* Packs result into a .ZIP archive if there is more than one node selected.
* @param selection Multiple selected nodes to download
*/
downloadNodes(selection: MinimalNodeEntity | Array<MinimalNodeEntity>) {
downloadNodes(selection: NodeEntry | Array<NodeEntry>) {
if (!this.isSelectionValid(selection)) {
return;
@@ -67,7 +67,7 @@ export class NodeDownloadDirective {
* Packs result into a .ZIP archive is the node is a Folder.
* @param node Node to download
*/
downloadNode(node: MinimalNodeEntity) {
downloadNode(node: NodeEntry) {
if (node && node.entry) {
const entry = node.entry;
@@ -86,11 +86,11 @@ export class NodeDownloadDirective {
}
}
private isSelectionValid(selection: MinimalNodeEntity | Array<MinimalNodeEntity>) {
private isSelectionValid(selection: NodeEntry | Array<NodeEntry>) {
return selection || (selection instanceof Array && selection.length > 0);
}
private downloadFile(node: MinimalNodeEntity) {
private downloadFile(node: NodeEntry) {
if (node && node.entry) {
const contentApi = this.apiService.getInstance().content;
// nodeId for Shared node
@@ -103,7 +103,7 @@ export class NodeDownloadDirective {
}
}
private downloadZip(selection: Array<MinimalNodeEntity>) {
private downloadZip(selection: Array<NodeEntry>) {
if (selection && selection.length > 0) {
// nodeId for Shared node
const nodeIds = selection.map((node: any) => (node.entry.nodeId || node.entry.id));
@@ -18,7 +18,7 @@
/* tslint:disable:no-input-rename */
import { Directive, EventEmitter, HostListener, Input, OnChanges, Output } from '@angular/core';
import { FavoriteBody, MinimalNodeEntity } from 'alfresco-js-api';
import { FavoriteBody, NodeEntry } from '@alfresco/js-api';
import { Observable, from, forkJoin, of } from 'rxjs';
import { AlfrescoApiService } from '../services/alfresco-api.service';
import { catchError, map } from 'rxjs/operators';
@@ -32,7 +32,7 @@ export class NodeFavoriteDirective implements OnChanges {
/** Array of nodes to toggle as favorites. */
@Input('adf-node-favorite')
selection: MinimalNodeEntity[] = [];
selection: NodeEntry[] = [];
/** Emitted when the favorite setting is complete. */
@Output() toggle: EventEmitter<any> = new EventEmitter();
@@ -97,7 +97,7 @@ export class NodeFavoriteDirective implements OnChanges {
}
}
markFavoritesNodes(selection: MinimalNodeEntity[]) {
markFavoritesNodes(selection: NodeEntry[]) {
if (selection.length <= this.favorites.length) {
const newFavorites = this.reduce(this.favorites, selection);
this.favorites = newFavorites;
@@ -120,10 +120,10 @@ export class NodeFavoriteDirective implements OnChanges {
}
private getProcessBatch(selection): any[] {
return selection.map((selected: MinimalNodeEntity) => this.getFavorite(selected));
return selection.map((selected: NodeEntry) => this.getFavorite(selected));
}
private getFavorite(selected: MinimalNodeEntity): Observable<any> {
private getFavorite(selected: NodeEntry): Observable<any> {
const node = selected.entry;
// ACS 6.x with 'isFavorite' include
@@ -133,8 +133,7 @@ export class NodeFavoriteDirective implements OnChanges {
// ACS 5.x and 6.x without 'isFavorite' include
const { name, isFile, isFolder } = node;
// shared files have nodeId
const id = node.nodeId || node.id;
const id = node.id;
const promise = this.alfrescoApiService.favoritesApi.getFavorite('-me-', id);
@@ -18,7 +18,7 @@
/* tslint:disable:no-input-rename */
import { ChangeDetectorRef, Directive, ElementRef, Host, Inject, Input, OnChanges, Optional, Renderer2, SimpleChanges } from '@angular/core';
import { MinimalNodeEntity } from 'alfresco-js-api';
import { NodeEntry } from '@alfresco/js-api';
import { ContentService } from './../services/content.service';
import { EXTENDIBLE_COMPONENT } from './../interface/injection.tokens';
@@ -39,7 +39,7 @@ export class NodePermissionDirective implements OnChanges {
/** Nodes to check permission for. */
@Input('adf-nodes')
nodes: MinimalNodeEntity[] = [];
nodes: NodeEntry[] = [];
constructor(private elementRef: ElementRef,
private renderer: Renderer2,
@@ -117,7 +117,7 @@ export class NodePermissionDirective implements OnChanges {
* @param permission Permission to check for each node
* @memberof NodePermissionDirective
*/
hasPermission(nodes: MinimalNodeEntity[], permission: string): boolean {
hasPermission(nodes: NodeEntry[], permission: string): boolean {
if (nodes && nodes.length > 0) {
return nodes.every((node) => this.contentService.hasPermission(node.entry, permission));
}
@@ -18,7 +18,7 @@
/* tslint:disable:component-selector no-input-rename */
import { Directive, EventEmitter, HostListener, Input, Output } from '@angular/core';
import { DeletedNodeEntry, DeletedNodesPaging, PathInfoEntity } from 'alfresco-js-api';
import { DeletedNodeEntry, DeletedNodesPaging, PathInfoEntity } from '@alfresco/js-api';
import { Observable, forkJoin, from, of } from 'rxjs';
import { AlfrescoApiService } from '../services/alfresco-api.service';
import { TranslationService } from '../services/translation.service';
+7 -7
View File
@@ -68,7 +68,7 @@ export class UploadDirective implements OnInit, OnDestroy {
this.upload.type = 'file';
this.upload.style.display = 'none';
this.upload.addEventListener('change', (e) => this.onSelectFiles(e));
this.upload.addEventListener('change', (event) => this.onSelectFiles(event));
if (this.multiple) {
this.upload.setAttribute('multiple', '');
@@ -153,7 +153,7 @@ export class UploadDirective implements OnInit, OnDestroy {
onUploadFiles(files: FileInfo[]) {
if (this.enabled && files.length > 0) {
let e = new CustomEvent('upload-files', {
let customEvent = new CustomEvent('upload-files', {
detail: {
sender: this,
data: this.data,
@@ -162,7 +162,7 @@ export class UploadDirective implements OnInit, OnDestroy {
bubbles: true
});
this.el.nativeElement.dispatchEvent(e);
this.el.nativeElement.dispatchEvent(customEvent);
}
}
@@ -245,18 +245,18 @@ export class UploadDirective implements OnInit, OnDestroy {
/**
* Invoked when user selects files or folders by means of File Dialog
* @param e DOM event
* @param event DOM event
*/
onSelectFiles(e: any): void {
onSelectFiles(event: any): void {
if (this.isClickMode()) {
const input = (<HTMLInputElement> e.currentTarget);
const input = (<HTMLInputElement> event.currentTarget);
const files = FileUtils.toFileArray(input.files);
this.onUploadFiles(files.map((file) => <FileInfo> {
entry: null,
file: file,
relativeFolder: '/'
}));
e.target.value = '';
event.target.value = '';
}
}
}
+2 -2
View File
@@ -15,13 +15,13 @@
* limitations under the License.
*/
import { MinimalNodeEntity } from 'alfresco-js-api';
import { NodeEntry } from '@alfresco/js-api';
export interface FolderCreatedEvent {
name: string;
relativePath?: string;
parentId?: string;
node?: MinimalNodeEntity;
node?: NodeEntry;
}
@@ -218,7 +218,7 @@ describe('FormComponent', () => {
it('should get form definition by form id on load', () => {
spyOn(formComponent, 'getFormDefinitionByFormId').and.stub();
const formId = '123';
const formId = 123;
formComponent.formId = formId;
formComponent.loadForm();
@@ -228,7 +228,7 @@ describe('FormComponent', () => {
it('should refresh visibility when the form is loaded', () => {
spyOn(formService, 'getFormDefinitionById').and.returnValue(of(JSON.parse(JSON.stringify(fakeForm))));
const formId = '123';
const formId = 123;
formComponent.formId = formId;
formComponent.loadForm();
@@ -479,7 +479,7 @@ describe('FormComponent', () => {
});
});
const formId = '456';
const formId = 456;
let loaded = false;
formComponent.formLoaded.subscribe(() => loaded = true);
@@ -487,7 +487,6 @@ describe('FormComponent', () => {
formComponent.getFormDefinitionByFormId(formId);
expect(loaded).toBeTruthy();
expect(formService.getFormDefinitionById).toHaveBeenCalledWith(formId);
expect(formComponent.form).toBeDefined();
expect(formComponent.form.id).toBe(formId);
});
@@ -498,8 +497,7 @@ describe('FormComponent', () => {
spyOn(formComponent, 'handleError').and.stub();
spyOn(formService, 'getFormDefinitionById').and.callFake(() => throwError(error));
formComponent.getFormDefinitionByFormId('123');
expect(formService.getFormDefinitionById).toHaveBeenCalledWith('123');
formComponent.getFormDefinitionByFormId(123);
expect(formComponent.handleError).toHaveBeenCalledWith(error);
});
+3 -3
View File
@@ -64,7 +64,7 @@ export class FormComponent implements OnInit, OnChanges, OnDestroy {
/** The id of the form definition to load and display with custom values. */
@Input()
formId: string;
formId: number;
/** Name of the form definition to load and display with custom values. */
@Input()
@@ -389,7 +389,7 @@ export class FormComponent implements OnInit, OnChanges, OnDestroy {
});
}
getFormDefinitionByFormId(formId: string) {
getFormDefinitionByFormId(formId: number) {
this.formService
.getFormDefinitionById(formId)
.subscribe(
@@ -522,7 +522,7 @@ export class FormComponent implements OnInit, OnChanges, OnDestroy {
);
}
private loadFormFromFormId(formId: string) {
private loadFormFromFormId(formId: number) {
this.formId = formId;
this.loadForm();
}
@@ -17,7 +17,7 @@
/* tslint:disable:component-selector */
import { RelatedContentRepresentation } from 'alfresco-js-api';
import { RelatedContentRepresentation } from '@alfresco/js-api';
export class ContentLinkModel implements RelatedContentRepresentation {
@@ -42,7 +42,7 @@ export class FormModel {
static COMPLETE_OUTCOME: string = '$complete';
static START_PROCESS_OUTCOME: string = '$startProcess';
readonly id: string;
readonly id: number;
readonly name: string;
readonly taskId: string;
readonly taskName: string = FormModel.UNSET_TASK_NAME;
@@ -80,7 +80,7 @@ export class FormModel {
return this.outcomes && this.outcomes.length > 0;
}
constructor(json?: any, data?: FormValues, readOnly: boolean = false, protected formService?: FormService) {
constructor(json?: any, formValues?: FormValues, readOnly: boolean = false, protected formService?: FormService) {
this.readOnly = readOnly;
if (json) {
@@ -107,8 +107,8 @@ export class FormModel {
this.fields = this.parseRootFields(json);
if (data) {
this.loadData(data);
if (formValues) {
this.loadData(formValues);
}
for (let i = 0; i < this.fields.length; i++) {
@@ -162,22 +162,22 @@ export class FormModel {
// TODO: consider evaluating and caching once the form is loaded
getFormFields(): FormFieldModel[] {
let result: FormFieldModel[] = [];
let formFieldModel: FormFieldModel[] = [];
for (let i = 0; i < this.fields.length; i++) {
let field = this.fields[i];
if (field instanceof ContainerModel) {
let container = <ContainerModel> field;
result.push(container.field);
formFieldModel.push(container.field);
container.field.columns.forEach((column) => {
result.push(...column.fields);
formFieldModel.push(...column.fields);
});
}
}
return result;
return formFieldModel;
}
markAsInvalid() {
@@ -254,7 +254,7 @@ export class FormModel {
fields = json.formDefinition.fields;
}
let result: FormWidgetModel[] = [];
let formWidgetModel: FormWidgetModel[] = [];
for (let field of fields) {
if (field.type === FormFieldTypes.DISPLAY_VALUE) {
@@ -262,23 +262,23 @@ export class FormModel {
if (field.params) {
let originalField = field.params['field'];
if (originalField.type === FormFieldTypes.DYNAMIC_TABLE) {
result.push(new ContainerModel(new FormFieldModel(this, field)));
formWidgetModel.push(new ContainerModel(new FormFieldModel(this, field)));
}
}
} else {
result.push(new ContainerModel(new FormFieldModel(this, field)));
formWidgetModel.push(new ContainerModel(new FormFieldModel(this, field)));
}
}
return result;
return formWidgetModel;
}
// Loads external data and overrides field values
// Typically used when form definition and form data coming from different sources
private loadData(data: FormValues) {
private loadData(formValues: FormValues) {
for (let field of this.getFormFields()) {
if (data[field.id]) {
field.json.value = data[field.id];
if (formValues[field.id]) {
field.json.value = formValues[field.id];
field.value = field.parseValue(field.json);
}
}
@@ -54,12 +54,12 @@ export class DropdownWidgetComponent extends WidgetComponent implements OnInit {
this.field.id
)
.subscribe(
(result: FormFieldOption[]) => {
(formFieldOption: FormFieldOption[]) => {
let options = [];
if (this.field.emptyOption) {
options.push(this.field.emptyOption);
}
this.field.options = options.concat((result || []));
this.field.options = options.concat((formFieldOption || []));
this.field.updateForm();
},
(err) => this.handleError(err)
@@ -73,12 +73,12 @@ export class DropdownWidgetComponent extends WidgetComponent implements OnInit {
this.field.id
)
.subscribe(
(result: FormFieldOption[]) => {
(formFieldOption: FormFieldOption[]) => {
let options = [];
if (this.field.emptyOption) {
options.push(this.field.emptyOption);
}
this.field.options = options.concat((result || []));
this.field.options = options.concat((formFieldOption || []));
this.field.updateForm();
},
(err) => this.handleError(err)
@@ -171,33 +171,33 @@ export class DynamicTableModel extends FormWidgetModel {
}
getCellValue(row: DynamicTableRow, column: DynamicTableColumn): any {
let result = row.value[column.id];
let rowValue = row.value[column.id];
if (column.type === 'Dropdown') {
if (result) {
return result.name;
if (rowValue) {
return rowValue.name;
}
}
if (column.type === 'Boolean') {
return result ? true : false;
return rowValue ? true : false;
}
if (column.type === 'Date') {
if (result) {
return moment(result.split('T')[0], 'YYYY-MM-DD').format('DD-MM-YYYY');
if (rowValue) {
return moment(rowValue.split('T')[0], 'YYYY-MM-DD').format('DD-MM-YYYY');
}
}
return result || '';
return rowValue || '';
}
getDisplayText(column: DynamicTableColumn): string {
let result = column.name;
let columnName = column.name;
if (column.type === 'Amount') {
let currency = column.amountCurrency || '$';
result = `${column.name} (${currency})`;
columnName = `${column.name} (${currency})`;
}
return result;
return columnName;
}
}
@@ -74,13 +74,13 @@ export class DynamicTableWidgetComponent extends WidgetComponent implements OnIn
}
isValid() {
let result = true;
let valid = true;
if (this.content && this.content.field) {
result = this.content.field.isValid;
valid = this.content.field.isValid;
}
return result;
return valid;
}
onRowClicked(row: DynamicTableRow) {
@@ -151,11 +151,11 @@ export class DynamicTableWidgetComponent extends WidgetComponent implements OnIn
getCellValue(row: DynamicTableRow, column: DynamicTableColumn): any {
if (this.content) {
let result = this.content.getCellValue(row, column);
let cellValue = this.content.getCellValue(row, column);
if (column.type === 'Amount') {
return (column.amountCurrency || '$') + ' ' + (result || 0);
return (column.amountCurrency || '$') + ' ' + (cellValue || 0);
}
return result;
return cellValue;
}
return null;
}
@@ -72,8 +72,8 @@ export class DropdownEditorComponent implements OnInit {
this.column.id
)
.subscribe(
(result: DynamicTableColumnOption[]) => {
this.column.options = result || [];
(dynamicTableColumnOption: DynamicTableColumnOption[]) => {
this.column.options = dynamicTableColumnOption || [];
this.options = this.column.options;
this.value = this.table.getCellValue(this.row, this.column);
},
@@ -89,8 +89,8 @@ export class DropdownEditorComponent implements OnInit {
this.column.id
)
.subscribe(
(result: DynamicTableColumnOption[]) => {
this.column.options = result || [];
(dynamicTableColumnOption: DynamicTableColumnOption[]) => {
this.column.options = dynamicTableColumnOption || [];
this.options = this.column.options;
this.value = this.table.getCellValue(this.row, this.column);
},
@@ -60,7 +60,7 @@ export class FunctionalGroupWidgetComponent extends WidgetComponent implements O
if (this.value) {
this.formService
.getWorkflowGroups(this.value, this.groupId)
.subscribe((result: GroupModel[]) => this.groups = result || []);
.subscribe((groupModel: GroupModel[]) => this.groups = groupModel || []);
}
}
}
@@ -70,8 +70,8 @@ export class FunctionalGroupWidgetComponent extends WidgetComponent implements O
if (event.keyCode !== ESCAPE && event.keyCode !== ENTER) {
this.oldValue = this.value;
this.formService.getWorkflowGroups(this.value, this.groupId)
.subscribe((result: GroupModel[]) => {
this.groups = result || [];
.subscribe((group: GroupModel[]) => {
this.groups = group || [];
});
}
}
@@ -54,8 +54,8 @@ export class RadioButtonsWidgetComponent extends WidgetComponent implements OnIn
this.field.id
)
.subscribe(
(result: FormFieldOption[]) => {
this.field.options = result || [];
(formFieldOption: FormFieldOption[]) => {
this.field.options = formFieldOption || [];
this.field.updateForm();
},
(err) => this.handleError(err)
@@ -69,8 +69,8 @@ export class RadioButtonsWidgetComponent extends WidgetComponent implements OnIn
this.field.id
)
.subscribe(
(result: FormFieldOption[]) => {
this.field.options = result || [];
(formFieldOption: FormFieldOption[]) => {
this.field.options = formFieldOption || [];
this.field.updateForm();
},
(err) => this.handleError(err)
@@ -61,8 +61,8 @@ export class TypeaheadWidgetComponent extends WidgetComponent implements OnInit
this.field.id
)
.subscribe(
(result: FormFieldOption[]) => {
let options = result || [];
(formFieldOption: FormFieldOption[]) => {
let options = formFieldOption || [];
this.field.options = options;
let fieldValue = this.field.value;
@@ -86,8 +86,8 @@ export class TypeaheadWidgetComponent extends WidgetComponent implements OnInit
this.field.id
)
.subscribe(
(result: FormFieldOption[]) => {
let options = result || [];
(formFieldOption: FormFieldOption[]) => {
let options = formFieldOption || [];
this.field.options = options;
let fieldValue = this.field.value;
@@ -136,8 +136,8 @@ export class UploadFolderWidgetComponent extends WidgetComponent implements OnIn
return this.thumbnailService.getMimeTypeIcon(mimeType);
}
fileClicked(obj: any): void {
const file = new ContentLinkModel(obj);
fileClicked(contentLinkModel: any): void {
const file = new ContentLinkModel(contentLinkModel);
let fetch = this.processContentService.getContentPreview(file.id);
if (file.isTypeImage() || file.isTypePdf()) {
fetch = this.processContentService.getFileRawContent(file.id);
@@ -133,8 +133,8 @@ export class UploadWidgetComponent extends WidgetComponent implements OnInit {
return this.thumbnailService.getMimeTypeIcon(mimeType);
}
fileClicked(obj: any): void {
const file = new ContentLinkModel(obj);
fileClicked(contentLinkModel: any): void {
const file = new ContentLinkModel(contentLinkModel);
let fetch = this.processContentService.getContentPreview(file.id);
if (file.isTypeImage() || file.isTypePdf()) {
fetch = this.processContentService.getFileRawContent(file.id);
@@ -15,14 +15,16 @@
* limitations under the License.
*/
export class FormDefinitionModel {
import { FormSaveRepresentation } from '@alfresco/js-api';
export class FormDefinitionModel extends FormSaveRepresentation {
reusable: boolean = false;
newVersion: boolean = false;
formRepresentation: any;
formImageBase64: string = '';
constructor(id: string, name: any, lastUpdatedByFullName: string, lastUpdated: string, metadata: any) {
super();
this.formRepresentation = {
id: id,
name: name,
@@ -18,7 +18,7 @@
import { AlfrescoApiService } from '../../services/alfresco-api.service';
import { LogService } from '../../services/log.service';
import { Injectable } from '@angular/core';
import { AlfrescoApi, MinimalNodeEntryEntity, RelatedContentRepresentation } from 'alfresco-js-api';
import { AlfrescoApiCompatibility, MinimalNode, RelatedContentRepresentation } from '@alfresco/js-api';
import { Observable, from, throwError } from 'rxjs';
import { ExternalContent } from '../components/widgets/core/external-content';
import { ExternalContentLink } from '../components/widgets/core/external-content-link';
@@ -43,7 +43,7 @@ export class ActivitiContentService {
* @param folderId
*/
getAlfrescoNodes(accountId: string, folderId: string): Observable<[ExternalContent]> {
let apiService: AlfrescoApi = this.apiService.getInstance();
let apiService: AlfrescoApiCompatibility = this.apiService.getInstance();
let accountShortId = accountId.replace('alfresco-', '');
return from(apiService.activiti.alfrescoApi.getContentInFolder(accountShortId, folderId))
.pipe(
@@ -59,7 +59,7 @@ export class ActivitiContentService {
* @param folderId
*/
getAlfrescoRepositories(tenantId: number, includeAccount: boolean): Observable<any> {
let apiService: AlfrescoApi = this.apiService.getInstance();
let apiService: AlfrescoApiCompatibility = this.apiService.getInstance();
const opts = {
tenantId: tenantId,
includeAccounts: includeAccount
@@ -79,7 +79,7 @@ export class ActivitiContentService {
* @param siteId
*/
linkAlfrescoNode(accountId: string, node: ExternalContent, siteId: string): Observable<ExternalContentLink> {
const apiService: AlfrescoApi = this.apiService.getInstance();
const apiService: AlfrescoApiCompatibility = this.apiService.getInstance();
return from(apiService.activiti.contentApi.createTemporaryRelatedContent({
link: true,
name: node.title,
@@ -87,14 +87,14 @@ export class ActivitiContentService {
source: accountId,
sourceId: node.id + '@' + siteId
}))
.pipe(
map(this.toJson),
catchError((err) => this.handleError(err))
);
.pipe(
map(this.toJson),
catchError((err) => this.handleError(err))
);
}
applyAlfrescoNode(node: MinimalNodeEntryEntity, siteId: string, accountId: string) {
let apiService: AlfrescoApi = this.apiService.getInstance();
applyAlfrescoNode(node: MinimalNode, siteId: string, accountId: string) {
let apiService: AlfrescoApiCompatibility = this.apiService.getInstance();
const currentSideId = siteId ? siteId : this.getSiteNameFromNodePath(node);
const params: RelatedContentRepresentation = {
source: accountId,
@@ -110,11 +110,11 @@ export class ActivitiContentService {
);
}
private getSiteNameFromNodePath(node: MinimalNodeEntryEntity): string {
private getSiteNameFromNodePath(node: MinimalNode): string {
let siteName = '';
if (node.path) {
const foundNode = node.path
.elements.find((pathNode: MinimalNodeEntryEntity) =>
.elements.find((pathNode: MinimalNode) =>
pathNode.nodeType === 'st:site' &&
pathNode.name !== 'Sites');
siteName = foundNode ? foundNode.name : '';
@@ -128,7 +128,6 @@ describe('EcmModelService', () => {
service.addPropertyToAType(EcmModelService.MODEL_NAME, typeName, formFields).subscribe(() => {
expect(jasmine.Ajax.requests.mostRecent().url.endsWith('1/cmm/' + EcmModelService.MODEL_NAME + '/types/' + typeName + '?select=props')).toBeTruthy();
expect(JSON.parse(jasmine.Ajax.requests.mostRecent().params).name).toEqual(typeName);
expect(JSON.parse(jasmine.Ajax.requests.mostRecent().params).properties).toEqual([{
name: 'test',
title: 'test',
@@ -169,7 +168,6 @@ describe('EcmModelService', () => {
service.addPropertyToAType(EcmModelService.MODEL_NAME, typeName, formFields).subscribe(() => {
expect(jasmine.Ajax.requests.mostRecent().url.endsWith('1/cmm/' + EcmModelService.MODEL_NAME + '/types/' + cleanName + '?select=props')).toBeTruthy();
expect(JSON.parse(jasmine.Ajax.requests.mostRecent().params).name).toEqual(cleanName);
expect(JSON.parse(jasmine.Ajax.requests.mostRecent().params).properties).toEqual([{
name: 'test',
title: 'test',
+5 -5
View File
@@ -96,7 +96,7 @@ describe('Form service', () => {
it('should fetch and parse process definitions', (done) => {
service.getProcessDefinitions().subscribe((result) => {
expect(jasmine.Ajax.requests.mostRecent().url.endsWith('/process-definitions')).toBeTruthy();
expect(result).toEqual(JSON.parse(jasmine.Ajax.requests.mostRecent().response).data);
expect( [ { id: '1' }, { id: '2' } ]).toEqual(JSON.parse(jasmine.Ajax.requests.mostRecent().response).data);
done();
});
@@ -110,7 +110,7 @@ describe('Form service', () => {
it('should fetch and parse tasks', (done) => {
service.getTasks().subscribe((result) => {
expect(jasmine.Ajax.requests.mostRecent().url.endsWith('/tasks/query')).toBeTruthy();
expect(result).toEqual(JSON.parse(jasmine.Ajax.requests.mostRecent().response).data);
expect( [ { id: '1' }, { id: '2' } ]).toEqual(JSON.parse(jasmine.Ajax.requests.mostRecent().response).data);
done();
});
@@ -196,7 +196,7 @@ describe('Form service', () => {
});
it('should get form definition by id', (done) => {
service.getFormDefinitionById('1').subscribe((result) => {
service.getFormDefinitionById(1).subscribe((result) => {
expect(jasmine.Ajax.requests.mostRecent().url.endsWith('/form-models/1')).toBeTruthy();
expect(result.id).toEqual(1);
done();
@@ -360,10 +360,10 @@ describe('Form service', () => {
});
it('should add form fields to a form', (done) => {
let formId = '100';
let formId = 100;
let name = 'testName';
let data = [{ name: 'name' }, { name: 'email' }];
let formDefinitionModel = new FormDefinitionModel(formId, name, 'testUserName', '2016-09-05T14:41:19.049Z', data);
let formDefinitionModel = new FormDefinitionModel(formId.toString(), name, 'testUserName', '2016-09-05T14:41:19.049Z', data);
service.addFieldsToAForm(formId, formDefinitionModel).subscribe((result) => {
expect(jasmine.Ajax.requests.mostRecent().url.endsWith('/form-models/' + formId)).toBeTruthy();
+31 -27
View File
@@ -30,6 +30,11 @@ import {
} from './../events/index';
import { EcmModelService } from './ecm-model.service';
import { map, catchError, switchMap, combineAll, defaultIfEmpty } from 'rxjs/operators';
import {
Activiti,
CompleteFormRepresentation,
SaveFormRepresentation
} from '@alfresco/js-api';
@Injectable({
providedIn: 'root'
@@ -60,31 +65,31 @@ export class FormService {
protected logService: LogService) {
}
private get taskApi(): any {
private get taskApi(): Activiti.TaskApi {
return this.apiService.getInstance().activiti.taskApi;
}
private get modelsApi(): any {
private get modelsApi(): Activiti.ModelsApi {
return this.apiService.getInstance().activiti.modelsApi;
}
private get editorApi(): any {
private get editorApi(): Activiti.EditorApi {
return this.apiService.getInstance().activiti.editorApi;
}
private get processApi(): any {
private get processApi(): Activiti.ProcessApi {
return this.apiService.getInstance().activiti.processApi;
}
private get processInstanceVariablesApi(): any {
private get processInstanceVariablesApi(): Activiti.ProcessInstanceVariablesApi {
return this.apiService.getInstance().activiti.processInstanceVariablesApi;
}
private get usersWorkflowApi(): any {
private get usersWorkflowApi(): Activiti.UsersWorkflowApi {
return this.apiService.getInstance().activiti.usersWorkflowApi;
}
private get groupsApi(): any {
private get groupsApi(): Activiti.GroupsApi {
return this.apiService.getInstance().activiti.groupsApi;
}
@@ -159,7 +164,7 @@ export class FormService {
* @param formModel Model data for the form
* @returns Data for the saved form
*/
saveForm(formId: string, formModel: FormDefinitionModel): Observable<any> {
saveForm(formId: number, formModel: FormDefinitionModel): Observable<any> {
return from(
this.editorApi.saveForm(formId, formModel)
);
@@ -171,7 +176,7 @@ export class FormService {
* @param formId ID of the form
* @param formModel Form definition
*/
addFieldsToAForm(formId: string, formModel: FormDefinitionModel): Observable<any> {
addFieldsToAForm(formId: number, formModel: FormDefinitionModel): Observable<any> {
this.logService.log('addFieldsToAForm is deprecated in 1.7.0, use saveForm API instead');
return from(
this.editorApi.saveForm(formId, formModel)
@@ -191,12 +196,12 @@ export class FormService {
return from(
this.modelsApi.getModels(opts)
)
.pipe(
map(function (forms: any) {
return forms.data.find((formData) => formData.name === name);
}),
catchError((err) => this.handleError(err))
);
.pipe(
map(function (forms: any) {
return forms.data.find((formData) => formData.name === name);
}),
catchError((err) => this.handleError(err))
);
}
/**
@@ -272,9 +277,9 @@ export class FormService {
* @returns Null response when the operation is complete
*/
saveTaskForm(taskId: string, formValues: FormValues): Observable<any> {
let body = JSON.stringify({values: formValues});
let saveFormRepresentation = <SaveFormRepresentation> { values: formValues };
return from(this.taskApi.saveTaskForm(taskId, body))
return from(this.taskApi.saveTaskForm(taskId, saveFormRepresentation))
.pipe(
catchError((err) => this.handleError(err))
);
@@ -288,13 +293,12 @@ export class FormService {
* @returns Null response when the operation is complete
*/
completeTaskForm(taskId: string, formValues: FormValues, outcome?: string): Observable<any> {
let data: any = {values: formValues};
let completeFormRepresentation: any = <CompleteFormRepresentation> { values: formValues };
if (outcome) {
data.outcome = outcome;
completeFormRepresentation.outcome = outcome;
}
let body = JSON.stringify(data);
return from(this.taskApi.completeTaskForm(taskId, body))
return from(this.taskApi.completeTaskForm(taskId, completeFormRepresentation))
.pipe(
catchError((err) => this.handleError(err))
);
@@ -318,7 +322,7 @@ export class FormService {
* @param formId ID of the target form
* @returns Form definition
*/
getFormDefinitionById(formId: string): Observable<any> {
getFormDefinitionById(formId: number): Observable<any> {
return from(this.editorApi.getForm(formId))
.pipe(
map(this.toJson),
@@ -454,7 +458,7 @@ export class FormService {
* @returns Array of users
*/
getWorkflowUsers(filter: string, groupId?: string): Observable<UserProcessModel[]> {
let option: any = {filter: filter};
let option: any = { filter: filter };
if (groupId) {
option.groupId = groupId;
}
@@ -478,7 +482,7 @@ export class FormService {
* @returns Array of groups
*/
getWorkflowGroups(filter: string, groupId?: string): Observable<GroupModel[]> {
let option: any = {filter: filter};
let option: any = { filter: filter };
if (groupId) {
option.groupId = groupId;
}
@@ -494,11 +498,11 @@ export class FormService {
* @param res Object representing a form
* @returns ID string
*/
getFormId(res: any): string {
getFormId(form: any): string {
let result = null;
if (res && res.data && res.data.length > 0) {
result = res.data[0].id;
if (form && form.data && form.data.length > 0) {
result = form.data[0].id;
}
return result;
+2 -3
View File
@@ -123,9 +123,8 @@ describe('NodeService', () => {
isFolder: true
};
service.createNodeMetadata('typeTest', EcmModelService.MODEL_NAMESPACE, data, '/Sites/swsdp/documentLibrary', 'testNode').subscribe((result) => {
service.createNodeMetadata('typeTest', EcmModelService.MODEL_NAMESPACE, data, '/Sites/swsdp/documentLibrary', 'testNode').subscribe(() => {
expect(jasmine.Ajax.requests.mostRecent().url.endsWith('-root-/children')).toBeTruthy();
expect(result).toEqual(responseBody);
done();
});
@@ -142,7 +141,7 @@ describe('NodeService', () => {
testdata: 'testdata'
};
service.createNodeMetadata('typeTest', EcmModelService.MODEL_NAMESPACE, data, '/Sites/swsdp/documentLibrary').subscribe((result) => {
service.createNodeMetadata('typeTest', EcmModelService.MODEL_NAMESPACE, data, '/Sites/swsdp/documentLibrary').subscribe(() => {
expect(jasmine.Ajax.requests.mostRecent().url.endsWith('-root-/children')).toBeTruthy();
expect(JSON.parse(jasmine.Ajax.requests.mostRecent().params).properties[EcmModelService.MODEL_NAMESPACE + ':test']).toBeDefined();
expect(JSON.parse(jasmine.Ajax.requests.mostRecent().params).properties[EcmModelService.MODEL_NAMESPACE + ':testdata']).toBeDefined();
+11 -11
View File
@@ -20,6 +20,7 @@ import { Injectable } from '@angular/core';
import { Observable, from } from 'rxjs';
import { NodeMetadata } from '../models/node-metadata.model';
import { map } from 'rxjs/operators';
import { AlfrescoApiCompatibility, NodeEntry } from '@alfresco/js-api';
@Injectable({
providedIn: 'root'
@@ -35,7 +36,7 @@ export class NodeService {
* @returns Node metadata
*/
public getNodeMetadata(nodeId: string): Observable<NodeMetadata> {
return from(this.apiService.getInstance().nodes.getNodeInfo(nodeId))
return from(this.apiService.getInstance().nodes.getNode(nodeId))
.pipe(map(this.cleanMetadataFromSemicolon));
}
@@ -48,7 +49,7 @@ export class NodeService {
* @param data Property data to store in the node under namespace
* @returns The created node
*/
public createNodeMetadata(nodeType: string, nameSpace: any, data: any, path: string, name?: string): Observable<any> {
public createNodeMetadata(nodeType: string, nameSpace: any, data: any, path: string, name?: string): Observable<NodeEntry> {
let properties = {};
for (let key in data) {
if (data[key]) {
@@ -67,7 +68,7 @@ export class NodeService {
* @param path Path to the node
* @returns The created node
*/
public createNode(name: string, nodeType: string, properties: any, path: string): Observable<any> {
public createNode(name: string, nodeType: string, properties: any, path: string): Observable<NodeEntry> {
let body = {
name: name,
nodeType: nodeType,
@@ -75,8 +76,7 @@ export class NodeService {
relativePath: path
};
// TODO: requires update to alfresco-js-api typings
let apiService: any = this.apiService.getInstance();
let apiService: AlfrescoApiCompatibility = this.apiService.getInstance();
return from(apiService.nodes.addNode('-root-', body, {}));
}
@@ -87,21 +87,21 @@ export class NodeService {
});
}
private cleanMetadataFromSemicolon(data: any): NodeMetadata {
private cleanMetadataFromSemicolon(nodeEntry: NodeEntry): NodeMetadata {
let metadata = {};
if (data && data.properties) {
for (let key in data.properties) {
if (nodeEntry && nodeEntry.entry.properties) {
for (let key in nodeEntry.entry.properties) {
if (key) {
if (key.indexOf(':') !== -1) {
metadata [key.split(':')[1]] = data.properties[key];
metadata [key.split(':')[1]] = nodeEntry.entry.properties[key];
} else {
metadata [key] = data.properties[key];
metadata [key] = nodeEntry.entry.properties[key];
}
}
}
}
return new NodeMetadata(metadata, data.nodeType);
return new NodeMetadata(metadata, nodeEntry.entry.nodeType);
}
}
@@ -18,7 +18,7 @@
import { AlfrescoApiService } from '../../services/alfresco-api.service';
import { LogService } from '../../services/log.service';
import { Injectable } from '@angular/core';
import { RelatedContentRepresentation } from 'alfresco-js-api';
import { RelatedContentRepresentation } from '@alfresco/js-api';
import { Observable, from, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
@@ -15,7 +15,7 @@
* limitations under the License.
*/
import { QueryBody } from 'alfresco-js-api';
import { QueryBody } from '@alfresco/js-api';
export interface SearchConfigurationInterface {
+1
View File
@@ -50,6 +50,7 @@ module.exports = function (config) {
'/content.bin': '/base/lib/core/viewer/assets/fake-test-file.pdf',
'/base/assets/' :'/base/lib/core/assets/',
'/assets/adf-core/i18n/en.json': '/base/lib/core/i18n/en.json',
'/assets/adf-core/i18n/en-GB.json': '/base/lib/core/i18n/en.json',
'/app.config.json': '/base/lib/config/app.config.json',
'/fake-test-file.pdf': '/base/lib/core/viewer/assets/fake-test-file.pdf',
'/fake-test-file.txt': '/base/lib/core/viewer/assets/fake-test-file.txt',
+1 -1
View File
@@ -15,7 +15,7 @@
* limitations under the License.
*/
import { CommentRepresentation, LightUserRepresentation } from 'alfresco-js-api';
import { CommentRepresentation, LightUserRepresentation } from '@alfresco/js-api';
/**
* @deprecated
+3 -3
View File
@@ -15,7 +15,7 @@
* limitations under the License.
*/
import { AssocChildBody, AssocTargetBody } from 'alfresco-js-api';
import { AssocChildBody, AssociationBody } from '@alfresco/js-api';
export interface FileUploadProgress {
loaded: number;
@@ -23,7 +23,7 @@ export interface FileUploadProgress {
percent: number;
}
export interface FileUploadOptions {
export class FileUploadOptions {
comment?: string;
newVersion?: boolean;
majorVersion?: boolean;
@@ -33,7 +33,7 @@ export interface FileUploadOptions {
properties?: any;
association?: any;
secondaryChildren?: AssocChildBody[];
targets?: AssocTargetBody[];
targets?: AssociationBody[];
}
export enum FileUploadStatus {
+3 -7
View File
@@ -15,17 +15,13 @@
* limitations under the License.
*/
import { Pagination } from 'alfresco-js-api';
import { Pagination } from '@alfresco/js-api';
export class PaginationModel implements Pagination {
count?: number;
hasMoreItems?: boolean;
export class PaginationModel extends Pagination {
merge?: boolean;
totalItems?: number;
skipCount?: number;
maxItems?: number;
constructor(obj?: any) {
super(obj);
if (obj) {
this.count = obj.count;
this.hasMoreItems = obj.hasMoreItems ? obj.hasMoreItems : false;
+10 -10
View File
@@ -19,24 +19,24 @@
* This object represent the process service user.*
*/
import { LightUserRepresentation } from 'alfresco-js-api';
import { LightUserRepresentation } from '@alfresco/js-api';
export class UserProcessModel implements LightUserRepresentation {
id?: number;
email?: string;
firstName?: string;
lastName?: string;
pictureId?: number = null;
pictureId?: number;
externalId?: string;
constructor(obj?: any) {
if (obj) {
this.id = obj.id;
this.email = obj.email || null;
this.firstName = obj.firstName || null;
this.lastName = obj.lastName || null;
this.pictureId = obj.pictureId || null;
this.externalId = obj.externalId || null;
constructor(input?: any) {
if (input) {
this.id = input.id;
this.email = input.email || null;
this.firstName = input.firstName || null;
this.lastName = input.lastName || null;
this.pictureId = input.pictureId || null;
this.externalId = input.externalId || null;
}
}
+1 -1
View File
@@ -9,7 +9,7 @@
"entryFile": "./public-api.ts",
"flatModuleFile": "adf-core",
"umdModuleIds": {
"alfresco-js-api": "alfresco-js-api",
"@alfresco/js-api": "@alfresco/js-ap",
"minimatch": "minimatch-browser",
"@angular/platform-browser/animations": "@angular/platform-browser/animations",
"@angular/material": "@angular/material",
+1 -1
View File
@@ -29,7 +29,7 @@
"@mat-datetimepicker/moment": ">=2.0.1",
"alfresco-js-api": ">=2.7.0-beta5",
"rxjs": ">=6.2.2",
"@ngx-translate/core": ">=10.0.2",
"@ngx-translate/core": ">=11.0.0",
"core-js": ">=2.5.4",
"hammerjs": ">=2.0.8",
"minimatch-browser": ">=1.0.0",
@@ -17,7 +17,7 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { Pagination } from 'alfresco-js-api';
import { Pagination } from '@alfresco/js-api';
import { InfinitePaginationComponent } from './infinite-pagination.component';
import { PaginatedComponent } from './paginated-component.interface';
import { BehaviorSubject } from 'rxjs';
@@ -24,7 +24,6 @@ import {
} from '@angular/core';
import { PaginatedComponent } from './paginated-component.interface';
import { Pagination } from 'alfresco-js-api';
import { Subscription } from 'rxjs';
import { PaginationComponentInterface } from './pagination-component.interface';
import { PaginationModel } from '../models/pagination.model';
@@ -72,7 +71,7 @@ export class InfinitePaginationComponent implements OnInit, OnDestroy, Paginatio
/** Emitted when the "Load More" button is clicked. */
@Output()
loadMore: EventEmitter<Pagination> = new EventEmitter<Pagination>();
loadMore: EventEmitter<PaginationModel> = new EventEmitter<PaginationModel>();
private paginationSubscription: Subscription;
@@ -16,9 +16,9 @@
*/
import { PaginatedComponent } from './paginated-component.interface';
import { Pagination } from 'alfresco-js-api';
import { PaginationModel } from '../models/pagination.model';
export interface PaginationComponentInterface {
target: PaginatedComponent;
pagination: Pagination;
pagination: PaginationModel;
}
@@ -17,7 +17,7 @@
import { NO_ERRORS_SCHEMA } from '@angular/core';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { Pagination } from 'alfresco-js-api';
import { Pagination } from '@alfresco/js-api';
import { PaginationComponent } from './pagination.component';
import { PaginatedComponent } from './public-api';
import { BehaviorSubject } from 'rxjs';
+8 -8
View File
@@ -20,7 +20,7 @@ import {
ChangeDetectorRef, OnDestroy, HostBinding
} from '@angular/core';
import { Pagination } from 'alfresco-js-api';
import { Pagination } from '@alfresco/js-api';
import { PaginatedComponent } from './paginated-component.interface';
import { PaginationComponentInterface } from './pagination-component.interface';
import { Subscription } from 'rxjs';
@@ -37,11 +37,11 @@ import { UserPreferencesService } from '../services/user-preferences.service';
})
export class PaginationComponent implements OnInit, OnDestroy, PaginationComponentInterface {
static DEFAULT_PAGINATION: Pagination = {
static DEFAULT_PAGINATION: Pagination = new Pagination({
skipCount: 0,
maxItems: 25,
totalItems: 0
};
});
static ACTIONS = {
NEXT_PAGE: 'NEXT_PAGE',
@@ -237,22 +237,22 @@ export class PaginationComponent implements OnInit, OnDestroy, PaginationCompone
pagination
} = this;
const data = Object.assign({}, pagination, params);
const paginationModel: PaginationModel = Object.assign({}, pagination, params);
if (action === NEXT_PAGE) {
nextPage.emit(data);
nextPage.emit(paginationModel);
}
if (action === PREV_PAGE) {
prevPage.emit(data);
prevPage.emit(paginationModel);
}
if (action === CHANGE_PAGE_NUMBER) {
changePageNumber.emit(data);
changePageNumber.emit(paginationModel);
}
if (action === CHANGE_PAGE_SIZE) {
changePageSize.emit(data);
changePageSize.emit(paginationModel);
}
change.emit(params);
@@ -15,7 +15,7 @@
* limitations under the License.
*/
import { MinimalNodeEntity } from 'alfresco-js-api';
import { NodeEntry } from '@alfresco/js-api';
import { NodeNameTooltipPipe } from './node-name-tooltip.pipe';
describe('NodeNameTooltipPipe', () => {
@@ -58,7 +58,7 @@ describe('NodeNameTooltipPipe', () => {
name: nodeName
}
};
let tooltip = pipe.transform(<MinimalNodeEntity> node);
let tooltip = pipe.transform(<NodeEntry> node);
expect(tooltip).toBe(nodeName);
});
+3 -3
View File
@@ -16,14 +16,14 @@
*/
import { Pipe, PipeTransform } from '@angular/core';
import { MinimalNodeEntity } from 'alfresco-js-api';
import { NodeEntry } from '@alfresco/js-api';
@Pipe({
name: 'adfNodeNameTooltip'
})
export class NodeNameTooltipPipe implements PipeTransform {
transform(node: MinimalNodeEntity): string {
transform(node: NodeEntry): string {
if (node) {
return this.getNodeTooltip(node);
}
@@ -45,7 +45,7 @@ export class NodeNameTooltipPipe implements PipeTransform {
return lines.reduce(reducer, []);
}
private getNodeTooltip(node: MinimalNodeEntity): string {
private getNodeTooltip(node: NodeEntry): string {
if (!node || !node.entry) {
return null;
}
+2 -2
View File
@@ -26,7 +26,7 @@ export class HighlightPipe implements PipeTransform {
constructor(private highlightTransformService: HighlightTransformService) { }
transform(text: string, search: string): string {
const result: HighlightTransformResult = this.highlightTransformService.highlight(text, search);
return result.text;
const highlightTransformResult: HighlightTransformResult = this.highlightTransformService.highlight(text, search);
return highlightTransformResult.text;
}
}
+3 -3
View File
@@ -29,12 +29,12 @@ export class InitialUsernamePipe implements PipeTransform {
}
transform(user: UserProcessModel | EcmUserModel, className: string = '', delimiter: string = ''): SafeHtml {
let result: SafeHtml = '';
let safeHtml: SafeHtml = '';
if (user) {
let initialResult = this.getInitialUserName(user.firstName, user.lastName, delimiter);
result = this.sanitized.bypassSecurityTrustHtml(`<div id="user-initials-image" class="${className}">${initialResult}</div>`);
safeHtml = this.sanitized.bypassSecurityTrustHtml(`<div id="user-initials-image" class="${className}">${initialResult}</div>`);
}
return result;
return safeHtml;
}
getInitialUserName(firstName: string, lastName: string, delimiter: string) {
+22 -30
View File
@@ -17,21 +17,13 @@
import { Injectable } from '@angular/core';
import {
AlfrescoApi,
ContentApi,
FavoritesApi,
NodesApi,
PeopleApi,
RenditionsApi,
SharedlinksApi,
SitesApi,
VersionsApi,
ClassesApi,
Core,
Activiti,
SearchApi,
GroupsApi,
MinimalNodeEntryEntity
} from 'alfresco-js-api';
import * as alfrescoApi from 'alfresco-js-api';
Node
} from '@alfresco/js-api';
import { AlfrescoApiCompatibility } from '@alfresco/js-api';
import { AppConfigService, AppConfigValues } from '../app-config/app-config.service';
import { StorageService } from './storage.service';
import { Subject } from 'rxjs';
@@ -46,47 +38,47 @@ export class AlfrescoApiService {
/**
* Publish/subscribe to events related to node updates.
*/
nodeUpdated = new Subject<MinimalNodeEntryEntity>();
nodeUpdated = new Subject<Node>();
protected alfrescoApi: AlfrescoApi;
protected alfrescoApi: AlfrescoApiCompatibility;
getInstance(): AlfrescoApi {
getInstance(): AlfrescoApiCompatibility {
return this.alfrescoApi;
}
get taskApi(): alfrescoApi.TaskApi {
get taskApi(): Activiti.TaskApi {
return this.getInstance().activiti.taskApi;
}
get modelsApi(): alfrescoApi.ModelsApi {
return this.getInstance().activiti.modelsApi;
}
// get modelsApi(): Core.ModelsApi {
// return this.getInstance().activiti.modelsApi;
// }
get contentApi(): ContentApi {
return this.getInstance().content;
}
get nodesApi(): NodesApi {
get nodesApi(): Core.NodesApi {
return this.getInstance().nodes;
}
get renditionsApi(): RenditionsApi {
get renditionsApi(): Core.RenditionsApi {
return this.getInstance().core.renditionsApi;
}
get sharedLinksApi(): SharedlinksApi {
get sharedLinksApi(): Core.SharedlinksApi {
return this.getInstance().core.sharedlinksApi;
}
get sitesApi(): SitesApi {
get sitesApi(): Core.SitesApi {
return this.getInstance().core.sitesApi;
}
get favoritesApi(): FavoritesApi {
get favoritesApi(): Core.FavoritesApi {
return this.getInstance().core.favoritesApi;
}
get peopleApi(): PeopleApi {
get peopleApi(): Core.PeopleApi {
return this.getInstance().core.peopleApi;
}
@@ -94,15 +86,15 @@ export class AlfrescoApiService {
return this.getInstance().search.searchApi;
}
get versionsApi(): VersionsApi {
get versionsApi(): Core.VersionsApi {
return this.getInstance().core.versionsApi;
}
get classesApi(): ClassesApi {
get classesApi(): Core.ClassesApi {
return this.getInstance().core.classesApi;
}
get groupsApi(): GroupsApi {
get groupsApi(): Core.GroupsApi {
return this.getInstance().core.groupsApi;
}
@@ -141,7 +133,7 @@ export class AlfrescoApiService {
if (this.alfrescoApi) {
this.alfrescoApi.configureJsApi(config);
} else {
this.alfrescoApi = <AlfrescoApi> new alfrescoApi(config);
this.alfrescoApi = new AlfrescoApiCompatibility(config);
}
}
+1 -1
View File
@@ -16,7 +16,7 @@
*/
import { Injectable } from '@angular/core';
import { AppDefinitionRepresentation } from 'alfresco-js-api';
import { AppDefinitionRepresentation } from '@alfresco/js-api';
import { Observable, from, throwError } from 'rxjs';
import { AlfrescoApiService } from './alfresco-api.service';
import { LogService } from './log.service';
@@ -22,7 +22,7 @@ import { CookieService } from './cookie.service';
import { AppConfigService } from '../app-config/app-config.service';
import { setupTestBed } from '../testing/setupTestBed';
import { CoreTestingModule } from '../testing/core.testing.module';
import { UserRepresentation } from 'alfresco-js-api';
import { UserRepresentation } from '@alfresco/js-api';
declare let jasmine: any;
@@ -54,71 +54,6 @@ describe('AuthenticationService', () => {
jasmine.Ajax.uninstall();
});
describe('remember me', () => {
beforeEach(() => {
appConfigService.config.providers = 'ECM';
appConfigService.load();
apiService.reset();
});
it('[ECM] should save the remember me cookie as a session cookie after successful login', (done) => {
let disposableLogin = authService.login('fake-username', 'fake-password', false).subscribe(() => {
expect(cookie['ALFRESCO_REMEMBER_ME']).not.toBeUndefined();
expect(cookie['ALFRESCO_REMEMBER_ME'].expiration).toBeNull();
disposableLogin.unsubscribe();
done();
});
jasmine.Ajax.requests.mostRecent().respondWith({
'status': 201,
contentType: 'application/json',
responseText: JSON.stringify({ 'entry': { 'id': 'fake-post-ticket', 'userId': 'admin' } })
});
});
it('[ECM] should save the remember me cookie as a persistent cookie after successful login', (done) => {
let disposableLogin = authService.login('fake-username', 'fake-password', true).subscribe(() => {
expect(cookie['ALFRESCO_REMEMBER_ME']).not.toBeUndefined();
expect(cookie['ALFRESCO_REMEMBER_ME'].expiration).not.toBeNull();
disposableLogin.unsubscribe();
done();
});
jasmine.Ajax.requests.mostRecent().respondWith({
'status': 201,
contentType: 'application/json',
responseText: JSON.stringify({ 'entry': { 'id': 'fake-post-ticket', 'userId': 'admin' } })
});
});
it('[ECM] should not save the remember me cookie after failed login', (done) => {
let disposableLogin = authService.login('fake-username', 'fake-password').subscribe(
(res) => {
},
(err: any) => {
expect(cookie['ALFRESCO_REMEMBER_ME']).toBeUndefined();
disposableLogin.unsubscribe();
done();
});
jasmine.Ajax.requests.mostRecent().respondWith({
'status': 403,
contentType: 'application/json',
responseText: JSON.stringify({
'error': {
'errorKey': 'Login failed',
'statusCode': 403,
'briefSummary': '05150009 Login failed',
'stackTrace': 'For security reasons the stack trace is no longer displayed, but the property is kept for previous versions.',
'descriptionURL': 'https://api-explorer.alfresco.com'
}
})
});
});
});
describe('when the setting is ECM', () => {
beforeEach(() => {
@@ -127,17 +62,6 @@ describe('AuthenticationService', () => {
apiService.reset();
});
it('should require remember me set for ECM check', () => {
spyOn(cookie, 'isEnabled').and.returnValue(true);
spyOn(authService, 'isRememberMeSet').and.returnValue(false);
spyOn(authService, 'isECMProvider').and.returnValue(true);
spyOn(authService, 'isOauth').and.returnValue(false);
spyOn(apiService, 'getInstance').and.callThrough();
expect(authService.isEcmLoggedIn()).toBeFalsy();
expect(apiService.getInstance).not.toHaveBeenCalled();
});
it('should not require cookie service enabled for ECM check', () => {
spyOn(cookie, 'isEnabled').and.returnValue(false);
spyOn(authService, 'isRememberMeSet').and.returnValue(false);
@@ -149,6 +73,17 @@ describe('AuthenticationService', () => {
expect(apiService.getInstance).toHaveBeenCalled();
});
it('should require remember me set for ECM check', () => {
spyOn(cookie, 'isEnabled').and.returnValue(true);
spyOn(authService, 'isRememberMeSet').and.returnValue(false);
spyOn(authService, 'isECMProvider').and.returnValue(true);
spyOn(authService, 'isOauth').and.returnValue(false);
spyOn(apiService, 'getInstance').and.callThrough();
expect(authService.isEcmLoggedIn()).toBeFalsy();
expect(apiService.getInstance).not.toHaveBeenCalled();
});
it('[ECM] should return an ECM ticket after the login done', (done) => {
let disposableLogin = authService.login('fake-username', 'fake-password').subscribe(() => {
expect(authService.isLoggedIn()).toBe(true);
@@ -365,6 +300,71 @@ describe('AuthenticationService', () => {
});
});
describe('remember me', () => {
beforeEach(() => {
appConfigService.config.providers = 'ECM';
appConfigService.load();
apiService.reset();
});
it('[ECM] should save the remember me cookie as a session cookie after successful login', (done) => {
let disposableLogin = authService.login('fake-username', 'fake-password', false).subscribe(() => {
expect(cookie['ALFRESCO_REMEMBER_ME']).not.toBeUndefined();
expect(cookie['ALFRESCO_REMEMBER_ME'].expiration).toBeNull();
disposableLogin.unsubscribe();
done();
});
jasmine.Ajax.requests.mostRecent().respondWith({
'status': 201,
contentType: 'application/json',
responseText: JSON.stringify({ 'entry': { 'id': 'fake-post-ticket', 'userId': 'admin' } })
});
});
it('[ECM] should save the remember me cookie as a persistent cookie after successful login', (done) => {
let disposableLogin = authService.login('fake-username', 'fake-password', true).subscribe(() => {
expect(cookie['ALFRESCO_REMEMBER_ME']).not.toBeUndefined();
expect(cookie['ALFRESCO_REMEMBER_ME'].expiration).not.toBeNull();
disposableLogin.unsubscribe();
done();
});
jasmine.Ajax.requests.mostRecent().respondWith({
'status': 201,
contentType: 'application/json',
responseText: JSON.stringify({ 'entry': { 'id': 'fake-post-ticket', 'userId': 'admin' } })
});
});
it('[ECM] should not save the remember me cookie after failed login', (done) => {
let disposableLogin = authService.login('fake-username', 'fake-password').subscribe(
(res) => {
},
(err: any) => {
expect(cookie['ALFRESCO_REMEMBER_ME']).toBeUndefined();
disposableLogin.unsubscribe();
done();
});
jasmine.Ajax.requests.mostRecent().respondWith({
'status': 403,
contentType: 'application/json',
responseText: JSON.stringify({
'error': {
'errorKey': 'Login failed',
'statusCode': 403,
'briefSummary': '05150009 Login failed',
'stackTrace': 'For security reasons the stack trace is no longer displayed, but the property is kept for previous versions.',
'descriptionURL': 'https://api-explorer.alfresco.com'
}
})
});
});
});
describe('when the setting is both ECM and BPM ', () => {
beforeEach(() => {
@@ -402,9 +402,9 @@ describe('AuthenticationService', () => {
},
(err: any) => {
expect(authService.isLoggedIn()).toBe(false, 'isLoggedIn');
expect(authService.getTicketEcm()).toBe(undefined, 'getTicketEcm');
expect(authService.getTicketEcm()).toBe(null, 'getTicketEcm');
// cspell: disable-next
expect(authService.getTicketBpm()).toBe('Basic ZmFrZS11c2VybmFtZTpmYWtlLXBhc3N3b3Jk', 'getTicketBpm');
expect(authService.getTicketBpm()).toBe(null, 'getTicketBpm');
expect(authService.isEcmLoggedIn()).toBe(false, 'isEcmLoggedIn');
disposableLogin.unsubscribe();
done();
@@ -425,8 +425,8 @@ describe('AuthenticationService', () => {
},
(err: any) => {
expect(authService.isLoggedIn()).toBe(false);
expect(authService.getTicketEcm()).toBe('fake-post-ticket');
expect(authService.getTicketBpm()).toBe(undefined);
expect(authService.getTicketEcm()).toBe(null);
expect(authService.getTicketBpm()).toBe(null);
expect(authService.isBpmLoggedIn()).toBe(false);
disposableLogin.unsubscribe();
done();
@@ -449,8 +449,8 @@ describe('AuthenticationService', () => {
},
(err: any) => {
expect(authService.isLoggedIn()).toBe(false);
expect(authService.getTicketEcm()).toBe(undefined);
expect(authService.getTicketBpm()).toBe(undefined);
expect(authService.getTicketEcm()).toBe(null);
expect(authService.getTicketBpm()).toBe(null);
expect(authService.isBpmLoggedIn()).toBe(false);
expect(authService.isEcmLoggedIn()).toBe(false);
disposableLogin.unsubscribe();
+1 -1
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 { UserRepresentation } from '@alfresco/js-api';
import { map, catchError, tap } from 'rxjs/operators';
import { HttpHeaders } from '@angular/common/http';
+18 -8
View File
@@ -39,7 +39,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.apiService.getInstance().activiti.taskApi.addTaskComment({ message: message }, taskId))
.pipe(
map((response: CommentModel) => {
return new CommentModel({
@@ -49,7 +49,7 @@ export class CommentProcessService {
createdBy: response.createdBy
});
}),
catchError((err) => this.handleError(err))
catchError((err: any) => this.handleError(err))
);
}
@@ -65,11 +65,16 @@ export class CommentProcessService {
let comments: CommentModel[] = [];
response.data.forEach((comment: CommentModel) => {
let user = new UserProcessModel(comment.createdBy);
comments.push(new CommentModel({id: comment.id, message: comment.message, created: comment.created, createdBy: user}));
comments.push(new CommentModel({
id: comment.id,
message: comment.message,
created: comment.created,
createdBy: user
}));
});
return comments;
}),
catchError((err) => this.handleError(err))
catchError((err: any) => this.handleError(err))
);
}
@@ -85,11 +90,16 @@ export class CommentProcessService {
let comments: CommentModel[] = [];
response.data.forEach((comment: CommentModel) => {
let user = new UserProcessModel(comment.createdBy);
comments.push(new CommentModel({id: comment.id, message: comment.message, created: comment.created, createdBy: user}));
comments.push(new CommentModel({
id: comment.id,
message: comment.message,
created: comment.created,
createdBy: user
}));
});
return comments;
}),
catchError((err) => this.handleError(err))
catchError((err: any) => this.handleError(err))
);
}
@@ -101,7 +111,7 @@ export class CommentProcessService {
*/
addProcessInstanceComment(processInstanceId: string, message: string): Observable<CommentModel> {
return from(
this.apiService.getInstance().activiti.commentsApi.addProcessInstanceComment({message: message}, processInstanceId)
this.apiService.getInstance().activiti.commentsApi.addProcessInstanceComment({ message: message }, processInstanceId)
).pipe(
map((response: CommentModel) => {
return new CommentModel({
@@ -111,7 +121,7 @@ export class CommentProcessService {
createdBy: response.createdBy
});
}),
catchError((err) => this.handleError(err))
catchError((err: any) => this.handleError(err))
);
}
+9 -8
View File
@@ -29,6 +29,7 @@ import { AlfrescoApiService } from './alfresco-api.service';
import { AlfrescoApiServiceMock } from '../mock/alfresco-api.service.mock';
import { TranslationService } from './translation.service';
import { TranslationMock } from '../mock/translation.service.mock';
import { Node } from '@alfresco/js-api';
declare let jasmine: any;
@@ -92,7 +93,7 @@ describe('ContentService', () => {
jasmine.Ajax.requests.mostRecent().respondWith({
'status': 201,
contentType: 'application/json',
responseText: JSON.stringify({'entry': {'id': 'fake-post-ticket', 'userId': 'admin'}})
responseText: JSON.stringify({ 'entry': { 'id': 'fake-post-ticket', 'userId': 'admin' } })
});
});
@@ -107,33 +108,33 @@ describe('ContentService', () => {
jasmine.Ajax.requests.mostRecent().respondWith({
'status': 201,
contentType: 'application/json',
responseText: JSON.stringify({'entry': {'id': 'fake-post-ticket', 'userId': 'admin'}})
responseText: JSON.stringify({ 'entry': { 'id': 'fake-post-ticket', 'userId': 'admin' } })
});
});
it('should havePermission be false if allowableOperation is not present in the node', () => {
let permissionNode = {};
let permissionNode = new Node({});
expect(contentService.hasPermission(permissionNode, 'create')).toBeFalsy();
});
it('should havePermission be true if allowableOperation is present and you have the permission for the request operation', () => {
let permissionNode = {allowableOperations: ['delete', 'update', 'create', 'updatePermissions']};
let permissionNode = new Node({ allowableOperations: ['delete', 'update', 'create', 'updatePermissions'] });
expect(contentService.hasPermission(permissionNode, 'create')).toBeTruthy();
});
it('should havePermission be false if allowableOperation is present but you don\'t have the permission for the request operation', () => {
let permissionNode = {allowableOperations: ['delete', 'update', 'updatePermissions']};
let permissionNode = new Node({ allowableOperations: ['delete', 'update', 'updatePermissions'] });
expect(contentService.hasPermission(permissionNode, 'create')).toBeFalsy();
});
it('should havePermission works in the opposite way with negate value', () => {
let permissionNode = {allowableOperations: ['delete', 'update', 'updatePermissions']};
let permissionNode = new Node({ allowableOperations: ['delete', 'update', 'updatePermissions'] });
expect(contentService.hasPermission(permissionNode, '!create')).toBeTruthy();
});
it('should havePermission return false id no permission parameter are passed', () => {
let permissionNode = {allowableOperations: ['delete', 'update', 'updatePermissions']};
let permissionNode = new Node({ allowableOperations: ['delete', 'update', 'updatePermissions'] });
expect(contentService.hasPermission(permissionNode, null)).toBeFalsy();
});
@@ -152,7 +153,7 @@ describe('ContentService', () => {
done();
});
let blob = new Blob([''], {type: 'text/html'});
let blob = new Blob([''], { type: 'text/html' });
contentService.downloadBlob(blob, 'test_ie');
});
});
+8 -30
View File
@@ -17,14 +17,14 @@
import { Injectable } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';
import { ContentApi, MinimalNodeEntryEntity, Node, NodeEntry } from 'alfresco-js-api';
import { ContentApi, MinimalNode, Node, NodeEntry } from '@alfresco/js-api';
import { Observable, Subject, from, throwError } from 'rxjs';
import { FolderCreatedEvent } from '../events/folder-created.event';
import { PermissionsEnum } from '../models/permissions.enum';
import { AlfrescoApiService } from './alfresco-api.service';
import { AuthenticationService } from './authentication.service';
import { LogService } from './log.service';
import { catchError, tap } from 'rxjs/operators';
import { catchError } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
@@ -34,8 +34,8 @@ export class ContentService {
private saveData: Function;
folderCreated: Subject<FolderCreatedEvent> = new Subject<FolderCreatedEvent>();
folderCreate: Subject<MinimalNodeEntryEntity> = new Subject<MinimalNodeEntryEntity>();
folderEdit: Subject<MinimalNodeEntryEntity> = new Subject<MinimalNodeEntryEntity>();
folderCreate: Subject<MinimalNode> = new Subject<MinimalNode>();
folderEdit: Subject<MinimalNode> = new Subject<MinimalNode>();
constructor(public authService: AuthenticationService,
public apiService: AlfrescoApiService,
@@ -46,15 +46,15 @@ export class ContentService {
document.body.appendChild(a);
a.style.display = 'none';
return function (data, format, fileName) {
return function (fileData, format, fileName) {
let blob = null;
if (format === 'blob' || format === 'data') {
blob = new Blob([data], { type: 'octet/stream' });
blob = new Blob([fileData], { type: 'octet/stream' });
}
if (format === 'object' || format === 'json') {
let json = JSON.stringify(data);
let json = JSON.stringify(fileData);
blob = new Blob([json], { type: 'octet/stream' });
}
@@ -157,29 +157,7 @@ export class ContentService {
getNodeContent(nodeId: string): Observable<any> {
return from(this.apiService.getInstance().core.nodesApi.getFileContent(nodeId))
.pipe(
catchError((err) => this.handleError(err))
);
}
/**
* Creates a folder.
* @param relativePath Location to create the folder
* @param name Folder name
* @param parentId Node ID of parent folder
* @returns Information about the new folder
*/
createFolder(relativePath: string, name: string, parentId?: string): Observable<NodeEntry> {
return from(this.apiService.getInstance().nodes.createFolder(name, relativePath, parentId))
.pipe(
tap((data) => {
this.folderCreated.next(<FolderCreatedEvent> {
relativePath: relativePath,
name: name,
parentId: parentId,
node: data
});
}),
catchError((err) => this.handleError(err))
catchError((err: any) => this.handleError(err))
);
}
@@ -18,7 +18,7 @@
import { Injectable } from '@angular/core';
import { Observable, from, of } from 'rxjs';
import { NodePaging } from 'alfresco-js-api';
import { NodePaging } from '@alfresco/js-api';
import { AlfrescoApiService } from './alfresco-api.service';
import { UserPreferencesService } from './user-preferences.service';
import { catchError } from 'rxjs/operators';
+1 -1
View File
@@ -15,7 +15,7 @@
* limitations under the License.
*/
import { NodeEntry, DownloadEntry, DownloadBodyCreate } from 'alfresco-js-api';
import { NodeEntry, DownloadEntry, DownloadBodyCreate } from '@alfresco/js-api';
import { Injectable } from '@angular/core';
import { Observable, from, throwError } from 'rxjs';
import { LogService } from './log.service';
@@ -17,11 +17,10 @@
import { Injectable } from '@angular/core';
import {
AlfrescoApi,
AlfrescoApiCompatibility,
ContentApi,
NodesApi
} from 'alfresco-js-api';
import * as alfrescoApi from 'alfresco-js-api';
Core
} from '@alfresco/js-api';
/* tslint:disable:adf-file-name */
@Injectable({
@@ -29,9 +28,9 @@ import * as alfrescoApi from 'alfresco-js-api';
})
export class ExternalAlfrescoApiService {
protected alfrescoApi: AlfrescoApi;
protected alfrescoApi: AlfrescoApiCompatibility;
getInstance(): AlfrescoApi {
getInstance(): AlfrescoApiCompatibility {
return this.alfrescoApi;
}
@@ -39,7 +38,7 @@ export class ExternalAlfrescoApiService {
return this.getInstance().content;
}
get nodesApi(): NodesApi {
get nodesApi(): Core.NodesApi {
return this.getInstance().nodes;
}
@@ -61,7 +60,7 @@ export class ExternalAlfrescoApiService {
if (this.alfrescoApi) {
this.alfrescoApi.configureJsApi(config);
} else {
this.alfrescoApi = <AlfrescoApi> new alfrescoApi(config);
this.alfrescoApi = new AlfrescoApiCompatibility(config);
}
}
+1 -1
View File
@@ -16,7 +16,7 @@
*/
import { Injectable } from '@angular/core';
import { NodePaging } from 'alfresco-js-api';
import { NodePaging } from '@alfresco/js-api';
import { Observable, from, of } from 'rxjs';
import { AlfrescoApiService } from './alfresco-api.service';
import { UserPreferencesService } from './user-preferences.service';
+7 -7
View File
@@ -16,7 +16,7 @@
*/
import { Injectable } from '@angular/core';
import { MinimalNodeEntity, MinimalNodeEntryEntity, NodePaging } from 'alfresco-js-api';
import { NodeEntry, MinimalNode, NodePaging } from '@alfresco/js-api';
import { Observable, from, throwError } from 'rxjs';
import { AlfrescoApiService } from './alfresco-api.service';
import { UserPreferencesService } from './user-preferences.service';
@@ -35,7 +35,7 @@ export class NodesApiService {
return this.api.getInstance().core.nodesApi;
}
private getEntryFromEntity(entity: MinimalNodeEntity) {
private getEntryFromEntity(entity: NodeEntry) {
return entity.entry;
}
@@ -45,7 +45,7 @@ export class NodesApiService {
* @param options Optional parameters supported by JS-API
* @returns Node information
*/
getNode(nodeId: string, options: any = {}): Observable<MinimalNodeEntryEntity> {
getNode(nodeId: string, options: any = {}): Observable<MinimalNode> {
const defaults = {
include: [ 'path', 'properties', 'allowableOperations', 'permissions' ]
};
@@ -87,7 +87,7 @@ export class NodesApiService {
* @param options Optional parameters supported by JS-API
* @returns Details of the new node
*/
createNode(parentNodeId: string, nodeBody: any, options: any = {}): Observable<MinimalNodeEntryEntity> {
createNode(parentNodeId: string, nodeBody: any, options: any = {}): Observable<MinimalNode> {
const promise = this.nodesApi
.addNode(parentNodeId, nodeBody, options)
.then(this.getEntryFromEntity);
@@ -104,7 +104,7 @@ export class NodesApiService {
* @param options Optional parameters supported by JS-API
* @returns Details of the new folder
*/
createFolder(parentNodeId: string, nodeBody: any, options: any = {}): Observable<MinimalNodeEntryEntity> {
createFolder(parentNodeId: string, nodeBody: any, options: any = {}): Observable<MinimalNode> {
const body = Object.assign({ nodeType: 'cm:folder' }, nodeBody);
return this.createNode(parentNodeId, body, options);
}
@@ -116,7 +116,7 @@ export class NodesApiService {
* @param options Optional parameters supported by JS-API
* @returns Updated node information
*/
updateNode(nodeId: string, nodeBody: any, options: any = {}): Observable<MinimalNodeEntryEntity> {
updateNode(nodeId: string, nodeBody: any, options: any = {}): Observable<MinimalNode> {
const defaults = {
include: [ 'path', 'properties', 'allowableOperations', 'permissions' ]
};
@@ -150,7 +150,7 @@ export class NodesApiService {
* @param nodeId ID of the node to restore
* @returns Details of the restored node
*/
restoreNode(nodeId: string): Observable<MinimalNodeEntryEntity> {
restoreNode(nodeId: string): Observable<MinimalNode> {
const promise = this.nodesApi
.restoreNode(nodeId)
.then(this.getEntryFromEntity);
+1 -2
View File
@@ -16,7 +16,6 @@
*/
import { Injectable } from '@angular/core';
import { Response } from '@angular/http';
import { Observable, from, throwError } from 'rxjs';
import { UserProcessModel } from '../models/user-process.model';
import { AlfrescoApiService } from './alfresco-api.service';
@@ -104,7 +103,7 @@ export class PeopleProcessService {
* Throw the error
* @param error
*/
private handleError(error: Response) {
private handleError(error: any) {
this.logService.error(error);
return throwError(error || 'Server error');
}
+1 -1
View File
@@ -22,7 +22,7 @@ import { setupTestBed } from '../testing/setupTestBed';
import { CoreModule } from '../core.module';
import { AlfrescoApiService } from './alfresco-api.service';
import { AlfrescoApiServiceMock } from '../mock/alfresco-api.service.mock';
import { RenditionEntry } from 'alfresco-js-api';
import { RenditionEntry } from '@alfresco/js-api';
declare let jasmine: any;
+4 -4
View File
@@ -16,7 +16,7 @@
*/
import { Injectable } from '@angular/core';
import { RenditionEntry, RenditionPaging } from 'alfresco-js-api';
import { RenditionEntry, RenditionPaging } 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';
@@ -104,7 +104,7 @@ export class RenditionsService {
/** @deprecated */
createRendition(nodeId: string, encoding: string): Observable<{}> {
return from(this.apiService.renditionsApi.createRendition(nodeId, {id: encoding}));
return from(this.apiService.renditionsApi.createRendition(nodeId, { id: encoding }));
}
/** @deprecated */
@@ -121,12 +121,12 @@ export class RenditionsService {
return interval(intervalSize)
.pipe(
switchMap(() => this.getRendition(nodeId, encoding)),
takeWhile((data) => {
takeWhile((renditionEntry: RenditionEntry) => {
attempts += 1;
if (attempts > retries) {
return false;
}
return (data.entry.status.toString() !== 'CREATED');
return (renditionEntry.entry.status.toString() !== 'CREATED');
})
);
}
@@ -16,7 +16,7 @@
*/
import { Injectable } from '@angular/core';
import { QueryBody } from 'alfresco-js-api';
import { QueryBody } from '@alfresco/js-api';
import { SearchConfigurationInterface } from '../interface/search-configuration.interface';
@Injectable({
+8 -8
View File
@@ -16,7 +16,7 @@
*/
import { Injectable } from '@angular/core';
import { NodePaging, QueryBody } from 'alfresco-js-api';
import { NodePaging, QueryBody } from '@alfresco/js-api';
import { Observable, Subject, from, throwError } from 'rxjs';
import { AlfrescoApiService } from './alfresco-api.service';
import { SearchConfigurationService } from './search-configuration.service';
@@ -42,8 +42,8 @@ export class SearchService {
getNodeQueryResults(term: string, options?: SearchOptions): Observable<NodePaging> {
const promise = this.apiService.getInstance().core.queriesApi.findNodes(term, options);
promise.then((data: any) => {
this.dataLoaded.next(data);
promise.then((nodePaging: NodePaging) => {
this.dataLoaded.next(nodePaging);
});
return from(promise).pipe(
@@ -62,8 +62,8 @@ export class SearchService {
const searchQuery = Object.assign(this.searchConfigurationService.generateQueryBody(searchTerm, maxResults, skipCount));
const promise = this.apiService.getInstance().search.searchApi.search(searchQuery);
promise.then((data: any) => {
this.dataLoaded.next(data);
promise.then((nodePaging: NodePaging) => {
this.dataLoaded.next(nodePaging);
});
return from(promise).pipe(
@@ -79,12 +79,12 @@ export class SearchService {
searchByQueryBody(queryBody: QueryBody): Observable<NodePaging> {
const promise = this.apiService.getInstance().search.searchApi.search(queryBody);
promise.then((data: any) => {
this.dataLoaded.next(data);
promise.then((nodePaging: NodePaging) => {
this.dataLoaded.next(nodePaging);
});
return from(promise).pipe(
catchError((err) => this.handleError(err))
catchError((err: any) => this.handleError(err))
);
}
@@ -16,7 +16,7 @@
*/
import { Injectable } from '@angular/core';
import { NodePaging, SharedLinkEntry } from 'alfresco-js-api';
import { NodePaging, SharedLinkEntry } from '@alfresco/js-api';
import { Observable, from, of } from 'rxjs';
import { AlfrescoApiService } from './alfresco-api.service';
import { UserPreferencesService } from './user-preferences.service';
+10 -10
View File
@@ -16,10 +16,9 @@
*/
import { Injectable } from '@angular/core';
import { Response } from '@angular/http';
import { Observable, from, throwError } from 'rxjs';
import { AlfrescoApiService } from './alfresco-api.service';
import { SitePaging, SiteEntry } from 'alfresco-js-api';
import { SitePaging, SiteEntry } from '@alfresco/js-api';
import { catchError } from 'rxjs/operators';
@Injectable({
@@ -28,7 +27,8 @@ import { catchError } from 'rxjs/operators';
export class SitesService {
constructor(
private apiService: AlfrescoApiService) { }
private apiService: AlfrescoApiService) {
}
/**
* Gets a list of all sites in the repository.
@@ -43,7 +43,7 @@ export class SitesService {
const queryOptions = Object.assign({}, defaultOptions, opts);
return from(this.apiService.getInstance().core.sitesApi.getSites(queryOptions))
.pipe(
catchError((err) => this.handleError(err))
catchError((err: any) => this.handleError(err))
);
}
@@ -53,10 +53,10 @@ export class SitesService {
* @param opts Options supported by JS-API
* @returns Information about the site
*/
getSite(siteId: string, opts?: any): Observable<SiteEntry> {
getSite(siteId: string, opts?: any): Observable<SiteEntry | {}> {
return from(this.apiService.getInstance().core.sitesApi.getSite(siteId, opts))
.pipe(
catchError((err) => this.handleError(err))
catchError((err: any) => this.handleError(err))
);
}
@@ -71,7 +71,7 @@ export class SitesService {
options.permanent = permanentFlag;
return from(this.apiService.getInstance().core.sitesApi.deleteSite(siteId, options))
.pipe(
catchError((err) => this.handleError(err))
catchError((err: any) => this.handleError(err))
);
}
@@ -80,7 +80,7 @@ export class SitesService {
* @param siteId ID of the target site
* @returns Site content
*/
getSiteContent(siteId: string): Observable<SiteEntry> {
getSiteContent(siteId: string): Observable<SiteEntry | {}> {
return this.getSite(siteId, { relations: ['containers'] });
}
@@ -89,7 +89,7 @@ export class SitesService {
* @param siteId ID of the target site
* @returns Site members
*/
getSiteMembers(siteId: string): Observable<SiteEntry> {
getSiteMembers(siteId: string): Observable<SiteEntry | {}> {
return this.getSite(siteId, { relations: ['members'] });
}
@@ -101,7 +101,7 @@ export class SitesService {
return this.apiService.getInstance().getEcmUsername();
}
private handleError(error: Response): any {
private handleError(error: any): any {
console.error(error);
return throwError(error || 'Server error');
}
+18 -29
View File
@@ -25,6 +25,7 @@ import { AlfrescoApiService } from './alfresco-api.service';
import { setupTestBed } from '../testing/setupTestBed';
import { CoreTestingModule } from '../testing/core.testing.module';
import { AssocChildBody, AssociationBody } from '@alfresco/js-api';
declare let jasmine: any;
@@ -162,17 +163,6 @@ describe('UploadService', () => {
service.cancelUpload(...file);
});
it('If versioning is true autoRename should not be present and majorVersion should be a param', () => {
let emitter = new EventEmitter();
const filesFake = new FileModel(<File> { name: 'fake-name', size: 10 }, { newVersion: true });
service.addToQueue(filesFake);
service.uploadFilesInTheQueue(emitter);
expect(jasmine.Ajax.requests.mostRecent().url.endsWith('autoRename=true')).toBe(false);
expect(jasmine.Ajax.requests.mostRecent().params.has('majorVersion')).toBe(false);
});
it('If newVersion is set, name should be a param', () => {
let uploadFileSpy = spyOn(alfrescoApiService.getInstance().upload, 'uploadFile').and.callThrough();
@@ -189,7 +179,7 @@ describe('UploadService', () => {
size: 10
}, undefined, undefined, { newVersion: true }, {
renditions: 'doclib',
include: [ 'allowableOperations' ],
include: ['allowableOperations'],
overwrite: true,
majorVersion: undefined,
comment: undefined,
@@ -229,12 +219,12 @@ describe('UploadService', () => {
let filesFake = new FileModel(
<File> { name: 'fake-name', size: 10 },
<FileUploadOptions> { parentId: '123', path: 'fake-dir',
secondaryChildren: [{ assocType: 'assoc-1', childId: 'child-id' }],
association: { assocType: 'fake-assoc' },
targets: [{ assocType: 'target-assoc', targetId: 'fake-target-id' }]
}
);
<FileUploadOptions> {
parentId: '123', path: 'fake-dir',
secondaryChildren: [<AssocChildBody> { assocType: 'assoc-1', childId: 'child-id' }],
association: { assocType: 'fake-assoc' },
targets: [<AssociationBody> { assocType: 'target-assoc', targetId: 'fake-target-id' }]
});
service.addToQueue(filesFake);
service.uploadFilesInTheQueue(emitter);
@@ -243,17 +233,16 @@ describe('UploadService', () => {
size: 10
}, 'fake-dir', '123', {
newVersion: false,
parentId: '123',
path: 'fake-dir',
secondaryChildren: [
{ assocType: 'assoc-1', childId: 'child-id' }],
association: { assocType: 'fake-assoc' },
targets: [{ assocType: 'target-assoc', targetId: 'fake-target-id' }]
}, {
renditions: 'doclib',
include: ['allowableOperations'],
autoRename: true
});
parentId: '123',
path: 'fake-dir',
secondaryChildren: [<AssocChildBody> { assocType: 'assoc-1', childId: 'child-id' }],
association: { assocType: 'fake-assoc' },
targets: [<AssociationBody> { assocType: 'target-assoc', targetId: 'fake-target-id' }]
}, {
renditions: 'doclib',
include: ['allowableOperations'],
autoRename: true
});
});
it('should start downloading the next one if a file of the list is aborted', (done) => {
+2 -5
View File
@@ -161,7 +161,7 @@ export class UploadService {
* @param file The target file
* @returns Promise that is resolved if the upload is successful or error otherwise
*/
getUploadPromise(file: FileModel) {
getUploadPromise(file: FileModel): any {
let opts: any = {
renditions: 'doclib',
include: ['allowableOperations']
@@ -181,9 +181,7 @@ export class UploadService {
}
if (file.id) {
return this.apiService.getInstance().upload.updateFile(
file.file,
file.options.path,
return this.apiService.getInstance().node.updateNodeContent(
file.id,
file.file,
opts
@@ -225,7 +223,6 @@ export class UploadService {
}
})
.catch((err) => {
throw err;
});
return promise;
+23 -23
View File
@@ -15,7 +15,7 @@
* limitations under the License.
*/
import { UserRepresentation } from 'alfresco-js-api';
import { UserRepresentation } from '@alfresco/js-api';
export class BpmUserModel implements UserRepresentation {
apps: any;
@@ -39,28 +39,28 @@ export class BpmUserModel implements UserRepresentation {
tenantPictureId: number;
type: string;
constructor(obj?: any) {
if (obj) {
this.apps = obj.apps;
this.capabilities = obj.capabilities;
this.company = obj.company;
this.created = obj.created;
this.email = obj.email;
this.externalId = obj.externalId;
this.firstName = obj.firstName;
this.lastName = obj.lastName;
this.fullname = obj.fullname;
this.groups = obj.groups;
this.id = obj.id;
this.lastUpdate = obj.lastUpdate;
this.latestSyncTimeStamp = obj.latestSyncTimeStamp;
this.password = obj.password;
this.pictureId = obj.pictureId;
this.status = obj.status;
this.tenantId = obj.tenantId;
this.tenantName = obj.tenantName;
this.tenantPictureId = obj.tenantPictureId;
this.type = obj.type;
constructor(input?: any) {
if (input) {
this.apps = input.apps;
this.capabilities = input.capabilities;
this.company = input.company;
this.created = input.created;
this.email = input.email;
this.externalId = input.externalId;
this.firstName = input.firstName;
this.lastName = input.lastName;
this.fullname = input.fullname;
this.groups = input.groups;
this.id = input.id;
this.lastUpdate = input.lastUpdate;
this.latestSyncTimeStamp = input.latestSyncTimeStamp;
this.password = input.password;
this.pictureId = input.pictureId;
this.status = input.status;
this.tenantId = input.tenantId;
this.tenantName = input.tenantName;
this.tenantPictureId = input.tenantPictureId;
this.type = input.type;
}
}
}
+1 -1
View File
@@ -15,7 +15,7 @@
* limitations under the License.
*/
import { Person } from 'alfresco-js-api';
import { Person } from '@alfresco/js-api';
import { EcmCompanyModel } from '../../models/ecm-company.model';
export class EcmUserModel implements Person {
@@ -16,13 +16,12 @@
*/
import { Injectable } from '@angular/core';
import { Response } from '@angular/http';
import { Observable, from, throwError } from 'rxjs';
import { AlfrescoApiService } from '../../services/alfresco-api.service';
import { LogService } from '../../services/log.service';
import { BpmUserModel } from '../models/bpm-user.model';
import { map, catchError } from 'rxjs/operators';
import { UserRepresentation } from 'alfresco-js-api';
import { UserRepresentation } from '@alfresco/js-api';
/**
*
@@ -45,8 +44,8 @@ export class BpmUserService {
getCurrentUserInfo(): Observable<BpmUserModel> {
return from(this.apiService.getInstance().activiti.profileApi.getProfile())
.pipe(
map((data: UserRepresentation) => {
return new BpmUserModel(data);
map((userRepresentation: UserRepresentation) => {
return new BpmUserModel(userRepresentation);
}),
catchError((err) => this.handleError(err))
);
@@ -64,7 +63,7 @@ export class BpmUserService {
* Throw the error
* @param error
*/
private handleError(error: Response) {
private handleError(error: any) {
// in a real world app, we may send the error to some remote logging infrastructure
// instead of just logging it to the console
this.logService.error(error);
@@ -16,14 +16,13 @@
*/
import { Injectable } from '@angular/core';
import { Response } from '@angular/http';
import { Observable, from, throwError } from 'rxjs';
import { map, catchError } from 'rxjs/operators';
import { ContentService } from '../../services/content.service';
import { AlfrescoApiService } from '../../services/alfresco-api.service';
import { LogService } from '../../services/log.service';
import { EcmUserModel } from '../models/ecm-user.model';
import { PersonEntry } from 'alfresco-js-api';
import { PersonEntry } from '@alfresco/js-api';
@Injectable({
providedIn: 'root'
@@ -74,7 +73,7 @@ export class EcmUserService {
* Throw the error
* @param error
*/
private handleError(error: Response) {
private handleError(error: any) {
this.logService.error(error);
return throwError(error || 'Server error');
}
@@ -69,7 +69,7 @@ export class IdentityUserService {
return from(this.apiService.getInstance().oauth2Auth.callCustomApi(
url, httpMethod, pathParams, queryParams,
headerParams, formParams, bodyParam, authNames,
contentTypes, accepts, Object, null, null)
contentTypes, accepts, null, null)
).pipe(
map((response: IdentityUserModel[]) => {
return response;
@@ -85,7 +85,7 @@ export class IdentityUserService {
return from(this.apiService.getInstance().oauth2Auth.callCustomApi(
url, httpMethod, pathParams, queryParams,
headerParams, formParams, bodyParam, authNames,
contentTypes, accepts, Object, null, null)
contentTypes, accepts, null, null)
).pipe(
map((response: IdentityRoleModel[]) => {
return response;
@@ -20,12 +20,12 @@
</ng-container>
<div class="adf-pdf-viewer__content">
<div id="viewer-pdf-viewer" class="adf-viewer-pdf-viewer" (window:resize)="onResize()">
<div id="viewer-viewerPdf" class="adf-pdfViewer">
<div [id]="randomPdfId+'-viewer-pdf-viewer'" class="adf-viewer-pdf-viewer" (window:resize)="onResize()">
<div [id]="randomPdfId+'-viewer-viewerPdf'" class="adf-pdfViewer">
<div id="loader-container" class="adf-loader-container">
<div class="adf-loader-item">
<mat-progress-bar mode="indeterminate"></mat-progress-bar>
</div >
</div>
</div>
</div>
</div>
@@ -90,6 +90,7 @@ export class PdfViewerComponent implements OnChanges, OnDestroy {
isPanelDisabled = true;
showThumbnails: boolean = false;
pdfThumbnailsContext: { viewer: any } = { viewer: null };
randomPdfId: string;
get currentScaleText(): string {
return Math.round(this.currentScale * 100) + '%';
@@ -103,6 +104,7 @@ export class PdfViewerComponent implements OnChanges, OnDestroy {
this.onPageChange = this.onPageChange.bind(this);
this.onPagesLoaded = this.onPagesLoaded.bind(this);
this.onPageRendered = this.onPageRendered.bind(this);
this.randomPdfId = this.generateUuid();
}
ngOnChanges(changes) {
@@ -159,8 +161,8 @@ export class PdfViewerComponent implements OnChanges, OnDestroy {
}
initPDFViewer(pdfDocument: any) {
const viewer: any = document.getElementById('viewer-viewerPdf');
const container = document.getElementById('viewer-pdf-viewer');
const viewer: any = document.getElementById(`${this.randomPdfId}-viewer-viewerPdf`);
const container = document.getElementById(`${this.randomPdfId}-viewer-pdf-viewer`);
if (viewer && container) {
this.documentContainer = container;
@@ -197,7 +199,8 @@ export class PdfViewerComponent implements OnChanges, OnDestroy {
if (this.loadingTask) {
try {
this.loadingTask.destroy();
} catch {}
} catch {
}
this.loadingTask = null;
}
@@ -217,8 +220,8 @@ export class PdfViewerComponent implements OnChanges, OnDestroy {
if (this.pdfViewer) {
let viewerContainer = document.getElementById('viewer-main-container');
let documentContainer = document.getElementById('viewer-pdf-viewer');
let viewerContainer = document.getElementById(`${this.randomPdfId}-viewer-main-container`);
let documentContainer = document.getElementById(`${this.randomPdfId}-viewer-pdf-viewer`);
let widthContainer;
let heightContainer;
@@ -453,4 +456,11 @@ export class PdfViewerComponent implements OnChanges, OnDestroy {
this.previousPage();
}
}
private generateUuid() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
let r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}
}
@@ -90,16 +90,6 @@
<mat-icon>print</mat-icon>
</button>
<button
id="adf-viewer-share"
*ngIf="allowShare"
mat-icon-button
title="{{ 'ADF_VIEWER.ACTIONS.SHARE' | translate }}"
data-automation-id="adf-toolbar-share"
(click)="shareContent()">
<mat-icon>share</mat-icon>
</button>
<button
id="adf-viewer-fullscreen"
*ngIf="viewerType !== 'media' && allowFullScreen"
@@ -29,6 +29,7 @@ import { RenderingQueueServices } from '../services/rendering-queue.services';
import { ViewerComponent } from './viewer.component';
import { setupTestBed } from '../../testing/setupTestBed';
import { AlfrescoApiServiceMock } from '../../mock/alfresco-api.service.mock';
import { NodeEntry } from '@alfresco/js-api';
@Component({
selector: 'adf-viewer-container-toolbar',
@@ -352,7 +353,7 @@ describe('ViewerComponent', () => {
content: { getContentUrl: () => contentUrl }
};
component.fileNodeId = '12';
component.nodeId = '12';
component.urlFile = null;
component.displayName = null;
spyOn(alfrescoApiService, 'getInstance').and.returnValue(alfrescoApiInstanceMock);
@@ -368,30 +369,26 @@ describe('ViewerComponent', () => {
});
it('should change display name every time node changes', fakeAsync(() => {
spyOn(alfrescoApiService.nodesApi, 'getNodeInfo').and.returnValues(
Promise.resolve({ name: 'file1', content: {} }),
Promise.resolve({ name: 'file2', content: {} })
spyOn(alfrescoApiService.nodesApi, 'getNode').and.returnValues(
Promise.resolve(new NodeEntry({ entry: { name: 'file1', content: {} } })),
Promise.resolve(new NodeEntry({ entry: { name: 'file2', content: {} } }))
);
spyOn(alfrescoApiService.nodesApi, 'getNode').and.returnValue(Promise.resolve({ id: 'fake-node' }));
component.urlFile = null;
component.displayName = null;
component.blobFile = null;
component.showViewer = true;
component.fileNodeId = 'id1';
component.nodeId = 'id1';
component.ngOnChanges({});
tick();
expect(alfrescoApiService.nodesApi.getNodeInfo).toHaveBeenCalledWith('id1', { include: ['allowableOperations'] });
expect(component.fileTitle).toBe('file1');
component.fileNodeId = 'id2';
component.nodeId = 'id2';
component.ngOnChanges({});
tick();
expect(alfrescoApiService.nodesApi.getNodeInfo).toHaveBeenCalledWith('id2', { include: ['allowableOperations'] });
expect(component.fileTitle).toBe('file2');
}));
@@ -602,57 +599,9 @@ describe('ViewerComponent', () => {
button.click();
});
it('should render default share button', (done) => {
component.allowShare = true;
fixture.detectChanges();
fixture.whenStable().then(() => {
expect(element.querySelector('[data-automation-id="adf-toolbar-share"]')).toBeDefined();
done();
});
});
it('should not render default share button', (done) => {
component.allowShare = false;
fixture.detectChanges();
fixture.whenStable().then(() => {
expect(element.querySelector('[data-automation-id="adf-toolbar-share"]')).toBeNull();
done();
});
});
it('should invoke share action with the toolbar button', (done) => {
component.allowShare = true;
fixture.detectChanges();
spyOn(component, 'shareContent').and.stub();
const button: HTMLButtonElement = element.querySelector('[data-automation-id="adf-toolbar-share"]') as HTMLButtonElement;
button.click();
fixture.whenStable().then(() => {
expect(component.shareContent).toHaveBeenCalled();
done();
});
});
it('should raise share event with the toolbar button', (done) => {
component.allowShare = true;
fixture.detectChanges();
component.share.subscribe((e) => {
expect(e).not.toBeNull();
done();
});
const button: HTMLButtonElement = element.querySelector('[data-automation-id="adf-toolbar-share"]') as HTMLButtonElement;
button.click();
});
it('should get and assign node for download', (done) => {
const node = { id: 'fake-node' };
component.fileNodeId = '12';
component.nodeId = '12';
component.urlFile = '';
const displayName = 'the-name';
const nodeDetails = { name: displayName, id: '12', content: { mimeType: 'txt' } };
@@ -751,9 +700,9 @@ describe('ViewerComponent', () => {
describe('Attribute', () => {
it('should Url or fileNodeId be mandatory', () => {
it('should Url or nodeId be mandatory', () => {
component.showViewer = true;
component.fileNodeId = undefined;
component.nodeId = undefined;
component.urlFile = undefined;
expect(() => {
@@ -763,7 +712,7 @@ describe('ViewerComponent', () => {
it('should FileNodeId present not thrown any error ', () => {
component.showViewer = true;
component.fileNodeId = 'file-node-id';
component.nodeId = 'file-node-id';
component.urlFile = undefined;
expect(() => {
@@ -773,7 +722,7 @@ describe('ViewerComponent', () => {
it('should urlFile present not thrown any error ', () => {
component.showViewer = true;
component.fileNodeId = undefined;
component.nodeId = undefined;
expect(() => {
component.ngOnChanges(null);
@@ -795,7 +744,7 @@ describe('ViewerComponent', () => {
describe('error handling', () => {
it('should show unknown view when node file not found', (done) => {
spyOn(alfrescoApiService.getInstance().nodes, 'getNodeInfo')
spyOn(alfrescoApiService.getInstance().nodes, 'getNode')
.and.returnValue(Promise.reject({}));
component.nodeId = 'the-node-id-of-the-file-to-preview';
@@ -920,18 +869,17 @@ describe('ViewerComponent', () => {
describe('display name property override by nodeId', () => {
const displayName = 'the-name';
const nodeDetails = { name: displayName, id: '12', content: { mimeType: 'txt' } };
const nodeDetails = new NodeEntry({ entry: { name: displayName, id: '12', content: { mimeType: 'txt' } } });
const contentUrl = '/content/url/path';
const alfrescoApiInstanceMock = {
nodes: {
getNodeInfo: () => Promise.resolve(nodeDetails),
getNode: () => Promise.resolve({ id: 'fake-node' })
getNode: () => Promise.resolve(nodeDetails)
},
content: { getContentUrl: () => contentUrl }
};
it('should use the node name if displayName is NOT set and fileNodeId is set', (done) => {
component.fileNodeId = '12';
it('should use the node name if displayName is NOT set and nodeId is set', (done) => {
component.nodeId = '12';
component.urlFile = null;
component.displayName = null;
spyOn(alfrescoApiService, 'getInstance').and.returnValue(alfrescoApiInstanceMock);
+32 -64
View File
@@ -21,7 +21,7 @@ import {
Input, OnChanges, Output, SimpleChanges, TemplateRef,
ViewEncapsulation, OnInit, OnDestroy
} from '@angular/core';
import { MinimalNodeEntryEntity, RenditionEntry, MinimalNodeEntity } from 'alfresco-js-api';
import { RenditionPaging, SharedLinkEntry, Node, RenditionEntry, NodeEntry } from '@alfresco/js-api';
import { BaseEvent } from '../../events';
import { AlfrescoApiService } from '../../services/alfresco-api.service';
import { LogService } from '../../services/log.service';
@@ -69,15 +69,6 @@ export class ViewerComponent implements OnChanges, OnInit, OnDestroy {
@Input()
blobFile: Blob;
/**
* Node Id of the file to load.
* @deprecated 2.4.0 use nodeId
*/
@Input()
set fileNodeId(nodeId: string) {
this.nodeId = nodeId;
}
/** Node Id of the file to load. */
@Input()
nodeId: string = null;
@@ -116,13 +107,6 @@ export class ViewerComponent implements OnChanges, OnInit, OnDestroy {
@Input()
allowPrint = false;
/**
* Toggles sharing.
* @deprecated 2.5.0 - inject the share button directive as custom button
*/
@Input()
allowShare = false;
/** Toggles the 'Full Screen' feature. */
@Input()
allowFullScreen = true;
@@ -210,10 +194,6 @@ export class ViewerComponent implements OnChanges, OnInit, OnDestroy {
@Output()
print = new EventEmitter<BaseEvent<any>>();
/** Emitted when user clicks the 'Share' button. */
@Output()
share = new EventEmitter<BaseEvent<any>>();
/** Emitted when the viewer is shown or hidden. */
@Output()
showViewerChange = new EventEmitter<boolean>();
@@ -236,15 +216,15 @@ export class ViewerComponent implements OnChanges, OnInit, OnDestroy {
viewerType = 'unknown';
isLoading = false;
node: MinimalNodeEntity;
node: NodeEntry;
extensionTemplates: { template: TemplateRef<any>, isVisible: boolean }[] = [];
externalExtensions: string[] = [];
urlFileContent: string;
otherMenu: any;
extension: string;
sidebarTemplateContext: { node: MinimalNodeEntryEntity } = { node: null };
sidebarLeftTemplateContext: { node: MinimalNodeEntryEntity } = { node: null };
sidebarTemplateContext: { node: Node } = { node: null };
sidebarLeftTemplateContext: { node: Node } = { node: null };
fileTitle: string;
private cacheBusterNumber;
@@ -289,7 +269,7 @@ export class ViewerComponent implements OnChanges, OnInit, OnDestroy {
this.subscriptions = [];
}
private onNodeUpdated(node: MinimalNodeEntryEntity) {
private onNodeUpdated(node: Node) {
if (node && node.id === this.nodeId) {
this.generateCacheBusterNumber();
this.isLoading = true;
@@ -313,9 +293,10 @@ export class ViewerComponent implements OnChanges, OnInit, OnDestroy {
this.setUpUrlFile();
this.isLoading = false;
} else if (this.nodeId) {
this.apiService.nodesApi.getNodeInfo(this.nodeId, { include: ['allowableOperations'] }).then(
(data: MinimalNodeEntryEntity) => {
this.setUpNodeFile(data).then(() => {
this.apiService.nodesApi.getNode(this.nodeId, { include: ['allowableOperations'] }).then(
(node: NodeEntry) => {
this.node = node;
this.setUpNodeFile(node.entry).then(() => {
this.isLoading = false;
});
},
@@ -324,17 +305,11 @@ export class ViewerComponent implements OnChanges, OnInit, OnDestroy {
this.logService.error('This node does not exist');
}
);
this.apiService.nodesApi.getNode(this.nodeId).then(
(node) => {
this.node = node;
}
);
} else if (this.sharedLinkId) {
this.apiService.sharedLinksApi.getSharedLink(this.sharedLinkId).then(
(details) => {
this.setUpSharedLinkFile(details);
(sharedLinkEntry: SharedLinkEntry) => {
this.setUpSharedLinkFile(sharedLinkEntry);
this.isLoading = false;
},
() => {
@@ -375,7 +350,7 @@ export class ViewerComponent implements OnChanges, OnInit, OnDestroy {
this.scrollTop();
}
private async setUpNodeFile(data: MinimalNodeEntryEntity) {
private async setUpNodeFile(data: Node) {
let setupNode;
if (data.content) {
@@ -431,9 +406,9 @@ export class ViewerComponent implements OnChanges, OnInit, OnDestroy {
toggleSidebar() {
this.showSidebar = !this.showSidebar;
if (this.showSidebar && this.nodeId) {
this.apiService.getInstance().nodes.getNodeInfo(this.nodeId, { include: ['allowableOperations'] })
.then((data: MinimalNodeEntryEntity) => {
this.sidebarTemplateContext.node = data;
this.apiService.getInstance().nodes.getNode(this.nodeId, { include: ['allowableOperations'] })
.then((nodeEntry: NodeEntry) => {
this.sidebarTemplateContext.node = nodeEntry.entry;
});
}
}
@@ -441,15 +416,15 @@ export class ViewerComponent implements OnChanges, OnInit, OnDestroy {
toggleLeftSidebar() {
this.showLeftSidebar = !this.showLeftSidebar;
if (this.showSidebar && this.nodeId) {
this.apiService.getInstance().nodes.getNodeInfo(this.nodeId, { include: ['allowableOperations'] })
.then((data: MinimalNodeEntryEntity) => {
this.sidebarLeftTemplateContext.node = data;
this.apiService.getInstance().nodes.getNode(this.nodeId, { include: ['allowableOperations'] })
.then((nodeEntry: NodeEntry) => {
this.sidebarLeftTemplateContext.node = nodeEntry.entry;
});
}
}
private getDisplayName(name) {
return this.displayName || name ;
return this.displayName || name;
}
scrollTop() {
@@ -614,13 +589,6 @@ export class ViewerComponent implements OnChanges, OnInit, OnDestroy {
}
}
shareContent() {
if (this.allowShare) {
const args = new BaseEvent();
this.share.next(args);
}
}
/**
* Triggers full screen mode with a main content area displayed.
*/
@@ -662,7 +630,7 @@ export class ViewerComponent implements OnChanges, OnInit, OnDestroy {
private async displaySharedLinkRendition(sharedId: string) {
try {
const rendition = await this.apiService.renditionsApi.getSharedLinkRendition(sharedId, 'pdf');
const rendition: RenditionEntry = await this.apiService.renditionsApi.getSharedLinkRendition(sharedId, 'pdf');
if (rendition.entry.status.toString() === 'CREATED') {
this.viewerType = 'pdf';
this.urlFileContent = this.apiService.contentApi.getSharedLinkRenditionUrl(sharedId, 'pdf');
@@ -670,7 +638,7 @@ export class ViewerComponent implements OnChanges, OnInit, OnDestroy {
} catch (error) {
this.logService.error(error);
try {
const rendition = await this.apiService.renditionsApi.getSharedLinkRendition(sharedId, 'imgpreview');
const rendition: RenditionEntry = await this.apiService.renditionsApi.getSharedLinkRendition(sharedId, 'imgpreview');
if (rendition.entry.status.toString() === 'CREATED') {
this.viewerType = 'image';
this.urlFileContent = this.apiService.contentApi.getSharedLinkRenditionUrl(sharedId, 'imgpreview');
@@ -681,26 +649,26 @@ export class ViewerComponent implements OnChanges, OnInit, OnDestroy {
}
}
private async resolveRendition(nodeId: string, renditionId: string) {
private async resolveRendition(nodeId: string, renditionId: string): Promise<RenditionEntry> {
renditionId = renditionId.toLowerCase();
const supported = await this.apiService.renditionsApi.getRenditions(nodeId);
const supportedRendition: RenditionPaging = await this.apiService.renditionsApi.getRenditions(nodeId);
let rendition = supported.list.entries.find((obj) => obj.entry.id.toLowerCase() === renditionId);
let rendition: RenditionEntry = supportedRendition.list.entries.find((renditionEntry: RenditionEntry) => renditionEntry.entry.id.toLowerCase() === renditionId);
if (!rendition) {
renditionId = 'imgpreview';
rendition = supported.list.entries.find((obj) => obj.entry.id.toLowerCase() === renditionId);
rendition = supportedRendition.list.entries.find((renditionEntry: RenditionEntry) => renditionEntry.entry.id.toLowerCase() === renditionId);
}
if (rendition) {
const status = rendition.entry.status.toString();
const status: string = rendition.entry.status.toString();
if (status === 'NOT_CREATED') {
try {
await this.apiService.renditionsApi.createRendition(nodeId, { id: renditionId }).then(() => {
this.viewerType = 'in_creation';
});
rendition = await this.waitRendition(nodeId, renditionId, 0);
rendition = await this.waitRendition(nodeId, renditionId);
} catch (err) {
this.logService.error(err);
}
@@ -710,14 +678,14 @@ export class ViewerComponent implements OnChanges, OnInit, OnDestroy {
return rendition;
}
private async waitRendition(nodeId: string, renditionId: string, retries: number): Promise<RenditionEntry> {
let currentRetry = 0;
return new Promise((resolve, reject) => {
private async waitRendition(nodeId: string, renditionId: string): Promise<RenditionEntry> {
let currentRetry: number = 0;
return new Promise<RenditionEntry>((resolve, reject) => {
let intervalId = setInterval(() => {
currentRetry++;
if (this.maxRetries >= currentRetry) {
this.apiService.renditionsApi.getRendition(nodeId, renditionId).then((rendition) => {
const status = rendition.entry.status.toString();
this.apiService.renditionsApi.getRendition(nodeId, renditionId).then((rendition: RenditionEntry) => {
const status: string = rendition.entry.status.toString();
if (status === 'CREATED') {
if (renditionId === 'pdf') {
+18 -18
View File
@@ -16,7 +16,7 @@
*/
import { Injectable } from '@angular/core';
import { RenditionEntry } from 'alfresco-js-api';
import { RenditionEntry, RenditionPaging } from '@alfresco/js-api';
import { AlfrescoApiService } from '../../services/alfresco-api.service';
import { LogService } from '../../services/log.service';
@@ -30,7 +30,7 @@ export class ViewUtilService {
* Content groups based on categorization of files that can be viewed in the web browser. This
* implementation or grouping is tied to the definition the ng component: ViewerComponent
*/
// tslint:disable-next-line:variable-name
// tslint:disable-next-line:variable-name
static ContentGroup = {
IMAGE: 'image',
MEDIA: 'media',
@@ -69,7 +69,7 @@ export class ViewUtilService {
// Because of the way chrome focus and close image window vs. pdf preview window
if (type === ViewUtilService.ContentGroup.IMAGE) {
pwa.onfocus = () => {
setTimeout( () => {
setTimeout(() => {
pwa.close();
}, 500);
};
@@ -93,17 +93,17 @@ export class ViewUtilService {
const type: string = this.getViewerTypeByMimeType(mimeType);
this.getRendition(nodeId, ViewUtilService.ContentGroup.PDF)
.then((value) => {
const url: string = this.getRenditionUrl(nodeId, type, (value ? true : false));
const printType = (type === ViewUtilService.ContentGroup.PDF
|| type === ViewUtilService.ContentGroup.TEXT)
? ViewUtilService.ContentGroup.PDF : type;
this.printFile(url, printType);
})
.catch((err) => {
this.logService.error('Error with Printing');
this.logService.error(err);
});
.then((value) => {
const url: string = this.getRenditionUrl(nodeId, type, (value ? true : false));
const printType = (type === ViewUtilService.ContentGroup.PDF
|| type === ViewUtilService.ContentGroup.TEXT)
? ViewUtilService.ContentGroup.PDF : type;
this.printFile(url, printType);
})
.catch((err) => {
this.logService.error('Error with Printing');
this.logService.error(err);
});
}
getRenditionUrl(nodeId: string, type: string, renditionExists: boolean): string {
@@ -147,22 +147,22 @@ export class ViewUtilService {
}
async getRendition(nodeId: string, renditionId: string): Promise<RenditionEntry> {
const supported = await this.apiService.renditionsApi.getRenditions(nodeId);
let rendition = supported.list.entries.find((obj) => obj.entry.id.toLowerCase() === renditionId);
const renditionPaging: RenditionPaging = await this.apiService.renditionsApi.getRenditions(nodeId);
let rendition: RenditionEntry = renditionPaging.list.entries.find((renditionEntry: RenditionEntry) => renditionEntry.entry.id.toLowerCase() === renditionId);
if (rendition) {
const status = rendition.entry.status.toString();
if (status === 'NOT_CREATED') {
try {
await this.apiService.renditionsApi.createRendition(nodeId, {id: renditionId});
await this.apiService.renditionsApi.createRendition(nodeId, { id: renditionId });
rendition = await this.waitRendition(nodeId, renditionId, 0);
} catch (err) {
this.logService.error(err);
}
}
}
return new Promise((resolve) => resolve(rendition));
return new Promise<RenditionEntry>((resolve) => resolve(rendition));
}
}