media.webtorrent#

Description#

Plugin to download and stream videos using webtorrent.

media.webtorrent will use the default media player plugin you have configured (e.g. mplayer, omxplayer, mpv) to stream the torrent.

Configuration#

media.webtorrent:
  # [Optional]
  # Path to your webtorrent executable. If not set,
  # then Platypush will search for the right executable in your PATH
  # webtorrent_bin:

  # [Optional]
  # Port where the webtorrent will be running
  # streaming server will be running (default: 8000)
  # webtorrent_port:

  # [Optional]
  # Directories that will be scanned for media files when
  # a search is performed (default: none)
  # media_dirs:   # type=Optional[List[str]]

  # [Optional]
  # Directory where external resources/torrents will be
  # downloaded (default: ~/Downloads)
  # download_dir:   # type=Optional[str]

  # [Optional]
  # Environment variables key-values to pass to the
  # player executable (e.g. DISPLAY, XDG_VTNR, PULSE_SINK etc.)
  # env:   # type=Optional[Dict[str, str]]

  # [Optional]
  # Default volume for the player (default: None, maximum volume).
  # volume:   # type=Union[float, int, NoneType]

  # [Optional]
  # Optional plugin to be used for torrent download. Possible values:
  #
  # - ``torrent`` - native ``libtorrent``-based plugin (default, recommended)
  # - ``rtorrent`` - torrent support over rtorrent RPC/XML interface
  # - ``webtorrent`` - torrent support over webtorrent (unstable)
  # torrent_plugin: torrent  # type=str

  # [Optional]
  # Select the preferred video/audio format for
  # YouTube videos - and any media supported by youtube-dl or the
  # selected fork. See the `youtube-dl documentation
  # <https://github.com/ytdl-org/youtube-dl#format-selection>`_ for more
  # info on supported formats. Default:
  # ``bv*[height<=?1080][ext=mp4]+bestaudio/best`` - select the best
  # mp4 video with a resolution <= 1080p, and the best audio format.
  # youtube_format: bv[height<=?1080][ext=mp4]+ba  # type=Optional[str]

  # [Optional]
  # Path to the ``youtube-dl`` executable, used to
  # extract information from YouTube videos and other media platforms.
  # Default: ``yt-dlp``. The default has changed from ``youtube-dl`` to
  # the ``yt-dlp`` fork because the former is badly maintained and its
  # latest release was pushed in 2021.
  # youtube_dl: yt-dlp  # type=str

  # [Optional]
  # How often the `RunnablePlugin.loop <https://docs.platypush.tech/platypush/plugins/.html#platypush.plugins.RunnablePlugin.loop>`_ function should be
  # executed (default: 15 seconds). *NOTE*: For back-compatibility
  # reasons, the `poll_seconds` argument is also supported, but it's
  # deprecated.
  # poll_interval: 15  # type=Optional[float]

  # [Optional]
  # How long we should wait for any running
  # threads/processes to stop before exiting (default: 5 seconds).
  # stop_timeout: 5  # type=Optional[float]

  # [Optional]
  # If set to True then the plugin will not monitor
  # for new events. This is useful if you want to run a plugin in
  # stateless mode and only leverage its actions, without triggering any
  # events. Defaults to False.
  # disable_monitor: False  # type=bool

Actions#

Module reference#

class platypush.plugins.media.webtorrent.MediaWebtorrentPlugin(webtorrent_bin=None, webtorrent_port=None, *args, **kwargs)[source]#

Bases: MediaPlugin

Plugin to download and stream videos using webtorrent.

__init__(webtorrent_bin=None, webtorrent_port=None, *args, **kwargs)[source]#

media.webtorrent will use the default media player plugin you have configured (e.g. mplayer, omxplayer, mpv) to stream the torrent.

Parameters:
  • webtorrent_bin (str) – Path to your webtorrent executable. If not set, then Platypush will search for the right executable in your PATH

  • webtorrent_port (int) – Port where the webtorrent will be running streaming server will be running (default: 8000)

cancel_download(url: str | None = None, path: str | None = None)#

Cancel a download in progress.

Either the URL or the path must be specified.

Parameters:
  • url – URL of the download.

  • path – Path of the download (default: any path associated with the URL).

clear_downloads(url: str | None = None, path: str | None = None)#

Clear completed/cancelled downloads from the queue.

Parameters:
  • url – URL of the download (default: all downloads).

  • path – Path of the download (default: any path associated with the URL).

download(resource, **kwargs)[source]#

Download a media URL to a local file on the Platypush host (yt-dlp required for YouTube URLs).

This action is non-blocking and returns the path to the downloaded file once the download is initiated.

You can then subscribe to these events to monitor the download progress:

Parameters:
  • url – Media URL.

  • filename – Media filename (default: inferred from the URL basename).

  • directory – Destination directory (default: download_dir).

  • timeout – Network timeout in seconds (default: 10).

  • sync – If set to True, the download will be synchronous and the action will return only when the download is completed.

  • youtube_format – Override the default youtube_format setting.

Returns:

The absolute path to the downloaded file.

get_downloads(url: str | None = None, path: str | None = None)#

Get the download threads.

Parameters:
  • url – URL of the download (default: all downloads).

  • path – Path of the download (default: any path associated with the URL).

Returns:

[
  {
    "ended_at": "2024-07-16T18:25:27.204236+00:00",
    "path": "/path/to/download/video.mp4",
    "size": 1024,
    "started_at": "2024-07-16T18:25:27.204210+00:00",
    "state": "Download state",
    "timeout": 60,
    "url": "https://example.com/video.mp4"
  }
]

get_media_file_duration(filename)#

Get the duration of a media file in seconds. Requires ffmpeg

load(resource, **kwargs)[source]#

Load a torrent resource in the player.

main()#

Implementation of the main loop of the plugin.

next()#

Play the next item in the queue

pause_download(url: str | None = None, path: str | None = None)#

Pause a download in progress.

Either the URL or the path must be specified.

Parameters:
  • url – URL of the download.

  • path – Path of the download (default: any path associated with the URL).

play(resource, player=None, download_only=False, **player_args)[source]#

Download and stream a torrent

Parameters:
  • resource (str) – Play a resource, as a magnet link, torrent URL or torrent file path

  • player (str) – If set, use this plugin type as a player for the torrent. Supported types: ‘mplayer’, ‘vlc’, ‘omxplayer’, ‘chromecast’, ‘mpv’. If not set, then the default configured media plugin will be used.

  • player_args (dict) – Any arguments to pass to the player plugin’s play() method

  • download_only (bool) – If false then it will start streaming the torrent on the local player once the download starts, otherwise it will just download it (default: false)

quit()[source]#

Quit the player

resume_download(url: str | None = None, path: str | None = None)#

Resume a paused download.

Either the URL or the path must be specified.

Parameters:
  • url – URL of the download.

  • path – Path of the download (default: any path associated with the URL).

search(query: str, types: Iterable[str] | None = None, queue_results: bool = False, autoplay: bool = False, timeout: float = 60)#

Perform a video search.

Parameters:
  • query – Query string, video name or partial name

  • types – Video types to search (default: ["youtube", "file", "torrent"])

  • queue_results – Append the results to the current playing queue (default: False)

  • autoplay – Play the first result of the search (default: False)

  • timeout – Search timeout (default: 60 seconds)

start()#

Start the plugin.

start_streaming(media: str, subtitles: str | None = None, download: bool = False)#

Starts streaming local media over the specified HTTP port. The stream will be available to HTTP clients on http://{this-ip}:{http_backend_port}/media/<media_id>

Parameters:
  • media – Media to stream

  • subtitles – Path or URL to the subtitles track to be used

  • download – Set to True if you prefer to download the file from the streaming link instead of streaming it

Returns:

dict containing the streaming URL.Example:

{
    "id": "0123456abcdef.mp4",
    "source": "file:///mnt/media/movies/movie.mp4",
    "mime_type": "video/mp4",
    "url": "http://192.168.1.2:8008/media/0123456abcdef.mp4"
}
status()[source]#

Get the current player state.

Returns:

A dictionary containing the current state.

Example:

output = {
    "state": "play"  # or "stop" or "pause"
}
stop()[source]#

Stop the playback

wait_stop(timeout=None)#

Wait until a stop event is received.

class platypush.plugins.media.webtorrent.TorrentState(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)[source]#

Bases: IntEnum

__init__(*args, **kwds)#
as_integer_ratio()#

Return a pair of integers, whose ratio is equal to the original int.

The ratio is in lowest terms and has a positive denominator.

>>> (10).as_integer_ratio()
(10, 1)
>>> (-10).as_integer_ratio()
(-10, 1)
>>> (0).as_integer_ratio()
(0, 1)
bit_count()#

Number of ones in the binary representation of the absolute value of self.

Also known as the population count.

>>> bin(13)
'0b1101'
>>> (13).bit_count()
3
bit_length()#

Number of bits necessary to represent self in binary.

>>> bin(37)
'0b100101'
>>> (37).bit_length()
6
conjugate()#

Returns self, the complex conjugate of any int.

denominator#

the denominator of a rational number in lowest terms

from_bytes(byteorder='big', *, signed=False)#

Return the integer represented by the given array of bytes.

bytes

Holds the array of bytes to convert. The argument must either support the buffer protocol or be an iterable object producing bytes. Bytes and bytearray are examples of built-in objects that support the buffer protocol.

byteorder

The byte order used to represent the integer. If byteorder is ‘big’, the most significant byte is at the beginning of the byte array. If byteorder is ‘little’, the most significant byte is at the end of the byte array. To request the native byte order of the host system, use `sys.byteorder’ as the byte order value. Default is to use ‘big’.

signed

Indicates whether two’s complement is used to represent the integer.

imag#

the imaginary part of a complex number

is_integer()#

Returns True. Exists for duck type compatibility with float.is_integer.

numerator#

the numerator of a rational number in lowest terms

real#

the real part of a complex number

to_bytes(length=1, byteorder='big', *, signed=False)#

Return an array of bytes representing an integer.

length

Length of bytes object to use. An OverflowError is raised if the integer is not representable with the given number of bytes. Default is length 1.

byteorder

The byte order used to represent the integer. If byteorder is ‘big’, the most significant byte is at the beginning of the byte array. If byteorder is ‘little’, the most significant byte is at the end of the byte array. To request the native byte order of the host system, use `sys.byteorder’ as the byte order value. Default is to use ‘big’.

signed

Determines whether two’s complement is used to represent the integer. If signed is False and a negative integer is given, an OverflowError is raised.