Merge remote-tracking branch 'phaer/add-oe1-support'
[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                               (the-colbert-report-(videos|collections)/(?P<clipID>[0-9]+)/[^/]*/(?P<cntitle>.*?))
47                               |(watch/(?P<date>[^/]*)/(?P<tdstitle>.*)))|
48                           (?P<interview>
49                               extended-interviews/(?P<interID>[0-9a-z]+)/(?:playlist_tds_extended_)?(?P<interview_title>.*?)(/.*?)?)))
50                      $'''
51     _TEST = {
52         'url': 'http://thedailyshow.cc.com/watch/thu-december-13-2012/kristen-stewart',
53         'md5': '4e2f5cb088a83cd8cdb7756132f9739d',
54         'info_dict': {
55             'id': 'ab9ab3e7-5a98-4dbe-8b21-551dc0523d55',
56             'ext': 'mp4',
57             'upload_date': '20121213',
58             'description': 'Kristen Stewart learns to let loose in "On the Road."',
59             'uploader': 'thedailyshow',
60             'title': 'thedailyshow-kristen-stewart part 1',
61         }
62     }
63
64     _available_formats = ['3500', '2200', '1700', '1200', '750', '400']
65
66     _video_extensions = {
67         '3500': 'mp4',
68         '2200': 'mp4',
69         '1700': 'mp4',
70         '1200': 'mp4',
71         '750': 'mp4',
72         '400': 'mp4',
73     }
74     _video_dimensions = {
75         '3500': (1280, 720),
76         '2200': (960, 540),
77         '1700': (768, 432),
78         '1200': (640, 360),
79         '750': (512, 288),
80         '400': (384, 216),
81     }
82
83     @staticmethod
84     def _transform_rtmp_url(rtmp_video_url):
85         m = re.match(r'^rtmpe?://.*?/(?P<finalid>gsp\.comedystor/.*)$', rtmp_video_url)
86         if not m:
87             raise ExtractorError('Cannot transform RTMP url')
88         base = 'http://mtvnmobile.vo.llnwd.net/kip0/_pxn=1+_pxI0=Ripod-h264+_pxL0=undefined+_pxM0=+_pxK=18639+_pxE=mp4/44620/mtvnorigin/'
89         return base + m.group('finalid')
90
91     def _real_extract(self, url):
92         mobj = re.match(self._VALID_URL, url, re.VERBOSE)
93         if mobj is None:
94             raise ExtractorError('Invalid URL: %s' % url)
95
96         if mobj.group('shortname'):
97             if mobj.group('shortname') in ('tds', 'thedailyshow'):
98                 url = 'http://thedailyshow.cc.com/full-episodes/'
99             else:
100                 url = 'http://thecolbertreport.cc.com/full-episodes/'
101             mobj = re.match(self._VALID_URL, url, re.VERBOSE)
102             assert mobj is not None
103
104         if mobj.group('clip'):
105             if mobj.group('showname') == 'thedailyshow':
106                 epTitle = mobj.group('tdstitle')
107             else:
108                 epTitle = mobj.group('cntitle')
109             dlNewest = False
110         elif mobj.group('interview'):
111             epTitle = mobj.group('interview_title')
112             dlNewest = False
113         else:
114             dlNewest = not mobj.group('episode')
115             if dlNewest:
116                 epTitle = mobj.group('showname')
117             else:
118                 epTitle = mobj.group('episode')
119         show_name = mobj.group('showname')
120
121         webpage, htmlHandle = self._download_webpage_handle(url, epTitle)
122         if dlNewest:
123             url = htmlHandle.geturl()
124             mobj = re.match(self._VALID_URL, url, re.VERBOSE)
125             if mobj is None:
126                 raise ExtractorError('Invalid redirected URL: ' + url)
127             if mobj.group('episode') == '':
128                 raise ExtractorError('Redirected URL is still not specific: ' + url)
129             epTitle = mobj.group('episode').rpartition('/')[-1]
130
131         mMovieParams = re.findall('(?:<param name="movie" value="|var url = ")(http://media.mtvnservices.com/([^"]*(?:episode|video).*?:.*?))"', webpage)
132         if len(mMovieParams) == 0:
133             # The Colbert Report embeds the information in a without
134             # a URL prefix; so extract the alternate reference
135             # and then add the URL prefix manually.
136
137             altMovieParams = re.findall('data-mgid="([^"]*(?:episode|video|playlist).*?:.*?)"', webpage)
138             if len(altMovieParams) == 0:
139                 raise ExtractorError('unable to find Flash URL in webpage ' + url)
140             else:
141                 mMovieParams = [("http://media.mtvnservices.com/" + altMovieParams[0], altMovieParams[0])]
142
143         uri = mMovieParams[0][1]
144         # Correct cc.com in uri
145         uri = re.sub(r'(episode:[^.]+)(\.cc)?\.com', r'\1.cc.com', uri)
146
147         index_url = 'http://%s.cc.com/feeds/mrss?%s' % (show_name, compat_urllib_parse.urlencode({'uri': uri}))
148         idoc = self._download_xml(
149             index_url, epTitle,
150             'Downloading show index', 'Unable to download episode index')
151
152         title = idoc.find('./channel/title').text
153         description = idoc.find('./channel/description').text
154
155         entries = []
156         item_els = idoc.findall('.//item')
157         for part_num, itemEl in enumerate(item_els):
158             upload_date = unified_strdate(itemEl.findall('./pubDate')[0].text)
159             thumbnail = itemEl.find('.//{http://search.yahoo.com/mrss/}thumbnail').attrib.get('url')
160
161             content = itemEl.find('.//{http://search.yahoo.com/mrss/}content')
162             duration = float_or_none(content.attrib.get('duration'))
163             mediagen_url = content.attrib['url']
164             guid = itemEl.find('.//guid').text.rpartition(':')[-1]
165
166             cdoc = self._download_xml(
167                 mediagen_url, epTitle,
168                 'Downloading configuration for segment %d / %d' % (part_num + 1, len(item_els)))
169
170             turls = []
171             for rendition in cdoc.findall('.//rendition'):
172                 finfo = (rendition.attrib['bitrate'], rendition.findall('./src')[0].text)
173                 turls.append(finfo)
174
175             formats = []
176             for format, rtmp_video_url in turls:
177                 w, h = self._video_dimensions.get(format, (None, None))
178                 formats.append({
179                     'format_id': 'vhttp-%s' % format,
180                     'url': self._transform_rtmp_url(rtmp_video_url),
181                     'ext': self._video_extensions.get(format, 'mp4'),
182                     'height': h,
183                     'width': w,
184                 })
185                 formats.append({
186                     'format_id': 'rtmp-%s' % format,
187                     'url': rtmp_video_url,
188                     'ext': self._video_extensions.get(format, 'mp4'),
189                     'height': h,
190                     'width': w,
191                 })
192                 self._sort_formats(formats)
193
194             virtual_id = show_name + ' ' + epTitle + ' part ' + compat_str(part_num + 1)
195             entries.append({
196                 'id': guid,
197                 'title': virtual_id,
198                 'formats': formats,
199                 'uploader': show_name,
200                 'upload_date': upload_date,
201                 'duration': duration,
202                 'thumbnail': thumbnail,
203                 'description': description,
204             })
205
206         return {
207             '_type': 'playlist',
208             'entries': entries,
209             'title': show_name + ' ' + title,
210             'description': description,
211         }