[ADF-2161] download directive (#2934)

* node download directive

* integrate with demo shell

* docs on the directive

* node actions integration

* test fixes

* remove old and disable invalid tests

* remove fdescribe

* fix unit tests
This commit is contained in:
Denys Vuika 2018-02-15 09:23:55 +00:00 committed by GitHub
parent 2c1271a5b2
commit 63a146616b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
13 changed files with 356 additions and 165 deletions

View File

@ -51,13 +51,13 @@
"CREATED": "Created"
},
"ACTIONS": {
"DOWNLOAD": "Download",
"FOLDER": {
"COPY": "Copy",
"MOVE": "Move",
"DELETE": "Delete"
},
"DOCUMENT": {
"DOWNLOAD": "Download",
"COPY": "Copy",
"MOVE": "Move",
"DELETE": "Delete",

View File

@ -48,7 +48,7 @@
<button mat-icon-button
[disabled]="!hasSelection(documentList.selection)"
title="Download"
(click)="downloadNodes(documentList.selection)">
[adfNodeDownload]="documentList.selection">
<mat-icon>get_app</mat-icon>
</button>
<button mat-icon-button
@ -196,6 +196,11 @@
<content-actions>
<!-- common actions -->
<content-action
icon="get_app"
title="DOCUMENT_LIST.ACTIONS.DOWNLOAD"
handler="download">
</content-action>
<content-action
icon="content_copy"
title="DOCUMENT_LIST.ACTIONS.FOLDER.COPY"
@ -230,12 +235,6 @@
title="Manage versions..."
(execute)="onManageVersions($event)">
</content-action>
<content-action
icon="file_download"
target="document"
title="DOCUMENT_LIST.ACTIONS.DOCUMENT.DOWNLOAD"
handler="download">
</content-action>
<content-action
*ngIf="authenticationService.isBpmLoggedIn()"
icon="play_arrow"

View File

@ -23,13 +23,13 @@ import { MatDialog } from '@angular/material';
import { ActivatedRoute, Params, Router } from '@angular/router';
import { MinimalNodeEntity, NodePaging, Pagination, MinimalNodeEntryEntity, SiteEntry } from 'alfresco-js-api';
import {
AlfrescoApiService, AuthenticationService, ContentService, TranslationService,
AuthenticationService, ContentService, TranslationService,
FileUploadEvent, FolderCreatedEvent, LogService, NotificationService,
UploadService, DataColumn, DataRow, UserPreferencesService,
PaginationComponent, FormValues
} from '@alfresco/adf-core';
import { DocumentListComponent, PermissionStyleModel, DownloadZipDialogComponent } from '@alfresco/adf-content-services';
import { DocumentListComponent, PermissionStyleModel } from '@alfresco/adf-content-services';
import { SelectAppsDialogComponent } from '@alfresco/adf-process-services';
@ -140,7 +140,6 @@ export class FilesComponent implements OnInit, OnChanges, OnDestroy {
private onEditFolder: Subscription;
constructor(private changeDetector: ChangeDetectorRef,
private apiService: AlfrescoApiService,
private notificationService: NotificationService,
private uploadService: UploadService,
private contentService: ContentService,
@ -361,73 +360,6 @@ export class FilesComponent implements OnInit, OnChanges, OnDestroy {
return this.contentService.hasPermission(selection[0].entry, 'update');
}
downloadNodes(selection: Array<MinimalNodeEntity>) {
if (!selection || selection.length === 0) {
return;
}
if (selection.length === 1) {
this.downloadNode(selection[0]);
} else {
this.downloadZip(selection);
}
}
downloadNode(node: MinimalNodeEntity) {
if (node && node.entry) {
const entry = node.entry;
if (entry.isFile) {
this.downloadFile(node);
}
if (entry.isFolder) {
this.downloadZip([node]);
}
}
}
downloadFile(node: MinimalNodeEntity) {
if (node && node.entry) {
const contentApi = this.apiService.getInstance().content;
const url = contentApi.getContentUrl(node.entry.id, true);
const fileName = node.entry.name;
this.download(url, fileName);
}
}
downloadZip(selection: Array<MinimalNodeEntity>) {
if (selection && selection.length > 0) {
const nodeIds = selection.map(node => node.entry.id);
const dialogRef = this.dialog.open(DownloadZipDialogComponent, {
width: '600px',
data: {
nodeIds: nodeIds
}
});
dialogRef.afterClosed().subscribe(result => {
this.logService.log(result);
});
}
}
download(url: string, fileName: string) {
if (url && fileName) {
const link = document.createElement('a');
link.style.display = 'none';
link.download = fileName;
link.href = url;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
}
getNodeNameTooltip(row: DataRow, col: DataColumn): string {
if (row) {
return row.getValue('name');

View File

@ -202,6 +202,7 @@ for more information about installing and using the source code.
| [Folder create directive](folder-create.directive.md) | Allows folders to be created. | [Source](../lib/content-services/folder-directive/folder-create.directive.ts) |
| [Folder edit directive](folder-edit.directive.md) | Allows folders to be edited. | [Source](../lib/content-services/folder-directive/folder-edit.directive.ts) |
| [File draggable directive](file-draggable.directive.md) | Provide drag-and-drop features for an element such as a `div`. | [Source](../lib/content-services/upload/directives/file-draggable.directive.ts) |
| [Node download directive](node-download.directive.md) | Downloads folders and files. Packs folders and/or multiple files into a .ZIP archive. | [Source](../lib/content-services/directives/node-download.directive.ts) |
## Models

View File

@ -0,0 +1,18 @@
# Node Download directive
Allows folders and/or files to be downloaded. Multiple nodes are packed as a '.ZIP' archive.
## Basic Usage
```html
<adf-toolbar>
<button mat-icon-button
[adfNodeDownload]="documentList.selection">
<mat-icon>get_app</mat-icon>
</button>
</adf-toolbar>
<adf-document-list #documentList ...>
...
</adf-document-list>
```

View File

@ -35,6 +35,7 @@ import { ContentNodeSelectorModule } from './content-node-selector/content-node-
import { DialogModule } from './dialogs/dialog.module';
import { FolderDirectiveModule } from './folder-directive/folder-directive.module';
import { ContentMetadataModule } from './content-metadata/content-metadata.module';
import { NodeDownloadDirective } from './directives/node-download.directive';
@NgModule({
imports: [
@ -57,6 +58,9 @@ import { ContentMetadataModule } from './content-metadata/content-metadata.modul
DialogModule,
FolderDirectiveModule
],
declarations: [
NodeDownloadDirective
],
providers: [
{
provide: TRANSLATION_PROVIDER,
@ -81,7 +85,8 @@ import { ContentMetadataModule } from './content-metadata/content-metadata.modul
ContentNodeSelectorModule,
ContentMetadataModule,
DialogModule,
FolderDirectiveModule
FolderDirectiveModule,
NodeDownloadDirective
]
})
export class ContentModule {

View File

@ -0,0 +1,142 @@
/*!
* @license
* Copyright 2016 Alfresco Software, Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { TestBed, ComponentFixture } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { MatDialog } from '@angular/material';
import { Component, DebugElement } from '@angular/core';
import { AlfrescoApiService } from '@alfresco/adf-core';
import { MaterialModule } from '../material.module';
import { DialogModule } from '../dialogs/dialog.module';
import { NodeDownloadDirective } from './node-download.directive';
@Component({
template: '<div [adfNodeDownload]="selection"></div>'
})
class TestComponent {
selection;
}
describe('NodeDownloadDirective', () => {
let component: TestComponent;
let fixture: ComponentFixture<TestComponent>;
let element: DebugElement;
let dialog: MatDialog;
let apiService: AlfrescoApiService;
let contentService;
let dialogSpy;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
DialogModule,
MaterialModule
],
declarations: [
TestComponent,
NodeDownloadDirective
]
});
fixture = TestBed.createComponent(TestComponent);
component = fixture.componentInstance;
element = fixture.debugElement.query(By.directive(NodeDownloadDirective));
dialog = TestBed.get(MatDialog);
apiService = TestBed.get(AlfrescoApiService);
contentService = apiService.getInstance().content;
dialogSpy = spyOn(dialog, 'open');
});
it('should not download node when selection is empty', () => {
spyOn(apiService, 'getInstance');
component.selection = [];
fixture.detectChanges();
element.triggerEventHandler('click', null);
expect(apiService.getInstance).not.toHaveBeenCalled();
});
it('should not download zip when selection has no nodes', () => {
component.selection = [];
fixture.detectChanges();
element.triggerEventHandler('click', null);
expect(dialogSpy).not.toHaveBeenCalled();
});
it('should download selected node as file', () => {
spyOn(contentService, 'getContentUrl');
const node = { entry: { id: 'node-id', isFile: true } };
component.selection = [node];
fixture.detectChanges();
element.triggerEventHandler('click', null);
expect(contentService.getContentUrl).toHaveBeenCalledWith(node.entry.id, true);
});
it('should download selected files nodes as zip', () => {
const node1 = { entry: { id: 'node-1' } };
const node2 = { entry: { id: 'node-2' } };
component.selection = [node1, node2];
fixture.detectChanges();
element.triggerEventHandler('click', null);
expect(dialogSpy.calls.argsFor(0)[1].data).toEqual({ nodeIds: [ 'node-1', 'node-2' ] });
});
it('should download selected folder node as zip', () => {
const node = { entry: { isFolder: true, id: 'node-id' } };
component.selection = [node];
fixture.detectChanges();
element.triggerEventHandler('click', null);
expect(dialogSpy.calls.argsFor(0)[1].data).toEqual({ nodeIds: [ 'node-id' ] });
});
it('should create link element to download file node', () => {
const dummyLinkElement = {
download: null,
href: null,
click: () => null,
style: {
display: null
}
};
const node = { entry: { name: 'dummy', isFile: true, id: 'node-id' } };
spyOn(contentService, 'getContentUrl').and.returnValue('somewhere-over-the-rainbow');
spyOn(document, 'createElement').and.returnValue(dummyLinkElement);
spyOn(document.body, 'appendChild').and.stub();
spyOn(document.body, 'removeChild').and.stub();
component.selection = [node];
fixture.detectChanges();
element.triggerEventHandler('click', null);
expect(document.createElement).toHaveBeenCalled();
expect(dummyLinkElement.download).toBe('dummy');
expect(dummyLinkElement.href).toContain('somewhere-over-the-rainbow');
});
});

View File

@ -0,0 +1,124 @@
/*!
* @license
* Copyright 2016 Alfresco Software, Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { Directive, Input, HostListener } from '@angular/core';
import { MatDialog } from '@angular/material';
import { MinimalNodeEntity } from 'alfresco-js-api';
import { AlfrescoApiService } from '@alfresco/adf-core';
import { DownloadZipDialogComponent } from '../dialogs/download-zip.dialog';
@Directive({
selector: '[adfNodeDownload]'
})
export class NodeDownloadDirective {
// tslint:disable-next-line:no-input-rename
@Input('adfNodeDownload')
nodes: MinimalNodeEntity[];
@HostListener('click')
onClick() {
this.downloadNodes(this.nodes);
}
constructor(
private apiService: AlfrescoApiService,
private dialog: MatDialog) {
}
/**
* Downloads multiple selected nodes.
* Packs result into a .ZIP archive if there is more than one node selected.
* @param selection Multiple selected nodes to download
*/
downloadNodes(selection: Array<MinimalNodeEntity>) {
if (!selection || selection.length === 0) {
return;
}
if (selection.length === 1) {
this.downloadNode(selection[0]);
} else {
this.downloadZip(selection);
}
}
/**
* Downloads a single node.
* Packs result into a .ZIP archive is the node is a Folder.
* @param node Node to download
*/
downloadNode(node: MinimalNodeEntity) {
if (node && node.entry) {
const entry = node.entry;
if (entry.isFile) {
this.downloadFile(node);
}
if (entry.isFolder) {
this.downloadZip([node]);
}
// Check if there's nodeId for Shared Files
if (!entry.isFile && !entry.isFolder && (<any> entry).nodeId) {
this.downloadFile(node);
}
}
}
private downloadFile(node: MinimalNodeEntity) {
if (node && node.entry) {
const contentApi = this.apiService.getInstance().content;
const url = contentApi.getContentUrl(node.entry.id, true);
const fileName = node.entry.name;
this.download(url, fileName);
}
}
private downloadZip(selection: Array<MinimalNodeEntity>) {
if (selection && selection.length > 0) {
// nodeId for Shared node
const nodeIds = selection.map((node: any) => (node.entry.nodeId || node.entry.id));
this.dialog.open(DownloadZipDialogComponent, {
width: '600px',
disableClose: true,
data: {
nodeIds
}
});
}
}
private download(url: string, fileName: string) {
if (url && fileName) {
const link = document.createElement('a');
link.style.display = 'none';
link.download = fileName;
link.href = url;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
}
}

View File

@ -15,25 +15,40 @@
* limitations under the License.
*/
import { ContentService } from '@alfresco/adf-core';
import { FileNode, FolderNode, DocumentListServiceMock } from '../../mock';
import { async, TestBed } from '@angular/core/testing';
import { FileNode, FolderNode } from '../../mock';
import { DocumentListModule } from '../document-list.module';
import { ContentActionHandler } from '../models/content-action.model';
import { DocumentActionsService } from './document-actions.service';
import { DocumentListService } from './document-list.service';
import { NodeActionsService } from './node-actions.service';
import { DialogModule } from '../../dialogs/dialog.module';
import { ContentNodeDialogService } from '../../content-node-selector/content-node-dialog.service';
import { Observable } from 'rxjs/Observable';
describe('DocumentActionsService', () => {
let service: DocumentActionsService;
let documentListService: DocumentListService;
let contentService: ContentService;
let nodeActionsService: NodeActionsService;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
DialogModule,
DocumentListModule
],
providers: [
ContentNodeDialogService
]
}).compileComponents();
}));
beforeEach(() => {
documentListService = new DocumentListServiceMock();
contentService = new ContentService(null, null, null, null);
nodeActionsService = new NodeActionsService(null, null);
service = new DocumentActionsService(nodeActionsService, documentListService, contentService);
documentListService = TestBed.get(DocumentListService);
nodeActionsService = TestBed.get(NodeActionsService);
service = TestBed.get(DocumentActionsService);
});
it('should register default download action', () => {
@ -87,7 +102,7 @@ describe('DocumentActionsService', () => {
});
it('should not delete the file node if there are no permissions', (done) => {
spyOn(documentListService, 'deleteNode').and.callThrough();
spyOn(documentListService, 'deleteNode').and.returnValue(Observable.of(true));
service.permissionEvent.subscribe((permission) => {
expect(permission).toBeDefined();
@ -102,7 +117,7 @@ describe('DocumentActionsService', () => {
});
it('should call the error on the returned Observable if there are no permissions', (done) => {
spyOn(documentListService, 'deleteNode').and.callThrough();
spyOn(documentListService, 'deleteNode').and.returnValue(Observable.of(true));
let file = new FileNode();
const deleteObservable = service.getHandler('delete')(file);
@ -116,7 +131,7 @@ describe('DocumentActionsService', () => {
});
it('should delete the file node if there is the delete permission', () => {
spyOn(documentListService, 'deleteNode').and.callThrough();
spyOn(documentListService, 'deleteNode').and.returnValue(Observable.of(true));
let permission = 'delete';
let file = new FileNode();
@ -145,7 +160,7 @@ describe('DocumentActionsService', () => {
});
it('should delete the file node if there is the delete and others permission ', () => {
spyOn(documentListService, 'deleteNode').and.callThrough();
spyOn(documentListService, 'deleteNode').and.returnValue(Observable.of(true));
let permission = 'delete';
let file = new FileNode();
@ -160,60 +175,8 @@ describe('DocumentActionsService', () => {
expect(service.getHandler('download')).toBeDefined();
});
it('should execute download action and cleanup', () => {
let file = new FileNode();
file.entry.name = 'test.png';
let url = 'http://<address>';
spyOn(contentService, 'getContentUrl').and.returnValue(url);
let link = jasmine.createSpyObj('a', [
'setAttribute',
'click'
]);
spyOn(document, 'createElement').and.returnValue(link);
spyOn(document.body, 'appendChild').and.stub();
spyOn(document.body, 'removeChild').and.stub();
service.getHandler('download')(file);
expect(contentService.getContentUrl).toHaveBeenCalledWith(file);
expect(document.createElement).toHaveBeenCalledWith('a');
expect(link.setAttribute).toHaveBeenCalledWith('download', 'test.png');
expect(document.body.appendChild).toHaveBeenCalledWith(link);
expect(link.click).toHaveBeenCalled();
expect(document.body.removeChild).toHaveBeenCalledWith(link);
});
it('should require internal service for download action', () => {
let actionService = new DocumentActionsService(nodeActionsService, null, contentService);
let file = new FileNode();
let result = actionService.getHandler('download')(file);
result.subscribe((value) => {
expect(value).toBeFalsy();
});
});
it('should require content service for download action', () => {
let actionService = new DocumentActionsService(nodeActionsService, documentListService, null);
let file = new FileNode();
let result = actionService.getHandler('download')(file);
result.subscribe((value) => {
expect(value).toBeFalsy();
});
});
it('should require file node for download action', () => {
let folder = new FolderNode();
let result = service.getHandler('download')(folder);
result.subscribe((value) => {
expect(value).toBeFalsy();
});
});
it('should delete file node', () => {
spyOn(documentListService, 'deleteNode').and.callThrough();
spyOn(documentListService, 'deleteNode').and.returnValue(Observable.of(true));
let permission = 'delete';
let file = new FileNode();
@ -226,7 +189,7 @@ describe('DocumentActionsService', () => {
});
it('should support deletion only file node', () => {
spyOn(documentListService, 'deleteNode').and.callThrough();
spyOn(documentListService, 'deleteNode').and.returnValue(Observable.of(true));
let folder = new FolderNode();
service.getHandler('delete')(folder);
@ -241,7 +204,7 @@ describe('DocumentActionsService', () => {
});
it('should require node id to delete', () => {
spyOn(documentListService, 'deleteNode').and.callThrough();
spyOn(documentListService, 'deleteNode').and.returnValue(Observable.of(true));
let file = new FileNode();
file.entry.id = null;
@ -251,14 +214,13 @@ describe('DocumentActionsService', () => {
});
it('should reload target upon node deletion', () => {
spyOn(documentListService, 'deleteNode').and.callThrough();
spyOn(documentListService, 'deleteNode').and.returnValue(Observable.of(true));
let target = jasmine.createSpyObj('obj', ['reload']);
let permission = 'delete';
let file = new FileNode();
let fileWithPermission: any = file;
fileWithPermission.entry.allowableOperations = [permission];
service.getHandler('delete')(fileWithPermission, target, permission);
let file: any = new FileNode();
file.entry.allowableOperations = ['delete'];
service.getHandler('delete')(file, target, permission);
expect(documentListService.deleteNode).toHaveBeenCalled();
expect(target.reload).toHaveBeenCalled();
@ -269,7 +231,7 @@ describe('DocumentActionsService', () => {
expect(nodeId).not.toBeNull();
done();
});
spyOn(documentListService, 'deleteNode').and.callThrough();
spyOn(documentListService, 'deleteNode').and.returnValue(Observable.of(true));
let target = jasmine.createSpyObj('obj', ['reload']);
let permission = 'delete';

View File

@ -76,23 +76,14 @@ export class DocumentActionsService {
}
private setupActionHandlers() {
this.handlers['download'] = this.download.bind(this);
this.handlers['copy'] = this.copyNode.bind(this);
this.handlers['move'] = this.moveNode.bind(this);
this.handlers['delete'] = this.deleteNode.bind(this);
this.handlers['download'] = this.downloadNode.bind(this);
}
private download(node: MinimalNodeEntity): Observable<boolean> {
if (this.canExecuteAction(node) && this.contentService) {
let link = document.createElement('a');
document.body.appendChild(link);
link.setAttribute('download', node.entry.name);
link.href = this.contentService.getContentUrl(node);
link.click();
document.body.removeChild(link);
return Observable.of(true);
}
return Observable.of(false);
private downloadNode(obj: MinimalNodeEntity, target?: any, permission?: string) {
this.nodeActionsService.downloadNode(obj);
}
private copyNode(node: MinimalNodeEntity, target?: any, permission?: string) {

View File

@ -79,6 +79,11 @@ export class FolderActionsService {
this.handlers['copy'] = this.copyNode.bind(this);
this.handlers['move'] = this.moveNode.bind(this);
this.handlers['delete'] = this.deleteNode.bind(this);
this.handlers['download'] = this.downloadNode.bind(this);
}
private downloadNode(obj: MinimalNodeEntity, target?: any, permission?: string) {
this.nodeActionsService.downloadNode(obj);
}
private copyNode(obj: MinimalNodeEntity, target?: any, permission?: string) {

View File

@ -16,16 +16,27 @@
*/
import { Injectable } from '@angular/core';
import { MinimalNodeEntryEntity } from 'alfresco-js-api';
import { MinimalNodeEntryEntity, MinimalNodeEntity } from 'alfresco-js-api';
import { Subject } from 'rxjs/Subject';
import { AlfrescoApiService } from '@alfresco/adf-core';
import { MatDialog } from '@angular/material';
import { DocumentListService } from './document-list.service';
import { ContentNodeDialogService } from '../../content-node-selector/content-node-dialog.service';
import { NodeDownloadDirective } from '../../directives/node-download.directive';
@Injectable()
export class NodeActionsService {
constructor(private contentDialogService: ContentNodeDialogService,
private documentListService?: DocumentListService) {}
private documentListService?: DocumentListService,
private apiService?: AlfrescoApiService,
private dialog?: MatDialog) {}
downloadNode(node: MinimalNodeEntity) {
new NodeDownloadDirective(this.apiService, this.dialog)
.downloadNode(node);
}
/**
* Copy content node

View File

@ -30,6 +30,7 @@ export * from './content-node-selector/content-node-selector.module';
export * from './dialogs/dialog.module';
export * from './folder-directive/folder-directive.module';
export * from './content-metadata/content-metadata.module';
export { NodeDownloadDirective } from './directives/node-download.directive';
export * from './social';
export * from './tag';