go-nativenotify

Native notifications in Go
Log | Files | Refs | README | LICENSE

notify_darwin.go (1955B)


      1 package nativenotify
      2 
      3 import (
      4 	"fmt"
      5 	"strconv"
      6 	"strings"
      7 
      8 	darwinnotify "git.sr.ht/~jackmordaunt/go-notify-darwin"
      9 )
     10 
     11 const defaultAction = "com.apple.UNNotificationDefaultActionIdentifier"
     12 
     13 func setup(cfg Config) error {
     14 	darwinnotify.Init(cfg.Darwin.Categories...)
     15 
     16 	darwinnotify.SetCallback(func(args darwinnotify.CallbackArgs) {
     17 		id := args.UserData["id"]
     18 
     19 		parts := strings.Split(args.Action, "-")
     20 
     21 		actionIDEncoded, _ := take(&parts)
     22 		actionArgsEncoded, _ := take(&parts)
     23 
     24 		actionID := decode(actionIDEncoded)
     25 		actionArgs := decode(actionArgsEncoded)
     26 
     27 		if args.Action == defaultAction {
     28 			actionID = "default"
     29 		}
     30 
     31 		if args.UserText != "" {
     32 			actionArgs = args.UserText
     33 		}
     34 
     35 		fn, ok := callbacksTake(&callbacks, id)
     36 		if !ok || fn == nil {
     37 			return
     38 		}
     39 
     40 		fn(actionID, actionArgs)
     41 	})
     42 
     43 	return nil
     44 }
     45 
     46 func push(n Notification) (err error) {
     47 	id := nextID.Add(1)
     48 
     49 	var (
     50 		buttons  = make([]darwinnotify.Action, 0, len(n.ButtonActions))
     51 		inputs   = make([]darwinnotify.TextInputAction, 0, len(n.TextActions))
     52 		userData = make(darwinnotify.UserData)
     53 	)
     54 
     55 	userData["id"] = strconv.FormatInt(id, 10)
     56 
     57 	for _, button := range n.ButtonActions {
     58 		buttons = append(buttons, darwinnotify.Action{
     59 			ID:    fmt.Sprintf("%s-%s", encode(button.ID), encode(button.Value)),
     60 			Title: button.LabelText,
     61 		})
     62 	}
     63 
     64 	for _, input := range n.TextActions {
     65 		inputs = append(inputs, darwinnotify.TextInputAction{
     66 			ID:          encode(input.ID),
     67 			Title:       input.Title,
     68 			Placeholder: input.PlaceholderHint,
     69 			ButtonTitle: input.ButtonLabel,
     70 		})
     71 	}
     72 
     73 	var attachments []string
     74 
     75 	if n.Icon != "" {
     76 		attachments = []string{n.Icon}
     77 	}
     78 
     79 	darwinnotify.Notify(darwinnotify.Notification{
     80 		Title:            n.Title,
     81 		Body:             n.Body,
     82 		Attachments:      attachments,
     83 		Actions:          buttons,
     84 		TextInputActions: inputs,
     85 		UserData:         userData,
     86 	})
     87 
     88 	callbacksPut(&callbacks, strconv.FormatInt(id, 10), n.Callback)
     89 
     90 	return nil
     91 }