feat: 添加后端版本号接口

This commit is contained in:
DLmaster361
2025-09-09 21:00:11 +08:00
parent 3490eff76e
commit e3c1143c0c
8 changed files with 76 additions and 395 deletions

View File

@@ -28,6 +28,34 @@ from app.models.schema import *
router = APIRouter(prefix="/api/info", tags=["信息获取"])
@router.post(
"/version",
summary="获取后端git版本信息",
response_model=VersionOut,
status_code=200,
)
async def get_git_version() -> VersionOut:
try:
is_latest, commit_hash, commit_time = await Config.get_git_version()
except Exception as e:
return VersionOut(
code=500,
status="error",
message=f"{type(e).__name__}: {str(e)}",
if_latest=False,
current_hash="",
current_time="",
current_version="",
)
return VersionOut(
if_latest=is_latest,
current_hash=commit_hash,
current_time=commit_time,
current_version=Config.version(),
)
@router.post(
"/combox/stage",
summary="获取关卡号下拉框信息",

View File

@@ -28,11 +28,11 @@ import sqlite3
import calendar
import requests
import truststore
from git import Repo
from pathlib import Path
from fastapi import WebSocket
from urllib.parse import quote
from collections import defaultdict
from datetime import datetime, timedelta, date, timezone
from datetime import datetime, timedelta, date
from typing import Literal, Optional
from app.models.ConfigBase import *
@@ -597,6 +597,7 @@ class AppConfig(GlobalConfig):
self.config_path.mkdir(parents=True, exist_ok=True)
self.history_path.mkdir(parents=True, exist_ok=True)
self.repo = Repo(Path.cwd())
self.server: Optional[uvicorn.Server] = None
self.websocket: Optional[WebSocket] = None
self.silence_dict: Dict[Path, datetime] = {}
@@ -908,6 +909,26 @@ class AppConfig(GlobalConfig):
else:
await Config.websocket.send_json(data)
async def get_git_version(self) -> tuple[bool, str, str]:
# 获取当前 commit
current_commit = self.repo.head.commit
# 获取 commit 哈希
commit_hash = current_commit.hexsha
# 获取 commit 时间
commit_time = datetime.fromtimestamp(current_commit.committed_date)
# 检查是否为最新 commit
# 获取远程分支的最新 commit
origin = self.repo.remotes.origin
origin.fetch() # 拉取最新信息
remote_commit = self.repo.commit(f"origin/{self.repo.active_branch.name}")
is_latest = bool(current_commit.hexsha == remote_commit.hexsha)
return is_latest, commit_hash, commit_time.strftime("%Y-%m-%d %H:%M:%S")
async def add_script(
self, script: Literal["MAA", "General"]
) -> tuple[uuid.UUID, ConfigBase]:

View File

@@ -34,6 +34,13 @@ class InfoOut(OutBase):
data: Dict[str, Any] = Field(..., description="收到的服务器数据")
class VersionOut(OutBase):
if_latest: bool = Field(..., description="后端代码是否为最新")
current_hash: str = Field(..., description="后端代码当前哈希值")
current_time: str = Field(..., description="后端代码当前时间戳")
current_version: str = Field(..., description="后端当前版本号")
class NoticeOut(OutBase):
if_need_show: bool = Field(..., description="是否需要显示公告")
data: Dict[str, str] = Field(

View File

@@ -22,6 +22,7 @@
import re
import time
import json
import asyncio
import zipfile
import requests
import subprocess
@@ -209,7 +210,7 @@ class _UpdateHandler:
f"连接失败: {download_url}, 状态码: {response.status_code}, 剩余重试次数: {check_times}"
)
time.sleep(1)
await asyncio.sleep(1)
continue
logger.info(f"连接成功: {download_url}, 状态码: {response.status_code}")
@@ -225,17 +226,6 @@ class _UpdateHandler:
f.write(chunk)
downloaded_size += len(chunk)
await Config.send_json(
WebSocketMessage(
id="Update",
type="Update",
data={
"downloaded_size": downloaded_size,
"file_size": file_size,
"speed": speed,
},
).model_dump()
)
# 更新指定线程的下载进度, 每秒更新一次
if time.time() - last_time >= 1.0:
@@ -247,6 +237,18 @@ class _UpdateHandler:
last_download_size = downloaded_size
last_time = time.time()
await Config.send_json(
WebSocketMessage(
id="Update",
type="Update",
data={
"downloaded_size": downloaded_size,
"file_size": file_size,
"speed": speed,
},
).model_dump()
)
(Path.cwd() / "download.temp").rename(
Path.cwd() / f"UpdatePack_{self.remote_version}.zip"
)
@@ -276,7 +278,7 @@ class _UpdateHandler:
logger.info(
f"下载出错: {download_url}, 错误信息: {e}, 剩余重试次数: {check_times}"
)
time.sleep(1)
await asyncio.sleep(1)
else:

View File

@@ -249,7 +249,7 @@ async def skland_sign_in(token) -> dict:
f"{character.get("nickName")}{character.get("channelName")}"
)
time.sleep(3)
await asyncio.sleep(3)
return result