Compare commits

...

6 Commits

Author SHA1 Message Date
gronod 6f6aa5b967 merge branch 'develop' into 'main' - Release v1.7.20
Build and Push Docker Image / build (push) Successful in 1m13s
Create Release / release (push) Successful in 1m3s
CI / Security audit (push) Successful in 2m36s
CI / Swagger Validation & Coverage (push) Successful in 3m7s
CI / Tests & coverage (push) Successful in 3m15s
2026-05-26 13:43:33 +01:00
gronod 5390bbf615 chore: bump version to 1.7.20 and resolve Ombi user hydration issue
Build and Push Docker Image / build (push) Successful in 2m6s
Docs Check / Markdown lint (push) Successful in 1m58s
Licence Check / Licence compatibility and copyright header verification (push) Successful in 2m4s
Docs Check / Mermaid diagram parse check (push) Successful in 1m58s
CI / Security audit (push) Successful in 1m48s
CI / Tests & coverage (push) Successful in 1m59s
CI / Swagger Validation & Coverage (push) Successful in 1m47s
2026-05-26 11:30:49 +01:00
gronod fb68bddedb merge branch 'develop' into 'main' - Update Release v1.7.19 to ignore scratch directory
Build and Push Docker Image / build (push) Successful in 1m8s
Create Release / release (push) Successful in 36s
CI / Tests & coverage (push) Successful in 1m55s
CI / Security audit (push) Successful in 2m12s
CI / Swagger Validation & Coverage (push) Successful in 1m50s
2026-05-25 08:33:16 +01:00
gronod 81d0aa82f2 chore: add scratch/ to gitignore and untrack existing scratch files
Build and Push Docker Image / build (push) Successful in 1m17s
Licence Check / Licence compatibility and copyright header verification (push) Successful in 2m26s
CI / Swagger Validation & Coverage (push) Successful in 3m1s
CI / Security audit (push) Successful in 3m15s
CI / Tests & coverage (push) Successful in 3m42s
2026-05-25 08:32:33 +01:00
gronod 7d7304637c merge branch 'develop' into 'main' - Release v1.7.19
Create Release / release (push) Successful in 33s
Build and Push Docker Image / build (push) Successful in 2m19s
CI / Security audit (push) Successful in 2m14s
CI / Tests & coverage (push) Successful in 2m21s
CI / Swagger Validation & Coverage (push) Successful in 2m24s
2026-05-25 08:28:28 +01:00
gronod d87ad9f1c7 fix: mobile request card overflow (#49) and admin arrLink active badges (#50), bump version to 1.7.19
Build and Push Docker Image / build (push) Successful in 1m23s
Docs Check / Markdown lint (push) Successful in 1m42s
Licence Check / Licence compatibility and copyright header verification (push) Failing after 2m33s
Docs Check / Mermaid diagram parse check (push) Successful in 3m19s
CI / Security audit (push) Successful in 3m21s
CI / Swagger Validation & Coverage (push) Successful in 3m40s
CI / Tests & coverage (push) Successful in 4m57s
2026-05-25 08:28:16 +01:00
28 changed files with 293 additions and 260 deletions
+2 -1
View File
@@ -11,4 +11,5 @@ data/
*.db-wal *.db-wal
*.db-shm *.db-shm
.agents/ .agents/
.windsurf/ .windsurf/
scratch/
+21
View File
@@ -4,6 +4,27 @@ All notable changes to this project will be documented in this file.
Format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). Format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [1.7.20] - 2026-05-26
### Fixed
- **Ombi Requesting User Hydration (Issue #51)** — Resolved a bug where Sofarr displayed "Unknown" for the requesting user on requests even when the Ombi database contains valid user information. Added automatic requestedUser object hydration on the server side by fetching the full user list from `/api/v1/Identity/Users` and caching it in memory. If a request is missing the nested `requestedUser` details but possesses a valid `requestedUserId`, Sofarr automatically resolves and binds the user's username/alias. Added robust unit tests safeguarding the client and the retriever. Resolves Gitea Issue [#51](https://git.i3omb.com/Gandalf/sofarr/issues/51).
### Changed
- **Aligned Gitea Interaction Skill** — Updated `.windsurf/skills/gitea-interaction/SKILL.md` to align with the Antigravity `tea-interaction` hybrid interaction model guidelines, detailing when to use the editor extension versus the Gitea CLI.
---
## [1.7.19] - 2026-05-25
### Fixed
- **Requests Mobile CSS Overflow Fix (Issue #49)** — Resolved the remaining viewport overflow on narrow screens by adding `min-width: 0` to `.request-card` to allow proper flexbox and grid shrinking, reducing mobile `.main-tabs` padding to `0 8px`, and tightening `.requests-container` mobile padding to `8px`.
- **Admin *arr Badge Links on Active Downloads (Issue #50)** — Fixed the missing Sonarr/Radarr badges and links on active downloads for admin users. Enabled robust `_instanceUrl` propagation during queue/history metadata compilation (`buildMetadataMaps`) and active matching (`DownloadMatcher.js`) to ensure link generation succeeds. Added complete schema documentation in OpenAPI.
---
## [1.7.18] - 2026-05-24 ## [1.7.18] - 2026-05-24
### Fixed ### Fixed
+2 -2
View File
@@ -1,12 +1,12 @@
{ {
"name": "sofarr", "name": "sofarr",
"version": "1.7.18", "version": "1.7.20",
"lockfileVersion": 3, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "sofarr", "name": "sofarr",
"version": "1.7.18", "version": "1.7.20",
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"axios": "^1.6.0", "axios": "^1.6.0",
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "sofarr", "name": "sofarr",
"version": "1.7.18", "version": "1.7.20",
"description": "A personal media download dashboard that shows your downloads 'so far' while you relax on the sofa waiting for your *arr services to finish", "description": "A personal media download dashboard that shows your downloads 'so far' while you relax on the sofa waiting for your *arr services to finish",
"main": "server/index.js", "main": "server/index.js",
"scripts": { "scripts": {
+7 -1
View File
@@ -1888,12 +1888,17 @@ body {
/* ===== Mobile ===== */ /* ===== Mobile ===== */
@media (max-width: 768px) { @media (max-width: 768px) {
.main-tabs {
padding: 0 8px;
}
.requests-container { .requests-container {
padding: 12px; padding: 8px;
} }
.request-card { .request-card {
gap: 8px; gap: 8px;
padding: 10px;
} }
.request-meta { .request-meta {
@@ -2258,6 +2263,7 @@ body {
border: 1px solid var(--border); border: 1px solid var(--border);
border-radius: 8px; border-radius: 8px;
transition: box-shadow 0.2s ease, border-color 0.2s ease; transition: box-shadow 0.2s ease, border-color 0.2s ease;
min-width: 0;
} }
.request-card:hover { .request-card:hover {
-21
View File
@@ -1,21 +0,0 @@
Problem:
The "Blocklist & Search" button on download cards fails with a "400 Bad Request (Missing required fields)" when clicked on any television release in Sonarr that represents a full season package or a multi-episode release.
Root Cause:
1. In `server/services/DownloadMatcher.js`, when a download is matched with a Sonarr queue record, `arrContentId` is populated with `sonarrMatch.episodeId || null`.
2. However, for multi-episode packs or full season grabs in Sonarr v3, the `episodeId` field is missing from the queue record payload (since the release is associated with multiple episodes). Instead, Sonarr provides an `episodeIds` array. As a result, `arrContentId` is normalized to `null`.
3. When the user clicks the "Blocklist & Search" button in the UI, the frontend calls the `POST /api/dashboard/blocklist-search` endpoint. The request body includes `arrContentId: null`.
4. The backend route validator in `server/routes/dashboard.js` strictly requires all fields including `arrContentId` to be truthy:
```javascript
if (!arrQueueId || !arrType || !arrInstanceUrl || !arrContentId || !arrContentType) {
return res.status(400).json({ error: 'Missing required fields' });
}
```
Because `arrContentId` is `null`, this check fails and returns `400 Missing required fields`, completely blocking the blocklist operation (even though queue removal itself does not require an episode ID).
5. Furthermore, the search trigger logic in `dashboard.js` only handles single episode searches via `{ name: 'EpisodeSearch', episodeIds: [arrContentId] }` and has no logic to handle `episodeIds` arrays or fallback searches (such as `SeriesSearch` or `SeasonSearch`).
Proposed Fix:
1. **Relax Backend Validation**: Allow `arrContentId` to be optional or null for `sonarr` queue records to ensure the deletion and blocklist steps can still execute.
2. **Robust Search Triggers**:
- If `episodeId` is missing but `episodeIds` array is available on the matched record, pass the array of IDs to the frontend/backend.
- Modify the `dashboard.js` re-search block to support `EpisodeSearch` with multiple IDs, or fall back to triggering a `SeriesSearch` command using the `seriesId` if no specific episode IDs are resolved.
-16
View File
@@ -1,16 +0,0 @@
Title:
FEATURE: Client-side console log capturing and streaming API endpoint with dual-authentication
Problem / Requirement:
To aid in frontend troubleshooting, developers need a way to capture and gather client-side console logs (`console.log`, `console.warn`, `console.error`) and make them accessible over a real-time log stream endpoint. This helps debug frontend issues (such as SSE failures, CSP violations, and state synchronization issues) in environments without direct access to browser devtools.
Success Criteria:
1. Client-Side Interceptor: Intercept standard browser console methods at SPA startup and place captured logs into an in-memory queue.
2. Batched Log Transmission (Selected Option A): Periodic HTTP POST batch queries to `POST /api/debug/client-logs` (every 2 seconds or when the queue hits 20 items) to minimize browser thread and network overhead.
3. Server storage and SSE log streaming:
- Save incoming logs into a separate rolling 1000-line buffer `clientLogBuffer`.
- Expose `GET /api/debug/client-logs/stream` to stream client-side logs in real-time via SSE.
4. Security & Configuration:
- Enableable only when the environment variable `ENABLE_LOG_STREAM=true` is set.
- Enforce exact same dual-auth rules (Emby session cookie, Basic Auth fallback, and X-Webhook-Secret header bypass) on both client logs endpoints.
5. API Documentation: Documented in `server/openapi.yaml`.
-12
View File
@@ -1,12 +0,0 @@
Amended the plan to add client-side console log capturing and streaming options:
### Proposed Client Logging Design:
- **Client-Side Capture (Frontend Interception)**: Hook into standard browser console methods (`console.log`, `console.warn`, `console.error`) at client-side startup.
- **Client-to-Server Transmission**:
- **Option A (Recommended)**: Store captured logs in a local memory queue, and periodically perform a batched `POST /api/debug/client-logs` (every 2 seconds or when the queue hits 20 items) to minimize network overhead.
- **Option B (WebSocket Channel)**: Stream logs instantly via persistent WebSockets, which adds structural and connection management complexity.
- **Server Storage & SSE Streaming**:
- Store incoming client logs in a separate rolling 1000-line buffer `clientLogBuffer`.
- Expose `GET /api/debug/client-logs/stream` (under the exact same dual-auth/webhook-secret constraints) to stream client-side logs in real-time via SSE to debugging tools.
The `implementation_plan.md` artifact has been successfully updated with these options.
-32
View File
@@ -1,32 +0,0 @@
const axios = require('axios');
const fs = require('fs');
const secret = '63f7eaf2b4e3ca7da48c003d5986afc8ba31119404d49e45102c61fc3a27329a';
const serverLogsUrl = 'https://sofarr.i3omb.com/api/debug/server-logs?testClose=true';
const clientLogsUrl = 'https://sofarr.i3omb.com/api/debug/client-logs?testClose=true';
async function fetchLogs(url, filename) {
console.log(`Fetching logs from ${url}...`);
try {
const response = await axios.get(url, {
headers: {
'x-webhook-secret': secret
}
});
fs.writeFileSync(filename, response.data);
console.log(`Logs saved to ${filename} (${response.data.length} bytes).`);
} catch (err) {
console.error(`Failed to fetch from ${url}:`, err.message);
if (err.response) {
console.error(`Status: ${err.response.status}`);
console.error(`Body:`, JSON.stringify(err.response.data));
}
}
}
async function run() {
await fetchLogs(serverLogsUrl, 'scratch/remote_server.log');
await fetchLogs(clientLogsUrl, 'scratch/remote_client.log');
}
run();
-26
View File
@@ -1,26 +0,0 @@
## Regression: Fix in v1.7.16 was insufficient — issue persists in production
### Updated Root Cause Analysis
Post-release investigation of live server debug logs on `sofarr.i3omb.com` confirms the blocklist feature is **still failing** after v1.7.16. The server logs still show:
```
[Blocklist] Download not found: { arrQueueId: 439913856, arrType: 'radarr' }
```
The v1.7.16 fix cast both sides of the comparison to `String`, which was the correct approach — but it was applied to the **wrong data source**.
The permission check at line 693 of `dashboard.js` calls:
```js
const allDownloads = await downloadClientRegistry.getAllDownloads();
const download = allDownloads.find(d => d.arrQueueId != null && String(d.arrQueueId) === String(arrQueueId) && d.arrType === arrType);
```
`downloadClientRegistry.getAllDownloads()` fetches **raw download client data** directly from qBittorrent, SABnzbd, etc. — these are unmatched objects with no Sonarr/Radarr queue metadata. The `arrQueueId` field is only populated during `DownloadMatcher.js` processing (which runs during the SSE/dashboard build from the *arr cache). Because qBittorrent's `normalizeDownload()` never sets `arrQueueId`, the lookup **always returns `undefined`** for any qBittorrent torrent, regardless of type casting.
### Correct Fix
The permission check should validate against the **Sonarr/Radarr queue cache records** directly (where `id` is the queue record ID), rather than against raw download client data. The fix will replace the `downloadClientRegistry.getAllDownloads()` lookup with a direct cache lookup of `poll:sonarr-queue` / `poll:radarr-queue` records, matching by `String(record.id) === String(arrQueueId)`.
This will be released in v1.7.17.
-46
View File
@@ -1,46 +0,0 @@
## Summary
The "Blocklist and search" feature is broken for all users. Clicking the blocklist button on a download (e.g. the film "Project Hail Mary", `arrQueueId: 905000340`, `arrType: radarr`) consistently returns a `403 Download not found or permission denied` error.
## Root Cause
The server-side lookup in `server/routes/dashboard.js` uses strict equality (`===`) to find the matching download:
```js
const download = allDownloads.find(d => d.arrQueueId === arrQueueId && d.arrType === arrType);
```
- `d.arrQueueId` is populated from the Radarr/Sonarr queue API response as a **number** (e.g. `905000340`).
- `arrQueueId` from `req.body` originates from the client SPA via a DOM `dataset` attribute, which is always a **string** (e.g. `"905000340"`).
- Due to the type mismatch, `905000340 === "905000340"` evaluates to `false`, so the lookup always fails and returns `403`.
## Evidence
Server log (live environment, `2026-05-24`):
```
[Blocklist] Download not found: { arrQueueId: 905000340, arrType: 'radarr' }
```
Client log confirms user clicked blocklist at `21:01:19`, `21:01:32`, and `21:02:35`.
## Steps to Reproduce
1. Open the dashboard on a Radarr or Sonarr download with a pending queue entry.
2. Click the "Blocklist and search" button.
3. The action silently fails; the download is not removed and no re-search is triggered.
4. Server logs show `[Blocklist] Download not found`.
## Proposed Fix
Cast both sides of the comparison to `String` before comparing:
```js
const download = allDownloads.find(d => d.arrQueueId != null && String(d.arrQueueId) === String(arrQueueId) && d.arrType === arrType);
```
This fix will be released in version `1.7.16`.
## Severity
**High** — The blocklist-and-search feature is completely non-functional for all users. There is no workaround within the UI.
-19
View File
@@ -1,19 +0,0 @@
Title:
FEATURE: Log streaming debug endpoint with dual-authentication and togglable runtime configuration
Problem / Requirement:
Administrators and developers need a lightweight, real-time method to stream application stdout/stderr logs (which correspond exactly to Docker container logs in standard setups) directly through the API. This enables easier live debugging without requiring full Docker daemon or terminal access.
Success Criteria:
1. **Lightweight Log Streaming**: Streams process standard output/error (representing Docker logs) via Server-Sent Events (SSE). Keep a rolling buffer of the last 1000 lines in memory.
2. **Dual-Authentication**:
- Accepts existing session cookie (`emby_user`) with administrative credentials.
- Accepts standard HTTP Basic Authentication (`Authorization: Basic <base64>`) using Emby administrator username/password credentials.
3. **Runtime Configuration Toggle**: Enableable using a runtime environment variable `ENABLE_LOG_STREAM=true` (defaulting to `false`/disabled). When disabled, returns a `403 Forbidden` response.
4. **API Spec Documentation**: Documented in `server/openapi.yaml` under the `/api/debug/logs` endpoint, including the query format and response schemas.
Proposed Implementation:
1. **Log Interceptor**: Implement a global stdout/stderr hook in `server/index.js` or in a new `server/utils/logCapture.js` to collect a rolling buffer of 1000 log lines and expose a Node `EventEmitter` to push new logs to active subscribers.
2. **Authentication Middleware**: Create `server/middleware/logStreamAuth.js` which verifies active sessions or fallback Basic Auth headers by calling Emby's `/Users/authenticatebyname` and `/Users/{id}` endpoints to verify the user is a valid administrator.
3. **Route Definition**: Define `server/routes/debug.js` to register `GET /api/debug/logs` backing the SSE stream, enforce the `ENABLE_LOG_STREAM === 'true'` check, and execute `logStreamAuth` checks.
4. **OpenAPI Spec Integration**: Define `/api/debug/logs` schemas, parameters, security schemes, and basic auth descriptions inside `server/openapi.yaml`.
-21
View File
@@ -1,21 +0,0 @@
### Bug Description
Ombi webhooks are currently failing to authenticate. In `server/routes/webhook.js`, all `/api/webhook/*` endpoints (sonarr, radarr, and ombi) require the custom `X-Sofarr-Webhook-Secret` HTTP header to be present and match the configured `SOFARR_WEBHOOK_SECRET`.
However, Ombi's built-in Webhook notification agent does not support adding custom HTTP headers to its outgoing webhook notification requests. This makes it impossible for Ombi to successfully authenticate using the current header-only validation mechanism.
### Root Cause
In `server/routes/webhook.js`, `validateWebhookSecret(req)` only inspects `req.get('X-Sofarr-Webhook-Secret')`:
```javascript
function validateWebhookSecret(req) {
const expectedSecret = getWebhookSecret();
const providedSecret = req.get('X-Sofarr-Webhook-Secret');
...
}
```
Since Ombi sends standard JSON payloads to a configured URL without custom headers, it cannot supply this header, resulting in a `401 Unauthorized` response.
### Proposed Remediation
1. **Fallback Authentication Method**: Update `validateWebhookSecret(req)` in `server/routes/webhook.js` to look for the secret in either the `X-Sofarr-Webhook-Secret` header OR as a `secret` query parameter (`req.query.secret`).
2. **Registration Update**: Update the `/webhook/enable` route in `server/routes/ombi.js` to automatically append `?secret=${webhookSecret}` to the registered `webhookUrl` sent to Ombi.
3. **OpenAPI Spec & JSDoc Updates**: Document the query-parameter fallback authentication option in `server/openapi.yaml` and the `@openapi` JSDoc comments in `server/routes/webhook.js`.
4. **Integration Testing**: Add new integration tests in `tests/integration/webhook.test.js` to assert that authentication via query parameters succeeds, and that invalid query parameters are rejected.
-6
View File
@@ -1,6 +0,0 @@
Amended the plan to include a high-priority bypass using the `X-Webhook-Secret` request header:
1. **Webhook Secret Bypass**: If the request contains the `X-Webhook-Secret` header, we verify if it matches the configured `SOFARR_WEBHOOK_SECRET` environment variable.
2. **Access Granted**: If matching, the request is immediately authorized, completely bypassing session and Emby Basic Auth checks. This is ideal for curl scripts, server-to-server monitoring, or external debugging logs captures.
I have updated the `implementation_plan.md` artifact to reflect this amendment.
-15
View File
@@ -1,15 +0,0 @@
I have investigated the blocklist & search failure reported in this issue and created a technical remediation plan:
### Root Cause
For television grabs representing a full-season pack or multi-episode package in Sonarr, the `episodeId` property is absent (instead, it has an `episodeIds` array). This maps to a `null` value for `arrContentId` on the client download card. The `/api/dashboard/blocklist-search` route strictly requires all fields including `arrContentId` to be truthy, returning `400 Bad Request: Missing required fields` and completely blocking the queue blocklist/removal action.
### Remediation Plan
1. **Enrich Backend Match Data**: Expose `arrContentIds` (`sonarrMatch.episodeIds`) and `arrSeriesId` (`sonarrMatch.seriesId`) from `DownloadMatcher.js` to the normalized download card object.
2. **Relax API Route Validation**: Remove `arrContentId` from the mandatory request parameters check in `server/routes/dashboard.js`.
3. **Enhance Search Commands**:
- If a single `arrContentId` is provided, trigger `EpisodeSearch` for that single ID.
- If an `arrContentIds` array is provided, trigger `EpisodeSearch` with that list of IDs.
- If no specific episode IDs can be resolved but `arrSeriesId` is provided, fall back to triggering a series-wide `SeriesSearch`.
4. **Update Frontend & Documentation**: Update the client payload, update the OpenAPI spec, and add integration tests covering single/multi/fallback searches.
Upon approval, I will execute this plan, merge to `main`, close this ticket referencing the resolving commit, and cut a new point release (v1.7.11).
-14
View File
@@ -1,14 +0,0 @@
Title:
FEATURE: Togglable server-side (Docker) log streaming debug endpoint with dual-authentication
Problem / Requirement:
Administrators and developers need a lightweight, real-time method to stream application stdout/stderr logs (which correspond exactly to Docker container logs in standard setups) directly through the API. This enables easier live debugging without requiring full Docker daemon or terminal access.
Success Criteria:
1. Lightweight Log Streaming: Streams process standard output/error (representing Docker logs) via Server-Sent Events (SSE). Keep a rolling buffer of the last 1000 lines in memory.
2. Dual-Authentication with Webhook Secret Bypass:
- Accepts existing session cookie (emby_user) with administrative credentials.
- Accepts standard HTTP Basic Authentication (Authorization: Basic <base64>) using Emby administrator username/password credentials.
- Accepts X-Webhook-Secret header matching the SOFARR_WEBHOOK_SECRET environment variable for programmatic bypass.
3. Runtime Configuration Toggle: Enableable using a runtime environment variable ENABLE_LOG_STREAM=true (defaulting to false/disabled). When disabled, returns a 403 Forbidden response.
4. API Spec Documentation: Documented in server/openapi.yaml under the /api/debug/logs endpoint, including the query format and response schemas.
-9
View File
@@ -1,9 +0,0 @@
Release v1.7.16
Remediate the blocklist-search queue ID type mismatch. The "Blocklist and
search" action was returning 403 for all users because the arrQueueId
comparison used strict equality between a string (from the SPA DOM dataset)
and a number (from the Radarr/Sonarr API). Both values are now cast to
String before comparison.
See CHANGELOG.md for full details.
-1
View File
@@ -1 +0,0 @@
63f7eaf2b4e3ca7da48c003d5986afc8ba31119404d49e45102c61fc3a27329a
+1 -1
View File
@@ -132,7 +132,7 @@ function createApp({ skipRateLimits = false } = {}) {
* version: * version:
* type: string * type: string
* description: sofarr version * description: sofarr version
* example: "1.7.16" * example: "1.7.20"
* x-code-samples: * x-code-samples:
* - lang: curl * - lang: curl
* label: cURL * label: cURL
+14
View File
@@ -125,6 +125,20 @@ class OmbiClient {
return false; return false;
} }
} }
/**
* Get all users from Ombi
* @returns {Promise<Array>} Array of user objects
*/
async getUsers() {
try {
const response = await this.axios.get(`${this.url}/api/v1/Identity/Users`);
return response.data || [];
} catch (error) {
logToFile(`[OmbiClient] Get users error: ${error.message}`);
return [];
}
}
} }
module.exports = OmbiClient; module.exports = OmbiClient;
+70 -10
View File
@@ -16,8 +16,10 @@ class OmbiRetriever extends ArrRetriever {
this.cache = { this.cache = {
movieRequests: [], movieRequests: [],
tvRequests: [], tvRequests: [],
users: [],
movieMap: new Map(), // tmdbId -> request movieMap: new Map(), // tmdbId -> request
tvMap: new Map(), // tvdbId -> request tvMap: new Map(), // tvdbId -> request
userMap: new Map(), // id -> user
lastFetch: 0, lastFetch: 0,
ttl: 5 * 60 * 1000 // 5 minutes TTL ttl: 5 * 60 * 1000 // 5 minutes TTL
}; };
@@ -98,20 +100,32 @@ class OmbiRetriever extends ArrRetriever {
try { try {
logToFile('[OmbiRetriever] Refreshing cache'); logToFile('[OmbiRetriever] Refreshing cache');
// Fetch requests in parallel // Fetch requests and users in parallel
const [movieRequests, tvRequests] = await Promise.all([ const [movieRequests, tvRequests, users] = await Promise.all([
this.client.getMovieRequests(), this.client.getMovieRequests(),
this.client.getTvRequests() this.client.getTvRequests(),
this.client.getUsers()
]); ]);
// Update cache // Update cache
this.cache.movieRequests = movieRequests; this.cache.movieRequests = movieRequests;
this.cache.tvRequests = tvRequests; this.cache.tvRequests = tvRequests;
this.cache.users = users;
this.cache.lastFetch = Date.now(); this.cache.lastFetch = Date.now();
// Build lookup maps // Build lookup maps
this.cache.movieMap.clear(); this.cache.movieMap.clear();
this.cache.tvMap.clear(); this.cache.tvMap.clear();
this.cache.userMap.clear();
// Build user map (id -> user)
if (Array.isArray(users)) {
users.forEach(user => {
if (user && user.id) {
this.cache.userMap.set(user.id, user);
}
});
}
// Build movie map (tmdbId -> request) // Build movie map (tmdbId -> request)
movieRequests.forEach(request => { movieRequests.forEach(request => {
@@ -133,13 +147,59 @@ class OmbiRetriever extends ArrRetriever {
} }
}); });
logToFile(`[OmbiRetriever] Cache refreshed: ${movieRequests.length} movies, ${tvRequests.length} TV shows`); logToFile(`[OmbiRetriever] Cache refreshed: ${movieRequests.length} movies, ${tvRequests.length} TV shows, ${users.length} users`);
} catch (error) { } catch (error) {
logToFile(`[OmbiRetriever] Cache refresh failed: ${error.message}`); logToFile(`[OmbiRetriever] Cache refresh failed: ${error.message}`);
// Don't throw error, continue with stale cache if available // Don't throw error, continue with stale cache if available
} }
} }
/**
* Hydrates requestedUser on a single request using the userMap cache
* @param {Object} req - The request object
* @returns {Object} Hydrated request object
* @private
*/
_hydrateRequest(req) {
if (!req) return req;
const reqUserId = req.requestedUserId || req.RequestedUserId;
if (reqUserId && this.cache.userMap.has(reqUserId)) {
const cachedUser = this.cache.userMap.get(reqUserId);
let requestedUser = req.requestedUser || req.RequestedUser;
// If requestedUser is not an object or is empty/null, populate it
if (!requestedUser || typeof requestedUser !== 'object' || Object.keys(requestedUser).length === 0) {
const hydratedUser = {
id: cachedUser.id,
userName: cachedUser.userName,
alias: cachedUser.alias || cachedUser.Alias || '',
userAlias: cachedUser.userAlias || cachedUser.UserAlias || '',
normalizedUserName: cachedUser.normalizedUserName || cachedUser.NormalizedUserName || ''
};
return {
...req,
requestedUser: hydratedUser,
RequestedUser: hydratedUser
};
}
}
return req;
}
/**
* Hydrates requestedUser on a list of requests using the userMap cache
* @param {Array} requests - Array of request objects
* @returns {Array} Array of hydrated request objects
* @private
*/
_hydrateRequests(requests) {
if (!Array.isArray(requests)) return [];
return requests.map(req => this._hydrateRequest(req));
}
/** /**
* Get all movie requests * Get all movie requests
* @param {boolean} force - Whether to force refresh from API * @param {boolean} force - Whether to force refresh from API
@@ -147,7 +207,7 @@ class OmbiRetriever extends ArrRetriever {
*/ */
async getMovieRequests(force = false) { async getMovieRequests(force = false) {
await this.refreshCache(force); await this.refreshCache(force);
return this.cache.movieRequests; return this._hydrateRequests(this.cache.movieRequests);
} }
/** /**
@@ -157,7 +217,7 @@ class OmbiRetriever extends ArrRetriever {
*/ */
async getTvRequests(force = false) { async getTvRequests(force = false) {
await this.refreshCache(force); await this.refreshCache(force);
return this.cache.tvRequests; return this._hydrateRequests(this.cache.tvRequests);
} }
/** /**
@@ -171,12 +231,12 @@ class OmbiRetriever extends ArrRetriever {
// Try TMDB ID first // Try TMDB ID first
if (tmdbId && this.cache.movieMap.has(tmdbId)) { if (tmdbId && this.cache.movieMap.has(tmdbId)) {
return this.cache.movieMap.get(tmdbId); return this._hydrateRequest(this.cache.movieMap.get(tmdbId));
} }
// Try IMDB ID as fallback // Try IMDB ID as fallback
if (imdbId && this.cache.movieMap.has(imdbId)) { if (imdbId && this.cache.movieMap.has(imdbId)) {
return this.cache.movieMap.get(imdbId); return this._hydrateRequest(this.cache.movieMap.get(imdbId));
} }
return null; return null;
@@ -193,12 +253,12 @@ class OmbiRetriever extends ArrRetriever {
// Try TVDB ID first // Try TVDB ID first
if (tvdbId && this.cache.tvMap.has(tvdbId)) { if (tvdbId && this.cache.tvMap.has(tvdbId)) {
return this.cache.tvMap.get(tvdbId); return this._hydrateRequest(this.cache.tvMap.get(tvdbId));
} }
// Try TMDB ID as fallback // Try TMDB ID as fallback
if (tmdbId && this.cache.tvMap.has(tmdbId)) { if (tmdbId && this.cache.tvMap.has(tmdbId)) {
return this.cache.tvMap.get(tmdbId); return this._hydrateRequest(this.cache.tvMap.get(tmdbId));
} }
return null; return null;
+1 -1
View File
@@ -249,7 +249,7 @@ app.use(express.json({ limit: '64kb' })); // prevent oversized JSON payloads
* version: * version:
* type: string * type: string
* description: sofarr version * description: sofarr version
* example: "1.7.16" * example: "1.7.20"
*/ */
app.get('/health', (req, res) => { app.get('/health', (req, res) => {
res.json({ status: 'ok', uptime: process.uptime(), version }); res.json({ status: 'ok', uptime: process.uptime(), version });
+22 -1
View File
@@ -22,7 +22,7 @@ info:
## SSE Streaming ## SSE Streaming
Real-time updates are available via Server-Sent Events at GET /api/dashboard/stream. Real-time updates are available via Server-Sent Events at GET /api/dashboard/stream.
version: 1.7.18 version: 1.7.20
contact: contact:
name: sofarr name: sofarr
license: license:
@@ -176,6 +176,27 @@ components:
nullable: true nullable: true
description: Tooltip text for Ombi icon ("Request" or "Search") description: Tooltip text for Ombi icon ("Request" or "Search")
example: "Request" example: "Request"
arrLink:
type: string
nullable: true
format: uri
description: Sonarr/Radarr show/movie web UI link (admin-only)
example: "http://sonarr:8989/series/show-slug"
downloadPath:
type: string
nullable: true
description: Save path in download client (admin-only)
example: "/downloads/series/show-slug"
targetPath:
type: string
nullable: true
description: Target path in library (admin-only)
example: "/tv/show-slug"
arrInstanceKey:
type: string
nullable: true
description: Sonarr/Radarr instance API key (admin-only)
example: "api-key-here"
DashboardPayload: DashboardPayload:
type: object type: object
+30 -4
View File
@@ -51,17 +51,43 @@ function readCacheSnapshot() {
function buildMetadataMaps(snapshot) { function buildMetadataMaps(snapshot) {
const seriesMap = new Map(); const seriesMap = new Map();
for (const r of snapshot.sonarrQueue.data.records) { for (const r of snapshot.sonarrQueue.data.records) {
if (r.series && r.seriesId) seriesMap.set(r.seriesId, r.series); if (r.series && r.seriesId) {
if (!r.series._instanceUrl && r._instanceUrl) {
r.series._instanceUrl = r._instanceUrl;
}
seriesMap.set(r.seriesId, r.series);
}
} }
for (const r of snapshot.sonarrHistory.data.records) { for (const r of snapshot.sonarrHistory.data.records) {
if (r.series && r.seriesId && !seriesMap.has(r.seriesId)) seriesMap.set(r.seriesId, r.series); if (r.series && r.seriesId) {
if (!r.series._instanceUrl && r._instanceUrl) {
r.series._instanceUrl = r._instanceUrl;
}
const existing = seriesMap.get(r.seriesId);
if (!existing || (!existing._instanceUrl && r.series._instanceUrl)) {
seriesMap.set(r.seriesId, r.series);
}
}
} }
const moviesMap = new Map(); const moviesMap = new Map();
for (const r of snapshot.radarrQueue.data.records) { for (const r of snapshot.radarrQueue.data.records) {
if (r.movie && r.movieId) moviesMap.set(r.movieId, r.movie); if (r.movie && r.movieId) {
if (!r.movie._instanceUrl && r._instanceUrl) {
r.movie._instanceUrl = r._instanceUrl;
}
moviesMap.set(r.movieId, r.movie);
}
} }
for (const r of snapshot.radarrHistory.data.records) { for (const r of snapshot.radarrHistory.data.records) {
if (r.movie && r.movieId && !moviesMap.has(r.movieId)) moviesMap.set(r.movieId, r.movie); if (r.movie && r.movieId) {
if (!r.movie._instanceUrl && r._instanceUrl) {
r.movie._instanceUrl = r._instanceUrl;
}
const existing = moviesMap.get(r.movieId);
if (!existing || (!existing._instanceUrl && r.movie._instanceUrl)) {
moviesMap.set(r.movieId, r.movie);
}
}
} }
const sonarrTagMap = new Map(snapshot.sonarrTagsResults.flatMap(t => t.data || []).map(t => [t.id, t.label])); const sonarrTagMap = new Map(snapshot.sonarrTagsResults.flatMap(t => t.data || []).map(t => [t.id, t.label]));
const radarrTagMap = new Map(snapshot.radarrTags.data.map(t => [t.id, t.label])); const radarrTagMap = new Map(snapshot.radarrTags.data.map(t => [t.id, t.label]));
+12
View File
@@ -215,6 +215,9 @@ async function matchSabSlots(slots, context) {
if (isAdmin) { if (isAdmin) {
dlObj.downloadPath = slot.storage || null; dlObj.downloadPath = slot.storage || null;
dlObj.targetPath = series.path || null; dlObj.targetPath = series.path || null;
if (series && !series._instanceUrl && sonarrMatch._instanceUrl) {
series._instanceUrl = sonarrMatch._instanceUrl;
}
dlObj.arrLink = DownloadAssembler.getSonarrLink(series); dlObj.arrLink = DownloadAssembler.getSonarrLink(series);
dlObj.arrInstanceKey = sonarrMatch._instanceKey || null; dlObj.arrInstanceKey = sonarrMatch._instanceKey || null;
} }
@@ -269,6 +272,9 @@ async function matchSabSlots(slots, context) {
if (isAdmin) { if (isAdmin) {
dlObj.downloadPath = slot.storage || null; dlObj.downloadPath = slot.storage || null;
dlObj.targetPath = movie.path || null; dlObj.targetPath = movie.path || null;
if (movie && !movie._instanceUrl && radarrMatch._instanceUrl) {
movie._instanceUrl = radarrMatch._instanceUrl;
}
dlObj.arrLink = DownloadAssembler.getRadarrLink(movie); dlObj.arrLink = DownloadAssembler.getRadarrLink(movie);
dlObj.arrInstanceKey = radarrMatch._instanceKey || null; dlObj.arrInstanceKey = radarrMatch._instanceKey || null;
} }
@@ -459,6 +465,9 @@ async function matchTorrents(torrents, context) {
if (isAdmin) { if (isAdmin) {
download.downloadPath = download.savePath || null; download.downloadPath = download.savePath || null;
download.targetPath = series.path || null; download.targetPath = series.path || null;
if (series && !series._instanceUrl && sonarrMatch._instanceUrl) {
series._instanceUrl = sonarrMatch._instanceUrl;
}
download.arrLink = DownloadAssembler.getSonarrLink(series); download.arrLink = DownloadAssembler.getSonarrLink(series);
download.arrInstanceKey = sonarrMatch._instanceKey || null; download.arrInstanceKey = sonarrMatch._instanceKey || null;
} }
@@ -505,6 +514,9 @@ async function matchTorrents(torrents, context) {
if (isAdmin) { if (isAdmin) {
download.downloadPath = download.savePath || null; download.downloadPath = download.savePath || null;
download.targetPath = movie.path || null; download.targetPath = movie.path || null;
if (movie && !movie._instanceUrl && radarrMatch._instanceUrl) {
movie._instanceUrl = radarrMatch._instanceUrl;
}
download.arrLink = DownloadAssembler.getRadarrLink(movie); download.arrLink = DownloadAssembler.getRadarrLink(movie);
download.arrInstanceKey = radarrMatch._instanceKey || null; download.arrInstanceKey = radarrMatch._instanceKey || null;
} }
+1
View File
@@ -349,6 +349,7 @@ describe('GET /api/dashboard/user-downloads', () => {
expect(dl.arrQueueId).toBe(1002); expect(dl.arrQueueId).toBe(1002);
expect(dl.arrType).toBe('sonarr'); expect(dl.arrType).toBe('sonarr');
expect(dl.arrInstanceUrl).toBe(SONARR_BASE); expect(dl.arrInstanceUrl).toBe(SONARR_BASE);
expect(dl.arrLink).toBe(SONARR_BASE + '/series/admin-show');
expect(dl.downloadPath).toBeDefined(); expect(dl.downloadPath).toBeDefined();
}); });
+43
View File
@@ -336,4 +336,47 @@ describe('OmbiClient', () => {
expect(result).toBe(false); expect(result).toBe(false);
}); });
}); });
describe('getUsers', () => {
it('should return user array for successful request', async () => {
const mockUsers = [
{ id: '1', userName: 'Gordon' },
{ id: '2', userName: 'Alice' }
];
nock(baseUrl)
.get('/api/v1/Identity/Users')
.matchHeader('ApiKey', apiKey)
.reply(200, mockUsers);
const client = new OmbiClient(baseUrl, apiKey);
const result = await client.getUsers();
expect(result).toEqual(mockUsers);
});
it('should return empty array on API error', async () => {
nock(baseUrl)
.get('/api/v1/Identity/Users')
.matchHeader('ApiKey', apiKey)
.reply(500, { error: 'Internal Server Error' });
const client = new OmbiClient(baseUrl, apiKey);
const result = await client.getUsers();
expect(result).toEqual([]);
});
it('should return empty array on network error', async () => {
nock(baseUrl)
.get('/api/v1/Identity/Users')
.matchHeader('ApiKey', apiKey)
.replyWithError('Network error');
const client = new OmbiClient(baseUrl, apiKey);
const result = await client.getUsers();
expect(result).toEqual([]);
});
});
}); });
+66
View File
@@ -766,4 +766,70 @@ describe('OmbiRetriever', () => {
expect(stats.age).toBeGreaterThanOrEqual(0); expect(stats.age).toBeGreaterThanOrEqual(0);
}); });
}); });
describe('hydration logic', () => {
it('should hydrate requestedUser when missing but requestedUserId is present', async () => {
const mockMovies = [
{ id: 1, title: 'Movie 1', requestedUserId: 'gordon-id', requestedUser: null }
];
const mockTvShows = [];
const mockUsers = [
{ id: 'gordon-id', userName: 'Gordon', alias: 'G-Man' }
];
nock(baseUrl)
.get('/api/v1/Request/movie')
.reply(200, mockMovies);
nock(baseUrl)
.get('/api/v1/Request/tv')
.reply(200, mockTvShows);
nock(baseUrl)
.get('/api/v1/Identity/Users')
.reply(200, mockUsers);
const retriever = new OmbiRetriever(instanceConfig);
const result = await retriever.getMovieRequests();
expect(result).toHaveLength(1);
expect(result[0].requestedUser).toBeDefined();
expect(result[0].requestedUser.userName).toBe('Gordon');
expect(result[0].requestedUser.alias).toBe('G-Man');
});
it('should not overwrite non-empty requestedUser object', async () => {
const mockMovies = [
{
id: 1,
title: 'Movie 1',
requestedUserId: 'gordon-id',
requestedUser: { userName: 'ExistingGordon', alias: 'ExistingG' }
}
];
const mockTvShows = [];
const mockUsers = [
{ id: 'gordon-id', userName: 'Gordon', alias: 'G-Man' }
];
nock(baseUrl)
.get('/api/v1/Request/movie')
.reply(200, mockMovies);
nock(baseUrl)
.get('/api/v1/Request/tv')
.reply(200, mockTvShows);
nock(baseUrl)
.get('/api/v1/Identity/Users')
.reply(200, mockUsers);
const retriever = new OmbiRetriever(instanceConfig);
const result = await retriever.getMovieRequests();
expect(result).toHaveLength(1);
expect(result[0].requestedUser.userName).toBe('ExistingGordon');
expect(result[0].requestedUser.alias).toBe('ExistingG');
});
});
}); });