cspan.py 12 KB

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