"use strict";

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); }
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports["default"] = void 0;
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
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 _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 _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); }
function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator["return"] && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, "catch": function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; }
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 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); }); }; }
// 删除文件
var deleteFile = function deleteFile(filePath) {
  return new Promise(function (resolve) {
    var fs = require("fs");
    if (!fs.existsSync(filePath)) {
      resolve({
        success: false,
        msg: "\u6587\u4EF6\u4E0D\u5B58\u5728 ".concat(filePath)
      });
      return;
    }
    fs.unlink(filePath, function (err) {
      if (err) {
        resolve({
          success: false,
          msg: "\u5220\u9664\u5931\u8D25".concat(err.message, " ").concat(filePath)
        });
        return;
      }
      resolve({
        success: true,
        msg: "\u5220\u9664\u6210\u529F ".concat(filePath)
      });
    });
  });
};
// 删除文件夹
var deleteFolder = function deleteFolder(folderPath) {
  return new Promise(function (resolve) {
    var fs = require("fs");
    if (!fs.existsSync(folderPath)) {
      resolve({
        success: false,
        msg: "\u6587\u4EF6\u5939\u4E0D\u5B58\u5728 ".concat(folderPath)
      });
      return;
    }
    var _require = require("child_process"),
      exec = _require.exec;
    // 根据操作系统选择不同的命令
    var command = process.platform === "win32" ? "rd /s /q \"".concat(folderPath, "\"") : "sudo rm -rf \"".concat(folderPath, "\"");
    exec(command, {
      windowsHide: true,
      timeout: 20000
    }, function (error) {
      if (error) {
        resolve({
          success: false,
          msg: "\u5220\u9664\u5931\u8D25 ".concat(folderPath)
        });
      } else {
        resolve({
          success: true,
          msg: "\u5220\u9664\u6210\u529F ".concat(folderPath)
        });
      }
    });
  });
};
// 删除升级残留
var delUpgradeResidue = /*#__PURE__*/function () {
  var _ref = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee() {
    var data, list, _iterator, _step, dir, res;
    return _regeneratorRuntime().wrap(function _callee$(_context) {
      while (1) switch (_context.prev = _context.next) {
        case 0:
          _context.prev = 0;
          data = localStorage.getItem("UP_DEL_DIR_LIST") || "[]";
          localStorage.removeItem("UP_DEL_DIR_LIST");
          list = JSON.parse(data);
          if (!(list.length === 0)) {
            _context.next = 6;
            break;
          }
          return _context.abrupt("return");
        case 6:
          _iterator = _createForOfIteratorHelper(list);
          _context.prev = 7;
          _iterator.s();
        case 9:
          if ((_step = _iterator.n()).done) {
            _context.next = 17;
            break;
          }
          dir = _step.value;
          _context.next = 13;
          return deleteFolder(dir);
        case 13:
          res = _context.sent;
          // 会等待上一个结束
          ktLog.i("\u5220\u9664\u5347\u7EA7\u6B8B\u7559\u5931\u8D25:".concat(JSON.stringify(res)));
        case 15:
          _context.next = 9;
          break;
        case 17:
          _context.next = 22;
          break;
        case 19:
          _context.prev = 19;
          _context.t0 = _context["catch"](7);
          _iterator.e(_context.t0);
        case 22:
          _context.prev = 22;
          _iterator.f();
          return _context.finish(22);
        case 25:
          _context.next = 30;
          break;
        case 27:
          _context.prev = 27;
          _context.t1 = _context["catch"](0);
          ktLog.i("\u5220\u9664\u5347\u7EA7\u6B8B\u7559\u5931\u8D25:".concat(_context.t1.message));
        case 30:
        case "end":
          return _context.stop();
      }
    }, _callee, null, [[0, 27], [7, 19, 22, 25]]);
  }));
  return function delUpgradeResidue() {
    return _ref.apply(this, arguments);
  };
}();
// 删除安装包
var deleteInstaller = function deleteInstaller() {
  return new Promise(function (resolve) {
    var _electron$remote;
    var fs = require("fs");
    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 appDataPath = app.getPath("appData");
    var installerTxtPath = path.join(appDataPath, "./cpcss_installer.txt");
    if (!fs.existsSync(installerTxtPath)) return;
    fs.readFile(installerTxtPath, {
      encoding: "utf-8"
    }, function (err, data) {
      deleteFile(installerTxtPath);
      if (err) {
        ktLog.i("\u5220\u9664\u5B89\u88C5\u5305\u5931\u8D25\uFF1A".concat(err.message));
        return;
      }
      // 获取第一行文本
      var firstLine = data.split("\n")[0].trim();
      deleteFile(firstLine).then(function (res) {
        ktLog.i("\u5220\u9664\u5B89\u88C5\u5305\u5B8C\u6210:".concat(JSON.stringify(res)));
      });
    });
  });
};

// 应用加载-删除升级残留
window.onload = function () {
  setTimeout(/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee2() {
    return _regeneratorRuntime().wrap(function _callee2$(_context2) {
      while (1) switch (_context2.prev = _context2.next) {
        case 0:
          _context2.next = 2;
          return deleteInstaller();
        case 2:
          _context2.next = 4;
          return delUpgradeResidue();
        case 4:
        case "end":
          return _context2.stop();
      }
    }, _callee2);
  })), 5000);
};
var PluginUpdate = exports["default"] = /*#__PURE__*/function () {
  function PluginUpdate() {
    var _ktLog, _electron$remote2;
    var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
    _classCallCheck(this, PluginUpdate);
    _defineProperty(this, "tempDir", "");
    _defineProperty(this, "tempDirName", "temp_dir");
    _defineProperty(this, "downloadJsonPath", "");
    _defineProperty(this, "baseDirUrl", "");
    _defineProperty(this, "hdBaseUrl", "");
    _defineProperty(this, "zipType", "1");
    // 增量包 1  第三方插件 2
    _defineProperty(this, "installType", "0");
    // 3 非标包 4 硬件库
    _defineProperty(this, "version", "");
    // 升级包版本
    _defineProperty(this, "unZipPath", "");
    // 解压后的资源文件夹
    _defineProperty(this, "zipName", "");
    // 压缩包名
    _defineProperty(this, "isReboot", false);
    // 是否自动重启
    _defineProperty(this, "isInstaller", false);
    _defineProperty(this, "onProgress", function () {});
    _defineProperty(this, "delDirList", []);
    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";
    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;
    var userDataPath = app.getPath("userData");
    this.baseDirUrl = path.join(path.dirname(userDataPath), "".concat(appCode, "_RESOURCE"));
    this.tempDir = path.join(this.baseDirUrl, this.tempDirName);
    this.downloadJsonPath = path.join(this.tempDir, "download.json");
    if (process.platform === "linux") {
      this.hdBaseUrl = process.resourcesPath;
    } else {
      this.hdBaseUrl = this.getAppDir();
    }
  }
  return _createClass(PluginUpdate, [{
    key: "getAppDir",
    value: function getAppDir() {
      var _electron$remote3;
      var path = require("path");
      var electron = require("electron");
      var app = ((_electron$remote3 = electron.remote) === null || _electron$remote3 === void 0 ? void 0 : _electron$remote3.app) || electron.app;
      if (app.isPackaged && process.platform === "win32") {
        var exePath = app.getPath("exe");
        return path.dirname(exePath);
      }
      return process.cwd();
    }
    // 收到升级指令
  }, {
    key: "update",
    value: function () {
      var _update = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee3() {
        var data,
          fs,
          path,
          newTerminalAppResUrl,
          newTerminalAppVersion,
          urlObj,
          filename,
          unZipPath,
          filePath,
          appJson,
          _args3 = arguments;
        return _regeneratorRuntime().wrap(function _callee3$(_context3) {
          while (1) switch (_context3.prev = _context3.next) {
            case 0:
              data = _args3.length > 0 && _args3[0] !== undefined ? _args3[0] : {};
              _context3.prev = 1;
              fs = require("fs");
              path = require("path");
              this.installType = data.installType + "";

              // 将下载地址中的IP替换为车场服务器IP
              if (this.serverIp) data.newTerminalAppResUrl = data.newTerminalAppResUrl.replace(/(\d{1,3}\.){3}\d{1,3}/, this.serverIp);
              _context3.next = 8;
              return this.getUpdateJson(data.newTerminalAppResUrl);
            case 8:
              newTerminalAppResUrl = data.newTerminalAppResUrl, newTerminalAppVersion = data.newTerminalAppVersion;
              this.version = newTerminalAppVersion;
              this.log("Update start\uFF1A".concat(newTerminalAppResUrl));
              // 压缩资源包下载 - CPCSS_RESOURCE
              if (!(newTerminalAppResUrl.indexOf(".zip") > -1)) {
                _context3.next = 34;
                break;
              }
              urlObj = new URL(newTerminalAppResUrl);
              filename = urlObj.pathname.split("/").pop();
              this.zipName = filename.replace(".zip", "").trim();
              // 解压版本文件夹
              unZipPath = this.unZipPath = path.join(this.baseDirUrl, this.zipName); // 创建临时下载文件夹
              if (!fs.existsSync(this.tempDir)) fs.mkdirSync(this.tempDir, {
                recursive: true
              });
              filePath = path.join(this.tempDir, filename);
              _context3.next = 20;
              return this.download({
                url: newTerminalAppResUrl,
                filename: filename,
                filePath: filePath,
                updateData: data
              });
            case 20:
              _context3.next = 22;
              return this.unzip({
                zipPath: filePath,
                targetDir: unZipPath,
                overWrite: true
              });
            case 22:
              _context3.next = 24;
              return this.delDir(this.tempDir);
            case 24:
              _context3.next = 26;
              return this.runScript();
            case 26:
              appJson = path.join(process.resourcesPath, "app.json"); // 删除app.json-新方案不需要-不删除新旧版本来回切换会出现问题
              if (this.zipType === "1" && fs.existsSync(appJson)) fs.unlinkSync(appJson);
              _context3.next = 30;
              return this.delDir(this.unZipPath);
            case 30:
              this.isInstaller = false;
              this.log("Update completed");
              if (this.isReboot) this.reboot();
              return _context3.abrupt("return", Promise.resolve());
            case 34:
              return _context3.abrupt("return", this.updateInstaller(data));
            case 37:
              _context3.prev = 37;
              _context3.t0 = _context3["catch"](1);
              this.log("Update failed:".concat(_context3.t0));
              _context3.next = 42;
              return this.delDir(this.tempDir);
            case 42:
              _context3.next = 44;
              return this.delDir(this.unZipPath);
            case 44:
              return _context3.abrupt("return", Promise.reject(_context3.t0));
            case 45:
            case "end":
              return _context3.stop();
          }
        }, _callee3, this, [[1, 37]]);
      }));
      function update() {
        return _update.apply(this, arguments);
      }
      return update;
    }() // 本地更新  // 1增量包(默认)  2第三方插件 3硬件库 4非标包
  }, {
    key: "localeUpdate",
    value: function () {
      var _localeUpdate = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee4(filePath) {
        var zipType,
          fs,
          path,
          unZipPath,
          asarPath,
          secondDir,
          secondZipPath,
          appJson,
          _args4 = arguments;
        return _regeneratorRuntime().wrap(function _callee4$(_context4) {
          while (1) switch (_context4.prev = _context4.next) {
            case 0:
              zipType = _args4.length > 1 && _args4[1] !== undefined ? _args4[1] : "1";
              _context4.prev = 1;
              this.log("Update start\uFF1A".concat(filePath));
              this.zipType = zipType;
              fs = require("fs");
              path = require("path");
              if (fs.existsSync(filePath)) {
                _context4.next = 8;
                break;
              }
              return _context4.abrupt("return", Promise.reject(new Error("Not Found ".concat(filePath))));
            case 8:
              // 压缩包名称、解压缩文件夹
              this.zipName = path.basename(filePath).replace(".zip", "").trim();
              unZipPath = this.unZipPath = path.join(this.baseDirUrl, this.zipName);
              _context4.next = 12;
              return this.unzip({
                zipPath: filePath,
                targetDir: this.unZipPath
              });
            case 12:
              // 上传运维的增量包是二次压缩包
              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))) {
                _context4.next = 20;
                break;
              }
              this.unZipPath = path.join(this.baseDirUrl, "".concat(this.zipName, "_second"));
              this.log("二次解压");
              _context4.next = 20;
              return this.unzip({
                zipPath: secondZipPath,
                targetDir: this.unZipPath
              });
            case 20:
              _context4.next = 22;
              return this.runScript();
            case 22:
              appJson = path.join(process.resourcesPath, "app.json"); // 删除app.json-新方案不需要-不删除新旧版本来回切换会出现问题
              if (this.zipType === "1" && fs.existsSync(appJson)) fs.unlinkSync(appJson);
              _context4.next = 26;
              return this.delDir(unZipPath);
            case 26:
              _context4.next = 28;
              return this.delDir(this.unZipPath);
            case 28:
              this.log("Update completed");
              if (this.isReboot) this.reboot();
              _context4.next = 38;
              break;
            case 32:
              _context4.prev = 32;
              _context4.t0 = _context4["catch"](1);
              this.log("localeUpdate failed:".concat(_context4.t0));
              _context4.next = 37;
              return this.delDir(this.unZipPath);
            case 37:
              return _context4.abrupt("return", Promise.reject(_context4.t0));
            case 38:
            case "end":
              return _context4.stop();
          }
        }, _callee4, this, [[1, 32]]);
      }));
      function localeUpdate(_x) {
        return _localeUpdate.apply(this, arguments);
      }
      return localeUpdate;
    }() // 读取更新配置
  }, {
    key: "getUpdateJson",
    value: function () {
      var _getUpdateJson = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee5(url) {
        var res, _yield$res$json, zipType;
        return _regeneratorRuntime().wrap(function _callee5$(_context5) {
          while (1) switch (_context5.prev = _context5.next) {
            case 0:
              _context5.prev = 0;
              url = url.substring(0, url.lastIndexOf("/"));
              url = "".concat(url, "/update.json");
              this.log("Get ".concat(url));
              _context5.next = 6;
              return fetch(url);
            case 6:
              res = _context5.sent;
              _context5.next = 9;
              return res.json();
            case 9:
              _yield$res$json = _context5.sent;
              zipType = _yield$res$json.zipType;
              this.zipType = zipType || "1";
              return _context5.abrupt("return", Promise.resolve());
            case 15:
              _context5.prev = 15;
              _context5.t0 = _context5["catch"](0);
              this.log("Not found update.json");
              return _context5.abrupt("return", Promise.resolve());
            case 19:
            case "end":
              return _context5.stop();
          }
        }, _callee5, this, [[0, 15]]);
      }));
      function getUpdateJson(_x2) {
        return _getUpdateJson.apply(this, arguments);
      }
      return getUpdateJson;
    }() // 下载
  }, {
    key: "download",
    value: function download(_ref3) {
      var _this = this;
      var url = _ref3.url,
        filePath = _ref3.filePath,
        fileName = _ref3.fileName,
        updateData = _ref3.updateData;
      return new Promise(function (resolve, reject) {
        try {
          _this.log("Download: ".concat(url, " -> ").concat(filePath));
          // 检查文件是否已经存在，如果存在则获取文件大小
          var downloadedBytes = 0;
          var fs = require("fs");
          var path = require("path");
          if (fs.existsSync(filePath)) {
            downloadedBytes = fs.statSync(filePath).size;
          }

          // 设置请求头
          var headers = {};
          var fileTotalLength = 0;
          // 获取下载进度
          if (fs.existsSync(_this.downloadJsonPath)) {
            var str = fs.readFileSync(_this.downloadJsonPath, {
              encoding: "utf-8"
            });
            if (str) {
              var data = JSON.parse(str);
              fileTotalLength = data.fileName === fileName ? data.totalLength : 0;
            }
          }
          if (fileTotalLength > 0 && fileTotalLength === downloadedBytes) {
            _this.log("文件已存在");
            resolve();
            return;
          }
          if (downloadedBytes > 0 && (downloadedBytes < fileTotalLength || fileTotalLength === 0)) {
            headers["Range"] = "bytes=".concat(downloadedBytes, "-");
          }
          var http = require("http");
          var https = require("https");
          // 选择合适的模块（http 或 https）
          var lib = url.startsWith("https") ? https : http;

          // 发送请求
          var request = lib.get(url, {
            headers: headers
          }, function (response) {
            if (response.statusCode === 206 || response.statusCode === 200) {
              var writer = fs.createWriteStream(filePath, {
                flags: "a"
              }); // 以追加模式打开文件
              var totalLength = parseInt(response.headers["content-length"], 10) + downloadedBytes;
              if (fileTotalLength === 0) {
                fs.writeFileSync(_this.downloadJsonPath, JSON.stringify(_objectSpread(_objectSpread({}, updateData), {}, {
                  url: url,
                  fileName: fileName,
                  totalLen: totalLength
                })), {
                  encoding: "utf-8"
                });
              }
              // 创建一个 PassThrough 流来处理数据
              var _require2 = require("stream"),
                PassThrough = _require2.PassThrough;
              var passThroughStream = new PassThrough();

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

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

              // 将 PassThrough 流管道到文件写入流
              passThroughStream.pipe(writer);
              writer.on("finish", function () {
                _this.log("Download completed.");
                resolve();
              });
              writer.on("error", function (err) {
                _this.log("Download failed: ".concat(err.message));
                reject(err);
              });
              passThroughStream.on("error", function (err) {
                _this.log("Download failed: ".concat(err.message));
                reject(err);
              });
            } else {
              _this.log("Server responded with status code: ".concat(response.statusCode));
              reject(new Error("Server responded with status code: ".concat(response.statusCode)));
            }
          }).on("error", function (error) {
            _this.log("Download failed: ".concat(error.message));
            reject(error);
          });

          // 超时处理
          request.setTimeout(30000, function () {
            request.destroy(new Error("Request timeout"));
          });
        } catch (error) {
          _this.log("Download failed: ".concat(error.message));
          reject(error);
        }
      });
    }
    // 解压
  }, {
    key: "unzip",
    value: function () {
      var _unzip = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee6(_ref4) {
        var _this2 = this;
        var zipPath, targetDir, _ref4$overWrite, overWrite, fs, _require3, exec, command, AdmZip, zip;
        return _regeneratorRuntime().wrap(function _callee6$(_context6) {
          while (1) switch (_context6.prev = _context6.next) {
            case 0:
              zipPath = _ref4.zipPath, targetDir = _ref4.targetDir, _ref4$overWrite = _ref4.overWrite, overWrite = _ref4$overWrite === void 0 ? true : _ref4$overWrite;
              _context6.prev = 1;
              if (!(process.platform === "linux")) {
                _context6.next = 9;
                break;
              }
              fs = require("fs");
              if (!fs.existsSync(targetDir)) fs.mkdirSync(targetDir, {
                recursive: true
              });
              _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.abrupt("return", new Promise(function (resolve, reject) {
                exec(command, function (error, stdout, stderr) {
                  if (error) {
                    _this2.log("Unzip failed: ".concat(stderr));
                    reject(error);
                  } else {
                    _this2.log("Unzip completed.");
                    resolve();
                  }
                });
              }));
            case 9:
              AdmZip = require("adm-zip");
              this.log("Unzip ".concat(zipPath, " -> ").concat(targetDir));
              zip = new AdmZip(zipPath);
              _context6.next = 14;
              return zip.extractAllTo(targetDir, overWrite);
            case 14:
              this.log("Unzip completed.");
              _context6.next = 25;
              break;
            case 17:
              _context6.prev = 17;
              _context6.t0 = _context6["catch"](1);
              this.log("Unzip failed:".concat(_context6.t0));
              _context6.next = 22;
              return this.delDir(zipPath);
            case 22:
              _context6.next = 24;
              return this.delDir(targetDir);
            case 24:
              return _context6.abrupt("return", Promise.reject(_context6.t0));
            case 25:
            case "end":
              return _context6.stop();
          }
        }, _callee6, this, [[1, 17]]);
      }));
      function unzip(_x3) {
        return _unzip.apply(this, arguments);
      }
      return unzip;
    }() // 删除文件夹
  }, {
    key: "delDir",
    value: function delDir(folderPath) {
      var _this3 = this;
      return new Promise(function (resolve, reject) {
        var fs = require("fs");
        if (!fs.existsSync(folderPath)) return resolve();
        _this3.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) {
            _this3.log("Error deleting directory: ".concat(error.message));
            _this3.delDirFailed(folderPath);
            return resolve();
          }
          if (stderr) {
            _this3.log("Error deleting directory: ".concat(stderr));
            _this3.delDirFailed(folderPath);
            return resolve();
          }
          _this3.log("Del completed");
          resolve();
        });
      });
    }
    // 文件夹删除失败
  }, {
    key: "delDirFailed",
    value: function delDirFailed(dir) {
      this.delDirList.push(dir);
      localStorage.setItem("UP_DEL_DIR_LIST", JSON.stringify(this.delDirList));
    }
    // 更新安装包
  }, {
    key: "updateInstaller",
    value: function updateInstaller(data) {
      var _this4 = this;
      return new Promise(function (resolve, reject) {
        var _require5 = require("electron"),
          ipcRenderer = _require5.ipcRenderer;
        // 升级错误
        ipcRenderer.on("update-error", function (err) {
          _this4.log("update-error ".concat(err));
          reject(err);
        });
        // 未检测到可升级版本
        ipcRenderer.on("update-not-available", function (e, newVersion) {
          _this4.log("update-not-available");
          reject(new Error("update-not-available"));
        });
        // 检测允许升级 -
        ipcRenderer.on("update-available", function (e, newVersion) {
          // 确认下载
          if (newVersion) {
            _this4.log("update-available：confirmDownload");
            var fs = require("fs");
            // 创建临时下载文件夹
            if (!fs.existsSync(_this4.tempDir)) fs.mkdirSync(_this4.tempDir, {
              recursive: true
            });
            fs.writeFileSync(_this4.downloadJsonPath, JSON.stringify(data), {
              encoding: "utf-8"
            });
            ipcRenderer.send("confirmDownload");
          }
        });
        // 下载进度
        ipcRenderer.on("download-progress", function (e, val) {
          var percent = val.percent.toFixed(0);
          _this4.onProgress(percent);
        });
        // 下载完成
        ipcRenderer.on("update-downloaded", /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee7() {
          return _regeneratorRuntime().wrap(function _callee7$(_context7) {
            while (1) switch (_context7.prev = _context7.next) {
              case 0:
                _this4.log("update-downloaded");
                _context7.next = 3;
                return _this4.delDir(_this4.tempDir);
              case 3:
                _this4.isInstaller = true;
                resolve();
                if (_this4.isReboot) ipcRenderer.send("confirmUpdate");
              case 6:
              case "end":
                return _context7.stop();
            }
          }, _callee7);
        })));
        var appExt = {
          win32: [".exe"],
          linux: [".AppImage", ".deb"]
        };
        if (!appExt[process.platform]) return reject(new Error(process.platform));
        var appExtension = "";
        var _iterator2 = _createForOfIteratorHelper(appExt[process.platform]),
          _step2;
        try {
          for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
            var val = _step2.value;
            if (data.newTerminalAppResUrl.endsWith(val)) {
              appExtension = val;
            }
          }
        } catch (err) {
          _iterator2.e(err);
        } finally {
          _iterator2.f();
        }
        if (!appExtension) {
          _this4.log("".concat(data.newTerminalAppResUrl, " invalid"));
          return reject(new Error("".concat(data.newTerminalAppResUrl, " invalid")));
        }
        _this4.log("update installer ".concat(data.newTerminalAppResUrl));
        if (process.platform == "linux" && data.newTerminalAppResUrl.includes(".deb")) {
          _this4.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
        });
      });
    }
    /** linux升级更新Deb包 */
  }, {
    key: "linuxUpdateDeb",
    value: function linuxUpdateDeb(data) {
      var _this5 = this;
      var electron = require("electron");
      var fs = require("fs");
      var path = require("path");
      var _require6 = require("child_process"),
        exec = _require6.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) {
                  _this5.log("卸载已安装LCD入口取票机deb包错误" + error);
                }
                exec("sudo dpkg -i ".concat(desktopDebPath), (error, stdout, function (stderr) {
                  if (error) {
                    _this5.log("安装新的Deb软件包报错：" + error);
                  }
                  _this5.log("安装新的eb软件包成功，进行设置开机自启动，系统重启");
                  _this5.setDesktopAndReboot(desktopDebPath, name, baseDir);
                }));
              });
            } else {
              exec("sudo dpkg -i ".concat(desktopDebPath), (error, stdout, function (stderr) {
                if (error) {
                  _this5.log("安装Deb软件包报错：" + error);
                }
                _this5.log("安装Deb软件包成功，进行设置开机自启动，删除相关文件，系统重启");
                _this5.setDesktopAndReboot(desktopDebPath, name, baseDir, desktopAppImagePath, autostartDesktop, autostartStartupSh);
              }));
            }
          });
        } catch (e) {
          _this5.log("升级Deb安装包异常：" + e);
        }
      }).stderr.on("data", function (data) {
        // 解析进度信息
        var progressMatch = data.toString().match(/(\d+)%/);
        if (progressMatch) {
          var progress = parseInt(progressMatch[1], 10);
          _this5.onProgress(progress);
        }
      });
    }
    // Deb软件包安装成功，进行设置开机自启动，删除相关文件，系统重启
  }, {
    key: "setDesktopAndReboot",
    value: function setDesktopAndReboot(desktopDebPath, name, baseDir, desktopAppImagePath, autostartDesktop, autostartStartupSh) {
      var _this6 = this;
      var fs = require("fs");
      var _require7 = require("child_process"),
        exec = _require7.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) {
            _this6.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);
            }
          }
          _this6.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 _this7 = this;
      var overwrite = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
      var isFile = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
      var fs = require("fs");
      var _require8 = require("child_process"),
        exec = _require8.exec;
      if (!fs.existsSync(dir)) return Promise.resolve();
      // 确保目标目录存在
      if (!fs.existsSync(targetPath)) {
        fs.mkdirSync(targetPath, {
          recursive: true
        });
      }

      // 构建命令
      var command;
      if (process.platform === "win32") {
        if (isFile) {
          command = "xcopy /Y \"".concat(dir, "\" \"").concat(targetPath, "\"");
          if (!overwrite) {
            command = "xcopy \"".concat(dir, "\" \"").concat(targetPath, "\"");
          }
        } else {
          command = "xcopy /E /I /Y \"".concat(dir, "\" \"").concat(targetPath, "\"");
          if (!overwrite) {
            command = "xcopy /E /I \"".concat(dir, "\" \"").concat(targetPath, "\"");
          }
        }
      } 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 (error) {
            _this7.log("Error copying: ".concat(error.message));
            return reject(error);
          }
          if (stderr) {
            _this7.log("Error copying: ".concat(stderr));
            return reject(new Error(stderr));
          }
          _this7.log("copied successfully.");
          resolve();
        });
      });
    }
    // 读取文件夹
  }, {
    key: "readDirFile",
    value: function () {
      var _readDirFile = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee8(dir) {
        return _regeneratorRuntime().wrap(function _callee8$(_context8) {
          while (1) switch (_context8.prev = _context8.next) {
            case 0:
              return _context8.abrupt("return", 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
                  });
                });
              }));
            case 1:
            case "end":
              return _context8.stop();
          }
        }, _callee8);
      }));
      function readDirFile(_x4) {
        return _readDirFile.apply(this, arguments);
      }
      return readDirFile;
    }() // 拷贝硬件库
  }, {
    key: "copyHdFiles",
    value: function () {
      var _copyHdFiles = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee9(hardwareDir, hardwareTargetDir, filter) {
        var _this8 = this;
        var _yield$this$readDirFi, files, dirList, dirPromises, hdFiles, promises;
        return _regeneratorRuntime().wrap(function _callee9$(_context9) {
          while (1) switch (_context9.prev = _context9.next) {
            case 0:
              _context9.next = 2;
              return this.readDirFile(hardwareDir);
            case 2:
              _yield$this$readDirFi = _context9.sent;
              files = _yield$this$readDirFi.files;
              dirList = _yield$this$readDirFi.dirList;
              dirPromises = dirList.map(function (i) {
                return _this8.copyDirectory(i, hardwareTargetDir, true);
              });
              hdFiles = filter ? filter(files) : files;
              promises = hdFiles.map(function (i) {
                return _this8.copyDirectory(i, hardwareTargetDir, true, true);
              });
              this.log("\u66FF\u6362\u786C\u4EF6\u5E93\uFF1A".concat(JSON.stringify(hdFiles.concat(dirList)), " -> ").concat(hardwareTargetDir));
              return _context9.abrupt("return", Promise.all(promises.concat(dirPromises)));
            case 10:
            case "end":
              return _context9.stop();
          }
        }, _callee9, this);
      }));
      function copyHdFiles(_x5, _x6, _x7) {
        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__*/_regeneratorRuntime().mark(function _callee10() {
        var fs, path, dir, enJsPath, dirName, hdDir, hdTargetDir, _dir, _dirName, _hdTargetDir, regex, linuxDir, targetDir, appPath, asar, _targetDir, _dirName2, _hdDir, _hdTargetDir2;
        return _regeneratorRuntime().wrap(function _callee10$(_context10) {
          while (1) switch (_context10.prev = _context10.next) {
            case 0:
              fs = require("fs");
              path = require("path"); // 非标包
              if (!(this.installType === "3" || this.zipType === "4")) {
                _context10.next = 19;
                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)) {
                _context10.next = 8;
                break;
              }
              return _context10.abrupt("return", Promise.reject(new Error("Not Found ".concat(enJsPath))));
            case 8:
              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))) {
                _context10.next = 15;
                break;
              }
              _context10.next = 15;
              return this.copyHdFiles(hdDir, hdTargetDir);
            case 15:
              _context10.next = 17;
              return this.delDir(path.join(dir, "hardware"));
            case 17:
              this.log("\u66FF\u6362\u975E\u6807\u6587\u4EF6\uFF1A".concat(dir, " -> ").concat(this.baseDirUrl));
              return _context10.abrupt("return", this.copyDirectory(dir, this.baseDirUrl, true));
            case 19:
              if (!(this.installType === "4" || this.zipType === "3")) {
                _context10.next = 35;
                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;
              _context10.t0 = _dirName;
              _context10.next = _context10.t0 === "linux-arm" ? 27 : _context10.t0 === "linux-arm64" ? 29 : _context10.t0 === "linux-x64" ? 31 : 33;
              break;
            case 27:
              regex = /-win|-linux-x86|-linux-arm64|-android|-ohos/g;
              return _context10.abrupt("break", 33);
            case 29:
              regex = /-win|-linux-x86|-linux-arm|-android|-ohos/g;
              return _context10.abrupt("break", 33);
            case 31:
              regex = /-win|-linux-arm64|-linux-arm|-android|-ohos/g;
              return _context10.abrupt("break", 33);
            case 33:
              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 _context10.abrupt("return", this.copyHdFiles(_dir, _hdTargetDir, function (list) {
                return list.filter(function (i) {
                  return !i.match(regex);
                });
              }));
            case 35:
              if (!(this.zipType === "2")) {
                _context10.next = 39;
                break;
              }
              targetDir = path.join(this.baseDirUrl, "./terminal_third_plugins");
              this.log("\u66FF\u6362\u7B2C\u4E09\u65B9\u63D2\u4EF6\uFF1A".concat(this.unZipPath, " -> ").concat(targetDir));
              return _context10.abrupt("return", this.copyDirectory(this.unZipPath, targetDir, true));
            case 39:
              if (!(this.zipType === "1")) {
                _context10.next = 58;
                break;
              }
              appPath = this.unZipPath;
              asar = path.join(appPath, "app.asar");
              if (fs.existsSync(asar)) {
                _context10.next = 44;
                break;
              }
              return _context10.abrupt("return", Promise.reject(new Error("Not Found ".concat(asar))));
            case 44:
              _targetDir = process.resourcesPath;
              if (process.env.NODE_ENV === "development") _targetDir = this.baseDirUrl;
              this.log("\u66FF\u6362\u589E\u91CF\u5305\uFF1A".concat(appPath, " -> ").concat(_targetDir));
              _context10.next = 49;
              return this.copyDirectory(appPath, _targetDir, true);
            case 49:
              // 更新硬件库
              _dirName2 = this.getHdDirName();
              _hdDir = path.join(_targetDir, "hardware");
              _hdTargetDir2 = path.join(this.hdBaseUrl, "hardware/".concat(_dirName2)); // 当前增量包存在硬件库-更新硬件库
              if (!fs.existsSync(_hdDir)) {
                _context10.next = 57;
                break;
              }
              _hdDir = path.join(_hdDir, _dirName2);
              if (process.platform === "linux") {
                // if (!fs.existsSync(hdDir)) {
                //   hdDir = path.join(targetDir, "hardware/linux");
                //   if (!fs.existsSync(hdDir)) hdDir = "";
                // }
                // hdTargetDir = path.join(this.hdBaseUrl, `hardware/${dirName}`);
                // if (!fs.existsSync(hdTargetDir))
                //   hdTargetDir = path.join(this.hdBaseUrl, "hardware/linux");
                //   await this.hdHardWareRelease();
              }

              // linux 下增量包已经拷贝到 resouce 下了，不需要再拷贝硬件库
              if (!(_hdDir && fs.existsSync(_hdDir) && process.platform !== "linux")) {
                _context10.next = 57;
                break;
              }
              return _context10.abrupt("return", this.copyHdFiles(_hdDir, _hdTargetDir2));
            case 57:
              return _context10.abrupt("return", Promise.resolve());
            case 58:
            case "end":
              return _context10.stop();
          }
        }, _callee10, this);
      }));
      function runScript() {
        return _runScript.apply(this, arguments);
      }
      return runScript;
    }() // 释放硬件库进程
  }, {
    key: "hdHardWareRelease",
    value: function hdHardWareRelease() {
      var _this9 = this;
      return new Promise(function (resolve, reject) {
        if (global.mainHdApi && global.mainHdApi.hdHardWareRelease) {
          _this9.log("释放硬件库进程");
          global.mainHdApi.hdHardWareRelease();
          return setTimeout(function () {
            return resolve();
          }, 300);
        }
        resolve();
      });
    }
    // 重启系统、应用
  }, {
    key: "reboot",
    value: function reboot() {
      var _electron$remote4;
      var _require9 = require("child_process"),
        exec = _require9.exec;
      var electron = require("electron");
      var app = ((_electron$remote4 = electron.remote) === null || _electron$remote4 === void 0 ? void 0 : _electron$remote4.app) || electron.app;

      // linux 上直接重启系统
      if (process.platform === "linux") {
        exec("sudo reboot");
      } else {
        if (this.isInstaller) {
          var _require10 = require("electron"),
            ipcRenderer = _require10.ipcRenderer;
          ipcRenderer.send("confirmUpdate");
        } else {
          app.relaunch();
          app.exit(0);
        }
      }
    }
    // 检测是否有未完成的下载任务
  }, {
    key: "checkDownloadTask",
    value: function checkDownloadTask() {
      try {
        var fs = require("fs");
        var path = require("path");
        if (!fs.existsSync(tempDir) || !fs.existsSync(this.downloadJsonPath)) return null;
        var data = fs.readFileSync(this.downloadJsonPath, "utf-8");
        if (!data) return null;
        return JSON.parse(data);
      } catch (err) {
        this.log("\u68C0\u6D4B\u7248\u672C\u662F\u5426\u8FD8\u6709\u672A\u5B8C\u6210\u7684\u4E0B\u8F7D\u4EFB\u52A1\u5931\u8D25\uFF1A".concat(err));
        return null;
      }
    }
  }]);
}();
