]> jfr.im git - yt-dlp.git/blame - yt_dlp/extractor/lbry.py
[ie/abc.net.au:iview] Improve `episode` extraction (#8201)
[yt-dlp.git] / yt_dlp / extractor / lbry.py
CommitLineData
29f7c58a 1import functools
8bdd16b4 2import json
127a2246 3import re
44c0d664 4import urllib.parse
8bdd16b4 5
6from .common import InfoExtractor
3d2623a8 7from ..networking import HEADRequest
8bdd16b4 8from ..utils import (
8bdd16b4 9 ExtractorError,
8a40bffa
M
10 OnDemandPagedList,
11 UnsupportedError,
12 determine_ext,
8bdd16b4 13 int_or_none,
14 mimetype2ext,
4dfbf869 15 parse_qs,
44c0d664 16 traverse_obj,
8bdd16b4 17 try_get,
44c0d664 18 url_or_none,
19 urlhandle_detect_ext,
29f7c58a 20 urljoin,
8bdd16b4 21)
22
23
29f7c58a 24class LBRYBaseIE(InfoExtractor):
57db6a87 25 _BASE_URL_REGEX = r'(?:https?://(?:www\.)?(?:lbry\.tv|odysee\.com)/|lbry://)'
29f7c58a 26 _CLAIM_ID_REGEX = r'[0-9a-f]{1,40}'
57db6a87 27 _OPT_CLAIM_ID = '[^:/?#&]+(?:[:#]%s)?' % _CLAIM_ID_REGEX
29f7c58a 28 _SUPPORTED_STREAM_TYPES = ['video', 'audio']
29
30 def _call_api_proxy(self, method, display_id, params, resource):
59a0c358
M
31 headers = {'Content-Type': 'application/json-rpc'}
32 token = try_get(self._get_cookies('https://odysee.com'), lambda x: x['auth_token'].value)
33 if token:
34 headers['x-lbry-auth-token'] = token
8100c772 35 response = self._download_json(
29f7c58a 36 'https://api.lbry.tv/api/v1/proxy',
37 display_id, 'Downloading %s JSON metadata' % resource,
59a0c358 38 headers=headers,
29f7c58a 39 data=json.dumps({
40 'method': method,
41 'params': params,
8100c772 42 }).encode())
43 err = response.get('error')
44 if err:
45 raise ExtractorError(
46 f'{self.IE_NAME} said: {err.get("code")} - {err.get("message")}', expected=True)
47 return response['result']
29f7c58a 48
49 def _resolve_url(self, url, display_id, resource):
50 return self._call_api_proxy(
51 'resolve', display_id, {'urls': url}, resource)[url]
52
53 def _permanent_url(self, url, claim_name, claim_id):
57db6a87 54 return urljoin(
55 url.replace('lbry://', 'https://lbry.tv/'),
56 '/%s:%s' % (claim_name, claim_id))
29f7c58a 57
58 def _parse_stream(self, stream, url):
44c0d664 59 stream_type = traverse_obj(stream, ('value', 'stream_type', {str}))
60
61 info = traverse_obj(stream, {
62 'title': ('value', 'title', {str}),
63 'thumbnail': ('value', 'thumbnail', 'url', {url_or_none}),
64 'description': ('value', 'description', {str}),
65 'license': ('value', 'license', {str}),
66 'timestamp': ('timestamp', {int_or_none}),
67 'release_timestamp': ('value', 'release_time', {int_or_none}),
68 'tags': ('value', 'tags', ..., {lambda x: x or None}),
69 'duration': ('value', stream_type, 'duration', {int_or_none}),
70 'channel': ('signing_channel', 'value', 'title', {str}),
71 'channel_id': ('signing_channel', 'claim_id', {str}),
72 })
73
74 channel_name = traverse_obj(stream, ('signing_channel', 'name', {str}))
75 if channel_name and info.get('channel_id'):
76 info['channel_url'] = self._permanent_url(url, channel_name, info['channel_id'])
29f7c58a 77
29f7c58a 78 return info
79
80
81class LBRYIE(LBRYBaseIE):
82 IE_NAME = 'lbry'
83 _VALID_URL = LBRYBaseIE._BASE_URL_REGEX + r'(?P<id>\$/[^/]+/[^/]+/{1}|@{0}/{0}|(?!@){0})'.format(LBRYBaseIE._OPT_CLAIM_ID, LBRYBaseIE._CLAIM_ID_REGEX)
8bdd16b4 84 _TESTS = [{
85 # Video
86 'url': 'https://lbry.tv/@Mantega:1/First-day-LBRY:1',
127a2246 87 'md5': '65bd7ec1f6744ada55da8e4c48a2edf9',
8bdd16b4 88 'info_dict': {
89 'id': '17f983b61f53091fb8ea58a9c56804e4ff8cff4d',
90 'ext': 'mp4',
91 'title': 'First day in LBRY? Start HERE!',
92 'description': 'md5:f6cb5c704b332d37f5119313c2c98f51',
93 'timestamp': 1595694354,
94 'upload_date': '20200725',
10db0d2f 95 'release_timestamp': 1595340697,
96 'release_date': '20200721',
29f7c58a 97 'width': 1280,
98 'height': 720,
8a40bffa
M
99 'thumbnail': 'https://spee.ch/7/67f2d809c263288c.png',
100 'license': 'None',
101 'duration': 346,
102 'channel': 'LBRY/Odysee rats united!!!',
103 'channel_id': '1c8ad6a2ab4e889a71146ae4deeb23bb92dab627',
104 'channel_url': 'https://lbry.tv/@Mantega:1c8ad6a2ab4e889a71146ae4deeb23bb92dab627',
105 'tags': [
106 'first day in lbry',
107 'lbc',
108 'lbry',
109 'start',
110 'tutorial'
111 ],
8bdd16b4 112 }
113 }, {
114 # Audio
115 'url': 'https://lbry.tv/@LBRYFoundation:0/Episode-1:e',
116 'md5': 'c94017d3eba9b49ce085a8fad6b98d00',
117 'info_dict': {
118 'id': 'e7d93d772bd87e2b62d5ab993c1c3ced86ebb396',
119 'ext': 'mp3',
120 'title': 'The LBRY Foundation Community Podcast Episode 1 - Introduction, Streaming on LBRY, Transcoding',
121 'description': 'md5:661ac4f1db09f31728931d7b88807a61',
122 'timestamp': 1591312601,
123 'upload_date': '20200604',
10db0d2f 124 'release_timestamp': 1591312421,
125 'release_date': '20200604',
29f7c58a 126 'tags': list,
127 'duration': 2570,
128 'channel': 'The LBRY Foundation',
129 'channel_id': '0ed629d2b9c601300cacf7eabe9da0be79010212',
130 'channel_url': 'https://lbry.tv/@LBRYFoundation:0ed629d2b9c601300cacf7eabe9da0be79010212',
131 'vcodec': 'none',
8a40bffa
M
132 'thumbnail': 'https://spee.ch/d/0bc63b0e6bf1492d.png',
133 'license': 'None',
8bdd16b4 134 }
201c1459 135 }, {
201c1459 136 'url': 'https://odysee.com/@gardeningincanada:b/plants-i-will-never-grow-again.-the:e',
127a2246 137 'md5': 'c35fac796f62a14274b4dc2addb5d0ba',
201c1459 138 'info_dict': {
139 'id': 'e51671357333fe22ae88aad320bde2f6f96b1410',
140 'ext': 'mp4',
141 'title': 'PLANTS I WILL NEVER GROW AGAIN. THE BLACK LIST PLANTS FOR A CANADIAN GARDEN | Gardening in Canada 🍁',
142 'description': 'md5:9c539c6a03fb843956de61a4d5288d5e',
143 'timestamp': 1618254123,
144 'upload_date': '20210412',
145 'release_timestamp': 1618254002,
146 'release_date': '20210412',
147 'tags': list,
148 'duration': 554,
149 'channel': 'Gardening In Canada',
150 'channel_id': 'b8be0e93b423dad221abe29545fbe8ec36e806bc',
151 'channel_url': 'https://odysee.com/@gardeningincanada:b8be0e93b423dad221abe29545fbe8ec36e806bc',
152 'formats': 'mincount:3',
8a40bffa
M
153 'thumbnail': 'https://thumbnails.lbry.com/AgHSc_HzrrE',
154 'license': 'Copyrighted (contact publisher)',
201c1459 155 }
59a0c358
M
156 }, {
157 # HLS live stream (might expire)
158 'url': 'https://odysee.com/@RT:fd/livestream_RT:d',
159 'info_dict': {
160 'id': 'fdd11cb3ab75f95efb7b3bc2d726aa13ac915b66',
161 'ext': 'mp4',
162 'live_status': 'is_live',
163 'title': 'startswith:RT News | Livestream 24/7',
164 'description': 'md5:fe68d0056dfe79c1a6b8ce8c34d5f6fa',
165 'timestamp': int,
166 'upload_date': str,
167 'release_timestamp': int,
168 'release_date': str,
169 'tags': list,
170 'duration': None,
171 'channel': 'RT',
172 'channel_id': 'fdd11cb3ab75f95efb7b3bc2d726aa13ac915b66',
173 'channel_url': 'https://odysee.com/@RT:fdd11cb3ab75f95efb7b3bc2d726aa13ac915b66',
174 'formats': 'mincount:1',
175 'thumbnail': 'startswith:https://thumb',
176 'license': 'None',
177 },
178 'params': {'skip_download': True}
44c0d664 179 }, {
180 # original quality format w/higher resolution than HLS formats
181 'url': 'https://odysee.com/@wickedtruths:2/Biotechnological-Invasion-of-Skin-(April-2023):4',
182 'md5': '305b0b3b369bde1b984961f005b67193',
183 'info_dict': {
184 'id': '41fbfe805eb73c8d3012c0c49faa0f563274f634',
185 'ext': 'mp4',
186 'title': 'Biotechnological Invasion of Skin (April 2023)',
187 'description': 'md5:709a2f4c07bd8891cda3a7cc2d6fcf5c',
188 'channel': 'Wicked Truths',
189 'channel_id': '23d2bbf856b0ceed5b1d7c5960bcc72da5a20cb0',
190 'channel_url': 'https://odysee.com/@wickedtruths:23d2bbf856b0ceed5b1d7c5960bcc72da5a20cb0',
191 'timestamp': 1685790036,
192 'upload_date': '20230603',
193 'release_timestamp': 1685617473,
194 'release_date': '20230601',
195 'duration': 1063,
196 'thumbnail': 'https://thumbs.odycdn.com/4e6d39da4df0cfdad45f64e253a15959.webp',
197 'tags': ['smart skin surveillance', 'biotechnology invasion of skin', 'morgellons'],
198 'license': 'None',
199 'protocol': 'https', # test for direct mp4 download
200 },
8bdd16b4 201 }, {
202 'url': 'https://odysee.com/@BrodieRobertson:5/apple-is-tracking-everything-you-do-on:e',
203 'only_matching': True,
70c5802b 204 }, {
8a40bffa 205 'url': 'https://odysee.com/@ScammerRevolts:b0/I-SYSKEY\'D-THE-SAME-SCAMMERS-3-TIMES!:b',
70c5802b 206 'only_matching': True,
29f7c58a 207 }, {
208 'url': 'https://lbry.tv/Episode-1:e7d93d772bd87e2b62d5ab993c1c3ced86ebb396',
209 'only_matching': True,
210 }, {
211 'url': 'https://lbry.tv/$/embed/Episode-1/e7d93d772bd87e2b62d5ab993c1c3ced86ebb396',
212 'only_matching': True,
213 }, {
214 'url': 'https://lbry.tv/Episode-1:e7',
215 'only_matching': True,
216 }, {
217 'url': 'https://lbry.tv/@LBRYFoundation/Episode-1',
218 'only_matching': True,
219 }, {
220 'url': 'https://lbry.tv/$/download/Episode-1/e7d93d772bd87e2b62d5ab993c1c3ced86ebb396',
221 'only_matching': True,
a820dc72
RA
222 }, {
223 'url': 'https://lbry.tv/@lacajadepandora:a/TRUMP-EST%C3%81-BIEN-PUESTO-con-Pilar-Baselga,-Carlos-Senra,-Luis-Palacios-(720p_30fps_H264-192kbit_AAC):1',
224 'only_matching': True,
57db6a87 225 }, {
226 'url': 'lbry://@lbry#3f/odysee#7',
227 'only_matching': True,
8bdd16b4 228 }]
229
8bdd16b4 230 def _real_extract(self, url):
29f7c58a 231 display_id = self._match_id(url)
232 if display_id.startswith('$/'):
233 display_id = display_id.split('/', 2)[-1].replace('/', ':')
234 else:
235 display_id = display_id.replace(':', '#')
44c0d664 236 display_id = urllib.parse.unquote(display_id)
8bdd16b4 237 uri = 'lbry://' + display_id
29f7c58a 238 result = self._resolve_url(uri, display_id, 'stream')
59a0c358 239 headers = {'Referer': 'https://odysee.com/'}
44c0d664 240
241 formats = []
242 stream_type = traverse_obj(result, ('value', 'stream_type', {str}))
243
244 if stream_type in self._SUPPORTED_STREAM_TYPES:
59a0c358 245 claim_id, is_live = result['claim_id'], False
c25de59c
AG
246 streaming_url = self._call_api_proxy(
247 'get', claim_id, {'uri': uri}, 'streaming url')['streaming_url']
44c0d664 248
127a2246 249 # GET request to v3 API returns original video/audio file if available
250 direct_url = re.sub(r'/api/v\d+/', '/api/v3/', streaming_url)
6148833f 251 urlh = self._request_webpage(
252 direct_url, display_id, 'Checking for original quality', headers=headers, fatal=False)
253 if urlh and urlhandle_detect_ext(urlh) != 'm3u8':
44c0d664 254 formats.append({
127a2246 255 'url': direct_url,
44c0d664 256 'format_id': 'original',
257 'quality': 1,
258 **traverse_obj(result, ('value', {
259 'ext': ('source', (('name', {determine_ext}), ('media_type', {mimetype2ext}))),
260 'filesize': ('source', 'size', {int_or_none}),
261 'width': ('video', 'width', {int_or_none}),
262 'height': ('video', 'height', {int_or_none}),
263 }), get_all=False),
264 'vcodec': 'none' if stream_type == 'audio' else None,
265 })
266
267 # HEAD request returns redirect response to m3u8 URL if available
c25de59c 268 final_url = self._request_webpage(
59a0c358 269 HEADRequest(streaming_url), display_id, headers=headers,
3d2623a8 270 note='Downloading streaming redirect url info').url
44c0d664 271
c25de59c
AG
272 elif result.get('value_type') == 'stream':
273 claim_id, is_live = result['signing_channel']['claim_id'], True
c25de59c 274 live_data = self._download_json(
9fde8a6b
M
275 'https://api.odysee.live/livestream/is_live', claim_id,
276 query={'channel_claim_id': claim_id},
c25de59c 277 note='Downloading livestream JSON metadata')['data']
44c0d664 278 final_url = live_data.get('VideoURL')
59a0c358
M
279 # Upcoming videos may still give VideoURL
280 if not live_data.get('Live'):
44c0d664 281 final_url = None
3a4bb9f7 282 self.raise_no_formats('This stream is not live', True, claim_id)
44c0d664 283
c25de59c 284 else:
3a4bb9f7 285 raise UnsupportedError(url)
c25de59c 286
c25de59c 287 if determine_ext(final_url) == 'm3u8':
44c0d664 288 formats.extend(self._extract_m3u8_formats(
289 final_url, display_id, 'mp4', m3u8_id='hls', live=is_live, headers=headers))
290
c25de59c 291 return {
44c0d664 292 **self._parse_stream(result, url),
29f7c58a 293 'id': claim_id,
44c0d664 294 'formats': formats,
c25de59c
AG
295 'is_live': is_live,
296 'http_headers': headers,
297 }
29f7c58a 298
299
300class LBRYChannelIE(LBRYBaseIE):
301 IE_NAME = 'lbry:channel'
57db6a87 302 _VALID_URL = LBRYBaseIE._BASE_URL_REGEX + r'(?P<id>@%s)/?(?:[?&]|$)' % LBRYBaseIE._OPT_CLAIM_ID
29f7c58a 303 _TESTS = [{
304 'url': 'https://lbry.tv/@LBRYFoundation:0',
305 'info_dict': {
306 'id': '0ed629d2b9c601300cacf7eabe9da0be79010212',
307 'title': 'The LBRY Foundation',
308 'description': 'Channel for the LBRY Foundation. Follow for updates and news.',
309 },
8a40bffa 310 'playlist_mincount': 29,
29f7c58a 311 }, {
312 'url': 'https://lbry.tv/@LBRYFoundation',
313 'only_matching': True,
57db6a87 314 }, {
315 'url': 'lbry://@lbry#3f',
316 'only_matching': True,
29f7c58a 317 }]
318 _PAGE_SIZE = 50
319
10db0d2f 320 def _fetch_page(self, claim_id, url, params, page):
29f7c58a 321 page += 1
10db0d2f 322 page_params = {
323 'channel_ids': [claim_id],
324 'claim_type': 'stream',
325 'no_totals': True,
326 'page': page,
327 'page_size': self._PAGE_SIZE,
328 }
329 page_params.update(params)
29f7c58a 330 result = self._call_api_proxy(
10db0d2f 331 'claim_search', claim_id, page_params, 'page %d' % page)
29f7c58a 332 for item in (result.get('items') or []):
333 stream_claim_name = item.get('name')
334 stream_claim_id = item.get('claim_id')
335 if not (stream_claim_name and stream_claim_id):
336 continue
337
44c0d664 338 yield {
339 **self._parse_stream(item, url),
29f7c58a 340 '_type': 'url',
341 'id': stream_claim_id,
29f7c58a 342 'url': self._permanent_url(url, stream_claim_name, stream_claim_id),
44c0d664 343 }
29f7c58a 344
345 def _real_extract(self, url):
346 display_id = self._match_id(url).replace(':', '#')
347 result = self._resolve_url(
348 'lbry://' + display_id, display_id, 'channel')
349 claim_id = result['claim_id']
4dfbf869 350 qs = parse_qs(url)
10db0d2f 351 content = qs.get('content', [None])[0]
352 params = {
353 'fee_amount': qs.get('fee_amount', ['>=0'])[0],
354 'order_by': {
355 'new': ['release_time'],
356 'top': ['effective_amount'],
357 'trending': ['trending_group', 'trending_mixed'],
358 }[qs.get('order', ['new'])[0]],
359 'stream_types': [content] if content in ['audio', 'video'] else self._SUPPORTED_STREAM_TYPES,
360 }
361 duration = qs.get('duration', [None])[0]
362 if duration:
363 params['duration'] = {
364 'long': '>=1200',
365 'short': '<=240',
366 }[duration]
367 language = qs.get('language', ['all'])[0]
368 if language != 'all':
369 languages = [language]
370 if language == 'en':
371 languages.append('none')
372 params['any_languages'] = languages
29f7c58a 373 entries = OnDemandPagedList(
10db0d2f 374 functools.partial(self._fetch_page, claim_id, url, params),
29f7c58a 375 self._PAGE_SIZE)
376 result_value = result.get('value') or {}
377 return self.playlist_result(
378 entries, claim_id, result_value.get('title'),
379 result_value.get('description'))