facebook.py 27 KB

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