"use strict";
var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (g && (g = 0, op[0] && (_ = 0)), _) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.FileService = void 0;
// import { uid } from "uid";
var fs = require("fs");
// import * as mkdirp from 'mkdirp'
// import {deleteAsync} from 'del';
var path = require("path");
var nodePath = path;
// import moment = require("moment")
// import * as cp from 'child-process'
// const cp = require('child-process');
// console.log('cp', cp)
var Client = require("ssh2-sftp-client");
var child_process_1 = require("child_process");
var uid_1 = require("uid");
var tsdav_1 = require("tsdav");
var Url = require("url-parse");
// import axios from 'axios';
var JSZip = require("jszip");
var OSS = require('ali-oss');
var axios = require('axios');
// import * as OSS from 'ali-oss'
// const zipPath = '/Users/yunser/app/test/未命名文件夹/归档.zip'
// read a zip file
// let publicConfig = {
//     bucket: 'xxx-public',
//     region: 'oss-cn-beijing',
//     accessKeyId: 'xx',
//     accessKeySecret: 'xx'
// }
// let publicStore = new OSS(publicConfig)
var g_webdav = {};
var g_publicStores = {};
function loadJson(path, defaultValue) {
    if (defaultValue === void 0) { defaultValue = null; }
    return __awaiter(this, void 0, void 0, function () {
        var content;
        return __generator(this, function (_a) {
            content = fs.readFileSync(path, 'utf-8');
            // console.log('content', content)
            if (content) {
                return [2 /*return*/, JSON.parse(content)];
            }
            return [2 /*return*/, defaultValue];
        });
    });
}
function getZipList(zipPath) {
    return new Promise(function (resolve) {
        fs.readFile(zipPath, function (err, data) {
            if (err)
                throw err;
            JSZip.loadAsync(data).then(function (zip) {
                // ...
                // console.log('zip', zip)
                var files = zip.files;
                var fileNames = Object.keys(files);
                var list = [];
                for (var _i = 0, fileNames_1 = fileNames; _i < fileNames_1.length; _i++) {
                    var fileName = fileNames_1[_i];
                    list.push(files[fileName]);
                }
                resolve(list);
            });
        });
    });
}
// let Client = require('ssh2-sftp-client');
// import trash from 'trash'
// import * as os from 'os'
// import('trash').then(transh => {
//     console.log('transh', transh)
// })
// console.log('trash', trash)
// async function load() {
//     const trash = await import('trash')
//     console.log('trash', trash)
// }
// load()
/**
 * 删除整个文件夹
 * @param {*} path
 */
function rmDir(path) {
    var _this = this;
    if (fs.existsSync(path)) {
        var dirs = [];
        var files = fs.readdirSync(path);
        files.forEach(function (file) { return __awaiter(_this, void 0, void 0, function () {
            var childPath;
            return __generator(this, function (_a) {
                childPath = path + "/" + file;
                if (fs.statSync(childPath).isDirectory()) {
                    rmDir(childPath);
                    //   dirs.push(childPath);
                }
                else {
                    fs.unlinkSync(childPath);
                }
                return [2 /*return*/];
            });
        }); });
        //   dirs.forEach((fir) => fs.rmdirSync(fir));
        fs.rmdirSync(path);
    }
    console.log('ok');
}
function sleep(ms) {
    return new Promise(function (resolve) {
        setTimeout(function () {
            resolve(null);
        }, ms);
    });
}
// const db = new client.Database(path.resolve(__dirname, 'db/tester.db'))
var g_connections = {};
// let g_sftp: Client
// let g_
// .then(() => {
//     return sftp.list('/root');
//   }).then(data => {
//     console.log('the data info', data);
//   }).catch(err => {
//     console.log(err, 'catch error');
//   });
var USER_HOME = process.env.HOME || process.env.USERPROFILE;
var yunserFolder = path.resolve(USER_HOME, '.yunser'); // TODO package，npm install cmd-core
// if (!fs.existsSync(yunserFolder)) {
//     // console.log('创建目录')
//     fs.mkdirSync(yunserFolder)
// }
var appFolder = path.resolve(yunserFolder, 'dms-cli'); // TODO package，npm install cmd-core
// if (!fs.existsSync(appFolder)) {
//     fs.mkdirSync(appFolder)
// }
var collectionDbFilePath = path.resolve(appFolder, 'file.collection.json');
if (!fs.existsSync(collectionDbFilePath)) {
    // console.log('创建目录')
    // fs.mkdirSync(yunserFolder)
    fs.writeFileSync(collectionDbFilePath, '[]', 'utf8');
}
var ossDbFilePath = path.resolve(appFolder, 'oss-v2.json');
if (!fs.existsSync(ossDbFilePath)) {
    // console.log('创建目录')
    // fs.mkdirSync(yunserFolder)
    fs.writeFileSync(ossDbFilePath, JSON.stringify({
        version: '2.0.0',
        accessKeys: [],
        favoriteBuckets: []
    }, null, 4), 'utf8');
}
var swaggerDbFilePath = path.resolve(appFolder, 'swagger.json');
if (!fs.existsSync(swaggerDbFilePath)) {
    // console.log('创建目录')
    // fs.mkdirSync(yunserFolder)
    var swaggerContent = [
        {
            id: '1',
            name: "Swagger Pet Store",
            url: 'https://petstore.swagger.io/v2/swagger.json'
        }
    ];
    fs.writeFileSync(swaggerDbFilePath, JSON.stringify(swaggerContent, null, 4), 'utf8');
}
var projectDbFilePath = path.resolve(appFolder, 'project.json');
if (!fs.existsSync(projectDbFilePath)) {
    // console.log('创建目录')
    // fs.mkdirSync(yunserFolder)
    var projectContent = {
        projects: [
            {
                id: '1',
                name: 'Example Project',
            }
        ]
    };
    fs.writeFileSync(projectDbFilePath, JSON.stringify(projectContent, null, 4), 'utf8');
}
var ossService = {
    // const list = await ossService.getAkList()
    getAkList: function () {
        return __awaiter(this, void 0, void 0, function () {
            var content, obj, aks, _i, aks_1, ak, _loop_1, _a, _b, bucket;
            return __generator(this, function (_c) {
                content = fs.readFileSync(ossDbFilePath, 'utf-8') || '[]';
                obj = JSON.parse(content);
                aks = obj.accessKeys;
                for (_i = 0, aks_1 = aks; _i < aks_1.length; _i++) {
                    ak = aks_1[_i];
                    _loop_1 = function (bucket) {
                        bucket.isFavorite = !!obj.favoriteBuckets.find(function (b) { return b.name == bucket.name; });
                    };
                    for (_a = 0, _b = ak.buckets; _a < _b.length; _a++) {
                        bucket = _b[_a];
                        _loop_1(bucket);
                    }
                }
                return [2 /*return*/, aks];
            });
        });
    },
    // await ossService.saveAkList(list)
    saveAkList: function (list) {
        return __awaiter(this, void 0, void 0, function () {
            var content, obj;
            return __generator(this, function (_a) {
                content = fs.readFileSync(ossDbFilePath, 'utf-8') || '[]';
                obj = JSON.parse(content);
                obj.accessKeys = list;
                fs.writeFileSync(ossDbFilePath, JSON.stringify(obj, null, 4), 'utf-8');
                return [2 /*return*/];
            });
        });
    },
};
var loggerDbFilePath = path.resolve(appFolder, 'logger.json');
var webdavDbFilePath = path.resolve(appFolder, 'webdav.json');
if (!fs.existsSync(webdavDbFilePath)) {
    // console.log('创建目录')
    // fs.mkdirSync(yunserFolder)
    var exampleList = [
        {}
    ];
    fs.writeFileSync(webdavDbFilePath, JSON.stringify(exampleList, null, 4), 'utf8');
}
// let gitSettingFilePath = path.resolve(appFolder, 'git.settings.json')
// if (!fs.existsSync(gitSettingFilePath)) {
//     // console.log('创建目录')
//     // fs.mkdirSync(yunserFolder)
//     fs.writeFileSync(gitSettingFilePath, '{}', 'utf8')
// }
function handleFolder(folderPath, r) {
    if (r === void 0) { r = false; }
    var fileNames = fs.readdirSync(folderPath);
    var results = [];
    for (var _i = 0, fileNames_2 = fileNames; _i < fileNames_2.length; _i++) {
        var fileName = fileNames_2[_i];
        if (fileName.startsWith('.')) {
            continue;
        }
        var filePath = path.resolve(folderPath, fileName);
        try {
            // const stat = fs.statSync(filePath)
            var stat = fs.lstatSync(filePath);
            // let type = stat.isFile() ? 'FILE' : 'DIRECTORY'
            // let path
            var node = {
                type: stat.isFile() ? 'FILE' : 'DIRECTORY',
                name: fileName,
                path: filePath,
                updateTime: stat.mtime,
                size: stat.size,
                // _stat: stat,
                isSymbolicLink: stat.isSymbolicLink() ? true : undefined,
                // _isFile: stat.isFile(),
                // _isDirectory: stat.isDirectory(),
            };
            if (stat.isSymbolicLink()) {
                var linkPath = fs.readlinkSync(filePath);
                var targetPath = linkPath;
                if (linkPath.startsWith('.')) {
                    targetPath = nodePath.resolve(filePath, '..', linkPath);
                }
                // node._targetPath = targetPath
                // node._link = linkPath
                node.path = targetPath;
                var _stat = fs.statSync(targetPath);
                node.type = _stat.isFile() ? 'FILE' : 'DIRECTORY';
            }
            if (r && stat.isDirectory()) {
                node.children = handleFolder(filePath, r);
            }
            results.push(node);
        }
        catch (err) {
            console.error(err);
            results.push({
                type: 'UNKNOWN',
                name: fileName,
                path: filePath,
            });
        }
    }
    return results;
}
function _copy(fromPath, toPath) {
    return new Promise((function (resolve) {
        var reader = fs.createReadStream(fromPath);
        var upStream = fs.createWriteStream(toPath);
        reader.pipe(upStream)
            .on('close', function () {
            resolve(null);
        });
        // .end(() => {
        // })
    }));
}
var folderPath = '/Users/yunser/app/dms-new';
var FileService = /** @class */ (function () {
    function FileService() {
    }
    FileService.prototype.getSftpClient = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var sourceType, path;
            return __generator(this, function (_a) {
                sourceType = body.sourceType, path = body.path;
                return [2 /*return*/, g_connections[sourceType]];
            });
        });
    };
    FileService.prototype.home = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                return [2 /*return*/, 'file home'];
            });
        });
    };
    FileService.prototype.info = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                return [2 /*return*/, {
                        homePath: USER_HOME,
                    }];
            });
        });
    };
    FileService.prototype.stat = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var sourceType, path, stat, g_sftp, stat;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        sourceType = body.sourceType, path = body.path;
                        if (!(sourceType == 'local')) return [3 /*break*/, 1];
                        stat = fs.statSync(path);
                        // atime: "2022-07-20T03:06:38.986Z"
                        // atimeMs: 1658286398985.5605
                        // birthtime: "2019-05-29T08:02:37.744Z"
                        // birthtimeMs: 1559116957743.9949
                        // blksize: 4096
                        // blocks: 0
                        // ctime: "2022-07-20T02:58:12.546Z"
                        // ctimeMs: 1658285892546.1113
                        // dev: 16777220
                        // gid: 20
                        // ino: 19585881
                        // mode: 16877
                        // mtime: "2022-07-20T02:58:12.546Z"
                        // mtimeMs: 1658285892546.1113
                        // nlink: 11
                        // rdev: 0
                        // size: 352
                        // uid: 501
                        return [2 /*return*/, {
                                stat: {
                                    modifyTime: new Date(stat.mtime),
                                    mode: stat.mode,
                                    _raw: stat,
                                },
                            }];
                    case 1: return [4 /*yield*/, this.getSftpClient(body)];
                    case 2:
                        g_sftp = _a.sent();
                        return [4 /*yield*/, g_sftp.stat(path)
                            // mode: 33279, // integer representing type and permissions
                            // uid: 1000, // user ID
                            // gid: 985, // group ID
                            // size: 5, // file size
                            // accessTime: 1566868566000, // Last access time. milliseconds
                            // modifyTime: 1566868566000, // last modify time. milliseconds
                            // isDirectory: false, // true if object is a directory
                            // isFile: true, // true if object is a file
                            // isBlockDevice: false, // true if object is a block device
                            // isCharacterDevice: false, // true if object is a character device
                            // isSymbolicLink: false, // true if object is a symbolic link
                            // isFIFO: false, // true if object is a FIFO
                            // isSocket: false // true if object is a socket
                        ];
                    case 3:
                        stat = _a.sent();
                        // mode: 33279, // integer representing type and permissions
                        // uid: 1000, // user ID
                        // gid: 985, // group ID
                        // size: 5, // file size
                        // accessTime: 1566868566000, // Last access time. milliseconds
                        // modifyTime: 1566868566000, // last modify time. milliseconds
                        // isDirectory: false, // true if object is a directory
                        // isFile: true, // true if object is a file
                        // isBlockDevice: false, // true if object is a block device
                        // isCharacterDevice: false, // true if object is a character device
                        // isSymbolicLink: false, // true if object is a symbolic link
                        // isFIFO: false, // true if object is a FIFO
                        // isSocket: false // true if object is a socket
                        return [2 /*return*/, {
                                stat: {
                                    modifyTime: new Date(stat.modifyTime),
                                    mode: stat.mode,
                                    _raw: stat,
                                },
                            }];
                }
            });
        });
    };
    FileService.prototype.sftpConnect = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var connectionId, client;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        connectionId = (0, uid_1.uid)(32);
                        client = new Client();
                        return [4 /*yield*/, client.connect({
                                host: body.host,
                                port: body.port,
                                username: body.username,
                                password: body.password,
                            })];
                    case 1:
                        _a.sent();
                        g_connections[connectionId] = client;
                        return [2 /*return*/, {
                                connectionId: connectionId,
                            }];
                }
            });
        });
    };
    FileService.prototype.loggerList = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var content, list;
            return __generator(this, function (_a) {
                content = fs.readFileSync(loggerDbFilePath, 'utf-8') || '[]';
                list = JSON.parse(content);
                return [2 /*return*/, {
                        list: list,
                    }];
            });
        });
    };
    FileService.prototype.webdavConnectionList = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var content, list;
            return __generator(this, function (_a) {
                content = fs.readFileSync(webdavDbFilePath, 'utf-8') || '[]';
                list = JSON.parse(content);
                return [2 /*return*/, {
                        list: list,
                    }];
            });
        });
    };
    FileService.prototype.webdavConnectionEdit = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var id, data, content, list, idx;
            return __generator(this, function (_a) {
                id = body.id, data = body.data;
                content = fs.readFileSync(webdavDbFilePath, 'utf-8');
                list = JSON.parse(content);
                idx = list.findIndex(function (_item) { return _item.id == id; });
                list[idx] = __assign(__assign({}, list[idx]), data);
                console.log('list', list);
                fs.writeFileSync(webdavDbFilePath, JSON.stringify(list, null, 4), 'utf-8');
                return [2 /*return*/, {}];
            });
        });
    };
    FileService.prototype.webdavConnectionCreate = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var content, list;
            return __generator(this, function (_a) {
                content = fs.readFileSync(webdavDbFilePath, 'utf-8');
                list = JSON.parse(content);
                list.unshift(__assign(__assign({}, body), { id: (0, uid_1.uid)(32) }));
                fs.writeFileSync(webdavDbFilePath, JSON.stringify(list, null, 4), 'utf-8');
                return [2 /*return*/, {}];
            });
        });
    };
    FileService.prototype.webdavConnectionDelete = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var id, content, list, newList;
            return __generator(this, function (_a) {
                id = body.id;
                content = fs.readFileSync(webdavDbFilePath, 'utf-8');
                list = JSON.parse(content);
                newList = list.filter(function (item) { return item.id != id; });
                console.log('id', id);
                console.log('newList', newList);
                fs.writeFileSync(webdavDbFilePath, JSON.stringify(newList, null, 4), 'utf-8');
                return [2 /*return*/, {}];
            });
        });
    };
    FileService.prototype.webdavConnect = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var url, username, password, headers, connectionId;
            return __generator(this, function (_a) {
                url = body.url, username = body.username, password = body.password;
                headers = tsdav_1.default.getBasicAuthHeaders({
                    username: username,
                    password: password,
                });
                connectionId = 'webdav:' + (0, uid_1.uid)(32);
                g_webdav[connectionId] = {
                    headers: headers,
                    url: url,
                };
                return [2 /*return*/, {
                        connectionId: connectionId
                    }];
            });
        });
    };
    FileService.prototype.accessKeyList = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var list;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, ossService.getAkList()];
                    case 1:
                        list = _a.sent();
                        return [2 /*return*/, {
                                list: list,
                            }];
                }
            });
        });
    };
    FileService.prototype.accessKeyEdit = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var id, data, list, idx, buckets, store, bucketResult;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        id = body.id, data = body.data;
                        return [4 /*yield*/, ossService.getAkList()];
                    case 1:
                        list = _a.sent();
                        idx = list.findIndex(function (_item) { return _item.id == id; });
                        buckets = [];
                        store = new OSS({
                            accessKeyId: data.accessKeyId,
                            accessKeySecret: data.accessKeySecret,
                        });
                        return [4 /*yield*/, store.listBuckets({
                            // "max-keys": 10
                            })];
                    case 2:
                        bucketResult = _a.sent();
                        console.log('bucketResult', bucketResult);
                        buckets = bucketResult.buckets;
                        list[idx] = __assign(__assign(__assign({}, list[idx]), data), { buckets: buckets });
                        return [4 /*yield*/, ossService.saveAkList(list)];
                    case 3:
                        _a.sent();
                        return [2 /*return*/, {}];
                }
            });
        });
    };
    FileService.prototype.accessKeyCreate = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var list, store, bucketResult, buckets;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, ossService.getAkList()];
                    case 1:
                        list = _a.sent();
                        store = new OSS({
                            accessKeyId: body.accessKeyId,
                            accessKeySecret: body.accessKeySecret,
                        });
                        return [4 /*yield*/, store.listBuckets({
                            // "max-keys": 10
                            })];
                    case 2:
                        bucketResult = _a.sent();
                        buckets = bucketResult.buckets;
                        list.unshift(__assign(__assign({}, body), { id: (0, uid_1.uid)(32), buckets: buckets }));
                        return [4 /*yield*/, ossService.saveAkList(list)];
                    case 3:
                        _a.sent();
                        return [2 /*return*/, {}];
                }
            });
        });
    };
    FileService.prototype.accessKeyDelete = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var id, list, newList;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        id = body.id;
                        return [4 /*yield*/, ossService.getAkList()];
                    case 1:
                        list = _a.sent();
                        newList = list.filter(function (item) { return item.id != id; });
                        console.log('id', id);
                        console.log('newList', newList);
                        return [4 /*yield*/, ossService.saveAkList(newList)];
                    case 2:
                        _a.sent();
                        return [2 /*return*/, {}];
                }
            });
        });
    };
    FileService.prototype.ossConnect = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var bucket, region, accessKeyId, accessKeySecret, connectionId;
            return __generator(this, function (_a) {
                bucket = body.bucket, region = body.region, accessKeyId = body.accessKeyId, accessKeySecret = body.accessKeySecret;
                connectionId = 'oss:' + (0, uid_1.uid)(32);
                g_publicStores[connectionId] = new OSS({
                    bucket: bucket,
                    region: region,
                    accessKeyId: accessKeyId,
                    accessKeySecret: accessKeySecret,
                });
                return [2 /*return*/, {
                        connectionId: connectionId
                    }];
            });
        });
    };
    FileService.prototype.ossInfo = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var sourceType, _a, path, simplePath, res;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        sourceType = body.sourceType, _a = body.path, path = _a === void 0 ? '/' : _a;
                        simplePath = path.replace(/^\//, '');
                        return [4 /*yield*/, g_publicStores[sourceType].generateObjectUrl(simplePath)];
                    case 1:
                        res = _b.sent();
                        console.log('res', res);
                        return [2 /*return*/, {
                                url: res,
                            }];
                }
            });
        });
    };
    FileService.prototype.ossList = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var sourceType, _a, path, simplePath, params, res, results;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        sourceType = body.sourceType, _a = body.path, path = _a === void 0 ? '/' : _a;
                        simplePath = path.replace(/^\//, '');
                        params = {
                            'max-keys': 100,
                            // prefix: '',
                            'prefix': path == '/' ? '' : (path.replace(/^\//, '') + '/'),
                            'delimiter': '/',
                            // marker 是实现分页时指向下一分页起始位置的标识。
                            // 阿里云 OSS 中不支持原生的文件夹，而是使用一个 0 字节的末尾为 / 的文件起到文件夹功能
                        };
                        console.log('params', params);
                        return [4 /*yield*/, g_publicStores[sourceType].list(params)
                            // console.log('res', res)
                        ];
                    case 1:
                        res = _b.sent();
                        results = [];
                        res.objects.forEach(function (item) {
                            // etag: "\"425E59DF40A72B04F032A939A36FD5AC\""
                            // lastModified: "2021-08-23T02:46:04.000Z"
                            // name: "公司.png"
                            // owner: {id: "1565619625401184", displayName: "1565619625401184"}
                            // size: 2198358
                            // storageClass: "Standard"
                            // type: "Normal"
                            // url: "http://linxot-public.oss-cn-beijing.aliyuncs.com/%E5%85%AC%E5%8F%B8.png"
                            var fileName = item.name.substring(simplePath.length).replace(/\/$/, '').replace(/^\//, '');
                            if (fileName) {
                                results.push({
                                    type: 'FILE',
                                    name: fileName,
                                    path: '/' + item.name,
                                    size: item.size,
                                    updateTime: item.lastModified,
                                });
                            }
                            // return {
                            // }
                        });
                        if (res.prefixes) {
                            res.prefixes.forEach(function (ossFolderName) {
                                var folderName = ossFolderName.replace(/\/$/, '').substring(simplePath.length).replace(/^\//, '');
                                // const fileName
                                if (folderName) {
                                    results.push({
                                        type: 'DIRECTORY',
                                        name: folderName,
                                        path: (path == '/' ? '/' : (path + '/')) + folderName,
                                        // path: '/' + item.name,
                                    });
                                }
                                // return {
                                // }
                            });
                        }
                        return [2 /*return*/, {
                                list: results,
                                _list: res,
                            }];
                }
            });
        });
    };
    FileService.prototype.webdavList = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var sourceType, _a, path, simplePath, params, _b, headers, url, fullUrl, result, _list, pathname, results;
            return __generator(this, function (_c) {
                switch (_c.label) {
                    case 0:
                        sourceType = body.sourceType, _a = body.path, path = _a === void 0 ? '/' : _a;
                        simplePath = path.replace(/^\//, '');
                        params = {
                            'max-keys': 100,
                            // prefix: '',
                            'prefix': path == '/' ? '' : (path.replace(/^\//, '') + '/'),
                            'delimiter': '/',
                        };
                        console.log('params', params);
                        _b = g_webdav[sourceType], headers = _b.headers, url = _b.url;
                        console.log('headers', headers);
                        fullUrl = url + (path == '/' ? '' : path.replace(/^\//, ''));
                        console.log('fullUrl', fullUrl);
                        return [4 /*yield*/, tsdav_1.default.davRequest({
                                url: fullUrl,
                                init: {
                                    method: 'PROPFIND',
                                    namespace: 'd',
                                    body: {
                                        propfind: {
                                            _attributes: {
                                                'xmlns:d': 'DAV:',
                                            },
                                            prop: {
                                            // 'd:current-user-principal': {} 
                                            },
                                        },
                                    },
                                    headers: headers,
                                    //   headers: {
                                    //     authorization: 'Basic x0C9uFWd9Vz8OwS0DEAtkAlj',
                                    //   },
                                },
                            })];
                    case 1:
                        result = (_c.sent())[0];
                        console.log('result', result);
                        console.log('result.raw', JSON.stringify(result.raw.multistatus, null, 4));
                        _list = result.raw.multistatus.response;
                        pathname = new Url(url).pathname;
                        results = [];
                        // console.log('_list', _list)
                        if (!Array.isArray(_list)) {
                            return [2 /*return*/, {
                                    list: [],
                                }];
                        }
                        _list.forEach(function (item) {
                            var href = decodeURIComponent(item.href);
                            var href2 = decodeURI(item.href);
                            var _path = href;
                            _path = _path.substring(pathname.length);
                            _path = _path.replace(/\/$/, '');
                            _path = _path.substring(simplePath.length);
                            _path = _path.replace(/^\//, '');
                            var _a = item.propstat.prop, getcontenttype = _a.getcontenttype, getlastmodified = _a.getlastmodified, getcontentlength = _a.getcontentlength, resourcetype = _a.resourcetype;
                            // const type = getcontenttype == 'httpd/unix-directory' ? 'DIRECTORY' : 'FILE'
                            var type = (resourcetype && resourcetype.collection) ? 'DIRECTORY' : 'FILE';
                            var updateTime = getlastmodified;
                            var size = getcontentlength;
                            if (_path) {
                                results.push({
                                    type: type,
                                    name: _path,
                                    path: (path == '/' ? '/' : (path + '/')) + _path,
                                    updateTime: updateTime,
                                    size: size,
                                    _debug: {
                                        pathname: pathname,
                                        simplePath: simplePath,
                                        href: href,
                                        href2: href2,
                                        rawHref: item.href,
                                    }
                                });
                            }
                        });
                        return [2 /*return*/, {
                                list: results,
                                _list: _list,
                            }];
                }
            });
        });
    };
    FileService.prototype.zipList = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var zipPath, _a, path, list, results, map;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        zipPath = body.zipPath, _a = body.path, path = _a === void 0 ? '/' : _a;
                        return [4 /*yield*/, getZipList(zipPath)];
                    case 1:
                        list = _b.sent();
                        console.log('list', list);
                        results = [];
                        map = {};
                        list.forEach(function (item) {
                            if (path == '/') {
                                if (item.name.includes('/')) {
                                    var folderName = item.name.split('/')[0];
                                    if (!map[folderName]) {
                                        map[folderName] = 1;
                                        results.push({
                                            type: 'DIRECTORY',
                                            name: folderName,
                                            path: '/' + folderName,
                                        });
                                    }
                                }
                                else {
                                    results.push({
                                        type: 'FILE',
                                        name: item.name,
                                        path: '/' + item.name,
                                    });
                                }
                            }
                            else {
                                if (item.name.startsWith(path.replace(/^\//, ''))) {
                                    var restPath = item.name.substring(path.length);
                                    if (restPath) {
                                        if (restPath.includes('/')) {
                                            var folderName = restPath.split('/')[0];
                                            if (!map[folderName]) {
                                                map[folderName] = 1;
                                                results.push({
                                                    type: 'DIRECTORY',
                                                    name: folderName,
                                                    path: path + '/' + folderName,
                                                });
                                            }
                                        }
                                        else {
                                            results.push({
                                                type: 'FILE',
                                                name: restPath,
                                                path: path + '/' + restPath,
                                            });
                                        }
                                    }
                                }
                            }
                        });
                        return [2 /*return*/, {
                                list: results.sort(function (a, b) {
                                    return a.name.localeCompare(b.name);
                                })
                            }
                            // if (sourceType == 'local') {
                            //     const list = handleFolder(path || USER_HOME)
                            //     return {
                            //         list,
                            //     }
                            // }
                            // else {
                            //     return {
                            //         type: item.type == 'd' ? 'DIRECTORY' : 'FILE',
                            //         name: item.name,
                            //         path: ((_path == '/') ? '/' : (_path + '/')) + item.name, // TODO
                            //         updateTime: new Date(item.modifyTime),
                            //         size: item.size,
                            //         _item: item,
                            //     }
                            // }
                        ];
                }
            });
        });
    };
    FileService.prototype.fileList = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var _a, sourceType, path, _b, r, list, g_sftp, _path_1, _list, list;
            return __generator(this, function (_c) {
                switch (_c.label) {
                    case 0:
                        _a = body.sourceType, sourceType = _a === void 0 ? 'local' : _a, path = body.path, _b = body.r, r = _b === void 0 ? false : _b;
                        if (!sourceType.includes('oss')) return [3 /*break*/, 2];
                        return [4 /*yield*/, this.ossList(body)];
                    case 1: return [2 /*return*/, _c.sent()];
                    case 2:
                        if (!sourceType.includes('webdav')) return [3 /*break*/, 4];
                        return [4 /*yield*/, this.webdavList(body)];
                    case 3: return [2 /*return*/, _c.sent()];
                    case 4:
                        if (!(sourceType == 'local')) return [3 /*break*/, 5];
                        list = handleFolder(path || USER_HOME, r);
                        return [2 /*return*/, {
                                list: list,
                            }];
                    case 5: return [4 /*yield*/, this.getSftpClient(body)];
                    case 6:
                        g_sftp = _c.sent();
                        _path_1 = path || '/root';
                        return [4 /*yield*/, g_sftp.list(_path_1)];
                    case 7:
                        _list = _c.sent();
                        list = _list.map(function (item) {
                            // accessTime: 1640168554000
                            // group: 0
                            // longname: "drwx------    3 root     root         4096 Dec 22  2021 .config"
                            // modifyTime: 1640168554000
                            // name: ".config"
                            // owner: 0
                            // rights: {user: "rwx", group: "", other: ""}
                            // size: 4096
                            // type: "d"
                            return {
                                type: item.type == 'd' ? 'DIRECTORY' : 'FILE',
                                name: item.name,
                                path: ((_path_1 == '/') ? '/' : (_path_1 + '/')) + item.name,
                                updateTime: new Date(item.modifyTime),
                                size: item.size,
                                _item: item,
                            };
                        });
                        return [2 /*return*/, {
                                list: list,
                            }];
                }
            });
        });
    };
    FileService.prototype.webdavRead = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var sourceType, _a, path, _b, headers, url, fullUrl, res;
            return __generator(this, function (_c) {
                switch (_c.label) {
                    case 0:
                        sourceType = body.sourceType, _a = body.path, path = _a === void 0 ? '/' : _a;
                        _b = g_webdav[sourceType], headers = _b.headers, url = _b.url;
                        fullUrl = url + (path == '/' ? '' : path.replace(/^\//, ''));
                        // const [result] = await tsdav.davRequest({
                        console.log('fullUrl', fullUrl);
                        return [4 /*yield*/, axios.get(fullUrl, {
                                headers: headers,
                            })
                            // 内容有可能被 axios 转成数字
                        ];
                    case 1:
                        res = _c.sent();
                        // 内容有可能被 axios 转成数字
                        return [2 /*return*/, {
                                content: '' + res.data,
                            }];
                }
            });
        });
    };
    FileService.prototype.webdavImagePreview = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            function download() {
                return new Promise(function (resolve, reject) {
                    writer.on("finish", resolve);
                    writer.on("error", reject);
                });
            }
            var sourceType, path, tmpPath, writer, _a, headers, url, fullUrl, res;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        sourceType = body.sourceType, path = body.path;
                        tmpPath = nodePath.join(appFolder, 'tmp.file');
                        writer = fs.createWriteStream(tmpPath);
                        _a = g_webdav[sourceType], headers = _a.headers, url = _a.url;
                        fullUrl = url + (path == '/' ? '' : path.replace(/^\//, ''));
                        // const [result] = await tsdav.davRequest({
                        console.log('fullUrl', fullUrl);
                        return [4 /*yield*/, axios.get(fullUrl, {
                                headers: headers,
                                responseType: "stream",
                            })];
                    case 1:
                        res = _b.sent();
                        res.data.pipe(writer);
                        return [4 /*yield*/, download()];
                    case 2:
                        _b.sent();
                        return [2 /*return*/, fs.readFileSync(tmpPath)
                            // return {
                            //     content: res.data,
                            // }
                        ];
                }
            });
        });
    };
    FileService.prototype.read = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var path, _a, sourceType, tmpPath, ossPath, content, content, g_sftp, content;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        path = body.path, _a = body.sourceType, sourceType = _a === void 0 ? 'local' : _a;
                        tmpPath = nodePath.join(appFolder, 'tmp.file');
                        if (!sourceType.includes('webdav')) return [3 /*break*/, 2];
                        return [4 /*yield*/, this.webdavRead(body)];
                    case 1: return [2 /*return*/, _b.sent()];
                    case 2:
                        if (!sourceType.includes('oss')) return [3 /*break*/, 4];
                        ossPath = path.replace(/^\//, '');
                        console.log('ossPath', ossPath);
                        return [4 /*yield*/, g_publicStores[sourceType].get(ossPath, tmpPath)];
                    case 3:
                        _b.sent();
                        content = fs.readFileSync(tmpPath, 'utf-8');
                        return [2 /*return*/, {
                                content: content,
                            }];
                    case 4:
                        if (!(sourceType == 'local')) return [3 /*break*/, 5];
                        content = fs.readFileSync(path, 'utf-8');
                        return [2 /*return*/, {
                                content: content,
                            }];
                    case 5: return [4 /*yield*/, this.getSftpClient(body)];
                    case 6:
                        g_sftp = _b.sent();
                        return [4 /*yield*/, g_sftp.fastGet(path, tmpPath)];
                    case 7:
                        _b.sent();
                        content = fs.readFileSync(tmpPath, 'utf-8');
                        return [2 /*return*/, {
                                content: content,
                            }];
                }
            });
        });
    };
    FileService.prototype.write = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var path, _a, sourceType, _b, content, tmpPath, ossPath, _c, headers, url, fullUrl, response, g_sftp, tmpPath;
            return __generator(this, function (_d) {
                switch (_d.label) {
                    case 0:
                        path = body.path, _a = body.sourceType, sourceType = _a === void 0 ? 'local' : _a, _b = body.content, content = _b === void 0 ? '' : _b;
                        if (!sourceType.includes('oss')) return [3 /*break*/, 2];
                        console.log('path', path);
                        tmpPath = nodePath.join(appFolder, 'tmp.file');
                        ossPath = path.replace(/^\//, '');
                        // + (type == 'FILE' ? '' : '/')
                        // console.log('ossPath', ossPath)
                        // // console.log('localPath', localPath)
                        fs.writeFileSync(tmpPath, content, 'utf-8');
                        return [4 /*yield*/, g_publicStores[sourceType].put(ossPath, tmpPath)];
                    case 1:
                        _d.sent();
                        return [2 /*return*/, {}];
                    case 2:
                        if (!sourceType.includes('webdav')) return [3 /*break*/, 4];
                        _c = g_webdav[sourceType], headers = _c.headers, url = _c.url;
                        fullUrl = url + (path == '/' ? '' : path.replace(/^\//, ''));
                        // + '/' + name
                        console.log('fullUrl', fullUrl);
                        return [4 /*yield*/, tsdav_1.default.createObject({
                                url: fullUrl,
                                data: content,
                                headers: __assign(__assign({}, headers), { 'content-type': 'text/plain; charset=utf-8' }),
                            })
                            // if (type == 'FILE') {
                            // }
                        ];
                    case 3:
                        response = _d.sent();
                        // if (type == 'FILE') {
                        // }
                        return [2 /*return*/, {}];
                    case 4:
                        if (!(sourceType == 'local')) return [3 /*break*/, 5];
                        fs.writeFileSync(path, content, 'utf-8');
                        return [2 /*return*/, {}];
                    case 5: return [4 /*yield*/, this.getSftpClient(body)];
                    case 6:
                        g_sftp = _d.sent();
                        tmpPath = nodePath.join(appFolder, 'tmp.file');
                        fs.writeFileSync(tmpPath, content, 'utf-8');
                        // const remotePath = nodePath.join(path, name) // TODO
                        return [4 /*yield*/, g_sftp.put(tmpPath, path)];
                    case 7:
                        // const remotePath = nodePath.join(path, name) // TODO
                        _d.sent();
                        return [2 /*return*/, {}];
                }
            });
        });
    };
    FileService.prototype.create = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var path, name, type, sourceType, localPath, sourceType_1, path_1, _a, headers, url, fullUrl, response, result, tmpPath, ossPath, g_sftp, tmpPath;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        path = body.path, name = body.name, type = body.type, sourceType = body.sourceType;
                        localPath = nodePath.join(path, name) // TODO
                        ;
                        if (!sourceType.includes('webdav')) return [3 /*break*/, 5];
                        sourceType_1 = body.sourceType, path_1 = body.path;
                        _a = g_webdav[sourceType_1], headers = _a.headers, url = _a.url;
                        fullUrl = url + (path_1 == '/' ? '' : path_1.replace(/^\//, ''))
                            + '/' + name;
                        console.log('fullUrl', fullUrl);
                        if (!(type == 'FILE')) return [3 /*break*/, 2];
                        return [4 /*yield*/, tsdav_1.default.createObject({
                                url: fullUrl,
                                data: '',
                                headers: __assign(__assign({}, headers), { 'content-type': 'text/plain; charset=utf-8' }),
                            })];
                    case 1:
                        response = _b.sent();
                        return [3 /*break*/, 4];
                    case 2: return [4 /*yield*/, tsdav_1.default.davRequest({
                            url: fullUrl,
                            init: {
                                method: 'MKCOL',
                                //   namespace: 'd',
                                body: '',
                                headers: headers,
                                //   headers: {
                                //     authorization: 'Basic x0C9uFWd9Vz8OwS0DEAtkAlj',
                                //   },
                            },
                        })];
                    case 3:
                        result = (_b.sent())[0];
                        console.log('result', result);
                        _b.label = 4;
                    case 4: return [2 /*return*/, {}];
                    case 5:
                        if (!sourceType.includes('oss')) return [3 /*break*/, 7];
                        tmpPath = nodePath.join(appFolder, 'tmp.file');
                        console.log('tmpPath', tmpPath);
                        ossPath = localPath.replace(/^\//, '')
                            + (type == 'FILE' ? '' : '/');
                        console.log('ossPath', ossPath);
                        // console.log('localPath', localPath)
                        fs.writeFileSync(tmpPath, '', 'utf-8');
                        return [4 /*yield*/, g_publicStores[sourceType].put(ossPath, tmpPath)];
                    case 6:
                        _b.sent();
                        return [2 /*return*/, {}
                            // const content = fs.readFileSync(tmpPath, 'utf-8')
                            // return {
                            //     content,
                            // }
                        ];
                    case 7:
                        if (!(sourceType == 'local')) return [3 /*break*/, 8];
                        if (type == 'FILE') {
                            fs.writeFileSync(localPath, '', 'utf-8');
                        }
                        else {
                            fs.mkdirSync(localPath);
                        }
                        return [2 /*return*/, {}];
                    case 8: return [4 /*yield*/, this.getSftpClient(body)];
                    case 9:
                        g_sftp = _b.sent();
                        if (!(type == 'FILE')) return [3 /*break*/, 11];
                        tmpPath = nodePath.join(appFolder, 'tmp.file');
                        fs.writeFileSync(tmpPath, '', 'utf-8');
                        return [4 /*yield*/, g_sftp.put(tmpPath, localPath)
                            // fs.writeFileSync(localPath, '', 'utf-8')
                        ];
                    case 10:
                        _b.sent();
                        return [3 /*break*/, 13];
                    case 11: return [4 /*yield*/, g_sftp.mkdir(localPath)];
                    case 12:
                        _b.sent();
                        _b.label = 13;
                    case 13: return [2 /*return*/, {}];
                }
            });
        });
    };
    FileService.prototype.delete = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var path, type, sourceType, sourceType_2, path_2, _a, headers, url, fullUrl, result, ossPath, g_sftp;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        path = body.path, type = body.type, sourceType = body.sourceType;
                        if (!sourceType.includes('webdav')) return [3 /*break*/, 2];
                        sourceType_2 = body.sourceType, path_2 = body.path;
                        console.log('path', path_2);
                        _a = g_webdav[sourceType_2], headers = _a.headers, url = _a.url;
                        console.log('url', url);
                        fullUrl = url + (path_2 == '/' ? '' : path_2.replace(/^\//, ''));
                        // + '/' + name
                        console.log('fullUrl', fullUrl);
                        return [4 /*yield*/, tsdav_1.default.davRequest({
                                url: fullUrl,
                                init: {
                                    method: 'DELETE',
                                    //   namespace: 'd',
                                    body: '',
                                    headers: headers,
                                    //   headers: {
                                    //     authorization: 'Basic x0C9uFWd9Vz8OwS0DEAtkAlj',
                                    //   },
                                },
                            })];
                    case 1:
                        result = (_b.sent())[0];
                        console.log('result', result);
                        return [2 /*return*/, {}];
                    case 2:
                        if (!sourceType.includes('oss')) return [3 /*break*/, 4];
                        ossPath = path.replace(/^\//, '')
                            + (type == 'FILE' ? '' : '/');
                        console.log('ossPath', ossPath);
                        // console.log('localPath', localPath)
                        // fs.writeFileSync(tmpPath, '', 'utf-8')
                        return [4 /*yield*/, g_publicStores[sourceType].delete(ossPath)];
                    case 3:
                        // console.log('localPath', localPath)
                        // fs.writeFileSync(tmpPath, '', 'utf-8')
                        _b.sent();
                        return [2 /*return*/, {}
                            // const content = fs.readFileSync(tmpPath, 'utf-8')
                            // return {
                            //     content,
                            // }
                        ];
                    case 4:
                        if (!(sourceType == 'local')) return [3 /*break*/, 5];
                        if (type == 'FILE') {
                            // if (os.type() == 'Windows_NT') {
                            //     //windows
                            // } else if (os.type() == 'Darwin') {
                            //     //mac
                            // } else if (os.type() == 'Linux') {
                            // if (os.type() == 'Darwin') {
                            // }
                            // await trash([path])
                            fs.unlinkSync(path);
                        }
                        else {
                            rmDir(path);
                            // await deleteAsync(path)
                            // fs.rmdirSync(path)
                        }
                        return [2 /*return*/, {}];
                    case 5: return [4 /*yield*/, this.getSftpClient(body)];
                    case 6:
                        g_sftp = _b.sent();
                        if (!(type == 'FILE')) return [3 /*break*/, 8];
                        return [4 /*yield*/, g_sftp.delete(path)];
                    case 7:
                        _b.sent();
                        return [3 /*break*/, 10];
                    case 8: return [4 /*yield*/, g_sftp.rmdir(path, true)];
                    case 9:
                        _b.sent();
                        _b.label = 10;
                    case 10: return [2 /*return*/];
                }
            });
        });
    };
    FileService.prototype.rename = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var fromPath, toPath, type, sourceType, _a, headers, url, fromPathFullUrl, toPathFullUrl, result, ossFromPath, ossToPath, g_sftp;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        fromPath = body.fromPath, toPath = body.toPath, type = body.type, sourceType = body.sourceType;
                        if (!sourceType.includes('webdav')) return [3 /*break*/, 2];
                        _a = g_webdav[sourceType], headers = _a.headers, url = _a.url;
                        fromPathFullUrl = url + (fromPath == '/' ? '' : fromPath.replace(/^\//, ''));
                        toPathFullUrl = url + (toPath == '/' ? '' : toPath.replace(/^\//, ''));
                        // console.log('fullUrl', fullUrl)
                        // console.log('name', path, name)
                        console.log('fromPathFullUrl', fromPathFullUrl);
                        console.log('toPathFullUrl', toPathFullUrl);
                        return [4 /*yield*/, tsdav_1.default.davRequest({
                                url: fromPathFullUrl,
                                init: {
                                    method: 'MOVE',
                                    //   namespace: 'd',
                                    body: '',
                                    headers: __assign(__assign({}, headers), { 
                                        // 'Destination': toPathFullUrl,
                                        'Destination': encodeURI(toPathFullUrl) }),
                                    //   headers: {
                                    //     authorization: 'Basic x0C9uFWd9Vz8OwS0DEAtkAlj',
                                    //   },
                                },
                            })];
                    case 1:
                        result = (_b.sent())[0];
                        return [2 /*return*/, {}];
                    case 2:
                        if (!sourceType.includes('oss')) return [3 /*break*/, 5];
                        ossFromPath = fromPath.replace(/^\//, '');
                        ossToPath = toPath.replace(/^\//, '');
                        console.log('ossFromPath', ossFromPath, ossToPath);
                        // const tmpPath = nodePath.join(appFolder, 'tmp.file')
                        // console.log('tmpPath', tmpPath)
                        // const ossPath = localPath.replace(/^\//, '')
                        //     + (type == 'FILE' ? '' : '/')
                        // console.log('ossPath', ossPath)
                        // console.log('localPath', localPath)
                        // fs.writeFileSync(tmpPath, '', 'utf-8')
                        // await g_publicStores[sourceType].copy(ossFromPath, ossToPath)
                        // await g_publicStores[sourceType].copy('cjh-test/ff2', 'cjh-test/ff3')
                        return [4 /*yield*/, g_publicStores[sourceType].copy(ossToPath, ossFromPath)];
                    case 3:
                        // const tmpPath = nodePath.join(appFolder, 'tmp.file')
                        // console.log('tmpPath', tmpPath)
                        // const ossPath = localPath.replace(/^\//, '')
                        //     + (type == 'FILE' ? '' : '/')
                        // console.log('ossPath', ossPath)
                        // console.log('localPath', localPath)
                        // fs.writeFileSync(tmpPath, '', 'utf-8')
                        // await g_publicStores[sourceType].copy(ossFromPath, ossToPath)
                        // await g_publicStores[sourceType].copy('cjh-test/ff2', 'cjh-test/ff3')
                        _b.sent();
                        return [4 /*yield*/, g_publicStores[sourceType].delete(ossFromPath)];
                    case 4:
                        _b.sent();
                        return [2 /*return*/, {}
                            // const content = fs.readFileSync(tmpPath, 'utf-8')
                            // return {
                            //     content,
                            // }
                        ];
                    case 5:
                        if (!(sourceType == 'local')) return [3 /*break*/, 6];
                        fs.renameSync(fromPath, toPath);
                        return [2 /*return*/, {}];
                    case 6: return [4 /*yield*/, this.getSftpClient(body)];
                    case 7:
                        g_sftp = _b.sent();
                        return [4 /*yield*/, g_sftp.rename(fromPath, toPath)
                            // if (type == 'FILE') {
                            //     await g_sftp.delete(path)
                            // }
                            // else {
                            //     await g_sftp.rmdir(path, true)
                            // }
                            // return {}
                        ];
                    case 8:
                        _b.sent();
                        _b.label = 9;
                    case 9: return [2 /*return*/, {}];
                }
            });
        });
    };
    FileService.prototype.imagePreview = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var sourceType, path, tmpPath, ossPath, g_sftp, tmpPath;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        sourceType = body.sourceType, path = body.path;
                        if (!sourceType.includes('oss')) return [3 /*break*/, 2];
                        tmpPath = nodePath.join(appFolder, 'tmp.file');
                        console.log('tmpPath', tmpPath);
                        ossPath = path.replace(/^\//, '');
                        console.log('ossPath', ossPath);
                        return [4 /*yield*/, g_publicStores[sourceType].get(ossPath, tmpPath)];
                    case 1:
                        _a.sent();
                        return [2 /*return*/, fs.readFileSync(tmpPath)
                            // const content = fs.readFileSync(tmpPath, 'utf-8')
                            // return {
                            //     content,
                            // }
                        ];
                    case 2:
                        if (!sourceType.includes('webdav')) return [3 /*break*/, 4];
                        return [4 /*yield*/, this.webdavImagePreview(body)];
                    case 3: return [2 /*return*/, _a.sent()];
                    case 4:
                        if (!(sourceType == 'local')) return [3 /*break*/, 5];
                        return [2 /*return*/, fs.readFileSync(path)];
                    case 5: return [4 /*yield*/, this.getSftpClient(body)];
                    case 6:
                        g_sftp = _a.sent();
                        tmpPath = nodePath.join(appFolder, 'tmp.file');
                        return [4 /*yield*/, g_sftp.fastGet(path, tmpPath)];
                    case 7:
                        _a.sent();
                        return [2 /*return*/, fs.readFileSync(tmpPath)];
                }
            });
        });
    };
    FileService.prototype.download = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var sourceType, path, tmpPath, ossPath, g_sftp, tmpPath;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        sourceType = body.sourceType, path = body.path;
                        if (!(sourceType == 'local')) return [3 /*break*/, 1];
                        return [3 /*break*/, 6];
                    case 1:
                        if (!sourceType.includes('oss')) return [3 /*break*/, 3];
                        tmpPath = nodePath.join(appFolder, 'tmp.file');
                        ossPath = path.replace(/^\//, '');
                        return [4 /*yield*/, g_publicStores[sourceType].get(ossPath, tmpPath)];
                    case 2:
                        _a.sent();
                        return [2 /*return*/, fs.readFileSync(tmpPath)];
                    case 3: return [4 /*yield*/, this.getSftpClient(body)];
                    case 4:
                        g_sftp = _a.sent();
                        tmpPath = nodePath.join(appFolder, 'tmp.file');
                        return [4 /*yield*/, g_sftp.fastGet(path, tmpPath)];
                    case 5:
                        _a.sent();
                        return [2 /*return*/, fs.readFileSync(tmpPath)];
                    case 6: return [2 /*return*/];
                }
            });
        });
    };
    FileService.prototype.openInFinder = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var sourceType, path, stat;
            return __generator(this, function (_a) {
                sourceType = body.sourceType, path = body.path;
                stat = fs.statSync(path);
                if (stat.isFile) {
                    (0, child_process_1.exec)("open ".concat(path, " -R"));
                }
                else {
                    (0, child_process_1.exec)("open ".concat(path));
                }
                return [2 /*return*/, {}];
            });
        });
    };
    FileService.prototype.aliyun = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var aliyunPath, ecs, rds, cert, domain, billing, tencentServer, tencentMysql, tencentLighthouse;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        aliyunPath = path.resolve(yunserFolder, 'aliyun-cli');
                        if (!fs.existsSync(aliyunPath)) {
                            return [2 /*return*/, {
                                    installed: false
                                }];
                        }
                        return [4 /*yield*/, loadJson(nodePath.resolve(aliyunPath, 'data', 'aliyun-ecs.json'), [])];
                    case 1:
                        ecs = _a.sent();
                        return [4 /*yield*/, loadJson(nodePath.resolve(aliyunPath, 'data', 'aliyun-rds.json'), [])];
                    case 2:
                        rds = _a.sent();
                        return [4 /*yield*/, loadJson(nodePath.resolve(aliyunPath, 'data', 'aliyun-cert.json'), [])];
                    case 3:
                        cert = _a.sent();
                        return [4 /*yield*/, loadJson(nodePath.resolve(aliyunPath, 'data', 'aliyun-domain.json'), [])];
                    case 4:
                        domain = _a.sent();
                        return [4 /*yield*/, loadJson(nodePath.resolve(aliyunPath, 'data', 'aliyun-billing.json'), [])];
                    case 5:
                        billing = _a.sent();
                        return [4 /*yield*/, loadJson(nodePath.resolve(aliyunPath, 'data', 'tencent-server.json'), [])];
                    case 6:
                        tencentServer = _a.sent();
                        return [4 /*yield*/, loadJson(nodePath.resolve(aliyunPath, 'data', 'tencent-mysql.json'), [])];
                    case 7:
                        tencentMysql = _a.sent();
                        return [4 /*yield*/, loadJson(nodePath.resolve(aliyunPath, 'data', 'tencent-lighthouse.json'), [])];
                    case 8:
                        tencentLighthouse = _a.sent();
                        return [2 /*return*/, {
                                installed: true,
                                ecs: ecs,
                                rds: rds,
                                cert: cert,
                                domain: domain,
                                billing: billing,
                                tencentServer: tencentServer,
                                tencentMysql: tencentMysql,
                                tencentLighthouse: tencentLighthouse,
                            }];
                }
            });
        });
    };
    FileService.prototype.projectList = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var project;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, loadJson(projectDbFilePath, {
                            projects: [],
                        })];
                    case 1:
                        project = _a.sent();
                        return [2 /*return*/, {
                                list: project.projects,
                            }];
                }
            });
        });
    };
    FileService.prototype.projectCreate = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var project;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, loadJson(projectDbFilePath, {
                            projects: [],
                        })];
                    case 1:
                        project = _a.sent();
                        project.projects.unshift(__assign(__assign({}, body), { id: (0, uid_1.uid)(32) }));
                        fs.writeFileSync(projectDbFilePath, JSON.stringify(project, null, 4), 'utf-8');
                        return [2 /*return*/, {}];
                }
            });
        });
    };
    FileService.prototype.projectDelete = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var id, project;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        id = body.id;
                        return [4 /*yield*/, loadJson(projectDbFilePath, {
                                projects: [],
                            })];
                    case 1:
                        project = _a.sent();
                        project.projects = project.projects.filter(function (item) { return item.id != id; });
                        fs.writeFileSync(projectDbFilePath, JSON.stringify(project, null, 4), 'utf-8');
                        return [2 /*return*/, {}];
                }
            });
        });
    };
    FileService.prototype.projectUpdate = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var id, data, project, idx;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        id = body.id, data = body.data;
                        return [4 /*yield*/, loadJson(projectDbFilePath, {
                                projects: [],
                            })
                            // const content = fs.readFileSync(swaggerDbFilePath, 'utf-8')
                            // const list = JSON.parse(content)
                        ];
                    case 1:
                        project = _a.sent();
                        idx = project.projects.findIndex(function (_item) { return _item.id == id; });
                        project.projects[idx] = __assign(__assign({}, project.projects[idx]), data);
                        fs.writeFileSync(projectDbFilePath, JSON.stringify(project, null, 4), 'utf-8');
                        return [2 /*return*/, {}];
                }
            });
        });
    };
    FileService.prototype.swaggerList = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var list;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, loadJson(swaggerDbFilePath, [])];
                    case 1:
                        list = _a.sent();
                        return [2 /*return*/, {
                                list: list,
                            }];
                }
            });
        });
    };
    FileService.prototype.swaggerDetail = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var id, list;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        id = body.id;
                        return [4 /*yield*/, loadJson(swaggerDbFilePath, [])];
                    case 1:
                        list = _a.sent();
                        return [2 /*return*/, list.find(function (item) { return item.id == id; })];
                }
            });
        });
    };
    FileService.prototype.serviceList = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var path, list;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        path = nodePath.resolve(appFolder, 'service.json');
                        return [4 /*yield*/, loadJson(path, [])];
                    case 1:
                        list = _a.sent();
                        return [2 /*return*/, {
                                list: list,
                            }];
                }
            });
        });
    };
    FileService.prototype.swaggerEdit = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var id, data, content, list, idx;
            return __generator(this, function (_a) {
                id = body.id, data = body.data;
                content = fs.readFileSync(swaggerDbFilePath, 'utf-8');
                list = JSON.parse(content);
                idx = list.findIndex(function (_item) { return _item.id == id; });
                list[idx] = __assign(__assign({}, list[idx]), data);
                fs.writeFileSync(swaggerDbFilePath, JSON.stringify(list, null, 4), 'utf-8');
                return [2 /*return*/, {}];
            });
        });
    };
    FileService.prototype.swaggerCreate = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var content, list;
            return __generator(this, function (_a) {
                content = fs.readFileSync(swaggerDbFilePath, 'utf-8');
                list = JSON.parse(content);
                list.unshift(__assign(__assign({}, body), { id: (0, uid_1.uid)(32) }));
                fs.writeFileSync(swaggerDbFilePath, JSON.stringify(list, null, 4), 'utf-8');
                return [2 /*return*/, {}];
            });
        });
    };
    FileService.prototype.swaggerDelete = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var id, content, list, newList;
            return __generator(this, function (_a) {
                id = body.id;
                content = fs.readFileSync(swaggerDbFilePath, 'utf-8');
                list = JSON.parse(content);
                newList = list.filter(function (item) { return item.id != id; });
                fs.writeFileSync(swaggerDbFilePath, JSON.stringify(newList, null, 4), 'utf-8');
                return [2 /*return*/, {}];
            });
        });
    };
    FileService.prototype.copy = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var sourceType, fromPath, toPath, copyType, _a, headers, url, fromPathFullUrl, toPathFullUrl, result, ossFromPath, ossToPath, g_sftp;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        sourceType = body.sourceType, fromPath = body.fromPath, toPath = body.toPath, copyType = body.copyType;
                        if (!(sourceType == 'local')) return [3 /*break*/, 2];
                        return [4 /*yield*/, _copy(fromPath, toPath)];
                    case 1:
                        _b.sent();
                        if (copyType == 'cut') {
                            fs.unlinkSync(fromPath);
                        }
                        return [3 /*break*/, 12];
                    case 2:
                        if (!sourceType.includes('webdav')) return [3 /*break*/, 4];
                        _a = g_webdav[sourceType], headers = _a.headers, url = _a.url;
                        fromPathFullUrl = url + (fromPath == '/' ? '' : fromPath.replace(/^\//, ''));
                        toPathFullUrl = url + (toPath == '/' ? '' : toPath.replace(/^\//, ''));
                        return [4 /*yield*/, tsdav_1.default.davRequest({
                                url: fromPathFullUrl,
                                init: {
                                    method: copyType == 'cut' ? 'MOVE' : 'COPY',
                                    //   namespace: 'd',
                                    body: '',
                                    headers: __assign(__assign({}, headers), { 
                                        // 'Destination': toPathFullUrl,
                                        'Destination': encodeURI(toPathFullUrl) }),
                                    //   headers: {
                                    //     authorization: 'Basic x0C9uFWd9Vz8OwS0DEAtkAlj',
                                    //   },
                                },
                            })];
                    case 3:
                        result = (_b.sent())[0];
                        return [2 /*return*/, {}];
                    case 4:
                        if (!sourceType.includes('oss')) return [3 /*break*/, 8];
                        ossFromPath = fromPath.replace(/^\//, '');
                        ossToPath = toPath.replace(/^\//, '');
                        // + (type == 'FILE' ? '' : '/')
                        return [4 /*yield*/, g_publicStores[sourceType].copy(ossToPath, ossFromPath)];
                    case 5:
                        // + (type == 'FILE' ? '' : '/')
                        _b.sent();
                        if (!(copyType == 'cut')) return [3 /*break*/, 7];
                        return [4 /*yield*/, g_publicStores[sourceType].delete(ossFromPath)];
                    case 6:
                        _b.sent();
                        _b.label = 7;
                    case 7: return [2 /*return*/, {}];
                    case 8: return [4 /*yield*/, this.getSftpClient(body)];
                    case 9:
                        g_sftp = _b.sent();
                        return [4 /*yield*/, g_sftp.rcopy(fromPath, toPath)];
                    case 10:
                        _b.sent();
                        if (!(copyType == 'cut')) return [3 /*break*/, 12];
                        return [4 /*yield*/, g_sftp.delete(fromPath)];
                    case 11:
                        _b.sent();
                        _b.label = 12;
                    case 12: return [2 /*return*/, {}];
                }
            });
        });
    };
    FileService.prototype.upload = function (body, tmpPath) {
        return __awaiter(this, void 0, void 0, function () {
            var path, sourceType, _a, headers, url, fullUrl, reader, response, ossPath, g_sftp, reader, newTmpPath, upStream;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        path = body.path, sourceType = body.sourceType;
                        if (!(sourceType == 'local')) return [3 /*break*/, 1];
                        fs.copyFileSync(tmpPath, path);
                        return [3 /*break*/, 8];
                    case 1:
                        if (!sourceType.includes('webdav')) return [3 /*break*/, 3];
                        _a = g_webdav[sourceType], headers = _a.headers, url = _a.url;
                        fullUrl = url + (path == '/' ? '' : path.replace(/^\//, ''));
                        reader = fs.createReadStream(tmpPath);
                        return [4 /*yield*/, tsdav_1.default.createObject({
                                url: fullUrl,
                                data: reader,
                                headers: __assign(__assign({}, headers), { 'content-type': 'text/plain; charset=utf-8' }),
                            })];
                    case 2:
                        response = _b.sent();
                        return [2 /*return*/, {}];
                    case 3:
                        if (!sourceType.includes('oss')) return [3 /*break*/, 5];
                        ossPath = path.replace(/^\//, '');
                        // + (type == 'FILE' ? '' : '/')
                        // console.log('localPath', localPath)
                        // fs.writeFileSync(tmpPath, '', 'utf-8')
                        return [4 /*yield*/, g_publicStores[sourceType].put(ossPath, tmpPath)];
                    case 4:
                        // + (type == 'FILE' ? '' : '/')
                        // console.log('localPath', localPath)
                        // fs.writeFileSync(tmpPath, '', 'utf-8')
                        _b.sent();
                        return [2 /*return*/, {}
                            // const content = fs.readFileSync(tmpPath, 'utf-8')
                            // return {
                            //     content,
                            // }
                        ];
                    case 5: return [4 /*yield*/, this.getSftpClient(body)
                        // let file = ctx.request.file; // 获取上传文件
                        // // 创建可读流
                        // const reader = fs.createReadStream(ctx.request.files['image']['path']);
                        // let filePath = `/shareSource/img/my_blog_img` + `/${ctx.request.files['image']['name']}`;
                        // let remotefilePath = `http://www.xxxx.com:8887/img/my_blog_img` + `/${ctx.request.files['image']['name']}`;
                        // // 创建可写流
                        // const upStream = fs.createWriteStream(filePath);
                        // // 可读流通过管道写入可写流
                        // reader.pipe(upStream);
                        // return ctx.body = {
                        //     url: remotefilePath,
                        //     message: "文件上传成功",
                        //     cc: 0
                        // }   
                        // 创建可读流
                    ];
                    case 6:
                        g_sftp = _b.sent();
                        reader = fs.createReadStream(tmpPath);
                        newTmpPath = nodePath.join(appFolder, 'tmp.file');
                        upStream = fs.createWriteStream(newTmpPath);
                        // 可读流通过管道写入可写流
                        reader.pipe(upStream);
                        // ctx.body = 'ok';
                        console.log('newTmpPath', newTmpPath);
                        return [4 /*yield*/, g_sftp.put(tmpPath, path)
                            // ctx.response.body = 'haha'
                            // console.log(text)
                        ];
                    case 7:
                        _b.sent();
                        // ctx.response.body = 'haha'
                        // console.log(text)
                        return [2 /*return*/, {}];
                    case 8: return [2 /*return*/];
                }
            });
        });
    };
    FileService.prototype.collectionList = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var content;
            return __generator(this, function (_a) {
                content = fs.readFileSync(collectionDbFilePath, 'utf-8');
                return [2 /*return*/, {
                        list: JSON.parse(content)
                    }];
            });
        });
    };
    FileService.prototype.collectionCreate = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            function lastSplit(text, sep) {
                var idx = text.lastIndexOf(sep);
                if (idx == -1) {
                    return [text];
                }
                return [
                    text.substring(0, idx),
                    text.substring(idx + 1),
                ];
            }
            var path, content, list;
            return __generator(this, function (_a) {
                path = body.path;
                content = fs.readFileSync(collectionDbFilePath, 'utf-8');
                list = JSON.parse(content);
                list.unshift({
                    id: (0, uid_1.uid)(32),
                    name: lastSplit(path, '/')[1],
                    path: path,
                });
                fs.writeFileSync(collectionDbFilePath, JSON.stringify(list, null, 4), 'utf8');
                return [2 /*return*/, {}
                    // return {
                    //     list: 
                    // }
                ];
            });
        });
    };
    return FileService;
}());
exports.FileService = FileService;
//# sourceMappingURL=file.service.js.map