Skip to content

Instantly share code, notes, and snippets.

@alexclst
Last active September 13, 2020 02:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexclst/2e5c1aa2ca98c662bae1 to your computer and use it in GitHub Desktop.
Save alexclst/2e5c1aa2ca98c662bae1 to your computer and use it in GitHub Desktop.
Shell script to encapsulate sending user notifications
#!/bin/bash
# sendusernotification.sh
# Created by Alexander Celeste for Tenseg in March 2016
# This script can be used to send user notifications to Notification Center, regularly just to OS X, but also to the Prowl iOS app if the Mac is idle
# It can be used in long-running scripts to notify of completion, and in scripts that run via launchd to notify of files being added to folders, or really any use you can dream up
# Dependencies:
# * terminal-notifier: https://github.com/julienXX/terminal-notifier
# * prowl.pl: https://www.prowlapp.com/static/prowl.pl
# get inputs
Title="$1"
Message="$2"
Identifier="$3"
if [ -z "$Identifier" ]; then
Identifier="com.apple.Terminal"
fi
# send to OS X Notification Center
# uses https://github.com/julienXX/terminal-notifier
/Applications/terminal-notifier.app/Contents/MacOS/terminal-notifier -title "$Title" -message "$Message" -sender "$Identifier"
# send to iOS Notification Center if the Mac has been idle for a minute or longer, there is both a Prowl and a IFTTT method below, pick the one you desire most
# both methods rely on you saving the API key used for the relevant service to a Secure Note in Keychain Access
IdleTime=$(/usr/bin/printf "%.0f" $(/usr/sbin/ioreg -c IOHIDSystem | /usr/bin/awk '/HIDIdleTime/ {print $NF/1000000000; exit}'))
if [ $IdleTime -ge 60 ]; then
Path=$(/usr/bin/mdfind kMDItemCFBundleIdentifier = "$Identifier")
b=$(/usr/bin/basename $Path)
Application=$(/bin/echo $b | /usr/bin/cut -f 1 -d '.')
# Prowl method, uses https://www.prowlapp.com/static/prowl.pl
ApiKey=$(/usr/bin/security find-generic-password -g -s "prowlapikey" 2>&1 1>/dev/null | /usr/bin/perl -pe '($_) = /"(.+)"/; s/\\012/\n/g' | perl -MXML::LibXML -e 'print XML::LibXML->new()->parse_file("-")->findvalue(q(//string[preceding-sibling::key[1] = "NOTE"]))')
/usr/local/bin/prowl.pl -apikey="$ApiKey" -application="$Application" -event="$Title" -notification="$Message"
# IFTTT method
Key=$(/usr/bin/security find-generic-password -g -s "iftttmakerkey" 2>&1 1>/dev/null | /usr/bin/perl -pe '($_) = /"(.+)"/; s/\\012/\n/g' | perl -MXML::LibXML -e 'print XML::LibXML->new()->parse_file("-")->findvalue(q(//string[preceding-sibling::key[1] = "NOTE"]))')
/usr/bin/curl -H "Content-type: application/json" -X POST -d ' {"value1":"'$Application'","value2":"'$Title'","value3":"'$Message'"}' https://maker.ifttt.com/trigger/mac_notification_recieved/with/key/$Key
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment