Compare commits
7 Commits
f4a718d44b
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8f38d3d9f4 | ||
|
|
035089c159 | ||
|
|
8c295d183b | ||
|
|
0de6dd8c0d | ||
|
|
206b378d93 | ||
|
|
5c7d21e574 | ||
|
|
5a706fedc4 |
@@ -1,5 +1,4 @@
|
||||
.git
|
||||
__pycache__
|
||||
*.pyc
|
||||
.env
|
||||
bellhop.db
|
||||
data/
|
||||
config.yaml
|
||||
bellhop
|
||||
|
||||
30
.env.example
30
.env.example
@@ -1,30 +0,0 @@
|
||||
# Matrix homeserver
|
||||
MATRIX_HOMESERVER_URL=https://matrix.example.com
|
||||
|
||||
# Matrix audit bot (pre-authenticated)
|
||||
MATRIX_AUDIT_ROOM_ID=!roomid:example.com
|
||||
MATRIX_BOT_USER_ID=@bot:example.com
|
||||
MATRIX_BOT_ACCESS_TOKEN=syt_bot_token_here
|
||||
|
||||
# Radarr
|
||||
RADARR_URL=https://radarr.example.com
|
||||
RADARR_API_KEY=your_radarr_api_key
|
||||
RADARR_QUALITY_PROFILE_ID=1
|
||||
RADARR_ROOT_FOLDER=/movies
|
||||
|
||||
# Sonarr
|
||||
SONARR_URL=https://sonarr.example.com
|
||||
SONARR_API_KEY=your_sonarr_api_key
|
||||
SONARR_QUALITY_PROFILE_ID=1
|
||||
SONARR_ROOT_FOLDER=/tv
|
||||
|
||||
# Lidarr
|
||||
LIDARR_URL=https://lidarr.example.com
|
||||
LIDARR_API_KEY=your_lidarr_api_key
|
||||
LIDARR_QUALITY_PROFILE_ID=1
|
||||
LIDARR_ROOT_FOLDER=/music
|
||||
|
||||
# App
|
||||
# SESSION_SECRET_KEY is auto-generated if omitted. A new key on every restart invalidates all sessions.
|
||||
# SESSION_SECRET_KEY=
|
||||
DATABASE_PATH=bellhop.db
|
||||
9
.gitignore
vendored
9
.gitignore
vendored
@@ -1,6 +1,3 @@
|
||||
__pycache__/
|
||||
*.pyc
|
||||
.env
|
||||
bellhop.db
|
||||
*.sqlite
|
||||
*.sqlite3
|
||||
/bellhop
|
||||
/data/
|
||||
config.yaml
|
||||
|
||||
27
Dockerfile
27
Dockerfile
@@ -1,12 +1,21 @@
|
||||
FROM python:3.12-slim
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY requirements.txt .
|
||||
RUN pip install --no-cache-dir -r requirements.txt
|
||||
# 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 ./
|
||||
|
||||
EXPOSE 8000
|
||||
|
||||
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]
|
||||
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
|
||||
|
||||
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)
|
||||
──► Radarr / Sonarr / Lidarr (search + add)
|
||||
──► Matrix room (audit log)
|
||||
──► SQLite (session storage)
|
||||
!movie <query> — add the top Radarr hit
|
||||
!tv <query> — add the top Sonarr hit
|
||||
!music <query> — add the top Lidarr hit
|
||||
!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+
|
||||
- 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
|
||||
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.
|
||||
|
||||
## 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
|
||||
git clone https://github.com/prosolis/Bellhop.git
|
||||
cd Bellhop
|
||||
cp .env.example .env
|
||||
```
|
||||
Required:
|
||||
|
||||
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
|
||||
pip install -r requirements.txt
|
||||
uvicorn app.main:app --host 0.0.0.0 --port 8000
|
||||
```
|
||||
Omit a service block to disable its command — `!movie` with no `radarr` block replies "Radarr is not configured".
|
||||
|
||||
Open `http://localhost:8000` in your browser.
|
||||
|
||||
### 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:
|
||||
**Finding quality profile IDs:**
|
||||
|
||||
```bash
|
||||
curl -H "X-Api-Key: YOUR_KEY" https://radarr.example.com/api/v3/qualityprofile
|
||||
```
|
||||
|
||||
### Audit Bot (optional)
|
||||
## Running
|
||||
|
||||
| Variable | Default | Description |
|
||||
|---|---|---|
|
||||
| `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:**
|
||||
### Local
|
||||
|
||||
```bash
|
||||
curl -X POST https://matrix.example.com/_matrix/client/v3/login \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"type":"m.login.password","identifier":{"type":"m.id.user","user":"@bellhop-bot:example.com"},"password":"bot-password"}'
|
||||
go build -tags goolm -o bellhop ./
|
||||
./bellhop -config config.toml
|
||||
```
|
||||
|
||||
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 |
|
||||
|---|---|---|
|
||||
| `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. |
|
||||
| `DATABASE_PATH` | `bellhop.db` | Path to the SQLite database file |
|
||||
|
||||
## API Reference
|
||||
|
||||
### 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"
|
||||
}
|
||||
```bash
|
||||
docker build -t bellhop .
|
||||
docker run -d \
|
||||
--name bellhop \
|
||||
-v "$PWD/config.toml:/app/config.toml:ro" \
|
||||
-v bellhop-data:/app/data \
|
||||
bellhop
|
||||
```
|
||||
|
||||
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
|
||||
{
|
||||
"user_id": "@user:example.com"
|
||||
}
|
||||
```
|
||||
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.
|
||||
|
||||
A `bellhop_session` cookie is set automatically.
|
||||
|
||||
### 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
|
||||
## Project layout
|
||||
|
||||
```
|
||||
Bellhop/
|
||||
├── app/
|
||||
│ ├── __init__.py
|
||||
│ ├── main.py # FastAPI app, lifespan, rate limiter, route mounting
|
||||
│ ├── config.py # Environment variable loading
|
||||
│ ├── database.py # Async SQLite session CRUD
|
||||
│ ├── 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
|
||||
main.go
|
||||
internal/
|
||||
config/ — TOML loader with ${ENV_VAR} expansion
|
||||
matrix/ — mautrix client: login, device persistence, E2EE, sync loop
|
||||
arr/ — Radarr/Sonarr/Lidarr HTTP clients
|
||||
bot/ — command parser + dispatch + threaded replies
|
||||
```
|
||||
|
||||
## 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
|
||||
|
||||
See repository for license details.
|
||||
|
||||
57
SESSION_PLAN.md
Normal file
57
SESSION_PLAN.md
Normal file
@@ -0,0 +1,57 @@
|
||||
# Bellhop Go Rewrite — Session Plan
|
||||
|
||||
Rewriting Bellhop from a Python FastAPI web portal into a Go-based Matrix command bot, modeled after [Pete](../pete). Users issue commands like `!movie dune` in allowlisted Matrix rooms; the bot performs the top-hit search against Radarr/Sonarr/Lidarr and adds the result.
|
||||
|
||||
## Design decisions (locked in)
|
||||
|
||||
- **Command UX:** top-hit auto-add (no numbered picker, no reaction selector).
|
||||
- **Authz:** any member of an allowlisted room ID can issue commands. No per-user list.
|
||||
- **Old Python code:** deleted, clean-slate Go rewrite.
|
||||
- **Module layout:** mirrors Pete (`main.go` + `internal/<pkg>/`).
|
||||
- **Config:** YAML with `${ENV_VAR}` expansion (Pete-style).
|
||||
- **Matrix client:** mautrix-go with cryptohelper for E2EE support.
|
||||
|
||||
## Session breakdown
|
||||
|
||||
- [x] **Session 1 — Foundation**
|
||||
- Delete Python (`app/`, `requirements.txt`, `Dockerfile`, `.env.example`)
|
||||
- Reset `.gitignore` / `.dockerignore` for Go
|
||||
- `go.mod` (mautrix + yaml)
|
||||
- `internal/config/config.go` — YAML loader: matrix creds, `allowed_rooms`, `services.{radarr,sonarr,lidarr}`
|
||||
|
||||
- [x] **Session 2 — Matrix client** (`internal/matrix/`)
|
||||
- Adapt Pete's `client.go`: login + device persistence + cryptohelper
|
||||
- Sync loop, auto-join on invite
|
||||
- Message handler scoped to `allowed_rooms` (not channel-name map like Pete)
|
||||
- Threaded reply helper for command responses
|
||||
- Drop Pete-specific bits: image upload, reaction handler, story formatting
|
||||
|
||||
- [x] **Session 3 — *arr clients** (`internal/arr/`)
|
||||
- One file per service or a single generic client (TBD in session)
|
||||
- `Search(term) → []Result` and `Add(result) → error`
|
||||
- Radarr: `/api/v3/movie/lookup` + POST `/api/v3/movie`
|
||||
- Sonarr: `/api/v3/series/lookup` + POST `/api/v3/series`
|
||||
- Lidarr: `/api/v1/artist/lookup` + POST `/api/v1/artist`
|
||||
- All adds: monitored=true, search-on-add=true, quality profile + root folder from config
|
||||
- Unit tests with httptest
|
||||
|
||||
- [x] **Session 4 — Command dispatch + main** (`internal/bot/`, `main.go`)
|
||||
- Parse `<prefix><cmd> <query>` (default prefix `!`)
|
||||
- Commands: `movie`, `tv`, `music`, `help`
|
||||
- On match: search → take `[0]` → add → reply with title/year (or error)
|
||||
- "Service not configured" reply if the corresponding *arr block is absent
|
||||
- `main.go`: load config, init matrix, wire handler, SIGINT/SIGTERM shutdown
|
||||
|
||||
- [x] **Session 5 — Ship polish**
|
||||
- Multi-stage Dockerfile (`golang:1.25-alpine` → `alpine:3.21`, build with `-tags goolm`)
|
||||
- `config.example.yaml`
|
||||
- Rewrite `README.md`: command UX, install, config reference, Docker
|
||||
- `go build ./...` + `go vet ./...` clean
|
||||
|
||||
## Out of scope (for now)
|
||||
|
||||
- Reaction-based result picker
|
||||
- Per-user allowlist or power-level gating
|
||||
- Persistent request audit log (the Matrix room itself is the audit trail since requests are in-channel)
|
||||
- Removal/cancellation commands
|
||||
- Search-only mode (browse without adding)
|
||||
234
app/arr.py
234
app/arr.py
@@ -1,234 +0,0 @@
|
||||
"""Proxy layer for Radarr, Sonarr, and Lidarr APIs."""
|
||||
|
||||
import httpx
|
||||
from fastapi import APIRouter, Request
|
||||
from fastapi.responses import JSONResponse
|
||||
|
||||
from app.auth import require_session
|
||||
from app.audit import send_audit_message
|
||||
from app.config import (
|
||||
LIDARR_API_KEY,
|
||||
LIDARR_QUALITY_PROFILE_ID,
|
||||
LIDARR_ROOT_FOLDER,
|
||||
LIDARR_URL,
|
||||
RADARR_API_KEY,
|
||||
RADARR_QUALITY_PROFILE_ID,
|
||||
RADARR_ROOT_FOLDER,
|
||||
RADARR_URL,
|
||||
SONARR_API_KEY,
|
||||
SONARR_QUALITY_PROFILE_ID,
|
||||
SONARR_ROOT_FOLDER,
|
||||
SONARR_URL,
|
||||
)
|
||||
|
||||
router = APIRouter(tags=["arr"])
|
||||
|
||||
SERVICE_CONFIG = {
|
||||
"movie": {
|
||||
"url": RADARR_URL,
|
||||
"api_key": RADARR_API_KEY,
|
||||
"quality_profile_id": RADARR_QUALITY_PROFILE_ID,
|
||||
"root_folder": RADARR_ROOT_FOLDER,
|
||||
"lookup_path": "/api/v3/movie/lookup",
|
||||
"add_path": "/api/v3/movie",
|
||||
"label": "Movie",
|
||||
},
|
||||
"tv": {
|
||||
"url": SONARR_URL,
|
||||
"api_key": SONARR_API_KEY,
|
||||
"quality_profile_id": SONARR_QUALITY_PROFILE_ID,
|
||||
"root_folder": SONARR_ROOT_FOLDER,
|
||||
"lookup_path": "/api/v3/series/lookup",
|
||||
"add_path": "/api/v3/series",
|
||||
"label": "Show",
|
||||
},
|
||||
"music": {
|
||||
"url": LIDARR_URL,
|
||||
"api_key": LIDARR_API_KEY,
|
||||
"quality_profile_id": LIDARR_QUALITY_PROFILE_ID,
|
||||
"root_folder": LIDARR_ROOT_FOLDER,
|
||||
"lookup_path": "/api/v1/artist/lookup",
|
||||
"add_path": "/api/v1/artist",
|
||||
"label": "Artist",
|
||||
},
|
||||
}
|
||||
|
||||
VALID_TYPES = set(SERVICE_CONFIG.keys())
|
||||
|
||||
|
||||
def _headers(api_key: str) -> dict[str, str]:
|
||||
return {"X-Api-Key": api_key}
|
||||
|
||||
|
||||
def _safe_result_movie(item: dict) -> dict:
|
||||
return {
|
||||
"title": item.get("title", ""),
|
||||
"year": item.get("year"),
|
||||
"tmdbId": item.get("tmdbId"),
|
||||
"overview": item.get("overview", ""),
|
||||
"remotePoster": item.get("remotePoster", ""),
|
||||
"hasFile": item.get("hasFile", False),
|
||||
}
|
||||
|
||||
|
||||
def _safe_result_tv(item: dict) -> dict:
|
||||
return {
|
||||
"title": item.get("title", ""),
|
||||
"year": item.get("year"),
|
||||
"tvdbId": item.get("tvdbId"),
|
||||
"overview": item.get("overview", ""),
|
||||
"remotePoster": item.get("remotePoster", ""),
|
||||
"statistics": item.get("statistics", {}),
|
||||
}
|
||||
|
||||
|
||||
def _safe_result_music(item: dict) -> dict:
|
||||
return {
|
||||
"artistName": item.get("artistName", ""),
|
||||
"foreignArtistId": item.get("foreignArtistId", ""),
|
||||
"overview": item.get("overview", ""),
|
||||
"remotePoster": (item.get("images") or [{}])[0].get("remoteUrl", "") if item.get("images") else "",
|
||||
}
|
||||
|
||||
|
||||
SAFE_MAPPERS = {
|
||||
"movie": _safe_result_movie,
|
||||
"tv": _safe_result_tv,
|
||||
"music": _safe_result_music,
|
||||
}
|
||||
|
||||
|
||||
@router.get("/search/{media_type}")
|
||||
async def search(media_type: str, term: str, request: Request) -> JSONResponse:
|
||||
session = await require_session(request)
|
||||
if not session:
|
||||
return JSONResponse({"error": "Not authenticated"}, status_code=401)
|
||||
|
||||
if media_type not in VALID_TYPES:
|
||||
return JSONResponse({"error": f"Invalid type. Must be one of: {', '.join(VALID_TYPES)}"}, status_code=400)
|
||||
|
||||
if not term or not term.strip():
|
||||
return JSONResponse({"error": "Search term is required"}, status_code=400)
|
||||
|
||||
cfg = SERVICE_CONFIG[media_type]
|
||||
if not cfg["url"] or not cfg["api_key"]:
|
||||
return JSONResponse({"error": f"{cfg['label']} service is not configured"}, status_code=503)
|
||||
|
||||
lookup_url = f"{cfg['url'].rstrip('/')}{cfg['lookup_path']}"
|
||||
params = {"term": term.strip()}
|
||||
|
||||
async with httpx.AsyncClient() as client:
|
||||
try:
|
||||
resp = await client.get(
|
||||
lookup_url,
|
||||
params=params,
|
||||
headers=_headers(cfg["api_key"]),
|
||||
timeout=15.0,
|
||||
)
|
||||
except httpx.RequestError:
|
||||
return JSONResponse({"error": f"Could not reach {cfg['label']} service"}, status_code=502)
|
||||
|
||||
if resp.status_code != 200:
|
||||
return JSONResponse({"error": f"{cfg['label']} lookup failed"}, status_code=resp.status_code)
|
||||
|
||||
results = resp.json()
|
||||
mapper = SAFE_MAPPERS[media_type]
|
||||
safe_results = [mapper(item) for item in results[:25]]
|
||||
|
||||
return JSONResponse(safe_results)
|
||||
|
||||
|
||||
@router.post("/request/{media_type}")
|
||||
async def add_request(media_type: str, request: Request) -> JSONResponse:
|
||||
session = await require_session(request)
|
||||
if not session:
|
||||
return JSONResponse({"error": "Not authenticated"}, status_code=401)
|
||||
|
||||
if media_type not in VALID_TYPES:
|
||||
return JSONResponse({"error": f"Invalid type. Must be one of: {', '.join(VALID_TYPES)}"}, status_code=400)
|
||||
|
||||
body = await request.json()
|
||||
cfg = SERVICE_CONFIG[media_type]
|
||||
|
||||
if not cfg["url"] or not cfg["api_key"]:
|
||||
return JSONResponse({"error": f"{cfg['label']} service is not configured"}, status_code=503)
|
||||
|
||||
add_url = f"{cfg['url'].rstrip('/')}{cfg['add_path']}"
|
||||
|
||||
if media_type == "movie":
|
||||
payload = _build_movie_payload(body, cfg)
|
||||
title_display = f"\"{body.get('title', 'Unknown')}\" ({body.get('year', '?')})"
|
||||
elif media_type == "tv":
|
||||
payload = _build_tv_payload(body, cfg)
|
||||
title_display = f"\"{body.get('title', 'Unknown')}\" ({body.get('year', '?')})"
|
||||
else:
|
||||
payload = _build_music_payload(body, cfg)
|
||||
title_display = f"\"{body.get('artistName', 'Unknown')}\" ({body.get('foreignArtistId', '?')})"
|
||||
|
||||
async with httpx.AsyncClient() as client:
|
||||
try:
|
||||
resp = await client.post(
|
||||
add_url,
|
||||
json=payload,
|
||||
headers=_headers(cfg["api_key"]),
|
||||
timeout=15.0,
|
||||
)
|
||||
except httpx.RequestError:
|
||||
return JSONResponse({"error": f"Could not reach {cfg['label']} service"}, status_code=502)
|
||||
|
||||
if resp.status_code not in (200, 201):
|
||||
error_detail = ""
|
||||
try:
|
||||
error_body = resp.json()
|
||||
if isinstance(error_body, list):
|
||||
error_detail = "; ".join(e.get("errorMessage", "") for e in error_body if e.get("errorMessage"))
|
||||
elif isinstance(error_body, dict):
|
||||
error_detail = error_body.get("message", "") or error_body.get("errorMessage", "")
|
||||
except Exception:
|
||||
pass
|
||||
msg = f"Failed to add to {cfg['label']}"
|
||||
if error_detail:
|
||||
msg += f": {error_detail}"
|
||||
return JSONResponse({"error": msg}, status_code=resp.status_code)
|
||||
|
||||
# Fire-and-forget audit message
|
||||
user_id = session["matrix_user_id"]
|
||||
audit_msg = f"[REQUEST] {user_id} → [{cfg['label']}] {title_display}"
|
||||
send_audit_message(audit_msg)
|
||||
|
||||
return JSONResponse({"ok": True, "message": f"{cfg['label']} added successfully"})
|
||||
|
||||
|
||||
def _build_movie_payload(body: dict, cfg: dict) -> dict:
|
||||
return {
|
||||
"title": body.get("title", ""),
|
||||
"tmdbId": body.get("tmdbId"),
|
||||
"year": body.get("year"),
|
||||
"qualityProfileId": cfg["quality_profile_id"],
|
||||
"rootFolderPath": cfg["root_folder"],
|
||||
"monitored": True,
|
||||
"addOptions": {"searchForMovie": True},
|
||||
}
|
||||
|
||||
|
||||
def _build_tv_payload(body: dict, cfg: dict) -> dict:
|
||||
return {
|
||||
"title": body.get("title", ""),
|
||||
"tvdbId": body.get("tvdbId"),
|
||||
"year": body.get("year"),
|
||||
"qualityProfileId": cfg["quality_profile_id"],
|
||||
"rootFolderPath": cfg["root_folder"],
|
||||
"monitored": True,
|
||||
"addOptions": {"searchForMissingEpisodes": True},
|
||||
}
|
||||
|
||||
|
||||
def _build_music_payload(body: dict, cfg: dict) -> dict:
|
||||
return {
|
||||
"artistName": body.get("artistName", ""),
|
||||
"foreignArtistId": body.get("foreignArtistId", ""),
|
||||
"qualityProfileId": cfg["quality_profile_id"],
|
||||
"rootFolderPath": cfg["root_folder"],
|
||||
"monitored": True,
|
||||
"addOptions": {"searchForMissingAlbums": True},
|
||||
}
|
||||
51
app/audit.py
51
app/audit.py
@@ -1,51 +0,0 @@
|
||||
"""Matrix audit log — fire-and-forget messages to an unencrypted room."""
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
|
||||
import httpx
|
||||
|
||||
from app.config import (
|
||||
MATRIX_AUDIT_ROOM_ID,
|
||||
MATRIX_BOT_ACCESS_TOKEN,
|
||||
MATRIX_HOMESERVER_URL,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def send_audit_message(message: str) -> None:
|
||||
"""Schedule an audit message to be sent without blocking the caller."""
|
||||
if not MATRIX_AUDIT_ROOM_ID or not MATRIX_BOT_ACCESS_TOKEN:
|
||||
logger.debug("Audit log not configured, skipping")
|
||||
return
|
||||
|
||||
try:
|
||||
loop = asyncio.get_running_loop()
|
||||
except RuntimeError:
|
||||
return
|
||||
|
||||
loop.create_task(_send(message))
|
||||
|
||||
|
||||
async def _send(message: str) -> None:
|
||||
import time
|
||||
|
||||
room_id = MATRIX_AUDIT_ROOM_ID
|
||||
txn_id = str(int(time.time() * 1000))
|
||||
|
||||
url = (
|
||||
f"{MATRIX_HOMESERVER_URL.rstrip('/')}/_matrix/client/v3/rooms/"
|
||||
f"{room_id}/send/m.room.message/{txn_id}"
|
||||
)
|
||||
body = {
|
||||
"msgtype": "m.text",
|
||||
"body": message,
|
||||
}
|
||||
headers = {"Authorization": f"Bearer {MATRIX_BOT_ACCESS_TOKEN}"}
|
||||
|
||||
try:
|
||||
async with httpx.AsyncClient() as client:
|
||||
await client.put(url, json=body, headers=headers, timeout=10.0)
|
||||
except Exception:
|
||||
logger.warning("Failed to send audit message: %s", message, exc_info=True)
|
||||
131
app/auth.py
131
app/auth.py
@@ -1,131 +0,0 @@
|
||||
import httpx
|
||||
from fastapi import APIRouter, Request, Response
|
||||
from fastapi.responses import JSONResponse
|
||||
|
||||
from app.config import MATRIX_HOMESERVER_URL
|
||||
from app.database import create_session, delete_session, get_session
|
||||
|
||||
router = APIRouter(prefix="/auth", tags=["auth"])
|
||||
|
||||
SESSION_COOKIE = "bellhop_session"
|
||||
MAX_SESSION_AGE = 60 * 60 * 24 * 7 # 7 days
|
||||
|
||||
|
||||
@router.post("/login")
|
||||
async def login(request: Request) -> Response:
|
||||
body = await request.json()
|
||||
username: str = body.get("username", "").strip()
|
||||
password: str = body.get("password", "")
|
||||
|
||||
if not username or not password:
|
||||
return JSONResponse({"error": "Username and password are required"}, status_code=400)
|
||||
|
||||
# Build the Matrix user identifier
|
||||
if username.startswith("@"):
|
||||
user_identifier = username
|
||||
else:
|
||||
user_identifier = username # let the homeserver resolve it
|
||||
|
||||
login_url = f"{MATRIX_HOMESERVER_URL.rstrip('/')}/_matrix/client/v3/login"
|
||||
payload = {
|
||||
"type": "m.login.password",
|
||||
"identifier": {"type": "m.id.user", "user": user_identifier},
|
||||
"password": password,
|
||||
}
|
||||
|
||||
async with httpx.AsyncClient() as client:
|
||||
try:
|
||||
resp = await client.post(login_url, json=payload, timeout=15.0)
|
||||
except httpx.RequestError:
|
||||
return JSONResponse({"error": "Could not reach Matrix homeserver"}, status_code=502)
|
||||
|
||||
if resp.status_code != 200:
|
||||
error_msg = resp.json().get("error", "Authentication failed")
|
||||
return JSONResponse({"error": error_msg}, status_code=401)
|
||||
|
||||
data = resp.json()
|
||||
matrix_user_id: str = data["user_id"]
|
||||
matrix_access_token: str = data["access_token"]
|
||||
|
||||
session_id = await create_session(matrix_user_id, matrix_access_token)
|
||||
|
||||
response = JSONResponse({"user_id": matrix_user_id})
|
||||
response.set_cookie(
|
||||
key=SESSION_COOKIE,
|
||||
value=session_id,
|
||||
httponly=True,
|
||||
samesite="strict",
|
||||
secure=True,
|
||||
max_age=MAX_SESSION_AGE,
|
||||
)
|
||||
return response
|
||||
|
||||
|
||||
@router.post("/logout")
|
||||
async def logout(request: Request) -> Response:
|
||||
session_id = request.cookies.get(SESSION_COOKIE)
|
||||
if session_id:
|
||||
await delete_session(session_id)
|
||||
response = JSONResponse({"ok": True})
|
||||
response.delete_cookie(key=SESSION_COOKIE)
|
||||
return response
|
||||
|
||||
|
||||
@router.get("/me")
|
||||
async def me(request: Request) -> Response:
|
||||
session_id = request.cookies.get(SESSION_COOKIE)
|
||||
if not session_id:
|
||||
return JSONResponse({"error": "Not authenticated"}, status_code=401)
|
||||
|
||||
session = await get_session(session_id)
|
||||
if not session:
|
||||
return JSONResponse({"error": "Not authenticated"}, status_code=401)
|
||||
|
||||
# Verify token is still valid with the homeserver
|
||||
whoami_url = f"{MATRIX_HOMESERVER_URL.rstrip('/')}/_matrix/client/v3/account/whoami"
|
||||
async with httpx.AsyncClient() as client:
|
||||
try:
|
||||
resp = await client.get(
|
||||
whoami_url,
|
||||
headers={"Authorization": f"Bearer {session['matrix_access_token']}"},
|
||||
timeout=10.0,
|
||||
)
|
||||
except httpx.RequestError:
|
||||
# If homeserver is unreachable, trust the local session
|
||||
return JSONResponse({"user_id": session["matrix_user_id"]})
|
||||
|
||||
if resp.status_code != 200:
|
||||
await delete_session(session_id)
|
||||
response = JSONResponse({"error": "Session expired"}, status_code=401)
|
||||
response.delete_cookie(key=SESSION_COOKIE)
|
||||
return response
|
||||
|
||||
return JSONResponse({"user_id": session["matrix_user_id"]})
|
||||
|
||||
|
||||
async def require_session(request: Request) -> dict | None:
|
||||
"""Utility: extract and validate session from a request. Returns session dict or None."""
|
||||
session_id = request.cookies.get(SESSION_COOKIE)
|
||||
if not session_id:
|
||||
return None
|
||||
session = await get_session(session_id)
|
||||
if not session:
|
||||
return None
|
||||
|
||||
# Verify token is still valid
|
||||
whoami_url = f"{MATRIX_HOMESERVER_URL.rstrip('/')}/_matrix/client/v3/account/whoami"
|
||||
async with httpx.AsyncClient() as client:
|
||||
try:
|
||||
resp = await client.get(
|
||||
whoami_url,
|
||||
headers={"Authorization": f"Bearer {session['matrix_access_token']}"},
|
||||
timeout=10.0,
|
||||
)
|
||||
except httpx.RequestError:
|
||||
return session # trust local session if homeserver unreachable
|
||||
|
||||
if resp.status_code != 200:
|
||||
await delete_session(session_id)
|
||||
return None
|
||||
|
||||
return session
|
||||
@@ -1,43 +0,0 @@
|
||||
import os
|
||||
import secrets
|
||||
from pathlib import Path
|
||||
|
||||
from dotenv import load_dotenv
|
||||
|
||||
load_dotenv()
|
||||
|
||||
|
||||
def _require(name: str) -> str:
|
||||
val = os.getenv(name)
|
||||
if not val:
|
||||
raise RuntimeError(f"Missing required environment variable: {name}")
|
||||
return val
|
||||
|
||||
|
||||
# Matrix
|
||||
MATRIX_HOMESERVER_URL: str = _require("MATRIX_HOMESERVER_URL")
|
||||
MATRIX_AUDIT_ROOM_ID: str = os.getenv("MATRIX_AUDIT_ROOM_ID", "")
|
||||
MATRIX_BOT_USER_ID: str = os.getenv("MATRIX_BOT_USER_ID", "")
|
||||
MATRIX_BOT_ACCESS_TOKEN: str = os.getenv("MATRIX_BOT_ACCESS_TOKEN", "")
|
||||
|
||||
# Radarr
|
||||
RADARR_URL: str = os.getenv("RADARR_URL", "")
|
||||
RADARR_API_KEY: str = os.getenv("RADARR_API_KEY", "")
|
||||
RADARR_QUALITY_PROFILE_ID: int = int(os.getenv("RADARR_QUALITY_PROFILE_ID", "1"))
|
||||
RADARR_ROOT_FOLDER: str = os.getenv("RADARR_ROOT_FOLDER", "/movies")
|
||||
|
||||
# Sonarr
|
||||
SONARR_URL: str = os.getenv("SONARR_URL", "")
|
||||
SONARR_API_KEY: str = os.getenv("SONARR_API_KEY", "")
|
||||
SONARR_QUALITY_PROFILE_ID: int = int(os.getenv("SONARR_QUALITY_PROFILE_ID", "1"))
|
||||
SONARR_ROOT_FOLDER: str = os.getenv("SONARR_ROOT_FOLDER", "/tv")
|
||||
|
||||
# Lidarr
|
||||
LIDARR_URL: str = os.getenv("LIDARR_URL", "")
|
||||
LIDARR_API_KEY: str = os.getenv("LIDARR_API_KEY", "")
|
||||
LIDARR_QUALITY_PROFILE_ID: int = int(os.getenv("LIDARR_QUALITY_PROFILE_ID", "1"))
|
||||
LIDARR_ROOT_FOLDER: str = os.getenv("LIDARR_ROOT_FOLDER", "/music")
|
||||
|
||||
# App
|
||||
SESSION_SECRET_KEY: str = os.getenv("SESSION_SECRET_KEY") or secrets.token_urlsafe(32)
|
||||
DATABASE_PATH: str = os.getenv("DATABASE_PATH", "bellhop.db")
|
||||
@@ -1,73 +0,0 @@
|
||||
import secrets
|
||||
import time
|
||||
|
||||
import aiosqlite
|
||||
|
||||
from app.config import DATABASE_PATH
|
||||
|
||||
_db: aiosqlite.Connection | None = None
|
||||
|
||||
|
||||
async def get_db() -> aiosqlite.Connection:
|
||||
global _db
|
||||
if _db is None:
|
||||
_db = await aiosqlite.connect(DATABASE_PATH)
|
||||
_db.row_factory = aiosqlite.Row
|
||||
await _db.execute("PRAGMA journal_mode=WAL")
|
||||
await _db.execute(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS sessions (
|
||||
session_id TEXT PRIMARY KEY,
|
||||
matrix_user_id TEXT NOT NULL,
|
||||
matrix_access_token TEXT NOT NULL,
|
||||
created_at REAL NOT NULL,
|
||||
last_seen REAL NOT NULL
|
||||
)
|
||||
"""
|
||||
)
|
||||
await _db.commit()
|
||||
return _db
|
||||
|
||||
|
||||
async def close_db() -> None:
|
||||
global _db
|
||||
if _db is not None:
|
||||
await _db.close()
|
||||
_db = None
|
||||
|
||||
|
||||
async def create_session(matrix_user_id: str, matrix_access_token: str) -> str:
|
||||
db = await get_db()
|
||||
session_id = secrets.token_urlsafe(32)
|
||||
now = time.time()
|
||||
await db.execute(
|
||||
"INSERT INTO sessions (session_id, matrix_user_id, matrix_access_token, created_at, last_seen) "
|
||||
"VALUES (?, ?, ?, ?, ?)",
|
||||
(session_id, matrix_user_id, matrix_access_token, now, now),
|
||||
)
|
||||
await db.commit()
|
||||
return session_id
|
||||
|
||||
|
||||
async def get_session(session_id: str) -> dict | None:
|
||||
db = await get_db()
|
||||
cursor = await db.execute(
|
||||
"SELECT session_id, matrix_user_id, matrix_access_token, created_at, last_seen "
|
||||
"FROM sessions WHERE session_id = ?",
|
||||
(session_id,),
|
||||
)
|
||||
row = await cursor.fetchone()
|
||||
if row is None:
|
||||
return None
|
||||
await db.execute(
|
||||
"UPDATE sessions SET last_seen = ? WHERE session_id = ?",
|
||||
(time.time(), session_id),
|
||||
)
|
||||
await db.commit()
|
||||
return dict(row)
|
||||
|
||||
|
||||
async def delete_session(session_id: str) -> None:
|
||||
db = await get_db()
|
||||
await db.execute("DELETE FROM sessions WHERE session_id = ?", (session_id,))
|
||||
await db.commit()
|
||||
48
app/main.py
48
app/main.py
@@ -1,48 +0,0 @@
|
||||
from contextlib import asynccontextmanager
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi import FastAPI, Request
|
||||
from fastapi.responses import HTMLResponse
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
from slowapi import Limiter, _rate_limit_exceeded_handler
|
||||
from slowapi.errors import RateLimitExceeded
|
||||
from slowapi.util import get_remote_address
|
||||
|
||||
from app.auth import router as auth_router
|
||||
from app.arr import router as arr_router
|
||||
from app.database import close_db, get_db
|
||||
|
||||
BASE_DIR = Path(__file__).resolve().parent
|
||||
|
||||
limiter = Limiter(key_func=get_remote_address)
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
await get_db()
|
||||
yield
|
||||
await close_db()
|
||||
|
||||
|
||||
app = FastAPI(title="Bellhop", lifespan=lifespan)
|
||||
app.state.limiter = limiter
|
||||
app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)
|
||||
|
||||
# Mount static files
|
||||
app.mount("/static", StaticFiles(directory=str(BASE_DIR / "static")), name="static")
|
||||
|
||||
# Apply rate limit to login specifically
|
||||
original_login = auth_router.routes
|
||||
for route in auth_router.routes:
|
||||
if hasattr(route, "path") and route.path == "/login" and hasattr(route, "endpoint"):
|
||||
route.endpoint = limiter.limit("5/minute")(route.endpoint)
|
||||
break
|
||||
|
||||
app.include_router(auth_router)
|
||||
app.include_router(arr_router)
|
||||
|
||||
|
||||
@app.get("/", response_class=HTMLResponse)
|
||||
async def index():
|
||||
html_path = BASE_DIR / "templates" / "index.html"
|
||||
return HTMLResponse(html_path.read_text())
|
||||
@@ -1,355 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Bellhop</title>
|
||||
<script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js"></script>
|
||||
<style>
|
||||
:root {
|
||||
--bg: #0f0f0f;
|
||||
--surface: #1a1a2e;
|
||||
--surface2: #16213e;
|
||||
--primary: #e94560;
|
||||
--primary-hover: #c73650;
|
||||
--text: #eee;
|
||||
--text-muted: #999;
|
||||
--border: #333;
|
||||
--success: #2ecc71;
|
||||
--error: #e74c3c;
|
||||
}
|
||||
* { box-sizing: border-box; margin: 0; padding: 0; }
|
||||
body {
|
||||
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
|
||||
background: var(--bg);
|
||||
color: var(--text);
|
||||
min-height: 100vh;
|
||||
}
|
||||
.container { max-width: 960px; margin: 0 auto; padding: 1.5rem; }
|
||||
header {
|
||||
display: flex; justify-content: space-between; align-items: center;
|
||||
padding: 1rem 0; border-bottom: 1px solid var(--border); margin-bottom: 1.5rem;
|
||||
}
|
||||
header h1 { font-size: 1.5rem; letter-spacing: 0.05em; }
|
||||
header h1 span { color: var(--primary); }
|
||||
.btn {
|
||||
padding: 0.5rem 1rem; border: none; border-radius: 6px;
|
||||
cursor: pointer; font-size: 0.9rem; font-weight: 500;
|
||||
transition: background 0.2s;
|
||||
}
|
||||
.btn-primary { background: var(--primary); color: #fff; }
|
||||
.btn-primary:hover { background: var(--primary-hover); }
|
||||
.btn-primary:disabled { opacity: 0.5; cursor: not-allowed; }
|
||||
.btn-ghost {
|
||||
background: transparent; color: var(--text-muted); border: 1px solid var(--border);
|
||||
}
|
||||
.btn-ghost:hover { color: var(--text); border-color: var(--text-muted); }
|
||||
.btn-sm { padding: 0.35rem 0.75rem; font-size: 0.8rem; }
|
||||
|
||||
/* Login */
|
||||
.login-card {
|
||||
max-width: 380px; margin: 4rem auto; background: var(--surface);
|
||||
border-radius: 12px; padding: 2rem;
|
||||
}
|
||||
.login-card h2 { margin-bottom: 0.25rem; }
|
||||
.login-card p { color: var(--text-muted); font-size: 0.85rem; margin-bottom: 1.5rem; }
|
||||
.form-group { margin-bottom: 1rem; }
|
||||
.form-group label { display: block; font-size: 0.8rem; color: var(--text-muted); margin-bottom: 0.3rem; }
|
||||
.form-group input {
|
||||
width: 100%; padding: 0.6rem 0.75rem; background: var(--bg);
|
||||
border: 1px solid var(--border); border-radius: 6px; color: var(--text);
|
||||
font-size: 0.95rem;
|
||||
}
|
||||
.form-group input:focus { outline: none; border-color: var(--primary); }
|
||||
.error-msg { color: var(--error); font-size: 0.85rem; margin-bottom: 0.75rem; }
|
||||
|
||||
/* Search bar */
|
||||
.search-bar {
|
||||
display: flex; gap: 0.5rem; margin-bottom: 1.5rem; flex-wrap: wrap;
|
||||
}
|
||||
.media-tabs { display: flex; gap: 0.25rem; margin-bottom: 1rem; }
|
||||
.media-tab {
|
||||
padding: 0.4rem 1rem; background: var(--surface); border: 1px solid var(--border);
|
||||
border-radius: 6px; cursor: pointer; color: var(--text-muted); font-size: 0.85rem;
|
||||
transition: all 0.2s;
|
||||
}
|
||||
.media-tab.active { background: var(--primary); color: #fff; border-color: var(--primary); }
|
||||
.search-input {
|
||||
flex: 1; min-width: 200px; padding: 0.6rem 0.75rem; background: var(--surface);
|
||||
border: 1px solid var(--border); border-radius: 6px; color: var(--text); font-size: 0.95rem;
|
||||
}
|
||||
.search-input:focus { outline: none; border-color: var(--primary); }
|
||||
|
||||
/* Results grid */
|
||||
.results-grid {
|
||||
display: grid; grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
|
||||
gap: 1rem;
|
||||
}
|
||||
.result-card {
|
||||
background: var(--surface); border-radius: 10px; overflow: hidden;
|
||||
transition: transform 0.15s;
|
||||
}
|
||||
.result-card:hover { transform: translateY(-2px); }
|
||||
.result-card img {
|
||||
width: 100%; aspect-ratio: 2/3; object-fit: cover; background: var(--surface2);
|
||||
}
|
||||
.result-card .info { padding: 0.75rem; }
|
||||
.result-card .title { font-size: 0.9rem; font-weight: 600; margin-bottom: 0.15rem; }
|
||||
.result-card .year { font-size: 0.8rem; color: var(--text-muted); margin-bottom: 0.5rem; }
|
||||
.result-card .btn { width: 100%; }
|
||||
|
||||
/* Feedback */
|
||||
.toast {
|
||||
position: fixed; bottom: 1.5rem; right: 1.5rem;
|
||||
padding: 0.75rem 1.25rem; border-radius: 8px;
|
||||
font-size: 0.9rem; color: #fff; z-index: 100;
|
||||
animation: slideIn 0.3s ease;
|
||||
}
|
||||
.toast.success { background: var(--success); }
|
||||
.toast.error { background: var(--error); }
|
||||
@keyframes slideIn {
|
||||
from { transform: translateY(1rem); opacity: 0; }
|
||||
to { transform: translateY(0); opacity: 1; }
|
||||
}
|
||||
|
||||
.spinner { display: inline-block; width: 1em; height: 1em; border: 2px solid #fff3;
|
||||
border-top-color: #fff; border-radius: 50%; animation: spin 0.6s linear infinite; }
|
||||
@keyframes spin { to { transform: rotate(360deg); } }
|
||||
|
||||
.placeholder {
|
||||
text-align: center; padding: 3rem 1rem; color: var(--text-muted);
|
||||
}
|
||||
.no-poster {
|
||||
width: 100%; aspect-ratio: 2/3; background: var(--surface2);
|
||||
display: flex; align-items: center; justify-content: center;
|
||||
color: var(--text-muted); font-size: 0.8rem;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container" x-data="bellhop()">
|
||||
|
||||
<!-- Toast -->
|
||||
<template x-if="toast.show">
|
||||
<div class="toast" :class="toast.type" x-text="toast.message"
|
||||
x-init="setTimeout(() => toast.show = false, 3000)"></div>
|
||||
</template>
|
||||
|
||||
<!-- Logged-out view -->
|
||||
<template x-if="!user">
|
||||
<div class="login-card">
|
||||
<h2>Bellhop</h2>
|
||||
<p>Sign in with your Matrix account to request media.</p>
|
||||
<div x-show="loginError" class="error-msg" x-text="loginError"></div>
|
||||
<form @submit.prevent="login">
|
||||
<div class="form-group">
|
||||
<label for="username">Matrix username</label>
|
||||
<input id="username" type="text" x-model="loginForm.username"
|
||||
placeholder="@user:example.com" required autocomplete="username">
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label for="password">Password</label>
|
||||
<input id="password" type="password" x-model="loginForm.password"
|
||||
required autocomplete="current-password">
|
||||
</div>
|
||||
<button type="submit" class="btn btn-primary" style="width:100%;margin-top:0.5rem"
|
||||
:disabled="loggingIn">
|
||||
<span x-show="!loggingIn">Sign in</span>
|
||||
<span x-show="loggingIn"><span class="spinner"></span></span>
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<!-- Logged-in view -->
|
||||
<template x-if="user">
|
||||
<div>
|
||||
<header>
|
||||
<h1><span>Bellhop</span></h1>
|
||||
<div style="display:flex;align-items:center;gap:0.75rem">
|
||||
<span style="font-size:0.85rem;color:var(--text-muted)" x-text="user"></span>
|
||||
<button class="btn btn-ghost btn-sm" @click="logout">Sign out</button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<!-- Media type tabs -->
|
||||
<div class="media-tabs">
|
||||
<template x-for="t in mediaTypes" :key="t.value">
|
||||
<button class="media-tab" :class="mediaType === t.value && 'active'"
|
||||
@click="mediaType = t.value" x-text="t.label"></button>
|
||||
</template>
|
||||
</div>
|
||||
|
||||
<!-- Search -->
|
||||
<div class="search-bar">
|
||||
<input class="search-input" type="text" x-model="searchTerm"
|
||||
@keydown.enter="search" placeholder="Search for a title...">
|
||||
<button class="btn btn-primary" @click="search" :disabled="searching">
|
||||
<span x-show="!searching">Search</span>
|
||||
<span x-show="searching"><span class="spinner"></span></span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- Results -->
|
||||
<div x-show="results.length > 0" class="results-grid">
|
||||
<template x-for="(item, idx) in results" :key="idx">
|
||||
<div class="result-card">
|
||||
<template x-if="posterUrl(item)">
|
||||
<img :src="posterUrl(item)" :alt="itemTitle(item)" loading="lazy">
|
||||
</template>
|
||||
<template x-if="!posterUrl(item)">
|
||||
<div class="no-poster">No image</div>
|
||||
</template>
|
||||
<div class="info">
|
||||
<div class="title" x-text="itemTitle(item)"></div>
|
||||
<div class="year" x-text="itemSubtitle(item)"></div>
|
||||
<button class="btn btn-primary btn-sm"
|
||||
@click="requestItem(item)" :disabled="item._requesting">
|
||||
<span x-show="!item._requesting">Request</span>
|
||||
<span x-show="item._requesting"><span class="spinner"></span></span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
|
||||
<div x-show="searched && results.length === 0" class="placeholder">
|
||||
No results found. Try a different search.
|
||||
</div>
|
||||
<div x-show="!searched && results.length === 0" class="placeholder">
|
||||
Select a media type and search for something to request.
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
function bellhop() {
|
||||
return {
|
||||
user: null,
|
||||
loginForm: { username: '', password: '' },
|
||||
loginError: '',
|
||||
loggingIn: false,
|
||||
mediaType: 'movie',
|
||||
mediaTypes: [
|
||||
{ value: 'movie', label: 'Movie' },
|
||||
{ value: 'tv', label: 'TV Show' },
|
||||
{ value: 'music', label: 'Music' },
|
||||
],
|
||||
searchTerm: '',
|
||||
results: [],
|
||||
searched: false,
|
||||
searching: false,
|
||||
toast: { show: false, type: 'success', message: '' },
|
||||
|
||||
async init() {
|
||||
try {
|
||||
const res = await fetch('/auth/me');
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
this.user = data.user_id;
|
||||
}
|
||||
} catch {}
|
||||
},
|
||||
|
||||
async login() {
|
||||
this.loginError = '';
|
||||
this.loggingIn = true;
|
||||
try {
|
||||
const res = await fetch('/auth/login', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
username: this.loginForm.username,
|
||||
password: this.loginForm.password,
|
||||
}),
|
||||
});
|
||||
const data = await res.json();
|
||||
if (res.ok) {
|
||||
this.user = data.user_id;
|
||||
this.loginForm = { username: '', password: '' };
|
||||
} else {
|
||||
this.loginError = data.error || 'Login failed';
|
||||
}
|
||||
} catch {
|
||||
this.loginError = 'Network error';
|
||||
} finally {
|
||||
this.loggingIn = false;
|
||||
}
|
||||
},
|
||||
|
||||
async logout() {
|
||||
try { await fetch('/auth/logout', { method: 'POST' }); } catch {}
|
||||
this.user = null;
|
||||
this.results = [];
|
||||
this.searched = false;
|
||||
},
|
||||
|
||||
async search() {
|
||||
if (!this.searchTerm.trim()) return;
|
||||
this.searching = true;
|
||||
this.results = [];
|
||||
this.searched = false;
|
||||
try {
|
||||
const res = await fetch(
|
||||
`/search/${this.mediaType}?term=${encodeURIComponent(this.searchTerm)}`
|
||||
);
|
||||
if (res.ok) {
|
||||
this.results = (await res.json()).map(r => ({ ...r, _requesting: false }));
|
||||
} else {
|
||||
const d = await res.json();
|
||||
this.showToast('error', d.error || 'Search failed');
|
||||
}
|
||||
} catch {
|
||||
this.showToast('error', 'Network error');
|
||||
} finally {
|
||||
this.searching = true; // keep spinner briefly
|
||||
this.searched = true;
|
||||
this.searching = false;
|
||||
}
|
||||
},
|
||||
|
||||
async requestItem(item) {
|
||||
item._requesting = true;
|
||||
try {
|
||||
const res = await fetch(`/request/${this.mediaType}`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(item),
|
||||
});
|
||||
const data = await res.json();
|
||||
if (res.ok) {
|
||||
this.showToast('success', data.message || 'Requested!');
|
||||
} else {
|
||||
this.showToast('error', data.error || 'Request failed');
|
||||
}
|
||||
} catch {
|
||||
this.showToast('error', 'Network error');
|
||||
} finally {
|
||||
item._requesting = false;
|
||||
}
|
||||
},
|
||||
|
||||
posterUrl(item) {
|
||||
return item.remotePoster || '';
|
||||
},
|
||||
|
||||
itemTitle(item) {
|
||||
return item.title || item.artistName || '—';
|
||||
},
|
||||
|
||||
itemSubtitle(item) {
|
||||
if (item.year) return String(item.year);
|
||||
if (item.foreignArtistId) return item.foreignArtistId;
|
||||
return '';
|
||||
},
|
||||
|
||||
showToast(type, message) {
|
||||
this.toast = { show: true, type, message };
|
||||
setTimeout(() => { this.toast.show = false; }, 3000);
|
||||
},
|
||||
};
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
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"
|
||||
27
go.mod
Normal file
27
go.mod
Normal file
@@ -0,0 +1,27 @@
|
||||
module bellhop
|
||||
|
||||
go 1.25.0
|
||||
|
||||
require (
|
||||
github.com/BurntSushi/toml v1.6.0
|
||||
maunium.net/go/mautrix v0.28.0
|
||||
)
|
||||
|
||||
require (
|
||||
filippo.io/edwards25519 v1.2.0 // indirect
|
||||
github.com/mattn/go-colorable v0.1.14 // indirect
|
||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||
github.com/mattn/go-sqlite3 v1.14.44 // indirect
|
||||
github.com/petermattis/goid v0.0.0-20260330135022-df67b199bc81 // indirect
|
||||
github.com/rs/zerolog v1.35.1 // indirect
|
||||
github.com/tidwall/gjson v1.19.0 // indirect
|
||||
github.com/tidwall/match v1.1.1 // indirect
|
||||
github.com/tidwall/pretty v1.2.1 // indirect
|
||||
github.com/tidwall/sjson v1.2.5 // indirect
|
||||
go.mau.fi/util v0.9.9 // indirect
|
||||
golang.org/x/crypto v0.51.0 // indirect
|
||||
golang.org/x/exp v0.0.0-20260508232706-74f9aab9d74a // indirect
|
||||
golang.org/x/net v0.54.0 // indirect
|
||||
golang.org/x/sys v0.44.0 // indirect
|
||||
golang.org/x/text v0.37.0 // indirect
|
||||
)
|
||||
49
go.sum
Normal file
49
go.sum
Normal file
@@ -0,0 +1,49 @@
|
||||
filippo.io/edwards25519 v1.2.0 h1:crnVqOiS4jqYleHd9vaKZ+HKtHfllngJIiOpNpoJsjo=
|
||||
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/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/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHPsaIE=
|
||||
github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8=
|
||||
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
|
||||
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||
github.com/mattn/go-sqlite3 v1.14.44 h1:3VSe+xafpbzsLbdr2AWlAZk9yRHiBhTBakioXaCKTF8=
|
||||
github.com/mattn/go-sqlite3 v1.14.44/go.mod h1:pjEuOr8IwzLJP2MfGeTb0A35jauH+C2kbHKBr7yXKVQ=
|
||||
github.com/petermattis/goid v0.0.0-20260330135022-df67b199bc81 h1:WDsQxOJDy0N1VRAjXLpi8sCEZRSGarLWQevDxpTBRrM=
|
||||
github.com/petermattis/goid v0.0.0-20260330135022-df67b199bc81/go.mod h1:pxMtw7cyUw6B2bRH0ZBANSPg+AoSud1I1iyJHI69jH4=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/rs/zerolog v1.35.1 h1:m7xQeoiLIiV0BCEY4Hs+j2NG4Gp2o2KPKmhnnLiazKI=
|
||||
github.com/rs/zerolog v1.35.1/go.mod h1:EjML9kdfa/RMA7h/6z6pYmq1ykOuA8/mjWaEvGI+jcw=
|
||||
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
||||
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||
github.com/tidwall/gjson v1.14.2/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk=
|
||||
github.com/tidwall/gjson v1.19.0 h1:xwxm7n691Uf3u5OFjzngavjGTh55KX5q/9w9xHW88JU=
|
||||
github.com/tidwall/gjson v1.19.0/go.mod h1:V37/opeE/JbLUOfH0QTXiNez2l0RUjYUhpT4szFQAfc=
|
||||
github.com/tidwall/match v1.1.1 h1:+Ho715JplO36QYgwN9PGYNhgZvoUSc9X2c80KVTi+GA=
|
||||
github.com/tidwall/match v1.1.1/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM=
|
||||
github.com/tidwall/pretty v1.2.0/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU=
|
||||
github.com/tidwall/pretty v1.2.1 h1:qjsOFOWWQl+N3RsoF5/ssm1pHmJJwhjlSbZ51I6wMl4=
|
||||
github.com/tidwall/pretty v1.2.1/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU=
|
||||
github.com/tidwall/sjson v1.2.5 h1:kLy8mja+1c9jlljvWTlSazM7cKDRfJuR/bOJhcY5NcY=
|
||||
github.com/tidwall/sjson v1.2.5/go.mod h1:Fvgq9kS/6ociJEDnK0Fk1cpYF4FIW6ZF7LAe+6jwd28=
|
||||
go.mau.fi/util v0.9.9 h1:ujDeXCo07HBor5oQLyO1tHklupmqVmPgasc53d7q/NE=
|
||||
go.mau.fi/util v0.9.9/go.mod h1:pqt4Vcrt+5gcH/CgrHZg11qSx+b34o6mknGzOEA6waY=
|
||||
golang.org/x/crypto v0.51.0 h1:IBPXwPfKxY7cWQZ38ZCIRPI50YLeevDLlLnyC5wRGTI=
|
||||
golang.org/x/crypto v0.51.0/go.mod h1:8AdwkbraGNABw2kOX6YFPs3WM22XqI4EXEd8g+x7Oc8=
|
||||
golang.org/x/exp v0.0.0-20260508232706-74f9aab9d74a h1:+3jdDGGB8NGb1Zktc737jlt3/A5f6UlwSzmvqUuufxw=
|
||||
golang.org/x/exp v0.0.0-20260508232706-74f9aab9d74a/go.mod h1:d2fgXJLVs4dYDHUk5lwMIfzRzSrWCfGZb0ZqeLa/Vcw=
|
||||
golang.org/x/net v0.54.0 h1:2zJIZAxAHV/OHCDTCOHAYehQzLfSXuf/5SoL/Dv6w/w=
|
||||
golang.org/x/net v0.54.0/go.mod h1:Sj4oj8jK6XmHpBZU/zWHw3BV3abl4Kvi+Ut7cQcY+cQ=
|
||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
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/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc=
|
||||
golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
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/go.mod h1:/a9A7LGaqb9B3nho4tLd28n0EPcCdwpm2dxkxkLLgh0=
|
||||
151
internal/arr/arr.go
Normal file
151
internal/arr/arr.go
Normal file
@@ -0,0 +1,151 @@
|
||||
// Package arr provides clients for Radarr, Sonarr, and Lidarr.
|
||||
//
|
||||
// Each client exposes Search to look up candidates by free-text query and
|
||||
// Add to enqueue the first/chosen candidate for download. Lookup responses
|
||||
// are preserved as raw JSON inside Result so Add can replay the entity back
|
||||
// to the *arr server with the configured profile and root folder layered on.
|
||||
package arr
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// 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
|
||||
// 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 {
|
||||
Title string
|
||||
Year int
|
||||
Exists bool
|
||||
raw json.RawMessage
|
||||
}
|
||||
|
||||
// Raw exposes the underlying lookup JSON; useful for tests and debugging.
|
||||
func (r Result) Raw() json.RawMessage { return r.raw }
|
||||
|
||||
// Client is the common interface implemented by every *arr backend.
|
||||
type Client interface {
|
||||
Search(ctx context.Context, term string) ([]Result, error)
|
||||
Add(ctx context.Context, r Result) error
|
||||
}
|
||||
|
||||
type httpClient struct {
|
||||
baseURL string
|
||||
apiKey string
|
||||
hc *http.Client
|
||||
}
|
||||
|
||||
func newHTTP(baseURL, apiKey string) *httpClient {
|
||||
return &httpClient{
|
||||
baseURL: strings.TrimRight(baseURL, "/"),
|
||||
apiKey: apiKey,
|
||||
hc: &http.Client{Timeout: 30 * time.Second},
|
||||
}
|
||||
}
|
||||
|
||||
func (c *httpClient) get(ctx context.Context, path string, query map[string]string) ([]byte, error) {
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.baseURL+path, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(query) > 0 {
|
||||
q := req.URL.Query()
|
||||
for k, v := range query {
|
||||
q.Set(k, v)
|
||||
}
|
||||
req.URL.RawQuery = q.Encode()
|
||||
}
|
||||
return c.do(req)
|
||||
}
|
||||
|
||||
func (c *httpClient) post(ctx context.Context, path string, body []byte) ([]byte, error) {
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.baseURL+path, bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
return c.do(req)
|
||||
}
|
||||
|
||||
func (c *httpClient) do(req *http.Request) ([]byte, error) {
|
||||
req.Header.Set("X-Api-Key", c.apiKey)
|
||||
req.Header.Set("Accept", "application/json")
|
||||
resp, err := c.hc.Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read response: %w", err)
|
||||
}
|
||||
if resp.StatusCode >= 400 {
|
||||
return nil, fmt.Errorf("%s %s: %d: %s", req.Method, req.URL.Path, resp.StatusCode, strings.TrimSpace(string(body)))
|
||||
}
|
||||
return body, nil
|
||||
}
|
||||
|
||||
// parseLookup decodes a lookup response into Results, pulling Title/Year out
|
||||
// of each item while keeping the original JSON object intact.
|
||||
func parseLookup(body []byte, titleField string) ([]Result, error) {
|
||||
var items []json.RawMessage
|
||||
if err := json.Unmarshal(body, &items); err != nil {
|
||||
return nil, fmt.Errorf("decode lookup: %w", err)
|
||||
}
|
||||
out := make([]Result, 0, len(items))
|
||||
for _, item := range items {
|
||||
var meta map[string]json.RawMessage
|
||||
if err := json.Unmarshal(item, &meta); err != nil {
|
||||
continue
|
||||
}
|
||||
var title string
|
||||
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
|
||||
if raw, ok := meta["year"]; ok && len(raw) > 0 {
|
||||
_ = 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
|
||||
}
|
||||
|
||||
// buildAddBody decodes the raw lookup item into a generic map, overlays the
|
||||
// provided fields, and re-marshals. Each *arr backend supplies the fields
|
||||
// specific to its add endpoint.
|
||||
func buildAddBody(raw json.RawMessage, overlay map[string]any) ([]byte, error) {
|
||||
var m map[string]any
|
||||
if err := json.Unmarshal(raw, &m); err != nil {
|
||||
return nil, fmt.Errorf("decode lookup item: %w", err)
|
||||
}
|
||||
for k, v := range overlay {
|
||||
m[k] = v
|
||||
}
|
||||
return json.Marshal(m)
|
||||
}
|
||||
57
internal/arr/lidarr.go
Normal file
57
internal/arr/lidarr.go
Normal file
@@ -0,0 +1,57 @@
|
||||
package arr
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"bellhop/internal/config"
|
||||
)
|
||||
|
||||
// Lidarr drives a Lidarr v1 instance.
|
||||
type Lidarr struct {
|
||||
h *httpClient
|
||||
qualityProfileID int
|
||||
metadataProfileID int
|
||||
rootFolder string
|
||||
}
|
||||
|
||||
func NewLidarr(cfg *config.ArrConfig) *Lidarr {
|
||||
return &Lidarr{
|
||||
h: newHTTP(cfg.URL, cfg.APIKey),
|
||||
qualityProfileID: cfg.QualityProfileID,
|
||||
metadataProfileID: cfg.MetadataProfileID,
|
||||
rootFolder: cfg.RootFolder,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *Lidarr) Search(ctx context.Context, term string) ([]Result, error) {
|
||||
body, err := l.h.get(ctx, "/api/v1/artist/lookup", map[string]string{"term": term})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Lidarr's lookup uses "artistName" instead of "title".
|
||||
return parseLookup(body, "artistName")
|
||||
}
|
||||
|
||||
func (l *Lidarr) Add(ctx context.Context, res Result) error {
|
||||
if len(res.raw) == 0 {
|
||||
return fmt.Errorf("lidarr: empty result")
|
||||
}
|
||||
body, err := buildAddBody(res.raw, map[string]any{
|
||||
"qualityProfileId": l.qualityProfileID,
|
||||
"metadataProfileId": l.metadataProfileID,
|
||||
"rootFolderPath": l.rootFolder,
|
||||
"monitored": true,
|
||||
"addOptions": map[string]any{
|
||||
"monitor": "all",
|
||||
"searchForMissingAlbums": true,
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = l.h.post(ctx, "/api/v1/artist", body)
|
||||
return err
|
||||
}
|
||||
|
||||
var _ Client = (*Lidarr)(nil)
|
||||
69
internal/arr/lidarr_test.go
Normal file
69
internal/arr/lidarr_test.go
Normal file
@@ -0,0 +1,69 @@
|
||||
package arr
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"bellhop/internal/config"
|
||||
)
|
||||
|
||||
func TestLidarrSearch(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path != "/api/v1/artist/lookup" {
|
||||
t.Errorf("path = %q", r.URL.Path)
|
||||
}
|
||||
if r.URL.Query().Get("term") != "radiohead" {
|
||||
t.Errorf("term = %q", r.URL.Query().Get("term"))
|
||||
}
|
||||
_, _ = io.WriteString(w, `[{"artistName":"Radiohead","foreignArtistId":"a74b1b7f-71a5-4011-9441-d0b5e4122711"}]`)
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
l := NewLidarr(&config.ArrConfig{URL: srv.URL, APIKey: "k", QualityProfileID: 2, MetadataProfileID: 1, RootFolder: "/music"})
|
||||
results, err := l.Search(context.Background(), "radiohead")
|
||||
if err != nil {
|
||||
t.Fatalf("search: %v", err)
|
||||
}
|
||||
if len(results) != 1 || results[0].Title != "Radiohead" {
|
||||
t.Fatalf("unexpected results: %+v", results)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLidarrAdd(t *testing.T) {
|
||||
var got map[string]any
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost || r.URL.Path != "/api/v1/artist" {
|
||||
t.Errorf("unexpected %s %s", r.Method, r.URL.Path)
|
||||
}
|
||||
_ = json.NewDecoder(r.Body).Decode(&got)
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
l := NewLidarr(&config.ArrConfig{URL: srv.URL, APIKey: "k", QualityProfileID: 2, MetadataProfileID: 1, RootFolder: "/music"})
|
||||
res := makeResult("Radiohead", 0, `{"artistName":"Radiohead","foreignArtistId":"a74b1b7f-71a5-4011-9441-d0b5e4122711"}`)
|
||||
if err := l.Add(context.Background(), res); err != nil {
|
||||
t.Fatalf("add: %v", err)
|
||||
}
|
||||
|
||||
if got["qualityProfileId"].(float64) != 2 {
|
||||
t.Errorf("qualityProfileId = %v", got["qualityProfileId"])
|
||||
}
|
||||
if got["metadataProfileId"].(float64) != 1 {
|
||||
t.Errorf("metadataProfileId = %v", got["metadataProfileId"])
|
||||
}
|
||||
if got["rootFolderPath"] != "/music" {
|
||||
t.Errorf("rootFolderPath = %v", got["rootFolderPath"])
|
||||
}
|
||||
if got["foreignArtistId"] != "a74b1b7f-71a5-4011-9441-d0b5e4122711" {
|
||||
t.Errorf("foreignArtistId not preserved: %v", got["foreignArtistId"])
|
||||
}
|
||||
opts := got["addOptions"].(map[string]any)
|
||||
if opts["searchForMissingAlbums"] != true || opts["monitor"] != "all" {
|
||||
t.Errorf("addOptions wrong: %v", opts)
|
||||
}
|
||||
}
|
||||
60
internal/arr/radarr.go
Normal file
60
internal/arr/radarr.go
Normal file
@@ -0,0 +1,60 @@
|
||||
package arr
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
|
||||
"bellhop/internal/config"
|
||||
)
|
||||
|
||||
// Radarr drives a Radarr v3 instance.
|
||||
type Radarr struct {
|
||||
h *httpClient
|
||||
qualityProfileID int
|
||||
rootFolder string
|
||||
}
|
||||
|
||||
func NewRadarr(cfg *config.ArrConfig) *Radarr {
|
||||
return &Radarr{
|
||||
h: newHTTP(cfg.URL, cfg.APIKey),
|
||||
qualityProfileID: cfg.QualityProfileID,
|
||||
rootFolder: cfg.RootFolder,
|
||||
}
|
||||
}
|
||||
|
||||
func (r *Radarr) Search(ctx context.Context, term string) ([]Result, error) {
|
||||
body, err := r.h.get(ctx, "/api/v3/movie/lookup", map[string]string{"term": term})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return parseLookup(body, "title")
|
||||
}
|
||||
|
||||
func (r *Radarr) Add(ctx context.Context, res Result) error {
|
||||
if len(res.raw) == 0 {
|
||||
return fmt.Errorf("radarr: empty result")
|
||||
}
|
||||
body, err := buildAddBody(res.raw, map[string]any{
|
||||
"qualityProfileId": r.qualityProfileID,
|
||||
"rootFolderPath": r.rootFolder,
|
||||
"monitored": true,
|
||||
"addOptions": map[string]any{
|
||||
"searchForMovie": true,
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = r.h.post(ctx, "/api/v3/movie", body)
|
||||
return err
|
||||
}
|
||||
|
||||
// compile-time interface check
|
||||
var _ Client = (*Radarr)(nil)
|
||||
|
||||
// makeResult is a tiny helper used by tests in this package to construct a
|
||||
// Result from arbitrary JSON without going through the network.
|
||||
func makeResult(title string, year int, raw string) Result {
|
||||
return Result{Title: title, Year: year, raw: json.RawMessage(raw)}
|
||||
}
|
||||
96
internal/arr/radarr_test.go
Normal file
96
internal/arr/radarr_test.go
Normal file
@@ -0,0 +1,96 @@
|
||||
package arr
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"bellhop/internal/config"
|
||||
)
|
||||
|
||||
func TestRadarrSearch(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if got := r.Header.Get("X-Api-Key"); got != "secret" {
|
||||
t.Errorf("api key header = %q, want secret", got)
|
||||
}
|
||||
if r.URL.Path != "/api/v3/movie/lookup" {
|
||||
t.Errorf("path = %q", r.URL.Path)
|
||||
}
|
||||
if r.URL.Query().Get("term") != "dune" {
|
||||
t.Errorf("term = %q", r.URL.Query().Get("term"))
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = io.WriteString(w, `[
|
||||
{"title":"Dune","year":2021,"tmdbId":438631,"titleSlug":"dune-2021"},
|
||||
{"title":"Dune: Part Two","year":2024,"tmdbId":693134,"titleSlug":"dune-part-two-2024"}
|
||||
]`)
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
r := NewRadarr(&config.ArrConfig{URL: srv.URL, APIKey: "secret", QualityProfileID: 6, RootFolder: "/movies"})
|
||||
results, err := r.Search(context.Background(), "dune")
|
||||
if err != nil {
|
||||
t.Fatalf("search: %v", err)
|
||||
}
|
||||
if len(results) != 2 {
|
||||
t.Fatalf("got %d results, want 2", len(results))
|
||||
}
|
||||
if results[0].Title != "Dune" || results[0].Year != 2021 {
|
||||
t.Errorf("first result = %+v", results[0])
|
||||
}
|
||||
}
|
||||
|
||||
func TestRadarrAdd(t *testing.T) {
|
||||
var got map[string]any
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost || r.URL.Path != "/api/v3/movie" {
|
||||
t.Errorf("unexpected %s %s", r.Method, r.URL.Path)
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&got); err != nil {
|
||||
t.Fatalf("decode body: %v", err)
|
||||
}
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
_, _ = io.WriteString(w, `{"id":42}`)
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
r := NewRadarr(&config.ArrConfig{URL: srv.URL, APIKey: "k", QualityProfileID: 6, RootFolder: "/movies"})
|
||||
res := makeResult("Dune", 2021, `{"title":"Dune","year":2021,"tmdbId":438631,"titleSlug":"dune-2021"}`)
|
||||
if err := r.Add(context.Background(), res); err != nil {
|
||||
t.Fatalf("add: %v", err)
|
||||
}
|
||||
|
||||
if got["qualityProfileId"].(float64) != 6 {
|
||||
t.Errorf("qualityProfileId = %v", got["qualityProfileId"])
|
||||
}
|
||||
if got["rootFolderPath"] != "/movies" {
|
||||
t.Errorf("rootFolderPath = %v", got["rootFolderPath"])
|
||||
}
|
||||
if got["monitored"] != true {
|
||||
t.Errorf("monitored = %v", got["monitored"])
|
||||
}
|
||||
if got["tmdbId"].(float64) != 438631 {
|
||||
t.Errorf("tmdbId not preserved from lookup: %v", got["tmdbId"])
|
||||
}
|
||||
opts := got["addOptions"].(map[string]any)
|
||||
if opts["searchForMovie"] != true {
|
||||
t.Errorf("addOptions.searchForMovie = %v", opts["searchForMovie"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestRadarrAddError(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
_, _ = io.WriteString(w, `{"error":"already exists"}`)
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
r := NewRadarr(&config.ArrConfig{URL: srv.URL, APIKey: "k", QualityProfileID: 1, RootFolder: "/m"})
|
||||
err := r.Add(context.Background(), makeResult("X", 0, `{"title":"X"}`))
|
||||
if err == nil {
|
||||
t.Fatal("expected error, got nil")
|
||||
}
|
||||
}
|
||||
55
internal/arr/sonarr.go
Normal file
55
internal/arr/sonarr.go
Normal file
@@ -0,0 +1,55 @@
|
||||
package arr
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"bellhop/internal/config"
|
||||
)
|
||||
|
||||
// Sonarr drives a Sonarr v3/v4 instance.
|
||||
type Sonarr struct {
|
||||
h *httpClient
|
||||
qualityProfileID int
|
||||
rootFolder string
|
||||
}
|
||||
|
||||
func NewSonarr(cfg *config.ArrConfig) *Sonarr {
|
||||
return &Sonarr{
|
||||
h: newHTTP(cfg.URL, cfg.APIKey),
|
||||
qualityProfileID: cfg.QualityProfileID,
|
||||
rootFolder: cfg.RootFolder,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Sonarr) Search(ctx context.Context, term string) ([]Result, error) {
|
||||
body, err := s.h.get(ctx, "/api/v3/series/lookup", map[string]string{"term": term})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return parseLookup(body, "title")
|
||||
}
|
||||
|
||||
func (s *Sonarr) Add(ctx context.Context, res Result) error {
|
||||
if len(res.raw) == 0 {
|
||||
return fmt.Errorf("sonarr: empty result")
|
||||
}
|
||||
body, err := buildAddBody(res.raw, map[string]any{
|
||||
"qualityProfileId": s.qualityProfileID,
|
||||
"rootFolderPath": s.rootFolder,
|
||||
"monitored": true,
|
||||
"seasonFolder": true,
|
||||
"addOptions": map[string]any{
|
||||
"monitor": "all",
|
||||
"searchForMissingEpisodes": true,
|
||||
"searchForCutoffUnmetEpisodes": false,
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = s.h.post(ctx, "/api/v3/series", body)
|
||||
return err
|
||||
}
|
||||
|
||||
var _ Client = (*Sonarr)(nil)
|
||||
66
internal/arr/sonarr_test.go
Normal file
66
internal/arr/sonarr_test.go
Normal file
@@ -0,0 +1,66 @@
|
||||
package arr
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"bellhop/internal/config"
|
||||
)
|
||||
|
||||
func TestSonarrSearch(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path != "/api/v3/series/lookup" {
|
||||
t.Errorf("path = %q", r.URL.Path)
|
||||
}
|
||||
if r.URL.Query().Get("term") != "severance" {
|
||||
t.Errorf("term = %q", r.URL.Query().Get("term"))
|
||||
}
|
||||
_, _ = io.WriteString(w, `[{"title":"Severance","year":2022,"tvdbId":371980}]`)
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
s := NewSonarr(&config.ArrConfig{URL: srv.URL, APIKey: "k", QualityProfileID: 4, RootFolder: "/tv"})
|
||||
results, err := s.Search(context.Background(), "severance")
|
||||
if err != nil {
|
||||
t.Fatalf("search: %v", err)
|
||||
}
|
||||
if len(results) != 1 || results[0].Title != "Severance" || results[0].Year != 2022 {
|
||||
t.Fatalf("unexpected results: %+v", results)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSonarrAdd(t *testing.T) {
|
||||
var got map[string]any
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost || r.URL.Path != "/api/v3/series" {
|
||||
t.Errorf("unexpected %s %s", r.Method, r.URL.Path)
|
||||
}
|
||||
_ = json.NewDecoder(r.Body).Decode(&got)
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
s := NewSonarr(&config.ArrConfig{URL: srv.URL, APIKey: "k", QualityProfileID: 4, RootFolder: "/tv"})
|
||||
res := makeResult("Severance", 2022, `{"title":"Severance","year":2022,"tvdbId":371980}`)
|
||||
if err := s.Add(context.Background(), res); err != nil {
|
||||
t.Fatalf("add: %v", err)
|
||||
}
|
||||
|
||||
if got["qualityProfileId"].(float64) != 4 {
|
||||
t.Errorf("qualityProfileId = %v", got["qualityProfileId"])
|
||||
}
|
||||
if got["rootFolderPath"] != "/tv" {
|
||||
t.Errorf("rootFolderPath = %v", got["rootFolderPath"])
|
||||
}
|
||||
if got["monitored"] != true || got["seasonFolder"] != true {
|
||||
t.Errorf("monitored/seasonFolder wrong: %v", got)
|
||||
}
|
||||
opts := got["addOptions"].(map[string]any)
|
||||
if opts["monitor"] != "all" || opts["searchForMissingEpisodes"] != true {
|
||||
t.Errorf("addOptions wrong: %v", opts)
|
||||
}
|
||||
}
|
||||
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))
|
||||
}
|
||||
}
|
||||
132
internal/config/config.go
Normal file
132
internal/config/config.go
Normal file
@@ -0,0 +1,132 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"os"
|
||||
"regexp"
|
||||
|
||||
"github.com/BurntSushi/toml"
|
||||
)
|
||||
|
||||
var envBracketRe = regexp.MustCompile(`\$\{([^}]+)\}`)
|
||||
|
||||
type Config struct {
|
||||
Matrix MatrixConfig `toml:"matrix"`
|
||||
Services ServicesConfig `toml:"services"`
|
||||
}
|
||||
|
||||
type MatrixConfig struct {
|
||||
Homeserver string `toml:"homeserver"`
|
||||
UserID string `toml:"user_id"`
|
||||
Password string `toml:"password"`
|
||||
PickleKey string `toml:"pickle_key"`
|
||||
DisplayName string `toml:"display_name"`
|
||||
DataDir string `toml:"data_dir"`
|
||||
CommandPrefix string `toml:"command_prefix"`
|
||||
// AllowedRooms is the set of room IDs the bot listens for commands in.
|
||||
// Messages in any other room are ignored.
|
||||
AllowedRooms []string `toml:"allowed_rooms"`
|
||||
}
|
||||
|
||||
type ServicesConfig struct {
|
||||
Radarr *ArrConfig `toml:"radarr"`
|
||||
Sonarr *ArrConfig `toml:"sonarr"`
|
||||
Lidarr *ArrConfig `toml:"lidarr"`
|
||||
}
|
||||
|
||||
type ArrConfig struct {
|
||||
URL string `toml:"url"`
|
||||
APIKey string `toml:"api_key"`
|
||||
QualityProfileID int `toml:"quality_profile_id"`
|
||||
RootFolder string `toml:"root_folder"`
|
||||
// MetadataProfileID is required by Lidarr; ignored by Radarr/Sonarr.
|
||||
MetadataProfileID int `toml:"metadata_profile_id"`
|
||||
}
|
||||
|
||||
func Load(path string) (*Config, error) {
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read config: %w", err)
|
||||
}
|
||||
|
||||
expanded := envBracketRe.ReplaceAllStringFunc(string(data), func(match string) string {
|
||||
varName := match[2 : len(match)-1]
|
||||
val := os.Getenv(varName)
|
||||
if val == "" {
|
||||
slog.Warn("config: env var referenced but not set", "var", varName)
|
||||
}
|
||||
return val
|
||||
})
|
||||
|
||||
var cfg Config
|
||||
if _, err := toml.Decode(expanded, &cfg); err != nil {
|
||||
return nil, fmt.Errorf("parse config: %w", err)
|
||||
}
|
||||
|
||||
cfg.applyDefaults()
|
||||
|
||||
if err := cfg.validate(); err != nil {
|
||||
return nil, fmt.Errorf("validate config: %w", err)
|
||||
}
|
||||
|
||||
return &cfg, nil
|
||||
}
|
||||
|
||||
func (c *Config) validate() error {
|
||||
if c.Matrix.Homeserver == "" {
|
||||
return fmt.Errorf("matrix.homeserver is required")
|
||||
}
|
||||
if c.Matrix.UserID == "" {
|
||||
return fmt.Errorf("matrix.user_id is required")
|
||||
}
|
||||
if c.Matrix.Password == "" {
|
||||
return fmt.Errorf("matrix.password is required")
|
||||
}
|
||||
if len(c.Matrix.AllowedRooms) == 0 {
|
||||
return fmt.Errorf("matrix.allowed_rooms must have at least one entry")
|
||||
}
|
||||
if c.Services.Radarr == nil && c.Services.Sonarr == nil && c.Services.Lidarr == nil {
|
||||
return fmt.Errorf("at least one of services.radarr/sonarr/lidarr must be configured")
|
||||
}
|
||||
for name, svc := range map[string]*ArrConfig{
|
||||
"radarr": c.Services.Radarr,
|
||||
"sonarr": c.Services.Sonarr,
|
||||
"lidarr": c.Services.Lidarr,
|
||||
} {
|
||||
if svc == nil {
|
||||
continue
|
||||
}
|
||||
if svc.URL == "" {
|
||||
return fmt.Errorf("services.%s.url is required when service is set", name)
|
||||
}
|
||||
if svc.APIKey == "" {
|
||||
return fmt.Errorf("services.%s.api_key is required when service is set", name)
|
||||
}
|
||||
if svc.RootFolder == "" {
|
||||
return fmt.Errorf("services.%s.root_folder is required when service is set", name)
|
||||
}
|
||||
if svc.QualityProfileID == 0 {
|
||||
return fmt.Errorf("services.%s.quality_profile_id is required when service is set", name)
|
||||
}
|
||||
}
|
||||
if c.Services.Lidarr != nil && c.Services.Lidarr.MetadataProfileID == 0 {
|
||||
return fmt.Errorf("services.lidarr.metadata_profile_id is required when lidarr is set")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Config) applyDefaults() {
|
||||
if c.Matrix.DataDir == "" {
|
||||
c.Matrix.DataDir = "./data"
|
||||
}
|
||||
if c.Matrix.DisplayName == "" {
|
||||
c.Matrix.DisplayName = "Bellhop"
|
||||
}
|
||||
if c.Matrix.PickleKey == "" {
|
||||
c.Matrix.PickleKey = "bellhop_pickle_key"
|
||||
}
|
||||
if c.Matrix.CommandPrefix == "" {
|
||||
c.Matrix.CommandPrefix = "!"
|
||||
}
|
||||
}
|
||||
344
internal/matrix/client.go
Normal file
344
internal/matrix/client.go
Normal file
@@ -0,0 +1,344 @@
|
||||
package matrix
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"bellhop/internal/config"
|
||||
|
||||
"maunium.net/go/mautrix"
|
||||
"maunium.net/go/mautrix/crypto/cryptohelper"
|
||||
"maunium.net/go/mautrix/event"
|
||||
"maunium.net/go/mautrix/id"
|
||||
)
|
||||
|
||||
// MessageHandler is called when a text message is received in an allowlisted room.
|
||||
type MessageHandler func(roomID id.RoomID, eventID id.EventID, sender id.UserID, body string)
|
||||
|
||||
type deviceInfo struct {
|
||||
AccessToken string `json:"access_token"`
|
||||
DeviceID string `json:"device_id"`
|
||||
UserID string `json:"user_id"`
|
||||
}
|
||||
|
||||
type Client struct {
|
||||
mx *mautrix.Client
|
||||
allowedRooms map[id.RoomID]struct{}
|
||||
userID id.UserID
|
||||
cfg config.MatrixConfig
|
||||
crypto *cryptohelper.CryptoHelper
|
||||
|
||||
mu sync.RWMutex
|
||||
onMessage MessageHandler
|
||||
cancelSync context.CancelFunc
|
||||
}
|
||||
|
||||
// New creates a Matrix client with password login, device persistence, and E2EE.
|
||||
func New(cfg config.MatrixConfig) (*Client, error) {
|
||||
if err := os.MkdirAll(cfg.DataDir, 0o755); err != nil {
|
||||
return nil, fmt.Errorf("create data dir: %w", err)
|
||||
}
|
||||
|
||||
devicePath := filepath.Join(cfg.DataDir, "device.json")
|
||||
|
||||
device, err := loadDevice(devicePath)
|
||||
if err != nil {
|
||||
// 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
|
||||
|
||||
if device != nil {
|
||||
if isTokenValid(cfg.Homeserver, device.AccessToken, cfg.UserID) {
|
||||
slog.Info("existing device credentials valid", "device_id", device.DeviceID)
|
||||
mx, err = mautrix.NewClient(cfg.Homeserver, id.UserID(device.UserID), device.AccessToken)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create client with existing token: %w", err)
|
||||
}
|
||||
mx.DeviceID = id.DeviceID(device.DeviceID)
|
||||
} else {
|
||||
slog.Warn("existing device credentials invalid, logging in again")
|
||||
device = nil
|
||||
}
|
||||
}
|
||||
|
||||
if device == nil {
|
||||
mx, err = mautrix.NewClient(cfg.Homeserver, "", "")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create client: %w", err)
|
||||
}
|
||||
|
||||
resp, err := mx.Login(context.Background(), &mautrix.ReqLogin{
|
||||
Type: mautrix.AuthTypePassword,
|
||||
Identifier: mautrix.UserIdentifier{
|
||||
Type: mautrix.IdentifierTypeUser,
|
||||
User: cfg.UserID,
|
||||
},
|
||||
Password: cfg.Password,
|
||||
InitialDeviceDisplayName: cfg.DisplayName,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("login: %w", err)
|
||||
}
|
||||
|
||||
mx.AccessToken = resp.AccessToken
|
||||
mx.UserID = resp.UserID
|
||||
mx.DeviceID = resp.DeviceID
|
||||
|
||||
if err := saveDevice(devicePath, &deviceInfo{
|
||||
AccessToken: resp.AccessToken,
|
||||
DeviceID: string(resp.DeviceID),
|
||||
UserID: string(resp.UserID),
|
||||
}); err != nil {
|
||||
slog.Warn("failed to save device info", "err", err)
|
||||
}
|
||||
|
||||
slog.Info("logged in successfully", "user_id", resp.UserID, "device_id", resp.DeviceID)
|
||||
}
|
||||
|
||||
cryptoDBPath := filepath.Join(cfg.DataDir, "crypto.db")
|
||||
ch, err := cryptohelper.NewCryptoHelper(mx, []byte(cfg.PickleKey), cryptoDBPath)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("init crypto helper: %w", err)
|
||||
}
|
||||
|
||||
// Surface decrypt failures — the default silent no-op hides missing-megolm-session
|
||||
// errors, which look like the bot ignoring commands.
|
||||
ch.DecryptErrorCallback = func(evt *event.Event, err error) {
|
||||
slog.Warn("matrix: failed to decrypt incoming event",
|
||||
"room", evt.RoomID, "event_id", evt.ID, "sender", evt.Sender, "err", err)
|
||||
}
|
||||
|
||||
// Intentionally NOT setting ch.LoginAs: cryptohelper.Init will Login() every
|
||||
// time LoginAs is non-nil (see mautrix cryptohelper.go), which would mint a
|
||||
// new access_token on every startup and silently invalidate the device.json
|
||||
// we just wrote. We already have valid credentials in mx by this point —
|
||||
// Init will reuse them.
|
||||
if err := ch.Init(context.Background()); err != nil {
|
||||
return nil, fmt.Errorf("crypto helper init: %w", err)
|
||||
}
|
||||
|
||||
mx.Crypto = ch
|
||||
|
||||
mach := ch.Machine()
|
||||
existingKeys, err := mach.GetOwnCrossSigningPublicKeys(context.Background())
|
||||
if err != nil {
|
||||
slog.Warn("cross-signing: failed to fetch existing keys", "err", err)
|
||||
}
|
||||
if existingKeys == nil || existingKeys.MasterKey == "" {
|
||||
_, _, err = mach.GenerateAndUploadCrossSigningKeys(context.Background(), func(ui *mautrix.RespUserInteractive) interface{} {
|
||||
return map[string]interface{}{
|
||||
"type": mautrix.AuthTypePassword,
|
||||
"identifier": map[string]interface{}{
|
||||
"type": mautrix.IdentifierTypeUser,
|
||||
"user": cfg.UserID,
|
||||
},
|
||||
"password": cfg.Password,
|
||||
"session": ui.Session,
|
||||
}
|
||||
}, "")
|
||||
if err != nil {
|
||||
slog.Warn("cross-signing: key upload failed", "err", err)
|
||||
} else {
|
||||
slog.Info("cross-signing: keys uploaded")
|
||||
}
|
||||
if err := mach.SignOwnDevice(context.Background(), mach.OwnIdentity()); err != nil {
|
||||
slog.Warn("cross-signing: sign own device failed", "err", err)
|
||||
}
|
||||
if err := mach.SignOwnMasterKey(context.Background()); err != nil {
|
||||
slog.Warn("cross-signing: sign master key failed", "err", err)
|
||||
}
|
||||
} else {
|
||||
slog.Info("cross-signing: already configured, skipping bootstrap")
|
||||
}
|
||||
|
||||
slog.Info("E2EE initialized", "device_id", mx.DeviceID)
|
||||
|
||||
allowed := make(map[id.RoomID]struct{}, len(cfg.AllowedRooms))
|
||||
for _, r := range cfg.AllowedRooms {
|
||||
allowed[id.RoomID(r)] = struct{}{}
|
||||
}
|
||||
|
||||
return &Client{
|
||||
mx: mx,
|
||||
allowedRooms: allowed,
|
||||
userID: mx.UserID,
|
||||
cfg: cfg,
|
||||
crypto: ch,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// SetMessageHandler registers a callback for text messages in allowlisted rooms.
|
||||
func (c *Client) SetMessageHandler(fn MessageHandler) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
c.onMessage = fn
|
||||
}
|
||||
|
||||
// Start begins the Matrix sync loop in the background.
|
||||
func (c *Client) Start(ctx context.Context) error {
|
||||
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) {
|
||||
if evt.Sender == c.userID {
|
||||
return
|
||||
}
|
||||
if _, ok := c.allowedRooms[evt.RoomID]; !ok {
|
||||
return
|
||||
}
|
||||
msg := evt.Content.AsMessage()
|
||||
if msg == nil || msg.MsgType != event.MsgText {
|
||||
return
|
||||
}
|
||||
c.mu.RLock()
|
||||
handler := c.onMessage
|
||||
c.mu.RUnlock()
|
||||
if handler != nil {
|
||||
handler(evt.RoomID, evt.ID, evt.Sender, msg.Body)
|
||||
}
|
||||
})
|
||||
|
||||
// Auto-join on invite to any room — allowlist still gates message handling.
|
||||
syncer.OnEventType(event.StateMember, func(ctx context.Context, evt *event.Event) {
|
||||
if evt.GetStateKey() == string(c.userID) && evt.Content.AsMember().Membership == event.MembershipInvite {
|
||||
if _, err := c.mx.JoinRoomByID(ctx, evt.RoomID); err != nil {
|
||||
slog.Error("failed to auto-join room", "room", evt.RoomID, "err", err)
|
||||
} else {
|
||||
slog.Info("auto-joined room", "room", evt.RoomID)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
syncCtx, cancel := context.WithCancel(ctx)
|
||||
c.cancelSync = cancel
|
||||
|
||||
go func() {
|
||||
for {
|
||||
err := c.mx.SyncWithContext(syncCtx)
|
||||
if syncCtx.Err() != nil {
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
slog.Error("matrix sync stopped, restarting in 5s", "err", err)
|
||||
} else {
|
||||
slog.Warn("matrix sync returned without error, restarting in 5s")
|
||||
}
|
||||
select {
|
||||
case <-time.After(5 * time.Second):
|
||||
case <-syncCtx.Done():
|
||||
return
|
||||
}
|
||||
}
|
||||
}()
|
||||
return nil
|
||||
}
|
||||
|
||||
// Stop halts the sync loop and closes the crypto store.
|
||||
func (c *Client) Stop() {
|
||||
if c.cancelSync != nil {
|
||||
c.cancelSync()
|
||||
}
|
||||
if c.crypto != nil {
|
||||
if err := c.crypto.Close(); err != nil {
|
||||
slog.Error("failed to close crypto helper", "err", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 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.
|
||||
// The caller's ctx governs cancellation and deadline.
|
||||
func (c *Client) PostThreadedReply(ctx context.Context, roomID id.RoomID, rootEventID id.EventID, plain, htmlBody string) error {
|
||||
content := &event.MessageEventContent{
|
||||
MsgType: event.MsgText,
|
||||
Body: plain,
|
||||
Format: event.FormatHTML,
|
||||
FormattedBody: htmlBody,
|
||||
RelatesTo: &event.RelatesTo{
|
||||
Type: event.RelThread,
|
||||
EventID: rootEventID,
|
||||
InReplyTo: &event.InReplyTo{EventID: rootEventID},
|
||||
IsFallingBack: true,
|
||||
},
|
||||
}
|
||||
_, err := c.mx.SendMessageEvent(ctx, roomID, event.EventMessage, content)
|
||||
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) {
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return nil, nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
var info deviceInfo
|
||||
if err := json.Unmarshal(data, &info); err != nil {
|
||||
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
|
||||
}
|
||||
|
||||
func saveDevice(path string, info *deviceInfo) error {
|
||||
data, err := json.MarshalIndent(info, "", " ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return os.WriteFile(path, data, 0o600)
|
||||
}
|
||||
|
||||
// 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)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
req.Header.Set("Authorization", "Bearer "+accessToken)
|
||||
|
||||
client := &http.Client{Timeout: 10 * time.Second}
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
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()
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
fastapi==0.115.6
|
||||
uvicorn[standard]==0.34.0
|
||||
httpx==0.28.1
|
||||
aiosqlite==0.20.0
|
||||
python-dotenv==1.0.1
|
||||
matrix-nio==0.24.0
|
||||
slowapi==0.1.9
|
||||
jinja2==3.1.5
|
||||
itsdangerous==2.2.0
|
||||
Reference in New Issue
Block a user