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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
//! Front-end library to be called from Javascript.
//! Targets WASM.
//!
//! In true Javascript tradition, this part of the library does not support error handling.
//!
#![warn(missing_docs)]

mod connection;
mod convert;
mod imports;

use js_sys::Array;
use wasm_bindgen::prelude::*;

use usdpl_core::{socket::Packet, RemoteCall};
//const REMOTE_CALL_ID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
//const REMOTE_PORT: std::sync::atomic::AtomicU16 = std::sync::atomic::AtomicU16::new(31337);

static mut CTX: UsdplContext = UsdplContext {
    port: 31337,
    id: 1,
    #[cfg(feature = "encrypt")]
    key: Vec::new(),
};

static mut CACHE: Option<std::collections::HashMap<String, JsValue>> = None;

#[cfg(feature = "translate")]
static mut TRANSLATIONS: Option<std::collections::HashMap<String, Vec<String>>> = None;

#[cfg(feature = "encrypt")]
fn encryption_key() -> Vec<u8> {
    hex::decode(obfstr::obfstr!(env!("USDPL_ENCRYPTION_KEY"))).unwrap()
}

//#[wasm_bindgen]
#[derive(Debug)]
struct UsdplContext {
    port: u16,
    id: u64,
    #[cfg(feature = "encrypt")]
    key: Vec<u8>,
}

fn get_port() -> u16 {
    unsafe { CTX.port }
}

#[cfg(feature = "encrypt")]
fn get_key() -> Vec<u8> {
    unsafe { CTX.key.clone() }
}

fn increment_id() -> u64 {
    let current_id = unsafe { CTX.id };
    unsafe {
        CTX.id += 1;
    }
    current_id
}

/// Initialize the front-end library
#[wasm_bindgen]
pub fn init_usdpl(port: u16) {
    #[cfg(feature = "console_error_panic_hook")]
    console_error_panic_hook::set_once();
    //REMOTE_PORT.store(port, std::sync::atomic::Ordering::SeqCst);
    unsafe {
        CTX = UsdplContext {
            port: port,
            id: 1,
            #[cfg(feature = "encrypt")]
            key: encryption_key(),
        };
    }

    unsafe {
        CACHE = Some(std::collections::HashMap::new());
    }
}

/// Get the targeted plugin framework, or "any" if unknown
#[wasm_bindgen]
pub fn target_usdpl() -> String {
    usdpl_core::api::Platform::current().to_string()
}

/// Get the UDSPL front-end version
#[wasm_bindgen]
pub fn version_usdpl() -> String {
    env!("CARGO_PKG_VERSION").into()
}

/// Get the targeted plugin framework, or "any" if unknown
#[wasm_bindgen]
pub fn set_value(key: String, value: JsValue) -> JsValue {
    unsafe {
        CACHE.as_mut().unwrap().insert(key, value).unwrap_or(JsValue::NULL)
    }
}

/// Get the targeted plugin framework, or "any" if unknown
#[wasm_bindgen]
pub fn get_value(key: String) -> JsValue {
    unsafe {
        CACHE.as_ref().unwrap().get(&key).map(|x| x.to_owned()).unwrap_or(JsValue::UNDEFINED)
    }
}

/// Call a function on the back-end.
/// Returns null (None) if this fails for any reason.
#[wasm_bindgen]
pub async fn call_backend(name: String, parameters: Vec<JsValue>) -> JsValue {
    #[cfg(feature = "debug")]
    imports::console_log(&format!(
        "call_backend({}, [params; {}])",
        name,
        parameters.len()
    ));
    let next_id = increment_id();
    let mut params = Vec::with_capacity(parameters.len());
    for val in parameters {
        params.push(convert::js_to_primitive(val));
    }
    let port = get_port();
    #[cfg(feature = "debug")]
    imports::console_log(&format!("USDPL: Got port {}", port));
    let results = connection::send_call(
        next_id,
        Packet::Call(RemoteCall {
            id: next_id,
            function: name.clone(),
            parameters: params,
        }),
        port,
        #[cfg(feature = "encrypt")]
        get_key()
    )
    .await;
    let results = match results {
        Ok(x) => x,
        #[allow(unused_variables)]
        Err(e) => {
            #[cfg(feature = "debug")]
            imports::console_error(&format!("USDPL: Got error while calling {}: {:?}", name, e));
            return JsValue::NULL;
        }
    };
    let results_js = Array::new_with_length(results.len() as _);
    let mut i = 0;
    for item in results {
        results_js.set(i as _, convert::primitive_to_js(item));
        i += 1;
    }
    results_js.into()
}

/// Initialize translation strings for the front-end
#[wasm_bindgen]
pub async fn init_tr(locale: String) {
    let next_id = increment_id();
    match connection::send_recv_packet(
        next_id,
        Packet::Language(locale.clone()),
        get_port(),
        #[cfg(feature = "encrypt")]
        get_key()
    ).await {
        Ok(Packet::Translations(translations)) => {
            #[cfg(feature = "debug")]
            imports::console_log(&format!("USDPL: Got translations for {}", locale));
            // convert translations into map
            let mut tr_map = std::collections::HashMap::with_capacity(translations.len());
            for (key, val) in translations {
                tr_map.insert(key, val);
            }
            unsafe { TRANSLATIONS = Some(tr_map) }
        },
        Ok(_) => {
            #[cfg(feature = "debug")]
            imports::console_error(&format!("USDPL: Got wrong packet response for init_tr"));
            unsafe { TRANSLATIONS = None }
        },
        #[allow(unused_variables)]
        Err(e) => {
            #[cfg(feature = "debug")]
            imports::console_error(&format!("USDPL: Got wrong error for init_tr: {}", e));
            unsafe { TRANSLATIONS = None }
        }
    }
}

/// Translate a phrase, equivalent to tr_n(msg_id, 0)
#[wasm_bindgen]
pub fn tr(msg_id: String) -> String {
    if let Some(translations) = unsafe { TRANSLATIONS.as_ref().unwrap().get(&msg_id) } {
        if let Some(translated) = translations.get(0) {
            translated.to_owned()
        } else {
            msg_id
        }
    } else {
        msg_id
    }
}

/// Translate a phrase, retrieving the plural form for `n` items
#[wasm_bindgen]
pub fn tr_n(msg_id: String, n: usize) -> String {
    if let Some(translations) = unsafe { TRANSLATIONS.as_ref().unwrap().get(&msg_id) } {
        if let Some(translated) = translations.get(n) {
            translated.to_owned()
        } else {
            msg_id
        }
    } else {
        msg_id
    }
}