forked from versa-syahptr/winotify
-
Notifications
You must be signed in to change notification settings - Fork 0
/
winotify.py
270 lines (232 loc) · 10.3 KB
/
winotify.py
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
import os
import subprocess
import sys
import argparse
from tempfile import NamedTemporaryFile
__version__ = "1.0.2"
class Sound:
def __init__(self, s):
self.s = s
def __str__(self):
return self.s
class audio:
""" audio wrapper class """
Default = Sound("ms-winsoundevent:Notification.Default")
IM = Sound("ms-winsoundevent:Notification.IM")
Mail = Sound("ms-winsoundevent:Notification.Mail")
Reminder = Sound("ms-winsoundevent:Notification.Reminder")
SMS = Sound("ms-winsoundevent:Notification.SMS")
LoopingAlarm = Sound("ms-winsoundevent:Notification.Looping.Alarm")
LoopingAlarm2 = Sound("ms-winsoundevent:Notification.Looping.Alarm2")
LoopingAlarm3 = Sound("ms-winsoundevent:Notification.Looping.Alarm3")
LoopingAlarm4 = Sound("ms-winsoundevent:Notification.Looping.Alarm4")
LoopingAlarm6 = Sound("ms-winsoundevent:Notification.Looping.Alarm6")
LoopingAlarm8 = Sound("ms-winsoundevent:Notification.Looping.Alarm8")
LoopingAlarm9 = Sound("ms-winsoundevent:Notification.Looping.Alarm9")
LoopingAlarm10 = Sound("ms-winsoundevent:Notification.Looping.Alarm10")
LoopingCall = Sound("ms-winsoundevent:Notification.Looping.Call")
LoopingCall2 = Sound("ms-winsoundevent:Notification.Looping.Call2")
LoopingCall3 = Sound("ms-winsoundevent:Notification.Looping.Call3")
LoopingCall4 = Sound("ms-winsoundevent:Notification.Looping.Call4")
LoopingCall5 = Sound("ms-winsoundevent:Notification.Looping.Call5")
LoopingCall6 = Sound("ms-winsoundevent:Notification.Looping.Call6")
LoopingCall7 = Sound("ms-winsoundevent:Notification.Looping.Call7")
LoopingCall8 = Sound("ms-winsoundevent:Notification.Looping.Call8")
LoopingCall9 = Sound("ms-winsoundevent:Notification.Looping.Call9")
LoopingCall10 = Sound("ms-winsoundevent:Notification.Looping.Call10")
Silent = Sound("silent")
audio_map = {key.lower(): value for key, value in audio.__dict__.items() if not key.startswith("__")}
TEMPLATE = r"""
[Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime] > $null
[Windows.UI.Notifications.ToastNotification, Windows.UI.Notifications, ContentType = WindowsRuntime] | Out-Null
[Windows.Data.Xml.Dom.XmlDocument, Windows.Data.Xml.Dom.XmlDocument, ContentType = WindowsRuntime] | Out-Null
$Template = @"
<toast {launch} duration="{duration}">
<visual>
<binding template="ToastImageAndText02">
<image id="1" src="{icon}" />
<text id="1"><![CDATA[{title}]]></text>
<text id="2"><![CDATA[{msg}]]></text>
</binding>
</visual>
<actions>
{actions}
</actions>
{audio}
</toast>
"@
$SerializedXml = New-Object Windows.Data.Xml.Dom.XmlDocument
$SerializedXml.LoadXml($Template)
$Toast = [Windows.UI.Notifications.ToastNotification]::new($SerializedXml)
$Toast.Tag = "{tag}"
$Toast.Group = "{group}"
$Notifier = [Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier("{app_id}")
$Notifier.Show($Toast);
"""
class Notification(object):
def __init__(self,
app_id: str,
title: str,
msg: str = "",
icon: str = "",
duration: str = 'short',
launch: str = ''):
"""
Notification class
:param app_id: your app name, make it readable to your user. It can contain spaces, however special characters
(eg. é) are not supported.
:param title: The heading of the toast.
:param msg: The content/message of the toast.
:param icon: An optional path to an image on the OS to display to the left of the title & message.
Make sure you use an absolute path to the image.
:param duration: How long the toast should show up for (short/long), default is short.
:param launch: The url to launch (invoked when the user clicks the notification)
"""
self.app_id = app_id
self.title = title
self.msg = msg
self.icon = icon
self.duration = duration
self.launch = launch
self.audio = audio.Silent
self.tag, self.group = '', '' # you can set this value outside __init__
self.actions = []
self.script = ""
self.__dict__.update(
tag=self.tag or self.app_id,
group=self.group or self.app_id
)
if duration not in ("short", "long"):
raise ValueError("Duration is not 'short' or 'long'")
def set_audio(self, audio: Sound, loop: bool):
"""
Set audio to the notification object.
:param audio: The audio to play when the notification is showing. Choose one from audio class,
(eg. audio.Default). If not calling this method, default audio is silent
:param loop: A boolean indicating the audio should looping or not
:return: None
"""
self.audio = '<audio src="{}" loop="{}" />'.format(audio, str(loop).lower())
def add_actions(self, label: str, link: str):
"""
Add action button to the notification. You can have up to 5 buttons each toast.
:param label: The label of the button
:param link: The url to launch when clicking the button, 'file:///' protocol is allowed
:return: None
"""
xml = '<action activationType="protocol" content="{label}" arguments="{link}" />'
if len(self.actions) < 5:
self.actions.append(xml.format(label=label, link=link))
def build(self):
"""
Builds a temporary Windows PowerShell script
:return: self
"""
if self.actions:
self.actions = '\n'.join(self.actions)
else:
self.actions = ''
if self.audio == audio.Silent:
self.audio = '<audio silent="true" />'
if self.launch:
self.launch = 'activationType="protocol" launch="{}"'.format(self.launch)
self.script = TEMPLATE.format(**self.__dict__)
return self
def show(self):
"""
Invoke the temporary created script to Powershell to show the toast.
Note: Running the PowerShell script is by far the slowest process here, and can take a few
seconds in some cases.
:return: None
"""
if not self.script:
raise ValueError("Build the notification first before calling show()")
with NamedTemporaryFile('w', encoding='utf-16', suffix='.ps1', delete=False) as file:
file.write(self.script)
si = subprocess.STARTUPINFO()
si.dwFlags |= subprocess.STARTF_USESHOWWINDOW
subprocess.run([
"powershell.exe",
"-ExecutionPolicy", "Bypass",
"-WindowStyle", "Hidden",
"-file", file.name
],
# stdin, stdout, and stderr have to be defined here, because windows tries to duplicate these if not null
stdin=subprocess.DEVNULL,
stdout=subprocess.DEVNULL, # set to null because we don't need the output :)
stderr=subprocess.DEVNULL,
startupinfo=si
)
os.remove(file.name)
def main():
parser = argparse.ArgumentParser(prog="winotify[-nc]", description="Show notification toast on Windows 10."
"Use 'winotify-nc' for no console window.")
parser.version = __version__
parser.add_argument('-id',
'--app-id',
metavar="NAME",
default="windows app",
help="Your app name")
parser.add_argument("-t",
"--title",
default="Winotify Test Toast",
help="the notification title")
parser.add_argument("-m",
"--message",
default='New Notification!',
help="the notification's main messages")
parser.add_argument("-i",
"--icon",
default='',
metavar="PATH",
help="the icon path for the notification (note: the path must be absolute)")
parser.add_argument("--duration",
default="short",
choices=("short", "long"),
help="the duration of the notification should display (default: short)")
parser.add_argument("--open-url",
default='',
metavar='URL',
help="the URL to open when user click the notification")
parser.add_argument("--audio",
help="type of audio to play (default: silent)")
parser.add_argument("--loop",
action="store_true",
help="whether to loop audio")
parser.add_argument("--action",
metavar="LABEL",
action="append",
help="add button with LABEL as text, you can add up to 5 buttons")
parser.add_argument("--action-url",
metavar="URL",
action="append",
required=("--action" in sys.argv),
help="an URL to launch when the button clicked")
parser.add_argument("-v",
"--version",
action="version")
args = parser.parse_args()
toast = Notification(args.app_id,
args.title,
args.message,
args.icon,
args.duration,
args.open_url)
if args.audio is not None:
if args.audio not in audio_map.keys():
sys.exit("Invalid audio " + args.audio)
else:
toast.set_audio(audio_map[args.audio], args.loop)
actions = args.action
action_urls = args.action_url
if actions and action_urls:
if len(actions) == len(action_urls):
dik = dict(zip(actions, action_urls))
for action, url in dik.items():
toast.add_actions(action, url)
else:
parser.error("imbalance arguments, "
"the amount of action specified is not the same as the specified amount of action-url")
toast.build().show()
if __name__ == '__main__':
main()