facebook.py 8.2 KB

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