facebook.py 21 KB

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