facebook.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140
  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(r'"lsd":"(\w*?)"', login_page, 'lsd')
  49. lgnrnd = self._search_regex(r'name="lgnrnd" value="([^"]*?)"', login_page, 'lgnrnd')
  50. login_form = {
  51. 'email': useremail,
  52. 'pass': password,
  53. 'lsd': lsd,
  54. 'lgnrnd': lgnrnd,
  55. 'next': 'http://facebook.com/home.php',
  56. 'default_persistent': '0',
  57. 'legacy_return': '1',
  58. 'timezone': '-60',
  59. 'trynum': '1',
  60. }
  61. request = compat_urllib_request.Request(self._LOGIN_URL, compat_urllib_parse.urlencode(login_form))
  62. request.add_header('Content-Type', 'application/x-www-form-urlencoded')
  63. try:
  64. login_results = compat_urllib_request.urlopen(request).read()
  65. if re.search(r'<form(.*)name="login"(.*)</form>', login_results) is not None:
  66. self._downloader.report_warning('unable to log in: bad username/password, or exceded login rate limit (~3/min). Check credentials or wait.')
  67. return
  68. check_form = {
  69. 'fb_dtsg': self._search_regex(r'"fb_dtsg":"(.*?)"', login_results, 'fb_dtsg'),
  70. 'nh': self._search_regex(r'name="nh" value="(\w*?)"', login_results, 'nh'),
  71. 'name_action_selected': 'dont_save',
  72. 'submit[Continue]': self._search_regex(r'<input value="(.*?)" name="submit\[Continue\]"', login_results, 'continue'),
  73. }
  74. check_req = compat_urllib_request.Request(self._CHECKPOINT_URL, compat_urllib_parse.urlencode(check_form))
  75. check_req.add_header('Content-Type', 'application/x-www-form-urlencoded')
  76. check_response = compat_urllib_request.urlopen(check_req).read()
  77. if re.search(r'id="checkpointSubmitButton"', check_response) is not None:
  78. self._downloader.report_warning('Unable to confirm login, you have to login in your brower and authorize the login.')
  79. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  80. self._downloader.report_warning('unable to log in: %s' % compat_str(err))
  81. return
  82. def _real_initialize(self):
  83. self._login()
  84. def _real_extract(self, url):
  85. mobj = re.match(self._VALID_URL, url)
  86. if mobj is None:
  87. raise ExtractorError('Invalid URL: %s' % url)
  88. video_id = mobj.group('id')
  89. url = 'https://www.facebook.com/video/video.php?v=%s' % video_id
  90. webpage = self._download_webpage(url, video_id)
  91. BEFORE = '{swf.addParam(param[0], param[1]);});\n'
  92. AFTER = '.forEach(function(variable) {swf.addVariable(variable[0], variable[1]);});'
  93. m = re.search(re.escape(BEFORE) + '(.*?)' + re.escape(AFTER), webpage)
  94. if not m:
  95. m_msg = re.search(r'class="[^"]*uiInterstitialContent[^"]*"><div>(.*?)</div>', webpage)
  96. if m_msg is not None:
  97. raise ExtractorError(
  98. 'The video is not available, Facebook said: "%s"' % m_msg.group(1),
  99. expected=True)
  100. else:
  101. raise ExtractorError('Cannot parse data')
  102. data = dict(json.loads(m.group(1)))
  103. params_raw = compat_urllib_parse.unquote(data['params'])
  104. params = json.loads(params_raw)
  105. video_data = params['video_data'][0]
  106. video_url = video_data.get('hd_src')
  107. if not video_url:
  108. video_url = video_data['sd_src']
  109. if not video_url:
  110. raise ExtractorError('Cannot find video URL')
  111. video_duration = int(video_data['video_duration'])
  112. thumbnail = video_data['thumbnail_src']
  113. video_title = self._html_search_regex(
  114. r'<h2 class="uiHeaderTitle">([^<]*)</h2>', webpage, 'title')
  115. info = {
  116. 'id': video_id,
  117. 'title': video_title,
  118. 'url': video_url,
  119. 'ext': 'mp4',
  120. 'duration': video_duration,
  121. 'thumbnail': thumbnail,
  122. }
  123. return [info]