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