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