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