Spaces:
Sleeping
Sleeping
Update licensing_client.py
Browse files- licensing_client.py +149 -139
licensing_client.py
CHANGED
|
@@ -1,7 +1,7 @@
|
|
| 1 |
# =========================================================
|
| 2 |
# MODULE: licensing_client.py
|
| 3 |
# SYSTEM: ADVANCED RESOURCE & CONCURRENCY THREAD MANAGER
|
| 4 |
-
# FIX:
|
| 5 |
# AUTHOR: Abu Alone © 2026
|
| 6 |
# =========================================================
|
| 7 |
|
|
@@ -14,70 +14,78 @@ import subprocess
|
|
| 14 |
from datetime import datetime
|
| 15 |
from loguru import logger
|
| 16 |
|
| 17 |
-
# Cấu hình đường dẫn lưu trữ thông tin
|
| 18 |
STORAGE_FILE = "Hugging AbuAlone09/AI-Video-Engine-storage"
|
| 19 |
-
# File
|
| 20 |
-
|
| 21 |
|
| 22 |
SERVER_URL = os.getenv("LICENSIFY_SERVER_URL", "https://abualone09-my-licensify-server.hf.space").strip()
|
| 23 |
SECRET_API_KEY = os.getenv("SECRET_API_KEY", "YOUR_SECRET_API_KEY_HERE").strip()
|
| 24 |
|
| 25 |
-
# Khởi tạo
|
| 26 |
os.makedirs(os.path.dirname(STORAGE_FILE), exist_ok=True)
|
| 27 |
-
if not os.path.exists(STORAGE_FILE):
|
| 28 |
-
with open(STORAGE_FILE, "w", encoding="utf-8") as f:
|
| 29 |
-
json.dump({"keys": {}, "free_devices": {}}, f, indent=4)
|
| 30 |
|
| 31 |
-
|
| 32 |
-
if not os.path.exists(
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 36 |
|
| 37 |
-
|
| 38 |
-
THREAD_POOL = {i: {"status": "idle", "key": None, "type": None, "pid": None, "device": None} for i in range(1, 7)}
|
| 39 |
|
| 40 |
# =========================================================
|
| 41 |
-
#
|
| 42 |
# =========================================================
|
| 43 |
|
| 44 |
-
def
|
| 45 |
-
"""Đọc trạng thái
|
| 46 |
try:
|
| 47 |
-
|
| 48 |
-
|
|
|
|
| 49 |
except Exception:
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
# Cơ chế tự động quét dọn (Garbage Collection): Nếu tiến trình bị sập đột ngột, giải phóng luồng ngay
|
| 53 |
-
changed = False
|
| 54 |
-
for slot_str, thread in pool.items():
|
| 55 |
-
if thread["status"] == "rendering" and thread["pid"]:
|
| 56 |
-
# Kiểm tra xem PID có thực sự đang chạy trên OS Linux không
|
| 57 |
-
try:
|
| 58 |
-
os.kill(thread["pid"], 0)
|
| 59 |
-
except (ProcessLookupError, OSError):
|
| 60 |
-
# PID đã chết, reset luồng về idle lập tức để tránh nghẽn mạch
|
| 61 |
-
pool[slot_str] = {"status": "idle", "key": None, "type": None, "pid": None, "device": None, "start_time": 0}
|
| 62 |
-
changed = True
|
| 63 |
-
if changed:
|
| 64 |
-
with open(THREAD_STATE_FILE, "w", encoding="utf-8") as f:
|
| 65 |
-
json.dump(pool, f, indent=4)
|
| 66 |
-
|
| 67 |
-
return pool
|
| 68 |
|
| 69 |
-
def
|
| 70 |
-
"""Ghi
|
| 71 |
try:
|
| 72 |
-
with open(
|
| 73 |
-
json.dump(
|
| 74 |
except Exception as e:
|
| 75 |
-
logger.error(f"
|
| 76 |
|
| 77 |
def get_active_threads_count() -> int:
|
| 78 |
-
"""
|
| 79 |
-
|
| 80 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 81 |
|
| 82 |
# =========================================================
|
| 83 |
# CORE 1: XỬ LÝ ĐỌC / GHI & XÁC THỰC API KEY TỪ XA TỚI SERVER
|
|
@@ -116,8 +124,8 @@ def verify_and_get_license_info(key_input: str, device_id: str) -> tuple:
|
|
| 116 |
clean_expired_keys()
|
| 117 |
token = key_input.strip()
|
| 118 |
|
| 119 |
-
admin_secret = os.getenv("ADMIN_KEY", "
|
| 120 |
-
vip_secret = os.getenv("VIP_KEY", "
|
| 121 |
|
| 122 |
if token == admin_secret:
|
| 123 |
return True, {
|
|
@@ -127,7 +135,7 @@ def verify_and_get_license_info(key_input: str, device_id: str) -> tuple:
|
|
| 127 |
"tx_date": datetime.now().strftime("%Y-%m-%d"),
|
| 128 |
"expiry": "Permanent Access",
|
| 129 |
"days_left": 9999,
|
| 130 |
-
"msg": "📋 SYSTEM STATUS: Admin Master Active.",
|
| 131 |
"show_test_panel": True,
|
| 132 |
"remove_watermark": True,
|
| 133 |
"bypass_limits": True
|
|
@@ -141,20 +149,21 @@ def verify_and_get_license_info(key_input: str, device_id: str) -> tuple:
|
|
| 141 |
"tx_date": datetime.now().strftime("%Y-%m-%d"),
|
| 142 |
"expiry": "2026-12-31",
|
| 143 |
"days_left": 200,
|
| 144 |
-
"msg": "👑 VIP STATUS: Promo Key Verified.",
|
| 145 |
"show_test_panel": False,
|
| 146 |
"remove_watermark": True,
|
| 147 |
"bypass_limits": True
|
| 148 |
}
|
| 149 |
|
| 150 |
data = _load_storage()
|
|
|
|
| 151 |
if token in data["keys"]:
|
| 152 |
info = data["keys"][token]
|
| 153 |
days_left = int((info["expiry_timestamp"] - time.time()) / 86400)
|
| 154 |
return True, {
|
| 155 |
"tier": "VIP", "tx_name": info["tx_name"], "amount": info["amount"],
|
| 156 |
"tx_date": info["tx_date"], "expiry": info["expiry"], "days_left": max(0, days_left),
|
| 157 |
-
"msg": f"👑 VIP ACTIVE | User: {info['tx_name']}",
|
| 158 |
"show_test_panel": False,
|
| 159 |
"remove_watermark": True,
|
| 160 |
"bypass_limits": False
|
|
@@ -185,42 +194,42 @@ def verify_and_get_license_info(key_input: str, device_id: str) -> tuple:
|
|
| 185 |
return True, {
|
| 186 |
"tier": "VIP", "tx_name": tx_info.get("buyer_name"), "amount": tx_info.get("amount_paid"),
|
| 187 |
"tx_date": tx_info.get("payment_date"), "expiry": expiry_str, "days_left": max(0, days_left),
|
| 188 |
-
"msg": f"👑 VIP KEY VERIFIED.",
|
| 189 |
"show_test_panel": False,
|
| 190 |
"remove_watermark": True,
|
| 191 |
"bypass_limits": False
|
| 192 |
}
|
| 193 |
-
return False, {"msg": "❌ Invalid Access Key", "show_test_panel": False, "remove_watermark": False, "tier": "FREE"}
|
| 194 |
except Exception as e:
|
| 195 |
-
return False, {"msg": f"⚠️ Connection error: {str(e)}", "show_test_panel": False, "remove_watermark": False, "tier": "FREE"}
|
| 196 |
|
| 197 |
# =========================================================
|
| 198 |
-
# CORE 2:
|
| 199 |
# =========================================================
|
| 200 |
|
| 201 |
-
def get_thread_status_json()
|
| 202 |
-
"""Hàm này nhảy số từng giây
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
# Chuyển đổi định dạng key thành kiểu số để tương thích ngược hoàn toàn với run_app.py
|
| 209 |
-
compatible_pool = {int(k): v for k, v in pool.items()}
|
| 210 |
return {
|
| 211 |
"busy_channels": f"{busy_count}/6",
|
| 212 |
"vip_active": vip_count,
|
| 213 |
"free_active": free_count,
|
| 214 |
-
"pool":
|
| 215 |
}
|
| 216 |
|
| 217 |
def allocate_render_thread(key_input: str, device_id: str, is_vip: bool) -> tuple:
|
| 218 |
-
"""
|
| 219 |
-
|
|
|
|
|
|
|
| 220 |
token = key_input.strip()
|
| 221 |
-
|
| 222 |
-
#
|
| 223 |
-
for
|
| 224 |
if thread["status"] == "rendering":
|
| 225 |
if is_vip and thread["key"] == token:
|
| 226 |
return False, "❌ This VIP Key is already running a rendering process! Multi-thread allocation denied."
|
|
@@ -228,46 +237,43 @@ def allocate_render_thread(key_input: str, device_id: str, is_vip: bool) -> tupl
|
|
| 228 |
return False, "❌ Your device is currently rendering a video. Please wait until it completes!"
|
| 229 |
|
| 230 |
target_slot = None
|
| 231 |
-
|
| 232 |
if is_vip:
|
| 233 |
-
#
|
| 234 |
for i in range(1, 6):
|
| 235 |
-
if
|
| 236 |
-
target_slot = i
|
| 237 |
break
|
| 238 |
-
|
| 239 |
-
# Nếu luồng 1-5 bận, kiểm tra luồng số 6
|
| 240 |
-
if not target_slot:
|
| 241 |
-
if pool["6"]["status"] == "idle":
|
| 242 |
-
target_slot = 6
|
| 243 |
-
elif pool["6"]["type"] == "FREE":
|
| 244 |
-
# CƠ CHẾ TRỤC XUẤT: Luồng 6 của user thường bị VIP đá văng khẩn cấp lập tức
|
| 245 |
-
free_pid = pool["6"]["pid"]
|
| 246 |
-
free_device = pool["6"]["device"]
|
| 247 |
-
logger.warning(f"👑 VIP Eviction Triggered: Terminating Free PID {free_pid} at Slot 6.")
|
| 248 |
-
try:
|
| 249 |
-
if free_pid:
|
| 250 |
-
os.kill(free_pid, signal.SIGKILL)
|
| 251 |
-
except ProcessLookupError:
|
| 252 |
-
pass
|
| 253 |
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
logger.
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 267 |
else:
|
| 268 |
-
#
|
| 269 |
-
if
|
| 270 |
-
target_slot = 6
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 271 |
|
| 272 |
if not target_slot:
|
| 273 |
return False, "⚠️ All rendering channels are currently full. Please try again in a few moments!"
|
|
@@ -275,8 +281,8 @@ def allocate_render_thread(key_input: str, device_id: str, is_vip: bool) -> tupl
|
|
| 275 |
return True, int(target_slot)
|
| 276 |
|
| 277 |
def register_process_to_slot(slot: int, key_input: str, device_id: str, is_vip: bool, pid: int):
|
| 278 |
-
|
| 279 |
-
|
| 280 |
"status": "rendering",
|
| 281 |
"key": key_input.strip() if is_vip else None,
|
| 282 |
"type": "VIP" if is_vip else "FREE",
|
|
@@ -284,26 +290,26 @@ def register_process_to_slot(slot: int, key_input: str, device_id: str, is_vip:
|
|
| 284 |
"device": device_id,
|
| 285 |
"start_time": time.time()
|
| 286 |
}
|
| 287 |
-
|
| 288 |
|
| 289 |
def release_thread_slot(slot: int):
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
|
|
|
|
| 294 |
|
| 295 |
# =========================================================
|
| 296 |
-
# CORE 3: GIÁM SÁT HẠN MỨC CHẶN
|
| 297 |
# =========================================================
|
| 298 |
|
| 299 |
def check_generation_limits(key_input: str, device_id: str, is_vip: bool) -> tuple:
|
| 300 |
-
|
| 301 |
data = _load_storage()
|
| 302 |
today_str = datetime.now().strftime("%Y-%m-%d")
|
| 303 |
now_ts = time.time()
|
| 304 |
|
| 305 |
if is_vip:
|
| 306 |
-
# Nếu là VIP Key mua từ cổng thanh toán, giới hạn 5 batches / ngày
|
| 307 |
if key_input not in data["keys"]:
|
| 308 |
return False, "License error: Key missing from verified list."
|
| 309 |
|
|
@@ -321,9 +327,9 @@ def check_generation_limits(key_input: str, device_id: str, is_vip: bool) -> tup
|
|
| 321 |
if vip_data.get("daily_batches", 0) >= 5:
|
| 322 |
return False, "❌ You have exhausted your daily limit of 5 batches. Please return tomorrow!"
|
| 323 |
|
| 324 |
-
|
|
|
|
| 325 |
else:
|
| 326 |
-
# Người dùng miễn phí: Khóa chặt 3 videos/ngày, cooldown 3 tiếng
|
| 327 |
if device_id not in data["free_devices"]:
|
| 328 |
data["free_devices"][device_id] = {
|
| 329 |
"last_date": today_str,
|
|
@@ -338,15 +344,16 @@ def check_generation_limits(key_input: str, device_id: str, is_vip: bool) -> tup
|
|
| 338 |
free_data["cooldown_until"] = 0
|
| 339 |
|
| 340 |
if now_ts < free_data.get("cooldown_until", 0):
|
| 341 |
-
wait_hours = int((free_data["cooldown_until"] - now_ts) / 3600)
|
| 342 |
-
return False, f"⏱️ Free Tier Cooldown: Please wait {wait_hours} hours before generating again, or upgrade to VIP Premium!"
|
| 343 |
|
| 344 |
if free_data.get("daily_batches", 0) >= 3:
|
| 345 |
return False, "❌ Free Tier Exhausted! Maximum 3 daily videos reached."
|
| 346 |
|
| 347 |
-
return True, "Free
|
| 348 |
|
| 349 |
def commit_generation_success(key_input: str, device_id: str, is_vip: bool):
|
|
|
|
| 350 |
data = _load_storage()
|
| 351 |
now_ts = time.time()
|
| 352 |
|
|
@@ -362,36 +369,39 @@ def commit_generation_success(key_input: str, device_id: str, is_vip: bool):
|
|
| 362 |
if device_id in data["free_devices"]:
|
| 363 |
free_data = data["free_devices"][device_id]
|
| 364 |
free_data["daily_batches"] = free_data.get("daily_batches", 0) + 1
|
| 365 |
-
free_data["cooldown_until"] = now_ts + (3 * 3600)
|
| 366 |
|
| 367 |
_save_storage(data)
|
| 368 |
|
| 369 |
# =========================================================
|
| 370 |
-
# CORE 4:
|
| 371 |
# =========================================================
|
| 372 |
|
| 373 |
-
def force_abort_user_session(
|
| 374 |
-
"""
|
| 375 |
-
|
| 376 |
-
|
|
|
|
| 377 |
released = False
|
| 378 |
|
| 379 |
-
for
|
| 380 |
if thread["status"] == "rendering":
|
| 381 |
-
#
|
| 382 |
-
|
| 383 |
-
|
| 384 |
-
|
| 385 |
-
|
| 386 |
-
|
|
|
|
| 387 |
os.kill(pid, signal.SIGKILL)
|
| 388 |
-
|
| 389 |
-
|
| 390 |
-
|
|
|
|
| 391 |
released = True
|
| 392 |
|
| 393 |
if released:
|
| 394 |
-
|
| 395 |
return released
|
| 396 |
|
| 397 |
def execute_admin_diagnostic_test() -> str:
|
|
@@ -403,9 +413,9 @@ def execute_admin_diagnostic_test() -> str:
|
|
| 403 |
if result.returncode == 0:
|
| 404 |
return f"✅ [TESTER REPORT SUCCESS]:\n{result.stdout.strip()}"
|
| 405 |
else:
|
| 406 |
-
return f"❌ [TESTER REPORT CRASHED]:\n{result.stderr.strip()}"
|
| 407 |
except subprocess.TimeoutExpired:
|
| 408 |
-
return "⚠️ [TESTER TIMEOUT]:
|
| 409 |
except Exception as e:
|
| 410 |
return f"❌ [SYSTEM CRASH]: Lỗi: {str(e)}"
|
| 411 |
|
|
|
|
| 1 |
# =========================================================
|
| 2 |
# MODULE: licensing_client.py
|
| 3 |
# SYSTEM: ADVANCED RESOURCE & CONCURRENCY THREAD MANAGER
|
| 4 |
+
# FIX: DYNAMIC FILE-BASED TRANSACTION SHARING FOR MULTI-WORKERS
|
| 5 |
# AUTHOR: Abu Alone © 2026
|
| 6 |
# =========================================================
|
| 7 |
|
|
|
|
| 14 |
from datetime import datetime
|
| 15 |
from loguru import logger
|
| 16 |
|
| 17 |
+
# Cấu hình đường dẫn lưu trữ và thông tin Server cổng thanh toán dịch vụ
|
| 18 |
STORAGE_FILE = "Hugging AbuAlone09/AI-Video-Engine-storage"
|
| 19 |
+
# File trạng thái phân luồng dùng chung giữa toàn bộ các Worker tiến trình để số nhảy thực tế từng giây
|
| 20 |
+
THREAD_STATUS_FILE = "Hugging AbuAlone09/AI-Video-Engine-threads"
|
| 21 |
|
| 22 |
SERVER_URL = os.getenv("LICENSIFY_SERVER_URL", "https://abualone09-my-licensify-server.hf.space").strip()
|
| 23 |
SECRET_API_KEY = os.getenv("SECRET_API_KEY", "YOUR_SECRET_API_KEY_HERE").strip()
|
| 24 |
|
| 25 |
+
# Khởi tạo thư mục và tệp cấu trúc lưu trữ
|
| 26 |
os.makedirs(os.path.dirname(STORAGE_FILE), exist_ok=True)
|
|
|
|
|
|
|
|
|
|
| 27 |
|
| 28 |
+
def _init_system_files():
|
| 29 |
+
if not os.path.exists(STORAGE_FILE):
|
| 30 |
+
with open(STORAGE_FILE, "w", encoding="utf-8") as f:
|
| 31 |
+
json.dump({"keys": {}, "free_devices": {}}, f, indent=4)
|
| 32 |
+
|
| 33 |
+
# Khởi tạo pool 6 luồng thực tế vào file dùng chung nếu chưa có
|
| 34 |
+
if not os.path.exists(THREAD_STATUS_FILE):
|
| 35 |
+
initial_pool = {str(i): {"status": "idle", "key": None, "type": None, "pid": None, "device": None, "start_time": 0} for i in range(1, 7)}
|
| 36 |
+
with open(THREAD_STATUS_FILE, "w", encoding="utf-8") as f:
|
| 37 |
+
json.dump(initial_pool, f, indent=4)
|
| 38 |
|
| 39 |
+
_init_system_files()
|
|
|
|
| 40 |
|
| 41 |
# =========================================================
|
| 42 |
+
# THÀNH PHẦN CORE: ĐỒNG BỘ THỜI GIAN THỰC ĐA TIẾN TRÌNH (FILE-BASED MONITOR)
|
| 43 |
# =========================================================
|
| 44 |
|
| 45 |
+
def _load_threads_state() -> dict:
|
| 46 |
+
"""Đọc trực tiếp trạng thái luồng từ tệp dùng chung để tránh lệch số giữa các API worker"""
|
| 47 |
try:
|
| 48 |
+
if os.path.exists(THREAD_STATUS_FILE):
|
| 49 |
+
with open(THREAD_STATUS_FILE, "r", encoding="utf-8") as f:
|
| 50 |
+
return json.load(f)
|
| 51 |
except Exception:
|
| 52 |
+
pass
|
| 53 |
+
return {str(i): {"status": "idle", "key": None, "type": None, "pid": None, "device": None, "start_time": 0} for i in range(1, 7)}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 54 |
|
| 55 |
+
def _save_threads_state(state: dict):
|
| 56 |
+
"""Ghi trạng thái luồng xuống tệp khóa ngay lập tức để đồng bộ hóa"""
|
| 57 |
try:
|
| 58 |
+
with open(THREAD_STATUS_FILE, "w", encoding="utf-8") as f:
|
| 59 |
+
json.dump(state, f, indent=4)
|
| 60 |
except Exception as e:
|
| 61 |
+
logger.error(f"Failed to write thread state cluster: {e}")
|
| 62 |
|
| 63 |
def get_active_threads_count() -> int:
|
| 64 |
+
"""Quét sạch tiến trình chết rớt mạng rồi tính tổng số luồng thực tế đang bận render"""
|
| 65 |
+
clean_dead_or_zombie_threads()
|
| 66 |
+
state = _load_threads_state()
|
| 67 |
+
return sum(1 for t in state.values() if t["status"] == "rendering")
|
| 68 |
+
|
| 69 |
+
def clean_dead_or_zombie_threads():
|
| 70 |
+
"""Kiểm tra PID hệ thống Linux để giải phóng luồng ngay lập tức nếu người dùng đóng tab, rớt mạng, F5"""
|
| 71 |
+
state = _load_threads_state()
|
| 72 |
+
changed = False
|
| 73 |
+
|
| 74 |
+
for slot_id, thread in state.items():
|
| 75 |
+
if thread["status"] == "rendering":
|
| 76 |
+
pid = thread.get("pid")
|
| 77 |
+
if pid:
|
| 78 |
+
try:
|
| 79 |
+
# Gửi tín hiệu 0 để kiểm tra xem tiến trình tạo video đó còn sống thực tế không
|
| 80 |
+
os.kill(pid, 0)
|
| 81 |
+
except (ProcessLookupError, PermissionError):
|
| 82 |
+
# Tiến trình đã chết (người dùng hủy tab hoặc crash giữa chừng) -> Trả luồng về idle lập tức
|
| 83 |
+
logger.warning(f"🧹 Clean-up monitor detected dead PID {pid} on Slot {slot_id}. Reverting to idle.")
|
| 84 |
+
state[slot_id] = {"status": "idle", "key": None, "type": None, "pid": None, "device": None, "start_time": 0}
|
| 85 |
+
changed = True
|
| 86 |
+
|
| 87 |
+
if changed:
|
| 88 |
+
_save_threads_state(state)
|
| 89 |
|
| 90 |
# =========================================================
|
| 91 |
# CORE 1: XỬ LÝ ĐỌC / GHI & XÁC THỰC API KEY TỪ XA TỚI SERVER
|
|
|
|
| 124 |
clean_expired_keys()
|
| 125 |
token = key_input.strip()
|
| 126 |
|
| 127 |
+
admin_secret = os.getenv("ADMIN_KEY", "ADMIN_ABUALONE_2026").strip()
|
| 128 |
+
vip_secret = os.getenv("VIP_KEY", "VIP_PROMO_2026").strip()
|
| 129 |
|
| 130 |
if token == admin_secret:
|
| 131 |
return True, {
|
|
|
|
| 135 |
"tx_date": datetime.now().strftime("%Y-%m-%d"),
|
| 136 |
"expiry": "Permanent Access",
|
| 137 |
"days_left": 9999,
|
| 138 |
+
"msg": "📋 SYSTEM STATUS: Admin Master Active. Full hardware diagnostic test layer unlocked.",
|
| 139 |
"show_test_panel": True,
|
| 140 |
"remove_watermark": True,
|
| 141 |
"bypass_limits": True
|
|
|
|
| 149 |
"tx_date": datetime.now().strftime("%Y-%m-%d"),
|
| 150 |
"expiry": "2026-12-31",
|
| 151 |
"days_left": 200,
|
| 152 |
+
"msg": "👑 VIP STATUS: Promo Key Verified. Watermarks and daily rendering limits removed.",
|
| 153 |
"show_test_panel": False,
|
| 154 |
"remove_watermark": True,
|
| 155 |
"bypass_limits": True
|
| 156 |
}
|
| 157 |
|
| 158 |
data = _load_storage()
|
| 159 |
+
|
| 160 |
if token in data["keys"]:
|
| 161 |
info = data["keys"][token]
|
| 162 |
days_left = int((info["expiry_timestamp"] - time.time()) / 86400)
|
| 163 |
return True, {
|
| 164 |
"tier": "VIP", "tx_name": info["tx_name"], "amount": info["amount"],
|
| 165 |
"tx_date": info["tx_date"], "expiry": info["expiry"], "days_left": max(0, days_left),
|
| 166 |
+
"msg": f"👑 VIP ACTIVE | User: {info['tx_name']} | {max(0, days_left)} days remaining.",
|
| 167 |
"show_test_panel": False,
|
| 168 |
"remove_watermark": True,
|
| 169 |
"bypass_limits": False
|
|
|
|
| 194 |
return True, {
|
| 195 |
"tier": "VIP", "tx_name": tx_info.get("buyer_name"), "amount": tx_info.get("amount_paid"),
|
| 196 |
"tx_date": tx_info.get("payment_date"), "expiry": expiry_str, "days_left": max(0, days_left),
|
| 197 |
+
"msg": f"👑 VIP KEY VERIFIED | Owner: {tx_info.get('buyer_name')} | Expiry: {expiry_str}.",
|
| 198 |
"show_test_panel": False,
|
| 199 |
"remove_watermark": True,
|
| 200 |
"bypass_limits": False
|
| 201 |
}
|
| 202 |
+
return False, {"msg": "❌ Invalid Access Key or communication failure with payment gateway!", "show_test_panel": False, "remove_watermark": False, "tier": "FREE"}
|
| 203 |
except Exception as e:
|
| 204 |
+
return False, {"msg": f"⚠️ Connection error to Licensify Server! Info: {str(e)}", "show_test_panel": False, "remove_watermark": False, "tier": "FREE"}
|
| 205 |
|
| 206 |
# =========================================================
|
| 207 |
+
# CORE 2: CƠ CHẾ PHÂN LUỒNG THÔNG MINH (5 VIP - 1 FREE, ÉP TRỤC XUẤT)
|
| 208 |
# =========================================================
|
| 209 |
|
| 210 |
+
def get_thread_status_json():
|
| 211 |
+
"""Hàm này nhảy số thực tế từng giây dựa trên trạng thái tệp tập trung"""
|
| 212 |
+
clean_dead_or_zombie_threads()
|
| 213 |
+
state = _load_threads_state()
|
| 214 |
+
busy_count = sum(1 for t in state.values() if t["status"] == "rendering")
|
| 215 |
+
vip_count = sum(1 for t in state.values() if t["type"] == "VIP")
|
| 216 |
+
free_count = sum(1 for t in state.values() if t["type"] == "FREE")
|
|
|
|
|
|
|
| 217 |
return {
|
| 218 |
"busy_channels": f"{busy_count}/6",
|
| 219 |
"vip_active": vip_count,
|
| 220 |
"free_active": free_count,
|
| 221 |
+
"pool": state
|
| 222 |
}
|
| 223 |
|
| 224 |
def allocate_render_thread(key_input: str, device_id: str, is_vip: bool) -> tuple:
|
| 225 |
+
"""Cơ chế phân luồng nghiêm ngặt: 5 luồng VIP độc quyền (1-5), luồng 6 cho Free.
|
| 226 |
+
Nếu VIP vào mà hệ thống full, Free ở luồng VIP hoặc luồng 6 sẽ bị ngắt tiến trình lập tức và không tính lượt."""
|
| 227 |
+
clean_dead_or_zombie_threads()
|
| 228 |
+
state = _load_threads_state()
|
| 229 |
token = key_input.strip()
|
| 230 |
+
|
| 231 |
+
# Chặn đứng trường hợp chính Key đó hoặc Device đó đang render trùng lặp
|
| 232 |
+
for slot_id, thread in state.items():
|
| 233 |
if thread["status"] == "rendering":
|
| 234 |
if is_vip and thread["key"] == token:
|
| 235 |
return False, "❌ This VIP Key is already running a rendering process! Multi-thread allocation denied."
|
|
|
|
| 237 |
return False, "❌ Your device is currently rendering a video. Please wait until it completes!"
|
| 238 |
|
| 239 |
target_slot = None
|
| 240 |
+
|
| 241 |
if is_vip:
|
| 242 |
+
# 1. Tìm vị trí trống trong 5 slot đầu của VIP
|
| 243 |
for i in range(1, 6):
|
| 244 |
+
if state[str(i)]["status"] == "idle":
|
| 245 |
+
target_slot = str(i)
|
| 246 |
break
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 247 |
|
| 248 |
+
# 2. Nếu 5 slot đầu bận, kiểm tra slot 6 của Free xem có trống không
|
| 249 |
+
if not target_slot and state["6"]["status"] == "idle":
|
| 250 |
+
target_slot = "6"
|
| 251 |
+
|
| 252 |
+
# 3. [CƠ CHẾ ÉP TRỤC XUẤT]: Nếu toàn bộ máy chủ 6 luồng đều bận, tìm luồng nào của USER THƯỜNG đang chạy ké để ngắt khẩn cấp
|
| 253 |
+
if not target_slot:
|
| 254 |
+
for i in ["6", "1", "2", "3", "4", "5"]:
|
| 255 |
+
if state[i]["type"] == "FREE":
|
| 256 |
+
free_pid = state[i]["pid"]
|
| 257 |
+
logger.warning(f"👑 VIP Eviction Triggered: Terminating Free PID {free_pid} at Slot {i} to liberate resources.")
|
| 258 |
+
try:
|
| 259 |
+
if free_pid:
|
| 260 |
+
os.kill(free_pid, signal.SIGKILL) # Đánh sập tiến trình tạo video của User thường lập tức
|
| 261 |
+
except ProcessLookupError:
|
| 262 |
+
pass
|
| 263 |
+
|
| 264 |
+
target_slot = i
|
| 265 |
+
state[i] = {"status": "idle", "key": None, "type": None, "pid": None, "device": None, "start_time": 0}
|
| 266 |
+
break
|
| 267 |
else:
|
| 268 |
+
# Đối với User thường: Kiểm tra slot 6 độc quyền trước
|
| 269 |
+
if state["6"]["status"] == "idle":
|
| 270 |
+
target_slot = "6"
|
| 271 |
+
else:
|
| 272 |
+
# Nếu slot 6 bận, cho phép dùng ké các slot VIP từ 1-5 nếu chúng đang rảnh hoàn toàn
|
| 273 |
+
for i in range(1, 6):
|
| 274 |
+
if state[str(i)]["status"] == "idle":
|
| 275 |
+
target_slot = str(i)
|
| 276 |
+
break
|
| 277 |
|
| 278 |
if not target_slot:
|
| 279 |
return False, "⚠️ All rendering channels are currently full. Please try again in a few moments!"
|
|
|
|
| 281 |
return True, int(target_slot)
|
| 282 |
|
| 283 |
def register_process_to_slot(slot: int, key_input: str, device_id: str, is_vip: bool, pid: int):
|
| 284 |
+
state = _load_threads_state()
|
| 285 |
+
state[str(slot)] = {
|
| 286 |
"status": "rendering",
|
| 287 |
"key": key_input.strip() if is_vip else None,
|
| 288 |
"type": "VIP" if is_vip else "FREE",
|
|
|
|
| 290 |
"device": device_id,
|
| 291 |
"start_time": time.time()
|
| 292 |
}
|
| 293 |
+
_save_threads_state(state)
|
| 294 |
|
| 295 |
def release_thread_slot(slot: int):
|
| 296 |
+
state = _load_threads_state()
|
| 297 |
+
slot_str = str(slot)
|
| 298 |
+
if slot_str in state:
|
| 299 |
+
state[slot_str] = {"status": "idle", "key": None, "type": None, "pid": None, "device": None, "start_time": 0}
|
| 300 |
+
_save_threads_state(state)
|
| 301 |
|
| 302 |
# =========================================================
|
| 303 |
+
# CORE 3: GIÁM SÁT HẠN MỨC CHẶN CHẶT CHẼ
|
| 304 |
# =========================================================
|
| 305 |
|
| 306 |
def check_generation_limits(key_input: str, device_id: str, is_vip: bool) -> tuple:
|
| 307 |
+
clean_expired_keys()
|
| 308 |
data = _load_storage()
|
| 309 |
today_str = datetime.now().strftime("%Y-%m-%d")
|
| 310 |
now_ts = time.time()
|
| 311 |
|
| 312 |
if is_vip:
|
|
|
|
| 313 |
if key_input not in data["keys"]:
|
| 314 |
return False, "License error: Key missing from verified list."
|
| 315 |
|
|
|
|
| 327 |
if vip_data.get("daily_batches", 0) >= 5:
|
| 328 |
return False, "❌ You have exhausted your daily limit of 5 batches. Please return tomorrow!"
|
| 329 |
|
| 330 |
+
remaining_batches = 5 - vip_data.get("daily_batches", 0)
|
| 331 |
+
return True, {"status_str": f"VIP Usage: Batch {vip_data.get('daily_batches', 0)}/5"}
|
| 332 |
else:
|
|
|
|
| 333 |
if device_id not in data["free_devices"]:
|
| 334 |
data["free_devices"][device_id] = {
|
| 335 |
"last_date": today_str,
|
|
|
|
| 344 |
free_data["cooldown_until"] = 0
|
| 345 |
|
| 346 |
if now_ts < free_data.get("cooldown_until", 0):
|
| 347 |
+
wait_hours = int((free_data["cooldown_until"] - now_ts) / 3600)
|
| 348 |
+
return False, f"⏱️ Free Tier Cooldown: Please wait {wait_hours + 1} hours before generating again, or upgrade to VIP Premium!"
|
| 349 |
|
| 350 |
if free_data.get("daily_batches", 0) >= 3:
|
| 351 |
return False, "❌ Free Tier Exhausted! Maximum 3 daily videos reached."
|
| 352 |
|
| 353 |
+
return True, {"status_str": f"Free Tier Usage: {free_data.get('daily_batches', 0)}/3 Videos"}
|
| 354 |
|
| 355 |
def commit_generation_success(key_input: str, device_id: str, is_vip: bool):
|
| 356 |
+
"""Chỉ cắn trừ lượt tạo thực tế khi video đã render thành công hoàn toàn ra file output"""
|
| 357 |
data = _load_storage()
|
| 358 |
now_ts = time.time()
|
| 359 |
|
|
|
|
| 369 |
if device_id in data["free_devices"]:
|
| 370 |
free_data = data["free_devices"][device_id]
|
| 371 |
free_data["daily_batches"] = free_data.get("daily_batches", 0) + 1
|
| 372 |
+
free_data["cooldown_until"] = now_ts + (3 * 3600)
|
| 373 |
|
| 374 |
_save_storage(data)
|
| 375 |
|
| 376 |
# =========================================================
|
| 377 |
+
# CORE 4: FORCE STOP - KHÔNG TÍNH LƯỢT KHI HỦY HOẶC NÉT MẠNG RỚT
|
| 378 |
# =========================================================
|
| 379 |
|
| 380 |
+
def force_abort_user_session(key_input: str, device_id: str) -> bool:
|
| 381 |
+
"""Khi người dùng nhấn nút STOP đỏ hoặc hệ thống quét F5: Hủy tiến trình Linux lập tức,
|
| 382 |
+
luồng giải phóng hoàn toàn về idle và TUYỆT ĐỐI KHÔNG cắn trừ lượt tạo video của user."""
|
| 383 |
+
state = _load_threads_state()
|
| 384 |
+
token = key_input.strip()
|
| 385 |
released = False
|
| 386 |
|
| 387 |
+
for slot_id, thread in state.items():
|
| 388 |
if thread["status"] == "rendering":
|
| 389 |
+
# Đối soát chuẩn xác phiên làm việc dựa trên key (VIP) hoặc IP thiết bị (Free)
|
| 390 |
+
is_match = (thread["key"] == token) if thread["type"] == "VIP" else (thread["device"] == device_id)
|
| 391 |
+
if is_match:
|
| 392 |
+
pid = thread.get("pid")
|
| 393 |
+
if pid:
|
| 394 |
+
try:
|
| 395 |
+
logger.warning(f"🛑 Manual Force Abort triggered. Killing Video Engine Process PID {pid} instantly.")
|
| 396 |
os.kill(pid, signal.SIGKILL)
|
| 397 |
+
except ProcessLookupError:
|
| 398 |
+
pass
|
| 399 |
+
|
| 400 |
+
state[slot_id] = {"status": "idle", "key": None, "type": None, "pid": None, "device": None, "start_time": 0}
|
| 401 |
released = True
|
| 402 |
|
| 403 |
if released:
|
| 404 |
+
_save_threads_state(state)
|
| 405 |
return released
|
| 406 |
|
| 407 |
def execute_admin_diagnostic_test() -> str:
|
|
|
|
| 413 |
if result.returncode == 0:
|
| 414 |
return f"✅ [TESTER REPORT SUCCESS]:\n{result.stdout.strip()}"
|
| 415 |
else:
|
| 416 |
+
return f"❌ [TESTER REPORT CRASHED WITH EXIT CODE {result.returncode}]:\n{result.stderr.strip()}"
|
| 417 |
except subprocess.TimeoutExpired:
|
| 418 |
+
return "⚠️ [TESTER TIMEOUT]: Tiến trình kiểm thử vượt ngưỡng 15 giây!"
|
| 419 |
except Exception as e:
|
| 420 |
return f"❌ [SYSTEM CRASH]: Lỗi: {str(e)}"
|
| 421 |
|