launcher/launcher.py

173 lines
6 KiB
Python
Raw Normal View History

import io
2024-09-23 16:12:34 +08:00
import json
import mimetypes
import os
import shutil
import subprocess
import threading
2024-09-23 16:12:34 +08:00
from pathlib import Path
2024-10-10 10:15:20 +08:00
from shutil import rmtree
from subprocess import CREATE_NO_WINDOW, Popen
2024-11-30 20:54:48 +08:00
import requests
2024-09-23 16:12:34 +08:00
import webview
2024-12-02 22:34:54 +08:00
from launcher import config
2024-11-30 20:54:48 +08:00
from log import logger
mimetypes.add_type("text/html", ".html")
mimetypes.add_type("text/css", ".css")
mimetypes.add_type("application/javascript", ".js")
2024-12-08 20:46:44 +08:00
version = "v0.3"
2024-12-02 12:04:08 +08:00
get_new_version_url = (
"https://git.zhaozuohong.vip/api/v1/repos/mower-ng/launcher/releases/latest"
)
2024-11-30 20:54:48 +08:00
upgrade_script_name = "upgrade.bat"
2024-10-10 10:15:20 +08:00
2024-09-23 19:42:56 +08:00
def custom_event(data):
data = json.dumps({"log": data})
2024-09-23 16:12:34 +08:00
js = f"var event = new CustomEvent('log', {{detail: {data}}}); window.dispatchEvent(event);"
window.evaluate_js(js)
2024-11-30 20:54:48 +08:00
2024-10-10 09:48:57 +08:00
mirror_list = {
"pypi": "https://pypi.org/simple",
"aliyun": "https://mirrors.aliyun.com/pypi/simple/",
2024-10-10 09:48:57 +08:00
"tuna": "https://mirrors.tuna.tsinghua.edu.cn/pypi/web/simple",
"sjtu": "https://mirror.sjtu.edu.cn/pypi/web/simple",
}
2024-09-23 19:14:57 +08:00
command_list = {
2024-09-23 19:42:56 +08:00
"lfs": "git\\bin\\git lfs install",
2024-09-23 20:03:52 +08:00
"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",
"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",
2024-09-23 19:14:57 +08:00
"webview": "start ..\\python\\pythonw webview_ui.py",
"manager": "start ..\\python\\pythonw manager.py",
}
def read_stream(stream, log_func):
text_io = io.TextIOWrapper(stream, encoding='utf-8', errors='replace')
try:
for line in iter(text_io.readline, ''):
text = line.rstrip('\n')
log_func(f"log: {text}")
custom_event(text.strip() + "\n")
finally:
text_io.close()
2024-09-23 16:12:34 +08:00
class Api:
2024-12-02 22:34:54 +08:00
def load_config(self):
logger.info("读取配置文件")
return config.conf.model_dump()
2024-09-23 16:12:34 +08:00
2024-12-02 22:34:54 +08:00
def save_config(self, conf):
logger.info(f"更新配置文件{conf}")
config.conf = config.Conf(**conf)
config.save_conf()
2024-10-10 09:48:57 +08:00
2024-11-30 20:54:48 +08:00
def get_version(self):
return version
def get_new_version(self):
logger.info("获取最新版本号")
response = requests.get(get_new_version_url)
return response.json()
# 更新启动器本身
def update_self(self, download_url):
# 下载压缩包的全路径
download_path = os.path.join(os.getcwd(), os.path.basename(download_url))
logger.info(f"下载新版本: {download_url}{download_path}")
2024-11-30 20:54:48 +08:00
response = requests.get(download_url, stream=True)
if response.status_code == 200:
2024-12-02 12:04:08 +08:00
with open(download_path, "wb") as file:
2024-11-30 20:54:48 +08:00
shutil.copyfileobj(response.raw, file)
logger.info("下载完成")
2024-11-30 20:54:48 +08:00
else:
logger.error(f"下载新版本失败: {response.status_code}")
return f"下载新版本失败: {response.status_code}"
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")
2024-12-02 12:04:08 +08:00
with open(script_path, "w") as b:
TempList = f"@echo off\n"
TempList += f"timeout /t 3 /nobreak\n" # 等待进程退出
TempList += f"rmdir {folder_path}\n" # 删除_internal
TempList += f"del {exe_path}\n" # 删除exe
TempList += f"tar -xf {download_path} -C ..\n" # 解压压缩包
TempList += f"timeout /t 1 /nobreak\n" # 等待解压
TempList += f"start {exe_path}\n" # 启动新程序
TempList += f"del {download_path}\n" # 删除压缩包
TempList += f"exit"
b.write(TempList)
# 不显示cmd窗口
2024-12-02 12:04:08 +08:00
Popen([script_path], creationflags=CREATE_NO_WINDOW)
os._exit(0)
2024-10-10 10:15:20 +08:00
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目录移除成功"
2024-10-10 10:15:20 +08:00
return "python\\Lib\\site-packages目录不存在"
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目录不存在"
2024-09-23 16:12:34 +08:00
def run(self, command, cwd=None):
2024-09-23 19:42:56 +08:00
command = command_list[command]
2024-10-10 09:48:57 +08:00
if callable(command):
command = command()
2024-09-23 19:42:56 +08:00
custom_event(command + "\n")
logger.info(f"cwd {cwd}")
logger.info(f"command {command}")
2024-10-10 10:48:01 +08:00
try:
with subprocess.Popen(
command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True, cwd=cwd, bufsize=0,
universal_newlines=False
2024-10-10 10:48:01 +08:00
) as p:
stdout_thread = threading.Thread(target=read_stream, args=(p.stdout, logger.info))
2024-12-08 20:46:44 +08:00
stderr_thread = threading.Thread(target=read_stream, args=(p.stderr, logger.info))
stdout_thread.start()
stderr_thread.start()
stdout_thread.join()
stderr_thread.join()
2024-10-10 10:48:01 +08:00
if p.returncode == 0:
return "success"
except Exception as e:
logger.error(f"command {command} 执行异常{e}")
logger.exception(e)
2024-10-10 10:48:01 +08:00
custom_event(str(e))
return "failed"
2024-09-23 16:12:34 +08:00
2024-11-30 20:54:48 +08:00
# 如果当前路径存在更新脚本,则删除
if Path(upgrade_script_name).exists():
os.remove(upgrade_script_name)
2024-09-23 16:12:34 +08:00
2024-12-02 22:34:54 +08:00
# url = "ui/dist/index.html"
url = "http://localhost:5173/"
2024-12-02 12:04:08 +08:00
window = webview.create_window(
2024-12-02 22:34:54 +08:00
f"mower-ng launcher {version}", url, js_api=Api()
2024-12-02 12:04:08 +08:00
)
2024-09-23 20:35:05 +08:00
webview.start()