Webtor.io Embed SDK for JavaScript

repository·master·Indexed 19 days ago

https://github.com/webtor-io/embed-sdk-js

A lightweight JavaScript library for embedding torrent streaming players and download functionality into websites using magnet URIs or torrent files. It supports custom video formats, subtitles, and self-hosted Webtor instances. The SDK provides automatic detection of HTML <video> and <a> elements, a configuration queue via window.webtor, and a Player API for programmatic control of playback and event handling.

Tokens
3.2K
Snippets
7
Records
12
Agent score
64%

What's inside @webtor/embed-sdk-js

  1. Using a self-hosted Webtor instance

    master

    If you are running your own Webtor instance, you can use the SDK by setting the baseUrl configuration attribute to your instance's URL.

    // Example configuration for a self-hosted instance
    window.webtor.push({
        id: 'player',
        magnet: '...', 
        baseUrl: 'https://your-webtor-instance.com'
    });
  2. Advanced usage via window.webtor queue

    master

    For more complex configurations, you can use the window.webtor array pattern. This allows you to define the player configuration in a script block before the SDK is loaded. This method is useful for passing complex objects like subtitle arrays or specific player settings.

    1. Create a container element (e.g., a <div>) with a specific id and the class webtor.
    2. Push a configuration object to window.webtor.
    3. Load the SDK script.
    <div id="player" class="webtor" />
    <script>
        window.webtor = window.webtor || [];
        window.webtor.push({
            id: 'player',
            magnet: 'magnet:?xt=urn:btih:08ada5a7a6183aae1e09d831df6748d566095a10&dn=Sintel&tr=udp%3A%2F%2Fexplodie.org%3A6969&tr=udp%3A%2F%2Ftracker.coppersurfer.tk%3A6969&tr=udp%3A%2F%2Ftracker.empire-js.us%3A1337&tr=udp%3A%2F%2Ftracker.leechers-paradise.org%3A6969&tr=udp%3A%2F%2Ftracker.opentrackr.org%3A1337&tr=wss%3A%2F%2Ftracker.btorrent.xyz&tr=wss%3A%2F%2Ftracker.fastcast.nz&tr=wss%3A%2F%2Ftracker.openwebtorrent.com&ws=https%3A%2F%2Fwebtorrent.io%2Ftorrents%2F',
            poster: 'https://via.placeholder.com/150/0000FF/808080',
            subtitles: [
                {
                    srclang: 'en',
                    label: 'test',
                    src: 'https://raw.githubusercontent.com/andreyvit/subtitle-tools/master/sample.srt',
                    default: true,
                }
            ],
            lang: 'en',
        });
    </script>
    <script src="https://cdn.jsdelivr.net/npm/@webtor/embed-sdk-js/dist/index.min.js" charset="utf-8" async></script>
  3. Basic usage via HTML video element

    master

    You can embed the Webtor player by using a standard HTML <video> element. The SDK will automatically detect the element and replace it with a player wrapper.

    To use this method, include a <video> tag with a src pointing to a magnet URI or a torrent file URL, and load the SDK script via CDN.

    Note: When using a torrent file URL that does not have a .torrent extension, you must set the type attribute to application/x-bittorrent.

    <video controls src="magnet:?xt=urn:btih:08ada5a7a6183aae1e09d831df6748d566095a10&dn=Sintel"></video>
    <script src="https://cdn.jsdelivr.net/npm/@webtor/embed-sdk-js/dist/index.min.js" charset="utf-8" async></script>
  4. Initialize the Webtor player embed

    master

    To embed a Webtor player, call the default export of the SDK with a configuration object. You must provide either a magnet link or a torrentUrl. You must also specify a target element via id (the ID of an existing DOM element) or by passing the element itself via the el property.

    Common configuration options include:

    • baseUrl: The Webtor instance URL (defaults to https://webtor.io).
    • width: The width of the iframe (e.g., '800px').
    • height: The height of the iframe. If not provided, the SDK uses an iframe resizer.
    • mode: The embed mode (defaults to 'video').
    • subtitles: An array of subtitle configurations.
    • poster: URL for the video poster image.
    • header: Boolean to show/hide the header (defaults to true).
    • title: The title to display.
    • imdbId: IMDB ID for the content.
    • path: The path to the file within the torrent.
    • on: A callback function that receives event data from the player.
    import webtor from '@webtor/embed-sdk-js';
    
    webtor({
      id: 'player-container',
      magnet: 'magnet:?xt=urn:btih:...
      width: '100%',
      height: '500px',
      on: (event) => {
        console.log('Player event:', event.name, event.data);
      }
    });
  5. Initialize the Webtor player on video elements

    master

    The SDK automatically scans the document for <video> elements and <a> tags with a download attribute to transform them into Webtor players.

    Automatic Detection

    1. <video> elements: The SDK looks for src or href attributes containing magnet links (magnet:.*) or .torrent files. It also respects the data-torrent attribute for specifying torrent sources.
    2. <a> elements: Links with the download attribute are converted into download-mode players.

    Configuration via Data Attributes

    You can configure the player directly on the HTML element using data-* attributes. These attributes are automatically parsed and passed to the player. For example:

    • data-width: Sets the player width.
    • data-height: Sets the player height.
    • data-poster: Sets the video poster image.
    • data-controls: Enables/disables controls.
    • data-torrent: Explicitly provides a .torrent URL.
    • data-config: A JSON string used to pass complex configuration objects.

    Subtitles

    Subtitles are automatically extracted from <track> elements inside the <video> tag. The SDK collects srclang, label, default, and src attributes and includes them in the player configuration.

    <!-- Example: Video with magnet link and custom config -->
    <video 
      src="magnet:?xt=urn:btih:..." 
      width="800" 
      height="450" 
      data-controls="true"
      data-config='{"someOption": true}'>
      <track srclang="en" label="English" src="subs_en.vtt" default>
    </video>
    
    <!-- Example: Download link converted to player -->
    <a href="https://example.com/file.torrent" download>Download Torrent</a>
  6. Configure the player using the data-config attribute

    master

    For advanced configuration that cannot be easily represented by simple data-* attributes, use the data-config attribute on your <video> or <a> element. The value must be a valid JSON string. This configuration is merged with other attributes and global initialization options.

    <video 
      src="magnet:?xt=urn:btih:..." 
      data-config='{"mode": "stream", "playerOptions": {"autoplay": true}}'>
    </video>
  7. Embed configuration options

    master

    When using the advanced window.webtor.push method or the data-* attributes on a video element, you can configure the player using the following keys:

    AttributeDescription
    idElement id where player will be embedded
    magnetMagnet URI
    torrentUrlUrl of the torrent-file (HTTP-server MUST include header Access-Control-Allow-Origin: *)
    widthWidth of an iframe (CSS value, default: 800px)
    heightHeight of an iframe (CSS value, optional)
    posterUrl to the poster image (optional)
    onCallback-function to capture player events (optional)
    subtitlesArray of subtitle objects (see Subtitle configuration)
    titleReplaces original file name in a header with specific title
    imdbIdHelps find subtitles/metadata (e.g., 'tt0133093')
    headerShows header with progress and title (boolean, default: true)
    pwdSelected directory in torrent
    fileSelected file in torrent (defaults to first video file)
    pathFull file path in torrent (use instead of pwd and file)
    langOverride UI language
    userLangOverride user language
    controlsEnables/disables all features (boolean, default: true)
    featuresEnables/disables specific player features
    baseUrlUrl of Webtor instance (default: https://webtor.io)
  8. Player features

    master

    You can enable or disable specific player features using the features configuration key. Available features include:

    • subtitles: Subtitles control
    • settings: Settings control (cog icon)
    • fullscreen: Fullscreen control
    • playpause: Play/pause control
    • currentTime: Displays current time
    • timeline: Timeline control
    • duration: Displays total duration
    • volume: Volume control
    • chromecast: Chromecast support
    • embed: Embed button
    • opensubtitles: OpenSubtitles support
  9. Subtitle configuration

    master

    Subtitles are configured as an array of objects passed to the subtitles key. Each object defines a track:

    AttributeDescription
    srclangTwo-letter language code
    labelSubtitle label
    srcDirect link to the subtitle (vtt, srt, or m3u8)
    defaultIf true, this track is selected by default (boolean, optional)
  10. Control the player using the Player API

    master

    When an event is received via the on callback, the event object includes a player instance. This instance allows you to programmatically control the video playback using the following methods:

    • play(): Starts playback.
    • pause(): Pauses playback.
    • setPosition(val): Sets the playback position to the specified value.
    • open(val): Opens a specific path within the torrent.

    Example of using the player instance from an event:

    webtor({
      id: 'player-container',
      magnet: 'magnet:?xt=urn:btih:...',
      on: (event) => {
        if (event.name === 'init') {
          // Use the player instance to pause immediately on init
          event.player.pause();
        }
      }
    });
    // Inside the 'on' callback
    player.play();
    player.pause();
    player.setPosition(120);
    player.open('/path/to/video.mp4');
  11. Initialize Webtor manually via makeEmbeds

    master

    While the SDK performs automatic initialization on page load, you can manually trigger the embedding process for specific elements using the internal logic (exposed via the SDK's initialization).

    When calling the embedding logic, you can pass an init object to set global defaults. For example, when targeting download links, you can specify a default mode and width:

    // This is how the SDK internally handles download links
    makeEmbeds(document.querySelectorAll('a[download]'), { mode: 'download', width: '400px' });
  12. Reference the Webtor event names

    master

    The SDK communicates player state and user interactions through specific event names. These are used within the on callback to identify what happened inside the iframe.

    Event NameDescription
    initThe player has been initialized
    initedThe player is fully ready
    torrent fetchedThe torrent metadata has been successfully retrieved
    torrent errorAn error occurred while fetching the torrent
    play_clickedThe user clicked the play button
    openA request to open a specific file/path
    injectAn injection command was received
    player statusChanges in player state
    current timeThe current playback time has changed
    durationThe total duration of the media has been determined
    open subtitlesA request to open specific subtitles