You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

543 lines
20 KiB

13 years ago
13 years ago
12 years ago
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. __authors__ = (
  4. 'Ricardo Garcia Gonzalez',
  5. 'Danny Colligan',
  6. 'Benjamin Johnson',
  7. 'Vasyl\' Vavrychuk',
  8. 'Witold Baryluk',
  9. 'Paweł Paprota',
  10. 'Gergely Imreh',
  11. 'Rogério Brito',
  12. 'Philipp Hagemeister',
  13. 'Sören Schulze',
  14. 'Kevin Ngo',
  15. 'Ori Avtalion',
  16. 'shizeeg',
  17. 'Filippo Valsorda',
  18. )
  19. __license__ = 'Public Domain'
  20. __version__ = '2012.02.27'
  21. UPDATE_URL = 'https://raw.github.com/rg3/youtube-dl/master/youtube-dl'
  22. UPDATE_URL_VERSION = 'https://raw.github.com/rg3/youtube-dl/master/LATEST_VERSION'
  23. UPDATE_URL_EXE = 'https://raw.github.com/rg3/youtube-dl/master/youtube-dl.exe'
  24. import cookielib
  25. import getpass
  26. import optparse
  27. import os
  28. import re
  29. import shlex
  30. import socket
  31. import subprocess
  32. import sys
  33. import urllib2
  34. import warnings
  35. from utils import *
  36. from FileDownloader import *
  37. from InfoExtractors import *
  38. from PostProcessor import *
  39. def updateSelf(downloader, filename):
  40. ''' Update the program file with the latest version from the repository '''
  41. # Note: downloader only used for options
  42. if not os.access(filename, os.W_OK):
  43. sys.exit('ERROR: no write permissions on %s' % filename)
  44. downloader.to_screen(u'Updating to latest version...')
  45. urlv = urllib2.urlopen(UPDATE_URL_VERSION)
  46. newversion = urlv.read().strip()
  47. if newversion == __version__:
  48. downloader.to_screen(u'youtube-dl is up-to-date (' + __version__ + ')')
  49. return
  50. urlv.close()
  51. if hasattr(sys, "frozen"): #py2exe
  52. exe = os.path.abspath(filename)
  53. directory = os.path.dirname(exe)
  54. if not os.access(directory, os.W_OK):
  55. sys.exit('ERROR: no write permissions on %s' % directory)
  56. try:
  57. urlh = urllib2.urlopen(UPDATE_URL_EXE)
  58. newcontent = urlh.read()
  59. urlh.close()
  60. with open(exe + '.new', 'wb') as outf:
  61. outf.write(newcontent)
  62. except (IOError, OSError), err:
  63. sys.exit('ERROR: unable to download latest version')
  64. try:
  65. bat = os.path.join(directory, 'youtube-dl-updater.bat')
  66. b = open(bat, 'w')
  67. print >> b, """
  68. echo Updating youtube-dl...
  69. ping 127.0.0.1 -n 5 -w 1000 > NUL
  70. move /Y "%s.new" "%s"
  71. del "%s"
  72. """ %(exe, exe, bat)
  73. b.close()
  74. os.startfile(bat)
  75. except (IOError, OSError), err:
  76. sys.exit('ERROR: unable to overwrite current version')
  77. else:
  78. try:
  79. urlh = urllib2.urlopen(UPDATE_URL)
  80. newcontent = urlh.read()
  81. urlh.close()
  82. except (IOError, OSError), err:
  83. sys.exit('ERROR: unable to download latest version')
  84. try:
  85. with open(filename, 'wb') as outf:
  86. outf.write(newcontent)
  87. except (IOError, OSError), err:
  88. sys.exit('ERROR: unable to overwrite current version')
  89. downloader.to_screen(u'Updated youtube-dl. Restart youtube-dl to use the new version.')
  90. def parseOpts():
  91. def _readOptions(filename_bytes):
  92. try:
  93. optionf = open(filename_bytes)
  94. except IOError:
  95. return [] # silently skip if file is not present
  96. try:
  97. res = []
  98. for l in optionf:
  99. res += shlex.split(l, comments=True)
  100. finally:
  101. optionf.close()
  102. return res
  103. def _format_option_string(option):
  104. ''' ('-o', '--option') -> -o, --format METAVAR'''
  105. opts = []
  106. if option._short_opts: opts.append(option._short_opts[0])
  107. if option._long_opts: opts.append(option._long_opts[0])
  108. if len(opts) > 1: opts.insert(1, ', ')
  109. if option.takes_value(): opts.append(' %s' % option.metavar)
  110. return "".join(opts)
  111. def _find_term_columns():
  112. columns = os.environ.get('COLUMNS', None)
  113. if columns:
  114. return int(columns)
  115. try:
  116. sp = subprocess.Popen(['stty', 'size'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  117. out,err = sp.communicate()
  118. return int(out.split()[1])
  119. except:
  120. pass
  121. return None
  122. max_width = 80
  123. max_help_position = 80
  124. # No need to wrap help messages if we're on a wide console
  125. columns = _find_term_columns()
  126. if columns: max_width = columns
  127. fmt = optparse.IndentedHelpFormatter(width=max_width, max_help_position=max_help_position)
  128. fmt.format_option_strings = _format_option_string
  129. kw = {
  130. 'version' : __version__,
  131. 'formatter' : fmt,
  132. 'usage' : '%prog [options] url [url...]',
  133. 'conflict_handler' : 'resolve',
  134. }
  135. parser = optparse.OptionParser(**kw)
  136. # option groups
  137. general = optparse.OptionGroup(parser, 'General Options')
  138. selection = optparse.OptionGroup(parser, 'Video Selection')
  139. authentication = optparse.OptionGroup(parser, 'Authentication Options')
  140. video_format = optparse.OptionGroup(parser, 'Video Format Options')
  141. postproc = optparse.OptionGroup(parser, 'Post-processing Options')
  142. filesystem = optparse.OptionGroup(parser, 'Filesystem Options')
  143. verbosity = optparse.OptionGroup(parser, 'Verbosity / Simulation Options')
  144. general.add_option('-h', '--help',
  145. action='help', help='print this help text and exit')
  146. general.add_option('-v', '--version',
  147. action='version', help='print program version and exit')
  148. general.add_option('-U', '--update',
  149. action='store_true', dest='update_self', help='update this program to latest version')
  150. general.add_option('-i', '--ignore-errors',
  151. action='store_true', dest='ignoreerrors', help='continue on download errors', default=False)
  152. general.add_option('-r', '--rate-limit',
  153. dest='ratelimit', metavar='LIMIT', help='download rate limit (e.g. 50k or 44.6m)')
  154. general.add_option('-R', '--retries',
  155. dest='retries', metavar='RETRIES', help='number of retries (default is 10)', default=10)
  156. general.add_option('--dump-user-agent',
  157. action='store_true', dest='dump_user_agent',
  158. help='display the current browser identification', default=False)
  159. general.add_option('--list-extractors',
  160. action='store_true', dest='list_extractors',
  161. help='List all supported extractors and the URLs they would handle', default=False)
  162. selection.add_option('--playlist-start',
  163. dest='playliststart', metavar='NUMBER', help='playlist video to start at (default is 1)', default=1)
  164. selection.add_option('--playlist-end',
  165. dest='playlistend', metavar='NUMBER', help='playlist video to end at (default is last)', default=-1)
  166. selection.add_option('--match-title', dest='matchtitle', metavar='REGEX',help='download only matching titles (regex or caseless sub-string)')
  167. selection.add_option('--reject-title', dest='rejecttitle', metavar='REGEX',help='skip download for matching titles (regex or caseless sub-string)')
  168. selection.add_option('--max-downloads', metavar='NUMBER', dest='max_downloads', help='Abort after downloading NUMBER files', default=None)
  169. authentication.add_option('-u', '--username',
  170. dest='username', metavar='USERNAME', help='account username')
  171. authentication.add_option('-p', '--password',
  172. dest='password', metavar='PASSWORD', help='account password')
  173. authentication.add_option('-n', '--netrc',
  174. action='store_true', dest='usenetrc', help='use .netrc authentication data', default=False)
  175. video_format.add_option('-f', '--format',
  176. action='store', dest='format', metavar='FORMAT', help='video format code')
  177. video_format.add_option('--all-formats',
  178. action='store_const', dest='format', help='download all available video formats', const='all')
  179. video_format.add_option('--prefer-free-formats',
  180. action='store_true', dest='prefer_free_formats', default=False, help='prefer free video formats unless a specific one is requested')
  181. video_format.add_option('--max-quality',
  182. action='store', dest='format_limit', metavar='FORMAT', help='highest quality format to download')
  183. video_format.add_option('-F', '--list-formats',
  184. action='store_true', dest='listformats', help='list all available formats (currently youtube only)')
  185. video_format.add_option('--write-srt',
  186. action='store_true', dest='writesubtitles',
  187. help='write video closed captions to a .srt file (currently youtube only)', default=False)
  188. video_format.add_option('--srt-lang',
  189. action='store', dest='subtitleslang', metavar='LANG',
  190. help='language of the closed captions to download (optional) use IETF language tags like \'en\'')
  191. verbosity.add_option('-q', '--quiet',
  192. action='store_true', dest='quiet', help='activates quiet mode', default=False)
  193. verbosity.add_option('-s', '--simulate',
  194. action='store_true', dest='simulate', help='do not download the video and do not write anything to disk', default=False)
  195. verbosity.add_option('--skip-download',
  196. action='store_true', dest='skip_download', help='do not download the video', default=False)
  197. verbosity.add_option('-g', '--get-url',
  198. action='store_true', dest='geturl', help='simulate, quiet but print URL', default=False)
  199. verbosity.add_option('-e', '--get-title',
  200. action='store_true', dest='gettitle', help='simulate, quiet but print title', default=False)
  201. verbosity.add_option('--get-thumbnail',
  202. action='store_true', dest='getthumbnail',
  203. help='simulate, quiet but print thumbnail URL', default=False)
  204. verbosity.add_option('--get-description',
  205. action='store_true', dest='getdescription',
  206. help='simulate, quiet but print video description', default=False)
  207. verbosity.add_option('--get-filename',
  208. action='store_true', dest='getfilename',
  209. help='simulate, quiet but print output filename', default=False)
  210. verbosity.add_option('--get-format',
  211. action='store_true', dest='getformat',
  212. help='simulate, quiet but print output format', default=False)
  213. verbosity.add_option('--no-progress',
  214. action='store_true', dest='noprogress', help='do not print progress bar', default=False)
  215. verbosity.add_option('--console-title',
  216. action='store_true', dest='consoletitle',
  217. help='display progress in console titlebar', default=False)
  218. verbosity.add_option('-v', '--verbose',
  219. action='store_true', dest='verbose', help='print various debugging information', default=False)
  220. filesystem.add_option('-t', '--title',
  221. action='store_true', dest='usetitle', help='use title in file name', default=False)
  222. filesystem.add_option('-l', '--literal',
  223. action='store_true', dest='useliteral', help='use literal title in file name', default=False)
  224. filesystem.add_option('-A', '--auto-number',
  225. action='store_true', dest='autonumber',
  226. help='number downloaded files starting from 00000', default=False)
  227. filesystem.add_option('-o', '--output',
  228. dest='outtmpl', metavar='TEMPLATE', help='output filename template. Use %(stitle)s to get the title, %(uploader)s for the uploader name, %(autonumber)s to get an automatically incremented number, %(ext)s for the filename extension, %(upload_date)s for the upload date (YYYYMMDD), and %% for a literal percent. Use - to output to stdout.')
  229. filesystem.add_option('-a', '--batch-file',
  230. dest='batchfile', metavar='FILE', help='file containing URLs to download (\'-\' for stdin)')
  231. filesystem.add_option('-w', '--no-overwrites',
  232. action='store_true', dest='nooverwrites', help='do not overwrite files', default=False)
  233. filesystem.add_option('-c', '--continue',
  234. action='store_true', dest='continue_dl', help='resume partially downloaded files', default=True)
  235. filesystem.add_option('--no-continue',
  236. action='store_false', dest='continue_dl',
  237. help='do not resume partially downloaded files (restart from beginning)')
  238. filesystem.add_option('--cookies',
  239. dest='cookiefile', metavar='FILE', help='file to read cookies from and dump cookie jar in')
  240. filesystem.add_option('--no-part',
  241. action='store_true', dest='nopart', help='do not use .part files', default=False)
  242. filesystem.add_option('--no-mtime',
  243. action='store_false', dest='updatetime',
  244. help='do not use the Last-modified header to set the file modification time', default=True)
  245. filesystem.add_option('--write-description',
  246. action='store_true', dest='writedescription',
  247. help='write video description to a .description file', default=False)
  248. filesystem.add_option('--write-info-json',
  249. action='store_true', dest='writeinfojson',
  250. help='write video metadata to a .info.json file', default=False)
  251. postproc.add_option('--extract-audio', action='store_true', dest='extractaudio', default=False,
  252. help='convert video files to audio-only files (requires ffmpeg or avconv and ffprobe or avprobe)')
  253. postproc.add_option('--audio-format', metavar='FORMAT', dest='audioformat', default='best',
  254. help='"best", "aac", "vorbis", "mp3", "m4a", or "wav"; best by default')
  255. postproc.add_option('--audio-quality', metavar='QUALITY', dest='audioquality', default='128K',
  256. help='ffmpeg/avconv audio bitrate specification, 128k by default')
  257. postproc.add_option('-k', '--keep-video', action='store_true', dest='keepvideo', default=False,
  258. help='keeps the video file on disk after the post-processing; the video is erased by default')
  259. parser.add_option_group(general)
  260. parser.add_option_group(selection)
  261. parser.add_option_group(filesystem)
  262. parser.add_option_group(verbosity)
  263. parser.add_option_group(video_format)
  264. parser.add_option_group(authentication)
  265. parser.add_option_group(postproc)
  266. xdg_config_home = os.environ.get('XDG_CONFIG_HOME')
  267. if xdg_config_home:
  268. userConf = os.path.join(xdg_config_home, 'youtube-dl.conf')
  269. else:
  270. userConf = os.path.join(os.path.expanduser('~'), '.config', 'youtube-dl.conf')
  271. argv = _readOptions('/etc/youtube-dl.conf') + _readOptions(userConf) + sys.argv[1:]
  272. opts, args = parser.parse_args(argv)
  273. return parser, opts, args
  274. def gen_extractors():
  275. """ Return a list of an instance of every supported extractor.
  276. The order does matter; the first extractor matched is the one handling the URL.
  277. """
  278. return [
  279. YoutubePlaylistIE(),
  280. YoutubeUserIE(),
  281. YoutubeSearchIE(),
  282. YoutubeIE(),
  283. MetacafeIE(),
  284. DailymotionIE(),
  285. GoogleIE(),
  286. GoogleSearchIE(),
  287. PhotobucketIE(),
  288. YahooIE(),
  289. YahooSearchIE(),
  290. DepositFilesIE(),
  291. FacebookIE(),
  292. BlipTVUserIE(),
  293. BlipTVIE(),
  294. VimeoIE(),
  295. MyVideoIE(),
  296. ComedyCentralIE(),
  297. EscapistIE(),
  298. CollegeHumorIE(),
  299. XVideosIE(),
  300. SoundcloudIE(),
  301. InfoQIE(),
  302. MixcloudIE(),
  303. StanfordOpenClassroomIE(),
  304. MTVIE(),
  305. YoukuIE(),
  306. GenericIE()
  307. ]
  308. def _real_main():
  309. parser, opts, args = parseOpts()
  310. # Open appropriate CookieJar
  311. if opts.cookiefile is None:
  312. jar = cookielib.CookieJar()
  313. else:
  314. try:
  315. jar = cookielib.MozillaCookieJar(opts.cookiefile)
  316. if os.path.isfile(opts.cookiefile) and os.access(opts.cookiefile, os.R_OK):
  317. jar.load()
  318. except (IOError, OSError), err:
  319. sys.exit(u'ERROR: unable to open cookie file')
  320. # Dump user agent
  321. if opts.dump_user_agent:
  322. print std_headers['User-Agent']
  323. sys.exit(0)
  324. # Batch file verification
  325. batchurls = []
  326. if opts.batchfile is not None:
  327. try:
  328. if opts.batchfile == '-':
  329. batchfd = sys.stdin
  330. else:
  331. batchfd = open(opts.batchfile, 'r')
  332. batchurls = batchfd.readlines()
  333. batchurls = [x.strip() for x in batchurls]
  334. batchurls = [x for x in batchurls if len(x) > 0 and not re.search(r'^[#/;]', x)]
  335. except IOError:
  336. sys.exit(u'ERROR: batch file could not be read')
  337. all_urls = batchurls + args
  338. all_urls = map(lambda url: url.strip(), all_urls)
  339. # General configuration
  340. cookie_processor = urllib2.HTTPCookieProcessor(jar)
  341. proxy_handler = urllib2.ProxyHandler()
  342. opener = urllib2.build_opener(proxy_handler, cookie_processor, YoutubeDLHandler())
  343. urllib2.install_opener(opener)
  344. socket.setdefaulttimeout(300) # 5 minutes should be enough (famous last words)
  345. extractors = gen_extractors()
  346. if opts.list_extractors:
  347. for ie in extractors:
  348. print(ie.IE_NAME)
  349. matchedUrls = filter(lambda url: ie.suitable(url), all_urls)
  350. all_urls = filter(lambda url: url not in matchedUrls, all_urls)
  351. for mu in matchedUrls:
  352. print(u' ' + mu)
  353. sys.exit(0)
  354. # Conflicting, missing and erroneous options
  355. if opts.usenetrc and (opts.username is not None or opts.password is not None):
  356. parser.error(u'using .netrc conflicts with giving username/password')
  357. if opts.password is not None and opts.username is None:
  358. parser.error(u'account username missing')
  359. if opts.outtmpl is not None and (opts.useliteral or opts.usetitle or opts.autonumber):
  360. parser.error(u'using output template conflicts with using title, literal title or auto number')
  361. if opts.usetitle and opts.useliteral:
  362. parser.error(u'using title conflicts with using literal title')
  363. if opts.username is not None and opts.password is None:
  364. opts.password = getpass.getpass(u'Type account password and press return:')
  365. if opts.ratelimit is not None:
  366. numeric_limit = FileDownloader.parse_bytes(opts.ratelimit)
  367. if numeric_limit is None:
  368. parser.error(u'invalid rate limit specified')
  369. opts.ratelimit = numeric_limit
  370. if opts.retries is not None:
  371. try:
  372. opts.retries = long(opts.retries)
  373. except (TypeError, ValueError), err:
  374. parser.error(u'invalid retry count specified')
  375. try:
  376. opts.playliststart = int(opts.playliststart)
  377. if opts.playliststart <= 0:
  378. raise ValueError(u'Playlist start must be positive')
  379. except (TypeError, ValueError), err:
  380. parser.error(u'invalid playlist start number specified')
  381. try:
  382. opts.playlistend = int(opts.playlistend)
  383. if opts.playlistend != -1 and (opts.playlistend <= 0 or opts.playlistend < opts.playliststart):
  384. raise ValueError(u'Playlist end must be greater than playlist start')
  385. except (TypeError, ValueError), err:
  386. parser.error(u'invalid playlist end number specified')
  387. if opts.extractaudio:
  388. if opts.audioformat not in ['best', 'aac', 'mp3', 'vorbis', 'm4a', 'wav']:
  389. parser.error(u'invalid audio format specified')
  390. # File downloader
  391. fd = FileDownloader({
  392. 'usenetrc': opts.usenetrc,
  393. 'username': opts.username,
  394. 'password': opts.password,
  395. 'quiet': (opts.quiet or opts.geturl or opts.gettitle or opts.getthumbnail or opts.getdescription or opts.getfilename or opts.getformat),
  396. 'forceurl': opts.geturl,
  397. 'forcetitle': opts.gettitle,
  398. 'forcethumbnail': opts.getthumbnail,
  399. 'forcedescription': opts.getdescription,
  400. 'forcefilename': opts.getfilename,
  401. 'forceformat': opts.getformat,
  402. 'simulate': opts.simulate,
  403. 'skip_download': (opts.skip_download or opts.simulate or opts.geturl or opts.gettitle or opts.getthumbnail or opts.getdescription or opts.getfilename or opts.getformat),
  404. 'format': opts.format,
  405. 'format_limit': opts.format_limit,
  406. 'listformats': opts.listformats,
  407. 'outtmpl': ((opts.outtmpl is not None and opts.outtmpl.decode(preferredencoding()))
  408. or (opts.format == '-1' and opts.usetitle and u'%(stitle)s-%(id)s-%(format)s.%(ext)s')
  409. or (opts.format == '-1' and opts.useliteral and u'%(title)s-%(id)s-%(format)s.%(ext)s')
  410. or (opts.format == '-1' and u'%(id)s-%(format)s.%(ext)s')
  411. or (opts.usetitle and opts.autonumber and u'%(autonumber)s-%(stitle)s-%(id)s.%(ext)s')
  412. or (opts.useliteral and opts.autonumber and u'%(autonumber)s-%(title)s-%(id)s.%(ext)s')
  413. or (opts.usetitle and u'%(stitle)s-%(id)s.%(ext)s')
  414. or (opts.useliteral and u'%(title)s-%(id)s.%(ext)s')
  415. or (opts.autonumber and u'%(autonumber)s-%(id)s.%(ext)s')
  416. or u'%(id)s.%(ext)s'),
  417. 'ignoreerrors': opts.ignoreerrors,
  418. 'ratelimit': opts.ratelimit,
  419. 'nooverwrites': opts.nooverwrites,
  420. 'retries': opts.retries,
  421. 'continuedl': opts.continue_dl,
  422. 'noprogress': opts.noprogress,
  423. 'playliststart': opts.playliststart,
  424. 'playlistend': opts.playlistend,
  425. 'logtostderr': opts.outtmpl == '-',
  426. 'consoletitle': opts.consoletitle,
  427. 'nopart': opts.nopart,
  428. 'updatetime': opts.updatetime,
  429. 'writedescription': opts.writedescription,
  430. 'writeinfojson': opts.writeinfojson,
  431. 'writesubtitles': opts.writesubtitles,
  432. 'subtitleslang': opts.subtitleslang,
  433. 'matchtitle': opts.matchtitle,
  434. 'rejecttitle': opts.rejecttitle,
  435. 'max_downloads': opts.max_downloads,
  436. 'prefer_free_formats': opts.prefer_free_formats,
  437. 'verbose': opts.verbose,
  438. })
  439. if opts.verbose:
  440. fd.to_screen(u'[debug] Proxy map: ' + str(proxy_handler.proxies))
  441. for extractor in extractors:
  442. fd.add_info_extractor(extractor)
  443. # PostProcessors
  444. if opts.extractaudio:
  445. fd.add_post_processor(FFmpegExtractAudioPP(preferredcodec=opts.audioformat, preferredquality=opts.audioquality, keepvideo=opts.keepvideo))
  446. # Update version
  447. if opts.update_self:
  448. updateSelf(fd, sys.argv[0])
  449. # Maybe do nothing
  450. if len(all_urls) < 1:
  451. if not opts.update_self:
  452. parser.error(u'you must provide at least one URL')
  453. else:
  454. sys.exit()
  455. try:
  456. retcode = fd.download(all_urls)
  457. except MaxDownloadsReached:
  458. fd.to_screen(u'--max-download limit reached, aborting.')
  459. retcode = 101
  460. # Dump cookie jar if requested
  461. if opts.cookiefile is not None:
  462. try:
  463. jar.save()
  464. except (IOError, OSError), err:
  465. sys.exit(u'ERROR: unable to save cookie jar')
  466. sys.exit(retcode)
  467. def main():
  468. try:
  469. _real_main()
  470. except DownloadError:
  471. sys.exit(1)
  472. except SameFileError:
  473. sys.exit(u'ERROR: fixed output name but more than one file to download')
  474. except KeyboardInterrupt:
  475. sys.exit(u'\nERROR: Interrupted by user')