CBV01 commited on
Commit
e02e015
·
1 Parent(s): a5e9e6a

Stability Update: Fix message code-blocks, double-sending, and account syncing

Browse files
Files changed (2) hide show
  1. backend/main.py +62 -45
  2. frontend/src/app/accounts/page.tsx +34 -4
backend/main.py CHANGED
@@ -614,6 +614,30 @@ async def verify_code(req: VerifyCodeRequest, user_id: str = Depends(get_current
614
  finally:
615
  pass
616
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
617
  from telethon.tl.functions.contacts import SearchRequest # type: ignore
618
  from telethon.tl.functions.channels import GetParticipantsRequest # type: ignore
619
  from telethon.tl.types import ChannelParticipantsSearch # type: ignore
@@ -1415,7 +1439,7 @@ async def bulk_join_stream(
1415
  failed_groups.append({'name': group_label, 'reason': err_s})
1416
  yield f"data: {_json.dumps({'type': 'failed', 'name': group_label, 'reason': err_s, 'idx': idx, 'total': total, 'joined': joined, 'failed': failed})}\n\n"
1417
  if "FloodWaitError" in err_r:
1418
- yield f"data: {_json.dumps({'type': 'flood', 'msg': 'Flood detected. Stopping to protect your account.'})}\n\n"
1419
  break
1420
 
1421
  yield f"data: {_json.dumps({'type': 'done', 'joined': joined, 'failed': failed, 'failed_groups': failed_groups})}\n\n"
@@ -2182,6 +2206,7 @@ async def task_poller():
2182
  return str(text_obj)
2183
 
2184
  failed_list = []
 
2185
  # High Fidelity Extraction Loop
2186
  for raw_group in target_groups:
2187
  try:
@@ -2208,7 +2233,6 @@ async def task_poller():
2208
  # High-Fidelity Authorization Check
2209
  if not await client.is_user_authorized():
2210
  log_debug(f"BKG_TASK[{task_id}]: CRITICAL - Session expired for {phone_num}")
2211
- # Mark failed and exit since we can't send anything
2212
  conn = get_db_connection()
2213
  conn.execute("UPDATE tasks SET status = 'failed' WHERE id = ?", (task_id,))
2214
  if hasattr(conn, "commit"): conn.commit()
@@ -2217,34 +2241,28 @@ async def task_poller():
2217
  active_tasks.remove(task_id)
2218
  return
2219
 
2220
- # Personalization Merging
2221
- final_msg_base = str(message)
2222
  final_msg_base = final_msg_base.replace('{{Group Name}}', getattr(entity, 'title', 'Our Group'))
2223
  final_msg_base = final_msg_base.replace('{{First Name}}', '').replace('{{Username}}', '')
2224
 
2225
  # Final Spintax processing
2226
- final_msg = recursive_spin(final_msg_base)
2227
 
2228
- # Forensic Snapshot
2229
- msg_snapshot = str(final_msg)
2230
- if len(msg_snapshot) > 50:
2231
- msg_p = ""
2232
- for i, char in enumerate(msg_snapshot):
2233
- if i >= 47: break
2234
- msg_p += char
2235
- msg_snapshot = msg_p + "..."
2236
-
2237
  log_debug(f"BKG_TASK[{task_id}]: Sending to {target_id} via {sender_name}...")
2238
- log_debug(f"BKG_TASK[{task_id}]: Content Snapshot: {msg_snapshot}")
2239
 
2240
  try:
2241
- await client.send_message(entity, final_msg)
2242
  log_debug(f"BKG_TASK[{task_id}]: TRANSMITTED successfully.")
 
2243
 
2244
- inc_conn = get_db_connection()
2245
- inc_conn.execute("UPDATE tasks SET sent_count = sent_count + 1 WHERE id = ?", (task_id,))
2246
- if hasattr(inc_conn, "commit"): inc_conn.commit()
2247
- if hasattr(inc_conn, "close"): inc_conn.close()
 
 
 
2248
  except Exception as send_e:
2249
  err_str = str(send_e)
2250
  log_debug(f"BKG_TASK[{task_id}]: SEND ERROR to {target_id}: {err_str}")
@@ -2252,15 +2270,10 @@ async def task_poller():
2252
  if "ChatWriteForbidden" in err_str: reason = "Chat Restricted"
2253
  elif "PeerIdInvalid" in err_str: reason = "Peer ID Invalid"
2254
  elif "UserIsBlocked" in err_str: reason = "User Blocked"
 
2255
 
2256
  failed_list.append({"id": group, "name": getattr(entity, 'title', group), "reason": reason})
2257
-
2258
- # Even if failed, we should probably update failed_groups in DB to keep user informed
2259
- f_conn = get_db_connection()
2260
- f_conn.execute("UPDATE tasks SET failed_groups = ? WHERE id = ?", (json.dumps(failed_list), task_id))
2261
- if hasattr(f_conn, "commit"): f_conn.commit()
2262
- if hasattr(f_conn, "close"): f_conn.close()
2263
-
2264
  # Moderate Anti-Spam Interval
2265
  await asyncio.sleep(random.randint(15, 30))
2266
  except Exception as group_err:
@@ -2269,20 +2282,18 @@ async def task_poller():
2269
  log_debug(f"BKG_TASK[{task_id}]: Flood detected. Aborting sequence.")
2270
  break
2271
 
2272
- # Mark completed OR Re-schedule
2273
  conn = get_db_connection()
2274
  if interval > 0:
2275
- # Calculate next time based on UTC
2276
  new_time = (datetime.now(timezone.utc) + timedelta(hours=interval)).isoformat()
2277
- # INCREMENT batch_number and RESET sent_count
2278
  conn.execute(
2279
- "UPDATE tasks SET status = 'pending', scheduled_time = ?, batch_number = batch_number + 1, sent_count = 0, failed_groups = ? WHERE id = ?",
2280
- (new_time, json.dumps(failed_list), task_id)
2281
  )
2282
- print(f"BKG: Task {task_id} rescheduled for {new_time} (Batch incremented, count reset)")
2283
  else:
2284
- conn.execute("UPDATE tasks SET status = 'completed', failed_groups = ? WHERE id = ?", (json.dumps(failed_list), task_id))
2285
- print(f"BKG: Task {task_id} marked COMPLETED")
2286
 
2287
  if hasattr(conn, "commit"): conn.commit()
2288
  if hasattr(conn, "close"): conn.close()
@@ -2302,29 +2313,35 @@ async def task_poller():
2302
  now_dt = datetime.now(timezone.utc)
2303
  now_str = now_dt.strftime('%Y-%m-%dT%H:%M')
2304
 
 
2305
  tasks = conn.execute(
2306
  "SELECT id, message_text, target_groups, phone_number, user_id, interval_hours, scheduled_time FROM tasks WHERE status = 'pending' AND scheduled_time <= ?",
2307
  (now_str,)
2308
  ).fetchall()
2309
 
2310
- # Heartbeat log
2311
- print(f"POLLER: Heartbeat - {now_str} | Pending tasks found: {len(tasks)}")
2312
-
 
 
 
 
 
2313
  if hasattr(conn, "close"): conn.close()
2314
 
2315
- # Launch loop
 
 
 
 
2316
  for t in tasks:
2317
  task_id = t[0]
2318
- task_time = t[6]
2319
  if task_id not in active_tasks:
2320
  active_tasks.add(task_id)
2321
- # Start task in background
2322
  asyncio.create_task(run_single_task(*t))
2323
- print(f"POLLER: Launched task {task_id} scheduled for {task_time} (Server now: {now_str})")
2324
  else:
2325
- # Log if it's already running to avoid confusion
2326
- print(f"POLLER: Task {task_id} is already in execution set. Skipping launch.")
2327
-
2328
  except Exception as e:
2329
  print(f"BKG: Poller major error: {e}")
2330
 
 
614
  finally:
615
  pass
616
 
617
+ @app.post("/api/telegram/accounts/{phone_number}/sync")
618
+ async def sync_account_profile(phone_number: str, user_id: str = Depends(get_current_user_id)):
619
+ """Manually refresh profile photo, name, and username from Telegram."""
620
+ try:
621
+ client = await POOL.get_client(user_id, phone_number)
622
+ profile_data = await fetch_tg_profile_data(client, phone_number)
623
+ profile: Dict[str, Any] = cast(Dict[str, Any], profile_data)
624
+
625
+ conn = get_db_connection()
626
+ conn.execute(
627
+ """UPDATE accounts SET
628
+ first_name = ?, last_name = ?, username = ?, profile_photo = ?, country = ?, status = 'active'
629
+ WHERE phone_number = ? AND user_id = ?""",
630
+ (profile['first_name'], profile['last_name'], profile['username'],
631
+ profile['profile_photo'], profile['country'], phone_number, user_id)
632
+ )
633
+ if hasattr(conn, "commit"): conn.commit()
634
+ if hasattr(conn, "close"): conn.close()
635
+
636
+ return {"status": "success", "profile": profile}
637
+ except Exception as e:
638
+ log_debug(f"SYNC_ERROR for {phone_number}: {str(e)}")
639
+ raise HTTPException(status_code=400, detail=f"Sync failed: {str(e)}")
640
+
641
  from telethon.tl.functions.contacts import SearchRequest # type: ignore
642
  from telethon.tl.functions.channels import GetParticipantsRequest # type: ignore
643
  from telethon.tl.types import ChannelParticipantsSearch # type: ignore
 
1439
  failed_groups.append({'name': group_label, 'reason': err_s})
1440
  yield f"data: {_json.dumps({'type': 'failed', 'name': group_label, 'reason': err_s, 'idx': idx, 'total': total, 'joined': joined, 'failed': failed})}\n\n"
1441
  if "FloodWaitError" in err_r:
1442
+ yield f"data: {_json.dumps({'type': 'flood', 'msg': 'Telegram Rate Limit: Your account is resting. Please wait 1-2 hours before joining more groups.'})}\n\n"
1443
  break
1444
 
1445
  yield f"data: {_json.dumps({'type': 'done', 'joined': joined, 'failed': failed, 'failed_groups': failed_groups})}\n\n"
 
2206
  return str(text_obj)
2207
 
2208
  failed_list = []
2209
+ sent_ok_stats = [0]
2210
  # High Fidelity Extraction Loop
2211
  for raw_group in target_groups:
2212
  try:
 
2233
  # High-Fidelity Authorization Check
2234
  if not await client.is_user_authorized():
2235
  log_debug(f"BKG_TASK[{task_id}]: CRITICAL - Session expired for {phone_num}")
 
2236
  conn = get_db_connection()
2237
  conn.execute("UPDATE tasks SET status = 'failed' WHERE id = ?", (task_id,))
2238
  if hasattr(conn, "commit"): conn.commit()
 
2241
  active_tasks.remove(task_id)
2242
  return
2243
 
2244
+ # Personalization Merging & STRIP WHITESPACE (Fixes Code Block bug)
2245
+ final_msg_base = str(message).strip()
2246
  final_msg_base = final_msg_base.replace('{{Group Name}}', getattr(entity, 'title', 'Our Group'))
2247
  final_msg_base = final_msg_base.replace('{{First Name}}', '').replace('{{Username}}', '')
2248
 
2249
  # Final Spintax processing
2250
+ final_msg = recursive_spin(final_msg_base).strip()
2251
 
 
 
 
 
 
 
 
 
 
2252
  log_debug(f"BKG_TASK[{task_id}]: Sending to {target_id} via {sender_name}...")
 
2253
 
2254
  try:
2255
+ await client.send_message(entity, final_msg, parse_mode='md') # Explicitly type as MD to avoid auto-code conversion
2256
  log_debug(f"BKG_TASK[{task_id}]: TRANSMITTED successfully.")
2257
+ sent_ok_stats[0] += 1 # type: ignore
2258
 
2259
+ # Background count update (Less frequent to avoid choke)
2260
+ if sent_ok_stats[0] % 5 == 0:
2261
+ u_conn = get_db_connection()
2262
+ u_conn.execute("UPDATE tasks SET sent_count = ?, failed_groups = ? WHERE id = ?", (sent_ok_stats[0], json.dumps(failed_list), task_id))
2263
+ if hasattr(u_conn, "commit"): u_conn.commit()
2264
+ if hasattr(u_conn, "close"): u_conn.close()
2265
+
2266
  except Exception as send_e:
2267
  err_str = str(send_e)
2268
  log_debug(f"BKG_TASK[{task_id}]: SEND ERROR to {target_id}: {err_str}")
 
2270
  if "ChatWriteForbidden" in err_str: reason = "Chat Restricted"
2271
  elif "PeerIdInvalid" in err_str: reason = "Peer ID Invalid"
2272
  elif "UserIsBlocked" in err_str: reason = "User Blocked"
2273
+ elif "FloodWait" in err_str: reason = "Telegram Limit"
2274
 
2275
  failed_list.append({"id": group, "name": getattr(entity, 'title', group), "reason": reason})
2276
+
 
 
 
 
 
 
2277
  # Moderate Anti-Spam Interval
2278
  await asyncio.sleep(random.randint(15, 30))
2279
  except Exception as group_err:
 
2282
  log_debug(f"BKG_TASK[{task_id}]: Flood detected. Aborting sequence.")
2283
  break
2284
 
2285
+ # Final Batch Update (One Connection)
2286
  conn = get_db_connection()
2287
  if interval > 0:
 
2288
  new_time = (datetime.now(timezone.utc) + timedelta(hours=interval)).isoformat()
 
2289
  conn.execute(
2290
+ "UPDATE tasks SET status = 'pending', scheduled_time = ?, batch_number = batch_number + 1, sent_count = ?, failed_groups = ? WHERE id = ?",
2291
+ (new_time, sent_ok_stats[0], json.dumps(failed_list), task_id)
2292
  )
2293
+ print(f"BKG: Task {task_id} rescheduled for {new_time} (Successful: {sent_ok_stats[0]})")
2294
  else:
2295
+ conn.execute("UPDATE tasks SET status = 'completed', sent_count = ?, failed_groups = ? WHERE id = ?", (sent_ok_stats[0], json.dumps(failed_list), task_id))
2296
+ print(f"BKG: Task {task_id} marked COMPLETED (Successful: {sent_ok_stats[0]})")
2297
 
2298
  if hasattr(conn, "commit"): conn.commit()
2299
  if hasattr(conn, "close"): conn.close()
 
2313
  now_dt = datetime.now(timezone.utc)
2314
  now_str = now_dt.strftime('%Y-%m-%dT%H:%M')
2315
 
2316
+ # 1. Fetch PENDING tasks
2317
  tasks = conn.execute(
2318
  "SELECT id, message_text, target_groups, phone_number, user_id, interval_hours, scheduled_time FROM tasks WHERE status = 'pending' AND scheduled_time <= ?",
2319
  (now_str,)
2320
  ).fetchall()
2321
 
2322
+ if tasks:
2323
+ # 2. IMMEDIATELY MARK QUEUED (Hard Lock) to prevent double picking
2324
+ task_ids = [t[0] for t in tasks]
2325
+ placeholders = ",".join(["?"] * len(task_ids))
2326
+ conn.execute(f"UPDATE tasks SET status = 'queued' WHERE id IN ({placeholders})", tuple(task_ids))
2327
+ if hasattr(conn, "commit"): conn.commit()
2328
+ print(f"POLLER: Locked {len(tasks)} tasks for production.")
2329
+
2330
  if hasattr(conn, "close"): conn.close()
2331
 
2332
+ # Heartbeat log
2333
+ if tasks:
2334
+ print(f"POLLER: Heartbeat - {now_str} | Launched tasks: {len(tasks)}")
2335
+
2336
+ # 3. Launch loop
2337
  for t in tasks:
2338
  task_id = t[0]
 
2339
  if task_id not in active_tasks:
2340
  active_tasks.add(task_id)
 
2341
  asyncio.create_task(run_single_task(*t))
 
2342
  else:
2343
+ print(f"POLLER: Task {task_id} is already in execution set. Checking lock.")
2344
+
 
2345
  except Exception as e:
2346
  print(f"BKG: Poller major error: {e}")
2347
 
frontend/src/app/accounts/page.tsx CHANGED
@@ -14,7 +14,8 @@ import {
14
  ChevronRight,
15
  Globe,
16
  ChevronDown,
17
- Search
 
18
  } from 'lucide-react';
19
  import { apiFetch } from '@/lib/auth';
20
  import { Preloader } from '@/components/Preloader';
@@ -247,6 +248,25 @@ export default function AccountsPage() {
247
  }
248
  };
249
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
250
  const handleSessionDump = async (phone: string) => {
251
  setActionLoading(phone + '_dump');
252
  try {
@@ -353,6 +373,13 @@ export default function AccountsPage() {
353
  {acc.status}
354
  </span>
355
  <div className="flex gap-2">
 
 
 
 
 
 
 
356
  <button
357
  onClick={() => handleValidateSession(acc.phone_number)}
358
  className="p-1.5 bg-foreground/5 hover:bg-emerald-500/10 hover:text-emerald-500 rounded-lg text-foreground/30 transition-all"
@@ -379,12 +406,15 @@ export default function AccountsPage() {
379
 
380
  {/* Profile Image and Identity */}
381
  <div className="flex flex-col items-center mb-6">
382
- <div className="w-20 h-20 rounded-full border-4 border-foreground/5 p-1 mb-3 bg-foreground/[0.02] relative shadow-inner">
383
  {acc.profile_photo ? (
384
  <img
385
- src={process.env.NEXT_PUBLIC_API_URL ? `${process.env.NEXT_PUBLIC_API_URL}${acc.profile_photo}` : `http://localhost:8000${acc.profile_photo}`}
386
  className="w-full h-full rounded-full object-cover"
387
- onError={(e) => { (e.target as any).src = 'https://abs.twimg.com/sticky/default_profile_images/default_profile_400x400.png' }}
 
 
 
388
  />
389
  ) : (
390
  <div className="w-full h-full rounded-full bg-indigo-500/10 flex items-center justify-center text-indigo-500">
 
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';
 
248
  }
249
  };
250
 
251
+ const handleSyncProfile = async (phone: string) => {
252
+ setActionLoading(phone + '_sync');
253
+ try {
254
+ const res = await apiFetch(`/api/telegram/accounts/${phone}/sync`, { method: 'POST' });
255
+ if (res.ok) {
256
+ setSuccessMsg(`Profile for ${phone} synchronized.`);
257
+ fetchAccounts();
258
+ setTimeout(() => setSuccessMsg(''), 5000);
259
+ } else {
260
+ const data = await res.json();
261
+ setError(data.detail || `Sync failed for ${phone}.`);
262
+ }
263
+ } catch (err) {
264
+ setError(`Sync failed for ${phone}.`);
265
+ } finally {
266
+ setActionLoading(null);
267
+ }
268
+ };
269
+
270
  const handleSessionDump = async (phone: string) => {
271
  setActionLoading(phone + '_dump');
272
  try {
 
373
  {acc.status}
374
  </span>
375
  <div className="flex gap-2">
376
+ <button
377
+ onClick={() => handleSyncProfile(acc.phone_number)}
378
+ className="p-1.5 bg-foreground/5 hover:bg-indigo-500/10 hover:text-indigo-500 rounded-lg text-foreground/30 transition-all"
379
+ title="Sync Profile"
380
+ >
381
+ {actionLoading === acc.phone_number + '_sync' ? <Loader2 size={14} className="animate-spin" /> : <CloudSync size={14} />}
382
+ </button>
383
  <button
384
  onClick={() => handleValidateSession(acc.phone_number)}
385
  className="p-1.5 bg-foreground/5 hover:bg-emerald-500/10 hover:text-emerald-500 rounded-lg text-foreground/30 transition-all"
 
406
 
407
  {/* Profile Image and Identity */}
408
  <div className="flex flex-col items-center mb-6">
409
+ <div className="w-20 h-20 rounded-full border-4 border-foreground/5 p-1 mb-3 bg-foreground/[0.02] relative shadow-inner overflow-hidden flex items-center justify-center">
410
  {acc.profile_photo ? (
411
  <img
412
+ src={acc.profile_photo.startsWith('http') ? acc.profile_photo : (process.env.NEXT_PUBLIC_API_URL ? `${process.env.NEXT_PUBLIC_API_URL}${acc.profile_photo}` : `http://localhost:8000${acc.profile_photo}`)}
413
  className="w-full h-full rounded-full object-cover"
414
+ onError={(e) => {
415
+ const target = e.target as any;
416
+ target.src = `https://ui-avatars.com/api/?name=${encodeURIComponent(acc.first_name || 'A')}&background=6366f1&color=fff`;
417
+ }}
418
  />
419
  ) : (
420
  <div className="w-full h-full rounded-full bg-indigo-500/10 flex items-center justify-center text-indigo-500">