Merge branch '18215-collection-update-without-manifest' into main.
[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         const select = [...Object.keys(data), 'version', 'modifiedAt'];
37         return super.update(uuid, { ...data, preserveVersion: true }, select);
38     }
39
40     async files(uuid: string) {
41         const request = await this.webdavClient.propfind(`c=${uuid}`);
42         if (request.responseXML != null) {
43             return extractFilesData(request.responseXML);
44         }
45         return Promise.reject();
46     }
47
48     async deleteFiles(collectionUuid: string, filePaths: string[]) {
49         const sortedUniquePaths = Array.from(new Set(filePaths))
50             .sort((a, b) => a.length - b.length)
51             .reduce((acc, currentPath) => {
52                 const parentPathFound = acc.find((parentPath) => currentPath.indexOf(`${parentPath}/`) > -1);
53
54                 if (!parentPathFound) {
55                     return [...acc, currentPath];
56                 }
57
58                 return acc;
59             }, []);
60
61         for (const path of sortedUniquePaths) {
62             if (path.indexOf(collectionUuid) === -1) {
63                 await this.webdavClient.delete(`c=${collectionUuid}${path}`);
64             } else {
65                 await this.webdavClient.delete(`c=${path}`);
66             }
67         }
68         await this.update(collectionUuid, { preserveVersion: true });
69     }
70
71     async uploadFiles(collectionUuid: string, files: File[], onProgress?: UploadProgress) {
72         if (collectionUuid === "" || files.length === 0) { return; }
73         // files have to be uploaded sequentially
74         for (let idx = 0; idx < files.length; idx++) {
75             await this.uploadFile(collectionUuid, files[idx], idx, onProgress);
76         }
77         await this.update(collectionUuid, { preserveVersion: true });
78     }
79
80     async moveFile(collectionUuid: string, oldPath: string, newPath: string) {
81         await this.webdavClient.move(
82             `c=${collectionUuid}${oldPath}`,
83             `c=${collectionUuid}/${customEncodeURI(newPath)}`
84         );
85         await this.update(collectionUuid, { preserveVersion: true });
86     }
87
88     extendFileURL = (file: CollectionDirectory | CollectionFile) => {
89         const baseUrl = this.webdavClient.defaults.baseURL.endsWith('/')
90             ? this.webdavClient.defaults.baseURL.slice(0, -1)
91             : this.webdavClient.defaults.baseURL;
92         const apiToken = this.authService.getApiToken();
93         const encodedApiToken = apiToken ? encodeURI(apiToken) : '';
94         const userApiToken = `/t=${encodedApiToken}/`;
95         const splittedPrevFileUrl = file.url.split('/');
96         const url = `${baseUrl}/${splittedPrevFileUrl[1]}${userApiToken}${splittedPrevFileUrl.slice(2).join('/')}`;
97         return {
98             ...file,
99             url
100         };
101     }
102
103     private async uploadFile(collectionUuid: string, file: File, fileId: number, onProgress: UploadProgress = () => { return; }) {
104         const fileURL = `c=${collectionUuid}/${file.name}`;
105         const requestConfig = {
106             headers: {
107                 'Content-Type': 'text/octet-stream'
108             },
109             onUploadProgress: (e: ProgressEvent) => {
110                 onProgress(fileId, e.loaded, e.total, Date.now());
111             }
112         };
113         return this.webdavClient.upload(fileURL, [file], requestConfig);
114     }
115 }