facebook.py 15 KB

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