1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
5 import { CollectionResource, defaultCollectionSelectedFields } from "models/collection";
6 import { AxiosInstance, AxiosResponse } 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 { Session } from "models/session";
14 import { CommonService } from "services/common-service/common-service";
15 import { snakeCase } from "lodash";
16 import { CommonResourceServiceError } from "services/common-service/common-resource-service";
18 export type UploadProgress = (fileId: number, loaded: number, total: number, currentTime: number) => void;
19 type CollectionPartialUpdateOrCreate =
20 | (Partial<CollectionResource> & Pick<CollectionResource, "uuid">)
21 | (Partial<CollectionResource> & Pick<CollectionResource, "ownerUuid">);
23 type ReplaceFilesPayload = {
24 collection: Partial<CollectionResource>;
25 replace_files: {[key: string]: string};
28 export const emptyCollectionPdh = "d41d8cd98f00b204e9800998ecf8427e+0";
29 export const SOURCE_DESTINATION_EQUAL_ERROR_MESSAGE = "Source and destination cannot be the same";
31 export class CollectionService extends TrashableResourceService<CollectionResource> {
32 constructor(serverApi: AxiosInstance, private keepWebdavClient: WebDAV, private authService: AuthService, actions: ApiActions) {
33 super(serverApi, "collections", actions, [
36 "replicationConfirmed",
37 "replicationConfirmedAt",
38 "storageClassesConfirmed",
39 "storageClassesConfirmedAt",
40 "unsignedManifestText",
45 async get(uuid: string, showErrors?: boolean, select?: string[], session?: Session) {
46 super.validateUuid(uuid);
47 const selectParam = select || defaultCollectionSelectedFields;
48 return super.get(uuid, showErrors, selectParam, session);
51 create(data?: Partial<CollectionResource>, showErrors?: boolean) {
52 return super.create({ ...data, preserveVersion: true }, showErrors);
55 update(uuid: string, data: Partial<CollectionResource>, showErrors?: boolean) {
56 const select = [...Object.keys(data), "version", "modifiedAt"];
57 return super.update(uuid, { ...data, preserveVersion: true }, showErrors, select);
60 async files(uuid: string) {
62 const request = await this.keepWebdavClient.propfind(`c=${uuid}`);
63 if (request.responseXML != null) {
64 return extractFilesData(request.responseXML);
67 return Promise.reject(e);
69 return Promise.reject();
72 private combineFilePath(parts: string[]) {
73 return parts.reduce((path, part) => {
74 // Trim leading and trailing slashes
75 const trimmedPart = part.split("/").filter(Boolean).join("/");
76 if (trimmedPart.length) {
77 const separator = path.endsWith("/") ? "" : "/";
78 return `${path}${separator}${trimmedPart}`;
85 private replaceFiles(data: CollectionPartialUpdateOrCreate, fileMap: {}, showErrors?: boolean) {
86 const payload: ReplaceFilesPayload = {
88 preserve_version: true,
89 ...CommonService.mapKeys(snakeCase)(data),
90 // Don't send uuid in payload when creating
93 replace_files: fileMap,
96 return CommonService.defaultResponse(
97 this.serverApi.put<ReplaceFilesPayload, AxiosResponse<CollectionResource>>(`/${this.resourceType}/${data.uuid}`, payload),
103 return CommonService.defaultResponse(
104 this.serverApi.post<ReplaceFilesPayload, AxiosResponse<CollectionResource>>(`/${this.resourceType}`, payload),
112 async uploadFiles(collectionUuid: string, files: File[], onProgress?: UploadProgress, targetLocation: string = "") {
113 if (collectionUuid === "" || files.length === 0) {
116 // files have to be uploaded sequentially
117 for (let idx = 0; idx < files.length; idx++) {
118 await this.uploadFile(collectionUuid, files[idx], idx, onProgress, targetLocation);
120 await this.update(collectionUuid, { preserveVersion: true });
123 async renameFile(collectionUuid: string, collectionPdh: string, oldPath: string, newPath: string) {
124 return this.replaceFiles(
125 { uuid: collectionUuid },
127 [this.combineFilePath([newPath])]: `${collectionPdh}${this.combineFilePath([oldPath])}`,
128 [this.combineFilePath([oldPath])]: "",
133 extendFileURL = (file: CollectionDirectory | CollectionFile) => {
134 const baseUrl = this.keepWebdavClient.getBaseUrl().endsWith("/")
135 ? this.keepWebdavClient.getBaseUrl().slice(0, -1)
136 : this.keepWebdavClient.getBaseUrl();
137 const apiToken = this.authService.getApiToken();
138 const encodedApiToken = apiToken ? encodeURI(apiToken) : "";
139 const userApiToken = `/t=${encodedApiToken}/`;
140 const splittedPrevFileUrl = file.url.split("/");
141 const url = `${baseUrl}/${splittedPrevFileUrl[1]}${userApiToken}${splittedPrevFileUrl.slice(2).join("/")}`;
148 async getFileContents(file: CollectionFile) {
149 return (await this.keepWebdavClient.get(`c=${file.id}`)).response;
152 private async uploadFile(
153 collectionUuid: string,
156 onProgress: UploadProgress = () => {
159 targetLocation: string = ""
161 const fileURL = `c=${targetLocation !== "" ? targetLocation : collectionUuid}/${file.name}`.replace("//", "/");
162 const requestConfig = {
164 "Content-Type": "text/octet-stream",
166 onUploadProgress: (e: ProgressEvent) => {
167 onProgress(fileId, e.loaded, e.total, Date.now());
170 return this.keepWebdavClient.upload(fileURL, [file], requestConfig);
173 deleteFiles(collectionUuid: string, files: string[], showErrors?: boolean) {
174 const optimizedFiles = files
175 .sort((a, b) => a.length - b.length)
176 .reduce((acc, currentPath) => {
177 const parentPathFound = acc.find(parentPath => currentPath.indexOf(`${parentPath}/`) > -1);
179 if (!parentPathFound) {
180 return [...acc, currentPath];
186 const fileMap = optimizedFiles.reduce((obj, filePath) => {
189 [this.combineFilePath([filePath])]: "",
193 return this.replaceFiles({ uuid: collectionUuid }, fileMap, showErrors);
199 destinationCollection: CollectionPartialUpdateOrCreate,
200 destinationPath: string,
203 const fileMap = files.reduce((obj, sourceFile) => {
204 const fileBasename = sourceFile.split("/").filter(Boolean).slice(-1).join("");
207 [this.combineFilePath([destinationPath, fileBasename])]: `${sourcePdh}${this.combineFilePath([sourceFile])}`,
211 return this.replaceFiles(destinationCollection, fileMap, showErrors);
218 destinationCollection: CollectionPartialUpdateOrCreate,
219 destinationPath: string,
222 if (sourceUuid === destinationCollection.uuid) {
223 let errors: CommonResourceServiceError[] = [];
224 const fileMap = files.reduce((obj, sourceFile) => {
225 const fileBasename = sourceFile.split("/").filter(Boolean).slice(-1).join("");
226 const fileDestinationPath = this.combineFilePath([destinationPath, fileBasename]);
227 const fileSourcePath = this.combineFilePath([sourceFile]);
228 const fileSourceUri = `${sourcePdh}${fileSourcePath}`;
230 if (fileDestinationPath !== fileSourcePath) {
233 [fileDestinationPath]: fileSourceUri,
234 [fileSourcePath]: "",
237 errors.push(CommonResourceServiceError.SOURCE_DESTINATION_CANNOT_BE_SAME);
242 if (errors.length === 0) {
243 return this.replaceFiles({ uuid: sourceUuid }, fileMap, showErrors);
245 return Promise.reject({ errors });
248 return this.copyFiles(sourcePdh, files, destinationCollection, destinationPath, showErrors).then(() => {
249 return this.deleteFiles(sourceUuid, files, showErrors);
254 createDirectory(collectionUuid: string, path: string, showErrors?: boolean) {
255 const fileMap = { [this.combineFilePath([path])]: emptyCollectionPdh };
257 return this.replaceFiles({ uuid: collectionUuid }, fileMap, showErrors);