__init__.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540
  1. #!/usr/bin/env python
  2. # coding: utf-8
  3. from __future__ import unicode_literals
  4. __license__ = 'Public Domain'
  5. import codecs
  6. import io
  7. import os
  8. import re
  9. import random
  10. import sys
  11. from .options import (
  12. parseOpts,
  13. )
  14. from .compat import (
  15. compat_getpass,
  16. compat_shlex_split,
  17. workaround_optparse_bug9161,
  18. )
  19. from .utils import (
  20. DateRange,
  21. decodeOption,
  22. DEFAULT_OUTTMPL,
  23. DownloadError,
  24. expand_path,
  25. match_filter_func,
  26. MaxDownloadsReached,
  27. preferredencoding,
  28. read_batch_urls,
  29. SameFileError,
  30. setproctitle,
  31. std_headers,
  32. write_string,
  33. render_table,
  34. )
  35. from .update import update_self
  36. from .downloader import (
  37. FileDownloader,
  38. )
  39. from .extractor import gen_extractors, list_extractors
  40. from .extractor.common import InfoExtractor
  41. from .extractor.adobepass import MSO_INFO
  42. from .YoutubeDL import YoutubeDL
  43. def _real_main(argv=None):
  44. # Compatibility fixes for Windows
  45. if sys.platform == 'win32':
  46. # https://github.com/ytdl-org/youtube-dl/issues/820
  47. codecs.register(lambda name: codecs.lookup('utf-8') if name == 'cp65001' else None)
  48. workaround_optparse_bug9161()
  49. setproctitle('youtube-dlc')
  50. parser, opts, args = parseOpts(argv)
  51. # Set user agent
  52. if opts.user_agent is not None:
  53. std_headers['User-Agent'] = opts.user_agent
  54. # Set referer
  55. if opts.referer is not None:
  56. std_headers['Referer'] = opts.referer
  57. # Custom HTTP headers
  58. if opts.headers is not None:
  59. for h in opts.headers:
  60. if ':' not in h:
  61. parser.error('wrong header formatting, it should be key:value, not "%s"' % h)
  62. key, value = h.split(':', 1)
  63. if opts.verbose:
  64. write_string('[debug] Adding header from command line option %s:%s\n' % (key, value))
  65. std_headers[key] = value
  66. # Dump user agent
  67. if opts.dump_user_agent:
  68. write_string(std_headers['User-Agent'] + '\n', out=sys.stdout)
  69. sys.exit(0)
  70. # Batch file verification
  71. batch_urls = []
  72. if opts.batchfile is not None:
  73. try:
  74. if opts.batchfile == '-':
  75. batchfd = sys.stdin
  76. else:
  77. batchfd = io.open(
  78. expand_path(opts.batchfile),
  79. 'r', encoding='utf-8', errors='ignore')
  80. batch_urls = read_batch_urls(batchfd)
  81. if opts.verbose:
  82. write_string('[debug] Batch file urls: ' + repr(batch_urls) + '\n')
  83. except IOError:
  84. sys.exit('ERROR: batch file %s could not be read' % opts.batchfile)
  85. all_urls = batch_urls + [url.strip() for url in args] # batch_urls are already striped in read_batch_urls
  86. _enc = preferredencoding()
  87. all_urls = [url.decode(_enc, 'ignore') if isinstance(url, bytes) else url for url in all_urls]
  88. if opts.list_extractors:
  89. for ie in list_extractors(opts.age_limit):
  90. write_string(ie.IE_NAME + (' (CURRENTLY BROKEN)' if not ie._WORKING else '') + '\n', out=sys.stdout)
  91. matchedUrls = [url for url in all_urls if ie.suitable(url)]
  92. for mu in matchedUrls:
  93. write_string(' ' + mu + '\n', out=sys.stdout)
  94. sys.exit(0)
  95. if opts.list_extractor_descriptions:
  96. for ie in list_extractors(opts.age_limit):
  97. if not ie._WORKING:
  98. continue
  99. desc = getattr(ie, 'IE_DESC', ie.IE_NAME)
  100. if desc is False:
  101. continue
  102. if hasattr(ie, 'SEARCH_KEY'):
  103. _SEARCHES = ('cute kittens', 'slithering pythons', 'falling cat', 'angry poodle', 'purple fish', 'running tortoise', 'sleeping bunny', 'burping cow')
  104. _COUNTS = ('', '5', '10', 'all')
  105. desc += ' (Example: "%s%s:%s" )' % (ie.SEARCH_KEY, random.choice(_COUNTS), random.choice(_SEARCHES))
  106. write_string(desc + '\n', out=sys.stdout)
  107. sys.exit(0)
  108. if opts.ap_list_mso:
  109. table = [[mso_id, mso_info['name']] for mso_id, mso_info in MSO_INFO.items()]
  110. write_string('Supported TV Providers:\n' + render_table(['mso', 'mso name'], table) + '\n', out=sys.stdout)
  111. sys.exit(0)
  112. # Conflicting, missing and erroneous options
  113. if opts.usenetrc and (opts.username is not None or opts.password is not None):
  114. parser.error('using .netrc conflicts with giving username/password')
  115. if opts.password is not None and opts.username is None:
  116. parser.error('account username missing\n')
  117. if opts.ap_password is not None and opts.ap_username is None:
  118. parser.error('TV Provider account username missing\n')
  119. if opts.outtmpl is not None and (opts.usetitle or opts.autonumber or opts.useid):
  120. parser.error('using output template conflicts with using title, video ID or auto number')
  121. if opts.autonumber_size is not None:
  122. if opts.autonumber_size <= 0:
  123. parser.error('auto number size must be positive')
  124. if opts.autonumber_start is not None:
  125. if opts.autonumber_start < 0:
  126. parser.error('auto number start must be positive or 0')
  127. if opts.usetitle and opts.useid:
  128. parser.error('using title conflicts with using video ID')
  129. if opts.username is not None and opts.password is None:
  130. opts.password = compat_getpass('Type account password and press [Return]: ')
  131. if opts.ap_username is not None and opts.ap_password is None:
  132. opts.ap_password = compat_getpass('Type TV provider account password and press [Return]: ')
  133. if opts.ratelimit is not None:
  134. numeric_limit = FileDownloader.parse_bytes(opts.ratelimit)
  135. if numeric_limit is None:
  136. parser.error('invalid rate limit specified')
  137. opts.ratelimit = numeric_limit
  138. if opts.min_filesize is not None:
  139. numeric_limit = FileDownloader.parse_bytes(opts.min_filesize)
  140. if numeric_limit is None:
  141. parser.error('invalid min_filesize specified')
  142. opts.min_filesize = numeric_limit
  143. if opts.max_filesize is not None:
  144. numeric_limit = FileDownloader.parse_bytes(opts.max_filesize)
  145. if numeric_limit is None:
  146. parser.error('invalid max_filesize specified')
  147. opts.max_filesize = numeric_limit
  148. if opts.sleep_interval is not None:
  149. if opts.sleep_interval < 0:
  150. parser.error('sleep interval must be positive or 0')
  151. if opts.max_sleep_interval is not None:
  152. if opts.max_sleep_interval < 0:
  153. parser.error('max sleep interval must be positive or 0')
  154. if opts.sleep_interval is None:
  155. parser.error('min sleep interval must be specified, use --min-sleep-interval')
  156. if opts.max_sleep_interval < opts.sleep_interval:
  157. parser.error('max sleep interval must be greater than or equal to min sleep interval')
  158. else:
  159. opts.max_sleep_interval = opts.sleep_interval
  160. if opts.ap_mso and opts.ap_mso not in MSO_INFO:
  161. parser.error('Unsupported TV Provider, use --ap-list-mso to get a list of supported TV Providers')
  162. if opts.overwrites:
  163. # --yes-overwrites implies --no-continue
  164. opts.continue_dl = False
  165. def parse_retries(retries):
  166. if retries in ('inf', 'infinite'):
  167. parsed_retries = float('inf')
  168. else:
  169. try:
  170. parsed_retries = int(retries)
  171. except (TypeError, ValueError):
  172. parser.error('invalid retry count specified')
  173. return parsed_retries
  174. if opts.retries is not None:
  175. opts.retries = parse_retries(opts.retries)
  176. if opts.fragment_retries is not None:
  177. opts.fragment_retries = parse_retries(opts.fragment_retries)
  178. if opts.buffersize is not None:
  179. numeric_buffersize = FileDownloader.parse_bytes(opts.buffersize)
  180. if numeric_buffersize is None:
  181. parser.error('invalid buffer size specified')
  182. opts.buffersize = numeric_buffersize
  183. if opts.http_chunk_size is not None:
  184. numeric_chunksize = FileDownloader.parse_bytes(opts.http_chunk_size)
  185. if not numeric_chunksize:
  186. parser.error('invalid http chunk size specified')
  187. opts.http_chunk_size = numeric_chunksize
  188. if opts.playliststart <= 0:
  189. raise ValueError('Playlist start must be positive')
  190. if opts.playlistend not in (-1, None) and opts.playlistend < opts.playliststart:
  191. raise ValueError('Playlist end must be greater than playlist start')
  192. if opts.extractaudio:
  193. if opts.audioformat not in ['best', 'aac', 'flac', 'mp3', 'm4a', 'opus', 'vorbis', 'wav']:
  194. parser.error('invalid audio format specified')
  195. if opts.audioquality:
  196. opts.audioquality = opts.audioquality.strip('k').strip('K')
  197. if not opts.audioquality.isdigit():
  198. parser.error('invalid audio quality specified')
  199. if opts.remuxvideo is not None:
  200. if opts.remuxvideo not in ['mp4', 'mkv']:
  201. parser.error('invalid video container format specified')
  202. if opts.recodevideo is not None:
  203. if opts.recodevideo not in ['mp4', 'flv', 'webm', 'ogg', 'mkv', 'avi']:
  204. parser.error('invalid video recode format specified')
  205. if opts.convertsubtitles is not None:
  206. if opts.convertsubtitles not in ['srt', 'vtt', 'ass', 'lrc']:
  207. parser.error('invalid subtitle format specified')
  208. if opts.date is not None:
  209. date = DateRange.day(opts.date)
  210. else:
  211. date = DateRange(opts.dateafter, opts.datebefore)
  212. # Do not download videos when there are audio-only formats
  213. if opts.extractaudio and not opts.keepvideo and opts.format is None:
  214. opts.format = 'bestaudio/best'
  215. # --all-sub automatically sets --write-sub if --write-auto-sub is not given
  216. # this was the old behaviour if only --all-sub was given.
  217. if opts.allsubtitles and not opts.writeautomaticsub:
  218. opts.writesubtitles = True
  219. outtmpl = ((opts.outtmpl is not None and opts.outtmpl)
  220. or (opts.format == '-1' and opts.usetitle and '%(title)s-%(id)s-%(format)s.%(ext)s')
  221. or (opts.format == '-1' and '%(id)s-%(format)s.%(ext)s')
  222. or (opts.usetitle and opts.autonumber and '%(autonumber)s-%(title)s-%(id)s.%(ext)s')
  223. or (opts.usetitle and '%(title)s-%(id)s.%(ext)s')
  224. or (opts.useid and '%(id)s.%(ext)s')
  225. or (opts.autonumber and '%(autonumber)s-%(id)s.%(ext)s')
  226. or DEFAULT_OUTTMPL)
  227. if not os.path.splitext(outtmpl)[1] and opts.extractaudio:
  228. parser.error('Cannot download a video and extract audio into the same'
  229. ' file! Use "{0}.%(ext)s" instead of "{0}" as the output'
  230. ' template'.format(outtmpl))
  231. for f in opts.format_sort:
  232. if re.match(InfoExtractor.FormatSort.regex, f) is None:
  233. parser.error('invalid format sort string "%s" specified' % f)
  234. any_getting = opts.geturl or opts.gettitle or opts.getid or opts.getthumbnail or opts.getdescription or opts.getfilename or opts.getformat or opts.getduration or opts.dumpjson or opts.dump_single_json
  235. any_printing = opts.print_json
  236. download_archive_fn = expand_path(opts.download_archive) if opts.download_archive is not None else opts.download_archive
  237. # PostProcessors
  238. postprocessors = []
  239. if opts.metafromtitle:
  240. postprocessors.append({
  241. 'key': 'MetadataFromTitle',
  242. 'titleformat': opts.metafromtitle
  243. })
  244. if opts.extractaudio:
  245. postprocessors.append({
  246. 'key': 'FFmpegExtractAudio',
  247. 'preferredcodec': opts.audioformat,
  248. 'preferredquality': opts.audioquality,
  249. 'nopostoverwrites': opts.nopostoverwrites,
  250. })
  251. if opts.remuxvideo:
  252. postprocessors.append({
  253. 'key': 'FFmpegVideoRemuxer',
  254. 'preferedformat': opts.remuxvideo,
  255. })
  256. if opts.recodevideo:
  257. postprocessors.append({
  258. 'key': 'FFmpegVideoConvertor',
  259. 'preferedformat': opts.recodevideo,
  260. })
  261. # FFmpegMetadataPP should be run after FFmpegVideoConvertorPP and
  262. # FFmpegExtractAudioPP as containers before conversion may not support
  263. # metadata (3gp, webm, etc.)
  264. # And this post-processor should be placed before other metadata
  265. # manipulating post-processors (FFmpegEmbedSubtitle) to prevent loss of
  266. # extra metadata. By default ffmpeg preserves metadata applicable for both
  267. # source and target containers. From this point the container won't change,
  268. # so metadata can be added here.
  269. if opts.addmetadata:
  270. postprocessors.append({'key': 'FFmpegMetadata'})
  271. if opts.convertsubtitles:
  272. postprocessors.append({
  273. 'key': 'FFmpegSubtitlesConvertor',
  274. 'format': opts.convertsubtitles,
  275. })
  276. if opts.embedsubtitles:
  277. postprocessors.append({
  278. 'key': 'FFmpegEmbedSubtitle',
  279. })
  280. if opts.embedthumbnail:
  281. already_have_thumbnail = opts.writethumbnail or opts.write_all_thumbnails
  282. postprocessors.append({
  283. 'key': 'EmbedThumbnail',
  284. 'already_have_thumbnail': already_have_thumbnail
  285. })
  286. if not already_have_thumbnail:
  287. opts.writethumbnail = True
  288. # XAttrMetadataPP should be run after post-processors that may change file
  289. # contents
  290. if opts.xattrs:
  291. postprocessors.append({'key': 'XAttrMetadata'})
  292. # This should be below all ffmpeg PP because it may cut parts out from the video
  293. # If opts.sponskrub is None, sponskrub is used, but it silently fails if the executable can't be found
  294. if opts.sponskrub is not False:
  295. postprocessors.append({
  296. 'key': 'SponSkrub',
  297. 'path': opts.sponskrub_path,
  298. 'args': opts.sponskrub_args,
  299. 'cut': opts.sponskrub_cut,
  300. 'force': opts.sponskrub_force,
  301. 'ignoreerror': opts.sponskrub is None,
  302. })
  303. # Please keep ExecAfterDownload towards the bottom as it allows the user to modify the final file in any way.
  304. # So if the user is able to remove the file before your postprocessor runs it might cause a few problems.
  305. if opts.exec_cmd:
  306. postprocessors.append({
  307. 'key': 'ExecAfterDownload',
  308. 'exec_cmd': opts.exec_cmd,
  309. })
  310. external_downloader_args = None
  311. if opts.external_downloader_args:
  312. external_downloader_args = compat_shlex_split(opts.external_downloader_args)
  313. postprocessor_args = {}
  314. if opts.postprocessor_args is not None:
  315. for string in opts.postprocessor_args:
  316. mobj = re.match(r'(?P<pp>\w+):(?P<args>.*)$', string)
  317. if mobj is None:
  318. if 'sponskrub' not in postprocessor_args: # for backward compatibility
  319. postprocessor_args['sponskrub'] = []
  320. if opts.verbose:
  321. write_string('[debug] Adding postprocessor args from command line option sponskrub:\n')
  322. pp_name, pp_args = 'default', string
  323. else:
  324. pp_name, pp_args = mobj.group('pp').lower(), mobj.group('args')
  325. if opts.verbose:
  326. write_string('[debug] Adding postprocessor args from command line option %s:%s\n' % (pp_name, pp_args))
  327. postprocessor_args[pp_name] = compat_shlex_split(pp_args)
  328. match_filter = (
  329. None if opts.match_filter is None
  330. else match_filter_func(opts.match_filter))
  331. ydl_opts = {
  332. 'convertsubtitles': opts.convertsubtitles,
  333. 'usenetrc': opts.usenetrc,
  334. 'username': opts.username,
  335. 'password': opts.password,
  336. 'twofactor': opts.twofactor,
  337. 'videopassword': opts.videopassword,
  338. 'ap_mso': opts.ap_mso,
  339. 'ap_username': opts.ap_username,
  340. 'ap_password': opts.ap_password,
  341. 'quiet': (opts.quiet or any_getting or any_printing),
  342. 'no_warnings': opts.no_warnings,
  343. 'forceurl': opts.geturl,
  344. 'forcetitle': opts.gettitle,
  345. 'forceid': opts.getid,
  346. 'forcethumbnail': opts.getthumbnail,
  347. 'forcedescription': opts.getdescription,
  348. 'forceduration': opts.getduration,
  349. 'forcefilename': opts.getfilename,
  350. 'forceformat': opts.getformat,
  351. 'forcejson': opts.dumpjson or opts.print_json,
  352. 'dump_single_json': opts.dump_single_json,
  353. 'force_write_download_archive': opts.force_write_download_archive,
  354. 'simulate': opts.simulate or any_getting,
  355. 'skip_download': opts.skip_download,
  356. 'format': opts.format,
  357. 'format_sort': opts.format_sort,
  358. 'format_sort_force': opts.format_sort_force,
  359. 'allow_multiple_video_streams': opts.allow_multiple_video_streams,
  360. 'allow_multiple_audio_streams': opts.allow_multiple_audio_streams,
  361. 'listformats': opts.listformats,
  362. 'listformats_table': opts.listformats_table,
  363. 'outtmpl': outtmpl,
  364. 'autonumber_size': opts.autonumber_size,
  365. 'autonumber_start': opts.autonumber_start,
  366. 'restrictfilenames': opts.restrictfilenames,
  367. 'ignoreerrors': opts.ignoreerrors,
  368. 'force_generic_extractor': opts.force_generic_extractor,
  369. 'ratelimit': opts.ratelimit,
  370. 'overwrites': opts.overwrites,
  371. 'retries': opts.retries,
  372. 'fragment_retries': opts.fragment_retries,
  373. 'skip_unavailable_fragments': opts.skip_unavailable_fragments,
  374. 'keep_fragments': opts.keep_fragments,
  375. 'buffersize': opts.buffersize,
  376. 'noresizebuffer': opts.noresizebuffer,
  377. 'http_chunk_size': opts.http_chunk_size,
  378. 'continuedl': opts.continue_dl,
  379. 'noprogress': opts.noprogress,
  380. 'progress_with_newline': opts.progress_with_newline,
  381. 'playliststart': opts.playliststart,
  382. 'playlistend': opts.playlistend,
  383. 'playlistreverse': opts.playlist_reverse,
  384. 'playlistrandom': opts.playlist_random,
  385. 'noplaylist': opts.noplaylist,
  386. 'logtostderr': opts.outtmpl == '-',
  387. 'consoletitle': opts.consoletitle,
  388. 'nopart': opts.nopart,
  389. 'updatetime': opts.updatetime,
  390. 'writedescription': opts.writedescription,
  391. 'writeannotations': opts.writeannotations,
  392. 'writeinfojson': opts.writeinfojson,
  393. 'writethumbnail': opts.writethumbnail,
  394. 'write_all_thumbnails': opts.write_all_thumbnails,
  395. 'writelink': opts.writelink,
  396. 'writeurllink': opts.writeurllink,
  397. 'writewebloclink': opts.writewebloclink,
  398. 'writedesktoplink': opts.writedesktoplink,
  399. 'writesubtitles': opts.writesubtitles,
  400. 'writeautomaticsub': opts.writeautomaticsub,
  401. 'allsubtitles': opts.allsubtitles,
  402. 'listsubtitles': opts.listsubtitles,
  403. 'subtitlesformat': opts.subtitlesformat,
  404. 'subtitleslangs': opts.subtitleslangs,
  405. 'matchtitle': decodeOption(opts.matchtitle),
  406. 'rejecttitle': decodeOption(opts.rejecttitle),
  407. 'max_downloads': opts.max_downloads,
  408. 'prefer_free_formats': opts.prefer_free_formats,
  409. 'trim_file_name': opts.trim_file_name,
  410. 'verbose': opts.verbose,
  411. 'dump_intermediate_pages': opts.dump_intermediate_pages,
  412. 'write_pages': opts.write_pages,
  413. 'test': opts.test,
  414. 'keepvideo': opts.keepvideo,
  415. 'min_filesize': opts.min_filesize,
  416. 'max_filesize': opts.max_filesize,
  417. 'min_views': opts.min_views,
  418. 'max_views': opts.max_views,
  419. 'daterange': date,
  420. 'cachedir': opts.cachedir,
  421. 'youtube_print_sig_code': opts.youtube_print_sig_code,
  422. 'age_limit': opts.age_limit,
  423. 'download_archive': download_archive_fn,
  424. 'break_on_existing': opts.break_on_existing,
  425. 'cookiefile': opts.cookiefile,
  426. 'nocheckcertificate': opts.no_check_certificate,
  427. 'prefer_insecure': opts.prefer_insecure,
  428. 'proxy': opts.proxy,
  429. 'socket_timeout': opts.socket_timeout,
  430. 'bidi_workaround': opts.bidi_workaround,
  431. 'debug_printtraffic': opts.debug_printtraffic,
  432. 'prefer_ffmpeg': opts.prefer_ffmpeg,
  433. 'include_ads': opts.include_ads,
  434. 'default_search': opts.default_search,
  435. 'dynamic_mpd': opts.dynamic_mpd,
  436. 'youtube_include_dash_manifest': opts.youtube_include_dash_manifest,
  437. 'youtube_include_hls_manifest': opts.youtube_include_hls_manifest,
  438. 'encoding': opts.encoding,
  439. 'extract_flat': opts.extract_flat,
  440. 'mark_watched': opts.mark_watched,
  441. 'merge_output_format': opts.merge_output_format,
  442. 'postprocessors': postprocessors,
  443. 'fixup': opts.fixup,
  444. 'source_address': opts.source_address,
  445. 'call_home': opts.call_home,
  446. 'sleep_interval': opts.sleep_interval,
  447. 'max_sleep_interval': opts.max_sleep_interval,
  448. 'sleep_interval_subtitles': opts.sleep_interval_subtitles,
  449. 'external_downloader': opts.external_downloader,
  450. 'list_thumbnails': opts.list_thumbnails,
  451. 'playlist_items': opts.playlist_items,
  452. 'xattr_set_filesize': opts.xattr_set_filesize,
  453. 'match_filter': match_filter,
  454. 'no_color': opts.no_color,
  455. 'ffmpeg_location': opts.ffmpeg_location,
  456. 'hls_prefer_native': opts.hls_prefer_native,
  457. 'hls_use_mpegts': opts.hls_use_mpegts,
  458. 'external_downloader_args': external_downloader_args,
  459. 'postprocessor_args': postprocessor_args,
  460. 'cn_verification_proxy': opts.cn_verification_proxy,
  461. 'geo_verification_proxy': opts.geo_verification_proxy,
  462. 'config_location': opts.config_location,
  463. 'geo_bypass': opts.geo_bypass,
  464. 'geo_bypass_country': opts.geo_bypass_country,
  465. 'geo_bypass_ip_block': opts.geo_bypass_ip_block,
  466. # just for deprecation check
  467. 'autonumber': opts.autonumber if opts.autonumber is True else None,
  468. 'usetitle': opts.usetitle if opts.usetitle is True else None,
  469. }
  470. with YoutubeDL(ydl_opts) as ydl:
  471. # Update version
  472. if opts.update_self:
  473. update_self(ydl.to_screen, opts.verbose, ydl._opener)
  474. # Remove cache dir
  475. if opts.rm_cachedir:
  476. ydl.cache.remove()
  477. # Maybe do nothing
  478. if (len(all_urls) < 1) and (opts.load_info_filename is None):
  479. if opts.update_self or opts.rm_cachedir:
  480. sys.exit()
  481. ydl.warn_if_short_id(sys.argv[1:] if argv is None else argv)
  482. parser.error(
  483. 'You must provide at least one URL.\n'
  484. 'Type youtube-dlc --help to see a list of all options.')
  485. try:
  486. if opts.load_info_filename is not None:
  487. retcode = ydl.download_with_info_file(expand_path(opts.load_info_filename))
  488. else:
  489. retcode = ydl.download(all_urls)
  490. except MaxDownloadsReached:
  491. ydl.to_screen('--max-download limit reached, aborting.')
  492. retcode = 101
  493. sys.exit(retcode)
  494. def main(argv=None):
  495. try:
  496. _real_main(argv)
  497. except DownloadError:
  498. sys.exit(1)
  499. except SameFileError:
  500. sys.exit('ERROR: fixed output name but more than one file to download')
  501. except KeyboardInterrupt:
  502. sys.exit('\nERROR: Interrupted by user')
  503. __all__ = ['main', 'YoutubeDL', 'gen_extractors', 'list_extractors']