Skip to content

feat(historyimport): add paginated graphql watchlist sync & plex oauth in admin ui - #388

Closed
drondeseries wants to merge 7 commits into
Silo-Server:mainfrom
drondeseries:main
Closed

drondeseries wants to merge 7 commits into
Silo-Server:mainfrom
drondeseries:main

Conversation

@drondeseries

@drondeseries drondeseries commented Jul 12, 2026 •

Copy link
Copy Markdown

Implement paginated GraphQL watchlist sync for friend accounts, direct admin watchlist fetch, and popup-based Plex OAuth sign-in flow.

Summary by CodeRabbit

  • New Features

    • Added Plex history-import sign-in via PIN + popup OAuth flow.
    • Added admin support for installing plugins from a server-side local ZIP path.
    • Improved playback for .strm shortcuts and dynamic .strm streams.
  • Improvements

    • Plex watchlist enrichment is now best-effort and reports issues as warnings.
    • Enhanced exact matching for titles ending in a parenthesized year.
    • Server base URLs are normalized on save/update.
    • Filesystem browsing now distinguishes directories to improve navigation/selection.
  • Bug Fixes / Behavior

    • “Subtitles off” is preserved when a negative subtitle index is provided.

@coderabbitai

coderabbitai Bot commented Jul 12, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 477dbf88-fb9e-4adc-9833-8b1a74ca8cc3

📥 Commits

Reviewing files that changed from the base of the PR and between d663585 and a967d6f.

📒 Files selected for processing (2)
  • web/src/components/admin/plugins/PluginConfigForm.test.tsx
  • web/src/components/admin/plugins/PluginConfigForm.tsx

📝 Walkthrough

Walkthrough

The PR expands Plex imports with watchlist enrichment and PIN OAuth, adds .strm scanning and playback retries, enables server-local plugin installation, exposes plugin host URLs, and updates filesystem browsing, subtitle handling, request-router defaults, plugin configuration values, and runtime settings.

Changes

Plex history import flow

Layer / File(s) Summary
Match and source normalization
internal/historyimport/matcher.go, internal/historyimport/matcher_test.go, internal/historyimport/service.go
Matching extracts trailing parenthesized years, while source creation and updates normalize base URLs.
Plex UUID and watchlist client
internal/historyimport/plex_client.go
Plex UUID resolution uses caching, and friend watchlists are fetched with pagination and metadata resolution.
Provider watchlist enrichment
internal/historyimport/plex_admin_provider.go, internal/historyimport/plex_admin_provider_test.go
Plex imports append normalized watchlist records and preserve history records when watchlist retrieval fails.
Plex PIN OAuth dialogs
web/src/pages/AdminHistoryImport.tsx
Source and token dialogs use PIN OAuth popups, polling, cancellation, pending states, and token-based saving.

Dynamic stream playback

Layer / File(s) Summary
STRM scanning and playback planning
internal/scanner/*, internal/playback/plan_v3.go, internal/playback/protocol_v3_test.go
.strm files receive synthetic probe data, bypass critical probe repair, and produce deferred transcode plans.
Stream resolution and candidate retry
internal/playback/transcode.go, internal/playback/transcode_manager.go, internal/playback/*test.go
Transcoding resolves .strm URLs, tracks resolver candidates, retries alternate streams, and uses a longer startup recovery wait.
STRM direct playback
internal/playback/directplay.go
Direct playback redirects .strm contents to non-empty remote URLs.

Plugin runtime and administration

Layer / File(s) Summary
Plugin host URL propagation
cmd/silo/main.go, internal/pluginhost/*
Public and internal URLs are propagated to plugin runtime services and installation-scoped proxy configuration.
Local plugin installation
internal/api/handlers/plugins.go, internal/api/router.go, web/src/hooks/queries/admin/plugins.ts, web/src/pages/AdminPlugins.tsx
Administrators can install plugins from existing server paths through a new API route and folder browser.
Filesystem browsing contract
internal/api/handlers/filesystem.go, web/src/api/types.ts, web/src/components/FolderBrowser.tsx, web/src/components/admin/plugins/SchemaForm.tsx
Browse entries identify directories, preserve ZIP files, resolve symlinks, and support path-field browsing.

Protocol and request configuration

Layer / File(s) Summary
Subtitles-off remapping
internal/api/handlers/playback_v3.go, internal/api/handlers/playback_v3_test.go
Negative subtitle indices clear subtitle selection without returning an error.
Request-router connection defaults
web/src/pages/AdminRequests.tsx
Connection forms derive and apply defaults from installed plugin configuration.
Plugin configuration values
web/src/components/admin/plugins/PluginConfigForm.tsx, web/src/components/admin/plugins/PluginConfigForm.test.tsx
Plugin form values preserve saved and default arrays for multi-select fields.

Build configuration

Layer / File(s) Summary
Runner and runtime settings
.github/workflows/docker.yml, cmd/silo/main.go
Docker builds use ubuntu-latest, and the plugin host receives a configured internal base URL.

Estimated code review effort: 5 (Critical) | ~120 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Admin
  participant HistoryImportUI
  participant PlexAuth
  participant PlexImport
  participant PlexAPI
  Admin->>HistoryImportUI: Sign in with Plex
  HistoryImportUI->>PlexAuth: create PIN and poll token
  PlexAuth-->>HistoryImportUI: admin token
  HistoryImportUI->>PlexImport: save source with token
  PlexImport->>PlexAPI: fetch history and watchlist
  PlexAPI-->>PlexImport: records and warnings
Loading

Possibly related PRs

Suggested labels: v1

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 22.22% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title matches the main changes: paginated GraphQL watchlist sync in history import and Plex OAuth sign-in in the admin UI.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot added the v1.0 Silo v1 scope - auto-adds to the Silo v1 project label Jul 12, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 86a2086593

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

// Try to resolve the friend's numeric accountID to their global Plex UUID first.
// Since this is best-effort (privacy settings or not friends can cause failures),
// any error should just be logged as a warning so the history import still completes.
friendUUID, err := p.client.ResolveUserUUID(ctx, p.token, p.accountID)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Use an account token for Plex watchlist APIs

The token passed into PlexAdminProvider is the source admin/PMS token used for /accounts and /status/sessions/history/all, but ResolveUserUUID and the subsequent watchlist calls go to plex.tv/community account-level APIs; the existing Plex import path keeps a separate account token because PMS access tokens are rejected by watchlist APIs. For existing Plex admin sources configured with a server access token, friend watchlist sync will consistently degrade to a warning and import no watchlist items. Store/pass the plex.tv account token separately, or skip watchlist sync when only a PMS token is available.

Useful? React with 👍 / 👎.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 5

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
internal/historyimport/service.go (1)

654-670: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Normalize before validation and reject empty URL updates.

Whitespace passes the current creation check and is then persisted as ""; updates have the same invalid-state path.

Proposed fix
 func (s *Service) CreateSource(ctx context.Context, input CreateSourceInput) (*Source, error) {
+	input.BaseURL = normalizeBaseURL(input.BaseURL)
 	if input.Name == "" || input.BaseURL == "" {
 		return nil, fmt.Errorf("name and base_url are required")
 	}
@@
-	input.BaseURL = normalizeBaseURL(input.BaseURL)
 	return s.repo.CreateSource(ctx, input)
 }

 func (s *Service) UpdateSource(ctx context.Context, id int, input UpdateSourceInput) (*Source, error) {
 	if input.BaseURL != nil {
 		normalized := normalizeBaseURL(*input.BaseURL)
+		if normalized == "" {
+			return nil, fmt.Errorf("base_url is required")
+		}
 		input.BaseURL = &normalized
 	}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/historyimport/service.go` around lines 654 - 670, Update
CreateSource and UpdateSource to normalize BaseURL before validating it, then
reject values that are empty after normalization, including empty URL updates
when UpdateSource receives a non-nil BaseURL. Preserve the existing source type
validation and repository calls while preventing whitespace-only URLs from being
persisted.
🧹 Nitpick comments (1)
internal/historyimport/plex_admin_provider_test.go (1)

71-93: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Assert that GraphQL receives the resolved friend UUID.

The mock returns data regardless of the request body, so passing the numeric account ID—or any incorrect UUID—would still pass.

Proposed test assertion
 		case "/api":
 			w.Header().Set("Content-Type", "application/json")
+			var payload plexFriendWatchlistRequest
+			if err := json.NewDecoder(r.Body).Decode(&payload); err != nil {
+				t.Errorf("decode GraphQL request: %v", err)
+			}
+			if got := payload.Variables.User.ID; got != "resolved-friend-uuid" {
+				t.Errorf("GraphQL user ID = %q, want resolved-friend-uuid", got)
+			}
 			resp := map[string]any{
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/historyimport/plex_admin_provider_test.go` around lines 71 - 93, The
GraphQL mock in the test currently ignores the request body, so it does not
verify the resolved friend UUID. Update the /api handler to decode the incoming
GraphQL request and assert that the user query receives the expected friend
UUID, while preserving the existing response payload.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@internal/historyimport/plex_client.go`:
- Around line 364-365: Update ResolveUserUUID and the corresponding cache-key
construction around the later cache path so raw adminToken values are never
retained. Namespace each UUID cache key with a one-way digest of the token or
another non-secret account identifier, while preserving targetID-based isolation
and existing cache behavior.
- Around line 618-622: Update the pagination loop using
gqlResp.Data.UserV2.Watchlist.PageInfo.EndCursor and afterCursor to stop when
HasNextPage is true but the cursor is empty or unchanged from the previous
cursor. Preserve the existing termination for HasNextPage=false or an empty
Nodes result, and only assign afterCursor when the cursor advances.

In `@web/src/pages/AdminHistoryImport.tsx`:
- Around line 174-180: Update the OAuth lifecycle across the effect cleanup and
source-type/dialog transition handlers, including the flows around lines
203–219, 232–239, 291–295, 341–345, 381–393, 502–506, and 527–539: store the
popup reference and close it during cancellation or cleanup, invalidate polling
callbacks so late checkPlexPin responses are ignored, call cancelOAuth() before
leaving OAuth or changing the source type, and clear adminToken whenever the
source type changes.
- Around line 203-223: The Plex PIN polling flows around checkPlexPin must
enforce a timeout or retry budget instead of polling indefinitely. Track polling
attempts or elapsed time, and when the limit is reached—or a terminal PIN/API
failure occurs—clear the interval and plexOAuthIntervalRef, close the popup, set
pending state false, and populate the existing retryable error UI; apply the
same behavior to the corresponding polling blocks near the other referenced
flows.
- Around line 182-201: Update triggerOAuth to open a blank Plex authentication
popup synchronously before awaiting createPlexPin, then navigate that popup to
the URL produced by buildPlexAuthURL once the PIN arrives. Preserve the existing
blocked-popup error handling and ensure the popup is closed if PIN creation or
URL construction fails.

---

Outside diff comments:
In `@internal/historyimport/service.go`:
- Around line 654-670: Update CreateSource and UpdateSource to normalize BaseURL
before validating it, then reject values that are empty after normalization,
including empty URL updates when UpdateSource receives a non-nil BaseURL.
Preserve the existing source type validation and repository calls while
preventing whitespace-only URLs from being persisted.

---

Nitpick comments:
In `@internal/historyimport/plex_admin_provider_test.go`:
- Around line 71-93: The GraphQL mock in the test currently ignores the request
body, so it does not verify the resolved friend UUID. Update the /api handler to
decode the incoming GraphQL request and assert that the user query receives the
expected friend UUID, while preserving the existing response payload.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: b754e5bd-4069-4a19-a79c-03ba9a5d27e4

📥 Commits

Reviewing files that changed from the base of the PR and between 28c6ddc and 86a2086.

📒 Files selected for processing (7)
  • internal/historyimport/matcher.go
  • internal/historyimport/matcher_test.go
  • internal/historyimport/plex_admin_provider.go
  • internal/historyimport/plex_admin_provider_test.go
  • internal/historyimport/plex_client.go
  • internal/historyimport/service.go
  • web/src/pages/AdminHistoryImport.tsx

Comment on lines +364 to +365
func (c *PlexClient) ResolveUserUUID(ctx context.Context, adminToken, targetID string) (string, error) {
cacheKey := adminToken + ":" + targetID

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

Do not retain raw Plex tokens in UUID cache keys.

Expired entries remain until the 100-entry flush, unnecessarily extending secret retention. Namespace the cache with a one-way token digest or a non-secret account identifier.

Proposed fix
+import "crypto/sha256"

+func uuidCacheKey(adminToken, targetID string) string {
+	tokenHash := sha256.Sum256([]byte(adminToken))
+	return fmt.Sprintf("%x:%s", tokenHash, targetID)
+}
+
 func (c *PlexClient) ResolveUserUUID(ctx context.Context, adminToken, targetID string) (string, error) {
-	cacheKey := adminToken + ":" + targetID
+	cacheKey := uuidCacheKey(adminToken, targetID)
-	c.uuidCache[adminToken+":"+targetID] = cachedUUID{
+	c.uuidCache[uuidCacheKey(adminToken, targetID)] = cachedUUID{

Also applies to: 461-477

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/historyimport/plex_client.go` around lines 364 - 365, Update
ResolveUserUUID and the corresponding cache-key construction around the later
cache path so raw adminToken values are never retained. Namespace each UUID
cache key with a one-way digest of the token or another non-secret account
identifier, while preserving targetID-based isolation and existing cache
behavior.

Comment on lines +618 to +622
if !gqlResp.Data.UserV2.Watchlist.PageInfo.HasNextPage || len(gqlResp.Data.UserV2.Watchlist.Nodes) == 0 {
break
}
cursor := gqlResp.Data.UserV2.Watchlist.PageInfo.EndCursor
afterCursor = &cursor

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Reject empty or non-advancing pagination cursors.

If Plex returns hasNextPage=true with an empty or repeated cursor, this loop repeatedly downloads the same page and grows allItems indefinitely.

Proposed fix
 	cursor := gqlResp.Data.UserV2.Watchlist.PageInfo.EndCursor
+	if cursor == "" || (afterCursor != nil && cursor == *afterCursor) {
+		return nil, nil, fmt.Errorf("GraphQL watchlist pagination returned a non-advancing cursor")
+	}
 	afterCursor = &cursor
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if !gqlResp.Data.UserV2.Watchlist.PageInfo.HasNextPage || len(gqlResp.Data.UserV2.Watchlist.Nodes) == 0 {
break
}
cursor := gqlResp.Data.UserV2.Watchlist.PageInfo.EndCursor
afterCursor = &cursor
if !gqlResp.Data.UserV2.Watchlist.PageInfo.HasNextPage || len(gqlResp.Data.UserV2.Watchlist.Nodes) == 0 {
break
}
cursor := gqlResp.Data.UserV2.Watchlist.PageInfo.EndCursor
if cursor == "" || (afterCursor != nil && cursor == *afterCursor) {
return nil, nil, fmt.Errorf("GraphQL watchlist pagination returned a non-advancing cursor")
}
afterCursor = &cursor
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/historyimport/plex_client.go` around lines 618 - 622, Update the
pagination loop using gqlResp.Data.UserV2.Watchlist.PageInfo.EndCursor and
afterCursor to stop when HasNextPage is true but the cursor is empty or
unchanged from the previous cursor. Preserve the existing termination for
HasNextPage=false or an empty Nodes result, and only assign afterCursor when the
cursor advances.

Comment thread web/src/pages/AdminHistoryImport.tsx Resolved
Comment thread web/src/pages/AdminHistoryImport.tsx Resolved
Comment thread web/src/pages/AdminHistoryImport.tsx Resolved
@drondeseries

This comment was marked as low quality.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
internal/historyimport/service.go (1)

655-664: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Empty-string validation runs before normalization, allowing whitespace-only base URLs to bypass the required check.

input.BaseURL == "" is checked at line 655 before normalizeBaseURL trims whitespace at line 663. A whitespace-only input like " " passes the required-field check, then normalizes to "", and is stored as an empty base URL in the repository. Move normalization before validation, or validate the normalized result.

🔧 Proposed fix
 func (s *Service) CreateSource(ctx context.Context, input CreateSourceInput) (*Source, error) {
+	input.BaseURL = normalizeBaseURL(input.BaseURL)
 	if input.Name == "" || input.BaseURL == "" {
 		return nil, fmt.Errorf("name and base_url are required")
 	}
 	switch input.SourceType {
 	case SourceTypeEmby, SourceTypeJellyfin, SourceTypePlex:
 	default:
 		return nil, fmt.Errorf("source_type must be emby, jellyfin, or plex")
 	}
-	input.BaseURL = normalizeBaseURL(input.BaseURL)
 	return s.repo.CreateSource(ctx, input)
 }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/historyimport/service.go` around lines 655 - 664, Update the source
creation flow around normalizeBaseURL to normalize input.BaseURL before
required-field validation, then reject the resulting empty value along with an
empty input.Name. Preserve the existing source-type validation and repository
creation behavior for valid normalized URLs.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@internal/historyimport/service.go`:
- Around line 679-688: Update normalizeBaseURL to detect http:// and https://
schemes case-insensitively, while returning the original trimmed URL unchanged
when either scheme is present. Continue prepending http:// only for URLs without
a recognized scheme.

---

Outside diff comments:
In `@internal/historyimport/service.go`:
- Around line 655-664: Update the source creation flow around normalizeBaseURL
to normalize input.BaseURL before required-field validation, then reject the
resulting empty value along with an empty input.Name. Preserve the existing
source-type validation and repository creation behavior for valid normalized
URLs.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: a6df04bb-26bf-4bb3-ad67-893a90895bb5

📥 Commits

Reviewing files that changed from the base of the PR and between 86a2086 and 5eb83dd.

📒 Files selected for processing (7)
  • internal/historyimport/matcher.go
  • internal/historyimport/matcher_test.go
  • internal/historyimport/plex_admin_provider.go
  • internal/historyimport/plex_admin_provider_test.go
  • internal/historyimport/plex_client.go
  • internal/historyimport/service.go
  • web/src/pages/AdminHistoryImport.tsx
🚧 Files skipped from review as they are similar to previous changes (6)
  • internal/historyimport/matcher_test.go
  • internal/historyimport/plex_admin_provider.go
  • internal/historyimport/matcher.go
  • internal/historyimport/plex_admin_provider_test.go
  • web/src/pages/AdminHistoryImport.tsx
  • internal/historyimport/plex_client.go

Comment thread internal/historyimport/service.go Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
internal/historyimport/matcher.go (1)

173-184: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Prefer strings.TrimSuffix over strings.LastIndex for clarity.

Since the regular expression is anchored to the end of the string ($), matches[0] is guaranteed to be a suffix. Using strings.TrimSuffix is more idiomatic and avoids an unnecessary backward string search.

♻️ Proposed refactor
-		cleanedTitle = strings.TrimSpace(title[:strings.LastIndex(title, matches[0])])
+		cleanedTitle = strings.TrimSpace(strings.TrimSuffix(title, matches[0]))
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/historyimport/matcher.go` around lines 173 - 184, In the
title-cleaning logic around the yearRegex match, replace the LastIndex-based
slice with strings.TrimSuffix using matches[0]. Preserve the existing whitespace
trimming and year parsing behavior.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@internal/historyimport/matcher.go`:
- Around line 173-184: In the title-cleaning logic around the yearRegex match,
replace the LastIndex-based slice with strings.TrimSuffix using matches[0].
Preserve the existing whitespace trimming and year parsing behavior.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: d4289c68-357a-4b59-bbe6-4e95434d5750

📥 Commits

Reviewing files that changed from the base of the PR and between 5eb83dd and e97f94e.

📒 Files selected for processing (7)
  • internal/historyimport/matcher.go
  • internal/historyimport/matcher_test.go
  • internal/historyimport/plex_admin_provider.go
  • internal/historyimport/plex_admin_provider_test.go
  • internal/historyimport/plex_client.go
  • internal/historyimport/service.go
  • web/src/pages/AdminHistoryImport.tsx
🚧 Files skipped from review as they are similar to previous changes (6)
  • internal/historyimport/service.go
  • internal/historyimport/matcher_test.go
  • internal/historyimport/plex_admin_provider_test.go
  • internal/historyimport/plex_admin_provider.go
  • internal/historyimport/plex_client.go
  • web/src/pages/AdminHistoryImport.tsx

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 6

🧹 Nitpick comments (3)
internal/pluginhost/host.go (1)

227-230: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Remove redundant trailing slash trims.

Both publicBaseURL and internalBaseURL are already securely stripped of trailing slashes upon assignment in NewHost and SetHostURLs. Trimming them again during internal read operations is redundant.

  • internal/pluginhost/host.go#L227-L230: Remove the strings.TrimRight calls and use h.internalBaseURL and h.publicBaseURL directly.
  • internal/pluginhost/runtime_host_server.go#L111-L114: Remove the strings.TrimRight calls and use s.internalBaseURL and s.publicBaseURL directly.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/pluginhost/host.go` around lines 227 - 230, Remove the redundant
strings.TrimRight calls in internal/pluginhost/host.go lines 227-230, using
h.internalBaseURL and h.publicBaseURL directly in the base selection. Apply the
same change in internal/pluginhost/runtime_host_server.go lines 111-114, using
s.internalBaseURL and s.publicBaseURL directly; no other behavior should change.
web/src/components/FolderBrowser.tsx (1)

290-308: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Update selection labels to reflect files and directories.

Since FolderBrowser now supports selecting files (like ZIP archives) in addition to directories, the terminology "Folder" in the selection summary and submit buttons can be misleading when a file is chosen.

Consider updating the labels to a more generic term like "Item". Additionally, since the new callers (AdminPlugins and SchemaForm) only utilize the first selected path, you might optionally consider adding a multiple?: boolean prop in the future to restrict the UI to single-selection where appropriate.

💡 Proposed update to UI strings
-          <div className="text-muted-foreground text-xs">
-            {selectedPaths.size > 0
-              ? `${selectedPaths.size} folder${selectedPaths.size !== 1 ? "s" : ""} selected`
-              : "Select folders or use current"}
-          </div>
+          <div className="text-muted-foreground text-xs">
+            {selectedPaths.size > 0
+              ? `${selectedPaths.size} item${selectedPaths.size !== 1 ? "s" : ""} selected`
+              : "Select items or use current directory"}
+          </div>
           <div className="flex gap-2">
             <Button type="button" variant="outline" onClick={() => onOpenChange(false)}>
               Cancel
             </Button>
             {addableSelected > 0 ? (
               <Button type="button" onClick={handleAddSelected}>
-                Add {addableSelected} Folder{addableSelected !== 1 ? "s" : ""}
+                Add {addableSelected} Item{addableSelected !== 1 ? "s" : ""}
               </Button>
             ) : (
-              <Button type="button" onClick={handleSelectCurrent} disabled={alreadyAdded}>
-                Use Current Folder
-              </Button>
+              <Button type="button" onClick={handleSelectCurrent} disabled={alreadyAdded}>
+                Use Current Directory
+              </Button>
             )}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@web/src/components/FolderBrowser.tsx` around lines 290 - 308, Update the
selection summary and add-selected button labels in FolderBrowser to use generic
“item” terminology instead of “folder,” including singular/plural handling;
leave the current-folder action unchanged.
internal/scanner/scanner.go (1)

2942-2966: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Consider using strings.EqualFold for consistency.

Using strings.EqualFold avoids a temporary string allocation for the lowercase extension and aligns with the matching logic in probe_repair.go and plan_v3.go.

♻️ Proposed refactor
-	if strings.ToLower(filepath.Ext(filePath)) == ".strm" {
+	if strings.EqualFold(filepath.Ext(filePath), ".strm") {
 		lowerPath := strings.ToLower(filePath)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/scanner/scanner.go` around lines 2942 - 2966, The .strm extension
check in the scanner flow currently lowercases the extension unnecessarily.
Replace the strings.ToLower(filepath.Ext(filePath)) comparison with
strings.EqualFold while preserving the existing case-insensitive matching and
subsequent STRM probe behavior.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@cmd/silo/main.go`:
- Around line 987-993: Update the SILO_INTERNAL_URL handling before constructing
pluginhost.Config to parse and canonicalize the configured URL, accept only HTTP
or HTTPS schemes case-insensitively, and reject invalid or non-HTTP values
during startup. Preserve the existing localhost default for empty input and pass
the normalized URL through InternalBaseURL.
- Around line 987-990: Update the SILO_INTERNAL_URL initialization near
InternalBaseURL so it no longer falls back to the loopback URL; require an
explicitly configured reachable URL or derive it from the actual server
configuration, preserving the value used for host URLs and plugin proxy
callbacks.

In `@internal/api/handlers/playback_v3.go`:
- Around line 1781-1786: The negative subtitle index must remain intact to
preserve the explicit subtitles-off selection. In
internal/api/handlers/playback_v3.go lines 1781-1786, remove the assignment that
sets request.SubtitleTrackIndex to nil and continue clearing only
request.SubtitleTrackID; in internal/api/handlers/playback_v3_test.go lines
1295-1297, update the assertion to verify SubtitleTrackIndex remains non-nil and
negative.

In `@internal/api/handlers/plugins.go`:
- Around line 675-678: Update the path validation before installUploadedPlugin
to reject directories as well as missing paths: inspect the os.Stat result and
require its FileInfo to represent a regular file, returning the existing 400
bad_request response when it does not.

In `@internal/playback/directplay.go`:
- Around line 55-69: Replace the duplicated .strm handling in the
direct-playback flow with the shared resolveTranscodeInputPath helper. Reuse its
validated URL, error handling, and HTTP/HTTPS enforcement before calling
http.Redirect, while preserving the existing response behavior for resolver
failures and empty or invalid shortcuts.

In `@internal/playback/transcode.go`:
- Around line 282-354: Validate the resolver’s Location header in
resolveStreamCandidate before returning it to the caller, matching the existing
http(s) validation used by resolveTranscodeInputPath. Reject file:// and other
non-http(s) schemes with an error, while preserving valid HTTP and HTTPS
locations so they can safely reach s.opts.InputPath and ffmpeg.

---

Nitpick comments:
In `@internal/pluginhost/host.go`:
- Around line 227-230: Remove the redundant strings.TrimRight calls in
internal/pluginhost/host.go lines 227-230, using h.internalBaseURL and
h.publicBaseURL directly in the base selection. Apply the same change in
internal/pluginhost/runtime_host_server.go lines 111-114, using
s.internalBaseURL and s.publicBaseURL directly; no other behavior should change.

In `@internal/scanner/scanner.go`:
- Around line 2942-2966: The .strm extension check in the scanner flow currently
lowercases the extension unnecessarily. Replace the
strings.ToLower(filepath.Ext(filePath)) comparison with strings.EqualFold while
preserving the existing case-insensitive matching and subsequent STRM probe
behavior.

In `@web/src/components/FolderBrowser.tsx`:
- Around line 290-308: Update the selection summary and add-selected button
labels in FolderBrowser to use generic “item” terminology instead of “folder,”
including singular/plural handling; leave the current-folder action unchanged.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 93258c80-256c-4501-9adb-ad1e0b246dd8

📥 Commits

Reviewing files that changed from the base of the PR and between e97f94e and d663585.

📒 Files selected for processing (27)
  • .github/workflows/docker.yml
  • cmd/silo/main.go
  • internal/api/handlers/filesystem.go
  • internal/api/handlers/playback_v3.go
  • internal/api/handlers/playback_v3_test.go
  • internal/api/handlers/plugins.go
  • internal/api/router.go
  • internal/playback/directplay.go
  • internal/playback/plan_v3.go
  • internal/playback/protocol_v3_test.go
  • internal/playback/stream_candidate_test.go
  • internal/playback/strm_test.go
  • internal/playback/transcode.go
  • internal/playback/transcode_manager.go
  • internal/playback/transcode_manifest_test.go
  • internal/pluginhost/host.go
  • internal/pluginhost/runtime_host_server.go
  • internal/pluginhost/runtime_host_server_test.go
  • internal/scanner/probe_repair.go
  • internal/scanner/probe_repair_strm_test.go
  • internal/scanner/scanner.go
  • web/src/api/types.ts
  • web/src/components/FolderBrowser.tsx
  • web/src/components/admin/plugins/SchemaForm.tsx
  • web/src/hooks/queries/admin/plugins.ts
  • web/src/pages/AdminPlugins.tsx
  • web/src/pages/AdminRequests.tsx

Comment thread cmd/silo/main.go
Comment on lines +987 to +990
siloInternalURL := strings.TrimSpace(os.Getenv("SILO_INTERNAL_URL"))
if siloInternalURL == "" {
siloInternalURL = "http://127.0.0.1:8080"
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '\n## Files containing SILO_INTERNAL_URL / InternalBaseURL\n'
rg -n --hidden --glob '!**/.git/**' 'SILO_INTERNAL_URL|InternalBaseURL|internal base url|InternalBaseURL' .

printf '\n## cmd/silo/main.go around the target lines\n'
sed -n '940,1025p' cmd/silo/main.go

printf '\n## Candidate definitions/usages of pluginhost.Config\n'
rg -n --hidden --glob '!**/.git/**' 'type Config struct|InternalBaseURL|pluginhost\.Config' .

printf '\n## Relevant docs mentioning SILO_INTERNAL_URL\n'
rg -n --hidden --glob '!**/.git/**' 'SILO_INTERNAL_URL|InternalBaseURL|plugin consumer|plugin consumers|callback|proxy URL' .

Repository: Silo-Server/silo-server

Length of output: 50381


🏁 Script executed:

#!/bin/bash
set -euo pipefail
rg -n --hidden --glob '!**/.git/**' 'SILO_INTERNAL_URL|InternalBaseURL|pluginhost\.Config|InternalBaseURL' .

Repository: Silo-Server/silo-server

Length of output: 1241


🌐 Web query:

"SILO_INTERNAL_URL" pluginhost InternalBaseURL

💡 Result:

The terms SILO_INTERNAL_URL, pluginhost, and InternalBaseURL originate from distinct technical contexts and do not refer to a single, unified configuration setting. 1. SILO_INTERNAL_URL is not a standard configuration variable in the Silo tool (silo.rs) [1][2][3]. In containerized or multi-service environments, similar patterns (e.g., API_INTERNAL_URL) are often used to route server-side requests to an internal container address that differs from the browser-facing or public-facing host URL [4]. 2. pluginhost and InternalBaseURL are specific concepts used in the Backstage framework's discovery architecture [5][6][7]. In Backstage, the HostDiscoveryEndpoint configuration allows developers to define target base URLs for plugins [5][8]. This configuration supports an optional object structure that distinguishes between internal and external access: target: { internal?: string; external?: string; } The internal URL is used for backend-to-backend communication, while the external URL is typically used for frontend-to-backend requests [5][8][9]. The pluginhost context is also associated with the silo-plugin-sdk, which facilitates communication between plugins and a host (RuntimeHost) in a different system called Silo-Server, though this system uses different mechanisms for plugin discovery and host info [10][11][12].

Citations:


🏁 Script executed:

#!/bin/bash
set -euo pipefail

sed -n '1,220p' internal/pluginhost/host.go

Repository: Silo-Server/silo-server

Length of output: 6796


🏁 Script executed:

#!/bin/bash
set -euo pipefail

rg -n 'internalBaseURL|publicBaseURL|pluginProxyURL|PublicBaseURL|InternalBaseURL' internal/pluginhost/host.go
sed -n '220,420p' internal/pluginhost/host.go

Repository: Silo-Server/silo-server

Length of output: 5425


cmd/silo/main.go:987-990 — Don’t default SILO_INTERNAL_URL to loopback. InternalBaseURL is used for host URLs and plugin proxy callbacks, so http://127.0.0.1:8080 breaks any deployment where plugins run outside the Silo process/network namespace. Require an explicit reachable URL or derive it from the actual server config.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@cmd/silo/main.go` around lines 987 - 990, Update the SILO_INTERNAL_URL
initialization near InternalBaseURL so it no longer falls back to the loopback
URL; require an explicitly configured reachable URL or derive it from the actual
server configuration, preserving the value used for host URLs and plugin proxy
callbacks.

Comment thread cmd/silo/main.go
Comment on lines +987 to +993
siloInternalURL := strings.TrimSpace(os.Getenv("SILO_INTERNAL_URL"))
if siloInternalURL == "" {
siloInternalURL = "http://127.0.0.1:8080"
}
pluginHost = pluginhost.NewHost(pluginhost.Config{
PublicBaseURL: os.Getenv("SILO_PUBLIC_URL"),
InternalBaseURL: siloInternalURL,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Inspect the cited area and the pluginhost URL handling.
sed -n '960,1025p' cmd/silo/main.go

printf '\n--- pluginhost references ---\n'
rg -n "PluginProxyBaseUrl|InternalBaseURL|PublicBaseURL|NewHost\\(" -S .

Repository: Silo-Server/silo-server

Length of output: 3895


🏁 Script executed:

#!/bin/bash
set -euo pipefail

sed -n '1,220p' internal/pluginhost/host.go
printf '\n--- runtime_host_server ---\n'
sed -n '1,220p' internal/pluginhost/runtime_host_server.go
printf '\n--- tests ---\n'
sed -n '200,280p' internal/pluginhost/runtime_host_server_test.go

Repository: Silo-Server/silo-server

Length of output: 17580


Normalize and validate the configured URL scheme.

SILO_INTERNAL_URL is only whitespace-trimmed here, then passed through to PluginProxyBaseUrl without parsing. Add HTTP/HTTPS validation and canonicalization (or fail startup) so values like HTTP://... or non-HTTP schemes don’t leak downstream.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@cmd/silo/main.go` around lines 987 - 993, Update the SILO_INTERNAL_URL
handling before constructing pluginhost.Config to parse and canonicalize the
configured URL, accept only HTTP or HTTPS schemes case-insensitively, and reject
invalid or non-HTTP values during startup. Preserve the existing localhost
default for empty input and pass the normalized URL through InternalBaseURL.

Comment on lines +1781 to +1786
// Protocol v3 uses a negative index as the explicit "subtitles off"
// selection. It is not file-bound, so preserve that intent while
// clearing any stale identity carried from the source version.
request.SubtitleTrackIndex = nil
request.SubtitleTrackID = ""
return nil

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🔴 Critical | ⚡ Quick win

Preserve the negative index to explicitly keep subtitles off.

The implementation incorrectly clears SubtitleTrackIndex by setting it to nil when a negative index (subtitles off) is requested. This contradicts the declared protocol intent and erases the explicit "off" selection, causing the playback planner to fall back to auto-selecting a default or forced subtitle track.

  • internal/api/handlers/playback_v3.go#L1781-L1786: Remove request.SubtitleTrackIndex = nil to retain the negative index value, clearing only the stale file-bound SubtitleTrackID.
  • internal/api/handlers/playback_v3_test.go#L1295-L1297: Update the test assertion to verify that request.SubtitleTrackIndex remains negative (e.g., *request.SubtitleTrackIndex < 0) instead of becoming nil.
📍 Affects 2 files
  • internal/api/handlers/playback_v3.go#L1781-L1786 (this comment)
  • internal/api/handlers/playback_v3_test.go#L1295-L1297
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/api/handlers/playback_v3.go` around lines 1781 - 1786, The negative
subtitle index must remain intact to preserve the explicit subtitles-off
selection. In internal/api/handlers/playback_v3.go lines 1781-1786, remove the
assignment that sets request.SubtitleTrackIndex to nil and continue clearing
only request.SubtitleTrackID; in internal/api/handlers/playback_v3_test.go lines
1295-1297, update the assertion to verify SubtitleTrackIndex remains non-nil and
negative.

Comment on lines +675 to +678
if _, err := os.Stat(req.Path); err != nil {
writeError(w, http.StatusBadRequest, "bad_request", fmt.Sprintf("file not found on server: %s", err.Error()))
return
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Validate that the path is a file, not a directory.

If a directory path is provided (e.g., erroneously selected from the folder browser), os.Stat succeeds, but the subsequent logic in installUploadedPlugin will attempt to call os.ReadFile on the directory, resulting in an unhandled error and a 500 Internal Server Error response. Return a 400 Bad Request instead.

🐛 Proposed fix
-	if _, err := os.Stat(req.Path); err != nil {
+	info, err := os.Stat(req.Path)
+	if err != nil {
 		writeError(w, http.StatusBadRequest, "bad_request", fmt.Sprintf("file not found on server: %s", err.Error()))
 		return
 	}
+
+	if info.IsDir() {
+		writeError(w, http.StatusBadRequest, "bad_request", "path must be a file, not a directory")
+		return
+	}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if _, err := os.Stat(req.Path); err != nil {
writeError(w, http.StatusBadRequest, "bad_request", fmt.Sprintf("file not found on server: %s", err.Error()))
return
}
info, err := os.Stat(req.Path)
if err != nil {
writeError(w, http.StatusBadRequest, "bad_request", fmt.Sprintf("file not found on server: %s", err.Error()))
return
}
if info.IsDir() {
writeError(w, http.StatusBadRequest, "bad_request", "path must be a file, not a directory")
return
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/api/handlers/plugins.go` around lines 675 - 678, Update the path
validation before installUploadedPlugin to reject directories as well as missing
paths: inspect the os.Stat result and require its FileInfo to represent a
regular file, returning the existing 400 bad_request response when it does not.

Comment on lines +55 to +69
if strings.ToLower(filepath.Ext(filePath)) == ".strm" {
content, err := os.ReadFile(filePath)
if err != nil {
http.Error(w, "failed to read stream shortcut", http.StatusInternalServerError)
return err
}
streamURL := strings.TrimSpace(string(content))
if streamURL == "" {
http.Error(w, "stream shortcut is empty", http.StatusBadRequest)
return nil
}
http.Redirect(w, r, streamURL, http.StatusTemporaryRedirect)
return nil
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

Reuse resolveTranscodeInputPath instead of a weaker, duplicated .strm parser.

This block re-implements .strm shortcut resolution but drops the safeguards already present in resolveTranscodeInputPath (internal/playback/transcode.go, same package): no file-size cap, no rejection of multi-line/multi-URL content, and — most importantly — no check that the extracted URL uses http:///https://. A .strm file containing something like file:///etc/passwd or a javascript:/other non-http(s) value is redirected to verbatim via http.Redirect, whereas the sibling transcode path explicitly rejects exactly this case (see the "local": "file:///etc/passwd" test in strm_test.go). Since directplay.go is in the same playback package, this can call the existing helper directly instead of duplicating (and weakening) the logic.

🔧 Proposed fix to reuse the shared, validated resolver
 	if strings.ToLower(filepath.Ext(filePath)) == ".strm" {
-		content, err := os.ReadFile(filePath)
-		if err != nil {
-			http.Error(w, "failed to read stream shortcut", http.StatusInternalServerError)
-			return err
-		}
-		streamURL := strings.TrimSpace(string(content))
-		if streamURL == "" {
-			http.Error(w, "stream shortcut is empty", http.StatusBadRequest)
-			return nil
-		}
+		streamURL, err := resolveTranscodeInputPath(filePath)
+		if err != nil {
+			http.Error(w, "invalid stream shortcut", http.StatusBadRequest)
+			return err
+		}
 		http.Redirect(w, r, streamURL, http.StatusTemporaryRedirect)
 		return nil
 	}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if strings.ToLower(filepath.Ext(filePath)) == ".strm" {
content, err := os.ReadFile(filePath)
if err != nil {
http.Error(w, "failed to read stream shortcut", http.StatusInternalServerError)
return err
}
streamURL := strings.TrimSpace(string(content))
if streamURL == "" {
http.Error(w, "stream shortcut is empty", http.StatusBadRequest)
return nil
}
http.Redirect(w, r, streamURL, http.StatusTemporaryRedirect)
return nil
}
if strings.ToLower(filepath.Ext(filePath)) == ".strm" {
streamURL, err := resolveTranscodeInputPath(filePath)
if err != nil {
http.Error(w, "invalid stream shortcut", http.StatusBadRequest)
return err
}
http.Redirect(w, r, streamURL, http.StatusTemporaryRedirect)
return nil
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/playback/directplay.go` around lines 55 - 69, Replace the duplicated
.strm handling in the direct-playback flow with the shared
resolveTranscodeInputPath helper. Reuse its validated URL, error handling, and
HTTP/HTTPS enforcement before calling http.Redirect, while preserving the
existing response behavior for resolver failures and empty or invalid shortcuts.

Comment on lines +282 to +354
location, count, unavailable, err := resolveStreamCandidate(ctx, base, candidate, refresh)
if err != nil {
return false, err
}
if unavailable {
s.mu.Lock()
alreadyRefreshed := s.streamCacheRefreshed
s.mu.Unlock()
if alreadyRefreshed || refresh {
return false, nil
}
candidate, refresh = 0, true
location, count, unavailable, err = resolveStreamCandidate(ctx, base, candidate, refresh)
if err != nil || unavailable {
return false, err
}
}

s.mu.Lock()
s.streamCandidate = candidate
if count > 0 {
s.streamCandidateCount = count
}
if refresh {
s.streamCacheRefreshed = true
}
s.opts.InputPath = location
seekSeconds, startSegment := s.opts.SeekSeconds, s.opts.StartSegmentNumber
s.mu.Unlock()

if err := s.Restart(ctx, seekSeconds, startSegment); err != nil {
return false, err
}
s.logFFmpegEvent(ctx, "ffmpeg stream candidate retry", "")
return true, nil
}

func resolveStreamCandidate(ctx context.Context, base string, candidate int, refresh bool) (location string, count int, unavailable bool, err error) {
u, err := url.Parse(base)
if err != nil {
return "", 0, false, err
}
query := u.Query()
query.Set("candidate", strconv.Itoa(candidate))
if refresh {
query.Set("refresh", "true")
} else {
query.Del("refresh")
}
u.RawQuery = query.Encode()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, u.String(), nil)
if err != nil {
return "", 0, false, err
}
client := &http.Client{Timeout: 30 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}
resp, err := client.Do(req)
if err != nil {
return "", 0, false, err
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusNotFound {
return "", 0, true, nil
}
if resp.StatusCode != http.StatusFound {
return "", 0, false, fmt.Errorf("stream resolver returned HTTP %d", resp.StatusCode)
}
location = strings.TrimSpace(resp.Header.Get("Location"))
if location == "" {
return "", 0, false, fmt.Errorf("stream resolver returned an empty location")
}
count, _ = strconv.Atoi(resp.Header.Get("X-Silo-Stream-Candidates"))
return location, count, false, nil
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo '--- transcode.go relevant ranges ---'
sed -n '240,420p' internal/playback/transcode.go

echo
echo '--- search for InputPath usage ---'
rg -n 'InputPath|resolveTranscodeInputPath|ffmpeg|protocol_whitelist|-i ' internal -S

Repository: Silo-Server/silo-server

Length of output: 50379


🏁 Script executed:

#!/bin/bash
set -euo pipefail

python3 - <<'PY'
from pathlib import Path
p = Path('internal/playback/transcode.go')
lines = p.read_text().splitlines()
for start,end in [(240,420)]:
    print(f'--- {p}:{start}-{end} ---')
    for i in range(start-1, min(end, len(lines))):
        print(f'{i+1:4d}: {lines[i]}')
PY

echo
echo '--- rg: InputPath / ffmpeg / resolver references ---'
rg -n 'InputPath|resolveTranscodeInputPath|protocol_whitelist|ffmpeg|StreamCandidate|stream resolver' internal -S

Repository: Silo-Server/silo-server

Length of output: 50379


🏁 Script executed:

#!/bin/bash
set -euo pipefail

sed -n '282,387p' internal/playback/transcode.go | cat -n

echo '---'
rg -n 'InputPath|NewCommand|exec.Command|ffmpeg' internal -S

Repository: Silo-Server/silo-server

Length of output: 50379


🌐 Web query:

FFmpeg input URL protocols file:// http:// https:// protocol_whitelist top-level -i documentation

💡 Result:

In FFmpeg, the protocol_whitelist is a security and configuration mechanism that restricts which input or output protocols are permitted during a session [1][2]. Key aspects of protocol_whitelist: Functionality: It accepts a comma-separated list of allowed protocol names (e.g., "file,http,https") [1][3][4]. When defined, FFmpeg will only allow the use of protocols explicitly included in this list [5][4]. Protocols prefixed with a "-" (e.g., "-file") are explicitly disabled [1]. If the value "ALL" is provided, it matches all available protocols [1]. Context: By default, all protocols compiled into the FFmpeg build are allowed [1]. However, the protocol_whitelist is particularly important for restricting "nested" protocols (protocols used by another protocol, such as an HTTP stream that internally uses TLS/HTTPS) [1]. Usage: It is a generic, global protocol option provided by the libavformat library [1]. Because it is an AVOption, it can be set via command-line arguments when using tools like ffmpeg or ffplay, or programmatically through the AVFormatContext or URLContext structures [2][3]. Supported Protocols: FFmpeg supports a wide variety of protocols, including file:// (local file access), http:// (unencrypted web streams), and https:// (encrypted web streams) [6][7]. You can verify which protocols are available in your specific FFmpeg build by running the command ffmpeg -protocols [6]. Technical Implementation: Internally, the libavformat library uses functions such as ffurl_open_whitelist and ffurl_get_protocols to validate requested protocols against the provided whitelist (and optional protocol_blacklist) [5][4]. If a protocol is not in the whitelist, the operation will be rejected with an error (e.g., "Protocol '...' not on whitelist '...'!") [5].

Citations:


Validate the resolver Location before passing it to ffmpeg (internal/playback/transcode.go:319-354). resolveStreamCandidate feeds the header straight into s.opts.InputPath, so a resolver-controlled file:// or internal URL can reach the next ffmpeg -i input. Mirror the http(s) check used by resolveTranscodeInputPath.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/playback/transcode.go` around lines 282 - 354, Validate the
resolver’s Location header in resolveStreamCandidate before returning it to the
caller, matching the existing http(s) validation used by
resolveTranscodeInputPath. Reject file:// and other non-http(s) schemes with an
error, while preserving valid HTTP and HTTPS locations so they can safely reach
s.opts.InputPath and ffmpeg.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

v1.0 Silo v1 scope - auto-adds to the Silo v1 project

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

1 participant