summaryrefslogtreecommitdiff
path: root/iptv-menu-dl.lua
blob: a207c91ee4e9b99a3ef654beb2fb56c12857d8cd (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
-- Copyright 2025 David Vazgenovich Shakaryan

local utils = require('mp.utils')

local queue = {}

function download(target, name, url, path)
	if utils.file_info(path) then
		return
	end

	local cmd = 'curl -sSfLo \'' .. path .. '\'' .. ' \'' .. url .. '\''
	print('exec: ' .. cmd)
	local ret = os.execute(cmd)

	if ret == 0 then
		mp.commandv('script-message-to', target, name, url, path)
	end
end

function process_next()
	download(unpack(table.remove(queue)))

	if #queue > 0 then
		mp.add_timeout(0, process_next)
	end
end

mp.register_script_message('download-file', function(...)
	queue[#queue+1] = {...}

	-- we want the ability for a later request to be downloaded before
	-- earlier ones, e.g., to prioritise the image for the current menu.
	--
	-- using a small timeout between receiving a message and processing it
	-- allows for multiple pending messages to be received before any are
	-- processed. however, immediately scheduling a timer for each request
	-- does not work, as all elapsed timeouts are executed before any new
	-- messages are received.
	--
	-- the workaround is to schedule a timeout only when adding to an empty
	-- queue and have each callback schedule an additional timeout if the
	-- queue is not empty after completion. this effectively results in new
	-- messages being received after each download.
	if #queue == 1 then
		mp.add_timeout(0, process_next)
	end
end)