pebbles 0.0.1

A unfinished webautomation framework for working with Firefox and the geckodriver.
Documentation
use crate::{
    result::PebblesError,
    Service,
};
use rand::Rng;
use serde_json::json;
use std::rc::Rc;

pub struct Keyboard {
    service: Rc<Service>,
}

impl Keyboard {
    pub fn new(service: Rc<Service>) -> Self {
        Keyboard {
            service,
        }
    }

    pub fn down(&self, key:&str) -> Result<(), PebblesError> {
        let actions = json!({"actions":[
            {
                "type": "key",
                "id": "key",
                "actions": [{
                    "type": "keyDown",
                    "value": key
                }]
            }
        ]});
        self.service.post("/actions", &actions)?;
        Ok(())
    }

    pub fn up(&self, key:&str) -> Result<(), PebblesError> {
        let actions = json!({"actions":[
            {
                "type": "key",
                "id": "key",
                "actions": [{
                    "type": "keyUp",
                    "value": key
                }]
            }
        ]});
        self.service.post("/actions", &actions)?;
        Ok(())
    }

    pub fn type_keys(&self, keys:&str) -> Result<(), PebblesError> {
        let mut rng = rand::thread_rng();
        let max_pause: i32 = 120;
        let min_pause: i32 = 50;
        let mut pause_duration: i32 = rng.gen_range(min_pause..max_pause);
        let mut actions = json!({"actions":[
            {
                "type": "key",
                "id": "key",
                "actions": []
            }
        ]});
        for key in keys.chars() {
            if rng.gen_range(1..3) == 1 {
                pause_duration = rng.gen_range(min_pause..max_pause);
            }
            let new_action = vec![
                json!({
                    "type": "keyDown",
                    "value": key
                }),
                json!({
                    "type": "pause",
                    "duration": pause_duration
                }),
                json!({
                    "type": "keyUp",
                    "value": key
                }),
                json!({
                    "type": "pause",
                    "duration": if key != ' ' {pause_duration} else {(pause_duration as f32 * rng.gen_range(1.0..3.0)) as i32}
                })
            ];
            if let Some(actions_array) = actions["actions"][0]["actions"].as_array_mut() {
                actions_array.extend(new_action);
            }
        }
        self.service.post("/actions", &actions)?;
        Ok(())
    }
}