-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.lua
More file actions
79 lines (72 loc) · 2.46 KB
/
Copy pathclient.lua
File metadata and controls
79 lines (72 loc) · 2.46 KB
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
70
71
72
73
74
75
76
77
78
79
local proxyclient = {}
proxyclient.BASE_URL = "http://localhost:3000"
function proxyclient.get(path)
local requestUrl = proxyclient.BASE_URL .. path
local okCheck, checkErr = http.checkURL(requestUrl)
if okCheck == false then
return nil, "URL blocked by http rules: " .. tostring(checkErr), requestUrl
end
local response, err, failingResponse = http.get(requestUrl)
if not response then
local status, body = nil, nil
if failingResponse then
status = failingResponse.getResponseCode()
body = failingResponse.readAll()
failingResponse.close()
end
local detail = string.format(
"GET %s -> %s%s",
requestUrl,
tostring(err),
body and (" | body: " .. body) or ""
)
return nil, detail, requestUrl, status
end
local body = response.readAll()
local headers = response.getResponseHeaders()
local status = response.getResponseCode()
response.close()
if not body or body == "" then
return nil, "Empty response from proxy (status " .. tostring(status) .. ")", requestUrl
end
return body, nil, requestUrl, status, headers
end
local function buildConvertUrl(imageUrl, width, height, format)
local encoded = textutils.urlEncode(imageUrl)
return string.format(
"/convert?url=%s&width=%d&height=%d&format=%s",
encoded, width, height, format
)
end
function proxyclient.fetch(imageUrl, width, height, format)
format = format or "nfp"
return proxyclient.get(buildConvertUrl(imageUrl, width, height, format))
end
function proxyclient.fetchAndDecode(imageUrl, width, height, format)
local body, err, _, _, headers = proxyclient.fetch(imageUrl, width, height, format)
if not body then
return nil, err
end
if format == "blit" then
local rows, jsonErr = textutils.unserialiseJSON(body)
if not rows then
return nil, "Failed to parse blit JSON: " .. tostring(jsonErr)
end
return { kind = "blit", rows = rows, headers = headers }
else
local ok, image = pcall(paintutils.parseImage, body)
if not ok or not image then
return nil, "Failed to parse NFP image"
end
return { kind = "nfp", image = image, headers = headers }
end
end
function proxyclient.aghpbRandom(category, width, height, format)
format = format or "nfp"
local path = string.format("/aghpb/random?width=%d&height=%d&format=%s", width, height, format)
if category then
path = path .. "&category=" .. textutils.urlEncode(category)
end
return proxyclient.get(path)
end
return proxyclient