__init__.py 47 KB

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