[roosterteeth] fix free episode extraction(#16094)
[youtube-dl] / youtube_dl / extractor / roosterteeth.py
1 # coding: utf-8
2 from __future__ import unicode_literals
3
4 import re
5
6 from .common import InfoExtractor
7 from ..compat import (
8     compat_HTTPError,
9     compat_str,
10 )
11 from ..utils import (
12     ExtractorError,
13     int_or_none,
14     str_or_none,
15     urlencode_postdata,
16 )
17
18
19 class RoosterTeethIE(InfoExtractor):
20     _VALID_URL = r'https?://(?:.+?\.)?roosterteeth\.com/episode/(?P<id>[^/?#&]+)'
21     _LOGIN_URL = 'https://roosterteeth.com/login'
22     _NETRC_MACHINE = 'roosterteeth'
23     _TESTS = [{
24         'url': 'http://roosterteeth.com/episode/million-dollars-but-season-2-million-dollars-but-the-game-announcement',
25         'md5': 'e2bd7764732d785ef797700a2489f212',
26         'info_dict': {
27             'id': '9156',
28             'display_id': 'million-dollars-but-season-2-million-dollars-but-the-game-announcement',
29             'ext': 'mp4',
30             'title': 'Million Dollars, But... The Game Announcement',
31             'description': 'md5:168a54b40e228e79f4ddb141e89fe4f5',
32             'thumbnail': r're:^https?://.*\.png$',
33             'series': 'Million Dollars, But...',
34             'episode': 'Million Dollars, But... The Game Announcement',
35         },
36     }, {
37         'url': 'http://achievementhunter.roosterteeth.com/episode/off-topic-the-achievement-hunter-podcast-2016-i-didn-t-think-it-would-pass-31',
38         'only_matching': True,
39     }, {
40         'url': 'http://funhaus.roosterteeth.com/episode/funhaus-shorts-2016-austin-sucks-funhaus-shorts',
41         'only_matching': True,
42     }, {
43         'url': 'http://screwattack.roosterteeth.com/episode/death-battle-season-3-mewtwo-vs-shadow',
44         'only_matching': True,
45     }, {
46         'url': 'http://theknow.roosterteeth.com/episode/the-know-game-news-season-1-boring-steam-sales-are-better',
47         'only_matching': True,
48     }, {
49         # only available for FIRST members
50         'url': 'http://roosterteeth.com/episode/rt-docs-the-world-s-greatest-head-massage-the-world-s-greatest-head-massage-an-asmr-journey-part-one',
51         'only_matching': True,
52     }]
53
54     def _login(self):
55         username, password = self._get_login_info()
56         if username is None:
57             return
58
59         login_page = self._download_webpage(
60             self._LOGIN_URL, None,
61             note='Downloading login page',
62             errnote='Unable to download login page')
63
64         login_form = self._hidden_inputs(login_page)
65
66         login_form.update({
67             'username': username,
68             'password': password,
69         })
70
71         login_request = self._download_webpage(
72             self._LOGIN_URL, None,
73             note='Logging in',
74             data=urlencode_postdata(login_form),
75             headers={
76                 'Referer': self._LOGIN_URL,
77             })
78
79         if not any(re.search(p, login_request) for p in (
80                 r'href=["\']https?://(?:www\.)?roosterteeth\.com/logout"',
81                 r'>Sign Out<')):
82             error = self._html_search_regex(
83                 r'(?s)<div[^>]+class=(["\']).*?\balert-danger\b.*?\1[^>]*>(?:\s*<button[^>]*>.*?</button>)?(?P<error>.+?)</div>',
84                 login_request, 'alert', default=None, group='error')
85             if error:
86                 raise ExtractorError('Unable to login: %s' % error, expected=True)
87             raise ExtractorError('Unable to log in')
88
89     def _real_initialize(self):
90         self._login()
91
92     def _real_extract(self, url):
93         display_id = self._match_id(url)
94         api_episode_url = 'https://svod-be.roosterteeth.com/api/v1/episodes/%s' % display_id
95
96         try:
97             m3u8_url = self._download_json(
98                 api_episode_url + '/videos', display_id,
99                 'Downloading video JSON metadata')['data'][0]['attributes']['url']
100         except ExtractorError as e:
101             if isinstance(e.cause, compat_HTTPError) and e.cause.code == 403:
102                 if self._parse_json(e.cause.read().decode(), display_id).get('access') is False:
103                     self.raise_login_required(
104                         '%s is only available for FIRST members' % display_id)
105             raise
106
107         formats = self._extract_m3u8_formats(
108             m3u8_url, display_id, 'mp4', 'm3u8_native', m3u8_id='hls')
109         self._sort_formats(formats)
110
111         episode = self._download_json(
112             api_episode_url, display_id,
113             'Downloading episode JSON metadata')['data'][0]
114         attributes = episode['attributes']
115         title = attributes.get('title') or attributes['display_title']
116         video_id = compat_str(episode['id'])
117
118         thumbnails = []
119         for image in episode.get('included', {}).get('images', []):
120             if image.get('type') == 'episode_image':
121                 img_attributes = image.get('attributes') or {}
122                 for k in ('thumb', 'small', 'medium', 'large'):
123                     img_url = img_attributes.get(k)
124                     if img_url:
125                         thumbnails.append({
126                             'id': k,
127                             'url': img_url,
128                         })
129
130         return {
131             'id': video_id,
132             'display_id': display_id,
133             'title': title,
134             'description': attributes.get('description') or attributes.get('caption'),
135             'thumbnails': thumbnails,
136             'series': attributes.get('show_title'),
137             'season_number': int_or_none(attributes.get('season_number')),
138             'season_id': attributes.get('season_id'),
139             'episode': title,
140             'episode_number': int_or_none(attributes.get('number')),
141             'episode_id': str_or_none(episode.get('uuid')),
142             'formats': formats,
143             'channel_id': attributes.get('channel_id'),
144             'duration': int_or_none(attributes.get('length')),
145         }