facebook.py 26 KB

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