]> Raphaƫl G. Git Repositories - youtubedl/blob - youtube-dl
Imported Upstream version 2006.11.12
[youtubedl] / youtube-dl
1 #!/usr/bin/env python
2 #
3 # Copyright (c) 2006 Ricardo Garcia Gonzalez
4 #
5 # Permission is hereby granted, free of charge, to any person obtaining a
6 # copy of this software and associated documentation files (the "Software"),
7 # to deal in the Software without restriction, including without limitation
8 # the rights to use, copy, modify, merge, publish, distribute, sublicense,
9 # and/or sell copies of the Software, and to permit persons to whom the
10 # Software is furnished to do so, subject to the following conditions:
11 #
12 # The above copyright notice and this permission notice shall be included
13 # in all copies or substantial portions of the Software.
14 #
15 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
18 # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
19 # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
20 # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
21 # OTHER DEALINGS IN THE SOFTWARE.
22 #
23 # Except as contained in this notice, the name(s) of the above copyright
24 # holders shall not be used in advertising or otherwise to promote the
25 # sale, use or other dealings in this Software without prior written
26 # authorization.
27 #
28 import sys
29 import optparse
30 import httplib
31 import urllib2
32 import re
33
34 # First off, check Python and refuse to run
35 if sys.hexversion < 0x020400f0:
36 sys.exit('Error: Python 2.4 or later needed to run the program')
37
38 # Global constants
39 const_video_url_str = 'http://www.youtube.com/watch?v=%s'
40 const_video_url_re = re.compile(r'http://(?:www\d*\.)?youtube\.com/(?:v/|(?:watch(?:\.php)?)?\?v=)([^&]+).*')
41 const_login_url_str = 'http://www.youtube.com/login?next=/watch%%3Fv%%3D%s'
42 const_login_post_str = 'current_form=loginForm&next=%%2Fwatch%%3Fv%%3D%s&username=%s&password=%s&action_login=Log+In'
43 const_age_url_str = 'http://www.youtube.com/verify_age?next_url=/watch%%3Fv%%3D%s'
44 const_age_post_str = 'next_url=%%2Fwatch%%3Fv%%3D%s&action_confirm=Confirm'
45 const_video_url_params_re = re.compile(r'player2\.swf\?([^"]+)"', re.M)
46 const_video_url_real_str = 'http://www.youtube.com/get_video?%s'
47 const_1k = 1024
48 const_block_size = 10 * const_1k
49
50 # Print error message, followed by standard advice information, and then exit
51 def error_advice_exit(error_text):
52 sys.stderr.write('Error: %s.\n' % error_text)
53 sys.stderr.write('Try again several times. It may be a temporal problem.\n')
54 sys.stderr.write('Other typical problems:\n\n')
55 sys.stderr.write('\tVideo no longer exists.\n')
56 sys.stderr.write('\tVideo requires age confirmation but you did not provide an account.\n')
57 sys.stderr.write('\tYou provided the account data, but it is not valid.\n')
58 sys.stderr.write('\tThe connection was cut suddenly for some reason.\n')
59 sys.stderr.write('\tYouTube changed their system, and the program no longer works.\n')
60 sys.stderr.write('\nTry to confirm you are able to view the video using a web browser.\n')
61 sys.stderr.write('Use the same video URL and account information, if needed, with this program.\n')
62 sys.stderr.write('When using a proxy, make sure http_proxy has http://host:port format.\n')
63 sys.stderr.write('Try again several times and contact me if the problem persists.\n')
64 sys.exit('\n')
65
66 # Wrapper to create custom requests with typical headers
67 def request_create(url, data=None):
68 retval = urllib2.Request(url)
69 if not data is None:
70 retval.add_data(data)
71 # Try to mimic Firefox, at least a little bit
72 retval.add_header('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1) Gecko/20061010 Firefox/2.0')
73 retval.add_header('Accept-Charset', 'ISO-8859-1,utf-8;q=0.7,*;q=0.7')
74 retval.add_header('Accept', 'text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5')
75 retval.add_header('Accept-Language', 'en-us,en;q=0.5')
76 return retval
77
78 # Perform a request, process headers and return response
79 def perform_request(url, data=None):
80 request = request_create(url, data)
81 response = urllib2.urlopen(request)
82 return response
83
84 # Convert bytes to KiB
85 def to_k(bytes):
86 global const_1k
87 return bytes / const_1k
88
89 # Conditional print
90 def cond_print(str):
91 global cmdl_opts
92 if not cmdl_opts.quiet:
93 sys.stdout.write(str)
94 sys.stdout.flush()
95
96 # Create the command line options parser and parse command line
97 cmdl_usage = 'usage: %prog [options] video_url'
98 cmdl_version = '2006.11.12'
99 cmdl_parser = optparse.OptionParser(usage=cmdl_usage, version=cmdl_version, conflict_handler='resolve')
100 cmdl_parser.add_option('-h', '--help', action='help', help='print this help text and exit')
101 cmdl_parser.add_option('-v', '--version', action='version', help='print program version and exit')
102 cmdl_parser.add_option('-u', '--username', dest='username', metavar='USERNAME', help='account username')
103 cmdl_parser.add_option('-p', '--password', dest='password', metavar='PASSWORD', help='account password')
104 cmdl_parser.add_option('-o', '--output', dest='outfile', metavar='FILE', help='output video file name')
105 cmdl_parser.add_option('-q', '--quiet', action='store_true', dest='quiet', help='activates quiet mode')
106 cmdl_parser.add_option('-s', '--simulate', action='store_true', dest='simulate', help='do not download video')
107 (cmdl_opts, cmdl_args) = cmdl_parser.parse_args()
108
109 # Get video URL
110 if len(cmdl_args) != 1:
111 cmdl_parser.print_help()
112 sys.exit('\n')
113 video_url_cmdl = cmdl_args[0]
114
115 # Verify video URL format and convert to "standard" format
116 video_url_mo = const_video_url_re.match(video_url_cmdl)
117 if video_url_mo is None:
118 sys.exit('Error: URL does not seem to be a youtube video URL. If it is, report a bug.')
119 video_url_id = video_url_mo.group(1)
120 video_url = const_video_url_str % video_url_id
121
122 # Check conflicting options
123 if not cmdl_opts.outfile is None and cmdl_opts.simulate:
124 sys.stderr.write('Warning: video file name given but will not be used.\n')
125
126 # Get output file name
127 if cmdl_opts.outfile is None:
128 video_filename = '%s.flv' % video_url_id
129 else:
130 video_filename = cmdl_opts.outfile
131
132 # Check name
133 if not video_filename.lower().endswith('.flv'):
134 sys.stderr.write('Warning: video file name does not end in .flv\n')
135
136 # Verify both or none present
137 if ((cmdl_opts.username is None and not cmdl_opts.password is None) or
138 (not cmdl_opts.username is None and cmdl_opts.password is None)):
139 sys.exit('Error: both username and password must be given, or none.')
140
141 # Test writable file
142 if not cmdl_opts.simulate:
143 try:
144 disk_test = open(video_filename, 'wb')
145 disk_test.close()
146
147 except (OSError, IOError):
148 sys.exit('Error: unable to open %s for writing.' % video_filename)
149
150 # Install cookie and proxy handlers
151 urllib2.install_opener(urllib2.build_opener(urllib2.ProxyHandler()))
152 urllib2.install_opener(urllib2.build_opener(urllib2.HTTPCookieProcessor()))
153
154 # Login and confirm age if needed
155 if not cmdl_opts.username is None:
156 try:
157 # Log in
158 cond_print('Logging in... ')
159 perform_request(const_login_url_str % video_url_id, const_login_post_str % (video_url_id, cmdl_opts.username, cmdl_opts.password)).read()
160 cond_print('done.\n')
161
162 except (urllib2.URLError, ValueError, httplib.HTTPException, TypeError):
163 cond_print('failed.\n')
164 error_advice_exit('unable to login')
165
166 except KeyboardInterrupt:
167 sys.exit('\n')
168
169 try:
170 # Get age confirmation cookie
171 cond_print('Confirming age... ')
172 perform_request(const_age_url_str % video_url_id, const_age_post_str % video_url_id).read()
173 cond_print('done.\n')
174
175 except (urllib2.URLError, ValueError, httplib.HTTPException, TypeError):
176 cond_print('failed.\n')
177 error_advice_exit('unable to confirm age')
178
179 except KeyboardInterrupt:
180 sys.exit('\n')
181
182 # Retrieve video webpage
183 try:
184 cond_print('Retrieving video webpage... ')
185 video_webpage = perform_request(video_url).read()
186 cond_print('done.\n')
187
188 except (urllib2.URLError, ValueError, httplib.HTTPException, TypeError):
189 cond_print('failed.\n')
190 error_advice_exit('unable to download video webpage')
191
192 except KeyboardInterrupt:
193 sys.exit('\n')
194
195 # Extract needed video URL parameters
196 try:
197 cond_print('Extracting video URL parameters... ')
198 video_url_params_mo = const_video_url_params_re.search(video_webpage)
199
200 if video_url_params_mo is None:
201 cond_print('failed.\n')
202 error_advice_exit('unable to extract URL parameters')
203
204 video_url_params = video_url_params_mo.group(1)
205 video_url_real = const_video_url_real_str % video_url_params
206 cond_print('done.\n')
207
208 except KeyboardInterrupt:
209 sys.exit('\n')
210
211 # Retrieve video data
212 try:
213 video_data = perform_request(video_url_real)
214 cond_print('Video data found at %s\n' % video_data.geturl())
215
216 # Abort here if in simulate mode
217 if cmdl_opts.simulate:
218 sys.exit()
219
220 cond_print('Retrieving video data... ')
221 video_file = open(video_filename, 'wb')
222 try:
223 video_len_str = '%sk' % to_k(int(video_data.info()['Content-length']))
224 except KeyError:
225 video_len_str = '(unknown)'
226
227 byte_counter = 0
228 video_block = video_data.read(const_block_size)
229 while len(video_block) != 0:
230 byte_counter += len(video_block)
231 video_file.write(video_block)
232 cond_print('\rRetrieving video data... %sk of %s ' % (to_k(byte_counter), video_len_str))
233 video_block = video_data.read(const_block_size)
234
235 video_file.close()
236 cond_print('done.\n')
237 cond_print('Video data saved to %s\n' % video_filename)
238 sys.exit()
239
240 except (urllib2.URLError, ValueError, httplib.HTTPException, TypeError):
241 cond_print('failed.\n')
242 error_advice_exit('unable to download video data')
243
244 except KeyboardInterrupt:
245 sys.exit('\n')