YoutubeDL.py 183 KB

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