Spaces:
Sleeping

File size: 2,220 Bytes
b3f4f50
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
"""
The public side of unsubscribing: the page an email's Unsubscribe link opens, and the one-click
POST that mail apps send on the reader's behalf. Nothing here needs a sign-in; the signed link
is the proof. The page asks for a click (GET never unsubscribes) so link scanners that open
every link in a message do not remove people by accident.
"""

from __future__ import annotations

import html

from fastapi import APIRouter, Request
from fastapi.responses import HTMLResponse

from backend import unsubscribe

router = APIRouter()


def _who(t: dict) -> str:
    return f"<b>{html.escape(t['mailbox'])}</b>" if t["mailbox"] else "this sender"


_BTN = "font:inherit;padding:10px 18px;cursor:pointer;margin:0 8px 8px 0"


@router.get("/u/{token}", response_class=HTMLResponse)
def unsubscribe_page(token: str):
    try:
        t = unsubscribe.read_token(token)
    except ValueError as exc:
        return HTMLResponse(unsubscribe.page("Link not valid", f"<p>{html.escape(str(exc))}.</p>"), status_code=400)
    every = (
        f'<button name="scope" value="all" style="{_BTN}">Stop all emails from this organisation</button>' if t["mailbox"] else ""
    )
    return unsubscribe.page(
        "Unsubscribe",
        f"<p>Stop emails from {_who(t)} to <b>{html.escape(t['email'])}</b>?</p>"
        f'<form method="post"><button name="scope" value="mailbox" style="{_BTN}">Unsubscribe</button>{every}</form>',
    )


@router.post("/u/{token}", response_class=HTMLResponse)
async def unsubscribe_now(token: str, request: Request):
    """The page's buttons send a scope. Mail apps' one-click button sends
    "List-Unsubscribe=One-Click" and opts out of the sending mailbox only."""
    try:
        form = await request.form()
        scope = form.get("scope")
        t = unsubscribe.unsubscribe_with_token(token, everything=scope == "all", how="link" if scope else "one-click")
    except ValueError as exc:
        return HTMLResponse(unsubscribe.page("Link not valid", f"<p>{html.escape(str(exc))}.</p>"), status_code=400)
    who = _who(t) if t["mailbox"] else "this organisation"
    return unsubscribe.page("You are unsubscribed", f"<p>{html.escape(t['email'])} will not get more emails from {who}.</p>")