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