]> jfr.im git - yt-dlp.git/blame - yt_dlp/extractor/cspan.py
[cleanup, docs] Misc cleanup
[yt-dlp.git] / yt_dlp / extractor / cspan.py
CommitLineData
ca9e7922
PH
1from __future__ import unicode_literals
2
aa0c8739
JMF
3import re
4
5from .common import InfoExtractor
edecb5f8 6from ..compat import compat_HTMLParseError
aa0c8739 7from ..utils import (
672f1bd8 8 determine_ext,
355c7ad3 9 ExtractorError,
5996d21a 10 extract_attributes,
7e810109 11 find_xpath_attr,
30a074c2 12 get_element_by_attribute,
7e810109
RA
13 get_element_by_class,
14 int_or_none,
edecb5f8 15 join_nonempty,
29f7c58a 16 js_to_json,
17 merge_dicts,
30a074c2 18 parse_iso8601,
edecb5f8 19 parse_qs,
7e810109 20 smuggle_url,
30a074c2 21 str_to_int,
7e810109 22 unescapeHTML,
aa0c8739 23)
909b0d66 24from .senategov import SenateISVPIE
4447fb23 25from .ustream import UstreamIE
aa0c8739 26
ca9e7922 27
aa0c8739 28class CSpanIE(InfoExtractor):
5886b38d 29 _VALID_URL = r'https?://(?:www\.)?c-span\.org/video/\?(?P<id>[0-9a-f]+)'
ca9e7922 30 IE_DESC = 'C-SPAN'
11a15be4 31 _TESTS = [{
009a3408 32 'url': 'http://www.c-span.org/video/?313572-1/HolderonV',
355c7ad3 33 'md5': '94b29a4f131ff03d23471dd6f60b6a1d',
ca9e7922 34 'info_dict': {
009a3408 35 'id': '315139',
ca9e7922 36 'title': 'Attorney General Eric Holder on Voting Rights Act Decision',
6f5ac90c 37 },
f3c21cb7 38 'playlist_mincount': 2,
11577ec0 39 'skip': 'Regularly fails on travis, for unknown reasons',
11a15be4
PH
40 }, {
41 'url': 'http://www.c-span.org/video/?c4486943/cspan-international-health-care-models',
f3c21cb7 42 # md5 is unstable
11a15be4 43 'info_dict': {
30787f72 44 'id': 'c4486943',
11a15be4 45 'ext': 'mp4',
30787f72 46 'title': 'CSPAN - International Health Care Models',
11a15be4
PH
47 'description': 'md5:7a985a2d595dba00af3d9c9f0783c967',
48 }
22a6f150
PH
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 },
f3c21cb7 55 'playlist_mincount': 6,
2fe1b5bd
YCH
56 }, {
57 # Video from senate.gov
58 'url': 'http://www.c-span.org/video/?104517-1/immigration-reforms-needed-protect-skilled-american-workers',
2fe1b5bd
YCH
59 'info_dict': {
60 'id': 'judiciary031715',
7b0d333a 61 'ext': 'mp4',
2fe1b5bd 62 'title': 'Immigration Reforms Needed to Protect Skilled American Workers',
7b0d333a
NP
63 },
64 'params': {
65 'skip_download': True, # m3u8 downloads
2fe1b5bd 66 }
4447fb23
YCH
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 },
7e810109
RA
80 }, {
81 # Audio Only
82 'url': 'https://www.c-span.org/video/?437336-1/judiciary-antitrust-competition-policy-consumer-rights',
83 'only_matching': True,
11a15be4 84 }]
5996d21a 85 BRIGHTCOVE_URL_TEMPLATE = 'http://players.brightcove.net/%s/%s_%s/index.html?videoId=%s'
aa0c8739
JMF
86
87 def _real_extract(self, url):
30787f72 88 video_id = self._match_id(url)
04e24906 89 video_type = None
30787f72 90 webpage = self._download_webpage(url, video_id)
4447fb23
YCH
91
92 ustream_url = UstreamIE._extract_url(webpage)
93 if ustream_url:
94 return self.url_result(ustream_url, UstreamIE.ie_key())
95
5996d21a
RA
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
29f7c58a 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'])
30a074c2 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
29f7c58a 131 ld_info = self._search_json_ld(webpage, video_id, default={})
edecb5f8
G
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)
30a074c2 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 })
29f7c58a 153
154 # Obsolete
6c6b8bd5
JMF
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]
30787f72 160 video_type, video_id = matches.groups()
6c6b8bd5 161 video_type = 'clip' if video_type == 'id' else 'program'
30787f72 162 else:
f6932135
S
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)
7e810109
RA
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'
04e24906 178 if video_type is None or video_id is None:
7e810109
RA
179 error_message = get_element_by_class('VLplayer-error-message', webpage)
180 if error_message:
181 raise ExtractorError(error_message)
04e24906 182 raise ExtractorError('unable to find video id and type')
ca9e7922 183
2a776f97 184 def get_text_attr(d, attr):
185 return d.get(attr, {}).get('#text')
186
30787f72 187 data = self._download_json(
355c7ad3 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':
2a776f97 191 raise ExtractorError('%s said: %s' % (self.IE_NAME, get_text_attr(data, 'error')), expected=True)
ca9e7922 192
aea6e7fc 193 doc = self._download_xml(
30787f72 194 'http://www.c-span.org/common/services/flashXml.php?%sid=%s' % (video_type, video_id),
009a3408
JMF
195 video_id)
196
30787f72 197 description = self._html_search_meta('description', webpage)
198
aea6e7fc
PH
199 title = find_xpath_attr(doc, './/string', 'name', 'title').text
200 thumbnail = find_xpath_attr(doc, './/string', 'name', 'poster').text
201
355c7ad3 202 files = data['files']
2a776f97 203 capfile = get_text_attr(data, 'capfile')
aea6e7fc 204
355c7ad3 205 entries = []
206 for partnum, f in enumerate(files):
207 formats = []
7e810109 208 for quality in f.get('qualities', []):
355c7ad3 209 formats.append({
2a776f97 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')),
355c7ad3 214 })
af9c2a07 215 if not formats:
68a0ea15 216 path = unescapeHTML(get_text_attr(f, 'path'))
af9c2a07
S
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, }]
29f7c58a 222 add_referer(formats)
355c7ad3 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,
2a776f97 232 'duration': int_or_none(get_text_attr(f, 'length')),
355c7ad3 233 'subtitles': {
234 'en': [{
235 'url': capfile,
236 'ext': determine_ext(capfile, 'dfxp')
237 }],
238 } if capfile else None,
239 })
009a3408 240
92dcba1e
YCH
241 if len(entries) == 1:
242 entry = dict(entries[0])
30787f72 243 entry['id'] = 'c' + video_id if video_type == 'clip' else video_id
92dcba1e
YCH
244 return entry
245 else:
246 return {
247 '_type': 'playlist',
248 'entries': entries,
249 'title': title,
30787f72 250 'id': 'c' + video_id if video_type == 'clip' else video_id,
92dcba1e 251 }
edecb5f8
G
252
253
254class 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 }