CCL_QMS检验
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

694 lines
27 KiB

2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
  1. # -*- coding: utf-8 -*-
  2. import json
  3. import os
  4. import queue
  5. import shutil
  6. import sys
  7. import threading
  8. import time
  9. from datetime import datetime
  10. from pathlib import Path
  11. from tkinter import Tk, Label, Entry, Button, StringVar, END, DISABLED, NORMAL, filedialog, messagebox, simpledialog
  12. from tkinter.scrolledtext import ScrolledText
  13. import requests
  14. from requests.adapters import HTTPAdapter
  15. from urllib3.util.retry import Retry
  16. def get_runtime_dir():
  17. if getattr(sys, "frozen", False):
  18. return Path(sys.executable).resolve().parent
  19. return Path(__file__).resolve().parent
  20. def _ensure_windows_run_registry(entry_name, exe_path):
  21. import winreg
  22. run_key_path = r"Software\Microsoft\Windows\CurrentVersion\Run"
  23. target_value = "\"%s\"" % exe_path
  24. try:
  25. with winreg.OpenKey(
  26. winreg.HKEY_CURRENT_USER,
  27. run_key_path,
  28. 0,
  29. winreg.KEY_READ | winreg.KEY_SET_VALUE
  30. ) as key:
  31. try:
  32. old_value, _ = winreg.QueryValueEx(key, entry_name)
  33. except FileNotFoundError:
  34. old_value = None
  35. if old_value and str(old_value).strip().strip("\"").lower() == exe_path.lower():
  36. return False, "系统自启动项已存在,无需重复写入。"
  37. winreg.SetValueEx(key, entry_name, 0, winreg.REG_SZ, target_value)
  38. if old_value:
  39. return True, "检测到自启动路径变化,已自动更新。"
  40. return True, "首次启动已写入系统自启动项,下次开机会自动运行。"
  41. except Exception as e:
  42. return False, "写入系统自启动项失败: %s" % e
  43. def _cleanup_legacy_startup_items(legacy_entry_name, app_data):
  44. if app_data:
  45. startup_dir = Path(app_data) / "Microsoft" / "Windows" / "Start Menu" / "Programs" / "Startup"
  46. legacy_script = startup_dir / (legacy_entry_name + ".vbs")
  47. try:
  48. if legacy_script.exists():
  49. legacy_script.unlink()
  50. except Exception:
  51. pass
  52. try:
  53. import winreg
  54. run_key_path = r"Software\Microsoft\Windows\CurrentVersion\Run"
  55. with winreg.OpenKey(
  56. winreg.HKEY_CURRENT_USER,
  57. run_key_path,
  58. 0,
  59. winreg.KEY_SET_VALUE
  60. ) as key:
  61. try:
  62. winreg.DeleteValue(key, legacy_entry_name)
  63. except FileNotFoundError:
  64. pass
  65. except Exception:
  66. pass
  67. def ensure_windows_startup():
  68. if os.name != "nt":
  69. return False, "当前系统非Windows,跳过自启动注册。"
  70. if not getattr(sys, "frozen", False):
  71. return False, "当前为源码运行,跳过自启动注册。"
  72. exe_path = str(Path(sys.executable).resolve())
  73. entry_name = "QMSFileCollector"
  74. app_data = os.getenv("APPDATA", "").strip()
  75. _cleanup_legacy_startup_items("CKPClientFileCollector", app_data)
  76. if app_data:
  77. startup_dir = Path(app_data) / "Microsoft" / "Windows" / "Start Menu" / "Programs" / "Startup"
  78. startup_script = startup_dir / (entry_name + ".vbs")
  79. script_content = (
  80. "Set WshShell = CreateObject(\"WScript.Shell\")\n"
  81. "WshShell.Run Chr(34) & \"%s\" & Chr(34), 0\n"
  82. "Set WshShell = Nothing\n"
  83. ) % exe_path.replace("\"", "\"\"")
  84. try:
  85. startup_dir.mkdir(parents=True, exist_ok=True)
  86. old_content = ""
  87. if startup_script.exists():
  88. old_content = startup_script.read_text(encoding="utf-8")
  89. if old_content == script_content:
  90. return False, "启动文件夹自启动项已存在,无需重复写入。"
  91. startup_script.write_text(script_content, encoding="utf-8")
  92. if old_content:
  93. return True, "检测到启动文件夹自启动路径变化,已自动更新。"
  94. return True, "首次启动已写入启动文件夹自启动项,下次开机会自动运行。"
  95. except Exception as startup_error:
  96. try:
  97. changed, reg_msg = _ensure_windows_run_registry(entry_name, exe_path)
  98. return changed, "写入启动文件夹失败,已回退注册表方式: %s" % reg_msg
  99. except Exception as reg_error:
  100. return False, "写入启动文件夹和注册表均失败: %s; %s" % (startup_error, reg_error)
  101. try:
  102. return _ensure_windows_run_registry(entry_name, exe_path)
  103. except Exception as e:
  104. return False, "未获取到APPDATA且注册表写入失败: %s" % e
  105. class CollectorApp:
  106. def __init__(self, root):
  107. self.root = root
  108. self.root.title("文件采集客户端")
  109. self.root.geometry("1280x720")
  110. self.root.resizable(True, True)
  111. self.config_path = get_runtime_dir() / "collector_config.json"
  112. self.log_queue = queue.Queue()
  113. self.running = False
  114. self.worker_thread = None
  115. self.stop_event = threading.Event()
  116. self.active_rows = []
  117. self.upload_state = {}
  118. self.notice_ts = {}
  119. self.processing_lock = threading.Lock()
  120. self.processing_files = set()
  121. self.http_session = self._create_http_session()
  122. self.base_url_var = StringVar()
  123. self.poll_seconds_var = StringVar(value="10")
  124. self.row_vars = []
  125. for _ in range(3):
  126. self.row_vars.append({
  127. "site": StringVar(),
  128. "bu_no": StringVar(),
  129. "equipment_no": StringVar(),
  130. "source_path": StringVar(),
  131. "backup_path": StringVar(),
  132. })
  133. self._build_ui()
  134. self.root.protocol("WM_DELETE_WINDOW", self._on_window_close)
  135. self._init_windows_startup()
  136. self._load_config()
  137. self.root.after(200, self._flush_logs)
  138. self.root.after(3000, self._watch_worker)
  139. def _create_http_session(self):
  140. retry = Retry(
  141. total=3,
  142. connect=3,
  143. read=3,
  144. backoff_factor=1.0,
  145. status_forcelist=[500, 502, 503, 504],
  146. allowed_methods=frozenset(["POST"]),
  147. raise_on_status=False,
  148. )
  149. adapter = HTTPAdapter(max_retries=retry, pool_connections=8, pool_maxsize=8)
  150. session = requests.Session()
  151. session.mount("http://", adapter)
  152. session.mount("https://", adapter)
  153. return session
  154. def _init_windows_startup(self):
  155. changed, message = ensure_windows_startup()
  156. if changed:
  157. self.log(message)
  158. return
  159. if getattr(sys, "frozen", False) and ("失败" in message):
  160. self.log(message)
  161. def _build_ui(self):
  162. Label(self.root, text="系统地址").place(x=20, y=20)
  163. Entry(self.root, textvariable=self.base_url_var, width=92).place(x=85, y=20)
  164. Button(self.root, text="弹框设置地址", command=self.popup_set_base_url).place(x=860, y=16)
  165. Button(self.root, text="保存配置", command=self.save_config).place(x=970, y=16)
  166. Label(self.root, text="轮询秒").place(x=20, y=58)
  167. Entry(self.root, textvariable=self.poll_seconds_var, width=10).place(x=85, y=58)
  168. Button(self.root, text="开始同步", command=self.start_collect).place(x=180, y=54)
  169. Button(self.root, text="停止同步", command=self.stop_collect).place(x=265, y=54)
  170. Button(self.root, text="退出程序", command=self.exit_app).place(x=1080, y=54)
  171. Label(self.root, text="配置说明:最多3行,每行需填写 site + buNo + equipmentNo + 本地目录;备份目录可选(为空则自动使用本地目录_bak)").place(x=360, y=58)
  172. Label(self.root, text="").place(x=20, y=100)
  173. Label(self.root, text="Site").place(x=80, y=100)
  174. Label(self.root, text="BuNo").place(x=220, y=100)
  175. Label(self.root, text="EquipmentNo").place(x=360, y=100)
  176. Label(self.root, text="本地目录").place(x=530, y=100)
  177. Label(self.root, text="备份目录").place(x=890, y=100)
  178. for idx, row in enumerate(self.row_vars):
  179. y = 130 + idx * 40
  180. Label(self.root, text=str(idx + 1)).place(x=26, y=y)
  181. Entry(self.root, textvariable=row["site"], width=16).place(x=80, y=y)
  182. Entry(self.root, textvariable=row["bu_no"], width=16).place(x=220, y=y)
  183. Entry(self.root, textvariable=row["equipment_no"], width=18).place(x=360, y=y)
  184. Entry(self.root, textvariable=row["source_path"], width=40).place(x=530, y=y)
  185. Button(self.root, text="选择目录", command=lambda x=idx: self.choose_source_dir(x)).place(x=815, y=y - 4)
  186. Entry(self.root, textvariable=row["backup_path"], width=30).place(x=890, y=y)
  187. Button(self.root, text="选择目录", command=lambda x=idx: self.choose_backup_dir(x)).place(x=1110, y=y - 4)
  188. self.log_text = ScrolledText(self.root, width=165, height=23)
  189. self.log_text.place(x=20, y=280)
  190. self.log_text.configure(state=DISABLED)
  191. def popup_set_base_url(self):
  192. new_url = simpledialog.askstring(
  193. "设置目标地址",
  194. "请输入xujie-sys地址,例如:http://172.26.58.88:8080",
  195. initialvalue=self.base_url_var.get().strip()
  196. )
  197. if new_url is not None:
  198. self.base_url_var.set(new_url.strip())
  199. self.log("已设置目标地址: %s" % new_url.strip())
  200. def choose_source_dir(self, row_index):
  201. path = filedialog.askdirectory(title="选择第%d行本地目录" % (row_index + 1))
  202. if path:
  203. row = self.row_vars[row_index]
  204. row["source_path"].set(path)
  205. if not row["backup_path"].get().strip():
  206. row["backup_path"].set(self._default_backup_path(path))
  207. def choose_backup_dir(self, row_index):
  208. path = filedialog.askdirectory(title="选择第%d行备份目录" % (row_index + 1))
  209. if path:
  210. self.row_vars[row_index]["backup_path"].set(path)
  211. def _default_backup_path(self, source_path):
  212. source_text = str(source_path).strip()
  213. if not source_text:
  214. return ""
  215. source = Path(source_text)
  216. return str(source.parent / (source.name + "_bak"))
  217. def _load_config(self):
  218. if not self.config_path.exists():
  219. self.log("未找到本地配置,请先录入并保存。")
  220. return
  221. try:
  222. config = json.loads(self.config_path.read_text(encoding="utf-8"))
  223. self.base_url_var.set(config.get("base_url", ""))
  224. self.poll_seconds_var.set(str(config.get("poll_seconds", "10")))
  225. rows = config.get("rows")
  226. # 兼容旧版本单行配置
  227. if not isinstance(rows, list):
  228. rows = [{
  229. "site": config.get("site", ""),
  230. "bu_no": config.get("bu_no", ""),
  231. "equipment_no": config.get("equipment_no", ""),
  232. "source_path": config.get("source_path", ""),
  233. "backup_path": config.get("backup_path", ""),
  234. }]
  235. for idx in range(min(3, len(rows))):
  236. item = rows[idx] if isinstance(rows[idx], dict) else {}
  237. source_path = str(item.get("source_path", "")).strip()
  238. backup_path = str(item.get("backup_path", "")).strip()
  239. if source_path and not backup_path:
  240. backup_path = self._default_backup_path(source_path)
  241. self.row_vars[idx]["site"].set(str(item.get("site", "")).strip())
  242. self.row_vars[idx]["bu_no"].set(str(item.get("bu_no", "")).strip())
  243. self.row_vars[idx]["equipment_no"].set(str(item.get("equipment_no", "")).strip())
  244. self.row_vars[idx]["source_path"].set(source_path)
  245. self.row_vars[idx]["backup_path"].set(backup_path)
  246. self.log("配置加载完成。")
  247. if self._can_auto_start():
  248. self.start_collect(auto_mode=True)
  249. except Exception as e:
  250. self.log("读取配置失败: %s" % e)
  251. def save_config(self):
  252. try:
  253. rows = self._get_valid_rows(require_complete=True, raise_on_empty=False)
  254. except ValueError as e:
  255. messagebox.showwarning("提示", str(e))
  256. return
  257. data = {
  258. "base_url": self.base_url_var.get().strip(),
  259. "poll_seconds": self.poll_seconds_var.get().strip(),
  260. "rows": rows,
  261. }
  262. try:
  263. self.config_path.write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8")
  264. self.log("配置已保存: %s" % self.config_path)
  265. except Exception as e:
  266. messagebox.showerror("错误", "保存配置失败: %s" % e)
  267. return
  268. if self.running:
  269. self.active_rows = rows
  270. self.log("采集配置已更新,下一轮轮询自动生效。")
  271. elif self._can_auto_start():
  272. self.start_collect(auto_mode=True)
  273. def _can_auto_start(self):
  274. if not self._base_url():
  275. return False
  276. if not self._is_poll_seconds_valid():
  277. return False
  278. try:
  279. rows = self._get_valid_rows(require_complete=True, raise_on_empty=True)
  280. return len(rows) > 0
  281. except Exception:
  282. return False
  283. def _is_poll_seconds_valid(self):
  284. try:
  285. return int(self.poll_seconds_var.get().strip()) > 0
  286. except Exception:
  287. return False
  288. def _base_url(self):
  289. return self.base_url_var.get().strip().rstrip("/")
  290. def _get_valid_rows(self, require_complete, raise_on_empty):
  291. rows = []
  292. for idx, row in enumerate(self.row_vars):
  293. site = row["site"].get().strip()
  294. bu_no = row["bu_no"].get().strip()
  295. equipment_no = row["equipment_no"].get().strip()
  296. source_path = row["source_path"].get().strip()
  297. backup_path = row["backup_path"].get().strip()
  298. filled_count = 0
  299. for value in (site, bu_no, equipment_no, source_path, backup_path):
  300. if value:
  301. filled_count += 1
  302. if filled_count == 0:
  303. continue
  304. required_count = 0
  305. for value in (site, bu_no, equipment_no, source_path):
  306. if value:
  307. required_count += 1
  308. if require_complete and required_count < 4:
  309. raise ValueError("%d行配置未填写完整,请补全site、buNo、equipmentNo、本地目录。" % (idx + 1))
  310. if required_count == 4:
  311. if not backup_path:
  312. backup_path = self._default_backup_path(source_path)
  313. if os.path.normcase(os.path.normpath(source_path)) == os.path.normcase(os.path.normpath(backup_path)):
  314. raise ValueError("%d行配置错误:本地目录和备份目录不能相同。" % (idx + 1))
  315. rows.append({
  316. "row_index": idx + 1,
  317. "site": site,
  318. "bu_no": bu_no,
  319. "equipment_no": equipment_no,
  320. "source_path": source_path,
  321. "backup_path": backup_path,
  322. })
  323. if raise_on_empty and len(rows) == 0:
  324. raise ValueError("请至少填写一行完整采集配置。")
  325. return rows
  326. def start_collect(self, auto_mode=False):
  327. if self.running and self.worker_thread is not None and self.worker_thread.is_alive():
  328. if not auto_mode:
  329. self.log("采集任务已在运行中。")
  330. return
  331. if self.running and (self.worker_thread is None or not self.worker_thread.is_alive()):
  332. self.log("检测到采集线程已退出,正在自动重启。")
  333. self.running = False
  334. if not self._base_url():
  335. if auto_mode:
  336. self.log("自动启动失败:系统地址为空。")
  337. else:
  338. messagebox.showwarning("提示", "请先设置系统地址")
  339. return
  340. try:
  341. poll_seconds = int(self.poll_seconds_var.get().strip() or "10")
  342. if poll_seconds <= 0:
  343. raise ValueError("轮询秒必须大于0")
  344. except Exception:
  345. if auto_mode:
  346. self.log("自动启动失败:轮询秒无效。")
  347. else:
  348. messagebox.showwarning("提示", "轮询秒必须是大于0的整数")
  349. return
  350. try:
  351. rows = self._get_valid_rows(require_complete=True, raise_on_empty=True)
  352. except ValueError as e:
  353. if auto_mode:
  354. self.log("自动启动失败:%s" % e)
  355. else:
  356. messagebox.showwarning("提示", str(e))
  357. return
  358. self.active_rows = rows
  359. # 每次手动/自动启动都重置一次状态,避免停启后误判“已同步”。
  360. self.upload_state = {}
  361. self.notice_ts = {}
  362. with self.processing_lock:
  363. self.processing_files.clear()
  364. self.stop_event = threading.Event()
  365. self.running = True
  366. self.worker_thread = threading.Thread(target=self._worker_loop, args=(self.stop_event,), daemon=True)
  367. self.worker_thread.start()
  368. if auto_mode:
  369. self.log("配置有效,已自动启动轮询同步。")
  370. else:
  371. self.log("采集任务已启动。")
  372. def stop_collect(self):
  373. if not self.running:
  374. self.log("采集任务未运行。")
  375. return
  376. self.running = False
  377. self.stop_event.set()
  378. self.log("正在停止采集任务...")
  379. def _on_window_close(self):
  380. self.root.iconify()
  381. self._log_with_interval("window_hidden", "配置窗口已最小化到任务栏,采集仍在后台运行。", 5)
  382. def exit_app(self):
  383. self.running = False
  384. self.stop_event.set()
  385. try:
  386. self.http_session.close()
  387. except Exception:
  388. pass
  389. self.root.destroy()
  390. def _watch_worker(self):
  391. try:
  392. if self.running and (self.worker_thread is None or not self.worker_thread.is_alive()):
  393. self.log("检测到采集线程中断,正在自动恢复...")
  394. self.running = False
  395. self.start_collect(auto_mode=True)
  396. finally:
  397. self.root.after(3000, self._watch_worker)
  398. def _worker_loop(self, stop_event):
  399. while not stop_event.is_set():
  400. try:
  401. rows = list(self.active_rows)
  402. for row in rows:
  403. if stop_event.is_set():
  404. break
  405. try:
  406. self._sync_one_row(row, stop_event)
  407. except Exception as row_error:
  408. self.log("%d行同步异常,已跳过并继续: %s" % (row.get("row_index", 0), row_error))
  409. try:
  410. poll_seconds = int(self.poll_seconds_var.get().strip() or "10")
  411. except Exception:
  412. poll_seconds = 10
  413. for _ in range(max(1, poll_seconds)):
  414. if stop_event.is_set():
  415. break
  416. time.sleep(1)
  417. except Exception as e:
  418. self.log("采集线程异常,将自动继续: %s" % e)
  419. for _ in range(5):
  420. if stop_event.is_set():
  421. break
  422. time.sleep(1)
  423. if self.stop_event is stop_event:
  424. self.running = False
  425. self.worker_thread = None
  426. self.log("采集任务已停止。")
  427. def _sync_one_row(self, row, stop_event):
  428. row_index = row["row_index"]
  429. source_path = row["source_path"]
  430. path_key = "row%d_missing" % row_index
  431. empty_key = "row%d_empty" % row_index
  432. if not os.path.isdir(source_path):
  433. self._log_with_interval(path_key, "%d行目录不存在: %s" % (row_index, source_path), 60)
  434. return
  435. files = []
  436. try:
  437. for name in os.listdir(source_path):
  438. file_path = Path(source_path) / name
  439. if file_path.is_file():
  440. files.append(file_path)
  441. except Exception as e:
  442. self._log_with_interval(path_key, "%d行读取目录失败: %s, 原因: %s" % (row_index, source_path, e), 30)
  443. return
  444. self._cleanup_row_upload_state(row_index, files)
  445. if not files:
  446. self._log_with_interval(empty_key, "%d行目录为空,等待新文件..." % row_index, 60)
  447. return
  448. files.sort(key=self._safe_mtime)
  449. for file_path in files:
  450. if stop_event.is_set():
  451. return
  452. state_key = "%d|%s" % (row_index, str(file_path).lower())
  453. if not self._try_acquire_processing(state_key):
  454. continue
  455. try:
  456. signature = self._file_signature(file_path)
  457. if signature is None:
  458. continue
  459. # 已上传但上次备份失败,则仅重试备份,避免重复上传造成服务器/备份放大。
  460. if self.upload_state.get(state_key) == signature:
  461. if self._backup_and_remove_file(row, file_path):
  462. self.upload_state.pop(state_key, None)
  463. continue
  464. if self._upload_file(row, file_path):
  465. self.upload_state[state_key] = signature
  466. if self._backup_and_remove_file(row, file_path):
  467. # 文件已从源目录移走,立即清理状态,允许后续同名新文件再次同步。
  468. self.upload_state.pop(state_key, None)
  469. finally:
  470. self._release_processing(state_key)
  471. def _cleanup_row_upload_state(self, row_index, files):
  472. prefix = "%d|" % row_index
  473. current_keys = set()
  474. for file_path in files:
  475. current_keys.add("%d|%s" % (row_index, str(file_path).lower()))
  476. stale_keys = []
  477. for key in list(self.upload_state.keys()):
  478. if key.startswith(prefix) and key not in current_keys:
  479. stale_keys.append(key)
  480. for key in stale_keys:
  481. self.upload_state.pop(key, None)
  482. def _try_acquire_processing(self, state_key):
  483. with self.processing_lock:
  484. if state_key in self.processing_files:
  485. return False
  486. self.processing_files.add(state_key)
  487. return True
  488. def _release_processing(self, state_key):
  489. with self.processing_lock:
  490. self.processing_files.discard(state_key)
  491. def _file_signature(self, file_path):
  492. try:
  493. stat = file_path.stat()
  494. return stat.st_mtime_ns, stat.st_size
  495. except Exception as e:
  496. self.log("读取文件状态失败: %s, 原因: %s" % (file_path, e))
  497. return None
  498. def _safe_mtime(self, file_path):
  499. try:
  500. return file_path.stat().st_mtime
  501. except Exception:
  502. return 0
  503. def _get_backup_dir(self, row):
  504. backup_path = str(row.get("backup_path", "")).strip()
  505. if backup_path:
  506. return Path(backup_path)
  507. return Path(self._default_backup_path(row["source_path"]))
  508. def _backup_and_remove_file(self, row, file_path):
  509. source_path = row["source_path"]
  510. row_index = row["row_index"]
  511. backup_dir = self._get_backup_dir(row)
  512. if os.path.normcase(os.path.normpath(str(source_path))) == os.path.normcase(os.path.normpath(str(backup_dir))):
  513. self.log("%d行备份目录不能与本地目录相同: %s" % (row_index, backup_dir))
  514. return False
  515. try:
  516. backup_dir.mkdir(parents=True, exist_ok=True)
  517. except Exception as e:
  518. self.log("%d行创建备份目录失败: %s, 原因: %s" % (row_index, backup_dir, e))
  519. return False
  520. if not file_path.exists():
  521. self.log("%d行源文件已不存在,视为已备份完成: %s" % (row_index, file_path.name))
  522. return True
  523. target = self._build_unique_backup_target(backup_dir, file_path)
  524. try:
  525. shutil.move(str(file_path), str(target))
  526. self.log("%d行源文件已转移至备份: %s -> %s" % (row_index, file_path.name, target))
  527. return True
  528. except FileNotFoundError:
  529. self.log("%d行源文件在备份时已被处理,忽略重复备份: %s" % (row_index, file_path.name))
  530. return True
  531. except Exception as e:
  532. self.log("%d行源文件备份转移失败: %s, 原因: %s" % (row_index, file_path.name, e))
  533. return False
  534. def _build_unique_backup_target(self, backup_dir, file_path):
  535. target = backup_dir / file_path.name
  536. if not target.exists():
  537. return target
  538. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S_%f")
  539. base_name = file_path.stem
  540. suffix = file_path.suffix
  541. candidate = backup_dir / ("%s_%s%s" % (base_name, timestamp, suffix))
  542. index = 1
  543. while candidate.exists():
  544. candidate = backup_dir / ("%s_%s_%d%s" % (base_name, timestamp, index, suffix))
  545. index += 1
  546. return candidate
  547. def _upload_file(self, row, file_path):
  548. url = self._base_url() + "/collector/client/upload"
  549. data = {
  550. "site": row["site"],
  551. "buNo": row["bu_no"],
  552. "equipmentNo": row["equipment_no"],
  553. }
  554. try:
  555. with open(file_path, "rb") as fp:
  556. files = {"file": (file_path.name, fp, "application/octet-stream")}
  557. resp = self.http_session.post(url, data=data, files=files, timeout=180)
  558. resp.raise_for_status()
  559. result = resp.json()
  560. if result.get("code") == 0:
  561. response_data = result.get("data") or {}
  562. server_path = response_data.get("savedFullPath", "")
  563. self.log("%d行上传成功: %s -> %s" % (row["row_index"], file_path.name, server_path))
  564. return True
  565. self.log("%d行上传失败: %s, 原因: %s" % (
  566. row["row_index"], file_path.name, result.get("msg")))
  567. return False
  568. except Exception as e:
  569. self.log("%d行上传异常: %s, 原因: %s" % (row["row_index"], file_path.name, e))
  570. return False
  571. def _log_with_interval(self, key, message, seconds):
  572. now = time.time()
  573. last = self.notice_ts.get(key, 0)
  574. if now - last >= seconds:
  575. self.notice_ts[key] = now
  576. self.log(message)
  577. def log(self, message):
  578. self.log_queue.put("[%s] %s" % (datetime.now().strftime("%H:%M:%S"), message))
  579. def _flush_logs(self):
  580. while not self.log_queue.empty():
  581. line = self.log_queue.get()
  582. self.log_text.configure(state=NORMAL)
  583. self.log_text.insert(END, line + "\n")
  584. self.log_text.see(END)
  585. self.log_text.configure(state=DISABLED)
  586. self.root.after(200, self._flush_logs)
  587. if __name__ == "__main__":
  588. app_root = Tk()
  589. app = CollectorApp(app_root)
  590. app_root.mainloop()