]> Raphaƫl G. Git Repositories - youtubedl/blob - youtube_dl/extractor/facebook.py
Update changelog.
[youtubedl] / youtube_dl / extractor / facebook.py
1 import json
2 import netrc
3 import re
4 import socket
5
6 from .common import InfoExtractor
7 from ..utils import (
8 compat_http_client,
9 compat_str,
10 compat_urllib_error,
11 compat_urllib_parse,
12 compat_urllib_request,
13
14 ExtractorError,
15 )
16
17
18 class FacebookIE(InfoExtractor):
19 """Information Extractor for Facebook"""
20
21 _VALID_URL = r'^(?:https?://)?(?:\w+\.)?facebook\.com/(?:video/video|photo)\.php\?(?:.*?)v=(?P<ID>\d+)(?:.*)'
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 = u'facebook'
26 _TEST = {
27 u'url': u'https://www.facebook.com/photo.php?v=120708114770723',
28 u'file': u'120708114770723.mp4',
29 u'md5': u'48975a41ccc4b7a581abd68651c1a5a8',
30 u'info_dict': {
31 u"duration": 279,
32 u"title": u"PEOPLE ARE AWESOME 2013"
33 }
34 }
35
36 def report_login(self):
37 """Report attempt to log in."""
38 self.to_screen(u'Logging in')
39
40 def _login(self):
41 (useremail, password) = self._get_login_info()
42 if useremail is None:
43 return
44
45 login_page_req = compat_urllib_request.Request(self._LOGIN_URL)
46 login_page_req.add_header('Cookie', 'locale=en_US')
47 self.report_login()
48 login_page = self._download_webpage(login_page_req, None, note=False,
49 errnote=u'Unable to download login page')
50 lsd = self._search_regex(r'"lsd":"(\w*?)"', login_page, u'lsd')
51 lgnrnd = self._search_regex(r'name="lgnrnd" value="([^"]*?)"', login_page, u'lgnrnd')
52
53 login_form = {
54 'email': useremail,
55 'pass': password,
56 'lsd': lsd,
57 'lgnrnd': lgnrnd,
58 'next': 'http://facebook.com/home.php',
59 'default_persistent': '0',
60 'legacy_return': '1',
61 'timezone': '-60',
62 'trynum': '1',
63 }
64 request = compat_urllib_request.Request(self._LOGIN_URL, compat_urllib_parse.urlencode(login_form))
65 request.add_header('Content-Type', 'application/x-www-form-urlencoded')
66 try:
67 login_results = compat_urllib_request.urlopen(request).read()
68 if re.search(r'<form(.*)name="login"(.*)</form>', login_results) is not None:
69 self._downloader.report_warning(u'unable to log in: bad username/password, or exceded login rate limit (~3/min). Check credentials or wait.')
70 return
71
72 check_form = {
73 'fb_dtsg': self._search_regex(r'"fb_dtsg":"(.*?)"', login_results, u'fb_dtsg'),
74 'nh': self._search_regex(r'name="nh" value="(\w*?)"', login_results, u'nh'),
75 'name_action_selected': 'dont_save',
76 'submit[Continue]': self._search_regex(r'<input value="(.*?)" name="submit\[Continue\]"', login_results, u'continue'),
77 }
78 check_req = compat_urllib_request.Request(self._CHECKPOINT_URL, compat_urllib_parse.urlencode(check_form))
79 check_req.add_header('Content-Type', 'application/x-www-form-urlencoded')
80 check_response = compat_urllib_request.urlopen(check_req).read()
81 if re.search(r'id="checkpointSubmitButton"', check_response) is not None:
82 self._downloader.report_warning(u'Unable to confirm login, you have to login in your brower and authorize the login.')
83 except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
84 self._downloader.report_warning(u'unable to log in: %s' % compat_str(err))
85 return
86
87 def _real_initialize(self):
88 self._login()
89
90 def _real_extract(self, url):
91 mobj = re.match(self._VALID_URL, url)
92 if mobj is None:
93 raise ExtractorError(u'Invalid URL: %s' % url)
94 video_id = mobj.group('ID')
95
96 url = 'https://www.facebook.com/video/video.php?v=%s' % video_id
97 webpage = self._download_webpage(url, video_id)
98
99 BEFORE = '{swf.addParam(param[0], param[1]);});\n'
100 AFTER = '.forEach(function(variable) {swf.addVariable(variable[0], variable[1]);});'
101 m = re.search(re.escape(BEFORE) + '(.*?)' + re.escape(AFTER), webpage)
102 if not m:
103 m_msg = re.search(r'class="[^"]*uiInterstitialContent[^"]*"><div>(.*?)</div>', webpage)
104 if m_msg is not None:
105 raise ExtractorError(
106 u'The video is not available, Facebook said: "%s"' % m_msg.group(1),
107 expected=True)
108 else:
109 raise ExtractorError(u'Cannot parse data')
110 data = dict(json.loads(m.group(1)))
111 params_raw = compat_urllib_parse.unquote(data['params'])
112 params = json.loads(params_raw)
113 video_data = params['video_data'][0]
114 video_url = video_data.get('hd_src')
115 if not video_url:
116 video_url = video_data['sd_src']
117 if not video_url:
118 raise ExtractorError(u'Cannot find video URL')
119 video_duration = int(video_data['video_duration'])
120 thumbnail = video_data['thumbnail_src']
121
122 video_title = self._html_search_regex(
123 r'<h2 class="uiHeaderTitle">([^<]*)</h2>', webpage, u'title')
124
125 info = {
126 'id': video_id,
127 'title': video_title,
128 'url': video_url,
129 'ext': 'mp4',
130 'duration': video_duration,
131 'thumbnail': thumbnail,
132 }
133 return [info]