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