diff --git a/.gitignore b/.gitignore index 768ee45..7ccfbfe 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,7 @@ /conf.yml /conf.json /dist +/instances/ # Byte-compiled / optimized / DLL files __pycache__/ @@ -66,7 +67,6 @@ db.sqlite3 db.sqlite3-journal # Flask stuff: -instance/ .webassets-cache # Scrapy stuff: diff --git a/README.md b/README.md index a5e8995..c49916e 100644 --- a/README.md +++ b/README.md @@ -2,18 +2,29 @@ ## 开发环境 -目前只有 `pywebview` 一个依赖。 +安装 `pip-tools` + +```bash +pip install pip-tools +``` + +安装依赖 + +```bash +pip-sync requirements.txt +``` ## 打包 前端运行 `npm run build` 生成 `ui/dist`,之后安装 PyInstaller,运行 ```bash -pyinstaller -w --add-data "ui/dist:ui/dist" --add-data "launcher/sys_config/config_dist.yaml:launcher/sys_config" launcher.py +pyinstaller -w --add-data "ui/dist:ui/dist" --add-data "launcher/sys_config/config_dist.json:launcher/sys_config" launcher.py ``` 在dist文件夹生成launcher文件夹 ```bash -tar -cf dist/launcher.tar dist/launcher +cd dist +py7zr c launcher.7z launcher ``` diff --git a/launcher.py b/launcher.py index b850fb9..5e92a69 100644 --- a/launcher.py +++ b/launcher.py @@ -1,18 +1,17 @@ import mimetypes -import os +import shutil from pathlib import Path -from launcher.constants import upgrade_script_name +from launcher.constants import update_tmp_folder from launcher.webview import start_webview mimetypes.add_type("text/html", ".html") mimetypes.add_type("text/css", ".css") mimetypes.add_type("application/javascript", ".js") -if __name__ == '__main__': - - # 如果当前路径存在更新脚本,则删除 - if Path(upgrade_script_name).exists(): - os.remove(upgrade_script_name) +if __name__ == "__main__": + # 如果当前路径存在临时文件夹,则删除 + if Path(update_tmp_folder).exists(): + shutil.rmtree(update_tmp_folder) start_webview() diff --git a/launcher/config/__init__.py b/launcher/config/__init__.py index b36e8f2..01d7c22 100644 --- a/launcher/config/__init__.py +++ b/launcher/config/__init__.py @@ -1,26 +1,15 @@ import json import os - -import yaml -from yamlcore import CoreDumper, CoreLoader +from pathlib import Path from launcher.config.conf import Conf -from pathlib import Path conf_path = Path(os.path.join(os.getcwd(), "conf.json")) def save_conf(): with conf_path.open("w", encoding="utf8") as f: - json.dump(conf.model_dump(), f, ensure_ascii=False, indent=4) # Use json.dump - # yaml.dump( - # conf.model_dump(), - # f, - # Dumper=CoreDumper, - # encoding="utf-8", - # default_flow_style=False, - # allow_unicode=True, - # ) + json.dump(conf.model_dump(), f, ensure_ascii=False, indent=4) def load_conf(): @@ -30,8 +19,8 @@ def load_conf(): conf = Conf() save_conf() return - with conf_path.open("r", encoding="utf-8") as f: - data = yaml.load(f, Loader=CoreLoader) + with conf_path.open("r", encoding="utf-8") as file: + data = json.load(file) if data is None: data = {} conf = Conf(**data) diff --git a/launcher/config/conf.py b/launcher/config/conf.py index 0f60eec..cfeca5c 100644 --- a/launcher/config/conf.py +++ b/launcher/config/conf.py @@ -1,3 +1,5 @@ +from typing import List, Literal, get_args, get_origin + from pydantic import BaseModel, model_validator from pydantic_core import PydanticUndefined @@ -7,30 +9,75 @@ class ConfModel(BaseModel): @classmethod def nested_defaults(cls, data): for name, field in cls.model_fields.items(): + expected_type = field.annotation if name not in data: if field.default is PydanticUndefined: - data[name] = field.annotation() + data[name] = expected_type else: data[name] = field.default + value = data[name] + + # 检查 Literal 类型并修正 + if get_origin(expected_type) is Literal: + valid_literals = get_args(expected_type) + if value not in valid_literals: + # 修正为默认值 + data[name] = ( + field.default + if field.default is not PydanticUndefined + else None + ) return data class Total(ConfModel): """整体""" + # 所在页面 page: str = "init" + # 是否已展示帮助文档 + is_already_show_doc: bool = False class UpdatePart(ConfModel): """更新代码""" + # mower-ng 代码分支 branch: str = "slow" # PyPI 仓库镜像 mirror: str = "aliyun" +class LaunchPart(ConfModel): + """启动程序""" + + class Instance(ConfModel): + """实例""" + + # 是否选中 + checked: bool = False + # 实例名 + name: str = "" + # 实例路径 + path: str = "" + + # 实例列表 + instances: List[Instance] = [] + # 是否展示日志窗口 + is_show_log: bool = False + + +class OtherPart(ConfModel): + """其他配置""" + + # xx.zhaozuohong.vip镜像 (访问xx.zhaozuohong.vip url时,0=原路径 1=在.zhaozuohong.vip前添加-cf前缀) + base_mirror: Literal["0", "1"] = "0" + + class Conf( Total, UpdatePart, + LaunchPart, + OtherPart, ): pass diff --git a/launcher/constants.py b/launcher/constants.py index 60ec018..10766e8 100644 --- a/launcher/constants.py +++ b/launcher/constants.py @@ -4,16 +4,25 @@ constants.py 该模块定义了应用程序中使用的各种常量。这些常量包括API URL和其他配置参数。 """ +# 更新临时文件夹名 +update_tmp_folder = "download_tmp" # 更新脚本名 upgrade_script_name = "upgrade.bat" +# 下载新版本压缩包名 +file_name = "launcher.7z" # 获取最新版本发布信息 -get_new_version_url = "https://git.zhaozuohong.vip/api/v1/repos/mower-ng/launcher/releases/latest" +get_new_version_url = ( + "https://git.zhaozuohong.vip/api/v1/repos/mower-ng/launcher/releases/latest" +) # 下载地址 download_git_url = "https://list.zhaozuohong.vip/mower-ng/git.7z" download_python_url = "https://list.zhaozuohong.vip/mower-ng/python.7z" +# mower-ng git链接 +mower_ng_git_url = "https://git.zhaozuohong.vip/mower-ng/mower-ng.git" + # pip镜像地址 mirror_list = { "pypi": "https://pypi.org/simple", @@ -22,3 +31,17 @@ mirror_list = { "sjtu": "https://mirror.sjtu.edu.cn/pypi/web/simple", } +# 实例文件夹名 +instances_folder_name = "instances" + +# cli命令 +cli_command = { + "status": "获取mower-ng实例状态", + "launch": "启动mower-ng进程", + "exit": "停止mower-ng进程", + "kill": "强制退出mower-ng进程", + "start": "开始运行调度器", + "stop": "停止运行调度器", + "webui": "在浏览器中打开网页面板", + "log": "通过WebSocket获取日志", +} diff --git a/launcher/file/download.py b/launcher/file/download.py index ccda67e..03825f8 100644 --- a/launcher/file/download.py +++ b/launcher/file/download.py @@ -5,7 +5,7 @@ import requests from launcher.file.extract import extract_7z_file from launcher.file.utils import format_size -from launcher.webview.events import custom_event +from launcher.webview.events import custom_event, LogType def download_file(download_name, download_url, destination_folder): @@ -21,11 +21,11 @@ def download_file(download_name, download_url, destination_folder): filename = os.path.basename(download_url) download_path = os.path.join(destination_folder, filename) - custom_event(f"开始下载: {download_name}") + custom_event(LogType.info, f"开始下载: {download_name}") response = requests.get(download_url, stream=True) if response.status_code == 200: - total_size = int(response.headers.get('content-length', 0)) + total_size = int(response.headers.get("content-length", 0)) downloaded_size = 0 start_time = time.time() last_update_time = time.time() # 记录上次更新时间 @@ -43,7 +43,9 @@ def download_file(download_name, download_url, destination_folder): else: download_speed = 0 - progress_percent = (downloaded_size / total_size) * 100 if total_size != 0 else 0 + progress_percent = ( + (downloaded_size / total_size) * 100 if total_size != 0 else 0 + ) # 检查是否需要更新进度信息,每1秒更新一次 if current_time - last_update_time >= 1: @@ -53,20 +55,26 @@ def download_file(download_name, download_url, destination_folder): formatted_speed = format_size(download_speed) + "/s" custom_event( - f"下载进度: {progress_percent:.2f}% ({formatted_downloaded_size}/{formatted_total_size}), 下载速度: {formatted_speed}") + LogType.info, + f"下载进度: {progress_percent:.2f}% ({formatted_downloaded_size}/{formatted_total_size}), 下载速度: {formatted_speed}", + ) last_update_time = current_time # 更新上次更新时间 end_time = time.time() total_elapsed_time = end_time - start_time - average_download_speed = downloaded_size / total_elapsed_time if total_elapsed_time != 0 else 0 + average_download_speed = ( + downloaded_size / total_elapsed_time if total_elapsed_time != 0 else 0 + ) # 格式化输出 formatted_total_elapsed_time = f"{total_elapsed_time:.2f} 秒" formatted_average_download_speed = format_size(average_download_speed) + "/s" custom_event( - f"下载完成: {filename}, 耗时: {formatted_total_elapsed_time}, 下载速度: {formatted_average_download_speed}") + LogType.info, + f"下载完成: {filename}, 耗时: {formatted_total_elapsed_time}, 下载速度: {formatted_average_download_speed}", + ) else: - custom_event(f"下载失败: {response.status_code}") + custom_event(LogType.error, f"下载失败: {response.status_code}") return False return True @@ -84,7 +92,7 @@ def init_download(download_name, download_url, destination_folder): def download(): target_folder = os.path.join(download_name) if os.path.exists(target_folder): - custom_event(f"{download_name} 文件夹已存在,跳过下载") + custom_event(LogType.info, f"{download_name} 文件夹已存在,跳过下载") return True filename = os.path.basename(download_url) diff --git a/launcher/file/extract.py b/launcher/file/extract.py index 17269a2..a1c523c 100644 --- a/launcher/file/extract.py +++ b/launcher/file/extract.py @@ -5,7 +5,7 @@ from py7zr import py7zr from py7zr.callbacks import ExtractCallback from launcher.file.utils import format_size -from launcher.webview.events import custom_event +from launcher.webview.events import custom_event, LogType class MyExtractCallback(ExtractCallback): @@ -24,7 +24,7 @@ class MyExtractCallback(ExtractCallback): self.total_size += int(wrote_bytes) current_time = time.time() if current_time - self.last_print_time >= 1.0: # 至少每隔1秒输出一次 - custom_event(f"已解压: {format_size(self.total_size)}") + custom_event(LogType.info, f"已解压: {format_size(self.total_size)}") self.last_print_time = current_time def report_postprocess(self): @@ -37,7 +37,9 @@ class MyExtractCallback(ExtractCallback): pass -def extract_7z_file(file_name, file_path, destination_folder, delete_after_extract=True): +def extract_7z_file( + file_name, file_path, destination_folder, delete_after_extract=True +): """ 解压7z文件到指定文件夹 :param file_name: 7z文件的名称 @@ -49,27 +51,28 @@ def extract_7z_file(file_name, file_path, destination_folder, delete_after_extra if not os.path.exists(destination_folder): os.makedirs(destination_folder) - custom_event(f"开始解压文件: {file_name}") + custom_event(LogType.info, f"开始解压文件: {file_name}") try: start_time = time.time() - with py7zr.SevenZipFile(file_path, mode='r') as z: + with py7zr.SevenZipFile(file_path, mode="r") as z: callback = MyExtractCallback() z.extractall(path=destination_folder, callback=callback) end_time = time.time() total_elapsed_time = end_time - start_time formatted_total_elapsed_time = f"{total_elapsed_time:.2f} 秒" custom_event( - f"解压完成: {file_name}, 总大小: {format_size(callback.total_size)}, 耗时: {formatted_total_elapsed_time}") + LogType.info, + f"解压完成: {file_name}, 总大小: {format_size(callback.total_size)}, 耗时: {formatted_total_elapsed_time}", + ) except Exception as e: - e.print_exc() - custom_event(f"解压失败: {str(e)}") + custom_event(LogType.error, f"解压失败: {repr(e)}") return False if delete_after_extract: try: os.remove(file_path) - custom_event(f"删除{file_path}成功") + custom_event(LogType.info, f"删除{file_path}成功") except OSError as e: - custom_event(f"删除{file_path}失败: {str(e)}") + custom_event(LogType.error, f"删除{file_path}失败: {repr(e)}") return True diff --git a/launcher/file/utils.py b/launcher/file/utils.py index e78dfcd..b9dd968 100644 --- a/launcher/file/utils.py +++ b/launcher/file/utils.py @@ -1,7 +1,33 @@ +import os + + def format_size(size_bytes): """格式化文件大小为人类可读的形式""" - for unit in ['B', 'KB', 'MB', 'GB', 'TB']: + for unit in ["B", "KB", "MB", "GB", "TB"]: if size_bytes < 1024: return f"{size_bytes:.2f} {unit}" size_bytes /= 1024 return f"{size_bytes:.2f} PB" + + +def ensure_directory_exists(directory): + """确保目录存在,如果不存在则创建""" + if not os.path.exists(directory): + os.makedirs(directory) + + +def check_command_path(command, cwd=None): + """检查命令路径是否存在exe文件 + :return 是否存在,命令exe文件全路径 + """ + command_name = command.split(" ")[0] + system_command = ["start", "explorer"] + if command_name in system_command: + return True, None + exec_command_path = os.getcwd() + if cwd: + exec_command_path = os.path.join(exec_command_path, cwd) + full_command_path = ( + os.path.abspath(os.path.join(exec_command_path, command_name)) + ".exe" + ) + return os.path.exists(full_command_path), full_command_path diff --git a/launcher/instances/__init__.py b/launcher/instances/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/launcher/instances/manager.py b/launcher/instances/manager.py new file mode 100644 index 0000000..f0ff759 --- /dev/null +++ b/launcher/instances/manager.py @@ -0,0 +1,129 @@ +import json +import os +import shutil +import uuid + +from launcher import config +from launcher.config.conf import LaunchPart +from launcher.constants import instances_folder_name +from launcher.webview.events import custom_event, LogType + + +def add_instance(): + instances_path = os.path.join(os.getcwd(), instances_folder_name) + if not os.path.exists(instances_path): + os.makedirs(instances_path) + instance_folder_name = str(uuid.uuid4()) + instance_folder_path = os.path.join(instances_path, instance_folder_name) + if os.path.exists(instance_folder_path): + raise Exception("创建实例目录失败") + os.makedirs(instance_folder_path) + custom_event(LogType.info, f"创建实例目录成功: {instance_folder_path}") + return instance_folder_path + + +def migrate_instance(source_folder): + """通用配置迁移方法 + Args: + source_folder: 源配置目录路径 + target_folder: 目标配置目录路径 + """ + try: + if not os.path.exists(source_folder): + custom_event(LogType.error, f"源配置目录不存在: {source_folder}") + return {"status": False, "message": f"源配置目录不存在{source_folder}"} + + target_folder = add_instance() + + # 需要复制的目录和文件列表 + copy_items = [("tmp", True), ("conf.yml", False), ("plan.json", False)] + + for item, is_dir in copy_items: + src = os.path.join(source_folder, item) + dst = os.path.join(target_folder, item) + + if is_dir: + if os.path.exists(src): + shutil.copytree(src, dst, dirs_exist_ok=True) + else: + if os.path.exists(src): + shutil.copy2(src, dst) + + custom_event(LogType.info, f"{source_folder} 配置成功迁移至 {target_folder}") + return {"status": True, "data": target_folder, "message": "配置迁移成功"} + + except Exception as e: + custom_event(LogType.error, f"配置迁移失败: {str(e)}") + return {"status": False, "message": str(e)} + + +def migrate_instances_config(): + try: + config_path = os.path.join(os.getcwd(), "mower-ng", "instances.json") + + if not os.path.exists(config_path): + custom_event(LogType.error, f"多开配置文件不存在{config_path}") + return {"status": False, "message": "多开配置文件不存在"} + + with open(config_path, "r", encoding="utf-8") as f: + instances_data = json.loads(f.read()) + custom_event(LogType.info, f"读取多开配置: {instances_data}") + + valid_instances = [] + error_messages = [] + + for index, item in enumerate(instances_data, 1): + try: + # 基础结构验证 + if not isinstance(item, dict): + raise ValueError("配置项必须是字典类型") + + # 必填字段检查 + required_fields = ["name", "path"] + for field in required_fields: + if field not in item: + raise ValueError(f"缺少必要字段: {field}") + + # 路径有效性验证 + if not os.path.exists(item["path"]): + raise ValueError(f"配置路径不存在{item['path']}") + + # 执行配置迁移 + migration_result = migrate_instance(item["path"]) + + if not migration_result["status"]: + raise Exception(f"路径迁移失败: {migration_result['message']}") + + # 转换为实例模型 + instance = LaunchPart.Instance( + name=item["name"].strip(), path=migration_result["data"] + ) + + valid_instances.append(instance) + + except Exception as e: + error_msg = f"第{index}项: {str(e)}" + error_messages.append(error_msg) + custom_event(LogType.error, error_msg) + + # 保存有效配置 + if valid_instances: + config.conf.instances.extend(valid_instances) + config.save_conf() + + message = f"成功导入{len(valid_instances)}个实例" + ( + f",存在{len(error_messages)}个错误项" if error_messages else "" + ) + custom_event(LogType.info, message) + return { + "status": not bool(error_messages), + "data": len(valid_instances), + "message": message, + } + + except json.JSONDecodeError as e: + custom_event(LogType.error, f"JSON解析失败: {str(e)}") + return {"status": False, "message": "配置文件格式错误"} + except Exception as e: + custom_event(LogType.error, f"迁移多开配置失败: {str(e)}") + return {"status": False, "message": str(e)} diff --git a/launcher/log.py b/launcher/log.py index 954ccc3..7588b05 100644 --- a/launcher/log.py +++ b/launcher/log.py @@ -1,5 +1,6 @@ import io import logging +import os import sys from logging.handlers import RotatingFileHandler @@ -8,21 +9,22 @@ from launcher.sys_config import sys_config # 配置日志 def setup_logger(): - log_level = sys_config.get('log_level') + log_level = sys_config.get("log_level") logger = logging.getLogger("launcher.log") logger.setLevel(log_level) # 设置标准输出编码为 UTF-8 - sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8') + sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8") # 控制台输出 console_handler = logging.StreamHandler() console_handler.setLevel(log_level) # 文件输出 + file_path = os.path.join(os.getcwd(), "launcher.log") file_handler = RotatingFileHandler( - "../launcher.log", maxBytes=5 * 1024 * 1024, backupCount=3, encoding='utf-8' + file_path, maxBytes=5 * 1024 * 1024, backupCount=3, encoding="utf-8" ) file_handler.setLevel(logging.INFO) diff --git a/launcher/sys_config/__init__.py b/launcher/sys_config/__init__.py index d50d859..b7be326 100644 --- a/launcher/sys_config/__init__.py +++ b/launcher/sys_config/__init__.py @@ -1,19 +1,21 @@ -import sys +import json import os - -import yaml +import sys class SysConfig: """ 读取系统配置文件 """ + # 版本 version: str # ui路径 url: str # 日志输出级别 log_level: str + # 是否开启ui调试 + debug: bool def __init__(self): self.config = {} @@ -21,32 +23,32 @@ class SysConfig: self.load_config() def get_config_path(self): - if getattr(sys, 'frozen', False): + if getattr(sys, "frozen", False): # logger.error("打包配置") # 如果是打包后的可执行文件 base_path = sys._MEIPASS - config_subdir = 'launcher/sys_config' # 添加子目录 - config_filename = 'config_dist.yaml' + config_subdir = "launcher/sys_config" # 添加子目录 + config_filename = "config_dist.json" else: # logger.error("本地配置") # 如果是本地开发环境 base_path = os.path.dirname(__file__) - config_subdir = '' # 本地开发环境不需要子目录 - config_filename = 'config_local.yaml' + config_subdir = "" # 本地开发环境不需要子目录 + config_filename = "config_local.json" config_path = os.path.join(base_path, config_subdir, config_filename) return config_path def load_config(self): try: - with open(self.config_path, 'r', encoding='utf-8') as file: - self.config = yaml.safe_load(file) + with open(self.config_path, "r", encoding="utf-8") as file: + self.config = json.load(file) except FileNotFoundError: pass # logger.error(f"配置文件未找到: {self.config_path}") - except Exception as e: + except Exception: pass - # logger.error(f"加载配置文件时出错: {str(e)}") + # logger.error(f"加载配置文件时出错: {repr(e)}") def get(self, key): return self.config.get(key) diff --git a/launcher/sys_config/config_dist.json b/launcher/sys_config/config_dist.json new file mode 100644 index 0000000..499fad5 --- /dev/null +++ b/launcher/sys_config/config_dist.json @@ -0,0 +1,6 @@ +{ + "version": "v0.7.1", + "url": "ui/dist/index.html", + "log_level": "INFO", + "debug": false +} \ No newline at end of file diff --git a/launcher/sys_config/config_dist.yaml b/launcher/sys_config/config_dist.yaml deleted file mode 100644 index 1319bb8..0000000 --- a/launcher/sys_config/config_dist.yaml +++ /dev/null @@ -1,3 +0,0 @@ -version: "v0.3" -url: "ui/dist/index.html" -log_level: "ERROR" \ No newline at end of file diff --git a/launcher/sys_config/config_local.json b/launcher/sys_config/config_local.json new file mode 100644 index 0000000..e42e05a --- /dev/null +++ b/launcher/sys_config/config_local.json @@ -0,0 +1,6 @@ +{ + "version": "dev", + "url": "http://localhost:5173/", + "log_level": "DEBUG", + "debug": true +} \ No newline at end of file diff --git a/launcher/sys_config/config_local.yaml b/launcher/sys_config/config_local.yaml deleted file mode 100644 index a556984..0000000 --- a/launcher/sys_config/config_local.yaml +++ /dev/null @@ -1,3 +0,0 @@ -version: "dev" -url: "http://localhost:5173/" -log_level: "INFO" \ No newline at end of file diff --git a/launcher/utils.py b/launcher/utils.py new file mode 100644 index 0000000..bb56ecc --- /dev/null +++ b/launcher/utils.py @@ -0,0 +1,12 @@ +from launcher import config + + +def build_base_url(url: str) -> str: + """ + 构建xx.zhaozuohong.vip,如果配置base_mirror是1,在.zhaozuohong.vip前添加-cf前缀 + :param url: 带有xx.zhaozuohong.vip的url字符串 + :return: 构建完成的url + """ + if config.conf.base_mirror == "1": + url = url.replace(".zhaozuohong.vip", "-cf.zhaozuohong.vip") + return url diff --git a/launcher/webview/__init__.py b/launcher/webview/__init__.py index d2dea2f..09ae4d6 100644 --- a/launcher/webview/__init__.py +++ b/launcher/webview/__init__.py @@ -1,12 +1,18 @@ import webview -from launcher.webview.api import Api from launcher.sys_config import sys_config +from launcher.webview.api import Api window = None def start_webview(): global window - window = webview.create_window(f"mower-ng launcher {sys_config.get('version')}", sys_config.get('url'), js_api=Api()) - webview.start() + window = webview.create_window( + f"mower-ng launcher {sys_config.get('version')}", + sys_config.get("url"), + js_api=Api(), + width=850, + height=600, + ) + webview.start(debug=sys_config.get("debug")) diff --git a/launcher/webview/api.py b/launcher/webview/api.py index 09fdd02..8bb62a3 100644 --- a/launcher/webview/api.py +++ b/launcher/webview/api.py @@ -1,65 +1,91 @@ import io import os +import shutil import subprocess -import threading +import time from _winapi import CREATE_NO_WINDOW from pathlib import Path from shutil import rmtree from subprocess import Popen -import chardet import requests from launcher import config -from launcher.constants import download_git_url, download_python_url, get_new_version_url, upgrade_script_name, \ - mirror_list +from launcher.constants import ( + download_git_url, + download_python_url, + get_new_version_url, + upgrade_script_name, + mirror_list, + file_name, + instances_folder_name, + mower_ng_git_url, + cli_command, +) from launcher.file.download import init_download, download_file +from launcher.file.extract import extract_7z_file +from launcher.file.utils import ensure_directory_exists, check_command_path +from launcher.instances import manager from launcher.log import logger from launcher.sys_config import sys_config -from launcher.webview.events import custom_event +from launcher.utils import build_base_url +from launcher.webview.events import custom_event, LogType command_list = { - "download_git": lambda: init_download("git", download_git_url, os.getcwd()), - "download_python": lambda: init_download("python", download_python_url, os.getcwd()), + "download_git": lambda: init_download( + "git", build_base_url(download_git_url), os.getcwd() + ), + "download_python": lambda: init_download( + "python", build_base_url(download_python_url), os.getcwd() + ), "lfs": "git\\bin\\git lfs install", "ensurepip": "python\\python -m ensurepip --default-pip", - "clone": "git\\bin\\git -c lfs.concurrenttransfers=100 clone https://git.zhaozuohong.vip/mower-ng/mower-ng.git --branch slow", + "clone": lambda: f"git\\bin\\git -c lfs.concurrenttransfers=100 clone {build_base_url(mower_ng_git_url)} --branch slow", + "set_remote": lambda: f"..\\git\\bin\\git remote set-url origin {build_base_url(mower_ng_git_url)}", + "set_lfs": lambda: f"..\\git\\bin\\git config lfs.url {build_base_url(mower_ng_git_url)}/info/lfs", "fetch": lambda: f"..\\git\\bin\\git fetch origin {config.conf.branch} --progress", "switch": lambda: f"..\\git\\bin\\git -c lfs.concurrenttransfers=100 switch -f {config.conf.branch} --progress", "reset": lambda: f"..\\git\\bin\\git -c lfs.concurrenttransfers=200 reset --hard origin/{config.conf.branch}", - "pip_install": lambda: f"..\\python\\Scripts\\pip install --no-cache-dir -i {mirror_list[config.conf.mirror]} -r requirements.txt --no-warn-script-location", - "webview": "start ..\\python\\pythonw webview_ui.py", - "manager": "start ..\\python\\pythonw manager.py", + "pip_tools_install": lambda: f"..\\python\\Scripts\\pip install --no-cache-dir -i {mirror_list[config.conf.mirror]} pip-tools --no-warn-script-location", + "pip_sync": lambda: f"..\\python\\Scripts\\pip-sync -i {mirror_list[config.conf.mirror]} requirements.txt", + "webview": lambda instance_path="": f'..\\python\\pythonw -X utf8 webview_ui.py "{instance_path}"', + "cli": lambda path, + command: f'..\\python\\pythonw -X utf8 cli.py -p "{path}" {command}', } -def detect_encoding(stream): - # 读取一部分数据来检测编码 - raw_data = stream.read(4096) - result = chardet.detect(raw_data) - stream.seek(0) # 将流指针重置到开头 - return result['encoding'] +def parse_stderr(stderr_output): + error_keywords = { + "fatal: destination path 'mower-ng' already exists and is not an empty directory.": "mower-ng文件夹已存在并且非空。", + "index.lock': File exists": "上一个git命令正在执行,请等待执行结束或在任务管理器中杀掉git进程,并确保上方提示的index.lock文件删除后再次运行。", + "Could not resolve host": "网络出现错误,请检查网络是否通畅。", + "ReadTimeoutError": "网络连接超时,请检查网络连接或尝试更换镜像源。", + "No space left on device": "磁盘空间不足。", + } + for keyword, message in error_keywords.items(): + if keyword in stderr_output: + return message + return "未定义的错误" -def read_stream(stream, log_func): - detected_encoding = detect_encoding(stream) - text_io = io.TextIOWrapper(stream, encoding=detected_encoding, errors='replace') - try: - for line in iter(text_io.readline, ''): - text = line.rstrip('\n') - custom_event(text.strip() + "\n") - finally: - text_io.close() +def check_command_end(command_key, output): + end_keywords = {"webview": {"WebSocket客户端建立连接": "mower_ng已成功运行"}} + if command_key in end_keywords: + keywords = end_keywords[command_key] + for keyword in keywords: + if keyword in output: + custom_event(LogType.info, keywords[keyword]) + return True + return False class Api: - def load_config(self): - logger.info("读取配置文件") + logger.debug("读取配置文件") return config.conf.model_dump() def save_config(self, conf): - logger.info(f"更新配置文件{conf}") + logger.debug(f"更新配置文件{conf}") config.conf = config.Conf(**conf) config.save_conf() @@ -68,31 +94,38 @@ class Api: def get_new_version(self): logger.info("获取最新版本号") - response = requests.get(get_new_version_url) + response = requests.get(build_base_url(get_new_version_url)) return response.json() # 更新启动器本身 def update_self(self, download_url): + download_url = build_base_url(download_url) logger.info(f"开始更新启动器 {download_url}") - # 下载压缩包的全路径 - file_name = os.path.basename(download_url) current_path = os.getcwd() - if not download_file("launcher", download_url, current_path): + download_tmp_folder = os.path.join(current_path, "download_tmp") + # 确保 download_tmp 文件夹存在 + ensure_directory_exists(download_tmp_folder) + if not download_file("launcher", download_url, download_tmp_folder): return "下载新版本失败" - download_path = os.path.join(current_path, file_name) - script_path = os.path.join(os.getcwd(), upgrade_script_name) - folder_path = os.path.join(os.getcwd(), "_internal") - exe_path = os.path.join(os.getcwd(), "launcher.exe") + download_path = os.path.join(download_tmp_folder, file_name) + if not extract_7z_file("launcher", download_path, download_tmp_folder, True): + return "解压新版本失败" + + exe_path = os.path.join(current_path, "launcher.exe") + folder_path = os.path.join(current_path, "_internal") + new_exe_path = os.path.join(download_tmp_folder, "launcher", "launcher.exe") + new_folder_path = os.path.join(download_tmp_folder, "launcher", "_internal") + script_path = os.path.join(download_tmp_folder, upgrade_script_name) with open(script_path, "w") as b: temp_list = "@echo off\n" temp_list += "timeout /t 3 /nobreak\n" # 等待进程退出 temp_list += f"rmdir {folder_path}\n" # 删除_internal temp_list += f"del {exe_path}\n" # 删除exe - temp_list += f"tar -xf {download_path} -C ..\n" # 解压压缩包 - temp_list += "timeout /t 1 /nobreak\n" # 等待解压 + temp_list += f"xcopy /e /i /y {new_folder_path} {folder_path}\n" + temp_list += f"move {new_exe_path} {exe_path}\n" + temp_list += "timeout /t 1 /nobreak\n" # 等待操作完成 temp_list += f"start {exe_path}\n" # 启动新程序 - temp_list += f"del {download_path}\n" # 删除压缩包 temp_list += "exit" b.write(temp_list) # 不显示cmd窗口 @@ -100,42 +133,175 @@ class Api: os._exit(0) def rm_site_packages(self): - site_packages_path = Path("./python/Lib/site-packages") - if site_packages_path.exists(): - rmtree(site_packages_path) - return "site-packages目录移除成功" - return "python\\Lib\\site-packages目录不存在" + try: + site_packages_path = Path("./python/Lib/site-packages") + if site_packages_path.exists(): + rmtree(site_packages_path) + return "site-packages目录移除成功" + return "python\\Lib\\site-packages目录不存在" + except Exception as e: + return repr(e) def rm_python_scripts(self): - python_scripts_path = Path("./python/Scripts") - if python_scripts_path.exists(): - rmtree(python_scripts_path) - return "Scripts目录移除成功" - return "python\\Scripts目录不存在" + try: + python_scripts_path = Path("./python/Scripts") + if python_scripts_path.exists(): + rmtree(python_scripts_path) + return "Scripts目录移除成功" + return "python\\Scripts目录不存在" + except Exception as e: + return repr(e) - def run(self, command, cwd=None): - command = command_list[command] + def run(self, command_key, cwd=None, params={}): + command = command_list[command_key] if callable(command): - command = command() + try: + command = command(**params) + except TypeError: + command = command() if callable(command): return "success" if command() else "failed" - custom_event(command + "\n") + if cwd is not None: + custom_event(LogType.info, f"命令执行目录:{cwd}") + custom_event(LogType.execute_command, command) + # 执行命令前先判断命令路径是否存在 + exist, command_path = check_command_path(command, cwd) + if not exist: + custom_event( + LogType.error, + f"命令路径不存在:{command_path} 请尝试依赖修复并重新初始化。", + ) + return "failed" try: + stdout_stderr = [] with subprocess.Popen( - command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True, cwd=cwd, bufsize=0, - universal_newlines=False + command, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + shell=True, + cwd=cwd, + bufsize=0, + universal_newlines=False, ) as p: - stdout_thread = threading.Thread(target=read_stream, args=(p.stdout, logger.info)) - stderr_thread = threading.Thread(target=read_stream, args=(p.stderr, logger.info)) - stdout_thread.start() - stderr_thread.start() + def process_lines(text_io): + for line in iter(text_io.readline, ""): + text = line.rstrip("\n").strip() + custom_event(LogType.command_out, text) + if stdout_stderr is not None: + stdout_stderr.append(text) + if check_command_end(command_key, text): + break + + detected_encoding = "utf-8" + text_io = io.TextIOWrapper( + p.stdout, encoding=detected_encoding, errors="replace" + ) + try: + process_lines(text_io) + except UnicodeDecodeError: + p.stdout.seek(0) # 重新将流指针重置到开头 + text_io = io.TextIOWrapper( + p.stdout, encoding="gbk", errors="replace" + ) + process_lines(text_io) + finally: + text_io.close() - stdout_thread.join() - stderr_thread.join() if p.returncode == 0: return "success" + else: + error_message = parse_stderr("\n".join(stdout_stderr)) + custom_event(LogType.error, f"命令执行失败,{error_message}") + return "failed" except Exception as e: logger.exception(e) - custom_event(str(e)) - return "failed" + custom_event(LogType.error, str(e)) + return "failed" + + def add_instance(self): + return manager.add_instance() + + def delete_instance(self, path): + instances_dir = os.path.join(os.getcwd(), instances_folder_name) + abs_path = os.path.abspath(path) + if os.path.commonpath( + [abs_path, instances_dir] + ) == instances_dir and os.path.exists(abs_path): + shutil.rmtree(abs_path) + + def migrate_default_instance(self): + """迁移默认实例文件到新实例""" + source_path = os.path.join(os.getcwd(), "mower-ng") + return manager.migrate_instance(source_path) + + def migrate_instances_config(self): + """迁移多开配置""" + return manager.migrate_instances_config() + + def open_folder(self, path): + if not os.path.exists(path): + custom_event(LogType.error, f"路径不存在:{path}") + else: + os.startfile(path) + custom_event(LogType.info, f"成功打开文件夹:{path}") + + def test_base_url_connect(self): + url = build_base_url(get_new_version_url) + custom_event(LogType.info, f"开始测试URL连接:{url}") + try: + start_time = time.time() + response = requests.get(url) + end_time = time.time() + if response.status_code == 200: + elapsed_time_ms = (end_time - start_time) * 1000 + custom_event( + LogType.info, f"测试成功,响应时间为 {elapsed_time_ms:.2f} 毫秒" + ) + else: + custom_event( + LogType.error, f"测试失败: HTTP状态码 {response.status_code}" + ) + except requests.exceptions.RequestException as e: + custom_event(LogType.error, f"发生错误: {e}") + + def cli_control(self, command: str, path: str): + """ + 统一的CLI控制接口,用于执行指定命令并可选地指定工作目录。 + + :param command_str: 要执行的命令字符串或命令键(如 "status", "launch" 等) + :param path: 实例路径 + """ + if command not in cli_command: + custom_event( + LogType.error, + f"无效的命令字符串或命令键:{command},请检查输入。", + ) + return + try: + ret = self.run("cli", "mower-ng", {"command": command, "path": path}) + if command == "launch" and ret == "success": + self.run("cli", "mower-ng", {"command": "webui", "path": path}) + except Exception as e: + custom_event(LogType.error, f"{cli_command[command]} 失败 {repr(e)}") + + def batch_cli_control(self, command): + checked_instances = [ + instance for instance in config.conf.instances if instance.checked + ] + if not checked_instances: + custom_event(LogType.warning, "没有选中的实例") + return [{"status": False, "message": "No checked instances"}] + + for instance in checked_instances: + try: + custom_event(LogType.info, f"{instance.name} {cli_command[command]}") + self.cli_control(command, instance.path) + custom_event( + LogType.info, f"{instance.name} {cli_command[command]} 完成" + ) + except Exception as e: + custom_event( + LogType.error, + f"{instance.name} {cli_command[command]} 失败 {repr(e)}", + ) diff --git a/launcher/webview/events.py b/launcher/webview/events.py index a28fd4f..cb4d714 100644 --- a/launcher/webview/events.py +++ b/launcher/webview/events.py @@ -1,11 +1,32 @@ import json +from enum import Enum import launcher from launcher.log import logger -def custom_event(data): - logger.info(data) +class LogType(Enum): + info = "信息" + error = "错误" + execute_command = "执行命令" + command_out = "命令输出" + + +def custom_event(log_type, data): + data = f"[{log_type.value}] {data}" + + match log_type: + case LogType.info: + logger.info(data) + case LogType.error: + logger.error(data) + case LogType.execute_command: + logger.info(data) + case LogType.command_out: + logger.info(data) + case _: + logger.info(data) + data = json.dumps({"log": data + "\n"}) js = f"var event = new CustomEvent('log', {{detail: {data}}}); window.dispatchEvent(event);" launcher.webview.window.evaluate_js(js) diff --git a/requirements.in b/requirements.in new file mode 100644 index 0000000..e8f09e4 --- /dev/null +++ b/requirements.in @@ -0,0 +1,5 @@ +pywebview==5.1 +requests==2.32.3 +py7zr==0.22.0 +pydantic==2.10.3 +pyinstaller==6.11.1 diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..7dbbb07 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,80 @@ +# +# This file is autogenerated by pip-compile with Python 3.12 +# by the following command: +# +# pip-compile requirements.in +# +--index-url https://pypi.tuna.tsinghua.edu.cn/simple + +altgraph==0.17.4 + # via pyinstaller +annotated-types==0.7.0 + # via pydantic +bottle==0.13.2 + # via pywebview +brotli==1.1.0 + # via py7zr +certifi==2024.12.14 + # via requests +cffi==1.17.1 + # via clr-loader +charset-normalizer==3.4.0 + # via requests +clr-loader==0.2.7.post0 + # via pythonnet +idna==3.10 + # via requests +inflate64==1.0.0 + # via py7zr +multivolumefile==0.2.3 + # via py7zr +packaging==24.2 + # via + # pyinstaller + # pyinstaller-hooks-contrib +pefile==2023.2.7 + # via pyinstaller +proxy-tools==0.1.0 + # via pywebview +psutil==6.1.0 + # via py7zr +py7zr==0.22.0 + # via -r requirements.in +pybcj==1.0.2 + # via py7zr +pycparser==2.22 + # via cffi +pycryptodomex==3.21.0 + # via py7zr +pydantic==2.10.3 + # via -r requirements.in +pydantic-core==2.27.1 + # via pydantic +pyinstaller==6.11.1 + # via -r requirements.in +pyinstaller-hooks-contrib==2024.11 + # via pyinstaller +pyppmd==1.1.0 + # via py7zr +pythonnet==3.0.5 + # via pywebview +pywebview==5.1 + # via -r requirements.in +pywin32-ctypes==0.2.3 + # via pyinstaller +pyzstd==0.16.2 + # via py7zr +requests==2.32.3 + # via -r requirements.in +texttable==1.7.0 + # via py7zr +typing-extensions==4.12.2 + # via + # pydantic + # pydantic-core + # pywebview +urllib3==2.2.3 + # via requests + +# The following packages are considered to be unsafe in a requirements file: +# setuptools diff --git a/ui/package-lock.json b/ui/package-lock.json index 3e30e87..7010b68 100644 --- a/ui/package-lock.json +++ b/ui/package-lock.json @@ -8,6 +8,7 @@ "name": "ui", "version": "0.0.0", "dependencies": { + "highlight.js": "^11.11.1", "pinia": "^2.2.8", "vue": "^3.5.11" }, @@ -2075,11 +2076,9 @@ } }, "node_modules/highlight.js": { - "version": "11.10.0", - "resolved": "https://registry.npmjs.org/highlight.js/-/highlight.js-11.10.0.tgz", - "integrity": "sha512-SYVnVFswQER+zu1laSya563s+F8VDGt7o35d4utbamowvUNLLMovFqwCLSocpZTz3MgaSRA1IbqRWZv97dtErQ==", - "dev": true, - "license": "BSD-3-Clause", + "version": "11.11.1", + "resolved": "https://registry.npmmirror.com/highlight.js/-/highlight.js-11.11.1.tgz", + "integrity": "sha512-Xwwo44whKBVCYoliBQwaPvtd/2tYFkRQtXDWj1nackaV2JPXx3L0+Jvd8/qCJ2p+ML0/XVkJ2q+Mr+UVdpJK5w==", "engines": { "node": ">=12.0.0" } diff --git a/ui/package.json b/ui/package.json index 4e707b9..ccf202c 100644 --- a/ui/package.json +++ b/ui/package.json @@ -11,6 +11,7 @@ "format": "prettier --write src/" }, "dependencies": { + "highlight.js": "^11.11.1", "pinia": "^2.2.8", "vue": "^3.5.11" }, diff --git a/ui/src/App.vue b/ui/src/App.vue index be241cb..eb2e815 100644 --- a/ui/src/App.vue +++ b/ui/src/App.vue @@ -12,6 +12,10 @@ const loading = ref(true) const page = ref(null) let conf +function show_doc() { + window.open('https://hedgedoc.zhaozuohong.vip/s/LfSzK2n0K', '_blank') +} + async function init_version() { version.value = await pywebview.api.get_version() new_version.value = await pywebview.api.get_new_version() @@ -22,19 +26,27 @@ async function init_version() { async function initialize_config() { await configStore.load_config() conf = configStore.config - await init_version() loading.value = false + if (!conf.is_already_show_doc) { + show_doc() + conf.is_already_show_doc = true + } + await init_version() } -const log = ref('') +const log = ref([]) provide('log', log) const log_ele = ref(null) provide('log_ele', log_ele) -watch(log, () => { - nextTick(() => { - log_ele.value?.scrollTo({ position: 'bottom' }) - }) -}) +watch( + log, + () => { + nextTick(() => { + log_ele.value?.scrollTo({ position: 'bottom' }) + }) + }, + { deep: true } +) onMounted(() => { if (window.pywebview && pywebview.api) { @@ -45,12 +57,15 @@ onMounted(() => { }) } window.addEventListener('log', (e) => { - log.value += e.detail.log + log.value.push(e.detail.log) + if (log.value.length > 200) { + log.value.shift() + } }) }) function set_page(value) { - log.value = '' + log.value.splice(0) } const running = ref(false) @@ -81,6 +96,7 @@ provide('new_version', new_version) class="container" v-model:value="conf.page" @update:value="set_page" + justify-content="center" > @@ -88,13 +104,18 @@ provide('new_version', new_version) + @@ -106,4 +127,17 @@ provide('new_version', new_version) width: 100vw; height: 100vh; } +.suffix-container { + margin: 0 4px 6px 4px; +} +.tab-content { + position: relative; +} +.tag { + margin-left: 4px; + position: absolute; + top: 50%; + left: 100%; + transform: translateY(-50%); +} diff --git a/ui/src/components/BaseMirrorOption.vue b/ui/src/components/BaseMirrorOption.vue new file mode 100644 index 0000000..8d1037d --- /dev/null +++ b/ui/src/components/BaseMirrorOption.vue @@ -0,0 +1,30 @@ + + + + + diff --git a/ui/src/components/FloatButton.vue b/ui/src/components/FloatButton.vue index 06f16c1..de0ff86 100644 --- a/ui/src/components/FloatButton.vue +++ b/ui/src/components/FloatButton.vue @@ -11,7 +11,7 @@ const current_state = inject('current_state') const notification = useNotification() async function start() { - log.value = '' + log.value = [] running.value = true for (const [i, step] of steps.value.entries()) { current_step.value = i + 1 diff --git a/ui/src/components/LogComponent.vue b/ui/src/components/LogComponent.vue index 8b19c0d..b16c676 100644 --- a/ui/src/components/LogComponent.vue +++ b/ui/src/components/LogComponent.vue @@ -1,14 +1,57 @@ @@ -23,10 +66,8 @@ const log_ele = inject('log_ele') height: 100% !important; box-sizing: border-box; } - - diff --git a/ui/src/main.js b/ui/src/main.js index e8343a7..647f8a5 100644 --- a/ui/src/main.js +++ b/ui/src/main.js @@ -1,5 +1,5 @@ -import 'vfonts/Lato.css' import 'vfonts/FiraCode.css' +import './styles/global.css' import { createApp } from 'vue' import { createPinia } from 'pinia' diff --git a/ui/src/pages/Init.vue b/ui/src/pages/Init.vue index ac577ad..0120bfe 100644 --- a/ui/src/pages/Init.vue +++ b/ui/src/pages/Init.vue @@ -1,4 +1,6 @@ diff --git a/ui/src/pages/Settings.vue b/ui/src/pages/Settings.vue index cd21d17..89c3209 100644 --- a/ui/src/pages/Settings.vue +++ b/ui/src/pages/Settings.vue @@ -1,5 +1,7 @@