summaryrefslogtreecommitdiff
path: root/downloader.lua
blob: 67fb67535755eb490f4a9fffb6add2d09c9e529e (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
-- Copyright 2025 David Vazgenovich Shakaryan

local 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 utils.file_info(file) then
		self:exec_next()
		return
	end

	local cmd = {'curl', '-sSfLo', file, url}
	print('exec: ' .. utils.to_string(cmd))

	self.running = true
	mp.command_native_async({
		name = 'subprocess',
		args = cmd,
		playback_only = false,
	}, function(success, res)
		self.running = false
		self:exec_next()
		if cb and success and res.status == 0 then
			cb(url, file)
		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