Debian Codegraph @

texmf-dist/tex/lualatex/luahttp/luahttp-fetch.lua

raw
1 --[[
2 -- This module is part of the LuaHTTP package
3 -- The purpose of this module is to make HTTP requests and return the response.
4 --
5 -- Dependencies:
6 -- dkjson
7 -- luasec
8 -- ltn12
9 -- feedparser
10 ]]
11
12 local moduleName = fetch
13 local M = {}
14
15 ---------- Dependencies ------------------------
16 local http = require("socket.http")
17 local urlsocket = require("socket.url")
18 local https = require("ssl.https")
19 local dkjson = require("dkjson")
20 local ltn12 = require("ltn12")
21 local feedparser = require("feedparser")
22
23 ---------- Local variables ---------------------
24
25 ---------- Helper functions --------------------
26
27 --- Makes an HTTP request using the provided request parameter.
28 -- @param request table containing the request parameters
29 -- @return the response as a table
30 local function http_request(request)
31 local url = request.url
32 print("\nConnecting to " .. url)
33
34 -- Detect HTTPS
35 local client = http
36 if url:lower():find("^https://") then
37 client = https
38 end
39
40 -- Save optional body
41 local body = request.body
42
43 -- Prepare request
44 local response = {}
45 local request = {
46 method = request.method or "GET",
47 url = url,
48 headers = request.headers or nil,
49 redirect = request.redirect or false,
50 sink = ltn12.sink.table(response)
51 }
52
53 -- Send optional body
54 if body then
55 if type(body) == "table" then
56 body = dkjson.encode(body)
57 end
58 request.source = ltn12.source.string(body)
59 request.headers["Content-Length"] = #body
60 end
61
62 -- Make the request
63 local response_status, response_code, response_header, response_message = client.request(request)
64
65 local message = response_message or "(No response message recieved)"
66
67 if response_status == nil then
68 error("\n!!! Error connecting to " .. url .. "\nResponse: " .. response_code .. "\nMessage: " .. message)
69 end
70
71 -- Check for redirects and return body
72 if response_code == 301 or response_code == 302 or response_code == 303 then
73 print("\nResponse " .. message)
74 local redirect_url = response_header["location"]
75 if redirect_url == url then
76 error("\n!!! Error connecting to " .. url .. " results in a redirection loop")
77 else
78 print("\n!! Warning: redirecting to " .. redirect_url)
79 request.url = redirect_url
80 return http_request(request)
81 end
82 elseif response_code == 200 then
83 print("\nResponse " .. message)
84 if response == null or not next(response) then
85 error("\n!!! Error empty response")
86 end
87 return response
88 else
89 error("\n!!! Error connecting to " .. url .. "\nResponse: " .. response_code .. "\nMessage: " .. message)
90 end
91 end
92
93 --- Parse the given JSON-file.
94 -- @param file_path path to JSON-file
95 -- @return table containing the JSON data
96 local function parse_json_file(file_path)
97 local file = io.open(file_path, "r")
98 local content = file:read("*all")
99 file:close()
100 return dkjson.decode(content)
101 end
102
103 --- Split a given string on the first occurence of a given character.
104 -- @param str string containing the given character
105 -- @param char target character at which the string gets split
106 -- @return table containing the first part of the string as the key and the second part as the value
107 local function split_first(str, char)
108 local result = {}
109 local pos = str:find(char)
110 local key = str:sub(1, pos - 1)
111 local value = str:sub(pos + 1)
112 result[key] = value
113 return result
114 end
115
116 ---------- Module functions --------------------
117
118 --- Make a GET request using the provided URL
119 -- @param url target URL
120 -- @return table containg the response
121 function M.json(url)
122 local request = {
123 method = "GET",
124 url = url,
125 headers = {
126 ["Accept"] = "application/json"
127 },
128 }
129 local response = http_request(request)
130 return dkjson.decode(table.concat(response))
131 end
132
133 --- Make a request using the provided JSON-file
134 -- @param json_file_path path to JSON-file
135 -- @return table containg the response
136 function M.json_using_file(json_file_path)
137 print("\nUsing file " .. json_file_path)
138 local request = parse_json_file(json_file_path)
139 local response = http_request(request)
140 return dkjson.decode(table.concat(response))
141 end
142
143 --- Make a GET request using the provided URL
144 -- @param url target URL
145 -- @return table containg the response
146 function M.rss(url)
147 local request = {
148 method = "GET",
149 url = url,
150 headers = {
151 ["Accept"] = "application/rss+xml"
152 },
153 }
154 local response = http_request(request)
155 return feedparser.parse(table.concat(response))
156 end
157
158 --- Fetch image data using the provided URL
159 -- @param url target URL leading to an image
160 -- @return image data
161 function M.image(url)
162 local request = {
163 method = "GET",
164 url = url
165 }
166 local response = http_request(request)
167 return table.concat(response)
168 end
169
170 --- Make a POST request using the provided URL and query parameters
171 -- @param url target URL
172 -- @param query_parameters parameters sent in the URL
173 -- @return table containg the response
174 function M.json_using_query(url, query_parameters)
175 local url = url
176 for _, value in ipairs(query_parameters) do
177 local params = split_first(value, "=")
178 for k, v in pairs(params) do
179 v = string.gsub(v, "\n", "")
180 url = url .. k .. "=" .. urlsocket.escape(v)
181 end
182 end
183
184 print("\nURL: " .. url)
185
186 local request = {
187 method = "POST",
188 url = url,
189 headers = {
190 ["Accept"] = "application/json",
191 ["Content-Type"] = "application/x-www-form-urlencoded";
192 },
193 redirect = false
194 }
195 local response = http_request(request)
196 return dkjson.decode(table.concat(response))
197 end
198
199 return M