Last active
November 20, 2015 11:41
-
-
Save samnung/c7e767167cf70531ccdc to your computer and use it in GitHub Desktop.
Script to turn on or off `Do Not Disturb` mode on Mac OS X from console
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
# Get current status of Do Not Disturb mode by reading specific plist file | |
# | |
# @return [TrueClass,FalseClass] true if the mode is active | |
# | |
def do_not_disturb | |
plist_file = Dir.glob(Dir.home + '/Library/Preferences/ByHost/com.apple.notificationcenterui.*.plist').last | |
`/usr/libexec/PlistBuddy -c "Print doNotDisturb" "#{plist_file}"`.strip == 'true' | |
end | |
# Set status of Do Not Disturb mode | |
# | |
# @warning this method can take about 4 seconds to run, it is wating until the value is written to plist files | |
# | |
# @param [TrueClass,FalseClass] enabled true if the mode should be active | |
# | |
def do_not_disturb=(enabled) | |
if enabled != do_not_disturb | |
toggle_do_not_disturb_mode | |
while enabled != do_not_disturb | |
sleep 0.1 | |
end | |
end | |
end | |
# Toggle status of Do Not Disturb mode | |
# | |
def toggle_do_not_disturb_mode | |
script = <<-EOD | |
tell application "System Events" to tell process "SystemUIServer" | |
key down option | |
try | |
click menu bar item 1 of menu bar 2 | |
on error errMsg | |
log "something is wrong, maybe the Terminal.app don't have permissons to perform clicks, try enabling in System Preferences > Security & Privace > Privacy > Accessibility" | |
end try | |
key up option | |
end tell | |
EOD | |
system('osascript', '-e', script) | |
end | |
# Prints help to stream | |
# | |
def print_help(stream) | |
stream.puts "Tool to turn on or off `Do Not Disturb` mode on Mac OS X" | |
stream.puts "Usage: #{File.basename($PROGRAM_NAME)} (on|off)" | |
end | |
def validate_input_value | |
if ARGV.count != 1 | |
print_help($stderr) | |
exit 1 | |
end | |
value = ARGV[0] | |
if value == '--help' | |
print_help($stdout) | |
exit 0 | |
end | |
valid_values = %w(on off) | |
unless valid_values.include?(value) | |
$stderr.puts "Invalid input `#{value}`, valid ones are #{valid_values}." | |
exit 1 | |
end | |
value | |
end | |
self.do_not_disturb = validate_input_value == 'on' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment