"use strict";

function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); }
function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); }
function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; }
function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); }
function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); }
function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); }
function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function _createForOfIteratorHelper(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t["return"] || t["return"](); } finally { if (u) throw o; } } }; }
function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
function _regenerator() { /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */ var e, t, r = "function" == typeof Symbol ? Symbol : {}, n = r.iterator || "@@iterator", o = r.toStringTag || "@@toStringTag"; function i(r, n, o, i) { var c = n && n.prototype instanceof Generator ? n : Generator, u = Object.create(c.prototype); return _regeneratorDefine2(u, "_invoke", function (r, n, o) { var i, c, u, f = 0, p = o || [], y = !1, G = { p: 0, n: 0, v: e, a: d, f: d.bind(e, 4), d: function d(t, r) { return i = t, c = 0, u = e, G.n = r, a; } }; function d(r, n) { for (c = r, u = n, t = 0; !y && f && !o && t < p.length; t++) { var o, i = p[t], d = G.p, l = i[2]; r > 3 ? (o = l === n) && (u = i[(c = i[4]) ? 5 : (c = 3, 3)], i[4] = i[5] = e) : i[0] <= d && ((o = r < 2 && d < i[1]) ? (c = 0, G.v = n, G.n = i[1]) : d < l && (o = r < 3 || i[0] > n || n > l) && (i[4] = r, i[5] = n, G.n = l, c = 0)); } if (o || r > 1) return a; throw y = !0, n; } return function (o, p, l) { if (f > 1) throw TypeError("Generator is already running"); for (y && 1 === p && d(p, l), c = p, u = l; (t = c < 2 ? e : u) || !y;) { i || (c ? c < 3 ? (c > 1 && (G.n = -1), d(c, u)) : G.n = u : G.v = u); try { if (f = 2, i) { if (c || (o = "next"), t = i[o]) { if (!(t = t.call(i, u))) throw TypeError("iterator result is not an object"); if (!t.done) return t; u = t.value, c < 2 && (c = 0); } else 1 === c && (t = i["return"]) && t.call(i), c < 2 && (u = TypeError("The iterator does not provide a '" + o + "' method"), c = 1); i = e; } else if ((t = (y = G.n < 0) ? u : r.call(n, G)) !== a) break; } catch (t) { i = e, c = 1, u = t; } finally { f = 1; } } return { value: t, done: y }; }; }(r, o, i), !0), u; } var a = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} t = Object.getPrototypeOf; var c = [][n] ? t(t([][n]())) : (_regeneratorDefine2(t = {}, n, function () { return this; }), t), u = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(c); function f(e) { return Object.setPrototypeOf ? Object.setPrototypeOf(e, GeneratorFunctionPrototype) : (e.__proto__ = GeneratorFunctionPrototype, _regeneratorDefine2(e, o, "GeneratorFunction")), e.prototype = Object.create(u), e; } return GeneratorFunction.prototype = GeneratorFunctionPrototype, _regeneratorDefine2(u, "constructor", GeneratorFunctionPrototype), _regeneratorDefine2(GeneratorFunctionPrototype, "constructor", GeneratorFunction), GeneratorFunction.displayName = "GeneratorFunction", _regeneratorDefine2(GeneratorFunctionPrototype, o, "GeneratorFunction"), _regeneratorDefine2(u), _regeneratorDefine2(u, o, "Generator"), _regeneratorDefine2(u, n, function () { return this; }), _regeneratorDefine2(u, "toString", function () { return "[object Generator]"; }), (_regenerator = function _regenerator() { return { w: i, m: f }; })(); }
function _regeneratorDefine2(e, r, n, t) { var i = Object.defineProperty; try { i({}, "", {}); } catch (e) { i = 0; } _regeneratorDefine2 = function _regeneratorDefine(e, r, n, t) { function o(r, n) { _regeneratorDefine2(e, r, function (e) { return this._invoke(r, n, e); }); } r ? i ? i(e, r, { value: n, enumerable: !t, configurable: !t, writable: !t }) : e[r] = n : (o("next", 0), o("throw", 1), o("return", 2)); }, _regeneratorDefine2(e, r, n, t); }
function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); }
function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; }
function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
var InstallerValidator = /*#__PURE__*/function () {
  function InstallerValidator() {
    _classCallCheck(this, InstallerValidator);
  }
  return _createClass(InstallerValidator, [{
    key: "validate",
    value: (
    /**
     * 验证安装包与 latest.yml 的一致性
     * @param {string} installerPath - 本地安装包路径
     * @param {string} ymlUrl - latest.yml 的 URL 地址 "http://10.1.6.119:10020/CPCSS/app/programs/latest.yml"
     * @returns {Promise<Object>} 验证结果 { localSize, totalSize, integrity, error }
     */
    function () {
      var _validate = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee(installerPath, ymlUrl) {
        var http, https, crypto, fs, url, result, stats, ymlContent, expectedSize, expectedHash, actualHash, _t;
        return _regenerator().w(function (_context) {
          while (1) switch (_context.p = _context.n) {
            case 0:
              http = require("http");
              https = require("https");
              crypto = require("crypto");
              fs = require("fs");
              url = require("url");
              result = {
                localSize: 0,
                totalSize: 0,
                integrity: false,
                error: null
              };
              _context.p = 1;
              if (fs.existsSync(installerPath)) {
                _context.n = 2;
                break;
              }
              result.localSize = 0;
              result.integrity = false;
              result.error = "";
              return _context.a(2, result);
            case 2:
              // 4. 获取本地文件大小
              stats = fs.statSync(installerPath);
              result.localSize = stats.size;

              // 1. 先获取 yml 中的期望大小
              _context.n = 3;
              return this._fetchYml(ymlUrl, http, https, url);
            case 3:
              ymlContent = _context.v;
              if (ymlContent) {
                _context.n = 4;
                break;
              }
              result.error = "无法获取 latest.yml 文件";
              return _context.a(2, result);
            case 4:
              // 2. 获取期望的文件大小
              expectedSize = this._getExpectedSizeFromYml(ymlContent);
              if (expectedSize) {
                _context.n = 5;
                break;
              }
              result.error = "无法从 latest.yml 获取文件大小信息";
              return _context.a(2, result);
            case 5:
              result.totalSize = expectedSize;

              // 5. 比较文件大小
              if (!(result.localSize !== result.totalSize)) {
                _context.n = 6;
                break;
              }
              result.integrity = false;
              return _context.a(2, result);
            case 6:
              // 6. 大小一致，验证完整性
              expectedHash = this._getExpectedHashFromYml(ymlContent);
              if (expectedHash) {
                _context.n = 7;
                break;
              }
              result.error = "无法从 latest.yml 获取校验和";
              result.integrity = false;
              return _context.a(2, result);
            case 7:
              _context.n = 8;
              return this._calculateSHA512(installerPath, fs, crypto);
            case 8:
              actualHash = _context.v;
              result.integrity = actualHash === expectedHash;
              _context.n = 10;
              break;
            case 9:
              _context.p = 9;
              _t = _context.v;
              result.error = _t.message;
            case 10:
              return _context.a(2, result);
          }
        }, _callee, this, [[1, 9]]);
      }));
      function validate(_x, _x2) {
        return _validate.apply(this, arguments);
      }
      return validate;
    }()
    /**
     * 使用 http/https 获取 yml 文件内容
     * @private
     */
    )
  }, {
    key: "_fetchYml",
    value: function _fetchYml(ymlUrl, http, https, url) {
      return new Promise(function (resolve, reject) {
        var parsedUrl = new url.URL(ymlUrl);
        var client = parsedUrl.protocol === "https:" ? https : http;
        var options = {
          hostname: parsedUrl.hostname,
          port: parsedUrl.port || (parsedUrl.protocol === "https:" ? 443 : 80),
          path: parsedUrl.pathname + parsedUrl.search,
          method: "GET",
          timeout: 10000
        };
        var req = client.request(options, function (res) {
          if (res.statusCode !== 200) {
            reject("HTTP ".concat(res.statusCode));
            return;
          }
          var data = "";
          res.setEncoding("utf8");
          res.on("data", function (chunk) {
            data += chunk;
          });
          res.on("end", function () {
            resolve(data);
          });
        });
        req.on("error", reject);
        req.on("timeout", function () {
          req.destroy();
          reject("请求超时");
        });
        req.end();
      });
    }

    /**
     * 从 yml 内容解析出期望的文件大小
     * @private
     */
  }, {
    key: "_getExpectedSizeFromYml",
    value: function _getExpectedSizeFromYml(ymlContent) {
      var lines = ymlContent.split("\n");
      var _iterator = _createForOfIteratorHelper(lines),
        _step;
      try {
        for (_iterator.s(); !(_step = _iterator.n()).done;) {
          var line = _step.value;
          // 匹配 size: 203355500
          var sizeMatch = line.match(/^\s*size:\s*(\d+)/);
          if (sizeMatch) {
            return parseInt(sizeMatch[1], 10);
          }

          // 匹配 files 数组中的 size
          var filesSizeMatch = line.match(/^\s*-\s*size:\s*(\d+)/);
          if (filesSizeMatch) {
            return parseInt(filesSizeMatch[1], 10);
          }
        }
      } catch (err) {
        _iterator.e(err);
      } finally {
        _iterator.f();
      }
      return null;
    }

    /**
     * 从 yml 内容解析出期望的 SHA512 哈希值
     * @private
     */
  }, {
    key: "_getExpectedHashFromYml",
    value: function _getExpectedHashFromYml(ymlContent) {
      var lines = ymlContent.split("\n");
      var _iterator2 = _createForOfIteratorHelper(lines),
        _step2;
      try {
        for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
          var line = _step2.value;
          // 匹配 sha512: Mtz9okK5w05...
          var hashMatch = line.match(/^\s*sha512:\s*(.+)/);
          if (hashMatch) {
            return hashMatch[1].trim();
          }

          // 匹配 files 数组中的 sha512
          var filesHashMatch = line.match(/^\s*-\s*sha512:\s*(.+)/);
          if (filesHashMatch) {
            return filesHashMatch[1].trim();
          }
        }
      } catch (err) {
        _iterator2.e(err);
      } finally {
        _iterator2.f();
      }
      return null;
    }

    /**
     * 计算文件的 SHA512 哈希值
     * @private
     */
  }, {
    key: "_calculateSHA512",
    value: function _calculateSHA512(filePath, fs, crypto) {
      return new Promise(function (resolve, reject) {
        var hash = crypto.createHash("sha512");
        var stream = fs.createReadStream(filePath);
        stream.on("data", function (data) {
          return hash.update(data);
        });
        stream.on("end", function () {
          resolve(hash.digest("base64"));
        });
        stream.on("error", reject);
      });
    }
  }]);
}();
var PluginUpdate = /*#__PURE__*/function () {
  function PluginUpdate() {
    var _ktLog, _electron$remote;
    var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
    _classCallCheck(this, PluginUpdate);
    _defineProperty(this, "tempDir", "");
    _defineProperty(this, "tempDirName", "temp_dir");
    _defineProperty(this, "baseDirUrl", "");
    _defineProperty(this, "hdBaseUrl", "");
    _defineProperty(this, "zipType", "1");
    // 全量压缩包 0 增量包 1  第三方插件 2
    _defineProperty(this, "installType", "0");
    // 3 非标包 4 硬件库
    _defineProperty(this, "version", "");
    // 升级包版本
    _defineProperty(this, "unZipPath", "");
    // 解压后的资源文件夹
    _defineProperty(this, "zipName", "");
    // 压缩包名
    _defineProperty(this, "isReboot", false);
    // 是否自动重启
    _defineProperty(this, "exeDir", "");
    // exe 所在目录
    _defineProperty(this, "isInstaller", false);
    _defineProperty(this, "downloadLastTs", 0);
    // 下载最后更新时间
    _defineProperty(this, "appCode", "CPCSS");
    _defineProperty(this, "installerPath", "");
    _defineProperty(this, "vbsPath", "");
    _defineProperty(this, "remoteVbsPath", "");
    _defineProperty(this, "downloading", false);
    _defineProperty(this, "totalLength", 0);
    _defineProperty(this, "latestYmlUrl", "");
    _defineProperty(this, "onProgress", function () {});
    _defineProperty(this, "delDirList", []);
    // 下载执行
    _defineProperty(this, "checkTimer", null);
    _defineProperty(this, "tryCount", 1);
    this.log = opts.log || ((_ktLog = ktLog) === null || _ktLog === void 0 ? void 0 : _ktLog.i) || console.log;
    this.serverIp = opts.serverIp || localConfig.serverIP;
    this.isReboot = !!opts.isReboot;
    this.onProgress = opts.onProgress || function () {};
    var appCode = opts.appCode || global.appCode || "CPCSS";
    this.appCode = appCode;
    this.exeDir = this.getAppDir();
    var path = require("path");
    var electron = require("electron");
    var app = ((_electron$remote = electron.remote) === null || _electron$remote === void 0 ? void 0 : _electron$remote.app) || electron.app;
    var userDataPath = app.getPath("userData");
    this.baseDirUrl = path.join(path.dirname(userDataPath), "".concat(appCode, "_RESOURCE"));
    this.tempDir = path.join(this.baseDirUrl, this.tempDirName);
    if (process.platform === "linux") {
      this.hdBaseUrl = process.resourcesPath;
    } else {
      this.hdBaseUrl = this.getAppDir();
    }
  }
  return _createClass(PluginUpdate, [{
    key: "getAppDir",
    value: function getAppDir() {
      var _electron$remote2;
      var path = require("path");
      var electron = require("electron");
      var app = ((_electron$remote2 = electron.remote) === null || _electron$remote2 === void 0 ? void 0 : _electron$remote2.app) || electron.app;
      if (app.isPackaged && process.platform === "win32") {
        var exePath = app.getPath("exe");
        return path.dirname(exePath);
      }
      return process.cwd();
    }
    // 检测系统是否有杀毒软件
  }, {
    key: "querySoftware",
    value: function querySoftware() {
      var _this = this;
      return new Promise(function (resolve) {
        try {
          if (process.platform !== "win32") return;
          var _require = require("child_process"),
            exec = _require.exec;
          // 一次性查询所有可能的相关服务
          var serviceQueries = ['sc query "ZhuDongFangYu"', 'sc query "HipsDaemon"', 'sc query "KSafeSvc"', 'sc query "QQPCMgr"', 'sc query "WinDefend"', 'sc query "AVP"', 'sc query "NIS"', 'sc query "McAfeeFramework"', 'sc query "VSSERV"', 'sc query "Avast"'];
          var results = [];
          var completed = 0;
          serviceQueries.forEach(function (query, index) {
            exec(query, function (error, stdout) {
              try {
                completed++;
                if (stdout && stdout.includes("SERVICE_NAME:")) {
                  // 从输出中提取服务名
                  var serviceMatch = stdout.match(/SERVICE_NAME:\s*(\S+)/);
                  if (serviceMatch) {
                    var serviceName = serviceMatch[1];
                    var status = stdout.includes("RUNNING") ? "运行中" : "已停止";

                    // 映射服务名到杀毒软件名称
                    var avMap = {
                      ZhuDongFangYu: "360安全卫士",
                      HipsDaemon: "火绒安全",
                      KSafeSvc: "金山毒霸",
                      QQPCMgr: "腾讯电脑管家",
                      WinDefend: "Windows Defender",
                      AVP: "卡巴斯基",
                      NIS: "诺顿",
                      McAfeeFramework: "迈克菲",
                      VSSERV: "比特梵德",
                      Avast: "Avast"
                    };
                    if (avMap[serviceName]) {
                      results.push({
                        name: avMap[serviceName],
                        service: serviceName,
                        status: status
                      });
                    }
                  }
                }
                if (completed === serviceQueries.length) {
                  resolve(results);
                  if (results.length > 0) {
                    _this.log("\u68C0\u6D4B\u5230\u6740\u6BD2\u8F6F\u4EF6\u670D\u52A1".concat(JSON.stringify(results)));
                  }
                }
              } catch (err) {
                _this.log("\u68C0\u6D4B\u6740\u6BD2\u8F6F\u4EF6\u5F02\u5E38".concat(JSON.stringify({
                  err: err
                })));
                resolve([]);
              }
            });
          });
        } catch (err) {
          _this.log("\u68C0\u6D4B\u6740\u6BD2\u8F6F\u4EF6\u5F02\u5E38".concat(JSON.stringify({
            err: err
          })));
          resolve([]);
        }
      });
    }
    // 收到升级指令
  }, {
    key: "update",
    value: function () {
      var _update = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee2() {
        var data,
          newTerminalAppResUrl,
          newTerminalAppVersion,
          path,
          exeName,
          src,
          remoteVbs,
          _args2 = arguments,
          _t2;
        return _regenerator().w(function (_context2) {
          while (1) switch (_context2.p = _context2.n) {
            case 0:
              data = _args2.length > 0 && _args2[0] !== undefined ? _args2[0] : {};
              _context2.p = 1;
              this.querySoftware();
              this.installType = data.installType + "";

              // 将下载地址中的IP替换为车场服务器IP
              if (this.serverIp) data.newTerminalAppResUrl = data.newTerminalAppResUrl.replace(/(\d{1,3}\.){3}\d{1,3}/, this.serverIp);
              _context2.n = 2;
              return this.getUpdateJson(data.newTerminalAppResUrl);
            case 2:
              newTerminalAppResUrl = data.newTerminalAppResUrl, newTerminalAppVersion = data.newTerminalAppVersion;
              this.version = newTerminalAppVersion;
              if (!(newTerminalAppResUrl.indexOf(".zip") > -1)) {
                _context2.n = 3;
                break;
              }
              this.log("\u589E\u91CF\u5305 Update start\uFF1A".concat(newTerminalAppResUrl));
              return _context2.a(2, this.updateDiffPackage(data));
            case 3:
              this.log("\u5B89\u88C5\u5305 Update start\uFF1A".concat(newTerminalAppResUrl));
              path = require("path");
              exeName = data.newTerminalAppResUrl.split("/").pop();
              src = data.newTerminalAppResUrl.replace(exeName, "install.vbs");
              remoteVbs = path.join(this.getAppDir(), "remoteInstall.vbs");
              _context2.n = 4;
              return this.downloadVbsScript(src, remoteVbs);
            case 4:
              this.remoteVbsPath = _context2.v;
              return _context2.a(2, this.updateInstaller(data));
            case 5:
              _context2.p = 5;
              _t2 = _context2.v;
              this.log("Update failed:".concat(_t2));
              _context2.n = 6;
              return this.delDir(this.tempDir);
            case 6:
              _context2.n = 7;
              return this.delDir(this.unZipPath);
            case 7:
              return _context2.a(2, Promise.reject(_t2));
          }
        }, _callee2, this, [[1, 5]]);
      }));
      function update() {
        return _update.apply(this, arguments);
      }
      return update;
    }() // 本地更新  // 1增量包(默认)  2第三方插件 3硬件库 4非标包
  }, {
    key: "localeUpdate",
    value: function () {
      var _localeUpdate = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee3(filePath) {
        var zipType,
          fs,
          path,
          unZipPath,
          asarPath,
          secondDir,
          secondZipPath,
          appJson,
          _args3 = arguments,
          _t3;
        return _regenerator().w(function (_context3) {
          while (1) switch (_context3.p = _context3.n) {
            case 0:
              zipType = _args3.length > 1 && _args3[1] !== undefined ? _args3[1] : "1";
              _context3.p = 1;
              this.log("Update start\uFF1A".concat(filePath));
              this.zipType = zipType;
              fs = require("fs");
              path = require("path");
              if (fs.existsSync(filePath)) {
                _context3.n = 2;
                break;
              }
              return _context3.a(2, Promise.reject("Not Found ".concat(filePath)));
            case 2:
              // 压缩包名称、解压缩文件夹
              this.zipName = path.basename(filePath).replace(".zip", "").trim();
              unZipPath = this.unZipPath = path.join(this.baseDirUrl, this.zipName);
              _context3.n = 3;
              return this.unzip({
                zipPath: filePath,
                targetDir: this.unZipPath
              });
            case 3:
              // 上传运维的增量包是二次压缩包
              asarPath = path.join(unZipPath, "app.asar");
              secondDir = path.join(this.baseDirUrl, "".concat(this.zipName, "/").concat(this.zipName));
              secondZipPath = path.join(secondDir, "".concat(this.zipName, ".zip"));
              if (!(zipType === "1" && !fs.existsSync(asarPath) && fs.existsSync(secondZipPath))) {
                _context3.n = 4;
                break;
              }
              this.unZipPath = path.join(this.baseDirUrl, "".concat(this.zipName, "_second"));
              this.log("\u4E8C\u6B21\u89E3\u538B\uFF1A".concat(secondZipPath, " -> ").concat(this.unZipPath));
              _context3.n = 4;
              return this.unzip({
                zipPath: secondZipPath,
                targetDir: this.unZipPath
              });
            case 4:
              _context3.n = 5;
              return this.runScript();
            case 5:
              appJson = path.join(process.resourcesPath, "app.json"); // 删除app.json-新方案不需要-不删除新旧版本来回切换会出现问题
              if (this.zipType === "1" && fs.existsSync(appJson)) {
                this.delFile(appJson);
              }
              _context3.n = 6;
              return this.delDir(unZipPath);
            case 6:
              _context3.n = 7;
              return this.delDir(this.unZipPath);
            case 7:
              this.log("Update completed");
              if (this.isReboot) this.reboot();
              _context3.n = 10;
              break;
            case 8:
              _context3.p = 8;
              _t3 = _context3.v;
              this.log("localeUpdate failed:".concat(_t3));
              _context3.n = 9;
              return this.delDir(this.unZipPath);
            case 9:
              return _context3.a(2, Promise.reject(_t3));
            case 10:
              return _context3.a(2);
          }
        }, _callee3, this, [[1, 8]]);
      }));
      function localeUpdate(_x3) {
        return _localeUpdate.apply(this, arguments);
      }
      return localeUpdate;
    }() // 读取更新配置
  }, {
    key: "getUpdateJson",
    value: function () {
      var _getUpdateJson = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee4(url) {
        var res, _yield$res$json, zipType, _t4;
        return _regenerator().w(function (_context4) {
          while (1) switch (_context4.p = _context4.n) {
            case 0:
              _context4.p = 0;
              url = url.substring(0, url.lastIndexOf("/"));
              url = "".concat(url, "/update.json");
              this.log("Get ".concat(url));
              _context4.n = 1;
              return fetch(url);
            case 1:
              res = _context4.v;
              _context4.n = 2;
              return res.json();
            case 2:
              _yield$res$json = _context4.v;
              zipType = _yield$res$json.zipType;
              this.zipType = zipType || "1";
              return _context4.a(2, Promise.resolve());
            case 3:
              _context4.p = 3;
              _t4 = _context4.v;
              this.log("Not found update.json");
              return _context4.a(2, Promise.resolve());
          }
        }, _callee4, this, [[0, 3]]);
      }));
      function getUpdateJson(_x4) {
        return _getUpdateJson.apply(this, arguments);
      }
      return getUpdateJson;
    }() // 下载
  }, {
    key: "startDownload",
    value: function startDownload(_ref) {
      var _this2 = this;
      var url = _ref.url,
        filePath = _ref.filePath;
      return new Promise(/*#__PURE__*/function () {
        var _ref2 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee5(resolve, reject) {
          var fs, _yield$_this2$checkPa, isFull, _t5;
          return _regenerator().w(function (_context5) {
            while (1) switch (_context5.p = _context5.n) {
              case 0:
                fs = require("fs");
                _context5.p = 1;
                _context5.n = 2;
                return _this2.checkPackages(filePath);
              case 2:
                _yield$_this2$checkPa = _context5.v;
                isFull = _yield$_this2$checkPa.isFull;
                if (!isFull) {
                  _context5.n = 3;
                  break;
                }
                return _context5.a(2, resolve());
              case 3:
                _this2.checkNetwork(url).then(function (_ref3) {
                  var available = _ref3.available,
                    error = _ref3.error,
                    contentLength = _ref3.contentLength;
                  if (!available) {
                    _this2.log("\u7F51\u7EDC/\u8FDE\u63A5\u4E0D\u53EF\u7528\uFF1A".concat(error));
                    return reject(error);
                  }
                  _this2.totalLength = contentLength || 0;
                  if (_this2.downloading) {
                    _this2.log("\u5F53\u524D\u6709\u6B63\u5728\u6267\u884C\u7684\u4E0B\u8F7D\u4EFB\u52A1\uFF0C\u4E0D\u7EE7\u7EED\u6267\u884C\u4E0B\u8F7D");
                    return reject("当前有正在执行的下载任务，不继续执行下载");
                  }
                  _this2.checkTimer && clearInterval(_this2.checkTimer);
                  _this2.tryCount = 1;
                  _this2.downloadTask({
                    url: url,
                    filePath: filePath
                  }).then(resolve)["catch"](reject)["finally"](function () {
                    _this2.downloading = false;
                    _this2.tryCount = 1;
                    _this2.checkTimer && clearInterval(_this2.checkTimer);
                  });
                });
                _context5.n = 5;
                break;
              case 4:
                _context5.p = 4;
                _t5 = _context5.v;
                _this2.downloading = false;
                _this2.tryCount = 1;
                _this2.checkTimer && clearInterval(_this2.checkTimer);
                if (fs.existsSync(filePath)) {
                  _this2.delFile(filePath);
                }
                _this2.log("\u6267\u884C\u4E0B\u8F7D\u5F02\u5E38\uFF1A".concat(_t5.message));
                return _context5.a(2, reject("\u6267\u884C\u4E0B\u8F7D\u5F02\u5E38\uFF1A".concat(_t5.message)));
              case 5:
                return _context5.a(2);
            }
          }, _callee5, null, [[1, 4]]);
        }));
        return function (_x5, _x6) {
          return _ref2.apply(this, arguments);
        };
      }());
    }
    // 检测网络是否可用
  }, {
    key: "checkNetwork",
    value: function checkNetwork(url) {
      return new Promise(function (resolve) {
        var http = require("http");
        var https = require("https");
        var lib = url.startsWith("https://") ? https : http;
        var options = {
          method: "HEAD",
          timeout: 10000
        };
        var req = lib.request(url, options, function (res) {
          var success = res.statusCode >= 200 && res.statusCode < 400;

          // 解析文件大小
          var fileSize = 0;
          var fileSizeValid = false;
          if (res.headers["content-length"]) {
            fileSize = parseInt(res.headers["content-length"], 10);
            fileSizeValid = !isNaN(fileSize) && fileSize > 0;
          }
          resolve({
            available: success,
            statusCode: res.statusCode,
            contentLength: fileSizeValid ? fileSize : null,
            contentLengthHeader: res.headers["content-length"],
            // 原始header值
            contentType: res.headers["content-type"],
            acceptRanges: res.headers["accept-ranges"],
            // 是否支持断点续传
            lastModified: res.headers["last-modified"],
            // 最后修改时间
            headers: res.headers,
            fileSizeValid: fileSizeValid
          });
          res.resume();
        });
        req.on("timeout", function () {
          req.destroy();
          resolve({
            available: false,
            error: "请求超时",
            contentLength: null,
            fileSizeValid: false
          });
        });
        req.on("error", function (error) {
          resolve({
            available: false,
            error: error.message,
            contentLength: null,
            fileSizeValid: false
          });
        });
        req.end();
      });
    }
  }, {
    key: "downloadTask",
    value: function downloadTask(_ref4) {
      var _this3 = this;
      var url = _ref4.url,
        filePath = _ref4.filePath;
      return new Promise(function (resolve, reject) {
        try {
          _this3.log("Download: ".concat(url, " -> ").concat(filePath));
          var fs = require("fs");
          var http = require("http");
          var https = require("https");
          var lib = url.startsWith("https") ? https : http;
          var downloadBytes = 0;
          var headers = {};
          if (fs.existsSync(filePath)) {
            downloadBytes = fs.statSync(filePath).size;
            if (downloadBytes === _this3.totalLength && downloadBytes > 0) {
              _this3.log("\u5DF2\u5168\u90E8\u4E0B\u8F7D\u5B8C\u6210 ".concat(downloadBytes));
              return resolve();
            }
            _this3.log("\u5DF2\u4E0B\u8F7D\u90E8\u5206\u6587\u4EF6\uFF0C\u7EE7\u7EED\u6267\u884C\u4E0B\u8F7D ".concat(downloadBytes));
            headers["Range"] = "bytes=".concat(downloadBytes, "-");
          }
          var isDestroy = false;

          // 发送请求
          _this3.downloading = true;
          var request = lib.get(url, {
            headers: headers
          }, function (response) {
            if (response.statusCode === 206 || response.statusCode === 200) {
              var writer = fs.createWriteStream(filePath, {
                flags: "a"
              }); // 以追加模式打开文件
              // 创建一个 PassThrough 流来处理数据
              var _require2 = require("stream"),
                PassThrough = _require2.PassThrough;
              var passThroughStream = new PassThrough();
              _this3.checkTimer && clearInterval(_this3.checkTimer);
              _this3.checkTimer = setInterval(function () {
                if (Date.now() - _this3.downloadLastTs > 30000) {
                  _this3.log("\u68C0\u6D4B\u523030s\u4E0B\u8F7D\u8FDB\u5EA6\u672A\u66F4\u65B0\uFF0C\u7B2C".concat(_this3.tryCount, "\u6B21\u91CD\u8BD5"));
                  if (_this3.tryCount > 10) {
                    reject("\u5C1D\u8BD5".concat(_this3.tryCount, "\u6B21\u4ECD\u4E0B\u8F7D\u5931\u8D25\uFF0C\u4E0D\u518D\u91CD\u8BD5"));
                    return;
                  }
                  _this3.tryCount += 1;
                  _this3.checkNetwork(url).then(function (_ref5) {
                    var available = _ref5.available,
                      error = _ref5.error;
                    if (available) {
                      _this3.log("尝试重新下载");
                      isDestroy = true;
                      request.destroy();
                      response.destroy();
                      passThroughStream.destroy();
                      writer.destroy();
                      _this3.checkTimer && clearInterval(_this3.checkTimer);
                      _this3.downloadTask({
                        url: url,
                        filePath: filePath
                      }).then(resolve)["catch"](reject);
                    } else {
                      _this3.log("\u91CD\u8BD5\u7F51\u7EDC\u4E0D\u53EF\u7528\uFF1A".concat(error));
                      if (_this3.tryCount > 10) {
                        reject("\u5C1D\u8BD5".concat(_this3.tryCount, "\u6B21\u4ECD\u4E0B\u8F7D\u5931\u8D25\uFF0C\u4E0D\u518D\u91CD\u8BD5"));
                      }
                    }
                  });
                }
              }, 30000);

              // 监听数据流的 'data' 事件来更新下载进度
              passThroughStream.on("data", function (chunk) {
                _this3.tryCount = 1;
                _this3.downloadLastTs = Date.now();
                downloadBytes += chunk.length;
                var progress = downloadBytes / _this3.totalLength * 100;
                var val = progress.toFixed(0);
                _this3.onProgress(val);
              });

              // 将响应数据流管道到 PassThrough 流
              response.pipe(passThroughStream);

              // 将 PassThrough 流管道到文件写入流
              passThroughStream.pipe(writer);
              writer.on("finish", function () {
                // 销毁时不做处理
                if (isDestroy) return;
                _this3.log("Download completed.");
                resolve();
              });
              writer.on("error", function (err) {
                _this3.log("Download failed: ".concat(err.message));
                reject(err);
              });
              passThroughStream.on("error", function (err) {
                _this3.log("Download failed: ".concat(err.message));
                reject(err);
              });
            } else {
              _this3.log("Server responded with status code: ".concat(response.statusCode));
              reject("Server responded with status code: ".concat(response.statusCode));
            }
          }).on("error", function (error) {
            _this3.log("Download failed: ".concat(error.message));
            reject(error);
          });

          // 超时处理 - 网络断开不做处理
          // request.setTimeout(20000, () => {
          //   request.destroy("Request timeout");
          // });
        } catch (error) {
          _this3.log("Download failed: ".concat(error.message));
          reject(error);
        }
      });
    }
    // 检测.zip文件完整性
  }, {
    key: "hasValidZipEndHeader",
    value: function hasValidZipEndHeader(filePath) {
      try {
        var fs = require("fs");
        var buffer = fs.readFileSync(filePath);

        // 文件太小不可能是有效的ZIP
        if (buffer.length < 22) {
          return false;
        }

        // END header 签名: 0x504B0506
        var endSignature = [0x50, 0x4b, 0x05, 0x06];

        // 从文件末尾向前搜索 (最多搜索64KB范围)
        var searchEnd = Math.max(0, buffer.length - 65557);
        for (var i = buffer.length - 4; i >= searchEnd; i--) {
          if (buffer[i] === endSignature[0] && buffer[i + 1] === endSignature[1] && buffer[i + 2] === endSignature[2] && buffer[i + 3] === endSignature[3]) {
            // 找到签名，验证基本结构
            return this.validateBasicEndHeader(buffer, i);
          }
        }
        return false;
      } catch (error) {
        console.error("检测失败:", error.message);
        return false;
      }
    }
    // 验证zip完整性
  }, {
    key: "validateBasicEndHeader",
    value: function validateBasicEndHeader(buffer, offset) {
      try {
        // 读取中央目录大小和偏移量
        var centralDirSize = buffer.readUInt32LE(offset + 12);
        var centralDirOffset = buffer.readUInt32LE(offset + 16);

        // 基本验证
        return centralDirOffset < buffer.length && centralDirSize > 0 && centralDirSize < buffer.length;
      } catch (_unused) {
        return false;
      }
    }
    // 解压
  }, {
    key: "unzip",
    value: function () {
      var _unzip = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee6(_ref6) {
        var _this4 = this;
        var zipPath, targetDir, _ref6$overWrite, overWrite, fs, _require3, exec, command, AdmZip, zip, _t6;
        return _regenerator().w(function (_context6) {
          while (1) switch (_context6.p = _context6.n) {
            case 0:
              zipPath = _ref6.zipPath, targetDir = _ref6.targetDir, _ref6$overWrite = _ref6.overWrite, overWrite = _ref6$overWrite === void 0 ? true : _ref6$overWrite;
              _context6.p = 1;
              fs = require("fs");
              if (!fs.existsSync(targetDir)) fs.mkdirSync(targetDir, {
                recursive: true
              });
              if (!(process.platform === "linux")) {
                _context6.n = 2;
                break;
              }
              _require3 = require("child_process"), exec = _require3.exec;
              command = "unzip ".concat(overWrite ? "-o" : "", " \"").concat(zipPath, "\" -d \"").concat(targetDir, "\"");
              this.log("Unzip using command: ".concat(command));
              return _context6.a(2, new Promise(function (resolve, reject) {
                exec(command, function (error, stdout, stderr) {
                  if (error) {
                    _this4.log("Unzip failed: ".concat(stderr));
                    reject(error);
                  } else {
                    _this4.log("Unzip completed.");
                    resolve();
                  }
                });
              }));
            case 2:
              AdmZip = require("adm-zip");
              this.log("Unzip ".concat(zipPath, " -> ").concat(targetDir));
              zip = new AdmZip(zipPath);
              _context6.n = 3;
              return zip.extractAllTo(targetDir, overWrite);
            case 3:
              this.log("Unzip completed.");
              _context6.n = 7;
              break;
            case 4:
              _context6.p = 4;
              _t6 = _context6.v;
              this.log("Unzip failed:".concat(_t6));
              _context6.n = 5;
              return this.delDir(zipPath);
            case 5:
              _context6.n = 6;
              return this.delDir(targetDir);
            case 6:
              return _context6.a(2, Promise.reject(_t6));
            case 7:
              return _context6.a(2);
          }
        }, _callee6, this, [[1, 4]]);
      }));
      function unzip(_x7) {
        return _unzip.apply(this, arguments);
      }
      return unzip;
    }() // 删除文件夹
  }, {
    key: "delDir",
    value: function delDir(folderPath) {
      var _this5 = this;
      return new Promise(function (resolve, reject) {
        var fs = require("fs");
        if (!fs.existsSync(folderPath)) return resolve();
        _this5.log("Del tempDir:".concat(folderPath));

        // 根据操作系统选择不同的命令
        var command = process.platform === "win32" ? "rmdir /s /q \"".concat(folderPath, "\"") : "sudo rm -rf \"".concat(folderPath, "\"");
        var _require4 = require("child_process"),
          exec = _require4.exec;
        exec(command, function (error, stdout, stderr) {
          if (error) {
            _this5.log("Error deleting directory: ".concat(error.message));
            _this5.delDirFailed(folderPath);
            return resolve();
          }
          if (stderr) {
            _this5.log("Error deleting directory: ".concat(stderr));
            _this5.delDirFailed(folderPath);
            return resolve();
          }
          _this5.log("Del completed");
          resolve();
        });
      });
    }
    // 删除文件
  }, {
    key: "delFile",
    value: function delFile(file) {
      var _this6 = this;
      var fs = require("fs");
      if (!fs.existsSync(file)) return Promise.resolve();
      var cmd = process.platform === "win32" ? "del /f /q \"".concat(file, "\"") : "rm -f \"".concat(file, "\"");

      // 执行命令
      return new Promise(function (resolve, reject) {
        _this6.log("\u6267\u884C\u6587\u4EF6\u5220\u9664\u547D\u4EE4: ".concat(cmd));
        var _require5 = require("child_process"),
          exec = _require5.exec;
        exec(cmd, function (error, stdout, stderr) {
          if (error) return reject(error);
          if (stderr) return reject(stderr);
          resolve();
        });
      });
    }
    // 文件夹删除失败
  }, {
    key: "delDirFailed",
    value: function delDirFailed(dir) {
      this.delDirList.push(dir);
      localStorage.setItem("UP_DEL_DIR_LIST", JSON.stringify(this.delDirList));
    }
    // 检测安装包/增量包完整性
  }, {
    key: "checkPackages",
    value: function () {
      var _checkPackages = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee7(filePath) {
        var result, fs, check, _yield$check$validate, localSize, totalSize, integrity, error, _t7;
        return _regenerator().w(function (_context7) {
          while (1) switch (_context7.p = _context7.n) {
            case 0:
              result = {
                size: 0,
                totalSize: 0,
                isFull: false,
                error: ""
              };
              _context7.p = 1;
              this.log("\u9A8C\u8BC1\u5305\u5B8C\u6574\u6027".concat(filePath));
              fs = require("fs");
              check = new InstallerValidator();
              _context7.n = 2;
              return check.validate(filePath, this.latestYmlUrl);
            case 2:
              _yield$check$validate = _context7.v;
              localSize = _yield$check$validate.localSize;
              totalSize = _yield$check$validate.totalSize;
              integrity = _yield$check$validate.integrity;
              error = _yield$check$validate.error;
              result.totalSize = totalSize;
              result.size = localSize;
              if (fs.existsSync(filePath)) {
                _context7.n = 3;
                break;
              }
              this.log("\u5305\u4E0D\u5B58\u5728\uFF0C\u9700\u91CD\u65B0\u4E0B\u8F7D");
              return _context7.a(2, result);
            case 3:
              if (error) this.log(error);
              if (!(totalSize === 0)) {
                _context7.n = 5;
                break;
              }
              if (!(filePath.indexOf(".zip") > -1)) {
                _context7.n = 4;
                break;
              }
              // 无 latest.yml时 zip 压缩包校验
              result.isFull = this.hasValidZipEndHeader(filePath);
              if (result.isFull) this.log("zip\u5305\u5B8C\u6574\uFF0C\u65E0\u9700\u4E0B\u8F7D");
              return _context7.a(2, result);
            case 4:
              result.error = error || "latest.yml读取异常";
              return _context7.a(2, result);
            case 5:
              if (!(localSize === totalSize && integrity)) {
                _context7.n = 6;
                break;
              }
              this.log("\u5B89\u88C5\u5305\u5B8C\u6574\uFF0C\u65E0\u9700\u4E0B\u8F7D (".concat(totalSize, ")"));
              result.isFull = true;
              return _context7.a(2, result);
            case 6:
              if (!(localSize >= totalSize)) {
                _context7.n = 7;
                break;
              }
              this.log("\u5305\u635F\u574F\uFF0C\u9700\u91CD\u65B0\u4E0B\u8F7D");
              fs.unlinkSync(filePath);
              return _context7.a(2, result);
            case 7:
              this.log("\u5305\u90E8\u5206\u5B58\u5728\uFF0C\u7EE7\u7EED\u4E0B\u8F7D");
              result.size = localSize;
              return _context7.a(2, result);
            case 8:
              _context7.n = 10;
              break;
            case 9:
              _context7.p = 9;
              _t7 = _context7.v;
              this.log("\u9A8C\u8BC1\u5305\u5B8C\u6574\u6027\u5F02\u5E38:".concat(_t7.message));
              return _context7.a(2, result);
            case 10:
              return _context7.a(2);
          }
        }, _callee7, this, [[1, 9]]);
      }));
      function checkPackages(_x8) {
        return _checkPackages.apply(this, arguments);
      }
      return checkPackages;
    }() // 更新增量包
  }, {
    key: "updateDiffPackage",
    value: function () {
      var _updateDiffPackage = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee8(data) {
        var url, fs, path, urlObj, filename, filePath, _yield$this$checkPack, isFull, error, unZipPath, appJson, _t8, _t9;
        return _regenerator().w(function (_context8) {
          while (1) switch (_context8.p = _context8.n) {
            case 0:
              _context8.p = 0;
              // 压缩资源包下载 - CPCSS_RESOURCE
              url = data.newTerminalAppResUrl;
              fs = require("fs");
              path = require("path");
              urlObj = new URL(url);
              filename = urlObj.pathname.split("/").pop();
              this.zipName = filename.replace(".zip", "").trim();
              // 创建临时下载文件夹
              if (!fs.existsSync(this.tempDir)) fs.mkdirSync(this.tempDir, {
                recursive: true
              });
              filePath = path.join(this.tempDir, filename);
              this.latestYmlUrl = url.replace(filename, "latest.yml");
              _context8.n = 1;
              return this.startDownload({
                url: url,
                filePath: filePath
              });
            case 1:
              _context8.n = 2;
              return this.checkPackages(filePath);
            case 2:
              _yield$this$checkPack = _context8.v;
              isFull = _yield$this$checkPack.isFull;
              error = _yield$this$checkPack.error;
              if (isFull) {
                _context8.n = 3;
                break;
              }
              this.log("\u5305\u5B8C\u6574\u6027\u9A8C\u8BC1\u5931\u8D25\uFF0C\u5347\u7EA7\u5931\u8D25");
              return _context8.a(2, Promise.reject(error));
            case 3:
              // 解压版本文件夹
              unZipPath = this.unZipPath = path.join(this.baseDirUrl, this.zipName);
              _context8.n = 4;
              return this.unzip({
                zipPath: filePath,
                targetDir: unZipPath,
                overWrite: true
              });
            case 4:
              _context8.n = 5;
              return this.runScript();
            case 5:
              _context8.p = 5;
              appJson = path.join(process.resourcesPath, "app.json"); // 删除app.json-新方案不需要-不删除新旧版本来回切换会出现问题
              if (this.zipType === "1" && fs.existsSync(appJson)) {
                fs.unlinkSync(appJson);
              }
              _context8.n = 6;
              return this.delDir(this.tempDir);
            case 6:
              _context8.n = 7;
              return this.delDir(this.unZipPath);
            case 7:
              _context8.n = 9;
              break;
            case 8:
              _context8.p = 8;
              _t8 = _context8.v;
              this.log("\u6355\u83B7\u5230\u5220\u9664\u4E34\u65F6\u6587\u4EF6\u5F02\u5E38".concat(_t8 ? _t8.message : ""));
            case 9:
              this.isInstaller = false;
              this.installerPath = "";
              this.log("Update completed");
              if (this.isReboot) this.reboot();
              return _context8.a(2, Promise.resolve());
            case 10:
              _context8.p = 10;
              _t9 = _context8.v;
              this.log("updateDiffPackage \u6267\u884C\u5F02\u5E38".concat(JSON.stringify({
                err: _t9
              })));
              return _context8.a(2, Promise.reject(_t9));
          }
        }, _callee8, this, [[5, 8], [0, 10]]);
      }));
      function updateDiffPackage(_x9) {
        return _updateDiffPackage.apply(this, arguments);
      }
      return updateDiffPackage;
    }() // 下载安装脚本
  }, {
    key: "downloadVbsScript",
    value: function () {
      var _downloadVbsScript = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee9(remoteUrl, localPath) {
        var _this7 = this;
        return _regenerator().w(function (_context9) {
          while (1) switch (_context9.n) {
            case 0:
              return _context9.a(2, new Promise(function (resolve) {
                var fs = require("fs");
                var http = require("http");
                var https = require("https");
                var protocol = remoteUrl.startsWith("https") ? https : http;
                var req = protocol.get(remoteUrl, function (response) {
                  if (response.statusCode !== 200) {
                    _this7.log("\u8FDC\u7A0B\u5B89\u88C5\u811A\u672C\u4E0B\u8F7D\u5931\u8D25: HTTP ".concat(response.statusCode));
                    resolve("");
                    return;
                  }
                  var writeStream = fs.createWriteStream(localPath);
                  response.pipe(writeStream);
                  writeStream.on("finish", function () {
                    writeStream.close();
                    _this7.log("\u5B89\u88C5\u811A\u672C\u5DF2\u4FDD\u5B58\u5230: ".concat(localPath));
                    resolve(localPath);
                  });
                  writeStream.on("error", function (err) {
                    // 清理可能损坏的文件
                    fs.unlink(localPath, function () {});
                    _this7.log("\u5B89\u88C5\u811A\u672C\u6587\u4EF6\u5199\u5165\u5931\u8D25: ".concat(err.message));
                    resolve("");
                  });
                });

                // 请求超时处理
                req.setTimeout(30000, function () {
                  req.destroy();
                  _this7.log("安装脚本请求30s超时");
                  resolve("");
                });

                // 请求错误处理
                req.on("error", function (err) {
                  _this7.log("\u5B89\u88C5\u811A\u672C\u7F51\u7EDC\u8BF7\u6C42\u5931\u8D25: ".concat(err.message));
                  resolve("");
                });
              }));
          }
        }, _callee9);
      }));
      function downloadVbsScript(_x0, _x1) {
        return _downloadVbsScript.apply(this, arguments);
      }
      return downloadVbsScript;
    }() // 更新安装包
  }, {
    key: "updateInstaller",
    value: function updateInstaller(data) {
      var _this8 = this;
      return new Promise(function (resolve, reject) {
        var fs = require("fs");
        var path = require("path");
        var _require6 = require("electron"),
          ipcRenderer = _require6.ipcRenderer;
        _this8.vbsPath = path.join(_this8.getAppDir(), "install.vbs");
        if (fs.existsSync(_this8.remoteVbsPath)) {
          _this8.vbsPath = _this8.remoteVbsPath;
        }
        if (data.newTerminalAppResUrl.includes(".exe") && fs.existsSync(_this8.vbsPath)) {
          var _electron$remote3;
          _this8.log("\u6267\u884C\u81EA\u5B9A\u4E49\u4E0B\u8F7D-\u5B89\u88C5\u6D41\u7A0B");
          var url = data.newTerminalAppResUrl;
          var electron = require("electron");
          var app = ((_electron$remote3 = electron.remote) === null || _electron$remote3 === void 0 ? void 0 : _electron$remote3.app) || electron.app;
          var filename = url.split("/").pop();
          var appDataPath = app.getPath("appData");
          var appCode = _this8.appCode.toLowerCase();
          var updaterDir = path.join(appDataPath, "../Local/".concat(appCode, "-updater"));
          if (!fs.existsSync(updaterDir)) {
            fs.mkdirSync(updaterDir, {
              recursive: true
            });
          }
          var filePath = path.join(updaterDir, filename);
          _this8.latestYmlUrl = url.replace(filename, "latest.yml");
          _this8.startDownload({
            url: url,
            filePath: filePath
          }).then(function () {
            // 下载完成后检测包完整性
            _this8.checkPackages(filePath).then(function (_ref7) {
              var isFull = _ref7.isFull;
              if (isFull) {
                _this8.isInstaller = true;
                _this8.installerPath = filePath;
                _this8.rebootInstall();
                if (_this8.isReboot) {
                  _this8.reboot();
                } else {
                  resolve();
                }
              } else {
                reject("\u5B89\u88C5\u5305\u5B8C\u6574\u6027\u9A8C\u8BC1\u5931\u8D25");
              }
            })["catch"](reject);
          })["catch"](reject);
          return;
        }
        _this8.log("\u6267\u884C\u9ED8\u8BA4\u4E0B\u8F7D-\u5B89\u88C5\u6D41\u7A0B");
        // 升级错误
        ipcRenderer.on("update-error", function (err) {
          _this8.log("update-error ".concat(err));
          reject(err);
        });
        // 未检测到可升级版本
        ipcRenderer.on("update-not-available", function (e, newVersion) {
          _this8.log("update-not-available");
          reject("update-not-available");
        });
        // 检测允许升级 -
        ipcRenderer.on("update-available", function (e, newVersion) {
          // 确认下载
          if (newVersion) {
            _this8.log("update-available：confirmDownload");
            ipcRenderer.send("confirmDownload");
          }
        });
        // 下载进度
        ipcRenderer.on("download-progress", function (e, val) {
          var percent = val.percent.toFixed(0);
          _this8.onProgress(percent);
        });
        // 下载完成
        ipcRenderer.on("update-downloaded", /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee0() {
          return _regenerator().w(function (_context0) {
            while (1) switch (_context0.n) {
              case 0:
                _this8.log("update-downloaded");
                _this8.installerPath = "";
                _this8.isInstaller = true;
                resolve();
                if (_this8.isReboot) _this8.reboot();
              case 1:
                return _context0.a(2);
            }
          }, _callee0);
        })));
        var appExt = {
          win32: [".exe"],
          linux: [".AppImage", ".deb"]
        };
        if (!appExt[process.platform]) return reject(process.platform);
        var appExtension = "";
        var _iterator3 = _createForOfIteratorHelper(appExt[process.platform]),
          _step3;
        try {
          for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
            var val = _step3.value;
            if (data.newTerminalAppResUrl.endsWith(val)) {
              appExtension = val;
            }
          }
        } catch (err) {
          _iterator3.e(err);
        } finally {
          _iterator3.f();
        }
        if (!appExtension) {
          _this8.log("".concat(data.newTerminalAppResUrl, " invalid"));
          return reject("".concat(data.newTerminalAppResUrl, " invalid"));
        }
        _this8.log("update installer ".concat(data.newTerminalAppResUrl));
        if (process.platform == "linux" && data.newTerminalAppResUrl.includes(".deb")) {
          _this8.linuxUpdateDeb(data);
          return;
        }
        data.newTerminalAppResUrl = data.newTerminalAppResUrl.substring(0, data.newTerminalAppResUrl.lastIndexOf("/"));
        data.appExtension = appExtension;
        // 开始升级
        ipcRenderer.send("focusWin");
        ipcRenderer.send("autoUpdate", {
          data: JSON.parse(JSON.stringify(data)),
          isAutoUpdate: false,
          isShowProgress: false,
          notificationStyle: 2
        });
      });
    }
  }, {
    key: "runInstallHandler",
    value: function runInstallHandler() {
      this.log("\u76D1\u542C\u5230-\u7A0B\u5E8F\u9000\u51FA\u4E8B\u4EF6-\u6267\u884C\u5B89\u88C5");
      this.reboot();
    }
    // 监听重启-触发安装
  }, {
    key: "rebootInstall",
    value: function rebootInstall() {
      try {
        var _require7 = require("electron"),
          ipcRenderer = _require7.ipcRenderer;
        this.log("\u5F00\u59CB\u76D1\u542C-\u7A0B\u5E8F\u9000\u51FA\u4E8B\u4EF6-\u76D1\u542C\u5230\u9000\u51FA\u65F6\u5B89\u88C5");
        // 还需监听程序退出时自动执行安装
        ipcRenderer.once("runInstall", this.runInstallHandler);
        ipcRenderer.send("awaitInstall");
      } catch (err) {
        this.log("\u76D1\u542C\u7A0B\u5E8F\u9000\u51FA-\u6267\u884C\u5B89\u88C5\u5F02\u5E38".concat(err.message));
      }
    }
    // 自定义安装脚本
  }, {
    key: "customInstall",
    value: function customInstall() {
      var _electron$remote4;
      if (!this.installerPath) return;
      this.log("开始执行自定义安装脚本");
      var fs = require("fs");
      var electron = require("electron");
      var app = ((_electron$remote4 = electron.remote) === null || _electron$remote4 === void 0 ? void 0 : _electron$remote4.app) || electron.app;
      var appDir = this.getAppDir();
      if (!fs.existsSync(this.vbsPath)) {
        this.log("install.vbs \u811A\u672C\u4E22\u5931");
        return;
      }
      if (!fs.existsSync(this.installerPath)) {
        this.log("".concat(this.installerPath, " \u5B89\u88C5\u5305\u4E22\u5931"));
        return;
      }
      var _require8 = require("electron"),
        ipcRenderer = _require8.ipcRenderer;
      ipcRenderer.removeListener("runInstall", this.runInstallHandler);
      var _require9 = require("child_process"),
        spawn = _require9.spawn;
      var files = fs.readdirSync(appDir);
      var pattern = new RegExp("^(KT_)?".concat(this.appCode, "_(\\d+\\.)+\\d+\\.exe$"));
      // const pattern = /^(KT_)?CPCSS_(\d+\.)+\d+\.exe$/;
      var productName = files.find(function (file) {
        return pattern.test(file);
      }) || app.getName();
      if (process.env.NODE_ENV === "development") {
        productName = "Electron";
        appDir = "";
      }
      var child = spawn("wscript", [this.vbsPath, productName, appDir, this.installerPath], {
        detached: true,
        stdio: "ignore"
      });
      child.unref();
      app.quit();
    }
    /** linux升级更新Deb包 */
  }, {
    key: "linuxUpdateDeb",
    value: function linuxUpdateDeb(data) {
      var _this9 = this;
      var electron = require("electron");
      var fs = require("fs");
      var path = require("path");
      var _require0 = require("child_process"),
        exec = _require0.exec;
      var packageJsonPath = process.env.NODE_ENV === "development" ? path.join(process.cwd(), "package.json") : path.join(process.resourcesPath, "./app.asar.unpacked/package.json");
      var packData = fs.readFileSync(packageJsonPath);
      var _JSON$parse = JSON.parse(packData),
        name = _JSON$parse.name,
        productName = _JSON$parse.productName;
      var processObj = electron.remote ? electron.remote.getGlobal("process") : process;
      var baseDir = processObj.env.HOME;
      if (!baseDir) {
        baseDir = (electron.app || electron.remote.app).getPath("appData");
      }
      data.newTerminalAppResName = data.newTerminalAppResUrl.substring(data.newTerminalAppResUrl.lastIndexOf("/") + 1, data.newTerminalAppResUrl.length);
      data.newTerminalAppResUrl = data.newTerminalAppResUrl.substring(0, data.newTerminalAppResUrl.lastIndexOf("/"));
      var desktopDebPath = "".concat(baseDir, "/Desktop/").concat(data.newTerminalAppResName);
      var desktopAppImagePath = "".concat(baseDir, "/Desktop/").concat(productName, ".AppImage");
      var autostartDesktop = "".concat(baseDir, "/.config/autostart/").concat(name.toUpperCase(), ".desktop");
      var autostartStartupSh = "".concat(baseDir, "/.config/autostart/Startup").concat(name.toLocaleUpperCase(), ".sh");
      data.newTerminalAppResUrl = data.newTerminalAppResUrl + "/" + data.newTerminalAppResName;
      //删除Deb安装包
      if (fs.existsSync(desktopDebPath)) {
        fs.unlinkSync(desktopDebPath);
      }
      exec(" wget --timeout=1800 --tries=6 --waitretry=300 -c -P  ".concat(baseDir, "/Desktop ").concat(data.newTerminalAppResUrl, " "), {
        timeout: 1000 * 60 * 30
      }, function (error, stdout, stderr) {
        try {
          fs.chmodSync(desktopDebPath, "777");
          exec("dpkg -l|grep ".concat(name.toLowerCase()), function (error, stdout, stderr) {
            if (stdout.includes("".concat(name.toLowerCase()))) {
              exec("sudo dpkg -r ".concat(name.toLowerCase()), function (error, stdout, stderr) {
                if (error) {
                  _this9.log("卸载已安装LCD入口取票机deb包错误" + error);
                }
                exec("sudo dpkg -i ".concat(desktopDebPath), (error, stdout, function (stderr) {
                  if (error) {
                    _this9.log("安装新的Deb软件包报错：" + error);
                  }
                  _this9.log("安装新的eb软件包成功，进行设置开机自启动，系统重启");
                  _this9.setDesktopAndReboot(desktopDebPath, name, baseDir);
                }));
              });
            } else {
              exec("sudo dpkg -i ".concat(desktopDebPath), (error, stdout, function (stderr) {
                if (error) {
                  _this9.log("安装Deb软件包报错：" + error);
                }
                _this9.log("安装Deb软件包成功，进行设置开机自启动，删除相关文件，系统重启");
                _this9.setDesktopAndReboot(desktopDebPath, name, baseDir, desktopAppImagePath, autostartDesktop, autostartStartupSh);
              }));
            }
          });
        } catch (e) {
          _this9.log("升级Deb安装包异常：" + e);
        }
      }).stderr.on("data", function (data) {
        // 解析进度信息
        var progressMatch = data.toString().match(/(\d+)%/);
        if (progressMatch) {
          var progress = parseInt(progressMatch[1], 10);
          _this9.onProgress(progress);
        }
      });
    }
    // Deb软件包安装成功，进行设置开机自启动，删除相关文件，系统重启
  }, {
    key: "setDesktopAndReboot",
    value: function setDesktopAndReboot(desktopDebPath, name, baseDir, desktopAppImagePath, autostartDesktop, autostartStartupSh) {
      var _this0 = this;
      var fs = require("fs");
      var _require1 = require("child_process"),
        exec = _require1.exec;
      var usrShareDesktop = "/usr/share/applications/".concat(name.toLowerCase(), ".desktop");
      var autostartDesktop = "".concat(baseDir, "/.config/autostart/").concat(name.toLowerCase(), ".desktop");
      var copyFile = function copyFile(usrShareDesktop, autostartDesktop) {
        fs.copyFile(usrShareDesktop, autostartDesktop, function (error) {
          if (error) {
            _this0.log("设置开机自启动.desktop报错：" + error);
            return;
          }
          //删除Deb安装包
          if (fs.existsSync(desktopDebPath)) {
            fs.unlinkSync(desktopDebPath);
          }
          //删除桌面AppImage包、开机自启动文件
          if (fs.existsSync(desktopAppImagePath)) {
            fs.unlinkSync(desktopAppImagePath);
            if (fs.existsSync(autostartDesktop)) {
              fs.unlinkSync(autostartDesktop);
            }
            if (fs.existsSync(autostartStartupSh)) {
              fs.unlinkSync(autostartStartupSh);
            }
          }
          _this0.log("三秒后重启系统");
          setTimeout(function () {
            exec("sudo reboot", function (error) {
              if (error) {
                exec("reboot");
              }
            });
          }, 3000);
        });
      };
      if (process.platform == "linux" && process.arch == "x64") {
        exec("lsb_release -ds", function (error, stdout) {
          if (error !== null) {
            console.log("获取当前系统版本号出错:" + error);
          } else {
            console.log("获取当前系统版本号：" + stdout.trim());
            if (stdout.trim().includes("Deepin")) {
              usrShareDesktop = "/usr/share/applications/com.keytop.".concat(name.toLowerCase(), ".desktop");
              autostartDesktop = "".concat(baseDir, "/.config/autostart/com.keytop.").concat(name.toLowerCase(), ".desktop");
            }
            copyFile(usrShareDesktop, autostartDesktop);
          }
        });
      } else {
        copyFile(usrShareDesktop, autostartDesktop);
      }
    }
    // 拷贝文件夹覆盖/不覆盖
  }, {
    key: "copyDirectory",
    value: function copyDirectory(dir, targetPath) {
      var _this1 = this;
      var overwrite = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
      var fs = require("fs");
      var path = require("path");
      var _require10 = require("child_process"),
        exec = _require10.exec;
      if (!fs.existsSync(dir)) return Promise.resolve();
      // 确保目标目录存在
      if (!fs.existsSync(targetPath)) {
        fs.mkdirSync(targetPath, {
          recursive: true
        });
      }
      var stat = fs.statSync(dir);
      var isFile = !stat.isDirectory() || path.extname(dir) === ".asar";
      // 构建命令
      var command;
      if (process.platform === "win32") {
        if (isFile) {
          // command = `xcopy /Y "${dir}" "${targetPath}"`;
          // if (!overwrite) {
          //   command = `xcopy "${dir}" "${targetPath}"`;
          // }
          var flag = overwrite ? "/IS" : "/XN /XO";
          var dirName = path.dirname(dir);
          var basename = path.basename(dir);
          command = "robocopy \"".concat(dirName, "\" \"").concat(targetPath, "\" \"").concat(basename, "\" ").concat(flag, " /NP");
        } else {
          // command = `xcopy /E /I /Y "${dir}" "${targetPath}"`;
          // if (!overwrite) {
          //   command = `xcopy /E /I "${dir}" "${targetPath}"`;
          // }
          var _flag = overwrite ? "/IS" : "/XN /XO";
          command = "robocopy \"".concat(dir, "\" \"").concat(targetPath, "\" /E ").concat(_flag, " /NP");
        }
      } else {
        if (isFile) {
          command = "cp -r -f \"".concat(dir, "\" \"").concat(targetPath, "\"");
          if (!overwrite) {
            command = "cp -nr \"".concat(dir, "\" \"").concat(targetPath, "\"");
          }
        } else {
          command = "cp -r -f \"".concat(dir, "\"/* \"").concat(targetPath, "\"");
          if (!overwrite) {
            command = "cp -nr \"".concat(dir, "\"/* \"").concat(targetPath, "\"");
          }
        }
      }

      // 执行命令
      return new Promise(function (resolve, reject) {
        exec(command, function (error, stdout, stderr) {
          if (process.platform === "win32") {
            if (error && typeof error.code === "undefined") {
              _this1.log("Error copying: ".concat(error.message));
              return reject(error);
            }
            var errCode = error ? error.code : 0;
            if (errCode > 7) {
              _this1.log("Error copying: ".concat(error.message));
              return reject(error);
            }
          } else {
            if (error) {
              _this1.log("Error copying: ".concat(error.message));
              return reject(error);
            }
            if (stderr) {
              _this1.log();
              return reject("Error copying: ".concat(stderr));
            }
          }
          _this1.log("copied successfully.");
          resolve();
        });
      });
    }
    // 读取文件夹
  }, {
    key: "readDirFile",
    value: function () {
      var _readDirFile = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee1(dir) {
        return _regenerator().w(function (_context1) {
          while (1) switch (_context1.n) {
            case 0:
              return _context1.a(2, new Promise(function (resolve, reject) {
                var fs = require("fs");
                var path = require("path");
                if (!fs.existsSync(dir)) return resolve({
                  files: [],
                  dirList: []
                });
                fs.readdir(dir, function (err, entries) {
                  if (err) return reject("Unable to scan directory: ".concat(err));
                  var files = [];
                  var dirList = [];
                  entries.forEach(function (fileName) {
                    var filePath = path.join(dir, fileName);
                    var stats = fs.statSync(filePath);
                    if (stats.isFile()) files.push(filePath);
                    if (stats.isDirectory()) dirList.push(filePath);
                  });
                  resolve({
                    files: files,
                    dirList: dirList
                  });
                });
              }));
          }
        }, _callee1);
      }));
      function readDirFile(_x10) {
        return _readDirFile.apply(this, arguments);
      }
      return readDirFile;
    }() // 拷贝硬件库
  }, {
    key: "copyHdFiles",
    value: function () {
      var _copyHdFiles = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee10(hardwareDir, hardwareTargetDir, filter) {
        var _this10 = this;
        var path, _yield$this$readDirFi, files, dirList, dirPromises, hdFiles, promises;
        return _regenerator().w(function (_context10) {
          while (1) switch (_context10.n) {
            case 0:
              path = require("path");
              _context10.n = 1;
              return this.readDirFile(hardwareDir);
            case 1:
              _yield$this$readDirFi = _context10.v;
              files = _yield$this$readDirFi.files;
              dirList = _yield$this$readDirFi.dirList;
              dirPromises = dirList.map(function (i) {
                var normalizedPath = path.normalize(i);
                var dirName = path.basename(normalizedPath);
                var targetDir = path.join(hardwareTargetDir, dirName);
                _this10.copyDirectory(i, targetDir, true);
              });
              hdFiles = filter ? filter(files) : files;
              promises = hdFiles.map(function (i) {
                return _this10.copyDirectory(i, hardwareTargetDir, true);
              });
              this.log("\u66FF\u6362\u786C\u4EF6\u5E93\uFF1A".concat(JSON.stringify(hdFiles.concat(dirList)), " -> ").concat(hardwareTargetDir));
              return _context10.a(2, Promise.all(promises.concat(dirPromises)));
          }
        }, _callee10, this);
      }));
      function copyHdFiles(_x11, _x12, _x13) {
        return _copyHdFiles.apply(this, arguments);
      }
      return copyHdFiles;
    }()
  }, {
    key: "getHdDirName",
    value: function getHdDirName() {
      var dirName = "win32";
      if (process.platform === "linux") {
        dirName = process.arch === "arm" ? "linux-arm" : process.arch === "arm64" ? "linux-arm64" : process.arch === "x64" ? "linux-x64" : "linux";
      }
      return dirName;
    }
    // 执行升级脚本
  }, {
    key: "runScript",
    value: function () {
      var _runScript = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee11() {
        var fs, path, dir, enJsPath, dirName, hdDir, hdTargetDir, _dir, _dirName, _hdTargetDir, regex, linuxDir, upDir, asar, packagesDir, hardwareDir, hasAsar, hasPackages, hasHardware, platformName, _hdTargetDir2, _hdDir, target, _t0, _t1;
        return _regenerator().w(function (_context11) {
          while (1) switch (_context11.p = _context11.n) {
            case 0:
              _context11.p = 0;
              fs = require("fs");
              path = require("path"); // 非标包
              if (!(this.installType === "3" || this.zipType === "4")) {
                _context11.n = 4;
                break;
              }
              dir = this.unZipPath;
              enJsPath = path.join(dir, "scriptEntry.js");
              if (!fs.existsSync(enJsPath)) {
                dir = path.join(this.unZipPath, this.zipName);
                enJsPath = path.join(dir, "scriptEntry.js");
              }
              if (fs.existsSync(enJsPath)) {
                _context11.n = 1;
                break;
              }
              return _context11.a(2, Promise.reject("Not Found ".concat(enJsPath)));
            case 1:
              dirName = this.getHdDirName();
              hdDir = path.join(dir, "hardware/".concat(dirName)); // 拷贝到安装目录下，避免文件占用无法替换问题
              hdTargetDir = path.join(this.hdBaseUrl, "hardware/".concat(dirName));
              if (process.platform === "linux") {
                if (!fs.existsSync(hdDir)) {
                  hdDir = path.join(dir, "hardware/linux");
                  if (!fs.existsSync(hdDir)) hdDir = "";
                }
                if (!fs.existsSync(hdTargetDir)) hdTargetDir = path.join(this.hdBaseUrl, "hardware/linux");
              }
              if (!(hdDir && fs.existsSync(hdDir))) {
                _context11.n = 2;
                break;
              }
              _context11.n = 2;
              return this.copyHdFiles(hdDir, hdTargetDir);
            case 2:
              _context11.n = 3;
              return this.delDir(path.join(dir, "hardware"));
            case 3:
              this.log("\u66FF\u6362\u975E\u6807\u6587\u4EF6\uFF1A".concat(dir, " -> ").concat(this.baseDirUrl));
              return _context11.a(2, this.copyDirectory(dir, this.baseDirUrl, true));
            case 4:
              if (!(this.installType === "4" || this.zipType === "3")) {
                _context11.n = 9;
                break;
              }
              _dir = this.unZipPath;
              _dirName = this.getHdDirName();
              _hdTargetDir = path.join(process.cwd(), "hardware/".concat(_dirName));
              regex = /-linux-arm|-linux-x86|-linux-arm64|-android|-ohos/g;
              _t0 = _dirName;
              _context11.n = _t0 === "linux-arm" ? 5 : _t0 === "linux-arm64" ? 6 : _t0 === "linux-x64" ? 7 : 8;
              break;
            case 5:
              regex = /-win|-linux-x86|-linux-arm64|-android|-ohos/g;
              return _context11.a(3, 8);
            case 6:
              regex = /-win|-linux-x86|-linux-arm|-android|-ohos/g;
              return _context11.a(3, 8);
            case 7:
              regex = /-win|-linux-arm64|-linux-arm|-android|-ohos/g;
              return _context11.a(3, 8);
            case 8:
              if (process.platform === "linux") {
                _hdTargetDir = path.join(this.hdBaseUrl, "hardware/".concat(_dirName));
                linuxDir = path.join(this.hdBaseUrl, "hardware/linux");
                if (!fs.existsSync(_hdTargetDir)) _hdTargetDir = linuxDir;
                // await this.hdHardWareRelease();
              }
              return _context11.a(2, this.copyHdFiles(_dir, _hdTargetDir, function (list) {
                return list.filter(function (i) {
                  return !i.match(regex);
                });
              }));
            case 9:
              if (!(this.zipType === "1" || this.zipType === "2")) {
                _context11.n = 17;
                break;
              }
              if (!(process.env.NODE_ENV === "development")) {
                _context11.n = 10;
                break;
              }
              return _context11.a(2, Promise.reject("开发环境不执行升级"));
            case 10:
              // 升级包地址
              upDir = this.unZipPath;
              asar = path.join(upDir, "app.asar");
              packagesDir = path.join(upDir, "packages");
              hardwareDir = path.join(upDir, "hardware");
              hasAsar = fs.existsSync(asar);
              hasPackages = fs.existsSync(packagesDir);
              hasHardware = fs.existsSync(hardwareDir);
              if (!(!hasAsar && !hasPackages && !hasHardware)) {
                _context11.n = 11;
                break;
              }
              return _context11.a(2, Promise.reject("\u6CA1\u6709\u627E\u5230\u6587\u4EF6 ".concat(asar, "|").concat(packagesDir, "|").concat(hardwareDir)));
            case 11:
              if (!hasPackages) {
                _context11.n = 12;
                break;
              }
              _context11.n = 12;
              return this.upPackages(packagesDir);
            case 12:
              if (!(hasHardware && process.platform === "win32")) {
                _context11.n = 14;
                break;
              }
              platformName = this.getHdDirName();
              _hdTargetDir2 = path.join(this.hdBaseUrl, "hardware/".concat(platformName));
              _hdDir = path.join(hardwareDir, platformName); // 存在该平台的硬件库文件夹
              if (!fs.existsSync(_hdDir)) {
                _context11.n = 13;
                break;
              }
              this.log("\u62F7\u8D1D\u786C\u4EF6\u5E93:".concat(_hdDir, "->").concat(_hdTargetDir2));
              _context11.n = 13;
              return this.copyDirectory(_hdDir, _hdTargetDir2);
            case 13:
              _context11.n = 14;
              return this.delDir(hasHardware);
            case 14:
              if (!hasAsar) {
                _context11.n = 16;
                break;
              }
              target = process.resourcesPath;
              this.log("\u62F7\u8D1D\u589E\u91CF\u5305\uFF1A".concat(upDir, " -> ").concat(target));
              _context11.n = 15;
              return this.copyDirectory(upDir, target, true);
            case 15:
              _context11.n = 16;
              return this.delDir(upDir);
            case 16:
              return _context11.a(2, Promise.resolve());
            case 17:
              _context11.n = 19;
              break;
            case 18:
              _context11.p = 18;
              _t1 = _context11.v;
              this.log("runScript \u6267\u884C\u5F02\u5E38".concat(JSON.stringify({
                err: _t1
              })));
              return _context11.a(2, Promise.reject(_t1));
            case 19:
              return _context11.a(2);
          }
        }, _callee11, this, [[0, 18]]);
      }));
      function runScript() {
        return _runScript.apply(this, arguments);
      }
      return runScript;
    }() // 更新packages
  }, {
    key: "upPackages",
    value: function () {
      var _upPackages = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee12(packagesDir) {
        var _this11 = this;
        var fs, path, files, promiseArr;
        return _regenerator().w(function (_context12) {
          while (1) switch (_context12.n) {
            case 0:
              fs = require("fs");
              path = require("path");
              files = fs.readdirSync(packagesDir);
              promiseArr = [];
              files.forEach(function (file) {
                var filePath = path.join(packagesDir, file);
                var stat = fs.statSync(filePath);
                var target = _this11.exeDir;
                if (stat.isDirectory()) {
                  target = path.join(_this11.exeDir, file);
                  if (!fs.existsSync(target)) fs.mkdirSync(target, {
                    recursive: true
                  });
                }
                _this11.log("\u62F7\u8D1D\u63D2\u4EF6:".concat(filePath, "->").concat(target));
                promiseArr.push(_this11.copyDirectory(filePath, target, true));
              });
              _context12.n = 1;
              return Promise.all(promiseArr);
            case 1:
              _context12.n = 2;
              return this.delDir(packagesDir);
            case 2:
              return _context12.a(2);
          }
        }, _callee12, this);
      }));
      function upPackages(_x14) {
        return _upPackages.apply(this, arguments);
      }
      return upPackages;
    }() // 释放硬件库进程
  }, {
    key: "hdHardWareRelease",
    value: function hdHardWareRelease() {
      var _this12 = this;
      return new Promise(function (resolve, reject) {
        if (global.mainHdApi && global.mainHdApi.hdHardWareRelease) {
          _this12.log("释放硬件库进程");
          global.mainHdApi.hdHardWareRelease();
          return setTimeout(function () {
            return resolve();
          }, 300);
        }
        resolve();
      });
    }
    // 重启系统、应用
  }, {
    key: "reboot",
    value: function reboot() {
      var _electron$remote5;
      var _require11 = require("child_process"),
        exec = _require11.exec;
      var electron = require("electron");
      var app = ((_electron$remote5 = electron.remote) === null || _electron$remote5 === void 0 ? void 0 : _electron$remote5.app) || electron.app;

      // linux 上直接重启系统
      if (process.platform === "linux") {
        exec("sudo reboot");
      } else {
        if (this.isInstaller) {
          if (this.installerPath) {
            this.customInstall();
          } else {
            var _require12 = require("electron"),
              ipcRenderer = _require12.ipcRenderer;
            ipcRenderer.send("confirmUpdate");
          }
        } else {
          app.relaunch();
          app.exit(0);
        }
      }
    }
    // 检测是否有未完成的下载任务
  }, {
    key: "checkDownloadTask",
    value: function checkDownloadTask() {
      return null;
    }
  }], [{
    key: "preTask",
    value: function () {
      var _preTask = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee13() {
        return _regenerator().w(function (_context13) {
          while (1) switch (_context13.n) {
            case 0:
              console.log("\u5347\u7EA7\u524D\u53EF\u6267\u884C\u811A\u672C");
            case 1:
              return _context13.a(2);
          }
        }, _callee13);
      }));
      function preTask() {
        return _preTask.apply(this, arguments);
      }
      return preTask;
    }()
  }]);
}(); // 升级完成-程序启动后执行
var RemoveTemp = /*#__PURE__*/function (_PluginUpdate2) {
  function RemoveTemp() {
    _classCallCheck(this, RemoveTemp);
    return _callSuper(this, RemoveTemp, arguments);
  }
  _inherits(RemoveTemp, _PluginUpdate2);
  return _createClass(RemoveTemp, [{
    key: "loadedDelDir",
    value: function () {
      var _loadedDelDir = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee14() {
        var _this13 = this;
        var data, list, fs, promiseArr, _t10;
        return _regenerator().w(function (_context14) {
          while (1) switch (_context14.p = _context14.n) {
            case 0:
              _context14.p = 0;
              data = localStorage.getItem("UP_DEL_DIR_LIST") || "[]";
              localStorage.removeItem("UP_DEL_DIR_LIST");
              list = JSON.parse(data);
              fs = require("fs");
              promiseArr = [];
              list.forEach(function (dirPath) {
                if (fs.existsSync(dirPath)) {
                  promiseArr.push(_this13.delDir(dirPath));
                }
              });
              if (!(promiseArr.length === 0)) {
                _context14.n = 1;
                break;
              }
              return _context14.a(2, Promise.resolve());
            case 1:
              this.log("\u5220\u9664-\u5347\u7EA7\u9057\u7559\u6587\u4EF6 ".concat(list.join()));
              _context14.n = 2;
              return Promise.all(promiseArr);
            case 2:
              return _context14.a(2, _context14.v);
            case 3:
              _context14.p = 3;
              _t10 = _context14.v;
              this.log("\u5220\u9664-\u5347\u7EA7\u9057\u7559\u6587\u4EF6\u5931\u8D25:".concat(_t10.message));
              return _context14.a(2, Promise.reject(_t10));
          }
        }, _callee14, this, [[0, 3]]);
      }));
      function loadedDelDir() {
        return _loadedDelDir.apply(this, arguments);
      }
      return loadedDelDir;
    }() // 程序启动后-删除安装包
  }, {
    key: "loadedDelInstaller",
    value: function loadedDelInstaller() {
      var _this14 = this;
      return new Promise(function (resolve) {
        var _electron$remote6, _global$utils;
        var fs = require("fs");
        var path = require("path");
        var electron = require("electron");
        var app = ((_electron$remote6 = electron.remote) === null || _electron$remote6 === void 0 ? void 0 : _electron$remote6.app) || electron.app;
        var appDataPath = app.getPath("appData");
        var appCode = global.appCode || ((_global$utils = global.utils) === null || _global$utils === void 0 ? void 0 : _global$utils.appCode) || "cpcss";
        appCode = appCode.toLowerCase();
        var installerTxtPath = path.join(appDataPath, "./".concat(appCode, "_installer.txt"));
        if (!fs.existsSync(installerTxtPath)) return;
        _this14.log("\u5220\u9664-\u5B89\u88C5\u5305");
        fs.readFile(installerTxtPath, {
          encoding: "utf-8"
        }, function (err, data) {
          _this14.delFile(installerTxtPath);
          if (err) return _this14.log("\u5220\u9664-\u5B89\u88C5\u5305\u5931\u8D25\uFF1A".concat(err.message));
          var firstLine = data.split("\n")[0].trim();
          _this14.delFile(firstLine);
        });
      });
    }
    // 程序启动后-检测是否存在第三方插件-未被拷贝
  }, {
    key: "loadedCheckPackages",
    value: function () {
      var _loadedCheckPackages = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee15() {
        var fs, path, resourcesPath, packagesDir;
        return _regenerator().w(function (_context15) {
          while (1) switch (_context15.n) {
            case 0:
              fs = require("fs");
              path = require("path");
              resourcesPath = process.resourcesPath;
              packagesDir = path.join(resourcesPath, "packages");
              if (!fs.existsSync(packagesDir)) {
                _context15.n = 1;
                break;
              }
              _context15.n = 1;
              return this.upPackages(packagesDir);
            case 1:
              return _context15.a(2);
          }
        }, _callee15, this);
      }));
      function loadedCheckPackages() {
        return _loadedCheckPackages.apply(this, arguments);
      }
      return loadedCheckPackages;
    }()
  }]);
}(PluginUpdate); // 应用加载-删除升级残留
window.onload = function () {
  var remove = new RemoveTemp();
  remove.loadedCheckPackages();
  remove.loadedDelDir();
  remove.loadedDelInstaller();
};
window.PluginUpdate = PluginUpdate;
