merge-conflicts
[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 { CommonResourceService } from "~/common/api/common-resource-service";
6 import { CollectionResource } from "~/models/collection";
7 import { AxiosInstance } from "axios";
8 import { CollectionFile, CollectionDirectory } from "~/models/collection-file";
9 import { WebDAV } from "~/common/webdav";
10 import { AuthService } from "../auth-service/auth-service";
11 import { mapTreeValues } from "~/models/tree";
12 import { parseFilesResponse } from "./collection-service-files-response";
13 import { fileToArrayBuffer } from "~/common/file";
14
15 export type UploadProgress = (fileId: number, loaded: number, total: number, currentTime: number) => void;
16
17 export class CollectionService extends CommonResourceService<CollectionResource> {
18     constructor(serverApi: AxiosInstance, private webdavClient: WebDAV, private authService: AuthService) {
19         super(serverApi, "collections");
20     }
21
22     async files(uuid: string) {
23         const request = await this.webdavClient.propfind(`/c=${uuid}`);
24         if (request.responseXML != null) {
25             const filesTree = parseFilesResponse(request.responseXML);
26             return mapTreeValues(this.extendFileURL)(filesTree);
27         }
28         return Promise.reject();
29     }
30
31     async deleteFile(collectionUuid: string, filePath: string) {
32         return this.webdavClient.delete(`/c=${collectionUuid}${filePath}`);
33     }
34
35     async uploadFiles(collectionUuid: string, files: File[], onProgress?: UploadProgress) {
36         // files have to be uploaded sequentially
37         for (let idx = 0; idx < files.length; idx++) {
38             await this.uploadFile(collectionUuid, files[idx], idx, onProgress);
39         }
40     }
41
42     private extendFileURL = (file: CollectionDirectory | CollectionFile) => ({
43         ...file,
44         url: this.webdavClient.defaults.baseURL + file.url + '?api_token=' + this.authService.getApiToken()
45     })
46
47     private async uploadFile(collectionUuid: string, file: File, fileId: number, onProgress: UploadProgress = () => { return; }) {
48         const fileURL = `/c=${collectionUuid}/${file.name}`;
49         const fileContent = await fileToArrayBuffer(file);
50         const requestConfig = {
51             headers: {
52                 'Content-Type': 'text/octet-stream'
53             },
54             onUploadProgress: (e: ProgressEvent) => {
55                 onProgress(fileId, e.loaded, e.total, Date.now());
56             }
57         };
58         return this.webdavClient.put(fileURL, fileContent, requestConfig);
59
60     }
61
62 }