2
0

facebook.py 12 KB

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