-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNotification.cs
More file actions
64 lines (53 loc) · 2.79 KB
/
Notification.cs
File metadata and controls
64 lines (53 loc) · 2.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
using System.Diagnostics;
namespace NotifysendSharp;
public class Notification
{
static (string[] Arguments, Dictionary<string, Func<CancellationToken, Task>> ButtonCallbacks) CompileArguments(NotificationOptions options)
{
List<string> args = [];
if (options.Urgency.HasValue) args.Add(Utils.Escape($"--urgency={options.Urgency.Value switch
{
NotificationUrgency.Low => "low",
NotificationUrgency.Normal => "normal",
NotificationUrgency.Critical => "critical",
_ => throw new NotImplementedException(),
}}"));
if (options.ExpireTime.HasValue) args.Add(Utils.Escape($"--expire-time={options.ExpireTime.Value.TotalMilliseconds}"));
if (!string.IsNullOrWhiteSpace(options.AppName)) args.Add(Utils.Escape($"--app-name={options.AppName}"));
if (!string.IsNullOrWhiteSpace(options.AppIcon)) args.Add(Utils.Escape($"--app-icon={options.AppIcon}"));
if (!string.IsNullOrWhiteSpace(options.Icon)) args.Add(Utils.Escape($"--icon={options.Icon}"));
if (options.Category is not null) args.Add(Utils.Escape($"--category={string.Join(',', options.Category)}"));
if (options.Transient) args.Add($"--transient");
if (options.Wait) args.Add($"--wait");
Dictionary<string, Func<CancellationToken, Task>> buttonCallbacks = [];
if (options.Buttons is not null && options.Buttons.Count > 0)
{
foreach (NotificationButton button in options.Buttons)
{
string key = Utils.GetNonce(buttonCallbacks.Count + 1);
buttonCallbacks.Add(key, button.Callback);
args.Add(Utils.Escape($"--action={key}={button.Label}"));
}
}
args.Add(Utils.Escape(options.Title));
if (!string.IsNullOrWhiteSpace(options.Body)) args.Add(Utils.Escape(options.Body));
return (args.ToArray(), buttonCallbacks);
}
public static async Task Send(NotificationOptions options, CancellationToken cancellationToken = default)
{
(string[] args, Dictionary<string, Func<CancellationToken, Task>> buttonCallbacks) = CompileArguments(options);
Process process = Process.Start(new ProcessStartInfo()
{
FileName = "notify-send",
Arguments = string.Join(' ', args),
RedirectStandardOutput = true,
UseShellExecute = false,
}) ?? throw new Exception($"Failed to start notify-send");
await process.WaitForExitAsync(cancellationToken).ContinueWith(_ => process.Kill(), cancellationToken);
string choice = process.StandardOutput.ReadToEnd().Trim();
if (buttonCallbacks.TryGetValue(choice, out Func<CancellationToken, Task>? callback))
{
await callback.Invoke(cancellationToken);
}
}
}