mirror of
https://github.com/streamyfin/streamyfin.git
synced 2026-06-04 21:18:31 +01:00
Compare commits
5 Commits
renovate/p
...
feat/unifi
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7fc74df0aa | ||
|
|
ef27674010 | ||
|
|
fb3a994351 | ||
|
|
b54b0c670b | ||
|
|
0f29457ff8 |
@@ -11,12 +11,15 @@ import {
|
||||
} from "react-native";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
import { toast } from "sonner-native";
|
||||
import { ServerUrlStatusText } from "@/components/common/ServerUrlStatusText";
|
||||
import { Text } from "@/components/common/Text";
|
||||
import { ListGroup } from "@/components/list/ListGroup";
|
||||
import { ListItem } from "@/components/list/ListItem";
|
||||
import DisabledSetting from "@/components/settings/DisabledSetting";
|
||||
import { useNetworkAwareQueryClient } from "@/hooks/useNetworkAwareQueryClient";
|
||||
import { useServerUrlResolver } from "@/hooks/useServerUrlResolver";
|
||||
import { useSettings } from "@/utils/atoms/settings";
|
||||
import { reachabilityProbe } from "@/utils/serverUrl/probes/reachability";
|
||||
|
||||
export default function MarlinSearchPage() {
|
||||
const navigation = useNavigation();
|
||||
@@ -29,6 +32,7 @@ export default function MarlinSearchPage() {
|
||||
const queryClient = useNetworkAwareQueryClient();
|
||||
|
||||
const [value, setValue] = useState<string>(settings?.marlinServerUrl || "");
|
||||
const urlResolver = useServerUrlResolver(reachabilityProbe);
|
||||
|
||||
const onSave = (val: string) => {
|
||||
updateSettings({
|
||||
@@ -127,8 +131,17 @@ export default function MarlinSearchPage() {
|
||||
autoCapitalize='none'
|
||||
textContentType='URL'
|
||||
onChangeText={(text) => setValue(text)}
|
||||
onBlur={() => {
|
||||
const candidate = value.trim();
|
||||
if (candidate) {
|
||||
urlResolver.resolve(candidate).then((r) => {
|
||||
if (r.ok) setValue(r.url);
|
||||
});
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</View>
|
||||
<ServerUrlStatusText state={urlResolver} className='mt-1' />
|
||||
</DisabledSetting>
|
||||
<Text className='px-4 text-xs text-neutral-500 mt-1'>
|
||||
{t("home.settings.plugins.marlin_search.marlin_search_hint")}{" "}
|
||||
|
||||
@@ -11,11 +11,14 @@ import {
|
||||
} from "react-native";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
import { toast } from "sonner-native";
|
||||
import { ServerUrlStatusText } from "@/components/common/ServerUrlStatusText";
|
||||
import { Text } from "@/components/common/Text";
|
||||
import { ListGroup } from "@/components/list/ListGroup";
|
||||
import { ListItem } from "@/components/list/ListItem";
|
||||
import { useNetworkAwareQueryClient } from "@/hooks/useNetworkAwareQueryClient";
|
||||
import { useServerUrlResolver } from "@/hooks/useServerUrlResolver";
|
||||
import { useSettings } from "@/utils/atoms/settings";
|
||||
import { reachabilityProbe } from "@/utils/serverUrl/probes/reachability";
|
||||
|
||||
export default function StreamystatsPage() {
|
||||
const { t } = useTranslation();
|
||||
@@ -32,6 +35,7 @@ export default function StreamystatsPage() {
|
||||
|
||||
// Local state for all editable fields
|
||||
const [url, setUrl] = useState<string>(settings?.streamyStatsServerUrl || "");
|
||||
const urlResolver = useServerUrlResolver(reachabilityProbe);
|
||||
const [useForSearch, setUseForSearch] = useState<boolean>(
|
||||
settings?.searchEngine === "Streamystats",
|
||||
);
|
||||
@@ -152,9 +156,20 @@ export default function StreamystatsPage() {
|
||||
autoCapitalize='none'
|
||||
textContentType='URL'
|
||||
onChangeText={setUrl}
|
||||
onBlur={() => {
|
||||
const candidate = url.trim();
|
||||
if (candidate) {
|
||||
urlResolver.resolve(candidate).then((r) => {
|
||||
if (r.ok) setUrl(r.url);
|
||||
});
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</ListItem>
|
||||
</ListGroup>
|
||||
<View className='px-4 mt-1'>
|
||||
<ServerUrlStatusText state={urlResolver} />
|
||||
</View>
|
||||
|
||||
<Text className='px-4 text-xs text-neutral-500 mt-1'>
|
||||
{t("home.settings.plugins.streamystats.streamystats_search_hint")}{" "}
|
||||
|
||||
20
bun.lock
20
bun.lock
@@ -57,8 +57,8 @@
|
||||
"lodash": "4.18.1",
|
||||
"nativewind": "^2.0.11",
|
||||
"patch-package": "^8.0.0",
|
||||
"react": "19.2.7",
|
||||
"react-dom": "19.2.7",
|
||||
"react": "19.2.3",
|
||||
"react-dom": "19.2.3",
|
||||
"react-i18next": "17.0.8",
|
||||
"react-native": "npm:react-native-tvos@0.85.3-0",
|
||||
"react-native-awesome-slider": "^2.9.0",
|
||||
@@ -111,7 +111,7 @@
|
||||
"expo-doctor": "1.19.7",
|
||||
"husky": "9.1.7",
|
||||
"lint-staged": "17.0.5",
|
||||
"react-test-renderer": "19.2.7",
|
||||
"react-test-renderer": "19.2.3",
|
||||
"typescript": "5.9.3",
|
||||
},
|
||||
},
|
||||
@@ -1529,11 +1529,11 @@
|
||||
|
||||
"raw-body": ["raw-body@3.0.2", "", { "dependencies": { "bytes": "~3.1.2", "http-errors": "~2.0.1", "iconv-lite": "~0.7.0", "unpipe": "~1.0.0" } }, "sha512-K5zQjDllxWkf7Z5xJdV0/B0WTNqx6vxG70zJE4N0kBs4LovmEYWJzQGxC9bS9RAKu3bgM40lrd5zoLJ12MQ5BA=="],
|
||||
|
||||
"react": ["react@19.2.7", "", {}, "sha512-HNe9WslTbXmFK8o8cmwgAeJFSBvt1bPdHCVKtaaV+WlAN36mpT4hcRpwbf3fY56ar2oIXzsBpOAiIRHAdY0OlQ=="],
|
||||
"react": ["react@19.2.3", "", {}, "sha512-Ku/hhYbVjOQnXDZFv2+RibmLFGwFdeeKHFcOTlrt7xplBnya5OGn/hIRDsqDiSUcfORsDC7MPxwork8jBwsIWA=="],
|
||||
|
||||
"react-devtools-core": ["react-devtools-core@6.1.5", "", { "dependencies": { "shell-quote": "^1.6.1", "ws": "^7" } }, "sha512-ePrwPfxAnB+7hgnEr8vpKxL9cmnp7F322t8oqcPshbIQQhDKgFDW4tjhF2wjVbdXF9O/nyuy3sQWd9JGpiLPvA=="],
|
||||
|
||||
"react-dom": ["react-dom@19.2.7", "", { "dependencies": { "scheduler": "^0.27.0" }, "peerDependencies": { "react": "^19.2.7" } }, "sha512-t0BRVXvbiE/o20Hfw669rLbMCDWtYZLvmJigy2f0MxsXF+71pxhR3xOkspmsO8h3ZlNzyibAmtCa3l4lYKk6gQ=="],
|
||||
"react-dom": ["react-dom@19.2.3", "", { "dependencies": { "scheduler": "^0.27.0" }, "peerDependencies": { "react": "^19.2.3" } }, "sha512-yELu4WmLPw5Mr/lmeEpox5rw3RETacE++JgHqQzd2dg+YbJuat3jH4ingc+WPZhxaoFzdv9y33G+F7Nl5O0GBg=="],
|
||||
|
||||
"react-fast-compare": ["react-fast-compare@3.2.2", "", {}, "sha512-nsO+KSNgo1SbJqJEYRE9ERzo7YtYbou/OqjSQKxV7jcKox7+usiUVZOAC+XnDOABXggQTno0Y1CpVnuWEc1boQ=="],
|
||||
|
||||
@@ -1541,7 +1541,7 @@
|
||||
|
||||
"react-i18next": ["react-i18next@17.0.8", "", { "dependencies": { "@babel/runtime": "^7.29.2", "html-parse-stringify": "^3.0.1", "use-sync-external-store": "^1.6.0" }, "peerDependencies": { "i18next": ">= 26.2.0", "react": ">= 16.8.0", "react-dom": "*", "react-native": "*", "typescript": "^5 || ^6" }, "optionalPeers": ["react-dom", "react-native", "typescript"] }, "sha512-0ooKbGLU8JXhe1zwpQUWIeXSgLPOfwJmgheWRIUpcoA0CpyabpGhayjdG+/eA5esC1AQ8h2jWpXjJfzQzeDOCw=="],
|
||||
|
||||
"react-is": ["react-is@19.2.7", "", {}, "sha512-kZFnouyVv7eP/Phmrlo9FK+zcAdriZJvzxXHF1Sl1P377WSGe2G/JxVolhTrB/jeV47lKImhNUsijjHAAbcl/A=="],
|
||||
"react-is": ["react-is@19.2.6", "", {}, "sha512-XjBR15BhXuylgWGuslhDKqlSayuqvqBX91BP8pauG8kd1zY8kotkNWbXksTCNRarse4kuGbe2kIY05ARtwNIvw=="],
|
||||
|
||||
"react-native": ["react-native-tvos@0.85.3-0", "", { "dependencies": { "@react-native-tvos/virtualized-lists": "0.85.3-0", "@react-native/assets-registry": "0.85.3", "@react-native/codegen": "0.85.3", "@react-native/community-cli-plugin": "0.85.3", "@react-native/gradle-plugin": "0.85.3", "@react-native/js-polyfills": "0.85.3", "@react-native/normalize-colors": "0.85.3", "abort-controller": "^3.0.0", "anser": "^1.4.9", "ansi-regex": "^5.0.0", "babel-plugin-syntax-hermes-parser": "0.33.3", "base64-js": "^1.5.1", "commander": "^12.0.0", "flow-enums-runtime": "^0.0.6", "hermes-compiler": "250829098.0.10", "invariant": "^2.2.4", "memoize-one": "^5.0.0", "metro-runtime": "^0.84.3", "metro-source-map": "^0.84.3", "nullthrows": "^1.1.1", "pretty-format": "^29.7.0", "promise": "^8.3.0", "react-devtools-core": "^6.1.5", "react-refresh": "^0.14.0", "regenerator-runtime": "^0.13.2", "scheduler": "0.27.0", "semver": "^7.1.3", "stacktrace-parser": "^0.1.10", "tinyglobby": "^0.2.15", "whatwg-fetch": "^3.0.0", "ws": "^7.5.10", "yargs": "^17.6.2" }, "peerDependencies": { "@react-native/jest-preset": "0.85.3", "@types/react": "^19.1.1", "react": "^19.2.3" }, "optionalPeers": ["@react-native/jest-preset", "@types/react"], "bin": { "react-native": "cli.js" } }, "sha512-Q9gUndppXbGEiYlQ8eudkdH7rDXdY+KM74Btd5xqMvXHgo7ZXdwI1hKvStmI47KmTaDn0NOmcRl2yBwHfc5+5A=="],
|
||||
|
||||
@@ -1599,7 +1599,7 @@
|
||||
|
||||
"react-native-text-ticker": ["react-native-text-ticker@1.15.0", "", {}, "sha512-d/uK+PIOhsYMy1r8h825iq/nADiHsabz3WMbRJSnkpQYn+K9aykUAXRRhu8ZbTAzk4CgnUWajJEFxS5ZDygsdg=="],
|
||||
|
||||
"react-native-track-player": ["react-native-track-player@github:lovegaoshi/react-native-track-player#33a3ecd", { "peerDependencies": { "react": "*", "react-native": "*", "react-native-windows": "*", "shaka-player": "^4.7.9" }, "optionalPeers": ["react-native-windows", "shaka-player"] }, "lovegaoshi-react-native-track-player-33a3ecd", "sha512-vfkld2jUj7EPkAjIc/Vbx4Q4MtOOLmYtCYCE2dWJsyLnPqgj1f0xVzBxbeVP7dfT+eSh4KIXfdxESXaHgrXIlw=="],
|
||||
"react-native-track-player": ["react-native-track-player@github:lovegaoshi/react-native-track-player#33a3ecd", { "peerDependencies": { "react": "*", "react-native": "*", "react-native-windows": "*", "shaka-player": "^4.7.9" }, "optionalPeers": ["react-native-windows", "shaka-player"] }, "lovegaoshi-react-native-track-player-33a3ecd"],
|
||||
|
||||
"react-native-udp": ["react-native-udp@4.1.7", "", { "dependencies": { "buffer": "^5.6.0", "events": "^3.1.0" } }, "sha512-NUE3zewu61NCdSsLlj+l0ad6qojcVEZPT4hVG/x6DU9U4iCzwtfZSASh9vm7teAcVzLkdD+cO3411LHshAi/wA=="],
|
||||
|
||||
@@ -1621,7 +1621,7 @@
|
||||
|
||||
"react-style-singleton": ["react-style-singleton@2.2.3", "", { "dependencies": { "get-nonce": "^1.0.0", "tslib": "^2.0.0" }, "peerDependencies": { "@types/react": "*", "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-b6jSvxvVnyptAiLjbkWLE/lOnR4lfTtDAl+eUC7RZy+QQWc6wRzIV2CE6xBuMmDxc2qIihtDCZD5NPOFl7fRBQ=="],
|
||||
|
||||
"react-test-renderer": ["react-test-renderer@19.2.7", "", { "dependencies": { "react-is": "^19.2.7", "scheduler": "^0.27.0" }, "peerDependencies": { "react": "^19.2.7" } }, "sha512-U4TyPDJ9MsC8rFimXuJum8w40aPc9kbOZYO8Pc2/4A884i8hwJsMNA/JNyuOc/f2/37wHvk7HjpVl1V4re7Dig=="],
|
||||
"react-test-renderer": ["react-test-renderer@19.2.3", "", { "dependencies": { "react-is": "^19.2.3", "scheduler": "^0.27.0" }, "peerDependencies": { "react": "^19.2.3" } }, "sha512-TMR1LnSFiWZMJkCgNf5ATSvAheTT2NvKIwiVwdBPHxjBI7n/JbWd4gaZ16DVd9foAXdvDz+sB5yxZTwMjPRxpw=="],
|
||||
|
||||
"read-cache": ["read-cache@1.0.0", "", { "dependencies": { "pify": "^2.3.0" } }, "sha512-Owdv/Ft7IjOgm/i0xvNDZ1LrRANRfew4b2prF3OWMQLxLfu3bS8FVhCsrSCMK4lR56Y9ya+AThoTpDCTxCmpRA=="],
|
||||
|
||||
@@ -2009,8 +2009,6 @@
|
||||
|
||||
"@react-native/metro-babel-transformer/@babel/core": ["@babel/core@7.28.6", "", { "dependencies": { "@babel/code-frame": "^7.28.6", "@babel/generator": "^7.28.6", "@babel/helper-compilation-targets": "^7.28.6", "@babel/helper-module-transforms": "^7.28.6", "@babel/helpers": "^7.28.6", "@babel/parser": "^7.28.6", "@babel/template": "^7.28.6", "@babel/traverse": "^7.28.6", "@babel/types": "^7.28.6", "@jridgewell/remapping": "^2.3.5", "convert-source-map": "^2.0.0", "debug": "^4.1.0", "gensync": "^1.0.0-beta.2", "json5": "^2.2.3", "semver": "^6.3.1" } }, "sha512-H3mcG6ZDLTlYfaSNi0iOKkigqMFvkTKlGUYlD8GW7nNOYRrevuA46iTypPyv+06V3fEmvvazfntkBU34L0azAw=="],
|
||||
|
||||
"@react-navigation/core/react-is": ["react-is@19.2.6", "", {}, "sha512-XjBR15BhXuylgWGuslhDKqlSayuqvqBX91BP8pauG8kd1zY8kotkNWbXksTCNRarse4kuGbe2kIY05ARtwNIvw=="],
|
||||
|
||||
"@react-navigation/elements/color": ["color@4.2.3", "", { "dependencies": { "color-convert": "^2.0.1", "color-string": "^1.9.0" } }, "sha512-1rXeuUUiGGrykh+CeBdu5Ie7OJwinCgQY0bc7GCRxy5xVHy+moaqkpL/jqQq0MtQOeYcrqEz4abc5f0KtU7W4A=="],
|
||||
|
||||
"@react-navigation/material-top-tabs/color": ["color@4.2.3", "", { "dependencies": { "color-convert": "^2.0.1", "color-string": "^1.9.0" } }, "sha512-1rXeuUUiGGrykh+CeBdu5Ie7OJwinCgQY0bc7GCRxy5xVHy+moaqkpL/jqQq0MtQOeYcrqEz4abc5f0KtU7W4A=="],
|
||||
@@ -2059,8 +2057,6 @@
|
||||
|
||||
"expo-router/color": ["color@4.2.3", "", { "dependencies": { "color-convert": "^2.0.1", "color-string": "^1.9.0" } }, "sha512-1rXeuUUiGGrykh+CeBdu5Ie7OJwinCgQY0bc7GCRxy5xVHy+moaqkpL/jqQq0MtQOeYcrqEz4abc5f0KtU7W4A=="],
|
||||
|
||||
"expo-router/react-is": ["react-is@19.2.6", "", {}, "sha512-XjBR15BhXuylgWGuslhDKqlSayuqvqBX91BP8pauG8kd1zY8kotkNWbXksTCNRarse4kuGbe2kIY05ARtwNIvw=="],
|
||||
|
||||
"fast-glob/glob-parent": ["glob-parent@5.1.2", "", { "dependencies": { "is-glob": "^4.0.1" } }, "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow=="],
|
||||
|
||||
"fbjs/promise": ["promise@7.3.1", "", { "dependencies": { "asap": "~2.0.3" } }, "sha512-nolQXZ/4L+bP/UGlkfaIujX9BKxGwmQ9OT4mOt5yvy8iK1h3wqTEJCijzGANTCCl9nWjY41juyAn2K3Q1hLLTg=="],
|
||||
|
||||
99
components/common/ServerUrlField.tsx
Normal file
99
components/common/ServerUrlField.tsx
Normal file
@@ -0,0 +1,99 @@
|
||||
import { useCallback, useRef } from "react";
|
||||
import { View } from "react-native";
|
||||
import { useServerUrlResolver } from "@/hooks/useServerUrlResolver";
|
||||
import type { ResolveOptions } from "@/utils/serverUrl/resolve";
|
||||
import type { ServerProbe } from "@/utils/serverUrl/types";
|
||||
import { Input } from "./Input";
|
||||
import { ServerUrlStatusText } from "./ServerUrlStatusText";
|
||||
import { Text } from "./Text";
|
||||
|
||||
interface ServerUrlFieldProps {
|
||||
/** Raw user input (controlled). */
|
||||
value: string;
|
||||
onChangeText: (text: string) => void;
|
||||
/** Service-specific validator. Pass a stable (module-level) reference. */
|
||||
probe: ServerProbe;
|
||||
/** Called with the canonical URL once a candidate validates. */
|
||||
onResolved?: (url: string, meta?: Record<string, unknown>) => void;
|
||||
label?: string;
|
||||
hint?: string;
|
||||
placeholder?: string;
|
||||
editable?: boolean;
|
||||
resolveOptions?: ResolveOptions;
|
||||
}
|
||||
|
||||
/**
|
||||
* Unified server-URL input: the user types a loose address (`media.example.com`,
|
||||
* `https://…`, `host:port`); on blur it auto-resolves via the given probe,
|
||||
* adopts the canonical URL into the field, and persists it. A small status line
|
||||
* (checking / resolved / error) shows underneath.
|
||||
*/
|
||||
export function ServerUrlField({
|
||||
value,
|
||||
onChangeText,
|
||||
probe,
|
||||
onResolved,
|
||||
label,
|
||||
hint,
|
||||
placeholder,
|
||||
editable = true,
|
||||
resolveOptions,
|
||||
}: ServerUrlFieldProps) {
|
||||
const resolver = useServerUrlResolver(probe, resolveOptions);
|
||||
const lastResolvedInput = useRef<string | null>(null);
|
||||
|
||||
const runResolve = useCallback(async () => {
|
||||
const input = value.trim();
|
||||
if (!input) {
|
||||
resolver.reset();
|
||||
lastResolvedInput.current = null;
|
||||
return;
|
||||
}
|
||||
lastResolvedInput.current = input;
|
||||
const result = await resolver.resolve(input);
|
||||
if (result.ok) {
|
||||
onChangeText(result.url); // adopt the canonical URL into the field
|
||||
onResolved?.(result.url, result.meta);
|
||||
}
|
||||
}, [value, resolver, onChangeText, onResolved]);
|
||||
|
||||
const handleBlur = useCallback(() => {
|
||||
const input = value.trim();
|
||||
if (input && input !== lastResolvedInput.current) runResolve();
|
||||
}, [value, runResolve]);
|
||||
|
||||
const handleChange = useCallback(
|
||||
(text: string) => {
|
||||
onChangeText(text);
|
||||
// Editing invalidates a previous result; drop the stale status.
|
||||
if (resolver.status !== "idle") resolver.reset();
|
||||
lastResolvedInput.current = null;
|
||||
},
|
||||
[onChangeText, resolver],
|
||||
);
|
||||
|
||||
return (
|
||||
<View>
|
||||
{label ? <Text className='font-bold mb-1'>{label}</Text> : null}
|
||||
{hint ? <Text className='text-xs text-gray-500 mb-2'>{hint}</Text> : null}
|
||||
|
||||
<Input
|
||||
value={value}
|
||||
onChangeText={handleChange}
|
||||
onBlur={handleBlur}
|
||||
onSubmitEditing={runResolve}
|
||||
placeholder={placeholder}
|
||||
editable={editable}
|
||||
extraClassName='border border-neutral-800'
|
||||
keyboardType='url'
|
||||
autoCapitalize='none'
|
||||
autoCorrect={false}
|
||||
returnKeyType='go'
|
||||
textContentType='URL'
|
||||
clearButtonMode='never'
|
||||
/>
|
||||
|
||||
<ServerUrlStatusText state={resolver} className='mt-2' />
|
||||
</View>
|
||||
);
|
||||
}
|
||||
49
components/common/ServerUrlStatusText.tsx
Normal file
49
components/common/ServerUrlStatusText.tsx
Normal file
@@ -0,0 +1,49 @@
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { ActivityIndicator, View } from "react-native";
|
||||
import type { ServerUrlResolverState } from "@/hooks/useServerUrlResolver";
|
||||
import { Text } from "./Text";
|
||||
|
||||
/**
|
||||
* Compact status line for the server-URL resolver, for screens whose layout
|
||||
* (e.g. ListItem rows) doesn't fit the full `ServerUrlField`. Renders nothing
|
||||
* while idle.
|
||||
*/
|
||||
export function ServerUrlStatusText({
|
||||
state,
|
||||
className = "",
|
||||
}: {
|
||||
state: ServerUrlResolverState;
|
||||
className?: string;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
if (state.status === "idle") return null;
|
||||
|
||||
if (state.status === "resolving") {
|
||||
return (
|
||||
<View className={`flex-row items-center ${className}`}>
|
||||
<ActivityIndicator size='small' color='#9ca3af' />
|
||||
<Text className='text-xs text-neutral-400 ml-2'>
|
||||
{t("server_url.resolving")}
|
||||
</Text>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
if (state.status === "ok") {
|
||||
return (
|
||||
<Text className={`text-xs text-green-500 ${className}`}>
|
||||
{t("server_url.resolved", { url: state.resolvedUrl })}
|
||||
</Text>
|
||||
);
|
||||
}
|
||||
|
||||
const message =
|
||||
state.reason === "wrong-service"
|
||||
? t("server_url.wrong_service")
|
||||
: state.reason === "invalid"
|
||||
? t("server_url.invalid_url")
|
||||
: t("server_url.unreachable");
|
||||
|
||||
return <Text className={`text-xs text-red-500 ${className}`}>{message}</Text>;
|
||||
}
|
||||
@@ -11,10 +11,13 @@ import {
|
||||
View,
|
||||
} from "react-native";
|
||||
import { Button } from "@/components/Button";
|
||||
import { ServerUrlStatusText } from "@/components/common/ServerUrlStatusText";
|
||||
import { Text } from "@/components/common/Text";
|
||||
import useRouter from "@/hooks/useAppRouter";
|
||||
import { useServerUrlResolver } from "@/hooks/useServerUrlResolver";
|
||||
import { apiAtom, userAtom } from "@/providers/JellyfinProvider";
|
||||
import { sendCredentialsToTV } from "@/utils/pairingService";
|
||||
import { jellyfinProbe } from "@/utils/serverUrl/probes/jellyfin";
|
||||
|
||||
type ScreenState =
|
||||
| "scanning"
|
||||
@@ -49,6 +52,7 @@ export const CompanionLoginScreen: React.FC = () => {
|
||||
const [username, setUsername] = useState("");
|
||||
const [password, setPassword] = useState("");
|
||||
const [errorMessage, setErrorMessage] = useState<string | null>(null);
|
||||
const serverResolver = useServerUrlResolver(jellyfinProbe);
|
||||
|
||||
// Pre-fill server URL and username from current session
|
||||
useEffect(() => {
|
||||
@@ -405,7 +409,16 @@ export const CompanionLoginScreen: React.FC = () => {
|
||||
autoCorrect={false}
|
||||
keyboardType='url'
|
||||
returnKeyType='next'
|
||||
onBlur={() => {
|
||||
const candidate = serverUrl.trim();
|
||||
if (candidate) {
|
||||
serverResolver.resolve(candidate).then((r) => {
|
||||
if (r.ok) setServerUrl(r.url);
|
||||
});
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<ServerUrlStatusText state={serverResolver} className='mt-2' />
|
||||
</View>
|
||||
|
||||
<View className='mb-5'>
|
||||
|
||||
@@ -7,8 +7,11 @@ import { toast } from "sonner-native";
|
||||
import { JellyseerrApi, useJellyseerr } from "@/hooks/useJellyseerr";
|
||||
import { userAtom } from "@/providers/JellyfinProvider";
|
||||
import { useSettings } from "@/utils/atoms/settings";
|
||||
import { jellyseerrProbe } from "@/utils/serverUrl/probes/jellyseerr";
|
||||
import { resolveServerUrl } from "@/utils/serverUrl/resolve";
|
||||
import { Button } from "../Button";
|
||||
import { Input } from "../common/Input";
|
||||
import { ServerUrlField } from "../common/ServerUrlField";
|
||||
import { Text } from "../common/Text";
|
||||
import { ListGroup } from "../list/ListGroup";
|
||||
import { ListItem } from "../list/ListItem";
|
||||
@@ -26,26 +29,44 @@ export const JellyseerrSettings = () => {
|
||||
string | undefined
|
||||
>(undefined);
|
||||
|
||||
const [jellyseerrServerUrl, setjellyseerrServerUrl] = useState<
|
||||
string | undefined
|
||||
>(settings?.jellyseerrServerUrl || undefined);
|
||||
const [jellyseerrServerUrl, setjellyseerrServerUrl] = useState<string>(
|
||||
settings?.jellyseerrServerUrl ?? "",
|
||||
);
|
||||
const [resolvedUrl, setResolvedUrl] = useState<string | undefined>(
|
||||
settings?.jellyseerrServerUrl ?? undefined,
|
||||
);
|
||||
|
||||
const loginToJellyseerrMutation = useMutation({
|
||||
mutationFn: async () => {
|
||||
if (!jellyseerrServerUrl && !settings?.jellyseerrServerUrl)
|
||||
throw new Error("Missing server url");
|
||||
if (!user?.Name)
|
||||
throw new Error("Missing required information for login");
|
||||
const jellyseerrTempApi = new JellyseerrApi(
|
||||
jellyseerrServerUrl || settings.jellyseerrServerUrl || "",
|
||||
);
|
||||
|
||||
// Prefer the already-resolved URL; otherwise resolve the raw input now
|
||||
// (covers tapping Login before the field's on-blur resolve settled).
|
||||
let finalUrl = resolvedUrl || settings?.jellyseerrServerUrl || "";
|
||||
if (!finalUrl && jellyseerrServerUrl) {
|
||||
const resolved = await resolveServerUrl(
|
||||
jellyseerrServerUrl,
|
||||
jellyseerrProbe,
|
||||
);
|
||||
if (!resolved.ok) throw new Error("Invalid server url");
|
||||
finalUrl = resolved.url;
|
||||
}
|
||||
if (!finalUrl) throw new Error("Missing server url");
|
||||
|
||||
const jellyseerrTempApi = new JellyseerrApi(finalUrl);
|
||||
const testResult = await jellyseerrTempApi.test();
|
||||
if (!testResult.isValid) throw new Error("Invalid server url");
|
||||
return jellyseerrTempApi.login(user.Name, jellyseerrPassword || "");
|
||||
const loggedInUser = await jellyseerrTempApi.login(
|
||||
user.Name,
|
||||
jellyseerrPassword || "",
|
||||
);
|
||||
return { user: loggedInUser, url: finalUrl };
|
||||
},
|
||||
onSuccess: (user) => {
|
||||
setJellyseerrUser(user);
|
||||
updateSettings({ jellyseerrServerUrl });
|
||||
onSuccess: ({ user: loggedInUser, url }) => {
|
||||
setJellyseerrUser(loggedInUser);
|
||||
setResolvedUrl(url);
|
||||
updateSettings({ jellyseerrServerUrl: url });
|
||||
},
|
||||
onError: () => {
|
||||
toast.error(t("jellyseerr.failed_to_login"));
|
||||
@@ -59,7 +80,8 @@ export const JellyseerrSettings = () => {
|
||||
clearAllJellyseerData().finally(() => {
|
||||
setJellyseerrUser(undefined);
|
||||
setJellyseerrPassword(undefined);
|
||||
setjellyseerrServerUrl(undefined);
|
||||
setjellyseerrServerUrl("");
|
||||
setResolvedUrl(undefined);
|
||||
});
|
||||
};
|
||||
|
||||
@@ -118,30 +140,20 @@ export const JellyseerrSettings = () => {
|
||||
<Text className='text-xs text-red-600 mb-2'>
|
||||
{t("home.settings.plugins.jellyseerr.jellyseerr_warning")}
|
||||
</Text>
|
||||
<Text className='font-bold mb-1'>
|
||||
{t("home.settings.plugins.jellyseerr.server_url")}
|
||||
</Text>
|
||||
<View className='flex flex-col shrink mb-2'>
|
||||
<Text className='text-xs text-gray-600'>
|
||||
{t("home.settings.plugins.jellyseerr.server_url_hint")}
|
||||
</Text>
|
||||
<View className='mb-2'>
|
||||
<ServerUrlField
|
||||
value={jellyseerrServerUrl}
|
||||
onChangeText={setjellyseerrServerUrl}
|
||||
onResolved={(url) => setResolvedUrl(url)}
|
||||
probe={jellyseerrProbe}
|
||||
label={t("home.settings.plugins.jellyseerr.server_url")}
|
||||
hint={t("home.settings.plugins.jellyseerr.server_url_hint")}
|
||||
placeholder={t(
|
||||
"home.settings.plugins.jellyseerr.server_url_placeholder",
|
||||
)}
|
||||
editable={!loginToJellyseerrMutation.isPending}
|
||||
/>
|
||||
</View>
|
||||
<Input
|
||||
className='border border-neutral-800 mb-2'
|
||||
placeholder={t(
|
||||
"home.settings.plugins.jellyseerr.server_url_placeholder",
|
||||
)}
|
||||
value={jellyseerrServerUrl ?? settings?.jellyseerrServerUrl}
|
||||
defaultValue={
|
||||
settings?.jellyseerrServerUrl ?? jellyseerrServerUrl
|
||||
}
|
||||
keyboardType='url'
|
||||
returnKeyType='done'
|
||||
autoCapitalize='none'
|
||||
textContentType='URL'
|
||||
onChangeText={setjellyseerrServerUrl}
|
||||
editable={!loginToJellyseerrMutation.isPending}
|
||||
/>
|
||||
<View>
|
||||
<Text className='font-bold mb-2'>
|
||||
{t("home.settings.plugins.jellyseerr.password")}
|
||||
|
||||
@@ -12,8 +12,9 @@ import {
|
||||
type LocalNetworkConfig,
|
||||
updateServerLocalConfig,
|
||||
} from "@/utils/secureCredentials";
|
||||
import { jellyfinProbe } from "@/utils/serverUrl/probes/jellyfin";
|
||||
import { Button } from "../Button";
|
||||
import { Input } from "../common/Input";
|
||||
import { ServerUrlField } from "../common/ServerUrlField";
|
||||
import { Text } from "../common/Text";
|
||||
import { ListGroup } from "../list/ListGroup";
|
||||
import { ListItem } from "../list/ListItem";
|
||||
@@ -162,13 +163,12 @@ export function LocalNetworkSettings(): React.ReactElement | null {
|
||||
}
|
||||
>
|
||||
<View className=''>
|
||||
<Input
|
||||
placeholder={t("home.settings.network.local_url_placeholder")}
|
||||
<ServerUrlField
|
||||
value={config.localUrl}
|
||||
onChangeText={handleLocalUrlChange}
|
||||
keyboardType='url'
|
||||
autoCapitalize='none'
|
||||
autoCorrect={false}
|
||||
onResolved={(url) => saveConfig({ ...config, localUrl: url })}
|
||||
probe={jellyfinProbe}
|
||||
placeholder={t("home.settings.network.local_url_placeholder")}
|
||||
/>
|
||||
</View>
|
||||
</ListGroup>
|
||||
|
||||
@@ -48,6 +48,7 @@ import type {
|
||||
TvDetails,
|
||||
} from "@/utils/jellyseerr/server/models/Tv";
|
||||
import { writeErrorLog } from "@/utils/log";
|
||||
import { isVersionBelow } from "@/utils/serverUrl/semver";
|
||||
|
||||
interface SearchParams {
|
||||
query: string;
|
||||
@@ -141,10 +142,13 @@ export class JellyseerrApi {
|
||||
.then((response) => {
|
||||
const { status, headers, data } = response;
|
||||
if (inRange(status, 200, 299)) {
|
||||
if (data.version < "2.0.0") {
|
||||
if (data.version && isVersionBelow(data.version, "2.0.0")) {
|
||||
const error = t(
|
||||
"jellyseerr.toasts.jellyseer_does_not_meet_requirements",
|
||||
);
|
||||
writeErrorLog(
|
||||
`Jellyseerr version ${data.version} is below the required 2.0.0`,
|
||||
);
|
||||
toast.error(error);
|
||||
throw Error(error);
|
||||
}
|
||||
|
||||
65
hooks/useServerUrlResolver.ts
Normal file
65
hooks/useServerUrlResolver.ts
Normal file
@@ -0,0 +1,65 @@
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import {
|
||||
type ResolveFailureReason,
|
||||
type ResolveOptions,
|
||||
type ResolveResult,
|
||||
resolveServerUrl,
|
||||
} from "@/utils/serverUrl/resolve";
|
||||
import type { ServerProbe } from "@/utils/serverUrl/types";
|
||||
|
||||
export type ServerUrlResolverState =
|
||||
| { status: "idle" }
|
||||
| { status: "resolving" }
|
||||
| { status: "ok"; resolvedUrl: string; meta?: Record<string, unknown> }
|
||||
| { status: "error"; reason: ResolveFailureReason };
|
||||
|
||||
/**
|
||||
* Stateful wrapper around `resolveServerUrl` for screens.
|
||||
*
|
||||
* `resolve(input)` cancels any in-flight resolution, drives the state machine
|
||||
* (idle → resolving → ok | error) and returns the raw result. Pass a stable
|
||||
* (module-level) probe; memoize `options` if you supply one.
|
||||
*/
|
||||
export function useServerUrlResolver(
|
||||
probe: ServerProbe,
|
||||
options?: ResolveOptions,
|
||||
) {
|
||||
const [state, setState] = useState<ServerUrlResolverState>({
|
||||
status: "idle",
|
||||
});
|
||||
const abortRef = useRef<AbortController | null>(null);
|
||||
|
||||
const resolve = useCallback(
|
||||
async (input: string): Promise<ResolveResult> => {
|
||||
abortRef.current?.abort();
|
||||
const controller = new AbortController();
|
||||
abortRef.current = controller;
|
||||
setState({ status: "resolving" });
|
||||
|
||||
const result = await resolveServerUrl(input, probe, {
|
||||
...options,
|
||||
signal: controller.signal,
|
||||
});
|
||||
|
||||
// Ignore results from a resolution that was superseded/cancelled.
|
||||
if (!controller.signal.aborted) {
|
||||
setState(
|
||||
result.ok
|
||||
? { status: "ok", resolvedUrl: result.url, meta: result.meta }
|
||||
: { status: "error", reason: result.reason },
|
||||
);
|
||||
}
|
||||
return result;
|
||||
},
|
||||
[probe, options],
|
||||
);
|
||||
|
||||
const reset = useCallback(() => {
|
||||
abortRef.current?.abort();
|
||||
setState({ status: "idle" });
|
||||
}, []);
|
||||
|
||||
useEffect(() => () => abortRef.current?.abort(), []);
|
||||
|
||||
return { ...state, resolve, reset };
|
||||
}
|
||||
@@ -78,8 +78,8 @@
|
||||
"lodash": "4.18.1",
|
||||
"nativewind": "^2.0.11",
|
||||
"patch-package": "^8.0.0",
|
||||
"react": "19.2.7",
|
||||
"react-dom": "19.2.7",
|
||||
"react": "19.2.3",
|
||||
"react-dom": "19.2.3",
|
||||
"react-i18next": "17.0.8",
|
||||
"react-native": "npm:react-native-tvos@0.85.3-0",
|
||||
"react-native-awesome-slider": "^2.9.0",
|
||||
@@ -132,7 +132,7 @@
|
||||
"expo-doctor": "1.19.7",
|
||||
"husky": "9.1.7",
|
||||
"lint-staged": "17.0.5",
|
||||
"react-test-renderer": "19.2.7",
|
||||
"react-test-renderer": "19.2.3",
|
||||
"typescript": "5.9.3"
|
||||
},
|
||||
"expo": {
|
||||
|
||||
@@ -1,4 +1,12 @@
|
||||
{
|
||||
"server_url": {
|
||||
"resolving": "Checking…",
|
||||
"resolved": "→ {{url}}",
|
||||
"connected": "Connected to {{url}}",
|
||||
"unreachable": "Server unreachable",
|
||||
"wrong_service": "Reachable, but not the expected server",
|
||||
"invalid_url": "Enter a valid address"
|
||||
},
|
||||
"login": {
|
||||
"username_required": "Username Is Required",
|
||||
"error_title": "Error",
|
||||
|
||||
75
utils/serverUrl/candidates.ts
Normal file
75
utils/serverUrl/candidates.ts
Normal file
@@ -0,0 +1,75 @@
|
||||
/**
|
||||
* Generic server-URL candidate generator.
|
||||
*
|
||||
* Turns loose user input (`media.uruk.dev`, `https://media.uruk.dev`,
|
||||
* `host:8096`, `http://10.0.0.5:3000/path`) into an ordered list of full URLs
|
||||
* to probe — https first, http as fallback — while preserving any explicit
|
||||
* port and path. Service-agnostic: unlike the Jellyfin SDK's `getAddressCandidates`
|
||||
* it adds no Jellyfin-specific ports, so it suits Jellyseerr/Streamystats/etc.
|
||||
*/
|
||||
|
||||
// scheme? host (port)? (path/query/hash)?
|
||||
const URL_RE = /^(?:(https?):\/\/)?([^/:\s?#]+)(?::(\d+))?([/?#].*)?$/i;
|
||||
|
||||
export interface ParsedServerInput {
|
||||
scheme?: "http" | "https";
|
||||
host: string;
|
||||
port?: string;
|
||||
/** Normalized path+query+hash, without a trailing slash; "" when none. */
|
||||
path: string;
|
||||
}
|
||||
|
||||
function normalizePath(path?: string): string {
|
||||
if (!path || path === "/") return "";
|
||||
return path.replace(/\/+$/, "");
|
||||
}
|
||||
|
||||
/** Parse loose user input. Returns null when it can't be understood. */
|
||||
export function parseServerInput(input: string): ParsedServerInput | null {
|
||||
const trimmed = input.trim();
|
||||
if (!trimmed) return null;
|
||||
|
||||
const match = URL_RE.exec(trimmed);
|
||||
if (!match) return null;
|
||||
|
||||
const [, scheme, host, port, rawPath] = match;
|
||||
return {
|
||||
scheme: scheme ? (scheme.toLowerCase() as "http" | "https") : undefined,
|
||||
host: host.toLowerCase(),
|
||||
port,
|
||||
path: normalizePath(rawPath),
|
||||
};
|
||||
}
|
||||
|
||||
function buildUrl(
|
||||
scheme: "http" | "https",
|
||||
host: string,
|
||||
port: string | undefined,
|
||||
path: string,
|
||||
): string {
|
||||
return `${scheme}://${host}${port ? `:${port}` : ""}${path}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Ordered, de-duplicated candidate URLs for the given input.
|
||||
*
|
||||
* - Explicit scheme AND port → trusted as-is (single candidate).
|
||||
* - Otherwise https is tried before http (prefer secure), keeping any port/path.
|
||||
*
|
||||
* @returns [] when the input can't be parsed.
|
||||
*/
|
||||
export function getServerUrlCandidates(input: string): string[] {
|
||||
const parsed = parseServerInput(input);
|
||||
if (!parsed) return [];
|
||||
|
||||
const { scheme, host, port, path } = parsed;
|
||||
|
||||
// Fully specified: don't second-guess the user.
|
||||
if (scheme && port) return [buildUrl(scheme, host, port, path)];
|
||||
|
||||
// Secure-first; the typed scheme (if any) is still covered by this set.
|
||||
const candidates = (["https", "http"] as const).map((s) =>
|
||||
buildUrl(s, host, port, path),
|
||||
);
|
||||
return Array.from(new Set(candidates));
|
||||
}
|
||||
16
utils/serverUrl/index.ts
Normal file
16
utils/serverUrl/index.ts
Normal file
@@ -0,0 +1,16 @@
|
||||
export {
|
||||
getServerUrlCandidates,
|
||||
type ParsedServerInput,
|
||||
parseServerInput,
|
||||
} from "./candidates";
|
||||
export { jellyfinProbe } from "./probes/jellyfin";
|
||||
export { jellyseerrProbe } from "./probes/jellyseerr";
|
||||
export { reachabilityProbe } from "./probes/reachability";
|
||||
export {
|
||||
type ResolveFailureReason,
|
||||
type ResolveOptions,
|
||||
type ResolveResult,
|
||||
resolveServerUrl,
|
||||
} from "./resolve";
|
||||
export { isVersionBelow } from "./semver";
|
||||
export type { ServerProbe, ServerProbeOutcome } from "./types";
|
||||
24
utils/serverUrl/probes/jellyfin.ts
Normal file
24
utils/serverUrl/probes/jellyfin.ts
Normal file
@@ -0,0 +1,24 @@
|
||||
import axios from "axios";
|
||||
import type { ServerProbe } from "../types";
|
||||
|
||||
/** Public, unauthenticated Jellyfin endpoint; `ProductName` confirms the service. */
|
||||
const PRODUCT_NAME = "Jellyfin Server";
|
||||
|
||||
export const jellyfinProbe: ServerProbe = async (url, signal) => {
|
||||
try {
|
||||
const { status, data } = await axios.get(`${url}/System/Info/Public`, {
|
||||
signal,
|
||||
timeout: 8000, // backstop; the resolver aborts via signal first
|
||||
});
|
||||
|
||||
if (status < 200 || status >= 300) return { status: "unreachable" };
|
||||
if (data?.ProductName !== PRODUCT_NAME) return { status: "wrong-service" };
|
||||
|
||||
return {
|
||||
status: "ok",
|
||||
meta: { version: data?.Version, serverName: data?.ServerName },
|
||||
};
|
||||
} catch {
|
||||
return { status: "unreachable" };
|
||||
}
|
||||
};
|
||||
30
utils/serverUrl/probes/jellyseerr.ts
Normal file
30
utils/serverUrl/probes/jellyseerr.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
import axios from "axios";
|
||||
import type { ServerProbe } from "../types";
|
||||
|
||||
/**
|
||||
* Probe for a Jellyseerr server. `/api/v1/status` is jellyseerr/overseerr
|
||||
* specific and unauthenticated, so it both proves reachability and confirms we
|
||||
* hit the right service. The minimum-version requirement is enforced at login
|
||||
* time (see JellyseerrApi.test) — not surfaced here, to keep the field UI clean.
|
||||
*/
|
||||
export const jellyseerrProbe: ServerProbe = async (url, signal) => {
|
||||
try {
|
||||
const { status, data } = await axios.get(`${url}/api/v1/status`, {
|
||||
signal,
|
||||
timeout: 8000, // backstop; the resolver aborts via signal first
|
||||
});
|
||||
|
||||
if (status < 200 || status >= 300) return { status: "unreachable" };
|
||||
|
||||
// A JSON body carrying version/commitTag identifies a real jellyseerr.
|
||||
const looksLikeJellyseerr =
|
||||
!!data &&
|
||||
typeof data === "object" &&
|
||||
(typeof data.version === "string" || "commitTag" in data);
|
||||
if (!looksLikeJellyseerr) return { status: "wrong-service" };
|
||||
|
||||
return { status: "ok", meta: { version: data.version } };
|
||||
} catch {
|
||||
return { status: "unreachable" };
|
||||
}
|
||||
};
|
||||
23
utils/serverUrl/probes/reachability.ts
Normal file
23
utils/serverUrl/probes/reachability.ts
Normal file
@@ -0,0 +1,23 @@
|
||||
import axios from "axios";
|
||||
import type { ServerProbe } from "../types";
|
||||
|
||||
/**
|
||||
* Minimal probe for services without a known/unauthenticated health endpoint
|
||||
* (e.g. Marlin Search, Streamystats). Any HTTP response — even 4xx — proves the
|
||||
* host is up and speaking HTTP at this protocol/port, which is enough to pick
|
||||
* https vs http. It cannot detect a "wrong service".
|
||||
*/
|
||||
export const reachabilityProbe: ServerProbe = async (url, signal) => {
|
||||
try {
|
||||
await axios.get(url, {
|
||||
signal,
|
||||
timeout: 8000,
|
||||
validateStatus: () => true, // any status = the server answered
|
||||
});
|
||||
return { status: "ok" };
|
||||
} catch (error) {
|
||||
// A delivered response that still threw counts as reachable.
|
||||
if ((error as { response?: unknown })?.response) return { status: "ok" };
|
||||
return { status: "unreachable" };
|
||||
}
|
||||
};
|
||||
88
utils/serverUrl/resolve.ts
Normal file
88
utils/serverUrl/resolve.ts
Normal file
@@ -0,0 +1,88 @@
|
||||
import { getServerUrlCandidates } from "./candidates";
|
||||
import type { ServerProbe, ServerProbeOutcome } from "./types";
|
||||
|
||||
export type ResolveFailureReason =
|
||||
| "empty"
|
||||
| "invalid"
|
||||
| "wrong-service"
|
||||
| "unreachable";
|
||||
|
||||
export type ResolveResult =
|
||||
| { ok: true; url: string; meta?: Record<string, unknown> }
|
||||
| { ok: false; reason: ResolveFailureReason };
|
||||
|
||||
export interface ResolveOptions {
|
||||
/** Per-candidate probe timeout in ms. Default 5000. */
|
||||
timeoutMs?: number;
|
||||
/** Abort the whole resolution (cancels every in-flight probe). */
|
||||
signal?: AbortSignal;
|
||||
}
|
||||
|
||||
// Order in which to surface a failure when no candidate validated:
|
||||
// the more specific/actionable the reason, the earlier it is reported.
|
||||
const FAILURE_PRIORITY = [
|
||||
"wrong-service",
|
||||
"unreachable",
|
||||
] as const satisfies ReadonlyArray<ResolveFailureReason>;
|
||||
|
||||
/**
|
||||
* Resolve loose user input to a single working, canonical server URL.
|
||||
*
|
||||
* Generates candidates (https-first), probes them in parallel with a per-candidate
|
||||
* timeout, and returns the first candidate (in preference order) the probe
|
||||
* accepted. When none work, the most actionable failure is returned.
|
||||
*/
|
||||
export async function resolveServerUrl(
|
||||
input: string,
|
||||
probe: ServerProbe,
|
||||
options: ResolveOptions = {},
|
||||
): Promise<ResolveResult> {
|
||||
const { timeoutMs = 5000, signal } = options;
|
||||
|
||||
if (!input.trim()) return { ok: false, reason: "empty" };
|
||||
|
||||
const candidates = getServerUrlCandidates(input);
|
||||
if (candidates.length === 0) return { ok: false, reason: "invalid" };
|
||||
|
||||
const outcomes = await Promise.all(
|
||||
candidates.map((url) => runProbe(url, probe, timeoutMs, signal)),
|
||||
);
|
||||
|
||||
// Prefer the first candidate (https-first) that validated.
|
||||
for (let i = 0; i < candidates.length; i++) {
|
||||
const outcome = outcomes[i];
|
||||
if (outcome.status === "ok") {
|
||||
return { ok: true, url: candidates[i], meta: outcome.meta };
|
||||
}
|
||||
}
|
||||
|
||||
// Nothing validated: report the most useful failure.
|
||||
for (const reason of FAILURE_PRIORITY) {
|
||||
const hit = outcomes.find((outcome) => outcome.status === reason);
|
||||
if (hit) {
|
||||
return { ok: false, reason };
|
||||
}
|
||||
}
|
||||
return { ok: false, reason: "unreachable" };
|
||||
}
|
||||
|
||||
async function runProbe(
|
||||
url: string,
|
||||
probe: ServerProbe,
|
||||
timeoutMs: number,
|
||||
parentSignal?: AbortSignal,
|
||||
): Promise<ServerProbeOutcome> {
|
||||
const controller = new AbortController();
|
||||
const abort = () => controller.abort();
|
||||
parentSignal?.addEventListener("abort", abort);
|
||||
const timer = setTimeout(abort, timeoutMs);
|
||||
|
||||
try {
|
||||
return await probe(url, controller.signal);
|
||||
} catch {
|
||||
return { status: "unreachable" };
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
parentSignal?.removeEventListener("abort", abort);
|
||||
}
|
||||
}
|
||||
22
utils/serverUrl/semver.ts
Normal file
22
utils/serverUrl/semver.ts
Normal file
@@ -0,0 +1,22 @@
|
||||
/**
|
||||
* Strict numeric "below" comparison for dotted versions.
|
||||
*
|
||||
* Avoids the string-comparison bug (`"1.9.9" < "2.0.0"` works by luck but
|
||||
* `"2.10.0" < "2.0.0"` is wrongly true). Non-numeric/pre-release suffixes on a
|
||||
* segment are ignored (e.g. `2.0.0-beta` → 2.0.0).
|
||||
*/
|
||||
export function isVersionBelow(version: string, minimum: string): boolean {
|
||||
const parse = (v: string) =>
|
||||
v.split(".").map((segment) => Number.parseInt(segment, 10) || 0);
|
||||
|
||||
const a = parse(version);
|
||||
const b = parse(minimum);
|
||||
const length = Math.max(a.length, b.length);
|
||||
|
||||
for (let i = 0; i < length; i++) {
|
||||
const x = a[i] ?? 0;
|
||||
const y = b[i] ?? 0;
|
||||
if (x !== y) return x < y;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
15
utils/serverUrl/types.ts
Normal file
15
utils/serverUrl/types.ts
Normal file
@@ -0,0 +1,15 @@
|
||||
/** Result of probing a single candidate URL for a specific service. */
|
||||
export type ServerProbeOutcome =
|
||||
| { status: "ok"; meta?: Record<string, unknown> }
|
||||
| { status: "wrong-service" }
|
||||
| { status: "unreachable" };
|
||||
|
||||
/**
|
||||
* Validates one fully-qualified candidate URL for a given service.
|
||||
* Implementations must resolve (never reject) — map errors to "unreachable".
|
||||
* The provided signal is aborted on timeout or cancellation.
|
||||
*/
|
||||
export type ServerProbe = (
|
||||
url: string,
|
||||
signal: AbortSignal,
|
||||
) => Promise<ServerProbeOutcome>;
|
||||
Reference in New Issue
Block a user