YoutubeDL.py 180 KB

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