17152: Avoids doing one extra request to persist versions on update.
[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         if (collectionUuid === "" || filePaths.length === 0) { return; }
48         for (const path of filePaths) {
49             const splittedPath = path.split('/');
50             if (collectionUuid) {
51                 await this.webdavClient.delete(`c=${collectionUuid}/${splittedPath[1]}`);
52             } else {
53                 await this.webdavClient.delete(`c=${collectionUuid}${path}`);
54             }
55         }
56         await this.update(collectionUuid, { preserveVersion: true });
57     }
58
59     async uploadFiles(collectionUuid: string, files: File[], onProgress?: UploadProgress) {
60         if (collectionUuid === "" || files.length === 0) { return; }
61         // files have to be uploaded sequentially
62         for (let idx = 0; idx < files.length; idx++) {
63             await this.uploadFile(collectionUuid, files[idx], idx, onProgress);
64         }
65         await this.update(collectionUuid, { preserveVersion: true });
66     }
67
68     async moveFile(collectionUuid: string, oldPath: string, newPath: string) {
69         await this.webdavClient.move(
70             `c=${collectionUuid}${oldPath}`,
71             `c=${collectionUuid}${encodeURI(newPath)}`
72         );
73         return await this.update(collectionUuid, { preserveVersion: true });
74     }
75
76     extendFileURL = (file: CollectionDirectory | CollectionFile) => {
77         const baseUrl = this.webdavClient.defaults.baseURL.endsWith('/')
78             ? this.webdavClient.defaults.baseURL.slice(0, -1)
79             : this.webdavClient.defaults.baseURL;
80         const apiToken = this.authService.getApiToken();
81         const encodedApiToken = apiToken ? encodeURI(apiToken) : '';
82         const userApiToken = `/t=${encodedApiToken}/`;
83         const splittedPrevFileUrl = file.url.split('/');
84         const url = `${baseUrl}/${splittedPrevFileUrl[1]}${userApiToken}${splittedPrevFileUrl.slice(2).join('/')}`;
85         return {
86             ...file,
87             url
88         };
89     }
90
91     private async uploadFile(collectionUuid: string, file: File, fileId: number, onProgress: UploadProgress = () => { return; }) {
92         const fileURL = `c=${collectionUuid}/${file.name}`;
93         const requestConfig = {
94             headers: {
95                 'Content-Type': 'text/octet-stream'
96             },
97             onUploadProgress: (e: ProgressEvent) => {
98                 onProgress(fileId, e.loaded, e.total, Date.now());
99             }
100         };
101         return this.webdavClient.upload(fileURL, [file], requestConfig);
102     }
103 }