Use osascript parameters for notification fallback on macOS

This commit is contained in:
Tulir Asokan 2021-09-19 20:38:29 -04:00
parent 86a9789013
commit 5b70a6f1e5

View File

@ -19,20 +19,23 @@ package notification
import ( import (
"fmt" "fmt"
"os/exec" "os/exec"
"strings"
) )
var TerminalNotifierAvailable = false var terminalNotifierAvailable = false
func init() { func init() {
if err := exec.Command("which", "terminal-notifier").Run(); err != nil { if err := exec.Command("which", "terminal-notifier").Run(); err != nil {
TerminalNotifierAvailable = false terminalNotifierAvailable = false
} }
TerminalNotifierAvailable = true terminalNotifierAvailable = true
} }
const sendScript = `on run {notifText, notifTitle}
display notification notifText with title "gomuks" subtitle notifTitle
end run`
func Send(title, text string, critical, sound bool) error { func Send(title, text string, critical, sound bool) error {
if TerminalNotifierAvailable { if terminalNotifierAvailable {
args := []string{"-title", "gomuks", "-subtitle", title, "-message", text} args := []string{"-title", "gomuks", "-subtitle", title, "-message", text}
if critical { if critical {
args = append(args, "-timeout", "15") args = append(args, "-timeout", "15")
@ -47,8 +50,16 @@ func Send(title, text string, critical, sound bool) error {
//} //}
return exec.Command("terminal-notifier", args...).Run() return exec.Command("terminal-notifier", args...).Run()
} }
title = strings.Replace(title, `"`, `\"`, -1) cmd := exec.Command("osascript", "-", text, title)
text = strings.Replace(text, `"`, `\"`, -1) if stdin, err := cmd.StdinPipe(); err != nil {
notification := fmt.Sprintf("display notification \"%s\" with title \"gomuks\" subtitle \"%s\"", text, title) return fmt.Errorf("failed to get stdin pipe for osascript: %w", err)
return exec.Command("osascript", "-e", notification).Run() } else if _, err = stdin.Write([]byte(sendScript)); err != nil {
return fmt.Errorf("failed to write notification script to osascript: %w", err)
} else if err = cmd.Run(); err != nil {
return fmt.Errorf("failed to run notification script: %w", err)
} else if !cmd.ProcessState.Success() {
return fmt.Errorf("notification script exited unsuccessfully")
} else {
return nil
}
} }