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