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