DXR is a code search and navigation tool aimed at making sense of large projects. It supports full-text and regex searches as well as structural queries.

Header

Mercurial (35bba5f95485)

VCS Links

Line Code
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 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "mozilla/dom/Notification.h"

#include "mozilla/BasePrincipal.h"
#include "mozilla/Components.h"
#include "mozilla/Encoding.h"
#include "mozilla/EventStateManager.h"
#include "mozilla/JSONWriter.h"
#include "mozilla/Move.h"
#include "mozilla/OwningNonNull.h"
#include "mozilla/Preferences.h"
#include "mozilla/Services.h"
#include "mozilla/StaticPrefs_dom.h"
#include "mozilla/Telemetry.h"
#include "mozilla/Unused.h"

#include "mozilla/dom/AppNotificationServiceOptionsBinding.h"
#include "mozilla/dom/BindingUtils.h"
#include "mozilla/dom/ContentChild.h"
#include "mozilla/dom/NotificationEvent.h"
#include "mozilla/dom/PermissionMessageUtils.h"
#include "mozilla/dom/Promise.h"
#include "mozilla/dom/PromiseWorkerProxy.h"
#include "mozilla/dom/ServiceWorkerGlobalScopeBinding.h"
#include "mozilla/dom/ServiceWorkerManager.h"
#include "mozilla/dom/ServiceWorkerUtils.h"
#include "mozilla/dom/WorkerPrivate.h"
#include "mozilla/dom/WorkerRunnable.h"
#include "mozilla/dom/WorkerScope.h"

#include "nsAlertsUtils.h"
#include "nsComponentManagerUtils.h"
#include "nsContentPermissionHelper.h"
#include "nsContentUtils.h"
#include "nsCRTGlue.h"
#include "nsDOMJSUtils.h"
#include "nsFocusManager.h"
#include "nsGlobalWindow.h"
#include "nsIAlertsService.h"
#include "nsIContentPermissionPrompt.h"
#include "mozilla/dom/Document.h"
#include "nsILoadContext.h"
#include "nsINotificationStorage.h"
#include "nsIPermissionManager.h"
#include "nsIPermission.h"
#include "nsIPushService.h"
#include "nsIScriptError.h"
#include "nsIServiceWorkerManager.h"
#include "nsISimpleEnumerator.h"
#include "nsIUUIDGenerator.h"
#include "nsNetUtil.h"
#include "nsProxyRelease.h"
#include "nsServiceManagerUtils.h"
#include "nsStructuredCloneContainer.h"
#include "nsThreadUtils.h"
#include "nsXULAppAPI.h"

namespace mozilla {
namespace dom {

struct NotificationStrings {
  const nsString mID;
  const nsString mTitle;
  const nsString mDir;
  const nsString mLang;
  const nsString mBody;
  const nsString mTag;
  const nsString mIcon;
  const nsString mData;
  const nsString mBehavior;
  const nsString mServiceWorkerRegistrationScope;
};

class ScopeCheckingGetCallback : public nsINotificationStorageCallback {
  const nsString mScope;

 public:
  explicit ScopeCheckingGetCallback(const nsAString& aScope) : mScope(aScope) {}

  NS_IMETHOD Handle(const nsAString& aID, const nsAString& aTitle,
                    const nsAString& aDir, const nsAString& aLang,
                    const nsAString& aBody, const nsAString& aTag,
                    const nsAString& aIcon, const nsAString& aData,
                    const nsAString& aBehavior,
                    const nsAString& aServiceWorkerRegistrationScope) final {
    AssertIsOnMainThread();
    MOZ_ASSERT(!aID.IsEmpty());

    // Skip scopes that don't match when called from getNotifications().
    if (!mScope.IsEmpty() && !mScope.Equals(aServiceWorkerRegistrationScope)) {
      return NS_OK;
    }

    NotificationStrings strings = {
        nsString(aID),       nsString(aTitle),
        nsString(aDir),      nsString(aLang),
        nsString(aBody),     nsString(aTag),
        nsString(aIcon),     nsString(aData),
        nsString(aBehavior), nsString(aServiceWorkerRegistrationScope),
    };

    mStrings.AppendElement(std::move(strings));
    return NS_OK;
  }

  NS_IMETHOD Done() override = 0;

 protected:
  virtual ~ScopeCheckingGetCallback() {}

  nsTArray<NotificationStrings> mStrings;
};

class NotificationStorageCallback final : public ScopeCheckingGetCallback {
 public:
  NS_DECL_CYCLE_COLLECTING_ISUPPORTS
  NS_DECL_CYCLE_COLLECTION_CLASS(NotificationStorageCallback)

  NotificationStorageCallback(nsIGlobalObject* aWindow, const nsAString& aScope,
                              Promise* aPromise)
      : ScopeCheckingGetCallback(aScope), mWindow(aWindow), mPromise(aPromise) {
    AssertIsOnMainThread();
    MOZ_ASSERT(aWindow);
    MOZ_ASSERT(aPromise);
  }

  NS_IMETHOD Done() final {
    ErrorResult result;
    AutoTArray<RefPtr<Notification>, 5> notifications;

    for (uint32_t i = 0; i < mStrings.Length(); ++i) {
      RefPtr<Notification> n = Notification::ConstructFromFields(
          mWindow, mStrings[i].mID, mStrings[i].mTitle, mStrings[i].mDir,
          mStrings[i].mLang, mStrings[i].mBody, mStrings[i].mTag,
          mStrings[i].mIcon, mStrings[i].mData,
          /* mStrings[i].mBehavior, not
           * supported */
          mStrings[i].mServiceWorkerRegistrationScope, result);

      n->SetStoredState(true);
      Unused << NS_WARN_IF(result.Failed());
      if (!result.Failed()) {
        notifications.AppendElement(n.forget());
      }
    }

    mPromise->MaybeResolve(notifications);
    return NS_OK;
  }

 private:
  virtual ~NotificationStorageCallback() {}

  nsCOMPtr<nsIGlobalObject> mWindow;
  RefPtr<Promise> mPromise;
  const nsString mScope;
};

NS_IMPL_CYCLE_COLLECTING_ADDREF(NotificationStorageCallback)
NS_IMPL_CYCLE_COLLECTING_RELEASE(NotificationStorageCallback)
NS_IMPL_CYCLE_COLLECTION(NotificationStorageCallback, mWindow, mPromise);

NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(NotificationStorageCallback)
  NS_INTERFACE_MAP_ENTRY(nsINotificationStorageCallback)
  NS_INTERFACE_MAP_ENTRY(nsISupports)
NS_INTERFACE_MAP_END

class NotificationGetRunnable final : public Runnable {
  const nsString mOrigin;
  const nsString mTag;
  nsCOMPtr<nsINotificationStorageCallback> mCallback;

 public:
  NotificationGetRunnable(const nsAString& aOrigin, const nsAString& aTag,
                          nsINotificationStorageCallback* aCallback)
      : Runnable("NotificationGetRunnable"),
        mOrigin(aOrigin),
        mTag(aTag),
        mCallback(aCallback) {}

  NS_IMETHOD
  Run() override {
    nsresult rv;
    nsCOMPtr<nsINotificationStorage> notificationStorage =
        do_GetService(NS_NOTIFICATION_STORAGE_CONTRACTID, &rv);
    if (NS_WARN_IF(NS_FAILED(rv))) {
      return rv;
    }

    rv = notificationStorage->Get(mOrigin, mTag, mCallback);
    // XXXnsm Is it guaranteed mCallback will be called in case of failure?
    Unused << NS_WARN_IF(NS_FAILED(rv));
    return rv;
  }
};

class NotificationPermissionRequest : public ContentPermissionRequestBase,
                                      public nsIRunnable,
                                      public nsINamed {
 public:
  NS_DECL_NSIRUNNABLE
  NS_DECL_ISUPPORTS_INHERITED
  NS_DECL_CYCLE_COLLECTION_CLASS_INHERITED(NotificationPermissionRequest,
                                           ContentPermissionRequestBase)

  // nsIContentPermissionRequest
  NS_IMETHOD Cancel(void) override;
  NS_IMETHOD Allow(JS::HandleValue choices) override;

  NotificationPermissionRequest(nsIPrincipal* aPrincipal,
                                nsPIDOMWindowInner* aWindow, Promise* aPromise,
                                NotificationPermissionCallback* aCallback)
      : ContentPermissionRequestBase(
            aPrincipal, aWindow, NS_LITERAL_CSTRING("notification"),
            NS_LITERAL_CSTRING("desktop-notification")),
        mPermission(NotificationPermission::Default),
        mPromise(aPromise),
        mCallback(aCallback) {
    MOZ_ASSERT(aPromise);
  }

  NS_IMETHOD GetName(nsACString& aName) override {
    aName.AssignLiteral("NotificationPermissionRequest");
    return NS_OK;
  }

 protected:
  ~NotificationPermissionRequest() = default;

  MOZ_CAN_RUN_SCRIPT nsresult ResolvePromise();
  nsresult DispatchResolvePromise();
  NotificationPermission mPermission;
  RefPtr<Promise> mPromise;
  RefPtr<NotificationPermissionCallback> mCallback;
};

namespace {
class ReleaseNotificationControlRunnable final
    : public MainThreadWorkerControlRunnable {
  Notification* mNotification;

 public:
  explicit ReleaseNotificationControlRunnable(Notification* aNotification)
      : MainThreadWorkerControlRunnable(aNotification->mWorkerPrivate),
        mNotification(aNotification) {}

  bool WorkerRun(JSContext* aCx, WorkerPrivate* aWorkerPrivate) override {
    mNotification->ReleaseObject();
    return true;
  }
};

class GetPermissionRunnable final : public WorkerMainThreadRunnable {
  NotificationPermission mPermission;

 public:
  explicit GetPermissionRunnable(WorkerPrivate* aWorker)
      : WorkerMainThreadRunnable(
            aWorker, NS_LITERAL_CSTRING("Notification :: Get Permission")),
        mPermission(NotificationPermission::Denied) {}

  bool MainThreadRun() override {
    ErrorResult result;
    mPermission = Notification::GetPermissionInternal(
        mWorkerPrivate->GetPrincipal(), result);
    return true;
  }

  NotificationPermission GetPermission() { return mPermission; }
};

class FocusWindowRunnable final : public Runnable {
  nsMainThreadPtrHandle<nsPIDOMWindowInner> mWindow;

 public:
  explicit FocusWindowRunnable(
      const nsMainThreadPtrHandle<nsPIDOMWindowInner>& aWindow)
      : Runnable("FocusWindowRunnable"), mWindow(aWindow) {}

  NS_IMETHOD
  Run() override {
    AssertIsOnMainThread();
    if (!mWindow->IsCurrentInnerWindow()) {
      // Window has been closed, this observer is not valid anymore
      return NS_OK;
    }

    nsFocusManager::FocusWindow(mWindow->GetOuterWindow());
    return NS_OK;
  }
};

nsresult CheckScope(nsIPrincipal* aPrincipal, const nsACString& aScope,
                    uint64_t aWindowID) {
  AssertIsOnMainThread();
  MOZ_ASSERT(aPrincipal);

  nsCOMPtr<nsIURI> scopeURI;
  nsresult rv = NS_NewURI(getter_AddRefs(scopeURI), aScope);
  if (NS_WARN_IF(NS_FAILED(rv))) {
    return rv;
  }

  return aPrincipal->CheckMayLoadWithReporting(
      scopeURI,
      /* allowIfInheritsPrincipal = */ false, aWindowID);
}
}  // anonymous namespace

// Subclass that can be directly dispatched to child workers from the main
// thread.
class NotificationWorkerRunnable : public MainThreadWorkerRunnable {
 protected:
  explicit NotificationWorkerRunnable(WorkerPrivate* aWorkerPrivate)
      : MainThreadWorkerRunnable(aWorkerPrivate) {}

  bool WorkerRun(JSContext* aCx, WorkerPrivate* aWorkerPrivate) override {
    aWorkerPrivate->AssertIsOnWorkerThread();
    aWorkerPrivate->ModifyBusyCountFromWorker(true);
    WorkerRunInternal(aWorkerPrivate);
    return true;
  }

  void PostRun(JSContext* aCx, WorkerPrivate* aWorkerPrivate,
               bool aRunResult) override {
    aWorkerPrivate->ModifyBusyCountFromWorker(false);
  }

  virtual void WorkerRunInternal(WorkerPrivate* aWorkerPrivate) = 0;
};

// Overrides dispatch and run handlers so we can directly dispatch from main
// thread to child workers.
class NotificationEventWorkerRunnable final
    : public NotificationWorkerRunnable {
  Notification* mNotification;
  const nsString mEventName;

 public:
  NotificationEventWorkerRunnable(Notification* aNotification,
                                  const nsString& aEventName)
      : NotificationWorkerRunnable(aNotification->mWorkerPrivate),
        mNotification(aNotification),
        mEventName(aEventName) {}

  void WorkerRunInternal(WorkerPrivate* aWorkerPrivate) override {
    mNotification->DispatchTrustedEvent(mEventName);
  }
};

class ReleaseNotificationRunnable final : public NotificationWorkerRunnable {
  Notification* mNotification;

 public:
  explicit ReleaseNotificationRunnable(Notification* aNotification)
      : NotificationWorkerRunnable(aNotification->mWorkerPrivate),
        mNotification(aNotification) {}

  void WorkerRunInternal(WorkerPrivate* aWorkerPrivate) override {
    mNotification->ReleaseObject();
  }

  nsresult Cancel() override {
    mNotification->ReleaseObject();
    return NS_OK;
  }
};

// Create one whenever you require ownership of the notification. Use with
// UniquePtr<>. See Notification.h for details.
class NotificationRef final {
  friend class WorkerNotificationObserver;

 private:
  Notification* mNotification;
  bool mInited;

  // Only useful for workers.
  void Forget() { mNotification = nullptr; }

 public:
  explicit NotificationRef(Notification* aNotification)
      : mNotification(aNotification) {
    MOZ_ASSERT(mNotification);
    if (mNotification->mWorkerPrivate) {
      mNotification->mWorkerPrivate->AssertIsOnWorkerThread();
    } else {
      AssertIsOnMainThread();
    }

    mInited = mNotification->AddRefObject();
  }

  // This is only required because Gecko runs script in a worker's onclose
  // handler (non-standard, Bug 790919) where calls to HoldWorker() will
  // fail. Due to non-standardness and added complications if we decide to
  // support this, attempts to create a Notification in onclose just throw
  // exceptions.
  bool Initialized() { return mInited; }

  ~NotificationRef() {
    if (Initialized() && mNotification) {
      Notification* notification = mNotification;
      mNotification = nullptr;
      if (notification->mWorkerPrivate && NS_IsMainThread()) {
        // Try to pass ownership back to the worker. If the dispatch succeeds we
        // are guaranteed this runnable will run, and that it will run after
        // queued event runnables, so event runnables will have a safe pointer
        // to the Notification.
        //
        // If the dispatch fails, the worker isn't running anymore and the event
        // runnables have already run or been canceled. We can use a control
        // runnable to release the reference.
        RefPtr<ReleaseNotificationRunnable> r =
            new ReleaseNotificationRunnable(notification);

        if (!r->Dispatch()) {
          RefPtr<ReleaseNotificationControlRunnable> r =
              new ReleaseNotificationControlRunnable(notification);
          MOZ_ALWAYS_TRUE(r->Dispatch());
        }
      } else {
        notification->AssertIsOnTargetThread();
        notification->ReleaseObject();
      }
    }
  }

  // XXXnsm, is it worth having some sort of WeakPtr like wrapper instead of
  // a rawptr that the NotificationRef can invalidate?
  Notification* GetNotification() {
    MOZ_ASSERT(Initialized());
    return mNotification;
  }
};

class NotificationTask : public Runnable {
 public:
  enum NotificationAction { eShow, eClose };

  NotificationTask(const char* aName, UniquePtr<NotificationRef> aRef,
                   NotificationAction aAction)
      : Runnable(aName), mNotificationRef(std::move(aRef)), mAction(aAction) {}

  NS_IMETHOD
  Run() override;

 protected:
  virtual ~NotificationTask() {}

  UniquePtr<NotificationRef> mNotificationRef;
  NotificationAction mAction;
};

uint32_t Notification::sCount = 0;

NS_IMPL_CYCLE_COLLECTION_INHERITED(NotificationPermissionRequest,
                                   ContentPermissionRequestBase, mCallback)
NS_IMPL_ADDREF_INHERITED(NotificationPermissionRequest,
                         ContentPermissionRequestBase)
NS_IMPL_RELEASE_INHERITED(NotificationPermissionRequest,
                          ContentPermissionRequestBase)

NS_IMPL_QUERY_INTERFACE_CYCLE_COLLECTION_INHERITED(
    NotificationPermissionRequest, ContentPermissionRequestBase, nsIRunnable,
    nsINamed)

NS_IMETHODIMP
NotificationPermissionRequest::Run() {
  bool isSystem = mPrincipal->IsSystemPrincipal();
  bool blocked = false;
  if (isSystem) {
    mPermission = NotificationPermission::Granted;
  } else {
    // File are automatically granted permission.

    if (mPrincipal->SchemeIs("file")) {
      mPermission = NotificationPermission::Granted;
    } else if (!StaticPrefs::dom_webnotifications_allowinsecure() &&
               !mWindow->IsSecureContext()) {
      mPermission = NotificationPermission::Denied;
      blocked = true;
      nsCOMPtr<Document> doc = mWindow->GetExtantDoc();
      if (doc) {
        nsContentUtils::ReportToConsole(
            nsIScriptError::errorFlag, NS_LITERAL_CSTRING("DOM"), doc,
            nsContentUtils::eDOM_PROPERTIES,
            "NotificationsInsecureRequestIsForbidden");
      }
    }
  }

  // We can't call ShowPrompt() directly here since our logic for determining
  // whether to display a prompt depends on the checks above as well as the
  // result of CheckPromptPrefs().  So we have to manually check the prompt
  // prefs and decide what to do based on that.
  PromptResult pr = CheckPromptPrefs();
  switch (pr) {
    case PromptResult::Granted:
      mPermission = NotificationPermission::Granted;
      break;
    case PromptResult::Denied:
      mPermission = NotificationPermission::Denied;
      break;
    default:
      // ignore
      break;
  }

  if (!mIsHandlingUserInput &&
      !StaticPrefs::dom_webnotifications_requireuserinteraction()) {
    nsCOMPtr<Document> doc = mWindow->GetExtantDoc();
    if (doc) {
      doc->WarnOnceAbout(Document::eNotificationsRequireUserGestureDeprecation);
    }
  }

  // Check this after checking the prompt prefs to make sure this pref overrides
  // those.  We rely on this for testing purposes.
  if (!isSystem && !blocked &&
      !StaticPrefs::dom_webnotifications_allowcrossoriginiframe() &&
      !mPrincipal->Subsumes(mTopLevelPrincipal)) {
    mPermission = NotificationPermission::Denied;
    blocked = true;
    nsCOMPtr<Document> doc = mWindow->GetExtantDoc();
    if (doc) {
      nsContentUtils::ReportToConsole(
          nsIScriptError::errorFlag, NS_LITERAL_CSTRING("DOM"), doc,
          nsContentUtils::eDOM_PROPERTIES,
          "NotificationsCrossOriginIframeRequestIsForbidden");
    }
  }

  if (mPermission != NotificationPermission::Default) {
    return DispatchResolvePromise();
  }

  return nsContentPermissionUtils::AskPermission(this, mWindow);
}

NS_IMETHODIMP
NotificationPermissionRequest::Cancel() {
  // `Cancel` is called if the user denied permission or dismissed the
  // permission request. To distinguish between the two, we set the
  // permission to "default" and query the permission manager in
  // `ResolvePromise`.
  mPermission = NotificationPermission::Default;
  return DispatchResolvePromise();
}

NS_IMETHODIMP
NotificationPermissionRequest::Allow(JS::HandleValue aChoices) {
  MOZ_ASSERT(aChoices.isUndefined());

  mPermission = NotificationPermission::Granted;
  return DispatchResolvePromise();
}

inline nsresult NotificationPermissionRequest::DispatchResolvePromise() {
  nsCOMPtr<nsIRunnable> resolver =
      NewRunnableMethod("NotificationPermissionRequest::DispatchResolvePromise",
                        this, &NotificationPermissionRequest::ResolvePromise);
  if (nsIEventTarget* target = mWindow->EventTargetFor(TaskCategory::Other)) {
    return target->Dispatch(resolver.forget(), nsIEventTarget::DISPATCH_NORMAL);
  }
  return NS_ERROR_FAILURE;
}

nsresult NotificationPermissionRequest::ResolvePromise() {
  nsresult rv = NS_OK;
  // This will still be "default" if the user dismissed the doorhanger,
  // or "denied" otherwise.
  if (mPermission == NotificationPermission::Default) {
    // When the front-end has decided to deny the permission request
    // automatically and we are not handling user input, then log a
    // warning in the current document that this happened because
    // Notifications require a user gesture.
    if (!mIsHandlingUserInput &&
        StaticPrefs::dom_webnotifications_requireuserinteraction()) {
      nsCOMPtr<Document> doc = mWindow->GetExtantDoc();
      if (doc) {
        nsContentUtils::ReportToConsole(
            nsIScriptError::errorFlag, NS_LITERAL_CSTRING("DOM"), doc,
            nsContentUtils::eDOM_PROPERTIES, "NotificationsRequireUserGesture");
      }
    }

    mPermission = Notification::TestPermission(mPrincipal);
  }
  if (mCallback) {
    ErrorResult error;
    RefPtr<NotificationPermissionCallback> callback(mCallback);
    callback->Call(mPermission, error);
    rv = error.StealNSResult();
  }
  mPromise->MaybeResolve(mPermission);
  return rv;
}

// Observer that the alert service calls to do common tasks and/or dispatch to
// the specific observer for the context e.g. main thread, worker, or service
// worker.
class NotificationObserver final : public nsIObserver {
 public:
  nsCOMPtr<nsIObserver> mObserver;
  nsCOMPtr<nsIPrincipal> mPrincipal;
  bool mInPrivateBrowsing;
  NS_DECL_ISUPPORTS
  NS_DECL_NSIOBSERVER

  NotificationObserver(nsIObserver* aObserver, nsIPrincipal* aPrincipal,
                       bool aInPrivateBrowsing)
      : mObserver(aObserver),
        mPrincipal(aPrincipal),
        mInPrivateBrowsing(aInPrivateBrowsing) {
    AssertIsOnMainThread();
    MOZ_ASSERT(mObserver);
    MOZ_ASSERT(mPrincipal);
  }

 protected:
  virtual ~NotificationObserver() { AssertIsOnMainThread(); }

  nsresult AdjustPushQuota(const char* aTopic);
};

NS_IMPL_ISUPPORTS(NotificationObserver, nsIObserver)

class MainThreadNotificationObserver : public nsIObserver {
 public:
  UniquePtr<NotificationRef> mNotificationRef;
  NS_DECL_ISUPPORTS
  NS_DECL_NSIOBSERVER

  explicit MainThreadNotificationObserver(UniquePtr<NotificationRef> aRef)
      : mNotificationRef(std::move(aRef)) {
    AssertIsOnMainThread();
  }

 protected:
  virtual ~MainThreadNotificationObserver() { AssertIsOnMainThread(); }
};

NS_IMPL_ISUPPORTS(MainThreadNotificationObserver, nsIObserver)

NS_IMETHODIMP
NotificationTask::Run() {
  AssertIsOnMainThread();

  // Get a pointer to notification before the notification takes ownership of
  // the ref (it owns itself temporarily, with ShowInternal() and
  // CloseInternal() passing on the ownership appropriately.)
  Notification* notif = mNotificationRef->GetNotification();
  notif->mTempRef.swap(mNotificationRef);
  if (mAction == eShow) {
    notif->ShowInternal();
  } else if (mAction == eClose) {
    notif->CloseInternal();
  } else {
    MOZ_CRASH("Invalid action");
  }

  MOZ_ASSERT(!mNotificationRef);
  return NS_OK;
}

// static
bool Notification::PrefEnabled(JSContext* aCx, JSObject* aObj) {
  if (!NS_IsMainThread()) {
    WorkerPrivate* workerPrivate = GetWorkerPrivateFromContext(aCx);
    if (!workerPrivate) {
      return false;
    }

    if (workerPrivate->IsServiceWorker()) {
      return StaticPrefs::dom_webnotifications_serviceworker_enabled();
    }
  }

  return StaticPrefs::dom_webnotifications_enabled();
}

// static
bool Notification::IsGetEnabled(JSContext* aCx, JSObject* aObj) {
  return NS_IsMainThread();
}

Notification::Notification(nsIGlobalObject* aGlobal, const nsAString& aID,
                           const nsAString& aTitle, const nsAString& aBody,
                           NotificationDirection aDir, const nsAString& aLang,
                           const nsAString& aTag, const nsAString& aIconUrl,
                           bool aRequireInteraction,
                           const NotificationBehavior& aBehavior)
    : DOMEventTargetHelper(aGlobal),
      mWorkerPrivate(nullptr),
      mObserver(nullptr),
      mID(aID),
      mTitle(aTitle),
      mBody(aBody),
      mDir(aDir),
      mLang(aLang),
      mTag(aTag),
      mIconUrl(aIconUrl),
      mRequireInteraction(aRequireInteraction),
      mBehavior(aBehavior),
      mData(JS::NullValue()),
      mIsClosed(false),
      mIsStored(false),
      mTaskCount(0) {
  if (!NS_IsMainThread()) {
    mWorkerPrivate = GetCurrentThreadWorkerPrivate();
    MOZ_ASSERT(mWorkerPrivate);
  }
}

nsresult Notification::Init() {
  if (!mWorkerPrivate) {
    nsCOMPtr<nsIObserverService> obs = mozilla::services::GetObserverService();
    NS_ENSURE_TRUE(obs, NS_ERROR_FAILURE);

    nsresult rv = obs->AddObserver(this, DOM_WINDOW_DESTROYED_TOPIC, true);
    NS_ENSURE_SUCCESS(rv, rv);

    rv = obs->AddObserver(this, DOM_WINDOW_FROZEN_TOPIC, true);
    NS_ENSURE_SUCCESS(rv, rv);
  }

  return NS_OK;
}

void Notification::SetAlertName() {
  AssertIsOnMainThread();
  if (!mAlertName.IsEmpty()) {
    return;
  }

  nsAutoString alertName;
  nsresult rv = GetOrigin(GetPrincipal(), alertName);
  if (NS_WARN_IF(NS_FAILED(rv))) {
    return;
  }

  // Get the notification name that is unique per origin + tag/ID.
  // The name of the alert is of the form origin#tag/ID.
  alertName.Append('#');
  if (!mTag.IsEmpty()) {
    alertName.AppendLiteral("tag:");
    alertName.Append(mTag);
  } else {
    alertName.AppendLiteral("notag:");
    alertName.Append(mID);
  }

  mAlertName = alertName;
}

// May be called on any thread.
// static
already_AddRefed<Notification> Notification::Constructor(
    const GlobalObject& aGlobal, const nsAString& aTitle,
    const NotificationOptions& aOptions, ErrorResult& aRv) {
  // FIXME(nsm): If the sticky flag is set, throw an error.
  RefPtr<ServiceWorkerGlobalScope> scope;
  UNWRAP_OBJECT(ServiceWorkerGlobalScope, aGlobal.Get(), scope);
  if (scope) {
    aRv.ThrowTypeError(
        u"Notification constructor cannot be used in ServiceWorkerGlobalScope. "
        u"Use registration.showNotification() instead.");
    return nullptr;
  }

  nsCOMPtr<nsIGlobalObject> global = do_QueryInterface(aGlobal.GetAsSupports());
  RefPtr<Notification> notification = CreateAndShow(
      aGlobal.Context(), global, aTitle, aOptions, EmptyString(), aRv);
  if (NS_WARN_IF(aRv.Failed())) {
    return nullptr;
  }

  // This is be ok since we are on the worker thread where this function will
  // run to completion before the Notification has a chance to go away.
  return notification.forget();
}

// static
already_AddRefed<Notification> Notification::ConstructFromFields(
    nsIGlobalObject* aGlobal, const nsAString& aID, const nsAString& aTitle,
    const nsAString& aDir, const nsAString& aLang, const nsAString& aBody,
    const nsAString& aTag, const nsAString& aIcon, const nsAString& aData,
    const nsAString& aServiceWorkerRegistrationScope, ErrorResult& aRv) {
  MOZ_ASSERT(aGlobal);

  RootedDictionary<NotificationOptions> options(RootingCx());
  options.mDir = Notification::StringToDirection(nsString(aDir));
  options.mLang = aLang;
  options.mBody = aBody;
  options.mTag = aTag;
  options.mIcon = aIcon;
  RefPtr<Notification> notification =
      CreateInternal(aGlobal, aID, aTitle, options);

  notification->InitFromBase64(aData, aRv);
  if (NS_WARN_IF(aRv.Failed())) {
    return nullptr;
  }

  notification->SetScope(aServiceWorkerRegistrationScope);

  return notification.forget();
}

nsresult Notification::PersistNotification() {
  AssertIsOnMainThread();
  nsresult rv;
  nsCOMPtr<nsINotificationStorage> notificationStorage =
      do_GetService(NS_NOTIFICATION_STORAGE_CONTRACTID, &rv);
  if (NS_FAILED(rv)) {
    return rv;
  }

  nsString origin;
  rv = GetOrigin(GetPrincipal(), origin);
  if (NS_WARN_IF(NS_FAILED(rv))) {
    return rv;
  }

  nsString id;
  GetID(id);

  nsString alertName;
  GetAlertName(alertName);

  nsAutoString behavior;
  if (!mBehavior.ToJSON(behavior)) {
    return NS_ERROR_FAILURE;
  }

  rv = notificationStorage->Put(origin, id, mTitle, DirectionToString(mDir),
                                mLang, mBody, mTag, mIconUrl, alertName,
                                mDataAsBase64, behavior, mScope);

  if (NS_FAILED(rv)) {
    return rv;
  }

  SetStoredState(true);
  return NS_OK;
}

void Notification::UnpersistNotification() {
  AssertIsOnMainThread();
  if (IsStored()) {
    nsCOMPtr<nsINotificationStorage> notificationStorage =
        do_GetService(NS_NOTIFICATION_STORAGE_CONTRACTID);
    if (notificationStorage) {
      nsString origin;
      nsresult rv = GetOrigin(GetPrincipal(), origin);
      if (NS_SUCCEEDED(rv)) {
        notificationStorage->Delete(origin, mID);
      }
    }
    SetStoredState(false);
  }
}

already_AddRefed<Notification> Notification::CreateInternal(
    nsIGlobalObject* aGlobal, const nsAString& aID, const nsAString& aTitle,
    const NotificationOptions& aOptions) {
  nsresult rv;
  nsString id;
  if (!aID.IsEmpty()) {
    id = aID;
  } else {
    nsCOMPtr<nsIUUIDGenerator> uuidgen =
        do_GetService("@mozilla.org/uuid-generator;1");
    NS_ENSURE_TRUE(uuidgen, nullptr);
    nsID uuid;
    rv = uuidgen->GenerateUUIDInPlace(&uuid);
    NS_ENSURE_SUCCESS(rv, nullptr);

    char buffer[NSID_LENGTH];
    uuid.ToProvidedString(buffer);
    NS_ConvertASCIItoUTF16 convertedID(buffer);
    id = convertedID;
  }

  RefPtr<Notification> notification =
      new Notification(aGlobal, id, aTitle, aOptions.mBody, aOptions.mDir,
                       aOptions.mLang, aOptions.mTag, aOptions.mIcon,
                       aOptions.mRequireInteraction, aOptions.mMozbehavior);
  rv = notification->Init();
  NS_ENSURE_SUCCESS(rv, nullptr);
  return notification.forget();
}

Notification::~Notification() {
  mData.setUndefined();
  mozilla::DropJSObjects(this);
  AssertIsOnTargetThread();
  MOZ_ASSERT(!mWorkerRef);
  MOZ_ASSERT(!mTempRef);
}

NS_IMPL_CYCLE_COLLECTION_CLASS(Notification)
NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN_INHERITED(Notification,
                                                DOMEventTargetHelper)
  tmp->mData.setUndefined();
NS_IMPL_CYCLE_COLLECTION_UNLINK_END

NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN_INHERITED(Notification,
                                                  DOMEventTargetHelper)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END

NS_IMPL_CYCLE_COLLECTION_TRACE_BEGIN_INHERITED(Notification,
                                               DOMEventTargetHelper)
  NS_IMPL_CYCLE_COLLECTION_TRACE_JS_MEMBER_CALLBACK(mData)
NS_IMPL_CYCLE_COLLECTION_TRACE_END

NS_IMPL_ADDREF_INHERITED(Notification, DOMEventTargetHelper)
NS_IMPL_RELEASE_INHERITED(Notification, DOMEventTargetHelper)

NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(Notification)
  NS_INTERFACE_MAP_ENTRY(nsIObserver)
  NS_INTERFACE_MAP_ENTRY(nsISupportsWeakReference)
NS_INTERFACE_MAP_END_INHERITING(DOMEventTargetHelper)

nsIPrincipal* Notification::GetPrincipal() {
  AssertIsOnMainThread();
  if (mWorkerPrivate) {
    return mWorkerPrivate->GetPrincipal();
  } else {
    nsCOMPtr<nsIScriptObjectPrincipal> sop = do_QueryInterface(GetOwner());
    NS_ENSURE_TRUE(sop, nullptr);
    return sop->GetPrincipal();
  }
}

class WorkerNotificationObserver final : public MainThreadNotificationObserver {
 public:
  NS_INLINE_DECL_REFCOUNTING_INHERITED(WorkerNotificationObserver,
                                       MainThreadNotificationObserver)
  NS_DECL_NSIOBSERVER

  explicit WorkerNotificationObserver(UniquePtr<NotificationRef> aRef)
      : MainThreadNotificationObserver(std::move(aRef)) {
    AssertIsOnMainThread();
    MOZ_ASSERT(mNotificationRef->GetNotification()->mWorkerPrivate);
  }

  void ForgetNotification() {
    AssertIsOnMainThread();
    mNotificationRef->Forget();
  }

 protected:
  virtual ~WorkerNotificationObserver() {
    AssertIsOnMainThread();

    MOZ_ASSERT(mNotificationRef);
    Notification* notification = mNotificationRef->GetNotification();
    if (notification) {
      notification->mObserver = nullptr;
    }
  }
};

class ServiceWorkerNotificationObserver final : public nsIObserver {
 public:
  NS_DECL_ISUPPORTS
  NS_DECL_NSIOBSERVER

  ServiceWorkerNotificationObserver(
      const nsAString& aScope, nsIPrincipal* aPrincipal, const nsAString& aID,
      const nsAString& aTitle, const nsAString& aDir, const nsAString& aLang,
      const nsAString& aBody, const nsAString& aTag, const nsAString& aIcon,
      const nsAString& aData, const nsAString& aBehavior)
      : mScope(aScope),
        mID(aID),
        mPrincipal(aPrincipal),
        mTitle(aTitle),
        mDir(aDir),
        mLang(aLang),
        mBody(aBody),
        mTag(aTag),
        mIcon(aIcon),
        mData(aData),
        mBehavior(aBehavior) {
    AssertIsOnMainThread();
    MOZ_ASSERT(aPrincipal);
  }

 private:
  ~ServiceWorkerNotificationObserver() {}

  const nsString mScope;
  const nsString mID;
  nsCOMPtr<nsIPrincipal> mPrincipal;
  const nsString mTitle;
  const nsString mDir;
  const nsString mLang;
  const nsString mBody;
  const nsString mTag;
  const nsString mIcon;
  const nsString mData;
  const nsString mBehavior;
};

NS_IMPL_ISUPPORTS(ServiceWorkerNotificationObserver, nsIObserver)

bool Notification::DispatchClickEvent() {
  AssertIsOnTargetThread();
  RefPtr<Event> event = NS_NewDOMEvent(this, nullptr, nullptr);
  event->InitEvent(NS_LITERAL_STRING("click"), false, true);
  event->SetTrusted(true);
  WantsPopupControlCheck popupControlCheck(event);
  return DispatchEvent(*event, CallerType::System, IgnoreErrors());
}

// Overrides dispatch and run handlers so we can directly dispatch from main
// thread to child workers.
class NotificationClickWorkerRunnable final
    : public NotificationWorkerRunnable {
  Notification* mNotification;
  // Optional window that gets focused if click event is not
  // preventDefault()ed.
  nsMainThreadPtrHandle<nsPIDOMWindowInner> mWindow;

 public:
  NotificationClickWorkerRunnable(
      Notification* aNotification,
      const nsMainThreadPtrHandle<nsPIDOMWindowInner>& aWindow)
      : NotificationWorkerRunnable(aNotification->mWorkerPrivate),
        mNotification(aNotification),
        mWindow(aWindow) {
    MOZ_ASSERT_IF(mWorkerPrivate->IsServiceWorker(), !mWindow);
  }

  void WorkerRunInternal(WorkerPrivate* aWorkerPrivate) override {
    bool doDefaultAction = mNotification->DispatchClickEvent();
    MOZ_ASSERT_IF(mWorkerPrivate->IsServiceWorker(), !doDefaultAction);
    if (doDefaultAction) {
      RefPtr<FocusWindowRunnable> r = new FocusWindowRunnable(mWindow);
      mWorkerPrivate->DispatchToMainThread(r.forget());
    }
  }
};

NS_IMETHODIMP
NotificationObserver::Observe(nsISupports* aSubject, const char* aTopic,
                              const char16_t* aData) {
  AssertIsOnMainThread();

  if (!strcmp("alertdisablecallback", aTopic)) {
    if (XRE_IsParentProcess()) {
      return Notification::RemovePermission(mPrincipal);
    }
    // Permissions can't be removed from the content process. Send a message
    // to the parent; `ContentParent::RecvDisableNotifications` will call
    // `RemovePermission`.
    ContentChild::GetSingleton()->SendDisableNotifications(
        IPC::Principal(mPrincipal));
    return NS_OK;
  } else if (!strcmp("alertsettingscallback", aTopic)) {
    if (XRE_IsParentProcess()) {
      return Notification::OpenSettings(mPrincipal);
    }
    // `ContentParent::RecvOpenNotificationSettings` notifies observers in the
    // parent process.
    ContentChild::GetSingleton()->SendOpenNotificationSettings(
        IPC::Principal(mPrincipal));
    return NS_OK;
  } else if (!strcmp("alertshow", aTopic) || !strcmp("alertfinished", aTopic)) {
    Unused << NS_WARN_IF(NS_FAILED(AdjustPushQuota(aTopic)));
  }

  return mObserver->Observe(aSubject, aTopic, aData);
}

nsresult NotificationObserver::AdjustPushQuota(const char* aTopic) {
  nsCOMPtr<nsIPushQuotaManager> pushQuotaManager =
      do_GetService("@mozilla.org/push/Service;1");
  if (!pushQuotaManager) {
    return NS_ERROR_FAILURE;
  }

  nsAutoCString origin;
  nsresult rv = mPrincipal->GetOrigin(origin);
  if (NS_FAILED(rv)) {
    return rv;
  }

  if (!strcmp("alertshow", aTopic)) {
    return pushQuotaManager->NotificationForOriginShown(origin.get());
  }
  return pushQuotaManager->NotificationForOriginClosed(origin.get());
}

NS_IMETHODIMP
MainThreadNotificationObserver::Observe(nsISupports* aSubject,
                                        const char* aTopic,
                                        const char16_t* aData) {
  AssertIsOnMainThread();
  MOZ_ASSERT(mNotificationRef);
  Notification* notification = mNotificationRef->GetNotification();
  MOZ_ASSERT(notification);
  if (!strcmp("alertclickcallback", aTopic)) {
    nsCOMPtr<nsPIDOMWindowInner> window = notification->GetOwner();
    if (NS_WARN_IF(!window || !window->IsCurrentInnerWindow())) {
      // Window has been closed, this observer is not valid anymore
      return NS_ERROR_FAILURE;
    }

    bool doDefaultAction = notification->DispatchClickEvent();
    if (doDefaultAction) {
      nsFocusManager::FocusWindow(window->GetOuterWindow());
    }
  } else if (!strcmp("alertfinished", aTopic)) {
    notification->UnpersistNotification();
    notification->mIsClosed = true;
    notification->DispatchTrustedEvent(NS_LITERAL_STRING("close"));
  } else if (!strcmp("alertshow", aTopic)) {
    notification->DispatchTrustedEvent(NS_LITERAL_STRING("show"));
  }
  return NS_OK;
}

NS_IMETHODIMP
WorkerNotificationObserver::Observe(nsISupports* aSubject, const char* aTopic,
                                    const char16_t* aData) {
  AssertIsOnMainThread();
  MOZ_ASSERT(mNotificationRef);
  // For an explanation of why it is OK to pass this rawptr to the event
  // runnables, see the Notification class comment.
  Notification* notification = mNotificationRef->GetNotification();
  // We can't assert notification here since the feature could've unset it.
  if (NS_WARN_IF(!notification)) {
    return NS_ERROR_FAILURE;
  }

  MOZ_ASSERT(notification->mWorkerPrivate);

  RefPtr<WorkerRunnable> r;
  if (!strcmp("alertclickcallback", aTopic)) {
    nsPIDOMWindowInner* window = nullptr;
    if (!notification->mWorkerPrivate->IsServiceWorker()) {
      WorkerPrivate* top = notification->mWorkerPrivate;
      while (top->GetParent()) {
        top = top->GetParent();
      }

      window = top->GetWindow();
      if (NS_WARN_IF(!window || !window->IsCurrentInnerWindow())) {
        // Window has been closed, this observer is not valid anymore
        return NS_ERROR_FAILURE;
      }
    }

    // Instead of bothering with adding features and other worker lifecycle
    // management, we simply hold strongrefs to the window and document.
    nsMainThreadPtrHandle<nsPIDOMWindowInner> windowHandle(
        new nsMainThreadPtrHolder<nsPIDOMWindowInner>(
            "WorkerNotificationObserver::Observe::nsPIDOMWindowInner", window));

    r = new NotificationClickWorkerRunnable(notification, windowHandle);
  } else if (!strcmp("alertfinished", aTopic)) {
    notification->UnpersistNotification();
    notification->mIsClosed = true;
    r = new NotificationEventWorkerRunnable(notification,
                                            NS_LITERAL_STRING("close"));
  } else if (!strcmp("alertshow", aTopic)) {
    r = new NotificationEventWorkerRunnable(notification,
                                            NS_LITERAL_STRING("show"));
  }

  MOZ_ASSERT(r);
  if (!r->Dispatch()) {
    NS_WARNING("Could not dispatch event to worker notification");
  }
  return NS_OK;
}

NS_IMETHODIMP
ServiceWorkerNotificationObserver::Observe(nsISupports* aSubject,
                                           const char* aTopic,
                                           const char16_t* aData) {
  AssertIsOnMainThread();

  nsAutoCString originSuffix;
  nsresult rv = mPrincipal->GetOriginSuffix(originSuffix);
  if (NS_WARN_IF(NS_FAILED(rv))) {
    return rv;
  }

  if (!strcmp("alertclickcallback", aTopic)) {
    if (XRE_IsParentProcess() || !ServiceWorkerParentInterceptEnabled()) {
      nsCOMPtr<nsIServiceWorkerManager> swm =
          mozilla::services::GetServiceWorkerManager();
      if (NS_WARN_IF(!swm)) {
        return NS_ERROR_FAILURE;
      }

      rv = swm->SendNotificationClickEvent(
          originSuffix, NS_ConvertUTF16toUTF8(mScope), mID, mTitle, mDir, mLang,
          mBody, mTag, mIcon, mData, mBehavior);
      Unused << NS_WARN_IF(NS_FAILED(rv));
    } else {
      auto* cc = ContentChild::GetSingleton();
      NotificationEventData data(originSuffix, NS_ConvertUTF16toUTF8(mScope),
                                 mID, mTitle, mDir, mLang, mBody, mTag, mIcon,
                                 mData, mBehavior);
      Unused << cc->SendNotificationEvent(NS_LITERAL_STRING("click"), data);
    }
    return NS_OK;
  }

  if (!strcmp("alertfinished", aTopic)) {
    nsString origin;
    nsresult rv = Notification::GetOrigin(mPrincipal, origin);
    if (NS_WARN_IF(NS_FAILED(rv))) {
      return rv;
    }

    // Remove closed or dismissed persistent notifications.
    nsCOMPtr<nsINotificationStorage> notificationStorage =
        do_GetService(NS_NOTIFICATION_STORAGE_CONTRACTID);
    if (notificationStorage) {
      notificationStorage->Delete(origin, mID);
    }

    if (XRE_IsParentProcess() || !ServiceWorkerParentInterceptEnabled()) {
      nsCOMPtr<nsIServiceWorkerManager> swm =
          mozilla::services::GetServiceWorkerManager();
      if (NS_WARN_IF(!swm)) {
        return NS_ERROR_FAILURE;
      }

      rv = swm->SendNotificationCloseEvent(
          originSuffix, NS_ConvertUTF16toUTF8(mScope), mID, mTitle, mDir, mLang,
          mBody, mTag, mIcon, mData, mBehavior);
      Unused << NS_WARN_IF(NS_FAILED(rv));
    } else {
      auto* cc = ContentChild::GetSingleton();
      NotificationEventData data(originSuffix, NS_ConvertUTF16toUTF8(mScope),
                                 mID, mTitle, mDir, mLang, mBody, mTag, mIcon,
                                 mData, mBehavior);
      Unused << cc->SendNotificationEvent(NS_LITERAL_STRING("close"), data);
    }
    return NS_OK;
  }

  return NS_OK;
}

bool Notification::IsInPrivateBrowsing() {
  AssertIsOnMainThread();

  Document* doc = nullptr;

  if (mWorkerPrivate) {
    doc = mWorkerPrivate->GetDocument();
  } else if (GetOwner()) {
    doc = GetOwner()->GetExtantDoc();
  }

  if (doc) {
    nsCOMPtr<nsILoadContext> loadContext = doc->GetLoadContext();
    return loadContext && loadContext->UsePrivateBrowsing();
  }

  if (mWorkerPrivate) {
    // Not all workers may have a document, but with Bug 1107516 fixed, they
    // should all have a loadcontext.
    nsCOMPtr<nsILoadGroup> loadGroup = mWorkerPrivate->GetLoadGroup();
    nsCOMPtr<nsILoadContext> loadContext;
    NS_QueryNotificationCallbacks(nullptr, loadGroup,
                                  NS_GET_IID(nsILoadContext),
                                  getter_AddRefs(loadContext));
    return loadContext && loadContext->UsePrivateBrowsing();
  }

  // XXXnsm Should this default to true?
  return false;
}

namespace {
struct StringWriteFunc : public JSONWriteFunc {
  nsAString& mBuffer;  // This struct must not outlive this buffer
  explicit StringWriteFunc(nsAString& buffer) : mBuffer(buffer) {}

  void Write(const char* aStr) override {
    mBuffer.Append(NS_ConvertUTF8toUTF16(aStr));
  }
};
}  // namespace

void Notification::ShowInternal() {
  AssertIsOnMainThread();
  MOZ_ASSERT(mTempRef,
             "Notification should take ownership of itself before"
             "calling ShowInternal!");
  // A notification can only have one observer and one call to ShowInternal.
  MOZ_ASSERT(!mObserver);

  // Transfer ownership to local scope so we can either release it at the end
  // of this function or transfer it to the observer.
  UniquePtr<NotificationRef> ownership;
  mozilla::Swap(ownership, mTempRef);
  MOZ_ASSERT(ownership->GetNotification() == this);

  nsresult rv = PersistNotification();
  if (NS_FAILED(rv)) {
    NS_WARNING("Could not persist Notification");
  }

  nsCOMPtr<nsIAlertsService> alertService = components::Alerts::Service();

  ErrorResult result;
  NotificationPermission permission = NotificationPermission::Denied;
  if (mWorkerPrivate) {
    permission = GetPermissionInternal(mWorkerPrivate->GetPrincipal(), result);
  } else {
    permission = GetPermissionInternal(GetOwner(), result);
  }
  // We rely on GetPermissionInternal returning Denied on all failure codepaths.
  MOZ_ASSERT_IF(result.Failed(), permission == NotificationPermission::Denied);
  result.SuppressException();
  if (permission != NotificationPermission::Granted || !alertService) {
    if (mWorkerPrivate) {
      RefPtr<NotificationEventWorkerRunnable> r =
          new NotificationEventWorkerRunnable(this, NS_LITERAL_STRING("error"));
      if (!r->Dispatch()) {
        NS_WARNING("Could not dispatch event to worker notification");
      }
    } else {
      DispatchTrustedEvent(NS_LITERAL_STRING("error"));
    }
    return;
  }

  nsAutoString iconUrl;
  nsAutoString soundUrl;
  ResolveIconAndSoundURL(iconUrl, soundUrl);

  bool isPersistent = false;
  nsCOMPtr<nsIObserver> observer;
  if (mScope.IsEmpty()) {
    // Ownership passed to observer.
    if (mWorkerPrivate) {
      // Scope better be set on ServiceWorker initiated requests.
      MOZ_ASSERT(!mWorkerPrivate->IsServiceWorker());
      // Keep a pointer so that the feature can tell the observer not to release
      // the notification.
      mObserver = new WorkerNotificationObserver(std::move(ownership));
      observer = mObserver;
    } else {
      observer = new MainThreadNotificationObserver(std::move(ownership));
    }
  } else {
    isPersistent = true;
    // This observer does not care about the Notification. It will be released
    // at the end of this function.
    //
    // The observer is wholly owned by the NotificationObserver passed to the
    // alert service.
    nsAutoString behavior;
    if (NS_WARN_IF(!mBehavior.ToJSON(behavior))) {
      behavior.Truncate();
    }
    observer = new ServiceWorkerNotificationObserver(
        mScope, GetPrincipal(), mID, mTitle, DirectionToString(mDir), mLang,
        mBody, mTag, iconUrl, mDataAsBase64, behavior);
  }
  MOZ_ASSERT(observer);
  nsCOMPtr<nsIObserver> alertObserver =
      new NotificationObserver(observer, GetPrincipal(), IsInPrivateBrowsing());

  // In the case of IPC, the parent process uses the cookie to map to
  // nsIObserver. Thus the cookie must be unique to differentiate observers.
  nsString uniqueCookie = NS_LITERAL_STRING("notification:");
  uniqueCookie.AppendInt(sCount++);
  bool inPrivateBrowsing = IsInPrivateBrowsing();

  bool requireInteraction = mRequireInteraction;
  if (!StaticPrefs::dom_webnotifications_requireinteraction_enabled()) {
    requireInteraction = false;
  }

  nsAutoString alertName;
  GetAlertName(alertName);
  nsCOMPtr<nsIAlertNotification> alert =
      do_CreateInstance(ALERT_NOTIFICATION_CONTRACTID);
  NS_ENSURE_TRUE_VOID(alert);
  nsIPrincipal* principal = GetPrincipal();
  rv = alert->Init(alertName, iconUrl, mTitle, mBody, true, uniqueCookie,
                   DirectionToString(mDir), mLang, mDataAsBase64,
                   GetPrincipal(), inPrivateBrowsing, requireInteraction);
  NS_ENSURE_SUCCESS_VOID(rv);

  if (isPersistent) {
    nsAutoString persistentData;

    JSONWriter w(MakeUnique<StringWriteFunc>(persistentData));
    w.Start();

    nsAutoString origin;
    Notification::GetOrigin(principal, origin);
    w.StringProperty("origin", NS_ConvertUTF16toUTF8(origin).get());

    w.StringProperty("id", NS_ConvertUTF16toUTF8(mID).get());

    nsAutoCString originSuffix;
    principal->GetOriginSuffix(originSuffix);
    w.StringProperty("originSuffix", originSuffix.get());

    w.End();

    alertService->ShowPersistentNotification(persistentData, alert,
                                             alertObserver);
  } else {
    alertService->ShowAlert(alert, alertObserver);
  }
}

/* static */
bool Notification::RequestPermissionEnabledForScope(JSContext* aCx,
                                                    JSObject* /* unused */) {
  // requestPermission() is not allowed on workers. The calling page should ask
  // for permission on the worker's behalf. This is to prevent 'which window
  // should show the browser pop-up'. See discussion:
  // http://lists.whatwg.org/pipermail/whatwg-whatwg.org/2013-October/041272.html
  return NS_IsMainThread();
}

// static
already_AddRefed<Promise> Notification::RequestPermission(
    const GlobalObject& aGlobal,
    const Optional<OwningNonNull<NotificationPermissionCallback> >& aCallback,
    ErrorResult& aRv) {
  AssertIsOnMainThread();

  // Get principal from global to make permission request for notifications.
  nsCOMPtr<nsPIDOMWindowInner> window =
      do_QueryInterface(aGlobal.GetAsSupports());
  nsCOMPtr<nsIScriptObjectPrincipal> sop =
      do_QueryInterface(aGlobal.GetAsSupports());
  if (!sop || !window) {
    aRv.Throw(NS_ERROR_UNEXPECTED);
    return nullptr;
  }
  nsCOMPtr<nsIPrincipal> principal = sop->GetPrincipal();

  RefPtr<Promise> promise = Promise::Create(window->AsGlobal(), aRv);
  if (aRv.Failed()) {
    return nullptr;
  }
  NotificationPermissionCallback* permissionCallback = nullptr;
  if (aCallback.WasPassed()) {
    permissionCallback = &aCallback.Value();
  }
  nsCOMPtr<nsIRunnable> request = new NotificationPermissionRequest(
      principal, window, promise, permissionCallback);

  window->AsGlobal()->Dispatch(TaskCategory::Other, request.forget());

  return promise.forget();
}

// static
NotificationPermission Notification::GetPermission(const GlobalObject& aGlobal,
                                                   ErrorResult& aRv) {
  nsCOMPtr<nsIGlobalObject> global = do_QueryInterface(aGlobal.GetAsSupports());
  return GetPermission(global, aRv);
}

// static
NotificationPermission Notification::GetPermission(nsIGlobalObject* aGlobal,
                                                   ErrorResult& aRv) {
  if (NS_IsMainThread()) {
    return GetPermissionInternal(aGlobal, aRv);
  } else {
    WorkerPrivate* worker = GetCurrentThreadWorkerPrivate();
    MOZ_ASSERT(worker);
    RefPtr<GetPermissionRunnable> r = new GetPermissionRunnable(worker);
    r->Dispatch(Canceling, aRv);
    if (aRv.Failed()) {
      return NotificationPermission::Denied;
    }

    return r->GetPermission();
  }
}

/* static */
NotificationPermission Notification::GetPermissionInternal(nsISupports* aGlobal,
                                                           ErrorResult& aRv) {
  // Get principal from global to check permission for notifications.
  nsCOMPtr<nsIScriptObjectPrincipal> sop = do_QueryInterface(aGlobal);
  if (!sop) {
    aRv.Throw(NS_ERROR_UNEXPECTED);
    return NotificationPermission::Denied;
  }

  nsCOMPtr<nsIPrincipal> principal = sop->GetPrincipal();
  return GetPermissionInternal(principal, aRv);
}

/* static */
NotificationPermission Notification::GetPermissionInternal(
    nsIPrincipal* aPrincipal, ErrorResult& aRv) {
  AssertIsOnMainThread();
  MOZ_ASSERT(aPrincipal);

  if (aPrincipal->IsSystemPrincipal()) {
    return NotificationPermission::Granted;
  } else {
    // Allow files to show notifications by default.
    if (aPrincipal->SchemeIs("file")) {
      return NotificationPermission::Granted;
    }
  }

  // We also allow notifications is they are pref'ed on.
  if (Preferences::GetBool("notification.prompt.testing", false)) {
    if (Preferences::GetBool("notification.prompt.testing.allow", true)) {
      return NotificationPermission::Granted;
    } else {
      return NotificationPermission::Denied;
    }
  }

  return TestPermission(aPrincipal);
}

/* static */
NotificationPermission Notification::TestPermission(nsIPrincipal* aPrincipal) {
  AssertIsOnMainThread();

  uint32_t permission = nsIPermissionManager::UNKNOWN_ACTION;

  nsCOMPtr<nsIPermissionManager> permissionManager =
      services::GetPermissionManager();
  if (!permissionManager) {
    return NotificationPermission::Default;
  }

  permissionManager->TestExactPermissionFromPrincipal(
      aPrincipal, NS_LITERAL_CSTRING("desktop-notification"), &permission);

  // Convert the result to one of the enum types.
  switch (permission) {
    case nsIPermissionManager::ALLOW_ACTION:
      return NotificationPermission::Granted;
    case nsIPermissionManager::DENY_ACTION:
      return NotificationPermission::Denied;
    default:
      return NotificationPermission::Default;
  }
}

nsresult Notification::ResolveIconAndSoundURL(nsString& iconUrl,
                                              nsString& soundUrl) {
  AssertIsOnMainThread();
  nsresult rv = NS_OK;

  nsIURI* baseUri = nullptr;

  // XXXnsm If I understand correctly, the character encoding for resolving
  // URIs in new specs is dictated by the URL spec, which states that unless
  // the URL parser is passed an override encoding, the charset to be used is
  // UTF-8. The new Notification icon/sound specification just says to use the
  // Fetch API, where the Request constructor defers to URL parsing specifying
  // the API base URL and no override encoding. So we've to use UTF-8 on
  // workers, but for backwards compat keeping it document charset on main
  // thread.
  auto encoding = UTF_8_ENCODING;

  if (mWorkerPrivate) {
    baseUri = mWorkerPrivate->GetBaseURI();
  } else {
    Document* doc = GetOwner() ? GetOwner()->GetExtantDoc() : nullptr;
    if (doc) {
      baseUri = doc->GetBaseURI();
      encoding = doc->GetDocumentCharacterSet();
    } else {
      NS_WARNING("No document found for main thread notification!");
      return NS_ERROR_FAILURE;
    }
  }

  if (baseUri) {
    if (mIconUrl.Length() > 0) {
      nsCOMPtr<nsIURI> srcUri;
      rv = NS_NewURI(getter_AddRefs(srcUri), mIconUrl, encoding, baseUri);
      if (NS_SUCCEEDED(rv)) {
        nsAutoCString src;
        srcUri->GetSpec(src);
        iconUrl = NS_ConvertUTF8toUTF16(src);
      }
    }
    if (mBehavior.mSoundFile.Length() > 0) {
      nsCOMPtr<nsIURI> srcUri;
      rv = NS_NewURI(getter_AddRefs(srcUri), mBehavior.mSoundFile, encoding,
                     baseUri);
      if (NS_SUCCEEDED(rv)) {
        nsAutoCString src;
        srcUri->GetSpec(src);
        soundUrl = NS_ConvertUTF8toUTF16(src);
      }
    }
  }

  return rv;
}

already_AddRefed<Promise> Notification::Get(
    nsPIDOMWindowInner* aWindow, const GetNotificationOptions& aFilter,
    const nsAString& aScope, ErrorResult& aRv) {
  AssertIsOnMainThread();
  MOZ_ASSERT(aWindow);

  nsCOMPtr<Document> doc = aWindow->GetExtantDoc();
  if (!doc) {
    aRv.Throw(NS_ERROR_UNEXPECTED);
    return nullptr;
  }

  nsString origin;
  aRv = GetOrigin(doc->NodePrincipal(), origin);
  if (aRv.Failed()) {
    return nullptr;
  }

  RefPtr<Promise> promise = Promise::Create(aWindow->AsGlobal(), aRv);
  if (aRv.Failed()) {
    return nullptr;
  }

  nsCOMPtr<nsINotificationStorageCallback> callback =
      new NotificationStorageCallback(aWindow->AsGlobal(), aScope, promise);

  RefPtr<NotificationGetRunnable> r =
      new NotificationGetRunnable(origin, aFilter.mTag, callback);

  aRv = aWindow->AsGlobal()->Dispatch(TaskCategory::Other, r.forget());
  if (NS_WARN_IF(aRv.Failed())) {
    return nullptr;
  }

  return promise.forget();
}

already_AddRefed<Promise> Notification::Get(
    const GlobalObject& aGlobal, const GetNotificationOptions& aFilter,
    ErrorResult& aRv) {
  AssertIsOnMainThread();
  nsCOMPtr<nsIGlobalObject> global = do_QueryInterface(aGlobal.GetAsSupports());
  MOZ_ASSERT(global);
  nsCOMPtr<nsPIDOMWindowInner> window = do_QueryInterface(global);

  return Get(window, aFilter, EmptyString(), aRv);
}

class WorkerGetResultRunnable final : public NotificationWorkerRunnable {
  RefPtr<PromiseWorkerProxy> mPromiseProxy;
  const nsTArray<NotificationStrings> mStrings;

 public:
  WorkerGetResultRunnable(WorkerPrivate* aWorkerPrivate,
                          PromiseWorkerProxy* aPromiseProxy,
                          const nsTArray<NotificationStrings>&& aStrings)
      : NotificationWorkerRunnable(aWorkerPrivate),
        mPromiseProxy(aPromiseProxy),
        mStrings(std::move(aStrings)) {}

  void WorkerRunInternal(WorkerPrivate* aWorkerPrivate) override {
    RefPtr<Promise> workerPromise = mPromiseProxy->WorkerPromise();

    ErrorResult result;
    AutoTArray<RefPtr<Notification>, 5> notifications;
    for (uint32_t i = 0; i < mStrings.Length(); ++i) {
      RefPtr<Notification> n = Notification::ConstructFromFields(
          aWorkerPrivate->GlobalScope(), mStrings[i].mID, mStrings[i].mTitle,
          mStrings[i].mDir, mStrings[i].mLang, mStrings[i].mBody,
          mStrings[i].mTag, mStrings[i].mIcon, mStrings[i].mData,
          /* mStrings[i].mBehavior, not
           * supported */
          mStrings[i].mServiceWorkerRegistrationScope, result);

      n->SetStoredState(true);
      Unused << NS_WARN_IF(result.Failed());
      if (!result.Failed()) {
        notifications.AppendElement(n.forget());
      }
    }

    workerPromise->MaybeResolve(notifications);
    mPromiseProxy->CleanUp();
  }
};

class WorkerGetCallback final : public ScopeCheckingGetCallback {
  RefPtr<PromiseWorkerProxy> mPromiseProxy;

 public:
  NS_DECL_ISUPPORTS

  WorkerGetCallback(PromiseWorkerProxy* aProxy, const nsAString& aScope)
      : ScopeCheckingGetCallback(aScope), mPromiseProxy(aProxy) {
    AssertIsOnMainThread();
    MOZ_ASSERT(aProxy);
  }

  NS_IMETHOD Done() final {
    AssertIsOnMainThread();
    MOZ_ASSERT(mPromiseProxy, "Was Done() called twice?");

    RefPtr<PromiseWorkerProxy> proxy = mPromiseProxy.forget();
    MutexAutoLock lock(proxy->Lock());
    if (proxy->CleanedUp()) {
      return NS_OK;
    }

    RefPtr<WorkerGetResultRunnable> r = new WorkerGetResultRunnable(
        proxy->GetWorkerPrivate(), proxy, std::move(mStrings));

    r->Dispatch();
    return NS_OK;
  }

 private:
  ~WorkerGetCallback() {}
};

NS_IMPL_ISUPPORTS(WorkerGetCallback, nsINotificationStorageCallback)

class WorkerGetRunnable final : public Runnable {
  RefPtr<PromiseWorkerProxy> mPromiseProxy;
  const nsString mTag;
  const nsString mScope;

 public:
  WorkerGetRunnable(PromiseWorkerProxy* aProxy, const nsAString& aTag,
                    const nsAString& aScope)
      : Runnable("WorkerGetRunnable"),
        mPromiseProxy(aProxy),
        mTag(aTag),
        mScope(aScope) {
    MOZ_ASSERT(mPromiseProxy);
  }

  NS_IMETHOD
  Run() override {
    AssertIsOnMainThread();
    nsCOMPtr<nsINotificationStorageCallback> callback =
        new WorkerGetCallback(mPromiseProxy, mScope);

    nsresult rv;
    nsCOMPtr<nsINotificationStorage> notificationStorage =
        do_GetService(NS_NOTIFICATION_STORAGE_CONTRACTID, &rv);
    if (NS_WARN_IF(NS_FAILED(rv))) {
      callback->Done();
      return rv;
    }

    MutexAutoLock lock(mPromiseProxy->Lock());
    if (mPromiseProxy->CleanedUp()) {
      return NS_OK;
    }

    nsString origin;
    rv = Notification::GetOrigin(
        mPromiseProxy->GetWorkerPrivate()->GetPrincipal(), origin);
    if (NS_WARN_IF(NS_FAILED(rv))) {
      callback->Done();
      return rv;
    }

    rv = notificationStorage->Get(origin, mTag, callback);
    if (NS_WARN_IF(NS_FAILED(rv))) {
      callback->Done();
      return rv;
    }

    return NS_OK;
  }

 private:
  ~WorkerGetRunnable() {}
};

// static
already_AddRefed<Promise> Notification::WorkerGet(
    WorkerPrivate* aWorkerPrivate, const GetNotificationOptions& aFilter,
    const nsAString& aScope, ErrorResult& aRv) {
  MOZ_ASSERT(aWorkerPrivate);
  aWorkerPrivate->AssertIsOnWorkerThread();
  RefPtr<Promise> p = Promise::Create(aWorkerPrivate->GlobalScope(), aRv);
  if (NS_WARN_IF(aRv.Failed())) {
    return nullptr;
  }

  RefPtr<PromiseWorkerProxy> proxy =
      PromiseWorkerProxy::Create(aWorkerPrivate, p);
  if (!proxy) {
    aRv.Throw(NS_ERROR_DOM_ABORT_ERR);
    return nullptr;
  }

  RefPtr<WorkerGetRunnable> r =
      new WorkerGetRunnable(proxy, aFilter.mTag, aScope);
  // Since this is called from script via
  // ServiceWorkerRegistration::GetNotifications, we can assert dispatch.
  MOZ_ALWAYS_SUCCEEDS(aWorkerPrivate->DispatchToMainThread(r.forget()));
  return p.forget();
}

JSObject* Notification::WrapObject(JSContext* aCx,
                                   JS::Handle<JSObject*> aGivenProto) {
  return mozilla::dom::Notification_Binding::Wrap(aCx, this, aGivenProto);
}

void Notification::Close() {
  AssertIsOnTargetThread();
  auto ref = MakeUnique<NotificationRef>(this);
  if (!ref->Initialized()) {
    return;
  }

  nsCOMPtr<nsIRunnable> closeNotificationTask = new NotificationTask(
      "Notification::Close", std::move(ref), NotificationTask::eClose);
  nsresult rv = DispatchToMainThread(closeNotificationTask.forget());

  if (NS_FAILED(rv)) {
    DispatchTrustedEvent(NS_LITERAL_STRING("error"));
    // If dispatch fails, NotificationTask will release the ref when it goes
    // out of scope at the end of this function.
  }
}

void Notification::CloseInternal() {
  AssertIsOnMainThread();
  // Transfer ownership (if any) to local scope so we can release it at the end
  // of this function. This is relevant when the call is from
  // NotificationTask::Run().
  UniquePtr<NotificationRef> ownership;
  mozilla::Swap(ownership, mTempRef);

  SetAlertName();
  UnpersistNotification();
  if (!mIsClosed) {
    nsCOMPtr<nsIAlertsService> alertService = components::Alerts::Service();
    if (alertService) {
      nsAutoString alertName;
      GetAlertName(alertName);
      alertService->CloseAlert(alertName, GetPrincipal());
    }
  }
}

nsresult Notification::GetOrigin(nsIPrincipal* aPrincipal, nsString& aOrigin) {
  if (!aPrincipal) {
    return NS_ERROR_FAILURE;
  }

  nsresult rv = nsContentUtils::GetUTFOrigin(aPrincipal, aOrigin);
  NS_ENSURE_SUCCESS(rv, rv);

  return NS_OK;
}

bool Notification::RequireInteraction() const { return mRequireInteraction; }

void Notification::GetData(JSContext* aCx,
                           JS::MutableHandle<JS::Value> aRetval) {
  if (mData.isNull() && !mDataAsBase64.IsEmpty()) {
    nsresult rv;
    RefPtr<nsStructuredCloneContainer> container =
        new nsStructuredCloneContainer();
    rv = container->InitFromBase64(mDataAsBase64, JS_STRUCTURED_CLONE_VERSION);
    if (NS_WARN_IF(NS_FAILED(rv))) {
      aRetval.setNull();
      return;
    }

    JS::Rooted<JS::Value> data(aCx);
    rv = container->DeserializeToJsval(aCx, &data);
    if (NS_WARN_IF(NS_FAILED(rv))) {
      aRetval.setNull();
      return;
    }

    if (data.isGCThing()) {
      mozilla::HoldJSObjects(this);
    }
    mData = data;
  }
  if (mData.isNull()) {
    aRetval.setNull();
    return;
  }

  aRetval.set(mData);
}

void Notification::InitFromJSVal(JSContext* aCx, JS::Handle<JS::Value> aData,
                                 ErrorResult& aRv) {
  if (!mDataAsBase64.IsEmpty() || aData.isNull()) {
    return;
  }
  RefPtr<nsStructuredCloneContainer> dataObjectContainer =
      new nsStructuredCloneContainer();
  aRv = dataObjectContainer->InitFromJSVal(aData, aCx);
  if (NS_WARN_IF(aRv.Failed())) {
    return;
  }

  aRv = dataObjectContainer->GetDataAsBase64(mDataAsBase64);
  if (NS_WARN_IF(aRv.Failed())) {
    return;
  }
}

void Notification::InitFromBase64(const nsAString& aData, ErrorResult& aRv) {
  if (!mDataAsBase64.IsEmpty() || aData.IsEmpty()) {
    return;
  }

  // To and fro to ensure it is valid base64.
  RefPtr<nsStructuredCloneContainer> container =
      new nsStructuredCloneContainer();
  aRv = container->InitFromBase64(aData, JS_STRUCTURED_CLONE_VERSION);
  if (NS_WARN_IF(aRv.Failed())) {
    return;
  }

  aRv = container->GetDataAsBase64(mDataAsBase64);
  if (NS_WARN_IF(aRv.Failed())) {
    return;
  }
}

bool Notification::AddRefObject() {
  AssertIsOnTargetThread();
  MOZ_ASSERT_IF(mWorkerPrivate && !mWorkerRef, mTaskCount == 0);
  MOZ_ASSERT_IF(mWorkerPrivate && mWorkerRef, mTaskCount > 0);
  if (mWorkerPrivate && !mWorkerRef) {
    if (!CreateWorkerRef()) {
      return false;
    }
  }
  AddRef();
  ++mTaskCount;
  return true;
}

void Notification::ReleaseObject() {
  AssertIsOnTargetThread();
  MOZ_ASSERT(mTaskCount > 0);
  MOZ_ASSERT_IF(mWorkerPrivate, mWorkerRef);

  --mTaskCount;
  if (mWorkerPrivate && mTaskCount == 0) {
    MOZ_ASSERT(mWorkerRef);
    mWorkerRef = nullptr;
  }
  Release();
}

/*
 * Called from the worker, runs on main thread, blocks worker.
 *
 * We can freely access mNotification here because the feature supplied it and
 * the Notification owns the feature.
 */
class CloseNotificationRunnable final : public WorkerMainThreadRunnable {
  Notification* mNotification;
  bool mHadObserver;

 public:
  explicit CloseNotificationRunnable(Notification* aNotification)
      : WorkerMainThreadRunnable(
            aNotification->mWorkerPrivate,
            NS_LITERAL_CSTRING("Notification :: Close Notification")),
        mNotification(aNotification),
        mHadObserver(false) {}

  bool MainThreadRun() override {
    if (mNotification->mObserver) {
      // The Notify() take's responsibility of releasing the Notification.
      mNotification->mObserver->ForgetNotification();
      mNotification->mObserver = nullptr;
      mHadObserver = true;
    }
    mNotification->CloseInternal();
    return true;
  }

  bool HadObserver() { return mHadObserver; }
};

bool Notification::CreateWorkerRef() {
  MOZ_ASSERT(mWorkerPrivate);
  mWorkerPrivate->AssertIsOnWorkerThread();
  MOZ_ASSERT(!mWorkerRef);

  RefPtr<Notification> self = this;
  mWorkerRef =
      StrongWorkerRef::Create(mWorkerPrivate, "Notification", [self]() {
        // CloseNotificationRunnable blocks the worker by pushing a sync event
        // loop on the stack. Meanwhile, WorkerControlRunnables dispatched to
        // the worker can still continue running. One of these is
        // ReleaseNotificationControlRunnable that releases the notification,
        // invalidating the notification and this feature. We hold this
        // reference to keep the notification valid until we are done with it.
        //
        // An example of when the control runnable could get dispatched to the
        // worker is if a Notification is created and the worker is immediately
        // closed, but there is no permission to show it so that the main thread
        // immediately drops the NotificationRef. In this case, this function
        // blocks on the main thread, but the main thread dispatches the control
        // runnable, invalidating mNotification.

        // Dispatched to main thread, blocks on closing the Notification.
        RefPtr<CloseNotificationRunnable> r =
            new CloseNotificationRunnable(self);
        ErrorResult rv;
        r->Dispatch(Killing, rv);
        // XXXbz I'm told throwing and returning false from here is pointless
        // (and also that doing sync stuff from here is really weird), so I
        // guess we just suppress the exception on rv, if any.
        rv.SuppressException();

        // Only call ReleaseObject() to match the observer's NotificationRef
        // ownership (since CloseNotificationRunnable asked the observer to drop
        // the reference to the notification).
        if (r->HadObserver()) {
          self->ReleaseObject();
        }

        // From this point we cannot touch properties of this feature because
        // ReleaseObject() may have led to the notification going away and the
        // notification owns this feature!
      });

  if (NS_WARN_IF(!mWorkerRef)) {
    return false;
  }

  return true;
}

/*
 * Checks:
 * 1) Is aWorker allowed to show a notification for scope?
 * 2) Is aWorker an active worker?
 *
 * If it is not an active worker, Result() will be NS_ERROR_NOT_AVAILABLE.
 */
class CheckLoadRunnable final : public WorkerMainThreadRunnable {
  nsresult mRv;
  nsCString mScope;
  ServiceWorkerRegistrationDescriptor mDescriptor;

 public:
  explicit CheckLoadRunnable(
      WorkerPrivate* aWorker, const nsACString& aScope,
      const ServiceWorkerRegistrationDescriptor& aDescriptor)
      : WorkerMainThreadRunnable(
            aWorker, NS_LITERAL_CSTRING("Notification :: Check Load")),
        mRv(NS_ERROR_DOM_SECURITY_ERR),
        mScope(aScope),
        mDescriptor(aDescriptor) {}

  bool MainThreadRun() override {
    nsIPrincipal* principal = mWorkerPrivate->GetPrincipal();
    mRv = CheckScope(principal, mScope, mWorkerPrivate->WindowID());

    if (NS_FAILED(mRv)) {
      return true;
    }

    auto activeWorker = mDescriptor.GetActive();

    if (!activeWorker ||
        activeWorker.ref().Id() != mWorkerPrivate->ServiceWorkerID()) {
      mRv = NS_ERROR_NOT_AVAILABLE;
    }

    return true;
  }

  nsresult Result() { return mRv; }
};

/* static */
already_AddRefed<Promise> Notification::ShowPersistentNotification(
    JSContext* aCx, nsIGlobalObject* aGlobal, const nsAString& aScope,
    const nsAString& aTitle, const NotificationOptions& aOptions,
    const ServiceWorkerRegistrationDescriptor& aDescriptor, ErrorResult& aRv) {
  MOZ_ASSERT(aGlobal);

  // Validate scope.
  // XXXnsm: This may be slow due to blocking the worker and waiting on the main
  // thread. On calls from content, we can be sure the scope is valid since
  // ServiceWorkerRegistrations have their scope set correctly. Can this be made
  // debug only? The problem is that there would be different semantics in
  // debug and non-debug builds in such a case.
  if (NS_IsMainThread()) {
    nsCOMPtr<nsIScriptObjectPrincipal> sop = do_QueryInterface(aGlobal);
    if (NS_WARN_IF(!sop)) {
      aRv.Throw(NS_ERROR_UNEXPECTED);
      return nullptr;
    }

    nsIPrincipal* principal = sop->GetPrincipal();
    if (NS_WARN_IF(!principal)) {
      aRv.Throw(NS_ERROR_UNEXPECTED);
      return nullptr;
    }

    uint64_t windowID = 0;
    nsCOMPtr<nsPIDOMWindowInner> win = do_QueryInterface(aGlobal);
    if (win) {
      windowID = win->WindowID();
    }

    aRv = CheckScope(principal, NS_ConvertUTF16toUTF8(aScope), windowID);
    if (NS_WARN_IF(aRv.Failed())) {
      aRv.Throw(NS_ERROR_DOM_SECURITY_ERR);
      return nullptr;
    }
  } else {
    WorkerPrivate* worker = GetCurrentThreadWorkerPrivate();
    MOZ_ASSERT(worker);
    worker->AssertIsOnWorkerThread();

    RefPtr<CheckLoadRunnable> loadChecker = new CheckLoadRunnable(
        worker, NS_ConvertUTF16toUTF8(aScope), aDescriptor);
    loadChecker->Dispatch(Canceling, aRv);
    if (aRv.Failed()) {
      return nullptr;
    }

    if (NS_WARN_IF(NS_FAILED(loadChecker->Result()))) {
      if (loadChecker->Result() == NS_ERROR_NOT_AVAILABLE) {
        aRv.ThrowTypeError<MSG_NO_ACTIVE_WORKER>(aScope);
      } else {
        aRv.Throw(NS_ERROR_DOM_SECURITY_ERR);
      }
      return nullptr;
    }
  }

  RefPtr<Promise> p = Promise::Create(aGlobal, aRv);
  if (NS_WARN_IF(aRv.Failed())) {
    return nullptr;
  }

  // We check permission here rather than pass the Promise to NotificationTask
  // which leads to uglier code.
  NotificationPermission permission = GetPermission(aGlobal, aRv);

  // "If permission for notification's origin is not "granted", reject promise
  // with a TypeError exception, and terminate these substeps."
  if (NS_WARN_IF(aRv.Failed()) ||
      permission == NotificationPermission::Denied) {
    p->MaybeRejectWithTypeError(u"Permission to show Notification denied.");
    return p.forget();
  }

  // "Otherwise, resolve promise with undefined."
  // The Notification may still not be shown due to other errors, but the spec
  // is not concerned with those.
  p->MaybeResolveWithUndefined();

  RefPtr<Notification> notification =
      CreateAndShow(aCx, aGlobal, aTitle, aOptions, aScope, aRv);
  if (NS_WARN_IF(aRv.Failed())) {
    return nullptr;
  }

  return p.forget();
}

/* static */
already_AddRefed<Notification> Notification::CreateAndShow(
    JSContext* aCx, nsIGlobalObject* aGlobal, const nsAString& aTitle,
    const NotificationOptions& aOptions, const nsAString& aScope,
    ErrorResult& aRv) {
  MOZ_ASSERT(aGlobal);

  RefPtr<Notification> notification =
      CreateInternal(aGlobal, EmptyString(), aTitle, aOptions);

  // Make a structured clone of the aOptions.mData object
  JS::Rooted<JS::Value> data(aCx, aOptions.mData);
  notification->InitFromJSVal(aCx, data, aRv);
  if (NS_WARN_IF(aRv.Failed())) {
    return nullptr;
  }

  notification->SetScope(aScope);

  auto ref = MakeUnique<NotificationRef>(notification);
  if (NS_WARN_IF(!ref->Initialized())) {
    aRv.Throw(NS_ERROR_DOM_ABORT_ERR);
    return nullptr;
  }

  // Queue a task to show the notification.
  nsCOMPtr<nsIRunnable> showNotificationTask = new NotificationTask(
      "Notification::CreateAndShow", std::move(ref), NotificationTask::eShow);

  nsresult rv =
      notification->DispatchToMainThread(showNotificationTask.forget());

  if (NS_WARN_IF(NS_FAILED(rv))) {
    notification->DispatchTrustedEvent(NS_LITERAL_STRING("error"));
  }

  return notification.forget();
}

/* static */
nsresult Notification::RemovePermission(nsIPrincipal* aPrincipal) {
  MOZ_ASSERT(XRE_IsParentProcess());
  nsCOMPtr<nsIPermissionManager> permissionManager =
      mozilla::services::GetPermissionManager();
  if (!permissionManager) {
    return NS_ERROR_FAILURE;
  }
  permissionManager->RemoveFromPrincipal(
      aPrincipal, NS_LITERAL_CSTRING("desktop-notification"));
  return NS_OK;
}

/* static */
nsresult Notification::OpenSettings(nsIPrincipal* aPrincipal) {
  MOZ_ASSERT(XRE_IsParentProcess());
  nsCOMPtr<nsIObserverService> obs = mozilla::services::GetObserverService();
  if (!obs) {
    return NS_ERROR_FAILURE;
  }
  // Notify other observers so they can show settings UI.
  obs->NotifyObservers(aPrincipal, "notifications-open-settings", nullptr);
  return NS_OK;
}

NS_IMETHODIMP
Notification::Observe(nsISupports* aSubject, const char* aTopic,
                      const char16_t* aData) {
  AssertIsOnMainThread();

  if (!strcmp(aTopic, DOM_WINDOW_DESTROYED_TOPIC) ||
      !strcmp(aTopic, DOM_WINDOW_FROZEN_TOPIC)) {
    nsCOMPtr<nsPIDOMWindowInner> window = GetOwner();
    if (SameCOMIdentity(aSubject, window)) {
      nsCOMPtr<nsIObserverService> obs =
          mozilla::services::GetObserverService();
      if (obs) {
        obs->RemoveObserver(this, DOM_WINDOW_DESTROYED_TOPIC);
        obs->RemoveObserver(this, DOM_WINDOW_FROZEN_TOPIC);
      }

      CloseInternal();
    }
  }

  return NS_OK;
}

nsresult Notification::DispatchToMainThread(
    already_AddRefed<nsIRunnable>&& aRunnable) {
  if (mWorkerPrivate) {
    return mWorkerPrivate->DispatchToMainThread(std::move(aRunnable));
  }
  AssertIsOnMainThread();
  if (nsCOMPtr<nsIGlobalObject> global = GetOwnerGlobal()) {
    if (nsIEventTarget* target = global->EventTargetFor(TaskCategory::Other)) {
      return target->Dispatch(std::move(aRunnable),
                              nsIEventTarget::DISPATCH_NORMAL);
    }
  }
  nsCOMPtr<nsIEventTarget> mainTarget = GetMainThreadEventTarget();
  MOZ_ASSERT(mainTarget);
  return mainTarget->Dispatch(std::move(aRunnable),
                              nsIEventTarget::DISPATCH_NORMAL);
}

}  // namespace dom
}  // namespace mozilla