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