]> jfr.im git - yt-dlp.git/blob - yt_dlp/extractor/cspan.py
[generic] Extract subtitles from video.js (#3156)
[yt-dlp.git] / yt_dlp / extractor / cspan.py
1 from __future__ import unicode_literals
2
3 import re
4
5 from .common import InfoExtractor
6 from ..compat import compat_HTMLParseError
7 from ..utils import (
8 determine_ext,
9 ExtractorError,
10 extract_attributes,
11 find_xpath_attr,
12 get_element_by_attribute,
13 get_element_by_class,
14 int_or_none,
15 join_nonempty,
16 js_to_json,
17 merge_dicts,
18 parse_iso8601,
19 parse_qs,
20 smuggle_url,
21 str_to_int,
22 unescapeHTML,
23 )
24 from .senategov import SenateISVPIE
25 from .ustream import UstreamIE
26
27
28 class CSpanIE(InfoExtractor):
29 _VALID_URL = r'https?://(?:www\.)?c-span\.org/video/\?(?P<id>[0-9a-f]+)'
30 IE_DESC = 'C-SPAN'
31 _TESTS = [{
32 'url': 'http://www.c-span.org/video/?313572-1/HolderonV',
33 'md5': '94b29a4f131ff03d23471dd6f60b6a1d',
34 'info_dict': {
35 'id': '315139',
36 'title': 'Attorney General Eric Holder on Voting Rights Act Decision',
37 },
38 'playlist_mincount': 2,
39 'skip': 'Regularly fails on travis, for unknown reasons',
40 }, {
41 'url': 'http://www.c-span.org/video/?c4486943/cspan-international-health-care-models',
42 # md5 is unstable
43 'info_dict': {
44 'id': 'c4486943',
45 'ext': 'mp4',
46 'title': 'CSPAN - International Health Care Models',
47 'description': 'md5:7a985a2d595dba00af3d9c9f0783c967',
48 }
49 }, {
50 'url': 'http://www.c-span.org/video/?318608-1/gm-ignition-switch-recall',
51 'info_dict': {
52 'id': '342759',
53 'title': 'General Motors Ignition Switch Recall',
54 },
55 'playlist_mincount': 6,
56 }, {
57 # Video from senate.gov
58 'url': 'http://www.c-span.org/video/?104517-1/immigration-reforms-needed-protect-skilled-american-workers',
59 'info_dict': {
60 'id': 'judiciary031715',
61 'ext': 'mp4',
62 'title': 'Immigration Reforms Needed to Protect Skilled American Workers',
63 },
64 'params': {
65 'skip_download': True, # m3u8 downloads
66 }
67 }, {
68 # Ustream embedded video
69 'url': 'https://www.c-span.org/video/?114917-1/armed-services',
70 'info_dict': {
71 'id': '58428542',
72 'ext': 'flv',
73 'title': 'USHR07 Armed Services Committee',
74 'description': 'hsas00-2118-20150204-1000et-07\n\n\nUSHR07 Armed Services Committee',
75 'timestamp': 1423060374,
76 'upload_date': '20150204',
77 'uploader': 'HouseCommittee',
78 'uploader_id': '12987475',
79 },
80 }, {
81 # Audio Only
82 'url': 'https://www.c-span.org/video/?437336-1/judiciary-antitrust-competition-policy-consumer-rights',
83 'only_matching': True,
84 }]
85 BRIGHTCOVE_URL_TEMPLATE = 'http://players.brightcove.net/%s/%s_%s/index.html?videoId=%s'
86
87 def _real_extract(self, url):
88 video_id = self._match_id(url)
89 video_type = None
90 webpage = self._download_webpage(url, video_id)
91
92 ustream_url = UstreamIE._extract_url(webpage)
93 if ustream_url:
94 return self.url_result(ustream_url, UstreamIE.ie_key())
95
96 if '&vod' not in url:
97 bc = self._search_regex(
98 r"(<[^>]+id='brightcove-player-embed'[^>]+>)",
99 webpage, 'brightcove embed', default=None)
100 if bc:
101 bc_attr = extract_attributes(bc)
102 bc_url = self.BRIGHTCOVE_URL_TEMPLATE % (
103 bc_attr.get('data-bcaccountid', '3162030207001'),
104 bc_attr.get('data-noprebcplayerid', 'SyGGpuJy3g'),
105 bc_attr.get('data-newbcplayerid', 'default'),
106 bc_attr['data-bcid'])
107 return self.url_result(smuggle_url(bc_url, {'source_url': url}))
108
109 def add_referer(formats):
110 for f in formats:
111 f.setdefault('http_headers', {})['Referer'] = url
112
113 # As of 01.12.2020 this path looks to cover all cases making the rest
114 # of the code unnecessary
115 jwsetup = self._parse_json(
116 self._search_regex(
117 r'(?s)jwsetup\s*=\s*({.+?})\s*;', webpage, 'jwsetup',
118 default='{}'),
119 video_id, transform_source=js_to_json, fatal=False)
120 if jwsetup:
121 info = self._parse_jwplayer_data(
122 jwsetup, video_id, require_title=False, m3u8_id='hls',
123 base_url=url)
124 add_referer(info['formats'])
125 for subtitles in info['subtitles'].values():
126 for subtitle in subtitles:
127 ext = determine_ext(subtitle['url'])
128 if ext == 'php':
129 ext = 'vtt'
130 subtitle['ext'] = ext
131 ld_info = self._search_json_ld(webpage, video_id, default={})
132 try:
133 title = get_element_by_class('video-page-title', webpage)
134 except compat_HTMLParseError:
135 title = None
136 if title is None:
137 title = self._og_search_title(webpage)
138 description = get_element_by_attribute('itemprop', 'description', webpage) or \
139 self._html_search_meta(['og:description', 'description'], webpage)
140 return merge_dicts(info, ld_info, {
141 'title': title,
142 'thumbnail': get_element_by_attribute('itemprop', 'thumbnailUrl', webpage),
143 'description': description,
144 'timestamp': parse_iso8601(get_element_by_attribute('itemprop', 'uploadDate', webpage)),
145 'location': get_element_by_attribute('itemprop', 'contentLocation', webpage),
146 'duration': int_or_none(self._search_regex(
147 r'jwsetup\.seclength\s*=\s*(\d+);',
148 webpage, 'duration', fatal=False)),
149 'view_count': str_to_int(self._search_regex(
150 r"<span[^>]+class='views'[^>]*>([\d,]+)\s+Views</span>",
151 webpage, 'views', fatal=False)),
152 })
153
154 # Obsolete
155 # We first look for clipid, because clipprog always appears before
156 patterns = [r'id=\'clip(%s)\'\s*value=\'([0-9]+)\'' % t for t in ('id', 'prog')]
157 results = list(filter(None, (re.search(p, webpage) for p in patterns)))
158 if results:
159 matches = results[0]
160 video_type, video_id = matches.groups()
161 video_type = 'clip' if video_type == 'id' else 'program'
162 else:
163 m = re.search(r'data-(?P<type>clip|prog)id=["\'](?P<id>\d+)', webpage)
164 if m:
165 video_id = m.group('id')
166 video_type = 'program' if m.group('type') == 'prog' else 'clip'
167 else:
168 senate_isvp_url = SenateISVPIE._search_iframe_url(webpage)
169 if senate_isvp_url:
170 title = self._og_search_title(webpage)
171 surl = smuggle_url(senate_isvp_url, {'force_title': title})
172 return self.url_result(surl, 'SenateISVP', video_id, title)
173 video_id = self._search_regex(
174 r'jwsetup\.clipprog\s*=\s*(\d+);',
175 webpage, 'jwsetup program id', default=None)
176 if video_id:
177 video_type = 'program'
178 if video_type is None or video_id is None:
179 error_message = get_element_by_class('VLplayer-error-message', webpage)
180 if error_message:
181 raise ExtractorError(error_message)
182 raise ExtractorError('unable to find video id and type')
183
184 def get_text_attr(d, attr):
185 return d.get(attr, {}).get('#text')
186
187 data = self._download_json(
188 'http://www.c-span.org/assets/player/ajax-player.php?os=android&html5=%s&id=%s' % (video_type, video_id),
189 video_id)['video']
190 if data['@status'] != 'Success':
191 raise ExtractorError('%s said: %s' % (self.IE_NAME, get_text_attr(data, 'error')), expected=True)
192
193 doc = self._download_xml(
194 'http://www.c-span.org/common/services/flashXml.php?%sid=%s' % (video_type, video_id),
195 video_id)
196
197 description = self._html_search_meta('description', webpage)
198
199 title = find_xpath_attr(doc, './/string', 'name', 'title').text
200 thumbnail = find_xpath_attr(doc, './/string', 'name', 'poster').text
201
202 files = data['files']
203 capfile = get_text_attr(data, 'capfile')
204
205 entries = []
206 for partnum, f in enumerate(files):
207 formats = []
208 for quality in f.get('qualities', []):
209 formats.append({
210 'format_id': '%s-%sp' % (get_text_attr(quality, 'bitrate'), get_text_attr(quality, 'height')),
211 'url': unescapeHTML(get_text_attr(quality, 'file')),
212 'height': int_or_none(get_text_attr(quality, 'height')),
213 'tbr': int_or_none(get_text_attr(quality, 'bitrate')),
214 })
215 if not formats:
216 path = unescapeHTML(get_text_attr(f, 'path'))
217 if not path:
218 continue
219 formats = self._extract_m3u8_formats(
220 path, video_id, 'mp4', entry_protocol='m3u8_native',
221 m3u8_id='hls') if determine_ext(path) == 'm3u8' else [{'url': path, }]
222 add_referer(formats)
223 self._sort_formats(formats)
224 entries.append({
225 'id': '%s_%d' % (video_id, partnum + 1),
226 'title': (
227 title if len(files) == 1 else
228 '%s part %d' % (title, partnum + 1)),
229 'formats': formats,
230 'description': description,
231 'thumbnail': thumbnail,
232 'duration': int_or_none(get_text_attr(f, 'length')),
233 'subtitles': {
234 'en': [{
235 'url': capfile,
236 'ext': determine_ext(capfile, 'dfxp')
237 }],
238 } if capfile else None,
239 })
240
241 if len(entries) == 1:
242 entry = dict(entries[0])
243 entry['id'] = 'c' + video_id if video_type == 'clip' else video_id
244 return entry
245 else:
246 return {
247 '_type': 'playlist',
248 'entries': entries,
249 'title': title,
250 'id': 'c' + video_id if video_type == 'clip' else video_id,
251 }
252
253
254 class CSpanCongressIE(InfoExtractor):
255 _VALID_URL = r'https?://(?:www\.)?c-span\.org/congress/'
256 _TESTS = [{
257 'url': 'https://www.c-span.org/congress/?chamber=house&date=2017-12-13&t=1513208380',
258 'info_dict': {
259 'id': 'house_2017-12-13',
260 'title': 'Congressional Chronicle - Members of Congress, Hearings and More',
261 'description': 'md5:54c264b7a8f219937987610243305a84',
262 'thumbnail': r're:https://ximage.c-spanvideo.org/.+',
263 'ext': 'mp4'
264 }
265 }]
266
267 def _real_extract(self, url):
268 query = parse_qs(url)
269 video_date = query.get('date', [None])[0]
270 video_id = join_nonempty(query.get('chamber', ['senate'])[0], video_date, delim='_')
271 webpage = self._download_webpage(url, video_id)
272 if not video_date:
273 jwp_date = re.search(r'jwsetup.clipprogdate = \'(?P<date>\d{4}-\d{2}-\d{2})\';', webpage)
274 if jwp_date:
275 video_id = f'{video_id}_{jwp_date.group("date")}'
276 jwplayer_data = self._parse_json(
277 self._search_regex(r'jwsetup\s*=\s*({(?:.|\n)[^;]+});', webpage, 'player config'),
278 video_id, transform_source=js_to_json)
279
280 title = (self._og_search_title(webpage, default=None)
281 or self._html_search_regex(r'(?s)<title>(.*?)</title>', webpage, 'video title'))
282 description = (self._og_search_description(webpage, default=None)
283 or self._html_search_meta('description', webpage, 'description', default=None))
284
285 return {
286 **self._parse_jwplayer_data(jwplayer_data, video_id, False),
287 'title': re.sub(r'\s+', ' ', title.split('|')[0]).strip(),
288 'description': description,
289 'http_headers': {'Referer': 'https://www.c-span.org/'},
290 }