Compare commits
4 Commits
206b378d93
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8f38d3d9f4 | ||
|
|
035089c159 | ||
|
|
8c295d183b | ||
|
|
0de6dd8c0d |
21
Dockerfile
Normal file
21
Dockerfile
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
# syntax=docker/dockerfile:1
|
||||||
|
|
||||||
|
FROM golang:1.25-alpine AS build
|
||||||
|
RUN apk add --no-cache build-base
|
||||||
|
WORKDIR /src
|
||||||
|
COPY go.mod go.sum ./
|
||||||
|
RUN go mod download
|
||||||
|
COPY . .
|
||||||
|
# goolm = pure-Go olm; sqlite needs cgo for the device/crypto stores.
|
||||||
|
ENV CGO_ENABLED=1
|
||||||
|
RUN go build -tags goolm -trimpath -ldflags="-s -w" -o /out/bellhop ./
|
||||||
|
|
||||||
|
FROM alpine:3.21
|
||||||
|
RUN apk add --no-cache ca-certificates tzdata
|
||||||
|
RUN addgroup -S bellhop && adduser -S -G bellhop bellhop
|
||||||
|
WORKDIR /app
|
||||||
|
COPY --from=build /out/bellhop /usr/local/bin/bellhop
|
||||||
|
USER bellhop
|
||||||
|
VOLUME ["/app/data"]
|
||||||
|
ENTRYPOINT ["/usr/local/bin/bellhop"]
|
||||||
|
CMD ["-config", "/app/config.toml"]
|
||||||
268
README.md
268
README.md
@@ -1,267 +1,81 @@
|
|||||||
# Bellhop
|
# Bellhop
|
||||||
|
|
||||||
A Matrix-authenticated web portal for submitting media requests to Radarr, Sonarr, and Lidarr. Users sign in with their Matrix homeserver credentials, search for movies, TV shows, or music, and submit requests — all through a clean single-page interface. Every request is logged to a Matrix room for auditing.
|
A Matrix bot that adds movies, TV, and music to Radarr/Sonarr/Lidarr from chat. Invite the bot to a room, allowlist the room ID, and any member can type `!movie dune` to add the top search hit.
|
||||||
|
|
||||||
## Architecture
|
## Command UX
|
||||||
|
|
||||||
```
|
```
|
||||||
Browser ──► FastAPI app ──► Matrix homeserver (authentication)
|
!movie <query> — add the top Radarr hit
|
||||||
──► Radarr / Sonarr / Lidarr (search + add)
|
!tv <query> — add the top Sonarr hit
|
||||||
──► Matrix room (audit log)
|
!music <query> — add the top Lidarr hit
|
||||||
──► SQLite (session storage)
|
!help — show the command list
|
||||||
```
|
```
|
||||||
|
|
||||||
All *arr communication happens server-side. API keys and service URLs are never exposed to the browser.
|
The bot replies in a thread under the request so a busy room stays readable. No numbered picker, no reaction selector — the top search result is what gets added. If you want something other than the top hit, narrow the query.
|
||||||
|
|
||||||
## Requirements
|
## Authorization
|
||||||
|
|
||||||
- Python 3.12+
|
Any member of an allowlisted room may issue commands. The bot auto-joins on invite, but the room ID must appear under `matrix.allowed_rooms` in the config before commands are honored.
|
||||||
- A Matrix homeserver (Synapse, Dendrite, Conduit, etc.)
|
|
||||||
- At least one of: Radarr, Sonarr, or Lidarr accessible over HTTPS
|
|
||||||
- (Optional) A Matrix bot account for audit logging
|
|
||||||
|
|
||||||
## Quick Start
|
## Configuration
|
||||||
|
|
||||||
### 1. Clone and configure
|
Copy `config.example.toml` to `config.toml` and edit. The loader expands `${ENV_VAR}` references at load time, so secrets can come from the environment.
|
||||||
|
|
||||||
```bash
|
Required:
|
||||||
git clone https://github.com/prosolis/Bellhop.git
|
|
||||||
cd Bellhop
|
|
||||||
cp .env.example .env
|
|
||||||
```
|
|
||||||
|
|
||||||
Edit `.env` with your actual values (see [Environment Variables](#environment-variables) below).
|
- `matrix.homeserver`, `matrix.user_id`, `matrix.password`
|
||||||
|
- `matrix.allowed_rooms` (at least one room ID)
|
||||||
|
- At least one of `services.radarr` / `services.sonarr` / `services.lidarr`
|
||||||
|
|
||||||
### 2. Run locally
|
Per-service: `url`, `api_key`, `quality_profile_id`, `root_folder`. Lidarr also needs `metadata_profile_id`.
|
||||||
|
|
||||||
```bash
|
Omit a service block to disable its command — `!movie` with no `radarr` block replies "Radarr is not configured".
|
||||||
pip install -r requirements.txt
|
|
||||||
uvicorn app.main:app --host 0.0.0.0 --port 8000
|
|
||||||
```
|
|
||||||
|
|
||||||
Open `http://localhost:8000` in your browser.
|
**Finding quality profile IDs:**
|
||||||
|
|
||||||
### 3. Run with Docker
|
|
||||||
|
|
||||||
```bash
|
|
||||||
docker build -t bellhop .
|
|
||||||
docker run -d \
|
|
||||||
--name bellhop \
|
|
||||||
--env-file .env \
|
|
||||||
-p 8000:8000 \
|
|
||||||
-v bellhop-data:/app \
|
|
||||||
bellhop
|
|
||||||
```
|
|
||||||
|
|
||||||
The SQLite database file is created at the path specified by `DATABASE_PATH` (default: `bellhop.db` in the working directory). Mount a volume if you want persistence across container recreations.
|
|
||||||
|
|
||||||
## Environment Variables
|
|
||||||
|
|
||||||
Create a `.env` file in the project root (or pass variables via Docker `--env-file`). See `.env.example` for a template.
|
|
||||||
|
|
||||||
### Required
|
|
||||||
|
|
||||||
| Variable | Description |
|
|
||||||
|---|---|
|
|
||||||
| `MATRIX_HOMESERVER_URL` | Base URL of your Matrix homeserver (e.g. `https://matrix.example.com`) |
|
|
||||||
|
|
||||||
### *arr Services
|
|
||||||
|
|
||||||
Configure one or more. If a service's URL or API key is left empty, that media type will return a "not configured" error when used.
|
|
||||||
|
|
||||||
| Variable | Default | Description |
|
|
||||||
|---|---|---|
|
|
||||||
| `RADARR_URL` | _(empty)_ | Radarr instance URL (e.g. `https://radarr.example.com`) |
|
|
||||||
| `RADARR_API_KEY` | _(empty)_ | Radarr API key (Settings > General in Radarr) |
|
|
||||||
| `RADARR_QUALITY_PROFILE_ID` | `1` | Quality profile ID to assign to new movies |
|
|
||||||
| `RADARR_ROOT_FOLDER` | `/movies` | Root folder path for movie storage |
|
|
||||||
| `SONARR_URL` | _(empty)_ | Sonarr instance URL |
|
|
||||||
| `SONARR_API_KEY` | _(empty)_ | Sonarr API key |
|
|
||||||
| `SONARR_QUALITY_PROFILE_ID` | `1` | Quality profile ID for new series |
|
|
||||||
| `SONARR_ROOT_FOLDER` | `/tv` | Root folder path for TV storage |
|
|
||||||
| `LIDARR_URL` | _(empty)_ | Lidarr instance URL |
|
|
||||||
| `LIDARR_API_KEY` | _(empty)_ | Lidarr API key |
|
|
||||||
| `LIDARR_QUALITY_PROFILE_ID` | `1` | Quality profile ID for new artists |
|
|
||||||
| `LIDARR_ROOT_FOLDER` | `/music` | Root folder path for music storage |
|
|
||||||
|
|
||||||
**Finding quality profile IDs:** Open your *arr instance, go to Settings > Profiles. The ID is visible in the URL when you click a profile, or query the API directly:
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
curl -H "X-Api-Key: YOUR_KEY" https://radarr.example.com/api/v3/qualityprofile
|
curl -H "X-Api-Key: YOUR_KEY" https://radarr.example.com/api/v3/qualityprofile
|
||||||
```
|
```
|
||||||
|
|
||||||
### Audit Bot (optional)
|
## Running
|
||||||
|
|
||||||
| Variable | Default | Description |
|
### Local
|
||||||
|---|---|---|
|
|
||||||
| `MATRIX_AUDIT_ROOM_ID` | _(empty)_ | Room ID for audit messages (e.g. `!abc123:example.com`) |
|
|
||||||
| `MATRIX_BOT_USER_ID` | _(empty)_ | Bot's Matrix user ID (e.g. `@bellhop-bot:example.com`) |
|
|
||||||
| `MATRIX_BOT_ACCESS_TOKEN` | _(empty)_ | Pre-authenticated access token for the bot |
|
|
||||||
|
|
||||||
If any of these are left empty, audit logging is silently disabled. The room must be **unencrypted** and the bot must already be joined to it.
|
|
||||||
|
|
||||||
**Getting a bot access token:**
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
curl -X POST https://matrix.example.com/_matrix/client/v3/login \
|
go build -tags goolm -o bellhop ./
|
||||||
-H "Content-Type: application/json" \
|
./bellhop -config config.toml
|
||||||
-d '{"type":"m.login.password","identifier":{"type":"m.id.user","user":"@bellhop-bot:example.com"},"password":"bot-password"}'
|
|
||||||
```
|
```
|
||||||
|
|
||||||
Copy the `access_token` from the response.
|
The `goolm` tag uses the pure-Go olm implementation so libolm isn't needed.
|
||||||
|
|
||||||
### Other
|
### Docker
|
||||||
|
|
||||||
| Variable | Default | Description |
|
```bash
|
||||||
|---|---|---|
|
docker build -t bellhop .
|
||||||
| `SESSION_SECRET_KEY` | _(auto-generated)_ | Secret for signing session cookies. Auto-generated at startup if not set. A new key is generated on every restart, which invalidates all existing sessions. |
|
docker run -d \
|
||||||
| `DATABASE_PATH` | `bellhop.db` | Path to the SQLite database file |
|
--name bellhop \
|
||||||
|
-v "$PWD/config.toml:/app/config.toml:ro" \
|
||||||
## API Reference
|
-v bellhop-data:/app/data \
|
||||||
|
bellhop
|
||||||
### Authentication
|
|
||||||
|
|
||||||
| Method | Path | Description |
|
|
||||||
|---|---|---|
|
|
||||||
| `POST` | `/auth/login` | Authenticate with Matrix credentials. Rate-limited to 5 requests/minute per IP. |
|
|
||||||
| `POST` | `/auth/logout` | Destroy the current session. |
|
|
||||||
| `GET` | `/auth/me` | Return the current user's Matrix ID, or 401 if not authenticated. |
|
|
||||||
|
|
||||||
**Login request body:**
|
|
||||||
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
"username": "@user:example.com",
|
|
||||||
"password": "your-password"
|
|
||||||
}
|
|
||||||
```
|
```
|
||||||
|
|
||||||
The username can be a full Matrix ID (`@user:example.com`) or a localpart (`user`) — the homeserver resolves it.
|
The `data` volume holds the Matrix device file and the E2EE crypto store. Losing it forces a re-login and re-verification on next start.
|
||||||
|
|
||||||
**Login response (200):**
|
## E2EE notes
|
||||||
|
|
||||||
```json
|
The bot bootstraps cross-signing on first run and persists Olm/Megolm sessions in `data/crypto.db`. If you rotate the bot's password or wipe `data/`, the bot logs in as a new device — existing rooms will need to re-share keys, which mautrix handles automatically on the next message.
|
||||||
{
|
|
||||||
"user_id": "@user:example.com"
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
A `bellhop_session` cookie is set automatically.
|
## Project layout
|
||||||
|
|
||||||
### Search
|
|
||||||
|
|
||||||
| Method | Path | Description |
|
|
||||||
|---|---|---|
|
|
||||||
| `GET` | `/search/movie?term=...` | Search Radarr for movies |
|
|
||||||
| `GET` | `/search/tv?term=...` | Search Sonarr for TV shows |
|
|
||||||
| `GET` | `/search/music?term=...` | Search Lidarr for artists |
|
|
||||||
|
|
||||||
All search endpoints require an active session (cookie). Results are capped at 25 items. Response fields are sanitized — only safe metadata (title, year, poster URL, IDs) is returned.
|
|
||||||
|
|
||||||
### Request
|
|
||||||
|
|
||||||
| Method | Path | Description |
|
|
||||||
|---|---|---|
|
|
||||||
| `POST` | `/request/movie` | Add a movie to Radarr |
|
|
||||||
| `POST` | `/request/tv` | Add a series to Sonarr |
|
|
||||||
| `POST` | `/request/music` | Add an artist to Lidarr |
|
|
||||||
|
|
||||||
**Movie request body:**
|
|
||||||
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
"title": "Movie Title",
|
|
||||||
"tmdbId": 12345,
|
|
||||||
"year": 2024
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
**TV request body:**
|
|
||||||
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
"title": "Show Title",
|
|
||||||
"tvdbId": 67890,
|
|
||||||
"year": 2024
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
**Music request body:**
|
|
||||||
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
"artistName": "Artist Name",
|
|
||||||
"foreignArtistId": "mbid-uuid-here"
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
All items are added as monitored with "search on add" enabled. Quality profile and root folder are set from the corresponding environment variables.
|
|
||||||
|
|
||||||
**Success response (200):**
|
|
||||||
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
"ok": true,
|
|
||||||
"message": "Movie added successfully"
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
### Frontend
|
|
||||||
|
|
||||||
| Method | Path | Description |
|
|
||||||
|---|---|---|
|
|
||||||
| `GET` | `/` | Serves the single-page Alpine.js frontend |
|
|
||||||
|
|
||||||
## Project Structure
|
|
||||||
|
|
||||||
```
|
```
|
||||||
Bellhop/
|
main.go
|
||||||
├── app/
|
internal/
|
||||||
│ ├── __init__.py
|
config/ — TOML loader with ${ENV_VAR} expansion
|
||||||
│ ├── main.py # FastAPI app, lifespan, rate limiter, route mounting
|
matrix/ — mautrix client: login, device persistence, E2EE, sync loop
|
||||||
│ ├── config.py # Environment variable loading
|
arr/ — Radarr/Sonarr/Lidarr HTTP clients
|
||||||
│ ├── database.py # Async SQLite session CRUD
|
bot/ — command parser + dispatch + threaded replies
|
||||||
│ ├── auth.py # /auth/* routes, session cookie management
|
|
||||||
│ ├── arr.py # /search/* and /request/* routes, *arr API proxying
|
|
||||||
│ ├── audit.py # Fire-and-forget Matrix room messaging
|
|
||||||
│ ├── static/ # Static assets (served at /static)
|
|
||||||
│ └── templates/
|
|
||||||
│ └── index.html # Alpine.js single-page frontend
|
|
||||||
├── Dockerfile
|
|
||||||
├── requirements.txt
|
|
||||||
├── .env.example
|
|
||||||
└── README.md
|
|
||||||
```
|
```
|
||||||
|
|
||||||
## Security
|
|
||||||
|
|
||||||
- **Session cookies** are set with `httponly`, `samesite=strict`, and `secure` flags. The `secure` flag means cookies are only sent over HTTPS — use a reverse proxy with TLS in production.
|
|
||||||
- **Login rate limiting** — 5 attempts per minute per IP address via slowapi.
|
|
||||||
- **Token validation** — every protected route verifies the Matrix access token against the homeserver's `/_matrix/client/v3/account/whoami` endpoint. If the token has been revoked, the session is deleted immediately. If the homeserver is unreachable, the local session is trusted as a fallback.
|
|
||||||
- **No credential leakage** — *arr API keys, URLs, and internal IDs are never included in any response to the browser. Search results are mapped to a safe subset of fields before returning.
|
|
||||||
- **Sessions expire** after 7 days (cookie `max_age`).
|
|
||||||
|
|
||||||
### Production Recommendations
|
|
||||||
|
|
||||||
- Run behind a reverse proxy (nginx, Caddy, Traefik) with TLS termination so the `secure` cookie flag works.
|
|
||||||
- If you want sessions to persist across restarts, set `SESSION_SECRET_KEY` explicitly. Otherwise, all users are logged out on restart.
|
|
||||||
- Restrict network access to your *arr instances — only the Bellhop container needs to reach them.
|
|
||||||
- Use a dedicated Matrix bot account for audit logging rather than a personal account.
|
|
||||||
|
|
||||||
## How It Works
|
|
||||||
|
|
||||||
1. **User signs in** — the frontend POSTs Matrix credentials to `/auth/login`. The backend authenticates against the Matrix homeserver's Client-Server API (`m.login.password`), stores the resulting access token in SQLite, and returns a session cookie.
|
|
||||||
|
|
||||||
2. **User searches** — the frontend sends a search query to `/search/{type}`. The backend proxies the request to the appropriate *arr instance, strips internal fields, and returns sanitized results with poster URLs.
|
|
||||||
|
|
||||||
3. **User requests** — clicking "Request" on a result POSTs it to `/request/{type}`. The backend sends the add command to the *arr API with preconfigured quality profile and root folder. On success, an audit message is fired asynchronously to the configured Matrix room.
|
|
||||||
|
|
||||||
4. **Audit trail** — every successful request posts a message like `[REQUEST] @user:example.com → [Movie] "Title" (2024)` to the Matrix audit room. This is fire-and-forget — failures are logged but never block the user's request.
|
|
||||||
|
|
||||||
## Lidarr Notes
|
|
||||||
|
|
||||||
Lidarr uses MusicBrainz IDs (`foreignArtistId`) rather than TMDB/TVDB IDs. The lookup response includes this field and it is passed through directly to the add call. No independent MBID resolution is needed.
|
|
||||||
|
|
||||||
## License
|
## License
|
||||||
|
|
||||||
See repository for license details.
|
See repository for license details.
|
||||||
|
|||||||
@@ -35,14 +35,14 @@ Rewriting Bellhop from a Python FastAPI web portal into a Go-based Matrix comman
|
|||||||
- All adds: monitored=true, search-on-add=true, quality profile + root folder from config
|
- All adds: monitored=true, search-on-add=true, quality profile + root folder from config
|
||||||
- Unit tests with httptest
|
- Unit tests with httptest
|
||||||
|
|
||||||
- [ ] **Session 4 — Command dispatch + main** (`internal/bot/`, `main.go`)
|
- [x] **Session 4 — Command dispatch + main** (`internal/bot/`, `main.go`)
|
||||||
- Parse `<prefix><cmd> <query>` (default prefix `!`)
|
- Parse `<prefix><cmd> <query>` (default prefix `!`)
|
||||||
- Commands: `movie`, `tv`, `music`, `help`
|
- Commands: `movie`, `tv`, `music`, `help`
|
||||||
- On match: search → take `[0]` → add → reply with title/year (or error)
|
- On match: search → take `[0]` → add → reply with title/year (or error)
|
||||||
- "Service not configured" reply if the corresponding *arr block is absent
|
- "Service not configured" reply if the corresponding *arr block is absent
|
||||||
- `main.go`: load config, init matrix, wire handler, SIGINT/SIGTERM shutdown
|
- `main.go`: load config, init matrix, wire handler, SIGINT/SIGTERM shutdown
|
||||||
|
|
||||||
- [ ] **Session 5 — Ship polish**
|
- [x] **Session 5 — Ship polish**
|
||||||
- Multi-stage Dockerfile (`golang:1.25-alpine` → `alpine:3.21`, build with `-tags goolm`)
|
- Multi-stage Dockerfile (`golang:1.25-alpine` → `alpine:3.21`, build with `-tags goolm`)
|
||||||
- `config.example.yaml`
|
- `config.example.yaml`
|
||||||
- Rewrite `README.md`: command UX, install, config reference, Docker
|
- Rewrite `README.md`: command UX, install, config reference, Docker
|
||||||
|
|||||||
43
config.example.toml
Normal file
43
config.example.toml
Normal file
@@ -0,0 +1,43 @@
|
|||||||
|
# Bellhop config. Values like ${ENV_VAR} are expanded from the environment
|
||||||
|
# at load time so secrets can stay out of this file.
|
||||||
|
|
||||||
|
[matrix]
|
||||||
|
homeserver = "https://matrix.example.com"
|
||||||
|
user_id = "@bellhop:example.com"
|
||||||
|
password = "${BELLHOP_MATRIX_PASSWORD}"
|
||||||
|
|
||||||
|
# Optional. Defaults shown.
|
||||||
|
display_name = "Bellhop"
|
||||||
|
data_dir = "./data" # device.json + crypto.db live here
|
||||||
|
pickle_key = "${BELLHOP_PICKLE_KEY}" # encrypts the crypto store; pick something stable
|
||||||
|
command_prefix = "!"
|
||||||
|
|
||||||
|
# Rooms the bot will respond to commands in. Messages anywhere else are
|
||||||
|
# ignored. The bot auto-joins on invite, but joining alone does not grant
|
||||||
|
# command access — the room ID must appear here.
|
||||||
|
allowed_rooms = [
|
||||||
|
"!room-id-one:example.com",
|
||||||
|
"!room-id-two:example.com",
|
||||||
|
]
|
||||||
|
|
||||||
|
# Configure any subset. Omit a section to disable that command:
|
||||||
|
# leaving out [services.radarr] makes `!movie` reply "Radarr is not configured".
|
||||||
|
|
||||||
|
[services.radarr]
|
||||||
|
url = "https://radarr.example.com"
|
||||||
|
api_key = "${RADARR_API_KEY}"
|
||||||
|
quality_profile_id = 1
|
||||||
|
root_folder = "/movies"
|
||||||
|
|
||||||
|
[services.sonarr]
|
||||||
|
url = "https://sonarr.example.com"
|
||||||
|
api_key = "${SONARR_API_KEY}"
|
||||||
|
quality_profile_id = 1
|
||||||
|
root_folder = "/tv"
|
||||||
|
|
||||||
|
[services.lidarr]
|
||||||
|
url = "https://lidarr.example.com"
|
||||||
|
api_key = "${LIDARR_API_KEY}"
|
||||||
|
quality_profile_id = 1
|
||||||
|
metadata_profile_id = 1 # required for Lidarr only
|
||||||
|
root_folder = "/music"
|
||||||
2
go.mod
2
go.mod
@@ -3,7 +3,7 @@ module bellhop
|
|||||||
go 1.25.0
|
go 1.25.0
|
||||||
|
|
||||||
require (
|
require (
|
||||||
gopkg.in/yaml.v3 v3.0.1
|
github.com/BurntSushi/toml v1.6.0
|
||||||
maunium.net/go/mautrix v0.28.0
|
maunium.net/go/mautrix v0.28.0
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
4
go.sum
4
go.sum
@@ -1,5 +1,7 @@
|
|||||||
filippo.io/edwards25519 v1.2.0 h1:crnVqOiS4jqYleHd9vaKZ+HKtHfllngJIiOpNpoJsjo=
|
filippo.io/edwards25519 v1.2.0 h1:crnVqOiS4jqYleHd9vaKZ+HKtHfllngJIiOpNpoJsjo=
|
||||||
filippo.io/edwards25519 v1.2.0/go.mod h1:xzAOLCNug/yB62zG1bQ8uziwrIqIuxhctzJT18Q77mc=
|
filippo.io/edwards25519 v1.2.0/go.mod h1:xzAOLCNug/yB62zG1bQ8uziwrIqIuxhctzJT18Q77mc=
|
||||||
|
github.com/BurntSushi/toml v1.6.0 h1:dRaEfpa2VI55EwlIW72hMRHdWouJeRF7TPYhI+AUQjk=
|
||||||
|
github.com/BurntSushi/toml v1.6.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho=
|
||||||
github.com/DATA-DOG/go-sqlmock v1.5.2 h1:OcvFkGmslmlZibjAjaHm3L//6LiuBgolP7OputlJIzU=
|
github.com/DATA-DOG/go-sqlmock v1.5.2 h1:OcvFkGmslmlZibjAjaHm3L//6LiuBgolP7OputlJIzU=
|
||||||
github.com/DATA-DOG/go-sqlmock v1.5.2/go.mod h1:88MAG/4G7SMwSE3CeA0ZKzrT5CiOU3OJ+JlNzwDqpNU=
|
github.com/DATA-DOG/go-sqlmock v1.5.2/go.mod h1:88MAG/4G7SMwSE3CeA0ZKzrT5CiOU3OJ+JlNzwDqpNU=
|
||||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||||
@@ -41,8 +43,6 @@ golang.org/x/sys v0.44.0 h1:ildZl3J4uzeKP07r2F++Op7E9B29JRUy+a27EibtBTQ=
|
|||||||
golang.org/x/sys v0.44.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
golang.org/x/sys v0.44.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||||
golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc=
|
golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc=
|
||||||
golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38=
|
golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38=
|
||||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
|
|
||||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
|
||||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||||
maunium.net/go/mautrix v0.28.0 h1:vBakLzf8MAdfED3NzAKiMeKQbc3AQ4EAS03NC+TVMXQ=
|
maunium.net/go/mautrix v0.28.0 h1:vBakLzf8MAdfED3NzAKiMeKQbc3AQ4EAS03NC+TVMXQ=
|
||||||
|
|||||||
@@ -19,11 +19,15 @@ import (
|
|||||||
|
|
||||||
// Result is a single candidate returned by an *arr lookup. Title and Year
|
// Result is a single candidate returned by an *arr lookup. Title and Year
|
||||||
// are extracted for display; raw is the untouched JSON object used to build
|
// are extracted for display; raw is the untouched JSON object used to build
|
||||||
// the Add payload.
|
// the Add payload. Exists is true when the *arr server already has this item
|
||||||
|
// in its library (lookup responses set "id" to a non-zero value in that case),
|
||||||
|
// so the bot can skip the Add and report 'already in library' instead of
|
||||||
|
// blindly re-POSTing.
|
||||||
type Result struct {
|
type Result struct {
|
||||||
Title string
|
Title string
|
||||||
Year int
|
Year int
|
||||||
raw json.RawMessage
|
Exists bool
|
||||||
|
raw json.RawMessage
|
||||||
}
|
}
|
||||||
|
|
||||||
// Raw exposes the underlying lookup JSON; useful for tests and debugging.
|
// Raw exposes the underlying lookup JSON; useful for tests and debugging.
|
||||||
@@ -105,10 +109,29 @@ func parseLookup(body []byte, titleField string) ([]Result, error) {
|
|||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
var title string
|
var title string
|
||||||
_ = json.Unmarshal(meta[titleField], &title)
|
if raw, ok := meta[titleField]; ok && len(raw) > 0 {
|
||||||
|
_ = json.Unmarshal(raw, &title)
|
||||||
|
}
|
||||||
|
if title == "" {
|
||||||
|
// Skip items we can't display. The Add path would still POST the
|
||||||
|
// raw JSON, but the user reply would read "Added to Radarr:" with
|
||||||
|
// no title — worse than dropping the candidate.
|
||||||
|
continue
|
||||||
|
}
|
||||||
var year int
|
var year int
|
||||||
_ = json.Unmarshal(meta["year"], &year)
|
if raw, ok := meta["year"]; ok && len(raw) > 0 {
|
||||||
out = append(out, Result{Title: title, Year: year, raw: item})
|
_ = json.Unmarshal(raw, &year)
|
||||||
|
}
|
||||||
|
var existingID int
|
||||||
|
if raw, ok := meta["id"]; ok && len(raw) > 0 {
|
||||||
|
_ = json.Unmarshal(raw, &existingID)
|
||||||
|
}
|
||||||
|
out = append(out, Result{
|
||||||
|
Title: title,
|
||||||
|
Year: year,
|
||||||
|
Exists: existingID > 0,
|
||||||
|
raw: item,
|
||||||
|
})
|
||||||
}
|
}
|
||||||
return out, nil
|
return out, nil
|
||||||
}
|
}
|
||||||
|
|||||||
173
internal/bot/bot.go
Normal file
173
internal/bot/bot.go
Normal file
@@ -0,0 +1,173 @@
|
|||||||
|
// Package bot wires Matrix command messages to the *arr clients.
|
||||||
|
//
|
||||||
|
// Commands take the form "<prefix><cmd> <query>" (e.g. "!movie dune"). The
|
||||||
|
// dispatcher parses the message, picks the *arr client by command name,
|
||||||
|
// performs a lookup, and adds the top hit. The reply is posted back into a
|
||||||
|
// thread rooted at the request event so a busy room stays readable.
|
||||||
|
package bot
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"html"
|
||||||
|
"log/slog"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"bellhop/internal/arr"
|
||||||
|
|
||||||
|
"maunium.net/go/mautrix/id"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Replier sends a threaded reply into roomID under rootEventID. The ctx
|
||||||
|
// governs cancellation/deadline so shutdown propagates through replies.
|
||||||
|
type Replier interface {
|
||||||
|
PostThreadedReply(ctx context.Context, roomID id.RoomID, rootEventID id.EventID, plain, htmlBody string) error
|
||||||
|
}
|
||||||
|
|
||||||
|
// Services holds the configured *arr clients. Any field may be nil; commands
|
||||||
|
// that target an unconfigured service reply with "not configured".
|
||||||
|
type Services struct {
|
||||||
|
Radarr arr.Client
|
||||||
|
Sonarr arr.Client
|
||||||
|
Lidarr arr.Client
|
||||||
|
}
|
||||||
|
|
||||||
|
// Dispatcher routes parsed commands to services and posts replies.
|
||||||
|
type Dispatcher struct {
|
||||||
|
baseCtx context.Context
|
||||||
|
prefix string
|
||||||
|
services Services
|
||||||
|
replier Replier
|
||||||
|
timeout time.Duration
|
||||||
|
}
|
||||||
|
|
||||||
|
// New builds a Dispatcher. prefix is the leading character(s) on a command
|
||||||
|
// (e.g. "!"); a zero value defaults to "!". baseCtx becomes the parent of
|
||||||
|
// every per-command context so app shutdown cancels in-flight handlers.
|
||||||
|
func New(baseCtx context.Context, prefix string, services Services, replier Replier) *Dispatcher {
|
||||||
|
if prefix == "" {
|
||||||
|
prefix = "!"
|
||||||
|
}
|
||||||
|
if baseCtx == nil {
|
||||||
|
baseCtx = context.Background()
|
||||||
|
}
|
||||||
|
return &Dispatcher{
|
||||||
|
baseCtx: baseCtx,
|
||||||
|
prefix: prefix,
|
||||||
|
services: services,
|
||||||
|
replier: replier,
|
||||||
|
timeout: 60 * time.Second,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Handle is the matrix.MessageHandler entry point. It parses body, dispatches
|
||||||
|
// the command, and posts a reply. Non-command messages are ignored silently.
|
||||||
|
func (d *Dispatcher) Handle(roomID id.RoomID, eventID id.EventID, sender id.UserID, body string) {
|
||||||
|
cmd, query, ok := parseCommand(d.prefix, body)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
slog.Info("bot: command received", "room", roomID, "sender", sender, "cmd", cmd, "query", query)
|
||||||
|
|
||||||
|
ctx, cancel := context.WithTimeout(d.baseCtx, d.timeout)
|
||||||
|
defer cancel()
|
||||||
|
|
||||||
|
plain, htmlBody := d.dispatch(ctx, cmd, query)
|
||||||
|
if err := d.replier.PostThreadedReply(ctx, roomID, eventID, plain, htmlBody); err != nil {
|
||||||
|
slog.Error("bot: reply failed", "room", roomID, "err", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// parseCommand pulls (cmd, query) out of a body like "!movie dune". Returns
|
||||||
|
// ok=false when the message is not a command for us.
|
||||||
|
func parseCommand(prefix, body string) (cmd, query string, ok bool) {
|
||||||
|
body = strings.TrimSpace(body)
|
||||||
|
if !strings.HasPrefix(body, prefix) {
|
||||||
|
return "", "", false
|
||||||
|
}
|
||||||
|
rest := strings.TrimSpace(body[len(prefix):])
|
||||||
|
if rest == "" {
|
||||||
|
return "", "", false
|
||||||
|
}
|
||||||
|
parts := strings.SplitN(rest, " ", 2)
|
||||||
|
cmd = strings.ToLower(parts[0])
|
||||||
|
if len(parts) == 2 {
|
||||||
|
query = strings.TrimSpace(parts[1])
|
||||||
|
}
|
||||||
|
return cmd, query, true
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Dispatcher) dispatch(ctx context.Context, cmd, query string) (plain, htmlBody string) {
|
||||||
|
switch cmd {
|
||||||
|
case "help":
|
||||||
|
return d.help()
|
||||||
|
case "movie":
|
||||||
|
return d.run(ctx, "movie", "Radarr", d.services.Radarr, query)
|
||||||
|
case "tv":
|
||||||
|
return d.run(ctx, "tv", "Sonarr", d.services.Sonarr, query)
|
||||||
|
case "music":
|
||||||
|
return d.run(ctx, "music", "Lidarr", d.services.Lidarr, query)
|
||||||
|
default:
|
||||||
|
msg := fmt.Sprintf("Unknown command %q. Try %shelp.", cmd, d.prefix)
|
||||||
|
return msg, html.EscapeString(msg)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Dispatcher) run(ctx context.Context, cmd, service string, client arr.Client, query string) (plain, htmlBody string) {
|
||||||
|
if client == nil {
|
||||||
|
msg := fmt.Sprintf("%s is not configured.", service)
|
||||||
|
return msg, html.EscapeString(msg)
|
||||||
|
}
|
||||||
|
if query == "" {
|
||||||
|
msg := fmt.Sprintf("Usage: %s%s <query>", d.prefix, cmd)
|
||||||
|
return msg, html.EscapeString(msg)
|
||||||
|
}
|
||||||
|
|
||||||
|
results, err := client.Search(ctx, query)
|
||||||
|
if err != nil {
|
||||||
|
slog.Error("bot: search failed", "service", service, "query", query, "err", err)
|
||||||
|
msg := fmt.Sprintf("%s search failed: %v", service, err)
|
||||||
|
return msg, html.EscapeString(msg)
|
||||||
|
}
|
||||||
|
if len(results) == 0 {
|
||||||
|
msg := fmt.Sprintf("No %s results for %q.", service, query)
|
||||||
|
return msg, html.EscapeString(msg)
|
||||||
|
}
|
||||||
|
|
||||||
|
top := results[0]
|
||||||
|
if top.Exists {
|
||||||
|
msg := fmt.Sprintf("%s already has %s in the library.", service, formatTitle(top))
|
||||||
|
return msg, html.EscapeString(msg)
|
||||||
|
}
|
||||||
|
if err := client.Add(ctx, top); err != nil {
|
||||||
|
slog.Error("bot: add failed", "service", service, "title", top.Title, "err", err)
|
||||||
|
msg := fmt.Sprintf("%s: failed to add %s: %v", service, formatTitle(top), err)
|
||||||
|
return msg, html.EscapeString(msg)
|
||||||
|
}
|
||||||
|
|
||||||
|
plain = fmt.Sprintf("Added to %s: %s", service, formatTitle(top))
|
||||||
|
htmlBody = fmt.Sprintf("Added to <b>%s</b>: %s", html.EscapeString(service), html.EscapeString(formatTitle(top)))
|
||||||
|
return plain, htmlBody
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Dispatcher) help() (string, string) {
|
||||||
|
lines := []string{
|
||||||
|
"Bellhop commands:",
|
||||||
|
fmt.Sprintf(" %smovie <query> — add the top Radarr hit", d.prefix),
|
||||||
|
fmt.Sprintf(" %stv <query> — add the top Sonarr hit", d.prefix),
|
||||||
|
fmt.Sprintf(" %smusic <query> — add the top Lidarr hit", d.prefix),
|
||||||
|
fmt.Sprintf(" %shelp — show this message", d.prefix),
|
||||||
|
}
|
||||||
|
plain := strings.Join(lines, "\n")
|
||||||
|
htmlBody := "<pre>" + html.EscapeString(plain) + "</pre>"
|
||||||
|
return plain, htmlBody
|
||||||
|
}
|
||||||
|
|
||||||
|
func formatTitle(r arr.Result) string {
|
||||||
|
if r.Year > 0 {
|
||||||
|
return fmt.Sprintf("%s (%d)", r.Title, r.Year)
|
||||||
|
}
|
||||||
|
return r.Title
|
||||||
|
}
|
||||||
237
internal/bot/bot_test.go
Normal file
237
internal/bot/bot_test.go
Normal file
@@ -0,0 +1,237 @@
|
|||||||
|
package bot
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"bellhop/internal/arr"
|
||||||
|
|
||||||
|
"maunium.net/go/mautrix/id"
|
||||||
|
)
|
||||||
|
|
||||||
|
type stubClient struct {
|
||||||
|
results []arr.Result
|
||||||
|
addErr error
|
||||||
|
srchErr error
|
||||||
|
|
||||||
|
searched string
|
||||||
|
added []arr.Result
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *stubClient) Search(_ context.Context, term string) ([]arr.Result, error) {
|
||||||
|
s.searched = term
|
||||||
|
if s.srchErr != nil {
|
||||||
|
return nil, s.srchErr
|
||||||
|
}
|
||||||
|
return s.results, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *stubClient) Add(_ context.Context, r arr.Result) error {
|
||||||
|
if s.addErr != nil {
|
||||||
|
return s.addErr
|
||||||
|
}
|
||||||
|
s.added = append(s.added, r)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type stubReplier struct {
|
||||||
|
mu sync.Mutex
|
||||||
|
plain string
|
||||||
|
htmlBody string
|
||||||
|
calls int
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *stubReplier) PostThreadedReply(_ context.Context, _ id.RoomID, _ id.EventID, plain, htmlBody string) error {
|
||||||
|
r.mu.Lock()
|
||||||
|
defer r.mu.Unlock()
|
||||||
|
r.calls++
|
||||||
|
r.plain = plain
|
||||||
|
r.htmlBody = htmlBody
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func newDispatcher(prefix string, services Services, replier Replier) *Dispatcher {
|
||||||
|
return New(context.Background(), prefix, services, replier)
|
||||||
|
}
|
||||||
|
|
||||||
|
const (
|
||||||
|
room = id.RoomID("!room:example.org")
|
||||||
|
event = id.EventID("$evt")
|
||||||
|
sender = id.UserID("@alice:example.org")
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestParseCommand(t *testing.T) {
|
||||||
|
cases := []struct {
|
||||||
|
body string
|
||||||
|
wantCmd, wantQ string
|
||||||
|
wantOk bool
|
||||||
|
}{
|
||||||
|
{"!movie dune", "movie", "dune", true},
|
||||||
|
{" !movie dune part two ", "movie", "dune part two", true},
|
||||||
|
{"!HELP", "help", "", true},
|
||||||
|
{"hello world", "", "", false},
|
||||||
|
{"!", "", "", false},
|
||||||
|
{"! ", "", "", false},
|
||||||
|
}
|
||||||
|
for _, c := range cases {
|
||||||
|
cmd, q, ok := parseCommand("!", c.body)
|
||||||
|
if cmd != c.wantCmd || q != c.wantQ || ok != c.wantOk {
|
||||||
|
t.Errorf("parseCommand(%q) = (%q,%q,%v); want (%q,%q,%v)",
|
||||||
|
c.body, cmd, q, ok, c.wantCmd, c.wantQ, c.wantOk)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDispatchMovieTopHit(t *testing.T) {
|
||||||
|
radarr := &stubClient{results: []arr.Result{
|
||||||
|
{Title: "Dune", Year: 2021},
|
||||||
|
{Title: "Dune", Year: 1984},
|
||||||
|
}}
|
||||||
|
rep := &stubReplier{}
|
||||||
|
d := newDispatcher("!", Services{Radarr: radarr}, rep)
|
||||||
|
|
||||||
|
d.Handle(room, event, sender, "!movie dune")
|
||||||
|
|
||||||
|
if radarr.searched != "dune" {
|
||||||
|
t.Fatalf("search term = %q", radarr.searched)
|
||||||
|
}
|
||||||
|
if len(radarr.added) != 1 || radarr.added[0].Year != 2021 {
|
||||||
|
t.Fatalf("expected top hit added, got %+v", radarr.added)
|
||||||
|
}
|
||||||
|
if !strings.Contains(rep.plain, "Dune (2021)") || !strings.Contains(rep.plain, "Radarr") {
|
||||||
|
t.Fatalf("reply missing expected content: %q", rep.plain)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDispatchNoResults(t *testing.T) {
|
||||||
|
sonarr := &stubClient{}
|
||||||
|
rep := &stubReplier{}
|
||||||
|
d := newDispatcher("!", Services{Sonarr: sonarr}, rep)
|
||||||
|
|
||||||
|
d.Handle(room, event, sender, "!tv obscure show")
|
||||||
|
|
||||||
|
if len(sonarr.added) != 0 {
|
||||||
|
t.Fatal("should not add when no results")
|
||||||
|
}
|
||||||
|
if !strings.Contains(rep.plain, "No Sonarr results") {
|
||||||
|
t.Fatalf("unexpected reply: %q", rep.plain)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDispatchUnconfigured(t *testing.T) {
|
||||||
|
rep := &stubReplier{}
|
||||||
|
d := newDispatcher("!", Services{}, rep)
|
||||||
|
|
||||||
|
d.Handle(room, event, sender, "!music radiohead")
|
||||||
|
|
||||||
|
if !strings.Contains(rep.plain, "Lidarr is not configured") {
|
||||||
|
t.Fatalf("unexpected reply: %q", rep.plain)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDispatchEmptyQuery(t *testing.T) {
|
||||||
|
radarr := &stubClient{}
|
||||||
|
rep := &stubReplier{}
|
||||||
|
d := newDispatcher("!", Services{Radarr: radarr}, rep)
|
||||||
|
|
||||||
|
d.Handle(room, event, sender, "!movie")
|
||||||
|
|
||||||
|
if radarr.searched != "" {
|
||||||
|
t.Fatal("should not search with empty query")
|
||||||
|
}
|
||||||
|
if !strings.Contains(rep.plain, "Usage:") {
|
||||||
|
t.Fatalf("unexpected reply: %q", rep.plain)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDispatchAddError(t *testing.T) {
|
||||||
|
radarr := &stubClient{
|
||||||
|
results: []arr.Result{{Title: "Dune", Year: 2021}},
|
||||||
|
addErr: errors.New("boom"),
|
||||||
|
}
|
||||||
|
rep := &stubReplier{}
|
||||||
|
d := newDispatcher("!", Services{Radarr: radarr}, rep)
|
||||||
|
|
||||||
|
d.Handle(room, event, sender, "!movie dune")
|
||||||
|
|
||||||
|
if !strings.Contains(rep.plain, "failed to add") || !strings.Contains(rep.plain, "boom") {
|
||||||
|
t.Fatalf("unexpected reply: %q", rep.plain)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDispatchSearchError(t *testing.T) {
|
||||||
|
radarr := &stubClient{srchErr: errors.New("network down")}
|
||||||
|
rep := &stubReplier{}
|
||||||
|
d := newDispatcher("!", Services{Radarr: radarr}, rep)
|
||||||
|
|
||||||
|
d.Handle(room, event, sender, "!movie dune")
|
||||||
|
|
||||||
|
if !strings.Contains(rep.plain, "search failed") {
|
||||||
|
t.Fatalf("unexpected reply: %q", rep.plain)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDispatchHelp(t *testing.T) {
|
||||||
|
rep := &stubReplier{}
|
||||||
|
d := newDispatcher("!", Services{}, rep)
|
||||||
|
|
||||||
|
d.Handle(room, event, sender, "!help")
|
||||||
|
|
||||||
|
for _, want := range []string{"!movie", "!tv", "!music", "!help"} {
|
||||||
|
if !strings.Contains(rep.plain, want) {
|
||||||
|
t.Errorf("help missing %q: %q", want, rep.plain)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDispatchUnknown(t *testing.T) {
|
||||||
|
rep := &stubReplier{}
|
||||||
|
d := newDispatcher("!", Services{}, rep)
|
||||||
|
|
||||||
|
d.Handle(room, event, sender, "!frobnicate stuff")
|
||||||
|
|
||||||
|
if !strings.Contains(rep.plain, "Unknown command") {
|
||||||
|
t.Fatalf("unexpected reply: %q", rep.plain)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNonCommandIgnored(t *testing.T) {
|
||||||
|
rep := &stubReplier{}
|
||||||
|
d := newDispatcher("!", Services{}, rep)
|
||||||
|
|
||||||
|
d.Handle(room, event, sender, "just chatting")
|
||||||
|
|
||||||
|
if rep.calls != 0 {
|
||||||
|
t.Fatalf("expected no reply, got %d", rep.calls)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDispatchAlreadyInLibrary(t *testing.T) {
|
||||||
|
radarr := &stubClient{results: []arr.Result{{Title: "Dune", Year: 2021, Exists: true}}}
|
||||||
|
rep := &stubReplier{}
|
||||||
|
d := newDispatcher("!", Services{Radarr: radarr}, rep)
|
||||||
|
|
||||||
|
d.Handle(room, event, sender, "!movie dune")
|
||||||
|
|
||||||
|
if len(radarr.added) != 0 {
|
||||||
|
t.Fatalf("should not re-add existing item, got %d adds", len(radarr.added))
|
||||||
|
}
|
||||||
|
if !strings.Contains(rep.plain, "already has") || !strings.Contains(rep.plain, "Dune (2021)") {
|
||||||
|
t.Fatalf("unexpected reply: %q", rep.plain)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCustomPrefix(t *testing.T) {
|
||||||
|
radarr := &stubClient{results: []arr.Result{{Title: "Dune", Year: 2021}}}
|
||||||
|
rep := &stubReplier{}
|
||||||
|
d := newDispatcher(".bh ", Services{Radarr: radarr}, rep)
|
||||||
|
|
||||||
|
d.Handle(room, event, sender, ".bh movie dune")
|
||||||
|
|
||||||
|
if len(radarr.added) != 1 {
|
||||||
|
t.Fatalf("expected add, got %d", len(radarr.added))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -6,42 +6,42 @@ import (
|
|||||||
"os"
|
"os"
|
||||||
"regexp"
|
"regexp"
|
||||||
|
|
||||||
"gopkg.in/yaml.v3"
|
"github.com/BurntSushi/toml"
|
||||||
)
|
)
|
||||||
|
|
||||||
var envBracketRe = regexp.MustCompile(`\$\{([^}]+)\}`)
|
var envBracketRe = regexp.MustCompile(`\$\{([^}]+)\}`)
|
||||||
|
|
||||||
type Config struct {
|
type Config struct {
|
||||||
Matrix MatrixConfig `yaml:"matrix"`
|
Matrix MatrixConfig `toml:"matrix"`
|
||||||
Services ServicesConfig `yaml:"services"`
|
Services ServicesConfig `toml:"services"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type MatrixConfig struct {
|
type MatrixConfig struct {
|
||||||
Homeserver string `yaml:"homeserver"`
|
Homeserver string `toml:"homeserver"`
|
||||||
UserID string `yaml:"user_id"`
|
UserID string `toml:"user_id"`
|
||||||
Password string `yaml:"password"`
|
Password string `toml:"password"`
|
||||||
PickleKey string `yaml:"pickle_key"`
|
PickleKey string `toml:"pickle_key"`
|
||||||
DisplayName string `yaml:"display_name"`
|
DisplayName string `toml:"display_name"`
|
||||||
DataDir string `yaml:"data_dir"`
|
DataDir string `toml:"data_dir"`
|
||||||
CommandPrefix string `yaml:"command_prefix"`
|
CommandPrefix string `toml:"command_prefix"`
|
||||||
// AllowedRooms is the set of room IDs the bot listens for commands in.
|
// AllowedRooms is the set of room IDs the bot listens for commands in.
|
||||||
// Messages in any other room are ignored.
|
// Messages in any other room are ignored.
|
||||||
AllowedRooms []string `yaml:"allowed_rooms"`
|
AllowedRooms []string `toml:"allowed_rooms"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type ServicesConfig struct {
|
type ServicesConfig struct {
|
||||||
Radarr *ArrConfig `yaml:"radarr"`
|
Radarr *ArrConfig `toml:"radarr"`
|
||||||
Sonarr *ArrConfig `yaml:"sonarr"`
|
Sonarr *ArrConfig `toml:"sonarr"`
|
||||||
Lidarr *ArrConfig `yaml:"lidarr"`
|
Lidarr *ArrConfig `toml:"lidarr"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type ArrConfig struct {
|
type ArrConfig struct {
|
||||||
URL string `yaml:"url"`
|
URL string `toml:"url"`
|
||||||
APIKey string `yaml:"api_key"`
|
APIKey string `toml:"api_key"`
|
||||||
QualityProfileID int `yaml:"quality_profile_id"`
|
QualityProfileID int `toml:"quality_profile_id"`
|
||||||
RootFolder string `yaml:"root_folder"`
|
RootFolder string `toml:"root_folder"`
|
||||||
// MetadataProfileID is required by Lidarr; ignored by Radarr/Sonarr.
|
// MetadataProfileID is required by Lidarr; ignored by Radarr/Sonarr.
|
||||||
MetadataProfileID int `yaml:"metadata_profile_id"`
|
MetadataProfileID int `toml:"metadata_profile_id"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func Load(path string) (*Config, error) {
|
func Load(path string) (*Config, error) {
|
||||||
@@ -60,7 +60,7 @@ func Load(path string) (*Config, error) {
|
|||||||
})
|
})
|
||||||
|
|
||||||
var cfg Config
|
var cfg Config
|
||||||
if err := yaml.Unmarshal([]byte(expanded), &cfg); err != nil {
|
if _, err := toml.Decode(expanded, &cfg); err != nil {
|
||||||
return nil, fmt.Errorf("parse config: %w", err)
|
return nil, fmt.Errorf("parse config: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ package matrix
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"log/slog"
|
"log/slog"
|
||||||
"net/http"
|
"net/http"
|
||||||
@@ -50,13 +51,16 @@ func New(cfg config.MatrixConfig) (*Client, error) {
|
|||||||
|
|
||||||
device, err := loadDevice(devicePath)
|
device, err := loadDevice(devicePath)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
slog.Info("no existing device found, will login fresh")
|
// File exists but is unparseable — refuse to overwrite. A silent fresh
|
||||||
|
// login would orphan the prior device's megolm sessions and break
|
||||||
|
// decryption in every encrypted room the bot is already in.
|
||||||
|
return nil, fmt.Errorf("load device file %s: %w (refusing to overwrite — fix or delete the file)", devicePath, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
var mx *mautrix.Client
|
var mx *mautrix.Client
|
||||||
|
|
||||||
if device != nil {
|
if device != nil {
|
||||||
if isTokenValid(cfg.Homeserver, device.AccessToken) {
|
if isTokenValid(cfg.Homeserver, device.AccessToken, cfg.UserID) {
|
||||||
slog.Info("existing device credentials valid", "device_id", device.DeviceID)
|
slog.Info("existing device credentials valid", "device_id", device.DeviceID)
|
||||||
mx, err = mautrix.NewClient(cfg.Homeserver, id.UserID(device.UserID), device.AccessToken)
|
mx, err = mautrix.NewClient(cfg.Homeserver, id.UserID(device.UserID), device.AccessToken)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -92,12 +96,11 @@ func New(cfg config.MatrixConfig) (*Client, error) {
|
|||||||
mx.UserID = resp.UserID
|
mx.UserID = resp.UserID
|
||||||
mx.DeviceID = resp.DeviceID
|
mx.DeviceID = resp.DeviceID
|
||||||
|
|
||||||
device = &deviceInfo{
|
if err := saveDevice(devicePath, &deviceInfo{
|
||||||
AccessToken: resp.AccessToken,
|
AccessToken: resp.AccessToken,
|
||||||
DeviceID: string(resp.DeviceID),
|
DeviceID: string(resp.DeviceID),
|
||||||
UserID: string(resp.UserID),
|
UserID: string(resp.UserID),
|
||||||
}
|
}); err != nil {
|
||||||
if err := saveDevice(devicePath, device); err != nil {
|
|
||||||
slog.Warn("failed to save device info", "err", err)
|
slog.Warn("failed to save device info", "err", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -117,16 +120,11 @@ func New(cfg config.MatrixConfig) (*Client, error) {
|
|||||||
"room", evt.RoomID, "event_id", evt.ID, "sender", evt.Sender, "err", err)
|
"room", evt.RoomID, "event_id", evt.ID, "sender", evt.Sender, "err", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
ch.LoginAs = &mautrix.ReqLogin{
|
// Intentionally NOT setting ch.LoginAs: cryptohelper.Init will Login() every
|
||||||
Type: mautrix.AuthTypePassword,
|
// time LoginAs is non-nil (see mautrix cryptohelper.go), which would mint a
|
||||||
Identifier: mautrix.UserIdentifier{
|
// new access_token on every startup and silently invalidate the device.json
|
||||||
Type: mautrix.IdentifierTypeUser,
|
// we just wrote. We already have valid credentials in mx by this point —
|
||||||
User: cfg.UserID,
|
// Init will reuse them.
|
||||||
},
|
|
||||||
Password: cfg.Password,
|
|
||||||
InitialDeviceDisplayName: cfg.DisplayName,
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := ch.Init(context.Background()); err != nil {
|
if err := ch.Init(context.Background()); err != nil {
|
||||||
return nil, fmt.Errorf("crypto helper init: %w", err)
|
return nil, fmt.Errorf("crypto helper init: %w", err)
|
||||||
}
|
}
|
||||||
@@ -189,8 +187,11 @@ func (c *Client) SetMessageHandler(fn MessageHandler) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Start begins the Matrix sync loop in the background.
|
// Start begins the Matrix sync loop in the background.
|
||||||
func (c *Client) Start(ctx context.Context) {
|
func (c *Client) Start(ctx context.Context) error {
|
||||||
syncer := c.mx.Syncer.(*mautrix.DefaultSyncer)
|
syncer, ok := c.mx.Syncer.(*mautrix.DefaultSyncer)
|
||||||
|
if !ok {
|
||||||
|
return fmt.Errorf("matrix syncer is not *mautrix.DefaultSyncer (got %T)", c.mx.Syncer)
|
||||||
|
}
|
||||||
|
|
||||||
syncer.OnEventType(event.EventMessage, func(ctx context.Context, evt *event.Event) {
|
syncer.OnEventType(event.EventMessage, func(ctx context.Context, evt *event.Event) {
|
||||||
if evt.Sender == c.userID {
|
if evt.Sender == c.userID {
|
||||||
@@ -243,6 +244,7 @@ func (c *Client) Start(ctx context.Context) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Stop halts the sync loop and closes the crypto store.
|
// Stop halts the sync loop and closes the crypto store.
|
||||||
@@ -259,10 +261,8 @@ func (c *Client) Stop() {
|
|||||||
|
|
||||||
// PostThreadedReply sends a plain/HTML message into the thread rooted at rootEventID.
|
// PostThreadedReply sends a plain/HTML message into the thread rooted at rootEventID.
|
||||||
// IsFallingBack + m.in_reply_to gives non-thread-aware clients a sensible quoted reply.
|
// IsFallingBack + m.in_reply_to gives non-thread-aware clients a sensible quoted reply.
|
||||||
func (c *Client) PostThreadedReply(roomID id.RoomID, rootEventID id.EventID, plain, htmlBody string) error {
|
// The caller's ctx governs cancellation and deadline.
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
func (c *Client) PostThreadedReply(ctx context.Context, roomID id.RoomID, rootEventID id.EventID, plain, htmlBody string) error {
|
||||||
defer cancel()
|
|
||||||
|
|
||||||
content := &event.MessageEventContent{
|
content := &event.MessageEventContent{
|
||||||
MsgType: event.MsgText,
|
MsgType: event.MsgText,
|
||||||
Body: plain,
|
Body: plain,
|
||||||
@@ -279,14 +279,24 @@ func (c *Client) PostThreadedReply(roomID id.RoomID, rootEventID id.EventID, pla
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// loadDevice returns (nil, nil) when no device file exists, the parsed device
|
||||||
|
// when it does, or (nil, err) when the file is present but unreadable/corrupt.
|
||||||
|
// Distinguishing the corrupt case lets the caller refuse to silently overwrite
|
||||||
|
// it with a brand-new device registration.
|
||||||
func loadDevice(path string) (*deviceInfo, error) {
|
func loadDevice(path string) (*deviceInfo, error) {
|
||||||
data, err := os.ReadFile(path)
|
data, err := os.ReadFile(path)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
if errors.Is(err, os.ErrNotExist) {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
var info deviceInfo
|
var info deviceInfo
|
||||||
if err := json.Unmarshal(data, &info); err != nil {
|
if err := json.Unmarshal(data, &info); err != nil {
|
||||||
return nil, err
|
return nil, fmt.Errorf("parse: %w", err)
|
||||||
|
}
|
||||||
|
if info.AccessToken == "" || info.DeviceID == "" || info.UserID == "" {
|
||||||
|
return nil, fmt.Errorf("missing required fields (access_token/device_id/user_id)")
|
||||||
}
|
}
|
||||||
return &info, nil
|
return &info, nil
|
||||||
}
|
}
|
||||||
@@ -299,7 +309,11 @@ func saveDevice(path string, info *deviceInfo) error {
|
|||||||
return os.WriteFile(path, data, 0o600)
|
return os.WriteFile(path, data, 0o600)
|
||||||
}
|
}
|
||||||
|
|
||||||
func isTokenValid(homeserver, accessToken string) bool {
|
// isTokenValid hits /whoami and confirms both that the token is accepted AND
|
||||||
|
// that it identifies the user we expect. A bare status-code check would accept
|
||||||
|
// a token belonging to a different account if the operator swapped user_id
|
||||||
|
// without clearing data_dir.
|
||||||
|
func isTokenValid(homeserver, accessToken, expectedUserID string) bool {
|
||||||
req, err := http.NewRequest("GET", homeserver+"/_matrix/client/v3/account/whoami", nil)
|
req, err := http.NewRequest("GET", homeserver+"/_matrix/client/v3/account/whoami", nil)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return false
|
return false
|
||||||
@@ -312,5 +326,19 @@ func isTokenValid(homeserver, accessToken string) bool {
|
|||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
defer resp.Body.Close()
|
defer resp.Body.Close()
|
||||||
return resp.StatusCode == http.StatusOK
|
if resp.StatusCode != http.StatusOK {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
var body struct {
|
||||||
|
UserID string `json:"user_id"`
|
||||||
|
}
|
||||||
|
if err := json.NewDecoder(resp.Body).Decode(&body); err != nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if body.UserID != expectedUserID {
|
||||||
|
slog.Warn("saved token belongs to a different user, will re-login",
|
||||||
|
"saved", body.UserID, "configured", expectedUserID)
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return true
|
||||||
}
|
}
|
||||||
|
|||||||
66
main.go
Normal file
66
main.go
Normal file
@@ -0,0 +1,66 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"flag"
|
||||||
|
"log/slog"
|
||||||
|
"os"
|
||||||
|
"os/signal"
|
||||||
|
"syscall"
|
||||||
|
|
||||||
|
"bellhop/internal/arr"
|
||||||
|
"bellhop/internal/bot"
|
||||||
|
"bellhop/internal/config"
|
||||||
|
"bellhop/internal/matrix"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
configPath := flag.String("config", "config.toml", "path to config file")
|
||||||
|
flag.Parse()
|
||||||
|
|
||||||
|
slog.SetDefault(slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelInfo})))
|
||||||
|
|
||||||
|
cfg, err := config.Load(*configPath)
|
||||||
|
if err != nil {
|
||||||
|
slog.Error("config load failed", "err", err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
|
||||||
|
services := bot.Services{}
|
||||||
|
if cfg.Services.Radarr != nil {
|
||||||
|
services.Radarr = arr.NewRadarr(cfg.Services.Radarr)
|
||||||
|
}
|
||||||
|
if cfg.Services.Sonarr != nil {
|
||||||
|
services.Sonarr = arr.NewSonarr(cfg.Services.Sonarr)
|
||||||
|
}
|
||||||
|
if cfg.Services.Lidarr != nil {
|
||||||
|
services.Lidarr = arr.NewLidarr(cfg.Services.Lidarr)
|
||||||
|
}
|
||||||
|
|
||||||
|
mx, err := matrix.New(cfg.Matrix)
|
||||||
|
if err != nil {
|
||||||
|
slog.Error("matrix init failed", "err", err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
defer cancel()
|
||||||
|
|
||||||
|
dispatcher := bot.New(ctx, cfg.Matrix.CommandPrefix, services, mx)
|
||||||
|
mx.SetMessageHandler(dispatcher.Handle)
|
||||||
|
|
||||||
|
if err := mx.Start(ctx); err != nil {
|
||||||
|
slog.Error("matrix start failed", "err", err)
|
||||||
|
mx.Stop()
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
slog.Info("bellhop started", "allowed_rooms", len(cfg.Matrix.AllowedRooms))
|
||||||
|
|
||||||
|
sig := make(chan os.Signal, 1)
|
||||||
|
signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM)
|
||||||
|
<-sig
|
||||||
|
|
||||||
|
slog.Info("shutting down")
|
||||||
|
cancel()
|
||||||
|
mx.Stop()
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user