Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import * as path from 'path'
- import axios, { AxiosRequestConfig } from 'axios'
- import { request } from 'http'
- export class YandexDisk{
- private login: string
- private password: string
- private workDir: string
- constructor(login: string, password: string){
- this.login = login;
- this.password = password;
- this.workDir = "/";
- }
- public async createDir(path: string){
- try {
- const request = await this.sendRequest("MKCOL", path);
- return true;
- } catch {
- return false;
- }
- }
- public async deleteFile(path: string){
- try {
- const request = await this.sendRequest("DELETE", path);
- return true;
- } catch(e) {
- console.log(e);
- return false;
- }
- }
- public async uploadFile(srcFile: any, targetPath: string){
- try {
- const request = await this.sendRequest("PUT", targetPath, {
- 'Expect': '100-continue',
- 'Content-Type': 'application/binary',
- 'Transfer-Encoding': 'chunked',
- }, srcFile);
- return request
- } catch(e){
- console.log(e);
- }
- }
- public async sendRequest(method: any, path: string, headers: object={}, body: any=null){
- const authToken = Buffer.from(`${this.login}:${this.password}`).toString('base64');
- let options: AxiosRequestConfig = {
- baseURL: 'https://webdav.yandex.ru:443',
- method: method.toUpperCase(),
- url: encodeURI(this.normalizePath(path)),
- headers: {
- 'Host': 'webdav.yandex.ru',
- 'Accept': '*/*',
- 'Authorization': `Basic ${authToken}`,
- }
- };
- if (body){
- options.data = body
- }
- for (const header of Object.keys(headers)){
- Object.defineProperty(options.headers, header, {
- value: Object.getOwnPropertyDescriptor(headers, header)?.value,
- writable: true,
- configurable: true,
- enumerable: true});
- }
- let request = await axios(options);
- return request.data
- }
- private normalizePath(fpath: string) {
- return fpath.indexOf('/') == 0 ? fpath : path.join(this.workDir, fpath).replace(/\\/g, '/');
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement