facebook.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627
  1. # coding: utf-8
  2. from __future__ import unicode_literals
  3. import re
  4. import socket
  5. from .common import InfoExtractor
  6. from ..compat import (
  7. compat_etree_fromstring,
  8. compat_http_client,
  9. compat_urllib_error,
  10. compat_urllib_parse_unquote,
  11. compat_urllib_parse_unquote_plus,
  12. )
  13. from ..utils import (
  14. clean_html,
  15. error_to_compat_str,
  16. ExtractorError,
  17. float_or_none,
  18. get_element_by_id,
  19. int_or_none,
  20. js_to_json,
  21. limit_length,
  22. parse_count,
  23. qualities,
  24. sanitized_Request,
  25. try_get,
  26. urlencode_postdata,
  27. )
  28. class FacebookIE(InfoExtractor):
  29. _VALID_URL = r'''(?x)
  30. (?:
  31. https?://
  32. (?:[\w-]+\.)?(?:facebook\.com|facebookcorewwwi\.onion)/
  33. (?:[^#]*?\#!/)?
  34. (?:
  35. (?:
  36. video/video\.php|
  37. photo\.php|
  38. video\.php|
  39. video/embed|
  40. story\.php|
  41. watch/?
  42. )\?(?:.*?)(?:v|video_id|story_fbid)=|
  43. [^/]+/videos/(?:[^/]+/)?|
  44. [^/]+/posts/|
  45. groups/[^/]+/permalink/
  46. )|
  47. facebook:
  48. )
  49. (?P<id>[0-9]+)
  50. '''
  51. _LOGIN_URL = 'https://www.facebook.com/login.php?next=http%3A%2F%2Ffacebook.com%2Fhome.php&login_attempt=1'
  52. _CHECKPOINT_URL = 'https://www.facebook.com/checkpoint/?next=http%3A%2F%2Ffacebook.com%2Fhome.php&_fb_noscript=1'
  53. _NETRC_MACHINE = 'facebook'
  54. IE_NAME = 'facebook'
  55. _VIDEO_PAGE_TEMPLATE = 'https://www.facebook.com/video/video.php?v=%s'
  56. _VIDEO_PAGE_TAHOE_TEMPLATE = 'https://www.facebook.com/video/tahoe/async/%s/?chain=true&isvideo=true&payloadtype=primary'
  57. _TESTS = [{
  58. 'url': 'https://www.facebook.com/video.php?v=637842556329505&fref=nf',
  59. 'md5': '6a40d33c0eccbb1af76cf0485a052659',
  60. 'info_dict': {
  61. 'id': '637842556329505',
  62. 'ext': 'mp4',
  63. 'title': 're:Did you know Kei Nishikori is the first Asian man to ever reach a Grand Slam',
  64. 'uploader': 'Tennis on Facebook',
  65. 'upload_date': '20140908',
  66. 'timestamp': 1410199200,
  67. },
  68. 'skip': 'Requires logging in',
  69. }, {
  70. # data.video
  71. 'url': 'https://www.facebook.com/video.php?v=274175099429670',
  72. 'info_dict': {
  73. 'id': '274175099429670',
  74. 'ext': 'mp4',
  75. 'title': 're:^Asif Nawab Butt posted a video',
  76. 'uploader': 'Asif Nawab Butt',
  77. 'upload_date': '20140506',
  78. 'timestamp': 1399398998,
  79. 'thumbnail': r're:^https?://.*',
  80. },
  81. 'expected_warnings': [
  82. 'title'
  83. ]
  84. }, {
  85. 'note': 'Video with DASH manifest',
  86. 'url': 'https://www.facebook.com/video.php?v=957955867617029',
  87. 'md5': 'b2c28d528273b323abe5c6ab59f0f030',
  88. 'info_dict': {
  89. 'id': '957955867617029',
  90. 'ext': 'mp4',
  91. 'title': 'When you post epic content on instagram.com/433 8 million followers, this is ...',
  92. 'uploader': 'Demy de Zeeuw',
  93. 'upload_date': '20160110',
  94. 'timestamp': 1452431627,
  95. },
  96. 'skip': 'Requires logging in',
  97. }, {
  98. 'url': 'https://www.facebook.com/maxlayn/posts/10153807558977570',
  99. 'md5': '037b1fa7f3c2d02b7a0d7bc16031ecc6',
  100. 'info_dict': {
  101. 'id': '544765982287235',
  102. 'ext': 'mp4',
  103. 'title': '"What are you doing running in the snow?"',
  104. 'uploader': 'FailArmy',
  105. },
  106. 'skip': 'Video gone',
  107. }, {
  108. 'url': 'https://m.facebook.com/story.php?story_fbid=1035862816472149&id=116132035111903',
  109. 'md5': '1deb90b6ac27f7efcf6d747c8a27f5e3',
  110. 'info_dict': {
  111. 'id': '1035862816472149',
  112. 'ext': 'mp4',
  113. 'title': 'What the Flock Is Going On In New Zealand Credit: ViralHog',
  114. 'uploader': 'S. Saint',
  115. },
  116. 'skip': 'Video gone',
  117. }, {
  118. 'note': 'swf params escaped',
  119. 'url': 'https://www.facebook.com/barackobama/posts/10153664894881749',
  120. 'md5': '97ba073838964d12c70566e0085c2b91',
  121. 'info_dict': {
  122. 'id': '10153664894881749',
  123. 'ext': 'mp4',
  124. 'title': 'Average time to confirm recent Supreme Court nominees: 67 days Longest it\'s t...',
  125. 'thumbnail': r're:^https?://.*',
  126. 'timestamp': 1456259628,
  127. 'upload_date': '20160223',
  128. 'uploader': 'Barack Obama',
  129. },
  130. }, {
  131. # have 1080P, but only up to 720p in swf params
  132. # data.video.story.attachments[].media
  133. 'url': 'https://www.facebook.com/cnn/videos/10155529876156509/',
  134. 'md5': '9571fae53d4165bbbadb17a94651dcdc',
  135. 'info_dict': {
  136. 'id': '10155529876156509',
  137. 'ext': 'mp4',
  138. 'title': 'She survived the holocaust — and years later, she’s getting her citizenship s...',
  139. 'timestamp': 1477818095,
  140. 'upload_date': '20161030',
  141. 'uploader': 'CNN',
  142. 'thumbnail': r're:^https?://.*',
  143. 'view_count': int,
  144. },
  145. }, {
  146. # bigPipe.onPageletArrive ... onPageletArrive pagelet_group_mall
  147. # data.node.comet_sections.content.story.attachments[].style_type_renderer.attachment.media
  148. 'url': 'https://www.facebook.com/yaroslav.korpan/videos/1417995061575415/',
  149. 'info_dict': {
  150. 'id': '1417995061575415',
  151. 'ext': 'mp4',
  152. 'title': 'md5:1db063d6a8c13faa8da727817339c857',
  153. 'timestamp': 1486648217,
  154. 'upload_date': '20170209',
  155. 'uploader': 'Yaroslav Korpan',
  156. },
  157. 'params': {
  158. 'skip_download': True,
  159. },
  160. }, {
  161. 'url': 'https://www.facebook.com/LaGuiaDelVaron/posts/1072691702860471',
  162. 'info_dict': {
  163. 'id': '1072691702860471',
  164. 'ext': 'mp4',
  165. 'title': 'md5:ae2d22a93fbb12dad20dc393a869739d',
  166. 'timestamp': 1477305000,
  167. 'upload_date': '20161024',
  168. 'uploader': 'La Guía Del Varón',
  169. 'thumbnail': r're:^https?://.*',
  170. },
  171. 'params': {
  172. 'skip_download': True,
  173. },
  174. }, {
  175. # data.node.comet_sections.content.story.attachments[].style_type_renderer.attachment.media
  176. 'url': 'https://www.facebook.com/groups/1024490957622648/permalink/1396382447100162/',
  177. 'info_dict': {
  178. 'id': '1396382447100162',
  179. 'ext': 'mp4',
  180. 'title': 'md5:19a428bbde91364e3de815383b54a235',
  181. 'timestamp': 1486035494,
  182. 'upload_date': '20170202',
  183. 'uploader': 'Elisabeth Ahtn',
  184. },
  185. 'params': {
  186. 'skip_download': True,
  187. },
  188. }, {
  189. 'url': 'https://www.facebook.com/video.php?v=10204634152394104',
  190. 'only_matching': True,
  191. }, {
  192. 'url': 'https://www.facebook.com/amogood/videos/1618742068337349/?fref=nf',
  193. 'only_matching': True,
  194. }, {
  195. # data.mediaset.currMedia.edges
  196. 'url': 'https://www.facebook.com/ChristyClarkForBC/videos/vb.22819070941/10153870694020942/?type=2&theater',
  197. 'only_matching': True,
  198. }, {
  199. # data.video.story.attachments[].media
  200. 'url': 'facebook:544765982287235',
  201. 'only_matching': True,
  202. }, {
  203. # data.node.comet_sections.content.story.attachments[].style_type_renderer.attachment.media
  204. 'url': 'https://www.facebook.com/groups/164828000315060/permalink/764967300301124/',
  205. 'only_matching': True,
  206. }, {
  207. # data.video.creation_story.attachments[].media
  208. 'url': 'https://zh-hk.facebook.com/peoplespower/videos/1135894589806027/',
  209. 'only_matching': True,
  210. }, {
  211. # data.video
  212. 'url': 'https://www.facebookcorewwwi.onion/video.php?v=274175099429670',
  213. 'only_matching': True,
  214. }, {
  215. # no title
  216. 'url': 'https://www.facebook.com/onlycleverentertainment/videos/1947995502095005/',
  217. 'only_matching': True,
  218. }, {
  219. # data.video
  220. 'url': 'https://www.facebook.com/WatchESLOne/videos/359649331226507/',
  221. 'info_dict': {
  222. 'id': '359649331226507',
  223. 'ext': 'mp4',
  224. 'title': '#ESLOne VoD - Birmingham Finals Day#1 Fnatic vs. @Evil Geniuses',
  225. 'uploader': 'ESL One Dota 2',
  226. },
  227. 'params': {
  228. 'skip_download': True,
  229. },
  230. }, {
  231. # data.node.comet_sections.content.story.attachments[].style_type_renderer.attachment.all_subattachments.nodes[].media
  232. 'url': 'https://www.facebook.com/100033620354545/videos/106560053808006/',
  233. 'info_dict': {
  234. 'id': '106560053808006',
  235. },
  236. 'playlist_count': 2,
  237. }, {
  238. # data.video_home_www_feed.video_home_sections.edges[].node.feed_section_renderer.section.section_components.edges[].node.feed_unit.attachments
  239. 'url': 'https://www.facebook.com/watch/?v=125475412191640',
  240. 'md5': 'a38bed45dd1b2881ea230f3561c914b7',
  241. 'info_dict': {
  242. 'id': '373249263226147',
  243. 'ext': 'mp4',
  244. 'title': 'شوف بعينيك ماذا يحدث...ماناش نخوف فيكم رانا ننقل لكم مايحدث...',
  245. 'description': 'شوف بعينيك ماذا يحدث خويا العزيز...ماناش نخوف فيكم رانا ننقل لكم مايحدث...\nتذكروا جيدا ماكنا نقوله لكم منذ سنوات وماكنا نحذركم .',
  246. 'timestamp': 1550353963,
  247. 'upload_date': '20190216',
  248. 'uploader_id': '176917942440142',
  249. },
  250. 'skip': 'Requires logging in',
  251. }]
  252. @staticmethod
  253. def _extract_urls(webpage):
  254. urls = []
  255. for mobj in re.finditer(
  256. r'<iframe[^>]+?src=(["\'])(?P<url>https?://www\.facebook\.com/(?:video/embed|plugins/video\.php).+?)\1',
  257. webpage):
  258. urls.append(mobj.group('url'))
  259. # Facebook API embed
  260. # see https://developers.facebook.com/docs/plugins/embedded-video-player
  261. for mobj in re.finditer(r'''(?x)<div[^>]+
  262. class=(?P<q1>[\'"])[^\'"]*\bfb-(?:video|post)\b[^\'"]*(?P=q1)[^>]+
  263. data-href=(?P<q2>[\'"])(?P<url>(?:https?:)?//(?:www\.)?facebook.com/.+?)(?P=q2)''', webpage):
  264. urls.append(mobj.group('url'))
  265. return urls
  266. def _login(self):
  267. useremail, password = self._get_login_info()
  268. if useremail is None:
  269. return
  270. login_page_req = sanitized_Request(self._LOGIN_URL)
  271. self._set_cookie('facebook.com', 'locale', 'en_US')
  272. login_page = self._download_webpage(login_page_req, None,
  273. note='Downloading login page',
  274. errnote='Unable to download login page')
  275. lsd = self._search_regex(
  276. r'<input type="hidden" name="lsd" value="([^"]*)"',
  277. login_page, 'lsd')
  278. lgnrnd = self._search_regex(r'name="lgnrnd" value="([^"]*?)"', login_page, 'lgnrnd')
  279. login_form = {
  280. 'email': useremail,
  281. 'pass': password,
  282. 'lsd': lsd,
  283. 'lgnrnd': lgnrnd,
  284. 'next': 'http://facebook.com/home.php',
  285. 'default_persistent': '0',
  286. 'legacy_return': '1',
  287. 'timezone': '-60',
  288. 'trynum': '1',
  289. }
  290. request = sanitized_Request(self._LOGIN_URL, urlencode_postdata(login_form))
  291. request.add_header('Content-Type', 'application/x-www-form-urlencoded')
  292. try:
  293. login_results = self._download_webpage(request, None,
  294. note='Logging in', errnote='unable to fetch login page')
  295. if re.search(r'<form(.*)name="login"(.*)</form>', login_results) is not None:
  296. error = self._html_search_regex(
  297. r'(?s)<div[^>]+class=(["\']).*?login_error_box.*?\1[^>]*><div[^>]*>.*?</div><div[^>]*>(?P<error>.+?)</div>',
  298. login_results, 'login error', default=None, group='error')
  299. if error:
  300. raise ExtractorError('Unable to login: %s' % error, expected=True)
  301. self._downloader.report_warning('unable to log in: bad username/password, or exceeded login rate limit (~3/min). Check credentials or wait.')
  302. return
  303. fb_dtsg = self._search_regex(
  304. r'name="fb_dtsg" value="(.+?)"', login_results, 'fb_dtsg', default=None)
  305. h = self._search_regex(
  306. r'name="h"\s+(?:\w+="[^"]+"\s+)*?value="([^"]+)"', login_results, 'h', default=None)
  307. if not fb_dtsg or not h:
  308. return
  309. check_form = {
  310. 'fb_dtsg': fb_dtsg,
  311. 'h': h,
  312. 'name_action_selected': 'dont_save',
  313. }
  314. check_req = sanitized_Request(self._CHECKPOINT_URL, urlencode_postdata(check_form))
  315. check_req.add_header('Content-Type', 'application/x-www-form-urlencoded')
  316. check_response = self._download_webpage(check_req, None,
  317. note='Confirming login')
  318. if re.search(r'id="checkpointSubmitButton"', check_response) is not None:
  319. self._downloader.report_warning('Unable to confirm login, you have to login in your browser and authorize the login.')
  320. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  321. self._downloader.report_warning('unable to log in: %s' % error_to_compat_str(err))
  322. return
  323. def _real_initialize(self):
  324. self._login()
  325. def _extract_from_url(self, url, video_id, fatal_if_no_video=True):
  326. webpage = self._download_webpage(
  327. url.replace('://m.facebook.com/', '://www.facebook.com/'), video_id)
  328. video_data = None
  329. def extract_video_data(instances):
  330. for item in instances:
  331. if item[1][0] == 'VideoConfig':
  332. video_item = item[2][0]
  333. if video_item.get('video_id'):
  334. return video_item['videoData']
  335. server_js_data = self._parse_json(self._search_regex(
  336. r'handleServerJS\(({.+})(?:\);|,")', webpage,
  337. 'server js data', default='{}'), video_id, fatal=False)
  338. if server_js_data:
  339. video_data = extract_video_data(server_js_data.get('instances', []))
  340. def extract_from_jsmods_instances(js_data):
  341. if js_data:
  342. return extract_video_data(try_get(
  343. js_data, lambda x: x['jsmods']['instances'], list) or [])
  344. def extract_dash_manifest(video, formats):
  345. dash_manifest = video.get('dash_manifest')
  346. if dash_manifest:
  347. formats.extend(self._parse_mpd_formats(
  348. compat_etree_fromstring(compat_urllib_parse_unquote_plus(dash_manifest))))
  349. if not video_data:
  350. server_js_data = self._parse_json(self._search_regex([
  351. r'bigPipe\.onPageletArrive\(({.+?})\)\s*;\s*}\s*\)\s*,\s*["\']onPageletArrive\s+(?:pagelet_group_mall|permalink_video_pagelet|hyperfeed_story_id_\d+)',
  352. r'bigPipe\.onPageletArrive\(({.*?id\s*:\s*"permalink_video_pagelet".*?})\);'
  353. ], webpage, 'js data', default='{}'), video_id, js_to_json, False)
  354. video_data = extract_from_jsmods_instances(server_js_data)
  355. if not video_data:
  356. graphql_data = self._parse_json(self._search_regex(
  357. r'handleWithCustomApplyEach\([^,]+,\s*({.*?"(?:dash_manifest|playable_url(?:_quality_hd)?)"\s*:\s*"[^"]+".*?})\);',
  358. webpage, 'graphql data', default='{}'), video_id, fatal=False) or {}
  359. for require in (graphql_data.get('require') or []):
  360. if require[0] == 'RelayPrefetchedStreamCache':
  361. entries = []
  362. def parse_graphql_video(video):
  363. formats = []
  364. q = qualities(['sd', 'hd'])
  365. for (suffix, format_id) in [('', 'sd'), ('_quality_hd', 'hd')]:
  366. playable_url = video.get('playable_url' + suffix)
  367. if not playable_url:
  368. continue
  369. formats.append({
  370. 'format_id': format_id,
  371. 'quality': q(format_id),
  372. 'url': playable_url,
  373. })
  374. extract_dash_manifest(video, formats)
  375. self._sort_formats(formats)
  376. v_id = video.get('videoId') or video.get('id') or video_id
  377. info = {
  378. 'id': v_id,
  379. 'formats': formats,
  380. 'thumbnail': try_get(video, lambda x: x['thumbnailImage']['uri']),
  381. 'uploader_id': try_get(video, lambda x: x['owner']['id']),
  382. 'timestamp': int_or_none(video.get('publish_time')),
  383. 'duration': float_or_none(video.get('playable_duration_in_ms'), 1000),
  384. }
  385. description = try_get(video, lambda x: x['savable_description']['text'])
  386. title = video.get('name')
  387. if title:
  388. info.update({
  389. 'title': title,
  390. 'description': description,
  391. })
  392. else:
  393. info['title'] = description or 'Facebook video #%s' % v_id
  394. entries.append(info)
  395. def parse_attachment(attachment, key='media'):
  396. media = attachment.get(key) or {}
  397. if media.get('__typename') == 'Video':
  398. return parse_graphql_video(media)
  399. data = try_get(require, lambda x: x[3][1]['__bbox']['result']['data'], dict) or {}
  400. attachments = try_get(data, [
  401. lambda x: x['video']['story']['attachments'],
  402. lambda x: x['video']['creation_story']['attachments'],
  403. lambda x: x['node']['comet_sections']['content']['story']['attachments']
  404. ], list) or []
  405. for attachment in attachments:
  406. attachment = try_get(attachment, lambda x: x['style_type_renderer']['attachment'], dict) or attachment
  407. nodes = try_get(attachment, lambda x: x['all_subattachments']['nodes'], list) or []
  408. for node in nodes:
  409. parse_attachment(node)
  410. parse_attachment(attachment)
  411. edges = try_get(data, lambda x: x['mediaset']['currMedia']['edges'], list) or []
  412. for edge in edges:
  413. parse_attachment(edge, key='node')
  414. video_home_sections = try_get(data, lambda x: x['video_home_www_feed']['video_home_sections']['edges'], list) or []
  415. for video_home_section in video_home_sections:
  416. section_components = try_get(video_home_section, lambda x: x['node']['feed_section_renderer']['section']['section_components']['edges'], list) or []
  417. for section_component in section_components:
  418. attachments = try_get(section_component, lambda x: x['node']['feed_unit']['attachments'], list) or []
  419. for attachment in attachments:
  420. parse_attachment(attachment)
  421. if not entries:
  422. video = data.get('video') or {}
  423. if video:
  424. parse_graphql_video(video)
  425. return webpage, self.playlist_result(entries, video_id)
  426. if not video_data:
  427. if not fatal_if_no_video:
  428. return webpage, False
  429. m_msg = re.search(r'class="[^"]*uiInterstitialContent[^"]*"><div>(.*?)</div>', webpage)
  430. if m_msg is not None:
  431. raise ExtractorError(
  432. 'The video is not available, Facebook said: "%s"' % m_msg.group(1),
  433. expected=True)
  434. elif '>You must log in to continue' in webpage:
  435. self.raise_login_required()
  436. # Video info not in first request, do a secondary request using
  437. # tahoe player specific URL
  438. tahoe_data = self._download_webpage(
  439. self._VIDEO_PAGE_TAHOE_TEMPLATE % video_id, video_id,
  440. data=urlencode_postdata({
  441. '__a': 1,
  442. '__pc': self._search_regex(
  443. r'pkg_cohort["\']\s*:\s*["\'](.+?)["\']', webpage,
  444. 'pkg cohort', default='PHASED:DEFAULT'),
  445. '__rev': self._search_regex(
  446. r'client_revision["\']\s*:\s*(\d+),', webpage,
  447. 'client revision', default='3944515'),
  448. 'fb_dtsg': self._search_regex(
  449. r'"DTSGInitialData"\s*,\s*\[\]\s*,\s*{\s*"token"\s*:\s*"([^"]+)"',
  450. webpage, 'dtsg token', default=''),
  451. }),
  452. headers={
  453. 'Content-Type': 'application/x-www-form-urlencoded',
  454. })
  455. tahoe_js_data = self._parse_json(
  456. self._search_regex(
  457. r'for\s+\(\s*;\s*;\s*\)\s*;(.+)', tahoe_data,
  458. 'tahoe js data', default='{}'),
  459. video_id, fatal=False)
  460. video_data = extract_from_jsmods_instances(tahoe_js_data)
  461. if not video_data:
  462. raise ExtractorError('Cannot parse data')
  463. formats = []
  464. subtitles = {}
  465. for f in video_data:
  466. format_id = f['stream_type']
  467. if f and isinstance(f, dict):
  468. f = [f]
  469. if not f or not isinstance(f, list):
  470. continue
  471. for quality in ('sd', 'hd'):
  472. for src_type in ('src', 'src_no_ratelimit'):
  473. src = f[0].get('%s_%s' % (quality, src_type))
  474. if src:
  475. preference = -10 if format_id == 'progressive' else 0
  476. if quality == 'hd':
  477. preference += 5
  478. formats.append({
  479. 'format_id': '%s_%s_%s' % (format_id, quality, src_type),
  480. 'url': src,
  481. 'preference': preference,
  482. })
  483. extract_dash_manifest(f[0], formats)
  484. subtitles_src = f[0].get('subtitles_src')
  485. if subtitles_src:
  486. subtitles.setdefault('en', []).append({'url': subtitles_src})
  487. if not formats:
  488. raise ExtractorError('Cannot find video formats')
  489. # Downloads with browser's User-Agent are rate limited. Working around
  490. # with non-browser User-Agent.
  491. for f in formats:
  492. f.setdefault('http_headers', {})['User-Agent'] = 'facebookexternalhit/1.1'
  493. self._sort_formats(formats)
  494. video_title = self._html_search_regex(
  495. r'<h2\s+[^>]*class="uiHeaderTitle"[^>]*>([^<]*)</h2>', webpage,
  496. 'title', default=None)
  497. if not video_title:
  498. video_title = self._html_search_regex(
  499. r'(?s)<span class="fbPhotosPhotoCaption".*?id="fbPhotoPageCaption"><span class="hasCaption">(.*?)</span>',
  500. webpage, 'alternative title', default=None)
  501. if not video_title:
  502. video_title = self._html_search_meta(
  503. 'description', webpage, 'title', default=None)
  504. if video_title:
  505. video_title = limit_length(video_title, 80)
  506. else:
  507. video_title = 'Facebook video #%s' % video_id
  508. uploader = clean_html(get_element_by_id(
  509. 'fbPhotoPageAuthorName', webpage)) or self._search_regex(
  510. r'ownerName\s*:\s*"([^"]+)"', webpage, 'uploader',
  511. default=None) or self._og_search_title(webpage, fatal=False)
  512. timestamp = int_or_none(self._search_regex(
  513. r'<abbr[^>]+data-utime=["\'](\d+)', webpage,
  514. 'timestamp', default=None))
  515. thumbnail = self._html_search_meta(['og:image', 'twitter:image'], webpage)
  516. view_count = parse_count(self._search_regex(
  517. r'\bviewCount\s*:\s*["\']([\d,.]+)', webpage, 'view count',
  518. default=None))
  519. info_dict = {
  520. 'id': video_id,
  521. 'title': video_title,
  522. 'formats': formats,
  523. 'uploader': uploader,
  524. 'timestamp': timestamp,
  525. 'thumbnail': thumbnail,
  526. 'view_count': view_count,
  527. 'subtitles': subtitles,
  528. }
  529. return webpage, info_dict
  530. def _real_extract(self, url):
  531. video_id = self._match_id(url)
  532. real_url = self._VIDEO_PAGE_TEMPLATE % video_id if url.startswith('facebook:') else url
  533. webpage, info_dict = self._extract_from_url(real_url, video_id, fatal_if_no_video=False)
  534. if info_dict:
  535. return info_dict
  536. if '/posts/' in url:
  537. video_id_json = self._search_regex(
  538. r'(["\'])video_ids\1\s*:\s*(?P<ids>\[.+?\])', webpage, 'video ids', group='ids',
  539. default='')
  540. if video_id_json:
  541. entries = [
  542. self.url_result('facebook:%s' % vid, FacebookIE.ie_key())
  543. for vid in self._parse_json(video_id_json, video_id)]
  544. return self.playlist_result(entries, video_id)
  545. # Single Video?
  546. video_id = self._search_regex(r'video_id:\s*"([0-9]+)"', webpage, 'single video id')
  547. return self.url_result('facebook:%s' % video_id, FacebookIE.ie_key())
  548. else:
  549. _, info_dict = self._extract_from_url(
  550. self._VIDEO_PAGE_TEMPLATE % video_id,
  551. video_id, fatal_if_no_video=True)
  552. return info_dict
  553. class FacebookPluginsVideoIE(InfoExtractor):
  554. _VALID_URL = r'https?://(?:[\w-]+\.)?facebook\.com/plugins/video\.php\?.*?\bhref=(?P<id>https.+)'
  555. _TESTS = [{
  556. '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',
  557. 'md5': '5954e92cdfe51fe5782ae9bda7058a07',
  558. 'info_dict': {
  559. 'id': '10154383743583686',
  560. 'ext': 'mp4',
  561. 'title': 'What to do during the haze?',
  562. 'uploader': 'Gov.sg',
  563. 'upload_date': '20160826',
  564. 'timestamp': 1472184808,
  565. },
  566. 'add_ie': [FacebookIE.ie_key()],
  567. }, {
  568. 'url': 'https://www.facebook.com/plugins/video.php?href=https%3A%2F%2Fwww.facebook.com%2Fvideo.php%3Fv%3D10204634152394104',
  569. 'only_matching': True,
  570. }, {
  571. 'url': 'https://www.facebook.com/plugins/video.php?href=https://www.facebook.com/gov.sg/videos/10154383743583686/&show_text=0&width=560',
  572. 'only_matching': True,
  573. }]
  574. def _real_extract(self, url):
  575. return self.url_result(
  576. compat_urllib_parse_unquote(self._match_id(url)),
  577. FacebookIE.ie_key())