test_YoutubeDL.py 56 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345
  1. #!/usr/bin/env python3
  2. # Allow direct execution
  3. import os
  4. import sys
  5. import unittest
  6. sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
  7. import contextlib
  8. import copy
  9. import json
  10. from test.helper import FakeYDL, assertRegexpMatches, try_rm
  11. from yt_dlp import YoutubeDL
  12. from yt_dlp.compat import compat_os_name
  13. from yt_dlp.extractor import YoutubeIE
  14. from yt_dlp.extractor.common import InfoExtractor
  15. from yt_dlp.postprocessor.common import PostProcessor
  16. from yt_dlp.utils import (
  17. ExtractorError,
  18. LazyList,
  19. OnDemandPagedList,
  20. int_or_none,
  21. match_filter_func,
  22. )
  23. from yt_dlp.utils.traversal import traverse_obj
  24. TEST_URL = 'http://localhost/sample.mp4'
  25. class YDL(FakeYDL):
  26. def __init__(self, *args, **kwargs):
  27. super().__init__(*args, **kwargs)
  28. self.downloaded_info_dicts = []
  29. self.msgs = []
  30. def process_info(self, info_dict):
  31. self.downloaded_info_dicts.append(info_dict.copy())
  32. def to_screen(self, msg, *args, **kwargs):
  33. self.msgs.append(msg)
  34. def dl(self, *args, **kwargs):
  35. assert False, 'Downloader must not be invoked for test_YoutubeDL'
  36. def _make_result(formats, **kwargs):
  37. res = {
  38. 'formats': formats,
  39. 'id': 'testid',
  40. 'title': 'testttitle',
  41. 'extractor': 'testex',
  42. 'extractor_key': 'TestEx',
  43. 'webpage_url': 'http://example.com/watch?v=shenanigans',
  44. }
  45. res.update(**kwargs)
  46. return res
  47. class TestFormatSelection(unittest.TestCase):
  48. def test_prefer_free_formats(self):
  49. # Same resolution => download webm
  50. ydl = YDL()
  51. ydl.params['prefer_free_formats'] = True
  52. formats = [
  53. {'ext': 'webm', 'height': 460, 'url': TEST_URL},
  54. {'ext': 'mp4', 'height': 460, 'url': TEST_URL},
  55. ]
  56. info_dict = _make_result(formats)
  57. ydl.sort_formats(info_dict)
  58. ydl.process_ie_result(info_dict)
  59. downloaded = ydl.downloaded_info_dicts[0]
  60. self.assertEqual(downloaded['ext'], 'webm')
  61. # Different resolution => download best quality (mp4)
  62. ydl = YDL()
  63. ydl.params['prefer_free_formats'] = True
  64. formats = [
  65. {'ext': 'webm', 'height': 720, 'url': TEST_URL},
  66. {'ext': 'mp4', 'height': 1080, 'url': TEST_URL},
  67. ]
  68. info_dict['formats'] = formats
  69. ydl.sort_formats(info_dict)
  70. ydl.process_ie_result(info_dict)
  71. downloaded = ydl.downloaded_info_dicts[0]
  72. self.assertEqual(downloaded['ext'], 'mp4')
  73. # No prefer_free_formats => prefer mp4 and webm
  74. ydl = YDL()
  75. ydl.params['prefer_free_formats'] = False
  76. formats = [
  77. {'ext': 'webm', 'height': 720, 'url': TEST_URL},
  78. {'ext': 'mp4', 'height': 720, 'url': TEST_URL},
  79. {'ext': 'flv', 'height': 720, 'url': TEST_URL},
  80. ]
  81. info_dict['formats'] = formats
  82. ydl.sort_formats(info_dict)
  83. ydl.process_ie_result(info_dict)
  84. downloaded = ydl.downloaded_info_dicts[0]
  85. self.assertEqual(downloaded['ext'], 'mp4')
  86. ydl = YDL()
  87. ydl.params['prefer_free_formats'] = False
  88. formats = [
  89. {'ext': 'flv', 'height': 720, 'url': TEST_URL},
  90. {'ext': 'webm', 'height': 720, 'url': TEST_URL},
  91. ]
  92. info_dict['formats'] = formats
  93. ydl.sort_formats(info_dict)
  94. ydl.process_ie_result(info_dict)
  95. downloaded = ydl.downloaded_info_dicts[0]
  96. self.assertEqual(downloaded['ext'], 'webm')
  97. def test_format_selection(self):
  98. formats = [
  99. {'format_id': '35', 'ext': 'mp4', 'preference': 0, 'url': TEST_URL},
  100. {'format_id': 'example-with-dashes', 'ext': 'webm', 'preference': 1, 'url': TEST_URL},
  101. {'format_id': '45', 'ext': 'webm', 'preference': 2, 'url': TEST_URL},
  102. {'format_id': '47', 'ext': 'webm', 'preference': 3, 'url': TEST_URL},
  103. {'format_id': '2', 'ext': 'flv', 'preference': 4, 'url': TEST_URL},
  104. ]
  105. info_dict = _make_result(formats)
  106. def test(inp, *expected, multi=False):
  107. ydl = YDL({
  108. 'format': inp,
  109. 'allow_multiple_video_streams': multi,
  110. 'allow_multiple_audio_streams': multi,
  111. })
  112. ydl.process_ie_result(info_dict.copy())
  113. downloaded = [x['format_id'] for x in ydl.downloaded_info_dicts]
  114. self.assertEqual(downloaded, list(expected))
  115. test('20/47', '47')
  116. test('20/71/worst', '35')
  117. test(None, '2')
  118. test('webm/mp4', '47')
  119. test('3gp/40/mp4', '35')
  120. test('example-with-dashes', 'example-with-dashes')
  121. test('all', '2', '47', '45', 'example-with-dashes', '35')
  122. test('mergeall', '2+47+45+example-with-dashes+35', multi=True)
  123. # See: https://github.com/yt-dlp/yt-dlp/pulls/8797
  124. test('7_a/worst', '35')
  125. def test_format_selection_audio(self):
  126. formats = [
  127. {'format_id': 'audio-low', 'ext': 'webm', 'preference': 1, 'vcodec': 'none', 'url': TEST_URL},
  128. {'format_id': 'audio-mid', 'ext': 'webm', 'preference': 2, 'vcodec': 'none', 'url': TEST_URL},
  129. {'format_id': 'audio-high', 'ext': 'flv', 'preference': 3, 'vcodec': 'none', 'url': TEST_URL},
  130. {'format_id': 'vid', 'ext': 'mp4', 'preference': 4, 'url': TEST_URL},
  131. ]
  132. info_dict = _make_result(formats)
  133. ydl = YDL({'format': 'bestaudio'})
  134. ydl.process_ie_result(info_dict.copy())
  135. downloaded = ydl.downloaded_info_dicts[0]
  136. self.assertEqual(downloaded['format_id'], 'audio-high')
  137. ydl = YDL({'format': 'worstaudio'})
  138. ydl.process_ie_result(info_dict.copy())
  139. downloaded = ydl.downloaded_info_dicts[0]
  140. self.assertEqual(downloaded['format_id'], 'audio-low')
  141. formats = [
  142. {'format_id': 'vid-low', 'ext': 'mp4', 'preference': 1, 'url': TEST_URL},
  143. {'format_id': 'vid-high', 'ext': 'mp4', 'preference': 2, 'url': TEST_URL},
  144. ]
  145. info_dict = _make_result(formats)
  146. ydl = YDL({'format': 'bestaudio/worstaudio/best'})
  147. ydl.process_ie_result(info_dict.copy())
  148. downloaded = ydl.downloaded_info_dicts[0]
  149. self.assertEqual(downloaded['format_id'], 'vid-high')
  150. def test_format_selection_audio_exts(self):
  151. formats = [
  152. {'format_id': 'mp3-64', 'ext': 'mp3', 'abr': 64, 'url': 'http://_', 'vcodec': 'none'},
  153. {'format_id': 'ogg-64', 'ext': 'ogg', 'abr': 64, 'url': 'http://_', 'vcodec': 'none'},
  154. {'format_id': 'aac-64', 'ext': 'aac', 'abr': 64, 'url': 'http://_', 'vcodec': 'none'},
  155. {'format_id': 'mp3-32', 'ext': 'mp3', 'abr': 32, 'url': 'http://_', 'vcodec': 'none'},
  156. {'format_id': 'aac-32', 'ext': 'aac', 'abr': 32, 'url': 'http://_', 'vcodec': 'none'},
  157. ]
  158. info_dict = _make_result(formats)
  159. ydl = YDL({'format': 'best', 'format_sort': ['abr', 'ext']})
  160. ydl.sort_formats(info_dict)
  161. ydl.process_ie_result(copy.deepcopy(info_dict))
  162. downloaded = ydl.downloaded_info_dicts[0]
  163. self.assertEqual(downloaded['format_id'], 'aac-64')
  164. ydl = YDL({'format': 'mp3'})
  165. ydl.sort_formats(info_dict)
  166. ydl.process_ie_result(copy.deepcopy(info_dict))
  167. downloaded = ydl.downloaded_info_dicts[0]
  168. self.assertEqual(downloaded['format_id'], 'mp3-64')
  169. ydl = YDL({'prefer_free_formats': True, 'format_sort': ['abr', 'ext']})
  170. ydl.sort_formats(info_dict)
  171. ydl.process_ie_result(copy.deepcopy(info_dict))
  172. downloaded = ydl.downloaded_info_dicts[0]
  173. self.assertEqual(downloaded['format_id'], 'ogg-64')
  174. def test_format_selection_video(self):
  175. formats = [
  176. {'format_id': 'dash-video-low', 'ext': 'mp4', 'preference': 1, 'acodec': 'none', 'url': TEST_URL},
  177. {'format_id': 'dash-video-high', 'ext': 'mp4', 'preference': 2, 'acodec': 'none', 'url': TEST_URL},
  178. {'format_id': 'vid', 'ext': 'mp4', 'preference': 3, 'url': TEST_URL},
  179. ]
  180. info_dict = _make_result(formats)
  181. ydl = YDL({'format': 'bestvideo'})
  182. ydl.process_ie_result(info_dict.copy())
  183. downloaded = ydl.downloaded_info_dicts[0]
  184. self.assertEqual(downloaded['format_id'], 'dash-video-high')
  185. ydl = YDL({'format': 'worstvideo'})
  186. ydl.process_ie_result(info_dict.copy())
  187. downloaded = ydl.downloaded_info_dicts[0]
  188. self.assertEqual(downloaded['format_id'], 'dash-video-low')
  189. ydl = YDL({'format': 'bestvideo[format_id^=dash][format_id$=low]'})
  190. ydl.process_ie_result(info_dict.copy())
  191. downloaded = ydl.downloaded_info_dicts[0]
  192. self.assertEqual(downloaded['format_id'], 'dash-video-low')
  193. formats = [
  194. {'format_id': 'vid-vcodec-dot', 'ext': 'mp4', 'preference': 1, 'vcodec': 'avc1.123456', 'acodec': 'none', 'url': TEST_URL},
  195. ]
  196. info_dict = _make_result(formats)
  197. ydl = YDL({'format': 'bestvideo[vcodec=avc1.123456]'})
  198. ydl.process_ie_result(info_dict.copy())
  199. downloaded = ydl.downloaded_info_dicts[0]
  200. self.assertEqual(downloaded['format_id'], 'vid-vcodec-dot')
  201. def test_format_selection_string_ops(self):
  202. formats = [
  203. {'format_id': 'abc-cba', 'ext': 'mp4', 'url': TEST_URL},
  204. {'format_id': 'zxc-cxz', 'ext': 'webm', 'url': TEST_URL},
  205. ]
  206. info_dict = _make_result(formats)
  207. # equals (=)
  208. ydl = YDL({'format': '[format_id=abc-cba]'})
  209. ydl.process_ie_result(info_dict.copy())
  210. downloaded = ydl.downloaded_info_dicts[0]
  211. self.assertEqual(downloaded['format_id'], 'abc-cba')
  212. # does not equal (!=)
  213. ydl = YDL({'format': '[format_id!=abc-cba]'})
  214. ydl.process_ie_result(info_dict.copy())
  215. downloaded = ydl.downloaded_info_dicts[0]
  216. self.assertEqual(downloaded['format_id'], 'zxc-cxz')
  217. ydl = YDL({'format': '[format_id!=abc-cba][format_id!=zxc-cxz]'})
  218. self.assertRaises(ExtractorError, ydl.process_ie_result, info_dict.copy())
  219. # starts with (^=)
  220. ydl = YDL({'format': '[format_id^=abc]'})
  221. ydl.process_ie_result(info_dict.copy())
  222. downloaded = ydl.downloaded_info_dicts[0]
  223. self.assertEqual(downloaded['format_id'], 'abc-cba')
  224. # does not start with (!^=)
  225. ydl = YDL({'format': '[format_id!^=abc]'})
  226. ydl.process_ie_result(info_dict.copy())
  227. downloaded = ydl.downloaded_info_dicts[0]
  228. self.assertEqual(downloaded['format_id'], 'zxc-cxz')
  229. ydl = YDL({'format': '[format_id!^=abc][format_id!^=zxc]'})
  230. self.assertRaises(ExtractorError, ydl.process_ie_result, info_dict.copy())
  231. # ends with ($=)
  232. ydl = YDL({'format': '[format_id$=cba]'})
  233. ydl.process_ie_result(info_dict.copy())
  234. downloaded = ydl.downloaded_info_dicts[0]
  235. self.assertEqual(downloaded['format_id'], 'abc-cba')
  236. # does not end with (!$=)
  237. ydl = YDL({'format': '[format_id!$=cba]'})
  238. ydl.process_ie_result(info_dict.copy())
  239. downloaded = ydl.downloaded_info_dicts[0]
  240. self.assertEqual(downloaded['format_id'], 'zxc-cxz')
  241. ydl = YDL({'format': '[format_id!$=cba][format_id!$=cxz]'})
  242. self.assertRaises(ExtractorError, ydl.process_ie_result, info_dict.copy())
  243. # contains (*=)
  244. ydl = YDL({'format': '[format_id*=bc-cb]'})
  245. ydl.process_ie_result(info_dict.copy())
  246. downloaded = ydl.downloaded_info_dicts[0]
  247. self.assertEqual(downloaded['format_id'], 'abc-cba')
  248. # does not contain (!*=)
  249. ydl = YDL({'format': '[format_id!*=bc-cb]'})
  250. ydl.process_ie_result(info_dict.copy())
  251. downloaded = ydl.downloaded_info_dicts[0]
  252. self.assertEqual(downloaded['format_id'], 'zxc-cxz')
  253. ydl = YDL({'format': '[format_id!*=abc][format_id!*=zxc]'})
  254. self.assertRaises(ExtractorError, ydl.process_ie_result, info_dict.copy())
  255. ydl = YDL({'format': '[format_id!*=-]'})
  256. self.assertRaises(ExtractorError, ydl.process_ie_result, info_dict.copy())
  257. def test_youtube_format_selection(self):
  258. # FIXME: Rewrite in accordance with the new format sorting options
  259. return
  260. order = [
  261. '38', '37', '46', '22', '45', '35', '44', '18', '34', '43', '6', '5', '17', '36', '13',
  262. # Apple HTTP Live Streaming
  263. '96', '95', '94', '93', '92', '132', '151',
  264. # 3D
  265. '85', '84', '102', '83', '101', '82', '100',
  266. # Dash video
  267. '137', '248', '136', '247', '135', '246',
  268. '245', '244', '134', '243', '133', '242', '160',
  269. # Dash audio
  270. '141', '172', '140', '171', '139',
  271. ]
  272. def format_info(f_id):
  273. info = YoutubeIE._formats[f_id].copy()
  274. # XXX: In real cases InfoExtractor._parse_mpd_formats() fills up 'acodec'
  275. # and 'vcodec', while in tests such information is incomplete since
  276. # commit a6c2c24479e5f4827ceb06f64d855329c0a6f593
  277. # test_YoutubeDL.test_youtube_format_selection is broken without
  278. # this fix
  279. if 'acodec' in info and 'vcodec' not in info:
  280. info['vcodec'] = 'none'
  281. elif 'vcodec' in info and 'acodec' not in info:
  282. info['acodec'] = 'none'
  283. info['format_id'] = f_id
  284. info['url'] = 'url:' + f_id
  285. return info
  286. formats_order = [format_info(f_id) for f_id in order]
  287. info_dict = _make_result(list(formats_order), extractor='youtube')
  288. ydl = YDL({'format': 'bestvideo+bestaudio'})
  289. ydl.sort_formats(info_dict)
  290. ydl.process_ie_result(info_dict)
  291. downloaded = ydl.downloaded_info_dicts[0]
  292. self.assertEqual(downloaded['format_id'], '248+172')
  293. self.assertEqual(downloaded['ext'], 'mp4')
  294. info_dict = _make_result(list(formats_order), extractor='youtube')
  295. ydl = YDL({'format': 'bestvideo[height>=999999]+bestaudio/best'})
  296. ydl.sort_formats(info_dict)
  297. ydl.process_ie_result(info_dict)
  298. downloaded = ydl.downloaded_info_dicts[0]
  299. self.assertEqual(downloaded['format_id'], '38')
  300. info_dict = _make_result(list(formats_order), extractor='youtube')
  301. ydl = YDL({'format': 'bestvideo/best,bestaudio'})
  302. ydl.sort_formats(info_dict)
  303. ydl.process_ie_result(info_dict)
  304. downloaded_ids = [info['format_id'] for info in ydl.downloaded_info_dicts]
  305. self.assertEqual(downloaded_ids, ['137', '141'])
  306. info_dict = _make_result(list(formats_order), extractor='youtube')
  307. ydl = YDL({'format': '(bestvideo[ext=mp4],bestvideo[ext=webm])+bestaudio'})
  308. ydl.sort_formats(info_dict)
  309. ydl.process_ie_result(info_dict)
  310. downloaded_ids = [info['format_id'] for info in ydl.downloaded_info_dicts]
  311. self.assertEqual(downloaded_ids, ['137+141', '248+141'])
  312. info_dict = _make_result(list(formats_order), extractor='youtube')
  313. ydl = YDL({'format': '(bestvideo[ext=mp4],bestvideo[ext=webm])[height<=720]+bestaudio'})
  314. ydl.sort_formats(info_dict)
  315. ydl.process_ie_result(info_dict)
  316. downloaded_ids = [info['format_id'] for info in ydl.downloaded_info_dicts]
  317. self.assertEqual(downloaded_ids, ['136+141', '247+141'])
  318. info_dict = _make_result(list(formats_order), extractor='youtube')
  319. ydl = YDL({'format': '(bestvideo[ext=none]/bestvideo[ext=webm])+bestaudio'})
  320. ydl.sort_formats(info_dict)
  321. ydl.process_ie_result(info_dict)
  322. downloaded_ids = [info['format_id'] for info in ydl.downloaded_info_dicts]
  323. self.assertEqual(downloaded_ids, ['248+141'])
  324. for f1, f2 in zip(formats_order, formats_order[1:]):
  325. info_dict = _make_result([f1, f2], extractor='youtube')
  326. ydl = YDL({'format': 'best/bestvideo'})
  327. ydl.sort_formats(info_dict)
  328. ydl.process_ie_result(info_dict)
  329. downloaded = ydl.downloaded_info_dicts[0]
  330. self.assertEqual(downloaded['format_id'], f1['format_id'])
  331. info_dict = _make_result([f2, f1], extractor='youtube')
  332. ydl = YDL({'format': 'best/bestvideo'})
  333. ydl.sort_formats(info_dict)
  334. ydl.process_ie_result(info_dict)
  335. downloaded = ydl.downloaded_info_dicts[0]
  336. self.assertEqual(downloaded['format_id'], f1['format_id'])
  337. def test_audio_only_extractor_format_selection(self):
  338. # For extractors with incomplete formats (all formats are audio-only or
  339. # video-only) best and worst should fallback to corresponding best/worst
  340. # video-only or audio-only formats (as per
  341. # https://github.com/ytdl-org/youtube-dl/pull/5556)
  342. formats = [
  343. {'format_id': 'low', 'ext': 'mp3', 'preference': 1, 'vcodec': 'none', 'url': TEST_URL},
  344. {'format_id': 'high', 'ext': 'mp3', 'preference': 2, 'vcodec': 'none', 'url': TEST_URL},
  345. ]
  346. info_dict = _make_result(formats)
  347. ydl = YDL({'format': 'best'})
  348. ydl.process_ie_result(info_dict.copy())
  349. downloaded = ydl.downloaded_info_dicts[0]
  350. self.assertEqual(downloaded['format_id'], 'high')
  351. ydl = YDL({'format': 'worst'})
  352. ydl.process_ie_result(info_dict.copy())
  353. downloaded = ydl.downloaded_info_dicts[0]
  354. self.assertEqual(downloaded['format_id'], 'low')
  355. def test_format_not_available(self):
  356. formats = [
  357. {'format_id': 'regular', 'ext': 'mp4', 'height': 360, 'url': TEST_URL},
  358. {'format_id': 'video', 'ext': 'mp4', 'height': 720, 'acodec': 'none', 'url': TEST_URL},
  359. ]
  360. info_dict = _make_result(formats)
  361. # This must fail since complete video-audio format does not match filter
  362. # and extractor does not provide incomplete only formats (i.e. only
  363. # video-only or audio-only).
  364. ydl = YDL({'format': 'best[height>360]'})
  365. self.assertRaises(ExtractorError, ydl.process_ie_result, info_dict.copy())
  366. def test_format_selection_issue_10083(self):
  367. # See https://github.com/ytdl-org/youtube-dl/issues/10083
  368. formats = [
  369. {'format_id': 'regular', 'height': 360, 'url': TEST_URL},
  370. {'format_id': 'video', 'height': 720, 'acodec': 'none', 'url': TEST_URL},
  371. {'format_id': 'audio', 'vcodec': 'none', 'url': TEST_URL},
  372. ]
  373. info_dict = _make_result(formats)
  374. ydl = YDL({'format': 'best[height>360]/bestvideo[height>360]+bestaudio'})
  375. ydl.process_ie_result(info_dict.copy())
  376. self.assertEqual(ydl.downloaded_info_dicts[0]['format_id'], 'video+audio')
  377. def test_invalid_format_specs(self):
  378. def assert_syntax_error(format_spec):
  379. self.assertRaises(SyntaxError, YDL, {'format': format_spec})
  380. assert_syntax_error('bestvideo,,best')
  381. assert_syntax_error('+bestaudio')
  382. assert_syntax_error('bestvideo+')
  383. assert_syntax_error('/')
  384. assert_syntax_error('[720<height]')
  385. def test_format_filtering(self):
  386. formats = [
  387. {'format_id': 'A', 'filesize': 500, 'width': 1000},
  388. {'format_id': 'B', 'filesize': 1000, 'width': 500},
  389. {'format_id': 'C', 'filesize': 1000, 'width': 400},
  390. {'format_id': 'D', 'filesize': 2000, 'width': 600},
  391. {'format_id': 'E', 'filesize': 3000},
  392. {'format_id': 'F'},
  393. {'format_id': 'G', 'filesize': 1000000},
  394. ]
  395. for f in formats:
  396. f['url'] = 'http://_/'
  397. f['ext'] = 'unknown'
  398. info_dict = _make_result(formats, _format_sort_fields=('id', ))
  399. ydl = YDL({'format': 'best[filesize<3000]'})
  400. ydl.process_ie_result(info_dict)
  401. downloaded = ydl.downloaded_info_dicts[0]
  402. self.assertEqual(downloaded['format_id'], 'D')
  403. ydl = YDL({'format': 'best[filesize<=3000]'})
  404. ydl.process_ie_result(info_dict)
  405. downloaded = ydl.downloaded_info_dicts[0]
  406. self.assertEqual(downloaded['format_id'], 'E')
  407. ydl = YDL({'format': 'best[filesize <= ? 3000]'})
  408. ydl.process_ie_result(info_dict)
  409. downloaded = ydl.downloaded_info_dicts[0]
  410. self.assertEqual(downloaded['format_id'], 'F')
  411. ydl = YDL({'format': 'best [filesize = 1000] [width>450]'})
  412. ydl.process_ie_result(info_dict)
  413. downloaded = ydl.downloaded_info_dicts[0]
  414. self.assertEqual(downloaded['format_id'], 'B')
  415. ydl = YDL({'format': 'best [filesize = 1000] [width!=450]'})
  416. ydl.process_ie_result(info_dict)
  417. downloaded = ydl.downloaded_info_dicts[0]
  418. self.assertEqual(downloaded['format_id'], 'C')
  419. ydl = YDL({'format': '[filesize>?1]'})
  420. ydl.process_ie_result(info_dict)
  421. downloaded = ydl.downloaded_info_dicts[0]
  422. self.assertEqual(downloaded['format_id'], 'G')
  423. ydl = YDL({'format': '[filesize<1M]'})
  424. ydl.process_ie_result(info_dict)
  425. downloaded = ydl.downloaded_info_dicts[0]
  426. self.assertEqual(downloaded['format_id'], 'E')
  427. ydl = YDL({'format': '[filesize<1MiB]'})
  428. ydl.process_ie_result(info_dict)
  429. downloaded = ydl.downloaded_info_dicts[0]
  430. self.assertEqual(downloaded['format_id'], 'G')
  431. ydl = YDL({'format': 'all[width>=400][width<=600]'})
  432. ydl.process_ie_result(info_dict)
  433. downloaded_ids = [info['format_id'] for info in ydl.downloaded_info_dicts]
  434. self.assertEqual(downloaded_ids, ['D', 'C', 'B'])
  435. ydl = YDL({'format': 'best[height<40]'})
  436. with contextlib.suppress(ExtractorError):
  437. ydl.process_ie_result(info_dict)
  438. self.assertEqual(ydl.downloaded_info_dicts, [])
  439. def test_default_format_spec(self):
  440. ydl = YDL({'simulate': True})
  441. self.assertEqual(ydl._default_format_spec({}), 'bestvideo*+bestaudio/best')
  442. ydl = YDL({})
  443. self.assertEqual(ydl._default_format_spec({'is_live': True}), 'best/bestvideo+bestaudio')
  444. ydl = YDL({'simulate': True})
  445. self.assertEqual(ydl._default_format_spec({'is_live': True}), 'bestvideo*+bestaudio/best')
  446. ydl = YDL({'outtmpl': '-'})
  447. self.assertEqual(ydl._default_format_spec({}), 'best/bestvideo+bestaudio')
  448. ydl = YDL({})
  449. self.assertEqual(ydl._default_format_spec({}, download=False), 'bestvideo*+bestaudio/best')
  450. self.assertEqual(ydl._default_format_spec({'is_live': True}), 'best/bestvideo+bestaudio')
  451. class TestYoutubeDL(unittest.TestCase):
  452. def test_subtitles(self):
  453. def s_formats(lang, autocaption=False):
  454. return [{
  455. 'ext': ext,
  456. 'url': f'http://localhost/video.{lang}.{ext}',
  457. '_auto': autocaption,
  458. } for ext in ['vtt', 'srt', 'ass']]
  459. subtitles = {l: s_formats(l) for l in ['en', 'fr', 'es']}
  460. auto_captions = {l: s_formats(l, True) for l in ['it', 'pt', 'es']}
  461. info_dict = {
  462. 'id': 'test',
  463. 'title': 'Test',
  464. 'url': 'http://localhost/video.mp4',
  465. 'subtitles': subtitles,
  466. 'automatic_captions': auto_captions,
  467. 'extractor': 'TEST',
  468. 'webpage_url': 'http://example.com/watch?v=shenanigans',
  469. }
  470. def get_info(params={}):
  471. params.setdefault('simulate', True)
  472. ydl = YDL(params)
  473. ydl.report_warning = lambda *args, **kargs: None
  474. return ydl.process_video_result(info_dict, download=False)
  475. result = get_info()
  476. self.assertFalse(result.get('requested_subtitles'))
  477. self.assertEqual(result['subtitles'], subtitles)
  478. self.assertEqual(result['automatic_captions'], auto_captions)
  479. result = get_info({'writesubtitles': True})
  480. subs = result['requested_subtitles']
  481. self.assertTrue(subs)
  482. self.assertEqual(set(subs.keys()), {'en'})
  483. self.assertTrue(subs['en'].get('data') is None)
  484. self.assertEqual(subs['en']['ext'], 'ass')
  485. result = get_info({'writesubtitles': True, 'subtitlesformat': 'foo/srt'})
  486. subs = result['requested_subtitles']
  487. self.assertEqual(subs['en']['ext'], 'srt')
  488. result = get_info({'writesubtitles': True, 'subtitleslangs': ['es', 'fr', 'it']})
  489. subs = result['requested_subtitles']
  490. self.assertTrue(subs)
  491. self.assertEqual(set(subs.keys()), {'es', 'fr'})
  492. result = get_info({'writesubtitles': True, 'subtitleslangs': ['all', '-en']})
  493. subs = result['requested_subtitles']
  494. self.assertTrue(subs)
  495. self.assertEqual(set(subs.keys()), {'es', 'fr'})
  496. result = get_info({'writesubtitles': True, 'subtitleslangs': ['en', 'fr', '-en']})
  497. subs = result['requested_subtitles']
  498. self.assertTrue(subs)
  499. self.assertEqual(set(subs.keys()), {'fr'})
  500. result = get_info({'writesubtitles': True, 'subtitleslangs': ['-en', 'en']})
  501. subs = result['requested_subtitles']
  502. self.assertTrue(subs)
  503. self.assertEqual(set(subs.keys()), {'en'})
  504. result = get_info({'writesubtitles': True, 'subtitleslangs': ['e.+']})
  505. subs = result['requested_subtitles']
  506. self.assertTrue(subs)
  507. self.assertEqual(set(subs.keys()), {'es', 'en'})
  508. result = get_info({'writesubtitles': True, 'writeautomaticsub': True, 'subtitleslangs': ['es', 'pt']})
  509. subs = result['requested_subtitles']
  510. self.assertTrue(subs)
  511. self.assertEqual(set(subs.keys()), {'es', 'pt'})
  512. self.assertFalse(subs['es']['_auto'])
  513. self.assertTrue(subs['pt']['_auto'])
  514. result = get_info({'writeautomaticsub': True, 'subtitleslangs': ['es', 'pt']})
  515. subs = result['requested_subtitles']
  516. self.assertTrue(subs)
  517. self.assertEqual(set(subs.keys()), {'es', 'pt'})
  518. self.assertTrue(subs['es']['_auto'])
  519. self.assertTrue(subs['pt']['_auto'])
  520. def test_add_extra_info(self):
  521. test_dict = {
  522. 'extractor': 'Foo',
  523. }
  524. extra_info = {
  525. 'extractor': 'Bar',
  526. 'playlist': 'funny videos',
  527. }
  528. YDL.add_extra_info(test_dict, extra_info)
  529. self.assertEqual(test_dict['extractor'], 'Foo')
  530. self.assertEqual(test_dict['playlist'], 'funny videos')
  531. outtmpl_info = {
  532. 'id': '1234',
  533. 'ext': 'mp4',
  534. 'width': None,
  535. 'height': 1080,
  536. 'filesize': 1024,
  537. 'title1': '$PATH',
  538. 'title2': '%PATH%',
  539. 'title3': 'foo/bar\\test',
  540. 'title4': 'foo "bar" test',
  541. 'title5': 'áéí 𝐀',
  542. 'timestamp': 1618488000,
  543. 'duration': 100000,
  544. 'playlist_index': 1,
  545. 'playlist_autonumber': 2,
  546. '__last_playlist_index': 100,
  547. 'n_entries': 10,
  548. 'formats': [
  549. {'id': 'id 1', 'height': 1080, 'width': 1920},
  550. {'id': 'id 2', 'height': 720},
  551. {'id': 'id 3'},
  552. ],
  553. }
  554. def test_prepare_outtmpl_and_filename(self):
  555. def test(tmpl, expected, *, info=None, **params):
  556. params['outtmpl'] = tmpl
  557. ydl = FakeYDL(params)
  558. ydl._num_downloads = 1
  559. self.assertEqual(ydl.validate_outtmpl(tmpl), None)
  560. out = ydl.evaluate_outtmpl(tmpl, info or self.outtmpl_info)
  561. fname = ydl.prepare_filename(info or self.outtmpl_info)
  562. if not isinstance(expected, (list, tuple)):
  563. expected = (expected, expected)
  564. for (name, got), expect in zip((('outtmpl', out), ('filename', fname)), expected):
  565. if callable(expect):
  566. self.assertTrue(expect(got), f'Wrong {name} from {tmpl}')
  567. elif expect is not None:
  568. self.assertEqual(got, expect, f'Wrong {name} from {tmpl}')
  569. # Side-effects
  570. original_infodict = dict(self.outtmpl_info)
  571. test('foo.bar', 'foo.bar')
  572. original_infodict['epoch'] = self.outtmpl_info.get('epoch')
  573. self.assertTrue(isinstance(original_infodict['epoch'], int))
  574. test('%(epoch)d', int_or_none)
  575. self.assertEqual(original_infodict, self.outtmpl_info)
  576. # Auto-generated fields
  577. test('%(id)s.%(ext)s', '1234.mp4')
  578. test('%(duration_string)s', ('27:46:40', '27-46-40'))
  579. test('%(resolution)s', '1080p')
  580. test('%(playlist_index|)s', '001')
  581. test('%(playlist_index&{}!)s', '1!')
  582. test('%(playlist_autonumber)s', '02')
  583. test('%(autonumber)s', '00001')
  584. test('%(autonumber+2)03d', '005', autonumber_start=3)
  585. test('%(autonumber)s', '001', autonumber_size=3)
  586. # Escaping %
  587. test('%', '%')
  588. test('%%', '%')
  589. test('%%%%', '%%')
  590. test('%s', '%s')
  591. test('%%%s', '%%s')
  592. test('%d', '%d')
  593. test('%abc%', '%abc%')
  594. test('%%(width)06d.%(ext)s', '%(width)06d.mp4')
  595. test('%%%(height)s', '%1080')
  596. test('%(width)06d.%(ext)s', 'NA.mp4')
  597. test('%(width)06d.%%(ext)s', 'NA.%(ext)s')
  598. test('%%(width)06d.%(ext)s', '%(width)06d.mp4')
  599. # ID sanitization
  600. test('%(id)s', '_abcd', info={'id': '_abcd'})
  601. test('%(some_id)s', '_abcd', info={'some_id': '_abcd'})
  602. test('%(formats.0.id)s', '_abcd', info={'formats': [{'id': '_abcd'}]})
  603. test('%(id)s', '-abcd', info={'id': '-abcd'})
  604. test('%(id)s', '.abcd', info={'id': '.abcd'})
  605. test('%(id)s', 'ab__cd', info={'id': 'ab__cd'})
  606. test('%(id)s', ('ab:cd', 'ab:cd'), info={'id': 'ab:cd'})
  607. test('%(id.0)s', '-', info={'id': '--'})
  608. # Invalid templates
  609. self.assertTrue(isinstance(YoutubeDL.validate_outtmpl('%(title)'), ValueError))
  610. test('%(invalid@tmpl|def)s', 'none', outtmpl_na_placeholder='none')
  611. test('%(..)s', 'NA')
  612. test('%(formats.{id)s', 'NA')
  613. # Entire info_dict
  614. def expect_same_infodict(out):
  615. got_dict = json.loads(out)
  616. for info_field, expected in self.outtmpl_info.items():
  617. self.assertEqual(got_dict.get(info_field), expected, info_field)
  618. return True
  619. test('%()j', (expect_same_infodict, None))
  620. # NA placeholder
  621. NA_TEST_OUTTMPL = '%(uploader_date)s-%(width)d-%(x|def)s-%(id)s.%(ext)s'
  622. test(NA_TEST_OUTTMPL, 'NA-NA-def-1234.mp4')
  623. test(NA_TEST_OUTTMPL, 'none-none-def-1234.mp4', outtmpl_na_placeholder='none')
  624. test(NA_TEST_OUTTMPL, '--def-1234.mp4', outtmpl_na_placeholder='')
  625. test('%(non_existent.0)s', 'NA')
  626. # String formatting
  627. FMT_TEST_OUTTMPL = '%%(height)%s.%%(ext)s'
  628. test(FMT_TEST_OUTTMPL % 's', '1080.mp4')
  629. test(FMT_TEST_OUTTMPL % 'd', '1080.mp4')
  630. test(FMT_TEST_OUTTMPL % '6d', ' 1080.mp4')
  631. test(FMT_TEST_OUTTMPL % '-6d', '1080 .mp4')
  632. test(FMT_TEST_OUTTMPL % '06d', '001080.mp4')
  633. test(FMT_TEST_OUTTMPL % ' 06d', ' 01080.mp4')
  634. test(FMT_TEST_OUTTMPL % ' 06d', ' 01080.mp4')
  635. test(FMT_TEST_OUTTMPL % '0 6d', ' 01080.mp4')
  636. test(FMT_TEST_OUTTMPL % '0 6d', ' 01080.mp4')
  637. test(FMT_TEST_OUTTMPL % ' 0 6d', ' 01080.mp4')
  638. # Type casting
  639. test('%(id)d', '1234')
  640. test('%(height)c', '1')
  641. test('%(ext)c', 'm')
  642. test('%(id)d %(id)r', "1234 '1234'")
  643. test('%(id)r %(height)r', "'1234' 1080")
  644. test('%(title5)a %(height)a', (R"'\xe1\xe9\xed \U0001d400' 1080", None))
  645. test('%(ext)s-%(ext|def)d', 'mp4-def')
  646. test('%(width|0)04d', '0')
  647. test('a%(width|b)d', 'ab', outtmpl_na_placeholder='none')
  648. FORMATS = self.outtmpl_info['formats']
  649. # Custom type casting
  650. test('%(formats.:.id)l', 'id 1, id 2, id 3')
  651. test('%(formats.:.id)#l', ('id 1\nid 2\nid 3', 'id 1 id 2 id 3'))
  652. test('%(ext)l', 'mp4')
  653. test('%(formats.:.id) 18l', ' id 1, id 2, id 3')
  654. test('%(formats)j', (json.dumps(FORMATS), None))
  655. test('%(formats)#j', (
  656. json.dumps(FORMATS, indent=4),
  657. json.dumps(FORMATS, indent=4).replace(':', ':').replace('"', '"').replace('\n', ' '),
  658. ))
  659. test('%(title5).3B', 'á')
  660. test('%(title5)U', 'áéí 𝐀')
  661. test('%(title5)#U', 'a\u0301e\u0301i\u0301 𝐀')
  662. test('%(title5)+U', 'áéí A')
  663. test('%(title5)+#U', 'a\u0301e\u0301i\u0301 A')
  664. test('%(height)D', '1k')
  665. test('%(filesize)#D', '1Ki')
  666. test('%(height)5.2D', ' 1.08k')
  667. test('%(title4)#S', 'foo_bar_test')
  668. test('%(title4).10S', ('foo "bar" ', 'foo "bar"' + ('#' if compat_os_name == 'nt' else ' ')))
  669. if compat_os_name == 'nt':
  670. test('%(title4)q', ('"foo ""bar"" test"', None))
  671. test('%(formats.:.id)#q', ('"id 1" "id 2" "id 3"', None))
  672. test('%(formats.0.id)#q', ('"id 1"', None))
  673. else:
  674. test('%(title4)q', ('\'foo "bar" test\'', '\'foo "bar" test\''))
  675. test('%(formats.:.id)#q', "'id 1' 'id 2' 'id 3'")
  676. test('%(formats.0.id)#q', "'id 1'")
  677. # Internal formatting
  678. test('%(timestamp-1000>%H-%M-%S)s', '11-43-20')
  679. test('%(title|%)s %(title|%%)s', '% %%')
  680. test('%(id+1-height+3)05d', '00158')
  681. test('%(width+100)05d', 'NA')
  682. test('%(filesize*8)d', '8192')
  683. test('%(formats.0) 15s', ('% 15s' % FORMATS[0], None))
  684. test('%(formats.0)r', (repr(FORMATS[0]), None))
  685. test('%(height.0)03d', '001')
  686. test('%(-height.0)04d', '-001')
  687. test('%(formats.-1.id)s', FORMATS[-1]['id'])
  688. test('%(formats.0.id.-1)d', FORMATS[0]['id'][-1])
  689. test('%(formats.3)s', 'NA')
  690. test('%(formats.:2:-1)r', repr(FORMATS[:2:-1]))
  691. test('%(formats.0.id.-1+id)f', '1235.000000')
  692. test('%(formats.0.id.-1+formats.1.id.-1)d', '3')
  693. out = json.dumps([{'id': f['id'], 'height.:2': str(f['height'])[:2]}
  694. if 'height' in f else {'id': f['id']}
  695. for f in FORMATS])
  696. test('%(formats.:.{id,height.:2})j', (out, None))
  697. test('%(formats.:.{id,height}.id)l', ', '.join(f['id'] for f in FORMATS))
  698. test('%(.{id,title})j', ('{"id": "1234"}', '{"id": "1234"}'))
  699. # Alternates
  700. test('%(title,id)s', '1234')
  701. test('%(width-100,height+20|def)d', '1100')
  702. test('%(width-100,height+width|def)s', 'def')
  703. test('%(timestamp-x>%H\\,%M\\,%S,timestamp>%H\\,%M\\,%S)s', '12,00,00')
  704. # Replacement
  705. test('%(id&foo)s.bar', 'foo.bar')
  706. test('%(title&foo)s.bar', 'NA.bar')
  707. test('%(title&foo|baz)s.bar', 'baz.bar')
  708. test('%(x,id&foo|baz)s.bar', 'foo.bar')
  709. test('%(x,title&foo|baz)s.bar', 'baz.bar')
  710. test('%(id&a\nb|)s', ('a\nb', 'a b'))
  711. test('%(id&hi {:>10} {}|)s', 'hi 1234 1234')
  712. test(R'%(id&{0} {}|)s', 'NA')
  713. test(R'%(id&{0.1}|)s', 'NA')
  714. test('%(height&{:,d})S', '1,080')
  715. # Laziness
  716. def gen():
  717. yield from range(5)
  718. raise self.assertTrue(False, 'LazyList should not be evaluated till here')
  719. test('%(key.4)s', '4', info={'key': LazyList(gen())})
  720. # Empty filename
  721. test('%(foo|)s-%(bar|)s.%(ext)s', '-.mp4')
  722. # test('%(foo|)s.%(ext)s', ('.mp4', '_.mp4')) # FIXME: ?
  723. # test('%(foo|)s', ('', '_')) # FIXME: ?
  724. # Environment variable expansion for prepare_filename
  725. os.environ['__yt_dlp_var'] = 'expanded'
  726. envvar = '%__yt_dlp_var%' if compat_os_name == 'nt' else '$__yt_dlp_var'
  727. test(envvar, (envvar, 'expanded'))
  728. if compat_os_name == 'nt':
  729. test('%s%', ('%s%', '%s%'))
  730. os.environ['s'] = 'expanded'
  731. test('%s%', ('%s%', 'expanded')) # %s% should be expanded before escaping %s
  732. os.environ['(test)s'] = 'expanded'
  733. test('%(test)s%', ('NA%', 'expanded')) # Environment should take priority over template
  734. # Path expansion and escaping
  735. test('Hello %(title1)s', 'Hello $PATH')
  736. test('Hello %(title2)s', 'Hello %PATH%')
  737. test('%(title3)s', ('foo/bar\\test', 'foo⧸bar⧹test'))
  738. test('folder/%(title3)s', ('folder/foo/bar\\test', f'folder{os.path.sep}foo⧸bar⧹test'))
  739. def test_format_note(self):
  740. ydl = YoutubeDL()
  741. self.assertEqual(ydl._format_note({}), '')
  742. assertRegexpMatches(self, ydl._format_note({
  743. 'vbr': 10,
  744. }), r'^\s*10k$')
  745. assertRegexpMatches(self, ydl._format_note({
  746. 'fps': 30,
  747. }), r'^30fps$')
  748. def test_postprocessors(self):
  749. filename = 'post-processor-testfile.mp4'
  750. audiofile = filename + '.mp3'
  751. class SimplePP(PostProcessor):
  752. def run(self, info):
  753. with open(audiofile, 'w') as f:
  754. f.write('EXAMPLE')
  755. return [info['filepath']], info
  756. def run_pp(params, pp):
  757. with open(filename, 'w') as f:
  758. f.write('EXAMPLE')
  759. ydl = YoutubeDL(params)
  760. ydl.add_post_processor(pp())
  761. ydl.post_process(filename, {'filepath': filename})
  762. run_pp({'keepvideo': True}, SimplePP)
  763. self.assertTrue(os.path.exists(filename), f'{filename} doesn\'t exist')
  764. self.assertTrue(os.path.exists(audiofile), f'{audiofile} doesn\'t exist')
  765. os.unlink(filename)
  766. os.unlink(audiofile)
  767. run_pp({'keepvideo': False}, SimplePP)
  768. self.assertFalse(os.path.exists(filename), f'{filename} exists')
  769. self.assertTrue(os.path.exists(audiofile), f'{audiofile} doesn\'t exist')
  770. os.unlink(audiofile)
  771. class ModifierPP(PostProcessor):
  772. def run(self, info):
  773. with open(info['filepath'], 'w') as f:
  774. f.write('MODIFIED')
  775. return [], info
  776. run_pp({'keepvideo': False}, ModifierPP)
  777. self.assertTrue(os.path.exists(filename), f'{filename} doesn\'t exist')
  778. os.unlink(filename)
  779. def test_match_filter(self):
  780. first = {
  781. 'id': '1',
  782. 'url': TEST_URL,
  783. 'title': 'one',
  784. 'extractor': 'TEST',
  785. 'duration': 30,
  786. 'filesize': 10 * 1024,
  787. 'playlist_id': '42',
  788. 'uploader': '變態妍字幕版 太妍 тест',
  789. 'creator': "тест ' 123 ' тест--",
  790. 'webpage_url': 'http://example.com/watch?v=shenanigans',
  791. }
  792. second = {
  793. 'id': '2',
  794. 'url': TEST_URL,
  795. 'title': 'two',
  796. 'extractor': 'TEST',
  797. 'duration': 10,
  798. 'description': 'foo',
  799. 'filesize': 5 * 1024,
  800. 'playlist_id': '43',
  801. 'uploader': 'тест 123',
  802. 'webpage_url': 'http://example.com/watch?v=SHENANIGANS',
  803. }
  804. videos = [first, second]
  805. def get_videos(filter_=None):
  806. ydl = YDL({'match_filter': filter_, 'simulate': True})
  807. for v in videos:
  808. ydl.process_ie_result(v.copy(), download=True)
  809. return [v['id'] for v in ydl.downloaded_info_dicts]
  810. res = get_videos()
  811. self.assertEqual(res, ['1', '2'])
  812. def f(v, incomplete):
  813. if v['id'] == '1':
  814. return None
  815. else:
  816. return 'Video id is not 1'
  817. res = get_videos(f)
  818. self.assertEqual(res, ['1'])
  819. f = match_filter_func('duration < 30')
  820. res = get_videos(f)
  821. self.assertEqual(res, ['2'])
  822. f = match_filter_func('description = foo')
  823. res = get_videos(f)
  824. self.assertEqual(res, ['2'])
  825. f = match_filter_func('description =? foo')
  826. res = get_videos(f)
  827. self.assertEqual(res, ['1', '2'])
  828. f = match_filter_func('filesize > 5KiB')
  829. res = get_videos(f)
  830. self.assertEqual(res, ['1'])
  831. f = match_filter_func('playlist_id = 42')
  832. res = get_videos(f)
  833. self.assertEqual(res, ['1'])
  834. f = match_filter_func('uploader = "變態妍字幕版 太妍 тест"')
  835. res = get_videos(f)
  836. self.assertEqual(res, ['1'])
  837. f = match_filter_func('uploader != "變態妍字幕版 太妍 тест"')
  838. res = get_videos(f)
  839. self.assertEqual(res, ['2'])
  840. f = match_filter_func('creator = "тест \' 123 \' тест--"')
  841. res = get_videos(f)
  842. self.assertEqual(res, ['1'])
  843. f = match_filter_func("creator = 'тест \\' 123 \\' тест--'")
  844. res = get_videos(f)
  845. self.assertEqual(res, ['1'])
  846. f = match_filter_func(r"creator = 'тест \' 123 \' тест--' & duration > 30")
  847. res = get_videos(f)
  848. self.assertEqual(res, [])
  849. def test_playlist_items_selection(self):
  850. INDICES, PAGE_SIZE = list(range(1, 11)), 3
  851. def entry(i, evaluated):
  852. evaluated.append(i)
  853. return {
  854. 'id': str(i),
  855. 'title': str(i),
  856. 'url': TEST_URL,
  857. }
  858. def pagedlist_entries(evaluated):
  859. def page_func(n):
  860. start = PAGE_SIZE * n
  861. for i in INDICES[start: start + PAGE_SIZE]:
  862. yield entry(i, evaluated)
  863. return OnDemandPagedList(page_func, PAGE_SIZE)
  864. def page_num(i):
  865. return (i + PAGE_SIZE - 1) // PAGE_SIZE
  866. def generator_entries(evaluated):
  867. for i in INDICES:
  868. yield entry(i, evaluated)
  869. def list_entries(evaluated):
  870. return list(generator_entries(evaluated))
  871. def lazylist_entries(evaluated):
  872. return LazyList(generator_entries(evaluated))
  873. def get_downloaded_info_dicts(params, entries):
  874. ydl = YDL(params)
  875. ydl.process_ie_result({
  876. '_type': 'playlist',
  877. 'id': 'test',
  878. 'extractor': 'test:playlist',
  879. 'extractor_key': 'test:playlist',
  880. 'webpage_url': 'http://example.com',
  881. 'entries': entries,
  882. })
  883. return ydl.downloaded_info_dicts
  884. def test_selection(params, expected_ids, evaluate_all=False):
  885. expected_ids = list(expected_ids)
  886. if evaluate_all:
  887. generator_eval = pagedlist_eval = INDICES
  888. elif not expected_ids:
  889. generator_eval = pagedlist_eval = []
  890. else:
  891. generator_eval = INDICES[0: max(expected_ids)]
  892. pagedlist_eval = INDICES[PAGE_SIZE * page_num(min(expected_ids)) - PAGE_SIZE:
  893. PAGE_SIZE * page_num(max(expected_ids))]
  894. for name, func, expected_eval in (
  895. ('list', list_entries, INDICES),
  896. ('Generator', generator_entries, generator_eval),
  897. # ('LazyList', lazylist_entries, generator_eval), # Generator and LazyList follow the exact same code path
  898. ('PagedList', pagedlist_entries, pagedlist_eval),
  899. ):
  900. evaluated = []
  901. entries = func(evaluated)
  902. results = [(v['playlist_autonumber'] - 1, (int(v['id']), v['playlist_index']))
  903. for v in get_downloaded_info_dicts(params, entries)]
  904. self.assertEqual(results, list(enumerate(zip(expected_ids, expected_ids))), f'Entries of {name} for {params}')
  905. self.assertEqual(sorted(evaluated), expected_eval, f'Evaluation of {name} for {params}')
  906. test_selection({}, INDICES)
  907. test_selection({'playlistend': 20}, INDICES, True)
  908. test_selection({'playlistend': 2}, INDICES[:2])
  909. test_selection({'playliststart': 11}, [], True)
  910. test_selection({'playliststart': 2}, INDICES[1:])
  911. test_selection({'playlist_items': '2-4'}, INDICES[1:4])
  912. test_selection({'playlist_items': '2,4'}, [2, 4])
  913. test_selection({'playlist_items': '20'}, [], True)
  914. test_selection({'playlist_items': '0'}, [])
  915. # Tests for https://github.com/ytdl-org/youtube-dl/issues/10591
  916. test_selection({'playlist_items': '2-4,3-4,3'}, [2, 3, 4])
  917. test_selection({'playlist_items': '4,2'}, [4, 2])
  918. # Tests for https://github.com/yt-dlp/yt-dlp/issues/720
  919. # https://github.com/yt-dlp/yt-dlp/issues/302
  920. test_selection({'playlistreverse': True}, INDICES[::-1])
  921. test_selection({'playliststart': 2, 'playlistreverse': True}, INDICES[:0:-1])
  922. test_selection({'playlist_items': '2,4', 'playlistreverse': True}, [4, 2])
  923. test_selection({'playlist_items': '4,2'}, [4, 2])
  924. # Tests for --playlist-items start:end:step
  925. test_selection({'playlist_items': ':'}, INDICES, True)
  926. test_selection({'playlist_items': '::1'}, INDICES, True)
  927. test_selection({'playlist_items': '::-1'}, INDICES[::-1], True)
  928. test_selection({'playlist_items': ':6'}, INDICES[:6])
  929. test_selection({'playlist_items': ':-6'}, INDICES[:-5], True)
  930. test_selection({'playlist_items': '-1:6:-2'}, INDICES[:4:-2], True)
  931. test_selection({'playlist_items': '9:-6:-2'}, INDICES[8:3:-2], True)
  932. test_selection({'playlist_items': '1:inf:2'}, INDICES[::2], True)
  933. test_selection({'playlist_items': '-2:inf'}, INDICES[-2:], True)
  934. test_selection({'playlist_items': ':inf:-1'}, [], True)
  935. test_selection({'playlist_items': '0-2:2'}, [2])
  936. test_selection({'playlist_items': '1-:2'}, INDICES[::2], True)
  937. test_selection({'playlist_items': '0--2:2'}, INDICES[1:-1:2], True)
  938. test_selection({'playlist_items': '10::3'}, [10], True)
  939. test_selection({'playlist_items': '-1::3'}, [10], True)
  940. test_selection({'playlist_items': '11::3'}, [], True)
  941. test_selection({'playlist_items': '-15::2'}, INDICES[1::2], True)
  942. test_selection({'playlist_items': '-15::15'}, [], True)
  943. def test_do_not_override_ie_key_in_url_transparent(self):
  944. ydl = YDL()
  945. class Foo1IE(InfoExtractor):
  946. _VALID_URL = r'foo1:'
  947. def _real_extract(self, url):
  948. return {
  949. '_type': 'url_transparent',
  950. 'url': 'foo2:',
  951. 'ie_key': 'Foo2',
  952. 'title': 'foo1 title',
  953. 'id': 'foo1_id',
  954. }
  955. class Foo2IE(InfoExtractor):
  956. _VALID_URL = r'foo2:'
  957. def _real_extract(self, url):
  958. return {
  959. '_type': 'url',
  960. 'url': 'foo3:',
  961. 'ie_key': 'Foo3',
  962. }
  963. class Foo3IE(InfoExtractor):
  964. _VALID_URL = r'foo3:'
  965. def _real_extract(self, url):
  966. return _make_result([{'url': TEST_URL}], title='foo3 title')
  967. ydl.add_info_extractor(Foo1IE(ydl))
  968. ydl.add_info_extractor(Foo2IE(ydl))
  969. ydl.add_info_extractor(Foo3IE(ydl))
  970. ydl.extract_info('foo1:')
  971. downloaded = ydl.downloaded_info_dicts[0]
  972. self.assertEqual(downloaded['url'], TEST_URL)
  973. self.assertEqual(downloaded['title'], 'foo1 title')
  974. self.assertEqual(downloaded['id'], 'testid')
  975. self.assertEqual(downloaded['extractor'], 'testex')
  976. self.assertEqual(downloaded['extractor_key'], 'TestEx')
  977. # Test case for https://github.com/ytdl-org/youtube-dl/issues/27064
  978. def test_ignoreerrors_for_playlist_with_url_transparent_iterable_entries(self):
  979. class _YDL(YDL):
  980. def __init__(self, *args, **kwargs):
  981. super().__init__(*args, **kwargs)
  982. def trouble(self, s, tb=None):
  983. pass
  984. ydl = _YDL({
  985. 'format': 'extra',
  986. 'ignoreerrors': True,
  987. })
  988. class VideoIE(InfoExtractor):
  989. _VALID_URL = r'video:(?P<id>\d+)'
  990. def _real_extract(self, url):
  991. video_id = self._match_id(url)
  992. formats = [{
  993. 'format_id': 'default',
  994. 'url': 'url:',
  995. }]
  996. if video_id == '0':
  997. raise ExtractorError('foo')
  998. if video_id == '2':
  999. formats.append({
  1000. 'format_id': 'extra',
  1001. 'url': TEST_URL,
  1002. })
  1003. return {
  1004. 'id': video_id,
  1005. 'title': f'Video {video_id}',
  1006. 'formats': formats,
  1007. }
  1008. class PlaylistIE(InfoExtractor):
  1009. _VALID_URL = r'playlist:'
  1010. def _entries(self):
  1011. for n in range(3):
  1012. video_id = str(n)
  1013. yield {
  1014. '_type': 'url_transparent',
  1015. 'ie_key': VideoIE.ie_key(),
  1016. 'id': video_id,
  1017. 'url': f'video:{video_id}',
  1018. 'title': f'Video Transparent {video_id}',
  1019. }
  1020. def _real_extract(self, url):
  1021. return self.playlist_result(self._entries())
  1022. ydl.add_info_extractor(VideoIE(ydl))
  1023. ydl.add_info_extractor(PlaylistIE(ydl))
  1024. info = ydl.extract_info('playlist:')
  1025. entries = info['entries']
  1026. self.assertEqual(len(entries), 3)
  1027. self.assertTrue(entries[0] is None)
  1028. self.assertTrue(entries[1] is None)
  1029. self.assertEqual(len(ydl.downloaded_info_dicts), 1)
  1030. downloaded = ydl.downloaded_info_dicts[0]
  1031. entries[2].pop('requested_downloads', None)
  1032. self.assertEqual(entries[2], downloaded)
  1033. self.assertEqual(downloaded['url'], TEST_URL)
  1034. self.assertEqual(downloaded['title'], 'Video Transparent 2')
  1035. self.assertEqual(downloaded['id'], '2')
  1036. self.assertEqual(downloaded['extractor'], 'Video')
  1037. self.assertEqual(downloaded['extractor_key'], 'Video')
  1038. def test_header_cookies(self):
  1039. from http.cookiejar import Cookie
  1040. ydl = FakeYDL()
  1041. ydl.report_warning = lambda *_, **__: None
  1042. def cookie(name, value, version=None, domain='', path='', secure=False, expires=None):
  1043. return Cookie(
  1044. version or 0, name, value, None, False,
  1045. domain, bool(domain), bool(domain), path, bool(path),
  1046. secure, expires, False, None, None, rest={})
  1047. _test_url = 'https://yt.dlp/test'
  1048. def test(encoded_cookies, cookies, *, headers=False, round_trip=None, error_re=None):
  1049. def _test():
  1050. ydl.cookiejar.clear()
  1051. ydl._load_cookies(encoded_cookies, autoscope=headers)
  1052. if headers:
  1053. ydl._apply_header_cookies(_test_url)
  1054. data = {'url': _test_url}
  1055. ydl._calc_headers(data)
  1056. self.assertCountEqual(
  1057. map(vars, ydl.cookiejar), map(vars, cookies),
  1058. 'Extracted cookiejar.Cookie is not the same')
  1059. if not headers:
  1060. self.assertEqual(
  1061. data.get('cookies'), round_trip or encoded_cookies,
  1062. 'Cookie is not the same as round trip')
  1063. ydl.__dict__['_YoutubeDL__header_cookies'] = []
  1064. with self.subTest(msg=encoded_cookies):
  1065. if not error_re:
  1066. _test()
  1067. return
  1068. with self.assertRaisesRegex(Exception, error_re):
  1069. _test()
  1070. test('test=value; Domain=.yt.dlp', [cookie('test', 'value', domain='.yt.dlp')])
  1071. test('test=value', [cookie('test', 'value')], error_re=r'Unscoped cookies are not allowed')
  1072. test('cookie1=value1; Domain=.yt.dlp; Path=/test; cookie2=value2; Domain=.yt.dlp; Path=/', [
  1073. cookie('cookie1', 'value1', domain='.yt.dlp', path='/test'),
  1074. cookie('cookie2', 'value2', domain='.yt.dlp', path='/')])
  1075. test('test=value; Domain=.yt.dlp; Path=/test; Secure; Expires=9999999999', [
  1076. cookie('test', 'value', domain='.yt.dlp', path='/test', secure=True, expires=9999999999)])
  1077. test('test="value; "; path=/test; domain=.yt.dlp', [
  1078. cookie('test', 'value; ', domain='.yt.dlp', path='/test')],
  1079. round_trip='test="value\\073 "; Domain=.yt.dlp; Path=/test')
  1080. test('name=; Domain=.yt.dlp', [cookie('name', '', domain='.yt.dlp')],
  1081. round_trip='name=""; Domain=.yt.dlp')
  1082. test('test=value', [cookie('test', 'value', domain='.yt.dlp')], headers=True)
  1083. test('cookie1=value; Domain=.yt.dlp; cookie2=value', [], headers=True, error_re=r'Invalid syntax')
  1084. ydl.deprecated_feature = ydl.report_error
  1085. test('test=value', [], headers=True, error_re=r'Passing cookies as a header is a potential security risk')
  1086. def test_infojson_cookies(self):
  1087. TEST_FILE = 'test_infojson_cookies.info.json'
  1088. TEST_URL = 'https://example.com/example.mp4'
  1089. COOKIES = 'a=b; Domain=.example.com; c=d; Domain=.example.com'
  1090. COOKIE_HEADER = {'Cookie': 'a=b; c=d'}
  1091. ydl = FakeYDL()
  1092. ydl.process_info = lambda x: ydl._write_info_json('test', x, TEST_FILE)
  1093. def make_info(info_header_cookies=False, fmts_header_cookies=False, cookies_field=False):
  1094. fmt = {'url': TEST_URL}
  1095. if fmts_header_cookies:
  1096. fmt['http_headers'] = COOKIE_HEADER
  1097. if cookies_field:
  1098. fmt['cookies'] = COOKIES
  1099. return _make_result([fmt], http_headers=COOKIE_HEADER if info_header_cookies else None)
  1100. def test(initial_info, note):
  1101. result = {}
  1102. result['processed'] = ydl.process_ie_result(initial_info)
  1103. self.assertTrue(ydl.cookiejar.get_cookies_for_url(TEST_URL),
  1104. msg=f'No cookies set in cookiejar after initial process when {note}')
  1105. ydl.cookiejar.clear()
  1106. with open(TEST_FILE) as infojson:
  1107. result['loaded'] = ydl.sanitize_info(json.load(infojson), True)
  1108. result['final'] = ydl.process_ie_result(result['loaded'].copy(), download=False)
  1109. self.assertTrue(ydl.cookiejar.get_cookies_for_url(TEST_URL),
  1110. msg=f'No cookies set in cookiejar after final process when {note}')
  1111. ydl.cookiejar.clear()
  1112. for key in ('processed', 'loaded', 'final'):
  1113. info = result[key]
  1114. self.assertIsNone(
  1115. traverse_obj(info, ((None, ('formats', 0)), 'http_headers', 'Cookie'), casesense=False, get_all=False),
  1116. msg=f'Cookie header not removed in {key} result when {note}')
  1117. self.assertEqual(
  1118. traverse_obj(info, ((None, ('formats', 0)), 'cookies'), get_all=False), COOKIES,
  1119. msg=f'No cookies field found in {key} result when {note}')
  1120. test({'url': TEST_URL, 'http_headers': COOKIE_HEADER, 'id': '1', 'title': 'x'}, 'no formats field')
  1121. test(make_info(info_header_cookies=True), 'info_dict header cokies')
  1122. test(make_info(fmts_header_cookies=True), 'format header cookies')
  1123. test(make_info(info_header_cookies=True, fmts_header_cookies=True), 'info_dict and format header cookies')
  1124. test(make_info(info_header_cookies=True, fmts_header_cookies=True, cookies_field=True), 'all cookies fields')
  1125. test(make_info(cookies_field=True), 'cookies format field')
  1126. test({'url': TEST_URL, 'cookies': COOKIES, 'id': '1', 'title': 'x'}, 'info_dict cookies field only')
  1127. try_rm(TEST_FILE)
  1128. def test_add_headers_cookie(self):
  1129. def check_for_cookie_header(result):
  1130. return traverse_obj(result, ((None, ('formats', 0)), 'http_headers', 'Cookie'), casesense=False, get_all=False)
  1131. ydl = FakeYDL({'http_headers': {'Cookie': 'a=b'}})
  1132. ydl._apply_header_cookies(_make_result([])['webpage_url']) # Scope to input webpage URL: .example.com
  1133. fmt = {'url': 'https://example.com/video.mp4'}
  1134. result = ydl.process_ie_result(_make_result([fmt]), download=False)
  1135. self.assertIsNone(check_for_cookie_header(result), msg='http_headers cookies in result info_dict')
  1136. self.assertEqual(result.get('cookies'), 'a=b; Domain=.example.com', msg='No cookies were set in cookies field')
  1137. self.assertIn('a=b', ydl.cookiejar.get_cookie_header(fmt['url']), msg='No cookies were set in cookiejar')
  1138. fmt = {'url': 'https://wrong.com/video.mp4'}
  1139. result = ydl.process_ie_result(_make_result([fmt]), download=False)
  1140. self.assertIsNone(check_for_cookie_header(result), msg='http_headers cookies for wrong domain')
  1141. self.assertFalse(result.get('cookies'), msg='Cookies set in cookies field for wrong domain')
  1142. self.assertFalse(ydl.cookiejar.get_cookie_header(fmt['url']), msg='Cookies set in cookiejar for wrong domain')
  1143. if __name__ == '__main__':
  1144. unittest.main()