release 2013.12.04
[youtube-dl] / youtube_dl / extractor / comedycentral.py
1 import re
2
3 from .common import InfoExtractor
4 from .mtv import MTVServicesInfoExtractor
5 from ..utils import (
6     compat_str,
7     compat_urllib_parse,
8
9     ExtractorError,
10     unified_strdate,
11 )
12
13
14 class ComedyCentralIE(MTVServicesInfoExtractor):
15     _VALID_URL = r'http://www.comedycentral.com/(video-clips|episodes|cc-studios)/(?P<title>.*)'
16     _FEED_URL = u'http://comedycentral.com/feeds/mrss/'
17
18     _TEST = {
19         u'url': u'http://www.comedycentral.com/video-clips/kllhuv/stand-up-greg-fitzsimmons--uncensored---too-good-of-a-mother',
20         u'md5': u'4167875aae411f903b751a21f357f1ee',
21         u'info_dict': {
22             u'id': u'cef0cbb3-e776-4bc9-b62e-8016deccb354',
23             u'ext': u'mp4',
24             u'title': u'Uncensored - Greg Fitzsimmons - Too Good of a Mother',
25             u'description': u'After a certain point, breastfeeding becomes c**kblocking.',
26         },
27     }
28
29     def _real_extract(self, url):
30         mobj = re.match(self._VALID_URL, url)
31         title = mobj.group('title')
32         webpage = self._download_webpage(url, title)
33         mgid = self._search_regex(r'data-mgid="(?P<mgid>mgid:.*?)"',
34                                   webpage, u'mgid')
35         return self._get_videos_info(mgid)
36
37
38 class ComedyCentralShowsIE(InfoExtractor):
39     IE_DESC = u'The Daily Show / Colbert Report'
40     # urls can be abbreviations like :thedailyshow or :colbert
41     # urls for episodes like:
42     # or urls for clips like: http://www.thedailyshow.com/watch/mon-december-10-2012/any-given-gun-day
43     #                     or: http://www.colbertnation.com/the-colbert-report-videos/421667/november-29-2012/moon-shattering-news
44     #                     or: http://www.colbertnation.com/the-colbert-report-collections/422008/festival-of-lights/79524
45     _VALID_URL = r"""^(:(?P<shortname>tds|thedailyshow|cr|colbert|colbertnation|colbertreport)
46                       |(https?://)?(www\.)?
47                           (?P<showname>thedailyshow|colbertnation)\.com/
48                          (full-episodes/(?P<episode>.*)|
49                           (?P<clip>
50                               (the-colbert-report-(videos|collections)/(?P<clipID>[0-9]+)/[^/]*/(?P<cntitle>.*?))
51                               |(watch/(?P<date>[^/]*)/(?P<tdstitle>.*)))|
52                           (?P<interview>
53                               extended-interviews/(?P<interID>[0-9]+)/playlist_tds_extended_(?P<interview_title>.*?)/.*?)))
54                      $"""
55     _TEST = {
56         u'url': u'http://www.thedailyshow.com/watch/thu-december-13-2012/kristen-stewart',
57         u'file': u'422212.mp4',
58         u'md5': u'4e2f5cb088a83cd8cdb7756132f9739d',
59         u'info_dict': {
60             u"upload_date": u"20121214", 
61             u"description": u"Kristen Stewart", 
62             u"uploader": u"thedailyshow", 
63             u"title": u"thedailyshow-kristen-stewart part 1"
64         }
65     }
66
67     _available_formats = ['3500', '2200', '1700', '1200', '750', '400']
68
69     _video_extensions = {
70         '3500': 'mp4',
71         '2200': 'mp4',
72         '1700': 'mp4',
73         '1200': 'mp4',
74         '750': 'mp4',
75         '400': 'mp4',
76     }
77     _video_dimensions = {
78         '3500': (1280, 720),
79         '2200': (960, 540),
80         '1700': (768, 432),
81         '1200': (640, 360),
82         '750': (512, 288),
83         '400': (384, 216),
84     }
85
86     @classmethod
87     def suitable(cls, url):
88         """Receives a URL and returns True if suitable for this IE."""
89         return re.match(cls._VALID_URL, url, re.VERBOSE) is not None
90
91     @staticmethod
92     def _transform_rtmp_url(rtmp_video_url):
93         m = re.match(r'^rtmpe?://.*?/(?P<finalid>gsp.comedystor/.*)$', rtmp_video_url)
94         if not m:
95             raise ExtractorError(u'Cannot transform RTMP url')
96         base = 'http://mtvnmobile.vo.llnwd.net/kip0/_pxn=1+_pxI0=Ripod-h264+_pxL0=undefined+_pxM0=+_pxK=18639+_pxE=mp4/44620/mtvnorigin/'
97         return base + m.group('finalid')
98
99     def _real_extract(self, url):
100         mobj = re.match(self._VALID_URL, url, re.VERBOSE)
101         if mobj is None:
102             raise ExtractorError(u'Invalid URL: %s' % url)
103
104         if mobj.group('shortname'):
105             if mobj.group('shortname') in ('tds', 'thedailyshow'):
106                 url = u'http://www.thedailyshow.com/full-episodes/'
107             else:
108                 url = u'http://www.colbertnation.com/full-episodes/'
109             mobj = re.match(self._VALID_URL, url, re.VERBOSE)
110             assert mobj is not None
111
112         if mobj.group('clip'):
113             if mobj.group('showname') == 'thedailyshow':
114                 epTitle = mobj.group('tdstitle')
115             else:
116                 epTitle = mobj.group('cntitle')
117             dlNewest = False
118         elif mobj.group('interview'):
119             epTitle = mobj.group('interview_title')
120             dlNewest = False
121         else:
122             dlNewest = not mobj.group('episode')
123             if dlNewest:
124                 epTitle = mobj.group('showname')
125             else:
126                 epTitle = mobj.group('episode')
127
128         self.report_extraction(epTitle)
129         webpage,htmlHandle = self._download_webpage_handle(url, epTitle)
130         if dlNewest:
131             url = htmlHandle.geturl()
132             mobj = re.match(self._VALID_URL, url, re.VERBOSE)
133             if mobj is None:
134                 raise ExtractorError(u'Invalid redirected URL: ' + url)
135             if mobj.group('episode') == '':
136                 raise ExtractorError(u'Redirected URL is still not specific: ' + url)
137             epTitle = mobj.group('episode')
138
139         mMovieParams = re.findall('(?:<param name="movie" value="|var url = ")(http://media.mtvnservices.com/([^"]*(?:episode|video).*?:.*?))"', webpage)
140
141         if len(mMovieParams) == 0:
142             # The Colbert Report embeds the information in a without
143             # a URL prefix; so extract the alternate reference
144             # and then add the URL prefix manually.
145
146             altMovieParams = re.findall('data-mgid="([^"]*(?:episode|video).*?:.*?)"', webpage)
147             if len(altMovieParams) == 0:
148                 raise ExtractorError(u'unable to find Flash URL in webpage ' + url)
149             else:
150                 mMovieParams = [("http://media.mtvnservices.com/" + altMovieParams[0], altMovieParams[0])]
151
152         uri = mMovieParams[0][1]
153         indexUrl = 'http://shadow.comedycentral.com/feeds/video_player/mrss/?' + compat_urllib_parse.urlencode({'uri': uri})
154         idoc = self._download_xml(indexUrl, epTitle,
155                                           u'Downloading show index',
156                                           u'unable to download episode index')
157
158         results = []
159
160         itemEls = idoc.findall('.//item')
161         for partNum,itemEl in enumerate(itemEls):
162             mediaId = itemEl.findall('./guid')[0].text
163             shortMediaId = mediaId.split(':')[-1]
164             showId = mediaId.split(':')[-2].replace('.com', '')
165             officialTitle = itemEl.findall('./title')[0].text
166             officialDate = unified_strdate(itemEl.findall('./pubDate')[0].text)
167
168             configUrl = ('http://www.comedycentral.com/global/feeds/entertainment/media/mediaGenEntertainment.jhtml?' +
169                         compat_urllib_parse.urlencode({'uri': mediaId}))
170             cdoc = self._download_xml(configUrl, epTitle,
171                                                u'Downloading configuration for %s' % shortMediaId)
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             if len(turls) == 0:
179                 self._downloader.report_error(u'unable to download ' + mediaId + ': No videos found')
180                 continue
181
182             formats = []
183             for format, rtmp_video_url in turls:
184                 w, h = self._video_dimensions.get(format, (None, None))
185                 formats.append({
186                     'url': self._transform_rtmp_url(rtmp_video_url),
187                     'ext': self._video_extensions.get(format, 'mp4'),
188                     'format_id': format,
189                     'height': h,
190                     'width': w,
191                 })
192
193             effTitle = showId + u'-' + epTitle + u' part ' + compat_str(partNum+1)
194             results.append({
195                 'id': shortMediaId,
196                 'formats': formats,
197                 'uploader': showId,
198                 'upload_date': officialDate,
199                 'title': effTitle,
200                 'thumbnail': None,
201                 'description': compat_str(officialTitle),
202             })
203
204         return results