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
//! A very thin wrapper around NSNotifications
#![deny(
    missing_docs, trivial_casts, trivial_numeric_casts, unused_import_braces, unused_qualifications
)]
#![cfg(target_os = "macos")]
#![allow(improper_ctypes)]

extern crate chrono;
extern crate objc_foundation;
#[macro_use]
extern crate failure;
pub mod error;

use chrono::offset::*;
use error::*;
use objc_foundation::{INSString, NSString};
use std::env;
use std::ops::Deref;
use std::path::PathBuf;

static mut APPLICATION_SET: bool = false;

mod sys {
    use objc_foundation::NSString;
    #[link(name = "notify")]
    extern "C" {
        pub fn scheduleNotification(
            title: *const NSString,
            subtitle: *const NSString,
            message: *const NSString,
            sound: *const NSString,
            deliveryDate: f64,
        ) -> bool;
        pub fn sendNotification(
            title: *const NSString,
            subtitle: *const NSString,
            message: *const NSString,
            sound: *const NSString,
        ) -> bool;
        pub fn setApplication(newbundleIdentifier: *const NSString) -> bool;
        pub fn getBundleIdentifier(appName: *const NSString) -> *const NSString;
    }
}

/// Schedules a new notification in the NotificationCenter
///
/// Returns a `NotificationError` if a notification could not be scheduled
/// or is scheduled in the past
///
/// # Example:
///
/// ```ignore
/// extern crate chrono;
/// # use mac_notification_sys::*;
/// use chrono::offset::*;
///
/// // schedule a notification in 5 seconds
/// let _ = schedule_notification("Title", &None, "This is the body", &Some("Ping"),
///                               Utc::now().timestamp() as f64 + 5.).unwrap();
/// ```
pub fn schedule_notification(
    title: &str,
    subtitle: &Option<&str>,
    message: &str,
    sound: &Option<&str>,
    delivery_date: f64,
) -> NotificationResult<()> {
    ensure!(
        delivery_date >= Utc::now().timestamp() as f64,
        NotificationError::ScheduleInThePast
    );

    let use_sound = match sound {
        Some(sound) if check_sound(sound) => sound,
        _ => "_mute",
    };
    unsafe {
        ensure!(
            sys::scheduleNotification(
                NSString::from_str(title).deref(),
                NSString::from_str(subtitle.unwrap_or("")).deref(),
                NSString::from_str(message).deref(),
                NSString::from_str(use_sound).deref(),
                delivery_date,
            ),
            NotificationError::UnableToSchedule
        );
        Ok(())
    }
}

/// Delivers a new notification
///
/// Returns a `NotificationError` if a notification could not be delivered
///
/// # Example:
///
/// ```no_run
/// # use mac_notification_sys::*;
/// // daliver a silent notification
/// let _ = send_notification("Title", &None, "This is the body", &None).unwrap();
/// ```
pub fn send_notification(
    title: &str,
    subtitle: &Option<&str>,
    message: &str,
    sound: &Option<&str>,
) -> NotificationResult<()> {
    let use_sound = match sound {
        Some(sound) if check_sound(sound) => sound,
        _ => "_mute",
    };

    unsafe {
        ensure!(
            sys::sendNotification(
                NSString::from_str(title).deref(),
                NSString::from_str(subtitle.unwrap_or("")).deref(),
                NSString::from_str(message).deref(),
                NSString::from_str(use_sound).deref()
            ),
            NotificationError::UnableToDeliver
        );
        Ok(())
    }
}

/// Search for a possible BundleIdentifier of a given appname.
/// Defaults to "com.apple.Terminal" if no BundleIdentifier is found.
pub fn get_bundle_identifier_or_default(app_name: &str) -> String {
    get_bundle_identifier(app_name).unwrap_or("com.apple.Terminal".to_string())
}

/// Search for a BundleIdentifier of an given appname.
pub fn get_bundle_identifier(app_name: &str) -> Option<String> {
    unsafe {
        sys::getBundleIdentifier(NSString::from_str(app_name).deref()) // *const NSString
            .as_ref() // Option<NSString>
            .map(NSString::as_str)
            .map(String::from)
    }
}

/// Set the application which delivers or schedules a notification
pub fn set_application(bundle_ident: &str) -> NotificationResult<()> {
    unsafe {
        ensure!(!APPLICATION_SET, ApplicationError::AlreadySet);
        APPLICATION_SET = true;
        ensure!(
            sys::setApplication(NSString::from_str(bundle_ident).deref()),
            ApplicationError::CouldNotSet
        );
        Ok(())
    }
}

fn check_sound(sound_name: &str) -> bool {
    env::home_dir()
        .map(|path| path.join("/Library/Sounds/"))
        .into_iter()
        .chain(
            [
                "/Library/Sounds/",
                "/Network/Library/Sounds/",
                "/System/Library/Sounds/",
            ].into_iter()
                .map(PathBuf::from),
        )
        .map(|sound_path| sound_path.join(format!("{}.aiff", sound_name)))
        .any(|some_path| some_path.exists())
}