OpenProject is the leading open source project management software for product, project and portfolio management. A powerful Jira alternative with agile planning, issue tracking, roadmaps, Gantt charts, time tracking, collaboration features, and more. Available on premises or in the cloud. ⭐ Star us on GitHub
Ruby agile-developmentangularbcfboardsbug-trackerganttgantt-chartifcissue-trackerjira-alternativekanbanopenprojectproduct-managementproject-managementproject-planningroadmaprubyscrumtimelineworkflows
[#46150] Added more upload service implementations
Eric Schubert60e912bd190a
diff --git a/frontend/src/app/app.module.ts b/frontend/src/app/app.module.tsindex 125d7428ff6..cd7e2803d41 100644--- a/frontend/src/app/app.module.ts+++ b/frontend/src/app/app.module.ts@@ -32,12 +32,15 @@ import {Injector,NgModule,} from '@angular/core';+import { A11yModule } from '@angular/cdk/a11y';import {- HTTP_INTERCEPTORS,+ HTTP_INTERCEPTORS, HttpClient,HttpClientModule,} from '@angular/common/http';import { ReactiveFormsModule } from '@angular/forms';-import { OpContextMenuTrigger } from 'core-app/shared/components/op-context-menu/handlers/op-context-menu-trigger.directive';+import {+ OpContextMenuTrigger,+} from 'core-app/shared/components/op-context-menu/handlers/op-context-menu-trigger.directive';import { States } from 'core-app/core/states/states.service';import { OpenprojectFieldsModule } from 'core-app/shared/components/fields/openproject-fields.module';import { OpSharedModule } from 'core-app/shared/shared.module';@@ -49,22 +52,30 @@ import { OpenprojectAttachmentsModule } from 'core-app/shared/components/attachmimport { OpenprojectEditorModule } from 'core-app/shared/components/editor/openproject-editor.module';import { OpenprojectGridsModule } from 'core-app/shared/components/grids/openproject-grids.module';import { OpenprojectRouterModule } from 'core-app/core/routing/openproject-router.module';-import { OpenprojectWorkPackageRoutesModule } from 'core-app/features/work-packages/openproject-work-package-routes.module';+import {+ OpenprojectWorkPackageRoutesModule,+} from 'core-app/features/work-packages/openproject-work-package-routes.module';import { BrowserModule } from '@angular/platform-browser';import { OpenprojectCalendarModule } from 'core-app/features/calendar/openproject-calendar.module';import { OpenprojectGlobalSearchModule } from 'core-app/core/global_search/openproject-global-search.module';import { OpenprojectDashboardsModule } from 'core-app/features/dashboards/openproject-dashboards.module';-import { OpenprojectWorkPackageGraphsModule } from 'core-app/shared/components/work-package-graphs/openproject-work-package-graphs.module';+import {+ OpenprojectWorkPackageGraphsModule,+} from 'core-app/shared/components/work-package-graphs/openproject-work-package-graphs.module';import { PreviewTriggerService } from 'core-app/core/setup/globals/global-listeners/preview-trigger.service';import { OpenprojectOverviewModule } from 'core-app/features/overview/openproject-overview.module';import { OpenprojectMyPageModule } from 'core-app/features/my-page/openproject-my-page.module';import { OpenprojectProjectsModule } from 'core-app/features/projects/openproject-projects.module';import { KeyboardShortcutService } from 'core-app/shared/directives/a11y/keyboard-shortcut.service';-import { OpenprojectMembersModule } from 'core-app/shared/components/autocompleter/members-autocompleter/members.module';+import {+ OpenprojectMembersModule,+} from 'core-app/shared/components/autocompleter/members-autocompleter/members.module';import { OpenprojectAugmentingModule } from 'core-app/core/augmenting/openproject-augmenting.module';import { OpenprojectInviteUserModalModule } from 'core-app/features/invite-user-modal/invite-user-modal.module';import { OpenprojectModalModule } from 'core-app/shared/components/modal/modal.module';-import { RevitAddInSettingsButtonService } from 'core-app/features/bim/revit_add_in/revit-add-in-settings-button.service';+import {+ RevitAddInSettingsButtonService,+} from 'core-app/features/bim/revit_add_in/revit-add-in-settings-button.service';import { OpenProjectFileUploadService } from 'core-app/core/file-upload/op-file-upload.service';import { OpenprojectEnterpriseModule } from 'core-app/features/enterprise/openproject-enterprise.module';import { MainMenuToggleComponent } from 'core-app/core/main-menu/main-menu-toggle.component';@@ -72,10 +83,18 @@ import { MainMenuNavigationService } from 'core-app/core/main-menu/main-menu-navimport { ConfirmDialogService } from 'core-app/shared/components/modals/confirm-dialog/confirm-dialog.service';import { ConfirmDialogModalComponent } from 'core-app/shared/components/modals/confirm-dialog/confirm-dialog.modal';import { DynamicContentModalComponent } from 'core-app/shared/components/modals/modal-wrapper/dynamic-content.modal';-import { PasswordConfirmationModalComponent } from 'core-app/shared/components/modals/request-for-confirmation/password-confirmation.modal';-import { WpPreviewModalComponent } from 'core-app/shared/components/modals/preview-modal/wp-preview-modal/wp-preview.modal';-import { OpHeaderProjectSelectComponent } from 'core-app/shared/components/header-project-select/header-project-select.component';-import { OpHeaderProjectSelectListComponent } from 'core-app/shared/components/header-project-select/list/header-project-select-list.component';+import {+ PasswordConfirmationModalComponent,+} from 'core-app/shared/components/modals/request-for-confirmation/password-confirmation.modal';+import {+ WpPreviewModalComponent,+} from 'core-app/shared/components/modals/preview-modal/wp-preview-modal/wp-preview.modal';+import {+ OpHeaderProjectSelectComponent,+} from 'core-app/shared/components/header-project-select/header-project-select.component';+import {+ OpHeaderProjectSelectListComponent,+} from 'core-app/shared/components/header-project-select/list/header-project-select-list.component';import { PaginationService } from 'core-app/shared/components/table-pagination/pagination-service';import { MainMenuResizerComponent } from 'core-app/shared/components/resizer/resizer/main-menu-resizer.component';@@ -86,14 +105,21 @@ import { globalDynamicComponents } from 'core-app/core/setup/global-dynamic-compimport { HookService } from 'core-app/features/plugins/hook-service';import { OpenprojectPluginsModule } from 'core-app/features/plugins/openproject-plugins.module';import { LinkedPluginsModule } from 'core-app/features/plugins/linked-plugins.module';-import { OpenProjectInAppNotificationsModule } from 'core-app/features/in-app-notifications/in-app-notifications.module';+import {+ OpenProjectInAppNotificationsModule,+} from 'core-app/features/in-app-notifications/in-app-notifications.module';import { OpenProjectBackupService } from './core/backup/op-backup.service';import { OpenProjectDirectFileUploadService } from './core/file-upload/op-direct-file-upload.service';import { OpenProjectStateModule } from 'core-app/core/state/openproject-state.module';-import { OpenprojectContentLoaderModule } from 'core-app/shared/components/op-content-loader/openproject-content-loader.module';+import {+ OpenprojectContentLoaderModule,+} from 'core-app/shared/components/op-content-loader/openproject-content-loader.module';import { OpenProjectHeaderInterceptor } from 'core-app/features/hal/http/openproject-header-interceptor';import { TopMenuService } from 'core-app/core/top-menu/top-menu.service';-import { A11yModule } from '@angular/cdk/a11y';+import { OpUploadService } from 'core-app/core/upload/upload.service';+import { ConfigurationService } from 'core-app/core/config/configuration.service';+import { FogUploadService } from 'core-app/core/upload/fog-upload.service';+import { LocalUploadService } from 'core-app/core/upload/local-upload.service';export function initializeServices(injector:Injector) {return () => {@@ -205,6 +231,12 @@ export function initializeServices(injector:Injector) {{provide: APP_INITIALIZER, useFactory: initializeServices, deps: [Injector], multi: true,},+ {+ provide: OpUploadService,+ useFactory: (config:ConfigurationService, http:HttpClient) =>+ (config.isDirectUploads() ? new FogUploadService(http) : new LocalUploadService(http)),+ deps: [ConfigurationService, HttpClient],+ },PaginationService,OpenProjectBackupService,OpenProjectFileUploadService,diff --git a/frontend/src/app/core/state/attachments/attachment.model.ts b/frontend/src/app/core/state/attachments/attachment.model.tsindex 9b1d8240c36..d58b4fdcf95 100644--- a/frontend/src/app/core/state/attachments/attachment.model.ts+++ b/frontend/src/app/core/state/attachments/attachment.model.ts@@ -28,7 +28,7 @@import { ID } from '@datorama/akita';import {- IFormattable,+ IFormattable, IHalMethodResourceLink,IHalResourceLink,IHalResourceLinks,} from 'core-app/core/state/hal-resource';@@ -43,6 +43,15 @@ export interface IAttachmentHalResourceLinks extends IHalResourceLinks {originOpen:IHalResourceLink;}+export interface IAddAttachmentLink extends IHalMethodResourceLink {+ form_fields:object;+}++export interface IAttachmentUploadHalResourceLinks extends IAttachmentHalResourceLinks {+ addAttachment:IAddAttachmentLink;+ completeUpload:IHalResourceLink;+}+export interface IAttachment {id:ID;title:string;@@ -51,8 +60,14 @@ export interface IAttachment {description:IFormattable;contentType:string;digest:string;-createdAt:string;-_links:IAttachmentHalResourceLinks;}++export interface IAttachmentUpload {+ id:ID;+ fileName:string;+ description:IFormattable;+ createdAt:string;+ _links:IAttachmentUploadHalResourceLinks;+}diff --git a/frontend/src/app/core/state/attachments/attachments.service.ts b/frontend/src/app/core/state/attachments/attachments.service.tsindex ec7d6c18b10..fb5ba78b2f8 100644--- a/frontend/src/app/core/state/attachments/attachments.service.ts+++ b/frontend/src/app/core/state/attachments/attachments.service.ts@@ -28,46 +28,42 @@import { Injectable } from '@angular/core';import {+ HttpErrorResponse,+ HttpEvent,HttpHeaders,} from '@angular/common/http';import { applyTransaction } from '@datorama/akita';-import {- from,- Observable,-} from 'rxjs';+import { Observable } from 'rxjs';import {catchError,map,tap,} from 'rxjs/operators';++import { I18nService } from 'core-app/core/i18n/i18n.service';+import { HalLink } from 'core-app/features/hal/hal-link/hal-link';+import { HalResource } from 'core-app/features/hal/resources/hal-resource';+import { ConfigurationService } from 'core-app/core/config/configuration.service';import { AttachmentsStore } from 'core-app/core/state/attachments/attachments.store';import { IAttachment } from 'core-app/core/state/attachments/attachment.model';import { IHALCollection } from 'core-app/core/apiv3/types/hal-collection.type';import { ToastService } from 'core-app/shared/components/toaster/toast.service';-import {- OpenProjectFileUploadService,- UploadFile,-} from 'core-app/core/file-upload/op-file-upload.service';-import { OpenProjectDirectFileUploadService } from 'core-app/core/file-upload/op-direct-file-upload.service';-import { I18nService } from 'core-app/core/i18n/i18n.service';-import { HalResource } from 'core-app/features/hal/resources/hal-resource';-import { HalLink } from 'core-app/features/hal/hal-link/hal-link';-import isNewResource, { HAL_NEW_RESOURCE_ID } from 'core-app/features/hal/helpers/is-new-resource';-import { ConfigurationService } from 'core-app/core/config/configuration.service';+import { IUploadFile, OpUploadService } from 'core-app/core/upload/upload.service';import { insertCollectionIntoState, removeEntityFromCollectionAndState } from 'core-app/core/state/collection-store';import {CollectionStore,ResourceCollectionService,} from 'core-app/core/state/resource-collection.service';import { InjectField } from 'core-app/shared/helpers/angular/inject-field.decorator';+import isNewResource, { HAL_NEW_RESOURCE_ID } from 'core-app/features/hal/helpers/is-new-resource';+import waitForUploadsFinished from 'core-app/core/upload/wait-for-uploads-finished';+import isNotNull from 'core-app/core/state/is-not-null';@Injectable()export class AttachmentsResourceService extends ResourceCollectionService<IAttachment> {@InjectField() I18n:I18nService;- @InjectField() fileUploadService:OpenProjectFileUploadService;-- @InjectField() directFileUploadService:OpenProjectDirectFileUploadService;+ @InjectField() uploadService:OpUploadService;@InjectField() configurationService:ConfigurationService;@@ -97,9 +93,9 @@ export class AttachmentsResourceService extends ResourceCollectionService<IAttac.get<IHALCollection<IAttachment>>(attachmentsSelfLink).pipe(tap((collection) => insertCollectionIntoState(this.store, collection, attachmentsSelfLink)),- catchError((error) => {+ catchError((error:HttpErrorResponse) => {this.toastService.addError(error);- throw error;+ throw new Error(error.message);}),);}@@ -117,9 +113,9 @@ export class AttachmentsResourceService extends ResourceCollectionService<IAttac.delete<void>(attachment._links.delete.href, { withCredentials: true, headers }).pipe(tap(() => removeEntityFromCollectionAndState(this.store, attachment.id, collectionKey)),- catchError((error) => {+ catchError((error:HttpErrorResponse) => {this.toastService.addError(error);- throw error;+ throw new Error(error.message);}),);}@@ -130,17 +126,15 @@ export class AttachmentsResourceService extends ResourceCollectionService<IAttac* @param resource The HAL resource to attach the files to* @param files The upload files to be attached.*/- attachFiles(resource:HalResource, files:UploadFile[]):Observable<IAttachment[]> {+ attachFiles(resource:HalResource, files:IUploadFile[]):Observable<IAttachment[]> {const identifier = AttachmentsResourceService.getAttachmentsSelfLink(resource) || HAL_NEW_RESOURCE_ID;const href = this.getUploadTarget(resource);- const isDirectUpload = !!this.getDirectUploadLink(resource);return this.addAttachments(identifier,href,files,- isDirectUpload,);}@@ -150,16 +144,14 @@ export class AttachmentsResourceService extends ResourceCollectionService<IAttac* @param collectionKey The identifier of the current attachment collection.* @param uploadHref The API target to perform the call against.* @param files The upload files to be attached.- * @param isDirectUpload whether the provided upload target is a direct upload URL.*/addAttachments(collectionKey:string,uploadHref:string,- files:UploadFile[],- isDirectUpload = false,+ files:IUploadFile[],):Observable<IAttachment[]> {return this- .uploadAttachments(uploadHref, files, isDirectUpload)+ .uploadAttachments(uploadHref, files).pipe(tap((attachments) => {applyTransaction(() => {@@ -180,24 +172,18 @@ export class AttachmentsResourceService extends ResourceCollectionService<IAttac);}- private uploadAttachments(href:string, files:UploadFile[], isDirectUpload:boolean):Observable<IAttachment[]> {- const { uploads, finished } = isDirectUpload- ? this.directFileUploadService.uploadAndMapResponse(href, files)- : this.fileUploadService.uploadAndMapResponse(href, files);+ private uploadAttachments(href:string, files:IUploadFile[]):Observable<IAttachment[]> {+ const observables = this.uploadService.upload<IAttachment>(href, files);+ const uploads = files.map((f, i):[File, Observable<HttpEvent<unknown>>] => [f.file, observables[i]]);- const message = this.I18n.t('js.label_upload_notification');- const notification = this.toastService.addAttachmentUpload(message, uploads);+ this.toastService.addUpload(this.I18n.t('js.label_upload_notification'), uploads);- return from(finished)+ return waitForUploadsFinished(observables).pipe(- tap(() => {- setTimeout(() => this.toastService.remove(notification), 700);- }),- map((result) => result.map(({ response }) => (response as HalResource).$source as IAttachment)),- catchError((error) => {- this.toastService.addError(error);- throw error;- }),+ map((responses) =>+ responses+ .map((response) => response.body)+ .filter(isNotNull)),);}diff --git a/frontend/src/app/core/upload/fog-upload.service.ts b/frontend/src/app/core/upload/fog-upload.service.tsnew file mode 100644index 00000000000..a557c0e8df9--- /dev/null+++ b/frontend/src/app/core/upload/fog-upload.service.ts@@ -0,0 +1,135 @@+// -- copyright+// OpenProject is an open source project management software.+// Copyright (C) 2012-2023 the OpenProject GmbH+//+// This program is free software; you can redistribute it and/or+// modify it under the terms of the GNU General Public License version 3.+//+// OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:+// Copyright (C) 2006-2013 Jean-Philippe Lang+// Copyright (C) 2010-2013 the ChiliProject Team+//+// This program is free software; you can redistribute it and/or+// modify it under the terms of the GNU General Public License+// as published by the Free Software Foundation; either version 2+// of the License, or (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU General Public License for more details.+//+// You should have received a copy of the GNU General Public License+// along with this program; if not, write to the Free Software+// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.+//+// See COPYRIGHT and LICENSE files for more details.+//++++import { getType } from 'mime';+import { Observable, of } from 'rxjs';+import { map, share, switchMap } from 'rxjs/operators';+import { HttpClient, HttpEvent, HttpEventType } from '@angular/common/http';++import { OpUploadService } from 'core-app/core/upload/upload.service';+import { AttachmentUploadFile } from 'core-app/core/upload/local-upload.service';+import { IAttachmentUpload } from 'core-app/core/state/attachments/attachment.model';+import { EXTERNAL_REQUEST_HEADER } from 'core-app/features/hal/http/openproject-header-interceptor';++interface PrepareUploadData {+ upload:{ href:string, method:string, form:FormData, };+ finishUrl:string;+}++export class FogUploadService extends OpUploadService {+ constructor(+ private readonly http:HttpClient,+ ) {+ super();+ }++ public upload<T>(+ href:string,+ uploadFiles:AttachmentUploadFile[],+ ):Observable<HttpEvent<T>>[] {+ return uploadFiles.map((file) => this.uploadSingle(href, file));+ }++ private uploadSingle<T>(href:string, uploadFile:AttachmentUploadFile):Observable<HttpEvent<T>> {+ return this.prepareUpload(href, uploadFile)+ .pipe(+ switchMap((data) =>+ this.performUpload(data.upload.href, data.upload.method, data.upload.form)+ .pipe(+ switchMap(this.finishUpload<T>(data.finishUrl)),+ )),+ share(),+ );+ }++ private prepareUpload(href:string, uploadFile:AttachmentUploadFile):Observable<PrepareUploadData> {+ const fileName = uploadFile.file.name;+ const contentType = (uploadFile.file.type || (fileName && getType(fileName)) || '' as string);+ const metadata = {+ fileName,+ contentType,+ description: uploadFile.description,+ fileSize: uploadFile.file.size,+ };++ const body = new FormData();+ body.append('metadata', JSON.stringify(metadata));++ return this.http.request<IAttachmentUpload>(+ 'post',+ href,+ {+ body,+ withCredentials: true,+ responseType: 'json',+ },+ ).pipe(+ map((response) => {+ const form = new FormData();+ const formFields = response._links.addAttachment.form_fields;+ Object.entries(formFields).forEach(([key, value]) => {+ form.append(key, value as string);+ });+ form.append('file', uploadFile.file, uploadFile.file.name);++ return {+ upload: {+ href: response._links.addAttachment.href,+ method: response._links.addAttachment.method,+ form,+ },+ finishUrl: response._links.completeUpload.href,+ };+ }),+ );+ }++ private performUpload(href:string, method:string, body:FormData):Observable<HttpEvent<string>> {+ return this.http.request(+ method,+ href,+ {+ body,+ observe: 'events',+ headers: { [EXTERNAL_REQUEST_HEADER]: 'true' },+ responseType: 'text',+ reportProgress: true,+ },+ );+ }++ private finishUpload<T>(href:string):(event:HttpEvent<string>) => Observable<HttpEvent<T>> {+ return (ev) => {+ if (ev.type === HttpEventType.Response) {+ return this.http.get<T>(href, { observe: 'response' });+ }++ return of(ev);+ };+ }+}diff --git a/frontend/src/app/core/upload/is-http-response.ts b/frontend/src/app/core/upload/is-http-response.tsnew file mode 100644index 00000000000..eccd41f4c1c--- /dev/null+++ b/frontend/src/app/core/upload/is-http-response.ts@@ -0,0 +1,33 @@+// -- copyright+// OpenProject is an open source project management software.+// Copyright (C) 2012-2023 the OpenProject GmbH+//+// This program is free software; you can redistribute it and/or+// modify it under the terms of the GNU General Public License version 3.+//+// OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:+// Copyright (C) 2006-2013 Jean-Philippe Lang+// Copyright (C) 2010-2013 the ChiliProject Team+//+// This program is free software; you can redistribute it and/or+// modify it under the terms of the GNU General Public License+// as published by the Free Software Foundation; either version 2+// of the License, or (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU General Public License for more details.+//+// You should have received a copy of the GNU General Public License+// along with this program; if not, write to the Free Software+// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.+//+// See COPYRIGHT and LICENSE files for more details.+//++++import { HttpEvent, HttpEventType, HttpResponse } from '@angular/common/http';++export default function isHttpResponse<T>(event:HttpEvent<T>):event is HttpResponse<T> {+ return event.type === HttpEventType.Response;+}diff --git a/frontend/src/app/core/upload/local-upload.service.ts b/frontend/src/app/core/upload/local-upload.service.tsnew file mode 100644index 00000000000..ab510a3b871--- /dev/null+++ b/frontend/src/app/core/upload/local-upload.service.ts@@ -0,0 +1,75 @@+// -- copyright+// OpenProject is an open source project management software.+// Copyright (C) 2012-2023 the OpenProject GmbH+//+// This program is free software; you can redistribute it and/or+// modify it under the terms of the GNU General Public License version 3.+//+// OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:+// Copyright (C) 2006-2013 Jean-Philippe Lang+// Copyright (C) 2010-2013 the ChiliProject Team+//+// This program is free software; you can redistribute it and/or+// modify it under the terms of the GNU General Public License+// as published by the Free Software Foundation; either version 2+// of the License, or (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU General Public License for more details.+//+// You should have received a copy of the GNU General Public License+// along with this program; if not, write to the Free Software+// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.+//+// See COPYRIGHT and LICENSE files for more details.+//++++import { Observable } from 'rxjs';+import { share } from 'rxjs/operators';+import { HttpClient, HttpEvent } from '@angular/common/http';++import { IUploadFile, OpUploadService } from 'core-app/core/upload/upload.service';++export interface AttachmentUploadFile extends IUploadFile {+ description?:string;+}++export class LocalUploadService extends OpUploadService {+ constructor(+ private readonly http:HttpClient,+ ) {+ super();+ }++ public upload<T>(+ href:string,+ uploadFiles:AttachmentUploadFile[],+ ):Observable<HttpEvent<T>>[] {+ return uploadFiles.map((file) => this.uploadSingle(href, file));+ }++ private uploadSingle<T>(href:string, uploadFile:AttachmentUploadFile):Observable<HttpEvent<T>> {+ const body = new FormData();+ const metadata = {+ description: uploadFile.description,+ fileName: uploadFile.file.name,+ };++ body.append('metadata', JSON.stringify(metadata));+ body.append('file', uploadFile.file, metadata.fileName);++ return this.http.request<T>(+ 'post',+ href,+ {+ body,+ observe: 'events',+ withCredentials: true,+ responseType: 'json',+ reportProgress: true,+ },+ ).pipe(share());+ }+}diff --git a/frontend/src/app/core/upload/wait-for-uploads-finished.ts b/frontend/src/app/core/upload/wait-for-uploads-finished.tsnew file mode 100644index 00000000000..2f50f60e16f--- /dev/null+++ b/frontend/src/app/core/upload/wait-for-uploads-finished.ts@@ -0,0 +1,39 @@+// -- copyright+// OpenProject is an open source project management software.+// Copyright (C) 2012-2023 the OpenProject GmbH+//+// This program is free software; you can redistribute it and/or+// modify it under the terms of the GNU General Public License version 3.+//+// OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:+// Copyright (C) 2006-2013 Jean-Philippe Lang+// Copyright (C) 2010-2013 the ChiliProject Team+//+// This program is free software; you can redistribute it and/or+// modify it under the terms of the GNU General Public License+// as published by the Free Software Foundation; either version 2+// of the License, or (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU General Public License for more details.+//+// You should have received a copy of the GNU General Public License+// along with this program; if not, write to the Free Software+// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.+//+// See COPYRIGHT and LICENSE files for more details.+//++++import { forkJoin, Observable } from 'rxjs';+import { filter } from 'rxjs/operators';+import { HttpEvent, HttpResponse } from '@angular/common/http';++import isHttpResponse from 'core-app/core/upload/is-http-response';++export default function waitForUploadsFinished<T>(uploads:Observable<HttpEvent<T>>[]):Observable<HttpResponse<T>[]> {+ return forkJoin(+ uploads.map((o) => o.pipe(filter(isHttpResponse))),+ );+}diff --git a/frontend/src/app/shared/components/attachments/attachments.component.ts b/frontend/src/app/shared/components/attachments/attachments.component.tsindex b191e3aaffa..8981144f77b 100644--- a/frontend/src/app/shared/components/attachments/attachments.component.ts+++ b/frontend/src/app/shared/components/attachments/attachments.component.ts@@ -41,15 +41,15 @@ import {import { Observable } from 'rxjs';import { filter, map, tap } from 'rxjs/operators';+import { States } from 'core-app/core/states/states.service';+import { I18nService } from 'core-app/core/i18n/i18n.service';import { HalResource } from 'core-app/features/hal/resources/hal-resource';import { HalResourceService } from 'core-app/features/hal/services/hal-resource.service';-import { I18nService } from 'core-app/core/i18n/i18n.service';-import { States } from 'core-app/core/states/states.service';import { UntilDestroyedMixin } from 'core-app/shared/helpers/angular/until-destroyed.mixin';import { populateInputsFromDataset } from 'core-app/shared/components/dataset-inputs';-import { UploadFile } from 'core-app/core/file-upload/op-file-upload.service';import { AttachmentsResourceService } from 'core-app/core/state/attachments/attachments.service';import { ToastService } from 'core-app/shared/components/toaster/toast.service';+import { IUploadFile, OpUploadService } from 'core-app/core/upload/upload.service';import { TimezoneService } from 'core-app/core/datetime/timezone.service';import { IAttachment } from 'core-app/core/state/attachments/attachment.model';import isNewResource from 'core-app/features/hal/helpers/is-new-resource';@@ -96,7 +96,7 @@ export class OpAttachmentsComponent extends UntilDestroyedMixin implements OnIni};private get attachmentsSelfLink():string {- const attachments = this.resource.attachments as unknown & { href:string };+ const attachments = this.resource.attachments as unknown&{ href:string };return attachments.href;}@@ -123,9 +123,10 @@ export class OpAttachmentsComponent extends UntilDestroyedMixin implements OnInipublic elementRef:ElementRef,protected readonly I18n:I18nService,protected readonly states:States,+ protected readonly toastService:ToastService,+ private readonly uploadService:OpUploadService,protected readonly halResourceService:HalResourceService,protected readonly attachmentsResourceService:AttachmentsResourceService,- protected readonly toastService:ToastService,protected readonly timezoneService:TimezoneService,protected readonly cdRef:ChangeDetectorRef,) {@@ -196,8 +197,7 @@ export class OpAttachmentsComponent extends UntilDestroyedMixin implements OnIniconst fileList = this.filePicker.nativeElement.files;if (fileList === null) return;- const files:UploadFile[] = Array.from(fileList);- this.uploadFiles(files);+ this.uploadFiles(Array.from(fileList));// reset file input, so that selecting the same file again triggers a changethis.filePicker.nativeElement.value = '';}@@ -208,15 +208,7 @@ export class OpAttachmentsComponent extends UntilDestroyedMixin implements OnIni// eslint-disable-next-line no-param-reassignevent.dataTransfer.dropEffect = 'copy';- const dfFiles = event.dataTransfer.files;- const length:number = dfFiles ? dfFiles.length : 0;-- const files:UploadFile[] = [];- for (let i = 0; i < length; i++) {- files.push(dfFiles[i]);- }-- this.uploadFiles(files);+ this.uploadFiles(Array.from(event.dataTransfer.files));this.draggingOverDropZone = false;this.dragging = 0;}@@ -233,12 +225,12 @@ export class OpAttachmentsComponent extends UntilDestroyedMixin implements OnInithis.draggingOverDropZone = false;}- protected uploadFiles(files:UploadFile[]):void {- let uploadFiles = files || [];+ protected uploadFiles(files:File[]):void {+ let filesWithoutFolders = files || [];const countBefore = files.length;- uploadFiles = this.filterFolders(uploadFiles);+ filesWithoutFolders = this.filterFolders(filesWithoutFolders);- if (uploadFiles.length === 0) {+ if (filesWithoutFolders.length === 0) {// If we filtered all files as directories, show a noticeif (countBefore > 0) {this.toastService.addNotice(this.text.foldersWarning);@@ -247,6 +239,8 @@ export class OpAttachmentsComponent extends UntilDestroyedMixin implements OnInireturn;}+ const uploadFiles:IUploadFile[] = filesWithoutFolders.map((file) => ({ file }));+this.attachmentsResourceService.attachFiles(this.resource, uploadFiles)@@ -258,7 +252,7 @@ export class OpAttachmentsComponent extends UntilDestroyedMixin implements OnIni* or empty file sizes.* @param files*/- protected filterFolders(files:UploadFile[]):UploadFile[] {+ protected filterFolders(files:File[]):File[] {return files.filter((file) => {// Folders never have a mime typeif (file.type !== '') {diff --git a/frontend/src/app/shared/components/storages/storage/interfaces.ts b/frontend/src/app/shared/components/storages/storage/interfaces.tsindex c11d245d5a0..96c66ff0c9d 100644--- a/frontend/src/app/shared/components/storages/storage/interfaces.ts+++ b/frontend/src/app/shared/components/storages/storage/interfaces.ts@@ -38,8 +38,3 @@ export interface LocationData {location:string;files:IStorageFile[];}--export interface FileUploadResponse {- file_name:string;- file_id:number;-}diff --git a/frontend/src/app/shared/components/storages/storage/storage.component.ts b/frontend/src/app/shared/components/storages/storage/storage.component.tsindex 81a77cd8a2d..d9a47813a48 100644--- a/frontend/src/app/shared/components/storages/storage/storage.component.ts+++ b/frontend/src/app/shared/components/storages/storage/storage.component.ts@@ -39,8 +39,6 @@ import {import {HttpClient,HttpErrorResponse,- HttpEventType,- HttpResponse,} from '@angular/common/http';import {BehaviorSubject,@@ -73,7 +71,6 @@ import {import { CurrentUserService } from 'core-app/core/current-user/current-user.service';import { UntilDestroyedMixin } from 'core-app/shared/helpers/angular/until-destroyed.mixin';import { I18nService } from 'core-app/core/i18n/i18n.service';-import isNewResource from 'core-app/features/hal/helpers/is-new-resource';import { StorageActionButton } from 'core-app/shared/components/storages/storage-information/storage-action-button';import {StorageInformationBox,@@ -97,12 +94,15 @@ import {UploadConflictModalComponent,} from 'core-app/shared/components/storages/upload-conflict-modal/upload-conflict-modal.component';import {+ NextcloudFileUploadResponse,NextcloudUploadFile,NextcloudUploadService,} from 'core-app/shared/components/storages/upload/nextcloud-upload.service';-import { FileUploadResponse, LocationData, UploadData } from 'core-app/shared/components/storages/storage/interfaces';+import { LocationData, UploadData } from 'core-app/shared/components/storages/storage/interfaces';import isNotNull from 'core-app/core/state/is-not-null';import compareId from 'core-app/core/state/compare-id';+import isHttpResponse from 'core-app/core/upload/is-http-response';+import isNewResource from 'core-app/features/hal/helpers/is-new-resource';@Component({selector: 'op-storage',@@ -401,16 +401,16 @@ export class StorageComponent extends UntilDestroyedMixin implements OnInit, OnD}}- private uploadAndNotify(link:IUploadLink, file:File, overwrite:boolean|null):Observable<FileUploadResponse> {+ private uploadAndNotify(link:IUploadLink, file:File, overwrite:boolean|null):Observable<NextcloudFileUploadResponse> {const { href } = link._links.destination;const uploadFiles:NextcloudUploadFile[] = [{ file, overwrite }];- const observable = this.uploadService.upload<FileUploadResponse>(href, uploadFiles)[0];+ const observable = this.uploadService.upload<NextcloudFileUploadResponse>(href, uploadFiles)[0];this.toastService.addUpload(this.text.toast.uploadingLabel, [[file, observable]]);return observable.pipe(- filter((ev) => ev.type === HttpEventType.Response),- map((ev:HttpResponse<FileUploadResponse>) => ev.body),+ filter(isHttpResponse),+ map((ev) => ev.body),map((data) => {if (data === null) {throw new Error('Upload data is null.');@@ -421,7 +421,7 @@ export class StorageComponent extends UntilDestroyedMixin implements OnInit, OnD);}- private createFileLinkData(file:File, response:FileUploadResponse):Observable<IFileLinkOriginData|null> {+ private createFileLinkData(file:File, response:NextcloudFileUploadResponse):Observable<IFileLinkOriginData|null> {return this.fileLinks$.pipe(take(1),diff --git a/frontend/src/app/shared/components/toaster/toast.service.ts b/frontend/src/app/shared/components/toaster/toast.service.tsindex ac36bc40db5..48bf8e6ddad 100644--- a/frontend/src/app/shared/components/toaster/toast.service.ts+++ b/frontend/src/app/shared/components/toaster/toast.service.ts@@ -26,15 +26,16 @@// See COPYRIGHT and LICENSE files for more details.//++-import { forkJoin, Observable } from 'rxjs';-import { filter, take } from 'rxjs/operators';+import { Observable } from 'rxjs';+import { take } from 'rxjs/operators';import { input, State } from 'reactivestates';import { Injectable } from '@angular/core';-import { HttpErrorResponse, HttpEvent, HttpEventType } from '@angular/common/http';+import { HttpErrorResponse, HttpEvent } from '@angular/common/http';import { I18nService } from 'core-app/core/i18n/i18n.service';import { ConfigurationService } from 'core-app/core/config/configuration.service';import { UploadInProgress } from 'core-app/core/file-upload/op-file-upload.service';+import waitForUploadsFinished from 'core-app/core/upload/wait-for-uploads-finished';import {IHalErrorBase,IHalMultipleError,@@ -144,15 +145,14 @@ export class ToastService {return this.add(this.createAttachmentUploadToast(message, uploads));}- public addUpload(message:string, uploads:[[File, Observable<HttpEvent<unknown>>]]):IToast {+ public addUpload(message:string, uploads:[File, Observable<HttpEvent<unknown>>][]):IToast {const notification = this.add({data: uploads,type: 'upload',message,});- const observables = uploads.map((o) => o[1].pipe(filter((ev) => ev.type === HttpEventType.Response)));- forkJoin(observables)+ waitForUploadsFinished(uploads.map((o) => o[1])).pipe(take(1)).subscribe(() => {setTimeout(() => this.remove(notification), 700);diff --git a/frontend/src/app/shared/components/toaster/upload-progress.component.ts b/frontend/src/app/shared/components/toaster/upload-progress.component.tsindex 044b3d4d916..6d414fb82d9 100644--- a/frontend/src/app/shared/components/toaster/upload-progress.component.ts+++ b/frontend/src/app/shared/components/toaster/upload-progress.component.ts@@ -44,6 +44,7 @@ import {HttpProgressEvent,} from '@angular/common/http';import { BehaviorSubject, combineLatest, Observable } from 'rxjs';+import { debugLog } from 'core-app/shared/helpers/debug_output';import { UntilDestroyedMixin } from 'core-app/shared/helpers/angular/until-destroyed.mixin';@@ -115,6 +116,10 @@ export class UploadProgressComponent extends UntilDestroyedMixin implements OnInthis.completed = true;this.uploadSuccess.emit();break;+ case HttpEventType.DownloadProgress:+ case HttpEventType.ResponseHeader:+ /* do nothing */+ break;default:console.warn(`unknown event type: ${evt.type}`);}diff --git a/frontend/src/app/shared/helpers/images/resizer.ts b/frontend/src/app/shared/helpers/images/resizer.tsindex 178c5551a2d..b5b01e3de7f 100644--- a/frontend/src/app/shared/helpers/images/resizer.ts+++ b/frontend/src/app/shared/helpers/images/resizer.ts@@ -47,16 +47,16 @@ export function resizeImage(maxSize:number, image:HTMLImageElement):[string, Upl/*** Resize a file input to the given max dimension, returning the data URL and a blob*- * @param {maxSize} Max width or height- * @param {File} Input file+ * @param maxSize Max width or height+ * @param file Input file*/export function resizeFile(maxSize:number, file:File):Promise<[string, UploadBlob]> {return new Promise((resolve) => {const reader = new FileReader();- reader.onload = (readerEvent:any) => {+ reader.onload = (readerEvent:ProgressEvent<FileReader>) => {const image = new Image();image.onload = () => resolve(resizeImage(maxSize, image));- image.src = readerEvent.target.result;+ image.src = readerEvent.target?.result as string;};reader.readAsDataURL(file);});diff --git a/modules/avatars/frontend/module/avatar-upload-form/avatar-upload-form.component.ts b/modules/avatars/frontend/module/avatar-upload-form/avatar-upload-form.component.tsindex 7a074dda269..bbeb36e5cf8 100644--- a/modules/avatars/frontend/module/avatar-upload-form/avatar-upload-form.component.ts+++ b/modules/avatars/frontend/module/avatar-upload-form/avatar-upload-form.component.ts@@ -1,4 +1,4 @@-//-- copyright+// -- copyright// OpenProject is an open source project management software.// Copyright (C) 2012-2023 the OpenProject GmbH//@@ -25,29 +25,46 @@//// See COPYRIGHT and LICENSE files for more details.//++-import { Component, ElementRef, OnInit, ViewChild } from "@angular/core";-import { OpenProjectFileUploadService, UploadFile } from "core-app/core/file-upload/op-file-upload.service";-import { resizeFile } from "core-app/shared/helpers/images/resizer";-import { I18nService } from "core-app/core/i18n/i18n.service";-import { ToastService } from "core-app/shared/components/toaster/toast.service";++import {+ ChangeDetectionStrategy,+ ChangeDetectorRef,+ Component,+ ElementRef,+ OnInit,+ ViewChild,+} from '@angular/core';++import { resizeFile } from 'core-app/shared/helpers/images/resizer';+import { I18nService } from 'core-app/core/i18n/i18n.service';+import { ToastService } from 'core-app/shared/components/toaster/toast.service';+import { OpUploadService } from 'core-app/core/upload/upload.service';++import { AvatarUploadFile, AvatarUploadService } from '../avatar-upload.service';+import { HttpErrorResponse } from '@angular/common/http';@Component({selector: 'avatar-upload-form',- templateUrl: './avatar-upload-form.html'+ templateUrl: './avatar-upload-form.html',+ providers: [{ provide: OpUploadService, useClass: AvatarUploadService }],+ changeDetection: ChangeDetectionStrategy.OnPush,})export class AvatarUploadFormComponent implements OnInit {- // Form targetspublic form:any;+public target:string;+public method:string;- // File- public avatarFile:any;- public avatarPreviewUrl:any;+ public avatarFile:File;++ public avatarPreviewUrl:string;+public busy = false;+public fileInvalid = false;- @ViewChild('avatarFilePicker', { static: true }) public avatarFilePicker:ElementRef;+ @ViewChild('avatarFilePicker', { static: true }) public avatarFilePicker:ElementRef<HTMLInputElement>;// Textpublic text = {@@ -57,68 +74,70 @@ export class AvatarUploadFormComponent implements OnInit {wrong_file_format: this.I18n.t('js.avatars.wrong_file_format'),button_update: this.I18n.t('js.button_update'),uploading: this.I18n.t('js.avatars.uploading_avatar'),- preview: this.I18n.t('js.label_preview')+ preview: this.I18n.t('js.label_preview'),};- public constructor(protected I18n:I18nService,- protected elementRef:ElementRef,- protected toastService:ToastService,- protected opFileUpload:OpenProjectFileUploadService) {- }+ public constructor(+ protected I18n:I18nService,+ protected elementRef:ElementRef,+ protected cdRef:ChangeDetectorRef,+ protected toastService:ToastService,+ protected uploadService:OpUploadService,+ ) { }public ngOnInit() {- const element = this.elementRef.nativeElement;- this.target = element.getAttribute('target');- this.method = element.getAttribute('method');+ const element = this.elementRef.nativeElement as HTMLElement;+ this.target = element.getAttribute('target') || '';+ this.method = element.getAttribute('method') || '';}public onFilePickerChanged(_evt:Event) {- const files:UploadFile[] = Array.from(this.avatarFilePicker.nativeElement.files);- if (files.length === 0) {+ const fileList = this.avatarFilePicker.nativeElement.files;+ if (fileList === null || fileList.length === 0) {return;}- const file = files[0];+ const file = fileList[0];if (['image/jpeg', 'image/png', 'image/gif'].indexOf(file.type) === -1) {this.fileInvalid = true;+ this.cdRef.detectChanges();return;}- resizeFile(128, file).then(([dataURL, blob]) => {+ void resizeFile(128, file).then(([dataURL, blob]) => {// Create resized file- blob.name = file.name;- this.avatarFile = blob;+ this.avatarFile = new File([blob], file.name);this.avatarPreviewUrl = dataURL;+ this.fileInvalid = false;+ this.cdRef.detectChanges();});}- public uploadAvatar(evt:Event) {- evt.preventDefault();+ public uploadAvatar(event:Event) {+ event.preventDefault();this.busy = true;- const upload = this.opFileUpload.uploadSingle(this.target, this.avatarFile, this.method, 'text');- this.toastService.addAttachmentUpload(this.text.uploading, [upload]);-- upload[1].subscribe(- (evt:any) => {- switch (evt.type) {- case 0: // Sent- return;-- case 4:- this.avatarFile.progress = 100;- this.busy = false;- window.location.reload();- return;-- default:+ const uploadFile:AvatarUploadFile = { file: this.avatarFile, method: this.method };+ const observable = this.uploadService.upload<string>(this.target, [uploadFile])[0];+ this.toastService.addUpload(this.text.uploading, [[this.avatarFile, observable]]);++ observable.subscribe(+ (ev) => {+ switch (ev.type) {+ case 0:+ // Sent+ break;+ case 4:+ this.busy = false;+ window.location.reload();+ break;+ default:// Sent or unknown event- return;}},- (error:any) => {+ (error:HttpErrorResponse) => {this.toastService.addError(error);this.busy = false;- }+ },);}}diff --git a/modules/avatars/frontend/module/avatar-upload.service.ts b/modules/avatars/frontend/module/avatar-upload.service.tsnew file mode 100644index 00000000000..38071731bd5--- /dev/null+++ b/modules/avatars/frontend/module/avatar-upload.service.ts@@ -0,0 +1,72 @@+// -- copyright+// OpenProject is an open source project management software.+// Copyright (C) 2012-2023 the OpenProject GmbH+//+// This program is free software; you can redistribute it and/or+// modify it under the terms of the GNU General Public License version 3.+//+// OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:+// Copyright (C) 2006-2013 Jean-Philippe Lang+// Copyright (C) 2010-2013 the ChiliProject Team+//+// This program is free software; you can redistribute it and/or+// modify it under the terms of the GNU General Public License+// as published by the Free Software Foundation; either version 2+// of the License, or (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU General Public License for more details.+//+// You should have received a copy of the GNU General Public License+// along with this program; if not, write to the Free Software+// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.+//+// See COPYRIGHT and LICENSE files for more details.+//++++import { Observable } from 'rxjs';+import { share } from 'rxjs/operators';+import { Injectable } from '@angular/core';+import { HttpClient, HttpEvent } from '@angular/common/http';++import { IUploadFile, OpUploadService } from 'core-app/core/upload/upload.service';++export interface AvatarUploadFile extends IUploadFile {+ method:string;+}++@Injectable()+export class AvatarUploadService extends OpUploadService {+ constructor(+ private readonly http:HttpClient,+ ) {+ super();+ }++ public upload<T>(+ href:string,+ uploadFiles:AvatarUploadFile[],+ ):Observable<HttpEvent<T>>[] {+ return uploadFiles.map((file) => this.uploadSingle(href, file));+ }++ private uploadSingle<T>(href:string, uploadFile:AvatarUploadFile):Observable<HttpEvent<T>> {+ const body = new FormData();+ body.append('metadata', JSON.stringify({ fileName: uploadFile.file.name }));+ body.append('file', uploadFile.file, uploadFile.file.name);++ return this.http.request(+ uploadFile.method,+ href,+ {+ body,+ observe: 'events',+ withCredentials: true,+ responseType: 'text',+ reportProgress: true,+ },+ ).pipe(share()) as Observable<HttpEvent<T>>;+ }+}