Sending {{ notify.events|join(', ') }} to {{ notify.services|join(', ') }} at {{ notify.priority }} priority.
+ {% if notify.last_error %}Last send failed: {{ notify.last_error }}
{% endif %} + + {% else %} +Off. Set NOTIFY_URLS to one or more Apprise URLs to be notified of new responses.
Great & useful!
") + response(app, n, "like", "Bob", "https://b.example/l") + response(app, n, "like", "Cy", "https://c.example/l") + response(app, n, "repost", "Dee", "https://d.example/rp") # not selected + response(app, n, "mention", "Eve", "https://e.example/m", moderation="pending") + count, _ = sweep(app) + assert count == 4 + titles = [m["title"] for m in sent] + assert "↩ Reply from Ana via Bluesky" in titles + assert "💬 Mention from Eve (awaiting moderation)" in titles + assert "♥ 2 new likes on “Starpunk now supports backfeeds”" in titles + reply = next(m for m in sent if m["title"].startswith("↩")) + assert reply["body"].startswith("Great & useful!") + assert f"({SITE}/note/{n.slug}#responses)" in reply["body"] + mention = next(m for m in sent if m["title"].startswith("💬")) + assert f"{SITE}/admin/webmentions/" in mention["body"], "pending ones link to moderation" + assert all(t.endswith("priority=high") or t.endswith("priority=max") for t in sent[0]["targets"]) + assert unsent(app) == [] + sent.clear() + assert sweep(app)[0] == 0 and sent == [], "nothing is sent twice" + + +def test_failed_send_is_retried_with_backoff(app, monkeypatch): + calls = [] + monkeypatch.setattr(notifications, "_deliver", lambda t, ti, b: (calls.append(ti), (False, "boom"))[1]) + n = note(app) + response(app, n, "reply", "Ana", "https://a.example/r") + count, sweeper = sweep(app) + assert count == 0 and unsent(app) == ["https://a.example/r"] + assert sweep(app, sweeper)[0] == 0 and len(calls) == 1, "waits before retrying" + with app.app_context(): + assert "boom" in notifications.last_error(get_db(app)) + sweeper._next_try = 0 + monkeypatch.setattr(notifications, "_deliver", lambda t, ti, b: (True, "")) + assert sweep(app, sweeper)[0] == 1 + with app.app_context(): + assert notifications.last_error(get_db(app)) == "" + + +def test_old_unsent_responses_are_dropped(app, sent): + n = note(app) + response(app, n, "reply", "Ana", "https://a.example/r", hours_ago=30) + assert sweep(app)[0] == 0 and sent == [] and unsent(app) == [] + + +def test_off_without_urls(app, sent): + app.config["NOTIFY_URLS"] = "" + n = note(app) + response(app, n, "reply", "Ana", "https://a.example/r") + assert sweep(app)[0] == 0 and unsent(app) == ["https://a.example/r"] + + +def test_backfill_and_late_first_checks_are_quiet(app, sent): + class Client: + config_token = "t" + def responses(self, remote_id, remote_url, cap=1000): + return Harvest([Response(kind="reply", source_url=f"{remote_url}/reply", remote_id="r", + author_name="Ana", content_html="hi
")]) + def maintain(self): + pass + + app.config.update(GOTOSOCIAL_URL="https://social.example", GOTOSOCIAL_ACCESS_TOKEN="t", + BACKFEED_ENABLED=True) + syndication._client_cache["https://social.example"] = Client() + fresh, old = note(app, "New"), note(app, "Old", age_days=10) + with app.app_context(): + for n, url in ((fresh, "https://social.example/1"), (old, "https://social.example/2")): + get_db(app).execute("INSERT INTO syndications (note_id, target, enabled, remote_id, remote_url, " + "state) VALUES (?, 'gotosocial', 1, 'x', ?, 'synced')", (n.id, url)) + get_db(app).commit() + backfeed.process_due() + assert unsent(app) == ["https://social.example/1/reply"], "only the new note's reply is news" + + +# --- Problems and admin ---------------------------------------------------------------------------- + +def test_problems(app, sent): + with app.app_context(): + notifications.problem(app.config, app.config["DATABASE_PATH"], "Crosspost to Bluesky failed", + "HTTP 400", f"{SITE}/admin/edit/1") + assert sent[0]["title"] == "⚠ Crosspost to Bluesky failed" + assert "HTTP 400" in sent[0]["body"] and "/admin/edit/1" in sent[0]["body"] + app.config["NOTIFY_EVENTS"] = "reply" + with app.app_context(): + notifications.problem(app.config, app.config["DATABASE_PATH"], "x", "y", "z") + assert len(sent) == 1, "not selected: not sent" + + +def test_final_crosspost_failure_notifies(app, sent): + n = note(app) + app.config.update(GOTOSOCIAL_URL="https://social.example", GOTOSOCIAL_ACCESS_TOKEN="t") + with app.app_context(): + cur = get_db(app).execute("INSERT INTO syndications (note_id, target, enabled, state, attempts) " + "VALUES (?, 'gotosocial', 1, 'pending', 0)", (n.id,)) + get_db(app).commit() + row = get_db(app).execute("SELECT * FROM syndications WHERE id = ?", (cur.lastrowid,)).fetchone() + syndication._fail(get_db(app), row, syndication.SyndicationError("temporary", permanent=False)) + assert sent == [], "a retry is coming: no message" + syndication._fail(get_db(app), row, syndication.SyndicationError("HTTP 422 bad", permanent=True)) + assert sent and sent[0]["title"] == "⚠ Crosspost to GoToSocial failed" + + +def test_admin_status_and_test_button(app, sent): + from starpunk.auth import create_session + + with app.test_request_context(): + token = create_session("https://example.com") + browser = app.test_client() + browser.set_cookie("starpunk_session", token) + page = browser.get("/admin/webmentions").get_data(as_text=True) + assert "Sending like, mention, problems, reply to gotifys, ntfys at high priority" in page + page = browser.post("/admin/notifications/test", follow_redirects=True).get_data(as_text=True) + assert "Test notification sent" in page and sent[-1]["title"] == "StarPunk test notification" + + +# --- Real Apprise ------------------------------------------------------------------------------------- + +def test_apprise_delivers_markdown_to_a_service(app): + received = [] + + class Handler(BaseHTTPRequestHandler): + def do_POST(self): + received.append(json.loads(self.rfile.read(int(self.headers["Content-Length"])))) + self.send_response(200) + self.end_headers() + + def log_message(self, *args): + pass + + server = HTTPServer(("127.0.0.1", 0), Handler) + threading.Thread(target=server.handle_request, daemon=True).start() + app.config["NOTIFY_URLS"] = f"json://127.0.0.1:{server.server_port}/" + ok, error = notifications.send(app.config, "Title", "Body with [a link](https://x.example)") + server.server_close() + assert ok, error + assert received[0]["title"] == "Title" and "a link" in received[0]["message"] + app.config["NOTIFY_URLS"] = "notaservice://nope" + ok, error = notifications.send(app.config, "t", "b") + assert not ok and "Not a usable Apprise URL" in error + + +def test_migration_021_marks_history(tmp_path): + from pathlib import Path + + conn = sqlite3.connect(tmp_path / "db") + conn.execute("CREATE TABLE webmentions (id INTEGER PRIMARY KEY, source_url TEXT)") + conn.execute("INSERT INTO webmentions (source_url) VALUES ('https://old.example')") + conn.executescript((Path(__file__).parent.parent / "migrations" / "021_notifications.sql").read_text()) + assert conn.execute("SELECT notified_at IS NOT NULL FROM webmentions").fetchone()[0] == 1