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.

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