Spaces:
Paused
Paused
File size: 134,663 Bytes
b72f5af |
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 |
/**
* Copyright (C) 2024 Puter Technologies Inc.
*
* This file is part of Puter.
*
* Puter is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import path from "./lib/path.js"
import mime from "./lib/mime.js";
import UIAlert from './UI/UIAlert.js'
import UIItem from './UI/UIItem.js'
import UIWindow from './UI/UIWindow.js'
import UIWindowLogin from './UI/UIWindowLogin.js';
import UIWindowSaveAccount from './UI/UIWindowSaveAccount.js';
import UIWindowConfirmDownload from './UI/UIWindowConfirmDownload.js';
import UIWindowCopyProgress from './UI/UIWindowCopyProgress.js';
import UIWindowMoveProgress from './UI/UIWindowMoveProgress.js';
import UIWindowNewFolderProgress from './UI/UIWindowNewFolderProgress.js';
import UIWindowDownloadProgress from './UI/UIWindowDownloadProgress.js';
import UIWindowUploadProgress from './UI/UIWindowUploadProgress.js';
import UIWindowProgressEmptyTrash from './UI/UIWindowProgressEmptyTrash.js';
import download from './helpers/download.js';
import update_username_in_gui from './helpers/update_username_in_gui.js';
import update_title_based_on_uploads from './helpers/update_title_based_on_uploads.js';
import content_type_to_icon from './helpers/content_type_to_icon.js';
import UIWindowDownloadDirProg from './UI/UIWindowDownloadDirProg.js';
window.is_auth = ()=>{
if(localStorage.getItem("auth_token") === null || auth_token === null)
return false;
else
return true;
}
window.suggest_apps_for_fsentry = async (options)=>{
let res = await $.ajax({
url: api_origin + "/suggest_apps",
type: 'POST',
contentType: "application/json",
data: JSON.stringify({
uid: options.uid ?? undefined,
path: options.path ?? undefined,
}),
headers: {
"Authorization": "Bearer "+auth_token
},
statusCode: {
401: function () {
logout();
},
},
success: function (res){
if(options.onSuccess && typeof options.onSuccess == "function")
options.onSuccess(res);
}
});
return res;
}
/**
* Formats a binary-byte integer into the human-readable form with units.
*
* @param {integer} bytes
* @returns
*/
window.byte_format = (bytes)=>{
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
if (bytes === 0) return '0 Byte';
const i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
return (bytes / Math.pow(1024, i)).toFixed(2) + ' ' + sizes[i];
};
/**
* A function that generates a UUID (Universally Unique Identifier) using the version 4 format,
* which are random UUIDs. It uses the cryptographic number generator available in modern browsers.
*
* The generated UUID is a 36 character string (32 alphanumeric characters separated by 4 hyphens).
* It follows the pattern: xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx, where x is any hexadecimal digit
* and y is one of 8, 9, A, or B.
*
* @returns {string} Returns a new UUID v4 string.
*
* @example
*
* let id = window.uuidv4(); // Generate a new UUID
*
*/
window.uuidv4 = ()=>{
return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c =>
(c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)
);
}
/**
* Checks if the provided string is a valid email format.
*
* @function
* @global
* @param {string} email - The email string to be validated.
* @returns {boolean} `true` if the email is valid, otherwise `false`.
* @example
* window.is_email("test@example.com"); // true
* window.is_email("invalid-email"); // false
*/
window.is_email = (email) => {
const re = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(String(email).toLowerCase());
}
/**
* A function that truncates a file name if it exceeds a certain length, while preserving the file extension.
* An ellipsis character '…' is added to indicate the truncation. If the original filename is short enough,
* it is returned unchanged.
*
* @param {string} input - The original filename to be potentially truncated.
* @param {number} max_length - The maximum length for the filename. If the original filename (excluding the extension) exceeds this length, it will be truncated.
*
* @returns {string} The truncated filename with preserved extension if original filename is too long; otherwise, the original filename.
*
* @example
*
* let truncatedFilename = window.truncate_filename('really_long_filename.txt', 10);
* // truncatedFilename would be something like 'really_lo…me.txt'
*
*/
window.truncate_filename = (input, max_length)=>{
const extname = path.extname('/' + input);
if ((input.length - 15) > max_length){
if(extname !== '')
return input.substring(0, max_length) + '…' + input.slice(-1 * (extname.length + 2));
else
return input.substring(0, max_length) + '…';
}
return input;
};
/**
* A function that scrolls the parent element so that the child element is in view.
* If the child element is already in view, no scrolling occurs.
* The function decides the best scroll direction based on which requires the smaller adjustment.
*
* @param {HTMLElement} parent - The parent HTML element that might be scrolled.
* @param {HTMLElement} child - The child HTML element that should be made viewable.
*
* @returns {void}
*
* @example
*
* let parentElem = document.querySelector('#parent');
* let childElem = document.querySelector('#child');
* window.scrollParentToChild(parentElem, childElem);
* // Scrolls parentElem so that childElem is in view
*
*/
window.scrollParentToChild = (parent, child)=>{
// Where is the parent on page
var parentRect = parent.getBoundingClientRect();
// What can you see?
var parentViewableArea = {
height: parent.clientHeight,
width: parent.clientWidth
};
// Where is the child
var childRect = child.getBoundingClientRect();
// Is the child viewable?
var isViewable = (childRect.top >= parentRect.top) && (childRect.bottom <= parentRect.top + parentViewableArea.height);
// if you can't see the child try to scroll parent
if (!isViewable) {
// Should we scroll using top or bottom? Find the smaller ABS adjustment
const scrollTop = childRect.top - parentRect.top;
const scrollBot = childRect.bottom - parentRect.bottom;
if (Math.abs(scrollTop) < Math.abs(scrollBot)) {
// we're near the top of the list
parent.scrollTop += (scrollTop + 80);
} else {
// we're near the bottom of the list
parent.scrollTop += (scrollBot + 80);
}
}
}
window.getItem = async function(options){
return $.ajax({
url: api_origin + "/getItem",
type: 'POST',
data: JSON.stringify({
key: options.key,
app: options.app_uid,
}),
async: true,
contentType: "application/json",
headers: {
"Authorization": "Bearer "+auth_token
},
statusCode: {
401: function () {
logout();
},
},
success: function (result){
if(options.success && typeof(options.success) === "function")
options.success(result);
}
})
}
window.setItem = async function(options){
return $.ajax({
url: api_origin + "/setItem",
type: 'POST',
data: JSON.stringify({
app: options.app_uid,
key: options.key,
value: options.value,
}),
async: true,
contentType: "application/json",
headers: {
"Authorization": "Bearer "+auth_token
},
statusCode: {
401: function () {
logout();
},
},
success: function (fsentry){
if(options.success && typeof(options.success) === "function")
options.success(fsentry)
}
})
}
/**
* Converts a glob pattern to a regular expression, with optional extended or globstar matching.
*
* @param {string} glob - The glob pattern to convert.
* @param {Object} [opts] - Optional options for the conversion.
* @param {boolean} [opts.extended=false] - If true, enables extended matching with single character matching, character ranges, group matching, etc.
* @param {boolean} [opts.globstar=false] - If true, uses globstar matching, where '*' matches zero or more path segments.
* @param {string} [opts.flags] - Regular expression flags to include (e.g., 'i' for case-insensitive).
* @returns {RegExp} The generated regular expression.
* @throws {TypeError} If the provided glob pattern is not a string.
*/
window.globToRegExp = function (glob, opts) {
if (typeof glob !== 'string') {
throw new TypeError('Expected a string');
}
var str = String(glob);
// The regexp we are building, as a string.
var reStr = "";
// Whether we are matching so called "extended" globs (like bash) and should
// support single character matching, matching ranges of characters, group
// matching, etc.
var extended = opts ? !!opts.extended : false;
// When globstar is _false_ (default), '/foo/*' is translated a regexp like
// '^\/foo\/.*$' which will match any string beginning with '/foo/'
// When globstar is _true_, '/foo/*' is translated to regexp like
// '^\/foo\/[^/]*$' which will match any string beginning with '/foo/' BUT
// which does not have a '/' to the right of it.
// E.g. with '/foo/*' these will match: '/foo/bar', '/foo/bar.txt' but
// these will not '/foo/bar/baz', '/foo/bar/baz.txt'
// Lastely, when globstar is _true_, '/foo/**' is equivelant to '/foo/*' when
// globstar is _false_
var globstar = opts ? !!opts.globstar : false;
// If we are doing extended matching, this boolean is true when we are inside
// a group (eg {*.html,*.js}), and false otherwise.
var inGroup = false;
// RegExp flags (eg "i" ) to pass in to RegExp constructor.
var flags = opts && typeof (opts.flags) === "string" ? opts.flags : "";
var c;
for (var i = 0, len = str.length; i < len; i++) {
c = str[i];
switch (c) {
case "/":
case "$":
case "^":
case "+":
case ".":
case "(":
case ")":
case "=":
case "!":
case "|":
reStr += "\\" + c;
break;
case "?":
if (extended) {
reStr += ".";
break;
}
case "[":
case "]":
if (extended) {
reStr += c;
break;
}
case "{":
if (extended) {
inGroup = true;
reStr += "(";
break;
}
case "}":
if (extended) {
inGroup = false;
reStr += ")";
break;
}
case ",":
if (inGroup) {
reStr += "|";
break;
}
reStr += "\\" + c;
break;
case "*":
// Move over all consecutive "*"'s.
// Also store the previous and next characters
var prevChar = str[i - 1];
var starCount = 1;
while (str[i + 1] === "*") {
starCount++;
i++;
}
var nextChar = str[i + 1];
if (!globstar) {
// globstar is disabled, so treat any number of "*" as one
reStr += ".*";
} else {
// globstar is enabled, so determine if this is a globstar segment
var isGlobstar = starCount > 1 // multiple "*"'s
&& (prevChar === "/" || prevChar === undefined) // from the start of the segment
&& (nextChar === "/" || nextChar === undefined) // to the end of the segment
if (isGlobstar) {
// it's a globstar, so match zero or more path segments
reStr += "((?:[^/]*(?:\/|$))*)";
i++; // move over the "/"
} else {
// it's not a globstar, so only match one path segment
reStr += "([^/]*)";
}
}
break;
default:
reStr += c;
}
}
// When regexp 'g' flag is specified don't
// constrain the regular expression with ^ & $
if (!flags || !~flags.indexOf('g')) {
reStr = "^" + reStr + "$";
}
return new RegExp(reStr, flags);
};
/**
* Validates the provided file system entry name.
*
* @function validate_fsentry_name
* @memberof window
* @param {string} name - The name of the file system entry to validate.
* @returns {boolean} Returns true if the name is valid.
* @throws {Object} Throws an object with a `message` property indicating the specific validation error.
*
* @description
* This function checks the provided name against a set of rules to determine its validity as a file system entry name:
* 1. Name cannot be empty.
* 2. Name must be a string.
* 3. Name cannot contain the '/' character.
* 4. Name cannot be the '.' character.
* 5. Name cannot be the '..' character.
* 6. Name cannot exceed the maximum allowed length (as defined in window.max_item_name_length).
*/
window.validate_fsentry_name = function(name){
if(!name)
throw {message: 'Name cannot be empty.'}
else if(!isString(name))
throw {message: "Name can only be a string."}
else if(name.includes('/'))
throw {message: "Name cannot contain the '/' character."}
else if(name === '.')
throw {message: "Name can not be the '.' character."};
else if(name === '..')
throw {message: "Name can not be the '..' character."};
else if(name.length > window.max_item_name_length)
throw {message: `Name can not be longer than ${config.max_item_name_length} characters`}
else
return true
}
/**
* A function that generates a unique identifier by combining a random adjective, a random noun, and a random number (between 0 and 9999).
* The result is returned as a string with components separated by hyphens.
* It is useful when you need to create unique identifiers that are also human-friendly.
*
* @returns {string} A unique, hyphen-separated string comprising of an adjective, a noun, and a number.
*
* @example
*
* let identifier = window.generate_identifier();
* // identifier would be something like 'clever-idea-123'
*
*/
window.generate_identifier = function(){
const first_adj = ['helpful','sensible', 'loyal', 'honest', 'clever', 'capable','calm', 'smart', 'genius', 'bright', 'charming', 'creative', 'diligent', 'elegant', 'fancy',
'colorful', 'avid', 'active', 'gentle', 'happy', 'intelligent', 'jolly', 'kind', 'lively', 'merry', 'nice', 'optimistic', 'polite',
'quiet', 'relaxed', 'silly', 'victorious', 'witty', 'young', 'zealous', 'strong', 'brave', 'agile', 'bold'];
const nouns = ['street', 'roof', 'floor', 'tv', 'idea', 'morning', 'game', 'wheel', 'shoe', 'bag', 'clock', 'pencil', 'pen',
'magnet', 'chair', 'table', 'house', 'dog', 'room', 'book', 'car', 'cat', 'tree',
'flower', 'bird', 'fish', 'sun', 'moon', 'star', 'cloud', 'rain', 'snow', 'wind', 'mountain',
'river', 'lake', 'sea', 'ocean', 'island', 'bridge', 'road', 'train', 'plane', 'ship', 'bicycle',
'horse', 'elephant', 'lion', 'tiger', 'bear', 'zebra', 'giraffe', 'monkey', 'snake', 'rabbit', 'duck',
'goose', 'penguin', 'frog', 'crab', 'shrimp', 'whale', 'octopus', 'spider', 'ant', 'bee', 'butterfly', 'dragonfly',
'ladybug', 'snail', 'camel', 'kangaroo', 'koala', 'panda', 'piglet', 'sheep', 'wolf', 'fox', 'deer', 'mouse', 'seal',
'chicken', 'cow', 'dinosaur', 'puppy', 'kitten', 'circle', 'square', 'garden', 'otter', 'bunny', 'meerkat', 'harp']
// return a random combination of first_adj + noun + number (between 0 and 9999)
// e.g. clever-idea-123
return first_adj[Math.floor(Math.random() * first_adj.length)] + '-' + nouns[Math.floor(Math.random() * nouns.length)] + '-' + Math.floor(Math.random() * 10000);
}
/**
* Checks if the provided variable is a string or an instance of the String object.
*
* @param {*} variable - The variable to check.
* @returns {boolean} True if the variable is a string or an instance of the String object, false otherwise.
*/
window.isString = function (variable) {
return typeof variable === 'string' || variable instanceof String;
}
/**
* A function that checks whether a file system entry (fsentry) matches a list of allowed file types.
* It handles both file extensions (like '.jpg') and MIME types (like 'text/plain').
* If the allowed file types string is empty or not provided, the function always returns true.
* It checks the file types only if the fsentry is a file, not a directory.
*
* @param {Object} fsentry - The file system entry to check. It must be an object with properties: 'is_dir', 'name', 'type'.
* @param {string} allowed_file_types_string - The list of allowed file types, separated by commas. Can include extensions and MIME types.
*
* @returns {boolean} True if the fsentry matches one of the allowed file types, or if the allowed_file_types_string is empty or not provided. False otherwise.
*
* @example
*
* let fsentry = {is_dir: false, name: 'example.jpg', type: 'image/jpeg'};
* let allowedTypes = '.jpg, text/plain, image/*';
* let result = window.check_fsentry_against_allowed_file_types_string(fsentry, allowedTypes);
* // result would be true, as 'example.jpg' matches the '.jpg' in allowedTypes
*
*/
window.check_fsentry_against_allowed_file_types_string =function (fsentry, allowed_file_types_string) {
// simple cases that are always a pass
if(!allowed_file_types_string || allowed_file_types_string.trim() === '')
return true;
// parse allowed_file_types into an array of extensions and types
let allowed_file_types = allowed_file_types_string.split(',');
if(allowed_file_types.length > 0){
// trim every entry
for (let index = 0; index < allowed_file_types.length; index++) {
allowed_file_types[index] = allowed_file_types[index].trim();
}
}
let passes_allowed_file_type_filter = true;
// check types, only if this fsentry is a file and not a directory
if(!fsentry.is_dir && allowed_file_types.length > 0){
passes_allowed_file_type_filter = false;
for (let index = 0; index < allowed_file_types.length; index++) {
const allowed_file_type = allowed_file_types[index].toLowerCase();
// if type is not already set, try to set it based on the file name
if(!fsentry.type)
fsentry.type = mime.getType(fsentry.name);
// extensions (e.g. .jpg)
if(allowed_file_type.startsWith('.') && fsentry.name.toLowerCase().endsWith(allowed_file_type)){
passes_allowed_file_type_filter = true;
break;
}
// MIME types (e.g. text/plain)
else if(globToRegExp(allowed_file_type).test(fsentry.type?.toLowerCase())){
passes_allowed_file_type_filter = true;
break;
}
}
}
return passes_allowed_file_type_filter;
}
// @author Rich Adams <rich@richadams.me>
// Implements a tap and hold functionality. If you click/tap and release, it will trigger a normal
// click event. But if you click/tap and hold for 1s (default), it will trigger a taphold event instead.
;(function($)
{
// Default options
var defaults = {
duration: 500, // ms
clickHandler: null
}
// When start of a taphold event is triggered.
function startHandler(event)
{
var $elem = jQuery(this);
// Merge the defaults and any user defined settings.
let settings = jQuery.extend({}, defaults, event.data);
// If object also has click handler, store it and unbind. Taphold will trigger the
// click itself, rather than normal propagation.
if (typeof $elem.data("events") != "undefined"
&& typeof $elem.data("events").click != "undefined")
{
// Find the one without a namespace defined.
for (var c in $elem.data("events").click)
{
if ($elem.data("events").click[c].namespace == "")
{
var handler = $elem.data("events").click[c].handler
$elem.data("taphold_click_handler", handler);
$elem.unbind("click", handler);
break;
}
}
}
// Otherwise, if a custom click handler was explicitly defined, then store it instead.
else if (typeof settings.clickHandler == "function")
{
$elem.data("taphold_click_handler", settings.clickHandler);
}
// Reset the flags
$elem.data("taphold_triggered", false); // If a hold was triggered
$elem.data("taphold_clicked", false); // If a click was triggered
$elem.data("taphold_cancelled", false); // If event has been cancelled.
// Set the timer for the hold event.
$elem.data("taphold_timer",
setTimeout(function()
{
// If event hasn't been cancelled/clicked already, then go ahead and trigger the hold.
if (!$elem.data("taphold_cancelled")
&& !$elem.data("taphold_clicked"))
{
// Trigger the hold event, and set the flag to say it's been triggered.
$elem.trigger(jQuery.extend(event, jQuery.Event("taphold")));
$elem.data("taphold_triggered", true);
}
}, settings.duration));
}
// When user ends a tap or click, decide what we should do.
function stopHandler(event)
{
var $elem = jQuery(this);
// If taphold has been cancelled, then we're done.
if ($elem.data("taphold_cancelled")) { return; }
// Clear the hold timer. If it hasn't already triggered, then it's too late anyway.
clearTimeout($elem.data("taphold_timer"));
// If hold wasn't triggered and not already clicked, then was a click event.
if (!$elem.data("taphold_triggered")
&& !$elem.data("taphold_clicked"))
{
// If click handler, trigger it.
if (typeof $elem.data("taphold_click_handler") == "function")
{
$elem.data("taphold_click_handler")(jQuery.extend(event, jQuery.Event("click")));
}
// Set flag to say we've triggered the click event.
$elem.data("taphold_clicked", true);
}
}
// If a user prematurely leaves the boundary of the object we're working on.
function leaveHandler(event)
{
// Cancel the event.
$(this).data("taphold_cancelled", true);
}
// Determine if touch events are supported.
var touchSupported = ("ontouchstart" in window) // Most browsers
|| ("onmsgesturechange" in window); // Microsoft
var taphold = $.event.special.taphold =
{
setup: function(data)
{
$(this).bind((touchSupported ? "touchstart" : "mousedown"), data, startHandler)
.bind((touchSupported ? "touchend" : "mouseup"), stopHandler)
.bind((touchSupported ? "touchmove touchcancel" : "mouseleave"), leaveHandler);
},
teardown: function(namespaces)
{
$(this).unbind((touchSupported ? "touchstart" : "mousedown"), startHandler)
.unbind((touchSupported ? "touchend" : "mouseup"), stopHandler)
.unbind((touchSupported ? "touchmove touchcancel" : "mouseleave"), leaveHandler);
}
};
})(jQuery);
window.refresh_user_data = async (auth_token)=>{
let whoami
try{
whoami = await puter.os.user();
}catch(e){
}
// update local user data
if(whoami){
update_auth_data(auth_token, whoami)
}
}
window.update_auth_data = (auth_token, user)=>{
window.auth_token = auth_token;
localStorage.setItem('auth_token', auth_token);
// Has username changed?
if(window.user?.username !== user.username)
update_username_in_gui(user.username);
// update this session's user data
window.user = user;
localStorage.setItem('user', JSON.stringify(window.user));
// re-initialize the Puter.js objects with the new auth token
puter.setAuthToken(auth_token, api_origin)
//update the logged_in_users array entry for this user
if(window.user){
let logged_in_users_updated = false;
for (let i = 0; i < window.logged_in_users.length && !logged_in_users_updated; i++) {
if(window.logged_in_users[i].uuid === window.user.uuid){
window.logged_in_users[i] = window.user;
window.logged_in_users[i].auth_token = window.auth_token;
logged_in_users_updated = true;
}
}
// no matching array elements, add one
if(!logged_in_users_updated){
let userobj = window.user;
userobj.auth_token = window.auth_token;
window.logged_in_users.push(userobj);
}
// update local storage
localStorage.setItem('logged_in_users', JSON.stringify(window.logged_in_users));
}
window.desktop_path = '/' + window.user.username + '/Desktop';
window.trash_path = '/' + window.user.username + '/Trash';
window.appdata_path = '/' + window.user.username + '/AppData';
window.docs_path = '/' + window.user.username + '/Documents';
window.pictures_path = '/' + window.user.username + '/Pictures';
window.videos_path = '/' + window.user.username + '/Videos';
window.desktop_path = '/' + window.user.username + '/Desktop';
window.home_path = '/' + window.user.username;
if(window.user !== null && !window.user.is_temp){
$('.user-options-login-btn, .user-options-create-account-btn').hide();
$('.user-options-menu-btn').show();
}
}
window.sendWindowWillCloseMsg = function(iframe_element) {
return new Promise(function(resolve){
const msg_id = uuidv4();
iframe_element.contentWindow.postMessage({
msg: "windowWillClose",
msg_id: msg_id
}, '*');
//register callback
appCallbackFunctions[msg_id] = resolve;
})
}
window.logout = ()=>{
document.dispatchEvent(new Event("logout", { bubbles: true}));
}
/**
* Checks if the current document is in fullscreen mode.
*
* @function is_fullscreen
* @memberof window
* @returns {boolean} Returns true if the document is in fullscreen mode, otherwise false.
*
* @example
* // Checks if the document is currently in fullscreen mode
* const inFullscreen = window.is_fullscreen();
*
* @description
* This function checks various browser-specific properties to determine if the document
* is currently being displayed in fullscreen mode. It covers standard as well as
* some vendor-prefixed properties to ensure compatibility across different browsers.
*/
window.is_fullscreen = ()=>{
return (document.fullscreenElement && document.fullscreenElement !== null) ||
(document.webkitIsFullScreen && document.webkitIsFullScreen !== null) ||
(document.webkitFullscreenElement && document.webkitFullscreenElement !== null) ||
(document.mozFullScreenElement && document.mozFullScreenElement !== null) ||
(document.msFullscreenElement && document.msFullscreenElement !== null);
}
window.get_apps = async (app_names, callback)=>{
if(Array.isArray(app_names))
app_names = app_names.join('|');
// 'explorer' is a special app, no metadata should be returned
if(app_names === 'explorer')
return [];
let res = await $.ajax({
url: api_origin + "/apps/"+app_names,
type: 'GET',
async: true,
contentType: "application/json",
headers: {
"Authorization": "Bearer "+auth_token
},
success: function (res){
}
});
if(res.length === 1)
res = res[0];
if(callback && typeof callback === 'function')
callback(res);
else
return res;
}
/**
* Sends an "itemChanged" event to all watching applications associated with a specific item.
*
* @function sendItemChangeEventToWatchingApps
* @memberof window
* @param {string} item_uid - Unique identifier of the item that experienced the change.
* @param {Object} event_data - Additional data about the event to be passed to the watching applications.
*
* @description
* This function sends an "itemChanged" message to all applications that are currently watching
* the specified item. If an application's iframe is not found or no longer valid,
* it is removed from the list of watchers.
*
* The function expects that `window.watchItems` contains a mapping of item UIDs to arrays of app instance IDs.
*
* @example
* // Example usage to send a change event to watching applications of an item with UID "item123".
* window.sendItemChangeEventToWatchingApps('item123', { property: 'value' });
*/
window.sendItemChangeEventToWatchingApps = function(item_uid, event_data){
if(window.watchItems[item_uid]){
window.watchItems[item_uid].forEach(app_instance_id => {
const iframe = $(`.window[data-element_uuid="${app_instance_id}"]`).find('.window-app-iframe')
if(iframe && iframe.length > 0){
iframe.get(0)?.contentWindow
.postMessage({
msg: 'itemChanged',
data: event_data,
}, '*');
}else{
window.watchItems[item_uid].splice(window.watchItems[item_uid].indexOf(app_instance_id), 1);
}
});
}
}
/**
* Assigns an icon to a filesystem entry based on its properties such as name, type,
* and whether it's a directory, app, trashed, or specific file type.
*
* @function item_icon
* @global
* @async
* @param {Object} fsentry - A filesystem entry object. It may contain various properties
* like name, type, path, associated_app, thumbnail, is_dir, and metadata, depending on
* the type of filesystem entry.
*/
window.item_icon = async (fsentry)=>{
// --------------------------------------------------
// If this file is Trashed then set the name to the original name of the file before it was trashed
// --------------------------------------------------
if(fsentry.path?.startsWith(trash_path + '/')){
if(fsentry.metadata){
try{
let metadata = JSON.parse(fsentry.metadata);
fsentry.name = (metadata && metadata.original_name) ? metadata.original_name : fsentry.name
}
catch(e){
}
}
}
// --------------------------------------------------
// thumbnail
// --------------------------------------------------
if(fsentry.thumbnail){
return {image: fsentry.thumbnail, type: 'thumb'};
}
// --------------------------------------------------
// app icon
// --------------------------------------------------
else if(fsentry.associated_app && fsentry.associated_app?.name){
if(fsentry.associated_app.icon)
return {image: fsentry.associated_app.icon, type: 'icon'};
else
return {image: window.icons['app.svg'], type: 'icon'};
}
// --------------------------------------------------
// Trash
// --------------------------------------------------
else if(fsentry.shortcut_to_path && fsentry.shortcut_to_path === trash_path){
// get trash image, this is needed to get the correct empty vs full trash icon
let trash_img = $(`.item[data-path="${html_encode(trash_path)}" i] .item-icon-icon`).attr('src')
// if trash_img is undefined that's probably because trash wasn't added anywhere, do a direct lookup to see if trash is empty or no
if(!trash_img){
let trashstat = await puter.fs.stat(trash_path);
if(trashstat.is_empty !== undefined && trashstat.is_empty === true)
trash_img = window.icons['trash.svg'];
else
trash_img = window.icons['trash-full.svg'];
}
return {image: trash_img, type: 'icon'};
}
// --------------------------------------------------
// Directories
// --------------------------------------------------
else if(fsentry.is_dir){
// System Directories
if(fsentry.path === docs_path)
return {image: window.icons['folder-documents.svg'], type: 'icon'};
else if (fsentry.path === pictures_path)
return { image: window.icons['folder-pictures.svg'], type: 'icon' };
else if (fsentry.path === home_path)
return { image: window.icons['folder-home.svg'], type: 'icon' };
else if (fsentry.path === videos_path)
return { image: window.icons['folder-videos.svg'], type: 'icon' };
else if (fsentry.path === desktop_path)
return { image: window.icons['folder-desktop.svg'], type: 'icon' };
// regular directories
else
return {image: window.icons['folder.svg'], type: 'icon'};
}
// --------------------------------------------------
// Match icon by file extension
// --------------------------------------------------
// *.doc
else if(fsentry.name.toLowerCase().endsWith('.doc')){
return {image: window.icons['file-doc.svg'], type: 'icon'};
}
// *.docx
else if(fsentry.name.toLowerCase().endsWith('.docx')){
return {image: window.icons['file-docx.svg'], type: 'icon'};
}
// *.exe
else if(fsentry.name.toLowerCase().endsWith('.exe')){
return {image: window.icons['file-exe.svg'], type: 'icon'};
}
// *.gz
else if(fsentry.name.toLowerCase().endsWith('.gz')){
return {image: window.icons['file-gzip.svg'], type: 'icon'};
}
// *.jar
else if(fsentry.name.toLowerCase().endsWith('.jar')){
return {image: window.icons['file-jar.svg'], type: 'icon'};
}
// *.java
else if(fsentry.name.toLowerCase().endsWith('.java')){
return {image: window.icons['file-java.svg'], type: 'icon'};
}
// *.jsp
else if(fsentry.name.toLowerCase().endsWith('.jsp')){
return {image: window.icons['file-jsp.svg'], type: 'icon'};
}
// *.log
else if(fsentry.name.toLowerCase().endsWith('.log')){
return {image: window.icons['file-log.svg'], type: 'icon'};
}
// *.mp3
else if(fsentry.name.toLowerCase().endsWith('.mp3')){
return {image: window.icons['file-mp3.svg'], type: 'icon'};
}
// *.rb
else if(fsentry.name.toLowerCase().endsWith('.rb')){
return {image: window.icons['file-ruby.svg'], type: 'icon'};
}
// *.rss
else if(fsentry.name.toLowerCase().endsWith('.rss')){
return {image: window.icons['file-rss.svg'], type: 'icon'};
}
// *.rtf
else if(fsentry.name.toLowerCase().endsWith('.rtf')){
return {image: window.icons['file-rtf.svg'], type: 'icon'};
}
// *.sketch
else if(fsentry.name.toLowerCase().endsWith('.sketch')){
return {image: window.icons['file-sketch.svg'], type: 'icon'};
}
// *.sql
else if(fsentry.name.toLowerCase().endsWith('.sql')){
return {image: window.icons['file-sql.svg'], type: 'icon'};
}
// *.tif
else if(fsentry.name.toLowerCase().endsWith('.tif')){
return {image: window.icons['file-tif.svg'], type: 'icon'};
}
// *.tiff
else if(fsentry.name.toLowerCase().endsWith('.tiff')){
return {image: window.icons['file-tiff.svg'], type: 'icon'};
}
// *.wav
else if(fsentry.name.toLowerCase().endsWith('.wav')){
return {image: window.icons['file-wav.svg'], type: 'icon'};
}
// *.cpp
else if(fsentry.name.toLowerCase().endsWith('.cpp')){
return {image: window.icons['file-cpp.svg'], type: 'icon'};
}
// *.pptx
else if(fsentry.name.toLowerCase().endsWith('.pptx')){
return {image: window.icons['file-pptx.svg'], type: 'icon'};
}
// *.psd
else if(fsentry.name.toLowerCase().endsWith('.psd')){
return {image: window.icons['file-psd.svg'], type: 'icon'};
}
// *.xlsx
else if(fsentry.name.toLowerCase().endsWith('.xlsx')){
return {image: window.icons['file-xlsx.svg'], type: 'icon'};
}
// --------------------------------------------------
// Determine icon by set or derived mime type
// --------------------------------------------------
else if(fsentry.type){
return {image: content_type_to_icon(fsentry.type), type: 'icon'};
}
else{
return {image: content_type_to_icon(mime.getType(fsentry.name)), type: 'icon'};
}
}
/**
* Asynchronously checks if a save account notice should be shown to the user, and if needed, displays the notice.
*
* This function first retrieves a key value pair from the cloud key-value storage to determine if the notice has been shown before.
* If the notice hasn't been shown and the user is using a temporary session, the notice is then displayed. After the notice is shown,
* the function updates the key-value storage indicating that the notice has been shown. The user can choose to save the session,
* remind later or log in to an existing account.
*
* @param {string} [message] - The custom message to be displayed in the notice. If not provided, a default message will be used.
* @global
* @function window.show_save_account_notice_if_needed
*/
window.show_save_account_notice_if_needed = function(message){
getItem({
key: "save_account_notice_shown",
success: async function(value){
if(!value && window.user?.is_temp){
setItem({key: "save_account_notice_shown", value: true});
// Show the notice
setTimeout(async () => {
const alert_resp = await UIAlert({
message: message ?? `<strong>Congrats on storing data!</strong><p>Don't forget to save your session! You are in a temporary session. Save session to avoid accidentally losing your work.</p>`,
body_icon: window.icons['reminder.svg'],
buttons:[
{
label: 'Save session',
value: 'save-session',
type: 'primary',
},
// {
// label: 'Log into an existing account',
// value: 'login',
// },
{
label: `I'll do it later`,
value: 'remind-later',
},
],
window_options: {
backdrop: true,
close_on_backdrop_click: false,
}
})
if(alert_resp === 'remind-later'){
}
if(alert_resp === 'save-session'){
let saved = await UIWindowSaveAccount({
send_confirmation_code: false,
});
}else if (alert_resp === 'login'){
let login_result = await UIWindowLogin({
show_signup_button: false,
reload_on_success: true,
send_confirmation_code: false,
window_options: {
show_in_taskbar: false,
backdrop: true,
close_on_backdrop_click: false,
}
});
if(!login_result)
$('.toolbar').prepend(ht);
}
}, desktop_loading_fade_delay + 1000);
}
}
})
}
window.launch_download_from_url = async function(){
// get url query params
const url_query_params = new URLSearchParams(window.location.search);
// is this download?
if(url_query_params.has('download')){
let url = url_query_params.get('download');
let name = url_query_params.get('name');
let is_dir = url_query_params.get('is_dir');
let url_obj;
// if url doesn't have a protocol, add http://
if(!url.startsWith('http://') && !url.startsWith('https://')){
url = 'http://' + url;
}
// parse url
try{
url_obj = new URL(url);
}catch(e){
UIAlert("Invalid download URL.");
return;
}
// get hostname from url
let hostname = url_obj.hostname;
// name
if(!name)
name = url.split('/').pop().split('#')[0].split('?')[0];
// determine file type from url
let file_type = mime.getType(name);
// confirm download
if(await UIWindowConfirmDownload({url: url, name: name, source: hostname, type: file_type, is_dir: is_dir})){
// download progress tracker
let dl_op_id = operation_id++;
// upload progress tracker defaults
window.progress_tracker[dl_op_id] = [];
window.progress_tracker[dl_op_id][0] = {};
window.progress_tracker[dl_op_id][0].total = 0;
window.progress_tracker[dl_op_id][0].ajax_uploaded = 0;
window.progress_tracker[dl_op_id][0].cloud_uploaded = 0;
const progress_window = await UIWindowDownloadProgress({operation_id: dl_op_id, item_name: name});
const res = await download({
url: url,
name: name,
dest_path: desktop_path,
auth_token: auth_token,
api_origin: api_origin,
dedupe_name: true,
overwrite: false,
operation_id: dl_op_id,
item_upload_id: 0,
success: function(res){
$(progress_window).close();
},
error: function(err){
UIAlert(err && err.message ? err.message : "Download failed.");
$(progress_window).close();
}
});
// clear window URL
window.history.pushState(null, document.title, '/');
}
}
}
window.refresh_item_container = function(el_item_container, options){
options = options || {};
let container_path = $(el_item_container).attr('data-path');
let el_window = $(el_item_container).closest('.window');
let el_window_head_icon = $(el_window).find('.window-head-icon');
const loading_spinner = $(el_item_container).find('.explorer-loading-spinner');
if(options.fadeInItems)
$(el_item_container).css('opacity', '0')
// Hide the 'This folder is empty' message to avoid the flickering effect
// if the folder is not empty.
$(el_item_container).find('.explorer-empty-message').hide();
// Hide the loading spinner to avoid the flickering effect if the folder
// is already loaded.
$(loading_spinner).hide();
// current timestamp in milliseconds
let start_ts = new Date().getTime();
// A timeout that will show the loading spinner if the folder is not loaded
// after 1000ms
let loading_timeout = setTimeout(function(){
// make sure the same folder is still loading
if($(loading_spinner).closest('.item-container').attr('data-path') !== container_path)
return;
// show the loading spinner
$(loading_spinner).show();
setTimeout(function(){
$(loading_spinner).find('.explorer-loading-spinner-msg').html('Taking a little longer than usual. Please wait...');
}, 3000)
}, 1000);
// --------------------------------------------------------
// Folder's configs and properties
// --------------------------------------------------------
puter.fs.stat(container_path, function(fsentry){
if(el_window){
$(el_window).attr('data-uid', fsentry.id);
$(el_window).attr('data-sort_by', fsentry.sort_by ?? 'name');
$(el_window).attr('data-sort_order', fsentry.sort_order ?? 'asc');
$(el_window).attr('data-layout', fsentry.layout ?? 'icons');
// data-name
$(el_window).attr('data-name', html_encode(fsentry.name));
// data-path
$(el_window).attr('data-path', html_encode(container_path));
$(el_window).find('.window-navbar-path-input').val(container_path);
$(el_window).find('.window-navbar-path-input').attr('data-path', container_path);
}
$(el_item_container).attr('data-sort_by', fsentry.sort_by ?? 'name');
$(el_item_container).attr('data-sort_order', fsentry.sort_order ?? 'asc');
// update layout
if(el_window && el_window.length > 0)
update_window_layout(el_window, fsentry.layout);
//
if(fsentry.layout === 'details'){
update_details_layout_sort_visuals(el_window, fsentry.sort_by, fsentry.sort_order);
}
});
// is_directoryPicker
let is_directoryPicker = $(el_window).attr('data-is_directoryPicker');
is_directoryPicker = (is_directoryPicker === 'true' || is_directoryPicker === '1') ? true : false;
// allowed_file_types
let allowed_file_types = $(el_window).attr('data-allowed_file_types');
// is_directoryPicker
let is_openFileDialog = $(el_window).attr('data-is_openFileDialog');
is_openFileDialog = (is_openFileDialog === 'true' || is_openFileDialog === '1') ? true : false;
// remove all existing items
$(el_item_container).find('.item').removeItems()
// get items
puter.fs.readdir(container_path).then((fsentries)=>{
// Check if the same folder is still loading since el_item_container's
// data-path might have changed by other operations while waiting for the response to this `readdir`.
if($(el_item_container).attr('data-path') !== container_path)
return;
setTimeout(async function(){
// clear loading timeout
clearTimeout(loading_timeout);
// hide loading spinner
$(loading_spinner).hide();
// if no items, show empty folder message
if(fsentries.length === 0){
$(el_item_container).find('.explorer-empty-message').show();
}
// trash icon
if(container_path === trash_path && el_window_head_icon){
if(fsentries.length > 0){
$(el_window_head_icon).attr('src', window.icons['trash-full.svg']);
}else{
$(el_window_head_icon).attr('src', window.icons['trash.svg']);
}
}
// add each item to window
for (let index = 0; index < fsentries.length; index++) {
const fsentry = fsentries[index];
let is_disabled = false;
// disable files if this is a showDirectoryPicker() window
if(is_directoryPicker && !fsentry.is_dir)
is_disabled = true;
// if this item is not allowed because of filetype restrictions, disable it
if(!window.check_fsentry_against_allowed_file_types_string(fsentry, allowed_file_types))
is_disabled = true;
// skip if hidden (i.e. name starts with `.`)
if(fsentry.name.startsWith('.'))
continue;
//metadata
let metadata;
if(fsentry.metadata !== ''){
try{
metadata = JSON.parse(fsentry.metadata);
}
catch(e){
}
}
const item_path = fsentry.path ?? path.join($(el_window).attr('data-path'), fsentry.name);
// render any item but Trash/AppData
if(item_path !== trash_path && item_path !== appdata_path){
// if this is trash, get original name from item metadata
fsentry.name = (metadata && metadata.original_name !== undefined) ? metadata.original_name : fsentry.name;
UIItem({
appendTo: el_item_container,
uid: fsentry.uid,
immutable: fsentry.immutable,
associated_app_name: fsentry.associated_app?.name,
path: item_path,
icon: await item_icon(fsentry),
name: (metadata && metadata.original_name !== undefined) ? metadata.original_name : fsentry.name,
is_dir: fsentry.is_dir,
multiselectable: !is_openFileDialog,
has_website: fsentry.has_website,
is_shared: fsentry.is_shared,
metadata: fsentry.metadata,
is_shortcut: fsentry.is_shortcut,
shortcut_to: fsentry.shortcut_to,
shortcut_to_path: fsentry.shortcut_to_path,
size: fsentry.size,
type: fsentry.type,
modified: fsentry.modified,
suggested_apps: fsentry.suggested_apps,
disabled: is_disabled,
});
}
}
// if this is desktop, add Trash
if($(el_item_container).hasClass('desktop')){
try{
const trash = await puter.fs.stat(window.trash_path);
UIItem({
appendTo: el_item_container,
uid: trash.id,
immutable: trash.immutable,
path: trash_path,
icon: {image: (trash.is_empty ? window.icons['trash.svg'] : window.icons['trash-full.svg']), type: 'icon'},
name: trash.name,
is_dir: trash.is_dir,
sort_by: trash.sort_by,
type: trash.type,
is_trash: true,
sortable: false,
});
sort_items(el_item_container, $(el_item_container).attr('data-sort_by'), $(el_item_container).attr('data-sort_order'));
}catch(e){
}
}
// sort items
sort_items(
el_item_container,
$(el_item_container).attr('data-sort_by'),
$(el_item_container).attr('data-sort_order')
);
if(options.fadeInItems)
$(el_item_container).animate({'opacity': '1'});
// update footer item count if this is an explorer window
if(el_window)
update_explorer_footer_item_count(el_window);
},
// This makes sure the loading spinner shows up if the request takes longer than 1 second
// and stay there for at least 1 second since the flickering is annoying
(Date.now() - start_ts) > 1000 ? 1000 : 1)
});
}
window.onpopstate = (event) => {
if(event.state !== null && event.state.window_id !== null){
$(`.window[data-id="${event.state.window_id}"]`).focusWindow();
}
}
window.sort_items = (item_container, sort_by, sort_order)=>{
if(sort_order !== 'asc' && sort_order !== 'desc')
sort_order = 'asc';
$(item_container).find(`.item[data-sortable="true"]`).detach().sort(function(a,b) {
// Name
if(!sort_by || sort_by === 'name'){
if(a.dataset.name.toLowerCase() < b.dataset.name.toLowerCase()) { return (sort_order === 'asc' ? -1 : 1); }
if(a.dataset.name.toLowerCase() > b.dataset.name.toLowerCase()) { return (sort_order === 'asc' ? 1 : -1); }
return 0;
}
// Size
else if(sort_by === 'size'){
if( parseInt(a.dataset.size) < parseInt(b.dataset.size)) { return (sort_order === 'asc' ? -1 : 1); }
if( parseInt(a.dataset.size) > parseInt(b.dataset.size)) { return (sort_order === 'asc' ? 1 : -1); }
return 0;
}
// Modified
else if(sort_by === 'modified'){
if( parseInt(a.dataset.modified) < parseInt(b.dataset.modified)) { return (sort_order === 'asc' ? -1 : 1); }
if( parseInt(a.dataset.modified) > parseInt(b.dataset.modified)) { return (sort_order === 'asc' ? 1 : -1); }
return 0;
}
// Type
else if(sort_by === 'type'){
if(path.extname(a.dataset.name.toLowerCase()) < path.extname(b.dataset.name.toLowerCase())) { return (sort_order === 'asc' ? -1 : 1); }
if(path.extname(a.dataset.name.toLowerCase()) > path.extname(b.dataset.name.toLowerCase())) { return (sort_order === 'asc' ? 1 : -1); }
return 0;
}
}).appendTo(item_container);
}
window.create_folder = async(basedir, appendto_element)=>{
let dirname = basedir;
let folder_name = 'New Folder';
let newfolder_op_id = operation_id++;
operation_cancelled[newfolder_op_id] = false;
let newfolder_progress_window_init_ts = Date.now();
let progwin;
// only show progress window if it takes longer than 500ms to create folder
let progwin_timeout = setTimeout(async () => {
progwin = await UIWindowNewFolderProgress({operation_id: newfolder_op_id});
}, 500);
// create folder
try{
await puter.fs.mkdir({
path: dirname + '/'+folder_name,
rename: true,
overwrite: false,
success: function (data){
const el_created_dir = $(appendto_element).find('.item[data-path="'+html_encode(dirname)+'/'+html_encode(data.name)+'"]');
if(el_created_dir.length > 0)
activate_item_name_editor(el_created_dir);
clearTimeout(progwin_timeout);
// done
let newfolder_duration = (Date.now() - newfolder_progress_window_init_ts);
if( progwin && newfolder_duration >= copy_progress_hide_delay){
$(progwin).close();
}else if(progwin){
setTimeout(() => {
setTimeout(() => {
$(progwin).close();
}, Math.abs(copy_progress_hide_delay - newfolder_duration));
})
}
}
});
}catch(err){
clearTimeout(progwin_timeout);
}
}
window.create_file = async(options)=>{
// args
let dirname = options.dirname;
let appendto_element = options.append_to_element;
let filename = options.name;
let content = options.content ? [options.content] : [];
// create file
try{
puter.fs.upload(new File(content, filename), dirname,
{
success: async function (data){
const created_file = $(appendto_element).find('.item[data-path="'+html_encode(dirname)+'/'+html_encode(data.name)+'"]');
if(created_file.length > 0){
activate_item_name_editor(created_file);
}
}
});
}catch(err){
console.log(err);
}
}
window.create_shortcut = async(filename, is_dir, basedir, appendto_element, shortcut_to, shortcut_to_path)=>{
let dirname = basedir;
const extname = path.extname(filename);
const basename = path.basename(filename, extname) + ' - Shortcut';
filename = basename + extname;
// create file shortcut
try{
await puter.fs.upload(new File([], filename), dirname, {
overwrite: false,
shortcutTo: shortcut_to_path ?? shortcut_to,
dedupeName: true,
});
}catch(err){
console.log(err)
}
}
window.copy_clipboard_items = async function(dest_path, dest_container_element){
let copy_op_id = operation_id++;
operation_cancelled[copy_op_id] = false;
// unselect previously selected items in the target container
$(dest_container_element).children('.item-selected').removeClass('item-selected');
update_explorer_footer_selected_items_count($(dest_container_element).closest('.window'));
let overwrite_all = false;
(async()=>{
let copy_progress_window_init_ts = Date.now();
let progwin = await UIWindowCopyProgress({operation_id: copy_op_id});
for(let i=0; i<clipboard.length; i++){
let copy_path = clipboard[i].path;
let item_with_same_name_already_exists = true;
let overwrite = overwrite_all;
$(progwin).find('.copy-from').html(copy_path);
do{
if(overwrite)
item_with_same_name_already_exists = false;
// cancelled?
if(operation_cancelled[copy_op_id])
return;
// perform copy
try{
await puter.fs.copy({
source: copy_path,
destination: dest_path,
overwrite: overwrite || overwrite_all,
// if user is copying an item to where its source is, change the name so there is no conflict
dedupeName: dest_path === path.dirname(copy_path),
});
// skips next loop iteration
break;
}catch(err){
if(err.code==='item_with_same_name_exists'){
const alert_resp = await UIAlert({
message: `<strong>${html_encode(err.entry_name)}</strong> already exists.`,
buttons:[
{label: 'Replace', type: 'primary'},
... (clipboard.length > 1) ? [{label: 'Replace all'}] : [],
... (clipboard.length > 1) ? [{label: 'Skip'}] : [{label: 'Cancel'}],
]
})
if(alert_resp === 'Replace'){
overwrite = true;
}else if (alert_resp === 'Replace all'){
overwrite = true;
overwrite_all = true;
}else if(alert_resp === 'Skip' || alert_resp === 'Cancel'){
item_with_same_name_already_exists = false;
}
}
else{
if(err.message){
UIAlert(err.message)
}
item_with_same_name_already_exists = false;
}
}
}while(item_with_same_name_already_exists)
}
// done
let copy_duration = (Date.now() - copy_progress_window_init_ts);
if( copy_duration >= copy_progress_hide_delay){
$(progwin).close();
}else{
setTimeout(() => {
setTimeout(() => {
$(progwin).close();
}, Math.abs(copy_progress_hide_delay - copy_duration));
})
}
})();
}
/**
* Copies the given items to the destination path.
*
* @param {HTMLElement[]} el_items - HTML elements representing the items to copy
* @param {string} dest_path - Destination path to copy items to
*/
window.copy_items = function(el_items, dest_path){
let copy_op_id = operation_id++;
let overwrite_all = false;
(async()=>{
let copy_progress_window_init_ts = Date.now();
let progwin = await UIWindowCopyProgress({operation_id: copy_op_id});
for(let i=0; i < el_items.length; i++){
let copy_path = $(el_items[i]).attr('data-path');
let item_with_same_name_already_exists = true;
let overwrite = overwrite_all;
$(progwin).find('.copy-from').html(copy_path);
do{
if(overwrite)
item_with_same_name_already_exists = false;
// cancelled?
if(operation_cancelled[copy_op_id])
return;
try{
await puter.fs.copy({
source: copy_path,
destination: dest_path,
overwrite: overwrite || overwrite_all,
// if user is copying an item to where the source is, automatically change the name so there is no conflict
dedupeName: dest_path === path.dirname(copy_path),
})
// skips next loop iteration
item_with_same_name_already_exists = false;
}catch(err){
if(err.code === 'item_with_same_name_exists'){
const alert_resp = await UIAlert({
message: `<strong>${html_encode(err.entry_name)}</strong> already exists.`,
buttons:[
{ label: 'Replace', type: 'primary' },
... (el_items.length > 1) ? [{label: 'Replace all'}] : [],
... (el_items.length > 1) ? [{label: 'Skip'}] : [{label: 'Cancel'}],
]
})
if(alert_resp === 'Replace'){
overwrite = true;
}else if (alert_resp === 'Replace all'){
overwrite = true;
overwrite_all = true;
}else if(alert_resp === 'Skip' || alert_resp === 'Cancel'){
item_with_same_name_already_exists = false;
}
}
else{
if(err.message){
UIAlert(err.message)
}
else if(err){
UIAlert(err)
}
item_with_same_name_already_exists = false;
}
}
}while(item_with_same_name_already_exists)
}
// done
let copy_duration = (Date.now() - copy_progress_window_init_ts);
if( copy_duration >= copy_progress_hide_delay){
$(progwin).close();
}else{
setTimeout(() => {
setTimeout(() => {
$(progwin).close();
}, Math.abs(copy_progress_hide_delay - copy_duration));
})
}
})()
}
/**
* Deletes the given item.
*
* @param {HTMLElement} el_item - HTML element representing the item to delete
* @param {boolean} [descendants_only=false] - If true, only deletes descendant items under the given item
* @returns {Promise<void>}
*/
window.delete_item = async function(el_item, descendants_only = false){
if($(el_item).attr('data-immutable') === '1')
return;
// hide all UIItems with matching uids
$(`.item[data-uid='${$(el_item).attr('data-uid')}']`).fadeOut(150, function(){
// close all windows with matching uids
$('.window-' + $(el_item).attr('data-uid')).close();
// close all windows that belong to a descendant of this item
// todo this has to be case-insensitive but the `i` selector doesn't work on ^=
$(`.window[data-path^="${$(el_item).attr('data-path')}/"]`).close();
});
try{
await puter.fs.delete({
paths: $(el_item).attr('data-path'),
descendantsOnly: descendants_only,
recursive: true,
});
// fade out item
$(`.item[data-uid='${$(el_item).attr('data-uid')}']`).fadeOut(150, function(){
// find all parent windows that contain this item
let parent_windows = $(`.item[data-uid='${$(el_item).attr('data-uid')}']`).closest('.window');
// remove item from DOM
$(`.item[data-uid='${$(el_item).attr('data-uid')}']`).removeItems();
// update parent windows' item counts
$(parent_windows).each(function(index){
update_explorer_footer_item_count(this);
update_explorer_footer_selected_items_count(this);
});
// update all shortcuts to this item
$(`.item[data-shortcut_to_path="${html_encode($(el_item).attr('data-path'))}" i]`).attr(`data-shortcut_to_path`, '');
});
}catch(err){
UIAlert(err.responseText);
}
}
window.move_clipboard_items = function (el_target_container, target_path){
let dest_path = target_path === undefined ? $(el_target_container).attr('data-path') : target_path;
let el_items = [];
if(clipboard.length > 0){
for(let i=0; i<clipboard.length; i++){
el_items.push($(`.item[data-path="${html_encode(clipboard[i])}" i]`));
}
if(el_items.length > 0)
move_items(el_items, dest_path);
}
clipboard = [];
}
/**
* Initiates a download for multiple files provided as an array of paths.
*
* This function triggers the download of files from given paths. It constructs the
* download URLs using an API base URL and the given paths, along with an authentication token.
* Each file is then fetched and prompted to the user for download using the `saveAs` function.
*
* Global dependencies:
* - `api_origin`: The base URL for the download API endpoint.
* - `auth_token`: The authentication token required for the download API.
* - `saveAs`: Function to save the fetched blob as a file.
* - `path.basename()`: Function to extract the filename from the provided path.
*
* @global
* @function trigger_download
* @param {string[]} paths - An array of file paths that are to be downloaded.
*
* @example
* let filePaths = ['/path/to/file1.txt', '/path/to/file2.png'];
* window.trigger_download(filePaths);
*/
window.trigger_download = (paths)=>{
let urls = [];
for (let index = 0; index < paths.length; index++) {
urls.push({
download: api_origin + "/down?path=" + paths[index] + "&auth_token=" + auth_token,
filename: path.basename(paths[index]),
});
}
urls.forEach(function (e) {
fetch(e.download)
.then(res => res.blob())
.then(blob => {
saveAs(blob, e.filename);
});
});
}
/**
*
* @param {*} options
*/
window.launch_app = async (options)=>{
const uuid = uuidv4();
let icon, title, file_signature;
const window_options = options.window_options ?? {};
// try to get 3rd-party app info
let app_info = options.app_obj ?? await get_apps(options.name);
//-----------------------------------
// icon
//-----------------------------------
if(app_info.icon)
icon = app_info.icon;
else if(app_info.icon)
icon = window.icons['app.svg'];
else if(options.name === 'explorer')
icon = window.icons['folder.svg'];
else
icon = window.icons['app-icon-'+options.name+'.svg']
//-----------------------------------
// title
//-----------------------------------
if(app_info.title)
title = app_info.title;
else if(options.window_title)
title = options.window_title;
else if(options.name)
title = options.name;
//-----------------------------------
// maximize on start
//-----------------------------------
if(app_info.maximize_on_start && app_info.maximize_on_start === 1)
options.maximized = 1;
//-----------------------------------
// if opened a file, sign it
//-----------------------------------
if(options.file_signature)
file_signature = options.file_signature;
else if(options.file_uid){
file_signature = await puter.fs.sign(app_info.uuid, {uid: options.file_uid, action: 'write'});
// add token to options
options.token = file_signature.token;
// add file_signature to options
file_signature = file_signature.items;
}
//------------------------------------
// Explorer
//------------------------------------
if(options.name === 'explorer'){
if(options.path === window.home_path){
title = 'Home';
icon = window.icons['folder-home.svg'];
}
else if(options.path === window.trash_path){
title = 'Trash';
}
else if(!options.path)
title = root_dirname;
else
title = path.dirname(options.path);
// open window
UIWindow({
element_uuid: uuid,
icon: icon,
path: options.path ?? window.home_path,
title: title,
uid: null,
is_dir: true,
app: 'explorer',
...window_options,
is_maximized: options.maximized,
});
}
//------------------------------------
// All other apps
//------------------------------------
else{
//-----------------------------------
// iframe_url
//-----------------------------------
let iframe_url;
if(!app_info.index_url){
iframe_url = new URL('https://'+options.name+'.' + window.app_domain + `/index.html`);
}else{
iframe_url = new URL(app_info.index_url);
}
// add app_instance_id to URL
iframe_url.searchParams.append('puter.app_instance_id', uuid);
// add app_id to URL
iframe_url.searchParams.append('puter.app.id', app_info.uuid);
if(file_signature){
iframe_url.searchParams.append('puter.item.uid', file_signature.uid);
iframe_url.searchParams.append('puter.item.path', options.file_path ? `~/` + options.file_path.split('/').slice(1).join('/') : file_signature.path);
iframe_url.searchParams.append('puter.item.name', file_signature.fsentry_name);
iframe_url.searchParams.append('puter.item.read_url', file_signature.read_url);
iframe_url.searchParams.append('puter.item.write_url', file_signature.write_url);
iframe_url.searchParams.append('puter.item.metadata_url', file_signature.metadata_url);
iframe_url.searchParams.append('puter.item.size', file_signature.fsentry_size);
iframe_url.searchParams.append('puter.item.accessed', file_signature.fsentry_accessed);
iframe_url.searchParams.append('puter.item.modified', file_signature.fsentry_modified);
iframe_url.searchParams.append('puter.item.created', file_signature.fsentry_created);
iframe_url.searchParams.append('puter.domain', app_domain);
}
else if(options.readURL){
iframe_url.searchParams.append('puter.item.name', options.filename);
iframe_url.searchParams.append('puter.item.path', options.file_path ? `~/` + options.file_path.split('/').slice(1).join('/') : undefined);
iframe_url.searchParams.append('puter.item.read_url', options.readURL);
// iframe_url.searchParams.append('puter.item.write_url', file_signature.write_url);
iframe_url.searchParams.append('puter.domain', window.app_domain);
}
// Add auth_token to GODMODE apps
if(app_info.godmode && app_info.godmode === 1){
iframe_url.searchParams.append('puter.auth.token', auth_token);
iframe_url.searchParams.append('puter.auth.username', window.user.username);
iframe_url.searchParams.append('puter.domain', window.app_domain);
}
// App token. Only add token if it's not a GODMODE app since GODMODE apps already have the super token
// that has access to everything.
else if(options.token){
iframe_url.searchParams.append('puter.auth.token', options.token);
}
// Try to acquire app token from the server
else{
let response = await fetch(window.api_origin + "/auth/get-user-app-token", {
"headers": {
"Content-Type": "application/json",
"Authorization": "Bearer "+ auth_token,
},
"body": JSON.stringify({app_uid: app_info.uid ?? app_info.uuid}),
"method": "POST",
});
let res = await response.json();
if(res.token){
iframe_url.searchParams.append('puter.auth.token', res.token);
}
}
// Add options.params to URL
if(options.params){
iframe_url.searchParams.append('puter.domain', window.app_domain);
for (const property in options.params) {
iframe_url.searchParams.append(property, options.params[property]);
}
}
// Add options.args to URL
iframe_url.searchParams.append('puter.args', JSON.stringify(options.args ?? {}));
// ...and finally append urm_source=puter.com to the URL
iframe_url.searchParams.append('urm_source', 'puter.com');
UIWindow({
element_uuid: uuid,
title: title,
iframe_url: iframe_url.href,
icon: icon,
window_class: 'window-app',
update_window_url: true,
app_uuid: app_info.uuid ?? app_info.uid,
// has_head: options.has_head ?? true,
// top: options.top ?? undefined,
// left: options.left ?? undefined,
// width: options.width ?? undefined,
// height: options.height ?? undefined,
// is_resizable: options.is_resizable ?? undefined,
// window_css: options.window_css ?? undefined,
top: options.maximized ? 0 : undefined,
left: options.maximized ? 0 : undefined,
height: options.maximized ? `calc(100% - ${window.taskbar_height + window.toolbar_height + 1}px)` : undefined,
width: options.maximized ? `100%` : undefined,
app: options.name,
is_maximized: options.maximized,
is_fullpage: options.is_fullpage,
...window_options,
});
// send post request to /rao to record app open
if(options.name !== 'explorer'){
// add the app to the beginning of the array
launch_apps.recent.unshift(app_info);
// dedupe the array by uuid, uid, and id
launch_apps.recent = _.uniqBy(launch_apps.recent, 'name');
// limit to window.launch_recent_apps_count
launch_apps.recent = launch_apps.recent.slice(0, window.launch_recent_apps_count);
// send post request to /rao to record app open
$.ajax({
url: api_origin + "/rao",
type: 'POST',
data: JSON.stringify({
original_client_socket_id: window.socket?.id,
app_uid: app_info.uid ?? app_info.uuid,
}),
async: true,
contentType: "application/json",
headers: {
"Authorization": "Bearer "+auth_token
},
})
}
}
}
window.open_item = async function(options){
let el_item = options.item;
const $el_parent_window = $(el_item).closest('.window');
const parent_win_id = $($el_parent_window).attr('data-id');
const is_dir = $(el_item).attr('data-is_dir') === '1' ? true : false;
const uid = $(el_item).attr('data-shortcut_to') === '' ? $(el_item).attr('data-uid') : $(el_item).attr('data-shortcut_to');
const item_path = $(el_item).attr('data-shortcut_to_path') === '' ? $(el_item).attr('data-path') : $(el_item).attr('data-shortcut_to_path');
const is_shortcut = $(el_item).attr('data-is_shortcut') === '1';
const shortcut_to_path = $(el_item).attr('data-shortcut_to_path');
const associated_app_name = $(el_item).attr('data-associated_app_name');
//----------------------------------------------------------------
// Is this a shortcut whose source is perma-deleted?
//----------------------------------------------------------------
if(is_shortcut && shortcut_to_path === ''){
UIAlert(`This shortcut can't be opened because its source has been deleted.`)
}
//----------------------------------------------------------------
// Is this a shortcut whose source is trashed?
//----------------------------------------------------------------
else if(is_shortcut && shortcut_to_path.startsWith(trash_path + '/')){
UIAlert(`This shortcut can't be opened because its source has been deleted.`)
}
//----------------------------------------------------------------
// Is this a trashed file?
//----------------------------------------------------------------
else if(item_path.startsWith(trash_path + '/')){
UIAlert(`This item can't be opened because it's in the trash. To use this item, first drag it out of the Trash.`)
}
//----------------------------------------------------------------
// Is this a file (no dir) on a SaveFileDialog?
//----------------------------------------------------------------
else if($el_parent_window.attr('data-is_saveFileDialog') === 'true' && !is_dir){
$el_parent_window.find('.savefiledialog-filename').val($(el_item).attr('data-name'));
$el_parent_window.find('.savefiledialog-save-btn').trigger('click');
}
//----------------------------------------------------------------
// Is this a file (no dir) on an OpenFileDialog?
//----------------------------------------------------------------
else if($el_parent_window.attr('data-is_openFileDialog') === 'true' && !is_dir){
$el_parent_window.find('.window-disable-mask, .busy-indicator').show();
let busy_init_ts = Date.now();
try{
let filedialog_parent_uid = $el_parent_window.attr('data-parent_uuid');
let $filedialog_parent_app_window = $(`.window[data-element_uuid="${filedialog_parent_uid}"]`);
let parent_window_app_uid = $filedialog_parent_app_window.attr('data-app_uuid');
const initiating_app_uuid = $el_parent_window.attr('data-initiating_app_uuid');
let res = await puter.fs.sign(window.host_app_uid ?? parent_window_app_uid, {uid: uid, action: 'write'});
res = res.items;
// todo split is buggy because there might be a slash in the filename
res.path = `~/` + item_path.split('/').slice(2).join('/');
const parent_uuid = $el_parent_window.attr('data-parent_uuid');
const return_to_parent_window = $el_parent_window.attr('data-return_to_parent_window') === 'true';
if(return_to_parent_window){
window.opener.postMessage({
msg: "fileOpenPicked",
original_msg_id: $el_parent_window.attr('data-iframe_msg_uid'),
items: Array.isArray(res) ? [...res] : [res],
// LEGACY SUPPORT, remove this in the future when Polotno uses the new SDK
// this is literally put in here to support Polotno's legacy code
...(!Array.isArray(res) && res)
}, '*');
window.close();
}
else if(parent_uuid){
// send event to iframe
const target_iframe = $(`.window[data-element_uuid="${parent_uuid}"]`).find('.window-app-iframe').get(0);
if(target_iframe){
let retobj = {
msg: "fileOpenPicked",
original_msg_id: $el_parent_window.attr('data-iframe_msg_uid'),
items: Array.isArray(res) ? [...res] : [res],
// LEGACY SUPPORT, remove this in the future when Polotno uses the new SDK
// this is literally put in here to support Polotno's legacy code
...(!Array.isArray(res) && res)
};
target_iframe.contentWindow.postMessage(retobj, '*');
}
// focus iframe
$(target_iframe).get(0)?.focus({preventScroll:true});
// send file_opened event
const file_opened_event = new CustomEvent('file_opened', {detail: res});
// dispatch event to parent window
$(`.window[data-element_uuid="${parent_uuid}"]`).get(0)?.dispatchEvent(file_opened_event);
}
}catch(e){
console.log(e);
}
// done
let busy_duration = (Date.now() - busy_init_ts);
if( busy_duration >= busy_indicator_hide_delay){
$el_parent_window.close();
}else{
setTimeout(() => {
// close this dialog
$el_parent_window.close();
}, Math.abs(busy_indicator_hide_delay - busy_duration));
}
}
//----------------------------------------------------------------
// Is there an app associated with this item?
//----------------------------------------------------------------
else if(associated_app_name !== ''){
launch_app({
name: associated_app_name,
})
}
//----------------------------------------------------------------
// Dir with no open windows: create a new window
//----------------------------------------------------------------
else if(is_dir && ($el_parent_window.length === 0 || options.new_window)){
UIWindow({
path: item_path,
title: path.basename(item_path),
icon: await item_icon({is_dir: true, path: item_path}),
uid: $(el_item).attr('data-uid'),
is_dir: is_dir,
app: 'explorer',
top: options.maximized ? 0 : undefined,
left: options.maximized ? 0 : undefined,
height: options.maximized ? `calc(100% - ${window.taskbar_height + window.toolbar_height + 1}px)` : undefined,
width: options.maximized ? `100%` : undefined,
});
}
//----------------------------------------------------------------
// Dir with an open window: change the path of the open window
//----------------------------------------------------------------
else if($el_parent_window.length > 0 && is_dir){
window_nav_history[parent_win_id] = window_nav_history[parent_win_id].slice(0, window_nav_history_current_position[parent_win_id]+1);
window_nav_history[parent_win_id].push(item_path);
window_nav_history_current_position[parent_win_id]++;
update_window_path($el_parent_window, item_path);
}
//----------------------------------------------------------------
// all other cases: try to open using an app
//----------------------------------------------------------------
else{
const fspath = item_path.toLowerCase();
const fsuid = uid.toLowerCase();
let open_item_meta;
// get all info needed to open an item
try{
open_item_meta = await $.ajax({
url: api_origin + "/open_item",
type: 'POST',
contentType: "application/json",
data: JSON.stringify({
uid: fsuid ?? undefined,
path: fspath ?? undefined,
}),
headers: {
"Authorization": "Bearer "+auth_token
},
statusCode: {
401: function () {
logout();
},
},
});
}catch(err){
}
// get a list of suggested apps for this file type.
let suggested_apps = open_item_meta?.suggested_apps ?? await suggest_apps_for_fsentry({uid: fsuid, path: fspath});
//---------------------------------------------
// No suitable apps, ask if user would like to
// download
//---------------------------------------------
if(suggested_apps.length === 0){
//---------------------------------------------
// If .zip file, unzip it
//---------------------------------------------
if(path.extname(item_path) === '.zip'){
unzipItem(item_path);
return;
}
const alert_resp = await UIAlert(
'Found no suitable apps to open this file with. Would you like to download it instead?',
[
{
label: 'Download File',
type: 'primary',
},
{
label: 'Cancel'
}
])
if(alert_resp === 'Download File'){
trigger_download([item_path]);
}
return;
}
//---------------------------------------------
// First suggested app is default app to open this item
//---------------------------------------------
else{
launch_app({
name: suggested_apps[0].name,
token: open_item_meta.token,
file_path: item_path,
app_obj: suggested_apps[0],
window_title: path.basename(item_path),
file_uid: fsuid,
maximized: options.maximized,
file_signature: open_item_meta.signature,
});
}
}
}
/**
* Returns a context menu item to create a new file/folder.
*
* @param {string} dirname - The directory path to create the item in
* @param {HTMLElement} append_to_element - Element to append the new item to
* @returns {Object} The context menu item object
*/
window.new_context_menu_item = function(dirname, append_to_element){
return {
html: "New",
items: [
// New Folder
{
html: "New Folder",
icon: `<img src="${html_encode(window.icons['folder.svg'])}" class="ctx-item-icon">`,
onClick: function(){
create_folder(dirname, append_to_element);
}
},
// divider
'-',
// Text Document
{
html: `Text Document`,
icon: `<img src="${html_encode(window.icons['file-text.svg'])}" class="ctx-item-icon">`,
onClick: async function(){
create_file({dirname: dirname, append_to_element: append_to_element, name: 'New File.txt'});
}
},
// HTML Document
{
html: `HTML Document`,
icon: `<img src="${html_encode(window.icons['file-html.svg'])}" class="ctx-item-icon">`,
onClick: async function(){
create_file({dirname: dirname, append_to_element: append_to_element, name: 'New File.html'});
}
},
// JPG Image
{
html: `JPG Image`,
icon: `<img src="${html_encode(window.icons['file-image.svg'])}" class="ctx-item-icon">`,
onClick: async function(){
var canvas = document.createElement("canvas");
canvas.width = 800;
canvas.height = 600;
canvas.toBlob((blob) =>{
create_file({dirname: dirname, append_to_element: append_to_element, name: 'New Image.jpg', content: blob});
});
}
},
]
}
}
/**
* Moves the given items to the destination path.
*
* @param {HTMLElement[]} el_items - jQuery elements representing the items to move
* @param {string} dest_path - The destination path to move the items to
* @returns {Promise<void>}
*/
window.move_items = async function(el_items, dest_path){
let move_op_id = operation_id++;
operation_cancelled[move_op_id] = false;
// --------------------------------------------------------
// Optimization: in case all items being moved
// are immutable do not proceed
// --------------------------------------------------------
let all_items_are_immutable = true;
for(let i=0; i<el_items.length; i++){
if($(el_items[i]).attr('data-immutable') === '0'){
all_items_are_immutable = false;
break;
}
}
if(all_items_are_immutable)
return;
// --------------------------------------------------------
// good to go, proceed
// --------------------------------------------------------
// overwrite all items? default is false unless in a conflict case user asks for it
let overwrite_all = false;
// when did this operation start
let move_init_ts = Date.now();
// create progress window
let progwin = await UIWindowMoveProgress({operation_id: move_op_id});
// Go through each item and try to move it
for(let i=0; i<el_items.length; i++){
// get current item
let el_item = el_items[i];
// if operation cancelled by user, stop
if(operation_cancelled[move_op_id])
return;
// cannot move an immutable item, skip it
if($(el_item).attr('data-immutable') === '1')
continue;
// cannot move item to its own path, skip it
if(path.dirname($(el_item).attr('data-path')) === dest_path){
await UIAlert(`<p>Moving <strong>${html_encode($(el_item).attr('data-name'))}</strong></p>Cannot move item to its current location.`)
continue;
}
// if an item with the same name already exists in the destination path
let item_with_same_name_already_exists = false;
let overwrite = overwrite_all;
let untrashed_at_least_one_item = false;
// --------------------------------------------------------
// Keep trying to move the item until it succeeds or is cancelled
// or user decides to overwrite or skip
// --------------------------------------------------------
do{
try{
let path_to_show_on_progwin = $(el_item).attr('data-path');
// parse metadata if any
let metadata = $(el_item).attr('data-metadata');
// no metadata?
if(metadata === '' || metadata === 'null' || metadata === null)
metadata = {}
// try to parse metadata as JSON
else{
try{
metadata = JSON.parse(metadata)
}catch(e){
}
}
let new_name;
// user cancelled?
if(operation_cancelled[move_op_id])
return;
// indicates whether this is a recycling operation
let recycling = false;
// --------------------------------------------------------
// Trashing
// --------------------------------------------------------
if(dest_path === trash_path){
new_name = $(el_item).attr('data-uid');
metadata = {
original_name: $(el_item).attr('data-name'),
original_path: $(el_item).attr('data-path'),
trashed_ts: Math.round(Date.now() / 1000),
};
// update other clients
if(window.socket)
window.socket.emit('trash.is_empty', {is_empty: false});
// change trash icons to 'trash-full.svg'
$(`[data-app="trash"]`).find('.taskbar-icon > img').attr('src', window.icons['trash-full.svg']);
$(`.item[data-path="${html_encode(trash_path)}" i], .item[data-shortcut_to_path="${html_encode(trash_path)}" i]`).find('.item-icon > img').attr('src', window.icons['trash-full.svg']);
$(`.window[data-path="${html_encode(trash_path)}" i]`).find('.window-head-icon').attr('src', window.icons['trash-full.svg']);
}
// moving an item into a trashed directory? deny.
else if(dest_path.startsWith(trash_path)){
$(progwin).close();
UIAlert('Cannot move items into a deleted folder.');
return;
}
// --------------------------------------------------------
// If recycling an item, restore its original name
// --------------------------------------------------------
else if(metadata.trashed_ts !== undefined){
recycling = true;
new_name = metadata.original_name;
metadata = {};
untrashed_at_least_one_item = true;
path_to_show_on_progwin = trash_path + '/' + new_name;
}
// --------------------------------------------------------
// update progress window with current item being moved
// --------------------------------------------------------
$(progwin).find('.move-from').html(path_to_show_on_progwin);
// execute move
let resp = await puter.fs.move({
source: $(el_item).attr('data-uid'),
destination: dest_path,
overwrite: overwrite || overwrite_all,
newName: new_name,
// recycling requires making all missing dirs
createMissingParents: recycling,
newMetadata: metadata,
excludeSocketID: window.socket?.id,
});
let fsentry = resp.moved;
// path must use the real name from DB
fsentry.path = path.join(dest_path, fsentry.name);
// skip next loop iteration because this iteration was successful
item_with_same_name_already_exists = false;
// update all shortcut_to_path
$(`.item[data-shortcut_to_path="${html_encode($(el_item).attr('data-path'))}" i]`).attr(`data-shortcut_to_path`, fsentry.path);
// Remove all items with matching uids
$(`.item[data-uid='${$(el_item).attr('data-uid')}']`).fadeOut(150, function(){
// find all parent windows that contain this item
let parent_windows = $(`.item[data-uid='${$(el_item).attr('data-uid')}']`).closest('.window');
// remove this item
$(this).removeItems();
// update parent windows' item counts and selected item counts in their footers
$(parent_windows).each(function(){
update_explorer_footer_item_count(this);
update_explorer_footer_selected_items_count(this)
});
})
// if trashing, close windows of trashed items and its descendants
if(dest_path === trash_path){
$(`.window[data-path="${html_encode($(el_item).attr('data-path'))}" i]`).close();
// todo this has to be case-insensitive but the `i` selector doesn't work on ^=
$(`.window[data-path^="${html_encode($(el_item).attr('data-path'))}/"]`).close();
}
// update all paths of its and its descendants' open windows
else{
// todo this has to be case-insensitive but the `i` selector doesn't work on ^=
$(`.window[data-path^="${html_encode($(el_item).attr('data-path'))}/"], .window[data-path="${html_encode($(el_item).attr('data-path'))}" i]`).each(function(){
update_window_path(this, $(this).attr('data-path').replace($(el_item).attr('data-path'), path.join(dest_path, fsentry.name)));
})
}
if(dest_path === trash_path){
// remove Public Token
// todo, some client-side check to see if this dir has an FR associated with it before sending a whole ajax req
$.ajax({
url: api_origin + "/removepubtok",
type: 'POST',
data: JSON.stringify({
uid: $(el_item).attr('data-uid'),
}),
async: true,
contentType: "application/json",
headers: {
"Authorization": "Bearer "+auth_token
},
statusCode: {
401: function () {
logout();
},
},
success: function (){
}
})
// remove all associated permissions
// todo, some client-side check to see if this dir has an FR associated with it before sending a whole ajax req
$.ajax({
url: api_origin + "/remove-item-perms",
type: 'POST',
data: JSON.stringify({
uid: $(el_item).attr('data-uid'),
}),
async: true,
contentType: "application/json",
headers: {
"Authorization": "Bearer "+auth_token
},
statusCode: {
401: function () {
logout();
},
},
success: function (){
}
})
$(`.item[data-uid="${$(el_item).attr('data-uid')}"]`).find('.item-is-shared').fadeOut(300);
// if trashing dir...
if($(el_item).attr('data-is_dir') === '1'){
// disassociate all its websites
// todo, some client-side check to see if this dir has at least one associated website before sending ajax request
puter.hosting.delete(dir_uuid)
$(`.mywebsites-dir-path[data-uuid="${$(el_item).attr('data-uid')}"]`).remove();
// remove the website badge from all instances of the dir
$(`.item[data-uid="${$(el_item).attr('data-uid')}"]`).find('.item-has-website-badge').fadeOut(300);
// remove File Rrequest Token
// todo, some client-side check to see if this dir has an FR associated with it before sending a whole ajax req
$.ajax({
url: api_origin + "/removefr",
type: 'POST',
data: JSON.stringify({
dir_uid: $(el_item).attr('data-uid'),
}),
async: true,
contentType: "application/json",
headers: {
"Authorization": "Bearer "+auth_token
},
statusCode: {
401: function () {
logout();
},
},
success: function (){
}
})
}
}
// if replacing an existing item, remove the old item that was just replaced
if(resp.overwritten?.id){
$(`.item[data-uid=${resp.overwritten.id}]`).removeItems();
}
// if this is trash, get original name from item metadata
fsentry.name = metadata?.original_name || fsentry.name;
// create new item on matching containers
UIItem({
appendTo: $(`.item-container[data-path="${html_encode(dest_path)}" i]`),
immutable: fsentry.immutable,
associated_app_name: fsentry.associated_app?.name,
uid: fsentry.uid,
path: fsentry.path,
icon: await item_icon(fsentry),
name: (dest_path === trash_path) ? $(el_item).attr('data-name') : fsentry.name,
is_dir: fsentry.is_dir,
size: fsentry.size,
type: fsentry.type,
modified: fsentry.modified,
is_selected: false,
is_shared: (dest_path === trash_path) ? false : fsentry.is_shared,
is_shortcut: fsentry.is_shortcut,
shortcut_to: fsentry.shortcut_to,
shortcut_to_path: fsentry.shortcut_to_path,
has_website: $(el_item).attr('data-has_website') === '1',
metadata: fsentry.metadata ?? '',
suggested_apps: fsentry.suggested_apps,
});
// this operation may have created some missing directories,
// see if any of the directories in the path of this file is new AND
// if these new path have any open parents that need to be updated
resp.parent_dirs_created?.forEach(async dir => {
let item_container = $(`.item-container[data-path="${html_encode(path.dirname(dir.path))}" i]`);
if(item_container.length > 0 && $(`.item[data-path="${html_encode(dir.path)}" i]`).length === 0){
UIItem({
appendTo: item_container,
immutable: false,
uid: dir.uid,
path: dir.path,
icon: await item_icon(dir),
name: dir.name,
size: dir.size,
type: dir.type,
modified: dir.modified,
is_dir: true,
is_selected: false,
is_shared: dir.is_shared,
has_website: false,
suggested_apps: dir.suggested_apps,
});
}
sort_items(item_container);
});
//sort each container
$(`.item-container[data-path="${html_encode(dest_path)}" i]`).each(function(){
sort_items(this, $(this).attr('data-sort_by'), $(this).attr('data-sort_order'))
})
}catch(err){
// -----------------------------------------------------------------------
// if item with same name already exists, ask user if they want to overwrite
// -----------------------------------------------------------------------
if(err.code==='item_with_same_name_exists'){
item_with_same_name_already_exists = true;
const alert_resp = await UIAlert({
message: `<strong>${html_encode(err.entry_name)}</strong> already exists.`,
buttons:[
{ label: 'Replace', type: 'primary',},
... (el_items.length > 1) ? [{label: 'Replace all'}] : [],
... (el_items.length > 1) ? [{label: 'Skip'}] : [{label: 'Cancel'}],
]
})
if(alert_resp === 'Replace'){
overwrite = true;
}else if (alert_resp === 'Replace all'){
overwrite = true;
overwrite_all = true;
}else if(alert_resp === 'Skip' || alert_resp === 'Cancel'){
item_with_same_name_already_exists = false;
}
}
// -----------------------------------------------------------------------
// all other errors
// -----------------------------------------------------------------------
else{
item_with_same_name_already_exists = false;
// error message after source item has reappeared
$(el_item).show(0, function(){
UIAlert(`<p>Moving <strong>${html_encode($(el_item).attr('data-name'))}</strong></p>${err.message ?? ''}`)
});
break;
}
}
}while(item_with_same_name_already_exists);
// check if trash is empty
if(untrashed_at_least_one_item){
const trash = await puter.fs.stat(trash_path);
if(window.socket){
window.socket.emit('trash.is_empty', {is_empty: trash.is_empty});
}
if(trash.is_empty){
$(`[data-app="trash"]`).find('.taskbar-icon > img').attr('src', window.icons['trash.svg']);
$(`.item[data-path="${html_encode(trash_path)}" i]`).find('.item-icon > img').attr('src', window.icons['trash.svg']);
$(`.window[data-path="${html_encode(trash_path)}" i]`).find('.window-head-icon').attr('src', window.icons['trash.svg']);
}
}
}
// log stats to console
let move_duration = (Date.now() - move_init_ts);
console.log(`moved ${el_items.length} item${el_items.length > 1 ? 's':''} in ${move_duration}ms`);
// -----------------------------------------------------------------------
// DONE! close progress window with delay to allow user to see 100% progress
// -----------------------------------------------------------------------
setTimeout(() => {
$(progwin).close();
}, copy_progress_hide_delay);
}
/**
* Generates sharing URLs for various social media platforms and services based on the provided arguments.
*
* @global
* @function
* @param {Object} args - Configuration object for generating share URLs.
* @param {string} [args.url] - The URL to share.
* @param {string} [args.title] - The title or headline of the content to share.
* @param {string} [args.image] - Image URL associated with the content.
* @param {string} [args.desc] - A description of the content.
* @param {string} [args.appid] - App ID for certain platforms that require it.
* @param {string} [args.redirecturl] - Redirect URL for certain platforms.
* @param {string} [args.via] - Attribution source, e.g., a Twitter username.
* @param {string} [args.hashtags] - Comma-separated list of hashtags without '#'.
* @param {string} [args.provider] - Content provider.
* @param {string} [args.language] - Content's language.
* @param {string} [args.userid] - User ID for certain platforms.
* @param {string} [args.category] - Content's category.
* @param {string} [args.phonenumber] - Phone number for platforms like SMS or Telegram.
* @param {string} [args.emailaddress] - Email address to share content to.
* @param {string} [args.ccemailaddress] - CC email address for sharing content.
* @param {string} [args.bccemailaddress] - BCC email address for sharing content.
* @returns {Object} - An object containing key-value pairs where keys are platform names and values are constructed sharing URLs.
*
* @example
* const shareConfig = {
* url: 'https://example.com',
* title: 'Check this out!',
* desc: 'This is an amazing article on example.com',
* via: 'exampleUser'
* };
* const shareLinks = window.socialLink(shareConfig);
* console.log(shareLinks.twitter); // Outputs the constructed Twitter share link
*/
window.socialLink = function (args) {
const validargs = [
'url',
'title',
'image',
'desc',
'appid',
'redirecturl',
'via',
'hashtags',
'provider',
'language',
'userid',
'category',
'phonenumber',
'emailaddress',
'cemailaddress',
'bccemailaddress',
];
for(var i = 0; i < validargs.length; i++) {
const validarg = validargs[i];
if(!args[validarg]) {
args[validarg] = '';
}
}
const url = fixedEncodeURIComponent(args.url);
const title = fixedEncodeURIComponent(args.title);
const image = fixedEncodeURIComponent(args.image);
const desc = fixedEncodeURIComponent(args.desc);
const via = fixedEncodeURIComponent(args.via);
const hash_tags = fixedEncodeURIComponent(args.hashtags);
const language = fixedEncodeURIComponent(args.language);
const user_id = fixedEncodeURIComponent(args.userid);
const category = fixedEncodeURIComponent(args.category);
const phone_number = fixedEncodeURIComponent(args.phonenumber);
const email_address = fixedEncodeURIComponent(args.emailaddress);
const cc_email_address = fixedEncodeURIComponent(args.ccemailaddress);
const bcc_email_address = fixedEncodeURIComponent(args.bccemailaddress);
var text = title;
if(desc) {
text += '%20%3A%20'; // This is just this, " : "
text += desc;
}
return {
'add.this':'http://www.addthis.com/bookmark.php?url=' + url,
'blogger':'https://www.blogger.com/blog-this.g?u=' + url + '&n=' + title + '&t=' + desc,
'buffer':'https://buffer.com/add?text=' + text + '&url=' + url,
'diaspora':'https://share.diasporafoundation.org/?title=' + title + '&url=' + url,
'douban':'http://www.douban.com/recommend/?url=' + url + '&title=' + text,
'email':'mailto:' + email_address + '?subject=' + title + '&body=' + desc,
'evernote':'https://www.evernote.com/clip.action?url=' + url + '&title=' + text,
'getpocket':'https://getpocket.com/edit?url=' + url,
'facebook':'http://www.facebook.com/sharer.php?u=' + url,
'flattr':'https://flattr.com/submit/auto?user_id=' + user_id + '&url=' + url + '&title=' + title + '&description=' + text + '&language=' + language + '&tags=' + hash_tags + '&hidden=HIDDEN&category=' + category,
'flipboard':'https://share.flipboard.com/bookmarklet/popout?v=2&title=' + text + '&url=' + url,
'gmail':'https://mail.google.com/mail/?view=cm&to=' + email_address + '&su=' + title + '&body=' + url + '&bcc=' + bcc_email_address + '&cc=' + cc_email_address,
'google.bookmarks':'https://www.google.com/bookmarks/mark?op=edit&bkmk=' + url + '&title=' + title + '&annotation=' + text + '&labels=' + hash_tags + '',
'instapaper':'http://www.instapaper.com/edit?url=' + url + '&title=' + title + '&description=' + desc,
'line.me':'https://lineit.line.me/share/ui?url=' + url + '&text=' + text,
'linkedin':'https://www.linkedin.com/sharing/share-offsite/?url=' + url,
'livejournal':'http://www.livejournal.com/update.bml?subject=' + text + '&event=' + url,
'hacker.news':'https://news.ycombinator.com/submitlink?u=' + url + '&t=' + title,
'ok.ru':'https://connect.ok.ru/dk?st.cmd=WidgetSharePreview&st.shareUrl=' + url,
'pinterest':'http://pinterest.com/pin/create/button/?url=' + url ,
'qzone':'http://sns.qzone.qq.com/cgi-bin/qzshare/cgi_qzshare_onekey?url=' + url,
'reddit':'https://reddit.com/submit?url=' + url + '&title=' + title,
'renren':'http://widget.renren.com/dialog/share?resourceUrl=' + url + '&srcUrl=' + url + '&title=' + text + '&description=' + desc,
'skype':'https://web.skype.com/share?url=' + url + '&text=' + text,
'sms':'sms:' + phone_number + '?body=' + text,
'surfingbird.ru':'http://surfingbird.ru/share?url=' + url + '&description=' + desc + '&screenshot=' + image + '&title=' + title,
'telegram.me':'https://t.me/share/url?url=' + url + '&text=' + text + '&to=' + phone_number,
'threema':'threema://compose?text=' + text + '&id=' + user_id,
'tumblr':'https://www.tumblr.com/widgets/share/tool?canonicalUrl=' + url + '&title=' + title + '&caption=' + desc + '&tags=' + hash_tags,
'twitter':'https://twitter.com/intent/tweet?url=' + url + '&text=' + text + '&via=' + via + '&hashtags=' + hash_tags,
'vk':'http://vk.com/share.php?url=' + url + '&title=' + title + '&comment=' + desc,
'weibo':'http://service.weibo.com/share/share.php?url=' + url + '&appkey=&title=' + title + '&pic=&ralateUid=',
'whatsapp':'https://api.whatsapp.com/send?text=' + text + '%20' + url,
'xing':'https://www.xing.com/spi/shares/new?url=' + url,
'yahoo':'http://compose.mail.yahoo.com/?to=' + email_address + '&subject=' + title + '&body=' + text,
};
}
/**
* Encodes a URI component with enhanced safety by replacing characters
* that are not typically encoded by the standard encodeURIComponent.
*
* @param {string} str - The string to be URI encoded.
* @returns {string} - Returns the URI encoded string.
*
* @example
* const str = "Hello, world!";
* const encodedStr = fixedEncodeURIComponent(str);
* console.log(encodedStr); // Expected output: "Hello%2C%20world%21"
*/
function fixedEncodeURIComponent(str) {
return encodeURIComponent(str).replace(/[!'()*]/g, function(c) {
return '%' + c.charCodeAt(0).toString(16);
});
}
/**
* Refreshes the desktop background based on the user's settings.
* If the user has set a custom desktop background URL or color, it will use that.
* If not, it defaults to a specific wallpaper image.
*
* @global
* @function
* @fires set_desktop_background - Calls this global function to set the desktop background.
*
* @example
* // This will refresh the desktop background according to the user's preference or defaults.
* window.refresh_desktop_background();
*/
window.refresh_desktop_background = function(){
if(window.user && (window.user.desktop_bg_url !== null || window.user.desktop_bg_color !== null)){
window.set_desktop_background({
url: window.user.desktop_bg_url,
fit: window.user.desktop_bg_fit,
color: window.user.desktop_bg_color,
})
}
// default background
else{
let wallpaper = (window.gui_env === 'prod') ? '/dist/images/wallpaper.webp' : '/images/wallpaper.webp';
window.set_desktop_background({
url: wallpaper,
fit: 'cover',
});
}
}
window.determine_website_url = function(fsentry_path){
// search window.sites and if any site has `dir_path` set and the fsentry_path starts with that dir_path + '/', return the site's url + path
for(let i=0; i<window.sites.length; i++){
if(window.sites[i].dir_path && fsentry_path.startsWith(window.sites[i].dir_path + '/')){
return window.sites[i].address + fsentry_path.replace(window.sites[i].dir_path, '');
}
}
return null;
}
window.update_sites_cache = function(){
return puter.hosting.list((sites)=>{
if(sites && sites.length > 0){
window.sites = sites;
}else{
window.sites = [];
}
})
}
/**
*
* @param {*} el_target_container
* @param {*} target_path
*/
window.init_upload_using_dialog = function(el_target_container, target_path = null){
$("#upload-file-dialog").unbind('onchange');
$("#upload-file-dialog").unbind('change');
$("#upload-file-dialog").unbind('onChange');
target_path = target_path === null ? $(el_target_container).attr('data-path') : path.resolve(target_path);
$('#upload-file-dialog').trigger('click');
$("#upload-file-dialog").on('change', async function(e){
if($("#upload-file-dialog").val() !== ''){
const files = $('#upload-file-dialog')[0].files;
if(files.length > 0){
try{
upload_items(files, target_path);
}
catch(err){
UIAlert(err.message ?? err)
}
$('#upload-file-dialog').val('');
}
}
else{
return
}
})
}
window.upload_items = async function(items, dest_path){
let upload_progress_window;
let opid;
puter.fs.upload(
// what to upload
items,
// where to upload
dest_path,
// options
{
// init
init: async(operation_id, xhr)=>{
opid = operation_id;
// create upload progress window
upload_progress_window = await UIWindowUploadProgress({operation_id: operation_id});
// cancel btn
$(upload_progress_window).find('.upload-cancel-btn').on('click', function(e){
$(upload_progress_window).close();
show_save_account_notice_if_needed();
xhr.abort();
})
// add to active_uploads
active_uploads[opid] = 0;
},
// start
start: async function(){
// change upload progress window message to uploading
$(upload_progress_window).find('.upload-progress-msg').html(`Uploading (<span class="upload-progress-percent">0%</span>)`);
},
// progress
progress: async function(operation_id, op_progress){
$(`[data-upload-operation-id="${operation_id}"]`).find('.upload-progress-bar').css( 'width', op_progress+'%');
$(`[data-upload-operation-id="${operation_id}"]`).find('.upload-progress-percent').html(op_progress+'%');
// update active_uploads
active_uploads[opid] = op_progress;
// update title if window is not visible
if(document.visibilityState !== "visible"){
update_title_based_on_uploads();
}
},
// success
success: async function(items){
// DONE
// close progress window after a bit of delay for a better UX
setTimeout(() => {
setTimeout(() => {
$(upload_progress_window).close();
show_save_account_notice_if_needed();
}, Math.abs(upload_progress_hide_delay));
})
// remove from active_uploads
delete active_uploads[opid];
},
// error
error: async function(err){
$(upload_progress_window).close();
// UIAlert(err?.message ?? 'An error occurred while uploading.');
// remove from active_uploads
delete active_uploads[opid];
},
// abort
abort: async function(operation_id){
// console.log('upload aborted');
// remove from active_uploads
delete active_uploads[opid];
}
}
);
}
window.empty_trash = async function(){
const alert_resp = await UIAlert({
message: `Are you sure you want to permanently delete the items in Trash?`,
buttons:[
{
label: 'Yes',
value: 'yes',
type: 'primary',
},
{
label: 'No',
value: 'no',
},
]
})
if(alert_resp === 'no')
return;
// only show progress window if it takes longer than 500ms to create folder
let init_ts = Date.now();
let progwin;
let op_id = uuidv4();
let progwin_timeout = setTimeout(async () => {
progwin = await UIWindowProgressEmptyTrash({operation_id: op_id});
}, 500);
await puter.fs.delete({
paths: trash_path,
descendantsOnly: true,
recursive: true,
success: async function (resp){
// update other clients
if(window.socket){
window.socket.emit('trash.is_empty', {is_empty: true});
}
// use the 'empty trash' icon for Trash
$(`[data-app="trash"]`).find('.taskbar-icon > img').attr('src', window.icons['trash.svg']);
$(`.item[data-path="${html_encode(trash_path)}" i], .item[data-shortcut_to_path="${html_encode(trash_path)}" i]`).find('.item-icon > img').attr('src', window.icons['trash.svg']);
$(`.window[data-path="${trash_path}"]`).find('.window-head-icon').attr('src', window.icons['trash.svg']);
// remove all items with trash paths
// todo this has to be case-insensitive but the `i` selector doesn't work on ^=
$(`.item[data-path^="${trash_path}/"]`).removeItems();
// update the footer item count for Trash
update_explorer_footer_item_count($(`.window[data-path="${trash_path}"]`))
// close progress window
clearTimeout(progwin_timeout);
setTimeout(() => {
$(progwin).close();
}, Math.max(0, copy_progress_hide_delay - (Date.now() - init_ts)));
},
error: async function (err){
clearTimeout(progwin_timeout);
setTimeout(() => {
$(progwin).close();
}, Math.max(0, copy_progress_hide_delay - (Date.now() - init_ts)));
}
});
}
window.copy_to_clipboard = async function(text){
if (navigator.clipboard) {
// copy text to clipboard
await navigator.clipboard.writeText(text);
}
else{
document.execCommand('copy');
}
}
window.getUsage = () => {
return fetch(api_origin + "/drivers/usage", {
headers: {
"Content-Type": "application/json",
"Authorization": "Bearer " + auth_token
},
method: "GET"
})
.then(response => {
// Check if the response is ok (status code in the range 200-299)
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json(); // Parse the response as JSON
})
.then(data => {
// Handle the JSON data
return data;
})
.catch(error => {
// Handle any errors
console.error('There has been a problem with your fetch operation:', error);
});
}
window.determine_active_container_parent = function(){
// the container is either an ancestor of active element...
let parent_container = $(active_element).closest('.item-container');
// ... or a descendant of it...
if(parent_container.length === 0){
parent_container = $(active_element).find('.item-container');
}
// ... or siblings or cousins
if(parent_container.length === 0){
parent_container = $(active_element).closest('.window').find('.item-container');
}
// ... or the active element itself (if it's a container)
if(parent_container.length === 0 && active_element && $(active_element).hasClass('item-container')){
parent_container = $(active_element);
}
// ... or if there is no active element, the selected item that is not blurred
if(parent_container.length === 0 && active_item_container){
parent_container = active_item_container;
}
return parent_container;
}
window.getAppUIDFromOrigin = async function(origin) {
try {
const response = await fetch(window.api_origin + "/auth/app-uid-from-origin", {
headers: {
"Content-Type": "application/json",
"Authorization": "Bearer " + window.auth_token,
},
body: JSON.stringify({ origin: origin }),
method: "POST",
});
const data = await response.json();
// Assuming the app_uid is in the data object, return it
return data.uid;
} catch (err) {
// Handle any errors here
console.error(err);
// You may choose to return something specific here in case of an error
return null;
}
}
window.getUserAppToken = async function(origin) {
try {
const response = await fetch(window.api_origin + "/auth/get-user-app-token", {
headers: {
"Content-Type": "application/json",
"Authorization": "Bearer " + window.auth_token,
},
body: JSON.stringify({ origin: origin }),
method: "POST",
});
const data = await response.json();
// return
return data;
} catch (err) {
// Handle any errors here
console.error(err);
// You may choose to return something specific here in case of an error
return null;
}
}
window.checkUserSiteRelationship = async function(origin) {
try {
const response = await fetch(window.api_origin + "/auth/check-app ", {
headers: {
"Content-Type": "application/json",
"Authorization": "Bearer " + window.auth_token,
},
body: JSON.stringify({ origin: origin }),
method: "POST",
});
const data = await response.json();
// return
return data;
} catch (err) {
// Handle any errors here
console.error(err);
// You may choose to return something specific here in case of an error
return null;
}
}
window.zipItems = async function(el_items, targetDirPath, download = true) {
const zip = new JSZip();
// if single item, convert to array
el_items = Array.isArray(el_items) ? el_items : [el_items];
// create progress window
let start_ts = Date.now();
let progwin, progwin_timeout;
// only show progress window if it takes longer than 500ms to download
progwin_timeout = setTimeout(async () => {
progwin = await UIWindowDownloadDirProg();
}, 500);
for (const el_item of el_items) {
let targetPath = $(el_item).attr('data-path');
// if directory, zip the directory
if($(el_item).attr('data-is_dir') === '1'){
$(progwin).find('.dir-dl-status').html(`Reading <strong>${html_encode(targetPath)}</strong>`);
// Recursively read the directory
let children = await readDirectoryRecursive(targetPath);
// Add files to the zip
for (const child of children) {
let relativePath;
if(el_items.length === 1)
relativePath = child.relativePath;
else
relativePath = path.basename(targetPath) + '/' + child.relativePath;
// update progress window
$(progwin).find('.dir-dl-status').html(`Zipping <strong>${html_encode(relativePath)}</strong>`);
// read file content
let content = await puter.fs.read(child.path);
try{
zip.file(relativePath, content, {binary: true});
}catch(e){
console.error(e);
}
}
}
// if item is a file, zip the file
else{
let content = await puter.fs.read(targetPath);
zip.file(path.basename(targetPath), content, {binary: true});
}
}
// determine name of zip file
let zipName;
if(el_items.length === 1)
zipName = path.basename($(el_items[0]).attr('data-path'));
else
zipName = 'Archive';
// Generate the zip file
zip.generateAsync({ type: "blob" })
.then(async function (content) {
// Trigger the download
if(download){
const url = URL.createObjectURL(content);
const a = document.createElement("a");
a.href = url;
a.download = zipName;
document.body.appendChild(a);
a.click();
// Cleanup
document.body.removeChild(a);
URL.revokeObjectURL(url);
}
// save
else
await puter.fs.write(targetDirPath + '/' + zipName + ".zip", content, {overwrite: false, dedupeName: true})
// close progress window
clearTimeout(progwin_timeout);
setTimeout(() => {
$(progwin).close();
}, Math.max(0, copy_progress_hide_delay - (Date.now() - start_ts)));
})
.catch(function (err) {
// close progress window
clearTimeout(progwin_timeout);
setTimeout(() => {
$(progwin).close();
}, Math.max(0, copy_progress_hide_delay - (Date.now() - start_ts)));
// handle errors
console.error("Error in zipping files: ", err);
});
}
async function readDirectoryRecursive(path, baseDir = '') {
let allFiles = [];
// Read the directory
const entries = await puter.fs.readdir(path);
// Process each entry
for (const entry of entries) {
const fullPath = `${path}/${entry.name}`;
if (entry.is_dir) {
// If entry is a directory, recursively read it
const subDirFiles = await readDirectoryRecursive(fullPath, `${baseDir}${entry.name}/`);
allFiles = allFiles.concat(subDirFiles);
} else {
// If entry is a file, add it to the list
allFiles.push({ path: fullPath, relativePath: `${baseDir}${entry.name}` });
}
}
return allFiles;
}
window.extractSubdomain = function(url) {
var subdomain = url.split('://')[1].split('.')[0];
return subdomain;
}
window.sleep = function(ms){
return new Promise(resolve => setTimeout(resolve, ms));
}
window.unzipItem = async function(itemPath) {
// create progress window
let start_ts = Date.now();
let progwin, progwin_timeout;
// only show progress window if it takes longer than 500ms to download
progwin_timeout = setTimeout(async () => {
progwin = await UIWindowDownloadDirProg();
}, 500);
const zip = new JSZip();
let filPath = itemPath;
let file = puter.fs.read(filPath);
zip.loadAsync(file).then(async function (zip) {
const rootdir = await puter.fs.mkdir(path.dirname(filPath) + '/' + path.basename(filPath, '.zip'), {dedupeName: true});
Object.keys(zip.files).forEach(async function (filename) {
console.log(filename);
if(filename.endsWith('/'))
await puter.fs.mkdir(rootdir.path +'/' + filename, {createMissingParents: true});
zip.files[filename].async('blob').then(async function (fileData) {
await puter.fs.write(rootdir.path +'/' + filename, fileData);
}).catch(function (e) {
// UIAlert(e.message);
})
})
// close progress window
clearTimeout(progwin_timeout);
setTimeout(() => {
$(progwin).close();
}, Math.max(0, copy_progress_hide_delay - (Date.now() - start_ts)));
}).catch(function (e) {
// UIAlert(e.message);
// close progress window
clearTimeout(progwin_timeout);
setTimeout(() => {
$(progwin).close();
}, Math.max(0, copy_progress_hide_delay - (Date.now() - start_ts)));
})
}
|