__init__.py 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122
  1. import sys
  2. if sys.version_info < (3, 9):
  3. raise ImportError(
  4. f'You are using an unsupported version of Python. Only Python versions 3.9 and above are supported by yt-dlp') # noqa: F541
  5. __license__ = 'The Unlicense'
  6. import collections
  7. import getpass
  8. import itertools
  9. import optparse
  10. import os
  11. import re
  12. import traceback
  13. from .cookies import SUPPORTED_BROWSERS, SUPPORTED_KEYRINGS, CookieLoadError
  14. from .downloader.external import get_external_downloader
  15. from .extractor import list_extractor_classes
  16. from .extractor.adobepass import MSO_INFO
  17. from .networking.impersonate import ImpersonateTarget
  18. from .options import parseOpts
  19. from .postprocessor import (
  20. FFmpegExtractAudioPP,
  21. FFmpegMergerPP,
  22. FFmpegPostProcessor,
  23. FFmpegSubtitlesConvertorPP,
  24. FFmpegThumbnailsConvertorPP,
  25. FFmpegVideoConvertorPP,
  26. FFmpegVideoRemuxerPP,
  27. MetadataFromFieldPP,
  28. MetadataParserPP,
  29. )
  30. from .update import Updater
  31. from .utils import (
  32. Config,
  33. NO_DEFAULT,
  34. POSTPROCESS_WHEN,
  35. DateRange,
  36. DownloadCancelled,
  37. DownloadError,
  38. FormatSorter,
  39. GeoUtils,
  40. PlaylistEntries,
  41. SameFileError,
  42. download_range_func,
  43. expand_path,
  44. float_or_none,
  45. format_field,
  46. int_or_none,
  47. join_nonempty,
  48. match_filter_func,
  49. parse_bytes,
  50. parse_duration,
  51. preferredencoding,
  52. read_batch_urls,
  53. read_stdin,
  54. render_table,
  55. setproctitle,
  56. shell_quote,
  57. traverse_obj,
  58. variadic,
  59. write_string,
  60. )
  61. from .utils.networking import std_headers
  62. from .utils._utils import _UnsafeExtensionError
  63. from .YoutubeDL import YoutubeDL
  64. _IN_CLI = False
  65. def _exit(status=0, *args):
  66. for msg in args:
  67. sys.stderr.write(msg)
  68. raise SystemExit(status)
  69. def get_urls(urls, batchfile, verbose):
  70. """
  71. @param verbose -1: quiet, 0: normal, 1: verbose
  72. """
  73. batch_urls = []
  74. if batchfile is not None:
  75. try:
  76. batch_urls = read_batch_urls(
  77. read_stdin(None if verbose == -1 else 'URLs') if batchfile == '-'
  78. else open(expand_path(batchfile), encoding='utf-8', errors='ignore'))
  79. if verbose == 1:
  80. write_string('[debug] Batch file urls: ' + repr(batch_urls) + '\n')
  81. except OSError:
  82. _exit(f'ERROR: batch file {batchfile} could not be read')
  83. _enc = preferredencoding()
  84. return [
  85. url.strip().decode(_enc, 'ignore') if isinstance(url, bytes) else url.strip()
  86. for url in batch_urls + urls]
  87. def print_extractor_information(opts, urls):
  88. out = ''
  89. if opts.list_extractors:
  90. # Importing GenericIE is currently slow since it imports YoutubeIE
  91. from .extractor.generic import GenericIE
  92. urls = dict.fromkeys(urls, False)
  93. for ie in list_extractor_classes(opts.age_limit):
  94. out += ie.IE_NAME + (' (CURRENTLY BROKEN)' if not ie.working() else '') + '\n'
  95. if ie == GenericIE:
  96. matched_urls = [url for url, matched in urls.items() if not matched]
  97. else:
  98. matched_urls = tuple(filter(ie.suitable, urls.keys()))
  99. urls.update(dict.fromkeys(matched_urls, True))
  100. out += ''.join(f' {url}\n' for url in matched_urls)
  101. elif opts.list_extractor_descriptions:
  102. _SEARCHES = ('cute kittens', 'slithering pythons', 'falling cat', 'angry poodle', 'purple fish', 'running tortoise', 'sleeping bunny', 'burping cow')
  103. out = '\n'.join(
  104. ie.description(markdown=False, search_examples=_SEARCHES)
  105. for ie in list_extractor_classes(opts.age_limit) if ie.working() and ie.IE_DESC is not False)
  106. elif opts.ap_list_mso:
  107. out = 'Supported TV Providers:\n{}\n'.format(render_table(
  108. ['mso', 'mso name'],
  109. [[mso_id, mso_info['name']] for mso_id, mso_info in MSO_INFO.items()]))
  110. else:
  111. return False
  112. write_string(out, out=sys.stdout)
  113. return True
  114. def set_compat_opts(opts):
  115. def _unused_compat_opt(name):
  116. if name not in opts.compat_opts:
  117. return False
  118. opts.compat_opts.discard(name)
  119. opts.compat_opts.update([f'*{name}'])
  120. return True
  121. def set_default_compat(compat_name, opt_name, default=True, remove_compat=True):
  122. attr = getattr(opts, opt_name)
  123. if compat_name in opts.compat_opts:
  124. if attr is None:
  125. setattr(opts, opt_name, not default)
  126. return True
  127. else:
  128. if remove_compat:
  129. _unused_compat_opt(compat_name)
  130. return False
  131. elif attr is None:
  132. setattr(opts, opt_name, default)
  133. return None
  134. set_default_compat('abort-on-error', 'ignoreerrors', 'only_download')
  135. set_default_compat('no-playlist-metafiles', 'allow_playlist_files')
  136. set_default_compat('no-clean-infojson', 'clean_infojson')
  137. if 'no-attach-info-json' in opts.compat_opts:
  138. if opts.embed_infojson:
  139. _unused_compat_opt('no-attach-info-json')
  140. else:
  141. opts.embed_infojson = False
  142. if 'format-sort' in opts.compat_opts:
  143. opts.format_sort.extend(FormatSorter.ytdl_default)
  144. elif 'prefer-vp9-sort' in opts.compat_opts:
  145. opts.format_sort.extend(FormatSorter._prefer_vp9_sort)
  146. _video_multistreams_set = set_default_compat('multistreams', 'allow_multiple_video_streams', False, remove_compat=False)
  147. _audio_multistreams_set = set_default_compat('multistreams', 'allow_multiple_audio_streams', False, remove_compat=False)
  148. if _video_multistreams_set is False and _audio_multistreams_set is False:
  149. _unused_compat_opt('multistreams')
  150. if 'filename' in opts.compat_opts:
  151. if opts.outtmpl.get('default') is None:
  152. opts.outtmpl.update({'default': '%(title)s-%(id)s.%(ext)s'})
  153. else:
  154. _unused_compat_opt('filename')
  155. def validate_options(opts):
  156. def validate(cndn, name, value=None, msg=None):
  157. if cndn:
  158. return True
  159. raise ValueError((msg or 'invalid {name} "{value}" given').format(name=name, value=value))
  160. def validate_in(name, value, items, msg=None):
  161. return validate(value is None or value in items, name, value, msg)
  162. def validate_regex(name, value, regex):
  163. return validate(value is None or re.match(regex, value), name, value)
  164. def validate_positive(name, value, strict=False):
  165. return validate(value is None or value > 0 or (not strict and value == 0),
  166. name, value, '{name} "{value}" must be positive' + ('' if strict else ' or 0'))
  167. def validate_minmax(min_val, max_val, min_name, max_name=None):
  168. if max_val is None or min_val is None or max_val >= min_val:
  169. return
  170. if not max_name:
  171. min_name, max_name = f'min {min_name}', f'max {min_name}'
  172. raise ValueError(f'{max_name} "{max_val}" must be must be greater than or equal to {min_name} "{min_val}"')
  173. # Usernames and passwords
  174. validate(sum(map(bool, (opts.usenetrc, opts.netrc_cmd, opts.username))) <= 1, '.netrc',
  175. msg='{name}, netrc command and username/password are mutually exclusive options')
  176. validate(opts.password is None or opts.username is not None, 'account username', msg='{name} missing')
  177. validate(opts.ap_password is None or opts.ap_username is not None,
  178. 'TV Provider account username', msg='{name} missing')
  179. validate_in('TV Provider', opts.ap_mso, MSO_INFO,
  180. 'Unsupported {name} "{value}", use --ap-list-mso to get a list of supported TV Providers')
  181. # Numbers
  182. validate_positive('autonumber start', opts.autonumber_start)
  183. validate_positive('autonumber size', opts.autonumber_size, True)
  184. validate_positive('concurrent fragments', opts.concurrent_fragment_downloads, True)
  185. validate_positive('playlist start', opts.playliststart, True)
  186. if opts.playlistend != -1:
  187. validate_minmax(opts.playliststart, opts.playlistend, 'playlist start', 'playlist end')
  188. # Time ranges
  189. validate_positive('subtitles sleep interval', opts.sleep_interval_subtitles)
  190. validate_positive('requests sleep interval', opts.sleep_interval_requests)
  191. validate_positive('sleep interval', opts.sleep_interval)
  192. validate_positive('max sleep interval', opts.max_sleep_interval)
  193. if opts.sleep_interval is None:
  194. validate(
  195. opts.max_sleep_interval is None, 'min sleep interval',
  196. msg='{name} must be specified; use --min-sleep-interval')
  197. elif opts.max_sleep_interval is None:
  198. opts.max_sleep_interval = opts.sleep_interval
  199. else:
  200. validate_minmax(opts.sleep_interval, opts.max_sleep_interval, 'sleep interval')
  201. if opts.wait_for_video is not None:
  202. min_wait, max_wait, *_ = map(parse_duration, [*opts.wait_for_video.split('-', 1), None])
  203. validate(min_wait is not None and not (max_wait is None and '-' in opts.wait_for_video),
  204. 'time range to wait for video', opts.wait_for_video)
  205. validate_minmax(min_wait, max_wait, 'time range to wait for video')
  206. opts.wait_for_video = (min_wait, max_wait)
  207. # Format sort
  208. for f in opts.format_sort:
  209. validate_regex('format sorting', f, FormatSorter.regex)
  210. # Postprocessor formats
  211. if opts.convertsubtitles == 'none':
  212. opts.convertsubtitles = None
  213. if opts.convertthumbnails == 'none':
  214. opts.convertthumbnails = None
  215. validate_regex('merge output format', opts.merge_output_format,
  216. r'({0})(/({0}))*'.format('|'.join(map(re.escape, FFmpegMergerPP.SUPPORTED_EXTS))))
  217. validate_regex('audio format', opts.audioformat, FFmpegExtractAudioPP.FORMAT_RE)
  218. validate_in('subtitle format', opts.convertsubtitles, FFmpegSubtitlesConvertorPP.SUPPORTED_EXTS)
  219. validate_regex('thumbnail format', opts.convertthumbnails, FFmpegThumbnailsConvertorPP.FORMAT_RE)
  220. validate_regex('recode video format', opts.recodevideo, FFmpegVideoConvertorPP.FORMAT_RE)
  221. validate_regex('remux video format', opts.remuxvideo, FFmpegVideoRemuxerPP.FORMAT_RE)
  222. if opts.audioquality:
  223. opts.audioquality = opts.audioquality.strip('k').strip('K')
  224. # int_or_none prevents inf, nan
  225. validate_positive('audio quality', int_or_none(float_or_none(opts.audioquality), default=0))
  226. # Retries
  227. def parse_retries(name, value):
  228. if value is None:
  229. return None
  230. elif value in ('inf', 'infinite'):
  231. return float('inf')
  232. try:
  233. int_value = int(value)
  234. except (TypeError, ValueError):
  235. validate(False, f'{name} retry count', value)
  236. validate_positive(f'{name} retry count', int_value)
  237. return int_value
  238. opts.retries = parse_retries('download', opts.retries)
  239. opts.fragment_retries = parse_retries('fragment', opts.fragment_retries)
  240. opts.extractor_retries = parse_retries('extractor', opts.extractor_retries)
  241. opts.file_access_retries = parse_retries('file access', opts.file_access_retries)
  242. # Retry sleep function
  243. def parse_sleep_func(expr):
  244. NUMBER_RE = r'\d+(?:\.\d+)?'
  245. op, start, limit, step, *_ = (*tuple(re.fullmatch(
  246. rf'(?:(linear|exp)=)?({NUMBER_RE})(?::({NUMBER_RE})?)?(?::({NUMBER_RE}))?',
  247. expr.strip()).groups()), None, None)
  248. if op == 'exp':
  249. return lambda n: min(float(start) * (float(step or 2) ** n), float(limit or 'inf'))
  250. else:
  251. default_step = start if op or limit else 0
  252. return lambda n: min(float(start) + float(step or default_step) * n, float(limit or 'inf'))
  253. for key, expr in opts.retry_sleep.items():
  254. if not expr:
  255. del opts.retry_sleep[key]
  256. continue
  257. try:
  258. opts.retry_sleep[key] = parse_sleep_func(expr)
  259. except AttributeError:
  260. raise ValueError(f'invalid {key} retry sleep expression {expr!r}')
  261. # Bytes
  262. def validate_bytes(name, value, strict_positive=False):
  263. if value is None:
  264. return None
  265. numeric_limit = parse_bytes(value)
  266. validate(numeric_limit is not None, name, value)
  267. if strict_positive:
  268. validate_positive(name, numeric_limit, True)
  269. return numeric_limit
  270. opts.ratelimit = validate_bytes('rate limit', opts.ratelimit, True)
  271. opts.throttledratelimit = validate_bytes('throttled rate limit', opts.throttledratelimit)
  272. opts.min_filesize = validate_bytes('min filesize', opts.min_filesize)
  273. opts.max_filesize = validate_bytes('max filesize', opts.max_filesize)
  274. opts.buffersize = validate_bytes('buffer size', opts.buffersize, True)
  275. opts.http_chunk_size = validate_bytes('http chunk size', opts.http_chunk_size)
  276. # Output templates
  277. def validate_outtmpl(tmpl, msg):
  278. err = YoutubeDL.validate_outtmpl(tmpl)
  279. if err:
  280. raise ValueError(f'invalid {msg} "{tmpl}": {err}')
  281. for k, tmpl in opts.outtmpl.items():
  282. validate_outtmpl(tmpl, f'{k} output template')
  283. for type_, tmpl_list in opts.forceprint.items():
  284. for tmpl in tmpl_list:
  285. validate_outtmpl(tmpl, f'{type_} print template')
  286. for type_, tmpl_list in opts.print_to_file.items():
  287. for tmpl, file in tmpl_list:
  288. validate_outtmpl(tmpl, f'{type_} print to file template')
  289. validate_outtmpl(file, f'{type_} print to file filename')
  290. validate_outtmpl(opts.sponsorblock_chapter_title, 'SponsorBlock chapter title')
  291. for k, tmpl in opts.progress_template.items():
  292. k = f'{k[:-6]} console title' if '-title' in k else f'{k} progress'
  293. validate_outtmpl(tmpl, f'{k} template')
  294. outtmpl_default = opts.outtmpl.get('default')
  295. if outtmpl_default == '':
  296. opts.skip_download = None
  297. del opts.outtmpl['default']
  298. def parse_chapters(name, value, advanced=False):
  299. parse_timestamp = lambda x: float('inf') if x in ('inf', 'infinite') else parse_duration(x)
  300. TIMESTAMP_RE = r'''(?x)(?:
  301. (?P<start_sign>-?)(?P<start>[^-]+)
  302. )?\s*-\s*(?:
  303. (?P<end_sign>-?)(?P<end>[^-]+)
  304. )?'''
  305. chapters, ranges, from_url = [], [], False
  306. for regex in value or []:
  307. if advanced and regex == '*from-url':
  308. from_url = True
  309. continue
  310. elif not regex.startswith('*'):
  311. try:
  312. chapters.append(re.compile(regex))
  313. except re.error as err:
  314. raise ValueError(f'invalid {name} regex "{regex}" - {err}')
  315. continue
  316. for range_ in map(str.strip, regex[1:].split(',')):
  317. mobj = range_ != '-' and re.fullmatch(TIMESTAMP_RE, range_)
  318. dur = mobj and [parse_timestamp(mobj.group('start') or '0'), parse_timestamp(mobj.group('end') or 'inf')]
  319. signs = mobj and (mobj.group('start_sign'), mobj.group('end_sign'))
  320. err = None
  321. if None in (dur or [None]):
  322. err = 'Must be of the form "*start-end"'
  323. elif not advanced and any(signs):
  324. err = 'Negative timestamps are not allowed'
  325. else:
  326. dur[0] *= -1 if signs[0] else 1
  327. dur[1] *= -1 if signs[1] else 1
  328. if dur[1] == float('-inf'):
  329. err = '"-inf" is not a valid end'
  330. if err:
  331. raise ValueError(f'invalid {name} time range "{regex}". {err}')
  332. ranges.append(dur)
  333. return chapters, ranges, from_url
  334. opts.remove_chapters, opts.remove_ranges, _ = parse_chapters('--remove-chapters', opts.remove_chapters)
  335. opts.download_ranges = download_range_func(*parse_chapters('--download-sections', opts.download_ranges, True))
  336. # Cookies from browser
  337. if opts.cookiesfrombrowser:
  338. container = None
  339. mobj = re.fullmatch(r'''(?x)
  340. (?P<name>[^+:]+)
  341. (?:\s*\+\s*(?P<keyring>[^:]+))?
  342. (?:\s*:\s*(?!:)(?P<profile>.+?))?
  343. (?:\s*::\s*(?P<container>.+))?
  344. ''', opts.cookiesfrombrowser)
  345. if mobj is None:
  346. raise ValueError(f'invalid cookies from browser arguments: {opts.cookiesfrombrowser}')
  347. browser_name, keyring, profile, container = mobj.group('name', 'keyring', 'profile', 'container')
  348. browser_name = browser_name.lower()
  349. if browser_name not in SUPPORTED_BROWSERS:
  350. raise ValueError(f'unsupported browser specified for cookies: "{browser_name}". '
  351. f'Supported browsers are: {", ".join(sorted(SUPPORTED_BROWSERS))}')
  352. if keyring is not None:
  353. keyring = keyring.upper()
  354. if keyring not in SUPPORTED_KEYRINGS:
  355. raise ValueError(f'unsupported keyring specified for cookies: "{keyring}". '
  356. f'Supported keyrings are: {", ".join(sorted(SUPPORTED_KEYRINGS))}')
  357. opts.cookiesfrombrowser = (browser_name, profile, keyring, container)
  358. if opts.impersonate is not None:
  359. opts.impersonate = ImpersonateTarget.from_str(opts.impersonate.lower())
  360. # MetadataParser
  361. def metadataparser_actions(f):
  362. if isinstance(f, str):
  363. cmd = f'--parse-metadata {shell_quote(f)}'
  364. try:
  365. actions = [MetadataFromFieldPP.to_action(f)]
  366. except Exception as err:
  367. raise ValueError(f'{cmd} is invalid; {err}')
  368. else:
  369. cmd = f'--replace-in-metadata {shell_quote(f)}'
  370. actions = ((MetadataParserPP.Actions.REPLACE, x, *f[1:]) for x in f[0].split(','))
  371. for action in actions:
  372. try:
  373. MetadataParserPP.validate_action(*action)
  374. except Exception as err:
  375. raise ValueError(f'{cmd} is invalid; {err}')
  376. yield action
  377. if opts.metafromtitle is not None:
  378. opts.parse_metadata.setdefault('pre_process', []).append(f'title:{opts.metafromtitle}')
  379. opts.parse_metadata = {
  380. k: list(itertools.chain(*map(metadataparser_actions, v)))
  381. for k, v in opts.parse_metadata.items()
  382. }
  383. # Other options
  384. if opts.playlist_items is not None:
  385. try:
  386. tuple(PlaylistEntries.parse_playlist_items(opts.playlist_items))
  387. except Exception as err:
  388. raise ValueError(f'Invalid playlist-items {opts.playlist_items!r}: {err}')
  389. opts.geo_bypass_country, opts.geo_bypass_ip_block = None, None
  390. if opts.geo_bypass.lower() not in ('default', 'never'):
  391. try:
  392. GeoUtils.random_ipv4(opts.geo_bypass)
  393. except Exception:
  394. raise ValueError(f'Unsupported --xff "{opts.geo_bypass}"')
  395. if len(opts.geo_bypass) == 2:
  396. opts.geo_bypass_country = opts.geo_bypass
  397. else:
  398. opts.geo_bypass_ip_block = opts.geo_bypass
  399. opts.geo_bypass = opts.geo_bypass.lower() != 'never'
  400. opts.match_filter = match_filter_func(opts.match_filter, opts.breaking_match_filter)
  401. if opts.download_archive is not None:
  402. opts.download_archive = expand_path(opts.download_archive)
  403. if opts.ffmpeg_location is not None:
  404. opts.ffmpeg_location = expand_path(opts.ffmpeg_location)
  405. if opts.user_agent is not None:
  406. opts.headers.setdefault('User-Agent', opts.user_agent)
  407. if opts.referer is not None:
  408. opts.headers.setdefault('Referer', opts.referer)
  409. if opts.no_sponsorblock:
  410. opts.sponsorblock_mark = opts.sponsorblock_remove = set()
  411. default_downloader = None
  412. for proto, path in opts.external_downloader.items():
  413. if path == 'native':
  414. continue
  415. ed = get_external_downloader(path)
  416. if ed is None:
  417. raise ValueError(
  418. f'No such {format_field(proto, None, "%s ", ignore="default")}external downloader "{path}"')
  419. elif ed and proto == 'default':
  420. default_downloader = ed.get_basename()
  421. for policy in opts.color.values():
  422. if policy not in ('always', 'auto', 'auto-tty', 'no_color', 'no_color-tty', 'never'):
  423. raise ValueError(f'"{policy}" is not a valid color policy')
  424. warnings, deprecation_warnings = [], []
  425. # Common mistake: -f best
  426. if opts.format == 'best':
  427. warnings.append('.\n '.join((
  428. '"-f best" selects the best pre-merged format which is often not the best option',
  429. 'To let yt-dlp download and merge the best available formats, simply do not pass any format selection',
  430. 'If you know what you are doing and want only the best pre-merged format, use "-f b" instead to suppress this warning')))
  431. # --(postprocessor/downloader)-args without name
  432. def report_args_compat(name, value, key1, key2=None, where=None):
  433. if key1 in value and key2 not in value:
  434. warnings.append(f'{name.title()} arguments given without specifying name. '
  435. f'The arguments will be given to {where or f"all {name}s"}')
  436. return True
  437. return False
  438. if report_args_compat('external downloader', opts.external_downloader_args,
  439. 'default', where=default_downloader) and default_downloader:
  440. # Compat with youtube-dl's behavior. See https://github.com/ytdl-org/youtube-dl/commit/49c5293014bc11ec8c009856cd63cffa6296c1e1
  441. opts.external_downloader_args.setdefault(default_downloader, opts.external_downloader_args.pop('default'))
  442. if report_args_compat('post-processor', opts.postprocessor_args, 'default-compat', 'default'):
  443. opts.postprocessor_args['default'] = opts.postprocessor_args.pop('default-compat')
  444. opts.postprocessor_args.setdefault('sponskrub', [])
  445. def report_conflict(arg1, opt1, arg2='--allow-unplayable-formats', opt2='allow_unplayable_formats',
  446. val1=NO_DEFAULT, val2=NO_DEFAULT, default=False):
  447. if val2 is NO_DEFAULT:
  448. val2 = getattr(opts, opt2)
  449. if not val2:
  450. return
  451. if val1 is NO_DEFAULT:
  452. val1 = getattr(opts, opt1)
  453. if val1:
  454. warnings.append(f'{arg1} is ignored since {arg2} was given')
  455. setattr(opts, opt1, default)
  456. # Conflicting options
  457. report_conflict('--playlist-reverse', 'playlist_reverse', '--playlist-random', 'playlist_random')
  458. report_conflict('--playlist-reverse', 'playlist_reverse', '--lazy-playlist', 'lazy_playlist')
  459. report_conflict('--playlist-random', 'playlist_random', '--lazy-playlist', 'lazy_playlist')
  460. report_conflict('--dateafter', 'dateafter', '--date', 'date', default=None)
  461. report_conflict('--datebefore', 'datebefore', '--date', 'date', default=None)
  462. report_conflict('--exec-before-download', 'exec_before_dl_cmd',
  463. '"--exec before_dl:"', 'exec_cmd', val2=opts.exec_cmd.get('before_dl'))
  464. report_conflict('--id', 'useid', '--output', 'outtmpl', val2=opts.outtmpl.get('default'))
  465. report_conflict('--remux-video', 'remuxvideo', '--recode-video', 'recodevideo')
  466. report_conflict('--sponskrub', 'sponskrub', '--remove-chapters', 'remove_chapters')
  467. report_conflict('--sponskrub', 'sponskrub', '--sponsorblock-mark', 'sponsorblock_mark')
  468. report_conflict('--sponskrub', 'sponskrub', '--sponsorblock-remove', 'sponsorblock_remove')
  469. report_conflict('--sponskrub-cut', 'sponskrub_cut', '--split-chapter', 'split_chapters',
  470. val1=opts.sponskrub and opts.sponskrub_cut)
  471. # Conflicts with --allow-unplayable-formats
  472. report_conflict('--embed-metadata', 'addmetadata')
  473. report_conflict('--embed-chapters', 'addchapters')
  474. report_conflict('--embed-info-json', 'embed_infojson')
  475. report_conflict('--embed-subs', 'embedsubtitles')
  476. report_conflict('--embed-thumbnail', 'embedthumbnail')
  477. report_conflict('--extract-audio', 'extractaudio')
  478. report_conflict('--fixup', 'fixup', val1=opts.fixup not in (None, 'never', 'ignore'), default='never')
  479. report_conflict('--recode-video', 'recodevideo')
  480. report_conflict('--remove-chapters', 'remove_chapters', default=[])
  481. report_conflict('--remux-video', 'remuxvideo')
  482. report_conflict('--sponskrub', 'sponskrub')
  483. report_conflict('--sponsorblock-remove', 'sponsorblock_remove', default=set())
  484. report_conflict('--xattrs', 'xattrs')
  485. # Fully deprecated options
  486. def report_deprecation(val, old, new=None):
  487. if not val:
  488. return
  489. deprecation_warnings.append(
  490. f'{old} is deprecated and may be removed in a future version. Use {new} instead' if new
  491. else f'{old} is deprecated and may not work as expected')
  492. report_deprecation(opts.sponskrub, '--sponskrub', '--sponsorblock-mark or --sponsorblock-remove')
  493. report_deprecation(not opts.prefer_ffmpeg, '--prefer-avconv', 'ffmpeg')
  494. # report_deprecation(opts.include_ads, '--include-ads') # We may re-implement this in future
  495. # report_deprecation(opts.call_home, '--call-home') # We may re-implement this in future
  496. # report_deprecation(opts.writeannotations, '--write-annotations') # It's just that no website has it
  497. # Dependent options
  498. opts.date = DateRange.day(opts.date) if opts.date else DateRange(opts.dateafter, opts.datebefore)
  499. if opts.exec_before_dl_cmd:
  500. opts.exec_cmd['before_dl'] = opts.exec_before_dl_cmd
  501. if opts.useid: # --id is not deprecated in youtube-dl
  502. opts.outtmpl['default'] = '%(id)s.%(ext)s'
  503. if opts.overwrites: # --force-overwrites implies --no-continue
  504. opts.continue_dl = False
  505. if (opts.addmetadata or opts.sponsorblock_mark) and opts.addchapters is None:
  506. # Add chapters when adding metadata or marking sponsors
  507. opts.addchapters = True
  508. if opts.extractaudio and not opts.keepvideo and opts.format is None:
  509. # Do not unnecessarily download audio
  510. opts.format = 'bestaudio/best'
  511. if opts.getcomments and opts.writeinfojson is None and not opts.embed_infojson:
  512. # If JSON is not printed anywhere, but comments are requested, save it to file
  513. if not opts.dumpjson or opts.print_json or opts.dump_single_json:
  514. opts.writeinfojson = True
  515. if opts.allsubtitles and not (opts.embedsubtitles or opts.writeautomaticsub):
  516. # --all-sub automatically sets --write-sub if --write-auto-sub is not given
  517. opts.writesubtitles = True
  518. if opts.addmetadata and opts.embed_infojson is None:
  519. # If embedding metadata and infojson is present, embed it
  520. opts.embed_infojson = 'if_exists'
  521. # Ask for passwords
  522. if opts.username is not None and opts.password is None:
  523. opts.password = getpass.getpass('Type account password and press [Return]: ')
  524. if opts.ap_username is not None and opts.ap_password is None:
  525. opts.ap_password = getpass.getpass('Type TV provider account password and press [Return]: ')
  526. # compat option changes global state destructively; only allow from cli
  527. if 'allow-unsafe-ext' in opts.compat_opts:
  528. warnings.append(
  529. 'Using allow-unsafe-ext opens you up to potential attacks. '
  530. 'Use with great care!')
  531. _UnsafeExtensionError.sanitize_extension = lambda x, prepend=False: x
  532. return warnings, deprecation_warnings
  533. def get_postprocessors(opts):
  534. yield from opts.add_postprocessors
  535. for when, actions in opts.parse_metadata.items():
  536. yield {
  537. 'key': 'MetadataParser',
  538. 'actions': actions,
  539. 'when': when,
  540. }
  541. sponsorblock_query = opts.sponsorblock_mark | opts.sponsorblock_remove
  542. if sponsorblock_query:
  543. yield {
  544. 'key': 'SponsorBlock',
  545. 'categories': sponsorblock_query,
  546. 'api': opts.sponsorblock_api,
  547. 'when': 'after_filter',
  548. }
  549. if opts.convertsubtitles:
  550. yield {
  551. 'key': 'FFmpegSubtitlesConvertor',
  552. 'format': opts.convertsubtitles,
  553. 'when': 'before_dl',
  554. }
  555. if opts.convertthumbnails:
  556. yield {
  557. 'key': 'FFmpegThumbnailsConvertor',
  558. 'format': opts.convertthumbnails,
  559. 'when': 'before_dl',
  560. }
  561. if opts.extractaudio:
  562. yield {
  563. 'key': 'FFmpegExtractAudio',
  564. 'preferredcodec': opts.audioformat,
  565. 'preferredquality': opts.audioquality,
  566. 'nopostoverwrites': opts.nopostoverwrites,
  567. }
  568. if opts.remuxvideo:
  569. yield {
  570. 'key': 'FFmpegVideoRemuxer',
  571. 'preferedformat': opts.remuxvideo,
  572. }
  573. if opts.recodevideo:
  574. yield {
  575. 'key': 'FFmpegVideoConvertor',
  576. 'preferedformat': opts.recodevideo,
  577. }
  578. # If ModifyChapters is going to remove chapters, subtitles must already be in the container.
  579. if opts.embedsubtitles:
  580. keep_subs = 'no-keep-subs' not in opts.compat_opts
  581. yield {
  582. 'key': 'FFmpegEmbedSubtitle',
  583. # already_have_subtitle = True prevents the file from being deleted after embedding
  584. 'already_have_subtitle': opts.writesubtitles and keep_subs,
  585. }
  586. if not opts.writeautomaticsub and keep_subs:
  587. opts.writesubtitles = True
  588. # ModifyChapters must run before FFmpegMetadataPP
  589. if opts.remove_chapters or sponsorblock_query:
  590. yield {
  591. 'key': 'ModifyChapters',
  592. 'remove_chapters_patterns': opts.remove_chapters,
  593. 'remove_sponsor_segments': opts.sponsorblock_remove,
  594. 'remove_ranges': opts.remove_ranges,
  595. 'sponsorblock_chapter_title': opts.sponsorblock_chapter_title,
  596. 'force_keyframes': opts.force_keyframes_at_cuts,
  597. }
  598. # FFmpegMetadataPP should be run after FFmpegVideoConvertorPP and
  599. # FFmpegExtractAudioPP as containers before conversion may not support
  600. # metadata (3gp, webm, etc.)
  601. # By default ffmpeg preserves metadata applicable for both
  602. # source and target containers. From this point the container won't change,
  603. # so metadata can be added here.
  604. if opts.addmetadata or opts.addchapters or opts.embed_infojson:
  605. yield {
  606. 'key': 'FFmpegMetadata',
  607. 'add_chapters': opts.addchapters,
  608. 'add_metadata': opts.addmetadata,
  609. 'add_infojson': opts.embed_infojson,
  610. }
  611. # Deprecated
  612. # This should be above EmbedThumbnail since sponskrub removes the thumbnail attachment
  613. # but must be below EmbedSubtitle and FFmpegMetadata
  614. # See https://github.com/yt-dlp/yt-dlp/issues/204 , https://github.com/faissaloo/SponSkrub/issues/29
  615. # If opts.sponskrub is None, sponskrub is used, but it silently fails if the executable can't be found
  616. if opts.sponskrub is not False:
  617. yield {
  618. 'key': 'SponSkrub',
  619. 'path': opts.sponskrub_path,
  620. 'args': opts.sponskrub_args,
  621. 'cut': opts.sponskrub_cut,
  622. 'force': opts.sponskrub_force,
  623. 'ignoreerror': opts.sponskrub is None,
  624. '_from_cli': True,
  625. }
  626. if opts.embedthumbnail:
  627. yield {
  628. 'key': 'EmbedThumbnail',
  629. # already_have_thumbnail = True prevents the file from being deleted after embedding
  630. 'already_have_thumbnail': opts.writethumbnail,
  631. }
  632. if not opts.writethumbnail:
  633. opts.writethumbnail = True
  634. opts.outtmpl['pl_thumbnail'] = ''
  635. if opts.split_chapters:
  636. yield {
  637. 'key': 'FFmpegSplitChapters',
  638. 'force_keyframes': opts.force_keyframes_at_cuts,
  639. }
  640. # XAttrMetadataPP should be run after post-processors that may change file contents
  641. if opts.xattrs:
  642. yield {'key': 'XAttrMetadata'}
  643. if opts.concat_playlist != 'never':
  644. yield {
  645. 'key': 'FFmpegConcat',
  646. 'only_multi_video': opts.concat_playlist != 'always',
  647. 'when': 'playlist',
  648. }
  649. # Exec must be the last PP of each category
  650. for when, exec_cmd in opts.exec_cmd.items():
  651. yield {
  652. 'key': 'Exec',
  653. 'exec_cmd': exec_cmd,
  654. 'when': when,
  655. }
  656. ParsedOptions = collections.namedtuple('ParsedOptions', ('parser', 'options', 'urls', 'ydl_opts'))
  657. def parse_options(argv=None):
  658. """@returns ParsedOptions(parser, opts, urls, ydl_opts)"""
  659. parser, opts, urls = parseOpts(argv)
  660. urls = get_urls(urls, opts.batchfile, -1 if opts.quiet and not opts.verbose else opts.verbose)
  661. set_compat_opts(opts)
  662. try:
  663. warnings, deprecation_warnings = validate_options(opts)
  664. except ValueError as err:
  665. parser.error(f'{err}\n')
  666. postprocessors = list(get_postprocessors(opts))
  667. print_only = bool(opts.forceprint) and all(k not in opts.forceprint for k in POSTPROCESS_WHEN[3:])
  668. any_getting = any(getattr(opts, k) for k in (
  669. 'dumpjson', 'dump_single_json', 'getdescription', 'getduration', 'getfilename',
  670. 'getformat', 'getid', 'getthumbnail', 'gettitle', 'geturl',
  671. ))
  672. if opts.quiet is None:
  673. opts.quiet = any_getting or opts.print_json or bool(opts.forceprint)
  674. playlist_pps = [pp for pp in postprocessors if pp.get('when') == 'playlist']
  675. write_playlist_infojson = (opts.writeinfojson and not opts.clean_infojson
  676. and opts.allow_playlist_files and opts.outtmpl.get('pl_infojson') != '')
  677. if not any((
  678. opts.extract_flat,
  679. opts.dump_single_json,
  680. opts.forceprint.get('playlist'),
  681. opts.print_to_file.get('playlist'),
  682. write_playlist_infojson,
  683. )):
  684. if not playlist_pps:
  685. opts.extract_flat = 'discard'
  686. elif playlist_pps == [{'key': 'FFmpegConcat', 'only_multi_video': True, 'when': 'playlist'}]:
  687. opts.extract_flat = 'discard_in_playlist'
  688. final_ext = (
  689. opts.recodevideo if opts.recodevideo in FFmpegVideoConvertorPP.SUPPORTED_EXTS
  690. else opts.remuxvideo if opts.remuxvideo in FFmpegVideoRemuxerPP.SUPPORTED_EXTS
  691. else opts.audioformat if (opts.extractaudio and opts.audioformat in FFmpegExtractAudioPP.SUPPORTED_EXTS)
  692. else None)
  693. return ParsedOptions(parser, opts, urls, {
  694. 'usenetrc': opts.usenetrc,
  695. 'netrc_location': opts.netrc_location,
  696. 'netrc_cmd': opts.netrc_cmd,
  697. 'username': opts.username,
  698. 'password': opts.password,
  699. 'twofactor': opts.twofactor,
  700. 'videopassword': opts.videopassword,
  701. 'ap_mso': opts.ap_mso,
  702. 'ap_username': opts.ap_username,
  703. 'ap_password': opts.ap_password,
  704. 'client_certificate': opts.client_certificate,
  705. 'client_certificate_key': opts.client_certificate_key,
  706. 'client_certificate_password': opts.client_certificate_password,
  707. 'quiet': opts.quiet,
  708. 'no_warnings': opts.no_warnings,
  709. 'forceurl': opts.geturl,
  710. 'forcetitle': opts.gettitle,
  711. 'forceid': opts.getid,
  712. 'forcethumbnail': opts.getthumbnail,
  713. 'forcedescription': opts.getdescription,
  714. 'forceduration': opts.getduration,
  715. 'forcefilename': opts.getfilename,
  716. 'forceformat': opts.getformat,
  717. 'forceprint': opts.forceprint,
  718. 'print_to_file': opts.print_to_file,
  719. 'forcejson': opts.dumpjson or opts.print_json,
  720. 'dump_single_json': opts.dump_single_json,
  721. 'force_write_download_archive': opts.force_write_download_archive,
  722. 'simulate': (print_only or any_getting or None) if opts.simulate is None else opts.simulate,
  723. 'skip_download': opts.skip_download,
  724. 'format': opts.format,
  725. 'allow_unplayable_formats': opts.allow_unplayable_formats,
  726. 'ignore_no_formats_error': opts.ignore_no_formats_error,
  727. 'format_sort': opts.format_sort,
  728. 'format_sort_force': opts.format_sort_force,
  729. 'allow_multiple_video_streams': opts.allow_multiple_video_streams,
  730. 'allow_multiple_audio_streams': opts.allow_multiple_audio_streams,
  731. 'check_formats': opts.check_formats,
  732. 'listformats': opts.listformats,
  733. 'listformats_table': opts.listformats_table,
  734. 'outtmpl': opts.outtmpl,
  735. 'outtmpl_na_placeholder': opts.outtmpl_na_placeholder,
  736. 'paths': opts.paths,
  737. 'autonumber_size': opts.autonumber_size,
  738. 'autonumber_start': opts.autonumber_start,
  739. 'restrictfilenames': opts.restrictfilenames,
  740. 'windowsfilenames': opts.windowsfilenames,
  741. 'ignoreerrors': opts.ignoreerrors,
  742. 'force_generic_extractor': opts.force_generic_extractor,
  743. 'allowed_extractors': opts.allowed_extractors or ['default'],
  744. 'ratelimit': opts.ratelimit,
  745. 'throttledratelimit': opts.throttledratelimit,
  746. 'overwrites': opts.overwrites,
  747. 'retries': opts.retries,
  748. 'file_access_retries': opts.file_access_retries,
  749. 'fragment_retries': opts.fragment_retries,
  750. 'extractor_retries': opts.extractor_retries,
  751. 'retry_sleep_functions': opts.retry_sleep,
  752. 'skip_unavailable_fragments': opts.skip_unavailable_fragments,
  753. 'keep_fragments': opts.keep_fragments,
  754. 'concurrent_fragment_downloads': opts.concurrent_fragment_downloads,
  755. 'buffersize': opts.buffersize,
  756. 'noresizebuffer': opts.noresizebuffer,
  757. 'http_chunk_size': opts.http_chunk_size,
  758. 'continuedl': opts.continue_dl,
  759. 'noprogress': opts.quiet if opts.noprogress is None else opts.noprogress,
  760. 'progress_with_newline': opts.progress_with_newline,
  761. 'progress_template': opts.progress_template,
  762. 'progress_delta': opts.progress_delta,
  763. 'playliststart': opts.playliststart,
  764. 'playlistend': opts.playlistend,
  765. 'playlistreverse': opts.playlist_reverse,
  766. 'playlistrandom': opts.playlist_random,
  767. 'lazy_playlist': opts.lazy_playlist,
  768. 'noplaylist': opts.noplaylist,
  769. 'logtostderr': opts.outtmpl.get('default') == '-',
  770. 'consoletitle': opts.consoletitle,
  771. 'nopart': opts.nopart,
  772. 'updatetime': opts.updatetime,
  773. 'writedescription': opts.writedescription,
  774. 'writeannotations': opts.writeannotations,
  775. 'writeinfojson': opts.writeinfojson,
  776. 'allow_playlist_files': opts.allow_playlist_files,
  777. 'clean_infojson': opts.clean_infojson,
  778. 'getcomments': opts.getcomments,
  779. 'writethumbnail': opts.writethumbnail is True,
  780. 'write_all_thumbnails': opts.writethumbnail == 'all',
  781. 'writelink': opts.writelink,
  782. 'writeurllink': opts.writeurllink,
  783. 'writewebloclink': opts.writewebloclink,
  784. 'writedesktoplink': opts.writedesktoplink,
  785. 'writesubtitles': opts.writesubtitles,
  786. 'writeautomaticsub': opts.writeautomaticsub,
  787. 'allsubtitles': opts.allsubtitles,
  788. 'listsubtitles': opts.listsubtitles,
  789. 'subtitlesformat': opts.subtitlesformat,
  790. 'subtitleslangs': opts.subtitleslangs,
  791. 'matchtitle': opts.matchtitle,
  792. 'rejecttitle': opts.rejecttitle,
  793. 'max_downloads': opts.max_downloads,
  794. 'prefer_free_formats': opts.prefer_free_formats,
  795. 'trim_file_name': opts.trim_file_name,
  796. 'verbose': opts.verbose,
  797. 'dump_intermediate_pages': opts.dump_intermediate_pages,
  798. 'write_pages': opts.write_pages,
  799. 'load_pages': opts.load_pages,
  800. 'test': opts.test,
  801. 'keepvideo': opts.keepvideo,
  802. 'min_filesize': opts.min_filesize,
  803. 'max_filesize': opts.max_filesize,
  804. 'min_views': opts.min_views,
  805. 'max_views': opts.max_views,
  806. 'daterange': opts.date,
  807. 'cachedir': opts.cachedir,
  808. 'youtube_print_sig_code': opts.youtube_print_sig_code,
  809. 'age_limit': opts.age_limit,
  810. 'download_archive': opts.download_archive,
  811. 'break_on_existing': opts.break_on_existing,
  812. 'break_on_reject': opts.break_on_reject,
  813. 'break_per_url': opts.break_per_url,
  814. 'skip_playlist_after_errors': opts.skip_playlist_after_errors,
  815. 'cookiefile': opts.cookiefile,
  816. 'cookiesfrombrowser': opts.cookiesfrombrowser,
  817. 'legacyserverconnect': opts.legacy_server_connect,
  818. 'nocheckcertificate': opts.no_check_certificate,
  819. 'prefer_insecure': opts.prefer_insecure,
  820. 'enable_file_urls': opts.enable_file_urls,
  821. 'http_headers': opts.headers,
  822. 'proxy': opts.proxy,
  823. 'socket_timeout': opts.socket_timeout,
  824. 'bidi_workaround': opts.bidi_workaround,
  825. 'debug_printtraffic': opts.debug_printtraffic,
  826. 'prefer_ffmpeg': opts.prefer_ffmpeg,
  827. 'include_ads': opts.include_ads,
  828. 'default_search': opts.default_search,
  829. 'dynamic_mpd': opts.dynamic_mpd,
  830. 'extractor_args': opts.extractor_args,
  831. 'youtube_include_dash_manifest': opts.youtube_include_dash_manifest,
  832. 'youtube_include_hls_manifest': opts.youtube_include_hls_manifest,
  833. 'encoding': opts.encoding,
  834. 'extract_flat': opts.extract_flat,
  835. 'live_from_start': opts.live_from_start,
  836. 'wait_for_video': opts.wait_for_video,
  837. 'mark_watched': opts.mark_watched,
  838. 'merge_output_format': opts.merge_output_format,
  839. 'final_ext': final_ext,
  840. 'postprocessors': postprocessors,
  841. 'fixup': opts.fixup,
  842. 'source_address': opts.source_address,
  843. 'impersonate': opts.impersonate,
  844. 'call_home': opts.call_home,
  845. 'sleep_interval_requests': opts.sleep_interval_requests,
  846. 'sleep_interval': opts.sleep_interval,
  847. 'max_sleep_interval': opts.max_sleep_interval,
  848. 'sleep_interval_subtitles': opts.sleep_interval_subtitles,
  849. 'external_downloader': opts.external_downloader,
  850. 'download_ranges': opts.download_ranges,
  851. 'force_keyframes_at_cuts': opts.force_keyframes_at_cuts,
  852. 'list_thumbnails': opts.list_thumbnails,
  853. 'playlist_items': opts.playlist_items,
  854. 'xattr_set_filesize': opts.xattr_set_filesize,
  855. 'match_filter': opts.match_filter,
  856. 'color': opts.color,
  857. 'ffmpeg_location': opts.ffmpeg_location,
  858. 'hls_prefer_native': opts.hls_prefer_native,
  859. 'hls_use_mpegts': opts.hls_use_mpegts,
  860. 'hls_split_discontinuity': opts.hls_split_discontinuity,
  861. 'external_downloader_args': opts.external_downloader_args,
  862. 'postprocessor_args': opts.postprocessor_args,
  863. 'cn_verification_proxy': opts.cn_verification_proxy,
  864. 'geo_verification_proxy': opts.geo_verification_proxy,
  865. 'geo_bypass': opts.geo_bypass,
  866. 'geo_bypass_country': opts.geo_bypass_country,
  867. 'geo_bypass_ip_block': opts.geo_bypass_ip_block,
  868. '_warnings': warnings,
  869. '_deprecation_warnings': deprecation_warnings,
  870. 'compat_opts': opts.compat_opts,
  871. })
  872. def _real_main(argv=None):
  873. setproctitle('yt-dlp')
  874. parser, opts, all_urls, ydl_opts = parse_options(argv)
  875. # HACK: Set the plugin dirs early on
  876. # TODO(coletdjnz): remove when plugin globals system is implemented
  877. if opts.plugin_dirs is not None:
  878. Config._plugin_dirs = list(map(expand_path, opts.plugin_dirs))
  879. # Dump user agent
  880. if opts.dump_user_agent:
  881. ua = traverse_obj(opts.headers, 'User-Agent', casesense=False, default=std_headers['User-Agent'])
  882. write_string(f'{ua}\n', out=sys.stdout)
  883. return
  884. if print_extractor_information(opts, all_urls):
  885. return
  886. # We may need ffmpeg_location without having access to the YoutubeDL instance
  887. # See https://github.com/yt-dlp/yt-dlp/issues/2191
  888. if opts.ffmpeg_location:
  889. FFmpegPostProcessor._ffmpeg_location.set(opts.ffmpeg_location)
  890. with YoutubeDL(ydl_opts) as ydl:
  891. pre_process = opts.update_self or opts.rm_cachedir
  892. actual_use = all_urls or opts.load_info_filename
  893. if opts.rm_cachedir:
  894. ydl.cache.remove()
  895. try:
  896. updater = Updater(ydl, opts.update_self)
  897. if opts.update_self and updater.update() and actual_use:
  898. if updater.cmd:
  899. return updater.restart()
  900. # This code is reachable only for zip variant in py < 3.10
  901. # It makes sense to exit here, but the old behavior is to continue
  902. ydl.report_warning('Restart yt-dlp to use the updated version')
  903. # return 100, 'ERROR: The program must exit for the update to complete'
  904. except Exception:
  905. traceback.print_exc()
  906. ydl._download_retcode = 100
  907. if opts.list_impersonate_targets:
  908. known_targets = [
  909. # List of simplified targets we know are supported,
  910. # to help users know what dependencies may be required.
  911. (ImpersonateTarget('chrome'), 'curl_cffi'),
  912. (ImpersonateTarget('edge'), 'curl_cffi'),
  913. (ImpersonateTarget('safari'), 'curl_cffi'),
  914. ]
  915. available_targets = ydl._get_available_impersonate_targets()
  916. def make_row(target, handler):
  917. return [
  918. join_nonempty(target.client.title(), target.version, delim='-') or '-',
  919. join_nonempty((target.os or '').title(), target.os_version, delim='-') or '-',
  920. handler,
  921. ]
  922. rows = [make_row(target, handler) for target, handler in available_targets]
  923. for known_target, known_handler in known_targets:
  924. if not any(
  925. known_target in target and handler == known_handler
  926. for target, handler in available_targets
  927. ):
  928. rows.append([
  929. ydl._format_out(text, ydl.Styles.SUPPRESS)
  930. for text in make_row(known_target, f'{known_handler} (not available)')
  931. ])
  932. ydl.to_screen('[info] Available impersonate targets')
  933. ydl.to_stdout(render_table(['Client', 'OS', 'Source'], rows, extra_gap=2, delim='-'))
  934. return
  935. if not actual_use:
  936. if pre_process:
  937. return ydl._download_retcode
  938. args = sys.argv[1:] if argv is None else argv
  939. ydl.warn_if_short_id(args)
  940. # Show a useful error message and wait for keypress if not launched from shell on Windows
  941. if not args and os.name == 'nt' and getattr(sys, 'frozen', False):
  942. import ctypes.wintypes
  943. import msvcrt
  944. kernel32 = ctypes.WinDLL('Kernel32')
  945. buffer = (1 * ctypes.wintypes.DWORD)()
  946. attached_processes = kernel32.GetConsoleProcessList(buffer, 1)
  947. # If we only have a single process attached, then the executable was double clicked
  948. # When using `pyinstaller` with `--onefile`, two processes get attached
  949. is_onefile = hasattr(sys, '_MEIPASS') and os.path.basename(sys._MEIPASS).startswith('_MEI')
  950. if attached_processes == 1 or (is_onefile and attached_processes == 2):
  951. print(parser._generate_error_message(
  952. 'Do not double-click the executable, instead call it from a command line.\n'
  953. 'Please read the README for further information on how to use yt-dlp: '
  954. 'https://github.com/yt-dlp/yt-dlp#readme'))
  955. msvcrt.getch()
  956. _exit(2)
  957. parser.error(
  958. 'You must provide at least one URL.\n'
  959. 'Type yt-dlp --help to see a list of all options.')
  960. parser.destroy()
  961. try:
  962. if opts.load_info_filename is not None:
  963. if all_urls:
  964. ydl.report_warning('URLs are ignored due to --load-info-json')
  965. return ydl.download_with_info_file(expand_path(opts.load_info_filename))
  966. else:
  967. return ydl.download(all_urls)
  968. except DownloadCancelled:
  969. ydl.to_screen('Aborting remaining downloads')
  970. return 101
  971. def main(argv=None):
  972. global _IN_CLI
  973. _IN_CLI = True
  974. try:
  975. _exit(*variadic(_real_main(argv)))
  976. except (CookieLoadError, DownloadError):
  977. _exit(1)
  978. except SameFileError as e:
  979. _exit(f'ERROR: {e}')
  980. except KeyboardInterrupt:
  981. _exit('\nERROR: Interrupted by user')
  982. except BrokenPipeError as e:
  983. # https://docs.python.org/3/library/signal.html#note-on-sigpipe
  984. devnull = os.open(os.devnull, os.O_WRONLY)
  985. os.dup2(devnull, sys.stdout.fileno())
  986. _exit(f'\nERROR: {e}')
  987. except optparse.OptParseError as e:
  988. _exit(2, f'\n{e}')
  989. from .extractor import gen_extractors, list_extractors
  990. __all__ = [
  991. 'YoutubeDL',
  992. 'gen_extractors',
  993. 'list_extractors',
  994. 'main',
  995. 'parse_options',
  996. ]