Compare commits
18
Commits
dde36cdcd2
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c7ef863530 | ||
|
|
a4a0b0bd0d | ||
|
|
8bf2e6d828 | ||
|
|
71054d2778 | ||
|
|
7c497d2a0a | ||
|
|
b18aae89d9 | ||
|
|
3a0a4e15a8 | ||
|
|
b3fec4af2a | ||
|
|
a57c91860b | ||
|
|
c8b7b2b049 | ||
|
|
c2ffb8907d | ||
|
|
16eca51e4c | ||
|
|
3c28ec16dd | ||
|
|
3e1659224b | ||
|
|
a73afea6b9 | ||
|
|
2d2ebf64a5 | ||
|
|
c793d4fb29 | ||
|
|
5268156e48 |
No files matched your search
@@ -85,10 +85,10 @@ jobs:
|
|||||||
mv ruff /usr/local/bin/ruff
|
mv ruff /usr/local/bin/ruff
|
||||||
|
|
||||||
- name: Check syntax errors
|
- name: Check syntax errors
|
||||||
run: ruff check matrixbot/ --select E9,F63,F7,F82 --output-format=github
|
run: ruff check matrixbot/ now-playing/ --select E9,F63,F7,F82 --output-format=github
|
||||||
|
|
||||||
- name: Run full lint
|
- name: Run full lint
|
||||||
run: ruff check matrixbot/ --output-format=github
|
run: ruff check matrixbot/ now-playing/ --output-format=github
|
||||||
|
|
||||||
python-audit:
|
python-audit:
|
||||||
name: Python deps (pip-audit)
|
name: Python deps (pip-audit)
|
||||||
|
|||||||
@@ -29,6 +29,10 @@ matrix/
|
|||||||
├── discord-bridge/
|
├── discord-bridge/
|
||||||
│ ├── config.yaml # mautrix-discord config (DB password filled in on the server, never committed)
|
│ ├── config.yaml # mautrix-discord config (DB password filled in on the server, never committed)
|
||||||
│ └── install.sh # One-time installer, run on the Proxmox node hosting LXC 109 + 151
|
│ └── install.sh # One-time installer, run on the Proxmox node hosting LXC 109 + 151
|
||||||
|
├── now-playing/ # "Listening to" service for Lotus Chat (cinny #491), LXC 151 :8072
|
||||||
|
│ ├── lotus_now_playing.py
|
||||||
|
│ ├── test_lotus_now_playing.py
|
||||||
|
│ └── install.sh
|
||||||
├── deploy/ # Auto-deployment infrastructure
|
├── deploy/ # Auto-deployment infrastructure
|
||||||
│ ├── lxc151-hookshot.sh # Deploy script for LXC 151 (matrix/hookshot/livekit)
|
│ ├── lxc151-hookshot.sh # Deploy script for LXC 151 (matrix/hookshot/livekit)
|
||||||
│ ├── lxc106-cinny.sh # Deploy script for LXC 106 (cinny)
|
│ ├── lxc106-cinny.sh # Deploy script for LXC 106 (cinny)
|
||||||
@@ -45,6 +49,7 @@ matrix/
|
|||||||
├── livekit-graceful-restart.timer # Runs every 5 min
|
├── livekit-graceful-restart.timer # Runs every 5 min
|
||||||
├── draupnir.service
|
├── draupnir.service
|
||||||
├── mautrix-discord.service # Discord bridge (LXC 151)
|
├── mautrix-discord.service # Discord bridge (LXC 151)
|
||||||
|
├── lotus-now-playing.service # "Listening to" service (LXC 151)
|
||||||
└── cinny-upstream-check.cron # Installed to /etc/cron.d/ on LXC 106 — runs daily at noon
|
└── cinny-upstream-check.cron # Installed to /etc/cron.d/ on LXC 106 — runs daily at noon
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -63,7 +68,7 @@ matrix/
|
|||||||
| NPM | 10.10.10.27 | 139 | — | — | Nginx Proxy Manager + matrix landing page |
|
| NPM | 10.10.10.27 | 139 | — | — | Nginx Proxy Manager + matrix landing page |
|
||||||
| Authelia | 10.10.10.36 | 167 | — | — | SSO/OIDC provider |
|
| Authelia | 10.10.10.36 | 167 | — | — | SSO/OIDC provider |
|
||||||
| LLDAP | 10.10.10.39 | 147 | — | — | LDAP user directory |
|
| LLDAP | 10.10.10.39 | 147 | — | — | LDAP user directory |
|
||||||
| Uptime Kuma | 10.10.10.25 | 101 | — | — | Uptime monitoring (micro1 node) |
|
| Uptime Kuma | 10.10.10.25 | 101 | — | — | Uptime monitoring |
|
||||||
|
|
||||||
**Key paths on Synapse LXC (151):**
|
**Key paths on Synapse LXC (151):**
|
||||||
- Synapse config: `/etc/matrix-synapse/homeserver.yaml`
|
- Synapse config: `/etc/matrix-synapse/homeserver.yaml`
|
||||||
@@ -304,6 +309,7 @@ The token in `draupnir/production.yaml` in this repo is **intentionally redacted
|
|||||||
| 7881 | LiveKit RTC TCP | 0.0.0.0 |
|
| 7881 | LiveKit RTC TCP | 0.0.0.0 |
|
||||||
| 8070 | voice-limit-guard (fronts lk-jwt-service) | 0.0.0.0 |
|
| 8070 | voice-limit-guard (fronts lk-jwt-service) | 0.0.0.0 |
|
||||||
| 8071 | lk-jwt-service (behind guard) | 127.0.0.1 (matrix #24; was 0.0.0.0) |
|
| 8071 | lk-jwt-service (behind guard) | 127.0.0.1 (matrix #24; was 0.0.0.0) |
|
||||||
|
| 8072 | lotus-now-playing ("Listening to", cinny #491) | 0.0.0.0 |
|
||||||
| 8080 | synapse-admin (nginx) | 0.0.0.0 |
|
| 8080 | synapse-admin (nginx) | 0.0.0.0 |
|
||||||
| 3478 | coturn STUN/TURN | 0.0.0.0 |
|
| 3478 | coturn STUN/TURN | 0.0.0.0 |
|
||||||
| 5349 | coturn TURNS/TLS | 0.0.0.0 |
|
| 5349 | coturn TURNS/TLS | 0.0.0.0 |
|
||||||
@@ -368,7 +374,6 @@ Webhook URL format: `https://matrix.lotusguild.org/webhook/<uuid>`
|
|||||||
| Sonarr | `c3dde7ba…` | All event types |
|
| Sonarr | `c3dde7ba…` | All event types |
|
||||||
| Radarr | `a7584167…` | All event types |
|
| Radarr | `a7584167…` | All event types |
|
||||||
| Readarr | `3b30c0df…` | All event types |
|
| Readarr | `3b30c0df…` | All event types |
|
||||||
| Lidarr | `aee60962…` | All event types |
|
|
||||||
| Uptime Kuma | `4b3fb94b…` | Status change notifications |
|
| Uptime Kuma | `4b3fb94b…` | Status change notifications |
|
||||||
| Seerr | `9c56d489…` | Request/approval events |
|
| Seerr | `9c56d489…` | Request/approval events |
|
||||||
| Owncast (Livestream) | `ff37824a…` | STREAM_STARTED / STREAM_STOPPED |
|
| Owncast (Livestream) | `ff37824a…` | STREAM_STARTED / STREAM_STOPPED |
|
||||||
@@ -382,7 +387,7 @@ Webhook URL format: `https://matrix.lotusguild.org/webhook/<uuid>`
|
|||||||
- JS transformation functions use hookshot v2 API: `result = { version: "v2", plain, html, msgtype }`
|
- JS transformation functions use hookshot v2 API: `result = { version: "v2", plain, html, msgtype }`
|
||||||
- The `result` variable must be assigned without `var`/`let`/`const` (QuickJS IIFE sandbox)
|
- The `result` variable must be assigned without `var`/`let`/`const` (QuickJS IIFE sandbox)
|
||||||
- NPM proxies `https://matrix.lotusguild.org/webhook/*` → `http://10.10.10.29:9003`
|
- NPM proxies `https://matrix.lotusguild.org/webhook/*` → `http://10.10.10.29:9003`
|
||||||
- NPM proxies `/sfu/get` and `/get_token` → `http://10.10.10.29:8070` (lk-jwt-service). Both paths are in `/data/nginx/proxy_host/49.conf` on LXC 139 — **NPM will overwrite these if proxy host 49 is re-saved via the UI; re-add both location blocks after any NPM save**
|
- NPM proxies `/sfu/get`, `/get_token` and `/delegate_delayed_leave` → `http://10.10.10.29:8070` (voice-limit-guard → lk-jwt-service), and `/now-playing/` → `:8072`. Since 2026-11-12 all of proxy host 49's custom locations live in its **Advanced** config (NPM sqlite `proxy_host.advanced_config`), so a UI save keeps them. Change them there (or in both the DB and `/data/nginx/proxy_host/49.conf`), never only in the conf file.
|
||||||
- Proxmox sends Discord embed format: `data.embeds[0].{title,description,fields}` — NOT flat fields
|
- Proxmox sends Discord embed format: `data.embeds[0].{title,description,fields}` — NOT flat fields
|
||||||
- Transform functions are stored as Matrix room state (`uk.half-shot.matrix-hookshot.generic.hook`) and deployed via `hookshot/deploy.sh`
|
- Transform functions are stored as Matrix room state (`uk.half-shot.matrix-hookshot.generic.hook`) and deployed via `hookshot/deploy.sh`
|
||||||
- Hook UUIDs are **not** in that state. Hookshot creates them and keeps a `{uuid: name}` map in the `@hookshot` bot's room account data (same event type). Deploying a new transform creates the hook. To look a UUID up on LXC 151, use the appservice token from `/etc/matrix-synapse/hookshot-registration.yaml`: `GET /_matrix/client/v3/user/@hookshot:matrix.lotusguild.org/rooms/<room>/account_data/uk.half-shot.matrix-hookshot.generic.hook?user_id=@hookshot:matrix.lotusguild.org`
|
- Hook UUIDs are **not** in that state. Hookshot creates them and keeps a `{uuid: name}` map in the `@hookshot` bot's room account data (same event type). Deploying a new transform creates the hook. To look a UUID up on LXC 151, use the appservice token from `/etc/matrix-synapse/hookshot-registration.yaml`: `GET /_matrix/client/v3/user/@hookshot:matrix.lotusguild.org/rooms/<room>/account_data/uk.half-shot.matrix-hookshot.generic.hook?user_id=@hookshot:matrix.lotusguild.org`
|
||||||
@@ -413,6 +418,22 @@ channel webhook with their own display name.
|
|||||||
- Database: `mautrix_discord` on LXC 109, role `mautrix_discord`, allowed from 10.10.10.29 in `pg_hba.conf`
|
- Database: `mautrix_discord` on LXC 109, role `mautrix_discord`, allowed from 10.10.10.29 in `pg_hba.conf`
|
||||||
- Service: `systemctl status mautrix-discord`, logs in `journalctl -u mautrix-discord` and `/var/log/mautrix-discord/`
|
- Service: `systemctl status mautrix-discord`, logs in `journalctl -u mautrix-discord` and `/var/log/mautrix-discord/`
|
||||||
- End-to-bridge encryption is allowed, so it can join encrypted rooms
|
- End-to-bridge encryption is allowed, so it can join encrypted rooms
|
||||||
|
- **Patched build.** The deployed binary is upstream v0.7.7 plus `discord-bridge/patches/`, built with
|
||||||
|
`discord-bridge/build-patched.sh` (deploy steps are in the script's header). `install.sh` still
|
||||||
|
downloads the stock release, so rebuild and redeploy the patched binary after any (re)install or upgrade.
|
||||||
|
- `0001`: when a Matrix → Discord send fails before the request reaches Discord (DNS, connect, or
|
||||||
|
`TLS handshake timeout`), the bridge retries after 2, 5, 10, 20, 30, 60, 60 and 60 s instead of
|
||||||
|
dropping the message with "⚠ Your message may not have been bridged". The room's later messages wait
|
||||||
|
in order behind the retry. Edits, reactions and deletes are not retried.
|
||||||
|
- `0002`: when a relay (webhook) send fails after the request may already have reached Discord
|
||||||
|
(connection reset, EOF, timeout waiting for the reply, Discord 5xx), the bridge waits up to 6 s for
|
||||||
|
its own post to come back over the Discord gateway. If it does, the send counts as delivered (no
|
||||||
|
resend, no copy back into Matrix); if not, it retries with the 0001 backoff, checking again before
|
||||||
|
each resend. A webhook post has no dedupe, so this echo check is what keeps those retries from
|
||||||
|
double-posting.
|
||||||
|
- `0003`: the name and avatar on relayed messages come from the bridge's database copy of room
|
||||||
|
membership. If that read fails (e.g. the database is unreachable) or misses, the bridge now asks
|
||||||
|
Synapse instead of posting under the raw Matrix ID with no avatar (happened 2026-11-23).
|
||||||
|
|
||||||
**Install (one time):** after this repo's `main` has reached `/opt/matrix-config` on LXC 151, run this
|
**Install (one time):** after this repo's `main` has reached `/opt/matrix-config` on LXC 151, run this
|
||||||
on the Proxmox node hosting LXC 109 and 151. It restarts Synapse once and is safe to re-run.
|
on the Proxmox node hosting LXC 109 and 151. It restarts Synapse once and is safe to re-run.
|
||||||
@@ -462,6 +483,18 @@ while the bridge or Synapse was down are bridged when it starts again.
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
## Now Playing ("Listening to", cinny #491)
|
||||||
|
|
||||||
|
`now-playing/lotus_now_playing.py` (`lotus-now-playing.service`, LXC 151, `:8072`, NPM `/now-playing/`) gives Lotus Chat what people are playing, for a Discord/Spotify-style "Listening to" card.
|
||||||
|
|
||||||
|
- **Source:** Navidrome `getNowPlaying`, polled every 10 s as the non-admin Navidrome user `lotus-nowplaying` (direct to `http://10.10.10.28:4533`). Navidrome is the scrobbling master and Dropped Needle passes the real listener through, so every play shows up under the listener's own Navidrome username, which is their SSO username. Dropped Needle's own `droppedneedle` service user is ignored.
|
||||||
|
- **Who's asking:** Lotus Chat sends a Matrix OpenID token; the service checks it with Synapse (`/_matrix/federation/v1/openid/userinfo`). Only users of this homeserver can read anything.
|
||||||
|
- **Matrix user → SSO username:** `/etc/lotus-now-playing/users.json` first (server-only, not in this public repo; for accounts whose SSO link has no email), then the Synapse admin API: an email `<name>@lotusguild.org`, or the legacy plain-username external ID. Uses `MATRIX_TOKEN` from `/etc/matrix-deploy.env`.
|
||||||
|
- **Opt-in:** off by default; each person turns on "Share what I'm listening to" in Lotus Chat. Stored in `/var/lib/lotus-now-playing/state.json`.
|
||||||
|
- **API:** `GET`/`PUT /now-playing/v1/me` (`{share, linked, playing}`), `GET /now-playing/v1/users?ids=@a,@b` (up to 50; only opted-in, matched, playing users), and `GET /now-playing/v1/cover/<id>?size=`. The cover endpoint has no auth (for `<img>`) but only serves covers an opted-in user is playing right now.
|
||||||
|
- Titles, artists and tokens are never logged.
|
||||||
|
- **Install / update:** create `/etc/lotus-now-playing/env` (`NAVIDROME_USER`, `NAVIDROME_PASSWORD`) once, then `bash /opt/matrix-config/now-playing/install.sh`. Tests: `python3 -m unittest now-playing/test_lotus_now_playing.py`.
|
||||||
|
|
||||||
## Voice Bridge (nether-voicebridge, Lotus-patched)
|
## Voice Bridge (nether-voicebridge, Lotus-patched)
|
||||||
|
|
||||||
Bridges Discord voice into a Lotus voice room. People on Discord appear **inside the Matrix call**
|
Bridges Discord voice into a Lotus voice room. People on Discord appear **inside the Matrix call**
|
||||||
@@ -513,6 +546,7 @@ Every bot account has a proper name and an avatar in one style (white glyph on a
|
|||||||
| `@draupnir` | Draupnir | Profile API with Draupnir's token (Draupnir doesn't manage its own profile) |
|
| `@draupnir` | Draupnir | Profile API with Draupnir's token (Draupnir doesn't manage its own profile) |
|
||||||
| `@lotusbot` | Lotus Bot | Already set |
|
| `@lotusbot` | Lotus Bot | Already set |
|
||||||
| `@notices` | Server Notices | `server_notices.system_mxid_avatar_url` in `homeserver.yaml` (Lotus logo); needs a Synapse restart |
|
| `@notices` | Server Notices | `server_notices.system_mxid_avatar_url` in `homeserver.yaml` (Lotus logo); needs a Synapse restart |
|
||||||
|
| `@lotus-mc-bridge` | Lotus Minecraft | Profile API with its own token, from the Minecraft mod's config (voxel block with a lotus, not the white-glyph style; image not in `avatars/`). Its status is the player count: `minecraft-bridge/lotus_mc_status.py`, which runs on CT 154 as `lotus-mc-status.service` (not on LXC 151; installed by hand) |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -656,6 +690,27 @@ Infra notes for THIS repo:
|
|||||||
**Full handoff & step-by-step plan:** `LotusGuild/cinny` →
|
**Full handoff & step-by-step plan:** `LotusGuild/cinny` →
|
||||||
[`HANDOFF_ELEMENT_CALL_FORK.md`](https://code.lotusguild.org/LotusGuild/cinny/src/branch/lotus/HANDOFF_ELEMENT_CALL_FORK.md).
|
[`HANDOFF_ELEMENT_CALL_FORK.md`](https://code.lotusguild.org/LotusGuild/cinny/src/branch/lotus/HANDOFF_ELEMENT_CALL_FORK.md).
|
||||||
|
|
||||||
|
### Not planned: background web push
|
||||||
|
|
||||||
|
**Decision (2026-11-09):** the web app does **not** get background push
|
||||||
|
notifications (notifications while no Lotus tab is open), and no push gateway
|
||||||
|
(Sygnal) is run on our infrastructure.
|
||||||
|
|
||||||
|
- **Why:** people who want notifications keep the **desktop app** open (it
|
||||||
|
notifies natively and keeps running in the tray), and on phones people use
|
||||||
|
**Element X** or **FluffyChat**, which already push through their own
|
||||||
|
gateways. A gateway would only help someone using the website with every tab
|
||||||
|
closed, which doesn't justify another service to run, monitor and secure on
|
||||||
|
LXC 151.
|
||||||
|
- **What users get:** OS notifications while the web or desktop app is open,
|
||||||
|
in-app toasts, quiet hours and pause, email notifications (optional, Synapse).
|
||||||
|
- **If this changes:** the plan (Sygnal on LXC 151, VAPID key, NPM route locked
|
||||||
|
to Synapse, config.json `webPush` entry) is in
|
||||||
|
[cinny #202](https://code.lotusguild.org/LotusGuild/cinny/issues/202#issuecomment-6221),
|
||||||
|
and the finished-but-unmerged client side (service-worker `push` handler,
|
||||||
|
pusher registration, setting, tests) is in closed
|
||||||
|
[cinny PR #489](https://code.lotusguild.org/LotusGuild/cinny/pulls/489).
|
||||||
|
|
||||||
### Custom Features
|
### Custom Features
|
||||||
|
|
||||||
All custom code lives in `src/app/` on the `lotus` branch of `code.lotusguild.org/LotusGuild/cinny`. Changes survive upstream merges as long as they don't conflict with the same files upstream touched.
|
All custom code lives in `src/app/` on the `lotus` branch of `code.lotusguild.org/LotusGuild/cinny`. Changes survive upstream merges as long as they don't conflict with the same files upstream touched.
|
||||||
@@ -752,7 +807,7 @@ Periodic `TLS/TCP socket error: Connection reset by peer` in coturn logs. Normal
|
|||||||
|
|
||||||
`net.ipv4.tcp_congestion_control = bbr` must be set on the Proxmox **host**, not inside an unprivileged LXC. All other sysctl tuning (TCP/UDP buffers, fin_timeout) is applied inside LXC 151.
|
`net.ipv4.tcp_congestion_control = bbr` must be set on the Proxmox **host**, not inside an unprivileged LXC. All other sysctl tuning (TCP/UDP buffers, fin_timeout) is applied inside LXC 151.
|
||||||
|
|
||||||
Applied 2026-07-26 via `/etc/sysctl.d/99-bbr.conf` on `compute-storage-01` and `large1`, and
|
Applied 2026-07-26 via `/etc/sysctl.d/99-bbr.conf` on `compute-storage-01` and `large1` (now `compute-storage-02`), and
|
||||||
**2026-08-16 on `compute-storage-gpu-01`** (which was found on `cubic`/`fq_codel` with `tcp_bbr` not
|
**2026-08-16 on `compute-storage-gpu-01`** (which was found on `cubic`/`fq_codel` with `tcp_bbr` not
|
||||||
even loaded). All three nodes that may host LXC 151 now report `bbr`/`fq`. Because the file lives on
|
even loaded). All three nodes that may host LXC 151 now report `bbr`/`fq`. Because the file lives on
|
||||||
the host, **a node that has never hosted 151 will not have it** — check before allowing 151 to migrate
|
the host, **a node that has never hosted 151 will not have it** — check before allowing 151 to migrate
|
||||||
@@ -762,9 +817,9 @@ somewhere new:
|
|||||||
sysctl net.ipv4.tcp_congestion_control net.core.default_qdisc # want: bbr / fq
|
sysctl net.ipv4.tcp_congestion_control net.core.default_qdisc # want: bbr / fq
|
||||||
```
|
```
|
||||||
|
|
||||||
### ⚠️ `large1` has a failing DIMM — keep Synapse and PostgreSQL off it
|
### ⚠️ `compute-storage-02` has a failing DIMM — keep Synapse and PostgreSQL off it
|
||||||
|
|
||||||
`large1` logs **corrected ECC errors** concentrated on one module (**P0 CHANNEL B, DIMM 1** —
|
`compute-storage-02` (called `large1` until the 2026-11-18 rename) logs **corrected ECC errors** concentrated on one module (**P0 CHANNEL B, DIMM 1** —
|
||||||
EDAC `mc#0csrow#2channel#1`, 421 corrected errors observed, with the MCE `Over`/overflow flag set
|
EDAC `mc#0csrow#2channel#1`, 421 corrected errors observed, with the MCE `Over`/overflow flag set
|
||||||
meaning more occurred than were logged). It has hard-crashed **on its own** twice — 2026-07-24 14:19
|
meaning more occurred than were logged). It has hard-crashed **on its own** twice — 2026-07-24 14:19
|
||||||
and 2026-07-26 00:20 — with no clean-shutdown markers and no OOM events, which is the classic
|
and 2026-07-26 00:20 — with no clean-shutdown markers and no OOM events, which is the classic
|
||||||
@@ -775,17 +830,18 @@ signature of an uncorrectable ECC error.
|
|||||||
|
|
||||||
Consequences for Matrix:
|
Consequences for Matrix:
|
||||||
|
|
||||||
- On the 2026-07-26 crash, HA relocated **LXC 109 (PostgreSQL)** and **LXC 151 (Synapse)** to
|
- LXC 109 (PostgreSQL) and LXC 151 (Synapse) are HA guests and move between nodes; keep them
|
||||||
`compute-storage-01`, which has **zero ECC errors across all boots**. They should stay there.
|
off compute-storage-02 through the HA rule weights, not by pinning.
|
||||||
- The HA rule `ha-rule-43cb668b-becf` in `/etc/pve/ha/rules.cfg` currently weights
|
- The HA rule `ha-rule-43cb668b-becf` in `/etc/pve/ha/rules.cfg` (checked 2026-11-18) weights
|
||||||
`compute-storage-01:1,large1:1` — **equal priority, non-strict** — so a future failover can put
|
`compute-storage-01:1,compute-storage-02:2,storage-01:2`, so the bad-RAM node is one of the two
|
||||||
Synapse straight back onto the bad-RAM node. Re-weighting to `compute-storage-01:2,large1:1` would
|
**preferred** nodes, and a failover can put Synapse or PostgreSQL onto it. Lowering
|
||||||
prefer the healthy node while keeping large1 as a fallback. Not changed automatically because that
|
`compute-storage-02` below `storage-01` would keep it as a fallback only. Not changed automatically,
|
||||||
rule governs 10 resources and `compute-storage-01` has only 46GB RAM vs large1's 128GB.
|
because that rule governs 9 CTs and a VM. Look up where 151 and 109 run now with
|
||||||
|
`ha-manager status | grep -E 'ct:(151|109) '`; they move.
|
||||||
- **Never run a large `VACUUM FULL` or state-compression job on a host with failing RAM** — those
|
- **Never run a large `VACUUM FULL` or state-compression job on a host with failing RAM** — those
|
||||||
rewrite the whole table through memory, and a bit-flip becomes silent, backup-propagated corruption.
|
rewrite the whole table through memory, and a bit-flip becomes silent, backup-propagated corruption.
|
||||||
- Ceph's **`noout` flag is intentionally left set.** With 10 OSDs on an intermittently-crashing node,
|
- Ceph's **`noout` flag is intentionally left set.** With 10 OSDs on an intermittently-crashing node,
|
||||||
`noout` prevents a full 10-OSD rebalance every time it bounces. Do not clear it until large1 is stable.
|
`noout` prevents a full 10-OSD rebalance every time it bounces. Do not clear it until compute-storage-02 is stable.
|
||||||
|
|
||||||
A replacement DIMM is not currently in budget. Free mitigations worth evaluating: physically removing
|
A replacement DIMM is not currently in budget. Free mitigations worth evaluating: physically removing
|
||||||
the bad module (96GB in flex mode, or 64GB symmetric dual-channel), kernel page soft-offlining via
|
the bad module (96GB in flex mode, or 64GB symmetric dual-channel), kernel page soft-offlining via
|
||||||
@@ -965,7 +1021,7 @@ than nightly compression can keep up with.
|
|||||||
- [x] TCP retransmit timeout lowered (`tcp_retries2=5`, `tcp_syn_retries=4`, `tcp_keepalive_probes=3`) — stalled outbound federation connections now fail in ~15-30s instead of ~15 min
|
- [x] TCP retransmit timeout lowered (`tcp_retries2=5`, `tcp_syn_retries=4`, `tcp_keepalive_probes=3`) — stalled outbound federation connections now fail in ~15-30s instead of ~15 min
|
||||||
- [x] Unreachable routes added for servers with asymmetric connectivity (can reach us but we can't reach their federation port) — prevents 90s TCP hangs from being added to lag; defined in `/etc/network/interfaces` post-up hooks and survive reboots (bark.lgbt ×2, parodia.dev, chat.ohaa.xyz, matrix.k8ekat.dev)
|
- [x] Unreachable routes added for servers with asymmetric connectivity (can reach us but we can't reach their federation port) — prevents 90s TCP hangs from being added to lag; defined in `/etc/network/interfaces` post-up hooks and survive reboots (bark.lgbt ×2, parodia.dev, chat.ohaa.xyz, matrix.k8ekat.dev)
|
||||||
- [x] Stuck `device_lists_remote_resync` entries cleared for dead-server users (@dalite:bark.lgbt, @arndot:matrix.goch.social) — device list resync was firing every 30s
|
- [x] Stuck `device_lists_remote_resync` entries cleared for dead-server users (@dalite:bark.lgbt, @arndot:matrix.goch.social) — device list resync was firing every 30s
|
||||||
- [x] BBR congestion control — applied 2026-07-26 on `compute-storage-01` and `large1`, and 2026-08-16 on `compute-storage-gpu-01`, via `/etc/sysctl.d/99-bbr.conf` (`net.ipv4.tcp_congestion_control=bbr`, `net.core.default_qdisc=fq`). Persists across reboots. All three nodes that may host LXC 151 are now covered. If 151 is ever allowed to run on another node, apply it there too.
|
- [x] BBR congestion control — applied 2026-07-26 on `compute-storage-01` and `large1` (now `compute-storage-02`), and 2026-08-16 on `compute-storage-gpu-01`, via `/etc/sysctl.d/99-bbr.conf` (`net.ipv4.tcp_congestion_control=bbr`, `net.core.default_qdisc=fq`). Persists across reboots. All three nodes that may host LXC 151 are now covered. If 151 is ever allowed to run on another node, apply it there too.
|
||||||
- [x] LXC 109 rootfs grown 30GB → 80GB (2026-07-26). It was at **89% full with only 3.4GB free**, and `pg_wal` shares that volume — PostgreSQL stops outright at 100%. Also a hard prerequisite for any `VACUUM FULL`, which must rewrite the table alongside the original.
|
- [x] LXC 109 rootfs grown 30GB → 80GB (2026-07-26). It was at **89% full with only 3.4GB free**, and `pg_wal` shares that volume — PostgreSQL stops outright at 100%. Also a hard prerequisite for any `VACUUM FULL`, which must rewrite the table alongside the original.
|
||||||
- [x] **Purged the `#community:matrix.org` space** (`!iMZEhwCvbfeAYUxAjZ:t2l.io`) 2026-07-26 — 81,724,747 rows / 17GB for a directory wrapper with **zero messages** and one local member. Admin API `DELETE /_synapse/admin/v2/rooms/` with `purge:true`, then `VACUUM FULL`. ~2.5 min downtime.
|
- [x] **Purged the `#community:matrix.org` space** (`!iMZEhwCvbfeAYUxAjZ:t2l.io`) 2026-07-26 — 81,724,747 rows / 17GB for a directory wrapper with **zero messages** and one local member. Admin API `DELETE /_synapse/admin/v2/rooms/` with `purge:true`, then `VACUUM FULL`. ~2.5 min downtime.
|
||||||
- [x] **Compressed room state** with `rust-synapse-compress-state` (built at `/opt/rust-synapse-compress-state/` on LXC 109). Every run verified `New state map matches old one` before commit:
|
- [x] **Compressed room state** with `rust-synapse-compress-state` (built at `/opt/rust-synapse-compress-state/` on LXC 109). Every run verified `New state map matches old one` before commit:
|
||||||
@@ -981,7 +1037,7 @@ than nightly compression can keep up with.
|
|||||||
> **Do NOT compress `Spam and Stuff`.** Its 107,763 state groups hold only 107,799 rows (~1 row each) — already minimal. The compressor's leveled structure would *add* rows (dry run: **110.16%**) and it refuses to run. High state-group count is not the same as compressible bloat.
|
> **Do NOT compress `Spam and Stuff`.** Its 107,763 state groups hold only 107,799 rows (~1 row each) — already minimal. The compressor's leveled structure would *add* rows (dry run: **110.16%**) and it refuses to run. High state-group count is not the same as compressible bloat.
|
||||||
|
|
||||||
- [x] PostgreSQL: `jit=off`, `wal_compression=lz4`, `max_worker_processes` 3→8, `maintenance_work_mem` 256MB→512MB, `shared_buffers` 1500MB→2GB in `/etc/postgresql/17/main/conf.d/synapse_tuning.conf`. Previous version kept as `synapse_tuning.conf.bak-20260726`. **That file is not in this repo — the tuning is unversioned.**
|
- [x] PostgreSQL: `jit=off`, `wal_compression=lz4`, `max_worker_processes` 3→8, `maintenance_work_mem` 256MB→512MB, `shared_buffers` 1500MB→2GB in `/etc/postgresql/17/main/conf.d/synapse_tuning.conf`. Previous version kept as `synapse_tuning.conf.bak-20260726`. **That file is not in this repo — the tuning is unversioned.**
|
||||||
- [ ] `synchronous_commit = off` — **deliberately NOT applied.** Would be a real write-latency win, but this cluster hard-resets every few hours (HA self-fences on corosync quorum loss + the large1 DIMM), so it would drop up to ~600ms of committed messages *per reset* rather than once in a blue moon. Revisit once the cluster is stable.
|
- [ ] `synchronous_commit = off` — **deliberately NOT applied.** Would be a real write-latency win, but this cluster hard-resets every few hours (HA self-fences on corosync quorum loss + the compute-storage-02 DIMM), so it would drop up to ~600ms of committed messages *per reset* rather than once in a blue moon. Revisit once the cluster is stable.
|
||||||
|
|
||||||
### Auth & SSO
|
### Auth & SSO
|
||||||
- [x] Open registration disabled (`enable_registration: false`, 2026-10-16): accounts come from LLDAP and are created on first sign-in through Lotus SSO (Authelia OIDC, which keeps its own registration on). The old registration token was deleted.
|
- [x] Open registration disabled (`enable_registration: false`, 2026-10-16): accounts come from LLDAP and are created on first sign-in through Lotus SSO (Authelia OIDC, which keeps its own registration on). The old registration token was deleted.
|
||||||
|
|||||||
+7
-1
@@ -28,12 +28,18 @@
|
|||||||
"statusPages": {
|
"statusPages": {
|
||||||
"matrix.lotusguild.org": {
|
"matrix.lotusguild.org": {
|
||||||
"url": "https://isitup.lotusguild.org",
|
"url": "https://isitup.lotusguild.org",
|
||||||
"slug": "matrix",
|
"slug": "public",
|
||||||
|
"noticePrefix": "Matrix:",
|
||||||
"groups": {
|
"groups": {
|
||||||
"homeserver": "Homeserver",
|
"homeserver": "Homeserver",
|
||||||
"calls": "Voice calls",
|
"calls": "Voice calls",
|
||||||
"login": "Login"
|
"login": "Login"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
},
|
||||||
|
"nowPlaying": {
|
||||||
|
"matrix.lotusguild.org": {
|
||||||
|
"url": "https://matrix.lotusguild.org/now-playing"
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Build mautrix-discord with the Lotus patches in discord-bridge/patches/.
|
||||||
|
#
|
||||||
|
# Needs: git, Go (version from upstream go.mod or newer), a C compiler and libolm-dev.
|
||||||
|
# Output: ./mautrix-discord-lotus (dynamically linked against libolm.so.3, which
|
||||||
|
# LXC 151 has from the libolm3 package).
|
||||||
|
#
|
||||||
|
# Deploy (on the Proxmox node hosting LXC 151):
|
||||||
|
# pct push 151 mautrix-discord-lotus /opt/mautrix-discord/mautrix-discord.new
|
||||||
|
# pct exec 151 -- bash -c 'cd /opt/mautrix-discord && cp -a mautrix-discord mautrix-discord.bak-$(date +%Y%m%d) \
|
||||||
|
# && chown mautrix-discord: mautrix-discord.new && chmod 755 mautrix-discord.new \
|
||||||
|
# && mv mautrix-discord.new mautrix-discord && systemctl restart mautrix-discord'
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
VERSION="${VERSION:-v0.7.7}"
|
||||||
|
HERE="$(cd "$(dirname "$0")" && pwd)"
|
||||||
|
OUT="${OUT:-$PWD/mautrix-discord-lotus}"
|
||||||
|
WORK="$(mktemp -d)"
|
||||||
|
trap 'rm -rf "$WORK"' EXIT
|
||||||
|
|
||||||
|
git clone -q --depth 1 --branch "$VERSION" https://github.com/mautrix/discord.git "$WORK/src"
|
||||||
|
cd "$WORK/src"
|
||||||
|
for p in "$HERE"/patches/*.patch; do
|
||||||
|
echo "applying $(basename "$p")"
|
||||||
|
git apply "$p"
|
||||||
|
done
|
||||||
|
|
||||||
|
go test -race -count=1 -run 'Retry|PreSend|Ambiguous|Echo' .
|
||||||
|
|
||||||
|
COMMIT="$(git rev-parse HEAD)"
|
||||||
|
MAUTRIX="$(go list -m -f '{{.Version}}' maunium.net/go/mautrix)"
|
||||||
|
CGO_ENABLED=1 go build -o "$OUT" -ldflags "-s -w \
|
||||||
|
-X main.Tag=$VERSION \
|
||||||
|
-X main.Commit=$COMMIT+lotus \
|
||||||
|
-X 'main.BuildTime=$(date '+%b %_d %Y, %H:%M:%S')' \
|
||||||
|
-X 'maunium.net/go/mautrix.GoModVersion=$MAUTRIX'" .
|
||||||
|
|
||||||
|
"$OUT" --version
|
||||||
|
echo "built $OUT"
|
||||||
@@ -0,0 +1,253 @@
|
|||||||
|
diff --git a/lotus_retry.go b/lotus_retry.go
|
||||||
|
new file mode 100644
|
||||||
|
index 0000000..972b612
|
||||||
|
--- /dev/null
|
||||||
|
+++ b/lotus_retry.go
|
||||||
|
@@ -0,0 +1,95 @@
|
||||||
|
+package main
|
||||||
|
+
|
||||||
|
+// [lotus] Retry Matrix→Discord sends that failed before reaching Discord.
|
||||||
|
+//
|
||||||
|
+// Upstream sends each message exactly once; a momentary network blip (for
|
||||||
|
+// example "net/http: TLS handshake timeout") drops the message and only posts
|
||||||
|
+// a "may not have been bridged" notice. We retry, but only for failures that
|
||||||
|
+// happen before the HTTP request is written (DNS, dial, TLS handshake). Those
|
||||||
|
+// cannot have reached Discord, so a retry can never post a duplicate.
|
||||||
|
+// Failures after the request was sent (read timeouts, resets, 5xx) are left
|
||||||
|
+// alone because webhook sends have no server-side dedupe.
|
||||||
|
+//
|
||||||
|
+// The retry runs inline in the portal's Matrix event loop, which handles a
|
||||||
|
+// room's events one at a time, so later messages queue behind it and ordering
|
||||||
|
+// is preserved.
|
||||||
|
+
|
||||||
|
+import (
|
||||||
|
+ "errors"
|
||||||
|
+ "io"
|
||||||
|
+ "net"
|
||||||
|
+ "strings"
|
||||||
|
+ "time"
|
||||||
|
+
|
||||||
|
+ "github.com/bwmarrin/discordgo"
|
||||||
|
+ "github.com/rs/zerolog"
|
||||||
|
+)
|
||||||
|
+
|
||||||
|
+var lotusSendRetryDelays = []time.Duration{
|
||||||
|
+ 2 * time.Second,
|
||||||
|
+ 5 * time.Second,
|
||||||
|
+ 10 * time.Second,
|
||||||
|
+ 20 * time.Second,
|
||||||
|
+ 30 * time.Second,
|
||||||
|
+ 60 * time.Second,
|
||||||
|
+ 60 * time.Second,
|
||||||
|
+ 60 * time.Second,
|
||||||
|
+}
|
||||||
|
+
|
||||||
|
+// lotusSleep is swapped out in tests.
|
||||||
|
+var lotusSleep = time.Sleep
|
||||||
|
+
|
||||||
|
+// isPreSendNetworkError reports whether err happened before the request could
|
||||||
|
+// have been written to Discord.
|
||||||
|
+func isPreSendNetworkError(err error) bool {
|
||||||
|
+ if err == nil {
|
||||||
|
+ return false
|
||||||
|
+ }
|
||||||
|
+ var restErr *discordgo.RESTError
|
||||||
|
+ if errors.As(err, &restErr) {
|
||||||
|
+ // Discord answered, so the request was delivered.
|
||||||
|
+ return false
|
||||||
|
+ }
|
||||||
|
+ var dnsErr *net.DNSError
|
||||||
|
+ if errors.As(err, &dnsErr) {
|
||||||
|
+ return true
|
||||||
|
+ }
|
||||||
|
+ var opErr *net.OpError
|
||||||
|
+ if errors.As(err, &opErr) && opErr.Op == "dial" {
|
||||||
|
+ return true
|
||||||
|
+ }
|
||||||
|
+ msg := err.Error()
|
||||||
|
+ return strings.Contains(msg, "TLS handshake timeout") ||
|
||||||
|
+ strings.Contains(msg, "proxyconnect")
|
||||||
|
+}
|
||||||
|
+
|
||||||
|
+func lotusRewindFiles(files []*discordgo.File) {
|
||||||
|
+ for _, f := range files {
|
||||||
|
+ if f == nil {
|
||||||
|
+ continue
|
||||||
|
+ }
|
||||||
|
+ if s, ok := f.Reader.(io.Seeker); ok {
|
||||||
|
+ _, _ = s.Seek(0, io.SeekStart)
|
||||||
|
+ }
|
||||||
|
+ }
|
||||||
|
+}
|
||||||
|
+
|
||||||
|
+// lotusRetrySend calls send until it succeeds, fails with an error that is not
|
||||||
|
+// a pre-send network error, or the retry budget runs out.
|
||||||
|
+func lotusRetrySend[T any](log zerolog.Logger, files []*discordgo.File, send func() (T, error)) (T, error) {
|
||||||
|
+ res, err := send()
|
||||||
|
+ for attempt := 0; attempt < len(lotusSendRetryDelays) && isPreSendNetworkError(err); attempt++ {
|
||||||
|
+ delay := lotusSendRetryDelays[attempt]
|
||||||
|
+ log.Warn().Err(err).
|
||||||
|
+ Int("attempt", attempt+1).
|
||||||
|
+ Dur("retry_in", delay).
|
||||||
|
+ Msg("[lotus] Discord send failed before reaching Discord, retrying")
|
||||||
|
+ lotusSleep(delay)
|
||||||
|
+ lotusRewindFiles(files)
|
||||||
|
+ res, err = send()
|
||||||
|
+ if err == nil {
|
||||||
|
+ log.Info().Int("attempts", attempt+2).Msg("[lotus] Discord send succeeded after retry")
|
||||||
|
+ }
|
||||||
|
+ }
|
||||||
|
+ return res, err
|
||||||
|
+}
|
||||||
|
diff --git a/lotus_retry_test.go b/lotus_retry_test.go
|
||||||
|
new file mode 100644
|
||||||
|
index 0000000..efa262e
|
||||||
|
--- /dev/null
|
||||||
|
+++ b/lotus_retry_test.go
|
||||||
|
@@ -0,0 +1,108 @@
|
||||||
|
+package main
|
||||||
|
+
|
||||||
|
+import (
|
||||||
|
+ "bytes"
|
||||||
|
+ "errors"
|
||||||
|
+ "io"
|
||||||
|
+ "net"
|
||||||
|
+ "net/http"
|
||||||
|
+ "net/url"
|
||||||
|
+ "testing"
|
||||||
|
+ "time"
|
||||||
|
+
|
||||||
|
+ "github.com/bwmarrin/discordgo"
|
||||||
|
+ "github.com/rs/zerolog"
|
||||||
|
+)
|
||||||
|
+
|
||||||
|
+type tlsTimeout struct{}
|
||||||
|
+
|
||||||
|
+func (tlsTimeout) Error() string { return "net/http: TLS handshake timeout" }
|
||||||
|
+func (tlsTimeout) Timeout() bool { return true }
|
||||||
|
+func (tlsTimeout) Temporary() bool { return true }
|
||||||
|
+
|
||||||
|
+func urlErr(err error) error {
|
||||||
|
+ return &url.Error{Op: "Post", URL: "https://discord.com/api/v9/webhooks/1/x?wait=true", Err: err}
|
||||||
|
+}
|
||||||
|
+
|
||||||
|
+func TestIsPreSendNetworkError(t *testing.T) {
|
||||||
|
+ cases := []struct {
|
||||||
|
+ name string
|
||||||
|
+ err error
|
||||||
|
+ want bool
|
||||||
|
+ }{
|
||||||
|
+ {"nil", nil, false},
|
||||||
|
+ {"tls handshake timeout", urlErr(tlsTimeout{}), true},
|
||||||
|
+ {"dns", urlErr(&net.DNSError{Err: "no such host", Name: "discord.com"}), true},
|
||||||
|
+ {"dial refused", urlErr(&net.OpError{Op: "dial", Net: "tcp", Err: errors.New("connection refused")}), true},
|
||||||
|
+ {"read reset after send", urlErr(&net.OpError{Op: "read", Net: "tcp", Err: errors.New("connection reset by peer")}), false},
|
||||||
|
+ {"response timeout", urlErr(errors.New("context deadline exceeded (Client.Timeout exceeded while awaiting headers)")), false},
|
||||||
|
+ {"discord rest error", &discordgo.RESTError{Response: &http.Response{StatusCode: 500}}, false},
|
||||||
|
+ {"other", errors.New("unknown message type"), false},
|
||||||
|
+ }
|
||||||
|
+ for _, c := range cases {
|
||||||
|
+ if got := isPreSendNetworkError(c.err); got != c.want {
|
||||||
|
+ t.Errorf("%s: got %v want %v", c.name, got, c.want)
|
||||||
|
+ }
|
||||||
|
+ }
|
||||||
|
+}
|
||||||
|
+
|
||||||
|
+func withNoSleep(t *testing.T) *[]time.Duration {
|
||||||
|
+ var slept []time.Duration
|
||||||
|
+ old := lotusSleep
|
||||||
|
+ lotusSleep = func(d time.Duration) { slept = append(slept, d) }
|
||||||
|
+ t.Cleanup(func() { lotusSleep = old })
|
||||||
|
+ return &slept
|
||||||
|
+}
|
||||||
|
+
|
||||||
|
+func TestRetrySendRecoversAndRewindsFiles(t *testing.T) {
|
||||||
|
+ slept := withNoSleep(t)
|
||||||
|
+ file := &discordgo.File{Name: "a.txt", Reader: bytes.NewReader([]byte("hello"))}
|
||||||
|
+ calls := 0
|
||||||
|
+ msg, err := lotusRetrySend(zerolog.Nop(), []*discordgo.File{file}, func() (*discordgo.Message, error) {
|
||||||
|
+ calls++
|
||||||
|
+ data, _ := io.ReadAll(file.Reader)
|
||||||
|
+ if string(data) != "hello" {
|
||||||
|
+ t.Fatalf("call %d read %q, file not rewound", calls, data)
|
||||||
|
+ }
|
||||||
|
+ if calls < 3 {
|
||||||
|
+ return nil, urlErr(tlsTimeout{})
|
||||||
|
+ }
|
||||||
|
+ return &discordgo.Message{ID: "42"}, nil
|
||||||
|
+ })
|
||||||
|
+ if err != nil || msg == nil || msg.ID != "42" {
|
||||||
|
+ t.Fatalf("got msg=%v err=%v", msg, err)
|
||||||
|
+ }
|
||||||
|
+ if calls != 3 {
|
||||||
|
+ t.Fatalf("calls=%d want 3", calls)
|
||||||
|
+ }
|
||||||
|
+ if len(*slept) != 2 || (*slept)[0] != 2*time.Second || (*slept)[1] != 5*time.Second {
|
||||||
|
+ t.Fatalf("slept=%v", *slept)
|
||||||
|
+ }
|
||||||
|
+}
|
||||||
|
+
|
||||||
|
+func TestRetrySendDoesNotRetryAfterSend(t *testing.T) {
|
||||||
|
+ withNoSleep(t)
|
||||||
|
+ calls := 0
|
||||||
|
+ _, err := lotusRetrySend(zerolog.Nop(), nil, func() (*discordgo.Message, error) {
|
||||||
|
+ calls++
|
||||||
|
+ return nil, urlErr(&net.OpError{Op: "read", Net: "tcp", Err: errors.New("connection reset by peer")})
|
||||||
|
+ })
|
||||||
|
+ if err == nil || calls != 1 {
|
||||||
|
+ t.Fatalf("calls=%d err=%v, want exactly one attempt", calls, err)
|
||||||
|
+ }
|
||||||
|
+}
|
||||||
|
+
|
||||||
|
+func TestRetrySendGivesUpAfterBudget(t *testing.T) {
|
||||||
|
+ slept := withNoSleep(t)
|
||||||
|
+ calls := 0
|
||||||
|
+ _, err := lotusRetrySend(zerolog.Nop(), nil, func() (*discordgo.Message, error) {
|
||||||
|
+ calls++
|
||||||
|
+ return nil, urlErr(tlsTimeout{})
|
||||||
|
+ })
|
||||||
|
+ if err == nil {
|
||||||
|
+ t.Fatal("expected error after budget")
|
||||||
|
+ }
|
||||||
|
+ if calls != len(lotusSendRetryDelays)+1 || len(*slept) != len(lotusSendRetryDelays) {
|
||||||
|
+ t.Fatalf("calls=%d slept=%d", calls, len(*slept))
|
||||||
|
+ }
|
||||||
|
+}
|
||||||
|
diff --git a/portal.go b/portal.go
|
||||||
|
index db26a0e..cc6da0d 100644
|
||||||
|
--- a/portal.go
|
||||||
|
+++ b/portal.go
|
||||||
|
@@ -1743,18 +1743,24 @@ func (portal *Portal) handleMatrixMessage(sender *User, evt *event.Event) {
|
||||||
|
sendReq.Nonce = generateNonce()
|
||||||
|
var msg *discordgo.Message
|
||||||
|
var err error
|
||||||
|
+ // [lotus] retry sends that failed before reaching Discord (see lotus_retry.go)
|
||||||
|
+ sendLog := portal.log.With().Str("event_id", evt.ID.String()).Logger()
|
||||||
|
if !isWebhookSend {
|
||||||
|
- msg, err = sess.ChannelMessageSendComplex(channelID, &sendReq, portal.RefererOptIfUser(sess, threadID)...)
|
||||||
|
+ msg, err = lotusRetrySend(sendLog, sendReq.Files, func() (*discordgo.Message, error) {
|
||||||
|
+ return sess.ChannelMessageSendComplex(channelID, &sendReq, portal.RefererOptIfUser(sess, threadID)...)
|
||||||
|
+ })
|
||||||
|
} else {
|
||||||
|
username, avatarURL := portal.getRelayUserMeta(sender)
|
||||||
|
- msg, err = relayClient.WebhookThreadExecute(portal.RelayWebhookID, portal.RelayWebhookSecret, true, threadID, &discordgo.WebhookParams{
|
||||||
|
- Content: sendReq.Content,
|
||||||
|
- Username: username,
|
||||||
|
- AvatarURL: avatarURL,
|
||||||
|
- Files: sendReq.Files,
|
||||||
|
- Components: sendReq.Components,
|
||||||
|
- Embeds: sendReq.Embeds,
|
||||||
|
- AllowedMentions: sendReq.AllowedMentions,
|
||||||
|
+ msg, err = lotusRetrySend(sendLog, sendReq.Files, func() (*discordgo.Message, error) {
|
||||||
|
+ return relayClient.WebhookThreadExecute(portal.RelayWebhookID, portal.RelayWebhookSecret, true, threadID, &discordgo.WebhookParams{
|
||||||
|
+ Content: sendReq.Content,
|
||||||
|
+ Username: username,
|
||||||
|
+ AvatarURL: avatarURL,
|
||||||
|
+ Files: sendReq.Files,
|
||||||
|
+ Components: sendReq.Components,
|
||||||
|
+ Embeds: sendReq.Embeds,
|
||||||
|
+ AllowedMentions: sendReq.AllowedMentions,
|
||||||
|
+ })
|
||||||
|
})
|
||||||
|
}
|
||||||
|
sender.handlePossible40002(err)
|
||||||
+437
@@ -0,0 +1,437 @@
|
|||||||
|
diff --git a/lotus_echo.go b/lotus_echo.go
|
||||||
|
new file mode 100644
|
||||||
|
index 0000000..0cfdd95
|
||||||
|
--- /dev/null
|
||||||
|
+++ b/lotus_echo.go
|
||||||
|
@@ -0,0 +1,118 @@
|
||||||
|
+package main
|
||||||
|
+
|
||||||
|
+// [lotus] Detect whether a webhook send that errored actually reached Discord.
|
||||||
|
+//
|
||||||
|
+// Discord echoes every webhook post back over the gateway as MESSAGE_CREATE.
|
||||||
|
+// While a relay send is in flight we register a waiter for its channel; the
|
||||||
|
+// gateway handler (user.go) offers every new message to the waiters before
|
||||||
|
+// queueing it for the portal. If a send fails ambiguously (the connection broke
|
||||||
|
+// after the request may have gone out), lotusRetrySend asks the waiter whether
|
||||||
|
+// the post showed up. If it did, the send is treated as successful and the
|
||||||
|
+// message ID recorded, so it is neither resent to Discord nor bridged back into
|
||||||
|
+// Matrix as a new message.
|
||||||
|
+//
|
||||||
|
+// The waiter is offered messages from the gateway goroutine, which keeps
|
||||||
|
+// running while the portal's own loop is blocked in the send.
|
||||||
|
+
|
||||||
|
+import (
|
||||||
|
+ "strings"
|
||||||
|
+ "sync"
|
||||||
|
+ "time"
|
||||||
|
+
|
||||||
|
+ "github.com/bwmarrin/discordgo"
|
||||||
|
+)
|
||||||
|
+
|
||||||
|
+// lotusEchoWait is how long to wait for the gateway echo after an ambiguous
|
||||||
|
+// failure. Echoes normally arrive well under a second after Discord accepts the
|
||||||
|
+// post.
|
||||||
|
+var lotusEchoWait = 6 * time.Second
|
||||||
|
+
|
||||||
|
+type lotusEchoWaiter struct {
|
||||||
|
+ match func(*discordgo.Message) bool
|
||||||
|
+ ch chan *discordgo.Message
|
||||||
|
+}
|
||||||
|
+
|
||||||
|
+var (
|
||||||
|
+ lotusEchoMu sync.Mutex
|
||||||
|
+ lotusEchoWaiters = map[string][]*lotusEchoWaiter{}
|
||||||
|
+)
|
||||||
|
+
|
||||||
|
+// lotusNoteGatewayMessage offers a newly created Discord message to any waiter
|
||||||
|
+// registered for its channel. Called for every MESSAGE_CREATE.
|
||||||
|
+func lotusNoteGatewayMessage(msg *discordgo.Message) {
|
||||||
|
+ if msg == nil || msg.WebhookID == "" {
|
||||||
|
+ return
|
||||||
|
+ }
|
||||||
|
+ lotusEchoMu.Lock()
|
||||||
|
+ defer lotusEchoMu.Unlock()
|
||||||
|
+ for _, w := range lotusEchoWaiters[msg.ChannelID] {
|
||||||
|
+ if w.match(msg) {
|
||||||
|
+ select {
|
||||||
|
+ case w.ch <- msg:
|
||||||
|
+ default:
|
||||||
|
+ }
|
||||||
|
+ }
|
||||||
|
+ }
|
||||||
|
+}
|
||||||
|
+
|
||||||
|
+// lotusExpectEcho registers a waiter for channelID. check(wait) returns the
|
||||||
|
+// matching message if one has arrived, waiting up to lotusEchoWait when wait
|
||||||
|
+// is true. done must be called when the send is finished.
|
||||||
|
+func lotusExpectEcho(channelID string, match func(*discordgo.Message) bool) (check func(wait bool) (*discordgo.Message, bool), done func()) {
|
||||||
|
+ w := &lotusEchoWaiter{match: match, ch: make(chan *discordgo.Message, 1)}
|
||||||
|
+ lotusEchoMu.Lock()
|
||||||
|
+ lotusEchoWaiters[channelID] = append(lotusEchoWaiters[channelID], w)
|
||||||
|
+ lotusEchoMu.Unlock()
|
||||||
|
+
|
||||||
|
+ check = func(wait bool) (*discordgo.Message, bool) {
|
||||||
|
+ if !wait {
|
||||||
|
+ select {
|
||||||
|
+ case msg := <-w.ch:
|
||||||
|
+ return msg, true
|
||||||
|
+ default:
|
||||||
|
+ return nil, false
|
||||||
|
+ }
|
||||||
|
+ }
|
||||||
|
+ timer := time.NewTimer(lotusEchoWait)
|
||||||
|
+ defer timer.Stop()
|
||||||
|
+ select {
|
||||||
|
+ case msg := <-w.ch:
|
||||||
|
+ return msg, true
|
||||||
|
+ case <-timer.C:
|
||||||
|
+ return nil, false
|
||||||
|
+ }
|
||||||
|
+ }
|
||||||
|
+ done = func() {
|
||||||
|
+ lotusEchoMu.Lock()
|
||||||
|
+ defer lotusEchoMu.Unlock()
|
||||||
|
+ list := lotusEchoWaiters[channelID]
|
||||||
|
+ for i, x := range list {
|
||||||
|
+ if x == w {
|
||||||
|
+ list = append(list[:i], list[i+1:]...)
|
||||||
|
+ break
|
||||||
|
+ }
|
||||||
|
+ }
|
||||||
|
+ if len(list) == 0 {
|
||||||
|
+ delete(lotusEchoWaiters, channelID)
|
||||||
|
+ } else {
|
||||||
|
+ lotusEchoWaiters[channelID] = list
|
||||||
|
+ }
|
||||||
|
+ }
|
||||||
|
+ return check, done
|
||||||
|
+}
|
||||||
|
+
|
||||||
|
+// lotusWebhookEchoMatcher matches the gateway echo of a relay post: same
|
||||||
|
+// webhook, same text (ignoring surrounding whitespace, which Discord trims),
|
||||||
|
+// same number of attachments, created no earlier than shortly before the send
|
||||||
|
+// started.
|
||||||
|
+func lotusWebhookEchoMatcher(webhookID, content string, numFiles int, started time.Time) func(*discordgo.Message) bool {
|
||||||
|
+ notBefore := started.Add(-2 * time.Second)
|
||||||
|
+ content = strings.TrimSpace(content)
|
||||||
|
+ return func(msg *discordgo.Message) bool {
|
||||||
|
+ if msg.WebhookID != webhookID || strings.TrimSpace(msg.Content) != content || len(msg.Attachments) != numFiles {
|
||||||
|
+ return false
|
||||||
|
+ }
|
||||||
|
+ ts, err := discordgo.SnowflakeTimestamp(msg.ID)
|
||||||
|
+ return err != nil || !ts.Before(notBefore)
|
||||||
|
+ }
|
||||||
|
+}
|
||||||
|
diff --git a/lotus_echo_test.go b/lotus_echo_test.go
|
||||||
|
new file mode 100644
|
||||||
|
index 0000000..6f5ad44
|
||||||
|
--- /dev/null
|
||||||
|
+++ b/lotus_echo_test.go
|
||||||
|
@@ -0,0 +1,153 @@
|
||||||
|
+package main
|
||||||
|
+
|
||||||
|
+import (
|
||||||
|
+ "errors"
|
||||||
|
+ "net"
|
||||||
|
+ "net/http"
|
||||||
|
+ "strconv"
|
||||||
|
+ "testing"
|
||||||
|
+ "time"
|
||||||
|
+
|
||||||
|
+ "github.com/bwmarrin/discordgo"
|
||||||
|
+ "github.com/rs/zerolog"
|
||||||
|
+)
|
||||||
|
+
|
||||||
|
+func resetErr() error {
|
||||||
|
+ return urlErr(&net.OpError{Op: "read", Net: "tcp", Err: errors.New("connection reset by peer")})
|
||||||
|
+}
|
||||||
|
+
|
||||||
|
+func TestIsAmbiguousSendError(t *testing.T) {
|
||||||
|
+ cases := []struct {
|
||||||
|
+ name string
|
||||||
|
+ err error
|
||||||
|
+ want bool
|
||||||
|
+ }{
|
||||||
|
+ {"nil", nil, false},
|
||||||
|
+ {"tls handshake timeout is pre-send", urlErr(tlsTimeout{}), false},
|
||||||
|
+ {"read reset", resetErr(), true},
|
||||||
|
+ {"awaiting headers", urlErr(errors.New("context deadline exceeded (Client.Timeout exceeded while awaiting headers)")), true},
|
||||||
|
+ {"unexpected EOF", urlErr(errors.New("unexpected EOF")), true},
|
||||||
|
+ {"discord 502", &discordgo.RESTError{Response: &http.Response{StatusCode: 502}}, true},
|
||||||
|
+ {"discord 400", &discordgo.RESTError{Response: &http.Response{StatusCode: 400}}, false},
|
||||||
|
+ {"other", errors.New("unknown message type"), false},
|
||||||
|
+ }
|
||||||
|
+ for _, c := range cases {
|
||||||
|
+ if got := isAmbiguousSendError(c.err); got != c.want {
|
||||||
|
+ t.Errorf("%s: got %v want %v", c.name, got, c.want)
|
||||||
|
+ }
|
||||||
|
+ }
|
||||||
|
+}
|
||||||
|
+
|
||||||
|
+func TestRetrySendAmbiguousWithoutCheckerIsNotRetried(t *testing.T) {
|
||||||
|
+ withNoSleep(t)
|
||||||
|
+ calls := 0
|
||||||
|
+ _, err := lotusRetrySend(zerolog.Nop(), nil, func() (*discordgo.Message, error) {
|
||||||
|
+ calls++
|
||||||
|
+ return nil, resetErr()
|
||||||
|
+ }, nil)
|
||||||
|
+ if err == nil || calls != 1 {
|
||||||
|
+ t.Fatalf("calls=%d err=%v", calls, err)
|
||||||
|
+ }
|
||||||
|
+}
|
||||||
|
+
|
||||||
|
+func TestRetrySendAmbiguousButDeliveredIsNotResent(t *testing.T) {
|
||||||
|
+ withNoSleep(t)
|
||||||
|
+ calls := 0
|
||||||
|
+ msg, err := lotusRetrySend(zerolog.Nop(), nil, func() (*discordgo.Message, error) {
|
||||||
|
+ calls++
|
||||||
|
+ return nil, resetErr()
|
||||||
|
+ }, func(wait bool) (*discordgo.Message, bool) {
|
||||||
|
+ return &discordgo.Message{ID: "echo"}, true
|
||||||
|
+ })
|
||||||
|
+ if err != nil || msg == nil || msg.ID != "echo" || calls != 1 {
|
||||||
|
+ t.Fatalf("calls=%d msg=%v err=%v", calls, msg, err)
|
||||||
|
+ }
|
||||||
|
+}
|
||||||
|
+
|
||||||
|
+func TestRetrySendAmbiguousNotDeliveredIsResent(t *testing.T) {
|
||||||
|
+ slept := withNoSleep(t)
|
||||||
|
+ calls := 0
|
||||||
|
+ var waits []bool
|
||||||
|
+ msg, err := lotusRetrySend(zerolog.Nop(), nil, func() (*discordgo.Message, error) {
|
||||||
|
+ calls++
|
||||||
|
+ if calls == 1 {
|
||||||
|
+ return nil, resetErr()
|
||||||
|
+ }
|
||||||
|
+ return &discordgo.Message{ID: "2"}, nil
|
||||||
|
+ }, func(wait bool) (*discordgo.Message, bool) {
|
||||||
|
+ waits = append(waits, wait)
|
||||||
|
+ return nil, false
|
||||||
|
+ })
|
||||||
|
+ if err != nil || msg.ID != "2" || calls != 2 || len(*slept) != 1 {
|
||||||
|
+ t.Fatalf("calls=%d msg=%v err=%v slept=%v", calls, msg, err, *slept)
|
||||||
|
+ }
|
||||||
|
+ if len(waits) != 2 || !waits[0] || waits[1] {
|
||||||
|
+ t.Fatalf("waits=%v, want [true false]", waits)
|
||||||
|
+ }
|
||||||
|
+}
|
||||||
|
+
|
||||||
|
+func TestRetrySendLateEchoDuringBackoffStopsResend(t *testing.T) {
|
||||||
|
+ withNoSleep(t)
|
||||||
|
+ calls := 0
|
||||||
|
+ checks := 0
|
||||||
|
+ msg, err := lotusRetrySend(zerolog.Nop(), nil, func() (*discordgo.Message, error) {
|
||||||
|
+ calls++
|
||||||
|
+ return nil, resetErr()
|
||||||
|
+ }, func(wait bool) (*discordgo.Message, bool) {
|
||||||
|
+ checks++
|
||||||
|
+ if checks == 2 { // the echo arrives during the backoff
|
||||||
|
+ return &discordgo.Message{ID: "late"}, true
|
||||||
|
+ }
|
||||||
|
+ return nil, false
|
||||||
|
+ })
|
||||||
|
+ if err != nil || msg.ID != "late" || calls != 1 {
|
||||||
|
+ t.Fatalf("calls=%d msg=%v err=%v", calls, msg, err)
|
||||||
|
+ }
|
||||||
|
+}
|
||||||
|
+
|
||||||
|
+func snowflakeAt(ts time.Time) string {
|
||||||
|
+ ms := ts.UnixMilli() - 1420070400000
|
||||||
|
+ return strconv.FormatInt(ms<<22, 10)
|
||||||
|
+}
|
||||||
|
+
|
||||||
|
+func TestEchoWaiterMatchesWebhookPost(t *testing.T) {
|
||||||
|
+ oldWait := lotusEchoWait
|
||||||
|
+ lotusEchoWait = 200 * time.Millisecond
|
||||||
|
+ t.Cleanup(func() { lotusEchoWait = oldWait })
|
||||||
|
+
|
||||||
|
+ start := time.Now()
|
||||||
|
+ check, done := lotusExpectEcho("chan1", lotusWebhookEchoMatcher("hook1", "hi", 1, start))
|
||||||
|
+ defer done()
|
||||||
|
+
|
||||||
|
+ if _, ok := check(false); ok {
|
||||||
|
+ t.Fatal("matched before any message")
|
||||||
|
+ }
|
||||||
|
+ // Wrong webhook, wrong content, wrong channel and an old message are ignored.
|
||||||
|
+ lotusNoteGatewayMessage(&discordgo.Message{ID: snowflakeAt(start), ChannelID: "chan1", WebhookID: "other", Content: "hi", Attachments: make([]*discordgo.MessageAttachment, 1)})
|
||||||
|
+ lotusNoteGatewayMessage(&discordgo.Message{ID: snowflakeAt(start), ChannelID: "chan1", WebhookID: "hook1", Content: "nope", Attachments: make([]*discordgo.MessageAttachment, 1)})
|
||||||
|
+ lotusNoteGatewayMessage(&discordgo.Message{ID: snowflakeAt(start), ChannelID: "chan2", WebhookID: "hook1", Content: "hi", Attachments: make([]*discordgo.MessageAttachment, 1)})
|
||||||
|
+ lotusNoteGatewayMessage(&discordgo.Message{ID: snowflakeAt(start.Add(-time.Minute)), ChannelID: "chan1", WebhookID: "hook1", Content: "hi", Attachments: make([]*discordgo.MessageAttachment, 1)})
|
||||||
|
+ if _, ok := check(true); ok {
|
||||||
|
+ t.Fatal("matched a non-matching message")
|
||||||
|
+ }
|
||||||
|
+
|
||||||
|
+ want := snowflakeAt(start.Add(time.Second))
|
||||||
|
+ go func() {
|
||||||
|
+ time.Sleep(20 * time.Millisecond)
|
||||||
|
+ lotusNoteGatewayMessage(&discordgo.Message{ID: want, ChannelID: "chan1", WebhookID: "hook1", Content: "hi", Attachments: make([]*discordgo.MessageAttachment, 1)})
|
||||||
|
+ }()
|
||||||
|
+ got, ok := check(true)
|
||||||
|
+ if !ok || got.ID != want {
|
||||||
|
+ t.Fatalf("got %v ok=%v", got, ok)
|
||||||
|
+ }
|
||||||
|
+}
|
||||||
|
+
|
||||||
|
+func TestEchoWaiterDoneUnregisters(t *testing.T) {
|
||||||
|
+ _, done := lotusExpectEcho("chanX", func(*discordgo.Message) bool { return true })
|
||||||
|
+ done()
|
||||||
|
+ lotusEchoMu.Lock()
|
||||||
|
+ defer lotusEchoMu.Unlock()
|
||||||
|
+ if _, ok := lotusEchoWaiters["chanX"]; ok {
|
||||||
|
+ t.Fatal("waiter still registered after done")
|
||||||
|
+ }
|
||||||
|
+}
|
||||||
|
diff --git a/lotus_retry.go b/lotus_retry.go
|
||||||
|
index 972b612..0c5e147 100644
|
||||||
|
--- a/lotus_retry.go
|
||||||
|
+++ b/lotus_retry.go
|
||||||
|
@@ -74,17 +74,69 @@ func lotusRewindFiles(files []*discordgo.File) {
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
+// isAmbiguousSendError reports whether err happened after the request may
|
||||||
|
+// already have reached Discord: the connection broke or timed out while
|
||||||
|
+// sending or waiting for the reply, or Discord answered with a 5xx.
|
||||||
|
+func isAmbiguousSendError(err error) bool {
|
||||||
|
+ if err == nil || isPreSendNetworkError(err) {
|
||||||
|
+ return false
|
||||||
|
+ }
|
||||||
|
+ var restErr *discordgo.RESTError
|
||||||
|
+ if errors.As(err, &restErr) {
|
||||||
|
+ return restErr.Response != nil && restErr.Response.StatusCode >= 500
|
||||||
|
+ }
|
||||||
|
+ if errors.Is(err, io.EOF) || errors.Is(err, io.ErrUnexpectedEOF) {
|
||||||
|
+ return true
|
||||||
|
+ }
|
||||||
|
+ var netErr net.Error
|
||||||
|
+ if errors.As(err, &netErr) {
|
||||||
|
+ return true
|
||||||
|
+ }
|
||||||
|
+ msg := err.Error()
|
||||||
|
+ return strings.Contains(msg, "connection reset") ||
|
||||||
|
+ strings.Contains(msg, "broken pipe") ||
|
||||||
|
+ strings.Contains(msg, "Client.Timeout exceeded") ||
|
||||||
|
+ strings.Contains(msg, "server sent GOAWAY") ||
|
||||||
|
+ strings.Contains(msg, "EOF")
|
||||||
|
+}
|
||||||
|
+
|
||||||
|
// lotusRetrySend calls send until it succeeds, fails with an error that is not
|
||||||
|
-// a pre-send network error, or the retry budget runs out.
|
||||||
|
-func lotusRetrySend[T any](log zerolog.Logger, files []*discordgo.File, send func() (T, error)) (T, error) {
|
||||||
|
+// retryable, or the retry budget runs out.
|
||||||
|
+//
|
||||||
|
+// Pre-send network errors are always retried. Ambiguous errors (see
|
||||||
|
+// isAmbiguousSendError) are retried only when checkDelivered is set: it is
|
||||||
|
+// called first (wait=true lets it wait briefly for evidence) and, if it finds
|
||||||
|
+// that the message did reach Discord, its result is returned as a success
|
||||||
|
+// instead of sending again. It is called again with wait=false just before
|
||||||
|
+// each resend.
|
||||||
|
+func lotusRetrySend[T any](log zerolog.Logger, files []*discordgo.File, send func() (T, error), checkDelivered func(wait bool) (T, bool)) (T, error) {
|
||||||
|
res, err := send()
|
||||||
|
- for attempt := 0; attempt < len(lotusSendRetryDelays) && isPreSendNetworkError(err); attempt++ {
|
||||||
|
+ for attempt := 0; attempt < len(lotusSendRetryDelays); attempt++ {
|
||||||
|
+ switch {
|
||||||
|
+ case isPreSendNetworkError(err):
|
||||||
|
+ case checkDelivered != nil && isAmbiguousSendError(err):
|
||||||
|
+ if delivered, ok := checkDelivered(true); ok {
|
||||||
|
+ log.Info().Err(err).Int("attempts", attempt+1).
|
||||||
|
+ Msg("[lotus] Discord send errored but the message was delivered, not resending")
|
||||||
|
+ return delivered, nil
|
||||||
|
+ }
|
||||||
|
+ default:
|
||||||
|
+ return res, err
|
||||||
|
+ }
|
||||||
|
delay := lotusSendRetryDelays[attempt]
|
||||||
|
log.Warn().Err(err).
|
||||||
|
Int("attempt", attempt+1).
|
||||||
|
Dur("retry_in", delay).
|
||||||
|
- Msg("[lotus] Discord send failed before reaching Discord, retrying")
|
||||||
|
+ Msg("[lotus] Discord send failed and the message was not delivered, retrying")
|
||||||
|
lotusSleep(delay)
|
||||||
|
+ if checkDelivered != nil {
|
||||||
|
+ // A late echo of an earlier attempt can land during the backoff.
|
||||||
|
+ if delivered, ok := checkDelivered(false); ok {
|
||||||
|
+ log.Info().Int("attempts", attempt+1).
|
||||||
|
+ Msg("[lotus] earlier Discord send turned out to be delivered, not resending")
|
||||||
|
+ return delivered, nil
|
||||||
|
+ }
|
||||||
|
+ }
|
||||||
|
lotusRewindFiles(files)
|
||||||
|
res, err = send()
|
||||||
|
if err == nil {
|
||||||
|
diff --git a/lotus_retry_test.go b/lotus_retry_test.go
|
||||||
|
index efa262e..e35585b 100644
|
||||||
|
--- a/lotus_retry_test.go
|
||||||
|
+++ b/lotus_retry_test.go
|
||||||
|
@@ -68,7 +68,7 @@ func TestRetrySendRecoversAndRewindsFiles(t *testing.T) {
|
||||||
|
return nil, urlErr(tlsTimeout{})
|
||||||
|
}
|
||||||
|
return &discordgo.Message{ID: "42"}, nil
|
||||||
|
- })
|
||||||
|
+ }, nil)
|
||||||
|
if err != nil || msg == nil || msg.ID != "42" {
|
||||||
|
t.Fatalf("got msg=%v err=%v", msg, err)
|
||||||
|
}
|
||||||
|
@@ -86,7 +86,7 @@ func TestRetrySendDoesNotRetryAfterSend(t *testing.T) {
|
||||||
|
_, err := lotusRetrySend(zerolog.Nop(), nil, func() (*discordgo.Message, error) {
|
||||||
|
calls++
|
||||||
|
return nil, urlErr(&net.OpError{Op: "read", Net: "tcp", Err: errors.New("connection reset by peer")})
|
||||||
|
- })
|
||||||
|
+ }, nil)
|
||||||
|
if err == nil || calls != 1 {
|
||||||
|
t.Fatalf("calls=%d err=%v, want exactly one attempt", calls, err)
|
||||||
|
}
|
||||||
|
@@ -98,7 +98,7 @@ func TestRetrySendGivesUpAfterBudget(t *testing.T) {
|
||||||
|
_, err := lotusRetrySend(zerolog.Nop(), nil, func() (*discordgo.Message, error) {
|
||||||
|
calls++
|
||||||
|
return nil, urlErr(tlsTimeout{})
|
||||||
|
- })
|
||||||
|
+ }, nil)
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("expected error after budget")
|
||||||
|
}
|
||||||
|
diff --git a/portal.go b/portal.go
|
||||||
|
index cc6da0d..57ba7f9 100644
|
||||||
|
--- a/portal.go
|
||||||
|
+++ b/portal.go
|
||||||
|
@@ -1748,9 +1748,18 @@ func (portal *Portal) handleMatrixMessage(sender *User, evt *event.Event) {
|
||||||
|
if !isWebhookSend {
|
||||||
|
msg, err = lotusRetrySend(sendLog, sendReq.Files, func() (*discordgo.Message, error) {
|
||||||
|
return sess.ChannelMessageSendComplex(channelID, &sendReq, portal.RefererOptIfUser(sess, threadID)...)
|
||||||
|
- })
|
||||||
|
+ }, nil)
|
||||||
|
} else {
|
||||||
|
username, avatarURL := portal.getRelayUserMeta(sender)
|
||||||
|
+ // [lotus] watch for the gateway echo so an ambiguous failure can be
|
||||||
|
+ // checked instead of resent blindly (see lotus_echo.go)
|
||||||
|
+ echoChannel := channelID
|
||||||
|
+ if threadID != "" {
|
||||||
|
+ echoChannel = threadID
|
||||||
|
+ }
|
||||||
|
+ checkEcho, echoDone := lotusExpectEcho(echoChannel,
|
||||||
|
+ lotusWebhookEchoMatcher(portal.RelayWebhookID, sendReq.Content, len(sendReq.Files), time.Now()))
|
||||||
|
+ defer echoDone()
|
||||||
|
msg, err = lotusRetrySend(sendLog, sendReq.Files, func() (*discordgo.Message, error) {
|
||||||
|
return relayClient.WebhookThreadExecute(portal.RelayWebhookID, portal.RelayWebhookSecret, true, threadID, &discordgo.WebhookParams{
|
||||||
|
Content: sendReq.Content,
|
||||||
|
@@ -1761,7 +1770,7 @@ func (portal *Portal) handleMatrixMessage(sender *User, evt *event.Event) {
|
||||||
|
Embeds: sendReq.Embeds,
|
||||||
|
AllowedMentions: sendReq.AllowedMentions,
|
||||||
|
})
|
||||||
|
- })
|
||||||
|
+ }, checkEcho)
|
||||||
|
}
|
||||||
|
sender.handlePossible40002(err)
|
||||||
|
go portal.sendMessageMetrics(evt, err, "Error sending")
|
||||||
|
diff --git a/user.go b/user.go
|
||||||
|
index 8c0d6ec..16cd8c8 100644
|
||||||
|
--- a/user.go
|
||||||
|
+++ b/user.go
|
||||||
|
@@ -704,6 +704,7 @@ func (user *User) eventHandler(rawEvt any) {
|
||||||
|
case *discordgo.RelationshipUpdate:
|
||||||
|
user.relationshipUpdateHandler(evt)
|
||||||
|
case *discordgo.MessageCreate:
|
||||||
|
+ lotusNoteGatewayMessage(evt.Message) // [lotus] see lotus_echo.go
|
||||||
|
user.pushPortalMessage(evt, "message create", evt.ChannelID, evt.GuildID)
|
||||||
|
case *discordgo.MessageDelete:
|
||||||
|
user.pushPortalMessage(evt, "message delete", evt.ChannelID, evt.GuildID)
|
||||||
+47
@@ -0,0 +1,47 @@
|
|||||||
|
diff --git a/lotus_member.go b/lotus_member.go
|
||||||
|
new file mode 100644
|
||||||
|
index 0000000..c9a8e95
|
||||||
|
--- /dev/null
|
||||||
|
+++ b/lotus_member.go
|
||||||
|
@@ -0,0 +1,19 @@
|
||||||
|
+package main
|
||||||
|
+
|
||||||
|
+import (
|
||||||
|
+ "maunium.net/go/mautrix/event"
|
||||||
|
+ "maunium.net/go/mautrix/id"
|
||||||
|
+)
|
||||||
|
+
|
||||||
|
+// lotusMember returns a room member's display name and avatar for relayed
|
||||||
|
+// messages. The bridge normally reads them from its own database copy of room
|
||||||
|
+// state; when that read fails (e.g. the database is unreachable) or the user
|
||||||
|
+// isn't cached yet, it asks the homeserver instead of falling back to the raw
|
||||||
|
+// Matrix ID with no avatar.
|
||||||
|
+func (portal *Portal) lotusMember(userID id.UserID) *event.MemberEventContent {
|
||||||
|
+ member := portal.MainIntent().Member(portal.MXID, userID)
|
||||||
|
+ if member == nil {
|
||||||
|
+ return &event.MemberEventContent{}
|
||||||
|
+ }
|
||||||
|
+ return member
|
||||||
|
+}
|
||||||
|
diff --git a/portal.go b/portal.go
|
||||||
|
index 57ba7f9..17ed1da 100644
|
||||||
|
--- a/portal.go
|
||||||
|
+++ b/portal.go
|
||||||
|
@@ -1450,7 +1450,7 @@ func (br *DiscordBridge) makeMediaProxyURL(mxc id.ContentURI) string {
|
||||||
|
}
|
||||||
|
|
||||||
|
func (portal *Portal) getRelayUserMeta(sender *User) (name, avatarURL string) {
|
||||||
|
- member := portal.bridge.StateStore.GetMember(portal.MXID, sender.MXID)
|
||||||
|
+ member := portal.lotusMember(sender.MXID)
|
||||||
|
name = member.Displayname
|
||||||
|
if name == "" {
|
||||||
|
name = sender.MXID.String()
|
||||||
|
@@ -1502,7 +1502,7 @@ func (portal *Portal) convertReplyMessageToEmbed(eventID id.EventID, url string)
|
||||||
|
targetUser = fmt.Sprintf("<@%s>", puppet.ID)
|
||||||
|
} else if user := portal.bridge.GetUserByMXID(evt.Sender); user != nil && user.DiscordID != "" {
|
||||||
|
targetUser = fmt.Sprintf("<@%s>", user.DiscordID)
|
||||||
|
- } else if member := portal.bridge.StateStore.GetMember(portal.MXID, evt.Sender); member != nil && member.Displayname != "" {
|
||||||
|
+ } else if member := portal.lotusMember(evt.Sender); member.Displayname != "" {
|
||||||
|
targetUser = member.Displayname
|
||||||
|
} else {
|
||||||
|
targetUser = evt.Sender.String()
|
||||||
@@ -1,37 +0,0 @@
|
|||||||
var ev = data.eventType || 'Unknown';
|
|
||||||
if (ev === 'Test') {
|
|
||||||
result = { version: 'v2', plain: '🧪 Lidarr: Connection test successful', msgtype: 'm.notice' };
|
|
||||||
} else {
|
|
||||||
var artist = (data.artist && data.artist.name) || 'Unknown Artist';
|
|
||||||
var albums = data.albums || (data.album ? [data.album] : []);
|
|
||||||
var albumStr = albums.map(function(a){ return a.title || ''; }).filter(Boolean).join(', ');
|
|
||||||
var quality = (data.release && data.release.quality) || (data.trackFiles && data.trackFiles[0] && data.trackFiles[0].quality) || '';
|
|
||||||
var releaseGroup = (data.release && data.release.releaseGroup) || '';
|
|
||||||
var client = data.downloadClient || '';
|
|
||||||
var upgrade = data.isUpgrade ? ' \u2191upgrade' : '';
|
|
||||||
var healthMsg = data.message || '';
|
|
||||||
var healthWiki = data.wikiUrl || '';
|
|
||||||
var prevVer = data.previousVersion || '';
|
|
||||||
var newVer = data.newVersion || '';
|
|
||||||
var emojiMap = { 'Grab':'📥','Download':'✅','Rename':'✏️','ArtistAdd':'➕','ArtistDelete':'🗑️','AlbumAdd':'➕','AlbumDelete':'🗑️','TrackFileDelete':'🗑️','HealthIssue':'⚠️','HealthRestored':'💚','ApplicationUpdate':'🔄' };
|
|
||||||
var emoji = emojiMap[ev] || '🎵';
|
|
||||||
var plain, html;
|
|
||||||
if (ev === 'HealthIssue' || ev === 'HealthRestored') {
|
|
||||||
plain = emoji + ' Lidarr ' + ev + ': ' + healthMsg + (healthWiki ? '\n' + healthWiki : '');
|
|
||||||
html = '<b>' + emoji + ' Lidarr ' + ev + '</b>: ' + healthMsg + (healthWiki ? '<br><a href="' + healthWiki + '">Wiki</a>' : '');
|
|
||||||
} else if (ev === 'ApplicationUpdate') {
|
|
||||||
plain = emoji + ' Lidarr updated: ' + prevVer + ' \u2192 ' + newVer;
|
|
||||||
html = '<b>' + emoji + ' Lidarr updated</b>: ' + prevVer + ' \u2192 ' + newVer;
|
|
||||||
} else if (ev === 'ArtistAdd' || ev === 'ArtistDelete') {
|
|
||||||
plain = emoji + ' Lidarr ' + ev + ': ' + artist;
|
|
||||||
html = '<b>' + emoji + ' Lidarr ' + ev + '</b>: ' + artist;
|
|
||||||
} else {
|
|
||||||
var albumPart = albumStr ? ' \u2014 ' + albumStr : '';
|
|
||||||
var qualPart = quality ? ' [' + quality + ']' : '';
|
|
||||||
var groupPart = releaseGroup ? ' {' + releaseGroup + '}' : '';
|
|
||||||
var clientPart = client ? ' via ' + client : '';
|
|
||||||
plain = emoji + ' Lidarr ' + ev + ': ' + artist + albumPart + qualPart + groupPart + upgrade + clientPart;
|
|
||||||
html = '<b>' + emoji + ' Lidarr ' + ev + '</b>: ' + artist + (albumStr ? ' \u2014 <i>' + albumStr + '</i>' : '') + qualPart + groupPart + upgrade + clientPart;
|
|
||||||
}
|
|
||||||
result = { version: 'v2', plain: plain, html: html, msgtype: 'm.notice' };
|
|
||||||
}
|
|
||||||
@@ -1616,7 +1616,7 @@
|
|||||||
"cells": [
|
"cells": [
|
||||||
{
|
{
|
||||||
"mark": "part",
|
"mark": "part",
|
||||||
"note": "OS notifications while the app is open; no background push yet"
|
"note": "OS notifications while the web or desktop app is open (the desktop app keeps running in the tray); background web push is not planned, so use Element X or FluffyChat on phones"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"mark": "part",
|
"mark": "part",
|
||||||
|
|||||||
+1
-1
@@ -1342,7 +1342,7 @@ Client comparison last reviewed <time datetime="2026-09-26">September 26, 2026</
|
|||||||
</tr>
|
</tr>
|
||||||
<tr>
|
<tr>
|
||||||
<td>Push notifications</td>
|
<td>Push notifications</td>
|
||||||
<td class="ours"><span class="part">~</span><small>OS notifications while the app is open; no background push yet</small></td>
|
<td class="ours"><span class="part">~</span><small>OS notifications while the web or desktop app is open (the desktop app keeps running in the tray); background web push is not planned, so use Element X or FluffyChat on phones</small></td>
|
||||||
<td><span class="part">~</span><small>only while the tab/app is open; optional email</small></td>
|
<td><span class="part">~</span><small>only while the tab/app is open; optional email</small></td>
|
||||||
<td><span class="yes">✓</span></td>
|
<td><span class="yes">✓</span></td>
|
||||||
<td><span class="yes">✓</span></td>
|
<td><span class="yes">✓</span></td>
|
||||||
|
|||||||
+5
-5
@@ -27,11 +27,11 @@ Matrix bot and server improvements for the Lotus Guild homeserver (`matrix.lotus
|
|||||||
|
|
||||||
| Service | Host | IP | LXC | Notes |
|
| Service | Host | IP | LXC | Notes |
|
||||||
|---------|------|-----|-----|-------|
|
|---------|------|-----|-----|-------|
|
||||||
| Synapse | micro1 | 10.10.10.29 | 151 | Homeserver + coturn + LiveKit |
|
| Synapse | HA (floats) | 10.10.10.29 | 151 | Homeserver + coturn + LiveKit |
|
||||||
| PostgreSQL 17 | micro1 | 10.10.10.44 | 109 | Synapse database backend |
|
| PostgreSQL 17 | HA (floats) | 10.10.10.44 | 109 | Synapse database backend |
|
||||||
| NPM | large1 | 10.10.10.27 | 139 | Reverse proxy + landing page |
|
| NPM | HA (floats) | 10.10.10.27 | 139 | Reverse proxy + landing page |
|
||||||
| Authelia | compute-storage-01 | 10.10.10.36 | 167 | SSO/OIDC provider |
|
| Authelia | HA (floats) | 10.10.10.36 | 167 | SSO/OIDC provider |
|
||||||
| LLDAP | large1 | 10.10.10.39 | 147 | LDAP user directory |
|
| LLDAP | HA (floats) | 10.10.10.39 | 147 | LDAP user directory |
|
||||||
|
|
||||||
**Key paths on Synapse LXC (10.10.10.29):**
|
**Key paths on Synapse LXC (10.10.10.29):**
|
||||||
- Synapse config: `/etc/matrix-synapse/homeserver.yaml`
|
- Synapse config: `/etc/matrix-synapse/homeserver.yaml`
|
||||||
|
|||||||
+38
-17
@@ -120,8 +120,19 @@ def is_elevated(client: AsyncClient, room_id: str, user_id: str, min_level: int
|
|||||||
# ==================== COMMANDS ====================
|
# ==================== COMMANDS ====================
|
||||||
|
|
||||||
|
|
||||||
@command("help", "Show all available commands")
|
@command("help", "Show all commands, or details for one (!help <command>)")
|
||||||
async def cmd_help(client: AsyncClient, room_id: str, sender: str, args: str):
|
async def cmd_help(client: AsyncClient, room_id: str, sender: str, args: str):
|
||||||
|
# Compact on purpose: the Discord bridge drops messages over 2000 characters.
|
||||||
|
query = args.strip().lstrip(BOT_PREFIX).lower()
|
||||||
|
if query:
|
||||||
|
entry = COMMANDS.get(query)
|
||||||
|
if entry is None:
|
||||||
|
await send_text(client, room_id, f"Unknown command: {BOT_PREFIX}{query}. Try {BOT_PREFIX}help for the list.")
|
||||||
|
return
|
||||||
|
_, desc = entry
|
||||||
|
await send_html(client, room_id, f"{BOT_PREFIX}{query} — {desc}", f"<strong>{BOT_PREFIX}{query}</strong> — {desc}")
|
||||||
|
return
|
||||||
|
|
||||||
elevated = is_elevated(client, room_id, sender)
|
elevated = is_elevated(client, room_id, sender)
|
||||||
categories = [
|
categories = [
|
||||||
("🤖 AI / Fun", ["ask", "fortune", "8ball", "roast", "story", "debate"]),
|
("🤖 AI / Fun", ["ask", "fortune", "8ball", "roast", "story", "debate"]),
|
||||||
@@ -148,18 +159,17 @@ async def cmd_help(client: AsyncClient, room_id: str, sender: str, args: str):
|
|||||||
"setpl", "kick", "purge", "members", "whois", "announce", "syncspace",
|
"setpl", "kick", "purge", "members", "whois", "announce", "syncspace",
|
||||||
]))
|
]))
|
||||||
|
|
||||||
plain_lines = ["LotusBot Commands"]
|
plain_lines = [f"LotusBot commands ({BOT_PREFIX}help <command> for details)"]
|
||||||
html_parts = ['<font color="#a855f7"><strong>🌸 LotusBot — Commands</strong></font>']
|
html_parts = [
|
||||||
|
'<font color="#a855f7"><strong>🌸 LotusBot — Commands</strong></font>'
|
||||||
|
f"<br><sup><em>{BOT_PREFIX}help <command> for details</em></sup>"
|
||||||
|
]
|
||||||
for cat_name, cmd_names in categories:
|
for cat_name, cmd_names in categories:
|
||||||
plain_lines.append(f"\n{cat_name}")
|
names = [f"{BOT_PREFIX}{name}" for name in cmd_names if name in COMMANDS]
|
||||||
html_parts.append(f"<br><strong>{cat_name}</strong><ul>")
|
if not names:
|
||||||
for name in cmd_names:
|
continue
|
||||||
if name in COMMANDS:
|
plain_lines.append(f"{cat_name}: " + " ".join(names))
|
||||||
_, desc = COMMANDS[name]
|
html_parts.append(f"<br><strong>{cat_name}:</strong> " + " ".join(f"<code>{n}</code>" for n in names))
|
||||||
plain_lines.append(f" {BOT_PREFIX}{name} — {desc}")
|
|
||||||
html_parts.append(f"<li><strong>{BOT_PREFIX}{name}</strong> — {desc}</li>")
|
|
||||||
html_parts.append("</ul>")
|
|
||||||
|
|
||||||
await send_html(client, room_id, "\n".join(plain_lines), "".join(html_parts))
|
await send_html(client, room_id, "\n".join(plain_lines), "".join(html_parts))
|
||||||
|
|
||||||
@@ -1313,6 +1323,11 @@ async def cmd_minecraft(client: AsyncClient, room_id: str, sender: str, args: st
|
|||||||
await send_text(client, room_id, "Minecraft server is not configured.")
|
await send_text(client, room_id, "Minecraft server is not configured.")
|
||||||
return
|
return
|
||||||
|
|
||||||
|
remaining = check_cooldown(sender, "minecraft", 60)
|
||||||
|
if remaining:
|
||||||
|
await send_text(client, room_id, f"Command on cooldown. Try again in {remaining}s.")
|
||||||
|
return
|
||||||
|
|
||||||
await send_text(client, room_id, f"Whitelisting {username}...")
|
await send_text(client, room_id, f"Whitelisting {username}...")
|
||||||
|
|
||||||
try:
|
try:
|
||||||
@@ -1327,7 +1342,11 @@ async def cmd_minecraft(client: AsyncClient, room_id: str, sender: str, args: st
|
|||||||
|
|
||||||
loop = asyncio.get_running_loop()
|
loop = asyncio.get_running_loop()
|
||||||
response = await asyncio.wait_for(loop.run_in_executor(None, _rcon), timeout=RCON_TIMEOUT)
|
response = await asyncio.wait_for(loop.run_in_executor(None, _rcon), timeout=RCON_TIMEOUT)
|
||||||
logger.info(f"RCON response: {response}")
|
logger.info(f"Minecraft whitelist: sender={sender} room={room_id} username={username} response={response!r}")
|
||||||
|
|
||||||
|
if "does not exist" in response.lower() or "unknown player" in response.lower():
|
||||||
|
await send_text(client, room_id, f"No Minecraft account named {username} exists. Check the spelling (Java Edition username).")
|
||||||
|
return
|
||||||
|
|
||||||
already = "already whitelisted" in response.lower()
|
already = "already whitelisted" in response.lower()
|
||||||
status_line = (
|
status_line = (
|
||||||
@@ -1336,16 +1355,18 @@ async def cmd_minecraft(client: AsyncClient, room_id: str, sender: str, args: st
|
|||||||
else f"✅ <strong>{username}</strong> is whitelisted and ready to join."
|
else f"✅ <strong>{username}</strong> is whitelisted and ready to join."
|
||||||
)
|
)
|
||||||
plain = (
|
plain = (
|
||||||
f"✿ Minecraft — Lotus SMP ✿\n"
|
f"✿ Lotus Minecraft Server ✿\n"
|
||||||
f"{'Already whitelisted' if already else 'Whitelisted'}: {username}\n"
|
f"{'Already whitelisted' if already else 'Whitelisted'}: {username}\n"
|
||||||
f"Server: minecraft.lotusguild.org"
|
f"Server: minecraft.lotusguild.org\n"
|
||||||
|
f"Modpack: All the Mods 10 (CurseForge), version 8.6"
|
||||||
)
|
)
|
||||||
html = (
|
html = (
|
||||||
f'<font color="#980000"><strong>✿ Minecraft — Lotus SMP ✿</strong></font><br>'
|
f'<font color="#980000"><strong>✿ Lotus Minecraft Server ✿</strong></font><br>'
|
||||||
f"<blockquote>"
|
f"<blockquote>"
|
||||||
f"{status_line}<br>"
|
f"{status_line}<br>"
|
||||||
f'<strong>Server:</strong> <code>minecraft.lotusguild.org</code><br>'
|
f'<strong>Server:</strong> <code>minecraft.lotusguild.org</code><br>'
|
||||||
f"<sup><em>fresh world · hard mode · no takebacks</em></sup>"
|
f'<strong>Modpack:</strong> All the Mods 10 (CurseForge), version <code>8.6</code><br>'
|
||||||
|
f"<sup><em>install the same pack version or the server won't let you in</em></sup>"
|
||||||
f"</blockquote>"
|
f"</blockquote>"
|
||||||
)
|
)
|
||||||
await send_html(client, room_id, plain, html)
|
await send_html(client, room_id, plain, html)
|
||||||
|
|||||||
@@ -0,0 +1,177 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Player count -> status message on the Lotus Minecraft bot.
|
||||||
|
|
||||||
|
Pings the Minecraft server the way the in-game server list does (no RCON, no
|
||||||
|
password) and sets the result as the Matrix status of the account the chat
|
||||||
|
bridge mod logs in as, for example "3 online: Daisybell, Honnehh, Wolf".
|
||||||
|
|
||||||
|
- Credentials: the homeserver and token come from the mod's own config, so there
|
||||||
|
is no extra account or secret. systemd hands this service a private copy.
|
||||||
|
- The mod syncs with set_presence=offline, so it doesn't keep the account online,
|
||||||
|
and Synapse drops an unrefreshed user to offline. So state is re-sent on a timer.
|
||||||
|
- This runs beside the game, not in it, so it can report the server being down.
|
||||||
|
One failed ping is ignored: a busy modded server can miss one.
|
||||||
|
"""
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import socket
|
||||||
|
import struct
|
||||||
|
import time
|
||||||
|
import tomllib
|
||||||
|
import urllib.error
|
||||||
|
import urllib.parse
|
||||||
|
import urllib.request
|
||||||
|
|
||||||
|
log = logging.getLogger("lotus-mc-status")
|
||||||
|
|
||||||
|
INTERVAL = 20 # seconds; Synapse's default limit for this endpoint is one per 10 s
|
||||||
|
PING_TIMEOUT = 8
|
||||||
|
MAX_LEN = 64 # what Cinny's own status field allows
|
||||||
|
FAILS_BEFORE_DOWN = 2
|
||||||
|
OFFLINE = "Server offline"
|
||||||
|
PLAYER_NAME = re.compile(r"[A-Za-z0-9_]{1,16}")
|
||||||
|
|
||||||
|
|
||||||
|
def varint(n: int) -> bytes:
|
||||||
|
out = b""
|
||||||
|
while True:
|
||||||
|
byte = n & 0x7F
|
||||||
|
n >>= 7
|
||||||
|
out += bytes([byte | (0x80 if n else 0)])
|
||||||
|
if not n:
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def read_varint(read) -> int:
|
||||||
|
result = 0
|
||||||
|
for shift in range(0, 35, 7):
|
||||||
|
byte = read(1)[0]
|
||||||
|
result |= (byte & 0x7F) << shift
|
||||||
|
if not byte & 0x80:
|
||||||
|
return result
|
||||||
|
raise ValueError("varint too long")
|
||||||
|
|
||||||
|
|
||||||
|
def parse_status(packet: bytes) -> tuple[int, list[str]]:
|
||||||
|
"""Return (players online, names) from a status response packet."""
|
||||||
|
pos = [0]
|
||||||
|
|
||||||
|
def read(n: int) -> bytes:
|
||||||
|
chunk = packet[pos[0] : pos[0] + n]
|
||||||
|
if len(chunk) < n:
|
||||||
|
raise ValueError("truncated status packet")
|
||||||
|
pos[0] += n
|
||||||
|
return chunk
|
||||||
|
|
||||||
|
if read_varint(read) != 0:
|
||||||
|
raise ValueError("not a status response")
|
||||||
|
players = json.loads(read(read_varint(read)))["players"]
|
||||||
|
return int(players["online"]), [str(p.get("name", "")) for p in players.get("sample") or []]
|
||||||
|
|
||||||
|
|
||||||
|
def ping(host: str, port: int) -> tuple[int, list[str]]:
|
||||||
|
with socket.create_connection((host, port), timeout=PING_TIMEOUT) as sock:
|
||||||
|
addr = host.encode()
|
||||||
|
hello = b"\0" + varint(767) + varint(len(addr)) + addr + struct.pack(">H", port) + varint(1)
|
||||||
|
sock.sendall(varint(len(hello)) + hello + b"\x01\0")
|
||||||
|
|
||||||
|
def read(n: int) -> bytes:
|
||||||
|
buf = b""
|
||||||
|
while len(buf) < n:
|
||||||
|
chunk = sock.recv(n - len(buf))
|
||||||
|
if not chunk:
|
||||||
|
raise ConnectionError("server closed the connection")
|
||||||
|
buf += chunk
|
||||||
|
return buf
|
||||||
|
|
||||||
|
return parse_status(read(read_varint(read)))
|
||||||
|
|
||||||
|
|
||||||
|
def format_status(online: int, names: list[str], max_len: int = MAX_LEN) -> str:
|
||||||
|
"""Count plus as many names as fit. Names are sorted so a re-ordered list
|
||||||
|
doesn't change the status, and anything that isn't a real player name
|
||||||
|
(servers can send placeholders) is dropped and counted under "more"."""
|
||||||
|
if online <= 0:
|
||||||
|
return "Nobody online"
|
||||||
|
head = f"{online} online"
|
||||||
|
real = sorted({n for n in names if PLAYER_NAME.fullmatch(n)}, key=str.casefold)[:online]
|
||||||
|
shown: list[str] = []
|
||||||
|
for name in real:
|
||||||
|
rest = online - len(shown) - 1
|
||||||
|
candidate = f"{head}: {', '.join([*shown, name])}" + (f" +{rest} more" if rest else "")
|
||||||
|
if len(candidate) > max_len:
|
||||||
|
break
|
||||||
|
shown.append(name)
|
||||||
|
if not shown:
|
||||||
|
return head
|
||||||
|
rest = online - len(shown)
|
||||||
|
return f"{head}: {', '.join(shown)}" + (f" +{rest} more" if rest else "")
|
||||||
|
|
||||||
|
|
||||||
|
def read_config(path: str) -> tuple[str, str]:
|
||||||
|
with open(path, "rb") as f:
|
||||||
|
matrix = tomllib.load(f)["matrix"]
|
||||||
|
return matrix["homeserver"].rstrip("/"), matrix["accessToken"]
|
||||||
|
|
||||||
|
|
||||||
|
def api(method: str, url: str, token: str, body: dict | None = None) -> dict:
|
||||||
|
data = json.dumps(body).encode() if body is not None else None
|
||||||
|
req = urllib.request.Request(url, data=data, method=method, headers={
|
||||||
|
"Authorization": f"Bearer {token}",
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
"User-Agent": "lotus-mc-status",
|
||||||
|
})
|
||||||
|
with urllib.request.urlopen(req, timeout=15) as resp:
|
||||||
|
return json.load(resp)
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> None:
|
||||||
|
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s")
|
||||||
|
creds = os.environ.get("CREDENTIALS_DIRECTORY")
|
||||||
|
path = os.path.join(creds, "bridge-config") if creds else os.environ["LOTUS_MC_CONFIG"]
|
||||||
|
host = os.environ["LOTUS_MC_HOST"]
|
||||||
|
port = int(os.environ.get("LOTUS_MC_PORT", "25565"))
|
||||||
|
homeserver, token = read_config(path)
|
||||||
|
|
||||||
|
user_id = api("GET", f"{homeserver}/_matrix/client/v3/account/whoami", token)["user_id"]
|
||||||
|
url = f"{homeserver}/_matrix/client/v3/presence/{urllib.parse.quote(user_id, safe='')}/status"
|
||||||
|
log.info("watching %s:%d for %s", host, port, user_id)
|
||||||
|
|
||||||
|
fails = 0
|
||||||
|
body = None
|
||||||
|
last_error = None
|
||||||
|
last_count = None
|
||||||
|
while True:
|
||||||
|
try:
|
||||||
|
online, names = ping(host, port)
|
||||||
|
fails = 0
|
||||||
|
body = {"presence": "online", "status_msg": format_status(online, names)}
|
||||||
|
if online != last_count:
|
||||||
|
log.info("%d online", online)
|
||||||
|
last_count = online
|
||||||
|
except (OSError, ValueError, KeyError, TypeError) as exc:
|
||||||
|
fails += 1
|
||||||
|
if fails == FAILS_BEFORE_DOWN:
|
||||||
|
log.warning("server not answering: %s", type(exc).__name__)
|
||||||
|
last_count = None
|
||||||
|
if fails >= FAILS_BEFORE_DOWN:
|
||||||
|
body = {"presence": "unavailable", "status_msg": OFFLINE}
|
||||||
|
if body:
|
||||||
|
try:
|
||||||
|
api("PUT", url, token, body)
|
||||||
|
if last_error:
|
||||||
|
log.info("Matrix reachable again")
|
||||||
|
last_error = None
|
||||||
|
except (OSError, ValueError) as exc:
|
||||||
|
# HTTPError and URLError are OSErrors. Their text has no token in it.
|
||||||
|
error = f"HTTP {exc.code}" if isinstance(exc, urllib.error.HTTPError) else type(exc).__name__
|
||||||
|
if error != last_error:
|
||||||
|
log.warning("could not set status: %s", error)
|
||||||
|
last_error = error
|
||||||
|
time.sleep(INTERVAL)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
import json
|
||||||
|
import unittest
|
||||||
|
|
||||||
|
import lotus_mc_status as s
|
||||||
|
|
||||||
|
|
||||||
|
def packet(players: dict) -> bytes:
|
||||||
|
body = json.dumps({"version": {"name": "1.21.1"}, "players": players}).encode()
|
||||||
|
return s.varint(0) + s.varint(len(body)) + body
|
||||||
|
|
||||||
|
|
||||||
|
class FormatStatus(unittest.TestCase):
|
||||||
|
def test_nobody(self):
|
||||||
|
self.assertEqual(s.format_status(0, []), "Nobody online")
|
||||||
|
|
||||||
|
def test_one(self):
|
||||||
|
self.assertEqual(s.format_status(1, ["Honnehh"]), "1 online: Honnehh")
|
||||||
|
|
||||||
|
def test_sorted_regardless_of_server_order(self):
|
||||||
|
self.assertEqual(s.format_status(3, ["b_x", "C", "a"]), "3 online: a, b_x, C")
|
||||||
|
|
||||||
|
def test_long_names_collapse_and_stay_within_the_limit(self):
|
||||||
|
names = [f"Player{i}_abcdefghi"[:16] for i in range(10)]
|
||||||
|
got = s.format_status(10, names)
|
||||||
|
self.assertLessEqual(len(got), s.MAX_LEN)
|
||||||
|
self.assertRegex(got, r"^10 online: .+ \+\d+ more$")
|
||||||
|
shown = got.split(": ")[1].split(" +")[0].split(", ")
|
||||||
|
self.assertEqual(int(got.split("+")[1].split()[0]), 10 - len(shown))
|
||||||
|
|
||||||
|
def test_exact_fit_has_no_more_suffix(self):
|
||||||
|
got = s.format_status(1, ["A" * 16], max_len=len("1 online: ") + 16)
|
||||||
|
self.assertEqual(got, "1 online: " + "A" * 16)
|
||||||
|
|
||||||
|
def test_more_players_than_the_sample(self):
|
||||||
|
self.assertEqual(s.format_status(14, ["a", "b"]), "14 online: a, b +12 more")
|
||||||
|
|
||||||
|
def test_placeholders_are_not_shown_as_players(self):
|
||||||
|
self.assertEqual(s.format_status(2, ["Anonymous Player", "a"]), "2 online: a +1 more")
|
||||||
|
self.assertEqual(s.format_status(1, ["§cinjected name"]), "1 online")
|
||||||
|
|
||||||
|
def test_count_only_when_nothing_fits(self):
|
||||||
|
self.assertEqual(s.format_status(2, ["abcdefgh"], max_len=9), "2 online")
|
||||||
|
|
||||||
|
def test_duplicates_and_stale_extras_do_not_overcount(self):
|
||||||
|
self.assertEqual(s.format_status(1, ["a", "a", "b"]), "1 online: a")
|
||||||
|
|
||||||
|
|
||||||
|
class ParseStatus(unittest.TestCase):
|
||||||
|
def test_with_sample(self):
|
||||||
|
p = packet({"max": 20, "online": 2, "sample": [{"name": "a", "id": "x"}, {"name": "b", "id": "y"}]})
|
||||||
|
self.assertEqual(s.parse_status(p), (2, ["a", "b"]))
|
||||||
|
|
||||||
|
def test_without_sample(self):
|
||||||
|
self.assertEqual(s.parse_status(packet({"max": 20, "online": 0})), (0, []))
|
||||||
|
|
||||||
|
def test_rejects_other_packets_and_truncation(self):
|
||||||
|
with self.assertRaises(ValueError):
|
||||||
|
s.parse_status(s.varint(1) + b"xx")
|
||||||
|
with self.assertRaises(ValueError):
|
||||||
|
s.parse_status(packet({"max": 20, "online": 0})[:-3])
|
||||||
|
|
||||||
|
def test_varint_round_trip(self):
|
||||||
|
for n in (0, 1, 127, 128, 300, 6087, 2097151):
|
||||||
|
data = iter([s.varint(n)])
|
||||||
|
buf = next(data)
|
||||||
|
pos = [0]
|
||||||
|
|
||||||
|
def read(k, buf=buf, pos=pos):
|
||||||
|
out = buf[pos[0] : pos[0] + k]
|
||||||
|
pos[0] += k
|
||||||
|
return out
|
||||||
|
|
||||||
|
self.assertEqual(s.read_varint(read), n)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
# Install or update the now-playing service (cinny #491) on LXC 151.
|
||||||
|
# Run with this repo's main branch pulled to /opt/matrix-config:
|
||||||
|
# bash /opt/matrix-config/now-playing/install.sh
|
||||||
|
# First install: put the Navidrome login in /etc/lotus-now-playing/env first
|
||||||
|
# (NAVIDROME_USER=lotus-nowplaying / NAVIDROME_PASSWORD=...), mode 640 root:lotus-now-playing.
|
||||||
|
# Optional /etc/lotus-now-playing/users.json maps Matrix IDs whose SSO link has no
|
||||||
|
# email to their SSO username, e.g. {"@bigmanjeff:matrix.lotusguild.org": "jeff"}.
|
||||||
|
# Neither file is kept in this (public) repo. Safe to re-run.
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
REPO=/opt/matrix-config
|
||||||
|
CONF=/etc/lotus-now-playing
|
||||||
|
|
||||||
|
id lotus-now-playing >/dev/null 2>&1 ||
|
||||||
|
useradd --system --no-create-home --home-dir /var/lib/lotus-now-playing --shell /usr/sbin/nologin lotus-now-playing
|
||||||
|
install -d -m750 -o root -g lotus-now-playing "$CONF"
|
||||||
|
install -D -m644 "$REPO/now-playing/lotus_now_playing.py" /opt/lotus-now-playing/lotus_now_playing.py
|
||||||
|
|
||||||
|
if [ ! -f "$CONF/env" ]; then
|
||||||
|
echo "missing $CONF/env (NAVIDROME_USER / NAVIDROME_PASSWORD); create it and re-run" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
chown root:lotus-now-playing "$CONF/env"
|
||||||
|
chmod 640 "$CONF/env"
|
||||||
|
if [ -f "$CONF/users.json" ]; then
|
||||||
|
chown root:lotus-now-playing "$CONF/users.json"
|
||||||
|
chmod 640 "$CONF/users.json"
|
||||||
|
fi
|
||||||
|
|
||||||
|
install -m644 "$REPO/systemd/lotus-now-playing.service" /etc/systemd/system/lotus-now-playing.service
|
||||||
|
systemctl daemon-reload
|
||||||
|
systemctl enable lotus-now-playing >/dev/null
|
||||||
|
systemctl restart lotus-now-playing
|
||||||
|
sleep 2
|
||||||
|
systemctl --no-pager --lines=5 status lotus-now-playing
|
||||||
|
curl -fsS http://127.0.0.1:8072/healthz && echo " (healthy)"
|
||||||
@@ -0,0 +1,493 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Now playing (Navidrome) -> Lotus Chat "Listening to" cards. [cinny #491]
|
||||||
|
|
||||||
|
Navidrome is the scrobbling master: every play, whether from Dropped Needle or
|
||||||
|
any Subsonic app, shows up in its `getNowPlaying` under the listener's own
|
||||||
|
username, which is their SSO (LLDAP) username. This service polls that list and
|
||||||
|
serves it to Lotus Chat for users who opted in, keyed by Matrix user ID.
|
||||||
|
|
||||||
|
- Who is asking: Lotus Chat sends a Matrix OpenID token (Authorization: Bearer).
|
||||||
|
It is checked against Synapse's /_matrix/federation/v1/openid/userinfo, so
|
||||||
|
only signed-in users of this homeserver can read anything.
|
||||||
|
- Matrix user -> SSO username: an override file first (accounts whose SSO link
|
||||||
|
carries no email), then the Synapse admin API (email <name>@<domain>, or a
|
||||||
|
legacy external ID that is the plain username).
|
||||||
|
- Opt-in: off by default, stored here in STATE_DIR/state.json.
|
||||||
|
- Cover art is proxied only for covers that an opted-in user is playing right
|
||||||
|
now, so the endpoint can't be used to browse the library.
|
||||||
|
|
||||||
|
Track titles, artists and tokens are never logged.
|
||||||
|
"""
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import secrets
|
||||||
|
import tempfile
|
||||||
|
import threading
|
||||||
|
import time
|
||||||
|
import urllib.error
|
||||||
|
import urllib.parse
|
||||||
|
import urllib.request
|
||||||
|
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||||
|
|
||||||
|
log = logging.getLogger("lotus-now-playing")
|
||||||
|
|
||||||
|
PREFIX = "/now-playing/v1"
|
||||||
|
MAX_IDS = 50
|
||||||
|
SUBSONIC_CLIENT = "lotus-now-playing"
|
||||||
|
SUBSONIC_VERSION = "1.16.1"
|
||||||
|
# Navidrome drops a session a while after the last report, so an entry older
|
||||||
|
# than this (no position updates, not paused) is treated as stale.
|
||||||
|
STALE_MINUTES = 30
|
||||||
|
COVER_SIZES = (64, 128, 256, 512)
|
||||||
|
UUID_RE = re.compile(r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}")
|
||||||
|
|
||||||
|
|
||||||
|
# --- pure helpers (unit tested) ----------------------------------------------
|
||||||
|
|
||||||
|
def parse_now_playing(payload, ignore_users=()):
|
||||||
|
"""getNowPlaying JSON -> {username: entry}. Keeps the most recent session per user."""
|
||||||
|
resp = (payload or {}).get("subsonic-response") or {}
|
||||||
|
if resp.get("status") != "ok":
|
||||||
|
raise ValueError((resp.get("error") or {}).get("message") or "getNowPlaying failed")
|
||||||
|
entries = (resp.get("nowPlaying") or {}).get("entry") or []
|
||||||
|
if isinstance(entries, dict):
|
||||||
|
entries = [entries]
|
||||||
|
out = {}
|
||||||
|
for e in entries:
|
||||||
|
user = (e.get("username") or "").strip()
|
||||||
|
if not user or user in ignore_users:
|
||||||
|
continue
|
||||||
|
state = (e.get("state") or "playing").lower()
|
||||||
|
if state not in ("playing", "paused"):
|
||||||
|
continue
|
||||||
|
minutes = int(e.get("minutesAgo") or 0)
|
||||||
|
if state == "playing" and minutes > STALE_MINUTES and not e.get("positionMs"):
|
||||||
|
continue
|
||||||
|
entry = {
|
||||||
|
"title": e.get("title") or "",
|
||||||
|
"artist": e.get("displayArtist") or e.get("artist") or "",
|
||||||
|
"album": e.get("album") or "",
|
||||||
|
"durationS": int(e.get("duration") or 0),
|
||||||
|
"positionMs": int(e.get("positionMs") or 0),
|
||||||
|
"state": state,
|
||||||
|
"player": e.get("playerName") or "",
|
||||||
|
"coverArt": e.get("coverArt") or "",
|
||||||
|
"minutesAgo": minutes,
|
||||||
|
}
|
||||||
|
if not entry["title"]:
|
||||||
|
continue
|
||||||
|
prev = out.get(user)
|
||||||
|
if prev is None or minutes < prev["minutesAgo"]:
|
||||||
|
out[user] = entry
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def username_from_admin_user(user, email_domain):
|
||||||
|
"""Synapse admin v2 user JSON -> SSO username, or None."""
|
||||||
|
for ext in user.get("external_ids") or []:
|
||||||
|
provider = ext.get("auth_provider") or ""
|
||||||
|
ext_id = ext.get("external_id") or ""
|
||||||
|
# One legacy link stores the plain username instead of Authelia's opaque ID.
|
||||||
|
if (provider.startswith("http") and re.fullmatch(r"[a-z0-9._-]+", ext_id)
|
||||||
|
and not UUID_RE.fullmatch(ext_id)):
|
||||||
|
return ext_id
|
||||||
|
suffix = "@" + email_domain.lower()
|
||||||
|
for tp in user.get("threepids") or []:
|
||||||
|
addr = (tp.get("address") or "").strip().lower()
|
||||||
|
if tp.get("medium") == "email" and addr.endswith(suffix):
|
||||||
|
local = addr[: -len(suffix)]
|
||||||
|
if re.fullmatch(r"[a-z0-9._-]+", local):
|
||||||
|
return local
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def public_entry(entry, now_ms):
|
||||||
|
"""What Lotus Chat gets for one listener."""
|
||||||
|
out = {k: entry[k] for k in ("title", "artist", "album", "durationS", "positionMs", "state", "player")}
|
||||||
|
out["updatedAt"] = now_ms
|
||||||
|
out["cover"] = f"{PREFIX}/cover/{urllib.parse.quote(entry['coverArt'], safe='')}" if entry.get("coverArt") else None
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def parse_ids(raw, server_name):
|
||||||
|
ids = []
|
||||||
|
for part in (raw or "").split(","):
|
||||||
|
part = part.strip()
|
||||||
|
if part.startswith("@") and part.endswith(":" + server_name) and part not in ids:
|
||||||
|
ids.append(part)
|
||||||
|
return ids[:MAX_IDS]
|
||||||
|
|
||||||
|
|
||||||
|
# --- stateful pieces ---------------------------------------------------------
|
||||||
|
|
||||||
|
class OptIns:
|
||||||
|
"""{mxid: True} persisted atomically."""
|
||||||
|
|
||||||
|
def __init__(self, path):
|
||||||
|
self.path = path
|
||||||
|
self.lock = threading.Lock()
|
||||||
|
self.data = {}
|
||||||
|
try:
|
||||||
|
with open(path) as f:
|
||||||
|
loaded = json.load(f)
|
||||||
|
self.data = {k: True for k, v in loaded.items() if v is True}
|
||||||
|
except FileNotFoundError:
|
||||||
|
pass
|
||||||
|
except (OSError, ValueError) as exc:
|
||||||
|
log.error("could not read %s: %s", path, exc)
|
||||||
|
|
||||||
|
def get(self, mxid):
|
||||||
|
with self.lock:
|
||||||
|
return self.data.get(mxid, False)
|
||||||
|
|
||||||
|
def all(self):
|
||||||
|
with self.lock:
|
||||||
|
return list(self.data)
|
||||||
|
|
||||||
|
def set(self, mxid, share):
|
||||||
|
with self.lock:
|
||||||
|
if share:
|
||||||
|
self.data[mxid] = True
|
||||||
|
else:
|
||||||
|
self.data.pop(mxid, None)
|
||||||
|
snapshot = dict(self.data)
|
||||||
|
d = os.path.dirname(self.path) or "."
|
||||||
|
fd, tmp = tempfile.mkstemp(dir=d, prefix=".state-")
|
||||||
|
try:
|
||||||
|
with os.fdopen(fd, "w") as f:
|
||||||
|
json.dump(snapshot, f, indent=1, sort_keys=True)
|
||||||
|
os.replace(tmp, self.path)
|
||||||
|
except BaseException:
|
||||||
|
try:
|
||||||
|
os.unlink(tmp)
|
||||||
|
except OSError:
|
||||||
|
pass
|
||||||
|
raise
|
||||||
|
|
||||||
|
|
||||||
|
class TTLCache:
|
||||||
|
def __init__(self, max_items=2000):
|
||||||
|
self.lock = threading.Lock()
|
||||||
|
self.items = {}
|
||||||
|
self.max_items = max_items
|
||||||
|
|
||||||
|
def get(self, key, now=None):
|
||||||
|
now = time.monotonic() if now is None else now
|
||||||
|
with self.lock:
|
||||||
|
hit = self.items.get(key)
|
||||||
|
if hit and hit[1] > now:
|
||||||
|
return hit[0], True
|
||||||
|
self.items.pop(key, None)
|
||||||
|
return None, False
|
||||||
|
|
||||||
|
def put(self, key, value, ttl, now=None):
|
||||||
|
now = time.monotonic() if now is None else now
|
||||||
|
with self.lock:
|
||||||
|
if len(self.items) >= self.max_items:
|
||||||
|
for k in [k for k, (_, exp) in self.items.items() if exp <= now] or list(self.items)[:100]:
|
||||||
|
self.items.pop(k, None)
|
||||||
|
self.items[key] = (value, now + ttl)
|
||||||
|
|
||||||
|
|
||||||
|
class Service:
|
||||||
|
def __init__(self, cfg, http_get=None):
|
||||||
|
self.cfg = cfg
|
||||||
|
self.http_get = http_get or _http_get
|
||||||
|
self.optins = OptIns(os.path.join(cfg["state_dir"], "state.json"))
|
||||||
|
self.tokens = TTLCache()
|
||||||
|
self.users = TTLCache()
|
||||||
|
self.lock = threading.Lock()
|
||||||
|
self.playing = {}
|
||||||
|
self.overrides = {}
|
||||||
|
self.overrides_mtime = None
|
||||||
|
self.load_overrides()
|
||||||
|
|
||||||
|
# Navidrome
|
||||||
|
def subsonic_url(self, method, **params):
|
||||||
|
salt = secrets.token_hex(8)
|
||||||
|
token = hashlib.md5((self.cfg["nd_password"] + salt).encode()).hexdigest() # noqa: S324 (Subsonic protocol)
|
||||||
|
q = {"u": self.cfg["nd_user"], "t": token, "s": salt, "v": SUBSONIC_VERSION,
|
||||||
|
"c": SUBSONIC_CLIENT, "f": "json", **params}
|
||||||
|
return f"{self.cfg['nd_url']}/rest/{method}?{urllib.parse.urlencode(q)}"
|
||||||
|
|
||||||
|
def poll_once(self):
|
||||||
|
status, body, _ = self.http_get(self.subsonic_url("getNowPlaying"), {}, 10)
|
||||||
|
if status != 200:
|
||||||
|
raise ValueError(f"getNowPlaying HTTP {status}")
|
||||||
|
parsed = parse_now_playing(json.loads(body), self.cfg["ignore_users"])
|
||||||
|
with self.lock:
|
||||||
|
self.playing = parsed
|
||||||
|
return len(parsed)
|
||||||
|
|
||||||
|
def poll_forever(self):
|
||||||
|
failures = 0
|
||||||
|
while True:
|
||||||
|
try:
|
||||||
|
n = self.poll_once()
|
||||||
|
if failures:
|
||||||
|
log.info("navidrome reachable again (%d sessions)", n)
|
||||||
|
failures = 0
|
||||||
|
except Exception as exc: # keep polling whatever happens
|
||||||
|
failures += 1
|
||||||
|
if failures in (1, 10) or failures % 100 == 0:
|
||||||
|
log.warning("poll failed (%d in a row): %s", failures, exc)
|
||||||
|
if failures >= 3:
|
||||||
|
with self.lock:
|
||||||
|
self.playing = {}
|
||||||
|
time.sleep(self.cfg["poll_s"])
|
||||||
|
|
||||||
|
# identity
|
||||||
|
def verify_token(self, token):
|
||||||
|
if not token or len(token) > 512:
|
||||||
|
return None
|
||||||
|
cached, hit = self.tokens.get(token)
|
||||||
|
if hit:
|
||||||
|
return cached
|
||||||
|
url = (f"{self.cfg['synapse']}/_matrix/federation/v1/openid/userinfo?"
|
||||||
|
+ urllib.parse.urlencode({"access_token": token}))
|
||||||
|
try:
|
||||||
|
status, body, _ = self.http_get(url, {}, 5)
|
||||||
|
except Exception as exc:
|
||||||
|
log.warning("openid check failed: %s", exc)
|
||||||
|
return None
|
||||||
|
mxid = None
|
||||||
|
if status == 200:
|
||||||
|
sub = (json.loads(body) or {}).get("sub") or ""
|
||||||
|
if sub.startswith("@") and sub.endswith(":" + self.cfg["server_name"]):
|
||||||
|
mxid = sub
|
||||||
|
# Tokens live about an hour; a rejected one is remembered briefly.
|
||||||
|
self.tokens.put(token, mxid, 600 if mxid else 30)
|
||||||
|
return mxid
|
||||||
|
|
||||||
|
def load_overrides(self):
|
||||||
|
path = self.cfg["users_file"]
|
||||||
|
try:
|
||||||
|
mtime = os.path.getmtime(path)
|
||||||
|
except OSError:
|
||||||
|
self.overrides = {}
|
||||||
|
return
|
||||||
|
if mtime == self.overrides_mtime:
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
with open(path) as f:
|
||||||
|
data = json.load(f)
|
||||||
|
self.overrides = {k: v for k, v in data.items() if isinstance(v, str) and v}
|
||||||
|
self.overrides_mtime = mtime
|
||||||
|
except (OSError, ValueError) as exc:
|
||||||
|
log.error("could not read %s: %s", path, exc)
|
||||||
|
|
||||||
|
def resolve(self, mxid):
|
||||||
|
self.load_overrides()
|
||||||
|
if mxid in self.overrides:
|
||||||
|
return self.overrides[mxid]
|
||||||
|
cached, hit = self.users.get(mxid)
|
||||||
|
if hit:
|
||||||
|
return cached
|
||||||
|
name = None
|
||||||
|
url = f"{self.cfg['synapse']}/_synapse/admin/v2/users/{urllib.parse.quote(mxid)}"
|
||||||
|
try:
|
||||||
|
status, body, _ = self.http_get(url, {"Authorization": f"Bearer {self.cfg['matrix_token']}"}, 5)
|
||||||
|
if status == 200:
|
||||||
|
name = username_from_admin_user(json.loads(body), self.cfg["email_domain"])
|
||||||
|
elif status != 404:
|
||||||
|
return None # don't cache transient failures
|
||||||
|
except Exception as exc:
|
||||||
|
log.warning("user lookup failed: %s", exc)
|
||||||
|
return None
|
||||||
|
self.users.put(mxid, name, 3600 if name else 300)
|
||||||
|
return name
|
||||||
|
|
||||||
|
# views
|
||||||
|
def entry_for(self, mxid):
|
||||||
|
if not self.optins.get(mxid):
|
||||||
|
return None
|
||||||
|
name = self.resolve(mxid)
|
||||||
|
if not name:
|
||||||
|
return None
|
||||||
|
with self.lock:
|
||||||
|
return self.playing.get(name)
|
||||||
|
|
||||||
|
def users_view(self, ids):
|
||||||
|
now_ms = int(time.time() * 1000)
|
||||||
|
out = {}
|
||||||
|
for mxid in ids:
|
||||||
|
entry = self.entry_for(mxid)
|
||||||
|
if entry:
|
||||||
|
out[mxid] = public_entry(entry, now_ms)
|
||||||
|
return out
|
||||||
|
|
||||||
|
def me_view(self, mxid):
|
||||||
|
name = self.resolve(mxid)
|
||||||
|
share = self.optins.get(mxid)
|
||||||
|
entry = None
|
||||||
|
if name:
|
||||||
|
with self.lock:
|
||||||
|
entry = self.playing.get(name)
|
||||||
|
return {
|
||||||
|
"share": share,
|
||||||
|
"linked": bool(name),
|
||||||
|
"playing": public_entry(entry, int(time.time() * 1000)) if entry else None,
|
||||||
|
}
|
||||||
|
|
||||||
|
def cover_allowed(self, cover_id):
|
||||||
|
with self.lock:
|
||||||
|
playing = dict(self.playing)
|
||||||
|
wanted = {name for name, e in playing.items() if e.get("coverArt") == cover_id}
|
||||||
|
if not wanted:
|
||||||
|
return False
|
||||||
|
return any(self.resolve(m) in wanted for m in self.optins.all())
|
||||||
|
|
||||||
|
|
||||||
|
# --- HTTP --------------------------------------------------------------------
|
||||||
|
|
||||||
|
def _http_get(url, headers, timeout):
|
||||||
|
req = urllib.request.Request(url, headers=headers)
|
||||||
|
try:
|
||||||
|
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
||||||
|
return resp.status, resp.read(), resp.headers.get("Content-Type", "")
|
||||||
|
except urllib.error.HTTPError as exc:
|
||||||
|
return exc.code, exc.read(), exc.headers.get("Content-Type", "")
|
||||||
|
|
||||||
|
|
||||||
|
class Handler(BaseHTTPRequestHandler):
|
||||||
|
server_version = "lotus-now-playing"
|
||||||
|
service: Service = None # set in main()
|
||||||
|
|
||||||
|
def log_message(self, fmt, *args): # no request logs: paths carry user IDs
|
||||||
|
pass
|
||||||
|
|
||||||
|
def _cors(self):
|
||||||
|
self.send_header("Access-Control-Allow-Origin", "*")
|
||||||
|
self.send_header("Access-Control-Allow-Headers", "Authorization, Content-Type")
|
||||||
|
self.send_header("Access-Control-Allow-Methods", "GET, PUT, OPTIONS")
|
||||||
|
self.send_header("Access-Control-Max-Age", "600")
|
||||||
|
|
||||||
|
def _json(self, status, obj):
|
||||||
|
body = json.dumps(obj).encode()
|
||||||
|
self.send_response(status)
|
||||||
|
self._cors()
|
||||||
|
self.send_header("Content-Type", "application/json")
|
||||||
|
self.send_header("Cache-Control", "no-store")
|
||||||
|
self.send_header("Content-Length", str(len(body)))
|
||||||
|
self.end_headers()
|
||||||
|
self.wfile.write(body)
|
||||||
|
|
||||||
|
def _caller(self):
|
||||||
|
auth = self.headers.get("Authorization") or ""
|
||||||
|
token = auth[7:].strip() if auth.lower().startswith("bearer ") else ""
|
||||||
|
return self.service.verify_token(token)
|
||||||
|
|
||||||
|
def do_OPTIONS(self):
|
||||||
|
self.send_response(204)
|
||||||
|
self._cors()
|
||||||
|
self.end_headers()
|
||||||
|
|
||||||
|
def do_GET(self):
|
||||||
|
url = urllib.parse.urlsplit(self.path)
|
||||||
|
if url.path == "/healthz":
|
||||||
|
return self._json(200, {"ok": True})
|
||||||
|
if url.path.startswith(PREFIX + "/cover/"):
|
||||||
|
return self._cover(urllib.parse.unquote(url.path[len(PREFIX) + 7:]), url.query)
|
||||||
|
mxid = self._caller()
|
||||||
|
if not mxid:
|
||||||
|
return self._json(401, {"errcode": "M_UNKNOWN_TOKEN", "error": "Matrix OpenID token required"})
|
||||||
|
if url.path == PREFIX + "/me":
|
||||||
|
return self._json(200, self.service.me_view(mxid))
|
||||||
|
if url.path == PREFIX + "/users":
|
||||||
|
raw = urllib.parse.parse_qs(url.query).get("ids", [""])[0]
|
||||||
|
ids = parse_ids(raw, self.service.cfg["server_name"])
|
||||||
|
return self._json(200, {"users": self.service.users_view(ids)})
|
||||||
|
return self._json(404, {"errcode": "M_NOT_FOUND"})
|
||||||
|
|
||||||
|
def do_PUT(self):
|
||||||
|
url = urllib.parse.urlsplit(self.path)
|
||||||
|
if url.path != PREFIX + "/me":
|
||||||
|
return self._json(404, {"errcode": "M_NOT_FOUND"})
|
||||||
|
mxid = self._caller()
|
||||||
|
if not mxid:
|
||||||
|
return self._json(401, {"errcode": "M_UNKNOWN_TOKEN", "error": "Matrix OpenID token required"})
|
||||||
|
try:
|
||||||
|
length = int(self.headers.get("Content-Length") or 0)
|
||||||
|
body = json.loads(self.rfile.read(min(length, 4096)) or b"{}")
|
||||||
|
share = body["share"]
|
||||||
|
if not isinstance(share, bool):
|
||||||
|
raise ValueError
|
||||||
|
except (ValueError, KeyError, TypeError):
|
||||||
|
return self._json(400, {"errcode": "M_BAD_JSON", "error": "expected {\"share\": true|false}"})
|
||||||
|
try:
|
||||||
|
self.service.optins.set(mxid, share)
|
||||||
|
except OSError as exc:
|
||||||
|
log.error("could not save opt-in: %s", exc)
|
||||||
|
return self._json(500, {"errcode": "M_UNKNOWN", "error": "could not save"})
|
||||||
|
log.info("sharing %s (now %d users)", "on" if share else "off", len(self.service.optins.all()))
|
||||||
|
return self._json(200, self.service.me_view(mxid))
|
||||||
|
|
||||||
|
def _cover(self, cover_id, query):
|
||||||
|
if not cover_id or len(cover_id) > 128 or not self.service.cover_allowed(cover_id):
|
||||||
|
return self._json(404, {"errcode": "M_NOT_FOUND"})
|
||||||
|
try:
|
||||||
|
size = int(urllib.parse.parse_qs(query).get("size", ["256"])[0])
|
||||||
|
except ValueError:
|
||||||
|
size = 256
|
||||||
|
size = min(COVER_SIZES, key=lambda s: abs(s - size))
|
||||||
|
try:
|
||||||
|
status, body, ctype = self.service.http_get(
|
||||||
|
self.service.subsonic_url("getCoverArt", id=cover_id, size=size), {}, 10)
|
||||||
|
except Exception:
|
||||||
|
status, body, ctype = 502, b"", ""
|
||||||
|
if status != 200 or not ctype.startswith("image/"):
|
||||||
|
return self._json(502, {"errcode": "M_UNKNOWN", "error": "cover unavailable"})
|
||||||
|
self.send_response(200)
|
||||||
|
self._cors()
|
||||||
|
self.send_header("Content-Type", ctype)
|
||||||
|
self.send_header("Cache-Control", "public, max-age=300")
|
||||||
|
self.send_header("Content-Length", str(len(body)))
|
||||||
|
self.end_headers()
|
||||||
|
self.wfile.write(body)
|
||||||
|
|
||||||
|
|
||||||
|
def load_config(env=os.environ):
|
||||||
|
def need(name):
|
||||||
|
value = env.get(name, "")
|
||||||
|
if not value:
|
||||||
|
raise SystemExit(f"missing {name}")
|
||||||
|
return value
|
||||||
|
|
||||||
|
return {
|
||||||
|
"bind": env.get("BIND_HOST", "0.0.0.0"),
|
||||||
|
"port": int(env.get("BIND_PORT", "8072")),
|
||||||
|
"server_name": env.get("SERVER_NAME", "matrix.lotusguild.org"),
|
||||||
|
"email_domain": env.get("EMAIL_DOMAIN", "lotusguild.org"),
|
||||||
|
"synapse": env.get("SYNAPSE_API", "http://127.0.0.1:8008").rstrip("/"),
|
||||||
|
"matrix_token": need("MATRIX_TOKEN"),
|
||||||
|
"nd_url": need("NAVIDROME_URL").rstrip("/"),
|
||||||
|
"nd_user": need("NAVIDROME_USER"),
|
||||||
|
"nd_password": need("NAVIDROME_PASSWORD"),
|
||||||
|
"ignore_users": tuple(u for u in env.get("IGNORE_USERS", "droppedneedle").split(",") if u),
|
||||||
|
"state_dir": env.get("STATE_DIR", "/var/lib/lotus-now-playing"),
|
||||||
|
"users_file": env.get("USERS_FILE", "/etc/lotus-now-playing/users.json"),
|
||||||
|
"poll_s": max(5, int(env.get("POLL_SECONDS", "10"))),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s")
|
||||||
|
cfg = load_config()
|
||||||
|
service = Service(cfg)
|
||||||
|
try:
|
||||||
|
log.info("navidrome ok, %d sessions", service.poll_once())
|
||||||
|
except Exception as exc:
|
||||||
|
log.warning("first poll failed: %s", exc)
|
||||||
|
threading.Thread(target=service.poll_forever, daemon=True).start()
|
||||||
|
Handler.service = service
|
||||||
|
server = ThreadingHTTPServer((cfg["bind"], cfg["port"]), Handler)
|
||||||
|
server.daemon_threads = True
|
||||||
|
log.info("listening on %s:%d (%d users sharing)", cfg["bind"], cfg["port"], len(service.optins.all()))
|
||||||
|
server.serve_forever()
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,173 @@
|
|||||||
|
"""Tests for lotus_now_playing.py. Run: python3 -m unittest now-playing/test_lotus_now_playing.py"""
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
import unittest
|
||||||
|
|
||||||
|
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||||
|
import lotus_now_playing as np # noqa: E402
|
||||||
|
|
||||||
|
|
||||||
|
def nd(entries, status="ok"):
|
||||||
|
return {"subsonic-response": {"status": status, "nowPlaying": {"entry": entries}}}
|
||||||
|
|
||||||
|
|
||||||
|
def entry(user, title="Song", minutes=0, state="playing", cover="al-1", **kw):
|
||||||
|
e = {"username": user, "title": title, "artist": "Band", "album": "LP", "duration": 200,
|
||||||
|
"minutesAgo": minutes, "state": state, "coverArt": cover, "playerName": "DN", "positionMs": 1000}
|
||||||
|
e.update(kw)
|
||||||
|
return e
|
||||||
|
|
||||||
|
|
||||||
|
class ParseTests(unittest.TestCase):
|
||||||
|
def test_basic_and_ignored_users(self):
|
||||||
|
out = np.parse_now_playing(nd([entry("jared"), entry("droppedneedle")]), ("droppedneedle",))
|
||||||
|
self.assertEqual(list(out), ["jared"])
|
||||||
|
self.assertEqual(out["jared"]["artist"], "Band")
|
||||||
|
self.assertEqual(out["jared"]["durationS"], 200)
|
||||||
|
|
||||||
|
def test_prefers_display_artist(self):
|
||||||
|
out = np.parse_now_playing(nd([entry("a", displayArtist="Band feat. X")]))
|
||||||
|
self.assertEqual(out["a"]["artist"], "Band feat. X")
|
||||||
|
|
||||||
|
def test_newest_session_wins(self):
|
||||||
|
out = np.parse_now_playing(nd([entry("a", "Old", minutes=5), entry("a", "New", minutes=0)]))
|
||||||
|
self.assertEqual(out["a"]["title"], "New")
|
||||||
|
|
||||||
|
def test_drops_stopped_untitled_and_stale(self):
|
||||||
|
out = np.parse_now_playing(nd([
|
||||||
|
entry("a", state="stopped"),
|
||||||
|
entry("b", title=""),
|
||||||
|
entry("c", minutes=90, positionMs=0),
|
||||||
|
entry("d", state="paused"),
|
||||||
|
]))
|
||||||
|
self.assertEqual(list(out), ["d"])
|
||||||
|
|
||||||
|
def test_single_entry_object_and_empty(self):
|
||||||
|
self.assertEqual(list(np.parse_now_playing(nd(entry("a")))), ["a"])
|
||||||
|
self.assertEqual(np.parse_now_playing({"subsonic-response": {"status": "ok"}}), {})
|
||||||
|
|
||||||
|
def test_error_raises(self):
|
||||||
|
with self.assertRaises(ValueError):
|
||||||
|
np.parse_now_playing({"subsonic-response": {"status": "failed", "error": {"message": "nope"}}})
|
||||||
|
|
||||||
|
|
||||||
|
class MappingTests(unittest.TestCase):
|
||||||
|
def test_email_on_domain(self):
|
||||||
|
user = {"threepids": [{"medium": "email", "address": "Tyler@LotusGuild.org"}]}
|
||||||
|
self.assertEqual(np.username_from_admin_user(user, "lotusguild.org"), "tyler")
|
||||||
|
|
||||||
|
def test_other_domain_ignored(self):
|
||||||
|
user = {"threepids": [{"medium": "email", "address": "x@gmail.com"}]}
|
||||||
|
self.assertIsNone(np.username_from_admin_user(user, "lotusguild.org"))
|
||||||
|
|
||||||
|
def test_legacy_external_id(self):
|
||||||
|
user = {"external_ids": [{"auth_provider": "https://auth.lotusguild.org", "external_id": "cole"}]}
|
||||||
|
self.assertEqual(np.username_from_admin_user(user, "lotusguild.org"), "cole")
|
||||||
|
|
||||||
|
def test_opaque_uuid_is_not_a_username(self):
|
||||||
|
user = {"external_ids": [
|
||||||
|
{"auth_provider": "oidc-authelia", "external_id": "b546660f-371c-45de-812c-bbae0e615148"},
|
||||||
|
{"auth_provider": "https://auth.lotusguild.org", "external_id": "b546660f-371c-45de-812c-bbae0e615148"},
|
||||||
|
]}
|
||||||
|
self.assertIsNone(np.username_from_admin_user(user, "lotusguild.org"))
|
||||||
|
|
||||||
|
def test_parse_ids(self):
|
||||||
|
ids = np.parse_ids("@a:hs, @b:other,@a:hs,junk,@c:hs", "hs")
|
||||||
|
self.assertEqual(ids, ["@a:hs", "@c:hs"])
|
||||||
|
self.assertEqual(len(np.parse_ids(",".join(f"@u{i}:hs" for i in range(80)), "hs")), np.MAX_IDS)
|
||||||
|
|
||||||
|
|
||||||
|
class FakeHttp:
|
||||||
|
def __init__(self):
|
||||||
|
self.calls = []
|
||||||
|
self.now_playing = nd([entry("jared", cover="al-9"), entry("jeff", cover="al-7")])
|
||||||
|
self.admin = {
|
||||||
|
"@jared:hs": {"threepids": [{"medium": "email", "address": "jared@lotusguild.org"}]},
|
||||||
|
"@nomail:hs": {"threepids": []},
|
||||||
|
}
|
||||||
|
self.openid = {"good": "@jared:hs", "foreign": "@x:elsewhere"}
|
||||||
|
|
||||||
|
def __call__(self, url, headers, timeout):
|
||||||
|
self.calls.append(url)
|
||||||
|
if "/rest/getNowPlaying" in url:
|
||||||
|
return 200, json.dumps(self.now_playing).encode(), "application/json"
|
||||||
|
if "/openid/userinfo" in url:
|
||||||
|
tok = url.split("access_token=")[1]
|
||||||
|
if tok in self.openid:
|
||||||
|
return 200, json.dumps({"sub": self.openid[tok]}).encode(), "application/json"
|
||||||
|
return 401, b"{}", "application/json"
|
||||||
|
if "/_synapse/admin/v2/users/" in url:
|
||||||
|
mxid = url.rsplit("/", 1)[1].replace("%40", "@").replace("%3A", ":")
|
||||||
|
if mxid in self.admin:
|
||||||
|
return 200, json.dumps(self.admin[mxid]).encode(), "application/json"
|
||||||
|
return 404, b"{}", "application/json"
|
||||||
|
raise AssertionError(url)
|
||||||
|
|
||||||
|
|
||||||
|
class ServiceTests(unittest.TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
self.tmp = tempfile.TemporaryDirectory()
|
||||||
|
users = os.path.join(self.tmp.name, "users.json")
|
||||||
|
with open(users, "w") as f:
|
||||||
|
json.dump({"@bigmanjeff:hs": "jeff"}, f)
|
||||||
|
self.http = FakeHttp()
|
||||||
|
self.svc = np.Service({
|
||||||
|
"server_name": "hs", "email_domain": "lotusguild.org", "synapse": "http://syn",
|
||||||
|
"matrix_token": "admin", "nd_url": "http://nd", "nd_user": "svc", "nd_password": "pw",
|
||||||
|
"ignore_users": ("droppedneedle",), "state_dir": self.tmp.name, "users_file": users, "poll_s": 10,
|
||||||
|
}, http_get=self.http)
|
||||||
|
self.svc.poll_once()
|
||||||
|
|
||||||
|
def tearDown(self):
|
||||||
|
self.tmp.cleanup()
|
||||||
|
|
||||||
|
def test_token_check_and_cache(self):
|
||||||
|
self.assertEqual(self.svc.verify_token("good"), "@jared:hs")
|
||||||
|
self.assertEqual(self.svc.verify_token("good"), "@jared:hs")
|
||||||
|
self.assertEqual(sum("/openid/" in c for c in self.http.calls), 1)
|
||||||
|
self.assertIsNone(self.svc.verify_token("bad"))
|
||||||
|
self.assertIsNone(self.svc.verify_token("foreign"))
|
||||||
|
self.assertIsNone(self.svc.verify_token(""))
|
||||||
|
|
||||||
|
def test_opt_in_required(self):
|
||||||
|
self.assertEqual(self.svc.users_view(["@jared:hs", "@bigmanjeff:hs"]), {})
|
||||||
|
self.svc.optins.set("@jared:hs", True)
|
||||||
|
view = self.svc.users_view(["@jared:hs", "@bigmanjeff:hs"])
|
||||||
|
self.assertEqual(list(view), ["@jared:hs"])
|
||||||
|
self.assertEqual(view["@jared:hs"]["cover"], "/now-playing/v1/cover/al-9")
|
||||||
|
|
||||||
|
def test_override_mapping(self):
|
||||||
|
self.svc.optins.set("@bigmanjeff:hs", True)
|
||||||
|
self.assertIn("@bigmanjeff:hs", self.svc.users_view(["@bigmanjeff:hs"]))
|
||||||
|
|
||||||
|
def test_opt_in_persists_and_opt_out(self):
|
||||||
|
self.svc.optins.set("@jared:hs", True)
|
||||||
|
reloaded = np.OptIns(os.path.join(self.tmp.name, "state.json"))
|
||||||
|
self.assertTrue(reloaded.get("@jared:hs"))
|
||||||
|
self.svc.optins.set("@jared:hs", False)
|
||||||
|
self.assertEqual(self.svc.users_view(["@jared:hs"]), {})
|
||||||
|
|
||||||
|
def test_me_view(self):
|
||||||
|
me = self.svc.me_view("@jared:hs")
|
||||||
|
self.assertEqual((me["share"], me["linked"]), (False, True))
|
||||||
|
self.assertEqual(me["playing"]["title"], "Song")
|
||||||
|
self.assertEqual(self.svc.me_view("@nomail:hs"), {"share": False, "linked": False, "playing": None})
|
||||||
|
|
||||||
|
def test_cover_allow_list(self):
|
||||||
|
self.assertFalse(self.svc.cover_allowed("al-9")) # nobody opted in yet
|
||||||
|
self.svc.optins.set("@jared:hs", True)
|
||||||
|
self.assertTrue(self.svc.cover_allowed("al-9"))
|
||||||
|
self.assertFalse(self.svc.cover_allowed("al-7")) # jeff hasn't opted in
|
||||||
|
self.assertFalse(self.svc.cover_allowed("al-unknown"))
|
||||||
|
|
||||||
|
def test_subsonic_url_never_contains_password(self):
|
||||||
|
url = self.svc.subsonic_url("getNowPlaying")
|
||||||
|
self.assertNotIn("pw", url.split("?")[1].split("&t=")[0])
|
||||||
|
self.assertIn("u=svc", url)
|
||||||
|
self.assertNotIn("p=", url)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
[Unit]
|
||||||
|
Description=Lotus Minecraft player count as the bridge bot's Matrix status
|
||||||
|
After=network-online.target
|
||||||
|
Wants=network-online.target
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
Type=simple
|
||||||
|
ExecStart=/usr/bin/python3 -I /opt/lotus-mc-status/lotus_mc_status.py
|
||||||
|
Environment=LOTUS_MC_HOST=10.10.10.78
|
||||||
|
Environment=LOTUS_MC_PORT=25565
|
||||||
|
LoadCredential=bridge-config:/var/lib/pelican/volumes/5476addf-384e-4f49-baa6-303e05719e9f/config/minecraftmatrixbridge.toml
|
||||||
|
DynamicUser=yes
|
||||||
|
NoNewPrivileges=yes
|
||||||
|
ProtectSystem=strict
|
||||||
|
ProtectHome=yes
|
||||||
|
PrivateTmp=yes
|
||||||
|
Restart=always
|
||||||
|
RestartSec=30
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=multi-user.target
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
[Unit]
|
||||||
|
Description=Now playing (Navidrome) for Lotus Chat "Listening to" cards
|
||||||
|
After=network-online.target matrix-synapse.service
|
||||||
|
Wants=network-online.target
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
Type=simple
|
||||||
|
User=lotus-now-playing
|
||||||
|
Group=lotus-now-playing
|
||||||
|
# MATRIX_TOKEN (Synapse admin API, user lookups only), shared with voice-limit-guard.
|
||||||
|
EnvironmentFile=/etc/matrix-deploy.env
|
||||||
|
# NAVIDROME_USER / NAVIDROME_PASSWORD for the read-only lotus-nowplaying account.
|
||||||
|
EnvironmentFile=/etc/lotus-now-playing/env
|
||||||
|
Environment=NAVIDROME_URL=http://10.10.10.28:4533
|
||||||
|
Environment=SERVER_NAME=matrix.lotusguild.org
|
||||||
|
Environment=BIND_HOST=0.0.0.0
|
||||||
|
Environment=BIND_PORT=8072
|
||||||
|
Environment=STATE_DIR=/var/lib/lotus-now-playing
|
||||||
|
Environment=USERS_FILE=/etc/lotus-now-playing/users.json
|
||||||
|
StateDirectory=lotus-now-playing
|
||||||
|
StateDirectoryMode=0750
|
||||||
|
ExecStart=/usr/bin/python3 /opt/lotus-now-playing/lotus_now_playing.py
|
||||||
|
Restart=always
|
||||||
|
RestartSec=10
|
||||||
|
StandardOutput=journal
|
||||||
|
StandardError=journal
|
||||||
|
SyslogIdentifier=lotus-now-playing
|
||||||
|
|
||||||
|
MemoryMax=96M
|
||||||
|
CPUQuota=20%
|
||||||
|
|
||||||
|
NoNewPrivileges=yes
|
||||||
|
ProtectSystem=strict
|
||||||
|
ProtectHome=yes
|
||||||
|
PrivateTmp=yes
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=multi-user.target
|
||||||
Reference in new issue
Block a user