|
| 1 | +import logging |
| 2 | + |
| 3 | +import requests |
| 4 | +from django.conf import settings |
| 5 | + |
| 6 | +logger = logging.getLogger(__name__) |
| 7 | + |
| 8 | + |
| 9 | +class MailmanAPIError(Exception): |
| 10 | + pass |
| 11 | + |
| 12 | + |
| 13 | +def _base_url() -> str: |
| 14 | + return settings.MAILMAN_REST_API_URL.rstrip("/") + settings.MAILMAN_REST_API_PATH |
| 15 | + |
| 16 | + |
| 17 | +def _auth() -> tuple[str, str]: |
| 18 | + return (settings.MAILMAN_REST_API_USER, settings.MAILMAN_REST_API_PASS) |
| 19 | + |
| 20 | + |
| 21 | +def subscribe(email: str, list_id: str) -> None: |
| 22 | + """POST /3.1/members — subscribe an email to a list. |
| 23 | +
|
| 24 | + All pre_* flags are True because Django owns the confirmation flow. This is |
| 25 | + only called after the user has clicked the Django confirmation link. |
| 26 | + """ |
| 27 | + url = f"{_base_url()}/members" |
| 28 | + payload = { |
| 29 | + "list_id": list_id, |
| 30 | + "subscriber": email, |
| 31 | + "pre_verified": True, |
| 32 | + "pre_confirmed": True, |
| 33 | + "pre_approved": True, |
| 34 | + } |
| 35 | + try: |
| 36 | + response = requests.post(url, data=payload, auth=_auth(), timeout=10) |
| 37 | + except requests.RequestException as exc: |
| 38 | + raise MailmanAPIError(f"Mailman API unreachable: {exc}") from exc |
| 39 | + |
| 40 | + if response.status_code == 409: |
| 41 | + # Already a member — treat as a no-op. |
| 42 | + return |
| 43 | + if not response.ok: |
| 44 | + raise MailmanAPIError( |
| 45 | + f"subscribe failed [{response.status_code}]: {response.text}" |
| 46 | + ) |
| 47 | + |
| 48 | + |
| 49 | +def is_confirmed(email: str, list_id: str) -> bool: |
| 50 | + """Return True if the email is a confirmed (active) member of the list.""" |
| 51 | + url = f"{_base_url()}/lists/{list_id}/member/{email}" |
| 52 | + try: |
| 53 | + response = requests.get(url, auth=_auth(), timeout=10) |
| 54 | + except requests.RequestException as exc: |
| 55 | + raise MailmanAPIError(f"Mailman API unreachable: {exc}") from exc |
| 56 | + |
| 57 | + if response.status_code == 404: |
| 58 | + return False |
| 59 | + if response.ok: |
| 60 | + return True |
| 61 | + raise MailmanAPIError( |
| 62 | + f"member lookup failed [{response.status_code}]: {response.text}" |
| 63 | + ) |
| 64 | + |
| 65 | + |
| 66 | +def _discard_pending(email: str, list_id: str) -> None: |
| 67 | + """Discard any pending (unconfirmed) subscription request for email on list_id.""" |
| 68 | + url = f"{_base_url()}/lists/{list_id}/requests" |
| 69 | + try: |
| 70 | + response = requests.get(url, auth=_auth(), timeout=10) |
| 71 | + except requests.RequestException as exc: |
| 72 | + raise MailmanAPIError(f"Mailman API unreachable: {exc}") from exc |
| 73 | + |
| 74 | + if not response.ok: |
| 75 | + raise MailmanAPIError( |
| 76 | + f"pending requests lookup failed [{response.status_code}]: {response.text}" |
| 77 | + ) |
| 78 | + |
| 79 | + entries = response.json().get("entries", []) |
| 80 | + token = next( |
| 81 | + ( |
| 82 | + e["token"] |
| 83 | + for e in entries |
| 84 | + if e.get("email") == email and e.get("type") == "subscription" |
| 85 | + ), |
| 86 | + None, |
| 87 | + ) |
| 88 | + if token is None: |
| 89 | + return |
| 90 | + |
| 91 | + discard_url = f"{_base_url()}/lists/{list_id}/requests/{token}" |
| 92 | + try: |
| 93 | + requests.post(discard_url, data={"action": "discard"}, auth=_auth(), timeout=10) |
| 94 | + except requests.RequestException as exc: |
| 95 | + raise MailmanAPIError(f"Mailman API unreachable: {exc}") from exc |
| 96 | + |
| 97 | + |
| 98 | +def unsubscribe(email: str, list_id: str) -> None: |
| 99 | + """DELETE /3.1/members/<id> — remove a subscription.""" |
| 100 | + url = f"{_base_url()}/lists/{list_id}/member/{email}" |
| 101 | + try: |
| 102 | + response = requests.get(url, auth=_auth(), timeout=10) |
| 103 | + except requests.RequestException as exc: |
| 104 | + raise MailmanAPIError(f"Mailman API unreachable: {exc}") from exc |
| 105 | + |
| 106 | + if response.status_code == 404: |
| 107 | + # Not a confirmed member — discard any pending subscription request so |
| 108 | + # the user can subscribe again cleanly. |
| 109 | + _discard_pending(email, list_id) |
| 110 | + return |
| 111 | + if not response.ok: |
| 112 | + raise MailmanAPIError( |
| 113 | + f"member lookup failed [{response.status_code}]: {response.text}" |
| 114 | + ) |
| 115 | + |
| 116 | + member_id = response.json().get("member_id") |
| 117 | + if not member_id: |
| 118 | + raise MailmanAPIError("member lookup returned no member_id") |
| 119 | + |
| 120 | + delete_url = f"{_base_url()}/members/{member_id}" |
| 121 | + try: |
| 122 | + del_response = requests.delete(delete_url, auth=_auth(), timeout=10) |
| 123 | + except requests.RequestException as exc: |
| 124 | + raise MailmanAPIError(f"Mailman API unreachable: {exc}") from exc |
| 125 | + |
| 126 | + if del_response.status_code == 404: |
| 127 | + return |
| 128 | + if not del_response.ok: |
| 129 | + raise MailmanAPIError( |
| 130 | + f"unsubscribe failed [{del_response.status_code}]: {del_response.text}" |
| 131 | + ) |
0 commit comments