1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385
| from __future__ import annotations
import json import queue import sys import tempfile import threading import zipfile from dataclasses import asdict, dataclass from pathlib import Path from typing import Callable, Sequence
import requests import tkinter as tk from tkinter import filedialog, messagebox, ttk from tkinter.scrolledtext import ScrolledText
APP_TITLE = "博客发布助手"
def application_directory() -> Path: """Return the script directory, or the executable directory after packaging.""" if getattr(sys, "frozen", False): return Path(sys.executable).resolve().parent return Path(__file__).resolve().parent
CONFIG_FILE = application_directory() / "blog_deployer_config.json" DEFAULT_LOGIN_URL = "http://upload.g01den.top/admin" DEFAULT_UPLOAD_URL = "http://upload.g01den.top/upload" REQUEST_TIMEOUT = (10, 300)
@dataclass class BlogConfig: name: str path: str option: str
DEFAULT_BLOGS = [ BlogConfig("主博客", r"D:\c\blogs\hexo1\public", "blog1"), BlogConfig("副博客", r"D:\c\blogs\hexo2\public", "blog2"), ]
def load_settings() -> dict: defaults = { "login_url": DEFAULT_LOGIN_URL, "upload_url": DEFAULT_UPLOAD_URL, "username": "admin", "password": "", "blogs": [asdict(item) for item in DEFAULT_BLOGS], } if not CONFIG_FILE.exists(): return defaults try: saved = json.loads(CONFIG_FILE.read_text(encoding="utf-8")) if isinstance(saved, dict): defaults.update({key: saved[key] for key in defaults.keys() & saved.keys()}) except (OSError, json.JSONDecodeError): pass return defaults
def save_settings(settings: dict) -> None: """Persist all GUI settings, including the password requested by the user.""" CONFIG_FILE.write_text( json.dumps(settings, ensure_ascii=False, indent=2), encoding="utf-8" )
class BlogDeployer: def __init__(self, login_url: str, upload_url: str, username: str, password: str): self.login_url = login_url self.upload_url = upload_url self.username = username self.password = password self.session = requests.Session()
def login(self) -> None: response = self.session.post( self.login_url, data={"username": self.username, "password": self.password}, timeout=REQUEST_TIMEOUT, ) response.raise_for_status() if not self.session.cookies: raise RuntimeError("登录响应中没有 Cookie,请检查用户名、密码和登录地址。")
@staticmethod def create_archive(source: Path, destination: Path) -> int: if not source.is_dir(): raise FileNotFoundError(f"目录不存在:{source}")
file_count = 0 with zipfile.ZipFile( destination, "w", compression=zipfile.ZIP_DEFLATED, compresslevel=6 ) as archive: for item in source.rglob("*"): if item.is_file(): archive.write(item, item.relative_to(source)) file_count += 1 if not file_count: raise ValueError(f"目录中没有可发布的文件:{source}") return file_count
def upload(self, archive_path: Path, option: str) -> str: with archive_path.open("rb") as archive: response = self.session.post( self.upload_url, files={"file": (archive_path.name, archive, "application/zip")}, data={"option": option}, timeout=REQUEST_TIMEOUT, ) response.raise_for_status() return response.text.strip() or "服务器未返回消息"
def deploy(self, blogs: Sequence[BlogConfig], log: Callable[[str], None]) -> None: log("正在登录服务器...") self.login() log("登录成功。")
for index, blog in enumerate(blogs, start=1): source = Path(blog.path).expanduser().resolve() log(f"[{index}/{len(blogs)}] 正在打包 {blog.name}...") temporary_path: Path | None = None try: with tempfile.NamedTemporaryFile( prefix="blog_deployer_", suffix=".zip", delete=False ) as temporary: temporary_path = Path(temporary.name) count = self.create_archive(source, temporary_path) size_mb = temporary_path.stat().st_size / 1024 / 1024 log(f"已打包 {count} 个文件,共 {size_mb:.2f} MB。") log(f"正在上传 {blog.name},请稍候...") result = self.upload(temporary_path, blog.option) log(f"{blog.name} 发布成功:{result}") finally: if temporary_path is not None: temporary_path.unlink(missing_ok=True)
class BlogRow: def __init__(self, parent: ttk.Frame, row: int, config: BlogConfig): self.enabled = tk.BooleanVar(value=True) self.name = tk.StringVar(value=config.name) self.path = tk.StringVar(value=config.path) self.option = tk.StringVar(value=config.option)
ttk.Checkbutton(parent, variable=self.enabled).grid(row=row, column=0, padx=(4, 2)) ttk.Entry(parent, textvariable=self.name, width=12).grid( row=row, column=1, padx=4, pady=6, sticky="ew" ) ttk.Entry(parent, textvariable=self.path).grid( row=row, column=2, padx=4, pady=6, sticky="ew" ) ttk.Button(parent, text="浏览...", command=self.choose_directory).grid( row=row, column=3, padx=4 ) ttk.Entry(parent, textvariable=self.option, width=13).grid( row=row, column=4, padx=4, pady=6, sticky="ew" )
def choose_directory(self) -> None: directory = filedialog.askdirectory(initialdir=self.path.get() or None) if directory: self.path.set(directory)
def get_config(self) -> BlogConfig: return BlogConfig( self.name.get().strip(), self.path.get().strip(), self.option.get().strip() )
class DeployerApp(tk.Tk): def __init__(self) -> None: super().__init__() self.title(APP_TITLE) self.geometry("850x650") self.minsize(720, 560) self._events: queue.Queue[tuple[str, object]] = queue.Queue() self._worker: threading.Thread | None = None self._build_ui(load_settings()) self.after(100, self._process_events)
def _build_ui(self, settings: dict) -> None: self.columnconfigure(0, weight=1) self.rowconfigure(2, weight=1) style = ttk.Style(self) if "vista" in style.theme_names(): style.theme_use("vista") style.configure("Title.TLabel", font=("Microsoft YaHei UI", 18, "bold")) style.configure("Hint.TLabel", foreground="#666666") style.configure("Publish.TButton", font=("Microsoft YaHei UI", 10, "bold"))
header = ttk.Frame(self, padding=(20, 16, 20, 8)) header.grid(row=0, column=0, sticky="ew") ttk.Label(header, text=APP_TITLE, style="Title.TLabel").pack(anchor="w") ttk.Label( header, text="选择站点,一键完成打包、登录和上传。", style="Hint.TLabel" ).pack(anchor="w", pady=(4, 0))
content = ttk.Frame(self, padding=(20, 4, 20, 8)) content.grid(row=1, column=0, sticky="ew") content.columnconfigure(0, weight=1)
server = ttk.LabelFrame(content, text="服务器与账号", padding=12) server.grid(row=0, column=0, sticky="ew", pady=(0, 12)) server.columnconfigure(1, weight=1) server.columnconfigure(3, weight=1) self.login_url = tk.StringVar(value=settings.get("login_url", DEFAULT_LOGIN_URL)) self.upload_url = tk.StringVar(value=settings.get("upload_url", DEFAULT_UPLOAD_URL)) self.username = tk.StringVar(value=settings.get("username", "admin")) self.password = tk.StringVar(value=settings.get("password", "")) self.show_password = tk.BooleanVar(value=False)
ttk.Label(server, text="登录地址").grid(row=0, column=0, sticky="w", padx=(0, 8)) ttk.Entry(server, textvariable=self.login_url).grid(row=0, column=1, sticky="ew", padx=(0, 16), pady=4) ttk.Label(server, text="上传地址").grid(row=0, column=2, sticky="w", padx=(0, 8)) ttk.Entry(server, textvariable=self.upload_url).grid(row=0, column=3, sticky="ew", pady=4) ttk.Label(server, text="用户名").grid(row=1, column=0, sticky="w", padx=(0, 8)) ttk.Entry(server, textvariable=self.username).grid(row=1, column=1, sticky="ew", padx=(0, 16), pady=4) ttk.Label(server, text="密码").grid(row=1, column=2, sticky="w", padx=(0, 8)) password_entry = ttk.Entry(server, textvariable=self.password, show="*") password_entry.grid(row=1, column=3, sticky="ew", pady=4) ttk.Checkbutton( server, text="显示", variable=self.show_password, command=lambda: password_entry.configure(show="" if self.show_password.get() else "*"), ).grid(row=1, column=4, padx=(8, 0))
fblogs_frame = ttk.LabelFrame(content, text="发布站点", padding=10) blogs_frame.grid(row=1, column=0, sticky="ew") blogs_frame.columnconfigure(2, weight=1) for column, label in enumerate(("选择", "名称", "静态文件目录", "", "服务端标识")): ttk.Label(blogs_frame, text=label, style="Hint.TLabel").grid( row=0, column=column, sticky="w", padx=4 ) configs = settings.get("blogs") or [asdict(item) for item in DEFAULT_BLOGS] self.blog_rows = [] for index, item in enumerate(configs[:2], start=1): try: config = BlogConfig(**item) except (TypeError, KeyError): config = DEFAULT_BLOGS[index - 1] self.blog_rows.append(BlogRow(blogs_frame, index, config)) while len(self.blog_rows) < 2: index = len(self.blog_rows) self.blog_rows.append(BlogRow(blogs_frame, index + 1, DEFAULT_BLOGS[index]))
log_frame = ttk.LabelFrame(self, text="运行日志", padding=10) log_frame.grid(row=2, column=0, sticky="nsew", padx=20, pady=(4, 8)) log_frame.columnconfigure(0, weight=1) log_frame.rowconfigure(0, weight=1) self.log_view = ScrolledText( log_frame, height=10, wrap="word", state="disabled", font=("Consolas", 9) ) self.log_view.grid(row=0, column=0, sticky="nsew")
footer = ttk.Frame(self, padding=(20, 0, 20, 16)) footer.grid(row=3, column=0, sticky="ew") footer.columnconfigure(0, weight=1) self.status = tk.StringVar(value="就绪") ttk.Label(footer, textvariable=self.status).grid(row=0, column=0, sticky="w") self.progress = ttk.Progressbar(footer, mode="indeterminate", length=150) self.progress.grid(row=0, column=1, padx=12) ttk.Button(footer, text="保存配置", command=self._save).grid(row=0, column=2, padx=(0, 8)) self.publish_button = ttk.Button( footer, text="开始发布", style="Publish.TButton", command=self._start_deploy ) self.publish_button.grid(row=0, column=3)
def _collect_settings(self) -> dict: return { "login_url": self.login_url.get().strip(), "upload_url": self.upload_url.get().strip(), "username": self.username.get().strip(), "password": self.password.get(), "blogs": [asdict(row.get_config()) for row in self.blog_rows], }
def _save(self, notify: bool = True) -> bool: try: save_settings(self._collect_settings()) except OSError as exc: messagebox.showerror(APP_TITLE, f"配置保存失败:{exc}") return False if notify: self.status.set("配置已保存(包含密码)") return True
def _validate(self) -> list[BlogConfig] | None: if not all((self.login_url.get().strip(), self.upload_url.get().strip())): messagebox.showwarning(APP_TITLE, "请填写登录地址和上传地址。") return None if not self.username.get().strip() or not self.password.get(): messagebox.showwarning(APP_TITLE, "请填写用户名和密码。") return None selected = [row.get_config() for row in self.blog_rows if row.enabled.get()] if not selected: messagebox.showwarning(APP_TITLE, "请至少选择一个要发布的站点。") return None for blog in selected: if not all((blog.name, blog.path, blog.option)): messagebox.showwarning(APP_TITLE, "所选站点的名称、目录和服务端标识不能为空。") return None if not Path(blog.path).expanduser().is_dir(): messagebox.showwarning(APP_TITLE, f"{blog.name} 的目录不存在:\n{blog.path}") return None return selected
def _start_deploy(self) -> None: blogs = self._validate() if blogs is None: return self._save(notify=False) self.publish_button.configure(state="disabled") self.progress.start(12) self.status.set("发布中...") self._append_log("-" * 56) deployer = BlogDeployer( self.login_url.get().strip(), self.upload_url.get().strip(), self.username.get().strip(), self.password.get(), ) self._worker = threading.Thread( target=self._run_deploy, args=(deployer, blogs), daemon=True ) self._worker.start()
def _run_deploy(self, deployer: BlogDeployer, blogs: list[BlogConfig]) -> None: try: deployer.deploy(blogs, lambda text: self._events.put(("log", text))) except requests.Timeout: self._events.put(("error", "连接超时,请检查网络或稍后重试。")) except requests.RequestException as exc: self._events.put(("error", f"网络请求失败:{exc}")) except Exception as exc: self._events.put(("error", str(exc))) else: self._events.put(("done", f"已成功发布 {len(blogs)} 个站点。"))
def _process_events(self) -> None: try: while True: event, payload = self._events.get_nowait() if event == "log": self._append_log(str(payload)) elif event == "error": self._finish("发布失败", str(payload), is_error=True) elif event == "done": self._finish("发布完成", str(payload), is_error=False) except queue.Empty: pass self.after(100, self._process_events)
def _append_log(self, message: str) -> None: self.log_view.configure(state="normal") self.log_view.insert("end", message + "\n") self.log_view.see("end") self.log_view.configure(state="disabled")
def _finish(self, title: str, message: str, is_error: bool) -> None: self.progress.stop() self.publish_button.configure(state="normal") self.status.set(message) self._append_log(message) if is_error: messagebox.showerror(title, message) else: messagebox.showinfo(title, message)
def main() -> None: app = DeployerApp() app.mainloop()
if __name__ == "__main__": main()
|