1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
5 import { customEncodeURI } from "./url";
9 private defaults: WebDAVDefaults = {
12 'Cache-Control': 'no-cache'
16 constructor(config?: Partial<WebDAVDefaults>, private createRequest = () => new XMLHttpRequest()) {
22 ...this.defaults.headers,
29 getBaseUrl = (): string => this.defaults.baseURL;
30 setAuthorization = (token?) => this.defaults.headers.Authorization = token;
32 propfind = (url: string, config: WebDAVRequestConfig = {}) =>
38 put = (url: string, data?: any, config: WebDAVRequestConfig = {}) =>
45 get = (url: string, config: WebDAVRequestConfig = {}) =>
51 upload = (url: string, files: File[], config: WebDAVRequestConfig = {}) => {
53 files.map(file => this.request({
61 copy = (url: string, destination: string, config: WebDAVRequestConfig = {}) =>
67 Destination: this.defaults.baseURL
68 ? this.defaults.baseURL.replace(/\/+$/, '') + '/' + destination.replace(/^\/+/, '')
73 move = (url: string, destination: string, config: WebDAVRequestConfig = {}) =>
79 Destination: this.defaults.baseURL
80 ? this.defaults.baseURL.replace(/\/+$/, '') + '/' + destination.replace(/^\/+/, '')
85 delete = (url: string, config: WebDAVRequestConfig = {}) =>
91 private request = (config: RequestConfig) => {
92 return new Promise<XMLHttpRequest>((resolve, reject) => {
93 const r = this.createRequest();
94 this.defaults.baseURL = this.defaults.baseURL.replace(/\/+$/, '');
96 `${this.defaults.baseURL
97 ? this.defaults.baseURL + '/'
98 : ''}${customEncodeURI(config.url)}`);
100 const headers = { ...this.defaults.headers, ...config.headers };
103 .forEach(key => r.setRequestHeader(key, headers[key]));
105 if (!(window as any).cancelTokens) {
106 Object.assign(window, { cancelTokens: {} });
109 (window as any).cancelTokens[config.url] = () => {
114 if (config.onUploadProgress) {
115 r.upload.addEventListener('progress', config.onUploadProgress);
118 // This event gets triggered on *any* server response
119 r.addEventListener('load', () => {
120 if (r.status >= 400) {
127 // This event gets triggered on network errors
128 r.addEventListener('error', () => {
132 r.upload.addEventListener('error', () => {
141 export interface WebDAVRequestConfig {
143 [key: string]: string;
145 onUploadProgress?: (event: ProgressEvent) => void;
148 interface WebDAVDefaults {
150 headers: { [key: string]: string };
153 interface RequestConfig {
156 headers?: { [key: string]: string };
158 onUploadProgress?: (event: ProgressEvent) => void;