Skip to content

Commit

Permalink
Merge pull request #2 from kanbereina/dev
Browse files Browse the repository at this point in the history
更新指令更新LLOB功能
  • Loading branch information
kanbereina authored Aug 27, 2024
2 parents 4ed7647 + 55f7e9e commit 14c2059
Show file tree
Hide file tree
Showing 8 changed files with 180 additions and 26 deletions.
149 changes: 143 additions & 6 deletions nonebot_plugin_llob_master/__main__.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,143 @@
import asyncio
from time import time
from datetime import datetime, timedelta

from nonebot import on_command
from nonebot.log import logger
from nonebot.params import ArgPlainText
from nonebot.permission import SUPERUSER
from nonebot.adapters.onebot.v11 import MessageEvent
from nonebot_plugin_apscheduler import scheduler

from .config import Driver
from .config import Driver, PluginConfig
from .utils import (
ntqq_update_checker, llob_update_checker, ntqq_start_checker,
get_ntqq_proc, ntqq_restart
get_ntqq_proc, ntqq_restart,
is_llob_installing, set_llob_install_status
)
# 指令更新
from .utils.llob.llob import LLOB
from .utils.llob.llob_path import LLOBPath
from .utils.llob.llob_install import llob_auto_install


update_llob = on_command(
"检查更新",
permission=SUPERUSER, block=True,
aliases={"检查LLOB更新", "更新LLOB"}
)


@update_llob.handle()
async def check_llob_update(event: MessageEvent):
await update_llob.send("正在检查更新中,请稍后...")
logger.info(f"用户(ID: {event.get_user_id()})触发了LLOB版本更新检查, 正在执行任务...")

try: # 获取当前LLOB版本信息
llqqnt_path = LLOBPath.get_llqqnt_path()
llob_path = LLOBPath.get_llob_path(path=llqqnt_path)
llob_version = LLOBPath.get_llob_version(path=llob_path)
logger.info(f"当前LLOB版本: {llob_version}")
except Exception as e:
await update_llob.finish(
f"检查当前LLOB版本失败: {e.__class__.__name__}(\n"
f"{', '.join(e.args)}\n"
")"
)
raise e # 防IDE若智检查

logger.debug("正在检查LLOB版本更新...")
try:
latest_version = await LLOB.get_latest_version(
api_url="https://api.github.com/repos/LLOneBot/LLOneBot/releases/latest"
)
except Exception:
logger.warning("无法访问GitHub, 尝试使用备用URL")
try:
latest_version = await LLOB.get_latest_version(
api_url="https://api.hydroroll.team/api/version?repo=LLOneBot/LLOneBot&type=github-releases-latest"
)
except Exception as e:
await update_llob.finish(
f"检查最新LLOB版本失败: {e.__class__.__name__}(\n"
f"{', '.join(e.args)}\n"
")"
)
raise e # 防IDE若智检查

# 检查是否有更新
if not LLOB.check_update(llob_version, latest_version):
await update_llob.finish(f"当前版本(v{llob_version})已为最新!")

logger.info(f"检测到LLOB有新版本: v{llob_version} => v{latest_version}")
await update_llob.send(
"检测到LLOB版本更新:\n"
f"v{llob_version} => v{latest_version}\n"
"\n"
"是否安装此次更新(是/否):"
)


@update_llob.got(key="choice")
async def check_choice(event: MessageEvent, choice: str = ArgPlainText()):
uid = event.get_user_id()

if choice != "是":
logger.info(f"用户(ID: {uid})取消安装此次LLOB更新")
await update_llob.finish("未进行确认,已取消此次操作。")

logger.info(f"用户(ID: {uid})确认安装此次LLOB更新")

result = "(已启用“断连重启”,安装完成后将自动重启!)" if (
PluginConfig.lm_enable_auto_restart
) else "(未启用“断连重启”,安装完成后请手动重启!)"
await update_llob.send(
"即将安装更新,安装过程中Bot将会下线!\n"
f"{result}"
)


@update_llob.handle()
async def install_latest_llob():
async def wait_for_bot_connect(max_time: int = 20):
"""等待Bot重连"""
start_time = time()
while True:
# 检查是否处于安装状态
if not is_llob_installing():
break

# 检查是否超时
end_time = time()
if (end_time - start_time) > max_time:
raise TimeoutError("等待NTQQ重连失败, 安装LLOB可能未成功!")
await asyncio.sleep(1)

# 设置当前指令安装LLOB状态
set_llob_install_status(value=True)

# 开始关闭NTQQ进程
ntqq_process = get_ntqq_proc()
ntqq_process.close()
await asyncio.sleep(3) # 防止假关闭进程

# 开始安装LLOB
result = await llob_auto_install() is not None

if PluginConfig.lm_enable_auto_restart: # 允许断连重启
# 重启NTQQ进程
await ntqq_restart()

# 等待重连
await wait_for_bot_connect()
msg = "更新已完成,Bot已重启。" if result else "更新失败,但Bot正常重启。"
await update_llob.finish(msg)

else:
if result:
logger.success("安装新版本LLOB成功, 请手动重启NTQQ!")
else:
logger.error("安装新版本LLOB失败, 请检查日志输出!")


@Driver.on_startup
Expand All @@ -24,6 +153,9 @@ async def start():

@Driver.on_bot_connect
async def handle_window():
if is_llob_installing(): # 安装完成
set_llob_install_status(value=False) # 还原状态

ntqq_proc = get_ntqq_proc()
# Bot连接时最小化NTQQ窗口
if ntqq_proc is not None:
Expand All @@ -42,10 +174,15 @@ async def restart_ntqq():
ntqq_proc = get_ntqq_proc()
# Bot断连后数秒后进行重连
if ntqq_proc is not None:
scheduler.add_job( # 防一直处于on_bot_disconnect状态, 并防止shutdown的时候无法立即停止
ntqq_restart, "date",
next_run_time=datetime.now() + timedelta(seconds=1)
)

# 检查是否正在指令更新LLOB, 若为该状态则忽略此次断连重启
if not is_llob_installing():
scheduler.add_job( # 防一直处于on_bot_disconnect状态, 并防止shutdown的时候无法立即停止
ntqq_restart, "date",
next_run_time=datetime.now() + timedelta(seconds=1)
)
else:
logger.info("正在指令更新LLOB, 忽略此次断连重启")


@Driver.on_shutdown
Expand Down
3 changes: 2 additions & 1 deletion nonebot_plugin_llob_master/utils/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from .ntqq import (
ntqq_update_checker, ntqq_start_checker,
NTQQProcess, get_ntqq_proc, ntqq_restart
NTQQProcess, get_ntqq_proc, ntqq_restart,
is_llob_installing, set_llob_install_status
)
from .llob import llob_update_checker
5 changes: 1 addition & 4 deletions nonebot_plugin_llob_master/utils/llob/llob.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,10 +42,7 @@ def check_update(
latest_version: LLOB_Version
) -> bool:
"""检测LLOB是否有更新"""
if now_version != latest_version:
return True

return False
return now_version != latest_version


__all__ = ["LLOB"]
1 change: 0 additions & 1 deletion nonebot_plugin_llob_master/utils/llob/llob_install.py
Original file line number Diff line number Diff line change
Expand Up @@ -250,7 +250,6 @@ async def llob_auto_install() -> Optional[LLOB_DataPath]:
llob_data_path = LLOBInstaller.install_llob(
zip_data=llob_zip, llqqnt_path=llqqnt_path
)
logger.success("LLOB安装完成")

except Exception as e:
logger.error(f"安装LLOB失败: {e.__class__.__name__}{e.args}")
Expand Down
5 changes: 4 additions & 1 deletion nonebot_plugin_llob_master/utils/ntqq/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
from .ntqq_update_main import ntqq_update_checker, NTQQUpdater
from .ntqq_process import NTQQProcess
from .ntqq_restart_main import ntqq_start_checker, get_ntqq_proc, ntqq_restart
from .ntqq_restart_main import (
ntqq_start_checker, get_ntqq_proc, ntqq_restart,
is_llob_installing, set_llob_install_status
)
5 changes: 1 addition & 4 deletions nonebot_plugin_llob_master/utils/ntqq/ntqq.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,10 +56,7 @@ def check_update(
latest: NTQQVersion
) -> bool:
"""检测NTQQ是否有更新"""
if (now.main + now.build) != (latest.main + latest.build):
return True

return False
return (now.main + now.build) != (latest.main + latest.build)


__all__ = ["NTQQ"]
36 changes: 28 additions & 8 deletions nonebot_plugin_llob_master/utils/ntqq/ntqq_restart_main.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,20 @@

NTQQ_Process: Optional[NTQQProcess] = None
NTQQ_Path: Optional[Path] = None
IsInstalling: Optional[bool] = False


def is_llob_installing() -> bool:
"""检查是否正在指令安装LLOB"""
global IsInstalling
return IsInstalling


def set_llob_install_status(value: bool):
"""设置安装状态"""
global IsInstalling
assert IsInstalling is not value, f"当前状态已为'{value}'!"
IsInstalling = value


def get_ntqq_proc() -> Optional[NTQQProcess]:
Expand Down Expand Up @@ -39,16 +53,19 @@ def ntqq_start_checker(ntqq_path: Path):
async def ntqq_restart():
"""重启NTQQ"""
global NTQQ_Process, NTQQ_Path
assert NTQQ_Process is not None, "进程信息为空!"
assert NTQQ_Path is not None, "NTQQ路径为空!"

# 关闭进程
NTQQ_Process.close()
NTQQ_Process = None
# 检查是否在指令安装状态, 若为该状态则直接启动NTQQ
if not is_llob_installing():
# 正常断线重连
assert NTQQ_Process is not None, "进程信息为空!"
# 关闭进程
NTQQ_Process.close()
NTQQ_Process = None

restart_time = PluginConfig.lm_restart_time
logger.info(f"将在Bot断连 {restart_time} 秒后尝试重启NTQQ...")
await asyncio.sleep(restart_time)
restart_time = PluginConfig.lm_restart_time
logger.info(f"将在Bot断连 {restart_time} 秒后尝试重启NTQQ...")
await asyncio.sleep(restart_time)

# 启动进程
ntqq_process = NTQQProcess(NTQQ_Path)
Expand All @@ -58,4 +75,7 @@ async def ntqq_restart():
logger.error("启动NTQQ进程失败, 请检查日志输出!")


__all__ = ["ntqq_start_checker", "get_ntqq_proc", "ntqq_restart"]
__all__ = [
"ntqq_start_checker", "get_ntqq_proc", "ntqq_restart",
"set_llob_install_status", "is_llob_installing"
]
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[project]
name = "nonebot_plugin_llob_master"
version = "1.0.3"
version = "1.1.0"
description = "Support for managing your LLOB on Windows"
authors = [
{name = "KanbeReina", email = "kano.2525@qq.com"},
Expand Down

0 comments on commit 14c2059

Please sign in to comment.