summaryrefslogtreecommitdiffstats
path: root/widget/windows/tests/unit/test_windows_alert_service.js
blob: 0ba0d2a4d4a1db6ce715786cfeb656c88e0ca068 (plain)
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
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
/* Any copyright is dedicated to the Public Domain.
   http://creativecommons.org/publicdomain/zero/1.0/ */

/*
 * Test that Windows alert notifications generate expected XML.
 */

var { AppConstants } = ChromeUtils.importESModule(
  "resource://gre/modules/AppConstants.sys.mjs"
);

let gProfD = do_get_profile();

// Setup that allows to use the profile service in xpcshell tests,
// lifted from `toolkit/profile/xpcshell/head.js`.
function setupProfileService() {
  let gDataHome = gProfD.clone();
  gDataHome.append("data");
  gDataHome.createUnique(Ci.nsIFile.DIRECTORY_TYPE, 0o755);
  let gDataHomeLocal = gProfD.clone();
  gDataHomeLocal.append("local");
  gDataHomeLocal.createUnique(Ci.nsIFile.DIRECTORY_TYPE, 0o755);

  let xreDirProvider = Cc["@mozilla.org/xre/directory-provider;1"].getService(
    Ci.nsIXREDirProvider
  );
  xreDirProvider.setUserDataDirectory(gDataHome, false);
  xreDirProvider.setUserDataDirectory(gDataHomeLocal, true);
}

add_setup(setupProfileService);

function makeAlert(options) {
  var alert = Cc["@mozilla.org/alert-notification;1"].createInstance(
    Ci.nsIAlertNotification
  );
  alert.init(
    options.name,
    options.imageURL,
    options.title,
    options.text,
    options.textClickable,
    options.cookie,
    options.dir,
    options.lang,
    options.data,
    options.principal,
    options.inPrivateBrowsing,
    options.requireInteraction,
    options.silent,
    options.vibrate || []
  );
  if (options.actions) {
    alert.actions = options.actions;
  }
  if (options.opaqueRelaunchData) {
    alert.opaqueRelaunchData = options.opaqueRelaunchData;
  }
  return alert;
}

/**
 * Take a `key1\nvalue1\n...` string encoding as used by the Windows native
 * notification server DLL, and split it into an object, keeping `action\n...`
 * intact.
 *
 * @param {string} t string encoding.
 * @returns {object} an object with keys and values.
 */
function parseOneEncoded(t) {
  var launch = {};

  var lines = t.split("\n");
  while (lines.length) {
    var key = lines.shift();
    var value;
    if (key === "action") {
      value = lines.join("\n");
      lines = [];
    } else {
      value = lines.shift();
    }
    launch[key] = value;
  }

  return launch;
}

/**
 * This complicated-looking function takes a (XML) string representation of a
 * Windows alert (toast notification), parses it into XML, extracts and further
 * parses internal data, and returns a simplified XML representation together
 * with the parsed internals.
 *
 * Doing this lets us compare JSON objects rather than stringified-JSON further
 * encoded as XML strings, which have lots of slashes and `"` characters to
 * contend with.
 *
 * @param {string} s XML string for Windows alert.

 * @returns {Array} a pair of a simplified XML string and an object with
 *                  `launch` and `actions` keys.
 */
function parseLaunchAndActions(s) {
  var document = new DOMParser().parseFromString(s, "text/xml");
  var root = document.documentElement;

  var launchString = root.getAttribute("launch");
  root.setAttribute("launch", "launch");
  var launch = parseOneEncoded(launchString);

  // `actions` is keyed by "content" attribute.
  let actions = {};
  for (var actionElement of root.querySelectorAll("action")) {
    // `activationType="system"` is special.  Leave them alone.
    let systemActivationType =
      actionElement.getAttribute("activationType") === "system";

    let action = {};
    let names = [...actionElement.attributes].map(attribute => attribute.name);

    for (var name of names) {
      let value = actionElement.getAttribute(name);

      // Here is where we parse stringified-JSON to simplify comparisons.
      if (value.startsWith("{")) {
        value = JSON.parse(value);
        if ("opaqueRelaunchData" in value) {
          value.opaqueRelaunchData = JSON.parse(value.opaqueRelaunchData);
        }
      }

      if (name == "arguments" && !systemActivationType) {
        action[name] = parseOneEncoded(value);
      } else {
        action[name] = value;
      }

      if (name != "content" && !systemActivationType) {
        actionElement.removeAttribute(name);
      }
    }

    let actionName = actionElement.getAttribute("content");
    actions[actionName] = action;
  }

  return [new XMLSerializer().serializeToString(document), { launch, actions }];
}

function escape(s) {
  return s
    .replace(/&/g, "&")
    .replace(/"/g, """)
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/\n/g, "&#xA;");
}

function unescape(s) {
  return s
    .replace(/&amp;/g, "&")
    .replace(/&quot;/g, '"')
    .replace(/&lt;/g, "<")
    .replace(/&gt;/g, ">")
    .replace(/&#xA;/g, "\n");
}

function testAlert(when, { serverEnabled, profD, isBackgroundTaskMode } = {}) {
  let argumentString = action => {
    // &#xA; is "\n".
    let s = ``;
    if (serverEnabled) {
      s += `program&#xA;${AppConstants.MOZ_APP_NAME}`;
    } else {
      s += `invalid key&#xA;invalid value`;
    }
    if (serverEnabled && profD) {
      s += `&#xA;profile&#xA;${profD.path}`;
    }
    if (serverEnabled) {
      s += "&#xA;windowsTag&#xA;";
    }
    if (action) {
      s += `&#xA;action&#xA;${escape(JSON.stringify(action))}`;
    }

    return s;
  };

  let parsedArgumentString = action =>
    parseOneEncoded(unescape(argumentString(action)));

  let settingsAction = isBackgroundTaskMode
    ? ""
    : `<action content="Notification settings"/>`;

  let parsedSettingsAction = hostport => {
    if (isBackgroundTaskMode) {
      return [];
    }
    let content = "Notification settings";
    return [
      content,
      {
        content,
        arguments: parsedArgumentString(
          Object.assign(
            {
              action: "settings",
            },
            hostport && {
              launchUrl: hostport,
            }
          )
        ),
        placement: "contextmenu",
      },
    ];
  };

  let parsedSnoozeAction = hostport => {
    let content = `Disable notifications from ${hostport}`;
    return [
      content,
      {
        content,
        arguments: parsedArgumentString(
          Object.assign(
            {
              action: "snooze",
            },
            hostport && {
              launchUrl: hostport,
            }
          )
        ),
        placement: "contextmenu",
      },
    ];
  };

  let alertsService = Cc["@mozilla.org/system-alerts-service;1"]
    .getService(Ci.nsIAlertsService)
    .QueryInterface(Ci.nsIWindowsAlertsService);

  let name = "name";
  let title = "title";
  let text = "text";
  let imageURL = "file:///image.png";
  let actions = [
    { action: "action1", title: "title1", iconURL: "file:///iconURL1.png" },
    { action: "action2", title: "title2", iconURL: "file:///iconURL2.png" },
  ];
  let opaqueRelaunchData = { foo: 1, bar: "two" };

  let alert = makeAlert({ name, title, text });
  let expected = `<toast launch="launch"><visual><binding template="ToastText03"><text id="1">title</text><text id="2">text</text></binding></visual><actions>${settingsAction}</actions></toast>`;
  Assert.deepEqual(
    [
      expected.replace("<actions></actions>", "<actions/>"),
      {
        launch: parsedArgumentString({ action: "" }),
        actions: Object.fromEntries(
          [parsedSettingsAction()].filter(x => x.length)
        ),
      },
    ],
    parseLaunchAndActions(alertsService.getXmlStringForWindowsAlert(alert)),
    when
  );

  alert = makeAlert({ name, title, text, imageURL });
  expected = `<toast launch="launch"><visual><binding template="ToastImageAndText03"><image id="1" src="file:///image.png"/><text id="1">title</text><text id="2">text</text></binding></visual><actions>${settingsAction}</actions></toast>`;
  Assert.deepEqual(
    [
      expected.replace("<actions></actions>", "<actions/>"),
      {
        launch: parsedArgumentString({ action: "" }),
        actions: Object.fromEntries(
          [parsedSettingsAction()].filter(x => x.length)
        ),
      },
    ],
    parseLaunchAndActions(alertsService.getXmlStringForWindowsAlert(alert)),
    when
  );

  alert = makeAlert({ name, title, text, imageURL, requireInteraction: true });
  expected = `<toast scenario="reminder" launch="launch"><visual><binding template="ToastImageAndText03"><image id="1" src="file:///image.png"/><text id="1">title</text><text id="2">text</text></binding></visual><actions>${settingsAction}<action content="Dismiss" arguments="dismiss" activationType="system"/></actions></toast>`;
  Assert.deepEqual(
    [
      expected.replace("<actions></actions>", "<actions/>"),
      {
        launch: parsedArgumentString({ action: "" }),
        actions: Object.fromEntries(
          [
            parsedSettingsAction(),
            [
              "Dismiss",
              {
                content: "Dismiss",
                arguments: "dismiss",
                activationType: "system",
              },
            ],
          ].filter(x => x.length)
        ),
      },
    ],
    parseLaunchAndActions(alertsService.getXmlStringForWindowsAlert(alert)),
    when
  );

  alert = makeAlert({ name, title, text, imageURL, actions });
  expected = `<toast launch="launch"><visual><binding template="ToastImageAndText03"><image id="1" src="file:///image.png"/><text id="1">title</text><text id="2">text</text></binding></visual><actions>${settingsAction}<action content="title1"/><action content="title2"/></actions></toast>`;
  Assert.deepEqual(
    [
      expected.replace("<actions></actions>", "<actions/>"),
      {
        launch: parsedArgumentString({ action: "" }),
        actions: Object.fromEntries(
          [
            parsedSettingsAction(),
            [
              "title1",
              {
                content: "title1",
                arguments: parsedArgumentString({ action: "action1" }),
              },
            ],
            [
              "title2",
              {
                content: "title2",
                arguments: parsedArgumentString({ action: "action2" }),
              },
            ],
          ].filter(x => x.length)
        ),
      },
    ],
    parseLaunchAndActions(alertsService.getXmlStringForWindowsAlert(alert)),
    when
  );

  // Chrome privileged alerts can use `windowsSystemActivationType`.
  let systemActions = [
    {
      action: "dismiss",
      title: "dismissTitle",
      windowsSystemActivationType: true,
    },
    {
      action: "snooze",
      title: "snoozeTitle",
      windowsSystemActivationType: true,
    },
  ];
  let systemPrincipal = Services.scriptSecurityManager.getSystemPrincipal();
  alert = makeAlert({
    name,
    title,
    text,
    imageURL,
    principal: systemPrincipal,
    actions: systemActions,
  });
  let parsedSettingsActionWithPrivilegedName = isBackgroundTaskMode
    ? []
    : [
        "Notification settings",
        {
          content: "Notification settings",
          arguments: parsedArgumentString({
            action: "settings",
            privilegedName: name,
          }),
          placement: "contextmenu",
        },
      ];

  expected = `<toast launch="launch"><visual><binding template="ToastGeneric"><image id="1" src="file:///image.png"/><text id="1">title</text><text id="2">text</text></binding></visual><actions>${settingsAction}<action content="dismissTitle" arguments="dismiss" activationType="system"/><action content="snoozeTitle" arguments="snooze" activationType="system"/></actions></toast>`;
  Assert.deepEqual(
    [
      expected.replace("<actions></actions>", "<actions/>"),
      {
        launch: parsedArgumentString({ action: "", privilegedName: name }),
        actions: Object.fromEntries(
          [
            parsedSettingsActionWithPrivilegedName,
            [
              "dismissTitle",
              {
                content: "dismissTitle",
                arguments: "dismiss",
                activationType: "system",
              },
            ],
            [
              "snoozeTitle",
              {
                content: "snoozeTitle",
                arguments: "snooze",
                activationType: "system",
              },
            ],
          ].filter(x => x.length)
        ),
      },
    ],
    parseLaunchAndActions(alertsService.getXmlStringForWindowsAlert(alert)),
    when
  );

  // But content unprivileged alerts can't use `windowsSystemActivationType`.
  let launchUrl = "https://example.com/foo/bar.html";
  const principaluri = Services.io.newURI(launchUrl);
  const principal = Services.scriptSecurityManager.createContentPrincipal(
    principaluri,
    {}
  );

  alert = makeAlert({
    name,
    title,
    text,
    imageURL,
    actions: systemActions,
    principal,
  });
  expected = `<toast launch="launch"><visual><binding template="ToastImageAndText04"><image id="1" src="file:///image.png"/><text id="1">title</text><text id="2">text</text><text id="3" placement="attribution">via example.com</text></binding></visual><actions><action content="Disable notifications from example.com"/>${settingsAction}<action content="dismissTitle"/><action content="snoozeTitle"/></actions></toast>`;
  Assert.deepEqual(
    [
      expected.replace("<actions></actions>", "<actions/>"),
      {
        launch: parsedArgumentString({
          action: "",
          launchUrl: principaluri.hostPort,
        }),
        actions: Object.fromEntries(
          [
            parsedSnoozeAction(principaluri.hostPort),
            parsedSettingsAction(principaluri.hostPort),
            [
              "dismissTitle",
              {
                content: "dismissTitle",
                arguments: parsedArgumentString({
                  action: "dismiss",
                  launchUrl: principaluri.hostPort,
                }),
              },
            ],
            [
              "snoozeTitle",
              {
                content: "snoozeTitle",
                arguments: parsedArgumentString({
                  action: "snooze",
                  launchUrl: principaluri.hostPort,
                }),
              },
            ],
          ].filter(x => x.length)
        ),
      },
    ],
    parseLaunchAndActions(alertsService.getXmlStringForWindowsAlert(alert)),
    when
  );

  // Chrome privileged alerts can set `opaqueRelaunchData`.
  alert = makeAlert({
    name,
    title,
    text,
    imageURL,
    principal: systemPrincipal,
    opaqueRelaunchData: JSON.stringify(opaqueRelaunchData),
  });
  expected = `<toast launch="launch"><visual><binding template="ToastGeneric"><image id="1" src="file:///image.png"/><text id="1">title</text><text id="2">text</text></binding></visual><actions>${settingsAction}</actions></toast>`;
  Assert.deepEqual(
    [
      expected.replace("<actions></actions>", "<actions/>"),
      {
        launch: parsedArgumentString({
          action: "",
          opaqueRelaunchData: JSON.stringify(opaqueRelaunchData),
          privilegedName: name,
        }),
        actions: Object.fromEntries(
          [parsedSettingsActionWithPrivilegedName].filter(x => x.length)
        ),
      },
    ],
    parseLaunchAndActions(alertsService.getXmlStringForWindowsAlert(alert)),
    when
  );

  // But content unprivileged alerts can't set `opaqueRelaunchData`.
  alert = makeAlert({
    name,
    title,
    text,
    imageURL,
    principal,
    opaqueRelaunchData: JSON.stringify(opaqueRelaunchData),
  });
  expected = `<toast launch="launch"><visual><binding template="ToastImageAndText04"><image id="1" src="file:///image.png"/><text id="1">title</text><text id="2">text</text><text id="3" placement="attribution">via example.com</text></binding></visual><actions><action content="Disable notifications from example.com"/>${settingsAction}</actions></toast>`;
  Assert.deepEqual(
    [
      expected.replace("<actions></actions>", "<actions/>"),
      {
        launch: parsedArgumentString({
          action: "",
          launchUrl: principaluri.hostPort,
        }),
        actions: Object.fromEntries(
          [
            parsedSnoozeAction(principaluri.hostPort),
            parsedSettingsAction(principaluri.hostPort),
          ].filter(x => x.length)
        ),
      },
    ],
    parseLaunchAndActions(alertsService.getXmlStringForWindowsAlert(alert)),
    when
  );

  // Chrome privileged alerts can set action-specific relaunch parameters.
  let systemRelaunchActions = [
    {
      action: "action1",
      title: "title1",
      opaqueRelaunchData: JSON.stringify({ json: "data1" }),
    },
    {
      action: "action2",
      title: "title2",
      opaqueRelaunchData: JSON.stringify({ json: "data2" }),
    },
  ];
  systemPrincipal = Services.scriptSecurityManager.getSystemPrincipal();
  alert = makeAlert({
    name,
    title,
    text,
    imageURL,
    principal: systemPrincipal,
    actions: systemRelaunchActions,
  });
  expected = `<toast launch="launch"><visual><binding template="ToastGeneric"><image id="1" src="file:///image.png"/><text id="1">title</text><text id="2">text</text></binding></visual><actions>${settingsAction}<action content="title1"/><action content="title2"/></actions></toast>`;
  Assert.deepEqual(
    [
      expected.replace("<actions></actions>", "<actions/>"),
      {
        launch: parsedArgumentString({ action: "", privilegedName: name }),
        actions: Object.fromEntries(
          [
            parsedSettingsActionWithPrivilegedName,
            [
              "title1",
              {
                content: "title1",
                arguments: parsedArgumentString(
                  {
                    action: "action1",
                    opaqueRelaunchData: JSON.stringify({ json: "data1" }),
                    privilegedName: name,
                  },
                  null,
                  name
                ),
              },
            ],

            [
              "title2",
              {
                content: "title2",
                arguments: parsedArgumentString(
                  {
                    action: "action2",
                    opaqueRelaunchData: JSON.stringify({ json: "data2" }),
                    privilegedName: name,
                  },
                  null,
                  name
                ),
              },
            ],
          ].filter(x => x.length)
        ),
      },
    ],
    parseLaunchAndActions(alertsService.getXmlStringForWindowsAlert(alert)),
    when
  );
}

add_task(async () => {
  Services.prefs.deleteBranch(
    "alerts.useSystemBackend.windows.notificationserver.enabled"
  );
  testAlert("when notification server pref is unset", {
    profD: gProfD,
  });

  Services.prefs.setBoolPref(
    "alerts.useSystemBackend.windows.notificationserver.enabled",
    false
  );
  testAlert("when notification server pref is false", { profD: gProfD });

  Services.prefs.setBoolPref(
    "alerts.useSystemBackend.windows.notificationserver.enabled",
    true
  );
  testAlert("when notification server pref is true", {
    serverEnabled: true,
    profD: gProfD,
  });
});

let condition = {
  skip_if: () => !AppConstants.MOZ_BACKGROUNDTASKS,
};

add_task(condition, async () => {
  const bts = Cc["@mozilla.org/backgroundtasks;1"]?.getService(
    Ci.nsIBackgroundTasks
  );

  // Pretend that this is a background task.
  bts.overrideBackgroundTaskNameForTesting("taskname");

  Services.prefs.setBoolPref(
    "alerts.useSystemBackend.windows.notificationserver.enabled",
    true
  );
  testAlert(
    "when notification server pref is true in background task, no default profile",
    { serverEnabled: true, isBackgroundTaskMode: true }
  );

  let profileService = Cc["@mozilla.org/toolkit/profile-service;1"].getService(
    Ci.nsIToolkitProfileService
  );

  let profilePath = do_get_profile();
  profilePath.append(`test_windows_alert_service`);
  let profile = profileService.createUniqueProfile(
    profilePath,
    "test_windows_alert_service"
  );

  profileService.defaultProfile = profile;

  testAlert(
    "when notification server pref is true in background task, default profile",
    { serverEnabled: true, isBackgroundTaskMode: true, profD: profilePath }
  );

  // No longer a background task,
  bts.overrideBackgroundTaskNameForTesting("");
});