Skip to content

Usenet streaming with a WebDAV server and a SABnzbd-compatible API

C#

Moved user-agent setting from env-variable to ui.

nzbdav-devfd55d796b057
diff --git a/backend/Api/SabControllers/AddUrl/AddUrlRequest.cs b/backend/Api/SabControllers/AddUrl/AddUrlRequest.cs
index 500bb206..a274e697 100644
--- a/backend/Api/SabControllers/AddUrl/AddUrlRequest.cs
+++ b/backend/Api/SabControllers/AddUrl/AddUrlRequest.cs
@@ -8,15 +8,15 @@ namespace NzbWebDAV.Api.SabControllers.AddUrl;
public class AddUrlRequest() : AddFileRequest
{
- private static readonly string DefaultUserAgent = $"nzbdav/{ConfigManager.AppVersion}";
- private static readonly HttpClient HttpClient = GetHttpClient();
+ private static readonly HttpClient HttpClientInstance = InitializeHttpClient();
private const int MaxAutomaticRedirections = 10;
public static async Task<AddUrlRequest> New(HttpContext context, ConfigManager configManager)
{
var nzbUrl = context.GetQueryParam("name");
var nzbName = context.GetQueryParam("nzbname");
- var nzbFile = await GetNzbFile(nzbUrl, nzbName).ConfigureAwait(false);
+ var userAgent = configManager.GetUserAgent();
+ var nzbFile = await GetNzbFile(nzbUrl, nzbName, userAgent).ConfigureAwait(false);
return new AddUrlRequest()
{
FileName = nzbFile.FileName,
@@ -29,7 +29,7 @@ public class AddUrlRequest() : AddFileRequest
};
}
- private static async Task<NzbFileResponse> GetNzbFile(string? url, string? nzbName)
+ private static async Task<NzbFileResponse> GetNzbFile(string? url, string? nzbName, string userAgent)
{
try
{
@@ -38,7 +38,7 @@ public class AddUrlRequest() : AddFileRequest
throw new Exception($"The url is invalid.");
// fetch url
- var response = await GetAsync(url).ConfigureAwait(false);
+ var response = await GetAsync(url, userAgent).ConfigureAwait(false);
if (!response.IsSuccessStatusCode)
throw new Exception($"Received status code {response.StatusCode}.");
@@ -75,9 +75,12 @@ public class AddUrlRequest() : AddFileRequest
: $"{nzbName}.nzb";
}
- private static async Task<HttpResponseMessage> GetAsync(string url)
+ private static async Task<HttpResponseMessage> GetAsync(string url, string userAgent)
{
- var response = await HttpClient.GetAsync(url);
+ var httpClient = HttpClientInstance;
+ httpClient.DefaultRequestHeaders.Remove("User-Agent");
+ httpClient.DefaultRequestHeaders.Add("User-Agent", userAgent);
+ var response = await httpClient.GetAsync(url);
var remainingRedirects = MaxAutomaticRedirections;
while
(
@@ -89,24 +92,21 @@ public class AddUrlRequest() : AddFileRequest
{
var redirect = response.Headers.Location;
var redirectUri = redirect.IsAbsoluteUri ? redirect : new Uri(new Uri(url), redirect);
- response = await HttpClient.GetAsync(redirectUri);
+ response = await httpClient.GetAsync(redirectUri);
remainingRedirects--;
}
return response;
}
- private static HttpClient GetHttpClient()
+ private static HttpClient InitializeHttpClient()
{
var handler = new HttpClientHandler
{
AllowAutoRedirect = true,
MaxAutomaticRedirections = MaxAutomaticRedirections,
};
- var httpClient = new HttpClient(handler);
- var userAgent = EnvironmentUtil.GetEnvironmentVariable("NZB_GRAB_USER_AGENT") ?? DefaultUserAgent;
- httpClient.DefaultRequestHeaders.Add("User-Agent", userAgent);
- return httpClient;
+ return new HttpClient(handler);
}
private static string? GetFilenameFromResponseHeader(HttpResponseMessage response)
diff --git a/backend/Config/ConfigManager.cs b/backend/Config/ConfigManager.cs
index d03be208..612d4120 100644
--- a/backend/Config/ConfigManager.cs
+++ b/backend/Config/ConfigManager.cs
@@ -233,6 +233,14 @@ public class ConfigManager
return GetConfigValue("general.base-url") ?? "http://localhost:3000";
}
+ public string GetUserAgent()
+ {
+ var defaultValue = $"nzbdav/{AppVersion}";
+ return StringUtil.EmptyToNull(GetConfigValue("api.user-agent"))
+ ?? EnvironmentUtil.GetEnvironmentVariable("NZB_GRAB_USER_AGENT")
+ ?? defaultValue;
+ }
+
public class ConfigEventArgs : EventArgs
{
public required Dictionary<string, string> ChangedConfig { get; init; }
diff --git a/frontend/app/components/expanding-text-input/expanding-text-input.module.css b/frontend/app/components/expanding-text-input/expanding-text-input.module.css
new file mode 100644
index 00000000..4d8ba301
--- /dev/null
+++ b/frontend/app/components/expanding-text-input/expanding-text-input.module.css
@@ -0,0 +1,4 @@
+.textarea {
+ resize: none;
+ overflow: hidden;
+}
diff --git a/frontend/app/components/expanding-text-input/expanding-text-input.tsx b/frontend/app/components/expanding-text-input/expanding-text-input.tsx
new file mode 100644
index 00000000..d1ff04ec
--- /dev/null
+++ b/frontend/app/components/expanding-text-input/expanding-text-input.tsx
@@ -0,0 +1,79 @@
+import { useCallback, useRef, useEffect, type ChangeEvent } from "react";
+import { Form } from "react-bootstrap";
+import styles from "./expanding-text-input.module.css";
+import { classNames } from "~/utils/styling";
+
+type ExpandingTextInputProps = {
+ className?: string;
+ value: string;
+ onChange: (value: string) => void;
+ placeholder?: string;
+ id?: string;
+ "aria-describedby"?: string;
+ readOnly?: boolean;
+};
+
+export function ExpandingTextInput({
+ className,
+ value,
+ onChange,
+ placeholder,
+ id,
+ "aria-describedby": ariaDescribedBy,
+ readOnly,
+}: ExpandingTextInputProps) {
+ const textareaRef = useRef<HTMLTextAreaElement>(null);
+
+ const adjustHeight = useCallback(() => {
+ const textarea = textareaRef.current;
+ if (textarea) {
+ textarea.style.height = '0';
+ textarea.style.height = `${textarea.scrollHeight}px`;
+ }
+ }, []);
+
+ // Adjust height when value changes, becoming visible, or container resizes
+ useEffect(() => {
+ const textarea = textareaRef.current;
+ if (!textarea) return;
+
+ adjustHeight();
+
+ const intersectionObserver = new IntersectionObserver((entries) => {
+ if (entries[0].isIntersecting) {
+ adjustHeight();
+ }
+ });
+ intersectionObserver.observe(textarea);
+
+ const resizeObserver = new ResizeObserver(() => {
+ adjustHeight();
+ });
+ resizeObserver.observe(textarea);
+
+ return () => {
+ intersectionObserver.disconnect();
+ resizeObserver.disconnect();
+ };
+ }, [value, adjustHeight]);
+
+ const handleChange = useCallback((e: ChangeEvent<HTMLTextAreaElement>) => {
+ onChange(e.target.value);
+ }, [onChange]);
+
+ return (
+ <Form.Control
+ as="textarea"
+ ref={textareaRef}
+ className={classNames([styles.textarea, className])}
+ value={value}
+ onChange={handleChange}
+ onInput={adjustHeight}
+ placeholder={placeholder}
+ id={id}
+ aria-describedby={ariaDescribedBy}
+ readOnly={readOnly}
+ spellCheck={false}
+ />
+ );
+}
diff --git a/frontend/app/routes/settings/route.tsx b/frontend/app/routes/settings/route.tsx
index 0d0def20..8f6ecffd 100644
--- a/frontend/app/routes/settings/route.tsx
+++ b/frontend/app/routes/settings/route.tsx
@@ -1,6 +1,6 @@
import type { Route } from "./+types/route";
import styles from "./route.module.css"
-import { Tabs, Tab, Button, Form } from "react-bootstrap"
+import { Tabs, Tab, Button } from "react-bootstrap"
import { backendClient } from "~/clients/backend-client.server";
import { isUsenetSettingsUpdated, UsenetSettings } from "./usenet/usenet";
import { isSabnzbdSettingsUpdated, isSabnzbdSettingsValid, SabnzbdSettings } from "./sabnzbd/sabnzbd";
@@ -22,6 +22,7 @@ const defaultConfig = {
"api.duplicate-nzb-behavior": "increment",
"api.import-strategy": "symlinks",
"api.completed-downloads-dir": "",
+ "api.user-agent": "",
"usenet.providers": "",
"usenet.max-download-connections": "15",
"usenet.streaming-priority": "80",
@@ -46,17 +47,22 @@ export async function loader({ request }: Route.LoaderArgs) {
for (const item of configItems) {
config[item.configName] = item.configValue;
}
- return { config: config }
+
+ return {
+ config: config,
+ appVersion: process.env.NZBDAV_VERSION ?? "unknown",
+ }
}
export default function Settings(props: Route.ComponentProps) {
return (
- <Body config={props.loaderData.config} />
+ <Body {...props.loaderData} />
);
}
type BodyProps = {
- config: Record<string, string>
+ config: Record<string, string>,
+ appVersion: string,
};
function Body(props: BodyProps) {
@@ -129,7 +135,7 @@ function Body(props: BodyProps) {
<UsenetSettings config={newConfig} setNewConfig={setNewConfig} />
</Tab>
<Tab eventKey="sabnzbd" title={sabnzbdTitle}>
- <SabnzbdSettings config={newConfig} setNewConfig={setNewConfig} />
+ <SabnzbdSettings config={newConfig} setNewConfig={setNewConfig} appVersion={props.appVersion} />
</Tab>
<Tab eventKey="webdav" title={webdavTitle}>
<WebdavSettings config={newConfig} setNewConfig={setNewConfig} />
diff --git a/frontend/app/routes/settings/sabnzbd/sabnzbd.tsx b/frontend/app/routes/settings/sabnzbd/sabnzbd.tsx
index 590b26f3..cd3a7a4d 100644
--- a/frontend/app/routes/settings/sabnzbd/sabnzbd.tsx
+++ b/frontend/app/routes/settings/sabnzbd/sabnzbd.tsx
@@ -2,14 +2,16 @@ import { Button, Form, InputGroup } from "react-bootstrap";
import { useCallback, useEffect, useMemo, useRef, type Dispatch, type SetStateAction } from "react";
import { TagInput } from "~/components/tag-input/tag-input";
import { MultiCheckboxInput } from "~/components/multi-checkbox-input/multi-checkbox-input";
+import { ExpandingTextInput } from "~/components/expanding-text-input/expanding-text-input";
import styles from "./sabnzbd.module.css"
type SabnzbdSettingsProps = {
config: Record<string, string>
setNewConfig: Dispatch<SetStateAction<Record<string, string>>>
+ appVersion: string,
};
-export function SabnzbdSettings({ config, setNewConfig }: SabnzbdSettingsProps) {
+export function SabnzbdSettings({ config, setNewConfig, appVersion }: SabnzbdSettingsProps) {
const onRefreshApiKey = useCallback(() => {
setNewConfig({ ...config, "api.key": generateNewApiKey() })
@@ -159,6 +161,22 @@ export function SabnzbdSettings({ config, setNewConfig }: SabnzbdSettingsProps)
</Form.Text>
</Form.Group>
<hr />
+ <Form.Group>
+ <Form.Label htmlFor="user-agent-input">User Agent</Form.Label>
+ <ExpandingTextInput
+ className={styles.input}
+ id="user-agent-input"
+ aria-describedby="user-agent-help"
+ value={config["api.user-agent"]}
+ placeholder={`nzbdav/${appVersion}`}
+ onChange={value => setNewConfig({ ...config, "api.user-agent": value })} />
+ <Form.Text id="user-agent-help" muted>
+ The user-agent used by the&nbsp;
+ <a href="https://sabnzbd.org/wiki/configuration/4.5/api#addurl">addurl</a> api
+ for fetching nzb files.
+ </Form.Text>
+ </Form.Group>
+ <hr />
<Form.Group>
<Form.Check
className={styles.input}
@@ -280,6 +298,7 @@ export function isSabnzbdSettingsUpdated(config: Record<string, string>, newConf
|| config["api.import-strategy"] !== newConfig["api.import-strategy"]
|| config["api.completed-downloads-dir"] !== newConfig["api.completed-downloads-dir"]
|| config["general.base-url"] !== newConfig["general.base-url"]
+ || config["api.user-agent"] !== newConfig["api.user-agent"]
}
export function isSabnzbdSettingsValid(newConfig: Record<string, string>) {