17152: Adjusts the collection service methods to preserve versions.
[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     async update(uuid: string, data: Partial<CollectionResource>) {
35         // First make the changes
36         const collection = await super.update(uuid, data);
37         if (data === { preserveVersion: true }) { return collection; }
38         // Then set the head version to be preserved
39         return await super.update(uuid, { preserveVersion: true });
40     }
41
42     async files(uuid: string) {
43         const request = await this.webdavClient.propfind(`c=${uuid}`);
44         if (request.responseXML != null) {
45             return extractFilesData(request.responseXML);
46         }
47         return Promise.reject();
48     }
49
50     async deleteFiles(collectionUuid: string, filePaths: string[]) {
51         if (collectionUuid === "" || filePaths.length === 0) { return; }
52         for (const path of filePaths) {
53             const splittedPath = path.split('/');
54             if (collectionUuid) {
55                 await this.webdavClient.delete(`c=${collectionUuid}/${splittedPath[1]}`);
56             } else {
57                 await this.webdavClient.delete(`c=${collectionUuid}${path}`);
58             }
59         }
60         await this.update(collectionUuid, { preserveVersion: true });
61     }
62
63     async uploadFiles(collectionUuid: string, files: File[], onProgress?: UploadProgress) {
64         if (collectionUuid === "" || files.length === 0) { return; }
65         // files have to be uploaded sequentially
66         for (let idx = 0; idx < files.length; idx++) {
67             await this.uploadFile(collectionUuid, files[idx], idx, onProgress);
68         }
69         await this.update(collectionUuid, { preserveVersion: true });
70     }
71
72     async moveFile(collectionUuid: string, oldPath: string, newPath: string) {
73         await this.webdavClient.move(
74             `c=${collectionUuid}${oldPath}`,
75             `c=${collectionUuid}${encodeURI(newPath)}`
76         );
77         return await this.update(collectionUuid, { preserveVersion: true });
78     }
79
80     extendFileURL = (file: CollectionDirectory | CollectionFile) => {
81         const baseUrl = this.webdavClient.defaults.baseURL.endsWith('/')
82             ? this.webdavClient.defaults.baseURL.slice(0, -1)
83             : this.webdavClient.defaults.baseURL;
84         const apiToken = this.authService.getApiToken();
85         const encodedApiToken = apiToken ? encodeURI(apiToken) : '';
86         const userApiToken = `/t=${encodedApiToken}/`;
87         const splittedPrevFileUrl = file.url.split('/');
88         const url = `${baseUrl}/${splittedPrevFileUrl[1]}${userApiToken}${splittedPrevFileUrl.slice(2).join('/')}`;
89         return {
90             ...file,
91             url
92         };
93     }
94
95     private async uploadFile(collectionUuid: string, file: File, fileId: number, onProgress: UploadProgress = () => { return; }) {
96         const fileURL = `c=${collectionUuid}/${file.name}`;
97         const requestConfig = {
98             headers: {
99                 'Content-Type': 'text/octet-stream'
100             },
101             onUploadProgress: (e: ProgressEvent) => {
102                 onProgress(fileId, e.loaded, e.total, Date.now());
103             }
104         };
105         return this.webdavClient.upload(fileURL, [file], requestConfig);
106     }
107 }