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