-- Copyright 2025 David Vazgenovich Shakaryan local mp_utils = require('mp.utils') local downloader = {} local mt = {} mt.__index = mt function downloader.new() return setmetatable({ pending = {}, running = false, }, mt) end function mt:exec(url, file, cb) if mp_utils.file_info(file) then self:exec_next() return end local tmp = file .. '.tmp' local cmd = {'curl', '-sSfLo', tmp, url} print('downloading ' .. url) self.running = true mp.command_native_async({ name = 'subprocess', args = cmd, playback_only = false, }, function(success, res) self.running = false self:exec_next() if success and res.status == 0 then os.rename(tmp, file) if cb then cb(url, file) end else os.remove(tmp) end end) end function mt:exec_next() if #self.pending > 0 then self:exec(unpack(table.remove(self.pending))) end end -- more recently requested downloads are executed first, as they are more -- likely to be used for the current display state function mt:schedule(...) if self.running then self.pending[#self.pending+1] = {...} else self:exec(...) end end return downloader