Skip to content

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

[#47501] Open file picker based on project folder from database

Eric Schubertc455e79743bc
diff --git a/frontend/src/app/core/state/project-storages/project-storages.service.ts b/frontend/src/app/core/state/project-storages/project-storages.service.ts
index 9100ff26ef0..de2f7f05ded 100644
--- a/frontend/src/app/core/state/project-storages/project-storages.service.ts
+++ b/frontend/src/app/core/state/project-storages/project-storages.service.ts
@@ -28,16 +28,13 @@
import { Injectable } from '@angular/core';
-import {
- CollectionStore,
- ResourceCollectionService,
-} from 'core-app/core/state/resource-collection.service';
import { IProjectStorage } from 'core-app/core/state/project-storages/project-storage.model';
import { ProjectStoragesStore } from 'core-app/core/state/project-storages/project-storages.store';
+import { ResourceStore, ResourceStoreService } from 'core-app/core/state/resource-store.service';
@Injectable()
-export class ProjectStoragesResourceService extends ResourceCollectionService<IProjectStorage> {
- protected createStore():CollectionStore<IProjectStorage> {
+export class ProjectStoragesResourceService extends ResourceStoreService<IProjectStorage> {
+ protected createStore():ResourceStore<IProjectStorage> {
return new ProjectStoragesStore();
}
diff --git a/frontend/src/app/core/state/project-storages/project-storages.store.ts b/frontend/src/app/core/state/project-storages/project-storages.store.ts
index 65ebd76a470..2d68cb90bda 100644
--- a/frontend/src/app/core/state/project-storages/project-storages.store.ts
+++ b/frontend/src/app/core/state/project-storages/project-storages.store.ts
@@ -29,13 +29,13 @@
import { EntityStore, StoreConfig } from '@datorama/akita';
import { IProjectStorage } from 'core-app/core/state/project-storages/project-storage.model';
-import { CollectionState, createInitialCollectionState } from 'core-app/core/state/collection-store';
+import { createInitialResourceState, ResourceState } from 'core-app/core/state/resource-store';
-export interface ProjectStoragesState extends CollectionState<IProjectStorage> {}
+export interface ProjectStoragesState extends ResourceState<IProjectStorage> {}
@StoreConfig({ name: 'project-storages' })
export class ProjectStoragesStore extends EntityStore<ProjectStoragesState> {
constructor() {
- super(createInitialCollectionState());
+ super(createInitialResourceState());
}
}
diff --git a/frontend/src/app/core/state/projects/projects.service.ts b/frontend/src/app/core/state/projects/projects.service.ts
index bfd2dab8f89..a28ef56f8ea 100644
--- a/frontend/src/app/core/state/projects/projects.service.ts
+++ b/frontend/src/app/core/state/projects/projects.service.ts
@@ -27,8 +27,6 @@
//++
import { Injectable } from '@angular/core';
-import { tap } from 'rxjs/operators';
-import { Observable } from 'rxjs';
import { IProject } from './project.model';
import {
ResourceStore,
@@ -38,15 +36,6 @@ import { ProjectsStore } from 'core-app/core/state/projects/projects.store';
@Injectable()
export class ProjectsResourceService extends ResourceStoreService<IProject> {
- update(link:string):Observable<IProject> {
- return this.http.get<IProject>(link)
- .pipe(
- tap((project) => {
- this.store.upsertMany([project]);
- }),
- );
- }
-
protected createStore():ResourceStore<IProject> {
return new ProjectsStore();
}
diff --git a/frontend/src/app/core/state/resource-store.service.ts b/frontend/src/app/core/state/resource-store.service.ts
index df04c04ecd3..c46175bf8f5 100644
--- a/frontend/src/app/core/state/resource-store.service.ts
+++ b/frontend/src/app/core/state/resource-store.service.ts
@@ -115,12 +115,17 @@ export abstract class ResourceStoreService<T extends { id:ID }> {
* @param href {string}
*/
public requireEntity(href:string):Observable<T> {
+ console.warn('REQUIRE');
+ console.warn(href);
const id = idFromLink(href);
if (this.query.hasEntity(id) || this.resourceLoading(href)) {
return this.lookup(id);
}
- return this.fetchEntity(href);
+ return this.fetchEntity(href)
+ .pipe(
+ switchMap(() => this.lookup(id)),
+ );
}
/**
diff --git a/frontend/src/app/features/work-packages/components/wp-single-view-tabs/files-tab/op-files-tab.component.html b/frontend/src/app/features/work-packages/components/wp-single-view-tabs/files-tab/op-files-tab.component.html
index dba8e7c7c68..493cd32e447 100644
--- a/frontend/src/app/features/work-packages/components/wp-single-view-tabs/files-tab/op-files-tab.component.html
+++ b/frontend/src/app/features/work-packages/components/wp-single-view-tabs/files-tab/op-files-tab.component.html
@@ -18,14 +18,13 @@
</section>
<section
- *ngFor="let sec of storageSections$ | async"
+ *ngFor="let storage of projectStorages | async"
data-qa-selector="op-tab-content--tab-section"
class="op-tab-content--tab-section"
>
<op-storage
[resource]="workPackage"
- [storage]="sec.storage | async"
- [projectStorage]="sec.projectStorage"
+ [projectStorage]="storage"
[allowUploading]="allowManageFileLinks$ | async"
[allowLinking]="allowManageFileLinks$ | async"
></op-storage>
diff --git a/frontend/src/app/features/work-packages/components/wp-single-view-tabs/files-tab/op-files-tab.component.ts b/frontend/src/app/features/work-packages/components/wp-single-view-tabs/files-tab/op-files-tab.component.ts
index 6b379cfb157..ab1a0f6eabc 100644
--- a/frontend/src/app/features/work-packages/components/wp-single-view-tabs/files-tab/op-files-tab.component.ts
+++ b/frontend/src/app/features/work-packages/components/wp-single-view-tabs/files-tab/op-files-tab.component.ts
@@ -35,10 +35,8 @@ import { I18nService } from 'core-app/core/i18n/i18n.service';
import { HookService } from 'core-app/features/plugins/hook-service';
import { CurrentUserService } from 'core-app/core/current-user/current-user.service';
import { StoragesResourceService } from 'core-app/core/state/storages/storages.service';
-import { IStorage } from 'core-app/core/state/storages/storage.model';
import { HalResource } from 'core-app/features/hal/resources/hal-resource';
import { ProjectStoragesResourceService } from 'core-app/core/state/project-storages/project-storages.service';
-import idFromLink from 'core-app/features/hal/helpers/id-from-link';
import { IProjectStorage } from 'core-app/core/state/project-storages/project-storage.model';
@Component({
@@ -57,7 +55,7 @@ export class WorkPackageFilesTabComponent implements OnInit {
showAttachmentHeader$:Observable<boolean>;
- storageSections$:Observable<{ projectStorage:IProjectStorage, storage:Observable<IStorage> }[]>;
+ projectStorages:Observable<IProjectStorage[]>;
allowManageFileLinks$:Observable<boolean>;
@@ -77,15 +75,9 @@ export class WorkPackageFilesTabComponent implements OnInit {
const canViewFileLinks = this.currentUserService.hasCapabilities$('file_links/view', project.id);
- this.storageSections$ = this.projectStoragesResourceService.require({ filters: [['projectId', '=', [project.id]]] })
- .pipe(
- map((projectStorages) =>
- projectStorages
- .map((ps) => ({
- projectStorage: ps,
- storage: this.storagesResourceService.lookup(idFromLink(ps._links.storage.href)),
- }))),
- );
+ this.projectStorages = this
+ .projectStoragesResourceService
+ .requireCollection({ filters: [['projectId', '=', [project.id]]] });
this.allowManageFileLinks$ = this
.currentUserService
@@ -93,7 +85,7 @@ export class WorkPackageFilesTabComponent implements OnInit {
this.showAttachmentHeader$ = combineLatest(
[
- this.storageSections$,
+ this.projectStorages,
canViewFileLinks,
],
).pipe(
diff --git a/frontend/src/app/features/work-packages/components/wp-single-view/wp-single-view.component.html b/frontend/src/app/features/work-packages/components/wp-single-view/wp-single-view.component.html
index f6cd3d6c6be..c093da2e085 100644
--- a/frontend/src/app/features/work-packages/components/wp-single-view/wp-single-view.component.html
+++ b/frontend/src/app/features/work-packages/components/wp-single-view/wp-single-view.component.html
@@ -145,10 +145,9 @@
</div>
<op-storage
- *ngFor="let sec of storageSections$ | async"
+ *ngFor="let storage of projectStorages | async"
[resource]="workPackage"
- [storage]="sec.storage | async"
- [projectStorage]="sec.projectStorage"
+ [projectStorage]="storage"
[allowLinking]="true"
[allowUploading]="true"
></op-storage>
diff --git a/frontend/src/app/features/work-packages/components/wp-single-view/wp-single-view.component.ts b/frontend/src/app/features/work-packages/components/wp-single-view/wp-single-view.component.ts
index cc52eb0ac95..0dfc0d4b658 100644
--- a/frontend/src/app/features/work-packages/components/wp-single-view/wp-single-view.component.ts
+++ b/frontend/src/app/features/work-packages/components/wp-single-view/wp-single-view.component.ts
@@ -39,14 +39,11 @@ import { StateService } from '@uirouter/core';
import {
BehaviorSubject,
combineLatest,
- Observable,
- of,
} from 'rxjs';
import {
distinctUntilChanged,
first,
map,
- switchMap,
} from 'rxjs/operators';
import { I18nService } from 'core-app/core/i18n/i18n.service';
@@ -67,15 +64,13 @@ import { CurrentProjectService } from 'core-app/core/current-project/current-pro
import { States } from 'core-app/core/states/states.service';
import { SchemaCacheService } from 'core-app/core/schemas/schema-cache.service';
import { debugLog } from 'core-app/shared/helpers/debug_output';
-import { IStorage } from 'core-app/core/state/storages/storage.model';
-import { StoragesResourceService } from 'core-app/core/state/storages/storages.service';
import { ProjectsResourceService } from 'core-app/core/state/projects/projects.service';
import { CurrentUserService } from 'core-app/core/current-user/current-user.service';
import { HalResource } from 'core-app/features/hal/resources/hal-resource';
-import idFromLink from 'core-app/features/hal/helpers/id-from-link';
-import isNewResource from 'core-app/features/hal/helpers/is-new-resource';
import { ProjectStoragesResourceService } from 'core-app/core/state/project-storages/project-storages.service';
import { IProjectStorage } from 'core-app/core/state/project-storages/project-storage.model';
+import idFromLink from 'core-app/features/hal/helpers/id-from-link';
+import isNewResource from 'core-app/features/hal/helpers/is-new-resource';
export interface FieldDescriptor {
name:string;
@@ -155,8 +150,7 @@ export class WorkPackageSingleViewComponent extends UntilDestroyedMixin implemen
$element:JQuery;
- // storages$ = new BehaviorSubject<IStorage[]>([]);
- storageSections$ = new BehaviorSubject<{ projectStorage:IProjectStorage, storage:Observable<IStorage> }[]>([]);
+ projectStorages = new BehaviorSubject<IProjectStorage[]>([]);
constructor(
protected readonly injector:Injector,
@@ -172,7 +166,6 @@ export class WorkPackageSingleViewComponent extends UntilDestroyedMixin implemen
private readonly halEditing:HalResourceEditingService,
private readonly halResourceService:HalResourceService,
private readonly currentUserService:CurrentUserService,
- private readonly storagesService:StoragesResourceService,
private readonly displayFieldService:DisplayFieldService,
private readonly projectsResourceService:ProjectsResourceService,
private readonly projectStoragesService:ProjectStoragesResourceService,
@@ -241,35 +234,26 @@ export class WorkPackageSingleViewComponent extends UntilDestroyedMixin implemen
}
if (resource.project === null) {
- this.storageSections$.next([]);
+ this.projectStorages.next([]);
} else {
const project = resource.project as unknown&{ href:string, id:string };
combineLatest([
- this.projectsResourceService.update(project.href),
- this.projectStoragesService.require({ filters: [['projectId', '=', [project.id]]] }),
+ this.projectsResourceService.requireEntity(project.href),
+ this.projectStoragesService.requireCollection({ filters: [['projectId', '=', [project.id]]] }),
this.currentUserService.hasCapabilities$('file_links/manage', project.id),
])
.pipe(
- switchMap(([p, projectStorages, manageFileLinks]) => {
+ map(([p, projectStorages, manageFileLinks]) => {
if (!p._links.storages || !manageFileLinks) {
- return of([]);
+ return [];
}
- return this.storagesService
- .updateCollection(p._links.self.href, p._links.storages)
- .pipe(
- map(() =>
- projectStorages
- .map((ps) => ({
- projectStorage: ps,
- storage: this.storagesService.lookup(idFromLink(ps._links.storage.href)),
- }))),
- );
+ return projectStorages;
}),
first(),
)
- .subscribe((storages) => {
- this.storageSections$.next(storages);
+ .subscribe((ps) => {
+ this.projectStorages.next(ps);
});
}
}
@@ -478,4 +462,6 @@ export class WorkPackageSingleViewComponent extends UntilDestroyedMixin implemen
}
return this.schemaCache.of(resource);
}
+
+ protected readonly structuredClone = structuredClone;
}
diff --git a/frontend/src/app/features/work-packages/routing/wp-view-base/work-package-single-view.base.ts b/frontend/src/app/features/work-packages/routing/wp-view-base/work-package-single-view.base.ts
index a26ca6a2f44..f846153b12b 100644
--- a/frontend/src/app/features/work-packages/routing/wp-view-base/work-package-single-view.base.ts
+++ b/frontend/src/app/features/work-packages/routing/wp-view-base/work-package-single-view.base.ts
@@ -163,7 +163,7 @@ export class WorkPackageSingleViewBase extends UntilDestroyedMixin {
// lazy load the work package's project, needed when initializing
// the work package resource from split view.
this.projectsResourceService
- .update((this.workPackage.$links.project as HalResource).href as string)
+ .requireEntity((this.workPackage.$links.project as HalResource).href as string)
.subscribe(
() => {},
(error:HttpErrorResponse) => {
@@ -190,20 +190,10 @@ export class WorkPackageSingleViewBase extends UntilDestroyedMixin {
if (this.workPackage.$links.fileLinks) {
this.fileLinkResourceService
.updateCollectionsForWorkPackage(this.workPackage.$links.fileLinks.href as string)
- .pipe(
- this.untilDestroyed(),
- switchMap(() => this.projectsResourceService.lookup((this.workPackage.project as unknown&{ id:string }).id)),
- take(1),
- )
+ .pipe(take(1))
.subscribe(
- (project) => {
- if (project._links.storages) {
- this.storages.updateCollection(project._links.self.href, project._links.storages).subscribe();
- }
- },
- (error:HttpErrorResponse) => {
- this.toastService.addError(error);
- },
+ () => { /* Do nothing */ },
+ (error:HttpErrorResponse) => { this.toastService.addError(error); },
);
}
diff --git a/frontend/src/app/shared/components/storages/functions/storages.functions.ts b/frontend/src/app/shared/components/storages/functions/storages.functions.ts
index a173f9e393f..5a339105cb4 100644
--- a/frontend/src/app/shared/components/storages/functions/storages.functions.ts
+++ b/frontend/src/app/shared/components/storages/functions/storages.functions.ts
@@ -33,6 +33,7 @@ import {
} from 'core-app/shared/components/storages/icons.mapping';
import { IHalResourceLink } from 'core-app/core/state/hal-resource';
import { IFileLinkOriginData } from 'core-app/core/state/file-links/file-link.model';
+import { nextcloud } from 'core-app/shared/components/storages/storages-constants.const';
export function isDirectory(originData:IFileLinkOriginData):boolean {
return originData.mimeType === 'application/x-op-directory';
@@ -62,3 +63,12 @@ export function makeFilesCollectionLink(storageLink:IHalResourceLink, location:s
title: 'Storage files',
};
}
+
+const storageTypeMap:Record<string, string> = {
+ [nextcloud]: 'js.storages.types.nextcloud',
+ default: 'js.storages.types.default',
+};
+
+export function storageLocaleString(storageTypeUrn:string) {
+ return storageTypeMap[storageTypeUrn] || storageTypeMap.default;
+}
diff --git a/frontend/src/app/shared/components/storages/openproject-storages.module.ts b/frontend/src/app/shared/components/storages/openproject-storages.module.ts
index a55edac9522..e17b7569e98 100644
--- a/frontend/src/app/shared/components/storages/openproject-storages.module.ts
+++ b/frontend/src/app/shared/components/storages/openproject-storages.module.ts
@@ -57,6 +57,9 @@ import {
import {
UploadConflictModalComponent,
} from 'core-app/shared/components/storages/upload-conflict-modal/upload-conflict-modal.component';
+import {
+ StorageInformationService,
+} from 'core-app/shared/components/storages/storage-information/storage-information.service';
@NgModule({
imports: [
@@ -82,6 +85,7 @@ import {
providers: [
SortFilesPipe,
CookieService,
+ StorageInformationService,
],
})
export class OpenprojectStoragesModule {}
diff --git a/frontend/src/app/shared/components/storages/storage-information/storage-information.service.ts b/frontend/src/app/shared/components/storages/storage-information/storage-information.service.ts
new file mode 100644
index 00000000000..6472ef48262
--- /dev/null
+++ b/frontend/src/app/shared/components/storages/storage-information/storage-information.service.ts
@@ -0,0 +1,145 @@
+// -- 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 { Injectable } from '@angular/core';
+import { CookieService } from 'ngx-cookie-service';
+import { v4 as uuidv4 } from 'uuid';
+import { Observable } from 'rxjs';
+import { map } from 'rxjs/operators';
+
+import { I18nService } from 'core-app/core/i18n/i18n.service';
+import { IStorage } from 'core-app/core/state/storages/storage.model';
+import { IFileLink } from 'core-app/core/state/file-links/file-link.model';
+import { StorageActionButton } from 'core-app/shared/components/storages/storage-information/storage-action-button';
+import { StorageInformationBox } from 'core-app/shared/components/storages/storage-information/storage-information-box';
+import { CurrentUserService } from 'core-app/core/current-user/current-user.service';
+import { storageLocaleString } from 'core-app/shared/components/storages/functions/storages.functions';
+import {
+ fileLinkViewError,
+ storageAuthorizationError,
+ storageConnected,
+ storageFailedAuthorization,
+} from 'core-app/shared/components/storages/storages-constants.const';
+
+@Injectable()
+export class StorageInformationService {
+ private text = {
+ fileLinkErrorHeader: this.i18n.t('js.storages.information.live_data_error'),
+ fileLinkErrorContent: (storageType:string):string => this.i18n.t('js.storages.information.live_data_error_description', { storageType }),
+ connectionErrorHeader: (storageType:string):string => this.i18n.t('js.storages.no_connection', { storageType }),
+ connectionErrorContent: (storageType:string):string => this.i18n.t('js.storages.information.connection_error', { storageType }),
+ authorizationFailureHeader: (storageType:string):string => this.i18n.t('js.storages.login_to', { storageType }),
+ authorizationFailureContent: (storageType:string):string => this.i18n.t('js.storages.information.not_logged_in', { storageType }),
+ loginButton: (storageType:string):string => this.i18n.t('js.storages.login', { storageType }),
+ };
+
+ constructor(
+ private readonly i18n:I18nService,
+ private readonly cookieService:CookieService,
+ private readonly currentUserService:CurrentUserService,
+ ) {}
+
+ public storageInformation(storage:IStorage, fileLinks:IFileLink[]):Observable<StorageInformationBox[]> {
+ return this.currentUserService.isLoggedIn$
+ .pipe(
+ map((loggedIn) => {
+ if (!loggedIn) {
+ return [];
+ }
+
+ const storageType = this.i18n.t(storageLocaleString(storage._links.type.href));
+
+ switch (storage._links.authorizationState.href) {
+ case storageFailedAuthorization:
+ return [this.failedAuthorizationInformation(storage, storageType)];
+ case storageAuthorizationError:
+ return [this.authorizationErrorInformation(storageType)];
+ case storageConnected:
+ if (this.hasFileLinkViewErrors(fileLinks)) {
+ return [this.fileLinkErrorInformation(storageType)];
+ }
+ return [];
+ default:
+ return [];
+ }
+ }),
+ );
+ }
+
+ private failedAuthorizationInformation(storage:IStorage, storageType:string):StorageInformationBox {
+ return new StorageInformationBox(
+ 'import',
+ this.text.authorizationFailureHeader(storageType),
+ this.text.authorizationFailureContent(storageType),
+ [new StorageActionButton(
+ this.text.loginButton(storageType),
+ () => {
+ if (storage._links.authorize) {
+ const nonce = uuidv4();
+ this.setAuthorizationCallbackCookie(nonce);
+ window.location.href = StorageInformationService.authorizationFailureActionUrl(storage._links.authorize.href, nonce);
+ } else {
+ throw new Error('Authorize link is missing!');
+ }
+ },
+ )],
+ );
+ }
+
+ private authorizationErrorInformation(storageType:string):StorageInformationBox {
+ return new StorageInformationBox(
+ 'remove-link',
+ this.text.connectionErrorHeader(storageType),
+ this.text.connectionErrorContent(storageType),
+ [],
+ );
+ }
+
+ private fileLinkErrorInformation(storageType:string):StorageInformationBox {
+ return new StorageInformationBox(
+ 'error',
+ this.text.fileLinkErrorHeader,
+ this.text.fileLinkErrorContent(storageType),
+ [],
+ );
+ }
+
+ private setAuthorizationCallbackCookie(nonce:string):void {
+ this.cookieService.set(`oauth_state_${nonce}`, window.location.href, {
+ path: '/',
+ });
+ }
+
+ private static authorizationFailureActionUrl(baseUrl:string, nonce:string):string {
+ return `${baseUrl}&state=${nonce}`;
+ }
+
+ private hasFileLinkViewErrors(fileLinks:IFileLink[]):boolean {
+ return fileLinks.filter((fileLink) => fileLink._links.permission?.href === fileLinkViewError).length > 0;
+ }
+}
diff --git a/frontend/src/app/shared/components/storages/storage/storage.component.html b/frontend/src/app/shared/components/storages/storage/storage.component.html
index 71ad94ef536..12b1a4e2918 100644
--- a/frontend/src/app/shared/components/storages/storage/storage.component.html
+++ b/frontend/src/app/shared/components/storages/storage/storage.component.html
@@ -5,12 +5,12 @@
<span
class="op-tab-content--header-icon spot-icon spot-icon_nextcloud-circle op-files-tab--icon op-files-tab--icon_primary"
></span>
- <span class="op-tab-content--header-text" [textContent]="storage.name"></span>
+ <span class="op-tab-content--header-text" [textContent]="(storage | async)?.name"></span>
<a
class="op-tab-content--header-action spot-link"
- aria-label="{{text.openStorage()}}"
- [title]="text.openStorage()"
- [href]="storageFilesLocation"
+ aria-label="{{text.openStorage(storageType | async)}}"
+ [title]="text.openStorage(storageType | async)"
+ [href]="(storage | async)?._links.open.href"
target="_blank"
>
<span class="spot-icon spot-icon_external-link"></span>
@@ -26,7 +26,7 @@
<div class="op-file-section">
<ul
- *ngIf="(fileLinks$ | async).length > 0"
+ *ngIf="(fileLinks | async)?.length > 0"
class="spot-list spot-list_compact op-file-list"
[ngClass]="{
'op-file-section': true,
@@ -35,21 +35,21 @@
data-qa-selector="file-list"
>
<li
- *ngFor="let fileLink of fileLinks$ | async; let i = index;"
+ *ngFor="let fileLink of fileLinks | async; let i = index;"
class="spot-list--item op-file-list--item"
data-qa-selector="file-list--item"
op-file-link-list-item
[fileLink]="fileLink"
- [disabled]="disabled"
+ [disabled]="disabled | async"
[allowEditing]="allowLinking"
(removeFileLink)="removeFileLink(fileLink)"
></li>
</ul>
<span
- *ngIf="!allowUploading && (storageErrors | async).length === 0 && (fileLinks$ | async).length === 0"
+ *ngIf="!allowUploading && (storageErrors | async)?.length === 0 && (fileLinks | async)?.length === 0"
class="op-file-section--empty-list-hint"
- [textContent]="text.emptyList()"
+ [textContent]="text.emptyList(this.storageType | async)"
></span>
<input
@@ -63,7 +63,7 @@
/>
<button
- *ngIf="allowUploading && (storageErrors | async).length === 0"
+ *ngIf="allowUploading && (storageErrors | async)?.length === 0"
[attr.aria-label]="text.dropBox.uploadLabel"
data-qa-selector="op-storage--drop-box"
[ngClass]="{
@@ -71,7 +71,7 @@
'op-file-section--drop-box': true,
'op-file-section--drop-box_dragging': dragging > 0,
'op-file-section--drop-box_dragging-over': draggingOverDropZone,
- 'op-file-section--drop-box_float': (fileLinks$ | async).length
+ 'op-file-section--drop-box_float': (fileLinks | async)?.length
}"
type="button"
(dragover)="onDragOver($event)"
@@ -83,19 +83,19 @@
class="spot-icon spot-icon_upload-arrow op-file-section--drop-box-icon"
></span>
<span
- *ngIf="(fileLinks$ | async).length > 0"
+ *ngIf="(fileLinks | async)?.length > 0"
class="op-file-section--drop-box-text"
- [textContent]="text.dropBox.dropFiles()"
+ [textContent]="text.dropBox.dropFiles(this.storageType | async)"
></span>
<span
- *ngIf="(fileLinks$ | async).length === 0"
+ *ngIf="(fileLinks | async)?.length === 0"
class="op-file-section--drop-box-text"
- [textContent]="text.dropBox.dropClickFiles()"
+ [textContent]="text.dropBox.dropClickFiles(this.storageType | async)"
></span>
</button>
<div
- *ngIf="(storageErrors | async).length === 0"
+ *ngIf="(storageErrors | async)?.length === 0"
class="op-file-section--actions"
>
<button
@@ -103,7 +103,7 @@
type="button"
class="spot-link"
data-qa-selector="op-storage--upload-file-button"
- (click)="triggerFileInput()"
+ (click)="triggerFileInput()"
>
<span class="spot-icon spot-icon_upload-arrow"></span>
<span [textContent]="text.actions.uploadFile"></span>
diff --git a/frontend/src/app/shared/components/storages/storage/storage.component.ts b/frontend/src/app/shared/components/storages/storage/storage.component.ts
index cff3c2cb07e..9862306b7db 100644
--- a/frontend/src/app/shared/components/storages/storage/storage.component.ts
+++ b/frontend/src/app/shared/components/storages/storage/storage.component.ts
@@ -38,21 +38,19 @@ import {
} from '@angular/core';
import { HttpErrorResponse } from '@angular/common/http';
import {
- BehaviorSubject, combineLatest,
+ combineLatest,
Observable,
of,
throwError,
} from 'rxjs';
import {
catchError,
- filter,
+ filter, first,
map,
switchMap,
take,
tap,
} from 'rxjs/operators';
-import { CookieService } from 'ngx-cookie-service';
-import { v4 as uuidv4 } from 'uuid';
import { HalResource } from 'core-app/features/hal/resources/hal-resource';
import { IFileLink, IFileLinkOriginData } from 'core-app/core/state/file-links/file-link.model';
@@ -61,15 +59,10 @@ import { IProjectStorage } from 'core-app/core/state/project-storages/project-st
import { FileLinksResourceService } from 'core-app/core/state/file-links/file-links.service';
import {
fileLinkViewError,
- nextcloud,
- storageAuthorizationError,
storageConnected,
- storageFailedAuthorization,
} from 'core-app/shared/components/storages/storages-constants.const';
-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 { StorageActionButton } from 'core-app/shared/components/storages/storage-information/storage-action-button';
import {
StorageInformationBox,
} from 'core-app/shared/components/storages/storage-information/storage-information-box';
@@ -101,6 +94,12 @@ 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';
+import { StoragesResourceService } from 'core-app/core/state/storages/storages.service';
+import {
+ StorageInformationService,
+} from 'core-app/shared/components/storages/storage-information/storage-information.service';
+import { storageLocaleString } from 'core-app/shared/components/storages/functions/storages.functions';
+import idFromLink from 'core-app/features/hal/helpers/id-from-link';
@Component({
selector: 'op-storage',
@@ -111,8 +110,6 @@ import isNewResource from 'core-app/features/hal/helpers/is-new-resource';
export class StorageComponent extends UntilDestroyedMixin implements OnInit, OnDestroy {
@Input() public resource:HalResource;
- @Input() public storage:IStorage;
-
@Input() public projectStorage:IProjectStorage;
@Input() public allowUploading = true;
@@ -121,32 +118,21 @@ export class StorageComponent extends UntilDestroyedMixin implements OnInit, OnD
@ViewChild('hiddenFileInput') public filePicker:ElementRef<HTMLInputElement>;
- fileLinks$:Observable<IFileLink[]>;
+ fileLinks:Observable<IFileLink[]>;
- disabled = false;
+ storage:Observable<IStorage>;
- storageType:string;
+ disabled:Observable<boolean>;
- storageErrors = new BehaviorSubject<StorageInformationBox[]>([]);
+ storageType:Observable<string>;
+
+ storageErrors:Observable<StorageInformationBox[]>;
draggingOverDropZone = false;
dragging = 0;
- private isLoggedIn = false;
-
- private readonly storageTypeMap:Record<string, string> = {};
-
text = {
- infoBox: {
- fileLinkErrorHeader: this.i18n.t('js.storages.information.live_data_error'),
- fileLinkErrorContent: (storageType:string):string => this.i18n.t('js.storages.information.live_data_error_description', { storageType }),
- connectionErrorHeader: (storageType:string):string => this.i18n.t('js.storages.no_connection', { storageType }),
- connectionErrorContent: (storageType:string):string => this.i18n.t('js.storages.information.connection_error', { storageType }),
- authorizationFailureHeader: (storageType:string):string => this.i18n.t('js.storages.login_to', { storageType }),
- authorizationFailureContent: (storageType:string):string => this.i18n.t('js.storages.information.not_logged_in', { storageType }),
- loginButton: (storageType:string):string => this.i18n.t('js.storages.login', { storageType }),
- },
actions: {
linkExisting: this.i18n.t('js.storages.link_existing_files'),
uploadFile: this.i18n.t('js.storages.upload_files'),
@@ -177,18 +163,13 @@ export class StorageComponent extends UntilDestroyedMixin implements OnInit, OnD
},
dropBox: {
uploadLabel: this.i18n.t('js.storages.upload_files'),
- dropFiles: ():string => this.i18n.t('js.storages.drop_files', { name: this.storage.name }),
- dropClickFiles: ():string => this.i18n.t('js.storages.drop_or_click_files', { name: this.storage.name }),
+ dropFiles: (name:string):string => this.i18n.t('js.storages.drop_files', { name }),
+ dropClickFiles: (name:string):string => this.i18n.t('js.storages.drop_or_click_files', { name }),
},
- emptyList: ():string => this.i18n.t('js.storages.file_links.empty', { storageType: this.storageType }),
- openStorage: ():string => this.i18n.t('js.storages.open_storage', { storageType: this.storageType }),
- nextcloud: this.i18n.t('js.storages.types.nextcloud'),
+ emptyList: (storageType:string):string => this.i18n.t('js.storages.file_links.empty', { storageType }),
+ openStorage: (storageType:string):string => this.i18n.t('js.storages.open_storage', { storageType }),
};
- public get storageFilesLocation():string {
- return this.storage._links.open.href;
- }
-
private get addFileLinksHref():string {
if (isNewResource(this.resource)) {
return this.pathHelperService.fileLinksPath();
@@ -216,40 +197,53 @@ export class StorageComponent extends UntilDestroyedMixin implements OnInit, OnD
private readonly i18n:I18nService,
private readonly cdRef:ChangeDetectorRef,
private readonly toastService:ToastService,
- private readonly cookieService:CookieService,
private readonly uploadService:OpUploadService,
private readonly opModalService:OpModalService,
private readonly timezoneService:TimezoneService,
private readonly pathHelperService:PathHelperService,
- private readonly currentUserService:CurrentUserService,
+ private readonly storagesResourceService:StoragesResourceService,
private readonly fileLinkResourceService:FileLinksResourceService,
+ private readonly storageInformationService:StorageInformationService,
private readonly storageFilesResourceService:StorageFilesResourceService,
) {
super();
}
ngOnInit():void {
- this.initializeStorageTypes();
-
- this.storageType = this.storageTypeMap[this.storage._links.type.href];
+ this.storagesResourceService.requireEntity(this.projectStorage._links.storage.href).subscribe();
- this.disabled = this.storage._links.authorizationState.href !== storageConnected;
+ this.storage = this.storagesResourceService.lookup(idFromLink(this.projectStorage._links.storage.href));
- this.fileLinks$ = this.fileLinkResourceService.collection(this.collectionKey);
+ this.fileLinks = this.collectionKey()
+ .pipe(
+ switchMap((key) => this.fileLinkResourceService.requireCollection(key)),
+ tap((fileLinks) => {
+ if (isNewResource(this.resource)) {
+ this.resource.fileLinks = { elements: fileLinks.map((a) => a._links?.self) };
+ }
+ }),
+ );
- this.currentUserService.isLoggedIn$
- .pipe(this.untilDestroyed())
- .subscribe((isLoggedIn) => { this.isLoggedIn = isLoggedIn; });
+ this.disabled = combineLatest([
+ this.storage,
+ this.fileLinks,
+ ]).pipe(
+ map(([storage, fileLinks]) =>
+ this.hasFileLinkViewErrors(fileLinks) || storage._links.authorizationState.href !== storageConnected),
+ );
- this.fileLinks$
- .pipe(this.untilDestroyed())
- .subscribe((fileLinks) => {
- if (isNewResource(this.resource)) {
- this.resource.fileLinks = { elements: fileLinks.map((a) => a._links?.self) };
- }
+ this.storageType = this.storage
+ .pipe(
+ map((storage) => this.i18n.t(storageLocaleString(storage._links.type.href))),
+ );
- this.storageErrors.next(this.getStorageErrors(fileLinks));
- });
+ this.storageErrors = combineLatest([
+ this.storage,
+ this.fileLinks,
+ ]).pipe(
+ this.untilDestroyed(),
+ switchMap(([storage, fileLinks]) => this.storageInformationService.storageInformation(storage, fileLinks)),
+ );
document.body.addEventListener('dragenter', this.onGlobalDragEnter);
document.body.addEventListener('dragleave', this.onGlobalDragLeave);
@@ -265,7 +259,10 @@ export class StorageComponent extends UntilDestroyedMixin implements OnInit, OnD
}
public removeFileLink(fileLink:IFileLink):void {
- this.fileLinkResourceService.remove(this.collectionKey, fileLink)
+ this.collectionKey()
+ .pipe(
+ switchMap((key) => this.fileLinkResourceService.remove(key, fileLink)),
+ )
.subscribe(
() => { /* Do nothing */ },
(error:HttpErrorResponse) => this.toastService.addError(error),
@@ -274,20 +271,23 @@ export class StorageComponent extends UntilDestroyedMixin implements OnInit, OnD
public openLinkFilesDialog():void {
combineLatest([
- this.fileLinks$.pipe(take(1)),
- this.entryLocation(),
- ]).subscribe(([fileLinks, location]) => {
- const locals = {
- storageType: this.storage._links.type.href,
- storageName: this.storage.name,
- storageLink: this.storage._links.self,
- addFileLinksHref: this.addFileLinksHref,
- collectionKey: this.collectionKey,
- location,
- fileLinks,
- };
- this.opModalService.show<FilePickerModalComponent>(FilePickerModalComponent, 'global', locals);
- });
+ this.storage,
+ this.fileLinks,
+ this.storage.pipe(switchMap((storage) => this.entryLocation(storage))),
+ this.collectionKey(),
+ ]).pipe(first())
+ .subscribe(([storage, fileLinks, location, collectionKey]) => {
+ const locals = {
+ storageType: storage._links.type.href,
+ storageName: storage.name,
+ storageLink: storage._links.self,
+ addFileLinksHref: this.addFileLinksHref,
+ collectionKey,
+ location,
+ fileLinks,
+ };
+ this.opModalService.show<FilePickerModalComponent>(FilePickerModalComponent, 'global', locals);
+ });
}
public triggerFileInput():void {
@@ -303,7 +303,7 @@ export class StorageComponent extends UntilDestroyedMixin implements OnInit, OnD
this.filePicker.nativeElement.value = '';
}
- private entryLocation():Observable<string> {
+ private entryLocation(storage:IStorage):Observable<string> {
if (this.projectStorage.projectFolderMode === 'inactive') {
return of('/');
}
@@ -313,14 +313,14 @@ export class StorageComponent extends UntilDestroyedMixin implements OnInit, OnD
}
return this.storageFilesResourceService
- .file(this.storage.id, this.projectStorage.projectFolderId)
+ .file(storage.id, this.projectStorage.projectFolderId)
.pipe(map((file) => file.location));
}
private storageFileUpload(file:File):void {
- this.entryLocation()
+ this.storage
.pipe(
- switchMap((entryLocation) => this.selectUploadLocation(entryLocation)),
+ switchMap((storage) => this.selectUploadLocation(storage)),
switchMap((data) => this.resolveUploadConflicts(file, data.files, data.location)),
)
.subscribe((data) => {
@@ -328,19 +328,19 @@ export class StorageComponent extends UntilDestroyedMixin implements OnInit, OnD
});
}
- private selectUploadLocation(entryLocation:string):Observable<LocationData> {
- const locals = {
- storageType: this.storage._links.type.href,
- storageName: this.storage.name,
- storageLink: this.storage._links.self,
- location: entryLocation,
- };
-
- return this.opModalService.show<LocationPickerModalComponent>(LocationPickerModalComponent, 'global', locals)
+ private selectUploadLocation(storage:IStorage):Observable<LocationData> {
+ return this.entryLocation(storage)
.pipe(
+ map((location):Record<string, unknown> => ({
+ storageType: storage._links.type.href,
+ storageName: storage.name,
+ storageLink: storage._links.self,
+ location,
+ })),
+ switchMap((locals) => this.opModalService.show<LocationPickerModalComponent>(LocationPickerModalComponent, 'global', locals)),
switchMap((modal) => modal.closingEvent),
filter((modal) => modal.submitted),
- take(1),
+ first(),
map((modal) => ({ location: modal.location, files: modal.filesAtLocation })),
);
}
@@ -363,9 +363,12 @@ export class StorageComponent extends UntilDestroyedMixin implements OnInit, OnD
private uploadAndCreateFileLink(data:UploadData):void {
let isUploadError = false;
- this.storageFilesResourceService
- .uploadLink(this.uploadResourceLink(data.file.name, data.location))
+ this.storage
.pipe(
+ switchMap((storage) => {
+ const link = this.uploadResourceLink(storage, data.file.name, data.location);
+ return this.storageFilesResourceService.uploadLink(link);
+ }),
switchMap((link) => this.uploadAndNotify(link, data.file, data.overwrite)),
catchError((error) => {
isUploadError = true;
@@ -375,16 +378,25 @@ export class StorageComponent extends UntilDestroyedMixin implements OnInit, OnD
tap((fileLinkCreationData) => {
// Update the file link list of this storage only in case of a linked file got updated
if (fileLinkCreationData === null) {
- this.fileLinkResourceService.updateCollection(this.fileLinkSelfLink).subscribe();
+ this.collectionKey()
+ .pipe(switchMap((key) => this.fileLinkResourceService.fetchCollection(key)))
+ .subscribe();
}
}),
filter(isNotNull),
- switchMap((file) => this.fileLinkResourceService.addFileLinks(
- this.collectionKey,
- this.addFileLinksHref,
- this.storage._links.self,
- [file],
- )),
+ switchMap((file) =>
+ combineLatest([
+ this.storage.pipe(first()),
+ this.collectionKey(),
+ ])
+ .pipe(
+ switchMap(([storage, collectionKey]) => this.fileLinkResourceService.addFileLinks(
+ collectionKey,
+ this.addFileLinksHref,
+ storage._links.self,
+ [file],
+ )),
+ )),
)
.subscribe(
(collection) => {
@@ -408,7 +420,13 @@ export class StorageComponent extends UntilDestroyedMixin implements OnInit, OnD
this.toastService.addError(this.text.toast.uploadFailedForbidden(fileName));
break;
case 413:
- this.toastService.addError(this.text.toast.uploadFailedSizeLimit(fileName, this.storageType));
+ this.storage
+ .pipe(first())
+ .subscribe((storage) => {
+ const storageType = this.i18n.t(storageLocaleString(storage._links.type.href));
+ const toast = this.text.toast.uploadFailedSizeLimit(fileName, storageType);
+ this.toastService.addError(toast);
+ });
break;
case 507:
this.toastService.addError(this.text.toast.uploadFailedQuota(fileName));
@@ -439,7 +457,7 @@ export class StorageComponent extends UntilDestroyedMixin implements OnInit, OnD
}
private createFileLinkData(file:File, response:NextcloudFileUploadResponse):Observable<IFileLinkOriginData|null> {
- return this.fileLinks$
+ return this.fileLinks
.pipe(
take(1),
map((fileLinks) => {
@@ -461,9 +479,9 @@ export class StorageComponent extends UntilDestroyedMixin implements OnInit, OnD
);
}
- private uploadResourceLink(fileName:string, location:string):IPrepareUploadLink {
+ private uploadResourceLink(storage:IStorage, fileName:string, location:string):IPrepareUploadLink {
const project = (this.resource.project as unknown&{ id:string }).id;
- const link = this.storage._links.prepareUpload.filter((value) => project === value.payload.projectId.toString());
+ const link = storage._links.prepareUpload.filter((value) => project === value.payload.projectId.toString());
if (link.length === 0) {
throw new Error('Cannot upload to this storage. Missing permissions in project.');
}
@@ -480,89 +498,22 @@ export class StorageComponent extends UntilDestroyedMixin implements OnInit, OnD
};
}
- private getStorageErrors(fileLinks:IFileLink[]):StorageInformationBox[] {
- if (!this.isLoggedIn) {
- return [];
- }
-
- switch (this.storage._links.authorizationState.href) {
- case storageFailedAuthorization:
- return [this.failedAuthorizationInformation];
- case storageAuthorizationError:
- return [this.authorizationErrorInformation];
- case storageConnected:
- if (fileLinks.filter((fileLink) => fileLink._links.permission?.href === fileLinkViewError).length > 0) {
- this.disabled = true;
- return [this.fileLinkErrorInformation];
- }
- return [];
- default:
- return [];
- }
- }
-
- private get failedAuthorizationInformation():StorageInformationBox {
- return new StorageInformationBox(
- 'import',
- this.text.infoBox.authorizationFailureHeader(this.storageType),
- this.text.infoBox.authorizationFailureContent(this.storageType),
- [new StorageActionButton(
- this.text.infoBox.loginButton(this.storageType),
- () => {
- if (this.storage._links.authorize) {
- const nonce = uuidv4();
- this.setAuthorizationCallbackCookie(nonce);
- window.location.href = StorageComponent.authorizationFailureActionUrl(
- this.storage._links.authorize.href,
- nonce,
- );
- } else {
- throw new Error('Authorize link is missing!');
- }
- },
- )],
- );
- }
-
- private get authorizationErrorInformation():StorageInformationBox {
- return new StorageInformationBox(
- 'remove-link',
- this.text.infoBox.connectionErrorHeader(this.storageType),
- this.text.infoBox.connectionErrorContent(this.storageType),
- [],
- );
+ private hasFileLinkViewErrors(fileLinks:IFileLink[]):boolean {
+ return fileLinks.filter((fileLink) => fileLink._links.permission?.href === fileLinkViewError).length > 0;
}
- private get fileLinkErrorInformation():StorageInformationBox {
- return new StorageInformationBox(
- 'error',
- this.text.infoBox.fileLinkErrorHeader,
- this.text.infoBox.fileLinkErrorContent(this.storageType),
- [],
- );
- }
-
- private get collectionKey():string {
- return isNewResource(this.resource) ? 'new' : this.fileLinkSelfLink;
+ private collectionKey():Observable<string> {
+ return isNewResource(this.resource)
+ ? of('new')
+ : this.storage.pipe(
+ first(),
+ map((storage) => this.fileLinkSelfLink(storage)),
+ );
}
- private get fileLinkSelfLink():string {
+ private fileLinkSelfLink(storage:IStorage):string {
const fileLinks = this.resource.fileLinks as unknown&{ href:string };
- return `${fileLinks.href}?filters=[{"storage":{"operator":"=","values":["${this.storage.id}"]}}]`;
- }
-
- private setAuthorizationCallbackCookie(nonce:string):void {
- this.cookieService.set(`oauth_state_${nonce}`, window.location.href, {
- path: '/',
- });
- }
-
- private static authorizationFailureActionUrl(baseUrl:string, nonce:string):string {
- return `${baseUrl}&state=${nonce}`;
- }
-
- private initializeStorageTypes() {
- this.storageTypeMap[nextcloud] = this.text.nextcloud;
+ return `${fileLinks.href}?filters=[{"storage":{"operator":"=","values":["${storage.id}"]}}]`;
}
public onDropFiles(event:DragEvent):void {
@@ -573,7 +524,12 @@ export class StorageComponent extends UntilDestroyedMixin implements OnInit, OnD
const files = event.dataTransfer.files;
if (files.length !== 1) {
- this.toastService.addError(this.text.toast.draggingManyFiles(this.storageType));
+ this.storageType
+ .pipe(first())
+ .subscribe((storageType) => {
+ const toast = this.text.toast.draggingManyFiles(storageType);
+ this.toastService.addError(toast);
+ });
return;
}
@@ -581,6 +537,8 @@ export class StorageComponent extends UntilDestroyedMixin implements OnInit, OnD
}
public onDragOver(event:DragEvent):void {
+ const containsFiles = (dataTransfer:DataTransfer):boolean => dataTransfer.types.indexOf('Files') >= 0;
+
if (event.dataTransfer !== null && containsFiles(event.dataTransfer)) {
// eslint-disable-next-line no-param-reassign
event.dataTransfer.dropEffect = 'copy';
@@ -592,7 +550,3 @@ export class StorageComponent extends UntilDestroyedMixin implements OnInit, OnD
this.draggingOverDropZone = false;
}
}
-
-function containsFiles(dataTransfer:DataTransfer):boolean {
- return dataTransfer.types.indexOf('Files') >= 0;
-}
diff --git a/modules/storages/config/locales/js-en.yml b/modules/storages/config/locales/js-en.yml
index af0e51dc55b..5f1b15968a7 100644
--- a/modules/storages/config/locales/js-en.yml
+++ b/modules/storages/config/locales/js-en.yml
@@ -16,6 +16,7 @@ en:
types:
nextcloud: "Nextcloud"
+ default: "Storage"
information:
connection_error: >