File size: 47,553 Bytes
22a3c56 e42cbba 22a3c56 e42cbba 22a3c56 e42cbba 22a3c56 e42cbba 22a3c56 e42cbba 22a3c56 e42cbba 22a3c56 e42cbba 22a3c56 e42cbba 22a3c56 e42cbba 22a3c56 e42cbba 22a3c56 e42cbba 22a3c56 e42cbba 22a3c56 e42cbba 22a3c56 e42cbba 22a3c56 e42cbba 22a3c56 e42cbba 22a3c56 e42cbba 22a3c56 e42cbba 22a3c56 e42cbba 22a3c56 e42cbba 22a3c56 e42cbba 22a3c56 e42cbba 22a3c56 e42cbba 22a3c56 e42cbba 22a3c56 e42cbba 22a3c56 e42cbba 22a3c56 e42cbba 22a3c56 e42cbba 7f0f0c8 e42cbba 22a3c56 e42cbba 22a3c56 e42cbba 22a3c56 e42cbba 22a3c56 e42cbba 22a3c56 e42cbba 22a3c56 e42cbba 22a3c56 e42cbba 22a3c56 e42cbba 22a3c56 e42cbba 22a3c56 e42cbba 22a3c56 e42cbba 22a3c56 e42cbba 22a3c56 e42cbba 22a3c56 e42cbba 22a3c56 e42cbba 22a3c56 e42cbba 22a3c56 e42cbba 22a3c56 e42cbba 22a3c56 e42cbba 22a3c56 e42cbba 22a3c56 e42cbba 22a3c56 e42cbba 22a3c56 e42cbba 22a3c56 e42cbba 22a3c56 e42cbba 22a3c56 e42cbba 22a3c56 e42cbba 22a3c56 e42cbba 22a3c56 e42cbba 22a3c56 e42cbba 22a3c56 e42cbba 22a3c56 e42cbba 22a3c56 e42cbba 22a3c56 e42cbba 22a3c56 e42cbba 22a3c56 e42cbba 22a3c56 e42cbba 22a3c56 e42cbba 22a3c56 e42cbba 22a3c56 e42cbba 22a3c56 e42cbba 22a3c56 e42cbba 22a3c56 e42cbba 22a3c56 e42cbba 22a3c56 e42cbba 22a3c56 e42cbba 22a3c56 e42cbba 22a3c56 e42cbba 22a3c56 e42cbba 22a3c56 e42cbba 22a3c56 e42cbba 22a3c56 e42cbba 22a3c56 e42cbba 22a3c56 e42cbba 22a3c56 e42cbba 22a3c56 e42cbba 22a3c56 e42cbba 22a3c56 e42cbba 22a3c56 e42cbba 22a3c56 e42cbba 22a3c56 e42cbba 22a3c56 e42cbba 22a3c56 e42cbba 22a3c56 e42cbba 22a3c56 e42cbba 22a3c56 e42cbba 22a3c56 e42cbba 22a3c56 |
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 |
"""Database storage layer"""
import aiomysql
import json
from datetime import datetime
from typing import Optional, List, Any
from pathlib import Path
from .models import Token, TokenStats, Task, RequestLog, AdminConfig, ProxyConfig, WatermarkFreeConfig, CacheConfig, GenerationConfig, TokenRefreshConfig
from .config import config
class MySQLCursorWrapper:
def __init__(self, cursor):
self.cursor = cursor
def __getattr__(self, name):
return getattr(self.cursor, name)
async def fetchone(self):
return await self.cursor.fetchone()
async def fetchall(self):
return await self.cursor.fetchall()
@property
def lastrowid(self):
return self.cursor.lastrowid
class MySQLConnectionWrapper:
def __init__(self, pool):
self.pool = pool
self.conn = None
self.cursor = None
async def __aenter__(self):
self.conn = await self.pool.acquire()
return self
async def __aexit__(self, exc_type, exc_val, exc_tb):
if self.conn:
self.pool.release(self.conn)
async def execute(self, query: str, args: tuple = None) -> MySQLCursorWrapper:
# Convert sqlite '?' placeholder to mysql '%s'
query = query.replace('?', '%s')
# Create cursor (default to DictCursor for compatibility with explicit dict access,
# but for row_factory we might need to handle it differently.
# Existing code uses DictCursor logic mostly via dict(row))
self.cursor = await self.conn.cursor(aiomysql.DictCursor)
try:
await self.cursor.execute(query, args)
except Exception as e:
# Add context to error
print(f"SQL Error: {e}\nQuery: {query}\nArgs: {args}")
raise e
return MySQLCursorWrapper(self.cursor)
async def commit(self):
await self.conn.commit()
@property
def row_factory(self):
return None
@row_factory.setter
def row_factory(self, value):
# aiomysql DictCursor yields dict-like objects already, close enough to aiosqlite.Row for most uses
pass
class Database:
"""MySQL database manager (compatible interface with previous SQLite implementation)"""
def __init__(self, db_path: str = None):
self._pool = None
# db_path is ignored for MySQL, we use config
async def get_pool(self):
if self._pool is None:
self._pool = await aiomysql.create_pool(
host=config.db_host,
port=config.db_port,
user=config.db_user,
password=config.db_password,
db=config.db_name,
autocommit=False, # We manually commit
cursorclass=aiomysql.DictCursor
)
return self._pool
def connect(self):
"""Return a context manager that mimics aiosqlite.connect"""
# We can't await in __init__ or synchronous property, so we return an async context manager helper
class ConnectContext:
def __init__(self, db_instance):
self.db = db_instance
async def __aenter__(self):
pool = await self.db.get_pool()
self.wrapper = MySQLConnectionWrapper(pool)
return await self.wrapper.__aenter__()
async def __aexit__(self, exc_type, exc_val, exc_tb):
await self.wrapper.__aexit__(exc_type, exc_val, exc_tb)
return ConnectContext(self)
async def db_exists(self) -> bool:
"""Check if database exists (always true for MySQL if we can connect)"""
try:
pool = await self.get_pool()
async with pool.acquire() as conn:
async with conn.cursor() as cur:
await cur.execute("SELECT 1")
return True
except Exception as e:
print(f"Database connection failed: {e}")
return False
async def _table_exists(self, db, table_name: str) -> bool:
"""Check if a table exists in the database"""
# Note: db here is our MySQLConnectionWrapper
cursor = await db.execute(
"SELECT count(*) as count FROM information_schema.tables WHERE table_schema = %s AND table_name = %s",
(config.db_name, table_name)
)
result = await cursor.fetchone()
return result['count'] > 0
async def _column_exists(self, db, table_name: str, column_name: str) -> bool:
"""Check if a column exists in a table"""
try:
cursor = await db.execute(
"SELECT count(*) as count FROM information_schema.columns WHERE table_schema = %s AND table_name = %s AND column_name = %s",
(config.db_name, table_name, column_name)
)
result = await cursor.fetchone()
return result['count'] > 0
except:
return False
async def _ensure_config_rows(self, db, config_dict: dict = None):
"""Ensure all config tables have their default rows"""
# Ensure admin_config has a row
cursor = await db.execute("SELECT COUNT(*) as count FROM admin_config")
count = await cursor.fetchone()
if count['count'] == 0:
# Get admin credentials from config_dict if provided, otherwise use defaults
admin_username = "admin"
admin_password = "admin"
error_ban_threshold = 3
if config_dict:
global_config = config_dict.get("global", {})
admin_username = global_config.get("admin_username", "admin")
admin_password = global_config.get("admin_password", "admin")
admin_config = config_dict.get("admin", {})
error_ban_threshold = admin_config.get("error_ban_threshold", 3)
await db.execute("""
INSERT INTO admin_config (id, admin_username, admin_password, error_ban_threshold)
VALUES (1, ?, ?, ?)
""", (admin_username, admin_password, error_ban_threshold))
# Ensure proxy_config has a row
cursor = await db.execute("SELECT COUNT(*) as count FROM proxy_config")
count = await cursor.fetchone()
if count['count'] == 0:
# Get proxy config from config_dict if provided, otherwise use defaults
proxy_enabled = False
proxy_url = None
if config_dict:
proxy_config = config_dict.get("proxy", {})
proxy_enabled = proxy_config.get("proxy_enabled", False)
proxy_url = proxy_config.get("proxy_url", "")
# Convert empty string to None
proxy_url = proxy_url if proxy_url else None
await db.execute("""
INSERT INTO proxy_config (id, proxy_enabled, proxy_url)
VALUES (1, ?, ?)
""", (proxy_enabled, proxy_url))
# Ensure watermark_free_config has a row
cursor = await db.execute("SELECT COUNT(*) as count FROM watermark_free_config")
count = await cursor.fetchone()
if count['count'] == 0:
# Get watermark-free config from config_dict if provided, otherwise use defaults
watermark_free_enabled = False
parse_method = "third_party"
custom_parse_url = None
custom_parse_token = None
if config_dict:
watermark_config = config_dict.get("watermark_free", {})
watermark_free_enabled = watermark_config.get("watermark_free_enabled", False)
parse_method = watermark_config.get("parse_method", "third_party")
custom_parse_url = watermark_config.get("custom_parse_url", "")
custom_parse_token = watermark_config.get("custom_parse_token", "")
# Convert empty strings to None
custom_parse_url = custom_parse_url if custom_parse_url else None
custom_parse_token = custom_parse_token if custom_parse_token else None
await db.execute("""
INSERT INTO watermark_free_config (id, watermark_free_enabled, parse_method, custom_parse_url, custom_parse_token)
VALUES (1, ?, ?, ?, ?)
""", (watermark_free_enabled, parse_method, custom_parse_url, custom_parse_token))
# Ensure cache_config has a row
cursor = await db.execute("SELECT COUNT(*) as count FROM cache_config")
count = await cursor.fetchone()
if count['count'] == 0:
# Get cache config from config_dict if provided, otherwise use defaults
cache_enabled = False
cache_timeout = 600
cache_base_url = None
if config_dict:
cache_config = config_dict.get("cache", {})
cache_enabled = cache_config.get("enabled", False)
cache_timeout = cache_config.get("timeout", 600)
cache_base_url = cache_config.get("base_url", "")
# Convert empty string to None
cache_base_url = cache_base_url if cache_base_url else None
await db.execute("""
INSERT INTO cache_config (id, cache_enabled, cache_timeout, cache_base_url)
VALUES (1, ?, ?, ?)
""", (cache_enabled, cache_timeout, cache_base_url))
# Ensure generation_config has a row
cursor = await db.execute("SELECT COUNT(*) as count FROM generation_config")
count = await cursor.fetchone()
if count['count'] == 0:
# Get generation config from config_dict if provided, otherwise use defaults
image_timeout = 300
video_timeout = 1500
if config_dict:
generation_config = config_dict.get("generation", {})
image_timeout = generation_config.get("image_timeout", 300)
video_timeout = generation_config.get("video_timeout", 1500)
await db.execute("""
INSERT INTO generation_config (id, image_timeout, video_timeout)
VALUES (1, ?, ?)
""", (image_timeout, video_timeout))
# Ensure token_refresh_config has a row
cursor = await db.execute("SELECT COUNT(*) as count FROM token_refresh_config")
count = await cursor.fetchone()
if count['count'] == 0:
# Get token refresh config from config_dict if provided, otherwise use defaults
at_auto_refresh_enabled = False
if config_dict:
token_refresh_config = config_dict.get("token_refresh", {})
at_auto_refresh_enabled = token_refresh_config.get("at_auto_refresh_enabled", False)
await db.execute("""
INSERT INTO token_refresh_config (id, at_auto_refresh_enabled)
VALUES (1, ?)
""", (at_auto_refresh_enabled,))
async def check_and_migrate_db(self, config_dict: dict = None):
"""Check database integrity and perform migrations if needed"""
async with self.connect() as db:
print("Checking database integrity and performing migrations...")
# Check and add missing columns to tokens table
if await self._table_exists(db, "tokens"):
columns_to_add = [
("sora2_supported", "BOOLEAN"),
("sora2_invite_code", "TEXT"),
("sora2_redeemed_count", "INT DEFAULT 0"),
("sora2_total_count", "INT DEFAULT 0"),
("sora2_remaining_count", "INT DEFAULT 0"),
("sora2_cooldown_until", "DATETIME"),
("image_enabled", "BOOLEAN DEFAULT 1"),
("video_enabled", "BOOLEAN DEFAULT 1"),
]
for col_name, col_type in columns_to_add:
if not await self._column_exists(db, "tokens", col_name):
try:
await db.execute(f"ALTER TABLE tokens ADD COLUMN {col_name} {col_type}")
print(f" ✓ Added column '{col_name}' to tokens table")
except Exception as e:
print(f" ✗ Failed to add column '{col_name}': {e}")
# Check and add missing columns to admin_config table
if await self._table_exists(db, "admin_config"):
columns_to_add = [
("admin_username", "TEXT"),
("admin_password", "TEXT"),
]
for col_name, col_type in columns_to_add:
if not await self._column_exists(db, "admin_config", col_name):
try:
await db.execute(f"ALTER TABLE admin_config ADD COLUMN {col_name} {col_type}")
print(f" ✓ Added column '{col_name}' to admin_config table")
except Exception as e:
print(f" ✗ Failed to add column '{col_name}': {e}")
# Check and add missing columns to watermark_free_config table
if await self._table_exists(db, "watermark_free_config"):
columns_to_add = [
("parse_method", "TEXT"),
("custom_parse_url", "TEXT"),
("custom_parse_token", "TEXT"),
]
for col_name, col_type in columns_to_add:
if not await self._column_exists(db, "watermark_free_config", col_name):
try:
await db.execute(f"ALTER TABLE watermark_free_config ADD COLUMN {col_name} {col_type}")
print(f" ✓ Added column '{col_name}' to watermark_free_config table")
except Exception as e:
print(f" ✗ Failed to add column '{col_name}': {e}")
# Ensure all config tables have their default rows
await self._ensure_config_rows(db, config_dict)
await db.commit()
print("Database migration check completed.")
async def init_db(self):
"""Initialize database tables - creates all tables and ensures data integrity"""
async with self.connect() as db:
# Tokens table
await db.execute("""
CREATE TABLE IF NOT EXISTS tokens (
id INT PRIMARY KEY AUTO_INCREMENT,
token VARCHAR(2000) NOT NULL,
email VARCHAR(255) NOT NULL,
username VARCHAR(255) NOT NULL,
name VARCHAR(255) NOT NULL,
st TEXT,
rt TEXT,
remark TEXT,
expiry_time DATETIME,
is_active BOOLEAN DEFAULT 1,
cooled_until DATETIME,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
last_used_at DATETIME,
use_count INT DEFAULT 0,
plan_type VARCHAR(50),
plan_title VARCHAR(100),
subscription_end DATETIME,
sora2_supported BOOLEAN,
sora2_invite_code VARCHAR(255),
sora2_redeemed_count INT DEFAULT 0,
sora2_total_count INT DEFAULT 0,
sora2_remaining_count INT DEFAULT 0,
sora2_cooldown_until DATETIME,
image_enabled BOOLEAN DEFAULT 1,
video_enabled BOOLEAN DEFAULT 1
)
""")
# Token stats table
await db.execute("""
CREATE TABLE IF NOT EXISTS token_stats (
id INT PRIMARY KEY AUTO_INCREMENT,
token_id INT NOT NULL,
image_count INT DEFAULT 0,
video_count INT DEFAULT 0,
error_count INT DEFAULT 0,
last_error_at DATETIME,
FOREIGN KEY (token_id) REFERENCES tokens(id)
)
""")
# Tasks table
await db.execute("""
CREATE TABLE IF NOT EXISTS tasks (
id INT PRIMARY KEY AUTO_INCREMENT,
task_id VARCHAR(255) UNIQUE NOT NULL,
token_id INT NOT NULL,
model VARCHAR(255) NOT NULL,
prompt TEXT NOT NULL,
status VARCHAR(50) NOT NULL DEFAULT 'processing',
progress FLOAT DEFAULT 0,
result_urls TEXT,
error_message TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
completed_at DATETIME,
FOREIGN KEY (token_id) REFERENCES tokens(id)
)
""")
# Request logs table
await db.execute("""
CREATE TABLE IF NOT EXISTS request_logs (
id INT PRIMARY KEY AUTO_INCREMENT,
token_id INT,
operation VARCHAR(255) NOT NULL,
request_body TEXT,
response_body TEXT,
status_code INT NOT NULL,
duration FLOAT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (token_id) REFERENCES tokens(id)
)
""")
# Admin config table
await db.execute("""
CREATE TABLE IF NOT EXISTS admin_config (
id INT PRIMARY KEY DEFAULT 1,
admin_username VARCHAR(255) DEFAULT 'admin',
admin_password VARCHAR(255) DEFAULT 'admin',
error_ban_threshold INT DEFAULT 3,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)
""")
# Proxy config table
await db.execute("""
CREATE TABLE IF NOT EXISTS proxy_config (
id INT PRIMARY KEY DEFAULT 1,
proxy_enabled BOOLEAN DEFAULT 0,
proxy_url TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)
""")
# Watermark-free config table
await db.execute("""
CREATE TABLE IF NOT EXISTS watermark_free_config (
id INT PRIMARY KEY DEFAULT 1,
watermark_free_enabled BOOLEAN DEFAULT 0,
parse_method VARCHAR(50) DEFAULT 'third_party',
custom_parse_url TEXT,
custom_parse_token TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)
""")
# Cache config table
await db.execute("""
CREATE TABLE IF NOT EXISTS cache_config (
id INT PRIMARY KEY DEFAULT 1,
cache_enabled BOOLEAN DEFAULT 0,
cache_timeout INT DEFAULT 600,
cache_base_url TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)
""")
# Generation config table
await db.execute("""
CREATE TABLE IF NOT EXISTS generation_config (
id INT PRIMARY KEY DEFAULT 1,
image_timeout INT DEFAULT 300,
video_timeout INT DEFAULT 1500,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)
""")
# Token refresh config table
await db.execute("""
CREATE TABLE IF NOT EXISTS token_refresh_config (
id INT PRIMARY KEY DEFAULT 1,
at_auto_refresh_enabled BOOLEAN DEFAULT 0,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)
""")
# Create indexes
# MySQL handles index creation slightly differently/implicitly but this is standard enough
# Use separate calls and catch error if index exists (or use CREATE INDEX IF NOT EXISTS which MySQL supports in 8.0+, assuming 5.7+ check needed?)
# MySQL 8.0+ supports IF NOT EXISTS.
try:
await db.execute("CREATE INDEX idx_task_id ON tasks(task_id)")
except: pass
try:
await db.execute("CREATE INDEX idx_task_status ON tasks(status)")
except: pass
try:
await db.execute("CREATE INDEX idx_token_active ON tokens(is_active)")
except: pass
await db.commit()
async def init_config_from_toml(self, config_dict: dict, is_first_startup: bool = True):
"""Initialize database configuration from setting.toml"""
async with self.connect() as db:
if is_first_startup:
await self._ensure_config_rows(db, config_dict)
# Initialize admin config
admin_config = config_dict.get("admin", {})
error_ban_threshold = admin_config.get("error_ban_threshold", 3)
global_config = config_dict.get("global", {})
admin_username = global_config.get("admin_username", "admin")
admin_password = global_config.get("admin_password", "admin")
if not is_first_startup:
await db.execute("""
UPDATE admin_config
SET admin_username = ?, admin_password = ?, error_ban_threshold = ?, updated_at = CURRENT_TIMESTAMP
WHERE id = 1
""", (admin_username, admin_password, error_ban_threshold))
# Initialize proxy config
proxy_config = config_dict.get("proxy", {})
proxy_enabled = proxy_config.get("proxy_enabled", False)
proxy_url = proxy_config.get("proxy_url", "")
proxy_url = proxy_url if proxy_url else None
if is_first_startup:
await db.execute("""
INSERT IGNORE INTO proxy_config (id, proxy_enabled, proxy_url)
VALUES (1, ?, ?)
""", (proxy_enabled, proxy_url))
else:
await db.execute("""
UPDATE proxy_config
SET proxy_enabled = ?, proxy_url = ?, updated_at = CURRENT_TIMESTAMP
WHERE id = 1
""", (proxy_enabled, proxy_url))
# Initialize watermark-free config
watermark_config = config_dict.get("watermark_free", {})
watermark_free_enabled = watermark_config.get("watermark_free_enabled", False)
parse_method = watermark_config.get("parse_method", "third_party")
custom_parse_url = watermark_config.get("custom_parse_url", "")
custom_parse_token = watermark_config.get("custom_parse_token", "")
custom_parse_url = custom_parse_url if custom_parse_url else None
custom_parse_token = custom_parse_token if custom_parse_token else None
if is_first_startup:
await db.execute("""
INSERT IGNORE INTO watermark_free_config (id, watermark_free_enabled, parse_method, custom_parse_url, custom_parse_token)
VALUES (1, ?, ?, ?, ?)
""", (watermark_free_enabled, parse_method, custom_parse_url, custom_parse_token))
else:
await db.execute("""
UPDATE watermark_free_config
SET watermark_free_enabled = ?, parse_method = ?, custom_parse_url = ?,
custom_parse_token = ?, updated_at = CURRENT_TIMESTAMP
WHERE id = 1
""", (watermark_free_enabled, parse_method, custom_parse_url, custom_parse_token))
# Initialize cache config
cache_config = config_dict.get("cache", {})
cache_enabled = cache_config.get("enabled", False)
cache_timeout = cache_config.get("timeout", 600)
cache_base_url = cache_config.get("base_url", "")
cache_base_url = cache_base_url if cache_base_url else None
if is_first_startup:
await db.execute("""
INSERT IGNORE INTO cache_config (id, cache_enabled, cache_timeout, cache_base_url)
VALUES (1, ?, ?, ?)
""", (cache_enabled, cache_timeout, cache_base_url))
else:
await db.execute("""
UPDATE cache_config
SET cache_enabled = ?, cache_timeout = ?, cache_base_url = ?, updated_at = CURRENT_TIMESTAMP
WHERE id = 1
""", (cache_enabled, cache_timeout, cache_base_url))
# Initialize generation config
generation_config = config_dict.get("generation", {})
image_timeout = generation_config.get("image_timeout", 300)
video_timeout = generation_config.get("video_timeout", 1500)
if is_first_startup:
await db.execute("""
INSERT IGNORE INTO generation_config (id, image_timeout, video_timeout)
VALUES (1, ?, ?)
""", (image_timeout, video_timeout))
else:
await db.execute("""
UPDATE generation_config
SET image_timeout = ?, video_timeout = ?, updated_at = CURRENT_TIMESTAMP
WHERE id = 1
""", (image_timeout, video_timeout))
# Initialize token refresh config
token_refresh_config = config_dict.get("token_refresh", {})
at_auto_refresh_enabled = token_refresh_config.get("at_auto_refresh_enabled", False)
if is_first_startup:
await db.execute("""
INSERT IGNORE INTO token_refresh_config (id, at_auto_refresh_enabled)
VALUES (1, ?)
""", (at_auto_refresh_enabled,))
else:
await db.execute("""
UPDATE token_refresh_config
SET at_auto_refresh_enabled = ?, updated_at = CURRENT_TIMESTAMP
WHERE id = 1
""", (at_auto_refresh_enabled,))
await db.commit()
# Token operations
async def add_token(self, token: Token) -> int:
"""Add a new token"""
async with self.connect() as db:
cursor = await db.execute("""
INSERT INTO tokens (token, email, username, name, st, rt, remark, expiry_time, is_active,
plan_type, plan_title, subscription_end, sora2_supported, sora2_invite_code,
sora2_redeemed_count, sora2_total_count, sora2_remaining_count, sora2_cooldown_until,
image_enabled, video_enabled)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""", (token.token, token.email, "", token.name, token.st, token.rt,
token.remark, token.expiry_time, token.is_active,
token.plan_type, token.plan_title, token.subscription_end,
token.sora2_supported, token.sora2_invite_code,
token.sora2_redeemed_count, token.sora2_total_count,
token.sora2_remaining_count, token.sora2_cooldown_until,
token.image_enabled, token.video_enabled))
await db.commit()
token_id = cursor.lastrowid
# Create stats entry
await db.execute("""
INSERT INTO token_stats (token_id) VALUES (?)
""", (token_id,))
await db.commit()
return token_id
async def get_token(self, token_id: int) -> Optional[Token]:
"""Get token by ID"""
async with self.connect() as db:
cursor = await db.execute("SELECT * FROM tokens WHERE id = ?", (token_id,))
row = await cursor.fetchone()
if row:
return Token(**dict(row))
return None
async def get_token_by_value(self, token: str) -> Optional[Token]:
"""Get token by value"""
async with self.connect() as db:
cursor = await db.execute("SELECT * FROM tokens WHERE token = ?", (token,))
row = await cursor.fetchone()
if row:
return Token(**dict(row))
return None
async def get_active_tokens(self) -> List[Token]:
"""Get all active tokens (enabled, not cooled down, not expired)"""
async with self.connect() as db:
# MySQL handles booleans as TinyInt, so is_active = 1 works.
# CURRENT_TIMESTAMP is standard.
cursor = await db.execute("""
SELECT * FROM tokens
WHERE is_active = 1
AND (cooled_until IS NULL OR cooled_until < CURRENT_TIMESTAMP)
AND expiry_time > CURRENT_TIMESTAMP
ORDER BY last_used_at ASC
""")
rows = await cursor.fetchall()
return [Token(**dict(row)) for row in rows]
async def get_all_tokens(self) -> List[Token]:
"""Get all tokens"""
async with self.connect() as db:
cursor = await db.execute("SELECT * FROM tokens ORDER BY created_at DESC")
rows = await cursor.fetchall()
return [Token(**dict(row)) for row in rows]
async def update_token_usage(self, token_id: int):
"""Update token usage"""
async with self.connect() as db:
await db.execute("""
UPDATE tokens
SET last_used_at = CURRENT_TIMESTAMP, use_count = use_count + 1
WHERE id = ?
""", (token_id,))
await db.commit()
async def update_token_status(self, token_id: int, is_active: bool):
"""Update token status"""
async with self.connect() as db:
await db.execute("""
UPDATE tokens SET is_active = ? WHERE id = ?
""", (is_active, token_id))
await db.commit()
async def update_token_sora2(self, token_id: int, supported: bool, invite_code: Optional[str] = None,
redeemed_count: int = 0, total_count: int = 0, remaining_count: int = 0):
"""Update token Sora2 support info"""
async with self.connect() as db:
await db.execute("""
UPDATE tokens
SET sora2_supported = ?, sora2_invite_code = ?, sora2_redeemed_count = ?, sora2_total_count = ?, sora2_remaining_count = ?
WHERE id = ?
""", (supported, invite_code, redeemed_count, total_count, remaining_count, token_id))
await db.commit()
async def update_token_sora2_remaining(self, token_id: int, remaining_count: int):
"""Update token Sora2 remaining count"""
async with self.connect() as db:
await db.execute("""
UPDATE tokens SET sora2_remaining_count = ? WHERE id = ?
""", (remaining_count, token_id))
await db.commit()
async def update_token_sora2_cooldown(self, token_id: int, cooldown_until: Optional[datetime]):
"""Update token Sora2 cooldown time"""
async with self.connect() as db:
await db.execute("""
UPDATE tokens SET sora2_cooldown_until = ? WHERE id = ?
""", (cooldown_until, token_id))
await db.commit()
async def update_token_cooldown(self, token_id: int, cooled_until: datetime):
"""Update token cooldown"""
async with self.connect() as db:
await db.execute("""
UPDATE tokens SET cooled_until = ? WHERE id = ?
""", (cooled_until, token_id))
await db.commit()
async def delete_token(self, token_id: int):
"""Delete token"""
async with self.connect() as db:
await db.execute("DELETE FROM token_stats WHERE token_id = ?", (token_id,))
await db.execute("DELETE FROM tokens WHERE id = ?", (token_id,))
await db.commit()
async def update_token(self, token_id: int,
token: Optional[str] = None,
st: Optional[str] = None,
rt: Optional[str] = None,
remark: Optional[str] = None,
expiry_time: Optional[datetime] = None,
plan_type: Optional[str] = None,
plan_title: Optional[str] = None,
subscription_end: Optional[datetime] = None,
image_enabled: Optional[bool] = None,
video_enabled: Optional[bool] = None):
"""Update token (AT, ST, RT, remark, expiry_time, subscription info, image_enabled, video_enabled)"""
async with self.connect() as db:
# Build dynamic update query
updates = []
params = []
if token is not None:
updates.append("token = ?")
params.append(token)
if st is not None:
updates.append("st = ?")
params.append(st)
if rt is not None:
updates.append("rt = ?")
params.append(rt)
if remark is not None:
updates.append("remark = ?")
params.append(remark)
if expiry_time is not None:
updates.append("expiry_time = ?")
params.append(expiry_time)
if plan_type is not None:
updates.append("plan_type = ?")
params.append(plan_type)
if plan_title is not None:
updates.append("plan_title = ?")
params.append(plan_title)
if subscription_end is not None:
updates.append("subscription_end = ?")
params.append(subscription_end)
if image_enabled is not None:
updates.append("image_enabled = ?")
params.append(image_enabled)
if video_enabled is not None:
updates.append("video_enabled = ?")
params.append(video_enabled)
if updates:
params.append(token_id)
query = f"UPDATE tokens SET {', '.join(updates)} WHERE id = ?"
await db.execute(query, params)
await db.commit()
# Token stats operations
async def get_token_stats(self, token_id: int) -> Optional[TokenStats]:
"""Get token statistics"""
async with self.connect() as db:
cursor = await db.execute("SELECT * FROM token_stats WHERE token_id = ?", (token_id,))
row = await cursor.fetchone()
if row:
return TokenStats(**dict(row))
return None
async def increment_image_count(self, token_id: int):
"""Increment image generation count"""
async with self.connect() as db:
await db.execute("""
UPDATE token_stats SET image_count = image_count + 1 WHERE token_id = ?
""", (token_id,))
await db.commit()
async def increment_video_count(self, token_id: int):
"""Increment video generation count"""
async with self.connect() as db:
await db.execute("""
UPDATE token_stats SET video_count = video_count + 1 WHERE token_id = ?
""", (token_id,))
await db.commit()
async def increment_error_count(self, token_id: int):
"""Increment error count"""
async with self.connect() as db:
await db.execute("""
UPDATE token_stats
SET error_count = error_count + 1, last_error_at = CURRENT_TIMESTAMP
WHERE token_id = ?
""", (token_id,))
await db.commit()
async def reset_error_count(self, token_id: int):
"""Reset error count"""
async with self.connect() as db:
await db.execute("""
UPDATE token_stats SET error_count = 0 WHERE token_id = ?
""", (token_id,))
await db.commit()
# Task operations
async def create_task(self, task: Task) -> int:
"""Create a new task"""
async with self.connect() as db:
cursor = await db.execute("""
INSERT INTO tasks (task_id, token_id, model, prompt, status, progress)
VALUES (?, ?, ?, ?, ?, ?)
""", (task.task_id, task.token_id, task.model, task.prompt, task.status, task.progress))
await db.commit()
return cursor.lastrowid
async def update_task(self, task_id: str, status: str, progress: float,
result_urls: Optional[str] = None, error_message: Optional[str] = None):
"""Update task status"""
async with self.connect() as db:
completed_at = datetime.now() if status in ["completed", "failed"] else None
await db.execute("""
UPDATE tasks
SET status = ?, progress = ?, result_urls = ?, error_message = ?, completed_at = ?
WHERE task_id = ?
""", (status, progress, result_urls, error_message, completed_at, task_id))
await db.commit()
async def get_task(self, task_id: str) -> Optional[Task]:
"""Get task by ID"""
async with self.connect() as db:
cursor = await db.execute("SELECT * FROM tasks WHERE task_id = ?", (task_id,))
row = await cursor.fetchone()
if row:
return Task(**dict(row))
return None
# Request log operations
async def log_request(self, log: RequestLog):
"""Log a request"""
async with self.connect() as db:
await db.execute("""
INSERT INTO request_logs (token_id, operation, request_body, response_body, status_code, duration)
VALUES (?, ?, ?, ?, ?, ?)
""", (log.token_id, log.operation, log.request_body, log.response_body,
log.status_code, log.duration))
await db.commit()
async def get_recent_logs(self, limit: int = 100) -> List[dict]:
"""Get recent logs with token email"""
async with self.connect() as db:
cursor = await db.execute("""
SELECT
rl.id,
rl.token_id,
rl.operation,
rl.request_body,
rl.response_body,
rl.status_code,
rl.duration,
rl.created_at,
t.email as token_email
FROM request_logs rl
LEFT JOIN tokens t ON rl.token_id = t.id
ORDER BY rl.created_at DESC
LIMIT ?
""", (limit,))
rows = await cursor.fetchall()
return [dict(row) for row in rows]
# Admin config operations
async def get_admin_config(self) -> AdminConfig:
"""Get admin configuration"""
async with self.connect() as db:
cursor = await db.execute("SELECT * FROM admin_config WHERE id = 1")
row = await cursor.fetchone()
if row:
return AdminConfig(**dict(row))
return AdminConfig(admin_username="admin", admin_password="admin")
async def update_admin_config(self, config: AdminConfig):
"""Update admin configuration"""
async with self.connect() as db:
await db.execute("""
UPDATE admin_config
SET admin_username = ?, admin_password = ?, error_ban_threshold = ?, updated_at = CURRENT_TIMESTAMP
WHERE id = 1
""", (config.admin_username, config.admin_password, config.error_ban_threshold))
await db.commit()
# Proxy config operations
async def get_proxy_config(self) -> ProxyConfig:
"""Get proxy configuration"""
async with self.connect() as db:
cursor = await db.execute("SELECT * FROM proxy_config WHERE id = 1")
row = await cursor.fetchone()
if row:
return ProxyConfig(**dict(row))
return ProxyConfig(proxy_enabled=False)
async def update_proxy_config(self, enabled: bool, proxy_url: Optional[str]):
"""Update proxy configuration"""
async with self.connect() as db:
await db.execute("""
UPDATE proxy_config
SET proxy_enabled = ?, proxy_url = ?, updated_at = CURRENT_TIMESTAMP
WHERE id = 1
""", (enabled, proxy_url))
await db.commit()
# Watermark-free config operations
async def get_watermark_free_config(self) -> WatermarkFreeConfig:
"""Get watermark-free configuration"""
async with self.connect() as db:
cursor = await db.execute("SELECT * FROM watermark_free_config WHERE id = 1")
row = await cursor.fetchone()
if row:
return WatermarkFreeConfig(**dict(row))
return WatermarkFreeConfig(watermark_free_enabled=False, parse_method="third_party")
async def update_watermark_free_config(self, enabled: bool, parse_method: str = None,
custom_parse_url: str = None, custom_parse_token: str = None):
"""Update watermark-free configuration"""
async with self.connect() as db:
if parse_method is None and custom_parse_url is None and custom_parse_token is None:
# Only update enabled status
await db.execute("""
UPDATE watermark_free_config
SET watermark_free_enabled = ?, updated_at = CURRENT_TIMESTAMP
WHERE id = 1
""", (enabled,))
else:
# Update all fields
await db.execute("""
UPDATE watermark_free_config
SET watermark_free_enabled = ?, parse_method = ?, custom_parse_url = ?,
custom_parse_token = ?, updated_at = CURRENT_TIMESTAMP
WHERE id = 1
""", (enabled, parse_method or "third_party", custom_parse_url, custom_parse_token))
await db.commit()
# Cache config operations
async def get_cache_config(self) -> CacheConfig:
"""Get cache configuration"""
async with self.connect() as db:
cursor = await db.execute("SELECT * FROM cache_config WHERE id = 1")
row = await cursor.fetchone()
if row:
return CacheConfig(**dict(row))
return CacheConfig(cache_enabled=False, cache_timeout=600)
async def update_cache_config(self, enabled: bool = None, timeout: int = None, base_url: Optional[str] = None):
"""Update cache configuration"""
async with self.connect() as db:
# Get current config first
cursor = await db.execute("SELECT * FROM cache_config WHERE id = 1")
row = await cursor.fetchone()
if row:
current = dict(row)
new_enabled = enabled if enabled is not None else current.get("cache_enabled", False)
new_timeout = timeout if timeout is not None else current.get("cache_timeout", 600)
new_base_url = base_url if base_url is not None else current.get("cache_base_url")
else:
new_enabled = enabled if enabled is not None else False
new_timeout = timeout if timeout is not None else 600
new_base_url = base_url
# Convert empty string to None
new_base_url = new_base_url if new_base_url else None
await db.execute("""
UPDATE cache_config
SET cache_enabled = ?, cache_timeout = ?, cache_base_url = ?, updated_at = CURRENT_TIMESTAMP
WHERE id = 1
""", (new_enabled, new_timeout, new_base_url))
await db.commit()
# Generation config operations
async def get_generation_config(self) -> GenerationConfig:
"""Get generation configuration"""
async with self.connect() as db:
cursor = await db.execute("SELECT * FROM generation_config WHERE id = 1")
row = await cursor.fetchone()
if row:
return GenerationConfig(**dict(row))
return GenerationConfig(image_timeout=300, video_timeout=1500)
async def update_generation_config(self, image_timeout: int = None, video_timeout: int = None):
"""Update generation configuration"""
async with self.connect() as db:
cursor = await db.execute("SELECT * FROM generation_config WHERE id = 1")
row = await cursor.fetchone()
if row:
current = dict(row)
new_image_timeout = image_timeout if image_timeout is not None else current.get("image_timeout", 300)
new_video_timeout = video_timeout if video_timeout is not None else current.get("video_timeout", 1500)
else:
new_image_timeout = image_timeout if image_timeout is not None else 300
new_video_timeout = video_timeout if video_timeout is not None else 1500
await db.execute("""
UPDATE generation_config
SET image_timeout = ?, video_timeout = ?, updated_at = CURRENT_TIMESTAMP
WHERE id = 1
""", (new_image_timeout, new_video_timeout))
await db.commit()
# Token refresh config operations
async def get_token_refresh_config(self) -> TokenRefreshConfig:
"""Get token refresh configuration"""
async with self.connect() as db:
cursor = await db.execute("SELECT * FROM token_refresh_config WHERE id = 1")
row = await cursor.fetchone()
if row:
return TokenRefreshConfig(**dict(row))
return TokenRefreshConfig(at_auto_refresh_enabled=False)
async def update_token_refresh_config(self, at_auto_refresh_enabled: bool):
"""Update token refresh configuration"""
async with self.connect() as db:
await db.execute("""
UPDATE token_refresh_config
SET at_auto_refresh_enabled = ?, updated_at = CURRENT_TIMESTAMP
WHERE id = 1
""", (at_auto_refresh_enabled,))
await db.commit()
|