]> git.bitcoin.ninja Git - youtube-dl/blob - youtube_dl/extractor/comedycentral.py
[aftonbladet] Modernize
[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
34 class ComedyCentralShowsIE(InfoExtractor):
35     IE_DESC = 'The Daily Show / 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"""^(:(?P<shortname>tds|thedailyshow|cr|colbert|colbertnation|colbertreport)
42                       |(https?://)?(www\.)?
43                           (?P<showname>thedailyshow|colbertnation)\.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-9]+)/playlist_tds_extended_(?P<interview_title>.*?)/.*?)))
50                      $"""
51     _TEST = {
52         'url': 'http://www.thedailyshow.com/watch/thu-december-13-2012/kristen-stewart',
53         'file': '422212.mp4',
54         'md5': '4e2f5cb088a83cd8cdb7756132f9739d',
55         'info_dict': {
56             "upload_date": "20121214",
57             "description": "Kristen Stewart",
58             "uploader": "thedailyshow",
59             "title": "thedailyshow-kristen-stewart part 1"
60         }
61     }
62
63     _available_formats = ['3500', '2200', '1700', '1200', '750', '400']
64
65     _video_extensions = {
66         '3500': 'mp4',
67         '2200': 'mp4',
68         '1700': 'mp4',
69         '1200': 'mp4',
70         '750': 'mp4',
71         '400': 'mp4',
72     }
73     _video_dimensions = {
74         '3500': (1280, 720),
75         '2200': (960, 540),
76         '1700': (768, 432),
77         '1200': (640, 360),
78         '750': (512, 288),
79         '400': (384, 216),
80     }
81
82     @classmethod
83     def suitable(cls, url):
84         """Receives a URL and returns True if suitable for this IE."""
85         return re.match(cls._VALID_URL, url, re.VERBOSE) is not None
86
87     @staticmethod
88     def _transform_rtmp_url(rtmp_video_url):
89         m = re.match(r'^rtmpe?://.*?/(?P<finalid>gsp\.comedystor/.*)$', rtmp_video_url)
90         if not m:
91             raise ExtractorError('Cannot transform RTMP url')
92         base = 'http://mtvnmobile.vo.llnwd.net/kip0/_pxn=1+_pxI0=Ripod-h264+_pxL0=undefined+_pxM0=+_pxK=18639+_pxE=mp4/44620/mtvnorigin/'
93         return base + m.group('finalid')
94
95     def _real_extract(self, url):
96         mobj = re.match(self._VALID_URL, url, re.VERBOSE)
97         if mobj is None:
98             raise ExtractorError('Invalid URL: %s' % url)
99
100         if mobj.group('shortname'):
101             if mobj.group('shortname') in ('tds', 'thedailyshow'):
102                 url = 'http://www.thedailyshow.com/full-episodes/'
103             else:
104                 url = 'http://www.colbertnation.com/full-episodes/'
105             mobj = re.match(self._VALID_URL, url, re.VERBOSE)
106             assert mobj is not None
107
108         if mobj.group('clip'):
109             if 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
124         self.report_extraction(epTitle)
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')
134
135         mMovieParams = re.findall('(?:<param name="movie" value="|var url = ")(http://media.mtvnservices.com/([^"]*(?:episode|video).*?:.*?))"', webpage)
136
137         if len(mMovieParams) == 0:
138             # The Colbert Report embeds the information in a without
139             # a URL prefix; so extract the alternate reference
140             # and then add the URL prefix manually.
141
142             altMovieParams = re.findall('data-mgid="([^"]*(?:episode|video).*?:.*?)"', webpage)
143             if len(altMovieParams) == 0:
144                 raise ExtractorError('unable to find Flash URL in webpage ' + url)
145             else:
146                 mMovieParams = [("http://media.mtvnservices.com/" + altMovieParams[0], altMovieParams[0])]
147
148         uri = mMovieParams[0][1]
149         indexUrl = 'http://shadow.comedycentral.com/feeds/video_player/mrss/?' + compat_urllib_parse.urlencode({'uri': uri})
150         idoc = self._download_xml(indexUrl, epTitle,
151                                           'Downloading show index',
152                                           'unable to download episode index')
153
154         results = []
155
156         itemEls = idoc.findall('.//item')
157         for partNum,itemEl in enumerate(itemEls):
158             mediaId = itemEl.findall('./guid')[0].text
159             shortMediaId = mediaId.split(':')[-1]
160             showId = mediaId.split(':')[-2].replace('.com', '')
161             officialTitle = itemEl.findall('./title')[0].text
162             officialDate = unified_strdate(itemEl.findall('./pubDate')[0].text)
163
164             configUrl = ('http://www.comedycentral.com/global/feeds/entertainment/media/mediaGenEntertainment.jhtml?' +
165                         compat_urllib_parse.urlencode({'uri': mediaId}))
166             cdoc = self._download_xml(configUrl, epTitle,
167                                                'Downloading configuration for %s' % shortMediaId)
168
169             turls = []
170             for rendition in cdoc.findall('.//rendition'):
171                 finfo = (rendition.attrib['bitrate'], rendition.findall('./src')[0].text)
172                 turls.append(finfo)
173
174             if len(turls) == 0:
175                 self._downloader.report_error('unable to download ' + mediaId + ': No videos found')
176                 continue
177
178             formats = []
179             for format, rtmp_video_url in turls:
180                 w, h = self._video_dimensions.get(format, (None, None))
181                 formats.append({
182                     'url': self._transform_rtmp_url(rtmp_video_url),
183                     'ext': self._video_extensions.get(format, 'mp4'),
184                     'format_id': format,
185                     'height': h,
186                     'width': w,
187                 })
188
189             effTitle = showId + '-' + epTitle + ' part ' + compat_str(partNum+1)
190             results.append({
191                 'id': shortMediaId,
192                 'formats': formats,
193                 'uploader': showId,
194                 'upload_date': officialDate,
195                 'title': effTitle,
196                 'thumbnail': None,
197                 'description': compat_str(officialTitle),
198             })
199
200         return results