File size: 45,148 Bytes
e581a8c 36dde81 273ab56 e581a8c 273ab56 36dde81 273ab56 36dde81 273ab56 36dde81 273ab56 36dde81 e581a8c 36dde81 e581a8c 36dde81 273ab56 e581a8c 36dde81 273ab56 36dde81 273ab56 e581a8c 273ab56 36dde81 273ab56 e581a8c b8fe50f 273ab56 36dde81 273ab56 36dde81 273ab56 36dde81 273ab56 36dde81 273ab56 e581a8c 273ab56 36dde81 273ab56 e581a8c 36dde81 273ab56 36dde81 273ab56 36dde81 273ab56 e581a8c 36dde81 273ab56 36dde81 273ab56 36dde81 273ab56 36dde81 273ab56 36dde81 273ab56 36dde81 273ab56 36dde81 273ab56 36dde81 273ab56 36dde81 e581a8c 273ab56 36dde81 273ab56 e581a8c 273ab56 36dde81 e581a8c 36dde81 e581a8c 273ab56 36dde81 273ab56 36dde81 273ab56 e581a8c 273ab56 e581a8c 36dde81 e581a8c 36dde81 273ab56 e581a8c 36dde81 273ab56 36dde81 273ab56 36dde81 273ab56 36dde81 e581a8c 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 273ab56 e581a8c 273ab56 36dde81 e581a8c 36dde81 e581a8c 36dde81 e581a8c 36dde81 273ab56 e581a8c 36dde81 273ab56 36dde81 273ab56 e581a8c 36dde81 e581a8c 36dde81 e581a8c 36dde81 e581a8c 36dde81 e581a8c 36dde81 273ab56 36dde81 273ab56 36dde81 e581a8c 36dde81 e581a8c 36dde81 e581a8c 36dde81 e581a8c 36dde81 273ab56 36dde81 273ab56 36dde81 273ab56 36dde81 273ab56 36dde81 e581a8c 36dde81 e581a8c 36dde81 b8fe50f 36dde81 e581a8c b8fe50f 273ab56 e581a8c 36dde81 273ab56 e581a8c 36dde81 273ab56 36dde81 273ab56 36dde81 e581a8c 36dde81 e581a8c 36dde81 e581a8c 36dde81 273ab56 e581a8c 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 | {% extends "base.html" %}
{% block title %}Tokens & Access{% endblock %}
{% block content %}
<style>
.access-shell { display: flex; flex-direction: column; gap: 2rem; }
.section-panel, .stat-card, .mobile-token-card, .modal-glass { background: var(--card); border: 1px solid var(--border); }
.section-panel { border-radius: var(--radius); }
.empty-state { border-radius: var(--radius-sm); }
.section-title { color: var(--text); }
.section-muted, .text-soft { color: var(--text-sec); }
.glass-btn { display: inline-flex; align-items: center; justify-content: center; gap: .5rem; border: 1px solid var(--border); background: transparent; color: var(--text); border-radius: 9999px !important; font-weight: 500 !important; transition: background-color .15s var(--ease), border-color .15s var(--ease), transform .12s var(--ease); white-space: nowrap; }
.glass-btn:hover { background: var(--card-high); }
.glass-btn:active { transform: scale(.97); }
.glass-btn:disabled { opacity: .45; }
.glass-btn-primary { background: var(--primary); color: var(--on-primary); border-color: var(--primary); }
.glass-btn-primary:hover { background: var(--primary); filter: brightness(1.07); }
.glass-btn-success { color: var(--ok); border-color: color-mix(in srgb, var(--ok) 35%, transparent); background: color-mix(in srgb, var(--ok) 10%, transparent); }
.glass-btn-warning { color: var(--warn); border-color: color-mix(in srgb, var(--warn) 35%, transparent); background: color-mix(in srgb, var(--warn) 10%, transparent); }
.glass-btn-danger { color: var(--danger); border-color: color-mix(in srgb, var(--danger) 35%, transparent); background: color-mix(in srgb, var(--danger) 10%, transparent); }
.glass-btn-purple, .glass-btn-gold { color: var(--primary); border-color: color-mix(in srgb, var(--primary) 35%, transparent); background: color-mix(in srgb, var(--primary) 10%, transparent); }
.glass-input, .glass-select { width: 100%; border-radius: var(--radius-sm); border: 1px solid var(--border); background: var(--bg); color: var(--text); padding: .7rem 1rem; outline: none; font-size: .9rem; transition: border-color .18s var(--ease), box-shadow .18s var(--ease); }
.glass-input::placeholder { color: var(--text-sec); }
.glass-input:focus, .glass-select:focus { border-color: var(--primary); box-shadow: 0 0 0 3px var(--ring); }
.stats-row { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 1.5rem; padding: 1.25rem; background: var(--card); border: 1px solid var(--border); border-radius: var(--radius); }
.stat-value { font-size: 1.5rem; font-weight: 600; line-height: 1.1; font-variant-numeric: tabular-nums; }
.stat-label { margin-top: .2rem; font-size: .85rem; color: var(--text-sec); }
.table-shell { overflow: hidden; border: 1px solid var(--border); border-radius: var(--radius-sm); }
.access-table { width: 100%; border-collapse: separate; border-spacing: 0; }
.access-table thead th { background: var(--card); color: var(--text-sec); font-size: .72rem; font-weight: 500 !important; text-transform: uppercase; letter-spacing: .08em; border-bottom: 1px solid var(--border); }
.access-table tbody tr { transition: background-color .15s var(--ease); }
.access-table tbody tr:hover { background: var(--surface); }
.access-table td { border-bottom: 1px solid var(--border); color: var(--text); vertical-align: top; }
.access-table tbody tr:last-child td { border-bottom: none; }
.row-expired { background: color-mix(in srgb, var(--danger) 5%, transparent); }
.status-badge { display: inline-flex; align-items: center; gap: .4rem; padding: .2rem .65rem; border-radius: 9999px; font-size: .75rem; font-weight: 500; white-space: nowrap; }
.status-active { background: color-mix(in srgb, var(--ok) 14%, transparent); color: var(--ok); }
.status-expired { background: color-mix(in srgb, var(--danger) 14%, transparent); color: var(--danger); }
.status-warning { background: color-mix(in srgb, var(--warn) 14%, transparent); color: var(--warn); }
.status-lifetime { background: color-mix(in srgb, var(--primary) 14%, transparent); color: var(--primary); }
.status-gold { background: color-mix(in srgb, var(--warn) 14%, transparent); color: var(--warn); }
.action-chip { display: inline-flex; align-items: center; gap: .35rem; border-radius: 9999px; padding: .35rem .75rem; font-size: .75rem; font-weight: 500; border: 1px solid var(--border); background: transparent; color: var(--text); transition: background-color .15s var(--ease), transform .12s var(--ease); white-space: nowrap; }
.action-chip:hover { background: var(--card-high); }
.action-chip:active { transform: scale(.96); }
.action-chip.text-danger { color: var(--danger); }
.addon-box { padding: .7rem .8rem; border-radius: 12px; background: var(--bg); border: 1px solid var(--border); min-width: 0; overflow-wrap: anywhere; }
.usage-box { font-size: .75rem; line-height: 1.55; }
.mobile-token-card { padding: 1rem; border-radius: var(--radius-sm); min-width: 0; }
.mobile-token-card + .mobile-token-card { margin-top: .75rem; }
.mobile-grid { display: none; }
.pagination-shell { display: flex; align-items: center; justify-content: space-between; gap: 1rem; flex-wrap: wrap; }
.pagination-text { color: var(--text-sec); }
.pagination-shell .controls { display: flex; align-items: center; gap: .5rem; }
.pagination-btn { min-width: 88px; }
.modal-backdrop { background: var(--scrim); backdrop-filter: blur(4px); -webkit-backdrop-filter: blur(4px); }
.modal-glass { border-radius: var(--radius); padding: 1.4rem; width: min(100%, 32rem); max-height: calc(100dvh - 2rem); overflow-y: auto; box-shadow: var(--shadow-strong); }
.modal-field label { color: var(--text-sec); font-size: .78rem; font-weight: 500 !important; margin-bottom: .45rem; display: block; }
.no-scrollbar::-webkit-scrollbar { display: none; }
.no-scrollbar { -ms-overflow-style: none; scrollbar-width: none; }
@media (max-width: 1024px) { .access-table th, .access-table td { padding-left: 1rem; padding-right: 1rem; } }
@media (max-width: 767.98px) {
.desktop-table-wrap { display: none; }
.mobile-grid { display: block; }
.section-panel { padding: 1rem; }
.stats-row { padding: 1rem; gap: 1rem; }
.pagination-shell { flex-direction: column; align-items: stretch; }
.pagination-shell .controls { width: 100%; display: grid; grid-template-columns: 1fr auto 1fr; }
.pagination-btn { width: 100%; }
}
</style>
<div class="access-shell">
<header class="page-head" style="margin-bottom:0">
<div>
<h1 class="page-title">Tokens</h1>
<p class="page-sub">Addon tokens, data limits, lifetime access and linked users</p>
</div>
<div class="page-actions">
<button onclick="loadTokens()" class="glass-btn px-4 py-2 text-sm"><i class="fa-solid fa-rotate-right"></i> Refresh</button>
<button onclick="openCreateModal()" class="glass-btn glass-btn-primary px-4 py-2 text-sm"><i class="fa-solid fa-plus"></i> New token</button>
</div>
</header>
<section class="stats-row">
<div><div class="stat-value" id="stat-total">–</div><div class="stat-label">Total</div></div>
<div><div class="stat-value" style="color: var(--ok);" id="stat-active">–</div><div class="stat-label">Active</div></div>
<div><div class="stat-value" style="color: var(--danger);" id="stat-expired">–</div><div class="stat-label">Expired</div></div>
</section>
<section class="section-panel p-5">
<div class="flex flex-col lg:flex-row lg:items-end lg:justify-between gap-4 mb-5">
<div>
<h2 class="text-lg font-semibold section-title">All tokens</h2>
<p class="text-sm section-muted mt-1">Search, filter, and manage every token and its access.</p>
</div>
<div class="w-full lg:w-auto grid grid-cols-1 sm:grid-cols-3 gap-3">
<input id="search-input" type="text" data-shortcut-search placeholder="Search by name or user ID..." class="glass-input" oninput="currentPage=1; renderPage()">
<select id="filter-status" class="glass-select" onchange="currentPage=1; renderPage()">
<option value="all">All Status</option>
<option value="active">Active</option>
<option value="expired">Expired</option>
</select>
<select id="page-size" class="glass-select" onchange="currentPage=1; renderPage()">
<option value="10">10 / page</option>
<option value="25">25 / page</option>
<option value="50">50 / page</option>
</select>
</div>
</div>
<div class="desktop-table-wrap table-shell">
<div class="overflow-x-auto">
<table class="access-table min-w-[980px] text-sm">
<thead>
<tr>
<th class="px-4 py-4 text-left font-semibold">Status</th>
<th class="px-4 py-4 text-left font-semibold">User</th>
<th class="px-4 py-4 text-left font-semibold">Addon Link</th>
<th class="px-4 py-4 text-left font-semibold">Usage / Limits</th>
<th class="px-4 py-4 text-left font-semibold">Expires</th>
<th class="px-4 py-4 text-right font-semibold">Actions</th>
</tr>
</thead>
<tbody id="token-table-body">
<tr><td colspan="6" class="text-center py-10 text-soft">Loading tokens…</td></tr>
</tbody>
</table>
</div>
</div>
<div id="token-mobile-list" class="mobile-grid mt-1">
<div class="empty-state text-center px-4 py-8 text-soft">Loading tokens…</div>
</div>
<div class="pagination-shell mt-5" id="pagination-bar">
<div id="page-info" class="pagination-text text-sm"></div>
<div class="controls">
<button id="btn-prev" onclick="changePage(-1)" class="glass-btn pagination-btn px-4 py-2 text-sm font-semibold"><i class="fa-solid fa-chevron-left text-xs"></i> Prev</button>
<span id="page-num" class="text-sm font-semibold text-center section-title px-2"></span>
<button id="btn-next" onclick="changePage(1)" class="glass-btn pagination-btn px-4 py-2 text-sm font-semibold">Next <i class="fa-solid fa-chevron-right text-xs"></i></button>
</div>
</div>
</section>
</div>
<!-- Create Token Modal -->
<div id="create-modal" class="fixed inset-0 hidden z-50 modal-backdrop items-center justify-center p-4">
<div class="modal-glass">
<div class="flex items-start justify-between gap-4 mb-5">
<div>
<h3 class="text-xl font-semibold section-title">Create Token</h3>
<p class="text-sm text-soft mt-1">Generate a new Stremio addon token.</p>
</div>
<button onclick="closeModal('create-modal')" class="glass-btn rounded-full w-10 h-10 flex items-center justify-center"><i class="fas fa-xmark"></i></button>
</div>
<div class="space-y-4">
<div class="modal-field">
<label>Token Name</label>
<input type="text" id="create-name" placeholder="e.g. Living Room TV" class="glass-input">
</div>
<div class="grid grid-cols-2 gap-3">
<div class="modal-field">
<label>Daily Limit (GB)</label>
<input type="number" id="create-daily" value="0" min="0" step="0.1" class="glass-input">
</div>
<div class="modal-field">
<label>Monthly Limit (GB)</label>
<input type="number" id="create-monthly" value="0" min="0" step="0.1" class="glass-input">
</div>
</div>
<label class="flex items-center gap-3 text-sm section-title cursor-pointer">
<input type="checkbox" id="create-lifetime" class="w-4 h-4" checked>
Never expires <span class="text-soft text-xs">(no expiry date; works even when subscription mode is ON)</span>
</label>
</div>
<div class="flex flex-col-reverse sm:flex-row justify-end gap-3 pt-6">
<button onclick="closeModal('create-modal')" class="glass-btn px-4 py-2 text-sm font-semibold">Cancel</button>
<button onclick="createToken()" class="glass-btn glass-btn-primary px-4 py-2 text-sm font-semibold">Create Token</button>
</div>
</div>
</div>
<div id="cf-modal" class="fixed inset-0 hidden z-50 modal-backdrop items-center justify-center p-4">
<div class="modal-glass">
<div class="flex items-start justify-between gap-4 mb-5">
<div>
<h3 class="text-xl font-semibold section-title">Cloudflare Proxy</h3>
<p class="text-sm text-soft mt-1">Worker for this user's own bots. Leave empty to turn it off.</p>
</div>
<button onclick="closeModal('cf-modal')" class="glass-btn rounded-full w-10 h-10 flex items-center justify-center"><i class="fas fa-xmark"></i></button>
</div>
<input type="hidden" id="cf-token">
<div class="grid grid-cols-1 gap-3">
<div class="modal-field">
<label>Worker URL</label>
<input type="url" id="cf-url" placeholder="https://telestream-user.workers.dev" class="glass-input" spellcheck="false">
</div>
<div class="modal-field">
<label>Shared Secret</label>
<input type="text" id="cf-secret" class="glass-input" spellcheck="false">
</div>
</div>
<div class="flex flex-col-reverse sm:flex-row justify-end gap-3 pt-6">
<button onclick="closeModal('cf-modal')" class="glass-btn px-4 py-2 text-sm font-semibold">Cancel</button>
<button onclick="saveCf()" class="glass-btn glass-btn-primary px-4 py-2 text-sm font-semibold">Save</button>
</div>
</div>
</div>
<!-- Edit Limits Modal -->
<div id="limits-modal" class="fixed inset-0 hidden z-50 modal-backdrop items-center justify-center p-4">
<div class="modal-glass">
<div class="flex items-start justify-between gap-4 mb-5">
<div>
<h3 class="text-xl font-semibold section-title">Edit Data Limits</h3>
<p class="text-sm text-soft mt-1">Set 0 for unlimited.</p>
</div>
<button onclick="closeModal('limits-modal')" class="glass-btn rounded-full w-10 h-10 flex items-center justify-center"><i class="fas fa-xmark"></i></button>
</div>
<input type="hidden" id="limits-token">
<div class="grid grid-cols-2 gap-3">
<div class="modal-field">
<label>Daily (GB)</label>
<input type="number" id="limits-daily" min="0" step="0.1" class="glass-input">
</div>
<div class="modal-field">
<label>Monthly (GB)</label>
<input type="number" id="limits-monthly" min="0" step="0.1" class="glass-input">
</div>
</div>
<div class="flex flex-col-reverse sm:flex-row justify-end gap-3 pt-6">
<button onclick="closeModal('limits-modal')" class="glass-btn px-4 py-2 text-sm font-semibold">Cancel</button>
<button onclick="saveLimits()" class="glass-btn glass-btn-primary px-4 py-2 text-sm font-semibold">Save</button>
</div>
</div>
</div>
<!-- Assign Plan Modal -->
<div id="assign-modal" class="fixed inset-0 hidden z-50 modal-backdrop items-center justify-center p-4">
<div class="modal-glass">
<div class="flex items-start justify-between gap-4 mb-5">
<div>
<h3 class="text-xl font-semibold section-title" id="assign-modal-title">Assign Subscription Plan</h3>
<p class="text-sm text-soft mt-1" id="assign-user-label">User: –</p>
</div>
<button onclick="closeModal('assign-modal')" class="glass-btn rounded-full w-10 h-10 flex items-center justify-center"><i class="fas fa-xmark"></i></button>
</div>
<input type="hidden" id="assign-user-id">
<input type="hidden" id="assign-token">
<div class="space-y-4">
<div class="modal-field" id="assign-plan-field">
<label>Select a Plan</label>
<select id="assign-plan-select" class="glass-select"><option value="">— Select plan —</option></select>
</div>
<div class="modal-field">
<label id="assign-days-label">Or enter custom days</label>
<input type="number" id="assign-custom-days" placeholder="e.g. 30" min="1" class="glass-input">
<p class="text-xs text-soft mt-2" id="assign-days-hint">Custom days override selected plan.</p>
</div>
<div class="modal-field" id="assign-userid-field" style="display:none">
<label>Link Telegram User ID <span class="text-soft text-xs">(optional)</span></label>
<input type="number" id="assign-userid" placeholder="e.g. 123456789" class="glass-input">
<p class="text-xs text-soft mt-2">Attaches this token to a user so it's reused when they press /start.</p>
</div>
</div>
<div class="flex flex-col-reverse sm:flex-row justify-end gap-3 pt-6">
<button onclick="closeModal('assign-modal')" class="glass-btn px-4 py-2 text-sm font-semibold">Cancel</button>
<button onclick="assignPlan()" class="glass-btn glass-btn-primary px-4 py-2 text-sm font-semibold">Assign & Activate</button>
</div>
</div>
</div>
<!-- Sub Action Modal -->
<div id="sub-action-modal" class="fixed inset-0 hidden z-50 modal-backdrop items-center justify-center p-4">
<div class="modal-glass">
<div class="flex items-start justify-between gap-4 mb-5">
<div>
<h3 class="text-xl font-semibold section-title" id="sub-action-title">Manage Subscription</h3>
<p class="text-sm text-soft mt-1" id="sub-action-desc"></p>
</div>
<button onclick="closeModal('sub-action-modal')" class="glass-btn rounded-full w-10 h-10 flex items-center justify-center"><i class="fas fa-xmark"></i></button>
</div>
<input type="hidden" id="sub-action-user-id">
<input type="hidden" id="sub-action-token">
<input type="hidden" id="sub-action-action">
<div id="sub-action-days-group" class="modal-field">
<label>Number of Days</label>
<input type="number" id="sub-action-days" value="30" min="1" class="glass-input">
</div>
<div class="flex flex-col-reverse sm:flex-row justify-end gap-3 pt-6">
<button onclick="closeModal('sub-action-modal')" class="glass-btn px-4 py-2 text-sm font-semibold">Cancel</button>
<button id="sub-action-btn" onclick="submitSubAction()" class="glass-btn glass-btn-success px-4 py-2 text-sm font-semibold">Confirm</button>
</div>
</div>
</div>
<script>
let allTokens = [];
let currentPage = 1;
let subEnabled = true;
function fmtDate(iso) {
if (!iso) return '—';
const d = new Date(iso);
return d.toLocaleDateString('en-IN', { timeZone: 'Asia/Kolkata', day: '2-digit', month: 'short', year: 'numeric' }) +
' ' + d.toLocaleTimeString('en-IN', { timeZone: 'Asia/Kolkata', hour: '2-digit', minute: '2-digit' });
}
function escHtml(s) {
return String(s || '').replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, ''');
}
function fmtBytes(bytes) {
const v = Number(bytes || 0);
if (!v) return '0 B';
const u = ['B', 'KB', 'MB', 'GB', 'TB'];
const i = Math.min(Math.floor(Math.log(v) / Math.log(1024)), u.length - 1);
return (v / Math.pow(1024, i)).toFixed(i === 0 ? 0 : 2) + ' ' + u[i];
}
function getFiltered() {
const q = document.getElementById('search-input').value.toLowerCase().trim();
const status = document.getElementById('filter-status').value;
return allTokens.filter(t => {
const matchQ = !q || (t.user_name && t.user_name.toLowerCase().includes(q)) || (t.user_id && String(t.user_id).includes(q));
const matchStatus = status === 'all' || (status === 'active' && !t.is_expired) || (status === 'expired' && t.is_expired);
return matchQ && matchStatus;
});
}
function statusBadge(t) {
if (t.is_admin) return `<span class="status-badge status-gold"><i class="fas fa-crown text-[8px]"></i> Owner</span>`;
return t.is_expired
? `<span class="status-badge status-expired"><i class="fas fa-circle text-[8px]"></i> Expired</span>`
: `<span class="status-badge status-active"><i class="fas fa-circle text-[8px]"></i> Active</span>`;
}
function addonHtml(t) {
if (!t.has_token) return `<div class="addon-box"><span class="status-badge status-warning">No Token</span></div>`;
if (t.is_expired && !t.never_expires && !t.is_admin) {
return `<div class="addon-box">
<span class="status-badge status-expired">Expired</span>
${t.addon_url ? `<button onclick="copyLink('${escHtml(t.addon_url)}')" class="mt-3 text-xs font-semibold underline opacity-70 hover:opacity-100 transition">Copy URL (admin)</button>` : ''}
</div>`;
}
return t.addon_url
? `<button onclick="copyLink('${escHtml(t.addon_url)}')" class="action-chip"><i class="fa-solid fa-link"></i> Copy install link</button>`
: `<div class="addon-box text-soft text-xs">—</div>`;
}
function ownBotsHtml(t) {
if (!t.own_bots) return '';
const names = t.own_bots.bots.map(b => '@' + (b.username || b.id)).join(', ');
return `<div class="flex flex-wrap gap-1.5 mt-2">
<span class="status-badge status-active" title="Channel ${escHtml(t.own_bots.channel)}"><i class="fa-solid fa-robot text-[10px]"></i> ${t.own_bots.bots.length} own bot${t.own_bots.bots.length === 1 ? '' : 's'}</span>
${t.cf_url ? `<span class="status-badge status-gold"><i class="fa-solid fa-cloud text-[10px]"></i> Cloudflare</span>` : ''}
</div>
<div class="text-xs text-soft mt-1 break-all">${escHtml(names)}</div>`;
}
function usageHtml(t) {
const dl = t.daily_limit_gb ? t.daily_limit_gb + ' GB' : '∞';
const ml = t.monthly_limit_gb ? t.monthly_limit_gb + ' GB' : '∞';
return `<div class="usage-box text-soft">
<div><span class="section-title font-semibold">Day:</span> ${fmtBytes(t.daily_bytes)} / ${dl}</div>
<div><span class="section-title font-semibold">Mon:</span> ${fmtBytes(t.monthly_bytes)} / ${ml}</div>
</div>`;
}
function expiryHtml(t) {
if (t.never_expires) return `<span class="text-green-300 font-semibold">Never expires</span>`;
if (t.expires_at) return `<span class="${t.is_expired ? 'text-red-300 font-semibold' : 'section-title'}">${fmtDate(t.expires_at)}</span>`;
return `<span class="text-soft italic">—</span>`;
}
function buildActions(t) {
const safeName = escHtml(t.user_name || String(t.user_id || ''));
let btns = '';
const tokenArg = t.token ? escHtml(t.token) : '';
if (t.has_token) {
btns += `<button onclick="openLimitsModal('${tokenArg}', ${t.daily_limit_gb || 0}, ${t.monthly_limit_gb || 0})" class="action-chip glass-btn">Limits</button>`;
}
if (t.own_bots) btns += `<button onclick="openCfModal('${tokenArg}')" class="action-chip"><i class="fa-solid fa-cloud"></i> Cloudflare</button>`;
if (subEnabled) {
if (t.user_id) {
btns += `<button onclick="openAssignModal(${t.user_id}, '${safeName}', '')" class="action-chip">Assign</button>`;
btns += `<button onclick="openSubModal(${t.user_id}, '${safeName}', 'extend', '')" class="action-chip">Extend</button>`;
btns += `<button onclick="openSubModal(${t.user_id}, '${safeName}', 'reduce', '')" class="action-chip">Reduce</button>`;
btns += `<button onclick="openSubModal(${t.user_id}, '${safeName}', 'delete', '')" class="action-chip text-danger">Revoke</button>`;
} else if (t.token) {
btns += `<button onclick="linkUser('${tokenArg}')" class="action-chip">Link User</button>`;
}
} else if (t.has_token) {
btns += `<button onclick="openAssignModal(${t.user_id || null}, '${safeName}', '${tokenArg}')" class="action-chip">Set Expiry</button>`;
btns += `<button onclick="openSubModal(${t.user_id || null}, '${safeName}', 'extend', '${tokenArg}')" class="action-chip">Extend</button>`;
btns += `<button onclick="openSubModal(${t.user_id || null}, '${safeName}', 'reduce', '${tokenArg}')" class="action-chip">Reduce</button>`;
if (!t.user_id) btns += `<button onclick="linkUser('${tokenArg}')" class="action-chip">Link User</button>`;
}
if (t.token) btns += `<button onclick="revokeToken('${tokenArg}')" class="action-chip text-danger">Delete</button>`;
return btns;
}
function renderDesktopRows(slice) {
const tbody = document.getElementById('token-table-body');
if (!slice.length) { tbody.innerHTML = `<tr><td colspan="6" class="text-center py-10 text-soft">No tokens match your search.</td></tr>`; return; }
tbody.innerHTML = slice.map(t => {
const displayName = t.user_name || (t.user_id ? 'Telegram User' : 'Web Token');
const idHtml = t.user_id ? `<div class="text-xs text-soft mt-1">ID: ${t.user_id}</div>` : `<div class="text-xs text-soft mt-1">No linked user</div>`;
return `
<tr class="${t.is_expired ? 'row-expired' : ''}">
<td class="px-4 py-4">${statusBadge(t)}</td>
<td class="px-4 py-4"><div class="font-semibold section-title">${escHtml(displayName)}</div>${idHtml}${ownBotsHtml(t)}</td>
<td class="px-4 py-4">${addonHtml(t)}</td>
<td class="px-4 py-4">${usageHtml(t)}</td>
<td class="px-4 py-4 text-xs">${expiryHtml(t)}</td>
<td class="px-4 py-4" style="width:300px"><div class="flex flex-wrap gap-1.5 justify-end">${buildActions(t)}</div></td>
</tr>`;
}).join('');
}
function renderMobileCards(slice) {
const wrap = document.getElementById('token-mobile-list');
if (!slice.length) { wrap.innerHTML = `<div class="empty-state text-center px-4 py-8 text-soft">No tokens match your search.</div>`; return; }
wrap.innerHTML = slice.map(t => {
const displayName = t.user_name || (t.user_id ? 'Telegram User' : 'Web Token');
return `
<div class="mobile-token-card ${t.is_expired ? 'row-expired' : ''}">
<div class="flex items-start justify-between gap-3 mb-3">
<div class="min-w-0">
<div class="font-semibold section-title break-words">${escHtml(displayName)}</div>
<div class="text-xs text-soft mt-1 break-all">${t.user_id ? 'ID: ' + t.user_id : 'No linked user'}</div>${ownBotsHtml(t)}
</div>
<div class="shrink-0">${statusBadge(t)}</div>
</div>
<div class="grid grid-cols-1 gap-3 mb-3">
<div class="rounded-2xl px-4 py-3" style="background: color-mix(in srgb, var(--bg) 55%, transparent); border: 1px solid color-mix(in srgb, var(--border) 70%, transparent);">
<div class="text-[11px] uppercase tracking-[0.14em] text-soft font-semibold mb-1">Addon Access</div>${addonHtml(t)}
</div>
<div class="grid grid-cols-2 gap-3">
<div class="rounded-2xl px-4 py-3" style="background: color-mix(in srgb, var(--bg) 55%, transparent); border: 1px solid color-mix(in srgb, var(--border) 70%, transparent);">
<div class="text-[11px] uppercase tracking-[0.14em] text-soft font-semibold mb-1">Usage / Limits</div>${usageHtml(t)}
</div>
<div class="rounded-2xl px-4 py-3" style="background: color-mix(in srgb, var(--bg) 55%, transparent); border: 1px solid color-mix(in srgb, var(--border) 70%, transparent);">
<div class="text-[11px] uppercase tracking-[0.14em] text-soft font-semibold mb-1">Expires</div>
<div class="text-sm font-semibold ${t.is_expired ? 'text-red-300' : 'section-title'} break-words">
${t.never_expires ? 'Never expires' : (t.expires_at ? fmtDate(t.expires_at) : '—')}
</div>
</div>
</div>
</div>
<div class="flex flex-wrap gap-2">${buildActions(t)}</div>
</div>`;
}).join('');
}
function renderPage() {
const filtered = getFiltered();
const pageSize = parseInt(document.getElementById('page-size').value);
const totalPages = Math.max(1, Math.ceil(filtered.length / pageSize));
if (currentPage > totalPages) currentPage = totalPages;
const start = filtered.length ? (currentPage - 1) * pageSize : 0;
const slice = filtered.slice(start, start + pageSize);
document.getElementById('page-info').textContent = filtered.length
? `Showing ${start + 1}–${Math.min(start + pageSize, filtered.length)} of ${filtered.length}` : 'Showing 0 of 0';
document.getElementById('page-num').textContent = `Page ${currentPage} / ${totalPages}`;
const prevBtn = document.getElementById('btn-prev'), nextBtn = document.getElementById('btn-next');
prevBtn.disabled = currentPage <= 1; nextBtn.disabled = currentPage >= totalPages;
prevBtn.style.opacity = currentPage <= 1 ? '0.45' : '1'; nextBtn.style.opacity = currentPage >= totalPages ? '0.45' : '1';
renderDesktopRows(slice);
renderMobileCards(slice);
}
function changePage(dir) {
const filtered = getFiltered();
const pageSize = parseInt(document.getElementById('page-size').value);
const totalPages = Math.max(1, Math.ceil(filtered.length / pageSize));
currentPage = Math.min(Math.max(1, currentPage + dir), totalPages);
renderPage();
}
async function loadTokens() {
document.getElementById('token-table-body').innerHTML = `<tr><td colspan="6" class="text-center py-10 text-soft">Loading…</td></tr>`;
try {
const resp = await fetch('/api/admin/access/tokens');
const data = await resp.json();
allTokens = data.tokens || [];
subEnabled = !!data.subscription;
document.getElementById('stat-total').textContent = allTokens.length;
document.getElementById('stat-active').textContent = allTokens.filter(t => !t.is_expired).length;
document.getElementById('stat-expired').textContent = allTokens.filter(t => t.is_expired).length;
currentPage = 1;
renderPage();
} catch (err) {
document.getElementById('token-table-body').innerHTML = `<tr><td colspan="6" class="text-center py-10 text-red-300">Error: ${err.message}</td></tr>`;
showToast('Failed to load access tokens.', 'error', 'Load Error');
}
}
async function loadPlans() {
try {
const resp = await fetch('/api/admin/subscriptions/plans');
if (!resp.ok) return;
const result = await resp.json();
const plans = result.data || [];
const sel = document.getElementById('assign-plan-select');
if (!sel) return;
sel.innerHTML = '<option value="">— Select a plan —</option>' +
plans.map(p => { const sym = ({INR:'₹',USD:'$',EUR:'€',GBP:'£',JPY:'¥',AUD:'A$',CAD:'C$',SGD:'S$',AED:'د.إ',BRL:'R$'}[(p.currency||'INR').toUpperCase()]||((p.currency||'INR')+' ')); return `<option value="${p.days}">${p.days} days${p.price != null ? ' — ' + sym + p.price : ''}</option>`; }).join('');
} catch (e) { /* ignore */ }
}
function openModal(id) {
const m = document.getElementById(id);
m.classList.remove('hidden'); m.classList.add('flex');
document.body.classList.add('overflow-hidden');
}
function closeModal(id) {
const m = document.getElementById(id);
m.classList.add('hidden'); m.classList.remove('flex');
document.body.classList.remove('overflow-hidden');
}
function openCreateModal() {
document.getElementById('create-name').value = '';
document.getElementById('create-daily').value = 0;
document.getElementById('create-monthly').value = 0;
document.getElementById('create-lifetime').checked = true;
openModal('create-modal');
}
async function createToken() {
const name = document.getElementById('create-name').value.trim();
if (!name) { showToast('Token name is required.', 'error', 'Validation'); return; }
const payload = {
name,
daily_limit_gb: Number(document.getElementById('create-daily').value || 0),
monthly_limit_gb: Number(document.getElementById('create-monthly').value || 0),
subscription_exempt: document.getElementById('create-lifetime').checked,
};
try {
const resp = await fetch('/api/tokens', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) });
if (resp.ok) { showToast('Token created.', 'success', 'Created'); closeModal('create-modal'); loadTokens(); }
else { const d = await resp.json(); showToast(d.detail || 'Failed to create token.', 'error', 'Failed'); }
} catch (err) { showToast('Error: ' + err.message, 'error', 'Network Error'); }
}
function openLimitsModal(token, daily, monthly) {
document.getElementById('limits-token').value = token;
document.getElementById('limits-daily').value = daily || 0;
document.getElementById('limits-monthly').value = monthly || 0;
openModal('limits-modal');
}
async function saveLimits() {
const token = document.getElementById('limits-token').value;
const payload = {
daily_limit_gb: Number(document.getElementById('limits-daily').value || 0),
monthly_limit_gb: Number(document.getElementById('limits-monthly').value || 0),
};
try {
const resp = await fetch('/api/tokens/' + encodeURIComponent(token), { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) });
if (resp.ok) { showToast('Limits updated.', 'success', 'Updated'); closeModal('limits-modal'); loadTokens(); }
else { showToast('Failed to update limits.', 'error', 'Failed'); }
} catch (err) { showToast('Error: ' + err.message, 'error', 'Network Error'); }
}
function openCfModal(token) {
const t = allTokens.find(x => x.token === token) || {};
document.getElementById('cf-token').value = token;
document.getElementById('cf-url').value = t.cf_url || '';
document.getElementById('cf-secret').value = t.cf_secret || '';
openModal('cf-modal');
}
async function saveCf() {
const token = document.getElementById('cf-token').value;
const payload = { cf_url: document.getElementById('cf-url').value.trim(), cf_secret: document.getElementById('cf-secret').value.trim() };
try {
const resp = await fetch('/api/tokens/' + encodeURIComponent(token) + '/cf', { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) });
if (resp.ok) { showToast('Cloudflare proxy saved.', 'success', 'Updated'); closeModal('cf-modal'); loadTokens(); }
else { showToast((await resp.json().catch(() => ({}))).detail || 'Failed to save.', 'error', 'Failed'); }
} catch (err) { showToast('Error: ' + err.message, 'error', 'Network Error'); }
}
async function revokeToken(token) {
if (!confirm('Delete this token? The user will lose addon access immediately.')) return;
try {
const resp = await fetch('/api/admin/access/tokens/' + encodeURIComponent(token), { method: 'DELETE' });
if (resp.ok) { showToast('Token deleted.', 'success', 'Access Updated'); loadTokens(); }
else { const d = await resp.json(); showToast(d.detail || 'Failed.', 'error', 'Delete Failed'); }
} catch (err) { showToast('Error: ' + err.message, 'error', 'Network Error'); }
}
async function linkUser(token) {
const userId = prompt('Enter the Telegram User ID to link this token to:');
if (!userId || isNaN(parseInt(userId))) { showToast('Invalid user ID.', 'error', 'Invalid Input'); return; }
try {
const resp = await fetch('/api/admin/access/tokens/' + encodeURIComponent(token) + '/link-user', {
method: 'PATCH', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ user_id: parseInt(userId) }),
});
if (resp.ok) { showToast(`Token linked to user ${userId}.`, 'success', 'User Linked'); loadTokens(); }
else { const d = await resp.json(); showToast(d.detail || 'Failed to link.', 'error', 'Link Failed'); }
} catch (err) { showToast('Error: ' + err.message, 'error', 'Network Error'); }
}
function openAssignModal(userId, userName, token) {
document.getElementById('assign-user-id').value = userId || '';
document.getElementById('assign-token').value = token || '';
document.getElementById('assign-user-label').textContent = userId ? `User: ${userName} (ID: ${userId})` : `Token: ${userName}`;
document.getElementById('assign-custom-days').value = '';
document.getElementById('assign-plan-select').value = '';
//----- With subscription off there are no plans — just set an expiry
document.getElementById('assign-plan-field').style.display = subEnabled ? '' : 'none';
document.getElementById('assign-modal-title').textContent = subEnabled ? 'Assign Subscription Plan' : 'Set Expiry';
document.getElementById('assign-days-label').textContent = subEnabled ? 'Or enter custom days' : 'Expires in (days)';
document.getElementById('assign-days-hint').textContent = subEnabled
? 'Custom days override the selected plan. Leave empty or 0 for never expires.'
: 'Leave empty or 0 for never expires.';
const uidField = document.getElementById('assign-userid-field');
uidField.style.display = subEnabled ? 'none' : '';
document.getElementById('assign-userid').value = (!subEnabled && userId) ? userId : '';
openModal('assign-modal');
}
async function assignPlan() {
const customDays = parseInt(document.getElementById('assign-custom-days').value) || 0;
const planDays = parseInt(document.getElementById('assign-plan-select').value) || 0;
const days = customDays || planDays; // 0 = never expires
try {
let resp;
if (subEnabled) {
const userId = parseInt(document.getElementById('assign-user-id').value);
resp = await fetch(`/api/admin/access/users/${userId}/assign-plan`, {
method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ days }),
});
} else {
const token = document.getElementById('assign-token').value;
const uid = parseInt(document.getElementById('assign-userid').value) || 0;
const body = { action: 'set', days };
if (uid) body.user_id = uid;
resp = await fetch(`/api/admin/access/tokens/${encodeURIComponent(token)}/expiry`, {
method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body),
});
}
const data = await resp.json();
if (resp.ok) { showToast(days > 0 ? `Expiry set: ${days} days.` : 'Set to never expire.', 'success', 'Updated'); closeModal('assign-modal'); loadTokens(); }
else { showToast(data.detail || 'Failed to update.', 'error', 'Request Failed'); }
} catch (err) { showToast('Error: ' + err.message, 'error', 'Network Error'); }
}
function openSubModal(userId, userName, action, token) {
document.getElementById('sub-action-user-id').value = userId || '';
document.getElementById('sub-action-token').value = token || '';
document.getElementById('sub-action-action').value = action;
const noun = subEnabled ? 'Subscription' : 'Expiry';
const thing = subEnabled ? 'subscription' : 'access';
const titles = { extend: `Extend ${noun}`, reduce: `Reduce ${noun}`, delete: 'Revoke Subscription' };
const descs = {
extend: `Add days to <b>${userName}</b>'s ${thing}.`,
reduce: `Remove days from <b>${userName}</b>'s ${thing}.`,
delete: `<b>Warning:</b> Revoke <b>${userName}</b>'s subscription entirely.`,
};
document.getElementById('sub-action-title').textContent = titles[action];
document.getElementById('sub-action-desc').innerHTML = descs[action];
const daysGroup = document.getElementById('sub-action-days-group');
const btn = document.getElementById('sub-action-btn');
if (action === 'delete') { daysGroup.style.display = 'none'; btn.className = 'glass-btn glass-btn-danger px-4 py-2 text-sm font-semibold'; }
else if (action === 'reduce') { daysGroup.style.display = 'block'; btn.className = 'glass-btn glass-btn-warning px-4 py-2 text-sm font-semibold'; }
else { daysGroup.style.display = 'block'; btn.className = 'glass-btn glass-btn-success px-4 py-2 text-sm font-semibold'; }
document.getElementById('sub-action-days').value = 30;
openModal('sub-action-modal');
}
async function submitSubAction() {
const action = document.getElementById('sub-action-action').value;
const days = parseInt(document.getElementById('sub-action-days').value) || 0;
try {
let resp;
if (subEnabled) {
const userId = parseInt(document.getElementById('sub-action-user-id').value);
resp = await fetch(`/api/admin/subscriptions/users/${userId}/manage`, {
method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action, days }),
});
} else {
const token = document.getElementById('sub-action-token').value;
resp = await fetch(`/api/admin/access/tokens/${encodeURIComponent(token)}/expiry`, {
method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action, days }),
});
}
const data = await resp.json();
if (resp.ok) { showToast('Updated.', 'success', 'Updated'); closeModal('sub-action-modal'); loadTokens(); }
else { showToast(data.detail || 'Failed.', 'error', 'Update Failed'); }
} catch (err) { showToast('Error: ' + err.message, 'error', 'Network Error'); }
}
async function copyLink(url) {
try { await navigator.clipboard.writeText(url); showToast('Link copied!', 'success', 'Copied'); }
catch { prompt('Copy this link:', url); }
}
['create-modal', 'limits-modal', 'cf-modal', 'assign-modal', 'sub-action-modal'].forEach(id => {
document.getElementById(id).addEventListener('click', function (e) { if (e.target === this) closeModal(id); });
});
document.addEventListener('keydown', e => {
if (e.key === 'Escape') ['create-modal', 'limits-modal', 'cf-modal', 'assign-modal', 'sub-action-modal'].forEach(closeModal);
});
loadPlans();
loadTokens();
</script>
{% endblock %}
|