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