YoutubeDL.py 201 KB

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