]> jfr.im git - yt-dlp.git/blob - yt_dlp/extractor/lbry.py
[version] update
[yt-dlp.git] / yt_dlp / extractor / lbry.py
1 # coding: utf-8
2 from __future__ import unicode_literals
3
4 import functools
5 import json
6
7 from .common import InfoExtractor
8 from ..compat import (
9 compat_str,
10 compat_urllib_parse_unquote,
11 )
12 from ..utils import (
13 determine_ext,
14 ExtractorError,
15 int_or_none,
16 mimetype2ext,
17 parse_qs,
18 OnDemandPagedList,
19 try_get,
20 UnsupportedError,
21 urljoin,
22 )
23
24
25 class LBRYBaseIE(InfoExtractor):
26 _BASE_URL_REGEX = r'(?:https?://(?:www\.)?(?:lbry\.tv|odysee\.com)/|lbry://)'
27 _CLAIM_ID_REGEX = r'[0-9a-f]{1,40}'
28 _OPT_CLAIM_ID = '[^:/?#&]+(?:[:#]%s)?' % _CLAIM_ID_REGEX
29 _SUPPORTED_STREAM_TYPES = ['video', 'audio']
30
31 def _call_api_proxy(self, method, display_id, params, resource):
32 response = self._download_json(
33 'https://api.lbry.tv/api/v1/proxy',
34 display_id, 'Downloading %s JSON metadata' % resource,
35 headers={'Content-Type': 'application/json-rpc'},
36 data=json.dumps({
37 'method': method,
38 'params': params,
39 }).encode())
40 err = response.get('error')
41 if err:
42 raise ExtractorError(
43 f'{self.IE_NAME} said: {err.get("code")} - {err.get("message")}', expected=True)
44 return response['result']
45
46 def _resolve_url(self, url, display_id, resource):
47 return self._call_api_proxy(
48 'resolve', display_id, {'urls': url}, resource)[url]
49
50 def _permanent_url(self, url, claim_name, claim_id):
51 return urljoin(
52 url.replace('lbry://', 'https://lbry.tv/'),
53 '/%s:%s' % (claim_name, claim_id))
54
55 def _parse_stream(self, stream, url):
56 stream_value = stream.get('value') or {}
57 stream_type = stream_value.get('stream_type')
58 source = stream_value.get('source') or {}
59 media = stream_value.get(stream_type) or {}
60 signing_channel = stream.get('signing_channel') or {}
61 channel_name = signing_channel.get('name')
62 channel_claim_id = signing_channel.get('claim_id')
63 channel_url = None
64 if channel_name and channel_claim_id:
65 channel_url = self._permanent_url(url, channel_name, channel_claim_id)
66
67 info = {
68 'thumbnail': try_get(stream_value, lambda x: x['thumbnail']['url'], compat_str),
69 'description': stream_value.get('description'),
70 'license': stream_value.get('license'),
71 'timestamp': int_or_none(stream.get('timestamp')),
72 'release_timestamp': int_or_none(stream_value.get('release_time')),
73 'tags': stream_value.get('tags'),
74 'duration': int_or_none(media.get('duration')),
75 'channel': try_get(signing_channel, lambda x: x['value']['title']),
76 'channel_id': channel_claim_id,
77 'channel_url': channel_url,
78 'ext': determine_ext(source.get('name')) or mimetype2ext(source.get('media_type')),
79 'filesize': int_or_none(source.get('size')),
80 }
81 if stream_type == 'audio':
82 info['vcodec'] = 'none'
83 else:
84 info.update({
85 'width': int_or_none(media.get('width')),
86 'height': int_or_none(media.get('height')),
87 })
88 return info
89
90
91 class LBRYIE(LBRYBaseIE):
92 IE_NAME = 'lbry'
93 _VALID_URL = LBRYBaseIE._BASE_URL_REGEX + r'(?P<id>\$/[^/]+/[^/]+/{1}|@{0}/{0}|(?!@){0})'.format(LBRYBaseIE._OPT_CLAIM_ID, LBRYBaseIE._CLAIM_ID_REGEX)
94 _TESTS = [{
95 # Video
96 'url': 'https://lbry.tv/@Mantega:1/First-day-LBRY:1',
97 'md5': '65bd7ec1f6744ada55da8e4c48a2edf9',
98 'info_dict': {
99 'id': '17f983b61f53091fb8ea58a9c56804e4ff8cff4d',
100 'ext': 'mp4',
101 'title': 'First day in LBRY? Start HERE!',
102 'description': 'md5:f6cb5c704b332d37f5119313c2c98f51',
103 'timestamp': 1595694354,
104 'upload_date': '20200725',
105 'release_timestamp': 1595340697,
106 'release_date': '20200721',
107 'width': 1280,
108 'height': 720,
109 }
110 }, {
111 # Audio
112 'url': 'https://lbry.tv/@LBRYFoundation:0/Episode-1:e',
113 'md5': 'c94017d3eba9b49ce085a8fad6b98d00',
114 'info_dict': {
115 'id': 'e7d93d772bd87e2b62d5ab993c1c3ced86ebb396',
116 'ext': 'mp3',
117 'title': 'The LBRY Foundation Community Podcast Episode 1 - Introduction, Streaming on LBRY, Transcoding',
118 'description': 'md5:661ac4f1db09f31728931d7b88807a61',
119 'timestamp': 1591312601,
120 'upload_date': '20200604',
121 'release_timestamp': 1591312421,
122 'release_date': '20200604',
123 'tags': list,
124 'duration': 2570,
125 'channel': 'The LBRY Foundation',
126 'channel_id': '0ed629d2b9c601300cacf7eabe9da0be79010212',
127 'channel_url': 'https://lbry.tv/@LBRYFoundation:0ed629d2b9c601300cacf7eabe9da0be79010212',
128 'vcodec': 'none',
129 }
130 }, {
131 # HLS
132 'url': 'https://odysee.com/@gardeningincanada:b/plants-i-will-never-grow-again.-the:e',
133 'md5': 'fc82f45ea54915b1495dd7cb5cc1289f',
134 'info_dict': {
135 'id': 'e51671357333fe22ae88aad320bde2f6f96b1410',
136 'ext': 'mp4',
137 'title': 'PLANTS I WILL NEVER GROW AGAIN. THE BLACK LIST PLANTS FOR A CANADIAN GARDEN | Gardening in Canada 🍁',
138 'description': 'md5:9c539c6a03fb843956de61a4d5288d5e',
139 'timestamp': 1618254123,
140 'upload_date': '20210412',
141 'release_timestamp': 1618254002,
142 'release_date': '20210412',
143 'tags': list,
144 'duration': 554,
145 'channel': 'Gardening In Canada',
146 'channel_id': 'b8be0e93b423dad221abe29545fbe8ec36e806bc',
147 'channel_url': 'https://odysee.com/@gardeningincanada:b8be0e93b423dad221abe29545fbe8ec36e806bc',
148 'formats': 'mincount:3',
149 }
150 }, {
151 'url': 'https://odysee.com/@BrodieRobertson:5/apple-is-tracking-everything-you-do-on:e',
152 'only_matching': True,
153 }, {
154 'url': "https://odysee.com/@ScammerRevolts:b0/I-SYSKEY'D-THE-SAME-SCAMMERS-3-TIMES!:b",
155 'only_matching': True,
156 }, {
157 'url': 'https://lbry.tv/Episode-1:e7d93d772bd87e2b62d5ab993c1c3ced86ebb396',
158 'only_matching': True,
159 }, {
160 'url': 'https://lbry.tv/$/embed/Episode-1/e7d93d772bd87e2b62d5ab993c1c3ced86ebb396',
161 'only_matching': True,
162 }, {
163 'url': 'https://lbry.tv/Episode-1:e7',
164 'only_matching': True,
165 }, {
166 'url': 'https://lbry.tv/@LBRYFoundation/Episode-1',
167 'only_matching': True,
168 }, {
169 'url': 'https://lbry.tv/$/download/Episode-1/e7d93d772bd87e2b62d5ab993c1c3ced86ebb396',
170 'only_matching': True,
171 }, {
172 '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',
173 'only_matching': True,
174 }, {
175 'url': 'lbry://@lbry#3f/odysee#7',
176 'only_matching': True,
177 }]
178
179 def _real_extract(self, url):
180 display_id = self._match_id(url)
181 if display_id.startswith('$/'):
182 display_id = display_id.split('/', 2)[-1].replace('/', ':')
183 else:
184 display_id = display_id.replace(':', '#')
185 display_id = compat_urllib_parse_unquote(display_id)
186 uri = 'lbry://' + display_id
187 result = self._resolve_url(uri, display_id, 'stream')
188 if result['value'].get('stream_type') in self._SUPPORTED_STREAM_TYPES:
189 claim_id, is_live, headers = result['claim_id'], False, None
190 streaming_url = self._call_api_proxy(
191 'get', claim_id, {'uri': uri}, 'streaming url')['streaming_url']
192 final_url = self._request_webpage(
193 streaming_url, display_id, note='Downloading streaming redirect url info').geturl()
194 elif result.get('value_type') == 'stream':
195 claim_id, is_live = result['signing_channel']['claim_id'], True
196 headers = {'referer': 'https://player.odysee.live/'}
197 live_data = self._download_json(
198 f'https://api.live.odysee.com/v1/odysee/live/{claim_id}', claim_id,
199 note='Downloading livestream JSON metadata')['data']
200 streaming_url = final_url = live_data.get('url')
201 if not final_url and not live_data.get('live'):
202 self.raise_no_formats('This stream is not live', True, claim_id)
203 else:
204 raise UnsupportedError(url)
205
206 info = self._parse_stream(result, url)
207 if determine_ext(final_url) == 'm3u8':
208 info['formats'] = self._extract_m3u8_formats(
209 final_url, display_id, 'mp4', 'm3u8_native', m3u8_id='hls', live=is_live, headers=headers)
210 self._sort_formats(info['formats'])
211 else:
212 info['url'] = streaming_url
213 return {
214 **info,
215 'id': claim_id,
216 'title': result['value']['title'],
217 'is_live': is_live,
218 'http_headers': headers,
219 }
220
221
222 class LBRYChannelIE(LBRYBaseIE):
223 IE_NAME = 'lbry:channel'
224 _VALID_URL = LBRYBaseIE._BASE_URL_REGEX + r'(?P<id>@%s)/?(?:[?&]|$)' % LBRYBaseIE._OPT_CLAIM_ID
225 _TESTS = [{
226 'url': 'https://lbry.tv/@LBRYFoundation:0',
227 'info_dict': {
228 'id': '0ed629d2b9c601300cacf7eabe9da0be79010212',
229 'title': 'The LBRY Foundation',
230 'description': 'Channel for the LBRY Foundation. Follow for updates and news.',
231 },
232 'playlist_count': 29,
233 }, {
234 'url': 'https://lbry.tv/@LBRYFoundation',
235 'only_matching': True,
236 }, {
237 'url': 'lbry://@lbry#3f',
238 'only_matching': True,
239 }]
240 _PAGE_SIZE = 50
241
242 def _fetch_page(self, claim_id, url, params, page):
243 page += 1
244 page_params = {
245 'channel_ids': [claim_id],
246 'claim_type': 'stream',
247 'no_totals': True,
248 'page': page,
249 'page_size': self._PAGE_SIZE,
250 }
251 page_params.update(params)
252 result = self._call_api_proxy(
253 'claim_search', claim_id, page_params, 'page %d' % page)
254 for item in (result.get('items') or []):
255 stream_claim_name = item.get('name')
256 stream_claim_id = item.get('claim_id')
257 if not (stream_claim_name and stream_claim_id):
258 continue
259
260 info = self._parse_stream(item, url)
261 info.update({
262 '_type': 'url',
263 'id': stream_claim_id,
264 'title': try_get(item, lambda x: x['value']['title']),
265 'url': self._permanent_url(url, stream_claim_name, stream_claim_id),
266 })
267 yield info
268
269 def _real_extract(self, url):
270 display_id = self._match_id(url).replace(':', '#')
271 result = self._resolve_url(
272 'lbry://' + display_id, display_id, 'channel')
273 claim_id = result['claim_id']
274 qs = parse_qs(url)
275 content = qs.get('content', [None])[0]
276 params = {
277 'fee_amount': qs.get('fee_amount', ['>=0'])[0],
278 'order_by': {
279 'new': ['release_time'],
280 'top': ['effective_amount'],
281 'trending': ['trending_group', 'trending_mixed'],
282 }[qs.get('order', ['new'])[0]],
283 'stream_types': [content] if content in ['audio', 'video'] else self._SUPPORTED_STREAM_TYPES,
284 }
285 duration = qs.get('duration', [None])[0]
286 if duration:
287 params['duration'] = {
288 'long': '>=1200',
289 'short': '<=240',
290 }[duration]
291 language = qs.get('language', ['all'])[0]
292 if language != 'all':
293 languages = [language]
294 if language == 'en':
295 languages.append('none')
296 params['any_languages'] = languages
297 entries = OnDemandPagedList(
298 functools.partial(self._fetch_page, claim_id, url, params),
299 self._PAGE_SIZE)
300 result_value = result.get('value') or {}
301 return self.playlist_result(
302 entries, claim_id, result_value.get('title'),
303 result_value.get('description'))