__init__.py 26 KB

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