|
| 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 | +class MailmanClient: |
| 14 | + """Thin wrapper around the Mailman REST API. |
| 15 | +
|
| 16 | + Instantiate with defaults (reads from settings) or pass explicit credentials |
| 17 | + to talk to a different Mailman instance: |
| 18 | +
|
| 19 | + client = MailmanClient() |
| 20 | + client = MailmanClient(base_url="http://other:8001", user="u", password="p") |
| 21 | + """ |
| 22 | + |
| 23 | + def __init__(self, base_url=None, api_version=None, user=None, password=None): |
| 24 | + url = (base_url or settings.MAILMAN_REST_API_URL).rstrip("/") |
| 25 | + version = api_version or settings.MAILMAN_REST_API_VERSION |
| 26 | + self._base = ( |
| 27 | + f"{url}/api-proxy/{version}" |
| 28 | + if not settings.LOCAL_DEVELOPMENT |
| 29 | + else f"{url}/{version}" |
| 30 | + ) |
| 31 | + self._credentials = ( |
| 32 | + user or settings.MAILMAN_REST_API_USER, |
| 33 | + password or settings.MAILMAN_REST_API_PASS, |
| 34 | + ) |
| 35 | + |
| 36 | + def subscribe(self, email: str, list_id: str) -> None: |
| 37 | + """POST /<version>/members — subscribe an email to a list. |
| 38 | +
|
| 39 | + All pre_* flags are True because Django owns the confirmation flow. This is |
| 40 | + only called after the user has clicked the Django confirmation link. |
| 41 | + """ |
| 42 | + url = f"{self._base}/members" |
| 43 | + payload = { |
| 44 | + "list_id": list_id, |
| 45 | + "subscriber": email, |
| 46 | + "pre_verified": True, |
| 47 | + "pre_confirmed": True, |
| 48 | + "pre_approved": True, |
| 49 | + } |
| 50 | + try: |
| 51 | + response = requests.post( |
| 52 | + url, data=payload, auth=self._credentials, timeout=10 |
| 53 | + ) |
| 54 | + except requests.RequestException as exc: |
| 55 | + raise MailmanAPIError(f"Mailman API unreachable: {exc}") from exc |
| 56 | + |
| 57 | + if response.status_code == 409: |
| 58 | + # Already a member — treat as a no-op. |
| 59 | + return |
| 60 | + if not response.ok: |
| 61 | + raise MailmanAPIError( |
| 62 | + f"subscribe failed [{response.status_code}]: {response.text}" |
| 63 | + ) |
| 64 | + |
| 65 | + def is_confirmed(self, email: str, list_id: str) -> bool: |
| 66 | + """Return True if the email is a confirmed (active) member of the list.""" |
| 67 | + url = f"{self._base}/lists/{list_id}/member/{email}" |
| 68 | + try: |
| 69 | + response = requests.get(url, auth=self._credentials, timeout=10) |
| 70 | + except requests.RequestException as exc: |
| 71 | + raise MailmanAPIError(f"Mailman API unreachable: {exc}") from exc |
| 72 | + |
| 73 | + if response.status_code == 404: |
| 74 | + return False |
| 75 | + if response.ok: |
| 76 | + return True |
| 77 | + raise MailmanAPIError( |
| 78 | + f"member lookup failed [{response.status_code}]: {response.text}" |
| 79 | + ) |
| 80 | + |
| 81 | + def _discard_pending(self, email: str, list_id: str) -> None: |
| 82 | + """Discard any pending (unconfirmed) subscription request for email on list_id.""" |
| 83 | + url = f"{self._base}/lists/{list_id}/requests" |
| 84 | + try: |
| 85 | + response = requests.get(url, auth=self._credentials, timeout=10) |
| 86 | + except requests.RequestException as exc: |
| 87 | + raise MailmanAPIError(f"Mailman API unreachable: {exc}") from exc |
| 88 | + |
| 89 | + if not response.ok: |
| 90 | + raise MailmanAPIError( |
| 91 | + f"pending requests lookup failed [{response.status_code}]: {response.text}" |
| 92 | + ) |
| 93 | + |
| 94 | + entries = response.json().get("entries", []) |
| 95 | + token = next( |
| 96 | + ( |
| 97 | + e["token"] |
| 98 | + for e in entries |
| 99 | + if e.get("email") == email and e.get("type") == "subscription" |
| 100 | + ), |
| 101 | + None, |
| 102 | + ) |
| 103 | + if token is None: |
| 104 | + return |
| 105 | + |
| 106 | + discard_url = f"{self._base}/lists/{list_id}/requests/{token}" |
| 107 | + try: |
| 108 | + discard_response = requests.post( |
| 109 | + discard_url, |
| 110 | + data={"action": "discard"}, |
| 111 | + auth=self._credentials, |
| 112 | + timeout=10, |
| 113 | + ) |
| 114 | + except requests.RequestException as exc: |
| 115 | + raise MailmanAPIError(f"Mailman API unreachable: {exc}") from exc |
| 116 | + |
| 117 | + if discard_response.status_code == 404: |
| 118 | + return |
| 119 | + if not discard_response.ok: |
| 120 | + raise MailmanAPIError( |
| 121 | + f"discard pending failed [{discard_response.status_code}]" |
| 122 | + ) |
| 123 | + |
| 124 | + def unsubscribe(self, email: str, list_id: str) -> None: |
| 125 | + """DELETE /<version>/members/<id> — remove a subscription.""" |
| 126 | + url = f"{self._base}/lists/{list_id}/member/{email}" |
| 127 | + try: |
| 128 | + response = requests.get(url, auth=self._credentials, timeout=10) |
| 129 | + except requests.RequestException as exc: |
| 130 | + raise MailmanAPIError(f"Mailman API unreachable: {exc}") from exc |
| 131 | + |
| 132 | + if response.status_code == 404: |
| 133 | + # Not a confirmed member — discard any pending subscription request so |
| 134 | + # the user can subscribe again cleanly. |
| 135 | + self._discard_pending(email, list_id) |
| 136 | + return |
| 137 | + if not response.ok: |
| 138 | + raise MailmanAPIError( |
| 139 | + f"member lookup failed [{response.status_code}]: {response.text}" |
| 140 | + ) |
| 141 | + |
| 142 | + member_id = response.json().get("member_id") |
| 143 | + if not member_id: |
| 144 | + raise MailmanAPIError("member lookup returned no member_id") |
| 145 | + |
| 146 | + delete_url = f"{self._base}/members/{member_id}" |
| 147 | + try: |
| 148 | + del_response = requests.delete( |
| 149 | + delete_url, auth=self._credentials, timeout=10 |
| 150 | + ) |
| 151 | + except requests.RequestException as exc: |
| 152 | + raise MailmanAPIError(f"Mailman API unreachable: {exc}") from exc |
| 153 | + |
| 154 | + if del_response.status_code == 404: |
| 155 | + return |
| 156 | + if not del_response.ok: |
| 157 | + raise MailmanAPIError( |
| 158 | + f"unsubscribe failed [{del_response.status_code}]: {del_response.text}" |
| 159 | + ) |
0 commit comments