lbry.py 17 KB

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