CBV01 commited on
Commit
1830912
·
1 Parent(s): e169f89

Fixed Session Expiry Bug: Optimized the Telegram Pool to trust active connections and avoid redundant pings that trigger security resets. Restored account longevity and high-yield discovery.

Browse files
Files changed (1) hide show
  1. backend/main.py +92 -74
backend/main.py CHANGED
@@ -302,78 +302,79 @@ async def debug_db():
302
  async def resolve_tg_entity(client, target):
303
  """Smarter handle resolver for Telegram joining & Campaigns."""
304
  try:
305
- # 1. Try resolving directly (ID or Username)
306
- resolved_id = target
307
  target_str = str(target).strip()
308
-
309
- if target_str.lstrip('-').isdigit():
310
- resolved_id = int(target_str)
311
-
312
- # Optional: DB lookup by ID to find username (much more stable)
313
- try:
314
- conn = get_db_connection()
315
- # Try exact ID match first
316
- row = conn.execute("SELECT username FROM scraped_groups WHERE id = ?", (target_str,)).fetchone()
317
- if not row:
318
- # Try with -100 prefix variations
319
- if target_str.isdigit():
320
- row = conn.execute("SELECT username FROM scraped_groups WHERE id = ?", (f"-100{target_str}",)).fetchone()
321
- elif target_str.startswith("-100"):
322
- # Use replace to avoid index errors in some linters
323
- clean_id = target_str.replace("-100", "", 1)
324
- row = conn.execute("SELECT username FROM scraped_groups WHERE id = ?", (clean_id,)).fetchone()
325
 
326
- if row and row[0]:
327
- resolved_id = row[0]
328
- if hasattr(conn, "close"): conn.close()
329
- except: pass
330
 
331
- try:
332
- entity = await client.get_entity(resolved_id)
333
- # If we got a User object but asked for a positive int, it's likely a channel missing the -100 prefix.
334
- if isinstance(entity, User) and isinstance(resolved_id, int) and resolved_id > 0:
335
- raise ValueError("Resolved to User, but likely meant a Channel/Group. Forcing -100 prefix check.")
336
- return entity
337
- except Exception as e:
338
- # If it's a positive number, try adding -100 prefix (common for Channels/Supergroups)
339
- if isinstance(resolved_id, int) and resolved_id > 0:
340
- try:
341
- alt_id = int(f"-100{resolved_id}")
342
- entity = await client.get_entity(alt_id)
343
- return entity
344
- except: pass
345
- pass
346
-
347
- # 2. Try cleaning username
348
- if target_str.startswith('@') or not target_str.replace('-','').isdigit():
349
- username = target_str.replace('@', '', 1)
350
  try:
351
- entity = await client.get_entity(username)
 
352
  return entity
353
- except: pass
 
 
 
 
 
 
354
 
355
- # 3. Try resolving as invite link
356
- if "t.me/" in target_str:
357
- if "joinchat/" in target_str or "t.me/+" in target_str:
358
- hash_val = target_str.split('/')[-1].replace('+', '')
 
 
359
  return ("invite", hash_val)
360
  else:
361
- username = target_str.split('/')[-1]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
362
  try:
 
 
 
 
 
 
363
  entity = await client.get_entity(username)
364
  return entity
365
- except: pass
 
366
 
367
- # 4. Final Hail Mary: Search for it globally to "prime" the session
368
  try:
369
- from telethon.tl.functions.contacts import SearchRequest # type: ignore
370
- await client(SearchRequest(q=target_str, limit=5))
371
- entity = await client.get_entity(target_str)
372
- return entity
 
 
 
 
 
373
  except: pass
374
 
375
  except Exception as gl_e:
376
- log_debug(f"RESOLVE_GL_ERR for {target}: {str(gl_e)}")
377
 
378
  return None
379
 
@@ -494,42 +495,59 @@ class TelegramPool:
494
  self._locks[session_key] = asyncio.Lock()
495
 
496
  async with self._locks[session_key]:
497
- # Use a separate key type for cache to avoid tuple confusion
498
- # We map the session object to the phone number
499
  if session_key in self._clients:
500
  client = self._clients[session_key]
501
  if client.is_connected():
502
- try:
503
- await client.get_me()
504
- return client
505
- except Exception:
506
- print(f"POOL: Node {phone_number} stale. Disconnecting...")
507
- try: await client.disconnect()
508
- except: pass
509
 
510
  log_debug(f"POOL: Deploying persistent kernel for {phone_number} (Owner: {owner_id})")
511
  new_client = TelegramClient(StringSession(session_str), api_id, api_hash)
 
 
512
  await new_client.connect()
513
 
514
- if not await new_client.is_user_authorized():
 
 
 
 
 
 
 
 
 
 
 
 
 
 
515
  await new_client.disconnect()
516
- # Update DB status
517
  conn = get_db_connection()
518
- conn.execute("UPDATE accounts SET status = 'expired', status_detail = 'Auth token invalid' WHERE phone_number = ?", (phone_number,))
519
  if hasattr(conn, "commit"): conn.commit()
520
  if hasattr(conn, "close"): conn.close()
521
  raise HTTPException(status_code=401, detail=f"Session for {phone_number} has expired.")
522
 
523
- # Success check & Mark active
524
  try:
525
- me = await new_client.get_me()
 
526
  log_debug(f"POOL: Node {phone_number} ( @{getattr(me,'username','?')} ) online.")
527
  except: pass
528
 
529
- conn = get_db_connection()
530
- conn.execute("UPDATE accounts SET status = 'active' WHERE phone_number = ?", (phone_number,))
531
- if hasattr(conn, "commit"): conn.commit()
532
- if hasattr(conn, "close"): conn.close()
 
 
 
533
 
534
  self._clients[session_key] = new_client
535
  return new_client
 
302
  async def resolve_tg_entity(client, target):
303
  """Smarter handle resolver for Telegram joining & Campaigns."""
304
  try:
305
+ # 1. Normalize target
 
306
  target_str = str(target).strip()
307
+ if not target_str:
308
+ return None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
309
 
310
+ log_debug(f"RESOLVE: Attempting to resolve '{target_str}'...")
 
 
 
311
 
312
+ # 2. Try numeric ID directly
313
+ if target_str.lstrip('-').isdigit():
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
314
  try:
315
+ # Try as-is
316
+ entity = await client.get_entity(int(target_str))
317
  return entity
318
+ except Exception:
319
+ # If it's a positive number, try adding -100 prefix (common for Channels/Supergroups)
320
+ if not target_str.startswith('-'):
321
+ try:
322
+ entity = await client.get_entity(int(f"-100{target_str}"))
323
+ return entity
324
+ except: pass
325
 
326
+ # 3. Try resolving as invite link / URL
327
+ if "t.me/" in target_str or "telegram.me/" in target_str:
328
+ clean_url = target_str.replace("https://", "").replace("http://", "")
329
+ # Handle joinchat links (private)
330
+ if "joinchat/" in clean_url or "/+" in clean_url:
331
+ hash_val = clean_url.split('/')[-1].replace('+', '')
332
  return ("invite", hash_val)
333
  else:
334
+ # Extract username from public link
335
+ username = clean_url.split('/')[-1]
336
+ target_str = username # Continue with username logic
337
+
338
+ # 4. Handle usernames (@name or name)
339
+ username = target_str.lstrip('@')
340
+ if not username.replace('_', '').isalnum():
341
+ # If it's not a valid username format, maybe it's still a numeric ID we missed?
342
+ pass
343
+ else:
344
+ try:
345
+ # Try getting by username
346
+ entity = await client.get_entity(username)
347
+ return entity
348
+ except Exception as e:
349
+ log_debug(f"RESOLVE: Username '{username}' direct resolve failed: {e}")
350
+ # Fallback: Search globally to "prime" the session
351
  try:
352
+ from telethon.tl.functions.messages import SearchGlobalRequest # type: ignore
353
+ from telethon.tl.types import InputMessagesFilterEmpty # type: ignore
354
+
355
+ # Search globally for this username
356
+ await client(SearchGlobalRequest(q=username, filter=InputMessagesFilterEmpty(), limit=1))
357
+ # Try again after search
358
  entity = await client.get_entity(username)
359
  return entity
360
+ except Exception as e2:
361
+ log_debug(f"RESOLVE: Global search fallback for '{username}' failed: {e2}")
362
 
363
+ # 5. DB lookup as last resort (if we have a mapping stored)
364
  try:
365
+ conn = get_db_connection()
366
+ # Try finding a username for this ID if we have it
367
+ row = conn.execute("SELECT username FROM scraped_groups WHERE id = ?", (target_str,)).fetchone()
368
+ if row and row[0]:
369
+ try:
370
+ entity = await client.get_entity(row[0])
371
+ return entity
372
+ except: pass
373
+ if hasattr(conn, "close"): conn.close()
374
  except: pass
375
 
376
  except Exception as gl_e:
377
+ log_debug(f"RESOLVE_FATAL_ERR for {target}: {str(gl_e)}")
378
 
379
  return None
380
 
 
495
  self._locks[session_key] = asyncio.Lock()
496
 
497
  async with self._locks[session_key]:
498
+ # Trust existing connected clients first to avoid over-pinging get_me()
 
499
  if session_key in self._clients:
500
  client = self._clients[session_key]
501
  if client.is_connected():
502
+ # Optional: only check authenticity if it's been idle for a long time
503
+ # For now, trust the connected socket to stay snappy and avoid FloodWait on pings
504
+ return client
505
+ else:
506
+ log_debug(f"POOL: Node {phone_number} socket closed. Reconnecting...")
 
 
507
 
508
  log_debug(f"POOL: Deploying persistent kernel for {phone_number} (Owner: {owner_id})")
509
  new_client = TelegramClient(StringSession(session_str), api_id, api_hash)
510
+
511
+ # Use a slightly longer timeout for connection to prevent flakes on slow proxies/VPS
512
  await new_client.connect()
513
 
514
+ # Multi-check for authorization (Don't disconnect instantly on flakes)
515
+ auth_retries = 2
516
+ authorized = False
517
+ while auth_retries > 0:
518
+ try:
519
+ authorized = await new_client.is_user_authorized()
520
+ break
521
+ except Exception as auth_flake:
522
+ auth_retries -= 1
523
+ if auth_retries > 0:
524
+ await asyncio.sleep(1)
525
+ else:
526
+ log_debug(f"POOL: Auth check fatal for {phone_number}: {auth_flake}")
527
+
528
+ if not authorized:
529
  await new_client.disconnect()
530
+ # Update DB state to reflect expiry for UI
531
  conn = get_db_connection()
532
+ conn.execute("UPDATE accounts SET status = 'expired', status_detail = 'Session expired/invalid' WHERE phone_number = ?", (phone_number,))
533
  if hasattr(conn, "commit"): conn.commit()
534
  if hasattr(conn, "close"): conn.close()
535
  raise HTTPException(status_code=401, detail=f"Session for {phone_number} has expired.")
536
 
537
+ # Node Success: Heartbeat for username sync
538
  try:
539
+ me = await new_client.get_me() if not hasattr(new_client, 'me_cache') else getattr(new_client, 'me_cache')
540
+ new_client.me_cache = me # type: ignore # Simple custom cache
541
  log_debug(f"POOL: Node {phone_number} ( @{getattr(me,'username','?')} ) online.")
542
  except: pass
543
 
544
+ # Persist status
545
+ try:
546
+ conn = get_db_connection()
547
+ conn.execute("UPDATE accounts SET status = 'active' WHERE phone_number = ?", (phone_number,))
548
+ if hasattr(conn, "commit"): conn.commit()
549
+ if hasattr(conn, "close"): conn.close()
550
+ except: pass
551
 
552
  self._clients[session_key] = new_client
553
  return new_client