facebook-tool/tasks/listed_tasks.py

68 lines
2.4 KiB
Python

import threading
import time
from database.db import get_connection
from services.core.log_service import log_service
from stores.shared_store import SharedStore
from database.models.setting import Setting
from gui.global_signals import global_signals
stop_event = threading.Event()
def stop_listed_task():
stop_event.set()
log_service.info("[Task] Stop signal sent")
def get_pending_items(limit):
conn = get_connection()
cursor = conn.cursor()
cursor.execute("""
SELECT l.id, l.account_id, l.product_id
FROM listed l
JOIN accounts a ON l.account_id = a.id
WHERE l.status='pending' AND a.is_active=1
ORDER BY l.listed_at ASC
LIMIT ?
""", (limit,))
rows = cursor.fetchall()
conn.close()
return rows
def background_loop():
log_service.info("[Task] Background SharedStore loop started")
store = SharedStore.get_instance()
while not stop_event.is_set():
try:
interval = int(Setting.get("LISTING_INTERVAL_SECONDS", 10))
max_concurrent = int(Setting.get("MAX_CONCURRENT_LISTING", 2))
slots = max_concurrent - store.size()
if slots > 0:
pending_items = get_pending_items(slots)
for row in pending_items:
listed_id, account_id, product_id = row
item = {"listed_id": listed_id, "account_id": account_id}
# --- Kiểm tra unique trước khi append ---
if not any(x["listed_id"] == listed_id for x in store.get_items()):
store.append(item)
log_service.info(f"[Task] Added listed_id={listed_id} to SharedStore")
# --- Emit signal để MainWindow mở dialog ---
global_signals.open_login_dialog.emit(account_id, listed_id)
log_service.info(f"[Task] Emitted open_login_dialog for listed_id={listed_id}")
else:
log_service.info(f"[Task] Skipped listed_id={listed_id}, already in SharedStore")
time.sleep(interval)
except Exception as e:
log_service.error(f"[Task] Exception in background_loop: {e}")
log_service.info("[Task] Background SharedStore loop stopped")
def start_background_listed():
t = threading.Thread(target=background_loop, daemon=True)
t.start()
return t