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.

132 lines
5.5 KiB

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