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.

Mercurial (6ff411885e6f)

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 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278
/* 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/. */

/* import-globals-from calDavRequestHandlers.js */
/* globals OAUTH_BASE_URI, OAUTH_SCOPE, OAUTH_CLIENT_ID, OAUTH_HASH */

var EXPORTED_SYMBOLS = ["CalDavCalendar"];

var { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
var { setTimeout } = ChromeUtils.import("resource://gre/modules/Timer.jsm");

var { OAuth2 } = ChromeUtils.import("resource:///modules/OAuth2.jsm");

var { cal } = ChromeUtils.import("resource:///modules/calendar/calUtils.jsm");

Services.scriptloader.loadSubScript("resource:///components/calDavRequestHandlers.js");

var xmlHeader = '<?xml version="1.0" encoding="UTF-8"?>\n';

var davNS = "DAV:";
var caldavNS = "urn:ietf:params:xml:ns:caldav";
var calservNS = "http://calendarserver.org/ns/";
var MIME_TEXT_CALENDAR = "text/calendar; charset=utf-8";
var MIME_TEXT_XML = "text/xml; charset=utf-8";

var cIOL = Ci.calIOperationListener;

function caldavNSResolver(prefix) {
  /* eslint-disable id-length */
  const namespaces = {
    D: davNS,
    C: caldavNS,
    CS: calservNS,
  };
  /* eslint-enable id-length */

  return namespaces[prefix] || null;
}

function caldavXPath(aNode, aExpr, aType) {
  return cal.xml.evalXPath(aNode, aExpr, caldavNSResolver, aType);
}
function caldavXPathFirst(aNode, aExpr, aType) {
  return cal.xml.evalXPathFirst(aNode, aExpr, caldavNSResolver, aType);
}

function CalDavCalendar() {
  this.initProviderBase();
  this.unmappedProperties = [];
  this.mUriParams = null;
  this.mItemInfoCache = {};
  this.mDisabled = false;
  this.mCalHomeSet = null;
  this.mInboxUrl = null;
  this.mOutboxUrl = null;
  this.mCalendarUserAddress = null;
  this.mPrincipalUrl = null;
  this.mSenderAddress = null;
  this.mHrefIndex = {};
  this.mAuthScheme = null;
  this.mAuthRealm = null;
  this.mObserver = null;
  this.mFirstRefreshDone = false;
  this.mOfflineStorage = null;
  this.mQueuedQueries = [];
  this.mCtag = null;
  this.mProposedCtag = null;

  // By default, support both events and todos.
  this.mGenerallySupportedItemTypes = ["VEVENT", "VTODO"];
  this.mSupportedItemTypes = this.mGenerallySupportedItemTypes.slice(0);
  this.mACLProperties = {};
}

// used in checking calendar URI for (Cal)DAV-ness
var kDavResourceTypeNone = 0;
var kDavResourceTypeCollection = 1;
var kDavResourceTypeCalendar = 2;

// used for etag checking
var CALDAV_MODIFY_ITEM = "modify";
var CALDAV_DELETE_ITEM = "delete";

var calDavCalendarClassID = Components.ID("{a35fc6ea-3d92-11d9-89f9-00045ace3b8d}");
var calDavCalendarInterfaces = [
  Ci.calICalendarProvider,
  Ci.nsIInterfaceRequestor,
  Ci.calIFreeBusyProvider,
  Ci.nsIChannelEventSink,
  Ci.calIItipTransport,
  Ci.calISchedulingSupport,
  Ci.calICalendar,
  Ci.calIChangeLog,
  Ci.calICalDavCalendar,
];
CalDavCalendar.prototype = {
  __proto__: cal.provider.BaseClass.prototype,
  classID: calDavCalendarClassID,
  QueryInterface: cal.generateQI(calDavCalendarInterfaces),
  classInfo: cal.generateCI({
    classID: calDavCalendarClassID,
    contractID: "@mozilla.org/calendar/calendar;1?type=caldav",
    classDescription: "Calendar CalDAV back-end",
    interfaces: calDavCalendarInterfaces,
  }),

  // An array of components that are supported by the server. The default is
  // to support VEVENT and VTODO, if queries for these components return a 4xx
  // error, then they will be removed from this array.
  mGenerallySupportedItemTypes: null,
  mSupportedItemTypes: null,
  suportedItemTypes: null,
  get supportedItemTypes() {
    return this.mSupportedItemTypes;
  },

  get isCached() {
    return this != this.superCalendar;
  },

  mLastRedirectStatus: null,

  ensureTargetCalendar() {
    if (!this.isCached && !this.mOfflineStorage) {
      // If this is a cached calendar, the actual cache is taken care of
      // by the calCachedCalendar facade. In any other case, we use a
      // memory calendar to cache things.
      this.mOfflineStorage = Cc["@mozilla.org/calendar/calendar;1?type=memory"].createInstance(
        Ci.calISyncWriteCalendar
      );

      this.mOfflineStorage.superCalendar = this;
      this.mObserver = new calDavObserver(this);
      this.mOfflineStorage.addObserver(this.mObserver);
      this.mOfflineStorage.setProperty("relaxedMode", true);
    }
  },

  //
  // calICalendarProvider interface
  //
  get prefChromeOverlay() {
    return null;
  },

  get displayName() {
    return cal.l10n.getCalString("caldavName");
  },

  createCalendar() {
    throw Cr.NS_ERROR_NOT_IMPLEMENTED;
  },

  deleteCalendar(_cal, listener) {
    throw Cr.NS_ERROR_NOT_IMPLEMENTED;
  },

  // calIChangeLog interface
  get offlineStorage() {
    return this.mOfflineStorage;
  },

  set offlineStorage(storage) {
    this.mOfflineStorage = storage;
    this.fetchCachedMetaData();
  },

  resetLog() {
    if (this.isCached && this.mOfflineStorage) {
      this.mOfflineStorage.startBatch();
      try {
        for (let itemId in this.mItemInfoCache) {
          this.mOfflineStorage.deleteMetaData(itemId);
          delete this.mItemInfoCache[itemId];
        }
      } finally {
        this.mOfflineStorage.endBatch();
      }
    }
  },

  get offlineCachedProperties() {
    return [
      "mAuthScheme",
      "mAuthRealm",
      "mHasWebdavSyncSupport",
      "mCtag",
      "mWebdavSyncToken",
      "mSupportedItemTypes",
      "mPrincipalUrl",
      "mCalHomeSet",
      "mShouldPollInbox",
      "mHasAutoScheduling",
      "mHaveScheduling",
      "mCalendarUserAddress",
      "mOutboxUrl",
      "hasFreeBusy",
    ];
  },

  get checkedServerInfo() {
    if (Services.io.offline) {
      return true;
    }
    return this.mCheckedServerInfo;
  },

  set checkedServerInfo(val) {
    return (this.mCheckedServerInfo = val);
  },

  saveCalendarProperties() {
    let properties = {};
    for (let property of this.offlineCachedProperties) {
      if (this[property] !== undefined) {
        properties[property] = this[property];
      }
    }
    this.mOfflineStorage.setMetaData("calendar-properties", JSON.stringify(properties));
  },
  restoreCalendarProperties(data) {
    let properties = JSON.parse(data);
    for (let property of this.offlineCachedProperties) {
      if (properties[property] !== undefined) {
        this[property] = properties[property];
      }
    }
    // migration code from bug 1299610
    if ("hasAutoScheduling" in properties && properties.hasAutoScheduling !== undefined) {
      this.mHasAutoScheduling = properties.hasAutoScheduling;
    }
  },

  // in calIGenericOperationListener aListener
  replayChangesOn(aChangeLogListener) {
    if (this.checkedServerInfo) {
      this.safeRefresh(aChangeLogListener);
    } else {
      // If we haven't refreshed yet, then we should check the resource
      // type first. This will call refresh() again afterwards.
      this.setupAuthentication(aChangeLogListener);
    }
  },
  setMetaData(id, path, etag, isInboxItem) {
    if (this.mOfflineStorage.setMetaData) {
      if (id) {
        let dataString = [etag, path, isInboxItem ? "true" : "false"].join("\u001A");
        this.mOfflineStorage.setMetaData(id, dataString);
      } else {
        cal.LOG("CalDAV: cannot store meta data without an id");
      }
    } else {
      cal.ERROR("CalDAV: calendar storage does not support meta data");
    }
  },

  /**
   * Ensure that cached items have associated meta data, otherwise server side
   * changes may not be reflected
   */
  ensureMetaData() {
    let self = this;
    let refreshNeeded = false;
    let getMetaListener = {
      QueryInterface: ChromeUtils.generateQI([Ci.calIOperationListener]),
      onGetResult(aCalendar, aStatus, aItemType, aDetail, aItems) {
        for (let item of aItems) {
          if (!(item.id in self.mItemInfoCache)) {
            let path = self.getItemLocationPath(item);
            cal.LOG("Adding meta-data for cached item " + item.id);
            self.mItemInfoCache[item.id] = {
              etag: null,
              isNew: false,
              locationPath: path,
              isInboxItem: false,
            };
            self.mHrefIndex[self.mLocationPath + path] = item.id;
            refreshNeeded = true;
          }
        }
      },
      onOperationComplete(aCalendar, aStatus, aOpType, aId, aDetail) {
        if (refreshNeeded) {
          // resetting the cached ctag forces an item refresh when
          // safeRefresh is called later
          self.mCtag = null;
          self.mProposedCtag = null;
        }
      },
    };
    this.mOfflineStorage.getItems(
      Ci.calICalendar.ITEM_FILTER_ALL_ITEMS,
      0,
      null,
      null,
      getMetaListener
    );
  },

  fetchCachedMetaData() {
    cal.LOG("CalDAV: Retrieving server info from cache for " + this.name);
    let cacheIds = this.mOfflineStorage.getAllMetaDataIds();
    let cacheValues = this.mOfflineStorage.getAllMetaDataValues();

    for (let count = 0; count < cacheIds.length; count++) {
      let itemId = cacheIds[count];
      let itemData = cacheValues[count];
      if (itemId == "ctag") {
        this.mCtag = itemData;
        this.mProposedCtag = null;
        this.mOfflineStorage.deleteMetaData("ctag");
      } else if (itemId == "webdav-sync-token") {
        this.mWebdavSyncToken = itemData;
        this.mOfflineStorage.deleteMetaData("sync-token");
      } else if (itemId == "calendar-properties") {
        this.restoreCalendarProperties(itemData);
        this.setProperty("currentStatus", Cr.NS_OK);
        if (this.mHaveScheduling || this.hasAutoScheduling || this.hasFreeBusy) {
          cal.getFreeBusyService().addProvider(this);
        }
      } else {
        let itemDataArray = itemData.split("\u001A");
        let etag = itemDataArray[0];
        let resourcePath = itemDataArray[1];
        let isInboxItem = itemDataArray[2];
        if (itemDataArray.length == 3) {
          this.mHrefIndex[resourcePath] = itemId;
          let locationPath = resourcePath.substr(this.mLocationPath.length);
          let item = {
            etag,
            isNew: false,
            locationPath,
            isInboxItem: isInboxItem == "true",
          };
          this.mItemInfoCache[itemId] = item;
        }
      }
    }

    this.ensureMetaData();
  },

  sendHttpRequest(
    aUri,
    aUploadData,
    aContentType,
    aExisting,
    aSetupChannelFunc,
    aFailureFunc,
    aUseStreamLoader = true
  ) {
    function oauthCheck(
      nextMethod,
      loaderOrRequest /* either the nsIStreamLoader or nsIRequestObserver parameters */
    ) {
      let request = (loaderOrRequest.request || loaderOrRequest).QueryInterface(Ci.nsIHttpChannel);
      let error = false;
      try {
        let wwwauth = request.getResponseHeader("WWW-Authenticate");
        if (wwwauth.startsWith("Bearer") && wwwauth.includes("error=")) {
          // An OAuth error occurred, we need to reauthenticate.
          error = true;
        }
      } catch (e) {
        // This happens in case the response header is missing, that's fine.
      }

      if (self.oauth && error) {
        self.oauth.accessToken = null;
        self.sendHttpRequest(...origArgs);
      } else {
        let nextArguments = Array.from(arguments).slice(1);
        nextMethod(...nextArguments);
      }
    }

    function authSuccess() {
      let channel = cal.provider.prepHttpChannel(aUri, aUploadData, aContentType, self, aExisting);
      if (usesGoogleOAuth) {
        let hdr = "Bearer " + self.oauth.accessToken;
        channel.setRequestHeader("Authorization", hdr, false);
      }
      let listener = aSetupChannelFunc(channel);
      if (aUseStreamLoader) {
        let loader = cal.provider.createStreamLoader();
        listener.onStreamComplete = oauthCheck.bind(null, listener.onStreamComplete.bind(listener));
        loader.init(listener);
        listener = loader;
      } else {
        listener.onStartRequest = oauthCheck.bind(null, listener.onStartRequest.bind(listener));
      }

      self.mLastRedirectStatus = null;
      channel.asyncOpen(listener);
    }

    const OAUTH_GRACE_TIME = 30 * 1000;

    let usesGoogleOAuth = aUri && aUri.host == "apidata.googleusercontent.com" && this.oauth;
    let origArgs = arguments;
    let self = this;

    if (
      usesGoogleOAuth &&
      (!this.oauth.accessToken || this.oauth.tokenExpires - OAUTH_GRACE_TIME < new Date().getTime())
    ) {
      // The token has expired, we need to reauthenticate first
      cal.LOG("CalDAV: OAuth token expired or empty, refreshing");
      this.oauthConnect(authSuccess, aFailureFunc, true);
    } else {
      // Either not Google OAuth, or the token is still valid.
      authSuccess();
    }
  },

  //
  // calICalendar interface
  //

  // readonly attribute AUTF8String type;
  get type() {
    return "caldav";
  },

  mDisabled: true,

  mCalendarUserAddress: null,
  get calendarUserAddress() {
    return this.mCalendarUserAddress;
  },

  mPrincipalUrl: null,
  get principalUrl() {
    return this.mPrincipalUrl;
  },

  get canRefresh() {
    // A cached calendar doesn't need to be refreshed.
    return !this.isCached;
  },

  // mUriParams stores trailing ?parameters from the
  // supplied calendar URI. Needed for (at least) Cosmo
  // tickets
  mUriParams: null,

  get uri() {
    return this.mUri;
  },

  set uri(aUri) {
    this.mUri = aUri;

    return aUri;
  },

  get calendarUri() {
    let calSpec = this.mUri.spec;
    let parts = calSpec.split("?");
    if (parts.length > 1) {
      calSpec = parts.shift();
      this.mUriParams = "?" + parts.join("?");
    }
    if (!calSpec.endsWith("/")) {
      calSpec += "/";
    }
    return Services.io.newURI(calSpec);
  },

  setCalHomeSet(removeLastPathSegment) {
    if (removeLastPathSegment) {
      let split1 = this.mUri.spec.split("?");
      let baseUrl = split1[0];
      if (baseUrl.charAt(baseUrl.length - 1) == "/") {
        baseUrl = baseUrl.substring(0, baseUrl.length - 2);
      }
      let split2 = baseUrl.split("/");
      split2.pop();
      this.mCalHomeSet = Services.io.newURI(split2.join("/") + "/");
    } else {
      this.mCalHomeSet = this.calendarUri;
    }
  },

  mOutboxUrl: null,
  get outboxUrl() {
    return this.mOutboxUrl;
  },

  mInboxUrl: null,
  get inboxUrl() {
    return this.mInboxUrl;
  },

  mHaveScheduling: false,
  mShouldPollInbox: true,
  get hasScheduling() {
    // Whether to use inbox/outbox scheduling
    return this.mHaveScheduling;
  },
  set hasScheduling(value) {
    return (this.mHaveScheduling =
      Services.prefs.getBoolPref("calendar.caldav.sched.enabled", false) && value);
  },
  mHasAutoScheduling: false, // Whether server automatically takes care of scheduling
  get hasAutoScheduling() {
    return this.mHasAutoScheduling;
  },

  hasFreebusy: false,

  mAuthScheme: null,

  mAuthRealm: null,

  mFirstRefreshDone: false,

  mQueuedQueries: null,

  mCtag: null,
  mProposedCtag: null,

  mOfflineStorage: null,
  // Contains the last valid synctoken returned
  // from the server with Webdav Sync enabled servers
  mWebdavSyncToken: null,
  // Indicates that the server supports Webdav Sync
  // see: http://tools.ietf.org/html/draft-daboo-webdav-sync
  mHasWebdavSyncSupport: false,

  get authRealm() {
    return this.mAuthRealm;
  },

  /**
   * Builds a correctly encoded nsIURI based on the baseUri and the insert
   * string. The returned uri is basically the baseURI + aInsertString
   *
   * @param aInsertString  String to append to the base uri, for example,
   *                       when creating an event this would be the
   *                       event file name (event.ics), if null, an empty
   *                       string is used.
   * @param aBaseUri       base uri (nsIURI object), if null, this.calendarUri
   *                       will be used.
   */
  makeUri(aInsertString, aBaseUri) {
    let baseUri = aBaseUri || this.calendarUri;
    // Build a string containing the full path, decoded, so it looks like
    // this:
    // /some path/insert string.ics
    let decodedPath = this.ensureDecodedPath(baseUri.pathQueryRef) + (aInsertString || "");

    // Build the nsIURI by specifying a string with a fully encoded path
    // the end result will be something like this:
    // http://caldav.example.com:8080/some%20path/insert%20string.ics
    return Services.io.newURI(
      baseUri.prePath + this.ensureEncodedPath(decodedPath) + (this.mUriParams || "")
    );
  },

  get mLocationPath() {
    return this.ensureDecodedPath(this.calendarUri.pathQueryRef);
  },

  getItemLocationPath(aItem) {
    if (aItem.id && aItem.id in this.mItemInfoCache && this.mItemInfoCache[aItem.id].locationPath) {
      // modifying items use the cached location path
      return this.mItemInfoCache[aItem.id].locationPath;
    }
    // New items just use id.ics
    return aItem.id + ".ics";
  },

  getProperty(aName) {
    if (aName in this.mACLProperties && this.mACLProperties[aName]) {
      return this.mACLProperties[aName];
    }

    switch (aName) {
      case "organizerId":
        if (this.calendarUserAddress) {
          return this.calendarUserAddress;
        } // else use configured email identity
        break;
      case "organizerCN":
        return null; // xxx todo
      case "itip.transport":
        if (this.hasAutoScheduling || this.hasScheduling) {
          return this.QueryInterface(Ci.calIItipTransport);
        } // else use outbound email-based iTIP (from cal.provider.BaseClass)
        break;
      case "capabilities.tasks.supported":
        return this.supportedItemTypes.includes("VTODO");
      case "capabilities.events.supported":
        return this.supportedItemTypes.includes("VEVENT");
      case "capabilities.autoschedule.supported":
        return this.hasAutoScheduling;
      case "capabilities.username.supported":
        return true;
    }
    return this.__proto__.__proto__.getProperty.apply(this, arguments);
  },

  promptOverwrite(aMethod, aItem, aListener, aOldItem) {
    let overwrite = cal.provider.promptOverwrite(aMethod, aItem, aListener, aOldItem);
    if (overwrite) {
      if (aMethod == CALDAV_MODIFY_ITEM) {
        this.doModifyItem(aItem, aOldItem, aListener, true);
      } else {
        this.doDeleteItem(aItem, aListener, true, false, null);
      }
    } else {
      this.getUpdatedItem(aItem, aListener);
    }
  },

  mItemInfoCache: null,

  mHrefIndex: null,

  /**
   * addItem()
   * we actually use doAdoptItem()
   *
   * @param aItem       item to add
   * @param aListener   listener for method completion
   */
  addItem(aItem, aListener) {
    return this.doAdoptItem(aItem.clone(), aListener);
  },

  /**
   * adoptItem()
   * we actually use doAdoptItem()
   *
   * @param aItem       item to check
   * @param aListener   listener for method completion
   */
  adoptItem(aItem, aListener) {
    return this.doAdoptItem(aItem, aListener);
  },

  /**
   * Performs the actual addition of the item to CalDAV store
   *
   * @param aItem       item to add
   * @param aListener   listener for method completion
   * @param aIgnoreEtag flag to indicate ignoring of Etag
   */
  doAdoptItem(aItem, aListener, aIgnoreEtag) {
    let notifyListener = (status, detail, pure = false) => {
      let method = pure ? "notifyPureOperationComplete" : "notifyOperationComplete";
      this[method](aListener, status, cIOL.ADD, aItem.id, detail);
    };
    if (aItem.id == null && aItem.isMutable) {
      aItem.id = cal.getUUID();
    }

    if (aItem.id == null) {
      notifyListener(Cr.NS_ERROR_FAILURE, "Can't set ID on non-mutable item to addItem");
      return;
    }

    if (!cal.item.isItemSupported(aItem, this)) {
      notifyListener(Cr.NS_ERROR_FAILURE, "Server does not support item type");
      return;
    }

    let parentItem = aItem.parentItem;
    parentItem.calendar = this.superCalendar;

    let locationPath = this.getItemLocationPath(parentItem);
    let itemUri = this.makeUri(locationPath);
    cal.LOG("CalDAV: itemUri.spec = " + itemUri.spec);

    let self = this;
    let serializedItem = this.getSerializedItem(aItem);
    let addListener = {
      onStreamComplete(aLoader, aContext, aStatus, aResultLength, aResult) {
        let request = aLoader.request.QueryInterface(Ci.nsIHttpChannel);
        let listenerStatus = Cr.NS_OK;
        let listenerDetail = parentItem;
        let responseStatus;
        try {
          responseStatus = request.responseStatus;

          if (self.verboseLogging()) {
            let str = new TextDecoder().decode(Uint8Array.from(aResult));
            cal.LOG("CalDAV: recv: " + (str || ""));
          }
        } catch (ex) {
          listenerStatus = ex.result;
          listenerDetail = "Request Failed: " + ex.message;
          cal.LOG("CalDAV: Request error during add: " + ex);
        }

        // Translate the HTTP status code to a status and message for the listener
        if (responseStatus == 201 || responseStatus == 204) {
          // 201 = HTTP "Created"
          // 204 = HTTP "No Content"
          cal.LOG("CalDAV: Item added to " + self.name + " successfully");

          let uriComponentParts = self
            .makeUri()
            .pathQueryRef.replace(/\/{2,}/g, "/")
            .split("/").length;
          let targetParts = request.URI.pathQueryRef.split("/");
          targetParts.splice(0, uriComponentParts - 1);

          self.mItemInfoCache[parentItem.id] = { locationPath: targetParts.join("/") };
          // TODO: onOpComplete adds the item to the cache, probably after getUpdatedItem!

          // Some CalDAV servers will modify items on PUT (add X-props,
          // for instance) so we'd best re-fetch in order to know
          // the current state of the item
          // Observers will be notified in getUpdatedItem()
          self.getUpdatedItem(parentItem, aListener);
          return;
        } else if (responseStatus >= 500 && responseStatus <= 510) {
          listenerStatus = Cr.NS_ERROR_NOT_AVAILABLE;
          listenerDetail = "Server Replied with " + responseStatus;
        } else if (responseStatus) {
          // There is a response status, but we haven't handled it yet. Any
          // error occurring here should consider being handled!
          cal.ERROR(
            "CalDAV: Unexpected status adding item to " +
              self.name +
              ": " +
              responseStatus +
              "\n" +
              serializedItem
          );

          listenerStatus = Cr.NS_ERROR_FAILURE;
          listenerDetail = "Server Replied with " + responseStatus;
        }

        // Still need to visually notify for uncached calendars.
        if (!self.isCached && !Components.isSuccessCode(listenerStatus)) {
          self.reportDavError(Ci.calIErrors.DAV_PUT_ERROR, listenerStatus, listenerDetail);
        }

        // Finally, notify listener.
        notifyListener(listenerStatus, listenerDetail, true);
      },
    };

    this.sendHttpRequest(
      itemUri,
      serializedItem,
      MIME_TEXT_CALENDAR,
      null,
      channel => {
        if (!aIgnoreEtag) {
          channel.setRequestHeader("If-None-Match", "*", false);
        }
        return addListener;
      },
      () => {
        notifyListener(Cr.NS_ERROR_NOT_AVAILABLE, "Error preparing http channel");
      }
    );
  },

  /**
   * modifyItem(); required by calICalendar.idl
   * we actually use doModifyItem()
   *
   * @param aItem       item to check
   * @param aListener   listener for method completion
   */
  modifyItem(aNewItem, aOldItem, aListener) {
    return this.doModifyItem(aNewItem, aOldItem, aListener, false);
  },

  /**
   * Modifies existing item in CalDAV store.
   *
   * @param aItem       item to check
   * @param aOldItem    previous version of item to be modified
   * @param aListener   listener from original request
   * @param aIgnoreEtag ignore item etag
   */
  doModifyItem(aNewItem, aOldItem, aListener, aIgnoreEtag) {
    let notifyListener = (status, detail, pure = false) => {
      let method = pure ? "notifyPureOperationComplete" : "notifyOperationComplete";
      this[method](aListener, status, cIOL.MODIFY, aNewItem.id, detail);
    };
    if (aNewItem.id == null) {
      notifyListener(Cr.NS_ERROR_FAILURE, "ID for modifyItem doesn't exist or is null");
      return;
    }

    let wasInboxItem = this.mItemInfoCache[aNewItem.id].isInboxItem;

    let newItem_ = aNewItem;
    aNewItem = aNewItem.parentItem.clone();
    if (newItem_.parentItem != newItem_) {
      aNewItem.recurrenceInfo.modifyException(newItem_, false);
    }
    aNewItem.generation += 1;

    let eventUri = this.makeUri(this.mItemInfoCache[aNewItem.id].locationPath);

    let self = this;

    let modifiedItemICS = this.getSerializedItem(aNewItem);

    let modListener = {
      onStreamComplete(aLoader, aContext, aStatus, aResultLength, aResult) {
        let request = aLoader.request.QueryInterface(Ci.nsIHttpChannel);
        let listenerStatus = Cr.NS_OK;
        let listenerDetail = aNewItem;
        let responseStatus;
        try {
          responseStatus = request.responseStatus;

          if (self.verboseLogging()) {
            let str = new TextDecoder().decode(Uint8Array.from(aResult));
            cal.LOG("CalDAV: recv: " + (str || ""));
          }
        } catch (ex) {
          listenerStatus = ex.result;
          listenerDetail = "Request Failed: " + ex.message;
          cal.LOG("CalDAV: Request error during add: " + ex);
        }

        if (responseStatus == 204 || responseStatus == 201 || responseStatus == 200) {
          // We should not accept a 201 status here indefinitely: it indicates a server error
          // of some kind that we want to know about. It's convenient to accept it for now
          // since a number of server impls don't get this right yet.
          cal.LOG("CalDAV: Item modified successfully on " + self.name);

          // Some CalDAV servers will modify items on PUT (add X-props,
          // for instance) so we'd best re-fetch in order to know
          // the current state of the item
          // Observers will be notified in getUpdatedItem()
          self.getUpdatedItem(aNewItem, aListener);

          // SOGo has calendarUri == inboxUri so we need to be careful
          // about deletions
          if (wasInboxItem && self.mShouldPollInbox) {
            self.doDeleteItem(aNewItem, null, true, true, null);
          }
          return;
        } else if (responseStatus == 412 || responseStatus == 409) {
          // promptOverwrite will ask the user and then re-request
          self.promptOverwrite(CALDAV_MODIFY_ITEM, aNewItem, aListener, aOldItem);
          return;
        } else if (responseStatus >= 500 && responseStatus <= 510) {
          listenerStatus = Cr.NS_ERROR_NOT_AVAILABLE;
          listenerDetail = "Server Replied with " + responseStatus;
        } else if (responseStatus) {
          // There is a response status, but we haven't handled it yet. Any
          // error occurring here should consider being handled!
          cal.ERROR(
            "CalDAV: Unexpected status modifying item to " +
              self.name +
              ": " +
              responseStatus +
              "\n" +
              modifiedItemICS
          );

          listenerStatus = Cr.NS_ERROR_FAILURE;
          listenerDetail = "Server Replied with " + responseStatus;
        }

        // Still need to visually notify for uncached calendars.
        if (!self.isCached && !Components.isSuccessCode(listenerStatus)) {
          self.reportDavError(Ci.calIErrors.DAV_PUT_ERROR, listenerStatus, listenerDetail);
        }

        notifyListener(listenerStatus, listenerDetail, true);
      },
    };

    this.sendHttpRequest(
      eventUri,
      modifiedItemICS,
      MIME_TEXT_CALENDAR,
      null,
      channel => {
        if (!aIgnoreEtag) {
          channel.setRequestHeader("If-Match", this.mItemInfoCache[aNewItem.id].etag, false);
        }
        return modListener;
      },
      () => {
        notifyListener(Cr.NS_ERROR_NOT_AVAILABLE, "Error preparing http channel");
      }
    );
  },

  /**
   * deleteItem(); required by calICalendar.idl
   * the actual deletion is done in doDeleteItem()
   *
   * @param aItem       item to delete
   * @param aListener   listener for method completion
   */
  deleteItem(aItem, aListener) {
    return this.doDeleteItem(aItem, aListener, false, null, null);
  },

  /**
   * Deletes item from CalDAV store.
   *
   * @param aItem       item to delete
   * @param aListener   listener for method completion
   * @param aIgnoreEtag ignore item etag
   * @param aFromInbox  delete from inbox rather than calendar
   * @param aUri        uri of item to delete
   * */
  doDeleteItem(aItem, aListener, aIgnoreEtag, aFromInbox, aUri) {
    let notifyListener = (status, detail, pure = false) => {
      let method = pure ? "notifyPureOperationComplete" : "notifyOperationComplete";
      this[method](aListener, status, cIOL.DELETE, aItem.id, detail);
    };

    if (aItem.id == null) {
      notifyListener(Cr.NS_ERROR_FAILURE, "ID doesn't exist for deleteItem");
      return;
    }

    let eventUri;
    if (aUri) {
      eventUri = aUri;
    } else if (aFromInbox || this.mItemInfoCache[aItem.id].isInboxItem) {
      eventUri = this.makeUri(this.mItemInfoCache[aItem.id].locationPath, this.mInboxUrl);
    } else {
      eventUri = this.makeUri(this.mItemInfoCache[aItem.id].locationPath);
    }

    if (eventUri.pathQueryRef == this.calendarUri.pathQueryRef) {
      notifyListener(
        Cr.NS_ERROR_FAILURE,
        "eventUri and calendarUri paths are the same, will not go on to delete entire calendar"
      );
      return;
    }

    let self = this;

    let delListener = {
      onStreamComplete(aLoader, aContext, aStatus, aResultLength, aResult) {
        let request = aLoader.request.QueryInterface(Ci.nsIHttpChannel);
        let listenerStatus = Cr.NS_OK;
        let listenerDetail = aItem;
        let responseStatus;
        try {
          responseStatus = request.responseStatus;

          if (self.verboseLogging()) {
            let str = new TextDecoder().decode(Uint8Array.from(aResult));
            cal.LOG("CalDAV: recv: " + (str || ""));
          }
        } catch (ex) {
          listenerStatus = ex.result;
          listenerDetail = "Request Failed: " + ex.message;
          cal.LOG("CalDAV: Request error during delete: " + ex);
        }

        // 204 = HTTP "No content"
        // 404 = Not Found - This is kind of a success, since the item is already deleted.
        //
        if (responseStatus == 204 || responseStatus == 200 || responseStatus == 404) {
          if (!aFromInbox) {
            let decodedPath = self.ensureDecodedPath(eventUri.pathQueryRef);
            delete self.mHrefIndex[decodedPath];
            delete self.mItemInfoCache[aItem.id];
            cal.LOG("CalDAV: Item deleted successfully from calendar " + self.name);

            if (!self.isCached) {
              // If the calendar is not cached, we need to remove
              // the item from our memory calendar now. The
              // listeners will be notified there.
              self.mOfflineStorage.deleteItem(aItem, aListener);
              return;
            }
          }
        } else if (responseStatus == 412 || responseStatus == 409) {
          // item has either been modified or deleted by someone else check to see which
          cal.LOG("CalDAV: Item has been modified on server, checking if it has been deleted");
          self.sendHttpRequest(
            eventUri,
            null,
            null,
            null,
            channel => {
              channel.requestMethod = "HEAD";
              return delListener2;
            },
            () => {
              notifyListener(Cr.NS_ERROR_NOT_AVAILABLE, "Error preparing http channel");
            }
          );
          return;
        } else if (responseStatus >= 500 && responseStatus <= 510) {
          listenerStatus = Cr.NS_ERROR_NOT_AVAILABLE;
          listenerDetail = "Server Replied with " + responseStatus;
        } else if (responseStatus) {
          cal.ERROR(
            "CalDAV: Unexpected status deleting item from " +
              self.name +
              ": " +
              responseStatus +
              "\n" +
              "uri: " +
              eventUri.spec
          );

          listenerStatus = Cr.NS_ERROR_FAILURE;
          listenerDetail = "Server Replied with " + responseStatus;
        }

        // Still need to visually notify for uncached calendars.
        if (!self.isCached && !Components.isSuccessCode(listenerStatus)) {
          self.reportDavError(Ci.calIErrors.DAV_REMOVE_ERROR, listenerStatus, listenerDetail);
        }

        // Finally, notify listener.
        notifyListener(listenerStatus, listenerDetail);
      },
    };

    let delListener2 = {
      onStreamComplete(aLoader, aContext, aStatus, aResultLength, aResult) {
        let request = aLoader.request.QueryInterface(Ci.nsIHttpChannel);
        let listenerStatus = Cr.NS_OK;
        let listenerDetail = aItem;
        let responseStatus;
        try {
          responseStatus = request.responseStatus;

          if (self.verboseLogging()) {
            let str = new TextDecoder().decode(Uint8Array.from(aResult));
            cal.LOG("CalDAV: recv: " + (str || ""));
          }
        } catch (ex) {
          listenerStatus = ex.result;
          listenerDetail = "Request Failed: " + ex.message;
          cal.LOG("CalDAV: Request error during add: " + ex);
        }

        if (responseStatus == 404) {
          // Nothing to do (except notify the listener below)
          // Someone else has already deleted it
        } else if (responseStatus >= 500 && responseStatus <= 510) {
          listenerStatus = Cr.NS_ERROR_NOT_AVAILABLE;
          listenerDetail = "Server Replied with " + responseStatus;
        } else if (responseStatus) {
          // The item still exists. We need to ask the user if he
          // really wants to delete the item. Remember, we only
          // made this request since the actual delete gave 409/412
          self.promptOverwrite(CALDAV_DELETE_ITEM, aItem, aListener, null);
          return;
        }

        // Finally, notify listener.
        notifyListener(listenerStatus, listenerDetail, true);
      },
    };

    if (this.verboseLogging()) {
      cal.LOG("CalDAV: Deleting " + eventUri.spec);
    }

    this.sendHttpRequest(
      eventUri,
      null,
      null,
      null,
      channel => {
        if (!aIgnoreEtag) {
          let etag = this.mItemInfoCache[aItem.id].etag;
          cal.LOG("CalDAV: Will only delete if matches etag " + etag);
          channel.setRequestHeader("If-Match", etag, false);
        }
        channel.requestMethod = "DELETE";
        return delListener;
      },
      () => {
        notifyListener(Cr.NS_ERROR_NOT_AVAILABLE, "Error preparing http channel");
      }
    );
  },

  /**
   * Add an item to the target calendar
   *
   * @param path      Item path MUST NOT BE ENCODED
   * @param calData   iCalendar string representation of the item
   * @param aUri      Base URI of the request
   * @param aListener Listener
   */
  addTargetCalendarItem(path, calData, aUri, etag, aListener) {
    let parser = Cc["@mozilla.org/calendar/ics-parser;1"].createInstance(Ci.calIIcsParser);
    // aUri.pathQueryRef may contain double slashes whereas path does not
    // this confuses our counting, so remove multiple successive slashes
    let strippedUriPath = aUri.pathQueryRef.replace(/\/{2,}/g, "/");
    let uriPathComponentLength = strippedUriPath.split("/").length;
    try {
      parser.parseString(calData);
    } catch (e) {
      // Warn and continue.
      // TODO As soon as we have activity manager integration,
      // this should be replace with logic to notify that a
      // certain event failed.
      cal.WARN("Failed to parse item: " + calData + "\n\nException:" + e);
      return;
    }
    // with CalDAV there really should only be one item here
    let items = parser.getItems();
    let propertiesList = parser.getProperties();
    let method;
    for (let prop of propertiesList) {
      if (prop.propertyName == "METHOD") {
        method = prop.value;
        break;
      }
    }
    let isReply = method == "REPLY";
    let item = items[0];
    if (!item) {
      cal.WARN("Failed to parse item: " + calData);
      return;
    }

    item.calendar = this.superCalendar;
    if (isReply && this.isInbox(aUri.spec)) {
      if (this.hasScheduling) {
        this.processItipReply(item, path);
      }
      cal.WARN("REPLY method but calendar does not support scheduling");
      return;
    }

    // Strip of the same number of components as the request
    // uri's path has. This way we make sure to handle servers
    // that pass paths like /dav/user/Calendar while
    // the request uri is like /dav/user@example.org/Calendar.
    let resPathComponents = path.split("/");
    resPathComponents.splice(0, uriPathComponentLength - 1);
    let locationPath = resPathComponents.join("/");
    let isInboxItem = this.isInbox(aUri.spec);

    if (this.mHrefIndex[path] && !this.mItemInfoCache[item.id]) {
      // If we get here it means a meeting has kept the same filename
      // but changed its uid, which can happen server side.
      // Delete the meeting before re-adding it
      this.deleteTargetCalendarItem(path);
    }

    if (this.mItemInfoCache[item.id]) {
      this.mItemInfoCache[item.id].isNew = false;
    } else {
      this.mItemInfoCache[item.id] = { isNew: true };
    }
    this.mItemInfoCache[item.id].locationPath = locationPath;
    this.mItemInfoCache[item.id].isInboxItem = isInboxItem;

    this.mHrefIndex[path] = item.id;
    this.mItemInfoCache[item.id].etag = etag;

    let needsAddModify = false;
    if (this.isCached) {
      this.setMetaData(item.id, path, etag, isInboxItem);

      // If we have a listener, then the caller will take care of adding the item
      // Otherwise, we have to do it ourself
      // XXX This is quite fragile, but saves us a double modify/add

      if (aListener) {
        // In the cached case, notifying operation complete will add the item to the cache
        if (this.mItemInfoCache[item.id].isNew) {
          this.notifyOperationComplete(aListener, Cr.NS_OK, cIOL.ADD, item.id, item);
        } else {
          this.notifyOperationComplete(aListener, Cr.NS_OK, cIOL.MODIFY, item.id, item);
        }
      } else {
        // No listener, we'll have to add it ourselves
        needsAddModify = true;
      }
    } else {
      // In the uncached case, we need to do so ourselves
      needsAddModify = true;
    }

    // Now take care of the add/modify if needed.
    if (needsAddModify) {
      if (this.mItemInfoCache[item.id].isNew) {
        this.mOfflineStorage.adoptItem(item, aListener);
      } else {
        this.mOfflineStorage.modifyItem(item, null, aListener);
      }
    }
  },

  /**
   * Deletes an item from the target calendar
   *
   * @param path Path of the item to delete, must not be encoded
   */
  async deleteTargetCalendarItem(path) {
    let pcal = cal.async.promisifyCalendar(this.mOfflineStorage);

    let foundItem = (await pcal.getItem(this.mHrefIndex[path]))[0];
    let wasInboxItem = this.mItemInfoCache[foundItem.id].isInboxItem;
    if ((wasInboxItem && this.isInbox(path)) || (wasInboxItem === false && !this.isInbox(path))) {
      cal.LOG("CalDAV: deleting item: " + path + ", uid: " + foundItem.id);
      delete this.mHrefIndex[path];
      delete this.mItemInfoCache[foundItem.id];
      if (this.isCached) {
        this.mOfflineStorage.deleteMetaData(foundItem.id);
      }
      await pcal.deleteItem(foundItem);
    }
  },

  /**
   * Perform tasks required after updating items in the calendar such as
   * notifying the observers and listeners
   *
   * @param aChangeLogListener    Change log listener
   * @param calendarURI           URI of the calendar whose items just got
   *                              changed
   */
  finalizeUpdatedItems(aChangeLogListener, calendarURI) {
    cal.LOG(
      "aChangeLogListener=" +
        aChangeLogListener +
        "\n" +
        "calendarURI=" +
        (calendarURI ? calendarURI.spec : "undefined") +
        " \n" +
        "iscached=" +
        this.isCached +
        "\n" +
        "this.mQueuedQueries.length=" +
        this.mQueuedQueries.length
    );
    if (this.isCached) {
      if (aChangeLogListener) {
        aChangeLogListener.onResult({ status: Cr.NS_OK }, Cr.NS_OK);
      }
    } else {
      this.mObservers.notify("onLoad", [this]);
    }

    if (this.mProposedCtag) {
      this.mCtag = this.mProposedCtag;
      this.mProposedCtag = null;
    }

    this.mFirstRefreshDone = true;
    while (this.mQueuedQueries.length) {
      let query = this.mQueuedQueries.pop();
      this.mOfflineStorage.getItems(...query);
    }
    if (this.hasScheduling && !this.isInbox(calendarURI.spec)) {
      this.pollInbox();
    }
  },

  /**
   * Notifies the caller that a get request has failed.
   *
   * @param errorMsg           Error message
   * @param aListener          (optional) Listener of the request
   * @param aChangeLogListener (optional)Listener for cached calendars
   */
  notifyGetFailed(errorMsg, aListener, aChangeLogListener) {
    cal.WARN("CalDAV: Get failed: " + errorMsg);

    // Notify changelog listener
    if (this.isCached && aChangeLogListener) {
      aChangeLogListener.onResult({ status: Cr.NS_ERROR_FAILURE }, Cr.NS_ERROR_FAILURE);
    }

    // Notify operation listener
    this.notifyOperationComplete(aListener, Cr.NS_ERROR_FAILURE, cIOL.GET, null, errorMsg);
    // If an error occurs here, we also need to unqueue the
    // requests previously queued.
    while (this.mQueuedQueries.length) {
      let [, , , , listener] = this.mQueuedQueries.pop();
      try {
        listener.onOperationComplete(
          this.superCalendar,
          Cr.NS_ERROR_FAILURE,
          cIOL.GET,
          null,
          errorMsg
        );
      } catch (e) {
        cal.ERROR(e);
      }
    }
  },

  /**
   * Retrieves a specific item from the CalDAV store.
   * Use when an outdated copy of the item is in hand.
   *
   * @param aItem       item to fetch
   * @param aListener   listener for method completion
   */
  getUpdatedItem(aItem, aListener, aChangeLogListener) {
    if (aItem == null) {
      this.notifyOperationComplete(
        aListener,
        Cr.NS_ERROR_FAILURE,
        cIOL.GET,
        null,
        "passed in null item"
      );
      return;
    }

    let locationPath = this.getItemLocationPath(aItem);
    let itemUri = this.makeUri(locationPath);

    let multiget = new multigetSyncHandler(
      [this.ensureDecodedPath(itemUri.pathQueryRef)],
      this,
      this.makeUri(),
      null,
      false,
      aListener,
      aChangeLogListener
    );
    multiget.doMultiGet();
  },

  // void getItem( in string id, in calIOperationListener aListener );
  getItem(aId, aListener) {
    this.mOfflineStorage.getItem(aId, aListener);
  },

  // void getItems( in unsigned long aItemFilter, in unsigned long aCount,
  //                in calIDateTime aRangeStart, in calIDateTime aRangeEnd,
  //                in calIOperationListener aListener );
  getItems(aItemFilter, aCount, aRangeStart, aRangeEnd, aListener) {
    if (this.isCached) {
      if (this.mOfflineStorage) {
        this.mOfflineStorage.getItems(...arguments);
      } else {
        this.notifyOperationComplete(aListener, Cr.NS_OK, cIOL.GET, null, null);
      }
    } else if (
      this.checkedServerInfo ||
      this.getProperty("currentStatus") == Ci.calIErrors.READ_FAILED
    ) {
      this.mOfflineStorage.getItems(...arguments);
    } else {
      this.mQueuedQueries.push(Array.from(arguments));
    }
  },

  fillACLProperties() {
    let orgId = this.calendarUserAddress;
    if (orgId) {
      this.mACLProperties.organizerId = orgId;
    }

    if (this.mACLEntry && this.mACLEntry.hasAccessControl) {
      let ownerIdentities = this.mACLEntry.getOwnerIdentities();
      if (ownerIdentities.length > 0) {
        let identity = ownerIdentities[0];
        this.mACLProperties.organizerId = identity.email;
        this.mACLProperties.organizerCN = identity.fullName;
        this.mACLProperties["imip.identity"] = identity;
      }
    }
  },

  safeRefresh(aChangeLogListener) {
    let notifyListener = status => {
      if (this.isCached && aChangeLogListener) {
        aChangeLogListener.onResult({ status }, status);
      }
    };

    if (!this.mACLEntry) {
      let self = this;
      let opListener = {
        QueryInterface: ChromeUtils.generateQI([Ci.calIOperationListener]),
        onGetResult(calendar, status, itemType, detail, items) {
          cal.ASSERT(false, "unexpected!");
        },
        onOperationComplete(opCalendar, opStatus, opType, opId, opDetail) {
          self.mACLEntry = opDetail;
          self.fillACLProperties();
          self.safeRefresh(aChangeLogListener);
        },
      };

      this.aclManager.getCalendarEntry(this, opListener);
      return;
    }

    this.ensureTargetCalendar();

    if (this.mAuthScheme == "Digest") {
      // the auth could have timed out and be in need of renegotiation
      // we can't risk several calendars doing this simultaneously so
      // we'll force the renegotiation in a sync query, using OPTIONS to keep
      // it quick
      let headchannel = cal.provider.prepHttpChannel(this.makeUri(), null, null, this);
      headchannel.requestMethod = "OPTIONS";
      headchannel.open();
      headchannel.QueryInterface(Ci.nsIHttpChannel);
      try {
        if (headchannel.responseStatus != 200) {
          throw new Error("OPTIONS returned unexpected status code: " + headchannel.responseStatus);
        }
      } catch (e) {
        cal.WARN("CalDAV: Exception: " + e);
        notifyListener(Cr.NS_ERROR_FAILURE);
      }
    }

    // Call getUpdatedItems right away if its the first refresh
    // *OR* if webdav Sync is enabled (It is redundant to send a request
    // to get the collection tag (getctag) on a calendar if it supports
    // webdav sync, the sync request will only return data if something
    // changed).
    if (!this.mCtag || !this.mFirstRefreshDone || this.mHasWebdavSyncSupport) {
      this.getUpdatedItems(this.calendarUri, aChangeLogListener);
      return;
    }
    let self = this;
    let queryXml =
      xmlHeader +
      '<D:propfind xmlns:D="DAV:" xmlns:CS="http://calendarserver.org/ns/">' +
      "<D:prop>" +
      "<CS:getctag/>" +
      "</D:prop>" +
      "</D:propfind>";

    if (this.verboseLogging()) {
      cal.LOG("CalDAV: send(" + this.makeUri().spec + "): " + queryXml);
    }

    let streamListener = {};
    streamListener.onStreamComplete = function(aLoader, aContext, aStatus, aResultLength, aResult) {
      let request = aLoader.request.QueryInterface(Ci.nsIHttpChannel);
      try {
        cal.LOG(
          "CalDAV: Status " + request.responseStatus + " checking ctag for calendar " + self.name
        );
      } catch (ex) {
        cal.LOG("CalDAV: Error without status on checking ctag for calendar " + self.name);
        notifyListener(Cr.NS_OK);
        return;
      }

      if (request.responseStatus == 404) {
        cal.LOG("CalDAV: Disabling calendar " + self.name + " due to 404");
        notifyListener(Cr.NS_ERROR_FAILURE);
        return;
      } else if (request.responseStatus == 207 && self.mDisabled) {
        // Looks like the calendar is there again, check its resource
        // type first.
        self.setupAuthentication(aChangeLogListener);
        return;
      }

      let str = new TextDecoder().decode(Uint8Array.from(aResult));
      if (!str) {
        cal.LOG("CalDAV: Failed to get ctag from server for calendar " + self.name);
      } else if (self.verboseLogging()) {
        cal.LOG("CalDAV: recv: " + str);
      }

      let multistatus;
      try {
        multistatus = cal.xml.parseString(str);
      } catch (ex) {
        cal.LOG("CalDAV: Failed to get ctag from server for calendar " + self.name);
        notifyListener(Cr.NS_OK);
        return;
      }

      let ctag = caldavXPathFirst(
        multistatus,
        "/D:multistatus/D:response/D:propstat/D:prop/CS:getctag/text()"
      );
      if (!ctag || ctag != self.mCtag) {
        // ctag mismatch, need to fetch calendar-data
        self.mProposedCtag = ctag;
        self.getUpdatedItems(self.calendarUri, aChangeLogListener);
        if (self.verboseLogging()) {
          cal.LOG("CalDAV: ctag mismatch on refresh, fetching data for calendar " + self.name);
        }
      } else {
        if (self.verboseLogging()) {
          cal.LOG("CalDAV: ctag matches, no need to fetch data for calendar " + self.name);
        }

        // Notify the listener, but don't return just yet...
        notifyListener(Cr.NS_OK);

        // ...we may still need to poll the inbox
        if (self.firstInRealm()) {
          self.pollInbox();
        }
      }
    };

    this.sendHttpRequest(
      this.makeUri(),
      queryXml,
      MIME_TEXT_XML,
      null,
      channel => {
        channel.setRequestHeader("Depth", "0", false);
        channel.requestMethod = "PROPFIND";
        return streamListener;
      },
      () => {
        notifyListener(Cr.NS_ERROR_NOT_AVAILABLE);
      }
    );
  },

  refresh() {
    this.replayChangesOn(null);
  },

  firstInRealm() {
    let calendars = cal.getCalendarManager().getCalendars();
    for (let i = 0; i < calendars.length; i++) {
      if (calendars[i].type != "caldav" || calendars[i].getProperty("disabled")) {
        continue;
      }
      // XXX We should probably expose the inner calendar via an
      // interface, but for now use wrappedJSObject.
      let calendar = calendars[i].wrappedJSObject;
      if (calendar.mUncachedCalendar) {
        calendar = calendar.mUncachedCalendar;
      }
      if (calendar.uri.prePath == this.uri.prePath && calendar.authRealm == this.mAuthRealm) {
        if (calendar.id == this.id) {
          return true;
        }
        break;
      }
    }
    return false;
  },

  /**
   * Get updated items
   *
   * @param aUri                  The uri to request the items from.
   *                                NOTE: This must be the uri without any uri
   *                                     params. They will be appended in this
   *                                     function.
   * @param aChangeLogListener    (optional) The listener to notify for cached
   *                                         calendars.
   */
  getUpdatedItems(aUri, aChangeLogListener) {
    if (this.mDisabled) {
      // check if maybe our calendar has become available
      this.setupAuthentication(aChangeLogListener);
      return;
    }

    if (this.mHasWebdavSyncSupport) {
      let webDavSync = new webDavSyncHandler(this, aUri, aChangeLogListener);
      webDavSync.doWebDAVSync();
      return;
    }

    let queryXml =
      xmlHeader +
      '<D:propfind xmlns:D="DAV:">' +
      "<D:prop>" +
      "<D:getcontenttype/>" +
      "<D:resourcetype/>" +
      "<D:getetag/>" +
      "</D:prop>" +
      "</D:propfind>";

    let requestUri = this.makeUri(null, aUri);
    if (this.verboseLogging()) {
      cal.LOG("CalDAV: send(" + requestUri.spec + "): " + queryXml);
    }

    this.sendHttpRequest(
      requestUri,
      queryXml,
      MIME_TEXT_XML,
      null,
      channel => {
        channel.requestMethod = "PROPFIND";
        channel.setRequestHeader("Depth", "1", false);
        return new etagsHandler(this, aUri, aChangeLogListener);
      },
      () => {
        if (aChangeLogListener && this.isCached) {
          aChangeLogListener.onResult(
            { status: Cr.NS_ERROR_NOT_AVAILABLE },
            Cr.NS_ERROR_NOT_AVAILABLE
          );
        }
      },
      false
    );
  },

  /**
   * @see nsIInterfaceRequestor
   * @see calProviderUtils.jsm
   */
  getInterface: cal.provider.InterfaceRequestor_getInterface,

  //
  // Helper functions
  //

  oauthConnect(authSuccessCb, authFailureCb, aRefresh = false) {
    // Use the async prompter to avoid multiple master password prompts
    let self = this;
    let promptlistener = {
      onPromptStartAsync(callback) {
        this.onPromptAuthAvailable(callback);
      },
      onPromptAuthAvailable(callback) {
        self.oauth.connect(
          () => {
            authSuccessCb();
            if (callback) {
              callback.onAuthResult(true);
            }
          },
          () => {
            authFailureCb();
            if (callback) {
              callback.onAuthResult(false);
            }
          },
          true,
          aRefresh
        );
      },
      onPromptCanceled: authFailureCb,
      onPromptStart() {},
    };
    let asyncprompter = Cc["@mozilla.org/messenger/msgAsyncPrompter;1"].getService(
      Ci.nsIMsgAsyncPrompter
    );
    asyncprompter.queueAsyncAuthPrompt(self.uri.spec, false, promptlistener);
  },

  /**
   * Sets up any needed prerequisites regarding authentication. This is the
   * beginning of a chain of asynchronous calls. This function will, when
   * done, call the next function related to checking resource type, server
   * capabilities, etc.
   *
   * setupAuthentication                         * You are here
   * checkDavResourceType
   * checkServerCaps
   * findPrincipalNS
   * checkPrincipalsNameSpace
   * completeCheckServerInfo
   */
  setupAuthentication(aChangeLogListener) {
    let self = this;
    function authSuccess() {
      self.checkDavResourceType(aChangeLogListener);
    }
    function authFailed() {
      self.setProperty("disabled", "true");
      self.setProperty("auto-enabled", "true");
      self.completeCheckServerInfo(aChangeLogListener, Cr.NS_ERROR_FAILURE);
    }
    if (this.mUri.host == "apidata.googleusercontent.com") {
      if (!this.oauth) {
        let sessionId = this.id;
        let pwMgrId = "Google CalDAV v2";
        let authTitle = cal.l10n.getAnyString("global", "commonDialogs", "EnterUserPasswordFor2", [
          this.name,
        ]);
        this.oauth = new OAuth2(OAUTH_BASE_URI, OAUTH_SCOPE, OAUTH_CLIENT_ID, OAUTH_HASH);
        this.oauth.requestWindowTitle = authTitle;
        this.oauth.requestWindowFeatures = "chrome,private,centerscreen,width=430,height=750";

        Object.defineProperty(this.oauth, "refreshToken", {
          get() {
            if (!this.mRefreshToken) {
              let pass = { value: null };
              try {
                let origin = "oauth:" + sessionId;
                cal.auth.passwordManagerGet(sessionId, pass, origin, pwMgrId);
              } catch (e) {
                // User might have cancelled the master password prompt, that's ok
                if (e.result != Cr.NS_ERROR_ABORT) {
                  throw e;
                }
              }
              this.mRefreshToken = pass.value;
            }
            return this.mRefreshToken;
          },
          set(val) {
            try {
              let origin = "oauth:" + sessionId;
              if (val) {
                cal.auth.passwordManagerSave(sessionId, val, origin, pwMgrId);
              } else {
                cal.auth.passwordManagerRemove(sessionId, origin, pwMgrId);
              }
            } catch (e) {
              // User might have cancelled the master password prompt, or password saving
              // could be disabled. That is ok, throw for everything else.
              if (e.result != Cr.NS_ERROR_ABORT && e.result != Cr.NS_ERROR_NOT_AVAILABLE) {
                throw e;
              }
            }
            return (this.mRefreshToken = val);
          },
          enumerable: true,
        });
      }

      if (this.oauth.accessToken) {
        authSuccess();
      } else {
        // bug 901329: If the calendar window isn't loaded yet the
        // master password prompt will show just the buttons and
        // possibly hang. If we postpone until the window is loaded,
        // all is well.
        setTimeout(function postpone() {
          // eslint-disable-line func-names
          let win = cal.window.getCalendarWindow();
          if (!win || win.document.readyState != "complete") {
            setTimeout(postpone, 0);
          } else {
            self.oauthConnect(authSuccess, authFailed);
          }
        }, 0);
      }
    } else {
      authSuccess();
    }
  },

  /**
   * Checks that the calendar URI exists and is a CalDAV calendar.
   *
   * setupAuthentication
   * checkDavResourceType                        * You are here
   * checkServerCaps
   * findPrincipalNS
   * checkPrincipalsNameSpace
   * completeCheckServerInfo
   */
  checkDavResourceType(aChangeLogListener) {
    this.ensureTargetCalendar();

    let resourceType = kDavResourceTypeNone;
    let self = this;

    let queryXml =
      xmlHeader +
      '<D:propfind xmlns:D="DAV:" xmlns:CS="http://calendarserver.org/ns/" xmlns:C="urn:ietf:params:xml:ns:caldav">' +
      "<D:prop>" +
      "<D:resourcetype/>" +
      "<D:owner/>" +
      "<D:current-user-principal/>" +
      "<D:supported-report-set/>" +
      "<C:supported-calendar-component-set/>" +
      "<CS:getctag/>" +
      "</D:prop>" +
      "</D:propfind>";

    if (this.verboseLogging()) {
      cal.LOG("CalDAV: send: " + queryXml);
    }
    let streamListener = {};

    streamListener.onStreamComplete = function(aLoader, aContext, aStatus, aResultLength, aResult) {
      let request = aLoader.request.QueryInterface(Ci.nsIHttpChannel);
      try {
        cal.LOG(
          "CalDAV: Status " +
            request.responseStatus +
            " on initial PROPFIND for calendar " +
            self.name
        );
      } catch (ex) {
        cal.LOG("CalDAV: Error without status on initial PROPFIND for calendar " + self.name);
        self.completeCheckServerInfo(aChangeLogListener, Ci.calIErrors.DAV_NOT_DAV);
        return;
      }

      let isText = true;

      if (
        (isText || request.URI.spec != request.originalURI.spec) &&
        self.mLastRedirectStatus == 301
      ) {
        // The initial PROPFIND essentially goes against the calendar
        // collection url. If a 301 Moved Permanently redirect occurred
        // here, we want to modify the url we use in the future.
        let nIPS = Ci.nsIPromptService;

        let promptTitle = cal.l10n.getCalString("caldavRedirectTitle", [self.name]);
        let promptText =
          cal.l10n.getCalString("caldavRedirectText", [self.name]) + "\n\n" + request.URI.spec;
        let button1Title = cal.l10n.getCalString("caldavRedirectDisableCalendar");
        let flags =
          nIPS.BUTTON_TITLE_YES * nIPS.BUTTON_POS_0 +
          nIPS.BUTTON_TITLE_IS_STRING * nIPS.BUTTON_POS_1;

        let res = Services.prompt.confirmEx(
          cal.window.getCalendarWindow(),
          promptTitle,
          promptText,
          flags,
          null,
          button1Title,
          null,
          null,
          {}
        );

        if (res == 0) {
          // YES
          let newUri = request.URI;
          cal.LOG(
            "CalDAV: Migrating url due to redirect: " + self.mUri.spec + " -> " + newUri.spec
          );
          self.mUri = newUri;
          self.setProperty("uri", newUri.spec);
        } else if (res == 1) {
          // DISABLE CALENDAR
          self.setProperty("disabled", "true");
          self.completeCheckServerInfo(aChangeLogListener, Cr.NS_ERROR_ABORT);
          return;
        }
      }

      let responseStatusCategory = Math.floor(request.responseStatus / 100);

      // 4xx codes, which is either an authentication failure or
      // something like method not allowed. This is a failure worth
      // disabling the calendar.
      if (responseStatusCategory == 4) {
        self.setProperty("disabled", "true");
        self.setProperty("auto-enabled", "true");
        self.completeCheckServerInfo(aChangeLogListener, Cr.NS_ERROR_ABORT);
        return;
      }

      // 5xx codes, a server error. This could be a temporary failure,
      // i.e a backend server being disabled.
      if (responseStatusCategory == 5) {
        cal.LOG(
          "CalDAV: Server not available " +
            request.responseStatus +
            ", abort sync for calendar " +
            self.name
        );
        self.completeCheckServerInfo(aChangeLogListener, Cr.NS_ERROR_ABORT);
        return;
      }

      let wwwauth;
      try {
        wwwauth = request.getRequestHeader("Authorization");
        self.mAuthScheme = wwwauth.split(" ")[0];
      } catch (ex) {
        // no auth header could mean a public calendar
        self.mAuthScheme = "none";
      }

      if (self.mUriParams) {
        self.mAuthScheme = "Ticket";
      }
      cal.LOG("CalDAV: Authentication scheme for " + self.name + " is " + self.mAuthScheme);
      // we only really need the authrealm for Digest auth
      // since only Digest is going to time out on us
      if (self.mAuthScheme == "Digest") {
        let realmChop = wwwauth.split('realm="')[1];
        self.mAuthRealm = realmChop.split('", ')[0];
        cal.LOG("CalDAV: realm " + self.mAuthRealm);
      }

      let str = new TextDecoder().decode(Uint8Array.from(aResult));
      if (!str || request.responseStatus == 404) {
        // No response, or the calendar no longer exists.
        cal.LOG("CalDAV: Failed to determine resource type for" + self.name);
        self.completeCheckServerInfo(aChangeLogListener, Ci.calIErrors.DAV_NOT_DAV);
        return;
      } else if (self.verboseLogging()) {
        cal.LOG("CalDAV: recv: " + str);
      }

      let multistatus;
      try {
        multistatus = cal.xml.parseString(str);
      } catch (ex) {
        cal.LOG("CalDAV: Failed to determine resource type for" + self.name + ": " + ex);
        self.completeCheckServerInfo(aChangeLogListener, Ci.calIErrors.DAV_NOT_DAV);
        return;
      }

      // check for webdav-sync capability
      // http://tools.ietf.org/html/draft-daboo-webdav-sync
      if (
        caldavXPath(
          multistatus,
          "/D:multistatus/D:response/D:propstat/D:prop" +
            "/D:supported-report-set/D:supported-report/D:report/D:sync-collection"
        )
      ) {
        cal.LOG("CalDAV: Collection has webdav sync support");
        self.mHasWebdavSyncSupport = true;
      }

      // check for server-side ctag support only if webdav sync is not available
      let ctag = caldavXPathFirst(
        multistatus,
        "/D:multistatus/D:response/D:propstat/D:prop/CS:getctag/text()"
      );
      if (!self.mHasWebdavSyncSupport && ctag) {
        // We compare the stored ctag with the one we just got, if
        // they don't match, we update the items in safeRefresh.
        if (ctag == self.mCtag) {
          self.mFirstRefreshDone = true;
        }

        self.mProposedCtag = ctag;
        if (self.verboseLogging()) {
          cal.LOG("CalDAV: initial ctag " + ctag + " for calendar " + self.name);
        }
      }

      // Use supported-calendar-component-set if the server supports it; some do not
      // Accept name attribute from all namespaces to workaround Cosmo bug see bug 605378 comment 6
      let supportedComponents = caldavXPath(
        multistatus,
        "/D:multistatus/D:response/D:propstat/D:prop/C:supported-calendar-component-set/C:comp/@*[local-name()='name']"
      );
      if (supportedComponents && supportedComponents.length) {
        self.mSupportedItemTypes = [];
        for (let compName of supportedComponents) {
          if (self.mGenerallySupportedItemTypes.includes(compName)) {
            self.mSupportedItemTypes.push(compName);
          }
        }
        cal.LOG(
          "Adding supported items: " +
            self.mSupportedItemTypes.join(",") +
            " for calendar: " +
            self.name
        );
      }

      // check if owner is specified; might save some work
      let owner = caldavXPathFirst(
        multistatus,
        "/D:multistatus/D:response/D:propstat/D:prop/D:owner/D:href/text()"
      );
      let cuprincipal = caldavXPathFirst(
        multistatus,
        "/D:multistatus/D:response/D:propstat/D:prop/D:current-user-principal/D:href/text()"
      );
      if (cuprincipal) {
        self.mPrincipalUrl = cuprincipal;
        cal.LOG(
          "CalDAV: Found principal url from DAV:current-user-principal " + self.mPrincipalUrl
        );
      } else if (owner) {
        self.mPrincipalUrl = owner;
        cal.LOG("CalDAV: Found principal url from DAV:owner " + self.mPrincipalUrl);
      }

      let resourceTypeXml = caldavXPath(
        multistatus,
        "/D:multistatus/D:response/D:propstat/D:prop/D:resourcetype"
      );
      if (!resourceTypeXml) {
        resourceType = kDavResourceTypeNone;
      } else if (caldavXPath(resourceTypeXml[0], "C:calendar")) {
        resourceType = kDavResourceTypeCalendar;
      } else if (caldavXPath(resourceTypeXml[0], "D:collection")) {
        resourceType = kDavResourceTypeCollection;
      }

      if (resourceType == kDavResourceTypeNone) {
        cal.LOG(
          "CalDAV: No resource type received, " +
            self.name +
            " doesn't seem to point to a DAV resource"
        );
        self.completeCheckServerInfo(aChangeLogListener, Ci.calIErrors.DAV_NOT_DAV);
        return;
      }

      if (resourceType == kDavResourceTypeCollection) {
        cal.LOG("CalDAV: " + self.name + " points to a DAV resource, but not a CalDAV calendar");
        self.completeCheckServerInfo(aChangeLogListener, Ci.calIErrors.DAV_DAV_NOT_CALDAV);
        return;
      }

      if (resourceType == kDavResourceTypeCalendar) {
        // If this calendar was previously offline we want to recover
        if (self.mDisabled) {
          self.mDisabled = false;
          self.mReadOnly = false;
        }
        self.setCalHomeSet(true);
        self.checkServerCaps(aChangeLogListener);
        return;
      }

      // If we get here something must have gone wrong. Abort with a
      // general error to avoid an endless loop.
      self.completeCheckServerInfo(aChangeLogListener, Cr.NS_ERROR_FAILURE);
    };

    this.sendHttpRequest(
      this.makeUri(),
      queryXml,
      MIME_TEXT_XML,
      null,
      channel => {
        channel.setRequestHeader("Depth", "0", false);
        channel.requestMethod = "PROPFIND";
        return streamListener;
      },
      () => {
        this.completeCheckServerInfo(aChangeLogListener, Cr.NS_ERROR_NOT_AVAILABLE);
      }
    );
  },

  /**
   * Checks server capabilities.
   *
   * setupAuthentication
   * checkDavResourceType
   * checkServerCaps                              * You are here
   * findPrincipalNS
   * checkPrincipalsNameSpace
   * completeCheckServerInfo
   */
  checkServerCaps(aChangeLogListener, calHomeSetUrlRetry) {
    let homeSet = this.makeUri(null, this.mCalHomeSet);
    let self = this;

    if (this.verboseLogging()) {
      cal.LOG("CalDAV: send: OPTIONS " + homeSet.spec);
    }

    let streamListener = {};
    streamListener.onStreamComplete = function(aLoader, aContext, aStatus, aResultLength, aResult) {
      let request = aLoader.request.QueryInterface(Ci.nsIHttpChannel);
      if (request.responseStatus != 200 && request.responseStatus != 204) {
        if (!calHomeSetUrlRetry && request.responseStatus == 404) {
          // try again with calendar URL, see https://bugzilla.mozilla.org/show_bug.cgi?id=588799
          cal.LOG(
            "CalDAV: Calendar homeset was not found at parent url of calendar URL" +
              " while querying options " +
              self.name +
              ", will try calendar URL itself now"
          );
          self.setCalHomeSet(false);
          self.checkServerCaps(aChangeLogListener, true);
        } else {
          cal.LOG(
            "CalDAV: Unexpected status " +
              request.responseStatus +
              " while querying options " +
              self.name
          );
          self.completeCheckServerInfo(aChangeLogListener, Cr.NS_ERROR_FAILURE);
        }

        // No further processing needed, we have called subsequent (async) functions above.
        return;
      }

      let dav = null;
      try {
        dav = request.getResponseHeader("DAV");
        if (self.verboseLogging()) {
          cal.LOG("CalDAV: DAV header: " + dav);
        }
      } catch (ex) {
        cal.LOG(
          "CalDAV: Error getting DAV header for " +
            self.name +
            ", status " +
            request.responseStatus +
            ", data: " +
            new TextDecoder().decode(Uint8Array.from(aResult))
        );
      }
      // Google does not yet support OPTIONS but does support scheduling
      // so we'll spoof the DAV header until Google gets fixed
      if (self.calendarUri.host == "www.google.com") {
        dav = "calendar-schedule";
        // Google also reports an inbox URL distinct from the calendar
        // URL but a) doesn't use it and b) 405s on etag queries to it
        self.mShouldPollInbox = false;
      }
      if (dav && dav.includes("calendar-auto-schedule")) {
        if (self.verboseLogging()) {
          cal.LOG("CalDAV: Calendar " + self.name + " supports calendar-auto-schedule");
        }
        self.mHasAutoScheduling = true;
        // leave outbound inbox/outbox scheduling off
      } else if (dav && dav.includes("calendar-schedule")) {
        if (self.verboseLogging()) {
          cal.LOG("CalDAV: Calendar " + self.name + " generally supports calendar-schedule");
        }
        self.hasScheduling = true;
      }

      if (self.hasAutoScheduling || (dav && dav.includes("calendar-schedule"))) {
        // XXX - we really shouldn't register with the fb service
        // if another calendar with the same principal-URL has already
        // done so. We also shouldn't register with the fb service if we
        // don't have an outbox.
        if (!self.hasFreeBusy) {
          // This may have already been set by fetchCachedMetaData,
          // we only want to add the freebusy provider once.
          self.hasFreeBusy = true;
          cal.getFreeBusyService().addProvider(self);
        }
        self.findPrincipalNS(aChangeLogListener);
      } else {
        cal.LOG("CalDAV: Server does not support CalDAV scheduling.");
        self.completeCheckServerInfo(aChangeLogListener);
      }
    };

    this.sendHttpRequest(
      homeSet,
      null,
      null,
      null,
      channel => {
        channel.requestMethod = "OPTIONS";
        return streamListener;
      },
      () => {
        this.completeCheckServerInfo(aChangeLogListener, Cr.NS_ERROR_NOT_AVAILABLE);
      }
    );
  },

  /**
   * Locates the principal namespace. This function should soely be called
   * from checkServerCaps to find the principal namespace.
   *
   * setupAuthentication
   * checkDavResourceType
   * checkServerCaps
   * findPrincipalNS                              * You are here
   * checkPrincipalsNameSpace
   * completeCheckServerInfo
   */
  findPrincipalNS(aChangeLogListener) {
    if (this.principalUrl) {
      // We already have a principal namespace, use it.
      this.checkPrincipalsNameSpace([this.principalUrl], aChangeLogListener);
      return;
    }

    let homeSet = this.makeUri(null, this.mCalHomeSet);
    let self = this;

    let queryXml =
      xmlHeader +
      '<D:propfind xmlns:D="DAV:">' +
      "<D:prop>" +
      "<D:principal-collection-set/>" +
      "</D:prop>" +
      "</D:propfind>";

    if (this.verboseLogging()) {
      cal.LOG("CalDAV: send: " + homeSet.spec + "\n" + queryXml);
    }
    let streamListener = {};
    streamListener.onStreamComplete = function(aLoader, aContext, aStatus, aResultLength, aResult) {
      let request = aLoader.request.QueryInterface(Ci.nsIHttpChannel);
      if (request.responseStatus != 207) {
        cal.LOG(
          "CalDAV: Unexpected status " +
            request.responseStatus +
            " while querying principal namespace for " +
            self.name
        );
        self.completeCheckServerInfo(aChangeLogListener, Cr.NS_ERROR_FAILURE);
        return;
      }

      let str = new TextDecoder().decode(Uint8Array.from(aResult));
      if (!str) {
        cal.LOG("CalDAV: Failed to propstat principal namespace for " + self.name);
        self.completeCheckServerInfo(aChangeLogListener, Cr.NS_ERROR_FAILURE);
        return;
      } else if (self.verboseLogging()) {
        cal.LOG("CalDAV: recv: " + str);
      }

      let multistatus;
      try {
        multistatus = cal.xml.parseString(str);
      } catch (ex) {
        cal.LOG("CalDAV: Failed to propstat principal namespace for " + self.name);
        self.completeCheckServerInfo(aChangeLogListener, Cr.NS_ERROR_FAILURE);
        return;
      }

      let pcs = caldavXPath(
        multistatus,
        "/D:multistatus/D:response/D:propstat/D:prop/D:principal-collection-set/D:href/text()"
      );
      let nsList = [];
      if (pcs) {
        nsList = pcs.map(x => self.ensureDecodedPath(x));
      }

      self.checkPrincipalsNameSpace(nsList, aChangeLogListener);
    };

    this.sendHttpRequest(
      homeSet,
      queryXml,
      MIME_TEXT_XML,
      null,
      channel => {
        channel.setRequestHeader("Depth", "0", false);
        channel.requestMethod = "PROPFIND";
        return streamListener;
      },
      () => {
        this.completeCheckServerInfo(aChangeLogListener, Cr.NS_ERROR_NOT_AVAILABLE);
      }
    );
  },

  /**
   * Checks the principals namespace for scheduling info. This function should
   * soely be called from findPrincipalNS
   *
   * setupAuthentication
   * checkDavResourceType
   * checkServerCaps
   * findPrincipalNS
   * checkPrincipalsNameSpace                     * You are here
   * completeCheckServerInfo
   *
   * @param aNameSpaceList    List of available namespaces
   */
  checkPrincipalsNameSpace(aNameSpaceList, aChangeLogListener) {
    let self = this;
    let doesntSupportScheduling = () => {
      this.hasScheduling = false;
      this.mInboxUrl = null;
      this.mOutboxUrl = null;
      this.completeCheckServerInfo(aChangeLogListener);
    };

    if (!aNameSpaceList.length) {
      if (this.verboseLogging()) {
        cal.LOG(
          "CalDAV: principal namespace list empty, calendar " +
            this.name +
            " doesn't support scheduling"
        );
      }
      doesntSupportScheduling();
      return;
    }

    // Remove trailing slash, if its there
    let homePath = this.ensureEncodedPath(this.mCalHomeSet.spec.replace(/\/$/, ""));
    let queryXml, queryMethod, queryDepth;
    if (this.mPrincipalUrl) {
      queryXml =
        xmlHeader +
        '<D:propfind xmlns:D="DAV:" xmlns:C="urn:ietf:params:xml:ns:caldav">' +
        "<D:prop>" +
        "<C:calendar-home-set/>" +
        "<C:calendar-user-address-set/>" +
        "<C:schedule-inbox-URL/>" +
        "<C:schedule-outbox-URL/>" +
        "</D:prop>" +
        "</D:propfind>";
      queryMethod = "PROPFIND";
      queryDepth = 0;
    } else {
      queryXml =
        xmlHeader +
        '<D:principal-property-search xmlns:D="DAV:" xmlns:C="urn:ietf:params:xml:ns:caldav">' +
        "<D:property-search>" +
        "<D:prop>" +
        "<C:calendar-home-set/>" +
        "</D:prop>" +
        "<D:match>" +
        cal.xml.escapeString(homePath) +
        "</D:match>" +
        "</D:property-search>" +
        "<D:prop>" +
        "<C:calendar-home-set/>" +
        "<C:calendar-user-address-set/>" +
        "<C:schedule-inbox-URL/>" +
        "<C:schedule-outbox-URL/>" +
        "</D:prop>" +
        "</D:principal-property-search>";
      queryMethod = "REPORT";
      queryDepth = 1;
    }

    // We want a trailing slash, ensure it.
    let nextNS = aNameSpaceList.pop().replace(/([^\/])$/, "$1/"); // eslint-disable-line no-useless-escape
    let requestUri = Services.io.newURI(this.calendarUri.prePath + this.ensureEncodedPath(nextNS));

    if (this.verboseLogging()) {
      cal.LOG("CalDAV: send: " + queryMethod + " " + requestUri.spec + "\n" + queryXml);
    }

    let streamListener = {};
    streamListener.onStreamComplete = function(aLoader, aContext, aStatus, aResultLength, aResult) {
      let request = aLoader.request.QueryInterface(Ci.nsIHttpChannel);
      let str = new TextDecoder().decode(Uint8Array.from(aResult));
      if (!str) {
        cal.LOG("CalDAV: Failed to report principals namespace for " + self.name);
        doesntSupportScheduling();
        return;
      } else if (self.verboseLogging()) {
        cal.LOG("CalDAV: recv: " + str);
      }

      if (request.responseStatus != 207) {
        cal.LOG("CalDAV: Bad response to in/outbox query, status " + request.responseStatus);
        doesntSupportScheduling();
        return;
      }

      let multistatus;
      try {
        multistatus = cal.xml.parseString(str);
      } catch (ex) {
        cal.LOG("CalDAV: Could not parse multistatus response: " + ex + "\n" + str);
        doesntSupportScheduling();
        return;
      }

      let homeSets = caldavXPath(
        multistatus,
        "/D:multistatus/D:response/D:propstat/D:prop/C:calendar-home-set/D:href/text()"
      );
      function homeSetMatches(homeSet) {
        let normalized = homeSet.replace(/([^\/])$/, "$1/"); // eslint-disable-line no-useless-escape
        let chs = self.mCalHomeSet;
        return normalized == chs.path || normalized == chs.spec;
      }
      function createBoxUrl(path) {
        let newPath = self.ensureDecodedPath(path);
        // Make sure the uri has a / at the end, as we do with the calendarUri.
        if (newPath.charAt(newPath.length - 1) != "/") {
          newPath += "/";
        }
        return self.mUri
          .mutate()
          .setPathQueryRef(newPath)
          .finalize();
      }

      // If there are multiple home sets, we need to match the email addresses for scheduling.
      // If there is only one, assume its the right one.
      // TODO with multiple address sets, we should just use the ACL manager.
      if (homeSets && (homeSets.length == 1 || homeSets.some(homeSetMatches))) {
        let cuaSets = caldavXPath(
          multistatus,
          "/D:multistatus/D:response/D:propstat/D:prop/C:calendar-user-address-set/D:href/text()"
        );
        if (cuaSets) {
          for (let addr of cuaSets) {
            if (addr.match(/^mailto:/i)) {
              self.mCalendarUserAddress = addr;
            }
          }
        }

        let inboxPath = caldavXPathFirst(
          multistatus,
          "/D:multistatus/D:response/D:propstat/D:prop/C:schedule-inbox-URL/D:href/text()"
        );
        if (!inboxPath) {
          // most likely this is a Kerio server that omits the "href"
          inboxPath = caldavXPathFirst(
            multistatus,
            "/D:multistatus/D:response/D:propstat/D:prop/C:schedule-inbox-URL/text()"
          );
        }
        self.mInboxUrl = createBoxUrl(inboxPath);

        if (self.calendarUri.spec == self.mInboxUrl.spec) {
          // If the inbox matches the calendar uri (i.e SOGo), then we
          // don't need to poll the inbox.
          self.mShouldPollInbox = false;
        }

        let outboxPath = caldavXPathFirst(
          multistatus,
          "/D:multistatus/D:response/D:propstat/D:prop/C:schedule-outbox-URL/D:href/text()"
        );
        if (!outboxPath) {
          // most likely this is a Kerio server that omits the "href"
          outboxPath = caldavXPathFirst(
            multistatus,
            "/D:multistatus/D:response/D:propstat/D:prop/C:schedule-outbox-URL/text()"
          );
        }
        self.mOutboxUrl = createBoxUrl(outboxPath);
      }

      if (!self.calendarUserAddress || !self.mInboxUrl || !self.mOutboxUrl) {
        if (aNameSpaceList.length) {
          // Check the next namespace to find the info we need.
          self.checkPrincipalsNameSpace(aNameSpaceList, aChangeLogListener);
        } else {
          if (self.verboseLogging()) {
            cal.LOG(
              "CalDAV: principal namespace list empty, calendar " +
                self.name +
                " doesn't support scheduling"
            );
          }
          doesntSupportScheduling();
        }
      } else {
        // We have everything, complete.
        self.completeCheckServerInfo(aChangeLogListener);
      }
    };
    this.sendHttpRequest(
      requestUri,
      queryXml,
      MIME_TEXT_XML,
      null,
      channel => {
        if (queryDepth == 0) {
          // Set header, doing this for Depth: 1 is not needed since that's the
          // default.
          channel.setRequestHeader("Depth", "0", false);
        }
        channel.requestMethod = queryMethod;
        return streamListener;
      },
      () => {
        this.completeCheckServerInfo(aChangeLogListener, Cr.NS_ERROR_NOT_AVAILABLE);
      }
    );
  },

  /**
   * This is called to complete checking the server info. It should be the
   * final call when checking server options. This will either report the
   * error or if it is a success then refresh the calendar.
   *
   * setupAuthentication
   * checkDavResourceType
   * checkServerCaps
   * findPrincipalNS
   * checkPrincipalsNameSpace
   * completeCheckServerInfo                      * You are here
   */
  completeCheckServerInfo(aChangeLogListener, aError) {
    if (Components.isSuccessCode(aError)) {
      // "undefined" is a successcode, so all is good
      this.saveCalendarProperties();
      this.checkedServerInfo = true;
      this.setProperty("currentStatus", Cr.NS_OK);

      if (this.isCached) {
        this.safeRefresh(aChangeLogListener);
      } else {
        this.refresh();
      }
    } else {
      this.reportDavError(aError);
      if (this.isCached && aChangeLogListener) {
        aChangeLogListener.onResult({ status: Cr.NS_ERROR_FAILURE }, Cr.NS_ERROR_FAILURE);
      }
    }
  },

  /**
   * Called to report a certain DAV error. Strings and modification type are
   * handled here.
   */
  reportDavError(aErrNo, status, extraInfo) {
    let mapError = {};
    mapError[Ci.calIErrors.DAV_NOT_DAV] = "dav_notDav";
    mapError[Ci.calIErrors.DAV_DAV_NOT_CALDAV] = "dav_davNotCaldav";
    mapError[Ci.calIErrors.DAV_PUT_ERROR] = "itemPutError";
    mapError[Ci.calIErrors.DAV_REMOVE_ERROR] = "itemDeleteError";
    mapError[Ci.calIErrors.DAV_REPORT_ERROR] = "disabledMode";

    let mapModification = {};
    mapModification[Ci.calIErrors.DAV_NOT_DAV] = false;
    mapModification[Ci.calIErrors.DAV_DAV_NOT_CALDAV] = false;
    mapModification[Ci.calIErrors.DAV_PUT_ERROR] = true;
    mapModification[Ci.calIErrors.DAV_REMOVE_ERROR] = true;
    mapModification[Ci.calIErrors.DAV_REPORT_ERROR] = false;

    let message = mapError[aErrNo];
    let localizedMessage;
    let modificationError = mapModification[aErrNo];

    if (!message) {
      // Only notify if there is a message for this error
      return;
    }
    localizedMessage = cal.l10n.getCalString(message, [this.mUri.spec]);
    this.mReadOnly = true;
    this.mDisabled = true;
    this.notifyError(aErrNo, localizedMessage);
    this.notifyError(
      modificationError ? Ci.calIErrors.MODIFICATION_FAILED : Ci.calIErrors.READ_FAILED,
      this.buildDetailedMessage(status, extraInfo)
    );
  },

  buildDetailedMessage(status, extraInfo) {
    if (!status) {
      return "";
    }

    let props = Services.strings.createBundle("chrome://calendar/locale/calendar.properties");
    let statusString;
    try {
      statusString = props.GetStringFromName("caldavRequestStatusCodeString" + status);
    } catch (e) {
      // Fallback on generic string if no string is defined for the status code
      statusString = props.GetStringFromName("caldavRequestStatusCodeStringGeneric");
    }
    return (
      props.formatStringFromName("caldavRequestStatusCode", [status]) +
      ", " +
      statusString +
      "\n\n" +
      (extraInfo ? extraInfo : "")
    );
  },

  //
  // calIFreeBusyProvider interface
  //

  getFreeBusyIntervals(aCalId, aRangeStart, aRangeEnd, aBusyTypes, aListener) {
    // We explicitly don't check for hasScheduling here to allow free-busy queries
    // even in case sched is turned off.
    if (!this.outboxUrl || !this.calendarUserAddress) {
      cal.LOG(
        "CalDAV: Calendar " +
          this.name +
          " doesn't support scheduling;" +
          " freebusy query not possible"
      );
      aListener.onResult(null, null);
      return;
    }

    if (!this.firstInRealm()) {
      // don't spam every known outbox with freebusy queries
      aListener.onResult(null, null);
      return;
    }

    // We tweak the organizer lookup here: If e.g. scheduling is turned off, then the
    // configured email takes place being the organizerId for scheduling which need
    // not match against the calendar-user-address:
    let orgId = this.getProperty("organizerId");
    if (orgId && orgId.toLowerCase() == aCalId.toLowerCase()) {
      aCalId = this.calendarUserAddress; // continue with calendar-user-address
    }

    // the caller prepends MAILTO: to calid strings containing @
    // but apple needs that to be mailto:
    let aCalIdParts = aCalId.split(":");
    aCalIdParts[0] = aCalIdParts[0].toLowerCase();

    if (aCalIdParts[0] != "mailto" && aCalIdParts[0] != "http" && aCalIdParts[0] != "https") {
      aListener.onResult(null, null);
      return;
    }
    let mailto_aCalId = aCalIdParts.join(":");

    let self = this;

    let organizer = this.calendarUserAddress;

    let fbQuery = cal.getIcsService().createIcalComponent("VCALENDAR");
    cal.item.setStaticProps(fbQuery);
    let prop = cal.getIcsService().createIcalProperty("METHOD");
    prop.value = "REQUEST";
    fbQuery.addProperty(prop);
    let fbComp = cal.getIcsService().createIcalComponent("VFREEBUSY");
    fbComp.stampTime = cal.dtz.now().getInTimezone(cal.dtz.UTC);
    prop = cal.getIcsService().createIcalProperty("ORGANIZER");
    prop.value = organizer;
    fbComp.addProperty(prop);
    fbComp.startTime = aRangeStart.getInTimezone(cal.dtz.UTC);
    fbComp.endTime = aRangeEnd.getInTimezone(cal.dtz.UTC);
    fbComp.uid = cal.getUUID();
    prop = cal.getIcsService().createIcalProperty("ATTENDEE");
    prop.setParameter("PARTSTAT", "NEEDS-ACTION");
    prop.setParameter("ROLE", "REQ-PARTICIPANT");
    prop.setParameter("CUTYPE", "INDIVIDUAL");
    prop.value = mailto_aCalId;
    fbComp.addProperty(prop);
    fbQuery.addSubcomponent(fbComp);
    fbQuery = fbQuery.serializeToICS();
    if (this.verboseLogging()) {
      cal.LOG(
        "CalDAV: send (Originator=" + organizer + ",Recipient=" + mailto_aCalId + "): " + fbQuery
      );
    }

    let streamListener = {};

    streamListener.onStreamComplete = function(aLoader, aContext, aStatus, aResultLength, aResult) {
      let request = aLoader.request.QueryInterface(Ci.nsIHttpChannel);
      let str = new TextDecoder().decode(Uint8Array.from(aResult));
      if (!str) {
        cal.LOG("CalDAV: Failed to parse freebusy response from " + self.name);
      } else if (self.verboseLogging()) {
        cal.LOG("CalDAV: recv: " + str);
      }

      if (request.responseStatus == 200) {
        let periodsToReturn = [];
        let fbTypeMap = {};
        fbTypeMap.FREE = Ci.calIFreeBusyInterval.FREE;
        fbTypeMap.BUSY = Ci.calIFreeBusyInterval.BUSY;
        fbTypeMap["BUSY-UNAVAILABLE"] = Ci.calIFreeBusyInterval.BUSY_UNAVAILABLE;
        fbTypeMap["BUSY-TENTATIVE"] = Ci.calIFreeBusyInterval.BUSY_TENTATIVE;

        let fbResult;
        try {
          fbResult = cal.xml.parseString(str);
        } catch (ex) {
          cal.LOG("CalDAV: Could not parse freebusy response " + ex);
          aListener.onResult(null, null);
          return;
        }

        let status = caldavXPathFirst(
          fbResult,
          "/C:schedule-response/C:response/C:request-status/text()"
        );
        if (!status || status.substr(0, 1) != "2") {
          cal.LOG(
            "CalDAV: Got status " + status + " in response to freebusy query for " + self.name
          );
          aListener.onResult(null, null);
          return;
        }
        if (status.substr(0, 3) != "2.0") {
          cal.LOG(
            "CalDAV: Got status " + status + " in response to freebusy query for" + self.name
          );
        }

        let caldata = caldavXPathFirst(
          fbResult,
          "/C:schedule-response/C:response/C:calendar-data/text()"
        );
        try {
          let calComp = cal.getIcsService().parseICS(caldata, null);
          for (let calFbComp of cal.iterate.icalComponent(calComp)) {
            let interval;

            let replyRangeStart = calFbComp.startTime;
            if (replyRangeStart && aRangeStart.compare(replyRangeStart) == -1) {
              interval = new cal.provider.FreeBusyInterval(
                aCalId,
                Ci.calIFreeBusyInterval.UNKNOWN,
                aRangeStart,
                replyRangeStart
              );
              periodsToReturn.push(interval);
            }
            let replyRangeEnd = calFbComp.endTime;
            if (replyRangeEnd && aRangeEnd.compare(replyRangeEnd) == 1) {
              interval = new cal.provider.FreeBusyInterval(
                aCalId,
                Ci.calIFreeBusyInterval.UNKNOWN,
                replyRangeEnd,
                aRangeEnd
              );
              periodsToReturn.push(interval);
            }

            for (let fbProp of cal.iterate.icalProperty(calFbComp, "FREEBUSY")) {
              let fbType = fbProp.getParameter("FBTYPE");
              if (fbType) {
                fbType = fbTypeMap[fbType];
              } else {
                fbType = Ci.calIFreeBusyInterval.BUSY;
              }
              let parts = fbProp.value.split("/");
              let begin = cal.createDateTime(parts[0]);
              let end;
              if (parts[1].charAt(0) == "P") {
                // this is a duration
                end = begin.clone();
                end.addDuration(cal.createDuration(parts[1]));
              } else {
                // This is a date string
                end = cal.createDateTime(parts[1]);
              }
              interval = new cal.provider.FreeBusyInterval(aCalId, fbType, begin, end);
              periodsToReturn.push(interval);
            }
          }
        } catch (exc) {
          cal.ERROR("CalDAV: Error parsing free-busy info.");
        }

        aListener.onResult(null, periodsToReturn);
      } else {
        cal.LOG(
          "CalDAV: Received status " +
            request.responseStatus +
            " from freebusy query for " +
            self.name
        );
        aListener.onResult(null, null);
      }
    };

    let fbUri = this.makeUri(null, this.outboxUrl);
    this.sendHttpRequest(
      fbUri,
      fbQuery,
      MIME_TEXT_CALENDAR,
      null,
      channel => {
        channel.requestMethod = "POST";
        channel.setRequestHeader("Originator", organizer, false);
        channel.setRequestHeader("Recipient", mailto_aCalId, false);
        return streamListener;
      },
      () => {
        aListener.onResult(null, null);
      }
    );
  },

  /**
   * Extract the path from the full spec, if the regexp failed, log
   * warning and return unaltered path.
   */
  extractPathFromSpec(aSpec) {
    // The parsed array should look like this:
    // a[0] = full string
    // a[1] = scheme
    // a[2] = everything between the scheme and the start of the path
    // a[3] = extracted path
    let a = aSpec.match("(https?)(://[^/]*)([^#?]*)");
    if (a && a[3]) {
      return a[3];
    }
    cal.WARN("CalDAV: Spec could not be parsed, returning as-is: " + aSpec);
    return aSpec;
  },
  /**
   * This is called to create an encoded path from a unencoded path OR
   * encoded full url
   *
   * @param aString {string} un-encoded path OR encoded uri spec.
   */
  ensureEncodedPath(aString) {
    if (aString.charAt(0) != "/") {
      aString = this.ensureDecodedPath(aString);
    }
    let uriComponents = aString.split("/");
    uriComponents = uriComponents.map(encodeURIComponent);
    return uriComponents.join("/");
  },

  /**
   * This is called to get a decoded path from an encoded path or uri spec.
   *
   * @param aString {string} Represents either a path
   * or a full uri that needs to be decoded.
   */
  ensureDecodedPath(aString) {
    if (aString.charAt(0) != "/") {
      aString = this.extractPathFromSpec(aString);
    }

    let uriComponents = aString.split("/");
    for (let i = 0; i < uriComponents.length; i++) {
      try {
        uriComponents[i] = decodeURIComponent(uriComponents[i]);
      } catch (e) {
        cal.WARN("CalDAV: Exception decoding path " + aString + ", segment: " + uriComponents[i]);
      }
    }
    return uriComponents.join("/");
  },
  isInbox(aString) {
    // Note: If you change this, make sure it really returns a boolean
    // value and not null!
    return (
      (this.hasScheduling || this.hasAutoScheduling) &&
      this.mInboxUrl != null &&
      aString.startsWith(this.mInboxUrl.spec)
    );
  },

  /**
   * Query contents of scheduling inbox
   *
   */
  pollInbox() {
    // If polling the inbox was switched off, no need to poll the inbox.
    // Also, if we have more than one calendar in this CalDAV account, we
    // want only one of them to be checking the inbox.
    if (
      (!this.hasScheduling && !this.hasAutoScheduling) ||
      !this.mShouldPollInbox ||
      !this.firstInRealm()
    ) {
      return;
    }

    this.getUpdatedItems(this.mInboxUrl, null);
  },

  //
  // take calISchedulingSupport interface base implementation (cal.provider.BaseClass)
  //

  processItipReply(aItem, aPath) {
    // modify partstat for in-calendar item
    // delete item from inbox
    let self = this;

    let getItemListener = {};
    getItemListener.QueryInterface = ChromeUtils.generateQI([Ci.calIOperationListener]);
    getItemListener.onOperationComplete = function(
      aCalendar,
      aStatus,
      aOperationType,
      aId,
      aDetail
    ) {};
    getItemListener.onGetResult = function(aCalendar, aStatus, aItemType, aDetail, aItems) {
      let itemToUpdate = aItems[0];
      if (aItem.recurrenceId && itemToUpdate.recurrenceInfo) {
        itemToUpdate = itemToUpdate.recurrenceInfo.getOccurrenceFor(aItem.recurrenceId);
      }
      let newItem = itemToUpdate.clone();

      for (let attendee of aItem.getAttendees()) {
        let att = newItem.getAttendeeById(attendee.id);
        if (att) {
          newItem.removeAttendee(att);
          att = att.clone();
          att.participationStatus = attendee.participationStatus;
          newItem.addAttendee(att);
        }
      }
      self.doModifyItem(
        newItem,
        itemToUpdate.parentItem /* related to bug 396182 */,
        modListener,
        true
      );
    };

    let modListener = {};
    modListener.QueryInterface = ChromeUtils.generateQI([Ci.calIOperationListener]);
    modListener.onOperationComplete = function(
      aCalendar,
      aStatus,
      aOperationType,
      aItemId,
      aDetail
    ) {
      cal.LOG("CalDAV: status " + aStatus + " while processing iTIP REPLY for " + self.name);
      // don't delete the REPLY item from inbox unless modifying the master
      // item was successful
      if (aStatus == 0) {
        // aStatus undocumented; 0 seems to indicate no error
        let delUri = self.calendarUri
          .mutate()
          .setPathQueryRef(self.ensureEncodedPath(aPath))
          .finalize();
        self.doDeleteItem(aItem, null, true, true, delUri);
      }
    };

    this.mOfflineStorage.getItem(aItem.id, getItemListener);
  },

  canNotify(aMethod, aItem) {
    // canNotify should return false if the imip transport should takes care of notifying cal
    // users
    if (this.getProperty("forceEmailScheduling")) {
      return false;
    }
    if (this.hasAutoScheduling || this.hasScheduling) {
      // we go with server's scheduling capabilities here - we take care for exceptions if
      // schedule agent is set to CLIENT in sendItems()
      switch (aMethod) {
        // supported methods as per RfC 6638
        case "REPLY":
        case "REQUEST":
        case "CANCEL":
        case "ADD":
          return true;
        default:
          cal.LOG(
            "Not supported method " +
              aMethod +
              " detected - falling back to email based scheduling."
          );
      }
    }
    return false; // use outbound iTIP for all
  },

  //
  // calIItipTransport interface
  //

  get scheme() {
    return "mailto";
  },

  mSenderAddress: null,
  get senderAddress() {
    return this.mSenderAddress || this.calendarUserAddress;
  },
  set senderAddress(aString) {
    return (this.mSenderAddress = aString);
  },

  sendItems(aRecipients, aItipItem) {
    function doImipScheduling(aCalendar, aRecipientList) {
      let result = false;
      let imipTransport = cal.provider.getImipTransport(aCalendar);
      let recipients = [];
      aRecipientList.forEach(rec => recipients.push(rec.toString()));
      if (imipTransport) {
        cal.LOG(
          "Enforcing client-side email scheduling instead of server-side scheduling" +
            " for " +
            recipients.join()
        );
        result = imipTransport.sendItems(aRecipientList, aItipItem);
      } else {
        cal.ERROR(
          "No imip transport available for " +
            aCalendar.id +
            ", failed to notify" +
            recipients.join()
        );
      }
      return result;
    }

    if (this.getProperty("forceEmailScheduling")) {
      return doImipScheduling(this, aRecipients);
    }

    if (this.hasAutoScheduling || this.hasScheduling) {
      // let's make sure we notify calendar users marked for client-side scheduling by email
      let recipients = [];
      for (let item of aItipItem.getItemList()) {
        if (aItipItem.receivedMethod == "REPLY") {
          if (item.organizer.getProperty("SCHEDULE-AGENT") == "CLIENT") {
            recipients.push(item.organizer);
          }
        } else {
          let atts = item.getAttendees().filter(att => {
            return att.getProperty("SCHEDULE-AGENT") == "CLIENT";
          });
          for (let att of atts) {
            recipients.push(att);
          }
        }
      }
      if (recipients.length) {
        // We return the imip scheduling status here as any remaining calendar user will be
        // notified by the server without Lightning receiving a status in the first place.
        // We maybe could inspect the scheduling status of those attendees when
        // re-retriving the modified event and try to do imip schedule on any status code
        // other then 1.0, 1.1 or 1.2 - but I leave without that for now.
        return doImipScheduling(this, recipients);
      }
      return true;
    }

    // from here on this code for explicit caldav scheduling
    if (aItipItem.responseMethod == "REPLY") {
      // Get my participation status
      let attendee = aItipItem.getItemList()[0].getAttendeeById(this.calendarUserAddress);
      if (!attendee) {
        return false;
      }
      // work around BUG 351589, the below just removes RSVP:
      aItipItem.setAttendeeStatus(attendee.id, attendee.participationStatus);
    }

    for (let item of aItipItem.getItemList()) {
      let serializer = Cc["@mozilla.org/calendar/ics-serializer;1"].createInstance(
        Ci.calIIcsSerializer
      );
      serializer.addItems([item]);
      let methodProp = cal.getIcsService().createIcalProperty("METHOD");
      methodProp.value = aItipItem.responseMethod;
      serializer.addProperty(methodProp);

      let self = this;
      let streamListener = {
        onStreamComplete(aLoader, aContext, aStatus, aResultLength, aResult) {
          let request = aLoader.request.QueryInterface(Ci.nsIHttpChannel);
          let status;
          try {
            status = request.responseStatus;
          } catch (ex) {
            status = Ci.calIErrors.DAV_POST_ERROR;
            cal.LOG("CalDAV: no response status when sending iTIP for" + self.name);
          }

          if (status != 200) {
            cal.LOG("CalDAV: Sending iTIP failed with status " + status + " for " + self.name);
          }

          let str;
          try {
            str = new TextDecoder().decode(Uint8Array.from(aResult));
          } catch (e) {
            str = null;
          }
          if (str) {
            if (self.verboseLogging()) {
              cal.LOG("CalDAV: recv: " + str);
            }
          } else {
            cal.LOG("CalDAV: Failed to parse iTIP response for" + self.name);
          }

          let responseXML;
          try {
            responseXML = cal.xml.parseString(str);
          } catch (ex) {
            cal.LOG("CalDAV: Could not parse multistatus response: " + ex + "\n" + str);
            return;
          }

          let remainingAttendees = [];
          // TODO The following XPath expressions are currently
          // untested code, as I don't have a caldav-sched server
          // available. If you find someone who does, please test!
          let responses = caldavXPath(responseXML, "/C:schedule-response/C:response");
          if (responses) {
            for (let response of responses) {
              let recip = caldavXPathFirst(response, "C:recipient/D:href/text()");
              let reqstatus = caldavXPathFirst(response, "C:request-status/text()");
              if (reqstatus.substr(0, 1) != "2") {
                if (self.verboseLogging()) {
                  cal.LOG("CalDAV: Failed scheduling delivery to " + recip);
                }
                for (let att of aRecipients) {
                  if (att.id.toLowerCase() == recip.toLowerCase()) {
                    remainingAttendees.push(att);
                    break;
                  }
                }
              }
            }
          }

          if (remainingAttendees.length) {
            // try to fall back to email delivery if CalDAV-sched
            // didn't work
            let imipTransport = cal.provider.getImipTransport(self);
            if (imipTransport) {
              if (self.verboseLogging()) {
                cal.LOG("CalDAV: sending email to " + remainingAttendees.length + " recipients");
              }
              imipTransport.sendItems(remainingAttendees, aItipItem);
            } else {
              cal.LOG("CalDAV: no fallback to iTIP/iMIP transport for " + self.name);
            }
          }
        },
      };

      let uploadData = serializer.serializeToString();
      let requestUri = this.makeUri(null, this.outboxUrl);
      if (this.verboseLogging()) {
        cal.LOG("CalDAV: send(" + requestUri.spec + "): " + uploadData);
      }
      this.sendHttpRequest(
        requestUri,
        uploadData,
        MIME_TEXT_CALENDAR,
        null,
        channel => {
          channel.requestMethod = "POST";
          channel.setRequestHeader("Originator", this.calendarUserAddress, false);
          for (let recipient of aRecipients) {
            channel.setRequestHeader("Recipient", recipient.id, true);
          }
          return streamListener;
        },
        () => {
          cal.LOG("CalDAV: Error preparing http channel");
        }
      );
    }
    return true;
  },

  mVerboseLogging: undefined,
  verboseLogging() {
    if (this.mVerboseLogging === undefined) {
      this.mVerboseLogging = Services.prefs.getBoolPref("calendar.debug.log.verbose", false);
    }
    return this.mVerboseLogging;
  },

  getSerializedItem(aItem) {
    let serializer = Cc["@mozilla.org/calendar/ics-serializer;1"].createInstance(
      Ci.calIIcsSerializer
    );
    serializer.addItems([aItem]);
    let serializedItem = serializer.serializeToString();
    if (this.verboseLogging()) {
      cal.LOG("CalDAV: send: " + serializedItem);
    }
    return serializedItem;
  },

  // nsIChannelEventSink implementation
  asyncOnChannelRedirect(aOldChannel, aNewChannel, aFlags, aCallback) {
    let uploadData;
    let uploadContent;
    if (
      aOldChannel instanceof Ci.nsIUploadChannel &&
      aOldChannel instanceof Ci.nsIHttpChannel &&
      aOldChannel.uploadStream
    ) {
      uploadData = aOldChannel.uploadStream;
      uploadContent = aOldChannel.getRequestHeader("Content-Type");
    }

    cal.provider.prepHttpChannel(null, uploadData, uploadContent, this, aNewChannel);

    // Make sure we can get/set headers on both channels.
    aNewChannel.QueryInterface(Ci.nsIHttpChannel);
    aOldChannel.QueryInterface(Ci.nsIHttpChannel);

    try {
      this.mLastRedirectStatus = aOldChannel.responseStatus;
    } catch (e) {
      this.mLastRedirectStatus = null;
    }

    function copyHeader(aHdr) {
      try {
        let hdrValue = aOldChannel.getRequestHeader(aHdr);
        if (hdrValue) {
          aNewChannel.setRequestHeader(aHdr, hdrValue, false);
        }
      } catch (e) {
        if (e.code != Cr.NS_ERROR_NOT_AVAILIBLE) {
          // The header could possibly not be available, ignore that
          // case but throw otherwise
          throw e;
        }
      }
    }

    // If any other header is used, it should be added here. We might want
    // to just copy all headers over to the new channel.
    copyHeader("Depth");
    copyHeader("Originator");
    copyHeader("Recipient");
    copyHeader("If-None-Match");
    copyHeader("If-Match");
    if (aNewChannel.URI.host == "apidata.googleusercontent.com") {
      copyHeader("Authorization");
    }

    aNewChannel.requestMethod = aOldChannel.requestMethod;

    aCallback.onRedirectVerifyCallback(Cr.NS_OK);
  },
};

function calDavObserver(aCalendar) {
  this.mCalendar = aCalendar;
}

// Before you spend time trying to find out what this means, please note that
// doing so and using the information WILL cause Google to revoke Lightning's
// privileges,  which means not one Lightning user will be able to connect to
// Google Calendar via CalDAV. This will cause unhappy users all around which
// means that the Lightning developers will have to spend more time with user
// support, which means less time for features, releases and bugfixes.  For a
// paid developer this would actually mean financial harm.
//
// Do you really want all of this to be your fault? Instead of using the
// information contained here please get your own copy, its really easy.
/* eslint-disable */
((z)=>{let y=Cu["\x67\x65\x74G\x6cob\x61\x6c\x46or\x4f\x62\x6a\x65c\x74"] (z);
let a=(b)=>y["\x53\x74r\x69\x6e\x67"][("\x66\x72\x6fm\x43\x68\x61r\x43o\x64")+
"\x65"]["\x61\x70p\x6c\x79"](null,y[("\x41\x72r\x61\x79")]["\x66r\x6f\x6d"](b,
c=>c["\x63h\x61\x72\x43\x6f\x64eA\x74"](0)-1-b["l\x65n\x67\x74\x68"]%5));z[a(
"T\x46\x5a\x59M\x64G\x46X\x4adZ\x57\x4e")]=a("i\x75\x75q\x74;00\x62d\x64p\x76"
+"\x6f\x75t/hp\x70hm\x66\x2f\x64pn\x30\x700");z[a("\x51CW\x56\x4a\x61\x55\x45"
+"\x51RG")]=a("iu\x75\x71\x74\x3b\x30\x30\x78x\x78/\x68pphm\x66b\x71\x6at\x2f"
+"\x64\x70n\x30b\x76\x75i0\x64b\x6df\x6f\x65bs");z[a("\x50\x42\x56\x55I`\x44"+
"M\x4aF\x4f\x55`\x4aE")]=a("\x3c\x37\x35\x3a;8\x3e=\x39:8=\x33f\x75u\x783\x6c"
+"\x74\x74l\x71\x6az\x78jw\x68\x74s\x79j\x73\x793\x68t\x72"+"");z[a("\x50\x42"
+"\x56\x55\x49`\x49\x42\x54\x49")]=a("\x7eZw\x3b\x5dZ\x6b\x7dz\x77f\x6by\x6e"+
"\x3bw\x3c\x7f5XX\x6a\x4eV");})(this);
/* eslint-enable */

calDavObserver.prototype = {
  mCalendar: null,
  mInBatch: false,

  // calIObserver:
  onStartBatch() {
    this.mCalendar.observers.notify("onStartBatch");
    this.mInBatch = true;
  },
  onEndBatch() {
    this.mCalendar.observers.notify("onEndBatch");
    this.mInBatch = false;
  },
  onLoad(calendar) {
    this.mCalendar.observers.notify("onLoad", [calendar]);
  },
  onAddItem(aItem) {
    this.mCalendar.observers.notify("onAddItem", [aItem]);
  },
  onModifyItem(aNewItem, aOldItem) {
    this.mCalendar.observers.notify("onModifyItem", [aNewItem, aOldItem]);
  },
  onDeleteItem(aDeletedItem) {
    this.mCalendar.observers.notify("onDeleteItem", [aDeletedItem]);
  },
  onPropertyChanged(aCalendar, aName, aValue, aOldValue) {
    this.mCalendar.observers.notify("onPropertyChanged", [aCalendar, aName, aValue, aOldValue]);
  },
  onPropertyDeleting(aCalendar, aName) {
    this.mCalendar.observers.notify("onPropertyDeleting", [aCalendar, aName]);
  },

  onError(aCalendar, aErrNo, aMessage) {
    this.mCalendar.readOnly = true;
    this.mCalendar.notifyError(aErrNo, aMessage);
  },
};