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