Spaces:
Paused
Paused
File size: 206,138 Bytes
00af25d 99a6e1d 139b872 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 32158c9 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 928185e 139b872 99a6e1d 1b5cc04 99a6e1d ffb6d50 00af25d 99a6e1d 00af25d 99a6e1d 00af25d ffb6d50 613885b ffb6d50 613885b ffb6d50 613885b ffb6d50 613885b ba49a39 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 928185e 00af25d 99a6e1d ffb6d50 1b5cc04 00af25d 99a6e1d be86b3f 99a6e1d 00af25d be86b3f 99a6e1d be86b3f 99a6e1d be86b3f 99a6e1d be86b3f 99a6e1d be86b3f 99a6e1d be86b3f 99a6e1d be86b3f c905d5a 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 1b5cc04 00af25d 99a6e1d 1b5cc04 928185e 1b5cc04 00af25d 99a6e1d ffb6d50 613885b ffb6d50 613885b ffb6d50 928185e 99a6e1d 928185e 99a6e1d ffb6d50 928185e ffb6d50 928185e ffb6d50 00af25d 613885b 99a6e1d ffb6d50 00af25d ffb6d50 99a6e1d 928185e 99a6e1d 613885b 928185e 00af25d 613885b ffb6d50 1b5cc04 99a6e1d 00af25d 1b5cc04 99a6e1d 1b5cc04 ffb6d50 613885b 1b5cc04 00af25d 99a6e1d 1b5cc04 00af25d 1b5cc04 00af25d 99a6e1d 1b5cc04 00af25d 99a6e1d 1b5cc04 99a6e1d 1b5cc04 99a6e1d 1b75c41 1b5cc04 99a6e1d 1b5cc04 99a6e1d ffb6d50 613885b ffb6d50 613885b ffb6d50 613885b ffb6d50 613885b ffb6d50 613885b ffb6d50 613885b ffb6d50 1b5cc04 613885b ffb6d50 1b75c41 99a6e1d 00af25d 99a6e1d 00af25d 928185e 00af25d 1b5cc04 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d ffb6d50 613885b 00af25d 613885b 1b5cc04 00af25d 99a6e1d 00af25d 99a6e1d 1b5cc04 99a6e1d ffb6d50 613885b 00af25d 928185e 613885b 1b5cc04 928185e 1b5cc04 613885b 00af25d 139b872 00af25d 139b872 928185e 00af25d 139b872 00af25d 99a6e1d 139b872 00af25d 139b872 00af25d 139b872 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 928185e 00af25d 99a6e1d 00af25d 99a6e1d 928185e 99a6e1d 928185e 99a6e1d 00af25d 99a6e1d 928185e 99a6e1d 00af25d 99a6e1d 00af25d 1b5cc04 00af25d 99a6e1d 1b5cc04 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 1b5cc04 99a6e1d 1b5cc04 99a6e1d 00af25d 1b5cc04 928185e 1b5cc04 139b872 00af25d 139b872 928185e 00af25d 139b872 00af25d 99a6e1d 139b872 1b5cc04 99a6e1d 139b872 00af25d 139b872 00af25d 1b5cc04 00af25d 1b5cc04 928185e 1b5cc04 928185e 1b5cc04 00af25d 1b5cc04 00af25d 1b5cc04 00af25d 1b5cc04 00af25d 99a6e1d 00af25d 99a6e1d 00af25d be86b3f 99a6e1d c905d5a 99a6e1d 00af25d 99a6e1d c905d5a 99a6e1d be86b3f c905d5a 99a6e1d c905d5a be86b3f c905d5a 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 613885b 99a6e1d 00af25d 99a6e1d 613885b 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d be86b3f 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d be86b3f 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d be86b3f 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d c905d5a 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 613885b 00af25d 99a6e1d 00af25d 99a6e1d 4124c6f 99a6e1d ffb6d50 00af25d ffb6d50 99a6e1d 613885b 99a6e1d ffb6d50 99a6e1d 00af25d 613885b 1b5cc04 613885b 1b5cc04 613885b 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d c905d5a 99a6e1d c905d5a 99a6e1d be86b3f 99a6e1d c905d5a 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d c905d5a 99a6e1d 00af25d c905d5a 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d c905d5a 99a6e1d 00af25d c905d5a 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 1b5cc04 99a6e1d 1b5cc04 99a6e1d 1b5cc04 99a6e1d 928185e 1b5cc04 928185e 1b5cc04 928185e 1b5cc04 99a6e1d 1b5cc04 928185e 1b5cc04 99a6e1d 1b5cc04 139b872 00af25d 99a6e1d 00af25d 99a6e1d 1b5cc04 99a6e1d 00af25d 613885b 00af25d 99a6e1d 613885b 1b5cc04 139b872 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 99a6e1d 00af25d 1bc2b5e 99a6e1d 1bc2b5e cadb5cb 1bc2b5e cadb5cb b6c213e cadb5cb 1bc2b5e cadb5cb 1bc2b5e 00af25d d5c09af 1bc2b5e 2f66adb 1bc2b5e | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 | import os
import asyncio
import logging
import time
import random
import contextlib
import gc
from collections import deque
import re
import subprocess
import json
import shutil
import tempfile
import zipfile
from typing import Optional, Dict, Any, List
from dataclasses import dataclass, field
from datetime import datetime, timedelta
from urllib.parse import quote_plus, urlparse
try:
from dotenv import load_dotenv
except Exception:
def load_dotenv(*args, **kwargs):
return False
import asyncpg
import psutil
from pyrogram import Client, filters
from pyrogram.types import (
Message, InlineKeyboardMarkup, InlineKeyboardButton, CallbackQuery
)
# =====================
# CONFIGURACIÓN
# =====================
load_dotenv()
API_ID = os.environ.get("API_ID", "24288670")
API_HASH = os.environ.get("API_HASH", "81c58005802498656d6b689dae1edacc")
BOT_TOKEN = os.environ.get("BOT_TOKEN", "")
BOT_VERSION = "V.6 Ultra Supabase"
BOT_CREATOR = "@Sasuke286"
SUPABASE_URL = os.environ.get("SUPABASE_URL", "https://lkqihreksoitujnwanik.supabase.co")
SUPABASE_PUBLISHABLE_KEY = os.environ.get("SUPABASE_PUBLISHABLE_KEY", "")
SUPABASE_SERVICE_ROLE_KEY = os.environ.get("SUPABASE_SERVICE_ROLE_KEY", "")
SUPABASE_DB_PASSWORD = os.environ.get("SUPABASE_DB_PASSWORD", "")
SUPABASE_PROJECT_REF = os.environ.get("SUPABASE_PROJECT_REF") or (urlparse(SUPABASE_URL).hostname or "").split(".")[0]
DATABASE_URL = os.environ.get("DATABASE_URL", "").strip()
SUPABASE_DB_URL = os.environ.get("SUPABASE_DB_URL", "").strip() or DATABASE_URL
SUPABASE_POOLER_URL = os.environ.get("SUPABASE_POOLER_URL", "").strip()
SUPABASE_DIRECT_URL = os.environ.get("SUPABASE_DIRECT_URL", "").strip()
SUPABASE_POOL_MODE = os.environ.get("SUPABASE_POOL_MODE", "session").strip().lower() or "session"
SUPABASE_USE_TRANSACTION_POOLER = SUPABASE_POOL_MODE == "transaction"
DB_NAME = f"supabase:{SUPABASE_PROJECT_REF or 'unknown'}"
def _redact_db_url(url: str) -> str:
if not url:
return ""
return re.sub(r"://([^:]+):([^@]+)@", r"://\1:***@", url)
def _looks_like_direct_supabase_url(url: str) -> bool:
if not url:
return False
host = (urlparse(url).hostname or "").lower()
return host.startswith("db.") and host.endswith(".supabase.co")
def _build_default_supabase_db_url() -> str:
if SUPABASE_DB_URL:
return SUPABASE_DB_URL
if SUPABASE_POOLER_URL:
return SUPABASE_POOLER_URL
if SUPABASE_DIRECT_URL:
return SUPABASE_DIRECT_URL
if not SUPABASE_PROJECT_REF or not SUPABASE_DB_PASSWORD:
return ""
# Último recurso: conexión directa. Si tu hosting es IPv4-only, el error posterior te indicará que uses el pooler.
return f"postgresql://postgres:{quote_plus(SUPABASE_DB_PASSWORD)}@db.{SUPABASE_PROJECT_REF}.supabase.co:5432/postgres?sslmode=require"
SUPER_ADMINS_STATIC = [5702506445]
# =====================
# CALIDADES PREDEFINIDAS
# Siempre reducen el tamaño del archivo
# =====================
QUALITY_PRESETS = {
"144p": {"resolution": "256x144", "crf": "38", "audio_bitrate": "48k", "fps": "24", "preset": "ultrafast", "codec": "libx265", "label": "144p — Mínimo tamaño"},
"240p": {"resolution": "426x240", "crf": "36", "audio_bitrate": "56k", "fps": "24", "preset": "ultrafast", "codec": "libx265", "label": "240p — Muy ligero"},
"360p": {"resolution": "640x360", "crf": "33", "audio_bitrate": "64k", "fps": "25", "preset": "ultrafast", "codec": "libx265", "label": "360p — Ligero"},
"480p": {"resolution": "854x480", "crf": "30", "audio_bitrate": "80k", "fps": "28", "preset": "ultrafast", "codec": "libx265", "label": "480p — Equilibrado ⭐"},
"720p": {"resolution": "1280x720", "crf": "28", "audio_bitrate": "96k", "fps": "30", "preset": "ultrafast", "codec": "libx265", "label": "720p — HD"},
"1080p": {"resolution": "1920x1080","crf": "26", "audio_bitrate": "128k", "fps": "30", "preset": "ultrafast", "codec": "libx265", "label": "1080p — Full HD"},
}
DEFAULT_QUALITY = QUALITY_PRESETS["480p"].copy()
DEFAULT_QUALITY.pop("label", None)
DEFAULT_PLANS = {
"free": {
"name": "🆓 Free",
"max_file_size_mb": 200,
"daily_videos": 5,
"queue_priority": False,
"custom_quality": False,
"own_queue": False,
},
"basic": {
"name": "⭐ Basic",
"max_file_size_mb": 500,
"daily_videos": 20,
"queue_priority": False,
"custom_quality": True,
"own_queue": True,
},
"pro": {
"name": "💎 Pro",
"max_file_size_mb": 2000,
"daily_videos": 100,
"queue_priority": True,
"custom_quality": True,
"own_queue": True,
},
"premium": {
"name": "👑 Premium",
"max_file_size_mb": 4000,
"daily_videos": 500,
"queue_priority": True,
"custom_quality": True,
"own_queue": True,
},
"admin": {
"name": "🛡️ Admin",
"max_file_size_mb": 999999,
"daily_videos": 999999,
"queue_priority": True,
"custom_quality": True,
"own_queue": True,
},
"superadmin": {
"name": "⚡ SuperAdmin",
"max_file_size_mb": 999999,
"daily_videos": 999999,
"queue_priority": True,
"custom_quality": True,
"own_queue": True,
},
}
PLANS: Dict[str, dict] = {k: dict(v) for k, v in DEFAULT_PLANS.items()}
BOT_MODE: str = "private"
INDIVIDUAL_QUEUES_ENABLED: bool = True
VIDEO_EXTENSIONS = {
".mp4", ".mkv", ".mpg", ".mpeg", ".ts", ".m2ts", ".mts",
".mov", ".avi", ".wmv", ".flv", ".webm", ".m4v", ".3gp", ".vob", ".ogv",
}
PROGRESS_EDIT_EVERY = 5
TRANSFER_PROGRESS_MIN_INTERVAL = max(2.0, float(os.environ.get("TRANSFER_PROGRESS_MIN_INTERVAL", "3.0")))
TRANSFER_SPEED_WINDOW_SECONDS = max(1.0, float(os.environ.get("TRANSFER_SPEED_WINDOW_SECONDS", "3.0")))
MAX_CPU_PERCENT = max(50, min(95, int(os.environ.get("MAX_CPU_PERCENT", "85"))))
CPU_MONITOR_INTERVAL = max(0.5, float(os.environ.get("CPU_MONITOR_INTERVAL", "2.0")))
COMPRESS_STALL_SECONDS = max(120, int(os.environ.get("COMPRESS_STALL_SECONDS", "420")))
COMPRESS_START_GRACE_SECONDS = max(60, int(os.environ.get("COMPRESS_START_GRACE_SECONDS", "120")))
FFMPEG_OUTPUT_IDLE_SECONDS = max(45, int(os.environ.get("FFMPEG_OUTPUT_IDLE_SECONDS", "120")))
STALL_CPU_FLOOR_PERCENT = max(0.5, float(os.environ.get("STALL_CPU_FLOOR_PERCENT", "2.0")))
UPLOAD_STALL_SECONDS = max(300, int(os.environ.get("UPLOAD_STALL_SECONDS", "1800")))
UPLOAD_HEARTBEAT_EVERY = max(5.0, float(os.environ.get("UPLOAD_HEARTBEAT_EVERY", "15.0")))
UPLOAD_HARD_TIMEOUT_SECONDS = max(900, int(os.environ.get("UPLOAD_HARD_TIMEOUT_SECONDS", "7200")))
FINALIZE_GRACE_SECONDS = max(120, int(os.environ.get("FINALIZE_GRACE_SECONDS", "900")))
QUEUE_WATCHDOG_INTERVAL = max(2.0, float(os.environ.get("QUEUE_WATCHDOG_INTERVAL", "5.0")))
CPU_LIMIT_HEADROOM_PERCENT = max(1, min(15, int(os.environ.get("CPU_LIMIT_HEADROOM_PERCENT", "4"))))
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
logger = logging.getLogger(__name__)
BASE_DIR = "/app"
DOWNLOADS_DIR = os.path.join(BASE_DIR, "downloads")
COMPRESSED_DIR = os.path.join(BASE_DIR, "compressed")
SESSION_DIR = os.path.join(BASE_DIR, "session")
BACKUPS_DIR = os.path.join(BASE_DIR, "backups")
os.makedirs(DOWNLOADS_DIR, exist_ok=True)
os.makedirs(COMPRESSED_DIR, exist_ok=True)
os.makedirs(SESSION_DIR, exist_ok=True)
os.makedirs(BACKUPS_DIR, exist_ok=True)
def _usable_cpu_ids() -> List[int]:
try:
proc = psutil.Process()
affinity = proc.cpu_affinity()
if affinity:
return sorted(int(cpu) for cpu in affinity)
except Exception:
pass
try:
affinity = os.sched_getaffinity(0)
if affinity:
return sorted(int(cpu) for cpu in affinity)
except Exception:
pass
cpu_count = psutil.cpu_count(logical=True) or (os.cpu_count() or 1)
return list(range(max(1, cpu_count)))
def _try_read_text(path: str) -> Optional[str]:
try:
with open(path, "r", encoding="utf-8", errors="replace") as f:
return f.read().strip()
except Exception:
return None
def _parse_cgroup_cpu_max(text: str) -> Optional[float]:
try:
parts = (text or "").strip().split()
if len(parts) < 2:
return None
quota_s, period_s = parts[0], parts[1]
if quota_s == "max":
return None
quota = int(quota_s)
period = int(period_s)
if quota <= 0 or period <= 0:
return None
return quota / period
except Exception:
return None
def _cgroup_paths() -> List[str]:
paths: List[str] = []
try:
with open("/proc/self/cgroup", "r", encoding="utf-8", errors="replace") as f:
for line in f:
line = line.strip()
if not line:
continue
parts = line.split(":")
if len(parts) != 3:
continue
_, controllers, cgrp_path = parts
if controllers == "":
paths.append(cgrp_path or "/")
else:
ctrls = set((controllers or "").split(","))
if "cpu" in ctrls:
paths.append(cgrp_path or "/")
except Exception:
pass
out: List[str] = []
for path in paths:
if path not in out:
out.append(path)
if "/" not in out:
out.append("/")
return out
def _cgroup_cpu_quota_cpus() -> Optional[float]:
candidates = ["/sys/fs/cgroup/cpu.max"]
for rel in _cgroup_paths():
if rel and rel != "/":
candidates.append(f"/sys/fs/cgroup{rel}/cpu.max")
for path in candidates:
txt = _try_read_text(path)
if not txt:
continue
if txt.split()[0] == "max":
return None
cpus = _parse_cgroup_cpu_max(txt)
if cpus is not None and cpus > 0:
return cpus
quota_pairs: List[tuple[str, str]] = []
for base in ("/sys/fs/cgroup/cpu", "/sys/fs/cgroup/cpu,cpuacct", "/sys/fs/cgroup"):
quota_pairs.append((f"{base}/cpu.cfs_quota_us", f"{base}/cpu.cfs_period_us"))
for rel in _cgroup_paths():
if rel and rel != "/":
for base in ("/sys/fs/cgroup/cpu", "/sys/fs/cgroup/cpu,cpuacct"):
quota_pairs.append((f"{base}{rel}/cpu.cfs_quota_us", f"{base}{rel}/cpu.cfs_period_us"))
for qpath, ppath in quota_pairs:
qtxt = _try_read_text(qpath)
ptxt = _try_read_text(ppath)
if not qtxt or not ptxt:
continue
try:
quota = int(qtxt)
period = int(ptxt)
if quota < 0:
return None
if quota == 0 or period <= 0:
continue
cpus = quota / period
if cpus > 0:
return cpus
except Exception:
continue
return None
def _effective_cpu_capacity() -> float:
usable = float(len(_usable_cpu_ids()) or 1)
quota = _cgroup_cpu_quota_cpus()
if quota is not None and quota > 0:
usable = min(usable, quota)
return max(1.0, usable)
def _max_parallel_cpu_slots() -> int:
usable_affinity = len(_usable_cpu_ids()) or 1
capacity = _effective_cpu_capacity()
limit = max(1, int(capacity * (MAX_CPU_PERCENT / 100.0)))
return max(1, min(usable_affinity, limit))
def _pick_cpu_subset(cpu_ids: List[int], slot_index: int, wanted: int) -> List[int]:
if not cpu_ids:
return []
wanted = max(1, min(len(cpu_ids), int(wanted)))
if wanted >= len(cpu_ids):
return list(cpu_ids)
start = (max(0, int(slot_index)) * wanted) % len(cpu_ids)
subset = [cpu_ids[(start + offset) % len(cpu_ids)] for offset in range(wanted)]
return sorted(set(subset))
def _allocate_cpu_subset(cpu_ids: List[int], job_index: int, active_jobs: int, total_slots: int) -> List[int]:
if not cpu_ids:
return []
active_jobs = max(1, int(active_jobs))
total_slots = max(1, min(len(cpu_ids), int(total_slots)))
pool = list(cpu_ids[:total_slots]) or list(cpu_ids)
j = int(job_index) % active_jobs
subset = pool[j::active_jobs]
if not subset:
subset = [pool[j % len(pool)]]
return sorted(set(subset))
FFMPEG_ACTIVE_JOBS: Dict[str, float] = {}
FFMPEG_ACTIVE_LOCK: asyncio.Lock = asyncio.Lock()
async def _register_active_ffmpeg(job_key: str) -> tuple[str, int, int]:
key = (job_key or "").strip() or f"anon:{time.time_ns()}"
async with FFMPEG_ACTIVE_LOCK:
FFMPEG_ACTIVE_JOBS[key] = time.time()
active_keys = list(FFMPEG_ACTIVE_JOBS.keys())
return key, len(active_keys), active_keys.index(key)
async def _unregister_active_ffmpeg(job_key: str):
if not job_key:
return
async with FFMPEG_ACTIVE_LOCK:
FFMPEG_ACTIVE_JOBS.pop(job_key, None)
async def _active_ffmpeg_count() -> int:
async with FFMPEG_ACTIVE_LOCK:
return len(FFMPEG_ACTIVE_JOBS)
# =====================
# SUPABASE / POSTGRES
# =====================
_pg_pool: Optional[asyncpg.Pool] = None
_COLLECTION_KEY_FIELDS = {
"users": "user_id",
"groups": "group_id",
"admins": "user_id",
"super_admins": "user_id",
"plans": "key",
"config": "key",
"reports": "id",
}
def _json_loads_if_needed(value):
if isinstance(value, str):
try:
return json.loads(value)
except Exception:
return value
return value
def _set_path(data: dict, path: str, value):
cur = data
parts = path.split(".")
for part in parts[:-1]:
if not isinstance(cur.get(part), dict):
cur[part] = {}
cur = cur[part]
cur[parts[-1]] = value
def _inc_path(data: dict, path: str, value):
cur = data
parts = path.split(".")
for part in parts[:-1]:
if not isinstance(cur.get(part), dict):
cur[part] = {}
cur = cur[part]
cur[parts[-1]] = cur.get(parts[-1], 0) + value
def _get_path(data: dict, path: str, default=None):
cur = data
for part in path.split("."):
if not isinstance(cur, dict) or part not in cur:
return default
cur = cur[part]
return cur
def _apply_update(doc: dict, update: dict) -> dict:
result = dict(doc)
for path, value in update.get("$set", {}).items():
_set_path(result, path, value)
for path, value in update.get("$inc", {}).items():
_inc_path(result, path, value)
return result
def _compare_value(actual, op: str, expected) -> bool:
if op == "$nin":
return actual not in expected
if op == "$in":
return actual in expected
if op == "$ne":
return actual != expected
if op == "$lt":
return actual is not None and actual < expected
if op == "$lte":
return actual is not None and actual <= expected
if op == "$gt":
return actual is not None and actual > expected
if op == "$gte":
return actual is not None and actual >= expected
if op == "$exists":
exists = actual is not None
return exists if expected else not exists
return actual == expected
def _matches_filter(doc: dict, flt: dict) -> bool:
if not flt:
return True
for key, cond in flt.items():
if key == "$or":
if not any(_matches_filter(doc, sub) for sub in cond):
return False
continue
actual = _get_path(doc, key, None)
if isinstance(cond, dict):
for op, expected in cond.items():
if op == "$exists":
exists = _get_path(doc, key, None) is not None or key in doc
if bool(expected) != bool(exists):
return False
elif not _compare_value(actual, op, expected):
return False
else:
if actual != cond:
return False
return True
class _AsyncCursor:
def __init__(self, docs: List[dict]):
self._docs = list(docs)
self._index = 0
def sort(self, field: str, direction: int = 1):
reverse = int(direction) < 0
self._docs.sort(key=lambda d: (_get_path(d, field, None) is None, _get_path(d, field, None)), reverse=reverse)
return self
def limit(self, n: int):
self._docs = self._docs[:n]
return self
async def to_list(self, length: Optional[int] = None):
return list(self._docs if length is None else self._docs[:length])
def __aiter__(self):
self._index = 0
return self
async def __anext__(self):
if self._index >= len(self._docs):
raise StopAsyncIteration
value = self._docs[self._index]
self._index += 1
return value
class _AsyncCollection:
def __init__(self, name: str):
self.name = name
self.key_field = _COLLECTION_KEY_FIELDS.get(name)
async def create_index(self, *args, **kwargs):
return None
async def _fetch_rows(self):
async with _pg_pool.acquire() as conn:
rows = await conn.fetch(
"SELECT doc_id, key, data FROM bot_store WHERE collection = $1 ORDER BY doc_id ASC",
self.name,
)
docs = []
for row in rows:
doc = _json_loads_if_needed(row["data"]) or {}
if not isinstance(doc, dict):
doc = {"value": doc}
doc = dict(doc)
if self.key_field and row["key"] is not None and self.key_field not in doc:
raw_key = row["key"]
try:
doc[self.key_field] = int(raw_key) if raw_key.isdigit() or (raw_key.startswith("-") and raw_key[1:].isdigit()) else raw_key
except Exception:
doc[self.key_field] = raw_key
doc["_doc_id"] = row["doc_id"]
docs.append(doc)
return docs
def _extract_key(self, data: dict):
if not self.key_field or not data:
return None
value = data.get(self.key_field)
return None if value is None else str(value)
async def find_one(self, flt: dict):
docs = await self.find(flt).to_list(1)
return docs[0] if docs else None
async def update_one(self, flt: dict, update: dict, upsert: bool = False):
current = await self.find_one(flt)
if current is None and not upsert:
return None
base = {k: v for k, v in (current or {}).items() if not k.startswith("_")}
new_doc = _apply_update(base, update)
key_value = self._extract_key(new_doc) or self._extract_key(flt)
async with _pg_pool.acquire() as conn:
if current is None:
await conn.execute(
"INSERT INTO bot_store(collection, key, data) VALUES($1, $2, $3::jsonb)",
self.name, key_value, json.dumps(new_doc),
)
else:
await conn.execute(
"UPDATE bot_store SET key=$1, data=$2::jsonb, updated_at=NOW() WHERE doc_id=$3",
key_value, json.dumps(new_doc), current.get("_doc_id"),
)
return new_doc
async def insert_one(self, doc: dict):
key_value = self._extract_key(doc)
async with _pg_pool.acquire() as conn:
await conn.execute(
"INSERT INTO bot_store(collection, key, data) VALUES($1, $2, $3::jsonb)",
self.name, key_value, json.dumps(doc),
)
return {"inserted": True}
async def delete_one(self, flt: dict):
doc = await self.find_one(flt)
if not doc:
return {"deleted_count": 0}
async with _pg_pool.acquire() as conn:
await conn.execute("DELETE FROM bot_store WHERE doc_id=$1", doc.get("_doc_id"))
return {"deleted_count": 1}
def find(self, flt: Optional[dict] = None):
async def _collect():
docs = await self._fetch_rows()
matched = [d for d in docs if _matches_filter(d, flt or {})]
return _AsyncCursor(matched)
return _AwaitableCursorFactory(_collect)
async def count_documents(self, flt: Optional[dict] = None):
docs = await self.find(flt or {}).to_list(None)
return len(docs)
def aggregate(self, pipeline: list):
async def _collect():
docs = await self.find({}).to_list(None)
if self.name == "stats" and pipeline:
orig = sum(float(d.get("original_mb", 0) or 0) for d in docs)
comp = sum(float(d.get("compressed_mb", 0) or 0) for d in docs)
return _AsyncCursor([{"_id": None, "o": orig, "c": comp}])
return _AsyncCursor([])
return _AwaitableCursorFactory(_collect)
class _AwaitableCursorFactory:
def __init__(self, builder):
self._builder = builder
self._cursor = None
async def _ensure(self):
if self._cursor is None:
self._cursor = await self._builder()
return self._cursor
def sort(self, *args, **kwargs):
async def _builder():
cursor = await self._ensure()
return cursor.sort(*args, **kwargs)
return _AwaitableCursorFactory(_builder)
def limit(self, *args, **kwargs):
async def _builder():
cursor = await self._ensure()
return cursor.limit(*args, **kwargs)
return _AwaitableCursorFactory(_builder)
async def to_list(self, length: Optional[int] = None):
cursor = await self._ensure()
return await cursor.to_list(length)
def __aiter__(self):
self._aiter = None
return self
async def __anext__(self):
if self._aiter is None:
cursor = await self._ensure()
self._aiter = cursor.__aiter__()
return await self._aiter.__anext__()
class _AsyncDB:
def __getitem__(self, name: str):
return _AsyncCollection(name)
async def list_collection_names(self):
docs = await db["config"].count_documents({}) # fuerza inicialización si hace falta
_ = docs
async with _pg_pool.acquire() as conn:
rows = await conn.fetch("SELECT DISTINCT collection FROM bot_store ORDER BY collection ASC")
return [r["collection"] for r in rows]
db = _AsyncDB()
col_users = db["users"]
col_groups = db["groups"]
col_admins = db["admins"]
col_super_admins = db["super_admins"]
col_stats = db["stats"]
col_plans = db["plans"]
col_config = db["config"]
async def _connect_pg():
global _pg_pool
if _pg_pool is not None:
return
db_url = _build_default_supabase_db_url()
if not db_url:
raise RuntimeError(
"Falta la cadena Postgres de Supabase. Usa una de estas variables: SUPABASE_DB_URL, DATABASE_URL, SUPABASE_POOLER_URL o SUPABASE_DIRECT_URL."
)
create_pool_kwargs = dict(min_size=1, max_size=4, command_timeout=60)
if ":6543/" in db_url or SUPABASE_USE_TRANSACTION_POOLER:
# Supavisor transaction mode no soporta prepared statements.
create_pool_kwargs["statement_cache_size"] = 0
try:
_pg_pool = await asyncpg.create_pool(db_url, **create_pool_kwargs)
except OSError as e:
_pg_pool = None
if getattr(e, "errno", None) == 101:
extra = ""
if _looks_like_direct_supabase_url(db_url):
extra = (
" Estás usando la URL directa de Supabase y ese host suele requerir IPv6. "
"Cambia a la URL del pooler en Supabase > Connect (Session mode para servidor normal o Transaction mode para serverless)."
)
raise RuntimeError(
"No se puede llegar a la base de datos de Supabase desde este hosting (Network is unreachable)."
+ extra
+ " URL actual: " + _redact_db_url(db_url)
) from e
raise
except Exception as e:
_pg_pool = None
msg = str(e)
if "prepared statement" in msg.lower() or "statement_cache_size" in msg.lower():
raise RuntimeError(
"La conexión parece estar usando Supabase Transaction mode. Usa el puerto 6543 y deja que el bot desactive statement_cache_size automáticamente."
) from e
raise
async with _pg_pool.acquire() as conn:
await conn.execute("""
CREATE TABLE IF NOT EXISTS bot_store (
doc_id BIGSERIAL PRIMARY KEY,
collection TEXT NOT NULL,
key TEXT NULL,
data JSONB NOT NULL DEFAULT '{}'::jsonb,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
)
""")
await conn.execute("CREATE INDEX IF NOT EXISTS bot_store_collection_idx ON bot_store(collection)")
await conn.execute("CREATE UNIQUE INDEX IF NOT EXISTS bot_store_collection_key_uidx ON bot_store(collection, key) WHERE key IS NOT NULL")
async def db_init():
await _connect_pg()
await col_users.create_index("user_id", unique=True)
await col_groups.create_index("group_id", unique=True)
await col_admins.create_index("user_id", unique=True)
await col_super_admins.create_index("user_id", unique=True)
await col_plans.create_index("key", unique=True)
await col_config.create_index("key", unique=True)
await _sync_plans_from_db()
await _load_config_from_db()
for uid in SUPER_ADMINS_STATIC:
await col_super_admins.update_one({"user_id": uid}, {"$set": {"user_id": uid}}, upsert=True)
await col_admins.update_one({"user_id": uid}, {"$set": {"user_id": uid}}, upsert=True)
await col_users.update_one({"user_id": uid}, {"$set": {"user_id": uid, "plan": "superadmin", "authorized": True}}, upsert=True)
logger.info("✅ Supabase/Postgres listo — %s", DB_NAME)
async def _sync_plans_from_db():
global PLANS
PLANS = {k: dict(v) for k, v in DEFAULT_PLANS.items()}
async for doc in col_plans.find({}):
key = doc.get("key")
if key and key in PLANS:
for f in ("max_file_size_mb", "daily_videos", "queue_priority", "custom_quality", "name", "own_queue"):
if f in doc:
PLANS[key][f] = doc[f]
async def _load_config_from_db():
global BOT_MODE, LOG_CHAT_ID, LOG_VIDEOS, INDIVIDUAL_QUEUES_ENABLED
doc = await col_config.find_one({"key": "bot_mode"})
if doc:
BOT_MODE = doc.get("value", "private")
doc2 = await col_config.find_one({"key": "log_chat_id"})
if doc2 and doc2.get("value") is not None:
LOG_CHAT_ID = int(doc2["value"])
doc3 = await col_config.find_one({"key": "log_videos"})
if doc3:
LOG_VIDEOS = bool(doc3.get("value", True))
doc4 = await col_config.find_one({"key": "individual_queues"})
if doc4:
INDIVIDUAL_QUEUES_ENABLED = bool(doc4.get("value", True))
logger.info("🔧 Modo: %s | Logs: %s | Cola individual: %s", BOT_MODE, LOG_CHAT_ID, INDIVIDUAL_QUEUES_ENABLED)
async def _save_config_to_db(key: str, value):
await col_config.update_one({"key": key}, {"$set": {"key": key, "value": value}}, upsert=True)
async def _save_plan_to_db(key: str):
data = dict(PLANS[key])
data["key"] = key
await col_plans.update_one({"key": key}, {"$set": data}, upsert=True)
# =====================
# DB HELPERS
# =====================
async def get_user(uid: int):
return await col_users.find_one({"user_id": uid})
async def upsert_user(uid: int, data: dict):
await col_users.update_one({"user_id": uid}, {"$set": data}, upsert=True)
async def is_super_admin(uid: int) -> bool:
if uid in SUPER_ADMINS_STATIC:
return True
return bool(await col_super_admins.find_one({"user_id": uid}))
async def is_admin(uid: int) -> bool:
if await is_super_admin(uid):
return True
return bool(await col_admins.find_one({"user_id": uid}))
async def is_authorized_user(uid: int) -> bool:
if await is_admin(uid):
return True
doc = await get_user(uid)
if doc and doc.get("authorized"):
return True
if BOT_MODE == "public":
if not doc:
await upsert_user(uid, {"user_id": uid, "authorized": True, "plan": "free"})
return True
return False
async def is_authorized_group(cid: int) -> bool:
if BOT_MODE == "public":
return True
return bool(await col_groups.find_one({"group_id": cid}))
PLAN_EXPIRY_DAYS: int = 30
async def _notify_plan_change(uid: int, old_plan: str, new_plan: str, reason: str = ""):
old_info = PLANS.get(old_plan, {}).get('name', old_plan)
new_info = PLANS.get(new_plan, {}).get('name', new_plan)
try:
text = (
f"📋 **Tu plan ha cambiado**\n\n"
f"📤 Plan anterior: **{old_info}**\n"
f"📥 Plan nuevo: **{new_info}**\n"
)
if reason:
text += f"\n📝 Motivo: {reason}"
if new_plan == "free":
text += "\n\n💡 Contacta al admin para renovar tu plan: /planes"
await bot.send_message(uid, text)
except Exception:
pass
async def _assign_plan(uid: int, plan_key: str, days: int = None, notify: bool = True, reason: str = ""):
old_doc = await get_user(uid)
old_plan = (old_doc or {}).get("plan", "free")
data = {"user_id": uid, "plan": plan_key, "authorized": True}
if plan_key == "free":
data["plan_expires"] = None
else:
expiry_days = days if days is not None else PLAN_EXPIRY_DAYS
data["plan_expires"] = (datetime.utcnow() + timedelta(days=expiry_days)).isoformat()
data["plan_days"] = expiry_days
await upsert_user(uid, data)
if notify and old_plan != plan_key:
await _notify_plan_change(uid, old_plan, plan_key, reason)
async def _check_plan_expiry(uid: int, doc: dict) -> str:
plan = doc.get("plan", "free")
if plan in ("free", "admin", "superadmin"):
return plan
expires_str = doc.get("plan_expires")
if not expires_str:
expiry = datetime.utcnow() + timedelta(days=PLAN_EXPIRY_DAYS)
await col_users.update_one(
{"user_id": uid},
{"$set": {"plan_expires": expiry.isoformat(), "plan_days": PLAN_EXPIRY_DAYS}}
)
return plan
try:
expires = datetime.fromisoformat(expires_str)
except Exception:
return plan
if datetime.utcnow() > expires:
await col_users.update_one(
{"user_id": uid},
{"$set": {"plan": "free", "plan_expires": None}}
)
await _notify_plan_change(uid, plan, "free",
"Tu plan ha expirado. Contacta al admin para renovarlo.")
asyncio.create_task(_log(f"⏰ Plan expirado: usuario `{uid}` — {plan} → free"))
return "free"
return plan
async def get_user_plan(uid: int) -> str:
if await is_super_admin(uid):
return "superadmin"
if await is_admin(uid):
return "admin"
doc = await get_user(uid)
if not doc:
return "free"
return await _check_plan_expiry(uid, doc)
async def get_plan_info(uid: int) -> dict:
return PLANS.get(await get_user_plan(uid), PLANS["free"])
async def check_daily_limit(uid: int, chat_id: int = None):
if chat_id and chat_id != uid and await is_authorized_group(chat_id):
return True, 0, 999999
plan = await get_plan_info(uid)
limit = plan["daily_videos"]
if limit >= 99999:
return True, 0, limit
today = datetime.utcnow().strftime("%Y-%m-%d")
doc = await get_user(uid)
used = (doc or {}).get("daily_usage", {}).get(today, 0)
return used < limit, used, limit
async def increment_daily_usage(uid: int):
today = datetime.utcnow().strftime("%Y-%m-%d")
await col_users.update_one({"user_id": uid}, {"$inc": {f"daily_usage.{today}": 1}}, upsert=True)
async def get_user_quality(uid: int) -> dict:
doc = await get_user(uid)
q = (doc or {}).get("quality", DEFAULT_QUALITY.copy())
# Limpiar campo label si existe
q.pop("label", None)
return q
async def set_user_quality(uid: int, quality: dict):
q = dict(quality)
q.pop("label", None)
await upsert_user(uid, {"quality": q})
async def log_stat(uid: int, orig_mb: float, comp_mb: float, dur_s: float):
await col_stats.insert_one({"user_id": uid, "original_mb": orig_mb, "compressed_mb": comp_mb, "duration_s": dur_s, "date": datetime.utcnow().isoformat()})
await col_users.update_one({"user_id": uid}, {"$inc": {"total_compressions": 1, "total_saved_mb": orig_mb - comp_mb}}, upsert=True)
# =====================
# BACKUP / IMPORT DB
# =====================
async def _next_numeric_id(collection_name: str, field: str = "id") -> int:
docs = await db[collection_name].find({}).to_list(None)
current = 0
for doc in docs:
try:
current = max(current, int(doc.get(field, 0) or 0))
except Exception:
pass
return current + 1
async def _export_database_zip() -> str:
export_dir = tempfile.mkdtemp(prefix="db_export_", dir=BACKUPS_DIR)
zip_path = os.path.join(BACKUPS_DIR, f"compresultra_supabase_backup_{datetime.utcnow().strftime('%Y%m%d_%H%M%S')}.zip")
collections = ["users", "groups", "admins", "super_admins", "plans", "config", "stats", "reports"]
manifest = {
"bot": "CompresUltra Bot",
"version": BOT_VERSION,
"database": DB_NAME,
"exported_at_utc": datetime.utcnow().isoformat() + "Z",
"collections": collections,
}
with open(os.path.join(export_dir, "manifest.json"), "w", encoding="utf-8") as fh:
json.dump(manifest, fh, ensure_ascii=False, indent=2)
for name in collections:
docs = await db[name].find({}).to_list(None)
cleaned = [{k: v for k, v in doc.items() if not str(k).startswith("_")} for doc in docs]
with open(os.path.join(export_dir, f"{name}.json"), "w", encoding="utf-8") as fh:
json.dump(cleaned, fh, ensure_ascii=False, indent=2, default=str)
with zipfile.ZipFile(zip_path, "w", compression=zipfile.ZIP_DEFLATED) as zf:
for filename in sorted(os.listdir(export_dir)):
zf.write(os.path.join(export_dir, filename), arcname=filename)
shutil.rmtree(export_dir, ignore_errors=True)
return zip_path
async def _replace_collection_docs(collection_name: str, docs: list):
async with _pg_pool.acquire() as conn:
await conn.execute("DELETE FROM bot_store WHERE collection = $1", collection_name)
col = db[collection_name]
for doc in docs:
doc = {k: v for k, v in dict(doc).items() if not str(k).startswith("_")}
await col.insert_one(doc)
async def _import_database_export(path_to_file: str) -> dict:
workdir = tempfile.mkdtemp(prefix="db_import_", dir=BACKUPS_DIR)
extracted_dir = workdir
try:
lower = path_to_file.lower()
if lower.endswith(".zip"):
with zipfile.ZipFile(path_to_file, "r") as zf:
zf.extractall(extracted_dir)
elif lower.endswith(".json"):
shutil.copy2(path_to_file, os.path.join(extracted_dir, os.path.basename(path_to_file)))
else:
raise ValueError("Formato no soportado. Usa un .zip o .json exportado por el bot.")
imported = {}
for name in ["users", "groups", "admins", "super_admins", "plans", "config", "stats", "reports"]:
file_path = os.path.join(extracted_dir, f"{name}.json")
if not os.path.exists(file_path):
continue
with open(file_path, "r", encoding="utf-8") as fh:
docs = json.load(fh)
if not isinstance(docs, list):
raise ValueError(f"{name}.json no contiene una lista válida.")
await _replace_collection_docs(name, docs)
imported[name] = len(docs)
await _sync_plans_from_db()
await _load_config_from_db()
for uid in SUPER_ADMINS_STATIC:
await col_super_admins.update_one({"user_id": uid}, {"$set": {"user_id": uid}}, upsert=True)
await col_admins.update_one({"user_id": uid}, {"$set": {"user_id": uid}}, upsert=True)
await col_users.update_one({"user_id": uid}, {"$set": {"user_id": uid, "plan": "superadmin", "authorized": True}}, upsert=True)
return imported
finally:
shutil.rmtree(workdir, ignore_errors=True)
# =====================
# JOB SYSTEM
# =====================
@dataclass
class Job:
job_id: str
user_id: int
chat_id: int
status_msg_id: int
cancelled: bool = False # True cuando el USUARIO cancela
system_cancelled: bool = False # True cuando el SISTEMA/watchdog cancela (no el usuario)
task: Optional[asyncio.Task] = None
process: Optional[asyncio.subprocess.Process] = None
files: list = field(default_factory=list)
fname: str = ""
progress_pct: float = 0.0
progress_bar: str = ""
stage: str = ""
queue_name: str = ""
is_processing: bool = False
started_at: float = 0.0
last_activity_at: float = field(default_factory=time.time)
cpu_throttle_events: int = 0
cpu_usage_pct: float = 0.0
cpu_slots: int = 0
cpu_slots_max: int = 0
ffmpeg_last_progress_at: float = 0.0
ffmpeg_last_output_at: float = 0.0
ffmpeg_last_stderr: str = ""
upload_started_at: float = 0.0
upload_last_progress_at: float = 0.0
upload_completed_at: float = 0.0
upload_last_bytes: int = 0
upload_total_bytes: int = 0
ACTIVE_JOBS: Dict[str, Job] = {}
# ── Sistema de colas ─────────────────────────────────────────────────
# Cola GLOBAL reservada para usuarios Free
_global_queue_list: list = []
_global_queue_lock: asyncio.Lock = asyncio.Lock()
_global_queue_event: asyncio.Event = asyncio.Event()
_global_worker_task: Optional[asyncio.Task] = None
_global_currently_processing: Optional[str] = None
# Colas separadas por plan: basic / pro / premium / grupos
_user_queues: Dict[str, dict] = {} # queue_key -> {"list": [], "lock": Lock, "event": Event, "worker": Task|None, "processing": str|None}
PLAN_QUEUE_LABELS = {
"free": "🆓 Cola Free",
"basic": "⭐ Cola Basic",
"pro": "💎 Cola Pro",
"premium": "👑 Cola Premium",
"group": "🏘️ Cola de Grupos",
}
QUEUE_PLANS_WITH_PRIVATE_LANES = {"basic", "pro", "premium", "admin", "superadmin"}
PENDING_CONFIRM: Dict[str, tuple] = {}
REPORTS: list = []
LOG_CHAT_ID: Optional[int] = None
LOG_VIDEOS: bool = True
def _queue_base_key(queue_key: str) -> str:
if not queue_key:
return "free"
return queue_key.split(":", 1)[0]
def _plan_queue_key(plan_key: str, in_group: bool = False, uid: Optional[int] = None) -> str:
if in_group:
return "group"
if INDIVIDUAL_QUEUES_ENABLED and plan_key in QUEUE_PLANS_WITH_PRIVATE_LANES:
if uid is not None:
return f"{plan_key}:{uid}"
return plan_key
return "free"
def _plan_queue_label(queue_key: str) -> str:
base_key = _queue_base_key(queue_key)
base_label = PLAN_QUEUE_LABELS.get(base_key, f"🧵 Cola {base_key.title()}")
if ":" not in queue_key:
return base_label
_, owner_id = queue_key.split(":", 1)
if owner_id.isdigit():
return f"{base_label} · Usuario {owner_id}"
return base_label
def _queue_snapshot_counts() -> Dict[str, int]:
counts = {"free": len(_global_queue_list), "basic": 0, "pro": 0, "premium": 0, "group": 0}
for key, uq in _user_queues.items():
base_key = _queue_base_key(key)
counts[base_key] = counts.get(base_key, 0) + len(uq.get("list", [])) + (1 if uq.get("processing") else 0)
return counts
def _user_plan_queue_keys(plan_key: str, in_group: bool = False, uid: Optional[int] = None) -> List[str]:
queue_key = _plan_queue_key(plan_key, in_group, uid)
keys = [queue_key]
if uid is None and INDIVIDUAL_QUEUES_ENABLED and plan_key in QUEUE_PLANS_WITH_PRIVATE_LANES:
prefix = f"{plan_key}:"
keys.extend(sorted(k for k in _user_queues.keys() if k.startswith(prefix)))
return list(dict.fromkeys(keys))
# ─── BOTONES ────────────────────────────────────────────────────────
def _cancel_markup(job_id: str) -> InlineKeyboardMarkup:
"""Botón cancelar en rojo usando URL vacía trick — usa inline button con emoji rojo."""
return InlineKeyboardMarkup([[
InlineKeyboardButton("🔴 Cancelar", callback_data=f"cancel:{job_id}")
]])
def _queue_markup(job_id: str) -> InlineKeyboardMarkup:
return InlineKeyboardMarkup([
[InlineKeyboardButton("📋 Mi posición en cola", callback_data=f"vcola:{job_id}")],
[InlineKeyboardButton("🔴 Cancelar", callback_data=f"cancel:{job_id}")],
])
def _confirm_markup(key: str) -> InlineKeyboardMarkup:
return InlineKeyboardMarkup([[
InlineKeyboardButton("✅ Comprimir", callback_data=f"cyes:{key}"),
InlineKeyboardButton("🔴 No comprimir", callback_data=f"cno:{key}"),
]])
def _quality_menu_markup(uid: int = None) -> InlineKeyboardMarkup:
"""Menú de calidades con botones."""
buttons = []
row = []
for key, preset in QUALITY_PRESETS.items():
label = preset["label"]
row.append(InlineKeyboardButton(f"📺 {label}", callback_data=f"setq:{key}"))
if len(row) == 1:
buttons.append(row)
row = []
if row:
buttons.append(row)
buttons.append([InlineKeyboardButton("🔴 Cancelar", callback_data="qcancel")])
return InlineKeyboardMarkup(buttons)
async def _terminate_process(proc: Optional[asyncio.subprocess.Process], timeout: float = 5.0):
if not proc or proc.returncode is not None:
return
with contextlib.suppress(Exception):
proc.terminate()
try:
await asyncio.wait_for(proc.wait(), timeout=timeout)
return
except Exception:
pass
with contextlib.suppress(Exception):
proc.kill()
with contextlib.suppress(Exception):
await asyncio.wait_for(proc.wait(), timeout=timeout)
def _job_touch(job: Optional[Job], *, stage: Optional[str] = None, progress: Optional[float] = None):
if not job:
return
now = time.time()
job.last_activity_at = now
if stage is not None:
job.stage = stage
if not job.started_at:
job.started_at = now
if progress is not None:
progress = max(0.0, min(100.0, float(progress)))
job.progress_pct = progress
job.progress_bar = _bar(progress / 100.0)
async def _cleanup_job(job: Job):
await _terminate_process(job.process)
job.process = None
job.is_processing = False
job.task = None
for p in list(job.files):
try:
if p and os.path.exists(p):
os.remove(p)
except Exception:
pass
ACTIVE_JOBS.pop(job.job_id, None)
async def _remove_job_from_queues(job_id: str):
async with _global_queue_lock:
for i, item in enumerate(list(_global_queue_list)):
if item[3] == job_id:
return "free", _global_queue_list.pop(i)
for queue_key, uq in _user_queues.items():
async with uq["lock"]:
for i, item in enumerate(list(uq["list"])):
if item[3] == job_id:
return queue_key, uq["list"].pop(i)
return None, None
def _is_job_processing(job_id: str) -> bool:
if _global_currently_processing == job_id:
return True
return any(uq.get("processing") == job_id for uq in _user_queues.values())
def _job_queue_position(job_id: str) -> Optional[tuple[str, int, int]]:
if _global_currently_processing == job_id:
return ("free", 0, max(1, len(_global_queue_list) + 1))
for i, item in enumerate(_global_queue_list, 1):
if item[3] == job_id:
return ("free", i, len(_global_queue_list))
for queue_key, uq in _user_queues.items():
if uq.get("processing") == job_id:
total = len(uq.get("list", [])) + 1
return (queue_key, 0, max(1, total))
for i, item in enumerate(uq.get("list", []), 1):
if item[3] == job_id:
total = len(uq.get("list", [])) + (1 if uq.get("processing") else 0)
return (queue_key, i, max(1, total))
return None
async def _edit_job_status(job: Job, text: str, *, remove_markup: bool = True):
try:
await bot.edit_message_text(
chat_id=job.chat_id,
message_id=job.status_msg_id,
text=text,
reply_markup=None if remove_markup else _cancel_markup(job.job_id),
)
except Exception:
pass
async def _force_finish_job(job: Job, reason: str, *, notify_user: bool = True):
# Usa system_cancelled para que no se confunda con una cancelación del usuario
job.system_cancelled = True
job.is_processing = False
if notify_user:
await _edit_job_status(job, reason, remove_markup=True)
await _cleanup_job(job)
# =====================
# UTILS
# =====================
def _fmt_bytes(n: float) -> str:
for u in ("B", "KB", "MB", "GB", "TB"):
if n < 1024 or u == "TB":
return f"{n:.2f} {u}" if u != "B" else f"{int(n)} B"
n /= 1024
return f"{n:.2f} TB"
def _fmt_eta(s) -> str:
if s is None or s <= 0 or s == float("inf"):
return "—"
m, sec = divmod(int(s), 60)
h, m = divmod(m, 60)
return f"{h}h {m:02d}m {sec:02d}s" if h else (f"{m}m {sec:02d}s" if m else f"{sec}s")
def _bar(p: float, n: int = 14) -> str:
p = max(0.0, min(1.0, float(p)))
f = int(round(p * n))
return "█" * f + "░" * (n - f)
def _fmt_time(s):
return f"{int(s//3600):02}:{int((s%3600)//60):02}:{int(s%60):02}"
def _is_video_doc(doc) -> bool:
if not doc:
return False
mt = getattr(doc, "mime_type", "") or ""
if mt.startswith("video/"):
return True
ext = os.path.splitext((getattr(doc, "file_name", "") or "").lower())[1]
return ext in VIDEO_EXTENSIONS
def _unlim(n) -> str:
return "∞" if n >= 99999 else str(n)
class _Editor:
def __init__(self, msg: Message, job_id=None, every=PROGRESS_EDIT_EVERY):
self.msg = msg
self.job_id = job_id
self.every = max(1, int(every))
self._last = 0.0
self._lock = asyncio.Lock()
async def set(self, text: str, force=False, keep_cancel=None):
now = time.time()
if not force and (now - self._last) < self.every:
return
async with self._lock:
now = time.time()
if not force and (now - self._last) < self.every:
return
if keep_cancel is None:
keep_cancel = bool(self.job_id)
rm = _cancel_markup(self.job_id) if (keep_cancel and self.job_id) else None
try:
await self.msg.edit_text(text, reply_markup=rm)
self._last = now
except Exception:
pass
# =====================
# FFMPEG HELPERS
# =====================
async def _duration(path: str) -> float:
try:
p = await asyncio.create_subprocess_exec(
"ffprobe", "-v", "error", "-show_entries", "format=duration",
"-of", "default=noprint_wrappers=1:nokey=1", path,
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
)
out, _ = await p.communicate()
if p.returncode == 0:
return float(out.decode().strip() or 0)
except Exception:
pass
return 0.0
async def _thumbnail(video: str, dest: str, sec: int = 3) -> bool:
try:
os.makedirs(os.path.dirname(dest) or ".", exist_ok=True)
p = await asyncio.create_subprocess_exec(
"ffmpeg", "-y", "-ss", str(max(0, sec)), "-i", video,
"-vframes", "1", "-vf", "scale=320:-1", "-q:v", "6", dest,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
)
await p.communicate()
return p.returncode == 0 and os.path.exists(dest) and os.path.getsize(dest) > 0
except Exception:
return False
async def _compress(in_f, out_f, uid, status_msg=None, job=None, title=""):
q = await get_user_quality(uid)
label = title or os.path.basename(in_f)
editor = _Editor(status_msg, job_id=(job.job_id if job else None)) if status_msg else None
dur = await _duration(in_f) if status_msg else 0.0
res = q.get("resolution", "854x480")
try:
rw, rh = res.split("x")
rw, rh = int(rw), int(rh)
except Exception:
rw, rh = 854, 480
usable_cpu_ids = _usable_cpu_ids()
usable_cpu_count = len(usable_cpu_ids) or 1
host_cpu_count = psutil.cpu_count(logical=True) or (os.cpu_count() or usable_cpu_count)
cpu_quota_cpus = _cgroup_cpu_quota_cpus()
cpu_capacity = _effective_cpu_capacity()
max_parallel_slots = _max_parallel_cpu_slots()
job_key, active_jobs, slot_index = await _register_active_ffmpeg(job.job_id if job else "")
cpu_subset = _allocate_cpu_subset(usable_cpu_ids, slot_index, active_jobs, max_parallel_slots)
current_cpu_slots = max(1, len(cpu_subset) or 1)
filter_threads = max(1, min(current_cpu_slots, usable_cpu_count))
frame_threads = max(2, min(6, current_cpu_slots))
# Usar flags=+ilme+ildct mejora velocidad en scale; añadir sws_flags para scale rápido
scale_filter = (
f"scale={rw}:{rh}:force_original_aspect_ratio=decrease:flags=fast_bilinear,"
f"scale=trunc(iw/2)*2:trunc(ih/2)*2,"
f"fps={q['fps']}"
)
codec_args = []
if str(q.get("codec", "")).lower() == "libx265":
# pools y frame-threads para máxima velocidad con ultrafast
codec_args = [
"-x265-params",
f"pools={filter_threads}:frame-threads={frame_threads}:wpp=1:pmode=1:pme=1:rd=2:me=hex:subme=2:b-adapt=0:rc-lookahead=5:no-open-gop=1",
"-tune", "fastdecode",
]
cmd = [
"ffmpeg", "-hide_banner", "-nostdin", "-loglevel", "warning", "-i", in_f,
"-vf", scale_filter,
"-filter_threads", str(filter_threads),
"-filter_complex_threads", str(max(1, min(4, filter_threads))),
"-c:v", q["codec"], "-crf", q["crf"], "-preset", q["preset"],
*codec_args,
"-thread_type", "frame+slice",
"-b:a", q["audio_bitrate"],
"-c:a", "aac",
"-ac", "2",
"-movflags", "+faststart",
"-threads", str(max(1, current_cpu_slots)),
"-max_muxing_queue_size", "4096",
"-progress", "pipe:1", "-nostats", "-y", out_f,
]
proc = await asyncio.create_subprocess_exec(*cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if job:
job.process = proc
job.cpu_slots = current_cpu_slots
job.cpu_slots_max = max_parallel_slots
job.cpu_usage_pct = 0.0
job.ffmpeg_last_progress_at = time.time()
job.ffmpeg_last_output_at = time.time()
job.ffmpeg_last_stderr = ""
_job_touch(job, stage="comprimiendo", progress=0)
out_time_ms = 0
now0 = time.time()
last_progress_at = now0
last_output_at = now0
last_stderr_at = now0
stderr_tail = deque(maxlen=80)
t0 = now0
ffmpeg_cpu_pct_total = 0.0
ffmpeg_cpu_pct_quota = 0.0
proc_cpu_raw = 0.0
input_size_mb = 0.0
with contextlib.suppress(Exception):
input_size_mb = max(0.0, os.path.getsize(in_f) / (1024 * 1024))
dynamic_start_grace = max(COMPRESS_START_GRACE_SECONDS, min(300, int(input_size_mb * 0.35) + int(dur * 0.02 if dur else 0)))
dynamic_stall_limit = max(COMPRESS_STALL_SECONDS, min(1200, int(dur * 0.12) if dur else 0))
async def _read_stdout():
nonlocal out_time_ms, last_progress_at, last_output_at
async for line in proc.stdout:
last_output_at = time.time()
if job:
job.ffmpeg_last_output_at = last_output_at
s = line.decode("utf-8", errors="replace").strip()
if "=" not in s:
continue
k, v = s.split("=", 1)
if k == "out_time_ms":
try:
new_out_time_ms = int(v)
if new_out_time_ms >= out_time_ms:
out_time_ms = new_out_time_ms
last_progress_at = time.time()
if job:
job.ffmpeg_last_progress_at = last_progress_at
except Exception:
pass
elif k == "progress" and v == "end":
last_progress_at = time.time()
if job:
job.ffmpeg_last_progress_at = last_progress_at
break
async def _read_stderr():
nonlocal last_output_at, last_stderr_at
while True:
line = await proc.stderr.readline()
if not line:
break
last_output_at = time.time()
last_stderr_at = last_output_at
decoded = line.decode("utf-8", errors="replace").strip()
stderr_tail.append(decoded)
if job:
job.ffmpeg_last_output_at = last_output_at
job.ffmpeg_last_stderr = decoded[:300]
async def _cpu_guard():
nonlocal ffmpeg_cpu_pct_total, ffmpeg_cpu_pct_quota, current_cpu_slots, cpu_subset, active_jobs, proc_cpu_raw
if proc.pid is None:
return
try:
ps_proc = psutil.Process(proc.pid)
except Exception:
return
def _apply_affinity(subset: List[int]):
nonlocal cpu_subset, current_cpu_slots
if not subset:
return
with contextlib.suppress(Exception):
ps_proc.cpu_affinity(subset)
cpu_subset = subset
current_cpu_slots = max(1, len(subset))
_apply_affinity(cpu_subset)
with contextlib.suppress(Exception):
ps_proc.cpu_percent(None)
await asyncio.sleep(0.5)
while proc.returncode is None:
try:
try:
active_now = await _active_ffmpeg_count()
except Exception:
active_now = active_jobs
active_now = max(1, int(active_now) or 1)
if active_now != active_jobs:
active_jobs = active_now
new_subset = _allocate_cpu_subset(usable_cpu_ids, slot_index, active_jobs, max_parallel_slots)
if new_subset and new_subset != cpu_subset:
_apply_affinity(new_subset)
proc_cpu_raw = ps_proc.cpu_percent(None)
ffmpeg_cpu_pct_total = max(0.0, min(100.0, proc_cpu_raw / max(1, host_cpu_count)))
ffmpeg_cpu_pct_quota = max(0.0, min(100.0, proc_cpu_raw / max(1.0, cpu_capacity)))
if job:
job.cpu_usage_pct = ffmpeg_cpu_pct_total
job.cpu_slots = current_cpu_slots
job.cpu_slots_max = max_parallel_slots
job.ffmpeg_last_output_at = max(job.ffmpeg_last_output_at or 0.0, last_output_at)
_job_touch(job, stage="comprimiendo", progress=(job.progress_pct if job else None))
except Exception:
pass
await asyncio.sleep(CPU_MONITOR_INTERVAL)
rt_out = asyncio.create_task(_read_stdout())
rt_err = asyncio.create_task(_read_stderr())
wt = asyncio.create_task(proc.wait())
cpu_guard_task = asyncio.create_task(_cpu_guard())
try:
while not wt.done():
if job and (job.cancelled or job.system_cancelled):
raise asyncio.CancelledError()
now = time.time()
elapsed = now - t0
progress_idle = now - last_progress_at
output_idle = now - max(last_output_at, last_stderr_at, last_progress_at)
no_progress_yet = out_time_ms <= 0
cpu_looks_idle = proc_cpu_raw < STALL_CPU_FLOOR_PERCENT
if no_progress_yet:
if elapsed > dynamic_start_grace and output_idle > FFMPEG_OUTPUT_IDLE_SECONDS and cpu_looks_idle:
raise RuntimeError("FFmpeg no arrancó bien la compresión y quedó sin actividad.")
else:
if progress_idle > dynamic_stall_limit and output_idle > FFMPEG_OUTPUT_IDLE_SECONDS and cpu_looks_idle:
raise RuntimeError("La compresión quedó atascada sin avance real durante demasiado tiempo.")
await asyncio.sleep(PROGRESS_EDIT_EVERY)
ds = out_time_ms / 1_000_000 if out_time_ms else 0.0
p = (ds / dur) if dur > 0 else 0.0
if job:
_job_touch(job, stage="comprimiendo", progress=(p * 100.0))
if editor:
el = time.time() - t0
sp = ds / el if el > 0 else 0.0
eta = (dur - ds) / sp if sp > 0 and dur > 0 else None
cpu_slots_txt = len(cpu_subset) if cpu_subset else current_cpu_slots
quota_txt = "sin límite" if cpu_quota_cpus is None else f"{cpu_quota_cpus:.2f}"
await editor.set(
(f"🎬 `{label}`\n" if label else "") +
f"🗜️ **Comprimiendo...**\n"
f"{_bar(p)} `{p*100:5.1f}%`\n"
f"⏱️ Procesado: `{_fmt_eta(ds)}` / `{_fmt_eta(dur)}`\n"
f"⚡ Velocidad: `{sp:.2f}x`\n"
f"🧠 CPU: `{cpu_slots_txt} cores` | FFmpeg: `{ffmpeg_cpu_pct_total:.1f}%` host / `{ffmpeg_cpu_pct_quota:.1f}%` cuota\n"
f"🛡️ Tope(host): `{MAX_CPU_PERCENT}%` | Pool: `{max_parallel_slots}` | Jobs: `{active_jobs}`\n"
f"🧩 Cuota cgroup: `{quota_txt}` CPU | Capacidad: `{cpu_capacity:.2f}`\n"
f"🧯 Stall: `{int(progress_idle)}s/{dynamic_stall_limit}s` | Salida: `{int(output_idle)}s/{FFMPEG_OUTPUT_IDLE_SECONDS}s`\n"
f"⏳ ETA: `{_fmt_eta(eta)}`"
)
await wt
except asyncio.CancelledError:
await _terminate_process(proc)
raise
except Exception:
await _terminate_process(proc)
raise
finally:
cpu_guard_task.cancel()
for task in (rt_out, rt_err, cpu_guard_task):
with contextlib.suppress(asyncio.CancelledError, Exception):
await task
await _unregister_active_ffmpeg(job_key)
if job:
job.cpu_usage_pct = 0.0
job.cpu_slots = 0
job.cpu_slots_max = 0
if proc.returncode != 0:
# Si el trabajo fue cancelado (usuario o sistema), ffmpeg termina con -15/143; no es un error real
if job and (job.cancelled or job.system_cancelled):
raise asyncio.CancelledError()
err = "\n".join([x for x in stderr_tail if x][-8:]) or "FFmpeg terminó con error."
if proc.returncode in (-9, 137):
err = "El proceso de compresión fue terminado por el sistema (memoria/recursos insuficientes)."
elif proc.returncode in (-15, 143):
err = "La compresión fue detenida antes de terminar. Revisa watchdog, reinicios del hosting o falta de recursos."
raise RuntimeError(err)
if not os.path.exists(out_f) or os.path.getsize(out_f) == 0:
raise RuntimeError("No se generó el archivo comprimido.")
return proc.returncode
async def _download(client, message, dst, editor, job=None, title=""):
t0 = time.time()
last_ui_at = 0.0
last_speed_at = t0
last_speed_bytes = 0
smoothed_speed = 0.0
async def _cb(cur, tot):
nonlocal last_ui_at, last_speed_at, last_speed_bytes, smoothed_speed
if job and (job.cancelled or job.system_cancelled):
raise asyncio.CancelledError()
now = time.time()
dt_speed = now - last_speed_at
if dt_speed >= TRANSFER_SPEED_WINDOW_SECONDS or (tot and cur >= tot):
delta_bytes = max(0, int(cur) - int(last_speed_bytes))
inst_speed = (delta_bytes / dt_speed) if dt_speed > 0 else 0.0
if inst_speed > 0:
smoothed_speed = inst_speed if smoothed_speed <= 0 else (smoothed_speed * 0.35) + (inst_speed * 0.65)
last_speed_at = now
last_speed_bytes = int(cur)
elapsed = max(0.001, now - t0)
sp = smoothed_speed if smoothed_speed > 0 else (cur / elapsed)
p = cur / tot if tot else 0
eta = (tot - cur) / sp if sp > 0 and tot else None
if job:
_job_touch(job, stage="descargando", progress=(p * 100.0))
if (now - last_ui_at) < TRANSFER_PROGRESS_MIN_INTERVAL and not (tot and cur >= tot):
return
last_ui_at = now
await editor.set(
(f"🎬 `{title}`\n" if title else "") +
f"📥 **Descargando...**\n"
f"{_bar(p)} `{p*100:5.1f}%`\n"
f"📦 {_fmt_bytes(cur)} / {_fmt_bytes(tot)}\n"
f"⚡ {_fmt_bytes(sp)}/s\n"
f"⏳ ETA: `{_fmt_eta(eta)}`",
force=bool(tot and cur >= tot),
)
await editor.set("📥 **Descargando...**\n" + _bar(0) + " `0.0%`", force=True)
await message.download(file_name=dst, progress=_cb)
await editor.set("✅ **Descarga completa.**\n" + _bar(1) + " `100%`", force=True)
# =====================
# COLA GLOBAL (para free)
# =====================
async def _ensure_global_worker():
global _global_worker_task
try:
loop = asyncio.get_running_loop()
except RuntimeError:
return
if _global_worker_task is None or _global_worker_task.done():
_global_worker_task = loop.create_task(_global_worker())
async def _global_worker():
global _global_currently_processing
while True:
await _global_queue_event.wait()
async with _global_queue_lock:
if not _global_queue_list:
_global_queue_event.clear()
continue
item = _global_queue_list.pop(0)
client, msg, status_msg, job_id = item
_global_currently_processing = job_id
try:
job = ACTIVE_JOBS.get(job_id)
if not job or job.cancelled or job.system_cancelled:
try:
await status_msg.edit_text("❌ **Cancelado.**\nTu video fue eliminado de la cola.", reply_markup=None)
except Exception:
pass
if job:
await _cleanup_job(job)
continue
job.is_processing = True
job.queue_name = "free"
_job_touch(job, stage="en cola", progress=job.progress_pct)
await _process(client, msg, status_msg=status_msg, job=job)
except asyncio.CancelledError:
job = ACTIVE_JOBS.get(job_id)
if job and job.cancelled:
logger.info("Global worker: cancelacion de usuario para job %s.", job_id)
else:
logger.warning("Global worker: cancelacion de sistema para job %s, continuando.", job_id)
except Exception as exc:
logger.exception("Global worker error: %s", exc)
finally:
_global_currently_processing = None
if _global_queue_list:
_global_queue_event.set()
# =====================
# COLAS POR PLAN (basic / pro / premium / groups)
# =====================
def _get_user_queue(queue_key: str) -> dict:
"""Obtiene o crea la estructura de cola para un plan o grupos."""
if queue_key not in _user_queues:
_user_queues[queue_key] = {
"list": [],
"lock": asyncio.Lock(),
"event": asyncio.Event(),
"worker": None,
"processing": None,
}
return _user_queues[queue_key]
async def _ensure_user_worker(queue_key: str):
uq = _get_user_queue(queue_key)
try:
loop = asyncio.get_running_loop()
except RuntimeError:
return
if uq["worker"] is None or uq["worker"].done():
uq["worker"] = loop.create_task(_user_worker(queue_key))
async def _user_worker(queue_key: str):
"""Worker dedicado para una cola de plan."""
uq = _get_user_queue(queue_key)
while True:
await uq["event"].wait()
async with uq["lock"]:
if not uq["list"]:
uq["event"].clear()
continue
item = uq["list"].pop(0)
client, msg, status_msg, job_id = item
uq["processing"] = job_id
try:
job = ACTIVE_JOBS.get(job_id)
if not job or job.cancelled or job.system_cancelled:
try:
await status_msg.edit_text("❌ **Cancelado.**", reply_markup=None)
except Exception:
pass
if job:
await _cleanup_job(job)
continue
job.is_processing = True
job.queue_name = queue_key
_job_touch(job, stage="en cola", progress=job.progress_pct)
await _process(client, msg, status_msg=status_msg, job=job)
except asyncio.CancelledError:
job = ACTIVE_JOBS.get(job_id)
if job and job.cancelled:
logger.info("Worker %s: cancelacion de usuario para job %s.", queue_key, job_id)
else:
logger.warning("Worker %s: cancelacion de sistema para job %s, continuando.", queue_key, job_id)
except Exception as exc:
logger.exception("Worker %s error: %s", queue_key, exc)
finally:
uq["processing"] = None
if uq["list"]:
uq["event"].set()
# =====================
# PROCESO PRINCIPAL
# =====================
async def _process(client, message: Message, status_msg: Message = None, job: Job = None):
if job:
job.task = asyncio.current_task()
editor = _Editor(status_msg, job_id=(job.job_id if job else None))
uid = message.from_user.id
cid = message.chat.id
media = message.video or message.document
in_group = cid != uid and await is_authorized_group(cid)
can, used, limit = await check_daily_limit(uid, cid)
if not can:
await editor.set(
f"⛔ **Límite diario alcanzado**\n\n"
f"📊 Usados hoy: `{used}` / `{_unlim(limit)}`\n"
f"💡 Cambia tu plan: /planes",
force=True, keep_cancel=False
)
return
if not in_group:
plan_info = await get_plan_info(uid)
max_mb = plan_info["max_file_size_mb"]
size_b = getattr(media, "file_size", 0) or 0
size_mb = size_b / (1024 * 1024)
if size_mb > max_mb and max_mb < 99999:
await editor.set(
f"⛔ **Video demasiado grande**\n\n"
f"📦 Tamaño: `{size_mb:.1f} MB`\n"
f"🔒 Límite de tu plan: `{max_mb} MB`\n\n"
f"💡 Actualiza tu plan: /planes",
force=True, keep_cancel=False
)
return
raw_name = getattr(media, "file_name", None) or f"{getattr(media,'file_id','vid')}.mp4"
base, _ = os.path.splitext(raw_name)
safe = re.sub(r"[^\w\-_. ]", "_", base)
fname = f"{safe}.mp4"
in_f = os.path.join(DOWNLOADS_DIR, f"{message.chat.id}_{message.id}_{fname}")
out_f = os.path.join(COMPRESSED_DIR, f"{message.chat.id}_{message.id}_{fname}")
thumb = None
if job:
job.files += [in_f, out_f]
job.fname = getattr(media, 'file_name', fname) or fname
job.stage = 'descargando'
job.is_processing = True
job.started_at = time.time()
job.last_activity_at = job.started_at
job.upload_started_at = 0.0
job.upload_last_progress_at = 0.0
job.upload_completed_at = 0.0
job.upload_last_bytes = 0
job.upload_total_bytes = 0
try:
await _download(client, message, in_f, editor, job=job, title=fname)
dur = await _duration(in_f)
if dur <= 0:
await editor.set(
"⚠️ **Archivo roto o incompleto**\n\n"
"El video no se pudo leer correctamente.\n"
"Intenta reenviarlo o usa otro formato.",
force=True
)
return
orig_mb = os.path.getsize(in_f) / (1024 * 1024)
t0 = time.time()
await editor.set(
f"🎬 `{fname}`\n"
f"🗜️ **Iniciando compresión...**\n"
+ _bar(0) + " `0.0%`",
force=True
)
if job:
_job_touch(job, stage='comprimiendo', progress=0)
rc = await _compress(in_f, out_f, uid, status_msg=status_msg, job=job, title=fname)
elapsed = time.time() - t0
if rc != 0:
await editor.set("⭕ Error al comprimir.", force=True)
return
comp_mb = os.path.getsize(out_f) / (1024 * 1024)
saved = orig_mb - comp_mb
pct = saved / orig_mb * 100 if orig_mb > 0 else 0
video_dur = 0
try:
video_dur = int((message.video.duration if message.video and message.video.duration else None) or await _duration(out_f) or dur)
except Exception:
video_dur = int(dur)
try:
sec = random.randint(1, min(10, max(1, video_dur - 1)))
thumb = os.path.join(DOWNLOADS_DIR, f"th_{message.chat.id}_{message.id}.jpg")
if not await _thumbnail(out_f, thumb, sec):
thumb = None
except Exception:
thumb = None
ratio_icon = "🟢" if pct >= 50 else ("🟡" if pct >= 20 else "🔴")
caption = (
"✅ **Compresión completada**\n"
"━━━━━━━━━━━━━━━━━━━━━\n"
f"📦 Original: `{orig_mb:.2f} MB`\n"
f"🗜️ Comprimido: `{comp_mb:.2f} MB`\n"
f"{ratio_icon} Reducción: `{saved:.2f} MB ({pct:.1f}%)`\n"
"━━━━━━━━━━━━━━━━━━━━━\n"
f"⏱️ Proceso: `{_fmt_time(elapsed)}`\n"
f"🎞️ Duración: `{_fmt_time(video_dur)}`\n"
"━━━━━━━━━━━━━━━━━━━━━\n"
"♠ ¡Que lo disfrutes! ♣"
)
upload_heartbeat_task = None
if job:
now_upload = time.time()
job.upload_started_at = now_upload
job.upload_last_progress_at = now_upload
job.upload_completed_at = 0.0
job.upload_last_bytes = 0
job.upload_total_bytes = 0
_job_touch(job, stage='subiendo', progress=0)
await editor.set(
f"📤 **Subiendo video...**\n🎬 `{fname}`\nPor favor espera...",
force=True, keep_cancel=False
)
up_t = time.time()
async def _upload_heartbeat():
while True:
await asyncio.sleep(UPLOAD_HEARTBEAT_EVERY)
if job and not job.cancelled and not job.system_cancelled and job.stage in {"subiendo", "finalizando"}:
_job_touch(job, stage=job.stage, progress=job.progress_pct)
up_last_ui_at = 0.0
up_last_speed_at = up_t
up_last_speed_bytes = 0
up_smoothed_speed = 0.0
async def _up_cb(cur, tot):
nonlocal up_last_ui_at, up_last_speed_at, up_last_speed_bytes, up_smoothed_speed
if job and (job.cancelled or job.system_cancelled):
raise asyncio.CancelledError()
now = time.time()
dt_speed = now - up_last_speed_at
if dt_speed >= TRANSFER_SPEED_WINDOW_SECONDS or (tot and cur >= tot):
delta_bytes = max(0, int(cur) - int(up_last_speed_bytes))
inst_speed = (delta_bytes / dt_speed) if dt_speed > 0 else 0.0
if inst_speed > 0:
up_smoothed_speed = inst_speed if up_smoothed_speed <= 0 else (up_smoothed_speed * 0.35) + (inst_speed * 0.65)
up_last_speed_at = now
up_last_speed_bytes = int(cur)
elapsed = max(0.001, now - up_t)
sp = up_smoothed_speed if up_smoothed_speed > 0 else (cur / elapsed)
p = cur / tot if tot else 0
eta = (tot - cur) / sp if sp > 0 and tot else None
if job:
job.upload_last_progress_at = now
job.upload_last_bytes = int(cur or 0)
job.upload_total_bytes = int(tot or 0)
_job_touch(job, stage="subiendo", progress=(p * 100.0))
if (now - up_last_ui_at) < TRANSFER_PROGRESS_MIN_INTERVAL and not (tot and cur >= tot):
return
up_last_ui_at = now
await editor.set(
f"📤 **Subiendo...**\n{_bar(p)} `{p*100:5.1f}%`\n"
f"📦 {_fmt_bytes(cur)} / {_fmt_bytes(tot)}\n"
f"⚡ {_fmt_bytes(sp)}/s\n"
f"⏳ ETA: `{_fmt_eta(eta)}`",
keep_cancel=False,
force=bool(tot and cur >= tot),
)
upload_heartbeat_task = asyncio.create_task(_upload_heartbeat())
try:
await client.send_video(
message.chat.id, out_f,
caption=caption,
duration=video_dur,
thumb=thumb,
supports_streaming=True,
reply_to_message_id=message.id,
progress=_up_cb,
)
finally:
if upload_heartbeat_task:
upload_heartbeat_task.cancel()
with contextlib.suppress(asyncio.CancelledError, Exception):
await upload_heartbeat_task
if job:
job.upload_completed_at = time.time()
_job_touch(job, stage='finalizando', progress=100.0)
await editor.set(
"✅ **¡Video enviado correctamente!**\n"
"Comprueba el mensaje justo arriba 👆",
force=True, keep_cancel=False
)
await increment_daily_usage(uid)
await log_stat(uid, orig_mb, comp_mb, elapsed)
except asyncio.CancelledError:
explicit_cancel = bool(job and job.cancelled)
system_cancel = bool(job and job.system_cancelled and not job.cancelled)
if explicit_cancel:
try:
if job and ACTIVE_JOBS.get(job.job_id) is job:
await editor.set("❌ **Proceso cancelado.**\nArchivos temporales eliminados.", force=True, keep_cancel=False)
except Exception:
pass
raise
if system_cancel:
# El watchdog ya editó el mensaje; solo re-lanzamos para limpiar el worker
raise
logger.warning("Cancelación inesperada de tarea en etapa final: job=%s stage=%s", getattr(job, "job_id", "?"), getattr(job, "stage", "?"))
try:
await editor.set(
"⭕ **La subida final se interrumpió inesperadamente.**\n\n"
"La compresión sí terminó, pero Telegram o el worker cortaron el envío al final.\n"
"Vuelve a probar el video.",
force=True, keep_cancel=False
)
except Exception:
pass
return
except Exception as e:
logger.error("Error proceso: %s", e)
try:
await editor.set(
f"⭕ **Error en el proceso**\n\n"
f"`{str(e)[:120]}`\n\n"
"Intenta reenviar el video.",
force=True, keep_cancel=False
)
except Exception:
pass
finally:
if job:
job.task = None
await _cleanup_job(job)
else:
for p in (in_f, out_f, thumb):
try:
if p and os.path.exists(p):
os.remove(p)
except Exception:
pass
# =====================
# BOT CLIENT
# =====================
bot = Client("compresultra01", api_id=API_ID, api_hash=API_HASH, bot_token=BOT_TOKEN, workdir=SESSION_DIR)
# =====================
# LOGS HELPER
# =====================
async def _log(text: str, is_video: bool = False):
if not LOG_CHAT_ID:
return
if is_video and not LOG_VIDEOS:
return
try:
await bot.send_message(LOG_CHAT_ID, text, disable_notification=True)
except Exception as e:
logger.warning("Log send failed: %s", e)
async def _log_video(msg, uid: int, cid: int, fname: str, size_mb: float, plan_name: str):
if not LOG_CHAT_ID or not LOG_VIDEOS:
return
caption = (
"Video recibido\n"
"ID: " + str(uid) + " | Chat: " + str(cid) + "\n"
"Archivo: " + fname + " - " + f"{size_mb:.1f}" + " MB\n"
"Plan: " + plan_name
)
try:
await bot.copy_message(
chat_id=LOG_CHAT_ID,
from_chat_id=msg.chat.id,
message_id=msg.id,
caption=caption,
disable_notification=True,
)
except Exception:
try:
await bot.send_message(LOG_CHAT_ID, caption, disable_notification=True)
except Exception as exc:
logger.warning("Log video send failed: %s", exc)
# =====================
# ACCESS DENIED
# =====================
_DEV_BTN = InlineKeyboardMarkup([[InlineKeyboardButton("👨💻 Desarrollador", url="https://t.me/Sasuke286")]])
async def _no_access(msg: Message):
await msg.reply_text("⛔ **No tienes acceso.**\nHabla con el desarrollador.", reply_markup=_DEV_BTN)
# ========================
# ENQUEUE OR PROCESS
# ========================
async def _enqueue(client, message: Message, status_msg: Message):
uid = message.from_user.id
cid = message.chat.id
jid = f"{cid}:{message.id}"
in_group = cid != uid and await is_authorized_group(cid)
job = Job(jid, uid, cid, status_msg.id)
ACTIVE_JOBS[jid] = job
# Admins siempre sin cola
if await is_admin(uid):
job.queue_name = "admin-direct"
job.task = asyncio.create_task(_process(client, message, status_msg=status_msg, job=job))
return
plan_key = await get_user_plan(uid)
plan = await get_plan_info(uid)
queue_key = _plan_queue_key(plan_key, in_group, uid)
job.queue_name = queue_key
if queue_key == "free":
await _ensure_global_worker()
async with _global_queue_lock:
item = (client, message, status_msg, jid)
_global_queue_list.append(item)
pos = _global_queue_list.index(item) + 1
total = len(_global_queue_list)
_global_queue_event.set()
queue_text = (
f"🆓 **Cola Free — Posición #{pos} de {total}**\n\n"
f"📋 Plan: {plan['name']}\n"
f"⏳ Esta cola está reservada para usuarios Free.\n\n"
f"✨ Los planes de pago ya no adelantan esta cola."
)
try:
await status_msg.edit_text(queue_text, reply_markup=_queue_markup(jid))
except Exception:
pass
return
uq = _get_user_queue(queue_key)
await _ensure_user_worker(queue_key)
async with uq["lock"]:
item = (client, message, status_msg, jid)
uq["list"].append(item)
pos = len(uq["list"])
total = len(uq["list"]) + (1 if uq["processing"] else 0)
uq["event"].set()
queue_title = _plan_queue_label(queue_key)
if pos == 1 and uq["processing"] is None:
queue_text = (
f"⚡ **{queue_title} — Procesando ahora**\n\n"
f"📋 Plan: {plan['name']}\n"
f"🎬 Tu video es el siguiente en esta cola.\n\n"
f"✨ Cola personal por usuario dentro de tu plan."
)
else:
queue_text = (
f"🧵 **{queue_title} — Posición #{pos} de {total}**\n\n"
f"📋 Plan: {plan['name']}\n"
f"⏳ Esperas solo dentro de tu cola personal.\n\n"
f"✨ Ya no se mezcla ni con Free ni con otros usuarios de pago."
)
try:
await status_msg.edit_text(queue_text, reply_markup=_queue_markup(jid))
except Exception:
pass
# ========================
# COMANDOS BÁSICOS
# ========================
@bot.on_message(filters.command("start") & (filters.private | filters.group))
async def cmd_start(client, msg: Message):
uid = msg.from_user.id
cid = msg.chat.id
if not (await is_authorized_user(uid) or await is_authorized_group(cid)):
await _no_access(msg)
return
plan_key = await get_user_plan(uid)
plan_info = PLANS.get(plan_key, PLANS["free"])
asyncio.create_task(_log(f"🟢 /start — 👤 `{uid}` en chat `{cid}`"))
modo_emoji = "🌐" if BOT_MODE == "public" else "🔒"
modo_txt = "Público" if BOT_MODE == "public" else "Privado"
name = msg.from_user.first_name or "Usuario"
# Botones del menú principal
buttons = InlineKeyboardMarkup([
[
InlineKeyboardButton("👤 Mi Perfil", callback_data="menu:perfil"),
InlineKeyboardButton("📋 Mi Plan", callback_data="menu:plan"),
],
[
InlineKeyboardButton("🎛️ Cambiar Calidad", callback_data="menu:calidad"),
InlineKeyboardButton("📊 Planes", callback_data="menu:planes"),
],
[
InlineKeyboardButton("🧵 Ver Cola", callback_data="menu:cola"),
InlineKeyboardButton("❓ Ayuda", callback_data="menu:help"),
],
[
InlineKeyboardButton("👨💻 Desarrollador", url="https://t.me/Sasuke286"),
InlineKeyboardButton("📝 Reportar", callback_data="menu:reporte"),
],
])
await msg.reply_text(
f"👋 **¡Hola, {name}!**\n\n"
f"🤖 Bienvenido a **CompresUltra Bot** {BOT_VERSION}\n"
f"━━━━━━━━━━━━━━━━━━━━━\n"
f"🗜️ Comprimo tus videos con la **mejor calidad**\n"
f"⚡ Motor: **FFmpeg + libx265**\n"
f"━━━━━━━━━━━━━━━━━━━━━\n"
f"📋 Tu plan: **{plan_info['name']}**\n"
f"{modo_emoji} Modo: **{modo_txt}**\n"
f"━━━━━━━━━━━━━━━━━━━━━\n\n"
f"📌 **Envía un video** como documento o directo para comprimirlo.\n\n"
f"_Usa los botones de abajo para navegar_ 👇",
reply_markup=buttons
)
# ── Callbacks del menú /start ──────────────────────────────────────
@bot.on_callback_query(filters.regex(r"^menu:"))
async def cb_menu(client, cq: CallbackQuery):
action = cq.data.split(":", 1)[1]
uid = cq.from_user.id
cid = cq.message.chat.id
if not (await is_authorized_user(uid) or await is_authorized_group(cid)):
await cq.answer("⛔ Sin acceso.", show_alert=True)
return
if action == "perfil":
await cq.answer()
# Reusar lógica de miperfil
doc = await get_user(uid) or {}
plan_key = await get_user_plan(uid)
plan_info = PLANS.get(plan_key, PLANS["free"])
can, used, limit = await check_daily_limit(uid)
expires_str = doc.get("plan_expires")
if expires_str and plan_key not in ("free", "admin", "superadmin"):
try:
exp_dt = datetime.fromisoformat(expires_str)
days_left = (exp_dt - datetime.utcnow()).days
expiry_line = f"⏳ Plan expira: `{exp_dt.strftime('%Y-%m-%d')}` ({days_left}d)"
except Exception:
expiry_line = ""
elif plan_key == "free":
expiry_line = "⏳ Sin expiración"
else:
expiry_line = ""
await cq.message.reply_text(
f"👤 **Tu Perfil**\n"
"━━━━━━━━━━━━━━━━━━━━━\n"
f"🆔 ID: `{uid}`\n"
f"📋 Plan: **{plan_info['name']}**\n"
+ (expiry_line + "\n" if expiry_line else "") +
"━━━━━━━━━━━━━━━━━━━━━\n"
f"🎬 Compresiones totales: **{doc.get('total_compressions', 0)}**\n"
f"💾 Espacio ahorrado: **{doc.get('total_saved_mb', 0.0):.1f} MB**\n"
"━━━━━━━━━━━━━━━━━━━━━\n"
f"📅 Hoy: {used} / {_unlim(limit)}\n"
f"📦 Tamaño máx: {_unlim(plan_info['max_file_size_mb'])} MB\n"
f"⚡ Cola por plan: {'✅' if plan_info.get('own_queue') else '❌'}\n"
f"🎛️ Calidad personalizada: {'✅' if plan_info['custom_quality'] else '❌'}"
)
elif action == "plan":
await cq.answer()
doc = await get_user(uid) or {}
plan_key = await get_user_plan(uid)
plan_inf = PLANS.get(plan_key, PLANS["free"])
exp_str = doc.get("plan_expires")
if plan_key in ("free", "admin", "superadmin"):
expiry_block = "⏳ Sin fecha de expiración"
elif exp_str:
try:
exp_dt = datetime.fromisoformat(exp_str)
days_left = (exp_dt - datetime.utcnow()).days
if days_left < 0:
expiry_block = "🔴 **Plan expirado**"
elif days_left <= 3:
expiry_block = f"🟠 Expira en **{days_left} días**"
else:
expiry_block = f"🟢 Expira en **{days_left} días** (`{exp_dt.strftime('%Y-%m-%d')}`)"
except Exception:
expiry_block = "⚠️ Fecha no válida"
else:
expiry_block = "⚠️ Sin fecha (contacta al admin)"
can, used, limit = await check_daily_limit(uid)
await cq.message.reply_text(
f"📋 **Tu Plan Actual**\n"
"━━━━━━━━━━━━━━━━━━━━━\n"
f"🏷️ **{plan_inf['name']}**\n"
f"{expiry_block}\n"
"━━━━━━━━━━━━━━━━━━━━━\n"
f"🎬 Videos/día: `{_unlim(plan_inf['daily_videos'])}`\n"
f"📦 Tamaño máx: `{_unlim(plan_inf['max_file_size_mb'])} MB`\n"
f"🎛️ Calidad personalizada: {'✅' if plan_inf['custom_quality'] else '❌'}\n"
f"⚡ Cola por plan: {'✅' if plan_inf.get('own_queue') else '❌'}\n"
"━━━━━━━━━━━━━━━━━━━━━\n"
f"📊 Usados hoy: `{used}` / `{_unlim(limit)}`\n"
"\n💡 Ver todos los planes: /planes"
)
elif action == "calidad":
await cq.answer()
plan_info = await get_plan_info(uid)
if not plan_info.get("custom_quality"):
await cq.answer("⛔ Tu plan no permite calidad personalizada. Usa /planes", show_alert=True)
return
q = await get_user_quality(uid)
# Detectar preset actual
current_preset = "Personalizada"
for pk, pv in QUALITY_PRESETS.items():
pv2 = {k: v for k, v in pv.items() if k != "label"}
if all(q.get(k) == pv2.get(k) for k in pv2):
current_preset = pv["label"]
break
await cq.message.reply_text(
f"🎛️ **Cambiar Calidad de Compresión**\n"
"━━━━━━━━━━━━━━━━━━━━━\n"
f"⚙️ Calidad actual: **{current_preset}**\n"
f"🖥️ Resolución: `{q.get('resolution', '?')}`\n"
f"🎯 CRF: `{q.get('crf', '?')}` | 🎵 Audio: `{q.get('audio_bitrate', '?')}`\n"
"━━━━━━━━━━━━━━━━━━━━━\n"
"📺 **Elige una calidad predefinida:**\n"
"_Todas reducen el tamaño del archivo_",
reply_markup=_quality_menu_markup()
)
elif action == "planes":
await cq.answer()
actual = await get_user_plan(uid)
txt = "📋 **Planes disponibles:**\n\n"
for k, p in PLANS.items():
if k in ("admin", "superadmin"):
continue
m = " ◀ Tu plan" if k == actual else ""
own_q = "✅" if p.get("own_queue") else "❌"
txt += (
f"**{p['name']}**{m}\n"
f" 🎬 Videos/día: {_unlim(p['daily_videos'])}\n"
f" 📦 Tamaño máx: {_unlim(p['max_file_size_mb'])} MB\n"
f" ⚡ Cola por plan: {own_q}\n"
f" 🎛️ Calidad personalizada: {'✅' if p['custom_quality'] else '❌'}\n\n"
)
txt += "💡 Contacta al admin para cambiar tu plan."
await cq.message.reply_text(txt)
elif action == "cola":
await cq.answer()
# Reusar lógica de /cola
await _show_cola_info(cq.message, uid)
elif action == "help":
await cq.answer()
adm = await is_admin(uid)
sadm = await is_super_admin(uid)
txt = _build_help_text(adm, sadm)
await cq.message.reply_text(txt)
elif action == "reporte":
await cq.answer("Usa /reporte [descripción del problema]", show_alert=True)
# ── Callback para seleccionar calidad ──────────────────────────────
@bot.on_callback_query(filters.regex(r"^setq:"))
async def cb_set_quality(client, cq: CallbackQuery):
uid = cq.from_user.id
plan_info = await get_plan_info(uid)
if not plan_info.get("custom_quality"):
await cq.answer("⛔ Tu plan no permite calidad personalizada.", show_alert=True)
return
preset_key = cq.data.split(":", 1)[1]
if preset_key not in QUALITY_PRESETS:
await cq.answer("⭕ Calidad no válida.", show_alert=True)
return
preset = QUALITY_PRESETS[preset_key].copy()
label = preset.pop("label", preset_key)
await set_user_quality(uid, preset)
await cq.answer(f"✅ Calidad cambiada a {label}", show_alert=False)
try:
await cq.message.edit_text(
f"✅ **Calidad actualizada**\n\n"
f"📺 **{label}**\n"
"━━━━━━━━━━━━━━━━━━━━━\n"
f"🖥️ Resolución: `{preset['resolution']}`\n"
f"🎯 CRF: `{preset['crf']}` (menor = mejor calidad)\n"
f"🎵 Audio: `{preset['audio_bitrate']}`\n"
f"🎞️ FPS: `{preset['fps']}`\n"
f"⚡ Preset: `{preset['preset']}`\n"
f"🔧 Codec: `{preset['codec']}`\n"
"━━━━━━━━━━━━━━━━━━━━━\n"
"_Siempre se reduce el tamaño del archivo._\n\n"
"Usa /calidad para volver a cambiar.",
reply_markup=None
)
except Exception:
pass
@bot.on_callback_query(filters.regex(r"^qcancel$"))
async def cb_quality_cancel(client, cq: CallbackQuery):
await cq.answer("Cancelado.")
try:
await cq.message.delete()
except Exception:
pass
@bot.on_message(filters.command("help") & (filters.private | filters.group))
async def cmd_help(client, msg: Message):
uid = msg.from_user.id
cid = msg.chat.id
if not (await is_authorized_user(uid) or await is_authorized_group(cid)):
await _no_access(msg)
return
adm = await is_admin(uid)
sadm = await is_super_admin(uid)
await msg.reply_text(_build_help_text(adm, sadm))
def _build_help_text(adm: bool, sadm: bool) -> str:
txt = (
"🤖 **CompresUltra Bot — Comandos**\n\n"
"**👤 Usuario:**\n"
"/start — 👋 Bienvenida con menú\n"
"/help — 📖 Ver comandos\n"
"/miperfil — 👤 Tu perfil y estadísticas\n"
"/miplan — 📋 Tu plan con días restantes\n"
"/planes — 📊 Ver planes disponibles\n"
"/micalidad — ⚙️ Tu calidad actual\n"
"/calidad — 🎛️ Cambiar calidad (menú visual)\n"
"/cola — 🧵 Ver estado de la cola\n"
"/cancelar — ❌ Cancelar tu compresión\n"
"/reporte [texto] — 📝 Reportar un problema\n"
"/id — 🆔 Ver tu ID\n"
"/about — ℹ️ Info del bot\n"
"/ping — 🏓 Verificar si el bot responde\n"
"/velocidad — ⚡ Test de velocidad\n"
)
if adm:
txt += (
"\n**👨✈️ Admin:**\n"
"/add [id] — ➕ Autorizar usuario\n"
"/ban [id] — 🚫 Desautorizar\n"
"/listusers — 👥 Lista usuarios\n"
"/grup [id] — 🏘️ Autorizar grupo\n"
"/bangrup [id] — 🚫 Desautorizar grupo\n"
"/listgrup — 📗 Lista grupos\n"
"/listadmins — 📓 Lista admins\n"
"/setplan [id] [plan] — 📋 Asignar plan\n"
"/renovar [id] [dias] — 🔄 Renovar plan\n"
"/userinfo [id] — 🔍 Info usuario\n"
"/proxvencer [dias] — ⏰ Planes por vencer\n"
"/stats — 📊 Stats del bot\n"
"/status_bot — 🖥️ Estado del servidor\n"
"/trabajos — 🧰 Ver trabajos activos y en espera\n"
"/diagnostico_cpu — 🧪 Ver límites reales de CPU\n"
"/info [msg] — 📢 Mensaje a autorizados\n"
"/msgusr [id] [msg] — 📨 Mensaje privado\n"
"/reportes — 📋 Ver reportes\n"
"/adelantar [id] — ⚡ Adelantar en cola\n"
"/cancelarcola [id] — 🗑️ Cancelar cola\n"
)
if sadm:
txt += (
"\n**⚡ Super Admin:**\n"
"/modo — 🔒 Ver/cambiar modo del bot\n"
"/colaindividual — 🧵 ON/OFF colas por plan\n"
"/add_admins [id] — 🛡️ Agregar admin\n"
"/ban_admins [id] — 🛡️ Quitar admin\n"
"/add_superadmin [id] — ⚡ Agregar super admin\n"
"/ban_superadmin [id] — ⚡ Quitar super admin\n"
"/listsuperadmins — ⚡ Lista super admins\n"
"/editplan [plan] [campo] [valor] — ✏️ Editar plan\n"
"/verplanes — 📋 Ver todos los planes\n"
"/resetplan [plan] — 🔄 Restaurar plan\n"
"/resetstats [id] — 🔄 Resetear stats\n"
"/broadcast [msg] — 📣 Broadcast global\n"
"/dbstats — 🗄️ Stats Supabase\n"
"/logs — 📡 Config de logs\n"
"/forzarwatchdog — 🛠️ Reparar colas/workers\n"
"/actualizarmenu — 🔄 Actualizar menú\n"
)
return txt
@bot.on_message(filters.command("about") & (filters.private | filters.group))
async def cmd_about(client, msg: Message):
await msg.reply_text(
f"🤖 **CompresUltra Bot**\n\n"
f"📔 Versión: **{BOT_VERSION}**\n"
f"👨💻 Creador: {BOT_CREATOR}\n"
f"🗄️ DB: **Supabase / Postgres — {DB_NAME}**\n"
f"⚡ Motor: **FFmpeg + libx265**\n"
f"🔧 Calidades: 144p a 1080p\n"
f"🧵 Colas separadas por plan\n"
f"🚀 Planes editables, estadísticas y más.\n\n"
f"¡Espero te guste! 🤗",
reply_markup=InlineKeyboardMarkup([[
InlineKeyboardButton("👨💻 Desarrollador", url="https://t.me/Sasuke286"),
InlineKeyboardButton("📊 Stats", callback_data="menu:perfil"),
]])
)
@bot.on_message(filters.command("ping") & (filters.private | filters.group))
async def cmd_ping(client, msg: Message):
t = time.time()
m = await msg.reply_text("🏓 Pong...")
elapsed = (time.time() - t) * 1000
await m.edit_text(f"🏓 **Pong!** `{elapsed:.0f}ms`")
@bot.on_message(filters.command("velocidad") & (filters.private | filters.group))
async def cmd_velocidad(client, msg: Message):
uid = msg.from_user.id
if not (await is_authorized_user(uid) or await is_authorized_group(msg.chat.id)):
await _no_access(msg)
return
m = await msg.reply_text("⚡ Calculando velocidad del servidor...")
t0 = time.time()
proc = await asyncio.create_subprocess_exec(
"ffmpeg", "-f", "lavfi", "-i", "color=c=black:size=640x480:rate=30",
"-t", "2", "-c:v", "libx265", "-preset", "ultrafast", "-crf", "30",
"-f", "null", "-",
stdout=subprocess.DEVNULL, stderr=subprocess.PIPE
)
_, _ = await proc.communicate()
elapsed = time.time() - t0
fps_est = 60 / elapsed if elapsed > 0 else 0
speed = min(fps_est / 30, 10)
await m.edit_text(
f"⚡ **Test de Velocidad**\n\n"
f"🖥️ Tiempo: `{elapsed:.2f}s`\n"
f"🚀 Velocidad estimada: `{speed:.1f}x`\n"
f"🎬 FPS procesados: `{fps_est:.0f}`\n\n"
f"_Basado en compresión de 2s de video 640x480_"
)
@bot.on_message(filters.command("id") & (filters.private | filters.group))
async def cmd_id(client, msg: Message):
uid = msg.from_user.id
cid = msg.chat.id
if not (await is_authorized_user(uid) or await is_authorized_group(cid)):
await _no_access(msg)
return
if msg.reply_to_message and msg.reply_to_message.from_user:
u = msg.reply_to_message.from_user
await msg.reply_text(f"👤 {u.first_name}\n🆔 `{u.id}`\n🔗 @{u.username or 'N/A'}")
elif len(msg.command) > 1:
try:
u = await client.get_users(msg.command[1])
await msg.reply_text(f"👤 {u.first_name}\n🆔 `{u.id}`\n🔗 @{u.username or 'N/A'}")
except Exception as e:
await msg.reply_text(f"⭕ No encontré ese usuario: {e}")
else:
await msg.reply_text(f"🆔 Tu ID: `{uid}`\n💬 Chat ID: `{cid}`")
@bot.on_message(filters.command("miperfil") & (filters.private | filters.group))
async def cmd_miperfil(client, msg: Message):
uid = msg.from_user.id
cid = msg.chat.id
if not (await is_authorized_user(uid) or await is_authorized_group(cid)):
await _no_access(msg)
return
doc = await get_user(uid) or {}
plan_key = await get_user_plan(uid)
plan_info = PLANS.get(plan_key, PLANS["free"])
can, used, limit = await check_daily_limit(uid)
expires_str = doc.get("plan_expires")
if expires_str and plan_key not in ("free", "admin", "superadmin"):
try:
exp_dt = datetime.fromisoformat(expires_str)
days_left = (exp_dt - datetime.utcnow()).days
expiry_line = f"⏳ Plan expira: `{exp_dt.strftime('%Y-%m-%d')}` ({days_left}d)"
except Exception:
expiry_line = ""
elif plan_key == "free":
expiry_line = "⏳ Sin expiración"
else:
expiry_line = ""
await msg.reply_text(
f"👤 **Tu Perfil**\n"
"━━━━━━━━━━━━━━━━━━━━━\n"
f"🆔 ID: `{uid}`\n"
f"📋 Plan: **{plan_info['name']}**\n"
+ (expiry_line + "\n" if expiry_line else "") +
"━━━━━━━━━━━━━━━━━━━━━\n"
f"🎬 Compresiones totales: **{doc.get('total_compressions', 0)}**\n"
f"💾 Espacio ahorrado: **{doc.get('total_saved_mb', 0.0):.1f} MB**\n"
"━━━━━━━━━━━━━━━━━━━━━\n"
f"📅 Hoy: {used} / {_unlim(limit)}\n"
f"📦 Tamaño máx: {_unlim(plan_info['max_file_size_mb'])} MB\n"
f"⚡ Cola por plan: {'✅' if plan_info.get('own_queue') else '❌'}\n"
f"🎛️ Calidad personalizada: {'✅' if plan_info['custom_quality'] else '❌'}"
)
@bot.on_message(filters.command("miplan") & (filters.private | filters.group))
async def cmd_miplan(client, msg: Message):
uid = msg.from_user.id
cid = msg.chat.id
if not (await is_authorized_user(uid) or await is_authorized_group(cid)):
await _no_access(msg)
return
doc = await get_user(uid) or {}
plan_key = await get_user_plan(uid)
plan_inf = PLANS.get(plan_key, PLANS["free"])
exp_str = doc.get("plan_expires")
if plan_key in ("free", "admin", "superadmin"):
expiry_block = "⏳ Sin fecha de expiración"
elif exp_str:
try:
exp_dt = datetime.fromisoformat(exp_str)
days_left = (exp_dt - datetime.utcnow()).days
if days_left < 0:
expiry_block = "🔴 **Plan expirado** (contacta al admin)"
elif days_left == 0:
expiry_block = "🔴 **Expira hoy**"
elif days_left <= 3:
expiry_block = f"🟠 Expira en **{days_left} días** (`{exp_dt.strftime('%Y-%m-%d')}`)"
elif days_left <= 7:
expiry_block = f"🟡 Expira en **{days_left} días** (`{exp_dt.strftime('%Y-%m-%d')}`)"
else:
expiry_block = f"🟢 Expira en **{days_left} días** (`{exp_dt.strftime('%Y-%m-%d')}`)"
except Exception:
expiry_block = "⚠️ Fecha no válida"
else:
expiry_block = "⚠️ Sin fecha configurada (contacta al admin)"
can, used, limit = await check_daily_limit(uid)
await msg.reply_text(
f"📋 **Tu Plan Actual**\n"
"━━━━━━━━━━━━━━━━━━━━━\n"
f"🏷️ **{plan_inf['name']}**\n"
f"{expiry_block}\n"
"━━━━━━━━━━━━━━━━━━━━━\n"
f"🎬 Videos/día: `{_unlim(plan_inf['daily_videos'])}`\n"
f"📦 Tamaño máx: `{_unlim(plan_inf['max_file_size_mb'])} MB`\n"
f"🎛️ Calidad personalizada: {'✅' if plan_inf['custom_quality'] else '❌'}\n"
f"⚡ Cola por plan: {'✅' if plan_inf.get('own_queue') else '❌'}\n"
"━━━━━━━━━━━━━━━━━━━━━\n"
f"📊 Usados hoy: `{used}` / `{_unlim(limit)}`\n"
"\n💡 Ver todos los planes: /planes"
)
@bot.on_message(filters.command("planes") & (filters.private | filters.group))
async def cmd_planes(client, msg: Message):
uid = msg.from_user.id
cid = msg.chat.id
if not (await is_authorized_user(uid) or await is_authorized_group(cid)):
await _no_access(msg)
return
actual = await get_user_plan(uid)
txt = "📋 **Planes disponibles:**\n\n"
for k, p in PLANS.items():
if k in ("admin", "superadmin"):
continue
m = " ◀ Tu plan" if k == actual else ""
own_q = "✅ Cola por plan" if p.get("own_queue") else "❌ Cola Free/global"
txt += (
f"**{p['name']}**{m}\n"
f" 🎬 Videos/día: {_unlim(p['daily_videos'])}\n"
f" 📦 Tamaño máx: {_unlim(p['max_file_size_mb'])} MB\n"
f" ⚡ {own_q}\n"
f" 🎛️ Calidad personalizada: {'✅' if p['custom_quality'] else '❌'}\n\n"
)
txt += "💡 Contacta al admin para cambiar tu plan.\n\n"
txt += "🧵 **¿Qué es la cola separada por plan?**\n"
txt += "_Cada plan tiene su propia cola; Free no se mezcla con Basic/Pro/Premium._"
await msg.reply_text(txt)
@bot.on_message(filters.command("micalidad") & (filters.private | filters.group))
async def cmd_micalidad(client, msg: Message):
uid = msg.from_user.id
cid = msg.chat.id
if not (await is_authorized_user(uid) or await is_authorized_group(cid)):
await _no_access(msg)
return
q = await get_user_quality(uid)
# Detectar preset
current_preset = "Personalizada"
for pk, pv in QUALITY_PRESETS.items():
pv2 = {k: v for k, v in pv.items() if k != "label"}
if all(q.get(k) == pv2.get(k) for k in pv2):
current_preset = pv["label"]
break
await msg.reply_text(
f"⚙️ **Tu calidad actual:**\n\n"
f"📺 **{current_preset}**\n"
"━━━━━━━━━━━━━━━━━━━━━\n"
f"🖥️ Resolución: `{q['resolution']}`\n"
f"🎯 CRF: `{q['crf']}` (menor = mayor calidad)\n"
f"🎵 Audio: `{q['audio_bitrate']}`\n"
f"🎞️ FPS: `{q['fps']}`\n"
f"⚡ Preset: `{q['preset']}`\n"
f"🔧 Codec: `{q['codec']}`\n"
"━━━━━━━━━━━━━━━━━━━━━\n"
"_Para cambiar usa /calidad_"
)
@bot.on_message(filters.command("calidad") & (filters.private | filters.group))
async def cmd_calidad(client, msg: Message):
"""
/calidad — Muestra menú visual con botones de calidad predefinida.
/calidad clave=valor ... — Permite configuración manual avanzada.
"""
uid = msg.from_user.id
cid = msg.chat.id
if not (await is_authorized_user(uid) or await is_authorized_group(cid)):
await _no_access(msg)
return
plan_info = await get_plan_info(uid)
if not plan_info.get("custom_quality"):
await msg.reply_text(
"⛔ **Tu plan no permite calidad personalizada.**\n\n"
"💡 Actualiza tu plan para cambiar la calidad: /planes"
)
return
args = msg.text.split()[1:]
if not args:
# Mostrar menú visual con botones
q = await get_user_quality(uid)
current_preset = "Personalizada"
for pk, pv in QUALITY_PRESETS.items():
pv2 = {k: v for k, v in pv.items() if k != "label"}
if all(q.get(k) == pv2.get(k) for k in pv2):
current_preset = pv["label"]
break
await msg.reply_text(
f"🎛️ **Cambiar Calidad de Compresión**\n"
"━━━━━━━━━━━━━━━━━━━━━\n"
f"⚙️ Calidad actual: **{current_preset}**\n"
f"🖥️ `{q.get('resolution', '?')}` | 🎯 CRF `{q.get('crf', '?')}`\n"
"━━━━━━━━━━━━━━━━━━━━━\n"
"📺 **Selecciona una calidad:**\n"
"_Todas las calidades siempre reducen el tamaño_\n\n"
"🔹 **144p** — Máxima compresión, mínimo tamaño\n"
"🔹 **240p** — Muy ligero, bueno para ahorrar espacio\n"
"🔹 **360p** — Ligero, calidad aceptable\n"
"🔹 **480p** — Equilibrado ⭐ (recomendado)\n"
"🔹 **720p** — HD, buena calidad\n"
"🔹 **1080p** — Full HD, mayor calidad\n\n"
"**Configuración manual avanzada:**\n"
"`/calidad resolution=1280x720 crf=28 fps=30`",
reply_markup=_quality_menu_markup()
)
return
# Configuración manual
q = await get_user_quality(uid)
for arg in args:
if "=" not in arg:
await msg.reply_text(f"⭕ Formato incorrecto: `{arg}`\nUsa `/calidad` sin argumentos para el menú visual.")
return
k, v = arg.split("=", 1)
if k not in q:
await msg.reply_text(f"⭕ Campo desconocido: `{k}`\n**Campos válidos:** resolution, crf, audio_bitrate, fps, preset, codec")
return
q[k] = v
await set_user_quality(uid, q)
await msg.reply_text(
f"✅ **Calidad personalizada actualizada:**\n\n"
f"🖥️ `{q['resolution']}` | 🎯 CRF `{q['crf']}`\n"
f"🎵 `{q['audio_bitrate']}` | 🎞️ `{q['fps']}`fps\n"
f"⚡ `{q['preset']}` | 🔧 `{q['codec']}`\n\n"
"_Usa /calidad sin argumentos para el menú visual._"
)
@bot.on_message(filters.command("cancelar") & (filters.private | filters.group))
async def cmd_cancelar(client, msg: Message):
uid = msg.from_user.id
found = False
async with _global_queue_lock:
to_remove = [i for i, (_, qm, _, _) in enumerate(_global_queue_list) if qm.from_user.id == uid]
for i in reversed(to_remove):
_, _, qstatus, qjid = _global_queue_list.pop(i)
job = ACTIVE_JOBS.get(qjid)
if job:
job.cancelled = True
await _cleanup_job(job)
try:
await qstatus.edit_text("❌ Cancelado de la cola.", reply_markup=None)
except Exception:
pass
found = True
for queue_key, uq in _user_queues.items():
async with uq["lock"]:
to_remove = []
kept = []
for item in uq["list"]:
if item[1].from_user.id == uid:
to_remove.append(item)
else:
kept.append(item)
uq["list"][:] = kept
for _, _, qstatus, qjid in to_remove:
job = ACTIVE_JOBS.get(qjid)
if job:
job.cancelled = True
await _cleanup_job(job)
try:
await qstatus.edit_text(f"❌ Cancelado de la {_plan_queue_label(queue_key).lower()}.", reply_markup=None)
except Exception:
pass
found = True
for job in list(ACTIVE_JOBS.values()):
if job.user_id != uid:
continue
if job.cancelled:
continue
if _is_job_processing(job.job_id) or (job.task and not job.task.done()):
job.cancelled = True
if job.process and job.process.returncode is None:
await _terminate_process(job.process)
if job.task and not job.task.done():
job.task.cancel()
found = True
await msg.reply_text("❌ Cancelando tu compresión..." if found else "ℹ️ No tienes ninguna compresión activa.")
# ========================
# ADMIN COMMANDS
# ========================
@bot.on_message(filters.command("add") & (filters.private | filters.group))
async def cmd_add(client, msg: Message):
if not await is_admin(msg.from_user.id):
await _no_access(msg)
return
args = msg.text.split()[1:]
if not args:
await msg.reply_text(
"📖 **Uso:** `/add user_id [user_id2 ...]`\n\n"
"Autoriza al usuario con plan **Free** por defecto.\n"
"Para asignar otro plan usa: `/setplan user_id plan`\n\n"
"**Planes disponibles:** free, basic, pro, premium"
)
return
res = []
for s in args:
try:
tid = int(s)
doc = await get_user(tid)
if doc and doc.get("authorized"):
res.append(f"⚠️ `{tid}` ya está autorizado.")
else:
await _assign_plan(tid, "free", notify=True,
reason=f"Autorizado por admin `{msg.from_user.id}`")
res.append(f"✅ `{tid}` autorizado (plan Free).")
except ValueError:
res.append(f"⭕ ID inválido: `{s}`")
await msg.reply_text("\n".join(res))
@bot.on_message(filters.command("ban") & (filters.private | filters.group))
async def cmd_ban(client, msg: Message):
if not await is_admin(msg.from_user.id):
await _no_access(msg)
return
args = msg.text.split()[1:]
if not args:
await msg.reply_text("📖 Uso: `/ban user_id`")
return
res = []
for s in args:
try:
tid = int(s)
if await is_super_admin(tid):
res.append(f"⛔ No puedes banear a un super admin.")
continue
old_doc = await get_user(tid)
old_plan = (old_doc or {}).get("plan", "free")
await col_users.update_one({"user_id": tid}, {"$set": {"authorized": False}}, upsert=True)
try:
await bot.send_message(tid,
"⛔ **Tu acceso al bot ha sido revocado.**\n\n"
"Contacta al desarrollador si crees que es un error."
)
except Exception:
pass
res.append(f"✅ `{tid}` desautorizado (era plan {old_plan}).")
except ValueError:
res.append(f"⭕ ID inválido: `{s}`")
await msg.reply_text("\n".join(res))
@bot.on_message(filters.command("listusers") & (filters.private | filters.group))
async def cmd_listusers(client, msg: Message):
if not await is_admin(msg.from_user.id):
await _no_access(msg)
return
users = await col_users.find({"authorized": True}).to_list(300)
if not users:
await msg.reply_text("❌ No hay usuarios autorizados.")
return
def _expiry_txt(u: dict) -> str:
plan = u.get("plan", "free")
if plan in ("free", "admin", "superadmin"):
return ""
exp = u.get("plan_expires")
if not exp:
return " ⚠️ sin fecha"
try:
days_left = (datetime.fromisoformat(exp) - datetime.utcnow()).days
if days_left < 0:
return " 🔴 expirado"
elif days_left <= 3:
return f" 🟠 {days_left}d"
elif days_left <= 7:
return f" 🟡 {days_left}d"
else:
return f" 🟢 {days_left}d"
except Exception:
return ""
lines = ["📘 **Usuarios autorizados:**\n"]
for u in users:
plan_key = u.get("plan", "free")
plan_name = PLANS.get(plan_key, {}).get("name", plan_key)
exp_txt = _expiry_txt(u)
lines.append(f"• `{u['user_id']}` — {plan_name}{exp_txt}")
full = "\n".join(lines)
await _send_long(msg, full)
@bot.on_message(filters.command("grup") & (filters.private | filters.group))
async def cmd_grup(client, msg: Message):
if not await is_admin(msg.from_user.id):
await _no_access(msg)
return
args = msg.text.split()[1:]
if not args:
await msg.reply_text("📖 Uso: `/grup group_id`")
return
res = []
for s in args:
try:
gid = int(s)
await col_groups.update_one({"group_id": gid}, {"$set": {"group_id": gid}}, upsert=True)
try:
chat = await client.get_chat(gid)
gname = getattr(chat, 'title', str(gid)) or str(gid)
except Exception:
gname = str(gid)
res.append(f"✅ Grupo autorizado:\n 🆔 `{gid}`\n 📛 {gname}\n ✅ Sin límites.")
except ValueError:
res.append(f"⭕ ID inválido: `{s}`")
await msg.reply_text("\n".join(res))
@bot.on_message(filters.command("bangrup") & (filters.private | filters.group))
async def cmd_bangrup(client, msg: Message):
if not await is_admin(msg.from_user.id):
await _no_access(msg)
return
args = msg.text.split()[1:]
if not args:
await msg.reply_text("📖 Uso: `/bangrup group_id`")
return
res = []
for s in args:
try:
gid = int(s)
await col_groups.delete_one({"group_id": gid})
res.append(f"✅ Grupo `{gid}` desautorizado.")
except ValueError:
res.append(f"⭕ ID inválido: `{s}`")
await msg.reply_text("\n".join(res))
@bot.on_message(filters.command("listgrup") & (filters.private | filters.group))
async def cmd_listgrup(client, msg: Message):
if not await is_admin(msg.from_user.id):
await _no_access(msg)
return
groups = await col_groups.find({}).to_list(300)
if not groups:
await msg.reply_text("❌ No hay grupos autorizados.")
return
lines = ["📗 **Grupos autorizados:**\n", "_✅ Sin límites de tamaño ni videos diarios_\n"]
for g in groups:
gid = g['group_id']
try:
chat = await client.get_chat(gid)
gname = getattr(chat, 'title', str(gid)) or str(gid)
except Exception:
gname = str(gid)
lines.append(f"• `{gid}` — {gname}")
await msg.reply_text("\n".join(lines))
@bot.on_message(filters.command("listadmins") & (filters.private | filters.group))
async def cmd_listadmins(client, msg: Message):
if not await is_admin(msg.from_user.id):
await _no_access(msg)
return
admins = await col_admins.find({}).to_list(200)
if not admins:
await msg.reply_text("❌ No hay admins.")
return
lines = ["📓 **Administradores:**\n"]
for a in admins:
mark = " ⚡" if a["user_id"] in SUPER_ADMINS_STATIC else ""
lines.append(f"• `{a['user_id']}`{mark}")
await msg.reply_text("\n".join(lines))
@bot.on_message(filters.command("setplan") & (filters.private | filters.group))
async def cmd_setplan(client, msg: Message):
if not await is_admin(msg.from_user.id):
await _no_access(msg)
return
args = msg.text.split()[1:]
if len(args) < 2:
valid = ", ".join(k for k in PLANS if k not in ("admin","superadmin"))
await msg.reply_text(
f"📖 **Uso:** `/setplan user_id plan [dias]`\n\n"
f"**Planes:** {valid}\n"
f"**Días por defecto:** {PLAN_EXPIRY_DAYS}\n\n"
"Ejemplos:\n"
"`/setplan 123456 pro` — 30 días\n"
"`/setplan 123456 premium 60` — 60 días\n"
"`/setplan 123456 free` — Sin expiración"
)
return
try:
tid = int(args[0])
pk = args[1].lower()
days = int(args[2]) if len(args) > 2 else None
if pk not in PLANS or pk in ("admin","superadmin"):
await msg.reply_text("⭕ Plan inválido.")
return
await _assign_plan(
tid, pk, days=days, notify=True,
reason=f"Asignado por admin `{msg.from_user.id}`"
)
expiry_days = days if days is not None else (PLAN_EXPIRY_DAYS if pk != "free" else None)
expiry_txt = f"{expiry_days} días" if expiry_days else "Sin expiración"
await msg.reply_text(
f"✅ **Plan actualizado**\n\n"
f"👤 Usuario: `{tid}`\n"
f"📋 Plan: **{PLANS[pk]['name']}**\n"
f"⏳ Duración: {expiry_txt}\n\n"
f"_El usuario ha sido notificado._"
)
asyncio.create_task(_log(
f"📋 /setplan — Admin `{msg.from_user.id}` → usuario `{tid}`: {pk} ({expiry_txt})"
))
except ValueError:
await msg.reply_text("⭕ ID o días inválido.")
@bot.on_message(filters.command("renovar") & filters.private)
async def cmd_renovar(client, msg: Message):
if not await is_admin(msg.from_user.id):
await _no_access(msg)
return
args = msg.text.split()[1:]
if len(args) < 2:
await msg.reply_text(
"📖 **Uso:** `/renovar user_id dias`\n\n"
"Establece o extiende la expiración del plan.\n\n"
"**Ejemplos:**\n"
"`/renovar 123456 30` — 30 días desde hoy\n"
"`/renovar 123456 +15` — añadir 15 días"
)
return
try:
tid = int(args[0])
dias_str = args[1]
extend = dias_str.startswith("+")
dias = int(dias_str.lstrip("+"))
if dias <= 0:
await msg.reply_text("⭕ Los días deben ser positivos.")
return
except ValueError:
await msg.reply_text("⭕ Formato incorrecto.")
return
doc = await get_user(tid)
if not doc:
await msg.reply_text(f"❌ Usuario `{tid}` no encontrado.")
return
plan_key = doc.get("plan", "free")
if plan_key in ("free", "admin", "superadmin"):
await msg.reply_text(f"⭕ El usuario tiene plan **{PLANS.get(plan_key,{}).get('name', plan_key)}**.\nUsa `/setplan` primero.")
return
exp_str = doc.get("plan_expires")
if extend and exp_str:
try:
base_dt = datetime.fromisoformat(exp_str)
if base_dt < datetime.utcnow():
base_dt = datetime.utcnow()
except Exception:
base_dt = datetime.utcnow()
else:
base_dt = datetime.utcnow()
new_expiry = base_dt + timedelta(days=dias)
await col_users.update_one(
{"user_id": tid},
{"$set": {"plan_expires": new_expiry.isoformat(), "plan_days": dias}}
)
accion = "extendido" if extend else "establecido"
try:
await bot.send_message(tid,
f"🔄 **Tu plan ha sido {accion}**\n\n"
f"📋 Plan: **{PLANS.get(plan_key, {}).get('name', plan_key)}**\n"
f"⏳ Nueva expiración: `{new_expiry.strftime('%Y-%m-%d')}`\n"
f"📅 Días: {dias}"
)
except Exception:
pass
days_from_now = (new_expiry - datetime.utcnow()).days
await msg.reply_text(
f"✅ **Expiración actualizada**\n\n"
f"👤 Usuario: `{tid}`\n"
f"📋 Plan: **{PLANS.get(plan_key, {}).get('name', plan_key)}**\n"
f"⏳ Expira: `{new_expiry.strftime('%Y-%m-%d')}` ({days_from_now}d)\n\n"
"_El usuario ha sido notificado._"
)
@bot.on_message(filters.command("userinfo") & (filters.private | filters.group))
async def cmd_userinfo(client, msg: Message):
if not await is_admin(msg.from_user.id):
await _no_access(msg)
return
args = msg.text.split()[1:]
if not args:
await msg.reply_text("📖 Uso: `/userinfo user_id`")
return
try:
tid = int(args[0])
doc = await get_user(tid)
if not doc:
await msg.reply_text(f"❌ Usuario `{tid}` no encontrado.")
return
pk = doc.get("plan", "free")
today = datetime.utcnow().strftime("%Y-%m-%d")
used = doc.get("daily_usage", {}).get(today, 0)
expires_str = doc.get("plan_expires")
if expires_str:
try:
exp_dt = datetime.fromisoformat(expires_str)
days_left = (exp_dt - datetime.utcnow()).days
expiry_txt = f"`{exp_dt.strftime('%Y-%m-%d')}` ({days_left}d restantes)"
except Exception:
expiry_txt = "Desconocida"
else:
expiry_txt = "Sin expiración" if pk == "free" else "No configurada"
# Ver si tiene actividad en su cola por plan
user_queue_key = _plan_queue_key(pk, uid=tid)
user_queue = _user_queues.get(user_queue_key)
own_q_active = bool(user_queue and user_queue["list"])
own_q_proc = bool(user_queue and user_queue["processing"] is not None)
await msg.reply_text(
f"👤 **Usuario `{tid}`**\n"
"━━━━━━━━━━━━━━━━━━━━━\n"
f"📋 Plan: **{PLANS.get(pk,{}).get('name',pk)}**\n"
f"⏳ Expiración: {expiry_txt}\n"
f"✅ Autorizado: {doc.get('authorized', False)}\n"
"━━━━━━━━━━━━━━━━━━━━━\n"
f"🎬 Total compresiones: {doc.get('total_compressions',0)}\n"
f"💾 Espacio ahorrado: {doc.get('total_saved_mb',0.0):.1f} MB\n"
f"📅 Usadas hoy: {used}\n"
"━━━━━━━━━━━━━━━━━━━━━\n"
f"🧵 Cola por plan: {'✅ Activa' if own_q_proc else ('⏳ En espera' if own_q_active else '—')}"
)
except ValueError:
await msg.reply_text("⭕ ID inválido.")
@bot.on_message(filters.command("proxvencer") & filters.private)
async def cmd_proxvencer(client, msg: Message):
if not await is_admin(msg.from_user.id):
await _no_access(msg)
return
args = msg.text.split()[1:]
dias = int(args[0]) if args and args[0].isdigit() else 7
deadline = (datetime.utcnow() + timedelta(days=dias)).isoformat()
now_iso = datetime.utcnow().isoformat()
docs = await col_users.find({
"plan": {"$nin": ["free", "admin", "superadmin", None]},
"plan_expires": {"$lte": deadline, "$gte": now_iso}
}).sort("plan_expires", 1).to_list(200)
no_fecha = await col_users.find({
"plan": {"$nin": ["free", "admin", "superadmin", None]},
"$or": [{"plan_expires": None}, {"plan_expires": {"$exists": False}}]
}).to_list(200)
lines = [f"⏰ **Planes por vencer (próximos {dias} días):**\n"]
if docs:
for d in docs:
try:
exp_dt = datetime.fromisoformat(d["plan_expires"])
days_left = (exp_dt - datetime.utcnow()).days
icon = "🔴" if days_left <= 1 else ("🟠" if days_left <= 3 else "🟡")
plan_name = PLANS.get(d.get("plan", ""), {}).get("name", d.get("plan","?"))
lines.append(f"{icon} `{d['user_id']}` — {plan_name}\n 📅 Vence: `{exp_dt.strftime('%Y-%m-%d')}` ({days_left}d)")
except Exception:
pass
else:
lines.append("✅ Ningún plan vence en este período.")
if no_fecha:
lines.append(f"\n⚠️ **Sin fecha configurada ({len(no_fecha)}):**")
for d in no_fecha:
plan_name = PLANS.get(d.get("plan", ""), {}).get("name", d.get("plan","?"))
lines.append(f" ⚠️ `{d['user_id']}` — {plan_name} → usa `/renovar {d['user_id']} 30`")
await _send_long(msg, "\n".join(lines))
@bot.on_message(filters.command("stats") & filters.private)
async def cmd_stats(client, msg: Message):
if not await is_admin(msg.from_user.id):
await _no_access(msg)
return
tu = await col_users.count_documents({"authorized": True})
tg = await col_groups.count_documents({})
ta = await col_admins.count_documents({})
tc = await col_stats.count_documents({})
res = await col_stats.aggregate([{"$group":{"_id":None,"o":{"$sum":"$original_mb"},"c":{"$sum":"$compressed_mb"}}}]).to_list(1)
saved = (res[0]["o"] - res[0]["c"]) if res else 0
queue_counts = _queue_snapshot_counts()
active_plan_queues = sum(1 for uq in _user_queues.values() if uq.get("processing") or uq.get("list"))
await msg.reply_text(
f"📊 **Stats del bot:**\n\n"
f"👥 Usuarios autorizados: **{tu}**\n"
f"👥 Grupos: **{tg}**\n"
f"🛡️ Admins: **{ta}**\n"
f"🎬 Compresiones totales: **{tc}**\n"
f"💾 Espacio ahorrado: **{saved:.1f} MB**\n"
"━━━━━━━━━━━━━━━━━━━━━\n"
f"🆓 Cola Free: **{queue_counts.get('free', 0)}**\n"
f"⭐ Cola Basic: **{queue_counts.get('basic', 0)}**\n"
f"💎 Cola Pro: **{queue_counts.get('pro', 0)}**\n"
f"👑 Cola Premium: **{queue_counts.get('premium', 0)}**\n"
f"🏘️ Cola grupos: **{queue_counts.get('group', 0)}**\n"
f"🧵 Colas separadas activas: **{active_plan_queues}**\n"
f"🟢 Colas por plan: **{'ON' if INDIVIDUAL_QUEUES_ENABLED else 'OFF'}**"
)
# ========================
# SUPERADMIN: COLA INDIVIDUAL
# ========================
@bot.on_message(filters.command("colaindividual") & filters.private)
async def cmd_colaindividual(client, msg: Message):
"""
/colaindividual — Ver estado actual
/colaindividual on — Activar colas por plan
/colaindividual off — Desactivar (todos a cola Free/global)
"""
global INDIVIDUAL_QUEUES_ENABLED
uid = msg.from_user.id
if not await is_super_admin(uid):
await _no_access(msg)
return
args = msg.text.split()[1:]
if not args:
estado = "✅ **ACTIVADAS**" if INDIVIDUAL_QUEUES_ENABLED else "❌ **DESACTIVADAS**"
desc = ("Con colas por plan: Free, Basic, Pro, Premium y grupos van por carriles separados."
if INDIVIDUAL_QUEUES_ENABLED
else "Sin colas por plan: todo vuelve a la cola Free/global.")
await msg.reply_text(
f"🧵 **Colas por Plan**\n\n"
f"Estado actual: {estado}\n\n"
f"📋 {desc}\n\n"
"**Comandos:**\n"
"`/colaindividual on` — Activar\n"
"`/colaindividual off` — Desactivar",
reply_markup=InlineKeyboardMarkup([
[
InlineKeyboardButton("✅ Activar", callback_data="ci:on"),
InlineKeyboardButton("❌ Desactivar", callback_data="ci:off"),
]
])
)
return
arg = args[0].lower()
if arg in ("on", "activar", "1"):
INDIVIDUAL_QUEUES_ENABLED = True
await _save_config_to_db("individual_queues", True)
await msg.reply_text(
"✅ **Colas por plan ACTIVADAS**\n\n"
"Basic, Pro, Premium y grupos ahora usan colas separadas.\n"
"_Cambio inmediato._"
)
asyncio.create_task(_log(f"🧵 Colas por plan activadas por superadmin `{uid}`"))
elif arg in ("off", "desactivar", "0"):
INDIVIDUAL_QUEUES_ENABLED = False
await _save_config_to_db("individual_queues", False)
await msg.reply_text(
"❌ **Colas por plan DESACTIVADAS**\n\n"
"Todos los usuarios ahora vuelven a la cola Free/global.\n"
"_Cambio inmediato._"
)
asyncio.create_task(_log(f"🧵 Colas por plan desactivadas por superadmin `{uid}`"))
else:
await msg.reply_text("⭕ Usa `on` o `off`.")
@bot.on_callback_query(filters.regex(r"^ci:"))
async def cb_cola_individual(client, cq: CallbackQuery):
uid = cq.from_user.id
if not await is_super_admin(uid):
await cq.answer("⛔ Sin permisos.", show_alert=True)
return
global INDIVIDUAL_QUEUES_ENABLED
action = cq.data.split(":", 1)[1]
if action == "on":
INDIVIDUAL_QUEUES_ENABLED = True
await _save_config_to_db("individual_queues", True)
await cq.answer("✅ Colas por plan activadas.", show_alert=True)
elif action == "off":
INDIVIDUAL_QUEUES_ENABLED = False
await _save_config_to_db("individual_queues", False)
await cq.answer("❌ Colas por plan desactivadas.", show_alert=True)
try:
estado = "✅ **ACTIVADAS**" if INDIVIDUAL_QUEUES_ENABLED else "❌ **DESACTIVADAS**"
await cq.message.edit_text(
f"🧵 **Colas por Plan**\n\nEstado: {estado}",
reply_markup=InlineKeyboardMarkup([
[
InlineKeyboardButton("✅ Activar", callback_data="ci:on"),
InlineKeyboardButton("❌ Desactivar", callback_data="ci:off"),
]
])
)
except Exception:
pass
@bot.on_message(filters.command("modo") & filters.private)
async def cmd_modo(client, msg: Message):
global BOT_MODE
uid = msg.from_user.id
if not await is_super_admin(uid):
await _no_access(msg)
return
args = msg.text.split()[1:]
if not args:
emoji = "🌐" if BOT_MODE == "public" else "🔒"
estado = "Público" if BOT_MODE == "public" else "Privado"
await msg.reply_text(
emoji + " **Modo actual del bot: " + estado + "**\n\n"
"Para cambiar:\n"
"`/modo publico` — Abre el bot a todos\n"
"`/modo privado` — Solo usuarios autorizados"
)
return
arg = args[0].lower()
if arg in ("publico", "público", "public", "abierto", "open"):
new_mode = "public"
elif arg in ("privado", "private", "cerrado", "closed"):
new_mode = "private"
else:
await msg.reply_text("⛔ Opción inválida.")
return
BOT_MODE = new_mode
await _save_config_to_db("bot_mode", new_mode)
emoji = "🌐" if new_mode == "public" else "🔒"
estado = "Público" if new_mode == "public" else "Privado"
await msg.reply_text(emoji + " **Modo cambiado a: " + estado + "**\n\n_Cambio activo inmediatamente._")
# =====================
# SUPERADMIN COMMANDS
# =====================
@bot.on_message(filters.command("add_admins") & filters.private)
async def cmd_add_admins(client, msg: Message):
if not await is_super_admin(msg.from_user.id):
await _no_access(msg)
return
args = msg.text.split()[1:]
if not args:
await msg.reply_text("📖 Uso: `/add_admins user_id`")
return
res = []
for s in args:
try:
tid = int(s)
await col_admins.update_one({"user_id": tid}, {"$set": {"user_id": tid}}, upsert=True)
await upsert_user(tid, {"user_id": tid, "authorized": True, "plan": "admin"})
res.append(f"✅ `{tid}` → **Admin** 🛡️")
except ValueError:
res.append(f"⭕ ID inválido: `{s}`")
await msg.reply_text("\n".join(res))
@bot.on_message(filters.command("ban_admins") & filters.private)
async def cmd_ban_admins(client, msg: Message):
if not await is_super_admin(msg.from_user.id):
await _no_access(msg)
return
args = msg.text.split()[1:]
if not args:
await msg.reply_text("📖 Uso: `/ban_admins user_id`")
return
res = []
for s in args:
try:
tid = int(s)
if await is_super_admin(tid):
res.append(f"⛔ No puedes quitar a un super admin.")
continue
await col_admins.delete_one({"user_id": tid})
await upsert_user(tid, {"plan": "free"})
res.append(f"✅ `{tid}` removido de Admins.")
except ValueError:
res.append(f"⭕ ID inválido: `{s}`")
await msg.reply_text("\n".join(res))
@bot.on_message(filters.command("add_superadmin") & filters.private)
async def cmd_add_superadmin(client, msg: Message):
if not await is_super_admin(msg.from_user.id):
await _no_access(msg)
return
args = msg.text.split()[1:]
if not args:
await msg.reply_text("📖 Uso: `/add_superadmin user_id`")
return
res = []
for s in args:
try:
tid = int(s)
await col_super_admins.update_one({"user_id": tid}, {"$set": {"user_id": tid}}, upsert=True)
await col_admins.update_one({"user_id": tid}, {"$set": {"user_id": tid}}, upsert=True)
await upsert_user(tid, {"user_id": tid, "authorized": True, "plan": "superadmin"})
res.append(f"✅ `{tid}` → **Super Admin** ⚡")
except ValueError:
res.append(f"⭕ ID inválido: `{s}`")
await msg.reply_text("\n".join(res))
@bot.on_message(filters.command("ban_superadmin") & filters.private)
async def cmd_ban_superadmin(client, msg: Message):
if not await is_super_admin(msg.from_user.id):
await _no_access(msg)
return
args = msg.text.split()[1:]
if not args:
await msg.reply_text("📖 Uso: `/ban_superadmin user_id`")
return
res = []
for s in args:
try:
tid = int(s)
if tid in SUPER_ADMINS_STATIC:
res.append(f"⛔ No puedes quitar al super admin principal.")
continue
await col_super_admins.delete_one({"user_id": tid})
await col_admins.delete_one({"user_id": tid})
await upsert_user(tid, {"plan": "free"})
res.append(f"✅ `{tid}` removido de Super Admins.")
except ValueError:
res.append(f"⭕ ID inválido: `{s}`")
await msg.reply_text("\n".join(res))
@bot.on_message(filters.command("listsuperadmins") & filters.private)
async def cmd_listsuperadmins(client, msg: Message):
if not await is_super_admin(msg.from_user.id):
await _no_access(msg)
return
sadmins = await col_super_admins.find({}).to_list(100)
if not sadmins:
await msg.reply_text("❌ No hay super admins.")
return
lines = ["⚡ **Super Admins:**\n"]
for s in sadmins:
mark = " (principal)" if s["user_id"] in SUPER_ADMINS_STATIC else ""
lines.append(f"• `{s['user_id']}`{mark}")
await msg.reply_text("\n".join(lines))
@bot.on_message(filters.command("editplan") & filters.private)
async def cmd_editplan(client, msg: Message):
if not await is_super_admin(msg.from_user.id):
await _no_access(msg)
return
args = msg.text.split()[1:]
if len(args) < 3:
await msg.reply_text(
"📖 **Uso:** `/editplan <plan> <campo> <valor>`\n\n"
"**Planes editables:** free, basic, pro, premium\n"
"**Campos:**\n"
" • `daily_videos` — número (ej: 10, 999999 para ∞)\n"
" • `max_file_size_mb` — número en MB\n"
" • `queue_priority` — true / false\n"
" • `custom_quality` — true / false\n"
" • `own_queue` — true / false (cola separada por plan)\n\n"
"**Ejemplos:**\n"
"`/editplan free daily_videos 10`\n"
"`/editplan basic own_queue true`"
)
return
plan_key = args[0].lower()
field_name = args[1].lower()
raw_val = args[2].lower()
if plan_key not in PLANS or plan_key in ("admin", "superadmin"):
await msg.reply_text(f"⭕ Plan inválido: `{plan_key}`")
return
int_fields = ("daily_videos", "max_file_size_mb")
bool_fields = ("queue_priority", "custom_quality", "own_queue")
if field_name in int_fields:
try:
value = int(raw_val)
if value < 0:
raise ValueError
except ValueError:
await msg.reply_text(f"⭕ `{field_name}` debe ser un número entero >= 0.")
return
elif field_name in bool_fields:
if raw_val in ("true", "1", "si", "yes", "on"):
value = True
elif raw_val in ("false", "0", "no", "off"):
value = False
else:
await msg.reply_text(f"⭕ `{field_name}` debe ser `true` o `false`.")
return
else:
await msg.reply_text(f"⭕ Campo inválido: `{field_name}`")
return
old_val = PLANS[plan_key].get(field_name)
PLANS[plan_key][field_name] = value
await _save_plan_to_db(plan_key)
await msg.reply_text(
f"✅ **Plan actualizado:**\n\n"
f"📋 Plan: **{PLANS[plan_key]['name']}**\n"
f"🔧 Campo: `{field_name}`\n"
f"📌 Antes: `{old_val}`\n"
f"✨ Ahora: `{value}`\n\n"
f"_Los cambios son inmediatos y persistentes._"
)
@bot.on_message(filters.command("verplanes") & filters.private)
async def cmd_verplanes(client, msg: Message):
if not await is_super_admin(msg.from_user.id):
await _no_access(msg)
return
txt = "📋 **Todos los planes actuales:**\n\n"
for k, p in PLANS.items():
own_q = "✅" if p.get("own_queue") else "❌"
txt += (
f"**{p['name']}** (`{k}`)\n"
f" 🎬 daily_videos: `{_unlim(p['daily_videos'])}`\n"
f" 📦 max_file_size_mb: `{_unlim(p['max_file_size_mb'])}`\n"
f" ⚡ queue_priority: `{p.get('queue_priority', False)}`\n"
f" 🎛️ custom_quality: `{p.get('custom_quality', False)}`\n"
f" 🧵 own_queue: {own_q}\n\n"
)
await msg.reply_text(txt)
@bot.on_message(filters.command("resetplan") & filters.private)
async def cmd_resetplan(client, msg: Message):
if not await is_super_admin(msg.from_user.id):
await _no_access(msg)
return
args = msg.text.split()[1:]
if not args:
await msg.reply_text("📖 Uso: `/resetplan <plan>`")
return
pk = args[0].lower()
if pk not in DEFAULT_PLANS:
await msg.reply_text(f"⭕ Plan inválido: `{pk}`")
return
PLANS[pk] = dict(DEFAULT_PLANS[pk])
await _save_plan_to_db(pk)
await msg.reply_text(f"✅ Plan **{PLANS[pk]['name']}** restaurado a valores predeterminados.")
@bot.on_message(filters.command("resetstats") & filters.private)
async def cmd_resetstats(client, msg: Message):
if not await is_super_admin(msg.from_user.id):
await _no_access(msg)
return
args = msg.text.split()[1:]
if not args:
await msg.reply_text("📖 Uso: `/resetstats user_id`")
return
try:
tid = int(args[0])
await col_users.update_one({"user_id": tid}, {"$set": {"total_compressions": 0, "total_saved_mb": 0.0, "daily_usage": {}}})
await msg.reply_text(f"✅ Stats de `{tid}` reseteadas.")
except ValueError:
await msg.reply_text("⭕ ID inválido.")
@bot.on_message(filters.command("dbstats") & filters.private)
async def cmd_dbstats(client, msg: Message):
if not await is_super_admin(msg.from_user.id):
await _no_access(msg)
return
tu = await col_users.count_documents({})
ta = await col_users.count_documents({"authorized": True})
tg = await col_groups.count_documents({})
tadm = await col_admins.count_documents({})
tsa = await col_super_admins.count_documents({})
tc = await col_stats.count_documents({})
tr = await db["reports"].count_documents({})
await msg.reply_text(
f"🗄️ **Supabase / Postgres — {DB_NAME}:**\n\n"
f"👥 Usuarios total: {tu} (auth: {ta})\n"
f"👥 Grupos: {tg}\n"
f"🛡️ Admins: {tadm}\n"
f"⚡ Super Admins: {tsa}\n"
f"📊 Compresiones: {tc}\n"
f"📝 Reportes: {tr}\n\n"
"**Backups:**\n"
"`/exportdb` — Exportar toda la base en .zip con .json\n"
"`/importdb` — Importar un backup respondiendo al .zip"
)
@bot.on_message(filters.command("exportdb") & filters.private)
async def cmd_exportdb(client, msg: Message):
if not await is_super_admin(msg.from_user.id):
await _no_access(msg)
return
wait = await msg.reply_text("🗄️ Preparando exportación completa de la base de datos...")
try:
zip_path = await _export_database_zip()
await client.send_document(
msg.chat.id,
zip_path,
caption=(
"✅ **Backup generado**\n\n"
f"🗄️ DB: `{DB_NAME}`\n"
f"📦 Archivo: `{os.path.basename(zip_path)}`\n"
"📁 Incluye JSON completos por colección."
),
reply_to_message_id=msg.id,
)
await wait.edit_text("✅ Exportación lista y enviada.")
except Exception as e:
await wait.edit_text(f"⭕ No pude exportar la base: `{str(e)[:180]}`")
@bot.on_message(filters.command("importdb") & filters.private)
async def cmd_importdb(client, msg: Message):
if not await is_super_admin(msg.from_user.id):
await _no_access(msg)
return
rm = msg.reply_to_message
doc = rm.document if rm and rm.document else None
if not doc:
await msg.reply_text(
"📖 **Uso:** responde a un `.zip` de backup con `/importdb`\n\n"
"El archivo debe ser un export generado por `/exportdb`."
)
return
wait = await msg.reply_text("📥 Descargando backup para importarlo...")
local_path = os.path.join(BACKUPS_DIR, f"import_{msg.id}_{doc.file_name or 'backup.zip'}")
try:
await rm.download(file_name=local_path)
await wait.edit_text("🗄️ Restaurando base de datos desde el backup...")
imported = await _import_database_export(local_path)
if not imported:
await wait.edit_text("⚠️ El backup no contenía colecciones importables.")
return
lines = [f"• `{name}`: {count}" for name, count in imported.items()]
await wait.edit_text(
"✅ **Importación completada**\n\n"
f"🗄️ DB: `{DB_NAME}`\n"
+ "\n".join(lines)
)
except Exception as e:
await wait.edit_text(f"⭕ No pude importar la base: `{str(e)[:180]}`")
finally:
try:
if os.path.exists(local_path):
os.remove(local_path)
except Exception:
pass
# ========================
# CALLBACKS
# ========================
@bot.on_callback_query(filters.regex(r"^cyes:"))
async def cb_confirm_yes(client, cq: CallbackQuery):
key = cq.data.split(":", 1)[1]
pending = PENDING_CONFIRM.pop(key, None)
if not pending:
await cq.answer("⏰ Esta solicitud ya expiró.", show_alert=True)
try:
await cq.message.edit_text("⏰ Solicitud expirada.", reply_markup=None)
except Exception:
pass
return
orig_client, orig_message = pending
uid = cq.from_user.id
if uid != orig_message.from_user.id and not await is_admin(uid):
await cq.answer("⛔ Solo el dueño puede confirmar.", show_alert=True)
PENDING_CONFIRM[key] = pending
return
await cq.answer("✅ Iniciando compresión...")
try:
await cq.message.edit_text("📥 Preparando...", reply_markup=None)
except Exception:
pass
await _enqueue(orig_client, orig_message, cq.message)
@bot.on_callback_query(filters.regex(r"^cno:"))
async def cb_confirm_no(client, cq: CallbackQuery):
key = cq.data.split(":", 1)[1]
PENDING_CONFIRM.pop(key, None)
await cq.answer("Cancelado.")
try:
await cq.message.edit_text("🔴 Compresión cancelada.", reply_markup=None)
except Exception:
pass
@bot.on_callback_query(filters.regex(r"^vcola:"))
async def cb_ver_cola(client, cq: CallbackQuery):
jid = cq.data.split(":", 1)[1]
if _global_currently_processing == jid:
await cq.answer("⚙️ Tu video se está procesando ahora en la cola Free.", show_alert=True)
return
async with _global_queue_lock:
snapshot = list(_global_queue_list)
for i, (_, _, _, qjid) in enumerate(snapshot, 1):
if qjid == jid:
total = len(snapshot)
await cq.answer(
f"🆓 Cola Free — Posición {i} de {total}\n"
f"⬆️ Delante: {i - 1} ⬇️ Detrás: {total - i}",
show_alert=True,
)
return
for queue_key, uq in _user_queues.items():
if uq.get("processing") == jid:
await cq.answer(f"⚙️ Tu video se está procesando ahora en {_plan_queue_label(queue_key)}.", show_alert=True)
return
async with uq["lock"]:
uq_snap = list(uq["list"])
for i, (_, _, _, qjid) in enumerate(uq_snap, 1):
if qjid == jid:
total = len(uq_snap) + (1 if uq.get("processing") else 0)
await cq.answer(
f"{_plan_queue_label(queue_key)} — Posición {i} de {total}\n"
f"✨ Esperas solo dentro de tu cola personal.",
show_alert=True,
)
return
await cq.answer("ℹ️ Tu video ya no está en cola.", show_alert=True)
@bot.on_callback_query(filters.regex(r"^cancel:"))
async def cb_cancel(client, cq: CallbackQuery):
jid = cq.data.split(":", 1)[1]
job = ACTIVE_JOBS.get(jid)
if not job:
await cq.answer("No hay nada que cancelar.", show_alert=False)
return
caller = cq.from_user.id
if caller != job.user_id and not await is_admin(caller):
await cq.answer("⛔ No puedes cancelar este proceso.", show_alert=False)
return
job.cancelled = True
queue_key, removed_item = await _remove_job_from_queues(jid)
if removed_item is not None:
try:
txt = "🔴 Cancelado de la cola." if queue_key == "free" else f"🔴 Cancelado de {_plan_queue_label(queue_key).lower()}."
await cq.message.edit_text(txt, reply_markup=None)
except Exception:
pass
await _cleanup_job(job)
await cq.answer("Cancelado.", show_alert=False)
return
if job.process and job.process.returncode is None:
await _terminate_process(job.process)
if job.task and not job.task.done():
job.task.cancel()
try:
await cq.message.edit_text("🔴 Cancelando...", reply_markup=None)
except Exception:
pass
await cq.answer("Cancelado.", show_alert=False)
# ========================
# MANEJADOR DE VIDEOS
# ========================
@bot.on_message((filters.video | filters.document) & (filters.private | filters.group))
async def handle_video(client, msg: Message):
uid = msg.from_user.id
cid = msg.chat.id
if not (await is_authorized_user(uid) or await is_authorized_group(cid)):
await _no_access(msg)
return
media = msg.video or msg.document
if not media:
return
if msg.document and not _is_video_doc(msg.document):
return
fname = getattr(media, "file_name", None) or "video"
size_b = getattr(media, "file_size", 0) or 0
size_mb = size_b / (1024 * 1024)
plan_key = await get_user_plan(uid)
plan_info = PLANS.get(plan_key, PLANS["free"])
can, used, limit = await check_daily_limit(uid)
key = f"{uid}:{msg.id}:{int(time.time())}"
PENDING_CONFIRM[key] = (client, msg)
async def _expire():
await asyncio.sleep(300)
PENDING_CONFIRM.pop(key, None)
asyncio.create_task(_expire())
asyncio.create_task(_log_video(msg, uid, cid, fname, size_mb, plan_info['name']))
in_group = cid != uid and await is_authorized_group(cid)
# Detectar cola por plan
queue_key = _plan_queue_key(plan_key, in_group, uid)
queue_icon = _plan_queue_label(queue_key)
if in_group:
confirm_text = (
f"🎬 **¿Comprimir este video?**\n"
f"━━━━━━━━━━━━━━━━━━━━━\n"
f"📄 Nombre: `{fname}`\n"
f"📦 Tamaño: `{size_mb:.2f} MB`\n"
f"🏘️ Grupo autorizado: **sin límites**\n"
f"━━━━━━━━━━━━━━━━━━━━━\n"
f"_⏰ Tienes 5 minutos para confirmar._"
)
else:
confirm_text = (
f"🎬 **¿Quieres comprimir este video?**\n"
f"━━━━━━━━━━━━━━━━━━━━━\n"
f"📄 Nombre: `{fname}`\n"
f"📦 Tamaño: `{size_mb:.2f} MB`\n"
f"📋 Plan: **{plan_info['name']}**\n"
f"📊 Videos hoy: `{used}` / `{_unlim(limit)}`\n"
f"🧵 Cola: **{queue_icon}**\n"
f"🔀 Sistema: **colas separadas por plan**\n"
f"━━━━━━━━━━━━━━━━━━━━━\n"
f"_⏰ Tienes 5 minutos para confirmar._"
)
await msg.reply_text(
confirm_text,
reply_markup=_confirm_markup(key),
)
# ========================
# /status_bot
# ========================
@bot.on_message(filters.command("status_bot") & (filters.private | filters.group))
async def cmd_status_bot(client, msg: Message):
if not await is_admin(msg.from_user.id):
await _no_access(msg)
return
import psutil
import datetime as _dt
cpu_pct = psutil.cpu_percent(interval=0.5)
cpu_count = psutil.cpu_count(logical=True) or 1
vm = psutil.virtual_memory()
ram_pct = vm.percent
ram_total = vm.total / (1024**3)
ram_used = vm.used / (1024**3)
du = psutil.disk_usage("/")
disk_pct = du.percent
disk_total= du.total / (1024**3)
disk_used = du.used / (1024**3)
try:
net = psutil.net_io_counters()
net_s = net.bytes_sent / (1024**3)
net_r = net.bytes_recv / (1024**3)
net_txt = f"↑ {net_s:.2f} GB | ↓ {net_r:.2f} GB"
except Exception:
net_txt = "N/A"
boot_ts = psutil.boot_time()
uptime_s = int(time.time() - boot_ts)
up_d, rem = divmod(uptime_s, 86400)
up_h, rem2 = divmod(rem, 3600)
up_m = rem2 // 60
uptime_txt = f"{up_d}d {up_h:02}h {up_m:02}m"
cpu_quota_cpus = _cgroup_cpu_quota_cpus()
cpu_capacity = _effective_cpu_capacity()
usable_affinity = len(_usable_cpu_ids()) or 1
max_parallel_slots = _max_parallel_cpu_slots()
quota_txt = "sin límite" if cpu_quota_cpus is None else f"{cpu_quota_cpus:.2f}"
def _sbp(p, n=12):
filled = int(round(p / 100 * n))
return "█" * filled + "░" * (n - filled)
ci = "🟢" if cpu_pct < 60 else ("🟡" if cpu_pct < 85 else "🔴")
ri = "🟢" if ram_pct < 60 else ("🟡" if ram_pct < 85 else "🔴")
di = "🟢" if disk_pct < 70 else ("🟡" if disk_pct < 90 else "🔴")
queue_counts = _queue_snapshot_counts()
active_jobs = [job for job in ACTIVE_JOBS.values() if job.is_processing]
active_compress = [job for job in active_jobs if job.stage == "comprimiendo"]
ffmpeg_cpu_total = sum(max(0.0, job.cpu_usage_pct) for job in active_compress)
active_ffmpeg = await _active_ffmpeg_count()
now_str = _dt.datetime.utcnow().strftime("%Y-%m-%d %H:%M UTC")
extra = ""
if active_compress:
hottest = max(active_compress, key=lambda j: j.cpu_usage_pct)
extra = (
f"🎞️ Compresiones activas: `{len(active_compress)}` | Pool FFmpeg: `{active_ffmpeg}`\n"
f"🔥 CPU FFmpeg total: `{ffmpeg_cpu_total:.1f}%` | Mayor carga: `{hottest.user_id}` ({hottest.cpu_usage_pct:.1f}%)\n"
)
await msg.reply_text(
f"🖥️ **Estado del Servidor**\n"
"━━━━━━━━━━━━━━━━━━━━━\n"
f"⚙️ **CPU:** {ci} {_sbp(cpu_pct)} `{cpu_pct:.1f}%` ({cpu_count} núcleos)\n"
f"🧩 CPU usable: `{cpu_capacity:.2f}` | afinidad: `{usable_affinity}` | cuota: `{quota_txt}` | pool bot: `{max_parallel_slots}`\n"
f"🧠 **RAM:** {ri} {_sbp(ram_pct)} `{ram_pct:.1f}%` ({ram_used:.1f}/{ram_total:.1f} GB)\n"
f"💽 **Disco:** {di} {_sbp(disk_pct)} `{disk_pct:.1f}%` ({disk_used:.1f}/{disk_total:.1f} GB)\n"
f"🌐 **Red:** {net_txt}\n"
"━━━━━━━━━━━━━━━━━━━━━\n"
f"⏱️ Uptime: `{uptime_txt}`\n"
f"🆓 Cola Free: `{queue_counts.get('free', 0)}` en espera\n"
f"⭐ Basic: `{queue_counts.get('basic', 0)}` | 💎 Pro: `{queue_counts.get('pro', 0)}`\n"
f"👑 Premium: `{queue_counts.get('premium', 0)}` | 🏘️ Grupos: `{queue_counts.get('group', 0)}`\n"
f"🔀 Colas por plan: `{'ON' if INDIVIDUAL_QUEUES_ENABLED else 'OFF'}`\n"
f"{extra}"
"━━━━━━━━━━━━━━━━━━━━━\n"
f"_🕐 {now_str}_"
)
def _job_elapsed(job: Job) -> str:
if not job.started_at:
return "—"
return _fmt_eta(max(0, time.time() - job.started_at))
@bot.on_message(filters.command("trabajos") & (filters.private | filters.group))
async def cmd_trabajos(client, msg: Message):
if not await is_admin(msg.from_user.id):
await _no_access(msg)
return
active = [job for job in ACTIVE_JOBS.values() if not job.cancelled]
if not active:
await msg.reply_text("📭 **No hay trabajos activos o pendientes ahora mismo.**")
return
lines = ["🧰 **Trabajos del bot**", "━━━━━━━━━━━━━━━━━━━━━"]
for idx, job in enumerate(sorted(active, key=lambda j: (j.is_processing, j.started_at or 0), reverse=True)[:20], 1):
qpos = _job_queue_position(job.job_id)
really_processing = bool(job.is_processing and (job.process and job.process.returncode is None or qpos and qpos[1] == 0 or job.task))
state = "🟢 Activo" if really_processing else "🟡 En espera"
queue_label = _plan_queue_label((qpos[0] if qpos else job.queue_name) or "free") if (qpos or job.queue_name) else "🧵 Cola pendiente"
extra_queue = ""
if qpos and qpos[1] > 0:
extra_queue = f" | Pos: `#{qpos[1]}/{qpos[2]}`"
lines.append(
f"{idx}. {state} | `{job.user_id}` | `{job.fname or job.job_id}`\n"
f" • Etapa: `{job.stage or 'pendiente'}` | Cola: `{queue_label}`{extra_queue}\n"
f" • Progreso: `{job.progress_pct:.1f}%` | CPU: `{job.cpu_usage_pct:.1f}%` | Slots: `{job.cpu_slots}/{job.cpu_slots_max}`\n"
f" • Última actividad: `{_fmt_eta(max(0, time.time() - (job.last_activity_at or time.time())))}` atrás | Tiempo: `{_job_elapsed(job)}`"
)
await _send_long(msg, "\n".join(lines))
@bot.on_message(filters.command("diagnostico_cpu") & (filters.private | filters.group))
async def cmd_diagnostico_cpu(client, msg: Message):
if not await is_admin(msg.from_user.id):
await _no_access(msg)
return
proc = psutil.Process()
affinity = []
with contextlib.suppress(Exception):
affinity = list(proc.cpu_affinity())
cpu_quota_cpus = _cgroup_cpu_quota_cpus()
cpu_capacity = _effective_cpu_capacity()
quota_txt = "sin límite" if cpu_quota_cpus is None else f"{cpu_quota_cpus:.2f}"
active_ffmpeg = await _active_ffmpeg_count()
await msg.reply_text(
"🧪 **Diagnóstico de CPU**\n"
"━━━━━━━━━━━━━━━━━━━━━\n"
f"⚙️ Host lógico: `{psutil.cpu_count(logical=True) or 1}` CPU\n"
f"🧵 Afinidad proceso: `{len(affinity) or len(_usable_cpu_ids())}` CPU -> `{affinity or _usable_cpu_ids()}`\n"
f"🧩 Cuota cgroup: `{quota_txt}` CPU\n"
f"🎯 Capacidad efectiva: `{cpu_capacity:.2f}` CPU\n"
f"🛡️ MAX_CPU_PERCENT: `{MAX_CPU_PERCENT}%`\n"
f"🏊 Pool máximo bot: `{_max_parallel_cpu_slots()}` slots\n"
f"⏱️ CPU_MONITOR_INTERVAL: `{CPU_MONITOR_INTERVAL}`\n"
f"🧯 COMPRESS_STALL_SECONDS: `{COMPRESS_STALL_SECONDS}`\n"
f"🎞️ FFmpeg activos: `{active_ffmpeg}`\n"
f"📊 CPU servidor actual: `{psutil.cpu_percent(interval=0.4):.1f}%`"
)
@bot.on_message(filters.command("forzarwatchdog") & filters.private)
async def cmd_forzarwatchdog(client, msg: Message):
global _global_currently_processing
if not await is_super_admin(msg.from_user.id):
await _no_access(msg)
return
repaired = []
if _global_currently_processing and _global_currently_processing not in ACTIVE_JOBS:
repaired.append("cola free")
_global_currently_processing = None
if _global_queue_list:
await _ensure_global_worker()
_global_queue_event.set()
repaired.append("worker free")
for queue_key, uq in list(_user_queues.items()):
processing_id = uq.get("processing")
if processing_id and processing_id not in ACTIVE_JOBS:
uq["processing"] = None
repaired.append(f"ref {queue_key}")
if uq.get("list"):
await _ensure_user_worker(queue_key)
uq["event"].set()
repaired.append(f"worker {queue_key}")
if not repaired:
await msg.reply_text("✅ **Watchdog manual ejecutado.** No había nada que reparar.")
return
await msg.reply_text("✅ **Watchdog manual ejecutado**\n\n" + "\n".join(f"• {x}" for x in repaired[:20]))
# ========================
# /cola — Ver cola de compresión
# ========================
async def _send_long(msg: Message, text: str, **kw):
MAX = 4000
parts = [text[i:i+MAX] for i in range(0, len(text), MAX)]
sent = None
for part in parts:
sent = await msg.reply_text(part, **kw)
kw = {}
return sent
async def _show_cola_info(msg: Message, uid: int):
adm = await is_admin(uid)
sep = "━━━━━━━━━━━━━━━━━━━━━"
lines = [f"📋 **Estado de las colas**\n{sep}\n"]
processing_job = ACTIVE_JOBS.get(_global_currently_processing) if _global_currently_processing else None
if processing_job:
pct = processing_job.progress_pct
bar = processing_job.progress_bar or _bar(pct / 100)
stage_icon = {"descargando": "📥", "comprimiendo": "🗜️", "subiendo": "📤"}.get(processing_job.stage, "⚙️")
is_mine = processing_job.user_id == uid
header = f"{stage_icon} **Cola Free — Procesando:**\n 👤 `{processing_job.user_id}`"
if is_mine:
header += " (tuyo)"
if is_mine or adm:
header += f"\n {bar} `{pct:.1f}%`"
lines.append(header)
else:
lines.append("🆓 Cola Free: sin procesamiento activo.\n")
async with _global_queue_lock:
free_snapshot = list(_global_queue_list)
if free_snapshot:
lines.append(f"🆓 **Cola Free: {len(free_snapshot)} en espera**")
for i, (_, q_msg, _, _) in enumerate(free_snapshot[:15], 1):
q_uid = q_msg.from_user.id
marker = " ◀ **tú**" if q_uid == uid else ""
lines.append(f" {i}. 👤 `{q_uid}`{marker}")
else:
lines.append("🆓 Cola Free vacía.")
in_group = msg.chat.id != uid and await is_authorized_group(msg.chat.id)
plan_key = await get_user_plan(uid)
my_queue_key = _plan_queue_key(plan_key, in_group, uid)
if my_queue_key != "free":
uq = _get_user_queue(my_queue_key)
processing_now = uq.get("processing")
async with uq["lock"]:
uq_snap = list(uq["list"])
lines.append(f"\n{sep}")
lines.append(f"{_plan_queue_label(my_queue_key)}")
if processing_now:
pjob = ACTIVE_JOBS.get(processing_now)
if pjob:
s_icon = {"descargando": "📥", "comprimiendo": "🗜️", "subiendo": "📤"}.get(pjob.stage, "⚙️")
mine = " (tuyo)" if pjob.user_id == uid else ""
lines.append(f" {s_icon} Procesando: `{pjob.fname or processing_now}`{mine} — `{pjob.progress_pct:.1f}%`")
else:
lines.append(" Sin procesamiento activo.")
if uq_snap:
lines.append(f" ⏳ En espera: {len(uq_snap)} video(s)")
for i, (_, qm, _, _) in enumerate(uq_snap[:10], 1):
qfname = getattr(qm.video or qm.document, "file_name", "?") or "?"
marker = " ◀ **tú**" if qm.from_user.id == uid else ""
lines.append(f" {i}. 🎬 `{qfname}`{marker}")
else:
lines.append(" Cola vacía.")
if adm:
active_plan_queues = [
(qk, uq) for qk, uq in _user_queues.items()
if qk != my_queue_key and (uq.get("processing") or uq.get("list"))
]
if active_plan_queues:
lines.append(f"\n{sep}\n🧵 **Otras colas por plan:**")
for qk, uq in active_plan_queues[:10]:
proc = "⚙️ proc." if uq.get("processing") else ""
wait = f"{len(uq['list'])} esp." if uq.get("list") else ""
lines.append(f" {_plan_queue_label(qk)} — {proc} {wait}".rstrip())
full_text = "\n".join(lines)
await _send_long(msg, full_text)
@bot.on_message(filters.command("cola") & (filters.private | filters.group))
async def cmd_cola(client, msg: Message):
uid = msg.from_user.id
cid = msg.chat.id
if not (await is_authorized_user(uid) or await is_authorized_group(cid)):
await _no_access(msg)
return
await _show_cola_info(msg, uid)
# ========================
# /reporte
# ========================
@bot.on_message(filters.command("reporte") & (filters.private | filters.group))
async def cmd_reporte(client, msg: Message):
uid = msg.from_user.id
cid = msg.chat.id
if not (await is_authorized_user(uid) or await is_authorized_group(cid)):
await _no_access(msg)
return
args = msg.text.split(None, 1)
if len(args) < 2:
await msg.reply_text(
"📝 **Enviar reporte**\n\n"
"Uso: `/reporte [descripción del problema]`\n\n"
"Ejemplo:\n"
"`/reporte El video tardó mucho y no se envió`"
)
return
texto = args[1].strip()
report = {
"id": await _next_numeric_id("reports"),
"user_id": uid,
"chat_id": cid,
"texto": texto,
"fecha": datetime.utcnow().strftime("%Y-%m-%d %H:%M UTC"),
"leido": False,
}
REPORTS.append(report)
await db["reports"].insert_one(dict(report))
for sa_id in SUPER_ADMINS_STATIC:
try:
await client.send_message(
sa_id,
f"📣 **Nuevo reporte #{report['id']}**\n\n"
f"👤 Usuario: `{uid}`\n"
f"📅 Fecha: {report['fecha']}\n\n"
f"📝 {texto}"
)
except Exception:
pass
await msg.reply_text(
f"✅ **Reporte enviado** (#{report['id']})\n\n"
f"Gracias, el equipo lo revisará pronto."
)
@bot.on_message(filters.command("reportes") & filters.private)
async def cmd_reportes(client, msg: Message):
if not await is_admin(msg.from_user.id):
await _no_access(msg)
return
args = msg.text.split()[1:]
if args:
try:
rid = int(args[0])
doc = await db["reports"].find_one({"id": rid})
if not doc:
await msg.reply_text(f"❌ Reporte #{rid} no encontrado.")
return
await db["reports"].update_one({"id": rid}, {"$set": {"leido": True}})
await msg.reply_text(
f"📋 **Reporte #{rid}**\n\n"
f"👤 Usuario: `{doc['user_id']}`\n"
f"📅 Fecha: {doc['fecha']}\n"
f"✅ Leído: {'Sí' if doc.get('leido') else 'No'}\n\n"
f"📝 {doc['texto']}"
)
return
except ValueError:
pass
cursor = db["reports"].find({}).sort("id", -1).limit(10)
docs = await cursor.to_list(length=10)
if not docs:
await msg.reply_text("📭 No hay reportes.")
return
no_leidos = await db["reports"].count_documents({"leido": False})
lines = [f"📋 **Reportes** (sin leer: {no_leidos})\n"]
for d in docs:
mark = "🔴" if not d.get("leido") else "✅"
resumen = d["texto"][:50] + ("..." if len(d["texto"]) > 50 else "")
lines.append(f"{mark} #{d['id']} — `{d['user_id']}` — {resumen}")
lines.append("\n_Usa `/reportes <número>` para ver un reporte completo._")
await msg.reply_text("\n".join(lines))
@bot.on_message(filters.command("msgusr") & filters.private)
async def cmd_msgusr(client, msg: Message):
if not await is_admin(msg.from_user.id):
await _no_access(msg)
return
args = msg.text.split(None, 2)
if len(args) < 2:
await msg.reply_text("📖 **Uso:**\n`/msgusr user_id mensaje`")
return
try:
tid = int(args[1])
except ValueError:
await msg.reply_text("⭕ ID de usuario inválido.")
return
texto = args[2].strip() if len(args) > 2 else ""
remitente = f"📨 **Mensaje del administrador:**\n\n"
try:
if msg.reply_to_message:
rm = msg.reply_to_message
caption = remitente + texto if texto else remitente.strip()
if rm.photo:
await client.send_photo(tid, rm.photo.file_id, caption=caption)
elif rm.video:
await client.send_video(tid, rm.video.file_id, caption=caption)
elif rm.document:
await client.send_document(tid, rm.document.file_id, caption=caption)
else:
await client.send_message(tid, remitente + (rm.text or texto or ""))
else:
if not texto:
await msg.reply_text("⭕ Escribe un mensaje.")
return
await client.send_message(tid, remitente + texto)
await msg.reply_text(f"✅ Mensaje enviado a `{tid}`.")
except Exception as e:
await msg.reply_text(f"⭕ No pude enviar el mensaje a `{tid}`: {e}")
@bot.on_message(filters.command("broadcast") & filters.private)
async def cmd_broadcast_media(client, msg: Message):
if not await is_super_admin(msg.from_user.id):
await _no_access(msg)
return
args = msg.text.split(None, 1)
caption_txt = args[1].strip() if len(args) > 1 else ""
header = "📣 **Anuncio global:**\n\n"
rm = msg.reply_to_message
has_media = rm and (rm.photo or rm.video or rm.document or rm.audio or rm.voice)
if not has_media and not caption_txt:
await msg.reply_text("📖 **Uso del broadcast:**\n\nSolo texto: `/broadcast mensaje`\nCon media: responde a ella con `/broadcast [caption]`")
return
all_users = await col_users.find({}).to_list(5000)
sent = failed = 0
caption = header + caption_txt if caption_txt else header.strip()
status_msg = await msg.reply_text(f"📣 Enviando broadcast a {len(all_users)} usuarios...")
for u in all_users:
try:
if has_media:
if rm.photo:
await client.send_photo(u["user_id"], rm.photo.file_id, caption=caption)
elif rm.video:
await client.send_video(u["user_id"], rm.video.file_id, caption=caption)
elif rm.document:
await client.send_document(u["user_id"], rm.document.file_id, caption=caption)
else:
await client.send_message(u["user_id"], caption)
sent += 1
except Exception:
failed += 1
await asyncio.sleep(0.05)
await status_msg.edit_text(
f"📣 **Broadcast terminado.**\n\n✅ Enviado: {sent}\n❌ Fallidos: {failed}"
)
@bot.on_message(filters.command("info") & filters.private)
async def cmd_info_media(client, msg: Message):
if not await is_admin(msg.from_user.id):
await _no_access(msg)
return
args = msg.text.split(None, 1)
caption_txt = args[1].strip() if len(args) > 1 else ""
header = "📢 **Aviso del bot:**\n\n"
rm = msg.reply_to_message
has_media = rm and (rm.photo or rm.video or rm.document)
if not has_media and not caption_txt:
await msg.reply_text("📖 **Uso:** `/info mensaje`")
return
targets_u = await col_users.find({"authorized": True}).to_list(1000)
targets_g = await col_groups.find({}).to_list(200)
sent = failed = 0
caption = header + caption_txt if caption_txt else header.strip()
async def _send(dest_id):
nonlocal sent, failed
try:
if has_media:
if rm.photo:
await client.send_photo(dest_id, rm.photo.file_id, caption=caption)
elif rm.video:
await client.send_video(dest_id, rm.video.file_id, caption=caption)
elif rm.document:
await client.send_document(dest_id, rm.document.file_id, caption=caption)
else:
await client.send_message(dest_id, caption)
sent += 1
except Exception:
failed += 1
for u in targets_u:
await _send(u["user_id"])
await asyncio.sleep(0.03)
for g in targets_g:
await _send(g["group_id"])
await asyncio.sleep(0.03)
await msg.reply_text(f"✅ Enviado: {sent} | ❌ Fallidos: {failed}")
# ========================
# /adelantar
# ========================
@bot.on_message(filters.command("adelantar") & filters.private)
async def cmd_adelantar(client, msg: Message):
if not await is_admin(msg.from_user.id):
await _no_access(msg)
return
args = msg.text.split()[1:]
if not args:
await msg.reply_text(
"""📖 **Uso:**
`/adelantar user_id` — Mueve sus videos al frente de su cola actual
`/adelantar user_id pos` — Mueve sus videos a la posición `pos` de su cola"""
)
return
try:
target_uid = int(args[0])
insert_pos = int(args[1]) - 1 if len(args) > 1 else 0
insert_pos = max(0, insert_pos)
except ValueError:
await msg.reply_text("⭕ ID o posición inválida.")
return
async with _global_queue_lock:
user_items = [(i, it) for i, it in enumerate(_global_queue_list) if it[1].from_user.id == target_uid]
if user_items:
other_items = [it for it in _global_queue_list if it[1].from_user.id != target_uid]
count = len(user_items)
extracted = [it for _, it in user_items]
ip = min(insert_pos, len(other_items))
_global_queue_list[:] = other_items[:ip] + extracted + other_items[ip:]
await msg.reply_text(
f"""⚡ **Cola actualizada**
👤 Usuario `{target_uid}` adelantado en **{_plan_queue_label('free')}**.
🎬 {count} video(s) movidos a la posición #{ip + 1}."""
)
return
for queue_key, uq in _user_queues.items():
async with uq["lock"]:
user_items = [(i, it) for i, it in enumerate(uq["list"]) if it[1].from_user.id == target_uid]
if not user_items:
continue
other_items = [it for it in uq["list"] if it[1].from_user.id != target_uid]
count = len(user_items)
extracted = [it for _, it in user_items]
ip = min(insert_pos, len(other_items))
uq["list"][:] = other_items[:ip] + extracted + other_items[ip:]
await msg.reply_text(
f"""⚡ **Cola actualizada**
👤 Usuario `{target_uid}` adelantado en **{_plan_queue_label(queue_key)}**.
🎬 {count} video(s) movidos a la posición #{ip + 1}."""
)
return
await msg.reply_text(f"❌ El usuario `{target_uid}` no tiene videos en ninguna cola administrable.")
# ========================
# /cancelarcola
# ========================
@bot.on_message(filters.command("cancelarcola") & filters.private)
async def cmd_cancelarcola(client, msg: Message):
uid = msg.from_user.id
if not await is_admin(uid):
await _no_access(msg)
return
args = msg.text.split()[1:]
if not args:
if not await is_super_admin(uid):
await msg.reply_text("⛔ Solo el Super Admin puede cancelar todas las colas.")
return
cancelled_items = []
async with _global_queue_lock:
cancelled_items.extend(list(_global_queue_list))
_global_queue_list.clear()
for uq in _user_queues.values():
async with uq["lock"]:
cancelled_items.extend(list(uq["list"]))
uq["list"].clear()
for _, _, qstatus, qjid in cancelled_items:
job = ACTIVE_JOBS.get(qjid)
if job:
job.cancelled = True
await _cleanup_job(job)
try:
await qstatus.edit_text("❌ **Cola vaciada por el administrador.**", reply_markup=None)
except Exception:
pass
await msg.reply_text(f"""🗑️ **Todas las colas vaciadas.**
❌ {len(cancelled_items)} video(s) cancelados.""")
return
try:
target_uid = int(args[0])
except ValueError:
await msg.reply_text("⭕ ID inválido.")
return
removed = []
async with _global_queue_lock:
removed.extend([it for it in _global_queue_list if it[1].from_user.id == target_uid])
_global_queue_list[:] = [it for it in _global_queue_list if it[1].from_user.id != target_uid]
for uq in _user_queues.values():
async with uq["lock"]:
removed.extend([it for it in uq["list"] if it[1].from_user.id == target_uid])
uq["list"][:] = [it for it in uq["list"] if it[1].from_user.id != target_uid]
if not removed:
await msg.reply_text(f"❌ `{target_uid}` no tiene videos en ninguna cola administrable.")
return
for _, _, qstatus, qjid in removed:
job = ACTIVE_JOBS.get(qjid)
if job:
job.cancelled = True
await _cleanup_job(job)
try:
await qstatus.edit_text("🔴 **Tu video fue cancelado por el administrador.**", reply_markup=None)
except Exception:
pass
await msg.reply_text(
f"""✅ **Videos cancelados**
👤 Usuario: `{target_uid}`
❌ {len(removed)} video(s) eliminados."""
)
# ========================
# /logs
# ========================
@bot.on_message(filters.command("logs") & filters.private)
async def cmd_logs(client, msg: Message):
global LOG_CHAT_ID, LOG_VIDEOS
uid = msg.from_user.id
if not await is_super_admin(uid):
await _no_access(msg)
return
args = msg.text.split()[1:]
if not args:
status = f"`{LOG_CHAT_ID}`" if LOG_CHAT_ID else "No configurado"
await msg.reply_text(
f"📡 **Configuración de Logs**\n\n"
f"📍 Canal/Grupo: {status}\n"
f"🎬 Log de videos: {'✅ Activo' if LOG_VIDEOS else '❌ Inactivo'}\n\n"
"**Comandos:**\n"
"`/logs canal <id>` — Configura un canal\n"
"`/logs grupo <id>` — Configura un grupo\n"
"`/logs off` — Desactiva los logs\n"
"`/logs videos on/off` — Log de videos"
)
return
sub = args[0].lower()
if sub == "off":
LOG_CHAT_ID = None
await _save_config_to_db("log_chat_id", None)
await msg.reply_text("✅ Logs desactivados.")
return
if sub == "videos":
val = args[1].lower() if len(args) > 1 else ""
if val in ("on", "1", "si", "true"):
LOG_VIDEOS = True
await _save_config_to_db("log_videos", True)
await msg.reply_text("✅ Log de videos **activado**.")
elif val in ("off", "0", "no", "false"):
LOG_VIDEOS = False
await _save_config_to_db("log_videos", False)
await msg.reply_text("✅ Log de videos **desactivado**.")
else:
await msg.reply_text("⭕ Usa `/logs videos on` o `/logs videos off`")
return
if sub in ("canal", "grupo") and len(args) > 1:
try:
chat_id = int(args[1])
except ValueError:
await msg.reply_text("⭕ ID inválido.")
return
LOG_CHAT_ID = chat_id
await _save_config_to_db("log_chat_id", chat_id)
try:
await bot.send_message(chat_id, f"📡 **Logs de CompresUltra Bot activados**\n⚡ Configurado por: `{uid}`")
await msg.reply_text(f"✅ Configurado: `{chat_id}`\n_Mensaje de prueba enviado._")
except Exception as e:
await msg.reply_text(f"⚠️ Configurado pero no pude enviar mensaje de prueba: `{e}`")
return
await msg.reply_text("⭕ Opción inválida. Usa `/logs` sin argumentos para ver la ayuda.")
# ========================
# VERIFICADOR PERIÓDICO DE PLANES EXPIRADOS
# ========================
async def _plan_expiry_checker():
while True:
await asyncio.sleep(3600)
try:
now = datetime.utcnow().isoformat()
expired = await col_users.find({
"plan": {"$nin": ["free", "admin", "superadmin", None]},
"plan_expires": {"$lt": now, "$ne": None}
}).to_list(length=500)
for doc in expired:
uid = doc["user_id"]
plan = doc["plan"]
await col_users.update_one(
{"user_id": uid},
{"$set": {"plan": "free", "plan_expires": None}}
)
await _notify_plan_change(uid, plan, "free", "Tu plan ha expirado automáticamente.")
asyncio.create_task(_log(f"⏰ Plan expirado (checker): `{uid}` — {plan} → free"))
if expired:
logger.info("Plan expiry checker: %d usuarios degradados a free", len(expired))
except Exception as e:
logger.error("Plan expiry checker error: %s", e)
async def _queue_watchdog():
global _global_currently_processing
while True:
await asyncio.sleep(QUEUE_WATCHDOG_INTERVAL)
try:
if _global_currently_processing and _global_currently_processing not in ACTIVE_JOBS:
_global_currently_processing = None
if _global_queue_list:
await _ensure_global_worker()
if _global_worker_task and _global_worker_task.done():
logger.warning("Watchdog: reiniciando worker global con %d elemento(s) pendientes.", len(_global_queue_list))
await _ensure_global_worker()
_global_queue_event.set()
for queue_key, uq in list(_user_queues.items()):
processing_id = uq.get("processing")
if processing_id and processing_id not in ACTIVE_JOBS:
uq["processing"] = None
if uq.get("list"):
await _ensure_user_worker(queue_key)
worker = uq.get("worker")
if worker and worker.done():
logger.warning("Watchdog: reiniciando worker %s con %d elemento(s) pendientes.", queue_key, len(uq["list"]))
await _ensure_user_worker(queue_key)
uq["event"].set()
now = time.time()
stale_limit = COMPRESS_STALL_SECONDS + 30
for job in list(ACTIVE_JOBS.values()):
if job.cancelled or job.system_cancelled:
# Ya fue cancelado (usuario o sistema); solo limpiar si sigue registrado
await _cleanup_job(job)
continue
idle_for = now - (job.last_activity_at or now)
queue_pos = _job_queue_position(job.job_id)
task_done = bool(job.task and job.task.done())
proc_running = bool(job.process and job.process.returncode is None)
if queue_pos is None and not proc_running and not job.is_processing:
logger.warning("Watchdog: limpiando trabajo huérfano %s fuera de cola.", job.job_id)
await _force_finish_job(job, "❌ **Trabajo eliminado por limpieza automática.**")
continue
if queue_pos is not None and queue_pos[1] > 0:
job.is_processing = False
job.queue_name = queue_pos[0]
continue
if proc_running:
ffmpeg_progress_at = job.ffmpeg_last_progress_at or job.last_activity_at or now
ffmpeg_output_at = job.ffmpeg_last_output_at or ffmpeg_progress_at
progress_idle = now - ffmpeg_progress_at
output_idle = now - ffmpeg_output_at
cpu_busy = (job.cpu_usage_pct or 0.0) >= STALL_CPU_FLOOR_PERCENT
watchdog_hard_limit = max(stale_limit, COMPRESS_STALL_SECONDS + FFMPEG_OUTPUT_IDLE_SECONDS + 120)
if progress_idle > watchdog_hard_limit and output_idle > FFMPEG_OUTPUT_IDLE_SECONDS and not cpu_busy:
logger.warning("Watchdog: trabajo %s cancelado por inactividad real (progress=%ss output=%ss).", job.job_id, int(progress_idle), int(output_idle))
reason = "❌ **Trabajo cancelado por inactividad real.**\n\nFFmpeg dejó de dar progreso y salida durante demasiado tiempo.\nReenvía el video para intentarlo otra vez."
if job.ffmpeg_last_stderr:
reason += f"\n\nÚltimo mensaje FFmpeg:\n`{job.ffmpeg_last_stderr[:160]}`"
job.system_cancelled = True
if job.task and not job.task.done():
with contextlib.suppress(Exception):
job.task.cancel()
await _force_finish_job(job, reason)
continue
if job.is_processing and job.stage in {"subiendo", "finalizando"}:
upload_ref = job.upload_last_progress_at or job.upload_started_at or job.last_activity_at or now
upload_idle = now - upload_ref
upload_elapsed = now - (job.upload_started_at or job.started_at or now)
if job.stage == "subiendo":
if upload_idle > UPLOAD_STALL_SECONDS and upload_elapsed > UPLOAD_STALL_SECONDS:
logger.warning("Watchdog: subida atascada para %s (idle=%ss elapsed=%ss bytes=%s/%s).", job.job_id, int(upload_idle), int(upload_elapsed), job.upload_last_bytes, job.upload_total_bytes)
if job.task and not task_done:
with contextlib.suppress(Exception):
job.system_cancelled = True
job.task.cancel()
await _force_finish_job(
job,
"❌ **La subida a Telegram quedó atascada.**\n\nLa compresión terminó, pero el envío final no avanzó durante demasiado tiempo.\nPuedes reenviar el video.",
)
if _global_currently_processing == job.job_id:
_global_currently_processing = None
for uq in _user_queues.values():
if uq.get("processing") == job.job_id:
uq["processing"] = None
continue
finalize_idle = now - (job.upload_completed_at or job.last_activity_at or now)
if finalize_idle > FINALIZE_GRACE_SECONDS:
logger.warning("Watchdog: finalización atascada para %s tras enviar video (%ss).", job.job_id, int(finalize_idle))
await _force_finish_job(
job,
"✅ **Video enviado, pero el cierre del trabajo quedó atascado.**\n\nSi ya recibiste el video, puedes ignorar este aviso.",
)
continue
if job.is_processing and idle_for > stale_limit:
logger.warning("Watchdog: trabajo %s atascado en etapa %s sin proceso activo.", job.job_id, job.stage or "desconocida")
if job.task and not task_done:
with contextlib.suppress(Exception):
job.system_cancelled = True
job.task.cancel()
await _force_finish_job(
job,
"❌ **Trabajo atascado y limpiado automáticamente.**\n\nLa cola quedó liberada. Puedes reenviar el video.",
)
if _global_currently_processing == job.job_id:
_global_currently_processing = None
for uq in _user_queues.values():
if uq.get("processing") == job.job_id:
uq["processing"] = None
if task_done and not proc_running and idle_for > 10:
logger.warning("Watchdog: limpiando trabajo %s con task finalizada pero aún registrado.", job.job_id)
await _force_finish_job(job, "❌ **Trabajo finalizado con estado inconsistente y fue limpiado.**")
except Exception as e:
logger.error("Queue watchdog error: %s", e)
@bot.on_message(filters.command("version") & (filters.private | filters.group))
async def cmd_version(client, msg: Message):
await msg.reply_text(
f"🧾 **Versión del bot**\n\n"
f"🤖 {BOT_VERSION}\n"
f"🔒 Modo: `{'Público' if BOT_MODE == 'public' else 'Privado'}`\n"
f"🧵 Colas por plan: `{'ON' if INDIVIDUAL_QUEUES_ENABLED else 'OFF'}`\n"
f"🛡️ Tope CPU host: `{MAX_CPU_PERCENT}%`\n"
f"🧯 Stall watchdog: `{COMPRESS_STALL_SECONDS}s`"
)
@bot.on_message(filters.command("misjobs") & (filters.private | filters.group))
async def cmd_misjobs(client, msg: Message):
uid = msg.from_user.id
jobs = [job for job in ACTIVE_JOBS.values() if job.user_id == uid and not job.cancelled]
if not jobs:
await msg.reply_text("📭 **No tienes trabajos activos ni en cola.**")
return
lines = ["🎞️ **Tus trabajos**", "━━━━━━━━━━━━━━━━━━━━━"]
for idx, job in enumerate(sorted(jobs, key=lambda j: j.started_at or 0, reverse=True)[:15], 1):
qpos = _job_queue_position(job.job_id)
queue_label = _plan_queue_label((qpos[0] if qpos else job.queue_name) or "free")
pos_txt = "procesando" if qpos and qpos[1] == 0 else (f"#{qpos[1]}/{qpos[2]}" if qpos else "—")
lines.append(
f"{idx}. `{job.fname or job.job_id}`\n"
f" • Etapa: `{job.stage or 'pendiente'}`\n"
f" • Cola: `{queue_label}` | Posición: `{pos_txt}`\n"
f" • Progreso: `{job.progress_pct:.1f}%` | Tiempo: `{_job_elapsed(job)}`"
)
await _send_long(msg, "\n".join(lines))
@bot.on_message(filters.command("limpiaratascos") & filters.private)
async def cmd_limpiaratascos(client, msg: Message):
global _global_currently_processing
if not await is_super_admin(msg.from_user.id):
await _no_access(msg)
return
cleaned = []
now = time.time()
for job in list(ACTIVE_JOBS.values()):
qpos = _job_queue_position(job.job_id)
idle_for = now - (job.last_activity_at or now)
proc_running = bool(job.process and job.process.returncode is None)
if job.cancelled or (job.is_processing and not proc_running and idle_for > 30) or (qpos is None and idle_for > 30):
cleaned.append(job.job_id)
await _force_finish_job(job, "❌ **Trabajo limpiado manualmente por administración.**")
if _global_currently_processing == job.job_id:
_global_currently_processing = None
for uq in _user_queues.values():
if uq.get("processing") == job.job_id:
uq["processing"] = None
if _global_queue_list:
_global_queue_event.set()
for uq in _user_queues.values():
if uq.get("list"):
uq["event"].set()
if not cleaned:
await msg.reply_text("✅ **No encontré trabajos atascados para limpiar.**")
return
await msg.reply_text("✅ **Limpieza completada**\n\n" + "\n".join(f"• `{jid}`" for jid in cleaned[:30]))
# ========================
# /setcpu — Cambiar límite de CPU de FFmpeg en caliente
# ========================
@bot.on_message(filters.command("setcpu") & filters.private)
async def cmd_setcpu(client, msg: Message):
global MAX_CPU_PERCENT
if not await is_super_admin(msg.from_user.id):
await _no_access(msg)
return
parts = msg.text.split()
if len(parts) < 2:
current_slots = _max_parallel_cpu_slots()
await msg.reply_text(
"⚙️ **Configuración de CPU para FFmpeg**\n"
"━━━━━━━━━━━━━━━━━━━━━\n"
f"🎚️ Límite actual: `{MAX_CPU_PERCENT}%`\n"
f"🏊 Pool de slots: `{current_slots}`\n"
f"🧩 Capacidad efectiva: `{_effective_cpu_capacity():.2f}` CPU\n"
"━━━━━━━━━━━━━━━━━━━━━\n"
"Uso: `/setcpu <porcentaje>`\n"
"Ejemplo: `/setcpu 60` (limita FFmpeg al 60% de CPU)\n"
"Rango permitido: `10` – `95`"
)
return
try:
new_val = int(parts[1])
except ValueError:
await msg.reply_text("❌ Valor inválido. Usa un número entero entre 10 y 95.")
return
if not (10 <= new_val <= 95):
await msg.reply_text("❌ El valor debe estar entre **10** y **95**.")
return
old_val = MAX_CPU_PERCENT
MAX_CPU_PERCENT = new_val
new_slots = _max_parallel_cpu_slots()
await msg.reply_text(
f"✅ **CPU de FFmpeg actualizado**\n"
"━━━━━━━━━━━━━━━━━━━━━\n"
f"📉 Anterior: `{old_val}%`\n"
f"📈 Nuevo: `{MAX_CPU_PERCENT}%`\n"
f"🏊 Slots de pool resultantes: `{new_slots}`\n"
"_El cambio aplica a los próximos trabajos de compresión._"
)
# ========================
# /limpiar — Liberar RAM, disco y caché de archivos huérfanos
# ========================
@bot.on_message(filters.command("limpiar") & filters.private)
async def cmd_limpiar(client, msg: Message):
global MAX_CPU_PERCENT
if not await is_super_admin(msg.from_user.id):
await _no_access(msg)
return
await msg.reply_text("🧹 **Iniciando limpieza del sistema…**")
import gc
import signal
freed_files = 0
freed_bytes = 0
errors_found = []
# ── 1. CPU: matar procesos ffmpeg zombies/huérfanos ──────────────────────
# Son ffmpeg que ya no tienen job asociado en ACTIVE_JOBS (o job cancelado)
known_pids: set = set()
for job in list(ACTIVE_JOBS.values()):
if not job.cancelled and job.process is not None:
try:
known_pids.add(job.process.pid)
except Exception:
pass
zombie_killed = 0
nice_applied = 0
try:
for proc in psutil.process_iter(["pid", "name", "status"]):
try:
pname = (proc.info.get("name") or "").lower()
if "ffmpeg" not in pname:
continue
pid = proc.info["pid"]
status = proc.info.get("status", "")
# Matar zombies reales
if status == psutil.STATUS_ZOMBIE:
proc.kill()
zombie_killed += 1
continue
# Si no es un pid conocido por el bot, es huérfano → matar
if pid not in known_pids:
proc.kill()
zombie_killed += 1
continue
# Para los ffmpeg activos y legítimos: bajar prioridad (nice 10)
# Esto libera CPU para el SO sin cancelar la compresión
try:
current_nice = proc.nice()
if current_nice < 10:
proc.nice(10)
nice_applied += 1
except Exception:
pass
except (psutil.NoSuchProcess, psutil.AccessDenied):
pass
except Exception as e:
errors_found.append(f"cpu_scan: {str(e)[:60]}")
# ── 2. CPU: limpiar jobs del bot con proceso muerto ───────────────────────
jobs_cleaned = 0
now = time.time()
for job in list(ACTIVE_JOBS.values()):
if job.cancelled:
continue
proc_dead = job.process is not None and job.process.returncode is not None
idle_for = now - (job.last_activity_at or now)
if proc_dead and idle_for > 30:
await _force_finish_job(job, "❌ **Trabajo limpiado automáticamente (proceso muerto detectado).**")
jobs_cleaned += 1
# ── 3. Disco: limpiar archivos huérfanos en downloads/ y compressed/ ─────
active_files: set = set()
for job in list(ACTIVE_JOBS.values()):
if not job.cancelled:
try:
if hasattr(job, "in_file") and job.in_file:
active_files.add(os.path.abspath(job.in_file))
if hasattr(job, "out_file") and job.out_file:
active_files.add(os.path.abspath(job.out_file))
except Exception:
pass
for folder in (DOWNLOADS_DIR, COMPRESSED_DIR):
try:
for fpath in os.listdir(folder):
full = os.path.join(folder, fpath)
if not os.path.isfile(full):
continue
if os.path.abspath(full) in active_files:
continue
try:
size = os.path.getsize(full)
age = time.time() - os.path.getmtime(full)
if age > 600: # huérfano si lleva más de 10 min
os.remove(full)
freed_files += 1
freed_bytes += size
except Exception as e:
errors_found.append(str(e)[:60])
except Exception as e:
errors_found.append(f"folder {folder}: {str(e)[:60]}")
# ── 4. RAM: garbage collector ─────────────────────────────────────────────
before_ram = psutil.virtual_memory()
gc_collected = gc.collect()
after_ram = psutil.virtual_memory()
ram_freed_mb = max(0.0, (before_ram.used - after_ram.used) / (1024 ** 2))
# ── 5. Resumen final ──────────────────────────────────────────────────────
freed_mb = freed_bytes / (1024 ** 2)
du_after = psutil.disk_usage("/")
vm_after = psutil.virtual_memory()
cpu_after = psutil.cpu_percent(interval=0.5)
report = (
"✅ **Limpieza completada**\n"
"━━━━━━━━━━━━━━━━━━━━━\n"
f"⚙️ CPU ahora: `{cpu_after:.1f}%`\n"
f"💀 FFmpeg zombies/huérfanos matados: `{zombie_killed}`\n"
f"📉 FFmpeg activos con prioridad bajada: `{nice_applied}`\n"
f"🗂️ Jobs bot con proceso muerto limpiados: `{jobs_cleaned}`\n"
"━━━━━━━━━━━━━━━━━━━━━\n"
f"🗑️ Archivos huérfanos eliminados: `{freed_files}` ({freed_mb:.1f} MB)\n"
f"🧠 RAM liberada (GC): `{ram_freed_mb:.1f} MB` | Ciclos GC: `{gc_collected}`\n"
f"💽 Disco libre: `{(du_after.total - du_after.used) / (1024**3):.1f} GB` "
f"({100 - du_after.percent:.1f}% libre)\n"
f"🧠 RAM libre: `{vm_after.available / (1024**3):.1f} GB` "
f"({100 - vm_after.percent:.1f}% libre)\n"
)
if errors_found:
report += f"⚠️ Errores menores: `{len(errors_found)}`\n"
report += "━━━━━━━━━━━━━━━━━━━━━"
await msg.reply_text(report)
# ========================
# COMANDOS DE MENÚ
# ========================
USER_COMMANDS = [
("start", "👋 Bienvenida al bot"),
("help", "📖 Ver lista de comandos"),
("miperfil", "👤 Tu perfil y estadísticas"),
("miplan", "📋 Ver tu plan con días restantes"),
("planes", "📊 Ver planes disponibles"),
("micalidad", "⚙️ Ver tu calidad actual"),
("calidad", "🎛️ Cambiar calidad de compresión"),
("cola", "🧵 Ver estado de la cola"),
("cancelar", "❌ Cancelar tu compresión activa"),
("reporte", "📝 Reportar un problema"),
("ping", "🏓 Verificar si el bot responde"),
("misjobs", "🎞️ Ver tus trabajos activos"),
("version", "🧾 Ver versión y modo del bot"),
("velocidad", "⚡ Test de velocidad del servidor"),
("id", "🆔 Ver tu ID"),
("about", "ℹ️ Información del bot"),
]
ADMIN_COMMANDS = USER_COMMANDS + [
("add", "➕ Autorizar usuario"),
("ban", "🚫 Desautorizar usuario"),
("listusers", "👥 Lista de usuarios autorizados"),
("setplan", "📋 Asignar plan a un usuario"),
("renovar", "🔄 Poner o extender días de plan"),
("proxvencer", "⏰ Planes por vencer pronto"),
("userinfo", "🔍 Info detallada de un usuario"),
("grup", "🏘️ Autorizar grupo"),
("bangrup", "🚫 Desautorizar grupo"),
("listgrup", "📗 Lista de grupos autorizados"),
("listadmins", "📓 Lista de administradores"),
("stats", "📊 Estadísticas del bot"),
("status_bot", "🖥️ Estado del servidor"),
("trabajos", "🧰 Ver trabajos activos y cola"),
("diagnostico_cpu", "🧪 Ver límites reales de CPU"),
("info", "📢 Enviar aviso a autorizados"),
("msgusr", "📨 Mensaje privado a usuario"),
("reportes", "📋 Ver reportes de usuarios"),
("adelantar", "⚡ Adelantar usuario en cola"),
("cancelarcola", "🗑️ Cancelar videos de la cola"),
]
SUPERADMIN_COMMANDS = ADMIN_COMMANDS + [
("modo", "🔒 Cambiar modo público/privado"),
("colaindividual", "🧵 Activar/desactivar colas por plan"),
("add_admins", "🛡️ Agregar administrador"),
("ban_admins", "🛡️ Quitar administrador"),
("add_superadmin", "⚡ Agregar super admin"),
("ban_superadmin", "⚡ Quitar super admin"),
("listsuperadmins", "⚡ Lista de super admins"),
("editplan", "✏️ Editar límites de un plan"),
("verplanes", "📋 Ver todos los planes actuales"),
("resetplan", "🔄 Restaurar plan a valores default"),
("resetstats", "🔄 Resetear stats de usuario"),
("broadcast", "📣 Broadcast global con media"),
("dbstats", "🗄️ Estadísticas de Supabase"),
("exportdb", "📦 Exportar backup DB"),
("importdb", "📥 Importar backup DB"),
("logs", "📡 Configurar canal de logs"),
("forzarwatchdog", "🛠️ Reparar workers/colas atascadas"),
("limpiaratascos", "🧹 Limpiar trabajos colgados"),
("setcpu", "⚙️ Cambiar límite de CPU de FFmpeg"),
("limpiar", "🧹 Liberar RAM, disco y caché"),
("actualizarmenu", "🔄 Actualizar menú de comandos"),
]
def _make_bot_commands(cmd_list):
from pyrogram.types import BotCommand
return [BotCommand(cmd, desc) for cmd, desc in cmd_list]
async def _set_menus():
from pyrogram.types import BotCommandScopeDefault, BotCommandScopeChat
errors = []
try:
await bot.set_bot_commands(_make_bot_commands(USER_COMMANDS), scope=BotCommandScopeDefault())
except Exception as e:
errors.append(f"default: {e}")
admins = await col_admins.find({}).to_list(500)
for a in admins:
uid = a["user_id"]
try:
is_sa = await is_super_admin(uid)
cmds = SUPERADMIN_COMMANDS if is_sa else ADMIN_COMMANDS
await bot.set_bot_commands(_make_bot_commands(cmds), scope=BotCommandScopeChat(chat_id=uid))
except Exception as e:
errors.append(f"admin {uid}: {e}")
for uid in SUPER_ADMINS_STATIC:
try:
await bot.set_bot_commands(_make_bot_commands(SUPERADMIN_COMMANDS), scope=BotCommandScopeChat(chat_id=uid))
except Exception as e:
errors.append(f"superadmin {uid}: {e}")
return errors
@bot.on_message(filters.command("actualizarmenu") & filters.private)
async def cmd_actualizarmenu(client, msg: Message):
if not await is_super_admin(msg.from_user.id):
await _no_access(msg)
return
wait = await msg.reply_text("⏳ Actualizando menús...")
errors = await _set_menus()
if errors:
err_txt = "\n".join(str(e) for e in errors[:10])
await wait.edit_text(f"✅ Menús actualizados con algunos errores:\n\n`{err_txt}`")
else:
await wait.edit_text(
"✅ **Menús actualizados correctamente**\n\n"
"👤 Usuarios normales → comandos básicos\n"
"🛡️ Admins → comandos de admin\n"
"⚡ Super Admins → todos los comandos"
)
import asyncio
import sys
# ========================
# INICIO / PARADA
# ========================
async def start_bot():
await db_init()
await bot.start()
me = await bot.get_me()
logger.info("🚀 Bot @%s iniciado | DB: %s", me.username, DB_NAME)
for sa_id in SUPER_ADMINS_STATIC:
try:
await bot.send_message(
sa_id,
f"✅ **CompresUltra Bot iniciado**\n\n"
f"🤖 @{me.username}\n"
f"🗄️ DB: {DB_NAME}\n"
f"⚡ {BOT_VERSION}\n"
f"🧵 Colas por plan: {'ON' if INDIVIDUAL_QUEUES_ENABLED else 'OFF'}",
)
except Exception:
pass
await _log(
f"🚀 **Bot iniciado**\n"
f"🤖 @{me.username} | {BOT_VERSION}\n"
f"🔒 Modo: {BOT_MODE} | 🎬 Log videos: {LOG_VIDEOS}\n"
f"🧵 Colas por plan: {INDIVIDUAL_QUEUES_ENABLED}"
)
await _ensure_global_worker()
asyncio.create_task(_plan_expiry_checker())
asyncio.create_task(_queue_watchdog())
asyncio.create_task(_set_menus())
async def stop_bot():
global _pg_pool
try:
await bot.stop()
except Exception:
pass
try:
if _pg_pool is not None:
await _pg_pool.close()
_pg_pool = None
except Exception:
pass
# ========================
# BLOQUE DE EJECUCIÓN PRINCIPAL
# ========================
if __name__ == "__main__":
# Soluciona problemas de bucles de eventos asíncronos en Windows si usas ese OS
if sys.platform == "win32":
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
# Obtenemos el bucle de eventos de asyncio
loop = asyncio.get_event_loop()
try:
print("⏳ Inicializando base de datos y levantando el bot...")
# Corremos la función que conecta la DB, inicia el bot y envía los mensajes
loop.run_until_complete(start_bot())
print("🚀 Bot iniciado correctamente y escuchando actualizaciones.")
# Mantiene el bot vivo y procesando comandos/mensajes de Telegram
loop.run_forever()
except KeyboardInterrupt:
print("\n🛑 Apagando el bot por señal del usuario (Ctrl+C)...")
finally:
# Esto asegura que cuando el bot se detenga, limpie las conexiones a la DB
print("💤 Cerrando sesiones de forma segura...")
loop.run_until_complete(stop_bot())
print("✅ Bot completamente apagado.")
|