You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

145 lines
5.8 KiB

  1. from __future__ import unicode_literals
  2. import json
  3. import re
  4. import socket
  5. from .common import InfoExtractor
  6. from ..utils import (
  7. compat_http_client,
  8. compat_str,
  9. compat_urllib_error,
  10. compat_urllib_parse,
  11. compat_urllib_request,
  12. urlencode_postdata,
  13. ExtractorError,
  14. )
  15. class FacebookIE(InfoExtractor):
  16. """Information Extractor for Facebook"""
  17. _VALID_URL = r'''(?x)
  18. (?:https?://)?(?:\w+\.)?facebook\.com/
  19. (?:[^#?]*\#!/)?
  20. (?:video/video\.php|photo\.php|video/embed)\?(?:.*?)
  21. (?:v|video_id)=(?P<id>[0-9]+)
  22. (?:.*)'''
  23. _LOGIN_URL = 'https://www.facebook.com/login.php?next=http%3A%2F%2Ffacebook.com%2Fhome.php&login_attempt=1'
  24. _CHECKPOINT_URL = 'https://www.facebook.com/checkpoint/?next=http%3A%2F%2Ffacebook.com%2Fhome.php&_fb_noscript=1'
  25. _NETRC_MACHINE = 'facebook'
  26. IE_NAME = 'facebook'
  27. _TEST = {
  28. 'url': 'https://www.facebook.com/photo.php?v=120708114770723',
  29. 'md5': '48975a41ccc4b7a581abd68651c1a5a8',
  30. 'info_dict': {
  31. 'id': '120708114770723',
  32. 'ext': 'mp4',
  33. 'duration': 279,
  34. 'title': 'PEOPLE ARE AWESOME 2013'
  35. }
  36. }
  37. def report_login(self):
  38. """Report attempt to log in."""
  39. self.to_screen('Logging in')
  40. def _login(self):
  41. (useremail, password) = self._get_login_info()
  42. if useremail is None:
  43. return
  44. login_page_req = compat_urllib_request.Request(self._LOGIN_URL)
  45. login_page_req.add_header('Cookie', 'locale=en_US')
  46. login_page = self._download_webpage(login_page_req, None,
  47. note='Downloading login page',
  48. errnote='Unable to download login page')
  49. lsd = self._search_regex(
  50. r'<input type="hidden" name="lsd" value="([^"]*)"',
  51. login_page, 'lsd')
  52. lgnrnd = self._search_regex(r'name="lgnrnd" value="([^"]*?)"', login_page, 'lgnrnd')
  53. login_form = {
  54. 'email': useremail,
  55. 'pass': password,
  56. 'lsd': lsd,
  57. 'lgnrnd': lgnrnd,
  58. 'next': 'http://facebook.com/home.php',
  59. 'default_persistent': '0',
  60. 'legacy_return': '1',
  61. 'timezone': '-60',
  62. 'trynum': '1',
  63. }
  64. request = compat_urllib_request.Request(self._LOGIN_URL, urlencode_postdata(login_form))
  65. request.add_header('Content-Type', 'application/x-www-form-urlencoded')
  66. try:
  67. login_results = self._download_webpage(request, None,
  68. note='Logging in', errnote='unable to fetch login page')
  69. if re.search(r'<form(.*)name="login"(.*)</form>', login_results) is not None:
  70. self._downloader.report_warning('unable to log in: bad username/password, or exceded login rate limit (~3/min). Check credentials or wait.')
  71. return
  72. check_form = {
  73. 'fb_dtsg': self._search_regex(r'name="fb_dtsg" value="(.+?)"', login_results, 'fb_dtsg'),
  74. 'nh': self._search_regex(r'name="nh" value="(\w*?)"', login_results, 'nh'),
  75. 'name_action_selected': 'dont_save',
  76. 'submit[Continue]': self._search_regex(r'<button[^>]+value="(.*?)"[^>]+name="submit\[Continue\]"', login_results, 'continue'),
  77. }
  78. check_req = compat_urllib_request.Request(self._CHECKPOINT_URL, urlencode_postdata(check_form))
  79. check_req.add_header('Content-Type', 'application/x-www-form-urlencoded')
  80. check_response = self._download_webpage(check_req, None,
  81. note='Confirming login')
  82. if re.search(r'id="checkpointSubmitButton"', check_response) is not None:
  83. self._downloader.report_warning('Unable to confirm login, you have to login in your brower and authorize the login.')
  84. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  85. self._downloader.report_warning('unable to log in: %s' % compat_str(err))
  86. return
  87. def _real_initialize(self):
  88. self._login()
  89. def _real_extract(self, url):
  90. mobj = re.match(self._VALID_URL, url)
  91. if mobj is None:
  92. raise ExtractorError('Invalid URL: %s' % url)
  93. video_id = mobj.group('id')
  94. url = 'https://www.facebook.com/video/video.php?v=%s' % video_id
  95. webpage = self._download_webpage(url, video_id)
  96. BEFORE = '{swf.addParam(param[0], param[1]);});\n'
  97. AFTER = '.forEach(function(variable) {swf.addVariable(variable[0], variable[1]);});'
  98. m = re.search(re.escape(BEFORE) + '(.*?)' + re.escape(AFTER), webpage)
  99. if not m:
  100. m_msg = re.search(r'class="[^"]*uiInterstitialContent[^"]*"><div>(.*?)</div>', webpage)
  101. if m_msg is not None:
  102. raise ExtractorError(
  103. 'The video is not available, Facebook said: "%s"' % m_msg.group(1),
  104. expected=True)
  105. else:
  106. raise ExtractorError('Cannot parse data')
  107. data = dict(json.loads(m.group(1)))
  108. params_raw = compat_urllib_parse.unquote(data['params'])
  109. params = json.loads(params_raw)
  110. video_data = params['video_data'][0]
  111. video_url = video_data.get('hd_src')
  112. if not video_url:
  113. video_url = video_data['sd_src']
  114. if not video_url:
  115. raise ExtractorError('Cannot find video URL')
  116. video_duration = int(video_data['video_duration'])
  117. thumbnail = video_data['thumbnail_src']
  118. video_title = self._html_search_regex(
  119. r'<h2 class="uiHeaderTitle">([^<]*)</h2>', webpage, 'title')
  120. info = {
  121. 'id': video_id,
  122. 'title': video_title,
  123. 'url': video_url,
  124. 'ext': 'mp4',
  125. 'duration': video_duration,
  126. 'thumbnail': thumbnail,
  127. }
  128. return [info]