Spaces:
Paused

CBV01 commited on
Commit
ac02b4d
·
1 Parent(s): c726414

Critical Fix: Resolved account-sharing session conflicts and restored Admin scraping access

Browse files
Files changed (1) hide show
  1. backend/main.py +53 -38
backend/main.py CHANGED
@@ -246,32 +246,14 @@ qr_sessions: Dict[str, Dict[str, Any]] = {}
246
  class TelegramPool:
247
  """Manages a pool of persistent Telegram clients for low-latency operations."""
248
  def __init__(self):
249
- # Key: (user_id, phone_number)
250
- self._clients: Dict[tuple, TelegramClient] = {}
251
- self._locks: Dict[tuple, asyncio.Lock] = {}
252
 
253
  async def get_client(self, user_id: str, phone_number: str) -> TelegramClient:
254
- key = (user_id, phone_number)
255
- if key not in self._locks:
256
- self._locks[key] = asyncio.Lock()
257
-
258
- async with self._locks[key]:
259
- # If we already have a client, verify it's still alive
260
- if key in self._clients:
261
- client = self._clients[key]
262
- if client.is_connected():
263
- try:
264
- # Lightweight health check
265
- await client.get_me()
266
- return client
267
- except Exception:
268
- log_debug(f"POOL: Client for {phone_number} lost connection or died. Reconnecting...")
269
- try: await client.disconnect()
270
- except: pass
271
-
272
- # Create a new connection instance
273
- conn = get_db_connection()
274
- # Admins can access ANY account. Regular users only their own.
275
  if user_id == "admin_virtual_id":
276
  row = conn.execute(
277
  "SELECT session_string, api_id, api_hash, user_id FROM accounts WHERE phone_number = ?",
@@ -283,18 +265,36 @@ class TelegramPool:
283
  (phone_number, user_id)
284
  ).fetchone()
285
 
286
- if hasattr(conn, "close"): conn.close()
287
-
288
  if not row:
289
- raise HTTPException(status_code=404, detail=f"Account {phone_number} not found or unauthorized.")
 
290
 
291
- session_str, api_id, api_hash, actual_owner_id = row[0], int(row[1]), row[2], row[3]
292
-
293
- # Map back to the ACTUAL owner to avoid duplicate client instances in pool
294
- key = (actual_owner_id, phone_number)
 
 
 
 
 
295
 
296
- log_debug(f"POOL: Booting new persistent node for {phone_number}")
297
- new_client = TelegramClient(StringSession(session_str), int(api_id), api_hash)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
298
  await new_client.connect()
299
 
300
  if not await new_client.is_user_authorized():
@@ -306,13 +306,18 @@ class TelegramPool:
306
  if hasattr(conn, "close"): conn.close()
307
  raise HTTPException(status_code=401, detail=f"Session for {phone_number} has expired.")
308
 
309
- # Mark as active
 
 
 
 
 
310
  conn = get_db_connection()
311
- conn.execute("UPDATE accounts SET status = 'active', status_detail = 'Pooled & Ready', last_active = ? WHERE phone_number = ?", (datetime.now(), phone_number))
312
  if hasattr(conn, "commit"): conn.commit()
313
  if hasattr(conn, "close"): conn.close()
314
 
315
- self._clients[key] = new_client
316
  return new_client
317
 
318
  async def disconnect_all(self):
@@ -1111,7 +1116,12 @@ async def scrape_keyword_stream(
1111
  user_id: str = Depends(get_current_user_id)
1112
  ):
1113
  conn = get_db_connection()
1114
- if phone_number:
 
 
 
 
 
1115
  rows = conn.execute("SELECT session_string, api_id, api_hash, phone_number FROM accounts WHERE phone_number = ? AND user_id = ?", (phone_number, user_id)).fetchall()
1116
  else:
1117
  rows = conn.execute("SELECT session_string, api_id, api_hash, phone_number FROM accounts WHERE user_id = ? AND status = 'active'", (user_id,)).fetchall()
@@ -1178,7 +1188,12 @@ async def scrape_keyword(
1178
  user_id: str = Depends(get_current_user_id)
1179
  ):
1180
  conn = get_db_connection()
1181
- if phone_number:
 
 
 
 
 
1182
  rows = conn.execute(
1183
  "SELECT session_string, api_id, api_hash, phone_number FROM accounts WHERE phone_number = ? AND user_id = ?",
1184
  (phone_number, user_id)
 
246
  class TelegramPool:
247
  """Manages a pool of persistent Telegram clients for low-latency operations."""
248
  def __init__(self):
249
+ # Key: phone_number (Each account has exactly one session regardless of who uses it)
250
+ self._clients: Dict[str, TelegramClient] = {}
251
+ self._locks: Dict[str, asyncio.Lock] = {}
252
 
253
  async def get_client(self, user_id: str, phone_number: str) -> TelegramClient:
254
+ # 1. Resolve ownership first to prevent duplicate sessions
255
+ conn = get_db_connection()
256
+ try:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
257
  if user_id == "admin_virtual_id":
258
  row = conn.execute(
259
  "SELECT session_string, api_id, api_hash, user_id FROM accounts WHERE phone_number = ?",
 
265
  (phone_number, user_id)
266
  ).fetchone()
267
 
 
 
268
  if not row:
269
+ print(f"POOL_ERROR: Account {phone_number} not found for user {user_id}")
270
+ raise HTTPException(status_code=404, detail="Account not found.")
271
 
272
+ session_str, api_id, api_hash, owner_id = row[0], int(row[1]), row[2], row[3]
273
+ finally:
274
+ if hasattr(conn, "close"): conn.close()
275
+
276
+ # Session-unique key (Phone number is the unique axis)
277
+ session_key = phone_number
278
+
279
+ if session_key not in self._locks:
280
+ self._locks[session_key] = asyncio.Lock()
281
 
282
+ async with self._locks[session_key]:
283
+ # Use a separate key type for cache to avoid tuple confusion
284
+ # We map the session object to the phone number
285
+ if session_key in self._clients:
286
+ client = self._clients[session_key]
287
+ if client.is_connected():
288
+ try:
289
+ await client.get_me()
290
+ return client
291
+ except Exception:
292
+ print(f"POOL: Node {phone_number} stale. Disconnecting...")
293
+ try: await client.disconnect()
294
+ except: pass
295
+
296
+ log_debug(f"POOL: Deploying persistent kernel for {phone_number} (Owner: {owner_id})")
297
+ new_client = TelegramClient(StringSession(session_str), api_id, api_hash)
298
  await new_client.connect()
299
 
300
  if not await new_client.is_user_authorized():
 
306
  if hasattr(conn, "close"): conn.close()
307
  raise HTTPException(status_code=401, detail=f"Session for {phone_number} has expired.")
308
 
309
+ # Success check & Mark active
310
+ try:
311
+ me = await new_client.get_me()
312
+ log_debug(f"POOL: Node {phone_number} ( @{getattr(me,'username','?')} ) online.")
313
+ except: pass
314
+
315
  conn = get_db_connection()
316
+ conn.execute("UPDATE accounts SET status = 'active', last_active = ? WHERE phone_number = ?", (datetime.now(), phone_number))
317
  if hasattr(conn, "commit"): conn.commit()
318
  if hasattr(conn, "close"): conn.close()
319
 
320
+ self._clients[session_key] = new_client
321
  return new_client
322
 
323
  async def disconnect_all(self):
 
1116
  user_id: str = Depends(get_current_user_id)
1117
  ):
1118
  conn = get_db_connection()
1119
+ if user_id == "admin_virtual_id":
1120
+ if phone_number:
1121
+ rows = conn.execute("SELECT session_string, api_id, api_hash, phone_number FROM accounts WHERE phone_number = ?", (phone_number,)).fetchall()
1122
+ else:
1123
+ rows = conn.execute("SELECT session_string, api_id, api_hash, phone_number FROM accounts WHERE status = 'active'").fetchall()
1124
+ elif phone_number:
1125
  rows = conn.execute("SELECT session_string, api_id, api_hash, phone_number FROM accounts WHERE phone_number = ? AND user_id = ?", (phone_number, user_id)).fetchall()
1126
  else:
1127
  rows = conn.execute("SELECT session_string, api_id, api_hash, phone_number FROM accounts WHERE user_id = ? AND status = 'active'", (user_id,)).fetchall()
 
1188
  user_id: str = Depends(get_current_user_id)
1189
  ):
1190
  conn = get_db_connection()
1191
+ if user_id == "admin_virtual_id":
1192
+ if phone_number:
1193
+ rows = conn.execute("SELECT session_string, api_id, api_hash, phone_number FROM accounts WHERE phone_number = ?", (phone_number,)).fetchall()
1194
+ else:
1195
+ rows = conn.execute("SELECT session_string, api_id, api_hash, phone_number FROM accounts WHERE status = 'active'").fetchall()
1196
+ elif phone_number:
1197
  rows = conn.execute(
1198
  "SELECT session_string, api_id, api_hash, phone_number FROM accounts WHERE phone_number = ? AND user_id = ?",
1199
  (phone_number, user_id)