Merge branch 'master' of github.com:rg3/youtube-dl
[youtube-dl] / youtube_dl / extractor / metacafe.py
1 import re
2 import socket
3
4 from .common import InfoExtractor
5 from ..utils import (
6     compat_http_client,
7     compat_parse_qs,
8     compat_urllib_error,
9     compat_urllib_parse,
10     compat_urllib_request,
11     compat_str,
12     determine_ext,
13     ExtractorError,
14 )
15
16 class MetacafeIE(InfoExtractor):
17     """Information Extractor for metacafe.com."""
18
19     _VALID_URL = r'(?:http://)?(?:www\.)?metacafe\.com/watch/([^/]+)/([^/]+)/.*'
20     _DISCLAIMER = 'http://www.metacafe.com/family_filter/'
21     _FILTER_POST = 'http://www.metacafe.com/f/index.php?inputType=filter&controllerGroup=user'
22     IE_NAME = u'metacafe'
23     _TESTS = [
24     # Youtube video
25     {
26         u"add_ie": ["Youtube"],
27         u"url":  u"http://metacafe.com/watch/yt-_aUehQsCQtM/the_electric_company_short_i_pbs_kids_go/",
28         u"file":  u"_aUehQsCQtM.mp4",
29         u"info_dict": {
30             u"upload_date": u"20090102",
31             u"title": u"The Electric Company | \"Short I\" | PBS KIDS GO!",
32             u"description": u"md5:2439a8ef6d5a70e380c22f5ad323e5a8",
33             u"uploader": u"PBS",
34             u"uploader_id": u"PBS"
35         }
36     },
37     # Normal metacafe video
38     {
39         u'url': u'http://www.metacafe.com/watch/11121940/news_stuff_you_wont_do_with_your_playstation_4/',
40         u'md5': u'6e0bca200eaad2552e6915ed6fd4d9ad',
41         u'info_dict': {
42             u'id': u'11121940',
43             u'ext': u'mp4',
44             u'title': u'News: Stuff You Won\'t Do with Your PlayStation 4',
45             u'uploader': u'ign',
46             u'description': u'Sony released a massive FAQ on the PlayStation Blog detailing the PS4\'s capabilities and limitations.',
47         },
48     },
49     # AnyClip video
50     {
51         u"url": u"http://www.metacafe.com/watch/an-dVVXnuY7Jh77J/the_andromeda_strain_1971_stop_the_bomb_part_3/",
52         u"file": u"an-dVVXnuY7Jh77J.mp4",
53         u"info_dict": {
54             u"title": u"The Andromeda Strain (1971): Stop the Bomb Part 3",
55             u"uploader": u"anyclip",
56             u"description": u"md5:38c711dd98f5bb87acf973d573442e67",
57         },
58     },
59     # age-restricted video
60     {
61         u'url': u'http://www.metacafe.com/watch/5186653/bbc_internal_christmas_tape_79_uncensored_outtakes_etc/',
62         u'md5': u'98dde7c1a35d02178e8ab7560fe8bd09',
63         u'info_dict': {
64             u'id': u'5186653',
65             u'ext': u'mp4',
66             u'title': u'BBC INTERNAL Christmas Tape \'79 - UNCENSORED Outtakes, Etc.',
67             u'uploader': u'Dwayne Pipe',
68             u'description': u'md5:950bf4c581e2c059911fa3ffbe377e4b',
69             u'age_limit': 18,
70         },
71     },
72     # cbs video
73     {
74         u'url': u'http://www.metacafe.com/watch/cb-0rOxMBabDXN6/samsung_galaxy_note_2_samsungs_next_generation_phablet/',
75         u'info_dict': {
76             u'id': u'0rOxMBabDXN6',
77             u'ext': u'flv',
78             u'title': u'Samsung Galaxy Note 2: Samsung\'s next-generation phablet',
79             u'description': u'md5:54d49fac53d26d5a0aaeccd061ada09d',
80             u'duration': 129,
81         },
82         u'params': {
83             # rtmp download
84             u'skip_download': True,
85         },
86     },
87     ]
88
89
90     def report_disclaimer(self):
91         """Report disclaimer retrieval."""
92         self.to_screen(u'Retrieving disclaimer')
93
94     def _real_initialize(self):
95         # Retrieve disclaimer
96         request = compat_urllib_request.Request(self._DISCLAIMER)
97         try:
98             self.report_disclaimer()
99             compat_urllib_request.urlopen(request).read()
100         except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
101             raise ExtractorError(u'Unable to retrieve disclaimer: %s' % compat_str(err))
102
103         # Confirm age
104         disclaimer_form = {
105             'filters': '0',
106             'submit': "Continue - I'm over 18",
107             }
108         request = compat_urllib_request.Request(self._FILTER_POST, compat_urllib_parse.urlencode(disclaimer_form))
109         request.add_header('Content-Type', 'application/x-www-form-urlencoded')
110         try:
111             self.report_age_confirmation()
112             compat_urllib_request.urlopen(request).read()
113         except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
114             raise ExtractorError(u'Unable to confirm age: %s' % compat_str(err))
115
116     def _real_extract(self, url):
117         # Extract id and simplified title from URL
118         mobj = re.match(self._VALID_URL, url)
119         if mobj is None:
120             raise ExtractorError(u'Invalid URL: %s' % url)
121
122         video_id = mobj.group(1)
123
124         # the video may come from an external site
125         m_external = re.match('^(\w{2})-(.*)$', video_id)
126         if m_external is not None:
127             prefix, ext_id = m_external.groups()
128             # Check if video comes from YouTube
129             if prefix == 'yt':
130                 return self.url_result('http://www.youtube.com/watch?v=%s' % ext_id, 'Youtube')
131             # CBS videos use theplatform.com
132             if prefix == 'cb':
133                 return self.url_result('theplatform:%s' % ext_id, 'ThePlatform')
134
135         # Retrieve video webpage to extract further information
136         req = compat_urllib_request.Request('http://www.metacafe.com/watch/%s/' % video_id)
137
138         # AnyClip videos require the flashversion cookie so that we get the link
139         # to the mp4 file
140         mobj_an = re.match(r'^an-(.*?)$', video_id)
141         if mobj_an:
142             req.headers['Cookie'] = 'flashVersion=0;'
143         webpage = self._download_webpage(req, video_id)
144
145         # Extract URL, uploader and title from webpage
146         self.report_extraction(video_id)
147         mobj = re.search(r'(?m)&mediaURL=([^&]+)', webpage)
148         if mobj is not None:
149             mediaURL = compat_urllib_parse.unquote(mobj.group(1))
150             video_ext = mediaURL[-3:]
151
152             # Extract gdaKey if available
153             mobj = re.search(r'(?m)&gdaKey=(.*?)&', webpage)
154             if mobj is None:
155                 video_url = mediaURL
156             else:
157                 gdaKey = mobj.group(1)
158                 video_url = '%s?__gda__=%s' % (mediaURL, gdaKey)
159         else:
160             mobj = re.search(r'<video src="([^"]+)"', webpage)
161             if mobj:
162                 video_url = mobj.group(1)
163                 video_ext = 'mp4'
164             else:
165                 mobj = re.search(r' name="flashvars" value="(.*?)"', webpage)
166                 if mobj is None:
167                     raise ExtractorError(u'Unable to extract media URL')
168                 vardict = compat_parse_qs(mobj.group(1))
169                 if 'mediaData' not in vardict:
170                     raise ExtractorError(u'Unable to extract media URL')
171                 mobj = re.search(r'"mediaURL":"(?P<mediaURL>http.*?)",(.*?)"key":"(?P<key>.*?)"', vardict['mediaData'][0])
172                 if mobj is None:
173                     raise ExtractorError(u'Unable to extract media URL')
174                 mediaURL = mobj.group('mediaURL').replace('\\/', '/')
175                 video_url = '%s?__gda__=%s' % (mediaURL, mobj.group('key'))
176                 video_ext = determine_ext(video_url)
177
178         video_title = self._html_search_regex(r'(?im)<title>(.*) - Video</title>', webpage, u'title')
179         description = self._og_search_description(webpage)
180         video_uploader = self._html_search_regex(
181                 r'submitter=(.*?);|googletag\.pubads\(\)\.setTargeting\("(?:channel|submiter)","([^"]+)"\);',
182                 webpage, u'uploader nickname', fatal=False)
183
184         if re.search(r'"contentRating":"restricted"', webpage) is not None:
185             age_limit = 18
186         else:
187             age_limit = 0
188
189         return {
190             '_type':    'video',
191             'id':       video_id,
192             'url':      video_url,
193             'description': description,
194             'uploader': video_uploader,
195             'upload_date':  None,
196             'title':    video_title,
197             'ext':      video_ext,
198             'age_limit': age_limit,
199         }