Merge pull request 'feat: Recently Completed downloads history, tab UI, and light theme refresh' (#7) from develop into main
All checks were successful
CI / Security audit (push) Successful in 39s
CI / Tests & coverage (push) Successful in 43s

Reviewed-on: #7
This commit was merged in pull request #7.
This commit is contained in:
2026-05-17 13:55:07 +01:00
17 changed files with 1754 additions and 157 deletions

View File

@@ -1,37 +0,0 @@
# Server Configuration
PORT=3001
LOG_LEVEL=info
# Cookie signing secret for tamper-proof session cookies
# Required in production. Generate with: openssl rand -hex 32
COOKIE_SECRET=your_cookie_secret_here
# Set to 1 (or a specific IP/CIDR) when running behind a reverse proxy
# (Nginx, Caddy, Traefik) so Express trusts X-Forwarded-For/Proto.
# Leave unset if sofarr is exposed directly.
# TRUST_PROXY=1
# Directory for persistent data (SQLite token store + logs)
# Defaults to ./data relative to project root
# DATA_DIR=/app/data
# Background polling interval in ms (default: 5000)
# Set to 0 or "off" to disable and fetch on-demand instead
# POLL_INTERVAL=5000
# Emby Configuration (single instance)
EMBY_URL=http://localhost:8096
EMBY_API_KEY=your_emby_api_key
# SABnzbd Instances (JSON array)
# Format: [{"name": "Instance Name", "url": "http://...", "apiKey": "..."}]
SABNZBD_INSTANCES=[{"name": "Primary", "url": "http://localhost:8080", "apiKey": "your_api_key"}]
# Sonarr Instances (JSON array)
SONARR_INSTANCES=[{"name": "Primary", "url": "http://localhost:8989", "apiKey": "your_api_key"}]
# Radarr Instances (JSON array)
RADARR_INSTANCES=[{"name": "Primary", "url": "http://localhost:7878", "apiKey": "your_api_key"}]
# qBittorrent Instances (JSON array)
QBITTORRENT_INSTANCES=[{"name": "main", "url": "http://localhost:8080", "username": "admin", "password": "your_password"}]

View File

@@ -19,6 +19,24 @@ LOG_LEVEL=info
# Generate with: openssl rand -hex 32
COOKIE_SECRET=your-cookie-secret-here
# =============================================================================
# TLS / HTTPS
# =============================================================================
# TLS is enabled by default using the bundled snakeoil self-signed certificate
# (valid for localhost/127.0.0.1, 10-year expiry).
# Set TLS_CERT and TLS_KEY to use your own certificate (recommended).
# Set TLS_ENABLED=false to run in plain HTTP mode (e.g. behind a TLS proxy).
#
# To generate a self-signed cert for your own hostname:
# openssl req -x509 -newkey rsa:2048 -keyout server.key -out server.crt \
# -days 365 -nodes -subj "/CN=yourhostname" \
# -addext "subjectAltName=DNS:yourhostname,IP:192.168.x.x"
#
# TLS_ENABLED=true
# TLS_CERT=/path/to/server.crt
# TLS_KEY=/path/to/server.key
# =============================================================================
# REVERSE PROXY & DEPLOYMENT
# =============================================================================
@@ -34,6 +52,10 @@ COOKIE_SECRET=your-cookie-secret-here
# Defaults to ./data relative to the project root.
# DATA_DIR=/app/data
# Number of days of completed download history to show in the Recently Completed section.
# Override per-request with ?days=N (capped at 90).
# RECENT_COMPLETED_DAYS=7
# Background polling interval in milliseconds (default: 5000)
# sofarr polls all services in the background and caches results so
# dashboard requests are near-instant.

View File

@@ -34,6 +34,9 @@ COPY --from=deps /app/node_modules ./node_modules
COPY --chown=root:root server/ ./server/
COPY --chown=root:root public/ ./public/
COPY --chown=root:root package.json ./
# Bundled snakeoil certificate for out-of-the-box TLS (self-signed, localhost only).
# Mount your own cert/key over /app/certs/ or set TLS_CERT/TLS_KEY env vars.
COPY --chown=root:root certs/ ./certs/
# Persistent data directory owned by node user (token store, logs)
RUN mkdir -p /app/data && chown node:node /app/data
@@ -47,7 +50,9 @@ USER node
EXPOSE 3001
# HEALTHCHECK — Docker will restart the container if this fails 3 times
# --no-check-certificate handles self-signed / snakeoil certs.
# Remove that flag when using a CA-signed certificate.
HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \
CMD wget -qO- http://localhost:3001/health || exit 1
CMD wget -qO- --no-check-certificate https://localhost:3001/health || exit 1
CMD ["node", "server/index.js"]

6
certs/.gitignore vendored Normal file
View File

@@ -0,0 +1,6 @@
# Ignore all cert/key files EXCEPT the bundled snakeoil development defaults.
# Never commit real TLS certificates or private keys to version control.
*
!.gitignore
!snakeoil.crt
!snakeoil.key

22
certs/snakeoil.crt Normal file
View File

@@ -0,0 +1,22 @@
-----BEGIN CERTIFICATE-----
MIIDoTCCAomgAwIBAgIUPgupZzf+zgMp4ylvf1NBRIWNpeUwDQYJKoZIhvcNAQEL
BQAwUjELMAkGA1UEBhMCR0IxDjAMBgNVBAgMBUxvY2FsMQ4wDAYDVQQHDAVMb2Nh
bDEPMA0GA1UECgwGc29mYXJyMRIwEAYDVQQDDAlsb2NhbGhvc3QwHhcNMjYwNTE3
MDk0NDQ4WhcNMzYwNTE0MDk0NDQ4WjBSMQswCQYDVQQGEwJHQjEOMAwGA1UECAwF
TG9jYWwxDjAMBgNVBAcMBUxvY2FsMQ8wDQYDVQQKDAZzb2ZhcnIxEjAQBgNVBAMM
CWxvY2FsaG9zdDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAL5Y05DF
9U3k27SGByJqdbKThRRabX0hsK0zckkbXoaj0U4odZatUicAqkm6yWzpqQyZM6qH
XX68LXqJk8r2VIdTTtKe5QU1WUAsW6KD0c514YC1VZ3a9ivQ2/tfdQsm8YxM/ECq
e2XFklfvE72HkHF4fM9LCMS/LeazazF0ogNTkyE27g9Ry/ofR2P4MymLtyBbQ1NA
B1zYRIhJ5HqFRMszBKhWi1zRgUQQNBuYA5wtxnXA9QNSz6ObtdWStfJ/C1Kuitpe
OVrB/TKCp1OKBpZTd4mBKlvdJWos9eZPzP4vLnsReT4pHBx6J2Jd1dC97/MAXLYP
mIXP+04zK5sWRUsCAwEAAaNvMG0wHQYDVR0OBBYEFCpYKb3zMgv4qThe8ukFrVIl
lhD3MB8GA1UdIwQYMBaAFCpYKb3zMgv4qThe8ukFrVIllhD3MA8GA1UdEwEB/wQF
MAMBAf8wGgYDVR0RBBMwEYcEfwAAAYIJbG9jYWxob3N0MA0GCSqGSIb3DQEBCwUA
A4IBAQBQ5Jg0pn4XW/560laNl7XAoGuMwrIy5j6zDlIgFE8DWAb0NGNyu/FkCVIZ
ruLNktq+w+kTeneAuYW3CGyac2HZo9T60VtQNL/k17hrDw1F6kMpAAYm6aiyFtE9
Stw07PMvpvjxKvetPLOQsfk0/hh0Nh2PiVVdqvVE/gGoraboHEfH+eGf/Arzg7s4
CzZTEz0OJP5i7VkZAvFygShPx/gHY77ojeHPl2LN3KI7s43TrjYZjxbUDwWDpGp0
BIsDFP+9NAvA5I74biChfEEopmBczVbQRtqBxBX1JTa2aT5w/ifUNyKVKIGp49Q8
o59gDmbCXhypom7OsyxBLZgyVWU1
-----END CERTIFICATE-----

28
certs/snakeoil.key Normal file
View File

@@ -0,0 +1,28 @@
-----BEGIN PRIVATE KEY-----
MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQC+WNOQxfVN5Nu0
hgcianWyk4UUWm19IbCtM3JJG16Go9FOKHWWrVInAKpJusls6akMmTOqh11+vC16
iZPK9lSHU07SnuUFNVlALFuig9HOdeGAtVWd2vYr0Nv7X3ULJvGMTPxAqntlxZJX
7xO9h5BxeHzPSwjEvy3ms2sxdKIDU5MhNu4PUcv6H0dj+DMpi7cgW0NTQAdc2ESI
SeR6hUTLMwSoVotc0YFEEDQbmAOcLcZ1wPUDUs+jm7XVkrXyfwtSroraXjlawf0y
gqdTigaWU3eJgSpb3SVqLPXmT8z+Ly57EXk+KRwceidiXdXQve/zAFy2D5iFz/tO
MyubFkVLAgMBAAECggEAEk0RCyNCJBSdqSKWLtFq8o0rdBsDpugyOymuOQHOjOxu
oQo6NnWaNF5kgQVAyfd0EpGFfavyw2iNVaUPo1zoU9ogwuOWSnHOj64UIcp0+PN6
VHknohWqdukBLyiGfnJM/0ieaKTbi2i7dGsfDA+rxbUoO6s2GYPC6O9inlUqVJGU
fBXKTbCneW1+hJQFcOKPW2+qwiUxbudG9neNTYFOm9a7Bfa6MLJ22mkfYVrHYDzo
gESo8sHXbEtvemka9jN0N/GoXgUi7iFXbqslPUoakCF7sgG0cXuUM9duSt67ynLj
j7Ix+QiKAZgvSO/83b7vK74Xmd6XFUif41VMZ2iEGQKBgQDqp/ZSCAakarRpBRN4
psKuhaYiBKurb5GezTOSfEGWxmng2s0bHcx74alKKNN8Tu2mNx6yafQdRNQdM+fG
dn8JnQUGXYpGwQbLHZ/aO0M64WBxfQku4JNGh+VZ3ZyUC+So28vzCYqx8qwJi94L
2sF8787hzHO1INzVaeXzQ89pEwKBgQDPqRzsJsP+zZmA4x16CtoWY7Z1d4z0GTkA
erlXNinu76AIvra6aUld/65ymMyNIIpLZoci55ZGxBY7g8U29e10iT+xmxAgq3VT
Tn438MbDXEgA+HvdRXCFPvNQQk0ZDegazdhTdtuhj+IHcm4M94zfVM3MSJOr0hJf
JGaVIGEx6QKBgDZLftckPEU221+haQv1qf4vtm0Qn5gfTJZt7Izsa1CzwDPi7Kpl
jrbrU/xwzd5pdNuMzXGCypUrI9lN9Ucai/JxfoQmiKQubZ/5zs7z/25UT7hysflC
xVEAiLTubhhjWBkqIlqtzoW2HNBoqIwdpb9+zWO5ptw2KmLHCgnrmsY5AoGBAKOt
YCaix4lm9L8qRGmVdCCBp6ce+/LKjqtaEAw1nQe/yBwcdlqn8jQs+4tH9LKoG1kj
DxDsCP7uP7fZPPD9FpTsOU/8MNIPUwK+s63UElaZvgdF1BusR+w+mfmAyNQeqfu2
k/P1k1fc2QOVpjiCRn8hkLSb4AlmIyTqxBB23SVBAoGATMtuk1r+SS9SDJW73CI1
jLkJkPGrBvX0dFZGtedpwLVhUTDnqKIsy2F1iGDRGIAy5IAiLEFx44qQrhUau7zR
/2avY0Ua9To9LW0k/matzJUKvXxYm59jh/GDp6LFU89hsL2zSd6z0Aknvh1SryCb
OSbN8wfCz53+7qea4NQEB4E=
-----END PRIVATE KEY-----

View File

@@ -4,14 +4,23 @@ services:
container_name: sofarr
restart: unless-stopped
ports:
- "127.0.0.1:3001:3001" # bind to loopback only — expose via reverse proxy
# Direct HTTPS (default — uses bundled snakeoil cert if TLS_CERT not set)
- "3001:3001"
# Uncomment the line below and comment out the above to bind to loopback
# only when using a reverse proxy (set TLS_ENABLED=false in that case):
# - "127.0.0.1:3001:3001"
environment:
- PORT=3001
- NODE_ENV=production
- LOG_LEVEL=info
# Set to 1 when running behind a reverse proxy (Nginx, Caddy, Traefik)
# so Express trusts X-Forwarded-For and X-Forwarded-Proto headers.
- TRUST_PROXY=1
# --- TLS ---
# Default: TLS enabled using bundled snakeoil cert (self-signed).
# Supply your own cert/key by mounting them and setting these paths:
# - TLS_CERT=/app/certs/server.crt
# - TLS_KEY=/app/certs/server.key
# Set TLS_ENABLED=false if terminating TLS at a reverse proxy instead.
# If using a reverse proxy, also set TRUST_PROXY=1 below.
# - TRUST_PROXY=1
# --- Replace placeholders with real values or use Docker secrets ---
- COOKIE_SECRET=change-me-generate-with-openssl-rand-hex-32
- EMBY_URL=https://emby.example.com
@@ -21,8 +30,11 @@ services:
- SABNZBD_INSTANCES=[{"name":"main","url":"https://sabnzbd.example.com","apiKey":"your-sabnzbd-api-key"}]
- QBITTORRENT_INSTANCES=[{"name":"main","url":"https://qbittorrent.example.com","username":"admin","password":"your-password"}]
volumes:
# Persistent volume for SQLite token store and log file
# Persistent volume for token store and log file
- sofarr-data:/app/data
# Mount your own TLS certificate and key (optional — snakeoil used if omitted)
# - /path/to/your/server.crt:/app/certs/server.crt:ro
# - /path/to/your/server.key:/app/certs/server.key:ro
# Run as the built-in non-root 'node' user (UID/GID 1000)
user: "1000:1000"
# Read-only root filesystem; only the data volume is writable
@@ -35,7 +47,9 @@ services:
- ALL # drop all Linux capabilities
cap_add: [] # add back none — Node.js needs no special caps
healthcheck:
test: ["CMD", "wget", "-qO-", "http://localhost:3001/health"]
# Uses --no-check-certificate for self-signed / snakeoil certs.
# Remove that flag if using a CA-signed certificate.
test: ["CMD", "wget", "-qO-", "--no-check-certificate", "https://localhost:3001/health"]
interval: 30s
timeout: 5s
retries: 3

View File

@@ -35,45 +35,46 @@ Admin users can view all users' downloads, see server status, cache statistics,
### High-Level Architecture
```
┌─────────────────────────────────────────────────────┐
Browser (SPA) │
┌──────────┐ ┌──────────┐ ┌───────────────────┐ │
Login │ │Dashboard │ │ Status Panel │ │
Form │ │ Cards │ │ (Admin only) │ │
└────┬─────┘ └────┬─────┘ └───────┬───────────┘ │
│ │ │ │ │
└───────┼──────────────┼────────────────┼──────────────┘
│ POST /login │ GET /user- │ GET /status
│ │ downloads │
▼ ▼ ▼
┌─────────────────────────────────────────────────────┐
│ Express Server (:3001) │
┌────────┐ ┌──────────┐ ┌────────┐ ┌────────────┐ │
Auth │ │Dashboard │ │ Emby │ │ Static │ │
│ Routes │ │ Routes │ │ Routes │ │ Files │ │
└────┬───┘ └────┬─────┘ └────┬───┘ └────────────┘ │
│ │ │ │ │
┌────┴──────────┴────────────┴──────────────────┐ │
│ │ Utilities Layer │ │
│ │ ┌────────┐ ┌────────┐ ┌──────┐ ┌──────────┐ │ │
│ Poller │ │ Cache │ │Config│ │qBittorrent│ │ │
└───┬────┘ └────────┘ └──────┘ └──────────┘ │ │
└──────┼────────────────────────────────────────┘ │
└─────────┼────────────────────────────────────────────┘
│ HTTP/API calls
┌──────────────────────────────────────────────────────┐
│ External Services │
┌──────────┐ ┌────────┐ ┌────────┐ ┌────────────┐ │
│ SABnzbd │ │ Sonarr │ │ Radarr │ │qBittorrent │ │
│ (Usenet) │ │ (TV) │ │(Movie) │ │ (Torrent) │ │
│ └──────────┘ └────────┘ └────────┘ └────────────┘ │
┌──────────────────────────────────────────────┐ │
│ │ Emby / Jellyfin │ │
(Authentication + User DB) │ │
└──────────────────────────────────────────────┘ │
└──────────────────────────────────────────────────────┘
```mermaid
flowchart TB
subgraph Browser["Browser (SPA)"]
login["Login Form"]
dash["Dashboard Cards"]
status["Status Panel\n(Admin only)"]
end
subgraph Server["Express Server (:3001)"]
auth_r["Auth Routes\n/api/auth"]
dash_r["Dashboard Routes\n/api/dashboard"]
emby_r["Emby Routes\n/api/emby"]
static_f["Static Files\npublic/"]
subgraph Utils["Utilities Layer"]
poller["Poller"]
cache["Cache"]
config["Config"]
qbt["qBittorrent"]
end
end
subgraph Ext["External Services"]
sab["SABnzbd\n(Usenet)"]
sonarr["Sonarr\n(TV)"]
radarr["Radarr\n(Movies)"]
qbittorrent["qBittorrent\n(Torrent)"]
emby["Emby / Jellyfin\n(Auth + User DB)"]
end
login -->|"POST /login"| auth_r
dash -->|"GET /stream SSE\nGET /user-downloads"| dash_r
status -->|"GET /status"| dash_r
auth_r -->|"authenticate"| emby
emby_r -->|"proxy"| emby
dash_r --> Utils
poller -->|"HTTP/API calls"| sab & sonarr & radarr
qbt -->|"HTTP/API calls"| qbittorrent
static_f -.->|"serve"| Browser
```
---
@@ -131,13 +132,15 @@ sofarr/
│ │ ├── emby.js # Proxy routes to Emby API
│ │ ├── sabnzbd.js # Proxy routes to SABnzbd API
│ │ ├── sonarr.js # Proxy routes to Sonarr API
│ │ ── radarr.js # Proxy routes to Radarr API
│ │ ── radarr.js # Proxy routes to Radarr API
│ │ └── history.js # GET /api/history/recent — recently completed downloads
│ ├── middleware/
│ │ ├── requireAuth.js # httpOnly cookie auth enforcement
│ │ └── verifyCsrf.js # CSRF double-submit cookie validation
│ └── utils/
│ ├── cache.js # MemoryCache class (Map + TTL + stats)
│ ├── config.js # Multi-instance service configuration parser
│ ├── historyFetcher.js # Fetch + cache Sonarr/Radarr history; event classification
│ ├── logger.js # File logger (DATA_DIR/server.log)
│ ├── poller.js # Background polling engine + timing
│ ├── qbittorrent.js # qBittorrent client with auth + torrent mapping
@@ -208,6 +211,7 @@ sofarr/
| `sabnzbd.js` | `/api/sabnzbd` | Yes (`requireAuth`) | Yes | Proxy to SABnzbd API |
| `sonarr.js` | `/api/sonarr` | Yes (`requireAuth`) | Yes | Proxy to Sonarr API |
| `radarr.js` | `/api/radarr` | Yes (`requireAuth`) | Yes | Proxy to Radarr API |
| `history.js` | `/api/history` | Yes (`requireAuth`) | No (GET only) | Recently completed downloads from Sonarr/Radarr history |
**`requireAuth`** (`server/middleware/requireAuth.js`) reads the `emby_user` cookie (signed if `COOKIE_SECRET` is set) and attaches the parsed `{ id, name, isAdmin }` user to `req.user`. Returns `401` if the cookie is absent, tampered, or schema-invalid.
@@ -229,6 +233,8 @@ sofarr/
**`sanitizeError.js`** — Redacts secrets from error message strings before they are logged or returned in API responses. Patterns: URL query-param secrets (`apikey=`, `token=`, etc.), HTTP auth headers (`Authorization:`, `X-Emby-Authorization:`, etc.), Bearer tokens, and basic-auth credentials in URLs.
**`historyFetcher.js`** — Fetches history records from all Sonarr/Radarr instances for a configurable date window (`since`). Results are cached under `history:sonarr` / `history:radarr` for 5 minutes. Exports `classifySonarrEvent` / `classifyRadarrEvent` (returns `'imported'` | `'failed'` | `'other'`) and `invalidateHistoryCache`.
**`logger.js`** — Simple file appender writing timestamped messages to `DATA_DIR/server.log`.
---
@@ -341,6 +347,8 @@ Users are matched to downloads via tags in Sonarr/Radarr:
| `poll:radarr-tags` | `[{id, label}]` | Radarr tag API |
| `poll:qbittorrent` | `[torrent, ...]` | qBittorrent all torrents |
| `emby:users` | `Map<lowerName, displayName>` | Full Emby user list (60s TTL) |
| `history:sonarr` | `[record, ...]` — flat array with `_instanceUrl` / `_instanceName` | Sonarr history (5 min TTL, fetched on-demand by `/api/history/recent`) |
| `history:radarr` | `[record, ...]` — flat array with `_instanceUrl` / `_instanceName` | Radarr history (5 min TTL, fetched on-demand by `/api/history/recent`) |
### TTL Strategy
@@ -361,22 +369,21 @@ The core logic in `dashboard.js` matches raw download client data to *arr servic
For each download item (SABnzbd slot or qBittorrent torrent):
```
1. Try Sonarr QUEUE match (by title substring)
→ resolve series via seriesMap (embedded in queue record)
extract user tag → check tag matches requesting user
```mermaid
flowchart TD
Start(["Download item"]) --> SQ{"Sonarr QUEUE\nmatch (title)"}
SQ -->|yes| SQR["Resolve series via seriesMap\nextract user tag → check match"]
SQ -->|no| RQ{"Radarr QUEUE\nmatch (title)"}
RQ -->|yes| RQR["Resolve movie via moviesMap\nextract user tag → check match"]
RQ -->|no| SH{"Sonarr HISTORY\nmatch (title)"}
SH -->|yes| SHR["Resolve series via seriesId\nextract user tag → check match"]
SH -->|no| RH{"Radarr HISTORY\nmatch (title)"}
RH -->|yes| RHR["Resolve movie via movieId\nextract user tag → check match"]
RH -->|no| Skip(["Skip — unmatched"])
2. Try Radarr QUEUE match (by title substring)
→ resolve movie via moviesMap (embedded in queue record)
→ extract user tag → check tag matches requesting user
3. Try Sonarr HISTORY match (by title substring)
→ resolve series via seriesMap (from queue) using seriesId
→ extract user tag → check tag matches requesting user
4. Try Radarr HISTORY match (by title substring)
→ resolve movie via moviesMap (from queue) using movieId
→ extract user tag → check tag matches requesting user
SQR & RQR & SHR & RHR --> Tagged{"Tag matches\nrequesting user?"}
Tagged -->|yes| Include(["Include in response"])
Tagged -->|no| Skip
```
### Title Matching
@@ -587,24 +594,75 @@ Admin-only per-user download counts (fetches live from APIs, not cached).
---
### `GET /api/history/recent`
Returns recently completed (imported or failed) downloads from Sonarr/Radarr history for the authenticated user, filtered to the last `days` days.
**Query Parameters:**
| Param | Type | Default | Description |
|-------|------|---------|-------------|
| `days` | integer | `RECENT_COMPLETED_DAYS` env (default `7`) | How many days back to search. Capped at 90. |
| `showAll` | `"true"` | — | (Admin) Return records for all tagged users, not just the current user |
**Response (200):**
```json
{
"user": "Alice",
"isAdmin": false,
"days": 7,
"history": [
{
"type": "series",
"outcome": "imported",
"title": "Show.S01E01.720p",
"seriesName": "My Show",
"coverArt": "https://…/poster.jpg",
"completedAt": "2026-05-15T18:00:00.000Z",
"quality": "720p",
"instanceName": "Main Sonarr",
"arrLink": "https://sonarr.example.com/series/my-show",
"allTags": ["alice"],
"matchedUserTag": "alice",
"arrRecordId": 1234,
"failureMessage": null
}
]
}
```
- `outcome` is `"imported"` or `"failed"`. Records with other event types (e.g. `grabbed`) are filtered out.
- `failureMessage` is only included when the authenticated user is an admin and `outcome` is `"failed"`.
- `arrRecordId` is only included for admin users.
- Results are sorted newest first.
- History data is cached server-side for 5 minutes (`history:sonarr` / `history:radarr` cache keys).
---
## 10. Frontend Architecture
The frontend is a **vanilla JavaScript SPA** with no build step. All logic resides in `app.js`, styled by `style.css`, and structured by `index.html`.
### UI States
```
┌──────────────┐ ┌──────────────┐ ┌──────────────┐
Splash Screen│────▶│ Login Form │────▶│ Dashboard │
│ (on load) │ │ (if no │ │ (after auth) │
│ │ │ session) │ │ │
└──────────────┘ └──────────────┘ └──────────────┘
┌─────┴─────┐
│ Status │
│ Panel │
│ (admin) │
└───────────┘
```mermaid
stateDiagram-v2
[*] --> SplashScreen : Page load
SplashScreen --> LoginForm : No session
SplashScreen --> Dashboard : Valid session
LoginForm --> Dashboard : Auth success
Dashboard --> LoginForm : Logout
state Dashboard {
[*] --> ActiveDownloads
ActiveDownloads --> ActiveDownloads : SSE update
state StatusPanel {
[*] --> Closed
Closed --> Open : Click Status (admin)
Open --> Closed : Click close
Open --> Open : 5s refresh
}
}
```
### Key Frontend Functions
@@ -661,6 +719,9 @@ The status panel refreshes on a fixed 5-second timer and shows each SSE client w
| `DATA_DIR` | No | `./data` | Directory for `tokens.json` and `server.log`. Must be writable by the server process. In Docker: `/app/data` (named volume). |
| `COOKIE_SECRET` | No | — | If set, signs all session cookies with HMAC-SHA256. Strongly recommended in production. |
| `TRUST_PROXY` | No | — | Express `trust proxy` setting. Set to `1` (or a hop count) when behind a reverse proxy (nginx, Traefik, etc.) so `req.ip` and `req.secure` are correct. |
| `TLS_ENABLED` | No | `true` | Set to `false` to disable HTTPS and run plain HTTP (e.g. when TLS is terminated by a reverse proxy). |
| `TLS_CERT` | No | `certs/snakeoil.crt` | Path to the TLS certificate file (PEM). Defaults to the bundled self-signed snakeoil certificate. |
| `TLS_KEY` | No | `certs/snakeoil.key` | Path to the TLS private key file (PEM). Defaults to the bundled snakeoil key. |
#### Emby
@@ -691,6 +752,7 @@ The status panel refreshes on a fixed 5-second timer and shows each SSE client w
| Variable | Required | Default | Description |
|----------|:--------:|---------|-------------|
| `POLL_INTERVAL` | No | `5000` | Poll interval in ms. Set to `0`, `off`, or `false` to disable background polling (on-demand mode). |
| `RECENT_COMPLETED_DAYS` | No | `7` | Default lookback window (days) for `GET /api/history/recent`. Overridable per-request via `?days=`. Max 90. |
| `LOG_LEVEL` | No | `info` | `debug`, `info`, `warn`, `error`, `silent` |
### Instance JSON Format
@@ -726,6 +788,7 @@ The production image uses a two-stage build on `node:22-alpine`:
Key environment variables set in the image:
- `NODE_ENV=production` — enables production startup validation and logging
- `DATA_DIR=/app/data` — token store and log file location
- TLS is **enabled by default** using the bundled snakeoil self-signed certificate (`certs/snakeoil.crt`). Set `TLS_CERT`/`TLS_KEY` to your own certificate, or set `TLS_ENABLED=false` when terminating TLS at a reverse proxy.
### Docker Compose
@@ -736,12 +799,17 @@ services:
container_name: sofarr
restart: unless-stopped
ports:
- "3001:3001"
- "3001:3001" # HTTPS by default (snakeoil cert if no TLS_CERT set)
environment:
- NODE_ENV=production
- DATA_DIR=/app/data
- COOKIE_SECRET=change-me-to-a-long-random-string
- TRUST_PROXY=1 # set if behind nginx/Traefik
# Option A: direct TLS (default). Supply your own cert/key:
# - TLS_CERT=/app/certs/server.crt
# - TLS_KEY=/app/certs/server.key
# Option B: behind a TLS-terminating reverse proxy:
# - TLS_ENABLED=false
# - TRUST_PROXY=1
- EMBY_URL=https://emby.example.com
- EMBY_API_KEY=your-emby-api-key
- SONARR_INSTANCES=[{"name":"main","url":"...","apiKey":"..."}]
@@ -751,7 +819,10 @@ services:
- POLL_INTERVAL=5000
- LOG_LEVEL=info
volumes:
- sofarr-data:/app/data # persists tokens.json and server.log
- sofarr-data:/app/data
# Uncomment to supply your own certificate (Option A):
# - /path/to/server.crt:/app/certs/server.crt:ro
# - /path/to/server.key:/app/certs/server.key:ro
volumes:
sofarr-data:
@@ -759,10 +830,10 @@ volumes:
### Security hardening checklist
- **Use HTTPS** — TLS is on by default (snakeoil cert). Supply `TLS_CERT`/`TLS_KEY` pointing to a CA-signed certificate for trusted HTTPS. Alternatively terminate TLS at a reverse proxy and set `TLS_ENABLED=false` + `TRUST_PROXY=1`.
- **Set `COOKIE_SECRET`** — enables HMAC-signed cookies, preventing client-side forgery.
- **Set `TRUST_PROXY=1`** when behind a reverse proxy — ensures `req.secure` is `true` so the `secure` cookie flag is enforced and HTTPS-upgrade CSP fires.
- **Set `TRUST_PROXY=1`** only when a TLS-terminating reverse proxy sits in front — ensures `req.secure` is correct and the CSP `upgrade-insecure-requests` + `secure` cookie flag fire correctly.
- **Mount a named volume** for `DATA_DIR` — token store and log file survive container recreates.
- **Use HTTPS** — set `TRUST_PROXY=1` to enable the CSP `upgrade-insecure-requests` directive, the `secure` cookie flag, and HSTS (1-year `maxAge`).
- **Rate limiting** — the login endpoint is limited to 10 failed attempts per IP per 15 minutes; all API endpoints share a 300 req/15 min window. Set `TRUST_PROXY` correctly so the client IP is not the proxy's IP.
### CI / CD
@@ -816,6 +887,7 @@ graph TB
sab_r[sabnzbd.js\n/api/sabnzbd]
sonarr_r[sonarr.js\n/api/sonarr]
radarr_r[radarr.js\n/api/radarr]
history_r[history.js\n/api/history]
end
subgraph Utilities
@@ -826,6 +898,7 @@ graph TB
tokenstore[tokenStore.js\ntokens.json]
sanitize[sanitizeError.js]
logger[logger.js]
historyfetcher[historyFetcher.js]
end
entry --> appfactory
@@ -835,11 +908,13 @@ graph TB
appfactory --> hm & rl & cp & ej
appfactory -->|pre-CSRF| auth
appfactory --> verifycsrf
appfactory --> dashboard & emby_r & sab_r & sonarr_r & radarr_r
appfactory --> dashboard & emby_r & sab_r & sonarr_r & radarr_r & history_r
dashboard & emby_r & sab_r & sonarr_r & radarr_r --> requireauth
dashboard & emby_r & sab_r & sonarr_r & radarr_r & history_r --> requireauth
auth --> tokenstore
dashboard --> cache & poller & config & qbt
history_r --> cache & config & historyfetcher
historyfetcher --> cache & config
poller --> cache & config & qbt & logger
qbt --> config & logger
auth & dashboard -.-> sanitize

View File

@@ -5,6 +5,11 @@ let showAll = false;
let csrfToken = null; // double-submit CSRF token, sent as X-CSRF-Token on mutating requests
const SPLASH_MIN_MS = 1200; // minimum splash display time
// History section state
let historyDays = parseInt(localStorage.getItem('sofarr-history-days'), 10) || 7;
let historyRefreshHandle = null;
const HISTORY_REFRESH_MS = 5 * 60 * 1000; // auto-refresh history every 5 min
// SSE stream state
let sseSource = null;
let sseReconnectTimer = null;
@@ -20,6 +25,8 @@ const SSE_RECONNECT_MS = 3000; // browser already retries, but we add explicit b
document.addEventListener('DOMContentLoaded', () => {
checkAuthentication();
initThemeSwitcher();
initTabs();
initHistoryControls();
document.getElementById('login-form').addEventListener('submit', handleLogin);
document.getElementById('logout-btn').addEventListener('click', handleLogout);
@@ -43,6 +50,30 @@ function setTheme(theme) {
});
}
function initTabs() {
const savedTab = localStorage.getItem('sofarr-active-tab') || 'downloads';
activateTab(savedTab, false);
document.querySelectorAll('.tab-btn').forEach(btn => {
btn.addEventListener('click', () => {
const tab = btn.dataset.tab;
activateTab(tab, true);
});
});
}
function activateTab(tabName, save) {
document.querySelectorAll('.tab-btn').forEach(btn => {
btn.classList.toggle('active', btn.dataset.tab === tabName);
});
document.querySelectorAll('.tab-panel').forEach(panel => {
panel.style.display = panel.id === `tab-${tabName}` ? '' : 'none';
});
if (save) localStorage.setItem('sofarr-active-tab', tabName);
// Load history the first time the history tab is shown
if (tabName === 'history') loadHistory();
}
// --- SSE connection management ---
function startSSE() {
@@ -88,6 +119,8 @@ function handleShowAllToggle(e) {
showAll = e.target.checked;
// Re-open stream with updated showAll param
startSSE();
// Reload history with updated showAll param
loadHistory();
}
function fadeOutLogin() {
@@ -209,6 +242,7 @@ async function handleLogin(e) {
async function handleLogout() {
try {
stopSSE();
stopHistoryRefresh();
if (statusRefreshHandle) { clearInterval(statusRefreshHandle); statusRefreshHandle = null; }
await fetch('/api/auth/logout', {
method: 'POST',
@@ -217,6 +251,7 @@ async function handleLogout() {
currentUser = null;
csrfToken = null;
downloads = [];
clearHistory();
showLogin();
} catch (err) {
console.error('Logout failed:', err);
@@ -238,6 +273,10 @@ function showDashboard() {
sp.style.display = 'none';
sp.innerHTML = '';
document.getElementById('admin-controls').style.display = isAdmin ? 'flex' : 'none';
// Initialise days input from saved value
const daysInput = document.getElementById('history-days');
if (daysInput) daysInput.value = historyDays;
startHistoryRefresh();
}
function showLoginError(message) {
@@ -784,3 +823,197 @@ function hideLoading() {
const loading = document.getElementById('loading');
loading.style.display = 'none';
}
// =============================================================================
// History section
// =============================================================================
function initHistoryControls() {
const daysInput = document.getElementById('history-days');
const refreshBtn = document.getElementById('history-refresh-btn');
if (daysInput) {
daysInput.addEventListener('change', () => {
const v = parseInt(daysInput.value, 10);
if (v > 0 && v <= 90) {
historyDays = v;
localStorage.setItem('sofarr-history-days', v);
loadHistory();
}
});
}
if (refreshBtn) {
refreshBtn.addEventListener('click', () => loadHistory(true));
}
}
function startHistoryRefresh() {
stopHistoryRefresh();
historyRefreshHandle = setInterval(() => loadHistory(), HISTORY_REFRESH_MS);
}
function stopHistoryRefresh() {
if (historyRefreshHandle) {
clearInterval(historyRefreshHandle);
historyRefreshHandle = null;
}
}
function clearHistory() {
document.getElementById('history-list').innerHTML = '';
document.getElementById('no-history').style.display = 'none';
document.getElementById('history-error').style.display = 'none';
}
async function loadHistory(forceRefresh = false) {
const listEl = document.getElementById('history-list');
const loadingEl = document.getElementById('history-loading');
const errorEl = document.getElementById('history-error');
const noHistoryEl = document.getElementById('no-history');
loadingEl.style.display = 'block';
errorEl.style.display = 'none';
noHistoryEl.style.display = 'none';
try {
const params = new URLSearchParams({ days: historyDays });
if (showAll) params.set('showAll', 'true');
if (forceRefresh) params.set('_t', Date.now());
const res = await fetch(`/api/history/recent?${params}`);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const data = await res.json();
loadingEl.style.display = 'none';
renderHistory(data.history || []);
} catch (err) {
loadingEl.style.display = 'none';
errorEl.textContent = 'Failed to load history.';
errorEl.style.display = 'block';
console.error('[History] Load error:', err);
}
}
function renderHistory(items) {
const listEl = document.getElementById('history-list');
const noHistoryEl = document.getElementById('no-history');
listEl.innerHTML = '';
if (!items.length) {
noHistoryEl.style.display = 'block';
return;
}
noHistoryEl.style.display = 'none';
items.forEach(item => listEl.appendChild(createHistoryCard(item)));
}
function createHistoryCard(item) {
const card = document.createElement('div');
card.className = `history-card ${item.type} ${item.outcome}`;
if (item.coverArt) {
const coverDiv = document.createElement('div');
coverDiv.className = 'history-cover';
const img = document.createElement('img');
img.src = '/api/dashboard/cover-art?url=' + encodeURIComponent(item.coverArt);
img.alt = item.movieName || item.seriesName || item.title;
img.loading = 'lazy';
coverDiv.appendChild(img);
card.appendChild(coverDiv);
}
const info = document.createElement('div');
info.className = 'history-info';
// Header row: type badge + outcome badge
const header = document.createElement('div');
header.className = 'history-card-header';
const typeBadge = document.createElement('span');
typeBadge.className = `history-type-badge ${item.type}`;
typeBadge.textContent = item.type === 'series' ? '📺 Series' : '🎬 Movie';
header.appendChild(typeBadge);
const outcomeBadge = document.createElement('span');
outcomeBadge.className = `history-outcome-badge ${item.outcome}`;
outcomeBadge.textContent = item.outcome === 'imported' ? '✓ Imported' : '✗ Failed';
header.appendChild(outcomeBadge);
if (item.instanceName) {
const instBadge = document.createElement('span');
instBadge.className = 'history-instance-badge';
instBadge.textContent = item.instanceName;
header.appendChild(instBadge);
}
if (showAll && item.tagBadges && item.tagBadges.length > 0) {
const unmatched = item.tagBadges.filter(b => !b.matchedUser);
const matched = item.tagBadges.filter(b => b.matchedUser);
for (const b of unmatched) {
const badge = document.createElement('span');
badge.className = 'download-user-badge unmatched';
badge.textContent = b.label;
header.appendChild(badge);
}
for (const b of matched) {
const badge = document.createElement('span');
badge.className = 'download-user-badge';
badge.textContent = b.matchedUser;
header.appendChild(badge);
}
} else if (item.matchedUserTag) {
const badge = document.createElement('span');
badge.className = 'download-user-badge';
badge.textContent = item.matchedUserTag;
header.appendChild(badge);
}
info.appendChild(header);
// Title
const title = document.createElement('h3');
title.className = 'history-title';
title.textContent = item.title;
info.appendChild(title);
// Series/movie name with optional arr link
if (item.seriesName) {
const p = document.createElement('p');
p.className = 'history-media-name';
if (isAdmin && item.arrLink) {
p.innerHTML = 'Series: <a href="' + escapeHtml(item.arrLink) + '" target="_blank" class="arr-link">' + escapeHtml(item.seriesName) + '</a>';
} else {
p.textContent = 'Series: ' + item.seriesName;
}
info.appendChild(p);
}
if (item.movieName) {
const p = document.createElement('p');
p.className = 'history-media-name';
if (isAdmin && item.arrLink) {
p.innerHTML = 'Movie: <a href="' + escapeHtml(item.arrLink) + '" target="_blank" class="arr-link">' + escapeHtml(item.movieName) + '</a>';
} else {
p.textContent = 'Movie: ' + item.movieName;
}
info.appendChild(p);
}
// Detail pills
const details = document.createElement('div');
details.className = 'history-details';
if (item.completedAt) {
details.appendChild(createDetailItem('Completed', formatDate(item.completedAt)));
}
if (item.quality) {
details.appendChild(createDetailItem('Quality', item.quality));
}
// Failed imports: show failure message
if (item.outcome === 'failed' && item.failureMessage) {
const failItem = document.createElement('div');
failItem.className = 'history-failure-message';
failItem.textContent = item.failureMessage;
details.appendChild(failItem);
}
info.appendChild(details);
card.appendChild(info);
return card;
}

View File

@@ -74,13 +74,40 @@
<div id="loading" class="loading" style="display: none;">Loading downloads...</div>
<div class="downloads-container">
<h2>Your Downloads</h2>
<div id="no-downloads" class="no-downloads" style="display: none;">
<p>No downloads found for your user.</p>
<p>Make sure your shows and movies are tagged with your username in Sonarr/Radarr.</p>
<div class="main-tabs">
<div class="tab-bar">
<button class="tab-btn active" data-tab="downloads">Active Downloads</button>
<button class="tab-btn" data-tab="history">Recently Completed</button>
</div>
<div class="tab-panel" id="tab-downloads">
<div class="downloads-container">
<div id="no-downloads" class="no-downloads" style="display: none;">
<p>No downloads found for your user.</p>
<p>Make sure your shows and movies are tagged with your username in Sonarr/Radarr.</p>
</div>
<div id="downloads-list" class="downloads-list"></div>
</div>
</div>
<div class="tab-panel" id="tab-history" style="display: none;">
<div class="history-container" id="history-container">
<div class="history-header">
<div class="history-controls">
<label class="history-days-label" for="history-days">Last</label>
<input type="number" id="history-days" class="history-days-input" value="7" min="1" max="90">
<span class="history-days-label">days</span>
<button id="history-refresh-btn" class="history-refresh-btn" title="Refresh history">&#8635;</button>
</div>
</div>
<div id="history-loading" class="history-loading" style="display: none;">Loading history...</div>
<div id="history-error" class="history-error" style="display: none;"></div>
<div id="no-history" class="no-history" style="display: none;">
<p>No completed downloads found in this period.</p>
</div>
<div id="history-list" class="history-list"></div>
</div>
</div>
<div id="downloads-list" class="downloads-list"></div>
</div>
<footer class="app-footer">

View File

@@ -31,41 +31,68 @@
/* ===== Theme Variables ===== */
:root, [data-theme="light"] {
--bg-gradient-start: #667eea;
--bg-gradient-end: #764ba2;
/* Page background — clean off-white matching logo backdrop */
--bg-gradient-start: #e8eef3;
--bg-gradient-end: #d4dee8;
/* Surfaces */
--surface: #ffffff;
--surface-alt: #f5f5f5;
--text-primary: #333333;
--text-secondary: #666666;
--text-muted: #999999;
--border: #e0e0e0;
--accent: #667eea;
--accent-hover: #5568d3;
--accent-light: #e8eaf6;
--series-color: #667eea;
--series-bg: #e8eaf6;
--movie-color: #e040a0;
--movie-bg: #fce4ec;
--torrent-color: #26a69a;
--torrent-bg: #e0f2f1;
--success: #4caf50;
--surface-alt: #f0f4f7;
/* Typography — charcoal from logo, all meet WCAG AA on white */
--text-primary: #2b2f33; /* ~14:1 on white */
--text-secondary: #4d5760; /* ~7.5:1 on white */
--text-muted: #6b7784; /* ~4.6:1 on white — AA compliant */
/* Borders */
--border: #c8d3db;
/* Accent — primary teal from couch outline */
--accent: #1f7d94; /* ~4.6:1 on white — AA compliant */
--accent-hover: #165f70; /* darker for hover */
--accent-light: #e0f0f4; /* very light teal tint for backgrounds */
/* Series — steel blue from sofa body */
--series-color: #1e6b8a; /* ~5.0:1 on white — AA */
--series-bg: #dceef5;
/* Movie — warm coral (complementary to teal, accessible) */
--movie-color: #b5451b; /* ~5.5:1 on white — AA */
--movie-bg: #fdeee8;
/* Torrent — mid teal-green */
--torrent-color: #1a7a6e; /* ~4.7:1 on white — AA */
--torrent-bg: #ddf2ef;
/* State colours */
--success: #2e7d32; /* ~7.1:1 on white — AA */
--success-bg: #e8f5e9;
--info: #2196f3;
--info-bg: #e3f2fd;
--danger: #f44336;
--danger-bg: #ffebee;
--danger-border: #ffcdd2;
--progress-bg: #ffebee;
--progress-border: #ffcdd2;
--progress-fill-start: #4caf50;
--progress-fill-end: #66bb6a;
--shadow: rgba(0, 0, 0, 0.1);
--shadow-strong: rgba(0, 0, 0, 0.15);
--footer-text: rgba(255, 255, 255, 0.9);
--info: #1565c0; /* ~7.3:1 on white — AA */
--info-bg: #e3f0fb;
--danger: #c62828; /* ~6.5:1 on white — AA */
--danger-bg: #fdecea;
--danger-border: #f5c6c2;
/* Progress bar */
--progress-bg: #eaf2f5;
--progress-border: #c8d3db;
--progress-fill-start: #1f7d94;
--progress-fill-end: #2da0bc;
/* Shadows */
--shadow: rgba(30, 60, 80, 0.10);
--shadow-strong: rgba(30, 60, 80, 0.18);
/* Footer — dark text on light page background */
--footer-text: #4d5760;
/* Inputs */
--input-bg: #ffffff;
--select-bg: #ffffff;
/* Unmatched tag — amber, accessible on its bg */
--unmatched-tag-bg: #fff3e0;
--unmatched-tag-color: #e65100;
--unmatched-tag-color: #7a4000; /* ~7.1:1 on #fff3e0 — AA */
}
[data-theme="dark"] {
@@ -552,6 +579,251 @@ body {
word-break: break-word;
}
/* ===== Main Tabs ===== */
.main-tabs {
max-width: 1200px;
margin: 16px auto 0;
padding: 0 16px;
}
.tab-bar {
display: flex;
gap: 4px;
border-bottom: 2px solid var(--border);
margin-bottom: 0;
}
.tab-btn {
background: none;
border: none;
border-bottom: 3px solid transparent;
margin-bottom: -2px;
padding: 10px 20px;
font-size: 0.95rem;
font-weight: 600;
color: var(--text-secondary);
cursor: pointer;
transition: color 0.2s, border-color 0.2s;
border-radius: 4px 4px 0 0;
}
.tab-btn:hover {
color: var(--text-primary);
background: var(--surface);
}
.tab-btn.active {
color: var(--accent);
border-bottom-color: var(--accent);
background: var(--surface);
}
.tab-panel {
padding-top: 0;
}
/* ===== Recently Completed History ===== */
.history-container {
max-width: unset;
margin: 0;
padding: 0;
}
.history-header {
display: flex;
align-items: center;
gap: 12px;
margin-bottom: 12px;
flex-wrap: wrap;
}
.history-header h2 {
margin: 0;
font-size: 1.2rem;
color: var(--text-primary);
flex: 1 1 auto;
}
.history-controls {
display: flex;
align-items: center;
gap: 6px;
flex-wrap: nowrap;
}
.history-days-label {
font-size: 0.85rem;
color: var(--text-secondary);
}
.history-days-input {
width: 52px;
padding: 3px 6px;
border: 1px solid var(--border);
border-radius: 4px;
background: var(--surface);
color: var(--text-primary);
font-size: 0.85rem;
text-align: center;
}
.history-refresh-btn {
background: none;
border: 1px solid var(--border);
border-radius: 4px;
color: var(--text-secondary);
cursor: pointer;
font-size: 1rem;
padding: 2px 7px;
line-height: 1.4;
transition: background 0.15s, color 0.15s;
}
.history-refresh-btn:hover {
background: var(--hover-bg);
color: var(--text-primary);
}
.history-loading,
.history-error,
.no-history {
color: var(--text-secondary);
font-size: 0.9rem;
padding: 8px 0;
}
.history-error {
color: var(--error, #e74c3c);
}
.history-list {
display: flex;
flex-direction: column;
gap: 8px;
}
.history-card {
display: flex;
gap: 12px;
background: var(--surface);
border: 1px solid var(--border);
border-radius: 8px;
padding: 10px 12px;
transition: background 0.2s;
align-items: flex-start;
}
.history-card.failed {
border-left: 3px solid var(--error, #e74c3c);
}
.history-card.imported {
border-left: 3px solid var(--success, #27ae60);
}
.history-cover {
flex: 0 0 48px;
width: 48px;
}
.history-cover img {
width: 48px;
height: 68px;
object-fit: cover;
border-radius: 4px;
display: block;
}
.history-info {
flex: 1 1 auto;
min-width: 0;
}
.history-card-header {
display: flex;
flex-wrap: wrap;
gap: 5px;
align-items: center;
margin-bottom: 4px;
}
.history-type-badge,
.history-outcome-badge,
.history-instance-badge {
font-size: 0.72rem;
font-weight: 600;
padding: 2px 7px;
border-radius: 10px;
white-space: nowrap;
}
.history-type-badge.series {
background: var(--badge-series-bg, #2980b9);
color: #fff;
}
.history-type-badge.movie {
background: var(--badge-movie-bg, #8e44ad);
color: #fff;
}
.history-outcome-badge.imported {
background: var(--success, #27ae60);
color: #fff;
}
.history-outcome-badge.failed {
background: var(--error, #e74c3c);
color: #fff;
}
.history-instance-badge {
background: var(--tag-bg, #ecf0f1);
color: var(--text-secondary);
border: 1px solid var(--border);
}
.history-title {
font-size: 0.9rem;
font-weight: 600;
margin: 0 0 2px;
color: var(--text-primary);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.history-media-name {
font-size: 0.82rem;
color: var(--text-secondary);
margin: 0 0 4px;
}
.history-details {
display: flex;
flex-wrap: wrap;
gap: 5px;
margin-top: 4px;
}
.history-failure-message {
font-size: 0.78rem;
color: var(--error, #e74c3c);
background: var(--error-bg, rgba(231, 76, 60, 0.08));
border-radius: 4px;
padding: 3px 7px;
flex-basis: 100%;
}
@media (max-width: 480px) {
.history-cover {
display: none;
}
.history-title {
white-space: normal;
}
}
/* ===== Footer ===== */
.app-footer {
margin-top: 12px;

View File

@@ -16,6 +16,7 @@ const sonarrRoutes = require('./routes/sonarr');
const radarrRoutes = require('./routes/radarr');
const embyRoutes = require('./routes/emby');
const dashboardRoutes = require('./routes/dashboard');
const historyRoutes = require('./routes/history');
const authRoutes = require('./routes/auth');
const verifyCsrf = require('./middleware/verifyCsrf');
@@ -100,6 +101,7 @@ function createApp({ skipRateLimits = false } = {}) {
app.use('/api/radarr', radarrRoutes);
app.use('/api/emby', embyRoutes);
app.use('/api/dashboard', dashboardRoutes);
app.use('/api/history', historyRoutes);
// Global error handler
// eslint-disable-next-line no-unused-vars

View File

@@ -5,6 +5,8 @@ const helmet = require('helmet');
const rateLimit = require('express-rate-limit');
const crypto = require('crypto');
const fs = require('fs');
const http = require('http');
const https = require('https');
require('dotenv').config();
// Setup logging with levels
@@ -77,6 +79,7 @@ const sonarrRoutes = require('./routes/sonarr');
const radarrRoutes = require('./routes/radarr');
const embyRoutes = require('./routes/emby');
const dashboardRoutes = require('./routes/dashboard');
const historyRoutes = require('./routes/history');
const authRoutes = require('./routes/auth');
const verifyCsrf = require('./middleware/verifyCsrf');
const { startPoller, POLL_INTERVAL, POLLING_ENABLED } = require('./utils/poller');
@@ -99,6 +102,9 @@ if (!process.env.EMBY_URL && process.env.NODE_ENV === 'production') {
const app = express();
const PORT = process.env.PORT || 3001;
// Resolve TLS_ENABLED early — used in Helmet CSP and server startup
const TLS_ENABLED = (process.env.TLS_ENABLED || 'true').toLowerCase() !== 'false';
// ---------------------------------------------------------------------------
// Trust proxy — required when behind Nginx/Caddy/Traefik so that
// req.ip reflects the real client IP (not 127.0.0.1) and
@@ -137,7 +143,7 @@ app.use((req, res, next) => {
baseUri: ["'self'"],
frameAncestors: ["'none'"],
formAction: ["'self'"],
upgradeInsecureRequests: process.env.TRUST_PROXY ? [] : null
upgradeInsecureRequests: (process.env.TRUST_PROXY || TLS_ENABLED) ? [] : null
}
},
hsts: {
@@ -245,6 +251,7 @@ app.use('/api/sonarr', sonarrRoutes);
app.use('/api/radarr', radarrRoutes);
app.use('/api/emby', embyRoutes);
app.use('/api/dashboard', dashboardRoutes);
app.use('/api/history', historyRoutes);
// SPA catch-all — serve index.html for any unmatched path
app.get('*', serveIndex);
@@ -258,10 +265,52 @@ app.use((err, req, res, next) => {
res.status(500).json({ error: 'Internal server error' });
});
app.listen(PORT, () => {
// ---------------------------------------------------------------------------
// TLS / HTTPS support
// Set TLS_CERT and TLS_KEY to paths of your certificate and private key.
// If unset, defaults to the bundled snakeoil self-signed certificate
// (localhost/127.0.0.1 only — suitable for local testing).
// Set TLS_ENABLED=false to force plain HTTP even if cert files exist.
// ---------------------------------------------------------------------------
const CERTS_DIR = path.join(__dirname, '../certs');
const TLS_CERT_PATH = process.env.TLS_CERT || path.join(CERTS_DIR, 'snakeoil.crt');
const TLS_KEY_PATH = process.env.TLS_KEY || path.join(CERTS_DIR, 'snakeoil.key');
function loadTlsCredentials() {
if (!TLS_ENABLED) return null;
try {
return {
cert: fs.readFileSync(TLS_CERT_PATH),
key: fs.readFileSync(TLS_KEY_PATH)
};
} catch (err) {
console.warn(`[TLS] Could not load certificate files — falling back to HTTP. (${err.message})`);
return null;
}
}
const tlsCredentials = loadTlsCredentials();
const server = tlsCredentials
? https.createServer(tlsCredentials, app)
: http.createServer(app);
const protocol = tlsCredentials ? 'https' : 'http';
const isSnakeoil = TLS_ENABLED &&
(!process.env.TLS_CERT || process.env.TLS_CERT === TLS_CERT_PATH);
server.listen(PORT, () => {
console.log(`=================================`);
console.log(` sofarr - Your Downloads Dashboard`);
console.log(` Server running on port ${PORT}`);
console.log(` Server running on ${protocol}://localhost:${PORT}`);
if (tlsCredentials && isSnakeoil) {
console.warn(` [TLS] Using bundled snakeoil certificate (self-signed).`);
console.warn(` [TLS] Set TLS_CERT and TLS_KEY for a trusted certificate.`);
console.warn(` [TLS] Set TLS_ENABLED=false to disable TLS entirely.`);
} else if (tlsCredentials) {
console.log(` [TLS] Certificate: ${TLS_CERT_PATH}`);
} else {
console.warn(` [TLS] Running in plain HTTP mode — not suitable for production.`);
}
console.log(` Log level: ${process.env.LOG_LEVEL || 'info'}`);
console.log(` Polling: ${POLLING_ENABLED ? POLL_INTERVAL + 'ms' : 'disabled (on-demand)'}`);
console.log(` Trust proxy: ${process.env.TRUST_PROXY || 'disabled'}`);

272
server/routes/history.js Normal file
View File

@@ -0,0 +1,272 @@
const express = require('express');
const router = express.Router();
const axios = require('axios');
const requireAuth = require('../middleware/requireAuth');
const cache = require('../utils/cache');
const { fetchSonarrHistory, fetchRadarrHistory, classifySonarrEvent, classifyRadarrEvent } = require('../utils/historyFetcher');
const { getSonarrInstances, getRadarrInstances } = require('../utils/config');
const sanitizeError = require('../utils/sanitizeError');
// Re-use the same tag/cover-art helpers as dashboard.js by importing them
// from a shared location. For now they are inlined here to keep dashboard.js
// untouched (zero-conflict v1 merges). If these diverge they can be extracted
// into server/utils/dashboardHelpers.js in a later refactor.
function getCoverArt(item) {
if (!item || !item.images) return null;
const poster = item.images.find(img => img.coverType === 'poster');
if (poster) return poster.remoteUrl || poster.url || null;
const fanart = item.images.find(img => img.coverType === 'fanart');
return fanart ? (fanart.remoteUrl || fanart.url || null) : null;
}
function sanitizeTagLabel(input) {
if (!input) return '';
return input.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/-+/g, '-').replace(/^-|-$/g, '');
}
function tagMatchesUser(tag, username) {
if (!tag || !username) return false;
const tagLower = tag.toLowerCase();
if (tagLower === username) return true;
if (tagLower === sanitizeTagLabel(username)) return true;
return false;
}
function extractAllTags(tags, tagMap) {
if (!tags || tags.length === 0) return [];
if (tagMap) return tags.map(id => tagMap.get(id)).filter(Boolean);
return tags.map(t => t && t.label).filter(Boolean);
}
function extractUserTag(tags, tagMap, username) {
const allLabels = extractAllTags(tags, tagMap);
if (!allLabels.length) return null;
if (username) {
const match = allLabels.find(label => tagMatchesUser(label, username));
if (match) return match;
}
return null;
}
async function getEmbyUsers() {
const cached = cache.get('emby:users');
if (cached) return cached;
try {
const embyUrl = process.env.EMBY_URL;
const embyKey = process.env.EMBY_API_KEY;
if (!embyUrl || !embyKey) return new Map();
const res = await axios.get(`${embyUrl}/Users`, { params: { api_key: embyKey } });
const users = res.data || [];
const map = new Map();
for (const u of users) {
if (!u.Name) continue;
const lower = u.Name.toLowerCase();
map.set(lower, u.Name);
map.set(sanitizeTagLabel(lower), u.Name);
}
cache.set('emby:users', map, 60000);
return map;
} catch (err) {
console.error('[History] Failed to fetch Emby users:', err.message);
return new Map();
}
}
function buildTagBadges(allTags, embyUserMap) {
return allTags.map(label => {
const lower = label.toLowerCase();
const sanitized = sanitizeTagLabel(label);
const matchedUser = embyUserMap.get(lower) || embyUserMap.get(sanitized) || null;
return { label, matchedUser };
});
}
function getSonarrLink(series) {
if (!series || !series._instanceUrl || !series.titleSlug) return null;
return `${series._instanceUrl}/series/${series.titleSlug}`;
}
function getRadarrLink(movie) {
if (!movie || !movie._instanceUrl || !movie.titleSlug) return null;
return `${movie._instanceUrl}/movie/${movie.titleSlug}`;
}
/**
* GET /api/history/recent
*
* Returns Sonarr/Radarr history records (imported + failed) for the
* authenticated user, filtered to the last RECENT_COMPLETED_DAYS days
* (default 7, overridable via env or ?days= query param).
*
* Response shape:
* {
* user: string,
* isAdmin: boolean,
* days: number,
* history: HistoryItem[]
* }
*
* HistoryItem shape:
* {
* type: 'series'|'movie',
* outcome: 'imported'|'failed',
* title: string, // sourceTitle from arr record
* seriesName?: string, // series.title (Sonarr)
* movieName?: string, // movie.title (Radarr)
* coverArt: string|null,
* completedAt: string, // ISO date string from arr record
* quality: string|null,
* instanceName: string, // arr instance name
* arrLink: string|null, // link to item in Sonarr/Radarr UI
* allTags: string[],
* matchedUserTag: string|null,
* // admin-only:
* arrRecordId?: number,
* failureMessage?: string,
* }
*/
router.get('/recent', requireAuth, async (req, res) => {
try {
const user = req.user;
const username = user.name.toLowerCase();
const isAdmin = !!user.isAdmin;
const showAll = isAdmin && req.query.showAll === 'true';
const defaultDays = parseInt(process.env.RECENT_COMPLETED_DAYS, 10) || 7;
const requestedDays = parseInt(req.query.days, 10);
const days = (requestedDays > 0 && requestedDays <= 90) ? requestedDays : defaultDays;
const since = new Date(Date.now() - days * 24 * 60 * 60 * 1000);
// Fetch tag maps and history in parallel
const sonarrInstances = getSonarrInstances();
const radarrInstances = getRadarrInstances();
const [sonarrHistory, radarrHistory, embyUserMap] = await Promise.all([
fetchSonarrHistory(since),
fetchRadarrHistory(since),
showAll ? getEmbyUsers() : Promise.resolve(new Map())
]);
// Build tag maps from the cached poll data where available,
// falling back to what's embedded in history records
const sonarrTagsData = cache.get('poll:sonarr-tags') || [];
const radarrTagsData = cache.get('poll:radarr-tags') || [];
const sonarrTagMap = new Map(sonarrTagsData.flatMap(t => t.data || []).map(t => [t.id, t.label]));
const radarrTagMap = new Map(radarrTagsData.map(t => [t.id, t.label]));
const historyItems = [];
// --- Sonarr history ---
for (const record of sonarrHistory) {
try {
const outcome = classifySonarrEvent(record.eventType);
if (outcome === 'other') continue;
const series = record.series;
if (!series) continue;
const allTags = extractAllTags(series.tags, sonarrTagMap);
const matchedUserTag = extractUserTag(series.tags, sonarrTagMap, username);
const hasAnyTag = allTags.length > 0;
if (!(showAll ? hasAnyTag : !!matchedUserTag)) continue;
const quality = record.quality && record.quality.quality && record.quality.quality.name
? record.quality.quality.name
: null;
const item = {
type: 'series',
outcome,
title: record.sourceTitle || record.title || series.title,
seriesName: series.title,
coverArt: getCoverArt(series),
completedAt: record.date,
quality,
instanceName: record._instanceName || null,
arrLink: getSonarrLink(series),
allTags,
matchedUserTag: matchedUserTag || null,
tagBadges: showAll ? buildTagBadges(allTags, embyUserMap) : undefined
};
if (isAdmin) {
item.arrRecordId = record.id;
if (outcome === 'failed' && record.data && record.data.message) {
item.failureMessage = record.data.message;
}
}
historyItems.push(item);
} catch (err) {
console.error('[History] Error processing Sonarr record:', err.message);
}
}
// --- Radarr history ---
for (const record of radarrHistory) {
try {
const outcome = classifyRadarrEvent(record.eventType);
if (outcome === 'other') continue;
const movie = record.movie;
if (!movie) continue;
const allTags = extractAllTags(movie.tags, radarrTagMap);
const matchedUserTag = extractUserTag(movie.tags, radarrTagMap, username);
const hasAnyTag = allTags.length > 0;
if (!(showAll ? hasAnyTag : !!matchedUserTag)) continue;
const quality = record.quality && record.quality.quality && record.quality.quality.name
? record.quality.quality.name
: null;
const item = {
type: 'movie',
outcome,
title: record.sourceTitle || record.title || movie.title,
movieName: movie.title,
coverArt: getCoverArt(movie),
completedAt: record.date,
quality,
instanceName: record._instanceName || null,
arrLink: getRadarrLink(movie),
allTags,
matchedUserTag: matchedUserTag || null,
tagBadges: showAll ? buildTagBadges(allTags, embyUserMap) : undefined
};
if (isAdmin) {
item.arrRecordId = record.id;
if (outcome === 'failed' && record.data && record.data.message) {
item.failureMessage = record.data.message;
}
}
historyItems.push(item);
} catch (err) {
console.error('[History] Error processing Radarr record:', err.message);
}
}
// Sort newest first
historyItems.sort((a, b) => new Date(b.completedAt) - new Date(a.completedAt));
console.log(`[History] Returning ${historyItems.length} items for user ${user.name} (days=${days}, showAll=${showAll})`);
res.json({
user: user.name,
isAdmin,
days,
history: historyItems
});
} catch (err) {
console.error('[History] Error:', err.message);
res.status(500).json({ error: 'Failed to fetch history', details: sanitizeError(err) });
}
});
module.exports = router;

View File

@@ -0,0 +1,141 @@
const axios = require('axios');
const cache = require('./cache');
const { getSonarrInstances, getRadarrInstances } = require('./config');
// Cache TTL for recent-history data: 5 minutes.
// History changes slowly compared to active downloads.
const HISTORY_CACHE_TTL = 5 * 60 * 1000;
// Sonarr event types that represent a successful import
const SONARR_IMPORTED_EVENTS = new Set(['downloadFolderImported', 'downloadImported']);
// Sonarr event types that represent a failed import
const SONARR_FAILED_EVENTS = new Set(['downloadFailed', 'importFailed']);
// Radarr equivalents
const RADARR_IMPORTED_EVENTS = new Set(['downloadFolderImported', 'downloadImported']);
const RADARR_FAILED_EVENTS = new Set(['downloadFailed', 'importFailed']);
/**
* Fetch recent history records from all Sonarr instances for the given date window.
* Results are cached under 'history:sonarr' for HISTORY_CACHE_TTL.
* @param {Date} since - Only include records on or after this date
* @returns {Promise<Array>} Flat array of Sonarr history records (with _instanceUrl and _instanceName)
*/
async function fetchSonarrHistory(since) {
const cacheKey = 'history:sonarr';
const cached = cache.get(cacheKey);
if (cached) return cached;
const instances = getSonarrInstances();
const results = await Promise.all(instances.map(async inst => {
try {
const response = await axios.get(`${inst.url}/api/v3/history`, {
headers: { 'X-Api-Key': inst.apiKey },
params: {
pageSize: 100,
sortKey: 'date',
sortDir: 'descending',
includeSeries: true,
startDate: since.toISOString()
}
});
const records = (response.data && response.data.records) || [];
return records.map(r => {
if (r.series) r.series._instanceUrl = inst.url;
if (r.series) r.series._instanceName = inst.name || inst.id;
r._instanceUrl = inst.url;
r._instanceName = inst.name || inst.id;
return r;
});
} catch (err) {
console.error(`[HistoryFetcher] Sonarr ${inst.id} error:`, err.message);
return [];
}
}));
const flat = results.flat();
cache.set(cacheKey, flat, HISTORY_CACHE_TTL);
return flat;
}
/**
* Fetch recent history records from all Radarr instances for the given date window.
* Results are cached under 'history:radarr' for HISTORY_CACHE_TTL.
* @param {Date} since - Only include records on or after this date
* @returns {Promise<Array>} Flat array of Radarr history records (with _instanceUrl and _instanceName)
*/
async function fetchRadarrHistory(since) {
const cacheKey = 'history:radarr';
const cached = cache.get(cacheKey);
if (cached) return cached;
const instances = getRadarrInstances();
const results = await Promise.all(instances.map(async inst => {
try {
const response = await axios.get(`${inst.url}/api/v3/history`, {
headers: { 'X-Api-Key': inst.apiKey },
params: {
pageSize: 100,
sortKey: 'date',
sortDir: 'descending',
includeMovie: true,
startDate: since.toISOString()
}
});
const records = (response.data && response.data.records) || [];
return records.map(r => {
if (r.movie) r.movie._instanceUrl = inst.url;
if (r.movie) r.movie._instanceName = inst.name || inst.id;
r._instanceUrl = inst.url;
r._instanceName = inst.name || inst.id;
return r;
});
} catch (err) {
console.error(`[HistoryFetcher] Radarr ${inst.id} error:`, err.message);
return [];
}
}));
const flat = results.flat();
cache.set(cacheKey, flat, HISTORY_CACHE_TTL);
return flat;
}
/**
* Classify a Sonarr history record's event type.
* @param {string} eventType
* @returns {'imported'|'failed'|'other'}
*/
function classifySonarrEvent(eventType) {
if (SONARR_IMPORTED_EVENTS.has(eventType)) return 'imported';
if (SONARR_FAILED_EVENTS.has(eventType)) return 'failed';
return 'other';
}
/**
* Classify a Radarr history record's event type.
* @param {string} eventType
* @returns {'imported'|'failed'|'other'}
*/
function classifyRadarrEvent(eventType) {
if (RADARR_IMPORTED_EVENTS.has(eventType)) return 'imported';
if (RADARR_FAILED_EVENTS.has(eventType)) return 'failed';
return 'other';
}
/**
* Invalidate cached history so the next request fetches fresh data.
* Called externally if needed (e.g. after a forced refresh).
*/
function invalidateHistoryCache() {
cache.invalidate('history:sonarr');
cache.invalidate('history:radarr');
}
module.exports = {
fetchSonarrHistory,
fetchRadarrHistory,
classifySonarrEvent,
classifyRadarrEvent,
invalidateHistoryCache,
HISTORY_CACHE_TTL
};

View File

@@ -0,0 +1,289 @@
/**
* Integration tests for GET /api/history/recent
*
* Uses supertest against createApp() with vi.mock to stub historyFetcher
* (avoids nock/ESM-CJS interop issues with axios) and nock for Emby auth.
* Covers:
* - 401 when unauthenticated
* - Empty history response when arr returns no records
* - Filters out records whose eventType is not imported/failed
* - Returns imported and failed records for tagged series/movies
* - ?days= param is respected (default 7, capped at 90)
* - failureMessage included for admins on failed records
*/
import request from 'supertest';
import nock from 'nock';
import { beforeEach, afterEach } from 'vitest';
import { createRequire } from 'module';
import { createApp } from '../../server/app.js';
// Use createRequire to get the same CJS singleton cache instance that
// server/utils/historyFetcher.js and server/routes/history.js use via
// require('./cache'). A plain ESM `import cache from '...'` resolves
// to a different module identity under vitest's ESM runtime.
const require = createRequire(import.meta.url);
const cache = require('../../server/utils/cache.js');
const EMBY_BASE = 'https://emby.test';
process.env.EMBY_URL = EMBY_BASE;
process.env.SONARR_INSTANCES = JSON.stringify([
{ id: 'sonarr-1', name: 'Main Sonarr', url: 'https://sonarr.test', apiKey: 'sk' }
]);
process.env.RADARR_INSTANCES = JSON.stringify([
{ id: 'radarr-1', name: 'Main Radarr', url: 'https://radarr.test', apiKey: 'rk' }
]);
// --- Fixtures ---
const EMBY_AUTH = { AccessToken: 'tok', User: { Id: 'uid1', Name: 'alice' } };
const EMBY_USER = { Id: 'uid1', Name: 'alice', Policy: { IsAdministrator: false } };
const EMBY_ADMIN = { Id: 'uid2', Name: 'admin', Policy: { IsAdministrator: true } };
const EMBY_AUTH_ADMIN = { AccessToken: 'tok2', User: { Id: 'uid2', Name: 'admin' } };
// Sonarr tag: id 1 → 'alice'
const SONARR_TAGS = [{ id: 1, label: 'alice' }];
const SONARR_RECORD_IMPORTED = {
id: 100,
eventType: 'downloadFolderImported',
sourceTitle: 'Show.S01E01.720p',
date: new Date().toISOString(),
quality: { quality: { name: '720p' } },
series: { id: 10, title: 'My Show', titleSlug: 'my-show', tags: [1], images: [] },
seriesId: 10
};
const SONARR_RECORD_FAILED = {
id: 101,
eventType: 'downloadFailed',
sourceTitle: 'Show.S01E02.720p',
date: new Date().toISOString(),
quality: { quality: { name: '720p' } },
data: { message: 'Not enough disk space' },
series: { id: 11, title: 'Admin Show', titleSlug: 'admin-show', tags: [2], images: [] },
};
// Tag id 2 → 'admin' (used in the failed-import admin test)
const SONARR_TAGS_WITH_ADMIN = [{ id: 1, label: 'alice' }, { id: 2, label: 'admin' }];
const SONARR_RECORD_FAILED_ALICE = { // failed record tagged alice, for event-type filtering test
id: 103,
eventType: 'downloadFailed',
sourceTitle: 'Show.S01E02.720p',
date: new Date().toISOString(),
quality: { quality: { name: '720p' } },
data: { message: 'Disk full' },
series: { id: 10, title: 'My Show', titleSlug: 'my-show', tags: [1], images: [] },
seriesId: 10
};
const SONARR_RECORD_GRABBED = {
id: 102,
eventType: 'grabbed',
sourceTitle: 'Show.S01E03.720p',
date: new Date().toISOString(),
series: { id: 10, title: 'My Show', titleSlug: 'my-show', tags: [1], images: [] },
seriesId: 10
};
const RADARR_RECORD_IMPORTED = {
id: 200,
eventType: 'downloadFolderImported',
sourceTitle: 'My.Movie.2024.1080p',
date: new Date().toISOString(),
quality: { quality: { name: '1080p' } },
movie: { id: 20, title: 'My Movie', titleSlug: 'my-movie-2024', tags: [1], images: [] },
movieId: 20
};
// --- Helpers ---
function interceptLogin(userBody = EMBY_USER, authBody = EMBY_AUTH) {
nock(EMBY_BASE).post('/Users/authenticatebyname').reply(200, authBody);
nock(EMBY_BASE).get(/\/Users\//).reply(200, userBody);
}
// Pre-seed the history cache keys that fetchSonarrHistory/fetchRadarrHistory check
// first, so they return without making any HTTP calls.
const CACHE_TTL = 60 * 60 * 1000; // 1 hour — won't expire during a test run
function setHistory(sonarrRecords = [], radarrRecords = []) {
cache.set('history:sonarr', sonarrRecords.map(r => ({
...r,
_instanceName: 'Main Sonarr',
series: r.series ? { ...r.series, _instanceUrl: 'https://sonarr.test', _instanceName: 'Main Sonarr' } : undefined
})), CACHE_TTL);
cache.set('history:radarr', radarrRecords.map(r => ({
...r,
_instanceName: 'Main Radarr',
movie: r.movie ? { ...r.movie, _instanceUrl: 'https://radarr.test', _instanceName: 'Main Radarr' } : undefined
})), CACHE_TTL);
}
async function loginAs(app, userBody = EMBY_USER, authBody = EMBY_AUTH) {
interceptLogin(userBody, authBody);
const res = await request(app)
.post('/api/auth/login')
.send({ username: userBody.Name, password: 'pw' });
const cookies = res.headers['set-cookie'];
const csrf = res.body.csrfToken;
return { cookies, csrf };
}
beforeEach(() => {
// Clear history caches so each test controls its own data
cache.invalidate('history:sonarr');
cache.invalidate('history:radarr');
// Default: empty history
setHistory([], []);
// Seed poll tag caches so the route can resolve tags
cache.set('poll:sonarr-tags', [{ data: SONARR_TAGS }], 60000);
cache.set('poll:radarr-tags', [], 60000);
});
afterEach(() => {
nock.cleanAll();
cache.invalidate('history:sonarr');
cache.invalidate('history:radarr');
});
describe('GET /api/history/recent', () => {
describe('authentication', () => {
it('returns 401 when not logged in', async () => {
const app = createApp({ skipRateLimits: true });
const res = await request(app).get('/api/history/recent');
expect(res.status).toBe(401);
});
});
describe('empty history', () => {
it('returns empty array when arr returns no records', async () => {
const app = createApp({ skipRateLimits: true });
const { cookies } = await loginAs(app);
const res = await request(app)
.get('/api/history/recent')
.set('Cookie', cookies);
expect(res.status).toBe(200);
expect(res.body.history).toEqual([]);
expect(res.body.days).toBe(7);
});
});
describe('event type filtering', () => {
it('includes imported and failed records, excludes grabbed', async () => {
const app = createApp({ skipRateLimits: true });
setHistory(
[SONARR_RECORD_IMPORTED, SONARR_RECORD_FAILED_ALICE, SONARR_RECORD_GRABBED],
[]
);
const { cookies } = await loginAs(app);
const res = await request(app)
.get('/api/history/recent')
.set('Cookie', cookies);
expect(res.status).toBe(200);
const outcomes = res.body.history.map(h => h.outcome);
expect(outcomes).toContain('imported');
expect(outcomes).toContain('failed');
expect(res.body.history).toHaveLength(2);
});
});
describe('tag filtering', () => {
it('only returns records tagged for the current user', async () => {
const app = createApp({ skipRateLimits: true });
setHistory([SONARR_RECORD_IMPORTED], []);
const { cookies } = await loginAs(app);
const res = await request(app)
.get('/api/history/recent')
.set('Cookie', cookies);
expect(res.status).toBe(200);
expect(res.body.history).toHaveLength(1);
expect(res.body.history[0].seriesName).toBe('My Show');
expect(res.body.history[0].outcome).toBe('imported');
expect(res.body.history[0].quality).toBe('720p');
});
it('excludes records tagged for a different user', async () => {
const app = createApp({ skipRateLimits: true });
const bobAuth = { AccessToken: 'tok3', User: { Id: 'uid3', Name: 'bob' } };
const bobUser = { Id: 'uid3', Name: 'bob', Policy: { IsAdministrator: false } };
setHistory([SONARR_RECORD_IMPORTED], []);
const { cookies } = await loginAs(app, bobUser, bobAuth);
const res = await request(app)
.get('/api/history/recent')
.set('Cookie', cookies);
expect(res.status).toBe(200);
expect(res.body.history).toHaveLength(0);
});
});
describe('radarr records', () => {
it('returns movie history items', async () => {
const app = createApp({ skipRateLimits: true });
cache.set('poll:radarr-tags', [{ id: 1, label: 'alice' }], 60000);
setHistory([], [RADARR_RECORD_IMPORTED]);
const { cookies } = await loginAs(app);
const res = await request(app)
.get('/api/history/recent')
.set('Cookie', cookies);
expect(res.status).toBe(200);
expect(res.body.history).toHaveLength(1);
expect(res.body.history[0].type).toBe('movie');
expect(res.body.history[0].movieName).toBe('My Movie');
});
});
describe('?days parameter', () => {
it('uses custom days value', async () => {
const app = createApp({ skipRateLimits: true });
const { cookies } = await loginAs(app);
const res = await request(app)
.get('/api/history/recent?days=14')
.set('Cookie', cookies);
expect(res.status).toBe(200);
expect(res.body.days).toBe(14);
});
it('caps days at 90', async () => {
const app = createApp({ skipRateLimits: true });
const { cookies } = await loginAs(app);
const res = await request(app)
.get('/api/history/recent?days=999')
.set('Cookie', cookies);
expect(res.status).toBe(200);
expect(res.body.days).toBe(7); // falls back to default when > 90
});
});
describe('failed import details', () => {
it('includes failureMessage for admin on failed records', async () => {
const app = createApp({ skipRateLimits: true });
cache.set('poll:sonarr-tags', [{ data: SONARR_TAGS_WITH_ADMIN }], 60000);
setHistory([SONARR_RECORD_FAILED], []);
const { cookies } = await loginAs(app, EMBY_ADMIN, EMBY_AUTH_ADMIN);
const res = await request(app)
.get('/api/history/recent')
.set('Cookie', cookies);
expect(res.status).toBe(200);
const failed = res.body.history.find(h => h.outcome === 'failed');
expect(failed).toBeDefined();
expect(failed.failureMessage).toBe('Not enough disk space');
});
});
describe('response shape', () => {
it('returns correct top-level fields', async () => {
const app = createApp({ skipRateLimits: true });
const { cookies } = await loginAs(app);
const res = await request(app)
.get('/api/history/recent')
.set('Cookie', cookies);
expect(res.status).toBe(200);
expect(res.body).toHaveProperty('user');
expect(res.body).toHaveProperty('isAdmin');
expect(res.body).toHaveProperty('days');
expect(res.body).toHaveProperty('history');
expect(Array.isArray(res.body.history)).toBe(true);
});
});
});

View File

@@ -0,0 +1,177 @@
/**
* Unit tests for server/utils/historyFetcher.js
*
* Covers:
* - classifySonarrEvent / classifyRadarrEvent event classification
* - fetchSonarrHistory / fetchRadarrHistory: successful fetch, cache hit, per-instance errors
* - invalidateHistoryCache
*/
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import nock from 'nock';
// Env must be set before importing modules that read it at load time
process.env.SONARR_INSTANCES = JSON.stringify([
{ id: 'sonarr-1', name: 'Main Sonarr', url: 'https://sonarr.test', apiKey: 'sonarr-key' }
]);
process.env.RADARR_INSTANCES = JSON.stringify([
{ id: 'radarr-1', name: 'Main Radarr', url: 'https://radarr.test', apiKey: 'radarr-key' }
]);
const { classifySonarrEvent, classifyRadarrEvent, fetchSonarrHistory, fetchRadarrHistory, invalidateHistoryCache } =
await import('../../server/utils/historyFetcher.js');
const since = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000);
afterEach(() => {
nock.cleanAll();
invalidateHistoryCache();
});
describe('classifySonarrEvent', () => {
it('returns imported for downloadFolderImported', () => {
expect(classifySonarrEvent('downloadFolderImported')).toBe('imported');
});
it('returns imported for downloadImported', () => {
expect(classifySonarrEvent('downloadImported')).toBe('imported');
});
it('returns failed for downloadFailed', () => {
expect(classifySonarrEvent('downloadFailed')).toBe('failed');
});
it('returns failed for importFailed', () => {
expect(classifySonarrEvent('importFailed')).toBe('failed');
});
it('returns other for grabbed', () => {
expect(classifySonarrEvent('grabbed')).toBe('other');
});
it('returns other for unknown event', () => {
expect(classifySonarrEvent('someFutureEvent')).toBe('other');
});
});
describe('classifyRadarrEvent', () => {
it('returns imported for downloadFolderImported', () => {
expect(classifyRadarrEvent('downloadFolderImported')).toBe('imported');
});
it('returns failed for downloadFailed', () => {
expect(classifyRadarrEvent('downloadFailed')).toBe('failed');
});
it('returns other for grabbed', () => {
expect(classifyRadarrEvent('grabbed')).toBe('other');
});
});
describe('fetchSonarrHistory', () => {
const mockRecords = [
{
id: 1,
eventType: 'downloadFolderImported',
sourceTitle: 'Show.S01E01',
date: new Date().toISOString(),
series: { id: 10, title: 'My Show', titleSlug: 'my-show', tags: [] },
seriesId: 10
}
];
it('fetches records and tags them with _instanceUrl and _instanceName', async () => {
nock('https://sonarr.test')
.get('/api/v3/history')
.query(true)
.reply(200, { records: mockRecords });
const result = await fetchSonarrHistory(since);
expect(result).toHaveLength(1);
expect(result[0].series._instanceUrl).toBe('https://sonarr.test');
expect(result[0].series._instanceName).toBe('Main Sonarr');
expect(result[0]._instanceName).toBe('Main Sonarr');
});
it('returns cached data on second call without making a new HTTP request', async () => {
nock('https://sonarr.test')
.get('/api/v3/history')
.query(true)
.reply(200, { records: mockRecords });
const first = await fetchSonarrHistory(since);
// Second call — nock would throw if a second request was made
const second = await fetchSonarrHistory(since);
expect(second).toEqual(first);
});
it('returns empty array and does not throw when instance errors', async () => {
nock('https://sonarr.test')
.get('/api/v3/history')
.query(true)
.replyWithError('ECONNREFUSED');
const result = await fetchSonarrHistory(since);
expect(result).toEqual([]);
});
it('handles missing records key gracefully', async () => {
nock('https://sonarr.test')
.get('/api/v3/history')
.query(true)
.reply(200, {});
const result = await fetchSonarrHistory(since);
expect(result).toEqual([]);
});
});
describe('fetchRadarrHistory', () => {
const mockRecords = [
{
id: 2,
eventType: 'downloadFolderImported',
sourceTitle: 'My.Movie.2024',
date: new Date().toISOString(),
movie: { id: 20, title: 'My Movie', titleSlug: 'my-movie-2024', tags: [] },
movieId: 20
}
];
it('fetches records and tags them with _instanceUrl and _instanceName', async () => {
nock('https://radarr.test')
.get('/api/v3/history')
.query(true)
.reply(200, { records: mockRecords });
const result = await fetchRadarrHistory(since);
expect(result).toHaveLength(1);
expect(result[0].movie._instanceUrl).toBe('https://radarr.test');
expect(result[0].movie._instanceName).toBe('Main Radarr');
});
it('returns empty array on network error', async () => {
nock('https://radarr.test')
.get('/api/v3/history')
.query(true)
.replyWithError('timeout');
const result = await fetchRadarrHistory(since);
expect(result).toEqual([]);
});
});
describe('invalidateHistoryCache', () => {
it('forces a fresh fetch after invalidation', async () => {
nock('https://sonarr.test')
.get('/api/v3/history')
.query(true)
.reply(200, { records: [] });
await fetchSonarrHistory(since);
invalidateHistoryCache();
// Should make a second HTTP request — nock will satisfy it
nock('https://sonarr.test')
.get('/api/v3/history')
.query(true)
.reply(200, { records: [] });
const result = await fetchSonarrHistory(since);
expect(result).toEqual([]);
expect(nock.isDone()).toBe(true);
});
});