-
Notifications
You must be signed in to change notification settings - Fork 334
/
AppNotificationUtility.cpp
483 lines (394 loc) · 17.7 KB
/
AppNotificationUtility.cpp
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
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
#include "pch.h"
#include <cwctype>
#include "AppNotificationUtility.h"
#include <winrt/Windows.ApplicationModel.Core.h>
#include <winrt/Windows.Foundation.h>
#include <winrt/base.h>
#include <externs.h>
#include <frameworkudk/pushnotifications.h>
#include "AppNotification.h"
#include "NotificationProgressData.h"
#include <wil/resource.h>
#include <wil/win32_helpers.h>
#include <propkey.h> // PKEY properties
#include <propsys.h> // IPropertyStore
#include <ShObjIdl_core.h>
namespace winrt
{
using namespace winrt::Windows::Foundation;
using namespace Windows::ApplicationModel::Core;
using namespace winrt::Microsoft::Windows::AppNotifications;
}
namespace ToastABI
{
using namespace ::ABI::Microsoft::Internal::ToastNotifications;
}
constexpr PCWSTR defaultAppNotificationIcon = LR"(ms-resource://Windows.UI.ShellCommon/Files/Images/DefaultSystemNotification.png)";
std::wstring Microsoft::Windows::AppNotifications::Helpers::RetrieveUnpackagedNotificationAppId()
{
wil::unique_cotaskmem_string appId;
// If the developer has called into SetCurrentProcessExplicitAppUserModelID, we should honor that AppId rather than dynamically generate our own
if (SUCCEEDED(GetCurrentProcessExplicitAppUserModelID(&appId)))
{
return appId.get();
}
else
{
// subKey: L"Software\\Classes\\AppUserModelId\\{Path to ToastNotificationsTestApp.exe}"
std::wstring subKey{ c_appIdentifierPath + ConvertPathToKey(GetCurrentProcessPath()) };
wil::unique_hkey hKey;
THROW_IF_WIN32_ERROR(RegCreateKeyEx(
HKEY_CURRENT_USER,
subKey.c_str(),
0,
nullptr /* lpClass */,
REG_OPTION_NON_VOLATILE,
KEY_ALL_ACCESS,
nullptr /* lpSecurityAttributes */,
&hKey,
nullptr /* lpdwDisposition */));
WCHAR registeredGuidBuffer[GUID_LENGTH];
DWORD bufferLength = sizeof(registeredGuidBuffer);
auto status = RegGetValueW(
hKey.get(),
nullptr /* lpValue */,
L"NotificationGUID",
RRF_RT_REG_SZ,
nullptr /* pdwType */,
®isteredGuidBuffer,
&bufferLength);
if (status == ERROR_FILE_NOT_FOUND)
{
GUID newNotificationGuid;
THROW_IF_FAILED(CoCreateGuid(&newNotificationGuid));
wil::unique_cotaskmem_string newNotificationGuidString;
THROW_IF_FAILED(StringFromCLSID(newNotificationGuid, &newNotificationGuidString));
RegisterValue(hKey, L"NotificationGUID", reinterpret_cast<const BYTE*>(newNotificationGuidString.get()), REG_SZ, wcslen(newNotificationGuidString.get()) * sizeof(wchar_t));
return newNotificationGuidString.get();
}
else
{
THROW_IF_WIN32_ERROR(status);
return registeredGuidBuffer;
}
}
}
std::wstring Microsoft::Windows::AppNotifications::Helpers::RetrieveNotificationAppId()
{
if (AppModel::Identity::IsPackagedProcess())
{
wchar_t appUserModelId[APPLICATION_USER_MODEL_ID_MAX_LENGTH] = {};
UINT32 appUserModelIdSize{ APPLICATION_USER_MODEL_ID_MAX_LENGTH };
THROW_IF_FAILED(GetCurrentApplicationUserModelId(&appUserModelIdSize, appUserModelId));
return appUserModelId;
}
else
{
return RetrieveUnpackagedNotificationAppId();
}
}
void Microsoft::Windows::AppNotifications::Helpers::RegisterComServer(wil::unique_cotaskmem_string const& clsid)
{
wil::unique_hkey hKey;
//subKey: Software\Classes\CLSID\{comActivatorGuidString}\LocalServer32
std::wstring subKey{ c_clsIdPath + clsid.get() + LR"(\LocalServer32)" };
THROW_IF_WIN32_ERROR(RegCreateKeyEx(
HKEY_CURRENT_USER,
subKey.c_str(),
0,
nullptr /* lpClass */,
REG_OPTION_NON_VOLATILE,
KEY_ALL_ACCESS,
nullptr /* lpSecurityAttributes */,
&hKey,
nullptr /* lpdwDisposition */));
std::wstring comRegistrationExeString{ c_quote + GetCurrentProcessPath() + c_quote + c_notificationActivatedArgument };
RegisterValue(hKey, nullptr, reinterpret_cast<const BYTE*>(comRegistrationExeString.c_str()), REG_SZ, (comRegistrationExeString.size() * sizeof(wchar_t)));
}
void Microsoft::Windows::AppNotifications::Helpers::UnRegisterComServer(std::wstring const& clsid)
{
wil::unique_hkey hKey;
//clsidPath: Software\Classes\CLSID\{comActivatorGuidString}
std::wstring clsidPath{ c_clsIdPath + clsid };
//subKey: Software\Classes\CLSID\{comActivatorGuidString}\LocalServer32
std::wstring subKey{ clsidPath + LR"(\LocalServer32)" };
THROW_IF_WIN32_ERROR(RegDeleteKeyEx(
HKEY_CURRENT_USER,
subKey.c_str(),
KEY_ALL_ACCESS,
0));
THROW_IF_WIN32_ERROR(RegDeleteKeyEx(
HKEY_CURRENT_USER,
clsidPath.c_str(),
KEY_ALL_ACCESS,
0));
}
void Microsoft::Windows::AppNotifications::Helpers::UnRegisterNotificationAppIdentifierFromRegistry()
{
wil::unique_cotaskmem_string appId;
std::wstring notificationAppId{ RetrieveNotificationAppId() };
wil::unique_hkey hKey;
//subKey: \Software\Classes\AppUserModelId\{AppGUID}
std::wstring subKey{ c_appIdentifierPath + notificationAppId };
THROW_IF_WIN32_ERROR(RegDeleteKeyEx(
HKEY_CURRENT_USER,
subKey.c_str(),
KEY_ALL_ACCESS,
0));
}
HRESULT Microsoft::Windows::AppNotifications::Helpers::GetActivatorGuid(std::wstring& activatorGuid) noexcept try
{
std::wstring notificationAppId{ RetrieveNotificationAppId() };
// subKey: \Software\Classes\AppUserModelId\{AppGUID}
std::wstring subKey{ c_appIdentifierPath + notificationAppId };
wil::unique_hkey hKey;
THROW_IF_WIN32_ERROR(RegCreateKeyEx(
HKEY_CURRENT_USER,
subKey.c_str(),
0,
nullptr /* lpClass */,
REG_OPTION_NON_VOLATILE,
KEY_ALL_ACCESS,
nullptr /* lpSecurityAttributes */,
&hKey,
nullptr /* lpdwDisposition */));
WCHAR activatorGuidBuffer[GUID_LENGTH];
DWORD bufferLength = sizeof(activatorGuidBuffer);
THROW_IF_WIN32_ERROR(RegGetValueW(
hKey.get(),
nullptr /* lpValue */,
L"CustomActivator",
RRF_RT_REG_SZ,
nullptr /* pdwType */,
&activatorGuidBuffer,
&bufferLength));
activatorGuid = activatorGuidBuffer;
// We want to verify the integrity of this COM registration in path: Software\Classes\CLSID\{comActivatorGuidString}\LocalServer32
// This would indicate data corruption in which case we create a new activator entry later on.
subKey = c_clsIdPath + activatorGuid + LR"(\LocalServer32)";
auto status = RegOpenKeyEx(
HKEY_CURRENT_USER,
subKey.c_str(),
0,
KEY_READ,
&hKey);
// If there is an activator GUID mismatch in the 2 paths, we should return ERROR_FILE_NOT_FOUND so that we can recreate the ActivatorGuid in the upper layers
if (FAILED_WIN32(status))
{
return HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND);
}
else
{
return S_OK;
}
}
CATCH_RETURN()
std::wstring Microsoft::Windows::AppNotifications::Helpers::SetDisplayNameBasedOnProcessName()
{
std::wstring displayName{};
THROW_IF_FAILED(wil::GetModuleFileNameExW(GetCurrentProcess(), nullptr, displayName));
size_t lastBackslashPosition{ displayName.rfind(L"\\") };
THROW_HR_IF(E_UNEXPECTED, lastBackslashPosition == std::wstring::npos);
displayName = displayName.substr(lastBackslashPosition + 1); // One after the delimiter
displayName.erase(displayName.find_first_of(L".")); // Remove file extension
displayName[0] = std::towupper(displayName[0]);
return displayName;
}
// Placeholder
HRESULT RetrieveAssetsFromProcess(_Out_ PWSTR* displayName, _Out_ PWSTR* iconFilePath)
{
*displayName = nullptr;
*iconFilePath = nullptr;
return E_NOTIMPL;
}
// Do nothing. This is just a placeholder while the UDK is ingested with the proper API.
HRESULT ToastNotifications_RetrieveAssets_Stub(_Out_ PWSTR* displayName, _Out_ PWSTR* iconFilePath)
{
*displayName = nullptr;
*iconFilePath = nullptr;
return E_NOTIMPL;
}
HRESULT RetrieveAssetsFromWindow(_Out_ PWSTR* displayName, _Out_ PWSTR* iconFilePath)
{
*displayName = nullptr;
*iconFilePath = nullptr;
wil::unique_cotaskmem_string localDisplayName;
wil::unique_cotaskmem_string localIconFilePath;
HWND hWindow = GetForegroundWindow();
if (hWindow)
{
winrt::com_ptr<IPropertyStore> propertyStore;
THROW_IF_FAILED(SHGetPropertyStoreForWindow(hWindow, IID_PPV_ARGS(propertyStore.put())));
wil::unique_prop_variant propVariantDisplayName;
THROW_IF_FAILED(propertyStore->GetValue(PKEY_AppUserModel_RelaunchDisplayNameResource, &propVariantDisplayName));
if (propVariantDisplayName.vt == VT_LPWSTR && Microsoft::Windows::AppNotifications::Helpers::IsWideStringEmptyOrNull(propVariantDisplayName.pwszVal))
{
localDisplayName = wil::make_unique_string<wil::unique_cotaskmem_string>(propVariantDisplayName.pwszVal);
}
wil::unique_prop_variant propVariantIcon;
THROW_IF_FAILED(propertyStore->GetValue(PKEY_AppUserModel_RelaunchIconResource, &propVariantIcon));
THROW_HR_IF(E_UNEXPECTED, propVariantIcon.vt != VT_LPWSTR || Microsoft::Windows::AppNotifications::Helpers::IsWideStringEmptyOrNull(propVariantIcon.pwszVal));
std::wstring localIconFilePathAsWstring = propVariantIcon.pwszVal;
// Icon filepaths from Shell APIs usually follow this format: <filepath>,-<index>,
// since .ico or .dll files can have multiple icons in the same file.
// NotificationController doesn't seem to support such format, so let it take the first icon by default.
auto iteratorForCommaDelimiter{ localIconFilePathAsWstring.find_first_of(L",") };
if (iteratorForCommaDelimiter != std::wstring::npos) // It may or may not have an index, which is fine.
{
localIconFilePath = wil::make_unique_string<wil::unique_cotaskmem_string>(localIconFilePathAsWstring.erase(iteratorForCommaDelimiter).c_str());
}
*displayName = localDisplayName.release();
*iconFilePath = localIconFilePath.release();
return S_OK;
}
return HRESULT_FROM_WIN32(ERROR_NOT_FOUND);
}
void Microsoft::Windows::AppNotifications::Helpers::RegisterAssets(std::wstring const& appId, std::wstring const& clsid)
{
wil::unique_hkey hKey;
// subKey: \Software\Classes\AppUserModelId\{AppGUID}
std::wstring subKey{ c_appIdentifierPath + appId };
THROW_IF_WIN32_ERROR(RegCreateKeyEx(
HKEY_CURRENT_USER,
subKey.c_str(),
0,
nullptr /* lpClass */,
REG_OPTION_NON_VOLATILE,
KEY_ALL_ACCESS,
nullptr /* lpSecurityAttributes */,
&hKey,
nullptr /* lpdwDisposition */));
bool useDefaultAssets{ false };
wil::unique_cotaskmem_string displayName;
wil::unique_cotaskmem_string iconFilePath;
// Try the following techniques to retrieve display name and icon:
// 1. From the current process.
// 2. Based on the best app shortcut, using the FrameworkUdk.
// 3. From the foreground window.
// 4. Use the default assets.
if (FAILED(RetrieveAssetsFromProcess(&displayName, &iconFilePath)) &&
FAILED(ToastNotifications_RetrieveAssets_Stub(&displayName, &iconFilePath)) &&
FAILED(RetrieveAssetsFromWindow(&displayName, &iconFilePath)))
{
displayName = wil::make_unique_string<wil::unique_cotaskmem_string>(SetDisplayNameBasedOnProcessName().c_str());
iconFilePath = wil::make_unique_string<wil::unique_cotaskmem_string>(defaultAppNotificationIcon);
useDefaultAssets = true;
}
// Verify if we support the provided file format for the icon. Do not verify for the default icon, we know it is supported.
if (!useDefaultAssets)
{
std::wstring iconFilePathAsWstring{ iconFilePath.get() };
auto iteratorForFileExtension{ iconFilePathAsWstring.find_first_of(L".") };
THROW_HR_IF_MSG(E_UNEXPECTED, iteratorForFileExtension == std::wstring::npos, "You must provide a valid filepath as the app icon.");
std::wstring iconFileExtension = iconFilePathAsWstring.substr(iteratorForFileExtension);
THROW_HR_IF_MSG(E_UNEXPECTED,
iconFileExtension != L".ico" && iconFileExtension != L".png" &&
iconFileExtension != L".jpg" && iconFileExtension != L".bmp",
"You must provide a supported file format for the icon. Supported formats: .bmp, .ico, .jpg, .png.");
}
RegisterValue(hKey, L"DisplayName", reinterpret_cast<const BYTE*>(displayName.get()), REG_EXPAND_SZ, wcslen(displayName.get()) * sizeof(wchar_t));
RegisterValue(hKey, L"IconUri", reinterpret_cast<const BYTE*>(iconFilePath.get()), REG_EXPAND_SZ, wcslen(iconFilePath.get()) * sizeof(wchar_t));
RegisterValue(hKey, L"CustomActivator", reinterpret_cast<const BYTE*>(clsid.c_str()), REG_SZ, clsid.size() * sizeof(wchar_t));
}
winrt::guid Microsoft::Windows::AppNotifications::Helpers::RegisterComActivatorGuidAndAssets()
{
std::wstring registeredGuid;
auto hr = GetActivatorGuid(registeredGuid);
if (hr == HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND))
{
// Create a GUID for the COM Activator
GUID comActivatorGuid = GUID_NULL;
THROW_IF_FAILED(CoCreateGuid(&comActivatorGuid));
// StringFromCLSID returns GUID String with braces
wil::unique_cotaskmem_string comActivatorGuidString;
THROW_IF_FAILED(StringFromCLSID(comActivatorGuid, &comActivatorGuidString));
RegisterComServer(comActivatorGuidString);
registeredGuid = comActivatorGuidString.get();
}
else
{
THROW_IF_FAILED(hr);
}
std::wstring notificationAppId{ RetrieveNotificationAppId() };
RegisterAssets(notificationAppId, registeredGuid);
// Remove braces around the guid string
return winrt::guid(registeredGuid.substr(1, registeredGuid.size() - 2));
}
wil::unique_cotaskmem_string Microsoft::Windows::AppNotifications::Helpers::ConvertUtf8StringToWideString(unsigned long length, const byte* utf8String)
{
int size{ MultiByteToWideChar(
CP_UTF8,
0,
reinterpret_cast<PCSTR>(utf8String),
length,
nullptr,
0) };
THROW_LAST_ERROR_IF(size == 0);
wil::unique_cotaskmem_string wideString{ wil::make_unique_string<wil::unique_cotaskmem_string>(nullptr, size) };
size = MultiByteToWideChar(
CP_UTF8,
0,
reinterpret_cast<PCSTR>(utf8String),
length,
wideString.get(),
size);
THROW_LAST_ERROR_IF(size == 0);
return wideString;
}
winrt::Microsoft::Windows::AppNotifications::AppNotification Microsoft::Windows::AppNotifications::Helpers::ToastNotificationFromToastProperties(ABI::Microsoft::Internal::ToastNotifications::INotificationProperties* properties)
{
unsigned int payloadSize{};
wil::unique_cotaskmem_array_ptr<byte> payload{};
THROW_IF_FAILED(properties->get_Payload(&payloadSize, &payload));
auto wide{ ConvertUtf8StringToWideString(payloadSize, payload.get()) };
winrt::hstring xmlPayload{ wide.get() };
winrt::Microsoft::Windows::AppNotifications::AppNotification notification(xmlPayload);
wil::unique_hstring tag{};
THROW_IF_FAILED(properties->get_Tag(&tag));
notification.Tag(wil::str_raw_ptr(tag));
wil::unique_hstring group{};
THROW_IF_FAILED(properties->get_Group(&group));
notification.Group(wil::str_raw_ptr(group));
unsigned int notificationId{};
THROW_IF_FAILED(properties->get_NotificationId(¬ificationId));
winrt::Microsoft::Windows::AppNotifications::implementation::AppNotification* notificationImpl{ winrt::get_self< winrt::Microsoft::Windows::AppNotifications::implementation::AppNotification>(notification) };
notificationImpl->SetNotificationId(notificationId);
winrt::com_ptr<ToastABI::IToastProgressData> toastProgressData;
THROW_IF_FAILED(properties->get_ToastProgressData(toastProgressData.put()));
if (toastProgressData)
{
// Sequence number is a transient property and we give it a default non-zero value of 1 in the ctor
winrt::AppNotificationProgressData progressData{ 1 };
wil::unique_hstring status{};
THROW_IF_FAILED(toastProgressData->get_Status(&status));
progressData.Status(wil::str_raw_ptr(status));
wil::unique_hstring title{};
THROW_IF_FAILED(toastProgressData->get_Title(&title));
progressData.Title(wil::str_raw_ptr(title));
double progressValue{};
THROW_IF_FAILED(toastProgressData->get_Value(&progressValue));
progressData.Value(progressValue);
wil::unique_hstring progressValueString{};
THROW_IF_FAILED(toastProgressData->get_ValueStringOverride(&progressValueString));
progressData.ValueStringOverride(wil::str_raw_ptr(progressValueString));
notification.Progress(progressData);
}
unsigned long long expiry{};
THROW_IF_FAILED(properties->get_Expiry(&expiry));
FILETIME expiryFileTime{};
expiryFileTime.dwHighDateTime = expiry >> 32;
expiryFileTime.dwLowDateTime = static_cast<DWORD>(expiry);
notification.Expiration(winrt::clock::from_file_time(expiryFileTime));
boolean expiresOnReboot{};
THROW_IF_FAILED(properties->get_ExpiresOnReboot(&expiresOnReboot));
notification.ExpiresOnReboot(expiresOnReboot);
// Priority and SupressDisplay are transient values that do not exist in ToastProperties and thus, are left to their default.
return notification;
}
bool Microsoft::Windows::AppNotifications::Helpers::IsWideStringEmptyOrNull(PCWSTR wideString)
{
return wideString == nullptr || wcslen(wideString) > 0;
}