refs #14671-download-file-from-collection-asks-for-auth
[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             const apiToken = this.authService.getApiToken();
58             const splittedApiToken = apiToken ? apiToken.split('/') : [];
59             const userApiToken = `/t=${splittedApiToken[2]}/`;
60             const splittedPrevFileUrl = file.url.split('/');
61             const url = `${baseUrl}/${splittedPrevFileUrl[1]}${userApiToken}${splittedPrevFileUrl[2]}`;
62         return {
63             ...file,
64             url
65         };
66     }
67
68     private async uploadFile(collectionUuid: string, file: File, fileId: number, onProgress: UploadProgress = () => { return; }) {
69         const fileURL = `c=${collectionUuid}/${file.name}`;
70         const requestConfig = {
71             headers: {
72                 'Content-Type': 'text/octet-stream'
73             },
74             onUploadProgress: (e: ProgressEvent) => {
75                 onProgress(fileId, e.loaded, e.total, Date.now());
76             }
77         };
78         return this.webdavClient.upload(fileURL, '', [file], requestConfig);
79     }
80
81     update(uuid: string, data: Partial<CollectionResource>) {
82         if (uuid && data && data.properties) {
83             const { properties } = data;
84             const mappedData = {
85                 ...TrashableResourceService.mapKeys(snakeCase)(data),
86                 properties,
87             };
88             return TrashableResourceService
89                 .defaultResponse(
90                     this.serverApi
91                         .put<CollectionResource>(this.resourceType + uuid, mappedData),
92                     this.actions,
93                     false
94                 );
95         }
96         return TrashableResourceService
97             .defaultResponse(
98                 this.serverApi
99                     .put<CollectionResource>(this.resourceType + uuid, data && TrashableResourceService.mapKeys(snakeCase)(data)),
100                 this.actions
101             );
102     }
103 }