facebook.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  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. sanitized_Request,
  22. try_get,
  23. urlencode_postdata,
  24. )
  25. class FacebookIE(InfoExtractor):
  26. _VALID_URL = r'''(?x)
  27. (?:
  28. https?://
  29. (?:[\w-]+\.)?(?:facebook\.com|facebookcorewwwi\.onion)/
  30. (?:[^#]*?\#!/)?
  31. (?:
  32. (?:
  33. video/video\.php|
  34. photo\.php|
  35. video\.php|
  36. video/embed|
  37. story\.php
  38. )\?(?:.*?)(?:v|video_id|story_fbid)=|
  39. [^/]+/videos/(?:[^/]+/)?|
  40. [^/]+/posts/|
  41. groups/[^/]+/permalink/
  42. )|
  43. facebook:
  44. )
  45. (?P<id>[0-9]+)
  46. '''
  47. _LOGIN_URL = 'https://www.facebook.com/login.php?next=http%3A%2F%2Ffacebook.com%2Fhome.php&login_attempt=1'
  48. _CHECKPOINT_URL = 'https://www.facebook.com/checkpoint/?next=http%3A%2F%2Ffacebook.com%2Fhome.php&_fb_noscript=1'
  49. _NETRC_MACHINE = 'facebook'
  50. IE_NAME = 'facebook'
  51. _CHROME_USER_AGENT = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.97 Safari/537.36'
  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'
  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': 'Asif Nawab Butt posted a video to his Timeline.',
  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': '0d9813160b146b3bc8744e006027fcc6',
  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. },
  139. }, {
  140. # bigPipe.onPageletArrive ... onPageletArrive pagelet_group_mall
  141. 'url': 'https://www.facebook.com/yaroslav.korpan/videos/1417995061575415/',
  142. 'info_dict': {
  143. 'id': '1417995061575415',
  144. 'ext': 'mp4',
  145. 'title': 'md5:a7b86ca673f51800cd54687b7f4012fe',
  146. 'timestamp': 1486648217,
  147. 'upload_date': '20170209',
  148. 'uploader': 'Yaroslav Korpan',
  149. },
  150. 'params': {
  151. 'skip_download': True,
  152. },
  153. }, {
  154. 'url': 'https://www.facebook.com/LaGuiaDelVaron/posts/1072691702860471',
  155. 'info_dict': {
  156. 'id': '1072691702860471',
  157. 'ext': 'mp4',
  158. 'title': 'md5:ae2d22a93fbb12dad20dc393a869739d',
  159. 'timestamp': 1477305000,
  160. 'upload_date': '20161024',
  161. 'uploader': 'La Guía Del Varón',
  162. 'thumbnail': r're:^https?://.*',
  163. },
  164. 'params': {
  165. 'skip_download': True,
  166. },
  167. }, {
  168. 'url': 'https://www.facebook.com/groups/1024490957622648/permalink/1396382447100162/',
  169. 'info_dict': {
  170. 'id': '1396382447100162',
  171. 'ext': 'mp4',
  172. 'title': 'md5:e2d2700afdf84e121f5d0f999bad13a3',
  173. 'timestamp': 1486035494,
  174. 'upload_date': '20170202',
  175. 'uploader': 'Elisabeth Ahtn',
  176. },
  177. 'params': {
  178. 'skip_download': True,
  179. },
  180. }, {
  181. 'url': 'https://www.facebook.com/video.php?v=10204634152394104',
  182. 'only_matching': True,
  183. }, {
  184. 'url': 'https://www.facebook.com/amogood/videos/1618742068337349/?fref=nf',
  185. 'only_matching': True,
  186. }, {
  187. 'url': 'https://www.facebook.com/ChristyClarkForBC/videos/vb.22819070941/10153870694020942/?type=2&theater',
  188. 'only_matching': True,
  189. }, {
  190. 'url': 'facebook:544765982287235',
  191. 'only_matching': True,
  192. }, {
  193. 'url': 'https://www.facebook.com/groups/164828000315060/permalink/764967300301124/',
  194. 'only_matching': True,
  195. }, {
  196. 'url': 'https://zh-hk.facebook.com/peoplespower/videos/1135894589806027/',
  197. 'only_matching': True,
  198. }, {
  199. 'url': 'https://www.facebookcorewwwi.onion/video.php?v=274175099429670',
  200. 'only_matching': True,
  201. }, {
  202. # no title
  203. 'url': 'https://www.facebook.com/onlycleverentertainment/videos/1947995502095005/',
  204. 'only_matching': True,
  205. }, {
  206. 'url': 'https://www.facebook.com/WatchESLOne/videos/359649331226507/',
  207. 'info_dict': {
  208. 'id': '359649331226507',
  209. 'ext': 'mp4',
  210. 'title': '#ESLOne VoD - Birmingham Finals Day#1 Fnatic vs. @Evil Geniuses',
  211. 'uploader': 'ESL One Dota 2',
  212. },
  213. 'params': {
  214. 'skip_download': True,
  215. },
  216. }]
  217. @staticmethod
  218. def _extract_urls(webpage):
  219. urls = []
  220. for mobj in re.finditer(
  221. r'<iframe[^>]+?src=(["\'])(?P<url>https?://www\.facebook\.com/(?:video/embed|plugins/video\.php).+?)\1',
  222. webpage):
  223. urls.append(mobj.group('url'))
  224. # Facebook API embed
  225. # see https://developers.facebook.com/docs/plugins/embedded-video-player
  226. for mobj in re.finditer(r'''(?x)<div[^>]+
  227. class=(?P<q1>[\'"])[^\'"]*\bfb-(?:video|post)\b[^\'"]*(?P=q1)[^>]+
  228. data-href=(?P<q2>[\'"])(?P<url>(?:https?:)?//(?:www\.)?facebook.com/.+?)(?P=q2)''', webpage):
  229. urls.append(mobj.group('url'))
  230. return urls
  231. def _login(self):
  232. useremail, password = self._get_login_info()
  233. if useremail is None:
  234. return
  235. login_page_req = sanitized_Request(self._LOGIN_URL)
  236. self._set_cookie('facebook.com', 'locale', 'en_US')
  237. login_page = self._download_webpage(login_page_req, None,
  238. note='Downloading login page',
  239. errnote='Unable to download login page')
  240. lsd = self._search_regex(
  241. r'<input type="hidden" name="lsd" value="([^"]*)"',
  242. login_page, 'lsd')
  243. lgnrnd = self._search_regex(r'name="lgnrnd" value="([^"]*?)"', login_page, 'lgnrnd')
  244. login_form = {
  245. 'email': useremail,
  246. 'pass': password,
  247. 'lsd': lsd,
  248. 'lgnrnd': lgnrnd,
  249. 'next': 'http://facebook.com/home.php',
  250. 'default_persistent': '0',
  251. 'legacy_return': '1',
  252. 'timezone': '-60',
  253. 'trynum': '1',
  254. }
  255. request = sanitized_Request(self._LOGIN_URL, urlencode_postdata(login_form))
  256. request.add_header('Content-Type', 'application/x-www-form-urlencoded')
  257. try:
  258. login_results = self._download_webpage(request, None,
  259. note='Logging in', errnote='unable to fetch login page')
  260. if re.search(r'<form(.*)name="login"(.*)</form>', login_results) is not None:
  261. error = self._html_search_regex(
  262. r'(?s)<div[^>]+class=(["\']).*?login_error_box.*?\1[^>]*><div[^>]*>.*?</div><div[^>]*>(?P<error>.+?)</div>',
  263. login_results, 'login error', default=None, group='error')
  264. if error:
  265. raise ExtractorError('Unable to login: %s' % error, expected=True)
  266. self._downloader.report_warning('unable to log in: bad username/password, or exceeded login rate limit (~3/min). Check credentials or wait.')
  267. return
  268. fb_dtsg = self._search_regex(
  269. r'name="fb_dtsg" value="(.+?)"', login_results, 'fb_dtsg', default=None)
  270. h = self._search_regex(
  271. r'name="h"\s+(?:\w+="[^"]+"\s+)*?value="([^"]+)"', login_results, 'h', default=None)
  272. if not fb_dtsg or not h:
  273. return
  274. check_form = {
  275. 'fb_dtsg': fb_dtsg,
  276. 'h': h,
  277. 'name_action_selected': 'dont_save',
  278. }
  279. check_req = sanitized_Request(self._CHECKPOINT_URL, urlencode_postdata(check_form))
  280. check_req.add_header('Content-Type', 'application/x-www-form-urlencoded')
  281. check_response = self._download_webpage(check_req, None,
  282. note='Confirming login')
  283. if re.search(r'id="checkpointSubmitButton"', check_response) is not None:
  284. self._downloader.report_warning('Unable to confirm login, you have to login in your browser and authorize the login.')
  285. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  286. self._downloader.report_warning('unable to log in: %s' % error_to_compat_str(err))
  287. return
  288. def _real_initialize(self):
  289. self._login()
  290. def _extract_from_url(self, url, video_id, fatal_if_no_video=True):
  291. req = sanitized_Request(url)
  292. req.add_header('User-Agent', self._CHROME_USER_AGENT)
  293. webpage = self._download_webpage(req, video_id)
  294. video_data = None
  295. def extract_video_data(instances):
  296. for item in instances:
  297. if item[1][0] == 'VideoConfig':
  298. video_item = item[2][0]
  299. if video_item.get('video_id'):
  300. return video_item['videoData']
  301. server_js_data = self._parse_json(self._search_regex(
  302. r'handleServerJS\(({.+})(?:\);|,")', webpage,
  303. 'server js data', default='{}'), video_id, fatal=False)
  304. if server_js_data:
  305. video_data = extract_video_data(server_js_data.get('instances', []))
  306. if not video_data:
  307. server_js_data = self._parse_json(
  308. self._search_regex(
  309. r'bigPipe\.onPageletArrive\(({.+?})\)\s*;\s*}\s*\)\s*,\s*["\']onPageletArrive\s+(?:stream_pagelet|pagelet_group_mall|permalink_video_pagelet)',
  310. webpage, 'js data', default='{}'),
  311. video_id, transform_source=js_to_json, fatal=False)
  312. if server_js_data:
  313. video_data = extract_video_data(try_get(
  314. server_js_data, lambda x: x['jsmods']['instances'],
  315. list) or [])
  316. if not video_data:
  317. # video info not in first request, do a secondary request using tahoe player specific url
  318. tahoe_data = self._download_webpage(
  319. self._VIDEO_PAGE_TAHOE_TEMPLATE % video_id, video_id,
  320. data=urlencode_postdata({
  321. '__user': 0,
  322. '__a': 1,
  323. '__pc': self._search_regex(r'"pkg_cohort":"(.*?)"', webpage, 'pkg cohort', default='PHASED:DEFAULT'),
  324. '__rev': self._search_regex(r'"client_revision":(\d+),', webpage, 'client revision', default=3944515),
  325. }),
  326. headers={
  327. 'Content-Type': 'application/x-www-form-urlencoded',
  328. })
  329. tahoe_js_data = self._parse_json(self._search_regex(
  330. r'for \(;;\);(.+)', tahoe_data,
  331. 'tahoe js data', default='{}'), video_id, fatal=False)
  332. video_data = extract_video_data(tahoe_js_data.get('jsmods', {}).get('instances', []))
  333. if not video_data:
  334. if not fatal_if_no_video:
  335. return webpage, False
  336. m_msg = re.search(r'class="[^"]*uiInterstitialContent[^"]*"><div>(.*?)</div>', webpage)
  337. if m_msg is not None:
  338. raise ExtractorError(
  339. 'The video is not available, Facebook said: "%s"' % m_msg.group(1),
  340. expected=True)
  341. elif '>You must log in to continue' in webpage:
  342. self.raise_login_required()
  343. else:
  344. raise ExtractorError('Cannot parse data')
  345. formats = []
  346. for f in video_data:
  347. format_id = f['stream_type']
  348. if f and isinstance(f, dict):
  349. f = [f]
  350. if not f or not isinstance(f, list):
  351. continue
  352. for quality in ('sd', 'hd'):
  353. for src_type in ('src', 'src_no_ratelimit'):
  354. src = f[0].get('%s_%s' % (quality, src_type))
  355. if src:
  356. preference = -10 if format_id == 'progressive' else 0
  357. if quality == 'hd':
  358. preference += 5
  359. formats.append({
  360. 'format_id': '%s_%s_%s' % (format_id, quality, src_type),
  361. 'url': src,
  362. 'preference': preference,
  363. })
  364. dash_manifest = f[0].get('dash_manifest')
  365. if dash_manifest:
  366. formats.extend(self._parse_mpd_formats(
  367. compat_etree_fromstring(compat_urllib_parse_unquote_plus(dash_manifest))))
  368. if not formats:
  369. raise ExtractorError('Cannot find video formats')
  370. self._sort_formats(formats)
  371. video_title = self._html_search_regex(
  372. r'<h2\s+[^>]*class="uiHeaderTitle"[^>]*>([^<]*)</h2>', webpage,
  373. 'title', default=None)
  374. if not video_title:
  375. video_title = self._html_search_regex(
  376. r'(?s)<span class="fbPhotosPhotoCaption".*?id="fbPhotoPageCaption"><span class="hasCaption">(.*?)</span>',
  377. webpage, 'alternative title', default=None)
  378. if not video_title:
  379. video_title = self._html_search_meta(
  380. 'description', webpage, 'title', default=None)
  381. if video_title:
  382. video_title = limit_length(video_title, 80)
  383. else:
  384. video_title = 'Facebook video #%s' % video_id
  385. uploader = clean_html(get_element_by_id('fbPhotoPageAuthorName', webpage))
  386. if not uploader:
  387. uploader = self._search_regex(
  388. [r'ownerName\s*:\s*"([^"]+)"', r'property="og:title"\s*content="(.*?)"'],
  389. webpage, 'uploader', fatal=False)
  390. timestamp = int_or_none(self._search_regex(
  391. r'<abbr[^>]+data-utime=["\'](\d+)', webpage,
  392. 'timestamp', default=None))
  393. thumbnail = self._og_search_thumbnail(webpage)
  394. info_dict = {
  395. 'id': video_id,
  396. 'title': video_title,
  397. 'formats': formats,
  398. 'uploader': uploader,
  399. 'timestamp': timestamp,
  400. 'thumbnail': thumbnail,
  401. }
  402. return webpage, info_dict
  403. def _real_extract(self, url):
  404. video_id = self._match_id(url)
  405. real_url = self._VIDEO_PAGE_TEMPLATE % video_id if url.startswith('facebook:') else url
  406. webpage, info_dict = self._extract_from_url(real_url, video_id, fatal_if_no_video=False)
  407. if info_dict:
  408. return info_dict
  409. if '/posts/' in url:
  410. entries = [
  411. self.url_result('facebook:%s' % vid, FacebookIE.ie_key())
  412. for vid in self._parse_json(
  413. self._search_regex(
  414. r'(["\'])video_ids\1\s*:\s*(?P<ids>\[.+?\])',
  415. webpage, 'video ids', group='ids'),
  416. video_id)]
  417. return self.playlist_result(entries, video_id)
  418. else:
  419. _, info_dict = self._extract_from_url(
  420. self._VIDEO_PAGE_TEMPLATE % video_id,
  421. video_id, fatal_if_no_video=True)
  422. return info_dict
  423. class FacebookPluginsVideoIE(InfoExtractor):
  424. _VALID_URL = r'https?://(?:[\w-]+\.)?facebook\.com/plugins/video\.php\?.*?\bhref=(?P<id>https.+)'
  425. _TESTS = [{
  426. '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',
  427. 'md5': '5954e92cdfe51fe5782ae9bda7058a07',
  428. 'info_dict': {
  429. 'id': '10154383743583686',
  430. 'ext': 'mp4',
  431. 'title': 'What to do during the haze?',
  432. 'uploader': 'Gov.sg',
  433. 'upload_date': '20160826',
  434. 'timestamp': 1472184808,
  435. },
  436. 'add_ie': [FacebookIE.ie_key()],
  437. }, {
  438. 'url': 'https://www.facebook.com/plugins/video.php?href=https%3A%2F%2Fwww.facebook.com%2Fvideo.php%3Fv%3D10204634152394104',
  439. 'only_matching': True,
  440. }, {
  441. 'url': 'https://www.facebook.com/plugins/video.php?href=https://www.facebook.com/gov.sg/videos/10154383743583686/&show_text=0&width=560',
  442. 'only_matching': True,
  443. }]
  444. def _real_extract(self, url):
  445. return self.url_result(
  446. compat_urllib_parse_unquote(self._match_id(url)),
  447. FacebookIE.ie_key())