1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
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 import { customEncodeURI } from "common/url";
14 import { FilterBuilder } from "services/api/filter-builder";
16 export type UploadProgress = (fileId: number, loaded: number, total: number, currentTime: number) => void;
18 export class CollectionService extends TrashableResourceService<CollectionResource> {
19 constructor(serverApi: AxiosInstance, private webdavClient: WebDAV, private authService: AuthService, actions: ApiActions) {
20 super(serverApi, "collections", actions, [
23 'replicationConfirmed',
24 'replicationConfirmedAt',
25 'storageClassesConfirmed',
26 'storageClassesConfirmedAt',
27 'unsignedManifestText',
32 async get(uuid: string, showErrors?: boolean) {
33 super.validateUuid(uuid);
34 // We use a filtered list request to avoid getting the manifest text
35 const filters = new FilterBuilder().addEqual('uuid', uuid).getFilters();
36 const lst = await super.list({filters}, showErrors);
40 create(data?: Partial<CollectionResource>) {
41 return super.create({ ...data, preserveVersion: true });
44 update(uuid: string, data: Partial<CollectionResource>) {
45 const select = [...Object.keys(data), 'version', 'modifiedAt'];
46 return super.update(uuid, { ...data, preserveVersion: true }, select);
49 async files(uuid: string) {
50 const request = await this.webdavClient.propfind(`c=${uuid}`);
51 if (request.responseXML != null) {
52 return extractFilesData(request.responseXML);
54 return Promise.reject();
57 async deleteFiles(collectionUuid: string, filePaths: string[]) {
58 const sortedUniquePaths = Array.from(new Set(filePaths))
59 .sort((a, b) => a.length - b.length)
60 .reduce((acc, currentPath) => {
61 const parentPathFound = acc.find((parentPath) => currentPath.indexOf(`${parentPath}/`) > -1);
63 if (!parentPathFound) {
64 return [...acc, currentPath];
70 for (const path of sortedUniquePaths) {
71 if (path.indexOf(collectionUuid) === -1) {
72 await this.webdavClient.delete(`c=${collectionUuid}${path}`);
74 await this.webdavClient.delete(`c=${path}`);
77 await this.update(collectionUuid, { preserveVersion: true });
80 async uploadFiles(collectionUuid: string, files: File[], onProgress?: UploadProgress) {
81 if (collectionUuid === "" || files.length === 0) { return; }
82 // files have to be uploaded sequentially
83 for (let idx = 0; idx < files.length; idx++) {
84 await this.uploadFile(collectionUuid, files[idx], idx, onProgress);
86 await this.update(collectionUuid, { preserveVersion: true });
89 async moveFile(collectionUuid: string, oldPath: string, newPath: string) {
90 await this.webdavClient.move(
91 `c=${collectionUuid}${oldPath}`,
92 `c=${collectionUuid}/${customEncodeURI(newPath)}`
94 await this.update(collectionUuid, { preserveVersion: true });
97 extendFileURL = (file: CollectionDirectory | CollectionFile) => {
98 const baseUrl = this.webdavClient.defaults.baseURL.endsWith('/')
99 ? this.webdavClient.defaults.baseURL.slice(0, -1)
100 : this.webdavClient.defaults.baseURL;
101 const apiToken = this.authService.getApiToken();
102 const encodedApiToken = apiToken ? encodeURI(apiToken) : '';
103 const userApiToken = `/t=${encodedApiToken}/`;
104 const splittedPrevFileUrl = file.url.split('/');
105 const url = `${baseUrl}/${splittedPrevFileUrl[1]}${userApiToken}${splittedPrevFileUrl.slice(2).join('/')}`;
112 private async uploadFile(collectionUuid: string, file: File, fileId: number, onProgress: UploadProgress = () => { return; }) {
113 const fileURL = `c=${collectionUuid}/${file.name}`;
114 const requestConfig = {
116 'Content-Type': 'text/octet-stream'
118 onUploadProgress: (e: ProgressEvent) => {
119 onProgress(fileId, e.loaded, e.total, Date.now());
122 return this.webdavClient.upload(fileURL, [file], requestConfig);