vendor/github.com/go-toast/toast/toast.go
359 lines · 11783 bytes
1package toast
2
3import (
4 "bytes"
5 "errors"
6 "io/ioutil"
7 "os"
8 "os/exec"
9 "path/filepath"
10 "strings"
11 "text/template"
12
13 "github.com/nu7hatch/gouuid"
14 "syscall"
15)
16
17var toastTemplate *template.Template
18
19var (
20 ErrorInvalidAudio error = errors.New("toast: invalid audio")
21 ErrorInvalidDuration = errors.New("toast: invalid duration")
22)
23
24type toastAudio string
25
26const (
27 Default toastAudio = "ms-winsoundevent:Notification.Default"
28 IM = "ms-winsoundevent:Notification.IM"
29 Mail = "ms-winsoundevent:Notification.Mail"
30 Reminder = "ms-winsoundevent:Notification.Reminder"
31 SMS = "ms-winsoundevent:Notification.SMS"
32 LoopingAlarm = "ms-winsoundevent:Notification.Looping.Alarm"
33 LoopingAlarm2 = "ms-winsoundevent:Notification.Looping.Alarm2"
34 LoopingAlarm3 = "ms-winsoundevent:Notification.Looping.Alarm3"
35 LoopingAlarm4 = "ms-winsoundevent:Notification.Looping.Alarm4"
36 LoopingAlarm5 = "ms-winsoundevent:Notification.Looping.Alarm5"
37 LoopingAlarm6 = "ms-winsoundevent:Notification.Looping.Alarm6"
38 LoopingAlarm7 = "ms-winsoundevent:Notification.Looping.Alarm7"
39 LoopingAlarm8 = "ms-winsoundevent:Notification.Looping.Alarm8"
40 LoopingAlarm9 = "ms-winsoundevent:Notification.Looping.Alarm9"
41 LoopingAlarm10 = "ms-winsoundevent:Notification.Looping.Alarm10"
42 LoopingCall = "ms-winsoundevent:Notification.Looping.Call"
43 LoopingCall2 = "ms-winsoundevent:Notification.Looping.Call2"
44 LoopingCall3 = "ms-winsoundevent:Notification.Looping.Call3"
45 LoopingCall4 = "ms-winsoundevent:Notification.Looping.Call4"
46 LoopingCall5 = "ms-winsoundevent:Notification.Looping.Call5"
47 LoopingCall6 = "ms-winsoundevent:Notification.Looping.Call6"
48 LoopingCall7 = "ms-winsoundevent:Notification.Looping.Call7"
49 LoopingCall8 = "ms-winsoundevent:Notification.Looping.Call8"
50 LoopingCall9 = "ms-winsoundevent:Notification.Looping.Call9"
51 LoopingCall10 = "ms-winsoundevent:Notification.Looping.Call10"
52 Silent = "silent"
53)
54
55type toastDuration string
56
57const (
58 Short toastDuration = "short"
59 Long = "long"
60)
61
62func init() {
63 toastTemplate = template.New("toast")
64 toastTemplate.Parse(`
65[Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime] | Out-Null
66[Windows.UI.Notifications.ToastNotification, Windows.UI.Notifications, ContentType = WindowsRuntime] | Out-Null
67[Windows.Data.Xml.Dom.XmlDocument, Windows.Data.Xml.Dom.XmlDocument, ContentType = WindowsRuntime] | Out-Null
68
69$APP_ID = '{{if .AppID}}{{.AppID}}{{else}}Windows App{{end}}'
70
71$template = @"
72<toast activationType="{{.ActivationType}}" launch="{{.ActivationArguments}}" duration="{{.Duration}}">
73 <visual>
74 <binding template="ToastGeneric">
75 {{if .Icon}}
76 <image placement="appLogoOverride" src="{{.Icon}}" />
77 {{end}}
78 {{if .Title}}
79 <text><![CDATA[{{.Title}}]]></text>
80 {{end}}
81 {{if .Message}}
82 <text><![CDATA[{{.Message}}]]></text>
83 {{end}}
84 </binding>
85 </visual>
86 {{if ne .Audio "silent"}}
87 <audio src="{{.Audio}}" loop="{{.Loop}}" />
88 {{else}}
89 <audio silent="true" />
90 {{end}}
91 {{if .Actions}}
92 <actions>
93 {{range .Actions}}
94 <action activationType="{{.Type}}" content="{{.Label}}" arguments="{{.Arguments}}" />
95 {{end}}
96 </actions>
97 {{end}}
98</toast>
99"@
100
101$xml = New-Object Windows.Data.Xml.Dom.XmlDocument
102$xml.LoadXml($template)
103$toast = New-Object Windows.UI.Notifications.ToastNotification $xml
104[Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier($APP_ID).Show($toast)
105 `)
106}
107
108// Notification
109//
110// The toast notification data. The following fields are strongly recommended;
111// - AppID
112// - Title
113//
114// If no toastAudio is provided, then the toast notification will be silent.
115// You can set the toast to have a default audio by setting "Audio" to "toast.Default", or if your go app takes
116// user-provided input for audio, call the "toast.Audio(name)" func.
117//
118// The AppID is shown beneath the toast message (in certain cases), and above the notification within the Action
119// Center - and is used to group your notifications together. It is recommended that you provide a "pretty"
120// name for your app, and not something like "com.example.MyApp".
121//
122// If no Title is provided, but a Message is, the message will display as the toast notification's title -
123// which is a slightly different font style (heavier).
124//
125// The Icon should be an absolute path to the icon (as the toast is invoked from a temporary path on the user's
126// system, not the working directory).
127//
128// If you would like the toast to call an external process/open a webpage, then you can set ActivationArguments
129// to the uri you would like to trigger when the toast is clicked. For example: "https://google.com" would open
130// the Google homepage when the user clicks the toast notification.
131// By default, clicking the toast just hides/dismisses it.
132//
133// The following would show a notification to the user letting them know they received an email, and opens
134// gmail.com when they click the notification. It also makes the Windows 10 "mail" sound effect.
135//
136// toast := toast.Notification{
137// AppID: "Google Mail",
138// Title: email.Subject,
139// Message: email.Preview,
140// Icon: "C:/Program Files/Google Mail/icons/logo.png",
141// ActivationArguments: "https://gmail.com",
142// Audio: toast.Mail,
143// }
144//
145// err := toast.Push()
146type Notification struct {
147 // The name of your app. This value shows up in Windows 10's Action Centre, so make it
148 // something readable for your users. It can contain spaces, however special characters
149 // (eg. é) are not supported.
150 AppID string
151
152 // The main title/heading for the toast notification.
153 Title string
154
155 // The single/multi line message to display for the toast notification.
156 Message string
157
158 // An optional path to an image on the OS to display to the left of the title & message.
159 Icon string
160
161 // The type of notification level action (like toast.Action)
162 ActivationType string
163
164 // The activation/action arguments (invoked when the user clicks the notification)
165 ActivationArguments string
166
167 // Optional action buttons to display below the notification title & message.
168 Actions []Action
169
170 // The audio to play when displaying the toast
171 Audio toastAudio
172
173 // Whether to loop the audio (default false)
174 Loop bool
175
176 // How long the toast should show up for (short/long)
177 Duration toastDuration
178}
179
180// Action
181//
182// Defines an actionable button.
183// See https://msdn.microsoft.com/en-us/windows/uwp/controls-and-patterns/tiles-and-notifications-adaptive-interactive-toasts for more info.
184//
185// Only protocol type action buttons are actually useful, as there's no way of receiving feedback from the
186// user's choice. Examples of protocol type action buttons include: "bingmaps:?q=sushi" to open up Windows 10's
187// maps app with a pre-populated search field set to "sushi".
188//
189// toast.Action{"protocol", "Open Maps", "bingmaps:?q=sushi"}
190type Action struct {
191 Type string
192 Label string
193 Arguments string
194}
195
196func (n *Notification) applyDefaults() {
197 if n.ActivationType == "" {
198 n.ActivationType = "protocol"
199 }
200 if n.Duration == "" {
201 n.Duration = Short
202 }
203 if n.Audio == "" {
204 n.Audio = Default
205 }
206}
207
208func (n *Notification) buildXML() (string, error) {
209 var out bytes.Buffer
210 err := toastTemplate.Execute(&out, n)
211 if err != nil {
212 return "", err
213 }
214 return out.String(), nil
215}
216
217// Builds the Windows PowerShell script & invokes it, causing the toast to display.
218//
219// Note: Running the PowerShell script is by far the slowest process here, and can take a few
220// seconds in some cases.
221//
222// notification := toast.Notification{
223// AppID: "Example App",
224// Title: "My notification",
225// Message: "Some message about how important something is...",
226// Icon: "go.png",
227// Actions: []toast.Action{
228// {"protocol", "I'm a button", ""},
229// {"protocol", "Me too!", ""},
230// },
231// }
232// err := notification.Push()
233// if err != nil {
234// log.Fatalln(err)
235// }
236func (n *Notification) Push() error {
237 n.applyDefaults()
238 xml, err := n.buildXML()
239 if err != nil {
240 return err
241 }
242 return invokeTemporaryScript(xml)
243}
244
245// Returns a toastAudio given a user-provided input (useful for cli apps).
246//
247// If the "name" doesn't match, then the default toastAudio is returned, along with ErrorInvalidAudio.
248//
249// The following names are valid;
250// - default
251// - im
252// - mail
253// - reminder
254// - sms
255// - loopingalarm
256// - loopimgalarm[2-10]
257// - loopingcall
258// - loopingcall[2-10]
259// - silent
260//
261// Handle the error appropriately according to how your app should work.
262func Audio(name string) (toastAudio, error) {
263 switch strings.ToLower(name) {
264 case "default":
265 return Default, nil
266 case "im":
267 return IM, nil
268 case "mail":
269 return Mail, nil
270 case "reminder":
271 return Reminder, nil
272 case "sms":
273 return SMS, nil
274 case "loopingalarm":
275 return LoopingAlarm, nil
276 case "loopingalarm2":
277 return LoopingAlarm2, nil
278 case "loopingalarm3":
279 return LoopingAlarm3, nil
280 case "loopingalarm4":
281 return LoopingAlarm4, nil
282 case "loopingalarm5":
283 return LoopingAlarm5, nil
284 case "loopingalarm6":
285 return LoopingAlarm6, nil
286 case "loopingalarm7":
287 return LoopingAlarm7, nil
288 case "loopingalarm8":
289 return LoopingAlarm8, nil
290 case "loopingalarm9":
291 return LoopingAlarm9, nil
292 case "loopingalarm10":
293 return LoopingAlarm10, nil
294 case "loopingcall":
295 return LoopingCall, nil
296 case "loopingcall2":
297 return LoopingCall2, nil
298 case "loopingcall3":
299 return LoopingCall3, nil
300 case "loopingcall4":
301 return LoopingCall4, nil
302 case "loopingcall5":
303 return LoopingCall5, nil
304 case "loopingcall6":
305 return LoopingCall6, nil
306 case "loopingcall7":
307 return LoopingCall7, nil
308 case "loopingcall8":
309 return LoopingCall8, nil
310 case "loopingcall9":
311 return LoopingCall9, nil
312 case "loopingcall10":
313 return LoopingCall10, nil
314 case "silent":
315 return Silent, nil
316 default:
317 return Default, ErrorInvalidAudio
318 }
319}
320
321// Returns a toastDuration given a user-provided input (useful for cli apps).
322//
323// The default duration is short. If the "name" doesn't match, then the default toastDuration is returned,
324// along with ErrorInvalidDuration. Most of the time "short" is the most appropriate for a toast notification,
325// and Microsoft recommend not using "long", but it can be useful for important dialogs or looping sound toasts.
326//
327// The following names are valid;
328// - short
329// - long
330//
331// Handle the error appropriately according to how your app should work.
332func Duration(name string) (toastDuration, error) {
333 switch strings.ToLower(name) {
334 case "short":
335 return Short, nil
336 case "long":
337 return Long, nil
338 default:
339 return Short, ErrorInvalidDuration
340 }
341}
342
343func invokeTemporaryScript(content string) error {
344 id, _ := uuid.NewV4()
345 file := filepath.Join(os.TempDir(), id.String()+".ps1")
346 defer os.Remove(file)
347 bomUtf8 := []byte{0xEF, 0xBB, 0xBF}
348 out := append(bomUtf8, []byte(content)...)
349 err := ioutil.WriteFile(file, out, 0600)
350 if err != nil {
351 return err
352 }
353 cmd := exec.Command("PowerShell", "-ExecutionPolicy", "Bypass", "-File", file)
354 cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true}
355 if err = cmd.Run(); err != nil {
356 return err
357 }
358 return nil
359}