yt-api-dlp 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (1048) hide show
  1. yt_api_dlp/YoutubeDL.py +4548 -0
  2. yt_api_dlp/__init__.py +1113 -0
  3. yt_api_dlp/__main__.py +17 -0
  4. yt_api_dlp/__pyinstaller/__init__.py +5 -0
  5. yt_api_dlp/__pyinstaller/hook-yt_dlp.py +37 -0
  6. yt_api_dlp/aes.py +552 -0
  7. yt_api_dlp/cache.py +91 -0
  8. yt_api_dlp/compat/__init__.py +64 -0
  9. yt_api_dlp/compat/_deprecated.py +21 -0
  10. yt_api_dlp/compat/_legacy.py +115 -0
  11. yt_api_dlp/compat/compat_utils.py +83 -0
  12. yt_api_dlp/compat/imghdr.py +22 -0
  13. yt_api_dlp/compat/shutil.py +30 -0
  14. yt_api_dlp/compat/urllib/__init__.py +10 -0
  15. yt_api_dlp/compat/urllib/request.py +36 -0
  16. yt_api_dlp/cookies.py +1420 -0
  17. yt_api_dlp/dependencies/Cryptodome.py +38 -0
  18. yt_api_dlp/dependencies/__init__.py +102 -0
  19. yt_api_dlp/downloader/__init__.py +133 -0
  20. yt_api_dlp/downloader/bunnycdn.py +50 -0
  21. yt_api_dlp/downloader/common.py +520 -0
  22. yt_api_dlp/downloader/dash.py +95 -0
  23. yt_api_dlp/downloader/external.py +595 -0
  24. yt_api_dlp/downloader/f4m.py +427 -0
  25. yt_api_dlp/downloader/fc2.py +46 -0
  26. yt_api_dlp/downloader/fragment.py +526 -0
  27. yt_api_dlp/downloader/hls.py +409 -0
  28. yt_api_dlp/downloader/http.py +376 -0
  29. yt_api_dlp/downloader/ism.py +283 -0
  30. yt_api_dlp/downloader/mhtml.py +174 -0
  31. yt_api_dlp/downloader/niconico.py +90 -0
  32. yt_api_dlp/downloader/rtmp.py +212 -0
  33. yt_api_dlp/downloader/rtsp.py +42 -0
  34. yt_api_dlp/downloader/soop.py +61 -0
  35. yt_api_dlp/downloader/websocket.py +53 -0
  36. yt_api_dlp/downloader/youtube_live_chat.py +228 -0
  37. yt_api_dlp/extractor/__init__.py +54 -0
  38. yt_api_dlp/extractor/_extractors.py +2464 -0
  39. yt_api_dlp/extractor/abc.py +443 -0
  40. yt_api_dlp/extractor/abcnews.py +153 -0
  41. yt_api_dlp/extractor/abcotvs.py +129 -0
  42. yt_api_dlp/extractor/abematv.py +496 -0
  43. yt_api_dlp/extractor/academicearth.py +39 -0
  44. yt_api_dlp/extractor/acast.py +149 -0
  45. yt_api_dlp/extractor/acfun.py +200 -0
  46. yt_api_dlp/extractor/adn.py +329 -0
  47. yt_api_dlp/extractor/adobeconnect.py +32 -0
  48. yt_api_dlp/extractor/adobepass.py +1878 -0
  49. yt_api_dlp/extractor/adobetv.py +100 -0
  50. yt_api_dlp/extractor/adultswim.py +200 -0
  51. yt_api_dlp/extractor/aenetworks.py +455 -0
  52. yt_api_dlp/extractor/aeonco.py +74 -0
  53. yt_api_dlp/extractor/afreecatv.py +475 -0
  54. yt_api_dlp/extractor/agalega.py +91 -0
  55. yt_api_dlp/extractor/agora.py +248 -0
  56. yt_api_dlp/extractor/aitube.py +60 -0
  57. yt_api_dlp/extractor/alibaba.py +42 -0
  58. yt_api_dlp/extractor/aliexpress.py +49 -0
  59. yt_api_dlp/extractor/aljazeera.py +83 -0
  60. yt_api_dlp/extractor/allocine.py +124 -0
  61. yt_api_dlp/extractor/allstar.py +252 -0
  62. yt_api_dlp/extractor/alphaporno.py +75 -0
  63. yt_api_dlp/extractor/altcensored.py +104 -0
  64. yt_api_dlp/extractor/alura.py +163 -0
  65. yt_api_dlp/extractor/amadeustv.py +77 -0
  66. yt_api_dlp/extractor/amara.py +100 -0
  67. yt_api_dlp/extractor/amazon.py +170 -0
  68. yt_api_dlp/extractor/amazonminitv.py +294 -0
  69. yt_api_dlp/extractor/amcnetworks.py +61 -0
  70. yt_api_dlp/extractor/americastestkitchen.py +215 -0
  71. yt_api_dlp/extractor/amp.py +101 -0
  72. yt_api_dlp/extractor/angel.py +56 -0
  73. yt_api_dlp/extractor/antenna.py +143 -0
  74. yt_api_dlp/extractor/anvato.py +357 -0
  75. yt_api_dlp/extractor/aol.py +133 -0
  76. yt_api_dlp/extractor/apa.py +90 -0
  77. yt_api_dlp/extractor/aparat.py +88 -0
  78. yt_api_dlp/extractor/appleconnect.py +125 -0
  79. yt_api_dlp/extractor/applepodcasts.py +79 -0
  80. yt_api_dlp/extractor/archiveorg.py +1134 -0
  81. yt_api_dlp/extractor/arcpublishing.py +179 -0
  82. yt_api_dlp/extractor/ard.py +765 -0
  83. yt_api_dlp/extractor/arnes.py +96 -0
  84. yt_api_dlp/extractor/art19.py +303 -0
  85. yt_api_dlp/extractor/arte.py +406 -0
  86. yt_api_dlp/extractor/asobichannel.py +168 -0
  87. yt_api_dlp/extractor/asobistage.py +155 -0
  88. yt_api_dlp/extractor/atresplayer.py +152 -0
  89. yt_api_dlp/extractor/atscaleconf.py +34 -0
  90. yt_api_dlp/extractor/audimedia.py +89 -0
  91. yt_api_dlp/extractor/audioboom.py +57 -0
  92. yt_api_dlp/extractor/audiodraft.py +94 -0
  93. yt_api_dlp/extractor/audiomack.py +146 -0
  94. yt_api_dlp/extractor/audius.py +273 -0
  95. yt_api_dlp/extractor/aws.py +75 -0
  96. yt_api_dlp/extractor/azmedien.py +63 -0
  97. yt_api_dlp/extractor/baidu.py +52 -0
  98. yt_api_dlp/extractor/banbye.py +226 -0
  99. yt_api_dlp/extractor/bandcamp.py +544 -0
  100. yt_api_dlp/extractor/bandlab.py +437 -0
  101. yt_api_dlp/extractor/bannedvideo.py +155 -0
  102. yt_api_dlp/extractor/bbc.py +1841 -0
  103. yt_api_dlp/extractor/beacon.py +68 -0
  104. yt_api_dlp/extractor/beatport.py +96 -0
  105. yt_api_dlp/extractor/beeg.py +89 -0
  106. yt_api_dlp/extractor/behindkink.py +42 -0
  107. yt_api_dlp/extractor/berufetv.py +70 -0
  108. yt_api_dlp/extractor/bet.py +47 -0
  109. yt_api_dlp/extractor/bfi.py +35 -0
  110. yt_api_dlp/extractor/bfmtv.py +143 -0
  111. yt_api_dlp/extractor/bibeltv.py +196 -0
  112. yt_api_dlp/extractor/bigo.py +57 -0
  113. yt_api_dlp/extractor/bild.py +63 -0
  114. yt_api_dlp/extractor/bilibili.py +2605 -0
  115. yt_api_dlp/extractor/biobiochiletv.py +83 -0
  116. yt_api_dlp/extractor/bitchute.py +315 -0
  117. yt_api_dlp/extractor/bitmovin.py +74 -0
  118. yt_api_dlp/extractor/blackboardcollaborate.py +179 -0
  119. yt_api_dlp/extractor/bleacherreport.py +110 -0
  120. yt_api_dlp/extractor/blerp.py +166 -0
  121. yt_api_dlp/extractor/blogger.py +56 -0
  122. yt_api_dlp/extractor/bloomberg.py +77 -0
  123. yt_api_dlp/extractor/bluesky.py +393 -0
  124. yt_api_dlp/extractor/bongacams.py +69 -0
  125. yt_api_dlp/extractor/boosty.py +254 -0
  126. yt_api_dlp/extractor/bostonglobe.py +67 -0
  127. yt_api_dlp/extractor/box.py +118 -0
  128. yt_api_dlp/extractor/boxcast.py +98 -0
  129. yt_api_dlp/extractor/bpb.py +157 -0
  130. yt_api_dlp/extractor/br.py +166 -0
  131. yt_api_dlp/extractor/brainpop.py +318 -0
  132. yt_api_dlp/extractor/breitbart.py +34 -0
  133. yt_api_dlp/extractor/brightcove.py +948 -0
  134. yt_api_dlp/extractor/brilliantpala.py +136 -0
  135. yt_api_dlp/extractor/btvplus.py +73 -0
  136. yt_api_dlp/extractor/bundesliga.py +34 -0
  137. yt_api_dlp/extractor/bundestag.py +124 -0
  138. yt_api_dlp/extractor/bunnycdn.py +195 -0
  139. yt_api_dlp/extractor/businessinsider.py +45 -0
  140. yt_api_dlp/extractor/buzzfeed.py +95 -0
  141. yt_api_dlp/extractor/byutv.py +104 -0
  142. yt_api_dlp/extractor/c56.py +59 -0
  143. yt_api_dlp/extractor/caltrans.py +37 -0
  144. yt_api_dlp/extractor/cam4.py +31 -0
  145. yt_api_dlp/extractor/camfm.py +85 -0
  146. yt_api_dlp/extractor/cammodels.py +77 -0
  147. yt_api_dlp/extractor/camsoda.py +57 -0
  148. yt_api_dlp/extractor/camtasia.py +71 -0
  149. yt_api_dlp/extractor/canal1.py +39 -0
  150. yt_api_dlp/extractor/canalalpha.py +107 -0
  151. yt_api_dlp/extractor/canalc2.py +68 -0
  152. yt_api_dlp/extractor/canalplus.py +109 -0
  153. yt_api_dlp/extractor/canalsurmas.py +84 -0
  154. yt_api_dlp/extractor/caracoltv.py +136 -0
  155. yt_api_dlp/extractor/cbc.py +1105 -0
  156. yt_api_dlp/extractor/cbs.py +280 -0
  157. yt_api_dlp/extractor/cbsnews.py +434 -0
  158. yt_api_dlp/extractor/cbssports.py +111 -0
  159. yt_api_dlp/extractor/ccc.py +133 -0
  160. yt_api_dlp/extractor/ccma.py +180 -0
  161. yt_api_dlp/extractor/cctv.py +200 -0
  162. yt_api_dlp/extractor/cda.py +418 -0
  163. yt_api_dlp/extractor/cellebrite.py +38 -0
  164. yt_api_dlp/extractor/ceskatelevize.py +289 -0
  165. yt_api_dlp/extractor/cgtn.py +65 -0
  166. yt_api_dlp/extractor/charlierose.py +54 -0
  167. yt_api_dlp/extractor/chaturbate.py +153 -0
  168. yt_api_dlp/extractor/chilloutzone.py +123 -0
  169. yt_api_dlp/extractor/chzzk.py +205 -0
  170. yt_api_dlp/extractor/cinemax.py +25 -0
  171. yt_api_dlp/extractor/cinetecamilano.py +62 -0
  172. yt_api_dlp/extractor/cineverse.py +140 -0
  173. yt_api_dlp/extractor/ciscolive.py +145 -0
  174. yt_api_dlp/extractor/ciscowebex.py +106 -0
  175. yt_api_dlp/extractor/cjsw.py +67 -0
  176. yt_api_dlp/extractor/clipchamp.py +61 -0
  177. yt_api_dlp/extractor/cliprs.py +31 -0
  178. yt_api_dlp/extractor/closertotruth.py +89 -0
  179. yt_api_dlp/extractor/cloudflarestream.py +96 -0
  180. yt_api_dlp/extractor/cloudycdn.py +110 -0
  181. yt_api_dlp/extractor/clubic.py +53 -0
  182. yt_api_dlp/extractor/clyp.py +99 -0
  183. yt_api_dlp/extractor/cnbc.py +97 -0
  184. yt_api_dlp/extractor/cnn.py +278 -0
  185. yt_api_dlp/extractor/comedycentral.py +27 -0
  186. yt_api_dlp/extractor/common.py +4188 -0
  187. yt_api_dlp/extractor/commonmistakes.py +58 -0
  188. yt_api_dlp/extractor/commonprotocols.py +70 -0
  189. yt_api_dlp/extractor/condenast.py +265 -0
  190. yt_api_dlp/extractor/corus.py +154 -0
  191. yt_api_dlp/extractor/coub.py +136 -0
  192. yt_api_dlp/extractor/cozytv.py +37 -0
  193. yt_api_dlp/extractor/cpac.py +134 -0
  194. yt_api_dlp/extractor/cracked.py +88 -0
  195. yt_api_dlp/extractor/craftsy.py +75 -0
  196. yt_api_dlp/extractor/croatianfilm.py +79 -0
  197. yt_api_dlp/extractor/crooksandliars.py +69 -0
  198. yt_api_dlp/extractor/crowdbunker.py +112 -0
  199. yt_api_dlp/extractor/crtvg.py +53 -0
  200. yt_api_dlp/extractor/cspan.py +286 -0
  201. yt_api_dlp/extractor/ctsnews.py +84 -0
  202. yt_api_dlp/extractor/ctvnews.py +182 -0
  203. yt_api_dlp/extractor/cultureunplugged.py +72 -0
  204. yt_api_dlp/extractor/curiositystream.py +202 -0
  205. yt_api_dlp/extractor/cybrary.py +144 -0
  206. yt_api_dlp/extractor/dacast.py +182 -0
  207. yt_api_dlp/extractor/dailymail.py +84 -0
  208. yt_api_dlp/extractor/dailymotion.py +664 -0
  209. yt_api_dlp/extractor/dailywire.py +113 -0
  210. yt_api_dlp/extractor/damtomo.py +107 -0
  211. yt_api_dlp/extractor/dangalplay.py +210 -0
  212. yt_api_dlp/extractor/daum.py +256 -0
  213. yt_api_dlp/extractor/daystar.py +47 -0
  214. yt_api_dlp/extractor/dbtv.py +61 -0
  215. yt_api_dlp/extractor/dctp.py +101 -0
  216. yt_api_dlp/extractor/democracynow.py +91 -0
  217. yt_api_dlp/extractor/detik.py +159 -0
  218. yt_api_dlp/extractor/deuxm.py +76 -0
  219. yt_api_dlp/extractor/dfb.py +52 -0
  220. yt_api_dlp/extractor/dhm.py +58 -0
  221. yt_api_dlp/extractor/digitalconcerthall.py +285 -0
  222. yt_api_dlp/extractor/digiteka.py +81 -0
  223. yt_api_dlp/extractor/digiview.py +130 -0
  224. yt_api_dlp/extractor/discogs.py +35 -0
  225. yt_api_dlp/extractor/disney.py +160 -0
  226. yt_api_dlp/extractor/dispeak.py +127 -0
  227. yt_api_dlp/extractor/dlf.py +192 -0
  228. yt_api_dlp/extractor/dlive.py +92 -0
  229. yt_api_dlp/extractor/douyutv.py +308 -0
  230. yt_api_dlp/extractor/dplay.py +1306 -0
  231. yt_api_dlp/extractor/drbonanza.py +54 -0
  232. yt_api_dlp/extractor/dreisat.py +124 -0
  233. yt_api_dlp/extractor/dropbox.py +111 -0
  234. yt_api_dlp/extractor/dropout.py +224 -0
  235. yt_api_dlp/extractor/drtalks.py +51 -0
  236. yt_api_dlp/extractor/drtuber.py +104 -0
  237. yt_api_dlp/extractor/drtv.py +400 -0
  238. yt_api_dlp/extractor/dtube.py +79 -0
  239. yt_api_dlp/extractor/dumpert.py +114 -0
  240. yt_api_dlp/extractor/duoplay.py +138 -0
  241. yt_api_dlp/extractor/dvtv.py +177 -0
  242. yt_api_dlp/extractor/dw.py +111 -0
  243. yt_api_dlp/extractor/ebaumsworld.py +31 -0
  244. yt_api_dlp/extractor/ebay.py +36 -0
  245. yt_api_dlp/extractor/egghead.py +133 -0
  246. yt_api_dlp/extractor/eggs.py +155 -0
  247. yt_api_dlp/extractor/elementorembed.py +72 -0
  248. yt_api_dlp/extractor/elonet.py +64 -0
  249. yt_api_dlp/extractor/elpais.py +92 -0
  250. yt_api_dlp/extractor/eltrecetv.py +62 -0
  251. yt_api_dlp/extractor/embedly.py +109 -0
  252. yt_api_dlp/extractor/epicon.py +116 -0
  253. yt_api_dlp/extractor/epidemicsound.py +124 -0
  254. yt_api_dlp/extractor/eplus.py +205 -0
  255. yt_api_dlp/extractor/epoch.py +55 -0
  256. yt_api_dlp/extractor/eporner.py +134 -0
  257. yt_api_dlp/extractor/erocast.py +63 -0
  258. yt_api_dlp/extractor/eroprofile.py +122 -0
  259. yt_api_dlp/extractor/err.py +292 -0
  260. yt_api_dlp/extractor/ertgr.py +310 -0
  261. yt_api_dlp/extractor/espn.py +427 -0
  262. yt_api_dlp/extractor/ettutv.py +60 -0
  263. yt_api_dlp/extractor/europa.py +190 -0
  264. yt_api_dlp/extractor/europeantour.py +34 -0
  265. yt_api_dlp/extractor/eurosport.py +165 -0
  266. yt_api_dlp/extractor/euscreen.py +59 -0
  267. yt_api_dlp/extractor/expressen.py +96 -0
  268. yt_api_dlp/extractor/extractors.py +43 -0
  269. yt_api_dlp/extractor/facebook.py +1189 -0
  270. yt_api_dlp/extractor/fancode.py +174 -0
  271. yt_api_dlp/extractor/fathom.py +54 -0
  272. yt_api_dlp/extractor/faulio.py +237 -0
  273. yt_api_dlp/extractor/faz.py +89 -0
  274. yt_api_dlp/extractor/fc2.py +299 -0
  275. yt_api_dlp/extractor/fczenit.py +51 -0
  276. yt_api_dlp/extractor/fifa.py +82 -0
  277. yt_api_dlp/extractor/filmarchiv.py +52 -0
  278. yt_api_dlp/extractor/filmon.py +170 -0
  279. yt_api_dlp/extractor/filmweb.py +38 -0
  280. yt_api_dlp/extractor/firsttv.py +171 -0
  281. yt_api_dlp/extractor/fivetv.py +85 -0
  282. yt_api_dlp/extractor/flextv.py +77 -0
  283. yt_api_dlp/extractor/flickr.py +112 -0
  284. yt_api_dlp/extractor/floatplane.py +387 -0
  285. yt_api_dlp/extractor/folketinget.py +74 -0
  286. yt_api_dlp/extractor/footyroom.py +38 -0
  287. yt_api_dlp/extractor/formula1.py +24 -0
  288. yt_api_dlp/extractor/fourtube.py +301 -0
  289. yt_api_dlp/extractor/fox.py +174 -0
  290. yt_api_dlp/extractor/fox9.py +38 -0
  291. yt_api_dlp/extractor/foxnews.py +185 -0
  292. yt_api_dlp/extractor/foxsports.py +52 -0
  293. yt_api_dlp/extractor/fptplay.py +117 -0
  294. yt_api_dlp/extractor/francaisfacile.py +76 -0
  295. yt_api_dlp/extractor/francetv.py +489 -0
  296. yt_api_dlp/extractor/freesound.py +77 -0
  297. yt_api_dlp/extractor/freespeech.py +29 -0
  298. yt_api_dlp/extractor/freetv.py +139 -0
  299. yt_api_dlp/extractor/frontendmasters.py +249 -0
  300. yt_api_dlp/extractor/frontro.py +101 -0
  301. yt_api_dlp/extractor/funk.py +43 -0
  302. yt_api_dlp/extractor/funker530.py +80 -0
  303. yt_api_dlp/extractor/fuyintv.py +30 -0
  304. yt_api_dlp/extractor/gab.py +83 -0
  305. yt_api_dlp/extractor/gaia.py +120 -0
  306. yt_api_dlp/extractor/gamedevtv.py +141 -0
  307. yt_api_dlp/extractor/gamejolt.py +537 -0
  308. yt_api_dlp/extractor/gamespot.py +76 -0
  309. yt_api_dlp/extractor/gamestar.py +60 -0
  310. yt_api_dlp/extractor/gaskrank.py +97 -0
  311. yt_api_dlp/extractor/gazeta.py +44 -0
  312. yt_api_dlp/extractor/gbnews.py +113 -0
  313. yt_api_dlp/extractor/gdcvault.py +214 -0
  314. yt_api_dlp/extractor/gedidigital.py +198 -0
  315. yt_api_dlp/extractor/generic.py +1303 -0
  316. yt_api_dlp/extractor/genericembeds.py +114 -0
  317. yt_api_dlp/extractor/genius.py +145 -0
  318. yt_api_dlp/extractor/germanupa.py +91 -0
  319. yt_api_dlp/extractor/getcourseru.py +188 -0
  320. yt_api_dlp/extractor/gettr.py +206 -0
  321. yt_api_dlp/extractor/giantbomb.py +85 -0
  322. yt_api_dlp/extractor/glide.py +38 -0
  323. yt_api_dlp/extractor/globalplayer.py +254 -0
  324. yt_api_dlp/extractor/globo.py +239 -0
  325. yt_api_dlp/extractor/glomex.py +233 -0
  326. yt_api_dlp/extractor/gmanetwork.py +83 -0
  327. yt_api_dlp/extractor/go.py +305 -0
  328. yt_api_dlp/extractor/godresource.py +79 -0
  329. yt_api_dlp/extractor/godtube.py +55 -0
  330. yt_api_dlp/extractor/golem.py +66 -0
  331. yt_api_dlp/extractor/goodgame.py +69 -0
  332. yt_api_dlp/extractor/googledrive.py +290 -0
  333. yt_api_dlp/extractor/googlesearch.py +38 -0
  334. yt_api_dlp/extractor/goplay.py +441 -0
  335. yt_api_dlp/extractor/gopro.py +105 -0
  336. yt_api_dlp/extractor/gotostage.py +66 -0
  337. yt_api_dlp/extractor/graspop.py +32 -0
  338. yt_api_dlp/extractor/gronkh.py +120 -0
  339. yt_api_dlp/extractor/groupon.py +63 -0
  340. yt_api_dlp/extractor/harpodeon.py +70 -0
  341. yt_api_dlp/extractor/hbo.py +172 -0
  342. yt_api_dlp/extractor/hearthisat.py +130 -0
  343. yt_api_dlp/extractor/heise.py +207 -0
  344. yt_api_dlp/extractor/hellporno.py +72 -0
  345. yt_api_dlp/extractor/hgtv.py +37 -0
  346. yt_api_dlp/extractor/hidive.py +119 -0
  347. yt_api_dlp/extractor/historicfilms.py +45 -0
  348. yt_api_dlp/extractor/hitrecord.py +65 -0
  349. yt_api_dlp/extractor/hollywoodreporter.py +72 -0
  350. yt_api_dlp/extractor/holodex.py +100 -0
  351. yt_api_dlp/extractor/hotnewhiphop.py +62 -0
  352. yt_api_dlp/extractor/hotstar.py +482 -0
  353. yt_api_dlp/extractor/hrefli.py +15 -0
  354. yt_api_dlp/extractor/hrfensehen.py +88 -0
  355. yt_api_dlp/extractor/hrti.py +200 -0
  356. yt_api_dlp/extractor/hse.py +93 -0
  357. yt_api_dlp/extractor/huajiao.py +53 -0
  358. yt_api_dlp/extractor/huffpost.py +90 -0
  359. yt_api_dlp/extractor/hungama.py +201 -0
  360. yt_api_dlp/extractor/huya.py +243 -0
  361. yt_api_dlp/extractor/hypem.py +47 -0
  362. yt_api_dlp/extractor/hypergryph.py +66 -0
  363. yt_api_dlp/extractor/hytale.py +59 -0
  364. yt_api_dlp/extractor/icareus.py +179 -0
  365. yt_api_dlp/extractor/ichinanalive.py +215 -0
  366. yt_api_dlp/extractor/idagio.py +262 -0
  367. yt_api_dlp/extractor/ign.py +396 -0
  368. yt_api_dlp/extractor/iheart.py +94 -0
  369. yt_api_dlp/extractor/ilpost.py +68 -0
  370. yt_api_dlp/extractor/iltalehti.py +51 -0
  371. yt_api_dlp/extractor/imdb.py +144 -0
  372. yt_api_dlp/extractor/imggaming.py +126 -0
  373. yt_api_dlp/extractor/imgur.py +428 -0
  374. yt_api_dlp/extractor/ina.py +84 -0
  375. yt_api_dlp/extractor/inc.py +57 -0
  376. yt_api_dlp/extractor/indavideo.py +130 -0
  377. yt_api_dlp/extractor/infoq.py +130 -0
  378. yt_api_dlp/extractor/instagram.py +728 -0
  379. yt_api_dlp/extractor/internazionale.py +75 -0
  380. yt_api_dlp/extractor/iprima.py +269 -0
  381. yt_api_dlp/extractor/iqiyi.py +579 -0
  382. yt_api_dlp/extractor/islamchannel.py +81 -0
  383. yt_api_dlp/extractor/israelnationalnews.py +50 -0
  384. yt_api_dlp/extractor/itprotv.py +138 -0
  385. yt_api_dlp/extractor/itv.py +267 -0
  386. yt_api_dlp/extractor/ivi.py +253 -0
  387. yt_api_dlp/extractor/ivideon.py +75 -0
  388. yt_api_dlp/extractor/ivoox.py +78 -0
  389. yt_api_dlp/extractor/iwara.py +305 -0
  390. yt_api_dlp/extractor/ixigua.py +83 -0
  391. yt_api_dlp/extractor/jamendo.py +216 -0
  392. yt_api_dlp/extractor/japandiet.py +277 -0
  393. yt_api_dlp/extractor/jeuxvideo.py +52 -0
  394. yt_api_dlp/extractor/jiosaavn.py +412 -0
  395. yt_api_dlp/extractor/jixie.py +47 -0
  396. yt_api_dlp/extractor/joj.py +115 -0
  397. yt_api_dlp/extractor/jove.py +73 -0
  398. yt_api_dlp/extractor/jstream.py +73 -0
  399. yt_api_dlp/extractor/jtbc.py +156 -0
  400. yt_api_dlp/extractor/jwplatform.py +102 -0
  401. yt_api_dlp/extractor/kakao.py +152 -0
  402. yt_api_dlp/extractor/kaltura.py +579 -0
  403. yt_api_dlp/extractor/kankanews.py +49 -0
  404. yt_api_dlp/extractor/karaoketv.py +61 -0
  405. yt_api_dlp/extractor/kelbyone.py +81 -0
  406. yt_api_dlp/extractor/kenh14.py +160 -0
  407. yt_api_dlp/extractor/khanacademy.py +153 -0
  408. yt_api_dlp/extractor/kick.py +258 -0
  409. yt_api_dlp/extractor/kicker.py +55 -0
  410. yt_api_dlp/extractor/kickstarter.py +68 -0
  411. yt_api_dlp/extractor/kika.py +174 -0
  412. yt_api_dlp/extractor/kinopoisk.py +63 -0
  413. yt_api_dlp/extractor/kommunetv.py +31 -0
  414. yt_api_dlp/extractor/kompas.py +26 -0
  415. yt_api_dlp/extractor/krasview.py +58 -0
  416. yt_api_dlp/extractor/kth.py +27 -0
  417. yt_api_dlp/extractor/ku6.py +30 -0
  418. yt_api_dlp/extractor/kukululive.py +140 -0
  419. yt_api_dlp/extractor/kuwo.py +352 -0
  420. yt_api_dlp/extractor/la7.py +234 -0
  421. yt_api_dlp/extractor/laracasts.py +114 -0
  422. yt_api_dlp/extractor/lastfm.py +129 -0
  423. yt_api_dlp/extractor/laxarxames.py +73 -0
  424. yt_api_dlp/extractor/lbry.py +443 -0
  425. yt_api_dlp/extractor/lci.py +49 -0
  426. yt_api_dlp/extractor/lcp.py +72 -0
  427. yt_api_dlp/extractor/learningonscreen.py +72 -0
  428. yt_api_dlp/extractor/lecture2go.py +67 -0
  429. yt_api_dlp/extractor/lecturio.py +234 -0
  430. yt_api_dlp/extractor/leeco.py +245 -0
  431. yt_api_dlp/extractor/lefigaro.py +136 -0
  432. yt_api_dlp/extractor/lego.py +141 -0
  433. yt_api_dlp/extractor/lemonde.py +56 -0
  434. yt_api_dlp/extractor/lenta.py +51 -0
  435. yt_api_dlp/extractor/libraryofcongress.py +147 -0
  436. yt_api_dlp/extractor/libsyn.py +111 -0
  437. yt_api_dlp/extractor/lifenews.py +231 -0
  438. yt_api_dlp/extractor/likee.py +182 -0
  439. yt_api_dlp/extractor/linkedin.py +353 -0
  440. yt_api_dlp/extractor/liputan6.py +64 -0
  441. yt_api_dlp/extractor/listennotes.py +84 -0
  442. yt_api_dlp/extractor/litv.py +117 -0
  443. yt_api_dlp/extractor/livejournal.py +39 -0
  444. yt_api_dlp/extractor/livestreamfails.py +37 -0
  445. yt_api_dlp/extractor/lnk.py +87 -0
  446. yt_api_dlp/extractor/locipo.py +209 -0
  447. yt_api_dlp/extractor/loco.py +159 -0
  448. yt_api_dlp/extractor/loom.py +484 -0
  449. yt_api_dlp/extractor/lovehomeporn.py +33 -0
  450. yt_api_dlp/extractor/lrt.py +167 -0
  451. yt_api_dlp/extractor/lsm.py +299 -0
  452. yt_api_dlp/extractor/lumni.py +23 -0
  453. yt_api_dlp/extractor/maariv.py +62 -0
  454. yt_api_dlp/extractor/magellantv.py +72 -0
  455. yt_api_dlp/extractor/magentamusik.py +62 -0
  456. yt_api_dlp/extractor/mailru.py +337 -0
  457. yt_api_dlp/extractor/mainstreaming.py +221 -0
  458. yt_api_dlp/extractor/mangomolo.py +72 -0
  459. yt_api_dlp/extractor/manyvids.py +108 -0
  460. yt_api_dlp/extractor/maoritv.py +28 -0
  461. yt_api_dlp/extractor/markiza.py +123 -0
  462. yt_api_dlp/extractor/massengeschmacktv.py +72 -0
  463. yt_api_dlp/extractor/masters.py +37 -0
  464. yt_api_dlp/extractor/matchitv.py +38 -0
  465. yt_api_dlp/extractor/matchtv.py +35 -0
  466. yt_api_dlp/extractor/mave.py +190 -0
  467. yt_api_dlp/extractor/mbn.py +89 -0
  468. yt_api_dlp/extractor/mdr.py +140 -0
  469. yt_api_dlp/extractor/medaltv.py +124 -0
  470. yt_api_dlp/extractor/mediaite.py +104 -0
  471. yt_api_dlp/extractor/mediaklikk.py +113 -0
  472. yt_api_dlp/extractor/medialaan.py +224 -0
  473. yt_api_dlp/extractor/mediaset.py +320 -0
  474. yt_api_dlp/extractor/mediasite.py +414 -0
  475. yt_api_dlp/extractor/mediastream.py +226 -0
  476. yt_api_dlp/extractor/mediaworksnz.py +103 -0
  477. yt_api_dlp/extractor/medici.py +153 -0
  478. yt_api_dlp/extractor/megaphone.py +46 -0
  479. yt_api_dlp/extractor/megatvcom.py +172 -0
  480. yt_api_dlp/extractor/meipai.py +99 -0
  481. yt_api_dlp/extractor/melonvod.py +68 -0
  482. yt_api_dlp/extractor/metacritic.py +62 -0
  483. yt_api_dlp/extractor/mgtv.py +173 -0
  484. yt_api_dlp/extractor/microsoftembed.py +358 -0
  485. yt_api_dlp/extractor/minds.py +192 -0
  486. yt_api_dlp/extractor/mir24tv.py +37 -0
  487. yt_api_dlp/extractor/mirrativ.py +118 -0
  488. yt_api_dlp/extractor/mirrorcouk.py +98 -0
  489. yt_api_dlp/extractor/mit.py +130 -0
  490. yt_api_dlp/extractor/mixch.py +171 -0
  491. yt_api_dlp/extractor/mixcloud.py +369 -0
  492. yt_api_dlp/extractor/mixlr.py +134 -0
  493. yt_api_dlp/extractor/mlb.py +526 -0
  494. yt_api_dlp/extractor/mlssoccer.py +115 -0
  495. yt_api_dlp/extractor/mocha.py +64 -0
  496. yt_api_dlp/extractor/mojevideo.py +121 -0
  497. yt_api_dlp/extractor/monstercat.py +96 -0
  498. yt_api_dlp/extractor/motorsport.py +51 -0
  499. yt_api_dlp/extractor/moviepilot.py +97 -0
  500. yt_api_dlp/extractor/movingimage.py +50 -0
  501. yt_api_dlp/extractor/msn.py +215 -0
  502. yt_api_dlp/extractor/mtv.py +268 -0
  503. yt_api_dlp/extractor/muenchentv.py +72 -0
  504. yt_api_dlp/extractor/murrtube.py +161 -0
  505. yt_api_dlp/extractor/museai.py +112 -0
  506. yt_api_dlp/extractor/musescore.py +72 -0
  507. yt_api_dlp/extractor/mux.py +92 -0
  508. yt_api_dlp/extractor/mx3.py +171 -0
  509. yt_api_dlp/extractor/mxplayer.py +450 -0
  510. yt_api_dlp/extractor/myspace.py +195 -0
  511. yt_api_dlp/extractor/myspass.py +91 -0
  512. yt_api_dlp/extractor/myvideoge.py +81 -0
  513. yt_api_dlp/extractor/myvidster.py +27 -0
  514. yt_api_dlp/extractor/mzaalo.py +95 -0
  515. yt_api_dlp/extractor/n1.py +202 -0
  516. yt_api_dlp/extractor/nascar.py +60 -0
  517. yt_api_dlp/extractor/nate.py +120 -0
  518. yt_api_dlp/extractor/nationalgeographic.py +23 -0
  519. yt_api_dlp/extractor/naver.py +284 -0
  520. yt_api_dlp/extractor/nba.py +423 -0
  521. yt_api_dlp/extractor/nbc.py +1108 -0
  522. yt_api_dlp/extractor/ndr.py +471 -0
  523. yt_api_dlp/extractor/ndtv.py +107 -0
  524. yt_api_dlp/extractor/nebula.py +541 -0
  525. yt_api_dlp/extractor/nekohacker.py +214 -0
  526. yt_api_dlp/extractor/nest.py +117 -0
  527. yt_api_dlp/extractor/netapp.py +79 -0
  528. yt_api_dlp/extractor/neteasemusic.py +671 -0
  529. yt_api_dlp/extractor/netzkino.py +60 -0
  530. yt_api_dlp/extractor/newgrounds.py +311 -0
  531. yt_api_dlp/extractor/newspicks.py +77 -0
  532. yt_api_dlp/extractor/newsy.py +47 -0
  533. yt_api_dlp/extractor/nexx.py +519 -0
  534. yt_api_dlp/extractor/nfb.py +293 -0
  535. yt_api_dlp/extractor/nfhsnetwork.py +135 -0
  536. yt_api_dlp/extractor/nfl.py +396 -0
  537. yt_api_dlp/extractor/nhk.py +920 -0
  538. yt_api_dlp/extractor/nhl.py +123 -0
  539. yt_api_dlp/extractor/nick.py +48 -0
  540. yt_api_dlp/extractor/niconico.py +1082 -0
  541. yt_api_dlp/extractor/niconicochannelplus.py +426 -0
  542. yt_api_dlp/extractor/ninaprotocol.py +225 -0
  543. yt_api_dlp/extractor/ninecninemedia.py +130 -0
  544. yt_api_dlp/extractor/ninegag.py +147 -0
  545. yt_api_dlp/extractor/ninenews.py +72 -0
  546. yt_api_dlp/extractor/ninenow.py +141 -0
  547. yt_api_dlp/extractor/nintendo.py +131 -0
  548. yt_api_dlp/extractor/nitter.py +361 -0
  549. yt_api_dlp/extractor/nobelprize.py +57 -0
  550. yt_api_dlp/extractor/noice.py +116 -0
  551. yt_api_dlp/extractor/nonktube.py +36 -0
  552. yt_api_dlp/extractor/noodlemagazine.py +74 -0
  553. yt_api_dlp/extractor/nosnl.py +115 -0
  554. yt_api_dlp/extractor/nova.py +307 -0
  555. yt_api_dlp/extractor/novaplay.py +67 -0
  556. yt_api_dlp/extractor/nowcanal.py +37 -0
  557. yt_api_dlp/extractor/nowness.py +141 -0
  558. yt_api_dlp/extractor/noz.py +84 -0
  559. yt_api_dlp/extractor/npo.py +612 -0
  560. yt_api_dlp/extractor/npr.py +132 -0
  561. yt_api_dlp/extractor/nrk.py +901 -0
  562. yt_api_dlp/extractor/nrl.py +27 -0
  563. yt_api_dlp/extractor/nts.py +76 -0
  564. yt_api_dlp/extractor/ntvcojp.py +82 -0
  565. yt_api_dlp/extractor/ntvde.py +83 -0
  566. yt_api_dlp/extractor/ntvru.py +179 -0
  567. yt_api_dlp/extractor/nubilesporn.py +98 -0
  568. yt_api_dlp/extractor/nuevo.py +32 -0
  569. yt_api_dlp/extractor/nuvid.py +99 -0
  570. yt_api_dlp/extractor/nytimes.py +437 -0
  571. yt_api_dlp/extractor/nzherald.py +119 -0
  572. yt_api_dlp/extractor/nzonscreen.py +93 -0
  573. yt_api_dlp/extractor/nzz.py +32 -0
  574. yt_api_dlp/extractor/odkmedia.py +105 -0
  575. yt_api_dlp/extractor/odnoklassniki.py +451 -0
  576. yt_api_dlp/extractor/oftv.py +54 -0
  577. yt_api_dlp/extractor/oktoberfesttv.py +44 -0
  578. yt_api_dlp/extractor/olympics.py +151 -0
  579. yt_api_dlp/extractor/on24.py +94 -0
  580. yt_api_dlp/extractor/ondemandkorea.py +169 -0
  581. yt_api_dlp/extractor/onefootball.py +51 -0
  582. yt_api_dlp/extractor/onenewsnz.py +107 -0
  583. yt_api_dlp/extractor/oneplace.py +43 -0
  584. yt_api_dlp/extractor/onet.py +259 -0
  585. yt_api_dlp/extractor/onsen.py +165 -0
  586. yt_api_dlp/extractor/opencast.py +188 -0
  587. yt_api_dlp/extractor/openload.py +243 -0
  588. yt_api_dlp/extractor/openrec.py +153 -0
  589. yt_api_dlp/extractor/orf.py +558 -0
  590. yt_api_dlp/extractor/outsidetv.py +25 -0
  591. yt_api_dlp/extractor/owncloud.py +80 -0
  592. yt_api_dlp/extractor/packtpub.py +153 -0
  593. yt_api_dlp/extractor/palcomp3.py +142 -0
  594. yt_api_dlp/extractor/pandatv.py +83 -0
  595. yt_api_dlp/extractor/panopto.py +598 -0
  596. yt_api_dlp/extractor/parler.py +89 -0
  597. yt_api_dlp/extractor/parlview.py +63 -0
  598. yt_api_dlp/extractor/parti.py +95 -0
  599. yt_api_dlp/extractor/patreon.py +748 -0
  600. yt_api_dlp/extractor/pbs.py +814 -0
  601. yt_api_dlp/extractor/pearvideo.py +68 -0
  602. yt_api_dlp/extractor/peekvids.py +188 -0
  603. yt_api_dlp/extractor/peertube.py +1772 -0
  604. yt_api_dlp/extractor/peertv.py +52 -0
  605. yt_api_dlp/extractor/peloton.py +215 -0
  606. yt_api_dlp/extractor/performgroup.py +74 -0
  607. yt_api_dlp/extractor/periscope.py +181 -0
  608. yt_api_dlp/extractor/pgatour.py +47 -0
  609. yt_api_dlp/extractor/philharmoniedeparis.py +96 -0
  610. yt_api_dlp/extractor/phoenix.py +98 -0
  611. yt_api_dlp/extractor/photobucket.py +43 -0
  612. yt_api_dlp/extractor/pialive.py +122 -0
  613. yt_api_dlp/extractor/piapro.py +112 -0
  614. yt_api_dlp/extractor/picarto.py +168 -0
  615. yt_api_dlp/extractor/piksel.py +177 -0
  616. yt_api_dlp/extractor/pinkbike.py +93 -0
  617. yt_api_dlp/extractor/pinterest.py +266 -0
  618. yt_api_dlp/extractor/platzi.py +211 -0
  619. yt_api_dlp/extractor/playerfm.py +70 -0
  620. yt_api_dlp/extractor/playsuisse.py +292 -0
  621. yt_api_dlp/extractor/playtvak.py +183 -0
  622. yt_api_dlp/extractor/pluralsight.py +484 -0
  623. yt_api_dlp/extractor/plutotv.py +192 -0
  624. yt_api_dlp/extractor/plyr.py +104 -0
  625. yt_api_dlp/extractor/podbayfm.py +88 -0
  626. yt_api_dlp/extractor/podchaser.py +114 -0
  627. yt_api_dlp/extractor/podomatic.py +73 -0
  628. yt_api_dlp/extractor/pokergo.py +109 -0
  629. yt_api_dlp/extractor/polsatgo.py +86 -0
  630. yt_api_dlp/extractor/polskieradio.py +609 -0
  631. yt_api_dlp/extractor/popcorntimes.py +92 -0
  632. yt_api_dlp/extractor/popcorntv.py +72 -0
  633. yt_api_dlp/extractor/pornbox.py +113 -0
  634. yt_api_dlp/extractor/pornflip.py +73 -0
  635. yt_api_dlp/extractor/pornhub.py +835 -0
  636. yt_api_dlp/extractor/pornotube.py +82 -0
  637. yt_api_dlp/extractor/pornovoisines.py +103 -0
  638. yt_api_dlp/extractor/pornoxo.py +55 -0
  639. yt_api_dlp/extractor/pr0gramm.py +203 -0
  640. yt_api_dlp/extractor/prankcast.py +168 -0
  641. yt_api_dlp/extractor/premiershiprugby.py +39 -0
  642. yt_api_dlp/extractor/presstv.py +69 -0
  643. yt_api_dlp/extractor/projectveritas.py +52 -0
  644. yt_api_dlp/extractor/prx.py +429 -0
  645. yt_api_dlp/extractor/puhutv.py +232 -0
  646. yt_api_dlp/extractor/pyvideo.py +69 -0
  647. yt_api_dlp/extractor/qdance.py +171 -0
  648. yt_api_dlp/extractor/qingting.py +46 -0
  649. yt_api_dlp/extractor/qqmusic.py +492 -0
  650. yt_api_dlp/extractor/r7.py +112 -0
  651. yt_api_dlp/extractor/radiko.py +263 -0
  652. yt_api_dlp/extractor/radiocanada.py +165 -0
  653. yt_api_dlp/extractor/radiode.py +50 -0
  654. yt_api_dlp/extractor/radiofrance.py +473 -0
  655. yt_api_dlp/extractor/radiojavan.py +81 -0
  656. yt_api_dlp/extractor/radiokapital.py +93 -0
  657. yt_api_dlp/extractor/radioradicale.py +105 -0
  658. yt_api_dlp/extractor/radiozet.py +50 -0
  659. yt_api_dlp/extractor/radlive.py +180 -0
  660. yt_api_dlp/extractor/rai.py +861 -0
  661. yt_api_dlp/extractor/raywenderlich.py +175 -0
  662. yt_api_dlp/extractor/rbgtum.py +142 -0
  663. yt_api_dlp/extractor/rcs.py +372 -0
  664. yt_api_dlp/extractor/rcti.py +379 -0
  665. yt_api_dlp/extractor/rds.py +67 -0
  666. yt_api_dlp/extractor/redbee.py +380 -0
  667. yt_api_dlp/extractor/redbulltv.py +223 -0
  668. yt_api_dlp/extractor/reddit.py +459 -0
  669. yt_api_dlp/extractor/redgifs.py +286 -0
  670. yt_api_dlp/extractor/redtube.py +144 -0
  671. yt_api_dlp/extractor/rentv.py +103 -0
  672. yt_api_dlp/extractor/restudy.py +41 -0
  673. yt_api_dlp/extractor/reuters.py +66 -0
  674. yt_api_dlp/extractor/reverbnation.py +51 -0
  675. yt_api_dlp/extractor/ridehome.py +96 -0
  676. yt_api_dlp/extractor/rinsefm.py +96 -0
  677. yt_api_dlp/extractor/rockstargames.py +65 -0
  678. yt_api_dlp/extractor/rokfin.py +455 -0
  679. yt_api_dlp/extractor/roosterteeth.py +352 -0
  680. yt_api_dlp/extractor/rottentomatoes.py +80 -0
  681. yt_api_dlp/extractor/roya.py +43 -0
  682. yt_api_dlp/extractor/rozhlas.py +363 -0
  683. yt_api_dlp/extractor/rte.py +162 -0
  684. yt_api_dlp/extractor/rtl2.py +95 -0
  685. yt_api_dlp/extractor/rtlnl.py +294 -0
  686. yt_api_dlp/extractor/rtnews.py +196 -0
  687. yt_api_dlp/extractor/rtp.py +332 -0
  688. yt_api_dlp/extractor/rtrfm.py +65 -0
  689. yt_api_dlp/extractor/rts.py +231 -0
  690. yt_api_dlp/extractor/rtvcplay.py +286 -0
  691. yt_api_dlp/extractor/rtve.py +434 -0
  692. yt_api_dlp/extractor/rtvs.py +89 -0
  693. yt_api_dlp/extractor/rtvslo.py +195 -0
  694. yt_api_dlp/extractor/rudovideo.py +135 -0
  695. yt_api_dlp/extractor/rule34video.py +123 -0
  696. yt_api_dlp/extractor/rumble.py +412 -0
  697. yt_api_dlp/extractor/rutube.py +468 -0
  698. yt_api_dlp/extractor/ruutu.py +262 -0
  699. yt_api_dlp/extractor/ruv.py +186 -0
  700. yt_api_dlp/extractor/s4c.py +134 -0
  701. yt_api_dlp/extractor/safari.py +255 -0
  702. yt_api_dlp/extractor/saitosan.py +75 -0
  703. yt_api_dlp/extractor/samplefocus.py +105 -0
  704. yt_api_dlp/extractor/sapo.py +114 -0
  705. yt_api_dlp/extractor/sauceplus.py +57 -0
  706. yt_api_dlp/extractor/sbs.py +165 -0
  707. yt_api_dlp/extractor/sbscokr.py +200 -0
  708. yt_api_dlp/extractor/screen9.py +62 -0
  709. yt_api_dlp/extractor/screencast.py +116 -0
  710. yt_api_dlp/extractor/screencastify.py +70 -0
  711. yt_api_dlp/extractor/screencastomatic.py +72 -0
  712. yt_api_dlp/extractor/screenrec.py +33 -0
  713. yt_api_dlp/extractor/scrippsnetworks.py +155 -0
  714. yt_api_dlp/extractor/scrolller.py +102 -0
  715. yt_api_dlp/extractor/sejmpl.py +218 -0
  716. yt_api_dlp/extractor/sen.py +36 -0
  717. yt_api_dlp/extractor/senalcolombia.py +32 -0
  718. yt_api_dlp/extractor/senategov.py +246 -0
  719. yt_api_dlp/extractor/servus.py +142 -0
  720. yt_api_dlp/extractor/sevenplus.py +131 -0
  721. yt_api_dlp/extractor/sexu.py +61 -0
  722. yt_api_dlp/extractor/seznamzpravy.py +155 -0
  723. yt_api_dlp/extractor/shahid.py +217 -0
  724. yt_api_dlp/extractor/sharepoint.py +112 -0
  725. yt_api_dlp/extractor/shemaroome.py +99 -0
  726. yt_api_dlp/extractor/shiey.py +34 -0
  727. yt_api_dlp/extractor/showroomlive.py +79 -0
  728. yt_api_dlp/extractor/sibnet.py +17 -0
  729. yt_api_dlp/extractor/simplecast.py +175 -0
  730. yt_api_dlp/extractor/sina.py +108 -0
  731. yt_api_dlp/extractor/skeb.py +132 -0
  732. yt_api_dlp/extractor/sky.py +135 -0
  733. yt_api_dlp/extractor/skyit.py +321 -0
  734. yt_api_dlp/extractor/skylinewebcams.py +40 -0
  735. yt_api_dlp/extractor/skynewsarabia.py +115 -0
  736. yt_api_dlp/extractor/skynewsau.py +43 -0
  737. yt_api_dlp/extractor/slideshare.py +51 -0
  738. yt_api_dlp/extractor/slideslive.py +536 -0
  739. yt_api_dlp/extractor/slutload.py +63 -0
  740. yt_api_dlp/extractor/smotrim.py +403 -0
  741. yt_api_dlp/extractor/snapchat.py +76 -0
  742. yt_api_dlp/extractor/softwhiteunderbelly.py +87 -0
  743. yt_api_dlp/extractor/sohu.py +289 -0
  744. yt_api_dlp/extractor/sonyliv.py +250 -0
  745. yt_api_dlp/extractor/soundcloud.py +1360 -0
  746. yt_api_dlp/extractor/soundgasm.py +74 -0
  747. yt_api_dlp/extractor/southpark.py +354 -0
  748. yt_api_dlp/extractor/sovietscloset.py +189 -0
  749. yt_api_dlp/extractor/spankbang.py +198 -0
  750. yt_api_dlp/extractor/spiegel.py +51 -0
  751. yt_api_dlp/extractor/sport5.py +86 -0
  752. yt_api_dlp/extractor/sportbox.py +98 -0
  753. yt_api_dlp/extractor/sportdeutschland.py +164 -0
  754. yt_api_dlp/extractor/spreaker.py +179 -0
  755. yt_api_dlp/extractor/sproutvideo.py +206 -0
  756. yt_api_dlp/extractor/srgssr.py +246 -0
  757. yt_api_dlp/extractor/srmediathek.py +102 -0
  758. yt_api_dlp/extractor/stacommu.py +251 -0
  759. yt_api_dlp/extractor/stageplus.py +515 -0
  760. yt_api_dlp/extractor/startrek.py +76 -0
  761. yt_api_dlp/extractor/startv.py +97 -0
  762. yt_api_dlp/extractor/steam.py +214 -0
  763. yt_api_dlp/extractor/storyfire.py +133 -0
  764. yt_api_dlp/extractor/streaks.py +244 -0
  765. yt_api_dlp/extractor/streamable.py +103 -0
  766. yt_api_dlp/extractor/streamcz.py +122 -0
  767. yt_api_dlp/extractor/streetvoice.py +97 -0
  768. yt_api_dlp/extractor/stripchat.py +63 -0
  769. yt_api_dlp/extractor/stv.py +88 -0
  770. yt_api_dlp/extractor/subsplash.py +199 -0
  771. yt_api_dlp/extractor/substack.py +158 -0
  772. yt_api_dlp/extractor/sunporno.py +75 -0
  773. yt_api_dlp/extractor/sverigesradio.py +149 -0
  774. yt_api_dlp/extractor/svt.py +463 -0
  775. yt_api_dlp/extractor/sztvhu.py +38 -0
  776. yt_api_dlp/extractor/tagesschau.py +164 -0
  777. yt_api_dlp/extractor/taptap.py +275 -0
  778. yt_api_dlp/extractor/tarangplus.py +244 -0
  779. yt_api_dlp/extractor/tass.py +59 -0
  780. yt_api_dlp/extractor/tbs.py +161 -0
  781. yt_api_dlp/extractor/tbsjp.py +153 -0
  782. yt_api_dlp/extractor/teachable.py +295 -0
  783. yt_api_dlp/extractor/teachertube.py +126 -0
  784. yt_api_dlp/extractor/teachingchannel.py +32 -0
  785. yt_api_dlp/extractor/teamcoco.py +281 -0
  786. yt_api_dlp/extractor/teamtreehouse.py +134 -0
  787. yt_api_dlp/extractor/ted.py +251 -0
  788. yt_api_dlp/extractor/tele13.py +84 -0
  789. yt_api_dlp/extractor/tele5.py +84 -0
  790. yt_api_dlp/extractor/telebruxelles.py +72 -0
  791. yt_api_dlp/extractor/telecaribe.py +91 -0
  792. yt_api_dlp/extractor/telecinco.py +182 -0
  793. yt_api_dlp/extractor/telegraaf.py +86 -0
  794. yt_api_dlp/extractor/telegram.py +136 -0
  795. yt_api_dlp/extractor/telemb.py +75 -0
  796. yt_api_dlp/extractor/telemundo.py +50 -0
  797. yt_api_dlp/extractor/telequebec.py +236 -0
  798. yt_api_dlp/extractor/teletask.py +52 -0
  799. yt_api_dlp/extractor/telewebion.py +133 -0
  800. yt_api_dlp/extractor/tencent.py +489 -0
  801. yt_api_dlp/extractor/tennistv.py +155 -0
  802. yt_api_dlp/extractor/tenplay.py +336 -0
  803. yt_api_dlp/extractor/testurl.py +50 -0
  804. yt_api_dlp/extractor/tf1.py +101 -0
  805. yt_api_dlp/extractor/tfo.py +49 -0
  806. yt_api_dlp/extractor/thechosen.py +118 -0
  807. yt_api_dlp/extractor/theguardian.py +134 -0
  808. yt_api_dlp/extractor/thehighwire.py +43 -0
  809. yt_api_dlp/extractor/theintercept.py +45 -0
  810. yt_api_dlp/extractor/theplatform.py +409 -0
  811. yt_api_dlp/extractor/thestar.py +33 -0
  812. yt_api_dlp/extractor/thesun.py +43 -0
  813. yt_api_dlp/extractor/theweatherchannel.py +99 -0
  814. yt_api_dlp/extractor/thisamericanlife.py +38 -0
  815. yt_api_dlp/extractor/thisoldhouse.py +153 -0
  816. yt_api_dlp/extractor/thisvid.py +226 -0
  817. yt_api_dlp/extractor/threeqsdn.py +156 -0
  818. yt_api_dlp/extractor/threespeak.py +93 -0
  819. yt_api_dlp/extractor/tiktok.py +1728 -0
  820. yt_api_dlp/extractor/tmz.py +191 -0
  821. yt_api_dlp/extractor/tnaflix.py +335 -0
  822. yt_api_dlp/extractor/toggle.py +204 -0
  823. yt_api_dlp/extractor/toggo.py +82 -0
  824. yt_api_dlp/extractor/tonline.py +53 -0
  825. yt_api_dlp/extractor/toongoggles.py +76 -0
  826. yt_api_dlp/extractor/toutiao.py +121 -0
  827. yt_api_dlp/extractor/toutv.py +87 -0
  828. yt_api_dlp/extractor/toypics.py +90 -0
  829. yt_api_dlp/extractor/trtcocuk.py +48 -0
  830. yt_api_dlp/extractor/trtworld.py +101 -0
  831. yt_api_dlp/extractor/trueid.py +136 -0
  832. yt_api_dlp/extractor/trunews.py +32 -0
  833. yt_api_dlp/extractor/truth.py +74 -0
  834. yt_api_dlp/extractor/tube8.py +170 -0
  835. yt_api_dlp/extractor/tubetugraz.py +263 -0
  836. yt_api_dlp/extractor/tubitv.py +206 -0
  837. yt_api_dlp/extractor/tumblr.py +574 -0
  838. yt_api_dlp/extractor/tunein.py +335 -0
  839. yt_api_dlp/extractor/turner.py +263 -0
  840. yt_api_dlp/extractor/tv2.py +324 -0
  841. yt_api_dlp/extractor/tv24ua.py +78 -0
  842. yt_api_dlp/extractor/tv2dk.py +166 -0
  843. yt_api_dlp/extractor/tv2hu.py +103 -0
  844. yt_api_dlp/extractor/tv4.py +149 -0
  845. yt_api_dlp/extractor/tv5mondeplus.py +178 -0
  846. yt_api_dlp/extractor/tv5unis.py +162 -0
  847. yt_api_dlp/extractor/tva.py +76 -0
  848. yt_api_dlp/extractor/tvanouvelles.py +62 -0
  849. yt_api_dlp/extractor/tvc.py +109 -0
  850. yt_api_dlp/extractor/tver.py +372 -0
  851. yt_api_dlp/extractor/tvigle.py +133 -0
  852. yt_api_dlp/extractor/tviplayer.py +72 -0
  853. yt_api_dlp/extractor/tvn24.py +100 -0
  854. yt_api_dlp/extractor/tvnoe.py +82 -0
  855. yt_api_dlp/extractor/tvo.py +152 -0
  856. yt_api_dlp/extractor/tvopengr.py +130 -0
  857. yt_api_dlp/extractor/tvp.py +644 -0
  858. yt_api_dlp/extractor/tvplay.py +306 -0
  859. yt_api_dlp/extractor/tvw.py +217 -0
  860. yt_api_dlp/extractor/tweakers.py +59 -0
  861. yt_api_dlp/extractor/twentymin.py +91 -0
  862. yt_api_dlp/extractor/twentythreevideo.py +76 -0
  863. yt_api_dlp/extractor/twitcasting.py +321 -0
  864. yt_api_dlp/extractor/twitch.py +1289 -0
  865. yt_api_dlp/extractor/twitter.py +1767 -0
  866. yt_api_dlp/extractor/txxx.py +422 -0
  867. yt_api_dlp/extractor/udemy.py +472 -0
  868. yt_api_dlp/extractor/udn.py +106 -0
  869. yt_api_dlp/extractor/ufctv.py +7 -0
  870. yt_api_dlp/extractor/ukcolumn.py +71 -0
  871. yt_api_dlp/extractor/uliza.py +113 -0
  872. yt_api_dlp/extractor/umg.py +53 -0
  873. yt_api_dlp/extractor/unistra.py +64 -0
  874. yt_api_dlp/extractor/unitednations.py +32 -0
  875. yt_api_dlp/extractor/unity.py +31 -0
  876. yt_api_dlp/extractor/unsupported.py +353 -0
  877. yt_api_dlp/extractor/uol.py +136 -0
  878. yt_api_dlp/extractor/uplynk.py +88 -0
  879. yt_api_dlp/extractor/urort.py +60 -0
  880. yt_api_dlp/extractor/urplay.py +179 -0
  881. yt_api_dlp/extractor/usanetwork.py +21 -0
  882. yt_api_dlp/extractor/usatoday.py +59 -0
  883. yt_api_dlp/extractor/ustream.py +272 -0
  884. yt_api_dlp/extractor/ustudio.py +119 -0
  885. yt_api_dlp/extractor/varzesh3.py +73 -0
  886. yt_api_dlp/extractor/vbox7.py +112 -0
  887. yt_api_dlp/extractor/veo.py +75 -0
  888. yt_api_dlp/extractor/vevo.py +352 -0
  889. yt_api_dlp/extractor/vgtv.py +310 -0
  890. yt_api_dlp/extractor/vh1.py +50 -0
  891. yt_api_dlp/extractor/vice.py +315 -0
  892. yt_api_dlp/extractor/viddler.py +147 -0
  893. yt_api_dlp/extractor/videa.py +208 -0
  894. yt_api_dlp/extractor/videocampus_sachsen.py +274 -0
  895. yt_api_dlp/extractor/videoken.py +46 -0
  896. yt_api_dlp/extractor/videopress.py +104 -0
  897. yt_api_dlp/extractor/vidflex.py +148 -0
  898. yt_api_dlp/extractor/vidio.py +309 -0
  899. yt_api_dlp/extractor/vidlii.py +154 -0
  900. yt_api_dlp/extractor/vidly.py +83 -0
  901. yt_api_dlp/extractor/vidyard.py +438 -0
  902. yt_api_dlp/extractor/viewlift.py +374 -0
  903. yt_api_dlp/extractor/viidea.py +196 -0
  904. yt_api_dlp/extractor/vimeo.py +2327 -0
  905. yt_api_dlp/extractor/viously.py +60 -0
  906. yt_api_dlp/extractor/viqeo.py +100 -0
  907. yt_api_dlp/extractor/visir.py +116 -0
  908. yt_api_dlp/extractor/viu.py +541 -0
  909. yt_api_dlp/extractor/vk.py +963 -0
  910. yt_api_dlp/extractor/vocaroo.py +63 -0
  911. yt_api_dlp/extractor/vodplatform.py +37 -0
  912. yt_api_dlp/extractor/voicy.py +145 -0
  913. yt_api_dlp/extractor/volejtv.py +167 -0
  914. yt_api_dlp/extractor/voxmedia.py +212 -0
  915. yt_api_dlp/extractor/vrsquare.py +185 -0
  916. yt_api_dlp/extractor/vrt.py +562 -0
  917. yt_api_dlp/extractor/vtm.py +42 -0
  918. yt_api_dlp/extractor/vtv.py +108 -0
  919. yt_api_dlp/extractor/walla.py +82 -0
  920. yt_api_dlp/extractor/washingtonpost.py +122 -0
  921. yt_api_dlp/extractor/wat.py +126 -0
  922. yt_api_dlp/extractor/wdr.py +349 -0
  923. yt_api_dlp/extractor/webcamerapl.py +44 -0
  924. yt_api_dlp/extractor/webcaster.py +92 -0
  925. yt_api_dlp/extractor/webofstories.py +151 -0
  926. yt_api_dlp/extractor/weibo.py +370 -0
  927. yt_api_dlp/extractor/weiqitv.py +50 -0
  928. yt_api_dlp/extractor/weverse.py +769 -0
  929. yt_api_dlp/extractor/wevidi.py +108 -0
  930. yt_api_dlp/extractor/whowatch.py +95 -0
  931. yt_api_dlp/extractor/whyp.py +60 -0
  932. yt_api_dlp/extractor/wikimedia.py +133 -0
  933. yt_api_dlp/extractor/wimbledon.py +61 -0
  934. yt_api_dlp/extractor/wimtv.py +157 -0
  935. yt_api_dlp/extractor/wistia.py +423 -0
  936. yt_api_dlp/extractor/wordpress.py +154 -0
  937. yt_api_dlp/extractor/worldstarhiphop.py +38 -0
  938. yt_api_dlp/extractor/wppilot.py +173 -0
  939. yt_api_dlp/extractor/wrestleuniverse.py +312 -0
  940. yt_api_dlp/extractor/wsj.py +130 -0
  941. yt_api_dlp/extractor/wwe.py +137 -0
  942. yt_api_dlp/extractor/wykop.py +268 -0
  943. yt_api_dlp/extractor/xboxclips.py +62 -0
  944. yt_api_dlp/extractor/xhamster.py +638 -0
  945. yt_api_dlp/extractor/xiaohongshu.py +109 -0
  946. yt_api_dlp/extractor/ximalaya.py +246 -0
  947. yt_api_dlp/extractor/xinpianchang.py +90 -0
  948. yt_api_dlp/extractor/xminus.py +77 -0
  949. yt_api_dlp/extractor/xnxx.py +83 -0
  950. yt_api_dlp/extractor/xvideos.py +225 -0
  951. yt_api_dlp/extractor/xxxymovies.py +77 -0
  952. yt_api_dlp/extractor/yahoo.py +369 -0
  953. yt_api_dlp/extractor/yandexdisk.py +143 -0
  954. yt_api_dlp/extractor/yandexmusic.py +453 -0
  955. yt_api_dlp/extractor/yandexvideo.py +413 -0
  956. yt_api_dlp/extractor/yapfiles.py +99 -0
  957. yt_api_dlp/extractor/yappy.py +128 -0
  958. yt_api_dlp/extractor/yfanefa.py +67 -0
  959. yt_api_dlp/extractor/yle_areena.py +182 -0
  960. yt_api_dlp/extractor/youjizz.py +90 -0
  961. yt_api_dlp/extractor/youku.py +290 -0
  962. yt_api_dlp/extractor/younow.py +194 -0
  963. yt_api_dlp/extractor/youporn.py +567 -0
  964. yt_api_dlp/extractor/youtube/__init__.py +49 -0
  965. yt_api_dlp/extractor/youtube/_base.py +1314 -0
  966. yt_api_dlp/extractor/youtube/_clip.py +68 -0
  967. yt_api_dlp/extractor/youtube/_mistakes.py +69 -0
  968. yt_api_dlp/extractor/youtube/_notifications.py +98 -0
  969. yt_api_dlp/extractor/youtube/_redirect.py +248 -0
  970. yt_api_dlp/extractor/youtube/_search.py +152 -0
  971. yt_api_dlp/extractor/youtube/_tab.py +2511 -0
  972. yt_api_dlp/extractor/youtube/_video.py +4592 -0
  973. yt_api_dlp/extractor/youtube/jsc/__init__.py +5 -0
  974. yt_api_dlp/extractor/youtube/jsc/_builtin/__init__.py +0 -0
  975. yt_api_dlp/extractor/youtube/jsc/_builtin/bun.py +165 -0
  976. yt_api_dlp/extractor/youtube/jsc/_builtin/deno.py +131 -0
  977. yt_api_dlp/extractor/youtube/jsc/_builtin/ejs.py +328 -0
  978. yt_api_dlp/extractor/youtube/jsc/_builtin/node.py +70 -0
  979. yt_api_dlp/extractor/youtube/jsc/_builtin/quickjs.py +67 -0
  980. yt_api_dlp/extractor/youtube/jsc/_builtin/vendor/__init__.py +17 -0
  981. yt_api_dlp/extractor/youtube/jsc/_builtin/vendor/_info.py +11 -0
  982. yt_api_dlp/extractor/youtube/jsc/_director.py +287 -0
  983. yt_api_dlp/extractor/youtube/jsc/_registry.py +4 -0
  984. yt_api_dlp/extractor/youtube/jsc/provider.py +161 -0
  985. yt_api_dlp/extractor/youtube/pot/__init__.py +3 -0
  986. yt_api_dlp/extractor/youtube/pot/_builtin/__init__.py +0 -0
  987. yt_api_dlp/extractor/youtube/pot/_builtin/memory_cache.py +78 -0
  988. yt_api_dlp/extractor/youtube/pot/_builtin/webpo_cachespec.py +48 -0
  989. yt_api_dlp/extractor/youtube/pot/_director.py +478 -0
  990. yt_api_dlp/extractor/youtube/pot/_provider.py +167 -0
  991. yt_api_dlp/extractor/youtube/pot/_registry.py +8 -0
  992. yt_api_dlp/extractor/youtube/pot/cache.py +97 -0
  993. yt_api_dlp/extractor/youtube/pot/provider.py +283 -0
  994. yt_api_dlp/extractor/youtube/pot/utils.py +77 -0
  995. yt_api_dlp/extractor/zaiko.py +145 -0
  996. yt_api_dlp/extractor/zapiks.py +205 -0
  997. yt_api_dlp/extractor/zattoo.py +862 -0
  998. yt_api_dlp/extractor/zdf.py +794 -0
  999. yt_api_dlp/extractor/zeenews.py +59 -0
  1000. yt_api_dlp/extractor/zenporn.py +118 -0
  1001. yt_api_dlp/extractor/zetland.py +71 -0
  1002. yt_api_dlp/extractor/zhihu.py +65 -0
  1003. yt_api_dlp/extractor/zingmp3.py +628 -0
  1004. yt_api_dlp/extractor/zoom.py +211 -0
  1005. yt_api_dlp/extractor/zype.py +135 -0
  1006. yt_api_dlp/globals.py +41 -0
  1007. yt_api_dlp/jsinterp.py +971 -0
  1008. yt_api_dlp/minicurses.py +182 -0
  1009. yt_api_dlp/networking/__init__.py +38 -0
  1010. yt_api_dlp/networking/_curlcffi.py +346 -0
  1011. yt_api_dlp/networking/_helper.py +273 -0
  1012. yt_api_dlp/networking/_requests.py +418 -0
  1013. yt_api_dlp/networking/_urllib.py +445 -0
  1014. yt_api_dlp/networking/_websockets.py +189 -0
  1015. yt_api_dlp/networking/common.py +608 -0
  1016. yt_api_dlp/networking/exceptions.py +103 -0
  1017. yt_api_dlp/networking/impersonate.py +155 -0
  1018. yt_api_dlp/networking/websocket.py +23 -0
  1019. yt_api_dlp/options.py +2012 -0
  1020. yt_api_dlp/plugins.py +247 -0
  1021. yt_api_dlp/postprocessor/__init__.py +69 -0
  1022. yt_api_dlp/postprocessor/common.py +215 -0
  1023. yt_api_dlp/postprocessor/embedthumbnail.py +233 -0
  1024. yt_api_dlp/postprocessor/exec.py +49 -0
  1025. yt_api_dlp/postprocessor/ffmpeg.py +1182 -0
  1026. yt_api_dlp/postprocessor/metadataparser.py +128 -0
  1027. yt_api_dlp/postprocessor/modify_chapters.py +336 -0
  1028. yt_api_dlp/postprocessor/movefilesafterdownload.py +53 -0
  1029. yt_api_dlp/postprocessor/sponsorblock.py +105 -0
  1030. yt_api_dlp/postprocessor/xattrpp.py +79 -0
  1031. yt_api_dlp/socks.py +274 -0
  1032. yt_api_dlp/update.py +634 -0
  1033. yt_api_dlp/utils/__init__.py +10 -0
  1034. yt_api_dlp/utils/_deprecated.py +61 -0
  1035. yt_api_dlp/utils/_jsruntime.py +153 -0
  1036. yt_api_dlp/utils/_legacy.py +269 -0
  1037. yt_api_dlp/utils/_utils.py +5742 -0
  1038. yt_api_dlp/utils/jslib/__init__.py +1 -0
  1039. yt_api_dlp/utils/jslib/devalue.py +167 -0
  1040. yt_api_dlp/utils/networking.py +256 -0
  1041. yt_api_dlp/utils/progress.py +109 -0
  1042. yt_api_dlp/utils/traversal.py +477 -0
  1043. yt_api_dlp/version.py +15 -0
  1044. yt_api_dlp/webvtt.py +398 -0
  1045. yt_api_dlp-0.1.0.dist-info/METADATA +6 -0
  1046. yt_api_dlp-0.1.0.dist-info/RECORD +1048 -0
  1047. yt_api_dlp-0.1.0.dist-info/WHEEL +5 -0
  1048. yt_api_dlp-0.1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,4548 @@
1
+ import collections
2
+ import contextlib
3
+ import copy
4
+ import datetime as dt
5
+ import errno
6
+ import fileinput
7
+ import functools
8
+ import http.cookiejar
9
+ import io
10
+ import itertools
11
+ import json
12
+ import locale
13
+ import operator
14
+ import os
15
+ import random
16
+ import re
17
+ import shutil
18
+ import string
19
+ import subprocess
20
+ import sys
21
+ import tempfile
22
+ import time
23
+ import tokenize
24
+ import traceback
25
+ import unicodedata
26
+
27
+ from .cache import Cache
28
+ from .compat import urllib # isort: split
29
+ from .compat import urllib_req_to_req
30
+ from .cookies import CookieLoadError, LenientSimpleCookie, load_cookies
31
+ from .downloader import FFmpegFD, get_suitable_downloader, shorten_protocol_name
32
+ from .downloader.rtmp import rtmpdump_version
33
+ from .extractor import gen_extractor_classes, get_info_extractor, import_extractors
34
+ from .extractor.common import UnsupportedURLIE
35
+ from .extractor.openload import PhantomJSwrapper
36
+ from .globals import (
37
+ IN_CLI,
38
+ LAZY_EXTRACTORS,
39
+ WINDOWS_VT_MODE,
40
+ plugin_ies,
41
+ plugin_ies_overrides,
42
+ plugin_pps,
43
+ all_plugins_loaded,
44
+ plugin_dirs,
45
+ supported_js_runtimes,
46
+ supported_remote_components,
47
+ )
48
+ from .minicurses import format_text
49
+ from .networking import HEADRequest, Request, RequestDirector
50
+ from .networking.common import _REQUEST_HANDLERS, _RH_PREFERENCES
51
+ from .networking.exceptions import (
52
+ HTTPError,
53
+ NoSupportingHandlers,
54
+ RequestError,
55
+ SSLError,
56
+ network_exceptions,
57
+ )
58
+ from .networking.impersonate import ImpersonateRequestHandler, ImpersonateTarget
59
+ from .plugins import directories as plugin_directories, load_all_plugins
60
+ from .postprocessor import (
61
+ EmbedThumbnailPP,
62
+ FFmpegFixupDuplicateMoovPP,
63
+ FFmpegFixupDurationPP,
64
+ FFmpegFixupM3u8PP,
65
+ FFmpegFixupM4aPP,
66
+ FFmpegFixupStretchedPP,
67
+ FFmpegFixupTimestampPP,
68
+ FFmpegMergerPP,
69
+ FFmpegPostProcessor,
70
+ FFmpegVideoConvertorPP,
71
+ MoveFilesAfterDownloadPP,
72
+ get_postprocessor,
73
+ )
74
+ from .postprocessor.ffmpeg import resolve_mapping as resolve_recode_mapping
75
+ from .update import (
76
+ REPOSITORY,
77
+ _get_system_deprecation,
78
+ _get_outdated_warning,
79
+ _make_label,
80
+ current_git_head,
81
+ detect_variant,
82
+ )
83
+ from .utils import (
84
+ DEFAULT_OUTTMPL,
85
+ IDENTITY,
86
+ LINK_TEMPLATES,
87
+ MEDIA_EXTENSIONS,
88
+ NO_DEFAULT,
89
+ NUMBER_RE,
90
+ OUTTMPL_TYPES,
91
+ POSTPROCESS_WHEN,
92
+ STR_FORMAT_RE_TMPL,
93
+ STR_FORMAT_TYPES,
94
+ ContentTooShortError,
95
+ DateRange,
96
+ DownloadCancelled,
97
+ DownloadError,
98
+ EntryNotInPlaylist,
99
+ ExistingVideoReached,
100
+ ExtractorError,
101
+ FormatSorter,
102
+ GeoRestrictedError,
103
+ ISO3166Utils,
104
+ LazyList,
105
+ MaxDownloadsReached,
106
+ Namespace,
107
+ PagedList,
108
+ PlaylistEntries,
109
+ Popen,
110
+ PostProcessingError,
111
+ ReExtractInfo,
112
+ RejectedVideoReached,
113
+ SameFileError,
114
+ UnavailableVideoError,
115
+ UnsafeExecExpansionError,
116
+ UserNotLive,
117
+ YoutubeDLError,
118
+ age_restricted,
119
+ bug_reports_message,
120
+ date_from_str,
121
+ deprecation_warning,
122
+ determine_ext,
123
+ determine_protocol,
124
+ encode_compat_str,
125
+ escapeHTML,
126
+ expand_path,
127
+ extract_basic_auth,
128
+ filter_dict,
129
+ float_or_none,
130
+ format_bytes,
131
+ format_decimal_suffix,
132
+ format_field,
133
+ formatSeconds,
134
+ get_compatible_ext,
135
+ get_domain,
136
+ int_or_none,
137
+ iri_to_uri,
138
+ is_path_like,
139
+ join_nonempty,
140
+ locked_file,
141
+ make_archive_id,
142
+ make_parent_dirs,
143
+ number_of_digits,
144
+ orderedSet,
145
+ orderedSet_from_options,
146
+ parse_filesize,
147
+ preferredencoding,
148
+ prepend_extension,
149
+ remove_terminal_sequences,
150
+ render_table,
151
+ replace_extension,
152
+ sanitize_filename,
153
+ sanitize_path,
154
+ sanitize_url,
155
+ shell_quote,
156
+ str_or_none,
157
+ strftime_or_none,
158
+ subtitles_filename,
159
+ supports_terminal_sequences,
160
+ system_identifier,
161
+ filesize_from_tbr,
162
+ timetuple_from_msec,
163
+ to_high_limit_path,
164
+ traverse_obj,
165
+ try_call,
166
+ try_get,
167
+ url_basename,
168
+ variadic,
169
+ windows_enable_vt_mode,
170
+ write_json_file,
171
+ write_string,
172
+ )
173
+ from .utils._utils import _UnsafeExtensionError, _YDLLogger, _ProgressState
174
+ from .utils.networking import (
175
+ HTTPHeaderDict,
176
+ clean_headers,
177
+ clean_proxies,
178
+ std_headers,
179
+ )
180
+ from .version import CHANNEL, ORIGIN, RELEASE_GIT_HEAD, VARIANT, __version__
181
+
182
+ if os.name == 'nt':
183
+ import ctypes
184
+
185
+
186
+ def _catch_unsafe_extension_error(func):
187
+ @functools.wraps(func)
188
+ def wrapper(self, *args, **kwargs):
189
+ try:
190
+ return func(self, *args, **kwargs)
191
+ except _UnsafeExtensionError as error:
192
+ self.report_error(
193
+ f'The extracted extension ({error.extension!r}) is unusual '
194
+ 'and will be skipped for safety reasons. '
195
+ f'If you believe this is an error{bug_reports_message(",")}')
196
+
197
+ return wrapper
198
+
199
+
200
+ class YoutubeDL:
201
+ """YoutubeDL class.
202
+
203
+ YoutubeDL objects are the ones responsible of downloading the
204
+ actual video file and writing it to disk if the user has requested
205
+ it, among some other tasks. In most cases there should be one per
206
+ program. As, given a video URL, the downloader doesn't know how to
207
+ extract all the needed information, task that InfoExtractors do, it
208
+ has to pass the URL to one of them.
209
+
210
+ For this, YoutubeDL objects have a method that allows
211
+ InfoExtractors to be registered in a given order. When it is passed
212
+ a URL, the YoutubeDL object handles it to the first InfoExtractor it
213
+ finds that reports being able to handle it. The InfoExtractor extracts
214
+ all the information about the video or videos the URL refers to, and
215
+ YoutubeDL process the extracted information, possibly using a File
216
+ Downloader to download the video.
217
+
218
+ YoutubeDL objects accept a lot of parameters. In order not to saturate
219
+ the object constructor with arguments, it receives a dictionary of
220
+ options instead. These options are available through the params
221
+ attribute for the InfoExtractors to use. The YoutubeDL also
222
+ registers itself as the downloader in charge for the InfoExtractors
223
+ that are added to it, so this is a "mutual registration".
224
+
225
+ Available options:
226
+
227
+ username: Username for authentication purposes.
228
+ password: Password for authentication purposes.
229
+ videopassword: Password for accessing a video.
230
+ ap_mso: Adobe Pass multiple-system operator identifier.
231
+ ap_username: Multiple-system operator account username.
232
+ ap_password: Multiple-system operator account password.
233
+ usenetrc: Use netrc for authentication instead.
234
+ netrc_location: Location of the netrc file. Defaults to ~/.netrc.
235
+ netrc_cmd: Use a shell command to get credentials
236
+ verbose: Print additional info to stdout.
237
+ quiet: Do not print messages to stdout.
238
+ no_warnings: Do not print out anything for warnings.
239
+ forceprint: A dict with keys WHEN mapped to a list of templates to
240
+ print to stdout. The allowed keys are video or any of the
241
+ items in utils.POSTPROCESS_WHEN.
242
+ For compatibility, a single list is also accepted
243
+ print_to_file: A dict with keys WHEN (same as forceprint) mapped to
244
+ a list of tuples with (template, filename)
245
+ forcejson: Force printing info_dict as JSON.
246
+ dump_single_json: Force printing the info_dict of the whole playlist
247
+ (or video) as a single JSON line.
248
+ force_write_download_archive: Force writing download archive regardless
249
+ of 'skip_download' or 'simulate'.
250
+ simulate: Do not download the video files. If unset (or None),
251
+ simulate only if listsubtitles, listformats or list_thumbnails is used
252
+ format: Video format code. see "FORMAT SELECTION" for more details.
253
+ You can also pass a function. The function takes 'ctx' as
254
+ argument and returns the formats to download.
255
+ See "build_format_selector" for an implementation
256
+ allow_unplayable_formats: Allow unplayable formats to be extracted and downloaded.
257
+ ignore_no_formats_error: Ignore "No video formats" error. Usefull for
258
+ extracting metadata even if the video is not actually
259
+ available for download (experimental)
260
+ format_sort: A list of fields by which to sort the video formats.
261
+ See "Sorting Formats" for more details.
262
+ format_sort_force: Force the given format_sort. see "Sorting Formats"
263
+ for more details.
264
+ prefer_free_formats: Whether to prefer video formats with free containers
265
+ over non-free ones of the same quality.
266
+ allow_multiple_video_streams: Allow multiple video streams to be merged
267
+ into a single file
268
+ allow_multiple_audio_streams: Allow multiple audio streams to be merged
269
+ into a single file
270
+ check_formats Whether to test if the formats are downloadable.
271
+ Can be True (check all), False (check none),
272
+ 'selected' (check selected formats),
273
+ or None (check only if requested by extractor)
274
+ paths: Dictionary of output paths. The allowed keys are 'home'
275
+ 'temp' and the keys of OUTTMPL_TYPES (in utils/_utils.py)
276
+ outtmpl: Dictionary of templates for output names. Allowed keys
277
+ are 'default' and the keys of OUTTMPL_TYPES (in utils/_utils.py).
278
+ For compatibility with youtube-dl, a single string can also be used
279
+ outtmpl_na_placeholder: Placeholder for unavailable meta fields.
280
+ restrictfilenames: Do not allow "&" and spaces in file names
281
+ trim_file_name: Limit length of filename (extension excluded)
282
+ windowsfilenames: True: Force filenames to be Windows compatible
283
+ False: Sanitize filenames only minimally
284
+ This option has no effect when running on Windows
285
+ ignoreerrors: Do not stop on download/postprocessing errors.
286
+ Can be 'only_download' to ignore only download errors.
287
+ Default is 'only_download' for CLI, but False for API
288
+ skip_playlist_after_errors: Number of allowed failures until the rest of
289
+ the playlist is skipped
290
+ allowed_extractors: List of regexes to match against extractor names that are allowed
291
+ overwrites: Overwrite all video and metadata files if True,
292
+ overwrite only non-video files if None
293
+ and don't overwrite any file if False
294
+ playlist_items: Specific indices of playlist to download.
295
+ playlistrandom: Download playlist items in random order.
296
+ lazy_playlist: Process playlist entries as they are received.
297
+ matchtitle: Download only matching titles.
298
+ rejecttitle: Reject downloads for matching titles.
299
+ logger: A class having a `debug`, `warning` and `error` function where
300
+ each has a single string parameter, the message to be logged.
301
+ For compatibility reasons, both debug and info messages are passed to `debug`.
302
+ A debug message will have a prefix of `[debug] ` to discern it from info messages.
303
+ logtostderr: Print everything to stderr instead of stdout.
304
+ consoletitle: Display progress in the console window's titlebar.
305
+ writedescription: Write the video description to a .description file
306
+ writeinfojson: Write the video description to a .info.json file
307
+ clean_infojson: Remove internal metadata from the infojson
308
+ getcomments: Extract video comments. This will not be written to disk
309
+ unless writeinfojson is also given
310
+ writethumbnail: Write the thumbnail image to a file
311
+ allow_playlist_files: Whether to write playlists' description, infojson etc
312
+ also to disk when using the 'write*' options
313
+ write_all_thumbnails: Write all thumbnail formats to files
314
+ writelink: Write an internet shortcut file, depending on the
315
+ current platform (.url/.webloc/.desktop)
316
+ writeurllink: Write a Windows internet shortcut file (.url)
317
+ writewebloclink: Write a macOS internet shortcut file (.webloc)
318
+ writedesktoplink: Write a Linux internet shortcut file (.desktop)
319
+ writesubtitles: Write the video subtitles to a file
320
+ writeautomaticsub: Write the automatically generated subtitles to a file
321
+ listsubtitles: Lists all available subtitles for the video
322
+ subtitlesformat: The format code for subtitles
323
+ subtitleslangs: List of languages of the subtitles to download (can be regex).
324
+ The list may contain "all" to refer to all the available
325
+ subtitles. The language can be prefixed with a "-" to
326
+ exclude it from the requested languages, e.g. ['all', '-live_chat']
327
+ keepvideo: Keep the video file after post-processing
328
+ daterange: A utils.DateRange object, download only if the upload_date is in the range.
329
+ skip_download: Skip the actual download of the video file
330
+ cachedir: Location of the cache files in the filesystem.
331
+ False to disable filesystem cache.
332
+ noplaylist: Download single video instead of a playlist if in doubt.
333
+ age_limit: An integer representing the user's age in years.
334
+ Unsuitable videos for the given age are skipped.
335
+ min_views: An integer representing the minimum view count the video
336
+ must have in order to not be skipped.
337
+ Videos without view count information are always
338
+ downloaded. None for no limit.
339
+ max_views: An integer representing the maximum view count.
340
+ Videos that are more popular than that are not
341
+ downloaded.
342
+ Videos without view count information are always
343
+ downloaded. None for no limit.
344
+ download_archive: A set, or the name of a file where all downloads are recorded.
345
+ Videos already present in the file are not downloaded again.
346
+ break_on_existing: Stop the download process after attempting to download a
347
+ file that is in the archive.
348
+ break_per_url: Whether break_on_reject and break_on_existing
349
+ should act on each input URL as opposed to for the entire queue
350
+ cookiefile: File name or text stream from where cookies should be read and dumped to
351
+ cookiesfrombrowser: A tuple containing the name of the browser, the profile
352
+ name/path from where cookies are loaded, the name of the keyring,
353
+ and the container name, e.g. ('chrome', ) or
354
+ ('vivaldi', 'default', 'BASICTEXT') or ('firefox', 'default', None, 'Meta')
355
+ legacyserverconnect: Explicitly allow HTTPS connection to servers that do not
356
+ support RFC 5746 secure renegotiation
357
+ nocheckcertificate: Do not verify SSL certificates
358
+ client_certificate: Path to client certificate file in PEM format. May include the private key
359
+ client_certificate_key: Path to private key file for client certificate
360
+ client_certificate_password: Password for client certificate private key, if encrypted.
361
+ If not provided and the key is encrypted, yt-dlp will ask interactively
362
+ prefer_insecure: Use HTTP instead of HTTPS to retrieve information.
363
+ (Only supported by some extractors)
364
+ enable_file_urls: Enable file:// URLs. This is disabled by default for security reasons.
365
+ http_headers: A dictionary of custom headers to be used for all requests
366
+ proxy: URL of the proxy server to use
367
+ geo_verification_proxy: URL of the proxy to use for IP address verification
368
+ on geo-restricted sites.
369
+ socket_timeout: Time to wait for unresponsive hosts, in seconds
370
+ bidi_workaround: Work around buggy terminals without bidirectional text
371
+ support, using fridibi
372
+ debug_printtraffic:Print out sent and received HTTP traffic
373
+ default_search: Prepend this string if an input url is not valid.
374
+ 'auto' for elaborate guessing
375
+ encoding: Use this encoding instead of the system-specified.
376
+ extract_flat: Whether to resolve and process url_results further
377
+ * False: Always process. Default for API
378
+ * True: Never process
379
+ * 'in_playlist': Do not process inside playlist/multi_video
380
+ * 'discard': Always process, but don't return the result
381
+ from inside playlist/multi_video
382
+ * 'discard_in_playlist': Same as "discard", but only for
383
+ playlists (not multi_video). Default for CLI
384
+ wait_for_video: If given, wait for scheduled streams to become available.
385
+ The value should be a tuple containing the range
386
+ (min_secs, max_secs) to wait between retries
387
+ postprocessors: A list of dictionaries, each with an entry
388
+ * key: The name of the postprocessor. See
389
+ yt_dlp/postprocessor/__init__.py for a list.
390
+ * when: When to run the postprocessor. Allowed values are
391
+ the entries of utils.POSTPROCESS_WHEN
392
+ Assumed to be 'post_process' if not given
393
+ progress_hooks: A list of functions that get called on download
394
+ progress, with a dictionary with the entries
395
+ * status: One of "downloading", "error", or "finished".
396
+ Check this first and ignore unknown values.
397
+ * info_dict: The extracted info_dict
398
+
399
+ If status is one of "downloading", or "finished", the
400
+ following properties may also be present:
401
+ * filename: The final filename (always present)
402
+ * tmpfilename: The filename we're currently writing to
403
+ * downloaded_bytes: Bytes on disk
404
+ * total_bytes: Size of the whole file, None if unknown
405
+ * total_bytes_estimate: Guess of the eventual file size,
406
+ None if unavailable.
407
+ * elapsed: The number of seconds since download started.
408
+ * eta: The estimated time in seconds, None if unknown
409
+ * speed: The download speed in bytes/second, None if
410
+ unknown
411
+ * fragment_index: The counter of the currently
412
+ downloaded video fragment.
413
+ * fragment_count: The number of fragments (= individual
414
+ files that will be merged)
415
+
416
+ Progress hooks are guaranteed to be called at least once
417
+ (with status "finished") if the download is successful.
418
+ postprocessor_hooks: A list of functions that get called on postprocessing
419
+ progress, with a dictionary with the entries
420
+ * status: One of "started", "processing", or "finished".
421
+ Check this first and ignore unknown values.
422
+ * postprocessor: Name of the postprocessor
423
+ * info_dict: The extracted info_dict
424
+
425
+ Progress hooks are guaranteed to be called at least twice
426
+ (with status "started" and "finished") if the processing is successful.
427
+ merge_output_format: "/" separated list of extensions to use when merging formats.
428
+ final_ext: Expected final extension; used to detect when the file was
429
+ already downloaded and converted
430
+ fixup: Automatically correct known faults of the file.
431
+ One of:
432
+ - "never": do nothing
433
+ - "warn": only emit a warning
434
+ - "detect_or_warn": check whether we can do anything
435
+ about it, warn otherwise (default)
436
+ source_address: Client-side IP address to bind to.
437
+ impersonate: Client to impersonate for requests.
438
+ An ImpersonateTarget (from yt_dlp.networking.impersonate)
439
+ sleep_interval_requests: Number of seconds to sleep between requests
440
+ during extraction
441
+ sleep_interval: Number of seconds to sleep before each download when
442
+ used alone or a lower bound of a range for randomized
443
+ sleep before each download (minimum possible number
444
+ of seconds to sleep) when used along with
445
+ max_sleep_interval.
446
+ max_sleep_interval:Upper bound of a range for randomized sleep before each
447
+ download (maximum possible number of seconds to sleep).
448
+ Must only be used along with sleep_interval.
449
+ Actual sleep time will be a random float from range
450
+ [sleep_interval; max_sleep_interval].
451
+ sleep_interval_subtitles: Number of seconds to sleep before each subtitle download
452
+ listformats: Print an overview of available video formats and exit.
453
+ list_thumbnails: Print a table of all thumbnails and exit.
454
+ match_filter: A function that gets called for every video with the signature
455
+ (info_dict, *, incomplete: bool) -> Optional[str]
456
+ For backward compatibility with youtube-dl, the signature
457
+ (info_dict) -> Optional[str] is also allowed.
458
+ - If it returns a message, the video is ignored.
459
+ - If it returns None, the video is downloaded.
460
+ - If it returns utils.NO_DEFAULT, the user is interactively
461
+ asked whether to download the video.
462
+ - Raise utils.DownloadCancelled(msg) to abort remaining
463
+ downloads when a video is rejected.
464
+ match_filter_func in utils/_utils.py is one example for this.
465
+ color: A Dictionary with output stream names as keys
466
+ and their respective color policy as values.
467
+ Can also just be a single color policy,
468
+ in which case it applies to all outputs.
469
+ Valid stream names are 'stdout' and 'stderr'.
470
+ Valid color policies are one of 'always', 'auto',
471
+ 'no_color', 'never', 'auto-tty' or 'no_color-tty'.
472
+ geo_bypass: Bypass geographic restriction via faking X-Forwarded-For
473
+ HTTP header
474
+ geo_bypass_country:
475
+ Two-letter ISO 3166-2 country code that will be used for
476
+ explicit geographic restriction bypassing via faking
477
+ X-Forwarded-For HTTP header
478
+ geo_bypass_ip_block:
479
+ IP range in CIDR notation that will be used similarly to
480
+ geo_bypass_country
481
+ external_downloader: A dictionary of protocol keys and the executable of the
482
+ external downloader to use for it. The allowed protocols
483
+ are default|http|ftp|m3u8|dash|rtsp|rtmp|mms.
484
+ Set the value to 'native' to use the native downloader
485
+ compat_opts: Compatibility options. See "Differences in default behavior".
486
+ The following options do not work when used through the API:
487
+ filename, abort-on-error, multistreams, no-live-chat,
488
+ format-sort, no-clean-infojson, no-playlist-metafiles,
489
+ no-keep-subs, no-attach-info-json, allow-unsafe-ext, prefer-vp9-sort,
490
+ mtime-by-default.
491
+ Refer __init__.py for their implementation
492
+ progress_template: Dictionary of templates for progress outputs.
493
+ Allowed keys are 'download', 'postprocess',
494
+ 'download-title' (console title) and 'postprocess-title'.
495
+ The template is mapped on a dictionary with keys 'progress' and 'info'
496
+ retry_sleep_functions: Dictionary of functions that takes the number of attempts
497
+ as argument and returns the time to sleep in seconds.
498
+ Allowed keys are 'http', 'fragment', 'file_access', 'extractor'
499
+ download_ranges: A callback function that gets called for every video with
500
+ the signature (info_dict, ydl) -> Iterable[Section].
501
+ Only the returned sections will be downloaded.
502
+ Each Section is a dict with the following keys:
503
+ * start_time: Start time of the section in seconds
504
+ * end_time: End time of the section in seconds
505
+ * title: Section title (Optional)
506
+ * index: Section number (Optional)
507
+ force_keyframes_at_cuts: Re-encode the video when downloading ranges to get precise cuts
508
+ noprogress: Do not print the progress bar
509
+ live_from_start: Whether to download livestreams videos from the start
510
+ warn_when_outdated: Emit a warning if the yt-dlp version is older than 90 days
511
+
512
+ The following parameters are not used by YoutubeDL itself, they are used by
513
+ the downloader (see yt_dlp/downloader/common.py):
514
+ nopart, updatetime, buffersize, ratelimit, throttledratelimit, min_filesize,
515
+ max_filesize, test, noresizebuffer, retries, file_access_retries, fragment_retries,
516
+ continuedl, hls_use_mpegts, http_chunk_size, external_downloader_args,
517
+ concurrent_fragment_downloads, progress_delta.
518
+
519
+ The following options are used by the post processors:
520
+ ffmpeg_location: Location of the ffmpeg binary; either the path
521
+ to the binary or its containing directory.
522
+ postprocessor_args: A dictionary of postprocessor/executable keys (in lower case)
523
+ and a list of additional command-line arguments for the
524
+ postprocessor/executable. The dict can also have "PP+EXE" keys
525
+ which are used when the given exe is used by the given PP.
526
+ Use 'default' as the name for arguments to passed to all PP
527
+ For compatibility with youtube-dl, a single list of args
528
+ can also be used
529
+
530
+ The following options are used by the extractors:
531
+ extractor_retries: Number of times to retry for known errors (default: 3)
532
+ dynamic_mpd: Whether to process dynamic DASH manifests (default: True)
533
+ hls_split_discontinuity: Split HLS playlists into different formats at
534
+ discontinuities such as ad breaks (default: False)
535
+ extractor_args: A dictionary of arguments to be passed to the extractors.
536
+ See "EXTRACTOR ARGUMENTS" for details.
537
+ Argument values must always be a list of string(s).
538
+ E.g. {'youtube': {'skip': ['dash', 'hls']}}
539
+ js_runtimes: A dictionary of JavaScript runtime keys (in lower case) to enable
540
+ and a dictionary of additional configuration for the runtime.
541
+ Currently supported runtimes are 'deno', 'node', 'bun', and 'quickjs'.
542
+ If None, the default runtime of "deno" will be enabled.
543
+ The runtime configuration dictionary can have the following keys:
544
+ - path: Path to the executable (optional)
545
+ E.g. {'deno': {'path': '/path/to/deno'}
546
+ remote_components: A list of remote components that are allowed to be fetched when required.
547
+ Supported components:
548
+ - ejs:npm (external JavaScript components from npm)
549
+ - ejs:github (external JavaScript components from yt-dlp-ejs GitHub)
550
+ By default, no remote components are allowed to be fetched.
551
+ mark_watched: Mark videos watched (even with --simulate). Only for YouTube
552
+
553
+ The following options are deprecated and may be removed in the future:
554
+
555
+ break_on_reject: Stop the download process when encountering a video that
556
+ has been filtered out.
557
+ - `raise DownloadCancelled(msg)` in match_filter instead
558
+ force_generic_extractor: Force downloader to use the generic extractor
559
+ - Use allowed_extractors = ['generic', 'default']
560
+ playliststart: - Use playlist_items
561
+ Playlist item to start at.
562
+ playlistend: - Use playlist_items
563
+ Playlist item to end at.
564
+ playlistreverse: - Use playlist_items
565
+ Download playlist items in reverse order.
566
+ forceurl: - Use forceprint
567
+ Force printing final URL.
568
+ forcetitle: - Use forceprint
569
+ Force printing title.
570
+ forceid: - Use forceprint
571
+ Force printing ID.
572
+ forcethumbnail: - Use forceprint
573
+ Force printing thumbnail URL.
574
+ forcedescription: - Use forceprint
575
+ Force printing description.
576
+ forcefilename: - Use forceprint
577
+ Force printing final filename.
578
+ forceduration: - Use forceprint
579
+ Force printing duration.
580
+ allsubtitles: - Use subtitleslangs = ['all']
581
+ Downloads all the subtitles of the video
582
+ (requires writesubtitles or writeautomaticsub)
583
+ post_hooks: - Register a custom postprocessor
584
+ A list of functions that get called as the final step
585
+ for each video file, after all postprocessors have been
586
+ called. The filename will be passed as the only argument.
587
+ hls_prefer_native: - Use external_downloader = {'m3u8': 'native'} or {'m3u8': 'ffmpeg'}.
588
+ Use the native HLS downloader instead of ffmpeg
589
+ if True, otherwise use ffmpeg if False, otherwise
590
+ use downloader suggested by extractor if None.
591
+ no_color: Same as `color='no_color'`
592
+ no_overwrites: Same as `overwrites=False`
593
+ """
594
+
595
+ _NUMERIC_FIELDS = {
596
+ 'width', 'height', 'asr', 'audio_channels', 'fps',
597
+ 'tbr', 'abr', 'vbr', 'filesize', 'filesize_approx',
598
+ 'timestamp', 'release_timestamp', 'available_at',
599
+ 'duration', 'view_count', 'like_count', 'dislike_count', 'repost_count', 'save_count',
600
+ 'average_rating', 'comment_count', 'age_limit',
601
+ 'start_time', 'end_time',
602
+ 'chapter_number', 'season_number', 'episode_number',
603
+ 'track_number', 'disc_number', 'release_year',
604
+ }
605
+
606
+ _format_fields = {
607
+ # NB: Keep in sync with the docstring of extractor/common.py
608
+ 'url', 'manifest_url', 'manifest_stream_number', 'ext', 'format', 'format_id', 'format_note', 'available_at',
609
+ 'width', 'height', 'aspect_ratio', 'resolution', 'dynamic_range', 'tbr', 'abr', 'acodec', 'asr', 'audio_channels',
610
+ 'vbr', 'fps', 'vcodec', 'container', 'filesize', 'filesize_approx', 'rows', 'columns', 'hls_media_playlist_data',
611
+ 'player_url', 'protocol', 'fragment_base_url', 'fragments', 'is_from_start', 'is_dash_periods', 'request_data',
612
+ 'preference', 'language', 'language_preference', 'quality', 'source_preference', 'cookies',
613
+ 'http_headers', 'stretched_ratio', 'no_resume', 'has_drm', 'extra_param_to_segment_url', 'extra_param_to_key_url',
614
+ 'hls_aes', 'downloader_options', 'impersonate', 'page_url', 'app', 'play_path', 'tc_url', 'flash_version',
615
+ 'rtmp_live', 'rtmp_conn', 'rtmp_protocol', 'rtmp_real_time',
616
+ }
617
+ _deprecated_multivalue_fields = {
618
+ 'album_artist': 'album_artists',
619
+ 'artist': 'artists',
620
+ 'composer': 'composers',
621
+ 'creator': 'creators',
622
+ 'genre': 'genres',
623
+ }
624
+ _format_selection_exts = {
625
+ 'audio': set(MEDIA_EXTENSIONS.common_audio),
626
+ 'video': {*MEDIA_EXTENSIONS.common_video, '3gp'},
627
+ 'storyboards': set(MEDIA_EXTENSIONS.storyboards),
628
+ }
629
+
630
+ def __init__(self, params=None, auto_init=True):
631
+ """Create a FileDownloader object with the given options.
632
+ @param auto_init Whether to load the default extractors and print header (if verbose).
633
+ Set to 'no_verbose_header' to not print the header
634
+ """
635
+ if params is None:
636
+ params = {}
637
+ self.params = params
638
+ self._ies = {}
639
+ self._ies_instances = {}
640
+ self._pps = {k: [] for k in POSTPROCESS_WHEN}
641
+ self._printed_messages = set()
642
+ self._first_webpage_request = True
643
+ self._post_hooks = []
644
+ self._close_hooks = []
645
+ self._progress_hooks = []
646
+ self._postprocessor_hooks = []
647
+ self._download_retcode = 0
648
+ self._num_downloads = 0
649
+ self._num_videos = 0
650
+ self._playlist_level = 0
651
+ self._playlist_urls = set()
652
+ self.cache = Cache(self)
653
+ self.__header_cookies = []
654
+
655
+ # compat for API: load plugins if they have not already
656
+ if not all_plugins_loaded.value:
657
+ load_all_plugins()
658
+
659
+ stdout = sys.stderr if self.params.get('logtostderr') else sys.stdout
660
+ self._out_files = Namespace(
661
+ out=stdout,
662
+ error=sys.stderr,
663
+ screen=sys.stderr if self.params.get('quiet') else stdout,
664
+ )
665
+
666
+ try:
667
+ windows_enable_vt_mode()
668
+ except Exception as e:
669
+ self.write_debug(f'Failed to enable VT mode: {e}')
670
+
671
+ # hehe "immutable" namespace
672
+ self._out_files.console = next(filter(supports_terminal_sequences, (sys.stderr, sys.stdout)), None)
673
+
674
+ if self.params.get('no_color'):
675
+ if self.params.get('color') is not None:
676
+ self.params.setdefault('_warnings', []).append(
677
+ 'Overwriting params from "color" with "no_color"')
678
+ self.params['color'] = 'no_color'
679
+
680
+ term_allow_color = os.getenv('TERM', '').lower() != 'dumb'
681
+ base_no_color = bool(os.getenv('NO_COLOR'))
682
+
683
+ def process_color_policy(stream):
684
+ stream_name = {sys.stdout: 'stdout', sys.stderr: 'stderr'}[stream]
685
+ policy = traverse_obj(self.params, ('color', (stream_name, None), {str}, any)) or 'auto'
686
+ if policy in ('auto', 'auto-tty', 'no_color-tty'):
687
+ no_color = base_no_color
688
+ if policy.endswith('tty'):
689
+ no_color = policy.startswith('no_color')
690
+ if term_allow_color and supports_terminal_sequences(stream):
691
+ return 'no_color' if no_color else True
692
+ return False
693
+ assert policy in ('always', 'never', 'no_color'), policy
694
+ return {'always': True, 'never': False}.get(policy, policy)
695
+
696
+ self._allow_colors = Namespace(**{
697
+ name: process_color_policy(stream)
698
+ for name, stream in self._out_files.items_ if name != 'console'
699
+ })
700
+
701
+ system_deprecation = _get_system_deprecation()
702
+ if system_deprecation:
703
+ self.deprecated_feature(system_deprecation.replace('\n', '\n '))
704
+ elif self.params.get('warn_when_outdated'):
705
+ if outdated_warning := _get_outdated_warning():
706
+ self.report_warning(outdated_warning)
707
+
708
+ if self.params.get('allow_unplayable_formats'):
709
+ self.report_warning(
710
+ f'You have asked for {self._format_err("UNPLAYABLE", self.Styles.EMPHASIS)} formats to be listed/downloaded. '
711
+ 'This is a developer option intended for debugging. \n'
712
+ ' If you experience any issues while using this option, '
713
+ f'{self._format_err("DO NOT", self.Styles.ERROR)} open a bug report')
714
+
715
+ if self.params.get('bidi_workaround', False):
716
+ try:
717
+ import pty
718
+ master, slave = pty.openpty()
719
+ width = shutil.get_terminal_size().columns
720
+ width_args = [] if width is None else ['-w', str(width)]
721
+ sp_kwargs = {'stdin': subprocess.PIPE, 'stdout': slave, 'stderr': self._out_files.error}
722
+ try:
723
+ self._output_process = Popen(['bidiv', *width_args], **sp_kwargs)
724
+ except OSError:
725
+ self._output_process = Popen(['fribidi', '-c', 'UTF-8', *width_args], **sp_kwargs)
726
+ self._output_channel = os.fdopen(master, 'rb')
727
+ except OSError as ose:
728
+ if ose.errno == errno.ENOENT:
729
+ self.report_warning(
730
+ 'Could not find fribidi executable, ignoring --bidi-workaround. '
731
+ 'Make sure that fribidi is an executable file in one of the directories in your $PATH.')
732
+ else:
733
+ raise
734
+
735
+ # Note: this must be after plugins are loaded
736
+ self.params['js_runtimes'] = self.params.get('js_runtimes', {'deno': {}})
737
+ self._clean_js_runtimes(self.params['js_runtimes'])
738
+
739
+ self.params['remote_components'] = set(self.params.get('remote_components', ()))
740
+ self._clean_remote_components(self.params['remote_components'])
741
+
742
+ self.params['compat_opts'] = set(self.params.get('compat_opts', ()))
743
+ self.params['http_headers'] = HTTPHeaderDict(std_headers, self.params.get('http_headers'))
744
+ self._load_cookies(self.params['http_headers'].get('Cookie')) # compat
745
+ self.params['http_headers'].pop('Cookie', None)
746
+
747
+ if auto_init and auto_init != 'no_verbose_header':
748
+ self.print_debug_header()
749
+
750
+ def check_deprecated(param, option, suggestion):
751
+ if self.params.get(param) is not None:
752
+ self.report_warning(f'{option} is deprecated. Use {suggestion} instead')
753
+ return True
754
+ return False
755
+
756
+ check_deprecated('useid', '--id', '-o "%(id)s.%(ext)s"')
757
+
758
+ for msg in self.params.get('_warnings', []):
759
+ self.report_warning(msg)
760
+ for msg in self.params.get('_deprecation_warnings', []):
761
+ self.deprecated_feature(msg)
762
+
763
+ if impersonate_target := self.params.get('impersonate'):
764
+ if not self._impersonate_target_available(impersonate_target):
765
+ raise YoutubeDLError(
766
+ f'Impersonate target "{impersonate_target}" is not available. '
767
+ f'Use --list-impersonate-targets to see available targets. '
768
+ f'You may be missing dependencies required to support this target.')
769
+
770
+ if 'list-formats' in self.params['compat_opts']:
771
+ self.params['listformats_table'] = False
772
+
773
+ if 'overwrites' not in self.params and self.params.get('nooverwrites') is not None:
774
+ # nooverwrites was unnecessarily changed to overwrites
775
+ # in 0c3d0f51778b153f65c21906031c2e091fcfb641
776
+ # This ensures compatibility with both keys
777
+ self.params['overwrites'] = not self.params['nooverwrites']
778
+ elif self.params.get('overwrites') is None:
779
+ self.params.pop('overwrites', None)
780
+ else:
781
+ self.params['nooverwrites'] = not self.params['overwrites']
782
+
783
+ if self.params.get('simulate') is None and any((
784
+ self.params.get('list_thumbnails'),
785
+ self.params.get('listformats'),
786
+ self.params.get('listsubtitles'),
787
+ )):
788
+ self.params['simulate'] = 'list_only'
789
+
790
+ self.params.setdefault('forceprint', {})
791
+ self.params.setdefault('print_to_file', {})
792
+
793
+ # Compatibility with older syntax
794
+ if not isinstance(params['forceprint'], dict):
795
+ self.params['forceprint'] = {'video': params['forceprint']}
796
+
797
+ if auto_init:
798
+ self.add_default_info_extractors()
799
+
800
+ if (sys.platform != 'win32'
801
+ and sys.getfilesystemencoding() in ['ascii', 'ANSI_X3.4-1968']
802
+ and not self.params.get('restrictfilenames', False)):
803
+ # Unicode filesystem API will throw errors (#1474, #13027)
804
+ self.report_warning(
805
+ 'Assuming --restrict-filenames since file system encoding '
806
+ 'cannot encode all characters. '
807
+ 'Set the LC_ALL environment variable to fix this.')
808
+ self.params['restrictfilenames'] = True
809
+
810
+ self._parse_outtmpl()
811
+
812
+ # Creating format selector here allows us to catch syntax errors before the extraction
813
+ self.format_selector = (
814
+ self.params.get('format') if self.params.get('format') in (None, '-')
815
+ else self.params['format'] if callable(self.params['format'])
816
+ else self.build_format_selector(self.params['format']))
817
+
818
+ hooks = {
819
+ 'post_hooks': self.add_post_hook,
820
+ 'progress_hooks': self.add_progress_hook,
821
+ 'postprocessor_hooks': self.add_postprocessor_hook,
822
+ }
823
+ for opt, fn in hooks.items():
824
+ for ph in self.params.get(opt, []):
825
+ fn(ph)
826
+
827
+ for pp_def_raw in self.params.get('postprocessors', []):
828
+ pp_def = dict(pp_def_raw)
829
+ when = pp_def.pop('when', 'post_process')
830
+ # Handle errors for ExecPP command validation
831
+ try:
832
+ self.add_post_processor(
833
+ get_postprocessor(pp_def.pop('key'))(self, **pp_def),
834
+ when=when)
835
+ except UnsafeExecExpansionError as e:
836
+ self.report_error(e)
837
+ raise
838
+
839
+ def preload_download_archive(fn):
840
+ """Preload the archive, if any is specified"""
841
+ archive = set()
842
+ if fn is None:
843
+ return archive
844
+ elif not is_path_like(fn):
845
+ return fn
846
+
847
+ self.write_debug(f'Loading archive file {fn!r}')
848
+ try:
849
+ with locked_file(fn, 'r', encoding='utf-8') as archive_file:
850
+ for line in archive_file:
851
+ archive.add(line.strip())
852
+ except OSError as ioe:
853
+ if ioe.errno != errno.ENOENT:
854
+ raise
855
+ return archive
856
+
857
+ self.archive = preload_download_archive(self.params.get('download_archive'))
858
+
859
+ def _clean_js_runtimes(self, runtimes):
860
+ if not (
861
+ isinstance(runtimes, dict)
862
+ and all(isinstance(k, str) and (v is None or isinstance(v, dict)) for k, v in runtimes.items())
863
+ ):
864
+ raise ValueError('Invalid js_runtimes format, expected a dict of {runtime: {config}}')
865
+
866
+ if unsupported_runtimes := runtimes.keys() - supported_js_runtimes.value.keys():
867
+ self.report_warning(
868
+ f'Ignoring unsupported JavaScript runtime(s): {", ".join(unsupported_runtimes)}.'
869
+ f' Supported runtimes: {", ".join(supported_js_runtimes.value.keys())}.')
870
+ for rt in unsupported_runtimes:
871
+ runtimes.pop(rt)
872
+
873
+ def _clean_remote_components(self, remote_components: set):
874
+ if unsupported_remote_components := set(remote_components) - set(supported_remote_components.value):
875
+ self.report_warning(
876
+ f'Ignoring unsupported remote component(s): {", ".join(unsupported_remote_components)}.'
877
+ f' Supported remote components: {", ".join(supported_remote_components.value)}.')
878
+ for rt in unsupported_remote_components:
879
+ remote_components.remove(rt)
880
+
881
+ @functools.cached_property
882
+ def _js_runtimes(self):
883
+ runtimes = {}
884
+ for name, config in self.params.get('js_runtimes', {}).items():
885
+ runtime_cls = supported_js_runtimes.value.get(name)
886
+ runtimes[name] = runtime_cls(path=config.get('path')) if runtime_cls else None
887
+ return runtimes
888
+
889
+ def warn_if_short_id(self, argv):
890
+ # short YouTube ID starting with dash?
891
+ idxs = [
892
+ i for i, a in enumerate(argv)
893
+ if re.match(r'^-[0-9A-Za-z_-]{10}$', a)]
894
+ if idxs:
895
+ correct_argv = (
896
+ ['yt-dlp']
897
+ + [a for i, a in enumerate(argv) if i not in idxs]
898
+ + ['--'] + [argv[i] for i in idxs]
899
+ )
900
+ self.report_warning(
901
+ 'Long argument string detected. '
902
+ f'Use -- to separate parameters and URLs, like this:\n{shell_quote(correct_argv)}')
903
+
904
+ def add_info_extractor(self, ie):
905
+ """Add an InfoExtractor object to the end of the list."""
906
+ ie_key = ie.ie_key()
907
+ self._ies[ie_key] = ie
908
+ if not isinstance(ie, type):
909
+ self._ies_instances[ie_key] = ie
910
+ ie.set_downloader(self)
911
+
912
+ def get_info_extractor(self, ie_key):
913
+ """
914
+ Get an instance of an IE with name ie_key, it will try to get one from
915
+ the _ies list, if there's no instance it will create a new one and add
916
+ it to the extractor list.
917
+ """
918
+ ie = self._ies_instances.get(ie_key)
919
+ if ie is None:
920
+ ie = get_info_extractor(ie_key)()
921
+ self.add_info_extractor(ie)
922
+ return ie
923
+
924
+ def add_default_info_extractors(self):
925
+ """
926
+ Add the InfoExtractors returned by gen_extractors to the end of the list
927
+ """
928
+ all_ies = {ie.IE_NAME.lower(): ie for ie in gen_extractor_classes()}
929
+ all_ies['end'] = UnsupportedURLIE()
930
+ try:
931
+ ie_names = orderedSet_from_options(
932
+ self.params.get('allowed_extractors', ['default']), {
933
+ 'all': list(all_ies),
934
+ 'default': [name for name, ie in all_ies.items() if ie._ENABLED],
935
+ }, use_regex=True)
936
+ except re.error as e:
937
+ raise ValueError(f'Wrong regex for allowed_extractors: {e.pattern}')
938
+ for name in ie_names:
939
+ self.add_info_extractor(all_ies[name])
940
+ self.write_debug(f'Loaded {len(ie_names)} extractors')
941
+
942
+ def add_post_processor(self, pp, when='post_process'):
943
+ """Add a PostProcessor object to the end of the chain."""
944
+ assert when in POSTPROCESS_WHEN, f'Invalid when={when}'
945
+ self._pps[when].append(pp)
946
+ pp.set_downloader(self)
947
+
948
+ def add_post_hook(self, ph):
949
+ """Add the post hook"""
950
+ self._post_hooks.append(ph)
951
+
952
+ def add_close_hook(self, ch):
953
+ """Add a close hook, called when YoutubeDL.close() is called"""
954
+ assert callable(ch), 'Close hook must be callable'
955
+ self._close_hooks.append(ch)
956
+
957
+ def add_progress_hook(self, ph):
958
+ """Add the download progress hook"""
959
+ self._progress_hooks.append(ph)
960
+
961
+ def add_postprocessor_hook(self, ph):
962
+ """Add the postprocessing progress hook"""
963
+ self._postprocessor_hooks.append(ph)
964
+ for pps in self._pps.values():
965
+ for pp in pps:
966
+ pp.add_progress_hook(ph)
967
+
968
+ def _bidi_workaround(self, message):
969
+ if not hasattr(self, '_output_channel'):
970
+ return message
971
+
972
+ assert hasattr(self, '_output_process')
973
+ assert isinstance(message, str)
974
+ line_count = message.count('\n') + 1
975
+ self._output_process.stdin.write((message + '\n').encode())
976
+ self._output_process.stdin.flush()
977
+ res = ''.join(self._output_channel.readline().decode()
978
+ for _ in range(line_count))
979
+ return res[:-len('\n')]
980
+
981
+ def _write_string(self, message, out=None, only_once=False):
982
+ if only_once:
983
+ if message in self._printed_messages:
984
+ return
985
+ self._printed_messages.add(message)
986
+ write_string(message, out=out, encoding=self.params.get('encoding'))
987
+
988
+ def to_stdout(self, message, skip_eol=False, quiet=None):
989
+ """Print message to stdout"""
990
+ if quiet is not None:
991
+ self.deprecation_warning('"YoutubeDL.to_stdout" no longer accepts the argument quiet. '
992
+ 'Use "YoutubeDL.to_screen" instead')
993
+ if skip_eol is not False:
994
+ self.deprecation_warning('"YoutubeDL.to_stdout" no longer accepts the argument skip_eol. '
995
+ 'Use "YoutubeDL.to_screen" instead')
996
+ self._write_string(f'{self._bidi_workaround(message)}\n', self._out_files.out)
997
+
998
+ def to_screen(self, message, skip_eol=False, quiet=None, only_once=False):
999
+ """Print message to screen if not in quiet mode"""
1000
+ if self.params.get('logger'):
1001
+ self.params['logger'].debug(message)
1002
+ return
1003
+ if (self.params.get('quiet') if quiet is None else quiet) and not self.params.get('verbose'):
1004
+ return
1005
+ self._write_string(
1006
+ '{}{}'.format(self._bidi_workaround(message), ('' if skip_eol else '\n')),
1007
+ self._out_files.screen, only_once=only_once)
1008
+
1009
+ def to_stderr(self, message, only_once=False):
1010
+ """Print message to stderr"""
1011
+ assert isinstance(message, str)
1012
+ if self.params.get('logger'):
1013
+ self.params['logger'].error(message)
1014
+ else:
1015
+ self._write_string(f'{self._bidi_workaround(message)}\n', self._out_files.error, only_once=only_once)
1016
+
1017
+ def _send_console_code(self, code):
1018
+ if not supports_terminal_sequences(self._out_files.console):
1019
+ return False
1020
+ self._write_string(code, self._out_files.console)
1021
+ return True
1022
+
1023
+ def to_console_title(self, message=None, progress_state=None, percent=None):
1024
+ if not self.params.get('consoletitle'):
1025
+ return
1026
+
1027
+ if message:
1028
+ success = self._send_console_code(f'\033]0;{remove_terminal_sequences(message)}\007')
1029
+ if not success and os.name == 'nt' and ctypes.windll.kernel32.GetConsoleWindow():
1030
+ ctypes.windll.kernel32.SetConsoleTitleW(message)
1031
+
1032
+ if isinstance(progress_state, _ProgressState):
1033
+ self._send_console_code(progress_state.get_ansi_escape(percent))
1034
+
1035
+ def save_console_title(self):
1036
+ if not self.params.get('consoletitle') or self.params.get('simulate'):
1037
+ return
1038
+ self._send_console_code('\033[22;0t') # Save the title on stack
1039
+
1040
+ def restore_console_title(self):
1041
+ if not self.params.get('consoletitle') or self.params.get('simulate'):
1042
+ return
1043
+ self._send_console_code('\033[23;0t') # Restore the title from stack
1044
+
1045
+ def __enter__(self):
1046
+ self.save_console_title()
1047
+ self.to_console_title(progress_state=_ProgressState.INDETERMINATE)
1048
+ return self
1049
+
1050
+ def save_cookies(self):
1051
+ if self.params.get('cookiefile') is not None:
1052
+ self.cookiejar.save()
1053
+
1054
+ def __exit__(self, *args):
1055
+ self.restore_console_title()
1056
+ self.to_console_title(progress_state=_ProgressState.HIDDEN)
1057
+ self.close()
1058
+
1059
+ def close(self):
1060
+ self.save_cookies()
1061
+ if '_request_director' in self.__dict__:
1062
+ self._request_director.close()
1063
+ del self._request_director
1064
+
1065
+ for close_hook in self._close_hooks:
1066
+ close_hook()
1067
+
1068
+ def trouble(self, message=None, tb=None, is_error=True):
1069
+ """Determine action to take when a download problem appears.
1070
+
1071
+ Depending on if the downloader has been configured to ignore
1072
+ download errors or not, this method may throw an exception or
1073
+ not when errors are found, after printing the message.
1074
+
1075
+ @param tb If given, is additional traceback information
1076
+ @param is_error Whether to raise error according to ignorerrors
1077
+ """
1078
+ if message is not None:
1079
+ self.to_stderr(message)
1080
+ if self.params.get('verbose'):
1081
+ if tb is None:
1082
+ if sys.exc_info()[0]: # if .trouble has been called from an except block
1083
+ tb = ''
1084
+ if hasattr(sys.exc_info()[1], 'exc_info') and sys.exc_info()[1].exc_info[0]:
1085
+ tb += ''.join(traceback.format_exception(*sys.exc_info()[1].exc_info))
1086
+ tb += encode_compat_str(traceback.format_exc())
1087
+ else:
1088
+ tb_data = traceback.format_list(traceback.extract_stack())
1089
+ tb = ''.join(tb_data)
1090
+ if tb:
1091
+ self.to_stderr(tb)
1092
+ if not is_error:
1093
+ return
1094
+ if not self.params.get('ignoreerrors'):
1095
+ if sys.exc_info()[0] and hasattr(sys.exc_info()[1], 'exc_info') and sys.exc_info()[1].exc_info[0]:
1096
+ exc_info = sys.exc_info()[1].exc_info
1097
+ else:
1098
+ exc_info = sys.exc_info()
1099
+ raise DownloadError(message, exc_info)
1100
+ self._download_retcode = 1
1101
+
1102
+ Styles = Namespace(
1103
+ HEADERS='yellow',
1104
+ EMPHASIS='light blue',
1105
+ FILENAME='green',
1106
+ ID='green',
1107
+ DELIM='blue',
1108
+ ERROR='red',
1109
+ BAD_FORMAT='light red',
1110
+ WARNING='yellow',
1111
+ SUPPRESS='light black',
1112
+ )
1113
+
1114
+ def _format_text(self, handle, allow_colors, text, f, fallback=None, *, test_encoding=False):
1115
+ text = str(text)
1116
+ if test_encoding:
1117
+ original_text = text
1118
+ # handle.encoding can be None. See https://github.com/yt-dlp/yt-dlp/issues/2711
1119
+ encoding = self.params.get('encoding') or getattr(handle, 'encoding', None) or 'ascii'
1120
+ text = text.encode(encoding, 'ignore').decode(encoding)
1121
+ if fallback is not None and text != original_text:
1122
+ text = fallback
1123
+ return format_text(text, f) if allow_colors is True else text if fallback is None else fallback
1124
+
1125
+ def _format_out(self, *args, **kwargs):
1126
+ return self._format_text(self._out_files.out, self._allow_colors.out, *args, **kwargs)
1127
+
1128
+ def _format_screen(self, *args, **kwargs):
1129
+ return self._format_text(self._out_files.screen, self._allow_colors.screen, *args, **kwargs)
1130
+
1131
+ def _format_err(self, *args, **kwargs):
1132
+ return self._format_text(self._out_files.error, self._allow_colors.error, *args, **kwargs)
1133
+
1134
+ def report_warning(self, message, only_once=False):
1135
+ """
1136
+ Print the message to stderr, it will be prefixed with 'WARNING:'
1137
+ If stderr is a tty file the 'WARNING:' will be colored
1138
+ """
1139
+ if self.params.get('logger') is not None:
1140
+ self.params['logger'].warning(message)
1141
+ elif self.params.get('no_warnings'):
1142
+ if self.params.get('verbose'):
1143
+ self.to_stderr(f'[debug:warning] {message}', only_once=only_once)
1144
+ else:
1145
+ self.to_stderr(f'{self._format_err("WARNING:", self.Styles.WARNING)} {message}', only_once)
1146
+
1147
+ def deprecation_warning(self, message, *, stacklevel=0):
1148
+ deprecation_warning(
1149
+ message, stacklevel=stacklevel + 1, printer=self.report_error, is_error=False)
1150
+
1151
+ def deprecated_feature(self, message):
1152
+ if self.params.get('logger') is not None:
1153
+ self.params['logger'].warning(f'Deprecated Feature: {message}')
1154
+ self.to_stderr(f'{self._format_err("Deprecated Feature:", self.Styles.ERROR)} {message}', True)
1155
+
1156
+ def report_error(self, message, *args, **kwargs):
1157
+ """
1158
+ Do the same as trouble, but prefixes the message with 'ERROR:', colored
1159
+ in red if stderr is a tty file.
1160
+ """
1161
+ self.trouble(f'{self._format_err("ERROR:", self.Styles.ERROR)} {message}', *args, **kwargs)
1162
+
1163
+ def write_debug(self, message, only_once=False):
1164
+ """Log debug message or Print message to stderr"""
1165
+ if not self.params.get('verbose', False):
1166
+ return
1167
+ message = f'[debug] {message}'
1168
+ if self.params.get('logger'):
1169
+ self.params['logger'].debug(message)
1170
+ else:
1171
+ self.to_stderr(message, only_once)
1172
+
1173
+ def report_file_already_downloaded(self, file_name):
1174
+ """Report file has already been fully downloaded."""
1175
+ try:
1176
+ self.to_screen(f'[download] {file_name} has already been downloaded')
1177
+ except UnicodeEncodeError:
1178
+ self.to_screen('[download] The file has already been downloaded')
1179
+
1180
+ def report_file_delete(self, file_name):
1181
+ """Report that existing file will be deleted."""
1182
+ try:
1183
+ self.to_screen(f'Deleting existing file {file_name}')
1184
+ except UnicodeEncodeError:
1185
+ self.to_screen('Deleting existing file')
1186
+
1187
+ def raise_no_formats(self, info, forced=False, *, msg=None):
1188
+ has_drm = info.get('_has_drm')
1189
+ ignored, expected = self.params.get('ignore_no_formats_error'), bool(msg)
1190
+ msg = msg or (has_drm and 'This video is DRM protected') or 'No video formats found!'
1191
+ if forced or not ignored:
1192
+ raise ExtractorError(msg, video_id=info['id'], ie=info['extractor'],
1193
+ expected=has_drm or ignored or expected)
1194
+ else:
1195
+ self.report_warning(msg)
1196
+
1197
+ def parse_outtmpl(self):
1198
+ self.deprecation_warning('"YoutubeDL.parse_outtmpl" is deprecated and may be removed in a future version')
1199
+ self._parse_outtmpl()
1200
+ return self.params['outtmpl']
1201
+
1202
+ def _parse_outtmpl(self):
1203
+ sanitize = IDENTITY
1204
+ if self.params.get('restrictfilenames'): # Remove spaces in the default template
1205
+ sanitize = lambda x: x.replace(' - ', ' ').replace(' ', '-')
1206
+
1207
+ outtmpl = self.params.setdefault('outtmpl', {})
1208
+ if not isinstance(outtmpl, dict):
1209
+ self.params['outtmpl'] = outtmpl = {'default': outtmpl}
1210
+ outtmpl.update({k: sanitize(v) for k, v in DEFAULT_OUTTMPL.items() if outtmpl.get(k) is None})
1211
+
1212
+ def get_output_path(self, dir_type='', filename=None):
1213
+ paths = self.params.get('paths', {})
1214
+ assert isinstance(paths, dict), '"paths" parameter must be a dictionary'
1215
+ path = os.path.join(
1216
+ expand_path(paths.get('home', '').strip()),
1217
+ expand_path(paths.get(dir_type, '').strip()) if dir_type else '',
1218
+ filename or '')
1219
+ return sanitize_path(path, force=self.params.get('windowsfilenames'))
1220
+
1221
+ @staticmethod
1222
+ def _outtmpl_expandpath(outtmpl):
1223
+ # expand_path translates '%%' into '%' and '$$' into '$'
1224
+ # correspondingly that is not what we want since we need to keep
1225
+ # '%%' intact for template dict substitution step. Working around
1226
+ # with boundary-alike separator hack.
1227
+ sep = ''.join(random.choices(string.ascii_letters, k=32))
1228
+ outtmpl = outtmpl.replace('%%', f'%{sep}%').replace('$$', f'${sep}$')
1229
+
1230
+ # outtmpl should be expand_path'ed before template dict substitution
1231
+ # because meta fields may contain env variables we don't want to
1232
+ # be expanded. E.g. for outtmpl "%(title)s.%(ext)s" and
1233
+ # title "Hello $PATH", we don't want `$PATH` to be expanded.
1234
+ return expand_path(outtmpl).replace(sep, '')
1235
+
1236
+ @staticmethod
1237
+ def escape_outtmpl(outtmpl):
1238
+ """ Escape any remaining strings like %s, %abc% etc. """
1239
+ return re.sub(
1240
+ STR_FORMAT_RE_TMPL.format('', '(?![%(\0])'),
1241
+ lambda mobj: ('' if mobj.group('has_key') else '%') + mobj.group(0),
1242
+ outtmpl)
1243
+
1244
+ @classmethod
1245
+ def validate_outtmpl(cls, outtmpl):
1246
+ """ @return None or Exception object """
1247
+ outtmpl = re.sub(
1248
+ STR_FORMAT_RE_TMPL.format('[^)]*', '[ljhqBUDS]'),
1249
+ lambda mobj: f'{mobj.group(0)[:-1]}s',
1250
+ cls._outtmpl_expandpath(outtmpl))
1251
+ try:
1252
+ cls.escape_outtmpl(outtmpl) % collections.defaultdict(int)
1253
+ return None
1254
+ except ValueError as err:
1255
+ return err
1256
+
1257
+ @staticmethod
1258
+ def _copy_infodict(info_dict):
1259
+ info_dict = dict(info_dict)
1260
+ info_dict.pop('__postprocessors', None)
1261
+ info_dict.pop('__pending_error', None)
1262
+ return info_dict
1263
+
1264
+ def prepare_outtmpl(self, outtmpl, info_dict, sanitize=False, *, _exec=False):
1265
+ """ Make the outtmpl and info_dict suitable for substitution: ydl.escape_outtmpl(outtmpl) % info_dict
1266
+ @param sanitize Whether to sanitize the output as a filename
1267
+ """
1268
+
1269
+ info_dict.setdefault('epoch', int(time.time())) # keep epoch consistent once set
1270
+
1271
+ info_dict = self._copy_infodict(info_dict)
1272
+ info_dict['duration_string'] = ( # %(duration>%H-%M-%S)s is wrong if duration > 24hrs
1273
+ formatSeconds(info_dict['duration'], '-' if sanitize else ':')
1274
+ if info_dict.get('duration', None) is not None
1275
+ else None)
1276
+ info_dict['autonumber'] = int(self.params.get('autonumber_start', 1) - 1 + self._num_downloads)
1277
+ info_dict['video_autonumber'] = self._num_videos
1278
+ if info_dict.get('resolution') is None:
1279
+ info_dict['resolution'] = self.format_resolution(info_dict, default=None)
1280
+
1281
+ # For fields playlist_index, playlist_autonumber and autonumber convert all occurrences
1282
+ # of %(field)s to %(field)0Nd for backward compatibility
1283
+ field_size_compat_map = {
1284
+ 'playlist_index': number_of_digits(info_dict.get('__last_playlist_index') or 0),
1285
+ 'playlist_autonumber': number_of_digits(info_dict.get('n_entries') or 0),
1286
+ 'autonumber': self.params.get('autonumber_size') or 5,
1287
+ }
1288
+
1289
+ TMPL_DICT = {}
1290
+ EXTERNAL_FORMAT_RE = re.compile(STR_FORMAT_RE_TMPL.format('[^)]*', f'[{STR_FORMAT_TYPES}ljhqBUDS]'))
1291
+ MATH_FUNCTIONS = {
1292
+ '+': float.__add__,
1293
+ '-': float.__sub__,
1294
+ '*': float.__mul__,
1295
+ }
1296
+ # Field is of the form key1.key2...
1297
+ # where keys (except first) can be string, int, slice or "{field, ...}"
1298
+ FIELD_INNER_RE = r'(?:\w+|%(num)s|%(num)s?(?::%(num)s?){1,2})' % {'num': r'(?:-?\d+)'} # noqa: UP031
1299
+ FIELD_RE = r'\w*(?:\.(?:%(inner)s|{%(field)s(?:,%(field)s)*}))*' % { # noqa: UP031
1300
+ 'inner': FIELD_INNER_RE,
1301
+ 'field': rf'\w*(?:\.{FIELD_INNER_RE})*',
1302
+ }
1303
+ MATH_FIELD_RE = rf'(?:{FIELD_RE}|-?{NUMBER_RE})'
1304
+ MATH_OPERATORS_RE = r'(?:{})'.format('|'.join(map(re.escape, MATH_FUNCTIONS.keys())))
1305
+ INTERNAL_FORMAT_RE = re.compile(rf'''(?xs)
1306
+ (?P<negate>-)?
1307
+ (?P<fields>{FIELD_RE})
1308
+ (?P<maths>(?:{MATH_OPERATORS_RE}{MATH_FIELD_RE})*)
1309
+ (?:>(?P<strf_format>.+?))?
1310
+ (?P<remaining>
1311
+ (?P<alternate>(?<!\\),[^|&)]+)?
1312
+ (?:&(?P<replacement>.*?))?
1313
+ (?:\|(?P<default>.*?))?
1314
+ )$''')
1315
+ SAFE_EXEC_CONVERSIONS = 'difq'
1316
+ UNSAFE_DEFAULT_CHARS = '"\' \n\t;&|^$%*<>{}()[]`#\\'
1317
+ EXEC_ADVISORY_MSG = 'See https://github.com/yt-dlp/yt-dlp/security/advisories/GHSA-69qj-pvh9-c5wg for details'
1318
+
1319
+ def _from_user_input(field):
1320
+ if field == ':':
1321
+ return ...
1322
+ elif ':' in field:
1323
+ return slice(*map(int_or_none, field.split(':')))
1324
+ elif int_or_none(field) is not None:
1325
+ return int(field)
1326
+ return field
1327
+
1328
+ def _traverse_infodict(fields):
1329
+ fields = [f for x in re.split(r'\.({.+?})\.?', fields)
1330
+ for f in ([x] if x.startswith('{') else x.split('.'))]
1331
+ for i in (0, -1):
1332
+ if fields and not fields[i]:
1333
+ fields.pop(i)
1334
+
1335
+ for i, f in enumerate(fields):
1336
+ if not f.startswith('{'):
1337
+ fields[i] = _from_user_input(f)
1338
+ continue
1339
+ assert f.endswith('}'), f'No closing brace for {f} in {fields}'
1340
+ fields[i] = {k: list(map(_from_user_input, k.split('.'))) for k in f[1:-1].split(',')}
1341
+
1342
+ return traverse_obj(info_dict, fields, traverse_string=True)
1343
+
1344
+ def get_value(mdict):
1345
+ # Object traversal
1346
+ value = _traverse_infodict(mdict['fields'])
1347
+ # Negative
1348
+ if mdict['negate']:
1349
+ value = float_or_none(value)
1350
+ if value is not None:
1351
+ value *= -1
1352
+ # Do maths
1353
+ offset_key = mdict['maths']
1354
+ if offset_key:
1355
+ value = float_or_none(value)
1356
+ operator = None
1357
+ while offset_key:
1358
+ item = re.match(
1359
+ MATH_FIELD_RE if operator else MATH_OPERATORS_RE,
1360
+ offset_key).group(0)
1361
+ offset_key = offset_key[len(item):]
1362
+ if operator is None:
1363
+ operator = MATH_FUNCTIONS[item]
1364
+ continue
1365
+ item, multiplier = (item[1:], -1) if item[0] == '-' else (item, 1)
1366
+ offset = float_or_none(item)
1367
+ if offset is None:
1368
+ offset = float_or_none(_traverse_infodict(item))
1369
+ try:
1370
+ value = operator(value, multiplier * offset)
1371
+ except (TypeError, ZeroDivisionError):
1372
+ return None
1373
+ operator = None
1374
+ # Datetime formatting
1375
+ if mdict['strf_format']:
1376
+ value = strftime_or_none(value, mdict['strf_format'].replace('\\,', ','))
1377
+
1378
+ # XXX: Workaround for https://github.com/yt-dlp/yt-dlp/issues/4485
1379
+ if sanitize and value == '':
1380
+ value = None
1381
+ return value
1382
+
1383
+ na = self.params.get('outtmpl_na_placeholder', 'NA')
1384
+
1385
+ def filename_sanitizer(key, value, restricted):
1386
+ return sanitize_filename(str(value), restricted=restricted, is_id=(
1387
+ bool(re.search(r'(^|[_.])id(\.|$)', key))
1388
+ if 'filename-sanitization' in self.params['compat_opts']
1389
+ else NO_DEFAULT))
1390
+
1391
+ if callable(sanitize):
1392
+ self.deprecation_warning('Passing a callable "sanitize" to YoutubeDL.prepare_outtmpl is deprecated')
1393
+ elif not sanitize:
1394
+ pass
1395
+ elif (sys.platform != 'win32' and not self.params.get('restrictfilenames')
1396
+ and self.params.get('windowsfilenames') is False):
1397
+ def sanitize(key, value):
1398
+ return str(value).replace('/', '\u29F8').replace('\0', '')
1399
+ else:
1400
+ def sanitize(key, value):
1401
+ return filename_sanitizer(key, value, restricted=self.params.get('restrictfilenames'))
1402
+
1403
+ def _dumpjson_default(obj):
1404
+ if isinstance(obj, (set, LazyList)):
1405
+ return list(obj)
1406
+ return repr(obj)
1407
+
1408
+ class _ReplacementFormatter(string.Formatter):
1409
+ def get_field(self, field_name, args, kwargs):
1410
+ if field_name.isdigit():
1411
+ return args[0], -1
1412
+ raise ValueError('Unsupported field')
1413
+
1414
+ replacement_formatter = _ReplacementFormatter()
1415
+
1416
+ def create_key(outer_mobj):
1417
+ if not outer_mobj.group('has_key'):
1418
+ return outer_mobj.group(0)
1419
+ key = outer_mobj.group('key')
1420
+ mobj = re.match(INTERNAL_FORMAT_RE, key)
1421
+ value, replacement, default, last_field = None, None, na, ''
1422
+ while mobj:
1423
+ mobj = mobj.groupdict()
1424
+ default = mobj['default'] if mobj['default'] is not None else default
1425
+ value = get_value(mobj)
1426
+ last_field, replacement = mobj['fields'], mobj['replacement']
1427
+ if value is None and mobj['alternate']:
1428
+ mobj = re.match(INTERNAL_FORMAT_RE, mobj['remaining'][1:])
1429
+ else:
1430
+ break
1431
+
1432
+ if None not in (value, replacement):
1433
+ try:
1434
+ value = replacement_formatter.format(replacement, value)
1435
+ except ValueError:
1436
+ value, default = None, na
1437
+
1438
+ fmt = outer_mobj.group('format')
1439
+ if fmt == 's' and last_field in field_size_compat_map and isinstance(value, int):
1440
+ fmt = f'0{field_size_compat_map[last_field]:d}d'
1441
+
1442
+ # Validate safety of exec commands
1443
+ if _exec:
1444
+ if fmt[-1] not in SAFE_EXEC_CONVERSIONS:
1445
+ raise UnsafeExecExpansionError(
1446
+ f'Unsafe conversion(s) in exec command: {outtmpl!r}\n'
1447
+ f'Conversions such as %()s are too dangerous to be used in '
1448
+ f'--exec command templates; use %()q instead. {EXEC_ADVISORY_MSG}')
1449
+ elif any(unsafe_char in default for unsafe_char in UNSAFE_DEFAULT_CHARS):
1450
+ if default == na:
1451
+ raise UnsafeExecExpansionError(
1452
+ f'Unsafe placeholder for exec command: {na!r}\n'
1453
+ f'The --output-na-placeholder argument also applies to '
1454
+ f'--exec command templates. {EXEC_ADVISORY_MSG}')
1455
+ else:
1456
+ raise UnsafeExecExpansionError(
1457
+ f'Unsafe default(s) in exec command: {outtmpl!r}\n'
1458
+ f'Conversions are not applied to --exec command template defaults, '
1459
+ f'e.g. %(...|DEFAULT;)q. {EXEC_ADVISORY_MSG}')
1460
+
1461
+ flags = outer_mobj.group('conversion') or ''
1462
+ str_fmt = f'{fmt[:-1]}s'
1463
+ if value is None:
1464
+ value, fmt = default, 's'
1465
+ elif fmt[-1] == 'l': # list
1466
+ delim = '\n' if '#' in flags else ', '
1467
+ value, fmt = delim.join(map(str, variadic(value, allowed_types=(str, bytes)))), str_fmt
1468
+ elif fmt[-1] == 'j': # json
1469
+ value, fmt = json.dumps(
1470
+ value, default=_dumpjson_default,
1471
+ indent=4 if '#' in flags else None, ensure_ascii='+' not in flags), str_fmt
1472
+ elif fmt[-1] == 'h': # html
1473
+ value, fmt = escapeHTML(str(value)), str_fmt
1474
+ elif fmt[-1] == 'q': # quoted
1475
+ value = map(str, variadic(value) if '#' in flags else [value])
1476
+ value, fmt = shell_quote(value, shell=True), str_fmt
1477
+ elif fmt[-1] == 'B': # bytes
1478
+ value = f'%{str_fmt}'.encode() % str(value).encode()
1479
+ value, fmt = value.decode('utf-8', 'ignore'), 's'
1480
+ elif fmt[-1] == 'U': # unicode normalized
1481
+ value, fmt = unicodedata.normalize(
1482
+ # "+" = compatibility equivalence, "#" = NFD
1483
+ 'NF{}{}'.format('K' if '+' in flags else '', 'D' if '#' in flags else 'C'),
1484
+ value), str_fmt
1485
+ elif fmt[-1] == 'D': # decimal suffix
1486
+ num_fmt, fmt = fmt[:-1].replace('#', ''), 's'
1487
+ value = format_decimal_suffix(value, f'%{num_fmt}f%s' if num_fmt else '%d%s',
1488
+ factor=1024 if '#' in flags else 1000)
1489
+ elif fmt[-1] == 'S': # filename sanitization
1490
+ value, fmt = filename_sanitizer(last_field, value, restricted='#' in flags), str_fmt
1491
+ elif fmt[-1] == 'c':
1492
+ if value:
1493
+ value = str(value)[0]
1494
+ else:
1495
+ fmt = str_fmt
1496
+ elif fmt[-1] not in 'rsa': # numeric
1497
+ value = float_or_none(value)
1498
+ if value is None:
1499
+ value, fmt = default, 's'
1500
+
1501
+ if sanitize:
1502
+ # If value is an object, sanitize might convert it to a string
1503
+ # So we manually convert it before sanitizing
1504
+ if fmt[-1] == 'r':
1505
+ value, fmt = repr(value), str_fmt
1506
+ elif fmt[-1] == 'a':
1507
+ value, fmt = ascii(value), str_fmt
1508
+ if fmt[-1] in 'csra':
1509
+ value = sanitize(last_field, value)
1510
+
1511
+ key = '{}\0{}'.format(key.replace('%', '%\0'), outer_mobj.group('format'))
1512
+ TMPL_DICT[key] = value
1513
+ return '{prefix}%({key}){fmt}'.format(key=key, fmt=fmt, prefix=outer_mobj.group('prefix'))
1514
+
1515
+ return EXTERNAL_FORMAT_RE.sub(create_key, outtmpl), TMPL_DICT
1516
+
1517
+ def evaluate_outtmpl(self, outtmpl, info_dict, *args, **kwargs):
1518
+ outtmpl, info_dict = self.prepare_outtmpl(outtmpl, info_dict, *args, **kwargs)
1519
+ return self.escape_outtmpl(outtmpl) % info_dict
1520
+
1521
+ @_catch_unsafe_extension_error
1522
+ def _prepare_filename(self, info_dict, *, outtmpl=None, tmpl_type=None):
1523
+ assert None in (outtmpl, tmpl_type), 'outtmpl and tmpl_type are mutually exclusive'
1524
+ if outtmpl is None:
1525
+ outtmpl = self.params['outtmpl'].get(tmpl_type or 'default', self.params['outtmpl']['default'])
1526
+ try:
1527
+ outtmpl = self._outtmpl_expandpath(outtmpl)
1528
+ filename = self.evaluate_outtmpl(outtmpl, info_dict, True)
1529
+ if not filename:
1530
+ return None
1531
+
1532
+ if tmpl_type in ('', 'temp'):
1533
+ final_ext, ext = self.params.get('final_ext'), info_dict.get('ext')
1534
+ if final_ext and ext and final_ext != ext and filename.endswith(f'.{final_ext}'):
1535
+ filename = replace_extension(filename, ext, final_ext)
1536
+ elif tmpl_type:
1537
+ force_ext = OUTTMPL_TYPES[tmpl_type]
1538
+ if force_ext:
1539
+ filename = replace_extension(filename, force_ext, info_dict.get('ext'))
1540
+
1541
+ # https://github.com/blackjack4494/youtube-dlc/issues/85
1542
+ trim_file_name = self.params.get('trim_file_name', False)
1543
+ if trim_file_name:
1544
+ no_ext, *ext = filename.rsplit('.', 2)
1545
+ filename = join_nonempty(no_ext[:trim_file_name], *ext, delim='.')
1546
+
1547
+ return filename
1548
+ except ValueError as err:
1549
+ self.report_error('Error in output template: ' + str(err) + ' (encoding: ' + repr(preferredencoding()) + ')')
1550
+ return None
1551
+
1552
+ def prepare_filename(self, info_dict, dir_type='', *, outtmpl=None, warn=False):
1553
+ """Generate the output filename"""
1554
+ if outtmpl:
1555
+ assert not dir_type, 'outtmpl and dir_type are mutually exclusive'
1556
+ dir_type = None
1557
+ filename = self._prepare_filename(info_dict, tmpl_type=dir_type, outtmpl=outtmpl)
1558
+ if not filename and dir_type not in ('', 'temp'):
1559
+ return ''
1560
+
1561
+ if warn:
1562
+ if not self.params.get('paths'):
1563
+ pass
1564
+ elif filename == '-':
1565
+ self.report_warning('--paths is ignored when an outputting to stdout', only_once=True)
1566
+ elif os.path.isabs(filename):
1567
+ self.report_warning('--paths is ignored since an absolute path is given in output template', only_once=True)
1568
+ if filename == '-' or not filename:
1569
+ return filename
1570
+
1571
+ return self.get_output_path(dir_type, filename)
1572
+
1573
+ def _match_entry(self, info_dict, incomplete=False, silent=False):
1574
+ """Returns None if the file should be downloaded"""
1575
+ _type = 'video' if 'playlist-match-filter' in self.params['compat_opts'] else info_dict.get('_type', 'video')
1576
+ assert incomplete or _type == 'video', 'Only video result can be considered complete'
1577
+
1578
+ video_title = info_dict.get('title', info_dict.get('id', 'entry'))
1579
+
1580
+ def check_filter():
1581
+ if _type in ('playlist', 'multi_video'):
1582
+ return
1583
+ elif _type in ('url', 'url_transparent') and not try_call(
1584
+ lambda: self.get_info_extractor(info_dict['ie_key']).is_single_video(info_dict['url'])):
1585
+ return
1586
+
1587
+ if 'title' in info_dict:
1588
+ # This can happen when we're just evaluating the playlist
1589
+ title = info_dict['title']
1590
+ matchtitle = self.params.get('matchtitle', False)
1591
+ if matchtitle:
1592
+ if not re.search(matchtitle, title, re.IGNORECASE):
1593
+ return '"' + title + '" title did not match pattern "' + matchtitle + '"'
1594
+ rejecttitle = self.params.get('rejecttitle', False)
1595
+ if rejecttitle:
1596
+ if re.search(rejecttitle, title, re.IGNORECASE):
1597
+ return '"' + title + '" title matched reject pattern "' + rejecttitle + '"'
1598
+
1599
+ date = info_dict.get('upload_date')
1600
+ if date is not None:
1601
+ date_range = self.params.get('daterange', DateRange())
1602
+ if date not in date_range:
1603
+ return f'{date_from_str(date).isoformat()} upload date is not in range {date_range}'
1604
+ view_count = info_dict.get('view_count')
1605
+ if view_count is not None:
1606
+ min_views = self.params.get('min_views')
1607
+ if min_views is not None and view_count < min_views:
1608
+ return 'Skipping %s, because it has not reached minimum view count (%d/%d)' % (video_title, view_count, min_views)
1609
+ max_views = self.params.get('max_views')
1610
+ if max_views is not None and view_count > max_views:
1611
+ return 'Skipping %s, because it has exceeded the maximum view count (%d/%d)' % (video_title, view_count, max_views)
1612
+ if age_restricted(info_dict.get('age_limit'), self.params.get('age_limit')):
1613
+ return f'Skipping "{video_title}" because it is age restricted'
1614
+
1615
+ match_filter = self.params.get('match_filter')
1616
+ if match_filter is None:
1617
+ return None
1618
+
1619
+ cancelled = None
1620
+ try:
1621
+ try:
1622
+ ret = match_filter(info_dict, incomplete=incomplete)
1623
+ except TypeError:
1624
+ # For backward compatibility
1625
+ ret = None if incomplete else match_filter(info_dict)
1626
+ except DownloadCancelled as err:
1627
+ if err.msg is not NO_DEFAULT:
1628
+ raise
1629
+ ret, cancelled = err.msg, err
1630
+
1631
+ if ret is NO_DEFAULT:
1632
+ while True:
1633
+ filename = self._format_screen(self.prepare_filename(info_dict), self.Styles.FILENAME)
1634
+ self.to_screen(
1635
+ self._format_screen(f'Download "{filename}"? (Y/n): ', self.Styles.EMPHASIS),
1636
+ skip_eol=True)
1637
+ reply = input().lower().strip()
1638
+ if reply in {'y', ''}:
1639
+ return None
1640
+ elif reply == 'n':
1641
+ if cancelled:
1642
+ raise type(cancelled)(f'Skipping {video_title}')
1643
+ return f'Skipping {video_title}'
1644
+ return ret
1645
+
1646
+ if self.in_download_archive(info_dict):
1647
+ reason = ''.join((
1648
+ format_field(info_dict, 'id', f'{self._format_screen("%s", self.Styles.ID)}: '),
1649
+ format_field(info_dict, 'title', f'{self._format_screen("%s", self.Styles.EMPHASIS)} '),
1650
+ 'has already been recorded in the archive'))
1651
+ break_opt, break_err = 'break_on_existing', ExistingVideoReached
1652
+ else:
1653
+ try:
1654
+ reason = check_filter()
1655
+ except DownloadCancelled as e:
1656
+ reason, break_opt, break_err = e.msg, 'match_filter', type(e)
1657
+ else:
1658
+ break_opt, break_err = 'break_on_reject', RejectedVideoReached
1659
+ if reason is not None:
1660
+ if not silent:
1661
+ self.to_screen('[download] ' + reason)
1662
+ if self.params.get(break_opt, False):
1663
+ raise break_err()
1664
+ return reason
1665
+
1666
+ @staticmethod
1667
+ def add_extra_info(info_dict, extra_info):
1668
+ """Set the keys from extra_info in info dict if they are missing"""
1669
+ for key, value in extra_info.items():
1670
+ info_dict.setdefault(key, value)
1671
+
1672
+ def extract_info(self, url, download=True, ie_key=None, extra_info=None,
1673
+ process=True, force_generic_extractor=False):
1674
+ """
1675
+ Extract and return the information dictionary of the URL
1676
+
1677
+ Arguments:
1678
+ @param url URL to extract
1679
+
1680
+ Keyword arguments:
1681
+ @param download Whether to download videos
1682
+ @param process Whether to resolve all unresolved references (URLs, playlist items).
1683
+ Must be True for download to work
1684
+ @param ie_key Use only the extractor with this key
1685
+
1686
+ @param extra_info Dictionary containing the extra values to add to the info (For internal use only)
1687
+ @force_generic_extractor Force using the generic extractor (Deprecated; use ie_key='Generic')
1688
+ """
1689
+
1690
+ if extra_info is None:
1691
+ extra_info = {}
1692
+
1693
+ if not ie_key and force_generic_extractor:
1694
+ ie_key = 'Generic'
1695
+
1696
+ if ie_key:
1697
+ ies = {ie_key: self._ies[ie_key]} if ie_key in self._ies else {}
1698
+ else:
1699
+ ies = self._ies
1700
+
1701
+ for key, ie in ies.items():
1702
+ if not ie.suitable(url):
1703
+ continue
1704
+
1705
+ if not ie.working():
1706
+ self.report_warning('The program functionality for this site has been marked as broken, '
1707
+ 'and will probably not work.')
1708
+
1709
+ temp_id = ie.get_temp_id(url)
1710
+ if temp_id is not None and self.in_download_archive({'id': temp_id, 'ie_key': key}):
1711
+ self.to_screen(f'[download] {self._format_screen(temp_id, self.Styles.ID)}: '
1712
+ 'has already been recorded in the archive')
1713
+ if self.params.get('break_on_existing', False):
1714
+ raise ExistingVideoReached
1715
+ break
1716
+ return self.__extract_info(url, self.get_info_extractor(key), download, extra_info, process)
1717
+ else:
1718
+ extractors_restricted = self.params.get('allowed_extractors') not in (None, ['default'])
1719
+ self.report_error(f'No suitable extractor{format_field(ie_key, None, " (%s)")} found for URL {url}',
1720
+ tb=False if extractors_restricted else None)
1721
+
1722
+ def _handle_extraction_exceptions(func):
1723
+ @functools.wraps(func)
1724
+ def wrapper(self, *args, **kwargs):
1725
+ while True:
1726
+ try:
1727
+ return func(self, *args, **kwargs)
1728
+ except (CookieLoadError, DownloadCancelled, LazyList.IndexError, PagedList.IndexError):
1729
+ raise
1730
+ except ReExtractInfo as e:
1731
+ if e.expected:
1732
+ self.to_screen(f'{e}; Re-extracting data')
1733
+ else:
1734
+ self.to_stderr('\r')
1735
+ self.report_warning(f'{e}; Re-extracting data')
1736
+ continue
1737
+ except GeoRestrictedError as e:
1738
+ msg = e.msg
1739
+ if e.countries:
1740
+ msg += '\nThis video is available in {}.'.format(', '.join(
1741
+ map(ISO3166Utils.short2full, e.countries)))
1742
+ msg += '\nYou might want to use a VPN or a proxy server (with --proxy) to workaround.'
1743
+ self.report_error(msg)
1744
+ except ExtractorError as e: # An error we somewhat expected
1745
+ self.report_error(str(e), e.format_traceback())
1746
+ except Exception as e:
1747
+ if self.params.get('ignoreerrors'):
1748
+ self.report_error(str(e), tb=encode_compat_str(traceback.format_exc()))
1749
+ else:
1750
+ raise
1751
+ break
1752
+ return wrapper
1753
+
1754
+ def _wait_for_video(self, ie_result={}):
1755
+ if (not self.params.get('wait_for_video')
1756
+ or ie_result.get('_type', 'video') != 'video'
1757
+ or ie_result.get('formats') or ie_result.get('url')):
1758
+ return
1759
+
1760
+ format_dur = lambda dur: '%02d:%02d:%02d' % timetuple_from_msec(dur * 1000)[:-1]
1761
+ last_msg = ''
1762
+
1763
+ def progress(msg):
1764
+ nonlocal last_msg
1765
+ full_msg = f'{msg}\n'
1766
+ if not self.params.get('noprogress'):
1767
+ full_msg = msg + ' ' * (len(last_msg) - len(msg)) + '\r'
1768
+ elif last_msg:
1769
+ return
1770
+ self.to_screen(full_msg, skip_eol=True)
1771
+ last_msg = msg
1772
+
1773
+ min_wait, max_wait = self.params.get('wait_for_video')
1774
+ diff = try_get(ie_result, lambda x: x['release_timestamp'] - time.time())
1775
+ if diff is None and ie_result.get('live_status') == 'is_upcoming':
1776
+ diff = round(random.uniform(min_wait, max_wait) if (max_wait and min_wait) else (max_wait or min_wait), 0)
1777
+ self.report_warning('Release time of video is not known')
1778
+ elif ie_result and (diff or 0) <= 0:
1779
+ self.report_warning('Video should already be available according to extracted info')
1780
+ diff = min(max(diff or 0, min_wait or 0), max_wait or float('inf'))
1781
+ self.to_screen(f'[wait] Waiting for {format_dur(diff)} - Press Ctrl+C to try now')
1782
+
1783
+ wait_till = time.time() + diff
1784
+ try:
1785
+ while True:
1786
+ diff = wait_till - time.time()
1787
+ if diff <= 0:
1788
+ progress('')
1789
+ raise ReExtractInfo('[wait] Wait period ended', expected=True)
1790
+ progress(f'[wait] Remaining time until next attempt: {self._format_screen(format_dur(diff), self.Styles.EMPHASIS)}')
1791
+ time.sleep(1)
1792
+ except KeyboardInterrupt:
1793
+ progress('')
1794
+ raise ReExtractInfo('[wait] Interrupted by user', expected=True)
1795
+ except BaseException as e:
1796
+ if not isinstance(e, ReExtractInfo):
1797
+ self.to_screen('')
1798
+ raise
1799
+
1800
+ def _load_cookies(self, data, *, autoscope=True):
1801
+ """Loads cookies from a `Cookie` header
1802
+
1803
+ This tries to work around the security vulnerability of passing cookies to every domain.
1804
+ See: https://github.com/yt-dlp/yt-dlp/security/advisories/GHSA-v8mc-9377-rwjj
1805
+
1806
+ @param data The Cookie header as string to load the cookies from
1807
+ @param autoscope If `False`, scope cookies using Set-Cookie syntax and error for cookie without domains
1808
+ If `True`, save cookies for later to be stored in the jar with a limited scope
1809
+ If a URL, save cookies in the jar with the domain of the URL
1810
+ """
1811
+ for cookie in LenientSimpleCookie(data).values():
1812
+ if autoscope and any(cookie.values()):
1813
+ raise ValueError('Invalid syntax in Cookie Header')
1814
+
1815
+ domain = cookie.get('domain') or ''
1816
+ expiry = cookie.get('expires')
1817
+ if expiry == '': # 0 is valid
1818
+ expiry = None
1819
+ prepared_cookie = http.cookiejar.Cookie(
1820
+ cookie.get('version') or 0, cookie.key, cookie.value, None, False,
1821
+ domain, True, True, cookie.get('path') or '', bool(cookie.get('path')),
1822
+ cookie.get('secure') or False, expiry, False, None, None, {})
1823
+
1824
+ if domain:
1825
+ self.cookiejar.set_cookie(prepared_cookie)
1826
+ elif autoscope is True:
1827
+ self.deprecated_feature(
1828
+ 'Passing cookies as a header is a potential security risk; '
1829
+ 'they will be scoped to the domain of the downloaded urls. '
1830
+ 'Please consider loading cookies from a file or browser instead.')
1831
+ self.__header_cookies.append(prepared_cookie)
1832
+ elif autoscope:
1833
+ self.report_warning(
1834
+ 'The extractor result contains an unscoped cookie as an HTTP header. '
1835
+ f'If you are using yt-dlp with an input URL{bug_reports_message(before=",")}',
1836
+ only_once=True)
1837
+ self._apply_header_cookies(autoscope, [prepared_cookie])
1838
+ else:
1839
+ self.report_error('Unscoped cookies are not allowed; please specify some sort of scoping',
1840
+ tb=False, is_error=False)
1841
+
1842
+ def _apply_header_cookies(self, url, cookies=None):
1843
+ """Applies stray header cookies to the provided url
1844
+
1845
+ This loads header cookies and scopes them to the domain provided in `url`.
1846
+ While this is not ideal, it helps reduce the risk of them being sent
1847
+ to an unintended destination while mostly maintaining compatibility.
1848
+ """
1849
+ parsed = urllib.parse.urlparse(url)
1850
+ if not parsed.hostname:
1851
+ return
1852
+
1853
+ for cookie in map(copy.copy, cookies or self.__header_cookies):
1854
+ cookie.domain = f'.{parsed.hostname}'
1855
+ self.cookiejar.set_cookie(cookie)
1856
+
1857
+ @_handle_extraction_exceptions
1858
+ def __extract_info(self, url, ie, download, extra_info, process):
1859
+ self._apply_header_cookies(url)
1860
+
1861
+ try:
1862
+ ie_result = ie.extract(url)
1863
+ except UserNotLive as e:
1864
+ if process:
1865
+ if self.params.get('wait_for_video'):
1866
+ self.report_warning(e)
1867
+ self._wait_for_video()
1868
+ raise
1869
+ if ie_result is None: # Finished already (backwards compatibility; listformats and friends should be moved here)
1870
+ self.report_warning(f'Extractor {ie.IE_NAME} returned nothing{bug_reports_message()}')
1871
+ return
1872
+ if isinstance(ie_result, list):
1873
+ # Backwards compatibility: old IE result format
1874
+ ie_result = {
1875
+ '_type': 'compat_list',
1876
+ 'entries': ie_result,
1877
+ }
1878
+ if extra_info.get('original_url'):
1879
+ ie_result.setdefault('original_url', extra_info['original_url'])
1880
+ self.add_default_extra_info(ie_result, ie, url)
1881
+ if process:
1882
+ self._wait_for_video(ie_result)
1883
+ return self.process_ie_result(ie_result, download, extra_info)
1884
+ else:
1885
+ return ie_result
1886
+
1887
+ def add_default_extra_info(self, ie_result, ie, url):
1888
+ if url is not None:
1889
+ self.add_extra_info(ie_result, {
1890
+ 'webpage_url': url,
1891
+ 'original_url': url,
1892
+ })
1893
+ webpage_url = ie_result.get('webpage_url')
1894
+ if webpage_url:
1895
+ self.add_extra_info(ie_result, {
1896
+ 'webpage_url_basename': url_basename(webpage_url),
1897
+ 'webpage_url_domain': get_domain(webpage_url),
1898
+ })
1899
+ if ie is not None:
1900
+ self.add_extra_info(ie_result, {
1901
+ 'extractor': ie.IE_NAME,
1902
+ 'extractor_key': ie.ie_key(),
1903
+ })
1904
+
1905
+ def process_ie_result(self, ie_result, download=True, extra_info=None):
1906
+ """
1907
+ Take the result of the ie(may be modified) and resolve all unresolved
1908
+ references (URLs, playlist items).
1909
+
1910
+ It will also download the videos if 'download'.
1911
+ Returns the resolved ie_result.
1912
+ """
1913
+ if extra_info is None:
1914
+ extra_info = {}
1915
+ result_type = ie_result.get('_type', 'video')
1916
+
1917
+ if result_type in ('url', 'url_transparent'):
1918
+ ie_result['url'] = sanitize_url(
1919
+ ie_result['url'], scheme='http' if self.params.get('prefer_insecure') else 'https')
1920
+ if ie_result.get('original_url') and not extra_info.get('original_url'):
1921
+ extra_info = {'original_url': ie_result['original_url'], **extra_info}
1922
+
1923
+ extract_flat = self.params.get('extract_flat', False)
1924
+ if ((extract_flat == 'in_playlist' and 'playlist' in extra_info)
1925
+ or extract_flat is True):
1926
+ info_copy = ie_result.copy()
1927
+ ie = try_get(ie_result.get('ie_key'), self.get_info_extractor)
1928
+ if ie and not ie_result.get('id'):
1929
+ info_copy['id'] = ie.get_temp_id(ie_result['url'])
1930
+ self.add_default_extra_info(info_copy, ie, ie_result['url'])
1931
+ self.add_extra_info(info_copy, extra_info)
1932
+ info_copy, _ = self.pre_process(info_copy)
1933
+ self._fill_common_fields(info_copy, False)
1934
+ self.__forced_printings(info_copy)
1935
+ self._raise_pending_errors(info_copy)
1936
+ if self.params.get('force_write_download_archive', False):
1937
+ self.record_download_archive(info_copy)
1938
+ return ie_result
1939
+
1940
+ if result_type == 'video':
1941
+ self.add_extra_info(ie_result, extra_info)
1942
+ ie_result = self.process_video_result(ie_result, download=download)
1943
+ self._raise_pending_errors(ie_result)
1944
+ additional_urls = (ie_result or {}).get('additional_urls')
1945
+ if additional_urls:
1946
+ # TODO: Improve MetadataParserPP to allow setting a list
1947
+ if isinstance(additional_urls, str):
1948
+ additional_urls = [additional_urls]
1949
+ self.to_screen(
1950
+ '[info] {}: {} additional URL(s) requested'.format(ie_result['id'], len(additional_urls)))
1951
+ self.write_debug('Additional URLs: "{}"'.format('", "'.join(additional_urls)))
1952
+ ie_result['additional_entries'] = [
1953
+ self.extract_info(
1954
+ url, download, extra_info=extra_info,
1955
+ force_generic_extractor=self.params.get('force_generic_extractor'))
1956
+ for url in additional_urls
1957
+ ]
1958
+ return ie_result
1959
+ elif result_type == 'url':
1960
+ # We have to add extra_info to the results because it may be
1961
+ # contained in a playlist
1962
+ return self.extract_info(
1963
+ ie_result['url'], download,
1964
+ ie_key=ie_result.get('ie_key'),
1965
+ extra_info=extra_info)
1966
+ elif result_type == 'url_transparent':
1967
+ # Use the information from the embedding page
1968
+ info = self.extract_info(
1969
+ ie_result['url'], ie_key=ie_result.get('ie_key'),
1970
+ extra_info=extra_info, download=False, process=False)
1971
+
1972
+ # extract_info may return None when ignoreerrors is enabled and
1973
+ # extraction failed with an error, don't crash and return early
1974
+ # in this case
1975
+ if not info:
1976
+ return info
1977
+
1978
+ exempted_fields = {'_type', 'url', 'ie_key'}
1979
+ if not ie_result.get('section_end') and ie_result.get('section_start') is None:
1980
+ # For video clips, the id etc of the clip extractor should be used
1981
+ exempted_fields |= {'id', 'extractor', 'extractor_key'}
1982
+
1983
+ new_result = info.copy()
1984
+ new_result.update(filter_dict(ie_result, lambda k, v: v is not None and k not in exempted_fields))
1985
+
1986
+ # Extracted info may not be a video result (i.e.
1987
+ # info.get('_type', 'video') != video) but rather an url or
1988
+ # url_transparent. In such cases outer metadata (from ie_result)
1989
+ # should be propagated to inner one (info). For this to happen
1990
+ # _type of info should be overridden with url_transparent. This
1991
+ # fixes issue from https://github.com/ytdl-org/youtube-dl/pull/11163.
1992
+ if new_result.get('_type') == 'url':
1993
+ new_result['_type'] = 'url_transparent'
1994
+
1995
+ return self.process_ie_result(
1996
+ new_result, download=download, extra_info=extra_info)
1997
+ elif result_type in ('playlist', 'multi_video'):
1998
+ # Protect from infinite recursion due to recursively nested playlists
1999
+ # (see https://github.com/ytdl-org/youtube-dl/issues/27833)
2000
+ webpage_url = ie_result.get('webpage_url') # Playlists maynot have webpage_url
2001
+ if webpage_url and webpage_url in self._playlist_urls:
2002
+ self.to_screen(
2003
+ '[download] Skipping already downloaded playlist: {}'.format(
2004
+ ie_result.get('title') or ie_result.get('id')))
2005
+ return
2006
+
2007
+ self._playlist_level += 1
2008
+ self._playlist_urls.add(webpage_url)
2009
+ self._fill_common_fields(ie_result, False)
2010
+ self._sanitize_thumbnails(ie_result)
2011
+ try:
2012
+ return self.__process_playlist(ie_result, download)
2013
+ finally:
2014
+ self._playlist_level -= 1
2015
+ if not self._playlist_level:
2016
+ self._playlist_urls.clear()
2017
+ elif result_type == 'compat_list':
2018
+ self.report_warning(
2019
+ 'Extractor {} returned a compat_list result. '
2020
+ 'It needs to be updated.'.format(ie_result.get('extractor')))
2021
+
2022
+ def _fixup(r):
2023
+ self.add_extra_info(r, {
2024
+ 'extractor': ie_result['extractor'],
2025
+ 'webpage_url': ie_result['webpage_url'],
2026
+ 'webpage_url_basename': url_basename(ie_result['webpage_url']),
2027
+ 'webpage_url_domain': get_domain(ie_result['webpage_url']),
2028
+ 'extractor_key': ie_result['extractor_key'],
2029
+ })
2030
+ return r
2031
+ ie_result['entries'] = [
2032
+ self.process_ie_result(_fixup(r), download, extra_info)
2033
+ for r in ie_result['entries']
2034
+ ]
2035
+ return ie_result
2036
+ else:
2037
+ raise Exception(f'Invalid result type: {result_type}')
2038
+
2039
+ def _ensure_dir_exists(self, path):
2040
+ try:
2041
+ make_parent_dirs(path)
2042
+ return True
2043
+ except OSError as e:
2044
+ self.report_error(f'Unable to create directory: {e}')
2045
+ return False
2046
+
2047
+ @staticmethod
2048
+ def _playlist_infodict(ie_result, strict=False, **kwargs):
2049
+ info = {
2050
+ 'playlist_count': ie_result.get('playlist_count'),
2051
+ 'playlist': ie_result.get('title') or ie_result.get('id'),
2052
+ 'playlist_id': ie_result.get('id'),
2053
+ 'playlist_title': ie_result.get('title'),
2054
+ 'playlist_uploader': ie_result.get('uploader'),
2055
+ 'playlist_uploader_id': ie_result.get('uploader_id'),
2056
+ 'playlist_channel': ie_result.get('channel'),
2057
+ 'playlist_channel_id': ie_result.get('channel_id'),
2058
+ 'playlist_webpage_url': ie_result.get('webpage_url'),
2059
+ **kwargs,
2060
+ }
2061
+ if strict:
2062
+ return info
2063
+ if ie_result.get('webpage_url'):
2064
+ info.update({
2065
+ 'webpage_url': ie_result['webpage_url'],
2066
+ 'webpage_url_basename': url_basename(ie_result['webpage_url']),
2067
+ 'webpage_url_domain': get_domain(ie_result['webpage_url']),
2068
+ })
2069
+ return {
2070
+ **info,
2071
+ 'playlist_index': 0,
2072
+ '__last_playlist_index': max(ie_result.get('requested_entries') or (0, 0)),
2073
+ 'extractor': ie_result['extractor'],
2074
+ 'extractor_key': ie_result['extractor_key'],
2075
+ }
2076
+
2077
+ def __process_playlist(self, ie_result, download):
2078
+ """Process each entry in the playlist"""
2079
+ assert ie_result['_type'] in ('playlist', 'multi_video')
2080
+
2081
+ common_info = self._playlist_infodict(ie_result, strict=True)
2082
+ title = common_info.get('playlist') or '<Untitled>'
2083
+ if self._match_entry(common_info, incomplete=True) is not None:
2084
+ return
2085
+ self.to_screen(f'[download] Downloading {ie_result["_type"]}: {title}')
2086
+
2087
+ all_entries = PlaylistEntries(self, ie_result)
2088
+ entries = orderedSet(all_entries.get_requested_items(), lazy=True)
2089
+
2090
+ lazy = self.params.get('lazy_playlist')
2091
+ if lazy:
2092
+ resolved_entries, n_entries = [], 'N/A'
2093
+ ie_result['requested_entries'], ie_result['entries'] = None, None
2094
+ else:
2095
+ entries = resolved_entries = list(entries)
2096
+ n_entries = len(resolved_entries)
2097
+ ie_result['requested_entries'], ie_result['entries'] = tuple(zip(*resolved_entries, strict=True)) or ([], [])
2098
+ if not ie_result.get('playlist_count'):
2099
+ # Better to do this after potentially exhausting entries
2100
+ ie_result['playlist_count'] = all_entries.get_full_count()
2101
+
2102
+ extra = self._playlist_infodict(ie_result, n_entries=int_or_none(n_entries))
2103
+ ie_copy = collections.ChainMap(ie_result, extra)
2104
+
2105
+ _infojson_written = False
2106
+ write_playlist_files = self.params.get('allow_playlist_files', True)
2107
+ if write_playlist_files and self.params.get('list_thumbnails'):
2108
+ self.list_thumbnails(ie_result)
2109
+ if write_playlist_files and not self.params.get('simulate'):
2110
+ _infojson_written = self._write_info_json(
2111
+ 'playlist', ie_result, self.prepare_filename(ie_copy, 'pl_infojson'))
2112
+ if _infojson_written is None:
2113
+ return
2114
+ if self._write_description('playlist', ie_result,
2115
+ self.prepare_filename(ie_copy, 'pl_description')) is None:
2116
+ return
2117
+ # TODO: This should be passed to ThumbnailsConvertor if necessary
2118
+ self._write_thumbnails('playlist', ie_result, self.prepare_filename(ie_copy, 'pl_thumbnail'))
2119
+
2120
+ if lazy:
2121
+ if self.params.get('playlistreverse') or self.params.get('playlistrandom'):
2122
+ self.report_warning('playlistreverse and playlistrandom are not supported with lazy_playlist', only_once=True)
2123
+ elif self.params.get('playlistreverse'):
2124
+ entries.reverse()
2125
+ elif self.params.get('playlistrandom'):
2126
+ random.shuffle(entries)
2127
+
2128
+ self.to_screen(f'[{ie_result["extractor"]}] Playlist {title}: Downloading {n_entries} items'
2129
+ f'{format_field(ie_result, "playlist_count", " of %s")}')
2130
+
2131
+ keep_resolved_entries = self.params.get('extract_flat') != 'discard'
2132
+ if self.params.get('extract_flat') == 'discard_in_playlist':
2133
+ keep_resolved_entries = ie_result['_type'] != 'playlist'
2134
+ if keep_resolved_entries:
2135
+ self.write_debug('The information of all playlist entries will be held in memory')
2136
+
2137
+ failures = 0
2138
+ max_failures = self.params.get('skip_playlist_after_errors') or float('inf')
2139
+ for i, (playlist_index, entry) in enumerate(entries):
2140
+ if lazy:
2141
+ resolved_entries.append((playlist_index, entry))
2142
+ if not entry:
2143
+ continue
2144
+
2145
+ entry['__x_forwarded_for_ip'] = ie_result.get('__x_forwarded_for_ip')
2146
+ if not lazy and 'playlist-index' in self.params['compat_opts']:
2147
+ playlist_index = ie_result['requested_entries'][i]
2148
+
2149
+ entry_copy = collections.ChainMap(entry, {
2150
+ **common_info,
2151
+ 'n_entries': int_or_none(n_entries),
2152
+ 'playlist_index': playlist_index,
2153
+ 'playlist_autonumber': i + 1,
2154
+ })
2155
+
2156
+ if self._match_entry(entry_copy, incomplete=True) is not None:
2157
+ # For compatabilty with youtube-dl. See https://github.com/yt-dlp/yt-dlp/issues/4369
2158
+ resolved_entries[i] = (playlist_index, NO_DEFAULT)
2159
+ continue
2160
+
2161
+ self.to_screen(
2162
+ f'[download] Downloading item {self._format_screen(i + 1, self.Styles.ID)} '
2163
+ f'of {self._format_screen(n_entries, self.Styles.EMPHASIS)}')
2164
+
2165
+ entry_result = self.__process_iterable_entry(entry, download, collections.ChainMap({
2166
+ 'playlist_index': playlist_index,
2167
+ 'playlist_autonumber': i + 1,
2168
+ }, extra))
2169
+ if not entry_result:
2170
+ failures += 1
2171
+ if failures >= max_failures:
2172
+ self.report_error(
2173
+ f'Skipping the remaining entries in playlist "{title}" since {failures} items failed extraction')
2174
+ break
2175
+ if keep_resolved_entries:
2176
+ resolved_entries[i] = (playlist_index, entry_result)
2177
+
2178
+ # Update with processed data
2179
+ ie_result['entries'] = [e for _, e in resolved_entries if e is not NO_DEFAULT]
2180
+ ie_result['requested_entries'] = [i for i, e in resolved_entries if e is not NO_DEFAULT]
2181
+ if ie_result['requested_entries'] == try_call(lambda: list(range(1, ie_result['playlist_count'] + 1))):
2182
+ # Do not set for full playlist
2183
+ ie_result.pop('requested_entries')
2184
+
2185
+ # Write the updated info to json
2186
+ if _infojson_written is True and self._write_info_json(
2187
+ 'updated playlist', ie_result,
2188
+ self.prepare_filename(ie_copy, 'pl_infojson'), overwrite=True) is None:
2189
+ return
2190
+
2191
+ ie_result = self.run_all_pps('playlist', ie_result)
2192
+ self.to_screen(f'[download] Finished downloading playlist: {title}')
2193
+ return ie_result
2194
+
2195
+ @_handle_extraction_exceptions
2196
+ def __process_iterable_entry(self, entry, download, extra_info):
2197
+ return self.process_ie_result(
2198
+ entry, download=download, extra_info=extra_info)
2199
+
2200
+ def _build_format_filter(self, filter_spec):
2201
+ " Returns a function to filter the formats according to the filter_spec "
2202
+
2203
+ OPERATORS = {
2204
+ '<': operator.lt,
2205
+ '<=': operator.le,
2206
+ '>': operator.gt,
2207
+ '>=': operator.ge,
2208
+ '=': operator.eq,
2209
+ '!=': operator.ne,
2210
+ }
2211
+ operator_rex = re.compile(r'''(?x)\s*
2212
+ (?P<key>[\w.-]+)\s*
2213
+ (?P<op>{})(?P<none_inclusive>\s*\?)?\s*
2214
+ (?P<value>[0-9.]+(?:[kKmMgGtTpPeEzZyY]i?[Bb]?)?)\s*
2215
+ '''.format('|'.join(map(re.escape, OPERATORS.keys()))))
2216
+ m = operator_rex.fullmatch(filter_spec)
2217
+ if m:
2218
+ try:
2219
+ comparison_value = float(m.group('value'))
2220
+ except ValueError:
2221
+ comparison_value = parse_filesize(m.group('value'))
2222
+ if comparison_value is None:
2223
+ comparison_value = parse_filesize(m.group('value') + 'B')
2224
+ if comparison_value is None:
2225
+ raise ValueError(
2226
+ 'Invalid value {!r} in format specification {!r}'.format(
2227
+ m.group('value'), filter_spec))
2228
+ op = OPERATORS[m.group('op')]
2229
+
2230
+ if not m:
2231
+ STR_OPERATORS = {
2232
+ '=': operator.eq,
2233
+ '^=': lambda attr, value: attr.startswith(value),
2234
+ '$=': lambda attr, value: attr.endswith(value),
2235
+ '*=': lambda attr, value: value in attr,
2236
+ '~=': lambda attr, value: value.search(attr) is not None,
2237
+ }
2238
+ str_operator_rex = re.compile(r'''(?x)\s*
2239
+ (?P<key>[a-zA-Z0-9._-]+)\s*
2240
+ (?P<negation>!\s*)?(?P<op>{})\s*(?P<none_inclusive>\?\s*)?
2241
+ (?P<quote>["'])?
2242
+ (?P<value>(?(quote)(?:(?!(?P=quote))[^\\]|\\.)+|[\w.-]+))
2243
+ (?(quote)(?P=quote))\s*
2244
+ '''.format('|'.join(map(re.escape, STR_OPERATORS.keys()))))
2245
+ m = str_operator_rex.fullmatch(filter_spec)
2246
+ if m:
2247
+ if m.group('op') == '~=':
2248
+ comparison_value = re.compile(m.group('value'))
2249
+ else:
2250
+ comparison_value = re.sub(r'''\\([\\"'])''', r'\1', m.group('value'))
2251
+ str_op = STR_OPERATORS[m.group('op')]
2252
+ if m.group('negation'):
2253
+ op = lambda attr, value: not str_op(attr, value)
2254
+ else:
2255
+ op = str_op
2256
+
2257
+ if not m:
2258
+ raise SyntaxError(f'Invalid filter specification {filter_spec!r}')
2259
+
2260
+ def _filter(f):
2261
+ actual_value = f.get(m.group('key'))
2262
+ if actual_value is None:
2263
+ return m.group('none_inclusive')
2264
+ return op(actual_value, comparison_value)
2265
+ return _filter
2266
+
2267
+ def _check_formats(self, formats, warning=True):
2268
+ for f in formats:
2269
+ working = f.get('__working')
2270
+ if working is not None:
2271
+ if working:
2272
+ yield f
2273
+ continue
2274
+ self.to_screen('[info] Testing format {}'.format(f['format_id']))
2275
+ path = self.get_output_path('temp')
2276
+ if not self._ensure_dir_exists(f'{path}/'):
2277
+ continue
2278
+ temp_file = tempfile.NamedTemporaryFile(suffix='.tmp', delete=False, dir=path or None)
2279
+ temp_file.close()
2280
+ # If FragmentFD fails when testing a fragment, it will wrongly set a non-zero return code.
2281
+ # Save the actual return code for later. See https://github.com/yt-dlp/yt-dlp/issues/13750
2282
+ original_retcode = self._download_retcode
2283
+ try:
2284
+ success, _ = self.dl(temp_file.name, f, test=True)
2285
+ except (DownloadError, OSError, ValueError, *network_exceptions):
2286
+ success = False
2287
+ finally:
2288
+ if os.path.exists(temp_file.name):
2289
+ try:
2290
+ os.remove(temp_file.name)
2291
+ except OSError:
2292
+ self.report_warning(f'Unable to delete temporary file "{temp_file.name}"')
2293
+ # Restore the actual return code
2294
+ self._download_retcode = original_retcode
2295
+ f['__working'] = success
2296
+ if success:
2297
+ f.pop('__needs_testing', None)
2298
+ yield f
2299
+ else:
2300
+ msg = f'Unable to download format {f["format_id"]}. Skipping...'
2301
+ if warning:
2302
+ self.report_warning(msg)
2303
+ else:
2304
+ self.to_screen(f'[info] {msg}')
2305
+
2306
+ def _select_formats(self, formats, selector):
2307
+ return list(selector({
2308
+ 'formats': formats,
2309
+ 'has_merged_format': any('none' not in (f.get('acodec'), f.get('vcodec')) for f in formats),
2310
+ 'incomplete_formats': (all(f.get('vcodec') == 'none' for f in formats) # No formats with video
2311
+ or all(f.get('acodec') == 'none' for f in formats)), # OR, No formats with audio
2312
+ }))
2313
+
2314
+ def _default_format_spec(self, info_dict):
2315
+ prefer_best = (
2316
+ self.params['outtmpl']['default'] == '-'
2317
+ or (info_dict.get('is_live') and not self.params.get('live_from_start')))
2318
+
2319
+ def can_merge():
2320
+ merger = FFmpegMergerPP(self)
2321
+ return merger.available and merger.can_merge()
2322
+
2323
+ if not prefer_best and not can_merge():
2324
+ prefer_best = True
2325
+ formats = self._get_formats(info_dict)
2326
+ evaluate_formats = lambda spec: self._select_formats(formats, self.build_format_selector(spec))
2327
+ if evaluate_formats('b/bv+ba') != evaluate_formats('bv*+ba/b'):
2328
+ self.report_warning('ffmpeg not found. The downloaded format may not be the best available. '
2329
+ 'Installing ffmpeg is strongly recommended: https://github.com/yt-dlp/yt-dlp#dependencies')
2330
+
2331
+ compat = (self.params.get('allow_multiple_audio_streams')
2332
+ or 'format-spec' in self.params['compat_opts'])
2333
+
2334
+ return ('best/bestvideo+bestaudio' if prefer_best
2335
+ else 'bestvideo+bestaudio/best' if compat
2336
+ else 'bestvideo*+bestaudio/best')
2337
+
2338
+ def build_format_selector(self, format_spec):
2339
+ def syntax_error(note, start):
2340
+ message = (
2341
+ 'Invalid format specification: '
2342
+ '{}\n\t{}\n\t{}^'.format(note, format_spec, ' ' * start[1]))
2343
+ return SyntaxError(message)
2344
+
2345
+ PICKFIRST = 'PICKFIRST'
2346
+ MERGE = 'MERGE'
2347
+ SINGLE = 'SINGLE'
2348
+ GROUP = 'GROUP'
2349
+ FormatSelector = collections.namedtuple('FormatSelector', ['type', 'selector', 'filters'])
2350
+
2351
+ allow_multiple_streams = {'audio': self.params.get('allow_multiple_audio_streams', False),
2352
+ 'video': self.params.get('allow_multiple_video_streams', False)}
2353
+
2354
+ def _parse_filter(tokens):
2355
+ filter_parts = []
2356
+ for type_, string_, _start, _, _ in tokens:
2357
+ if type_ == tokenize.OP and string_ == ']':
2358
+ return ''.join(filter_parts)
2359
+ else:
2360
+ filter_parts.append(string_)
2361
+
2362
+ def _remove_unused_ops(tokens):
2363
+ # Remove operators that we don't use and join them with the surrounding strings.
2364
+ # E.g. 'mp4' '-' 'baseline' '-' '16x9' is converted to 'mp4-baseline-16x9'
2365
+ ALLOWED_OPS = ('/', '+', ',', '(', ')')
2366
+ last_string, last_start, last_end, last_line = None, None, None, None
2367
+ for type_, string_, start, end, line in tokens:
2368
+ if type_ == tokenize.OP and string_ == '[':
2369
+ if last_string:
2370
+ yield tokenize.NAME, last_string, last_start, last_end, last_line
2371
+ last_string = None
2372
+ yield type_, string_, start, end, line
2373
+ # everything inside brackets will be handled by _parse_filter
2374
+ for type_, string_, start, end, line in tokens:
2375
+ yield type_, string_, start, end, line
2376
+ if type_ == tokenize.OP and string_ == ']':
2377
+ break
2378
+ elif type_ == tokenize.OP and string_ in ALLOWED_OPS:
2379
+ if last_string:
2380
+ yield tokenize.NAME, last_string, last_start, last_end, last_line
2381
+ last_string = None
2382
+ yield type_, string_, start, end, line
2383
+ elif type_ in [tokenize.NAME, tokenize.NUMBER, tokenize.OP]:
2384
+ if not last_string:
2385
+ last_string = string_
2386
+ last_start = start
2387
+ last_end = end
2388
+ else:
2389
+ last_string += string_
2390
+ if last_string:
2391
+ yield tokenize.NAME, last_string, last_start, last_end, last_line
2392
+
2393
+ def _parse_format_selection(tokens, inside_merge=False, inside_choice=False, inside_group=False):
2394
+ selectors = []
2395
+ current_selector = None
2396
+ for type_, string_, start, _, _ in tokens:
2397
+ # ENCODING is only defined in Python 3.x
2398
+ if type_ == getattr(tokenize, 'ENCODING', None):
2399
+ continue
2400
+ elif type_ in [tokenize.NAME, tokenize.NUMBER]:
2401
+ current_selector = FormatSelector(SINGLE, string_, [])
2402
+ elif type_ == tokenize.OP:
2403
+ if string_ == ')':
2404
+ if not inside_group:
2405
+ # ')' will be handled by the parentheses group
2406
+ tokens.restore_last_token()
2407
+ break
2408
+ elif inside_merge and string_ in ['/', ',']:
2409
+ tokens.restore_last_token()
2410
+ break
2411
+ elif inside_choice and string_ == ',':
2412
+ tokens.restore_last_token()
2413
+ break
2414
+ elif string_ == ',':
2415
+ if not current_selector:
2416
+ raise syntax_error('"," must follow a format selector', start)
2417
+ selectors.append(current_selector)
2418
+ current_selector = None
2419
+ elif string_ == '/':
2420
+ if not current_selector:
2421
+ raise syntax_error('"/" must follow a format selector', start)
2422
+ first_choice = current_selector
2423
+ second_choice = _parse_format_selection(tokens, inside_choice=True)
2424
+ current_selector = FormatSelector(PICKFIRST, (first_choice, second_choice), [])
2425
+ elif string_ == '[':
2426
+ if not current_selector:
2427
+ current_selector = FormatSelector(SINGLE, 'best', [])
2428
+ format_filter = _parse_filter(tokens)
2429
+ current_selector.filters.append(format_filter)
2430
+ elif string_ == '(':
2431
+ if current_selector:
2432
+ raise syntax_error('Unexpected "("', start)
2433
+ group = _parse_format_selection(tokens, inside_group=True)
2434
+ current_selector = FormatSelector(GROUP, group, [])
2435
+ elif string_ == '+':
2436
+ if not current_selector:
2437
+ raise syntax_error('Unexpected "+"', start)
2438
+ selector_1 = current_selector
2439
+ selector_2 = _parse_format_selection(tokens, inside_merge=True)
2440
+ if not selector_2:
2441
+ raise syntax_error('Expected a selector', start)
2442
+ current_selector = FormatSelector(MERGE, (selector_1, selector_2), [])
2443
+ else:
2444
+ raise syntax_error(f'Operator not recognized: "{string_}"', start)
2445
+ elif type_ == tokenize.ENDMARKER:
2446
+ break
2447
+ if current_selector:
2448
+ selectors.append(current_selector)
2449
+ return selectors
2450
+
2451
+ def _merge(formats_pair):
2452
+ format_1, format_2 = formats_pair
2453
+
2454
+ formats_info = []
2455
+ formats_info.extend(format_1.get('requested_formats', (format_1,)))
2456
+ formats_info.extend(format_2.get('requested_formats', (format_2,)))
2457
+
2458
+ if not allow_multiple_streams['video'] or not allow_multiple_streams['audio']:
2459
+ get_no_more = {'video': False, 'audio': False}
2460
+ for (i, fmt_info) in enumerate(formats_info):
2461
+ if fmt_info.get('acodec') == fmt_info.get('vcodec') == 'none':
2462
+ formats_info.pop(i)
2463
+ continue
2464
+ for aud_vid in ['audio', 'video']:
2465
+ if not allow_multiple_streams[aud_vid] and fmt_info.get(aud_vid[0] + 'codec') != 'none':
2466
+ if get_no_more[aud_vid]:
2467
+ formats_info.pop(i)
2468
+ break
2469
+ get_no_more[aud_vid] = True
2470
+
2471
+ if len(formats_info) == 1:
2472
+ return formats_info[0]
2473
+
2474
+ video_fmts = [fmt_info for fmt_info in formats_info if fmt_info.get('vcodec') != 'none']
2475
+ audio_fmts = [fmt_info for fmt_info in formats_info if fmt_info.get('acodec') != 'none']
2476
+
2477
+ the_only_video = video_fmts[0] if len(video_fmts) == 1 else None
2478
+ the_only_audio = audio_fmts[0] if len(audio_fmts) == 1 else None
2479
+
2480
+ output_ext = get_compatible_ext(
2481
+ vcodecs=[f.get('vcodec') for f in video_fmts],
2482
+ acodecs=[f.get('acodec') for f in audio_fmts],
2483
+ vexts=[f['ext'] for f in video_fmts],
2484
+ aexts=[f['ext'] for f in audio_fmts],
2485
+ preferences=(try_call(lambda: self.params['merge_output_format'].split('/'))
2486
+ or (self.params.get('prefer_free_formats') and ('webm', 'mkv'))))
2487
+
2488
+ filtered = lambda *keys: filter(None, (traverse_obj(fmt, *keys) for fmt in formats_info))
2489
+
2490
+ new_dict = {
2491
+ 'requested_formats': formats_info,
2492
+ 'format': '+'.join(filtered('format')),
2493
+ 'format_id': '+'.join(filtered('format_id')),
2494
+ 'ext': output_ext,
2495
+ 'protocol': '+'.join(map(determine_protocol, formats_info)),
2496
+ 'language': '+'.join(orderedSet(filtered('language'))) or None,
2497
+ 'format_note': '+'.join(orderedSet(filtered('format_note'))) or None,
2498
+ 'filesize_approx': sum(filtered('filesize', 'filesize_approx')) or None,
2499
+ 'tbr': sum(filtered('tbr', 'vbr', 'abr')),
2500
+ }
2501
+
2502
+ if the_only_video:
2503
+ new_dict.update({
2504
+ 'width': the_only_video.get('width'),
2505
+ 'height': the_only_video.get('height'),
2506
+ 'resolution': the_only_video.get('resolution') or self.format_resolution(the_only_video),
2507
+ 'fps': the_only_video.get('fps'),
2508
+ 'dynamic_range': the_only_video.get('dynamic_range'),
2509
+ 'vcodec': the_only_video.get('vcodec'),
2510
+ 'vbr': the_only_video.get('vbr'),
2511
+ 'stretched_ratio': the_only_video.get('stretched_ratio'),
2512
+ 'aspect_ratio': the_only_video.get('aspect_ratio'),
2513
+ })
2514
+
2515
+ if the_only_audio:
2516
+ new_dict.update({
2517
+ 'acodec': the_only_audio.get('acodec'),
2518
+ 'abr': the_only_audio.get('abr'),
2519
+ 'asr': the_only_audio.get('asr'),
2520
+ 'audio_channels': the_only_audio.get('audio_channels'),
2521
+ })
2522
+
2523
+ return new_dict
2524
+
2525
+ def _check_formats(formats):
2526
+ if self.params.get('check_formats') == 'selected':
2527
+ yield from self._check_formats(formats)
2528
+ return
2529
+ elif (self.params.get('check_formats') is not None
2530
+ or self.params.get('allow_unplayable_formats')):
2531
+ yield from formats
2532
+ return
2533
+
2534
+ for f in formats:
2535
+ if f.get('has_drm') or f.get('__needs_testing'):
2536
+ yield from self._check_formats([f])
2537
+ else:
2538
+ yield f
2539
+
2540
+ def _build_selector_function(selector):
2541
+ if isinstance(selector, list): # ,
2542
+ fs = [_build_selector_function(s) for s in selector]
2543
+
2544
+ def selector_function(ctx):
2545
+ for f in fs:
2546
+ yield from f(ctx)
2547
+ return selector_function
2548
+
2549
+ elif selector.type == GROUP: # ()
2550
+ selector_function = _build_selector_function(selector.selector)
2551
+
2552
+ elif selector.type == PICKFIRST: # /
2553
+ fs = [_build_selector_function(s) for s in selector.selector]
2554
+
2555
+ def selector_function(ctx):
2556
+ for f in fs:
2557
+ picked_formats = list(f(ctx))
2558
+ if picked_formats:
2559
+ return picked_formats
2560
+ return []
2561
+
2562
+ elif selector.type == MERGE: # +
2563
+ selector_1, selector_2 = map(_build_selector_function, selector.selector)
2564
+
2565
+ def selector_function(ctx):
2566
+ for pair in itertools.product(selector_1(ctx), selector_2(ctx)):
2567
+ yield _merge(pair)
2568
+
2569
+ elif selector.type == SINGLE: # atom
2570
+ format_spec = selector.selector or 'best'
2571
+
2572
+ # TODO: Add allvideo, allaudio etc by generalizing the code with best/worst selector
2573
+ if format_spec == 'all':
2574
+ def selector_function(ctx):
2575
+ yield from _check_formats(ctx['formats'][::-1])
2576
+ elif format_spec == 'mergeall':
2577
+ def selector_function(ctx):
2578
+ formats = list(_check_formats(
2579
+ f for f in ctx['formats'] if f.get('vcodec') != 'none' or f.get('acodec') != 'none'))
2580
+ if not formats:
2581
+ return
2582
+ merged_format = formats[-1]
2583
+ for f in formats[-2::-1]:
2584
+ merged_format = _merge((merged_format, f))
2585
+ yield merged_format
2586
+
2587
+ else:
2588
+ format_fallback, seperate_fallback, format_reverse, format_idx = False, None, True, 1
2589
+ mobj = re.match(
2590
+ r'(?P<bw>best|worst|b|w)(?P<type>video|audio|v|a)?(?P<mod>\*)?(?:\.(?P<n>[1-9]\d*))?$',
2591
+ format_spec)
2592
+ if mobj is not None:
2593
+ format_idx = int_or_none(mobj.group('n'), default=1)
2594
+ format_reverse = mobj.group('bw')[0] == 'b'
2595
+ format_type = (mobj.group('type') or [None])[0]
2596
+ not_format_type = {'v': 'a', 'a': 'v'}.get(format_type)
2597
+ format_modified = mobj.group('mod') is not None
2598
+
2599
+ format_fallback = not format_type and not format_modified # for b, w
2600
+ _filter_f = (
2601
+ (lambda f: f.get(f'{format_type}codec') != 'none')
2602
+ if format_type and format_modified # bv*, ba*, wv*, wa*
2603
+ else (lambda f: f.get(f'{not_format_type}codec') == 'none')
2604
+ if format_type # bv, ba, wv, wa
2605
+ else (lambda f: f.get('vcodec') != 'none' and f.get('acodec') != 'none')
2606
+ if not format_modified # b, w
2607
+ else lambda f: True) # b*, w*
2608
+ filter_f = lambda f: _filter_f(f) and (
2609
+ f.get('vcodec') != 'none' or f.get('acodec') != 'none')
2610
+ else:
2611
+ if format_spec in self._format_selection_exts['audio']:
2612
+ filter_f = lambda f: f.get('ext') == format_spec and f.get('acodec') != 'none'
2613
+ elif format_spec in self._format_selection_exts['video']:
2614
+ filter_f = lambda f: f.get('ext') == format_spec and f.get('acodec') != 'none' and f.get('vcodec') != 'none'
2615
+ seperate_fallback = lambda f: f.get('ext') == format_spec and f.get('vcodec') != 'none'
2616
+ elif format_spec in self._format_selection_exts['storyboards']:
2617
+ filter_f = lambda f: f.get('ext') == format_spec and f.get('acodec') == 'none' and f.get('vcodec') == 'none'
2618
+ else:
2619
+ filter_f = lambda f: f.get('format_id') == format_spec # id
2620
+
2621
+ def selector_function(ctx):
2622
+ formats = list(ctx['formats'])
2623
+ matches = list(filter(filter_f, formats)) if filter_f is not None else formats
2624
+ if not matches:
2625
+ if format_fallback and ctx['incomplete_formats']:
2626
+ # for extractors with incomplete formats (audio only (soundcloud)
2627
+ # or video only (imgur)) best/worst will fallback to
2628
+ # best/worst {video,audio}-only format
2629
+ matches = list(filter(lambda f: f.get('vcodec') != 'none' or f.get('acodec') != 'none', formats))
2630
+ elif seperate_fallback and not ctx['has_merged_format']:
2631
+ # for compatibility with youtube-dl when there is no pre-merged format
2632
+ matches = list(filter(seperate_fallback, formats))
2633
+ matches = LazyList(_check_formats(matches[::-1 if format_reverse else 1]))
2634
+ try:
2635
+ yield matches[format_idx - 1]
2636
+ except LazyList.IndexError:
2637
+ return
2638
+
2639
+ filters = [self._build_format_filter(f) for f in selector.filters]
2640
+
2641
+ def final_selector(ctx):
2642
+ ctx_copy = dict(ctx)
2643
+ for _filter in filters:
2644
+ ctx_copy['formats'] = list(filter(_filter, ctx_copy['formats']))
2645
+ return selector_function(ctx_copy)
2646
+ return final_selector
2647
+
2648
+ # HACK: Python 3.12 changed the underlying parser, rendering '7_a' invalid
2649
+ # Prefix numbers with random letters to avoid it being classified as a number
2650
+ # See: https://github.com/yt-dlp/yt-dlp/pulls/8797
2651
+ # TODO: Implement parser not reliant on tokenize.tokenize
2652
+ prefix = ''.join(random.choices(string.ascii_letters, k=32))
2653
+ stream = io.BytesIO(re.sub(r'\d[_\d]*', rf'{prefix}\g<0>', format_spec).encode())
2654
+ try:
2655
+ tokens = list(_remove_unused_ops(
2656
+ token._replace(string=token.string.replace(prefix, ''))
2657
+ for token in tokenize.tokenize(stream.readline)))
2658
+ except tokenize.TokenError:
2659
+ raise syntax_error('Missing closing/opening brackets or parenthesis', (0, len(format_spec)))
2660
+
2661
+ class TokenIterator:
2662
+ def __init__(self, tokens):
2663
+ self.tokens = tokens
2664
+ self.counter = 0
2665
+
2666
+ def __iter__(self):
2667
+ return self
2668
+
2669
+ def __next__(self):
2670
+ if self.counter >= len(self.tokens):
2671
+ raise StopIteration
2672
+ value = self.tokens[self.counter]
2673
+ self.counter += 1
2674
+ return value
2675
+
2676
+ next = __next__
2677
+
2678
+ def restore_last_token(self):
2679
+ self.counter -= 1
2680
+
2681
+ parsed_selector = _parse_format_selection(iter(TokenIterator(tokens)))
2682
+ return _build_selector_function(parsed_selector)
2683
+
2684
+ def _calc_headers(self, info_dict, load_cookies=False):
2685
+ res = HTTPHeaderDict(self.params['http_headers'], info_dict.get('http_headers'))
2686
+ clean_headers(res)
2687
+
2688
+ if load_cookies: # For --load-info-json
2689
+ self._load_cookies(res.get('Cookie'), autoscope=info_dict['url']) # compat
2690
+ self._load_cookies(info_dict.get('cookies'), autoscope=False)
2691
+ # The `Cookie` header is removed to prevent leaks and unscoped cookies.
2692
+ # See: https://github.com/yt-dlp/yt-dlp/security/advisories/GHSA-v8mc-9377-rwjj
2693
+ res.pop('Cookie', None)
2694
+ cookies = self.cookiejar.get_cookies_for_url(info_dict['url'])
2695
+ if cookies:
2696
+ encoder = LenientSimpleCookie()
2697
+ values = []
2698
+ for cookie in cookies:
2699
+ _, value = encoder.value_encode(cookie.value)
2700
+ values.append(f'{cookie.name}={value}')
2701
+ if cookie.domain:
2702
+ values.append(f'Domain={cookie.domain}')
2703
+ if cookie.path:
2704
+ values.append(f'Path={cookie.path}')
2705
+ if cookie.secure:
2706
+ values.append('Secure')
2707
+ if cookie.expires:
2708
+ values.append(f'Expires={cookie.expires}')
2709
+ if cookie.version:
2710
+ values.append(f'Version={cookie.version}')
2711
+ info_dict['cookies'] = '; '.join(values)
2712
+
2713
+ if 'X-Forwarded-For' not in res:
2714
+ x_forwarded_for_ip = info_dict.get('__x_forwarded_for_ip')
2715
+ if x_forwarded_for_ip:
2716
+ res['X-Forwarded-For'] = x_forwarded_for_ip
2717
+
2718
+ return res
2719
+
2720
+ def _calc_cookies(self, url):
2721
+ self.deprecation_warning('"YoutubeDL._calc_cookies" is deprecated and may be removed in a future version')
2722
+ return self.cookiejar.get_cookie_header(url)
2723
+
2724
+ def _sort_thumbnails(self, thumbnails):
2725
+ thumbnails.sort(key=lambda t: (
2726
+ t.get('preference') if t.get('preference') is not None else -1,
2727
+ t.get('width') if t.get('width') is not None else -1,
2728
+ t.get('height') if t.get('height') is not None else -1,
2729
+ t.get('id') if t.get('id') is not None else '',
2730
+ t.get('url')))
2731
+
2732
+ def _sanitize_thumbnails(self, info_dict):
2733
+ thumbnails = info_dict.get('thumbnails')
2734
+ if thumbnails is None:
2735
+ thumbnail = info_dict.get('thumbnail')
2736
+ if thumbnail:
2737
+ info_dict['thumbnails'] = thumbnails = [{'url': thumbnail}]
2738
+ if not thumbnails:
2739
+ return
2740
+
2741
+ def check_thumbnails(thumbnails):
2742
+ for t in thumbnails:
2743
+ self.to_screen(f'[info] Testing thumbnail {t["id"]}')
2744
+ try:
2745
+ self.urlopen(HEADRequest(t['url']))
2746
+ except network_exceptions as err:
2747
+ self.to_screen(f'[info] Unable to connect to thumbnail {t["id"]} URL {t["url"]!r} - {err}. Skipping...')
2748
+ continue
2749
+ yield t
2750
+
2751
+ self._sort_thumbnails(thumbnails)
2752
+ for i, t in enumerate(thumbnails):
2753
+ if t.get('id') is None:
2754
+ t['id'] = str(i)
2755
+ if t.get('width') and t.get('height'):
2756
+ t['resolution'] = '%dx%d' % (t['width'], t['height'])
2757
+ t['url'] = sanitize_url(t['url'])
2758
+
2759
+ if self.params.get('check_formats') is True:
2760
+ info_dict['thumbnails'] = LazyList(check_thumbnails(thumbnails[::-1]), reverse=True)
2761
+ else:
2762
+ info_dict['thumbnails'] = thumbnails
2763
+
2764
+ def _fill_common_fields(self, info_dict, final=True):
2765
+ # TODO: move sanitization here
2766
+ if final:
2767
+ title = info_dict['fulltitle'] = info_dict.get('title')
2768
+ if not title:
2769
+ if title == '':
2770
+ self.write_debug('Extractor gave empty title. Creating a generic title')
2771
+ else:
2772
+ self.report_warning('Extractor failed to obtain "title". Creating a generic title instead')
2773
+ info_dict['title'] = f'{info_dict["extractor"].replace(":", "-")} video #{info_dict["id"]}'
2774
+
2775
+ if info_dict.get('duration') is not None:
2776
+ info_dict['duration_string'] = formatSeconds(info_dict['duration'])
2777
+
2778
+ for ts_key, date_key in (
2779
+ ('timestamp', 'upload_date'),
2780
+ ('release_timestamp', 'release_date'),
2781
+ ('modified_timestamp', 'modified_date'),
2782
+ ):
2783
+ if info_dict.get(date_key) is None and info_dict.get(ts_key) is not None:
2784
+ info_dict[date_key] = strftime_or_none(info_dict[ts_key])
2785
+
2786
+ if not info_dict.get('release_year'):
2787
+ info_dict['release_year'] = traverse_obj(info_dict, ('release_date', {lambda x: int(x[:4])}))
2788
+
2789
+ live_keys = ('is_live', 'was_live')
2790
+ live_status = info_dict.get('live_status')
2791
+ if live_status is None:
2792
+ for key in live_keys:
2793
+ if info_dict.get(key) is False:
2794
+ continue
2795
+ if info_dict.get(key):
2796
+ live_status = key
2797
+ break
2798
+ if all(info_dict.get(key) is False for key in live_keys):
2799
+ live_status = 'not_live'
2800
+ if live_status:
2801
+ info_dict['live_status'] = live_status
2802
+ for key in live_keys:
2803
+ if info_dict.get(key) is None:
2804
+ info_dict[key] = (live_status == key)
2805
+ if live_status == 'post_live':
2806
+ info_dict['was_live'] = True
2807
+
2808
+ # Auto generate title fields corresponding to the *_number fields when missing
2809
+ # in order to always have clean titles. This is very common for TV series.
2810
+ for field in ('chapter', 'season', 'episode'):
2811
+ if final and info_dict.get(f'{field}_number') is not None and not info_dict.get(field):
2812
+ info_dict[field] = '%s %d' % (field.capitalize(), info_dict[f'{field}_number'])
2813
+
2814
+ for old_key, new_key in self._deprecated_multivalue_fields.items():
2815
+ if new_key in info_dict and old_key in info_dict:
2816
+ if '_version' not in info_dict: # HACK: Do not warn when using --load-info-json
2817
+ self.deprecation_warning(f'Do not return {old_key!r} when {new_key!r} is present')
2818
+ elif old_value := info_dict.get(old_key):
2819
+ info_dict[new_key] = old_value.split(', ')
2820
+ elif new_value := info_dict.get(new_key):
2821
+ info_dict[old_key] = ', '.join(v.replace(',', '\N{FULLWIDTH COMMA}') for v in new_value)
2822
+
2823
+ def _raise_pending_errors(self, info):
2824
+ err = info.pop('__pending_error', None)
2825
+ if err:
2826
+ self.report_error(err, tb=False)
2827
+
2828
+ def sort_formats(self, info_dict):
2829
+ formats = self._get_formats(info_dict)
2830
+ formats.sort(key=FormatSorter(
2831
+ self, info_dict.get('_format_sort_fields') or []).calculate_preference)
2832
+
2833
+ def process_video_result(self, info_dict, download=True):
2834
+ assert info_dict.get('_type', 'video') == 'video'
2835
+ self._num_videos += 1
2836
+
2837
+ if 'id' not in info_dict:
2838
+ raise ExtractorError('Missing "id" field in extractor result', ie=info_dict['extractor'])
2839
+ elif not info_dict.get('id'):
2840
+ raise ExtractorError('Extractor failed to obtain "id"', ie=info_dict['extractor'])
2841
+
2842
+ def report_force_conversion(field, field_not, conversion):
2843
+ self.report_warning(
2844
+ f'"{field}" field is not {field_not} - forcing {conversion} conversion, '
2845
+ 'there is an error in extractor')
2846
+
2847
+ def sanitize_string_field(info, string_field):
2848
+ field = info.get(string_field)
2849
+ if field is None or isinstance(field, str):
2850
+ return
2851
+ report_force_conversion(string_field, 'a string', 'string')
2852
+ info[string_field] = str(field)
2853
+
2854
+ def sanitize_numeric_fields(info):
2855
+ for numeric_field in self._NUMERIC_FIELDS:
2856
+ field = info.get(numeric_field)
2857
+ if field is None or isinstance(field, (int, float)):
2858
+ continue
2859
+ report_force_conversion(numeric_field, 'numeric', 'int')
2860
+ info[numeric_field] = int_or_none(field)
2861
+
2862
+ sanitize_string_field(info_dict, 'id')
2863
+ sanitize_numeric_fields(info_dict)
2864
+ if info_dict.get('section_end') and info_dict.get('section_start') is not None:
2865
+ info_dict['duration'] = round(info_dict['section_end'] - info_dict['section_start'], 3)
2866
+ if (info_dict.get('duration') or 0) <= 0 and info_dict.pop('duration', None):
2867
+ self.report_warning('"duration" field is negative, there is an error in extractor')
2868
+
2869
+ chapters = info_dict.get('chapters') or []
2870
+ if chapters and chapters[0].get('start_time'):
2871
+ chapters.insert(0, {'start_time': 0})
2872
+
2873
+ dummy_chapter = {'end_time': 0, 'start_time': info_dict.get('duration')}
2874
+ for idx, (prev, current, next_) in enumerate(zip(
2875
+ (dummy_chapter, *chapters), chapters, (*chapters[1:], dummy_chapter), strict=False), 1):
2876
+ if current.get('start_time') is None:
2877
+ current['start_time'] = prev.get('end_time')
2878
+ if not current.get('end_time'):
2879
+ current['end_time'] = next_.get('start_time')
2880
+ if not current.get('title'):
2881
+ current['title'] = f'<Untitled Chapter {idx}>'
2882
+
2883
+ if 'playlist' not in info_dict:
2884
+ # It isn't part of a playlist
2885
+ info_dict['playlist'] = None
2886
+ info_dict['playlist_index'] = None
2887
+
2888
+ self._sanitize_thumbnails(info_dict)
2889
+
2890
+ thumbnail = info_dict.get('thumbnail')
2891
+ thumbnails = info_dict.get('thumbnails')
2892
+ if thumbnail:
2893
+ info_dict['thumbnail'] = sanitize_url(thumbnail)
2894
+ elif thumbnails:
2895
+ info_dict['thumbnail'] = thumbnails[-1]['url']
2896
+
2897
+ if info_dict.get('display_id') is None and 'id' in info_dict:
2898
+ info_dict['display_id'] = info_dict['id']
2899
+
2900
+ self._fill_common_fields(info_dict)
2901
+
2902
+ for cc_kind in ('subtitles', 'automatic_captions'):
2903
+ cc = info_dict.get(cc_kind)
2904
+ if cc:
2905
+ for _, subtitle in cc.items():
2906
+ for subtitle_format in subtitle:
2907
+ if subtitle_format.get('url'):
2908
+ subtitle_format['url'] = sanitize_url(subtitle_format['url'])
2909
+ if subtitle_format.get('ext') is None:
2910
+ subtitle_format['ext'] = determine_ext(subtitle_format['url']).lower()
2911
+
2912
+ automatic_captions = info_dict.get('automatic_captions')
2913
+ subtitles = info_dict.get('subtitles')
2914
+
2915
+ info_dict['requested_subtitles'] = self.process_subtitles(
2916
+ info_dict['id'], subtitles, automatic_captions)
2917
+
2918
+ formats = self._get_formats(info_dict)
2919
+
2920
+ # Backward compatibility with InfoExtractor._sort_formats
2921
+ field_preference = (formats or [{}])[0].pop('__sort_fields', None)
2922
+ if field_preference:
2923
+ info_dict['_format_sort_fields'] = field_preference
2924
+
2925
+ info_dict['_has_drm'] = any( # or None ensures --clean-infojson removes it
2926
+ f.get('has_drm') and f['has_drm'] != 'maybe' for f in formats) or None
2927
+ if not self.params.get('allow_unplayable_formats'):
2928
+ formats = [f for f in formats if not f.get('has_drm') or f['has_drm'] == 'maybe']
2929
+
2930
+ if formats and all(f.get('acodec') == f.get('vcodec') == 'none' for f in formats):
2931
+ self.report_warning(
2932
+ f'{"This video is DRM protected and " if info_dict["_has_drm"] else ""}'
2933
+ 'only images are available for download. Use --list-formats to see them'.capitalize())
2934
+
2935
+ get_from_start = not info_dict.get('is_live') or bool(self.params.get('live_from_start'))
2936
+ if not get_from_start:
2937
+ info_dict['title'] += ' ' + dt.datetime.now().strftime('%Y-%m-%d %H:%M')
2938
+ if info_dict.get('is_live') and formats:
2939
+ formats = [f for f in formats if bool(f.get('is_from_start')) == get_from_start]
2940
+ if get_from_start and not formats:
2941
+ self.raise_no_formats(info_dict, msg=(
2942
+ '--live-from-start is passed, but there are no formats that can be downloaded from the start. '
2943
+ 'If you want to download from the current time, use --no-live-from-start'))
2944
+
2945
+ def is_wellformed(f):
2946
+ url = f.get('url')
2947
+ if not url:
2948
+ self.report_warning(
2949
+ '"url" field is missing or empty - skipping format, '
2950
+ 'there is an error in extractor')
2951
+ return False
2952
+ if isinstance(url, bytes):
2953
+ sanitize_string_field(f, 'url')
2954
+ return True
2955
+
2956
+ # Filter out malformed formats for better extraction robustness
2957
+ formats = list(filter(is_wellformed, formats or []))
2958
+
2959
+ if not formats:
2960
+ self.raise_no_formats(info_dict)
2961
+
2962
+ for fmt in formats:
2963
+ sanitize_string_field(fmt, 'format_id')
2964
+ sanitize_numeric_fields(fmt)
2965
+ fmt['url'] = sanitize_url(fmt['url'])
2966
+ FormatSorter._fill_sorting_fields(fmt)
2967
+ if fmt['ext'] in ('aac', 'opus', 'mp3', 'flac', 'vorbis'):
2968
+ if fmt.get('acodec') is None:
2969
+ fmt['acodec'] = fmt['ext']
2970
+ if fmt.get('resolution') is None:
2971
+ fmt['resolution'] = self.format_resolution(fmt, default=None)
2972
+ if fmt.get('dynamic_range') is None and fmt.get('vcodec') != 'none':
2973
+ fmt['dynamic_range'] = 'SDR'
2974
+ if fmt.get('aspect_ratio') is None:
2975
+ fmt['aspect_ratio'] = try_call(lambda: round(fmt['width'] / fmt['height'], 2))
2976
+ # For fragmented formats, "tbr" is often max bitrate and not average
2977
+ if (('manifest-filesize-approx' in self.params['compat_opts'] or not fmt.get('manifest_url'))
2978
+ and not fmt.get('filesize') and not fmt.get('filesize_approx')):
2979
+ fmt['filesize_approx'] = filesize_from_tbr(fmt.get('tbr'), info_dict.get('duration'))
2980
+ fmt['http_headers'] = self._calc_headers(collections.ChainMap(fmt, info_dict), load_cookies=True)
2981
+
2982
+ # Safeguard against old/insecure infojson when using --load-info-json
2983
+ if info_dict.get('http_headers'):
2984
+ info_dict['http_headers'] = HTTPHeaderDict(info_dict['http_headers'])
2985
+ info_dict['http_headers'].pop('Cookie', None)
2986
+
2987
+ # This is copied to http_headers by the above _calc_headers and can now be removed
2988
+ if '__x_forwarded_for_ip' in info_dict:
2989
+ del info_dict['__x_forwarded_for_ip']
2990
+
2991
+ self.sort_formats({
2992
+ 'formats': formats,
2993
+ '_format_sort_fields': info_dict.get('_format_sort_fields'),
2994
+ })
2995
+
2996
+ # Sanitize and group by format_id
2997
+ formats_dict = {}
2998
+ for i, fmt in enumerate(formats):
2999
+ if not fmt.get('format_id'):
3000
+ fmt['format_id'] = str(i)
3001
+ else:
3002
+ # Sanitize format_id from characters used in format selector expression
3003
+ fmt['format_id'] = re.sub(r'[\s,/+\[\]()]', '_', fmt['format_id'])
3004
+ formats_dict.setdefault(fmt['format_id'], []).append(fmt)
3005
+
3006
+ # Make sure all formats have unique format_id
3007
+ common_exts = set(itertools.chain(*self._format_selection_exts.values()))
3008
+ for format_id, ambiguous_formats in formats_dict.items():
3009
+ ambigious_id = len(ambiguous_formats) > 1
3010
+ for i, fmt in enumerate(ambiguous_formats):
3011
+ if ambigious_id:
3012
+ fmt['format_id'] = f'{format_id}-{i}'
3013
+ # Ensure there is no conflict between id and ext in format selection
3014
+ # See https://github.com/yt-dlp/yt-dlp/issues/1282
3015
+ if fmt['format_id'] != fmt['ext'] and fmt['format_id'] in common_exts:
3016
+ fmt['format_id'] = 'f{}'.format(fmt['format_id'])
3017
+
3018
+ if fmt.get('format') is None:
3019
+ fmt['format'] = '{id} - {res}{note}'.format(
3020
+ id=fmt['format_id'],
3021
+ res=self.format_resolution(fmt),
3022
+ note=format_field(fmt, 'format_note', ' (%s)'),
3023
+ )
3024
+
3025
+ if self.params.get('check_formats') is True:
3026
+ formats = LazyList(self._check_formats(formats[::-1], warning=False), reverse=True)
3027
+
3028
+ if not formats or formats[0] is not info_dict:
3029
+ # only set the 'formats' fields if the original info_dict list them
3030
+ # otherwise we end up with a circular reference, the first (and unique)
3031
+ # element in the 'formats' field in info_dict is info_dict itself,
3032
+ # which can't be exported to json
3033
+ info_dict['formats'] = formats
3034
+
3035
+ info_dict, _ = self.pre_process(info_dict)
3036
+
3037
+ if self._match_entry(info_dict, incomplete=self._format_fields) is not None:
3038
+ return info_dict
3039
+
3040
+ self.post_extract(info_dict)
3041
+ info_dict, _ = self.pre_process(info_dict, 'after_filter')
3042
+
3043
+ # The pre-processors may have modified the formats
3044
+ formats = self._get_formats(info_dict)
3045
+
3046
+ list_only = self.params.get('simulate') == 'list_only'
3047
+ interactive_format_selection = not list_only and self.format_selector == '-'
3048
+ if self.params.get('list_thumbnails'):
3049
+ self.list_thumbnails(info_dict)
3050
+ if self.params.get('listsubtitles'):
3051
+ if 'automatic_captions' in info_dict:
3052
+ self.list_subtitles(
3053
+ info_dict['id'], automatic_captions, 'automatic captions')
3054
+ self.list_subtitles(info_dict['id'], subtitles, 'subtitles')
3055
+ if self.params.get('listformats') or interactive_format_selection:
3056
+ self.list_formats(info_dict)
3057
+ if list_only:
3058
+ # Without this printing, -F --print-json will not work
3059
+ self.__forced_printings(info_dict)
3060
+ return info_dict
3061
+
3062
+ format_selector = self.format_selector
3063
+ while True:
3064
+ if interactive_format_selection:
3065
+ if not formats:
3066
+ # Bypass interactive format selection if no formats & --ignore-no-formats-error
3067
+ formats_to_download = None
3068
+ break
3069
+ self.to_screen(self._format_screen('\nEnter format selector ', self.Styles.EMPHASIS)
3070
+ + '(Press ENTER for default, or Ctrl+C to quit)'
3071
+ + self._format_screen(': ', self.Styles.EMPHASIS), skip_eol=True)
3072
+ req_format = input()
3073
+ try:
3074
+ format_selector = self.build_format_selector(req_format) if req_format else None
3075
+ except SyntaxError as err:
3076
+ self.report_error(err, tb=False, is_error=False)
3077
+ continue
3078
+
3079
+ if format_selector is None:
3080
+ req_format = self._default_format_spec(info_dict)
3081
+ self.write_debug(f'Default format spec: {req_format}')
3082
+ format_selector = self.build_format_selector(req_format)
3083
+
3084
+ formats_to_download = self._select_formats(formats, format_selector)
3085
+ if interactive_format_selection and not formats_to_download:
3086
+ self.report_error('Requested format is not available', tb=False, is_error=False)
3087
+ continue
3088
+ break
3089
+
3090
+ if not formats_to_download:
3091
+ if not self.params.get('ignore_no_formats_error'):
3092
+ raise ExtractorError(
3093
+ 'Requested format is not available. Use --list-formats for a list of available formats',
3094
+ expected=True, video_id=info_dict['id'], ie=info_dict['extractor'])
3095
+ self.report_warning('Requested format is not available')
3096
+ # Process what we can, even without any available formats.
3097
+ formats_to_download = [{}]
3098
+
3099
+ requested_ranges = tuple(self.params.get('download_ranges', lambda *_: [{}])(info_dict, self))
3100
+ best_format, downloaded_formats = formats_to_download[-1], []
3101
+ if download:
3102
+ if best_format and requested_ranges:
3103
+ def to_screen(*msg):
3104
+ self.to_screen(f'[info] {info_dict["id"]}: {" ".join(", ".join(variadic(m)) for m in msg)}')
3105
+
3106
+ to_screen(f'Downloading {len(formats_to_download)} format(s):',
3107
+ (f['format_id'] for f in formats_to_download))
3108
+ if requested_ranges != ({}, ):
3109
+ to_screen(f'Downloading {len(requested_ranges)} time ranges:',
3110
+ (f'{c["start_time"]:.1f}-{c["end_time"]:.1f}' for c in requested_ranges))
3111
+ max_downloads_reached = False
3112
+
3113
+ for fmt, chapter in itertools.product(formats_to_download, requested_ranges):
3114
+ new_info = self._copy_infodict(info_dict)
3115
+ new_info.update(fmt)
3116
+ offset, duration = info_dict.get('section_start') or 0, info_dict.get('duration') or float('inf')
3117
+ end_time = offset + min(chapter.get('end_time', duration), duration)
3118
+ # duration may not be accurate. So allow deviations <1sec
3119
+ if end_time == float('inf') or end_time > offset + duration + 1:
3120
+ end_time = None
3121
+ if chapter or offset:
3122
+ new_info.update({
3123
+ 'section_start': offset + chapter.get('start_time', 0),
3124
+ 'section_end': end_time,
3125
+ 'section_title': chapter.get('title'),
3126
+ 'section_number': chapter.get('index'),
3127
+ })
3128
+ downloaded_formats.append(new_info)
3129
+ try:
3130
+ self.process_info(new_info)
3131
+ except MaxDownloadsReached:
3132
+ max_downloads_reached = True
3133
+ self._raise_pending_errors(new_info)
3134
+ # Remove copied info
3135
+ for key, val in tuple(new_info.items()):
3136
+ if info_dict.get(key) == val:
3137
+ new_info.pop(key)
3138
+ if max_downloads_reached:
3139
+ break
3140
+
3141
+ write_archive = {f.get('__write_download_archive', False) for f in downloaded_formats}
3142
+ assert write_archive.issubset({True, False, 'ignore'})
3143
+ if True in write_archive and False not in write_archive:
3144
+ self.record_download_archive(info_dict)
3145
+
3146
+ info_dict['requested_downloads'] = downloaded_formats
3147
+ info_dict = self.run_all_pps('after_video', info_dict)
3148
+ if max_downloads_reached:
3149
+ raise MaxDownloadsReached
3150
+
3151
+ # We update the info dict with the selected best quality format (backwards compatibility)
3152
+ info_dict.update(best_format)
3153
+ return info_dict
3154
+
3155
+ def process_subtitles(self, video_id, normal_subtitles, automatic_captions):
3156
+ """Select the requested subtitles and their format"""
3157
+ available_subs, normal_sub_langs = {}, []
3158
+ if normal_subtitles and self.params.get('writesubtitles'):
3159
+ available_subs.update(normal_subtitles)
3160
+ normal_sub_langs = tuple(normal_subtitles.keys())
3161
+ if automatic_captions and self.params.get('writeautomaticsub'):
3162
+ for lang, cap_info in automatic_captions.items():
3163
+ if lang not in available_subs:
3164
+ available_subs[lang] = cap_info
3165
+
3166
+ if not available_subs or (
3167
+ not self.params.get('writesubtitles')
3168
+ and not self.params.get('writeautomaticsub')):
3169
+ return None
3170
+
3171
+ all_sub_langs = tuple(available_subs.keys())
3172
+ if self.params.get('allsubtitles', False):
3173
+ requested_langs = all_sub_langs
3174
+ elif self.params.get('subtitleslangs', False):
3175
+ try:
3176
+ requested_langs = orderedSet_from_options(
3177
+ self.params.get('subtitleslangs'), {'all': all_sub_langs}, use_regex=True)
3178
+ except re.error as e:
3179
+ raise ValueError(f'Wrong regex for subtitlelangs: {e.pattern}')
3180
+ else:
3181
+ requested_langs = LazyList(itertools.chain(
3182
+ ['en'] if 'en' in normal_sub_langs else [],
3183
+ filter(lambda f: f.startswith('en'), normal_sub_langs),
3184
+ ['en'] if 'en' in all_sub_langs else [],
3185
+ filter(lambda f: f.startswith('en'), all_sub_langs),
3186
+ normal_sub_langs, all_sub_langs,
3187
+ ))[:1]
3188
+ if requested_langs:
3189
+ self.to_screen(f'[info] {video_id}: Downloading subtitles: {", ".join(requested_langs)}')
3190
+
3191
+ formats_query = self.params.get('subtitlesformat', 'best')
3192
+ formats_preference = formats_query.split('/') if formats_query else []
3193
+ subs = {}
3194
+ for lang in requested_langs:
3195
+ formats = available_subs.get(lang)
3196
+ if formats is None:
3197
+ self.report_warning(f'{lang} subtitles not available for {video_id}')
3198
+ continue
3199
+ for ext in formats_preference:
3200
+ if ext == 'best':
3201
+ f = formats[-1]
3202
+ break
3203
+ matches = list(filter(lambda f: f['ext'] == ext, formats))
3204
+ if matches:
3205
+ f = matches[-1]
3206
+ break
3207
+ else:
3208
+ f = formats[-1]
3209
+ self.report_warning(
3210
+ 'No subtitle format found matching "{}" for language {}, '
3211
+ 'using {}. Use --list-subs for a list of available subtitles'.format(formats_query, lang, f['ext']))
3212
+ subs[lang] = f
3213
+ return subs
3214
+
3215
+ def _forceprint(self, key, info_dict):
3216
+ if info_dict is None:
3217
+ return
3218
+ info_copy = info_dict.copy()
3219
+ info_copy.setdefault('filename', self.prepare_filename(info_dict))
3220
+ if info_dict.get('requested_formats') is not None:
3221
+ # For RTMP URLs, also include the playpath
3222
+ info_copy['urls'] = '\n'.join(f['url'] + f.get('play_path', '') for f in info_dict['requested_formats'])
3223
+ elif info_dict.get('url'):
3224
+ info_copy['urls'] = info_dict['url'] + info_dict.get('play_path', '')
3225
+ info_copy['formats_table'] = self.render_formats_table(info_dict)
3226
+ info_copy['thumbnails_table'] = self.render_thumbnails_table(info_dict)
3227
+ info_copy['subtitles_table'] = self.render_subtitles_table(info_dict.get('id'), info_dict.get('subtitles'))
3228
+ info_copy['automatic_captions_table'] = self.render_subtitles_table(info_dict.get('id'), info_dict.get('automatic_captions'))
3229
+
3230
+ def format_tmpl(tmpl):
3231
+ mobj = re.fullmatch(r'([\w.:,]|-\d|(?P<dict>{([\w.:,]|-\d)+}))+=?', tmpl)
3232
+ if not mobj:
3233
+ return tmpl
3234
+
3235
+ fmt = '%({})s'
3236
+ if tmpl.startswith('{'):
3237
+ tmpl, fmt = f'.{tmpl}', '%({})j'
3238
+ if tmpl.endswith('='):
3239
+ tmpl, fmt = tmpl[:-1], '{0} = %({0})#j'
3240
+ return '\n'.join(map(fmt.format, [tmpl] if mobj.group('dict') else tmpl.split(',')))
3241
+
3242
+ for tmpl in self.params['forceprint'].get(key, []):
3243
+ self.to_stdout(self.evaluate_outtmpl(format_tmpl(tmpl), info_copy))
3244
+
3245
+ for tmpl, file_tmpl in self.params['print_to_file'].get(key, []):
3246
+ filename = self.prepare_filename(info_dict, outtmpl=file_tmpl)
3247
+ tmpl = format_tmpl(tmpl)
3248
+ self.to_screen(f'[info] Writing {tmpl!r} to: {filename}')
3249
+ if self._ensure_dir_exists(filename):
3250
+ with open(filename, 'a', encoding='utf-8', newline='') as f:
3251
+ f.write(self.evaluate_outtmpl(tmpl, info_copy) + os.linesep)
3252
+
3253
+ return info_copy
3254
+
3255
+ def __forced_printings(self, info_dict, filename=None, incomplete=True):
3256
+ if (self.params.get('forcejson')
3257
+ or self.params['forceprint'].get('video')
3258
+ or self.params['print_to_file'].get('video')):
3259
+ self.post_extract(info_dict)
3260
+ if filename:
3261
+ info_dict['filename'] = filename
3262
+ info_copy = self._forceprint('video', info_dict)
3263
+
3264
+ def print_field(field, actual_field=None, optional=False):
3265
+ if actual_field is None:
3266
+ actual_field = field
3267
+ if self.params.get(f'force{field}') and (
3268
+ info_copy.get(field) is not None or (not optional and not incomplete)):
3269
+ self.to_stdout(info_copy[actual_field])
3270
+
3271
+ print_field('title')
3272
+ print_field('id')
3273
+ print_field('url', 'urls')
3274
+ print_field('thumbnail', optional=True)
3275
+ print_field('description', optional=True)
3276
+ print_field('filename')
3277
+ if self.params.get('forceduration') and info_copy.get('duration') is not None:
3278
+ self.to_stdout(formatSeconds(info_copy['duration']))
3279
+ print_field('format')
3280
+
3281
+ if self.params.get('forcejson'):
3282
+ self.to_stdout(json.dumps(self.sanitize_info(info_dict)))
3283
+
3284
+ def dl(self, name, info, subtitle=False, test=False):
3285
+ if not info.get('url'):
3286
+ self.raise_no_formats(info, True)
3287
+
3288
+ if test:
3289
+ verbose = self.params.get('verbose')
3290
+ quiet = self.params.get('quiet') or not verbose
3291
+ params = {
3292
+ 'test': True,
3293
+ 'quiet': quiet,
3294
+ 'verbose': verbose,
3295
+ 'noprogress': quiet,
3296
+ 'nopart': True,
3297
+ 'skip_unavailable_fragments': False,
3298
+ 'keep_fragments': False,
3299
+ 'overwrites': True,
3300
+ '_no_ytdl_file': True,
3301
+ }
3302
+ else:
3303
+ params = self.params
3304
+
3305
+ fd = get_suitable_downloader(info, params, to_stdout=(name == '-'))(self, params)
3306
+ if not test:
3307
+ for ph in self._progress_hooks:
3308
+ fd.add_progress_hook(ph)
3309
+ urls = '", "'.join(
3310
+ (f['url'].split(',')[0] + ',<data>' if f['url'].startswith('data:') else f['url'])
3311
+ for f in info.get('requested_formats', []) or [info])
3312
+ self.write_debug(f'Invoking {fd.FD_NAME} downloader on "{urls}"')
3313
+
3314
+ # Note: Ideally info should be a deep-copied so that hooks cannot modify it.
3315
+ # But it may contain objects that are not deep-copyable
3316
+ new_info = self._copy_infodict(info)
3317
+ if new_info.get('http_headers') is None:
3318
+ new_info['http_headers'] = self._calc_headers(new_info)
3319
+ return fd.download(name, new_info, subtitle)
3320
+
3321
+ def existing_file(self, filepaths, *, default_overwrite=True):
3322
+ existing_files = list(filter(os.path.exists, orderedSet(filepaths)))
3323
+ if existing_files and not self.params.get('overwrites', default_overwrite):
3324
+ return existing_files[0]
3325
+
3326
+ for file in existing_files:
3327
+ self.report_file_delete(file)
3328
+ os.remove(file)
3329
+ return None
3330
+
3331
+ @_catch_unsafe_extension_error
3332
+ def process_info(self, info_dict):
3333
+ """Process a single resolved IE result. (Modifies it in-place)"""
3334
+
3335
+ assert info_dict.get('_type', 'video') == 'video'
3336
+ original_infodict = info_dict
3337
+
3338
+ if 'format' not in info_dict and 'ext' in info_dict:
3339
+ info_dict['format'] = info_dict['ext']
3340
+
3341
+ if self._match_entry(info_dict) is not None:
3342
+ info_dict['__write_download_archive'] = 'ignore'
3343
+ return
3344
+
3345
+ # Does nothing under normal operation - for backward compatibility of process_info
3346
+ self.post_extract(info_dict)
3347
+
3348
+ def replace_info_dict(new_info):
3349
+ nonlocal info_dict
3350
+ if new_info == info_dict:
3351
+ return
3352
+ info_dict.clear()
3353
+ info_dict.update(new_info)
3354
+
3355
+ new_info, _ = self.pre_process(info_dict, 'video')
3356
+ replace_info_dict(new_info)
3357
+ self._num_downloads += 1
3358
+
3359
+ # info_dict['_filename'] needs to be set for backward compatibility
3360
+ info_dict['_filename'] = full_filename = self.prepare_filename(info_dict, warn=True)
3361
+ temp_filename = self.prepare_filename(info_dict, 'temp')
3362
+ files_to_move = {}
3363
+
3364
+ # Forced printings
3365
+ self.__forced_printings(info_dict, full_filename, incomplete=('format' not in info_dict))
3366
+
3367
+ def check_max_downloads():
3368
+ if self._num_downloads >= float(self.params.get('max_downloads') or 'inf'):
3369
+ raise MaxDownloadsReached
3370
+
3371
+ if self.params.get('simulate'):
3372
+ info_dict['__write_download_archive'] = self.params.get('force_write_download_archive')
3373
+ check_max_downloads()
3374
+ return
3375
+
3376
+ if full_filename is None:
3377
+ return
3378
+ if not self._ensure_dir_exists(full_filename):
3379
+ return
3380
+ if not self._ensure_dir_exists(temp_filename):
3381
+ return
3382
+
3383
+ if self._write_description('video', info_dict,
3384
+ self.prepare_filename(info_dict, 'description')) is None:
3385
+ return
3386
+
3387
+ sub_files = self._write_subtitles(info_dict, temp_filename)
3388
+ if sub_files is None:
3389
+ return
3390
+ files_to_move.update(dict(sub_files))
3391
+
3392
+ thumb_files = self._write_thumbnails(
3393
+ 'video', info_dict, temp_filename, self.prepare_filename(info_dict, 'thumbnail'))
3394
+ if thumb_files is None:
3395
+ return
3396
+ files_to_move.update(dict(thumb_files))
3397
+
3398
+ infofn = self.prepare_filename(info_dict, 'infojson')
3399
+ _infojson_written = self._write_info_json('video', info_dict, infofn)
3400
+ if _infojson_written:
3401
+ info_dict['infojson_filename'] = infofn
3402
+ # For backward compatibility, even though it was a private field
3403
+ info_dict['__infojson_filename'] = infofn
3404
+ elif _infojson_written is None:
3405
+ return
3406
+
3407
+ # Write internet shortcut files
3408
+ def _write_link_file(link_type):
3409
+ url = try_get(info_dict['webpage_url'], iri_to_uri)
3410
+ if not url:
3411
+ self.report_warning(
3412
+ f'Cannot write internet shortcut file because the actual URL of "{info_dict["webpage_url"]}" is unknown')
3413
+ return True
3414
+ linkfn = replace_extension(
3415
+ self.prepare_filename(info_dict, 'link'), link_type,
3416
+ info_dict.get('ext'), _allowed_exts=tuple(LINK_TEMPLATES))
3417
+ if not self._ensure_dir_exists(linkfn):
3418
+ return False
3419
+ if self.params.get('overwrites', True) and os.path.exists(linkfn):
3420
+ self.to_screen(f'[info] Internet shortcut (.{link_type}) is already present')
3421
+ return True
3422
+ try:
3423
+ self.to_screen(f'[info] Writing internet shortcut (.{link_type}) to: {linkfn}')
3424
+ with open(to_high_limit_path(linkfn), 'w', encoding='utf-8',
3425
+ newline='\r\n' if link_type == 'url' else '\n') as linkfile:
3426
+ template_vars = {'url': url}
3427
+ if link_type == 'desktop':
3428
+ template_vars['filename'] = linkfn[:-(len(link_type) + 1)]
3429
+ linkfile.write(LINK_TEMPLATES[link_type] % template_vars)
3430
+ except OSError:
3431
+ self.report_error(f'Cannot write internet shortcut {linkfn}')
3432
+ return False
3433
+ return True
3434
+
3435
+ write_links = {
3436
+ 'url': self.params.get('writeurllink'),
3437
+ 'webloc': self.params.get('writewebloclink'),
3438
+ 'desktop': self.params.get('writedesktoplink'),
3439
+ }
3440
+ if self.params.get('writelink'):
3441
+ link_type = ('webloc' if sys.platform == 'darwin'
3442
+ else 'desktop' if sys.platform.startswith('linux')
3443
+ else 'url')
3444
+ write_links[link_type] = True
3445
+
3446
+ if any(should_write and not _write_link_file(link_type)
3447
+ for link_type, should_write in write_links.items()):
3448
+ return
3449
+
3450
+ new_info, files_to_move = self.pre_process(info_dict, 'before_dl', files_to_move)
3451
+ replace_info_dict(new_info)
3452
+
3453
+ if self.params.get('skip_download'):
3454
+ info_dict['filepath'] = temp_filename
3455
+ info_dict['__finaldir'] = os.path.dirname(os.path.abspath(full_filename))
3456
+ info_dict['__files_to_move'] = files_to_move
3457
+ replace_info_dict(self.run_pp(MoveFilesAfterDownloadPP(self, False), info_dict))
3458
+ info_dict['__write_download_archive'] = self.params.get('force_write_download_archive')
3459
+ else:
3460
+ # Download
3461
+ info_dict.setdefault('__postprocessors', [])
3462
+ try:
3463
+
3464
+ def existing_video_file(*filepaths):
3465
+ ext = info_dict.get('ext')
3466
+ converted = lambda file: replace_extension(file, self.params.get('final_ext') or ext, ext)
3467
+ file = self.existing_file(itertools.chain(*zip(map(converted, filepaths), filepaths, strict=True)),
3468
+ default_overwrite=False)
3469
+ if file:
3470
+ info_dict['ext'] = os.path.splitext(file)[1][1:]
3471
+ return file
3472
+
3473
+ fd, success = None, True
3474
+ if info_dict.get('protocol') or info_dict.get('url'):
3475
+ fd = get_suitable_downloader(info_dict, self.params, to_stdout=temp_filename == '-')
3476
+ if fd != FFmpegFD and 'no-direct-merge' not in self.params['compat_opts'] and (
3477
+ info_dict.get('section_start') or info_dict.get('section_end')):
3478
+ msg = ('This format cannot be partially downloaded' if FFmpegFD.available()
3479
+ else 'You have requested downloading the video partially, but ffmpeg is not installed')
3480
+ self.report_error(f'{msg}. Aborting')
3481
+ return
3482
+
3483
+ if info_dict.get('requested_formats') is not None:
3484
+ old_ext = info_dict['ext']
3485
+ if self.params.get('merge_output_format') is None:
3486
+ if (info_dict['ext'] == 'webm'
3487
+ and info_dict.get('thumbnails')
3488
+ # check with type instead of pp_key, __name__, or isinstance
3489
+ # since we dont want any custom PPs to trigger this
3490
+ and any(type(pp) == EmbedThumbnailPP for pp in self._pps['post_process'])): # noqa: E721
3491
+ info_dict['ext'] = 'mkv'
3492
+ self.report_warning(
3493
+ 'webm doesn\'t support embedding a thumbnail, mkv will be used')
3494
+ new_ext = info_dict['ext']
3495
+
3496
+ def correct_ext(filename, ext=new_ext):
3497
+ if filename == '-':
3498
+ return filename
3499
+ filename_real_ext = os.path.splitext(filename)[1][1:]
3500
+ filename_wo_ext = (
3501
+ os.path.splitext(filename)[0]
3502
+ if filename_real_ext in (old_ext, new_ext)
3503
+ else filename)
3504
+ return f'{filename_wo_ext}.{ext}'
3505
+
3506
+ # Ensure filename always has a correct extension for successful merge
3507
+ full_filename = correct_ext(full_filename)
3508
+ temp_filename = correct_ext(temp_filename)
3509
+ dl_filename = existing_video_file(full_filename, temp_filename)
3510
+
3511
+ info_dict['__real_download'] = False
3512
+ # NOTE: Copy so that original format dicts are not modified
3513
+ info_dict['requested_formats'] = list(map(dict, info_dict['requested_formats']))
3514
+
3515
+ merger = FFmpegMergerPP(self)
3516
+ downloaded = []
3517
+ if dl_filename is not None:
3518
+ self.report_file_already_downloaded(dl_filename)
3519
+ elif fd:
3520
+ if fd != FFmpegFD and temp_filename != '-':
3521
+ for f in info_dict['requested_formats']:
3522
+ f['filepath'] = fname = prepend_extension(
3523
+ correct_ext(temp_filename, info_dict['ext']),
3524
+ 'f{}'.format(f['format_id']), info_dict['ext'])
3525
+ downloaded.append(fname)
3526
+ info_dict['url'] = '\n'.join(f['url'] for f in info_dict['requested_formats'])
3527
+ success, real_download = self.dl(temp_filename, info_dict)
3528
+ info_dict['__real_download'] = real_download
3529
+ else:
3530
+ if self.params.get('allow_unplayable_formats'):
3531
+ self.report_warning(
3532
+ 'You have requested merging of multiple formats '
3533
+ 'while also allowing unplayable formats to be downloaded. '
3534
+ 'The formats won\'t be merged to prevent data corruption.')
3535
+ elif not merger.available:
3536
+ msg = 'You have requested merging of multiple formats but ffmpeg is not installed'
3537
+ if not self.params.get('ignoreerrors'):
3538
+ self.report_error(f'{msg}. Aborting due to --abort-on-error')
3539
+ return
3540
+ self.report_warning(f'{msg}. The formats won\'t be merged')
3541
+
3542
+ if temp_filename == '-':
3543
+ reason = ('using a downloader other than ffmpeg' if FFmpegFD.can_merge_formats(info_dict, self.params)
3544
+ else 'but the formats are incompatible for simultaneous download' if merger.available
3545
+ else 'but ffmpeg is not installed')
3546
+ self.report_warning(
3547
+ f'You have requested downloading multiple formats to stdout {reason}. '
3548
+ 'The formats will be streamed one after the other')
3549
+ fname = temp_filename
3550
+ for f in info_dict['requested_formats']:
3551
+ new_info = dict(info_dict)
3552
+ del new_info['requested_formats']
3553
+ new_info.update(f)
3554
+ if temp_filename != '-':
3555
+ fname = prepend_extension(
3556
+ correct_ext(temp_filename, new_info['ext']),
3557
+ 'f{}'.format(f['format_id']), new_info['ext'])
3558
+ if not self._ensure_dir_exists(fname):
3559
+ return
3560
+ f['filepath'] = fname
3561
+ downloaded.append(fname)
3562
+ partial_success, real_download = self.dl(fname, new_info)
3563
+ info_dict['__real_download'] = info_dict['__real_download'] or real_download
3564
+ success = success and partial_success
3565
+
3566
+ if downloaded and merger.available and not self.params.get('allow_unplayable_formats'):
3567
+ info_dict['__postprocessors'].append(merger)
3568
+ info_dict['__files_to_merge'] = downloaded
3569
+ # Even if there were no downloads, it is being merged only now
3570
+ info_dict['__real_download'] = True
3571
+ else:
3572
+ for file in downloaded:
3573
+ files_to_move[file] = None
3574
+ else:
3575
+ # Just a single file
3576
+ dl_filename = existing_video_file(full_filename, temp_filename)
3577
+ if dl_filename is None or dl_filename == temp_filename:
3578
+ # dl_filename == temp_filename could mean that the file was partially downloaded with --no-part.
3579
+ # So we should try to resume the download
3580
+ success, real_download = self.dl(temp_filename, info_dict)
3581
+ info_dict['__real_download'] = real_download
3582
+ else:
3583
+ self.report_file_already_downloaded(dl_filename)
3584
+
3585
+ dl_filename = dl_filename or temp_filename
3586
+ info_dict['__finaldir'] = os.path.dirname(os.path.abspath(full_filename))
3587
+
3588
+ except network_exceptions as err:
3589
+ self.report_error(f'unable to download video data: {err}')
3590
+ return
3591
+ except OSError as err:
3592
+ raise UnavailableVideoError(err)
3593
+ except ContentTooShortError as err:
3594
+ self.report_error(f'content too short (expected {err.expected} bytes and served {err.downloaded})')
3595
+ return
3596
+
3597
+ self._raise_pending_errors(info_dict)
3598
+ if success and full_filename != '-':
3599
+
3600
+ def fixup():
3601
+ do_fixup = True
3602
+ fixup_policy = self.params.get('fixup')
3603
+ vid = info_dict['id']
3604
+
3605
+ if fixup_policy in ('ignore', 'never'):
3606
+ return
3607
+ elif fixup_policy == 'warn':
3608
+ do_fixup = 'warn'
3609
+ elif fixup_policy != 'force':
3610
+ assert fixup_policy in ('detect_or_warn', None)
3611
+ if not info_dict.get('__real_download'):
3612
+ do_fixup = False
3613
+
3614
+ def ffmpeg_fixup(cndn, msg, cls):
3615
+ if not (do_fixup and cndn):
3616
+ return
3617
+ elif do_fixup == 'warn':
3618
+ self.report_warning(f'{vid}: {msg}')
3619
+ return
3620
+ pp = cls(self)
3621
+ if pp.available:
3622
+ info_dict['__postprocessors'].append(pp)
3623
+ else:
3624
+ self.report_warning(f'{vid}: {msg}. Install ffmpeg to fix this automatically')
3625
+
3626
+ stretched_ratio = info_dict.get('stretched_ratio')
3627
+ ffmpeg_fixup(stretched_ratio not in (1, None),
3628
+ f'Non-uniform pixel ratio {stretched_ratio}',
3629
+ FFmpegFixupStretchedPP)
3630
+
3631
+ downloader = get_suitable_downloader(info_dict, self.params) if 'protocol' in info_dict else None
3632
+ downloader = downloader.FD_NAME if downloader else None
3633
+
3634
+ ext = info_dict.get('ext')
3635
+ postprocessed_by_ffmpeg = info_dict.get('requested_formats') or any((
3636
+ isinstance(pp, FFmpegVideoConvertorPP)
3637
+ and resolve_recode_mapping(ext, pp.mapping)[0] not in (ext, None)
3638
+ ) for pp in self._pps['post_process'])
3639
+
3640
+ if not postprocessed_by_ffmpeg:
3641
+ ffmpeg_fixup(fd != FFmpegFD and ext == 'm4a'
3642
+ and info_dict.get('container') == 'm4a_dash',
3643
+ 'writing DASH m4a. Only some players support this container',
3644
+ FFmpegFixupM4aPP)
3645
+ ffmpeg_fixup((downloader == 'hlsnative' and not self.params.get('hls_use_mpegts'))
3646
+ or (info_dict.get('is_live') and self.params.get('hls_use_mpegts') is None),
3647
+ 'Possible MPEG-TS in MP4 container or malformed AAC timestamps',
3648
+ FFmpegFixupM3u8PP)
3649
+ ffmpeg_fixup(downloader == 'dashsegments'
3650
+ and (info_dict.get('is_live') or info_dict.get('is_dash_periods')),
3651
+ 'Possible duplicate MOOV atoms', FFmpegFixupDuplicateMoovPP)
3652
+
3653
+ ffmpeg_fixup(downloader == 'web_socket_fragment', 'Malformed timestamps detected', FFmpegFixupTimestampPP)
3654
+ ffmpeg_fixup(downloader == 'web_socket_fragment', 'Malformed duration detected', FFmpegFixupDurationPP)
3655
+
3656
+ fixup()
3657
+ try:
3658
+ replace_info_dict(self.post_process(dl_filename, info_dict, files_to_move))
3659
+ except PostProcessingError as err:
3660
+ self.report_error(f'Postprocessing: {err}')
3661
+ return
3662
+ try:
3663
+ for ph in self._post_hooks:
3664
+ ph(info_dict['filepath'])
3665
+ except Exception as err:
3666
+ self.report_error(f'post hooks: {err}')
3667
+ return
3668
+ info_dict['__write_download_archive'] = True
3669
+
3670
+ assert info_dict is original_infodict # Make sure the info_dict was modified in-place
3671
+ if self.params.get('force_write_download_archive'):
3672
+ info_dict['__write_download_archive'] = True
3673
+ check_max_downloads()
3674
+
3675
+ def __download_wrapper(self, func):
3676
+ @functools.wraps(func)
3677
+ def wrapper(*args, **kwargs):
3678
+ try:
3679
+ res = func(*args, **kwargs)
3680
+ except CookieLoadError:
3681
+ raise
3682
+ except UnavailableVideoError as e:
3683
+ self.report_error(e)
3684
+ except DownloadCancelled as e:
3685
+ self.to_screen(f'[info] {e}')
3686
+ if not self.params.get('break_per_url'):
3687
+ raise
3688
+ self._num_downloads = 0
3689
+ else:
3690
+ if self.params.get('dump_single_json', False):
3691
+ self.post_extract(res)
3692
+ self.to_stdout(json.dumps(self.sanitize_info(res)))
3693
+ return wrapper
3694
+
3695
+ def download(self, url_list):
3696
+ """Download a given list of URLs."""
3697
+ url_list = variadic(url_list) # Passing a single URL is a common mistake
3698
+ outtmpl = self.params['outtmpl']['default']
3699
+ if (len(url_list) > 1
3700
+ and outtmpl != '-'
3701
+ and '%' not in outtmpl
3702
+ and self.params.get('max_downloads') != 1):
3703
+ raise SameFileError(outtmpl)
3704
+
3705
+ for url in url_list:
3706
+ self.__download_wrapper(self.extract_info)(
3707
+ url, force_generic_extractor=self.params.get('force_generic_extractor', False))
3708
+
3709
+ return self._download_retcode
3710
+
3711
+ def download_with_info_file(self, info_filename):
3712
+ with contextlib.closing(fileinput.FileInput(
3713
+ [info_filename], mode='r',
3714
+ openhook=fileinput.hook_encoded('utf-8'))) as f:
3715
+ # FileInput doesn't have a read method, we can't call json.load
3716
+ infos = [self.sanitize_info(info, self.params.get('clean_infojson', True))
3717
+ for info in variadic(json.loads('\n'.join(f)))]
3718
+ for info in infos:
3719
+ try:
3720
+ self.__download_wrapper(self.process_ie_result)(info, download=True)
3721
+ except (DownloadError, EntryNotInPlaylist, ReExtractInfo) as e:
3722
+ if not isinstance(e, EntryNotInPlaylist):
3723
+ self.to_stderr('\r')
3724
+ webpage_url = info.get('webpage_url')
3725
+ if webpage_url is None:
3726
+ raise
3727
+ self.report_warning(f'The info failed to download: {e}; trying with URL {webpage_url}')
3728
+ self.download([webpage_url])
3729
+ except ExtractorError as e:
3730
+ self.report_error(e)
3731
+ return self._download_retcode
3732
+
3733
+ @staticmethod
3734
+ def sanitize_info(info_dict, remove_private_keys=False):
3735
+ """ Sanitize the infodict for converting to json """
3736
+ if info_dict is None:
3737
+ return info_dict
3738
+ info_dict.setdefault('epoch', int(time.time()))
3739
+ info_dict.setdefault('_type', 'video')
3740
+ info_dict.setdefault('_version', {
3741
+ 'version': __version__,
3742
+ 'current_git_head': current_git_head(),
3743
+ 'release_git_head': RELEASE_GIT_HEAD,
3744
+ 'repository': ORIGIN,
3745
+ })
3746
+
3747
+ if remove_private_keys:
3748
+ reject = lambda k, v: v is None or k.startswith('__') or k in {
3749
+ 'requested_downloads', 'requested_formats', 'requested_subtitles', 'requested_entries',
3750
+ 'entries', 'filepath', '_filename', 'filename', 'infojson_filename', 'original_url',
3751
+ 'playlist_autonumber',
3752
+ }
3753
+ else:
3754
+ reject = lambda k, v: False
3755
+
3756
+ def filter_fn(obj):
3757
+ if isinstance(obj, dict):
3758
+ return {k: filter_fn(v) for k, v in obj.items() if not reject(k, v)}
3759
+ elif isinstance(obj, (list, tuple, set, LazyList)):
3760
+ return list(map(filter_fn, obj))
3761
+ elif isinstance(obj, ImpersonateTarget):
3762
+ return str(obj)
3763
+ elif obj is None or isinstance(obj, (str, int, float, bool)):
3764
+ return obj
3765
+ else:
3766
+ return repr(obj)
3767
+
3768
+ return filter_fn(info_dict)
3769
+
3770
+ @staticmethod
3771
+ def filter_requested_info(info_dict, actually_filter=True):
3772
+ """ Alias of sanitize_info for backward compatibility """
3773
+ return YoutubeDL.sanitize_info(info_dict, actually_filter)
3774
+
3775
+ def _delete_downloaded_files(self, *files_to_delete, info={}, msg=None):
3776
+ for filename in set(filter(None, files_to_delete)):
3777
+ if msg:
3778
+ self.to_screen(msg % filename)
3779
+ try:
3780
+ os.remove(filename)
3781
+ except OSError:
3782
+ self.report_warning(f'Unable to delete file {filename}')
3783
+ if filename in info.get('__files_to_move', []): # NB: Delete even if None
3784
+ del info['__files_to_move'][filename]
3785
+
3786
+ @staticmethod
3787
+ def post_extract(info_dict):
3788
+ def actual_post_extract(info_dict):
3789
+ if info_dict.get('_type') in ('playlist', 'multi_video'):
3790
+ for video_dict in info_dict.get('entries', {}):
3791
+ actual_post_extract(video_dict or {})
3792
+ return
3793
+
3794
+ post_extractor = info_dict.pop('__post_extractor', None) or dict
3795
+ info_dict.update(post_extractor())
3796
+
3797
+ actual_post_extract(info_dict or {})
3798
+
3799
+ def run_pp(self, pp, infodict):
3800
+ files_to_delete = []
3801
+ if '__files_to_move' not in infodict:
3802
+ infodict['__files_to_move'] = {}
3803
+ try:
3804
+ files_to_delete, infodict = pp.run(infodict)
3805
+ except PostProcessingError as e:
3806
+ # Must be True and not 'only_download'
3807
+ if self.params.get('ignoreerrors') is True:
3808
+ self.report_error(e)
3809
+ return infodict
3810
+ raise
3811
+
3812
+ if not files_to_delete:
3813
+ return infodict
3814
+ if self.params.get('keepvideo', False):
3815
+ for f in files_to_delete:
3816
+ infodict['__files_to_move'].setdefault(f, '')
3817
+ else:
3818
+ self._delete_downloaded_files(
3819
+ *files_to_delete, info=infodict, msg='Deleting original file %s (pass -k to keep)')
3820
+ return infodict
3821
+
3822
+ def run_all_pps(self, key, info, *, additional_pps=None):
3823
+ if key != 'video':
3824
+ self._forceprint(key, info)
3825
+ for pp in (additional_pps or []) + self._pps[key]:
3826
+ info = self.run_pp(pp, info)
3827
+ return info
3828
+
3829
+ def pre_process(self, ie_info, key='pre_process', files_to_move=None):
3830
+ info = dict(ie_info)
3831
+ info['__files_to_move'] = files_to_move or {}
3832
+ try:
3833
+ info = self.run_all_pps(key, info)
3834
+ except PostProcessingError as err:
3835
+ msg = f'Preprocessing: {err}'
3836
+ info.setdefault('__pending_error', msg)
3837
+ self.report_error(msg, is_error=False)
3838
+ return info, info.pop('__files_to_move', None)
3839
+
3840
+ def post_process(self, filename, info, files_to_move=None):
3841
+ """Run all the postprocessors on the given file."""
3842
+ info['filepath'] = filename
3843
+ info['__files_to_move'] = files_to_move or {}
3844
+ info = self.run_all_pps('post_process', info, additional_pps=info.get('__postprocessors'))
3845
+ info = self.run_pp(MoveFilesAfterDownloadPP(self), info)
3846
+ del info['__files_to_move']
3847
+ return self.run_all_pps('after_move', info)
3848
+
3849
+ def _make_archive_id(self, info_dict):
3850
+ video_id = info_dict.get('id')
3851
+ if not video_id:
3852
+ return
3853
+ # Future-proof against any change in case
3854
+ # and backwards compatibility with prior versions
3855
+ extractor = info_dict.get('extractor_key') or info_dict.get('ie_key') # key in a playlist
3856
+ if extractor is None:
3857
+ url = str_or_none(info_dict.get('url'))
3858
+ if not url:
3859
+ return
3860
+ # Try to find matching extractor for the URL and take its ie_key
3861
+ for ie_key, ie in self._ies.items():
3862
+ if ie.suitable(url):
3863
+ extractor = ie_key
3864
+ break
3865
+ else:
3866
+ return
3867
+ return make_archive_id(extractor, video_id)
3868
+
3869
+ def in_download_archive(self, info_dict):
3870
+ if not self.archive:
3871
+ return False
3872
+
3873
+ vid_ids = [self._make_archive_id(info_dict)]
3874
+ vid_ids.extend(info_dict.get('_old_archive_ids') or [])
3875
+ return any(id_ in self.archive for id_ in vid_ids)
3876
+
3877
+ def record_download_archive(self, info_dict):
3878
+ fn = self.params.get('download_archive')
3879
+ if fn is None:
3880
+ return
3881
+ vid_id = self._make_archive_id(info_dict)
3882
+ assert vid_id
3883
+
3884
+ self.write_debug(f'Adding to archive: {vid_id}')
3885
+ if is_path_like(fn):
3886
+ with locked_file(fn, 'a', encoding='utf-8') as archive_file:
3887
+ archive_file.write(vid_id + '\n')
3888
+ self.archive.add(vid_id)
3889
+
3890
+ @staticmethod
3891
+ def format_resolution(format, default='unknown'):
3892
+ if format.get('vcodec') == 'none' and format.get('acodec') != 'none':
3893
+ return 'audio only'
3894
+ if format.get('resolution') is not None:
3895
+ return format['resolution']
3896
+ if format.get('width') and format.get('height'):
3897
+ return '%dx%d' % (format['width'], format['height'])
3898
+ elif format.get('height'):
3899
+ return '{}p'.format(format['height'])
3900
+ elif format.get('width'):
3901
+ return '%dx?' % format['width']
3902
+ return default
3903
+
3904
+ def _list_format_headers(self, *headers):
3905
+ if self.params.get('listformats_table', True) is not False:
3906
+ return [self._format_out(header, self.Styles.HEADERS) for header in headers]
3907
+ return headers
3908
+
3909
+ def _format_note(self, fdict):
3910
+ res = ''
3911
+ if fdict.get('ext') in ['f4f', 'f4m']:
3912
+ res += '(unsupported)'
3913
+ if fdict.get('language'):
3914
+ if res:
3915
+ res += ' '
3916
+ res += '[{}]'.format(fdict['language'])
3917
+ if fdict.get('format_note') is not None:
3918
+ if res:
3919
+ res += ' '
3920
+ res += fdict['format_note']
3921
+ if fdict.get('tbr') is not None:
3922
+ if res:
3923
+ res += ', '
3924
+ res += '%4dk' % fdict['tbr']
3925
+ if fdict.get('container') is not None:
3926
+ if res:
3927
+ res += ', '
3928
+ res += '{} container'.format(fdict['container'])
3929
+ if (fdict.get('vcodec') is not None
3930
+ and fdict.get('vcodec') != 'none'):
3931
+ if res:
3932
+ res += ', '
3933
+ res += fdict['vcodec']
3934
+ if fdict.get('vbr') is not None:
3935
+ res += '@'
3936
+ elif fdict.get('vbr') is not None and fdict.get('abr') is not None:
3937
+ res += 'video@'
3938
+ if fdict.get('vbr') is not None:
3939
+ res += '%4dk' % fdict['vbr']
3940
+ if fdict.get('fps') is not None:
3941
+ if res:
3942
+ res += ', '
3943
+ res += '{}fps'.format(fdict['fps'])
3944
+ if fdict.get('acodec') is not None:
3945
+ if res:
3946
+ res += ', '
3947
+ if fdict['acodec'] == 'none':
3948
+ res += 'video only'
3949
+ else:
3950
+ res += '%-5s' % fdict['acodec']
3951
+ elif fdict.get('abr') is not None:
3952
+ if res:
3953
+ res += ', '
3954
+ res += 'audio'
3955
+ if fdict.get('abr') is not None:
3956
+ res += '@%3dk' % fdict['abr']
3957
+ if fdict.get('asr') is not None:
3958
+ res += ' (%5dHz)' % fdict['asr']
3959
+ if fdict.get('filesize') is not None:
3960
+ if res:
3961
+ res += ', '
3962
+ res += format_bytes(fdict['filesize'])
3963
+ elif fdict.get('filesize_approx') is not None:
3964
+ if res:
3965
+ res += ', '
3966
+ res += '~' + format_bytes(fdict['filesize_approx'])
3967
+ return res
3968
+
3969
+ def _get_formats(self, info_dict):
3970
+ if info_dict.get('formats') is None:
3971
+ if info_dict.get('url') and info_dict.get('_type', 'video') == 'video':
3972
+ return [info_dict]
3973
+ return []
3974
+ return info_dict['formats']
3975
+
3976
+ def render_formats_table(self, info_dict):
3977
+ formats = self._get_formats(info_dict)
3978
+ if not formats:
3979
+ return
3980
+ if not self.params.get('listformats_table', True) is not False:
3981
+ table = [
3982
+ [
3983
+ format_field(f, 'format_id'),
3984
+ format_field(f, 'ext'),
3985
+ self.format_resolution(f),
3986
+ self._format_note(f),
3987
+ ] for f in formats if (f.get('preference') or 0) >= -1000]
3988
+ return render_table(['format code', 'extension', 'resolution', 'note'], table, extra_gap=1)
3989
+
3990
+ def simplified_codec(f, field):
3991
+ assert field in ('acodec', 'vcodec')
3992
+ codec = f.get(field)
3993
+ if not codec:
3994
+ return 'unknown'
3995
+ elif codec != 'none':
3996
+ return '.'.join(codec.split('.')[:4])
3997
+
3998
+ if field == 'vcodec' and f.get('acodec') == 'none':
3999
+ return 'images'
4000
+ elif field == 'acodec' and f.get('vcodec') == 'none':
4001
+ return ''
4002
+ return self._format_out('audio only' if field == 'vcodec' else 'video only',
4003
+ self.Styles.SUPPRESS)
4004
+
4005
+ delim = self._format_out('\u2502', self.Styles.DELIM, '|', test_encoding=True)
4006
+ table = [
4007
+ [
4008
+ self._format_out(format_field(f, 'format_id'), self.Styles.ID),
4009
+ format_field(f, 'ext'),
4010
+ format_field(f, func=self.format_resolution, ignore=('audio only', 'images')),
4011
+ format_field(f, 'fps', '\t%d', func=round),
4012
+ format_field(f, 'dynamic_range', '%s', ignore=(None, 'SDR')).replace('HDR', ''),
4013
+ format_field(f, 'audio_channels', '\t%s'),
4014
+ delim, (
4015
+ format_field(f, 'filesize', ' \t%s', func=format_bytes)
4016
+ or format_field(f, 'filesize_approx', '≈\t%s', func=format_bytes)
4017
+ or format_field(filesize_from_tbr(f.get('tbr'), info_dict.get('duration')), None,
4018
+ self._format_out('~\t%s', self.Styles.SUPPRESS), func=format_bytes)),
4019
+ format_field(f, 'tbr', '\t%dk', func=round),
4020
+ shorten_protocol_name(f.get('protocol', '')),
4021
+ delim,
4022
+ simplified_codec(f, 'vcodec'),
4023
+ format_field(f, 'vbr', '\t%dk', func=round),
4024
+ simplified_codec(f, 'acodec'),
4025
+ format_field(f, 'abr', '\t%dk', func=round),
4026
+ format_field(f, 'asr', '\t%s', func=format_decimal_suffix),
4027
+ join_nonempty(format_field(f, 'language', '[%s]'), join_nonempty(
4028
+ self._format_out('UNSUPPORTED', self.Styles.BAD_FORMAT) if f.get('ext') in ('f4f', 'f4m') else None,
4029
+ (self._format_out('Maybe DRM', self.Styles.WARNING) if f.get('has_drm') == 'maybe'
4030
+ else self._format_out('DRM', self.Styles.BAD_FORMAT) if f.get('has_drm') else None),
4031
+ self._format_out('Untested', self.Styles.WARNING) if f.get('__needs_testing') else None,
4032
+ format_field(f, 'format_note'),
4033
+ format_field(f, 'container', ignore=(None, f.get('ext'))),
4034
+ delim=', '), delim=' '),
4035
+ ] for f in formats if f.get('preference') is None or f['preference'] >= -1000]
4036
+ header_line = self._list_format_headers(
4037
+ 'ID', 'EXT', 'RESOLUTION', '\tFPS', 'HDR', 'CH', delim, '\tFILESIZE', '\tTBR', 'PROTO',
4038
+ delim, 'VCODEC', '\tVBR', 'ACODEC', '\tABR', '\tASR', 'MORE INFO')
4039
+
4040
+ return render_table(
4041
+ header_line, table, hide_empty=True,
4042
+ delim=self._format_out('\u2500', self.Styles.DELIM, '-', test_encoding=True))
4043
+
4044
+ def render_thumbnails_table(self, info_dict):
4045
+ thumbnails = list(info_dict.get('thumbnails') or [])
4046
+ if not thumbnails:
4047
+ return None
4048
+ return render_table(
4049
+ self._list_format_headers('ID', 'Width', 'Height', 'URL'),
4050
+ [[t.get('id'), t.get('width') or 'unknown', t.get('height') or 'unknown', t['url']] for t in thumbnails])
4051
+
4052
+ def render_subtitles_table(self, video_id, subtitles):
4053
+ def _row(lang, formats):
4054
+ exts, names = zip(*((f['ext'], f.get('name') or 'unknown') for f in reversed(formats)), strict=True)
4055
+ if len(set(names)) == 1:
4056
+ names = [] if names[0] == 'unknown' else names[:1]
4057
+ return [lang, ', '.join(names), ', '.join(exts)]
4058
+
4059
+ if not subtitles:
4060
+ return None
4061
+ return render_table(
4062
+ self._list_format_headers('Language', 'Name', 'Formats'),
4063
+ [_row(lang, formats) for lang, formats in subtitles.items()],
4064
+ hide_empty=True)
4065
+
4066
+ def __list_table(self, video_id, name, func, *args):
4067
+ table = func(*args)
4068
+ if not table:
4069
+ self.to_screen(f'{video_id} has no {name}')
4070
+ return
4071
+ self.to_screen(f'[info] Available {name} for {video_id}:')
4072
+ self.to_stdout(table)
4073
+
4074
+ def list_formats(self, info_dict):
4075
+ self.__list_table(info_dict['id'], 'formats', self.render_formats_table, info_dict)
4076
+
4077
+ def list_thumbnails(self, info_dict):
4078
+ self.__list_table(info_dict['id'], 'thumbnails', self.render_thumbnails_table, info_dict)
4079
+
4080
+ def list_subtitles(self, video_id, subtitles, name='subtitles'):
4081
+ self.__list_table(video_id, name, self.render_subtitles_table, video_id, subtitles)
4082
+
4083
+ def print_debug_header(self):
4084
+ if not self.params.get('verbose'):
4085
+ return
4086
+
4087
+ def get_encoding(stream):
4088
+ ret = str(getattr(stream, 'encoding', f'missing ({type(stream).__name__})'))
4089
+ additional_info = []
4090
+ if os.environ.get('TERM', '').lower() == 'dumb':
4091
+ additional_info.append('dumb')
4092
+ if not supports_terminal_sequences(stream):
4093
+ additional_info.append('No VT' if WINDOWS_VT_MODE.value is False else 'No ANSI')
4094
+ if additional_info:
4095
+ ret = f'{ret} ({",".join(additional_info)})'
4096
+ return ret
4097
+
4098
+ encoding_str = 'Encodings: locale {}, fs {}, pref {}, {}'.format(
4099
+ locale.getpreferredencoding(),
4100
+ sys.getfilesystemencoding(),
4101
+ self.get_encoding(),
4102
+ ', '.join(
4103
+ f'{key} {get_encoding(stream)}' for key, stream in self._out_files.items_
4104
+ if stream is not None and key != 'console'),
4105
+ )
4106
+
4107
+ logger = self.params.get('logger')
4108
+ if logger:
4109
+ write_debug = lambda msg: logger.debug(f'[debug] {msg}')
4110
+ write_debug(encoding_str)
4111
+ else:
4112
+ write_string(f'[debug] {encoding_str}\n', encoding=None)
4113
+ write_debug = lambda msg: self._write_string(f'[debug] {msg}\n')
4114
+
4115
+ source = detect_variant()
4116
+ if VARIANT not in (None, 'pip'):
4117
+ source += '*'
4118
+ klass = type(self)
4119
+ write_debug(join_nonempty(
4120
+ f'{REPOSITORY.rpartition("/")[2]} version',
4121
+ _make_label(ORIGIN, CHANNEL.partition('@')[2] or __version__, __version__),
4122
+ f'[{RELEASE_GIT_HEAD[:9]}]' if RELEASE_GIT_HEAD else '',
4123
+ '' if source == 'unknown' else f'({source})',
4124
+ '' if IN_CLI.value else 'API' if klass == YoutubeDL else f'API:{self.__module__}.{klass.__qualname__}',
4125
+ delim=' '))
4126
+
4127
+ if not IN_CLI.value:
4128
+ write_debug(f'params: {self.params}')
4129
+
4130
+ import_extractors()
4131
+ lazy_extractors = LAZY_EXTRACTORS.value
4132
+ if lazy_extractors is None:
4133
+ write_debug('Lazy loading extractors is disabled')
4134
+ elif not lazy_extractors:
4135
+ write_debug('Lazy loading extractors is forcibly disabled')
4136
+ if self.params['compat_opts']:
4137
+ write_debug('Compatibility options: {}'.format(', '.join(self.params['compat_opts'])))
4138
+
4139
+ if current_git_head():
4140
+ write_debug(f'Git HEAD: {current_git_head()}')
4141
+ write_debug(system_identifier())
4142
+
4143
+ exe_versions, ffmpeg_features = FFmpegPostProcessor.get_versions_and_features(self)
4144
+ ffmpeg_features = {key for key, val in ffmpeg_features.items() if val}
4145
+ if ffmpeg_features:
4146
+ exe_versions['ffmpeg'] += ' ({})'.format(','.join(sorted(ffmpeg_features)))
4147
+
4148
+ exe_versions['rtmpdump'] = rtmpdump_version()
4149
+ exe_versions['phantomjs'] = PhantomJSwrapper._version()
4150
+ exe_str = ', '.join(
4151
+ f'{exe} {v}' for exe, v in sorted(exe_versions.items()) if v
4152
+ ) or 'none'
4153
+ write_debug(f'exe versions: {exe_str}')
4154
+
4155
+ from .compat.compat_utils import get_package_info
4156
+ from .dependencies import available_dependencies
4157
+
4158
+ write_debug('Optional libraries: %s' % (', '.join(sorted({
4159
+ join_nonempty(*get_package_info(m)) for m in available_dependencies.values()
4160
+ })) or 'none'))
4161
+
4162
+ if not self.params.get('js_runtimes'):
4163
+ write_debug('JS runtimes: none (disabled)')
4164
+ else:
4165
+ write_debug('JS runtimes: %s' % (', '.join(sorted(
4166
+ f'{name} (unknown)' if runtime is None
4167
+ else join_nonempty(
4168
+ runtime.info.name,
4169
+ runtime.info.version + (' (unsupported)' if runtime.info.supported is False else ''),
4170
+ )
4171
+ for name, runtime in self._js_runtimes.items() if runtime is None or runtime.info is not None
4172
+ )) or 'none'))
4173
+
4174
+ write_debug(f'Proxy map: {self.proxies}')
4175
+ write_debug(f'Request Handlers: {", ".join(rh.RH_NAME for rh in self._request_director.handlers.values())}')
4176
+
4177
+ for plugin_type, plugins in (('Extractor', plugin_ies), ('Post-Processor', plugin_pps)):
4178
+ display_list = [
4179
+ klass.__name__ if klass.__name__ == name else f'{klass.__name__} as {name}'
4180
+ for name, klass in plugins.value.items()]
4181
+ if plugin_type == 'Extractor':
4182
+ display_list.extend(f'{plugins[-1].IE_NAME.partition("+")[2]} ({parent.__name__})'
4183
+ for parent, plugins in plugin_ies_overrides.value.items())
4184
+ if not display_list:
4185
+ continue
4186
+ write_debug(f'{plugin_type} Plugins: {", ".join(sorted(display_list))}')
4187
+
4188
+ plugin_dirs_msg = 'none'
4189
+ if not plugin_dirs.value:
4190
+ plugin_dirs_msg = 'none (disabled)'
4191
+ else:
4192
+ found_plugin_directories = plugin_directories()
4193
+ if found_plugin_directories:
4194
+ plugin_dirs_msg = ', '.join(found_plugin_directories)
4195
+
4196
+ write_debug(f'Plugin directories: {plugin_dirs_msg}')
4197
+
4198
+ @functools.cached_property
4199
+ def proxies(self):
4200
+ """Global proxy configuration"""
4201
+ opts_proxy = self.params.get('proxy')
4202
+ if opts_proxy is not None:
4203
+ if opts_proxy == '':
4204
+ opts_proxy = '__noproxy__'
4205
+ proxies = {'all': opts_proxy}
4206
+ else:
4207
+ proxies = urllib.request.getproxies()
4208
+ # compat. Set HTTPS_PROXY to __noproxy__ to revert
4209
+ if 'http' in proxies and 'https' not in proxies:
4210
+ proxies['https'] = proxies['http']
4211
+
4212
+ return proxies
4213
+
4214
+ @functools.cached_property
4215
+ def cookiejar(self):
4216
+ """Global cookiejar instance"""
4217
+ try:
4218
+ return load_cookies(
4219
+ self.params.get('cookiefile'), self.params.get('cookiesfrombrowser'), self)
4220
+ except CookieLoadError as error:
4221
+ cause = error.__context__
4222
+ self.report_error(str(cause), tb=''.join(traceback.format_exception(cause)))
4223
+ raise
4224
+
4225
+ @property
4226
+ def _opener(self):
4227
+ """
4228
+ Get a urllib OpenerDirector from the Urllib handler (deprecated).
4229
+ """
4230
+ self.deprecation_warning('YoutubeDL._opener is deprecated, use YoutubeDL.urlopen()')
4231
+ handler = self._request_director.handlers['Urllib']
4232
+ return handler._get_instance(cookiejar=self.cookiejar, proxies=self.proxies)
4233
+
4234
+ def _get_available_impersonate_targets(self):
4235
+ # TODO(future): make available as public API
4236
+ return [
4237
+ (target, rh.RH_NAME)
4238
+ for rh in self._request_director.handlers.values()
4239
+ if isinstance(rh, ImpersonateRequestHandler)
4240
+ for target in reversed(rh.supported_targets)
4241
+ ]
4242
+
4243
+ def _impersonate_target_available(self, target):
4244
+ # TODO(future): make available as public API
4245
+ return any(
4246
+ rh.is_supported_target(target)
4247
+ for rh in self._request_director.handlers.values()
4248
+ if isinstance(rh, ImpersonateRequestHandler))
4249
+
4250
+ def _parse_impersonate_targets(self, impersonate):
4251
+ if impersonate in (True, ''):
4252
+ impersonate = ImpersonateTarget()
4253
+
4254
+ requested_targets = [
4255
+ t if isinstance(t, ImpersonateTarget) else ImpersonateTarget.from_str(t)
4256
+ for t in variadic(impersonate)
4257
+ ] if impersonate else []
4258
+
4259
+ available_target = next(filter(self._impersonate_target_available, requested_targets), None)
4260
+
4261
+ return available_target, requested_targets
4262
+
4263
+ @staticmethod
4264
+ def _unavailable_targets_message(requested_targets, note=None, is_error=False):
4265
+ note = note or 'The extractor specified to use impersonation for this download'
4266
+ specific_targets = ', '.join(filter(None, map(str, requested_targets)))
4267
+ message = (
4268
+ 'no impersonate target is available' if not specific_targets
4269
+ else f'none of these impersonate targets are available: {specific_targets}')
4270
+ return (
4271
+ f'{note}, but {message}. {"See" if is_error else "If you encounter errors, then see"}'
4272
+ f' https://github.com/yt-dlp/yt-dlp#impersonation '
4273
+ f'for information on installing the required dependencies')
4274
+
4275
+ def urlopen(self, req):
4276
+ """ Start an HTTP download """
4277
+ if isinstance(req, str):
4278
+ req = Request(req)
4279
+ elif isinstance(req, urllib.request.Request):
4280
+ self.deprecation_warning(
4281
+ 'Passing a urllib.request.Request object to YoutubeDL.urlopen() is deprecated. '
4282
+ 'Use yt_dlp.networking.common.Request instead.')
4283
+ req = urllib_req_to_req(req)
4284
+ assert isinstance(req, Request)
4285
+
4286
+ # compat: Assume user:pass url params are basic auth
4287
+ url, basic_auth_header = extract_basic_auth(req.url)
4288
+ if basic_auth_header:
4289
+ req.headers['Authorization'] = basic_auth_header
4290
+ req.url = sanitize_url(url)
4291
+
4292
+ clean_proxies(proxies=req.proxies, headers=req.headers)
4293
+ clean_headers(req.headers)
4294
+
4295
+ try:
4296
+ return self._request_director.send(req)
4297
+ except NoSupportingHandlers as e:
4298
+ for ue in e.unsupported_errors:
4299
+ # FIXME: This depends on the order of errors.
4300
+ if not (ue.handler and ue.msg):
4301
+ continue
4302
+ if ue.handler.RH_KEY == 'Urllib' and 'unsupported url scheme: "file"' in ue.msg.lower():
4303
+ raise RequestError(
4304
+ 'file:// URLs are disabled by default in yt-dlp for security reasons. '
4305
+ 'Use --enable-file-urls to enable at your own risk.', cause=ue) from ue
4306
+ if (
4307
+ 'unsupported proxy type: "https"' in ue.msg.lower()
4308
+ and 'requests' not in self._request_director.handlers
4309
+ and 'curl_cffi' not in self._request_director.handlers
4310
+ ):
4311
+ raise RequestError(
4312
+ 'To use an HTTPS proxy for this request, one of the following dependencies needs to be installed: requests, curl_cffi')
4313
+
4314
+ elif (
4315
+ re.match(r'unsupported url scheme: "wss?"', ue.msg.lower())
4316
+ and 'websockets' not in self._request_director.handlers
4317
+ ):
4318
+ raise RequestError(
4319
+ 'This request requires WebSocket support. '
4320
+ 'Ensure one of the following dependencies are installed: websockets',
4321
+ cause=ue) from ue
4322
+
4323
+ elif re.match(r'unsupported (?:extensions: impersonate|impersonate target)', ue.msg.lower()):
4324
+ raise RequestError(
4325
+ f'Impersonate target "{req.extensions["impersonate"]}" is not available.'
4326
+ f' See --list-impersonate-targets for available targets.'
4327
+ f' This request requires browser impersonation, however you may be missing dependencies'
4328
+ f' required to support this target.')
4329
+ raise
4330
+ except SSLError as e:
4331
+ if 'UNSAFE_LEGACY_RENEGOTIATION_DISABLED' in str(e):
4332
+ raise RequestError('UNSAFE_LEGACY_RENEGOTIATION_DISABLED: Try using --legacy-server-connect', cause=e) from e
4333
+ elif 'SSLV3_ALERT_HANDSHAKE_FAILURE' in str(e):
4334
+ raise RequestError(
4335
+ 'SSLV3_ALERT_HANDSHAKE_FAILURE: The server may not support the current cipher list. '
4336
+ 'Try using --legacy-server-connect', cause=e) from e
4337
+ raise
4338
+
4339
+ def build_request_director(self, handlers, preferences=None):
4340
+ logger = _YDLLogger(self)
4341
+ headers = self.params['http_headers'].copy()
4342
+ proxies = self.proxies.copy()
4343
+ clean_headers(headers)
4344
+ clean_proxies(proxies, headers)
4345
+
4346
+ director = RequestDirector(logger=logger, verbose=self.params.get('debug_printtraffic'))
4347
+ for handler in handlers:
4348
+ director.add_handler(handler(
4349
+ logger=logger,
4350
+ headers=headers,
4351
+ cookiejar=self.cookiejar,
4352
+ proxies=proxies,
4353
+ prefer_system_certs='no-certifi' in self.params['compat_opts'],
4354
+ verify=not self.params.get('nocheckcertificate'),
4355
+ **traverse_obj(self.params, {
4356
+ 'verbose': 'debug_printtraffic',
4357
+ 'source_address': 'source_address',
4358
+ 'timeout': 'socket_timeout',
4359
+ 'legacy_ssl_support': 'legacyserverconnect',
4360
+ 'enable_file_urls': 'enable_file_urls',
4361
+ 'impersonate': 'impersonate',
4362
+ 'client_cert': {
4363
+ 'client_certificate': 'client_certificate',
4364
+ 'client_certificate_key': 'client_certificate_key',
4365
+ 'client_certificate_password': 'client_certificate_password',
4366
+ },
4367
+ }),
4368
+ ))
4369
+ director.preferences.update(preferences or [])
4370
+ if 'prefer-legacy-http-handler' in self.params['compat_opts']:
4371
+ director.preferences.add(lambda rh, _: 500 if rh.RH_KEY == 'Urllib' else 0)
4372
+ return director
4373
+
4374
+ @functools.cached_property
4375
+ def _request_director(self):
4376
+ return self.build_request_director(_REQUEST_HANDLERS.values(), _RH_PREFERENCES)
4377
+
4378
+ def encode(self, s):
4379
+ if isinstance(s, bytes):
4380
+ return s # Already encoded
4381
+
4382
+ try:
4383
+ return s.encode(self.get_encoding())
4384
+ except UnicodeEncodeError as err:
4385
+ err.reason = err.reason + '. Check your system encoding configuration or use the --encoding option.'
4386
+ raise
4387
+
4388
+ def get_encoding(self):
4389
+ encoding = self.params.get('encoding')
4390
+ if encoding is None:
4391
+ encoding = preferredencoding()
4392
+ return encoding
4393
+
4394
+ def _write_info_json(self, label, ie_result, infofn, overwrite=None):
4395
+ """ Write infojson and returns True = written, 'exists' = Already exists, False = skip, None = error """
4396
+ if overwrite is None:
4397
+ overwrite = self.params.get('overwrites', True)
4398
+ if not self.params.get('writeinfojson'):
4399
+ return False
4400
+ elif not infofn:
4401
+ self.write_debug(f'Skipping writing {label} infojson')
4402
+ return False
4403
+ elif not self._ensure_dir_exists(infofn):
4404
+ return None
4405
+ elif not overwrite and os.path.exists(infofn):
4406
+ self.to_screen(f'[info] {label.title()} metadata is already present')
4407
+ return 'exists'
4408
+
4409
+ self.to_screen(f'[info] Writing {label} metadata as JSON to: {infofn}')
4410
+ try:
4411
+ write_json_file(self.sanitize_info(ie_result, self.params.get('clean_infojson', True)), infofn)
4412
+ return True
4413
+ except OSError:
4414
+ self.report_error(f'Cannot write {label} metadata to JSON file {infofn}')
4415
+ return None
4416
+
4417
+ def _write_description(self, label, ie_result, descfn):
4418
+ """ Write description and returns True = written, False = skip, None = error """
4419
+ if not self.params.get('writedescription'):
4420
+ return False
4421
+ elif not descfn:
4422
+ self.write_debug(f'Skipping writing {label} description')
4423
+ return False
4424
+ elif not self._ensure_dir_exists(descfn):
4425
+ return None
4426
+ elif not self.params.get('overwrites', True) and os.path.exists(descfn):
4427
+ self.to_screen(f'[info] {label.title()} description is already present')
4428
+ elif ie_result.get('description') is None:
4429
+ self.to_screen(f'[info] There\'s no {label} description to write')
4430
+ return False
4431
+ else:
4432
+ try:
4433
+ self.to_screen(f'[info] Writing {label} description to: {descfn}')
4434
+ with open(descfn, 'w', encoding='utf-8') as descfile:
4435
+ descfile.write(ie_result['description'])
4436
+ except OSError:
4437
+ self.report_error(f'Cannot write {label} description file {descfn}')
4438
+ return None
4439
+ return True
4440
+
4441
+ def _write_subtitles(self, info_dict, filename):
4442
+ """ Write subtitles to file and return list of (sub_filename, final_sub_filename); or None if error"""
4443
+ ret = []
4444
+ subtitles = info_dict.get('requested_subtitles')
4445
+ if not (self.params.get('writesubtitles') or self.params.get('writeautomaticsub')):
4446
+ # subtitles download errors are already managed as troubles in relevant IE
4447
+ # that way it will silently go on when used with unsupporting IE
4448
+ return ret
4449
+ elif not subtitles:
4450
+ self.to_screen('[info] There are no subtitles for the requested languages')
4451
+ return ret
4452
+ sub_filename_base = self.prepare_filename(info_dict, 'subtitle')
4453
+ if not sub_filename_base:
4454
+ self.to_screen('[info] Skipping writing video subtitles')
4455
+ return ret
4456
+
4457
+ for sub_lang, sub_info in subtitles.items():
4458
+ sub_format = sub_info['ext']
4459
+ sub_filename = subtitles_filename(filename, sub_lang, sub_format, info_dict.get('ext'))
4460
+ sub_filename_final = subtitles_filename(sub_filename_base, sub_lang, sub_format, info_dict.get('ext'))
4461
+ existing_sub = self.existing_file((sub_filename_final, sub_filename))
4462
+ if existing_sub:
4463
+ self.to_screen(f'[info] Video subtitle {sub_lang}.{sub_format} is already present')
4464
+ sub_info['filepath'] = existing_sub
4465
+ ret.append((existing_sub, sub_filename_final))
4466
+ continue
4467
+
4468
+ self.to_screen(f'[info] Writing video subtitles to: {sub_filename}')
4469
+ if sub_info.get('data') is not None:
4470
+ try:
4471
+ # Use newline='' to prevent conversion of newline characters
4472
+ # See https://github.com/ytdl-org/youtube-dl/issues/10268
4473
+ with open(sub_filename, 'w', encoding='utf-8', newline='') as subfile:
4474
+ subfile.write(sub_info['data'])
4475
+ sub_info['filepath'] = sub_filename
4476
+ ret.append((sub_filename, sub_filename_final))
4477
+ continue
4478
+ except OSError:
4479
+ self.report_error(f'Cannot write video subtitles file {sub_filename}')
4480
+ return None
4481
+
4482
+ try:
4483
+ sub_copy = sub_info.copy()
4484
+ sub_copy.setdefault('http_headers', info_dict.get('http_headers'))
4485
+ self.dl(sub_filename, sub_copy, subtitle=True)
4486
+ sub_info['filepath'] = sub_filename
4487
+ ret.append((sub_filename, sub_filename_final))
4488
+ except (DownloadError, ExtractorError, OSError, ValueError, *network_exceptions) as err:
4489
+ msg = f'Unable to download video subtitles for {sub_lang!r}: {err}'
4490
+ if self.params.get('ignoreerrors') is not True: # False or 'only_download'
4491
+ if not self.params.get('ignoreerrors'):
4492
+ self.report_error(msg)
4493
+ raise DownloadError(msg)
4494
+ self.report_warning(msg)
4495
+ return ret
4496
+
4497
+ def _write_thumbnails(self, label, info_dict, filename, thumb_filename_base=None):
4498
+ """ Write thumbnails to file and return list of (thumb_filename, final_thumb_filename); or None if error """
4499
+ write_all = self.params.get('write_all_thumbnails', False)
4500
+ thumbnails, ret = [], []
4501
+ if write_all or self.params.get('writethumbnail', False):
4502
+ thumbnails = info_dict.get('thumbnails') or []
4503
+ if not thumbnails:
4504
+ self.to_screen(f'[info] There are no {label} thumbnails to download')
4505
+ return ret
4506
+ multiple = write_all and len(thumbnails) > 1
4507
+
4508
+ if thumb_filename_base is None:
4509
+ thumb_filename_base = filename
4510
+ if thumbnails and not thumb_filename_base:
4511
+ self.write_debug(f'Skipping writing {label} thumbnail')
4512
+ return ret
4513
+
4514
+ if thumbnails and not self._ensure_dir_exists(filename):
4515
+ return None
4516
+
4517
+ for idx, t in list(enumerate(thumbnails))[::-1]:
4518
+ thumb_ext = t.get('ext') or determine_ext(t['url'], 'jpg')
4519
+ if multiple:
4520
+ thumb_ext = f'{t["id"]}.{thumb_ext}'
4521
+ thumb_display_id = f'{label} thumbnail {t["id"]}'
4522
+ thumb_filename = replace_extension(filename, thumb_ext, info_dict.get('ext'))
4523
+ thumb_filename_final = replace_extension(thumb_filename_base, thumb_ext, info_dict.get('ext'))
4524
+
4525
+ existing_thumb = self.existing_file((thumb_filename_final, thumb_filename))
4526
+ if existing_thumb:
4527
+ self.to_screen('[info] {} is already present'.format((
4528
+ thumb_display_id if multiple else f'{label} thumbnail').capitalize()))
4529
+ t['filepath'] = existing_thumb
4530
+ ret.append((existing_thumb, thumb_filename_final))
4531
+ else:
4532
+ self.to_screen(f'[info] Downloading {thumb_display_id} ...')
4533
+ try:
4534
+ uf = self.urlopen(Request(t['url'], headers=t.get('http_headers', {})))
4535
+ self.to_screen(f'[info] Writing {thumb_display_id} to: {thumb_filename}')
4536
+ with open(thumb_filename, 'wb') as thumbf:
4537
+ shutil.copyfileobj(uf, thumbf)
4538
+ ret.append((thumb_filename, thumb_filename_final))
4539
+ t['filepath'] = thumb_filename
4540
+ except network_exceptions as err:
4541
+ if isinstance(err, HTTPError) and err.status == 404:
4542
+ self.to_screen(f'[info] {thumb_display_id.title()} does not exist')
4543
+ else:
4544
+ self.report_warning(f'Unable to download {thumb_display_id}: {err}')
4545
+ thumbnails.pop(idx)
4546
+ if ret and not write_all:
4547
+ break
4548
+ return ret