[adultswim] detect when video needs authentication
[youtube-dl] / youtube_dl / extractor / adultswim.py
1 # coding: utf-8
2 from __future__ import unicode_literals
3
4 import re
5
6 from .common import InfoExtractor
7 from ..utils import (
8     determine_ext,
9     ExtractorError,
10     float_or_none,
11     xpath_text,
12 )
13
14
15 class AdultSwimIE(InfoExtractor):
16     _VALID_URL = r'https?://(?:www\.)?adultswim\.com/videos/(?P<is_playlist>playlists/)?(?P<show_path>[^/]+)/(?P<episode_path>[^/?#]+)/?'
17
18     _TESTS = [{
19         'url': 'http://adultswim.com/videos/rick-and-morty/pilot',
20         'playlist': [
21             {
22                 'md5': '247572debc75c7652f253c8daa51a14d',
23                 'info_dict': {
24                     'id': 'rQxZvXQ4ROaSOqq-or2Mow-0',
25                     'ext': 'flv',
26                     'title': 'Rick and Morty - Pilot Part 1',
27                     'description': "Rick moves in with his daughter's family and establishes himself as a bad influence on his grandson, Morty. "
28                 },
29             },
30             {
31                 'md5': '77b0e037a4b20ec6b98671c4c379f48d',
32                 'info_dict': {
33                     'id': 'rQxZvXQ4ROaSOqq-or2Mow-3',
34                     'ext': 'flv',
35                     'title': 'Rick and Morty - Pilot Part 4',
36                     'description': "Rick moves in with his daughter's family and establishes himself as a bad influence on his grandson, Morty. "
37                 },
38             },
39         ],
40         'info_dict': {
41             'id': 'rQxZvXQ4ROaSOqq-or2Mow',
42             'title': 'Rick and Morty - Pilot',
43             'description': "Rick moves in with his daughter's family and establishes himself as a bad influence on his grandson, Morty. "
44         },
45         'skip': 'This video is only available for registered users',
46     }, {
47         'url': 'http://www.adultswim.com/videos/playlists/american-parenting/putting-francine-out-of-business/',
48         'playlist': [
49             {
50                 'md5': '2eb5c06d0f9a1539da3718d897f13ec5',
51                 'info_dict': {
52                     'id': '-t8CamQlQ2aYZ49ItZCFog-0',
53                     'ext': 'flv',
54                     'title': 'American Dad - Putting Francine Out of Business',
55                     'description': 'Stan hatches a plan to get Francine out of the real estate business.Watch more American Dad on [adult swim].'
56                 },
57             }
58         ],
59         'info_dict': {
60             'id': '-t8CamQlQ2aYZ49ItZCFog',
61             'title': 'American Dad - Putting Francine Out of Business',
62             'description': 'Stan hatches a plan to get Francine out of the real estate business.Watch more American Dad on [adult swim].'
63         },
64     }, {
65         'url': 'http://www.adultswim.com/videos/tim-and-eric-awesome-show-great-job/dr-steve-brule-for-your-wine/',
66         'playlist': [
67             {
68                 'md5': '3e346a2ab0087d687a05e1e7f3b3e529',
69                 'info_dict': {
70                     'id': 'sY3cMUR_TbuE4YmdjzbIcQ-0',
71                     'ext': 'flv',
72                     'title': 'Tim and Eric Awesome Show Great Job! - Dr. Steve Brule, For Your Wine',
73                     'description': 'Dr. Brule reports live from Wine Country with a special report on wines.  \r\nWatch Tim and Eric Awesome Show Great Job! episode #20, "Embarrassed" on Adult Swim.\r\n\r\n',
74                 },
75             }
76         ],
77         'info_dict': {
78             'id': 'sY3cMUR_TbuE4YmdjzbIcQ',
79             'title': 'Tim and Eric Awesome Show Great Job! - Dr. Steve Brule, For Your Wine',
80             'description': 'Dr. Brule reports live from Wine Country with a special report on wines.  \r\nWatch Tim and Eric Awesome Show Great Job! episode #20, "Embarrassed" on Adult Swim.\r\n\r\n',
81         },
82     }]
83
84     @staticmethod
85     def find_video_info(collection, slug):
86         for video in collection.get('videos'):
87             if video.get('slug') == slug:
88                 if video.get('auth'):
89                     raise ExtractorError('This video is only available for registered users', expected=True)
90                 else:
91                     return video
92
93     @staticmethod
94     def find_collection_by_linkURL(collections, linkURL):
95         for collection in collections:
96             if collection.get('linkURL') == linkURL:
97                 return collection
98
99     @staticmethod
100     def find_collection_containing_video(collections, slug):
101         for collection in collections:
102             for video in collection.get('videos'):
103                 if video.get('slug') == slug:
104                     if video.get('auth'):
105                         raise ExtractorError('This video is only available for registered users', expected=True)
106                     else:
107                         return collection, video
108         return None, None
109
110     def _real_extract(self, url):
111         mobj = re.match(self._VALID_URL, url)
112         show_path = mobj.group('show_path')
113         episode_path = mobj.group('episode_path')
114         is_playlist = True if mobj.group('is_playlist') else False
115
116         webpage = self._download_webpage(url, episode_path)
117
118         # Extract the value of `bootstrappedData` from the Javascript in the page.
119         bootstrapped_data = self._parse_json(self._search_regex(
120             r'var bootstrappedData = ({.*});', webpage, 'bootstraped data'), episode_path)
121
122         # Downloading videos from a /videos/playlist/ URL needs to be handled differently.
123         # NOTE: We are only downloading one video (the current one) not the playlist
124         if is_playlist:
125             collections = bootstrapped_data['playlists']['collections']
126             collection = self.find_collection_by_linkURL(collections, show_path)
127             video_info = self.find_video_info(collection, episode_path)
128
129             show_title = video_info['showTitle']
130             segment_ids = [video_info['videoPlaybackID']]
131         else:
132             collections = bootstrapped_data['show']['collections']
133             collection, video_info = self.find_collection_containing_video(collections, episode_path)
134             # Video wasn't found in the collections, let's try `slugged_video`.
135             if video_info is None:
136                 if bootstrapped_data.get('slugged_video', {}).get('slug') == episode_path:
137                     video_info = bootstrapped_data['slugged_video']
138                     if video_info.get('auth'):
139                         raise ExtractorError('This video is only available for registered users', expected=True)
140                 else:
141                     raise ExtractorError('Unable to find video info')
142
143             show = bootstrapped_data['show']
144             show_title = show['title']
145             stream = video_info.get('stream')
146             clips = [stream] if stream else video_info['clips']
147             segment_ids = [clip['videoPlaybackID'] for clip in clips]
148
149         episode_id = video_info['id']
150         episode_title = video_info['title']
151         episode_description = video_info['description']
152         episode_duration = video_info.get('duration')
153
154         entries = []
155         for part_num, segment_id in enumerate(segment_ids):
156             segment_url = 'http://www.adultswim.com/videos/api/v0/assets?id=%s&platform=desktop' % segment_id
157
158             segment_title = '%s - %s' % (show_title, episode_title)
159             if len(segment_ids) > 1:
160                 segment_title += ' Part %d' % (part_num + 1)
161
162             idoc = self._download_xml(
163                 segment_url, segment_title,
164                 'Downloading segment information', 'Unable to download segment information')
165
166             segment_duration = float_or_none(
167                 xpath_text(idoc, './/trt', 'segment duration').strip())
168
169             formats = []
170             file_els = idoc.findall('.//files/file') or idoc.findall('./files/file')
171
172             unique_urls = []
173             unique_file_els = []
174             for file_el in file_els:
175                 media_url = file_el.text
176                 if not media_url or determine_ext(media_url) == 'f4m':
177                     continue
178                 if file_el.text not in unique_urls:
179                     unique_urls.append(file_el.text)
180                     unique_file_els.append(file_el)
181
182             for file_el in unique_file_els:
183                 bitrate = file_el.attrib.get('bitrate')
184                 ftype = file_el.attrib.get('type')
185                 media_url = file_el.text
186                 if determine_ext(media_url) == 'm3u8':
187                     formats.extend(self._extract_m3u8_formats(
188                         media_url, segment_title, 'mp4', 'm3u8_native', preference=0, m3u8_id='hls'))
189                 else:
190                     formats.append({
191                         'format_id': '%s_%s' % (bitrate, ftype),
192                         'url': file_el.text.strip(),
193                         # The bitrate may not be a number (for example: 'iphone')
194                         'tbr': int(bitrate) if bitrate.isdigit() else None,
195                     })
196
197             self._sort_formats(formats)
198
199             entries.append({
200                 'id': segment_id,
201                 'title': segment_title,
202                 'formats': formats,
203                 'duration': segment_duration,
204                 'description': episode_description
205             })
206
207         return {
208             '_type': 'playlist',
209             'id': episode_id,
210             'display_id': episode_path,
211             'entries': entries,
212             'title': '%s - %s' % (show_title, episode_title),
213             'description': episode_description,
214             'duration': episode_duration
215         }