YoutubeDL.py 187 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988
  1. import collections
  2. import contextlib
  3. import datetime
  4. import errno
  5. import fileinput
  6. import functools
  7. import io
  8. import itertools
  9. import json
  10. import locale
  11. import operator
  12. import os
  13. import random
  14. import re
  15. import shutil
  16. import subprocess
  17. import sys
  18. import tempfile
  19. import time
  20. import tokenize
  21. import traceback
  22. import unicodedata
  23. import urllib.request
  24. from string import ascii_letters
  25. from .cache import Cache
  26. from .compat import compat_os_name, compat_shlex_quote
  27. from .cookies import load_cookies
  28. from .downloader import FFmpegFD, get_suitable_downloader, shorten_protocol_name
  29. from .downloader.rtmp import rtmpdump_version
  30. from .extractor import gen_extractor_classes, get_info_extractor
  31. from .extractor.common import UnsupportedURLIE
  32. from .extractor.openload import PhantomJSwrapper
  33. from .minicurses import format_text
  34. from .postprocessor import _PLUGIN_CLASSES as plugin_postprocessors
  35. from .postprocessor import (
  36. EmbedThumbnailPP,
  37. FFmpegFixupDuplicateMoovPP,
  38. FFmpegFixupDurationPP,
  39. FFmpegFixupM3u8PP,
  40. FFmpegFixupM4aPP,
  41. FFmpegFixupStretchedPP,
  42. FFmpegFixupTimestampPP,
  43. FFmpegMergerPP,
  44. FFmpegPostProcessor,
  45. FFmpegVideoConvertorPP,
  46. MoveFilesAfterDownloadPP,
  47. get_postprocessor,
  48. )
  49. from .postprocessor.ffmpeg import resolve_mapping as resolve_recode_mapping
  50. from .update import REPOSITORY, current_git_head, detect_variant
  51. from .utils import (
  52. DEFAULT_OUTTMPL,
  53. IDENTITY,
  54. LINK_TEMPLATES,
  55. MEDIA_EXTENSIONS,
  56. NO_DEFAULT,
  57. NUMBER_RE,
  58. OUTTMPL_TYPES,
  59. POSTPROCESS_WHEN,
  60. STR_FORMAT_RE_TMPL,
  61. STR_FORMAT_TYPES,
  62. ContentTooShortError,
  63. DateRange,
  64. DownloadCancelled,
  65. DownloadError,
  66. EntryNotInPlaylist,
  67. ExistingVideoReached,
  68. ExtractorError,
  69. GeoRestrictedError,
  70. HEADRequest,
  71. ISO3166Utils,
  72. LazyList,
  73. MaxDownloadsReached,
  74. Namespace,
  75. PagedList,
  76. PerRequestProxyHandler,
  77. PlaylistEntries,
  78. Popen,
  79. PostProcessingError,
  80. ReExtractInfo,
  81. RejectedVideoReached,
  82. SameFileError,
  83. UnavailableVideoError,
  84. UserNotLive,
  85. YoutubeDLCookieProcessor,
  86. YoutubeDLHandler,
  87. YoutubeDLRedirectHandler,
  88. age_restricted,
  89. args_to_str,
  90. bug_reports_message,
  91. date_from_str,
  92. deprecation_warning,
  93. determine_ext,
  94. determine_protocol,
  95. encode_compat_str,
  96. encodeFilename,
  97. error_to_compat_str,
  98. escapeHTML,
  99. expand_path,
  100. filter_dict,
  101. float_or_none,
  102. format_bytes,
  103. format_decimal_suffix,
  104. format_field,
  105. formatSeconds,
  106. get_compatible_ext,
  107. get_domain,
  108. int_or_none,
  109. iri_to_uri,
  110. is_path_like,
  111. join_nonempty,
  112. locked_file,
  113. make_archive_id,
  114. make_dir,
  115. make_HTTPS_handler,
  116. merge_headers,
  117. network_exceptions,
  118. number_of_digits,
  119. orderedSet,
  120. orderedSet_from_options,
  121. parse_filesize,
  122. preferredencoding,
  123. prepend_extension,
  124. register_socks_protocols,
  125. remove_terminal_sequences,
  126. render_table,
  127. replace_extension,
  128. sanitize_filename,
  129. sanitize_path,
  130. sanitize_url,
  131. sanitized_Request,
  132. std_headers,
  133. str_or_none,
  134. strftime_or_none,
  135. subtitles_filename,
  136. supports_terminal_sequences,
  137. system_identifier,
  138. timetuple_from_msec,
  139. to_high_limit_path,
  140. traverse_obj,
  141. try_call,
  142. try_get,
  143. url_basename,
  144. variadic,
  145. version_tuple,
  146. windows_enable_vt_mode,
  147. write_json_file,
  148. write_string,
  149. )
  150. from .version import RELEASE_GIT_HEAD, VARIANT, __version__
  151. if compat_os_name == 'nt':
  152. import ctypes
  153. class YoutubeDL:
  154. """YoutubeDL class.
  155. YoutubeDL objects are the ones responsible of downloading the
  156. actual video file and writing it to disk if the user has requested
  157. it, among some other tasks. In most cases there should be one per
  158. program. As, given a video URL, the downloader doesn't know how to
  159. extract all the needed information, task that InfoExtractors do, it
  160. has to pass the URL to one of them.
  161. For this, YoutubeDL objects have a method that allows
  162. InfoExtractors to be registered in a given order. When it is passed
  163. a URL, the YoutubeDL object handles it to the first InfoExtractor it
  164. finds that reports being able to handle it. The InfoExtractor extracts
  165. all the information about the video or videos the URL refers to, and
  166. YoutubeDL process the extracted information, possibly using a File
  167. Downloader to download the video.
  168. YoutubeDL objects accept a lot of parameters. In order not to saturate
  169. the object constructor with arguments, it receives a dictionary of
  170. options instead. These options are available through the params
  171. attribute for the InfoExtractors to use. The YoutubeDL also
  172. registers itself as the downloader in charge for the InfoExtractors
  173. that are added to it, so this is a "mutual registration".
  174. Available options:
  175. username: Username for authentication purposes.
  176. password: Password for authentication purposes.
  177. videopassword: Password for accessing a video.
  178. ap_mso: Adobe Pass multiple-system operator identifier.
  179. ap_username: Multiple-system operator account username.
  180. ap_password: Multiple-system operator account password.
  181. usenetrc: Use netrc for authentication instead.
  182. verbose: Print additional info to stdout.
  183. quiet: Do not print messages to stdout.
  184. no_warnings: Do not print out anything for warnings.
  185. forceprint: A dict with keys WHEN mapped to a list of templates to
  186. print to stdout. The allowed keys are video or any of the
  187. items in utils.POSTPROCESS_WHEN.
  188. For compatibility, a single list is also accepted
  189. print_to_file: A dict with keys WHEN (same as forceprint) mapped to
  190. a list of tuples with (template, filename)
  191. forcejson: Force printing info_dict as JSON.
  192. dump_single_json: Force printing the info_dict of the whole playlist
  193. (or video) as a single JSON line.
  194. force_write_download_archive: Force writing download archive regardless
  195. of 'skip_download' or 'simulate'.
  196. simulate: Do not download the video files. If unset (or None),
  197. simulate only if listsubtitles, listformats or list_thumbnails is used
  198. format: Video format code. see "FORMAT SELECTION" for more details.
  199. You can also pass a function. The function takes 'ctx' as
  200. argument and returns the formats to download.
  201. See "build_format_selector" for an implementation
  202. allow_unplayable_formats: Allow unplayable formats to be extracted and downloaded.
  203. ignore_no_formats_error: Ignore "No video formats" error. Usefull for
  204. extracting metadata even if the video is not actually
  205. available for download (experimental)
  206. format_sort: A list of fields by which to sort the video formats.
  207. See "Sorting Formats" for more details.
  208. format_sort_force: Force the given format_sort. see "Sorting Formats"
  209. for more details.
  210. prefer_free_formats: Whether to prefer video formats with free containers
  211. over non-free ones of same quality.
  212. allow_multiple_video_streams: Allow multiple video streams to be merged
  213. into a single file
  214. allow_multiple_audio_streams: Allow multiple audio streams to be merged
  215. into a single file
  216. check_formats Whether to test if the formats are downloadable.
  217. Can be True (check all), False (check none),
  218. 'selected' (check selected formats),
  219. or None (check only if requested by extractor)
  220. paths: Dictionary of output paths. The allowed keys are 'home'
  221. 'temp' and the keys of OUTTMPL_TYPES (in utils.py)
  222. outtmpl: Dictionary of templates for output names. Allowed keys
  223. are 'default' and the keys of OUTTMPL_TYPES (in utils.py).
  224. For compatibility with youtube-dl, a single string can also be used
  225. outtmpl_na_placeholder: Placeholder for unavailable meta fields.
  226. restrictfilenames: Do not allow "&" and spaces in file names
  227. trim_file_name: Limit length of filename (extension excluded)
  228. windowsfilenames: Force the filenames to be windows compatible
  229. ignoreerrors: Do not stop on download/postprocessing errors.
  230. Can be 'only_download' to ignore only download errors.
  231. Default is 'only_download' for CLI, but False for API
  232. skip_playlist_after_errors: Number of allowed failures until the rest of
  233. the playlist is skipped
  234. allowed_extractors: List of regexes to match against extractor names that are allowed
  235. overwrites: Overwrite all video and metadata files if True,
  236. overwrite only non-video files if None
  237. and don't overwrite any file if False
  238. For compatibility with youtube-dl,
  239. "nooverwrites" may also be used instead
  240. playlist_items: Specific indices of playlist to download.
  241. playlistrandom: Download playlist items in random order.
  242. lazy_playlist: Process playlist entries as they are received.
  243. matchtitle: Download only matching titles.
  244. rejecttitle: Reject downloads for matching titles.
  245. logger: Log messages to a logging.Logger instance.
  246. logtostderr: Print everything to stderr instead of stdout.
  247. consoletitle: Display progress in console window's titlebar.
  248. writedescription: Write the video description to a .description file
  249. writeinfojson: Write the video description to a .info.json file
  250. clean_infojson: Remove private fields from the infojson
  251. getcomments: Extract video comments. This will not be written to disk
  252. unless writeinfojson is also given
  253. writeannotations: Write the video annotations to a .annotations.xml file
  254. writethumbnail: Write the thumbnail image to a file
  255. allow_playlist_files: Whether to write playlists' description, infojson etc
  256. also to disk when using the 'write*' options
  257. write_all_thumbnails: Write all thumbnail formats to files
  258. writelink: Write an internet shortcut file, depending on the
  259. current platform (.url/.webloc/.desktop)
  260. writeurllink: Write a Windows internet shortcut file (.url)
  261. writewebloclink: Write a macOS internet shortcut file (.webloc)
  262. writedesktoplink: Write a Linux internet shortcut file (.desktop)
  263. writesubtitles: Write the video subtitles to a file
  264. writeautomaticsub: Write the automatically generated subtitles to a file
  265. listsubtitles: Lists all available subtitles for the video
  266. subtitlesformat: The format code for subtitles
  267. subtitleslangs: List of languages of the subtitles to download (can be regex).
  268. The list may contain "all" to refer to all the available
  269. subtitles. The language can be prefixed with a "-" to
  270. exclude it from the requested languages, e.g. ['all', '-live_chat']
  271. keepvideo: Keep the video file after post-processing
  272. daterange: A DateRange object, download only if the upload_date is in the range.
  273. skip_download: Skip the actual download of the video file
  274. cachedir: Location of the cache files in the filesystem.
  275. False to disable filesystem cache.
  276. noplaylist: Download single video instead of a playlist if in doubt.
  277. age_limit: An integer representing the user's age in years.
  278. Unsuitable videos for the given age are skipped.
  279. min_views: An integer representing the minimum view count the video
  280. must have in order to not be skipped.
  281. Videos without view count information are always
  282. downloaded. None for no limit.
  283. max_views: An integer representing the maximum view count.
  284. Videos that are more popular than that are not
  285. downloaded.
  286. Videos without view count information are always
  287. downloaded. None for no limit.
  288. download_archive: A set, or the name of a file where all downloads are recorded.
  289. Videos already present in the file are not downloaded again.
  290. break_on_existing: Stop the download process after attempting to download a
  291. file that is in the archive.
  292. break_on_reject: Stop the download process when encountering a video that
  293. has been filtered out.
  294. break_per_url: Whether break_on_reject and break_on_existing
  295. should act on each input URL as opposed to for the entire queue
  296. cookiefile: File name or text stream from where cookies should be read and dumped to
  297. cookiesfrombrowser: A tuple containing the name of the browser, the profile
  298. name/path from where cookies are loaded, the name of the keyring,
  299. and the container name, e.g. ('chrome', ) or
  300. ('vivaldi', 'default', 'BASICTEXT') or ('firefox', 'default', None, 'Meta')
  301. legacyserverconnect: Explicitly allow HTTPS connection to servers that do not
  302. support RFC 5746 secure renegotiation
  303. nocheckcertificate: Do not verify SSL certificates
  304. client_certificate: Path to client certificate file in PEM format. May include the private key
  305. client_certificate_key: Path to private key file for client certificate
  306. client_certificate_password: Password for client certificate private key, if encrypted.
  307. If not provided and the key is encrypted, yt-dlp will ask interactively
  308. prefer_insecure: Use HTTP instead of HTTPS to retrieve information.
  309. (Only supported by some extractors)
  310. http_headers: A dictionary of custom headers to be used for all requests
  311. proxy: URL of the proxy server to use
  312. geo_verification_proxy: URL of the proxy to use for IP address verification
  313. on geo-restricted sites.
  314. socket_timeout: Time to wait for unresponsive hosts, in seconds
  315. bidi_workaround: Work around buggy terminals without bidirectional text
  316. support, using fridibi
  317. debug_printtraffic:Print out sent and received HTTP traffic
  318. default_search: Prepend this string if an input url is not valid.
  319. 'auto' for elaborate guessing
  320. encoding: Use this encoding instead of the system-specified.
  321. extract_flat: Whether to resolve and process url_results further
  322. * False: Always process (default)
  323. * True: Never process
  324. * 'in_playlist': Do not process inside playlist/multi_video
  325. * 'discard': Always process, but don't return the result
  326. from inside playlist/multi_video
  327. * 'discard_in_playlist': Same as "discard", but only for
  328. playlists (not multi_video)
  329. wait_for_video: If given, wait for scheduled streams to become available.
  330. The value should be a tuple containing the range
  331. (min_secs, max_secs) to wait between retries
  332. postprocessors: A list of dictionaries, each with an entry
  333. * key: The name of the postprocessor. See
  334. yt_dlp/postprocessor/__init__.py for a list.
  335. * when: When to run the postprocessor. Allowed values are
  336. the entries of utils.POSTPROCESS_WHEN
  337. Assumed to be 'post_process' if not given
  338. progress_hooks: A list of functions that get called on download
  339. progress, with a dictionary with the entries
  340. * status: One of "downloading", "error", or "finished".
  341. Check this first and ignore unknown values.
  342. * info_dict: The extracted info_dict
  343. If status is one of "downloading", or "finished", the
  344. following properties may also be present:
  345. * filename: The final filename (always present)
  346. * tmpfilename: The filename we're currently writing to
  347. * downloaded_bytes: Bytes on disk
  348. * total_bytes: Size of the whole file, None if unknown
  349. * total_bytes_estimate: Guess of the eventual file size,
  350. None if unavailable.
  351. * elapsed: The number of seconds since download started.
  352. * eta: The estimated time in seconds, None if unknown
  353. * speed: The download speed in bytes/second, None if
  354. unknown
  355. * fragment_index: The counter of the currently
  356. downloaded video fragment.
  357. * fragment_count: The number of fragments (= individual
  358. files that will be merged)
  359. Progress hooks are guaranteed to be called at least once
  360. (with status "finished") if the download is successful.
  361. postprocessor_hooks: A list of functions that get called on postprocessing
  362. progress, with a dictionary with the entries
  363. * status: One of "started", "processing", or "finished".
  364. Check this first and ignore unknown values.
  365. * postprocessor: Name of the postprocessor
  366. * info_dict: The extracted info_dict
  367. Progress hooks are guaranteed to be called at least twice
  368. (with status "started" and "finished") if the processing is successful.
  369. merge_output_format: "/" separated list of extensions to use when merging formats.
  370. final_ext: Expected final extension; used to detect when the file was
  371. already downloaded and converted
  372. fixup: Automatically correct known faults of the file.
  373. One of:
  374. - "never": do nothing
  375. - "warn": only emit a warning
  376. - "detect_or_warn": check whether we can do anything
  377. about it, warn otherwise (default)
  378. source_address: Client-side IP address to bind to.
  379. sleep_interval_requests: Number of seconds to sleep between requests
  380. during extraction
  381. sleep_interval: Number of seconds to sleep before each download when
  382. used alone or a lower bound of a range for randomized
  383. sleep before each download (minimum possible number
  384. of seconds to sleep) when used along with
  385. max_sleep_interval.
  386. max_sleep_interval:Upper bound of a range for randomized sleep before each
  387. download (maximum possible number of seconds to sleep).
  388. Must only be used along with sleep_interval.
  389. Actual sleep time will be a random float from range
  390. [sleep_interval; max_sleep_interval].
  391. sleep_interval_subtitles: Number of seconds to sleep before each subtitle download
  392. listformats: Print an overview of available video formats and exit.
  393. list_thumbnails: Print a table of all thumbnails and exit.
  394. match_filter: A function that gets called for every video with the signature
  395. (info_dict, *, incomplete: bool) -> Optional[str]
  396. For backward compatibility with youtube-dl, the signature
  397. (info_dict) -> Optional[str] is also allowed.
  398. - If it returns a message, the video is ignored.
  399. - If it returns None, the video is downloaded.
  400. - If it returns utils.NO_DEFAULT, the user is interactively
  401. asked whether to download the video.
  402. match_filter_func in utils.py is one example for this.
  403. no_color: Do not emit color codes in output.
  404. geo_bypass: Bypass geographic restriction via faking X-Forwarded-For
  405. HTTP header
  406. geo_bypass_country:
  407. Two-letter ISO 3166-2 country code that will be used for
  408. explicit geographic restriction bypassing via faking
  409. X-Forwarded-For HTTP header
  410. geo_bypass_ip_block:
  411. IP range in CIDR notation that will be used similarly to
  412. geo_bypass_country
  413. external_downloader: A dictionary of protocol keys and the executable of the
  414. external downloader to use for it. The allowed protocols
  415. are default|http|ftp|m3u8|dash|rtsp|rtmp|mms.
  416. Set the value to 'native' to use the native downloader
  417. compat_opts: Compatibility options. See "Differences in default behavior".
  418. The following options do not work when used through the API:
  419. filename, abort-on-error, multistreams, no-live-chat, format-sort
  420. no-clean-infojson, no-playlist-metafiles, no-keep-subs, no-attach-info-json.
  421. Refer __init__.py for their implementation
  422. progress_template: Dictionary of templates for progress outputs.
  423. Allowed keys are 'download', 'postprocess',
  424. 'download-title' (console title) and 'postprocess-title'.
  425. The template is mapped on a dictionary with keys 'progress' and 'info'
  426. retry_sleep_functions: Dictionary of functions that takes the number of attempts
  427. as argument and returns the time to sleep in seconds.
  428. Allowed keys are 'http', 'fragment', 'file_access'
  429. download_ranges: A callback function that gets called for every video with
  430. the signature (info_dict, ydl) -> Iterable[Section].
  431. Only the returned sections will be downloaded.
  432. Each Section is a dict with the following keys:
  433. * start_time: Start time of the section in seconds
  434. * end_time: End time of the section in seconds
  435. * title: Section title (Optional)
  436. * index: Section number (Optional)
  437. force_keyframes_at_cuts: Re-encode the video when downloading ranges to get precise cuts
  438. noprogress: Do not print the progress bar
  439. live_from_start: Whether to download livestreams videos from the start
  440. The following parameters are not used by YoutubeDL itself, they are used by
  441. the downloader (see yt_dlp/downloader/common.py):
  442. nopart, updatetime, buffersize, ratelimit, throttledratelimit, min_filesize,
  443. max_filesize, test, noresizebuffer, retries, file_access_retries, fragment_retries,
  444. continuedl, xattr_set_filesize, hls_use_mpegts, http_chunk_size,
  445. external_downloader_args, concurrent_fragment_downloads.
  446. The following options are used by the post processors:
  447. ffmpeg_location: Location of the ffmpeg/avconv binary; either the path
  448. to the binary or its containing directory.
  449. postprocessor_args: A dictionary of postprocessor/executable keys (in lower case)
  450. and a list of additional command-line arguments for the
  451. postprocessor/executable. The dict can also have "PP+EXE" keys
  452. which are used when the given exe is used by the given PP.
  453. Use 'default' as the name for arguments to passed to all PP
  454. For compatibility with youtube-dl, a single list of args
  455. can also be used
  456. The following options are used by the extractors:
  457. extractor_retries: Number of times to retry for known errors
  458. dynamic_mpd: Whether to process dynamic DASH manifests (default: True)
  459. hls_split_discontinuity: Split HLS playlists to different formats at
  460. discontinuities such as ad breaks (default: False)
  461. extractor_args: A dictionary of arguments to be passed to the extractors.
  462. See "EXTRACTOR ARGUMENTS" for details.
  463. E.g. {'youtube': {'skip': ['dash', 'hls']}}
  464. mark_watched: Mark videos watched (even with --simulate). Only for YouTube
  465. The following options are deprecated and may be removed in the future:
  466. force_generic_extractor: Force downloader to use the generic extractor
  467. - Use allowed_extractors = ['generic', 'default']
  468. playliststart: - Use playlist_items
  469. Playlist item to start at.
  470. playlistend: - Use playlist_items
  471. Playlist item to end at.
  472. playlistreverse: - Use playlist_items
  473. Download playlist items in reverse order.
  474. forceurl: - Use forceprint
  475. Force printing final URL.
  476. forcetitle: - Use forceprint
  477. Force printing title.
  478. forceid: - Use forceprint
  479. Force printing ID.
  480. forcethumbnail: - Use forceprint
  481. Force printing thumbnail URL.
  482. forcedescription: - Use forceprint
  483. Force printing description.
  484. forcefilename: - Use forceprint
  485. Force printing final filename.
  486. forceduration: - Use forceprint
  487. Force printing duration.
  488. allsubtitles: - Use subtitleslangs = ['all']
  489. Downloads all the subtitles of the video
  490. (requires writesubtitles or writeautomaticsub)
  491. include_ads: - Doesn't work
  492. Download ads as well
  493. call_home: - Not implemented
  494. Boolean, true iff we are allowed to contact the
  495. yt-dlp servers for debugging.
  496. post_hooks: - Register a custom postprocessor
  497. A list of functions that get called as the final step
  498. for each video file, after all postprocessors have been
  499. called. The filename will be passed as the only argument.
  500. hls_prefer_native: - Use external_downloader = {'m3u8': 'native'} or {'m3u8': 'ffmpeg'}.
  501. Use the native HLS downloader instead of ffmpeg/avconv
  502. if True, otherwise use ffmpeg/avconv if False, otherwise
  503. use downloader suggested by extractor if None.
  504. prefer_ffmpeg: - avconv support is deprecated
  505. If False, use avconv instead of ffmpeg if both are available,
  506. otherwise prefer ffmpeg.
  507. youtube_include_dash_manifest: - Use extractor_args
  508. If True (default), DASH manifests and related
  509. data will be downloaded and processed by extractor.
  510. You can reduce network I/O by disabling it if you don't
  511. care about DASH. (only for youtube)
  512. youtube_include_hls_manifest: - Use extractor_args
  513. If True (default), HLS manifests and related
  514. data will be downloaded and processed by extractor.
  515. You can reduce network I/O by disabling it if you don't
  516. care about HLS. (only for youtube)
  517. """
  518. _NUMERIC_FIELDS = {
  519. 'width', 'height', 'asr', 'audio_channels', 'fps',
  520. 'tbr', 'abr', 'vbr', 'filesize', 'filesize_approx',
  521. 'timestamp', 'release_timestamp',
  522. 'duration', 'view_count', 'like_count', 'dislike_count', 'repost_count',
  523. 'average_rating', 'comment_count', 'age_limit',
  524. 'start_time', 'end_time',
  525. 'chapter_number', 'season_number', 'episode_number',
  526. 'track_number', 'disc_number', 'release_year',
  527. }
  528. _format_fields = {
  529. # NB: Keep in sync with the docstring of extractor/common.py
  530. 'url', 'manifest_url', 'manifest_stream_number', 'ext', 'format', 'format_id', 'format_note',
  531. 'width', 'height', 'resolution', 'dynamic_range', 'tbr', 'abr', 'acodec', 'asr', 'audio_channels',
  532. 'vbr', 'fps', 'vcodec', 'container', 'filesize', 'filesize_approx',
  533. 'player_url', 'protocol', 'fragment_base_url', 'fragments', 'is_from_start',
  534. 'preference', 'language', 'language_preference', 'quality', 'source_preference',
  535. 'http_headers', 'stretched_ratio', 'no_resume', 'has_drm', 'downloader_options',
  536. 'page_url', 'app', 'play_path', 'tc_url', 'flash_version', 'rtmp_live', 'rtmp_conn', 'rtmp_protocol', 'rtmp_real_time'
  537. }
  538. _format_selection_exts = {
  539. 'audio': set(MEDIA_EXTENSIONS.common_audio),
  540. 'video': set(MEDIA_EXTENSIONS.common_video + ('3gp', )),
  541. 'storyboards': set(MEDIA_EXTENSIONS.storyboards),
  542. }
  543. def __init__(self, params=None, auto_init=True):
  544. """Create a FileDownloader object with the given options.
  545. @param auto_init Whether to load the default extractors and print header (if verbose).
  546. Set to 'no_verbose_header' to not print the header
  547. """
  548. if params is None:
  549. params = {}
  550. self.params = params
  551. self._ies = {}
  552. self._ies_instances = {}
  553. self._pps = {k: [] for k in POSTPROCESS_WHEN}
  554. self._printed_messages = set()
  555. self._first_webpage_request = True
  556. self._post_hooks = []
  557. self._progress_hooks = []
  558. self._postprocessor_hooks = []
  559. self._download_retcode = 0
  560. self._num_downloads = 0
  561. self._num_videos = 0
  562. self._playlist_level = 0
  563. self._playlist_urls = set()
  564. self.cache = Cache(self)
  565. windows_enable_vt_mode()
  566. stdout = sys.stderr if self.params.get('logtostderr') else sys.stdout
  567. self._out_files = Namespace(
  568. out=stdout,
  569. error=sys.stderr,
  570. screen=sys.stderr if self.params.get('quiet') else stdout,
  571. console=None if compat_os_name == 'nt' else next(
  572. filter(supports_terminal_sequences, (sys.stderr, sys.stdout)), None)
  573. )
  574. self._allow_colors = Namespace(**{
  575. type_: not self.params.get('no_color') and supports_terminal_sequences(stream)
  576. for type_, stream in self._out_files.items_ if type_ != 'console'
  577. })
  578. # The code is left like this to be reused for future deprecations
  579. MIN_SUPPORTED, MIN_RECOMMENDED = (3, 7), (3, 7)
  580. current_version = sys.version_info[:2]
  581. if current_version < MIN_RECOMMENDED:
  582. msg = ('Support for Python version %d.%d has been deprecated. '
  583. 'See https://github.com/yt-dlp/yt-dlp/issues/3764 for more details.'
  584. '\n You will no longer receive updates on this version')
  585. if current_version < MIN_SUPPORTED:
  586. msg = 'Python version %d.%d is no longer supported'
  587. self.deprecation_warning(
  588. f'{msg}! Please update to Python %d.%d or above' % (*current_version, *MIN_RECOMMENDED))
  589. if self.params.get('allow_unplayable_formats'):
  590. self.report_warning(
  591. f'You have asked for {self._format_err("UNPLAYABLE", self.Styles.EMPHASIS)} formats to be listed/downloaded. '
  592. 'This is a developer option intended for debugging. \n'
  593. ' If you experience any issues while using this option, '
  594. f'{self._format_err("DO NOT", self.Styles.ERROR)} open a bug report')
  595. def check_deprecated(param, option, suggestion):
  596. if self.params.get(param) is not None:
  597. self.report_warning(f'{option} is deprecated. Use {suggestion} instead')
  598. return True
  599. return False
  600. if check_deprecated('cn_verification_proxy', '--cn-verification-proxy', '--geo-verification-proxy'):
  601. if self.params.get('geo_verification_proxy') is None:
  602. self.params['geo_verification_proxy'] = self.params['cn_verification_proxy']
  603. check_deprecated('autonumber', '--auto-number', '-o "%(autonumber)s-%(title)s.%(ext)s"')
  604. check_deprecated('usetitle', '--title', '-o "%(title)s-%(id)s.%(ext)s"')
  605. check_deprecated('useid', '--id', '-o "%(id)s.%(ext)s"')
  606. for msg in self.params.get('_warnings', []):
  607. self.report_warning(msg)
  608. for msg in self.params.get('_deprecation_warnings', []):
  609. self.deprecated_feature(msg)
  610. self.params['compat_opts'] = set(self.params.get('compat_opts', ()))
  611. if 'list-formats' in self.params['compat_opts']:
  612. self.params['listformats_table'] = False
  613. if 'overwrites' not in self.params and self.params.get('nooverwrites') is not None:
  614. # nooverwrites was unnecessarily changed to overwrites
  615. # in 0c3d0f51778b153f65c21906031c2e091fcfb641
  616. # This ensures compatibility with both keys
  617. self.params['overwrites'] = not self.params['nooverwrites']
  618. elif self.params.get('overwrites') is None:
  619. self.params.pop('overwrites', None)
  620. else:
  621. self.params['nooverwrites'] = not self.params['overwrites']
  622. self.params.setdefault('forceprint', {})
  623. self.params.setdefault('print_to_file', {})
  624. # Compatibility with older syntax
  625. if not isinstance(params['forceprint'], dict):
  626. self.params['forceprint'] = {'video': params['forceprint']}
  627. if self.params.get('bidi_workaround', False):
  628. try:
  629. import pty
  630. master, slave = pty.openpty()
  631. width = shutil.get_terminal_size().columns
  632. width_args = [] if width is None else ['-w', str(width)]
  633. sp_kwargs = {'stdin': subprocess.PIPE, 'stdout': slave, 'stderr': self._out_files.error}
  634. try:
  635. self._output_process = Popen(['bidiv'] + width_args, **sp_kwargs)
  636. except OSError:
  637. self._output_process = Popen(['fribidi', '-c', 'UTF-8'] + width_args, **sp_kwargs)
  638. self._output_channel = os.fdopen(master, 'rb')
  639. except OSError as ose:
  640. if ose.errno == errno.ENOENT:
  641. self.report_warning(
  642. 'Could not find fribidi executable, ignoring --bidi-workaround. '
  643. 'Make sure that fribidi is an executable file in one of the directories in your $PATH.')
  644. else:
  645. raise
  646. if auto_init:
  647. if auto_init != 'no_verbose_header':
  648. self.print_debug_header()
  649. self.add_default_info_extractors()
  650. if (sys.platform != 'win32'
  651. and sys.getfilesystemencoding() in ['ascii', 'ANSI_X3.4-1968']
  652. and not self.params.get('restrictfilenames', False)):
  653. # Unicode filesystem API will throw errors (#1474, #13027)
  654. self.report_warning(
  655. 'Assuming --restrict-filenames since file system encoding '
  656. 'cannot encode all characters. '
  657. 'Set the LC_ALL environment variable to fix this.')
  658. self.params['restrictfilenames'] = True
  659. self._parse_outtmpl()
  660. # Creating format selector here allows us to catch syntax errors before the extraction
  661. self.format_selector = (
  662. self.params.get('format') if self.params.get('format') in (None, '-')
  663. else self.params['format'] if callable(self.params['format'])
  664. else self.build_format_selector(self.params['format']))
  665. # Set http_headers defaults according to std_headers
  666. self.params['http_headers'] = merge_headers(std_headers, self.params.get('http_headers', {}))
  667. hooks = {
  668. 'post_hooks': self.add_post_hook,
  669. 'progress_hooks': self.add_progress_hook,
  670. 'postprocessor_hooks': self.add_postprocessor_hook,
  671. }
  672. for opt, fn in hooks.items():
  673. for ph in self.params.get(opt, []):
  674. fn(ph)
  675. for pp_def_raw in self.params.get('postprocessors', []):
  676. pp_def = dict(pp_def_raw)
  677. when = pp_def.pop('when', 'post_process')
  678. self.add_post_processor(
  679. get_postprocessor(pp_def.pop('key'))(self, **pp_def),
  680. when=when)
  681. self._setup_opener()
  682. register_socks_protocols()
  683. def preload_download_archive(fn):
  684. """Preload the archive, if any is specified"""
  685. archive = set()
  686. if fn is None:
  687. return archive
  688. elif not is_path_like(fn):
  689. return fn
  690. self.write_debug(f'Loading archive file {fn!r}')
  691. try:
  692. with locked_file(fn, 'r', encoding='utf-8') as archive_file:
  693. for line in archive_file:
  694. archive.add(line.strip())
  695. except OSError as ioe:
  696. if ioe.errno != errno.ENOENT:
  697. raise
  698. return archive
  699. self.archive = preload_download_archive(self.params.get('download_archive'))
  700. def warn_if_short_id(self, argv):
  701. # short YouTube ID starting with dash?
  702. idxs = [
  703. i for i, a in enumerate(argv)
  704. if re.match(r'^-[0-9A-Za-z_-]{10}$', a)]
  705. if idxs:
  706. correct_argv = (
  707. ['yt-dlp']
  708. + [a for i, a in enumerate(argv) if i not in idxs]
  709. + ['--'] + [argv[i] for i in idxs]
  710. )
  711. self.report_warning(
  712. 'Long argument string detected. '
  713. 'Use -- to separate parameters and URLs, like this:\n%s' %
  714. args_to_str(correct_argv))
  715. def add_info_extractor(self, ie):
  716. """Add an InfoExtractor object to the end of the list."""
  717. ie_key = ie.ie_key()
  718. self._ies[ie_key] = ie
  719. if not isinstance(ie, type):
  720. self._ies_instances[ie_key] = ie
  721. ie.set_downloader(self)
  722. def get_info_extractor(self, ie_key):
  723. """
  724. Get an instance of an IE with name ie_key, it will try to get one from
  725. the _ies list, if there's no instance it will create a new one and add
  726. it to the extractor list.
  727. """
  728. ie = self._ies_instances.get(ie_key)
  729. if ie is None:
  730. ie = get_info_extractor(ie_key)()
  731. self.add_info_extractor(ie)
  732. return ie
  733. def add_default_info_extractors(self):
  734. """
  735. Add the InfoExtractors returned by gen_extractors to the end of the list
  736. """
  737. all_ies = {ie.IE_NAME.lower(): ie for ie in gen_extractor_classes()}
  738. all_ies['end'] = UnsupportedURLIE()
  739. try:
  740. ie_names = orderedSet_from_options(
  741. self.params.get('allowed_extractors', ['default']), {
  742. 'all': list(all_ies),
  743. 'default': [name for name, ie in all_ies.items() if ie._ENABLED],
  744. }, use_regex=True)
  745. except re.error as e:
  746. raise ValueError(f'Wrong regex for allowed_extractors: {e.pattern}')
  747. for name in ie_names:
  748. self.add_info_extractor(all_ies[name])
  749. self.write_debug(f'Loaded {len(ie_names)} extractors')
  750. def add_post_processor(self, pp, when='post_process'):
  751. """Add a PostProcessor object to the end of the chain."""
  752. assert when in POSTPROCESS_WHEN, f'Invalid when={when}'
  753. self._pps[when].append(pp)
  754. pp.set_downloader(self)
  755. def add_post_hook(self, ph):
  756. """Add the post hook"""
  757. self._post_hooks.append(ph)
  758. def add_progress_hook(self, ph):
  759. """Add the download progress hook"""
  760. self._progress_hooks.append(ph)
  761. def add_postprocessor_hook(self, ph):
  762. """Add the postprocessing progress hook"""
  763. self._postprocessor_hooks.append(ph)
  764. for pps in self._pps.values():
  765. for pp in pps:
  766. pp.add_progress_hook(ph)
  767. def _bidi_workaround(self, message):
  768. if not hasattr(self, '_output_channel'):
  769. return message
  770. assert hasattr(self, '_output_process')
  771. assert isinstance(message, str)
  772. line_count = message.count('\n') + 1
  773. self._output_process.stdin.write((message + '\n').encode())
  774. self._output_process.stdin.flush()
  775. res = ''.join(self._output_channel.readline().decode()
  776. for _ in range(line_count))
  777. return res[:-len('\n')]
  778. def _write_string(self, message, out=None, only_once=False):
  779. if only_once:
  780. if message in self._printed_messages:
  781. return
  782. self._printed_messages.add(message)
  783. write_string(message, out=out, encoding=self.params.get('encoding'))
  784. def to_stdout(self, message, skip_eol=False, quiet=None):
  785. """Print message to stdout"""
  786. if quiet is not None:
  787. self.deprecation_warning('"YoutubeDL.to_stdout" no longer accepts the argument quiet. '
  788. 'Use "YoutubeDL.to_screen" instead')
  789. if skip_eol is not False:
  790. self.deprecation_warning('"YoutubeDL.to_stdout" no longer accepts the argument skip_eol. '
  791. 'Use "YoutubeDL.to_screen" instead')
  792. self._write_string(f'{self._bidi_workaround(message)}\n', self._out_files.out)
  793. def to_screen(self, message, skip_eol=False, quiet=None, only_once=False):
  794. """Print message to screen if not in quiet mode"""
  795. if self.params.get('logger'):
  796. self.params['logger'].debug(message)
  797. return
  798. if (self.params.get('quiet') if quiet is None else quiet) and not self.params.get('verbose'):
  799. return
  800. self._write_string(
  801. '%s%s' % (self._bidi_workaround(message), ('' if skip_eol else '\n')),
  802. self._out_files.screen, only_once=only_once)
  803. def to_stderr(self, message, only_once=False):
  804. """Print message to stderr"""
  805. assert isinstance(message, str)
  806. if self.params.get('logger'):
  807. self.params['logger'].error(message)
  808. else:
  809. self._write_string(f'{self._bidi_workaround(message)}\n', self._out_files.error, only_once=only_once)
  810. def _send_console_code(self, code):
  811. if compat_os_name == 'nt' or not self._out_files.console:
  812. return
  813. self._write_string(code, self._out_files.console)
  814. def to_console_title(self, message):
  815. if not self.params.get('consoletitle', False):
  816. return
  817. message = remove_terminal_sequences(message)
  818. if compat_os_name == 'nt':
  819. if ctypes.windll.kernel32.GetConsoleWindow():
  820. # c_wchar_p() might not be necessary if `message` is
  821. # already of type unicode()
  822. ctypes.windll.kernel32.SetConsoleTitleW(ctypes.c_wchar_p(message))
  823. else:
  824. self._send_console_code(f'\033]0;{message}\007')
  825. def save_console_title(self):
  826. if not self.params.get('consoletitle') or self.params.get('simulate'):
  827. return
  828. self._send_console_code('\033[22;0t') # Save the title on stack
  829. def restore_console_title(self):
  830. if not self.params.get('consoletitle') or self.params.get('simulate'):
  831. return
  832. self._send_console_code('\033[23;0t') # Restore the title from stack
  833. def __enter__(self):
  834. self.save_console_title()
  835. return self
  836. def __exit__(self, *args):
  837. self.restore_console_title()
  838. if self.params.get('cookiefile') is not None:
  839. self.cookiejar.save(ignore_discard=True, ignore_expires=True)
  840. def trouble(self, message=None, tb=None, is_error=True):
  841. """Determine action to take when a download problem appears.
  842. Depending on if the downloader has been configured to ignore
  843. download errors or not, this method may throw an exception or
  844. not when errors are found, after printing the message.
  845. @param tb If given, is additional traceback information
  846. @param is_error Whether to raise error according to ignorerrors
  847. """
  848. if message is not None:
  849. self.to_stderr(message)
  850. if self.params.get('verbose'):
  851. if tb is None:
  852. if sys.exc_info()[0]: # if .trouble has been called from an except block
  853. tb = ''
  854. if hasattr(sys.exc_info()[1], 'exc_info') and sys.exc_info()[1].exc_info[0]:
  855. tb += ''.join(traceback.format_exception(*sys.exc_info()[1].exc_info))
  856. tb += encode_compat_str(traceback.format_exc())
  857. else:
  858. tb_data = traceback.format_list(traceback.extract_stack())
  859. tb = ''.join(tb_data)
  860. if tb:
  861. self.to_stderr(tb)
  862. if not is_error:
  863. return
  864. if not self.params.get('ignoreerrors'):
  865. if sys.exc_info()[0] and hasattr(sys.exc_info()[1], 'exc_info') and sys.exc_info()[1].exc_info[0]:
  866. exc_info = sys.exc_info()[1].exc_info
  867. else:
  868. exc_info = sys.exc_info()
  869. raise DownloadError(message, exc_info)
  870. self._download_retcode = 1
  871. Styles = Namespace(
  872. HEADERS='yellow',
  873. EMPHASIS='light blue',
  874. FILENAME='green',
  875. ID='green',
  876. DELIM='blue',
  877. ERROR='red',
  878. WARNING='yellow',
  879. SUPPRESS='light black',
  880. )
  881. def _format_text(self, handle, allow_colors, text, f, fallback=None, *, test_encoding=False):
  882. text = str(text)
  883. if test_encoding:
  884. original_text = text
  885. # handle.encoding can be None. See https://github.com/yt-dlp/yt-dlp/issues/2711
  886. encoding = self.params.get('encoding') or getattr(handle, 'encoding', None) or 'ascii'
  887. text = text.encode(encoding, 'ignore').decode(encoding)
  888. if fallback is not None and text != original_text:
  889. text = fallback
  890. return format_text(text, f) if allow_colors else text if fallback is None else fallback
  891. def _format_out(self, *args, **kwargs):
  892. return self._format_text(self._out_files.out, self._allow_colors.out, *args, **kwargs)
  893. def _format_screen(self, *args, **kwargs):
  894. return self._format_text(self._out_files.screen, self._allow_colors.screen, *args, **kwargs)
  895. def _format_err(self, *args, **kwargs):
  896. return self._format_text(self._out_files.error, self._allow_colors.error, *args, **kwargs)
  897. def report_warning(self, message, only_once=False):
  898. '''
  899. Print the message to stderr, it will be prefixed with 'WARNING:'
  900. If stderr is a tty file the 'WARNING:' will be colored
  901. '''
  902. if self.params.get('logger') is not None:
  903. self.params['logger'].warning(message)
  904. else:
  905. if self.params.get('no_warnings'):
  906. return
  907. self.to_stderr(f'{self._format_err("WARNING:", self.Styles.WARNING)} {message}', only_once)
  908. def deprecation_warning(self, message, *, stacklevel=0):
  909. deprecation_warning(
  910. message, stacklevel=stacklevel + 1, printer=self.report_error, is_error=False)
  911. def deprecated_feature(self, message):
  912. if self.params.get('logger') is not None:
  913. self.params['logger'].warning(f'Deprecated Feature: {message}')
  914. self.to_stderr(f'{self._format_err("Deprecated Feature:", self.Styles.ERROR)} {message}', True)
  915. def report_error(self, message, *args, **kwargs):
  916. '''
  917. Do the same as trouble, but prefixes the message with 'ERROR:', colored
  918. in red if stderr is a tty file.
  919. '''
  920. self.trouble(f'{self._format_err("ERROR:", self.Styles.ERROR)} {message}', *args, **kwargs)
  921. def write_debug(self, message, only_once=False):
  922. '''Log debug message or Print message to stderr'''
  923. if not self.params.get('verbose', False):
  924. return
  925. message = f'[debug] {message}'
  926. if self.params.get('logger'):
  927. self.params['logger'].debug(message)
  928. else:
  929. self.to_stderr(message, only_once)
  930. def report_file_already_downloaded(self, file_name):
  931. """Report file has already been fully downloaded."""
  932. try:
  933. self.to_screen('[download] %s has already been downloaded' % file_name)
  934. except UnicodeEncodeError:
  935. self.to_screen('[download] The file has already been downloaded')
  936. def report_file_delete(self, file_name):
  937. """Report that existing file will be deleted."""
  938. try:
  939. self.to_screen('Deleting existing file %s' % file_name)
  940. except UnicodeEncodeError:
  941. self.to_screen('Deleting existing file')
  942. def raise_no_formats(self, info, forced=False, *, msg=None):
  943. has_drm = info.get('_has_drm')
  944. ignored, expected = self.params.get('ignore_no_formats_error'), bool(msg)
  945. msg = msg or has_drm and 'This video is DRM protected' or 'No video formats found!'
  946. if forced or not ignored:
  947. raise ExtractorError(msg, video_id=info['id'], ie=info['extractor'],
  948. expected=has_drm or ignored or expected)
  949. else:
  950. self.report_warning(msg)
  951. def parse_outtmpl(self):
  952. self.deprecation_warning('"YoutubeDL.parse_outtmpl" is deprecated and may be removed in a future version')
  953. self._parse_outtmpl()
  954. return self.params['outtmpl']
  955. def _parse_outtmpl(self):
  956. sanitize = IDENTITY
  957. if self.params.get('restrictfilenames'): # Remove spaces in the default template
  958. sanitize = lambda x: x.replace(' - ', ' ').replace(' ', '-')
  959. outtmpl = self.params.setdefault('outtmpl', {})
  960. if not isinstance(outtmpl, dict):
  961. self.params['outtmpl'] = outtmpl = {'default': outtmpl}
  962. outtmpl.update({k: sanitize(v) for k, v in DEFAULT_OUTTMPL.items() if outtmpl.get(k) is None})
  963. def get_output_path(self, dir_type='', filename=None):
  964. paths = self.params.get('paths', {})
  965. assert isinstance(paths, dict), '"paths" parameter must be a dictionary'
  966. path = os.path.join(
  967. expand_path(paths.get('home', '').strip()),
  968. expand_path(paths.get(dir_type, '').strip()) if dir_type else '',
  969. filename or '')
  970. return sanitize_path(path, force=self.params.get('windowsfilenames'))
  971. @staticmethod
  972. def _outtmpl_expandpath(outtmpl):
  973. # expand_path translates '%%' into '%' and '$$' into '$'
  974. # correspondingly that is not what we want since we need to keep
  975. # '%%' intact for template dict substitution step. Working around
  976. # with boundary-alike separator hack.
  977. sep = ''.join([random.choice(ascii_letters) for _ in range(32)])
  978. outtmpl = outtmpl.replace('%%', f'%{sep}%').replace('$$', f'${sep}$')
  979. # outtmpl should be expand_path'ed before template dict substitution
  980. # because meta fields may contain env variables we don't want to
  981. # be expanded. E.g. for outtmpl "%(title)s.%(ext)s" and
  982. # title "Hello $PATH", we don't want `$PATH` to be expanded.
  983. return expand_path(outtmpl).replace(sep, '')
  984. @staticmethod
  985. def escape_outtmpl(outtmpl):
  986. ''' Escape any remaining strings like %s, %abc% etc. '''
  987. return re.sub(
  988. STR_FORMAT_RE_TMPL.format('', '(?![%(\0])'),
  989. lambda mobj: ('' if mobj.group('has_key') else '%') + mobj.group(0),
  990. outtmpl)
  991. @classmethod
  992. def validate_outtmpl(cls, outtmpl):
  993. ''' @return None or Exception object '''
  994. outtmpl = re.sub(
  995. STR_FORMAT_RE_TMPL.format('[^)]*', '[ljhqBUDS]'),
  996. lambda mobj: f'{mobj.group(0)[:-1]}s',
  997. cls._outtmpl_expandpath(outtmpl))
  998. try:
  999. cls.escape_outtmpl(outtmpl) % collections.defaultdict(int)
  1000. return None
  1001. except ValueError as err:
  1002. return err
  1003. @staticmethod
  1004. def _copy_infodict(info_dict):
  1005. info_dict = dict(info_dict)
  1006. info_dict.pop('__postprocessors', None)
  1007. info_dict.pop('__pending_error', None)
  1008. return info_dict
  1009. def prepare_outtmpl(self, outtmpl, info_dict, sanitize=False):
  1010. """ Make the outtmpl and info_dict suitable for substitution: ydl.escape_outtmpl(outtmpl) % info_dict
  1011. @param sanitize Whether to sanitize the output as a filename.
  1012. For backward compatibility, a function can also be passed
  1013. """
  1014. info_dict.setdefault('epoch', int(time.time())) # keep epoch consistent once set
  1015. info_dict = self._copy_infodict(info_dict)
  1016. info_dict['duration_string'] = ( # %(duration>%H-%M-%S)s is wrong if duration > 24hrs
  1017. formatSeconds(info_dict['duration'], '-' if sanitize else ':')
  1018. if info_dict.get('duration', None) is not None
  1019. else None)
  1020. info_dict['autonumber'] = int(self.params.get('autonumber_start', 1) - 1 + self._num_downloads)
  1021. info_dict['video_autonumber'] = self._num_videos
  1022. if info_dict.get('resolution') is None:
  1023. info_dict['resolution'] = self.format_resolution(info_dict, default=None)
  1024. # For fields playlist_index, playlist_autonumber and autonumber convert all occurrences
  1025. # of %(field)s to %(field)0Nd for backward compatibility
  1026. field_size_compat_map = {
  1027. 'playlist_index': number_of_digits(info_dict.get('__last_playlist_index') or 0),
  1028. 'playlist_autonumber': number_of_digits(info_dict.get('n_entries') or 0),
  1029. 'autonumber': self.params.get('autonumber_size') or 5,
  1030. }
  1031. TMPL_DICT = {}
  1032. EXTERNAL_FORMAT_RE = re.compile(STR_FORMAT_RE_TMPL.format('[^)]*', f'[{STR_FORMAT_TYPES}ljhqBUDS]'))
  1033. MATH_FUNCTIONS = {
  1034. '+': float.__add__,
  1035. '-': float.__sub__,
  1036. }
  1037. # Field is of the form key1.key2...
  1038. # where keys (except first) can be string, int, slice or "{field, ...}"
  1039. FIELD_INNER_RE = r'(?:\w+|%(num)s|%(num)s?(?::%(num)s?){1,2})' % {'num': r'(?:-?\d+)'}
  1040. FIELD_RE = r'\w*(?:\.(?:%(inner)s|{%(field)s(?:,%(field)s)*}))*' % {
  1041. 'inner': FIELD_INNER_RE,
  1042. 'field': rf'\w*(?:\.{FIELD_INNER_RE})*'
  1043. }
  1044. MATH_FIELD_RE = rf'(?:{FIELD_RE}|-?{NUMBER_RE})'
  1045. MATH_OPERATORS_RE = r'(?:%s)' % '|'.join(map(re.escape, MATH_FUNCTIONS.keys()))
  1046. INTERNAL_FORMAT_RE = re.compile(rf'''(?x)
  1047. (?P<negate>-)?
  1048. (?P<fields>{FIELD_RE})
  1049. (?P<maths>(?:{MATH_OPERATORS_RE}{MATH_FIELD_RE})*)
  1050. (?:>(?P<strf_format>.+?))?
  1051. (?P<remaining>
  1052. (?P<alternate>(?<!\\),[^|&)]+)?
  1053. (?:&(?P<replacement>.*?))?
  1054. (?:\|(?P<default>.*?))?
  1055. )$''')
  1056. def _traverse_infodict(fields):
  1057. fields = [f for x in re.split(r'\.({.+?})\.?', fields)
  1058. for f in ([x] if x.startswith('{') else x.split('.'))]
  1059. for i in (0, -1):
  1060. if fields and not fields[i]:
  1061. fields.pop(i)
  1062. for i, f in enumerate(fields):
  1063. if not f.startswith('{'):
  1064. continue
  1065. assert f.endswith('}'), f'No closing brace for {f} in {fields}'
  1066. fields[i] = {k: k.split('.') for k in f[1:-1].split(',')}
  1067. return traverse_obj(info_dict, fields, is_user_input=True, traverse_string=True)
  1068. def get_value(mdict):
  1069. # Object traversal
  1070. value = _traverse_infodict(mdict['fields'])
  1071. # Negative
  1072. if mdict['negate']:
  1073. value = float_or_none(value)
  1074. if value is not None:
  1075. value *= -1
  1076. # Do maths
  1077. offset_key = mdict['maths']
  1078. if offset_key:
  1079. value = float_or_none(value)
  1080. operator = None
  1081. while offset_key:
  1082. item = re.match(
  1083. MATH_FIELD_RE if operator else MATH_OPERATORS_RE,
  1084. offset_key).group(0)
  1085. offset_key = offset_key[len(item):]
  1086. if operator is None:
  1087. operator = MATH_FUNCTIONS[item]
  1088. continue
  1089. item, multiplier = (item[1:], -1) if item[0] == '-' else (item, 1)
  1090. offset = float_or_none(item)
  1091. if offset is None:
  1092. offset = float_or_none(_traverse_infodict(item))
  1093. try:
  1094. value = operator(value, multiplier * offset)
  1095. except (TypeError, ZeroDivisionError):
  1096. return None
  1097. operator = None
  1098. # Datetime formatting
  1099. if mdict['strf_format']:
  1100. value = strftime_or_none(value, mdict['strf_format'].replace('\\,', ','))
  1101. # XXX: Workaround for https://github.com/yt-dlp/yt-dlp/issues/4485
  1102. if sanitize and value == '':
  1103. value = None
  1104. return value
  1105. na = self.params.get('outtmpl_na_placeholder', 'NA')
  1106. def filename_sanitizer(key, value, restricted=self.params.get('restrictfilenames')):
  1107. return sanitize_filename(str(value), restricted=restricted, is_id=(
  1108. bool(re.search(r'(^|[_.])id(\.|$)', key))
  1109. if 'filename-sanitization' in self.params['compat_opts']
  1110. else NO_DEFAULT))
  1111. sanitizer = sanitize if callable(sanitize) else filename_sanitizer
  1112. sanitize = bool(sanitize)
  1113. def _dumpjson_default(obj):
  1114. if isinstance(obj, (set, LazyList)):
  1115. return list(obj)
  1116. return repr(obj)
  1117. def create_key(outer_mobj):
  1118. if not outer_mobj.group('has_key'):
  1119. return outer_mobj.group(0)
  1120. key = outer_mobj.group('key')
  1121. mobj = re.match(INTERNAL_FORMAT_RE, key)
  1122. initial_field = mobj.group('fields') if mobj else ''
  1123. value, replacement, default = None, None, na
  1124. while mobj:
  1125. mobj = mobj.groupdict()
  1126. default = mobj['default'] if mobj['default'] is not None else default
  1127. value = get_value(mobj)
  1128. replacement = mobj['replacement']
  1129. if value is None and mobj['alternate']:
  1130. mobj = re.match(INTERNAL_FORMAT_RE, mobj['remaining'][1:])
  1131. else:
  1132. break
  1133. fmt = outer_mobj.group('format')
  1134. if fmt == 's' and value is not None and key in field_size_compat_map.keys():
  1135. fmt = f'0{field_size_compat_map[key]:d}d'
  1136. value = default if value is None else value if replacement is None else replacement
  1137. flags = outer_mobj.group('conversion') or ''
  1138. str_fmt = f'{fmt[:-1]}s'
  1139. if fmt[-1] == 'l': # list
  1140. delim = '\n' if '#' in flags else ', '
  1141. value, fmt = delim.join(map(str, variadic(value, allowed_types=(str, bytes)))), str_fmt
  1142. elif fmt[-1] == 'j': # json
  1143. value, fmt = json.dumps(
  1144. value, default=_dumpjson_default,
  1145. indent=4 if '#' in flags else None, ensure_ascii=False), str_fmt
  1146. elif fmt[-1] == 'h': # html
  1147. value, fmt = escapeHTML(str(value)), str_fmt
  1148. elif fmt[-1] == 'q': # quoted
  1149. value = map(str, variadic(value) if '#' in flags else [value])
  1150. value, fmt = ' '.join(map(compat_shlex_quote, value)), str_fmt
  1151. elif fmt[-1] == 'B': # bytes
  1152. value = f'%{str_fmt}'.encode() % str(value).encode()
  1153. value, fmt = value.decode('utf-8', 'ignore'), 's'
  1154. elif fmt[-1] == 'U': # unicode normalized
  1155. value, fmt = unicodedata.normalize(
  1156. # "+" = compatibility equivalence, "#" = NFD
  1157. 'NF%s%s' % ('K' if '+' in flags else '', 'D' if '#' in flags else 'C'),
  1158. value), str_fmt
  1159. elif fmt[-1] == 'D': # decimal suffix
  1160. num_fmt, fmt = fmt[:-1].replace('#', ''), 's'
  1161. value = format_decimal_suffix(value, f'%{num_fmt}f%s' if num_fmt else '%d%s',
  1162. factor=1024 if '#' in flags else 1000)
  1163. elif fmt[-1] == 'S': # filename sanitization
  1164. value, fmt = filename_sanitizer(initial_field, value, restricted='#' in flags), str_fmt
  1165. elif fmt[-1] == 'c':
  1166. if value:
  1167. value = str(value)[0]
  1168. else:
  1169. fmt = str_fmt
  1170. elif fmt[-1] not in 'rs': # numeric
  1171. value = float_or_none(value)
  1172. if value is None:
  1173. value, fmt = default, 's'
  1174. if sanitize:
  1175. if fmt[-1] == 'r':
  1176. # If value is an object, sanitize might convert it to a string
  1177. # So we convert it to repr first
  1178. value, fmt = repr(value), str_fmt
  1179. if fmt[-1] in 'csr':
  1180. value = sanitizer(initial_field, value)
  1181. key = '%s\0%s' % (key.replace('%', '%\0'), outer_mobj.group('format'))
  1182. TMPL_DICT[key] = value
  1183. return '{prefix}%({key}){fmt}'.format(key=key, fmt=fmt, prefix=outer_mobj.group('prefix'))
  1184. return EXTERNAL_FORMAT_RE.sub(create_key, outtmpl), TMPL_DICT
  1185. def evaluate_outtmpl(self, outtmpl, info_dict, *args, **kwargs):
  1186. outtmpl, info_dict = self.prepare_outtmpl(outtmpl, info_dict, *args, **kwargs)
  1187. return self.escape_outtmpl(outtmpl) % info_dict
  1188. def _prepare_filename(self, info_dict, *, outtmpl=None, tmpl_type=None):
  1189. assert None in (outtmpl, tmpl_type), 'outtmpl and tmpl_type are mutually exclusive'
  1190. if outtmpl is None:
  1191. outtmpl = self.params['outtmpl'].get(tmpl_type or 'default', self.params['outtmpl']['default'])
  1192. try:
  1193. outtmpl = self._outtmpl_expandpath(outtmpl)
  1194. filename = self.evaluate_outtmpl(outtmpl, info_dict, True)
  1195. if not filename:
  1196. return None
  1197. if tmpl_type in ('', 'temp'):
  1198. final_ext, ext = self.params.get('final_ext'), info_dict.get('ext')
  1199. if final_ext and ext and final_ext != ext and filename.endswith(f'.{final_ext}'):
  1200. filename = replace_extension(filename, ext, final_ext)
  1201. elif tmpl_type:
  1202. force_ext = OUTTMPL_TYPES[tmpl_type]
  1203. if force_ext:
  1204. filename = replace_extension(filename, force_ext, info_dict.get('ext'))
  1205. # https://github.com/blackjack4494/youtube-dlc/issues/85
  1206. trim_file_name = self.params.get('trim_file_name', False)
  1207. if trim_file_name:
  1208. no_ext, *ext = filename.rsplit('.', 2)
  1209. filename = join_nonempty(no_ext[:trim_file_name], *ext, delim='.')
  1210. return filename
  1211. except ValueError as err:
  1212. self.report_error('Error in output template: ' + str(err) + ' (encoding: ' + repr(preferredencoding()) + ')')
  1213. return None
  1214. def prepare_filename(self, info_dict, dir_type='', *, outtmpl=None, warn=False):
  1215. """Generate the output filename"""
  1216. if outtmpl:
  1217. assert not dir_type, 'outtmpl and dir_type are mutually exclusive'
  1218. dir_type = None
  1219. filename = self._prepare_filename(info_dict, tmpl_type=dir_type, outtmpl=outtmpl)
  1220. if not filename and dir_type not in ('', 'temp'):
  1221. return ''
  1222. if warn:
  1223. if not self.params.get('paths'):
  1224. pass
  1225. elif filename == '-':
  1226. self.report_warning('--paths is ignored when an outputting to stdout', only_once=True)
  1227. elif os.path.isabs(filename):
  1228. self.report_warning('--paths is ignored since an absolute path is given in output template', only_once=True)
  1229. if filename == '-' or not filename:
  1230. return filename
  1231. return self.get_output_path(dir_type, filename)
  1232. def _match_entry(self, info_dict, incomplete=False, silent=False):
  1233. """ Returns None if the file should be downloaded """
  1234. video_title = info_dict.get('title', info_dict.get('id', 'entry'))
  1235. def check_filter():
  1236. if 'title' in info_dict:
  1237. # This can happen when we're just evaluating the playlist
  1238. title = info_dict['title']
  1239. matchtitle = self.params.get('matchtitle', False)
  1240. if matchtitle:
  1241. if not re.search(matchtitle, title, re.IGNORECASE):
  1242. return '"' + title + '" title did not match pattern "' + matchtitle + '"'
  1243. rejecttitle = self.params.get('rejecttitle', False)
  1244. if rejecttitle:
  1245. if re.search(rejecttitle, title, re.IGNORECASE):
  1246. return '"' + title + '" title matched reject pattern "' + rejecttitle + '"'
  1247. date = info_dict.get('upload_date')
  1248. if date is not None:
  1249. dateRange = self.params.get('daterange', DateRange())
  1250. if date not in dateRange:
  1251. return f'{date_from_str(date).isoformat()} upload date is not in range {dateRange}'
  1252. view_count = info_dict.get('view_count')
  1253. if view_count is not None:
  1254. min_views = self.params.get('min_views')
  1255. if min_views is not None and view_count < min_views:
  1256. return 'Skipping %s, because it has not reached minimum view count (%d/%d)' % (video_title, view_count, min_views)
  1257. max_views = self.params.get('max_views')
  1258. if max_views is not None and view_count > max_views:
  1259. return 'Skipping %s, because it has exceeded the maximum view count (%d/%d)' % (video_title, view_count, max_views)
  1260. if age_restricted(info_dict.get('age_limit'), self.params.get('age_limit')):
  1261. return 'Skipping "%s" because it is age restricted' % video_title
  1262. match_filter = self.params.get('match_filter')
  1263. if match_filter is not None:
  1264. try:
  1265. ret = match_filter(info_dict, incomplete=incomplete)
  1266. except TypeError:
  1267. # For backward compatibility
  1268. ret = None if incomplete else match_filter(info_dict)
  1269. if ret is NO_DEFAULT:
  1270. while True:
  1271. filename = self._format_screen(self.prepare_filename(info_dict), self.Styles.FILENAME)
  1272. reply = input(self._format_screen(
  1273. f'Download "{filename}"? (Y/n): ', self.Styles.EMPHASIS)).lower().strip()
  1274. if reply in {'y', ''}:
  1275. return None
  1276. elif reply == 'n':
  1277. return f'Skipping {video_title}'
  1278. elif ret is not None:
  1279. return ret
  1280. return None
  1281. if self.in_download_archive(info_dict):
  1282. reason = '%s has already been recorded in the archive' % video_title
  1283. break_opt, break_err = 'break_on_existing', ExistingVideoReached
  1284. else:
  1285. reason = check_filter()
  1286. break_opt, break_err = 'break_on_reject', RejectedVideoReached
  1287. if reason is not None:
  1288. if not silent:
  1289. self.to_screen('[download] ' + reason)
  1290. if self.params.get(break_opt, False):
  1291. raise break_err()
  1292. return reason
  1293. @staticmethod
  1294. def add_extra_info(info_dict, extra_info):
  1295. '''Set the keys from extra_info in info dict if they are missing'''
  1296. for key, value in extra_info.items():
  1297. info_dict.setdefault(key, value)
  1298. def extract_info(self, url, download=True, ie_key=None, extra_info=None,
  1299. process=True, force_generic_extractor=False):
  1300. """
  1301. Extract and return the information dictionary of the URL
  1302. Arguments:
  1303. @param url URL to extract
  1304. Keyword arguments:
  1305. @param download Whether to download videos
  1306. @param process Whether to resolve all unresolved references (URLs, playlist items).
  1307. Must be True for download to work
  1308. @param ie_key Use only the extractor with this key
  1309. @param extra_info Dictionary containing the extra values to add to the info (For internal use only)
  1310. @force_generic_extractor Force using the generic extractor (Deprecated; use ie_key='Generic')
  1311. """
  1312. if extra_info is None:
  1313. extra_info = {}
  1314. if not ie_key and force_generic_extractor:
  1315. ie_key = 'Generic'
  1316. if ie_key:
  1317. ies = {ie_key: self._ies[ie_key]} if ie_key in self._ies else {}
  1318. else:
  1319. ies = self._ies
  1320. for key, ie in ies.items():
  1321. if not ie.suitable(url):
  1322. continue
  1323. if not ie.working():
  1324. self.report_warning('The program functionality for this site has been marked as broken, '
  1325. 'and will probably not work.')
  1326. temp_id = ie.get_temp_id(url)
  1327. if temp_id is not None and self.in_download_archive({'id': temp_id, 'ie_key': key}):
  1328. self.to_screen(f'[{key}] {temp_id}: has already been recorded in the archive')
  1329. if self.params.get('break_on_existing', False):
  1330. raise ExistingVideoReached()
  1331. break
  1332. return self.__extract_info(url, self.get_info_extractor(key), download, extra_info, process)
  1333. else:
  1334. extractors_restricted = self.params.get('allowed_extractors') not in (None, ['default'])
  1335. self.report_error(f'No suitable extractor{format_field(ie_key, None, " (%s)")} found for URL {url}',
  1336. tb=False if extractors_restricted else None)
  1337. def _handle_extraction_exceptions(func):
  1338. @functools.wraps(func)
  1339. def wrapper(self, *args, **kwargs):
  1340. while True:
  1341. try:
  1342. return func(self, *args, **kwargs)
  1343. except (DownloadCancelled, LazyList.IndexError, PagedList.IndexError):
  1344. raise
  1345. except ReExtractInfo as e:
  1346. if e.expected:
  1347. self.to_screen(f'{e}; Re-extracting data')
  1348. else:
  1349. self.to_stderr('\r')
  1350. self.report_warning(f'{e}; Re-extracting data')
  1351. continue
  1352. except GeoRestrictedError as e:
  1353. msg = e.msg
  1354. if e.countries:
  1355. msg += '\nThis video is available in %s.' % ', '.join(
  1356. map(ISO3166Utils.short2full, e.countries))
  1357. msg += '\nYou might want to use a VPN or a proxy server (with --proxy) to workaround.'
  1358. self.report_error(msg)
  1359. except ExtractorError as e: # An error we somewhat expected
  1360. self.report_error(str(e), e.format_traceback())
  1361. except Exception as e:
  1362. if self.params.get('ignoreerrors'):
  1363. self.report_error(str(e), tb=encode_compat_str(traceback.format_exc()))
  1364. else:
  1365. raise
  1366. break
  1367. return wrapper
  1368. def _wait_for_video(self, ie_result={}):
  1369. if (not self.params.get('wait_for_video')
  1370. or ie_result.get('_type', 'video') != 'video'
  1371. or ie_result.get('formats') or ie_result.get('url')):
  1372. return
  1373. format_dur = lambda dur: '%02d:%02d:%02d' % timetuple_from_msec(dur * 1000)[:-1]
  1374. last_msg = ''
  1375. def progress(msg):
  1376. nonlocal last_msg
  1377. full_msg = f'{msg}\n'
  1378. if not self.params.get('noprogress'):
  1379. full_msg = msg + ' ' * (len(last_msg) - len(msg)) + '\r'
  1380. elif last_msg:
  1381. return
  1382. self.to_screen(full_msg, skip_eol=True)
  1383. last_msg = msg
  1384. min_wait, max_wait = self.params.get('wait_for_video')
  1385. diff = try_get(ie_result, lambda x: x['release_timestamp'] - time.time())
  1386. if diff is None and ie_result.get('live_status') == 'is_upcoming':
  1387. diff = round(random.uniform(min_wait, max_wait) if (max_wait and min_wait) else (max_wait or min_wait), 0)
  1388. self.report_warning('Release time of video is not known')
  1389. elif ie_result and (diff or 0) <= 0:
  1390. self.report_warning('Video should already be available according to extracted info')
  1391. diff = min(max(diff or 0, min_wait or 0), max_wait or float('inf'))
  1392. self.to_screen(f'[wait] Waiting for {format_dur(diff)} - Press Ctrl+C to try now')
  1393. wait_till = time.time() + diff
  1394. try:
  1395. while True:
  1396. diff = wait_till - time.time()
  1397. if diff <= 0:
  1398. progress('')
  1399. raise ReExtractInfo('[wait] Wait period ended', expected=True)
  1400. progress(f'[wait] Remaining time until next attempt: {self._format_screen(format_dur(diff), self.Styles.EMPHASIS)}')
  1401. time.sleep(1)
  1402. except KeyboardInterrupt:
  1403. progress('')
  1404. raise ReExtractInfo('[wait] Interrupted by user', expected=True)
  1405. except BaseException as e:
  1406. if not isinstance(e, ReExtractInfo):
  1407. self.to_screen('')
  1408. raise
  1409. @_handle_extraction_exceptions
  1410. def __extract_info(self, url, ie, download, extra_info, process):
  1411. try:
  1412. ie_result = ie.extract(url)
  1413. except UserNotLive as e:
  1414. if process:
  1415. if self.params.get('wait_for_video'):
  1416. self.report_warning(e)
  1417. self._wait_for_video()
  1418. raise
  1419. if ie_result is None: # Finished already (backwards compatibility; listformats and friends should be moved here)
  1420. self.report_warning(f'Extractor {ie.IE_NAME} returned nothing{bug_reports_message()}')
  1421. return
  1422. if isinstance(ie_result, list):
  1423. # Backwards compatibility: old IE result format
  1424. ie_result = {
  1425. '_type': 'compat_list',
  1426. 'entries': ie_result,
  1427. }
  1428. if extra_info.get('original_url'):
  1429. ie_result.setdefault('original_url', extra_info['original_url'])
  1430. self.add_default_extra_info(ie_result, ie, url)
  1431. if process:
  1432. self._wait_for_video(ie_result)
  1433. return self.process_ie_result(ie_result, download, extra_info)
  1434. else:
  1435. return ie_result
  1436. def add_default_extra_info(self, ie_result, ie, url):
  1437. if url is not None:
  1438. self.add_extra_info(ie_result, {
  1439. 'webpage_url': url,
  1440. 'original_url': url,
  1441. })
  1442. webpage_url = ie_result.get('webpage_url')
  1443. if webpage_url:
  1444. self.add_extra_info(ie_result, {
  1445. 'webpage_url_basename': url_basename(webpage_url),
  1446. 'webpage_url_domain': get_domain(webpage_url),
  1447. })
  1448. if ie is not None:
  1449. self.add_extra_info(ie_result, {
  1450. 'extractor': ie.IE_NAME,
  1451. 'extractor_key': ie.ie_key(),
  1452. })
  1453. def process_ie_result(self, ie_result, download=True, extra_info=None):
  1454. """
  1455. Take the result of the ie(may be modified) and resolve all unresolved
  1456. references (URLs, playlist items).
  1457. It will also download the videos if 'download'.
  1458. Returns the resolved ie_result.
  1459. """
  1460. if extra_info is None:
  1461. extra_info = {}
  1462. result_type = ie_result.get('_type', 'video')
  1463. if result_type in ('url', 'url_transparent'):
  1464. ie_result['url'] = sanitize_url(
  1465. ie_result['url'], scheme='http' if self.params.get('prefer_insecure') else 'https')
  1466. if ie_result.get('original_url'):
  1467. extra_info.setdefault('original_url', ie_result['original_url'])
  1468. extract_flat = self.params.get('extract_flat', False)
  1469. if ((extract_flat == 'in_playlist' and 'playlist' in extra_info)
  1470. or extract_flat is True):
  1471. info_copy = ie_result.copy()
  1472. ie = try_get(ie_result.get('ie_key'), self.get_info_extractor)
  1473. if ie and not ie_result.get('id'):
  1474. info_copy['id'] = ie.get_temp_id(ie_result['url'])
  1475. self.add_default_extra_info(info_copy, ie, ie_result['url'])
  1476. self.add_extra_info(info_copy, extra_info)
  1477. info_copy, _ = self.pre_process(info_copy)
  1478. self.__forced_printings(info_copy, self.prepare_filename(info_copy), incomplete=True)
  1479. self._raise_pending_errors(info_copy)
  1480. if self.params.get('force_write_download_archive', False):
  1481. self.record_download_archive(info_copy)
  1482. return ie_result
  1483. if result_type == 'video':
  1484. self.add_extra_info(ie_result, extra_info)
  1485. ie_result = self.process_video_result(ie_result, download=download)
  1486. self._raise_pending_errors(ie_result)
  1487. additional_urls = (ie_result or {}).get('additional_urls')
  1488. if additional_urls:
  1489. # TODO: Improve MetadataParserPP to allow setting a list
  1490. if isinstance(additional_urls, str):
  1491. additional_urls = [additional_urls]
  1492. self.to_screen(
  1493. '[info] %s: %d additional URL(s) requested' % (ie_result['id'], len(additional_urls)))
  1494. self.write_debug('Additional URLs: "%s"' % '", "'.join(additional_urls))
  1495. ie_result['additional_entries'] = [
  1496. self.extract_info(
  1497. url, download, extra_info=extra_info,
  1498. force_generic_extractor=self.params.get('force_generic_extractor'))
  1499. for url in additional_urls
  1500. ]
  1501. return ie_result
  1502. elif result_type == 'url':
  1503. # We have to add extra_info to the results because it may be
  1504. # contained in a playlist
  1505. return self.extract_info(
  1506. ie_result['url'], download,
  1507. ie_key=ie_result.get('ie_key'),
  1508. extra_info=extra_info)
  1509. elif result_type == 'url_transparent':
  1510. # Use the information from the embedding page
  1511. info = self.extract_info(
  1512. ie_result['url'], ie_key=ie_result.get('ie_key'),
  1513. extra_info=extra_info, download=False, process=False)
  1514. # extract_info may return None when ignoreerrors is enabled and
  1515. # extraction failed with an error, don't crash and return early
  1516. # in this case
  1517. if not info:
  1518. return info
  1519. exempted_fields = {'_type', 'url', 'ie_key'}
  1520. if not ie_result.get('section_end') and ie_result.get('section_start') is None:
  1521. # For video clips, the id etc of the clip extractor should be used
  1522. exempted_fields |= {'id', 'extractor', 'extractor_key'}
  1523. new_result = info.copy()
  1524. new_result.update(filter_dict(ie_result, lambda k, v: v is not None and k not in exempted_fields))
  1525. # Extracted info may not be a video result (i.e.
  1526. # info.get('_type', 'video') != video) but rather an url or
  1527. # url_transparent. In such cases outer metadata (from ie_result)
  1528. # should be propagated to inner one (info). For this to happen
  1529. # _type of info should be overridden with url_transparent. This
  1530. # fixes issue from https://github.com/ytdl-org/youtube-dl/pull/11163.
  1531. if new_result.get('_type') == 'url':
  1532. new_result['_type'] = 'url_transparent'
  1533. return self.process_ie_result(
  1534. new_result, download=download, extra_info=extra_info)
  1535. elif result_type in ('playlist', 'multi_video'):
  1536. # Protect from infinite recursion due to recursively nested playlists
  1537. # (see https://github.com/ytdl-org/youtube-dl/issues/27833)
  1538. webpage_url = ie_result.get('webpage_url') # Playlists maynot have webpage_url
  1539. if webpage_url and webpage_url in self._playlist_urls:
  1540. self.to_screen(
  1541. '[download] Skipping already downloaded playlist: %s'
  1542. % ie_result.get('title') or ie_result.get('id'))
  1543. return
  1544. self._playlist_level += 1
  1545. self._playlist_urls.add(webpage_url)
  1546. self._fill_common_fields(ie_result, False)
  1547. self._sanitize_thumbnails(ie_result)
  1548. try:
  1549. return self.__process_playlist(ie_result, download)
  1550. finally:
  1551. self._playlist_level -= 1
  1552. if not self._playlist_level:
  1553. self._playlist_urls.clear()
  1554. elif result_type == 'compat_list':
  1555. self.report_warning(
  1556. 'Extractor %s returned a compat_list result. '
  1557. 'It needs to be updated.' % ie_result.get('extractor'))
  1558. def _fixup(r):
  1559. self.add_extra_info(r, {
  1560. 'extractor': ie_result['extractor'],
  1561. 'webpage_url': ie_result['webpage_url'],
  1562. 'webpage_url_basename': url_basename(ie_result['webpage_url']),
  1563. 'webpage_url_domain': get_domain(ie_result['webpage_url']),
  1564. 'extractor_key': ie_result['extractor_key'],
  1565. })
  1566. return r
  1567. ie_result['entries'] = [
  1568. self.process_ie_result(_fixup(r), download, extra_info)
  1569. for r in ie_result['entries']
  1570. ]
  1571. return ie_result
  1572. else:
  1573. raise Exception('Invalid result type: %s' % result_type)
  1574. def _ensure_dir_exists(self, path):
  1575. return make_dir(path, self.report_error)
  1576. @staticmethod
  1577. def _playlist_infodict(ie_result, strict=False, **kwargs):
  1578. info = {
  1579. 'playlist_count': ie_result.get('playlist_count'),
  1580. 'playlist': ie_result.get('title') or ie_result.get('id'),
  1581. 'playlist_id': ie_result.get('id'),
  1582. 'playlist_title': ie_result.get('title'),
  1583. 'playlist_uploader': ie_result.get('uploader'),
  1584. 'playlist_uploader_id': ie_result.get('uploader_id'),
  1585. **kwargs,
  1586. }
  1587. if strict:
  1588. return info
  1589. if ie_result.get('webpage_url'):
  1590. info.update({
  1591. 'webpage_url': ie_result['webpage_url'],
  1592. 'webpage_url_basename': url_basename(ie_result['webpage_url']),
  1593. 'webpage_url_domain': get_domain(ie_result['webpage_url']),
  1594. })
  1595. return {
  1596. **info,
  1597. 'playlist_index': 0,
  1598. '__last_playlist_index': max(ie_result['requested_entries'] or (0, 0)),
  1599. 'extractor': ie_result['extractor'],
  1600. 'extractor_key': ie_result['extractor_key'],
  1601. }
  1602. def __process_playlist(self, ie_result, download):
  1603. """Process each entry in the playlist"""
  1604. assert ie_result['_type'] in ('playlist', 'multi_video')
  1605. common_info = self._playlist_infodict(ie_result, strict=True)
  1606. title = common_info.get('playlist') or '<Untitled>'
  1607. if self._match_entry(common_info, incomplete=True) is not None:
  1608. return
  1609. self.to_screen(f'[download] Downloading {ie_result["_type"]}: {title}')
  1610. all_entries = PlaylistEntries(self, ie_result)
  1611. entries = orderedSet(all_entries.get_requested_items(), lazy=True)
  1612. lazy = self.params.get('lazy_playlist')
  1613. if lazy:
  1614. resolved_entries, n_entries = [], 'N/A'
  1615. ie_result['requested_entries'], ie_result['entries'] = None, None
  1616. else:
  1617. entries = resolved_entries = list(entries)
  1618. n_entries = len(resolved_entries)
  1619. ie_result['requested_entries'], ie_result['entries'] = tuple(zip(*resolved_entries)) or ([], [])
  1620. if not ie_result.get('playlist_count'):
  1621. # Better to do this after potentially exhausting entries
  1622. ie_result['playlist_count'] = all_entries.get_full_count()
  1623. extra = self._playlist_infodict(ie_result, n_entries=int_or_none(n_entries))
  1624. ie_copy = collections.ChainMap(ie_result, extra)
  1625. _infojson_written = False
  1626. write_playlist_files = self.params.get('allow_playlist_files', True)
  1627. if write_playlist_files and self.params.get('list_thumbnails'):
  1628. self.list_thumbnails(ie_result)
  1629. if write_playlist_files and not self.params.get('simulate'):
  1630. _infojson_written = self._write_info_json(
  1631. 'playlist', ie_result, self.prepare_filename(ie_copy, 'pl_infojson'))
  1632. if _infojson_written is None:
  1633. return
  1634. if self._write_description('playlist', ie_result,
  1635. self.prepare_filename(ie_copy, 'pl_description')) is None:
  1636. return
  1637. # TODO: This should be passed to ThumbnailsConvertor if necessary
  1638. self._write_thumbnails('playlist', ie_result, self.prepare_filename(ie_copy, 'pl_thumbnail'))
  1639. if lazy:
  1640. if self.params.get('playlistreverse') or self.params.get('playlistrandom'):
  1641. self.report_warning('playlistreverse and playlistrandom are not supported with lazy_playlist', only_once=True)
  1642. elif self.params.get('playlistreverse'):
  1643. entries.reverse()
  1644. elif self.params.get('playlistrandom'):
  1645. random.shuffle(entries)
  1646. self.to_screen(f'[{ie_result["extractor"]}] Playlist {title}: Downloading {n_entries} videos'
  1647. f'{format_field(ie_result, "playlist_count", " of %s")}')
  1648. keep_resolved_entries = self.params.get('extract_flat') != 'discard'
  1649. if self.params.get('extract_flat') == 'discard_in_playlist':
  1650. keep_resolved_entries = ie_result['_type'] != 'playlist'
  1651. if keep_resolved_entries:
  1652. self.write_debug('The information of all playlist entries will be held in memory')
  1653. failures = 0
  1654. max_failures = self.params.get('skip_playlist_after_errors') or float('inf')
  1655. for i, (playlist_index, entry) in enumerate(entries):
  1656. if lazy:
  1657. resolved_entries.append((playlist_index, entry))
  1658. if not entry:
  1659. continue
  1660. entry['__x_forwarded_for_ip'] = ie_result.get('__x_forwarded_for_ip')
  1661. if not lazy and 'playlist-index' in self.params.get('compat_opts', []):
  1662. playlist_index = ie_result['requested_entries'][i]
  1663. entry_copy = collections.ChainMap(entry, {
  1664. **common_info,
  1665. 'n_entries': int_or_none(n_entries),
  1666. 'playlist_index': playlist_index,
  1667. 'playlist_autonumber': i + 1,
  1668. })
  1669. if self._match_entry(entry_copy, incomplete=True) is not None:
  1670. # For compatabilty with youtube-dl. See https://github.com/yt-dlp/yt-dlp/issues/4369
  1671. resolved_entries[i] = (playlist_index, NO_DEFAULT)
  1672. continue
  1673. self.to_screen('[download] Downloading video %s of %s' % (
  1674. self._format_screen(i + 1, self.Styles.ID), self._format_screen(n_entries, self.Styles.EMPHASIS)))
  1675. extra.update({
  1676. 'playlist_index': playlist_index,
  1677. 'playlist_autonumber': i + 1,
  1678. })
  1679. entry_result = self.__process_iterable_entry(entry, download, extra)
  1680. if not entry_result:
  1681. failures += 1
  1682. if failures >= max_failures:
  1683. self.report_error(
  1684. f'Skipping the remaining entries in playlist "{title}" since {failures} items failed extraction')
  1685. break
  1686. if keep_resolved_entries:
  1687. resolved_entries[i] = (playlist_index, entry_result)
  1688. # Update with processed data
  1689. ie_result['requested_entries'] = [i for i, e in resolved_entries if e is not NO_DEFAULT]
  1690. ie_result['entries'] = [e for _, e in resolved_entries if e is not NO_DEFAULT]
  1691. # Write the updated info to json
  1692. if _infojson_written is True and self._write_info_json(
  1693. 'updated playlist', ie_result,
  1694. self.prepare_filename(ie_copy, 'pl_infojson'), overwrite=True) is None:
  1695. return
  1696. ie_result = self.run_all_pps('playlist', ie_result)
  1697. self.to_screen(f'[download] Finished downloading playlist: {title}')
  1698. return ie_result
  1699. @_handle_extraction_exceptions
  1700. def __process_iterable_entry(self, entry, download, extra_info):
  1701. return self.process_ie_result(
  1702. entry, download=download, extra_info=extra_info)
  1703. def _build_format_filter(self, filter_spec):
  1704. " Returns a function to filter the formats according to the filter_spec "
  1705. OPERATORS = {
  1706. '<': operator.lt,
  1707. '<=': operator.le,
  1708. '>': operator.gt,
  1709. '>=': operator.ge,
  1710. '=': operator.eq,
  1711. '!=': operator.ne,
  1712. }
  1713. operator_rex = re.compile(r'''(?x)\s*
  1714. (?P<key>width|height|tbr|abr|vbr|asr|filesize|filesize_approx|fps)\s*
  1715. (?P<op>%s)(?P<none_inclusive>\s*\?)?\s*
  1716. (?P<value>[0-9.]+(?:[kKmMgGtTpPeEzZyY]i?[Bb]?)?)\s*
  1717. ''' % '|'.join(map(re.escape, OPERATORS.keys())))
  1718. m = operator_rex.fullmatch(filter_spec)
  1719. if m:
  1720. try:
  1721. comparison_value = int(m.group('value'))
  1722. except ValueError:
  1723. comparison_value = parse_filesize(m.group('value'))
  1724. if comparison_value is None:
  1725. comparison_value = parse_filesize(m.group('value') + 'B')
  1726. if comparison_value is None:
  1727. raise ValueError(
  1728. 'Invalid value %r in format specification %r' % (
  1729. m.group('value'), filter_spec))
  1730. op = OPERATORS[m.group('op')]
  1731. if not m:
  1732. STR_OPERATORS = {
  1733. '=': operator.eq,
  1734. '^=': lambda attr, value: attr.startswith(value),
  1735. '$=': lambda attr, value: attr.endswith(value),
  1736. '*=': lambda attr, value: value in attr,
  1737. '~=': lambda attr, value: value.search(attr) is not None
  1738. }
  1739. str_operator_rex = re.compile(r'''(?x)\s*
  1740. (?P<key>[a-zA-Z0-9._-]+)\s*
  1741. (?P<negation>!\s*)?(?P<op>%s)\s*(?P<none_inclusive>\?\s*)?
  1742. (?P<quote>["'])?
  1743. (?P<value>(?(quote)(?:(?!(?P=quote))[^\\]|\\.)+|[\w.-]+))
  1744. (?(quote)(?P=quote))\s*
  1745. ''' % '|'.join(map(re.escape, STR_OPERATORS.keys())))
  1746. m = str_operator_rex.fullmatch(filter_spec)
  1747. if m:
  1748. if m.group('op') == '~=':
  1749. comparison_value = re.compile(m.group('value'))
  1750. else:
  1751. comparison_value = re.sub(r'''\\([\\"'])''', r'\1', m.group('value'))
  1752. str_op = STR_OPERATORS[m.group('op')]
  1753. if m.group('negation'):
  1754. op = lambda attr, value: not str_op(attr, value)
  1755. else:
  1756. op = str_op
  1757. if not m:
  1758. raise SyntaxError('Invalid filter specification %r' % filter_spec)
  1759. def _filter(f):
  1760. actual_value = f.get(m.group('key'))
  1761. if actual_value is None:
  1762. return m.group('none_inclusive')
  1763. return op(actual_value, comparison_value)
  1764. return _filter
  1765. def _check_formats(self, formats):
  1766. for f in formats:
  1767. self.to_screen('[info] Testing format %s' % f['format_id'])
  1768. path = self.get_output_path('temp')
  1769. if not self._ensure_dir_exists(f'{path}/'):
  1770. continue
  1771. temp_file = tempfile.NamedTemporaryFile(suffix='.tmp', delete=False, dir=path or None)
  1772. temp_file.close()
  1773. try:
  1774. success, _ = self.dl(temp_file.name, f, test=True)
  1775. except (DownloadError, OSError, ValueError) + network_exceptions:
  1776. success = False
  1777. finally:
  1778. if os.path.exists(temp_file.name):
  1779. try:
  1780. os.remove(temp_file.name)
  1781. except OSError:
  1782. self.report_warning('Unable to delete temporary file "%s"' % temp_file.name)
  1783. if success:
  1784. yield f
  1785. else:
  1786. self.to_screen('[info] Unable to download format %s. Skipping...' % f['format_id'])
  1787. def _default_format_spec(self, info_dict, download=True):
  1788. def can_merge():
  1789. merger = FFmpegMergerPP(self)
  1790. return merger.available and merger.can_merge()
  1791. prefer_best = (
  1792. not self.params.get('simulate')
  1793. and download
  1794. and (
  1795. not can_merge()
  1796. or info_dict.get('is_live') and not self.params.get('live_from_start')
  1797. or self.params['outtmpl']['default'] == '-'))
  1798. compat = (
  1799. prefer_best
  1800. or self.params.get('allow_multiple_audio_streams', False)
  1801. or 'format-spec' in self.params['compat_opts'])
  1802. return (
  1803. 'best/bestvideo+bestaudio' if prefer_best
  1804. else 'bestvideo*+bestaudio/best' if not compat
  1805. else 'bestvideo+bestaudio/best')
  1806. def build_format_selector(self, format_spec):
  1807. def syntax_error(note, start):
  1808. message = (
  1809. 'Invalid format specification: '
  1810. '{}\n\t{}\n\t{}^'.format(note, format_spec, ' ' * start[1]))
  1811. return SyntaxError(message)
  1812. PICKFIRST = 'PICKFIRST'
  1813. MERGE = 'MERGE'
  1814. SINGLE = 'SINGLE'
  1815. GROUP = 'GROUP'
  1816. FormatSelector = collections.namedtuple('FormatSelector', ['type', 'selector', 'filters'])
  1817. allow_multiple_streams = {'audio': self.params.get('allow_multiple_audio_streams', False),
  1818. 'video': self.params.get('allow_multiple_video_streams', False)}
  1819. check_formats = self.params.get('check_formats') == 'selected'
  1820. def _parse_filter(tokens):
  1821. filter_parts = []
  1822. for type, string, start, _, _ in tokens:
  1823. if type == tokenize.OP and string == ']':
  1824. return ''.join(filter_parts)
  1825. else:
  1826. filter_parts.append(string)
  1827. def _remove_unused_ops(tokens):
  1828. # Remove operators that we don't use and join them with the surrounding strings.
  1829. # E.g. 'mp4' '-' 'baseline' '-' '16x9' is converted to 'mp4-baseline-16x9'
  1830. ALLOWED_OPS = ('/', '+', ',', '(', ')')
  1831. last_string, last_start, last_end, last_line = None, None, None, None
  1832. for type, string, start, end, line in tokens:
  1833. if type == tokenize.OP and string == '[':
  1834. if last_string:
  1835. yield tokenize.NAME, last_string, last_start, last_end, last_line
  1836. last_string = None
  1837. yield type, string, start, end, line
  1838. # everything inside brackets will be handled by _parse_filter
  1839. for type, string, start, end, line in tokens:
  1840. yield type, string, start, end, line
  1841. if type == tokenize.OP and string == ']':
  1842. break
  1843. elif type == tokenize.OP and string in ALLOWED_OPS:
  1844. if last_string:
  1845. yield tokenize.NAME, last_string, last_start, last_end, last_line
  1846. last_string = None
  1847. yield type, string, start, end, line
  1848. elif type in [tokenize.NAME, tokenize.NUMBER, tokenize.OP]:
  1849. if not last_string:
  1850. last_string = string
  1851. last_start = start
  1852. last_end = end
  1853. else:
  1854. last_string += string
  1855. if last_string:
  1856. yield tokenize.NAME, last_string, last_start, last_end, last_line
  1857. def _parse_format_selection(tokens, inside_merge=False, inside_choice=False, inside_group=False):
  1858. selectors = []
  1859. current_selector = None
  1860. for type, string, start, _, _ in tokens:
  1861. # ENCODING is only defined in python 3.x
  1862. if type == getattr(tokenize, 'ENCODING', None):
  1863. continue
  1864. elif type in [tokenize.NAME, tokenize.NUMBER]:
  1865. current_selector = FormatSelector(SINGLE, string, [])
  1866. elif type == tokenize.OP:
  1867. if string == ')':
  1868. if not inside_group:
  1869. # ')' will be handled by the parentheses group
  1870. tokens.restore_last_token()
  1871. break
  1872. elif inside_merge and string in ['/', ',']:
  1873. tokens.restore_last_token()
  1874. break
  1875. elif inside_choice and string == ',':
  1876. tokens.restore_last_token()
  1877. break
  1878. elif string == ',':
  1879. if not current_selector:
  1880. raise syntax_error('"," must follow a format selector', start)
  1881. selectors.append(current_selector)
  1882. current_selector = None
  1883. elif string == '/':
  1884. if not current_selector:
  1885. raise syntax_error('"/" must follow a format selector', start)
  1886. first_choice = current_selector
  1887. second_choice = _parse_format_selection(tokens, inside_choice=True)
  1888. current_selector = FormatSelector(PICKFIRST, (first_choice, second_choice), [])
  1889. elif string == '[':
  1890. if not current_selector:
  1891. current_selector = FormatSelector(SINGLE, 'best', [])
  1892. format_filter = _parse_filter(tokens)
  1893. current_selector.filters.append(format_filter)
  1894. elif string == '(':
  1895. if current_selector:
  1896. raise syntax_error('Unexpected "("', start)
  1897. group = _parse_format_selection(tokens, inside_group=True)
  1898. current_selector = FormatSelector(GROUP, group, [])
  1899. elif string == '+':
  1900. if not current_selector:
  1901. raise syntax_error('Unexpected "+"', start)
  1902. selector_1 = current_selector
  1903. selector_2 = _parse_format_selection(tokens, inside_merge=True)
  1904. if not selector_2:
  1905. raise syntax_error('Expected a selector', start)
  1906. current_selector = FormatSelector(MERGE, (selector_1, selector_2), [])
  1907. else:
  1908. raise syntax_error(f'Operator not recognized: "{string}"', start)
  1909. elif type == tokenize.ENDMARKER:
  1910. break
  1911. if current_selector:
  1912. selectors.append(current_selector)
  1913. return selectors
  1914. def _merge(formats_pair):
  1915. format_1, format_2 = formats_pair
  1916. formats_info = []
  1917. formats_info.extend(format_1.get('requested_formats', (format_1,)))
  1918. formats_info.extend(format_2.get('requested_formats', (format_2,)))
  1919. if not allow_multiple_streams['video'] or not allow_multiple_streams['audio']:
  1920. get_no_more = {'video': False, 'audio': False}
  1921. for (i, fmt_info) in enumerate(formats_info):
  1922. if fmt_info.get('acodec') == fmt_info.get('vcodec') == 'none':
  1923. formats_info.pop(i)
  1924. continue
  1925. for aud_vid in ['audio', 'video']:
  1926. if not allow_multiple_streams[aud_vid] and fmt_info.get(aud_vid[0] + 'codec') != 'none':
  1927. if get_no_more[aud_vid]:
  1928. formats_info.pop(i)
  1929. break
  1930. get_no_more[aud_vid] = True
  1931. if len(formats_info) == 1:
  1932. return formats_info[0]
  1933. video_fmts = [fmt_info for fmt_info in formats_info if fmt_info.get('vcodec') != 'none']
  1934. audio_fmts = [fmt_info for fmt_info in formats_info if fmt_info.get('acodec') != 'none']
  1935. the_only_video = video_fmts[0] if len(video_fmts) == 1 else None
  1936. the_only_audio = audio_fmts[0] if len(audio_fmts) == 1 else None
  1937. output_ext = get_compatible_ext(
  1938. vcodecs=[f.get('vcodec') for f in video_fmts],
  1939. acodecs=[f.get('acodec') for f in audio_fmts],
  1940. vexts=[f['ext'] for f in video_fmts],
  1941. aexts=[f['ext'] for f in audio_fmts],
  1942. preferences=(try_call(lambda: self.params['merge_output_format'].split('/'))
  1943. or self.params.get('prefer_free_formats') and ('webm', 'mkv')))
  1944. filtered = lambda *keys: filter(None, (traverse_obj(fmt, *keys) for fmt in formats_info))
  1945. new_dict = {
  1946. 'requested_formats': formats_info,
  1947. 'format': '+'.join(filtered('format')),
  1948. 'format_id': '+'.join(filtered('format_id')),
  1949. 'ext': output_ext,
  1950. 'protocol': '+'.join(map(determine_protocol, formats_info)),
  1951. 'language': '+'.join(orderedSet(filtered('language'))) or None,
  1952. 'format_note': '+'.join(orderedSet(filtered('format_note'))) or None,
  1953. 'filesize_approx': sum(filtered('filesize', 'filesize_approx')) or None,
  1954. 'tbr': sum(filtered('tbr', 'vbr', 'abr')),
  1955. }
  1956. if the_only_video:
  1957. new_dict.update({
  1958. 'width': the_only_video.get('width'),
  1959. 'height': the_only_video.get('height'),
  1960. 'resolution': the_only_video.get('resolution') or self.format_resolution(the_only_video),
  1961. 'fps': the_only_video.get('fps'),
  1962. 'dynamic_range': the_only_video.get('dynamic_range'),
  1963. 'vcodec': the_only_video.get('vcodec'),
  1964. 'vbr': the_only_video.get('vbr'),
  1965. 'stretched_ratio': the_only_video.get('stretched_ratio'),
  1966. })
  1967. if the_only_audio:
  1968. new_dict.update({
  1969. 'acodec': the_only_audio.get('acodec'),
  1970. 'abr': the_only_audio.get('abr'),
  1971. 'asr': the_only_audio.get('asr'),
  1972. 'audio_channels': the_only_audio.get('audio_channels')
  1973. })
  1974. return new_dict
  1975. def _check_formats(formats):
  1976. if not check_formats:
  1977. yield from formats
  1978. return
  1979. yield from self._check_formats(formats)
  1980. def _build_selector_function(selector):
  1981. if isinstance(selector, list): # ,
  1982. fs = [_build_selector_function(s) for s in selector]
  1983. def selector_function(ctx):
  1984. for f in fs:
  1985. yield from f(ctx)
  1986. return selector_function
  1987. elif selector.type == GROUP: # ()
  1988. selector_function = _build_selector_function(selector.selector)
  1989. elif selector.type == PICKFIRST: # /
  1990. fs = [_build_selector_function(s) for s in selector.selector]
  1991. def selector_function(ctx):
  1992. for f in fs:
  1993. picked_formats = list(f(ctx))
  1994. if picked_formats:
  1995. return picked_formats
  1996. return []
  1997. elif selector.type == MERGE: # +
  1998. selector_1, selector_2 = map(_build_selector_function, selector.selector)
  1999. def selector_function(ctx):
  2000. for pair in itertools.product(selector_1(ctx), selector_2(ctx)):
  2001. yield _merge(pair)
  2002. elif selector.type == SINGLE: # atom
  2003. format_spec = selector.selector or 'best'
  2004. # TODO: Add allvideo, allaudio etc by generalizing the code with best/worst selector
  2005. if format_spec == 'all':
  2006. def selector_function(ctx):
  2007. yield from _check_formats(ctx['formats'][::-1])
  2008. elif format_spec == 'mergeall':
  2009. def selector_function(ctx):
  2010. formats = list(_check_formats(
  2011. f for f in ctx['formats'] if f.get('vcodec') != 'none' or f.get('acodec') != 'none'))
  2012. if not formats:
  2013. return
  2014. merged_format = formats[-1]
  2015. for f in formats[-2::-1]:
  2016. merged_format = _merge((merged_format, f))
  2017. yield merged_format
  2018. else:
  2019. format_fallback, seperate_fallback, format_reverse, format_idx = False, None, True, 1
  2020. mobj = re.match(
  2021. r'(?P<bw>best|worst|b|w)(?P<type>video|audio|v|a)?(?P<mod>\*)?(?:\.(?P<n>[1-9]\d*))?$',
  2022. format_spec)
  2023. if mobj is not None:
  2024. format_idx = int_or_none(mobj.group('n'), default=1)
  2025. format_reverse = mobj.group('bw')[0] == 'b'
  2026. format_type = (mobj.group('type') or [None])[0]
  2027. not_format_type = {'v': 'a', 'a': 'v'}.get(format_type)
  2028. format_modified = mobj.group('mod') is not None
  2029. format_fallback = not format_type and not format_modified # for b, w
  2030. _filter_f = (
  2031. (lambda f: f.get('%scodec' % format_type) != 'none')
  2032. if format_type and format_modified # bv*, ba*, wv*, wa*
  2033. else (lambda f: f.get('%scodec' % not_format_type) == 'none')
  2034. if format_type # bv, ba, wv, wa
  2035. else (lambda f: f.get('vcodec') != 'none' and f.get('acodec') != 'none')
  2036. if not format_modified # b, w
  2037. else lambda f: True) # b*, w*
  2038. filter_f = lambda f: _filter_f(f) and (
  2039. f.get('vcodec') != 'none' or f.get('acodec') != 'none')
  2040. else:
  2041. if format_spec in self._format_selection_exts['audio']:
  2042. filter_f = lambda f: f.get('ext') == format_spec and f.get('acodec') != 'none'
  2043. elif format_spec in self._format_selection_exts['video']:
  2044. filter_f = lambda f: f.get('ext') == format_spec and f.get('acodec') != 'none' and f.get('vcodec') != 'none'
  2045. seperate_fallback = lambda f: f.get('ext') == format_spec and f.get('vcodec') != 'none'
  2046. elif format_spec in self._format_selection_exts['storyboards']:
  2047. filter_f = lambda f: f.get('ext') == format_spec and f.get('acodec') == 'none' and f.get('vcodec') == 'none'
  2048. else:
  2049. filter_f = lambda f: f.get('format_id') == format_spec # id
  2050. def selector_function(ctx):
  2051. formats = list(ctx['formats'])
  2052. matches = list(filter(filter_f, formats)) if filter_f is not None else formats
  2053. if not matches:
  2054. if format_fallback and ctx['incomplete_formats']:
  2055. # for extractors with incomplete formats (audio only (soundcloud)
  2056. # or video only (imgur)) best/worst will fallback to
  2057. # best/worst {video,audio}-only format
  2058. matches = formats
  2059. elif seperate_fallback and not ctx['has_merged_format']:
  2060. # for compatibility with youtube-dl when there is no pre-merged format
  2061. matches = list(filter(seperate_fallback, formats))
  2062. matches = LazyList(_check_formats(matches[::-1 if format_reverse else 1]))
  2063. try:
  2064. yield matches[format_idx - 1]
  2065. except LazyList.IndexError:
  2066. return
  2067. filters = [self._build_format_filter(f) for f in selector.filters]
  2068. def final_selector(ctx):
  2069. ctx_copy = dict(ctx)
  2070. for _filter in filters:
  2071. ctx_copy['formats'] = list(filter(_filter, ctx_copy['formats']))
  2072. return selector_function(ctx_copy)
  2073. return final_selector
  2074. stream = io.BytesIO(format_spec.encode())
  2075. try:
  2076. tokens = list(_remove_unused_ops(tokenize.tokenize(stream.readline)))
  2077. except tokenize.TokenError:
  2078. raise syntax_error('Missing closing/opening brackets or parenthesis', (0, len(format_spec)))
  2079. class TokenIterator:
  2080. def __init__(self, tokens):
  2081. self.tokens = tokens
  2082. self.counter = 0
  2083. def __iter__(self):
  2084. return self
  2085. def __next__(self):
  2086. if self.counter >= len(self.tokens):
  2087. raise StopIteration()
  2088. value = self.tokens[self.counter]
  2089. self.counter += 1
  2090. return value
  2091. next = __next__
  2092. def restore_last_token(self):
  2093. self.counter -= 1
  2094. parsed_selector = _parse_format_selection(iter(TokenIterator(tokens)))
  2095. return _build_selector_function(parsed_selector)
  2096. def _calc_headers(self, info_dict):
  2097. res = merge_headers(self.params['http_headers'], info_dict.get('http_headers') or {})
  2098. cookies = self._calc_cookies(info_dict['url'])
  2099. if cookies:
  2100. res['Cookie'] = cookies
  2101. if 'X-Forwarded-For' not in res:
  2102. x_forwarded_for_ip = info_dict.get('__x_forwarded_for_ip')
  2103. if x_forwarded_for_ip:
  2104. res['X-Forwarded-For'] = x_forwarded_for_ip
  2105. return res
  2106. def _calc_cookies(self, url):
  2107. pr = sanitized_Request(url)
  2108. self.cookiejar.add_cookie_header(pr)
  2109. return pr.get_header('Cookie')
  2110. def _sort_thumbnails(self, thumbnails):
  2111. thumbnails.sort(key=lambda t: (
  2112. t.get('preference') if t.get('preference') is not None else -1,
  2113. t.get('width') if t.get('width') is not None else -1,
  2114. t.get('height') if t.get('height') is not None else -1,
  2115. t.get('id') if t.get('id') is not None else '',
  2116. t.get('url')))
  2117. def _sanitize_thumbnails(self, info_dict):
  2118. thumbnails = info_dict.get('thumbnails')
  2119. if thumbnails is None:
  2120. thumbnail = info_dict.get('thumbnail')
  2121. if thumbnail:
  2122. info_dict['thumbnails'] = thumbnails = [{'url': thumbnail}]
  2123. if not thumbnails:
  2124. return
  2125. def check_thumbnails(thumbnails):
  2126. for t in thumbnails:
  2127. self.to_screen(f'[info] Testing thumbnail {t["id"]}')
  2128. try:
  2129. self.urlopen(HEADRequest(t['url']))
  2130. except network_exceptions as err:
  2131. self.to_screen(f'[info] Unable to connect to thumbnail {t["id"]} URL {t["url"]!r} - {err}. Skipping...')
  2132. continue
  2133. yield t
  2134. self._sort_thumbnails(thumbnails)
  2135. for i, t in enumerate(thumbnails):
  2136. if t.get('id') is None:
  2137. t['id'] = '%d' % i
  2138. if t.get('width') and t.get('height'):
  2139. t['resolution'] = '%dx%d' % (t['width'], t['height'])
  2140. t['url'] = sanitize_url(t['url'])
  2141. if self.params.get('check_formats') is True:
  2142. info_dict['thumbnails'] = LazyList(check_thumbnails(thumbnails[::-1]), reverse=True)
  2143. else:
  2144. info_dict['thumbnails'] = thumbnails
  2145. def _fill_common_fields(self, info_dict, is_video=True):
  2146. # TODO: move sanitization here
  2147. if is_video:
  2148. # playlists are allowed to lack "title"
  2149. title = info_dict.get('title', NO_DEFAULT)
  2150. if title is NO_DEFAULT:
  2151. raise ExtractorError('Missing "title" field in extractor result',
  2152. video_id=info_dict['id'], ie=info_dict['extractor'])
  2153. info_dict['fulltitle'] = title
  2154. if not title:
  2155. if title == '':
  2156. self.write_debug('Extractor gave empty title. Creating a generic title')
  2157. else:
  2158. self.report_warning('Extractor failed to obtain "title". Creating a generic title instead')
  2159. info_dict['title'] = f'{info_dict["extractor"].replace(":", "-")} video #{info_dict["id"]}'
  2160. if info_dict.get('duration') is not None:
  2161. info_dict['duration_string'] = formatSeconds(info_dict['duration'])
  2162. for ts_key, date_key in (
  2163. ('timestamp', 'upload_date'),
  2164. ('release_timestamp', 'release_date'),
  2165. ('modified_timestamp', 'modified_date'),
  2166. ):
  2167. if info_dict.get(date_key) is None and info_dict.get(ts_key) is not None:
  2168. # Working around out-of-range timestamp values (e.g. negative ones on Windows,
  2169. # see http://bugs.python.org/issue1646728)
  2170. with contextlib.suppress(ValueError, OverflowError, OSError):
  2171. upload_date = datetime.datetime.utcfromtimestamp(info_dict[ts_key])
  2172. info_dict[date_key] = upload_date.strftime('%Y%m%d')
  2173. live_keys = ('is_live', 'was_live')
  2174. live_status = info_dict.get('live_status')
  2175. if live_status is None:
  2176. for key in live_keys:
  2177. if info_dict.get(key) is False:
  2178. continue
  2179. if info_dict.get(key):
  2180. live_status = key
  2181. break
  2182. if all(info_dict.get(key) is False for key in live_keys):
  2183. live_status = 'not_live'
  2184. if live_status:
  2185. info_dict['live_status'] = live_status
  2186. for key in live_keys:
  2187. if info_dict.get(key) is None:
  2188. info_dict[key] = (live_status == key)
  2189. if live_status == 'post_live':
  2190. info_dict['was_live'] = True
  2191. # Auto generate title fields corresponding to the *_number fields when missing
  2192. # in order to always have clean titles. This is very common for TV series.
  2193. for field in ('chapter', 'season', 'episode'):
  2194. if info_dict.get('%s_number' % field) is not None and not info_dict.get(field):
  2195. info_dict[field] = '%s %d' % (field.capitalize(), info_dict['%s_number' % field])
  2196. def _raise_pending_errors(self, info):
  2197. err = info.pop('__pending_error', None)
  2198. if err:
  2199. self.report_error(err, tb=False)
  2200. def process_video_result(self, info_dict, download=True):
  2201. assert info_dict.get('_type', 'video') == 'video'
  2202. self._num_videos += 1
  2203. if 'id' not in info_dict:
  2204. raise ExtractorError('Missing "id" field in extractor result', ie=info_dict['extractor'])
  2205. elif not info_dict.get('id'):
  2206. raise ExtractorError('Extractor failed to obtain "id"', ie=info_dict['extractor'])
  2207. def report_force_conversion(field, field_not, conversion):
  2208. self.report_warning(
  2209. '"%s" field is not %s - forcing %s conversion, there is an error in extractor'
  2210. % (field, field_not, conversion))
  2211. def sanitize_string_field(info, string_field):
  2212. field = info.get(string_field)
  2213. if field is None or isinstance(field, str):
  2214. return
  2215. report_force_conversion(string_field, 'a string', 'string')
  2216. info[string_field] = str(field)
  2217. def sanitize_numeric_fields(info):
  2218. for numeric_field in self._NUMERIC_FIELDS:
  2219. field = info.get(numeric_field)
  2220. if field is None or isinstance(field, (int, float)):
  2221. continue
  2222. report_force_conversion(numeric_field, 'numeric', 'int')
  2223. info[numeric_field] = int_or_none(field)
  2224. sanitize_string_field(info_dict, 'id')
  2225. sanitize_numeric_fields(info_dict)
  2226. if info_dict.get('section_end') and info_dict.get('section_start') is not None:
  2227. info_dict['duration'] = round(info_dict['section_end'] - info_dict['section_start'], 3)
  2228. if (info_dict.get('duration') or 0) <= 0 and info_dict.pop('duration', None):
  2229. self.report_warning('"duration" field is negative, there is an error in extractor')
  2230. chapters = info_dict.get('chapters') or []
  2231. if chapters and chapters[0].get('start_time'):
  2232. chapters.insert(0, {'start_time': 0})
  2233. dummy_chapter = {'end_time': 0, 'start_time': info_dict.get('duration')}
  2234. for idx, (prev, current, next_) in enumerate(zip(
  2235. (dummy_chapter, *chapters), chapters, (*chapters[1:], dummy_chapter)), 1):
  2236. if current.get('start_time') is None:
  2237. current['start_time'] = prev.get('end_time')
  2238. if not current.get('end_time'):
  2239. current['end_time'] = next_.get('start_time')
  2240. if not current.get('title'):
  2241. current['title'] = f'<Untitled Chapter {idx}>'
  2242. if 'playlist' not in info_dict:
  2243. # It isn't part of a playlist
  2244. info_dict['playlist'] = None
  2245. info_dict['playlist_index'] = None
  2246. self._sanitize_thumbnails(info_dict)
  2247. thumbnail = info_dict.get('thumbnail')
  2248. thumbnails = info_dict.get('thumbnails')
  2249. if thumbnail:
  2250. info_dict['thumbnail'] = sanitize_url(thumbnail)
  2251. elif thumbnails:
  2252. info_dict['thumbnail'] = thumbnails[-1]['url']
  2253. if info_dict.get('display_id') is None and 'id' in info_dict:
  2254. info_dict['display_id'] = info_dict['id']
  2255. self._fill_common_fields(info_dict)
  2256. for cc_kind in ('subtitles', 'automatic_captions'):
  2257. cc = info_dict.get(cc_kind)
  2258. if cc:
  2259. for _, subtitle in cc.items():
  2260. for subtitle_format in subtitle:
  2261. if subtitle_format.get('url'):
  2262. subtitle_format['url'] = sanitize_url(subtitle_format['url'])
  2263. if subtitle_format.get('ext') is None:
  2264. subtitle_format['ext'] = determine_ext(subtitle_format['url']).lower()
  2265. automatic_captions = info_dict.get('automatic_captions')
  2266. subtitles = info_dict.get('subtitles')
  2267. info_dict['requested_subtitles'] = self.process_subtitles(
  2268. info_dict['id'], subtitles, automatic_captions)
  2269. if info_dict.get('formats') is None:
  2270. # There's only one format available
  2271. formats = [info_dict]
  2272. else:
  2273. formats = info_dict['formats']
  2274. # or None ensures --clean-infojson removes it
  2275. info_dict['_has_drm'] = any(f.get('has_drm') for f in formats) or None
  2276. if not self.params.get('allow_unplayable_formats'):
  2277. formats = [f for f in formats if not f.get('has_drm')]
  2278. if formats and all(f.get('acodec') == f.get('vcodec') == 'none' for f in formats):
  2279. self.report_warning(
  2280. f'{"This video is DRM protected and " if info_dict["_has_drm"] else ""}'
  2281. 'only images are available for download. Use --list-formats to see them'.capitalize())
  2282. get_from_start = not info_dict.get('is_live') or bool(self.params.get('live_from_start'))
  2283. if not get_from_start:
  2284. info_dict['title'] += ' ' + datetime.datetime.now().strftime('%Y-%m-%d %H:%M')
  2285. if info_dict.get('is_live') and formats:
  2286. formats = [f for f in formats if bool(f.get('is_from_start')) == get_from_start]
  2287. if get_from_start and not formats:
  2288. self.raise_no_formats(info_dict, msg=(
  2289. '--live-from-start is passed, but there are no formats that can be downloaded from the start. '
  2290. 'If you want to download from the current time, use --no-live-from-start'))
  2291. def is_wellformed(f):
  2292. url = f.get('url')
  2293. if not url:
  2294. self.report_warning(
  2295. '"url" field is missing or empty - skipping format, '
  2296. 'there is an error in extractor')
  2297. return False
  2298. if isinstance(url, bytes):
  2299. sanitize_string_field(f, 'url')
  2300. return True
  2301. # Filter out malformed formats for better extraction robustness
  2302. formats = list(filter(is_wellformed, formats or []))
  2303. if not formats:
  2304. self.raise_no_formats(info_dict)
  2305. formats_dict = {}
  2306. # We check that all the formats have the format and format_id fields
  2307. for i, format in enumerate(formats):
  2308. sanitize_string_field(format, 'format_id')
  2309. sanitize_numeric_fields(format)
  2310. format['url'] = sanitize_url(format['url'])
  2311. if not format.get('format_id'):
  2312. format['format_id'] = str(i)
  2313. else:
  2314. # Sanitize format_id from characters used in format selector expression
  2315. format['format_id'] = re.sub(r'[\s,/+\[\]()]', '_', format['format_id'])
  2316. format_id = format['format_id']
  2317. if format_id not in formats_dict:
  2318. formats_dict[format_id] = []
  2319. formats_dict[format_id].append(format)
  2320. # Make sure all formats have unique format_id
  2321. common_exts = set(itertools.chain(*self._format_selection_exts.values()))
  2322. for format_id, ambiguous_formats in formats_dict.items():
  2323. ambigious_id = len(ambiguous_formats) > 1
  2324. for i, format in enumerate(ambiguous_formats):
  2325. if ambigious_id:
  2326. format['format_id'] = '%s-%d' % (format_id, i)
  2327. if format.get('ext') is None:
  2328. format['ext'] = determine_ext(format['url']).lower()
  2329. # Ensure there is no conflict between id and ext in format selection
  2330. # See https://github.com/yt-dlp/yt-dlp/issues/1282
  2331. if format['format_id'] != format['ext'] and format['format_id'] in common_exts:
  2332. format['format_id'] = 'f%s' % format['format_id']
  2333. for i, format in enumerate(formats):
  2334. if format.get('format') is None:
  2335. format['format'] = '{id} - {res}{note}'.format(
  2336. id=format['format_id'],
  2337. res=self.format_resolution(format),
  2338. note=format_field(format, 'format_note', ' (%s)'),
  2339. )
  2340. if format.get('protocol') is None:
  2341. format['protocol'] = determine_protocol(format)
  2342. if format.get('resolution') is None:
  2343. format['resolution'] = self.format_resolution(format, default=None)
  2344. if format.get('dynamic_range') is None and format.get('vcodec') != 'none':
  2345. format['dynamic_range'] = 'SDR'
  2346. if (info_dict.get('duration') and format.get('tbr')
  2347. and not format.get('filesize') and not format.get('filesize_approx')):
  2348. format['filesize_approx'] = int(info_dict['duration'] * format['tbr'] * (1024 / 8))
  2349. # Add HTTP headers, so that external programs can use them from the
  2350. # json output
  2351. full_format_info = info_dict.copy()
  2352. full_format_info.update(format)
  2353. format['http_headers'] = self._calc_headers(full_format_info)
  2354. # Remove private housekeeping stuff
  2355. if '__x_forwarded_for_ip' in info_dict:
  2356. del info_dict['__x_forwarded_for_ip']
  2357. if self.params.get('check_formats') is True:
  2358. formats = LazyList(self._check_formats(formats[::-1]), reverse=True)
  2359. if not formats or formats[0] is not info_dict:
  2360. # only set the 'formats' fields if the original info_dict list them
  2361. # otherwise we end up with a circular reference, the first (and unique)
  2362. # element in the 'formats' field in info_dict is info_dict itself,
  2363. # which can't be exported to json
  2364. info_dict['formats'] = formats
  2365. info_dict, _ = self.pre_process(info_dict)
  2366. if self._match_entry(info_dict, incomplete=self._format_fields) is not None:
  2367. return info_dict
  2368. self.post_extract(info_dict)
  2369. info_dict, _ = self.pre_process(info_dict, 'after_filter')
  2370. # The pre-processors may have modified the formats
  2371. formats = info_dict.get('formats', [info_dict])
  2372. list_only = self.params.get('simulate') is None and (
  2373. self.params.get('list_thumbnails') or self.params.get('listformats') or self.params.get('listsubtitles'))
  2374. interactive_format_selection = not list_only and self.format_selector == '-'
  2375. if self.params.get('list_thumbnails'):
  2376. self.list_thumbnails(info_dict)
  2377. if self.params.get('listsubtitles'):
  2378. if 'automatic_captions' in info_dict:
  2379. self.list_subtitles(
  2380. info_dict['id'], automatic_captions, 'automatic captions')
  2381. self.list_subtitles(info_dict['id'], subtitles, 'subtitles')
  2382. if self.params.get('listformats') or interactive_format_selection:
  2383. self.list_formats(info_dict)
  2384. if list_only:
  2385. # Without this printing, -F --print-json will not work
  2386. self.__forced_printings(info_dict, self.prepare_filename(info_dict), incomplete=True)
  2387. return info_dict
  2388. format_selector = self.format_selector
  2389. if format_selector is None:
  2390. req_format = self._default_format_spec(info_dict, download=download)
  2391. self.write_debug('Default format spec: %s' % req_format)
  2392. format_selector = self.build_format_selector(req_format)
  2393. while True:
  2394. if interactive_format_selection:
  2395. req_format = input(
  2396. self._format_screen('\nEnter format selector: ', self.Styles.EMPHASIS))
  2397. try:
  2398. format_selector = self.build_format_selector(req_format)
  2399. except SyntaxError as err:
  2400. self.report_error(err, tb=False, is_error=False)
  2401. continue
  2402. formats_to_download = list(format_selector({
  2403. 'formats': formats,
  2404. 'has_merged_format': any('none' not in (f.get('acodec'), f.get('vcodec')) for f in formats),
  2405. 'incomplete_formats': (
  2406. # All formats are video-only or
  2407. all(f.get('vcodec') != 'none' and f.get('acodec') == 'none' for f in formats)
  2408. # all formats are audio-only
  2409. or all(f.get('vcodec') == 'none' and f.get('acodec') != 'none' for f in formats)),
  2410. }))
  2411. if interactive_format_selection and not formats_to_download:
  2412. self.report_error('Requested format is not available', tb=False, is_error=False)
  2413. continue
  2414. break
  2415. if not formats_to_download:
  2416. if not self.params.get('ignore_no_formats_error'):
  2417. raise ExtractorError(
  2418. 'Requested format is not available. Use --list-formats for a list of available formats',
  2419. expected=True, video_id=info_dict['id'], ie=info_dict['extractor'])
  2420. self.report_warning('Requested format is not available')
  2421. # Process what we can, even without any available formats.
  2422. formats_to_download = [{}]
  2423. requested_ranges = tuple(self.params.get('download_ranges', lambda *_: [{}])(info_dict, self))
  2424. best_format, downloaded_formats = formats_to_download[-1], []
  2425. if download:
  2426. if best_format and requested_ranges:
  2427. def to_screen(*msg):
  2428. self.to_screen(f'[info] {info_dict["id"]}: {" ".join(", ".join(variadic(m)) for m in msg)}')
  2429. to_screen(f'Downloading {len(formats_to_download)} format(s):',
  2430. (f['format_id'] for f in formats_to_download))
  2431. if requested_ranges != ({}, ):
  2432. to_screen(f'Downloading {len(requested_ranges)} time ranges:',
  2433. (f'{c["start_time"]:.1f}-{c["end_time"]:.1f}' for c in requested_ranges))
  2434. max_downloads_reached = False
  2435. for fmt, chapter in itertools.product(formats_to_download, requested_ranges):
  2436. new_info = self._copy_infodict(info_dict)
  2437. new_info.update(fmt)
  2438. offset, duration = info_dict.get('section_start') or 0, info_dict.get('duration') or float('inf')
  2439. end_time = offset + min(chapter.get('end_time', duration), duration)
  2440. if chapter or offset:
  2441. new_info.update({
  2442. 'section_start': offset + chapter.get('start_time', 0),
  2443. 'section_end': end_time if end_time < offset + duration else None,
  2444. 'section_title': chapter.get('title'),
  2445. 'section_number': chapter.get('index'),
  2446. })
  2447. downloaded_formats.append(new_info)
  2448. try:
  2449. self.process_info(new_info)
  2450. except MaxDownloadsReached:
  2451. max_downloads_reached = True
  2452. self._raise_pending_errors(new_info)
  2453. # Remove copied info
  2454. for key, val in tuple(new_info.items()):
  2455. if info_dict.get(key) == val:
  2456. new_info.pop(key)
  2457. if max_downloads_reached:
  2458. break
  2459. write_archive = {f.get('__write_download_archive', False) for f in downloaded_formats}
  2460. assert write_archive.issubset({True, False, 'ignore'})
  2461. if True in write_archive and False not in write_archive:
  2462. self.record_download_archive(info_dict)
  2463. info_dict['requested_downloads'] = downloaded_formats
  2464. info_dict = self.run_all_pps('after_video', info_dict)
  2465. if max_downloads_reached:
  2466. raise MaxDownloadsReached()
  2467. # We update the info dict with the selected best quality format (backwards compatibility)
  2468. info_dict.update(best_format)
  2469. return info_dict
  2470. def process_subtitles(self, video_id, normal_subtitles, automatic_captions):
  2471. """Select the requested subtitles and their format"""
  2472. available_subs, normal_sub_langs = {}, []
  2473. if normal_subtitles and self.params.get('writesubtitles'):
  2474. available_subs.update(normal_subtitles)
  2475. normal_sub_langs = tuple(normal_subtitles.keys())
  2476. if automatic_captions and self.params.get('writeautomaticsub'):
  2477. for lang, cap_info in automatic_captions.items():
  2478. if lang not in available_subs:
  2479. available_subs[lang] = cap_info
  2480. if not available_subs or (
  2481. not self.params.get('writesubtitles')
  2482. and not self.params.get('writeautomaticsub')):
  2483. return None
  2484. all_sub_langs = tuple(available_subs.keys())
  2485. if self.params.get('allsubtitles', False):
  2486. requested_langs = all_sub_langs
  2487. elif self.params.get('subtitleslangs', False):
  2488. try:
  2489. requested_langs = orderedSet_from_options(
  2490. self.params.get('subtitleslangs'), {'all': all_sub_langs}, use_regex=True)
  2491. except re.error as e:
  2492. raise ValueError(f'Wrong regex for subtitlelangs: {e.pattern}')
  2493. elif normal_sub_langs:
  2494. requested_langs = ['en'] if 'en' in normal_sub_langs else normal_sub_langs[:1]
  2495. else:
  2496. requested_langs = ['en'] if 'en' in all_sub_langs else all_sub_langs[:1]
  2497. if requested_langs:
  2498. self.to_screen(f'[info] {video_id}: Downloading subtitles: {", ".join(requested_langs)}')
  2499. formats_query = self.params.get('subtitlesformat', 'best')
  2500. formats_preference = formats_query.split('/') if formats_query else []
  2501. subs = {}
  2502. for lang in requested_langs:
  2503. formats = available_subs.get(lang)
  2504. if formats is None:
  2505. self.report_warning(f'{lang} subtitles not available for {video_id}')
  2506. continue
  2507. for ext in formats_preference:
  2508. if ext == 'best':
  2509. f = formats[-1]
  2510. break
  2511. matches = list(filter(lambda f: f['ext'] == ext, formats))
  2512. if matches:
  2513. f = matches[-1]
  2514. break
  2515. else:
  2516. f = formats[-1]
  2517. self.report_warning(
  2518. 'No subtitle format found matching "%s" for language %s, '
  2519. 'using %s' % (formats_query, lang, f['ext']))
  2520. subs[lang] = f
  2521. return subs
  2522. def _forceprint(self, key, info_dict):
  2523. if info_dict is None:
  2524. return
  2525. info_copy = info_dict.copy()
  2526. info_copy['formats_table'] = self.render_formats_table(info_dict)
  2527. info_copy['thumbnails_table'] = self.render_thumbnails_table(info_dict)
  2528. info_copy['subtitles_table'] = self.render_subtitles_table(info_dict.get('id'), info_dict.get('subtitles'))
  2529. info_copy['automatic_captions_table'] = self.render_subtitles_table(info_dict.get('id'), info_dict.get('automatic_captions'))
  2530. def format_tmpl(tmpl):
  2531. mobj = re.fullmatch(r'([\w.:,]|-\d|(?P<dict>{([\w.:,]|-\d)+}))+=?', tmpl)
  2532. if not mobj:
  2533. return tmpl
  2534. fmt = '%({})s'
  2535. if tmpl.startswith('{'):
  2536. tmpl = f'.{tmpl}'
  2537. if tmpl.endswith('='):
  2538. tmpl, fmt = tmpl[:-1], '{0} = %({0})#j'
  2539. return '\n'.join(map(fmt.format, [tmpl] if mobj.group('dict') else tmpl.split(',')))
  2540. for tmpl in self.params['forceprint'].get(key, []):
  2541. self.to_stdout(self.evaluate_outtmpl(format_tmpl(tmpl), info_copy))
  2542. for tmpl, file_tmpl in self.params['print_to_file'].get(key, []):
  2543. filename = self.prepare_filename(info_dict, outtmpl=file_tmpl)
  2544. tmpl = format_tmpl(tmpl)
  2545. self.to_screen(f'[info] Writing {tmpl!r} to: {filename}')
  2546. if self._ensure_dir_exists(filename):
  2547. with open(filename, 'a', encoding='utf-8') as f:
  2548. f.write(self.evaluate_outtmpl(tmpl, info_copy) + '\n')
  2549. def __forced_printings(self, info_dict, filename, incomplete):
  2550. def print_mandatory(field, actual_field=None):
  2551. if actual_field is None:
  2552. actual_field = field
  2553. if (self.params.get('force%s' % field, False)
  2554. and (not incomplete or info_dict.get(actual_field) is not None)):
  2555. self.to_stdout(info_dict[actual_field])
  2556. def print_optional(field):
  2557. if (self.params.get('force%s' % field, False)
  2558. and info_dict.get(field) is not None):
  2559. self.to_stdout(info_dict[field])
  2560. info_dict = info_dict.copy()
  2561. if filename is not None:
  2562. info_dict['filename'] = filename
  2563. if info_dict.get('requested_formats') is not None:
  2564. # For RTMP URLs, also include the playpath
  2565. info_dict['urls'] = '\n'.join(f['url'] + f.get('play_path', '') for f in info_dict['requested_formats'])
  2566. elif info_dict.get('url'):
  2567. info_dict['urls'] = info_dict['url'] + info_dict.get('play_path', '')
  2568. if (self.params.get('forcejson')
  2569. or self.params['forceprint'].get('video')
  2570. or self.params['print_to_file'].get('video')):
  2571. self.post_extract(info_dict)
  2572. self._forceprint('video', info_dict)
  2573. print_mandatory('title')
  2574. print_mandatory('id')
  2575. print_mandatory('url', 'urls')
  2576. print_optional('thumbnail')
  2577. print_optional('description')
  2578. print_optional('filename')
  2579. if self.params.get('forceduration') and info_dict.get('duration') is not None:
  2580. self.to_stdout(formatSeconds(info_dict['duration']))
  2581. print_mandatory('format')
  2582. if self.params.get('forcejson'):
  2583. self.to_stdout(json.dumps(self.sanitize_info(info_dict)))
  2584. def dl(self, name, info, subtitle=False, test=False):
  2585. if not info.get('url'):
  2586. self.raise_no_formats(info, True)
  2587. if test:
  2588. verbose = self.params.get('verbose')
  2589. params = {
  2590. 'test': True,
  2591. 'quiet': self.params.get('quiet') or not verbose,
  2592. 'verbose': verbose,
  2593. 'noprogress': not verbose,
  2594. 'nopart': True,
  2595. 'skip_unavailable_fragments': False,
  2596. 'keep_fragments': False,
  2597. 'overwrites': True,
  2598. '_no_ytdl_file': True,
  2599. }
  2600. else:
  2601. params = self.params
  2602. fd = get_suitable_downloader(info, params, to_stdout=(name == '-'))(self, params)
  2603. if not test:
  2604. for ph in self._progress_hooks:
  2605. fd.add_progress_hook(ph)
  2606. urls = '", "'.join(
  2607. (f['url'].split(',')[0] + ',<data>' if f['url'].startswith('data:') else f['url'])
  2608. for f in info.get('requested_formats', []) or [info])
  2609. self.write_debug(f'Invoking {fd.FD_NAME} downloader on "{urls}"')
  2610. # Note: Ideally info should be a deep-copied so that hooks cannot modify it.
  2611. # But it may contain objects that are not deep-copyable
  2612. new_info = self._copy_infodict(info)
  2613. if new_info.get('http_headers') is None:
  2614. new_info['http_headers'] = self._calc_headers(new_info)
  2615. return fd.download(name, new_info, subtitle)
  2616. def existing_file(self, filepaths, *, default_overwrite=True):
  2617. existing_files = list(filter(os.path.exists, orderedSet(filepaths)))
  2618. if existing_files and not self.params.get('overwrites', default_overwrite):
  2619. return existing_files[0]
  2620. for file in existing_files:
  2621. self.report_file_delete(file)
  2622. os.remove(file)
  2623. return None
  2624. def process_info(self, info_dict):
  2625. """Process a single resolved IE result. (Modifies it in-place)"""
  2626. assert info_dict.get('_type', 'video') == 'video'
  2627. original_infodict = info_dict
  2628. if 'format' not in info_dict and 'ext' in info_dict:
  2629. info_dict['format'] = info_dict['ext']
  2630. # This is mostly just for backward compatibility of process_info
  2631. # As a side-effect, this allows for format-specific filters
  2632. if self._match_entry(info_dict) is not None:
  2633. info_dict['__write_download_archive'] = 'ignore'
  2634. return
  2635. # Does nothing under normal operation - for backward compatibility of process_info
  2636. self.post_extract(info_dict)
  2637. self._num_downloads += 1
  2638. # info_dict['_filename'] needs to be set for backward compatibility
  2639. info_dict['_filename'] = full_filename = self.prepare_filename(info_dict, warn=True)
  2640. temp_filename = self.prepare_filename(info_dict, 'temp')
  2641. files_to_move = {}
  2642. # Forced printings
  2643. self.__forced_printings(info_dict, full_filename, incomplete=('format' not in info_dict))
  2644. def check_max_downloads():
  2645. if self._num_downloads >= float(self.params.get('max_downloads') or 'inf'):
  2646. raise MaxDownloadsReached()
  2647. if self.params.get('simulate'):
  2648. info_dict['__write_download_archive'] = self.params.get('force_write_download_archive')
  2649. check_max_downloads()
  2650. return
  2651. if full_filename is None:
  2652. return
  2653. if not self._ensure_dir_exists(encodeFilename(full_filename)):
  2654. return
  2655. if not self._ensure_dir_exists(encodeFilename(temp_filename)):
  2656. return
  2657. if self._write_description('video', info_dict,
  2658. self.prepare_filename(info_dict, 'description')) is None:
  2659. return
  2660. sub_files = self._write_subtitles(info_dict, temp_filename)
  2661. if sub_files is None:
  2662. return
  2663. files_to_move.update(dict(sub_files))
  2664. thumb_files = self._write_thumbnails(
  2665. 'video', info_dict, temp_filename, self.prepare_filename(info_dict, 'thumbnail'))
  2666. if thumb_files is None:
  2667. return
  2668. files_to_move.update(dict(thumb_files))
  2669. infofn = self.prepare_filename(info_dict, 'infojson')
  2670. _infojson_written = self._write_info_json('video', info_dict, infofn)
  2671. if _infojson_written:
  2672. info_dict['infojson_filename'] = infofn
  2673. # For backward compatibility, even though it was a private field
  2674. info_dict['__infojson_filename'] = infofn
  2675. elif _infojson_written is None:
  2676. return
  2677. # Note: Annotations are deprecated
  2678. annofn = None
  2679. if self.params.get('writeannotations', False):
  2680. annofn = self.prepare_filename(info_dict, 'annotation')
  2681. if annofn:
  2682. if not self._ensure_dir_exists(encodeFilename(annofn)):
  2683. return
  2684. if not self.params.get('overwrites', True) and os.path.exists(encodeFilename(annofn)):
  2685. self.to_screen('[info] Video annotations are already present')
  2686. elif not info_dict.get('annotations'):
  2687. self.report_warning('There are no annotations to write.')
  2688. else:
  2689. try:
  2690. self.to_screen('[info] Writing video annotations to: ' + annofn)
  2691. with open(encodeFilename(annofn), 'w', encoding='utf-8') as annofile:
  2692. annofile.write(info_dict['annotations'])
  2693. except (KeyError, TypeError):
  2694. self.report_warning('There are no annotations to write.')
  2695. except OSError:
  2696. self.report_error('Cannot write annotations file: ' + annofn)
  2697. return
  2698. # Write internet shortcut files
  2699. def _write_link_file(link_type):
  2700. url = try_get(info_dict['webpage_url'], iri_to_uri)
  2701. if not url:
  2702. self.report_warning(
  2703. f'Cannot write internet shortcut file because the actual URL of "{info_dict["webpage_url"]}" is unknown')
  2704. return True
  2705. linkfn = replace_extension(self.prepare_filename(info_dict, 'link'), link_type, info_dict.get('ext'))
  2706. if not self._ensure_dir_exists(encodeFilename(linkfn)):
  2707. return False
  2708. if self.params.get('overwrites', True) and os.path.exists(encodeFilename(linkfn)):
  2709. self.to_screen(f'[info] Internet shortcut (.{link_type}) is already present')
  2710. return True
  2711. try:
  2712. self.to_screen(f'[info] Writing internet shortcut (.{link_type}) to: {linkfn}')
  2713. with open(encodeFilename(to_high_limit_path(linkfn)), 'w', encoding='utf-8',
  2714. newline='\r\n' if link_type == 'url' else '\n') as linkfile:
  2715. template_vars = {'url': url}
  2716. if link_type == 'desktop':
  2717. template_vars['filename'] = linkfn[:-(len(link_type) + 1)]
  2718. linkfile.write(LINK_TEMPLATES[link_type] % template_vars)
  2719. except OSError:
  2720. self.report_error(f'Cannot write internet shortcut {linkfn}')
  2721. return False
  2722. return True
  2723. write_links = {
  2724. 'url': self.params.get('writeurllink'),
  2725. 'webloc': self.params.get('writewebloclink'),
  2726. 'desktop': self.params.get('writedesktoplink'),
  2727. }
  2728. if self.params.get('writelink'):
  2729. link_type = ('webloc' if sys.platform == 'darwin'
  2730. else 'desktop' if sys.platform.startswith('linux')
  2731. else 'url')
  2732. write_links[link_type] = True
  2733. if any(should_write and not _write_link_file(link_type)
  2734. for link_type, should_write in write_links.items()):
  2735. return
  2736. def replace_info_dict(new_info):
  2737. nonlocal info_dict
  2738. if new_info == info_dict:
  2739. return
  2740. info_dict.clear()
  2741. info_dict.update(new_info)
  2742. new_info, files_to_move = self.pre_process(info_dict, 'before_dl', files_to_move)
  2743. replace_info_dict(new_info)
  2744. if self.params.get('skip_download'):
  2745. info_dict['filepath'] = temp_filename
  2746. info_dict['__finaldir'] = os.path.dirname(os.path.abspath(encodeFilename(full_filename)))
  2747. info_dict['__files_to_move'] = files_to_move
  2748. replace_info_dict(self.run_pp(MoveFilesAfterDownloadPP(self, False), info_dict))
  2749. info_dict['__write_download_archive'] = self.params.get('force_write_download_archive')
  2750. else:
  2751. # Download
  2752. info_dict.setdefault('__postprocessors', [])
  2753. try:
  2754. def existing_video_file(*filepaths):
  2755. ext = info_dict.get('ext')
  2756. converted = lambda file: replace_extension(file, self.params.get('final_ext') or ext, ext)
  2757. file = self.existing_file(itertools.chain(*zip(map(converted, filepaths), filepaths)),
  2758. default_overwrite=False)
  2759. if file:
  2760. info_dict['ext'] = os.path.splitext(file)[1][1:]
  2761. return file
  2762. fd, success = None, True
  2763. if info_dict.get('protocol') or info_dict.get('url'):
  2764. fd = get_suitable_downloader(info_dict, self.params, to_stdout=temp_filename == '-')
  2765. if fd is not FFmpegFD and (
  2766. info_dict.get('section_start') or info_dict.get('section_end')):
  2767. msg = ('This format cannot be partially downloaded' if FFmpegFD.available()
  2768. else 'You have requested downloading the video partially, but ffmpeg is not installed')
  2769. self.report_error(f'{msg}. Aborting')
  2770. return
  2771. if info_dict.get('requested_formats') is not None:
  2772. requested_formats = info_dict['requested_formats']
  2773. old_ext = info_dict['ext']
  2774. if self.params.get('merge_output_format') is None:
  2775. if (info_dict['ext'] == 'webm'
  2776. and info_dict.get('thumbnails')
  2777. # check with type instead of pp_key, __name__, or isinstance
  2778. # since we dont want any custom PPs to trigger this
  2779. and any(type(pp) == EmbedThumbnailPP for pp in self._pps['post_process'])): # noqa: E721
  2780. info_dict['ext'] = 'mkv'
  2781. self.report_warning(
  2782. 'webm doesn\'t support embedding a thumbnail, mkv will be used')
  2783. new_ext = info_dict['ext']
  2784. def correct_ext(filename, ext=new_ext):
  2785. if filename == '-':
  2786. return filename
  2787. filename_real_ext = os.path.splitext(filename)[1][1:]
  2788. filename_wo_ext = (
  2789. os.path.splitext(filename)[0]
  2790. if filename_real_ext in (old_ext, new_ext)
  2791. else filename)
  2792. return f'{filename_wo_ext}.{ext}'
  2793. # Ensure filename always has a correct extension for successful merge
  2794. full_filename = correct_ext(full_filename)
  2795. temp_filename = correct_ext(temp_filename)
  2796. dl_filename = existing_video_file(full_filename, temp_filename)
  2797. info_dict['__real_download'] = False
  2798. merger = FFmpegMergerPP(self)
  2799. downloaded = []
  2800. if dl_filename is not None:
  2801. self.report_file_already_downloaded(dl_filename)
  2802. elif fd:
  2803. for f in requested_formats if fd != FFmpegFD else []:
  2804. f['filepath'] = fname = prepend_extension(
  2805. correct_ext(temp_filename, info_dict['ext']),
  2806. 'f%s' % f['format_id'], info_dict['ext'])
  2807. downloaded.append(fname)
  2808. info_dict['url'] = '\n'.join(f['url'] for f in requested_formats)
  2809. success, real_download = self.dl(temp_filename, info_dict)
  2810. info_dict['__real_download'] = real_download
  2811. else:
  2812. if self.params.get('allow_unplayable_formats'):
  2813. self.report_warning(
  2814. 'You have requested merging of multiple formats '
  2815. 'while also allowing unplayable formats to be downloaded. '
  2816. 'The formats won\'t be merged to prevent data corruption.')
  2817. elif not merger.available:
  2818. msg = 'You have requested merging of multiple formats but ffmpeg is not installed'
  2819. if not self.params.get('ignoreerrors'):
  2820. self.report_error(f'{msg}. Aborting due to --abort-on-error')
  2821. return
  2822. self.report_warning(f'{msg}. The formats won\'t be merged')
  2823. if temp_filename == '-':
  2824. reason = ('using a downloader other than ffmpeg' if FFmpegFD.can_merge_formats(info_dict, self.params)
  2825. else 'but the formats are incompatible for simultaneous download' if merger.available
  2826. else 'but ffmpeg is not installed')
  2827. self.report_warning(
  2828. f'You have requested downloading multiple formats to stdout {reason}. '
  2829. 'The formats will be streamed one after the other')
  2830. fname = temp_filename
  2831. for f in requested_formats:
  2832. new_info = dict(info_dict)
  2833. del new_info['requested_formats']
  2834. new_info.update(f)
  2835. if temp_filename != '-':
  2836. fname = prepend_extension(
  2837. correct_ext(temp_filename, new_info['ext']),
  2838. 'f%s' % f['format_id'], new_info['ext'])
  2839. if not self._ensure_dir_exists(fname):
  2840. return
  2841. f['filepath'] = fname
  2842. downloaded.append(fname)
  2843. partial_success, real_download = self.dl(fname, new_info)
  2844. info_dict['__real_download'] = info_dict['__real_download'] or real_download
  2845. success = success and partial_success
  2846. if downloaded and merger.available and not self.params.get('allow_unplayable_formats'):
  2847. info_dict['__postprocessors'].append(merger)
  2848. info_dict['__files_to_merge'] = downloaded
  2849. # Even if there were no downloads, it is being merged only now
  2850. info_dict['__real_download'] = True
  2851. else:
  2852. for file in downloaded:
  2853. files_to_move[file] = None
  2854. else:
  2855. # Just a single file
  2856. dl_filename = existing_video_file(full_filename, temp_filename)
  2857. if dl_filename is None or dl_filename == temp_filename:
  2858. # dl_filename == temp_filename could mean that the file was partially downloaded with --no-part.
  2859. # So we should try to resume the download
  2860. success, real_download = self.dl(temp_filename, info_dict)
  2861. info_dict['__real_download'] = real_download
  2862. else:
  2863. self.report_file_already_downloaded(dl_filename)
  2864. dl_filename = dl_filename or temp_filename
  2865. info_dict['__finaldir'] = os.path.dirname(os.path.abspath(encodeFilename(full_filename)))
  2866. except network_exceptions as err:
  2867. self.report_error('unable to download video data: %s' % error_to_compat_str(err))
  2868. return
  2869. except OSError as err:
  2870. raise UnavailableVideoError(err)
  2871. except (ContentTooShortError, ) as err:
  2872. self.report_error(f'content too short (expected {err.expected} bytes and served {err.downloaded})')
  2873. return
  2874. self._raise_pending_errors(info_dict)
  2875. if success and full_filename != '-':
  2876. def fixup():
  2877. do_fixup = True
  2878. fixup_policy = self.params.get('fixup')
  2879. vid = info_dict['id']
  2880. if fixup_policy in ('ignore', 'never'):
  2881. return
  2882. elif fixup_policy == 'warn':
  2883. do_fixup = 'warn'
  2884. elif fixup_policy != 'force':
  2885. assert fixup_policy in ('detect_or_warn', None)
  2886. if not info_dict.get('__real_download'):
  2887. do_fixup = False
  2888. def ffmpeg_fixup(cndn, msg, cls):
  2889. if not (do_fixup and cndn):
  2890. return
  2891. elif do_fixup == 'warn':
  2892. self.report_warning(f'{vid}: {msg}')
  2893. return
  2894. pp = cls(self)
  2895. if pp.available:
  2896. info_dict['__postprocessors'].append(pp)
  2897. else:
  2898. self.report_warning(f'{vid}: {msg}. Install ffmpeg to fix this automatically')
  2899. stretched_ratio = info_dict.get('stretched_ratio')
  2900. ffmpeg_fixup(stretched_ratio not in (1, None),
  2901. f'Non-uniform pixel ratio {stretched_ratio}',
  2902. FFmpegFixupStretchedPP)
  2903. downloader = get_suitable_downloader(info_dict, self.params) if 'protocol' in info_dict else None
  2904. downloader = downloader.FD_NAME if downloader else None
  2905. ext = info_dict.get('ext')
  2906. postprocessed_by_ffmpeg = info_dict.get('requested_formats') or any((
  2907. isinstance(pp, FFmpegVideoConvertorPP)
  2908. and resolve_recode_mapping(ext, pp.mapping)[0] not in (ext, None)
  2909. ) for pp in self._pps['post_process'])
  2910. if not postprocessed_by_ffmpeg:
  2911. ffmpeg_fixup(ext == 'm4a' and info_dict.get('container') == 'm4a_dash',
  2912. 'writing DASH m4a. Only some players support this container',
  2913. FFmpegFixupM4aPP)
  2914. ffmpeg_fixup(downloader == 'hlsnative' and not self.params.get('hls_use_mpegts')
  2915. or info_dict.get('is_live') and self.params.get('hls_use_mpegts') is None,
  2916. 'Possible MPEG-TS in MP4 container or malformed AAC timestamps',
  2917. FFmpegFixupM3u8PP)
  2918. ffmpeg_fixup(info_dict.get('is_live') and downloader == 'DashSegmentsFD',
  2919. 'Possible duplicate MOOV atoms', FFmpegFixupDuplicateMoovPP)
  2920. ffmpeg_fixup(downloader == 'web_socket_fragment', 'Malformed timestamps detected', FFmpegFixupTimestampPP)
  2921. ffmpeg_fixup(downloader == 'web_socket_fragment', 'Malformed duration detected', FFmpegFixupDurationPP)
  2922. fixup()
  2923. try:
  2924. replace_info_dict(self.post_process(dl_filename, info_dict, files_to_move))
  2925. except PostProcessingError as err:
  2926. self.report_error('Postprocessing: %s' % str(err))
  2927. return
  2928. try:
  2929. for ph in self._post_hooks:
  2930. ph(info_dict['filepath'])
  2931. except Exception as err:
  2932. self.report_error('post hooks: %s' % str(err))
  2933. return
  2934. info_dict['__write_download_archive'] = True
  2935. assert info_dict is original_infodict # Make sure the info_dict was modified in-place
  2936. if self.params.get('force_write_download_archive'):
  2937. info_dict['__write_download_archive'] = True
  2938. check_max_downloads()
  2939. def __download_wrapper(self, func):
  2940. @functools.wraps(func)
  2941. def wrapper(*args, **kwargs):
  2942. try:
  2943. res = func(*args, **kwargs)
  2944. except UnavailableVideoError as e:
  2945. self.report_error(e)
  2946. except DownloadCancelled as e:
  2947. self.to_screen(f'[info] {e}')
  2948. if not self.params.get('break_per_url'):
  2949. raise
  2950. self._num_downloads = 0
  2951. else:
  2952. if self.params.get('dump_single_json', False):
  2953. self.post_extract(res)
  2954. self.to_stdout(json.dumps(self.sanitize_info(res)))
  2955. return wrapper
  2956. def download(self, url_list):
  2957. """Download a given list of URLs."""
  2958. url_list = variadic(url_list) # Passing a single URL is a common mistake
  2959. outtmpl = self.params['outtmpl']['default']
  2960. if (len(url_list) > 1
  2961. and outtmpl != '-'
  2962. and '%' not in outtmpl
  2963. and self.params.get('max_downloads') != 1):
  2964. raise SameFileError(outtmpl)
  2965. for url in url_list:
  2966. self.__download_wrapper(self.extract_info)(
  2967. url, force_generic_extractor=self.params.get('force_generic_extractor', False))
  2968. return self._download_retcode
  2969. def download_with_info_file(self, info_filename):
  2970. with contextlib.closing(fileinput.FileInput(
  2971. [info_filename], mode='r',
  2972. openhook=fileinput.hook_encoded('utf-8'))) as f:
  2973. # FileInput doesn't have a read method, we can't call json.load
  2974. info = self.sanitize_info(json.loads('\n'.join(f)), self.params.get('clean_infojson', True))
  2975. try:
  2976. self.__download_wrapper(self.process_ie_result)(info, download=True)
  2977. except (DownloadError, EntryNotInPlaylist, ReExtractInfo) as e:
  2978. if not isinstance(e, EntryNotInPlaylist):
  2979. self.to_stderr('\r')
  2980. webpage_url = info.get('webpage_url')
  2981. if webpage_url is not None:
  2982. self.report_warning(f'The info failed to download: {e}; trying with URL {webpage_url}')
  2983. return self.download([webpage_url])
  2984. else:
  2985. raise
  2986. return self._download_retcode
  2987. @staticmethod
  2988. def sanitize_info(info_dict, remove_private_keys=False):
  2989. ''' Sanitize the infodict for converting to json '''
  2990. if info_dict is None:
  2991. return info_dict
  2992. info_dict.setdefault('epoch', int(time.time()))
  2993. info_dict.setdefault('_type', 'video')
  2994. info_dict.setdefault('_version', {
  2995. 'version': __version__,
  2996. 'current_git_head': current_git_head(),
  2997. 'release_git_head': RELEASE_GIT_HEAD,
  2998. 'repository': REPOSITORY,
  2999. })
  3000. if remove_private_keys:
  3001. reject = lambda k, v: v is None or k.startswith('__') or k in {
  3002. 'requested_downloads', 'requested_formats', 'requested_subtitles', 'requested_entries',
  3003. 'entries', 'filepath', '_filename', 'infojson_filename', 'original_url', 'playlist_autonumber',
  3004. }
  3005. else:
  3006. reject = lambda k, v: False
  3007. def filter_fn(obj):
  3008. if isinstance(obj, dict):
  3009. return {k: filter_fn(v) for k, v in obj.items() if not reject(k, v)}
  3010. elif isinstance(obj, (list, tuple, set, LazyList)):
  3011. return list(map(filter_fn, obj))
  3012. elif obj is None or isinstance(obj, (str, int, float, bool)):
  3013. return obj
  3014. else:
  3015. return repr(obj)
  3016. return filter_fn(info_dict)
  3017. @staticmethod
  3018. def filter_requested_info(info_dict, actually_filter=True):
  3019. ''' Alias of sanitize_info for backward compatibility '''
  3020. return YoutubeDL.sanitize_info(info_dict, actually_filter)
  3021. def _delete_downloaded_files(self, *files_to_delete, info={}, msg=None):
  3022. for filename in set(filter(None, files_to_delete)):
  3023. if msg:
  3024. self.to_screen(msg % filename)
  3025. try:
  3026. os.remove(filename)
  3027. except OSError:
  3028. self.report_warning(f'Unable to delete file {filename}')
  3029. if filename in info.get('__files_to_move', []): # NB: Delete even if None
  3030. del info['__files_to_move'][filename]
  3031. @staticmethod
  3032. def post_extract(info_dict):
  3033. def actual_post_extract(info_dict):
  3034. if info_dict.get('_type') in ('playlist', 'multi_video'):
  3035. for video_dict in info_dict.get('entries', {}):
  3036. actual_post_extract(video_dict or {})
  3037. return
  3038. post_extractor = info_dict.pop('__post_extractor', None) or (lambda: {})
  3039. info_dict.update(post_extractor())
  3040. actual_post_extract(info_dict or {})
  3041. def run_pp(self, pp, infodict):
  3042. files_to_delete = []
  3043. if '__files_to_move' not in infodict:
  3044. infodict['__files_to_move'] = {}
  3045. try:
  3046. files_to_delete, infodict = pp.run(infodict)
  3047. except PostProcessingError as e:
  3048. # Must be True and not 'only_download'
  3049. if self.params.get('ignoreerrors') is True:
  3050. self.report_error(e)
  3051. return infodict
  3052. raise
  3053. if not files_to_delete:
  3054. return infodict
  3055. if self.params.get('keepvideo', False):
  3056. for f in files_to_delete:
  3057. infodict['__files_to_move'].setdefault(f, '')
  3058. else:
  3059. self._delete_downloaded_files(
  3060. *files_to_delete, info=infodict, msg='Deleting original file %s (pass -k to keep)')
  3061. return infodict
  3062. def run_all_pps(self, key, info, *, additional_pps=None):
  3063. self._forceprint(key, info)
  3064. for pp in (additional_pps or []) + self._pps[key]:
  3065. info = self.run_pp(pp, info)
  3066. return info
  3067. def pre_process(self, ie_info, key='pre_process', files_to_move=None):
  3068. info = dict(ie_info)
  3069. info['__files_to_move'] = files_to_move or {}
  3070. try:
  3071. info = self.run_all_pps(key, info)
  3072. except PostProcessingError as err:
  3073. msg = f'Preprocessing: {err}'
  3074. info.setdefault('__pending_error', msg)
  3075. self.report_error(msg, is_error=False)
  3076. return info, info.pop('__files_to_move', None)
  3077. def post_process(self, filename, info, files_to_move=None):
  3078. """Run all the postprocessors on the given file."""
  3079. info['filepath'] = filename
  3080. info['__files_to_move'] = files_to_move or {}
  3081. info = self.run_all_pps('post_process', info, additional_pps=info.get('__postprocessors'))
  3082. info = self.run_pp(MoveFilesAfterDownloadPP(self), info)
  3083. del info['__files_to_move']
  3084. return self.run_all_pps('after_move', info)
  3085. def _make_archive_id(self, info_dict):
  3086. video_id = info_dict.get('id')
  3087. if not video_id:
  3088. return
  3089. # Future-proof against any change in case
  3090. # and backwards compatibility with prior versions
  3091. extractor = info_dict.get('extractor_key') or info_dict.get('ie_key') # key in a playlist
  3092. if extractor is None:
  3093. url = str_or_none(info_dict.get('url'))
  3094. if not url:
  3095. return
  3096. # Try to find matching extractor for the URL and take its ie_key
  3097. for ie_key, ie in self._ies.items():
  3098. if ie.suitable(url):
  3099. extractor = ie_key
  3100. break
  3101. else:
  3102. return
  3103. return make_archive_id(extractor, video_id)
  3104. def in_download_archive(self, info_dict):
  3105. if not self.archive:
  3106. return False
  3107. vid_ids = [self._make_archive_id(info_dict)]
  3108. vid_ids.extend(info_dict.get('_old_archive_ids') or [])
  3109. return any(id_ in self.archive for id_ in vid_ids)
  3110. def record_download_archive(self, info_dict):
  3111. fn = self.params.get('download_archive')
  3112. if fn is None:
  3113. return
  3114. vid_id = self._make_archive_id(info_dict)
  3115. assert vid_id
  3116. self.write_debug(f'Adding to archive: {vid_id}')
  3117. if is_path_like(fn):
  3118. with locked_file(fn, 'a', encoding='utf-8') as archive_file:
  3119. archive_file.write(vid_id + '\n')
  3120. self.archive.add(vid_id)
  3121. @staticmethod
  3122. def format_resolution(format, default='unknown'):
  3123. if format.get('vcodec') == 'none' and format.get('acodec') != 'none':
  3124. return 'audio only'
  3125. if format.get('resolution') is not None:
  3126. return format['resolution']
  3127. if format.get('width') and format.get('height'):
  3128. return '%dx%d' % (format['width'], format['height'])
  3129. elif format.get('height'):
  3130. return '%sp' % format['height']
  3131. elif format.get('width'):
  3132. return '%dx?' % format['width']
  3133. return default
  3134. def _list_format_headers(self, *headers):
  3135. if self.params.get('listformats_table', True) is not False:
  3136. return [self._format_out(header, self.Styles.HEADERS) for header in headers]
  3137. return headers
  3138. def _format_note(self, fdict):
  3139. res = ''
  3140. if fdict.get('ext') in ['f4f', 'f4m']:
  3141. res += '(unsupported)'
  3142. if fdict.get('language'):
  3143. if res:
  3144. res += ' '
  3145. res += '[%s]' % fdict['language']
  3146. if fdict.get('format_note') is not None:
  3147. if res:
  3148. res += ' '
  3149. res += fdict['format_note']
  3150. if fdict.get('tbr') is not None:
  3151. if res:
  3152. res += ', '
  3153. res += '%4dk' % fdict['tbr']
  3154. if fdict.get('container') is not None:
  3155. if res:
  3156. res += ', '
  3157. res += '%s container' % fdict['container']
  3158. if (fdict.get('vcodec') is not None
  3159. and fdict.get('vcodec') != 'none'):
  3160. if res:
  3161. res += ', '
  3162. res += fdict['vcodec']
  3163. if fdict.get('vbr') is not None:
  3164. res += '@'
  3165. elif fdict.get('vbr') is not None and fdict.get('abr') is not None:
  3166. res += 'video@'
  3167. if fdict.get('vbr') is not None:
  3168. res += '%4dk' % fdict['vbr']
  3169. if fdict.get('fps') is not None:
  3170. if res:
  3171. res += ', '
  3172. res += '%sfps' % fdict['fps']
  3173. if fdict.get('acodec') is not None:
  3174. if res:
  3175. res += ', '
  3176. if fdict['acodec'] == 'none':
  3177. res += 'video only'
  3178. else:
  3179. res += '%-5s' % fdict['acodec']
  3180. elif fdict.get('abr') is not None:
  3181. if res:
  3182. res += ', '
  3183. res += 'audio'
  3184. if fdict.get('abr') is not None:
  3185. res += '@%3dk' % fdict['abr']
  3186. if fdict.get('asr') is not None:
  3187. res += ' (%5dHz)' % fdict['asr']
  3188. if fdict.get('filesize') is not None:
  3189. if res:
  3190. res += ', '
  3191. res += format_bytes(fdict['filesize'])
  3192. elif fdict.get('filesize_approx') is not None:
  3193. if res:
  3194. res += ', '
  3195. res += '~' + format_bytes(fdict['filesize_approx'])
  3196. return res
  3197. def render_formats_table(self, info_dict):
  3198. if not info_dict.get('formats') and not info_dict.get('url'):
  3199. return None
  3200. formats = info_dict.get('formats', [info_dict])
  3201. if not self.params.get('listformats_table', True) is not False:
  3202. table = [
  3203. [
  3204. format_field(f, 'format_id'),
  3205. format_field(f, 'ext'),
  3206. self.format_resolution(f),
  3207. self._format_note(f)
  3208. ] for f in formats if f.get('preference') is None or f['preference'] >= -1000]
  3209. return render_table(['format code', 'extension', 'resolution', 'note'], table, extra_gap=1)
  3210. def simplified_codec(f, field):
  3211. assert field in ('acodec', 'vcodec')
  3212. codec = f.get(field, 'unknown')
  3213. if not codec:
  3214. return 'unknown'
  3215. elif codec != 'none':
  3216. return '.'.join(codec.split('.')[:4])
  3217. if field == 'vcodec' and f.get('acodec') == 'none':
  3218. return 'images'
  3219. elif field == 'acodec' and f.get('vcodec') == 'none':
  3220. return ''
  3221. return self._format_out('audio only' if field == 'vcodec' else 'video only',
  3222. self.Styles.SUPPRESS)
  3223. delim = self._format_out('\u2502', self.Styles.DELIM, '|', test_encoding=True)
  3224. table = [
  3225. [
  3226. self._format_out(format_field(f, 'format_id'), self.Styles.ID),
  3227. format_field(f, 'ext'),
  3228. format_field(f, func=self.format_resolution, ignore=('audio only', 'images')),
  3229. format_field(f, 'fps', '\t%d', func=round),
  3230. format_field(f, 'dynamic_range', '%s', ignore=(None, 'SDR')).replace('HDR', ''),
  3231. format_field(f, 'audio_channels', '\t%s'),
  3232. delim,
  3233. format_field(f, 'filesize', ' \t%s', func=format_bytes) + format_field(f, 'filesize_approx', '~\t%s', func=format_bytes),
  3234. format_field(f, 'tbr', '\t%dk', func=round),
  3235. shorten_protocol_name(f.get('protocol', '')),
  3236. delim,
  3237. simplified_codec(f, 'vcodec'),
  3238. format_field(f, 'vbr', '\t%dk', func=round),
  3239. simplified_codec(f, 'acodec'),
  3240. format_field(f, 'abr', '\t%dk', func=round),
  3241. format_field(f, 'asr', '\t%s', func=format_decimal_suffix),
  3242. join_nonempty(
  3243. self._format_out('UNSUPPORTED', 'light red') if f.get('ext') in ('f4f', 'f4m') else None,
  3244. format_field(f, 'language', '[%s]'),
  3245. join_nonempty(format_field(f, 'format_note'),
  3246. format_field(f, 'container', ignore=(None, f.get('ext'))),
  3247. delim=', '),
  3248. delim=' '),
  3249. ] for f in formats if f.get('preference') is None or f['preference'] >= -1000]
  3250. header_line = self._list_format_headers(
  3251. 'ID', 'EXT', 'RESOLUTION', '\tFPS', 'HDR', 'CH', delim, '\tFILESIZE', '\tTBR', 'PROTO',
  3252. delim, 'VCODEC', '\tVBR', 'ACODEC', '\tABR', '\tASR', 'MORE INFO')
  3253. return render_table(
  3254. header_line, table, hide_empty=True,
  3255. delim=self._format_out('\u2500', self.Styles.DELIM, '-', test_encoding=True))
  3256. def render_thumbnails_table(self, info_dict):
  3257. thumbnails = list(info_dict.get('thumbnails') or [])
  3258. if not thumbnails:
  3259. return None
  3260. return render_table(
  3261. self._list_format_headers('ID', 'Width', 'Height', 'URL'),
  3262. [[t.get('id'), t.get('width') or 'unknown', t.get('height') or 'unknown', t['url']] for t in thumbnails])
  3263. def render_subtitles_table(self, video_id, subtitles):
  3264. def _row(lang, formats):
  3265. exts, names = zip(*((f['ext'], f.get('name') or 'unknown') for f in reversed(formats)))
  3266. if len(set(names)) == 1:
  3267. names = [] if names[0] == 'unknown' else names[:1]
  3268. return [lang, ', '.join(names), ', '.join(exts)]
  3269. if not subtitles:
  3270. return None
  3271. return render_table(
  3272. self._list_format_headers('Language', 'Name', 'Formats'),
  3273. [_row(lang, formats) for lang, formats in subtitles.items()],
  3274. hide_empty=True)
  3275. def __list_table(self, video_id, name, func, *args):
  3276. table = func(*args)
  3277. if not table:
  3278. self.to_screen(f'{video_id} has no {name}')
  3279. return
  3280. self.to_screen(f'[info] Available {name} for {video_id}:')
  3281. self.to_stdout(table)
  3282. def list_formats(self, info_dict):
  3283. self.__list_table(info_dict['id'], 'formats', self.render_formats_table, info_dict)
  3284. def list_thumbnails(self, info_dict):
  3285. self.__list_table(info_dict['id'], 'thumbnails', self.render_thumbnails_table, info_dict)
  3286. def list_subtitles(self, video_id, subtitles, name='subtitles'):
  3287. self.__list_table(video_id, name, self.render_subtitles_table, video_id, subtitles)
  3288. def urlopen(self, req):
  3289. """ Start an HTTP download """
  3290. if isinstance(req, str):
  3291. req = sanitized_Request(req)
  3292. return self._opener.open(req, timeout=self._socket_timeout)
  3293. def print_debug_header(self):
  3294. if not self.params.get('verbose'):
  3295. return
  3296. from . import _IN_CLI # Must be delayed import
  3297. # These imports can be slow. So import them only as needed
  3298. from .extractor.extractors import _LAZY_LOADER
  3299. from .extractor.extractors import _PLUGIN_CLASSES as plugin_extractors
  3300. def get_encoding(stream):
  3301. ret = str(getattr(stream, 'encoding', 'missing (%s)' % type(stream).__name__))
  3302. if not supports_terminal_sequences(stream):
  3303. from .utils import WINDOWS_VT_MODE # Must be imported locally
  3304. ret += ' (No VT)' if WINDOWS_VT_MODE is False else ' (No ANSI)'
  3305. return ret
  3306. encoding_str = 'Encodings: locale %s, fs %s, pref %s, %s' % (
  3307. locale.getpreferredencoding(),
  3308. sys.getfilesystemencoding(),
  3309. self.get_encoding(),
  3310. ', '.join(
  3311. f'{key} {get_encoding(stream)}' for key, stream in self._out_files.items_
  3312. if stream is not None and key != 'console')
  3313. )
  3314. logger = self.params.get('logger')
  3315. if logger:
  3316. write_debug = lambda msg: logger.debug(f'[debug] {msg}')
  3317. write_debug(encoding_str)
  3318. else:
  3319. write_string(f'[debug] {encoding_str}\n', encoding=None)
  3320. write_debug = lambda msg: self._write_string(f'[debug] {msg}\n')
  3321. source = detect_variant()
  3322. if VARIANT not in (None, 'pip'):
  3323. source += '*'
  3324. write_debug(join_nonempty(
  3325. f'{"yt-dlp" if REPOSITORY == "yt-dlp/yt-dlp" else REPOSITORY} version',
  3326. __version__,
  3327. f'[{RELEASE_GIT_HEAD}]' if RELEASE_GIT_HEAD else '',
  3328. '' if source == 'unknown' else f'({source})',
  3329. '' if _IN_CLI else 'API',
  3330. delim=' '))
  3331. if not _LAZY_LOADER:
  3332. if os.environ.get('YTDLP_NO_LAZY_EXTRACTORS'):
  3333. write_debug('Lazy loading extractors is forcibly disabled')
  3334. else:
  3335. write_debug('Lazy loading extractors is disabled')
  3336. if plugin_extractors or plugin_postprocessors:
  3337. write_debug('Plugins: %s' % [
  3338. '%s%s' % (klass.__name__, '' if klass.__name__ == name else f' as {name}')
  3339. for name, klass in itertools.chain(plugin_extractors.items(), plugin_postprocessors.items())])
  3340. if self.params['compat_opts']:
  3341. write_debug('Compatibility options: %s' % ', '.join(self.params['compat_opts']))
  3342. if current_git_head():
  3343. write_debug(f'Git HEAD: {current_git_head()}')
  3344. write_debug(system_identifier())
  3345. exe_versions, ffmpeg_features = FFmpegPostProcessor.get_versions_and_features(self)
  3346. ffmpeg_features = {key for key, val in ffmpeg_features.items() if val}
  3347. if ffmpeg_features:
  3348. exe_versions['ffmpeg'] += ' (%s)' % ','.join(sorted(ffmpeg_features))
  3349. exe_versions['rtmpdump'] = rtmpdump_version()
  3350. exe_versions['phantomjs'] = PhantomJSwrapper._version()
  3351. exe_str = ', '.join(
  3352. f'{exe} {v}' for exe, v in sorted(exe_versions.items()) if v
  3353. ) or 'none'
  3354. write_debug('exe versions: %s' % exe_str)
  3355. from .compat.compat_utils import get_package_info
  3356. from .dependencies import available_dependencies
  3357. write_debug('Optional libraries: %s' % (', '.join(sorted({
  3358. join_nonempty(*get_package_info(m)) for m in available_dependencies.values()
  3359. })) or 'none'))
  3360. self._setup_opener()
  3361. proxy_map = {}
  3362. for handler in self._opener.handlers:
  3363. if hasattr(handler, 'proxies'):
  3364. proxy_map.update(handler.proxies)
  3365. write_debug(f'Proxy map: {proxy_map}')
  3366. # Not implemented
  3367. if False and self.params.get('call_home'):
  3368. ipaddr = self.urlopen('https://yt-dl.org/ip').read().decode()
  3369. write_debug('Public IP address: %s' % ipaddr)
  3370. latest_version = self.urlopen(
  3371. 'https://yt-dl.org/latest/version').read().decode()
  3372. if version_tuple(latest_version) > version_tuple(__version__):
  3373. self.report_warning(
  3374. 'You are using an outdated version (newest version: %s)! '
  3375. 'See https://yt-dl.org/update if you need help updating.' %
  3376. latest_version)
  3377. def _setup_opener(self):
  3378. if hasattr(self, '_opener'):
  3379. return
  3380. timeout_val = self.params.get('socket_timeout')
  3381. self._socket_timeout = 20 if timeout_val is None else float(timeout_val)
  3382. opts_cookiesfrombrowser = self.params.get('cookiesfrombrowser')
  3383. opts_cookiefile = self.params.get('cookiefile')
  3384. opts_proxy = self.params.get('proxy')
  3385. self.cookiejar = load_cookies(opts_cookiefile, opts_cookiesfrombrowser, self)
  3386. cookie_processor = YoutubeDLCookieProcessor(self.cookiejar)
  3387. if opts_proxy is not None:
  3388. if opts_proxy == '':
  3389. proxies = {}
  3390. else:
  3391. proxies = {'http': opts_proxy, 'https': opts_proxy}
  3392. else:
  3393. proxies = urllib.request.getproxies()
  3394. # Set HTTPS proxy to HTTP one if given (https://github.com/ytdl-org/youtube-dl/issues/805)
  3395. if 'http' in proxies and 'https' not in proxies:
  3396. proxies['https'] = proxies['http']
  3397. proxy_handler = PerRequestProxyHandler(proxies)
  3398. debuglevel = 1 if self.params.get('debug_printtraffic') else 0
  3399. https_handler = make_HTTPS_handler(self.params, debuglevel=debuglevel)
  3400. ydlh = YoutubeDLHandler(self.params, debuglevel=debuglevel)
  3401. redirect_handler = YoutubeDLRedirectHandler()
  3402. data_handler = urllib.request.DataHandler()
  3403. # When passing our own FileHandler instance, build_opener won't add the
  3404. # default FileHandler and allows us to disable the file protocol, which
  3405. # can be used for malicious purposes (see
  3406. # https://github.com/ytdl-org/youtube-dl/issues/8227)
  3407. file_handler = urllib.request.FileHandler()
  3408. def file_open(*args, **kwargs):
  3409. raise urllib.error.URLError('file:// scheme is explicitly disabled in yt-dlp for security reasons')
  3410. file_handler.file_open = file_open
  3411. opener = urllib.request.build_opener(
  3412. proxy_handler, https_handler, cookie_processor, ydlh, redirect_handler, data_handler, file_handler)
  3413. # Delete the default user-agent header, which would otherwise apply in
  3414. # cases where our custom HTTP handler doesn't come into play
  3415. # (See https://github.com/ytdl-org/youtube-dl/issues/1309 for details)
  3416. opener.addheaders = []
  3417. self._opener = opener
  3418. def encode(self, s):
  3419. if isinstance(s, bytes):
  3420. return s # Already encoded
  3421. try:
  3422. return s.encode(self.get_encoding())
  3423. except UnicodeEncodeError as err:
  3424. err.reason = err.reason + '. Check your system encoding configuration or use the --encoding option.'
  3425. raise
  3426. def get_encoding(self):
  3427. encoding = self.params.get('encoding')
  3428. if encoding is None:
  3429. encoding = preferredencoding()
  3430. return encoding
  3431. def _write_info_json(self, label, ie_result, infofn, overwrite=None):
  3432. ''' Write infojson and returns True = written, 'exists' = Already exists, False = skip, None = error '''
  3433. if overwrite is None:
  3434. overwrite = self.params.get('overwrites', True)
  3435. if not self.params.get('writeinfojson'):
  3436. return False
  3437. elif not infofn:
  3438. self.write_debug(f'Skipping writing {label} infojson')
  3439. return False
  3440. elif not self._ensure_dir_exists(infofn):
  3441. return None
  3442. elif not overwrite and os.path.exists(infofn):
  3443. self.to_screen(f'[info] {label.title()} metadata is already present')
  3444. return 'exists'
  3445. self.to_screen(f'[info] Writing {label} metadata as JSON to: {infofn}')
  3446. try:
  3447. write_json_file(self.sanitize_info(ie_result, self.params.get('clean_infojson', True)), infofn)
  3448. return True
  3449. except OSError:
  3450. self.report_error(f'Cannot write {label} metadata to JSON file {infofn}')
  3451. return None
  3452. def _write_description(self, label, ie_result, descfn):
  3453. ''' Write description and returns True = written, False = skip, None = error '''
  3454. if not self.params.get('writedescription'):
  3455. return False
  3456. elif not descfn:
  3457. self.write_debug(f'Skipping writing {label} description')
  3458. return False
  3459. elif not self._ensure_dir_exists(descfn):
  3460. return None
  3461. elif not self.params.get('overwrites', True) and os.path.exists(descfn):
  3462. self.to_screen(f'[info] {label.title()} description is already present')
  3463. elif ie_result.get('description') is None:
  3464. self.report_warning(f'There\'s no {label} description to write')
  3465. return False
  3466. else:
  3467. try:
  3468. self.to_screen(f'[info] Writing {label} description to: {descfn}')
  3469. with open(encodeFilename(descfn), 'w', encoding='utf-8') as descfile:
  3470. descfile.write(ie_result['description'])
  3471. except OSError:
  3472. self.report_error(f'Cannot write {label} description file {descfn}')
  3473. return None
  3474. return True
  3475. def _write_subtitles(self, info_dict, filename):
  3476. ''' Write subtitles to file and return list of (sub_filename, final_sub_filename); or None if error'''
  3477. ret = []
  3478. subtitles = info_dict.get('requested_subtitles')
  3479. if not subtitles or not (self.params.get('writesubtitles') or self.params.get('writeautomaticsub')):
  3480. # subtitles download errors are already managed as troubles in relevant IE
  3481. # that way it will silently go on when used with unsupporting IE
  3482. return ret
  3483. sub_filename_base = self.prepare_filename(info_dict, 'subtitle')
  3484. if not sub_filename_base:
  3485. self.to_screen('[info] Skipping writing video subtitles')
  3486. return ret
  3487. for sub_lang, sub_info in subtitles.items():
  3488. sub_format = sub_info['ext']
  3489. sub_filename = subtitles_filename(filename, sub_lang, sub_format, info_dict.get('ext'))
  3490. sub_filename_final = subtitles_filename(sub_filename_base, sub_lang, sub_format, info_dict.get('ext'))
  3491. existing_sub = self.existing_file((sub_filename_final, sub_filename))
  3492. if existing_sub:
  3493. self.to_screen(f'[info] Video subtitle {sub_lang}.{sub_format} is already present')
  3494. sub_info['filepath'] = existing_sub
  3495. ret.append((existing_sub, sub_filename_final))
  3496. continue
  3497. self.to_screen(f'[info] Writing video subtitles to: {sub_filename}')
  3498. if sub_info.get('data') is not None:
  3499. try:
  3500. # Use newline='' to prevent conversion of newline characters
  3501. # See https://github.com/ytdl-org/youtube-dl/issues/10268
  3502. with open(sub_filename, 'w', encoding='utf-8', newline='') as subfile:
  3503. subfile.write(sub_info['data'])
  3504. sub_info['filepath'] = sub_filename
  3505. ret.append((sub_filename, sub_filename_final))
  3506. continue
  3507. except OSError:
  3508. self.report_error(f'Cannot write video subtitles file {sub_filename}')
  3509. return None
  3510. try:
  3511. sub_copy = sub_info.copy()
  3512. sub_copy.setdefault('http_headers', info_dict.get('http_headers'))
  3513. self.dl(sub_filename, sub_copy, subtitle=True)
  3514. sub_info['filepath'] = sub_filename
  3515. ret.append((sub_filename, sub_filename_final))
  3516. except (DownloadError, ExtractorError, IOError, OSError, ValueError) + network_exceptions as err:
  3517. msg = f'Unable to download video subtitles for {sub_lang!r}: {err}'
  3518. if self.params.get('ignoreerrors') is not True: # False or 'only_download'
  3519. if not self.params.get('ignoreerrors'):
  3520. self.report_error(msg)
  3521. raise DownloadError(msg)
  3522. self.report_warning(msg)
  3523. return ret
  3524. def _write_thumbnails(self, label, info_dict, filename, thumb_filename_base=None):
  3525. ''' Write thumbnails to file and return list of (thumb_filename, final_thumb_filename) '''
  3526. write_all = self.params.get('write_all_thumbnails', False)
  3527. thumbnails, ret = [], []
  3528. if write_all or self.params.get('writethumbnail', False):
  3529. thumbnails = info_dict.get('thumbnails') or []
  3530. multiple = write_all and len(thumbnails) > 1
  3531. if thumb_filename_base is None:
  3532. thumb_filename_base = filename
  3533. if thumbnails and not thumb_filename_base:
  3534. self.write_debug(f'Skipping writing {label} thumbnail')
  3535. return ret
  3536. for idx, t in list(enumerate(thumbnails))[::-1]:
  3537. thumb_ext = (f'{t["id"]}.' if multiple else '') + determine_ext(t['url'], 'jpg')
  3538. thumb_display_id = f'{label} thumbnail {t["id"]}'
  3539. thumb_filename = replace_extension(filename, thumb_ext, info_dict.get('ext'))
  3540. thumb_filename_final = replace_extension(thumb_filename_base, thumb_ext, info_dict.get('ext'))
  3541. existing_thumb = self.existing_file((thumb_filename_final, thumb_filename))
  3542. if existing_thumb:
  3543. self.to_screen('[info] %s is already present' % (
  3544. thumb_display_id if multiple else f'{label} thumbnail').capitalize())
  3545. t['filepath'] = existing_thumb
  3546. ret.append((existing_thumb, thumb_filename_final))
  3547. else:
  3548. self.to_screen(f'[info] Downloading {thumb_display_id} ...')
  3549. try:
  3550. uf = self.urlopen(sanitized_Request(t['url'], headers=t.get('http_headers', {})))
  3551. self.to_screen(f'[info] Writing {thumb_display_id} to: {thumb_filename}')
  3552. with open(encodeFilename(thumb_filename), 'wb') as thumbf:
  3553. shutil.copyfileobj(uf, thumbf)
  3554. ret.append((thumb_filename, thumb_filename_final))
  3555. t['filepath'] = thumb_filename
  3556. except network_exceptions as err:
  3557. thumbnails.pop(idx)
  3558. self.report_warning(f'Unable to download {thumb_display_id}: {err}')
  3559. if ret and not write_all:
  3560. break
  3561. return ret