YoutubeDL.py 189 KB

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