]> Raphaƫl G. Git Repositories - youtubedl/blob - youtube_dl/extractor/comedycentral.py
Update changelog.
[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': (1280, 720),
55 '2200': (960, 540),
56 '1700': (768, 432),
57 '1200': (640, 360),
58 '750': (512, 288),
59 '400': (384, 216),
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 @staticmethod
68 def _transform_rtmp_url(rtmp_video_url):
69 m = re.match(r'^rtmpe?://.*?/(?P<finalid>gsp.comedystor/.*)$', rtmp_video_url)
70 if not m:
71 raise ExtractorError(u'Cannot transform RTMP url')
72 base = 'http://mtvnmobile.vo.llnwd.net/kip0/_pxn=1+_pxI0=Ripod-h264+_pxL0=undefined+_pxM0=+_pxK=18639+_pxE=mp4/44620/mtvnorigin/'
73 return base + m.group('finalid')
74
75 def _real_extract(self, url):
76 mobj = re.match(self._VALID_URL, url, re.VERBOSE)
77 if mobj is None:
78 raise ExtractorError(u'Invalid URL: %s' % url)
79
80 if mobj.group('shortname'):
81 if mobj.group('shortname') in ('tds', 'thedailyshow'):
82 url = u'http://www.thedailyshow.com/full-episodes/'
83 else:
84 url = u'http://www.colbertnation.com/full-episodes/'
85 mobj = re.match(self._VALID_URL, url, re.VERBOSE)
86 assert mobj is not None
87
88 if mobj.group('clip'):
89 if mobj.group('showname') == 'thedailyshow':
90 epTitle = mobj.group('tdstitle')
91 else:
92 epTitle = mobj.group('cntitle')
93 dlNewest = False
94 elif mobj.group('interview'):
95 epTitle = mobj.group('interview_title')
96 dlNewest = False
97 else:
98 dlNewest = not mobj.group('episode')
99 if dlNewest:
100 epTitle = mobj.group('showname')
101 else:
102 epTitle = mobj.group('episode')
103
104 self.report_extraction(epTitle)
105 webpage,htmlHandle = self._download_webpage_handle(url, epTitle)
106 if dlNewest:
107 url = htmlHandle.geturl()
108 mobj = re.match(self._VALID_URL, url, re.VERBOSE)
109 if mobj is None:
110 raise ExtractorError(u'Invalid redirected URL: ' + url)
111 if mobj.group('episode') == '':
112 raise ExtractorError(u'Redirected URL is still not specific: ' + url)
113 epTitle = mobj.group('episode')
114
115 mMovieParams = re.findall('(?:<param name="movie" value="|var url = ")(http://media.mtvnservices.com/([^"]*(?:episode|video).*?:.*?))"', webpage)
116
117 if len(mMovieParams) == 0:
118 # The Colbert Report embeds the information in a without
119 # a URL prefix; so extract the alternate reference
120 # and then add the URL prefix manually.
121
122 altMovieParams = re.findall('data-mgid="([^"]*(?:episode|video).*?:.*?)"', webpage)
123 if len(altMovieParams) == 0:
124 raise ExtractorError(u'unable to find Flash URL in webpage ' + url)
125 else:
126 mMovieParams = [("http://media.mtvnservices.com/" + altMovieParams[0], altMovieParams[0])]
127
128 uri = mMovieParams[0][1]
129 indexUrl = 'http://shadow.comedycentral.com/feeds/video_player/mrss/?' + compat_urllib_parse.urlencode({'uri': uri})
130 indexXml = self._download_webpage(indexUrl, epTitle,
131 u'Downloading show index',
132 u'unable to download episode index')
133
134 results = []
135
136 idoc = xml.etree.ElementTree.fromstring(indexXml)
137 itemEls = idoc.findall('.//item')
138 for partNum,itemEl in enumerate(itemEls):
139 mediaId = itemEl.findall('./guid')[0].text
140 shortMediaId = mediaId.split(':')[-1]
141 showId = mediaId.split(':')[-2].replace('.com', '')
142 officialTitle = itemEl.findall('./title')[0].text
143 officialDate = unified_strdate(itemEl.findall('./pubDate')[0].text)
144
145 configUrl = ('http://www.comedycentral.com/global/feeds/entertainment/media/mediaGenEntertainment.jhtml?' +
146 compat_urllib_parse.urlencode({'uri': mediaId}))
147 configXml = self._download_webpage(configUrl, epTitle,
148 u'Downloading configuration for %s' % shortMediaId)
149
150 cdoc = xml.etree.ElementTree.fromstring(configXml)
151 turls = []
152 for rendition in cdoc.findall('.//rendition'):
153 finfo = (rendition.attrib['bitrate'], rendition.findall('./src')[0].text)
154 turls.append(finfo)
155
156 if len(turls) == 0:
157 self._downloader.report_error(u'unable to download ' + mediaId + ': No videos found')
158 continue
159
160 formats = []
161 for format, rtmp_video_url in turls:
162 w, h = self._video_dimensions.get(format, (None, None))
163 formats.append({
164 'url': self._transform_rtmp_url(rtmp_video_url),
165 'ext': self._video_extensions.get(format, 'mp4'),
166 'format_id': format,
167 'height': h,
168 'width': w,
169 })
170
171 effTitle = showId + u'-' + epTitle + u' part ' + compat_str(partNum+1)
172 info = {
173 'id': shortMediaId,
174 'formats': formats,
175 'uploader': showId,
176 'upload_date': officialDate,
177 'title': effTitle,
178 'thumbnail': None,
179 'description': compat_str(officialTitle),
180 }
181
182 # TODO: Remove when #980 has been merged
183 info.update(info['formats'][-1])
184
185 results.append(info)
186
187 return results