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

[#45772] Use direct upload tokens as provided by the NC app

Eric Schubertbe17f6692b8a
diff --git a/frontend/src/app/core/file-upload/op-file-upload.service.ts b/frontend/src/app/core/file-upload/op-file-upload.service.ts
index 497d3a66be4..02085687af1 100644
--- a/frontend/src/app/core/file-upload/op-file-upload.service.ts
+++ b/frontend/src/app/core/file-upload/op-file-upload.service.ts
@@ -28,7 +28,10 @@
import { Injectable } from '@angular/core';
import {
- HttpClient, HttpEvent, HttpEventType, HttpResponse,
+ HttpClient,
+ HttpEvent,
+ HttpEventType,
+ HttpResponse,
} from '@angular/common/http';
import { Observable } from 'rxjs';
import { filter, map, share } from 'rxjs/operators';
@@ -61,9 +64,10 @@ export interface MappedUploadResult {
@Injectable()
export class OpenProjectFileUploadService {
- constructor(protected http:HttpClient,
- protected halResource:HalResourceService) {
- }
+ constructor(
+ protected readonly http:HttpClient,
+ protected readonly halResource:HalResourceService,
+ ) { }
/**
* Upload multiple files and return a promise for each uploading file and a single promise for all processed uploads
@@ -76,7 +80,10 @@ export class OpenProjectFileUploadService {
public uploadAndMapResponse(url:string, files:UploadFile[], method = 'post') {
const { uploads, finished } = this.upload(url, files);
const mapped = finished
- .then((result:HalResource[]) => result.map((el:HalResource) => ({ response: el, uploadUrl: el.staticDownloadLocation.href }))) as Promise<{ response:HalResource, uploadUrl:string }[]>;
+ .then((result:HalResource[]) => result.map((el:HalResource) => ({
+ response: el,
+ uploadUrl: el.staticDownloadLocation.href,
+ }))) as Promise<{ response:HalResource, uploadUrl:string }[]>;
return { uploads, finished: mapped } as MappedUploadResult;
}
@@ -98,6 +105,7 @@ export class OpenProjectFileUploadService {
* @param {string} url
* @param {UploadFile} file
* @param {string} method
+ * @param {'text'|'json'} responseType
*/
public uploadSingle(url:string, file:UploadFile|UploadBlob, method = 'post', responseType:'text'|'json' = 'json') {
const formData = new FormData();
@@ -115,9 +123,7 @@ export class OpenProjectFileUploadService {
// Add the file
formData.append('file', file, metadata.fileName);
- const observable = this
- .http
- .request<HalResource>(
+ const observable = this.http.request<HalResource>(
method,
url,
{
@@ -129,10 +135,7 @@ export class OpenProjectFileUploadService {
// Subscribe to progress events. subscribe() will fire multiple times!
reportProgress: true,
},
- )
- .pipe(
- share(),
- );
+ ).pipe(share());
return [file, observable] as UploadInProgress;
}
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 b3ea6854412..30fa03f8add 100644
--- a/frontend/src/app/shared/components/storages/storage/storage.component.ts
+++ b/frontend/src/app/shared/components/storages/storage/storage.component.ts
@@ -36,8 +36,17 @@ import {
OnInit,
ViewChild,
} from '@angular/core';
+import { HttpClient, HttpEventType, HttpResponse } from '@angular/common/http';
import { BehaviorSubject, Observable, throwError } from 'rxjs';
-import { catchError, switchMap, take } from 'rxjs/operators';
+import {
+ catchError,
+ filter,
+ map,
+ share,
+ switchMap,
+ take,
+ tap,
+} from 'rxjs/operators';
import { CookieService } from 'ngx-cookie-service';
import { v4 as uuidv4 } from 'uuid';
@@ -71,8 +80,11 @@ import {
} from 'core-app/shared/components/storages/location-picker-modal/location-picker-modal.component';
import { UploadStorageFilesService } from 'core-app/shared/components/storages/services/upload-storage-files.service';
import { ToastService } from 'core-app/shared/components/toaster/toast.service';
-import { UploadFile } from 'core-app/core/file-upload/op-file-upload.service';
+import { OpenProjectFileUploadService, UploadFile } from 'core-app/core/file-upload/op-file-upload.service';
import { StorageFilesResourceService } from 'core-app/core/state/storage-files/storage-files.service';
+import { IStorageFile } from 'core-app/core/state/storage-files/storage-file.model';
+import { IUploadLink } from 'core-app/core/state/storage-files/upload-link.model';
+import { TimezoneService } from 'core-app/core/datetime/timezone.service';
@Component({
selector: 'op-storage',
@@ -163,6 +175,7 @@ export class StorageComponent extends UntilDestroyedMixin implements OnInit, OnD
constructor(
private readonly i18n:I18nService,
private readonly cdRef:ChangeDetectorRef,
+ private readonly http:HttpClient,
private readonly toastService:ToastService,
private readonly cookieService:CookieService,
private readonly opModalService:OpModalService,
@@ -171,6 +184,8 @@ export class StorageComponent extends UntilDestroyedMixin implements OnInit, OnD
private readonly fileLinkResourceService:FileLinksResourceService,
private readonly uploadStorageFilesService:UploadStorageFilesService,
private readonly storageFilesResourceService:StorageFilesResourceService,
+ private readonly fileUploadService:OpenProjectFileUploadService,
+ private readonly timezoneService:TimezoneService,
) {
super();
}
@@ -266,13 +281,14 @@ export class StorageComponent extends UntilDestroyedMixin implements OnInit, OnD
});
}
- private uploadFile(file:UploadFile, location:string):void {
+ private uploadFile(file:UploadFile, _location:string):void {
let isUploadError = false;
this.storageFilesResourceService
- .uploadLink(this.uploadResourceLink(file.name, location))
+ .uploadLink(this.uploadResourceLink(file.name, '1023'))
.pipe(
- switchMap((link) => this.uploadStorageFilesService.uploadFile(link, file)),
+ // switchMap((link) => this.uploadStorageFilesService.uploadFile(link, file)),
+ switchMap((link) => this.uploadAndNotify(link, file)),
catchError((error) => {
isUploadError = true;
return throwError(error);
@@ -300,6 +316,56 @@ export class StorageComponent extends UntilDestroyedMixin implements OnInit, OnD
);
}
+ private uploadAndNotify(link:IUploadLink, file:UploadFile):Observable<IStorageFile> {
+ const { method, href } = link._links.destination;
+
+ interface FileUploadResponse {
+ file_name:string;
+ file_id:string;
+ }
+
+ const formData = new FormData();
+ formData.append('file', file, file.name);
+ const observable = this.http.request<FileUploadResponse>(
+ method,
+ href,
+ {
+ body: formData,
+ headers: { 'X-External-Request': 'true' },
+ observe: 'events',
+ reportProgress: true,
+ responseType: 'json',
+ },
+ ).pipe(share());
+ const message = this.i18n.t('js.label_upload_notification');
+ const notification = this.toastService.add({ data: [[file, observable]], type: 'upload', message });
+
+ return observable
+ .pipe(
+ tap(() => {
+ setTimeout(() => this.toastService.remove(notification), 700);
+ }),
+ filter((ev) => ev.type === HttpEventType.Response),
+ map((ev:HttpResponse<FileUploadResponse>) => ev.body),
+ map((data) => {
+ if (data === null) {
+ throw new Error('Upload data is null.');
+ }
+
+ const now = this.timezoneService.parseDate(new Date()).toISOString();
+ return ({
+ id: data.file_id,
+ name: data.file_name,
+ location: '',
+ mimeType: file.type,
+ size: file.size,
+ createdAt: now,
+ lastModifiedAt: now,
+ });
+ }),
+ );
+ }
+
private uploadResourceLink(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());
@@ -409,6 +475,8 @@ export class StorageComponent extends UntilDestroyedMixin implements OnInit, OnD
this.draggingOverDropZone = false;
this.dragging = 0;
+
+ this.openSelectLocationDialog(event.dataTransfer.files);
}
public onDragOver(event:DragEvent):void {
diff --git a/frontend/src/app/shared/components/toaster/toast.component.html b/frontend/src/app/shared/components/toaster/toast.component.html
index 700a0fc3f55..cd087177674 100644
--- a/frontend/src/app/shared/components/toaster/toast.component.html
+++ b/frontend/src/app/shared/components/toaster/toast.component.html
@@ -18,7 +18,7 @@
<span [textContent]="' '"></span>
<a class="op-toast--target-link"
*ngIf="toast.link"
- (click)="executeTarget($event)"
+ (click)="executeTarget()"
[textContent]="toast.link!.text">
</a>
</p>
@@ -37,9 +37,10 @@
<ul class="op-toast--uploads" *ngIf="data && data.length > 0">
<op-toasters-upload-progress
*ngFor="let upload of data"
- [upload]="upload"
- (onSuccess)="onUploadSuccess()"
- (onError)="remove()">
+ [file]="upload[0]"
+ [upload]="upload[1]"
+ (uploadSuccess)="onUploadSuccess()"
+ (uploadError)="remove()">
</op-toasters-upload-progress>
</ul>
</div>
diff --git a/frontend/src/app/shared/components/toaster/upload-progress.component.ts b/frontend/src/app/shared/components/toaster/upload-progress.component.ts
index 6ab7ddbdb01..f20a3f0d925 100644
--- a/frontend/src/app/shared/components/toaster/upload-progress.component.ts
+++ b/frontend/src/app/shared/components/toaster/upload-progress.component.ts
@@ -27,13 +27,25 @@
//++
import {
- Component, ElementRef, EventEmitter, Input, OnInit, Output, ViewChild,
+ AfterViewInit,
+ ChangeDetectionStrategy,
+ Component,
+ ElementRef,
+ EventEmitter,
+ Input,
+ OnInit,
+ Output,
+ ViewChild,
} from '@angular/core';
-import { HttpErrorResponse, HttpEventType, HttpProgressEvent } from '@angular/common/http';
-import { I18nService } from 'core-app/core/i18n/i18n.service';
+import {
+ HttpErrorResponse,
+ HttpEvent,
+ HttpEventType,
+ 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';
-import { UploadFile, UploadHttpEvent, UploadInProgress } from 'core-app/core/file-upload/op-file-upload.service';
@Component({
selector: 'op-toasters-upload-progress',
@@ -48,78 +60,80 @@ import { UploadFile, UploadHttpEvent, UploadInProgress } from 'core-app/core/fil
</span>
</li>
`,
+ changeDetection: ChangeDetectionStrategy.OnPush,
})
-export class UploadProgressComponent extends UntilDestroyedMixin implements OnInit {
- @Input() public upload:UploadInProgress;
+export class UploadProgressComponent extends UntilDestroyedMixin implements OnInit, AfterViewInit {
+ @Input() public file:File;
- @Output() public onError = new EventEmitter<HttpErrorResponse>();
+ @Input() public upload:Observable<HttpEvent<unknown>>;
- @Output() public onSuccess = new EventEmitter<undefined>();
+ @Output() public uploadError = new EventEmitter<HttpErrorResponse>();
- @ViewChild('progressBar')
- progressBar:ElementRef;
+ @Output() public uploadSuccess = new EventEmitter<void>();
- @ViewChild('progressPercentage')
- progressPercentage:ElementRef;
+ @ViewChild('progressBar') progressBar:ElementRef;
- public file:UploadFile;
+ @ViewChild('progressPercentage') progressPercentage:ElementRef;
public error = false;
public completed = false;
+ private viewInitialized = new BehaviorSubject<boolean>(false);
+
set value(value:number) {
- this.progressBar.nativeElement.value = value;
- this.progressPercentage.nativeElement.innerText = `${value}%`;
+ (this.progressBar.nativeElement as HTMLProgressElement).value = value;
+ (this.progressPercentage.nativeElement as HTMLParagraphElement).innerText = `${value}%`;
if (value === 100) {
- this.progressBar.nativeElement.style.display = 'none';
+ (this.progressBar.nativeElement as HTMLElement).style.display = 'none';
}
}
- constructor(protected readonly I18n:I18nService) {
- super();
- }
-
ngOnInit() {
- this.file = this.upload[0];
- const observable = this.upload[1];
-
- observable
- .pipe(
- this.untilDestroyed(),
- )
+ combineLatest([
+ this.upload,
+ this.viewInitialized,
+ ]).pipe(this.untilDestroyed())
.subscribe(
- (evt:UploadHttpEvent) => {
+ ([evt, initialized]) => {
+ if (!initialized) {
+ return;
+ }
+
switch (evt.type) {
case HttpEventType.Sent:
this.value = 5;
- return debugLog(`Uploading file "${this.file.name}" of size ${this.file.size}.`);
-
+ debugLog(`Uploading file "${this.file.name}" of size ${this.file.size}.`);
+ break;
case HttpEventType.UploadProgress:
- return this.updateProgress(evt);
-
+ this.updateProgress(evt);
+ break;
case HttpEventType.Response:
debugLog(`File ${this.fileName} was fully uploaded.`);
this.value = 100;
this.completed = true;
- return this.onSuccess.emit();
-
+ this.uploadSuccess.emit();
+ break;
default:
- // Sent or unknown event
+ // unknown event
}
},
(error:HttpErrorResponse) => this.handleError(error),
);
}
- public get fileName():string|undefined {
+ ngAfterViewInit():void {
+ this.viewInitialized.next(true);
+ }
+
+ public get fileName():string {
return this.file && this.file.name;
}
private updateProgress(evt:HttpProgressEvent) {
if (evt.total) {
- this.value = Math.round(evt.loaded / evt.total * 100);
+ this.value = Math.round((evt.loaded / evt.total) * 100);
} else {
this.value = 10;
}
@@ -127,6 +141,6 @@ export class UploadProgressComponent extends UntilDestroyedMixin implements OnIn
private handleError(error:HttpErrorResponse) {
this.error = true;
- this.onError.emit(error);
+ this.uploadError.emit(error);
}
}
diff --git a/modules/storages/app/common/storages/peripherals/storage_interaction/nextcloud/legacy_upload_link_query.rb b/modules/storages/app/common/storages/peripherals/storage_interaction/nextcloud/legacy_upload_link_query.rb
new file mode 100644
index 00000000000..ac1ac9a4314
--- /dev/null
+++ b/modules/storages/app/common/storages/peripherals/storage_interaction/nextcloud/legacy_upload_link_query.rb
@@ -0,0 +1,150 @@
+#-- 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.
+#++
+
+module Storages::Peripherals::StorageInteraction::Nextcloud
+ class LegacyUploadLinkQuery < Storages::Peripherals::StorageInteraction::StorageQuery
+ using Storages::Peripherals::ServiceResultRefinements # use '>>' (bind) operator for ServiceResult
+
+ URI_BASE_PATH = '/ocs/v2.php/apps/files_sharing/api/v1/shares'.freeze
+ UPLOAD_LINK_BASE = '/public.php/webdav'.freeze
+
+ def initialize(base_uri:, token:, retry_proc:)
+ super()
+
+ @base_uri = base_uri
+ @token = token
+ @retry_proc = retry_proc
+ end
+
+ def query(data)
+ validated(data) >>
+ method(:create_file_share) >>
+ method(:apply_drop_permission) >>
+ method(:build_upload_link)
+ end
+
+ private
+
+ def validated(data)
+ if data.nil? || data['fileName'].nil? || data['parent'].nil?
+ error(:error, 'Data is invalid', data)
+ else
+ ServiceResult.success(
+ result: Struct.new(:file_name, :parent)
+ .new(data['fileName'], data['parent'])
+ )
+ end
+ end
+
+ def create_file_share(data)
+ password = SecureRandom.uuid
+
+ outbound_response(
+ method: :post,
+ relative_path: URI_BASE_PATH,
+ payload: {
+ shareType: 3,
+ password:,
+ path: data.parent,
+ expireDate: Date.tomorrow
+ }
+ ).map do |response|
+ Struct.new(:id, :token, :password, :file_name)
+ .new(response.ocs.data.id, response.ocs.data.token, password, data.file_name)
+ end
+ end
+
+ def apply_drop_permission(share)
+ outbound_response(
+ method: :put,
+ relative_path: "#{URI_BASE_PATH}/#{share.id}",
+ payload: {
+ permissions: 5
+ }
+ ).map { share }
+ end
+
+ def build_upload_link(share)
+ destination = @base_uri.merge("#{UPLOAD_LINK_BASE}/#{ERB::Util.url_encode(share.file_name)}")
+ destination.user = share.token
+ destination.password = share.password
+
+ ServiceResult.success(result: Storages::UploadLink.new(destination, :put))
+ end
+
+ def outbound_response(method:, relative_path:, payload:) # rubocop:disable Metrics/AbcSize
+ @retry_proc.call(@token) do |token|
+ begin
+ response = ServiceResult.success(
+ result: RestClient::Request.execute(
+ method:,
+ url: @base_uri.merge(relative_path).to_s,
+ payload: payload.to_json,
+ headers: {
+ 'Authorization' => "Bearer #{token.access_token}",
+ 'OCS-APIRequest' => 'true',
+ 'Accept' => 'application/json',
+ 'Content-Type' => 'application/json'
+ }
+ )
+ )
+ rescue RestClient::Unauthorized => e
+ response = error(:not_authorized, 'Outbound request not authorized!', e.response)
+ rescue RestClient::NotFound => e
+ response = error(:not_found, 'Outbound request destination not found!', e.response)
+ rescue RestClient::ExceptionWithResponse => e
+ response = error(:error, 'Outbound request failed!', e.response)
+ rescue StandardError
+ response = error(:error, 'Outbound request failed!')
+ end
+
+ # rubocop:disable Style/OpenStructUse
+ # rubocop:disable Style/MultilineBlockChain
+ response
+ .bind do |r|
+ # The nextcloud API returns a successful response with empty body if the authorization is missing or expired
+ if r.body.blank?
+ error(:not_authorized, 'Outbound request not authorized!')
+ else
+ ServiceResult.success(result: r)
+ end
+ end
+ .map { |r| JSON.parse(r.body, object_class: OpenStruct) }
+ # rubocop:enable Style/MultilineBlockChain
+ # rubocop:enable Style/OpenStructUse Style/MultilineBlockChain
+ end
+ end
+
+ def error(code, log_message = nil, data = nil)
+ ServiceResult.failure(
+ result: code, # This is needed to work with the ConnectionManager token refresh mechanism.
+ errors: Storages::StorageError.new(code:, log_message:, data:)
+ )
+ end
+ end
+end
diff --git a/modules/storages/app/common/storages/peripherals/storage_interaction/nextcloud/upload_link_query.rb b/modules/storages/app/common/storages/peripherals/storage_interaction/nextcloud/upload_link_query.rb
index f5e78cde0a4..3a35973282b 100644
--- a/modules/storages/app/common/storages/peripherals/storage_interaction/nextcloud/upload_link_query.rb
+++ b/modules/storages/app/common/storages/peripherals/storage_interaction/nextcloud/upload_link_query.rb
@@ -30,75 +30,50 @@ module Storages::Peripherals::StorageInteraction::Nextcloud
class UploadLinkQuery < Storages::Peripherals::StorageInteraction::StorageQuery
using Storages::Peripherals::ServiceResultRefinements # use '>>' (bind) operator for ServiceResult
- URI_BASE_PATH = '/ocs/v2.php/apps/files_sharing/api/v1/shares'.freeze
- UPLOAD_LINK_BASE = '/public.php/webdav'.freeze
+ URI_TOKEN_REQUEST = 'apps/integration_openproject/direct-upload-token'.freeze
+ URI_UPLOAD_BASE_PATH = 'apps/integration_openproject/direct-upload'.freeze
- def initialize(base_uri:, token:, retry_proc:, finalize_url:)
+ def initialize(base_uri:, token:, retry_proc:)
super()
@base_uri = base_uri
@token = token
@retry_proc = retry_proc
- @finalize_url = finalize_url
end
def query(data)
validated(data) >>
- method(:create_file_share) >>
- method(:apply_drop_permission) >>
+ method(:request_direct_upload_token) >>
method(:build_upload_link)
end
private
def validated(data)
- if data.nil? || data['fileName'].nil? || data['parent'].nil?
- error(:error, 'Data is not valid', data)
+ if data.nil? || data['parent'].nil?
+ error(:error, 'Data is invalid', data)
else
ServiceResult.success(
- result: Struct.new(:file_name, :parent)
- .new(data['fileName'], data['parent'])
+ result: Struct.new(:parent).new(data['parent'])
)
end
end
- def create_file_share(data)
- password = SecureRandom.uuid
-
+ def request_direct_upload_token(data)
outbound_response(
method: :post,
- relative_path: URI_BASE_PATH,
- payload: {
- shareType: 3,
- password:,
- path: data.parent,
- expireDate: Date.tomorrow
- }
- ).map do |response|
- Struct.new(:id, :token, :password, :file_name)
- .new(response.ocs.data.id, response.ocs.data.token, password, data.file_name)
- end
- end
-
- def apply_drop_permission(share)
- outbound_response(
- method: :put,
- relative_path: "#{URI_BASE_PATH}/#{share.id}",
- payload: {
- permissions: 5
- }
- ).map { share }
+ relative_path: URI_TOKEN_REQUEST,
+ payload: { folder_id: data.parent }
+ )
end
- def build_upload_link(share)
- destination = @base_uri.merge("#{UPLOAD_LINK_BASE}/#{ERB::Util.url_encode(share.file_name)}")
- destination.user = share.token
- destination.password = share.password
-
+ def build_upload_link(response)
+ destination = @base_uri.merge(File.join(URI_UPLOAD_BASE_PATH, response.token))
ServiceResult.success(result: Storages::UploadLink.new(destination))
end
- def outbound_response(method:, relative_path:, payload:) # rubocop:disable Metrics/AbcSize
+ # rubocop:disable Metrics/AbcSize
+ def outbound_response(method:, relative_path:, payload:)
@retry_proc.call(@token) do |token|
begin
response = ServiceResult.success(
@@ -108,7 +83,6 @@ module Storages::Peripherals::StorageInteraction::Nextcloud
payload: payload.to_json,
headers: {
'Authorization' => "Bearer #{token.access_token}",
- 'OCS-APIRequest' => 'true',
'Accept' => 'application/json',
'Content-Type' => 'application/json'
}
@@ -128,18 +102,19 @@ module Storages::Peripherals::StorageInteraction::Nextcloud
# rubocop:disable Style/MultilineBlockChain
response
.bind do |r|
- # The nextcloud API returns a successful response with empty body if the authorization is missing or expired
- if r.body.blank?
- error(:not_authorized, 'Outbound request not authorized!')
- else
- ServiceResult.success(result: r)
- end
+ # The nextcloud API returns a successful response with empty body if the authorization is missing or expired
+ if r.body.blank?
+ error(:not_authorized, 'Outbound request not authorized!')
+ else
+ ServiceResult.success(result: r)
end
+ end
.map { |r| JSON.parse(r.body, object_class: OpenStruct) }
# rubocop:enable Style/MultilineBlockChain
# rubocop:enable Style/OpenStructUse Style/MultilineBlockChain
end
end
+ # rubocop:enable Metrics/AbcSize
def error(code, log_message = nil, data = nil)
ServiceResult.failure(
diff --git a/modules/storages/app/common/storages/peripherals/storage_interaction/storage_queries.rb b/modules/storages/app/common/storages/peripherals/storage_interaction/storage_queries.rb
index 88a2e38a25b..02e4eeee36f 100644
--- a/modules/storages/app/common/storages/peripherals/storage_interaction/storage_queries.rb
+++ b/modules/storages/app/common/storages/peripherals/storage_interaction/storage_queries.rb
@@ -52,16 +52,23 @@ module Storages::Peripherals::StorageInteraction
end
end
- def upload_link_query(finalize_url)
+ def upload_link_query
case @provider_type
when ::Storages::Storage::PROVIDER_TYPE_NEXTCLOUD
retry_with_refreshed_token do |token, with_refreshed_token_proc|
- ::Storages::Peripherals::StorageInteraction::Nextcloud::UploadLinkQuery.new(
- base_uri: @uri,
- token:,
- retry_proc: with_refreshed_token_proc,
- finalize_url:
- )
+ if OpenProject::FeatureDecisions.legacy_upload_preparation_active?
+ ::Storages::Peripherals::StorageInteraction::Nextcloud::LegacyUploadLinkQuery.new(
+ base_uri: @uri,
+ token:,
+ retry_proc: with_refreshed_token_proc
+ )
+ else
+ ::Storages::Peripherals::StorageInteraction::Nextcloud::UploadLinkQuery.new(
+ base_uri: @uri,
+ token:,
+ retry_proc: with_refreshed_token_proc
+ )
+ end
end
else
raise ArgumentError
diff --git a/modules/storages/app/common/storages/peripherals/storage_interaction/upload_link_query_helpers.rb b/modules/storages/app/common/storages/peripherals/storage_interaction/upload_link_query_helpers.rb
index 447907f893c..439a34b632e 100644
--- a/modules/storages/app/common/storages/peripherals/storage_interaction/upload_link_query_helpers.rb
+++ b/modules/storages/app/common/storages/peripherals/storage_interaction/upload_link_query_helpers.rb
@@ -45,10 +45,7 @@ module Storages::Peripherals::StorageInteraction
def upload_link_query(storage, user)
Storages::Peripherals::StorageRequests
.new(storage:)
- .upload_link_query(
- user:,
- finalize_url: nil # ToDo: api_v3_paths.finalize_upload(@storage.id)
- )
+ .upload_link_query(user:)
end
def execute_upload_link_query(request_body)
diff --git a/modules/storages/app/common/storages/peripherals/storage_requests.rb b/modules/storages/app/common/storages/peripherals/storage_requests.rb
index fc660ce4535..542e7922f6f 100644
--- a/modules/storages/app/common/storages/peripherals/storage_requests.rb
+++ b/modules/storages/app/common/storages/peripherals/storage_requests.rb
@@ -45,9 +45,9 @@ module Storages::Peripherals
.map { |query| query.method(:query).to_proc }
end
- def upload_link_query(user:, finalize_url:)
+ def upload_link_query(user:)
storage_queries(user)
- .upload_link_query(finalize_url)
+ .upload_link_query
.map { |query| query.method(:query).to_proc }
end
diff --git a/modules/storages/app/models/storages/upload_link.rb b/modules/storages/app/models/storages/upload_link.rb
index 68e67cb3362..2b0b527733b 100644
--- a/modules/storages/app/models/storages/upload_link.rb
+++ b/modules/storages/app/models/storages/upload_link.rb
@@ -27,10 +27,10 @@
#++
class Storages::UploadLink
- attr_reader :destination, :finalize
+ attr_reader :destination, :method
- def initialize(destination = '', finalize = nil)
+ def initialize(destination = '', method = :post)
@destination = destination
- @finalize = finalize
+ @method = method
end
end
diff --git a/modules/storages/lib/api/v3/storage_files/storage_files_api.rb b/modules/storages/lib/api/v3/storage_files/storage_files_api.rb
index 72c91b3d648..d26cab883c0 100644
--- a/modules/storages/lib/api/v3/storage_files/storage_files_api.rb
+++ b/modules/storages/lib/api/v3/storage_files/storage_files_api.rb
@@ -55,7 +55,7 @@ module API::V3::StorageFiles
# "parent": "/Pictures"
# }
post :prepare_upload do
- raise ::API::Errors::NotFound unless OpenProject::FeatureDecisions.storage_file_upload_active?
+ raise API::Errors::NotFound unless OpenProject::FeatureDecisions.storage_file_upload_active?
(upload_link_query(@storage, current_user) >> execute_upload_link_query(request_body))
.match(
diff --git a/modules/storages/lib/api/v3/storage_files/storage_upload_link_representer.rb b/modules/storages/lib/api/v3/storage_files/storage_upload_link_representer.rb
index 595ffa14e1f..eac02630328 100644
--- a/modules/storages/lib/api/v3/storage_files/storage_upload_link_representer.rb
+++ b/modules/storages/lib/api/v3/storage_files/storage_upload_link_representer.rb
@@ -35,22 +35,11 @@ module API::V3::StorageFiles
link :destination do
{
href: represented.destination,
- method: :put,
+ method: represented.method,
title: 'Upload File'
}
end
- link :finalize do
- next if represented.finalize.nil?
-
- {
- href: represented.finalize.destination,
- method: :post,
- title: 'Conclude file upload',
- payload: represented.finalize.payload
- }
- end
-
def _type
Storages::UploadLink.name.split('::').last
end
diff --git a/modules/storages/lib/open_project/storages/engine.rb b/modules/storages/lib/open_project/storages/engine.rb
index 01cc5bfed88..d5518166089 100644
--- a/modules/storages/lib/open_project/storages/engine.rb
+++ b/modules/storages/lib/open_project/storages/engine.rb
@@ -43,6 +43,7 @@ module OpenProject::Storages
initializer 'openproject_storages.feature_decisions' do
OpenProject::FeatureDecisions.add :storage_file_linking
OpenProject::FeatureDecisions.add :storage_file_upload
+ OpenProject::FeatureDecisions.add :legacy_upload_preparation
end
# For documentation see the definition of register in "ActsAsOpEngine"
diff --git a/modules/storages/spec/common/peripherals/storage_requests_spec.rb b/modules/storages/spec/common/peripherals/storage_requests_spec.rb
index c5f8fdf7da5..4daa7bcb1b7 100644
--- a/modules/storages/spec/common/peripherals/storage_requests_spec.rb
+++ b/modules/storages/spec/common/peripherals/storage_requests_spec.rb
@@ -397,7 +397,7 @@ describe Storages::Peripherals::StorageRequests, webmock: true do
describe 'with Nextcloud storage type selected' do
it 'must return an upload link URL' do
subject
- .upload_link_query(user:, finalize_url: nil)
+ .upload_link_query(user:)
.match(
on_success: ->(query) do
query.call(query_payload).match(
@@ -457,7 +457,7 @@ describe Storages::Peripherals::StorageRequests, webmock: true do
it 'must return :not_authorized ServiceResult' do
subject
- .upload_link_query(user:, finalize_url: nil)
+ .upload_link_query(user:)
.match(
on_success: ->(query) do
result = query.call(query_payload)
@@ -480,7 +480,7 @@ describe Storages::Peripherals::StorageRequests, webmock: true do
it 'must return :not_authorized ServiceResult' do
subject
- .upload_link_query(user:, finalize_url: nil)
+ .upload_link_query(user:)
.match(
on_success: ->(query) do
result = query.call(query_payload)
@@ -502,7 +502,7 @@ describe Storages::Peripherals::StorageRequests, webmock: true do
it "must return :#{symbol} ServiceResult" do
subject
- .upload_link_query(user:, finalize_url: nil)
+ .upload_link_query(user:)
.match(
on_success: ->(query) do
result = query.call(query_payload)