facebook.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609
  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.story.attachments[].media
  239. 'url': 'https://www.facebook.com/watch/?v=647537299265662',
  240. 'only_matching': True,
  241. }]
  242. @staticmethod
  243. def _extract_urls(webpage):
  244. urls = []
  245. for mobj in re.finditer(
  246. r'<iframe[^>]+?src=(["\'])(?P<url>https?://www\.facebook\.com/(?:video/embed|plugins/video\.php).+?)\1',
  247. webpage):
  248. urls.append(mobj.group('url'))
  249. # Facebook API embed
  250. # see https://developers.facebook.com/docs/plugins/embedded-video-player
  251. for mobj in re.finditer(r'''(?x)<div[^>]+
  252. class=(?P<q1>[\'"])[^\'"]*\bfb-(?:video|post)\b[^\'"]*(?P=q1)[^>]+
  253. data-href=(?P<q2>[\'"])(?P<url>(?:https?:)?//(?:www\.)?facebook.com/.+?)(?P=q2)''', webpage):
  254. urls.append(mobj.group('url'))
  255. return urls
  256. def _login(self):
  257. useremail, password = self._get_login_info()
  258. if useremail is None:
  259. return
  260. login_page_req = sanitized_Request(self._LOGIN_URL)
  261. self._set_cookie('facebook.com', 'locale', 'en_US')
  262. login_page = self._download_webpage(login_page_req, None,
  263. note='Downloading login page',
  264. errnote='Unable to download login page')
  265. lsd = self._search_regex(
  266. r'<input type="hidden" name="lsd" value="([^"]*)"',
  267. login_page, 'lsd')
  268. lgnrnd = self._search_regex(r'name="lgnrnd" value="([^"]*?)"', login_page, 'lgnrnd')
  269. login_form = {
  270. 'email': useremail,
  271. 'pass': password,
  272. 'lsd': lsd,
  273. 'lgnrnd': lgnrnd,
  274. 'next': 'http://facebook.com/home.php',
  275. 'default_persistent': '0',
  276. 'legacy_return': '1',
  277. 'timezone': '-60',
  278. 'trynum': '1',
  279. }
  280. request = sanitized_Request(self._LOGIN_URL, urlencode_postdata(login_form))
  281. request.add_header('Content-Type', 'application/x-www-form-urlencoded')
  282. try:
  283. login_results = self._download_webpage(request, None,
  284. note='Logging in', errnote='unable to fetch login page')
  285. if re.search(r'<form(.*)name="login"(.*)</form>', login_results) is not None:
  286. error = self._html_search_regex(
  287. r'(?s)<div[^>]+class=(["\']).*?login_error_box.*?\1[^>]*><div[^>]*>.*?</div><div[^>]*>(?P<error>.+?)</div>',
  288. login_results, 'login error', default=None, group='error')
  289. if error:
  290. raise ExtractorError('Unable to login: %s' % error, expected=True)
  291. self._downloader.report_warning('unable to log in: bad username/password, or exceeded login rate limit (~3/min). Check credentials or wait.')
  292. return
  293. fb_dtsg = self._search_regex(
  294. r'name="fb_dtsg" value="(.+?)"', login_results, 'fb_dtsg', default=None)
  295. h = self._search_regex(
  296. r'name="h"\s+(?:\w+="[^"]+"\s+)*?value="([^"]+)"', login_results, 'h', default=None)
  297. if not fb_dtsg or not h:
  298. return
  299. check_form = {
  300. 'fb_dtsg': fb_dtsg,
  301. 'h': h,
  302. 'name_action_selected': 'dont_save',
  303. }
  304. check_req = sanitized_Request(self._CHECKPOINT_URL, urlencode_postdata(check_form))
  305. check_req.add_header('Content-Type', 'application/x-www-form-urlencoded')
  306. check_response = self._download_webpage(check_req, None,
  307. note='Confirming login')
  308. if re.search(r'id="checkpointSubmitButton"', check_response) is not None:
  309. self._downloader.report_warning('Unable to confirm login, you have to login in your browser and authorize the login.')
  310. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  311. self._downloader.report_warning('unable to log in: %s' % error_to_compat_str(err))
  312. return
  313. def _real_initialize(self):
  314. self._login()
  315. def _extract_from_url(self, url, video_id, fatal_if_no_video=True):
  316. webpage = self._download_webpage(
  317. url.replace('://m.facebook.com/', '://www.facebook.com/'), video_id)
  318. video_data = None
  319. def extract_video_data(instances):
  320. for item in instances:
  321. if item[1][0] == 'VideoConfig':
  322. video_item = item[2][0]
  323. if video_item.get('video_id'):
  324. return video_item['videoData']
  325. server_js_data = self._parse_json(self._search_regex(
  326. r'handleServerJS\(({.+})(?:\);|,")', webpage,
  327. 'server js data', default='{}'), video_id, fatal=False)
  328. if server_js_data:
  329. video_data = extract_video_data(server_js_data.get('instances', []))
  330. def extract_from_jsmods_instances(js_data):
  331. if js_data:
  332. return extract_video_data(try_get(
  333. js_data, lambda x: x['jsmods']['instances'], list) or [])
  334. def extract_dash_manifest(video, formats):
  335. dash_manifest = video.get('dash_manifest')
  336. if dash_manifest:
  337. formats.extend(self._parse_mpd_formats(
  338. compat_etree_fromstring(compat_urllib_parse_unquote_plus(dash_manifest))))
  339. if not video_data:
  340. server_js_data = self._parse_json(self._search_regex([
  341. r'bigPipe\.onPageletArrive\(({.+?})\)\s*;\s*}\s*\)\s*,\s*["\']onPageletArrive\s+(?:pagelet_group_mall|permalink_video_pagelet|hyperfeed_story_id_\d+)',
  342. r'bigPipe\.onPageletArrive\(({.*?id\s*:\s*"permalink_video_pagelet".*?})\);'
  343. ], webpage, 'js data', default='{}'), video_id, js_to_json, False)
  344. video_data = extract_from_jsmods_instances(server_js_data)
  345. if not video_data:
  346. graphql_data = self._parse_json(self._search_regex(
  347. r'handleWithCustomApplyEach\([^,]+,\s*({.*?"(?:dash_manifest|playable_url(?:_quality_hd)?)"\s*:\s*"[^"]+".*?})\);',
  348. webpage, 'graphql data', default='{}'), video_id, fatal=False) or {}
  349. for require in (graphql_data.get('require') or []):
  350. if require[0] == 'RelayPrefetchedStreamCache':
  351. entries = []
  352. def parse_graphql_video(video):
  353. formats = []
  354. q = qualities(['sd', 'hd'])
  355. for (suffix, format_id) in [('', 'sd'), ('_quality_hd', 'hd')]:
  356. playable_url = video.get('playable_url' + suffix)
  357. if not playable_url:
  358. continue
  359. formats.append({
  360. 'format_id': format_id,
  361. 'quality': q(format_id),
  362. 'url': playable_url,
  363. })
  364. extract_dash_manifest(video, formats)
  365. self._sort_formats(formats)
  366. v_id = video.get('videoId') or video.get('id') or video_id
  367. info = {
  368. 'id': v_id,
  369. 'formats': formats,
  370. 'thumbnail': try_get(video, lambda x: x['thumbnailImage']['uri']),
  371. 'uploader_id': try_get(video, lambda x: x['owner']['id']),
  372. 'timestamp': int_or_none(video.get('publish_time')),
  373. 'duration': float_or_none(video.get('playable_duration_in_ms'), 1000),
  374. }
  375. description = try_get(video, lambda x: x['savable_description']['text'])
  376. title = video.get('name')
  377. if title:
  378. info.update({
  379. 'title': title,
  380. 'description': description,
  381. })
  382. else:
  383. info['title'] = description or 'Facebook video #%s' % v_id
  384. entries.append(info)
  385. def parse_attachment(attachment, key='media'):
  386. media = attachment.get(key) or {}
  387. if media.get('__typename') == 'Video':
  388. return parse_graphql_video(media)
  389. data = try_get(require, lambda x: x[3][1]['__bbox']['result']['data'], dict) or {}
  390. attachments = try_get(data, [
  391. lambda x: x['video']['story']['attachments'],
  392. lambda x: x['video']['creation_story']['attachments'],
  393. lambda x: x['node']['comet_sections']['content']['story']['attachments']
  394. ], list) or []
  395. for attachment in attachments:
  396. attachment = try_get(attachment, lambda x: x['style_type_renderer']['attachment'], dict) or attachment
  397. nodes = try_get(attachment, lambda x: x['all_subattachments']['nodes'], list) or []
  398. for node in nodes:
  399. parse_attachment(node)
  400. parse_attachment(attachment)
  401. edges = try_get(data, lambda x: x['mediaset']['currMedia']['edges'], list) or []
  402. for edge in edges:
  403. parse_attachment(edge, key='node')
  404. if not entries:
  405. video = data.get('video') or {}
  406. if video:
  407. parse_graphql_video(video)
  408. return webpage, self.playlist_result(entries, video_id)
  409. if not video_data:
  410. if not fatal_if_no_video:
  411. return webpage, False
  412. m_msg = re.search(r'class="[^"]*uiInterstitialContent[^"]*"><div>(.*?)</div>', webpage)
  413. if m_msg is not None:
  414. raise ExtractorError(
  415. 'The video is not available, Facebook said: "%s"' % m_msg.group(1),
  416. expected=True)
  417. elif '>You must log in to continue' in webpage:
  418. self.raise_login_required()
  419. # Video info not in first request, do a secondary request using
  420. # tahoe player specific URL
  421. tahoe_data = self._download_webpage(
  422. self._VIDEO_PAGE_TAHOE_TEMPLATE % video_id, video_id,
  423. data=urlencode_postdata({
  424. '__a': 1,
  425. '__pc': self._search_regex(
  426. r'pkg_cohort["\']\s*:\s*["\'](.+?)["\']', webpage,
  427. 'pkg cohort', default='PHASED:DEFAULT'),
  428. '__rev': self._search_regex(
  429. r'client_revision["\']\s*:\s*(\d+),', webpage,
  430. 'client revision', default='3944515'),
  431. 'fb_dtsg': self._search_regex(
  432. r'"DTSGInitialData"\s*,\s*\[\]\s*,\s*{\s*"token"\s*:\s*"([^"]+)"',
  433. webpage, 'dtsg token', default=''),
  434. }),
  435. headers={
  436. 'Content-Type': 'application/x-www-form-urlencoded',
  437. })
  438. tahoe_js_data = self._parse_json(
  439. self._search_regex(
  440. r'for\s+\(\s*;\s*;\s*\)\s*;(.+)', tahoe_data,
  441. 'tahoe js data', default='{}'),
  442. video_id, fatal=False)
  443. video_data = extract_from_jsmods_instances(tahoe_js_data)
  444. if not video_data:
  445. raise ExtractorError('Cannot parse data')
  446. formats = []
  447. subtitles = {}
  448. for f in video_data:
  449. format_id = f['stream_type']
  450. if f and isinstance(f, dict):
  451. f = [f]
  452. if not f or not isinstance(f, list):
  453. continue
  454. for quality in ('sd', 'hd'):
  455. for src_type in ('src', 'src_no_ratelimit'):
  456. src = f[0].get('%s_%s' % (quality, src_type))
  457. if src:
  458. preference = -10 if format_id == 'progressive' else 0
  459. if quality == 'hd':
  460. preference += 5
  461. formats.append({
  462. 'format_id': '%s_%s_%s' % (format_id, quality, src_type),
  463. 'url': src,
  464. 'preference': preference,
  465. })
  466. extract_dash_manifest(f[0], formats)
  467. subtitles_src = f[0].get('subtitles_src')
  468. if subtitles_src:
  469. subtitles.setdefault('en', []).append({'url': subtitles_src})
  470. if not formats:
  471. raise ExtractorError('Cannot find video formats')
  472. # Downloads with browser's User-Agent are rate limited. Working around
  473. # with non-browser User-Agent.
  474. for f in formats:
  475. f.setdefault('http_headers', {})['User-Agent'] = 'facebookexternalhit/1.1'
  476. self._sort_formats(formats)
  477. video_title = self._html_search_regex(
  478. r'<h2\s+[^>]*class="uiHeaderTitle"[^>]*>([^<]*)</h2>', webpage,
  479. 'title', default=None)
  480. if not video_title:
  481. video_title = self._html_search_regex(
  482. r'(?s)<span class="fbPhotosPhotoCaption".*?id="fbPhotoPageCaption"><span class="hasCaption">(.*?)</span>',
  483. webpage, 'alternative title', default=None)
  484. if not video_title:
  485. video_title = self._html_search_meta(
  486. 'description', webpage, 'title', default=None)
  487. if video_title:
  488. video_title = limit_length(video_title, 80)
  489. else:
  490. video_title = 'Facebook video #%s' % video_id
  491. uploader = clean_html(get_element_by_id(
  492. 'fbPhotoPageAuthorName', webpage)) or self._search_regex(
  493. r'ownerName\s*:\s*"([^"]+)"', webpage, 'uploader',
  494. default=None) or self._og_search_title(webpage, fatal=False)
  495. timestamp = int_or_none(self._search_regex(
  496. r'<abbr[^>]+data-utime=["\'](\d+)', webpage,
  497. 'timestamp', default=None))
  498. thumbnail = self._html_search_meta(['og:image', 'twitter:image'], webpage)
  499. view_count = parse_count(self._search_regex(
  500. r'\bviewCount\s*:\s*["\']([\d,.]+)', webpage, 'view count',
  501. default=None))
  502. info_dict = {
  503. 'id': video_id,
  504. 'title': video_title,
  505. 'formats': formats,
  506. 'uploader': uploader,
  507. 'timestamp': timestamp,
  508. 'thumbnail': thumbnail,
  509. 'view_count': view_count,
  510. 'subtitles': subtitles,
  511. }
  512. return webpage, info_dict
  513. def _real_extract(self, url):
  514. video_id = self._match_id(url)
  515. real_url = self._VIDEO_PAGE_TEMPLATE % video_id if url.startswith('facebook:') else url
  516. webpage, info_dict = self._extract_from_url(real_url, video_id, fatal_if_no_video=False)
  517. if info_dict:
  518. return info_dict
  519. if '/posts/' in url:
  520. video_id_json = self._search_regex(
  521. r'(["\'])video_ids\1\s*:\s*(?P<ids>\[.+?\])', webpage, 'video ids', group='ids',
  522. default='')
  523. if video_id_json:
  524. entries = [
  525. self.url_result('facebook:%s' % vid, FacebookIE.ie_key())
  526. for vid in self._parse_json(video_id_json, video_id)]
  527. return self.playlist_result(entries, video_id)
  528. # Single Video?
  529. video_id = self._search_regex(r'video_id:\s*"([0-9]+)"', webpage, 'single video id')
  530. return self.url_result('facebook:%s' % video_id, FacebookIE.ie_key())
  531. else:
  532. _, info_dict = self._extract_from_url(
  533. self._VIDEO_PAGE_TEMPLATE % video_id,
  534. video_id, fatal_if_no_video=True)
  535. return info_dict
  536. class FacebookPluginsVideoIE(InfoExtractor):
  537. _VALID_URL = r'https?://(?:[\w-]+\.)?facebook\.com/plugins/video\.php\?.*?\bhref=(?P<id>https.+)'
  538. _TESTS = [{
  539. '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',
  540. 'md5': '5954e92cdfe51fe5782ae9bda7058a07',
  541. 'info_dict': {
  542. 'id': '10154383743583686',
  543. 'ext': 'mp4',
  544. 'title': 'What to do during the haze?',
  545. 'uploader': 'Gov.sg',
  546. 'upload_date': '20160826',
  547. 'timestamp': 1472184808,
  548. },
  549. 'add_ie': [FacebookIE.ie_key()],
  550. }, {
  551. 'url': 'https://www.facebook.com/plugins/video.php?href=https%3A%2F%2Fwww.facebook.com%2Fvideo.php%3Fv%3D10204634152394104',
  552. 'only_matching': True,
  553. }, {
  554. 'url': 'https://www.facebook.com/plugins/video.php?href=https://www.facebook.com/gov.sg/videos/10154383743583686/&show_text=0&width=560',
  555. 'only_matching': True,
  556. }]
  557. def _real_extract(self, url):
  558. return self.url_result(
  559. compat_urllib_parse_unquote(self._match_id(url)),
  560. FacebookIE.ie_key())