__init__.py 47 KB

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