Merge branch '13862-get-current-projects-picker-selection'
[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 { mapTreeValues } from "~/models/tree";
11 import { parseFilesResponse } from "./collection-service-files-response";
12 import { fileToArrayBuffer } from "~/common/file";
13 import { TrashableResourceService } from "~/services/common-service/trashable-resource-service";
14 import { ApiActions } from "~/services/api/api-actions";
15 import { snakeCase } from 'lodash';
16
17 export type UploadProgress = (fileId: number, loaded: number, total: number, currentTime: number) => void;
18
19 export class CollectionService extends TrashableResourceService<CollectionResource> {
20     constructor(serverApi: AxiosInstance, private webdavClient: WebDAV, private authService: AuthService, actions: ApiActions) {
21         super(serverApi, "collections", actions);
22     }
23
24     async files(uuid: string) {
25         const request = await this.webdavClient.propfind(`c=${uuid}`);
26         if (request.responseXML != null) {
27             const filesTree = parseFilesResponse(request.responseXML);
28             return mapTreeValues(this.extendFileURL)(filesTree);
29         }
30         return Promise.reject();
31     }
32
33     async deleteFiles(collectionUuid: string, filePaths: string[]) {
34         for (const path of filePaths) {
35             await this.webdavClient.delete(`c=${collectionUuid}${path}`);
36         }
37     }
38
39     async uploadFiles(collectionUuid: string, files: File[], onProgress?: UploadProgress) {
40         // files have to be uploaded sequentially
41         for (let idx = 0; idx < files.length; idx++) {
42             await this.uploadFile(collectionUuid, files[idx], idx, onProgress);
43         }
44     }
45
46     moveFile(collectionUuid: string, oldPath: string, newPath: string) {
47         return this.webdavClient.move(
48             `c=${collectionUuid}${oldPath}`,
49             `c=${collectionUuid}${encodeURI(newPath)}`
50         );
51     }
52
53     private extendFileURL = (file: CollectionDirectory | CollectionFile) => {
54         const baseUrl = this.webdavClient.defaults.baseURL.endsWith('/')
55             ? this.webdavClient.defaults.baseURL.slice(0, -1)
56             : this.webdavClient.defaults.baseURL;
57         return {
58             ...file,
59             url: baseUrl + file.url + '?api_token=' + this.authService.getApiToken()
60         };
61     }
62
63     private async uploadFile(collectionUuid: string, file: File, fileId: number, onProgress: UploadProgress = () => { return; }) {
64         const fileURL = `c=${collectionUuid}/${file.name}`;
65         const fileContent = await fileToArrayBuffer(file);
66         const requestConfig = {
67             headers: {
68                 'Content-Type': 'text/octet-stream'
69             },
70             onUploadProgress: (e: ProgressEvent) => {
71                 onProgress(fileId, e.loaded, e.total, Date.now());
72             }
73         };
74         return this.webdavClient.put(fileURL, fileContent, requestConfig);
75
76     }
77
78     update(uuid: string, data: Partial<CollectionResource>) {
79         if (uuid && data && data.properties) {
80             const { properties } = data;
81             const mappedData = {
82                 ...TrashableResourceService.mapKeys(snakeCase)(data),
83                 properties,
84             };
85             return TrashableResourceService
86                 .defaultResponse(
87                     this.serverApi
88                         .put<CollectionResource>(this.resourceType + uuid, mappedData),
89                     this.actions,
90                     false
91                 );
92         }
93         return TrashableResourceService
94             .defaultResponse(
95                 this.serverApi
96                     .put<CollectionResource>(this.resourceType + uuid, data && TrashableResourceService.mapKeys(snakeCase)(data)),
97                 this.actions
98             );
99     }
100 }