protector_list.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. """Simple manager for the protector list stored in protector_list.json.
  2. Each entry is a dict with keys:
  3. - id: int (unique)
  4. - target_ip: str
  5. - src_port: int
  6. - threshold: int | None
  7. This module provides simple load/save/add/remove/update helpers.
  8. """
  9. from __future__ import annotations
  10. import json
  11. from pathlib import Path
  12. from typing import List, Optional, Dict
  13. import sys
  14. ROOT = Path(__file__).resolve().parent
  15. def _get_app_dir() -> Path:
  16. try:
  17. if getattr(sys, "frozen", False):
  18. return Path(sys.executable).resolve().parent
  19. except Exception:
  20. pass
  21. try:
  22. return Path.cwd()
  23. except Exception:
  24. return Path(__file__).resolve().parent
  25. ROOT = _get_app_dir()
  26. LIST_PATH = ROOT / "protector_list.json"
  27. def load_list() -> List[Dict]:
  28. if not LIST_PATH.exists():
  29. return []
  30. with open(LIST_PATH, "r", encoding="utf-8") as f:
  31. return json.load(f)
  32. def save_list(items: List[Dict]) -> None:
  33. with open(LIST_PATH, "w", encoding="utf-8") as f:
  34. json.dump(items, f, ensure_ascii=False, indent=2)
  35. def _next_id(items: List[Dict]) -> int:
  36. if not items:
  37. return 1
  38. return max(int(i.get("id", 0)) for i in items) + 1
  39. def add_entry(target_ip: str, src_port: int, threshold: Optional[int] = None) -> Dict:
  40. items = load_list()
  41. entry = {"id": _next_id(items), "target_ip": target_ip, "src_port": int(src_port), "threshold": (int(threshold) if threshold is not None else None)}
  42. items.append(entry)
  43. save_list(items)
  44. return entry
  45. def remove_entry(entry_id: int) -> bool:
  46. items = load_list()
  47. new_items = [i for i in items if int(i.get("id", -1)) != int(entry_id)]
  48. if len(new_items) == len(items):
  49. return False
  50. save_list(new_items)
  51. return True
  52. def update_entry(entry_id: int, **kwargs) -> Optional[Dict]:
  53. items = load_list()
  54. found = None
  55. for i in items:
  56. if int(i.get("id", -1)) == int(entry_id):
  57. i.update({k: v for k, v in kwargs.items() if v is not None})
  58. found = i
  59. break
  60. if found is None:
  61. return None
  62. save_list(items)
  63. return found
  64. if __name__ == "__main__":
  65. # quick demo
  66. print("Current protector list:")
  67. print(load_list())