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 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773
| // 订阅续期通知网站 - 基于CloudFlare Workers (完全优化版)
// 时区处理工具函数 // 常量:每秒转换为小时/天,全局复用 const MS_PER_HOUR = 1000 * 60 * 60; const MS_PER_DAY = MS_PER_HOUR * 24;
function getCurrentTimeInTimezone(timezone = 'UTC') { 尝试 { // Workers 环境下 Date 始终存储 UTC 时间,这里直接返回当前时间对象 返回新的 Date(); } catch (error) { console.error(`时区转换错误: ${error.message}`); // 如果时区无效,返回UTC时间 返回新的 Date(); } }
function getTimestampInTimezone(timezone = 'UTC') { 返回 getCurrentTimeInTimezone(timezone).getTime(); }
function convertUTCToTimezone(utcTime, timezone = 'UTC') { 尝试 { // 同 getCurrentTimeInTimezone,一律返回 Date 供后续统一处理 返回新的 Date(utcTime); } catch (error) { console.error(`时区转换错误: ${error.message}`); 返回新的 Date(utcTime); } }
// 获取指定时区的年/月/日/时/分/秒,可以避免重复的国际解析逻辑 function getTimezoneDateParts(date, timezone = 'UTC') { 尝试 { const formatter = new Intl.DateTimeFormat('en-US', { 时区:时区, hour12:否, 年份:'数字',月份:'两位数',日期:'两位数', 小时:两位数,分钟:两位数,秒:两位数 }); const parts = formatter.formatToParts(date); const pick = (type) => { const part = parts.find(item => item.type === type); 返回部件值?Number(部件.值) : 0; }; 返回 { 年份:pick('year'), 月份:选择('月份'), day: pick('day'), 小时:选择('小时'), 分钟:选择('分钟'), second: pick('second') }; } catch (error) { console.error(`解析时区(${timezone})失败: ${error.message}`); 返回 { 年份:date.getUTCFullYear(), 月份:date.getUTCMonth() + 1, day: date.getUTCDate(), 小时:date.getUTCHours(), 分钟:date.getUTCMinutes(), 秒:date.getUTCSeconds() }; } }
// 计算指定日期在目标时区的午夜(毫秒),用于统一的“剩余天数”计算 function getTimezoneMidnightTimestamp(date, timezone = 'UTC') { const { year, month, day } = getTimezoneDateParts(date, timezone); 返回 Date.UTC(年, 月 - 1, 日, 0, 0, 0); }
function calculateExpirationTime(expirationMinutes, timezone = 'UTC') { const currentTime = getCurrentTimeInTimezone(timezone); const expirationTime = new Date(currentTime.getTime() + (expirationMinutes * 60 * 1000)); 返回过期时间; }
function isExpired(targetTime, timezone = 'UTC') { const currentTime = getCurrentTimeInTimezone(timezone); const target = new Date(targetTime); 返回当前时间大于目标时间; }
function formatTimeInTimezone(time, timezone = 'UTC', format = 'full') { 尝试 { const date = new Date(time); 如果 (format === 'date') { 返回 date.toLocaleDateString('zh-CN', { 时区:时区, 年份:'数字', 月份:两位数, 日期:两位数 }); } else if (format === 'datetime') { 返回 date.toLocaleString('zh-CN', { 时区:时区, 年份:'数字', 月份:两位数, 日期:两位数 小时:两位数, 分钟:'两位数', 第二个:'两位数' }); } 别的 { // 完整格式 返回 date.toLocaleString('zh-CN', { 时区:时区 }); } } catch (error) { console.error(`时间整理错误: ${error.message}`); 返回新的 Date(time).toISOString(); } }
function getTimezoneOffset(timezone = 'UTC') { 尝试 { const now = new Date(); const { year, month, day, hour, minute, second } = getTimezoneDateParts(now, timezone); const zonedTimestamp = Date.UTC(year, month - 1, day, hour, minute, second); 返回 Math.round((zonedTimestamp - now.getTime()) / MS_PER_HOUR); } catch (error) { console.error(`获取时区偏移量错误: ${error.message}`); 返回 0; } }
// 格式化时区显示,包含UTC偏移 function formatTimezoneDisplay(timezone = 'UTC') { 尝试 { const offset = getTimezoneOffset(timezone); const offsetStr = offset >= 0 ? `+${offset}` : `${offset}`; // 时区中文名称地图 const timezoneNames = { 'UTC': '世界标准时间', '亚洲/上海': '中国标准时间', 'Asia/Hong_Kong': '香港时间', '亚洲/台北': '台北时间', '亚洲/新加坡': '新加坡时间', '亚洲/东京': '日本时间', '亚洲/首尔': '韩国时间', 'America/New_York': '美国东部时间', 'America/Los_Angeles': '美国太平洋时间', 'America/Chicago': '美国中部时间', 'America/Denver': '美国山地时间', '欧洲/伦敦': '英国时间', '欧洲/巴黎': '巴黎时间', 'Europe/Berlin': '柏林时间', '欧洲/莫斯科': '莫斯科时间', '澳大利亚/悉尼': '悉尼时间', '澳大利亚/墨尔本': '墨尔本时间', “太平洋/奥克兰”:“奥克兰时间” }; const timezoneName = timezoneNames[timezone] || timezone; 返回 `${timezoneName} (UTC${offsetStr})`; } catch (error) { console.error('格式化时区显示失败:', error); 返回时区; } }
// 兼容性函数 - 保持原有接口 function formatBeijingTime(date = new Date(), format = 'full') { return formatTimeInTimezone(date, 'Asia/Shanghai', format); }
// 时区处理中间件函数 function extractTimezone(request) { // 优先级:URL参数 > 请求头 > 默认值 const url = new URL(request.url); const timezoneParam = url.searchParams.get('timezone'); 如果 (timezoneParam) { 返回 timezoneParam; } // 从请求头获取时区 const timezoneHeader = request.headers.get('X-Timezone'); 如果 (timezoneHeader) { 返回时区标头; } // 从Accept-Language头推断时区(简化处理) const acceptLanguage = request.headers.get('Accept-Language'); 如果 (接受语言) { // 简单的时区推断逻辑 如果 (acceptLanguage.includes('zh')) { 返回'Asia/Shanghai'; } else if (acceptLanguage.includes('en-US')) { 返回'America/New_York'; } else if (acceptLanguage.includes('en-GB')) { 返回'Europe/London'; } } // 默认返回UTC 返回'UTC'; }
function isValidTimezone(timezone) { 尝试 { // 尝试使用该时区清理时间 new Date().toLocaleString('en-US', { timeZone: timezone }); 返回 true; } catch (error) { 返回 false; } }
// 农历转换工具函数 const lunarCalendar = { // 农历数据 (1900-2100年) lunarInfo: [ 0x04bd8、0x04ae0、0x0a570、0x054d5、0x0d260、0x0d950、0x16554、0x056a0、0x09ad0、0x055d2、 0x04ae0、0x0a5b6、0x0a4d0、0x0d250、0x1d255、0x0b540、0x0d6a0、0x0ada2、0x095b0、0x14977、 0x04970、0x0a4b0、0x0b4b5、0x06a50、0x06d40、0x1ab54、0x02b60、0x09570、0x052f2、0x04970 0x06566、0x0d4a0、0x0ea50、0x06e95、0x05ad0、0x02b60、0x186e3、0x092e0、0x1c8d7、0x0c950 0x0d4a0、0x1d8a6、0x0b550、0x056a0、0x1a5b4、0x025d0、0x092d0、0x0d2b2、0x0a950、0x0b557、 0x06ca0、0x0b550、0x15355、0x04da0、0x0a5b0、0x14573、0x052b0、0x0a9a8、0x0e950、0x06aa0 0x0aea6、0x0ab50、0x04b60、0x0aae4、0x0a570、0x05260、0x0f263、0x0d950、0x05b57、0x056a0、 0x096d0、0x04dd5、0x04ad0、0x0a4d0、0x0d4d4、0x0d250、0x0d558、0x0b540、0x0b6a0、0x195a6、 0x095b0、0x049b0、0x0a974、0x0a4b0、0x0b27a、0x06a50、0x06d40、0x0af46、0x0ab60、0x09570、 0x04af5、0x04970、0x064b0、0x074a3、0x0ea50、0x06b58、0x055c0、0x0ab60、0x096d5、0x092e0、 0x0c960、0x0d954、0x0d4a0、0x0da50、0x07552、0x056a0、0x0abb7、0x025d0、0x092d0、0x0cab5 0x0a950、0x0b4a0、0x0baa4、0x0ad50、0x055d9、0x04ba0、0x0a5b0、0x15176、0x052b0、0x0a930 0x07954、0x06aa0、0x0ad50、0x05b52、0x04b60、0x0a6e6、0x0a4e0、0x0d260、0x0ea65、0x0d530、 0x05aa0、0x076a3、0x096d0、0x04bd7、0x04ad0、0x0a4d0、0x1d0b6、0x0d250、0x0d520、0x0dd45、 0x0b5a0、0x056d0、0x055b2、0x049b0、0x0a577、0x0a4b0、0x0aa50、0x1b255、0x06d20、0x0ada0 ],
// 天干地支 干: ['甲', '乙', '丙', '丁', '戊', '己', '庚', '辛', '壬', '癸'], zhi: ['子', '丑', '寅', '卯', '辰', '巳', '午', '未', '申', '酉', '戌', '亥'],
// 农历月份 月份: ['正', '二', '三', '四', '五', '六', '七', '八', '九', '十', '冬', '腊'],
// 农历日期 days: ['初一', '初二', '初三', '初四', '初五', '初六', '初七', '初八', '初九', '初十', '十一', '十二', '十三', '十四', '十五', '十六', '十七', '十八', '十九', '二十', '二十一', '二十二', '二十三', '二十四', '二十五', '二十六', '二十七', '二十八', '二十九', '三十'],
// 获取农历年天数 lunarYearDays: function(year) { 令总和 = 348; for (let i = 0x8000; i > 0x8; i >>= 1) { sum += (this.lunarInfo[year - 1900] & i) ? 1 : 0; } 返回总和 + this.leapDays(year); },
//获取闰月天数 闰日:function(year) { 如果 (this.leapMonth(year)) { return (this.lunarInfo[year - 1900] & 0x10000) ? 30 : 29; } 返回 0; },
// 获取闰月月份 闰月:function(year) { 返回 this.lunarInfo[year - 1900] & 0xf; },
// 获取农历月天数 monthDays: function(year, month) { return (this.lunarInfo[year - 1900] & (0x10000 >> month)) ? 30 : 29; },
// 公历转农历 solar2lunar: function(year, month, day) { 如果(年份小于 1900 年或大于 2100 年)则返回 null;
const baseDate = new Date(1900, 0, 31); const objDate = new Date(year, month - 1, day); //let offset = Math.floor((objDate - baseDate) / 86400000); let offset = Math.round((objDate - baseDate) / 86400000);
let temp = 0; let lunarYear = 1900;
for (lunarYear = 1900; lunarYear < 2101 && offset > 0; lunarYear++) { temp = this.lunarYearDays(lunarYear); 偏移量 -= 温度; }
如果(偏移量 < 0){ 偏移量 += 温度; 农历年--; }
let lunarMonth = 1; let leap = this.leapMonth(lunarYear); let isLeap = false;
for (lunarMonth = 1; lunarMonth < 13 && offset > 0; lunarMonth++) { 如果(闰月 > 0 && 农历月份 === (闰月 + 1) && !isLeap){ --lunarMonth; isLeap = true; temp = this.leapDays(lunarYear); } 别的 { temp = this.monthDays(lunarYear, lunarMonth); }
如果(是闰月且农历月份等于(闰月 + 1))isLeap = false; 偏移量 -= 温度; }
如果(偏移量 === 0 && 闰月 > 0 && 农历月份 === 闰月 + 1){ 如果 (isLeap) { isLeap = false; } 别的 { isLeap = true; --lunarMonth; } }
如果(偏移量 < 0){ 偏移量 += 温度; --lunarMonth; }
const lunarDay = offset + 1;
// 生成农历字符串 const ganIndex = (lunarYear - 4) % 10; const zhiIndex = (lunarYear - 4) % 12; constyearStr = this.gan[ganIndex] + this.zhi[zhiIndex] + '年'; const MonthStr = (isLeap ? '闰' : '') + this.months[lunarMonth - 1] + '月'; const dayStr = this.days[lunarDay - 1];
返回 { 年份:农历年, 月份:农历月, 日期:农历日, isLeap:isLeap, yearStr: yearStr, monthStr: monthStr, dayStr: dayStr, 完整字符串:年份字符串 + 月份字符串 + 日期字符串 }; } };
// 1.新增lunarBiz工具模块,支持农历周期加、农历转公历、农历距离天数 const lunarBiz = { // 农历加周期,返回新的农历数据对象 addLunarPeriod(农历, periodValue, periodUnit) { let { year, month, day, isLeap } = lunar; 如果 (periodUnit === 'year') { 年份 += 时期值; const leap = lunarCalendar.leapMonth(year); 如果(是闰月 && 闰月 === 月份){ isLeap = true; } 别的 { isLeap = false; } } else if (periodUnit === 'month') { let totalMonths = (year - 1900) * 12 + (month - 1) + periodValue; 年份 = Math.floor(总月份 / 12) + 1900; 月份 = (总月份 % 12) + 1; const leap = lunarCalendar.leapMonth(year); 如果(是闰月 && 闰月 === 月份){ isLeap = true; } 别的 { isLeap = false; } } else if (periodUnit === 'day') { const solar = lunarBiz.lunar2solar(lunar); const date = new Date(solar.year, solar.month - 1, solar.day + periodValue); return lunarCalendar.solar2lunar(date.getFullYear(), date.getMonth() + 1, date.getDate()); } let maxDay = isLeap ? lunarCalendar.leapDays(year) : lunarCalendar.monthDays(year, month); let targetDay = Math.min(day, maxDay); while (targetDay > 0) { let solar = lunarBiz.lunar2solar({ year, month, day: targetDay, isLeap }); 如果(太阳能){ 返回 { year, month, day: targetDay, isLeap }; } 目标日期--; } 返回 { 年,月,日,是否为闰年 }; }, // 农历转公历(遍历法,适用1900-2100年) lunar2solar(lunar) { for (let y = lunar.year - 1; y <= lunar.year + 1; y++) { for (let m = 1; m <= 12; m++) { for (let d = 1; d <= 31; d++) { const date = new Date(y, m - 1, d); 如果(日期的完整年份不是 y,月份加 1 不是 m,日期的日期不是 d),则继续; const l=lunarCalendar.solar2lunar(y, m, d); 如果 ( l && l.year === 农历年 && l.month === lunar.month && l.day === 农历日 && l.isLeap === lunar.isLeap ) { 返回 { year: y, month: m, day: d }; } } } } 返回空值; }, // 距离农历日期还有多少天 daysToLunar(lunar) { const solar = lunarBiz.lunar2solar(lunar); const date = new Date(solar.year, solar.month - 1, solar.day); const now = new Date(); 返回 Math.ceil((date - now) / (1000 * 60 * 60 * 24)); } };
// 定义HTML模板 const loginPage = ` <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>订阅管理系统</title> <link href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css" rel="stylesheet"> <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css" rel="stylesheet"> <style> .login-container { background: linear-gradient(135deg, 最小高度:100vh; } .login-box { 背景滤镜:模糊(8px); background-color: rgba(255, 255, 255, 0.9); box-shadow: 0 10px 25px rgba(0, 0, 0, 0.15); } .btn-primary { background: linear-gradient(135deg, 过渡:全部 0.3 秒; } .btn-primary:hover { transform: translateY(-2px); box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1); } .input-field { 过渡:全部 0.3 秒; border: 1px solid } .input-field:focus { 边框颜色: box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.25); } </style> </head> <body class="login-container flex items-center justify-center"> <div class="login-box p-8 rounded-xl w-full max-w-md"> <div class="text-center mb-8"> <h1 class="text-2xl font-bold text-gray-800"><i class="fas fa-calendar-check mr-2"></i>订阅管理系统</h1> <p class="text-gray-600 mt-2">登录管理您的提醒订阅</p> </div> <form id="loginForm" class="space-y-6"> <div> <label for="username" class="block text-sm font-medium text-gray-700 mb-1"> <i class="fas fa-user mr-2"></i>用户名 </label> <input type="text" id="username" name="username" required class="input-field w-full px-4 py-3 rounded-lg text-gray-700 focus:outline-none"> </div> <div> <label for="password" class="block text-sm font-medium text-gray-700 mb-1"> <i class="fas fa-lock mr-2"></i>密码 </label> <input type="password" id="password" name="password" required class="input-field w-full px-4 py-3 rounded-lg text-gray-700 focus:outline-none"> </div> <button type="提交" class="btn-primary w-full py-3 rounded-lg text-white font-medium focus:outline-none"> <i class="fas fa-sign-in-alt mr-2"></i>登录 </button> <div id="errorMsg" class="text-red-500 text-center"></div> </form> </div> <script> document.getElementById('loginForm').addEventListener('submit', async (e) => { e.preventDefault(); const username = document.getElementById('username').value; const password = document.getElementById('password').value; const button = e.target.querySelector('button'); const OriginalContent = Button.innerHTML; button.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i>登录中...'; 按钮已禁用 = true; 尝试 { const response = await fetch('/api/login', { 方法:'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username, password }) }); const result = await response.json(); 如果 (结果成功) { window.location.href = '/admin'; } 别的 { document.getElementById('errorMsg').textContent = result.message || '用户名或密码错误'; 按钮.innerHTML = 原始内容; 按钮已禁用 = false; } } catch (error) { document.getElementById('errorMsg').textContent = '发生错误,请稍后再试'; 按钮.innerHTML = 原始内容; 按钮已禁用 = false; } }); </script> </body> </html> `;
const adminPage = ` <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>订阅管理系统</title> <link href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css" rel="stylesheet"> <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css" rel="stylesheet"> <style> .btn-primary { background: linear-gradient(135deg, .btn-primary:hover { transform: translateY(-2px); box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1); } .btn-danger { background: linear-gradient(135deg, .btn-danger:hover { transform: translateY(-2px); box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1); } .btn-success { background: linear-gradient(135deg, .btn-success:hover { transform: translateY(-2px); box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1); } .btn-warning { background: linear-gradient(135deg, .btn-warning:hover { transform: translateY(-2px); box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1); } .btn-info { background: linear-gradient(135deg, .btn-info:hover { transform: translateY(-2px); box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1); } .table-container { box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06); } .modal-container { background-filter: blur(8px); } .readonly-input { background-color: .error-message { font-size: 0.875rem; margin-top: 0.25rem; display: none; } .error-message.show { display: block; }
/* 通用悬浮提示优化 */ .hover-container { 位置:相对; 宽度:100%; } .hover-text { 最大宽度:100%; 溢出:隐藏; 文本溢出:省略号; 空格:不换行; 光标:指针; 过渡:全部缓动 0.3 秒; 显示:块; } .hover-text:hover { color: .hover-tooltip { 位置:固定; z-index:9999; 背景色: 颜色:白色; 内边距:10px 14px; 圆角半径:8px; 字体大小:0.875rem; 最大宽度:320像素; 换行:break-word; box-shadow: 0 10px 25px rgba(0, 0, 0, 0.2); 不透明度:0; 可见性:隐藏; 过渡:全部缓动 0.3 秒; transform: translateY(-10px); 空格:正常; 指针事件:无; 行高:1.4; } .hover-tooltip.show { 不透明度:1; 可见性:可见; 变换:translateY(0); } .hover-tooltip::before { 内容: ''; 位置:绝对定位; 顶部:-6px; 左侧:20像素; border-left: 6px solid transparent; border-right: 6px solid transparent; border-bottom: 6px solid } .hover-tooltip.tooltip-above::before { 顶部:自动; 底部:-6px; 底部边框:无; border-top: 6px solid }
/* 备注显示优化 */ .notes-container { 位置:相对; 最大宽度:200像素; 宽度:100%; } .notes-text { 最大宽度:100%; 溢出:隐藏; 文本溢出:省略号; 空格:不换行; 光标:指针; 过渡:全部缓动 0.3 秒; 显示:块; } .notes-text:hover { color: .notes-tooltip { 位置:固定; z-index:9999; 背景色: 颜色:白色; 内边距:10px 14px; 圆角半径:8px; 字体大小:0.875rem; 最大宽度:320像素; 换行:break-word; box-shadow: 0 10px 25px rgba(0, 0, 0, 0.2); 不透明度:0; 可见性:隐藏; 过渡:全部缓动 0.3 秒; transform: translateY(-10px); 空格:正常; 指针事件:无; 行高:1.4; } .notes-tooltip.show { 不透明度:1; 可见性:可见; 变换:translateY(0); } .notes-tooltip::before { 内容: ''; 位置:绝对定位; 顶部:-6px; 左侧:20像素; border-left: 6px solid transparent; border-right: 6px solid transparent; border-bottom: 6px solid } .notes-tooltip.tooltip-above::before { 顶部:自动; 底部:-6px; 底部边框:无; border-top: 6px solid }
/* 农历显示样式 */ .lunar-display { 字体大小:0.75rem; 颜色: margin-top: 2px; 不透明度:0; transition: opacity 0.3s ease; } .lunar-display.show { 不透明度:1; } /* 自定义日期选择器样式 */ .hidden { 显示:无!重要; } .custom-date-picker { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; box-shadow: 0 10px 25px rgba(0, 0, 0, 0.15); 圆角半径:12px; 最小宽度:380像素; } .custom-date-picker .calendar-day { 显示方式:flex; 弯曲方向:柱; align-items: center; justify-content: center; 宽度:48像素; 高度:60像素; 圆角半径:6px; 光标:指针; 过渡:全部缓动 0.2 秒; 位置:相对; 内边距:4px; 字体大小:14px; } .custom-date-picker .calendar-day:hover { 背景颜色: 变换:缩放(1.05); } .custom-date-picker .calendar-day.selected { 背景颜色: 颜色:白色; 变换:缩放(1.1); box-shadow: 0 2px 8px rgba(99, 102, 241, 0.3); } .custom-date-picker .calendar-day.today { 背景颜色: 颜色: 字体粗细:600; border: 2px solid } .custom-date-picker .calendar-day.other-month { 颜色: } .custom-date-picker .calendar-day .lunar-text { 字体大小:11像素; 行高:1.2; margin-top: 3px; 不透明度:0.85; 文本对齐方式:居中; 字体粗细:500; } .custom-date-picker .calendar-day.selected .lunar-text { 颜色:rgba(255, 255, 255, 0.9); } .custom-date-picker .calendar-day.today .lunar-text { 颜色: } /* 年份和年份选择器样式 */ .month-option, .year-option { 过渡:全部缓动 0.2 秒; border: 1px solid transparent; } .month-option:hover, .year-option:hover { background-color: 边框颜色: 颜色: } .month-option.selected, .year-option.selected { background-color: 颜色:白色; 边框颜色: } .lunar-toggle { 显示:内联弹性; align-items: center; margin-bottom: 8px; 字体大小:0.875rem; } .lunar-toggle 输入[type="checkbox"] { 右边距:6px; }
/* 表格布局优化 */ .table-container { 宽度:100%; 溢出:可见; }
.table-container 表格 { 表格布局:固定; 宽度:100%; }
/* 防止表单内容溢出 */ .table-container td { 溢出:隐藏; 换行:break-word; }
.truncate { 溢出:隐藏; 文本溢出:省略号; 空格:不换行; }
/* 响应式优化 */ .responsive-table { table-layout: fixed; width: 100%; } .td-content-wrapper { word-wrap: break-word; white-space: normal; text-align: left; width: 100%; } .td-content-wrapper > * { text-align: left; } /* 将容器内的内容左对齐 */
@media (max-width: 767px) { .table-container { overflow-x: initial; } /* 覆盖之前的设置 */ .responsive-table thead { display: none; } .responsive-table tbody, .responsive-table tr, .responsive-table td { display: block; width: 100%; } .responsive-table tr { margin-bottom: 1.5rem; border: 1px solid .responsive-table td { display: flex; justify-content: flex-start; align-items: center; padding: 0.75rem 1rem; border-bottom: 1px solid .responsive-table td:last-of-type { border-bottom: none; } .responsive-table td:before { content: attr(data-label); font-weight: 600; text-align: left; padding-right: 1rem; color: .action-buttons-wrapper { display: flex; flex-wrap: wrap; gap: 0.5rem; justify-content: flex-end; } .notes-container, .hover-container { max-width: 180px; /* 调整以适应新布局 */ 文本对齐方式:右对齐; } .td-content-wrapper .notes-text { 文本对齐方式:右对齐; } } @media (max-width: 767px) { 显示:无!重要; } } @media (min-width: 768px) { .table-container { 溢出:可见; } /* .td-content-wrapper 默认左对齐 */ }
/* 吐司样式 */ .toast { position: fixed; top: 20px; right: 20px; padding: 12px 20px; border-radius: 8px; 颜色:白色;字体粗细:500;z轴索引:1000;变换:translateX(400px); transition: all 0.3s ease-in-out; box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15); } .toast.show { transform: translateX(0); } .toast.success { background-color: .toast.error { background-color: .toast.info { background-color: .toast.warning { background-color: </style> </head> <body class="bg-gray-100 min-h-screen"> <div id="toast-container"></div>
<nav class="bg-white shadow-md"> <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8"> <div class="flex justify-between h-16"> <div class="flex items-center"> <i class="fas fa-calendar-check text-indigo-600 text-2xl mr-2"></i> <span class="font-bold text-xl text-gray-800">订阅管理系统</span> <span id="systemTimeDisplay" class="ml-4 text-base text-indigo-600 font-normal"></span> </div> <div class="flex items-center space-x-4"> <a href="/admin" class="text-indigo-600 border-b-2 border-indigo-600 px-3 py-2 rounded-md text-sm font-medium"> <i class="fas fa-list mr-1"></i>订阅列表 </a> <a href="/admin/config" class="text-gray-700 hover:text-gray-900 px-3 py-2 rounded-md text-sm font-medium"> <i class="fas fa-cog mr-1"></i>系统配置 </a> <a href="/api/logout" class="text-gray-700 hover:text-gray-900 px-3 py-2 rounded-md text-sm font-medium"> <i class="fas fa-sign-out-alt mr-1"></i>退出登录 </a> </div> </div> </div> </nav> <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8"> <div class="flex flex-col md:flex-row md:items-center md:justify-between gap-4 mb-6"> <div> <h2 class="text-2xl font-bold text-gray-800">订阅列表</h2> <p class="text-sm text-gray-500 mt-1">使用搜索与分类快速定位订阅,开启农历显示可同步查看农历日期</p> </div> <div class="flex flex-col lg:flex-row lg:items-center lg:justify-between gap-4 w-full"> <div class="flex flex-col sm:flex-row sm:items-center gap-3 w-full lg:flex-1 lg:max-w-2xl"> <div class="relative flex-1 min-w-[200px] lg:max-w-md"> <input type="text" id="searchKeyword" placeholder="搜索名称、类型或备注..." class="w-full pl-10 pr-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-indigo-500 focus:border-indigo-500"> <span class="absolute inset-y-0 left-0 pl-3 flex items-center text-gray-400"> <i class="fas fa-search"></i> </span> </div> <div class="sm:w-44 lg:w-40"> <select id="categoryFilter" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 bg-white"> <option value="">全部分类</option> </select> </div> </div> <div class="flex items-center space-x-3 lg:space-x-4"> <label class="lunar-toggle"> <input type="checkbox" id="listShowLunar" class="form-checkbox h-4 w-4 text-indigo-600 shrink-0"> <span class="text-gray-700">显示农历</span> </label> <button id="addSubscriptionBtn" class="btn-primary text-white px-4 py-2 rounded-md text-sm font-medium flex items-center shrink-0"> <i class="fas fa-plus mr-2"></i>添加新订阅 </button> </div> </div> </div> <div class="table-container bg-white rounded-lg overflow-hidden"> <div class="overflow-x-auto"> <table class="w-full divide-y divide-gray-200 responsive-table"> <thead class="bg-gray-50"> <tr> <th scope="col" class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider" style="width: 25%;"> 名称 </th> <th scope="col" class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider" style="width: 15%;"> 类型 </th> <th scope="col" class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider" style="width: 20%;"> 兑时间 <i class="fas fa-sort-up ml-1 text-indigo-500" title="按兑时间升序排列"></i> </th> <th scope="col" class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider" style="width: 15%;"> 提醒设置 </th> <th scope="col" class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider" style="width: 10%;"> 状态 </th> <th scope="col" class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider" style="width: 15%;"> 操作 </th> </tr> </thead> <tbody id="subscriptionsBody" class="bg-white divide-y divide-gray-200"> </tbody> </table> </div> </div> </div>
<!- 制作-/编辑订阅的模态框 --> <div id="subscriptionModal" class="fixed inset-0 bg-gray-600 bg-opacity-50 modal-container hidden flex items-center justify-center z-50"> <div class="bg-white rounded-lg shadow-xl max-w-2xl w-full mx-4 max-h-screen overflow-y-auto"> <div class="bg-gray-50 px-6 py-4 border-b border-gray-200 rounded-t-lg"> <div class="flex items-center justify-between"> <h3 id="modalTitle" class="text-lg font-medium text-gray-900">添加新订阅</h3> <button id="closeModal" class="text-gray-400 hover:text-gray-600"> <i class="fas fa-times text-xl"></i> </button> </div> </div> <form id="subscriptionForm" class="p-6 space-y-6"> <input type="hidden" id="subscriptionId"> <div class="grid grid-cols-1 md:grid-cols-3 gap-6"> <div> <label for="name" class="block text-sm font-medium text-gray-700 mb-1">订阅名称 *</label> <input type="text" id="name" required class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-indigo-500 focus:border-indigo-500"> <div class="error-message text-red-500" data-for="reminderValue"></div> </div> <div> <label for="customType" class="block text-sm font-medium text-gray-700 mb-1">订阅类型</label> <input type="text" id="customType" placeholder="例如:流媒体、云服务、软件、生日等" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-indigo-500 focus:border-indigo-500"> <div class="error-message text-red-500"></div> </div>
<div> <label for="category" class="block text-sm font-medium text-gray-700 mb-1">分类标签</label> <input type="text" id="category" placeholder="例如:个人、家庭、公司" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-indigo-500 focus:border-indigo-500"> <p class="mt-1 text-xs text-gray-500">可输入多个标签并使用“/”分隔,根据筛选和统计</p> <div class="error-message text-red-500"></div> </div> </div> <div class="mb-4 flex items-center space-x-6"> <label class="lunar-toggle"> <input type="checkbox" id="showLunar" class="form-checkbox h-4 w-4 text-indigo-600"> <span class="text-gray-700">显示农历日期</span> </label> <label class="lunar-toggle"> <input type="checkbox" id="useLunar" class="form-checkbox h-4 w-4 text-indigo-600"> <span class="text-gray-700">周期按农历</span> </label> </div>
<div class="grid grid-cols-1 md:grid-cols-4 gap-4"> <div class="md:col-span-2"> <label for="startDate" class="block text-sm font-medium text-gray-700 mb-1">开始日期</label> <div class="relative"> <input type="text" id="startDate" class="w-full px-3 py-2 pr-10 border border-gray-300 rounded-md focus:outline-none focus:ring-indigo-500 focus:border-indigo-500" placeholder="YYYY-MM-DD 或点击右侧图标选择"> <div class="absolute inset-y-0 right-0 flex items-center pr-3 pointer-events-none"> <i class="fas fa-calendar text-gray-400"></i> </div> <div id="startDatePicker" class="custom-date-picker hidden absolute top-full left-0 z-50 bg-white border border-gray-300 rounded-md shadow-lg p-6 min-w-[380px]"> <div class="flex justify-between items-center mb-4"> <button type="button" id="startDatePrevMonth" class="text-gray-600 hover:text-gray-800"> <i class="fas fa-chevron-left"></i> </button> <div class="flex items-center space-x-2"> <span id="startDateMonth" class="font-medium text-gray-900 cursor-pointer hover:text-indigo-600">1月</span> <span class="text-gray-400">|</span> <span id="startDateYear" class="font-medium text-gray-900 cursor-pointer hover:text-indigo-600">2024</span> </div> <button type="button" id="startDateNextMonth" class="text-gray-600 hover:text-gray-800"> <i class="fas fa-chevron-right"></i> </button> </div> <!-- 月份选择器 --> <div id="startDateMonthPicker" class="hidden mb-4"> <div class="flex justify-between items-center mb-3"> <span class="font-medium text-gray-900">选择月份</span> <button type="button" id="startDateBackToCalendar" class="text-gray-600 hover:text-gray-800"> <i class="fas fa-times"></i> </button> </div> <div class="grid grid-cols-3 gap-2"> <button type="button" class="month-option px-3 py-2 text-sm rounded hover:bg-gray-100" data-month="0">1月</button> <button type="button" class="month-option px-3 py-2 text-sm rounded hover:bg-gray-100" data-month="1">2月</button> <button type="button" class="month-option px-3 py-2 text-sm rounded hover:bg-gray-100" data-month="2">3月</button> <button type="button" class="month-option px-3 py-2 text-sm rounded hover:bg-gray-100" data-month="3">4月</button> <button type="button" class="month-option px-3 py-2 text-sm rounded hover:bg-gray-100" data-month="4">5月</button> <button type="button" class="month-option px-3 py-2 text-sm rounded hover:bg-gray-100" data-month="5">6月</button> <button type="button" class="month-option px-3 py-2 text-sm rounded hover:bg-gray-100" data-month="6">7月</button> <button type="button" class="month-option px-3 py-2 text-sm rounded hover:bg-gray-100" data-month="7">8月</button> <button type="button" class="month-option px-3 py-2 text-sm rounded hover:bg-gray-100" data-month="8">9月</button> <button type="button" class="month-option px-3 py-2 text-sm rounded hover:bg-gray-100" data-month="9">10月</button> <button type="button" class="month-option px-3 py-2 text-sm rounded hover:bg-gray-100" data-month="10">11月</button> <button type="button" class="month-option px-3 py-2 text-sm rounded hover:bg-gray-100" data-month="11">12月</button> </div> </div> <!-- 年份选择器 --> <div id="startDateYearPicker" class="hidden mb-4"> <div class="flex justify-between items-center mb-3"> <span class="font-medium text-gray-900">选择年份</span> <button type="button" id="startDateBackToCalendarFromYear" class="text-gray-600 hover:text-gray-800"> <i class="fas fa-times"></i> </button> </div> <div class="flex justify-between items-center mb-3"> <button type="button" id="startDatePrevYearDecade" class="text-gray-600 hover:text-gray-800"> <i class="fas fa-chevron-left"></i> </button> <span id="startDateYearRange" class="font-medium text-gray-900">2020-2029</span> <button type="button" id="startDateNextYearDecade" class="text-gray-600 hover:text-gray-800"> <i class="fas fa-chevron-right"></i> </button> </div> <div id="startDateYearGrid" class="grid grid-cols-3 gap-2"> <!-- 年份按钮将通过JavaScript动态生成 --> </div> </div> <div class="grid grid-cols-7 gap-2 mb-3"> <div class="text-center text-sm font-semibold text-gray-600 py-2">日</div> <div class="text-center text-sm font-semibold text-gray-600 py-2">一</div> <div class="text-center text-sm font-semibold text-gray-600 py-2">二</div> <div class="text-center text-sm font-semibold text-gray-600 py-2">三</div> <div class="text-center text-sm font-semibold text-gray-600 py-2">四</div> <div class="text-center text-sm font-semibold text-gray-600 py-2">五</div> <div class="text-center text-sm font-semibold text-gray-600 py-2">六</div> </div> <div id="startDateCalendar" class="grid grid-cols-7 gap-2"></div> <!-- 回到今天按钮 --> <div class="mt-4 pt-3 border-t border-gray-200"> <button type="button" id="startDateGoToToday" class="w-full px-3 py-2 text-sm text-indigo-600 hover:bg-indigo-50 rounded-md"> <i class="fas fa-calendar-day mr-2"></i>回到今天 </button> </div> </div> </div> <div id="startDateLunar" class="lunar-display"></div> <div class="error-message text-red-500"></div> </div> <div> <label for="periodValue" class="block text-sm font-medium text-gray-700 mb-1">周期数值 *</label> <input type="number" id="periodValue" min="1" value="1" required class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-indigo-500 focus:border-indigo-500"> <div class="error-message text-red-500"></div> </div> <div> <label for="periodUnit" class="block text-sm font-medium text-gray-700 mb-1">周期单位 *</label> <select id="periodUnit" 必填 class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-indigo-500 focus:border-indigo-500"> <option value="day">天</option> <option value="month" selected>月</option> <option value="year">年</option> </select> <div class="error-message text-red-500"></div> </div> </div> <div class="grid grid-cols-1 md:grid-cols-2 gap-6"> <div> <label for="expiryDate" class="block text-sm font-medium text-gray-700 mb-1">暴力日期 *</label> <div class="relative"> <input type="text" id="expiryDate" required class="w-full px-3 py-2 pr-10 border border-gray-300 rounded-md focus:outline-none focus:ring-indigo-500 focus:border-indigo-500" placeholder="YYYY-MM-DD 或点击右侧图标选择"> <div class="absolute inset-y-0 right-0 flex items-center pr-3 pointer-events-none"> <i class="fas fa-calendar text-gray-400"></i> </div> <div id="expiryDatePicker" class="custom-date-picker hidden absolute top-full left-0 z-50 bg-white border border-gray-300 rounded-md shadow-lg p-6 min-w-[380px]"> <div class="flex justify-between items-center mb-4"> <button type="button" id="expiryDatePrevMonth" class="text-gray-600 hover:text-gray-800"> <i class="fas fa-chevron-left"></i> </button> <div class="flex items-center space-x-2"> <span id="expiryDateMonth" class="font-medium text-gray-900 cursor-pointer hover:text-indigo-600">1月</span> <span class="text-gray-400">|</span> <span id="expiryDateYear" class="font-medium text-gray-900 cursor-pointer hover:text-indigo-600">2024</span> </div> <button type="button" id="expiryDateNextMonth" class="text-gray-600 hover:text-gray-800"> <i class="fas fa-chevron-right"></i> </button> </div> <!-- 月份选择器 --> <div id="expiryDateMonthPicker" class="hidden mb-4"> <div class="flex justify-between items-center mb-3"> <span class="font-medium text-gray-900">选择月份</span> <button type="button" id="expiryDateBackToCalendar" class="text-gray-600 hover:text-gray-800"> <i class="fas fa-times"></i> </button> </div> <div class="grid grid-cols-3 gap-2"> <button type="button" class="month-option px-3 py-2 text-sm rounded hover:bg-gray-100" data-month="0">1月</button> <button type="button" class="month-option px-3 py-2 text-sm rounded hover:bg-gray-100" data-month="1">2月</button> <button type="button" class="month-option px-3 py-2 text-sm rounded hover:bg-gray-100" data-month="2">3月</button> <button type="button" class="month-option px-3 py-2 text-sm rounded hover:bg-gray-100" data-month="3">4月</button> <button type="button" class="month-option px-3 py-2 text-sm rounded hover:bg-gray-100" data-month="4">5月</button> <button type="button" class="month-option px-3 py-2 text-sm rounded hover:bg-gray-100" data-month="5">6月</button> <button type="button" class="month-option px-3 py-2 text-sm rounded hover:bg-gray-100" data-month="6">7月</button> <button type="button" class="month-option px-3 py-2 text-sm rounded hover:bg-gray-100" data-month="7">8月</button> <button type="button" class="month-option px-3 py-2 text-sm rounded hover:bg-gray-100" data-month="8">9月</button> <button type="button" class="month-option px-3 py-2 text-sm rounded hover:bg-gray-100" data-month="9">10月</button> <button type="button" class="month-option px-3 py-2 text-sm rounded hover:bg-gray-100" data-month="10">11月</button> <button type="button" class="month-option px-3 py-2 text-sm rounded hover:bg-gray-100" data-month="11">12月</button> </div> </div> <!-- 年份选择器 --> <div id="expiryDateYearPicker" class="hidden mb-4"> <div class="flex justify-between items-center mb-3"> <span class="font-medium text-gray-900">选择年份</span> <button type="button" id="expiryDateBackToCalendarFromYear" class="text-gray-600 hover:text-gray-800"> <i class="fas fa-times"></i> </button> </div> <div class="flex justify-between items-center mb-3"> <button type="button" id="expiryDatePrevYearDecade" class="text-gray-600 hover:text-gray-800"> <i class="fas fa-chevron-left"></i> </button> <span id="expiryDateYearRange" class="font-medium text-gray-900">2020-2029</span> <button type="button" id="expiryDateNextYearDecade" class="text-gray-600 hover:text-gray-800"> <i class="fas fa-chevron-right"></i> </button> </div> <div id="expiryDateYearGrid" class="grid grid-cols-3 gap-2"> <!-- 年份按钮将通过JavaScript动态生成 --> </div> </div> <div class="grid grid-cols-7 gap-2 mb-3"> <div class="text-center text-sm font-semibold text-gray-600 py-2">日</div> <div class="text-center text-sm font-semibold text-gray-600 py-2">一</div> <div class="text-center text-sm font-semibold text-gray-600 py-2">二</div> <div class="text-center text-sm font-semibold text-gray-600 py-2">三</div> <div class="text-center text-sm font-semibold text-gray-600 py-2">四</div> <div class="text-center text-sm font-semibold text-gray-600 py-2">五</div> <div class="text-center text-sm font-semibold text-gray-600 py-2">六</div> </div> <div id="expiryDateCalendar" class="grid grid-cols-7 gap-2"></div> <!-- 回到今天按钮 --> <div class="mt-4 pt-3 border-t border-gray-200"> <button type="button" id="expiryDateGoToToday" class="w-full px-3 py-2 text-sm text-indigo-600 hover:bg-indigo-50 rounded-md"> <i class="fas fa-calendar-day mr-2"></i>回到今天 </button> </div> </div> </div> <div id="expiryDateLunar" class="lunar-display"></div> <div class="error-message text-red-500"></div> <div class="flex justify-end mt-2"> <button type="button" id="calculateExpiryBtn" class="btn-primary text-white px-4 py-2 rounded-md text-sm font-medium whitespace-nowrap"> <i class="fas fa-calculator mr-2"></i>自动计算变量日期 </button> </div> </div> </div> <div class="grid grid-cols-1 md:grid-cols-2 gap-6"> <div> <label for="reminderValue" class="block text-sm font-medium text-gray-700 mb-1">提醒提前量</label> <div class="flex space-x-3"> <input type="number" id="reminderValue" min="0" value="7" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-indigo-500 focus:border-indigo-500"> <select id="reminderUnit" class="w-32 px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 bg-white"> <option value="day" selected>天</option> <option value="hour">小时</option> </select> </div> <p class="text-xs text-gray-500 mt-1">0 = 仅在定时任务提醒;选择“小时”需要将 Worker 定时任务调整为级执行</p> <div class="error-message text-red-500"></div> </div> <div> <label class="block text-sm font-medium text-gray-700 mb-3">选项设置</label> <div class="space-y-2"> <label class="inline-flex items-center"> <input type="checkbox" id="isActive" checked class="form-checkbox h-4 w-4 text-indigo-600 rounded border-gray-300 focus:ring-indigo-500"> <span class="ml-2 text-sm text-gray-700">订阅</span> </label> <label class="inline-flex items-center"> <input type="checkbox" id="autoRenew" checked class="form-checkbox h-4 w-4 text-indigo-600 rounded border-gray-300 focus:ring-indigo-500"> <span class="ml-2 text-sm text-gray-700">自动续订</span> </label> </div> </div> </div> <div> <label for="notes" class="block text-sm font-medium text-gray-700 mb-1">备注</label> <textarea id="notes" rows="3" placeholder="可添加相关备注信息..." class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-indigo-500 focus:border-indigo-500"></textarea> <div class="error-message text-red-500"></div> </div> <div class="flex justify-end space-x-3 pt-4 border-t border-gray-200"> <button type="button" id="cancelBtn" class="px-4 py-2 border border-gray-300 rounded-md text-sm font-medium text-gray-700 hover:bg-gray-50"> 取消 </button> <button type="提交" class="btn-primary text-white px-4 py-2 rounded-md text-sm font-medium"> <i class="fas fa-save mr-2"></i>保存 </button> </div> </form> </div> </div>
<script> // 兼容性函数 - 保持原有接口 function formatBeijingTime(date = new Date(), format = 'full') { 尝试 { const timezone = 'Asia/Shanghai'; const dateObj = new Date(date); 如果 (format === 'date') { 返回 dateObj.toLocaleDateString('zh-CN', { 时区:时区, 年份:'数字', 月份:两位数, 日期:两位数 }); } else if (format === 'datetime') { 返回 dateObj.toLocaleString('zh-CN', { 时区:时区, 年份:'数字', 月份:两位数, 日期:两位数 小时:两位数, 分钟:两位数, 第二个:'两位数' }); } 别的 { // 完整格式 返回 dateObj.toLocaleString('zh-CN', { 时区:时区 }); } } catch (error) { console.error('时间整理错误: ' + error.message); 返回新的 Date(date).toISOString(); } }
// 农历转换工具函数 - 移植版本 const lunarCalendar = { // 农历数据 (1900-2100年) lunarInfo: [ 0x04bd8、0x04ae0、0x0a570、0x054d5、0x0d260、0x0d950、0x16554、0x056a0、0x09ad0、0x055d2、 0x04ae0、0x0a5b6、0x0a4d0、0x0d250、0x1d255、0x0b540、0x0d6a0、0x0ada2、0x095b0、0x14977、 0x04970、0x0a4b0、0x0b4b5、0x06a50、0x06d40、0x1ab54、0x02b60、0x09570、0x052f2、0x04970 0x06566、0x0d4a0、0x0ea50、0x06e95、0x05ad0、0x02b60、0x186e3、0x092e0、0x1c8d7、0x0c950 0x0d4a0、0x1d8a6、0x0b550、0x056a0、0x1a5b4、0x025d0、0x092d0、0x0d2b2、0x0a950、0x0b557、 0x06ca0、0x0b550、0x15355、0x04da0、0x0a5b0、0x14573、0x052b0、0x0a9a8、0x0e950、0x06aa0 0x0aea6、0x0ab50、0x04b60、0x0aae4、0x0a570、0x05260、0x0f263、0x0d950、0x05b57、0x056a0、 0x096d0、0x04dd5、0x04ad0、0x0a4d0、0x0d4d4、0x0d250、0x0d558、0x0b540、0x0b6a0、0x195a6、 0x095b0、0x049b0、0x0a974、0x0a4b0、0x0b27a、0x06a50、0x06d40、0x0af46、0x0ab60、0x09570、 0x04af5、0x04970、0x064b0、0x074a3、0x0ea50、0x06b58、0x055c0、0x0ab60、0x096d5、0x092e0、 0x0c960、0x0d954、0x0d4a0、0x0da50、0x07552、0x056a0、0x0abb7、0x025d0、0x092d0、0x0cab5 0x0a950、0x0b4a0、0x0baa4、0x0ad50、0x055d9、0x04ba0、0x0a5b0、0x15176、0x052b0、0x0a930 0x07954、0x06aa0、0x0ad50、0x05b52、0x04b60、0x0a6e6、0x0a4e0、0x0d260、0x0ea65、0x0d530、 0x05aa0、0x076a3、0x096d0、0x04bd7、0x04ad0、0x0a4d0、0x1d0b6、0x0d250、0x0d520、0x0dd45、 0x0b5a0、0x056d0、0x055b2、0x049b0、0x0a577、0x0a4b0、0x0aa50、0x1b255、0x06d20、0x0ada0 ],
// 天干地支 干: ['甲', '乙', '丙', '丁', '戊', '己', '庚', '辛', '壬', '癸'], zhi: ['子', '丑', '寅', '卯', '辰', '巳', '午', '未', '申', '酉', '戌', '亥'],
// 农历月份 月份: ['正', '二', '三', '四', '五', '六', '七', '八', '九', '十', '冬', '腊'],
// 农历日期 days: ['初一', '初二', '初三', '初四', '初五', '初六', '初七', '初八', '初九', '初十', '十一', '十二', '十三', '十四', '十五', '十六', '十七', '十八', '十九', '二十', '二十一', '二十二', '二十三', '二十四', '二十五', '二十六', '二十七', '二十八', '二十九', '三十'],
// 获取农历年天数 lunarYearDays: function(year) { 令总和 = 348; for (let i = 0x8000; i > 0x8; i >>= 1) { sum += (this.lunarInfo[year - 1900] & i) ? 1 : 0; } 返回总和 + this.leapDays(year); },
//获取闰月天数 闰日:function(year) { 如果 (this.leapMonth(year)) { return (this.lunarInfo[year - 1900] & 0x10000) ? 30 : 29; } 返回 0; },
// 获取闰月月份 闰月:function(year) { 返回 this.lunarInfo[year - 1900] & 0xf; },
// 获取农历月天数 monthDays: function(year, month) { return (this.lunarInfo[year - 1900] & (0x10000 >> month)) ? 30 : 29; },
// 公历转农历 solar2lunar: function(year, month, day) { 如果(年份小于 1900 年或大于 2100 年)则返回 null;
const baseDate = new Date(1900, 0, 31); const objDate = new Date(year, month - 1, day); //let offset = Math.floor((objDate - baseDate) / 86400000); let offset = Math.round((objDate - baseDate) / 86400000);
let temp = 0; let lunarYear = 1900;
for (lunarYear = 1900; lunarYear < 2101 && offset > 0; lunarYear++) { temp = this.lunarYearDays(lunarYear); 偏移量 -= 温度; }
如果(偏移量 < 0){ 偏移量 += 温度; 农历年--; }
let lunarMonth = 1; let leap = this.leapMonth(lunarYear); let isLeap = false;
for (lunarMonth = 1; lunarMonth < 13 && offset > 0; lunarMonth++) { 如果(闰月 > 0 && 农历月份 === (闰月 + 1) && !isLeap){ --lunarMonth; isLeap = true; temp = this.leapDays(lunarYear); } 别的 { temp = this.monthDays(lunarYear, lunarMonth); }
如果(是闰月且农历月份等于(闰月 + 1))isLeap = false; 偏移量 -= 温度; }
如果(偏移量 === 0 && 闰月 > 0 && 农历月份 === 闰月 + 1){ 如果 (isLeap) { isLeap = false; } 别的 { isLeap = true; --lunarMonth; } }
如果(偏移量 < 0){ 偏移量 += 温度; --lunarMonth; }
const lunarDay = offset + 1;
// 生成农历字符串 const ganIndex = (lunarYear - 4) % 10; const zhiIndex = (lunarYear - 4) % 12; constyearStr = this.gan[ganIndex] + this.zhi[zhiIndex] + '年'; const MonthStr = (isLeap ? '闰' : '') + this.months[lunarMonth - 1] + '月'; const dayStr = this.days[lunarDay - 1];
返回 { 年份:农历年 月份:农历月, 日期:农历日, isLeap:isLeap, yearStr: yearStr, monthStr: monthStr, dayStr: dayStr, 完整字符串:年份字符串 + 月份字符串 + 日期字符串 }; } };
// 新增修改,农历转公历(简化,适用1900-2100年) 函数 lunar2solar(lunar) { for (let y = lunar.year - 1; y <= lunar.year + 1; y++) { for (let m = 1; m <= 12; m++) { for (let d = 1; d <= 31; d++) { const date = new Date(y, m - 1, d); 如果(日期的完整年份不是 y,月份加 1 不是 m,日期的日期不是 d),则继续; const l=lunarCalendar.solar2lunar(y, m, d); 如果 ( l && l.year === 农历年 && l.month === lunar.month && l.day === 农历日 && l.isLeap === lunar.isLeap ) { 返回 { year: y, month: m, day: d }; } } } } 返回空值; }
// 新增修改,农历加周期,前期版本 function addLunarPeriod(lunar, periodValue, periodUnit) { let { year, month, day, isLeap } = lunar; 如果 (periodUnit === 'year') { 年份 += 时期值; const leap = lunarCalendar.leapMonth(year); 如果(是闰月 && 闰月 === 月份){ isLeap = true; } 别的 { isLeap = false; } } else if (periodUnit === 'month') { let totalMonths = (year - 1900) * 12 + (month - 1) + periodValue; 年份 = Math.floor(总月份 / 12) + 1900; 月份 = (总月份 % 12) + 1; const leap = lunarCalendar.leapMonth(year); 如果(是闰月 && 闰月 === 月份){ isLeap = true; } 别的 { isLeap = false; } } else if (periodUnit === 'day') { const solar = lunar2solar(lunar); const date = new Date(solar.year, solar.month - 1, solar.day + periodValue); return lunarCalendar.solar2lunar(date.getFullYear(), date.getMonth() + 1, date.getDate()); } let maxDay = isLeap ? lunarCalendar.leapDays(year) : lunarCalendar.monthDays(year, month); let targetDay = Math.min(day, maxDay); while (targetDay > 0) { let solar = lunar2solar({ year, month, day: targetDay, isLeap }); 如果(太阳能){ 返回 { year, month, day: targetDay, isLeap }; } 目标日期--; } 返回 { 年,月,日,是否为闰年 }; }
// 传入lunarBiz对象的版本 const lunarBiz = { // 农历加周期,返回新的农历数据对象 addLunarPeriod(农历, periodValue, periodUnit) { 返回 addLunarPeriod(lunar, periodValue, periodUnit); }, // 农历转公历(遍历法,适用1900-2100年) lunar2solar(lunar) { 返回 lunar2solar(lunar); }, // 距离农历日期还有多少天 daysToLunar(lunar) { const solar = lunarBiz.lunar2solar(lunar); const date = new Date(solar.year, solar.month - 1, solar.day); const now = new Date(); 返回 Math.ceil((date - now) / (1000 * 60 * 60 * 24)); } };
// 农历显示相关函数 function updateLunarDisplay(dateInputId, lunarDisplayId) { const dateInput = document.getElementById(dateInputId); const lunarDisplay = document.getElementById(lunarDisplayId); const showLunar = document.getElementById('showLunar');
如果 (!dateInput || !lunarDisplay) { 返回; }
如果 (!dateInput.value || !showLunar || !showLunar.checked) { lunarDisplay.classList.remove('show'); 返回; }
const date = new Date(dateInput.value); const lunar = lunarCalendar.solar2lunar(date.getFullYear(), date.getMonth() + 1, date.getDate());
如果(月球){ 月球显示.textContent = '农历:' + 月球.fullStr; lunarDisplay.classList.add('show'); } 别的 { lunarDisplay.classList.remove('show'); } }
function toggleLunarDisplay() { const showLunar = document.getElementById('showLunar'); 如果 (!showLunar) { 返回; } updateLunarDisplay('startDate', 'startDateLunar'); updateLunarDisplay('expiryDate', 'expiryDateLunar');
// 保存用户偏好 localStorage.setItem('showLunar', showLunar.checked); }
function loadLunarPreference() { const showLunar = document.getElementById('showLunar'); 如果 (!showLunar) { 返回; } const saved = localStorage.getItem('showLunar'); 如果 (已保存 !== null) { showLunar.checked = saved === 'true'; } 别的 { showLunar.checked = true; //默认显示 } 切换月球显示(); }
function handleListLunarToggle() { const listShowLunar = document.getElementById('listShowLunar'); // 保存用户偏好 localStorage.setItem('showLunar', listShowLunar.checked); // 重新加载订阅列表以应用农历显示设置 renderSubscriptionTable(); }
function showToast(message, type = 'success', duration = 3000) { const container = document.getElementById('toast-container'); const toast = document.createElement('div'); toast.className = 'toast ' + type; const icon = type === 'success' ? 'check-circle' : type === 'error' ? '感叹号' : type === 'warning' ? 'exclamation-triangle' : 'info-circle'; toast.innerHTML = '<div class="flex items-center"><i class="fas fa-' + icon + ' mr-2"></i><span>' + message + '</span></div>'; container.appendChild(toast); setTimeout(() => toast.classList.add('show'), 100); setTimeout(() => { toast.classList.remove('show'); setTimeout(() => { 如果(容器包含(toast)){ container.removeChild(toast); } }, 300); }, 期间); }
function showFieldError(fieldId, message) { const field = document.getElementById(fieldId); let errorDiv = field.parentElement ? field.parentElement.querySelector('.error-message') : null; 如果 (!errorDiv) { errorDiv = document.querySelector('.error-message[data-for="' + fieldId + '"]'); } 如果 (errorDiv) { errorDiv.textContent = 消息; errorDiv.classList.add('show'); field.classList.add('border-red-500'); } }
function clearFieldErrors() { document.querySelectorAll('.error-message').forEach(el => { el.classList.remove('show'); el.textContent = ''; }); document.querySelectorAll('.border-red-500').forEach(el => { el.classList.remove('border-red-500'); }); }
function validateForm() { 清除字段错误(); let isValid = true;
const name = document.getElementById('name').value.trim(); 如果 (!name) { showFieldError('name', '请输入订阅名称'); isValid = false; }
const periodValue = document.getElementById('periodValue').value; 如果 (!periodValue || periodValue < 1) { showFieldError('periodValue', '周期数值必须大于0'); isValid = false; }
const expiryDate = document.getElementById('expiryDate').value; 如果 (!expiryDate) { showFieldError('expiryDate', '请选择日期'); isValid = false; }
const reminderValueField = document.getElementById('reminderValue'); const reminderValue = reminderValueField.value; 如果 (reminderValue === '' || Number(reminderValue) < 0) { showFieldError('reminderValue', '提醒值不能为负数'); isValid = false; }
返回 isValid; }
// 创建带悬浮提示的文本元素 function createHoverText(text, maxLength = 30, className = 'text-sm text-gray-900') { 如果 (!text || text.length <= maxLength) { return '<div class="' + className + '">' + text + '</div>'; }
const truncated = text.substring(0, maxLength) + '...'; 返回'<div class="hover-container">' + '<div class="hover-text ' + className + '" data-full-text="' + text.replace(/"/g, '"') + '">' + 截断 + '</div>' + '<div class="hover-tooltip"></div>' + '</div>'; }
const categorySeparator = /[\/,,\s]+/; let subscriptionsCache = []; let searchDebounceTimer = null;
function normalizeCategoryTokens(category = '') { 返回类别 .split(categorySeparator) .map(token => token.trim()) .filter(token => token.length > 0); }
function populateCategoryFilter(subscriptions) { const select = document.getElementById('categoryFilter'); 如果 (!select) { 返回; }
const previousValue = select.value; const categories = new Set();
(subscriptions || []).forEach(subscription => { normalizeCategoryTokens(subscription.category).forEach(token => categories.add(token)); });
const sorted = Array.from(categories).sort((a, b) => a.localeCompare(b, 'zh-CN')); select.innerHTML = '';
const defaultOption = document.createElement('option'); defaultOption.value = ''; defaultOption.textContent = '全部分类'; select.appendChild(defaultOption);
sorted.forEach(cat => { const option = document.createElement('option'); option.value = cat; option.textContent = cat; select.appendChild(option); });
如果 (previousValue && sorted.map(item => item.toLowerCase()).includes(previousValue.toLowerCase())) { select.value = previousValue; } 别的 { select.value = ''; } }
function getReminderSettings(subscription) { const fallbackDays = subscription.reminderDays !== undefined ? subscription.reminderDays : 7; let unit = subscription.reminderUnit || ''; let value = subscription.reminderValue ;
如果 (unit !== 'hour') { 单位 = '天'; }
如果 (unit === 'hour' && (value === undefined || value === null || isNaN(value))) { value = subscription.reminderHours !== undefined ? subscription.reminderHours : 0; }
如果 (value === undefined || value === null || isNaN(value)) { 值 = fallbackDays; }
value = Number(value);
返回 { 单元, 价值, 显示文本:单位 === '小时' ? '提前' + value + '小时' : '提前' + value + '天' }; }
function attachHoverListeners() { function positionTooltip(element, tooltip) { const rect = element.getBoundingClientRect(); const tooltipHeight = 100; const viewportHeight = window.innerHeight; const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
let top = rect.bottom + scrollTop + 8; let left = rect.left;
如果 (rect.bottom + tooltipHeight > viewportHeight) { top = rect.top + scrollTop - tooltipHeight - 8; tooltip.style.transform = 'translateY(10px)'; tooltip.classList.add('tooltip-above'); } 别的 { tooltip.style.transform = 'translateY(-10px)'; tooltip.classList.remove('tooltip-above'); }
const maxLeft = window.innerWidth - 320 - 20; 如果(左侧 > maxLeft){ 左侧 = 最大左侧; }
tooltip.style.left = left + 'px'; tooltip.style.top = top + 'px'; }
document.querySelectorAll('.notes-text').forEach(notesElement => { const fullNotes = notesElement.getAttribute('data-full-notes'); const tooltip = notesElement.parentElement.querySelector('.notes-tooltip');
如果(完整笔记 && 工具提示){ notesElement.addEventListener('mouseenter', () => { 工具提示.textContent = fullNotes; positionTooltip(notesElement, tooltip); tooltip.classList.add('显示'); });
notesElement.addEventListener('mouseleave', () => { tooltip.classList.remove('显示'); });
window.addEventListener('scroll', () => { 如果 (tooltip.classList.contains('show')) { tooltip.classList.remove('显示'); } }, { passive: true }); } });
document.querySelectorAll('.hover-text').forEach(hoverElement => { const fullText = hideElement.getAttribute('data-full-text'); const tooltip = hoverElement.parentElement.querySelector('.hover-tooltip');
如果(全文 && 工具提示){ mouseenter.hoverElement.addEventListener('mouseenter', () => { 工具提示.textContent = fullText; positionTooltip(hoverElement, tooltip); tooltip.classList.add('显示'); });
mouseleave.hoverElement.addEventListener('mouseleave', () => { tooltip.classList.remove('显示'); });
window.addEventListener('scroll', () => { 如果 (tooltip.classList.contains('show')) { tooltip.classList.remove('显示'); } }, { passive: true }); } }); }
function renderSubscriptionTable() { const tbody = document.getElementById('subscriptionsBody'); 如果 (!tbody) { 返回; }
const listShowLunar = document.getElementById('listShowLunar'); const showLunar = listShowLunar ? listShowLunar.checked : false; const searchInput = document.getElementById('searchKeyword'); const keyword = searchInput ? searchInput.value.trim().toLowerCase() : ''; const categorySelect = document.getElementById('categoryFilter'); const selectedCategory = categorySelect ? categorySelect.value.trim().toLowerCase() : '';
let filtered = Array.isArray(subscriptionsCache) ? [...subscriptionsCache] : [];
如果 (selectedCategory) { filtered = filtered.filter(subscription => normalizeCategoryTokens(subscription.category).some(token => token.toLowerCase() === selectedCategory) ); }
如果(关键字){ filtered = filtered.filter(subscription => { const haystack = [ 订阅名称 subscription.customType, 订阅备注 订阅类别 ].filter(Boolean).join(' ').toLowerCase(); 返回 haystack.includes(keyword); }); }
如果 (filtered.length === 0) { tbody.innerHTML = '<tr><td colspan="6" class="text-center py-4 text-gray-500">没有符合条件的订阅</td></tr>'; 返回; }
filtered.sort((a, b) => new Date(a.expiryDate) - new Date(b.expiryDate)); tbody.innerHTML = '';
const currentTime = new Date();
filtered.forEach(subscription => { const row = document.createElement('tr'); row.className = subscription.isActive === false ? 'hover:bg-gray-50 bg-gray-100' : 'hover:bg-gray-50';
const calendarTypeHtml = subscription.useLunar ? '<div class="text-xs text-purple-600 mt-1">日历类型:农历</div>' : '<div class="text-xs text-gray-600 mt-1">日历类型:公历</div>';
const expiryDate = new Date(subscription.expiryDate); const currentDtf = new Intl.DateTimeFormat('en-US', { 时区:全球时区 hour12:否, 年份:'数字',月份:'两位数',日期:'两位数' }); const currentParts = currentDtf.formatToParts(currentTime); const getCurrent = type => Number(currentParts.find(x => x.type === type).value); const currentDateInTimezone = Date.UTC(getCurrent('year'), getCurrent('month') - 1, getCurrent('day'), 0, 0, 0);
const expiryDtf = new Intl.DateTimeFormat('en-US', { 时区:全球时区 hour12:否, 年份:'数字',月份:'两位数',日期:'两位数' }); const expiryParts = expiryDtf.formatToParts(expiryDate); const getExpiry = type => Number(expiryParts.find(x => x.type === type).value); const expiryDateInTimezone = Date.UTC(getExpiry('year'), getExpiry('month') - 1, getExpiry('day'), 0, 0, 0);
const daysDiff = Math.round((expiryDateInTimezone - currentDateInTimezone) / (1000 * 60 * 60 * 24)); const diffMs = expiryDate.getTime() - currentTime.getTime(); const diffHours = diffMs / (1000 * 60 * 60);
const reminder = getReminderSettings(subscription); const isSoon = reminder.unit === 'hour' diffHours >= 0 && diffHours <= reminder.value : daysDiff >= 0 && daysDiff <= reminder.value;
let statusHtml = ''; 如果(!subscription.isActive){ statusHtml = '<span class="px-2 py-1 text-xs font-medium rounded-full text-white bg-gray-500"><i class="fas fa-pause-circle mr-1"></i>已停用</span>'; } else if (daysDiff < 0) { statusHtml = '<span class="px-2 py-1 text-xs font-medium rounded-full text-white bg-red-500"><i class="fas fa-exclamation-circle mr-1"></i>已过期</span>'; } 否则如果 (isSoon) { statusHtml = '<span class="px-2 py-1 text-xs font-medium rounded-full text-white bg-yellow-500"><i class="fas fa-exclamation-triangle mr-1"></i>即将到期</span>'; } 别的 { statusHtml = '<span class="px-2 py-1 text-xs font-medium rounded-full text-white bg-green-500"><i class="fas fa-check-circle mr-1"></i>正常</span>'; }
let periodText = ''; 如果 (subscription.periodValue && subscription.periodUnit) { const unitMap = { 日: '天', 月: '月', 年份: '年' }; periodText = subscription.periodValue + ' ' + (unitMap[subscription.periodUnit] || subscription.periodUnit); }
const autoRenewIcon = subscription.autoRenew !== false ? '<i class="fas fa-sync-alt text-blue-500 ml-1" title="自动续订"></i>' : '<i class="fas fa-ban text-gray-400 ml-1" title="不自动续订"></i>';
let lunarExpiryText = ''; let startLunarText = ''; 如果(显示月球){ const expiryDateObj = new Date(subscription.expiryDate); const lunarExpiry = lunarCalendar.solar2lunar(expiryDateObj.getFullYear(), expiryDateObj.getMonth() + 1, expiryDateObj.getDate()); lunarExpiryText = lunarExpiry ? lunarExpiry.fullStr : '';
如果 (subscription.startDate) { const startDateObj = new Date(subscription.startDate); const lunarStart = lunarCalendar.solar2lunar(startDateObj.getFullYear(), startDateObj.getMonth() + 1, startDateObj.getDate()); startLunarText = 月球开始 ?月球开始.fullStr : ''; } }
let notesHtml = ''; 如果 (subscription.notes) { const notes = subscription.notes; 如果(notes.length > 50){ const truncatedNotes = notes.substring(0, 50) + '...'; notesHtml = '<div class="notes-container">' + '<div class="notes-text text-xs text-gray-500" data-full-notes="' + notes.replace(/"/g, '"') + '">' + 截断的笔记 + '</div>' + '<div class="notes-tooltip"></div>' + '</div>'; } 别的 { notesHtml = '<div class="text-xs text-gray-500">' + notes + '</div>'; } }
const nameHtml = createHoverText(subscription.name, 20, 'text-sm font-medium text-gray-900'); const typeHtml = createHoverText(subscription.customType || '其他', 15, 'text-sm text-gray-900'); const periodHtml = periodText ? createHoverText('周期: ' + periodText, 20, 'text-xs text-gray-500 mt-1') : '';
const categoryTokens = normalizeCategoryTokens(subscription.category); const categoryHtml = categoryTokens.length ? '<div class="flex flex-wrap gap-2 mt-2">' + categoryTokens.map(cat => '<span class="px-2 py-0.5 bg-indigo-50 text-indigo-600 text-xs rounded-full"><i class="fas fa-tag mr-1"></i>' + cat + '</span>' ).join('') + '</div>' :'';
function formatDateInTimezone(date, timezone) { 返回 date.toLocaleDateString('zh-CN', { 时区:时区, 年份:'数字', 月份:两位数, 日期:两位数 }); }
const expiryDateText = formatDateInTimezone(new Date(subscription.expiryDate), globalTimezone); const lunarHtml = lunarExpiryText ? createHoverText('农历: ' + lunarExpiryText, 25, 'text-xs text-blue-600 mt-1') : '';
let daysLeftText = ''; 如果 (diffMs < 0) { const absDays = Math.abs(daysDiff); 如果 (absDays >= 1) { daysLeftText = '已过渡' + absDays + '天'; } 别的 { const absHours = Math.ceil(Math.abs(diffHours)); daysLeftText = '已过渡' + absHours + '小时'; } } 否则如果 (daysDiff >= 1) { daysLeftText = '还剩' + daysDiff + '天'; } 别的 { const hoursLeft = Math.max(0, Math.ceil(diffHours)); 剩余天数 = 剩余时间 > 0 ? '约' + hoursLeft + '小时后轮胎' : '即将轮胎'; }
const startDateText = subscription.startDate ? '开始: ' + formatDateInTimezone(new Date(subscription.startDate), globalTimezone) + (startLunarText ? ' (' + startLunarText + ')' : '') :''; const startDateHtml = startDateText ? createHoverText(startDateText, 30, 'text-xs text-gray-500 mt-1') : '';
const reminderExtra = reminder.value === 0 ? '<div class="text-xs text-gray-500 mt-1">仅限天气预报时提醒</div>' : (reminder.unit === '小时' ? '<div class="text-xs text-gray-500 mt-1">小时级提醒</div>' : ''); const reminderHtml = '<div><i class="fas fa-bell mr-1"></i>' + reminder.displayText + '</div>' + reminderExtra;
row.innerHTML = '<td data-label="名称" class="px-4 py-3"><div class="td-content-wrapper">' + nameHtml + notesHtml + '</div></td>' + '<td data-label="类型" class="px-4 py-3"><div class="td-content-wrapper space-y-1">' + '<div class="flex items-center gap-1">' + '<i class="fas fa-layer-group text-gray-400"></i>' + typeHtml + '</div>' + (periodHtml ? '<div class="flex items-center gap-1">' + periodHtml + autoRenewIcon + '</div>' : '') + 类别:HTML+ calendarTypeHtml + '</div></td>' + '<td data-label="兑时间" class="px-4 py-3"><div class="td-content-wrapper">' + '<div class="text-sm text-gray-900">' + expiryDateText + '</div>' + lunarHtml + '<div class="text-xs text-gray-500 mt-1">' + daysLeftText + '</div>' + startDateHtml + '</div></td>' + '<td data-label="提醒设置" class="px-4 py-3"><div class="td-content-wrapper">' + 提醒Html + '</div></td>' + '<td data-label="状态" class="px-4 py-3"><div class="td-content-wrapper">' + statusHtml + '</div></td>' + '<td data-label="操作" class="px-4 py-3">' + '<div class="action-buttons-wrapper">' + '<button class="edit btn-primary text-white px-2 py-1 rounded text-xs whitespace-nowrap" data-id="' + subscription.id + '"><i class="fas fa-edit mr-1"></i>编辑</button>' + '<button class="test-notify btn-info text-white px-2 py-1 rounded text-xs whitespace-nowrap" data-id="' + subscription.id + '"><i class="fas fa-paper-plane mr-1"></i>测试</button>' + '<button class="delete btn-danger text-white px-2 py-1 rounded text-xs whitespace-nowrap" data-id="' + subscription.id + '"><i class="fas fa-trash-alt mr-1"></i>删除</button>' + (订阅已激活) ? '<button class="toggle-status btn-warning text-white px-2 py-1 rounded text-xs whitespace-nowrap" data-id="' + subscription.id + '" data-action="deactivate"><i class="fas fa-pause-circle mr-1"></i>停止使用</button>' : '<button class="toggle-status btn-success text-white px-2 py-1 rounded text-xs whitespace-nowrap" data-id="' + subscription.id + '" data-action="activate"><i class="fas fa-play-circle mr-1"></i>启用</button>') + '</div>' + '</td>';
tbody.appendChild(row); });
document.querySelectorAll('.edit').forEach(button => { button.addEventListener('click', editSubscription); });
document.querySelectorAll('.delete').forEach(button => { button.addEventListener('click', deleteSubscription); });
document.querySelectorAll('.toggle-status').forEach(button => { button.addEventListener('click', toggleSubscriptionStatus); });
document.querySelectorAll('.test-notify').forEach(button => { button.addEventListener('click', testSubscriptionNotification); });
attachHoverListeners(); }
const searchInput = document.getElementById('searchKeyword'); 如果 (搜索输入) { searchInput.addEventListener('input', () => { 清除超时(searchDebounceTimer); searchDebounceTimer = setTimeout(() => renderSubscriptionTable(), 200); }); }
const categorySelect = document.getElementById('categoryFilter'); 如果 (categorySelect) { categorySelect.addEventListener('change', () => renderSubscriptionTable()); }
// 获取所有订阅并按时间排序 异步函数 loadSubscriptions(showLoading = true) { 尝试 { const listShowLunar = document.getElementById('listShowLunar'); const saved = localStorage.getItem('showLunar'); 如果 (listShowLunar) { 如果 (已保存 !== null) { listShowLunar.checked = saved === 'true'; } 别的 { listShowLunar.checked = true; } }
const tbody = document.getElementById('subscriptionsBody'); 如果 (tbody && showLoading) { tbody.innerHTML = '<tr><td colspan="6" class="text-center py-4"><i class="fas fa-spinner fa-spin mr-2"></i>加载中...</td></tr>'; }
const response = await fetch('/api/subscriptions'); const data = await response.json();
subscriptionsCache = Array.isArray(data) ? data : []; 填充类别过滤器(订阅缓存); renderSubscriptionTable(); } catch (error) { console.error('加载订阅失败:', error); const tbody = document.getElementById('subscriptionsBody'); 如果 (tbody) { tbody.innerHTML = '<tr><td colspan="6" class="text-center py-4 text-red-500"><i class="fas fa-exclamation-circle mr-2"></i>加载失败,请刷新页面重试</td></tr>'; } showToast('加载订阅列表失败', '错误'); } } 异步函数 testSubscriptionNotification(e) { const button = e.target.tagName === 'BUTTON' ? e.target : e.target.parentElement; const id = button.dataset.id; const OriginalContent = Button.innerHTML; button.innerHTML = '<i class="fas fa-spinner fa-spin mr-1"></i>'; 按钮已禁用 = true;
尝试 { const response = await fetch('/api/subscriptions/' + id + '/test-notify', { method: 'POST' }); const result = await response.json(); 如果 (结果成功) { showToast(result.message || '测试通知已发送', '成功'); } 别的 { showToast(result.message || '测试通知发送失败', '错误'); } } catch (error) { console.error('测试通知失败:', error); showToast('发送测试通知时发生错误', 'error'); } 最后 { 按钮.innerHTML = 原始内容; 按钮已禁用 = false; } } 异步函数 toggleSubscriptionStatus(e) { const id = e.target.dataset.id || e.target.parentElement.dataset.id; const action = e.target.dataset.action || e.target.parentElement.dataset.action; const isActivate = action === 'activate'; const button = e.target.tagName === 'BUTTON' ? e.target : e.target.parentElement; const OriginalContent = Button.innerHTML; Button.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i>' + (isActivate ? '启用中...' : '禁用中...'); 按钮已禁用 = true; 尝试 { const response = await fetch('/api/subscriptions/' + id + '/toggle-status', { 方法:'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ isActive: isActivate }) }); 如果 (response.ok) { showToast((isActivate ? '启用' : '失效') + '成功', '成功'); 加载订阅(); } 别的 { const error = await response.json(); showToast((isActivate ? '启用' : '失效') + '失败: ' + (error.message || '未知错误'), 'error'); 按钮.innerHTML = 原始内容; 按钮已禁用 = false; } } catch (error) { console.error((isActivate ? '启用' : '失效') + '订阅失败:', error); showToast((isActivate ? '启用' : '失效') + '失败,请稍后再试', 'error'); 按钮.innerHTML = 原始内容; 按钮已禁用 = false; } } document.getElementById('addSubscriptionBtn').addEventListener('click', () => { document.getElementById('modalTitle').textContent = '添加新订阅'; document.getElementById('subscriptionModal').classList.remove('hidden');
document.getElementById('subscriptionForm').reset(); document.getElementById('subscriptionId').value = ''; 清除字段错误();
const Today = new Date().toISOString().split('T')[0]; // 前置使用本地时间 document.getElementById('startDate').value = today; document.getElementById('category').value = ''; document.getElementById('reminderValue').value = '7'; document.getElementById('reminderUnit').value = 'day'; document.getElementById('isActive').checked = true; document.getElementById('autoRenew').checked = true;
加载 LunarPreference(); 计算到期日(); setupModalEventListeners(); });
// 自定义日期选择器功能 class CustomDatePicker { constructor(inputId, pickerId, calendarId, monthId, yearId, prevBtnId, nextBtnId) { console.log('CustomDatePicker构造函数:', { inputId, pickerId, calendarId,monthId,yearId, prevBtnId, nextBtnId }); this.input = document.getElementById(inputId); this.picker = document.getElementById(pickerId); this.calendar = document.getElementById(calendarId); this.monthElement = document.getElementById(monthId); this.yearElement = document.getElementById(yearId); this.prevBtn = document.getElementById(prevBtnId); this.nextBtn = document.getElementById(nextBtnId); // 新增元素 this.monthPicker = document.getElementById(pickerId.replace('Picker', 'MonthPicker')); this.yearPicker = document.getElementById(pickerId.replace('Picker', 'YearPicker')); this.backToCalendarBtn = document.getElementById(pickerId.replace('Picker', 'BackToCalendar')); this.backToCalendarFromYearBtn = document.getElementById(pickerId.replace('Picker', 'BackToCalendarFromYear')); this.goToTodayBtn = document.getElementById(pickerId.replace('Picker', 'GoToToday')); this.prevYearDecadeBtn = document.getElementById(pickerId.replace('Picker', 'PrevYearDecade')); this.nextYearDecadeBtn = document.getElementById(pickerId.replace('Picker', 'NextYearDecade')); this.yearRangeElement = document.getElementById(pickerId.replace('Picker', 'YearRange')); this.yearGrid = document.getElementById(pickerId.replace('Picker', 'YearGrid')); console.log('找到的元素:', { 输入:!!this.input, 选择器:!!this.picker, 日历:!!this.calendar, monthElement: !!this.monthElement, yearElement: !!this.yearElement, prevBtn: !!this.prevBtn, nextBtn: !!this.nextBtn }); this.currentDate = new Date(); this.selectedDate = null; this.currentView = 'calendar'; // 'calendar', 'month', 'year' this.yearDecade = Math.floor(this.currentDate.getFullYear() / 10) * 10; this.init(); } init() { console.log('初始化日期选择器,输入框:', !!this.input, '选择器:', !!this.picker); // 绑定基本事件 如果 (this.input) { // 移除之前的事件监听器(如果存在) this.input.removeEventListener('click', this._forceShowHandler); this._forceShowHandler = () => this.forceShow(); this.input.addEventListener('click', this._forceShowHandler); 如果 (this._manualInputHandler) { this.input.removeEventListener('blur', this._manualInputHandler); } this._manualInputHandler = () => this.syncFromInputValue(); this.input.addEventListener('blur', this._manualInputHandler);
如果 (this._manualKeydownHandler) { this.input.removeEventListener('keydown', this._manualKeydownHandler); } this._manualKeydownHandler = (event) => { 如果 (event.key === 'Enter') { event.preventDefault(); this.syncFromInputValue(); } }; this.input.addEventListener('keydown', this._manualKeydownHandler); } 如果 (this.prevBtn) { this.prevBtn.removeEventListener('click', this._prevHandler); this._prevHandler = () => this.previousMonth(); this.prevBtn.addEventListener('click', this._prevHandler); } 如果 (this.nextBtn) { this.nextBtn.removeEventListener('click', this._nextHandler); this._nextHandler = () => this.nextMonth(); this.nextBtn.addEventListener('click', this._nextHandler); } // 绑定年份和年份点击事件 如果 (this.monthElement) { this.monthElement.removeEventListener('click', this._showMonthHandler); this._showMonthHandler = () => this.showMonthPicker(); this.monthElement.addEventListener('click', this._showMonthHandler); } 如果 (this.yearElement) { this.yearElement.removeEventListener('click', this._showYearHandler); this._showYearHandler = () => this.showYearPicker(); this.yearElement.addEventListener('click', this._showYearHandler); } // 绑定月份选择器事件 如果 (this.monthPicker) { this.monthPicker.removeEventListener('click', this._monthSelectHandler); this._monthSelectHandler = (e) => { 如果 (e.target.classList.contains('month-option')) { const month = parseInt(e.target.dataset.month); this.selectMonth(month); } }; this.monthPicker.addEventListener('click', this._monthSelectHandler); } 如果 (this.backToCalendarBtn) { this.backToCalendarBtn.removeEventListener('click', this._backToCalendarHandler); this._backToCalendarHandler = () => this.showCalendar(); this.backToCalendarBtn.addEventListener('click', this._backToCalendarHandler); } 如果 (this.backToCalendarFromYearBtn) { this.backToCalendarFromYearBtn.removeEventListener('click', this._backToCalendarFromYearHandler); this._backToCalendarFromYearHandler = () => this.showCalendar(); this.backToCalendarFromYearBtn.addEventListener('click', this._backToCalendarFromYearHandler); } // 绑定年份选择器事件 如果 (this.prevYearDecadeBtn) { this.prevYearDecadeBtn.removeEventListener('click', this._prevYearDecadeHandler); this._prevYearDecadeHandler = (e) => { e.stopPropagation(); // 防止事件冒泡到表单 this.previousYearDecade(); }; this.prevYearDecadeBtn.addEventListener('click', this._prevYearDecadeHandler); }
如果 (this.nextYearDecadeBtn) { this.nextYearDecadeBtn.removeEventListener('click', this._nextYearDecadeHandler); this._nextYearDecadeHandler = (e) => { e.stopPropagation(); // 防止事件冒泡到表单 this.nextYearDecade(); }; this.nextYearDecadeBtn.addEventListener('click', this._nextYearDecadeHandler); } // 绑定回到今天事件 如果 (this.goTodayBtn) { this.goToTodayBtn.removeEventListener('click', this._goToTodayHandler); this._goToTodayHandler = () => this.goToToday(); this.goToTodayBtn.addEventListener('click', this._goToTodayHandler); } // 点击外部关闭 如果 (this._outsideClickHandler) { document.removeEventListener('click', this._outsideClickHandler); } this._outsideClickHandler = (e) => { 如果 (this.picker && !this.picker.contains(e.target) && !this.input.contains(e.target)) { console.log('点击外部,隐藏日期选择器'); this.hide(); } }; document.addEventListener('click', this._outsideClickHandler); // 初始化显示 this.syncFromInputValue(); this.render(); this.renderYearGrid(); } 切换() { console.log('toggle 被调用'); console.log('picker 元素:', this.picker); console.log('picker 类名:', this.picker ? this.picker.className : 'null'); console.log('是否包含hidden:', this.picker ? this.picker.classList.contains('hidden') : 'null'); 如果 (this.picker && this.picker.classList.contains('hidden')) { console.log('显示日期选择器'); this.show(); } 别的 { console.log('隐藏日期选择器'); this.hide(); } } // 强制显示日期选择器 forceShow() { console.log('forceShow 被调用'); 如果 (this.picker) { //确保选择器显示 this.picker.classList.remove('hidden'); // 重置到日历视图 this.currentView = 'calendar'; this.hideAllViews(); this.render(); console.log('日期选择器已显示'); } 别的 { console.error('日期选择器元素不存在'); } } 展示() { 如果 (this.picker) { this.picker.classList.remove('hidden'); this.render(); } } 隐藏() { 如果 (this.picker) { this.picker.classList.add('hidden'); } } previousMonth() { this.currentDate.setMonth(this.currentDate.getMonth() - 1); this.render(); } nextMonth() { this.currentDate.setMonth(this.currentDate.getMonth() + 1); this.render(); } selectDate(date) { this.selectedDate = date; 如果 (this.input) { // 使用本地时间格式化,避免时区问题 const year = date.getFullYear(); const month = String(date.getMonth() + 1).padStart(2, '0'); const day = String(date.getDate()).padStart(2, '0'); this.input.value = year + '-' + month + '-' + day; } this.hide(); // 触发change事件,但不冒泡到表单 如果 (this.input) { const event = new Event('change', { bubbles: false }); this.input.dispatchEvent(event); } }
syncFromInputValue() { 如果 (!this.input) { 返回; } const value = this.input.value.trim(); 如果 (!value) { this.selectedDate = null; 返回; }
const match = value.match(/^(\d{4})-(\d{1,2})-(\d{1,2})$/); 如果 (!match) { 如果 (typeof showToast === 'function') { showToast('日期格式需为YYYY-MM-DD', '警告'); } 返回; }
const year = Number(match[1]); const month = Number(match[2]); const day = Number(match[3]); const parsed = new Date(year, month - 1, day); 如果 (isNaN(parsed.getTime()) || parsed.getFullYear() !== year || parsed.getMonth() !== month - 1 || parsed.getDate() !== day) { 如果 (typeof showToast === 'function') { showToast('请输入有效的日期', '警告'); } 返回; }
this.selectedDate = 已解析; this.currentDate = new Date(parsed); this.render();
const event = new Event('change', { bubbles: false }); this.input.dispatchEvent(event); } 使成为() { 如果 (!this.monthElement || !this.yearElement || !this.calendar) 返回; const year = this.currentDate.getFullYear(); const month = this.currentDate.getMonth(); // 更新年份显示 this.monthElement.textContent = (month + 1) + '月'; this.yearElement.textContent = year; // 清空日历 this.calendar.innerHTML = ''; // 获取当月第一天和最后一天 const firstDay = new Date(year, month, 1); const lastDay = new Date(year, month + 1, 0); const startDate = new Date(firstDay); startDate.setDate(startDate.getDate() - firstDay.getDay()); // 生成日历网格 for (let i = 0; i < 42; i++) { const date = new Date(startDate); date.setDate(startDate.getDate() + i); const dayElement = document.createElement('div'); dayElement.className = 'calendar-day'; //判断是否是当前月份 如果 (date.getMonth() !== month) { dayElement.classList.add('other-month'); } //判断是否是今天 const today = new Date(); 如果 (date.toDateString() === today.toDateString()) { dayElement.classList.add('today'); } //判断日期是否被选中 如果 (this.selectedDate && date.toDateString() === this.selectedDate.toDateString()) { dayElement.classList.add('selected'); } // 获取农历信息 let lunarText = ''; 尝试 { const lunar = lunarCalendar.solar2lunar(date.getFullYear(), date.getMonth() + 1, date.getDate()); 如果(月球){ 如果(lunar.day === 1){ // 初一,只显示月份 月球文本 = 月球.isLeap ? '闰' + 月历.monthStr.replace('闰', '') : 月历.monthStr; } 别的 { // 不是初一,显示日 lunarText = lunar.dayStr; } } } catch (error) { console.error('农历转换错误:', error); } dayElement.innerHTML = '<div>' + date.getDate() + '</div>' + '<div class="lunar-text">' + lunarText + '</div>'; dayElement.addEventListener('click', () => this.selectDate(date)); this.calendar.appendChild(dayElement); } } // 显示月份选择器 showMonthPicker() { this.currentView = 'month'; this.hideAllViews(); 如果 (this.monthPicker) { this.monthPicker.classList.remove('hidden'); // 高亮当前月份 const monthOptions = this.monthPicker.querySelectorAll('.month-option'); monthOptions.forEach((option, index) => { option.classList.remove('selected'); 如果 (index === this.currentDate.getMonth()) { option.classList.add('selected'); } }); } } // 显示年份选择器 showYearPicker() { this.currentView = 'year'; this.hideAllViews(); 如果 (this.yearPicker) { this.yearPicker.classList.remove('hidden'); } this.renderYearGrid(); } // 显示日历视图 showCalendar() { this.currentView = 'calendar'; this.hideAllViews(); this.render(); } // 隐藏所有视图 hideAllViews() { 如果 (this.monthPicker) this.monthPicker.classList.add('hidden'); 如果 (this.yearPicker) this.yearPicker.classList.add('hidden'); //注意:不隐藏日历视图,因为它是主视图 } // 选择月份 selectMonth(month) { this.currentDate.setMonth(month); this.showCalendar(); } // 选择年份 selectYear(year) { this.currentDate.setFullYear(year); this.showCalendar(); } // 上十年 previousYearDecade() { this.yearDecade -= 10; this.renderYearGrid(); } // 下一个十年 下一个十年() { this.yearDecade += 10; this.renderYearGrid(); } // 配送年份网格 renderYearGrid() { 如果 (!this.yearGrid || !this.yearRangeElement) 返回; const startYear = this.yearDecade; const endYear = this.yearDecade + 9; // 更新年份范围显示 this.yearRangeElement.textContent = startYear + '-' + endYear; // 清空年份网格 this.yearGrid.innerHTML = ''; // 生成年份按钮 for (let year = startYear; year <= endYear; year++) { const yearBtn = document.createElement('button'); yearBtn.type = '按钮'; yearBtn.className = 'year-option px-3 py-2 text-sm rounded hover:bg-gray-100'; yearBtn.textContent = year; yearBtn.dataset.year = year; // 高亮当前年份 如果 (year === this.currentDate.getFullYear()) { yearBtn.classList.add('bg-indigo-100', 'text-indigo-600'); } // 限制年份范围 1900-2100 如果(年份 < 1900 || 年份 > 2100){ yearBtn.disabled = true; yearBtn.classList.add('opacity-50', 'cursor-not-allowed'); } 别的 { yearBtn.addEventListener('click', () => this.selectYear(year)); } this.yearGrid.appendChild(yearBtn); } } // 回到今天 goToToday() { this.currentDate = new Date(); this.yearDecade = Math.floor(this.currentDate.getFullYear() / 10) * 10; this.showCalendar(); } 破坏() { this.hide(); //清理事件监听器 如果 (this.input && this._forceShowHandler) { this.input.removeEventListener('click', this._forceShowHandler); } 如果 (this.input && this._manualInputHandler) { this.input.removeEventListener('blur', this._manualInputHandler); } 如果 (this.input && this._manualKeydownHandler) { this.input.removeEventListener('keydown', this._manualKeydownHandler); } 如果 (this.prevBtn && this._prevHandler) { this.prevBtn.removeEventListener('click', this._prevHandler); } 如果 (this.nextBtn && this._nextHandler) { this.nextBtn.removeEventListener('click', this._nextHandler); } 如果 (this.monthElement && this._showMonthHandler) { this.monthElement.removeEventListener('click', this._showMonthHandler); } 如果 (this.yearElement && this._showYearHandler) { this.yearElement.removeEventListener('click', this._showYearHandler); } 如果 (this.monthPicker && this._monthSelectHandler) { this.monthPicker.removeEventListener('click', this._monthSelectHandler); } 如果 (this.backToCalendarBtn && this._backToCalendarHandler) { this.backToCalendarBtn.removeEventListener('click', this._backToCalendarHandler); } 如果 (this.backToCalendarFromYearBtn && this._backToCalendarFromYearHandler) { this.backToCalendarFromYearBtn.removeEventListener('click', this._backToCalendarFromYearHandler); } 如果 (this.prevYearDecadeBtn && this._prevYearDecadeHandler) { this.prevYearDecadeBtn.removeEventListener('click', this._prevYearDecadeHandler); } 如果 (this.nextYearDecadeBtn && this._nextYearDecadeHandler) { this.nextYearDecadeBtn.removeEventListener('click', this._nextYearDecadeHandler); } 如果 (this.goTodayBtn && this._goToTodayHandler) { this.goToTodayBtn.removeEventListener('click', this._goToTodayHandler); } 如果 (this._outsideClickHandler) { document.removeEventListener('click', this._outsideClickHandler); } } } function setupModalEventListeners() { // 获取DOM元素 const calculateExpiryBtn = document.getElementById('calculateExpiryBtn'); const useLunar = document.getElementById('useLunar'); const showLunar = document.getElementById('showLunar'); const startDate = document.getElementById('startDate'); const expiryDate = document.getElementById('expiryDate'); const cancelBtn = document.getElementById('cancelBtn'); // 直接绑定事件监听器(简化处理,避免重复移除的问题) 如果 (计算过期按钮) { calculateExpiryBtn.addEventListener('click', calculateExpiryDate); } 如果(使用月球){ useLunar.addEventListener('change', calculateExpiryDate); } 如果(显示月球){ showLunar.addEventListener('change', toggleLunarDisplay); } 如果 (开始日期) { startDate.addEventListener('change', () => updateLunarDisplay('startDate', 'startDateLunar')); } 如果(到期日){ expiryDate.addEventListener('change', () => updateLunarDisplay('expiryDate', 'expiryDateLunar')); } 如果 (取消按钮) { cancelBtn.addEventListener('click', () => { document.getElementById('subscriptionModal').classList.add('hidden'); }); } // 为周期相关字段添加事件监听 ['startDate', 'periodValue', 'periodUnit'].forEach(id => { const element = document.getElementById(id); 如果(元素){ element.addEventListener('change', calculateExpiryDate); } });
// 初始化自定义日期选择器 尝试 { // 在该实例之前安全地清理 如果 (window.startDatePicker && typeof window.startDatePicker.destroy === 'function') { window.startDatePicker.destroy(); } 如果 (window.expiryDatePicker && typeof window.expiryDatePicker.destroy === 'function') { window.expiryDatePicker.destroy(); } //清理全局变量 window.startDatePicker = null; window.expiryDatePicker = null; //确保DOM要素存在之后创建选择器 setTimeout(() => { console.log('创建开始日期选择器...'); window.startDatePicker = new CustomDatePicker( 'startDate', 'startDatePicker', 'startDateCalendar', 'startDateMonth', 'startDateYear', 'startDatePrevMonth', 'startDateNextMonth' ); console.log('创建日期选择器...'); window.expiryDatePicker = new CustomDatePicker( 'expiryDate'、'expiryDatePicker'、'expiryDateCalendar' 'expiryDateMonth', 'expiryDateYear', 'expiryDatePrevMonth', 'expiryDateNextMonth' ); console.log('日期选择器初始化完成'); }, 50); } catch (error) { console.error('初始化日期选择器失败:', error); //确定清理失败的实例 window.startDatePicker = null; window.expiryDatePicker = null; } }
// 3.新增,修改calculateExpiryDate函数,支持农历周期推算 函数 calculateExpiryDate() { const startDate = document.getElementById('startDate').value; const periodValue = parseInt(document.getElementById('periodValue').value); const periodUnit = document.getElementById('periodUnit').value; const useLunar = document.getElementById('useLunar').checked;
如果 (!startDate || !periodValue || !periodUnit) { 返回; }
如果(使用月球){ // 农历推算 const start = new Date(startDate); const lunar = lunarCalendar.solar2lunar(start.getFullYear(), start.getMonth() + 1, start.getDate()); let nextLunar = addLunarPeriod(lunar, periodValue, periodUnit); const solar = lunar2solar(nextLunar); // 使用与公历相同的方式创建日期 const expiry = new Date(开始日期); // 从原始日期开始 expiry.setFullYear(solar.year); expiry.setMonth(solar.month - 1); expiry.setDate(solar.day); document.getElementById('expiryDate').value = expiry.toISOString().split('T')[0]; console.log('start:', start); console.log('nextLunar:', nextLunar); console.log('过期时间:', 过期时间); console.log('expiryDate:', document.getElementById('expiryDate').value); console.log('来自 lunar2solar 的 solar 数据:', solar); console.log('solar.year:', solar.year, 'solar.month:', solar.month, 'solar.day:', solar.day); console.log('expiry.getTime():', expiry.getTime()); console.log('expiry.toString():', expiry.toString()); } 别的 { // 公历推算 const start = new Date(startDate); const expiry = new Date(start); 如果 (periodUnit === 'day') { expiry.setDate(start.getDate() + periodValue); } else if (periodUnit === 'month') { expiry.setMonth(start.getMonth() + periodValue); } else if (periodUnit === 'year') { expiry.setFullYear(start.getFullYear() + periodValue); } document.getElementById('expiryDate').value = expiry.toISOString().split('T')[0]; console.log('start:', start); console.log('过期时间:', 过期时间); console.log('expiryDate:', document.getElementById('expiryDate').value); }
// 更新农历显示 updateLunarDisplay('startDate', 'startDateLunar'); updateLunarDisplay('expiryDate', 'expiryDateLunar'); } document.getElementById('closeModal').addEventListener('click', () => { document.getElementById('subscriptionModal').classList.add('hidden'); }); // 禁止点击弹窗外区域关闭弹窗,防止误操作丢失内容 // document.getElementById('subscriptionModal').addEventListener('click', (event) => { // 如果 (event.target === document.getElementById('subscriptionModal')) { // document.getElementById('subscriptionModal').classList.add('hidden'); // } // }); // 4. 新增,监听 useLunar 修改变化时也自动重新计算 // 注意:这个事件监听器已经在 setupModalEventListeners 中处理了 // 新增修改,表单提交时带上 useLunar 字段 document.getElementById('subscriptionForm').addEventListener('submit', async (e) => { e.preventDefault(); 如果 (!validateForm()) { 返回; } const id = document.getElementById('subscriptionId').value; const reminderUnit = document.getElementById('reminderUnit').value; const reminderValue = Number(document.getElementById('reminderValue').value) || 0;
const subscription = { name: document.getElementById('name').value.trim(), customType: document.getElementById('customType').value.trim(), 类别: document.getElementById('category').value.trim(), 备注:document.getElementById('notes').value.trim() || '', isActive:document.getElementById('isActive').checked, autoRenew: document.getElementById('autoRenew').checked, startDate: document.getElementById('startDate').value, expiryDate: document.getElementById('expiryDate').value, periodValue: Number(document.getElementById('periodValue').value), periodUnit: document.getElementById('periodUnit').value, 提醒单元:提醒单元, 提醒值:提醒值, reminderDays: reminderUnit === 'day' ? reminderValue : 0, reminderHours: reminderUnit === 'hour' ? reminderValue : undefined, useLunar: document.getElementById('useLunar').checked }; const submitButton = e.target.querySelector('button[type="submit"]'); const originalContent = submitButton.innerHTML; commitButton.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i>' + (id ? '更新中...' : '保存中...'); submitButton.disabled = true; 尝试 { const url = id ? '/api/subscriptions/' + id : '/api/subscriptions'; const method = id ? 'PUT' : 'POST'; const response = await fetch(url, { 方法:方法, headers: { 'Content-Type': 'application/json' }, 正文:JSON.stringify(subscription) }); const result = await response.json(); 如果 (结果成功) { showToast((id ? '更新' : '添加') + '订阅成功', '成功'); document.getElementById('subscriptionModal').classList.add('hidden'); 加载订阅(); } 别的 { showToast((id ? '更新' : '添加') + '订阅失败: ' + (result.message || '未知错误'), '错误'); } } catch (error) { console.error((id ? '更新' : '添加') + '订阅失败:', error); showToast((id ? '更新' : '添加') + '订阅失败,请稍后再试', '错误'); } 最后 { submitButton.innerHTML = originalContent; submitButton.disabled = false; } }); // 新增修改,编辑订阅时回显 useLunar 字段 异步函数 editSubscription(e) { const id = e.target.dataset.id || e.target.parentElement.dataset.id; 尝试 { const response = await fetch('/api/subscriptions/' + id); const subscription = await response.json(); 如果(订阅){ document.getElementById('modalTitle').textContent = '编辑订阅'; document.getElementById('subscriptionId').value = subscription.id; document.getElementById('name').value = subscription.name; document.getElementById('customType').value = subscription.customType || ''; document.getElementById('category').value = subscription.category || ''; document.getElementById('notes').value = subscription.notes || ''; document.getElementById('isActive').checked = subscription.isActive !== false; document.getElementById('autoRenew').checked = subscription.autoRenew !== false; document.getElementById('startDate').value = subscription.startDate ? subscription.startDate.split('T')[0] : ''; document.getElementById('expiryDate').value = subscription.expiryDate ? subscription.expiryDate.split('T')[0] : ''; document.getElementById('periodValue').value = subscription.periodValue || 1; document.getElementById('periodUnit').value = subscription.periodUnit || 'month'; const reminderUnit = subscription.reminderUnit || (subscription.reminderHours !== undefined ? 'hour' : 'day'); let reminderValue; 如果 (reminderUnit === 'hour') { if (subscription.reminderValue !== undefined && subscription.reminderValue !== null) { reminderValue = subscription.reminderValue; } else if (subscription.reminderHours !== undefined) { reminderValue = subscription.reminderHours; } 别的 { 提醒值 = 0; } } 别的 { if (subscription.reminderValue !== undefined && subscription.reminderValue !== null) { reminderValue = subscription.reminderValue; } else if (subscription.reminderDays !== undefined) { 提醒值 = 订阅.提醒天数; } 别的 { 提醒值 = 7; } } document.getElementById('reminderUnit').value = reminderUnit; document.getElementById('reminderValue').value = reminderValue; document.getElementById('useLunar').checked = !!subscription.useLunar; 清除字段错误(); 加载 LunarPreference(); document.getElementById('subscriptionModal').classList.remove('hidden'); // 重要:编辑订阅时也需要重新设置事件监听器 setupModalEventListeners();
// 更新农历显示 setTimeout(() => { updateLunarDisplay('startDate', 'startDateLunar'); updateLunarDisplay('expiryDate', 'expiryDateLunar'); }, 100); } } catch (error) { console.error('获取订阅信息失败:', error); showToast('获取订阅信息失败', '错误'); } } 异步函数 deleteSubscription(e) { const id = e.target.dataset.id || e.target.parentElement.dataset.id; if (!confirm('确定要删除这个订阅吗?此操作不可恢复。')) { 返回; } const button = e.target.tagName === 'BUTTON' ? e.target : e.target.parentElement; const OriginalContent = Button.innerHTML; Button.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i>删除中...'; 按钮已禁用 = true; 尝试 { const response = await fetch('/api/subscriptions/' + id, { 方法:'删除' }); 如果 (response.ok) { showToast('删除成功', '成功'); 加载订阅(); } 别的 { const error = await response.json(); showToast('删除失败: ' + (error.message || '未知错误'), 'error'); 按钮.innerHTML = 原始内容; 按钮已禁用 = false; } } catch (error) { console.error('删除订阅失败:', error); showToast('删除失败,请稍后再试', 'error'); 按钮.innerHTML = 原始内容; 按钮已禁用 = false; } } // 全局时区配置 let globalTimezone = 'UTC'; // 检测时区更新 函数 checkTimezoneUpdate() { const lastUpdate = localStorage.getItem('timezoneUpdated'); 如果 (lastUpdate) { const updateTime = parseInt(lastUpdate); const currentTime = Date.now(); // 如果时区更新发生在最近5秒内,则刷新页面 如果(当前时间 - 更新时间 < 5000){ localStorage.removeItem('timezoneUpdated'); window.location.reload(); } } } // 页面加载时检查时区更新 window.addEventListener('load', () => { 检查时区更新(); 加载订阅(); }); // 定期检查时区更新(每2秒检查一次) setInterval(checkTimezoneUpdate, 2000);
// 实时显示系统时间和时区 异步函数 showSystemTime() { 尝试 { // 获取后台配置的时区 const response = await fetch('/api/config'); const config = await response.json(); globalTimezone = config.TIMEZONE || 'UTC'; // 删除当前时间 function formatTime(dt, tz) { return dt.toLocaleString('zh-CN', { timeZone: tz, year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit' }); } function formatTimezoneDisplay(tz) { 尝试 { // 使用更准确的时区偏移计算方法 const now = new Date(); const dtf = new Intl.DateTimeFormat('en-US', { 时区:tz hour12:否, 年份:'数字',月份:'两位数',日期:'两位数', 小时:两位数,分钟:两位数,秒:两位数 }); const parts = dtf.formatToParts(now); const get = type => Number(parts.find(x => x.type === type).value); const target = Date.UTC(get('year'), get('month') - 1, get('day'), get('hour'), get('minute'), get('second')); const utc = now.getTime(); const offset = Math.round((target - utc) / (1000 * 60 * 60)); // 时区中文名称地图 const timezoneNames = { 'UTC': '世界标准时间', '亚洲/上海': '中国标准时间', 'Asia/Hong_Kong': '香港时间', '亚洲/台北': '台北时间', '亚洲/新加坡': '新加坡时间', '亚洲/东京': '日本时间', '亚洲/首尔': '韩国时间', 'America/New_York': '美国东部时间', 'America/Los_Angeles': '美国太平洋时间', 'America/Chicago': '美国中部时间', 'America/Denver': '美国山地时间', '欧洲/伦敦': '英国时间', '欧洲/巴黎': '巴黎时间', 'Europe/Berlin': '柏林时间', '欧洲/莫斯科': '莫斯科时间', '澳大利亚/悉尼': '悉尼时间', '澳大利亚/墨尔本': '墨尔本时间', “太平洋/奥克兰”:“奥克兰时间” }; const offsetStr = offset >= 0 ? '+' + offset : offset; const timezoneName = timezoneNames[tz] || tz; 返回 timezoneName + ' (UTC' + offsetStr + ')'; } catch (error) { console.error('格式化时区显示失败:', error); 返回 tz; } } 函数 update() { const now = new Date(); const timeStr = formatTime(now, globalTimezone); const tzStr = formatTimezoneDisplay(globalTimezone); const el = document.getElementById('systemTimeDisplay'); 如果 (el) { el.textContent = timeStr + ' ' + tzStr; } } 更新(); // 每秒刷新 设置更新间隔为 1000。 //定期检查时区变化并重新加载订阅列表(每30秒检查一次) setInterval(async () => { 尝试 { const response = await fetch('/api/config'); const config = await response.json(); const newTimezone = config.TIMEZONE || '世界标准时间'; if (globalTimezone !== newTimezone) { globalTimezone = newTimezone; console.log('时区已更新为:', globalTimezone); // 重新加载订阅列表以更新天数计算 加载订阅(); } } catch (error) { console.error('检查时区更新失败:', error); } }, 30000); // 初始加载订阅列表 加载订阅(); } catch (e) { // 错误时显示本地时间 const el = document.getElementById('systemTimeDisplay'); 如果 (el) { el.textContent = new Date().toLocaleString(); } } } 显示系统时间(); </script> </body> </html> `;
const configPage = ` <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>系统配置-订阅管理系统</title> <link href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css" rel="stylesheet"> <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css" rel="stylesheet"> <style> .btn-primary { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); transition: all 0.3s; } .btn-primary:hover { transform: translateY(-2px); box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1); } .btn-secondary { background: linear-gradient(135deg, #6b7280 0%, #4b5563 100%); transition: all 0.3s; } .btn-secondary:hover { transform: translateY(-2px); box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1); } .toast { position: fixed; top: 20px; right: 20px; padding: 12px 20px; border-radius: 8px; 颜色:白色;字体粗细:500;z轴索引:1000;变换:translateX(400px); transition: all 0.3s ease-in-out; box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15); } .toast.show { transform: translateX(0); } .toast.success { background-color: #10b981; } .toast.error { background-color: #ef4444; } .toast.info { background-color: #3b82f6; } .toast.warning { background-color: #f59e0b; } .config-section { border: 1px solid #e5e7eb; 圆角半径:8px; 内边距:16px; margin-bottom: 24px; } .config-section.active { 背景颜色:#f8fafc; 边框颜色:#6366f1; } .config-section.inactive { 背景颜色:#f9fafb; 不透明度:0.7; } </style> </head> <body class="bg-gray-100 min-h-screen"> <div id="toast-container"></div>
<nav class="bg-white shadow-md"> <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8"> <div class="flex justify-between h-16"> <div class="flex items-center"> <i class="fas fa-calendar-check text-indigo-600 text-2xl mr-2"></i> <span class="font-bold text-xl text-gray-800">订阅管理系统</span> <span id="systemTimeDisplay" class="ml-4 text-base text-indigo-600 font-normal"></span> </div> <div class="flex items-center space-x-4"> <a href="/admin" class="text-gray-700 hover:text-gray-900 px-3 py-2 rounded-md text-sm font-medium"> <i class="fas fa-list mr-1"></i>订阅列表 </a> <a href="/admin/config" class="text-indigo-600 border-b-2 border-indigo-600 px-3 py-2 rounded-md text-sm font-medium"> <i class="fas fa-cog mr-1"></i>系统配置 </a> <a href="/api/logout" class="text-gray-700 hover:text-gray-900 px-3 py-2 rounded-md text-sm font-medium"> <i class="fas fa-sign-out-alt mr-1"></i>退出登录 </a> </div> </div> </div> </nav> <div class="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-8"> <div class="bg-white rounded-lg shadow-md p-6"> <h2 class="text-2xl font-bold text-gray-800 mb-6">系统配置</h2> <form id="configForm" class="space-y-8"> <div class="border-b border-gray-200 pb-6"> <h3 class="text-lg font-medium text-gray-900 mb-4">管理员账户</h3> <div class="grid grid-cols-1 md:grid-cols-2 gap-6"> <div> <label for="adminUsername" class="block text-sm font-medium text-gray-700">用户名</label> <input type="text" id="adminUsername" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"> </div> <div> <label for="adminPassword" class="block text-sm font-medium text-gray-700">密码</label> <input type="password" id="adminPassword" placeholder="如不修改密码,请留空" class="mt-1 block w-full border border-gray-300 rounded-md Shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"> <p class="mt-1 text-sm text-gray-500">留空表示不修改当前密码</p> </div> </div> </div> <div class="border-b border-gray-200 pb-6"> <h3 class="text-lg font-medium text-gray-900 mb-4">显示设置</h3> <div class="mb-6"> <label class="inline-flex items-center"> <input type="checkbox" id="showLunarGlobal" class="form-checkbox h-4 w-4 text-indigo-600 border-gray-300 rounded focus:ring-indigo-500" checked> <span class="ml-2 text-sm text-gray-700">在通知中显示农历日期</span> </label> <p class="mt-1 text-sm text-gray-500">控制通知消息中是否包含农历日期信息</p> </div> </div>
<div class="border-b border-gray-200 pb-6"> <h3 class="text-lg font-medium text-gray-900 mb-4">时区设置</h3> <div class="mb-6"> <label for="timezone" class="block text-sm font-medium text-gray-700 mb-1">时区选择</label> <select id="timezone" name="timezone" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 bg-white"> <option value="UTC">世界标准时间(UTC+0)</option> <option value="Asia/Shanghai">中国标准时间(UTC+8)</option> <option value="Asia/Hong_Kong">香港时间(UTC+8)</option> <option value="Asia/Taipei">台北时间(UTC+8)</option> <option value="Asia/Singapore">新加坡时间(UTC+8)</option> <option value="Asia/Tokyo">日本时间(UTC+9)</option> <option value="Asia/Seoul">韩国时间(UTC+9)</option> <option value="America/New_York">美国东部时间(UTC-5)</option> <option value="America/Chicago">美国中部时间(UTC-6)</option> <option value="America/Denver">美国山地时间(UTC-7)</option> <option value="America/Los_Angeles">美国太平洋时间(UTC-8)</option> <option value="Europe/London">英国时间(UTC+0)</option> <option value="Europe/Paris">巴黎时间(UTC+1)</option> <option value="Europe/Berlin">柏林时间(UTC+1)</option> <option value="Europe/Moscow">莫斯科时间(UTC+3)</option> <option value="Australia/Sydney">悉尼时间(UTC+10)</option> <option value="Australia/Melbourne">墨尔本时间(UTC+10)</option> <option value="Pacific/Auckland">奥克兰时间(UTC+12)</option> </select> <p class="mt-1 text-sm text-gray-500">选择需要使用时区,系统会按该时区计算剩余时间(提醒 Cron 仍基于 UTC,请在 Cloudflare 控制台换算触发时间)</p> </div> </div>
<div class="border-b border-gray-200 pb-6"> <h3 class="text-lg font-medium text-gray-900 mb-4">通知设置</h3> <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-6"> <div> <label for="notificationHours" class="block text-sm font-medium text-gray-700">通知积分(UTC)</label> <input type="text" id="notificationHours" placeholder="例如:08, 12, 20 或输入 * 表示全天" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"> <p class="mt-1 text-sm text-gray-500">可输入多个小时,使用逗号或空格分隔;留空则默认每天执行一次任务即可</p> </div> <div class="bg-indigo-50 border border-indigo-100 rounded-md p-3 text-sm text-indigo-700"> <p class="font-medium mb-1">提示</p> <p>Cloudflare Workers Cron 以 UTC 计算,例如北京时间 08:00 需设置 Cron 为 <code>0 0 * * *</code> 并在此填入 08。</p> <p class="mt-1">若 Cron 已设置为底部执行,可用该字段限制实际发送提醒的小时段。</p> </div> </div> <div class="mb-6"> <label class="block text-sm font-medium text-gray-700 mb-3">通知方式(可多选)</label> <div class="grid grid-cols-1 md:grid-cols-2 gap-4"> <label class="inline-flex items-center"> <input type="checkbox" name="enabledNotifiers" value="telegram" class="form-checkbox h-4 w-4 text-indigo-600 border-gray-300 rounded focus:ring-indigo-500"> <span class="ml-2 text-sm text-gray-700">Telegram</span> </label> <label class="inline-flex items-center"> <input type="checkbox" name="enabledNotifiers" value="notifyx" class="form-checkbox h-4 w-4 text-indigo-600 border-gray-300 rounded focus:ring-indigo-500" checked> <span class="ml-2 text-sm text-gray-700 font-semibold">NotifyX</span> </label> <label class="inline-flex items-center"> <input type="checkbox" name="enabledNotifiers" value="webhook" class="form-checkbox h-4 w-4 text-indigo-600 border-gray-300 rounded focus:ring-indigo-500"> <span class="ml-2 text-sm text-gray-700">Webhook 通知</span> </label> <label class="inline-flex items-center"> <input type="checkbox" name="enabledNotifiers" value="wechatbot" class="form-checkbox h-4 w-4 text-indigo-600 border-gray-300 rounded focus:ring-indigo-500"> <span class="ml-2 text-sm text-gray-700">企业微信机器人</span> </label> <label class="inline-flex items-center"> <input type="checkbox" name="enabledNotifiers" value="email" class="form-checkbox h-4 w-4 text-indigo-600 border-gray-300 rounded focus:ring-indigo-500"> <span class="ml-2 text-sm text-gray-700">邮件通知</span> </label> <label class="inline-flex items-center"> <input type="checkbox" name="enabledNotifiers" value="bark" class="form-checkbox h-4 w-4 text-indigo-600 border-gray-300 rounded focus:ring-indigo-500"> <span class="ml-2 text-sm text-gray-700">树皮</span> </label> </div> <div class="mt-2 flex flex-wrap gap-4"> <a href="https://www.notifyx.cn/" target="_blank" class="text-indigo-600 hover:text-indigo-800 text-sm"> <i class="fas fa-external-link-alt ml-1"></i> NotifyX 官网 </a> <a href="https://webhook.site" target="_blank" class="text-indigo-600 hover:text-indigo-800 text-sm"> <i class="fas fa-external-link-alt ml-1"></i> Webhook 调试工具 </a> <a href="https://developer.work.weixin.qq.com/document/path/91770" target="_blank" class="text-indigo-600 hover:text-indigo-800 text-sm"> <i class="fas fa-external-link-alt ml-1"></i> 企业微信机器人文档 </a> <a href="https://developers.cloudflare.com/workers/tutorials/send-emails-with-resend/" target="_blank" class="text-indigo-600 hover:text-indigo-800 text-sm"> <i class="fas fa-external-link-alt ml-1"></i> 获取重新发送 API 密钥 </a> <a href="https://apps.apple.com/cn/app/bark-customed-notifications/id1403753865" target="_blank" class="text-indigo-600 hover:text-indigo-800 text-sm"> <i class="fas fa-external-link-alt ml-1"></i> Bark iOS应用 </a> </div> </div>
<div class="mb-6"> <label for="thirdPartyToken" class="block text-sm font-medium text-gray-700">第三方 API 访问令牌</label> <div class="mt-1 flex flex-col sm:flex-row sm:items-center gap-3"> <input type="text" id="thirdPartyToken" placeholder="建议使用随机字符串,例如:iH5s9vB3..." class="flex-1 border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"> <button type="button" id="generateThirdPartyToken" class="btn-info text-white px-4 py-2 rounded-md text-sm font-medium whitespace-nowrap"> <i class="fas fa-magic mr-2"></i>生成令牌 </button> </div> <p class="mt-1 text-sm text-gray-500"> /api/notify/{token} 接口时需调用此令牌;留空表示取消第三方API。</p> </div> <div id="telegramConfig" class="config-section"> <h4 class="text-md font-medium text-gray-900 mb-3">Telegram 配置</h4> <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4"> <div> <label for="tgBotToken" class="block text-sm font-medium text-gray-700">机器人令牌</label> <input type="text" id="tgBotToken" placeholder="从 @BotFather 获取" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"> </div> <div> <label for="tgChatId" class="block text-sm font-medium text-gray-700">聊天 ID</label> <input type="text" id="tgChatId" placeholder="可从 @userinfobot 获取" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"> </div> </div> <div class="flex justify-end"> <button type="button" id="testTelegramBtn" class="btn-secondary text-white px-4 py-2 rounded-md text-sm font-medium"> <i class="fas fa-paper-plane mr-2"></i>测试 Telegram 通知 </button> </div> </div> <div id="notifyxConfig" class="config-section"> <h4 class="text-md font-medium text-gray-900 mb-3">NotifyX 配置</h4> <div class="mb-4"> <label for="notifyxApiKey" class="block text-sm font-medium text-gray-700">API 密钥</label> <input type="text" id="notifyxApiKey" placeholder="从NotifyX平台获取的API Key" class="mt-1 block w-full border border-gray-300 rounded-md Shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"> <p class="mt-1 text-sm text-gray-500">从<a href="https://www.notifyx.cn/" target="_blank" class="text-indigo-600 hide:text-indigo-800">NotifyX平台</a>获取的API Key</p> </div> <div class="flex justify-end"> <button type="button" id="testNotifyXBtn" class="btn-secondary text-white px-4 py-2 rounded-md text-sm font-medium"> <i class="fas fa-paper-plane mr-2"></i>测试 NotifyX 通知 </button> </div> </div>
<div id="webhookConfig" class="config-section"> <h4 class="text-md font-medium text-gray-900 mb-3">Webhook 通知配置</h4> <div class="grid grid-cols-1 gap-4 mb-4"> <div> <label for="webhookUrl" class="block text-sm font-medium text-gray-700">Webhook 通知 URL</label> <input type="url" id="webhookUrl" placeholder="https://your-webhook-endpoint.com/path" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"> <p class="mt-1 text-sm text-gray-500">请填写自建服务或第三方平台提供的Webhook地址,例如<code>https://your-webhook-endpoint.com/path</code></p> </div> <div> <label for="webhookMethod" class="block text-sm font-medium text-gray-700">请求方法</label> <select id="webhookMethod" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"> <option value="POST">POST</option> <option value="GET">获取</option> <option value="PUT">PUT</option> </select> </div> <div> <label for="webhookHeaders" class="block text-sm font-medium text-gray-700">自定义请求头 (JSON格式,任选)</label> <textarea id="webhookHeaders" rows="3" placeholder='{"Authorization": "Bearer your-token", "Content-Type": "application/json"}' class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"></textarea> <p class="mt-1 text-sm text-gray-500">JSON格式的自定义请求头,留空使用默认</p> </div> <div> <label for="webhookTemplate" class="block text-sm font-medium text-gray-700">消息模板 (JSON格式,任选)</label> <textarea id="webhookTemplate" rows="4" placeholder='{"title": "{{title}}", "content": "{{content}}", "timestamp": "{{timestamp}}"}' class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"></textarea> <p class="mt-1 text-sm text-gray-500">支持变量: {{title}}, {{content}}, {{timestamp}}。留空使用默认格式</p> </div> </div> <div class="flex justify-end"> <button type="button" id="testWebhookBtn" class="btn-secondary text-white px-4 py-2 rounded-md text-sm font-medium"> <i class="fas fa-paper-plane mr-2"></i>测试 Webhook 通知 </button> </div> </div>
<div id="wechatbotConfig" class="config-section"> <h4 class="text-md font-medium text-gray-900 mb-3">企业微信机器人配置</h4> <div class="grid grid-cols-1 gap-4 mb-4"> <div> <label for="wechatbotWebhook" class="block text-sm font-medium text-gray-700">机器人 Webhook URL</label> <input type="url" id="wechatbotWebhook" placeholder="https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=your-key" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"> <p class="mt-1 text-sm text-gray-500">从企业微信群聊中添加机器人获取的Webhook URL</p> </div> <div> <label for="wechatbotMsgType" class="block text-sm font-medium text-gray-700">消息类型</label> <select id="wechatbotMsgType" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"> <option value="text">文本消息</option> <option value="markdown">Markdown 消息</option> </select> <p class="mt-1 text-sm text-gray-500">选择发送的消息格式类型</p> </div> <div> <label for="wechatbotAtMobiles" class="block text-sm font-medium text-gray-700">@手机号 (任选)</label> <input type="text" id="wechatbotAtMobiles" placeholder="13800138000,13900139000" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"> <p class="mt-1 text-sm text-gray-500">需要@的手机号,多个用分隔符分隔,留空则不@任何人</p> </div> <div> <label for="wechatbotAtAll" class="block text-sm font-medium text-gray-700 mb-2">@所有人</label> <label class="inline-flex items-center"> <input type="checkbox" id="wechatbotAtAll" class="form-checkbox h-4 w-4 text-indigo-600 border-gray-300 rounded focus:ring-indigo-500"> <span class="ml-2 text-sm text-gray-700">发送消息时@所有者</span> </label> </div> </div> <div class="flex justify-end"> <button type="button" id="testWechatBotBtn" class="btn-secondary text-white px-4 py-2 rounded-md text-sm font-medium"> <i class="fas fa-paper-plane mr-2"></i>测试企业微信机器人 </button> </div> </div>
<div id="emailConfig" class="config-section"> <h4 class="text-md font-medium text-gray-900 mb-3">邮件通知配置</h4> <div class="grid grid-cols-1 gap-4 mb-4"> <div> <label for="resendApiKey" class="block text-sm font-medium text-gray-700">重新发送 API 密钥</label> <input type="text" id="resendApiKey" placeholder="re_xxxxxxxxxx" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"> <p class="mt-1 text-sm text-gray-500">从<a href="https://resend.com/api-keys" target="_blank" class="text-indigo-600 hide:text-indigo-800">重新发送控制台</a>获取API密钥</p> </div> <div> <label for="emailFrom" class="block text-sm font-medium text-gray-700">发件人邮箱</label> <input type="email" id="emailFrom" placeholder="noreply@yourdomain.com" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"> <p class="mt-1 text-sm text-gray-500">必须已在重新发送验证的域名邮箱</p> </div> <div> <label for="emailFromName" class="block text-sm font-medium text-gray-700">发件人名称</label> <input type="text" id="emailFromName" placeholder="订阅提醒系统" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"> <p class="mt-1 text-sm text-gray-500">在邮件中显示发件人名</p> </div> <div> <label for="emailTo" class="block text-sm font-medium text-gray-700">职业邮箱</label> <input type="email" id="emailTo" placeholder="user@example.com" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"> <p class="mt-1 text-sm text-gray-500">接收通知邮件的邮箱地址</p> </div> </div> <div class="flex justify-end"> <button type="button" id="testEmailBtn" class="btn-secondary text-white px-4 py-2 rounded-md text-sm font-medium"> <i class="fas fa-paper-plane mr-2"></i>测试邮件通知 </button> </div> </div>
<div id="barkConfig" class="config-section"> <h4 class="text-md font-medium text-gray-900 mb-3">Bark 配置</h4> <div class="grid grid-cols-1 gap-4 mb-4"> <div> <label for="barkServer" class="block text-sm font-medium text-gray-700"> 服务器地址</label> <input type="url" id="barkServer" placeholder="https://api.day.app" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"> <p class="mt-1 text-sm text-gray-500">Bark服务器地址,默认为官方服务器,也可以使用自建服务器</p> </div> <div> <label for="barkDeviceKey" class="block text-sm font-medium text-gray-700">设备键</label> <input type="text" id="barkDeviceKey" placeholder="从Bark应用获取的设备Key" class="mt-1 block w-full border border-gray-300 rounded-md Shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"> <p class="mt-1 text-sm text-gray-500">从<a href="https://apps.apple.com/cn/app/bark-customed-notifications/id1403753865" target="_blank" class="text-indigo-600 hide:text-indigo-800">Bark iOS应用</a>中获取的设备密钥</p> </div> <div> <label for="barkIsArchive" class="block text-sm font-medium text-gray-700 mb-2">保存主动</label> <label class="inline-flex items-center"> <input type="checkbox" id="barkIsArchive" class="form-checkbox h-4 w-4 text-indigo-600 border-gray-300 rounded focus:ring-indigo-500"> <span class="ml-2 text-sm text-gray-700">保存个体到历史记录</span> </label> <p class="mt-1 text-sm text-gray-500">勾选后自动消息会保存到Bark的历史记录中</p> </div> </div> <div class="flex justify-end"> <button type="button" id="testBarkBtn" class="btn-secondary text-white px-4 py-2 rounded-md text-sm font-medium"> <i class="fas fa-paper-plane mr-2"></i>测试 Bark 通知 </button> </div> </div> </div>
<div class="flex justify-end"> <button type="submit" class="btn-primary text-white px-6 py-2 rounded-md text-sm font-medium"> <i class="fas fa-save mr-2"></i>保存配置 </button> </div> </form> </div> </div>
<script> function showToast(message, type = 'success', duration = 3000) { const container = document.getElementById('toast-container'); const toast = document.createElement('div'); toast.className = 'toast ' + type; const icon = type === 'success' ? 'check-circle' : type === 'error' ? '感叹号' : type === 'warning' ? 'exclamation-triangle' : 'info-circle'; toast.innerHTML = '<div class="flex items-center"><i class="fas fa-' + icon + ' mr-2"></i><span>' + message + '</span></div>'; container.appendChild(toast); setTimeout(() => toast.classList.add('show'), 100); setTimeout(() => { toast.classList.remove('show'); setTimeout(() => { 如果(容器包含(toast)){ container.removeChild(toast); } }, 300); }, 期间); }
异步函数 loadConfig() { 尝试 { const response = await fetch('/api/config'); const config = await response.json();
document.getElementById('adminUsername').value = config.ADMIN_USERNAME || ''; document.getElementById('tgBotToken').value = config.TG_BOT_TOKEN || ''; document.getElementById('tgChatId').value = config.TG_CHAT_ID || ''; document.getElementById('notifyxApiKey').value = config.NOTIFYX_API_KEY || ''; document.getElementById('webhookUrl').value = config.WEBHOOK_URL || ''; document.getElementById('webhookMethod').value = config.WEBHOOK_METHOD || 'POST'; document.getElementById('webhookHeaders').value = config.WEBHOOK_HEADERS || ''; document.getElementById('webhookTemplate').value = config.WEBHOOK_TEMPLATE || ''; document.getElementById('wechatbotWebhook').value = config.WECHATBOT_WEBHOOK || ''; document.getElementById('wechatbotMsgType').value = config.WECHATBOT_MSG_TYPE || 'text'; document.getElementById('wechatbotAtMobiles').value = config.WECHATBOT_AT_MOBILES || ''; document.getElementById('wechatbotAtAll').checked = config.WECHATBOT_AT_ALL === 'true'; document.getElementById('resendApiKey').value = config.RESEND_API_KEY || ''; document.getElementById('emailFrom').value = config.EMAIL_FROM || ''; document.getElementById('emailFromName').value = config.EMAIL_FROM_NAME || '订阅提醒系统'; document.getElementById('emailTo').value = config.EMAIL_TO || ''; document.getElementById('barkServer').value = config.BARK_SERVER || 'https://api.day.app'; document.getElementById('barkDeviceKey').value = config.BARK_DEVICE_KEY || ''; document.getElementById('barkIsArchive').checked = config.BARK_IS_ARCHIVE === 'true'; document.getElementById('thirdPartyToken').value = config.THIRD_PARTY_API_TOKEN || ''; const notificationHoursInput = document.getElementById('notificationHours'); 如果 (notificationHoursInput) { // 将通知几个小时整理为删除分隔的字符串,然后管理员查看与编辑 const hours = Array.isArray(config.NOTIFICATION_HOURS) ? config.NOTIFICATION_HOURS : []; notificationHoursInput.value = hours.join(', '); } // 加载农历显示设置 document.getElementById('showLunarGlobal').checked = config.SHOW_LUNAR === true;
// 动态生成时区选项,并设置保存的值 generateTimezoneOptions(config.TIMEZONE || 'UTC');
// 处理多选通知渠道 const enabledNotifiers = config.ENABLED_NOTIFIERS || ['notifyx']; document.querySelectorAll('input[name="enabledNotifiers"]').forEach(checkbox => { checkbox.checked = enabledNotifiers.includes(checkbox.value); });
toggleNotificationConfigs(enabledNotifiers); } catch (error) { console.error('加载配置失败:', error); showToast('加载配置失败,请刷新页面重试', '错误'); } } // 动态生成时区选项 function generateTimezoneOptions(selectedTimezone = 'UTC') { const timezoneSelect = document.getElementById('timezone'); const timezones = [ { value: 'UTC', name: '世界标准时间', offset: '+0' }, { value: '亚洲/上海', name: '中国标准时间', offset: '+8' }, { value: 'Asia/Hong_Kong', name: '香港时间', offset: '+8' }, { value: '亚洲/台北', name: '台北时间', offset: '+8' }, { value: '亚洲/新加坡', name: '新加坡时间', offset: '+8' }, { value: '亚洲/东京', name: '日本时间', offset: '+9' }, { value: '亚洲/首尔', name: '韩国时间', offset: '+9' }, { value: 'America/New_York', name: '美国东部时间', offset: '-5' }, { value: 'America/Chicago', name: '美国中部时间', offset: '-6' }, { value: '美国/丹佛', name: '美国山地时间', offset: '-7' }, { value: 'America/Los_Angeles', name: '美国太平洋时间', offset: '-8' }, { value: '欧洲/伦敦', name: '英国时间', offset: '+0' }, { value: '欧洲/巴黎', name: '巴黎时间', offset: '+1' }, { value: '欧洲/柏林', name: '柏林时间', offset: '+1' }, { value: '欧洲/莫斯科', name: '莫斯科时间', offset: '+3' }, { value: '澳大利亚/悉尼', name: '悉尼时间', offset: '+10' }, { value: '澳大利亚/墨尔本', name: '墨尔本时间', offset: '+10' }, { value: '太平洋/奥克兰', name: '奥克兰时间', offset: '+12' } ]; // 清空现有选项 timezoneSelect.innerHTML = ''; //添加新选项 timezones.forEach(tz => { const option = document.createElement('option'); option.value = tz.value; option.textContent = tz.name + '(UTC' + tz.offset + ')'; timezoneSelect.appendChild(option); }); // 设置选中的时区 timezoneSelect.value = selectedTimezone; } function toggleNotificationConfigs(enabledNotifiers) { const telegramConfig = document.getElementById('telegramConfig'); const notifyxConfig = document.getElementById('notifyxConfig'); const webhookConfig = document.getElementById('webhookConfig'); const wechatbotConfig = document.getElementById('wechatbotConfig'); const emailConfig = document.getElementById('emailConfig'); const barkConfig = document.getElementById('barkConfig');
// 重置所有配置区域 [telegramConfig, notifyxConfig, webhookConfig, wechatbotConfig, emailConfig, barkConfig].forEach(config => { config.classList.remove('active', 'inactive'); config.classList.add('inactive'); });
// 激活选中的配置区域 enabledNotifiers.forEach(type => { 如果(类型 === 'telegram'){ telegramConfig.classList.remove('inactive'); telegramConfig.classList.add('active'); } else if (type === 'notifyx') { notifyxConfig.classList.remove('inactive'); notifyxConfig.classList.add('active'); } else if (type === 'webhook') { webhookConfig.classList.remove('inactive'); webhookConfig.classList.add('active'); } else if (type === 'wechatbot') { wechatbotConfig.classList.remove('inactive'); wechatbotConfig.classList.add('active'); } else if (type === 'email') { emailConfig.classList.remove('inactive'); emailConfig.classList.add('active'); } else if (type === 'bark') { barkConfig.classList.remove('inactive'); barkConfig.classList.add('active'); } }); }
document.querySelectorAll('input[name="enabledNotifiers"]').forEach(checkbox => { checkbox.addEventListener('change', () => { const enabledNotifiers = Array.from(document.querySelectorAll('input[name="enabledNotifiers"]:checked')) .map(cb => cb.value); toggleNotificationConfigs(enabledNotifiers); }); }); document.getElementById('configForm').addEventListener('submit', async (e) => { e.preventDefault();
const enabledNotifiers = Array.from(document.querySelectorAll('input[name="enabledNotifiers"]:checked')) .map(cb => cb.value);
如果 (enabledNotifiers.length === 0) { showToast('请至少选择一种通知方式', '警告'); 返回; }
const config = { ADMIN_USERNAME: document.getElementById('adminUsername').value.trim(), TG_BOT_TOKEN: document.getElementById('tgBotToken').value.trim(), TG_CHAT_ID: document.getElementById('tgChatId').value.trim(), NOTIFYX_API_KEY: document.getElementById('notifyxApiKey').value.trim(), WEBHOOK_URL: document.getElementById('webhookUrl').value.trim(), WEBHOOK_METHOD: document.getElementById('webhookMethod').value, WEBHOOK_HEADERS: document.getElementById('webhookHeaders').value.trim(), WEBHOOK_TEMPLATE: document.getElementById('webhookTemplate').value.trim(), SHOW_LUNAR: document.getElementById('showLunarGlobal').checked, WECHATBOT_WEBHOOK: document.getElementById('wechatbotWebhook').value.trim(), WECHATBOT_MSG_TYPE: document.getElementById('wechatbotMsgType').value, WECHATBOT_AT_MOBILES: document.getElementById('wechatbotAtMobiles').value.trim(), WECHATBOT_AT_ALL: document.getElementById('wechatbotAtAll').checked.toString(), RESEND_API_KEY: document.getElementById('resendApiKey').value.trim(), EMAIL_FROM: document.getElementById('emailFrom').value.trim(), EMAIL_FROM_NAME: document.getElementById('emailFromName').value.trim(), EMAIL_TO: document.getElementById('emailTo').value.trim(), BARK_SERVER: document.getElementById('barkServer').value.trim() || 'https://api.day.app', BARK_DEVICE_KEY: document.getElementById('barkDeviceKey').value.trim(), BARK_IS_ARCHIVE: document.getElementById('barkIsArchive').checked.toString(), ENABLED_NOTIFIERS:已启用的通知器, 时区:document.getElementById('timezone').value.trim(), THIRD_PARTY_API_TOKEN: document.getElementById('thirdPartyToken').value.trim(), // 前置先行整理通知小时列表,届时仍会重新审核 通知时间:(() => { const raw = document.getElementById('notificationHours').value.trim(); 如果 (!raw) { 返回 []; } 返回原始数据 .split(/[,,\s]+/) .map(item => item.trim()) .filter(item => item.length > 0); })() };
const passwordField = document.getElementById('adminPassword'); if (passwordField.value.trim()) { config.ADMIN_PASSWORD = passwordField.value.trim(); }
const submitButton = e.target.querySelector('button[type="submit"]'); const originalContent = submitButton.innerHTML; submitButton.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i>保存中...'; submitButton.disabled = true;
尝试 { const response = await fetch('/api/config', { 方法:'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(config) });
const result = await response.json();
如果 (结果成功) { showToast('配置保存成功', '成功'); passwordField.value = ''; // 更新全局时区并重新显示时间 globalTimezone = config.TIMEZONE; 显示系统时间(); // 标记时区已更新,提供其他页面检测 localStorage.setItem('timezoneUpdated', Date.now().toString()); // 如果当前在订阅列表页面,则自动刷新页面以更新时区显示 如果 (window.location.pathname === '/admin') { window.location.reload(); } } 别的 { showToast('配置保存失败: ' + (result.message || '未知错误'), '错误'); } } catch (error) { console.error('保存配置失败:', error); showToast('保存配置失败,请稍后再试', '错误'); } 最后 { submitButton.innerHTML = originalContent; submitButton.disabled = false; } }); 异步函数 testNotification(type) { const buttonId = type === 'telegram' ? 'testTelegramBtn' : 类型 === 'notifyx' ? 'testNotifyXBtn': 输入==='微信机器人'? 'testWechatBotBtn': type === 'email' ? 'testEmailBtn' : 类型 === '吠' ? 'testBarkBtn' : 'testWebhookBtn'; const button = document.getElementById(buttonId); const OriginalContent = Button.innerHTML; const serviceName = type === 'telegram' ? 'Telegram' : type === 'notifyx' ? 'NotifyX' : 输入==='微信机器人'? ‘企业微信机器人’: 输入==='电子邮件'? ‘邮件通知’: 类型 === '吠' ? 'Bark' : 'Webhook 通知';
button.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i>测试中...'; 按钮已禁用 = true;
const config = {}; 如果(类型 === 'telegram'){ config.TG_BOT_TOKEN = document.getElementById('tgBotToken').value.trim(); config.TG_CHAT_ID = document.getElementById('tgChatId').value.trim();
如果 (!config.TG_BOT_TOKEN || !config.TG_CHAT_ID) { showToast('请先填写 Telegram Bot Token 和聊天 ID', '警告'); 按钮.innerHTML = 原始内容; 按钮已禁用 = false; 返回; } } else if (type === 'notifyx') { config.NOTIFYX_API_KEY = document.getElementById('notifyxApiKey').value.trim();
如果 (!config.NOTIFYX_API_KEY) { showToast('请先填写NotifyX API Key', '警告'); 按钮.innerHTML = 原始内容; 按钮已禁用 = false; 返回; } } else if (type === 'webhook') { config.WEBHOOK_URL = document.getElementById('webhookUrl').value.trim(); config.WEBHOOK_METHOD = document.getElementById('webhookMethod').value; config.WEBHOOK_HEADERS = document.getElementById('webhookHeaders').value.trim(); config.WEBHOOK_TEMPLATE = document.getElementById('webhookTemplate').value.trim();
如果 (!config.WEBHOOK_URL) { showToast('请先填写Webhook通知URL', '警告'); 按钮.innerHTML = 原始内容; 按钮已禁用 = false; 返回; } } else if (type === 'wechatbot') { config.WECHATBOT_WEBHOOK = document.getElementById('wechatbotWebhook').value.trim(); config.WECHATBOT_MSG_TYPE = document.getElementById('wechatbotMsgType').value; config.WECHATBOT_AT_MOBILES = document.getElementById('wechatbotAtMobiles').value.trim(); config.WECHATBOT_AT_ALL = document.getElementById('wechatbotAtAll').checked.toString();
如果 (!config.WECHATBOT_WEBHOOK) { showToast('请先填写企业微信机器人Webhook URL', '警告'); 按钮.innerHTML = 原始内容; 按钮已禁用 = false; 返回; } } else if (type === 'email') { config.RESEND_API_KEY = document.getElementById('resendApiKey').value.trim(); config.EMAIL_FROM = document.getElementById('emailFrom').value.trim(); config.EMAIL_FROM_NAME = document.getElementById('emailFromName').value.trim(); config.EMAIL_TO = document.getElementById('emailTo').value.trim();
如果 (!config.RESEND_API_KEY || !config.EMAIL_FROM || !config.EMAIL_TO) { showToast('请先填写 重新发送API Key、发件人邮箱和食谱邮箱', '警告'); 按钮.innerHTML = 原始内容; 按钮已禁用 = false; 返回; } } else if (type === 'bark') { config.BARK_SERVER = document.getElementById('barkServer').value.trim() || 'https://api.day.app'; config.BARK_DEVICE_KEY = document.getElementById('barkDeviceKey').value.trim(); config.BARK_IS_ARCHIVE = document.getElementById('barkIsArchive').checked.toString();
如果 (!config.BARK_DEVICE_KEY) { showToast('请先填写 Bark 设备Key', '警告'); 按钮.innerHTML = 原始内容; 按钮已禁用 = false; 返回; } }
尝试 { const response = await fetch('/api/test-notification', { 方法:'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ type: type, ...config }) });
const result = await response.json();
如果 (结果成功) { showToast(serviceName + '通知测试成功!', '成功'); } 别的 { showToast(serviceName + '通知测试失败:' + (result.message || '未知错误'), 'error'); } } catch (error) { console.error('测试通知失败:', error); showToast('测试失败,请稍后再试', 'error'); } 最后 { 按钮.innerHTML = 原始内容; 按钮已禁用 = false; } } document.getElementById('testTelegramBtn').addEventListener('click', () => { testNotification('telegram'); }); document.getElementById('testNotifyXBtn').addEventListener('click', () => { testNotification('notifyx'); });
document.getElementById('testWebhookBtn').addEventListener('click', () => { testNotification('webhook'); });
document.getElementById('testWechatBotBtn').addEventListener('click', () => { testNotification('微信机器人'); });
document.getElementById('testEmailBtn').addEventListener('click', () => { testNotification('email'); });
document.getElementById('testBarkBtn').addEventListener('click', () => { testNotification('bark'); });
document.getElementById('generateThirdPartyToken').addEventListener('click', () => { 尝试 { // 生成32位随机令牌,避免出现特殊字符,方便写入URL const charset = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; const buffer = new Uint8Array(32); window.crypto.getRandomValues(buffer); const token = Array.from(buffer).map(v => charset[v % charset.length]).join(''); const input = document.getElementById('thirdPartyToken'); 输入值 = token; input.dispatchEvent(new Event('input')); showToast('已生成新的第三方API令牌,请保存配置后生效', 'info'); } catch (error) { console.error('生成令牌失败:', error); showToast('生成令牌失败,请手动输入', '错误'); } });
window.addEventListener('load', loadConfig); // 全局时区配置 let globalTimezone = 'UTC'; // 实时显示系统时间和时区 异步函数 showSystemTime() { 尝试 { // 获取后台配置的时区 const response = await fetch('/api/config'); const config = await response.json(); globalTimezone = config.TIMEZONE || 'UTC'; // 删除当前时间 function formatTime(dt, tz) { return dt.toLocaleString('zh-CN', { timeZone: tz, year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit' }); } function formatTimezoneDisplay(tz) { 尝试 { // 使用更准确的时区偏移计算方法 const now = new Date(); const dtf = new Intl.DateTimeFormat('en-US', { 时区:tz hour12:否, 年份:'数字',月份:'两位数',日期:'两位数', 小时:两位数,分钟:两位数,秒:两位数 }); const parts = dtf.formatToParts(now); const get = type => Number(parts.find(x => x.type === type).value); const target = Date.UTC(get('year'), get('month') - 1, get('day'), get('hour'), get('minute'), get('second')); const utc = now.getTime(); const offset = Math.round((target - utc) / (1000 * 60 * 60)); // 时区中文名称地图 const timezoneNames = { 'UTC': '世界标准时间', '亚洲/上海': '中国标准时间', 'Asia/Hong_Kong': '香港时间', '亚洲/台北': '台北时间', '亚洲/新加坡': '新加坡时间', '亚洲/东京': '日本时间', '亚洲/首尔': '韩国时间', 'America/New_York': '美国东部时间', 'America/Los_Angeles': '美国太平洋时间', 'America/Chicago': '美国中部时间', 'America/Denver': '美国山地时间', '欧洲/伦敦': '英国时间', '欧洲/巴黎': '巴黎时间', 'Europe/Berlin': '柏林时间', '欧洲/莫斯科': '莫斯科时间', '澳大利亚/悉尼': '悉尼时间', '澳大利亚/墨尔本': '墨尔本时间', “太平洋/奥克兰”:“奥克兰时间” }; const offsetStr = offset >= 0 ? '+' + offset : offset; const timezoneName = timezoneNames[tz] || tz; 返回 timezoneName + ' (UTC' + offsetStr + ')'; } catch (error) { console.error('格式化时区显示失败:', error); 返回 tz; } } 函数 update() { const now = new Date(); const timeStr = formatTime(now, globalTimezone); const tzStr = formatTimezoneDisplay(globalTimezone); const el = document.getElementById('systemTimeDisplay'); 如果 (el) { el.textContent = timeStr + ' ' + tzStr; } } 更新(); // 每秒刷新 设置更新间隔为 1000。 //定期检查时区变化并重新加载订阅列表(每30秒检查一次) setInterval(async () => { 尝试 { const response = await fetch('/api/config'); const config = await response.json(); const newTimezone = config.TIMEZONE || '世界标准时间'; if (globalTimezone !== newTimezone) { globalTimezone = newTimezone; console.log('时区已更新为:', globalTimezone); // 重新加载订阅列表以更新天数计算 加载订阅(); } } catch (error) { console.error('检查时区更新失败:', error); } }, 30000); } catch (e) { // 错误时显示本地时间 const el = document.getElementById('systemTimeDisplay'); 如果 (el) { el.textContent = new Date().toLocaleString(); } } } 显示系统时间(); </script> </body> </html> `;
// 管理页面 // 与前端一致的分类切割则,用于提取标签信息 const CATEGORY_SEPARATOR_REGEX = /[\/,,\s]+/;
function extractTagsFromSubscriptions(subscriptions = []) { const tagSet = new Set(); (subscriptions || []).forEach(sub => { 如果 (!sub || typeof sub !== 'object') { 返回; } 如果 (Array.isArray(sub.tags)) { sub.tags.forEach(tag => { 如果 (typeof tag === 'string' && tag.trim().length > 0) { tagSet.add(tag.trim()); } }); } 如果 (子类别类型 === '字符串') { sub.category.split(CATEGORY_SEPARATOR_REGEX) .map(tag => tag.trim()) .filter(tag => tag.length > 0) .forEach(tag => tagSet.add(tag)); } 如果 (typeof sub.customType === 'string' && sub.customType.trim().length > 0) { tagSet.add(sub.customType.trim()); } }); 返回 Array.from(tagSet); }
const admin = { async handleRequest(request, env, ctx) { 尝试 { const url = new URL(request.url); const pathname = url.pathname;
console.log('[管理页面]访问路径:', 路径名);
const token = getCookieValue(request.headers.get('Cookie'), 'token'); console.log('[管理页面] Token存在:', !!token);
const config = await getConfig(env); const user = token ? await verifyJWT(token, config.JWT_SECRET) : null;
console.log('[管理页面]用户验证结果:', !!user);
如果 (!user) { console.log('[管理页面]用户未登录,重定向到登录页面'); 返回新的 Response('', { 状态:302 headers: { 'Location': '/' } }); }
如果 (pathname === '/admin/config') { 返回新的 Response(configPage, { headers: { 'Content-Type': 'text/html; charset=utf-8' } }); }
返回新的 Response(adminPage, { headers: { 'Content-Type': 'text/html; charset=utf-8' } }); } catch (error) { console.error('[管理页面]处理请求时错误:', error); return new Response('服务器内部错误', { 状态:500 headers: { 'Content-Type': 'text/plain; charset=utf-8' } }); } } };
// 处理API请求 const api = { async handleRequest(request, env, ctx) { const url = new URL(request.url); const path = url.pathname.slice(4); const method = request.method;
const config = await getConfig(env);
如果 (路径 === '/login' && 方法 === 'POST') { const body = await request.json();
如果 (body.username === config.ADMIN_USERNAME && body.password === config.ADMIN_PASSWORD) { const token = await generateJWT(body.username, config.JWT_SECRET);
返回新的响应( JSON.stringify({ success: true }), { 标题:{ 'Content-Type': 'application/json', 'Set-Cookie': 'token=' + token + '; HttpOnly; Path=/; SameSite=Strict; Max-Age=86400' } } ); } 别的 { 返回新的响应( JSON.stringify({ success: false, message: '用户名或密码错误' }), { headers: { 'Content-Type': 'application/json' } } ); } }
如果 (路径 === '/logout' && (方法 === 'GET' || 方法 === 'POST')) { 返回新的 Response('', { 状态:302 标题:{ '地点': '/', 'Set-Cookie': 'token=; HttpOnly; Path=/; SameSite=Strict; Max-Age=0' } }); }
const token = getCookieValue(request.headers.get('Cookie'), 'token'); const user = token ? await verifyJWT(token, config.JWT_SECRET) : null;
如果 (!user && path !== '/login') { 返回新的响应( JSON.stringify({ success: false, message: '未授权访问' }), { status: 401, headers: { 'Content-Type': 'application/json' } } ); }
如果 (路径 === '/config') { 如果 (方法 === 'GET') { const { JWT_SECRET, ADMIN_PASSWORD, ...safeConfig } = config; 返回新的响应( JSON.stringify(safeConfig), { headers: { 'Content-Type': 'application/json' } } ); }
如果 (方法 === 'POST') { 尝试 { const newConfig = await request.json();
const updatedConfig = { ...配置, ADMIN_USERNAME: newConfig.ADMIN_USERNAME || config.ADMIN_USERNAME, TG_BOT_TOKEN:newConfig.TG_BOT_TOKEN || '', TG_CHAT_ID:newConfig.TG_CHAT_ID || '', NOTIFYX_API_KEY: newConfig.NOTIFYX_API_KEY || '', WEBHOOK_URL:newConfig.WEBHOOK_URL || '', WEBHOOK_METHOD: newConfig.WEBHOOK_METHOD || 'POST', WEBHOOK_HEADERS: newConfig.WEBHOOK_HEADERS || '', WEBHOOK_TEMPLATE: newConfig.WEBHOOK_TEMPLATE || '', SHOW_LUNAR:newConfig.SHOW_LUNAR === true, WECHATBOT_WEBHOOK:newConfig.WECHATBOT_WEBHOOK || '', WECHATBOT_MSG_TYPE:newConfig.WECHATBOT_MSG_TYPE || '文本', WECHATBOT_AT_MOBILES:newConfig.WECHATBOT_AT_MOBILES || '', WECHATBOT_AT_ALL:newConfig.WECHATBOT_AT_ALL || '错误的', RESEND_API_KEY: newConfig.RESEND_API_KEY || '', EMAIL_FROM: newConfig.EMAIL_FROM || '', EMAIL_FROM_NAME: newConfig.EMAIL_FROM_NAME || '', EMAIL_TO:newConfig.EMAIL_TO || '', BARK_DEVICE_KEY: newConfig.BARK_DEVICE_KEY || '', BARK_SERVER: newConfig.BARK_SERVER || 'https://api.day.app', BARK_IS_ARCHIVE: newConfig.BARK_IS_ARCHIVE || 'false', ENABLED_NOTIFIERS: newConfig.ENABLED_NOTIFIERS || ['notifyx'], 时区:newConfig.TIMEZONE || config.TIMEZONE || '世界标准时间', THIRD_PARTY_API_TOKEN: newConfig.THIRD_PARTY_API_TOKEN || '' };
const rawNotificationHours = Array.isArray(newConfig.NOTIFICATION_HOURS) ? newConfig.NOTIFICATION_HOURS newConfig.NOTIFICATION_HOURS 的类型 === 'string' newConfig.NOTIFICATION_HOURS.split(',') : [];
const sanitizedNotificationHours = rawNotificationHours .map(value => String(value).trim()) .filter(value => value.length > 0) .map(value => { const upperValue = value.toUpperCase(); 如果 (upperValue === '*' || upperValue === 'ALL') { 返回 ''; } const numeric = Number(upperValue); 如果 (!isNaN(数值)) { return String(Math.max(0, Math.min(23, Math.floor(numeric)))).padStart(2, '0'); } 返回 upperValue; });
updatedConfig.NOTIFICATION_HOURS = sanitizedNotificationHours;
如果(newConfig.ADMIN_PASSWORD){ updateConfig.ADMIN_PASSWORD = newConfig.ADMIN_PASSWORD; }
//确保JWT_SECRET存在且安全 if (!updatedConfig.JWT_SECRET || updatedConfig.JWT_SECRET === 'your-secret-key') { updatedConfig.JWT_SECRET = generateRandomSecret(); console.log('[安全]生成新的JWT密钥'); }
await env.SUBSCRIPTIONS_KV.put('config', JSON.stringify(updatedConfig));
返回新的响应( JSON.stringify({ success: true }), { headers: { 'Content-Type': 'application/json' } } ); } catch (error) { console.error('配置保存错误:', error); 返回新的响应( JSON.stringify({ success: false, message: '更新配置失败: ' + error.message }), { status: 400, headers: { 'Content-Type': 'application/json' } } ); } } }
如果 (路径 === '/test-notification' && 方法 === 'POST') { 尝试 { const body = await request.json(); let success = false; let message = '';
如果 (body.type === 'telegram') { const testConfig = { ...配置, TG_BOT_TOKEN: body.TG_BOT_TOKEN, TG_CHAT_ID:body.TG_CHAT_ID };
const content = '*测试通知*\n\n这是一条测试通知,用于验证Telegram通知功能是否正常工作。\n\n发送时间: ' + formatBeijingTime(); success = await sendTelegramNotification(content, testConfig); 消息=成功? 'Telegram通知发送成功' : 'Telegram通知发送失败,请检查配置'; } else if (body.type === 'notifyx') { const testConfig = { ...配置, NOTIFYX_API_KEY: body.NOTIFYX_API_KEY };
const title = '测试通知'; const content = ' const description = '测试NotifyX通知功能';
success = await sendNotifyXNotification(title, content, description, testConfig); 消息=成功? 'NotifyX通知发送成功' : 'NotifyX通知发送失败,请检查配置'; } else if (body.type === 'webhook') { const testConfig = { ...配置, WEBHOOK_URL:body.WEBHOOK_URL, WEBHOOK_METHOD: body.WEBHOOK_METHOD, WEBHOOK_HEADERS: body.WEBHOOK_HEADERS, WEBHOOK_TEMPLATE: body.WEBHOOK_TEMPLATE };
const title = '测试通知'; const content = '这是一条测试通知,用于验证Webhook通知功能是否正常工作。\n\n发送时间: ' + formatBeijingTime();
success = await sendWebhookNotification(title, content, testConfig); 消息=成功? 'Webhook通知发送成功' : 'Webhook通知发送失败,请检查配置'; } else if (body.type === 'wechatbot') { const testConfig = { ...配置, 微信_WEBHOOK:body.微信_WEBHOOK, WECHATBOT_MSG_TYPE: body.WECHATBOT_MSG_TYPE, 移动端微信:body.移动端微信, 微信全能:body.微信全能 };
const title = '测试通知'; const content = '这是一条测试通知,用于验证企业微信机器人功能是否正常工作。\n\n发送时间: ' + formatBeijingTime();
success = await sendWechatBotNotification(title, content, testConfig); 消息=成功? '企业微信机器人通知发送成功' : '企业微信机器人通知发送失败,请检查配置'; } else if (body.type === 'email') { const testConfig = { ...配置, RESEND_API_KEY: body.RESEND_API_KEY, EMAIL_FROM: body.EMAIL_FROM, EMAIL_FROM_NAME: body.EMAIL_FROM_NAME, EMAIL_TO: body.EMAIL_TO };
const title = '测试通知'; const content = '这是一条测试通知,用于验证邮件通知功能是否正常工作。\n\n发送时间: ' + formatBeijingTime();
success = await sendEmailNotification(title, content, testConfig); 消息=成功? '邮件通知发送成功' : '邮件通知发送失败,请检查配置'; } else if (body.type === 'bark') { const testConfig = { ...配置, BARK_SERVER: body.BARK_SERVER, BARK_DEVICE_KEY: body.BARK_DEVICE_KEY, BARK_IS_ARCHIVE:body.BARK_IS_ARCHIVE };
const title = '测试通知'; const content = '这是一条测试通知,用于验证Bark通知功能是否正常工作。\n\n发送时间: ' + formatBeijingTime();
success = await sendBarkNotification(title, content, testConfig); 消息=成功? 'Bark通知发送成功' : 'Bark通知发送失败,请检查'; }
返回新的响应( JSON.stringify({ success, message }), { headers: { 'Content-Type': 'application/json' } } ); } catch (error) { console.error('测试通知失败:', error); 返回新的响应( JSON.stringify({ success: false, message: '测试通知失败:' + error.message }), { status: 500, headers: { 'Content-Type': 'application/json' } } ); } }
如果 (路径 === '/subscriptions') { 如果 (方法 === 'GET') { const subscriptions = await getAllSubscriptions(env); 返回新的响应( JSON.stringify(subscriptions), { headers: { 'Content-Type': 'application/json' } } ); }
如果 (方法 === 'POST') { const subscription = await request.json(); const result = await createSubscription(subscription, env);
返回新的响应( JSON.stringify(result), { 状态:result.success ? 201 : 400, headers: { 'Content-Type': 'application/json' } } ); } }
如果 (路径以'/subscriptions/'开头) { const parts = path.split('/'); const id = parts[2];
如果 (parts[3] === 'toggle-status' && method === 'POST') { const body = await request.json(); const result = await toggleSubscriptionStatus(id, body.isActive, env);
返回新的响应( JSON.stringify(result), { 状态:result.success ? 200 : 400, headers: { 'Content-Type': 'application/json' } } ); }
如果 (parts[3] === 'test-notify' && method === 'POST') { const result = await testSingleSubscriptionNotification(id, env); return new Response(JSON.stringify(result), { status: result.success ? 200 : 500, headers: { 'Content-Type': 'application/json' } }); }
如果 (方法 === 'GET') { const subscription = await getSubscription(id, env);
返回新的响应( JSON.stringify(subscription), { headers: { 'Content-Type': 'application/json' } } ); }
如果 (方法 === 'PUT') { const subscription = await request.json(); const result = await updateSubscription(id, subscription, env);
返回新的响应( JSON.stringify(result), { 状态:result.success ? 200 : 400, headers: { 'Content-Type': 'application/json' } } ); }
如果 (方法 === 'DELETE') { const result = await deleteSubscription(id, env);
返回新的响应( JSON.stringify(result), { 状态:result.success ? 200 : 400, headers: { 'Content-Type': 'application/json' } } ); } }
// 处理第三方通知API 如果 (路径以'/notify/'开头) { const pathSegments = path.split('/'); // 允许通过路径、授权头或查询参数清晰方式确定访问令牌 const tokenFromPath = pathSegments[2] || ''; const tokenFromHeader = (request.headers.get('Authorization') || '').replace(/^Bearer\s+/i, '').trim(); const tokenFromQuery = url.searchParams.get('token') || ''; const providedToken = tokenFromPath || tokenFromHeader || tokenFromQuery; const expectedToken = config.THIRD_PARTY_API_TOKEN || '';
如果 (!expectedToken) { 返回新的响应( JSON.stringify({ message: '第三方API已禁用,请在后台配置访问令牌后使用' }), { status: 403, headers: { 'Content-Type': 'application/json' } } ); }
如果 (!providedToken || providedToken !== expectedToken) { 返回新的响应( JSON.stringify({ message: '访问未授权,令牌无效或退出' }), { status: 401, headers: { 'Content-Type': 'application/json' } } ); }
如果 (方法 === 'POST') { 尝试 { const body = await request.json(); const 标题 = body.title || '第三方通知'; const content = body.content || '';
如果 (!content) { 返回新的响应( JSON.stringify({ message: '缺少必填参数内容' }), { status: 400, headers: { 'Content-Type': 'application/json' } } ); }
const config = await getConfig(env); const bodyTagsRaw = Array.isArray(body.tags) ?body.tags : (typeof body.tags === 'string' ? body.tags.split(/[,,\s]+/) : []); const bodyTags = Array.isArray(bodyTagsRaw) bodyTagsRaw.filter(tag => typeof tag === 'string' && tag.trim().length > 0).map(tag => tag.trim()) : [];
// 使用多渠道发送通知 等待 sendNotificationToAllChannels(标题, 内容, config, '[第三方API]', { 元数据:{ tags: bodyTags } });
返回新的响应( JSON.stringify({ message: '发送成功', 回复: { 错误代码:0 错误信息:'好的' msgid: 'MSGID' + Date.now() } }), { headers: { 'Content-Type': 'application/json' } } ); } catch (error) { console.error('[第三方API]发送通知失败:', error); 返回新的响应( JSON.stringify({ message: '发送失败', 回复: { 错误代码:1 错误信息:错误消息 } }), { status: 500, headers: { 'Content-Type': 'application/json' } } ); } } }
返回新的响应( JSON.stringify({ success: false, message: '未找到请求的资源' }), { status: 404, headers: { 'Content-Type': 'application/json' } } ); } };
// 工具函数 function generateRandomSecret() { // 生成一个64字符的随机遥控器 const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*'; let result = ''; for (let i = 0; i < 64; i++) { result += chars.charAt(Math.floor(Math.random() * chars.length)); } 返回结果; }
异步函数 getConfig(env) { 尝试 { 如果 (!env.SUBSCRIPTIONS_KV) { console.error('[配置] KV存储未绑定'); throw new Error('KV存储未绑定'); }
const data = await env.SUBSCRIPTIONS_KV.get('config'); console.log('[配置]从KV读取配置:', data ? '成功' : '空配置');
const config = data ? JSON.parse(data) : {};
//保证JWT_SECRET的一致性 let jwtSecret = config.JWT_SECRET; 如果 (!jwtSecret || jwtSecret === 'your-secret-key') { jwtSecret = generateRandomSecret(); console.log('[配置]生成新的JWT密钥');
// 保存新的 JWT 密钥 const updatedConfig = { ...config, JWT_SECRET: jwtSecret }; await env.SUBSCRIPTIONS_KV.put('config', JSON.stringify(updatedConfig)); }
const finalConfig = { ADMIN_USERNAME: config.ADMIN_USERNAME || 'admin', ADMIN_PASSWORD: config.ADMIN_PASSWORD || 'password', JWT_SECRET:jwtSecret, TG_BOT_TOKEN: config.TG_BOT_TOKEN || '', TG_CHAT_ID: config.TG_CHAT_ID || '', NOTIFYX_API_KEY: config.NOTIFYX_API_KEY || '', WEBHOOK_URL:config.WEBHOOK_URL || '', WEBHOOK_METHOD: config.WEBHOOK_METHOD || 'POST', WEBHOOK_HEADERS: config.WEBHOOK_HEADERS || '', WEBHOOK_TEMPLATE: config.WEBHOOK_TEMPLATE || '', SHOW_LUNAR:config.SHOW_LUNAR === true, WECHATBOT_WEBHOOK: config.WECHATBOT_WEBHOOK || '', WECHATBOT_MSG_TYPE: config.WECHATBOT_MSG_TYPE || 'text', WECHATBOT_AT_MOBILES: config.WECHATBOT_AT_MOBILES || '', WECHATBOT_AT_ALL: config.WECHATBOT_AT_ALL || 'false', RESEND_API_KEY: config.RESEND_API_KEY || '', EMAIL_FROM: config.EMAIL_FROM || '', EMAIL_FROM_NAME: config.EMAIL_FROM_NAME || '', EMAIL_TO: config.EMAIL_TO || '', BARK_DEVICE_KEY: config.BARK_DEVICE_KEY || '', BARK_SERVER: config.BARK_SERVER || 'https://api.day.app', BARK_IS_ARCHIVE: config.BARK_IS_ARCHIVE || 'false', ENABLED_NOTIFIERS: config.ENABLED_NOTIFIERS || ['notifyx'], 时区:config.TIMEZONE || 'UTC', // 新增时区字段 NOTIFICATION_HOURS: Array.isArray(config.NOTIFICATION_HOURS) ? config.NOTIFICATION_HOURS : [], 第三方 API 令牌:config.THIRD_PARTY_API_TOKEN || '' };
console.log('[配置]最终配置用户名:', FinalConfig.ADMIN_USERNAME); 返回 finalConfig; } catch (error) { console.error('[配置]获取配置失败:', error); const defaultJwtSecret = generateRandomSecret();
返回 { ADMIN_USERNAME: 'admin', ADMIN_PASSWORD: 'password', JWT_SECRET:defaultJwtSecret, TG_BOT_TOKEN: '', TG_CHAT_ID: '', NOTIFYX_API_KEY: '', WEBHOOK_URL: '', WEBHOOK_METHOD: 'POST', WEBHOOK_HEADERS: '', WEBHOOK_TEMPLATE: '', SHOW_LUNAR: true, WECHATBOT_WEBHOOK:'', WECHATBOT_MSG_TYPE: 'text', 手机上的WECHATBOT:'', WECHATBOT_AT_ALL: 'false', RESEND_API_KEY: '', EMAIL_FROM: '', EMAIL_FROM_NAME: '', EMAIL_TO: '', ENABLED_NOTIFIERS: ['notifyx'], 通知时间:[] TIMEZONE: 'UTC', // 新增时区字段 第三方 API 令牌:'' }; } }
异步函数 generateJWT(username, secret) { const header = { alg: 'HS256', typ: 'JWT' }; const payload = { username, iat: Math.floor(Date.now() / 1000) };
const headerBase64 = btoa(JSON.stringify(header)); const payloadBase64 = btoa(JSON.stringify(payload));
const signatureInput = headerBase64 + '.' + payloadBase64; const signature = await CryptoJS.HmacSHA256(signatureInput, secret);
返回 headerBase64 + '.' + payloadBase64 + '.' + signature; }
异步函数 verifyJWT(token, secret) { 尝试 { 如果 (!token || !secret) { console.log('[JWT] Token或Secret为空'); 返回空值; }
const parts = token.split('.'); 如果(parts.length !== 3){ console.log('[JWT] Token格式错误,部分数量:', parts.length); 返回空值; }
const [headerBase64, payloadBase64, signature] = parts; const signatureInput = headerBase64 + '.' + payloadBase64; const expectedSignature = await CryptoJS.HmacSHA256(signatureInput, secret);
如果 (签名 !== 预期签名) { console.log('[JWT]签名验证失败'); 返回空值; }
const payload = JSON.parse(atob(payloadBase64)); console.log('[JWT]验证成功,用户:', Payload.username); 返回有效载荷; } catch (error) { console.error('[JWT]验证过程错误:', error); 返回空值; } }
异步函数 getAllSubscriptions(env) { 尝试 { const data = await env.SUBSCRIPTIONS_KV.get('subscriptions'); 返回数据?JSON.parse(data) : []; } catch (error) { 返回 []; } }
async function getSubscription(id, env) { const subscriptions = await getAllSubscriptions(env); 返回 subscriptions.find(s => s.id === id); }
// 2.修改createSubscription,支持useLunar字段 async function createSubscription(subscription, env) { 尝试 { const subscriptions = await getAllSubscriptions(env);
如果 (!subscription.name || !subscription.expiryDate) { return { success: false, message: '缺货必填字段' }; }
let expiryDate = new Date(subscription.expiryDate); const config = await getConfig(env); const timezone = config?.TIMEZONE || 'UTC'; const currentTime = getCurrentTimeInTimezone(timezone);
let useLunar = !!subscription.useLunar; 如果(使用月球){ let lunar = lunarCalendar.solar2lunar( expiryDate.getFullYear(), expiryDate.getMonth() + 1, expiryDate.getDate() ); 如果(月亮 && 订阅周期值 && 订阅周期单位){ // 如果预计日<=今天,自动推到算下一个周期 while (expiryDate <= currentTime) { lunar = lunarBiz.addLunarPeriod(lunar, subscription.periodValue, subscription.periodUnit); const solar = lunarBiz.lunar2solar(lunar); expiryDate = new Date(solar.year, solar.month - 1, solar.day); } subscription.expiryDate = expiryDate.toISOString(); } } 别的 { 如果(到期日期 < 当前时间 && 订阅周期值 && 订阅周期单位){ while (expiryDate < currentTime) { 如果 (subscription.periodUnit === 'day') { expiryDate.setDate(expiryDate.getDate() + subscription.periodValue); } else if (subscription.periodUnit === 'month') { expiryDate.setMonth(expiryDate.getMonth() + subscription.periodValue); } else if (subscription.periodUnit === 'year') { expiryDate.setFullYear(expiryDate.getFullYear() + subscription.periodValue); } } subscription.expiryDate = expiryDate.toISOString(); } }
const reminderSetting = resolveReminderSetting(subscription);
const newSubscription = { id: Date.now().toString(), // 接口使用本地时钟 名称:订阅名称, customType: subscription.customType || '', category: subscription.category ? subscription.category.trim() : '', 开始日期:subscription.startDate || null, 到期日期:subscription.到期日期, periodValue: subscription.periodValue || 1, periodUnit: subscription.periodUnit || 'month', 提醒单元:remindSetting.unit, reminderValue: reminderSetting.value, reminderDays: reminderSetting.unit === 'day' ? reminderSetting.value : undefined, reminderHours: reminderSetting.unit === 'hour' ? reminderSetting.value : undefined, 备注:订阅.备注 || '', isActive:subscription.isActive !== false, autoRenew: 订阅.autoRenew !== false, useLunar:useLunar, createdAt: new Date().toISOString() };
subscriptions.push(newSubscription);
await env.SUBSCRIPTIONS_KV.put('subscriptions', JSON.stringify(subscriptions));
返回 { success: true, subscription: newSubscription }; } catch (error) { console.error("创建订阅异常:", error && error.stack ? error.stack : error); 返回 { 成功:错误,消息:错误 && error.message ? error.message : '创建订阅失败' }; } }
// 3.修改updateSubscription,支持useLunar字段 async function updateSubscription(id, subscription, env) { 尝试 { const subscriptions = await getAllSubscriptions(env); const index = subscriptions.findIndex(s => s.id === id);
如果 (index === -1) { return { success: false, message: '订阅不存在' }; }
如果 (!subscription.name || !subscription.expiryDate) { return { success: false, message: '缺货必填字段' }; }
let expiryDate = new Date(subscription.expiryDate); const config = await getConfig(env); const timezone = config?.TIMEZONE || 'UTC'; const currentTime = getCurrentTimeInTimezone(timezone);
let useLunar = !!subscription.useLunar; 如果(使用月球){ let lunar = lunarCalendar.solar2lunar( expiryDate.getFullYear(), expiryDate.getMonth() + 1, expiryDate.getDate() ); 如果(!lunar){ return { success: false, message: '农历日期超出支持范围(1900-2100年)' }; } 如果(月相 && 到期日 < 当前时间 && 订阅周期值 && 订阅周期单位){ // 新增:循环加周期,直到expiryDate > currentTime 做 { lunar = lunarBiz.addLunarPeriod(lunar, subscription.periodValue, subscription.periodUnit); const solar = lunarBiz.lunar2solar(lunar); expiryDate = new Date(solar.year, solar.month - 1, solar.day); } while (expiryDate < currentTime); subscription.expiryDate = expiryDate.toISOString(); } } 别的 { 如果(到期日期 < 当前时间 && 订阅周期值 && 订阅周期单位){ while (expiryDate < currentTime) { 如果 (subscription.periodUnit === 'day') { expiryDate.setDate(expiryDate.getDate() + subscription.periodValue); } else if (subscription.periodUnit === 'month') { expiryDate.setMonth(expiryDate.getMonth() + subscription.periodValue); } else if (subscription.periodUnit === 'year') { expiryDate.setFullYear(expiryDate.getFullYear() + subscription.periodValue); } } subscription.expiryDate = expiryDate.toISOString(); } }
const reminderSource = { reminderUnit: subscription.reminderUnit !== undefined ? subscription.reminderUnit : subscriptions[index].reminderUnit, reminderValue: subscription.reminderValue !== undefined ? subscription.reminderValue : subscriptions[index].reminderValue, reminderHours: subscription.reminderHours !== undefined ? subscription.reminderHours : subscriptions[index].reminderHours, reminderDays: subscription.reminderDays !== undefined ? subscription.reminderDays : subscriptions[index].reminderDays }; const reminderSetting = resolveReminderSetting(reminderSource);
subscriptions[index] = { ...subscriptions[index], 名称:订阅名称, customType: subscription.customType || subscriptions[index].customType || '', category: subscription.category !== undefined ? subscription.category.trim() : (subscriptions[index].category || ''), 开始日期:subscription.startDate || subscriptions[index].startDate, 到期日期:subscription.到期日期, periodValue: subscription.periodValue || subscriptions[index].periodValue || 1, periodUnit: subscription.periodUnit || subscriptions[index].periodUnit || 'month', 提醒单元:remindSetting.unit, reminderValue: reminderSetting.value, reminderDays: reminderSetting.unit === 'day' ? reminderSetting.value : undefined, reminderHours: reminderSetting.unit === 'hour' ? reminderSetting.value : undefined, 备注:订阅.备注 || '', isActive: subscription.isActive !== undefined ? subscription.isActive : subscriptions[index].isActive, autoRenew: 订阅.autoRenew!== 未定义? subscription.autoRenew : (subscriptions[index].autoRenew !== undefined ? subscriptions[index].autoRenew : true), useLunar:useLunar, updatedAt: new Date().toISOString() };
await env.SUBSCRIPTIONS_KV.put('subscriptions', JSON.stringify(subscriptions));
返回 { success: true, subscription: subscriptions[index] }; } catch (error) { return { success: false, message: '更新订阅失败' }; } }
异步函数 deleteSubscription(id, env) { 尝试 { const subscriptions = await getAllSubscriptions(env); const filteredSubscriptions = subscriptions.filter(s => s.id !== id);
如果 (filteredSubscriptions.length === subscriptions.length) { return { success: false, message: '订阅不存在' }; }
await env.SUBSCRIPTIONS_KV.put('subscriptions', JSON.stringify(filteredSubscriptions));
返回 { success: true }; } catch (error) { return { success: false, message: '删除订阅失败' }; } }
async function toggleSubscriptionStatus(id, isActive, env) { 尝试 { const subscriptions = await getAllSubscriptions(env); const index = subscriptions.findIndex(s => s.id === id);
如果 (index === -1) { return { success: false, message: '订阅不存在' }; }
subscriptions[index] = { ...subscriptions[index], isActive:isActive, updatedAt: new Date().toISOString() };
await env.SUBSCRIPTIONS_KV.put('subscriptions', JSON.stringify(subscriptions));
返回 { success: true, subscription: subscriptions[index] }; } catch (error) { return { success: false, message: '更新订阅状态失败' }; } }
async function testSingleSubscriptionNotification(id, env) { 尝试 { const subscription = await getSubscription(id, env); 如果(!subscription){ return { success: false, message: '未找到该订阅' }; } const config = await getConfig(env);
const title = `手动测试通知:${subscription.name}`;
// 检查是否显示农历(从配置中获取,默认不显示) const showLunar = config.SHOW_LUNAR === true; let lunarExpiryText = '';
如果(显示月球){ // 计算农历日期 const expiryDateObj = new Date(subscription.expiryDate); const lunarExpiry = lunarCalendar.solar2lunar(expiryDateObj.getFullYear(), expiryDateObj.getMonth() + 1, expiryDateObj.getDate()); lunarExpiryText = lunarExpiry ? ` (农历: ${lunarExpiry.fullStr})` : ''; }
// 预测日期(使用所选时区) const timezone = config?.TIMEZONE || 'UTC'; const formattedExpiryDate = formatTimeInTimezone(new Date(subscription.expiryDate), timezone, 'date'); const currentTime = formatTimeInTimezone(new Date(), timezone, 'datetime'); // 获取日历类型和自动续期状态 const calendarType = subscription.useLunar ? '农历' : '公历'; const autoRenewText = 订阅.autoRenew ? '是' : '否'; const commonContent = `**订阅详情** 类型:${subscription.customType || '其他'} 日历类型:${calendarType} 回复日期: ${formattedExpiryDate}${lunarExpiryText} 自动期续: ${autoRenewText} 备注: ${subscription.notes || '无'} 发送时间:${currentTime} 当前时区: ${formatTimezoneDisplay(timezone)}`;
// 使用多渠道发送 const tags = extractTagsFromSubscriptions([subscription]); wait sendNotificationToAllChannels(title, commonContent, config, '[手动测试]', { 元数据:{标签} });
return { success: true, message: '测试通知已发送到所有启用的渠道' };
} catch (error) { console.error('[手动测试]发送失败:', error); return { success: false, message: '发送时发生错误:' + error.message }; } }
异步函数 sendWebhookNotification(title, content, config, metadata = {}) { 尝试 { 如果 (!config.WEBHOOK_URL) { console.error('[Webhook通知]通知未配置,缺少URL'); 返回 false; }
console.log('[Webhook通知]开始发送通知到:' + config.WEBHOOK_URL);
let requestBody; let headers = { 'Content-Type': 'application/json' };
// 处理自定义请求头 如果 (config.WEBHOOK_HEADERS) { 尝试 { const customHeaders = JSON.parse(config.WEBHOOK_HEADERS); headers = { ...headers, ...customHeaders }; } catch (error) { console.warn('[Webhook通知]自定义请求头格式错误,使用默认请求头'); } }
const tagsArray = Array.isArray(metadata.tags) ? metadata.tags.filter(tag => typeof tag === 'string' && tag.trim().length > 0).map(tag => tag.trim()) : []; const tagsBlock = tagsArray.length ? tagsArray.map(tag => `- ${tag}`).join('\n') : ''; const tagLine = tagArray.length ? '标签:' + tagArray.join('、') : ''; const timestamp = formatTimeInTimezone(new Date(), config?.TIMEZONE || 'UTC', 'datetime'); const formattedMessage = [标题,内容,tagsLine,`发送时间:${timestamp}`] .filter(section => section && section.trim().length > 0) .join('\n\n');
const templateData = { 标题, 内容, 标签:tagsBlock, tagsLine, rawTags:tagsArray, 时间戳 格式化消息, 消息:格式化消息 };
const escapeForJson = (value) => { 如果 (value === null || value === undefined) { 返回 ''; } 返回 JSON.stringify(String(value)).slice(1, -1); };
const applyTemplate = (template, data) => { const templateString = JSON.stringify(template); const replaced = templateString.replace(/\{\{\s*([a-zA-Z0-9_]+)\s*\}\}/g, (_, key) => { if (Object.prototype.hasOwnProperty.call(data, key)) { 返回 escapeForJson(data[key]); } 返回 ''; }); 返回 JSON.parse(替换后的内容); };
// 处理消息模板 如果 (config.WEBHOOK_TEMPLATE) { 尝试 { const template = JSON.parse(config.WEBHOOK_TEMPLATE); requestBody = applyTemplate(template, templateData); } catch (error) { console.warn('[Webhook通知]消息模板格式错误,使用默认格式'); 请求体 = { 标题, 内容, tags: tagsArray, tagsLine, 时间戳 消息:格式化消息 }; } } 别的 { 请求体 = { 标题, 内容, tags: tagsArray, tagsLine, 时间戳 消息:格式化消息 }; }
const response = await fetch(config.WEBHOOK_URL, { 方法:config.WEBHOOK_METHOD || 'POST', 标题:标题, body: JSON.stringify(requestBody) });
const result = await response.text(); console.log('[Webhook通知]发送结果:', response.status, result); 返回 response.ok; } catch (error) { console.error('[Webhook通知]发送通知失败:', error); 返回 false; } }
异步函数 sendWeComNotification(message, config) { // 这是一个占位符。在实际应用中,您需要在此处实现 WeCom 通知逻辑。 console.log("[企业微信]通知功能未实现"); return { success: false, message: "企业微信通知功能未实现" }; }
异步函数 sendWechatBotNotification(title, content, config) { 尝试 { 如果 (!config.WECHATBOT_WEBHOOK) { console.error('[企业微信机器人]通知未配置,缺少Webhook URL'); 返回 false; }
console.log('[企业微信机器人]开始发送通知到:' + config.WECHATBOT_WEBHOOK);
// 构建消息内容 let messageData; const msgType = config.WECHATBOT_MSG_TYPE || 'text';
如果 (msgType === 'markdown') { // Markdown 消息格式 const markdownContent = ` messageData = { msgtype: 'markdown', markdown: { 内容:markdown内容 } }; } 别的 { // 文本消息格式 - 优化显示 const textContent = `${title}\n\n${content}`; messageData = { 消息类型:'文本', 文本: { 内容:文本内容 } }; }
// 处理@功能 如果 (config.WECHATBOT_AT_ALL === 'true') { //@所有者 如果 (msgType === 'text') { messageData.text.mentioned_list = ['@all']; } } else if (config.WECHATBOT_AT_MOBILES) { // @指定手机号 const mobiles = config.WECHATBOT_AT_MOBILES.split(',').map(m => m.trim()).filter(m => m); 如果 (mobiles.length > 0) { 如果 (msgType === 'text') { messageData.text.mentioned_mobile_list = 手机; } } }
console.log('[企业微信机器人]发送消息数据:', JSON.stringify(messageData, null, 2));
const response = await fetch(config.WECHATBOT_WEBHOOK, { 方法:'POST', 标题:{ 'Content-Type': 'application/json' }, 正文:JSON.stringify(messageData) });
const responseText = await response.text(); console.log('[企业微信机器人]响应状态:', response.status); console.log('[企业微信机器人]响应内容:',responseText);
如果 (response.ok) { 尝试 { const result = JSON.parse(responseText); 如果 (result.errcode === 0) { console.log('[企业微信机器人]通知发送成功'); 返回 true; } 别的 { console.error('[企业微信机器人]发送失败,错误码:', result.errcode, '错误信息:', result.errmsg); 返回 false; } } catch (parseError) { console.error('[企业微信机器人]解析响应失败:', parseError); 返回 false; } } 别的 { console.error('[企业微信机器人] HTTP请求失败,状态码:', response.status); 返回 false; } } catch (error) { console.error('[企业微信机器人]发送通知失败:', error); 返回 false; } }
// 优化通知内容格式 function resolveReminderSetting(subscription) { const defaultDays = subscription && subscription.reminderDays !== undefined ? Number(subscription.reminderDays) : 7; let unit = subscription && subscription.reminderUnit === 'hour' ? 'hour' : 'day';
令值; 如果(单位 === 'hour'){ 如果(subscription 存在 && subscription.reminderValue !== undefined && subscription.reminderValue !== null && !isNaN(Number(subscription.reminderValue))) { value = Number(subscription.reminderValue); } else if (subscription && subscription.reminderHours !== undefined && subscription.reminderHours !== null && !isNaN(Number(subscription.reminderHours))) { value = Number(subscription.reminderHours); } 别的 { 值 = 0; } } 别的 { 如果(subscription 存在 && subscription.reminderValue !== undefined && subscription.reminderValue !== null && !isNaN(Number(subscription.reminderValue))) { value = Number(subscription.reminderValue); } else if (!isNaN(defaultDays)) { value = Number(defaultDays); } 别的 { 值 = 7; } }
如果 (value < 0 || isNaN(value)) { 值 = 0; }
返回 { 单位,值 }; }
function shouldTriggerReminder(reminder, daysDiff, hoursDiff) { 如果(!reminder){ 返回 false; } 如果 (提醒.单位 === 'hour') { 如果 (reminder.value === 0) { 返回 hoursDiff >= 0 && hoursDiff < 1; } 返回 hoursDiff >= 0 && hoursDiff <= reminder.value; } 如果 (reminder.value === 0) { 返回 daysDiff === 0; } 返回 daysDiff >= 0 && daysDiff <= reminder.value; }
function formatNotificationContent(subscriptions, config) { const showLunar = config.SHOW_LUNAR === true; const timezone = config?.TIMEZONE || 'UTC'; let content = '';
for (const sub of subscriptions) { const typeText = sub.customType || '其他'; const periodText = (sub.periodValue && sub.periodUnit) ? `(周期: ${sub.periodValue} ${ { day: '天', month: '月', year: '年' }[sub.periodUnit] || sub.periodUnit})` : ''; const 类别文本 = 子类别 ? sub.category : '未分类'; const reminderSetting = resolveReminderSetting(sub);
// 预测日期(使用所选时区) const expiryDateObj = new Date(sub.expiryDate); const formattedExpiryDate = formatTimeInTimezone(expiryDateObj, timezone, 'date'); // 农历日期 let lunarExpiryText = ''; 如果(显示月球){ const lunarExpiry = lunarCalendar.solar2lunar(expiryDateObj.getFullYear(), expiryDateObj.getMonth() + 1, expiryDateObj.getDate()); lunarExpiryText = lunarExpiry ? ` 农历日期:${lunarExpiry.fullStr}`:''; }
// 状态和预计时间 let statusText = ''; let statusEmoji = ''; 如果 (sub.daysRemaining === 0) { statusEmoji = '⚠️'; statusText = '今天到达!'; } else if (sub.daysRemaining < 0) { statusEmoji = '🚨'; statusText = `已过渡 ${Math.abs(sub.daysRemaining)} 天`; } 别的 { statusEmoji = '📅'; statusText = `将在 ${sub.daysRemaining} 天后兑`; }
const reminderSuffix = reminderSetting.value === 0 ? '(仅提示时提醒)' : (reminderSetting.unit === '小时' ? '(小时级提醒)' : ''); const reminderText = reminderSetting.unit === 'hour' ? `提醒策略:提前${reminderSetting.value}小时${reminderSuffix}` : `提醒策略:提前${reminderSetting.value}天${reminderSuffix}`;
// 获取日历类型和自动续期状态 const calendarType = sub.useLunar ? '农历' : '公历'; 常量 autoRenewText = sub.autoRenew ? '是' : '否'; // 构建格式化的通知内容 const subscriptionContent = `${statusEmoji} **${sub.name}** 类型:${typeText} ${periodText} 分类: ${categoryText} 日历类型:${calendarType} 回复日期: ${formattedExpiryDate}${lunarExpiryText} 自动期续: ${autoRenewText} ${reminderText} 回复状态: ${statusText}`;
//添加备注 let finalContent = sub.notes ? 订阅内容 + `\n 备注: ${sub.notes}` : 订阅内容;
content += finalContent + '\n\n'; }
//添加发送时间和时区信息 const currentTime = formatTimeInTimezone(new Date(), timezone, 'datetime'); content += `发送时间: ${currentTime}\n当前时区: ${formatTimezoneDisplay(timezone)}`;
返回内容; }
异步函数 sendNotificationToAllChannels(title, commonContent, config, logPrefix = '[定时任务]', options = {}) { const metadata = options.metadata || {}; 如果 (!config.ENABLED_NOTIFIERS || config.ENABLED_NOTIFIERS.length === 0) { console.log(`${logPrefix} 未启用任何通知渠道。`); 返回; }
如果 (config.ENABLED_NOTIFIERS.includes('notifyx')) { const notifyxContent = ` const success =等待sendNotifyXNotification(标题,notifyxContent,`订阅提醒`,config); console.log(`${logPrefix} 发送NotifyX通知 ${success ? '成功' : '失败'}`); } 如果 (config.ENABLED_NOTIFIERS.includes('telegram')) { const telegramContent = `*${title}*\n\n${commonContent}`; const success = await sendTelegramNotification(telegramContent, config); console.log(`${logPrefix} 发送Telegram通知 ${success ? '成功' : '失败'}`); } 如果 (config.ENABLED_NOTIFIERS.includes('webhook')) { const webhookContent = commonContent.replace(/(\**|\*| const success = await sendWebhookNotification(title, webhookContent, config, metadata); console.log(`${logPrefix} 发送Webhook通知 ${success ? '成功' : '失败'}`); } if (config.ENABLED_NOTIFIERS.includes('wechatbot')) { const wechatbotContent = commonContent.replace(/(\**|\*| const success = await sendWechatBotNotification(title, wechatbotContent, config); console.log(`${logPrefix} 发送企业微信机器人通知 ${success ? '成功' : '失败'}`); } 如果 (config.ENABLED_NOTIFIERS.includes('weixin')) { const weixinContent = `【${title}】\n\n${commonContent.replace(/(\**|\*| const result = await sendWeComNotification(weixinContent, config); console.log(`${logPrefix} 发送企业微信通知${result.success ? '成功' : '失败'}.${result.message}`); } 如果 (config.ENABLED_NOTIFIERS.includes('email')) { const emailContent = commonContent.replace(/(\**|\*| const success = await sendEmailNotification(title, emailContent, config); console.log(`${logPrefix} 发送邮件通知 ${success ? '成功' : '失败'}`); } 如果 (config.ENABLED_NOTIFIERS.includes('bark')) { const barkContent = commonContent.replace(/(\**|\*| const success = await sendBarkNotification(title, barkContent, config); console.log(`${logPrefix} 发送Bark通知 ${success ? '成功' : '失败'}`); } }
异步函数 sendTelegramNotification(message, config) { 尝试 { 如果 (!config.TG_BOT_TOKEN || !config.TG_CHAT_ID) { console.error('[Telegram]通知未配置,缺少Bot Token或聊天ID'); 返回 false; }
console.log('[Telegram] 开始发送通知到聊天 ID: ' + config.TG_CHAT_ID);
const url = 'https://api.telegram.org/bot' + config.TG_BOT_TOKEN + '/sendMessage'; const response = await fetch(url, { 方法:'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ chat_id: config.TG_CHAT_ID, 短信, 解析模式:'Markdown' }) });
const result = await response.json(); console.log('[Telegram] 发送结果:', result); 返回 result.ok; } catch (error) { console.error('[Telegram]发送通知失败:', error); 返回 false; } }
异步函数 sendNotifyXNotification(title, content, description, config) { 尝试 { 如果 (!config.NOTIFYX_API_KEY) { console.error('[NotifyX]通知未配置,缺少API Key'); 返回 false; }
console.log('[NotifyX] 开始发送通知: ' + title);
const url = 'https://www.notifyx.cn/api/v1/send/' + config.NOTIFYX_API_KEY; const response = await fetch(url, { 方法:'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ 标题:标题, 内容:内容, 描述:描述 || '' }) });
const result = await response.json(); console.log('[NotifyX] 发送结果:', result); 返回结果状态 === '已排队'; } catch (error) { console.error('[NotifyX]发送通知失败:', error); 返回 false; } }
异步函数 sendBarkNotification(title, content, config) { 尝试 { 如果 (!config.BARK_DEVICE_KEY) { console.error('[Bark] 通知未配置,缺少设备Key'); 返回 false; }
console.log('[Bark] 开始发送通知到设备: ' + config.BARK_DEVICE_KEY);
const serverUrl = config.BARK_SERVER || 'https://api.day.app'; const url = serverUrl + '/push'; const payload = { 标题:标题, 正文:内容, 设备密钥:config.BARK_DEVICE_KEY };
// 如果配置了保存参数,则添加isArchive参数 如果 (config.BARK_IS_ARCHIVE === 'true') { payload.isArchive = 1; }
const response = await fetch(url, { 方法:'POST', 标题:{ 'Content-Type': 'application/json; charset=utf-8' }, body: JSON.stringify(payload) });
const result = await response.json(); console.log('[Bark] 发送结果:', result); // Bark API返回code为200表示成功 返回 result.code === 200; } catch (error) { console.error('[Bark]发送通知失败:', error); 返回 false; } }
异步函数 sendEmailNotification(title, content, config) { 尝试 { 如果 (!config.RESEND_API_KEY || !config.EMAIL_FROM || !config.EMAIL_TO) { console.error('[邮件通知]通知未配置,缺少必要参数'); 返回 false; }
console.log('[邮件通知]开始发送邮件到:' + config.EMAIL_TO);
// 生成HTML邮件内容 const htmlContent = ` <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>${title}</title> <style> body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; margin: 0; padding: 0; background-color: .container { max-width: 600px; margin: 0 auto; background-color: .header { background: linear-gradient(135deg, .header h1 { color: white; margin: 0; font-size: 24px; } .content { padding: 30px 20px; } .content h2 { color: .content p { color: .footer { background-color: .highlight { background-color: .button { display: inline-block; background: linear-gradient(135deg, </style> </head> <body> <div class="container"> <div class="header"> <h1>📅 ${title}</h1> </div> <div class="content"> <div class="highlight"> ${content.replace(/\n/g, '<br>')} </div> <p>此邮件由订阅管理系统自动发送,请及时处理相关订阅事务。</p> </div> <div class="footer"> <p>订阅管理系统| 发送时间: ${formatTimeInTimezone(new Date(), config?.TIMEZONE || 'UTC', 'datetime')}</p> </div> </div> </body> </html>`;
const fromEmail = config.EMAIL_FROM_NAME ? `${config.EMAIL_FROM_NAME} <${config.EMAIL_FROM}>` : config.EMAIL_FROM;
const response = await fetch('https://api.resend.com/emails', { 方法:'POST', 标题:{ '授权': `Bearer ${config.RESEND_API_KEY}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ 发件人:fromEmail, 至:config.EMAIL_TO, 主题:标题, html:html内容, text: content // 纯文本备用 }) });
const result = await response.json(); console.log('[邮件通知]发送结果:', response.status, result);
如果 (response.ok && result.id) { console.log('[邮件通知]邮件发送成功,ID:', result.id); 返回 true; } 别的 { console.error('[邮件通知]邮件发送失败:', result); 返回 false; } } catch (error) { console.error('[邮件通知]发送邮件失败:', error); 返回 false; } }
异步函数 sendNotification(title, content, description, config) { 如果 (config.NOTIFICATION_TYPE === 'notifyx') { return await sendNotifyXNotification(title, content, description, config); } 别的 { return await sendTelegramNotification(content, config); } }
// 4.修改定时任务checkExpiringSubscriptions,支持农历周期自动续订和农历提醒 异步函数 checkExpiringSubscriptions(env) { 尝试 { const config = await getConfig(env); const timezone = config?.TIMEZONE || 'UTC'; const currentTime = getCurrentTimeInTimezone(timezone); console.log('[定时任务]开始检查即将订阅的UTC: ' + new Date().toISOString() + ', ' + timezone + ': ' + currentTime.toLocaleString('zh-CN', {timeZone: timezone}));
const currentMidnight = getTimezoneMidnightTimestamp(currentTime, 时区); // 统一计算当天的零点时间,避免多次修复
const rawNotificationHours = Array.isArray(config.NOTIFICATION_HOURS) ? config.NOTIFICATION_HOURS : []; const normalizedNotificationHours = rawNotificationHours .map(value => String(value).trim()) .filter(value => value.length > 0) .map(value => value === '*' ? '*' : value.toUpperCase() === 'ALL' ? 'ALL' : value.padStart(2, '0')); const allowAllHours = normalizedNotificationHours.includes('*') || normalizedNotificationHours.includes('ALL'); const hourFormatter = new Intl.DateTimeFormat('en-US', { timeZone: timezone, hour12: false, hour: '2-digit' }); const currentHour = hourFormatter.format(currentTime); const shouldNotifyThisHour = allowAllHours || normalizedNotificationHours.length === 0 || normalizedNotificationHours.includes(currentHour);
const subscriptions = await getAllSubscriptions(env); console.log('[定时任务]共找到' + subscriptions.length + '个订阅'); const expiringSubscriptions = []; const updatedSubscriptions = []; let hasUpdates = false;
for (const subscription of subscriptions) { 如果(subscription.isActive === false){ console.log('[定时任务]订阅 "' + subscription.name + '" 已终止,跳过'); 继续; }
const reminderSetting = resolveReminderSetting(subscription); 令 diffMs = 0; let diffHours = 0; let daysDiff; 如果 (subscription.useLunar) { const expiryDate = new Date(subscription.expiryDate); let lunar = lunarCalendar.solar2lunar( expiryDate.getFullYear(), expiryDate.getMonth() + 1, expiryDate.getDate() ); const solar = lunarBiz.lunar2solar(lunar); const lunarDate = new Date(solar.year, solar.month - 1, solar.day); const lunarMidnight = getTimezoneMidnightTimestamp(lunarDate, timezone); daysDiff = Math.round((lunarMidnight - currentMidnight) / MS_PER_DAY);
console.log('[定时任务]订阅 "' + subscription.name + '" 回复日期: ' + expiryDate.toISOString() + ', 农历转换后午夜时间: ' + new Date(lunarMidnight).toISOString() + ', 剩余天数: ' + daysDiff);
diffMs = expiryDate.getTime() - currentTime.getTime(); diffHours = diffMs / MS_PER_HOUR;
如果(天数差 < 0 && 订阅周期值 && 订阅周期单位 && 订阅自动续订 !== false){ let nextLunar = lunar; 做 { nextLunar = lunarBiz.addLunarPeriod(nextLunar, subscription.periodValue, subscription.periodUnit); const solar = lunarBiz.lunar2solar(nextLunar); var newExpiryDate = new Date(solar.year, solar.month - 1, solar.day); const newLunarMidnight = getTimezoneMidnightTimestamp(newExpiryDate, timezone); daysDiff = Math.round((newLunarMidnight - currentMidnight) / MS_PER_DAY); console.log('[定时任务]订阅 "' + subscription.name + '" 更新日期: ' + newExpiryDate.toISOString() + ', 农历转换后午夜时间: ' + new Date(newLunarMidnight).toISOString() + ', 剩余天数: ' + daysDiff); } while (daysDiff < 0);
diffMs = newExpiryDate.getTime() - currentTime.getTime(); diffHours = diffMs / MS_PER_HOUR;
const updatedSubscription = { ...subscription, expiryDate: newExpiryDate.toISOString() }; updatedSubscriptions.push(updatedSubscription); hasUpdates = true;
const shouldRemindAfterRenewal = shouldTriggerReminder(reminderSetting, daysDiff, diffHours); 如果(应该在续订后提醒){ console.log('[定时任务]订阅 "' + subscription.name + '" 提醒在范围内,将发送通知'); expiringSubscriptions.push({ ...更新订阅, 剩余天数:天差, 剩余小时数:Math.round(diffHours) }); } 继续; } } 别的 { const expiryDate = new Date(subscription.expiryDate); const expiryMidnight = getTimezoneMidnightTimestamp(expiryDate, timezone);
daysDiff = Math.round((expiryMidnight - currentMidnight) / MS_PER_DAY);
console.log('[定时任务]订阅 "' + subscription.name + '" 回复日期: ' + expiryDate.toISOString() + ', 时区午夜时间: ' + new Date(expiryMidnight).toISOString() + ', 剩余天数: ' + daysDiff);
diffMs = expiryDate.getTime() - currentTime.getTime(); diffHours = diffMs / MS_PER_HOUR;
如果(天数差 < 0 && 订阅周期值 && 订阅周期单位 && 订阅自动续订 !== false){ const newExpiryDate = new Date(expiryDate);
如果 (subscription.periodUnit === 'day') { newExpiryDate.setDate(expiryDate.getDate() + subscription.periodValue); } else if (subscription.periodUnit === 'month') { newExpiryDate.setMonth(expiryDate.getMonth() + subscription.periodValue); } else if (subscription.periodUnit === 'year') { newExpiryDate.setFullYear(expiryDate.getFullYear() + subscription.periodValue); }
let newExpiryMidnight = getTimezoneMidnightTimestamp(newExpiryDate, timezone); while (newExpiryMidnight < currentMidnight) { console.log('[定时任务]新计算的转换日期 ' + newExpiryDate.toISOString() + ' (时区转换后午夜: ' + new Date(newExpiryMidnight).toISOString() + ') 仍然,过渡继续计算下一个周期'); 如果 (subscription.periodUnit === 'day') { newExpiryDate.setDate(newExpiryDate.getDate() + subscription.periodValue); } else if (subscription.periodUnit === 'month') { newExpiryDate.setMonth(newExpiryDate.getMonth() + subscription.periodValue); } else if (subscription.periodUnit === 'year') { newExpiryDate.setFullYear(newExpiryDate.getFullYear() + subscription.periodValue); } newExpiryMidnight = getTimezoneMidnightTimestamp(newExpiryDate, timezone); }
console.log('[定时任务]订阅 "' + subscription.name + '" 更新近期日期: ' + newExpiryDate.toISOString());
diffMs = newExpiryDate.getTime() - currentTime.getTime(); diffHours = diffMs / MS_PER_HOUR;
const updatedSubscription = { ...subscription, expiryDate: newExpiryDate.toISOString() }; updatedSubscriptions.push(updatedSubscription); hasUpdates = true;
const newDaysDiff = Math.round((newExpiryMidnight - currentMidnight) / MS_PER_DAY); const shouldRemindAfterRenewal = shouldTriggerReminder(reminderSetting, newDaysDiff, diffHours); 如果(应该在续订后提醒){ console.log('[定时任务]订阅 "' + subscription.name + '" 提醒在范围内,将发送通知'); expiringSubscriptions.push({ ...更新订阅, 剩余天数:新天数差, 剩余小时数:Math.round(diffHours) }); } 继续; } }
diffMs = new Date(subscription.expiryDate).getTime() - currentTime.getTime(); diffHours = diffMs / MS_PER_HOUR; const shouldRemind = shouldTriggerReminder(reminderSetting, daysDiff, diffHours);
if (daysDiff < 0 && subscription.autoRenew === false) { console.log('[定时任务]订阅 "' + subscription.name + '" 已过期且未启用自动续订,将发送过期通知'); expiringSubscriptions.push({ ...订阅, 剩余天数:天差, 剩余小时数:Math.round(diffHours) }); } else if (shouldRemind) { console.log('[定时任务]订阅 "' + subscription.name + '" 提醒在范围内,将发送通知'); expiringSubscriptions.push({ ...订阅, 剩余天数:天差, 剩余小时数:Math.round(diffHours) }); } }
如果(有更新){ const mergedSubscriptions = subscriptions.map(sub => { const updated = updatedSubscriptions.find(u => u.id === sub.id); 返回更新后的子程序; }); await env.SUBSCRIPTIONS_KV.put('subscriptions', JSON.stringify(mergedSubscriptions)); }
如果(过期订阅.长度 > 0){ 如果 (!shouldNotifyThisHour) { console.log('[定时任务]当前小时' + currentHour + '未配置为自治时间,跳过发送通知'); expiringSubscriptions.length = 0; } 别的 { // 按一下时间排序 expiringSubscriptions.sort((a, b) => a.daysRemaining - b.daysRemaining);
// 使用优化的格式化函数 const commonContent = formatNotificationContent(expiringSubscriptions, config); const metadataTags = extractTagsFromSubscriptions(expiringSubscriptions);
const title = '订阅提醒'; wait sendNotificationToAllChannels(title, commonContent, config, '[定时任务]', { 元数据:{ 标签:metadataTags } }); } } } catch (error) { console.error('[定时任务]检查即将到来的订阅失败:', error); } }
function getCookieValue(cookieString, key) { 如果 (!cookieString) 返回 null;
const match = cookieString.match(new RegExp('(^| )' + key + '=([^;]+)')); 返回匹配项?匹配项[2]:null; }
异步函数 handleRequest(request, env, ctx) { 返回新的 Response(loginPage, { headers: { 'Content-Type': 'text/html; charset=utf-8' } }); }
const CryptoJS = { HmacSHA256: 函数(message, key) { const keyData = new TextEncoder().encode(key); const messageData = new TextEncoder().encode(message);
return Promise.resolve().then(() => { 返回 crypto.subtle.importKey( “生的”, keyData, { name: "HMAC", hash: {name: "SHA-256"}}, 错误的, [“符号”] ); }).then(cryptoKey => { 返回 crypto.subtle.sign( “HMAC”, 加密密钥, 消息数据 ); }).then(buffer => { const hashArray = Array.from(new Uint8Array(buffer)); return hashArray.map(b => b.toString(16).padStart(2, '0')).join(''); }); } };
function getCurrentTime(config) { const timezone = config?.TIMEZONE || 'UTC'; const currentTime = getCurrentTimeInTimezone(timezone); const formatter = new Intl.DateTimeFormat('zh-CN', { 时区:时区, 年份:'数字',月份:'两位数',日期:'两位数', 小时:两位数,分钟:两位数,秒:两位数 }); 返回 { 日期:当前时间, localString: formatter.format(currentTime), isoString: currentTime.toISOString() }; }
export default { 异步获取(请求,环境,ctx) { const url = new URL(request.url);
//添加调试页面 如果 (url.pathname === '/debug') { 尝试 { const config = await getConfig(env); const debugInfo = { timestamp: new Date().toISOString(), // 使用UTC时钟 路径名:url.路径名, kvBinding: !!env.SUBSCRIPTIONS_KV, configExists: !!config, adminUsername: config.ADMIN_USERNAME, hasJwtSecret: !!config.JWT_SECRET, jwtSecretLength: config.JWT_SECRET ? config.JWT_SECRET.length : 0 };
返回新的响应(` <!DOCTYPE html> <html> <head> <title>调试信息</title> <style> body { font-family: monospace; padding: 20px; background: .info { background: white; padding: 15px; margin: 10px 0; border-radius: 5px; } .success { 颜色:绿色; } .error { color: red; } </style> </head> <body> <h1>系统调试信息</h1> <div class="info"> <h3>基本信息</h3> <p>时间:${debugInfo.timestamp}</p> <p>路径:${debugInfo.pathname}</p> <p class="${debugInfo.kvBinding ? 'success' : 'error'}">键绑定:${debugInfo.kvBinding ? '✓' : '✗'}</p> </div>
<div class="info"> <h3>配置信息</h3> <p class="${debugInfo.configExists ? 'success' : 'error'}">配置存在: ${debugInfo.configExists ? '✓' : '✗'}</p> <p>管理员用户名:${debugInfo.adminUsername}</p> <p class="${debugInfo.hasJwtSecret ? 'success' : 'error'}">JWT 密钥:${debugInfo.hasJwtSecret ? '✓' : '✗'}(长度:${debugInfo.jwtSecretLength})</p> </div>
<div class="info"> <h3>解决方案</h3> <p>1. 确定KV命名空间已正确绑定为SUBSCRIPTIONS_KV</p> <p>2. 尝试访问 <a href="/">/</a> 进行登录</p> <p>3. 如果问题,请检查Cloudflare Workers日志</p> </div> </body> </html>`, { headers: { 'Content-Type': 'text/html; charset=utf-8' } }); } catch (error) { 返回新的响应(`调试页面错误:$ {error.message}`,{ 状态:500 headers: { 'Content-Type': 'text/plain; charset=utf-8' } }); } }
如果 (url.pathname.startsWith('/api')) { return api.handleRequest(request, env, ctx); } else if (url.pathname.startsWith('/admin')) { return admin.handleRequest(request, env, ctx); } 别的 { 返回 handleRequest(request, env, ctx); } },
async scheduled(event, env, ctx) { const config = await getConfig(env); const timezone = config?.TIMEZONE || 'UTC'; const currentTime = getCurrentTimeInTimezone(timezone); console.log('[Workers]定时任务触发UTC:', new Date().toISOString(), timezone + ':', currentTime.toLocaleString('zh-CN', {timeZone: timezone})); await checkExpiringSubscriptions(env); } };
|