]> Raphaƫl G. Git Repositories - youtubedl/blob - youtube-dl
Imported Upstream version 2006.09.25
[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 # Exit status constants
39 exit_failure = 1
40 exit_success = 0
41
42 # Global constants
43 const_video_url_str = 'http://www.youtube.com/watch?v=%s'
44 const_video_url_re = re.compile(r'http://(?:www\.)?youtube\.com/(?:v/|(?:watch(?:\.php)?)?\?v=)([^&]+).*')
45 const_login_url_str = 'http://www.youtube.com/signup?next=/'
46 const_login_post_str = 'current_form=loginForm&next=%%2F&username=%s&password=%s&action_login=Log+In'
47 const_age_url_str = 'http://www.youtube.com/verify_age?next_url=/watch%%3Fv%%3D%s'
48 const_age_post_str = 'next_url=%%2Fwatch%%3Fv%%3D%s&action_confirm=Confirm'
49 const_video_url_params_re = re.compile(r'player2\.swf\?([^"]+)"', re.M)
50 const_video_url_real_str = 'http://www.youtube.com/get_video?%s'
51 const_1k = 1024
52 const_block_size = 10 * const_1k
53
54 # Print error message, followed by standard advice information, and then exit
55 def error_advice_exit(error_text):
56 global exit_failure
57 sys.stderr.write('Error: %s.\n' % error_text)
58 sys.stderr.write('Try again several times. It may be a temporal problem.\n')
59 sys.stderr.write('Other typical problems:\n\n')
60 sys.stderr.write('\tVideo no longer exists.\n')
61 sys.stderr.write('\tVideo requires age confirmation but you did not provide an account.\n')
62 sys.stderr.write('\tYou provided the account data, but it is not valid.\n')
63 sys.stderr.write('\tThe connection was cut suddenly for some reason.\n')
64 sys.stderr.write('\tYouTube changed their system, and the program no longer works.\n')
65 sys.stderr.write('\nTry to confirm you are able to view the video using a web browser.\n')
66 sys.stderr.write('Use the same video URL and account information, if needed, with this program.\n')
67 sys.stderr.write('When using a proxy, make sure http_proxy has http://host:port format.\n')
68 sys.stderr.write('Try again several times and contact me if the problem persists.\n')
69 sys.exit(exit_failure)
70
71 # Wrapper to create custom requests with typical headers
72 def request_create(url, data=None):
73 retval = urllib2.Request(url)
74 if not data is None:
75 retval.add_data(data)
76 # Try to mimic Firefox, at least a little bit
77 retval.add_header('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.0.6) Gecko/20060728 Firefox/1.5.0.6')
78 retval.add_header('Accept-Charset', 'ISO-8859-1,utf-8;q=0.7,*;q=0.7')
79 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')
80 retval.add_header('Accept-Language', 'en-us,en;q=0.5')
81 return retval
82
83 # Perform a request, process headers and return response
84 def perform_request(url, data=None):
85 request = request_create(url, data)
86 response = urllib2.urlopen(request)
87 return response
88
89 # Convert bytes to KiB
90 def to_k(bytes):
91 global const_1k
92 return bytes / const_1k
93
94 # Conditional print
95 def cond_print(str):
96 global cmdl_opts
97 if not cmdl_opts.quiet:
98 sys.stdout.write(str)
99 sys.stdout.flush()
100
101 # Create the command line options parser and parse command line
102 cmdl_usage = 'usage: %prog [options] video_url'
103 cmdl_version = '2006.09.25'
104 cmdl_parser = optparse.OptionParser(usage=cmdl_usage, version=cmdl_version, conflict_handler='resolve')
105 cmdl_parser.add_option('-h', '--help', action='help', help='print this help text and exit')
106 cmdl_parser.add_option('-v', '--version', action='version', help='print program version and exit')
107 cmdl_parser.add_option('-u', '--username', dest='username', metavar='USERNAME', help='account username')
108 cmdl_parser.add_option('-p', '--password', dest='password', metavar='PASSWORD', help='account password')
109 cmdl_parser.add_option('-o', '--output', dest='outfile', metavar='FILE', help='output video file name')
110 cmdl_parser.add_option('-q', '--quiet', action='store_true', dest='quiet', help='activates quiet mode')
111 cmdl_parser.add_option('-s', '--simulate', action='store_true', dest='simulate', help='do not download video')
112 (cmdl_opts, cmdl_args) = cmdl_parser.parse_args()
113
114 # Get video URL
115 if len(cmdl_args) != 1:
116 cmdl_parser.print_help()
117 sys.exit(exit_failure)
118 video_url_cmdl = cmdl_args[0]
119
120 # Verify video URL format and convert to "standard" format
121 video_url_mo = const_video_url_re.match(video_url_cmdl)
122 if video_url_mo is None:
123 sys.exit('Error: URL does not seem to be a youtube video URL. If it is, report a bug.')
124 video_url_id = video_url_mo.group(1)
125 video_url = const_video_url_str % video_url_id
126
127 # Check conflicting options
128 if not cmdl_opts.outfile is None and cmdl_opts.simulate:
129 sys.stderr.write('Warning: video file name given but will not be used.\n')
130
131 # Get output file name
132 if cmdl_opts.outfile is None:
133 video_filename = '%s.flv' % video_url_id
134 else:
135 video_filename = cmdl_opts.outfile
136
137 # Check name
138 if not video_filename.lower().endswith('.flv'):
139 sys.stderr.write('Warning: video file name does not end in .flv\n')
140
141 # Verify both or none present
142 if ((cmdl_opts.username is None and not cmdl_opts.password is None) or
143 (not cmdl_opts.username is None and cmdl_opts.password is None)):
144 sys.exit('Error: both username and password must be given, or none.')
145
146 # Test writable file
147 if not cmdl_opts.simulate:
148 try:
149 disk_test = open(video_filename, 'wb')
150 disk_test.close()
151
152 except (OSError, IOError):
153 sys.exit('Error: unable to open %s for writing.' % video_filename)
154
155 # Install cookie and proxy handlers
156 urllib2.install_opener(urllib2.build_opener(urllib2.HTTPCookieProcessor()))
157 urllib2.install_opener(urllib2.build_opener(urllib2.ProxyHandler()))
158
159 # Login and confirm age if needed
160 if not cmdl_opts.username is None:
161 try:
162 # Log in
163 cond_print('Logging in... ')
164 perform_request(const_login_url_str, const_login_post_str % (cmdl_opts.username, cmdl_opts.password)).read()
165 cond_print('done.\n')
166
167 except (urllib2.URLError, ValueError, httplib.HTTPException, TypeError):
168 cond_print('failed.\n')
169 error_advice_exit('unable to login')
170
171 except KeyboardInterrupt:
172 sys.exit('\n')
173
174 try:
175 # Get age confirmation cookie
176 cond_print('Confirming age... ')
177 perform_request(const_age_url_str % video_url_id, const_age_post_str % video_url_id).read()
178 cond_print('done.\n')
179
180 except (urllib2.URLError, ValueError, httplib.HTTPException, TypeError):
181 cond_print('failed.\n')
182 error_advice_exit('unable to confirm age')
183
184 except KeyboardInterrupt:
185 sys.exit('\n')
186
187 # Retrieve video webpage
188 try:
189 cond_print('Retrieving video webpage... ')
190 video_webpage = perform_request(video_url).read()
191 cond_print('done.\n')
192
193 except (urllib2.URLError, ValueError, httplib.HTTPException, TypeError):
194 cond_print('failed.\n')
195 error_advice_exit('unable to download video webpage')
196
197 except KeyboardInterrupt:
198 sys.exit('\n')
199
200 # Extract needed video URL parameters
201 try:
202 cond_print('Extracting video URL parameters... ')
203 video_url_params_mo = const_video_url_params_re.search(video_webpage)
204
205 if video_url_params_mo is None:
206 cond_print('failed.\n')
207 error_advice_exit('unable to extract URL parameters')
208
209 video_url_params = video_url_params_mo.group(1)
210 video_url_real = const_video_url_real_str % video_url_params
211 cond_print('done.\n')
212
213 except KeyboardInterrupt:
214 sys.exit('\n')
215
216 # Retrieve video data
217 try:
218 video_data = perform_request(video_url_real)
219 cond_print('Video data found at %s\n' % video_data.geturl())
220
221 # Abort here if in simulate mode
222 if cmdl_opts.simulate:
223 sys.exit()
224
225 cond_print('Retrieving video data... ')
226 video_file = open(video_filename, 'wb')
227 try:
228 video_len_str = '%sk' % to_k(int(video_data.info()['Content-length']))
229 except KeyError:
230 video_len_str = '(unknown)'
231
232 byte_counter = 0
233 video_block = video_data.read(const_block_size)
234 while len(video_block) != 0:
235 byte_counter += len(video_block)
236 video_file.write(video_block)
237 cond_print('\rRetrieving video data... %sk of %s ' % (to_k(byte_counter), video_len_str))
238 video_block = video_data.read(const_block_size)
239
240 video_file.close()
241 cond_print('done.\n')
242 cond_print('Video data saved to %s\n' % video_filename)
243 sys.exit()
244
245 except (urllib2.URLError, ValueError, httplib.HTTPException, TypeError):
246 cond_print('failed.\n')
247 error_advice_exit('unable to download video data')
248
249 except KeyboardInterrupt:
250 sys.exit('\n')