grace/htmlua

HTML Templating Engine

git clone https://git.gae.moe/grace/htmlua

Quin GillespieMerge pull request #11 from gyoder/httpstdlib8b631dd

render_fixes
6.7 KiB228 linesraw
1use std::{
2    cell::{LazyCell, RefCell},
3    collections::HashMap,
4    fmt::Write,
5    rc::Rc,
6    str::FromStr,
7    time::Duration,
8};
9
10use mlua::{Error, Lua, Table, prelude::*};
11use reqwest::{
12    Method, Url,
13    blocking::{Client, Response},
14    header::HeaderMap,
15};
16use serde::{Deserialize, Serialize};
17
18
19pub fn create_htmlua_stdlib(l: &Lua, stdout: &Rc<RefCell<String>>) -> mlua::Result<Table> {
20    let t = l.create_table()?;
21
22    // This cannot be the best way to do this
23
24    let stdout_println = stdout.clone();
25    t.set(
26        "println",
27        l.create_function(move |_, text: String| {
28            let mut stdout_ref = stdout_println.borrow_mut();
29            writeln!(stdout_ref, "{text}").map_err(mlua::Error::external)
30        })?,
31    )?;
32
33    let stdout_print = stdout.clone();
34    t.set(
35        "print",
36        l.create_function(move |_, text: String| {
37            let mut stdout_ref = stdout_print.borrow_mut();
38            write!(stdout_ref, "{text}").map_err(mlua::Error::external)
39        })?,
40    )?;
41
42    t.set("http", create_http_lib(l)?)?;
43    Ok(t)
44}
45
46#[allow(clippy::too_many_lines)]
47fn create_http_lib(l: &Lua) -> mlua::Result<Table> {
48    let t = l.create_table()?;
49    let http_client: Rc<LazyCell<Client>> = Rc::new(LazyCell::new(|| {
50        Client::builder()
51            .timeout(std::time::Duration::from_secs(3))
52            .user_agent("htmlua/0.1.0")
53            .build()
54            .unwrap()
55    }));
56
57
58    let client = http_client.clone();
59    t.set(
60        "get",
61        l.create_function(move |_, url: String| {
62            let res = client.get(url).send().map_err(|e| Error::RuntimeError(e.to_string()))?;
63            let lua_res: LuaHttpResponse = TryFrom::try_from(res)?;
64            Ok(lua_res)
65        })?,
66    )?;
67
68    let client = http_client.clone();
69    t.set(
70        "post",
71        l.create_function(move |_, url: String| {
72            let res = client
73                .post(url)
74                .send()
75                .map_err(|e| Error::RuntimeError(e.to_string()))?;
76            let lua_res: LuaHttpResponse = TryFrom::try_from(res)?;
77            Ok(lua_res)
78        })?,
79    )?;
80
81    let client = http_client.clone();
82    t.set(
83        "get_with_data",
84        l.create_function(move |_, (url, data): (String, HashMap<String, String>)| {
85            let res = client
86                .get(url)
87                .query(&data)
88                .send()
89                .map_err(|e| Error::RuntimeError(e.to_string()))?;
90            let lua_res: LuaHttpResponse = TryFrom::try_from(res)?;
91            Ok(lua_res)
92        })?,
93    )?;
94
95    let client = http_client.clone();
96    t.set(
97        "post_with_data_form",
98        l.create_function(move |_, (url, data): (String, HashMap<String, String>)| {
99            let res = client
100                .post(url)
101                .form(&data)
102                .send()
103                .map_err(|e| Error::RuntimeError(e.to_string()))?;
104            let lua_res: LuaHttpResponse = TryFrom::try_from(res)?;
105            Ok(lua_res)
106        })?,
107    )?;
108
109    let client = http_client.clone();
110    t.set(
111        "post_with_data_json",
112        l.create_function(move |_, (url, data): (String, HashMap<String, String>)| {
113            let res = client
114                .post(url)
115                .json(&data)
116                .send()
117                .map_err(|e| Error::RuntimeError(e.to_string()))?;
118            let lua_res: LuaHttpResponse = TryFrom::try_from(res)?;
119            Ok(lua_res)
120        })?,
121    )?;
122
123    let client = http_client.clone();
124    t.set(
125        "request",
126        l.create_function(move |_, table: mlua::Table| {
127            let mut request = client.request(
128                Method::from_bytes(table.get::<String>("method")?.as_bytes())
129                    .map_err(|e| Error::RuntimeError(e.to_string()))?,
130                Url::from_str(table.get::<String>("url")?.as_str()).map_err(|e| Error::RuntimeError(e.to_string()))?,
131            );
132
133            if let Ok(header_tbl) = table.get::<mlua::Table>("headers") {
134                request = header_tbl
135                    .pairs::<String, String>()
136                    .filter_map(std::result::Result::ok)
137                    .fold(request, |req, (k, v)| req.header(k, v));
138            }
139
140            if let Ok(basic_auth) = table.get::<mlua::Table>("basic_auth") {
141                request = request
142                    .basic_auth(basic_auth.get::<String>("username")?, basic_auth.get::<String>("password").ok());
143            }
144
145            if let Ok(bearer_auth) = table.get::<mlua::Table>("bearer_auth") {
146                request = request.bearer_auth(bearer_auth.get::<String>("token")?);
147            }
148
149            if let Ok(body) = table.get::<String>("body") {
150                request = request.body(body);
151            }
152
153            if let Ok(json) = table.get::<String>("json") {
154                request = request.json(&json);
155            }
156
157            if let Ok(timeout) = table.get::<u64>("timeout") {
158                request = request.timeout(Duration::from_secs(timeout));
159            }
160
161
162            let res = request.send().map_err(|e| Error::RuntimeError(e.to_string()))?;
163            let lua_res: LuaHttpResponse = TryFrom::try_from(res)?;
164            Ok(lua_res)
165        })?,
166    )?;
167
168    t.set(
169        "decode_json",
170        l.create_function(move |l, text: String| {
171            let table: serde_json::Value =
172                serde_json::from_str(&text).map_err(|e| Error::RuntimeError(e.to_string()))?;
173            Ok(l.to_value(&table))
174        })?,
175    )?;
176
177    Ok(t)
178}
179
180
181#[derive(Serialize, Deserialize)]
182struct LuaHttpResponse {
183    headers: HashMap<String, String>,
184    body: String,
185    status: u16,
186}
187
188impl TryFrom<Response> for LuaHttpResponse {
189    fn try_from(value: Response) -> Result<Self, Self::Error> {
190        Ok(LuaHttpResponse {
191            headers: headermap_to_hashmap(value.headers()),
192            status: value.status().as_u16(),
193            body: value.text().map_err(|e| Error::RuntimeError(e.to_string()))?,
194        })
195    }
196
197    type Error = Error;
198}
199
200fn headermap_to_hashmap(headers: &HeaderMap) -> HashMap<String, String> {
201    let mut map = HashMap::new();
202
203    for (name, value) in headers {
204        if let Ok(value_str) = value.to_str() {
205            map.insert(name.as_str().to_string(), value_str.to_string());
206        }
207    }
208
209    map
210}
211
212
213impl IntoLua for LuaHttpResponse {
214    fn into_lua(self, lua: &Lua) -> LuaResult<LuaValue> {
215        let table = lua.create_table()?;
216
217        table.set("status", self.status)?;
218        table.set("body", self.body)?;
219
220        let headers_table = lua.create_table()?;
221        for (key, value) in self.headers {
222            headers_table.set(key, value)?;
223        }
224        table.set("headers", headers_table)?;
225
226        Ok(LuaValue::Table(table))
227    }
228}