-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
437 lines (361 loc) · 16.1 KB
/
main.py
File metadata and controls
437 lines (361 loc) · 16.1 KB
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
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
# entrypoint.py 顶部
import os
import sys
import atexit
def _ensure_stdio_redirect():
# 在无控制台(--windowed)打包的 exe 下,stdout/stderr 常为 None
base_dir = os.path.dirname(getattr(sys, "executable", "") or os.getcwd())
out_path = os.path.join(base_dir, "stdout.log")
err_path = os.path.join(base_dir, "stderr.log")
def _open(path):
try:
return open(path, "a", buffering=1, encoding="utf-8", errors="backslashreplace")
except Exception:
return open(os.devnull, "w")
if not getattr(sys.stdout, "write", None):
sys.stdout = _open(out_path)
atexit.register(sys.stdout.close)
if not getattr(sys.stderr, "write", None):
sys.stderr = _open(err_path)
atexit.register(sys.stderr.close)
_ensure_stdio_redirect()
import tkinter as tk
import webbrowser
import threading
from http.server import SimpleHTTPRequestHandler
from http.server import CGIHTTPRequestHandler
from http.server import ThreadingHTTPServer
from functools import partial
import contextlib
import socket
import sys
import os
import json
import platform
import re
import winreg
from tkinter import filedialog, messagebox
import pystray
from PIL import Image, ImageDraw
from urllib.parse import urlparse
import res
print("随机点名工具启动成功,请点击桌面左上角“点”按钮。")
def is_frozen() -> bool:
return getattr(sys, "frozen", False)
def get_base_dir() -> str:
# 运行在 PyInstaller EXE 时返回 EXE 所在目录,否则返回脚本所在目录
return os.path.dirname(sys.executable) if is_frozen() else os.path.dirname(os.path.abspath(__file__))
def resource_path(relative_path: str) -> str:
# 当使用 PyInstaller 打包时,资源会被释放到临时目录 sys._MEIPASS
base = getattr(sys, "_MEIPASS", None)
if base:
return os.path.join(base, relative_path)
return os.path.join(get_base_dir(), relative_path)
def load_config() -> dict:
# 仅读取程序同目录下的 config.json,且仅支持 autostart 配置项
cfg_path = os.path.join(get_base_dir(), "config.json")
if os.path.isfile(cfg_path):
try:
with open(cfg_path, "r", encoding="utf-8") as f:
data = json.load(f)
# 只保留 autostart
return {"autostart": bool(data.get("autostart", False))}
except Exception as e:
print(f"加载配置文件失败 {cfg_path}: {e}")
return {"autostart": False}
def save_config(cfg: dict) -> None:
# 仅保存到程序同目录
cfg_path = os.path.join(get_base_dir(), "config.json")
try:
with open(cfg_path, "w", encoding="utf-8") as f:
json.dump({"autostart": bool(cfg.get("autostart", False))}, f, ensure_ascii=False, indent=2)
except Exception as e:
print(f"保存配置失败 {cfg_path}: {e}")
def set_autostart(app_name: str, enable: bool, command: str) -> None:
# 基于配置开关设置/取消开机自启(当前用户)
if platform.system() != "Windows" or winreg is None:
return
key_path = r"Software\Microsoft\Windows\CurrentVersion\Run"
try:
with winreg.OpenKey(winreg.HKEY_CURRENT_USER, key_path, 0, winreg.KEY_ALL_ACCESS) as key:
if enable:
winreg.SetValueEx(key, app_name, 0, winreg.REG_SZ, command)
else:
try:
winreg.DeleteValue(key, app_name)
except FileNotFoundError:
pass
except Exception as e:
print(f"设置开机自启失败: {e}")
def read_names_file() -> list:
# 从程序目录读取 name_list.txt,每行一个姓名
names_path = os.path.join(get_base_dir(), "name_list.txt")
result = []
try:
if os.path.isfile(names_path):
with open(names_path, "r", encoding="utf-8") as f:
for line in f:
name = line.strip()
if name:
result.append(name)
except Exception as e:
print(f"读取名单失败: {e}")
return result
# 统一设置工作目录为程序所在目录,避免打包后在开机自启时工作目录错误
BASE_DIR = get_base_dir()
try:
os.chdir(BASE_DIR)
except Exception as e:
print(f"切换工作目录失败: {e}")
# 加载配置
config = load_config()
APP_NAME = "RandomPicker"
# 服务器配置(固定默认,可在需要时调整)
SERVER_PORT = 5000
SERVER_BIND = "127.0.0.1"
SERVER_CGI = False
# 静态资源:改为仅使用内嵌资源(res.py)
SERVER_DIR = None
if res is not None and hasattr(res, "ASSETS"):
try:
assets_count = len(getattr(res, "ASSETS", {}))
except Exception:
assets_count = 0
print(f"静态资源:使用内嵌资源(res.py),共 {assets_count} 个文件")
else:
print("静态资源:res.py 未找到,页面可能无法访问。请先运行 `python script/pack_res.py` 生成 res.py")
class DualStackServer(ThreadingHTTPServer):
def server_bind(self):
# suppress exception when protocol is IPv4
with contextlib.suppress(Exception):
self.socket.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 0)
return super().server_bind()
def make_handler(directory: str):
class CustomHandler(SimpleHTTPRequestHandler):
def __init__(self, *args, **kwargs):
super().__init__(*args, directory=directory, **kwargs)
def do_GET(self):
if self.path.startswith("/api/names"):
try:
data = read_names_file()
payload = json.dumps(data, ensure_ascii=False).encode("utf-8")
self.send_response(200)
self.send_header("Content-Type", "application/json; charset=utf-8")
self.send_header("Content-Length", str(len(payload)))
self.end_headers()
self.wfile.write(payload)
except Exception as e:
err = {"error": str(e)}
payload = json.dumps(err, ensure_ascii=False).encode("utf-8")
self.send_response(500)
self.send_header("Content-Type", "application/json; charset=utf-8")
self.send_header("Content-Length", str(len(payload)))
self.end_headers()
self.wfile.write(payload)
else:
# Embedded-only static serving (no filesystem), with Range support for identity-encoded media
try:
req_path = urlparse(self.path).path # strip query string
if req_path in ("", "/") or req_path.endswith("/"):
rel_path = "index.html"
else:
rel_path = req_path.lstrip("/")
except Exception:
rel_path = "index.html"
if res is not None and hasattr(res, "get_asset"):
found = res.get_asset(rel_path)
if not found and rel_path != "index.html":
# SPA-like routing fallback
found = res.get_asset("index.html")
if found:
mime, data_bytes, enc = found
total = len(data_bytes)
if enc == "gzip":
# Full-body response only (no range for gzip)
self.send_response(200)
self.send_header("Content-Type", mime)
self.send_header("Content-Encoding", "gzip")
self.send_header("Content-Length", str(total))
self.end_headers()
if self.command != "HEAD":
self.wfile.write(data_bytes)
return
else:
# identity: support Range requests for media
range_header = self.headers.get("Range")
if range_header and range_header.startswith("bytes="):
# Parse first range only: bytes=start-end
spec = range_header.split("=", 1)[1].split(",", 1)[0].strip()
start_str, _, end_str = spec.partition("-")
try:
if start_str:
start = int(start_str)
else:
# suffix range: bytes=-N (last N bytes)
n = int(end_str) if end_str else 0
start = max(total - n, 0)
end = int(end_str) if end_str else total - 1
except Exception:
start, end = 0, total - 1
if start >= total:
# Unsatisfiable
self.send_response(416)
self.send_header("Content-Range", f"bytes */{total}")
self.end_headers()
return
end = min(end, total - 1)
length = end - start + 1
self.send_response(206)
self.send_header("Content-Type", mime)
self.send_header("Content-Range", f"bytes {start}-{end}/{total}")
self.send_header("Accept-Ranges", "bytes")
self.send_header("Content-Length", str(length))
self.end_headers()
if self.command != "HEAD":
self.wfile.write(data_bytes[start:end + 1])
return
# No Range: send full body
self.send_response(200)
self.send_header("Content-Type", mime)
self.send_header("Accept-Ranges", "bytes")
self.send_header("Content-Length", str(total))
self.end_headers()
if self.command != "HEAD":
self.wfile.write(data_bytes)
return
# Not found in embedded assets
self.send_error(404, "File not found")
return CustomHandler
def http_server(server_class=DualStackServer, handler_class=SimpleHTTPRequestHandler, port=5000, bind='127.0.0.1', cgi=False, directory=os.path.join(os.getcwd(), "www")):
if cgi:
handler_cls = partial(CGIHTTPRequestHandler, directory=directory)
else:
handler_cls = make_handler(directory)
with server_class((bind, port), handler_cls) as httpd:
print(
f"Serving HTTP on {bind} port {port} "
f" (http://{bind}:{port}/) ..."
)
try:
httpd.serve_forever()
except KeyboardInterrupt:
print("\nKeyboard interrupt received, exiting.")
sys.exit(0)
threading.Thread(
target=http_server,
kwargs={
"port": SERVER_PORT,
"bind": SERVER_BIND,
"cgi": SERVER_CGI,
"directory": None,
},
daemon=True,
).start()
def open_url():
webbrowser.open(f"http://{SERVER_BIND}:{SERVER_PORT}")
# ========== 系统托盘与设置 ==========
tray_icon = None
def _create_tray_image():
if Image is None:
return None
img = Image.new("RGBA", (64, 64), (0, 0, 0, 0))
d = ImageDraw.Draw(img)
d.ellipse((8, 8, 56, 56), fill=(46, 204, 113, 255))
d.text((24, 20), "点", fill=(255, 255, 255, 255))
return img
def toggle_autostart():
config["autostart"] = not bool(config.get("autostart", False))
save_config(config)
set_autostart(APP_NAME, config["autostart"], start_cmd)
def import_names_via_dialog():
path = filedialog.askopenfilename(
title="选择名单文本文件",
filetypes=[("Text Files", "*.txt"), ("All Files", "*.*")]
)
if not path:
return
try:
with open(path, "r", encoding="utf-8") as f:
lines = [line.strip() for line in f if line.strip()]
dest = os.path.join(get_base_dir(), "name_list.txt")
with open(dest, "w", encoding="utf-8") as f:
f.write("\n".join(lines))
messagebox.showinfo("导入成功", f"已导入 {len(lines)} 条名单到: {dest}")
except Exception as e:
messagebox.showerror("导入失败", str(e))
def show_settings_window():
if any(isinstance(w, tk.Toplevel) and str(w) == ".settings" for w in root.winfo_children()):
w = next(w for w in root.winfo_children() if isinstance(w, tk.Toplevel) and str(w) == ".settings")
try:
w.deiconify()
w.lift()
w.focus_force()
except Exception:
pass
return
win = tk.Toplevel(root, name="settings")
win.title("设置")
win.attributes("-topmost", True)
win.geometry("280x160")
var_autostart = tk.BooleanVar(value=bool(config.get("autostart", False)))
chk = tk.Checkbutton(win, text="开机自启动", variable=var_autostart)
chk.pack(pady=10, anchor="w", padx=12)
btn_import = tk.Button(win, text="导入名单", command=import_names_via_dialog)
btn_import.pack(pady=5, padx=12, fill=tk.X)
def on_save():
config["autostart"] = bool(var_autostart.get())
save_config(config)
set_autostart(APP_NAME, config["autostart"], start_cmd)
messagebox.showinfo("已保存", "设置已保存")
btn_save = tk.Button(win, text="保存", command=on_save)
btn_save.pack(pady=5, padx=12, fill=tk.X)
btn_close = tk.Button(win, text="关闭", command=win.destroy)
btn_close.pack(pady=5, padx=12, fill=tk.X)
def _quit_app():
try:
if tray_icon is not None:
tray_icon.stop()
except Exception:
pass
root.quit()
def _start_tray():
global tray_icon
if pystray is None:
print("未安装 pystray 或 Pillow,系统托盘不可用。")
return
image = _create_tray_image()
menu = pystray.Menu(
pystray.MenuItem("打开点名页面", lambda icon, item: open_url()),
pystray.MenuItem("设置...", lambda icon, item: root.after(0, show_settings_window)),
pystray.MenuItem(
"开机自启动",
lambda icon, item: root.after(0, toggle_autostart),
checked=lambda item: bool(config.get("autostart", False))
),
pystray.MenuItem("导入名单", lambda icon, item: root.after(0, import_names_via_dialog)),
pystray.MenuItem("退出", lambda icon, item: root.after(0, _quit_app)),
)
tray_icon = pystray.Icon("RandomPicker", image, "随机点名", menu)
try:
tray_icon.run_detached()
except Exception:
# 某些平台没有 run_detached
threading.Thread(target=tray_icon.run, daemon=True).start()
# 创建主窗口
root = tk.Tk()
root.title("悬浮窗")
root.geometry("20x20") # 设置窗口大小
root.overrideredirect(True) # 去掉窗口边框
root.attributes("-topmost", True) # 确保窗口总在最上层
# 设置不透明度
root.wm_attributes("-alpha", 0.3)
# 创建按钮
button = tk.Button(root, text="点", command=open_url)
button.pack(expand=True, fill=tk.BOTH) # 按钮填充整个窗口
# 设置窗口位置(例如在屏幕右上角)
screen_width = root.winfo_screenwidth()
root.geometry(f"+0+0")
# 启动系统托盘
_start_tray()
# 运行主循环
root.mainloop()