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.

154 lines
6.4 KiB

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