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