gui.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  1. """A simple tkinter GUI to edit config.json and manage protector list.
  2. Features:
  3. - Edit base_url, conn_threshold, scan_interval (saved to config.json)
  4. - Manage protector_list entries (add/edit/remove) stored in protector_list.json
  5. - On saving base_url, attempt login via auth_session.login() and store sess_key
  6. """
  7. from __future__ import annotations
  8. import json
  9. import threading
  10. import tkinter as tk
  11. from tkinter import messagebox
  12. from pathlib import Path
  13. from auth_session import load_config, get_base_url, login, set_sess_key
  14. import protector_list
  15. ROOT = Path(__file__).resolve().parent
  16. CONFIG_PATH = ROOT / "config.json"
  17. def load_cfg():
  18. return load_config()
  19. def save_cfg(cfg: dict):
  20. with open(CONFIG_PATH, "w", encoding="utf-8") as f:
  21. json.dump(cfg, f, ensure_ascii=False, indent=2)
  22. class ProtectorGUI(tk.Tk):
  23. def __init__(self):
  24. super().__init__()
  25. self.title("Protector GUI")
  26. self.geometry("700x500")
  27. self.cfg = load_cfg()
  28. # Config frame
  29. cf = tk.LabelFrame(self, text="Config")
  30. cf.pack(fill="x", padx=8, pady=6)
  31. tk.Label(cf, text="base_url:").grid(row=0, column=0, sticky="w")
  32. self.base_entry = tk.Entry(cf, width=60)
  33. self.base_entry.grid(row=0, column=1, padx=4, pady=2)
  34. tk.Label(cf, text="conn_threshold:").grid(row=1, column=0, sticky="w")
  35. self.th_entry = tk.Entry(cf, width=10)
  36. self.th_entry.grid(row=1, column=1, sticky="w", padx=4, pady=2)
  37. tk.Label(cf, text="scan_interval (s):").grid(row=2, column=0, sticky="w")
  38. self.interval_entry = tk.Entry(cf, width=10)
  39. self.interval_entry.grid(row=2, column=1, sticky="w", padx=4, pady=2)
  40. tk.Button(cf, text="Save Config", command=self.save_config).grid(row=3, column=1, sticky="w", pady=6)
  41. # Protector list frame
  42. lf = tk.LabelFrame(self, text="Protector List")
  43. lf.pack(fill="both", expand=True, padx=8, pady=6)
  44. self.listbox = tk.Listbox(lf)
  45. self.listbox.pack(side="left", fill="both", expand=True, padx=4, pady=4)
  46. self.listbox.bind("<<ListboxSelect>>", self.on_select)
  47. right = tk.Frame(lf)
  48. right.pack(side="right", fill="y", padx=4)
  49. tk.Label(right, text="target_ip:").pack(anchor="w")
  50. self.ip_entry = tk.Entry(right)
  51. self.ip_entry.pack(fill="x")
  52. tk.Label(right, text="src_port:").pack(anchor="w")
  53. self.port_entry = tk.Entry(right)
  54. self.port_entry.pack(fill="x")
  55. tk.Label(right, text="threshold (optional):").pack(anchor="w")
  56. self.entry_threshold = tk.Entry(right)
  57. self.entry_threshold.pack(fill="x")
  58. tk.Button(right, text="Add", command=self.add_entry).pack(fill="x", pady=4)
  59. tk.Button(right, text="Update", command=self.update_entry).pack(fill="x", pady=4)
  60. tk.Button(right, text="Remove", command=self.remove_entry).pack(fill="x", pady=4)
  61. self.load_values()
  62. def load_values(self):
  63. self.cfg = load_cfg()
  64. self.base_entry.delete(0, tk.END)
  65. self.base_entry.insert(0, self.cfg.get("base_url", ""))
  66. self.th_entry.delete(0, tk.END)
  67. self.th_entry.insert(0, str(self.cfg.get("conn_threshold", "")))
  68. self.interval_entry.delete(0, tk.END)
  69. self.interval_entry.insert(0, str(self.cfg.get("scan_interval", 60)))
  70. self.reload_listbox()
  71. def reload_listbox(self):
  72. self.listbox.delete(0, tk.END)
  73. items = protector_list.load_list()
  74. for i in items:
  75. self.listbox.insert(tk.END, f"{i['id']}: {i['target_ip']}:{i['src_port']} (th={i.get('threshold')})")
  76. def save_config(self):
  77. try:
  78. self.cfg["base_url"] = self.base_entry.get().strip()
  79. self.cfg["conn_threshold"] = int(self.th_entry.get().strip())
  80. self.cfg["scan_interval"] = int(self.interval_entry.get().strip())
  81. except Exception as e:
  82. messagebox.showerror("错误", f"配置输入无效: {e}")
  83. return
  84. save_cfg(self.cfg)
  85. # try login on a background thread
  86. def _login():
  87. try:
  88. resp, sess_cookie = login()
  89. if sess_cookie:
  90. set_sess_key(sess_cookie)
  91. messagebox.showinfo("登录", f"登录完成, 状态: {resp.status_code}")
  92. except Exception as e:
  93. messagebox.showerror("登录失败", str(e))
  94. threading.Thread(target=_login, daemon=True).start()
  95. def on_select(self, evt):
  96. sel = self.listbox.curselection()
  97. if not sel:
  98. return
  99. idx = sel[0]
  100. items = protector_list.load_list()
  101. if idx >= len(items):
  102. return
  103. item = items[idx]
  104. self.ip_entry.delete(0, tk.END)
  105. self.ip_entry.insert(0, item.get("target_ip", ""))
  106. self.port_entry.delete(0, tk.END)
  107. self.port_entry.insert(0, str(item.get("src_port", "")))
  108. self.entry_threshold.delete(0, tk.END)
  109. self.entry_threshold.insert(0, str(item.get("threshold", "")))
  110. def add_entry(self):
  111. ip = self.ip_entry.get().strip()
  112. port = self.port_entry.get().strip()
  113. th = self.entry_threshold.get().strip() or None
  114. if not ip or not port:
  115. messagebox.showerror("错误", "ip 与 port 为必填")
  116. return
  117. try:
  118. entry = protector_list.add_entry(ip, int(port), int(th) if th else None)
  119. self.reload_listbox()
  120. messagebox.showinfo("添加", f"已添加: {entry}")
  121. except Exception as e:
  122. messagebox.showerror("错误", str(e))
  123. def update_entry(self):
  124. sel = self.listbox.curselection()
  125. if not sel:
  126. messagebox.showerror("错误", "先选择一条")
  127. return
  128. idx = sel[0]
  129. items = protector_list.load_list()
  130. if idx >= len(items):
  131. return
  132. eid = items[idx]["id"]
  133. ip = self.ip_entry.get().strip()
  134. port = self.port_entry.get().strip()
  135. th = self.entry_threshold.get().strip() or None
  136. try:
  137. updated = protector_list.update_entry(eid, target_ip=ip, src_port=int(port), threshold=(int(th) if th else None))
  138. if updated is None:
  139. messagebox.showerror("错误", "更新失败")
  140. else:
  141. self.reload_listbox()
  142. messagebox.showinfo("更新", f"已更新: {updated}")
  143. except Exception as e:
  144. messagebox.showerror("错误", str(e))
  145. def remove_entry(self):
  146. sel = self.listbox.curselection()
  147. if not sel:
  148. messagebox.showerror("错误", "先选择一条")
  149. return
  150. idx = sel[0]
  151. items = protector_list.load_list()
  152. if idx >= len(items):
  153. return
  154. eid = items[idx]["id"]
  155. ok = protector_list.remove_entry(eid)
  156. if ok:
  157. self.reload_listbox()
  158. messagebox.showinfo("删除", "已删除")
  159. else:
  160. messagebox.showerror("错误", "删除失败")
  161. def run_gui():
  162. app = ProtectorGUI()
  163. app.mainloop()
  164. if __name__ == "__main__":
  165. run_gui()