web_whatsapp_session.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. """Preserve WhatsApp authentication state before dashboard re-pairing."""
  2. import tempfile
  3. from datetime import UTC, datetime
  4. from pathlib import Path
  5. from fastapi import HTTPException
  6. def _assert_whatsapp_bridge_stopped(session_path: Path) -> None:
  7. from gateway.status import _pid_exists, get_process_start_time
  8. pid_file = session_path / "bridge.pid"
  9. if not pid_file.exists():
  10. return
  11. unknown = "Cannot verify the WhatsApp bridge is stopped. Check its bridge.pid before re-pairing."
  12. try:
  13. lines = pid_file.read_text(encoding="utf-8-sig").splitlines()
  14. pid = int(lines[0])
  15. if pid <= 0:
  16. raise ValueError("invalid bridge PID")
  17. except (OSError, ValueError, IndexError) as exc:
  18. raise HTTPException(status_code=409, detail=unknown) from exc
  19. if not _pid_exists(pid):
  20. return
  21. try:
  22. recorded_start = int(lines[1])
  23. if recorded_start <= 0:
  24. raise ValueError("invalid bridge start time")
  25. except (ValueError, IndexError) as exc:
  26. raise HTTPException(status_code=409, detail=unknown) from exc
  27. current_start = get_process_start_time(pid)
  28. if current_start is None:
  29. raise HTTPException(status_code=409, detail=unknown)
  30. if current_start == recorded_start:
  31. raise HTTPException(status_code=409, detail="The WhatsApp bridge is still running. Stop it before re-pairing.")
  32. # Both fingerprints are available and differ. This is a recycled PID,
  33. # not evidence that the old bridge still owns the session.
  34. def _backup_whatsapp_session(session_path: Path) -> None:
  35. """Called while onboarding owns the session reservation. Never delete keys."""
  36. _assert_whatsapp_bridge_stopped(session_path)
  37. if session_path.is_symlink():
  38. raise HTTPException(status_code=409, detail="The WhatsApp session is a symbolic link. Back it up manually before re-pairing.")
  39. backup = None
  40. try:
  41. if session_path.exists():
  42. stamp = datetime.now(UTC).strftime("%Y%m%dT%H%M%SZ")
  43. backup = Path(tempfile.mkdtemp(prefix=f"session-backup-{stamp}-", dir=session_path.parent)) / "session"
  44. session_path.rename(backup)
  45. session_path.mkdir(mode=0o700)
  46. except OSError as exc:
  47. detail = f"Could not back up the WhatsApp session: {exc}. Pairing was not started."
  48. if backup is not None and backup.exists():
  49. detail += f" The previous session is preserved at {backup}."
  50. raise HTTPException(status_code=500, detail=detail) from exc