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";
15 import { ListArguments } from "services/common-service/common-service";
17 export type UploadProgress = (fileId: number, loaded: number, total: number, currentTime: number) => void;
19 export class CollectionService extends TrashableResourceService<CollectionResource> {
20 constructor(serverApi: AxiosInstance, private webdavClient: WebDAV, private authService: AuthService, actions: ApiActions) {
21 super(serverApi, "collections", actions, [
24 'replicationConfirmed',
25 'replicationConfirmedAt',
26 'storageClassesConfirmed',
27 'storageClassesConfirmedAt',
28 'unsignedManifestText',
33 async get(uuid: string, showErrors?: boolean, select?: string[]) {
34 super.validateUuid(uuid);
35 // We use a filtered list request to avoid getting the manifest text
36 const filters = new FilterBuilder().addEqual('uuid', uuid).getFilters();
37 const listArgs: ListArguments = {filters, includeOldVersions: true};
39 listArgs.select = select;
41 const lst = await super.list(listArgs, showErrors);
45 create(data?: Partial<CollectionResource>) {
46 return super.create({ ...data, preserveVersion: true });
49 update(uuid: string, data: Partial<CollectionResource>) {
50 const select = [...Object.keys(data), 'version', 'modifiedAt'];
51 return super.update(uuid, { ...data, preserveVersion: true }, select);
54 async files(uuid: string) {
55 const request = await this.webdavClient.propfind(`c=${uuid}`);
56 if (request.responseXML != null) {
57 return extractFilesData(request.responseXML);
59 return Promise.reject();
62 async deleteFiles(collectionUuid: string, filePaths: string[]) {
63 const sortedUniquePaths = Array.from(new Set(filePaths))
64 .sort((a, b) => a.length - b.length)
65 .reduce((acc, currentPath) => {
66 const parentPathFound = acc.find((parentPath) => currentPath.indexOf(`${parentPath}/`) > -1);
68 if (!parentPathFound) {
69 return [...acc, currentPath];
75 for (const path of sortedUniquePaths) {
76 if (path.indexOf(collectionUuid) === -1) {
77 await this.webdavClient.delete(`c=${collectionUuid}${path}`);
79 await this.webdavClient.delete(`c=${path}`);
82 await this.update(collectionUuid, { preserveVersion: true });
85 async uploadFiles(collectionUuid: string, files: File[], onProgress?: UploadProgress) {
86 if (collectionUuid === "" || files.length === 0) { return; }
87 // files have to be uploaded sequentially
88 for (let idx = 0; idx < files.length; idx++) {
89 await this.uploadFile(collectionUuid, files[idx], idx, onProgress);
91 await this.update(collectionUuid, { preserveVersion: true });
94 async moveFile(collectionUuid: string, oldPath: string, newPath: string) {
95 await this.webdavClient.move(
96 `c=${collectionUuid}${oldPath}`,
97 `c=${collectionUuid}/${customEncodeURI(newPath)}`
99 await this.update(collectionUuid, { preserveVersion: true });
102 extendFileURL = (file: CollectionDirectory | CollectionFile) => {
103 const baseUrl = this.webdavClient.defaults.baseURL.endsWith('/')
104 ? this.webdavClient.defaults.baseURL.slice(0, -1)
105 : this.webdavClient.defaults.baseURL;
106 const apiToken = this.authService.getApiToken();
107 const encodedApiToken = apiToken ? encodeURI(apiToken) : '';
108 const userApiToken = `/t=${encodedApiToken}/`;
109 const splittedPrevFileUrl = file.url.split('/');
110 const url = `${baseUrl}/${splittedPrevFileUrl[1]}${userApiToken}${splittedPrevFileUrl.slice(2).join('/')}`;
117 private async uploadFile(collectionUuid: string, file: File, fileId: number, onProgress: UploadProgress = () => { return; }) {
118 const fileURL = `c=${collectionUuid}/${file.name}`;
119 const requestConfig = {
121 'Content-Type': 'text/octet-stream'
123 onUploadProgress: (e: ProgressEvent) => {
124 onProgress(fileId, e.loaded, e.total, Date.now());
127 return this.webdavClient.upload(fileURL, [file], requestConfig);