facebook.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  1. from __future__ import unicode_literals
  2. import re
  3. import socket
  4. from .common import InfoExtractor
  5. from ..compat import (
  6. compat_etree_fromstring,
  7. compat_http_client,
  8. compat_urllib_error,
  9. compat_urllib_parse_unquote,
  10. compat_urllib_parse_unquote_plus,
  11. )
  12. from ..utils import (
  13. clean_html,
  14. error_to_compat_str,
  15. ExtractorError,
  16. get_element_by_id,
  17. int_or_none,
  18. js_to_json,
  19. limit_length,
  20. sanitized_Request,
  21. try_get,
  22. urlencode_postdata,
  23. )
  24. class FacebookIE(InfoExtractor):
  25. _VALID_URL = r'''(?x)
  26. (?:
  27. https?://
  28. (?:[\w-]+\.)?(?:facebook\.com|facebookcorewwwi\.onion)/
  29. (?:[^#]*?\#!/)?
  30. (?:
  31. (?:
  32. video/video\.php|
  33. photo\.php|
  34. video\.php|
  35. video/embed|
  36. story\.php
  37. )\?(?:.*?)(?:v|video_id|story_fbid)=|
  38. [^/]+/videos/(?:[^/]+/)?|
  39. [^/]+/posts/|
  40. groups/[^/]+/permalink/
  41. )|
  42. facebook:
  43. )
  44. (?P<id>[0-9]+)
  45. '''
  46. _LOGIN_URL = 'https://www.facebook.com/login.php?next=http%3A%2F%2Ffacebook.com%2Fhome.php&login_attempt=1'
  47. _CHECKPOINT_URL = 'https://www.facebook.com/checkpoint/?next=http%3A%2F%2Ffacebook.com%2Fhome.php&_fb_noscript=1'
  48. _NETRC_MACHINE = 'facebook'
  49. IE_NAME = 'facebook'
  50. _CHROME_USER_AGENT = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.97 Safari/537.36'
  51. _VIDEO_PAGE_TEMPLATE = 'https://www.facebook.com/video/video.php?v=%s'
  52. _TESTS = [{
  53. 'url': 'https://www.facebook.com/video.php?v=637842556329505&fref=nf',
  54. 'md5': '6a40d33c0eccbb1af76cf0485a052659',
  55. 'info_dict': {
  56. 'id': '637842556329505',
  57. 'ext': 'mp4',
  58. 'title': 're:Did you know Kei Nishikori is the first Asian man to ever reach a Grand Slam',
  59. 'uploader': 'Tennis on Facebook',
  60. 'upload_date': '20140908',
  61. 'timestamp': 1410199200,
  62. }
  63. }, {
  64. 'note': 'Video without discernible title',
  65. 'url': 'https://www.facebook.com/video.php?v=274175099429670',
  66. 'info_dict': {
  67. 'id': '274175099429670',
  68. 'ext': 'mp4',
  69. 'title': 'Asif Nawab Butt posted a video to his Timeline.',
  70. 'uploader': 'Asif Nawab Butt',
  71. 'upload_date': '20140506',
  72. 'timestamp': 1399398998,
  73. },
  74. 'expected_warnings': [
  75. 'title'
  76. ]
  77. }, {
  78. 'note': 'Video with DASH manifest',
  79. 'url': 'https://www.facebook.com/video.php?v=957955867617029',
  80. 'md5': 'b2c28d528273b323abe5c6ab59f0f030',
  81. 'info_dict': {
  82. 'id': '957955867617029',
  83. 'ext': 'mp4',
  84. 'title': 'When you post epic content on instagram.com/433 8 million followers, this is ...',
  85. 'uploader': 'Demy de Zeeuw',
  86. 'upload_date': '20160110',
  87. 'timestamp': 1452431627,
  88. },
  89. }, {
  90. 'url': 'https://www.facebook.com/maxlayn/posts/10153807558977570',
  91. 'md5': '037b1fa7f3c2d02b7a0d7bc16031ecc6',
  92. 'info_dict': {
  93. 'id': '544765982287235',
  94. 'ext': 'mp4',
  95. 'title': '"What are you doing running in the snow?"',
  96. 'uploader': 'FailArmy',
  97. },
  98. 'skip': 'Video gone',
  99. }, {
  100. 'url': 'https://m.facebook.com/story.php?story_fbid=1035862816472149&id=116132035111903',
  101. 'md5': '1deb90b6ac27f7efcf6d747c8a27f5e3',
  102. 'info_dict': {
  103. 'id': '1035862816472149',
  104. 'ext': 'mp4',
  105. 'title': 'What the Flock Is Going On In New Zealand Credit: ViralHog',
  106. 'uploader': 'S. Saint',
  107. },
  108. 'skip': 'Video gone',
  109. }, {
  110. 'note': 'swf params escaped',
  111. 'url': 'https://www.facebook.com/barackobama/posts/10153664894881749',
  112. 'md5': '97ba073838964d12c70566e0085c2b91',
  113. 'info_dict': {
  114. 'id': '10153664894881749',
  115. 'ext': 'mp4',
  116. 'title': 'Facebook video #10153664894881749',
  117. },
  118. }, {
  119. # have 1080P, but only up to 720p in swf params
  120. 'url': 'https://www.facebook.com/cnn/videos/10155529876156509/',
  121. 'md5': '0d9813160b146b3bc8744e006027fcc6',
  122. 'info_dict': {
  123. 'id': '10155529876156509',
  124. 'ext': 'mp4',
  125. 'title': 'Holocaust survivor becomes US citizen',
  126. 'timestamp': 1477818095,
  127. 'upload_date': '20161030',
  128. 'uploader': 'CNN',
  129. },
  130. }, {
  131. # bigPipe.onPageletArrive ... onPageletArrive pagelet_group_mall
  132. 'url': 'https://www.facebook.com/yaroslav.korpan/videos/1417995061575415/',
  133. 'info_dict': {
  134. 'id': '1417995061575415',
  135. 'ext': 'mp4',
  136. 'title': 'md5:a7b86ca673f51800cd54687b7f4012fe',
  137. 'timestamp': 1486648217,
  138. 'upload_date': '20170209',
  139. 'uploader': 'Yaroslav Korpan',
  140. },
  141. 'params': {
  142. 'skip_download': True,
  143. },
  144. }, {
  145. 'url': 'https://www.facebook.com/video.php?v=10204634152394104',
  146. 'only_matching': True,
  147. }, {
  148. 'url': 'https://www.facebook.com/amogood/videos/1618742068337349/?fref=nf',
  149. 'only_matching': True,
  150. }, {
  151. 'url': 'https://www.facebook.com/ChristyClarkForBC/videos/vb.22819070941/10153870694020942/?type=2&theater',
  152. 'only_matching': True,
  153. }, {
  154. 'url': 'facebook:544765982287235',
  155. 'only_matching': True,
  156. }, {
  157. 'url': 'https://www.facebook.com/groups/164828000315060/permalink/764967300301124/',
  158. 'only_matching': True,
  159. }, {
  160. 'url': 'https://zh-hk.facebook.com/peoplespower/videos/1135894589806027/',
  161. 'only_matching': True,
  162. }, {
  163. 'url': 'https://www.facebookcorewwwi.onion/video.php?v=274175099429670',
  164. 'only_matching': True,
  165. }]
  166. @staticmethod
  167. def _extract_url(webpage):
  168. mobj = re.search(
  169. r'<iframe[^>]+?src=(["\'])(?P<url>https://www\.facebook\.com/video/embed.+?)\1', webpage)
  170. if mobj is not None:
  171. return mobj.group('url')
  172. # Facebook API embed
  173. # see https://developers.facebook.com/docs/plugins/embedded-video-player
  174. mobj = re.search(r'''(?x)<div[^>]+
  175. class=(?P<q1>[\'"])[^\'"]*\bfb-(?:video|post)\b[^\'"]*(?P=q1)[^>]+
  176. data-href=(?P<q2>[\'"])(?P<url>(?:https?:)?//(?:www\.)?facebook.com/.+?)(?P=q2)''', webpage)
  177. if mobj is not None:
  178. return mobj.group('url')
  179. def _login(self):
  180. (useremail, password) = self._get_login_info()
  181. if useremail is None:
  182. return
  183. login_page_req = sanitized_Request(self._LOGIN_URL)
  184. self._set_cookie('facebook.com', 'locale', 'en_US')
  185. login_page = self._download_webpage(login_page_req, None,
  186. note='Downloading login page',
  187. errnote='Unable to download login page')
  188. lsd = self._search_regex(
  189. r'<input type="hidden" name="lsd" value="([^"]*)"',
  190. login_page, 'lsd')
  191. lgnrnd = self._search_regex(r'name="lgnrnd" value="([^"]*?)"', login_page, 'lgnrnd')
  192. login_form = {
  193. 'email': useremail,
  194. 'pass': password,
  195. 'lsd': lsd,
  196. 'lgnrnd': lgnrnd,
  197. 'next': 'http://facebook.com/home.php',
  198. 'default_persistent': '0',
  199. 'legacy_return': '1',
  200. 'timezone': '-60',
  201. 'trynum': '1',
  202. }
  203. request = sanitized_Request(self._LOGIN_URL, urlencode_postdata(login_form))
  204. request.add_header('Content-Type', 'application/x-www-form-urlencoded')
  205. try:
  206. login_results = self._download_webpage(request, None,
  207. note='Logging in', errnote='unable to fetch login page')
  208. if re.search(r'<form(.*)name="login"(.*)</form>', login_results) is not None:
  209. error = self._html_search_regex(
  210. r'(?s)<div[^>]+class=(["\']).*?login_error_box.*?\1[^>]*><div[^>]*>.*?</div><div[^>]*>(?P<error>.+?)</div>',
  211. login_results, 'login error', default=None, group='error')
  212. if error:
  213. raise ExtractorError('Unable to login: %s' % error, expected=True)
  214. self._downloader.report_warning('unable to log in: bad username/password, or exceeded login rate limit (~3/min). Check credentials or wait.')
  215. return
  216. fb_dtsg = self._search_regex(
  217. r'name="fb_dtsg" value="(.+?)"', login_results, 'fb_dtsg', default=None)
  218. h = self._search_regex(
  219. r'name="h"\s+(?:\w+="[^"]+"\s+)*?value="([^"]+)"', login_results, 'h', default=None)
  220. if not fb_dtsg or not h:
  221. return
  222. check_form = {
  223. 'fb_dtsg': fb_dtsg,
  224. 'h': h,
  225. 'name_action_selected': 'dont_save',
  226. }
  227. check_req = sanitized_Request(self._CHECKPOINT_URL, urlencode_postdata(check_form))
  228. check_req.add_header('Content-Type', 'application/x-www-form-urlencoded')
  229. check_response = self._download_webpage(check_req, None,
  230. note='Confirming login')
  231. if re.search(r'id="checkpointSubmitButton"', check_response) is not None:
  232. self._downloader.report_warning('Unable to confirm login, you have to login in your browser and authorize the login.')
  233. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  234. self._downloader.report_warning('unable to log in: %s' % error_to_compat_str(err))
  235. return
  236. def _real_initialize(self):
  237. self._login()
  238. def _extract_from_url(self, url, video_id, fatal_if_no_video=True):
  239. req = sanitized_Request(url)
  240. req.add_header('User-Agent', self._CHROME_USER_AGENT)
  241. webpage = self._download_webpage(req, video_id)
  242. video_data = None
  243. def extract_video_data(instances):
  244. for item in instances:
  245. if item[1][0] == 'VideoConfig':
  246. video_item = item[2][0]
  247. if video_item.get('video_id') == video_id:
  248. return video_item['videoData']
  249. server_js_data = self._parse_json(self._search_regex(
  250. r'handleServerJS\(({.+})(?:\);|,")', webpage,
  251. 'server js data', default='{}'), video_id, fatal=False)
  252. if server_js_data:
  253. video_data = extract_video_data(server_js_data.get('instances', []))
  254. if not video_data:
  255. server_js_data = self._parse_json(
  256. self._search_regex(
  257. r'bigPipe\.onPageletArrive\(({.+?})\)\s*;\s*}\s*\)\s*,\s*["\']onPageletArrive\s+(?:stream_pagelet|pagelet_group_mall)',
  258. webpage, 'js data', default='{}'),
  259. video_id, transform_source=js_to_json, fatal=False)
  260. if server_js_data:
  261. video_data = extract_video_data(try_get(
  262. server_js_data, lambda x: x['jsmods']['instances'],
  263. list) or [])
  264. if not video_data:
  265. if not fatal_if_no_video:
  266. return webpage, False
  267. m_msg = re.search(r'class="[^"]*uiInterstitialContent[^"]*"><div>(.*?)</div>', webpage)
  268. if m_msg is not None:
  269. raise ExtractorError(
  270. 'The video is not available, Facebook said: "%s"' % m_msg.group(1),
  271. expected=True)
  272. elif '>You must log in to continue' in webpage:
  273. self.raise_login_required()
  274. else:
  275. raise ExtractorError('Cannot parse data')
  276. formats = []
  277. for f in video_data:
  278. format_id = f['stream_type']
  279. if f and isinstance(f, dict):
  280. f = [f]
  281. if not f or not isinstance(f, list):
  282. continue
  283. for quality in ('sd', 'hd'):
  284. for src_type in ('src', 'src_no_ratelimit'):
  285. src = f[0].get('%s_%s' % (quality, src_type))
  286. if src:
  287. preference = -10 if format_id == 'progressive' else 0
  288. if quality == 'hd':
  289. preference += 5
  290. formats.append({
  291. 'format_id': '%s_%s_%s' % (format_id, quality, src_type),
  292. 'url': src,
  293. 'preference': preference,
  294. })
  295. dash_manifest = f[0].get('dash_manifest')
  296. if dash_manifest:
  297. formats.extend(self._parse_mpd_formats(
  298. compat_etree_fromstring(compat_urllib_parse_unquote_plus(dash_manifest))))
  299. if not formats:
  300. raise ExtractorError('Cannot find video formats')
  301. self._sort_formats(formats)
  302. video_title = self._html_search_regex(
  303. r'<h2\s+[^>]*class="uiHeaderTitle"[^>]*>([^<]*)</h2>', webpage, 'title',
  304. default=None)
  305. if not video_title:
  306. video_title = self._html_search_regex(
  307. r'(?s)<span class="fbPhotosPhotoCaption".*?id="fbPhotoPageCaption"><span class="hasCaption">(.*?)</span>',
  308. webpage, 'alternative title', default=None)
  309. if not video_title:
  310. video_title = self._html_search_meta(
  311. 'description', webpage, 'title')
  312. if video_title:
  313. video_title = limit_length(video_title, 80)
  314. else:
  315. video_title = 'Facebook video #%s' % video_id
  316. uploader = clean_html(get_element_by_id(
  317. 'fbPhotoPageAuthorName', webpage)) or self._search_regex(
  318. r'ownerName\s*:\s*"([^"]+)"', webpage, 'uploader', fatal=False)
  319. timestamp = int_or_none(self._search_regex(
  320. r'<abbr[^>]+data-utime=["\'](\d+)', webpage,
  321. 'timestamp', default=None))
  322. info_dict = {
  323. 'id': video_id,
  324. 'title': video_title,
  325. 'formats': formats,
  326. 'uploader': uploader,
  327. 'timestamp': timestamp,
  328. }
  329. return webpage, info_dict
  330. def _real_extract(self, url):
  331. video_id = self._match_id(url)
  332. real_url = self._VIDEO_PAGE_TEMPLATE % video_id if url.startswith('facebook:') else url
  333. webpage, info_dict = self._extract_from_url(real_url, video_id, fatal_if_no_video=False)
  334. if info_dict:
  335. return info_dict
  336. if '/posts/' in url:
  337. entries = [
  338. self.url_result('facebook:%s' % vid, FacebookIE.ie_key())
  339. for vid in self._parse_json(
  340. self._search_regex(
  341. r'(["\'])video_ids\1\s*:\s*(?P<ids>\[.+?\])',
  342. webpage, 'video ids', group='ids'),
  343. video_id)]
  344. return self.playlist_result(entries, video_id)
  345. else:
  346. _, info_dict = self._extract_from_url(
  347. self._VIDEO_PAGE_TEMPLATE % video_id,
  348. video_id, fatal_if_no_video=True)
  349. return info_dict
  350. class FacebookPluginsVideoIE(InfoExtractor):
  351. _VALID_URL = r'https?://(?:[\w-]+\.)?facebook\.com/plugins/video\.php\?.*?\bhref=(?P<id>https.+)'
  352. _TESTS = [{
  353. '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',
  354. 'md5': '5954e92cdfe51fe5782ae9bda7058a07',
  355. 'info_dict': {
  356. 'id': '10154383743583686',
  357. 'ext': 'mp4',
  358. 'title': 'What to do during the haze?',
  359. 'uploader': 'Gov.sg',
  360. 'upload_date': '20160826',
  361. 'timestamp': 1472184808,
  362. },
  363. 'add_ie': [FacebookIE.ie_key()],
  364. }, {
  365. 'url': 'https://www.facebook.com/plugins/video.php?href=https%3A%2F%2Fwww.facebook.com%2Fvideo.php%3Fv%3D10204634152394104',
  366. 'only_matching': True,
  367. }, {
  368. 'url': 'https://www.facebook.com/plugins/video.php?href=https://www.facebook.com/gov.sg/videos/10154383743583686/&show_text=0&width=560',
  369. 'only_matching': True,
  370. }]
  371. def _real_extract(self, url):
  372. return self.url_result(
  373. compat_urllib_parse_unquote(self._match_id(url)),
  374. FacebookIE.ie_key())