aboutsummaryrefslogtreecommitdiff
path: root/lib/curl.lua
blob: 4c56325a553ef890c6cbf1f34d431bc5776da951 (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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#!/usr/bin/env lua

local util = require("lib.util")

local def_headr = {
	["User-Agent"] = "cia",
	["Accept-Encoding"] = "gzip, deflate, br",
}

local head_to_args = function(t)
	local args = {}

	for k, v in pairs(t) do
		args[#args + 1] = "-H" .. k .. ": " .. v
	end

	return args
end

local get = function(url, headr, args)
	local fetch, hcode, def_args

	def_args = {
		"curl",
		"--silent",
		"--compressed",
		"--write-out",
		"%{http_code}",
		"--globoff",
		"--location",
		url,
	}

	args = util.array_merge(def_args, args)
	headr = util.table_merge(def_headr, headr)
	args = util.array_merge(args, head_to_args(headr))

	fetch = util.run(args)
	hcode = fetch:match("%d*$")
	fetch = fetch:gsub("%s*%d*$", "")

	return fetch, tonumber(hcode)
end

local zip_link_to_file = function(url, headr, out)
	local hcode, zip, rc, args

	zip = os.tmpname()
	args = { "-o" .. zip }

	_, hcode = get(url, headr, args)

	rc = (hcode == 200)
	if rc then
		rc = util.zip_ext_first(zip, out)
	end
	os.remove(zip)

	if hcode and not rc then
		util.error("curl: zip_link_to_file")
	end

	return rc
end

return {
	get = get,
	zip_link_to_file = zip_link_to_file,
}