3 # Copyright (c) 2006 Ricardo Garcia Gonzalez 
   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: 
  12 # The above copyright notice and this permission notice shall be included 
  13 # in all copies or substantial portions of the Software. 
  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. 
  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 
  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') 
  38 # Exit status 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' 
  52 const_block_size 
= 10 * const_1k
 
  54 # Print error message, followed by standard advice information, and then exit 
  55 def error_advice_exit(error_text
): 
  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
) 
  71 # Wrapper to create custom requests with typical headers 
  72 def request_create(url
, data
=None): 
  73         retval 
= urllib2
.Request(url
) 
  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') 
  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
) 
  89 # Convert bytes to KiB 
  92         return bytes / const_1k
 
  97         if not cmdl_opts
.quiet
: 
 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() 
 115 if len(cmdl_args
) != 1: 
 116         cmdl_parser
.print_help() 
 117         sys
.exit(exit_failure
) 
 118 video_url_cmdl 
= cmdl_args
[0] 
 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
 
 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') 
 131 # Get output file name  
 132 if cmdl_opts
.outfile 
is None: 
 133         video_filename 
= '%s.flv' % video_url_id
 
 135         video_filename 
= cmdl_opts
.outfile
 
 138 if not video_filename
.lower().endswith('.flv'): 
 139         sys
.stderr
.write('Warning: video file name does not end in .flv\n') 
 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.') 
 147 if not cmdl_opts
.simulate
: 
 149                 disk_test 
= open(video_filename
, 'wb') 
 152         except (OSError, IOError): 
 153                 sys
.exit('Error: unable to open %s for writing.' % video_filename
) 
 155 # Install cookie and proxy handlers 
 156 urllib2
.install_opener(urllib2
.build_opener(urllib2
.HTTPCookieProcessor())) 
 157 urllib2
.install_opener(urllib2
.build_opener(urllib2
.ProxyHandler())) 
 159 # Login and confirm age if needed 
 160 if not cmdl_opts
.username 
is None: 
 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') 
 167         except (urllib2
.URLError
, ValueError, httplib
.HTTPException
, TypeError): 
 168                 cond_print('failed.\n') 
 169                 error_advice_exit('unable to login') 
 171         except KeyboardInterrupt: 
 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') 
 180         except (urllib2
.URLError
, ValueError, httplib
.HTTPException
, TypeError): 
 181                 cond_print('failed.\n') 
 182                 error_advice_exit('unable to confirm age') 
 184         except KeyboardInterrupt: 
 187 # Retrieve video webpage 
 189         cond_print('Retrieving video webpage... ') 
 190         video_webpage 
= perform_request(video_url
).read() 
 191         cond_print('done.\n') 
 193 except (urllib2
.URLError
, ValueError, httplib
.HTTPException
, TypeError): 
 194         cond_print('failed.\n') 
 195         error_advice_exit('unable to download video webpage') 
 197 except KeyboardInterrupt: 
 200 # Extract needed video URL parameters 
 202         cond_print('Extracting video URL parameters... ') 
 203         video_url_params_mo 
= const_video_url_params_re
.search(video_webpage
) 
 205         if video_url_params_mo 
is None: 
 206                 cond_print('failed.\n') 
 207                 error_advice_exit('unable to extract URL parameters') 
 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') 
 213 except KeyboardInterrupt: 
 216 # Retrieve video data 
 218         video_data 
= perform_request(video_url_real
) 
 219         cond_print('Video data found at %s\n' % video_data
.geturl()) 
 221         # Abort here if in simulate mode 
 222         if cmdl_opts
.simulate
: 
 225         cond_print('Retrieving video data... ') 
 226         video_file 
= open(video_filename
, 'wb') 
 228                 video_len_str 
= '%sk' % to_k(int(video_data
.info()['Content-length'])) 
 230                 video_len_str 
= '(unknown)' 
 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
) 
 241         cond_print('done.\n') 
 242         cond_print('Video data saved to %s\n' % video_filename
) 
 245 except (urllib2
.URLError
, ValueError, httplib
.HTTPException
, TypeError): 
 246         cond_print('failed.\n') 
 247         error_advice_exit('unable to download video data') 
 249 except KeyboardInterrupt: