Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import { ScrollToService } from '@nicky-lenaers/ngx-scroll-to';
import { Subject } from 'rxjs';

import { AuthService } from '../../core/auth/auth.service';
import { ConfigurationDataService } from '../../core/data/configuration-data.service';
import { EntityTypeDataService } from '../../core/data/entity-type-data.service';
import { DragService } from '../../core/drag.service';
import { CookieService } from '../../core/services/cookie.service';
Expand All @@ -37,6 +38,7 @@ import { getMockScrollToService } from '../../shared/mocks/scroll-to-service.moc
import { TranslateLoaderMock } from '../../shared/mocks/translate-loader.mock';
import { NotificationsService } from '../../shared/notifications/notifications.service';
import { AuthServiceStub } from '../../shared/testing/auth-service.stub';
import { ConfigurationDataServiceStub } from '../../shared/testing/configuration-data.service.stub';
import { HALEndpointServiceStub } from '../../shared/testing/hal-endpoint-service.stub';
import { HostWindowServiceStub } from '../../shared/testing/host-window-service.stub';
import { NotificationsServiceStub } from '../../shared/testing/notifications-service.stub';
Expand Down Expand Up @@ -83,6 +85,7 @@ describe('MyDSpaceNewSubmissionComponent test', () => {
{ provide: HostWindowService, useValue: new HostWindowServiceStub(800) },
{ provide: EntityTypeDataService, useValue: getMockEntityTypeService() },
{ provide: LiveRegionService, useValue: getLiveRegionServiceStub() },
{ provide: ConfigurationDataService, useClass: ConfigurationDataServiceStub },
],
schemas: [NO_ERRORS_SCHEMA],
}).compileComponents();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,18 @@ describe('DsDynamicAutocompleteComponent test suite', () => {
expect(autComp.change.emit).toHaveBeenCalled();
}));

it('should mark only the change of a picked suggestion as picked', () => {
const pickedOnChange = [];
autComp.change.subscribe(() => pickedOnChange.push(autComp.model.suggestionPicked));
const event = { item: Object.assign(new VocabularyEntry(), { display: 'Name, Lastname', value: 1 }), preventDefault: () => undefined };

autComp.onSelectItem(event);
autComp.onBlur(new Event('blur'));

expect(pickedOnChange).toEqual([true, false]);
expect(autComp.model.suggestionPicked).toBeFalse();
});

it('should normalize object value to string on blur', () => {
spyOn(autComp.change, 'emit');
autComp.currentValue = { value: 'aig', display: 'Alumu-Tesu' };
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,9 @@ export class DsDynamicAutocompleteComponent extends DsDynamicTagComponent implem
* @param event The value to set.
*/
onSelectItem(event: NgbTypeaheadSelectItemEvent) {
this.model.suggestionPicked = true;
this.updateModel(event.item);
this.model.suggestionPicked = false;
this.cdr.detectChanges();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,10 @@ export class DsDynamicAutocompleteModel extends DsDynamicInputModel {
@serializable() minChars: number;
@serializable() readonly type: string = DYNAMIC_FORM_CONTROL_TYPE_AUTOCOMPLETE;
@serializable() autocompleteCustom: string;
/**
* True only while the change of a picked suggestion is emitted, so listeners can tell it from typed text.
*/
suggestionPicked = false;

constructor(config: DsDynamicAutocompleteModelConfig, layout?: DynamicFormControlLayout) {

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,10 @@ export class DsDynamicSponsorAutocompleteModel extends DsDynamicInputModel {
@serializable() maxLength: number;
@serializable() readonly type: string = DYNAMIC_FORM_CONTROL_TYPE_AUTOCOMPLETE;
@serializable() autocompleteCustom: string;
/**
* True only while the change of a picked suggestion is emitted, so listeners can tell it from typed text.
*/
suggestionPicked = false;

constructor(config: DsDynamicSponsorAutocompleteModelConfig, layout?: DynamicFormControlLayout) {

Expand Down
100 changes: 99 additions & 1 deletion src/app/shared/upload/uploader/uploader.component.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,28 @@ import {
} from '@angular/core/testing';
import { TranslateModule } from '@ngx-translate/core';
import { FileUploadModule } from 'ng2-file-upload';
import {
Observable,
of,
Subject,
} from 'rxjs';

import { ConfigurationDataService } from '../../../core/data/configuration-data.service';
import { RemoteData } from '../../../core/data/remote-data';
import { DragService } from '../../../core/drag.service';
import { CookieService } from '../../../core/services/cookie.service';
import { ConfigurationProperty } from '../../../core/shared/configuration-property.model';
import { LiveRegionService } from '../../live-region/live-region.service';
import { getLiveRegionServiceStub } from '../../live-region/live-region.service.stub';
import { CookieServiceMock } from '../../mocks/cookie.service.mock';
import { HttpXsrfTokenExtractorMock } from '../../mocks/http-xsrf-token-extractor.mock';
import { createSuccessfulRemoteDataObject } from '../../remote-data.utils';
import { ConfigurationDataServiceStub } from '../../testing/configuration-data.service.stub';
import { createTestComponent } from '../../testing/utils.test';
import { UploaderComponent } from './uploader.component';
import {
MAX_UPLOAD_FILE_SIZE_CFG_PROPERTY,
UploaderComponent,
} from './uploader.component';
import { UploaderOptions } from './uploader-options.model';

describe('Uploader component', () => {
Expand All @@ -46,12 +59,29 @@ describe('Uploader component', () => {
{ provide: HttpXsrfTokenExtractor, useValue: new HttpXsrfTokenExtractorMock('mock-token') },
{ provide: CookieService, useValue: new CookieServiceMock() },
{ provide: LiveRegionService, useValue: getLiveRegionServiceStub() },
{ provide: ConfigurationDataService, useClass: ConfigurationDataServiceStub },
],
schemas: [CUSTOM_ELEMENTS_SCHEMA],
});

}));

function maxFileSizeProperty(maxFileSize: string): RemoteData<ConfigurationProperty> {
return createSuccessfulRemoteDataObject(Object.assign(new ConfigurationProperty(), { name: MAX_UPLOAD_FILE_SIZE_CFG_PROPERTY, values: [maxFileSize] }));
}

function initWithMaxFileSize(app: UploaderComponent, maxFileSize$: Observable<RemoteData<ConfigurationProperty>>) {
spyOn(TestBed.inject(ConfigurationDataService), 'findByPropertyName').and.returnValue(maxFileSize$);
app.uploadFilesOptions = Object.assign(new UploaderOptions(), {
url: 'http://test',
authToken: null,
disableMultipart: false,
itemAlias: null,
});
app.ngOnInit();
app.ngAfterViewInit();
}

// synchronous beforeEach
beforeEach(() => {
html = `
Expand Down Expand Up @@ -253,6 +283,74 @@ describe('Uploader component', () => {
});
}));

it('should use the backend multipart limit as the max file size', inject([UploaderComponent], (app: UploaderComponent) => {
initWithMaxFileSize(app, of(maxFileSizeProperty('4GB')));

expect(TestBed.inject(ConfigurationDataService).findByPropertyName).toHaveBeenCalledWith(MAX_UPLOAD_FILE_SIZE_CFG_PROPERTY);
expect(app.uploader.options.maxFileSize).toBe(4 * 1024 * 1024 * 1024);
}));

it('should read the unit of the backend multipart limit', inject([UploaderComponent], (app: UploaderComponent) => {
initWithMaxFileSize(app, of(maxFileSizeProperty('512MB')));

expect(app.uploader.options.maxFileSize).toBe(512 * 1024 * 1024);
}));

it('should not limit the file size when the backend limit is -1', inject([UploaderComponent], (app: UploaderComponent) => {
initWithMaxFileSize(app, of(maxFileSizeProperty('-1')));

expect(app.uploader.options.maxFileSize).toBeUndefined();
expect(app.uploader.options.autoUpload).toBeTrue();
}));

it('should refuse a file over the limit before upload and emit the size-limit error', inject([UploaderComponent], (app: UploaderComponent) => {
initWithMaxFileSize(app, of(maxFileSizeProperty('1KB')));
spyOn(app.onUploadError, 'emit');

app.uploader.addToQueue([new File([new Uint8Array(2048)], 'big.zip')]);

expect(app.uploader.queue.length).toBe(0);
expect(app.onUploadError.emit).toHaveBeenCalledWith(jasmine.objectContaining({
status: 400,
response: 'submission.sections.upload.upload-failed.size-limit-exceeded',
}));
}));

it('should queue a file within the limit', inject([UploaderComponent], (app: UploaderComponent) => {
initWithMaxFileSize(app, of(maxFileSizeProperty('1KB')));
spyOn(app.onUploadError, 'emit');

app.uploader.addToQueue([new File([new Uint8Array(512)], 'small.zip')]);

expect(app.uploader.queue.length).toBe(1);
expect(app.onUploadError.emit).not.toHaveBeenCalled();
}));

it('should not send files added before the limit is known and drop the ones over it', inject([UploaderComponent], (app: UploaderComponent) => {
const maxFileSize$ = new Subject<RemoteData<ConfigurationProperty>>();
initWithMaxFileSize(app, maxFileSize$);
spyOn(app.onUploadError, 'emit');
spyOn(app.uploader, 'uploadItem');

app.uploader.addToQueue([
new File([new Uint8Array(2048)], 'big.zip'),
new File([new Uint8Array(512)], 'small.zip'),
new File([new Uint8Array(2048)], 'other-big.zip'),
]);

expect(app.uploader.uploadItem).not.toHaveBeenCalled();

maxFileSize$.next(maxFileSizeProperty('1KB'));

expect(app.uploader.queue.map((item) => item.file.name)).toEqual(['small.zip']);
expect(app.uploader.uploadItem).toHaveBeenCalledOnceWith(app.uploader.queue[0]);
expect(app.onUploadError.emit).toHaveBeenCalledTimes(2);
expect(app.onUploadError.emit).toHaveBeenCalledWith(jasmine.objectContaining({
status: 400,
response: 'submission.sections.upload.upload-failed.size-limit-exceeded',
}));
}));

});

// declare a test component
Expand Down
69 changes: 67 additions & 2 deletions src/app/shared/upload/uploader/uploader.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,17 +12,25 @@ import {
Output,
ViewEncapsulation,
} from '@angular/core';
import { TranslateModule } from '@ngx-translate/core';
import {
TranslateModule,
TranslateService,
} from '@ngx-translate/core';
import uniqueId from 'lodash/uniqueId';
import {
FileItem,
FileLikeObject,
FileUploader,
FileUploadModule,
} from 'ng2-file-upload';
import { of } from 'rxjs';

import { ConfigurationDataService } from '../../../core/data/configuration-data.service';
import { RemoteData } from '../../../core/data/remote-data';
import { DragService } from '../../../core/drag.service';
import { CookieService } from '../../../core/services/cookie.service';
import { ConfigurationProperty } from '../../../core/shared/configuration-property.model';
import { getFirstCompletedRemoteData } from '../../../core/shared/operators';
import {
XSRF_COOKIE,
XSRF_REQUEST_HEADER,
Expand All @@ -40,6 +48,8 @@ import { UploaderError } from './uploader-error.model';
import { UploaderOptions } from './uploader-options.model';
import { UploaderProperties } from './uploader-properties.model';

export const MAX_UPLOAD_FILE_SIZE_CFG_PROPERTY = 'spring.servlet.multipart.max-file-size';

@Component({
selector: 'ds-uploader',
templateUrl: 'uploader.component.html',
Expand Down Expand Up @@ -155,6 +165,8 @@ export class UploaderComponent implements OnInit, AfterViewInit {
private tokenExtractor: HttpXsrfTokenExtractor,
private cookieService: CookieService,
private liveRegionService: LiveRegionService,
private configurationService: ConfigurationDataService,
private translate: TranslateService,
) {
}

Expand All @@ -170,10 +182,12 @@ export class UploaderComponent implements OnInit, AfterViewInit {
disableMultipart: this.uploadFilesOptions.disableMultipart,
itemAlias: this.uploadFilesOptions.itemAlias,
removeAfterUpload: true,
autoUpload: this.uploadFilesOptions.autoUpload,
// Turned on once the size limit is known, see setMaxFileSizeFromConfig.
autoUpload: false,
method: this.uploadFilesOptions.method,
queueLimit: this.uploadFilesOptions.maxFileNumber,
});
this.setMaxFileSizeFromConfig();

if (isUndefined(this.enableDragOverDocument)) {
this.enableDragOverDocument = false;
Expand Down Expand Up @@ -243,6 +257,11 @@ export class UploaderComponent implements OnInit, AfterViewInit {
this.onUploadError.emit({ item: item, response: response, status: status, headers: headers });
this.uploader.cancelAll();
};
this.uploader.onWhenAddingFileFailed = (item: FileLikeObject, filter: any) => {
if (filter?.name === 'fileSize') {
this.emitSizeLimitError(item);
}
};
this.uploader.onProgressAll = () => this.onProgress();
// Live region service setup
this.liveRegionService.setMessageTimeOutMs(1500);
Expand Down Expand Up @@ -318,4 +337,50 @@ export class UploaderComponent implements OnInit, AfterViewInit {
this.cookieService.set(XSRF_COOKIE, token);
}

/**
* Use the backend multipart limit as the uploader's max file size, so a too large file is refused before it is sent.
* Auto upload starts only after that, and files added in the meantime are checked first.
*/
private setMaxFileSizeFromConfig(): void {
this.configurationService.findByPropertyName(MAX_UPLOAD_FILE_SIZE_CFG_PROPERTY).pipe(
getFirstCompletedRemoteData(),
).subscribe((propertyRD: RemoteData<ConfigurationProperty>) => {
const maxFileSize = propertyRD.hasSucceeded ? this.dataSizeToBytes(propertyRD.payload.values[0]) : undefined;
this.uploader.options.maxFileSize = maxFileSize;
this.uploader.options.autoUpload = this.uploadFilesOptions.autoUpload;
this.uploader.setOptions(this.uploader.options);
this.uploader.queue
.filter((item: FileItem) => hasValue(maxFileSize) && item.file.size > maxFileSize)
.forEach((item: FileItem) => {
item.remove();
this.emitSizeLimitError(item.file);
});
if (this.uploader.autoUpload) {
this.uploader.uploadAll();
}
});
}

private emitSizeLimitError(item: FileLikeObject): void {
this.onUploadError.emit({
item: item,
response: this.translate.instant('submission.sections.upload.upload-failed.size-limit-exceeded'),
status: 400,
headers: {},
});
}

/**
* Convert a Spring data size like `4GB` or `512MB` to bytes; a bare number is bytes.
* Returns undefined for anything else, e.g. `-1`, which means no limit.
*/
private dataSizeToBytes(size: string): number {
const match = /^(\d+)\s*([KMGT]?B)?$/i.exec(size?.trim() ?? '');
if (!match) {
return undefined;
}
const units = ['B', 'KB', 'MB', 'GB', 'TB'];
return parseInt(match[1], 10) * Math.pow(1024, units.indexOf((match[2] ?? 'B').toUpperCase()));
}

}
Loading
Loading