]> Raphaƫl G. Git Repositories - youtubedl/blob - youtube_dl/extractor/facebook.py
Imported Upstream version 2013.06.26
[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://login.facebook.com/login.php?m&next=http%3A%2F%2Fm.facebook.com%2Fhome.php&'
23 _NETRC_MACHINE = 'facebook'
24 IE_NAME = u'facebook'
25
26 def report_login(self):
27 """Report attempt to log in."""
28 self.to_screen(u'Logging in')
29
30 def _real_initialize(self):
31 if self._downloader is None:
32 return
33
34 useremail = None
35 password = None
36 downloader_params = self._downloader.params
37
38 # Attempt to use provided username and password or .netrc data
39 if downloader_params.get('username', None) is not None:
40 useremail = downloader_params['username']
41 password = downloader_params['password']
42 elif downloader_params.get('usenetrc', False):
43 try:
44 info = netrc.netrc().authenticators(self._NETRC_MACHINE)
45 if info is not None:
46 useremail = info[0]
47 password = info[2]
48 else:
49 raise netrc.NetrcParseError('No authenticators for %s' % self._NETRC_MACHINE)
50 except (IOError, netrc.NetrcParseError) as err:
51 self._downloader.report_warning(u'parsing .netrc: %s' % compat_str(err))
52 return
53
54 if useremail is None:
55 return
56
57 # Log in
58 login_form = {
59 'email': useremail,
60 'pass': password,
61 'login': 'Log+In'
62 }
63 request = compat_urllib_request.Request(self._LOGIN_URL, compat_urllib_parse.urlencode(login_form))
64 try:
65 self.report_login()
66 login_results = compat_urllib_request.urlopen(request).read()
67 if re.search(r'<form(.*)name="login"(.*)</form>', login_results) is not None:
68 self._downloader.report_warning(u'unable to log in: bad username/password, or exceded login rate limit (~3/min). Check credentials or wait.')
69 return
70 except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
71 self._downloader.report_warning(u'unable to log in: %s' % compat_str(err))
72 return
73
74 def _real_extract(self, url):
75 mobj = re.match(self._VALID_URL, url)
76 if mobj is None:
77 raise ExtractorError(u'Invalid URL: %s' % url)
78 video_id = mobj.group('ID')
79
80 url = 'https://www.facebook.com/video/video.php?v=%s' % video_id
81 webpage = self._download_webpage(url, video_id)
82
83 BEFORE = '{swf.addParam(param[0], param[1]);});\n'
84 AFTER = '.forEach(function(variable) {swf.addVariable(variable[0], variable[1]);});'
85 m = re.search(re.escape(BEFORE) + '(.*?)' + re.escape(AFTER), webpage)
86 if not m:
87 raise ExtractorError(u'Cannot parse data')
88 data = dict(json.loads(m.group(1)))
89 params_raw = compat_urllib_parse.unquote(data['params'])
90 params = json.loads(params_raw)
91 video_data = params['video_data'][0]
92 video_url = video_data.get('hd_src')
93 if not video_url:
94 video_url = video_data['sd_src']
95 if not video_url:
96 raise ExtractorError(u'Cannot find video URL')
97 video_duration = int(video_data['video_duration'])
98 thumbnail = video_data['thumbnail_src']
99
100 video_title = self._html_search_regex('<h2 class="uiHeaderTitle">([^<]+)</h2>',
101 webpage, u'title')
102
103 info = {
104 'id': video_id,
105 'title': video_title,
106 'url': video_url,
107 'ext': 'mp4',
108 'duration': video_duration,
109 'thumbnail': thumbnail,
110 }
111 return [info]