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
//! This library implements limited functionality for the OSA System on macOS.
//! In particular it allows you to execute JavaScript via the OSA system to
//! script applications.  It's particularly useful if you need to tell other
//! applications to execute certain functionality.
//!
//! Currently only JavaScript is supported.  Parameters passed to it show up
//! as `$params` and the return value from the script (as returned with the
//! `return` keyword) is deserialized later.
//!
//! # Example
//!
//! ```
//! extern crate osascript;
//! #[macro_use] extern crate serde_derive;
//! 
//! #[derive(Serialize)]
//! struct AlertParams {
//!     title: String,
//!     message: String,
//!     alert_type: String,
//!     buttons: Vec<String>,
//! }
//! 
//! #[derive(Deserialize)]
//! struct AlertResult {
//!     #[serde(rename="buttonReturned")]
//!     button: String,
//! }
//! 
//! fn main() {
//!     let script = osascript::JavaScript::new("
//!         var App = Application('Finder');
//!         App.includeStandardAdditions = true;
//!         return App.displayAlert($params.title, {
//!             message: $params.message,
//!             'as': $params.alert_type,
//!             buttons: $params.buttons,
//!         });
//!     ");
//! 
//!     let rv: AlertResult = script.execute_with_params(AlertParams {
//!         title: "Shit is on fire!".into(),
//!         message: "What is happening".into(),
//!         alert_type: "critical".into(),
//!         buttons: vec![
//!             "Show details".into(),
//!             "Ignore".into(),
//!         ]
//!     }).unwrap();
//! 
//!     println!("You clicked '{}'", rv.button);
//! }
//! ```
use std::process;
use std::io;
use std::fmt;
use std::string::FromUtf8Error;
use std::io::Write;
use std::error;

extern crate serde;
extern crate serde_json;
#[macro_use] extern crate serde_derive;

use serde::Serialize;
use serde::de::DeserializeOwned;

/// The error from the script system
#[derive(Debug)]
pub enum Error {
    Io(io::Error),
    Json(serde_json::Error),
    Script(String),
}

/// Holds an apple flavoured JavaScript
pub struct JavaScript {
    code: String,
}

impl From<io::Error> for Error {
    fn from(err: io::Error) -> Error {
        Error::Io(err)
    }
}

impl From<serde_json::Error> for Error {
    fn from(err: serde_json::Error) -> Error {
        Error::Json(err)
    }
}

impl From<FromUtf8Error> for Error {
    fn from(err: FromUtf8Error) -> Error {
        Error::Script(format!("UTF-8 Error: {}", err))
    }
}

impl error::Error for Error {
    fn description(&self) -> &str {
        match *self {
            Error::Io(ref err) => err.description(),
            Error::Json(ref err) => err.description(),
            Error::Script(..) => "script error",
        }
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            Error::Io(ref err) => write!(f, "script io error: {}", err),
            Error::Json(ref err) => write!(f, "script json error: {}", err),
            Error::Script(ref msg) => write!(f, "script error: {}", msg),
        }
    }
}

#[derive(Serialize)]
struct EmptyParams {}

fn wrap_code<S: Serialize>(code: &str, params: S) -> Result<String, Error> {
    let mut buf: Vec<u8> = vec![];
    write!(&mut buf, "var $params = ")?;
    serde_json::to_writer(&mut buf, &params)?;
    write!(&mut buf, ";JSON.stringify((function() {{{};return null;}})());", code)?;
    Ok(String::from_utf8(buf)?)
}

impl JavaScript {
    /// Creates a new script from the given code.
    pub fn new(code: &str) -> JavaScript {
        JavaScript {
            code: code.to_string(),
        }
    }

    /// Executes the script and does not pass any arguments.
    pub fn execute<'a, D: DeserializeOwned>(&self) -> Result<D, Error> {
        self.execute_with_params(EmptyParams {})
    }

    /// Executes the script and passes the provided arguments.
    pub fn execute_with_params<'a, S: Serialize, D: DeserializeOwned>(&self, params: S)
        -> Result<D, Error>
    {
        let wrapped_code = wrap_code(&self.code, params)?;
        let output = process::Command::new("osascript")
            .arg("-l")
            .arg("JavaScript")
            .arg("-e")
            .arg(&wrapped_code)
            .output()?;
        if output.status.success() {
            Ok(serde_json::from_slice(&output.stdout)?)
        } else {
            Err(Error::Script(String::from_utf8(output.stderr)?))
        }
    }
}