[ign] improve extraction and extract uploader_id
[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     }, {
46         'url': 'http://www.adultswim.com/videos/playlists/american-parenting/putting-francine-out-of-business/',
47         'playlist': [
48             {
49                 'md5': '2eb5c06d0f9a1539da3718d897f13ec5',
50                 'info_dict': {
51                     'id': '-t8CamQlQ2aYZ49ItZCFog-0',
52                     'ext': 'flv',
53                     'title': 'American Dad - Putting Francine Out of Business',
54                     'description': 'Stan hatches a plan to get Francine out of the real estate business.Watch more American Dad on [adult swim].'
55                 },
56             }
57         ],
58         'info_dict': {
59             'id': '-t8CamQlQ2aYZ49ItZCFog',
60             'title': 'American Dad - Putting Francine Out of Business',
61             'description': 'Stan hatches a plan to get Francine out of the real estate business.Watch more American Dad on [adult swim].'
62         },
63     }, {
64         'url': 'http://www.adultswim.com/videos/tim-and-eric-awesome-show-great-job/dr-steve-brule-for-your-wine/',
65         'playlist': [
66             {
67                 'md5': '3e346a2ab0087d687a05e1e7f3b3e529',
68                 'info_dict': {
69                     'id': 'sY3cMUR_TbuE4YmdjzbIcQ-0',
70                     'ext': 'flv',
71                     'title': 'Tim and Eric Awesome Show Great Job! - Dr. Steve Brule, For Your Wine',
72                     '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',
73                 },
74             }
75         ],
76         'info_dict': {
77             'id': 'sY3cMUR_TbuE4YmdjzbIcQ',
78             'title': 'Tim and Eric Awesome Show Great Job! - Dr. Steve Brule, For Your Wine',
79             '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',
80         },
81     }]
82
83     @staticmethod
84     def find_video_info(collection, slug):
85         for video in collection.get('videos'):
86             if video.get('slug') == slug:
87                 return video
88
89     @staticmethod
90     def find_collection_by_linkURL(collections, linkURL):
91         for collection in collections:
92             if collection.get('linkURL') == linkURL:
93                 return collection
94
95     @staticmethod
96     def find_collection_containing_video(collections, slug):
97         for collection in collections:
98             for video in collection.get('videos'):
99                 if video.get('slug') == slug:
100                     return collection, video
101         return None, None
102
103     def _real_extract(self, url):
104         mobj = re.match(self._VALID_URL, url)
105         show_path = mobj.group('show_path')
106         episode_path = mobj.group('episode_path')
107         is_playlist = True if mobj.group('is_playlist') else False
108
109         webpage = self._download_webpage(url, episode_path)
110
111         # Extract the value of `bootstrappedData` from the Javascript in the page.
112         bootstrapped_data = self._parse_json(self._search_regex(
113             r'var bootstrappedData = ({.*});', webpage, 'bootstraped data'), episode_path)
114
115         # Downloading videos from a /videos/playlist/ URL needs to be handled differently.
116         # NOTE: We are only downloading one video (the current one) not the playlist
117         if is_playlist:
118             collections = bootstrapped_data['playlists']['collections']
119             collection = self.find_collection_by_linkURL(collections, show_path)
120             video_info = self.find_video_info(collection, episode_path)
121
122             show_title = video_info['showTitle']
123             segment_ids = [video_info['videoPlaybackID']]
124         else:
125             collections = bootstrapped_data['show']['collections']
126             collection, video_info = self.find_collection_containing_video(collections, episode_path)
127             # Video wasn't found in the collections, let's try `slugged_video`.
128             if video_info is None:
129                 if bootstrapped_data.get('slugged_video', {}).get('slug') == episode_path:
130                     video_info = bootstrapped_data['slugged_video']
131                 else:
132                     raise ExtractorError('Unable to find video info')
133
134             show = bootstrapped_data['show']
135             show_title = show['title']
136             stream = video_info.get('stream')
137             clips = [stream] if stream else video_info['clips']
138             segment_ids = [clip['videoPlaybackID'] for clip in clips]
139
140         episode_id = video_info['id']
141         episode_title = video_info['title']
142         episode_description = video_info['description']
143         episode_duration = video_info.get('duration')
144
145         entries = []
146         for part_num, segment_id in enumerate(segment_ids):
147             segment_url = 'http://www.adultswim.com/videos/api/v0/assets?id=%s&platform=desktop' % segment_id
148
149             segment_title = '%s - %s' % (show_title, episode_title)
150             if len(segment_ids) > 1:
151                 segment_title += ' Part %d' % (part_num + 1)
152
153             idoc = self._download_xml(
154                 segment_url, segment_title,
155                 'Downloading segment information', 'Unable to download segment information')
156
157             segment_duration = float_or_none(
158                 xpath_text(idoc, './/trt', 'segment duration').strip())
159
160             formats = []
161             file_els = idoc.findall('.//files/file') or idoc.findall('./files/file')
162
163             unique_urls = []
164             unique_file_els = []
165             for file_el in file_els:
166                 media_url = file_el.text
167                 if not media_url or determine_ext(media_url) == 'f4m':
168                     continue
169                 if file_el.text not in unique_urls:
170                     unique_urls.append(file_el.text)
171                     unique_file_els.append(file_el)
172
173             for file_el in unique_file_els:
174                 bitrate = file_el.attrib.get('bitrate')
175                 ftype = file_el.attrib.get('type')
176                 media_url = file_el.text
177                 if determine_ext(media_url) == 'm3u8':
178                     formats.extend(self._extract_m3u8_formats(
179                         media_url, segment_title, 'mp4', 'm3u8_native', preference=0, m3u8_id='hls'))
180                 else:
181                     formats.append({
182                         'format_id': '%s_%s' % (bitrate, ftype),
183                         'url': file_el.text.strip(),
184                         # The bitrate may not be a number (for example: 'iphone')
185                         'tbr': int(bitrate) if bitrate.isdigit() else None,
186                     })
187
188             self._sort_formats(formats)
189
190             entries.append({
191                 'id': segment_id,
192                 'title': segment_title,
193                 'formats': formats,
194                 'duration': segment_duration,
195                 'description': episode_description
196             })
197
198         return {
199             '_type': 'playlist',
200             'id': episode_id,
201             'display_id': episode_path,
202             'entries': entries,
203             'title': '%s - %s' % (show_title, episode_title),
204             'description': episode_description,
205             'duration': episode_duration
206         }