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