[comedycentral] Add support for /videos URLs (Fixes #2660)
[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 ..utils import (
8     compat_str,
9     compat_urllib_parse,
10     ExtractorError,
11     float_or_none,
12     unified_strdate,
13 )
14
15
16 class ComedyCentralIE(MTVServicesInfoExtractor):
17     _VALID_URL = r'''(?x)https?://(?:www\.)?(comedycentral|cc)\.com/
18         (video-clips|episodes|cc-studios|video-collections)
19         /(?P<title>.*)'''
20     _FEED_URL = 'http://comedycentral.com/feeds/mrss/'
21
22     _TEST = {
23         'url': 'http://www.comedycentral.com/video-clips/kllhuv/stand-up-greg-fitzsimmons--uncensored---too-good-of-a-mother',
24         'md5': '4167875aae411f903b751a21f357f1ee',
25         'info_dict': {
26             'id': 'cef0cbb3-e776-4bc9-b62e-8016deccb354',
27             'ext': 'mp4',
28             'title': 'CC:Stand-Up|Greg Fitzsimmons: Life on Stage|Uncensored - Too Good of a Mother',
29             'description': 'After a certain point, breastfeeding becomes c**kblocking.',
30         },
31     }
32
33
34 class ComedyCentralShowsIE(InfoExtractor):
35     IE_DESC = 'The Daily Show / The Colbert Report'
36     # urls can be abbreviations like :thedailyshow or :colbert
37     # urls for episodes like:
38     # or urls for clips like: http://www.thedailyshow.com/watch/mon-december-10-2012/any-given-gun-day
39     #                     or: http://www.colbertnation.com/the-colbert-report-videos/421667/november-29-2012/moon-shattering-news
40     #                     or: http://www.colbertnation.com/the-colbert-report-collections/422008/festival-of-lights/79524
41     _VALID_URL = r'''(?x)^(:(?P<shortname>tds|thedailyshow|cr|colbert|colbertnation|colbertreport)
42                       |https?://(:www\.)?
43                           (?P<showname>thedailyshow|thecolbertreport)\.(?:cc\.)?com/
44                          (full-episodes/(?P<episode>.*)|
45                           (?P<clip>
46                               (?:videos/[^/]+/(?P<videotitle>[^/?#]+))
47                               |(the-colbert-report-(videos|collections)/(?P<clipID>[0-9]+)/[^/]*/(?P<cntitle>.*?))
48                               |(watch/(?P<date>[^/]*)/(?P<tdstitle>.*)))|
49                           (?P<interview>
50                               extended-interviews/(?P<interID>[0-9a-z]+)/(?:playlist_tds_extended_)?(?P<interview_title>.*?)(/.*?)?)))
51                      $'''
52     _TEST = {
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
65     _available_formats = ['3500', '2200', '1700', '1200', '750', '400']
66
67     _video_extensions = {
68         '3500': 'mp4',
69         '2200': 'mp4',
70         '1700': 'mp4',
71         '1200': 'mp4',
72         '750': 'mp4',
73         '400': 'mp4',
74     }
75     _video_dimensions = {
76         '3500': (1280, 720),
77         '2200': (960, 540),
78         '1700': (768, 432),
79         '1200': (640, 360),
80         '750': (512, 288),
81         '400': (384, 216),
82     }
83
84     @staticmethod
85     def _transform_rtmp_url(rtmp_video_url):
86         m = re.match(r'^rtmpe?://.*?/(?P<finalid>gsp\.comedystor/.*)$', rtmp_video_url)
87         if not m:
88             raise ExtractorError('Cannot transform RTMP url')
89         base = 'http://mtvnmobile.vo.llnwd.net/kip0/_pxn=1+_pxI0=Ripod-h264+_pxL0=undefined+_pxM0=+_pxK=18639+_pxE=mp4/44620/mtvnorigin/'
90         return base + m.group('finalid')
91
92     def _real_extract(self, url):
93         mobj = re.match(self._VALID_URL, url, re.VERBOSE)
94         if mobj is None:
95             raise ExtractorError('Invalid URL: %s' % url)
96
97         if mobj.group('shortname'):
98             if mobj.group('shortname') in ('tds', 'thedailyshow'):
99                 url = 'http://thedailyshow.cc.com/full-episodes/'
100             else:
101                 url = 'http://thecolbertreport.cc.com/full-episodes/'
102             mobj = re.match(self._VALID_URL, url, re.VERBOSE)
103             assert mobj is not None
104
105         if mobj.group('clip'):
106             if mobj.group('videotitle'):
107                 epTitle = mobj.group('videotitle')
108             elif mobj.group('showname') == 'thedailyshow':
109                 epTitle = mobj.group('tdstitle')
110             else:
111                 epTitle = mobj.group('cntitle')
112             dlNewest = False
113         elif mobj.group('interview'):
114             epTitle = mobj.group('interview_title')
115             dlNewest = False
116         else:
117             dlNewest = not mobj.group('episode')
118             if dlNewest:
119                 epTitle = mobj.group('showname')
120             else:
121                 epTitle = mobj.group('episode')
122         show_name = mobj.group('showname')
123
124         webpage, htmlHandle = self._download_webpage_handle(url, epTitle)
125         if dlNewest:
126             url = htmlHandle.geturl()
127             mobj = re.match(self._VALID_URL, url, re.VERBOSE)
128             if mobj is None:
129                 raise ExtractorError('Invalid redirected URL: ' + url)
130             if mobj.group('episode') == '':
131                 raise ExtractorError('Redirected URL is still not specific: ' + url)
132             epTitle = mobj.group('episode').rpartition('/')[-1]
133
134         mMovieParams = re.findall('(?:<param name="movie" value="|var url = ")(http://media.mtvnservices.com/([^"]*(?:episode|video).*?:.*?))"', webpage)
135         if len(mMovieParams) == 0:
136             # The Colbert Report embeds the information in a without
137             # a URL prefix; so extract the alternate reference
138             # and then add the URL prefix manually.
139
140             altMovieParams = re.findall('data-mgid="([^"]*(?:episode|video|playlist).*?:.*?)"', webpage)
141             if len(altMovieParams) == 0:
142                 raise ExtractorError('unable to find Flash URL in webpage ' + url)
143             else:
144                 mMovieParams = [("http://media.mtvnservices.com/" + altMovieParams[0], altMovieParams[0])]
145
146         uri = mMovieParams[0][1]
147         # Correct cc.com in uri
148         uri = re.sub(r'(episode:[^.]+)(\.cc)?\.com', r'\1.cc.com', uri)
149
150         index_url = 'http://%s.cc.com/feeds/mrss?%s' % (show_name, compat_urllib_parse.urlencode({'uri': uri}))
151         idoc = self._download_xml(
152             index_url, epTitle,
153             'Downloading show index', 'Unable to download episode index')
154
155         title = idoc.find('./channel/title').text
156         description = idoc.find('./channel/description').text
157
158         entries = []
159         item_els = idoc.findall('.//item')
160         for part_num, itemEl in enumerate(item_els):
161             upload_date = unified_strdate(itemEl.findall('./pubDate')[0].text)
162             thumbnail = itemEl.find('.//{http://search.yahoo.com/mrss/}thumbnail').attrib.get('url')
163
164             content = itemEl.find('.//{http://search.yahoo.com/mrss/}content')
165             duration = float_or_none(content.attrib.get('duration'))
166             mediagen_url = content.attrib['url']
167             guid = itemEl.find('.//guid').text.rpartition(':')[-1]
168
169             cdoc = self._download_xml(
170                 mediagen_url, epTitle,
171                 'Downloading configuration for segment %d / %d' % (part_num + 1, len(item_els)))
172
173             turls = []
174             for rendition in cdoc.findall('.//rendition'):
175                 finfo = (rendition.attrib['bitrate'], rendition.findall('./src')[0].text)
176                 turls.append(finfo)
177
178             formats = []
179             for format, rtmp_video_url in turls:
180                 w, h = self._video_dimensions.get(format, (None, None))
181                 formats.append({
182                     'format_id': 'vhttp-%s' % format,
183                     'url': self._transform_rtmp_url(rtmp_video_url),
184                     'ext': self._video_extensions.get(format, 'mp4'),
185                     'height': h,
186                     'width': w,
187                 })
188                 formats.append({
189                     'format_id': 'rtmp-%s' % format,
190                     'url': rtmp_video_url,
191                     'ext': self._video_extensions.get(format, 'mp4'),
192                     'height': h,
193                     'width': w,
194                 })
195                 self._sort_formats(formats)
196
197             virtual_id = show_name + ' ' + epTitle + ' part ' + compat_str(part_num + 1)
198             entries.append({
199                 'id': guid,
200                 'title': virtual_id,
201                 'formats': formats,
202                 'uploader': show_name,
203                 'upload_date': upload_date,
204                 'duration': duration,
205                 'thumbnail': thumbnail,
206                 'description': description,
207             })
208
209         return {
210             '_type': 'playlist',
211             'entries': entries,
212             'title': show_name + ' ' + title,
213             'description': description,
214         }