Skip to content

LightAPIs/userscript-with-webdav

Repository files navigation

userscript-with-webdav

Connect WebDAV in the Tampermonkey/Violentmonkey script.

Installation

in userscript:

// @require  https://cdn.jsdelivr.net/npm/userscript-with-webdav@latest/index.iife.js
// @grant    GM_xmlhttpRequest
// @connect  *

or embed:

npm install userscript-with-webdav

Usage

Example:

// When embed:
import Webdav from 'userscript-with-webdav';

(async () => {
  const wh = new Webdav('<webDAVURL>', '<webDAVUser>', '<webDAVPassword>');

  // download
  try {
    const res = await wh.download('path/to/your/file');
    console.log('status:', res.status);
    console.log('data:', res.data);
  } catch (err) {
    if (err instanceof Webdav.NotFound) {
      console.error('file does not exist');
    } else if (err instanceof Webdav.Unauthorized) {
      console.error('authentication failed');
    }
  }

  // upload
  try {
    await wh.upload('path/to/your/file', '<data>');
  } catch (err) {
    if (err instanceof Webdav.Forbidden) {
      console.error('permission error');
    }
  }
})();

Type

declare class Webdav {
  static InternalError: typeof InternalError;
  static Unauthorized: typeof Unauthorized;
  static Forbidden: typeof Forbidden;
  static NotFound: typeof NotFound;
  static Redirection: typeof Redirection;
  static ClientSideError: typeof ClientSideError;
  static ServerSideError: typeof ServerSideError;
  /**
   * Constructor
   * @param domainURL WebDAV domain
   * @param user User name
   * @param password User password
   */
  constructor(domainURL?: string, user?: string, password?: string);
  /**
   * Generate validation request header
   * @returns Verification request header
   */
  updateConfig(domainURL: string, user: string, password: string): void;
  /**
   * Download file content
   * @param fileURL Relative file URL
   * @returns Response
   */
  download(fileURL: string): Promise<ConnectionResponse>;
  /**
   * Upload file content
   * @param fileURL Relative file URL
   * @param data Data
   * @returns Response
   */
  upload(fileURL: string, data: string): Promise<ConnectionResponse>;
}

declare interface ConnectionResponse {
    /** Response status code */
    status: number;
    /** Response data */
    data: string;
}

License

MIT