matroskin 0.1.0

whatsminer api client lib
Documentation
//! Implement `set.system.timezone` command
//!
//! Sets the system's time zone. This configuration does not take effect
//! until the network is restarted.
//!
//! - Command: [SetSystemTimezone]
//! - ApiDoc: <https://apidoc.whatsminer.com/#api-System-btminer_set_system_timezone>
use core::str;

use serde::Serialize;

use crate::{
    command::{Command, CommandLevel},
    error::Result,
};

/// This command represents the `set.system.timezone` operation.
///
/// Sets the system's time zone. This configuration does not take effect
/// until the network is restarted.
///
/// - ApiDoc: <https://apidoc.whatsminer.com/#api-System-btminer_set_system_timezone>
///
/// # Example
/// ```rust,no_run
/// use matroskin::actor::Actor;
/// use matroskin::account::Account;
/// use matroskin::password::Password;
/// use matroskin::command::set_system_timezone::SetSystemTimezone;
///
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
///     let addr = "10.10.10.10:4433";
///     let username = Account::Super;
///     let password = Password::Super;
///
///     let actor = Actor::new(addr, username, password);
///     actor.connect()?;
///
///     let cmd = SetSystemTimezone::new("CST-8", "Asia/Shanghai");
///     let response = actor.send(cmd).await?;
///     println!("Response: {:#?}", response);
///
///     Ok(())
/// }
/// ```
#[derive(Debug, Serialize, Clone, PartialEq, Eq)]
pub struct SetSystemTimezone {
    /// Time zone string (e.g., `"CST-8"`).
    pub timezone: String,
    /// Time zone name (e.g., `"Asia/Shanghai"`).
    pub zonename: String,
}

impl SetSystemTimezone {
    /// Create a new `set.system.timezone` command.
    pub fn new(timezone: impl Into<String>, zonename: impl Into<String>) -> Self {
        Self {
            timezone: timezone.into(),
            zonename: zonename.into(),
        }
    }
}

impl Command for SetSystemTimezone {
    type Response = String;
    const CMD_NAME: &'static str = "set.system.timezone";
    const LEVEL: CommandLevel = CommandLevel::Secured;

    fn params(&self) -> Result<Option<impl serde::Serialize>> {
        Ok(Some(self))
    }
}

#[cfg(test)]
mod tests {
    use crate::account::Account;
    use crate::auth_data::AuthData;

    use super::*;

    const RESPONSE_JSON: &str =
        r#"{"code":0,"when":1692685512,"msg":"ok","desc":"set.system.timezone"}"#;

    #[test]
    fn request_has_correct_structure() {
        let cmd = SetSystemTimezone::new("CST-8", "Asia/Shanghai");
        assert!(cmd.is_secured());
        assert!(!cmd.is_encrypted());

        let auth = AuthData::new::<SetSystemTimezone>(Account::Super, "pass", "salt").unwrap();
        let encoded = cmd.encode(Some(auth)).unwrap();
        let json: serde_json::Value = serde_json::from_slice(&encoded.0).unwrap();

        assert_eq!(json["cmd"], "set.system.timezone");
        assert_eq!(json["account"], "super");
        assert!(json["ts"].as_u64().unwrap() > 0);
        assert_eq!(json["token"].as_str().unwrap().len(), 8);
        assert_eq!(json["param"]["timezone"], "CST-8");
        assert_eq!(json["param"]["zonename"], "Asia/Shanghai");
    }

    #[test]
    fn request_without_auth_omits_token() {
        let cmd = SetSystemTimezone::new("CST-8", "Asia/Shanghai");
        let encoded = cmd.encode(None).unwrap();
        let json: serde_json::Value = serde_json::from_slice(&encoded.0).unwrap();
        assert!(json.get("token").is_none());
        assert_eq!(json["param"]["timezone"], "CST-8");
        assert_eq!(json["param"]["zonename"], "Asia/Shanghai");
    }

    #[test]
    fn deserialize_response_fixture() {
        let response = SetSystemTimezone::parse_response(RESPONSE_JSON.as_bytes()).unwrap();
        assert!(response.code.is_success());
        assert_eq!(response.desc, "set.system.timezone");
        assert_eq!(response.when, 1692685512);
        assert_eq!(response.msg, "ok");
    }
}