e427b9821cfe8b7aab793e7c814474efbac4477e
[youtube-dl] / youtube_dl / extractor / comedycentral.py
1 from __future__ import unicode_literals
2
3 import re
4
5 from .common import InfoExtractor
6 from .mtv import MTVServicesInfoExtractor
7 from ..compat import (
8     compat_str,
9     compat_urllib_parse,
10 )
11 from ..utils import (
12     ExtractorError,
13     float_or_none,
14     unified_strdate,
15 )
16
17
18 class ComedyCentralIE(MTVServicesInfoExtractor):
19     _VALID_URL = r'''(?x)https?://(?:www\.)?cc\.com/
20         (video-clips|episodes|cc-studios|video-collections|full-episodes)
21         /(?P<title>.*)'''
22     _FEED_URL = 'http://comedycentral.com/feeds/mrss/'
23
24     _TEST = {
25         'url': 'http://www.cc.com/video-clips/kllhuv/stand-up-greg-fitzsimmons--uncensored---too-good-of-a-mother',
26         'md5': 'c4f48e9eda1b16dd10add0744344b6d8',
27         'info_dict': {
28             'id': 'cef0cbb3-e776-4bc9-b62e-8016deccb354',
29             'ext': 'mp4',
30             'title': 'CC:Stand-Up|Greg Fitzsimmons: Life on Stage|Uncensored - Too Good of a Mother',
31             'description': 'After a certain point, breastfeeding becomes c**kblocking.',
32         },
33     }
34
35
36 class ComedyCentralShowsIE(MTVServicesInfoExtractor):
37     IE_DESC = 'The Daily Show / The Colbert Report'
38     # urls can be abbreviations like :thedailyshow
39     # urls for episodes like:
40     # or urls for clips like: http://www.thedailyshow.com/watch/mon-december-10-2012/any-given-gun-day
41     #                     or: http://www.colbertnation.com/the-colbert-report-videos/421667/november-29-2012/moon-shattering-news
42     #                     or: http://www.colbertnation.com/the-colbert-report-collections/422008/festival-of-lights/79524
43     _VALID_URL = r'''(?x)^(:(?P<shortname>tds|thedailyshow)
44                       |https?://(:www\.)?
45                           (?P<showname>thedailyshow|thecolbertreport)\.(?:cc\.)?com/
46                          ((?:full-)?episodes/(?:[0-9a-z]{6}/)?(?P<episode>.*)|
47                           (?P<clip>
48                               (?:(?:guests/[^/]+|videos|video-playlists|special-editions|news-team/[^/]+)/[^/]+/(?P<videotitle>[^/?#]+))
49                               |(the-colbert-report-(videos|collections)/(?P<clipID>[0-9]+)/[^/]*/(?P<cntitle>.*?))
50                               |(watch/(?P<date>[^/]*)/(?P<tdstitle>.*))
51                           )|
52                           (?P<interview>
53                               extended-interviews/(?P<interID>[0-9a-z]+)/
54                               (?:playlist_tds_extended_)?(?P<interview_title>[^/?#]*?)
55                               (?:/[^/?#]?|[?#]|$))))
56                      '''
57     _TESTS = [{
58         'url': 'http://thedailyshow.cc.com/watch/thu-december-13-2012/kristen-stewart',
59         'md5': '4e2f5cb088a83cd8cdb7756132f9739d',
60         'info_dict': {
61             'id': 'ab9ab3e7-5a98-4dbe-8b21-551dc0523d55',
62             'ext': 'mp4',
63             'upload_date': '20121213',
64             'description': 'Kristen Stewart learns to let loose in "On the Road."',
65             'uploader': 'thedailyshow',
66             'title': 'thedailyshow kristen-stewart part 1',
67         }
68     }, {
69         'url': 'http://thedailyshow.cc.com/extended-interviews/b6364d/sarah-chayes-extended-interview',
70         'info_dict': {
71             'id': 'sarah-chayes-extended-interview',
72             'description': 'Carnegie Endowment Senior Associate Sarah Chayes discusses how corrupt institutions function throughout the world in her book "Thieves of State: Why Corruption Threatens Global Security."',
73             'title': 'thedailyshow Sarah Chayes Extended Interview',
74         },
75         'playlist': [
76             {
77                 'info_dict': {
78                     'id': '0baad492-cbec-4ec1-9e50-ad91c291127f',
79                     'ext': 'mp4',
80                     'upload_date': '20150129',
81                     'description': 'Carnegie Endowment Senior Associate Sarah Chayes discusses how corrupt institutions function throughout the world in her book "Thieves of State: Why Corruption Threatens Global Security."',
82                     'uploader': 'thedailyshow',
83                     'title': 'thedailyshow sarah-chayes-extended-interview part 1',
84                 },
85             },
86             {
87                 'info_dict': {
88                     'id': '1e4fb91b-8ce7-4277-bd7c-98c9f1bbd283',
89                     'ext': 'mp4',
90                     'upload_date': '20150129',
91                     'description': 'Carnegie Endowment Senior Associate Sarah Chayes discusses how corrupt institutions function throughout the world in her book "Thieves of State: Why Corruption Threatens Global Security."',
92                     'uploader': 'thedailyshow',
93                     'title': 'thedailyshow sarah-chayes-extended-interview part 2',
94                 },
95             },
96         ],
97         'params': {
98             'skip_download': True,
99         },
100     }, {
101         'url': 'http://thedailyshow.cc.com/extended-interviews/xm3fnq/andrew-napolitano-extended-interview',
102         'only_matching': True,
103     }, {
104         'url': 'http://thecolbertreport.cc.com/videos/29w6fx/-realhumanpraise-for-fox-news',
105         'only_matching': True,
106     }, {
107         'url': 'http://thecolbertreport.cc.com/videos/gh6urb/neil-degrasse-tyson-pt--1?xrs=eml_col_031114',
108         'only_matching': True,
109     }, {
110         'url': 'http://thedailyshow.cc.com/guests/michael-lewis/3efna8/exclusive---michael-lewis-extended-interview-pt--3',
111         'only_matching': True,
112     }, {
113         'url': 'http://thedailyshow.cc.com/episodes/sy7yv0/april-8--2014---denis-leary',
114         'only_matching': True,
115     }, {
116         'url': 'http://thecolbertreport.cc.com/episodes/8ase07/april-8--2014---jane-goodall',
117         'only_matching': True,
118     }, {
119         'url': 'http://thedailyshow.cc.com/video-playlists/npde3s/the-daily-show-19088-highlights',
120         'only_matching': True,
121     }, {
122         'url': 'http://thedailyshow.cc.com/video-playlists/t6d9sg/the-daily-show-20038-highlights/be3cwo',
123         'only_matching': True,
124     }, {
125         'url': 'http://thedailyshow.cc.com/special-editions/2l8fdb/special-edition---a-look-back-at-food',
126         'only_matching': True,
127     }, {
128         'url': 'http://thedailyshow.cc.com/news-team/michael-che/7wnfel/we-need-to-talk-about-israel',
129         'only_matching': True,
130     }]
131
132     _available_formats = ['3500', '2200', '1700', '1200', '750', '400']
133
134     _video_extensions = {
135         '3500': 'mp4',
136         '2200': 'mp4',
137         '1700': 'mp4',
138         '1200': 'mp4',
139         '750': 'mp4',
140         '400': 'mp4',
141     }
142     _video_dimensions = {
143         '3500': (1280, 720),
144         '2200': (960, 540),
145         '1700': (768, 432),
146         '1200': (640, 360),
147         '750': (512, 288),
148         '400': (384, 216),
149     }
150
151     def _real_extract(self, url):
152         mobj = re.match(self._VALID_URL, url)
153
154         if mobj.group('shortname'):
155             if mobj.group('shortname') in ('tds', 'thedailyshow'):
156                 url = 'http://thedailyshow.cc.com/full-episodes/'
157             else:
158                 url = 'http://thecolbertreport.cc.com/full-episodes/'
159             mobj = re.match(self._VALID_URL, url, re.VERBOSE)
160             assert mobj is not None
161
162         if mobj.group('clip'):
163             if mobj.group('videotitle'):
164                 epTitle = mobj.group('videotitle')
165             elif mobj.group('showname') == 'thedailyshow':
166                 epTitle = mobj.group('tdstitle')
167             else:
168                 epTitle = mobj.group('cntitle')
169             dlNewest = False
170         elif mobj.group('interview'):
171             epTitle = mobj.group('interview_title')
172             dlNewest = False
173         else:
174             dlNewest = not mobj.group('episode')
175             if dlNewest:
176                 epTitle = mobj.group('showname')
177             else:
178                 epTitle = mobj.group('episode')
179         show_name = mobj.group('showname')
180
181         webpage, htmlHandle = self._download_webpage_handle(url, epTitle)
182         if dlNewest:
183             url = htmlHandle.geturl()
184             mobj = re.match(self._VALID_URL, url, re.VERBOSE)
185             if mobj is None:
186                 raise ExtractorError('Invalid redirected URL: ' + url)
187             if mobj.group('episode') == '':
188                 raise ExtractorError('Redirected URL is still not specific: ' + url)
189             epTitle = (mobj.group('episode') or mobj.group('videotitle')).rpartition('/')[-1]
190
191         mMovieParams = re.findall('(?:<param name="movie" value="|var url = ")(http://media.mtvnservices.com/([^"]*(?:episode|video).*?:.*?))"', webpage)
192         if len(mMovieParams) == 0:
193             # The Colbert Report embeds the information in a without
194             # a URL prefix; so extract the alternate reference
195             # and then add the URL prefix manually.
196
197             altMovieParams = re.findall('data-mgid="([^"]*(?:episode|video|playlist).*?:.*?)"', webpage)
198             if len(altMovieParams) == 0:
199                 raise ExtractorError('unable to find Flash URL in webpage ' + url)
200             else:
201                 mMovieParams = [("http://media.mtvnservices.com/" + altMovieParams[0], altMovieParams[0])]
202
203         uri = mMovieParams[0][1]
204         # Correct cc.com in uri
205         uri = re.sub(r'(episode:[^.]+)(\.cc)?\.com', r'\1.cc.com', uri)
206
207         index_url = 'http://%s.cc.com/feeds/mrss?%s' % (show_name, compat_urllib_parse.urlencode({'uri': uri}))
208         idoc = self._download_xml(
209             index_url, epTitle,
210             'Downloading show index', 'Unable to download episode index')
211
212         title = idoc.find('./channel/title').text
213         description = idoc.find('./channel/description').text
214
215         entries = []
216         item_els = idoc.findall('.//item')
217         for part_num, itemEl in enumerate(item_els):
218             upload_date = unified_strdate(itemEl.findall('./pubDate')[0].text)
219             thumbnail = itemEl.find('.//{http://search.yahoo.com/mrss/}thumbnail').attrib.get('url')
220
221             content = itemEl.find('.//{http://search.yahoo.com/mrss/}content')
222             duration = float_or_none(content.attrib.get('duration'))
223             mediagen_url = content.attrib['url']
224             guid = itemEl.find('./guid').text.rpartition(':')[-1]
225
226             cdoc = self._download_xml(
227                 mediagen_url, epTitle,
228                 'Downloading configuration for segment %d / %d' % (part_num + 1, len(item_els)))
229
230             turls = []
231             for rendition in cdoc.findall('.//rendition'):
232                 finfo = (rendition.attrib['bitrate'], rendition.findall('./src')[0].text)
233                 turls.append(finfo)
234
235             formats = []
236             for format, rtmp_video_url in turls:
237                 w, h = self._video_dimensions.get(format, (None, None))
238                 formats.append({
239                     'format_id': 'vhttp-%s' % format,
240                     'url': self._transform_rtmp_url(rtmp_video_url),
241                     'ext': self._video_extensions.get(format, 'mp4'),
242                     'height': h,
243                     'width': w,
244                 })
245                 formats.append({
246                     'format_id': 'rtmp-%s' % format,
247                     'url': rtmp_video_url.replace('viacomccstrm', 'viacommtvstrm'),
248                     'ext': self._video_extensions.get(format, 'mp4'),
249                     'height': h,
250                     'width': w,
251                 })
252                 self._sort_formats(formats)
253
254             subtitles = self._extract_subtitles(cdoc, guid)
255
256             virtual_id = show_name + ' ' + epTitle + ' part ' + compat_str(part_num + 1)
257             entries.append({
258                 'id': guid,
259                 'title': virtual_id,
260                 'formats': formats,
261                 'uploader': show_name,
262                 'upload_date': upload_date,
263                 'duration': duration,
264                 'thumbnail': thumbnail,
265                 'description': description,
266                 'subtitles': subtitles,
267             })
268
269         return {
270             '_type': 'playlist',
271             'id': epTitle,
272             'entries': entries,
273             'title': show_name + ' ' + title,
274             'description': description,
275         }
276
277 class TheDailyShowPodcastIE(InfoExtractor):
278     _VALID_URL = r'(?P<scheme>https?:)?//thedailyshow\.cc\.com/podcast/(?P<id>[a-z\-]+)'
279
280     def _real_extract(self, url):
281         display_id = self._match_id(url)
282         webpage = self._download_webpage(url, display_id)
283
284         player_url = self._search_regex(r'<iframe(?:\s+[^>]+)?\s*src="((?:https?:)?//html5-player\.libsyn\.com/embed/episode/id/[0-9]+)', webpage, 'player URL')
285         if player_url.startswith('//'):
286             mobj = re.match(self._VALID_URL, url)
287             scheme = mobj.group('scheme')
288             if not scheme:
289                 scheme = 'https:'
290             player_url = scheme + player_url
291
292         return {
293             '_type': 'url_transparent',
294             'url': player_url,
295         }