Desktop notifications for Go
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

94 lines
1.8 KiB

  1. package gotifier
  2. import (
  3. //"log"
  4. "os/exec"
  5. )
  6. const (
  7. terminalNotifier = "terminal-notifier"
  8. notifySend = "notify-send"
  9. )
  10. type Notification struct {
  11. Title, Subtitle, Message string
  12. }
  13. func (notif Notification) Push() bool {
  14. //log.Println("Pushing notification")
  15. if activeCmd == nil {
  16. //log.Println("No active notification command found")
  17. return false
  18. }
  19. cmd := (*activeCmd).Command(notif)
  20. cmd.Run()
  21. return true
  22. }
  23. type NotifierCommand struct {
  24. Name, Path string
  25. }
  26. func (cmd NotifierCommand) Command(notif Notification) *exec.Cmd {
  27. // message is required
  28. message := nonNull(notif.Message, notif.Title, notif.Subtitle)
  29. var args = []string{""}
  30. switch cmd.Name {
  31. case terminalNotifier:
  32. // Append message
  33. args = append(args, "-message")
  34. args = append(args, "\""+message+"\"")
  35. if notif.Title != "" {
  36. args = append(args, "-title")
  37. args = append(args, "\""+notif.Title+"\"")
  38. }
  39. if notif.Subtitle != "" {
  40. args = append(args, "-subtitle")
  41. args = append(args, "\""+notif.Subtitle+"\"")
  42. }
  43. case notifySend:
  44. if notif.Title != "" {
  45. args = append(args, notif.Title)
  46. }
  47. args = append(args, message)
  48. }
  49. //return log.Sprintf("%s %s", cmd.Path, strings.Join(args, " "))
  50. return &exec.Cmd{Path: cmd.Path, Args: args}
  51. }
  52. var activeCmd *NotifierCommand
  53. var notifiers = []NotifierCommand{
  54. NotifierCommand{Name: "terminal-notifier"},
  55. NotifierCommand{Name: "notify-send"},
  56. }
  57. func nonNull(vals ...string) string {
  58. for _, val := range vals {
  59. if val != "" {
  60. return val
  61. }
  62. }
  63. return ""
  64. }
  65. func init() {
  66. //log.Println("Initing Gotifier")
  67. for _, cmd := range notifiers {
  68. path, err := exec.LookPath(cmd.Name)
  69. if err == nil && path != "" {
  70. activeCmd = &cmd
  71. activeCmd.Path = path
  72. //log.Println("Found notifier command: " + path)
  73. return
  74. }
  75. }
  76. }