Wednesday, November 18, 2020

an applescript to remind you of the sunset

I wanted to find a way to be reminded of when sunset was coming up, and couldn't find anything useful anywhere. So I wrote up my own AppleScript that displays a notification an hour ahead of sunset, and another when sunset happens. This script relies on LocationHelper and JSONHelper to function properly.

Without further ado, here it is:

-- get current location
tell application "Location Helper"
	-- Fetch the Google Map API information for the current location
	set current_location to get location coordinates
	set latitude to item 1 of current_location
	set longitude to item 2 of current_location
end tell

-- parse result
tell application "JSON Helper"
	set json to fetch JSON from "https://api.sunrise-sunset.org/json?lat=" & latitude & "&lng=" & longitude
	set json_parsed to json's items
	set json_data to json_parsed's first item
	set sunset to sunset of json_data
end tell

-- change hour to 24h (getting sunset in 12h format)
set sunset_time to date sunset
set sunset_time_24h to sunset_time + 12 * hours
set sunset_time to (time string of sunset_time_24h)

-- set reminder to hour before
set hour_before to sunset_time_24h - 1 * hours
set hour_before to (time string of hour_before)

-- get current time in UTC
set UTC to (current date) - (time to GMT)
set current_time to (time string of UTC)

-- now time
set time_now to current date
set time_now to text 1 thru 5 of time string of time_now

-- strip to hour and minutes
set sunset_time to (text 1 thru 5) of sunset_time
set hour_before_sunset to (text 1 thru 5) of hour_before
set current_time to (text 1 thru 5) of current_time

if current_time = hour_before_sunset then
	display notification "Sunset is in an hour!" with title "Sunset coming up" sound name "Submarine"
	delay 1
else if current_time = sunset_time then
	display notification "Sunset is now! (" & time_now & ")" sound name "Submarine"
	delay 1
end if

I have saved this script as an app in a folder under ~/Documents/SunsetReminder folder, and created the following plist file under ~/Library/LaunchAgents:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
	<key>Label</key>
	<string>local.sunsetreminder.notify</string>
	<key>ProgramArguments</key>
	<array>
		<string>/bin/sh</string>
		<string>-c</string>
		<string>/usr/bin/osascript ~/Documents/SunsetReminder/SunsetReminder.app</string>
	</array>
	<key>StartInterval</key>
	<integer>60</integer>
</dict>
</plist>

Finally, you want to run launchctl load -w /LaunchAgents/local.sunsetreminder.notify.plist from your terminal to load it. Good luck, and I hope it serves you well!

Sunday, August 16, 2020