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.

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