Move tests to the IE definitions
[youtube-dl] / youtube_dl / extractor / comedycentral.py
1 import re
2 import xml.etree.ElementTree
3
4 from .common import InfoExtractor
5 from ..utils import (
6     compat_str,
7     compat_urllib_parse,
8
9     ExtractorError,
10     unified_strdate,
11 )
12
13
14 class ComedyCentralIE(InfoExtractor):
15     """Information extractor for The Daily Show and Colbert Report """
16
17     # urls can be abbreviations like :thedailyshow or :colbert
18     # urls for episodes like:
19     # or urls for clips like: http://www.thedailyshow.com/watch/mon-december-10-2012/any-given-gun-day
20     #                     or: http://www.colbertnation.com/the-colbert-report-videos/421667/november-29-2012/moon-shattering-news
21     #                     or: http://www.colbertnation.com/the-colbert-report-collections/422008/festival-of-lights/79524
22     _VALID_URL = r"""^(:(?P<shortname>tds|thedailyshow|cr|colbert|colbertnation|colbertreport)
23                       |(https?://)?(www\.)?
24                           (?P<showname>thedailyshow|colbertnation)\.com/
25                          (full-episodes/(?P<episode>.*)|
26                           (?P<clip>
27                               (the-colbert-report-(videos|collections)/(?P<clipID>[0-9]+)/[^/]*/(?P<cntitle>.*?))
28                               |(watch/(?P<date>[^/]*)/(?P<tdstitle>.*)))))
29                      $"""
30     _TEST = {
31         u'url': u'http://www.thedailyshow.com/watch/thu-december-13-2012/kristen-stewart',
32         u'file': u'422212.mp4',
33         u'md5': u'4e2f5cb088a83cd8cdb7756132f9739d',
34         u'info_dict': {
35             u"upload_date": u"20121214", 
36             u"description": u"Kristen Stewart", 
37             u"uploader": u"thedailyshow", 
38             u"title": u"thedailyshow-kristen-stewart part 1"
39         }
40     }
41
42     _available_formats = ['3500', '2200', '1700', '1200', '750', '400']
43
44     _video_extensions = {
45         '3500': 'mp4',
46         '2200': 'mp4',
47         '1700': 'mp4',
48         '1200': 'mp4',
49         '750': 'mp4',
50         '400': 'mp4',
51     }
52     _video_dimensions = {
53         '3500': '1280x720',
54         '2200': '960x540',
55         '1700': '768x432',
56         '1200': '640x360',
57         '750': '512x288',
58         '400': '384x216',
59     }
60
61     @classmethod
62     def suitable(cls, url):
63         """Receives a URL and returns True if suitable for this IE."""
64         return re.match(cls._VALID_URL, url, re.VERBOSE) is not None
65
66     def _print_formats(self, formats):
67         print('Available formats:')
68         for x in formats:
69             print('%s\t:\t%s\t[%s]' %(x, self._video_extensions.get(x, 'mp4'), self._video_dimensions.get(x, '???')))
70
71
72     def _real_extract(self, url):
73         mobj = re.match(self._VALID_URL, url, re.VERBOSE)
74         if mobj is None:
75             raise ExtractorError(u'Invalid URL: %s' % url)
76
77         if mobj.group('shortname'):
78             if mobj.group('shortname') in ('tds', 'thedailyshow'):
79                 url = u'http://www.thedailyshow.com/full-episodes/'
80             else:
81                 url = u'http://www.colbertnation.com/full-episodes/'
82             mobj = re.match(self._VALID_URL, url, re.VERBOSE)
83             assert mobj is not None
84
85         if mobj.group('clip'):
86             if mobj.group('showname') == 'thedailyshow':
87                 epTitle = mobj.group('tdstitle')
88             else:
89                 epTitle = mobj.group('cntitle')
90             dlNewest = False
91         else:
92             dlNewest = not mobj.group('episode')
93             if dlNewest:
94                 epTitle = mobj.group('showname')
95             else:
96                 epTitle = mobj.group('episode')
97
98         self.report_extraction(epTitle)
99         webpage,htmlHandle = self._download_webpage_handle(url, epTitle)
100         if dlNewest:
101             url = htmlHandle.geturl()
102             mobj = re.match(self._VALID_URL, url, re.VERBOSE)
103             if mobj is None:
104                 raise ExtractorError(u'Invalid redirected URL: ' + url)
105             if mobj.group('episode') == '':
106                 raise ExtractorError(u'Redirected URL is still not specific: ' + url)
107             epTitle = mobj.group('episode')
108
109         mMovieParams = re.findall('(?:<param name="movie" value="|var url = ")(http://media.mtvnservices.com/([^"]*(?:episode|video).*?:.*?))"', webpage)
110
111         if len(mMovieParams) == 0:
112             # The Colbert Report embeds the information in a without
113             # a URL prefix; so extract the alternate reference
114             # and then add the URL prefix manually.
115
116             altMovieParams = re.findall('data-mgid="([^"]*(?:episode|video).*?:.*?)"', webpage)
117             if len(altMovieParams) == 0:
118                 raise ExtractorError(u'unable to find Flash URL in webpage ' + url)
119             else:
120                 mMovieParams = [("http://media.mtvnservices.com/" + altMovieParams[0], altMovieParams[0])]
121
122         uri = mMovieParams[0][1]
123         indexUrl = 'http://shadow.comedycentral.com/feeds/video_player/mrss/?' + compat_urllib_parse.urlencode({'uri': uri})
124         indexXml = self._download_webpage(indexUrl, epTitle,
125                                           u'Downloading show index',
126                                           u'unable to download episode index')
127
128         results = []
129
130         idoc = xml.etree.ElementTree.fromstring(indexXml)
131         itemEls = idoc.findall('.//item')
132         for partNum,itemEl in enumerate(itemEls):
133             mediaId = itemEl.findall('./guid')[0].text
134             shortMediaId = mediaId.split(':')[-1]
135             showId = mediaId.split(':')[-2].replace('.com', '')
136             officialTitle = itemEl.findall('./title')[0].text
137             officialDate = unified_strdate(itemEl.findall('./pubDate')[0].text)
138
139             configUrl = ('http://www.comedycentral.com/global/feeds/entertainment/media/mediaGenEntertainment.jhtml?' +
140                         compat_urllib_parse.urlencode({'uri': mediaId}))
141             configXml = self._download_webpage(configUrl, epTitle,
142                                                u'Downloading configuration for %s' % shortMediaId)
143
144             cdoc = xml.etree.ElementTree.fromstring(configXml)
145             turls = []
146             for rendition in cdoc.findall('.//rendition'):
147                 finfo = (rendition.attrib['bitrate'], rendition.findall('./src')[0].text)
148                 turls.append(finfo)
149
150             if len(turls) == 0:
151                 self._downloader.report_error(u'unable to download ' + mediaId + ': No videos found')
152                 continue
153
154             if self._downloader.params.get('listformats', None):
155                 self._print_formats([i[0] for i in turls])
156                 return
157
158             # For now, just pick the highest bitrate
159             format,rtmp_video_url = turls[-1]
160
161             # Get the format arg from the arg stream
162             req_format = self._downloader.params.get('format', None)
163
164             # Select format if we can find one
165             for f,v in turls:
166                 if f == req_format:
167                     format, rtmp_video_url = f, v
168                     break
169
170             m = re.match(r'^rtmpe?://.*?/(?P<finalid>gsp.comedystor/.*)$', rtmp_video_url)
171             if not m:
172                 raise ExtractorError(u'Cannot transform RTMP url')
173             base = 'http://mtvnmobile.vo.llnwd.net/kip0/_pxn=1+_pxI0=Ripod-h264+_pxL0=undefined+_pxM0=+_pxK=18639+_pxE=mp4/44620/mtvnorigin/'
174             video_url = base + m.group('finalid')
175
176             effTitle = showId + u'-' + epTitle + u' part ' + compat_str(partNum+1)
177             info = {
178                 'id': shortMediaId,
179                 'url': video_url,
180                 'uploader': showId,
181                 'upload_date': officialDate,
182                 'title': effTitle,
183                 'ext': 'mp4',
184                 'format': format,
185                 'thumbnail': None,
186                 'description': compat_str(officialTitle),
187             }
188             results.append(info)
189
190         return results