logo

oasis-root

Compiled tree of Oasis Linux based on own branch at <https://hacktivis.me/git/oasis/> git clone https://anongit.hacktivis.me/git/oasis-root.git

facebook.py (52862B)


  1. import json
  2. import re
  3. import urllib.parse
  4. from .common import InfoExtractor
  5. from ..compat import compat_etree_fromstring
  6. from ..networking import Request
  7. from ..networking.exceptions import network_exceptions
  8. from ..utils import (
  9. ExtractorError,
  10. clean_html,
  11. determine_ext,
  12. float_or_none,
  13. format_field,
  14. get_element_by_id,
  15. get_first,
  16. int_or_none,
  17. join_nonempty,
  18. js_to_json,
  19. merge_dicts,
  20. parse_count,
  21. parse_qs,
  22. qualities,
  23. str_or_none,
  24. traverse_obj,
  25. try_get,
  26. url_or_none,
  27. urlencode_postdata,
  28. urljoin,
  29. variadic,
  30. )
  31. class FacebookIE(InfoExtractor):
  32. _VALID_URL = r'''(?x)
  33. (?:
  34. https?://
  35. (?:[\w-]+\.)?(?:facebook\.com|facebookwkhpilnemxj7asaniu7vnjjbiltxjqhye3mhbshg7kx5tfyd\.onion)/
  36. (?:[^#]*?\#!/)?
  37. (?:
  38. (?:
  39. permalink\.php|
  40. video/video\.php|
  41. photo\.php|
  42. video\.php|
  43. video/embed|
  44. story\.php|
  45. watch(?:/live)?/?
  46. )\?(?:.*?)(?:v|video_id|story_fbid)=|
  47. [^/]+/videos/(?:[^/]+/)?|
  48. [^/]+/posts/|
  49. events/(?:[^/]+/)?|
  50. groups/[^/]+/(?:permalink|posts)/(?:[\da-f]+/)?|
  51. watchparty/
  52. )|
  53. facebook:
  54. )
  55. (?P<id>pfbid[A-Za-z0-9]+|\d+)
  56. '''
  57. _EMBED_REGEX = [
  58. r'<iframe[^>]+?src=(["\'])(?P<url>https?://www\.facebook\.com/(?:video/embed|plugins/video\.php).+?)\1',
  59. # Facebook API embed https://developers.facebook.com/docs/plugins/embedded-video-player
  60. r'''(?x)<div[^>]+
  61. class=(?P<q1>[\'"])[^\'"]*\bfb-(?:video|post)\b[^\'"]*(?P=q1)[^>]+
  62. data-href=(?P<q2>[\'"])(?P<url>(?:https?:)?//(?:www\.)?facebook.com/.+?)(?P=q2)''',
  63. ]
  64. _LOGIN_URL = 'https://www.facebook.com/login.php?next=http%3A%2F%2Ffacebook.com%2Fhome.php&login_attempt=1'
  65. _CHECKPOINT_URL = 'https://www.facebook.com/checkpoint/?next=http%3A%2F%2Ffacebook.com%2Fhome.php&_fb_noscript=1'
  66. _NETRC_MACHINE = 'facebook'
  67. IE_NAME = 'facebook'
  68. _VIDEO_PAGE_TEMPLATE = 'https://www.facebook.com/video/video.php?v=%s'
  69. _VIDEO_PAGE_TAHOE_TEMPLATE = 'https://www.facebook.com/video/tahoe/async/%s/?chain=true&isvideo=true&payloadtype=primary'
  70. _TESTS = [{
  71. 'url': 'https://www.facebook.com/radiokicksfm/videos/3676516585958356/',
  72. 'info_dict': {
  73. 'id': '3676516585958356',
  74. 'ext': 'mp4',
  75. 'title': 'dr Adam Przygoda',
  76. 'description': 'md5:34675bda53336b1d16400265c2bb9b3b',
  77. 'uploader': 'RADIO KICKS FM',
  78. 'upload_date': '20230818',
  79. 'timestamp': 1692346159,
  80. 'thumbnail': r're:^https?://.*',
  81. 'uploader_id': '100063551323670',
  82. 'duration': 3133.583,
  83. 'view_count': int,
  84. 'concurrent_view_count': 0,
  85. },
  86. }, {
  87. 'url': 'https://www.facebook.com/video.php?v=637842556329505&fref=nf',
  88. 'md5': '6a40d33c0eccbb1af76cf0485a052659',
  89. 'info_dict': {
  90. 'id': '637842556329505',
  91. 'ext': 'mp4',
  92. 'title': 're:Did you know Kei Nishikori is the first Asian man to ever reach a Grand Slam',
  93. 'uploader': 'Tennis on Facebook',
  94. 'upload_date': '20140908',
  95. 'timestamp': 1410199200,
  96. },
  97. 'skip': 'Requires logging in',
  98. }, {
  99. # data.video
  100. 'url': 'https://www.facebook.com/video.php?v=274175099429670',
  101. 'info_dict': {
  102. 'id': '274175099429670',
  103. 'ext': 'mp4',
  104. 'title': 'Asif',
  105. 'description': '',
  106. 'uploader': 'Asif Nawab Butt',
  107. 'upload_date': '20140506',
  108. 'timestamp': 1399398998,
  109. 'thumbnail': r're:^https?://.*',
  110. 'uploader_id': 'pfbid05AzrFTXgY37tqwaSgbFTTEpCLBjjEJHkigogwGiRPtKEpAsJYJpzE94H1RxYXWEtl',
  111. 'duration': 131.03,
  112. 'concurrent_view_count': int,
  113. 'view_count': int,
  114. },
  115. }, {
  116. 'note': 'Video with DASH manifest',
  117. 'url': 'https://www.facebook.com/video.php?v=957955867617029',
  118. 'md5': 'b2c28d528273b323abe5c6ab59f0f030',
  119. 'info_dict': {
  120. 'id': '957955867617029',
  121. 'ext': 'mp4',
  122. 'title': 'When you post epic content on instagram.com/433 8 million followers, this is ...',
  123. 'uploader': 'Demy de Zeeuw',
  124. 'upload_date': '20160110',
  125. 'timestamp': 1452431627,
  126. },
  127. 'skip': 'Requires logging in',
  128. }, {
  129. 'url': 'https://www.facebook.com/maxlayn/posts/10153807558977570',
  130. 'md5': '037b1fa7f3c2d02b7a0d7bc16031ecc6',
  131. 'info_dict': {
  132. 'id': '544765982287235',
  133. 'ext': 'mp4',
  134. 'title': '"What are you doing running in the snow?"',
  135. 'uploader': 'FailArmy',
  136. },
  137. 'skip': 'Video gone',
  138. }, {
  139. 'url': 'https://m.facebook.com/story.php?story_fbid=1035862816472149&id=116132035111903',
  140. 'md5': '1deb90b6ac27f7efcf6d747c8a27f5e3',
  141. 'info_dict': {
  142. 'id': '1035862816472149',
  143. 'ext': 'mp4',
  144. 'title': 'What the Flock Is Going On In New Zealand Credit: ViralHog',
  145. 'uploader': 'S. Saint',
  146. },
  147. 'skip': 'Video gone',
  148. }, {
  149. 'note': 'swf params escaped',
  150. 'url': 'https://www.facebook.com/barackobama/posts/10153664894881749',
  151. 'md5': '97ba073838964d12c70566e0085c2b91',
  152. 'info_dict': {
  153. 'id': '10153664894881749',
  154. 'ext': 'mp4',
  155. 'title': 'Average time to confirm recent Supreme Court nominees: 67 days Longest it\'s t...',
  156. 'thumbnail': r're:^https?://.*',
  157. 'timestamp': 1456259628,
  158. 'upload_date': '20160223',
  159. 'uploader': 'Barack Obama',
  160. },
  161. 'skip': 'Gif on giphy.com gone',
  162. }, {
  163. # have 1080P, but only up to 720p in swf params
  164. # data.video.story.attachments[].media
  165. 'url': 'https://www.facebook.com/cnn/videos/10155529876156509/',
  166. 'md5': '1659aa21fb3dd1585874f668e81a72c8',
  167. 'info_dict': {
  168. 'id': '10155529876156509',
  169. 'ext': 'mp4',
  170. 'title': 'Holocaust survivor becomes US citizen',
  171. 'description': 'She survived the holocaust — and years later, she’s getting her citizenship so she can vote for Hillary Clinton http://cnn.it/2eERh5f',
  172. 'timestamp': 1477818095,
  173. 'upload_date': '20161030',
  174. 'uploader': 'CNN',
  175. 'thumbnail': r're:^https?://.*',
  176. 'view_count': int,
  177. 'uploader_id': '100059479812265',
  178. 'concurrent_view_count': int,
  179. 'duration': 44.181,
  180. },
  181. }, {
  182. # FIXME: unable to extract uploader, no formats found
  183. # bigPipe.onPageletArrive ... onPageletArrive pagelet_group_mall
  184. # data.node.comet_sections.content.story.attachments[].style_type_renderer.attachment.media
  185. 'url': 'https://www.facebook.com/yaroslav.korpan/videos/1417995061575415/',
  186. 'info_dict': {
  187. 'id': '1417995061575415',
  188. 'ext': 'mp4',
  189. 'title': 'Довгоочікуване відео | By Yaroslav - Facebook',
  190. 'description': 'Довгоочікуване відео',
  191. 'timestamp': 1486648217,
  192. 'upload_date': '20170209',
  193. 'uploader': 'Yaroslav Korpan',
  194. 'uploader_id': 'pfbid06AScABAWcW91qpiuGrLt99Ef9tvwHoXP6t8KeFYEqkSfreMtfa9nTveh8b2ZEVSWl',
  195. 'concurrent_view_count': int,
  196. 'thumbnail': r're:^https?://.*',
  197. 'view_count': int,
  198. 'duration': 11736.446,
  199. },
  200. 'params': {
  201. 'skip_download': True,
  202. },
  203. }, {
  204. # FIXME: Cannot parse data error
  205. 'url': 'https://www.facebook.com/LaGuiaDelVaron/posts/1072691702860471',
  206. 'info_dict': {
  207. 'id': '1072691702860471',
  208. 'ext': 'mp4',
  209. 'title': 'md5:ae2d22a93fbb12dad20dc393a869739d',
  210. 'timestamp': 1477305000,
  211. 'upload_date': '20161024',
  212. 'uploader': 'La Guía Del Varón',
  213. 'thumbnail': r're:^https?://.*',
  214. },
  215. 'skip': 'Requires logging in',
  216. }, {
  217. # data.node.comet_sections.content.story.attachments[].style_type_renderer.attachment.media
  218. 'url': 'https://www.facebook.com/groups/1024490957622648/permalink/1396382447100162/',
  219. 'info_dict': {
  220. 'id': '202882990186699',
  221. 'ext': 'mp4',
  222. 'title': 'birb (O v O") | Hello? Yes your uber ride is here',
  223. 'description': 'Hello? Yes your uber ride is here * Jukin Media Verified * Find this video and others like it by visiting...',
  224. 'timestamp': 1486035513,
  225. 'upload_date': '20170202',
  226. 'uploader': 'Elisabeth Ahtn',
  227. 'uploader_id': '100013949973717',
  228. },
  229. 'skip': 'Requires logging in',
  230. }, {
  231. # data.node.comet_sections.content.story.attachments[].throwbackStyles.attachment_target_renderer.attachment.target.attachments[].styles.attachment.media
  232. 'url': 'https://www.facebook.com/groups/1645456212344334/posts/3737828833107051/',
  233. 'info_dict': {
  234. 'id': '1569199726448814',
  235. 'ext': 'mp4',
  236. 'title': 'Pence MUST GO!',
  237. 'description': 'Vickie Gentry shared a memory.',
  238. 'timestamp': 1511548260,
  239. 'upload_date': '20171124',
  240. 'uploader': 'Vickie Gentry',
  241. 'uploader_id': 'pfbid0FkkycT95ySNNyfCw4Cho6u5G7WbbZEcxT496Hq8rtx1K3LcTCATpR3wnyYhmyGC5l',
  242. 'thumbnail': r're:^https?://.*',
  243. 'duration': 148.224,
  244. },
  245. }, {
  246. # data.node.comet_sections.content.story.attachments[].styles.attachment.media
  247. 'url': 'https://www.facebook.com/attn/posts/pfbid0j1Czf2gGDVqeQ8KiMLFm3pWN8GxsQmeRrVhimWDzMuKQoR8r4b1knNsejELmUgyhl',
  248. 'info_dict': {
  249. 'id': '6968553779868435',
  250. 'ext': 'mp4',
  251. 'description': 'md5:2f2fcf93e97ac00244fe64521bbdb0cb',
  252. 'uploader': 'ATTN:',
  253. 'upload_date': '20231207',
  254. 'title': 'ATTN:',
  255. 'duration': 132.675,
  256. 'uploader_id': '100064451419378',
  257. 'view_count': int,
  258. 'thumbnail': r're:^https?://.*',
  259. 'timestamp': 1701975646,
  260. },
  261. }, {
  262. # data.node.comet_sections.content.story.attachments[].styles.attachment.media
  263. 'url': 'https://www.facebook.com/permalink.php?story_fbid=pfbid0fqQuVEQyXRa9Dp4RcaTR14KHU3uULHV1EK7eckNXSH63JMuoALsAvVCJ97zAGitil&id=100068861234290',
  264. 'info_dict': {
  265. 'id': '270103405756416',
  266. 'ext': 'mp4',
  267. 'title': 'Lela Evans',
  268. 'description': 'Today Makkovik\'s own Pilot Mandy Smith made her inaugural landing on the airstrip in her hometown. What a proud moment as we all cheered and...',
  269. 'thumbnail': r're:^https?://.*',
  270. 'uploader': 'Lela Evans',
  271. 'uploader_id': 'pfbid0swT2y7t6TAsZVBvcyeYPdhTMefGaS26mzUwML3vd1ma6ndGZKxsyS4Ssu3jitZLXl',
  272. 'upload_date': '20231228',
  273. 'timestamp': 1703804085,
  274. 'duration': 394.347,
  275. 'view_count': int,
  276. },
  277. }, {
  278. 'url': 'https://www.facebook.com/story.php?story_fbid=pfbid0Fnzhm8UuzjBYpPMNFzaSpFE9UmLdU4fJN8qTANi1Dmtj5q7DNrL5NERXfsAzDEV7l&id=100073071055552',
  279. 'only_matching': True,
  280. }, {
  281. 'url': 'https://www.facebook.com/video.php?v=10204634152394104',
  282. 'only_matching': True,
  283. }, {
  284. 'url': 'https://www.facebook.com/amogood/videos/1618742068337349/?fref=nf',
  285. 'only_matching': True,
  286. }, {
  287. # data.mediaset.currMedia.edges
  288. 'url': 'https://www.facebook.com/ChristyClarkForBC/videos/vb.22819070941/10153870694020942/?type=2&theater',
  289. 'only_matching': True,
  290. }, {
  291. # data.video.story.attachments[].media
  292. 'url': 'facebook:544765982287235',
  293. 'only_matching': True,
  294. }, {
  295. # data.node.comet_sections.content.story.attachments[].style_type_renderer.attachment.media
  296. 'url': 'https://www.facebook.com/groups/164828000315060/permalink/764967300301124/',
  297. 'only_matching': True,
  298. }, {
  299. # data.video.creation_story.attachments[].media
  300. 'url': 'https://zh-hk.facebook.com/peoplespower/videos/1135894589806027/',
  301. 'only_matching': True,
  302. }, {
  303. # data.video
  304. 'url': 'https://www.facebookwkhpilnemxj7asaniu7vnjjbiltxjqhye3mhbshg7kx5tfyd.onion/video.php?v=274175099429670',
  305. 'only_matching': True,
  306. }, {
  307. # no title
  308. 'url': 'https://www.facebook.com/onlycleverentertainment/videos/1947995502095005/',
  309. 'only_matching': True,
  310. }, {
  311. # data.video
  312. 'url': 'https://www.facebook.com/WatchESLOne/videos/359649331226507/',
  313. 'info_dict': {
  314. 'id': '359649331226507',
  315. 'ext': 'mp4',
  316. 'title': 'Fnatic vs. EG - Group A - Opening Match - ESL One Birmingham Day 1',
  317. 'description': '#ESLOne VoD - Birmingham Finals Day#1 Fnatic vs. @Evil Geniuses',
  318. 'timestamp': 1527084179,
  319. 'upload_date': '20180523',
  320. 'uploader': 'ESL One Dota 2',
  321. 'uploader_id': '100066514874195',
  322. 'duration': 4524.001,
  323. 'view_count': int,
  324. 'thumbnail': r're:^https?://.*',
  325. 'concurrent_view_count': int,
  326. },
  327. 'params': {
  328. 'skip_download': True,
  329. },
  330. }, {
  331. # data.node.comet_sections.content.story.attachments[].style_type_renderer.attachment.all_subattachments.nodes[].media
  332. 'url': 'https://www.facebook.com/100033620354545/videos/106560053808006/',
  333. 'info_dict': {
  334. 'id': '106560053808006',
  335. 'ext': 'mp4',
  336. 'title': 'Josef',
  337. 'thumbnail': r're:^https?://.*',
  338. 'concurrent_view_count': int,
  339. 'uploader_id': 'pfbid02gpfwRM2XvdEJfsERupwQiNmBiDArc38RMRYZnap372q6Vs7MtFTVy72mmFWpJBTKl',
  340. 'timestamp': 1549275572,
  341. 'duration': 3.283,
  342. 'uploader': 'Josef Novak',
  343. 'description': '',
  344. 'upload_date': '20190204',
  345. },
  346. }, {
  347. # data.video.story.attachments[].media
  348. 'url': 'https://www.facebook.com/watch/?v=647537299265662',
  349. 'only_matching': True,
  350. }, {
  351. # FIXME: https://github.com/yt-dlp/yt-dlp/issues/542
  352. # data.node.comet_sections.content.story.attachments[].style_type_renderer.attachment.all_subattachments.nodes[].media
  353. 'url': 'https://www.facebook.com/PankajShahLondon/posts/10157667649866271',
  354. 'info_dict': {
  355. 'id': '10157667649866271',
  356. },
  357. 'playlist_count': 3,
  358. 'skip': 'Requires logging in',
  359. }, {
  360. # data.nodes[].comet_sections.content.story.attachments[].style_type_renderer.attachment.media
  361. 'url': 'https://m.facebook.com/Alliance.Police.Department/posts/4048563708499330',
  362. 'info_dict': {
  363. 'id': '117576630041613',
  364. 'ext': 'mp4',
  365. # TODO: title can be extracted from video page
  366. 'title': 'Facebook video #117576630041613',
  367. 'uploader_id': '189393014416438',
  368. 'upload_date': '20201123',
  369. 'timestamp': 1606162592,
  370. },
  371. 'skip': 'Requires logging in',
  372. }, {
  373. # node.comet_sections.content.story.attached_story.attachments.style_type_renderer.attachment.media
  374. 'url': 'https://www.facebook.com/groups/ateistiskselskab/permalink/10154930137678856/',
  375. 'info_dict': {
  376. 'id': '211567722618337',
  377. 'ext': 'mp4',
  378. 'title': 'Facebook video #211567722618337',
  379. 'uploader_id': '127875227654254',
  380. 'upload_date': '20161122',
  381. 'timestamp': 1479793574,
  382. },
  383. 'skip': 'No video',
  384. }, {
  385. # data.video.creation_story.attachments[].media
  386. 'url': 'https://www.facebook.com/watch/live/?v=1823658634322275',
  387. 'only_matching': True,
  388. }, {
  389. 'url': 'https://www.facebook.com/watchparty/211641140192478',
  390. 'info_dict': {
  391. 'id': '211641140192478',
  392. },
  393. 'playlist_count': 1,
  394. 'skip': 'Requires logging in',
  395. }, {
  396. # FIXME: Cannot parse data error
  397. # data.event.cover_media_renderer.cover_video
  398. 'url': 'https://m.facebook.com/events/1509582499515440',
  399. 'info_dict': {
  400. 'id': '637246984455045',
  401. 'ext': 'mp4',
  402. 'title': 'ANALISI IN CAMPO OSCURO " Coaguli nel sangue dei vaccinati"',
  403. 'description': 'Other event by Comitato Liberi Pensatori on Tuesday, October 18 2022',
  404. 'thumbnail': r're:^https?://.*',
  405. 'uploader': 'Comitato Liberi Pensatori',
  406. 'uploader_id': '100065709540881',
  407. },
  408. }, {
  409. 'url': 'https://www.facebook.com/groups/1513990329015294/posts/d41d8cd9/2013209885760000/?app=fbl',
  410. 'only_matching': True,
  411. }]
  412. _SUPPORTED_PAGLETS_REGEX = r'(?:pagelet_group_mall|permalink_video_pagelet|hyperfeed_story_id_[0-9a-f]+)'
  413. _api_config = {
  414. 'graphURI': '/api/graphql/',
  415. }
  416. def _perform_login(self, username, password):
  417. login_page_req = Request(self._LOGIN_URL)
  418. self._set_cookie('facebook.com', 'locale', 'en_US')
  419. login_page = self._download_webpage(login_page_req, None,
  420. note='Downloading login page',
  421. errnote='Unable to download login page')
  422. lsd = self._search_regex(
  423. r'<input type="hidden" name="lsd" value="([^"]*)"',
  424. login_page, 'lsd')
  425. lgnrnd = self._search_regex(r'name="lgnrnd" value="([^"]*?)"', login_page, 'lgnrnd')
  426. login_form = {
  427. 'email': username,
  428. 'pass': password,
  429. 'lsd': lsd,
  430. 'lgnrnd': lgnrnd,
  431. 'next': 'http://facebook.com/home.php',
  432. 'default_persistent': '0',
  433. 'legacy_return': '1',
  434. 'timezone': '-60',
  435. 'trynum': '1',
  436. }
  437. request = Request(self._LOGIN_URL, urlencode_postdata(login_form))
  438. request.headers['Content-Type'] = 'application/x-www-form-urlencoded'
  439. try:
  440. login_results = self._download_webpage(request, None,
  441. note='Logging in', errnote='unable to fetch login page')
  442. if re.search(r'<form(.*)name="login"(.*)</form>', login_results) is not None:
  443. error = self._html_search_regex(
  444. r'(?s)<div[^>]+class=(["\']).*?login_error_box.*?\1[^>]*><div[^>]*>.*?</div><div[^>]*>(?P<error>.+?)</div>',
  445. login_results, 'login error', default=None, group='error')
  446. if error:
  447. raise ExtractorError(f'Unable to login: {error}', expected=True)
  448. self.report_warning('unable to log in: bad username/password, or exceeded login rate limit (~3/min). Check credentials or wait.')
  449. return
  450. fb_dtsg = self._search_regex(
  451. r'name="fb_dtsg" value="(.+?)"', login_results, 'fb_dtsg', default=None)
  452. h = self._search_regex(
  453. r'name="h"\s+(?:\w+="[^"]+"\s+)*?value="([^"]+)"', login_results, 'h', default=None)
  454. if not fb_dtsg or not h:
  455. return
  456. check_form = {
  457. 'fb_dtsg': fb_dtsg,
  458. 'h': h,
  459. 'name_action_selected': 'dont_save',
  460. }
  461. check_req = Request(self._CHECKPOINT_URL, urlencode_postdata(check_form))
  462. check_req.headers['Content-Type'] = 'application/x-www-form-urlencoded'
  463. check_response = self._download_webpage(check_req, None,
  464. note='Confirming login')
  465. if re.search(r'id="checkpointSubmitButton"', check_response) is not None:
  466. self.report_warning('Unable to confirm login, you have to login in your browser and authorize the login.')
  467. except network_exceptions as err:
  468. self.report_warning(f'unable to log in: {err}')
  469. return
  470. def _extract_from_url(self, url, video_id):
  471. webpage = self._download_webpage(
  472. url.replace('://m.facebook.com/', '://www.facebook.com/'), video_id)
  473. def extract_metadata(webpage):
  474. post_data = [self._parse_json(j, video_id, fatal=False) for j in re.findall(
  475. r'data-sjs>({.*?ScheduledServerJS.*?})</script>', webpage)]
  476. post = traverse_obj(post_data, (
  477. ..., 'require', ..., ..., ..., '__bbox', 'require', ..., ..., ..., '__bbox', 'result', 'data'), expected_type=dict) or []
  478. media = traverse_obj(post, (..., 'attachments', ..., lambda k, v: (
  479. k == 'media' and str(v['id']) == video_id and v['__typename'] == 'Video')), expected_type=dict)
  480. title = get_first(media, ('title', 'text'))
  481. description = get_first(media, ('creation_story', 'comet_sections', 'message', 'story', 'message', 'text'))
  482. page_title = title or self._html_search_regex((
  483. r'<h2\s+[^>]*class="uiHeaderTitle"[^>]*>(?P<content>[^<]*)</h2>',
  484. r'(?s)<span class="fbPhotosPhotoCaption".*?id="fbPhotoPageCaption"><span class="hasCaption">(?P<content>.*?)</span>',
  485. self._meta_regex('og:title'), self._meta_regex('twitter:title'), r'<title>(?P<content>.+?)</title>',
  486. ), webpage, 'title', default=None, group='content')
  487. description = description or self._html_search_meta(
  488. ['description', 'og:description', 'twitter:description'],
  489. webpage, 'description', default=None)
  490. uploader_data = (
  491. get_first(media, ('owner', {dict}))
  492. or get_first(post, ('video', 'creation_story', 'attachments', ..., 'media', lambda k, v: k == 'owner' and v['name']))
  493. or get_first(post, (..., 'video', lambda k, v: k == 'owner' and v['name']))
  494. or get_first(post, ('node', 'actors', ..., {dict}))
  495. or get_first(post, ('event', 'event_creator', {dict}))
  496. or get_first(post, ('video', 'creation_story', 'short_form_video_context', 'video_owner', {dict})) or {})
  497. uploader = uploader_data.get('name') or (
  498. clean_html(get_element_by_id('fbPhotoPageAuthorName', webpage))
  499. or self._search_regex(
  500. (r'ownerName\s*:\s*"([^"]+)"', *self._og_regexes('title')), webpage, 'uploader', fatal=False))
  501. timestamp = int_or_none(self._search_regex(
  502. r'<abbr[^>]+data-utime=["\'](\d+)', webpage,
  503. 'timestamp', default=None))
  504. thumbnail = self._html_search_meta(
  505. ['og:image', 'twitter:image'], webpage, 'thumbnail', default=None)
  506. # some webpages contain unretrievable thumbnail urls
  507. # like https://lookaside.fbsbx.com/lookaside/crawler/media/?media_id=10155168902769113&get_thumbnail=1
  508. # in https://www.facebook.com/yaroslav.korpan/videos/1417995061575415/
  509. if thumbnail and not re.search(r'\.(?:jpg|png)', thumbnail):
  510. thumbnail = None
  511. info_dict = {
  512. 'description': description,
  513. 'uploader': uploader,
  514. 'uploader_id': uploader_data.get('id'),
  515. 'timestamp': timestamp,
  516. 'thumbnail': thumbnail,
  517. 'view_count': parse_count(self._search_regex(
  518. (r'\bviewCount\s*:\s*["\']([\d,.]+)', r'video_view_count["\']\s*:\s*(\d+)'),
  519. webpage, 'view count', default=None)),
  520. 'concurrent_view_count': get_first(post, (
  521. ('video', (..., ..., 'attachments', ..., 'media')), 'liveViewerCount', {int_or_none})),
  522. **traverse_obj(post, (lambda _, v: video_id in v['url'], 'feedback', {
  523. 'like_count': ('likers', 'count', {int}),
  524. 'comment_count': ('total_comment_count', {int}),
  525. 'repost_count': ('share_count_reduced', {parse_count}),
  526. }), get_all=False),
  527. }
  528. info_json_ld = self._search_json_ld(webpage, video_id, default={})
  529. info_json_ld['title'] = (re.sub(r'\s*\|\s*Facebook$', '', title or info_json_ld.get('title') or page_title or '')
  530. or (description or '').replace('\n', ' ') or f'Facebook video #{video_id}')
  531. return merge_dicts(info_json_ld, info_dict)
  532. video_data = None
  533. def extract_video_data(instances):
  534. video_data = []
  535. for item in instances:
  536. if try_get(item, lambda x: x[1][0]) == 'VideoConfig':
  537. video_item = item[2][0]
  538. if video_item.get('video_id'):
  539. video_data.append(video_item['videoData'])
  540. return video_data
  541. server_js_data = self._parse_json(self._search_regex(
  542. [r'handleServerJS\(({.+})(?:\);|,")', r'\bs\.handle\(({.+?})\);'],
  543. webpage, 'server js data', default='{}'), video_id, fatal=False)
  544. if server_js_data:
  545. video_data = extract_video_data(server_js_data.get('instances', []))
  546. def extract_from_jsmods_instances(js_data):
  547. if js_data:
  548. return extract_video_data(try_get(
  549. js_data, lambda x: x['jsmods']['instances'], list) or [])
  550. def extract_dash_manifest(vid_data, formats, mpd_url=None):
  551. dash_manifest = traverse_obj(
  552. vid_data, 'dash_manifest', 'playlist', 'dash_manifest_xml_string', 'manifest_xml', expected_type=str)
  553. if dash_manifest:
  554. formats.extend(self._parse_mpd_formats(
  555. compat_etree_fromstring(urllib.parse.unquote_plus(dash_manifest)),
  556. mpd_url=url_or_none(vid_data.get('dash_manifest_url')) or mpd_url))
  557. def process_formats(info):
  558. # Downloads with browser's User-Agent are rate limited. Working around
  559. # with non-browser User-Agent.
  560. for f in info['formats']:
  561. # Downloads with browser's User-Agent are rate limited. Working around
  562. # with non-browser User-Agent.
  563. f.setdefault('http_headers', {})['User-Agent'] = 'facebookexternalhit/1.1'
  564. # Formats larger than ~500MB will return error 403 unless chunk size is regulated
  565. f.setdefault('downloader_options', {})['http_chunk_size'] = 250 << 20
  566. def yield_all_relay_data(_filter):
  567. for relay_data in re.findall(rf'data-sjs>({{.*?{_filter}.*?}})</script>', webpage):
  568. yield self._parse_json(relay_data, video_id, fatal=False) or {}
  569. def extract_relay_data(_filter):
  570. return next(filter(None, yield_all_relay_data(_filter)), {})
  571. def extract_relay_prefetched_data(_filter, target_keys=None):
  572. path = 'data'
  573. if target_keys is not None:
  574. path = lambda k, v: k == 'data' and any(target in v for target in variadic(target_keys))
  575. return traverse_obj(yield_all_relay_data(_filter), (
  576. ..., 'require', (None, (..., ..., ..., '__bbox', 'require')),
  577. lambda _, v: any(key.startswith('RelayPrefetchedStreamCache') for key in v),
  578. ..., ..., '__bbox', 'result', path, {dict}), get_all=False) or {}
  579. if not video_data:
  580. server_js_data = self._parse_json(self._search_regex([
  581. r'bigPipe\.onPageletArrive\(({.+?})\)\s*;\s*}\s*\)\s*,\s*["\']onPageletArrive\s+' + self._SUPPORTED_PAGLETS_REGEX,
  582. rf'bigPipe\.onPageletArrive\(({{.*?id\s*:\s*"{self._SUPPORTED_PAGLETS_REGEX}".*?}})\);',
  583. ], webpage, 'js data', default='{}'), video_id, js_to_json, False)
  584. video_data = extract_from_jsmods_instances(server_js_data)
  585. if not video_data:
  586. data = extract_relay_prefetched_data(
  587. r'"(?:dash_manifest|playable_url(?:_quality_hd)?)',
  588. target_keys=('video', 'event', 'nodes', 'node', 'mediaset'))
  589. if data:
  590. entries = []
  591. def parse_graphql_video(video):
  592. v_id = video.get('videoId') or video.get('id') or video_id
  593. reel_info = traverse_obj(
  594. video, ('creation_story', 'short_form_video_context', 'playback_video', {dict}))
  595. if reel_info:
  596. video = video['creation_story']
  597. video['owner'] = traverse_obj(video, ('short_form_video_context', 'video_owner'))
  598. video.update(reel_info)
  599. formats = []
  600. q = qualities(['sd', 'hd'])
  601. # Legacy formats extraction
  602. fmt_data = traverse_obj(video, ('videoDeliveryLegacyFields', {dict})) or video
  603. for key, format_id in (('playable_url', 'sd'), ('playable_url_quality_hd', 'hd'),
  604. ('playable_url_dash', ''), ('browser_native_hd_url', 'hd'),
  605. ('browser_native_sd_url', 'sd')):
  606. playable_url = fmt_data.get(key)
  607. if not playable_url:
  608. continue
  609. if determine_ext(playable_url) == 'mpd':
  610. formats.extend(self._extract_mpd_formats(playable_url, video_id, fatal=False))
  611. else:
  612. formats.append({
  613. 'format_id': format_id,
  614. # sd, hd formats w/o resolution info should be deprioritized below DASH
  615. 'quality': q(format_id) - 3,
  616. 'url': playable_url,
  617. })
  618. extract_dash_manifest(fmt_data, formats)
  619. # New videoDeliveryResponse formats extraction
  620. fmt_data = traverse_obj(video, ('videoDeliveryResponseFragment', 'videoDeliveryResponseResult'))
  621. mpd_urls = traverse_obj(fmt_data, ('dash_manifest_urls', ..., 'manifest_url', {url_or_none}))
  622. dash_manifests = traverse_obj(fmt_data, ('dash_manifests', lambda _, v: v['manifest_xml']))
  623. for idx, dash_manifest in enumerate(dash_manifests):
  624. extract_dash_manifest(dash_manifest, formats, mpd_url=traverse_obj(mpd_urls, idx))
  625. if not dash_manifests:
  626. # Only extract from MPD URLs if the manifests are not already provided
  627. for mpd_url in mpd_urls:
  628. formats.extend(self._extract_mpd_formats(mpd_url, video_id, fatal=False))
  629. for prog_fmt in traverse_obj(fmt_data, ('progressive_urls', lambda _, v: v['progressive_url'])):
  630. format_id = traverse_obj(prog_fmt, ('metadata', 'quality', {str.lower}))
  631. formats.append({
  632. 'format_id': format_id,
  633. # sd, hd formats w/o resolution info should be deprioritized below DASH
  634. 'quality': q(format_id) - 3,
  635. 'url': prog_fmt['progressive_url'],
  636. })
  637. for m3u8_url in traverse_obj(fmt_data, ('hls_playlist_urls', ..., 'hls_playlist_url', {url_or_none})):
  638. formats.extend(self._extract_m3u8_formats(m3u8_url, video_id, 'mp4', fatal=False, m3u8_id='hls'))
  639. if not formats:
  640. # Do not append false positive entry w/o any formats
  641. return
  642. automatic_captions, subtitles = {}, {}
  643. is_broadcast = traverse_obj(video, ('is_video_broadcast', {bool}))
  644. for caption in traverse_obj(video, (
  645. 'video_available_captions_locales',
  646. {lambda x: sorted(x, key=lambda c: c['locale'])},
  647. lambda _, v: url_or_none(v['captions_url']),
  648. )):
  649. lang = caption.get('localized_language') or 'und'
  650. subs = {
  651. 'url': caption['captions_url'],
  652. 'name': format_field(caption, 'localized_country', f'{lang} (%s)', default=lang),
  653. }
  654. if caption.get('localized_creation_method') or is_broadcast:
  655. automatic_captions.setdefault(caption['locale'], []).append(subs)
  656. else:
  657. subtitles.setdefault(caption['locale'], []).append(subs)
  658. captions_url = traverse_obj(video, ('captions_url', {url_or_none}))
  659. if captions_url and not automatic_captions and not subtitles:
  660. locale = self._html_search_meta(
  661. ['og:locale', 'twitter:locale'], webpage, 'locale', default='en_US')
  662. (automatic_captions if is_broadcast else subtitles)[locale] = [{'url': captions_url}]
  663. info = {
  664. 'id': v_id,
  665. 'formats': formats,
  666. 'thumbnail': traverse_obj(
  667. video, ('thumbnailImage', 'uri'), ('preferred_thumbnail', 'image', 'uri')),
  668. 'uploader_id': traverse_obj(video, ('owner', 'id', {str_or_none})),
  669. 'timestamp': traverse_obj(video, 'publish_time', 'creation_time', expected_type=int_or_none),
  670. 'duration': (float_or_none(video.get('playable_duration_in_ms'), 1000)
  671. or float_or_none(video.get('length_in_second'))),
  672. 'automatic_captions': automatic_captions,
  673. 'subtitles': subtitles,
  674. }
  675. process_formats(info)
  676. description = try_get(video, lambda x: x['savable_description']['text'])
  677. title = video.get('name')
  678. if title:
  679. info.update({
  680. 'title': title,
  681. 'description': description,
  682. })
  683. else:
  684. info['title'] = description or f'Facebook video #{v_id}'
  685. entries.append(info)
  686. def parse_attachment(attachment, key='media'):
  687. media = attachment.get(key) or {}
  688. if media.get('__typename') == 'Video':
  689. return parse_graphql_video(media)
  690. nodes = variadic(traverse_obj(data, 'nodes', 'node') or [])
  691. attachments = traverse_obj(nodes, (
  692. ..., 'comet_sections', 'content', 'story', (None, 'attached_story'), 'attachments',
  693. ..., ('styles', 'style_type_renderer', ('throwbackStyles', 'attachment_target_renderer')),
  694. 'attachment', {dict}))
  695. for attachment in attachments:
  696. ns = traverse_obj(attachment, ('all_subattachments', 'nodes', ..., {dict}),
  697. ('target', 'attachments', ..., 'styles', 'attachment', {dict}))
  698. for n in ns:
  699. parse_attachment(n)
  700. parse_attachment(attachment)
  701. edges = try_get(data, lambda x: x['mediaset']['currMedia']['edges'], list) or []
  702. for edge in edges:
  703. parse_attachment(edge, key='node')
  704. video = traverse_obj(data, (
  705. 'event', 'cover_media_renderer', 'cover_video'), 'video', expected_type=dict) or {}
  706. if video:
  707. attachments = try_get(video, [
  708. lambda x: x['story']['attachments'],
  709. lambda x: x['creation_story']['attachments'],
  710. ], list) or []
  711. for attachment in attachments:
  712. parse_attachment(attachment)
  713. if not entries:
  714. parse_graphql_video(video)
  715. if len(entries) > 1:
  716. return self.playlist_result(entries, video_id)
  717. video_info = entries[0] if entries else {'id': video_id}
  718. webpage_info = extract_metadata(webpage)
  719. # honor precise duration in video info
  720. if video_info.get('duration'):
  721. webpage_info['duration'] = video_info['duration']
  722. # preserve preferred_thumbnail in video info
  723. if video_info.get('thumbnail'):
  724. webpage_info['thumbnail'] = video_info['thumbnail']
  725. return merge_dicts(webpage_info, video_info)
  726. if not video_data:
  727. m_msg = re.search(r'class="[^"]*uiInterstitialContent[^"]*"><div>(.*?)</div>', webpage)
  728. if m_msg is not None:
  729. raise ExtractorError(
  730. f'The video is not available, Facebook said: "{m_msg.group(1)}"',
  731. expected=True)
  732. elif any(p in webpage for p in (
  733. '>You must log in to continue',
  734. 'id="login_form"',
  735. 'id="loginbutton"')):
  736. self.raise_login_required()
  737. if not video_data and '/watchparty/' in url:
  738. post_data = {
  739. 'doc_id': 3731964053542869,
  740. 'variables': json.dumps({
  741. 'livingRoomID': video_id,
  742. }),
  743. }
  744. prefetched_data = extract_relay_prefetched_data(r'"login_data"\s*:\s*{')
  745. if prefetched_data:
  746. lsd = try_get(prefetched_data, lambda x: x['login_data']['lsd'], dict)
  747. if lsd:
  748. post_data[lsd['name']] = lsd['value']
  749. relay_data = extract_relay_data(r'\[\s*"RelayAPIConfigDefaults"\s*,')
  750. for define in (relay_data.get('define') or []):
  751. if define[0] == 'RelayAPIConfigDefaults':
  752. self._api_config = define[2]
  753. living_room = self._download_json(
  754. urljoin(url, self._api_config['graphURI']), video_id,
  755. data=urlencode_postdata(post_data))['data']['living_room']
  756. entries = []
  757. for edge in (try_get(living_room, lambda x: x['recap']['watched_content']['edges']) or []):
  758. video = try_get(edge, lambda x: x['node']['video']) or {}
  759. v_id = video.get('id')
  760. if not v_id:
  761. continue
  762. v_id = str(v_id)
  763. entries.append(self.url_result(
  764. self._VIDEO_PAGE_TEMPLATE % v_id,
  765. self.ie_key(), v_id, video.get('name')))
  766. return self.playlist_result(entries, video_id)
  767. if not video_data:
  768. # Video info not in first request, do a secondary request using
  769. # tahoe player specific URL
  770. tahoe_data = self._download_webpage(
  771. self._VIDEO_PAGE_TAHOE_TEMPLATE % video_id, video_id,
  772. data=urlencode_postdata({
  773. '__a': 1,
  774. '__pc': self._search_regex(
  775. r'pkg_cohort["\']\s*:\s*["\'](.+?)["\']', webpage,
  776. 'pkg cohort', default='PHASED:DEFAULT'),
  777. '__rev': self._search_regex(
  778. r'client_revision["\']\s*:\s*(\d+),', webpage,
  779. 'client revision', default='3944515'),
  780. 'fb_dtsg': self._search_regex(
  781. r'"DTSGInitialData"\s*,\s*\[\]\s*,\s*{\s*"token"\s*:\s*"([^"]+)"',
  782. webpage, 'dtsg token', default=''),
  783. }),
  784. headers={
  785. 'Content-Type': 'application/x-www-form-urlencoded',
  786. })
  787. tahoe_js_data = self._parse_json(
  788. self._search_regex(
  789. r'for\s+\(\s*;\s*;\s*\)\s*;(.+)', tahoe_data,
  790. 'tahoe js data', default='{}'),
  791. video_id, fatal=False)
  792. video_data = extract_from_jsmods_instances(tahoe_js_data)
  793. if not video_data:
  794. raise ExtractorError('Cannot parse data')
  795. if len(video_data) > 1:
  796. entries = []
  797. for v in video_data:
  798. video_url = v[0].get('video_url')
  799. if not video_url:
  800. continue
  801. entries.append(self.url_result(urljoin(
  802. url, video_url), self.ie_key(), v[0].get('video_id')))
  803. return self.playlist_result(entries, video_id)
  804. video_data = video_data[0]
  805. formats = []
  806. subtitles = {}
  807. for f in video_data:
  808. format_id = f['stream_type']
  809. if f and isinstance(f, dict):
  810. f = [f]
  811. if not f or not isinstance(f, list):
  812. continue
  813. for quality in ('sd', 'hd'):
  814. for src_type in ('src', 'src_no_ratelimit'):
  815. src = f[0].get(f'{quality}_{src_type}')
  816. if src:
  817. # sd, hd formats w/o resolution info should be deprioritized below DASH
  818. # TODO: investigate if progressive or src formats still exist
  819. preference = -10 if format_id == 'progressive' else -3
  820. if quality == 'hd':
  821. preference += 1
  822. formats.append({
  823. 'format_id': f'{format_id}_{quality}_{src_type}',
  824. 'url': src,
  825. 'quality': preference,
  826. 'height': 720 if quality == 'hd' else None,
  827. })
  828. extract_dash_manifest(f[0], formats)
  829. subtitles_src = f[0].get('subtitles_src')
  830. if subtitles_src:
  831. subtitles.setdefault('en', []).append({'url': subtitles_src})
  832. info_dict = {
  833. 'id': video_id,
  834. 'formats': formats,
  835. 'subtitles': subtitles,
  836. }
  837. process_formats(info_dict)
  838. info_dict.update(extract_metadata(webpage))
  839. return info_dict
  840. def _real_extract(self, url):
  841. video_id = self._match_id(url)
  842. real_url = self._VIDEO_PAGE_TEMPLATE % video_id if url.startswith('facebook:') else url
  843. return self._extract_from_url(real_url, video_id)
  844. class FacebookPluginsVideoIE(InfoExtractor):
  845. _VALID_URL = r'https?://(?:[\w-]+\.)?facebook\.com/plugins/video\.php\?.*?\bhref=(?P<id>https.+)'
  846. _TESTS = [{
  847. 'url': 'https://www.facebook.com/plugins/video.php?href=https%3A%2F%2Fwww.facebook.com%2Fgov.sg%2Fvideos%2F10154383743583686%2F&show_text=0&width=560',
  848. 'md5': '5954e92cdfe51fe5782ae9bda7058a07',
  849. 'info_dict': {
  850. 'id': '10154383743583686',
  851. 'ext': 'mp4',
  852. # TODO: Fix title, uploader
  853. 'title': 'What to do during the haze?',
  854. 'uploader': 'Gov.sg',
  855. 'upload_date': '20160826',
  856. 'timestamp': 1472184808,
  857. },
  858. 'add_ie': [FacebookIE.ie_key()],
  859. }, {
  860. 'url': 'https://www.facebook.com/plugins/video.php?href=https%3A%2F%2Fwww.facebook.com%2Fvideo.php%3Fv%3D10204634152394104',
  861. 'only_matching': True,
  862. }, {
  863. 'url': 'https://www.facebook.com/plugins/video.php?href=https://www.facebook.com/gov.sg/videos/10154383743583686/&show_text=0&width=560',
  864. 'only_matching': True,
  865. }]
  866. def _real_extract(self, url):
  867. return self.url_result(
  868. urllib.parse.unquote(self._match_id(url)),
  869. FacebookIE.ie_key())
  870. class FacebookRedirectURLIE(InfoExtractor):
  871. IE_DESC = False # Do not list
  872. _VALID_URL = r'https?://(?:[\w-]+\.)?facebook\.com/flx/warn[/?]'
  873. _TESTS = [{
  874. 'url': 'https://www.facebook.com/flx/warn/?h=TAQHsoToz&u=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DpO8h3EaFRdo&s=1',
  875. 'info_dict': {
  876. 'id': 'pO8h3EaFRdo',
  877. 'ext': 'mp4',
  878. 'title': 'Tripeo Boiler Room x Dekmantel Festival DJ Set',
  879. 'description': 'md5:2d713ccbb45b686a1888397b2c77ca6b',
  880. 'channel_id': 'UCGBpxWJr9FNOcFYA5GkKrMg',
  881. 'playable_in_embed': True,
  882. 'categories': ['Music'],
  883. 'channel': 'Boiler Room',
  884. 'uploader_id': 'brtvofficial',
  885. 'uploader': 'Boiler Room',
  886. 'tags': 'count:11',
  887. 'duration': 3332,
  888. 'live_status': 'not_live',
  889. 'thumbnail': 'https://i.ytimg.com/vi/pO8h3EaFRdo/maxresdefault.jpg',
  890. 'channel_url': 'https://www.youtube.com/channel/UCGBpxWJr9FNOcFYA5GkKrMg',
  891. 'availability': 'public',
  892. 'uploader_url': 'http://www.youtube.com/user/brtvofficial',
  893. 'upload_date': '20150917',
  894. 'age_limit': 0,
  895. 'view_count': int,
  896. 'like_count': int,
  897. },
  898. 'add_ie': ['Youtube'],
  899. 'params': {'skip_download': 'Youtube'},
  900. }]
  901. def _real_extract(self, url):
  902. redirect_url = url_or_none(parse_qs(url).get('u', [None])[-1])
  903. if not redirect_url:
  904. raise ExtractorError('Invalid facebook redirect URL', expected=True)
  905. return self.url_result(redirect_url)
  906. class FacebookReelIE(InfoExtractor):
  907. _VALID_URL = r'https?://(?:[\w-]+\.)?facebook\.com/reel/(?P<id>\d+)'
  908. IE_NAME = 'facebook:reel'
  909. _TESTS = [{
  910. 'url': 'https://www.facebook.com/reel/1195289147628387',
  911. 'md5': 'a53256d10fc2105441fe0c4212ed8cea',
  912. 'info_dict': {
  913. 'id': '1195289147628387',
  914. 'ext': 'mp4',
  915. 'title': r're:9\.6K views · 355 reactions .+ Let the “Slapathon” commence!! .+ LL COOL J · Mama Said Knock You Out$',
  916. 'description': r're:When your trying to help your partner .+ LL COOL J · Mama Said Knock You Out$',
  917. 'uploader': 'Beast Camp Training',
  918. 'uploader_id': '100040874179269',
  919. 'duration': 9.579,
  920. 'timestamp': 1637502609,
  921. 'upload_date': '20211121',
  922. 'thumbnail': r're:^https?://.*',
  923. 'like_count': int,
  924. 'comment_count': int,
  925. 'repost_count': int,
  926. },
  927. }]
  928. def _real_extract(self, url):
  929. video_id = self._match_id(url)
  930. return self.url_result(
  931. f'https://m.facebook.com/watch/?v={video_id}&_rdr', FacebookIE, video_id)
  932. class FacebookAdsIE(InfoExtractor):
  933. _VALID_URL = r'https?://(?:[\w-]+\.)?facebook\.com/ads/library/?\?(?:[^#]+&)?id=(?P<id>\d+)'
  934. IE_NAME = 'facebook:ads'
  935. _TESTS = [{
  936. 'url': 'https://www.facebook.com/ads/library/?id=899206155126718',
  937. 'info_dict': {
  938. 'id': '899206155126718',
  939. 'ext': 'mp4',
  940. 'title': 'video by Kandao',
  941. 'description': 'md5:0822724069e3aca97cbed5dabbab282e',
  942. 'uploader': 'Kandao',
  943. 'uploader_id': '774114102743284',
  944. 'uploader_url': r're:^https?://.*',
  945. 'timestamp': 1702548330,
  946. 'thumbnail': r're:^https?://.*',
  947. 'upload_date': '20231214',
  948. 'like_count': int,
  949. },
  950. }, {
  951. # key 'watermarked_video_sd_url' missing
  952. 'url': 'https://www.facebook.com/ads/library/?id=501152689226254',
  953. 'info_dict': {
  954. 'id': '501152689226254',
  955. 'ext': 'mp4',
  956. 'title': 'video by mat.nawrocki',
  957. 'description': 'md5:02a446ace7ff8c3c37a2892922492490',
  958. 'uploader': 'mat.nawrocki',
  959. 'uploader_id': '148586968341456',
  960. 'uploader_url': r're:^https?://.*',
  961. 'timestamp': 1723452305,
  962. 'thumbnail': r're:^https?://.*',
  963. 'upload_date': '20240812',
  964. 'like_count': int,
  965. },
  966. }, {
  967. 'url': 'https://www.facebook.com/ads/library/?id=893637265423481',
  968. 'info_dict': {
  969. 'id': '893637265423481',
  970. 'title': 'Jusqu\u2019\u00e0 -25% sur une s\u00e9lection de vins p\u00e9tillants italiens ',
  971. 'uploader': 'Eataly Paris Marais',
  972. 'uploader_id': '2086668958314152',
  973. 'uploader_url': r're:^https?://.*',
  974. 'timestamp': 1703571529,
  975. 'upload_date': '20231226',
  976. 'like_count': int,
  977. },
  978. 'playlist_count': 3,
  979. }, {
  980. 'url': 'https://es-la.facebook.com/ads/library/?id=901230958115569',
  981. 'only_matching': True,
  982. }, {
  983. 'url': 'https://m.facebook.com/ads/library/?id=901230958115569',
  984. 'only_matching': True,
  985. }]
  986. _FORMATS_MAP = {
  987. 'watermarked_video_sd_url': ('sd-wmk', 'SD, watermarked'),
  988. 'video_sd_url': ('sd', None),
  989. 'watermarked_video_hd_url': ('hd-wmk', 'HD, watermarked'),
  990. 'video_hd_url': ('hd', None),
  991. }
  992. def _extract_formats(self, video_dict):
  993. formats = []
  994. for format_key, format_url in traverse_obj(video_dict, (
  995. {dict.items}, lambda _, v: v[0] in self._FORMATS_MAP and url_or_none(v[1]),
  996. )):
  997. formats.append({
  998. 'format_id': self._FORMATS_MAP[format_key][0],
  999. 'format_note': self._FORMATS_MAP[format_key][1],
  1000. 'url': format_url,
  1001. 'ext': 'mp4',
  1002. 'quality': qualities(tuple(self._FORMATS_MAP))(format_key),
  1003. })
  1004. return formats
  1005. def _real_extract(self, url):
  1006. video_id = self._match_id(url)
  1007. webpage = self._download_webpage(url, video_id)
  1008. post_data = traverse_obj(
  1009. re.findall(r'data-sjs>({.*?ScheduledServerJS.*?})</script>', webpage), (..., {json.loads}))
  1010. data = get_first(post_data, (
  1011. 'require', ..., ..., ..., '__bbox', 'require', ..., ..., ...,
  1012. 'entryPointRoot', 'otherProps', 'deeplinkAdCard', 'snapshot', {dict}))
  1013. if not data:
  1014. raise ExtractorError('Unable to extract ad data')
  1015. title = data.get('title')
  1016. if not title or title == '{{product.name}}':
  1017. title = join_nonempty('display_format', 'page_name', delim=' by ', from_dict=data)
  1018. markup_id = traverse_obj(data, ('body', '__m', {str}))
  1019. markup = traverse_obj(post_data, (
  1020. ..., 'require', ..., ..., ..., '__bbox', 'markup', lambda _, v: v[0].startswith(markup_id),
  1021. ..., '__html', {clean_html}, {lambda x: not x.startswith('{{product.') and x}, any))
  1022. info_dict = merge_dicts({
  1023. 'title': title,
  1024. 'description': markup or None,
  1025. }, traverse_obj(data, {
  1026. 'description': ('link_description', {lambda x: x if not x.startswith('{{product.') else None}),
  1027. 'uploader': ('page_name', {str}),
  1028. 'uploader_id': ('page_id', {str_or_none}),
  1029. 'uploader_url': ('page_profile_uri', {url_or_none}),
  1030. 'timestamp': ('creation_time', {int_or_none}),
  1031. 'like_count': ('page_like_count', {int_or_none}),
  1032. }))
  1033. entries = []
  1034. for idx, entry in enumerate(traverse_obj(
  1035. data, (('videos', 'cards'), lambda _, v: any(url_or_none(v.get(f)) for f in self._FORMATS_MAP))), 1,
  1036. ):
  1037. entries.append({
  1038. 'id': f'{video_id}_{idx}',
  1039. 'title': entry.get('title') or title,
  1040. 'description': traverse_obj(entry, 'body', 'link_description') or info_dict.get('description'),
  1041. 'thumbnail': url_or_none(entry.get('video_preview_image_url')),
  1042. 'formats': self._extract_formats(entry),
  1043. })
  1044. if len(entries) == 1:
  1045. info_dict.update(entries[0])
  1046. elif len(entries) > 1:
  1047. info_dict.update({
  1048. 'title': entries[0]['title'],
  1049. 'entries': entries,
  1050. '_type': 'playlist',
  1051. })
  1052. info_dict['id'] = video_id
  1053. return info_dict