CBV01 commited on
Commit
ac02e1d
·
1 Parent(s): 4300801

Implement active account selection, live countdowns, and improved join feedback

Browse files
backend/database.py CHANGED
@@ -202,6 +202,7 @@ def init_db():
202
  country TEXT,
203
  status TEXT DEFAULT 'active',
204
  status_detail TEXT,
 
205
  last_active DATETIME DEFAULT CURRENT_TIMESTAMP,
206
  created_at DATETIME DEFAULT CURRENT_TIMESTAMP
207
  )""",
@@ -322,6 +323,7 @@ def init_db():
322
  ("username", "TEXT"),
323
  ("profile_photo", "TEXT"),
324
  ("country", "TEXT"),
 
325
  ("created_at", "DATETIME")
326
  ]
327
  for col_name, col_type in needed_cols:
 
202
  country TEXT,
203
  status TEXT DEFAULT 'active',
204
  status_detail TEXT,
205
+ is_active INTEGER DEFAULT 0,
206
  last_active DATETIME DEFAULT CURRENT_TIMESTAMP,
207
  created_at DATETIME DEFAULT CURRENT_TIMESTAMP
208
  )""",
 
323
  ("username", "TEXT"),
324
  ("profile_photo", "TEXT"),
325
  ("country", "TEXT"),
326
+ ("is_active", "INTEGER DEFAULT 0"),
327
  ("created_at", "DATETIME")
328
  ]
329
  for col_name, col_type in needed_cols:
backend/main.py CHANGED
@@ -890,14 +890,14 @@ async def get_accounts(user_id: str = Depends(get_current_user_id)):
890
  # Admin sees all accounts in the system
891
  rows = conn.execute("""
892
  SELECT phone_number, status, api_id, api_hash,
893
- first_name, last_name, username, profile_photo, country, created_at, user_id
894
  FROM accounts
895
  """).fetchall()
896
  else:
897
  # Regular user only sees their own accounts
898
  rows = conn.execute("""
899
  SELECT phone_number, status, api_id, api_hash,
900
- first_name, last_name, username, profile_photo, country, created_at, user_id
901
  FROM accounts WHERE user_id = ?
902
  """, (user_id,)).fetchall()
903
  if hasattr(conn, "close"): conn.close()
@@ -915,9 +915,25 @@ async def get_accounts(user_id: str = Depends(get_current_user_id)):
915
  "profile_photo": row[7],
916
  "country": row[8],
917
  "created_at": row[9],
918
- "user_id": row[10]
 
919
  })
920
  return {"accounts": accounts}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
921
  @app.delete("/api/telegram/accounts/{phone_number}")
922
  async def delete_account(phone_number: str, user_id: str = Depends(get_current_user_id)):
923
  conn = get_db_connection()
@@ -1380,11 +1396,12 @@ async def scrape_keyword_stream(
1380
  if phone_number:
1381
  rows = conn.execute("SELECT session_string, api_id, api_hash, phone_number FROM accounts WHERE phone_number = ?", (phone_number,)).fetchall()
1382
  else:
1383
- rows = conn.execute("SELECT session_string, api_id, api_hash, phone_number FROM accounts WHERE status = 'active'").fetchall()
1384
  elif phone_number:
1385
  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()
1386
  else:
1387
- rows = conn.execute("SELECT session_string, api_id, api_hash, phone_number FROM accounts WHERE user_id = ? AND status = 'active'", (user_id,)).fetchall()
 
1388
  if hasattr(conn, "close"): conn.close()
1389
  if not rows: raise HTTPException(status_code=404, detail="No active accounts found.")
1390
 
@@ -1663,11 +1680,13 @@ async def bulk_join_stream(
1663
 
1664
  # Micro-Rest: Pause for 2 mins every 5 joins to avoid account flagging
1665
  if idx > 1 and (idx - 1) % 5 == 0:
1666
- yield f"data: {_json.dumps({'type': 'progress', 'idx': idx, 'total': total, 'msg': 'Applying 2-minute Micro-Rest for account safety...'})}\n\n"
1667
- await asyncio.sleep(120)
 
1668
 
1669
- yield f"data: {_json.dumps({'type': 'progress', 'idx': idx, 'total': total, 'msg': f'Safety delay {wait_time}s...'})}\n\n"
1670
- await asyncio.sleep(wait_time)
 
1671
 
1672
  yield f"data: {_json.dumps({'type': 'progress', 'idx': idx, 'total': total, 'msg': f'Joining {group_label}...'})}\n\n"
1673
  # Use pool-based client
@@ -1676,35 +1695,27 @@ async def bulk_join_stream(
1676
  joined = joined + 1
1677
  yield f"data: {_json.dumps({'type': 'joined', 'name': group_label, 'idx': idx, 'total': total, 'joined': joined, 'failed': failed})}\n\n"
1678
  except Exception as e:
1679
- from telethon.errors import FloodWaitError # type: ignore
1680
  err_r = str(e)
1681
 
1682
  if isinstance(e, FloodWaitError):
1683
  wait_seconds: int = cast(int, getattr(e, 'seconds', 0))
1684
- if wait_seconds <= 300: # Wait up to 5 mins automatically
1685
- yield f"data: {_json.dumps({'type': 'progress', 'idx': idx, 'total': total, 'msg': f'Rate limit: Staying quiet for {wait_seconds}s...'})}\n\n"
1686
- await asyncio.sleep(wait_seconds + 2)
1687
- # Retry this same index once
1688
- try:
1689
- await smart_join(client, g_id, str(user_id), str(phone_number))
1690
- joined = joined + 1
1691
- yield f"data: {_json.dumps({'type': 'joined', 'name': group_label, 'idx': idx, 'total': total, 'joined': joined, 'failed': failed})}\n\n"
1692
- continue
1693
- except Exception as retry_e:
1694
- err_r = str(retry_e)
1695
- else:
1696
- yield f"data: {_json.dumps({'type': 'flood', 'msg': f'Telegram Rate Limit: Please wait {wait_seconds} seconds before joining more groups.'})}\n\n"
1697
- break
1698
-
1699
  failed = failed + 1
1700
- err_s = err_r
1701
- # Extremely safe truncation to avoid indexing errors
1702
- if len(err_r) > 80:
1703
- err_s = ""
1704
- for i, char in enumerate(err_r):
1705
- if i >= 77: break
1706
- err_s += char
1707
- err_s += "..."
1708
  failed_groups.append({'name': group_label, 'reason': err_s})
1709
  yield f"data: {_json.dumps({'type': 'failed', 'name': group_label, 'reason': err_s, 'idx': idx, 'total': total, 'joined': joined, 'failed': failed})}\n\n"
1710
 
 
890
  # Admin sees all accounts in the system
891
  rows = conn.execute("""
892
  SELECT phone_number, status, api_id, api_hash,
893
+ first_name, last_name, username, profile_photo, country, created_at, user_id, is_active
894
  FROM accounts
895
  """).fetchall()
896
  else:
897
  # Regular user only sees their own accounts
898
  rows = conn.execute("""
899
  SELECT phone_number, status, api_id, api_hash,
900
+ first_name, last_name, username, profile_photo, country, created_at, user_id, is_active
901
  FROM accounts WHERE user_id = ?
902
  """, (user_id,)).fetchall()
903
  if hasattr(conn, "close"): conn.close()
 
915
  "profile_photo": row[7],
916
  "country": row[8],
917
  "created_at": row[9],
918
+ "user_id": row[10],
919
+ "is_active": row[11]
920
  })
921
  return {"accounts": accounts}
922
+
923
+ @app.post("/api/telegram/accounts/{phone_number}/active")
924
+ async def set_active_account(phone_number: str, user_id: str = Depends(get_current_user_id)):
925
+ conn = get_db_connection()
926
+ try:
927
+ # 1. Deactivate all other accounts for this user
928
+ conn.execute("UPDATE accounts SET is_active = 0 WHERE user_id = ?", (user_id,))
929
+ # 2. Activate the selected account
930
+ conn.execute("UPDATE accounts SET is_active = 1 WHERE phone_number = ? AND user_id = ?", (phone_number, user_id))
931
+ if hasattr(conn, "commit"): conn.commit()
932
+ return {"status": "success", "msg": f"Account {phone_number} is now active."}
933
+ except Exception as e:
934
+ raise HTTPException(status_code=500, detail=str(e))
935
+ finally:
936
+ if hasattr(conn, "close"): conn.close()
937
  @app.delete("/api/telegram/accounts/{phone_number}")
938
  async def delete_account(phone_number: str, user_id: str = Depends(get_current_user_id)):
939
  conn = get_db_connection()
 
1396
  if phone_number:
1397
  rows = conn.execute("SELECT session_string, api_id, api_hash, phone_number FROM accounts WHERE phone_number = ?", (phone_number,)).fetchall()
1398
  else:
1399
+ rows = conn.execute("SELECT session_string, api_id, api_hash, phone_number FROM accounts WHERE status = 'active' ORDER BY is_active DESC LIMIT 1").fetchall()
1400
  elif phone_number:
1401
  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()
1402
  else:
1403
+ # Prioritize explicitly active account, fallback to any active status account
1404
+ rows = conn.execute("SELECT session_string, api_id, api_hash, phone_number FROM accounts WHERE user_id = ? AND status = 'active' ORDER BY is_active DESC LIMIT 1", (user_id,)).fetchall()
1405
  if hasattr(conn, "close"): conn.close()
1406
  if not rows: raise HTTPException(status_code=404, detail="No active accounts found.")
1407
 
 
1680
 
1681
  # Micro-Rest: Pause for 2 mins every 5 joins to avoid account flagging
1682
  if idx > 1 and (idx - 1) % 5 == 0:
1683
+ for remaining in range(120, 0, -1):
1684
+ yield f"data: {_json.dumps({'type': 'progress', 'idx': idx, 'total': total, 'msg': f'Micro-Rest: Resuming in {remaining}s...', 'remaining': remaining})}\n\n"
1685
+ await asyncio.sleep(1)
1686
 
1687
+ for remaining in range(wait_time, 0, -1):
1688
+ yield f"data: {_json.dumps({'type': 'progress', 'idx': idx, 'total': total, 'msg': f'Safety delay: {remaining}s...', 'remaining': remaining})}\n\n"
1689
+ await asyncio.sleep(1)
1690
 
1691
  yield f"data: {_json.dumps({'type': 'progress', 'idx': idx, 'total': total, 'msg': f'Joining {group_label}...'})}\n\n"
1692
  # Use pool-based client
 
1695
  joined = joined + 1
1696
  yield f"data: {_json.dumps({'type': 'joined', 'name': group_label, 'idx': idx, 'total': total, 'joined': joined, 'failed': failed})}\n\n"
1697
  except Exception as e:
1698
+ from telethon.errors import FloodWaitError, ChannelsTooMuchError, UserDeactivatedError # type: ignore
1699
  err_r = str(e)
1700
 
1701
  if isinstance(e, FloodWaitError):
1702
  wait_seconds: int = cast(int, getattr(e, 'seconds', 0))
1703
+ yield f"data: {_json.dumps({'type': 'progress', 'idx': idx, 'total': total, 'msg': f'🚨 RATE LIMIT: Telegram says wait {wait_seconds}s. Use the manual Copy button if you are in a hurry.'})}\n\n"
1704
+ # We stop the automated process for FloodWait to protect the account
1705
+ break
1706
+
1707
+ if "too many channels" in err_r.lower() or isinstance(e, ChannelsTooMuchError):
1708
+ err_s = "Account Limit: You are in 500 groups already. Leave some groups first."
1709
+ elif "privacy" in err_r.lower():
1710
+ err_s = "Privacy: Group doesn't allow invites or joining."
1711
+ elif "deactivated" in err_r.lower() or isinstance(e, UserDeactivatedError):
1712
+ err_s = "Account Alert: This account seems banned/deactivated by Telegram."
1713
+ elif "chat_admin_required" in err_r.lower():
1714
+ err_s = "Restricted: Admin required to join."
1715
+ else:
1716
+ err_s = "Join Ignored: Telegram restricted this action. Use the 'Copy' button and join manually."
1717
+
1718
  failed = failed + 1
 
 
 
 
 
 
 
 
1719
  failed_groups.append({'name': group_label, 'reason': err_s})
1720
  yield f"data: {_json.dumps({'type': 'failed', 'name': group_label, 'reason': err_s, 'idx': idx, 'total': total, 'joined': joined, 'failed': failed})}\n\n"
1721
 
frontend/src/app/accounts/page.tsx CHANGED
@@ -11,11 +11,13 @@ import {
11
  AlertCircle,
12
  Users,
13
  Rocket,
14
- ChevronRight,
 
 
15
  Globe,
16
- ChevronDown,
17
  Search,
18
- CloudSync
 
19
  } from 'lucide-react';
20
  import { apiFetch } from '@/lib/auth';
21
  import { Preloader } from '@/components/Preloader';
@@ -262,6 +264,22 @@ export default function AccountsPage() {
262
  }
263
  };
264
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
265
  const handleSessionDump = async (phone: string) => {
266
  setActionLoading(phone + '_dump');
267
  try {
@@ -368,6 +386,21 @@ export default function AccountsPage() {
368
  }`} />
369
  {acc.status}
370
  </span>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
371
  <div className="flex gap-2">
372
  <button
373
  onClick={() => handleSyncProfile(acc.phone_number)}
 
11
  AlertCircle,
12
  Users,
13
  Rocket,
14
+ CloudSync,
15
+ Star,
16
+ Check,
17
  Globe,
 
18
  Search,
19
+ ChevronRight,
20
+ ChevronDown
21
  } from 'lucide-react';
22
  import { apiFetch } from '@/lib/auth';
23
  import { Preloader } from '@/components/Preloader';
 
264
  }
265
  };
266
 
267
+ const handleSetActive = async (phone: string) => {
268
+ setActionLoading(phone + '_active');
269
+ try {
270
+ const res = await apiFetch(`/api/telegram/accounts/${phone}/active`, { method: 'POST' });
271
+ if (res.ok) {
272
+ setSuccessMsg(`Account ${phone} is now your primary node.`);
273
+ fetchAccounts();
274
+ setTimeout(() => setSuccessMsg(''), 5000);
275
+ }
276
+ } catch (err) {
277
+ setError(`Failed to set ${phone} as active.`);
278
+ } finally {
279
+ setActionLoading(null);
280
+ }
281
+ };
282
+
283
  const handleSessionDump = async (phone: string) => {
284
  setActionLoading(phone + '_dump');
285
  try {
 
386
  }`} />
387
  {acc.status}
388
  </span>
389
+ <div className="flex items-center gap-2">
390
+ {acc.is_active ? (
391
+ <div className="flex items-center gap-1.5 px-3 py-1 bg-indigo-500/10 text-indigo-500 rounded-full text-[10px] font-black uppercase border border-indigo-500/20 shadow-lg shadow-indigo-500/10">
392
+ <Star size={12} className="fill-indigo-500" />
393
+ Primary Node
394
+ </div>
395
+ ) : (
396
+ <button
397
+ onClick={() => handleSetActive(acc.phone_number)}
398
+ className="px-3 py-1 bg-foreground/5 hover:bg-foreground/10 text-foreground/40 hover:text-foreground/60 rounded-full text-[10px] font-bold uppercase transition-all"
399
+ >
400
+ {actionLoading === acc.phone_number + '_active' ? <Loader2 size={10} className="animate-spin" /> : 'Make Active'}
401
+ </button>
402
+ )}
403
+ </div>
404
  <div className="flex gap-2">
405
  <button
406
  onClick={() => handleSyncProfile(acc.phone_number)}
frontend/src/app/campaigns/page.tsx CHANGED
@@ -107,7 +107,15 @@ export default function CampaignsPage() {
107
  const res = await apiFetch('/api/telegram/accounts');
108
  if (res.ok) {
109
  const data = await res.json();
110
- setAccounts(data.accounts || []);
 
 
 
 
 
 
 
 
111
  }
112
  } catch (err) {
113
  console.error("Failed to fetch accounts", err);
 
107
  const res = await apiFetch('/api/telegram/accounts');
108
  if (res.ok) {
109
  const data = await res.json();
110
+ const accs = data.accounts || [];
111
+ setAccounts(accs);
112
+
113
+ // If there's an active/primary account, pre-select it for the user
114
+ const active = accs.find((a: any) => a.is_active) || accs.find((a: any) => a.status === 'active');
115
+ if (active && !editingId) {
116
+ setCampaignData(prev => ({ ...prev, phone_number: active.phone_number }));
117
+ if (!dialogs.length) fetchDialogs(active.phone_number);
118
+ }
119
  }
120
  } catch (err) {
121
  console.error("Failed to fetch accounts", err);
frontend/src/app/leads/page.tsx CHANGED
@@ -115,7 +115,7 @@ export default function LeadsPage() {
115
  const groupIds = Array.from(selectedIds).filter(id => typeof id === 'string') as string[];
116
  if (groupIds.length === 0) return;
117
 
118
- const activeAcc = accounts.find(a => a.status === 'active') || accounts[0];
119
  const phoneNumber = activeAcc?.phone_number;
120
  if (!phoneNumber) { setError('No connected account found.'); return; }
121
 
@@ -169,9 +169,17 @@ export default function LeadsPage() {
169
  evtSource.close();
170
  setJoining(false);
171
  } else if (data.type === 'progress') {
172
- setJoinProgress(p => ({
173
- ...p, log: [{ type: 'joined', name: data.msg }, ...p.log.slice(0, 49)]
174
- }));
 
 
 
 
 
 
 
 
175
  }
176
  } catch { }
177
  };
@@ -605,6 +613,18 @@ export default function LeadsPage() {
605
  <div className="flex gap-2 opacity-0 group-hover:opacity-100 transition-opacity">
606
  {l.itemType === 'community' && (
607
  <>
 
 
 
 
 
 
 
 
 
 
 
 
608
  {joinedIds.has(l.id) || (l.username && joinedIds.has(l.username)) ? (
609
  <div
610
  className="px-2 py-1 h-7 bg-emerald-500/10 text-emerald-500 rounded-lg text-[10px] font-bold tracking-wider uppercase flex items-center justify-center border border-emerald-500/20 shadow-sm"
 
115
  const groupIds = Array.from(selectedIds).filter(id => typeof id === 'string') as string[];
116
  if (groupIds.length === 0) return;
117
 
118
+ const activeAcc = accounts.find(a => a.is_active) || accounts.find(a => a.status === 'active') || accounts[0];
119
  const phoneNumber = activeAcc?.phone_number;
120
  if (!phoneNumber) { setError('No connected account found.'); return; }
121
 
 
169
  evtSource.close();
170
  setJoining(false);
171
  } else if (data.type === 'progress') {
172
+ setJoinProgress(p => {
173
+ const newLog = [...p.log];
174
+ // If the latest log is a safety delay or rest, replace it instead of pushing
175
+ const isCountdown = data.msg.includes('s...') || data.msg.includes('delay');
176
+ if (isCountdown && newLog.length > 0 && (newLog[0].name.includes('delay') || newLog[0].name.includes('Resuming'))) {
177
+ newLog[0] = { type: 'joined', name: data.msg };
178
+ } else {
179
+ newLog.unshift({ type: 'joined', name: data.msg });
180
+ }
181
+ return { ...p, log: newLog.slice(0, 50) };
182
+ });
183
  }
184
  } catch { }
185
  };
 
613
  <div className="flex gap-2 opacity-0 group-hover:opacity-100 transition-opacity">
614
  {l.itemType === 'community' && (
615
  <>
616
+ <button
617
+ onClick={(e) => {
618
+ e.stopPropagation();
619
+ const text = l.username ? `@${l.username}` : l.id;
620
+ navigator.clipboard.writeText(text);
621
+ alert('Copied to clipboard');
622
+ }}
623
+ className="p-1.5 bg-foreground/5 hover:bg-indigo-500/10 hover:text-indigo-500 rounded-lg text-foreground/30 transition-all"
624
+ title="Copy Username/ID"
625
+ >
626
+ <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect width="14" height="14" x="8" y="8" rx="2" ry="2"/><path d="M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"/></svg>
627
+ </button>
628
  {joinedIds.has(l.id) || (l.username && joinedIds.has(l.username)) ? (
629
  <div
630
  className="px-2 py-1 h-7 bg-emerald-500/10 text-emerald-500 rounded-lg text-[10px] font-bold tracking-wider uppercase flex items-center justify-center border border-emerald-500/20 shadow-sm"