Spaces:
Paused
Paused
File size: 117,054 Bytes
22d2ae1 dfdcf91 ac0a9be 29a0cd3 ac0a9be dfdcf91 ac0a9be aa49f24 29a0cd3 aa49f24 29a0cd3 22d2ae1 ac0a9be 22d2ae1 ac0a9be 29a0cd3 ac0a9be 29a0cd3 22d2ae1 ac0a9be aa49f24 ac0a9be aa49f24 9b1b573 aa49f24 9b1b573 aa49f24 9b1b573 aa49f24 293e4c5 aa49f24 ac0a9be aa49f24 ac0a9be 22d2ae1 ac0a9be 22d2ae1 ac0a9be dfdcf91 ac0a9be 6af7362 ac0a9be b872222 92f5884 b872222 728abc7 b872222 bdb45aa 6af7362 bdb45aa 6af7362 b872222 ac0a9be 98a7e9a bdb45aa 728abc7 6af7362 bdb45aa 96ff4c7 ac0a9be 2745445 22d2ae1 2745445 bdb45aa 2745445 7a1e1f1 22d2ae1 96ff4c7 2745445 ac0a9be bdb45aa ac0a9be 9f5cd2f ac0a9be 2745445 e7ff9ac 2745445 e7ff9ac ac0a9be ea4fab5 22d2ae1 2745445 ea4fab5 9f5cd2f ea4fab5 ac0a9be 96ff4c7 ac0a9be 9b1b573 aa49f24 9b1b573 aa49f24 dfdcf91 9b1b573 dfdcf91 ac0a9be 0e7dc9f 976c248 0e7dc9f 6f0d256 976c248 ac0a9be dfdcf91 ac0a9be 0f7abfd 976c248 0f7abfd a0378d8 0f7abfd ac0a9be dfdcf91 ac0a9be dfdcf91 ac0a9be 0f7abfd 976c248 ac0a9be dfdcf91 ac0a9be dfdcf91 ac0a9be dfdcf91 ac0a9be dfdcf91 ac0a9be dfdcf91 ac0a9be dfdcf91 ac0a9be dfdcf91 ac0a9be 3fdbb1d ac0a9be 3fdbb1d dfdcf91 3fdbb1d dfdcf91 3fdbb1d dfdcf91 ac0a9be b8e067b ac0a9be b8e067b ac0a9be 22d2ae1 ac0a9be 22d2ae1 ac0a9be dfdcf91 ac0a9be ea4fab5 dfdcf91 aa49f24 9b1b573 aa49f24 dfdcf91 1048be8 dfdcf91 ea4fab5 dfdcf91 1048be8 dfdcf91 ea4fab5 ac0a9be 22d2ae1 ac0a9be aa49f24 ac0a9be dfdcf91 ac0a9be dfdcf91 ac0a9be 4eeabd1 ac0a9be 4eeabd1 976c248 4eeabd1 ac0a9be 4eeabd1 976c248 ac0a9be dfdcf91 ac0a9be dfdcf91 ac0a9be dfdcf91 ac0a9be dc42ed2 ac0a9be dc42ed2 976c248 dc42ed2 ac0a9be dc42ed2 976c248 dc42ed2 ac0a9be dfdcf91 ac0a9be dfdcf91 ac0a9be dfdcf91 ac0a9be aa49f24 ac0a9be 3fdbb1d dfdcf91 3fdbb1d ac0a9be b8e067b 3fdbb1d ac0a9be dfdcf91 ac0a9be 3fdbb1d dfdcf91 3fdbb1d ac0a9be b8e067b 3fdbb1d dfdcf91 3fdbb1d ac0a9be b8e067b 3fdbb1d dfdcf91 3fdbb1d ac0a9be 3fdbb1d ac0a9be aa49f24 ac0a9be 3fdbb1d dfdcf91 3fdbb1d ac0a9be b8e067b 3fdbb1d ac0a9be 3fdbb1d dfdcf91 3fdbb1d ac0a9be b8e067b 3fdbb1d dfdcf91 3fdbb1d ac0a9be b8e067b 3fdbb1d dfdcf91 3fdbb1d ac0a9be 3fdbb1d ac0a9be aa49f24 293e4c5 aa49f24 293e4c5 aa49f24 ac0a9be 47e088b 22d2ae1 ac0a9be 22d2ae1 ac0a9be 9b1b573 ac0a9be 9b1b573 a98a43c dfdcf91 a98a43c 22d2ae1 a98a43c b8e067b a98a43c 22d2ae1 ac0a9be dfdcf91 2745445 dfdcf91 2745445 22d2ae1 2745445 a98a43c 2745445 ac0a9be dfdcf91 9679763 ac0a9be dfdcf91 9679763 dfdcf91 ac0a9be dfdcf91 ac0a9be dfdcf91 ac0a9be 3fdbb1d ac0a9be dfdcf91 ac0a9be b8e067b ac0a9be dfdcf91 ac0a9be dfdcf91 ac0a9be 3fdbb1d ac0a9be aa49f24 293e4c5 aa49f24 293e4c5 aa49f24 293e4c5 aa49f24 29a0cd3 22d2ae1 29a0cd3 22d2ae1 29a0cd3 22d2ae1 ac0a9be 22d2ae1 ac0a9be | 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 | import base64
import hashlib
import json
import os
import platform
import re
import signal
import shutil
import socket
import subprocess
import threading
import time
from pathlib import Path
from urllib.parse import parse_qs, quote, urlparse
from flask import Flask, flash, jsonify, redirect, render_template, request, url_for
import psutil
import qbittorrentapi
import requests
import aria2
BASE_DIR = Path(__file__).resolve().parent
UPLOAD_DIR = BASE_DIR / "uploads"
STATE_FILE = BASE_DIR / "monitor_state.json"
STATE_LOCK = threading.Lock()
UPLOAD_DIR.mkdir(exist_ok=True)
ACTIVE_DOWNLOAD_STATES = {"downloading", "metaDL", "stalledDL", "forcedMetaDL", "forcedDL"}
PAUSED_STATES = {"pausedDL", "pausedUP"}
FAILED_STATES = {"error", "missingFiles", "unknown"}
STUCK_TIMEOUT_MINUTES = int(os.getenv("TORRENT_STUCK_TIMEOUT_MINUTES", "5"))
STUCK_TIMEOUT_SECONDS = STUCK_TIMEOUT_MINUTES * 60
MAX_EVENTS = 12
SYSTEM_INFO_CACHE_SECONDS = 900
LOCATION_CACHE_SECONDS = 3600
GOFILE_LATENCY_CACHE_SECONDS = 600
GOFILE_ENDPOINT_CACHE: dict[str, object] = {"expires_at": 0.0, "urls": []}
RCLONE_CONFIG_CACHE_SECONDS = 60
RCLONE_CONFIG_CACHE: dict[str, object] = {"expires_at": 0.0, "path": "", "remotes": [], "error": ""}
RCLONE_CONFIG_MAX_BYTES = 2 * 1024 * 1024
BTIH_HASH_PATTERN = re.compile(r"^(?:[A-Fa-f0-9]{40}|[A-Z2-7]{32})$")
TORRENT_FILE_SELECTION_WAIT_SECONDS = 8
class GofileUploadCancelled(Exception):
pass
class TorrentMetadataError(ValueError):
pass
class QBittorrentWebAPIError(RuntimeError):
pass
class InsufficientStorageError(ValueError):
pass
def env(name: str, default: str) -> str:
return os.getenv(name, default)
def default_download_path() -> str:
if "QBITTORRENT_SAVE_PATH" in os.environ:
return os.environ["QBITTORRENT_SAVE_PATH"]
if Path("/data").exists():
return "/data/downloads"
return "/downloads"
def default_gofile_upload_urls() -> str:
return ",".join(
[
"https://upload.gofile.io/uploadfile",
"https://upload-na-phx.gofile.io/uploadfile",
"https://upload-na-nyc.gofile.io/uploadfile",
"https://upload-eu-par.gofile.io/uploadfile",
"https://upload-ap-sgp.gofile.io/uploadfile",
]
)
def parse_gofile_upload_urls() -> list[str]:
raw_value = env("GOFILE_UPLOAD_URLS", default_gofile_upload_urls())
urls = [item.strip() for item in raw_value.split(",") if item.strip()]
return urls or ["https://upload.gofile.io/uploadfile"]
def safe_filename(value: str) -> str:
sanitized = re.sub(r"[^A-Za-z0-9._-]+", "-", value).strip("-")
return sanitized or "archive"
def flatten_relative_name(relative_path: Path) -> str:
flattened = "__".join(relative_path.parts)
return safe_filename(flattened)
def validate_magnet_link(raw_value: str) -> tuple[bool, str]:
magnet = (raw_value or "").strip()
if not magnet:
return False, "Magnet link wajib diisi."
parsed = urlparse(magnet)
if parsed.scheme.lower() != "magnet":
return False, "Hanya magnet link yang didukung. Link selain magnet tidak diterima."
query = parse_qs(parsed.query, keep_blank_values=False)
xt_values = query.get("xt", [])
if not xt_values:
return False, "Magnet link tidak valid: parameter xt wajib ada."
btih_value = ""
for xt_value in xt_values:
if xt_value.lower().startswith("urn:btih:"):
btih_value = xt_value[9:]
break
if not btih_value:
return False, "Magnet link tidak valid: xt harus berupa urn:btih."
if not BTIH_HASH_PATTERN.fullmatch(btih_value.upper()):
return False, "Magnet link tidak valid: info hash btih tidak sesuai format."
return True, magnet
def magnet_info_hash(magnet: str) -> str:
parsed = urlparse(magnet)
query = parse_qs(parsed.query, keep_blank_values=False)
for xt_value in query.get("xt", []):
if not xt_value.lower().startswith("urn:btih:"):
continue
raw_hash = xt_value[9:]
if re.fullmatch(r"[A-Fa-f0-9]{40}", raw_hash):
return raw_hash.lower()
if re.fullmatch(r"[A-Z2-7a-z2-7]{32}", raw_hash):
return base64.b32decode(raw_hash.upper()).hex()
raise TorrentMetadataError("Magnet link tidak mengandung info hash btih yang valid.")
def _read_bencoded_bytes(data: bytes, offset: int) -> tuple[bytes, int]:
colon_index = data.find(b":", offset)
if colon_index < 0:
raise TorrentMetadataError("Metadata torrent tidak valid.")
try:
length = int(data[offset:colon_index])
except ValueError as exc:
raise TorrentMetadataError("Metadata torrent tidak valid.") from exc
start = colon_index + 1
end = start + length
if length < 0 or end > len(data):
raise TorrentMetadataError("Metadata torrent tidak valid.")
return data[start:end], end
def _skip_bencoded_value(data: bytes, offset: int) -> int:
if offset >= len(data):
raise TorrentMetadataError("Metadata torrent tidak valid.")
token = data[offset : offset + 1]
if token == b"i":
end = data.find(b"e", offset + 1)
if end < 0:
raise TorrentMetadataError("Metadata torrent tidak valid.")
return end + 1
if token in {b"l", b"d"}:
offset += 1
while offset < len(data) and data[offset : offset + 1] != b"e":
offset = _skip_bencoded_value(data, offset)
if offset >= len(data):
raise TorrentMetadataError("Metadata torrent tidak valid.")
return offset + 1
if token.isdigit():
_value, next_offset = _read_bencoded_bytes(data, offset)
return next_offset
raise TorrentMetadataError("Metadata torrent tidak valid.")
def torrent_info_hash_from_bytes(data: bytes) -> str:
if not data.startswith(b"d"):
raise TorrentMetadataError("File torrent tidak valid.")
offset = 1
while offset < len(data) and data[offset : offset + 1] != b"e":
key, offset = _read_bencoded_bytes(data, offset)
value_start = offset
value_end = _skip_bencoded_value(data, offset)
if key == b"info":
return hashlib.sha1(data[value_start:value_end]).hexdigest()
offset = value_end
raise TorrentMetadataError("File torrent tidak mengandung metadata info.")
def parse_size_token(token: str) -> int | None:
cleaned = token.strip()
if not cleaned or cleaned in {"-", "--", "--:--:--"}:
return None
unit = ""
if cleaned[-1].isalpha():
unit = cleaned[-1].lower()
cleaned = cleaned[:-1]
try:
value = float(cleaned)
except ValueError:
return None
multipliers = {
"": 1,
"k": 1000,
"m": 1000**2,
"g": 1000**3,
"t": 1000**4,
"p": 1000**5,
}
return int(value * multipliers.get(unit, 1))
def gofile_endpoint_label(upload_url: str) -> str:
host = urlparse(upload_url).hostname or "upload.gofile.io"
return host.replace(".gofile.io", "")
def measure_gofile_endpoint_latency(upload_url: str) -> float:
host = urlparse(upload_url).hostname
if not host:
return float("inf")
started = time.perf_counter()
connection = socket.create_connection((host, 443), timeout=2)
connection.close()
return time.perf_counter() - started
def ranked_gofile_upload_urls() -> list[str]:
now = time.time()
cached_urls = GOFILE_ENDPOINT_CACHE.get("urls", [])
expires_at = float(GOFILE_ENDPOINT_CACHE.get("expires_at", 0.0) or 0.0)
if cached_urls and now < expires_at:
return list(cached_urls)
ranked: list[tuple[float, int, str]] = []
for index, upload_url in enumerate(GOFILE_UPLOAD_URLS):
try:
latency = measure_gofile_endpoint_latency(upload_url)
except OSError:
latency = float("inf")
ranked.append((latency, index, upload_url))
ranked.sort(key=lambda item: (item[0], item[1]))
ordered_urls = [item[2] for item in ranked]
GOFILE_ENDPOINT_CACHE["urls"] = ordered_urls
GOFILE_ENDPOINT_CACHE["expires_at"] = now + GOFILE_LATENCY_CACHE_SECONDS
return ordered_urls
def discover_root_rclone_config() -> Path | None:
candidates = [
RCLONE_CONFIG_PATH,
BASE_DIR / "rclone.conf",
Path("/config/rclone.conf"),
Path("/data/rclone.conf"),
]
for candidate in candidates:
if candidate.exists() and candidate.is_file() and candidate.stat().st_size > 0:
return candidate
return None
def download_rclone_config_from_url(raw_url: str) -> Path:
parsed = urlparse(raw_url)
if parsed.scheme.lower() not in {"http", "https"}:
raise ValueError("RCLONE_CONFIG_URL harus berupa URL http/https.")
response = requests.get(raw_url, timeout=30)
response.raise_for_status()
content = response.content
if len(content) > RCLONE_CONFIG_MAX_BYTES:
raise ValueError("rclone.conf dari URL terlalu besar.")
if not content.strip():
raise ValueError("rclone.conf dari URL kosong.")
destination = UPLOAD_DIR / "rclone.conf"
destination.write_bytes(content)
return destination
def runtime_rclone_config_url() -> str:
if RCLONE_CONFIG_URL:
return RCLONE_CONFIG_URL
try:
state = load_monitor_state()
except Exception:
return ""
return str(state.get("rclone", {}).get("config_url", "") or "").strip()
def set_runtime_rclone_config_url(raw_url: str) -> None:
def mutator(state: dict):
state.setdefault("rclone", {})["config_url"] = raw_url.strip()
update_state(mutator)
RCLONE_CONFIG_CACHE.update({"expires_at": 0.0, "path": "", "remotes": [], "error": ""})
def rclone_config_path() -> Path:
config_url = runtime_rclone_config_url()
if config_url:
return download_rclone_config_from_url(config_url)
config_path = discover_root_rclone_config()
if config_path is None:
raise FileNotFoundError(
"rclone.conf belum ditemukan. Tambahkan rclone.conf di root project, /config, /data, "
"atau set RCLONE_CONFIG_URL ke raw URL GitHub/Gist."
)
return config_path
def validate_rclone_config(force_refresh: bool = False) -> dict:
now = time.time()
if not force_refresh and now < float(RCLONE_CONFIG_CACHE.get("expires_at", 0.0) or 0.0):
return dict(RCLONE_CONFIG_CACHE)
result: dict[str, object] = {"expires_at": now + RCLONE_CONFIG_CACHE_SECONDS, "path": "", "remotes": [], "error": ""}
try:
if shutil.which("rclone") is None:
raise FileNotFoundError("Binary rclone belum tersedia di container.")
config_path = rclone_config_path()
process = subprocess.run(
["rclone", "--config", str(config_path), "listremotes"],
capture_output=True,
text=True,
timeout=30,
check=False,
)
if process.returncode != 0:
detail = (process.stderr or process.stdout or "").strip()
raise ValueError(f"rclone.conf tidak valid: {detail[:500]}")
remotes = [line.strip().rstrip(":") for line in process.stdout.splitlines() if line.strip()]
if not remotes:
raise ValueError("rclone.conf tidak berisi remote aktif.")
if RCLONE_REMOTE and RCLONE_REMOTE not in remotes:
raise ValueError(f"Remote rclone '{RCLONE_REMOTE}' tidak ditemukan. Remote tersedia: {', '.join(remotes)}")
result["path"] = str(config_path)
result["remotes"] = remotes
except (OSError, ValueError, requests.RequestException) as exc:
result["error"] = str(exc)
RCLONE_CONFIG_CACHE.update(result)
return dict(RCLONE_CONFIG_CACHE)
def is_rclone_upload_available() -> bool:
config = validate_rclone_config()
return bool(config.get("remotes")) and not config.get("error")
def rclone_config_summary(force_refresh: bool = False) -> dict:
config = validate_rclone_config(force_refresh=force_refresh)
return {
"available": bool(config.get("remotes")) and not config.get("error"),
"error": config.get("error", ""),
"remotes": config.get("remotes", []),
"selected_remote": selected_rclone_remote(config),
"config_url_set": bool(runtime_rclone_config_url()),
"config_path": config.get("path", ""),
}
def selected_rclone_remote(config: dict | None = None) -> str:
config = config or validate_rclone_config()
remotes = list(config.get("remotes", []) or [])
if RCLONE_REMOTE:
return RCLONE_REMOTE
return str(remotes[0]) if remotes else ""
def requested_rclone_remote(config: dict, raw_remote: str) -> str:
remotes = [str(remote) for remote in list(config.get("remotes", []) or [])]
remote = raw_remote.strip().rstrip(":")
if not remote:
remote = selected_rclone_remote(config)
if not remote:
raise ValueError("Remote rclone belum dipilih.")
if remote not in remotes:
available = ", ".join(remotes) if remotes else "-"
raise ValueError(f"Remote rclone '{remote}' tidak ditemukan. Remote tersedia: {available}")
return remote
def rclone_remote_label() -> str:
remote = selected_rclone_remote()
return remote or "rclone"
def rclone_remote_path(*parts: str) -> str:
cleaned = [part.strip("/").replace("\\", "/") for part in parts if part and part.strip("/")]
return "/".join(cleaned)
def rclone_destination_spec(remote: str, *parts: str) -> str:
destination_path = rclone_remote_path(RCLONE_DESTINATION_PATH, *parts)
return f"{remote}:{destination_path}" if destination_path else f"{remote}:"
def path_total_size(source_path: Path) -> int:
if source_path.is_file():
return source_path.stat().st_size
total = 0
for item in source_path.rglob("*"):
if item.is_file():
try:
total += item.stat().st_size
except OSError:
continue
return total
def process_exists(pid: int | None) -> bool:
if not pid or pid <= 0:
return False
try:
os.kill(pid, 0)
except OSError:
return False
return True
def cancel_upload_process(pid: int | None) -> bool:
if not process_exists(pid):
return False
try:
os.kill(pid, signal.SIGTERM)
return True
except OSError:
return False
GOFILE_UPLOAD_URLS = parse_gofile_upload_urls()
GOFILE_API_TOKEN = env("GOFILE_API_TOKEN", "Rqm8uMPcbDbAV8wdiG93lNRcGuvSJj3r")
PIXELDRAIN_API_KEY = env("PIXELDRAIN_API_KEY", "acee6b32-bba9-45f1-bfb1-71cf583ad405")
PIXELDRAIN_API_URL = env("PIXELDRAIN_API_URL", "https://pixeldrain.com/api")
IP_LOCATION_API_URL = env("IP_LOCATION_API_URL", "https://ipapi.co/json/")
CLOUDFLARE_DOWNLOAD_URL = env("CLOUDFLARE_DOWNLOAD_URL", "https://speed.cloudflare.com/__down")
CLOUDFLARE_UPLOAD_URL = env("CLOUDFLARE_UPLOAD_URL", "https://speed.cloudflare.com/__up")
RCLONE_CONFIG_URL = env("RCLONE_CONFIG_URL", "").strip()
RCLONE_CONFIG_PATH = Path(env("RCLONE_CONFIG_PATH", str(BASE_DIR / "rclone.conf"))).expanduser()
RCLONE_REMOTE = env("RCLONE_REMOTE", "").strip().rstrip(":")
RCLONE_DESTINATION_PATH = env("RCLONE_DESTINATION_PATH", "torrent-web").strip().strip("/")
WEB_PORT = int(env("PORT", "5000"))
app = Flask(__name__)
app.config["SECRET_KEY"] = env("FLASK_SECRET_KEY", "dev-secret")
app.config["MAX_CONTENT_LENGTH"] = 100 * 1024 * 1024
DOWNLOAD_PATH = default_download_path()
def get_client() -> qbittorrentapi.Client:
host = env("QBITTORRENT_HOST", "127.0.0.1")
port = int(env("QBITTORRENT_PORT", "8080"))
username = env("QBITTORRENT_USERNAME", "")
password = env("QBITTORRENT_PASSWORD", "")
client = qbittorrentapi.Client(
host=host,
port=port,
username=username,
password=password,
)
if username and password:
try:
client.auth_log_in()
except qbittorrentapi.LoginFailed:
# Docker deployments in this repo can allow the app subnet to bypass
# WebUI auth. Fall back to a session without explicit login so the UI
# still works while qBittorrent config is being repaired or migrated.
fallback_client = qbittorrentapi.Client(host=host, port=port)
fallback_client.app.version
return fallback_client
return client
def qbt_base_url() -> str:
host = env("QBITTORRENT_HOST", "127.0.0.1")
port = int(env("QBITTORRENT_PORT", "8080"))
return f"http://{host}:{port}/api/v2"
def qbt_webapi_request(method: str, path: str, **kwargs) -> requests.Response:
session = requests.Session()
base_url = qbt_base_url()
username = env("QBITTORRENT_USERNAME", "")
password = env("QBITTORRENT_PASSWORD", "")
timeout = kwargs.pop("timeout", 20)
if username and password:
login_response = session.post(
f"{base_url}/auth/login",
data={"username": username, "password": password},
timeout=10,
)
if login_response.status_code >= 400 or login_response.text.strip() not in {"Ok.", ""}:
# Some bundled qBittorrent configs bypass auth for the app subnet.
session = requests.Session()
response = session.request(method, f"{base_url}{path}", timeout=timeout, **kwargs)
if response.status_code >= 400:
raise QBittorrentWebAPIError(response.text.strip() or f"HTTP {response.status_code}")
return response
def qbt_add_torrent_url(url: str, paused: bool) -> None:
response = qbt_webapi_request(
"POST",
"/torrents/add",
data={
"urls": url,
"savepath": DOWNLOAD_PATH,
"paused": "true" if paused else "false",
"stopped": "true" if paused else "false",
},
timeout=30,
)
if response.text.strip() not in {"Ok.", ""}:
raise QBittorrentWebAPIError(response.text.strip())
def qbt_add_torrent_file(file_path: Path, paused: bool) -> None:
with file_path.open("rb") as handle:
response = qbt_webapi_request(
"POST",
"/torrents/add",
data={
"savepath": DOWNLOAD_PATH,
"paused": "true" if paused else "false",
"stopped": "true" if paused else "false",
},
files={"torrents": (file_path.name, handle, "application/x-bittorrent")},
timeout=30,
)
if response.text.strip() not in {"Ok.", ""}:
raise QBittorrentWebAPIError(response.text.strip())
def qbt_torrent_files(torrent_hash: str) -> list[dict]:
response = qbt_webapi_request("GET", "/torrents/files", params={"hash": torrent_hash}, timeout=15)
payload = response.json()
return payload if isinstance(payload, list) else []
def qbt_torrent_exists(torrent_hash: str) -> bool:
response = qbt_webapi_request("GET", "/torrents/info", params={"hashes": torrent_hash}, timeout=15)
payload = response.json()
return isinstance(payload, list) and len(payload) > 0
def qbt_delete_torrent(torrent_hash: str, delete_files: bool = False) -> None:
qbt_webapi_request(
"POST",
"/torrents/delete",
data={"hashes": torrent_hash, "deleteFiles": "true" if delete_files else "false"},
timeout=15,
)
def wait_for_torrent_task(torrent_hash: str, timeout_seconds: int = 6) -> bool:
deadline = time.time() + timeout_seconds
while time.time() <= deadline:
if qbt_torrent_exists(torrent_hash):
return True
time.sleep(0.5)
return False
def qbt_pause_torrent(torrent_hash: str) -> None:
try:
qbt_webapi_request("POST", "/torrents/stop", data={"hashes": torrent_hash}, timeout=15)
except QBittorrentWebAPIError:
qbt_webapi_request("POST", "/torrents/pause", data={"hashes": torrent_hash}, timeout=15)
def qbt_resume_torrent(torrent_hash: str) -> None:
try:
qbt_webapi_request("POST", "/torrents/start", data={"hashes": torrent_hash}, timeout=15)
except QBittorrentWebAPIError:
qbt_webapi_request("POST", "/torrents/resume", data={"hashes": torrent_hash}, timeout=15)
def qbt_set_file_priority(torrent_hash: str, file_ids: list[int], priority: int) -> None:
if not file_ids:
return
qbt_webapi_request(
"POST",
"/torrents/filePrio",
data={
"hash": torrent_hash,
"id": "|".join(str(file_id) for file_id in file_ids),
"priority": str(priority),
},
timeout=20,
)
def torrent_file_index(file_entry: dict, fallback: int) -> int:
for key in ("index", "id"):
value = file_entry.get(key)
if value is not None:
return int(value)
return fallback
def serialize_torrent_file(file_entry: dict, fallback_index: int) -> dict:
file_index = torrent_file_index(file_entry, fallback_index)
size = int(file_entry.get("size", 0) or 0)
priority = int(file_entry.get("priority", 1) or 0)
return {
"id": file_index,
"name": str(file_entry.get("name", "") or f"File {file_index + 1}"),
"size": format_size(size),
"size_bytes": size,
"priority": priority,
"selected": priority != 0,
}
def download_storage_usage():
return shutil.disk_usage(DOWNLOAD_PATH)
def storage_validation(required_bytes: int) -> dict:
disk = download_storage_usage()
available_bytes = int(disk.free)
required_bytes = max(0, int(required_bytes or 0))
ok = required_bytes <= available_bytes
return {
"storage_ok": ok,
"storage_required_bytes": required_bytes,
"storage_required": format_size(required_bytes),
"storage_available_bytes": available_bytes,
"storage_available": format_size(available_bytes),
"storage_warning": ""
if ok
else (
f"Storage tidak cukup. Butuh {format_size(required_bytes)}, "
f"tersedia {format_size(available_bytes)}. Hapus atau bersihkan file lama dulu."
),
}
def ensure_storage_available(required_bytes: int) -> None:
validation = storage_validation(required_bytes)
if not validation["storage_ok"]:
raise InsufficientStorageError(validation["storage_warning"])
def selected_torrent_file_stats(torrent_hash: str, fallback_total_size: int) -> dict:
try:
files = qbt_torrent_files(torrent_hash)
except (QBittorrentWebAPIError, requests.RequestException, ValueError):
files = []
if not files:
return {
"selected_total_size": fallback_total_size,
"selected_downloaded": 0,
"selected_file_count": 0,
"file_count": 0,
"has_file_selection": False,
}
selected_files = [file_entry for file_entry in files if int(file_entry.get("priority", 0) or 0) > 0]
selected_total_size = sum(int(file_entry.get("size", 0) or 0) for file_entry in selected_files)
selected_downloaded = sum(
int((int(file_entry.get("size", 0) or 0) * float(file_entry.get("progress", 0) or 0)))
for file_entry in selected_files
)
return {
"selected_total_size": selected_total_size,
"selected_downloaded": min(selected_downloaded, selected_total_size),
"selected_file_count": len(selected_files),
"file_count": len(files),
"has_file_selection": len(files) > 1 and len(selected_files) < len(files),
}
def wait_for_torrent_files(torrent_hash: str, timeout_seconds: int = TORRENT_FILE_SELECTION_WAIT_SECONDS) -> list[dict]:
deadline = time.time() + timeout_seconds
while time.time() <= deadline:
files = qbt_torrent_files(torrent_hash)
if files:
return files
time.sleep(0.5)
return []
def build_file_selection_payload(torrent_hash: str, files: list[dict]) -> dict:
serialized_files = [serialize_torrent_file(file_entry, index) for index, file_entry in enumerate(files)]
selected_total_size = sum(int(file_entry.get("size_bytes", 0) or 0) for file_entry in serialized_files if file_entry.get("selected", True))
storage = storage_validation(selected_total_size)
selection_required = len(serialized_files) > 1
if selection_required:
qbt_pause_torrent(torrent_hash)
return {
"selection_required": True,
"selection_pending": False,
"torrent_hash": torrent_hash,
"files": serialized_files,
**storage,
"message": "Torrent berisi beberapa file. Pilih file yang ingin didownload.",
}
if not storage["storage_ok"]:
try:
qbt_delete_torrent(torrent_hash, delete_files=False)
except (QBittorrentWebAPIError, requests.RequestException):
pass
raise InsufficientStorageError(storage["storage_warning"])
qbt_resume_torrent(torrent_hash)
return {
"selection_required": False,
"selection_pending": False,
"torrent_hash": torrent_hash,
"files": serialized_files,
**storage,
"message": "Torrent ditambahkan dan download dimulai.",
}
def clear_torrent_status_message(torrent_hash: str) -> None:
state = load_monitor_state()
entry = state.setdefault("torrents", {}).setdefault(torrent_hash, {})
entry["last_progress_at"] = time.time()
entry["status_message"] = ""
save_monitor_state(state)
def add_magnet_and_confirm_task(magnet: str, torrent_hash: str) -> None:
try:
qbt_add_torrent_url(magnet, paused=False)
except (QBittorrentWebAPIError, requests.RequestException):
if not wait_for_torrent_task(torrent_hash):
raise
else:
wait_for_torrent_task(torrent_hash)
def format_size(value: int | None) -> str:
if value in (None, 0):
return "0 B"
size = float(value)
units = ["B", "KB", "MB", "GB", "TB"]
for unit in units:
if size < 1024 or unit == units[-1]:
return f"{size:.1f} {unit}"
size /= 1024
return f"{size:.1f} TB"
def format_speed(value: int | None) -> str:
return f"{format_size(value)}/s"
def format_mbps(bits_per_second: float | None) -> str:
if not bits_per_second:
return "0 Mbps"
return f"{bits_per_second / 1_000_000:.2f} Mbps"
def progress_percent(progress: float | None) -> int:
if progress is None:
return 0
return round(progress * 100)
def format_duration(seconds: float) -> str:
seconds = max(0, int(seconds))
if seconds < 60:
return f"{seconds} detik"
if seconds < 3600:
return f"{seconds // 60} menit"
return f"{seconds // 3600} jam"
def human_eta(seconds: float | int | None) -> str:
if seconds is None:
return "-"
total_seconds = int(seconds)
if total_seconds <= 0:
return "-"
if total_seconds < 60:
return f"{total_seconds} seconds left"
minutes = total_seconds // 60
if total_seconds < 3600:
return f"{minutes} minute left" if minutes == 1 else f"{minutes} minutes left"
if total_seconds < 86400:
hours = total_seconds // 3600
remaining_minutes = (total_seconds % 3600) // 60
if remaining_minutes == 0:
return f"{hours} hour left" if hours == 1 else f"{hours} hours left"
hour_label = "hour" if hours == 1 else "hours"
minute_label = "minute" if remaining_minutes == 1 else "minutes"
return f"{hours} {hour_label} {remaining_minutes} {minute_label} left"
days = total_seconds // 86400
hours = total_seconds // 3600
remaining_hours = (total_seconds % 86400) // 3600
if remaining_hours == 0:
return f"{days} day left" if days == 1 else f"{days} days left"
day_label = "day" if days == 1 else "days"
hour_label = "hour" if remaining_hours == 1 else "hours"
return f"{days} {day_label} {remaining_hours} {hour_label} left"
def load_monitor_state() -> dict:
with STATE_LOCK:
if not STATE_FILE.exists():
return {"torrents": {}, "aria2": {}, "events": [], "system": {}, "speedtest": {"running": False}}
try:
data = json.loads(STATE_FILE.read_text(encoding="utf-8"))
except (json.JSONDecodeError, OSError):
return {"torrents": {}, "aria2": {}, "events": [], "system": {}, "speedtest": {"running": False}}
data.setdefault("torrents", {})
data.setdefault("aria2", {})
data.setdefault("events", [])
data.setdefault("system", {})
data.setdefault("speedtest", {"running": False})
return data
def save_monitor_state(state: dict) -> None:
with STATE_LOCK:
temp_file = STATE_FILE.with_suffix(".tmp")
temp_file.write_text(json.dumps(state, ensure_ascii=True, indent=2), encoding="utf-8")
temp_file.replace(STATE_FILE)
def update_state(mutator):
state = load_monitor_state()
mutator(state)
save_monitor_state(state)
def add_event(state: dict, level: str, message: str) -> None:
state.setdefault("events", []).insert(
0,
{
"level": level,
"message": message,
"created_at": int(time.time()),
},
)
state["events"] = state["events"][:MAX_EVENTS]
def state_label(raw_state: str) -> str:
mapping = {
"downloading": "Downloading",
"stalledDL": "Stalled",
"metaDL": "Fetching Metadata",
"pausedDL": "Paused",
"pausedUP": "Paused",
"uploading": "Seeding",
"stalledUP": "Stalled Up",
"queuedDL": "Queued",
"queuedUP": "Queued Up",
"checkingUP": "Checking",
"checkingDL": "Checking",
"forcedDL": "Forced Download",
"forcedMetaDL": "Forced Metadata",
"forcedUP": "Seeding",
"error": "Error",
"missingFiles": "Missing Files",
}
return mapping.get(raw_state, raw_state)
def status_badge(raw_state: str) -> str:
if raw_state in FAILED_STATES:
return "border-rose-500/30 bg-rose-500/10 text-rose-200"
if raw_state in ACTIVE_DOWNLOAD_STATES:
return "border-amber-500/30 bg-amber-500/10 text-amber-100"
if raw_state in PAUSED_STATES:
return "border-stone-500/30 bg-stone-500/10 text-stone-200"
return "border-emerald-500/30 bg-emerald-500/10 text-emerald-100"
def effective_state_label(torrent, state_entry: dict | None = None) -> str:
if state_entry and state_entry.get("gofile_uploading"):
provider_name = state_entry.get("gofile_provider") or "Remote"
return f"{provider_name} Upload"
raw_state = getattr(torrent, "state", "")
progress = float(getattr(torrent, "progress", 0) or 0)
if progress >= 1:
if raw_state in {"uploading", "forcedUP", "stalledUP"}:
return "Seeding"
if raw_state == "pausedUP":
return "Paused"
if raw_state == "queuedUP":
return "Queued Up"
if raw_state == "checkingUP":
return "Checking Up"
return state_label(raw_state)
def effective_status_badge(torrent, state_entry: dict | None = None) -> str:
if state_entry and state_entry.get("gofile_uploading"):
return "border-sky-500/30 bg-sky-500/10 text-sky-100"
raw_state = getattr(torrent, "state", "")
progress = float(getattr(torrent, "progress", 0) or 0)
upspeed = int(getattr(torrent, "upspeed", 0) or 0)
if progress >= 1 and raw_state in {"uploading", "forcedUP", "stalledUP"}:
if upspeed > 0:
return "border-sky-500/30 bg-sky-500/10 text-sky-100"
return "border-lime/30 bg-lime/10 text-lime"
return status_badge(raw_state)
def swarm_peer_counts(torrent) -> tuple[int, int]:
live_seeds = int(getattr(torrent, "num_seeds", 0) or 0)
live_leechs = int(getattr(torrent, "num_leechs", 0) or 0)
tracker_complete = int(getattr(torrent, "num_complete", 0) or 0)
tracker_incomplete = int(getattr(torrent, "num_incomplete", 0) or 0)
return max(live_seeds, tracker_complete), max(live_leechs, tracker_incomplete)
def serialize_event(event: dict) -> dict:
return {
"level": event.get("level", "info"),
"message": event.get("message", ""),
"created_at": event.get("created_at", 0),
}
def serialize_torrent(torrent, state_entry: dict | None = None) -> dict:
eta_value = getattr(torrent, "eta", None)
raw_state = getattr(torrent, "state", "")
torrent_total_size = int(getattr(torrent, "total_size", 0) or 0)
torrent_progress = float(getattr(torrent, "progress", 0) or 0)
raw_torrent_dlspeed = int(getattr(torrent, "dlspeed", 0) or 0)
torrent_upspeed = int(getattr(torrent, "upspeed", 0) or 0)
torrent_downloaded = max(
int(getattr(torrent, "downloaded", 0) or 0),
int(getattr(torrent, "downloaded_session", 0) or 0),
)
torrent_uploaded = max(
int(getattr(torrent, "uploaded", 0) or 0),
int(getattr(torrent, "uploaded_session", 0) or 0),
)
selected_stats = selected_torrent_file_stats(getattr(torrent, "hash", ""), torrent_total_size)
display_total_size = int(selected_stats["selected_total_size"] or 0)
display_downloaded = int(selected_stats["selected_downloaded"] or 0)
if not selected_stats["file_count"]:
display_downloaded = torrent_downloaded
elif not selected_stats["has_file_selection"]:
display_downloaded = torrent_downloaded
torrent_num_seeds, torrent_num_leechs = swarm_peer_counts(torrent)
state_entry = state_entry or {}
status_message = state_entry.get("status_message", "")
content_path = Path(getattr(torrent, "content_path", "") or "")
is_folder = bool(content_path and content_path.exists() and content_path.is_dir())
gofile_uploading = bool(state_entry.get("gofile_uploading"))
upload_provider = state_entry.get("gofile_provider", "GoFile")
gofile_progress = int(state_entry.get("gofile_progress", 0) or 0)
gofile_eta_seconds = int(state_entry.get("gofile_eta_seconds", 0) or 0)
torrent_dlspeed = 0 if not gofile_uploading and torrent_progress >= 1 else raw_torrent_dlspeed
display_progress = gofile_progress if gofile_uploading else progress_percent(torrent_progress)
if gofile_uploading and upload_provider == "Archiving":
progress_label = "Archiving"
else:
progress_label = f"{upload_provider} Upload" if gofile_uploading else "Progress"
gofile_speed = state_entry.get("gofile_speed", "")
badge_download_speed = format_speed(torrent_dlspeed)
badge_upload_speed = format_speed(torrent_upspeed)
if gofile_uploading:
eta_text = human_eta(gofile_eta_seconds)
badge_download_speed = "0 B/s"
badge_upload_speed = gofile_speed or "0 B/s"
elif torrent_progress >= 1:
eta_text = "-"
else:
eta_text = human_eta(eta_value)
display_speed = gofile_speed if gofile_uploading else format_speed(torrent_dlspeed)
if gofile_uploading and upload_provider == "Archiving":
display_speed = state_entry.get("gofile_status", "") or "Archiving..."
display_speed_label = "Archive"
else:
display_speed_label = f"{upload_provider} Upload" if gofile_uploading else "Down"
display_speed_meta = f"{gofile_progress}%" if gofile_uploading else ""
if not gofile_uploading and torrent_progress >= 1:
display_speed = format_speed(torrent_upspeed)
display_speed_label = "Up"
display_speed_meta = ""
can_gofile_upload = (
bool(content_path)
and content_path.exists()
and progress_percent(torrent_progress) >= 100
and not gofile_uploading
)
return {
"hash": torrent.hash,
"name": torrent.name,
"state": torrent.state,
"state_label": effective_state_label(torrent, state_entry),
"state_badge": effective_status_badge(torrent, state_entry),
"total_size": format_size(display_total_size),
"torrent_total_size": format_size(torrent_total_size),
"selected_file_count": selected_stats["selected_file_count"],
"file_count": selected_stats["file_count"],
"has_file_selection": selected_stats["has_file_selection"],
"downloaded": format_size(display_downloaded),
"uploaded": format_size(torrent_uploaded),
"ratio": f"{float(getattr(torrent, 'ratio', 0) or 0):.2f}",
"dlspeed": badge_download_speed,
"upspeed": badge_upload_speed,
"display_speed": display_speed,
"display_speed_label": display_speed_label,
"display_speed_meta": display_speed_meta,
"progress": display_progress,
"progress_label": progress_label,
"num_seeds": torrent_num_seeds,
"num_leechs": torrent_num_leechs,
"eta": eta_text,
"status_message": status_message,
"can_pause": torrent.state not in PAUSED_STATES and torrent.state not in FAILED_STATES and not gofile_uploading,
"can_resume": torrent.state in PAUSED_STATES,
"can_gofile_upload": can_gofile_upload,
"gofile_link": state_entry.get("gofile_link", ""),
"gofile_status": state_entry.get("gofile_status", ""),
"gofile_uploading": gofile_uploading,
"gofile_speed": gofile_speed,
"gofile_eta": human_eta(gofile_eta_seconds) if gofile_uploading else "-",
"gofile_endpoint": state_entry.get("gofile_endpoint", ""),
"upload_provider": upload_provider,
"can_copy_link": bool(state_entry.get("gofile_link")),
"can_cancel_gofile_upload": gofile_uploading,
"can_pixeldrain_upload": can_gofile_upload and bool(PIXELDRAIN_API_KEY),
"can_rclone_upload": can_gofile_upload,
"rclone_config_ready": is_rclone_upload_available(),
"rclone_config_error": validate_rclone_config().get("error", ""),
"is_folder": is_folder,
"can_raw_gofile_upload": is_folder and bool(GOFILE_API_TOKEN),
"can_raw_pixeldrain_upload": is_folder and bool(PIXELDRAIN_API_KEY),
"can_raw_rclone_upload": is_folder,
"task_kind": "torrent",
"added_at": int(getattr(torrent, "added_on", 0) or 0),
}
def is_aria2_task(task_id: str) -> bool:
return str(task_id).startswith("aria2_")
def get_task_state_entry(state: dict, task_id: str) -> dict:
bucket_name = "aria2" if is_aria2_task(task_id) else "torrents"
return state.setdefault(bucket_name, {}).setdefault(task_id, {})
def update_task_entry(task_id: str, **fields) -> None:
def mutator(state: dict):
entry = get_task_state_entry(state, task_id)
entry.update(fields)
update_state(mutator)
def prepare_upload_source(source_path: Path, torrent_hash: str, provider_name: str) -> tuple[Path, bool]:
if source_path.is_file():
return source_path, False
archive_name = f"{source_path.name}.zip"
archive_path = UPLOAD_DIR / archive_name
if archive_path.exists():
archive_path = UPLOAD_DIR / f"{source_path.name}-{torrent_hash[:8]}.zip"
update_task_entry(
torrent_hash,
gofile_provider="Archiving",
gofile_status=f"Archiving folder for {provider_name}...",
status_message=f"Archiving folder for {provider_name}...",
gofile_progress=0,
gofile_speed="",
gofile_eta_seconds=0,
)
process = subprocess.Popen(
["7z", "a", "-tzip", "-mx=5", "-bsp1", str(archive_path), source_path.name],
cwd=str(source_path.parent),
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
bufsize=1,
)
error_lines: list[str] = []
monitor_thread = threading.Thread(
target=monitor_7z_progress,
args=(process.stdout, torrent_hash, provider_name, error_lines),
daemon=True,
)
monitor_thread.start()
update_task_entry(torrent_hash, gofile_pid=process.pid)
while True:
return_code = process.poll()
current_state = load_monitor_state()
current_entry = get_task_state_entry(current_state, torrent_hash)
if current_entry.get("gofile_cancel_requested"):
cancel_upload_process(process.pid)
if return_code is not None:
break
time.sleep(1)
monitor_thread.join(timeout=1)
if current_entry.get("gofile_cancel_requested") or process.returncode == -15:
archive_path.unlink(missing_ok=True)
raise GofileUploadCancelled(f"Archiving {provider_name} dibatalkan.")
if process.returncode != 0:
archive_path.unlink(missing_ok=True)
raise ValueError(" | ".join(error_lines[-3:]).strip() or "Gagal membuat arsip ZIP.")
update_task_entry(
torrent_hash,
gofile_provider=provider_name,
gofile_status=f"Archive ready, memulai upload ke {provider_name}...",
status_message="",
gofile_progress=100,
)
return archive_path, True
def list_folder_files(source_path: Path) -> list[tuple[Path, Path]]:
return [(file_path, file_path.relative_to(source_path)) for file_path in source_path.rglob("*") if file_path.is_file()]
def upload_folder_raw_gofile(torrent_hash: str, source_path: Path) -> tuple[str, str]:
if not GOFILE_API_TOKEN:
raise ValueError("Raw folder upload GoFile memerlukan GOFILE_API_TOKEN.")
file_entries = list_folder_files(source_path)
if not file_entries:
raise ValueError("Folder tidak berisi file yang bisa diupload.")
total_files = len(file_entries)
total_bytes = sum(file_path.stat().st_size for file_path, _ in file_entries)
uploaded_bytes = 0
folder_id = ""
folder_link = ""
folder_renamed = False
for index, (file_path, relative_path) in enumerate(file_entries, start=1):
current_state = load_monitor_state()
current_entry = get_task_state_entry(current_state, torrent_hash)
if current_entry.get("gofile_cancel_requested"):
raise GofileUploadCancelled("Upload GoFile dibatalkan.")
progress = int((uploaded_bytes / total_bytes) * 100) if total_bytes else 0
update_task_entry(
torrent_hash,
gofile_progress=progress,
gofile_speed="",
gofile_eta_seconds=0,
gofile_status=f"Uploading raw folder to GoFile... {index}/{total_files}",
status_message=f"Uploading raw folder to GoFile... {index}/{total_files}",
)
with file_path.open("rb") as handle:
files = {"file": (relative_path.name, handle)}
data: dict[str, str] = {}
headers = {"Authorization": f"Bearer {GOFILE_API_TOKEN}"}
if folder_id:
data["folderId"] = folder_id
response = requests.post(GOFILE_UPLOAD_URLS[0], files=files, data=data, headers=headers, timeout=3600)
response.raise_for_status()
payload = response.json()
data_payload = payload.get("data", payload)
folder_id = (
data_payload.get("parentFolder")
or data_payload.get("folderId")
or data_payload.get("parentFolderId")
or folder_id
)
folder_link = data_payload.get("downloadPage", folder_link)
if folder_id and not folder_renamed:
requests.put(
f"https://api.gofile.io/contents/{folder_id}/update",
json={"attribute": "name", "attributeValue": source_path.name},
headers={"Authorization": f"Bearer {GOFILE_API_TOKEN}"},
timeout=60,
).raise_for_status()
folder_renamed = True
uploaded_bytes += file_path.stat().st_size
progress = int((uploaded_bytes / total_bytes) * 100) if total_bytes else 100
update_task_entry(
torrent_hash,
gofile_progress=progress,
gofile_status=f"Uploading raw folder to GoFile... {index}/{total_files}",
status_message=f"Uploading raw folder to GoFile... {index}/{total_files}",
)
if not folder_link:
raise ValueError("GoFile tidak mengembalikan link folder.")
return folder_link, folder_id
def upload_folder_raw_pixeldrain(torrent_hash: str, source_path: Path) -> str:
file_entries = list_folder_files(source_path)
if not file_entries:
raise ValueError("Folder tidak berisi file yang bisa diupload.")
total_files = len(file_entries)
total_bytes = sum(file_path.stat().st_size for file_path, _ in file_entries)
uploaded_bytes = 0
uploaded_files: list[dict[str, str]] = []
for index, (file_path, relative_path) in enumerate(file_entries, start=1):
current_state = load_monitor_state()
current_entry = get_task_state_entry(current_state, torrent_hash)
if current_entry.get("gofile_cancel_requested"):
raise GofileUploadCancelled("Upload PixelDrain dibatalkan.")
progress = int((uploaded_bytes / total_bytes) * 100) if total_bytes else 0
update_task_entry(
torrent_hash,
gofile_progress=progress,
gofile_speed="",
gofile_eta_seconds=0,
gofile_status=f"Uploading raw folder to PixelDrain... {index}/{total_files}",
status_message=f"Uploading raw folder to PixelDrain... {index}/{total_files}",
)
with file_path.open("rb") as handle:
encoded_name = quote(relative_path.name, safe="")
response = requests.put(
f"{PIXELDRAIN_API_URL}/file/{encoded_name}",
data=handle,
auth=("", PIXELDRAIN_API_KEY),
timeout=3600,
)
response.raise_for_status()
payload = response.json()
file_id = payload.get("id")
if not file_id:
raise ValueError("Respons PixelDrain tidak mengandung file id.")
uploaded_files.append({"id": file_id, "description": relative_path.as_posix()})
uploaded_bytes += file_path.stat().st_size
progress = int((uploaded_bytes / total_bytes) * 100) if total_bytes else 100
update_task_entry(
torrent_hash,
gofile_progress=progress,
gofile_status=f"Uploading raw folder to PixelDrain... {index}/{total_files}",
status_message=f"Uploading raw folder to PixelDrain... {index}/{total_files}",
)
response = requests.post(
f"{PIXELDRAIN_API_URL}/list",
json={"title": source_path.name, "anonymous": False, "files": uploaded_files},
auth=("", PIXELDRAIN_API_KEY),
timeout=60,
)
response.raise_for_status()
payload = response.json()
list_id = payload.get("id")
if not list_id:
raise ValueError("Respons PixelDrain tidak mengandung list id.")
return f"https://pixeldrain.com/l/{list_id}"
def clear_gofile_runtime_fields(entry: dict) -> None:
entry["gofile_uploading"] = False
entry["gofile_progress"] = 0
entry["gofile_speed"] = ""
entry["gofile_eta_seconds"] = 0
entry["gofile_cancel_requested"] = False
entry["gofile_pid"] = 0
entry["gofile_endpoint"] = ""
entry["gofile_provider"] = ""
def clear_pre_upload_restore_fields(entry: dict) -> None:
entry.pop("pre_upload_state", None)
entry.pop("pre_upload_force_start", None)
def restore_torrent_state_after_remote_upload(torrent_hash: str) -> None:
if is_aria2_task(torrent_hash):
update_state(lambda current: clear_pre_upload_restore_fields(get_task_state_entry(current, torrent_hash)))
return
state = load_monitor_state()
entry = get_task_state_entry(state, torrent_hash)
previous_state = str(entry.get("pre_upload_state", "") or "")
previous_force_start = bool(entry.get("pre_upload_force_start", False))
if not previous_state and "pre_upload_force_start" not in entry:
return
try:
client = get_client()
torrents = client.torrents_info(torrent_hashes=torrent_hash)
if not torrents:
return
torrent = torrents[0]
progress = float(getattr(torrent, "progress", 0) or 0)
seeding_states = {"uploading", "stalledUP", "forcedUP", "checkingUP"}
if previous_state in PAUSED_STATES:
try:
client.torrents_set_force_start(enable=False, torrent_hashes=torrent_hash)
except qbittorrentapi.APIError:
pass
client.torrents_pause(torrent_hashes=torrent_hash)
else:
client.torrents_resume(torrent_hashes=torrent_hash)
if previous_force_start or previous_state in {"forcedDL", "forcedUP"}:
try:
client.torrents_set_force_start(enable=True, torrent_hashes=torrent_hash)
except qbittorrentapi.APIError:
pass
elif progress >= 1 and previous_state in seeding_states:
try:
client.torrents_reannounce(torrent_hashes=torrent_hash)
except qbittorrentapi.APIError:
pass
refreshed = client.torrents_info(torrent_hashes=torrent_hash)
current_state = getattr(refreshed[0], "state", "") if refreshed else ""
if current_state == "queuedUP":
try:
client.torrents_set_force_start(enable=True, torrent_hashes=torrent_hash)
except qbittorrentapi.APIError:
pass
except qbittorrentapi.APIError:
pass
finally:
update_state(lambda current: clear_pre_upload_restore_fields(get_task_state_entry(current, torrent_hash)))
def evaluate_torrent_health(client, torrents: list, state: dict) -> bool:
now = time.time()
torrent_state = state.setdefault("torrents", {})
active_hashes = {torrent.hash for torrent in torrents}
changed = False
for hash_value in list(torrent_state.keys()):
if hash_value not in active_hashes:
entry = torrent_state[hash_value]
if entry.get("gofile_uploading"):
continue
del torrent_state[hash_value]
changed = True
for torrent in torrents:
entry = torrent_state.setdefault(
torrent.hash,
{
"name": torrent.name,
"last_progress": float(getattr(torrent, "progress", 0) or 0),
"last_downloaded": int(getattr(torrent, "downloaded", 0) or 0),
"last_progress_at": now,
"status_message": "",
"gofile_progress": 0,
"gofile_uploading": False,
"gofile_speed": "",
"gofile_status": "",
"gofile_link": "",
"gofile_pid": 0,
"gofile_endpoint": "",
"gofile_provider": "",
},
)
entry["name"] = torrent.name
current_progress = float(getattr(torrent, "progress", 0) or 0)
current_downloaded = int(getattr(torrent, "downloaded", 0) or 0)
current_speed = int(getattr(torrent, "dlspeed", 0) or 0)
previous_progress = float(entry.get("last_progress", 0))
previous_downloaded = int(entry.get("last_downloaded", 0))
if current_downloaded > previous_downloaded or current_progress > previous_progress or current_speed > 0:
entry["last_progress"] = current_progress
entry["last_downloaded"] = current_downloaded
entry["last_progress_at"] = now
if entry.get("status_message") and not entry.get("gofile_uploading"):
entry["status_message"] = ""
changed = True
idle_for = now - float(entry.get("last_progress_at", now))
status_message = entry.get("status_message", "")
if entry.get("gofile_uploading"):
status_message = ""
elif torrent.state in FAILED_STATES:
status_message = "Torrent gagal diproses. Cek file torrent atau sumber tracker."
elif torrent.state in PAUSED_STATES:
status_message = ""
elif torrent.state in ACTIVE_DOWNLOAD_STATES and current_speed == 0:
if idle_for >= STUCK_TIMEOUT_SECONDS:
if torrent.num_seeds <= 0:
reason = f"{torrent.name} dibatalkan otomatis karena tidak ada seed selama {format_duration(idle_for)}."
else:
reason = f"{torrent.name} dibatalkan otomatis karena tidak ada progres selama {format_duration(idle_for)}."
client.torrents_delete(delete_files=False, torrent_hashes=torrent.hash)
add_event(state, "error", reason)
torrent_state.pop(torrent.hash, None)
changed = True
continue
remaining = max(0, STUCK_TIMEOUT_SECONDS - int(idle_for))
if torrent.num_seeds <= 0 and torrent.num_leechs <= 0:
status_message = f"Seed dan peer tidak ada. Auto cancel dalam {format_duration(remaining)}."
elif torrent.num_seeds <= 0:
status_message = f"Seed tidak tersedia. Menunggu sampai {format_duration(remaining)} sebelum auto cancel."
else:
status_message = f"Torrent belum bergerak selama {format_duration(idle_for)}. Auto cancel dalam {format_duration(remaining)}."
elif float(getattr(torrent, "progress", 0) or 0) >= 1:
status_message = ""
if entry.get("status_message") != status_message:
entry["status_message"] = status_message
changed = True
if entry.get("last_progress") != current_progress or entry.get("last_downloaded") != current_downloaded:
entry["last_progress"] = current_progress
entry["last_downloaded"] = current_downloaded
changed = True
return changed
def fetch_location_info(state: dict) -> dict:
cached = state.setdefault("system", {}).get("location", {})
now = int(time.time())
if cached and now - int(cached.get("fetched_at", 0)) < LOCATION_CACHE_SECONDS:
return cached
try:
response = requests.get(IP_LOCATION_API_URL, timeout=10)
response.raise_for_status()
data = response.json()
location = {
"ip": data.get("ip", "-"),
"city": data.get("city", "-"),
"region": data.get("region", "-"),
"country": data.get("country_name", data.get("country", "-")),
"org": data.get("org", "-"),
"timezone": data.get("timezone", "-"),
"fetched_at": now,
}
except requests.RequestException:
location = {
"ip": "-",
"city": "-",
"region": "-",
"country": "-",
"org": "unavailable",
"timezone": "-",
"fetched_at": now,
}
state.setdefault("system", {})["location"] = location
return location
def get_system_info() -> dict:
state = load_monitor_state()
cached = state.setdefault("system", {}).get("snapshot", {})
now = int(time.time())
if cached and now - int(cached.get("fetched_at", 0)) < SYSTEM_INFO_CACHE_SECONDS:
snapshot = cached
else:
disk = download_storage_usage()
memory = psutil.virtual_memory()
snapshot = {
"os": f"{platform.system()} {platform.release()}",
"cpu": platform.processor() or platform.machine() or "Unknown CPU",
"cpu_cores": psutil.cpu_count(logical=True) or 0,
"cpu_usage": f"{psutil.cpu_percent(interval=0.2):.0f}%",
"ram_total": format_size(memory.total),
"ram_used": format_size(memory.used),
"ram_percent": f"{memory.percent:.0f}%",
"storage_total": format_size(disk.total),
"storage_used": format_size(disk.used),
"storage_free": format_size(disk.free),
"storage_percent": f"{(disk.used / disk.total) * 100:.0f}%" if disk.total else "0%",
"hostname": platform.node() or "-",
"fetched_at": now,
}
state.setdefault("system", {})["snapshot"] = snapshot
save_monitor_state(state)
location = fetch_location_info(state)
save_monitor_state(state)
speedtest = state.get("speedtest", {"running": False})
return {
**snapshot,
"location": location,
"speedtest": speedtest,
}
def run_speedtest_background() -> None:
def set_speedtest_state(**fields):
def mutator(state: dict):
speedtest = state.setdefault("speedtest", {})
speedtest.update(fields)
update_state(mutator)
try:
set_speedtest_state(running=True, status="Running speedtest...", result={})
ping_samples = []
for _ in range(3):
start = time.perf_counter()
response = requests.get(CLOUDFLARE_DOWNLOAD_URL, params={"bytes": 0}, timeout=15)
response.raise_for_status()
ping_samples.append((time.perf_counter() - start) * 1000)
download_bytes = 25_000_000
start = time.perf_counter()
response = requests.get(CLOUDFLARE_DOWNLOAD_URL, params={"bytes": download_bytes}, timeout=120)
response.raise_for_status()
total_download = len(response.content)
elapsed = max(time.perf_counter() - start, 0.001)
download_bps = (total_download * 8) / elapsed
payload = os.urandom(10_000_000)
start = time.perf_counter()
response = requests.post(CLOUDFLARE_UPLOAD_URL, data=payload, timeout=120)
response.raise_for_status()
elapsed = max(time.perf_counter() - start, 0.001)
upload_bps = (len(payload) * 8) / elapsed
result = {
"download": format_mbps(download_bps),
"upload": format_mbps(upload_bps),
"ping": f"{sum(ping_samples) / len(ping_samples):.0f} ms",
"tested_at": int(time.time()),
}
set_speedtest_state(running=False, status="Speedtest selesai.", result=result)
except requests.RequestException as exc:
set_speedtest_state(running=False, status=f"Speedtest gagal: {exc}", result={})
def get_dashboard_data() -> tuple[list[dict], dict]:
client = get_client()
state = load_monitor_state()
raw_torrents = list(client.torrents_info(sort="added_on", reverse=True))
state_changed = evaluate_torrent_health(client, raw_torrents, state)
if state_changed:
save_monitor_state(state)
raw_torrents = list(client.torrents_info(sort="added_on", reverse=True))
version = client.app.version
torrent_items = [serialize_torrent(torrent, state.get("torrents", {}).get(torrent.hash)) for torrent in raw_torrents]
rclone_available = is_rclone_upload_available()
aria2_items = []
for task in state.get("aria2", {}).values():
item = aria2.serialize_task(task)
item["can_rclone_upload"] = bool(item.get("can_gofile_upload"))
item["rclone_config_ready"] = rclone_available
item["rclone_config_error"] = validate_rclone_config().get("error", "")
item["can_raw_rclone_upload"] = False
aria2_items.append(item)
torrents = sorted(torrent_items + aria2_items, key=lambda item: int(item.get("added_at", 0) or 0), reverse=True)
seeding_states = {"uploading", "stalledUP", "forcedUP", "pausedUP", "queuedUP", "checkingUP"}
aria2_active_count = sum(1 for item in state.get("aria2", {}).values() if item.get("state") == "downloading")
aria2_downloaded_bytes = sum(int(item.get("downloaded_bytes", 0) or 0) for item in state.get("aria2", {}).values())
stats = {
"connected": True,
"download_path": DOWNLOAD_PATH,
"version": version,
"torrent_count": len(torrents),
"downloading": sum(1 for item in raw_torrents if item.state in ACTIVE_DOWNLOAD_STATES) + aria2_active_count,
"total_seeds": sum(1 for item in raw_torrents if getattr(item, "state", "") in seeding_states),
"total_leechs": sum(1 for item in raw_torrents if getattr(item, "state", "") in ACTIVE_DOWNLOAD_STATES) + aria2_active_count,
"all_time_download": format_size(sum(int(getattr(item, "downloaded", 0) or 0) for item in raw_torrents) + aria2_downloaded_bytes),
"all_time_upload": format_size(sum(int(getattr(item, "uploaded", 0) or 0) for item in raw_torrents)),
}
system_info = get_system_info()
return torrents, {
"stats": stats,
"events": [serialize_event(event) for event in state.get("events", [])],
"system_info": system_info,
}
def action_response(message: str, ok: bool = True, status_code: int = 200, **extra):
payload = {"success": ok, "message": message}
payload.update(extra)
return jsonify(payload), status_code
def torrent_selection_response(payload: dict):
message = payload.get("message", "Torrent membutuhkan seleksi file.")
extra = {key: value for key, value in payload.items() if key != "message"}
return action_response(message, **extra)
def wants_json_response() -> bool:
accept = request.headers.get("Accept", "")
requested_with = request.headers.get("X-Requested-With", "")
return "application/json" in accept or requested_with == "XMLHttpRequest"
def parse_curl_progress_line(line: str, total_bytes: int) -> dict | None:
stripped = line.strip()
if not stripped or "%" in stripped or "Total" in stripped:
return None
parts = stripped.split()
if len(parts) < 2:
return None
try:
progress_percent_value = int(parts[0])
except ValueError:
return None
current_speed = parse_size_token(parts[-1]) or 0
uploaded_bytes = int((total_bytes * progress_percent_value) / 100) if total_bytes > 0 else 0
remaining_bytes = max(0, total_bytes - uploaded_bytes)
eta_seconds = int(remaining_bytes / current_speed) if current_speed > 0 else 0
return {
"progress": max(0, min(progress_percent_value, 100)),
"speed": current_speed,
"eta_seconds": eta_seconds,
}
def parse_7z_progress_line(line: str) -> int | None:
match = re.search(r"(\d{1,3})%", line)
if not match:
return None
return max(0, min(int(match.group(1)), 100))
def parse_rclone_progress_line(line: str, total_bytes: int) -> dict | None:
stripped = line.strip()
if not stripped:
return None
progress_match = re.search(r"\b(\d{1,3})%", stripped)
if not progress_match:
return None
speed = 0
speed_match = re.search(r"([\d.]+)\s*([KMGTPE]?i?B|Bytes)/s", stripped, re.IGNORECASE)
if speed_match:
value = float(speed_match.group(1))
unit = speed_match.group(2).lower()
multipliers = {
"b": 1,
"bytes": 1,
"kb": 1000,
"kib": 1024,
"mb": 1000**2,
"mib": 1024**2,
"gb": 1000**3,
"gib": 1024**3,
"tb": 1000**4,
"tib": 1024**4,
}
speed = int(value * multipliers.get(unit, 1))
progress = max(0, min(int(progress_match.group(1)), 100))
uploaded_bytes = int((total_bytes * progress) / 100) if total_bytes > 0 else 0
remaining_bytes = max(0, total_bytes - uploaded_bytes)
eta_seconds = int(remaining_bytes / speed) if speed > 0 else 0
return {"progress": progress, "speed": speed, "eta_seconds": eta_seconds}
def monitor_rclone_progress(output_pipe, torrent_hash: str, total_bytes: int, remote_label: str, error_lines: list[str]) -> None:
last_progress = -1
try:
for line in output_pipe:
progress = parse_rclone_progress_line(line, total_bytes)
if progress:
if progress["progress"] != last_progress:
last_progress = progress["progress"]
speed_text = format_speed(progress["speed"]) if progress["speed"] else ""
update_state(
lambda state: get_task_state_entry(state, torrent_hash).update(
{
"gofile_progress": progress["progress"],
"gofile_speed": speed_text,
"gofile_eta_seconds": progress["eta_seconds"],
"gofile_status": f"Sedang upload ke rclone remote {remote_label}...",
"status_message": "",
}
)
)
continue
stripped = line.strip()
if stripped and not any(token in stripped.lower() for token in ["transferred:", "elapsed time:", "checks:"]):
error_lines.append(stripped)
finally:
try:
output_pipe.close()
except OSError:
pass
def monitor_7z_progress(stdout_pipe, torrent_hash: str, provider_name: str, error_lines: list[str]) -> None:
buffer = ""
last_progress = -1
try:
while True:
chunk = stdout_pipe.read(1)
if chunk == "":
break
buffer += chunk
progress = parse_7z_progress_line(buffer)
if progress is not None and progress != last_progress:
last_progress = progress
update_state(
lambda state: get_task_state_entry(state, torrent_hash).update(
{
"gofile_provider": "Archiving",
"gofile_progress": progress,
"gofile_speed": "",
"gofile_eta_seconds": 0,
"gofile_status": f"Archiving folder for {provider_name}... {progress}%",
"status_message": f"Archiving folder for {provider_name}... {progress}%",
}
)
)
if chunk in {"\r", "\n"}:
if buffer.strip() and parse_7z_progress_line(buffer) is None:
error_lines.append(buffer.strip())
buffer = ""
continue
if len(buffer) > 256:
# Keep only the latest tail so progress repaints from 7z remain parseable.
buffer = buffer[-256:]
finally:
if buffer.strip() and parse_7z_progress_line(buffer) is None:
error_lines.append(buffer.strip())
try:
stdout_pipe.close()
except OSError:
pass
def monitor_curl_progress(stderr_pipe, torrent_hash: str, total_bytes: int, upload_label: str, error_lines: list[str]) -> None:
buffer = ""
try:
while True:
chunk = stderr_pipe.read(1)
if chunk == "":
break
if chunk in {"\r", "\n"}:
progress = parse_curl_progress_line(buffer, total_bytes)
if progress:
speed_text = format_speed(progress["speed"])
update_state(
lambda state: get_task_state_entry(state, torrent_hash).update(
{
"gofile_progress": progress["progress"],
"gofile_speed": speed_text,
"gofile_eta_seconds": progress["eta_seconds"],
"gofile_status": f"Sedang upload ke {state.setdefault('torrents', {}).setdefault(torrent_hash, {}).get('gofile_provider', 'GoFile')} via {upload_label}...",
"status_message": "",
}
)
)
elif buffer.strip():
error_lines.append(buffer.strip())
buffer = ""
continue
buffer += chunk
finally:
if buffer.strip():
error_lines.append(buffer.strip())
try:
stderr_pipe.close()
except OSError:
pass
def gofile_upload_attempt(
upload_url: str,
torrent_hash: str,
file_path: Path,
started_at: float,
) -> dict:
response_path = UPLOAD_DIR / f"gofile-{torrent_hash}.json"
command = [
"curl",
"--show-error",
"--location",
"--globoff",
"--ipv4",
"--retry",
"2",
"--retry-delay",
"2",
"--retry-all-errors",
"--connect-timeout",
"15",
"--speed-time",
"60",
"--speed-limit",
"10240",
"--max-time",
"0",
"--output",
str(response_path),
"--write-out",
"%{http_code}",
]
if GOFILE_API_TOKEN:
command.extend(["-H", f"Authorization: Bearer {GOFILE_API_TOKEN}"])
command.extend(["-F", f'file=@"{file_path}"', upload_url])
process = subprocess.Popen(
command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
bufsize=1,
)
total_bytes = file_path.stat().st_size
upload_label = gofile_endpoint_label(upload_url)
error_lines: list[str] = []
monitor_thread = threading.Thread(
target=monitor_curl_progress,
args=(process.stderr, torrent_hash, total_bytes, upload_label, error_lines),
daemon=True,
)
monitor_thread.start()
update_state(
lambda state: get_task_state_entry(state, torrent_hash).update(
{
"gofile_uploading": True,
"gofile_pid": process.pid,
"gofile_endpoint": upload_label,
"gofile_provider": "GoFile",
"gofile_status": f"Sedang upload ke GoFile via {upload_label}...",
"status_message": "",
}
)
)
while True:
return_code = process.poll()
current_state = load_monitor_state()
current_entry = get_task_state_entry(current_state, torrent_hash)
if current_entry.get("gofile_cancel_requested"):
cancel_upload_process(process.pid)
if return_code is not None:
break
elapsed = max(int(time.time() - started_at), 1)
update_state(
lambda state: get_task_state_entry(state, torrent_hash).update(
{
"gofile_uploading": True,
"gofile_pid": process.pid,
"gofile_endpoint": upload_label,
"gofile_provider": "GoFile",
"gofile_status": f"Sedang upload ke GoFile via {upload_label}...",
"status_message": "",
}
)
)
time.sleep(1)
stdout = process.stdout.read() if process.stdout else ""
monitor_thread.join(timeout=1)
if current_entry.get("gofile_cancel_requested") or process.returncode == -15:
raise GofileUploadCancelled("Upload GoFile dibatalkan.")
if process.returncode != 0:
error_detail = " | ".join(error_lines[-3:]).strip() or stdout.strip() or f"curl exited with code {process.returncode}"
raise ValueError(error_detail)
http_code = int((stdout or "0").strip() or "0")
if http_code >= 400 or http_code == 0:
error_body = response_path.read_text(encoding="utf-8", errors="replace") if response_path.exists() else ""
raise ValueError(f"HTTP {http_code}: {error_body[:500]}".strip())
payload = json.loads(response_path.read_text(encoding="utf-8"))
return payload
def pixeldrain_upload_attempt(torrent_hash: str, file_path: Path, started_at: float) -> dict:
response_path = UPLOAD_DIR / f"pixeldrain-{torrent_hash}.json"
encoded_name = quote(file_path.name, safe="")
upload_url = f"{PIXELDRAIN_API_URL}/file/{encoded_name}"
command = [
"curl",
"--show-error",
"--location",
"--globoff",
"--ipv4",
"--retry",
"2",
"--retry-delay",
"2",
"--retry-all-errors",
"--connect-timeout",
"15",
"--speed-time",
"60",
"--speed-limit",
"10240",
"--max-time",
"0",
"--url",
upload_url,
"--upload-file",
str(file_path),
"--user",
f":{PIXELDRAIN_API_KEY}",
"--output",
str(response_path),
"--write-out",
"%{http_code}",
]
process = subprocess.Popen(
command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
bufsize=1,
)
total_bytes = file_path.stat().st_size
upload_label = "pixeldrain"
error_lines: list[str] = []
monitor_thread = threading.Thread(
target=monitor_curl_progress,
args=(process.stderr, torrent_hash, total_bytes, upload_label, error_lines),
daemon=True,
)
monitor_thread.start()
update_state(
lambda state: get_task_state_entry(state, torrent_hash).update(
{
"gofile_uploading": True,
"gofile_pid": process.pid,
"gofile_endpoint": upload_label,
"gofile_provider": "PixelDrain",
"gofile_status": "Sedang upload ke PixelDrain...",
"status_message": "",
}
)
)
while True:
return_code = process.poll()
current_state = load_monitor_state()
current_entry = get_task_state_entry(current_state, torrent_hash)
if current_entry.get("gofile_cancel_requested"):
cancel_upload_process(process.pid)
if return_code is not None:
break
update_state(
lambda state: get_task_state_entry(state, torrent_hash).update(
{
"gofile_uploading": True,
"gofile_pid": process.pid,
"gofile_endpoint": upload_label,
"gofile_provider": "PixelDrain",
"gofile_status": "Sedang upload ke PixelDrain...",
"status_message": "",
}
)
)
time.sleep(1)
stdout = process.stdout.read() if process.stdout else ""
monitor_thread.join(timeout=1)
if current_entry.get("gofile_cancel_requested") or process.returncode == -15:
raise GofileUploadCancelled("Upload PixelDrain dibatalkan.")
if process.returncode != 0:
error_detail = " | ".join(error_lines[-3:]).strip() or stdout.strip() or f"curl exited with code {process.returncode}"
raise ValueError(error_detail)
http_code = int((stdout or "0").strip() or "0")
if http_code >= 400 or http_code == 0:
error_body = response_path.read_text(encoding="utf-8", errors="replace") if response_path.exists() else ""
raise ValueError(f"HTTP {http_code}: {error_body[:500]}".strip())
payload = json.loads(response_path.read_text(encoding="utf-8"))
return payload
def rclone_link(config_path: Path, destination_spec: str) -> str:
process = subprocess.run(
["rclone", "--config", str(config_path), "link", destination_spec],
capture_output=True,
text=True,
timeout=60,
check=False,
)
if process.returncode != 0:
return ""
for line in process.stdout.splitlines():
candidate = line.strip()
if candidate.startswith(("http://", "https://")):
return candidate
return ""
def rclone_upload_attempt(
torrent_hash: str,
source_path: Path,
destination_spec: str,
config_path: Path,
remote_label: str,
) -> str:
command = [
"rclone",
"--config",
str(config_path),
"--stats",
"1s",
"--stats-one-line",
"--progress",
]
if source_path.is_dir():
command.extend(["copy", str(source_path), destination_spec])
else:
command.extend(["copyto", str(source_path), destination_spec])
process = subprocess.Popen(
command,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
bufsize=1,
)
total_bytes = path_total_size(source_path)
error_lines: list[str] = []
monitor_thread = threading.Thread(
target=monitor_rclone_progress,
args=(process.stdout, torrent_hash, total_bytes, remote_label, error_lines),
daemon=True,
)
monitor_thread.start()
update_state(
lambda state: get_task_state_entry(state, torrent_hash).update(
{
"gofile_uploading": True,
"gofile_pid": process.pid,
"gofile_endpoint": remote_label,
"gofile_provider": "rclone",
"gofile_status": f"Sedang upload ke rclone remote {remote_label}...",
"status_message": "",
}
)
)
while True:
return_code = process.poll()
current_state = load_monitor_state()
current_entry = get_task_state_entry(current_state, torrent_hash)
if current_entry.get("gofile_cancel_requested"):
cancel_upload_process(process.pid)
if return_code is not None:
break
update_state(
lambda state: get_task_state_entry(state, torrent_hash).update(
{
"gofile_uploading": True,
"gofile_pid": process.pid,
"gofile_endpoint": remote_label,
"gofile_provider": "rclone",
"gofile_status": f"Sedang upload ke rclone remote {remote_label}...",
"status_message": "",
}
)
)
time.sleep(1)
monitor_thread.join(timeout=1)
if current_entry.get("gofile_cancel_requested") or process.returncode == -15:
raise GofileUploadCancelled("Upload rclone dibatalkan.")
if process.returncode != 0:
error_detail = " | ".join(error_lines[-4:]).strip() or f"rclone exited with code {process.returncode}"
raise ValueError(error_detail)
update_task_entry(torrent_hash, gofile_progress=100, gofile_speed="", gofile_eta_seconds=0)
return rclone_link(config_path, destination_spec)
def start_gofile_upload_background(torrent_hash: str, torrent_name: str, file_path: Path, mode: str = "zip") -> None:
def worker():
upload_path = file_path
cleanup_upload_path = False
try:
if file_path.is_dir() and mode == "raw":
folder_link, _folder_id = upload_folder_raw_gofile(torrent_hash, file_path)
def success_raw_mutator(state: dict):
entry = get_task_state_entry(state, torrent_hash)
clear_gofile_runtime_fields(entry)
entry["gofile_link"] = folder_link
entry["gofile_provider"] = "GoFile"
entry["gofile_status"] = f"Upload raw folder GoFile berhasil: {folder_link}"
entry["status_message"] = ""
update_state(success_raw_mutator)
restore_torrent_state_after_remote_upload(torrent_hash)
return
upload_path, cleanup_upload_path = prepare_upload_source(file_path, torrent_hash, "GoFile")
started_at = time.time()
payload = None
last_error = None
for upload_url in ranked_gofile_upload_urls():
try:
payload = gofile_upload_attempt(upload_url, torrent_hash, upload_path, started_at)
break
except GofileUploadCancelled:
raise
except ValueError as exc:
last_error = f"{upload_url}: {exc}"
update_state(
lambda state: get_task_state_entry(state, torrent_hash).update(
{
"gofile_uploading": True,
"gofile_provider": "GoFile",
"gofile_status": f"Endpoint gagal, mencoba server lain: {upload_url}",
"status_message": f"Endpoint gagal, mencoba server lain: {upload_url}",
}
)
)
if payload is None:
raise ValueError(last_error or "Semua endpoint GoFile gagal.")
data = payload.get("data", {})
download_page = data.get("downloadPage")
if not download_page:
raise ValueError("Respons GoFile tidak mengandung downloadPage.")
def success_mutator(state: dict):
entry = get_task_state_entry(state, torrent_hash)
clear_gofile_runtime_fields(entry)
entry["gofile_link"] = download_page
entry["gofile_provider"] = "GoFile"
entry["gofile_status"] = f"Upload GoFile berhasil: {download_page}"
entry["status_message"] = ""
update_state(success_mutator)
restore_torrent_state_after_remote_upload(torrent_hash)
except GofileUploadCancelled:
def cancel_mutator(state: dict):
entry = get_task_state_entry(state, torrent_hash)
clear_gofile_runtime_fields(entry)
entry["gofile_provider"] = "GoFile"
entry["gofile_status"] = "Upload GoFile dibatalkan."
entry["status_message"] = ""
add_event(state, "warning", f"Upload GoFile dibatalkan untuk {torrent_name}.")
update_state(cancel_mutator)
restore_torrent_state_after_remote_upload(torrent_hash)
except (ValueError, requests.RequestException) as exc:
def error_mutator(state: dict):
entry = get_task_state_entry(state, torrent_hash)
clear_gofile_runtime_fields(entry)
entry["gofile_provider"] = "GoFile"
entry["gofile_status"] = f"Upload GoFile gagal: {exc}"
entry["status_message"] = f"Upload GoFile gagal: {exc}"
add_event(state, "error", f"Upload GoFile gagal untuk {torrent_name}: {exc}")
update_state(error_mutator)
restore_torrent_state_after_remote_upload(torrent_hash)
finally:
(UPLOAD_DIR / f"gofile-{torrent_hash}.json").unlink(missing_ok=True)
if cleanup_upload_path:
upload_path.unlink(missing_ok=True)
thread = threading.Thread(target=worker, daemon=True)
thread.start()
def start_pixeldrain_upload_background(torrent_hash: str, torrent_name: str, file_path: Path, mode: str = "zip") -> None:
def worker():
upload_path = file_path
cleanup_upload_path = False
try:
if file_path.is_dir() and mode == "raw":
download_page = upload_folder_raw_pixeldrain(torrent_hash, file_path)
def success_raw_mutator(state: dict):
entry = get_task_state_entry(state, torrent_hash)
clear_gofile_runtime_fields(entry)
entry["gofile_link"] = download_page
entry["gofile_provider"] = "PixelDrain"
entry["gofile_status"] = f"Upload raw folder PixelDrain berhasil: {download_page}"
entry["status_message"] = ""
update_state(success_raw_mutator)
restore_torrent_state_after_remote_upload(torrent_hash)
return
upload_path, cleanup_upload_path = prepare_upload_source(file_path, torrent_hash, "PixelDrain")
payload = pixeldrain_upload_attempt(torrent_hash, upload_path, time.time())
file_id = payload.get("id")
if not file_id:
raise ValueError("Respons PixelDrain tidak mengandung file id.")
download_page = f"https://pixeldrain.com/u/{file_id}"
def success_mutator(state: dict):
entry = get_task_state_entry(state, torrent_hash)
clear_gofile_runtime_fields(entry)
entry["gofile_link"] = download_page
entry["gofile_provider"] = "PixelDrain"
entry["gofile_status"] = f"Upload PixelDrain berhasil: {download_page}"
entry["status_message"] = ""
update_state(success_mutator)
restore_torrent_state_after_remote_upload(torrent_hash)
except GofileUploadCancelled:
def cancel_mutator(state: dict):
entry = get_task_state_entry(state, torrent_hash)
clear_gofile_runtime_fields(entry)
entry["gofile_provider"] = "PixelDrain"
entry["gofile_status"] = "Upload PixelDrain dibatalkan."
entry["status_message"] = ""
add_event(state, "warning", f"Upload PixelDrain dibatalkan untuk {torrent_name}.")
update_state(cancel_mutator)
restore_torrent_state_after_remote_upload(torrent_hash)
except (ValueError, requests.RequestException) as exc:
def error_mutator(state: dict):
entry = get_task_state_entry(state, torrent_hash)
clear_gofile_runtime_fields(entry)
entry["gofile_provider"] = "PixelDrain"
entry["gofile_status"] = f"Upload PixelDrain gagal: {exc}"
entry["status_message"] = f"Upload PixelDrain gagal: {exc}"
add_event(state, "error", f"Upload PixelDrain gagal untuk {torrent_name}: {exc}")
update_state(error_mutator)
restore_torrent_state_after_remote_upload(torrent_hash)
finally:
(UPLOAD_DIR / f"pixeldrain-{torrent_hash}.json").unlink(missing_ok=True)
if cleanup_upload_path:
upload_path.unlink(missing_ok=True)
thread = threading.Thread(target=worker, daemon=True)
thread.start()
def start_rclone_upload_background(
torrent_hash: str,
torrent_name: str,
file_path: Path,
mode: str = "zip",
remote_name: str = "",
) -> None:
def worker():
upload_path = file_path
cleanup_upload_path = False
destination_spec = ""
try:
config = validate_rclone_config(force_refresh=True)
if config.get("error") or not config.get("remotes"):
raise ValueError(str(config.get("error") or "rclone.conf tidak berisi remote aktif."))
config_path = Path(str(config["path"]))
remote = requested_rclone_remote(config, remote_name)
remote_label = remote or "rclone"
if file_path.is_dir() and mode == "raw":
destination_spec = rclone_destination_spec(remote, safe_filename(torrent_name or file_path.name))
download_link = rclone_upload_attempt(torrent_hash, file_path, destination_spec, config_path, remote_label)
else:
upload_path, cleanup_upload_path = prepare_upload_source(file_path, torrent_hash, "rclone")
destination_spec = rclone_destination_spec(remote, upload_path.name)
download_link = rclone_upload_attempt(torrent_hash, upload_path, destination_spec, config_path, remote_label)
def success_mutator(state: dict):
entry = get_task_state_entry(state, torrent_hash)
clear_gofile_runtime_fields(entry)
entry["gofile_link"] = download_link
entry["gofile_provider"] = "rclone"
if download_link:
entry["gofile_status"] = f"Upload rclone berhasil: {download_link}"
else:
entry["gofile_status"] = f"Upload rclone berhasil ke {destination_spec}. Public link tidak tersedia dari remote ini."
entry["status_message"] = ""
update_state(success_mutator)
restore_torrent_state_after_remote_upload(torrent_hash)
except GofileUploadCancelled:
def cancel_mutator(state: dict):
entry = get_task_state_entry(state, torrent_hash)
clear_gofile_runtime_fields(entry)
entry["gofile_provider"] = "rclone"
entry["gofile_status"] = "Upload rclone dibatalkan."
entry["status_message"] = ""
add_event(state, "warning", f"Upload rclone dibatalkan untuk {torrent_name}.")
update_state(cancel_mutator)
restore_torrent_state_after_remote_upload(torrent_hash)
except (ValueError, requests.RequestException, OSError) as exc:
def error_mutator(state: dict):
entry = get_task_state_entry(state, torrent_hash)
clear_gofile_runtime_fields(entry)
entry["gofile_provider"] = "rclone"
entry["gofile_status"] = f"Upload rclone gagal: {exc}"
entry["status_message"] = f"Upload rclone gagal: {exc}"
add_event(state, "error", f"Upload rclone gagal untuk {torrent_name}: {exc}")
update_state(error_mutator)
restore_torrent_state_after_remote_upload(torrent_hash)
finally:
if cleanup_upload_path:
upload_path.unlink(missing_ok=True)
thread = threading.Thread(target=worker, daemon=True)
thread.start()
@app.route("/", methods=["GET"])
def index():
try:
torrents, payload = get_dashboard_data()
stats = payload["stats"]
events = payload["events"]
system_info = payload["system_info"]
except qbittorrentapi.APIConnectionError as exc:
torrents = []
events = []
stats = {
"connected": False,
"download_path": "-",
"version": "unreachable",
"torrent_count": 0,
"downloading": 0,
}
system_info = get_system_info()
flash(f"Gagal terhubung ke qBittorrent: {exc}", "error")
except qbittorrentapi.LoginFailed as exc:
torrents = []
events = []
stats = {
"connected": False,
"download_path": "-",
"version": "login failed",
"torrent_count": 0,
"downloading": 0,
}
system_info = get_system_info()
flash(f"Login qBittorrent gagal: {exc}", "error")
return render_template("index.html", torrents=torrents, stats=stats, events=events, system_info=system_info)
@app.route("/healthz", methods=["GET"])
def healthz():
return jsonify({"status": "ok"})
@app.route("/api/torrents", methods=["GET"])
def torrents_api():
try:
torrents, payload = get_dashboard_data()
return jsonify(
{
"success": True,
"stats": payload["stats"],
"events": payload["events"],
"torrents": torrents,
}
)
except (qbittorrentapi.APIConnectionError, qbittorrentapi.LoginFailed, qbittorrentapi.APIError) as exc:
return jsonify({"success": False, "error": str(exc) or "Gagal mengambil data torrent."}), 503
@app.route("/api/torrents/<torrent_hash>/files", methods=["GET"])
def torrent_files_api(torrent_hash: str):
try:
files = qbt_torrent_files(torrent_hash)
if not files:
return jsonify(
{
"success": True,
"metadata_ready": False,
"selection_required": False,
"selection_pending": True,
"torrent_hash": torrent_hash,
"files": [],
"message": "Metadata torrent masih diambil. Menunggu daftar file...",
}
)
payload = build_file_selection_payload(torrent_hash, files)
clear_torrent_status_message(torrent_hash)
payload["success"] = True
payload["metadata_ready"] = True
return jsonify(payload)
except InsufficientStorageError as exc:
return action_response(str(exc), ok=False, status_code=507)
except (QBittorrentWebAPIError, requests.RequestException, ValueError) as exc:
return action_response(f"Gagal mengambil daftar file torrent: {exc}", ok=False, status_code=502)
@app.route("/api/torrents/<torrent_hash>/files/selection", methods=["POST"])
def apply_torrent_file_selection(torrent_hash: str):
try:
files = qbt_torrent_files(torrent_hash)
if not files:
return action_response("Metadata torrent belum siap. Coba lagi sebentar.", ok=False, status_code=409)
if len(files) <= 1:
required_bytes = sum(int(file_entry.get("size", 0) or 0) for file_entry in files)
ensure_storage_available(required_bytes)
qbt_resume_torrent(torrent_hash)
clear_torrent_status_message(torrent_hash)
return action_response("Torrent tidak memerlukan seleksi file.")
payload = request.get_json(silent=True) or {}
raw_selected_ids = payload.get("selected_file_ids", [])
if not isinstance(raw_selected_ids, list):
return action_response("Format pilihan file tidak valid.", ok=False, status_code=400)
selected_ids = {int(file_id) for file_id in raw_selected_ids}
all_ids = {torrent_file_index(file_entry, index) for index, file_entry in enumerate(files)}
if not selected_ids:
return action_response("Pilih minimal satu file untuk didownload.", ok=False, status_code=400)
if not selected_ids.issubset(all_ids):
return action_response("Pilihan file mengandung ID yang tidak valid.", ok=False, status_code=400)
selected_size = sum(
int(file_entry.get("size", 0) or 0)
for index, file_entry in enumerate(files)
if torrent_file_index(file_entry, index) in selected_ids
)
ensure_storage_available(selected_size)
skipped_ids = sorted(all_ids - selected_ids)
qbt_set_file_priority(torrent_hash, sorted(skipped_ids), 0)
qbt_set_file_priority(torrent_hash, sorted(selected_ids), 1)
qbt_resume_torrent(torrent_hash)
clear_torrent_status_message(torrent_hash)
return action_response("Seleksi file diterapkan dan torrent dimulai.")
except InsufficientStorageError as exc:
return action_response(str(exc), ok=False, status_code=507)
except (QBittorrentWebAPIError, requests.RequestException, ValueError) as exc:
return action_response(f"Gagal menerapkan seleksi file: {exc}", ok=False, status_code=502)
@app.route("/api/system", methods=["GET"])
def system_api():
return jsonify({"success": True, "system": get_system_info()})
@app.route("/api/system/speedtest", methods=["POST"])
def system_speedtest():
state = load_monitor_state()
if state.get("speedtest", {}).get("running"):
return action_response("Speedtest sedang berjalan.", ok=False, status_code=409)
update_state(lambda current: current.setdefault("speedtest", {}).update({"running": True, "status": "Memulai speedtest...", "result": {}}))
threading.Thread(target=run_speedtest_background, daemon=True).start()
return action_response("Speedtest dimulai.")
@app.route("/api/rclone/config", methods=["GET", "POST"])
def rclone_config_api():
if request.method == "GET":
return action_response("Status rclone config.", rclone=rclone_config_summary(force_refresh=True))
payload = request.get_json(silent=True) or {}
raw_url = str(payload.get("config_url", "") or "").strip()
if not raw_url:
return action_response("Raw URL rclone.conf wajib diisi.", ok=False, status_code=400)
parsed = urlparse(raw_url)
if parsed.scheme.lower() not in {"http", "https"}:
return action_response("Raw URL harus memakai http atau https.", ok=False, status_code=400)
set_runtime_rclone_config_url(raw_url)
summary = rclone_config_summary(force_refresh=True)
if not summary["available"]:
return action_response(f"rclone.conf belum valid: {summary['error']}", ok=False, status_code=400, rclone=summary)
return action_response(
f"rclone.conf valid. Remote terdeteksi: {', '.join(summary['remotes'])}",
rclone=summary,
)
@app.route("/api/torrents/<torrent_hash>/pause", methods=["POST"])
def pause_torrent(torrent_hash: str):
if is_aria2_task(torrent_hash):
ok, message = aria2.pause_task(torrent_hash, STATE_FILE, STATE_LOCK)
return action_response(message, ok=ok, status_code=200 if ok else 400)
try:
client = get_client()
try:
client.torrents_set_force_start(enable=False, torrent_hashes=torrent_hash)
except qbittorrentapi.APIError:
pass
qbt_pause_torrent(torrent_hash)
state = load_monitor_state()
entry = state.setdefault("torrents", {}).setdefault(torrent_hash, {})
entry["status_message"] = ""
save_monitor_state(state)
return action_response("Torrent dijeda.")
except qbittorrentapi.APIError as exc:
return action_response(f"Gagal pause torrent: {exc}", ok=False, status_code=400)
@app.route("/api/torrents/<torrent_hash>/resume", methods=["POST"])
def resume_torrent(torrent_hash: str):
if is_aria2_task(torrent_hash):
ok, message = aria2.resume_task(torrent_hash, STATE_FILE, STATE_LOCK)
return action_response(message, ok=ok, status_code=200 if ok else 400)
try:
client = get_client()
qbt_resume_torrent(torrent_hash)
torrents = client.torrents_info(torrent_hashes=torrent_hash)
if torrents and float(getattr(torrents[0], "progress", 0) or 0) >= 1:
try:
client.torrents_set_force_start(enable=True, torrent_hashes=torrent_hash)
except qbittorrentapi.APIError:
pass
try:
client.torrents_reannounce(torrent_hashes=torrent_hash)
except qbittorrentapi.APIError:
pass
state = load_monitor_state()
entry = state.setdefault("torrents", {}).setdefault(torrent_hash, {})
entry["last_progress_at"] = time.time()
entry["status_message"] = ""
save_monitor_state(state)
return action_response("Torrent dilanjutkan.")
except qbittorrentapi.APIError as exc:
return action_response(f"Gagal melanjutkan torrent: {exc}", ok=False, status_code=400)
@app.route("/api/torrents/<torrent_hash>", methods=["DELETE"])
def delete_torrent(torrent_hash: str):
delete_files = request.args.get("with_files", "false").lower() == "true"
if torrent_hash.startswith("aria2_"):
ok, message = aria2.delete_task(torrent_hash, STATE_FILE, STATE_LOCK, delete_files)
if ok:
return action_response(message)
return action_response(message, ok=False, status_code=404)
try:
client = get_client()
client.torrents_delete(delete_files=delete_files, torrent_hashes=torrent_hash)
state = load_monitor_state()
state.setdefault("torrents", {}).pop(torrent_hash, None)
if delete_files:
message = "Torrent dan file hasil download dihapus."
else:
message = "Torrent dihapus dari daftar."
save_monitor_state(state)
return action_response(message)
except qbittorrentapi.APIError as exc:
return action_response(f"Gagal menghapus torrent: {exc}", ok=False, status_code=400)
@app.route("/add-aria2", methods=["POST"])
def add_aria2():
is_valid_url, url_or_error = aria2.validate_download_url(request.form.get("aria2_link", ""))
if not is_valid_url:
if wants_json_response():
return action_response(url_or_error, ok=False, status_code=400)
flash(url_or_error, "error")
return redirect(url_for("index"))
if shutil.which("aria2c") is None:
message = "aria2c belum tersedia di environment aplikasi."
if wants_json_response():
return action_response(message, ok=False, status_code=503)
flash(message, "error")
return redirect(url_for("index"))
try:
_task_id, filename = aria2.start_download(url_or_error, DOWNLOAD_PATH, STATE_FILE, STATE_LOCK)
if wants_json_response():
return action_response(f"Aria2 download dimulai: {filename}")
flash(f"Aria2 download dimulai: {filename}", "success")
except (OSError, requests.RequestException) as exc:
if wants_json_response():
return action_response(f"Gagal memulai Aria2 download: {exc}", ok=False, status_code=502)
flash(f"Gagal memulai Aria2 download: {exc}", "error")
return redirect(url_for("index"))
@app.route("/api/torrents/<torrent_hash>/upload-gofile", methods=["POST"])
def upload_torrent_to_gofile(torrent_hash: str):
if is_aria2_task(torrent_hash):
state = load_monitor_state()
entry = state.get("aria2", {}).get(torrent_hash)
if not entry:
return action_response("Tugas Aria2 tidak ditemukan.", ok=False, status_code=404)
if entry.get("gofile_uploading"):
return action_response("Upload GoFile masih berjalan.", ok=False, status_code=409)
file_path = Path(entry.get("file_path", "") or "")
if not file_path.exists():
return action_response("File Aria2 tidak ditemukan di storage.", ok=False, status_code=404)
entry["gofile_uploading"] = True
entry["gofile_progress"] = 0
entry["gofile_speed"] = ""
entry["gofile_eta_seconds"] = 0
entry["gofile_cancel_requested"] = False
entry["gofile_pid"] = 0
entry["gofile_endpoint"] = ""
entry["gofile_provider"] = "GoFile"
entry["gofile_status"] = "Sedang upload ke GoFile..."
entry["status_message"] = ""
save_monitor_state(state)
start_gofile_upload_background(torrent_hash, entry.get("name", file_path.name), file_path, mode="zip")
return action_response("Upload Aria2 ke GoFile dimulai.")
try:
client = get_client()
torrents = client.torrents_info(torrent_hashes=torrent_hash)
if not torrents:
return action_response("Torrent tidak ditemukan.", ok=False, status_code=404)
torrent = torrents[0]
mode = request.args.get("mode", "zip").lower()
progress = float(getattr(torrent, "progress", 0) or 0)
if progress < 1:
return action_response("Upload ke GoFile hanya tersedia setelah download selesai.", ok=False, status_code=400)
content_path = Path(getattr(torrent, "content_path", "") or "")
if not content_path.exists():
return action_response("File hasil download tidak ditemukan di storage.", ok=False, status_code=404)
if mode not in {"zip", "raw"}:
return action_response("Mode upload tidak valid.", ok=False, status_code=400)
if mode == "raw" and content_path.is_dir() and not GOFILE_API_TOKEN:
return action_response("Raw folder upload GoFile memerlukan GOFILE_API_TOKEN.", ok=False, status_code=400)
state = load_monitor_state()
entry = get_task_state_entry(state, torrent_hash)
if entry.get("gofile_uploading"):
return action_response("Upload GoFile masih berjalan.", ok=False, status_code=409)
entry["gofile_uploading"] = True
entry["gofile_progress"] = 0
entry["gofile_speed"] = ""
entry["gofile_eta_seconds"] = 0
entry["gofile_cancel_requested"] = False
entry["gofile_pid"] = 0
entry["gofile_endpoint"] = ""
entry["gofile_provider"] = "GoFile"
entry["gofile_status"] = "Sedang upload ke GoFile..."
entry["pre_upload_state"] = getattr(torrent, "state", "") or ""
entry["pre_upload_force_start"] = bool(getattr(torrent, "force_start", False))
entry["status_message"] = ""
save_monitor_state(state)
start_gofile_upload_background(torrent_hash, torrent.name, content_path, mode=mode)
return action_response("Upload ke GoFile dimulai." if mode == "zip" else "Upload raw folder ke GoFile dimulai.")
except qbittorrentapi.APIError as exc:
return action_response(f"Gagal memulai upload GoFile: {exc}", ok=False, status_code=502)
@app.route("/api/torrents/<torrent_hash>/cancel-gofile", methods=["POST"])
def cancel_gofile_upload(torrent_hash: str):
state = load_monitor_state()
bucket_name = "aria2" if is_aria2_task(torrent_hash) else "torrents"
entry = state.setdefault(bucket_name, {}).get(torrent_hash)
if not entry or not entry.get("gofile_uploading"):
return action_response("Upload GoFile tidak sedang berjalan.", ok=False, status_code=409)
provider = entry.get("gofile_provider", "upload")
entry["gofile_cancel_requested"] = True
entry["status_message"] = ""
save_monitor_state(state)
cancel_upload_process(int(entry.get("gofile_pid", 0) or 0))
if provider == "Archiving":
return action_response("Pembatalan proses archive diproses.")
return action_response(f"Pembatalan upload {provider} diproses.")
@app.route("/api/torrents/<torrent_hash>/upload-pixeldrain", methods=["POST"])
def upload_torrent_to_pixeldrain(torrent_hash: str):
if not PIXELDRAIN_API_KEY:
return action_response("PIXELDRAIN_API_KEY belum diset.", ok=False, status_code=400)
if is_aria2_task(torrent_hash):
state = load_monitor_state()
entry = state.get("aria2", {}).get(torrent_hash)
if not entry:
return action_response("Tugas Aria2 tidak ditemukan.", ok=False, status_code=404)
if entry.get("gofile_uploading"):
return action_response("Upload file eksternal masih berjalan.", ok=False, status_code=409)
file_path = Path(entry.get("file_path", "") or "")
if not file_path.exists():
return action_response("File Aria2 tidak ditemukan di storage.", ok=False, status_code=404)
entry["gofile_uploading"] = True
entry["gofile_progress"] = 0
entry["gofile_speed"] = ""
entry["gofile_eta_seconds"] = 0
entry["gofile_cancel_requested"] = False
entry["gofile_pid"] = 0
entry["gofile_endpoint"] = "pixeldrain"
entry["gofile_provider"] = "PixelDrain"
entry["gofile_status"] = "Sedang upload ke PixelDrain..."
entry["status_message"] = ""
save_monitor_state(state)
start_pixeldrain_upload_background(torrent_hash, entry.get("name", file_path.name), file_path, mode="zip")
return action_response("Upload Aria2 ke PixelDrain dimulai.")
try:
client = get_client()
torrents = client.torrents_info(torrent_hashes=torrent_hash)
if not torrents:
return action_response("Torrent tidak ditemukan.", ok=False, status_code=404)
torrent = torrents[0]
mode = request.args.get("mode", "zip").lower()
progress = float(getattr(torrent, "progress", 0) or 0)
if progress < 1:
return action_response("Upload ke PixelDrain hanya tersedia setelah download selesai.", ok=False, status_code=400)
content_path = Path(getattr(torrent, "content_path", "") or "")
if not content_path.exists():
return action_response("File hasil download tidak ditemukan di storage.", ok=False, status_code=404)
if mode not in {"zip", "raw"}:
return action_response("Mode upload tidak valid.", ok=False, status_code=400)
state = load_monitor_state()
entry = get_task_state_entry(state, torrent_hash)
if entry.get("gofile_uploading"):
return action_response("Upload file eksternal masih berjalan.", ok=False, status_code=409)
entry["gofile_uploading"] = True
entry["gofile_progress"] = 0
entry["gofile_speed"] = ""
entry["gofile_eta_seconds"] = 0
entry["gofile_cancel_requested"] = False
entry["gofile_pid"] = 0
entry["gofile_endpoint"] = "pixeldrain"
entry["gofile_provider"] = "PixelDrain"
entry["gofile_status"] = "Sedang upload ke PixelDrain..."
entry["pre_upload_state"] = getattr(torrent, "state", "") or ""
entry["pre_upload_force_start"] = bool(getattr(torrent, "force_start", False))
entry["status_message"] = ""
save_monitor_state(state)
start_pixeldrain_upload_background(torrent_hash, torrent.name, content_path, mode=mode)
return action_response("Upload ke PixelDrain dimulai." if mode == "zip" else "Upload raw folder ke PixelDrain dimulai.")
except qbittorrentapi.APIError as exc:
return action_response(f"Gagal memulai upload PixelDrain: {exc}", ok=False, status_code=502)
@app.route("/api/torrents/<torrent_hash>/upload-rclone", methods=["POST"])
def upload_torrent_to_rclone(torrent_hash: str):
config = validate_rclone_config(force_refresh=True)
if config.get("error") or not config.get("remotes"):
return action_response(f"rclone belum siap: {config.get('error') or 'remote tidak ditemukan.'}", ok=False, status_code=400)
try:
remote = requested_rclone_remote(config, request.args.get("remote", ""))
except ValueError as exc:
return action_response(str(exc), ok=False, status_code=400, rclone=rclone_config_summary(force_refresh=False))
if is_aria2_task(torrent_hash):
state = load_monitor_state()
entry = state.get("aria2", {}).get(torrent_hash)
if not entry:
return action_response("Tugas Aria2 tidak ditemukan.", ok=False, status_code=404)
if entry.get("gofile_uploading"):
return action_response("Upload file eksternal masih berjalan.", ok=False, status_code=409)
file_path = Path(entry.get("file_path", "") or "")
if not file_path.exists():
return action_response("File Aria2 tidak ditemukan di storage.", ok=False, status_code=404)
entry["gofile_uploading"] = True
entry["gofile_progress"] = 0
entry["gofile_speed"] = ""
entry["gofile_eta_seconds"] = 0
entry["gofile_cancel_requested"] = False
entry["gofile_pid"] = 0
entry["gofile_endpoint"] = remote
entry["gofile_provider"] = "rclone"
entry["gofile_status"] = f"Sedang upload ke rclone remote {remote}..."
entry["status_message"] = ""
save_monitor_state(state)
start_rclone_upload_background(torrent_hash, entry.get("name", file_path.name), file_path, mode="zip", remote_name=remote)
return action_response("Upload Aria2 ke rclone dimulai.")
try:
client = get_client()
torrents = client.torrents_info(torrent_hashes=torrent_hash)
if not torrents:
return action_response("Torrent tidak ditemukan.", ok=False, status_code=404)
torrent = torrents[0]
mode = request.args.get("mode", "zip").lower()
progress = float(getattr(torrent, "progress", 0) or 0)
if progress < 1:
return action_response("Upload ke rclone hanya tersedia setelah download selesai.", ok=False, status_code=400)
content_path = Path(getattr(torrent, "content_path", "") or "")
if not content_path.exists():
return action_response("File hasil download tidak ditemukan di storage.", ok=False, status_code=404)
if mode not in {"zip", "raw"}:
return action_response("Mode upload tidak valid.", ok=False, status_code=400)
if mode == "raw" and not content_path.is_dir():
return action_response("Mode raw rclone hanya tersedia untuk folder.", ok=False, status_code=400)
state = load_monitor_state()
entry = get_task_state_entry(state, torrent_hash)
if entry.get("gofile_uploading"):
return action_response("Upload file eksternal masih berjalan.", ok=False, status_code=409)
entry["gofile_uploading"] = True
entry["gofile_progress"] = 0
entry["gofile_speed"] = ""
entry["gofile_eta_seconds"] = 0
entry["gofile_cancel_requested"] = False
entry["gofile_pid"] = 0
entry["gofile_endpoint"] = remote
entry["gofile_provider"] = "rclone"
entry["gofile_status"] = f"Sedang upload ke rclone remote {remote}..."
entry["pre_upload_state"] = getattr(torrent, "state", "") or ""
entry["pre_upload_force_start"] = bool(getattr(torrent, "force_start", False))
entry["status_message"] = ""
save_monitor_state(state)
start_rclone_upload_background(torrent_hash, torrent.name, content_path, mode=mode, remote_name=remote)
return action_response("Upload ke rclone dimulai." if mode == "zip" else "Upload raw folder ke rclone dimulai.")
except qbittorrentapi.APIError as exc:
return action_response(f"Gagal memulai upload rclone: {exc}", ok=False, status_code=502)
@app.route("/add-magnet", methods=["POST"])
def add_magnet():
magnet = request.form.get("magnet_link", "").strip()
is_valid_magnet, magnet_or_error = validate_magnet_link(magnet)
if not is_valid_magnet:
if wants_json_response():
return action_response(magnet_or_error, ok=False, status_code=400)
flash(magnet_or_error, "error")
return redirect(url_for("index"))
try:
torrent_hash = magnet_info_hash(magnet_or_error)
add_magnet_and_confirm_task(magnet_or_error, torrent_hash)
files = wait_for_torrent_files(torrent_hash)
if wants_json_response():
if files:
payload = build_file_selection_payload(torrent_hash, files)
clear_torrent_status_message(torrent_hash)
return torrent_selection_response(payload)
return action_response(
"Magnet link ditambahkan. Metadata masih diambil sebelum seleksi file.",
selection_required=False,
selection_pending=True,
torrent_hash=torrent_hash,
files=[],
)
qbt_resume_torrent(torrent_hash)
flash("Magnet link berhasil ditambahkan.", "success")
except InsufficientStorageError as exc:
if wants_json_response():
return action_response(str(exc), ok=False, status_code=507)
flash(str(exc), "error")
except (QBittorrentWebAPIError, TorrentMetadataError, requests.RequestException) as exc:
if wants_json_response():
return action_response(f"Gagal menambahkan magnet link: {exc}", ok=False, status_code=400)
flash(f"Gagal menambahkan magnet link: {exc}", "error")
return redirect(url_for("index"))
@app.route("/upload-torrent", methods=["POST"])
def upload_torrent():
torrent_file = request.files.get("torrent_file")
if torrent_file is None or torrent_file.filename == "":
if wants_json_response():
return action_response("Silakan pilih file torrent.", ok=False, status_code=400)
flash("Silakan pilih file torrent.", "error")
return redirect(url_for("index"))
if not torrent_file.filename.lower().endswith(".torrent"):
if wants_json_response():
return action_response("File harus berekstensi .torrent.", ok=False, status_code=400)
flash("File harus berekstensi .torrent.", "error")
return redirect(url_for("index"))
destination = UPLOAD_DIR / Path(torrent_file.filename).name
torrent_file.save(destination)
try:
torrent_hash = torrent_info_hash_from_bytes(destination.read_bytes())
qbt_add_torrent_file(destination, paused=True)
files = wait_for_torrent_files(torrent_hash)
if wants_json_response():
if files:
payload = build_file_selection_payload(torrent_hash, files)
clear_torrent_status_message(torrent_hash)
return torrent_selection_response(payload)
return action_response(
"File torrent berhasil diunggah, tetapi daftar file belum siap.",
selection_required=False,
selection_pending=True,
torrent_hash=torrent_hash,
files=[],
)
qbt_resume_torrent(torrent_hash)
flash("File torrent berhasil diunggah.", "success")
except InsufficientStorageError as exc:
if wants_json_response():
return action_response(str(exc), ok=False, status_code=507)
flash(str(exc), "error")
except (QBittorrentWebAPIError, TorrentMetadataError, requests.RequestException) as exc:
if wants_json_response():
return action_response(f"Gagal menambahkan file torrent: {exc}", ok=False, status_code=400)
flash(f"Gagal menambahkan file torrent: {exc}", "error")
finally:
destination.unlink(missing_ok=True)
return redirect(url_for("index"))
if __name__ == "__main__":
app.run(host="0.0.0.0", port=WEB_PORT, debug=False)
|