1
//! `format-date`: an RFC 3339 instant printed in the user's zone.
2

            
3
use chrono::{DateTime, Utc};
4
use scripting::runtime::{alloc_string_ref, read_string_arg};
5
use server::timezone::display;
6
use uuid::Uuid;
7
use wasmtime::{ArrayRef, Linker, Rooted};
8

            
9
use crate::forms::user_zone;
10
use crate::natives::args::required;
11
use crate::natives::forms::{args_error, native_failure};
12
use crate::natives::native::register_native;
13
use crate::session::SessionData;
14

            
15
pub const REGISTERED_COMMANDS: &[&str] = &["format-date"];
16

            
17
230199
pub fn register(linker: &mut Linker<SessionData>) -> wasmtime::Result<()> {
18
230199
    register_native(
19
230199
        linker,
20
230199
        "date_format_date",
21
4
        |caller, (instant_arg,): (Option<Rooted<ArrayRef>>,)| {
22
4
            Box::pin(async move {
23
4
                let user_id = caller.data().ctx().user_id;
24
4
                let instant = read_string_arg(caller, instant_arg)?;
25
4
                let printed = run_format_date(user_id, instant).await?;
26
2
                Ok(Some(alloc_string_ref(caller, printed.as_bytes())?))
27
4
            })
28
4
        },
29
    )
30
230199
}
31

            
32
4
async fn run_format_date(user_id: Uuid, instant_arg: Option<String>) -> wasmtime::Result<String> {
33
4
    let text = required("format-date", "instant", instant_arg)?;
34
4
    let at = DateTime::parse_from_rfc3339(&text)
35
2
        .map_err(|err| {
36
2
            args_error(format!(
37
2
                "format-date: '{text}' is not an RFC 3339 instant: {err}"
38
2
            ))
39
2
        })?
40
2
        .with_timezone(&Utc);
41
2
    let zone = user_zone(user_id).await.map_err(native_failure)?;
42
2
    Ok(display(at, zone))
43
4
}