File size: 106,829 Bytes
1404692 36dde81 1404692 273ab56 36dde81 273ab56 36dde81 273ab56 36dde81 273ab56 36dde81 273ab56 36dde81 273ab56 36dde81 273ab56 36dde81 273ab56 36dde81 273ab56 36dde81 273ab56 36dde81 273ab56 36dde81 273ab56 36dde81 273ab56 36dde81 273ab56 36dde81 273ab56 36dde81 273ab56 36dde81 c778c21 36dde81 c778c21 36dde81 c778c21 273ab56 36dde81 273ab56 36dde81 b8fe50f 273ab56 36dde81 273ab56 1404692 36dde81 1404692 273ab56 b8fe50f 36dde81 273ab56 1404692 36dde81 1404692 36dde81 1404692 f697c3b b8fe50f ef88983 273ab56 f946b58 b8fe50f f946b58 c778c21 36dde81 c778c21 36dde81 c778c21 36dde81 c778c21 36dde81 c778c21 ef88983 c778c21 36dde81 c778c21 36dde81 c778c21 36dde81 c778c21 b5f02cc 36dde81 b5f02cc 36dde81 b5f02cc 36dde81 b5f02cc 36dde81 273ab56 b8fe50f 273ab56 1404692 273ab56 b8fe50f 273ab56 b8fe50f 273ab56 1404692 273ab56 b8fe50f 273ab56 b8fe50f 273ab56 1404692 273ab56 b8fe50f 273ab56 1404692 f697c3b 273ab56 f946b58 273ab56 b8fe50f 273ab56 f946b58 1404692 f697c3b b8fe50f 273ab56 b8fe50f 273ab56 b8fe50f 273ab56 b8fe50f 273ab56 36dde81 1404692 36dde81 1404692 f697c3b 1404692 36dde81 273ab56 f697c3b 1404692 36dde81 f697c3b 1404692 b8fe50f 36dde81 f697c3b 1404692 36dde81 273ab56 36dde81 b8fe50f 36dde81 b8fe50f f697c3b 36dde81 b8fe50f 36dde81 f946b58 1404692 36dde81 1404692 36dde81 b8fe50f 36dde81 1404692 36dde81 b8fe50f 1404692 36dde81 1404692 273ab56 ef88983 273ab56 36dde81 ef88983 273ab56 36dde81 273ab56 ef88983 273ab56 ef88983 36dde81 ef88983 273ab56 ef88983 273ab56 36dde81 273ab56 36dde81 273ab56 36dde81 273ab56 36dde81 1404692 b8fe50f c778c21 36dde81 c778c21 36dde81 c778c21 36dde81 c778c21 36dde81 c778c21 36dde81 c778c21 cda1677 c778c21 b8fe50f 273ab56 b8fe50f 273ab56 b8fe50f 273ab56 b8fe50f 273ab56 b8fe50f 273ab56 b8fe50f 273ab56 b8fe50f 273ab56 b8fe50f 273ab56 b8fe50f 36dde81 273ab56 b8fe50f 36dde81 b8fe50f 273ab56 b8fe50f 273ab56 b8fe50f 36dde81 273ab56 b8fe50f 36dde81 b8fe50f 273ab56 b8fe50f 273ab56 b8fe50f 36dde81 273ab56 b8fe50f 36dde81 b8fe50f 273ab56 b8fe50f 36dde81 273ab56 b8fe50f 36dde81 b8fe50f 273ab56 b8fe50f 273ab56 b8fe50f 273ab56 b8fe50f 273ab56 b8fe50f 09f6d64 b8fe50f 273ab56 b8fe50f 09f6d64 b8fe50f b5f02cc 36dde81 b5f02cc 36dde81 b5f02cc 36dde81 b5f02cc 36dde81 b5f02cc 36dde81 b5f02cc 273ab56 b5f02cc 36dde81 273ab56 b8fe50f 273ab56 b8fe50f ef88983 273ab56 b8fe50f ef88983 36dde81 b8fe50f ef88983 273ab56 b8fe50f 36dde81 b8fe50f 273ab56 b8fe50f 273ab56 b8fe50f 36dde81 b8fe50f 273ab56 b8fe50f 36dde81 b8fe50f 36dde81 b8fe50f 36dde81 b8fe50f 273ab56 b8fe50f 273ab56 b8fe50f 36dde81 b8fe50f 273ab56 b8fe50f 273ab56 b8fe50f 273ab56 b8fe50f 273ab56 36dde81 273ab56 f697c3b 273ab56 | 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 | {% extends "base.html" %}
{% block title %}{{ media_details.title if media_details else "Edit" }} - Telegram Stremio{% endblock %}
{% block content %}
<style>
.glass-card { background: var(--card); border: 1px solid var(--border); }
.glass-card-soft { background: var(--bg); border: 1px solid var(--border); }
.section-title { color: var(--text); font-weight: 600; letter-spacing: -0.015em; }
.muted {
color: var(--text-sec);
}
.field-label { display: block; font-size: .72rem; font-weight: 500; letter-spacing: .1em; text-transform: uppercase; margin-bottom: .45rem; color: var(--text-sec); }
.field-input, .field-textarea { width: 100%; border-radius: var(--radius-sm); border: 1px solid var(--border); background: var(--bg); color: var(--text); padding: .75rem 1rem; outline: none; transition: border-color .18s var(--ease), box-shadow .18s var(--ease); }
[data-sub-row] .sub-url { min-width: 0; }
@media (min-width: 640px) {
[data-sub-row] .sub-lang { width: 11rem; flex: none; }
}
.field-input::placeholder,
.field-textarea::placeholder {
color: color-mix(in srgb, var(--text-sec) 85%, transparent);
}
.field-input:focus, .field-textarea:focus { border-color: var(--primary); box-shadow: 0 0 0 3px var(--ring); }
.hero-wrap { position: relative; overflow: hidden; isolation: isolate; background: #0e0e0d; color: #f3f1ec; min-height: 280px; }
.hero-backdrop { position: absolute; inset: 0; width: 100%; height: 100%; object-fit: cover; object-position: center 25%; opacity: .7; }
.hero-gradient { position: absolute; inset: 0; background: linear-gradient(90deg, rgba(14,14,13,.94) 0%, rgba(14,14,13,.72) 42%, rgba(14,14,13,.2) 100%), linear-gradient(0deg, rgba(14,14,13,.9) 0%, transparent 55%); }
.hero-body { position: relative; z-index: 1; display: flex; align-items: flex-end; gap: 1.75rem; padding: 2rem; }
.hero-poster { width: 168px; aspect-ratio: 2 / 3; object-fit: cover; border-radius: 14px; flex-shrink: 0; background: #232321; box-shadow: 0 12px 32px rgba(0,0,0,.45); }
.hero-info { min-width: 0; flex: 1; display: flex; flex-direction: column; align-items: flex-start; gap: .9rem; }
.hero-logo { display: block; max-width: min(100%, 380px); max-height: 110px; object-fit: contain; object-position: left bottom; filter: drop-shadow(0 2px 10px rgba(0,0,0,.55)); animation: logo-in .4s var(--ease); }
@keyframes logo-in { from { opacity: 0; transform: translateY(4px); } to { opacity: 1; transform: none; } }
.hero-title { font-size: clamp(1.6rem, 3.6vw, 2.4rem); font-weight: 600; line-height: 1.1; letter-spacing: -.02em; text-wrap: balance; overflow-wrap: anywhere; }
.hero-meta { display: flex; flex-wrap: wrap; align-items: center; gap: .35rem .9rem; font-size: .92rem; color: rgba(243,241,236,.78); }
.hero-meta > span + span::before { content: "·"; margin-right: .9rem; color: rgba(243,241,236,.45); }
.hero-rating { color: #f5c451; font-weight: 500; }
.hero-rating i { font-size: .78rem; }
.hero-genres { display: flex; flex-wrap: wrap; gap: .4rem; }
.hero-chip { padding: .2rem .7rem; border-radius: 9999px; font-size: .8rem; color: #f3f1ec; background: rgba(255,255,255,.1); border: 1px solid rgba(255,255,255,.16); }
.sr-only { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0,0,0,0); white-space: nowrap; border: 0; }
@media (max-width: 767.98px) {
.hero-body { flex-direction: column; align-items: center; text-align: center; padding: 1.5rem 1.25rem; gap: 1.25rem; }
.hero-gradient { background: linear-gradient(0deg, rgba(14,14,13,.96) 0%, rgba(14,14,13,.7) 55%, rgba(14,14,13,.35) 100%); }
.hero-poster { width: 132px; }
.hero-info { align-items: center; }
.hero-logo { max-height: 80px; object-position: center; }
.hero-meta, .hero-genres { justify-content: center; }
}
.pill { display: inline-flex; align-items: center; gap: .35rem; padding: .25rem .7rem; border-radius: 9999px; font-size: .8rem; font-weight: 500; border: 1px solid var(--border); background: color-mix(in srgb, var(--card) 70%, transparent); color: var(--text); }
.quality-row { background: var(--bg); border: 1px solid var(--border); }
.quality-badge { border-radius: 9999px; padding: .2rem .65rem; font-size: .75rem; font-weight: 500; }
.btn-ui { display: inline-flex; align-items: center; justify-content: center; gap: .45rem; border-radius: 9999px; padding: .6rem 1.1rem; font-size: .9rem; font-weight: 500; transition: background-color .18s var(--ease), border-color .18s var(--ease), transform .12s var(--ease), filter .18s var(--ease); border: 1px solid transparent; white-space: nowrap; }
.btn-ui:active { transform: scale(.97); }
.btn-primary { background: var(--primary); color: var(--on-primary); }
.btn-primary:hover { filter: brightness(1.03); }
.btn-ghost { background: transparent; color: var(--text); border-color: var(--border); }
.btn-ghost:hover { background: var(--card-high); }
.btn-danger {
background: color-mix(in srgb, var(--danger) 16%, transparent);
color: var(--danger);
border-color: color-mix(in srgb, var(--danger) 26%, transparent);
}
.btn-success { background: transparent; color: var(--text); border-color: var(--border); }
.btn-success i { color: var(--ok); }
.btn-success:hover, .btn-info:hover { background: var(--card-high); }
.btn-info { background: transparent; color: var(--text); border-color: var(--border); }
.btn-info i { color: var(--info); }
.season-content {
transition: max-height 0.32s ease, opacity 0.25s ease, transform 0.25s ease;
overflow: hidden;
}
.season-collapsed {
max-height: 0 !important;
opacity: 0;
transform: translateY(-4px);
}
.break-all {
word-break: break-all;
overflow-wrap: anywhere;
}
.file-list { display: flex; flex-direction: column; gap: .5rem; }
.file-row { display: flex; align-items: center; gap: .85rem; padding: .7rem .75rem .7rem .85rem; border-radius: var(--radius-sm); background: var(--bg); border: 1px solid var(--border); min-width: 0; transition: border-color .15s var(--ease); }
.file-row:hover { border-color: var(--hairline-strong); }
.file-main { min-width: 0; flex: 1; }
.file-name { font-size: .88rem; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.file-sub { font-size: .78rem; color: var(--text-sec); }
.file-actions { display: flex; gap: .25rem; flex-shrink: 0; }
.q-badge { flex-shrink: 0; min-width: 3.4rem; text-align: center; padding: .2rem .5rem; border-radius: 8px; font-size: .74rem; font-weight: 600; background: var(--card-high); color: var(--text); }
.q-badge.q-4k { background: color-mix(in srgb, var(--primary) 16%, transparent); color: var(--primary); }
.q-badge.q-1080p { background: color-mix(in srgb, var(--info) 15%, transparent); color: var(--info); }
.icon-act { width: 34px; height: 34px; display: grid; place-items: center; border-radius: 9999px; border: 1px solid transparent; background: transparent; color: var(--text-sec); font-size: .82rem; cursor: pointer; transition: background-color .15s var(--ease), color .15s var(--ease), transform .12s var(--ease); }
.icon-act:hover { background: var(--card-high); color: var(--text); }
.icon-act.danger:hover { background: color-mix(in srgb, var(--danger) 12%, transparent); color: var(--danger); }
.icon-act:active { transform: scale(.9); }
.season-tabs { display: flex; gap: .4rem; overflow-x: auto; scrollbar-width: none; margin: 0 0 1rem; padding-bottom: 2px; }
.season-tabs::-webkit-scrollbar { display: none; }
.season-tab { flex-shrink: 0; padding: .45rem .95rem; border-radius: 9999px; border: 1px solid var(--border); background: transparent; color: var(--text-sec); font-size: .86rem; cursor: pointer; white-space: nowrap; transition: all .15s var(--ease); }
.season-tab span { margin-left: .35rem; font-size: .76rem; opacity: .7; }
.season-tab:hover { color: var(--text); }
.season-tab[aria-selected="true"] { color: var(--primary); border-color: color-mix(in srgb, var(--primary) 50%, var(--border)); background: color-mix(in srgb, var(--primary) 10%, transparent); }
.season-block { animation: edit-panel-in .22s ease; }
.season-head { display: flex; align-items: center; justify-content: space-between; gap: .75rem; padding-bottom: .9rem; margin-bottom: .25rem; border-bottom: 1px solid var(--border); }
.ep-list { display: flex; flex-direction: column; }
.ep { padding: 1rem 0; border-bottom: 1px solid var(--border); display: flex; flex-direction: column; gap: .75rem; min-width: 0; }
.ep:last-child { border-bottom: 0; padding-bottom: 0; }
.ep-top { display: flex; gap: 1rem; min-width: 0; }
.ep-thumb { position: relative; flex-shrink: 0; width: 176px; aspect-ratio: 16 / 9; border-radius: 12px; overflow: hidden; background: linear-gradient(135deg, var(--card-high), var(--bg)); }
.ep-thumb img { position: absolute; inset: 0; width: 100%; height: 100%; object-fit: cover; }
.ep-fallback { position: absolute; inset: 0; display: grid; place-items: center; font-size: 1.35rem; font-weight: 600; letter-spacing: -.02em; color: var(--text-sec); }
.ep-num { position: absolute; left: 6px; bottom: 6px; min-width: 22px; padding: 1px 7px; border-radius: 99px; font-size: .7rem; text-align: center; color: #fff; background: rgba(0,0,0,.72); }
.ep-thumb:not(:has(img)) .ep-num { display: none; }
.ep-info { min-width: 0; flex: 1; }
.ep-title-row { display: flex; align-items: flex-start; justify-content: space-between; gap: .5rem; }
.ep-title { font-weight: 500; line-height: 1.3; padding-top: .15rem; overflow-wrap: anywhere; }
.ep-meta { font-size: .8rem; color: var(--text-sec); margin-top: .15rem; font-variant-numeric: tabular-nums; }
.ep-overview { font-size: .85rem; color: var(--text-sec); margin-top: .4rem; line-height: 1.5; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; }
.content-empty { text-align: center; padding: 2.5rem 1rem; color: var(--text-sec); font-size: .92rem; }
.content-empty i { display: grid; place-items: center; width: 48px; height: 48px; margin: 0 auto .75rem; border-radius: 99px; background: var(--card-high); }
@media (max-width: 640px) {
.ep-thumb { width: 120px; }
.ep-overview { -webkit-line-clamp: 3; }
.file-row { gap: .6rem; padding: .6rem .4rem .6rem .65rem; }
.file-name { white-space: normal; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow-wrap: anywhere; font-size: .84rem; line-height: 1.3; }
.q-badge { min-width: 3rem; font-size: .7rem; padding: .2rem .4rem; }
.file-actions { gap: 0; }
.icon-act { width: 32px; height: 32px; }
.season-head .btn-ui { width: 40px; height: 40px; padding: 0; flex-shrink: 0; }
}
.match-card { background: var(--bg); border: 1px solid var(--border); border-radius: var(--radius-sm); padding: 1rem; transition: border-color .2s var(--ease); }
.match-card:hover { border-color: color-mix(in srgb, var(--primary) 40%, var(--border)); }
.match-card.active {
border-color: var(--primary);
box-shadow: 0 0 0 4px color-mix(in srgb, var(--primary) 18%, transparent);
}
.match-thumb { width: 4.5rem; height: 6.75rem; border-radius: 10px; object-fit: cover; background: var(--card-high); flex-shrink: 0; }
@keyframes spin {
to { transform: rotate(360deg); }
}
.st-spin {
animation: spin 1s linear infinite;
}
.speed-modal-shell {
width: min(100%, 56rem);
max-height: calc(100dvh - 1rem);
overflow: hidden;
}
.speed-modal-body {
max-height: calc(100dvh - 11rem);
overflow-y: auto;
-webkit-overflow-scrolling: touch;
}
@media (max-width: 640px) {
.btn-ui { width: 100%; }
.speed-modal-shell {
width: calc(100vw - 0.75rem);
max-height: calc(100dvh - 0.75rem);
border-radius: 1.25rem;
}
.speed-modal-body {
max-height: calc(100dvh - 9.5rem);
}
.st-table thead { display: none; }
.st-table, .st-table tbody, .st-table td { display: block; width: 100%; }
.st-table tr { display: grid; grid-template-columns: 1fr 1fr; gap: 0.6rem 0.9rem; padding: 0.85rem 1rem; }
.st-table td { padding: 0 !important; font-size: 0.8rem; }
.st-table td:first-child { grid-column: 1 / -1; font-size: 0.9rem; }
.st-table td[data-label]::before {
content: attr(data-label);
display: block;
font-size: 0.62rem;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.05em;
opacity: 0.55;
margin-bottom: 0.15rem;
}
.st-actions .btn-ui { flex: 1; }
}
.edit-tabs { position: sticky; top: .75rem; z-index: 20; display: flex; gap: 2px; overflow-x: auto; padding: 4px; margin-bottom: 1.5rem; border-radius: 9999px; scrollbar-width: none; background: var(--card); border: 1px solid var(--border); }
.edit-tabs::-webkit-scrollbar { display: none; }
.edit-tab { flex: 1 0 auto; display: inline-flex; align-items: center; justify-content: center; gap: .45rem; white-space: nowrap; padding: .55rem 1rem; border-radius: 9999px; font-size: .9rem; font-weight: 500; color: var(--text-sec); border: 0; background: transparent; cursor: pointer; transition: color .18s var(--ease), background-color .2s var(--ease); }
.edit-tab:hover { color: var(--text); }
.edit-tab.active { color: var(--primary); background: var(--card-high); }
.edit-panel {
animation: edit-panel-in 0.22s ease;
}
@keyframes edit-panel-in {
from { opacity: 0; transform: translateY(6px); }
to { opacity: 1; transform: translateY(0); }
}
@media (max-width: 767.98px) { .edit-tabs { top: calc(64px + env(safe-area-inset-top)); } }
@media (max-width: 640px) {
.edit-tab {
flex: 0 0 auto;
font-size: 0.82rem;
padding: 0.55rem 0.85rem;
}
}
</style>
<div>
<header class="mb-6">
<a id="back-to-list" href="/media/manage?media_type={{ media_type }}" class="inline-flex items-center gap-2 text-sm text-text-secondary hover:text-text transition-colors">
<i class="fa-solid fa-arrow-left text-xs"></i> {{ 'Movies' if media_type == 'movie' else 'TV shows' }}
</a>
<p class="text-sm text-text-secondary mt-3">Edit {{ 'movie' if media_type == 'movie' else 'series' }} · TMDB {{ tmdb_id }} · DB {{ db_index }}</p>
</header>
{% if media_details %}
<div class="glass-card rounded-3xl overflow-hidden mb-6">
<div class="hero-wrap">
{% if media_details.backdrop %}
<img src="{{ cover_url(media_details.backdrop) }}" alt="" class="hero-backdrop" decoding="async" onerror="this.remove()">
{% endif %}
<div class="hero-gradient"></div>
<div class="hero-body">
<img src="{{ cover_url(media_details.poster) or '/static/placeholder.svg' }}" alt="{{ media_details.title }} poster"
class="hero-poster" onerror="this.onerror=null;this.src='/static/placeholder.svg'">
<div class="hero-info">
{% if media_details.logo %}
<img src="{{ cover_url(media_details.logo) }}" alt="{{ media_details.title }}" class="hero-logo" decoding="async"
onload="if (this.naturalWidth < 40) this.onerror()"
onerror="this.remove(); document.getElementById('hero-title').classList.remove('sr-only')">
{% endif %}
<h2 id="hero-title" class="hero-title{{ ' sr-only' if media_details.logo else '' }}">{{ media_details.title }}</h2>
<div class="hero-meta">
{% if media_details.rating %}<span class="hero-rating"><i class="fa-solid fa-star"></i> {{ media_details.rating }}</span>{% endif %}
{% if media_details.release_year %}<span>{{ media_details.release_year }}{% if media_details.release_year_end and media_details.release_year_end != media_details.release_year %}–{{ media_details.release_year_end }}{% endif %}</span>{% endif %}
{% if media_details.runtime %}<span>{{ media_details.runtime }}</span>{% endif %}
<span>{{ 'Movie' if media_type == 'movie' else 'Series' }}</span>
</div>
{% if media_details.genres %}
<div class="hero-genres">
{% for genre in media_details.genres[:6] %}<span class="hero-chip">{{ genre }}</span>{% endfor %}
</div>
{% endif %}
</div>
</div>
</div>
{% if media_details.description %}
<div class="border-t border-hairline p-5 sm:p-6 lg:p-8">
<h3 class="section-title text-lg sm:text-xl mb-3">Overview</h3>
<p class="muted leading-7 text-sm sm:text-base">{{ media_details.description }}</p>
</div>
{% endif %}
</div>
{% endif %}
{% if media_details %}
<div class="edit-tabs" role="tablist" id="edit-tabs">
<button type="button" class="edit-tab active" data-tab="details" onclick="switchEditTab('details')"><i class="fa-solid fa-pen"></i> <span>Details</span></button>
<button type="button" class="edit-tab" data-tab="content" onclick="switchEditTab('content')"><i class="fa-solid fa-film"></i> <span>Content</span></button>
<button type="button" class="edit-tab" data-tab="subtitles" onclick="switchEditTab('subtitles')"><i class="fa-solid fa-closed-captioning"></i> <span>Subtitles</span></button>
<button type="button" class="edit-tab" data-tab="catalog" onclick="switchEditTab('catalog')"><i class="fa-solid fa-layer-group"></i> <span>Catalog</span></button>
<button type="button" class="edit-tab" data-tab="rescan" onclick="switchEditTab('rescan')"><i class="fa-solid fa-rotate"></i> <span>Rescan</span></button>
</div>
{% endif %}
{% if media_details %}
<div class="glass-card edit-panel hidden rounded-3xl p-5 sm:p-6 lg:p-8 mb-6 sm:mb-8" data-panel="rescan">
<div class="flex flex-col lg:flex-row lg:items-end lg:justify-between gap-3 mb-5 sm:mb-6">
<div>
<h3 class="section-title text-xl sm:text-2xl">Rescan Metadata</h3>
<p class="muted mt-1 text-sm sm:text-base">
Use this only when the auto-detected {{ media_type }} is mismatched. Existing Telegram files will stay safe.
</p>
</div>
<div class="flex items-center gap-2">
<span class="pill">IMDb / TMDb re-match</span>
<button type="button" class="btn-ui btn-ghost" onclick="tagMediaFiles()" title="Add the IMDB link to every file's caption"><i class="fa-solid fa-tag"></i> Tag files</button>
</div>
</div>
<div class="grid grid-cols-1 lg:grid-cols-[1fr_auto] gap-3">
<input
id="rescan-query"
type="text"
class="field-input"
placeholder="Title (with or without year), IMDb id/link, or TMDB id/link..."
value="{{ media_details.title if media_details else '' }}"
>
<button type="button" class="btn-ui btn-primary" onclick="searchRescanCandidates()">
<i class="fa-solid fa-magnifying-glass"></i> Search Matches
</button>
</div>
<div id="rescan-state" class="muted text-sm mt-4 hidden"></div>
<div id="rescan-results" class="grid grid-cols-1 xl:grid-cols-2 gap-3 mt-4"></div>
<div id="rescan-preview" class="hidden mt-5 rounded-3xl border border-hairline bg-surface p-4 sm:p-5">
<div class="flex items-start gap-4">
<img id="rescan-preview-poster" src="/static/placeholder.svg" alt="Selected poster" class="match-thumb">
<div class="min-w-0 flex-1">
<h4 id="rescan-preview-title" class="text-text font-semibold text-lg"></h4>
<p id="rescan-preview-subtitle" class="muted text-sm mt-1"></p>
<p id="rescan-preview-ids" class="muted text-xs mt-2 break-all"></p>
</div>
</div>
<div class="flex flex-col sm:flex-row justify-end gap-3 mt-5">
<button type="button" onclick="clearRescanSelection()" class="btn-ui btn-ghost">Cancel</button>
<button type="button" onclick="applyRescanSelection()" class="btn-ui btn-primary">
<i class="fa-solid fa-wand-magic-sparkles"></i> Apply Selected Match
</button>
</div>
</div>
</div>
{% endif %}
{% if media_details %}
<div class="glass-card edit-panel hidden rounded-3xl p-5 sm:p-6 lg:p-8 mb-6 sm:mb-8" data-panel="catalog">
<div class="flex flex-col lg:flex-row lg:items-end lg:justify-between gap-3 mb-5 sm:mb-6">
<div>
<h3 class="section-title text-xl sm:text-2xl">Custom Catalog</h3>
<p class="muted mt-1 text-sm sm:text-base">Add this title directly into any custom Stremio catalog.</p>
</div>
<a href="/catalogs" class="btn-ui btn-ghost">Manage Catalogs</a>
</div>
<div class="grid grid-cols-1 lg:grid-cols-[1fr_auto_auto] gap-3">
<select id="custom-catalog-select" class="field-input">
<option value="">Loading catalogs...</option>
</select>
<button type="button" onclick="addCurrentMediaToCatalog()" class="btn-ui btn-primary">
<i class="fa-solid fa-plus"></i> Add to Catalog
</button>
<button type="button" onclick="removeCurrentMediaFromCatalog()" class="btn-ui btn-danger">
Remove
</button>
</div>
<div id="media-in-catalogs" class="flex flex-wrap gap-2 mt-3"></div>
<p id="custom-catalog-status" class="muted text-sm mt-3">Add this title to a catalog, then choose who can see it below.</p>
<div class="mt-5 pt-5" style="border-top:1px solid color-mix(in srgb, var(--border) 85%, transparent)">
<label class="field-label">Who can see this title</label>
<div class="flex flex-col sm:flex-row sm:items-center gap-3">
<select id="media-visibility" class="field-input" onchange="onMediaVisibilityChange()">
<option value="public">Everyone</option>
<option value="tokens">Specific users</option>
<option value="owner">Owner only (hidden)</option>
</select>
<button type="button" onclick="applyMediaVisibility()" class="btn-ui btn-primary sm:w-auto shrink-0">Apply</button>
</div>
<div id="media-token-picker-wrap" class="hidden mt-3">
<label class="field-label">Allowed users</label>
<div id="media-token-picker" class="me-token-picker"></div>
</div>
<p class="muted text-xs mt-3">This overrides the title's visibility in every custom catalog it belongs to.</p>
</div>
</div>
{% endif %}
<style>
.me-token-picker { max-height: 12rem; overflow-y: auto; border: 1px solid color-mix(in srgb, var(--border) 95%, transparent); border-radius: 0.9rem; padding: .5rem; display: flex; flex-direction: column; gap: .35rem; background: color-mix(in srgb, var(--bg) 74%, transparent); }
.me-token-row { display: flex; align-items: center; gap: .6rem; padding: .5rem .65rem; border-radius: .7rem; cursor: pointer; }
.me-token-row:hover { background: color-mix(in srgb, var(--primary) 10%, transparent); }
.me-token-row input { width: 1.05rem; height: 1.05rem; accent-color: var(--primary); cursor: pointer; flex-shrink: 0; }
.me-chip { display: inline-flex; align-items: center; gap: .35rem; padding: .3rem .7rem; border-radius: 9999px; font-size: .75rem; font-weight: 600; border: 1px solid var(--border); max-width: 100%; }
.me-chip-hidden { color: var(--danger); background: color-mix(in srgb, var(--danger) 14%, transparent); border-color: color-mix(in srgb, var(--danger) 30%, transparent); }
.me-chip-custom { color: var(--info); background: color-mix(in srgb, var(--info) 14%, transparent); border-color: color-mix(in srgb, var(--info) 30%, transparent); }
.me-chip-auto { color: var(--ok); background: color-mix(in srgb, var(--ok) 14%, transparent); border-color: color-mix(in srgb, var(--ok) 30%, transparent); }
.me-chip-empty { color: var(--text-sec); background: color-mix(in srgb, var(--bg) 70%, transparent); }
</style>
<div class="glass-card edit-panel rounded-3xl p-5 sm:p-6 lg:p-8 mb-6 sm:mb-8" data-panel="details">
<div class="flex items-center justify-between gap-3 mb-5 sm:mb-6">
<h3 class="section-title text-xl sm:text-2xl">Edit Details</h3>
</div>
<form onsubmit="updateMedia(event)" id="edit-form">
<div class="grid grid-cols-1 md:grid-cols-2 gap-4 sm:gap-5 lg:gap-6 mb-6">
<div class="md:col-span-2">
<label class="field-label">Title *</label>
<input type="text" id="title" name="title" value="{{ media_details.title if media_details else '' }}"
class="field-input" required>
</div>
<div>
<label class="field-label">Release Year *</label>
<input type="number" id="release_year" name="release_year"
value="{{ media_details.release_year if media_details else '' }}"
class="field-input" required>
</div>
<div>
<label class="field-label">Rating (0-10)</label>
<input type="number" step="0.1" min="0" max="10" id="rating" name="rating"
value="{{ media_details.rating if media_details else '' }}"
class="field-input">
</div>
<div class="md:col-span-2">
<label class="field-label">Logo URL</label>
<input type="url" id="logo" name="logo" value="{{ media_details.logo if media_details else '' }}"
class="field-input">
</div>
<div class="md:col-span-2">
<label class="field-label">Poster URL</label>
<input type="url" id="poster" name="poster" value="{{ media_details.poster if media_details else '' }}"
class="field-input">
</div>
<div class="md:col-span-2">
<label class="field-label">Backdrop URL</label>
<input type="url" id="backdrop" name="backdrop"
value="{{ media_details.backdrop if media_details else '' }}"
class="field-input">
</div>
</div>
<div class="mb-6">
<label class="field-label">Description</label>
<textarea id="description" name="description" rows="4"
class="field-textarea resize-y">{{ media_details.description if media_details else '' }}</textarea>
</div>
<div class="mb-6">
<label class="field-label">Genres (comma-separated)</label>
<input type="text" id="genres" name="genres"
value="{% if media_details and media_details.genres %}{{ media_details.genres|join(', ') }}{% endif %}"
class="field-input" placeholder="Action, Comedy, Drama">
</div>
<div class="flex flex-col sm:flex-row justify-end gap-3">
<button type="button" onclick="goBackToList()" class="btn-ui btn-ghost">
Cancel
</button>
<button type="submit" class="btn-ui btn-primary" data-shortcut-save>
Save changes
</button>
</div>
</form>
</div>
{% if media_details %}
<div class="glass-card edit-panel hidden rounded-3xl p-5 sm:p-6" data-panel="content">
<div class="flex flex-wrap items-center justify-between gap-3 mb-5">
<div class="min-w-0">
<h3 class="section-title text-lg">{{ 'Files' if media_type == 'movie' else 'Episodes' }}</h3>
<p class="muted text-sm mt-0.5">
{%- if media_type == 'movie' -%}
{{ (media_details.telegram or [])|length }} file{{ '' if (media_details.telegram or [])|length == 1 else 's' }} indexed from Telegram
{%- else -%}
{% set ns = namespace(eps=0) %}{% for s in media_details.seasons or [] %}{% set ns.eps = ns.eps + s.episodes|length %}{% endfor %}
{{ (media_details.seasons or [])|length }} season{{ '' if (media_details.seasons or [])|length == 1 else 's' }} · {{ ns.eps }} episode{{ '' if ns.eps == 1 else 's' }}
{%- endif -%}
</p>
</div>
<button type="button" onclick="openAddStream()" class="btn-ui btn-ghost">
<i class="fa-solid fa-plus"></i> {{ 'Add episode or file' if media_type == 'tv' else 'Add file' }}
</button>
</div>
{% if media_type == 'movie' and media_details.telegram %}
<div class="file-list" id="movie-quality-list">
{% for quality in media_details.telegram|sort(attribute='quality', reverse=true) %}
<div class="file-row" data-quality-row>
<span class="q-badge q-{{ (quality.quality or '')|lower|replace('2160p','4k') }}">{{ quality.quality }}</span>
<div class="file-main">
<p class="file-name" title="{{ quality.name }}">{{ quality.name }}</p>
<p class="file-sub">{{ quality.size }}{% if quality.parts %} · {{ quality.parts|length }} parts{% endif %}</p>
</div>
<div class="file-actions">
<button type="button" class="icon-act" data-id="{{ quality.id }}" data-name="{{ quality.name }}" onclick="copyStreamLink(this.dataset.id, this.dataset.name)" title="Copy stream link" aria-label="Copy stream link"><i class="fa-solid fa-link"></i></button>
<button type="button" class="icon-act" data-id="{{ quality.id }}" data-q="{{ quality.quality }}" onclick="runSpeedTest(this.dataset.id, 'movie', this.dataset.q)" title="Speed test" aria-label="Speed test"><i class="fa-solid fa-gauge-high"></i></button>
<button type="button" class="icon-act danger" data-id="{{ quality.id }}" onclick="deleteQuality(this.dataset.id, this)" title="Delete file" aria-label="Delete file"><i class="fa-solid fa-trash-can"></i></button>
</div>
</div>
{% endfor %}
</div>
<div id="content-empty-state" class="hidden content-empty">
<i class="fa-solid fa-film"></i><p>No files left. Add one to make this title playable.</p>
</div>
{% elif media_type == 'tv' and media_details.seasons %}
{% set seasons_sorted = media_details.seasons|sort(attribute='season_number') %}
<div class="season-tabs" id="season-tabs" role="tablist"></div>
<div id="season-list">
{% for season in seasons_sorted %}
<section class="season-block{{ '' if loop.first else ' hidden' }}" data-season-block data-season="{{ season.season_number }}">
<div class="season-head">
<div class="min-w-0 flex-1">
<h4 class="font-semibold whitespace-nowrap">{{ 'Specials' if season.season_number == 0 else 'Season ' ~ season.season_number }}</h4>
<p class="muted text-sm" data-ep-count>{{ season.episodes|length }} episode{{ 's' if season.episodes|length != 1 else '' }}</p>
</div>
<button type="button" onclick="deleteTVSeason({{ season.season_number }}, this)" class="btn-ui btn-danger text-sm py-2 shrink-0" title="Delete season {{ season.season_number }}" aria-label="Delete season {{ season.season_number }}">
<i class="fa-solid fa-trash-can text-xs"></i><span class="hidden sm:inline">Delete season</span>
</button>
</div>
<div class="ep-list" data-episodes>
{% for episode in season.episodes|sort(attribute='episode_number') %}
{% set ep_title = (episode.title or '')|trim %}
<article class="ep" data-episode-block data-episode="{{ episode.episode_number }}">
<div class="ep-top">
<div class="ep-thumb">
<span class="ep-fallback">E{{ episode.episode_number }}</span>
{% if episode.episode_backdrop %}
<img src="{{ cover_url(episode.episode_backdrop) }}" alt="" loading="lazy" decoding="async" onerror="this.remove()">
{% endif %}
<span class="ep-num">{{ episode.episode_number }}</span>
</div>
<div class="ep-info">
<div class="ep-title-row">
<h5 class="ep-title">
{%- if ep_title and ep_title|lower != 'episode ' ~ episode.episode_number -%}{{ ep_title }}{%- else -%}Episode {{ episode.episode_number }}{%- endif -%}
</h5>
<button type="button" onclick="deleteTVEpisode({{ season.season_number }}, {{ episode.episode_number }}, this)" class="icon-act danger shrink-0" title="Delete episode" aria-label="Delete episode {{ episode.episode_number }}"><i class="fa-solid fa-trash-can"></i></button>
</div>
<p class="ep-meta">
S{{ '%02d'|format(season.season_number) }}E{{ '%02d'|format(episode.episode_number) }}
{%- if episode.released %} · <time data-date="{{ episode.released }}">{{ episode.released[:10] }}</time>{% endif %}
· {{ (episode.telegram or [])|length }} file{{ '' if (episode.telegram or [])|length == 1 else 's' }}
</p>
{% if episode.overview %}<p class="ep-overview">{{ episode.overview }}</p>{% endif %}
</div>
</div>
<div class="file-list" data-ep-qualities>
{% if episode.telegram %}
{% for quality in episode.telegram|sort(attribute='quality', reverse=true) %}
<div class="file-row" data-tv-quality>
<span class="q-badge q-{{ (quality.quality or '')|lower|replace('2160p','4k') }}">{{ quality.quality }}</span>
<div class="file-main">
<p class="file-name" title="{{ quality.name }}">{{ quality.name }}</p>
<p class="file-sub">{{ quality.size }}{% if quality.parts %} · {{ quality.parts|length }} parts{% endif %}</p>
</div>
<div class="file-actions">
<button type="button" class="icon-act" data-id="{{ quality.id }}" data-name="{{ quality.name }}" onclick="copyStreamLink(this.dataset.id, this.dataset.name)" title="Copy stream link" aria-label="Copy stream link"><i class="fa-solid fa-link"></i></button>
<button type="button" class="icon-act" data-id="{{ quality.id }}" data-q="{{ quality.quality }}" onclick="runSpeedTest(this.dataset.id, 'tv', this.dataset.q)" title="Speed test" aria-label="Speed test"><i class="fa-solid fa-gauge-high"></i></button>
<button type="button" class="icon-act danger" data-id="{{ quality.id }}" onclick="deleteTVQuality({{ season.season_number }}, {{ episode.episode_number }}, this.dataset.id, this)" title="Delete file" aria-label="Delete file"><i class="fa-solid fa-trash-can"></i></button>
</div>
</div>
{% endfor %}
{% else %}
<p class="muted text-sm" data-no-qualities>No files for this episode</p>
{% endif %}
</div>
</article>
{% endfor %}
</div>
</section>
{% endfor %}
</div>
<div id="content-empty-state-tv" class="hidden content-empty">
<i class="fa-solid fa-tv"></i><p>No episodes left. Add one to make this series playable.</p>
</div>
{% else %}
<div class="content-empty">
<i class="fa-solid {{ 'fa-film' if media_type == 'movie' else 'fa-tv' }}"></i>
<p>Nothing indexed yet. Add a file from Telegram to make this title playable.</p>
</div>
{% endif %}
</div>
<div class="glass-card edit-panel hidden rounded-3xl p-5 sm:p-6 lg:p-8" data-panel="subtitles">
<div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3 mb-5">
<div>
<h3 class="section-title text-xl sm:text-2xl">Subtitles</h3>
<p class="muted text-sm mt-1">Attach subtitle files from a Telegram channel your bot can read.</p>
</div>
<button type="button" onclick="openSubtitleModal()" class="btn-ui btn-success"><i class="fa-solid fa-plus"></i> Add Subtitle</button>
</div>
<div id="subtitle-list" class="space-y-2"></div>
<div id="subtitle-empty" class="hidden text-center py-8"><p class="muted text-sm">No subtitles added yet.</p></div>
</div>
{% endif %}
</div>
<div id="speed-test-modal" class="fixed inset-0 z-50 hidden" aria-modal="true" role="dialog">
<div class="absolute inset-0 bg-black/60 backdrop-blur-sm" onclick="closeSpeedTest()"></div>
<div class="absolute inset-0 flex items-center justify-center p-2 sm:p-4">
<div class="glass-card speed-modal-shell rounded-2xl sm:rounded-3xl">
<div class="flex items-start sm:items-center justify-between gap-3 px-4 sm:px-6 py-4 border-b border-hairline bg-surface">
<div class="min-w-0">
<h2 class="text-base sm:text-xl font-semibold text-text leading-tight"><i class="fa-solid fa-gauge-high"></i> DC Speed Test</h2>
<p id="st-label" class="text-[11px] sm:text-sm text-text-secondary mt-1 break-all"></p>
</div>
<button onclick="closeSpeedTest()" class="icon-btn shrink-0" aria-label="Close"><i class="fa-solid fa-xmark"></i></button>
</div>
<div class="speed-modal-body px-4 sm:px-6 py-5 sm:py-6">
<div id="st-spinner" class="flex flex-col items-center gap-4 py-8 sm:py-10">
<div class="w-12 h-12 sm:w-14 sm:h-14 rounded-full border-4 border-hairline-strong border-t-primary st-spin"></div>
<p class="text-sm text-text text-center">Testing all DC clients simultaneously…</p>
<p class="text-xs text-text-secondary text-center max-w-md">Downloading 100 MB from each bot client</p>
</div>
<div id="st-results" class="hidden">
<div class="overflow-x-auto rounded-2xl border border-hairline">
<table class="st-table w-full sm:min-w-[760px] text-sm">
<thead class="bg-surface text-left">
<tr class="text-text-secondary">
<th class="px-4 py-3 font-semibold text-xs uppercase tracking-wider whitespace-nowrap">Bot / DC</th>
<th class="px-4 py-3 font-semibold text-xs uppercase tracking-wider whitespace-nowrap">Ping</th>
<th class="px-4 py-3 font-semibold text-xs uppercase tracking-wider whitespace-nowrap">Speed</th>
<th class="px-4 py-3 font-semibold text-xs uppercase tracking-wider whitespace-nowrap">Time</th>
<th class="px-4 py-3 font-semibold text-xs uppercase tracking-wider whitespace-nowrap">Downloaded</th>
<th class="px-4 py-3 font-semibold text-xs uppercase tracking-wider whitespace-nowrap">Status</th>
</tr>
</thead>
<tbody id="st-tbody" class="divide-y divide-hairline bg-surface"></tbody>
</table>
</div>
<p id="st-summary" class="text-xs text-text-secondary mt-3 text-center sm:text-right"></p>
</div>
<div id="st-error" class="hidden mt-2 rounded-2xl border border-red-500/25 bg-red-500/10 px-4 py-3 text-sm text-red-200"></div>
</div>
<div class="st-actions flex flex-row justify-end gap-3 px-4 sm:px-6 py-3 sm:py-4 border-t border-hairline bg-surface">
<button id="st-rerun-btn" onclick="rerunSpeedTest()" class="hidden btn-ui btn-primary">
<i class="fa-solid fa-rotate"></i> Re-run
</button>
<button onclick="closeSpeedTest()" class="btn-ui btn-ghost">
Close
</button>
</div>
</div>
</div>
</div>
<style>
#add-stream-modal .as-input {
width: 100%; border-radius: 0.85rem;
border: 1px solid color-mix(in srgb, var(--border) 95%, transparent);
background: color-mix(in srgb, var(--bg) 78%, transparent);
color: var(--text); padding: 0.7rem 0.9rem; font-size: 0.9rem; outline: none;
}
#add-stream-modal .as-input:focus { border-color: var(--primary); box-shadow: 0 0 0 3px color-mix(in srgb, var(--primary) 16%, transparent); }
#add-stream-modal .as-label { display:block; font-size:0.72rem; font-weight: 600; text-transform:uppercase; letter-spacing:0.04em; color:var(--text-sec); margin-bottom:0.35rem; }
#add-stream-modal .as-btn { display:inline-flex; align-items:center; justify-content:center; gap:0.4rem; border-radius:0.85rem; padding:0.7rem 1.1rem; font-weight: 600; font-size:0.88rem; border:1px solid transparent; cursor:pointer; white-space:nowrap; transition:filter .15s ease; }
#add-stream-modal .as-btn:hover { filter: brightness(1.06); }
#add-stream-modal .as-btn-ghost { background: color-mix(in srgb, var(--bg) 74%, transparent); color: var(--text); border-color: color-mix(in srgb, var(--border) 95%, transparent); }
#add-stream-modal .as-btn-success { background: var(--ok); color:#fff; }
</style>
<div id="add-stream-modal" class="fixed inset-0 z-50 hidden" aria-modal="true" role="dialog">
<div class="absolute inset-0 bg-black/60 backdrop-blur-sm" onclick="closeAddStream()"></div>
<div class="absolute inset-0 flex items-end sm:items-center justify-center p-0 sm:p-4">
<div class="glass-card w-full sm:max-w-xl rounded-t-3xl sm:rounded-3xl max-h-[92dvh] sm:max-h-[90dvh] flex flex-col">
<div class="flex items-center justify-between gap-3 px-4 sm:px-6 py-4 border-b border-hairline">
<h2 class="text-base sm:text-xl font-semibold text-text"><i class="fa-solid fa-plus"></i> Add Stream</h2>
<button onclick="closeAddStream()" class="icon-btn shrink-0" aria-label="Close"><i class="fa-solid fa-xmark"></i></button>
</div>
<div class="px-4 sm:px-6 py-5 space-y-4 overflow-y-auto flex-1 min-h-0">
{% if media_type == 'tv' %}
<div class="grid grid-cols-2 gap-3">
<div>
<label class="as-label">Season *</label>
<input id="as-season" type="number" min="0" class="as-input" placeholder="1">
</div>
<div>
<label class="as-label">Episode *</label>
<input id="as-episode" type="number" min="0" class="as-input" placeholder="1">
</div>
<div class="col-span-2">
<label class="as-label">Episode Title</label>
<input id="as-episode-title" class="as-input" placeholder="Optional">
</div>
</div>
<p class="text-xs text-text-secondary">New season/episode numbers are created automatically; existing ones just get the new stream.</p>
{% endif %}
<div>
<div class="flex items-center justify-between gap-2">
<label class="as-label" style="margin-bottom:0">Telegram message link(s) *</label>
<button type="button" onclick="addStreamPart()" class="text-xs font-semibold text-primary shrink-0"><i class="fa-solid fa-plus"></i> Add split part</button>
</div>
<div id="as-parts" class="space-y-2 mt-2"></div>
<p class="text-xs text-text-secondary mt-2">Add more parts only for a split file (they join into one stream, in order).</p>
<p id="as-resolve-state" class="text-xs text-text-secondary mt-1 hidden"></p>
</div>
<div class="grid grid-cols-1 sm:grid-cols-3 gap-3">
<div>
<label class="as-label">Quality *</label>
<select id="as-quality" class="as-input" onchange="document.getElementById('as-quality-custom').classList.toggle('hidden', this.value !== '__custom')">
<option value="">Select</option>
<option>480p</option><option>720p</option><option selected>1080p</option>
<option>2160p</option><option value="__custom">Custom…</option>
</select>
</div>
<div class="sm:col-span-2">
<label class="as-label">File name</label>
<input id="as-name" class="as-input" placeholder="Auto-detected on resolve">
</div>
</div>
<input id="as-quality-custom" class="as-input hidden" placeholder="Custom quality label (e.g. 4K HDR)">
</div>
<div class="flex flex-col sm:flex-row sm:justify-end gap-2 sm:gap-3 px-4 sm:px-6 py-4 border-t border-hairline">
<button onclick="closeAddStream()" class="as-btn as-btn-ghost w-full sm:w-auto">Cancel</button>
<button id="as-submit" onclick="submitAddStream()" class="as-btn as-btn-success w-full sm:w-auto">Add Stream</button>
</div>
</div>
</div>
</div>
<div id="subtitle-modal" class="fixed inset-0 z-50 hidden" aria-modal="true" role="dialog">
<div class="absolute inset-0 bg-black/60 backdrop-blur-sm" onclick="closeSubtitleModal()"></div>
<div class="absolute inset-0 flex items-end sm:items-center justify-center p-0 sm:p-4">
<div class="glass-card w-full sm:max-w-xl rounded-t-3xl sm:rounded-3xl max-h-[92dvh] sm:max-h-[90dvh] flex flex-col">
<div class="flex items-center justify-between gap-3 px-4 sm:px-6 py-4 border-b border-hairline">
<h2 class="text-base sm:text-xl font-semibold text-text"><i class="fa-solid fa-plus"></i> Add Subtitle</h2>
<button onclick="closeSubtitleModal()" class="icon-btn shrink-0" aria-label="Close"><i class="fa-solid fa-xmark"></i></button>
</div>
<div class="px-4 sm:px-6 py-5 space-y-4 overflow-y-auto flex-1 min-h-0">
{% if media_type == 'tv' %}
<div class="grid grid-cols-2 gap-3">
<div>
<label class="block text-xs font-semibold uppercase tracking-wider text-text-secondary mb-2">Season *</label>
<input id="sub-season" type="number" min="0" class="field-input" placeholder="1">
</div>
<div>
<label class="block text-xs font-semibold uppercase tracking-wider text-text-secondary mb-2">Episode *</label>
<input id="sub-episode" type="number" min="0" class="field-input" placeholder="1">
</div>
</div>
{% endif %}
<div>
<div class="flex items-center justify-between gap-2 mb-2">
<label class="block text-xs font-semibold uppercase tracking-wider text-text-secondary">Subtitle link(s) *</label>
<button type="button" onclick="addSubtitleRow()" class="text-xs font-semibold text-primary shrink-0"><i class="fa-solid fa-plus"></i> Add another</button>
</div>
<div id="subtitle-rows" class="space-y-3"></div>
<p class="muted text-xs mt-2">Forward the subtitle file to a channel your bot admins (a MANUAL channel is recommended), then paste its message link. Language is auto-detected but you can override it.</p>
</div>
</div>
<div class="flex flex-col sm:flex-row sm:justify-end gap-2 sm:gap-3 px-4 sm:px-6 py-4 border-t border-hairline">
<button onclick="closeSubtitleModal()" class="btn-ui btn-ghost w-full sm:w-auto">Cancel</button>
<button id="sub-submit" onclick="submitSubtitles()" class="btn-ui btn-success w-full sm:w-auto">Add Subtitle</button>
</div>
</div>
</div>
</div>
<script>
const tmdbId = {{ tmdb_id }};
const dbIndex = {{ db_index }};
const mediaType = '{{ media_type }}';
let selectedRescanMatch = null;
let latestRescanResults = [];
function escapeHtml(value) {
return String(value ?? '')
.replaceAll('&', '&')
.replaceAll('<', '<')
.replaceAll('>', '>')
.replaceAll('"', '"')
.replaceAll("'", ''');
}
function setRescanState(message = '', visible = false) {
const el = document.getElementById('rescan-state');
if (!el) return;
el.textContent = message;
el.classList.toggle('hidden', !visible);
}
function clearRescanSelection() {
selectedRescanMatch = null;
document.querySelectorAll('.match-card').forEach(card => card.classList.remove('active'));
const preview = document.getElementById('rescan-preview');
if (preview) preview.classList.add('hidden');
}
function selectRescanMatch(index) {
const item = latestRescanResults[index];
if (!item) return;
selectedRescanMatch = item;
document.querySelectorAll('.match-card').forEach(card => card.classList.remove('active'));
const activeCard = document.getElementById(`match-card-${index}`);
if (activeCard) activeCard.classList.add('active');
document.getElementById('rescan-preview-title').textContent = item.title || 'Unknown title';
document.getElementById('rescan-preview-subtitle').textContent = `${item.subtitle || 'Match'}${item.year ? ` • ${item.year}` : ''}`;
document.getElementById('rescan-preview-ids').textContent = `IMDb: ${item.imdb_id || 'N/A'} • TMDb: ${item.tmdb_id || 'N/A'}`;
document.getElementById('rescan-preview-poster').src = item.poster || '/static/placeholder.svg';
document.getElementById('rescan-preview').classList.remove('hidden');
}
async function searchRescanCandidates() {
const query = document.getElementById('rescan-query').value.trim();
const resultsEl = document.getElementById('rescan-results');
if (!query) {
showErrorMessage('Please enter a title to search.');
return;
}
clearRescanSelection();
latestRescanResults = [];
resultsEl.innerHTML = '';
setRescanState('Searching matches...', true);
try {
const params = new URLSearchParams({
media_type: mediaType,
query
});
const yearValue = document.getElementById('release_year')?.value;
if (yearValue) {
params.set('year', yearValue);
}
const response = await fetch(`/api/media/rescan/search?${params.toString()}`);
const data = await response.json().catch(() => ({}));
if (!response.ok) {
setRescanState('', false);
showErrorMessage(data.detail || 'Failed to search matches.');
return;
}
const results = data.results || [];
latestRescanResults = results;
if (!results.length) {
setRescanState('No matches found.', true);
return;
}
setRescanState(`Found ${results.length} match${results.length > 1 ? 'es' : ''}. Select one below.`, true);
resultsEl.innerHTML = results.map((item, index) => `
<button
type="button"
id="match-card-${index}"
class="match-card text-left w-full"
data-index="${index}"
>
<div class="flex items-start gap-4">
<img
src="${item.poster || '/static/placeholder.svg'}"
alt="${escapeHtml(item.title || 'Poster')}"
class="match-thumb"
onerror="this.src='/static/placeholder.svg'"
>
<div class="min-w-0 flex-1">
<div class="flex flex-wrap items-center gap-2">
<h4 class="text-text font-semibold text-base sm:text-lg">${escapeHtml(item.title || 'Unknown title')}</h4>
<span class="pill">${escapeHtml(item.year || '—')}</span>
</div>
<p class="muted text-sm mt-2">${escapeHtml(item.subtitle || '')}</p>
<p class="muted text-xs mt-2 break-all">
IMDb: ${escapeHtml(item.imdb_id || 'N/A')} · TMDb: ${escapeHtml(item.tmdb_id || 'N/A')}
</p>
</div>
</div>
</button>
`).join('');
document.querySelectorAll('#rescan-results .match-card').forEach((card) => {
card.addEventListener('click', () => {
const index = Number(card.dataset.index);
selectRescanMatch(index);
});
});
} catch (error) {
console.error('Rescan search failed:', error);
setRescanState('', false);
showErrorMessage('Failed to search matches. Please try again.');
}
}
async function tagMediaFiles() {
try {
const response = await fetch(`/api/media/tag?tmdb_id=${tmdbId}&db_index=${dbIndex}&media_type=${mediaType}`, { method: 'POST' });
const data = await response.json().catch(() => ({}));
if (!response.ok) return showErrorMessage(data.detail || 'Failed to tag files.');
showSuccessMessage(data.message);
} catch (error) {
showErrorMessage('Failed to tag files. Please try again.');
}
}
async function applyRescanSelection() {
if (!selectedRescanMatch) {
showErrorMessage('Please select a match first.');
return;
}
const selectedId = selectedRescanMatch.tmdb_id || selectedRescanMatch.imdb_id;
if (!selectedId) {
showErrorMessage('Selected match does not contain a valid IMDb/TMDb id.');
return;
}
if (!confirm(`Replace current metadata with "${selectedRescanMatch.title}"?\n\nExisting Telegram files will stay safe.`)) {
return;
}
try {
const response = await fetch(`/api/media/rescan/apply?tmdb_id=${tmdbId}&db_index=${dbIndex}&media_type=${mediaType}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ selected_id: String(selectedId) })
});
const data = await response.json().catch(() => ({}));
if (!response.ok) {
showErrorMessage(data.detail || 'Failed to apply selected metadata.');
return;
}
showSuccessMessage(data.message || 'Metadata rescanned successfully.');
const newTmdbId = data.redirect_tmdb_id || tmdbId;
const newDbIndex = data.db_index || dbIndex;
setTimeout(() => {
window.location.href = `/media/edit?tmdb_id=${newTmdbId}&db_index=${newDbIndex}&media_type=${mediaType}`;
}, 700);
} catch (error) {
console.error('Apply rescan failed:', error);
showErrorMessage('Failed to apply selected metadata. Please try again.');
}
}
function toggleSeason(seasonIndex) {
const content = document.getElementById(`season-content-${seasonIndex}`);
const arrow = document.getElementById(`season-arrow-${seasonIndex}`);
if (!content || !arrow) return;
const collapsed = content.classList.contains('season-collapsed');
if (collapsed) {
content.classList.remove('season-collapsed');
arrow.style.transform = 'rotate(0deg)';
requestAnimationFrame(() => {
content.style.maxHeight = content.scrollHeight + 'px';
content.style.opacity = '1';
});
} else {
content.style.maxHeight = content.scrollHeight + 'px';
requestAnimationFrame(() => {
content.classList.add('season-collapsed');
content.style.maxHeight = '0px';
content.style.opacity = '0';
arrow.style.transform = 'rotate(-90deg)';
});
}
}
async function updateMedia(event) {
event.preventDefault();
const formData = new FormData(event.target);
const updateData = {};
for (let [key, value] of formData.entries()) {
if (key === 'genres') {
updateData[key] = value.split(',').map(g => g.trim()).filter(Boolean);
} else if (key === 'rating' || key === 'release_year' || key === 'runtime') {
updateData[key] = value ? parseFloat(value) : null;
} else {
updateData[key] = value || null;
}
}
try {
const response = await fetch(`/api/media/update?tmdb_id=${tmdbId}&db_index=${dbIndex}&media_type=${mediaType}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(updateData)
});
if (response.ok) {
showSuccessMessage('Media updated successfully');
setTimeout(() => location.reload(), 900);
} else {
const error = await response.json().catch(() => ({}));
showErrorMessage(`Error updating media: ${error.detail || 'Unknown error'}`);
}
} catch (error) {
console.error('Error updating media:', error);
showErrorMessage('Error updating media. Please try again.');
}
}
function _refreshSeasonHeight(node) {
const content = node.closest('.season-content') || (node.querySelector ? node.querySelector('.season-content') : null);
if (content && !content.classList.contains('season-collapsed')) {
requestAnimationFrame(() => { content.style.maxHeight = content.scrollHeight + 'px'; });
}
}
function _updateSeasonCount(seasonBlock) {
const count = seasonBlock.querySelectorAll('[data-episode-block]').length;
const label = seasonBlock.querySelector('[data-ep-count]');
if (label) label.textContent = `${count} episode${count !== 1 ? 's' : ''}`;
return count;
}
function _checkContentEmpty(listId, emptyId) {
const list = document.getElementById(listId);
if (list && !list.querySelector(list === document.getElementById('season-list') ? '[data-season-block]' : '[data-quality-row]')) {
list.classList.add('hidden');
document.getElementById(emptyId)?.classList.remove('hidden');
}
}
async function deleteQuality(id, btn) {
if (!confirm(`Are you sure you want to delete ${id}?`)) return;
try {
const response = await fetch(`/api/media/delete-quality?tmdb_id=${tmdbId}&db_index=${dbIndex}&id=${encodeURIComponent(id)}`, {
method: 'DELETE'
});
if (response.ok) {
showSuccessMessage(`${id} deleted successfully`);
btn?.closest('[data-quality-row]')?.remove();
_checkContentEmpty('movie-quality-list', 'content-empty-state');
} else {
const error = await response.json().catch(() => ({}));
showErrorMessage(`Error deleting: ${error.detail || 'Unknown error'}`);
}
} catch (error) {
console.error('Error deleting:', error);
showErrorMessage('Error deleting. Please try again.');
}
}
async function deleteTVQuality(season, episode, id, btn) {
if (!confirm(`Are you sure you want to delete ${id} from Season ${season} Episode ${episode}?`)) return;
try {
const response = await fetch(`/api/media/delete-tv-quality?tmdb_id=${tmdbId}&db_index=${dbIndex}&season=${season}&episode=${episode}&id=${encodeURIComponent(id)}`, {
method: 'DELETE'
});
if (response.ok) {
showSuccessMessage(`${id} deleted successfully`);
const epBlock = btn?.closest('[data-episode-block]');
btn?.closest('[data-tv-quality]')?.remove();
if (epBlock) {
const qWrap = epBlock.querySelector('[data-ep-qualities]');
if (qWrap && !qWrap.querySelector('[data-tv-quality]')) {
qWrap.innerHTML = '<p class="muted text-xs sm:text-sm text-center sm:text-left" data-no-qualities>No qualities available</p>';
}
_refreshSeasonHeight(epBlock);
}
} else {
const error = await response.json().catch(() => ({}));
showErrorMessage(`Error deleting: ${error.detail || 'Unknown error'}`);
}
} catch (error) {
console.error('Error deleting:', error);
showErrorMessage('Error deleting. Please try again.');
}
}
async function deleteTVEpisode(season, episode, btn) {
if (!confirm(`Delete Season ${season} Episode ${episode}? This removes the episode and all its qualities.`)) return;
try {
const response = await fetch(`/api/media/delete-tv-episode?tmdb_id=${tmdbId}&db_index=${dbIndex}&season=${season}&episode=${episode}`, {
method: 'DELETE'
});
if (response.ok) {
showSuccessMessage(`Episode ${episode} deleted successfully`);
const seasonBlock = btn?.closest('[data-season-block]');
btn?.closest('[data-episode-block]')?.remove();
if (seasonBlock) {
if (_updateSeasonCount(seasonBlock) === 0) {
seasonBlock.remove();
_checkContentEmpty('season-list', 'content-empty-state-tv');
} else {
_refreshSeasonHeight(seasonBlock);
}
}
} else {
const error = await response.json().catch(() => ({}));
showErrorMessage(`Error deleting episode: ${error.detail || 'Unknown error'}`);
}
} catch (error) {
console.error('Error deleting episode:', error);
showErrorMessage('Error deleting episode. Please try again.');
}
}
async function deleteTVSeason(season, btn) {
if (!confirm(`Delete the entire Season ${season}? This action cannot be undone.`)) return;
try {
const response = await fetch(`/api/media/delete-tv-season?tmdb_id=${tmdbId}&db_index=${dbIndex}&season=${season}`, {
method: 'DELETE'
});
if (response.ok) {
showSuccessMessage(`Season ${season} deleted successfully`);
btn?.closest('[data-season-block]')?.remove();
_checkContentEmpty('season-list', 'content-empty-state-tv');
} else {
const error = await response.json().catch(() => ({}));
showErrorMessage(`Error deleting season: ${error.detail || 'Unknown error'}`);
}
} catch (error) {
console.error('Error deleting season:', error);
showErrorMessage('Error deleting season. Please try again.');
}
}
function showSuccessMessage(message) {
showToast(message, 'success', 'Success');
}
function showErrorMessage(message) {
showToast(message, 'error', 'Error');
}
function copyStreamLink(qualityId, fileName) {
const base = window.location.origin;
const token = getCopylinkToken();
if (!token) {
showErrorMessage('No API token found. Please create an API token on the Dashboard page first.');
return;
}
const encodedName = encodeURIComponent(fileName || 'stream');
const url = `${base}/dl/${token}/${qualityId}/${encodedName}`;
navigator.clipboard.writeText(url).then(() => {
showSuccessMessage('Stream link copied to clipboard!');
}).catch(() => {
prompt('Copy this stream link:', url);
});
}
function getCopylinkToken() {
const serverToken = {{ (api_token | tojson) if api_token else 'null' }};
return serverToken || sessionStorage.getItem('api_token') || localStorage.getItem('api_token') || null;
}
const CURRENT_TMDB_ID = Number("{{ tmdb_id }}");
const CURRENT_DB_INDEX = Number("{{ db_index }}");
const CURRENT_MEDIA_TYPE = "{{ media_type }}";
let meSubscriptionOn = false;
let meTokens = [];
function mePublicLabel() { return meSubscriptionOn ? 'Active subscribers' : 'Everyone'; }
async function loadMediaVisibilityDeps() {
try {
const [sRes, tRes] = await Promise.all([
fetch('/api/admin/settings'),
fetch('/api/admin/access/tokens')
]);
const sData = await sRes.json().catch(() => ({}));
const tData = await tRes.json().catch(() => ({}));
meSubscriptionOn = !!(sData.settings && sData.settings.subscription);
meTokens = (tData.tokens || []).filter(t => t.token);
} catch (e) {}
const opt = document.querySelector('#media-visibility option[value="public"]');
if (opt) opt.textContent = mePublicLabel();
await loadMediaVisibility();
}
function renderMediaTokenPicker(selected) {
const box = document.getElementById('media-token-picker');
if (!box) return;
const sel = new Set(selected || []);
if (!meTokens.length) {
box.innerHTML = '<p class="muted text-xs p-2">No users/tokens found. Create access tokens on the Access page first.</p>';
return;
}
box.innerHTML = meTokens.map(t => `
<label class="me-token-row">
<input type="checkbox" value="${escapeHtml(t.token)}" ${sel.has(t.token) ? 'checked' : ''}>
<span class="min-w-0">
<span class="font-semibold text-sm block truncate text-text">${escapeHtml(t.user_name || 'User')}</span>
<span class="muted text-xs block truncate">${escapeHtml((t.token || '').slice(0, 12))}…${t.user_id ? ' · ' + escapeHtml(t.user_id) : ''}</span>
</span>
</label>`).join('');
}
function getMediaPickedTokens() {
return Array.from(document.querySelectorAll('#media-token-picker input:checked')).map(i => i.value);
}
function onMediaVisibilityChange(selected) {
const mode = document.getElementById('media-visibility').value;
const wrap = document.getElementById('media-token-picker-wrap');
if (wrap) wrap.classList.toggle('hidden', mode !== 'tokens');
if (mode === 'tokens') renderMediaTokenPicker(selected || []);
}
async function loadMediaVisibility() {
try {
const params = new URLSearchParams({
tmdb_id: String(CURRENT_TMDB_ID),
db_index: String(CURRENT_DB_INDEX),
media_type: CURRENT_MEDIA_TYPE
});
const res = await fetch(`/api/custom-catalogs/media-visibility?${params}`);
const data = await res.json().catch(() => ({}));
const vis = data.visibility || {};
const mode = vis.visibility || 'public';
const sel = document.getElementById('media-visibility');
if (sel) sel.value = mode;
onMediaVisibilityChange(vis.allowed_tokens || []);
} catch (e) {
onMediaVisibilityChange([]);
}
}
async function applyMediaVisibility() {
const visibility = document.getElementById('media-visibility').value;
const allowed_tokens = visibility === 'tokens' ? getMediaPickedTokens() : [];
if (visibility === 'tokens' && !allowed_tokens.length) {
showErrorMessage('Select at least one user.');
return;
}
try {
const res = await fetch('/api/custom-catalogs/media-visibility', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
tmdb_id: CURRENT_TMDB_ID,
db_index: CURRENT_DB_INDEX,
media_type: CURRENT_MEDIA_TYPE,
visibility,
allowed_tokens
})
});
const data = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(data.detail || 'Failed to update visibility');
showSuccessMessage(data.message || 'Visibility updated.');
} catch (e) {
showErrorMessage(e.message || 'Failed to update visibility.');
}
}
function setCatalogStatus(message, type = 'info') {
const status = document.getElementById('custom-catalog-status');
if (!status) return;
status.textContent = message;
status.classList.remove('text-emerald-300', 'text-rose-300', 'text-amber-300');
if (type === 'success') status.classList.add('text-emerald-300');
if (type === 'error') status.classList.add('text-rose-300');
if (type === 'warn') status.classList.add('text-amber-300');
}
//----- Rank a catalog for default selection: hidden (3) > custom (2) > auto (1)
function catalogRank(c) {
const hidden = (c.visibility === 'owner') || (c.visible === false);
if (hidden) return 3;
if (!c.auto) return 2;
return 1;
}
//----- Show which catalogs this title currently belongs to
function renderMediaInCatalogs(catalogs) {
const box = document.getElementById('media-in-catalogs');
if (!box) return;
const inList = (catalogs || []).filter(c => c.contains_current);
if (!inList.length) {
box.innerHTML = '<span class="me-chip me-chip-empty">Not in any catalog yet</span>';
return;
}
inList.sort((a, b) => catalogRank(b) - catalogRank(a));
box.innerHTML = inList.map(c => {
const hidden = (c.visibility === 'owner') || (c.visible === false);
const kind = c.auto ? 'auto' : (hidden ? 'hidden' : 'custom');
const icon = c.auto ? '<i class="fa-solid fa-wand-magic-sparkles"></i>' : (hidden ? '<i class="fa-solid fa-lock"></i>' : '<i class="fa-solid fa-bullseye"></i>');
const label = c.auto ? 'Auto' : (hidden ? 'Hidden' : 'Custom');
const excl = c.exclusive ? ' · <i class="fa-solid fa-lock"></i>' : '';
return `<span class="me-chip me-chip-${kind}" title="${escapeHtml(label)} catalog">${icon} ${escapeHtml(c.name)}${excl}</span>`;
}).join('');
}
async function loadMediaCatalogDropdown(selectedCatalogId = '') {
const select = document.getElementById('custom-catalog-select');
if (!select) return;
select.disabled = true;
select.innerHTML = '<option value="">Loading catalogs...</option>';
setCatalogStatus('Loading custom catalogs...');
try {
const params = new URLSearchParams({
tmdb_id: String(CURRENT_TMDB_ID),
db_index: String(CURRENT_DB_INDEX),
media_type: CURRENT_MEDIA_TYPE
});
const res = await fetch(`/api/custom-catalogs?${params.toString()}`);
const data = await res.json().catch(() => ({}));
if (!res.ok) {
throw new Error(data.detail || 'Failed to load catalogs');
}
const catalogs = data.catalogs || [];
if (!catalogs.length) {
select.innerHTML = '<option value="">No custom catalog found</option>';
setCatalogStatus('Create a catalog first from Manage Catalogs.', 'warn');
return;
}
select.innerHTML = catalogs.map(catalog => {
const visibility = catalog.visible ? 'Visible' : 'Hidden';
const added = catalog.contains_current ? ' · Added' : '';
return `<option value="${escapeHtml(catalog._id)}" data-visible="${catalog.visible ? '1' : '0'}" data-added="${catalog.contains_current ? '1' : '0'}">${escapeHtml(catalog.name)} (${visibility}${added})</option>`;
}).join('');
renderMediaInCatalogs(catalogs);
//----- Pre-select the catalog this title lives in: hidden > custom > auto
const containing = catalogs.filter(c => c.contains_current);
const priority = [...containing].sort((a, b) => catalogRank(b) - catalogRank(a))[0];
if (selectedCatalogId && catalogs.some(c => c._id === selectedCatalogId)) {
select.value = selectedCatalogId;
} else if (priority) {
select.value = priority._id;
}
select.disabled = false;
updateCatalogDropdownStatus();
} catch (error) {
select.innerHTML = '<option value="">Failed to load catalogs</option>';
setCatalogStatus(error.message || 'Failed to load custom catalogs.', 'error');
showToast(error.message || 'Failed to load custom catalogs', 'error', 'Error');
}
}
function updateCatalogDropdownStatus() {
const select = document.getElementById('custom-catalog-select');
if (!select || !select.value) return;
const option = select.options[select.selectedIndex];
const isVisible = option?.dataset.visible === '1';
const isAdded = option?.dataset.added === '1';
if (isAdded) {
setCatalogStatus(`This title is already added to ${option.textContent.replace(' · Added', '')}.`, 'success');
} else if (!isVisible) {
setCatalogStatus('This catalog is hidden from Stremio main catalog screen, but you can still manage it here.', 'warn');
} else {
setCatalogStatus('This visible catalog will appear in Stremio main catalog screen.', 'info');
}
}
async function addCurrentMediaToCatalog() {
const select = document.getElementById('custom-catalog-select');
const catalogId = select?.value;
if (!catalogId) {
showToast('Please select a catalog first.', 'error', 'Error');
return;
}
try {
const res = await fetch(`/api/custom-catalogs/${catalogId}/items`, {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
tmdb_id: CURRENT_TMDB_ID,
db_index: CURRENT_DB_INDEX,
media_type: CURRENT_MEDIA_TYPE
})
});
const data = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(data.detail || 'Failed to add title to catalog');
let msg = data.message || 'Added to catalog.';
if (data.visibility_synced) {
await loadMediaVisibility();
msg += data.visibility_synced === 'owner'
? ' Title is now Owner only.'
: ' Title is now limited to specific users.';
}
showToast(msg, 'success', 'Success');
await loadMediaCatalogDropdown(catalogId);
} catch (error) {
showToast(error.message || 'Failed to add title to catalog', 'error', 'Error');
setCatalogStatus(error.message || 'Failed to add title to catalog.', 'error');
}
}
async function removeCurrentMediaFromCatalog() {
const select = document.getElementById('custom-catalog-select');
const catalogId = select?.value;
if (!catalogId) {
showToast('Please select a catalog first.', 'error', 'Error');
return;
}
try {
const params = new URLSearchParams({
tmdb_id: String(CURRENT_TMDB_ID),
db_index: String(CURRENT_DB_INDEX),
media_type: CURRENT_MEDIA_TYPE
});
const res = await fetch(`/api/custom-catalogs/${catalogId}/items?${params.toString()}`, {method: 'DELETE'});
const data = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(data.detail || 'Failed to remove title from catalog');
showToast(data.message || 'Removed from catalog.', data.removed === false ? 'info' : 'success', 'Done');
await loadMediaCatalogDropdown(catalogId);
} catch (error) {
showToast(error.message || 'Failed to remove title from catalog', 'error', 'Error');
setCatalogStatus(error.message || 'Failed to remove title from catalog.', 'error');
}
}
document.addEventListener('DOMContentLoaded', () => {
const select = document.getElementById('custom-catalog-select');
if (select) select.addEventListener('change', updateCatalogDropdownStatus);
loadMediaCatalogDropdown();
loadMediaVisibilityDeps();
document.querySelectorAll('.season-content').forEach((content, index) => {
if (index > 0) {
content.classList.add('season-collapsed');
content.style.maxHeight = '0px';
content.style.opacity = '0';
const arrow = document.getElementById(`season-arrow-${index}`);
if (arrow) arrow.style.transform = 'rotate(-90deg)';
} else {
content.style.maxHeight = content.scrollHeight + 'px';
content.style.opacity = '1';
}
});
});
let _stQualityId = null;
let _stMediaType = null;
let _stLabel = null;
async function runSpeedTest(qualityId, mediaTypeArg, label) {
_stQualityId = qualityId;
_stMediaType = mediaTypeArg;
_stLabel = label;
_openModal(label);
await _exec();
}
async function rerunSpeedTest() {
if (!_stQualityId) return;
_resetUI(_stLabel);
await _exec();
}
function _openModal(label) {
document.getElementById('speed-test-modal').classList.remove('hidden');
document.body.style.overflow = 'hidden';
_resetUI(label);
}
function _resetUI(label) {
document.getElementById('st-label').textContent = label ? `File: ${label}` : '';
document.getElementById('st-spinner').classList.remove('hidden');
document.getElementById('st-results').classList.add('hidden');
document.getElementById('st-error').classList.add('hidden');
document.getElementById('st-rerun-btn').classList.add('hidden');
document.getElementById('st-tbody').innerHTML = '';
document.getElementById('st-summary').textContent = '';
}
function closeSpeedTest() {
document.getElementById('speed-test-modal').classList.add('hidden');
document.body.style.overflow = '';
if (window._stEventSource) {
window._stEventSource.close();
window._stEventSource = null;
}
}
function _pingClass(ms) {
if (ms === null) return 'text-text-secondary';
if (ms < 100) return 'text-emerald-300 font-semibold';
if (ms < 300) return 'text-amber-300 font-semibold';
return 'text-rose-300 font-semibold';
}
function _speedClass(mbps) {
if (mbps === null) return 'text-text-secondary';
if (mbps >= 20) return 'text-emerald-300 font-semibold';
if (mbps >= 5) return 'text-amber-300 font-semibold';
return 'text-rose-300 font-semibold';
}
function _miniBar(value, max, color) {
if (!value || !max) return '';
const pct = Math.min(100, (value / max) * 100).toFixed(1);
return `<div class="w-full bg-surface-2 rounded-full h-1.5 mt-1 overflow-hidden">
<div class="${color} h-1.5 rounded-full transition-all" style="width:${pct}%"></div>
</div>`;
}
function _resultRow(r, medal, maxSpeed) {
const isErr = !!r.error && !r.speed_mbps;
const ping = r.ping_ms !== null ? `<span class="${_pingClass(r.ping_ms)}">${r.ping_ms} ms</span>` : '<span class="text-text-secondary">—</span>';
const speed = r.speed_mbps !== null
? `<span class="${_speedClass(r.speed_mbps)}">${r.speed_mbps.toFixed(2)} MB/s</span>
${_miniBar(r.speed_mbps, maxSpeed, r.speed_mbps >= 20 ? 'bg-emerald-400' : r.speed_mbps >= 5 ? 'bg-amber-300' : 'bg-rose-300')}`
: '<span class="text-text-secondary">—</span>';
const badge = isErr
? `<span class="px-2 py-0.5 rounded-full text-xs font-medium bg-rose-500/15 text-rose-200 border border-rose-500/20">Error</span>`
: `<span class="px-2 py-0.5 rounded-full text-xs font-medium bg-emerald-500/15 text-emerald-200 border border-emerald-500/20"><i class="fa-solid fa-check mr-1"></i>OK</span>`;
const tr = document.createElement('tr');
tr.className = `transition-colors ${isErr ? 'opacity-70' : ''}`;
tr.innerHTML = `
<td class="px-4 py-3 font-medium text-text">${medal}Bot ${r.client_index + 1} <span class="text-xs text-text-secondary">(DC ${r.dc_id})</span></td>
<td data-label="Ping" class="px-4 py-3 text-text">${ping}</td>
<td data-label="Speed" class="px-4 py-3 text-text">${speed}${isErr ? `<div class="text-xs text-rose-300 mt-1 break-words">${r.error}</div>` : ''}</td>
<td data-label="Time" class="px-4 py-3 text-text-secondary text-sm">${r.time_taken_sec !== null ? `${r.time_taken_sec.toFixed(2)}s` : '—'}</td>
<td data-label="Downloaded" class="px-4 py-3 text-text-secondary text-xs">${r.bytes_downloaded ? `${(r.bytes_downloaded / 1048576).toFixed(2)} MB` : '—'}</td>
<td data-label="Status" class="px-4 py-3">${badge}</td>`;
return tr;
}
async function _exec() {
const params = new URLSearchParams({
quality_id: _stQualityId,
tmdb_id: tmdbId,
db_index: dbIndex,
media_type: _stMediaType || mediaType
});
if (window._stEventSource) {
window._stEventSource.close();
window._stEventSource = null;
}
let maxSpeed = 1;
let completedCount = 0;
let totalCount = 0;
const allResults = [];
const pendingRows = {};
const es = new EventSource(`/api/system/speedtest/stream?${params}`);
window._stEventSource = es;
function updateSummary() {
const best = allResults.filter(r => r.speed_mbps).sort((a, b) => b.speed_mbps - a.speed_mbps)[0];
const summaryEl = document.getElementById('st-summary');
if (!summaryEl) return;
if (best) {
summaryEl.textContent = `Fastest: DC ${best.dc_id} — ${best.speed_mbps.toFixed(2)} MB/s | ${completedCount}/${totalCount} client(s) done`;
} else {
summaryEl.textContent = `${completedCount}/${totalCount} client(s) done`;
}
}
es.onmessage = (e) => {
let msg;
try { msg = JSON.parse(e.data); } catch { return; }
if (msg.type === 'error') {
es.close();
document.getElementById('st-spinner').classList.add('hidden');
document.getElementById('st-error').textContent = `Speed test stream error: ${msg.message}`;
document.getElementById('st-error').classList.remove('hidden');
document.getElementById('st-rerun-btn').classList.remove('hidden');
showToast(msg.message || 'Speed test failed.', 'error', 'Speed Test Error');
return;
}
if (msg.type === 'start') {
totalCount = msg.total;
document.getElementById('st-spinner').classList.add('hidden');
document.getElementById('st-results').classList.remove('hidden');
if (msg.target_dc && msg.target_dc !== "?") {
document.getElementById('st-label').innerHTML += ` | Target DC: <span class="text-text font-semibold">${msg.target_dc}</span>`;
}
const tbody = document.getElementById('st-tbody');
tbody.innerHTML = '';
for (let i = 0; i < totalCount; i++) {
const tr = document.createElement('tr');
tr.className = 'animate-pulse';
tr.innerHTML = `
<td class="px-4 py-3 font-medium text-text-secondary"><i class="fa-solid fa-rotate"></i> Bot ${i + 1}</td>
<td data-label="Ping" class="px-4 py-3"><span class="text-muted">testing…</span></td>
<td data-label="Speed" class="px-4 py-3"><span class="text-muted">testing…</span></td>
<td data-label="Time" class="px-4 py-3 text-muted">—</td>
<td data-label="Downloaded" class="px-4 py-3 text-muted">—</td>
<td data-label="Status" class="px-4 py-3"><span class="px-2 py-0.5 rounded-full text-xs bg-surface-2 text-text-secondary">Pending</span></td>`;
tbody.appendChild(tr);
pendingRows[i] = tr;
}
updateSummary();
}
if (msg.type === 'progress') {
const r = msg.data;
const tr = pendingRows[r.client_index];
if (tr) {
maxSpeed = Math.max(maxSpeed, r.speed_mbps || 0, 1);
const newTr = _resultRow(r, '', maxSpeed);
if (pendingRows[r.client_index]) {
pendingRows[r.client_index].replaceWith(newTr);
delete pendingRows[r.client_index];
} else {
document.getElementById('st-tbody').appendChild(newTr);
}
allResults.push(r);
completedCount += 1;
updateSummary();
}
}
if (msg.type === 'done') {
es.close();
window._stEventSource = null;
allResults.sort((a, b) => (b.speed_mbps || 0) - (a.speed_mbps || 0));
const tbody = document.getElementById('st-tbody');
tbody.innerHTML = '';
for (let i = 0; i < allResults.length; i++) {
const r = allResults[i];
const tr = _resultRow(r, i === 0 && r.speed_mbps ? '<i class="fa-solid fa-medal text-warn mr-1"></i>' : '', maxSpeed);
tbody.appendChild(tr);
}
document.getElementById('st-rerun-btn').classList.remove('hidden');
updateSummary();
showToast('Speed test completed.', 'success', 'Speed Test');
}
};
es.onerror = () => {
es.close();
window._stEventSource = null;
if (completedCount === 0) {
document.getElementById('st-spinner').classList.add('hidden');
document.getElementById('st-error').textContent = 'Live tracking connection failed or interrupted.';
document.getElementById('st-error').classList.remove('hidden');
showToast('Live tracking connection failed or interrupted.', 'error', 'Speed Test Error');
}
document.getElementById('st-rerun-btn').classList.remove('hidden');
};
}
document.addEventListener('keydown', e => {
if (e.key === 'Escape') { closeSpeedTest(); closeAddStream(); }
});
function addStreamResetParts() {
document.getElementById('as-parts').innerHTML =
`<div class="flex flex-col sm:flex-row gap-2" data-part>
<input class="as-input as-part-url" placeholder="https://t.me/c/123456/789">
<button type="button" onclick="addStreamResolve()" class="as-btn as-btn-ghost w-full sm:w-auto">Resolve</button>
</div>`;
}
function addStreamPart() {
const div = document.createElement('div');
div.className = 'flex flex-col sm:flex-row gap-2';
div.setAttribute('data-part', '');
div.innerHTML = `<input class="as-input as-part-url" placeholder="Split part link (in order)">
<button type="button" onclick="this.closest('[data-part]').remove()" class="as-btn as-btn-ghost w-full sm:w-auto">Remove</button>`;
document.getElementById('as-parts').appendChild(div);
}
function addStreamCollectParts() {
return [...document.querySelectorAll('#as-parts .as-part-url')]
.map(i => i.value.trim()).filter(Boolean).map(url => ({ url }));
}
function openAddStream() {
['as-name', 'as-season', 'as-episode', 'as-episode-title', 'as-quality-custom'].forEach(id => {
const el = document.getElementById(id);
if (el) el.value = '';
});
addStreamResetParts();
const q = document.getElementById('as-quality');
if (q) q.value = '1080p';
document.getElementById('as-quality-custom')?.classList.add('hidden');
document.getElementById('as-resolve-state')?.classList.add('hidden');
document.getElementById('add-stream-modal').classList.remove('hidden');
document.body.style.overflow = 'hidden';
}
function closeAddStream() {
document.getElementById('add-stream-modal')?.classList.add('hidden');
document.body.style.overflow = '';
}
function addStreamQuality() {
const sel = document.getElementById('as-quality');
if (sel.value === '__custom') return document.getElementById('as-quality-custom').value.trim();
return sel.value;
}
async function addStreamResolve() {
const first = document.querySelector('#as-parts .as-part-url');
const url = first ? first.value.trim() : '';
const state = document.getElementById('as-resolve-state');
if (!url) { showErrorMessage('Paste a Telegram message link first.'); return; }
state.textContent = 'Resolving...';
state.classList.remove('hidden');
try {
const res = await fetch('/api/media/resolve-telegram', {
method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ url })
});
const data = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(data.detail || 'Could not resolve link');
const d = data.data || {};
document.getElementById('as-name').value = d.name || '';
if (d.quality) {
const sel = document.getElementById('as-quality');
const custom = document.getElementById('as-quality-custom');
const opt = [...sel.options].find(o => o.value.toLowerCase() === String(d.quality).toLowerCase());
if (opt) {
sel.value = opt.value;
custom.classList.add('hidden');
} else {
sel.value = '__custom';
custom.value = d.quality;
custom.classList.remove('hidden');
}
}
if (mediaType === 'tv') {
if (d.season != null && !document.getElementById('as-season').value) document.getElementById('as-season').value = d.season;
if (d.episode != null && !document.getElementById('as-episode').value) document.getElementById('as-episode').value = d.episode;
}
state.textContent = `Found: ${d.name || 'file'} (${d.size || '—'})`;
} catch (e) {
state.textContent = e.message || 'Could not resolve link.';
showErrorMessage(e.message || 'Could not resolve link.');
}
}
async function submitAddStream() {
const btn = document.getElementById('as-submit');
const parts = addStreamCollectParts();
const quality = addStreamQuality();
if (!parts.length) { showErrorMessage('Paste at least one Telegram message link.'); return; }
if (!quality) { showErrorMessage('Select a quality.'); return; }
const payload = {
media_type: mediaType,
tmdb_id: tmdbId,
db_index: dbIndex,
stream: { quality, name: document.getElementById('as-name').value.trim() || undefined, parts }
};
if (mediaType === 'tv') {
const s = document.getElementById('as-season').value.trim();
const ep = document.getElementById('as-episode').value.trim();
if (s === '' || ep === '') { showErrorMessage('Season and episode are required.'); return; }
payload.season_number = Number(s);
payload.episode_number = Number(ep);
payload.episode_title = document.getElementById('as-episode-title').value.trim() || undefined;
}
btn.disabled = true;
try {
const res = await fetch('/api/media/manual-add', {
method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload)
});
const data = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(data.detail || 'Failed to add stream');
showSuccessMessage(data.message || 'Stream added successfully.');
closeAddStream();
const goTmdb = data.tmdb_id || tmdbId;
const goDb = data.db_index || dbIndex;
setTimeout(() => {
window.location.href = `/media/edit?tmdb_id=${goTmdb}&db_index=${goDb}&media_type=${mediaType}`;
}, 700);
} catch (e) {
showErrorMessage(e.message || 'Failed to add stream.');
} finally {
btn.disabled = false;
}
}
let subtitleLanguages = [];
function subtitleLangOptions() {
const opts = ['<option value="">Auto-detect</option>'];
for (const l of subtitleLanguages) opts.push(`<option value="${l.code}">${l.label}</option>`);
return opts.join('');
}
function addSubtitleRow(url = '') {
const div = document.createElement('div');
div.className = 'flex flex-col sm:flex-row gap-2';
div.setAttribute('data-sub-row', '');
div.innerHTML = `<input class="field-input flex-1 sub-url" placeholder="Telegram message link" value="${url}">
<select class="field-input sub-lang">${subtitleLangOptions()}</select>
<button type="button" onclick="this.closest('[data-sub-row]').remove()" class="btn-ui btn-ghost w-full sm:w-auto">Remove</button>`;
document.getElementById('subtitle-rows').appendChild(div);
}
async function loadSubtitleLanguages() {
if (subtitleLanguages.length) return;
try {
const res = await fetch('/api/media/subtitles/languages');
const data = await res.json().catch(() => ({}));
subtitleLanguages = data.languages || [];
} catch (e) {}
}
async function loadSubtitles() {
const listEl = document.getElementById('subtitle-list');
const emptyEl = document.getElementById('subtitle-empty');
if (!listEl) return;
try {
const res = await fetch(`/api/media/subtitles?media_type=${mediaType}&tmdb_id=${tmdbId}&db_index=${dbIndex}`);
const data = await res.json().catch(() => ({}));
const subs = data.subtitles || [];
if (!subs.length) { listEl.innerHTML = ''; emptyEl.classList.remove('hidden'); return; }
emptyEl.classList.add('hidden');
listEl.innerHTML = subs.map(s => {
const pad = n => String(n).padStart(2, '0');
const where = (s.media_type === 'tv' && s.season) ? `S${pad(s.season)}E${pad(s.episode)} · ` : '';
return `<div class="quality-row rounded-2xl p-4 flex flex-col sm:flex-row sm:items-center justify-between gap-3">
<div class="min-w-0 flex-1">
<div class="flex flex-wrap items-center gap-2">
<span class="quality-badge bg-purple-500/15 text-purple-300 border border-purple-500/20">${s.lang_label || s.lang_code || 'Unknown'}</span>
<span class="pill">${where}${s.source || 'auto'}</span>
</div>
<p class="muted mt-2 text-sm break-all">${s.name || ''}</p>
</div>
<button onclick="removeSubtitle(${s.chat_id}, ${s.msg_id}, this)" class="btn-ui btn-danger w-full sm:w-auto">Delete</button>
</div>`;
}).join('');
} catch (e) {
listEl.innerHTML = ''; emptyEl.classList.remove('hidden');
}
}
function openSubtitleModal() {
if (mediaType === 'tv') {
document.getElementById('sub-season').value = '';
document.getElementById('sub-episode').value = '';
}
document.getElementById('subtitle-rows').innerHTML = '';
addSubtitleRow();
document.getElementById('subtitle-modal').classList.remove('hidden');
document.body.style.overflow = 'hidden';
}
function closeSubtitleModal() {
document.getElementById('subtitle-modal')?.classList.add('hidden');
document.body.style.overflow = '';
}
async function submitSubtitles() {
const btn = document.getElementById('sub-submit');
let season = '', episode = '';
if (mediaType === 'tv') {
season = document.getElementById('sub-season').value.trim();
episode = document.getElementById('sub-episode').value.trim();
if (season === '' || episode === '') { showErrorMessage('Season and episode are required.'); return; }
}
const items = [...document.querySelectorAll('#subtitle-rows [data-sub-row]')].map(r => {
const url = r.querySelector('.sub-url').value.trim();
if (!url) return null;
const item = { url, lang_code: r.querySelector('.sub-lang').value || undefined };
if (mediaType === 'tv') { item.season = Number(season); item.episode = Number(episode); }
return item;
}).filter(Boolean);
if (!items.length) { showErrorMessage('Paste at least one subtitle link.'); return; }
btn.disabled = true;
try {
const res = await fetch('/api/media/subtitles/add', {
method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ media_type: mediaType, tmdb_id: tmdbId, db_index: dbIndex, items })
});
const data = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(data.detail || 'Failed to add subtitle');
showSuccessMessage(data.message || 'Subtitle added.');
closeSubtitleModal();
loadSubtitles();
} catch (e) {
showErrorMessage(e.message || 'Failed to add subtitle.');
} finally {
btn.disabled = false;
}
}
async function removeSubtitle(chatId, msgId, el) {
if (el) el.disabled = true;
try {
const res = await fetch('/api/media/subtitles/remove', {
method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ chat_id: chatId, msg_id: msgId })
});
const data = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(data.detail || 'Failed to remove subtitle');
showSuccessMessage(data.message || 'Subtitle removed.');
loadSubtitles();
} catch (e) {
if (el) el.disabled = false;
showErrorMessage(e.message || 'Failed to remove subtitle.');
}
}
function manageListUrl() {
const p = new URLSearchParams(location.search);
const params = new URLSearchParams();
params.set('media_type', mediaType);
const page = p.get('page');
const search = p.get('search');
if (page && parseInt(page, 10) > 1) params.set('page', page);
if (search) params.set('search', search);
return `/media/manage?${params.toString()}`;
}
function goBackToList() {
window.location.href = manageListUrl();
}
function refreshVisibleSeasonHeights() {
document.querySelectorAll('.season-content').forEach(content => {
if (!content.classList.contains('season-collapsed')) {
content.style.maxHeight = content.scrollHeight + 'px';
}
});
}
function switchEditTab(name, doScroll = true) {
document.querySelectorAll('.edit-tab').forEach(t => t.classList.toggle('active', t.dataset.tab === name));
document.querySelectorAll('.edit-panel').forEach(p => p.classList.toggle('hidden', p.dataset.panel !== name));
if (name === 'content') refreshVisibleSeasonHeights();
try { history.replaceState(null, '', '#' + name); } catch (e) {}
if (doScroll) {
const tabs = document.getElementById('edit-tabs');
if (tabs) tabs.scrollIntoView({ behavior: 'smooth', block: 'start' });
}
}
document.addEventListener('DOMContentLoaded', () => {
const valid = ['details', 'content', 'subtitles', 'catalog', 'rescan'];
const hash = (location.hash || '').replace('#', '');
if (valid.includes(hash)) {
switchEditTab(hash, false);
} else {
refreshVisibleSeasonHeights();
}
});
document.addEventListener('DOMContentLoaded', () => {
const backLink = document.getElementById('back-to-list');
if (backLink) backLink.href = manageListUrl();
if (document.getElementById('subtitle-list')) {
loadSubtitleLanguages().then(loadSubtitles);
}
});
(function seasonTabs() {
const list = document.getElementById('season-list');
const tabs = document.getElementById('season-tabs');
if (!list || !tabs) return;
let active = list.querySelector('[data-season-block]')?.dataset.season;
function render() {
const blocks = [...list.querySelectorAll('[data-season-block]')];
if (!blocks.some(b => b.dataset.season === active)) active = blocks[0]?.dataset.season;
tabs.hidden = blocks.length < 2;
tabs.innerHTML = blocks.map(b => {
const n = b.dataset.season;
const eps = b.querySelectorAll('[data-episode-block]').length;
return `<button type="button" class="season-tab" role="tab" data-season-tab="${n}" aria-selected="${n === active}">${n === '0' ? 'Specials' : 'Season ' + n}<span>${eps}</span></button>`;
}).join('');
blocks.forEach(b => b.classList.toggle('hidden', b.dataset.season !== active));
}
tabs.addEventListener('click', e => {
const t = e.target.closest('[data-season-tab]');
if (!t) return;
active = t.dataset.seasonTab;
render();
});
new MutationObserver(render).observe(list, { childList: true, subtree: true });
render();
})();
document.querySelectorAll('.file-list').forEach(list => {
const rank = row => parseInt(row.querySelector('.q-badge')?.textContent, 10) || (/4k/i.test(row.querySelector('.q-badge')?.textContent) ? 2160 : 0);
[...list.querySelectorAll(':scope > .file-row')].sort((a, b) => rank(b) - rank(a)).forEach(r => list.appendChild(r));
});
document.querySelectorAll('time[data-date]').forEach(el => {
const d = new Date(el.dataset.date);
if (!isNaN(d)) el.textContent = d.toLocaleDateString(undefined, { day: 'numeric', month: 'short', year: 'numeric' });
});
</script>
{% endblock %}
|