facebook.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  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_etree_fromstring,
  8. compat_http_client,
  9. compat_urllib_error,
  10. compat_urllib_parse_unquote,
  11. compat_urllib_parse_unquote_plus,
  12. )
  13. from ..utils import (
  14. error_to_compat_str,
  15. ExtractorError,
  16. limit_length,
  17. sanitized_Request,
  18. urlencode_postdata,
  19. get_element_by_id,
  20. clean_html,
  21. )
  22. class FacebookIE(InfoExtractor):
  23. _VALID_URL = r'''(?x)
  24. (?:
  25. https?://
  26. (?:\w+\.)?facebook\.com/
  27. (?:[^#]*?\#!/)?
  28. (?:
  29. (?:
  30. video/video\.php|
  31. photo\.php|
  32. video\.php|
  33. video/embed
  34. )\?(?:.*?)(?:v|video_id)=|
  35. [^/]+/videos/(?:[^/]+/)?
  36. )|
  37. facebook:
  38. )
  39. (?P<id>[0-9]+)
  40. '''
  41. _LOGIN_URL = 'https://www.facebook.com/login.php?next=http%3A%2F%2Ffacebook.com%2Fhome.php&login_attempt=1'
  42. _CHECKPOINT_URL = 'https://www.facebook.com/checkpoint/?next=http%3A%2F%2Ffacebook.com%2Fhome.php&_fb_noscript=1'
  43. _NETRC_MACHINE = 'facebook'
  44. IE_NAME = 'facebook'
  45. _CHROME_USER_AGENT = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.97 Safari/537.36'
  46. _TESTS = [{
  47. 'url': 'https://www.facebook.com/video.php?v=637842556329505&fref=nf',
  48. 'md5': '6a40d33c0eccbb1af76cf0485a052659',
  49. 'info_dict': {
  50. 'id': '637842556329505',
  51. 'ext': 'mp4',
  52. 'title': 're:Did you know Kei Nishikori is the first Asian man to ever reach a Grand Slam',
  53. 'uploader': 'Tennis on Facebook',
  54. }
  55. }, {
  56. 'note': 'Video without discernible title',
  57. 'url': 'https://www.facebook.com/video.php?v=274175099429670',
  58. 'info_dict': {
  59. 'id': '274175099429670',
  60. 'ext': 'mp4',
  61. 'title': 'Facebook video #274175099429670',
  62. 'uploader': 'Asif Nawab Butt',
  63. },
  64. 'expected_warnings': [
  65. 'title'
  66. ]
  67. }, {
  68. 'note': 'Video with DASH manifest',
  69. 'url': 'https://www.facebook.com/video.php?v=957955867617029',
  70. 'info_dict': {
  71. 'id': '957955867617029',
  72. 'ext': 'mp4',
  73. 'title': 'When you post epic content on instagram.com/433 8 million followers, this is ...',
  74. 'uploader': 'Demy de Zeeuw',
  75. },
  76. }, {
  77. 'url': 'https://www.facebook.com/video.php?v=10204634152394104',
  78. 'only_matching': True,
  79. }, {
  80. 'url': 'https://www.facebook.com/amogood/videos/1618742068337349/?fref=nf',
  81. 'only_matching': True,
  82. }, {
  83. 'url': 'https://www.facebook.com/ChristyClarkForBC/videos/vb.22819070941/10153870694020942/?type=2&theater',
  84. 'only_matching': True,
  85. }, {
  86. 'url': 'facebook:544765982287235',
  87. 'only_matching': True,
  88. }]
  89. def _login(self):
  90. (useremail, password) = self._get_login_info()
  91. if useremail is None:
  92. return
  93. login_page_req = sanitized_Request(self._LOGIN_URL)
  94. self._set_cookie('facebook.com', 'locale', 'en_US')
  95. login_page = self._download_webpage(login_page_req, None,
  96. note='Downloading login page',
  97. errnote='Unable to download login page')
  98. lsd = self._search_regex(
  99. r'<input type="hidden" name="lsd" value="([^"]*)"',
  100. login_page, 'lsd')
  101. lgnrnd = self._search_regex(r'name="lgnrnd" value="([^"]*?)"', login_page, 'lgnrnd')
  102. login_form = {
  103. 'email': useremail,
  104. 'pass': password,
  105. 'lsd': lsd,
  106. 'lgnrnd': lgnrnd,
  107. 'next': 'http://facebook.com/home.php',
  108. 'default_persistent': '0',
  109. 'legacy_return': '1',
  110. 'timezone': '-60',
  111. 'trynum': '1',
  112. }
  113. request = sanitized_Request(self._LOGIN_URL, urlencode_postdata(login_form))
  114. request.add_header('Content-Type', 'application/x-www-form-urlencoded')
  115. try:
  116. login_results = self._download_webpage(request, None,
  117. note='Logging in', errnote='unable to fetch login page')
  118. if re.search(r'<form(.*)name="login"(.*)</form>', login_results) is not None:
  119. error = self._html_search_regex(
  120. r'(?s)<div[^>]+class=(["\']).*?login_error_box.*?\1[^>]*><div[^>]*>.*?</div><div[^>]*>(?P<error>.+?)</div>',
  121. login_results, 'login error', default=None, group='error')
  122. if error:
  123. raise ExtractorError('Unable to login: %s' % error, expected=True)
  124. self._downloader.report_warning('unable to log in: bad username/password, or exceeded login rate limit (~3/min). Check credentials or wait.')
  125. return
  126. fb_dtsg = self._search_regex(
  127. r'name="fb_dtsg" value="(.+?)"', login_results, 'fb_dtsg', default=None)
  128. h = self._search_regex(
  129. r'name="h"\s+(?:\w+="[^"]+"\s+)*?value="([^"]+)"', login_results, 'h', default=None)
  130. if not fb_dtsg or not h:
  131. return
  132. check_form = {
  133. 'fb_dtsg': fb_dtsg,
  134. 'h': h,
  135. 'name_action_selected': 'dont_save',
  136. }
  137. check_req = sanitized_Request(self._CHECKPOINT_URL, urlencode_postdata(check_form))
  138. check_req.add_header('Content-Type', 'application/x-www-form-urlencoded')
  139. check_response = self._download_webpage(check_req, None,
  140. note='Confirming login')
  141. if re.search(r'id="checkpointSubmitButton"', check_response) is not None:
  142. self._downloader.report_warning('Unable to confirm login, you have to login in your browser and authorize the login.')
  143. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  144. self._downloader.report_warning('unable to log in: %s' % error_to_compat_str(err))
  145. return
  146. def _real_initialize(self):
  147. self._login()
  148. def _real_extract(self, url):
  149. video_id = self._match_id(url)
  150. req = sanitized_Request('https://www.facebook.com/video/video.php?v=%s' % video_id)
  151. req.add_header('User-Agent', self._CHROME_USER_AGENT)
  152. webpage = self._download_webpage(req, video_id)
  153. video_data = None
  154. BEFORE = '{swf.addParam(param[0], param[1]);});\n'
  155. AFTER = '.forEach(function(variable) {swf.addVariable(variable[0], variable[1]);});'
  156. m = re.search(re.escape(BEFORE) + '(.*?)' + re.escape(AFTER), webpage)
  157. if m:
  158. data = dict(json.loads(m.group(1)))
  159. params_raw = compat_urllib_parse_unquote(data['params'])
  160. video_data = json.loads(params_raw)['video_data']
  161. def video_data_list2dict(video_data):
  162. ret = {}
  163. for item in video_data:
  164. format_id = item['stream_type']
  165. ret.setdefault(format_id, []).append(item)
  166. return ret
  167. if not video_data:
  168. server_js_data = self._parse_json(self._search_regex(
  169. r'handleServerJS\(({.+})\);', webpage, 'server js data'), video_id)
  170. for item in server_js_data['instances']:
  171. if item[1][0] == 'VideoConfig':
  172. video_data = video_data_list2dict(item[2][0]['videoData'])
  173. break
  174. if not video_data:
  175. m_msg = re.search(r'class="[^"]*uiInterstitialContent[^"]*"><div>(.*?)</div>', webpage)
  176. if m_msg is not None:
  177. raise ExtractorError(
  178. 'The video is not available, Facebook said: "%s"' % m_msg.group(1),
  179. expected=True)
  180. else:
  181. raise ExtractorError('Cannot parse data')
  182. formats = []
  183. for format_id, f in video_data.items():
  184. if not f or not isinstance(f, list):
  185. continue
  186. for quality in ('sd', 'hd'):
  187. for src_type in ('src', 'src_no_ratelimit'):
  188. src = f[0].get('%s_%s' % (quality, src_type))
  189. if src:
  190. formats.append({
  191. 'format_id': '%s_%s_%s' % (format_id, quality, src_type),
  192. 'url': src,
  193. 'preference': -10 if format_id == 'progressive' else 0,
  194. })
  195. dash_manifest = f[0].get('dash_manifest')
  196. if dash_manifest:
  197. formats.extend(self._parse_dash_manifest(
  198. video_id, compat_etree_fromstring(compat_urllib_parse_unquote_plus(dash_manifest)),
  199. default_ns='urn:mpeg:dash:schema:mpd:2011'))
  200. if not formats:
  201. raise ExtractorError('Cannot find video formats')
  202. self._sort_formats(formats)
  203. video_title = self._html_search_regex(
  204. r'<h2\s+[^>]*class="uiHeaderTitle"[^>]*>([^<]*)</h2>', webpage, 'title',
  205. default=None)
  206. if not video_title:
  207. video_title = self._html_search_regex(
  208. r'(?s)<span class="fbPhotosPhotoCaption".*?id="fbPhotoPageCaption"><span class="hasCaption">(.*?)</span>',
  209. webpage, 'alternative title', default=None)
  210. video_title = limit_length(video_title, 80)
  211. if not video_title:
  212. video_title = 'Facebook video #%s' % video_id
  213. uploader = clean_html(get_element_by_id('fbPhotoPageAuthorName', webpage))
  214. return {
  215. 'id': video_id,
  216. 'title': video_title,
  217. 'formats': formats,
  218. 'uploader': uploader,
  219. }
  220. class FacebookPostIE(InfoExtractor):
  221. IE_NAME = 'facebook:post'
  222. _VALID_URL = r'https?://(?:\w+\.)?facebook\.com/[^/]+/posts/(?P<id>\d+)'
  223. _TEST = {
  224. 'url': 'https://www.facebook.com/maxlayn/posts/10153807558977570',
  225. 'md5': '037b1fa7f3c2d02b7a0d7bc16031ecc6',
  226. 'info_dict': {
  227. 'id': '544765982287235',
  228. 'ext': 'mp4',
  229. 'title': '"What are you doing running in the snow?"',
  230. 'uploader': 'FailArmy',
  231. }
  232. }
  233. def _real_extract(self, url):
  234. post_id = self._match_id(url)
  235. webpage = self._download_webpage(url, post_id)
  236. entries = [
  237. self.url_result('facebook:%s' % video_id, FacebookIE.ie_key())
  238. for video_id in self._parse_json(
  239. self._search_regex(
  240. r'(["\'])video_ids\1\s*:\s*(?P<ids>\[.+?\])',
  241. webpage, 'video ids', group='ids'),
  242. post_id)]
  243. return self.playlist_result(entries, post_id)