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.

152 lines
6.2 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. limit_length,
  15. )
  16. class FacebookIE(InfoExtractor):
  17. _VALID_URL = r'''(?x)
  18. https?://(?:\w+\.)?facebook\.com/
  19. (?:[^#]*?\#!/)?
  20. (?:video/video\.php|photo\.php|video\.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. _TESTS = [{
  28. 'url': 'https://www.facebook.com/video.php?v=637842556329505&fref=nf',
  29. 'md5': '6a40d33c0eccbb1af76cf0485a052659',
  30. 'info_dict': {
  31. 'id': '637842556329505',
  32. 'ext': 'mp4',
  33. 'duration': 38,
  34. 'title': 're:Did you know Kei Nishikori is the first Asian man to ever reach a Grand Slam',
  35. }
  36. }, {
  37. 'note': 'Video without discernible title',
  38. 'url': 'https://www.facebook.com/video.php?v=274175099429670',
  39. 'info_dict': {
  40. 'id': '274175099429670',
  41. 'ext': 'mp4',
  42. 'title': 'Facebook video #274175099429670',
  43. }
  44. }, {
  45. 'url': 'https://www.facebook.com/video.php?v=10204634152394104',
  46. 'only_matching': True,
  47. }]
  48. def _login(self):
  49. (useremail, password) = self._get_login_info()
  50. if useremail is None:
  51. return
  52. login_page_req = compat_urllib_request.Request(self._LOGIN_URL)
  53. login_page_req.add_header('Cookie', 'locale=en_US')
  54. login_page = self._download_webpage(login_page_req, None,
  55. note='Downloading login page',
  56. errnote='Unable to download login page')
  57. lsd = self._search_regex(
  58. r'<input type="hidden" name="lsd" value="([^"]*)"',
  59. login_page, 'lsd')
  60. lgnrnd = self._search_regex(r'name="lgnrnd" value="([^"]*?)"', login_page, 'lgnrnd')
  61. login_form = {
  62. 'email': useremail,
  63. 'pass': password,
  64. 'lsd': lsd,
  65. 'lgnrnd': lgnrnd,
  66. 'next': 'http://facebook.com/home.php',
  67. 'default_persistent': '0',
  68. 'legacy_return': '1',
  69. 'timezone': '-60',
  70. 'trynum': '1',
  71. }
  72. request = compat_urllib_request.Request(self._LOGIN_URL, urlencode_postdata(login_form))
  73. request.add_header('Content-Type', 'application/x-www-form-urlencoded')
  74. try:
  75. login_results = self._download_webpage(request, None,
  76. note='Logging in', errnote='unable to fetch login page')
  77. if re.search(r'<form(.*)name="login"(.*)</form>', login_results) is not None:
  78. self._downloader.report_warning('unable to log in: bad username/password, or exceded login rate limit (~3/min). Check credentials or wait.')
  79. return
  80. check_form = {
  81. 'fb_dtsg': self._search_regex(r'name="fb_dtsg" value="(.+?)"', login_results, 'fb_dtsg'),
  82. 'h': self._search_regex(
  83. r'name="h"\s+(?:\w+="[^"]+"\s+)*?value="([^"]+)"', login_results, 'h'),
  84. 'name_action_selected': 'dont_save',
  85. }
  86. check_req = compat_urllib_request.Request(self._CHECKPOINT_URL, urlencode_postdata(check_form))
  87. check_req.add_header('Content-Type', 'application/x-www-form-urlencoded')
  88. check_response = self._download_webpage(check_req, None,
  89. note='Confirming login')
  90. if re.search(r'id="checkpointSubmitButton"', check_response) is not None:
  91. self._downloader.report_warning('Unable to confirm login, you have to login in your brower and authorize the login.')
  92. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  93. self._downloader.report_warning('unable to log in: %s' % compat_str(err))
  94. return
  95. def _real_initialize(self):
  96. self._login()
  97. def _real_extract(self, url):
  98. mobj = re.match(self._VALID_URL, url)
  99. video_id = mobj.group('id')
  100. url = 'https://www.facebook.com/video/video.php?v=%s' % video_id
  101. webpage = self._download_webpage(url, video_id)
  102. BEFORE = '{swf.addParam(param[0], param[1]);});\n'
  103. AFTER = '.forEach(function(variable) {swf.addVariable(variable[0], variable[1]);});'
  104. m = re.search(re.escape(BEFORE) + '(.*?)' + re.escape(AFTER), webpage)
  105. if not m:
  106. m_msg = re.search(r'class="[^"]*uiInterstitialContent[^"]*"><div>(.*?)</div>', webpage)
  107. if m_msg is not None:
  108. raise ExtractorError(
  109. 'The video is not available, Facebook said: "%s"' % m_msg.group(1),
  110. expected=True)
  111. else:
  112. raise ExtractorError('Cannot parse data')
  113. data = dict(json.loads(m.group(1)))
  114. params_raw = compat_urllib_parse.unquote(data['params'])
  115. params = json.loads(params_raw)
  116. video_data = params['video_data'][0]
  117. video_url = video_data.get('hd_src')
  118. if not video_url:
  119. video_url = video_data['sd_src']
  120. if not video_url:
  121. raise ExtractorError('Cannot find video URL')
  122. video_title = self._html_search_regex(
  123. r'<h2 class="uiHeaderTitle">([^<]*)</h2>', webpage, 'title',
  124. fatal=False)
  125. if not video_title:
  126. video_title = self._html_search_regex(
  127. r'(?s)<span class="fbPhotosPhotoCaption".*?id="fbPhotoPageCaption"><span class="hasCaption">(.*?)</span>',
  128. webpage, 'alternative title', default=None)
  129. video_title = limit_length(video_title, 80)
  130. if not video_title:
  131. video_title = 'Facebook video #%s' % video_id
  132. return {
  133. 'id': video_id,
  134. 'title': video_title,
  135. 'url': video_url,
  136. 'duration': int(video_data['video_duration']),
  137. 'thumbnail': video_data['thumbnail_src'],
  138. }