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