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.

542 lines
20 KiB

13 years ago
13 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. GenericIE()
  306. ]
  307. def _real_main():
  308. parser, opts, args = parseOpts()
  309. # Open appropriate CookieJar
  310. if opts.cookiefile is None:
  311. jar = cookielib.CookieJar()
  312. else:
  313. try:
  314. jar = cookielib.MozillaCookieJar(opts.cookiefile)
  315. if os.path.isfile(opts.cookiefile) and os.access(opts.cookiefile, os.R_OK):
  316. jar.load()
  317. except (IOError, OSError), err:
  318. sys.exit(u'ERROR: unable to open cookie file')
  319. # Dump user agent
  320. if opts.dump_user_agent:
  321. print std_headers['User-Agent']
  322. sys.exit(0)
  323. # Batch file verification
  324. batchurls = []
  325. if opts.batchfile is not None:
  326. try:
  327. if opts.batchfile == '-':
  328. batchfd = sys.stdin
  329. else:
  330. batchfd = open(opts.batchfile, 'r')
  331. batchurls = batchfd.readlines()
  332. batchurls = [x.strip() for x in batchurls]
  333. batchurls = [x for x in batchurls if len(x) > 0 and not re.search(r'^[#/;]', x)]
  334. except IOError:
  335. sys.exit(u'ERROR: batch file could not be read')
  336. all_urls = batchurls + args
  337. all_urls = map(lambda url: url.strip(), all_urls)
  338. # General configuration
  339. cookie_processor = urllib2.HTTPCookieProcessor(jar)
  340. proxy_handler = urllib2.ProxyHandler()
  341. opener = urllib2.build_opener(proxy_handler, cookie_processor, YoutubeDLHandler())
  342. urllib2.install_opener(opener)
  343. socket.setdefaulttimeout(300) # 5 minutes should be enough (famous last words)
  344. extractors = gen_extractors()
  345. if opts.list_extractors:
  346. for ie in extractors:
  347. print(ie.IE_NAME)
  348. matchedUrls = filter(lambda url: ie.suitable(url), all_urls)
  349. all_urls = filter(lambda url: url not in matchedUrls, all_urls)
  350. for mu in matchedUrls:
  351. print(u' ' + mu)
  352. sys.exit(0)
  353. # Conflicting, missing and erroneous options
  354. if opts.usenetrc and (opts.username is not None or opts.password is not None):
  355. parser.error(u'using .netrc conflicts with giving username/password')
  356. if opts.password is not None and opts.username is None:
  357. parser.error(u'account username missing')
  358. if opts.outtmpl is not None and (opts.useliteral or opts.usetitle or opts.autonumber):
  359. parser.error(u'using output template conflicts with using title, literal title or auto number')
  360. if opts.usetitle and opts.useliteral:
  361. parser.error(u'using title conflicts with using literal title')
  362. if opts.username is not None and opts.password is None:
  363. opts.password = getpass.getpass(u'Type account password and press return:')
  364. if opts.ratelimit is not None:
  365. numeric_limit = FileDownloader.parse_bytes(opts.ratelimit)
  366. if numeric_limit is None:
  367. parser.error(u'invalid rate limit specified')
  368. opts.ratelimit = numeric_limit
  369. if opts.retries is not None:
  370. try:
  371. opts.retries = long(opts.retries)
  372. except (TypeError, ValueError), err:
  373. parser.error(u'invalid retry count specified')
  374. try:
  375. opts.playliststart = int(opts.playliststart)
  376. if opts.playliststart <= 0:
  377. raise ValueError(u'Playlist start must be positive')
  378. except (TypeError, ValueError), err:
  379. parser.error(u'invalid playlist start number specified')
  380. try:
  381. opts.playlistend = int(opts.playlistend)
  382. if opts.playlistend != -1 and (opts.playlistend <= 0 or opts.playlistend < opts.playliststart):
  383. raise ValueError(u'Playlist end must be greater than playlist start')
  384. except (TypeError, ValueError), err:
  385. parser.error(u'invalid playlist end number specified')
  386. if opts.extractaudio:
  387. if opts.audioformat not in ['best', 'aac', 'mp3', 'vorbis', 'm4a', 'wav']:
  388. parser.error(u'invalid audio format specified')
  389. # File downloader
  390. fd = FileDownloader({
  391. 'usenetrc': opts.usenetrc,
  392. 'username': opts.username,
  393. 'password': opts.password,
  394. 'quiet': (opts.quiet or opts.geturl or opts.gettitle or opts.getthumbnail or opts.getdescription or opts.getfilename or opts.getformat),
  395. 'forceurl': opts.geturl,
  396. 'forcetitle': opts.gettitle,
  397. 'forcethumbnail': opts.getthumbnail,
  398. 'forcedescription': opts.getdescription,
  399. 'forcefilename': opts.getfilename,
  400. 'forceformat': opts.getformat,
  401. 'simulate': opts.simulate,
  402. '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),
  403. 'format': opts.format,
  404. 'format_limit': opts.format_limit,
  405. 'listformats': opts.listformats,
  406. 'outtmpl': ((opts.outtmpl is not None and opts.outtmpl.decode(preferredencoding()))
  407. or (opts.format == '-1' and opts.usetitle and u'%(stitle)s-%(id)s-%(format)s.%(ext)s')
  408. or (opts.format == '-1' and opts.useliteral and u'%(title)s-%(id)s-%(format)s.%(ext)s')
  409. or (opts.format == '-1' and u'%(id)s-%(format)s.%(ext)s')
  410. or (opts.usetitle and opts.autonumber and u'%(autonumber)s-%(stitle)s-%(id)s.%(ext)s')
  411. or (opts.useliteral and opts.autonumber and u'%(autonumber)s-%(title)s-%(id)s.%(ext)s')
  412. or (opts.usetitle and u'%(stitle)s-%(id)s.%(ext)s')
  413. or (opts.useliteral and u'%(title)s-%(id)s.%(ext)s')
  414. or (opts.autonumber and u'%(autonumber)s-%(id)s.%(ext)s')
  415. or u'%(id)s.%(ext)s'),
  416. 'ignoreerrors': opts.ignoreerrors,
  417. 'ratelimit': opts.ratelimit,
  418. 'nooverwrites': opts.nooverwrites,
  419. 'retries': opts.retries,
  420. 'continuedl': opts.continue_dl,
  421. 'noprogress': opts.noprogress,
  422. 'playliststart': opts.playliststart,
  423. 'playlistend': opts.playlistend,
  424. 'logtostderr': opts.outtmpl == '-',
  425. 'consoletitle': opts.consoletitle,
  426. 'nopart': opts.nopart,
  427. 'updatetime': opts.updatetime,
  428. 'writedescription': opts.writedescription,
  429. 'writeinfojson': opts.writeinfojson,
  430. 'writesubtitles': opts.writesubtitles,
  431. 'subtitleslang': opts.subtitleslang,
  432. 'matchtitle': opts.matchtitle,
  433. 'rejecttitle': opts.rejecttitle,
  434. 'max_downloads': opts.max_downloads,
  435. 'prefer_free_formats': opts.prefer_free_formats,
  436. 'verbose': opts.verbose,
  437. })
  438. if opts.verbose:
  439. fd.to_screen(u'[debug] Proxy map: ' + str(proxy_handler.proxies))
  440. for extractor in extractors:
  441. fd.add_info_extractor(extractor)
  442. # PostProcessors
  443. if opts.extractaudio:
  444. fd.add_post_processor(FFmpegExtractAudioPP(preferredcodec=opts.audioformat, preferredquality=opts.audioquality, keepvideo=opts.keepvideo))
  445. # Update version
  446. if opts.update_self:
  447. updateSelf(fd, sys.argv[0])
  448. # Maybe do nothing
  449. if len(all_urls) < 1:
  450. if not opts.update_self:
  451. parser.error(u'you must provide at least one URL')
  452. else:
  453. sys.exit()
  454. try:
  455. retcode = fd.download(all_urls)
  456. except MaxDownloadsReached:
  457. fd.to_screen(u'--max-download limit reached, aborting.')
  458. retcode = 101
  459. # Dump cookie jar if requested
  460. if opts.cookiefile is not None:
  461. try:
  462. jar.save()
  463. except (IOError, OSError), err:
  464. sys.exit(u'ERROR: unable to save cookie jar')
  465. sys.exit(retcode)
  466. def main():
  467. try:
  468. _real_main()
  469. except DownloadError:
  470. sys.exit(1)
  471. except SameFileError:
  472. sys.exit(u'ERROR: fixed output name but more than one file to download')
  473. except KeyboardInterrupt:
  474. sys.exit(u'\nERROR: Interrupted by user')