Merge remote-tracking branch 'Dineshs91/f4m-2.0'
[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 or :colbert
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|cr|colbert|colbertnation|colbertreport)
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]+)/(?:playlist_tds_extended_)?(?P<interview_title>.*?)(/.*?)?)))
53                      '''
54     _TESTS = [{
55         'url': 'http://thedailyshow.cc.com/watch/thu-december-13-2012/kristen-stewart',
56         'md5': '4e2f5cb088a83cd8cdb7756132f9739d',
57         'info_dict': {
58             'id': 'ab9ab3e7-5a98-4dbe-8b21-551dc0523d55',
59             'ext': 'mp4',
60             'upload_date': '20121213',
61             'description': 'Kristen Stewart learns to let loose in "On the Road."',
62             'uploader': 'thedailyshow',
63             'title': 'thedailyshow kristen-stewart part 1',
64         }
65     }, {
66         'url': 'http://thedailyshow.cc.com/extended-interviews/xm3fnq/andrew-napolitano-extended-interview',
67         'only_matching': True,
68     }, {
69         'url': 'http://thecolbertreport.cc.com/videos/29w6fx/-realhumanpraise-for-fox-news',
70         'only_matching': True,
71     }, {
72         'url': 'http://thecolbertreport.cc.com/videos/gh6urb/neil-degrasse-tyson-pt--1?xrs=eml_col_031114',
73         'only_matching': True,
74     }, {
75         'url': 'http://thedailyshow.cc.com/guests/michael-lewis/3efna8/exclusive---michael-lewis-extended-interview-pt--3',
76         'only_matching': True,
77     }, {
78         'url': 'http://thedailyshow.cc.com/episodes/sy7yv0/april-8--2014---denis-leary',
79         'only_matching': True,
80     }, {
81         'url': 'http://thecolbertreport.cc.com/episodes/8ase07/april-8--2014---jane-goodall',
82         'only_matching': True,
83     }, {
84         'url': 'http://thedailyshow.cc.com/video-playlists/npde3s/the-daily-show-19088-highlights',
85         'only_matching': True,
86     }, {
87         'url': 'http://thedailyshow.cc.com/video-playlists/t6d9sg/the-daily-show-20038-highlights/be3cwo',
88         'only_matching': True,
89     }, {
90         'url': 'http://thedailyshow.cc.com/special-editions/2l8fdb/special-edition---a-look-back-at-food',
91         'only_matching': True,
92     }, {
93         'url': 'http://thedailyshow.cc.com/news-team/michael-che/7wnfel/we-need-to-talk-about-israel',
94         'only_matching': True,
95     }]
96
97     _available_formats = ['3500', '2200', '1700', '1200', '750', '400']
98
99     _video_extensions = {
100         '3500': 'mp4',
101         '2200': 'mp4',
102         '1700': 'mp4',
103         '1200': 'mp4',
104         '750': 'mp4',
105         '400': 'mp4',
106     }
107     _video_dimensions = {
108         '3500': (1280, 720),
109         '2200': (960, 540),
110         '1700': (768, 432),
111         '1200': (640, 360),
112         '750': (512, 288),
113         '400': (384, 216),
114     }
115
116     def _real_extract(self, url):
117         mobj = re.match(self._VALID_URL, url)
118
119         if mobj.group('shortname'):
120             if mobj.group('shortname') in ('tds', 'thedailyshow'):
121                 url = 'http://thedailyshow.cc.com/full-episodes/'
122             else:
123                 url = 'http://thecolbertreport.cc.com/full-episodes/'
124             mobj = re.match(self._VALID_URL, url, re.VERBOSE)
125             assert mobj is not None
126
127         if mobj.group('clip'):
128             if mobj.group('videotitle'):
129                 epTitle = mobj.group('videotitle')
130             elif mobj.group('showname') == 'thedailyshow':
131                 epTitle = mobj.group('tdstitle')
132             else:
133                 epTitle = mobj.group('cntitle')
134             dlNewest = False
135         elif mobj.group('interview'):
136             epTitle = mobj.group('interview_title')
137             dlNewest = False
138         else:
139             dlNewest = not mobj.group('episode')
140             if dlNewest:
141                 epTitle = mobj.group('showname')
142             else:
143                 epTitle = mobj.group('episode')
144         show_name = mobj.group('showname')
145
146         webpage, htmlHandle = self._download_webpage_handle(url, epTitle)
147         if dlNewest:
148             url = htmlHandle.geturl()
149             mobj = re.match(self._VALID_URL, url, re.VERBOSE)
150             if mobj is None:
151                 raise ExtractorError('Invalid redirected URL: ' + url)
152             if mobj.group('episode') == '':
153                 raise ExtractorError('Redirected URL is still not specific: ' + url)
154             epTitle = (mobj.group('episode') or mobj.group('videotitle')).rpartition('/')[-1]
155
156         mMovieParams = re.findall('(?:<param name="movie" value="|var url = ")(http://media.mtvnservices.com/([^"]*(?:episode|video).*?:.*?))"', webpage)
157         if len(mMovieParams) == 0:
158             # The Colbert Report embeds the information in a without
159             # a URL prefix; so extract the alternate reference
160             # and then add the URL prefix manually.
161
162             altMovieParams = re.findall('data-mgid="([^"]*(?:episode|video|playlist).*?:.*?)"', webpage)
163             if len(altMovieParams) == 0:
164                 raise ExtractorError('unable to find Flash URL in webpage ' + url)
165             else:
166                 mMovieParams = [("http://media.mtvnservices.com/" + altMovieParams[0], altMovieParams[0])]
167
168         uri = mMovieParams[0][1]
169         # Correct cc.com in uri
170         uri = re.sub(r'(episode:[^.]+)(\.cc)?\.com', r'\1.cc.com', uri)
171
172         index_url = 'http://%s.cc.com/feeds/mrss?%s' % (show_name, compat_urllib_parse.urlencode({'uri': uri}))
173         idoc = self._download_xml(
174             index_url, epTitle,
175             'Downloading show index', 'Unable to download episode index')
176
177         title = idoc.find('./channel/title').text
178         description = idoc.find('./channel/description').text
179
180         entries = []
181         item_els = idoc.findall('.//item')
182         for part_num, itemEl in enumerate(item_els):
183             upload_date = unified_strdate(itemEl.findall('./pubDate')[0].text)
184             thumbnail = itemEl.find('.//{http://search.yahoo.com/mrss/}thumbnail').attrib.get('url')
185
186             content = itemEl.find('.//{http://search.yahoo.com/mrss/}content')
187             duration = float_or_none(content.attrib.get('duration'))
188             mediagen_url = content.attrib['url']
189             guid = itemEl.find('./guid').text.rpartition(':')[-1]
190
191             cdoc = self._download_xml(
192                 mediagen_url, epTitle,
193                 'Downloading configuration for segment %d / %d' % (part_num + 1, len(item_els)))
194
195             turls = []
196             for rendition in cdoc.findall('.//rendition'):
197                 finfo = (rendition.attrib['bitrate'], rendition.findall('./src')[0].text)
198                 turls.append(finfo)
199
200             formats = []
201             for format, rtmp_video_url in turls:
202                 w, h = self._video_dimensions.get(format, (None, None))
203                 formats.append({
204                     'format_id': 'vhttp-%s' % format,
205                     'url': self._transform_rtmp_url(rtmp_video_url),
206                     'ext': self._video_extensions.get(format, 'mp4'),
207                     'height': h,
208                     'width': w,
209                 })
210                 formats.append({
211                     'format_id': 'rtmp-%s' % format,
212                     'url': rtmp_video_url.replace('viacomccstrm', 'viacommtvstrm'),
213                     'ext': self._video_extensions.get(format, 'mp4'),
214                     'height': h,
215                     'width': w,
216                 })
217                 self._sort_formats(formats)
218
219             virtual_id = show_name + ' ' + epTitle + ' part ' + compat_str(part_num + 1)
220             entries.append({
221                 'id': guid,
222                 'title': virtual_id,
223                 'formats': formats,
224                 'uploader': show_name,
225                 'upload_date': upload_date,
226                 'duration': duration,
227                 'thumbnail': thumbnail,
228                 'description': description,
229             })
230
231         return {
232             '_type': 'playlist',
233             'entries': entries,
234             'title': show_name + ' ' + title,
235             'description': description,
236         }