18169: Removed cancel disable when uploading
[arvados-workbench2.git] / src / services / collection-service / collection-service.ts
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 import { CollectionResource } from "models/collection";
6 import { AxiosInstance } from "axios";
7 import { CollectionFile, CollectionDirectory } from "models/collection-file";
8 import { WebDAV } from "common/webdav";
9 import { AuthService } from "../auth-service/auth-service";
10 import { extractFilesData } from "./collection-service-files-response";
11 import { TrashableResourceService } from "services/common-service/trashable-resource-service";
12 import { ApiActions } from "services/api/api-actions";
13 import { customEncodeURI } from "common/url";
14
15 export type UploadProgress = (fileId: number, loaded: number, total: number, currentTime: number) => void;
16
17 export class CollectionService extends TrashableResourceService<CollectionResource> {
18     constructor(serverApi: AxiosInstance, private webdavClient: WebDAV, private authService: AuthService, actions: ApiActions) {
19         super(serverApi, "collections", actions, [
20             'fileCount',
21             'fileSizeTotal',
22             'replicationConfirmed',
23             'replicationConfirmedAt',
24             'storageClassesConfirmed',
25             'storageClassesConfirmedAt',
26             'unsignedManifestText',
27             'version',
28         ]);
29     }
30
31     create(data?: Partial<CollectionResource>) {
32         return super.create({ ...data, preserveVersion: true });
33     }
34
35     update(uuid: string, data: Partial<CollectionResource>) {
36         return super.update(uuid, { ...data, preserveVersion: true });
37     }
38
39     async files(uuid: string) {
40         const request = await this.webdavClient.propfind(`c=${uuid}`);
41         if (request.responseXML != null) {
42             return extractFilesData(request.responseXML);
43         }
44         return Promise.reject();
45     }
46
47     async deleteFiles(collectionUuid: string, filePaths: string[]) {
48         const sortedUniquePaths = Array.from(new Set(filePaths))
49             .sort((a, b) => a.length - b.length)
50             .reduce((acc, currentPath) => {
51                 const parentPathFound = acc.find((parentPath) => currentPath.indexOf(`${parentPath}/`) > -1);
52
53                 if (!parentPathFound) {
54                     return [...acc, currentPath];
55                 }
56
57                 return acc;
58             }, []);
59
60         for (const path of sortedUniquePaths) {
61             if (path.indexOf(collectionUuid) === -1) {
62                 await this.webdavClient.delete(`c=${collectionUuid}${path}`);
63             } else {
64                 await this.webdavClient.delete(`c=${path}`);
65             }
66         }
67         await this.update(collectionUuid, { preserveVersion: true });
68     }
69
70     async uploadFiles(collectionUuid: string, files: File[], onProgress?: UploadProgress) {
71         if (collectionUuid === "" || files.length === 0) { return; }
72         // files have to be uploaded sequentially
73         for (let idx = 0; idx < files.length; idx++) {
74             await this.uploadFile(collectionUuid, files[idx], idx, onProgress);
75         }
76         await this.update(collectionUuid, { preserveVersion: true });
77     }
78
79     async moveFile(collectionUuid: string, oldPath: string, newPath: string) {
80         await this.webdavClient.move(
81             `c=${collectionUuid}${oldPath}`,
82             `c=${collectionUuid}/${customEncodeURI(newPath)}`
83         );
84         await this.update(collectionUuid, { preserveVersion: true });
85     }
86
87     extendFileURL = (file: CollectionDirectory | CollectionFile) => {
88         const baseUrl = this.webdavClient.defaults.baseURL.endsWith('/')
89             ? this.webdavClient.defaults.baseURL.slice(0, -1)
90             : this.webdavClient.defaults.baseURL;
91         const apiToken = this.authService.getApiToken();
92         const encodedApiToken = apiToken ? encodeURI(apiToken) : '';
93         const userApiToken = `/t=${encodedApiToken}/`;
94         const splittedPrevFileUrl = file.url.split('/');
95         const url = `${baseUrl}/${splittedPrevFileUrl[1]}${userApiToken}${splittedPrevFileUrl.slice(2).join('/')}`;
96         return {
97             ...file,
98             url
99         };
100     }
101
102     private async uploadFile(collectionUuid: string, file: File, fileId: number, onProgress: UploadProgress = () => { return; }) {
103         const fileURL = `c=${collectionUuid}/${file.name}`;
104         const requestConfig = {
105             headers: {
106                 'Content-Type': 'text/octet-stream'
107             },
108             onUploadProgress: (e: ProgressEvent) => {
109                 onProgress(fileId, e.loaded, e.total, Date.now());
110             },
111         };
112         return this.webdavClient.upload(fileURL, [file], requestConfig);
113     }
114 }