feat: 新增媒体排序组件,支持图片与视频的拖拽排序与上传,优化媒体查看器功能
This commit is contained in:
+406
-5
@@ -1,6 +1,7 @@
|
||||
"""artveris 脚本公共库:读取 YAML 配置、生成 .env、运行命令。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import socket
|
||||
import subprocess
|
||||
@@ -13,6 +14,42 @@ import yaml
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
SCRIPTS = ROOT / "scripts"
|
||||
IS_WINDOWS = os.name == "nt"
|
||||
# 本地启动偏好记忆(数据源选择 + 手动输入的连接信息)。不纳入 git。
|
||||
STATE_FILE = SCRIPTS / ".dev.local.json"
|
||||
|
||||
|
||||
def load_state() -> dict:
|
||||
"""读取本地启动偏好(不存在/损坏则返回空字典)。"""
|
||||
try:
|
||||
with open(STATE_FILE, "r", encoding="utf-8") as f:
|
||||
return json.load(f)
|
||||
except (OSError, json.JSONDecodeError):
|
||||
return {}
|
||||
|
||||
|
||||
def save_state(state: dict) -> None:
|
||||
try:
|
||||
with open(STATE_FILE, "w", encoding="utf-8", newline="\n") as f:
|
||||
json.dump(state, f, ensure_ascii=False, indent=2)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def ask(prompt_text: str, default: str = "") -> str:
|
||||
"""带默认值的输入:直接回车则采用默认值。"""
|
||||
suffix = f"(默认 {default})" if default != "" else "(可留空)"
|
||||
try:
|
||||
val = input(f"{prompt_text}{suffix}: ").strip()
|
||||
except EOFError:
|
||||
return default
|
||||
return val or default
|
||||
|
||||
|
||||
def is_interactive() -> bool:
|
||||
try:
|
||||
return sys.stdin is not None and sys.stdin.isatty()
|
||||
except Exception: # noqa: BLE001
|
||||
return False
|
||||
|
||||
|
||||
def load_config(path: Path | None = None) -> dict:
|
||||
@@ -91,15 +128,236 @@ def run(cmd: str, cwd: Path | None = None, check: bool = True) -> int:
|
||||
return proc.returncode
|
||||
|
||||
|
||||
def popen(cmd: str, cwd: Path | None = None) -> subprocess.Popen:
|
||||
_WIN: dict = {}
|
||||
|
||||
|
||||
def _winapi():
|
||||
"""初始化并缓存配置好签名的 Win32 函数(64 位下 HANDLE 必须显式声明,否则被截断为 32 位)。"""
|
||||
if _WIN:
|
||||
return _WIN["k32"], _WIN["ntdll"]
|
||||
import ctypes
|
||||
from ctypes import wintypes
|
||||
|
||||
k32 = ctypes.WinDLL("kernel32", use_last_error=True)
|
||||
ntdll = ctypes.WinDLL("ntdll", use_last_error=True)
|
||||
k32.CreateJobObjectW.restype = wintypes.HANDLE
|
||||
k32.CreateJobObjectW.argtypes = [wintypes.LPVOID, wintypes.LPCWSTR]
|
||||
k32.OpenProcess.restype = wintypes.HANDLE
|
||||
k32.OpenProcess.argtypes = [wintypes.DWORD, wintypes.BOOL, wintypes.DWORD]
|
||||
k32.AssignProcessToJobObject.restype = wintypes.BOOL
|
||||
k32.AssignProcessToJobObject.argtypes = [wintypes.HANDLE, wintypes.HANDLE]
|
||||
k32.SetInformationJobObject.restype = wintypes.BOOL
|
||||
k32.SetInformationJobObject.argtypes = [
|
||||
wintypes.HANDLE,
|
||||
ctypes.c_int,
|
||||
wintypes.LPVOID,
|
||||
wintypes.DWORD,
|
||||
]
|
||||
k32.CloseHandle.argtypes = [wintypes.HANDLE]
|
||||
_WIN.update(k32=k32, ntdll=ntdll, ctypes=ctypes, wintypes=wintypes)
|
||||
return k32, ntdll
|
||||
|
||||
|
||||
def create_kill_job():
|
||||
"""创建一个设置了 KILL_ON_JOB_CLOSE 的 Windows Job Object。
|
||||
将子进程加入该 Job 后,一旦本脚本进程结束(即使被强制结束、未走 finally),
|
||||
操作系统会自动终止 Job 内所有子进程,从根本上杜绝 nest/vite 残留。
|
||||
非 Windows 返回 None(用进程组 + killpg 处理)。"""
|
||||
if not IS_WINDOWS:
|
||||
return None
|
||||
try:
|
||||
k32, _ = _winapi()
|
||||
ctypes = _WIN["ctypes"]
|
||||
wintypes = _WIN["wintypes"]
|
||||
job = k32.CreateJobObjectW(None, None)
|
||||
if not job:
|
||||
return None
|
||||
|
||||
class _BASIC(ctypes.Structure):
|
||||
_fields_ = [
|
||||
("PerProcessUserTimeLimit", ctypes.c_int64),
|
||||
("PerJobUserTimeLimit", ctypes.c_int64),
|
||||
("LimitFlags", wintypes.DWORD),
|
||||
("MinimumWorkingSetSize", ctypes.c_size_t),
|
||||
("MaximumWorkingSetSize", ctypes.c_size_t),
|
||||
("ActiveProcessLimit", wintypes.DWORD),
|
||||
("Affinity", ctypes.c_void_p),
|
||||
("PriorityClass", wintypes.DWORD),
|
||||
("SchedulingClass", wintypes.DWORD),
|
||||
]
|
||||
|
||||
class _IO(ctypes.Structure):
|
||||
_fields_ = [(n, ctypes.c_uint64) for n in (
|
||||
"ReadOperationCount", "WriteOperationCount", "OtherOperationCount",
|
||||
"ReadTransferCount", "WriteTransferCount", "OtherTransferCount",
|
||||
)]
|
||||
|
||||
class _EXT(ctypes.Structure):
|
||||
_fields_ = [
|
||||
("BasicLimitInformation", _BASIC),
|
||||
("IoInfo", _IO),
|
||||
("ProcessMemoryLimit", ctypes.c_size_t),
|
||||
("JobMemoryLimit", ctypes.c_size_t),
|
||||
("PeakProcessMemoryUsed", ctypes.c_size_t),
|
||||
("PeakJobMemoryUsed", ctypes.c_size_t),
|
||||
]
|
||||
|
||||
JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE = 0x2000
|
||||
info = _EXT()
|
||||
info.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE
|
||||
if not k32.SetInformationJobObject(
|
||||
job, 9, ctypes.byref(info), ctypes.sizeof(info)
|
||||
):
|
||||
return None
|
||||
return job
|
||||
except Exception: # noqa: BLE001
|
||||
return None
|
||||
|
||||
|
||||
def _assign_and_resume(job, pid: int) -> None:
|
||||
"""把挂起创建的进程加入 Job 后再恢复运行。
|
||||
必须在进程派生任何子进程之前完成,才能确保其所有后代都纳入 Job。"""
|
||||
k32, ntdll = _winapi()
|
||||
PROCESS_TERMINATE = 0x0001
|
||||
PROCESS_SET_QUOTA = 0x0100
|
||||
PROCESS_SUSPEND_RESUME = 0x0800
|
||||
h = k32.OpenProcess(
|
||||
PROCESS_TERMINATE | PROCESS_SET_QUOTA | PROCESS_SUSPEND_RESUME, False, pid
|
||||
)
|
||||
if not h:
|
||||
return
|
||||
try:
|
||||
k32.AssignProcessToJobObject(job, h)
|
||||
finally:
|
||||
# 无论是否加入成功都必须恢复,否则进程会一直挂起
|
||||
ntdll.NtResumeProcess(h)
|
||||
k32.CloseHandle(h)
|
||||
|
||||
|
||||
CREATE_SUSPENDED = 0x00000004
|
||||
|
||||
|
||||
def popen(cmd: str, cwd: Path | None = None, job=None) -> subprocess.Popen:
|
||||
print(f"[artveris] 启动: {cmd}")
|
||||
return subprocess.Popen(cmd, cwd=str(cwd or ROOT), shell=True)
|
||||
kwargs: dict = {}
|
||||
if IS_WINDOWS:
|
||||
# 独立进程组:Ctrl+C 不直接乱传播给子进程,统一由脚本在退出时整树结束
|
||||
flags = subprocess.CREATE_NEW_PROCESS_GROUP
|
||||
if job:
|
||||
flags |= CREATE_SUSPENDED # 挂起创建,加入 Job 后再恢复,避免漏掉先派生的子进程
|
||||
kwargs["creationflags"] = flags
|
||||
else:
|
||||
kwargs["start_new_session"] = True # 便于用 killpg 整组结束
|
||||
proc = subprocess.Popen(cmd, cwd=str(cwd or ROOT), shell=True, **kwargs)
|
||||
if IS_WINDOWS and job:
|
||||
try:
|
||||
_assign_and_resume(job, proc.pid)
|
||||
except Exception: # noqa: BLE001
|
||||
# 兜底恢复,避免进程一直挂起
|
||||
try:
|
||||
k32, ntdll = _winapi()
|
||||
h = k32.OpenProcess(0x0800, False, proc.pid)
|
||||
if h:
|
||||
ntdll.NtResumeProcess(h)
|
||||
k32.CloseHandle(h)
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
return proc
|
||||
|
||||
|
||||
def stop_proc_tree(proc: subprocess.Popen) -> None:
|
||||
"""结束一个 popen 进程的整棵子树(含 pnpm -> nest/vite -> node)。"""
|
||||
try:
|
||||
if proc.poll() is not None:
|
||||
return
|
||||
if IS_WINDOWS:
|
||||
subprocess.run(
|
||||
f"taskkill /F /T /PID {proc.pid}", shell=True, capture_output=True
|
||||
)
|
||||
else:
|
||||
import signal
|
||||
|
||||
try:
|
||||
os.killpg(os.getpgid(proc.pid), signal.SIGTERM)
|
||||
except ProcessLookupError:
|
||||
pass
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
|
||||
|
||||
def stop_all(procs: list[subprocess.Popen]) -> None:
|
||||
for p in procs:
|
||||
stop_proc_tree(p)
|
||||
|
||||
|
||||
def install_console_ctrl_handler(cleanup) -> None:
|
||||
"""在 OS 层拦截 Ctrl+C / Ctrl+Break / 关闭终端 / 注销 / 关机 等事件,
|
||||
统一调用 cleanup 结束所有子进程。比依赖 Python 信号更可靠,且能覆盖"关闭窗口"。"""
|
||||
if not IS_WINDOWS:
|
||||
return
|
||||
import ctypes
|
||||
from ctypes import wintypes
|
||||
|
||||
HANDLER = ctypes.WINFUNCTYPE(wintypes.BOOL, wintypes.DWORD)
|
||||
|
||||
def _handler(ctrl_type): # 0=C 1=BREAK 2=CLOSE 5=LOGOFF 6=SHUTDOWN
|
||||
try:
|
||||
cleanup()
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
return ctrl_type in (0, 1) # C/Break 由我们处理;其余交还系统(子进程已清理)
|
||||
|
||||
cb = HANDLER(_handler)
|
||||
_WIN.setdefault("handlers", []).append(cb) # 持有引用,防止被 GC 回收
|
||||
k32, _ = _winapi()
|
||||
k32.SetConsoleCtrlHandler.argtypes = [HANDLER, wintypes.BOOL]
|
||||
k32.SetConsoleCtrlHandler.restype = wintypes.BOOL
|
||||
k32.SetConsoleCtrlHandler(cb, True)
|
||||
|
||||
|
||||
def _kill_tree_windows(pid: str) -> None:
|
||||
# /T 结束进程树(含 nest --watch 等监视器派生的子进程),避免端口被自动重启重新占用
|
||||
subprocess.run(f"taskkill /F /T /PID {pid}", shell=True, capture_output=True)
|
||||
|
||||
|
||||
def _free_port_psutil(port: int) -> bool:
|
||||
"""用 psutil 按端口定位进程,并结束其"监视父进程 + 整棵子树"。
|
||||
仅作用于真正监听该端口的进程及其 node 监视器,不影响 IDE 语言服务。"""
|
||||
try:
|
||||
import psutil # 延迟导入:仅 dev.py 声明该依赖
|
||||
except ImportError:
|
||||
return False
|
||||
for conn in psutil.net_connections(kind="inet"):
|
||||
try:
|
||||
if not (conn.laddr and conn.laddr.port == port):
|
||||
continue
|
||||
if conn.status != psutil.CONN_LISTEN or not conn.pid:
|
||||
continue
|
||||
proc = psutil.Process(conn.pid)
|
||||
root = proc
|
||||
parent = proc.parent()
|
||||
# nest start --watch / pnpm 会在子进程退出后重启:上溯到 node 父进程一并结束
|
||||
if parent and "node" in (parent.name() or "").lower():
|
||||
root = parent
|
||||
for child in root.children(recursive=True):
|
||||
try:
|
||||
child.kill()
|
||||
except psutil.Error:
|
||||
pass
|
||||
root.kill()
|
||||
print(f"[artveris] 释放端口 {port}(结束进程树 PID {root.pid})")
|
||||
except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
|
||||
continue
|
||||
return True
|
||||
|
||||
|
||||
def free_port(port: int) -> None:
|
||||
"""结束本机占用指定端口的进程(用于释放上次的 api/admin/h5 及被锁的 Prisma 引擎)。
|
||||
仅用于本地 node 进程,不要对 Docker 管理的端口使用。"""
|
||||
"""结束本机占用指定端口的进程(释放上次的 api/admin/h5,并解除对 Prisma 引擎 DLL 的占用)。
|
||||
仅用于本地 node 服务,不要对 Docker 管理的端口使用。"""
|
||||
try:
|
||||
if _free_port_psutil(port):
|
||||
return
|
||||
# 回退:psutil 不可用时用系统命令(taskkill /T 结束进程树)
|
||||
if IS_WINDOWS:
|
||||
out = subprocess.run(
|
||||
"netstat -ano -p tcp", capture_output=True, text=True, shell=True
|
||||
@@ -111,7 +369,7 @@ def free_port(port: int) -> None:
|
||||
if pid and pid != "0":
|
||||
pids.add(pid)
|
||||
for pid in pids:
|
||||
subprocess.run(f"taskkill /F /PID {pid}", shell=True, capture_output=True)
|
||||
_kill_tree_windows(pid)
|
||||
print(f"[artveris] 释放端口 {port}(结束 PID {pid})")
|
||||
else:
|
||||
out = subprocess.run(
|
||||
@@ -129,6 +387,85 @@ def free_ports(ports: list[int]) -> None:
|
||||
free_port(int(p))
|
||||
|
||||
|
||||
# 本项目本地服务的命令行特征:用于按命令行(而非端口)精准识别 nest/vite/api 进程,
|
||||
# 以便清理处于 idle 状态、当前并不监听端口的 `nest --watch` 监视器。
|
||||
_SERVER_MARKERS = (
|
||||
"nest",
|
||||
"vite",
|
||||
"dist\\main",
|
||||
"dist/main",
|
||||
"start:dev",
|
||||
"dev:api",
|
||||
"dev:admin",
|
||||
"dev:h5",
|
||||
"nodemon",
|
||||
)
|
||||
|
||||
|
||||
def _kill_project_psutil(root_lower: str) -> tuple[bool, int]:
|
||||
try:
|
||||
import psutil # 延迟导入:仅 dev.py 声明该依赖
|
||||
except ImportError:
|
||||
return False, 0
|
||||
killed = 0
|
||||
me = os.getpid()
|
||||
for proc in psutil.process_iter(["pid", "name", "cmdline"]):
|
||||
try:
|
||||
if proc.pid == me:
|
||||
continue
|
||||
name = (proc.info.get("name") or "").lower()
|
||||
if "node" not in name:
|
||||
continue
|
||||
cmd = " ".join(proc.info.get("cmdline") or []).lower()
|
||||
# 必须同时命中"项目路径"和"服务特征",避免误杀 IDE 的 tsserver/eslint 等
|
||||
if root_lower not in cmd:
|
||||
continue
|
||||
if not any(m in cmd for m in _SERVER_MARKERS):
|
||||
continue
|
||||
for child in proc.children(recursive=True):
|
||||
try:
|
||||
child.kill()
|
||||
except psutil.Error:
|
||||
pass
|
||||
proc.kill()
|
||||
killed += 1
|
||||
except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
|
||||
continue
|
||||
return True, killed
|
||||
|
||||
|
||||
def _kill_project_fallback(root_lower: str) -> None:
|
||||
if IS_WINDOWS:
|
||||
ps = (
|
||||
"Get-CimInstance Win32_Process | Where-Object { "
|
||||
"$_.Name -like 'node*' -and "
|
||||
f"$_.CommandLine -like '*{root_lower}*' -and "
|
||||
"($_.CommandLine -match 'nest|vite|dist.main|dev:') } | "
|
||||
"ForEach-Object { taskkill /F /T /PID $_.ProcessId } | Out-Null"
|
||||
)
|
||||
subprocess.run(
|
||||
["powershell", "-NoProfile", "-Command", ps], capture_output=True
|
||||
)
|
||||
else:
|
||||
for pat in ("nest start", "vite", "dist/main"):
|
||||
subprocess.run(f"pkill -f '{pat}'", shell=True, capture_output=True)
|
||||
|
||||
|
||||
def kill_project_servers(ports: list[int] | None = None, root: Path | None = None) -> None:
|
||||
"""清理本项目残留的本地服务进程(nest/vite/api 及其子进程)。
|
||||
按命令行特征识别,可清掉处于 idle、当前未监听端口的 `nest --watch` 监视器,
|
||||
从根本上避免下次启动时被其自动重启抢占端口(EADDRINUSE)。"""
|
||||
root_lower = str(root or ROOT).lower()
|
||||
ok, killed = _kill_project_psutil(root_lower)
|
||||
if ok:
|
||||
if killed:
|
||||
print(f"[artveris] 已清理 {killed} 个残留服务进程(nest/vite/api)")
|
||||
else:
|
||||
_kill_project_fallback(root_lower)
|
||||
if ports:
|
||||
free_ports(ports) # 端口兜底:防止非 node 进程或漏网者占用
|
||||
|
||||
|
||||
def run_retry(cmd: str, cwd: Path | None = None, attempts: int = 4, delay: float = 2.0) -> bool:
|
||||
"""运行命令,失败自动重试(用于规避偶发文件锁,如 Prisma 引擎 DLL 占用)。"""
|
||||
for i in range(attempts):
|
||||
@@ -152,3 +489,67 @@ def wait_port(host: str, port: int, timeout: int = 60) -> bool:
|
||||
time.sleep(1.5)
|
||||
print(f"[artveris] 等待 {host}:{port} 超时")
|
||||
return False
|
||||
|
||||
|
||||
def ensure_mysql_database(
|
||||
host: str, port, user: str, password: str, db_name: str
|
||||
) -> bool:
|
||||
"""连接已有 MySQL,确保目标库存在(不存在则以 utf8mb4 创建)。
|
||||
用于"手动连接已有 MySQL"模式,使外部库也能零手工。
|
||||
- 库已存在:直接返回 True(不需要建库权限)。
|
||||
- 库不存在:尝试创建(需账号有 CREATE 权限),失败给出可手动执行的 SQL 提示。"""
|
||||
import re
|
||||
|
||||
if not re.fullmatch(r"[A-Za-z0-9_]+", db_name or ""):
|
||||
print(f"[artveris] 数据库名非法:{db_name!r}(仅允许字母/数字/下划线),跳过自动建库。")
|
||||
return False
|
||||
try:
|
||||
import pymysql
|
||||
except ImportError:
|
||||
print("[artveris] 未安装 pymysql,跳过自动建库(请确保目标库已存在)。")
|
||||
return False
|
||||
|
||||
create_sql = (
|
||||
f"CREATE DATABASE IF NOT EXISTS `{db_name}` "
|
||||
"CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci"
|
||||
)
|
||||
manual_hint = f"[artveris] 可用有权限的账号手动执行:{create_sql};"
|
||||
|
||||
# 1) 先看库是否已存在(连接时指定 database)
|
||||
try:
|
||||
conn = pymysql.connect(
|
||||
host=host, port=int(port), user=user, password=password,
|
||||
database=db_name, connect_timeout=8, charset="utf8mb4",
|
||||
)
|
||||
conn.close()
|
||||
print(f"[artveris] 数据库已存在:{db_name}")
|
||||
return True
|
||||
except pymysql.err.OperationalError as e:
|
||||
code = e.args[0] if e.args else None
|
||||
if code != 1049: # 1049 = Unknown database;其它多为认证/网络问题
|
||||
print(f"[artveris] 连接 MySQL 失败({user}@{host}:{port}):{e}")
|
||||
print(manual_hint)
|
||||
return False
|
||||
except Exception as e: # noqa: BLE001
|
||||
print(f"[artveris] 连接 MySQL 失败({user}@{host}:{port}):{e}")
|
||||
print(manual_hint)
|
||||
return False
|
||||
|
||||
# 2) 库不存在 → 尝试创建
|
||||
try:
|
||||
conn = pymysql.connect(
|
||||
host=host, port=int(port), user=user, password=password,
|
||||
connect_timeout=8, charset="utf8mb4",
|
||||
)
|
||||
try:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(create_sql)
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
print(f"[artveris] 已创建数据库:{db_name}(utf8mb4)")
|
||||
return True
|
||||
except Exception as e: # noqa: BLE001
|
||||
print(f"[artveris] 自动建库失败(账号可能无 CREATE 权限):{e}")
|
||||
print(manual_hint)
|
||||
return False
|
||||
|
||||
Reference in New Issue
Block a user