usePlayUrl Hook in Stremio Web: Handling Direct URLs and Magnet Links
The usePlayUrl hook is a custom React hook that centralizes the logic for validating user-provided URLs and magnet links, then launching them in Stremio Web's streaming player.
In the Stremio Web React application (Stremio/stremio-web), the usePlayUrl hook serves as the primary interface for handling direct media inputs. Located at src/common/usePlayUrl.ts, this hook encapsulates validation, toast notifications, and core communication required to transform raw text strings into playable streams.
How usePlayUrl Processes Input Streams
The hook returns an object containing handlePlayUrl, an async function that accepts a string and returns a boolean indicating whether a playable stream was successfully launched. This function discriminates between HTTP URLs and magnet links using protocol-specific validation logic implemented in the source file.
HTTP Stream Handling
When the input matches the internal HTTP_REGEX pattern (detecting http:// or https://), the hook executes a three-step pipeline:
- User Feedback: Displays a "Loading HTTP stream..." toast notification via the
useToastdependency. - Stream Registration: Calls
core.transport.encodeStream(url)to register the URL with the Stremio core transport layer. - Navigation: Updates
window.location.hashto#/player/<encoded-url>, triggering the player view route.
If encodeStream throws an exception, the hook catches the error and displays an error toast instead. This logic is implemented in lines 20-35 of src/common/usePlayUrl.ts.
Magnet Link Processing
For inputs parseable as magnet URIs (validated via magnet.decode), the hook enforces streaming server prerequisites:
- Server State Check: Verifies that
streamingServer.settings.type === 'Ready'using theuseStreamingServerhook. If the server is not ready, it immediately shows an error toast and returnsfalse. - Torrent Creation: When the server is ready, invokes
createTorrentFromMagnet(trimmed)to initiate the download. - Return Value: Returns
trueto indicate the torrent creation was triggered successfully.
This magnet link pathway appears in lines 47-60 of the source file.
Integration Examples in Stremio Web Components
The usePlayUrl hook is consumed by multiple UI components that accept external media links, demonstrating its utility across different input contexts.
Search Bar Implementation
The SearchBar component (src/components/NavBar/HorizontalNavBar/SearchBar/SearchBar.js) uses the hook to play URLs entered directly into the search field:
import usePlayUrl from 'stremio/common/usePlayUrl';
import { useState } from 'react';
const SearchBar = () => {
const { handlePlayUrl } = usePlayUrl();
const [input, setInput] = useState('');
const onSubmit = async () => {
const success = await handlePlayUrl(input);
if (success) {
setInput('');
}
};
return (
<input
value={input}
onChange={(e) => setInput(e.target.value)}
onKeyPress={(e) => e.key === 'Enter' && onSubmit()}
/>
);
};
Clipboard Paste Handling
The NavMenuContent component (src/components/NavBar/HorizontalNavBar/NavMenu/NavMenuContent.js) demonstrates handling clipboard paste events:
import usePlayUrl from 'stremio/common/usePlayUrl';
const NavMenuContent = () => {
const { handlePlayUrl } = usePlayUrl();
const onPaste = async (clipboardText: string) => {
const handled = await handlePlayUrl(clipboardText);
if (handled) {
// Close menu or update UI state
}
};
return (
<div onPaste={(e) => onPaste(e.clipboardData.getData('Text'))}>
{/* Menu content */}
</div>
);
};
Dependencies and Error Handling
The hook relies on two critical Stremio Web utilities:
useToast: Provides the toast notification system for "Loading HTTP stream..." and error messages.useStreamingServer: Supplies the streaming server state that the hook checks before attempting to handle magnet links.
All errors generated during stream encoding or torrent creation are caught and surfaced to the user via toast notifications, ensuring the UI never crashes from malformed URLs or unavailable servers.
Summary
usePlayUrlis located atsrc/common/usePlayUrl.tsand exports thehandlePlayUrlfunction for processing external media links.- HTTP URLs are encoded via
core.transport.encodeStreamand routed to#/player/<encoded-url>. - Magnet links require the streaming server to be in a
Readystate before invokingcreateTorrentFromMagnet. - The hook is consumed by
SearchBarandNavMenuContentcomponents to enable direct URL playback from user input or clipboard pastes. - Boolean return values allow calling components to react to success or failure states.
Frequently Asked Questions
What does the usePlayUrl hook return?
The hook returns an object containing a single async function, handlePlayUrl(url: string): Promise<boolean>. This function returns true if the input was successfully identified as either an HTTP stream or magnet link and the appropriate playback sequence was initiated, or false if validation failed or the streaming server was unavailable.
How does usePlayUrl validate magnet links?
The hook uses magnet.decode to verify the input string represents a valid magnet URI. It then checks the streamingServer.settings.type property via the useStreamingServer hook to ensure the value equals 'Ready' before calling createTorrentFromMagnet. If the server is not ready, it displays an error toast and returns false.
What happens when usePlayUrl receives an HTTP URL?
When the input matches the HTTP_REGEX (detecting http:// or https://), the hook displays a loading toast, calls core.transport.encodeStream(url) to register with the Stremio core, and updates the window hash to #/player/<encoded-url>. This hash change triggers the React Router player view to mount and begin streaming.
Where is the usePlayUrl hook used in the Stremio Web interface?
According to the source code analysis, usePlayUrl is imported and utilized in src/components/NavBar/HorizontalNavBar/SearchBar/SearchBar.js for handling search bar inputs, and in src/components/NavBar/HorizontalNavBar/NavMenu/NavMenuContent.js for processing clipboard paste events in the navigation menu.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →