facebook.py 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800
  1. import json
  2. import re
  3. import urllib.parse
  4. from .common import InfoExtractor
  5. from ..compat import (
  6. compat_etree_fromstring,
  7. compat_str,
  8. compat_urllib_parse_unquote,
  9. )
  10. from ..utils import (
  11. ExtractorError,
  12. clean_html,
  13. determine_ext,
  14. error_to_compat_str,
  15. float_or_none,
  16. get_element_by_id,
  17. get_first,
  18. int_or_none,
  19. js_to_json,
  20. merge_dicts,
  21. network_exceptions,
  22. parse_count,
  23. parse_qs,
  24. qualities,
  25. sanitized_Request,
  26. traverse_obj,
  27. try_get,
  28. url_or_none,
  29. urlencode_postdata,
  30. urljoin,
  31. variadic,
  32. )
  33. class FacebookIE(InfoExtractor):
  34. _VALID_URL = r'''(?x)
  35. (?:
  36. https?://
  37. (?:[\w-]+\.)?(?:facebook\.com|facebookwkhpilnemxj7asaniu7vnjjbiltxjqhye3mhbshg7kx5tfyd\.onion)/
  38. (?:[^#]*?\#!/)?
  39. (?:
  40. (?:
  41. video/video\.php|
  42. photo\.php|
  43. video\.php|
  44. video/embed|
  45. story\.php|
  46. watch(?:/live)?/?
  47. )\?(?:.*?)(?:v|video_id|story_fbid)=|
  48. [^/]+/videos/(?:[^/]+/)?|
  49. [^/]+/posts/|
  50. groups/[^/]+/permalink/|
  51. watchparty/
  52. )|
  53. facebook:
  54. )
  55. (?P<id>[0-9]+)
  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/video.php?v=637842556329505&fref=nf',
  72. 'md5': '6a40d33c0eccbb1af76cf0485a052659',
  73. 'info_dict': {
  74. 'id': '637842556329505',
  75. 'ext': 'mp4',
  76. 'title': 're:Did you know Kei Nishikori is the first Asian man to ever reach a Grand Slam',
  77. 'uploader': 'Tennis on Facebook',
  78. 'upload_date': '20140908',
  79. 'timestamp': 1410199200,
  80. },
  81. 'skip': 'Requires logging in',
  82. }, {
  83. # data.video
  84. 'url': 'https://www.facebook.com/video.php?v=274175099429670',
  85. 'info_dict': {
  86. 'id': '274175099429670',
  87. 'ext': 'mp4',
  88. 'title': 'Asif Nawab Butt',
  89. 'description': 'Asif Nawab Butt',
  90. 'uploader': 'Asif Nawab Butt',
  91. 'upload_date': '20140506',
  92. 'timestamp': 1399398998,
  93. 'thumbnail': r're:^https?://.*',
  94. },
  95. 'expected_warnings': [
  96. 'title'
  97. ]
  98. }, {
  99. 'note': 'Video with DASH manifest',
  100. 'url': 'https://www.facebook.com/video.php?v=957955867617029',
  101. 'md5': 'b2c28d528273b323abe5c6ab59f0f030',
  102. 'info_dict': {
  103. 'id': '957955867617029',
  104. 'ext': 'mp4',
  105. 'title': 'When you post epic content on instagram.com/433 8 million followers, this is ...',
  106. 'uploader': 'Demy de Zeeuw',
  107. 'upload_date': '20160110',
  108. 'timestamp': 1452431627,
  109. },
  110. 'skip': 'Requires logging in',
  111. }, {
  112. 'url': 'https://www.facebook.com/maxlayn/posts/10153807558977570',
  113. 'md5': '037b1fa7f3c2d02b7a0d7bc16031ecc6',
  114. 'info_dict': {
  115. 'id': '544765982287235',
  116. 'ext': 'mp4',
  117. 'title': '"What are you doing running in the snow?"',
  118. 'uploader': 'FailArmy',
  119. },
  120. 'skip': 'Video gone',
  121. }, {
  122. 'url': 'https://m.facebook.com/story.php?story_fbid=1035862816472149&id=116132035111903',
  123. 'md5': '1deb90b6ac27f7efcf6d747c8a27f5e3',
  124. 'info_dict': {
  125. 'id': '1035862816472149',
  126. 'ext': 'mp4',
  127. 'title': 'What the Flock Is Going On In New Zealand Credit: ViralHog',
  128. 'uploader': 'S. Saint',
  129. },
  130. 'skip': 'Video gone',
  131. }, {
  132. 'note': 'swf params escaped',
  133. 'url': 'https://www.facebook.com/barackobama/posts/10153664894881749',
  134. 'md5': '97ba073838964d12c70566e0085c2b91',
  135. 'info_dict': {
  136. 'id': '10153664894881749',
  137. 'ext': 'mp4',
  138. 'title': 'Average time to confirm recent Supreme Court nominees: 67 days Longest it\'s t...',
  139. 'thumbnail': r're:^https?://.*',
  140. 'timestamp': 1456259628,
  141. 'upload_date': '20160223',
  142. 'uploader': 'Barack Obama',
  143. },
  144. 'skip': 'Gif on giphy.com gone',
  145. }, {
  146. # have 1080P, but only up to 720p in swf params
  147. # data.video.story.attachments[].media
  148. 'url': 'https://www.facebook.com/cnn/videos/10155529876156509/',
  149. 'md5': '3f3798adb2b73423263e59376f1f5eb7',
  150. 'info_dict': {
  151. 'id': '10155529876156509',
  152. 'ext': 'mp4',
  153. 'title': 'Holocaust survivor becomes US citizen',
  154. 'description': 'She survived the holocaust — and years later, she’s getting her citizenship so she can vote for Hillary Clinton http://cnn.it/2eERh5f',
  155. 'timestamp': 1477818095,
  156. 'upload_date': '20161030',
  157. 'uploader': 'CNN',
  158. 'thumbnail': r're:^https?://.*',
  159. 'view_count': int,
  160. },
  161. }, {
  162. # bigPipe.onPageletArrive ... onPageletArrive pagelet_group_mall
  163. # data.node.comet_sections.content.story.attachments[].style_type_renderer.attachment.media
  164. 'url': 'https://www.facebook.com/yaroslav.korpan/videos/1417995061575415/',
  165. 'info_dict': {
  166. 'id': '1417995061575415',
  167. 'ext': 'mp4',
  168. 'title': 'Ukrainian Scientists Worldwide | Довгоочікуване відео',
  169. 'description': 'Довгоочікуване відео',
  170. 'timestamp': 1486648771,
  171. 'upload_date': '20170209',
  172. 'uploader': 'Yaroslav Korpan',
  173. 'uploader_id': '100000948048708',
  174. },
  175. 'params': {
  176. 'skip_download': True,
  177. },
  178. }, {
  179. # FIXME
  180. 'url': 'https://www.facebook.com/LaGuiaDelVaron/posts/1072691702860471',
  181. 'info_dict': {
  182. 'id': '1072691702860471',
  183. 'ext': 'mp4',
  184. 'title': 'md5:ae2d22a93fbb12dad20dc393a869739d',
  185. 'timestamp': 1477305000,
  186. 'upload_date': '20161024',
  187. 'uploader': 'La Guía Del Varón',
  188. 'thumbnail': r're:^https?://.*',
  189. },
  190. 'params': {
  191. 'skip_download': True,
  192. },
  193. }, {
  194. # data.node.comet_sections.content.story.attachments[].style_type_renderer.attachment.media
  195. 'url': 'https://www.facebook.com/groups/1024490957622648/permalink/1396382447100162/',
  196. 'info_dict': {
  197. 'id': '202882990186699',
  198. 'ext': 'mp4',
  199. 'title': 'birb (O v O") | Hello? Yes your uber ride is here',
  200. 'description': 'Hello? Yes your uber ride is here * Jukin Media Verified * Find this video and others like it by visiting...',
  201. 'timestamp': 1486035513,
  202. 'upload_date': '20170202',
  203. 'uploader': 'Elisabeth Ahtn',
  204. 'uploader_id': '100013949973717',
  205. },
  206. 'params': {
  207. 'skip_download': True,
  208. },
  209. }, {
  210. 'url': 'https://www.facebook.com/video.php?v=10204634152394104',
  211. 'only_matching': True,
  212. }, {
  213. 'url': 'https://www.facebook.com/amogood/videos/1618742068337349/?fref=nf',
  214. 'only_matching': True,
  215. }, {
  216. # data.mediaset.currMedia.edges
  217. 'url': 'https://www.facebook.com/ChristyClarkForBC/videos/vb.22819070941/10153870694020942/?type=2&theater',
  218. 'only_matching': True,
  219. }, {
  220. # data.video.story.attachments[].media
  221. 'url': 'facebook:544765982287235',
  222. 'only_matching': True,
  223. }, {
  224. # data.node.comet_sections.content.story.attachments[].style_type_renderer.attachment.media
  225. 'url': 'https://www.facebook.com/groups/164828000315060/permalink/764967300301124/',
  226. 'only_matching': True,
  227. }, {
  228. # data.video.creation_story.attachments[].media
  229. 'url': 'https://zh-hk.facebook.com/peoplespower/videos/1135894589806027/',
  230. 'only_matching': True,
  231. }, {
  232. # data.video
  233. 'url': 'https://www.facebookwkhpilnemxj7asaniu7vnjjbiltxjqhye3mhbshg7kx5tfyd.onion/video.php?v=274175099429670',
  234. 'only_matching': True,
  235. }, {
  236. # no title
  237. 'url': 'https://www.facebook.com/onlycleverentertainment/videos/1947995502095005/',
  238. 'only_matching': True,
  239. }, {
  240. # data.video
  241. 'url': 'https://www.facebook.com/WatchESLOne/videos/359649331226507/',
  242. 'info_dict': {
  243. 'id': '359649331226507',
  244. 'ext': 'mp4',
  245. 'title': 'Fnatic vs. EG - Group A - Opening Match - ESL One Birmingham Day 1',
  246. 'description': '#ESLOne VoD - Birmingham Finals Day#1 Fnatic vs. @Evil Geniuses',
  247. 'timestamp': 1527084179,
  248. 'upload_date': '20180523',
  249. 'uploader': 'ESL One Dota 2',
  250. 'uploader_id': '234218833769558',
  251. },
  252. 'params': {
  253. 'skip_download': True,
  254. },
  255. }, {
  256. # data.node.comet_sections.content.story.attachments[].style_type_renderer.attachment.all_subattachments.nodes[].media
  257. 'url': 'https://www.facebook.com/100033620354545/videos/106560053808006/',
  258. 'info_dict': {
  259. 'id': '106560053808006',
  260. },
  261. 'playlist_count': 2,
  262. }, {
  263. # data.video.story.attachments[].media
  264. 'url': 'https://www.facebook.com/watch/?v=647537299265662',
  265. 'only_matching': True,
  266. }, {
  267. # FIXME: https://github.com/hypervideo/hypervideo/issues/542
  268. # data.node.comet_sections.content.story.attachments[].style_type_renderer.attachment.all_subattachments.nodes[].media
  269. 'url': 'https://www.facebook.com/PankajShahLondon/posts/10157667649866271',
  270. 'info_dict': {
  271. 'id': '10157667649866271',
  272. },
  273. 'playlist_count': 3,
  274. }, {
  275. # data.nodes[].comet_sections.content.story.attachments[].style_type_renderer.attachment.media
  276. 'url': 'https://m.facebook.com/Alliance.Police.Department/posts/4048563708499330',
  277. 'info_dict': {
  278. 'id': '117576630041613',
  279. 'ext': 'mp4',
  280. # TODO: title can be extracted from video page
  281. 'title': 'Facebook video #117576630041613',
  282. 'uploader_id': '189393014416438',
  283. 'upload_date': '20201123',
  284. 'timestamp': 1606162592,
  285. },
  286. 'skip': 'Requires logging in',
  287. }, {
  288. # node.comet_sections.content.story.attached_story.attachments.style_type_renderer.attachment.media
  289. 'url': 'https://www.facebook.com/groups/ateistiskselskab/permalink/10154930137678856/',
  290. 'info_dict': {
  291. 'id': '211567722618337',
  292. 'ext': 'mp4',
  293. 'title': 'Facebook video #211567722618337',
  294. 'uploader_id': '127875227654254',
  295. 'upload_date': '20161122',
  296. 'timestamp': 1479793574,
  297. },
  298. 'skip': 'No video',
  299. }, {
  300. # data.video.creation_story.attachments[].media
  301. 'url': 'https://www.facebook.com/watch/live/?v=1823658634322275',
  302. 'only_matching': True,
  303. }, {
  304. 'url': 'https://www.facebook.com/watchparty/211641140192478',
  305. 'info_dict': {
  306. 'id': '211641140192478',
  307. },
  308. 'playlist_count': 1,
  309. 'skip': 'Requires logging in',
  310. }]
  311. _SUPPORTED_PAGLETS_REGEX = r'(?:pagelet_group_mall|permalink_video_pagelet|hyperfeed_story_id_[0-9a-f]+)'
  312. _api_config = {
  313. 'graphURI': '/api/graphql/'
  314. }
  315. def _perform_login(self, username, password):
  316. login_page_req = sanitized_Request(self._LOGIN_URL)
  317. self._set_cookie('facebook.com', 'locale', 'en_US')
  318. login_page = self._download_webpage(login_page_req, None,
  319. note='Downloading login page',
  320. errnote='Unable to download login page')
  321. lsd = self._search_regex(
  322. r'<input type="hidden" name="lsd" value="([^"]*)"',
  323. login_page, 'lsd')
  324. lgnrnd = self._search_regex(r'name="lgnrnd" value="([^"]*?)"', login_page, 'lgnrnd')
  325. login_form = {
  326. 'email': username,
  327. 'pass': password,
  328. 'lsd': lsd,
  329. 'lgnrnd': lgnrnd,
  330. 'next': 'http://facebook.com/home.php',
  331. 'default_persistent': '0',
  332. 'legacy_return': '1',
  333. 'timezone': '-60',
  334. 'trynum': '1',
  335. }
  336. request = sanitized_Request(self._LOGIN_URL, urlencode_postdata(login_form))
  337. request.add_header('Content-Type', 'application/x-www-form-urlencoded')
  338. try:
  339. login_results = self._download_webpage(request, None,
  340. note='Logging in', errnote='unable to fetch login page')
  341. if re.search(r'<form(.*)name="login"(.*)</form>', login_results) is not None:
  342. error = self._html_search_regex(
  343. r'(?s)<div[^>]+class=(["\']).*?login_error_box.*?\1[^>]*><div[^>]*>.*?</div><div[^>]*>(?P<error>.+?)</div>',
  344. login_results, 'login error', default=None, group='error')
  345. if error:
  346. raise ExtractorError('Unable to login: %s' % error, expected=True)
  347. self.report_warning('unable to log in: bad username/password, or exceeded login rate limit (~3/min). Check credentials or wait.')
  348. return
  349. fb_dtsg = self._search_regex(
  350. r'name="fb_dtsg" value="(.+?)"', login_results, 'fb_dtsg', default=None)
  351. h = self._search_regex(
  352. r'name="h"\s+(?:\w+="[^"]+"\s+)*?value="([^"]+)"', login_results, 'h', default=None)
  353. if not fb_dtsg or not h:
  354. return
  355. check_form = {
  356. 'fb_dtsg': fb_dtsg,
  357. 'h': h,
  358. 'name_action_selected': 'dont_save',
  359. }
  360. check_req = sanitized_Request(self._CHECKPOINT_URL, urlencode_postdata(check_form))
  361. check_req.add_header('Content-Type', 'application/x-www-form-urlencoded')
  362. check_response = self._download_webpage(check_req, None,
  363. note='Confirming login')
  364. if re.search(r'id="checkpointSubmitButton"', check_response) is not None:
  365. self.report_warning('Unable to confirm login, you have to login in your browser and authorize the login.')
  366. except network_exceptions as err:
  367. self.report_warning('unable to log in: %s' % error_to_compat_str(err))
  368. return
  369. def _extract_from_url(self, url, video_id):
  370. webpage = self._download_webpage(
  371. url.replace('://m.facebook.com/', '://www.facebook.com/'), video_id)
  372. def extract_metadata(webpage):
  373. post_data = [self._parse_json(j, video_id, fatal=False) for j in re.findall(
  374. r'handleWithCustomApplyEach\(\s*ScheduledApplyEach\s*,\s*(\{.+?\})\s*\);', webpage)]
  375. post = traverse_obj(post_data, (
  376. ..., 'require', ..., ..., ..., '__bbox', 'result', 'data'), expected_type=dict) or []
  377. media = traverse_obj(post, (..., 'attachments', ..., lambda k, v: (
  378. k == 'media' and str(v['id']) == video_id and v['__typename'] == 'Video')), expected_type=dict)
  379. title = get_first(media, ('title', 'text'))
  380. description = get_first(media, ('creation_story', 'comet_sections', 'message', 'story', 'message', 'text'))
  381. uploader_data = get_first(media, 'owner') or get_first(post, ('node', 'actors', ...)) or {}
  382. page_title = title or self._html_search_regex((
  383. r'<h2\s+[^>]*class="uiHeaderTitle"[^>]*>(?P<content>[^<]*)</h2>',
  384. r'(?s)<span class="fbPhotosPhotoCaption".*?id="fbPhotoPageCaption"><span class="hasCaption">(?P<content>.*?)</span>',
  385. self._meta_regex('og:title'), self._meta_regex('twitter:title'), r'<title>(?P<content>.+?)</title>'
  386. ), webpage, 'title', default=None, group='content')
  387. description = description or self._html_search_meta(
  388. ['description', 'og:description', 'twitter:description'],
  389. webpage, 'description', default=None)
  390. uploader = uploader_data.get('name') or (
  391. clean_html(get_element_by_id('fbPhotoPageAuthorName', webpage))
  392. or self._search_regex(
  393. (r'ownerName\s*:\s*"([^"]+)"', *self._og_regexes('title')), webpage, 'uploader', fatal=False))
  394. timestamp = int_or_none(self._search_regex(
  395. r'<abbr[^>]+data-utime=["\'](\d+)', webpage,
  396. 'timestamp', default=None))
  397. thumbnail = self._html_search_meta(
  398. ['og:image', 'twitter:image'], webpage, 'thumbnail', default=None)
  399. # some webpages contain unretrievable thumbnail urls
  400. # like https://lookaside.fbsbx.com/lookaside/crawler/media/?media_id=10155168902769113&get_thumbnail=1
  401. # in https://www.facebook.com/yaroslav.korpan/videos/1417995061575415/
  402. if thumbnail and not re.search(r'\.(?:jpg|png)', thumbnail):
  403. thumbnail = None
  404. view_count = parse_count(self._search_regex(
  405. r'\bviewCount\s*:\s*["\']([\d,.]+)', webpage, 'view count',
  406. default=None))
  407. info_dict = {
  408. 'description': description,
  409. 'uploader': uploader,
  410. 'uploader_id': uploader_data.get('id'),
  411. 'timestamp': timestamp,
  412. 'thumbnail': thumbnail,
  413. 'view_count': view_count,
  414. }
  415. info_json_ld = self._search_json_ld(webpage, video_id, default={})
  416. info_json_ld['title'] = (re.sub(r'\s*\|\s*Facebook$', '', title or info_json_ld.get('title') or page_title or '')
  417. or (description or '').replace('\n', ' ') or f'Facebook video #{video_id}')
  418. return merge_dicts(info_json_ld, info_dict)
  419. video_data = None
  420. def extract_video_data(instances):
  421. video_data = []
  422. for item in instances:
  423. if try_get(item, lambda x: x[1][0]) == 'VideoConfig':
  424. video_item = item[2][0]
  425. if video_item.get('video_id'):
  426. video_data.append(video_item['videoData'])
  427. return video_data
  428. server_js_data = self._parse_json(self._search_regex(
  429. [r'handleServerJS\(({.+})(?:\);|,")', r'\bs\.handle\(({.+?})\);'],
  430. webpage, 'server js data', default='{}'), video_id, fatal=False)
  431. if server_js_data:
  432. video_data = extract_video_data(server_js_data.get('instances', []))
  433. def extract_from_jsmods_instances(js_data):
  434. if js_data:
  435. return extract_video_data(try_get(
  436. js_data, lambda x: x['jsmods']['instances'], list) or [])
  437. def extract_dash_manifest(video, formats):
  438. dash_manifest = video.get('dash_manifest')
  439. if dash_manifest:
  440. formats.extend(self._parse_mpd_formats(
  441. compat_etree_fromstring(urllib.parse.unquote_plus(dash_manifest))))
  442. def process_formats(info):
  443. # Downloads with browser's User-Agent are rate limited. Working around
  444. # with non-browser User-Agent.
  445. for f in info['formats']:
  446. f.setdefault('http_headers', {})['User-Agent'] = 'facebookexternalhit/1.1'
  447. info['_format_sort_fields'] = ('res', 'quality')
  448. def extract_relay_data(_filter):
  449. return self._parse_json(self._search_regex(
  450. r'handleWithCustomApplyEach\([^,]+,\s*({.*?%s.*?})\);' % _filter,
  451. webpage, 'replay data', default='{}'), video_id, fatal=False) or {}
  452. def extract_relay_prefetched_data(_filter):
  453. replay_data = extract_relay_data(_filter)
  454. for require in (replay_data.get('require') or []):
  455. if require[0] == 'RelayPrefetchedStreamCache':
  456. return try_get(require, lambda x: x[3][1]['__bbox']['result']['data'], dict) or {}
  457. if not video_data:
  458. server_js_data = self._parse_json(self._search_regex([
  459. r'bigPipe\.onPageletArrive\(({.+?})\)\s*;\s*}\s*\)\s*,\s*["\']onPageletArrive\s+' + self._SUPPORTED_PAGLETS_REGEX,
  460. r'bigPipe\.onPageletArrive\(({.*?id\s*:\s*"%s".*?})\);' % self._SUPPORTED_PAGLETS_REGEX
  461. ], webpage, 'js data', default='{}'), video_id, js_to_json, False)
  462. video_data = extract_from_jsmods_instances(server_js_data)
  463. if not video_data:
  464. data = extract_relay_prefetched_data(
  465. r'"(?:dash_manifest|playable_url(?:_quality_hd)?)"\s*:\s*"[^"]+"')
  466. if data:
  467. entries = []
  468. def parse_graphql_video(video):
  469. formats = []
  470. q = qualities(['sd', 'hd'])
  471. for key, format_id in (('playable_url', 'sd'), ('playable_url_quality_hd', 'hd'),
  472. ('playable_url_dash', '')):
  473. playable_url = video.get(key)
  474. if not playable_url:
  475. continue
  476. if determine_ext(playable_url) == 'mpd':
  477. formats.extend(self._extract_mpd_formats(playable_url, video_id))
  478. else:
  479. formats.append({
  480. 'format_id': format_id,
  481. 'quality': q(format_id),
  482. 'url': playable_url,
  483. })
  484. extract_dash_manifest(video, formats)
  485. v_id = video.get('videoId') or video.get('id') or video_id
  486. info = {
  487. 'id': v_id,
  488. 'formats': formats,
  489. 'thumbnail': traverse_obj(
  490. video, ('thumbnailImage', 'uri'), ('preferred_thumbnail', 'image', 'uri')),
  491. 'uploader_id': try_get(video, lambda x: x['owner']['id']),
  492. 'timestamp': int_or_none(video.get('publish_time')),
  493. 'duration': float_or_none(video.get('playable_duration_in_ms'), 1000),
  494. }
  495. process_formats(info)
  496. description = try_get(video, lambda x: x['savable_description']['text'])
  497. title = video.get('name')
  498. if title:
  499. info.update({
  500. 'title': title,
  501. 'description': description,
  502. })
  503. else:
  504. info['title'] = description or 'Facebook video #%s' % v_id
  505. entries.append(info)
  506. def parse_attachment(attachment, key='media'):
  507. media = attachment.get(key) or {}
  508. if media.get('__typename') == 'Video':
  509. return parse_graphql_video(media)
  510. nodes = variadic(traverse_obj(data, 'nodes', 'node') or [])
  511. attachments = traverse_obj(nodes, (
  512. ..., 'comet_sections', 'content', 'story', (None, 'attached_story'), 'attachments',
  513. ..., ('styles', 'style_type_renderer'), 'attachment'), expected_type=dict) or []
  514. for attachment in attachments:
  515. ns = try_get(attachment, lambda x: x['all_subattachments']['nodes'], list) or []
  516. for n in ns:
  517. parse_attachment(n)
  518. parse_attachment(attachment)
  519. edges = try_get(data, lambda x: x['mediaset']['currMedia']['edges'], list) or []
  520. for edge in edges:
  521. parse_attachment(edge, key='node')
  522. video = data.get('video') or {}
  523. if video:
  524. attachments = try_get(video, [
  525. lambda x: x['story']['attachments'],
  526. lambda x: x['creation_story']['attachments']
  527. ], list) or []
  528. for attachment in attachments:
  529. parse_attachment(attachment)
  530. if not entries:
  531. parse_graphql_video(video)
  532. if len(entries) > 1:
  533. return self.playlist_result(entries, video_id)
  534. video_info = entries[0]
  535. webpage_info = extract_metadata(webpage)
  536. # honor precise duration in video info
  537. if video_info.get('duration'):
  538. webpage_info['duration'] = video_info['duration']
  539. return merge_dicts(webpage_info, video_info)
  540. if not video_data:
  541. m_msg = re.search(r'class="[^"]*uiInterstitialContent[^"]*"><div>(.*?)</div>', webpage)
  542. if m_msg is not None:
  543. raise ExtractorError(
  544. 'The video is not available, Facebook said: "%s"' % m_msg.group(1),
  545. expected=True)
  546. elif any(p in webpage for p in (
  547. '>You must log in to continue',
  548. 'id="login_form"',
  549. 'id="loginbutton"')):
  550. self.raise_login_required()
  551. if not video_data and '/watchparty/' in url:
  552. post_data = {
  553. 'doc_id': 3731964053542869,
  554. 'variables': json.dumps({
  555. 'livingRoomID': video_id,
  556. }),
  557. }
  558. prefetched_data = extract_relay_prefetched_data(r'"login_data"\s*:\s*{')
  559. if prefetched_data:
  560. lsd = try_get(prefetched_data, lambda x: x['login_data']['lsd'], dict)
  561. if lsd:
  562. post_data[lsd['name']] = lsd['value']
  563. relay_data = extract_relay_data(r'\[\s*"RelayAPIConfigDefaults"\s*,')
  564. for define in (relay_data.get('define') or []):
  565. if define[0] == 'RelayAPIConfigDefaults':
  566. self._api_config = define[2]
  567. living_room = self._download_json(
  568. urljoin(url, self._api_config['graphURI']), video_id,
  569. data=urlencode_postdata(post_data))['data']['living_room']
  570. entries = []
  571. for edge in (try_get(living_room, lambda x: x['recap']['watched_content']['edges']) or []):
  572. video = try_get(edge, lambda x: x['node']['video']) or {}
  573. v_id = video.get('id')
  574. if not v_id:
  575. continue
  576. v_id = compat_str(v_id)
  577. entries.append(self.url_result(
  578. self._VIDEO_PAGE_TEMPLATE % v_id,
  579. self.ie_key(), v_id, video.get('name')))
  580. return self.playlist_result(entries, video_id)
  581. if not video_data:
  582. # Video info not in first request, do a secondary request using
  583. # tahoe player specific URL
  584. tahoe_data = self._download_webpage(
  585. self._VIDEO_PAGE_TAHOE_TEMPLATE % video_id, video_id,
  586. data=urlencode_postdata({
  587. '__a': 1,
  588. '__pc': self._search_regex(
  589. r'pkg_cohort["\']\s*:\s*["\'](.+?)["\']', webpage,
  590. 'pkg cohort', default='PHASED:DEFAULT'),
  591. '__rev': self._search_regex(
  592. r'client_revision["\']\s*:\s*(\d+),', webpage,
  593. 'client revision', default='3944515'),
  594. 'fb_dtsg': self._search_regex(
  595. r'"DTSGInitialData"\s*,\s*\[\]\s*,\s*{\s*"token"\s*:\s*"([^"]+)"',
  596. webpage, 'dtsg token', default=''),
  597. }),
  598. headers={
  599. 'Content-Type': 'application/x-www-form-urlencoded',
  600. })
  601. tahoe_js_data = self._parse_json(
  602. self._search_regex(
  603. r'for\s+\(\s*;\s*;\s*\)\s*;(.+)', tahoe_data,
  604. 'tahoe js data', default='{}'),
  605. video_id, fatal=False)
  606. video_data = extract_from_jsmods_instances(tahoe_js_data)
  607. if not video_data:
  608. raise ExtractorError('Cannot parse data')
  609. if len(video_data) > 1:
  610. entries = []
  611. for v in video_data:
  612. video_url = v[0].get('video_url')
  613. if not video_url:
  614. continue
  615. entries.append(self.url_result(urljoin(
  616. url, video_url), self.ie_key(), v[0].get('video_id')))
  617. return self.playlist_result(entries, video_id)
  618. video_data = video_data[0]
  619. formats = []
  620. subtitles = {}
  621. for f in video_data:
  622. format_id = f['stream_type']
  623. if f and isinstance(f, dict):
  624. f = [f]
  625. if not f or not isinstance(f, list):
  626. continue
  627. for quality in ('sd', 'hd'):
  628. for src_type in ('src', 'src_no_ratelimit'):
  629. src = f[0].get('%s_%s' % (quality, src_type))
  630. if src:
  631. preference = -10 if format_id == 'progressive' else -1
  632. if quality == 'hd':
  633. preference += 5
  634. formats.append({
  635. 'format_id': '%s_%s_%s' % (format_id, quality, src_type),
  636. 'url': src,
  637. 'quality': preference,
  638. 'height': 720 if quality == 'hd' else None
  639. })
  640. extract_dash_manifest(f[0], formats)
  641. subtitles_src = f[0].get('subtitles_src')
  642. if subtitles_src:
  643. subtitles.setdefault('en', []).append({'url': subtitles_src})
  644. info_dict = {
  645. 'id': video_id,
  646. 'formats': formats,
  647. 'subtitles': subtitles,
  648. }
  649. process_formats(info_dict)
  650. info_dict.update(extract_metadata(webpage))
  651. return info_dict
  652. def _real_extract(self, url):
  653. video_id = self._match_id(url)
  654. real_url = self._VIDEO_PAGE_TEMPLATE % video_id if url.startswith('facebook:') else url
  655. return self._extract_from_url(real_url, video_id)
  656. class FacebookPluginsVideoIE(InfoExtractor):
  657. _VALID_URL = r'https?://(?:[\w-]+\.)?facebook\.com/plugins/video\.php\?.*?\bhref=(?P<id>https.+)'
  658. _TESTS = [{
  659. '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',
  660. 'md5': '5954e92cdfe51fe5782ae9bda7058a07',
  661. 'info_dict': {
  662. 'id': '10154383743583686',
  663. 'ext': 'mp4',
  664. # TODO: Fix title, uploader
  665. 'title': 'What to do during the haze?',
  666. 'uploader': 'Gov.sg',
  667. 'upload_date': '20160826',
  668. 'timestamp': 1472184808,
  669. },
  670. 'add_ie': [FacebookIE.ie_key()],
  671. }, {
  672. 'url': 'https://www.facebook.com/plugins/video.php?href=https%3A%2F%2Fwww.facebook.com%2Fvideo.php%3Fv%3D10204634152394104',
  673. 'only_matching': True,
  674. }, {
  675. 'url': 'https://www.facebook.com/plugins/video.php?href=https://www.facebook.com/gov.sg/videos/10154383743583686/&show_text=0&width=560',
  676. 'only_matching': True,
  677. }]
  678. def _real_extract(self, url):
  679. return self.url_result(
  680. compat_urllib_parse_unquote(self._match_id(url)),
  681. FacebookIE.ie_key())
  682. class FacebookRedirectURLIE(InfoExtractor):
  683. IE_DESC = False # Do not list
  684. _VALID_URL = r'https?://(?:[\w-]+\.)?facebook\.com/flx/warn[/?]'
  685. _TESTS = [{
  686. 'url': 'https://www.facebook.com/flx/warn/?h=TAQHsoToz&u=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DpO8h3EaFRdo&s=1',
  687. 'info_dict': {
  688. 'id': 'pO8h3EaFRdo',
  689. 'ext': 'mp4',
  690. 'title': 'Tripeo Boiler Room x Dekmantel Festival DJ Set',
  691. 'description': 'md5:2d713ccbb45b686a1888397b2c77ca6b',
  692. 'channel_id': 'UCGBpxWJr9FNOcFYA5GkKrMg',
  693. 'playable_in_embed': True,
  694. 'categories': ['Music'],
  695. 'channel': 'Boiler Room',
  696. 'uploader_id': 'brtvofficial',
  697. 'uploader': 'Boiler Room',
  698. 'tags': 'count:11',
  699. 'duration': 3332,
  700. 'live_status': 'not_live',
  701. 'thumbnail': 'https://i.ytimg.com/vi/pO8h3EaFRdo/maxresdefault.jpg',
  702. 'channel_url': 'https://www.youtube.com/channel/UCGBpxWJr9FNOcFYA5GkKrMg',
  703. 'availability': 'public',
  704. 'uploader_url': 'http://www.youtube.com/user/brtvofficial',
  705. 'upload_date': '20150917',
  706. 'age_limit': 0,
  707. 'view_count': int,
  708. 'like_count': int,
  709. },
  710. 'add_ie': ['Youtube'],
  711. 'params': {'skip_download': 'Youtube'},
  712. }]
  713. def _real_extract(self, url):
  714. redirect_url = url_or_none(parse_qs(url).get('u', [None])[-1])
  715. if not redirect_url:
  716. raise ExtractorError('Invalid facebook redirect URL', expected=True)
  717. return self.url_result(redirect_url)
  718. class FacebookReelIE(InfoExtractor):
  719. _VALID_URL = r'https?://(?:[\w-]+\.)?facebook\.com/reel/(?P<id>\d+)'
  720. IE_NAME = 'facebook:reel'
  721. _TESTS = [{
  722. 'url': 'https://www.facebook.com/reel/1195289147628387',
  723. 'md5': 'c4ff9a7182ff9ff7d6f7a83603bae831',
  724. 'info_dict': {
  725. 'id': '1195289147628387',
  726. 'ext': 'mp4',
  727. 'title': 'md5:9f5b142921b2dc57004fa13f76005f87',
  728. 'description': 'md5:24ea7ef062215d295bdde64e778f5474',
  729. 'uploader': 'Beast Camp Training',
  730. 'uploader_id': '1738535909799870',
  731. 'duration': 9.536,
  732. 'thumbnail': r're:^https?://.*',
  733. 'upload_date': '20211121',
  734. 'timestamp': 1637502604,
  735. }
  736. }]
  737. def _real_extract(self, url):
  738. video_id = self._match_id(url)
  739. return self.url_result(
  740. f'https://m.facebook.com/watch/?v={video_id}&_rdr', FacebookIE, video_id)