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.

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