#!/usr/bin/env python3 """Build the website into dist/. .venv/bin/python build.py --drafts --serve # local preview at http://localhost:8000 python3 build.py # what deploys: verified entries only Facts come from the data repo (../data by default, or --data / $DATA_DIR). Its validator runs first, so an invalid entry stops the build. A guide whose entry is still a draft stops the build too, unless --drafts is given, in which case every page shows a draft banner and check_dist.py refuses to deploy it. """ import argparse import datetime as dt import email.utils import functools import hashlib import html import http.client import http.server import json import os import pathlib import re import shutil import ssl import subprocess import sys import urllib.parse import urllib.error import urllib.request import urllib.robotparser import xml.etree.ElementTree as ET import markdown import yaml from jinja2 import Environment, FileSystemLoader, StrictUndefined, select_autoescape from markupsafe import Markup, escape try: # python.org builds on macOS ship without CA certificates; certifi fills the gap. import certifi TLS = ssl.create_default_context(cafile=certifi.where()) except ImportError: TLS = ssl.create_default_context() ROOT = pathlib.Path(__file__).resolve().parent # Requests say who is asking, instead of posing as a browser. USER_AGENT = "ArbitrationWatch/1.0 (+https://arbitrationwatch.org/methodology/)" class BuildError(Exception): pass # --------------------------------------------------------------------------- # Data def load_entries(data_dir, drafts): validator = data_dir / "scripts" / "validate.py" result = subprocess.run([sys.executable, str(validator), str(data_dir / "entries")]) if result.returncode != 0: raise BuildError("the data repo's validator found problems (listed above)") entries = {} for path in sorted((data_dir / "entries").glob("*.yaml")): entry = yaml.safe_load(path.read_text(encoding="utf-8")) if entry["status"] == "verified" or drafts: entries[entry["id"]] = entry return entries # --------------------------------------------------------------------------- # In the news: headlines from publishers' own RSS feeds (site.yaml lists them), fetched # here at build time so visitors' browsers never contact them. A daily scheduled rebuild # keeps them fresh. Each feed is read only while its site's robots.txt allows it. # A headline counts when its title mentions arbitration, or its summary uses one of these. ARBITRATION_TOPIC = re.compile( r"forced arbitration|mandatory arbitration|arbitration (clause|agreement|provision|polic|requirement)" r"|class[- ]action waiver|mass arbitration|opt(ing)? out of arbitration", re.I) def fetch_url(url, timeout): request = urllib.request.Request(url, headers={"User-Agent": USER_AGENT}) with urllib.request.urlopen(request, timeout=timeout, context=TLS) as response: return response.read() def robots_allow(url, timeout): """True when the site's robots.txt lets this project fetch the URL. A missing robots.txt allows everything; one that can't be read allows nothing.""" parts = urllib.parse.urlsplit(url) robots = urllib.robotparser.RobotFileParser() try: text = fetch_url(f"{parts.scheme}://{parts.netloc}/robots.txt", timeout) except urllib.error.HTTPError as error: return error.code == 404 except (OSError, http.client.HTTPException): return False robots.parse(text.decode("utf-8", "replace").splitlines()) return robots.can_fetch(USER_AGENT, url) def fetch_feed(feed, settings): timeout = settings.get("timeout", 10) if not robots_allow(feed["url"], timeout): print(f"Warning: robots.txt doesn't allow {feed['url']}; skipping it.", file=sys.stderr) return [] try: root = ET.fromstring(fetch_url(feed["url"], timeout)) except (OSError, ET.ParseError, http.client.HTTPException) as error: print(f"Warning: couldn't fetch {feed['url']} ({error}); skipping it.", file=sys.stderr) return [] host = urllib.parse.urlsplit(feed["url"]).netloc oldest = dt.date.today() - dt.timedelta(days=settings.get("max_age_days", 90)) items = [] for item in root.findall("./channel/item"): title = re.sub(r"\s+", " ", html.unescape(item.findtext("title") or "")).strip() summary = html.unescape(re.sub(r"<[^>]+>", " ", item.findtext("description") or "")) link = (item.findtext("link") or "").strip() try: date = email.utils.parsedate_to_datetime(item.findtext("pubDate")).date() except (TypeError, ValueError): continue on_topic = re.search("arbitrat", title, re.I) or ARBITRATION_TOPIC.search(summary) if not (title and on_topic and date >= oldest and link.startswith("https://")): continue link, outlet = link.split("#")[0], feed["outlet"] if urllib.parse.urlsplit(link).netloc != host: # A press mention: the feed links to another outlet's article, titled # "Outlet: Headline". Anything else that leaves the site is skipped. outlet, colon, headline = title.partition(": ") if not (feed.get("mentions") and colon and headline and len(outlet) <= 60): continue title = headline.strip() items.append({"title": title, "outlet": outlet.strip(), "url": link, "date": date}) return items def outlet_initials(outlet): """Letters for an outlet's badge in "In the news": "CBS News" -> "CBS", "NCLC" -> "NC", "Quiver Quantitative" -> "QQ", "Medill on the Hill" -> "MH", "GamesIndustry.biz" -> "GA".""" small = {"the", "a", "an", "of", "on", "in", "and", "for", "at", "to"} domains = {"com", "org", "net", "gov", "biz", "news"} words = [re.sub(r"[^A-Za-z0-9]", "", w) for w in re.split(r"[\s.]+", outlet)] words = [w for w in words if w and w.lower() not in small] if not words: return "?" first = words[0] if first.isupper() and len(first) >= 2: return first if len(first) <= 3 else first[:2] rest = [w for w in words[1:] if w.lower() not in domains] if rest: return (first[0] + rest[0][0]).upper() return first[:2].upper() def outlet_color(outlet): """The same outlet always gets the same of 8 badge colors.""" return int(hashlib.sha256(outlet.lower().encode("utf-8")).hexdigest(), 16) % 8 def normalize_title(title): return re.sub(r"[^a-z0-9]+", " ", title.lower()).strip() NEWS_CACHE = ROOT / ".cache" / "news.json" def fetch_feeds_cached(settings, max_age_hours=6): """Reuse a recent fetch when there is one (local builds); CI builds start empty.""" now = dt.datetime.now(dt.timezone.utc) feeds = [feed["url"] for feed in settings["feeds"]] if NEWS_CACHE.is_file(): cached = json.loads(NEWS_CACHE.read_text(encoding="utf-8")) fetched = dt.datetime.fromisoformat(cached["fetched"]) if cached.get("feeds") == feeds and now - fetched < dt.timedelta(hours=max_age_hours): return [{**item, "date": dt.date.fromisoformat(item["date"])} for item in cached["items"]] items = [item for feed in settings["feeds"] for item in fetch_feed(feed, settings)] if items: NEWS_CACHE.parent.mkdir(exist_ok=True) NEWS_CACHE.write_text(json.dumps({"fetched": now.isoformat(), "feeds": feeds, "items": [{**i, "date": i["date"].isoformat()} for i in items]}), encoding="utf-8") return items def load_news(data_dir, settings): """Hand-picked headlines from the data repo's news.yaml plus the publishers' feeds. A hand-picked headline wins over the same story from a feed.""" path = data_dir / "news.yaml" curated = (yaml.safe_load(path.read_text(encoding="utf-8")) or []) if path.is_file() else [] seen = {normalize_title(item["title"]) for item in curated} news = list(curated) for item in fetch_feeds_cached(settings): key = normalize_title(item["title"]) if key not in seen: seen.add(key) news.append(item) return sorted(news, key=lambda item: item["date"], reverse=True) UNVERIFIED_SHORT = {} # filled from site.yaml in build() METHOD_WORDS = {"mail": "Mail", "email": "Email", "online": "Online form", "phone": "Phone"} def how_to_reject(entry, tiers): """One short line for the company list: how and by when you can reject.""" if entry.get("summary"): return entry["summary"] tier = entry["tier"] if tier == "unverified" and entry.get("unverified_reason") in UNVERIFIED_SHORT: return UNVERIFIED_SHORT[entry["unverified_reason"]] if tier not in ("easy", "mail"): return tiers[tier].get("note", "") return reject_line(entry) def deadline_passed(opt_out): """True once a dated deadline is behind us. Builds run daily, so a page that also has a window (new accounts) switches to it the day after.""" return bool(opt_out.get("deadline")) and opt_out["deadline"] < dt.date.today() def reject_line(entry): """How and by when a rejection must be sent, ignoring any summary: "Mail, within 30 days of opening the account". Only for entries that can be rejected.""" o = entry["opt_out"] method = METHOD_WORDS[o["method"]] window = f"within {o['window_days']} days of {o.get('window_starts', 'opening')}" if o.get("window_days") else None if o["deadline_type"] == "days-after-opening" or (window and deadline_passed(o)): return f"{method}, {window}" when = "arriving by" if o["deadline_type"] == "received" else "postmarked by" if window: return f"{method}, {when} {o['deadline']:%b} {o['deadline'].day}, {o['deadline'].year}, or {window} if later" return f"{method}, {when} {o['deadline']:%b} {o['deadline'].day}, {o['deadline'].year}" # --------------------------------------------------------------------------- # Company names, page descriptions and share cards NAME_FILLER = {"bank", "credit", "union", "federal", "savings", "na", "the", "of", "from", "by", "a", "and", "inc", "llc", "fsb", "ssb"} def _word(word): return re.sub(r"[^a-z0-9&*]", "", word.lower()) def entry_name(entry): """The product, led by the company's name once: "Chase personal checking and savings accounts (JPMorgan Chase Bank, N.A.)", "Wealthfront Cash Account".""" product = entry["product"] company = re.sub(r"\s*\([^)]*\)", "", entry["institution"]).strip() names = {_word(w) for w in company.split()} - NAME_FILLER first = _word(re.sub(r"^the\s+", "", product, flags=re.I).split()[0]) if product.lower().startswith(company.lower()) or first in names: return product[:1].upper() + product[1:] # "Checking and savings accounts" reads as "Navy Federal Credit Union checking and # savings accounts"; a name like "Personal Savings" keeps its capitals. words = product.split() if words[0].rstrip(",") in ("Checking", "Personal", "Savings") and len(words) > 1 and words[1][:1].islower(): product = product[:1].lower() + product[1:] return f"{entry['institution']} {product}" def short_name(entry): """entry_name without the parentheses, for page titles, previews and cards. The page itself shows the full product.""" return re.sub(r"\s*\([^)]*\)", "", entry_name(entry)).strip() METHOD_BY = {"mail": "by mail", "email": "by email", "online": "online", "phone": "by phone"} def entry_description(entry): """The page's search and link-preview text. Names the product once and says the rating in words; never a date, since it only changes with the entry.""" name = short_name(entry) name = name[:4].lower() + name[4:] if name.startswith("The ") else name agreement = f"The agreement for {name}" tier = entry["tier"] if tier == "none": return f"{agreement} has no arbitration clause. Every fact is quoted from the agreement, with links." if tier in ("easy", "mail"): return (f"{agreement} has an arbitration clause you can reject " f"{METHOD_BY[entry['opt_out']['method']]}. How, by when and who it covers, " f"quoted from the agreement.") if tier == "no-opt-out": return (f"{agreement} has an arbitration clause with no way to reject it. " f"What it covers, quoted from the agreement.") if entry.get("unverified_reason") == "unclear": return (f"{agreement} doesn't say clearly whether disputes go to arbitration. " f"The wording, quoted from the agreement.") return f"{agreement} couldn't be read, so its arbitration terms couldn't be checked." CARD_LINES = { "none": "The agreement has no arbitration clause.", "no-opt-out": "There’s an arbitration clause, with no way to reject it.", "unverified": "The agreement couldn’t be read, so it couldn’t be checked.", } CARDS_LIST = ROOT / ".cache" / "share-cards.json" def company_card(entry, site): """What a company page's share card says. The PNG's name carries a hash of this, so a card drawn before the entry changed is never used: the page falls back to the default.""" tier = entry["tier"] if tier in ("easy", "mail"): rest = reject_line(entry).split(", ", 1)[1] method = METHOD_BY[entry["opt_out"]["method"]] line = f"{method[:1].upper()}{method[1:]}, {rest}." elif entry.get("unverified_reason") == "unclear": line = "The agreement doesn’t say clearly whether disputes go to arbitration." else: line = CARD_LINES[tier] curly = lambda text: text.replace("'", "’") card = {"id": entry["id"], "title": curly(short_name(entry)), "tier": tier, "label": curly(site["tiers"][tier]["label"]), "line": curly(line)} key = hashlib.sha256(json.dumps(card, sort_keys=True).encode()).hexdigest()[:10] return {**card, "file": f"companies/{entry['id']}-{key}.png"} def card_share(entry, site, missing): """The page's share image: its own card if drawn, else None (the default card).""" card = company_card(entry, site) if not (ROOT / "static" / "share" / card["file"]).is_file(): missing.append(entry["id"]) return None return {"file": card["file"], "alt": f"{card['title']}: {card['label']}"} QUOTE_LABELS = { "arbitration": "Arbitration", "class_action_waiver": "Class actions", "jury": "Jury trial", "effective": "When it starts", "opt_out": "How to reject it", "deadline": "Deadline", "address": "Where to send it", "required": "What to include", "applies_to": "Which accounts a rejection covers", "no_other_change": "What rejecting doesn't change", "joint": "Joint accounts", "future_accounts": "Future accounts", "missed": "If you miss the deadline", "small_claims": "Small claims court", "military": "Service members", "no_opt_out": "No way to reject", "all_accounts": "“All Accounts”", "not_part": "What rejecting does", } def quote_label(name, quote, entry): """The heading shown above a quote: the quote's own `label`, a standard one, or its name. In a `none` entry, `arbitration` holds the clause that says where disputes go.""" if quote.get("label"): return quote["label"] if name == "arbitration" and entry["tier"] == "none": return "Where disputes go" return QUOTE_LABELS.get(name, name.replace("_", " ").capitalize()) def monogram(institution): """Two letters for the circle in the company list. Several words give two capitals ("Ally Bank" -> "AB", "Capital One" -> "CO"); one word gives a capital and a lowercase letter ("Discover" -> "Di", "Chime" -> "Ch"). A "by ..." part is the parent company and is ignored ("Marcus by Goldman Sachs" -> "Ma").""" name = re.split(r"\s+by\s+", institution.strip(), maxsplit=1)[0] small = {"the", "of", "and", "for", "a", "an"} words = [w for w in re.findall(r"[A-Za-z0-9]+", name) if w.lower() not in small] if not words: return "?" if len(words) >= 2: return (words[0][0] + words[1][0]).upper() word = words[0] if word.isupper(): # an acronym keeps its capitals: "USAA" -> "US" return word[:2] return word[0].upper() + word[1:2].lower() def entry_links(entries, guides): """The page for each entry: its hand-written guide, or /companies//.""" links = {guide["entry"]: f"/{guide['slug']}/" for guide in guides} links.update({eid: f"/companies/{eid}/" for eid in entries if eid not in links}) return links def related_services(entries, guides): """For each entry, the company's other published entries, and whether their ratings differ. Entries rated `unverified` don't count as differing, since their rules aren't known.""" links = entry_links(entries, guides) groups = {} for eid, entry in entries.items(): groups.setdefault(entry["institution"], []).append(eid) related = {} for eid, entry in entries.items(): others = [entries[o] for o in groups[entry["institution"]] if o != eid] known = {e["tier"] for e in [entry, *others] if e["tier"] != "unverified"} related[eid] = { "differs": len(known) > 1, "services": sorted( ({"product": o["product"][:1].upper() + o["product"][1:], "tier": o["tier"], "url": links[o["id"]]} for o in others), key=lambda r: r["product"].lower()), } return related def company_rows(entries, guides, tiers): links = entry_links(entries, guides) related = related_services(entries, guides) alerts = {} for guide in guides: entry = entries.get(guide["entry"]) if entry and (entry.get("opt_out") or {}).get("deadline") and not deadline_passed(entry["opt_out"]): d = entry["opt_out"]["deadline"] e = entry.get("effective") alerts[guide["entry"]] = (f"Terms change: arbitration starts {e:%b} {e.day}, {e.year}" if e else f"Terms change: rejections due {d:%b} {d.day}, {d.year}") tier_order = list(tiers) rows = [] for entry in entries.values(): can_reject = entry["tier"] in ("easy", "mail") rows.append({ "id": entry["id"], "institution": entry["institution"], "monogram": monogram(entry["institution"]), "product": entry["product"][:1].upper() + entry["product"][1:], "kind": entry["kind"], "tier": entry["tier"], "tier_rank": tier_order.index(entry["tier"]), "how": how_to_reject(entry, tiers), "method": entry["opt_out"]["method"] if can_reject else None, "reject": reject_line(entry) if can_reject else None, "dated": can_reject and entry["opt_out"]["deadline_type"] != "days-after-opening" and not (entry["opt_out"].get("window_days") and deadline_passed(entry["opt_out"])), "last_verified": entry["last_verified"], "url": links.get(entry.get("id")), "alert": alerts.get(entry.get("id")), "differs": related[entry["id"]]["differs"], }) return sorted(rows, key=lambda r: (r["institution"].lower(), r["product"].lower())) def read_markdown_page(path): """Split a content/*.md file into its YAML front matter and Markdown body.""" text = path.read_text(encoding="utf-8") if not text.startswith("---\n"): raise BuildError(f"{path.name} must start with --- front matter") _, front, body = text.split("---\n", 2) return yaml.safe_load(front), body # --------------------------------------------------------------------------- # Template helpers def long_date(value): return f"{value:%A}, {value:%B} {value.day}, {value.year}" def short_date(value): return f"{value:%B} {value.day}, {value.year}" def abbr_date(value): return f"{value:%b} {value.day}, {value.year}" def make_cite(entry): """cite('deadline') links a fact to its verbatim quote by number, and fails the build when the entry has no quote for that fact. The number is the quote's place in "Sources and exact wording", which shows the same number.""" numbers = {name: i for i, name in enumerate(entry["quotes"], start=1)} def cite(name): if name not in entry["quotes"]: raise BuildError(f"the page cites quotes.{name}, which {entry['id']}.yaml doesn't have") return Markup( f'{numbers[name]}' ) return cite def renumber_citations(page): """Number a page's quotes in the order the text first cites them (1, 2, 3 down the page), and list "Sources and exact wording" in that order; uncited quotes go last.""" cited = [] for name in re.findall(r')(.*?)(\n \n)', page, re.S) if not block: return page figures = re.findall(r'\s*
.*?
', block.group(2), re.S) names = [re.search(r'id="q-([^"]+)"', f).group(1) for f in figures] order = cited + [n for n in names if n not in cited] number = {name: i for i, name in enumerate(order, start=1)} by_name = dict(zip(names, figures)) listed = "".join(re.sub(r'\d+', f'{number[n]}', by_name[n]) for n in order if n in by_name) rest = block.group(2) for f in figures: rest = rest.replace(f, "", 1) page = page[:block.start(2)] + listed + rest + page[block.end(2):] return re.sub(r'
\d+', lambda m: (f'{number[m.group(1)]}'), page) def asset_url(name): digest = hashlib.sha256((ROOT / "static" / name).read_bytes()).hexdigest()[:10] return f"/static/{name}?v={digest}" # --------------------------------------------------------------------------- # Calendar reminder (the same file for everyone, so it can be static) def ics_escape(text): return (text.replace("\\", "\\\\").replace(";", "\\;") .replace(",", "\\,").replace("\n", "\\n")) def ics_fold(line): """Fold lines longer than 75 octets, as RFC 5545 requires.""" out, current = [], "" for char in line: if len((current + char).encode("utf-8")) > 75: out.append(current) current = " " + char else: current += char out.append(current) return "\r\n".join(out) def reminder(site, page_path, entry, mail_by=None): """A calendar reminder to mail the letter, for a mail opt-out with a calendar deadline. Without a suggested date, it falls 10 days before a deadline the letter must arrive by, or 3 days before a postmark deadline.""" o = entry.get("opt_out") or {} deadline = o.get("deadline") if entry["tier"] != "mail" or o.get("method") != "mail" or not deadline: return None if mail_by is None: mail_by = deadline - dt.timedelta(days=10 if o.get("deadline_type") == "received" else 3) address = o["address"].strip() page = f"{site['url']}{page_path}" title = f"Mail your letter rejecting {entry['institution']}'s arbitration agreement" details = ( f"{entry['institution']} must receive your letter by {long_date(deadline)}.\n\n" f"Mail it to:\n{address}\n\n" f"Sign it by hand. Certified Mail with Return Receipt gives you proof of delivery.\n\n" f"Instructions and a free letter: {page}" ) return {"title": title, "details": details, "start": mail_by, "end": mail_by + dt.timedelta(days=1), "uid": f"{page_path.strip('/').replace('/', '-')}-mail-by"} # --------------------------------------------------------------------------- # Change feeds (Atom): one per company, from its `changes` log, and one for the site def atom_feed(site, title, self_url, page_url, items): """items: dicts with date, title, summary, url and id, newest first.""" esc = lambda text: html.escape(str(text), quote=True) stamp = lambda day: f"{day.isoformat()}T00:00:00Z" updated = stamp(items[0]["date"]) if items else stamp(dt.date.today()) lines = ['', '', f" {esc(title)}", f' ', f' ', f" {esc(self_url)}", f" {updated}", f" {esc(site['name'])}"] for item in items: lines += [" ", f" {esc(item['title'])}", f' ', f" {esc(item['id'])}", f" {stamp(item['date'])}", f" {esc(item['summary'])}", " "] lines.append("") return "\n".join(lines) + "\n" def change_items(site, entry, path): items = [] for i, change in enumerate(entry.get("changes") or []): items.append({"date": change["date"], "title": change["summary"], "summary": change["summary"], "url": f"{site['url']}{path}", "id": f"tag:arbitrationwatch.org,2026:{entry['id']}/{change['date']}/{len(entry['changes']) - i}"}) return items def watch_links(site, entry, path): """Where to follow a company: its feed in a reader, or a Google Alert for news.""" feed = f"{site['url']}{path}feed.xml" q = urllib.parse.quote brand = re.sub(r"\s*\([^)]*\)", "", entry["institution"]).strip() return { "feed": feed, "feedly": "https://feedly.com/i/subscription/feed%2F" + q(feed, safe=""), "inoreader": "https://www.inoreader.com/?add_feed=" + q(feed, safe=""), "newsblur": "https://www.newsblur.com/?url=" + q(feed, safe=""), "google_alert": "https://www.google.com/alerts?q=" + q(f'"{brand}" arbitration', safe=""), "brand": brand, } def reminder_ics(site, event, stamp): lines = [ "BEGIN:VCALENDAR", "VERSION:2.0", f"PRODID:-//{site['name']}//EN", "CALSCALE:GREGORIAN", "METHOD:PUBLISH", "BEGIN:VEVENT", f"UID:{event['uid']}@{urllib.parse.urlparse(site['url']).hostname}", f"DTSTAMP:{stamp:%Y%m%dT%H%M%SZ}", f"DTSTART;VALUE=DATE:{event['start']:%Y%m%d}", f"DTEND;VALUE=DATE:{event['end']:%Y%m%d}", f"SUMMARY:{ics_escape(event['title'])}", f"DESCRIPTION:{ics_escape(event['details'])}", "TRANSP:TRANSPARENT", # Two reminders: a week ahead, and the morning of the day (9:00 local). "BEGIN:VALARM", "ACTION:DISPLAY", f"DESCRIPTION:{ics_escape(event['title'])}", "TRIGGER:-P6DT15H", "END:VALARM", "BEGIN:VALARM", "ACTION:DISPLAY", f"DESCRIPTION:{ics_escape(event['title'])}", "TRIGGER:PT9H", "END:VALARM", "END:VEVENT", "END:VCALENDAR", ] return "\r\n".join(ics_fold(line) for line in lines) + "\r\n" def letter_config(entry): """The entry's `opt_out.letter` (data repo): which fields the letter has, its statement, and which part covers each required item. validate.py checks the coverage.""" o = entry.get("opt_out") or {} return (o.get("letter") or {}) if o.get("method") == "mail" else {} def letter_fits(entry, guide=None): """A letter is made only from a complete `opt_out.letter` with a statement (or the guide's own letter), and never when the company requires its own form.""" cfg = letter_config(entry) if not cfg or cfg.get("form"): return False return bool(cfg.get("statement") or (guide and guide.get("letter"))) def opt_out_mailto(entry): """A draft email for an email opt-out. A subject line the agreement requires is used as the subject; "send it from..." stays on the page, since it isn't part of the text.""" o = entry.get("opt_out") or {} if o.get("method") != "email" or not o.get("email"): return None subject = "Rejection of Arbitration Agreement" lines = ["I reject the arbitration agreement for my account.", ""] for item in o.get("required") or []: low = item.lower() if "signature" in low or low.startswith("send it from"): continue # an email can't carry a handwritten signature; the sender isn't text if low.startswith("subject line:"): subject = item.split(":", 1)[1].strip() continue lines.append(f"{item[:1].upper()}{item[1:]}: ") query = urllib.parse.urlencode({"subject": subject, "body": "\n".join(lines)}, quote_via=urllib.parse.quote) return f"mailto:{o['email']}?{query}" def google_calendar_url(event): query = urllib.parse.urlencode({ "action": "TEMPLATE", "text": event["title"], "dates": f"{event['start']:%Y%m%d}/{event['end']:%Y%m%d}", "details": event["details"], }, quote_via=urllib.parse.quote) return f"https://calendar.google.com/calendar/render?{query}" # --------------------------------------------------------------------------- # Build def json_ready(value): if isinstance(value, dict): return {k: json_ready(v) for k, v in value.items()} if isinstance(value, list): return [json_ready(v) for v in value] if isinstance(value, (dt.date, dt.datetime)): return value.isoformat() return value def write(path, text): path.parent.mkdir(parents=True, exist_ok=True) path.write_text(text, encoding="utf-8", newline="") # --------------------------------------------------------------------------- # "On this page" (templates/_outline.html): pages that ask for it get a list of their # sections when they have at least OUTLINE_MIN. OUTLINE_MIN = 3 def outline(page): """Give every h2 inside
an id (keeping one it already has) and list them in order. An h2 marked data-no-outline stays out of the list.""" start, end = page.find("") if start < 0 or end < 0: return page, [] taken, items = set(re.findall(r'\sid="([^"]+)"', page)), [] def add(match): attrs, inner = match.group(1) or "", match.group(2) text = html.unescape(re.sub(r"\s+", " ", re.sub(r"<[^>]+>", "", inner))).strip() if not text or "data-no-outline" in attrs: return match.group(0) found = re.search(r'\sid="([^"]+)"', attrs) if found: hid = found.group(1) else: base = re.sub(r"[^a-z0-9]+", "-", text.lower()).strip("-") or "section" hid, n = base, 2 while hid in taken: hid, n = f"{base}-{n}", n + 1 taken.add(hid) attrs += f' id="{hid}"' items.append({"id": hid, "text": text}) return f"{inner}" main = re.sub(r"]*)?>(.*?)", add, page[start:end], flags=re.S) return page[:start] + main + page[end:], items def build(data_dir, out, drafts): site = yaml.safe_load((ROOT / "site.yaml").read_text(encoding="utf-8")) entries = load_entries(data_dir, drafts) UNVERIFIED_SHORT.update({k: v["short"] for k, v in site.get("unverified_reasons", {}).items()}) news = load_news(data_dir, site["news"]) previous = None for item in news: # each outlet keeps its color, unless it would match the row above color = outlet_color(item["outlet"]) while color == previous: color = (color + 1) % 8 item["badge"] = previous = color today = dt.date.today() stamp = dt.datetime.now(dt.timezone.utc) env = Environment( loader=FileSystemLoader(ROOT / "templates"), autoescape=select_autoescape(["html", "xml"]), undefined=StrictUndefined, trim_blocks=True, lstrip_blocks=True, ) env.filters["long_date"] = long_date # "Cash App (Block, Inc.)" -> "Cash App": the name people know, for buttons and steps. env.filters["brand"] = lambda name: re.sub(r"\s*\([^)]*\)", "", name).strip() env.filters["short_date"] = short_date env.filters["abbr_date"] = abbr_date env.filters["initials"] = outlet_initials env.filters["outlet_color"] = outlet_color env.globals.update(site=site, asset=asset_url, build_date=today, quote_label=quote_label) env.globals["timeline"] = yaml.safe_load((ROOT / "content" / "timeline.yaml").read_text(encoding="utf-8")) if out.exists(): shutil.rmtree(out) out.mkdir(parents=True) shutil.copytree(ROOT / "static", out / "static") # Browsers, phones and crawlers ask for these at the root. for name in ("favicon.ico", "apple-touch-icon.png"): shutil.copy2(ROOT / "static" / name, out / name) pages = [] # paths for the sitemap def render(template, path, outlined=False, listed=True, **context): context.setdefault("draft", False) context.setdefault("card", None) page = env.get_template(template).render(path=path, **context) if context.get("entry"): page = renumber_citations(page) if outlined: page, items = outline(page) # Company pages always get the panel when they have two sections: it also # carries "Report an error". if len(items) >= (2 if context.get("entry") else OUTLINE_MIN): before, _, after = page.rpartition("
") report = f"/report/?entry={context['entry']['id']}" if context.get("entry") else None h1 = re.search(r"]*>(.*?)", page, re.S) page_title = html.unescape(re.sub(r"\s+", " ", re.sub(r"<[^>]+>", "", h1.group(1)))).strip() if h1 else "" page = (before + env.get_template("_outline.html").render( items=items, report=report, page_title=page_title or "On this page") + "" + after) target = out / path.lstrip("/") / "index.html" if path.endswith("/") else out / path.lstrip("/") write(target, page) if path.endswith("/") and listed: pages.append(path) # One page per entry: its guide's URL and template when it has one (site.yaml guides), # otherwise /companies// with the standard template. Mail opt-outs also get a # blank letter, and a calendar reminder when the deadline is a date. related = related_services(entries, site["guides"]) guide_for = {guide["entry"]: guide for guide in site["guides"]} for gid in guide_for: if gid not in entries: raise BuildError( f"{gid} is still a draft (or missing), so its guide can't be published. " f"Preview it with --drafts." ) guides = [(guide, entries[guide["entry"]]) for guide in site["guides"]] missing_cards = [] all_changes = [] # every company's change log, for the site-wide feed CARDS_LIST.parent.mkdir(exist_ok=True) CARDS_LIST.write_text(json.dumps( [company_card(e, site) for eid, e in entries.items() if eid not in guide_for], indent=1, ensure_ascii=False), encoding="utf-8") for eid, entry in entries.items(): guide = guide_for.get(eid) path = f"/{guide['slug']}/" if guide else f"/companies/{eid}/" if guide and guide.get("letter"): letter_text = guide["letter"] else: letter_text = {k: v.format(institution=entry["institution"]) if isinstance(v, str) else v for k, v in site["letter"].items()} event = reminder(site, path, entry, guide.get("mail_by") if guide else None) label = site["tiers"][entry["tier"]]["label"].lower() context = dict( entry=entry, guide=guide, cite=make_cite(entry), related=related[eid], how=how_to_reject(entry, site["tiers"]), letter_text=letter_text, letter_ok=letter_fits(entry, guide), letter_cfg=letter_config(entry), # What the company's own form asks for: the required items other than the form. form_details=[r for r in (entry.get("opt_out") or {}).get("required") or [] if "form" not in r.lower()], form_source=next((src for src in entry["sources"] if src["id"] == letter_config(entry).get("form")), None), mailto=opt_out_mailto(entry), draft=entry["status"] != "verified", event=event, google_calendar=google_calendar_url(event) if event else None, title=guide["title"] if guide else f"{short_name(entry)}: {label}", description=guide["description"].strip() if guide else entry_description(entry), card=None if guide else card_share(entry, site, missing_cards), watch=watch_links(site, entry, path), latest_change=(entry.get("changes") or [None])[0], ) render(guide["template"] if guide else "entry.html", path, outlined=True, **context) if event: write(out / path.strip("/") / "reminder.ics", reminder_ics(site, event, stamp)) items = change_items(site, entry, path) all_changes += [{**item, "title": f"{short_name(entry)}: {item['summary']}"} for item in items] write(out / path.strip("/") / "feed.xml", atom_feed(site, f"{short_name(entry)} · {site['name']}", context["watch"]["feed"], f"{site['url']}{path}", items)) all_changes.sort(key=lambda item: item["date"], reverse=True) write(out / "feed.xml", atom_feed(site, f"{site['name']}: changes to tracked agreements", f"{site['url']}/feed.xml", f"{site['url']}/", all_changes[:200])) if missing_cards: print(f"{len(missing_cards)} company page(s) use the default share card until the cards " f"are drawn: swift scripts/share_images.swift") any_draft = any(entry["status"] != "verified" for entry in entries.values()) rows = company_rows(entries, site["guides"], site["tiers"]) counts = {tier: sum(1 for r in rows if r["tier"] == tier) for tier in site["tiers"]} kind_counts = {kind: sum(1 for r in rows if r["kind"] == kind) for kind in site["kinds"]} kinds_present = [k for k in site["kinds"] if kind_counts[k]] # Written guides (content/guides/*.md). Their Markdown can use `entries`, `rows` and # `banks` (bank-account rows by tier), so lists inside them follow the data. A guide's # "Updated" date is the latest check among the kinds in its front matter (all if none). # Only these guides are listed under Guides: the site.yaml guides are company pages. md = markdown.Markdown(extensions=["smarty", "attr_list", "md_in_html"]) banks = {tier: [r for r in rows if r["kind"] == "deposit" and r["tier"] == tier] for tier in site["tiers"]} posts = [] for path in sorted((ROOT / "content" / "guides").glob("*.md")): front, body = read_markdown_page(path) body = env.from_string(body).render(entries=entries, rows=rows, banks=banks) kinds = front.get("kinds") or list(site["kinds"]) listed = [r["last_verified"] for r in rows if r["kind"] in kinds] updated = max(listed) if listed else None render("guide.html", f"/{path.stem}/", outlined=True, title=front["title"], description=front["description"].strip(), updated=updated, body=Markup(md.reset().convert(body)), draft=any_draft) posts.append({"title": front["title"], "url": f"/{path.stem}/", "description": front["description"].strip(), "updated": updated, "order": front.get("order", 100)}) # Guides have no publication date: their lists are rebuilt from the entries on every # run. They're listed by their front matter `order` (lowest first), then by title. posts.sort(key=lambda p: (p["order"], p["title"])) render("guides.html", "/guides/", posts=posts, title="Guides", description="Guides to forced arbitration: which companies use it, and how to reject it.") # The home page's "Terms change" box shows until the rejection deadline has passed. current = [(g, e) for g, e in guides if not deadline_passed(e.get("opt_out") or {})] render("home.html", "/", guides=current, posts=posts, rows=rows, counts=counts, kind_counts=kind_counts, kinds_present=kinds_present, news=news[:site["news"].get("count", 5)], draft=any_draft, title=f"{site['name']}: arbitration agreements, explained", description=site["description"].strip()) for path in sorted((ROOT / "content").glob("*.md")): front, body = read_markdown_page(path) body = env.from_string(body).render() render("page.html", f"/{path.stem}/", outlined=front.get("outline", False), title=front["title"], description=front["description"].strip(), body=Markup(md.reset().convert(body)), draft=any_draft) # "Report an error" (worker/index.js receives it) and where it sends people after. render("report.html", "/report/", rows=rows, title="Report an error", description="Report a wrong address, deadline, rating or quote on Arbitration Watch.", kinds=[("address", "Wrong address or contact"), ("deadline", "Wrong deadline"), ("rating", "Wrong rating"), ("quote", "Quote doesn't match the agreement"), ("outdated", "The agreement has changed"), ("other", "Something else")]) for slug, title, message in ( ("sent", "Report sent", "Thank you. It will be checked against the company's agreement " "at the next update, and the entry corrected if it's wrong."), ("error", "The report wasn't sent", "Something went wrong, or a field was missing. " f"Try again, or email {site['tips_email']}."), ("busy", "Too many reports at once", "Wait a minute, then try again."), ): render("report-status.html", f"/report/{slug}/", listed=False, title=title, description=title, message=message, back=None) # "Request a company", reached from an empty search on the home page. render("request.html", "/report/request/", title="Request a company", description="Ask for a company or product to be added to Arbitration Watch.") render("report-status.html", "/report/request/sent/", listed=False, title="Request sent", description="Request sent", back=("/report/request/", "Request another company"), message="Thank you. Requests are read at each update; there's no promise of " "whether or when a company is added.") render("404.html", "/404.html", title="Page not found", description="Page not found.", draft=False) # Open data published = [json_ready(e) for e in entries.values()] write(out / "data" / "entries.json", json.dumps({ "license": "CC BY 4.0, https://creativecommons.org/licenses/by/4.0/", "attribution": f"{site['name']}, {site['url']}", "generated": stamp.strftime("%Y-%m-%dT%H:%M:%SZ"), "entries": published, }, indent=2, ensure_ascii=False) + "\n") # Code and prompts, published as plain text (see content/code.md) published = { "research-brief.md.txt": data_dir / "prompts" / "research-brief.md", "validate.py.txt": data_dir / "scripts" / "validate.py", "verify_sources.py.txt": data_dir / "scripts" / "verify_sources.py", "check_dist.py.txt": ROOT / "scripts" / "check_dist.py", "build.py.txt": ROOT / "build.py", "report-worker.js.txt": ROOT / "worker" / "index.js", "pull_reports.py.txt": ROOT / "scripts" / "pull_reports.py", } (out / "code").mkdir(exist_ok=True) for name, source in published.items(): shutil.copy(source, out / "code" / name) # Search engines and headers write(out / "sitemap.xml", env.get_template("sitemap.xml").render(pages=pages)) write(out / "robots.txt", f"User-agent: *\nAllow: /\n\nSitemap: {site['url']}/sitemap.xml\n") shutil.copy(ROOT / "_headers", out / "_headers") shutil.copy(ROOT / "_redirects", out / "_redirects") print(f"Built {len(pages)} pages and {len(entries)} entr{'y' if len(entries) == 1 else 'ies'} " f"into {out}{' (drafts included)' if drafts else ''}.") def serve(out, port): handler = functools.partial(http.server.SimpleHTTPRequestHandler, directory=str(out)) handler.extensions_map = {**http.server.SimpleHTTPRequestHandler.extensions_map, ".ics": "text/calendar"} with http.server.ThreadingHTTPServer(("127.0.0.1", port), handler) as server: print(f"Serving {out} at http://localhost:{port}/ (Ctrl+C to stop)") try: server.serve_forever() except KeyboardInterrupt: pass def main(): parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) parser.add_argument("--data", type=pathlib.Path, default=pathlib.Path(os.environ.get("DATA_DIR", ROOT.parent / "data")), help="path to the data repo (default: ../data or $DATA_DIR)") parser.add_argument("--out", type=pathlib.Path, default=ROOT / "dist") parser.add_argument("--drafts", action="store_true", help="include draft entries, with a banner") parser.add_argument("--serve", action="store_true", help="serve dist/ after building") parser.add_argument("--port", type=int, default=8000) args = parser.parse_args() try: build(args.data.resolve(), args.out.resolve(), args.drafts) except BuildError as error: print(f"Build failed: {error}", file=sys.stderr) return 1 if args.serve: serve(args.out.resolve(), args.port) return 0 if __name__ == "__main__": sys.exit(main())