aboutsummaryrefslogtreecommitdiffstats
path: root/src/plugins/factoid/utils.rs
blob: f9ab8c257e12d09efb7c839baba44fb5331b34de (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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
use std::thread;
use std::time::Duration;

use serde_json::{self, Value as SerdeValue};

use super::rlua::Error as LuaError;
use super::rlua::Error::RuntimeError;
use super::rlua::{Context, Value as LuaValue};

use crate::utils::error::ErrorKind::Connection;
use crate::utils::Url;

use failure::Fail;

pub fn sleep(_: &Context, dur: u64) -> Result<(), LuaError> {
    thread::sleep(Duration::from_millis(dur));
    Ok(())
}

pub fn download(_: &Context, url: String) -> Result<String, LuaError> {
    let url = Url::from(url).max_kib(1024);
    match url.request() {
        Ok(v) => Ok(v),
        Err(e) => {
            let error = match e.kind() {
                Connection => e.cause().unwrap().to_string(),
                _ => e.to_string(),
            };

            Err(RuntimeError(format!(
                "Failed to download {} - {}",
                url.as_str(),
                error
            )))
        }
    }
}

fn convert_value<'l>(
    lua: &Context<'l>,
    sval: SerdeValue,
    max_recurs: usize,
) -> Result<LuaValue<'l>, LuaError> {
    if max_recurs == 0 {
        return Err(RuntimeError(String::from(
            "Reached max recursion level - json is nested too deep",
        )));
    }

    let lval = match sval {
        SerdeValue::Null => LuaValue::Nil,
        SerdeValue::Bool(b) => LuaValue::Boolean(b),
        SerdeValue::String(s) => LuaValue::String(lua.create_string(&s)?),
        SerdeValue::Number(n) => {
            let f = n.as_f64().ok_or_else(|| {
                RuntimeError(String::from("Failed to convert number into double"))
            })?;
            LuaValue::Number(f)
        }
        SerdeValue::Array(arr) => {
            let table = lua.create_table()?;
            for (i, val) in arr.into_iter().enumerate() {
                table.set(i + 1, convert_value(lua, val, max_recurs - 1)?)?;
            }

            LuaValue::Table(table)
        }
        SerdeValue::Object(obj) => {
            let table = lua.create_table()?;
            for (key, val) in obj {
                table.set(key, convert_value(lua, val, max_recurs - 1)?)?;
            }

            LuaValue::Table(table)
        }
    };

    Ok(lval)
}

pub fn json_decode<'l>(lua: &Context<'l>, json: String) -> Result<LuaValue<'l>, LuaError> {
    let ser_val: SerdeValue =
        serde_json::from_str(&json).map_err(|e| RuntimeError(e.to_string()))?;

    convert_value(lua, ser_val, 25)
}