1# coding: utf-8
2from .common import InfoExtractor
3from ..compat import compat_HTTPError
4from ..utils import (
5    ExtractorError,
6    int_or_none,
7    join_nonempty,
8    LazyList,
9    parse_qs,
10    str_or_none,
11    traverse_obj,
12    url_or_none,
13    urlencode_postdata,
14    urljoin,
15    update_url_query,
16)
17
18
19class RoosterTeethBaseIE(InfoExtractor):
20    _NETRC_MACHINE = 'roosterteeth'
21    _API_BASE = 'https://svod-be.roosterteeth.com'
22    _API_BASE_URL = f'{_API_BASE}/api/v1'
23
24    def _login(self):
25        username, password = self._get_login_info()
26        if username is None:
27            return
28        if self._get_cookies(self._API_BASE_URL).get('rt_access_token'):
29            return
30
31        try:
32            self._download_json(
33                'https://auth.roosterteeth.com/oauth/token',
34                None, 'Logging in', data=urlencode_postdata({
35                    'client_id': '4338d2b4bdc8db1239360f28e72f0d9ddb1fd01e7a38fbb07b4b1f4ba4564cc5',
36                    'grant_type': 'password',
37                    'username': username,
38                    'password': password,
39                }))
40        except ExtractorError as e:
41            msg = 'Unable to login'
42            if isinstance(e.cause, compat_HTTPError) and e.cause.code == 401:
43                resp = self._parse_json(e.cause.read().decode(), None, fatal=False)
44                if resp:
45                    error = resp.get('extra_info') or resp.get('error_description') or resp.get('error')
46                    if error:
47                        msg += ': ' + error
48            self.report_warning(msg)
49
50    def _real_initialize(self):
51        self._login()
52
53    def _extract_video_info(self, data):
54        thumbnails = []
55        for image in traverse_obj(data, ('included', 'images')):
56            if image.get('type') not in ('episode_image', 'bonus_feature_image'):
57                continue
58            thumbnails.extend([{
59                'id': name,
60                'url': url,
61            } for name, url in (image.get('attributes') or {}).items() if url_or_none(url)])
62
63        attributes = data.get('attributes') or {}
64        title = traverse_obj(attributes, 'title', 'display_title')
65        sub_only = attributes.get('is_sponsors_only')
66
67        return {
68            'id': str(data.get('id')),
69            'display_id': attributes.get('slug'),
70            'title': title,
71            'description': traverse_obj(attributes, 'description', 'caption'),
72            'series': attributes.get('show_title'),
73            'season_number': int_or_none(attributes.get('season_number')),
74            'season_id': attributes.get('season_id'),
75            'episode': title,
76            'episode_number': int_or_none(attributes.get('number')),
77            'episode_id': str_or_none(data.get('uuid')),
78            'channel_id': attributes.get('channel_id'),
79            'duration': int_or_none(attributes.get('length')),
80            'thumbnails': thumbnails,
81            'availability': self._availability(
82                needs_premium=sub_only, needs_subscription=sub_only, needs_auth=sub_only,
83                is_private=False, is_unlisted=False),
84            'tags': attributes.get('genres')
85        }
86
87
88class RoosterTeethIE(RoosterTeethBaseIE):
89    _VALID_URL = r'https?://(?:.+?\.)?roosterteeth\.com/(?:episode|watch)/(?P<id>[^/?#&]+)'
90    _TESTS = [{
91        'url': 'http://roosterteeth.com/episode/million-dollars-but-season-2-million-dollars-but-the-game-announcement',
92        'info_dict': {
93            'id': '9156',
94            'display_id': 'million-dollars-but-season-2-million-dollars-but-the-game-announcement',
95            'ext': 'mp4',
96            'title': 'Million Dollars, But... The Game Announcement',
97            'description': 'md5:168a54b40e228e79f4ddb141e89fe4f5',
98            'thumbnail': r're:^https?://.*\.png$',
99            'series': 'Million Dollars, But...',
100            'episode': 'Million Dollars, But... The Game Announcement',
101        },
102        'params': {'skip_download': True},
103    }, {
104        'url': 'https://roosterteeth.com/watch/rwby-bonus-25',
105        'info_dict': {
106            'id': '40432',
107            'display_id': 'rwby-bonus-25',
108            'title': 'Grimm',
109            'description': 'md5:f30ff570741213418a8d2c19868b93ab',
110            'episode': 'Grimm',
111            'channel_id': '92f780eb-ebfe-4bf5-a3b5-c6ad5460a5f1',
112            'thumbnail': r're:^https?://.*\.(png|jpe?g)$',
113            'ext': 'mp4',
114        },
115        'params': {'skip_download': True},
116    }, {
117        'url': 'http://achievementhunter.roosterteeth.com/episode/off-topic-the-achievement-hunter-podcast-2016-i-didn-t-think-it-would-pass-31',
118        'only_matching': True,
119    }, {
120        'url': 'http://funhaus.roosterteeth.com/episode/funhaus-shorts-2016-austin-sucks-funhaus-shorts',
121        'only_matching': True,
122    }, {
123        'url': 'http://screwattack.roosterteeth.com/episode/death-battle-season-3-mewtwo-vs-shadow',
124        'only_matching': True,
125    }, {
126        'url': 'http://theknow.roosterteeth.com/episode/the-know-game-news-season-1-boring-steam-sales-are-better',
127        'only_matching': True,
128    }, {
129        # only available for FIRST members
130        'url': 'http://roosterteeth.com/episode/rt-docs-the-world-s-greatest-head-massage-the-world-s-greatest-head-massage-an-asmr-journey-part-one',
131        'only_matching': True,
132    }, {
133        'url': 'https://roosterteeth.com/watch/million-dollars-but-season-2-million-dollars-but-the-game-announcement',
134        'only_matching': True,
135    }]
136
137    def _real_extract(self, url):
138        display_id = self._match_id(url)
139        api_episode_url = f'{self._API_BASE_URL}/watch/{display_id}'
140
141        try:
142            video_data = self._download_json(
143                api_episode_url + '/videos', display_id,
144                'Downloading video JSON metadata')['data'][0]
145            m3u8_url = video_data['attributes']['url']
146            # XXX: additional URL at video_data['links']['download']
147        except ExtractorError as e:
148            if isinstance(e.cause, compat_HTTPError) and e.cause.code == 403:
149                if self._parse_json(e.cause.read().decode(), display_id).get('access') is False:
150                    self.raise_login_required(
151                        '%s is only available for FIRST members' % display_id)
152            raise
153
154        formats, subtitles = self._extract_m3u8_formats_and_subtitles(
155            m3u8_url, display_id, 'mp4', 'm3u8_native', m3u8_id='hls')
156        self._sort_formats(formats)
157
158        episode = self._download_json(
159            api_episode_url, display_id,
160            'Downloading episode JSON metadata')['data'][0]
161
162        return {
163            'display_id': display_id,
164            'formats': formats,
165            'subtitles': subtitles,
166            **self._extract_video_info(episode)
167        }
168
169
170class RoosterTeethSeriesIE(RoosterTeethBaseIE):
171    _VALID_URL = r'https?://(?:.+?\.)?roosterteeth\.com/series/(?P<id>[^/?#&]+)'
172    _TESTS = [{
173        'url': 'https://roosterteeth.com/series/rwby?season=7',
174        'playlist_count': 13,
175        'info_dict': {
176            'id': 'rwby-7',
177            'title': 'RWBY - Season 7',
178        }
179    }, {
180        'url': 'https://roosterteeth.com/series/role-initiative',
181        'playlist_mincount': 16,
182        'info_dict': {
183            'id': 'role-initiative',
184            'title': 'Role Initiative',
185        }
186    }, {
187        'url': 'https://roosterteeth.com/series/let-s-play-minecraft?season=9',
188        'playlist_mincount': 50,
189        'info_dict': {
190            'id': 'let-s-play-minecraft-9',
191            'title': 'Let\'s Play Minecraft - Season 9',
192        }
193    }]
194
195    def _entries(self, series_id, season_number):
196        display_id = join_nonempty(series_id, season_number)
197        # TODO: extract bonus material
198        for data in self._download_json(
199                f'{self._API_BASE_URL}/shows/{series_id}/seasons?order=asc&order_by', display_id)['data']:
200            idx = traverse_obj(data, ('attributes', 'number'))
201            if season_number and idx != season_number:
202                continue
203            season_url = update_url_query(urljoin(self._API_BASE, data['links']['episodes']), {'per_page': 1000})
204            season = self._download_json(season_url, display_id, f'Downloading season {idx} JSON metadata')['data']
205            for episode in season:
206                yield self.url_result(
207                    f'https://www.roosterteeth.com{episode["canonical_links"]["self"]}',
208                    RoosterTeethIE.ie_key(),
209                    **self._extract_video_info(episode))
210
211    def _real_extract(self, url):
212        series_id = self._match_id(url)
213        season_number = traverse_obj(parse_qs(url), ('season', 0), expected_type=int_or_none)
214
215        entries = LazyList(self._entries(series_id, season_number))
216        return self.playlist_result(
217            entries,
218            join_nonempty(series_id, season_number),
219            join_nonempty(entries[0].get('series'), season_number, delim=' - Season '))
220