]> jfr.im git - yt-dlp.git/blobdiff - yt_dlp/extractor/roosterteeth.py
[cleanup] Add more ruff rules (#10149)
[yt-dlp.git] / yt_dlp / extractor / roosterteeth.py
index c2576cb600b4313de1b6a40347a84dfb1ec5a12e..8b0099ec3c4a6401547f7a57c1cea146fe870133 100644 (file)
@@ -2,17 +2,18 @@
 from ..networking.exceptions import HTTPError
 from ..utils import (
     ExtractorError,
+    LazyList,
     int_or_none,
     join_nonempty,
-    LazyList,
+    parse_iso8601,
     parse_qs,
+    smuggle_url,
     str_or_none,
-    traverse_obj,
     url_or_none,
     urlencode_postdata,
     urljoin,
-    update_url_query,
 )
+from ..utils.traversal import traverse_obj
 
 
 class RoosterTeethBaseIE(InfoExtractor):
@@ -57,29 +58,37 @@ def _extract_video_info(self, data):
         title = traverse_obj(attributes, 'title', 'display_title')
         sub_only = attributes.get('is_sponsors_only')
 
+        episode_id = str_or_none(data.get('uuid'))
+        video_id = str_or_none(data.get('id'))
+        if video_id and 'parent_content_id' in attributes:  # parent_content_id is a bonus-only key
+            video_id += '-bonus'  # there are collisions with bonus ids and regular ids
+        elif not video_id:
+            video_id = episode_id
+
         return {
-            'id': str(data.get('id')),
+            'id': video_id,
             'display_id': attributes.get('slug'),
             'title': title,
             'description': traverse_obj(attributes, 'description', 'caption'),
-            'series': attributes.get('show_title'),
+            'series': traverse_obj(attributes, 'show_title', 'parent_content_title'),
             'season_number': int_or_none(attributes.get('season_number')),
-            'season_id': attributes.get('season_id'),
+            'season_id': str_or_none(attributes.get('season_id')),
             'episode': title,
             'episode_number': int_or_none(attributes.get('number')),
-            'episode_id': str_or_none(data.get('uuid')),
+            'episode_id': episode_id,
             'channel_id': attributes.get('channel_id'),
             'duration': int_or_none(attributes.get('length')),
+            'release_timestamp': parse_iso8601(attributes.get('original_air_date')),
             'thumbnails': thumbnails,
             'availability': self._availability(
                 needs_premium=sub_only, needs_subscription=sub_only, needs_auth=sub_only,
                 is_private=False, is_unlisted=False),
-            'tags': attributes.get('genres')
+            'tags': attributes.get('genres'),
         }
 
 
 class RoosterTeethIE(RoosterTeethBaseIE):
-    _VALID_URL = r'https?://(?:.+?\.)?roosterteeth\.com/(?:episode|watch)/(?P<id>[^/?#&]+)'
+    _VALID_URL = r'https?://(?:.+?\.)?roosterteeth\.com/(?:bonus-feature|episode|watch)/(?P<id>[^/?#&]+)'
     _TESTS = [{
         'url': 'http://roosterteeth.com/episode/million-dollars-but-season-2-million-dollars-but-the-game-announcement',
         'info_dict': {
@@ -100,6 +109,8 @@ class RoosterTeethIE(RoosterTeethBaseIE):
             'season_id': 'ffa27d48-464d-11e7-a302-065410f210c4',
             'channel_id': '92b6bb21-91d2-4b1b-bf95-3268fa0d9939',
             'duration': 145,
+            'release_timestamp': 1462982400,
+            'release_date': '20160511',
         },
         'params': {'skip_download': True},
     }, {
@@ -122,8 +133,81 @@ class RoosterTeethIE(RoosterTeethBaseIE):
             'series': 'RWBY: World of Remnant',
             'season_number': 1,
             'duration': 216,
+            'release_timestamp': 1413489600,
+            'release_date': '20141016',
+        },
+        'params': {'skip_download': True},
+    }, {
+        # bonus feature with /watch/ url
+        'url': 'https://roosterteeth.com/watch/rwby-bonus-21',
+        'info_dict': {
+            'id': '33-bonus',
+            'display_id': 'rwby-bonus-21',
+            'title': 'Volume 5 Yang Character Short',
+            'description': 'md5:8c2440bc763ea90c52cfe0a68093e1f7',
+            'episode': 'Volume 5 Yang Character Short',
+            'channel_id': '92f780eb-ebfe-4bf5-a3b5-c6ad5460a5f1',
+            'thumbnail': r're:^https?://.*\.(png|jpe?g)$',
+            'ext': 'mp4',
+            'availability': 'public',
+            'episode_id': 'f2a9f132-1fe2-44ad-8956-63d7c0267720',
+            'episode_number': 55,
+            'series': 'RWBY',
+            'duration': 255,
+            'release_timestamp': 1507993200,
+            'release_date': '20171014',
+        },
+        'params': {'skip_download': True},
+    }, {
+        # only works with video_data['attributes']['url'] m3u8 url
+        'url': 'https://www.roosterteeth.com/watch/achievement-hunter-achievement-hunter-fatality-walkthrough-deathstroke-lex-luthor-captain-marvel-green-lantern-and-wonder-woman',
+        'info_dict': {
+            'id': '25394',
+            'ext': 'mp4',
+            'title': 'Fatality Walkthrough: Deathstroke, Lex Luthor, Captain Marvel, Green Lantern, and Wonder Woman',
+            'description': 'md5:91bb934698344fb9647b1c7351f16964',
+            'availability': 'public',
+            'thumbnail': r're:^https?://.*\.(png|jpe?g)$',
+            'episode': 'Fatality Walkthrough: Deathstroke, Lex Luthor, Captain Marvel, Green Lantern, and Wonder Woman',
+            'episode_number': 71,
+            'episode_id': 'ffaec998-464d-11e7-a302-065410f210c4',
+            'season': 'Season 2008',
+            'tags': ['Gaming'],
+            'series': 'Achievement Hunter',
+            'display_id': 'md5:4465ce4f001735f9d7a2ae529a543d31',
+            'season_id': 'ffa13340-464d-11e7-a302-065410f210c4',
+            'season_number': 2008,
+            'channel_id': '2cb2a70c-be50-46f5-93d7-84a1baabb4f7',
+            'duration': 189,
+            'release_timestamp': 1228317300,
+            'release_date': '20081203',
         },
         'params': {'skip_download': True},
+    }, {
+        # brightcove fallback extraction needed
+        'url': 'https://roosterteeth.com/watch/lets-play-2013-126',
+        'info_dict': {
+            'id': '17845',
+            'ext': 'mp4',
+            'title': 'WWE \'13',
+            'availability': 'public',
+            'series': 'Let\'s Play',
+            'episode_number': 10,
+            'season_id': 'ffa23d9c-464d-11e7-a302-065410f210c4',
+            'channel_id': '75ba87e8-06fd-4482-bad9-52a4da2c6181',
+            'episode': 'WWE \'13',
+            'episode_id': 'ffdbe55e-464d-11e7-a302-065410f210c4',
+            'thumbnail': r're:^https?://.*\.(png|jpe?g)$',
+            'tags': ['Gaming', 'Our Favorites'],
+            'description': 'md5:b4a5226d2bbcf0dafbde11a2ba27262d',
+            'display_id': 'lets-play-2013-126',
+            'season_number': 3,
+            'season': 'Season 3',
+            'release_timestamp': 1359999840,
+            'release_date': '20130204',
+        },
+        'expected_warnings': ['Direct m3u8 URL returned HTTP Error 403'],
+        'params': {'skip_download': True},
     }, {
         'url': 'http://achievementhunter.roosterteeth.com/episode/off-topic-the-achievement-hunter-podcast-2016-i-didn-t-think-it-would-pass-31',
         'only_matching': True,
@@ -143,8 +227,21 @@ class RoosterTeethIE(RoosterTeethBaseIE):
     }, {
         'url': 'https://roosterteeth.com/watch/million-dollars-but-season-2-million-dollars-but-the-game-announcement',
         'only_matching': True,
+    }, {
+        'url': 'https://roosterteeth.com/bonus-feature/camp-camp-soundtrack-another-rap-song-about-foreign-cars-richie-branson',
+        'only_matching': True,
     }]
 
+    _BRIGHTCOVE_ACCOUNT_ID = '6203312018001'
+
+    def _extract_brightcove_formats_and_subtitles(self, bc_id, url, m3u8_url):
+        account_id = self._search_regex(
+            r'/accounts/(\d+)/videos/', m3u8_url, 'account id', default=self._BRIGHTCOVE_ACCOUNT_ID)
+        info = self._downloader.get_info_extractor('BrightcoveNew').extract(smuggle_url(
+            f'https://players.brightcove.net/{account_id}/default_default/index.html?videoId={bc_id}',
+            {'referrer': url}))
+        return info['formats'], info['subtitles']
+
     def _real_extract(self, url):
         display_id = self._match_id(url)
         api_episode_url = f'{self._API_BASE_URL}/watch/{display_id}'
@@ -153,17 +250,28 @@ def _real_extract(self, url):
             video_data = self._download_json(
                 api_episode_url + '/videos', display_id, 'Downloading video JSON metadata',
                 headers={'Client-Type': 'web'})['data'][0]  # web client-type yields ad-free streams
-            m3u8_url = video_data['attributes']['url']
-            # XXX: additional ad-free URL at video_data['links']['download'] but often gives 403 errors
         except ExtractorError as e:
             if isinstance(e.cause, HTTPError) and e.cause.status == 403:
                 if self._parse_json(e.cause.response.read().decode(), display_id).get('access') is False:
                     self.raise_login_required(
-                        '%s is only available for FIRST members' % display_id)
+                        f'{display_id} is only available for FIRST members')
             raise
 
-        formats, subtitles = self._extract_m3u8_formats_and_subtitles(
-            m3u8_url, display_id, 'mp4', 'm3u8_native', m3u8_id='hls')
+        # XXX: additional ad-free URL at video_data['links']['download'] but often gives 403 errors
+        m3u8_url = video_data['attributes']['url']
+        is_brightcove = traverse_obj(video_data, ('attributes', 'encoding_pipeline')) == 'brightcove'
+        bc_id = traverse_obj(video_data, ('attributes', 'uid', {str}))
+
+        try:
+            formats, subtitles = self._extract_m3u8_formats_and_subtitles(
+                m3u8_url, display_id, 'mp4', 'm3u8_native', m3u8_id='hls')
+        except ExtractorError as e:
+            if is_brightcove and bc_id and isinstance(e.cause, HTTPError) and e.cause.status == 403:
+                self.report_warning(
+                    'Direct m3u8 URL returned HTTP Error 403; retrying with Brightcove extraction')
+                formats, subtitles = self._extract_brightcove_formats_and_subtitles(bc_id, url, m3u8_url)
+            else:
+                raise
 
         episode = self._download_json(
             api_episode_url, display_id,
@@ -173,7 +281,7 @@ def _real_extract(self, url):
             'display_id': display_id,
             'formats': formats,
             'subtitles': subtitles,
-            **self._extract_video_info(episode)
+            **self._extract_video_info(episode),
         }
 
 
@@ -185,38 +293,53 @@ class RoosterTeethSeriesIE(RoosterTeethBaseIE):
         'info_dict': {
             'id': 'rwby-7',
             'title': 'RWBY - Season 7',
-        }
+        },
+    }, {
+        'url': 'https://roosterteeth.com/series/the-weird-place',
+        'playlist_count': 7,
+        'info_dict': {
+            'id': 'the-weird-place',
+            'title': 'The Weird Place',
+        },
     }, {
         'url': 'https://roosterteeth.com/series/role-initiative',
         'playlist_mincount': 16,
         'info_dict': {
             'id': 'role-initiative',
             'title': 'Role Initiative',
-        }
+        },
     }, {
         'url': 'https://roosterteeth.com/series/let-s-play-minecraft?season=9',
         'playlist_mincount': 50,
         'info_dict': {
             'id': 'let-s-play-minecraft-9',
             'title': 'Let\'s Play Minecraft - Season 9',
-        }
+        },
     }]
 
     def _entries(self, series_id, season_number):
         display_id = join_nonempty(series_id, season_number)
-        # TODO: extract bonus material
-        for data in self._download_json(
-                f'{self._API_BASE_URL}/shows/{series_id}/seasons?order=asc&order_by', display_id)['data']:
-            idx = traverse_obj(data, ('attributes', 'number'))
-            if season_number and idx != season_number:
-                continue
-            season_url = update_url_query(urljoin(self._API_BASE, data['links']['episodes']), {'per_page': 1000})
-            season = self._download_json(season_url, display_id, f'Downloading season {idx} JSON metadata')['data']
-            for episode in season:
+
+        def yield_episodes(data):
+            for episode in traverse_obj(data, ('data', lambda _, v: v['canonical_links']['self'])):
                 yield self.url_result(
-                    f'https://www.roosterteeth.com{episode["canonical_links"]["self"]}',
-                    RoosterTeethIE.ie_key(),
-                    **self._extract_video_info(episode))
+                    urljoin('https://www.roosterteeth.com', episode['canonical_links']['self']),
+                    RoosterTeethIE, **self._extract_video_info(episode))
+
+        series_data = self._download_json(
+            f'{self._API_BASE_URL}/shows/{series_id}/seasons?order=asc&order_by', display_id)
+        for season_data in traverse_obj(series_data, ('data', lambda _, v: v['links']['episodes'])):
+            idx = traverse_obj(season_data, ('attributes', 'number'))
+            if season_number is not None and idx != season_number:
+                continue
+            yield from yield_episodes(self._download_json(
+                urljoin(self._API_BASE, season_data['links']['episodes']), display_id,
+                f'Downloading season {idx} JSON metadata', query={'per_page': 1000}))
+
+        if season_number is None:  # extract series-level bonus features
+            yield from yield_episodes(self._download_json(
+                f'{self._API_BASE_URL}/shows/{series_id}/bonus_features?order=asc&order_by&per_page=1000',
+                display_id, 'Downloading bonus features JSON metadata', fatal=False))
 
     def _real_extract(self, url):
         series_id = self._match_id(url)