protector_list.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. ROOT = Path(__file__).resolve().parent
  14. LIST_PATH = ROOT / "protector_list.json"
  15. def load_list() -> List[Dict]:
  16. if not LIST_PATH.exists():
  17. return []
  18. with open(LIST_PATH, "r", encoding="utf-8") as f:
  19. return json.load(f)
  20. def save_list(items: List[Dict]) -> None:
  21. with open(LIST_PATH, "w", encoding="utf-8") as f:
  22. json.dump(items, f, ensure_ascii=False, indent=2)
  23. def _next_id(items: List[Dict]) -> int:
  24. if not items:
  25. return 1
  26. return max(int(i.get("id", 0)) for i in items) + 1
  27. def add_entry(target_ip: str, src_port: int, threshold: Optional[int] = None) -> Dict:
  28. items = load_list()
  29. entry = {"id": _next_id(items), "target_ip": target_ip, "src_port": int(src_port), "threshold": (int(threshold) if threshold is not None else None)}
  30. items.append(entry)
  31. save_list(items)
  32. return entry
  33. def remove_entry(entry_id: int) -> bool:
  34. items = load_list()
  35. new_items = [i for i in items if int(i.get("id", -1)) != int(entry_id)]
  36. if len(new_items) == len(items):
  37. return False
  38. save_list(new_items)
  39. return True
  40. def update_entry(entry_id: int, **kwargs) -> Optional[Dict]:
  41. items = load_list()
  42. found = None
  43. for i in items:
  44. if int(i.get("id", -1)) == int(entry_id):
  45. i.update({k: v for k, v in kwargs.items() if v is not None})
  46. found = i
  47. break
  48. if found is None:
  49. return None
  50. save_list(items)
  51. return found
  52. if __name__ == "__main__":
  53. # quick demo
  54. print("Current protector list:")
  55. print(load_list())