[ADF-3095] ability to intercept, pause and resume upload process (#3416)

* prevent and resume upload process

* upload fixes and confirmation dialog demo

* ability to toggle the upload confirmation demo

* fix tests

* unit tests

* docs update

* remove deprecation

* fix test name
This commit is contained in:
Denys Vuika
2018-05-31 10:21:32 +01:00
committed by Eugenio Romano
parent 64a8c66103
commit 54e80e7863
11 changed files with 273 additions and 36 deletions

View File

@@ -12,7 +12,8 @@
"ALLOW_DOWNLOAD" :"Enable version download", "ALLOW_DOWNLOAD" :"Enable version download",
"READ_ONLY" : "Read only" "READ_ONLY" : "Read only"
}, },
"PERSONAL-FILES": "Personal Files" "PERSONAL-FILES": "Personal Files",
"WARN-MULTIPLE-UPLOADS": "Warn on multiple uploads"
}, },
"title": "Welcome", "title": "Welcome",
"VERSION": { "VERSION": {

View File

@@ -39,7 +39,8 @@
[rootFolderId]="getDocumentListCurrentFolderId()" [rootFolderId]="getDocumentListCurrentFolderId()"
[versioning]="versioning" [versioning]="versioning"
[adf-node-permission]="'create'" [adf-node-permission]="'create'"
[adf-nodes]="disableDragArea ? getCurrentDocumentListNode() : []"> [adf-nodes]="disableDragArea ? getCurrentDocumentListNode() : []"
(beginUpload)="onBeginUpload($event)">
<div *ngIf="errorMessage" class="error-message"> <div *ngIf="errorMessage" class="error-message">
<button (click)="resetError()" mat-icon-button> <button (click)="resetError()" mat-icon-button>
<mat-icon>highlight_off</mat-icon> <mat-icon>highlight_off</mat-icon>
@@ -500,6 +501,12 @@
</mat-slide-toggle> </mat-slide-toggle>
</section> </section>
<section>
<mat-slide-toggle color="primary" [(ngModel)]="warnOnMultipleUploads">
{{'APP.WARN-MULTIPLE-UPLOADS' | translate}}
</mat-slide-toggle>
</section>
<h5>Upload</h5> <h5>Upload</h5>
<section *ngIf="acceptedFilesTypeShow"> <section *ngIf="acceptedFilesTypeShow">
<mat-form-field floatPlaceholder="float"> <mat-form-field floatPlaceholder="float">

View File

@@ -31,7 +31,7 @@ import {
PaginationComponent, FormValues, DisplayMode, UserPreferenceValues, InfinitePaginationComponent PaginationComponent, FormValues, DisplayMode, UserPreferenceValues, InfinitePaginationComponent
} from '@alfresco/adf-core'; } from '@alfresco/adf-core';
import { DocumentListComponent, PermissionStyleModel } from '@alfresco/adf-content-services'; import { DocumentListComponent, PermissionStyleModel, UploadFilesEvent, ConfirmDialogComponent } from '@alfresco/adf-content-services';
import { SelectAppsDialogComponent } from '@alfresco/adf-process-services'; import { SelectAppsDialogComponent } from '@alfresco/adf-process-services';
@@ -177,6 +177,7 @@ export class FilesComponent implements OnInit, OnChanges, OnDestroy {
infiniteScrolling: boolean; infiniteScrolling: boolean;
supportedPages: number[]; supportedPages: number[];
currentSiteid = ''; currentSiteid = '';
warnOnMultipleUploads = false;
private onCreateFolder: Subscription; private onCreateFolder: Subscription;
private onEditFolder: Subscription; private onEditFolder: Subscription;
@@ -513,4 +514,27 @@ export class FilesComponent implements OnInit, OnChanges, OnDestroy {
} }
return false; return false;
} }
onBeginUpload(event: UploadFilesEvent) {
if (this.warnOnMultipleUploads && event) {
const files = event.files || [];
if (files.length > 1) {
event.pauseUpload();
const dialogRef = this.dialog.open(ConfirmDialogComponent, {
data: {
title: 'Upload',
message: `Are you sure you want to upload ${files.length} file(s)?`
},
minWidth: '250px'
});
dialogRef.afterClosed().subscribe(result => {
if (result === true) {
event.resumeUpload();
}
});
}
}
}
} }

View File

@@ -48,7 +48,64 @@ export class AppComponent {
### Events ### Events
| Name | Type | Description | | Name | Type | Description |
| -- | -- | -- | | --- | --- | --- |
| createFolder | `EventEmitter<Object>` | Emitted when a folder is created. | | beginUpload | `EventEmitter<UploadFilesEvent>()` | Raised after files or folders dropped and before the upload process starts. |
| error | `EventEmitter<Object>` | Emitted when an error occurs. | | createFolder | `EventEmitter<Object>` | **Deprecated:** No longer used by the framework |
| success | `EventEmitter<Object>` | Emitted when the file is uploaded successfully. | | error | `EventEmitter<Object>` | Emitted when the file is uploaded successfully. |
| success | `EventEmitter<Object>` | Emitted when an error occurs. |
## Intercepting uploads
You can intercept the upload process by utilizing the `beginUpload` event.
The event has a type of `UploadFilesEvent` and provides the following APIs:
* **files**: get access to the FileInfo objects that are prepared for the upload
* **pauseUpload**: pause the upload and perform additional tasks, like showing the confirmation dialog
* **resumeUpload**: resume the upload process
## Example
Wire the `beginUpload` event at the template level
```html
<adf-upload-drag-area (beginUpload)="onBeginUpload($event)" ...>
...
</adf-upload-drag-area>
```
Create the `onBeginUpload` handler that invokes a confirmation dialog
```ts
import { UploadFilesEvent, ConfirmDialogComponent } from '@alfresco/adf-content-services';
@Component({...})
export class MyComponent {
onBeginUpload(event: UploadFilesEvent) {
const files = event.files || [];
if (files.length > 1) {
event.pauseUpload();
const dialogRef = this.dialog.open(ConfirmDialogComponent, {
data: {
title: 'Upload',
message: `Are you sure you want to upload ${files.length} file(s)?`
},
minWidth: '250px'
});
dialogRef.afterClosed().subscribe(result => {
if (result === true) {
event.resumeUpload();
}
});
}
}
}
```
The example above is going to raise confirmation dialog every time a user uploads more than 1 file.
That can be either 2 or more files, or a folder with multiple entries.

View File

@@ -15,22 +15,24 @@
* limitations under the License. * limitations under the License.
*/ */
import { Component } from '@angular/core'; import { Component, NgZone } from '@angular/core';
import { ComponentFixture, TestBed } from '@angular/core/testing'; import { ComponentFixture, TestBed, fakeAsync, tick } from '@angular/core/testing';
import { TranslationService, UploadService, setupTestBed, CoreModule, FileModel } from '@alfresco/adf-core'; import { TranslationService, UploadService, setupTestBed, CoreModule, FileModel } from '@alfresco/adf-core';
import { UploadBase } from './upload-base'; import { UploadBase } from './upload-base';
import { TranslationMock } from '@alfresco/adf-core'; import { TranslationMock } from '@alfresco/adf-core';
import { NoopAnimationsModule } from '@angular/platform-browser/animations'; import { NoopAnimationsModule } from '@angular/platform-browser/animations';
import { UploadFilesEvent } from '../upload-files.event';
@Component({ @Component({
selector: 'adf-upload-button-test', selector: 'adf-upload-button-test',
template: 'test componente' template: 'test component'
}) })
export class UploadTestComponent extends UploadBase { export class UploadTestComponent extends UploadBase {
constructor(protected uploadService: UploadService, constructor(protected uploadService: UploadService,
protected translationService: TranslationService) { protected translationService: TranslationService,
super(uploadService, translationService); protected ngZone: NgZone) {
super(uploadService, translationService, ngZone);
} }
} }
@@ -67,6 +69,66 @@ describe('UploadBase', () => {
TestBed.resetTestingModule(); TestBed.resetTestingModule();
}); });
describe('beginUpload', () => {
it('should raise event', done => {
spyOn(uploadService, 'addToQueue').and.stub();
spyOn(uploadService, 'uploadFilesInTheQueue').and.stub();
component.beginUpload.subscribe(() => done());
const file = <File> { name: 'bigFile.png', size: 1000 };
component.uploadFiles([file]);
fixture.detectChanges();
});
it('should pause upload', fakeAsync(() => {
spyOn(uploadService, 'addToQueue').and.stub();
spyOn(uploadService, 'uploadFilesInTheQueue').and.stub();
let prevented = false;
component.beginUpload.subscribe(event => {
event.preventDefault();
prevented = true;
});
const file = <File> { name: 'bigFile.png', size: 1000 };
component.uploadFiles([file]);
tick();
expect(prevented).toBeTruthy();
expect(uploadService.addToQueue).not.toHaveBeenCalled();
expect(uploadService.uploadFilesInTheQueue).not.toHaveBeenCalled();
}));
it('should resume upload', fakeAsync(() => {
const addToQueue = spyOn(uploadService, 'addToQueue').and.stub();
const uploadFilesInTheQueue = spyOn(uploadService, 'uploadFilesInTheQueue').and.stub();
let prevented = false;
let uploadEvent: UploadFilesEvent;
component.beginUpload.subscribe(event => {
uploadEvent = event;
event.preventDefault();
prevented = true;
});
const file = <File> { name: 'bigFile.png', size: 1000 };
component.uploadFiles([file]);
tick();
expect(prevented).toBeTruthy();
expect(addToQueue).not.toHaveBeenCalled();
expect(uploadFilesInTheQueue).not.toHaveBeenCalled();
addToQueue.calls.reset();
uploadFilesInTheQueue.calls.reset();
uploadEvent.resumeUpload();
expect(addToQueue).toHaveBeenCalled();
expect(uploadFilesInTheQueue).toHaveBeenCalled();
}));
});
describe('filesize', () => { describe('filesize', () => {
const files: File[] = [ const files: File[] = [

View File

@@ -16,10 +16,12 @@
*/ */
import { FileModel, FileInfo } from '@alfresco/adf-core'; import { FileModel, FileInfo } from '@alfresco/adf-core';
import { EventEmitter, Input, Output } from '@angular/core'; import { EventEmitter, Input, Output, OnInit, OnDestroy, NgZone } from '@angular/core';
import { UploadService, TranslationService } from '@alfresco/adf-core'; import { UploadService, TranslationService } from '@alfresco/adf-core';
import { Subscription } from 'rxjs/Rx';
import { UploadFilesEvent } from '../upload-files.event';
export abstract class UploadBase { export abstract class UploadBase implements OnInit, OnDestroy {
/** Sets a limit on the maximum size (in bytes) of a file to be uploaded. /** Sets a limit on the maximum size (in bytes) of a file to be uploaded.
* Has no effect if undefined. * Has no effect if undefined.
@@ -61,7 +63,7 @@ export abstract class UploadBase {
@Output() @Output()
success = new EventEmitter(); success = new EventEmitter();
/** @deprecated 2.4.0 */ /** @deprecated 2.4.0 No longer used by the framework */
/** Emitted when a folder is created. */ /** Emitted when a folder is created. */
@Output() @Output()
createFolder = new EventEmitter(); createFolder = new EventEmitter();
@@ -70,8 +72,28 @@ export abstract class UploadBase {
@Output() @Output()
error = new EventEmitter(); error = new EventEmitter();
@Output()
beginUpload = new EventEmitter<UploadFilesEvent>();
protected subscriptions: Subscription[] = [];
constructor(protected uploadService: UploadService, constructor(protected uploadService: UploadService,
protected translationService: TranslationService) { protected translationService: TranslationService,
protected ngZone: NgZone) {
}
ngOnInit() {
this.subscriptions.push(
this.uploadService.fileUploadError.subscribe((error) => {
this.error.emit(error);
})
);
}
ngOnDestroy() {
this.subscriptions.forEach(subscription => subscription.unsubscribe());
this.subscriptions = [];
} }
/** /**
@@ -102,14 +124,21 @@ export abstract class UploadBase {
.filter(this.isFileAcceptable.bind(this)) .filter(this.isFileAcceptable.bind(this))
.filter(this.isFileSizeAcceptable.bind(this)); .filter(this.isFileSizeAcceptable.bind(this));
this.ngZone.run(() => {
const event = new UploadFilesEvent(
[...filteredFiles],
this.uploadService
);
this.beginUpload.emit(event);
if (!event.defaultPrevented) {
if (filteredFiles.length > 0) { if (filteredFiles.length > 0) {
this.uploadService.addToQueue(...filteredFiles); this.uploadService.addToQueue(...filteredFiles);
this.uploadService.uploadFilesInTheQueue(this.success); this.uploadService.uploadFilesInTheQueue(this.success);
this.uploadService.fileUploadError.subscribe((error) => {
this.error.emit(error);
});
} }
} }
});
}
/** /**
* Checks if the given file is allowed by the extension filters * Checks if the given file is allowed by the extension filters
@@ -176,9 +205,12 @@ export abstract class UploadBase {
if (!this.isFileSizeAllowed(file)) { if (!this.isFileSizeAllowed(file)) {
acceptableSize = false; acceptableSize = false;
this.translationService.get('FILE_UPLOAD.MESSAGES.EXCEED_MAX_FILE_SIZE', { fileName: file.name }).subscribe((message: string) => { const message = this.translationService.instant(
'FILE_UPLOAD.MESSAGES.EXCEED_MAX_FILE_SIZE',
{ fileName: file.name }
);
this.error.emit(message); this.error.emit(message);
});
} }
return acceptableSize; return acceptableSize;

View File

@@ -21,7 +21,7 @@ import {
} from '@alfresco/adf-core'; } from '@alfresco/adf-core';
import { import {
Component, EventEmitter, forwardRef, Input, Component, EventEmitter, forwardRef, Input,
OnChanges, OnInit, Output, SimpleChanges, ViewEncapsulation OnChanges, OnInit, Output, SimpleChanges, ViewEncapsulation, NgZone
} from '@angular/core'; } from '@angular/core';
import { MinimalNodeEntryEntity } from 'alfresco-js-api'; import { MinimalNodeEntryEntity } from 'alfresco-js-api';
import { Subject } from 'rxjs/Subject'; import { Subject } from 'rxjs/Subject';
@@ -67,8 +67,9 @@ export class UploadButtonComponent extends UploadBase implements OnInit, OnChang
constructor(protected uploadService: UploadService, constructor(protected uploadService: UploadService,
private contentService: ContentService, private contentService: ContentService,
protected translationService: TranslationService, protected translationService: TranslationService,
protected logService: LogService) { protected logService: LogService,
super(uploadService, translationService); protected ngZone: NgZone) {
super(uploadService, translationService, ngZone);
} }
ngOnInit() { ngOnInit() {

View File

@@ -19,7 +19,7 @@ import {
EXTENDIBLE_COMPONENT, FileInfo, FileModel, FileUtils, NodePermissionSubject, EXTENDIBLE_COMPONENT, FileInfo, FileModel, FileUtils, NodePermissionSubject,
NotificationService, TranslationService, UploadService, ContentService, PermissionsEnum NotificationService, TranslationService, UploadService, ContentService, PermissionsEnum
} from '@alfresco/adf-core'; } from '@alfresco/adf-core';
import { Component, forwardRef, Input, ViewEncapsulation } from '@angular/core'; import { Component, forwardRef, Input, ViewEncapsulation, NgZone } from '@angular/core';
import { UploadBase } from './base-upload/upload-base'; import { UploadBase } from './base-upload/upload-base';
@Component({ @Component({
@@ -43,8 +43,9 @@ export class UploadDragAreaComponent extends UploadBase implements NodePermissio
constructor(protected uploadService: UploadService, constructor(protected uploadService: UploadService,
protected translationService: TranslationService, protected translationService: TranslationService,
private notificationService: NotificationService, private notificationService: NotificationService,
private contentService: ContentService) { private contentService: ContentService,
super(uploadService, translationService); protected ngZone: NgZone) {
super(uploadService, translationService, ngZone);
} }
/** /**

View File

@@ -0,0 +1,45 @@
/*!
* @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 { FileModel, UploadService } from '@alfresco/adf-core';
export class UploadFilesEvent {
private isDefaultPrevented: boolean = false;
get defaultPrevented() {
return this.isDefaultPrevented;
}
preventDefault() {
this.isDefaultPrevented = true;
}
constructor(public files: Array<FileModel>, private uploadService: UploadService) {
}
pauseUpload() {
this.preventDefault();
}
resumeUpload() {
if (this.files && this.files.length > 0) {
this.uploadService.addToQueue(...this.files);
this.uploadService.uploadFilesInTheQueue();
}
}
}

View File

@@ -21,6 +21,7 @@ export * from './components/file-uploading-dialog.component';
export * from './components/upload-drag-area.component'; export * from './components/upload-drag-area.component';
export * from './components/file-uploading-list.component'; export * from './components/file-uploading-list.component';
export * from './components/file-uploading-list-row.component'; export * from './components/file-uploading-list-row.component';
export * from './components/upload-files.event';
export * from './directives/file-draggable.directive'; export * from './directives/file-draggable.directive';

View File

@@ -98,7 +98,7 @@ export class UploadService {
* Finds all the files in the queue that are not yet uploaded and uploads them into the directory folder. * Finds all the files in the queue that are not yet uploaded and uploads them into the directory folder.
* @param emitter (Deprecated) Emitter to invoke on file status change * @param emitter (Deprecated) Emitter to invoke on file status change
*/ */
uploadFilesInTheQueue(emitter: EventEmitter<any>): void { uploadFilesInTheQueue(emitter?: EventEmitter<any>): void {
if (!this.activeTask) { if (!this.activeTask) {
let file = this.queue.find(currentFile => currentFile.status === FileUploadStatus.Pending); let file = this.queue.find(currentFile => currentFile.status === FileUploadStatus.Pending);
if (file) { if (file) {
@@ -200,15 +200,21 @@ export class UploadService {
}) })
.on('abort', () => { .on('abort', () => {
this.onUploadAborted(file); this.onUploadAborted(file);
if (emitter) {
emitter.emit({ value: 'File aborted' }); emitter.emit({ value: 'File aborted' });
}
}) })
.on('error', err => { .on('error', err => {
this.onUploadError(file, err); this.onUploadError(file, err);
if (emitter) {
emitter.emit({ value: 'Error file uploaded' }); emitter.emit({ value: 'Error file uploaded' });
}
}) })
.on('success', data => { .on('success', data => {
this.onUploadComplete(file, data); this.onUploadComplete(file, data);
if (emitter) {
emitter.emit({ value: data }); emitter.emit({ value: data });
}
}) })
.catch(err => { .catch(err => {
throw err; throw err;