Selaa lähdekoodia

处理打包问题

rambo 9 kuukautta sitten
vanhempi
commit
6500b50e67

+ 3 - 1
.gitignore

@@ -9,4 +9,6 @@ data/
 public/electron/
 pnpm-lock.yaml
 __pycache__
-*.pyc
+*.pyc
+build/*
+**/dist/

+ 102 - 43
electron/config/bin.js

@@ -9,19 +9,20 @@ module.exports = {
    */
   dev: {
     frontend: {
-      directory: './frontend',
-      cmd: 'npm',
-      args: ['run', 'dev'],
-      protocol: 'http://',
-      hostname: 'localhost',
+      directory: "./frontend",
+      cmd: "npm",
+      args: ["run", "dev"],
+      protocol: "http://",
+      hostname: "localhost",
       port: 8080,
-      indexPath: 'index.html'
+      indexPath: "index.html",
     },
     electron: {
-      directory: './',
-      cmd: 'electron',
-      args: ['.', '--env=local', '--color=always'],
-    }
+      directory: "./",
+      cmd: "electron",
+      args: [".", "--env=local"],
+      loadingPage: "/public/html/loading.html",
+    },
   },
 
   /**
@@ -30,52 +31,92 @@ module.exports = {
    */
   build: {
     frontend: {
-      directory: './frontend',
-      cmd: 'npm',
-      args: ['run', 'build'],
-    }
+      directory: "./frontend",
+      cmd: "npm",
+      args: ["run", "build"],
+    },
+    go_w: {
+      directory: "./go",
+      cmd: "go",
+      args: ["build", "-o=../build/extraResources/goapp.exe"],
+    },
+    go_m: {
+      directory: "./go",
+      cmd: "go",
+      args: ["build", "-o=../build/extraResources/goapp"],
+    },
+    go_l: {
+      directory: "./go",
+      cmd: "go",
+      args: ["build", "-o=../build/extraResources/goapp"],
+    },
+    python: {
+      directory: "./python",
+      cmd: "python",
+      args: ["./setup.py", "build"],
+    },
   },
 
   /**
    * 移动资源
-   * ee-bin move 
+   * ee-bin move
    */
   move: {
     frontend_dist: {
-      dist: './frontend/dist',
-      target: './public/dist'
-    }
-  },  
+      dist: "./frontend/dist",
+      target: "./public/dist",
+    },
+    go_static: {
+      dist: "./frontend/dist",
+      target: "./go/public/dist",
+    },
+    go_config: {
+      dist: "./go/config",
+      target: "./go/public/config",
+    },
+    go_package: {
+      dist: "./package.json",
+      target: "./go/public/package.json",
+    },
+    go_images: {
+      dist: "./public/images",
+      target: "./go/public/images",
+    },
+    python_dist: {
+      dist: "./python/dist",
+      target: "./build/extraResources/py",
+    },
+  },
 
   /**
    * 预发布模式(prod)
    * ee-bin start
    */
   start: {
-    directory: './',
-    cmd: 'electron',
-    args: ['.', '--env=prod']
+    directory: "./",
+    cmd: "electron",
+    args: [".", "--env=prod"],
   },
 
   /**
    * 加密
-   */  
+   */
   encrypt: {
-    type: 'confusion',
+    type: "confusion",
     files: [
-      'electron/**/*.(js|json)',
-      '!electron/config/encrypt.js',
-      '!electron/config/nodemon.json',
-      '!electron/config/builder.json',
-      '!electron/config/bin.json',
+      "electron/**/*.(js|json)",
+      "!electron/config/encrypt.js",
+      "!electron/config/nodemon.json",
+      "!electron/config/builder.json",
+      "!electron/config/bin.js",
     ],
-    fileExt: ['.js'],
+    fileExt: [".js"],
     confusionOptions: {
-      compact: true,      
+      compact: true,
       stringArray: true,
-      stringArrayEncoding: ['none'],
+      stringArrayEncoding: ["none"],
       deadCodeInjection: false,
-    }
+    },
   },
 
   /**
@@ -84,20 +125,38 @@ module.exports = {
    */
   exec: {
     node_v: {
-      directory: './',
-      cmd: 'node',
-      args: ['-v'],
+      directory: "./",
+      cmd: "node",
+      args: ["-v"],
     },
     npm_v: {
-      directory: './',
-      cmd: 'npm',
-      args: ['-v'],
+      directory: "./",
+      cmd: "npm",
+      args: ["-v"],
+    },
+    // 单独调试,air 实现 go 热重载
+    go: {
+      directory: "./go",
+      cmd: "air",
+      args: ["-c=config/.air.toml"],
+    },
+    // windows 单独调试,air 实现 go 热重载
+    go_w: {
+      directory: "./go",
+      cmd: "air",
+      args: ["-c=config/.air.windows.toml"],
+    },
+    // 单独调试,以基础方式启动 go
+    go2: {
+      directory: "./go",
+      cmd: "go",
+      args: ["run", "./main.go", "--env=dev", "--basedir=../", "--port=7073"],
     },
     python: {
-      directory: './python',
-      cmd: 'python',
-      args: ['./index.py', '--port=7074'],
+      directory: "./python",
+      cmd: "python",
+      args: ["./main.py", "--port=7074"],
       stdio: "inherit", // ignore
     },
-  },   
+  },
 };

+ 3 - 1
electron/config/builder.json

@@ -11,6 +11,8 @@
     "!frontend/",
     "!run/",
     "!logs/",
+    "!go/",
+    "!python/",
     "!data/"
   ],
   "extraResources": {
@@ -50,7 +52,7 @@
     ]
   },
   "linux": {
-    "icon": "build/icons/icon.icns",
+    "icon": "build/icons",
     "artifactName": "${productName}-${os}-${version}-${arch}.${ext}",
     "target": [
       "deb"

+ 52 - 48
electron/config/config.default.js

@@ -6,7 +6,6 @@ const path = require('path');
  * 默认配置
  */
 module.exports = (appInfo) => {
-
   const config = {};
 
   /**
@@ -23,7 +22,7 @@ module.exports = (appInfo) => {
    * 主窗口
    */
   config.windowsOption = {
-    title: 'EE框架',
+    title: "EE框架",
     width: 980,
     height: 650,
     minWidth: 400,
@@ -36,30 +35,30 @@ module.exports = (appInfo) => {
     },
     frame: true,
     show: false,
-    icon: path.join(appInfo.home, 'public', 'images', 'logo-32.png'),
+    icon: path.join(appInfo.home, "public", "images", "logo-32.png"),
   };
 
   /**
    * ee框架日志
    */
   config.logger = {
-    encoding: 'utf8',
-    level: 'INFO',
+    encoding: "utf8",
+    level: "INFO",
     outputJSON: false,
     buffer: true,
     enablePerformanceTimer: false,
-    rotator: 'day',
-    appLogName: 'ee.log',
-    coreLogName: 'ee-core.log',
-    errorLogName: 'ee-error.log'
-  }
+    rotator: "day",
+    appLogName: "ee.log",
+    coreLogName: "ee-core.log",
+    errorLogName: "ee-error.log",
+  };
 
   /**
    * 远程模式-web地址
    */
   config.remoteUrl = {
     enable: false,
-    url: 'http://electron-egg.kaka996.com/'
+    url: "http://electron-egg.kaka996.com/",
   };
 
   /**
@@ -77,9 +76,29 @@ module.exports = (appInfo) => {
     cors: {
       origin: true,
     },
-    channel: 'c1'
+    channel: "c1",
+  };
+  /**
+   * Cross-language service
+   * 跨语言服务
+   * 例如:执行go的二进制程序,默认目录为 ./extraResources/
+   */
+  config.cross = {
+    go: {
+      enable: false,
+      name: "goapp",
+      args: ["--port=7073"],
+      appExit: true,
+    },
+    python: {
+      enable: false,
+      name: "pyapp",
+      cmd: "./py/pyapp",
+      directory: "./py",
+      args: ["--port=7074"],
+      appExit: true,
+    },
   };
-
   /**
    * 内置http服务
    */
@@ -87,41 +106,39 @@ module.exports = (appInfo) => {
     enable: false,
     https: {
       enable: false,
-      key: '/public/ssl/localhost+1.key',
-      cert: '/public/ssl/localhost+1.pem'
+      key: "/public/ssl/localhost+1.key",
+      cert: "/public/ssl/localhost+1.pem",
     },
-    host: '127.0.0.1',
+    host: "127.0.0.1",
     port: 7071,
     cors: {
-      origin: "*"
+      origin: "*",
     },
     body: {
       multipart: true,
       formidable: {
-        keepExtensions: true
-      }
+        keepExtensions: true,
+      },
     },
     filterRequest: {
-      uris: [
-        'favicon.ico'
-      ],
-      returnData: ''
-    }
+      uris: ["favicon.ico"],
+      returnData: "",
+    },
   };
 
   /**
    * 主进程
    */
   config.mainServer = {
-    protocol: 'file://',
-    indexPath: '/public/dist/index.html',
+    protocol: "file://",
+    indexPath: "/public/dist/index.html",
   };
 
   /**
    * 硬件加速
    */
   config.hardGpu = {
-    enable: true
+    enable: true,
   };
 
   /**
@@ -137,7 +154,7 @@ module.exports = (appInfo) => {
    * jobs
    */
   config.jobs = {
-    messageLog: true
+    messageLog: true,
   };
 
   /**
@@ -149,16 +166,16 @@ module.exports = (appInfo) => {
     },
     tray: {
       enable: true,
-      title: 'EE程序',
-      icon: '/public/images/tray.png'
+      title: "EE程序",
+      icon: "/public/images/tray.png",
     },
     security: {
       enable: true,
     },
     awaken: {
       enable: true,
-      protocol: 'ee',
-      args: []
+      protocol: "ee",
+      args: [],
     },
     autoUpdater: {
       enable: true,
@@ -166,26 +183,13 @@ module.exports = (appInfo) => {
       macOS: false,
       linux: false,
       options: {
-        provider: 'generic',
-        url: 'http://kodo.qiniu.com/'
+        provider: "generic",
+        url: "http://kodo.qiniu.com/",
       },
       force: false,
-    }
-  };
-  config.cross = {
-    python: {
-      enable: false,
-      // 程序名
-      name: "pyapp",
-      // 可执行程序路径
-      cmd: "./py/pyapp",
-      // 可执行程序目录
-      directory: "./py",
-      args: ["--port=7074"],
-      appExit: true,
     },
   };
   return {
-    ...config
+    ...config,
   };
 }

+ 23 - 16
electron/config/config.local.js

@@ -10,41 +10,48 @@ module.exports = (appInfo) => {
    * 开发者工具
    */
   config.openDevTools = {
-    mode: 'undocked'
+    mode: "undocked",
   };
 
   /**
    * 应用程序顶部菜单
    */
   config.openAppMenu = true;
-
   /**
-   * jobs
+   * Cross-language service
+   * 跨语言服务
+   * 如果有cmd参数,则执行该命令且需要指定 directory
    */
-  config.jobs = {
-    messageLog: true
-  };
   config.cross = {
-    python: {
+    go: {
       // 应用运行时启动
       enable: false,
       // 程序名
+      name: "goapp",
+      // 可执行程序
+      cmd: "go",
+      // 程序目录
+      directory: "./go",
+      args: ["run", "./main.go", "--env=dev", "--basedir=../", "--port=7073"],
+      appExit: true,
+    },
+    python: {
+      enable: false,
       name: "pyapp",
-      // 可执行程序路径,或本机的可执行命令
-      // 如果有cmd参数,则执行该命令且需要指定 directory
       cmd: "python",
-      // 程序目录,如python代码所在目录
       directory: "./python",
-      // 可执行程序参数,如果配置中的端口被占用,则框架会随机生成一个。
-      args: ["./index.py", "--port=7074"],
-      // 可能python web stdio与node.js stdio有冲突,忽略io。
-      // 如果想要查看控制台输出,请单独启动服务 npm run dev-python
+      args: ["./main.py", "--port=7074"],
       stdio: "ignore",
-      // 程序退出时,是否退出electron应用
       appExit: true,
     },
   };
+  /**
+   * jobs
+   */
+  config.jobs = {
+    messageLog: true,
+  };
   return {
-    ...config
+    ...config,
   };
 };

+ 99 - 0
electron/controller/cross.js

@@ -0,0 +1,99 @@
+"use strict";
+
+const { Controller } = require("ee-core");
+const Cross = require("ee-core/cross");
+const Log = require("ee-core/log");
+const HttpClient = require("ee-core/httpclient");
+const Services = require("ee-core/services");
+
+/**
+ * Cross
+ * @class
+ */
+class CrossController extends Controller {
+  constructor(ctx) {
+    super(ctx);
+  }
+
+  /**
+   * View process service information
+   */
+  info() {
+    const pids = Cross.getPids();
+    Log.info("cross pids:", pids);
+
+    let num = 1;
+    pids.forEach((pid) => {
+      let entity = Cross.getProc(pid);
+      Log.info(`server-${num} name:${entity.name}`);
+      Log.info(`server-${num} config:`, entity.config);
+      num++;
+    });
+
+    return "hello electron-egg";
+  }
+
+  /**
+   * Get service url
+   */
+  async getUrl(args) {
+    const { name } = args;
+    const serverUrl = Cross.getUrl(name);
+    return serverUrl;
+  }
+
+  /**
+   * kill service
+   * By default (modifiable), killing the process will exit the electron application.
+   */
+  async killServer(args) {
+    const { type, name } = args;
+    if (type == "all") {
+      Cross.killAll();
+    } else {
+      Cross.killByName(name);
+    }
+
+    return;
+  }
+
+  /**
+   * create service
+   */
+  async createServer(args) {
+    const { program } = args;
+    if (program == "go") {
+      Services.get("cross").createGoServer();
+    } else if (program == "java") {
+      Services.get("cross").createJavaServer();
+    } else if (program == "python") {
+      Services.get("cross").createPythonServer();
+    }
+
+    return;
+  }
+
+  /**
+   * Access the api for the cross service
+   */
+  async requestApi(args) {
+    const { name, urlPath, params } = args;
+    const hc = new HttpClient();
+    const serverUrl = Cross.getUrl(name);
+    console.log("Server Url:", serverUrl);
+
+    const apiHello = serverUrl + urlPath;
+    const options = {
+      method: "GET",
+      data: params || {},
+      dataType: "json",
+      timeout: 1000,
+    };
+    const result = await hc.request(apiHello, options);
+
+    return result.data;
+  }
+}
+
+CrossController.toString = () => "[class CrossController]";
+module.exports = CrossController;

+ 11 - 7
electron/preload/index.js

@@ -1,14 +1,18 @@
 /*************************************************
  ** preload为预加载模块,该文件将会在程序启动时加载 **
  *************************************************/
-const Addon = require('ee-core/addon');
+const Addon = require("ee-core/addon");
+const Services = require("ee-core/services");
 
 /**
-* 预加载模块入口
-*/
+ * 预加载模块入口
+ */
 module.exports = async () => {
+  // 已实现的功能模块,可选择性使用和修改
+  Addon.get("tray").create();
+  Addon.get("security").create();
+  Addon.get("awaken").create();
+  Addon.get("autoUpdater").create();
 
-  // 示例功能模块,可选择性使用和修改
-  Addon.get('tray').create();
-  Addon.get('security').create();
-}
+  Services.get("cross").createPythonServer();
+};

+ 116 - 0
electron/service/cross.js

@@ -0,0 +1,116 @@
+"use strict";
+
+const { Service } = require("ee-core");
+const Cross = require("ee-core/cross");
+const Log = require("ee-core/log");
+const Ps = require("ee-core/ps");
+const path = require("path");
+const Is = require("ee-core/utils/is");
+
+/**
+ * cross(service层为单例)
+ * @class
+ */
+class CrossService extends Service {
+  constructor(ctx) {
+    super(ctx);
+  }
+
+  /**
+   * create go service
+   * In the default configuration, services can be started with applications.
+   * Developers can turn off the configuration and create it manually.
+   */
+  async createGoServer() {
+    // method 1: Use the default Settings
+    //const entity = await Cross.run(serviceName);
+
+    // method 2: Use custom configuration
+    const serviceName = "go";
+    const opt = {
+      name: "goapp",
+      cmd: path.join(Ps.getExtraResourcesDir(), "goapp"),
+      directory: Ps.getExtraResourcesDir(),
+      args: ["--port=7073"],
+      appExit: true,
+    };
+    const entity = await Cross.run(serviceName, opt);
+    Log.info("server name:", entity.name);
+    Log.info("server config:", entity.config);
+    Log.info("server url:", entity.getUrl());
+
+    return;
+  }
+
+  /**
+   * create java server
+   */
+  async createJavaServer() {
+    const serviceName = "java";
+    const jarPath = path.join(Ps.getExtraResourcesDir(), "java-app.jar");
+    const opt = {
+      name: "javaapp",
+      cmd: path.join(Ps.getExtraResourcesDir(), "jre1.8.0_201/bin/javaw.exe"),
+      directory: Ps.getExtraResourcesDir(),
+      args: [
+        "-jar",
+        "-server",
+        "-Xms512M",
+        "-Xmx512M",
+        "-Xss512k",
+        "-Dspring.profiles.active=prod",
+        `-Dserver.port=18080`,
+        `-Dlogging.file.path=${Ps.getLogDir()}`,
+        `${jarPath}`,
+      ],
+      appExit: false,
+    };
+    if (Is.macOS()) {
+      // Setup Java program
+      opt.cmd = path.join(
+        Ps.getExtraResourcesDir(),
+        "jre1.8.0_201.jre/Contents/Home/bin/java"
+      );
+    }
+    if (Is.linux()) {
+      // Setup Java program
+    }
+
+    const entity = await Cross.run(serviceName, opt);
+    Log.info("server name:", entity.name);
+    Log.info("server config:", entity.config);
+    Log.info("server url:", Cross.getUrl(entity.name));
+
+    return;
+  }
+
+  /**
+   * create python service
+   * In the default configuration, services can be started with applications.
+   * Developers can turn off the configuration and create it manually.
+   */
+  async createPythonServer() {
+    // method 1: Use the default Settings
+    //const entity = await Cross.run(serviceName);
+
+    // method 2: Use custom configuration
+    const serviceName = "python";
+    const opt = {
+      name: "pyapp",
+      cmd: path.join(Ps.getExtraResourcesDir(), "py", "pyapp"),
+      directory: path.join(Ps.getExtraResourcesDir(), "py"),
+      args: ["--port=7074"],
+      windowsExtname: true,
+      appExit: true,
+    };
+    const entity = await Cross.run(serviceName, opt);
+    Log.info("server name:", entity.name);
+    Log.info("server config:", entity.config);
+    Log.info("server url:", entity.getUrl());
+
+    return;
+  }
+}
+
+CrossService.toString = () => "[class CrossService]";
+module.exports = CrossService;

+ 0 - 29
electron/service/example.js

@@ -1,29 +0,0 @@
-'use strict';
-
-const { Service } = require('ee-core');
-
-/**
- * 示例服务(service层为单例)
- * @class
- */
-class ExampleService extends Service {
-
-  constructor(ctx) {
-    super(ctx);
-  }
-
-  /**
-   * test
-   */
-  async test(args) {
-    let obj = {
-      status:'ok',
-      params: args
-    }
-
-    return obj;
-  }
-}
-
-ExampleService.toString = () => '[class ExampleService]';
-module.exports = ExampleService;

+ 3 - 1
package.json

@@ -13,6 +13,7 @@
     "rd": "ee-bin move --flag=frontend_dist",
     "encrypt": "ee-bin encrypt",
     "clean": "ee-bin clean",
+    "build-python": "ee-bin build --cmds=python && ee-bin move --flag=python_dist",
     "icon": "ee-bin icon",
     "reload": "nodemon --config ./electron/config/nodemon.json",
     "rebuild": "electron-rebuild",
@@ -56,9 +57,10 @@
     "nodemon": "^2.0.16"
   },
   "dependencies": {
+    "axios": "^1.8.3",
     "dayjs": "^1.10.7",
     "ee-core": "2.12.0",
     "electron-updater": "^5.3.0",
     "lodash": "^4.17.21"
   }
-}
+}

+ 22 - 0
python/config.ini

@@ -0,0 +1,22 @@
+[app]
+# 应用名称
+app_name=智慧拍-后端应用
+# 应用版本号
+version=1.0.0
+# 应用host地址
+host=127.0.0.1
+# 应用服务启动名称
+app_run=api:app
+# 端口号
+port=7074
+debug=false
+env=prod
+# 线程数
+works=1
+[log]
+# 日志相关
+log_file_name=app.log 
+#最大字节数
+max_bytes=102400 
+#备份数量
+backup_counts=3 

+ 9 - 2
python/index.py

@@ -3,6 +3,12 @@ import uvicorn
 import signal
 from api import *
 from sockets.socket_server import *
+import uvicorn.loops.auto
+import uvicorn.protocols.http.auto
+import uvicorn.protocols.websockets.auto
+import uvicorn.lifespan.on
+from multiprocessing import Process, freeze_support
+
 def handle_shutdown(signum, frame):
     """关闭系统应用服务"""
      # 终止事件循环
@@ -10,17 +16,18 @@ def handle_shutdown(signum, frame):
     loop.call_soon_threadsafe(loop.stop)
     sys.exit(0)
 
-
 if __name__ == "__main__":
     signal.signal(signal.SIGINT, handle_shutdown)
     signal.signal(signal.SIGTERM, handle_shutdown)
     # 控制台默认关闭输出信息,如果想要查看控制台输出,请单独启动服务 npm run dev-python
     print("python server is running at port:", PORT)
     # uvicorn会多创建一个进程,并且stdio独立于控制台,如果(开发时)出现进程没有关闭,可尝试关闭终端
+    print("python server is running at port:", APP_RUN)
+    isDebug = True if IS_DEBUG == "true" else False
     uvicorn.run(
         APP_RUN,
         host=APP_HOST,
         port=int(PORT),
-        reload=False,
+        reload=isDebug,
         workers=int(APP_WORKS),
     )

BIN
python/requestments.txt


+ 15 - 22
python/settings.py

@@ -1,36 +1,29 @@
 from dotenv import load_dotenv, find_dotenv
 from pathlib import Path  # Python 3.6+ only
-import os
+import configparser
 
-# 一、自动搜索 .env 文件
-load_dotenv(verbose=True)
-
-
-# 二、与上面方式等价
-load_dotenv(find_dotenv(), verbose=True)
-
-# 三、或者指定 .env 文件位置
-env_path = Path(".") / ".env"
-load_dotenv(dotenv_path=env_path, verbose=True)
+config = configparser.ConfigParser()
+config_name = "config.ini"
+config.read(config_name, encoding="utf-8")
 # 应用名称
-APP_NAME = os.getenv("app_name")
+APP_NAME = config.get("app", "app_name")
 # 应用版本号
-APP_VERSION = os.getenv("version")
+APP_VERSION = config.get("app", "version")
 # 是否开启调试模式
-IS_DEBUG = os.getenv("debug")
+IS_DEBUG = config.get("app", "debug")
 # 应用端口号
-PORT = os.getenv("port")
+PORT = config.get("app", "port")
 # 应用线程数
-APP_WORKS = os.getenv("works")
+APP_WORKS = config.get("app", "works")
 # 应用host地址
-APP_HOST = os.getenv("app_host")
+APP_HOST = config.get("app", "host")
 # 应用服务启动名称
-APP_RUN = os.getenv("app_run")
+APP_RUN = config.get("app", "app_run")
 
 # 日志名称
-LOG_FILE_NAME = os.getenv("log_file_name")
+LOG_FILE_NAME = config.get("log", "log_file_name")
 # 最大字节数
-MAX_BYTES = os.getenv("max_bytes")
+MAX_BYTES = config.get("log", "max_bytes")
+print("Max bytes is", MAX_BYTES)
 # 备份数量
-BACKUP_COUNTS = os.getenv("backup_counts")
-
+BACKUP_COUNTS = config.get("log", "backup_counts")

+ 5 - 4
python/setup.py

@@ -2,15 +2,16 @@ from cx_Freeze import setup, Executable
 
 # 创建可执行文件的配置
 executableApp = Executable(
-    script="main.py",
+    script="index.py",
     target_name="pyapp",
 )
 
 # 打包的参数配置
 options = {
     "build_exe": {
-        "build_exe":"./dist/",
+        "build_exe": "./dist/",
         "excludes": ["*.txt"],
+        "include_files": ["config.ini"],
         "optimize": 2,
     }
 }
@@ -20,5 +21,5 @@ setup(
     version="1.0",
     description="python app",
     options=options,
-    executables=[executableApp]
-)
+    executables=[executableApp],
+)