1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
5 import { customEncodeURI } from "./url";
9 defaults: WebDAVDefaults = {
14 constructor(config?: Partial<WebDAVDefaults>, private createRequest = () => new XMLHttpRequest()) {
16 this.defaults = { ...this.defaults, ...config };
20 propfind = (url: string, config: WebDAVRequestConfig = {}) =>
26 put = (url: string, data?: any, config: WebDAVRequestConfig = {}) =>
33 upload = (url: string, files: File[], config: WebDAVRequestConfig = {}) => {
35 files.map(file => this.request({
43 copy = (url: string, destination: string, config: WebDAVRequestConfig = {}) =>
49 Destination: this.defaults.baseURL
50 ? this.defaults.baseURL.replace(/\/+$/, '') + '/' + destination.replace(/^\/+/, '')
55 move = (url: string, destination: string, config: WebDAVRequestConfig = {}) =>
61 Destination: this.defaults.baseURL
62 ? this.defaults.baseURL.replace(/\/+$/, '') + '/' + destination.replace(/^\/+/, '')
67 delete = (url: string, config: WebDAVRequestConfig = {}) =>
73 private request = (config: RequestConfig) => {
74 return new Promise<XMLHttpRequest>((resolve, reject) => {
75 const r = this.createRequest();
76 this.defaults.baseURL = this.defaults.baseURL.replace(/\/+$/, '');
78 `${this.defaults.baseURL
79 ? this.defaults.baseURL+'/'
80 : ''}${customEncodeURI(config.url)}`);
82 if (config.headers && config.headers.Destination) {
83 const regexp = /(http[s]?:\/\/)?([^\/\s]+\/)(.*)/;
84 const match = decodeURIComponent(config.headers.Destination).match(regexp) || {};
85 config.headers.Destination = `${match[1]}${match[2]}${customEncodeURI(match[3])}`;
88 const headers = { ...this.defaults.headers, ...config.headers };
91 .forEach(key => r.setRequestHeader(key, headers[key]));
93 if (config.onUploadProgress) {
94 r.upload.addEventListener('progress', config.onUploadProgress);
97 // This event gets triggered on *any* server response
98 r.addEventListener('load', () => {
99 if (r.status >= 400) {
106 // This event gets triggered on network errors
107 r.addEventListener('error', () => {
111 r.upload.addEventListener('error', () => {
120 export interface WebDAVRequestConfig {
122 [key: string]: string;
124 onUploadProgress?: (event: ProgressEvent) => void;
127 interface WebDAVDefaults {
129 headers: { [key: string]: string };
132 interface RequestConfig {
135 headers?: { [key: string]: string };
137 onUploadProgress?: (event: ProgressEvent) => void;