"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.SshService = exports.closeWebSocketByTcpConnectionId = exports.closeWebSocketBySftpConnectionId = exports.closeWebSocketByDbConnectionId = exports.closeWebSocketByConnectionId = exports.sendWebSocketMsg = exports.sendTcpMsg = exports.sendMqttMsg = exports.sendRedisMsg = void 0;
// import { simpleGit, ResetMode, SimpleGit } from 'simple-git'
var uid_1 = require("uid");
var fs = require("fs");
// import * as mkdirp from 'mkdirp'
var os = require("os");
var path = require("path");
// import moment = require("moment");
var ws_1 = require("ws");
var ssh2_1 = require("ssh2");
var utf8 = require("utf8");
// import * as pty from 'node-pty'
var moment = require("moment");
var socket_service_1 = require("./socket.service");
function getConnectParams(body) {
    var connectParams = {
        host: body.host,
        port: body.port,
        username: body.username,
        // password: body.password,
        readyTimeout: 4 * 1000,
        /** How often (in milliseconds) to send SSH-level keepalive packets to the server. Set to 0 to disable. */
        keepaliveInterval: 10 * 1000,
        /** How many consecutive, unanswered SSH-level keepalive packets that can be sent to the server before disconnection. */
        // keepaliveCountMax?: number;
        /** * How long (in milliseconds) to wait for the SSH handshake to complete. */
        // readyTimeout?: number;
        /** Performs a strict server vendor check before sending vendor-specific requests. */
        /** The underlying socket timeout in ms. Default: none) */
        timeout: 2 * 1000,
    };
    if (body.privateKey) {
        connectParams.privateKey = body.privateKey;
    }
    else if (body.password) {
        connectParams.password = body.password;
    }
    else {
        throw new Error('privateKey or password required');
    }
    return connectParams;
}
function sleep(ms) {
    return new Promise(function (resolve) {
        setTimeout(function () {
            resolve();
        }, ms);
    });
}
function parseStat(stat) {
    var rows = stat.split('\n');
    var cupStat = rows[0];
    var _a = cupStat.split(/\s+/), cpu = _a[0], _user = _a[1], _nice = _a[2], _system = _a[3], _idle = _a[4];
    // CPU利用率   =   100   *（user   +   nice   +   system）/（user   +   nice   +   system   +   idle）
    // console.log('ccpp', _user, _nice, _system, _idle)
    var _b = [_user, _nice, _system, _idle].map(function (item) {
        return parseInt(item.trim());
    }), user = _b[0], nice = _b[1], system = _b[2], idle = _b[3];
    // console.log('user, nice, system, idle', user, nice, system, idle)
    var cpuRate = (user + nice + system) / (user + nice + system + idle);
    return {
        // cpuUsage: Math.floor(100 * cpuRate),
        idle: idle,
        total: user + nice + system + idle,
    };
}
function createSshConnection(config) {
    return new Promise(function (resolve, reject) {
        var sshClient = new ssh2_1.Client();
        sshClient
            .on("ready", function () {
            console.log('ssh/ready1');
            // console.log('ssh/ready')
            // ws.send("\r\n*** SSH CONNECTION ESTABLISHED ***\r\n");
            resolve(sshClient);
        })
            .on("close", function () {
            console.log('ssh/close1');
            // reject() // TODO
        })
            .on("error", function (err) {
            console.log('ssh/error1');
            console.log("\r\n*** SSH CONNECTION ERROR: " + err.message + " ***\r\n");
            reject();
        });
        sshClient.connect(getConnectParams(config));
    });
}
function sshExec(sshClient, cmd) {
    return new Promise(function (resolve, reject) {
        var _data = '';
        sshClient.exec(cmd, function (err, stream) {
            if (err) {
                reject(err);
                return;
            }
            stream
                .on('close', function (code, signal) {
                resolve(_data);
            })
                .on('data', function (data) {
                _data += data.toString();
            })
                .stderr.on('data', function (data) {
                console.log('STDERR: ' + data);
            });
        });
    });
}
function sshExec2(sshClient, cmd) {
    return new Promise(function (resolve, reject) {
        var _data = '';
        sshClient.exec(cmd, function (err, stream) {
            if (err) {
                // reject(err)
                reject({
                    stderr: err.toString(),
                    stdout: null,
                });
                return;
            }
            stream
                .on('close', function (code, signal) {
                // resolve(_data)
                resolve({
                    stderr: null,
                    stdout: _data,
                });
            })
                .on('data', function (data) {
                _data += data.toString();
            })
                .stderr.on('data', function (data) {
                console.log('STDERR: ' + data);
            });
        });
    });
}
var shell = os.platform() === 'win32' ? 'powershell.exe' : '/bin/zsh';
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 sshConnectionFilePath = path.resolve(appFolder, 'ssh.connection.json');
if (!fs.existsSync(sshConnectionFilePath)) {
    // console.log('创建目录')
    // fs.mkdirSync(yunserFolder)
    fs.writeFileSync(sshConnectionFilePath, '[]', 'utf8');
}
var commandDbFilePath = path.resolve(appFolder, 'ssh.command.json');
if (!fs.existsSync(commandDbFilePath)) {
    // console.log('创建目录')
    // fs.mkdirSync(yunserFolder)
    fs.writeFileSync(commandDbFilePath, '[]', 'utf8');
}
// let gitSettingFilePath = path.resolve(appFolder, 'git.settings.json')
// if (!fs.existsSync(gitSettingFilePath)) {
//     // console.log('创建目录')
//     // fs.mkdirSync(yunserFolder)
//     fs.writeFileSync(gitSettingFilePath, '{}', 'utf8')
// }
var folderPath = '/Users/yunser/app/dms-new';
var wss = new ws_1.WebSocket.Server({
    port: 10087
});
var redisSubscribeSockets = [];
var mqttSubscribeSockets = [];
var redisSockets = [];
var dbSockets = [];
var sftpSockets = [];
var tcpSockets = [];
var websockServerSockets = [];
var webSocketId2SocketMap = {};
function sendRedisMsg(_a) {
    var channel = _a.channel, message = _a.message;
    console.log('redisSubscribeSockets.length', redisSubscribeSockets.length);
    var time = moment().format('YYYY-MM-DD HH:mm:ss');
    for (var _i = 0, redisSubscribeSockets_1 = redisSubscribeSockets; _i < redisSubscribeSockets_1.length; _i++) {
        var ws = redisSubscribeSockets_1[_i];
        ws.send(JSON.stringify({
            id: (0, uid_1.uid)(8),
            channel: channel,
            message: message,
            time: time,
        }));
    }
}
exports.sendRedisMsg = sendRedisMsg;
function sendMqttMsg(_a) {
    var topic = _a.topic, message = _a.message;
    console.log('sendMqttMsg/mqttSubscribeSockets.length', mqttSubscribeSockets.length);
    var time = moment().format('YYYY-MM-DD HH:mm:ss');
    for (var _i = 0, mqttSubscribeSockets_1 = mqttSubscribeSockets; _i < mqttSubscribeSockets_1.length; _i++) {
        var ws = mqttSubscribeSockets_1[_i];
        ws.send(JSON.stringify({
            id: (0, uid_1.uid)(8),
            topic: topic,
            message: message,
            time: time,
        }));
    }
}
exports.sendMqttMsg = sendMqttMsg;
function sendTcpMsg(_a) {
    var webSocketId = _a.webSocketId, message = _a.message;
    // console.log('tcpSockets', tcpSockets)
    var ws = webSocketId2SocketMap[webSocketId];
    if (!ws) {
        console.log('sendTcpMsg/notFound');
        return;
    }
    ws.send(JSON.stringify(message));
    // const fItem = tcpSockets.find(item => item.connectionId == connectionId)
    // // console.log('fItem', fItem)
    // if (fItem) {
    //     fItem.socket.send(JSON.stringify(message))
    // }
    // else {
    //     console.log('sendTcpMsg/notFound', )
    // }
}
exports.sendTcpMsg = sendTcpMsg;
function sendWebSocketMsg(_a) {
    var connectionId = _a.connectionId, message = _a.message;
    var time = moment().format('YYYY-MM-DD HH:mm:ss');
    // console.log('websockServerSockets', websockServerSockets)
    console.log('connectionId', connectionId);
    var fItem = websockServerSockets.find(function (item) { return item.connectionId == connectionId; });
    // console.log('fItem', fItem)
    if (fItem) {
        fItem.socket.send(JSON.stringify(message));
    }
}
exports.sendWebSocketMsg = sendWebSocketMsg;
function closeWebSocketByConnectionId(connectionId) {
    console.log('closeWebSocketByConnectionId', connectionId);
    // console.log('redisSockets', redisSockets)
    redisSockets = redisSockets.filter(function (item) {
        if (item.connectionId == connectionId) {
            // console.log('找到', item, item.socket)
            // console.log('找到', item, item.socket)
            item.socket && item.socket.close();
            // console.log('关闭了')
        }
        return item.connectionId != connectionId;
    });
}
exports.closeWebSocketByConnectionId = closeWebSocketByConnectionId;
function closeWebSocketByDbConnectionId(connectionId) {
    console.log('closeWebSocketByDbConnectionId', connectionId);
    // console.log('redisSockets', redisSockets)
    dbSockets = dbSockets.filter(function (item) {
        if (item.connectionId == connectionId) {
            // console.log('找到', item, item.socket)
            // console.log('找到', item, item.socket)
            item.socket && item.socket.close();
            console.log('关闭了');
        }
        return item.connectionId != connectionId;
    });
}
exports.closeWebSocketByDbConnectionId = closeWebSocketByDbConnectionId;
function closeWebSocketBySftpConnectionId(connectionId) {
    console.log('closeWebSocketBySftpConnectionId', connectionId);
    // console.log('redisSockets', redisSockets)
    sftpSockets = sftpSockets.filter(function (item) {
        if (item.connectionId == connectionId) {
            // console.log('找到', item, item.socket)
            // console.log('找到', item, item.socket)
            item.socket && item.socket.close();
            console.log('关闭了');
        }
        return item.connectionId != connectionId;
    });
}
exports.closeWebSocketBySftpConnectionId = closeWebSocketBySftpConnectionId;
function closeWebSocketByTcpConnectionId(connectionId) {
    tcpSockets = tcpSockets.filter(function (item) {
        if (item.connectionId == connectionId) {
            // console.log('找到', item, item.socket)
            // console.log('找到', item, item.socket)
            item.socket && item.socket.close();
            console.log('关闭了');
        }
        return item.connectionId != connectionId;
    });
}
exports.closeWebSocketByTcpConnectionId = closeWebSocketByTcpConnectionId;
function createSocket(ws) {
    var _this = this;
    var ssh;
    var g_stream;
    var g_isRecord = false;
    // let l_client: SshClient
    function initSsh(config, ws) {
        var defaultPath = config.defaultPath, ptySize = config.ptySize;
        if (config && config.host) {
            var sshClient_1 = new ssh2_1.Client();
            // l_client = sshClient
            sshClient_1
                .on("close", function () {
                console.log('ssh/onClose2');
                ws.close();
            })
                .on('keyboard-interactive', function (name, instructions, instructionsLang, prompts, finish) {
                console.log('ssh/keyboard-interactive 2');
                // finish([this.pass]);
            })
                .on("end", function () {
                console.log('ssh/end 2');
                ws.close();
            })
                .on("error", function (err) {
                console.log('ssh/error2');
                console.log("\r\n*** SSH CONNECTION ERROR: " + err.message + " ***\r\n");
                ws.close();
            })
                .on("ready", function () {
                console.log('ssh/ready 2');
                // ws.send("\r\n*** SSH CONNECTION ESTABLISHED ***\r\n");
                sshClient_1.shell({ cols: ptySize.cols, rows: ptySize.rows }, function (err, stream) {
                    if (err) {
                        return ws.emit("\r\n*** SSH SHELL ERROR: " + err.message + " ***\r\n");
                    }
                    g_stream = stream;
                    // TODO
                    g_stream.resize = function (cols, rows, width, height) {
                        stream.setWindow(rows, cols, width, height);
                    };
                    if (defaultPath) {
                        console.log('cd cd cd cd');
                        g_stream.write("cd ".concat(defaultPath, "\r"));
                    }
                    stream
                        .on("data", function (d) {
                        var data = utf8.decode(d.toString("binary"));
                        // ws.send(data)
                        console.log('ws/send', data);
                        if (g_isRecord) {
                            g_isRecord = false;
                            var path_1 = data.split('\r\n')[1];
                            console.log('path', path_1);
                            ws.send(JSON.stringify({
                                type: 'pwd',
                                data: {
                                    path: path_1,
                                },
                            }));
                        }
                        else {
                            ws.send(JSON.stringify({
                                type: 'res',
                                data: data,
                            }));
                        }
                    })
                        .on("close", function () {
                        console.log('ssh/stream/close');
                        // SSH 断开连接
                        sshClient_1.end();
                        ws.close();
                    });
                });
            })
                .connect(getConnectParams(config));
            return sshClient_1;
        }
        else {
            throw new Error('local terminal is no longer supported from v0.21.0');
            var pty = null;
            var ptyProcess = pty.spawn(shell, [], {
                name: 'xterm-color',
                // cols: 80,
                // rows: 30,
                cols: ptySize.cols || 42,
                rows: ptySize.rows || 30,
                cwd: defaultPath || process.env.HOME,
                // cwd: '/Users/yunser/app/git-auto-2',
                env: process.env
            });
            // ptyProcess.resize()
            ptyProcess.onData(function (data) {
                ws.send(JSON.stringify({
                    type: 'res',
                    data: data,
                }));
            });
            // ptyProcess.on('data', function(data) {
            //     // console.log('ptyProcess', data)
            //     // process.stdout.write(data);
            // })
            // ptyProcess.write('ls\r');
            // ptyProcess.resize(100, 40);
            // ptyProcess.write('ls\r');
            g_stream = ptyProcess;
        }
    }
    var webSocketId = (0, uid_1.uid)(16);
    webSocketId2SocketMap[webSocketId] = ws;
    ws.on("message", function (data) { return __awaiter(_this, void 0, void 0, function () {
        var msgContent, msg, _a, rows, cols, width, height, connectionId, connectionId, connectionId, connectionId, connectionId, connectionId, connectionId;
        return __generator(this, function (_b) {
            console.log("websocket/on message", data.toString());
            msgContent = data.toString();
            if (msgContent == 'ping') {
                ws.send('pong');
                return [2 /*return*/];
            }
            try {
                msg = JSON.parse(data.toString());
            }
            catch (err) {
                // nothing
            }
            if (msg) {
                if (msg.type == 'connect') {
                    ssh = initSsh(msg.data, ws);
                }
                else if (msg.type == 'command') {
                    g_stream.write(msg.data);
                }
                else if (msg.type == 'resize') {
                    _a = msg.data, rows = _a.rows, cols = _a.cols, width = _a.width, height = _a.height;
                    g_stream.resize(cols, rows, width, height);
                }
                else if (msg.type == 'pwd') {
                    // const path = (await sshExec(l_client, 'pwd')).replace(/\s/g, '')
                    // console.log('path', path)
                    // ws.send(JSON.stringify({
                    //     type: 'pwd',
                    //     data: {
                    //         path,
                    //     },
                    // }))
                    g_isRecord = true;
                    g_stream.write('pwd\r');
                }
                else if (msg.type == 'redisSubscribe') {
                    connectionId = msg.data.connectionId;
                    redisSubscribeSockets.push(ws);
                }
                else if (msg.type == 'mqttSubscribe') {
                    connectionId = msg.data.connectionId;
                    mqttSubscribeSockets.push(ws);
                }
                else if (msg.type == 'redisBind') {
                    connectionId = msg.data.connectionId;
                    redisSockets.push({
                        connectionId: connectionId,
                        socket: ws,
                    });
                }
                else if (msg.type == 'dbBind') {
                    connectionId = msg.data.connectionId;
                    dbSockets.push({
                        connectionId: connectionId,
                        socket: ws,
                    });
                }
                else if (msg.type == 'sftpBind') {
                    connectionId = msg.data.connectionId;
                    sftpSockets.push({
                        connectionId: connectionId,
                        socket: ws,
                    });
                }
                else if (msg.type == 'tcpSubscribe') {
                    connectionId = msg.data.connectionId;
                    tcpSockets.push({
                        connectionId: connectionId,
                        socket: ws,
                    });
                }
                else if (msg.type == 'websocketServerSubscribe') {
                    connectionId = msg.data.connectionId;
                    websockServerSockets.push({
                        connectionId: connectionId,
                        socket: ws,
                    });
                    ws['_linkServer'] = connectionId;
                }
                else if (msg.type == 'getWebSocketId') {
                    ws.send(JSON.stringify({
                        type: 'websocketId',
                        data: {
                            webSocketId: webSocketId,
                        },
                    }));
                }
            }
            return [2 /*return*/];
        });
    }); });
    ws.on("close", function () {
        console.log("websocket/close");
        ssh && ssh.end();
        redisSubscribeSockets = redisSubscribeSockets.filter(function (item) { return item !== ws; });
        mqttSubscribeSockets = mqttSubscribeSockets.filter(function (item) { return item !== ws; });
        if (ws['_linkServer']) {
            (0, socket_service_1.closeWebSocketServer)(ws['_linkServer']);
        }
    });
}
wss.on("connection", function (ws) {
    console.log('websocket/connection');
    createSocket(ws);
});
var SshService = /** @class */ (function () {
    function SshService() {
    }
    SshService.prototype.home = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                return [2 /*return*/, 'ssh home'];
            });
        });
    };
    SshService.prototype.connect = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            function _connect() {
                return new Promise(function (resolve, reject) {
                    var ssh = new ssh2_1.Client();
                    ssh
                        .on("ready", function () {
                        console.log('ssh/ready 3');
                        resolve();
                    })
                        .on("close", function () {
                        console.log('ssh/close3');
                        // reject() // TODO
                    })
                        .on("error", function (err) {
                        console.log('ssh/error3');
                        reject(err);
                    });
                    ssh.connect(getConnectParams(body));
                });
            }
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, _connect()];
                    case 1:
                        _a.sent();
                        return [2 /*return*/];
                }
            });
        });
    };
    SshService.prototype._getConnectionList = function () {
        return __awaiter(this, void 0, void 0, function () {
            var content;
            return __generator(this, function (_a) {
                content = fs.readFileSync(sshConnectionFilePath, 'utf-8');
                return [2 /*return*/, JSON.parse(content)];
            });
        });
    };
    SshService.prototype.connectionList = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var _a;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        _a = {};
                        return [4 /*yield*/, this._getConnectionList()];
                    case 1: return [2 /*return*/, (_a.list = _b.sent(),
                            _a)];
                }
            });
        });
    };
    SshService.prototype.connectionMonite = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var id, list, item, sshClient, meminfo, loadavg, uptime, cpuinfo, disk, top, version, lsb, stat1, _a, stat2, _b, cpuRate;
            return __generator(this, function (_c) {
                switch (_c.label) {
                    case 0:
                        id = body.id;
                        return [4 /*yield*/, this._getConnectionList()];
                    case 1:
                        list = _c.sent();
                        item = list.find(function (item) { return item.id == id; });
                        return [4 /*yield*/, createSshConnection(item)
                            // console.log('sshClient', new Date().getTime() - startTime.getTime())
                        ];
                    case 2:
                        sshClient = _c.sent();
                        return [4 /*yield*/, sshExec(sshClient, 'cat /proc/meminfo')];
                    case 3:
                        meminfo = _c.sent();
                        return [4 /*yield*/, sshExec(sshClient, 'cat /proc/loadavg')];
                    case 4:
                        loadavg = _c.sent();
                        return [4 /*yield*/, sshExec(sshClient, 'cat /proc/uptime')];
                    case 5:
                        uptime = _c.sent();
                        return [4 /*yield*/, sshExec(sshClient, 'cat /proc/cpuinfo')
                            // console.log('cpuinfo', new Date().getTime() - startTime.getTime())
                        ];
                    case 6:
                        cpuinfo = _c.sent();
                        return [4 /*yield*/, sshExec(sshClient, 'df -h')
                            // console.log('disk', new Date().getTime() - startTime.getTime())
                        ];
                    case 7:
                        disk = _c.sent();
                        return [4 /*yield*/, sshExec(sshClient, 'top -b -n 1')
                            // console.log('top', new Date().getTime() - startTime.getTime())
                        ];
                    case 8:
                        top = _c.sent();
                        return [4 /*yield*/, sshExec(sshClient, 'cat /proc/version')];
                    case 9:
                        version = _c.sent();
                        return [4 /*yield*/, sshExec(sshClient, 'lsb_release -a')];
                    case 10:
                        lsb = _c.sent();
                        _a = parseStat;
                        return [4 /*yield*/, sshExec(sshClient, 'cat /proc/stat')];
                    case 11:
                        stat1 = _a.apply(void 0, [_c.sent()]);
                        return [4 /*yield*/, sleep(50)];
                    case 12:
                        _c.sent();
                        _b = parseStat;
                        return [4 /*yield*/, sshExec(sshClient, 'cat /proc/stat')];
                    case 13:
                        stat2 = _b.apply(void 0, [_c.sent()]);
                        cpuRate = 1 - (stat2.idle - stat1.idle) / (stat2.total - stat1.total);
                        // console.log('cpuRate', cpuRate)
                        return [2 /*return*/, {
                                item: item,
                                meminfo: meminfo,
                                // stat,
                                cpuUsage: Math.floor(100 * cpuRate),
                                loadavg: loadavg,
                                uptime: uptime,
                                cpuinfo: cpuinfo,
                                disk: disk,
                                top: top,
                                version: version,
                                lsb: lsb,
                            }];
                }
            });
        });
    };
    SshService.prototype._exec = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var id, command, list, item, sshClient, result;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        id = body.id, command = body.command;
                        return [4 /*yield*/, this._getConnectionList()];
                    case 1:
                        list = _a.sent();
                        item = list.find(function (item) { return item.id == id; });
                        return [4 /*yield*/, createSshConnection(item)
                            // console.log('sshClient', new Date().getTime() - startTime.getTime())
                        ];
                    case 2:
                        sshClient = _a.sent();
                        return [4 /*yield*/, sshExec2(sshClient, command)];
                    case 3:
                        result = _a.sent();
                        return [2 /*return*/, result];
                }
            });
        });
    };
    SshService.prototype.connectionEdit = 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(sshConnectionFilePath, '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(sshConnectionFilePath, JSON.stringify(list, null, 4), 'utf-8');
                return [2 /*return*/, {}];
            });
        });
    };
    SshService.prototype.connectionCreate = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var content, list;
            return __generator(this, function (_a) {
                content = fs.readFileSync(sshConnectionFilePath, 'utf-8');
                list = JSON.parse(content);
                list.unshift(__assign(__assign({}, body), { id: (0, uid_1.uid)(32) }));
                fs.writeFileSync(sshConnectionFilePath, JSON.stringify(list, null, 4), 'utf-8');
                return [2 /*return*/, {}];
            });
        });
    };
    SshService.prototype.connectionDelete = 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(sshConnectionFilePath, '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(sshConnectionFilePath, JSON.stringify(newList, null, 4), 'utf-8');
                return [2 /*return*/, {}];
            });
        });
    };
    SshService.prototype.commandList = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var content;
            return __generator(this, function (_a) {
                content = fs.readFileSync(commandDbFilePath, 'utf-8');
                return [2 /*return*/, {
                        list: JSON.parse(content)
                    }];
            });
        });
    };
    return SshService;
}());
exports.SshService = SshService;
//# sourceMappingURL=ssh.service.js.map