brightcove.py 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951
  1. import base64
  2. import re
  3. import struct
  4. import xml.etree.ElementTree
  5. from .adobepass import AdobePassIE
  6. from .common import InfoExtractor
  7. from ..compat import (
  8. compat_etree_fromstring,
  9. compat_HTTPError,
  10. compat_parse_qs,
  11. compat_urlparse,
  12. )
  13. from ..utils import (
  14. clean_html,
  15. dict_get,
  16. extract_attributes,
  17. ExtractorError,
  18. find_xpath_attr,
  19. fix_xml_ampersands,
  20. float_or_none,
  21. int_or_none,
  22. js_to_json,
  23. mimetype2ext,
  24. parse_iso8601,
  25. parse_qs,
  26. smuggle_url,
  27. str_or_none,
  28. try_get,
  29. unescapeHTML,
  30. unsmuggle_url,
  31. UnsupportedError,
  32. update_url_query,
  33. url_or_none,
  34. )
  35. class BrightcoveLegacyIE(InfoExtractor):
  36. IE_NAME = 'brightcove:legacy'
  37. _VALID_URL = r'(?:https?://.*brightcove\.com/(services|viewer).*?\?|brightcove:)(?P<query>.*)'
  38. _TESTS = [
  39. {
  40. # From http://www.8tv.cat/8aldia/videos/xavier-sala-i-martin-aquesta-tarda-a-8-al-dia/
  41. 'url': 'http://c.brightcove.com/services/viewer/htmlFederated?playerID=1654948606001&flashID=myExperience&%40videoPlayer=2371591881001',
  42. 'md5': '5423e113865d26e40624dce2e4b45d95',
  43. 'note': 'Test Brightcove downloads and detection in GenericIE',
  44. 'info_dict': {
  45. 'id': '2371591881001',
  46. 'ext': 'mp4',
  47. 'title': 'Xavier Sala i Martín: “Un banc que no presta és un banc zombi que no serveix per a res”',
  48. 'uploader': '8TV',
  49. 'description': 'md5:a950cc4285c43e44d763d036710cd9cd',
  50. 'timestamp': 1368213670,
  51. 'upload_date': '20130510',
  52. 'uploader_id': '1589608506001',
  53. },
  54. 'skip': 'The player has been deactivated by the content owner',
  55. },
  56. {
  57. # From http://medianetwork.oracle.com/video/player/1785452137001
  58. 'url': 'http://c.brightcove.com/services/viewer/htmlFederated?playerID=1217746023001&flashID=myPlayer&%40videoPlayer=1785452137001',
  59. 'info_dict': {
  60. 'id': '1785452137001',
  61. 'ext': 'flv',
  62. 'title': 'JVMLS 2012: Arrays 2.0 - Opportunities and Challenges',
  63. 'description': 'John Rose speaks at the JVM Language Summit, August 1, 2012.',
  64. 'uploader': 'Oracle',
  65. 'timestamp': 1344975024,
  66. 'upload_date': '20120814',
  67. 'uploader_id': '1460825906',
  68. },
  69. 'skip': 'video not playable',
  70. },
  71. {
  72. # From http://mashable.com/2013/10/26/thermoelectric-bracelet-lets-you-control-your-body-temperature/
  73. 'url': 'http://c.brightcove.com/services/viewer/federated_f9?&playerID=1265504713001&publisherID=AQ%7E%7E%2CAAABBzUwv1E%7E%2CxP-xFHVUstiMFlNYfvF4G9yFnNaqCw_9&videoID=2750934548001',
  74. 'info_dict': {
  75. 'id': '2750934548001',
  76. 'ext': 'mp4',
  77. 'title': 'This Bracelet Acts as a Personal Thermostat',
  78. 'description': 'md5:547b78c64f4112766ccf4e151c20b6a0',
  79. # 'uploader': 'Mashable',
  80. 'timestamp': 1382041798,
  81. 'upload_date': '20131017',
  82. 'uploader_id': '1130468786001',
  83. },
  84. },
  85. {
  86. # test that the default referer works
  87. # from http://national.ballet.ca/interact/video/Lost_in_Motion_II/
  88. 'url': 'http://link.brightcove.com/services/player/bcpid756015033001?bckey=AQ~~,AAAApYJi_Ck~,GxhXCegT1Dp39ilhXuxMJxasUhVNZiil&bctid=2878862109001',
  89. 'info_dict': {
  90. 'id': '2878862109001',
  91. 'ext': 'mp4',
  92. 'title': 'Lost in Motion II',
  93. 'description': 'md5:363109c02998fee92ec02211bd8000df',
  94. 'uploader': 'National Ballet of Canada',
  95. },
  96. 'skip': 'Video gone',
  97. },
  98. {
  99. # test flv videos served by akamaihd.net
  100. # From http://www.redbull.com/en/bike/stories/1331655643987/replay-uci-dh-world-cup-2014-from-fort-william
  101. 'url': 'http://c.brightcove.com/services/viewer/htmlFederated?%40videoPlayer=ref%3Aevent-stream-356&linkBaseURL=http%3A%2F%2Fwww.redbull.com%2Fen%2Fbike%2Fvideos%2F1331655630249%2Freplay-uci-fort-william-2014-dh&playerKey=AQ%7E%7E%2CAAAApYJ7UqE%7E%2Cxqr_zXk0I-zzNndy8NlHogrCb5QdyZRf&playerID=1398061561001#__youtubedl_smuggle=%7B%22Referer%22%3A+%22http%3A%2F%2Fwww.redbull.com%2Fen%2Fbike%2Fstories%2F1331655643987%2Freplay-uci-dh-world-cup-2014-from-fort-william%22%7D',
  102. # The md5 checksum changes on each download
  103. 'info_dict': {
  104. 'id': '3750436379001',
  105. 'ext': 'flv',
  106. 'title': 'UCI MTB World Cup 2014: Fort William, UK - Downhill Finals',
  107. 'uploader': 'RBTV Old (do not use)',
  108. 'description': 'UCI MTB World Cup 2014: Fort William, UK - Downhill Finals',
  109. 'timestamp': 1409122195,
  110. 'upload_date': '20140827',
  111. 'uploader_id': '710858724001',
  112. },
  113. 'skip': 'Video gone',
  114. },
  115. {
  116. # playlist with 'videoList'
  117. # from http://support.brightcove.com/en/video-cloud/docs/playlist-support-single-video-players
  118. 'url': 'http://c.brightcove.com/services/viewer/htmlFederated?playerID=3550052898001&playerKey=AQ%7E%7E%2CAAABmA9XpXk%7E%2C-Kp7jNgisre1fG5OdqpAFUTcs0lP_ZoL',
  119. 'info_dict': {
  120. 'title': 'Sealife',
  121. 'id': '3550319591001',
  122. },
  123. 'playlist_mincount': 7,
  124. 'skip': 'Unsupported URL',
  125. },
  126. {
  127. # playlist with 'playlistTab' (https://github.com/ytdl-org/youtube-dl/issues/9965)
  128. 'url': 'http://c.brightcove.com/services/json/experience/runtime/?command=get_programming_for_experience&playerKey=AQ%7E%7E,AAABXlLMdok%7E,NJ4EoMlZ4rZdx9eU1rkMVd8EaYPBBUlg',
  129. 'info_dict': {
  130. 'id': '1522758701001',
  131. 'title': 'Lesson 08',
  132. },
  133. 'playlist_mincount': 10,
  134. 'skip': 'Unsupported URL',
  135. },
  136. {
  137. # playerID inferred from bcpid
  138. # from http://www.un.org/chinese/News/story.asp?NewsID=27724
  139. 'url': 'https://link.brightcove.com/services/player/bcpid1722935254001/?bctid=5360463607001&autoStart=false&secureConnections=true&width=650&height=350',
  140. 'only_matching': True, # Tested in GenericIE
  141. }
  142. ]
  143. _WEBPAGE_TESTS = [{
  144. # embedded brightcove video
  145. # it also tests brightcove videos that need to set the 'Referer'
  146. # in the http requests
  147. 'url': 'http://www.bfmtv.com/video/bfmbusiness/cours-bourse/cours-bourse-l-analyse-technique-154522/',
  148. 'info_dict': {
  149. 'id': '2765128793001',
  150. 'ext': 'mp4',
  151. 'title': 'Le cours de bourse : l’analyse technique',
  152. 'description': 'md5:7e9ad046e968cb2d1114004aba466fd9',
  153. 'uploader': 'BFM BUSINESS',
  154. },
  155. 'params': {
  156. 'skip_download': True,
  157. },
  158. 'skip': '404 Not Found',
  159. }, {
  160. # embedded with itemprop embedURL and video id spelled as `idVideo`
  161. 'url': 'http://bfmbusiness.bfmtv.com/mediaplayer/chroniques/olivier-delamarche/',
  162. 'info_dict': {
  163. 'id': '5255628253001',
  164. 'ext': 'mp4',
  165. 'title': 'md5:37c519b1128915607601e75a87995fc0',
  166. 'description': 'md5:37f7f888b434bb8f8cc8dbd4f7a4cf26',
  167. 'uploader': 'BFM BUSINESS',
  168. 'uploader_id': '876450612001',
  169. 'timestamp': 1482255315,
  170. 'upload_date': '20161220',
  171. },
  172. 'params': {
  173. 'skip_download': True,
  174. },
  175. 'skip': 'Redirects, page gone',
  176. }, {
  177. # https://github.com/ytdl-org/youtube-dl/issues/2253
  178. 'url': 'http://bcove.me/i6nfkrc3',
  179. 'md5': '0ba9446db037002366bab3b3eb30c88c',
  180. 'info_dict': {
  181. 'id': '3101154703001',
  182. 'ext': 'mp4',
  183. 'title': 'Still no power',
  184. 'uploader': 'thestar.com',
  185. 'description': 'Mississauga resident David Farmer is still out of power as a result of the ice storm a month ago. To keep the house warm, Farmer cuts wood from his property for a wood burning stove downstairs.',
  186. },
  187. 'skip': 'video gone',
  188. }, {
  189. # https://github.com/ytdl-org/youtube-dl/issues/3541
  190. 'url': 'http://www.kijk.nl/sbs6/leermijvrouwenkennen/videos/jqMiXKAYan2S/aflevering-1',
  191. 'info_dict': {
  192. 'id': '3866516442001',
  193. 'ext': 'mp4',
  194. 'title': 'Leer mij vrouwen kennen: Aflevering 1',
  195. 'description': 'Leer mij vrouwen kennen: Aflevering 1',
  196. 'uploader': 'SBS Broadcasting',
  197. },
  198. 'skip': 'Restricted to Netherlands, 404 Not Found',
  199. 'params': {
  200. 'skip_download': True, # m3u8 download
  201. },
  202. }, {
  203. # Brightcove video in <iframe>
  204. 'url': 'http://www.un.org/chinese/News/story.asp?NewsID=27724',
  205. 'md5': '36d74ef5e37c8b4a2ce92880d208b968',
  206. 'info_dict': {
  207. 'id': '5360463607001',
  208. 'ext': 'mp4',
  209. 'title': '叙利亚失明儿童在废墟上演唱《心跳》 呼吁获得正常童年生活',
  210. 'description': '联合国儿童基金会中东和北非区域大使、作曲家扎德·迪拉尼(Zade Dirani)在3月15日叙利亚冲突爆发7周年纪念日之际发布了为叙利亚谱写的歌曲《心跳》(HEARTBEAT),为受到六年冲突影响的叙利亚儿童发出强烈呐喊,呼吁世界做出共同努力,使叙利亚儿童重新获得享有正常童年生活的权利。',
  211. 'uploader': 'United Nations',
  212. 'uploader_id': '1362235914001',
  213. 'timestamp': 1489593889,
  214. 'upload_date': '20170315',
  215. },
  216. 'skip': '404 Not Found',
  217. }, {
  218. # Brightcove with UUID in videoPlayer
  219. 'url': 'http://www8.hp.com/cn/zh/home.html',
  220. 'info_dict': {
  221. 'id': '5255815316001',
  222. 'ext': 'mp4',
  223. 'title': 'Sprocket Video - China',
  224. 'description': 'Sprocket Video - China',
  225. 'uploader': 'HP-Video Gallery',
  226. 'timestamp': 1482263210,
  227. 'upload_date': '20161220',
  228. 'uploader_id': '1107601872001',
  229. },
  230. 'params': {
  231. 'skip_download': True, # m3u8 download
  232. },
  233. 'skip': 'video rotates...weekly?',
  234. }, {
  235. # Multiple brightcove videos
  236. # https://github.com/ytdl-org/youtube-dl/issues/2283
  237. 'url': 'http://www.newyorker.com/online/blogs/newsdesk/2014/01/always-never-nuclear-command-and-control.html',
  238. 'info_dict': {
  239. 'id': 'always-never',
  240. 'title': 'Always / Never - The New Yorker',
  241. },
  242. 'playlist_count': 3,
  243. 'params': {
  244. 'extract_flat': False,
  245. 'skip_download': True,
  246. },
  247. 'skip': 'Redirects, page gone',
  248. }, {
  249. # BrightcoveInPageEmbed embed
  250. 'url': 'http://www.geekandsundry.com/tabletop-bonus-wils-final-thoughts-on-dread/',
  251. 'info_dict': {
  252. 'id': '4238694884001',
  253. 'ext': 'flv',
  254. 'title': 'Tabletop: Dread, Last Thoughts',
  255. 'description': 'Tabletop: Dread, Last Thoughts',
  256. 'duration': 51690,
  257. },
  258. 'skip': 'Redirects, page gone',
  259. }, {
  260. # Brightcove embed, with no valid 'renditions' but valid 'IOSRenditions'
  261. # This video can't be played in browsers if Flash disabled and UA set to iPhone, which is actually a false alarm
  262. 'url': 'https://dl.dropboxusercontent.com/u/29092637/interview.html',
  263. 'info_dict': {
  264. 'id': '4785848093001',
  265. 'ext': 'mp4',
  266. 'title': 'The Cardinal Pell Interview',
  267. 'description': 'Sky News Contributor Andrew Bolt interviews George Pell in Rome, following the Cardinal\'s evidence before the Royal Commission into Child Abuse. ',
  268. 'uploader': 'GlobeCast Australia - GlobeStream',
  269. 'uploader_id': '2733773828001',
  270. 'upload_date': '20160304',
  271. 'timestamp': 1457083087,
  272. },
  273. 'params': {
  274. # m3u8 downloads
  275. 'skip_download': True,
  276. },
  277. 'skip': '404 Not Found',
  278. }, {
  279. # Brightcove embed with whitespace around attribute names
  280. 'url': 'http://www.stack.com/video/3167554373001/learn-to-hit-open-three-pointers-with-damian-lillard-s-baseline-drift-drill',
  281. 'info_dict': {
  282. 'id': '3167554373001',
  283. 'ext': 'mp4',
  284. 'title': "Learn to Hit Open Three-Pointers With Damian Lillard's Baseline Drift Drill",
  285. 'description': 'md5:57bacb0e0f29349de4972bfda3191713',
  286. 'uploader_id': '1079349493',
  287. 'upload_date': '20140207',
  288. 'timestamp': 1391810548,
  289. },
  290. 'params': {
  291. 'skip_download': True,
  292. },
  293. 'skip': '410 Gone',
  294. }]
  295. @classmethod
  296. def _build_brightcove_url(cls, object_str):
  297. """
  298. Build a Brightcove url from a xml string containing
  299. <object class="BrightcoveExperience">{params}</object>
  300. """
  301. # Fix up some stupid HTML, see https://github.com/ytdl-org/youtube-dl/issues/1553
  302. object_str = re.sub(r'(<param(?:\s+[a-zA-Z0-9_]+="[^"]*")*)>',
  303. lambda m: m.group(1) + '/>', object_str)
  304. # Fix up some stupid XML, see https://github.com/ytdl-org/youtube-dl/issues/1608
  305. object_str = object_str.replace('<--', '<!--')
  306. # remove namespace to simplify extraction
  307. object_str = re.sub(r'(<object[^>]*)(xmlns=".*?")', r'\1', object_str)
  308. object_str = fix_xml_ampersands(object_str)
  309. try:
  310. object_doc = compat_etree_fromstring(object_str.encode('utf-8'))
  311. except xml.etree.ElementTree.ParseError:
  312. return
  313. fv_el = find_xpath_attr(object_doc, './param', 'name', 'flashVars')
  314. if fv_el is not None:
  315. flashvars = dict(
  316. (k, v[0])
  317. for k, v in compat_parse_qs(fv_el.attrib['value']).items())
  318. else:
  319. flashvars = {}
  320. data_url = object_doc.attrib.get('data', '')
  321. data_url_params = parse_qs(data_url)
  322. def find_param(name):
  323. if name in flashvars:
  324. return flashvars[name]
  325. node = find_xpath_attr(object_doc, './param', 'name', name)
  326. if node is not None:
  327. return node.attrib['value']
  328. return data_url_params.get(name)
  329. params = {}
  330. playerID = find_param('playerID') or find_param('playerId')
  331. if playerID is None:
  332. raise ExtractorError('Cannot find player ID')
  333. params['playerID'] = playerID
  334. playerKey = find_param('playerKey')
  335. # Not all pages define this value
  336. if playerKey is not None:
  337. params['playerKey'] = playerKey
  338. # These fields hold the id of the video
  339. videoPlayer = find_param('@videoPlayer') or find_param('videoId') or find_param('videoID') or find_param('@videoList')
  340. if videoPlayer is not None:
  341. if isinstance(videoPlayer, list):
  342. videoPlayer = videoPlayer[0]
  343. videoPlayer = videoPlayer.strip()
  344. # UUID is also possible for videoPlayer (e.g.
  345. # http://www.popcornflix.com/hoodies-vs-hooligans/7f2d2b87-bbf2-4623-acfb-ea942b4f01dd
  346. # or http://www8.hp.com/cn/zh/home.html)
  347. if not (re.match(
  348. r'^(?:\d+|[\da-fA-F]{8}-?[\da-fA-F]{4}-?[\da-fA-F]{4}-?[\da-fA-F]{4}-?[\da-fA-F]{12})$',
  349. videoPlayer) or videoPlayer.startswith('ref:')):
  350. return None
  351. params['@videoPlayer'] = videoPlayer
  352. linkBase = find_param('linkBaseURL')
  353. if linkBase is not None:
  354. params['linkBaseURL'] = linkBase
  355. return cls._make_brightcove_url(params)
  356. @classmethod
  357. def _build_brightcove_url_from_js(cls, object_js):
  358. # The layout of JS is as follows:
  359. # customBC.createVideo = function (width, height, playerID, playerKey, videoPlayer, VideoRandomID) {
  360. # // build Brightcove <object /> XML
  361. # }
  362. m = re.search(
  363. r'''(?x)customBC\.createVideo\(
  364. .*? # skipping width and height
  365. ["\'](?P<playerID>\d+)["\']\s*,\s* # playerID
  366. ["\'](?P<playerKey>AQ[^"\']{48})[^"\']*["\']\s*,\s* # playerKey begins with AQ and is 50 characters
  367. # in length, however it's appended to itself
  368. # in places, so truncate
  369. ["\'](?P<videoID>\d+)["\'] # @videoPlayer
  370. ''', object_js)
  371. if m:
  372. return cls._make_brightcove_url(m.groupdict())
  373. @classmethod
  374. def _make_brightcove_url(cls, params):
  375. return update_url_query(
  376. 'http://c.brightcove.com/services/viewer/htmlFederated', params)
  377. @classmethod
  378. def _extract_brightcove_url(cls, webpage):
  379. """Try to extract the brightcove url from the webpage, returns None
  380. if it can't be found
  381. """
  382. urls = cls._extract_brightcove_urls(webpage)
  383. return urls[0] if urls else None
  384. @classmethod
  385. def _extract_brightcove_urls(cls, webpage):
  386. """Return a list of all Brightcove URLs from the webpage """
  387. url_m = re.search(
  388. r'''(?x)
  389. <meta\s+
  390. (?:property|itemprop)=([\'"])(?:og:video|embedURL)\1[^>]+
  391. content=([\'"])(?P<url>https?://(?:secure|c)\.brightcove.com/(?:(?!\2).)+)\2
  392. ''', webpage)
  393. if url_m:
  394. url = unescapeHTML(url_m.group('url'))
  395. # Some sites don't add it, we can't download with this url, for example:
  396. # http://www.ktvu.com/videos/news/raw-video-caltrain-releases-video-of-man-almost/vCTZdY/
  397. if 'playerKey' in url or 'videoId' in url or 'idVideo' in url:
  398. return [url]
  399. matches = re.findall(
  400. r'''(?sx)<object
  401. (?:
  402. [^>]+?class=[\'"][^>]*?BrightcoveExperience.*?[\'"] |
  403. [^>]*?>\s*<param\s+name="movie"\s+value="https?://[^/]*brightcove\.com/
  404. ).+?>\s*</object>''',
  405. webpage)
  406. if matches:
  407. return list(filter(None, [cls._build_brightcove_url(m) for m in matches]))
  408. matches = re.findall(r'(customBC\.createVideo\(.+?\);)', webpage)
  409. if matches:
  410. return list(filter(None, [
  411. cls._build_brightcove_url_from_js(custom_bc)
  412. for custom_bc in matches]))
  413. return [src for _, src in re.findall(
  414. r'<iframe[^>]+src=([\'"])((?:https?:)?//link\.brightcove\.com/services/player/(?!\1).+)\1', webpage)]
  415. def _extract_from_webpage(self, url, webpage):
  416. bc_urls = self._extract_brightcove_urls(webpage)
  417. for bc_url in bc_urls:
  418. yield self.url_result(smuggle_url(bc_url, {'Referer': url}), BrightcoveLegacyIE)
  419. def _real_extract(self, url):
  420. url, smuggled_data = unsmuggle_url(url, {})
  421. # Change the 'videoId' and others field to '@videoPlayer'
  422. url = re.sub(r'(?<=[?&])(videoI(d|D)|idVideo|bctid)', '%40videoPlayer', url)
  423. # Change bckey (used by bcove.me urls) to playerKey
  424. url = re.sub(r'(?<=[?&])bckey', 'playerKey', url)
  425. mobj = self._match_valid_url(url)
  426. query_str = mobj.group('query')
  427. query = compat_urlparse.parse_qs(query_str)
  428. videoPlayer = query.get('@videoPlayer')
  429. if videoPlayer:
  430. # We set the original url as the default 'Referer' header
  431. referer = query.get('linkBaseURL', [None])[0] or smuggled_data.get('Referer', url)
  432. video_id = videoPlayer[0]
  433. if 'playerID' not in query:
  434. mobj = re.search(r'/bcpid(\d+)', url)
  435. if mobj is not None:
  436. query['playerID'] = [mobj.group(1)]
  437. publisher_id = query.get('publisherId')
  438. if publisher_id and publisher_id[0].isdigit():
  439. publisher_id = publisher_id[0]
  440. if not publisher_id:
  441. player_key = query.get('playerKey')
  442. if player_key and ',' in player_key[0]:
  443. player_key = player_key[0]
  444. else:
  445. player_id = query.get('playerID')
  446. if player_id and player_id[0].isdigit():
  447. headers = {}
  448. if referer:
  449. headers['Referer'] = referer
  450. player_page = self._download_webpage(
  451. 'http://link.brightcove.com/services/player/bcpid' + player_id[0],
  452. video_id, headers=headers, fatal=False)
  453. if player_page:
  454. player_key = self._search_regex(
  455. r'<param\s+name="playerKey"\s+value="([\w~,-]+)"',
  456. player_page, 'player key', fatal=False)
  457. if player_key:
  458. enc_pub_id = player_key.split(',')[1].replace('~', '=')
  459. publisher_id = struct.unpack('>Q', base64.urlsafe_b64decode(enc_pub_id))[0]
  460. if publisher_id:
  461. brightcove_new_url = 'http://players.brightcove.net/%s/default_default/index.html?videoId=%s' % (publisher_id, video_id)
  462. if referer:
  463. brightcove_new_url = smuggle_url(brightcove_new_url, {'referrer': referer})
  464. return self.url_result(brightcove_new_url, BrightcoveNewIE.ie_key(), video_id)
  465. # TODO: figure out if it's possible to extract playlistId from playerKey
  466. # elif 'playerKey' in query:
  467. # player_key = query['playerKey']
  468. # return self._get_playlist_info(player_key[0])
  469. raise UnsupportedError(url)
  470. class BrightcoveNewBaseIE(AdobePassIE):
  471. def _parse_brightcove_metadata(self, json_data, video_id, headers={}):
  472. title = json_data['name'].strip()
  473. formats, subtitles = [], {}
  474. sources = json_data.get('sources') or []
  475. for source in sources:
  476. container = source.get('container')
  477. ext = mimetype2ext(source.get('type'))
  478. src = source.get('src')
  479. if ext == 'm3u8' or container == 'M2TS':
  480. if not src:
  481. continue
  482. fmts, subs = self._extract_m3u8_formats_and_subtitles(
  483. src, video_id, 'mp4', 'm3u8_native', m3u8_id='hls', fatal=False)
  484. subtitles = self._merge_subtitles(subtitles, subs)
  485. elif ext == 'mpd':
  486. if not src:
  487. continue
  488. fmts, subs = self._extract_mpd_formats_and_subtitles(src, video_id, 'dash', fatal=False)
  489. subtitles = self._merge_subtitles(subtitles, subs)
  490. else:
  491. streaming_src = source.get('streaming_src')
  492. stream_name, app_name = source.get('stream_name'), source.get('app_name')
  493. if not src and not streaming_src and (not stream_name or not app_name):
  494. continue
  495. tbr = float_or_none(source.get('avg_bitrate'), 1000)
  496. height = int_or_none(source.get('height'))
  497. width = int_or_none(source.get('width'))
  498. f = {
  499. 'tbr': tbr,
  500. 'filesize': int_or_none(source.get('size')),
  501. 'container': container,
  502. 'ext': ext or container.lower(),
  503. }
  504. if width == 0 and height == 0:
  505. f.update({
  506. 'vcodec': 'none',
  507. })
  508. else:
  509. f.update({
  510. 'width': width,
  511. 'height': height,
  512. 'vcodec': source.get('codec'),
  513. })
  514. def build_format_id(kind):
  515. format_id = kind
  516. if tbr:
  517. format_id += '-%dk' % int(tbr)
  518. if height:
  519. format_id += '-%dp' % height
  520. return format_id
  521. if src or streaming_src:
  522. f.update({
  523. 'url': src or streaming_src,
  524. 'format_id': build_format_id('http' if src else 'http-streaming'),
  525. 'source_preference': 0 if src else -1,
  526. })
  527. else:
  528. f.update({
  529. 'url': app_name,
  530. 'play_path': stream_name,
  531. 'format_id': build_format_id('rtmp'),
  532. })
  533. fmts = [f]
  534. # https://support.brightcove.com/playback-api-video-fields-reference#key_systems_object
  535. if container == 'WVM' or source.get('key_systems') or ext == 'ism':
  536. for f in fmts:
  537. f['has_drm'] = True
  538. formats.extend(fmts)
  539. if not formats:
  540. errors = json_data.get('errors')
  541. if errors:
  542. error = errors[0]
  543. self.raise_no_formats(
  544. error.get('message') or error.get('error_subcode') or error['error_code'], expected=True)
  545. for f in formats:
  546. f.setdefault('http_headers', {}).update(headers)
  547. for text_track in json_data.get('text_tracks', []):
  548. if text_track.get('kind') != 'captions':
  549. continue
  550. text_track_url = url_or_none(text_track.get('src'))
  551. if not text_track_url:
  552. continue
  553. lang = (str_or_none(text_track.get('srclang'))
  554. or str_or_none(text_track.get('label')) or 'en').lower()
  555. subtitles.setdefault(lang, []).append({
  556. 'url': text_track_url,
  557. })
  558. is_live = False
  559. duration = float_or_none(json_data.get('duration'), 1000)
  560. if duration is not None and duration <= 0:
  561. is_live = True
  562. common_res = [(160, 90), (320, 180), (480, 720), (640, 360), (768, 432), (1024, 576), (1280, 720), (1366, 768), (1920, 1080)]
  563. thumb_base_url = dict_get(json_data, ('poster', 'thumbnail'))
  564. thumbnails = [{
  565. 'url': re.sub(r'\d+x\d+', f'{w}x{h}', thumb_base_url),
  566. 'width': w,
  567. 'height': h,
  568. } for w, h in common_res] if thumb_base_url else None
  569. return {
  570. 'id': video_id,
  571. 'title': title,
  572. 'description': clean_html(json_data.get('description')),
  573. 'thumbnails': thumbnails,
  574. 'duration': duration,
  575. 'timestamp': parse_iso8601(json_data.get('published_at')),
  576. 'uploader_id': json_data.get('account_id'),
  577. 'formats': formats,
  578. 'subtitles': subtitles,
  579. 'tags': json_data.get('tags', []),
  580. 'is_live': is_live,
  581. }
  582. class BrightcoveNewIE(BrightcoveNewBaseIE):
  583. IE_NAME = 'brightcove:new'
  584. _VALID_URL = r'https?://players\.brightcove\.net/(?P<account_id>\d+)/(?P<player_id>[^/]+)_(?P<embed>[^/]+)/index\.html\?.*(?P<content_type>video|playlist)Id=(?P<video_id>\d+|ref:[^&]+)'
  585. _TESTS = [{
  586. 'url': 'http://players.brightcove.net/929656772001/e41d32dc-ec74-459e-a845-6c69f7b724ea_default/index.html?videoId=4463358922001',
  587. 'md5': 'c8100925723840d4b0d243f7025703be',
  588. 'info_dict': {
  589. 'id': '4463358922001',
  590. 'ext': 'mp4',
  591. 'title': 'Meet the man behind Popcorn Time',
  592. 'description': 'md5:eac376a4fe366edc70279bfb681aea16',
  593. 'duration': 165.768,
  594. 'timestamp': 1441391203,
  595. 'upload_date': '20150904',
  596. 'uploader_id': '929656772001',
  597. 'formats': 'mincount:20',
  598. },
  599. 'skip': '404 Not Found',
  600. }, {
  601. # with rtmp streams
  602. 'url': 'http://players.brightcove.net/4036320279001/5d112ed9-283f-485f-a7f9-33f42e8bc042_default/index.html?videoId=4279049078001',
  603. 'info_dict': {
  604. 'id': '4279049078001',
  605. 'ext': 'mp4',
  606. 'title': 'Titansgrave: Chapter 0',
  607. 'description': 'Titansgrave: Chapter 0',
  608. 'duration': 1242.058,
  609. 'timestamp': 1433556729,
  610. 'upload_date': '20150606',
  611. 'uploader_id': '4036320279001',
  612. 'formats': 'mincount:39',
  613. },
  614. 'params': {
  615. # m3u8 download
  616. 'skip_download': True,
  617. }
  618. }, {
  619. # playlist stream
  620. 'url': 'https://players.brightcove.net/1752604059001/S13cJdUBz_default/index.html?playlistId=5718313430001',
  621. 'info_dict': {
  622. 'id': '5718313430001',
  623. 'title': 'No Audio Playlist',
  624. },
  625. 'playlist_count': 7,
  626. 'params': {
  627. # m3u8 download
  628. 'skip_download': True,
  629. }
  630. }, {
  631. 'url': 'http://players.brightcove.net/5690807595001/HyZNerRl7_default/index.html?playlistId=5743160747001',
  632. 'only_matching': True,
  633. }, {
  634. # ref: prefixed video id
  635. 'url': 'http://players.brightcove.net/3910869709001/21519b5c-4b3b-4363-accb-bdc8f358f823_default/index.html?videoId=ref:7069442',
  636. 'only_matching': True,
  637. }, {
  638. # non numeric ref: prefixed video id
  639. 'url': 'http://players.brightcove.net/710858724001/default_default/index.html?videoId=ref:event-stream-356',
  640. 'only_matching': True,
  641. }, {
  642. # unavailable video without message but with error_code
  643. 'url': 'http://players.brightcove.net/1305187701/c832abfb-641b-44eb-9da0-2fe76786505f_default/index.html?videoId=4377407326001',
  644. 'only_matching': True,
  645. }]
  646. _WEBPAGE_TESTS = [{
  647. # brightcove player url embed
  648. 'url': 'https://nbc-2.com/weather/forecast/2022/11/16/forecast-warmest-day-of-the-week/',
  649. 'md5': '2934d5372b354d27083ccf8575dbfee2',
  650. 'info_dict': {
  651. 'id': '6315650313112',
  652. 'title': 'First Alert Forecast: November 15, 2022',
  653. 'ext': 'mp4',
  654. 'tags': ['nbc2', 'forecast'],
  655. 'uploader_id': '6146886170001',
  656. 'thumbnail': r're:^https?://.*\.jpg$',
  657. 'timestamp': 1668574571,
  658. 'duration': 233.375,
  659. 'upload_date': '20221116',
  660. },
  661. }, {
  662. # embedded with video tag only
  663. 'url': 'https://www.gooddishtv.com/tiktok-rapping-chef-mr-pyrex',
  664. 'info_dict': {
  665. 'id': 'tiktok-rapping-chef-mr-pyrex',
  666. 'title': 'TikTok\'s Rapping Chef Makes Jambalaya for the Hosts',
  667. 'thumbnail': r're:^https?://.*\.jpg$',
  668. 'age_limit': 0,
  669. 'description': 'Just in time for Mardi Gras',
  670. },
  671. 'playlist': [{
  672. 'info_dict': {
  673. 'id': '6299189544001',
  674. 'ext': 'mp4',
  675. 'title': 'TGD_01-032_5',
  676. 'thumbnail': r're:^https?://.*\.jpg$',
  677. 'tags': [],
  678. 'timestamp': 1646078943,
  679. 'uploader_id': '1569565978001',
  680. 'upload_date': '20220228',
  681. 'duration': 217.195,
  682. },
  683. }, {
  684. 'info_dict': {
  685. 'id': '6305565995112',
  686. 'ext': 'mp4',
  687. 'title': 'TGD 01-087 (Airs 05.25.22)_Segment 5',
  688. 'thumbnail': r're:^https?://.*\.jpg$',
  689. 'tags': [],
  690. 'timestamp': 1651604591,
  691. 'uploader_id': '1569565978001',
  692. 'upload_date': '20220503',
  693. 'duration': 310.421,
  694. },
  695. }],
  696. }, {
  697. # Brightcove:new type [2].
  698. 'url': 'http://www.delawaresportszone.com/video-st-thomas-more-earns-first-trip-to-basketball-semis',
  699. 'md5': '2b35148fcf48da41c9fb4591650784f3',
  700. 'info_dict': {
  701. 'id': '5348741021001',
  702. 'ext': 'mp4',
  703. 'upload_date': '20170306',
  704. 'uploader_id': '4191638492001',
  705. 'timestamp': 1488769918,
  706. 'title': 'VIDEO: St. Thomas More earns first trip to basketball semis',
  707. },
  708. 'skip': '404 Not Found',
  709. }, {
  710. # Alternative brightcove <video> attributes
  711. 'url': 'http://www.programme-tv.net/videos/extraits/81095-guillaume-canet-evoque-les-rumeurs-d-infidelite-de-marion-cotillard-avec-brad-pitt-dans-vivement-dimanche/',
  712. 'info_dict': {
  713. 'id': '81095-guillaume-canet-evoque-les-rumeurs-d-infidelite-de-marion-cotillard-avec-brad-pitt-dans-vivement-dimanche',
  714. 'title': "Guillaume Canet évoque les rumeurs d'infidélité de Marion Cotillard avec Brad Pitt dans Vivement Dimanche, Extraits : toutes les vidéos avec Télé-Loisirs",
  715. },
  716. 'playlist': [{
  717. 'md5': '732d22ba3d33f2f3fc253c39f8f36523',
  718. 'info_dict': {
  719. 'id': '5311302538001',
  720. 'ext': 'mp4',
  721. 'title': "Guillaume Canet évoque les rumeurs d'infidélité de Marion Cotillard avec Brad Pitt dans Vivement Dimanche",
  722. 'description': "Guillaume Canet évoque les rumeurs d'infidélité de Marion Cotillard avec Brad Pitt dans Vivement Dimanche (France 2, 5 février 2017)",
  723. 'timestamp': 1486321708,
  724. 'upload_date': '20170205',
  725. 'uploader_id': '800000640001',
  726. },
  727. 'only_matching': True,
  728. }],
  729. 'skip': '404 Not Found',
  730. }, {
  731. # Brightcove URL in single quotes
  732. 'url': 'http://www.sportsnet.ca/baseball/mlb/sn-presents-russell-martin-world-citizen/',
  733. 'md5': '4ae374f1f8b91c889c4b9203c8c752af',
  734. 'info_dict': {
  735. 'id': '4255764656001',
  736. 'ext': 'mp4',
  737. 'title': 'SN Presents: Russell Martin, World Citizen',
  738. 'description': 'To understand why he was the Toronto Blue Jays’ top off-season priority is to appreciate his background and upbringing in Montreal, where he first developed his baseball skills. Written and narrated by Stephen Brunt.',
  739. 'uploader': 'Rogers Sportsnet',
  740. 'uploader_id': '1704050871',
  741. 'upload_date': '20150525',
  742. 'timestamp': 1432570283,
  743. },
  744. 'skip': 'Page no longer has URL, now has javascript',
  745. }]
  746. @staticmethod
  747. def _extract_url(ie, webpage):
  748. urls = BrightcoveNewIE._extract_brightcove_urls(ie, webpage)
  749. return urls[0] if urls else None
  750. @staticmethod
  751. def _extract_brightcove_urls(ie, webpage):
  752. # Reference:
  753. # 1. http://docs.brightcove.com/en/video-cloud/brightcove-player/guides/publish-video.html#setvideoiniframe
  754. # 2. http://docs.brightcove.com/en/video-cloud/brightcove-player/guides/publish-video.html#tag
  755. # 3. http://docs.brightcove.com/en/video-cloud/brightcove-player/guides/publish-video.html#setvideousingjavascript
  756. # 4. http://docs.brightcove.com/en/video-cloud/brightcove-player/guides/in-page-embed-player-implementation.html
  757. # 5. https://support.brightcove.com/en/video-cloud/docs/dynamically-assigning-videos-player
  758. entries = []
  759. # Look for iframe embeds [1]
  760. for _, url in re.findall(
  761. r'<iframe[^>]+src=(["\'])((?:https?:)?//players\.brightcove\.net/\d+/[^/]+/index\.html.+?)\1', webpage):
  762. entries.append(url if url.startswith('http') else 'http:' + url)
  763. # Look for <video> tags [2] and embed_in_page embeds [3]
  764. # [2] looks like:
  765. for video, script_tag, account_id, player_id, embed in re.findall(
  766. r'''(?isx)
  767. (<video(?:-js)?\s+[^>]*\bdata-video-id\s*=\s*['"]?[^>]+>)
  768. (?:.*?
  769. (<script[^>]+
  770. src=["\'](?:https?:)?//players\.brightcove\.net/
  771. (\d+)/([^/]+)_([^/]+)/index(?:\.min)?\.js
  772. )
  773. )?
  774. ''', webpage):
  775. attrs = extract_attributes(video)
  776. # According to examples from [4] it's unclear whether video id
  777. # may be optional and what to do when it is
  778. video_id = attrs.get('data-video-id')
  779. if not video_id:
  780. continue
  781. account_id = account_id or attrs.get('data-account')
  782. if not account_id:
  783. continue
  784. player_id = player_id or attrs.get('data-player') or 'default'
  785. embed = embed or attrs.get('data-embed') or 'default'
  786. bc_url = 'http://players.brightcove.net/%s/%s_%s/index.html?videoId=%s' % (
  787. account_id, player_id, embed, video_id)
  788. # Some brightcove videos may be embedded with video tag only and
  789. # without script tag or any mentioning of brightcove at all. Such
  790. # embeds are considered ambiguous since they are matched based only
  791. # on data-video-id and data-account attributes and in the wild may
  792. # not be brightcove embeds at all. Let's check reconstructed
  793. # brightcove URLs in case of such embeds and only process valid
  794. # ones. By this we ensure there is indeed a brightcove embed.
  795. if not script_tag and not ie._is_valid_url(
  796. bc_url, video_id, 'possible brightcove video'):
  797. continue
  798. entries.append(bc_url)
  799. return entries
  800. def _extract_from_webpage(self, url, webpage):
  801. bc_urls = self._extract_brightcove_urls(self, webpage)
  802. for bc_url in bc_urls:
  803. yield self.url_result(smuggle_url(bc_url, {'referrer': url}), BrightcoveNewIE)
  804. def _real_extract(self, url):
  805. url, smuggled_data = unsmuggle_url(url, {})
  806. self._initialize_geo_bypass({
  807. 'countries': smuggled_data.get('geo_countries'),
  808. 'ip_blocks': smuggled_data.get('geo_ip_blocks'),
  809. })
  810. account_id, player_id, embed, content_type, video_id = self._match_valid_url(url).groups()
  811. policy_key_id = '%s_%s' % (account_id, player_id)
  812. policy_key = self.cache.load('brightcove', policy_key_id)
  813. policy_key_extracted = False
  814. store_pk = lambda x: self.cache.store('brightcove', policy_key_id, x)
  815. def extract_policy_key():
  816. base_url = 'http://players.brightcove.net/%s/%s_%s/' % (account_id, player_id, embed)
  817. config = self._download_json(
  818. base_url + 'config.json', video_id, fatal=False) or {}
  819. policy_key = try_get(
  820. config, lambda x: x['video_cloud']['policy_key'])
  821. if not policy_key:
  822. webpage = self._download_webpage(
  823. base_url + 'index.min.js', video_id)
  824. catalog = self._search_regex(
  825. r'catalog\(({.+?})\);', webpage, 'catalog', default=None)
  826. if catalog:
  827. catalog = self._parse_json(
  828. js_to_json(catalog), video_id, fatal=False)
  829. if catalog:
  830. policy_key = catalog.get('policyKey')
  831. if not policy_key:
  832. policy_key = self._search_regex(
  833. r'policyKey\s*:\s*(["\'])(?P<pk>.+?)\1',
  834. webpage, 'policy key', group='pk')
  835. store_pk(policy_key)
  836. return policy_key
  837. api_url = 'https://edge.api.brightcove.com/playback/v1/accounts/%s/%ss/%s' % (account_id, content_type, video_id)
  838. headers = {}
  839. referrer = smuggled_data.get('referrer') # XXX: notice the spelling/case of the key
  840. if referrer:
  841. headers.update({
  842. 'Referer': referrer,
  843. 'Origin': re.search(r'https?://[^/]+', referrer).group(0),
  844. })
  845. for _ in range(2):
  846. if not policy_key:
  847. policy_key = extract_policy_key()
  848. policy_key_extracted = True
  849. headers['Accept'] = 'application/json;pk=%s' % policy_key
  850. try:
  851. json_data = self._download_json(api_url, video_id, headers=headers)
  852. break
  853. except ExtractorError as e:
  854. if isinstance(e.cause, compat_HTTPError) and e.cause.code in (401, 403):
  855. json_data = self._parse_json(e.cause.read().decode(), video_id)[0]
  856. message = json_data.get('message') or json_data['error_code']
  857. if json_data.get('error_subcode') == 'CLIENT_GEO':
  858. self.raise_geo_restricted(msg=message)
  859. elif json_data.get('error_code') == 'INVALID_POLICY_KEY' and not policy_key_extracted:
  860. policy_key = None
  861. store_pk(None)
  862. continue
  863. raise ExtractorError(message, expected=True)
  864. raise
  865. errors = json_data.get('errors')
  866. if errors and errors[0].get('error_subcode') == 'TVE_AUTH':
  867. custom_fields = json_data['custom_fields']
  868. tve_token = self._extract_mvpd_auth(
  869. smuggled_data['source_url'], video_id,
  870. custom_fields['bcadobepassrequestorid'],
  871. custom_fields['bcadobepassresourceid'])
  872. json_data = self._download_json(
  873. api_url, video_id, headers={
  874. 'Accept': 'application/json;pk=%s' % policy_key
  875. }, query={
  876. 'tveToken': tve_token,
  877. })
  878. if content_type == 'playlist':
  879. return self.playlist_result(
  880. [self._parse_brightcove_metadata(vid, vid.get('id'), headers)
  881. for vid in json_data.get('videos', []) if vid.get('id')],
  882. json_data.get('id'), json_data.get('name'),
  883. json_data.get('description'))
  884. return self._parse_brightcove_metadata(
  885. json_data, video_id, headers=headers)