rayohx 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (127) hide show
  1. rayohx/__init__.py +200 -0
  2. rayohx/_crypto/__init__.py +51 -0
  3. rayohx/_crypto/_cipher.py +55 -0
  4. rayohx/_crypto/_keys.py +128 -0
  5. rayohx/_crypto/_support.py +32 -0
  6. rayohx/_download/__init__.py +48 -0
  7. rayohx/_download/_containers/__init__.py +58 -0
  8. rayohx/_download/_containers/_files.py +123 -0
  9. rayohx/_download/_containers/_formats.py +17 -0
  10. rayohx/_download/_containers/_segments.py +27 -0
  11. rayohx/_download/_containers/_sniff.py +26 -0
  12. rayohx/_download/_fetcher.py +99 -0
  13. rayohx/_download/_media.py +345 -0
  14. rayohx/_download/_output/__init__.py +55 -0
  15. rayohx/_download/_output/_names.py +60 -0
  16. rayohx/_download/_output/_plan.py +144 -0
  17. rayohx/_download/_pipeline.py +302 -0
  18. rayohx/_download/_progress.py +95 -0
  19. rayohx/_download/_sinks.py +316 -0
  20. rayohx/_download/_state.py +121 -0
  21. rayohx/_download/_storage/__init__.py +105 -0
  22. rayohx/_download/_storage/_common.py +15 -0
  23. rayohx/_download/_storage/_metrics.py +69 -0
  24. rayohx/_download/_storage/_space.py +171 -0
  25. rayohx/_download/_storage/_stores.py +214 -0
  26. rayohx/_download/_storage/_strategy.py +37 -0
  27. rayohx/_download/_workspace.py +186 -0
  28. rayohx/_http/__init__.py +36 -0
  29. rayohx/_http/_client.py +279 -0
  30. rayohx/_http/_common.py +171 -0
  31. rayohx/_http/_credentials.py +59 -0
  32. rayohx/_http/_response.py +124 -0
  33. rayohx/_http/_stream.py +107 -0
  34. rayohx/_http/_transport.py +70 -0
  35. rayohx/_logs.py +62 -0
  36. rayohx/_mux/__init__.py +6 -0
  37. rayohx/_mux/_aac.py +135 -0
  38. rayohx/_mux/_ac3.py +234 -0
  39. rayohx/_mux/_bits.py +73 -0
  40. rayohx/_mux/_boxes.py +40 -0
  41. rayohx/_mux/_ffmpeg.py +127 -0
  42. rayohx/_mux/_fmp4.py +149 -0
  43. rayohx/_mux/_fmp4_source.py +286 -0
  44. rayohx/_mux/_fragmenter.py +100 -0
  45. rayohx/_mux/_h264.py +218 -0
  46. rayohx/_mux/_hevc.py +163 -0
  47. rayohx/_mux/_model.py +33 -0
  48. rayohx/_mux/_mp3.py +90 -0
  49. rayohx/_mux/_mp4read.py +52 -0
  50. rayohx/_mux/_muxer.py +269 -0
  51. rayohx/_mux/_sink.py +252 -0
  52. rayohx/_mux/_source.py +324 -0
  53. rayohx/_mux/_ts.py +285 -0
  54. rayohx/_mux/_webvtt.py +150 -0
  55. rayohx/_ratelimit.py +64 -0
  56. rayohx/_redaction.py +84 -0
  57. rayohx/cancellation.py +55 -0
  58. rayohx/config/__init__.py +57 -0
  59. rayohx/config/_common.py +29 -0
  60. rayohx/config/download.py +82 -0
  61. rayohx/config/network.py +131 -0
  62. rayohx/config/output.py +52 -0
  63. rayohx/config/proxy.py +66 -0
  64. rayohx/config/selection.py +163 -0
  65. rayohx/config/storage.py +56 -0
  66. rayohx/config/url.py +23 -0
  67. rayohx/downloader/__init__.py +52 -0
  68. rayohx/downloader/_delivery.py +307 -0
  69. rayohx/downloader/_prepare.py +129 -0
  70. rayohx/downloader/_result.py +27 -0
  71. rayohx/downloader/_stream.py +99 -0
  72. rayohx/downloader/batch.py +119 -0
  73. rayohx/downloader/controller.py +358 -0
  74. rayohx/downloader/shortcut.py +96 -0
  75. rayohx/enums.py +96 -0
  76. rayohx/errors.py +193 -0
  77. rayohx/events/__init__.py +49 -0
  78. rayohx/events/bus.py +46 -0
  79. rayohx/events/download.py +88 -0
  80. rayohx/logs.py +66 -0
  81. rayohx/models/__init__.py +108 -0
  82. rayohx/models/download/__init__.py +50 -0
  83. rayohx/models/download/output.py +20 -0
  84. rayohx/models/download/progress.py +43 -0
  85. rayohx/models/download/request.py +38 -0
  86. rayohx/models/download/result.py +45 -0
  87. rayohx/models/download/storage.py +17 -0
  88. rayohx/models/download/workspace.py +22 -0
  89. rayohx/models/playlist/__init__.py +61 -0
  90. rayohx/models/playlist/master.py +44 -0
  91. rayohx/models/playlist/media.py +45 -0
  92. rayohx/models/playlist/resolution.py +46 -0
  93. rayohx/models/playlist/tracks/__init__.py +41 -0
  94. rayohx/models/playlist/tracks/audio.py +20 -0
  95. rayohx/models/playlist/tracks/subtitle.py +19 -0
  96. rayohx/models/playlist/tracks/video.py +16 -0
  97. rayohx/models/playlist/variant.py +36 -0
  98. rayohx/models/segment/__init__.py +47 -0
  99. rayohx/models/segment/data.py +17 -0
  100. rayohx/models/segment/encryption.py +54 -0
  101. rayohx/models/segment/init_map.py +17 -0
  102. rayohx/models/segment/range.py +51 -0
  103. rayohx/models/segment/segment.py +35 -0
  104. rayohx/playlist/__init__.py +57 -0
  105. rayohx/playlist/_keys.py +67 -0
  106. rayohx/playlist/_lines.py +29 -0
  107. rayohx/playlist/_master.py +142 -0
  108. rayohx/playlist/_media.py +157 -0
  109. rayohx/playlist/_values.py +122 -0
  110. rayohx/playlist/_variables.py +104 -0
  111. rayohx/playlist/attributes.py +61 -0
  112. rayohx/playlist/detect.py +8 -0
  113. rayohx/playlist/inspection.py +79 -0
  114. rayohx/playlist/parser.py +71 -0
  115. rayohx/py.typed +0 -0
  116. rayohx/serialization.py +163 -0
  117. rayohx/stream/__init__.py +52 -0
  118. rayohx/stream/_ranking.py +77 -0
  119. rayohx/stream/_tracks.py +113 -0
  120. rayohx/stream/quality.py +15 -0
  121. rayohx/stream/selection.py +51 -0
  122. rayohx/stream/variants.py +141 -0
  123. rayohx/workspaces.py +81 -0
  124. rayohx-0.1.0.dist-info/METADATA +102 -0
  125. rayohx-0.1.0.dist-info/RECORD +127 -0
  126. rayohx-0.1.0.dist-info/WHEEL +4 -0
  127. rayohx-0.1.0.dist-info/licenses/LICENSE +201 -0
rayohx/__init__.py ADDED
@@ -0,0 +1,200 @@
1
+ """RayoHX: an HLS download engine. Front ends (command line, API, window) all use this package.
2
+
3
+ The names below are imported the first time they are used, so ``import rayohx`` stays fast and a
4
+ front end loads only the parts it needs.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import logging
10
+ from importlib import import_module
11
+ from typing import TYPE_CHECKING, Any
12
+
13
+ __version__ = "0.1.0"
14
+
15
+ # A library must stay quiet until the application asks for logs.
16
+ logging.getLogger("rayohx").addHandler(logging.NullHandler())
17
+
18
+ if TYPE_CHECKING:
19
+ from rayohx.cancellation import CancellationToken
20
+ from rayohx.downloader import BatchItem, Downloader, batch_outputs, download, download_many
21
+ from rayohx.enums import (
22
+ ContainerFormat,
23
+ DownloadState,
24
+ EncryptionMethod,
25
+ EventType,
26
+ OutputFormat,
27
+ RemuxBackend,
28
+ SegmentState,
29
+ StorageStrategy,
30
+ )
31
+ from rayohx.logs import (
32
+ configure_logging,
33
+ )
34
+ from rayohx.models import (
35
+ AudioTrack,
36
+ DownloadProgress,
37
+ DownloadRequest,
38
+ DownloadResult,
39
+ EncryptionInfo,
40
+ InitMap,
41
+ LeftoverWorkspace,
42
+ MasterPlaylist,
43
+ MediaPlaylist,
44
+ OutputInfo,
45
+ Playlist,
46
+ Resolution,
47
+ Segment,
48
+ SegmentData,
49
+ SegmentRange,
50
+ StorageMetrics,
51
+ SubtitleTrack,
52
+ Variant,
53
+ VideoTrack,
54
+ )
55
+ from rayohx.playlist import (
56
+ PlaylistFetcher,
57
+ inspect_playlist,
58
+ inspect_text,
59
+ is_hls_playlist,
60
+ parse_playlist,
61
+ )
62
+ from rayohx.playlist.inspection import inspect
63
+ from rayohx.serialization import (
64
+ playlist_to_dict,
65
+ progress_to_dict,
66
+ result_to_dict,
67
+ )
68
+ from rayohx.stream import StreamSelection, select_stream
69
+ from rayohx.workspaces import find_workspaces, remove_workspaces
70
+
71
+ _SUBMODULES = frozenset(
72
+ {
73
+ "cancellation",
74
+ "config",
75
+ "errors",
76
+ "events",
77
+ "models",
78
+ "playlist",
79
+ "stream",
80
+ }
81
+ )
82
+ _EXPORTS = {
83
+ "AudioTrack": "rayohx.models",
84
+ "CancellationToken": "rayohx.cancellation",
85
+ "ContainerFormat": "rayohx.enums",
86
+ "DownloadProgress": "rayohx.models",
87
+ "DownloadRequest": "rayohx.models",
88
+ "DownloadResult": "rayohx.models",
89
+ "DownloadState": "rayohx.enums",
90
+ "BatchItem": "rayohx.downloader",
91
+ "batch_outputs": "rayohx.downloader",
92
+ "Downloader": "rayohx.downloader",
93
+ "EncryptionInfo": "rayohx.models",
94
+ "EncryptionMethod": "rayohx.enums",
95
+ "EventType": "rayohx.enums",
96
+ "InitMap": "rayohx.models",
97
+ "LeftoverWorkspace": "rayohx.models",
98
+ "MasterPlaylist": "rayohx.models",
99
+ "MediaPlaylist": "rayohx.models",
100
+ "OutputFormat": "rayohx.enums",
101
+ "OutputInfo": "rayohx.models",
102
+ "Playlist": "rayohx.models",
103
+ "PlaylistFetcher": "rayohx.playlist",
104
+ "RemuxBackend": "rayohx.enums",
105
+ "Resolution": "rayohx.models",
106
+ "Segment": "rayohx.models",
107
+ "SegmentData": "rayohx.models",
108
+ "SegmentRange": "rayohx.models",
109
+ "SegmentState": "rayohx.enums",
110
+ "StorageMetrics": "rayohx.models",
111
+ "StorageStrategy": "rayohx.enums",
112
+ "StreamSelection": "rayohx.stream",
113
+ "SubtitleTrack": "rayohx.models",
114
+ "Variant": "rayohx.models",
115
+ "VideoTrack": "rayohx.models",
116
+ "configure_logging": "rayohx.logs",
117
+ "download": "rayohx.downloader",
118
+ "download_many": "rayohx.downloader",
119
+ "find_workspaces": "rayohx.workspaces",
120
+ "inspect": "rayohx.playlist.inspection",
121
+ "inspect_playlist": "rayohx.playlist",
122
+ "inspect_text": "rayohx.playlist",
123
+ "is_hls_playlist": "rayohx.playlist",
124
+ "parse_playlist": "rayohx.playlist",
125
+ "playlist_to_dict": "rayohx.serialization",
126
+ "progress_to_dict": "rayohx.serialization",
127
+ "remove_workspaces": "rayohx.workspaces",
128
+ "result_to_dict": "rayohx.serialization",
129
+ "select_stream": "rayohx.stream",
130
+ }
131
+
132
+
133
+ def __getattr__(name: str) -> Any:
134
+ """Import a public name the first time it is used."""
135
+ if name in _SUBMODULES:
136
+ value = import_module(f"{__name__}.{name}")
137
+ globals()[name] = value
138
+ return value
139
+ module = _EXPORTS.get(name)
140
+ if module is None:
141
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
142
+ value = getattr(import_module(module), name)
143
+ globals()[name] = value
144
+ return value
145
+
146
+
147
+ def __dir__() -> list[str]:
148
+ return sorted({*globals(), *_EXPORTS, *_SUBMODULES})
149
+
150
+
151
+ __all__ = [
152
+ "AudioTrack",
153
+ "BatchItem",
154
+ "CancellationToken",
155
+ "ContainerFormat",
156
+ "DownloadProgress",
157
+ "DownloadRequest",
158
+ "DownloadResult",
159
+ "DownloadState",
160
+ "Downloader",
161
+ "EncryptionInfo",
162
+ "EncryptionMethod",
163
+ "EventType",
164
+ "InitMap",
165
+ "LeftoverWorkspace",
166
+ "MasterPlaylist",
167
+ "MediaPlaylist",
168
+ "OutputFormat",
169
+ "OutputInfo",
170
+ "Playlist",
171
+ "PlaylistFetcher",
172
+ "RemuxBackend",
173
+ "Resolution",
174
+ "Segment",
175
+ "SegmentData",
176
+ "SegmentRange",
177
+ "SegmentState",
178
+ "StorageMetrics",
179
+ "StorageStrategy",
180
+ "StreamSelection",
181
+ "SubtitleTrack",
182
+ "Variant",
183
+ "VideoTrack",
184
+ "__version__",
185
+ "batch_outputs",
186
+ "configure_logging",
187
+ "download",
188
+ "download_many",
189
+ "find_workspaces",
190
+ "inspect",
191
+ "inspect_playlist",
192
+ "inspect_text",
193
+ "is_hls_playlist",
194
+ "parse_playlist",
195
+ "playlist_to_dict",
196
+ "progress_to_dict",
197
+ "remove_workspaces",
198
+ "result_to_dict",
199
+ "select_stream",
200
+ ]
@@ -0,0 +1,51 @@
1
+ """HLS AES-128 segment decryption and key retrieval, internal to the engine.
2
+
3
+ Only ``METHOD=AES-128`` with the standard key format is handled. SAMPLE-AES and DRM key formats
4
+ are refused up front by ``require_supported_encryption``. Keys are fetched through the HTTP layer,
5
+ so the configured headers and cookies apply (to the key server's host only if it is trusted for
6
+ credentials).
7
+
8
+ The names below are imported the first time they are used, so loading this package does not load
9
+ ``cryptography`` or the HTTP layer until they are needed.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from importlib import import_module
15
+ from typing import TYPE_CHECKING, Any
16
+
17
+ if TYPE_CHECKING:
18
+ from rayohx._crypto._cipher import decrypt_aes128, decrypt_segment, derive_iv
19
+ from rayohx._crypto._keys import KeyProvider
20
+ from rayohx._crypto._support import require_supported_encryption
21
+
22
+ _EXPORTS = {
23
+ "KeyProvider": "rayohx._crypto._keys",
24
+ "decrypt_aes128": "rayohx._crypto._cipher",
25
+ "decrypt_segment": "rayohx._crypto._cipher",
26
+ "derive_iv": "rayohx._crypto._cipher",
27
+ "require_supported_encryption": "rayohx._crypto._support",
28
+ }
29
+
30
+
31
+ def __getattr__(name: str) -> Any:
32
+ """Import a name the first time it is used."""
33
+ module = _EXPORTS.get(name)
34
+ if module is None:
35
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
36
+ value = getattr(import_module(module), name)
37
+ globals()[name] = value
38
+ return value
39
+
40
+
41
+ def __dir__() -> list[str]:
42
+ return sorted({*globals(), *_EXPORTS})
43
+
44
+
45
+ __all__ = [
46
+ "KeyProvider",
47
+ "decrypt_aes128",
48
+ "decrypt_segment",
49
+ "derive_iv",
50
+ "require_supported_encryption",
51
+ ]
@@ -0,0 +1,55 @@
1
+ """AES-128-CBC decryption of segments and the choice of the IV."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import TYPE_CHECKING
6
+
7
+ if TYPE_CHECKING:
8
+ from rayohx.models import Segment
9
+
10
+ KEY_SIZE = 16
11
+ BLOCK_SIZE = 16
12
+
13
+
14
+ def derive_iv(segment: Segment) -> bytes:
15
+ """The IV for ``segment``: the playlist's, or the segment's sequence number (RFC 8216)."""
16
+ encryption = segment.encryption
17
+ if encryption is not None and encryption.iv is not None:
18
+ return encryption.iv
19
+ return segment.sequence_number.to_bytes(16, "big")
20
+
21
+
22
+ def decrypt_aes128(data: bytes, key: bytes, iv: bytes) -> bytes:
23
+ """Decrypt AES-128-CBC data with PKCS#7 padding.
24
+
25
+ Raises:
26
+ DecryptionError: If the data is not whole blocks or the padding is wrong.
27
+ """
28
+ from cryptography.hazmat.primitives import padding
29
+ from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
30
+
31
+ from rayohx.errors import DecryptionError
32
+
33
+ if len(key) != KEY_SIZE or len(iv) != BLOCK_SIZE:
34
+ raise DecryptionError("The key and the initialization vector must be 16 bytes each.")
35
+ if not data or len(data) % BLOCK_SIZE:
36
+ raise DecryptionError(
37
+ "The encrypted data is not a whole number of blocks.",
38
+ hint="The segment may be cut short or not encrypted as the playlist says.",
39
+ )
40
+ # HLS defines AES-128 segments as plain CBC, so there is no tag to check: GCM is not an option.
41
+ decryptor = Cipher(algorithms.AES(key), modes.CBC(iv)).decryptor() # nosemgrep
42
+ padded = decryptor.update(data) + decryptor.finalize()
43
+ unpadder = padding.PKCS7(128).unpadder()
44
+ try:
45
+ return unpadder.update(padded) + unpadder.finalize()
46
+ except ValueError:
47
+ raise DecryptionError(
48
+ "The segment could not be decrypted.",
49
+ hint="The key is probably wrong or has expired. Check the key server's access.",
50
+ ) from None
51
+
52
+
53
+ def decrypt_segment(data: bytes, segment: Segment, key: bytes) -> bytes:
54
+ """Decrypt one segment's media bytes with ``key`` and the segment's IV."""
55
+ return decrypt_aes128(data, key, derive_iv(segment))
@@ -0,0 +1,128 @@
1
+ """Fetching decryption keys through the HTTP layer."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import TYPE_CHECKING
6
+
7
+ if TYPE_CHECKING:
8
+ from collections.abc import Callable
9
+
10
+ from rayohx._http import HttpClient
11
+ from rayohx.models import EncryptionInfo
12
+
13
+ MAX_CACHED_KEYS = 64
14
+
15
+
16
+ class KeyProvider:
17
+ """Fetches decryption keys once each and keeps them for the rest of the download."""
18
+
19
+ def __init__(
20
+ self,
21
+ client: HttpClient,
22
+ *,
23
+ max_keys: int = MAX_CACHED_KEYS,
24
+ fetcher: Callable[[str], bytes] | None = None,
25
+ allow_file_keys: bool = False,
26
+ ) -> None:
27
+ import threading
28
+
29
+ self._client = client
30
+ self._fetcher = fetcher
31
+ self._allow_file_keys = allow_file_keys
32
+ self._max_keys = max_keys
33
+ self._keys: dict[str, bytes] = {}
34
+ self._lock = threading.Lock()
35
+
36
+ def key_for(self, encryption: EncryptionInfo) -> bytes:
37
+ """Return the 16-byte key for ``encryption``, fetching it on first use."""
38
+ from rayohx._crypto._cipher import KEY_SIZE
39
+ from rayohx.errors import DecryptionError, InvalidResponseError
40
+
41
+ uri = encryption.uri
42
+ if not uri:
43
+ raise DecryptionError("The playlist gives no address for the key.")
44
+ with self._lock:
45
+ cached = self._keys.get(uri)
46
+ if cached is not None:
47
+ return cached
48
+ key = self._fetch(uri)
49
+ if len(key) != KEY_SIZE:
50
+ raise InvalidResponseError(
51
+ f"The key must be {KEY_SIZE} bytes but {len(key)} were received.",
52
+ hint="The key server may have sent an error page or a protected (DRM) key.",
53
+ )
54
+ if len(self._keys) >= self._max_keys:
55
+ self._keys.pop(next(iter(self._keys)))
56
+ self._keys[uri] = key
57
+ return key
58
+
59
+ def _fetch(self, uri: str) -> bytes:
60
+ from urllib.parse import urlsplit
61
+
62
+ from rayohx.errors import AuthenticationError, DecryptionError, RayoHXError
63
+
64
+ if self._fetcher is not None:
65
+ try:
66
+ return bytes(self._fetcher(uri))
67
+ except RayoHXError:
68
+ raise
69
+ except Exception as exc:
70
+ raise DecryptionError(
71
+ "Your key_fetcher failed.", hint=f"{type(exc).__name__}: {exc}"
72
+ ) from exc
73
+ scheme = urlsplit(uri).scheme.lower()
74
+ if scheme == "data":
75
+ return _data_key(uri)
76
+ if scheme == "file":
77
+ return self._file_key(uri)
78
+ if scheme not in ("http", "https"):
79
+ raise DecryptionError(
80
+ f"Keys at {scheme or 'this kind of'!s} addresses cannot be fetched.",
81
+ hint="Give the config a key_fetcher that returns the key for this address.",
82
+ )
83
+ try:
84
+ return self._client.fetch_bytes(uri, max_bytes=1024).content
85
+ except AuthenticationError as exc:
86
+ raise AuthenticationError(
87
+ uri,
88
+ exc.status_code,
89
+ hint="The key server refused the request. If it needs your Authorization "
90
+ "header or cookies, add its host to credential_hosts.",
91
+ ) from exc
92
+
93
+ def _file_key(self, uri: str) -> bytes:
94
+ from pathlib import Path
95
+ from urllib.parse import urlsplit
96
+ from urllib.request import url2pathname
97
+
98
+ from rayohx._crypto._cipher import KEY_SIZE
99
+ from rayohx.errors import DecryptionError
100
+
101
+ if not self._allow_file_keys:
102
+ raise DecryptionError(
103
+ "The playlist points to a key on this machine.",
104
+ hint="Local key files are off by default. Set allow_file_keys "
105
+ "(--allow-file-keys) if you trust this stream.",
106
+ )
107
+ path = Path(url2pathname(urlsplit(uri).path))
108
+ try:
109
+ with path.open("rb") as handle:
110
+ return handle.read(KEY_SIZE + 1)
111
+ except OSError as exc:
112
+ raise DecryptionError(f"The key file {path} cannot be read.") from exc
113
+
114
+
115
+ def _data_key(uri: str) -> bytes:
116
+ """The bytes inside a ``data:`` address (``data:;base64,...`` or percent-encoded)."""
117
+ import base64
118
+ from urllib.parse import unquote_to_bytes
119
+
120
+ from rayohx.errors import DecryptionError
121
+
122
+ header, _, payload = uri.partition(",")
123
+ try:
124
+ if header.lower().endswith(";base64"):
125
+ return base64.b64decode(payload, validate=True)
126
+ return unquote_to_bytes(payload)
127
+ except ValueError as exc:
128
+ raise DecryptionError("The key inside the playlist is not valid.") from exc
@@ -0,0 +1,32 @@
1
+ """Refusing playlists whose encryption the engine cannot undo."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import TYPE_CHECKING
6
+
7
+ if TYPE_CHECKING:
8
+ from collections.abc import Iterable
9
+
10
+ from rayohx.models import Segment
11
+
12
+
13
+ def require_supported_encryption(segments: Iterable[Segment]) -> None:
14
+ """Refuse playlists whose encryption the engine cannot undo.
15
+
16
+ Only ``METHOD=AES-128`` with the standard key format is handled. SAMPLE-AES and DRM key
17
+ formats are refused up front: RayoHX never claims to support DRM.
18
+
19
+ Raises:
20
+ UnsupportedPlaylistError: For SAMPLE-AES or any non-standard key format.
21
+ """
22
+ from rayohx.errors import UnsupportedPlaylistError
23
+
24
+ for segment in segments:
25
+ encryption = segment.encryption
26
+ if encryption is not None and not encryption.is_supported:
27
+ raise UnsupportedPlaylistError(
28
+ f"This stream uses {encryption.method.value} with the key format "
29
+ f"{encryption.key_format!r}, which is not supported.",
30
+ hint="Only plain AES-128 encryption is supported. Protected (DRM) streams "
31
+ "cannot be downloaded.",
32
+ )
@@ -0,0 +1,48 @@
1
+ """The download engine, internal: the parts ``rayohx.downloader`` uses to run a download.
2
+
3
+ ``MediaDownload`` downloads one media playlist: it prepares everything (strategy, disk space,
4
+ working folder, resume state), runs the segment pipeline, and then commits the output or cleans up.
5
+ The underscore modules next to it are its parts. Nothing here is public API.
6
+
7
+ The names below are imported the first time they are used.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from importlib import import_module
13
+ from typing import TYPE_CHECKING, Any
14
+
15
+ if TYPE_CHECKING:
16
+ from rayohx._download._media import DownloadSummary, MediaDownload
17
+ from rayohx._download._sinks import FileSink, OutputSink, StreamSink
18
+
19
+ _EXPORTS = {
20
+ "DownloadSummary": "rayohx._download._media",
21
+ "FileSink": "rayohx._download._sinks",
22
+ "MediaDownload": "rayohx._download._media",
23
+ "OutputSink": "rayohx._download._sinks",
24
+ "StreamSink": "rayohx._download._sinks",
25
+ }
26
+
27
+
28
+ def __getattr__(name: str) -> Any:
29
+ """Import a name the first time it is used."""
30
+ module = _EXPORTS.get(name)
31
+ if module is None:
32
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
33
+ value = getattr(import_module(module), name)
34
+ globals()[name] = value
35
+ return value
36
+
37
+
38
+ def __dir__() -> list[str]:
39
+ return sorted({*globals(), *_EXPORTS})
40
+
41
+
42
+ __all__ = [
43
+ "DownloadSummary",
44
+ "FileSink",
45
+ "MediaDownload",
46
+ "OutputSink",
47
+ "StreamSink",
48
+ ]
@@ -0,0 +1,58 @@
1
+ """Recognising and checking segment formats.
2
+
3
+ RayoHX joins MPEG-TS and fragmented MP4 segments by simple concatenation, which is only valid when
4
+ the pieces really are that format. These checks catch the common failures (an error page served as
5
+ media, a wrong decryption key, a cut-off file) before they turn into a corrupt output that looks
6
+ like a success.
7
+
8
+ * ``sniff_container`` guesses the format from the first bytes of a segment.
9
+ * ``check_segment`` checks one downloaded segment against the promised format.
10
+ * ``validate_output`` (with ``validate_ts_file`` and ``validate_fmp4_file``) checks a finished file.
11
+
12
+ The names below are imported the first time they are used.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ from importlib import import_module
18
+ from typing import TYPE_CHECKING, Any
19
+
20
+ if TYPE_CHECKING:
21
+ from rayohx._download._containers._files import (
22
+ validate_fmp4_file,
23
+ validate_output,
24
+ validate_ts_file,
25
+ )
26
+ from rayohx._download._containers._segments import check_segment
27
+ from rayohx._download._containers._sniff import sniff_container
28
+
29
+ _EXPORTS = {
30
+ "check_segment": "rayohx._download._containers._segments",
31
+ "sniff_container": "rayohx._download._containers._sniff",
32
+ "validate_fmp4_file": "rayohx._download._containers._files",
33
+ "validate_output": "rayohx._download._containers._files",
34
+ "validate_ts_file": "rayohx._download._containers._files",
35
+ }
36
+
37
+
38
+ def __getattr__(name: str) -> Any:
39
+ """Import a name the first time it is used."""
40
+ module = _EXPORTS.get(name)
41
+ if module is None:
42
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
43
+ value = getattr(import_module(module), name)
44
+ globals()[name] = value
45
+ return value
46
+
47
+
48
+ def __dir__() -> list[str]:
49
+ return sorted({*globals(), *_EXPORTS})
50
+
51
+
52
+ __all__ = [
53
+ "check_segment",
54
+ "sniff_container",
55
+ "validate_fmp4_file",
56
+ "validate_output",
57
+ "validate_ts_file",
58
+ ]