logo

oasis-root

Compiled tree of Oasis Linux based on own branch at <https://hacktivis.me/git/oasis/> git clone https://anongit.hacktivis.me/git/oasis-root.git

reddit.py (16439B)


  1. import json
  2. import urllib.parse
  3. from .common import InfoExtractor
  4. from ..utils import (
  5. ExtractorError,
  6. float_or_none,
  7. int_or_none,
  8. parse_qs,
  9. traverse_obj,
  10. try_get,
  11. unescapeHTML,
  12. update_url_query,
  13. url_or_none,
  14. urlencode_postdata,
  15. )
  16. class RedditIE(InfoExtractor):
  17. _NETRC_MACHINE = 'reddit'
  18. _VALID_URL = r'https?://(?:\w+\.)?reddit(?:media)?\.com/(?P<slug>(?:(?:r|user)/[^/]+/)?comments/(?P<id>[^/?#&]+))'
  19. _TESTS = [{
  20. 'url': 'https://www.reddit.com/r/videos/comments/6rrwyj/that_small_heart_attack/',
  21. 'info_dict': {
  22. 'id': 'zv89llsvexdz',
  23. 'ext': 'mp4',
  24. 'display_id': '6rrwyj',
  25. 'title': 'That small heart attack.',
  26. 'thumbnail': r're:^https?://.*\.(?:jpg|png)',
  27. 'thumbnails': 'count:4',
  28. 'timestamp': 1501941939,
  29. 'upload_date': '20170805',
  30. 'uploader': 'Antw87',
  31. 'duration': 12,
  32. 'like_count': int,
  33. 'dislike_count': int,
  34. 'comment_count': int,
  35. 'age_limit': 0,
  36. 'channel_id': 'videos',
  37. },
  38. 'params': {
  39. 'skip_download': True,
  40. },
  41. }, {
  42. # 1080p fallback format
  43. 'url': 'https://www.reddit.com/r/aww/comments/90bu6w/heat_index_was_110_degrees_so_we_offered_him_a/',
  44. 'md5': '8b5902cfda3006bf90faea7adf765a49',
  45. 'info_dict': {
  46. 'id': 'gyh95hiqc0b11',
  47. 'ext': 'mp4',
  48. 'display_id': '90bu6w',
  49. 'title': 'Heat index was 110 degrees so we offered him a cold drink. He went for a full body soak instead',
  50. 'thumbnail': r're:^https?://.*\.(?:jpg|png)',
  51. 'thumbnails': 'count:7',
  52. 'timestamp': 1532051078,
  53. 'upload_date': '20180720',
  54. 'uploader': 'FootLoosePickleJuice',
  55. 'duration': 14,
  56. 'like_count': int,
  57. 'dislike_count': int,
  58. 'comment_count': int,
  59. 'age_limit': 0,
  60. 'channel_id': 'aww',
  61. },
  62. }, {
  63. # User post
  64. 'url': 'https://www.reddit.com/user/creepyt0es/comments/nip71r/i_plan_to_make_more_stickers_and_prints_check/',
  65. 'info_dict': {
  66. 'id': 'zasobba6wp071',
  67. 'ext': 'mp4',
  68. 'display_id': 'nip71r',
  69. 'title': 'I plan to make more stickers and prints! Check them out on my Etsy! Or get them through my Patreon. Links below.',
  70. 'thumbnail': r're:^https?://.*\.(?:jpg|png)',
  71. 'thumbnails': 'count:5',
  72. 'timestamp': 1621709093,
  73. 'upload_date': '20210522',
  74. 'uploader': 'creepyt0es',
  75. 'duration': 6,
  76. 'like_count': int,
  77. 'dislike_count': int,
  78. 'comment_count': int,
  79. 'age_limit': 18,
  80. 'channel_id': 'u_creepyt0es',
  81. },
  82. 'params': {
  83. 'skip_download': True,
  84. },
  85. }, {
  86. # videos embedded in reddit text post
  87. 'url': 'https://www.reddit.com/r/KamenRider/comments/wzqkxp/finale_kamen_rider_revice_episode_50_family_to/',
  88. 'playlist_count': 2,
  89. 'info_dict': {
  90. 'id': 'wzqkxp',
  91. 'title': 'md5:72d3d19402aa11eff5bd32fc96369b37',
  92. },
  93. }, {
  94. # crossposted reddit-hosted media
  95. 'url': 'https://www.reddit.com/r/dumbfuckers_club/comments/zjjw82/cringe/',
  96. 'md5': '746180895c7b75a9d6b05341f507699a',
  97. 'info_dict': {
  98. 'id': 'a1oneun6pa5a1',
  99. 'ext': 'mp4',
  100. 'display_id': 'zjjw82',
  101. 'title': 'Cringe',
  102. 'uploader': 'Otaku-senpai69420',
  103. 'thumbnail': r're:^https?://.*\.(?:jpg|png)',
  104. 'upload_date': '20221212',
  105. 'timestamp': 1670812309,
  106. 'duration': 16,
  107. 'like_count': int,
  108. 'dislike_count': int,
  109. 'comment_count': int,
  110. 'age_limit': 0,
  111. 'channel_id': 'dumbfuckers_club',
  112. },
  113. }, {
  114. # post link without subreddit
  115. 'url': 'https://www.reddit.com/comments/124pp33',
  116. 'md5': '15eec9d828adcef4468b741a7e45a395',
  117. 'info_dict': {
  118. 'id': 'antsenjc2jqa1',
  119. 'ext': 'mp4',
  120. 'display_id': '124pp33',
  121. 'title': 'Harmless prank of some old friends',
  122. 'uploader': 'Dudezila',
  123. 'channel_id': 'ContagiousLaughter',
  124. 'duration': 17,
  125. 'upload_date': '20230328',
  126. 'timestamp': 1680012043,
  127. 'thumbnail': r're:^https?://.*\.(?:jpg|png)',
  128. 'age_limit': 0,
  129. 'comment_count': int,
  130. 'dislike_count': int,
  131. 'like_count': int,
  132. },
  133. }, {
  134. # quarantined subreddit post
  135. 'url': 'https://old.reddit.com/r/GenZedong/comments/12fujy3/based_hasan/',
  136. 'md5': '3156ea69e3c1f1b6259683c5abd36e71',
  137. 'info_dict': {
  138. 'id': '8bwtclfggpsa1',
  139. 'ext': 'mp4',
  140. 'display_id': '12fujy3',
  141. 'title': 'Based Hasan?',
  142. 'uploader': 'KingNigelXLII',
  143. 'channel_id': 'GenZedong',
  144. 'duration': 16,
  145. 'upload_date': '20230408',
  146. 'timestamp': 1680979138,
  147. 'age_limit': 0,
  148. 'comment_count': int,
  149. 'dislike_count': int,
  150. 'like_count': int,
  151. },
  152. 'skip': 'Requires account that has opted-in to the GenZedong subreddit',
  153. }, {
  154. # subtitles in HLS manifest
  155. 'url': 'https://www.reddit.com/r/Unexpected/comments/1cl9h0u/the_insurance_claim_will_be_interesting/',
  156. 'info_dict': {
  157. 'id': 'a2mdj5d57qyc1',
  158. 'ext': 'mp4',
  159. 'display_id': '1cl9h0u',
  160. 'title': 'The insurance claim will be interesting',
  161. 'uploader': 'darrenpauli',
  162. 'channel_id': 'Unexpected',
  163. 'duration': 53,
  164. 'upload_date': '20240506',
  165. 'timestamp': 1714966382,
  166. 'age_limit': 0,
  167. 'comment_count': int,
  168. 'dislike_count': int,
  169. 'like_count': int,
  170. 'subtitles': {'en': 'mincount:1'},
  171. },
  172. 'params': {
  173. 'skip_download': True,
  174. },
  175. }, {
  176. # subtitles from caption-url
  177. 'url': 'https://www.reddit.com/r/soccer/comments/1cxwzso/tottenham_1_0_newcastle_united_james_maddison_31/',
  178. 'info_dict': {
  179. 'id': 'xbmj4t3igy1d1',
  180. 'ext': 'mp4',
  181. 'display_id': '1cxwzso',
  182. 'title': 'Tottenham [1] - 0 Newcastle United - James Maddison 31\'',
  183. 'uploader': 'Woodstovia',
  184. 'channel_id': 'soccer',
  185. 'duration': 30,
  186. 'upload_date': '20240522',
  187. 'timestamp': 1716373798,
  188. 'age_limit': 0,
  189. 'comment_count': int,
  190. 'dislike_count': int,
  191. 'like_count': int,
  192. 'subtitles': {'en': 'mincount:1'},
  193. },
  194. 'params': {
  195. 'skip_download': True,
  196. 'writesubtitles': True,
  197. },
  198. }, {
  199. 'url': 'https://www.reddit.com/r/videos/comments/6rrwyj',
  200. 'only_matching': True,
  201. }, {
  202. # imgur
  203. 'url': 'https://www.reddit.com/r/MadeMeSmile/comments/6t7wi5/wait_for_it/',
  204. 'only_matching': True,
  205. }, {
  206. # imgur @ old reddit
  207. 'url': 'https://old.reddit.com/r/MadeMeSmile/comments/6t7wi5/wait_for_it/',
  208. 'only_matching': True,
  209. }, {
  210. # streamable
  211. 'url': 'https://www.reddit.com/r/videos/comments/6t7sg9/comedians_hilarious_joke_about_the_guam_flag/',
  212. 'only_matching': True,
  213. }, {
  214. # youtube
  215. 'url': 'https://www.reddit.com/r/videos/comments/6t75wq/southern_man_tries_to_speak_without_an_accent/',
  216. 'only_matching': True,
  217. }, {
  218. # reddit video @ nm reddit
  219. 'url': 'https://nm.reddit.com/r/Cricket/comments/8idvby/lousy_cameraman_finds_himself_in_cairns_line_of/',
  220. 'only_matching': True,
  221. }, {
  222. 'url': 'https://www.redditmedia.com/r/serbia/comments/pu9wbx/ako_vu%C4%8Di%C4%87_izgubi_izbore_ja_%C4%87u_da_crknem/',
  223. 'only_matching': True,
  224. }]
  225. def _perform_login(self, username, password):
  226. captcha = self._download_json(
  227. 'https://www.reddit.com/api/requires_captcha/login.json', None,
  228. 'Checking login requirement')['required']
  229. if captcha:
  230. raise ExtractorError('Reddit is requiring captcha before login', expected=True)
  231. login = self._download_json(
  232. f'https://www.reddit.com/api/login/{username}', None, data=urlencode_postdata({
  233. 'op': 'login-main',
  234. 'user': username,
  235. 'passwd': password,
  236. 'api_type': 'json',
  237. }), note='Logging in', errnote='Login request failed')
  238. errors = '; '.join(traverse_obj(login, ('json', 'errors', ..., 1)))
  239. if errors:
  240. raise ExtractorError(f'Unable to login, Reddit API says {errors}', expected=True)
  241. elif not traverse_obj(login, ('json', 'data', 'cookie', {str})):
  242. raise ExtractorError('Unable to login, no cookie was returned')
  243. def _get_subtitles(self, video_id):
  244. # Fallback if there were no subtitles provided by DASH or HLS manifests
  245. caption_url = f'https://v.redd.it/{video_id}/wh_ben_en.vtt'
  246. if self._is_valid_url(caption_url, video_id, item='subtitles'):
  247. return {'en': [{'url': caption_url}]}
  248. def _real_extract(self, url):
  249. slug, video_id = self._match_valid_url(url).group('slug', 'id')
  250. try:
  251. data = self._download_json(
  252. f'https://www.reddit.com/{slug}/.json', video_id, expected_status=403)
  253. except ExtractorError as e:
  254. if isinstance(e.cause, json.JSONDecodeError):
  255. if self._get_cookies('https://www.reddit.com/').get('reddit_session'):
  256. raise ExtractorError('Your IP address is unable to access the Reddit API', expected=True)
  257. self.raise_login_required('Account authentication is required')
  258. raise
  259. if traverse_obj(data, 'error') == 403:
  260. reason = data.get('reason')
  261. if reason == 'quarantined':
  262. self.raise_login_required('Quarantined subreddit; an account that has opted in is required')
  263. elif reason == 'private':
  264. self.raise_login_required('Private subreddit; an account that has been approved is required')
  265. else:
  266. raise ExtractorError(f'HTTP Error 403 Forbidden; reason given: {reason}')
  267. data = data[0]['data']['children'][0]['data']
  268. video_url = data['url']
  269. over_18 = data.get('over_18')
  270. if over_18 is True:
  271. age_limit = 18
  272. elif over_18 is False:
  273. age_limit = 0
  274. else:
  275. age_limit = None
  276. thumbnails = []
  277. def add_thumbnail(src):
  278. if not isinstance(src, dict):
  279. return
  280. thumbnail_url = url_or_none(src.get('url'))
  281. if not thumbnail_url:
  282. return
  283. thumbnails.append({
  284. 'url': unescapeHTML(thumbnail_url),
  285. 'width': int_or_none(src.get('width')),
  286. 'height': int_or_none(src.get('height')),
  287. 'http_headers': {'Accept': '*/*'},
  288. })
  289. for image in try_get(data, lambda x: x['preview']['images']) or []:
  290. if not isinstance(image, dict):
  291. continue
  292. add_thumbnail(image.get('source'))
  293. resolutions = image.get('resolutions')
  294. if isinstance(resolutions, list):
  295. for resolution in resolutions:
  296. add_thumbnail(resolution)
  297. info = {
  298. 'title': data.get('title'),
  299. 'thumbnails': thumbnails,
  300. 'timestamp': float_or_none(data.get('created_utc')),
  301. 'uploader': data.get('author'),
  302. 'channel_id': data.get('subreddit'),
  303. 'like_count': int_or_none(data.get('ups')),
  304. 'dislike_count': int_or_none(data.get('downs')),
  305. 'comment_count': int_or_none(data.get('num_comments')),
  306. 'age_limit': age_limit,
  307. }
  308. parsed_url = urllib.parse.urlparse(video_url)
  309. # Check for embeds in text posts, or else raise to avoid recursing into the same reddit URL
  310. if 'reddit.com' in parsed_url.netloc and f'/{video_id}/' in parsed_url.path:
  311. entries = []
  312. for media in traverse_obj(data, ('media_metadata', ...), expected_type=dict):
  313. if not media.get('id') or media.get('e') != 'RedditVideo':
  314. continue
  315. formats = []
  316. if media.get('hlsUrl'):
  317. formats.extend(self._extract_m3u8_formats(
  318. unescapeHTML(media['hlsUrl']), video_id, 'mp4', m3u8_id='hls', fatal=False))
  319. if media.get('dashUrl'):
  320. formats.extend(self._extract_mpd_formats(
  321. unescapeHTML(media['dashUrl']), video_id, mpd_id='dash', fatal=False))
  322. if formats:
  323. entries.append({
  324. 'id': media['id'],
  325. 'display_id': video_id,
  326. 'formats': formats,
  327. **info,
  328. })
  329. if entries:
  330. return self.playlist_result(entries, video_id, info.get('title'))
  331. raise ExtractorError('No media found', expected=True)
  332. # Check if media is hosted on reddit:
  333. reddit_video = traverse_obj(data, (
  334. (None, ('crosspost_parent_list', ...)), ('secure_media', 'media'), 'reddit_video'), get_all=False)
  335. if reddit_video:
  336. playlist_urls = [
  337. try_get(reddit_video, lambda x: unescapeHTML(x[y]))
  338. for y in ('dash_url', 'hls_url')
  339. ]
  340. # Update video_id
  341. display_id = video_id
  342. video_id = self._search_regex(
  343. r'https?://v\.redd\.it/(?P<id>[^/?#&]+)', reddit_video['fallback_url'],
  344. 'video_id', default=display_id)
  345. dash_playlist_url = playlist_urls[0] or f'https://v.redd.it/{video_id}/DASHPlaylist.mpd'
  346. hls_playlist_url = playlist_urls[1] or f'https://v.redd.it/{video_id}/HLSPlaylist.m3u8'
  347. qs = traverse_obj(parse_qs(hls_playlist_url), {
  348. 'f': ('f', 0, {lambda x: ','.join([x, 'subsAll']) if x else 'hd,subsAll'}),
  349. })
  350. hls_playlist_url = update_url_query(hls_playlist_url, qs)
  351. formats = [{
  352. 'url': unescapeHTML(reddit_video['fallback_url']),
  353. 'height': int_or_none(reddit_video.get('height')),
  354. 'width': int_or_none(reddit_video.get('width')),
  355. 'tbr': int_or_none(reddit_video.get('bitrate_kbps')),
  356. 'acodec': 'none',
  357. 'vcodec': 'h264',
  358. 'ext': 'mp4',
  359. 'format_id': 'fallback',
  360. 'format_note': 'DASH video, mp4_dash',
  361. }]
  362. hls_fmts, subtitles = self._extract_m3u8_formats_and_subtitles(
  363. hls_playlist_url, display_id, 'mp4', m3u8_id='hls', fatal=False)
  364. formats.extend(hls_fmts)
  365. dash_fmts, dash_subs = self._extract_mpd_formats_and_subtitles(
  366. dash_playlist_url, display_id, mpd_id='dash', fatal=False)
  367. formats.extend(dash_fmts)
  368. self._merge_subtitles(dash_subs, target=subtitles)
  369. return {
  370. **info,
  371. 'id': video_id,
  372. 'display_id': display_id,
  373. 'formats': formats,
  374. 'subtitles': subtitles or self.extract_subtitles(video_id),
  375. 'duration': int_or_none(reddit_video.get('duration')),
  376. }
  377. if parsed_url.netloc == 'v.redd.it':
  378. self.raise_no_formats('This video is processing', expected=True, video_id=video_id)
  379. return {
  380. **info,
  381. 'id': parsed_url.path.split('/')[1],
  382. 'display_id': video_id,
  383. }
  384. # Not hosted on reddit, must continue extraction
  385. return {
  386. **info,
  387. 'display_id': video_id,
  388. '_type': 'url_transparent',
  389. 'url': video_url,
  390. }