saske560 commited on
Commit
1b5cc04
·
verified ·
1 Parent(s): dc2e8fc

Upload main.py

Browse files
Files changed (1) hide show
  1. main.py +332 -35
main.py CHANGED
@@ -158,7 +158,14 @@ VIDEO_EXTENSIONS = {
158
  PROGRESS_EDIT_EVERY = 5
159
  MAX_CPU_PERCENT = max(50, min(95, int(os.environ.get("MAX_CPU_PERCENT", "85"))))
160
  CPU_MONITOR_INTERVAL = max(0.5, float(os.environ.get("CPU_MONITOR_INTERVAL", "2.0")))
161
- COMPRESS_STALL_SECONDS = max(60, int(os.environ.get("COMPRESS_STALL_SECONDS", "180")))
 
 
 
 
 
 
 
162
  QUEUE_WATCHDOG_INTERVAL = max(2.0, float(os.environ.get("QUEUE_WATCHDOG_INTERVAL", "5.0")))
163
  CPU_LIMIT_HEADROOM_PERCENT = max(1, min(15, int(os.environ.get("CPU_LIMIT_HEADROOM_PERCENT", "4"))))
164
 
@@ -980,6 +987,14 @@ class Job:
980
  cpu_usage_pct: float = 0.0
981
  cpu_slots: int = 0
982
  cpu_slots_max: int = 0
 
 
 
 
 
 
 
 
983
 
984
  ACTIVE_JOBS: Dict[str, Job] = {}
985
 
@@ -1095,6 +1110,7 @@ async def _cleanup_job(job: Job):
1095
  await _terminate_process(job.process)
1096
  job.process = None
1097
  job.is_processing = False
 
1098
  for p in list(job.files):
1099
  try:
1100
  if p and os.path.exists(p):
@@ -1122,6 +1138,43 @@ def _is_job_processing(job_id: str) -> bool:
1122
  return True
1123
  return any(uq.get("processing") == job_id for uq in _user_queues.values())
1124
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1125
  # =====================
1126
  # UTILS
1127
  # =====================
@@ -1273,18 +1326,33 @@ async def _compress(in_f, out_f, uid, status_msg=None, job=None, title=""):
1273
  job.cpu_slots = current_cpu_slots
1274
  job.cpu_slots_max = max_parallel_slots
1275
  job.cpu_usage_pct = 0.0
 
 
 
1276
  _job_touch(job, stage="comprimiendo", progress=0)
1277
 
1278
  out_time_ms = 0
1279
- last_progress_at = time.time()
 
 
 
1280
  stderr_tail = deque(maxlen=80)
1281
- t0 = time.time()
1282
  ffmpeg_cpu_pct_total = 0.0
1283
  ffmpeg_cpu_pct_quota = 0.0
 
 
 
 
 
 
1284
 
1285
  async def _read_stdout():
1286
- nonlocal out_time_ms, last_progress_at
1287
  async for line in proc.stdout:
 
 
 
1288
  s = line.decode("utf-8", errors="replace").strip()
1289
  if "=" not in s:
1290
  continue
@@ -1295,21 +1363,32 @@ async def _compress(in_f, out_f, uid, status_msg=None, job=None, title=""):
1295
  if new_out_time_ms >= out_time_ms:
1296
  out_time_ms = new_out_time_ms
1297
  last_progress_at = time.time()
 
 
1298
  except Exception:
1299
  pass
1300
  elif k == "progress" and v == "end":
1301
  last_progress_at = time.time()
 
 
1302
  break
1303
 
1304
  async def _read_stderr():
 
1305
  while True:
1306
  line = await proc.stderr.readline()
1307
  if not line:
1308
  break
1309
- stderr_tail.append(line.decode("utf-8", errors="replace").strip())
 
 
 
 
 
 
1310
 
1311
  async def _cpu_guard():
1312
- nonlocal ffmpeg_cpu_pct_total, ffmpeg_cpu_pct_quota, current_cpu_slots, cpu_subset, active_jobs
1313
  if proc.pid is None:
1314
  return
1315
  try:
@@ -1350,6 +1429,7 @@ async def _compress(in_f, out_f, uid, status_msg=None, job=None, title=""):
1350
  job.cpu_usage_pct = ffmpeg_cpu_pct_total
1351
  job.cpu_slots = current_cpu_slots
1352
  job.cpu_slots_max = max_parallel_slots
 
1353
  _job_touch(job, stage="comprimiendo", progress=(job.progress_pct if job else None))
1354
  except Exception:
1355
  pass
@@ -1364,8 +1444,18 @@ async def _compress(in_f, out_f, uid, status_msg=None, job=None, title=""):
1364
  while not wt.done():
1365
  if job and job.cancelled:
1366
  raise asyncio.CancelledError()
1367
- if (time.time() - last_progress_at) > COMPRESS_STALL_SECONDS:
1368
- raise RuntimeError("La compresión quedó bloqueada sin progreso durante demasiado tiempo.")
 
 
 
 
 
 
 
 
 
 
1369
  await asyncio.sleep(PROGRESS_EDIT_EVERY)
1370
  ds = out_time_ms / 1_000_000 if out_time_ms else 0.0
1371
  p = (ds / dur) if dur > 0 else 0.0
@@ -1386,6 +1476,7 @@ async def _compress(in_f, out_f, uid, status_msg=None, job=None, title=""):
1386
  f"🧠 CPU: `{cpu_slots_txt} cores` | FFmpeg: `{ffmpeg_cpu_pct_total:.1f}%` host / `{ffmpeg_cpu_pct_quota:.1f}%` cuota\n"
1387
  f"🛡️ Tope(host): `{MAX_CPU_PERCENT}%` | Pool: `{max_parallel_slots}` | Jobs: `{active_jobs}`\n"
1388
  f"🧩 Cuota cgroup: `{quota_txt}` CPU | Capacidad: `{cpu_capacity:.2f}`\n"
 
1389
  f"⏳ ETA: `{_fmt_eta(eta)}`"
1390
  )
1391
  await wt
@@ -1398,7 +1489,7 @@ async def _compress(in_f, out_f, uid, status_msg=None, job=None, title=""):
1398
  finally:
1399
  cpu_guard_task.cancel()
1400
  for task in (rt_out, rt_err, cpu_guard_task):
1401
- with contextlib.suppress(Exception):
1402
  await task
1403
  await _unregister_active_ffmpeg(job_key)
1404
  if job:
@@ -1408,6 +1499,10 @@ async def _compress(in_f, out_f, uid, status_msg=None, job=None, title=""):
1408
 
1409
  if proc.returncode != 0:
1410
  err = "\n".join([x for x in stderr_tail if x][-8:]) or "FFmpeg terminó con error."
 
 
 
 
1411
  raise RuntimeError(err)
1412
  if not os.path.exists(out_f) or os.path.getsize(out_f) == 0:
1413
  raise RuntimeError("No se generó el archivo comprimido.")
@@ -1545,6 +1640,8 @@ async def _user_worker(queue_key: str):
1545
  # PROCESO PRINCIPAL
1546
  # =====================
1547
  async def _process(client, message: Message, status_msg: Message = None, job: Job = None):
 
 
1548
  editor = _Editor(status_msg, job_id=(job.job_id if job else None))
1549
  uid = message.from_user.id
1550
  cid = message.chat.id
@@ -1591,6 +1688,11 @@ async def _process(client, message: Message, status_msg: Message = None, job: Jo
1591
  job.is_processing = True
1592
  job.started_at = time.time()
1593
  job.last_activity_at = job.started_at
 
 
 
 
 
1594
 
1595
  try:
1596
  await _download(client, message, in_f, editor, job=job, title=fname)
@@ -1646,13 +1748,27 @@ async def _process(client, message: Message, status_msg: Message = None, job: Jo
1646
  "━━━━━━━━━━━━━━━━━━━━━\n"
1647
  "♠ ¡Que lo disfrutes! ♣"
1648
  )
 
1649
  if job:
 
 
 
 
 
 
1650
  _job_touch(job, stage='subiendo', progress=0)
1651
  await editor.set(
1652
  f"📤 **Subiendo video...**\n🎬 `{fname}`\nPor favor espera...",
1653
  force=True, keep_cancel=False
1654
  )
1655
  up_t = time.time()
 
 
 
 
 
 
 
1656
  async def _up_cb(cur, tot):
1657
  if job and job.cancelled:
1658
  raise asyncio.CancelledError()
@@ -1661,6 +1777,9 @@ async def _process(client, message: Message, status_msg: Message = None, job: Jo
1661
  p = cur / tot if tot else 0
1662
  eta = (tot - cur) / sp if sp > 0 and tot else None
1663
  if job:
 
 
 
1664
  _job_touch(job, stage="subiendo", progress=(p * 100.0))
1665
  await editor.set(
1666
  f"📤 **Subiendo...**\n{_bar(p)} `{p*100:5.1f}%`\n"
@@ -1669,15 +1788,27 @@ async def _process(client, message: Message, status_msg: Message = None, job: Jo
1669
  f"⏳ ETA: `{_fmt_eta(eta)}`",
1670
  keep_cancel=False,
1671
  )
1672
- await client.send_video(
1673
- message.chat.id, out_f,
1674
- caption=caption,
1675
- duration=video_dur,
1676
- thumb=thumb,
1677
- supports_streaming=True,
1678
- reply_to_message_id=message.id,
1679
- progress=_up_cb,
1680
- )
 
 
 
 
 
 
 
 
 
 
 
 
1681
  await editor.set(
1682
  "✅ **¡Video enviado correctamente!**\n"
1683
  "Comprueba el mensaje justo arriba 👆",
@@ -1686,13 +1817,26 @@ async def _process(client, message: Message, status_msg: Message = None, job: Jo
1686
  await increment_daily_usage(uid)
1687
  await log_stat(uid, orig_mb, comp_mb, elapsed)
1688
  except asyncio.CancelledError:
1689
- if job:
1690
- job.cancelled = True
 
 
 
 
 
 
 
 
1691
  try:
1692
- await editor.set("❌ **Proceso cancelado.**\nArchivos temporales eliminados.", force=True, keep_cancel=False)
 
 
 
 
 
1693
  except Exception:
1694
  pass
1695
- raise
1696
  except Exception as e:
1697
  logger.error("Error proceso: %s", e)
1698
  try:
@@ -1706,6 +1850,7 @@ async def _process(client, message: Message, status_msg: Message = None, job: Jo
1706
  pass
1707
  finally:
1708
  if job:
 
1709
  await _cleanup_job(job)
1710
  else:
1711
  for p in (in_f, out_f, thumb):
@@ -3590,11 +3735,16 @@ async def cmd_trabajos(client, msg: Message):
3590
 
3591
  lines = ["🧰 **Trabajos del bot**", "━━━━━━━━━━━━━━━━━━━━━"]
3592
  for idx, job in enumerate(sorted(active, key=lambda j: (j.is_processing, j.started_at or 0), reverse=True)[:20], 1):
3593
- state = "🟢 Activo" if job.is_processing else "🟡 En espera"
3594
- queue_label = _plan_queue_label(job.queue_name or "free") if job.queue_name else "🧵 Cola pendiente"
 
 
 
 
 
3595
  lines.append(
3596
  f"{idx}. {state} | `{job.user_id}` | `{job.fname or job.job_id}`\n"
3597
- f" • Etapa: `{job.stage or 'pendiente'}` | Cola: `{queue_label}`\n"
3598
  f" • Progreso: `{job.progress_pct:.1f}%` | CPU: `{job.cpu_usage_pct:.1f}%` | Slots: `{job.cpu_slots}/{job.cpu_slots_max}`\n"
3599
  f" • Última actividad: `{_fmt_eta(max(0, time.time() - (job.last_activity_at or time.time())))}` atrás | Tiempo: `{_job_elapsed(job)}`"
3600
  )
@@ -4179,6 +4329,7 @@ async def _queue_watchdog():
4179
  if _global_worker_task and _global_worker_task.done():
4180
  logger.warning("Watchdog: reiniciando worker global con %d elemento(s) pendientes.", len(_global_queue_list))
4181
  await _ensure_global_worker()
 
4182
 
4183
  for queue_key, uq in list(_user_queues.items()):
4184
  processing_id = uq.get("processing")
@@ -4190,23 +4341,165 @@ async def _queue_watchdog():
4190
  if worker and worker.done():
4191
  logger.warning("Watchdog: reiniciando worker %s con %d elemento(s) pendientes.", queue_key, len(uq["list"]))
4192
  await _ensure_user_worker(queue_key)
 
4193
 
4194
  now = time.time()
 
4195
  for job in list(ACTIVE_JOBS.values()):
4196
- if not job.is_processing or job.cancelled:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4197
  continue
4198
- if job.process and job.process.returncode is None:
4199
- idle_for = now - (job.last_activity_at or now)
4200
- if idle_for > (COMPRESS_STALL_SECONDS + 30):
4201
- logger.warning("Watchdog: trabajo %s cancelado por inactividad (%ss).", job.job_id, int(idle_for))
4202
- job.cancelled = True
4203
- await _terminate_process(job.process)
4204
- elif job.stage == "comprimiendo" and (now - (job.last_activity_at or now)) > (COMPRESS_STALL_SECONDS + 30):
4205
- logger.warning("Watchdog: trabajo %s quedó sin proceso activo en compresión; se marca cancelado.", job.job_id)
4206
- job.cancelled = True
 
 
 
 
 
 
 
 
 
 
 
4207
  except Exception as e:
4208
  logger.error("Queue watchdog error: %s", e)
4209
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4210
  # ========================
4211
  # COMANDOS DE MENÚ
4212
  # ========================
@@ -4222,6 +4515,8 @@ USER_COMMANDS = [
4222
  ("cancelar", "❌ Cancelar tu compresión activa"),
4223
  ("reporte", "📝 Reportar un problema"),
4224
  ("ping", "🏓 Verificar si el bot responde"),
 
 
4225
  ("velocidad", "⚡ Test de velocidad del servidor"),
4226
  ("id", "🆔 Ver tu ID"),
4227
  ("about", "ℹ️ Información del bot"),
@@ -4268,6 +4563,7 @@ SUPERADMIN_COMMANDS = ADMIN_COMMANDS + [
4268
  ("importdb", "📥 Importar backup DB"),
4269
  ("logs", "📡 Configurar canal de logs"),
4270
  ("forzarwatchdog", "🛠️ Reparar workers/colas atascadas"),
 
4271
  ("actualizarmenu", "🔄 Actualizar menú de comandos"),
4272
  ]
4273
 
@@ -4342,6 +4638,7 @@ async def start_bot():
4342
  f"🔒 Modo: {BOT_MODE} | 🎬 Log videos: {LOG_VIDEOS}\n"
4343
  f"🧵 Colas por plan: {INDIVIDUAL_QUEUES_ENABLED}"
4344
  )
 
4345
  asyncio.create_task(_plan_expiry_checker())
4346
  asyncio.create_task(_queue_watchdog())
4347
  asyncio.create_task(_set_menus())
 
158
  PROGRESS_EDIT_EVERY = 5
159
  MAX_CPU_PERCENT = max(50, min(95, int(os.environ.get("MAX_CPU_PERCENT", "85"))))
160
  CPU_MONITOR_INTERVAL = max(0.5, float(os.environ.get("CPU_MONITOR_INTERVAL", "2.0")))
161
+ COMPRESS_STALL_SECONDS = max(120, int(os.environ.get("COMPRESS_STALL_SECONDS", "420")))
162
+ COMPRESS_START_GRACE_SECONDS = max(60, int(os.environ.get("COMPRESS_START_GRACE_SECONDS", "120")))
163
+ FFMPEG_OUTPUT_IDLE_SECONDS = max(45, int(os.environ.get("FFMPEG_OUTPUT_IDLE_SECONDS", "120")))
164
+ STALL_CPU_FLOOR_PERCENT = max(0.5, float(os.environ.get("STALL_CPU_FLOOR_PERCENT", "2.0")))
165
+ UPLOAD_STALL_SECONDS = max(300, int(os.environ.get("UPLOAD_STALL_SECONDS", "1800")))
166
+ UPLOAD_HEARTBEAT_EVERY = max(5.0, float(os.environ.get("UPLOAD_HEARTBEAT_EVERY", "15.0")))
167
+ UPLOAD_HARD_TIMEOUT_SECONDS = max(900, int(os.environ.get("UPLOAD_HARD_TIMEOUT_SECONDS", "7200")))
168
+ FINALIZE_GRACE_SECONDS = max(120, int(os.environ.get("FINALIZE_GRACE_SECONDS", "900")))
169
  QUEUE_WATCHDOG_INTERVAL = max(2.0, float(os.environ.get("QUEUE_WATCHDOG_INTERVAL", "5.0")))
170
  CPU_LIMIT_HEADROOM_PERCENT = max(1, min(15, int(os.environ.get("CPU_LIMIT_HEADROOM_PERCENT", "4"))))
171
 
 
987
  cpu_usage_pct: float = 0.0
988
  cpu_slots: int = 0
989
  cpu_slots_max: int = 0
990
+ ffmpeg_last_progress_at: float = 0.0
991
+ ffmpeg_last_output_at: float = 0.0
992
+ ffmpeg_last_stderr: str = ""
993
+ upload_started_at: float = 0.0
994
+ upload_last_progress_at: float = 0.0
995
+ upload_completed_at: float = 0.0
996
+ upload_last_bytes: int = 0
997
+ upload_total_bytes: int = 0
998
 
999
  ACTIVE_JOBS: Dict[str, Job] = {}
1000
 
 
1110
  await _terminate_process(job.process)
1111
  job.process = None
1112
  job.is_processing = False
1113
+ job.task = None
1114
  for p in list(job.files):
1115
  try:
1116
  if p and os.path.exists(p):
 
1138
  return True
1139
  return any(uq.get("processing") == job_id for uq in _user_queues.values())
1140
 
1141
+
1142
+ def _job_queue_position(job_id: str) -> Optional[tuple[str, int, int]]:
1143
+ if _global_currently_processing == job_id:
1144
+ return ("free", 0, max(1, len(_global_queue_list) + 1))
1145
+ for i, item in enumerate(_global_queue_list, 1):
1146
+ if item[3] == job_id:
1147
+ return ("free", i, len(_global_queue_list))
1148
+ for queue_key, uq in _user_queues.items():
1149
+ if uq.get("processing") == job_id:
1150
+ total = len(uq.get("list", [])) + 1
1151
+ return (queue_key, 0, max(1, total))
1152
+ for i, item in enumerate(uq.get("list", []), 1):
1153
+ if item[3] == job_id:
1154
+ total = len(uq.get("list", [])) + (1 if uq.get("processing") else 0)
1155
+ return (queue_key, i, max(1, total))
1156
+ return None
1157
+
1158
+
1159
+ async def _edit_job_status(job: Job, text: str, *, remove_markup: bool = True):
1160
+ try:
1161
+ await bot.edit_message_text(
1162
+ chat_id=job.chat_id,
1163
+ message_id=job.status_msg_id,
1164
+ text=text,
1165
+ reply_markup=None if remove_markup else _cancel_markup(job.job_id),
1166
+ )
1167
+ except Exception:
1168
+ pass
1169
+
1170
+
1171
+ async def _force_finish_job(job: Job, reason: str, *, notify_user: bool = True):
1172
+ job.cancelled = True
1173
+ job.is_processing = False
1174
+ if notify_user:
1175
+ await _edit_job_status(job, reason, remove_markup=True)
1176
+ await _cleanup_job(job)
1177
+
1178
  # =====================
1179
  # UTILS
1180
  # =====================
 
1326
  job.cpu_slots = current_cpu_slots
1327
  job.cpu_slots_max = max_parallel_slots
1328
  job.cpu_usage_pct = 0.0
1329
+ job.ffmpeg_last_progress_at = time.time()
1330
+ job.ffmpeg_last_output_at = time.time()
1331
+ job.ffmpeg_last_stderr = ""
1332
  _job_touch(job, stage="comprimiendo", progress=0)
1333
 
1334
  out_time_ms = 0
1335
+ now0 = time.time()
1336
+ last_progress_at = now0
1337
+ last_output_at = now0
1338
+ last_stderr_at = now0
1339
  stderr_tail = deque(maxlen=80)
1340
+ t0 = now0
1341
  ffmpeg_cpu_pct_total = 0.0
1342
  ffmpeg_cpu_pct_quota = 0.0
1343
+ proc_cpu_raw = 0.0
1344
+ input_size_mb = 0.0
1345
+ with contextlib.suppress(Exception):
1346
+ input_size_mb = max(0.0, os.path.getsize(in_f) / (1024 * 1024))
1347
+ dynamic_start_grace = max(COMPRESS_START_GRACE_SECONDS, min(300, int(input_size_mb * 0.35) + int(dur * 0.02 if dur else 0)))
1348
+ dynamic_stall_limit = max(COMPRESS_STALL_SECONDS, min(1200, int(dur * 0.12) if dur else 0))
1349
 
1350
  async def _read_stdout():
1351
+ nonlocal out_time_ms, last_progress_at, last_output_at
1352
  async for line in proc.stdout:
1353
+ last_output_at = time.time()
1354
+ if job:
1355
+ job.ffmpeg_last_output_at = last_output_at
1356
  s = line.decode("utf-8", errors="replace").strip()
1357
  if "=" not in s:
1358
  continue
 
1363
  if new_out_time_ms >= out_time_ms:
1364
  out_time_ms = new_out_time_ms
1365
  last_progress_at = time.time()
1366
+ if job:
1367
+ job.ffmpeg_last_progress_at = last_progress_at
1368
  except Exception:
1369
  pass
1370
  elif k == "progress" and v == "end":
1371
  last_progress_at = time.time()
1372
+ if job:
1373
+ job.ffmpeg_last_progress_at = last_progress_at
1374
  break
1375
 
1376
  async def _read_stderr():
1377
+ nonlocal last_output_at, last_stderr_at
1378
  while True:
1379
  line = await proc.stderr.readline()
1380
  if not line:
1381
  break
1382
+ last_output_at = time.time()
1383
+ last_stderr_at = last_output_at
1384
+ decoded = line.decode("utf-8", errors="replace").strip()
1385
+ stderr_tail.append(decoded)
1386
+ if job:
1387
+ job.ffmpeg_last_output_at = last_output_at
1388
+ job.ffmpeg_last_stderr = decoded[:300]
1389
 
1390
  async def _cpu_guard():
1391
+ nonlocal ffmpeg_cpu_pct_total, ffmpeg_cpu_pct_quota, current_cpu_slots, cpu_subset, active_jobs, proc_cpu_raw
1392
  if proc.pid is None:
1393
  return
1394
  try:
 
1429
  job.cpu_usage_pct = ffmpeg_cpu_pct_total
1430
  job.cpu_slots = current_cpu_slots
1431
  job.cpu_slots_max = max_parallel_slots
1432
+ job.ffmpeg_last_output_at = max(job.ffmpeg_last_output_at or 0.0, last_output_at)
1433
  _job_touch(job, stage="comprimiendo", progress=(job.progress_pct if job else None))
1434
  except Exception:
1435
  pass
 
1444
  while not wt.done():
1445
  if job and job.cancelled:
1446
  raise asyncio.CancelledError()
1447
+ now = time.time()
1448
+ elapsed = now - t0
1449
+ progress_idle = now - last_progress_at
1450
+ output_idle = now - max(last_output_at, last_stderr_at, last_progress_at)
1451
+ no_progress_yet = out_time_ms <= 0
1452
+ cpu_looks_idle = proc_cpu_raw < STALL_CPU_FLOOR_PERCENT
1453
+ if no_progress_yet:
1454
+ if elapsed > dynamic_start_grace and output_idle > FFMPEG_OUTPUT_IDLE_SECONDS and cpu_looks_idle:
1455
+ raise RuntimeError("FFmpeg no arrancó bien la compresión y quedó sin actividad.")
1456
+ else:
1457
+ if progress_idle > dynamic_stall_limit and output_idle > FFMPEG_OUTPUT_IDLE_SECONDS and cpu_looks_idle:
1458
+ raise RuntimeError("La compresión quedó atascada sin avance real durante demasiado tiempo.")
1459
  await asyncio.sleep(PROGRESS_EDIT_EVERY)
1460
  ds = out_time_ms / 1_000_000 if out_time_ms else 0.0
1461
  p = (ds / dur) if dur > 0 else 0.0
 
1476
  f"🧠 CPU: `{cpu_slots_txt} cores` | FFmpeg: `{ffmpeg_cpu_pct_total:.1f}%` host / `{ffmpeg_cpu_pct_quota:.1f}%` cuota\n"
1477
  f"🛡️ Tope(host): `{MAX_CPU_PERCENT}%` | Pool: `{max_parallel_slots}` | Jobs: `{active_jobs}`\n"
1478
  f"🧩 Cuota cgroup: `{quota_txt}` CPU | Capacidad: `{cpu_capacity:.2f}`\n"
1479
+ f"🧯 Stall: `{int(progress_idle)}s/{dynamic_stall_limit}s` | Salida: `{int(output_idle)}s/{FFMPEG_OUTPUT_IDLE_SECONDS}s`\n"
1480
  f"⏳ ETA: `{_fmt_eta(eta)}`"
1481
  )
1482
  await wt
 
1489
  finally:
1490
  cpu_guard_task.cancel()
1491
  for task in (rt_out, rt_err, cpu_guard_task):
1492
+ with contextlib.suppress(asyncio.CancelledError, Exception):
1493
  await task
1494
  await _unregister_active_ffmpeg(job_key)
1495
  if job:
 
1499
 
1500
  if proc.returncode != 0:
1501
  err = "\n".join([x for x in stderr_tail if x][-8:]) or "FFmpeg terminó con error."
1502
+ if proc.returncode in (-9, 137):
1503
+ err = "El proceso de compresión fue terminado por el sistema (memoria/recursos insuficientes)."
1504
+ elif proc.returncode in (-15, 143) and not (job and job.cancelled):
1505
+ err = "La compresión fue detenida antes de terminar. Revisa watchdog, reinicios del hosting o falta de recursos."
1506
  raise RuntimeError(err)
1507
  if not os.path.exists(out_f) or os.path.getsize(out_f) == 0:
1508
  raise RuntimeError("No se generó el archivo comprimido.")
 
1640
  # PROCESO PRINCIPAL
1641
  # =====================
1642
  async def _process(client, message: Message, status_msg: Message = None, job: Job = None):
1643
+ if job:
1644
+ job.task = asyncio.current_task()
1645
  editor = _Editor(status_msg, job_id=(job.job_id if job else None))
1646
  uid = message.from_user.id
1647
  cid = message.chat.id
 
1688
  job.is_processing = True
1689
  job.started_at = time.time()
1690
  job.last_activity_at = job.started_at
1691
+ job.upload_started_at = 0.0
1692
+ job.upload_last_progress_at = 0.0
1693
+ job.upload_completed_at = 0.0
1694
+ job.upload_last_bytes = 0
1695
+ job.upload_total_bytes = 0
1696
 
1697
  try:
1698
  await _download(client, message, in_f, editor, job=job, title=fname)
 
1748
  "━━━━━━━━━━━━━━━━━━━━━\n"
1749
  "♠ ¡Que lo disfrutes! ♣"
1750
  )
1751
+ upload_heartbeat_task = None
1752
  if job:
1753
+ now_upload = time.time()
1754
+ job.upload_started_at = now_upload
1755
+ job.upload_last_progress_at = now_upload
1756
+ job.upload_completed_at = 0.0
1757
+ job.upload_last_bytes = 0
1758
+ job.upload_total_bytes = 0
1759
  _job_touch(job, stage='subiendo', progress=0)
1760
  await editor.set(
1761
  f"📤 **Subiendo video...**\n🎬 `{fname}`\nPor favor espera...",
1762
  force=True, keep_cancel=False
1763
  )
1764
  up_t = time.time()
1765
+
1766
+ async def _upload_heartbeat():
1767
+ while True:
1768
+ await asyncio.sleep(UPLOAD_HEARTBEAT_EVERY)
1769
+ if job and not job.cancelled and job.stage in {"subiendo", "finalizando"}:
1770
+ _job_touch(job, stage=job.stage, progress=job.progress_pct)
1771
+
1772
  async def _up_cb(cur, tot):
1773
  if job and job.cancelled:
1774
  raise asyncio.CancelledError()
 
1777
  p = cur / tot if tot else 0
1778
  eta = (tot - cur) / sp if sp > 0 and tot else None
1779
  if job:
1780
+ job.upload_last_progress_at = time.time()
1781
+ job.upload_last_bytes = int(cur or 0)
1782
+ job.upload_total_bytes = int(tot or 0)
1783
  _job_touch(job, stage="subiendo", progress=(p * 100.0))
1784
  await editor.set(
1785
  f"📤 **Subiendo...**\n{_bar(p)} `{p*100:5.1f}%`\n"
 
1788
  f"⏳ ETA: `{_fmt_eta(eta)}`",
1789
  keep_cancel=False,
1790
  )
1791
+
1792
+ upload_heartbeat_task = asyncio.create_task(_upload_heartbeat())
1793
+ try:
1794
+ await client.send_video(
1795
+ message.chat.id, out_f,
1796
+ caption=caption,
1797
+ duration=video_dur,
1798
+ thumb=thumb,
1799
+ supports_streaming=True,
1800
+ reply_to_message_id=message.id,
1801
+ progress=_up_cb,
1802
+ )
1803
+ finally:
1804
+ if upload_heartbeat_task:
1805
+ upload_heartbeat_task.cancel()
1806
+ with contextlib.suppress(asyncio.CancelledError, Exception):
1807
+ await upload_heartbeat_task
1808
+
1809
+ if job:
1810
+ job.upload_completed_at = time.time()
1811
+ _job_touch(job, stage='finalizando', progress=100.0)
1812
  await editor.set(
1813
  "✅ **¡Video enviado correctamente!**\n"
1814
  "Comprueba el mensaje justo arriba 👆",
 
1817
  await increment_daily_usage(uid)
1818
  await log_stat(uid, orig_mb, comp_mb, elapsed)
1819
  except asyncio.CancelledError:
1820
+ explicit_cancel = bool(job and job.cancelled)
1821
+ if explicit_cancel:
1822
+ try:
1823
+ if job and ACTIVE_JOBS.get(job.job_id) is job:
1824
+ await editor.set("❌ **Proceso cancelado.**\nArchivos temporales eliminados.", force=True, keep_cancel=False)
1825
+ except Exception:
1826
+ pass
1827
+ raise
1828
+
1829
+ logger.warning("Cancelación inesperada de tarea en etapa final: job=%s stage=%s", getattr(job, "job_id", "?"), getattr(job, "stage", "?"))
1830
  try:
1831
+ await editor.set(
1832
+ "⭕ **La subida final se interrumpió inesperadamente.**\n\n"
1833
+ "La compresión sí terminó, pero Telegram o el worker cortaron el envío al final.\n"
1834
+ "Vuelve a probar el video.",
1835
+ force=True, keep_cancel=False
1836
+ )
1837
  except Exception:
1838
  pass
1839
+ return
1840
  except Exception as e:
1841
  logger.error("Error proceso: %s", e)
1842
  try:
 
1850
  pass
1851
  finally:
1852
  if job:
1853
+ job.task = None
1854
  await _cleanup_job(job)
1855
  else:
1856
  for p in (in_f, out_f, thumb):
 
3735
 
3736
  lines = ["🧰 **Trabajos del bot**", "━━━━━━━━━━━━━━━━━━━━━"]
3737
  for idx, job in enumerate(sorted(active, key=lambda j: (j.is_processing, j.started_at or 0), reverse=True)[:20], 1):
3738
+ qpos = _job_queue_position(job.job_id)
3739
+ really_processing = bool(job.is_processing and (job.process and job.process.returncode is None or qpos and qpos[1] == 0 or job.task))
3740
+ state = "🟢 Activo" if really_processing else "🟡 En espera"
3741
+ queue_label = _plan_queue_label((qpos[0] if qpos else job.queue_name) or "free") if (qpos or job.queue_name) else "🧵 Cola pendiente"
3742
+ extra_queue = ""
3743
+ if qpos and qpos[1] > 0:
3744
+ extra_queue = f" | Pos: `#{qpos[1]}/{qpos[2]}`"
3745
  lines.append(
3746
  f"{idx}. {state} | `{job.user_id}` | `{job.fname or job.job_id}`\n"
3747
+ f" • Etapa: `{job.stage or 'pendiente'}` | Cola: `{queue_label}`{extra_queue}\n"
3748
  f" • Progreso: `{job.progress_pct:.1f}%` | CPU: `{job.cpu_usage_pct:.1f}%` | Slots: `{job.cpu_slots}/{job.cpu_slots_max}`\n"
3749
  f" • Última actividad: `{_fmt_eta(max(0, time.time() - (job.last_activity_at or time.time())))}` atrás | Tiempo: `{_job_elapsed(job)}`"
3750
  )
 
4329
  if _global_worker_task and _global_worker_task.done():
4330
  logger.warning("Watchdog: reiniciando worker global con %d elemento(s) pendientes.", len(_global_queue_list))
4331
  await _ensure_global_worker()
4332
+ _global_queue_event.set()
4333
 
4334
  for queue_key, uq in list(_user_queues.items()):
4335
  processing_id = uq.get("processing")
 
4341
  if worker and worker.done():
4342
  logger.warning("Watchdog: reiniciando worker %s con %d elemento(s) pendientes.", queue_key, len(uq["list"]))
4343
  await _ensure_user_worker(queue_key)
4344
+ uq["event"].set()
4345
 
4346
  now = time.time()
4347
+ stale_limit = COMPRESS_STALL_SECONDS + 30
4348
  for job in list(ACTIVE_JOBS.values()):
4349
+ if job.cancelled:
4350
+ await _force_finish_job(job, "❌ **Trabajo cancelado por watchdog.**")
4351
+ continue
4352
+
4353
+ idle_for = now - (job.last_activity_at or now)
4354
+ queue_pos = _job_queue_position(job.job_id)
4355
+ task_done = bool(job.task and job.task.done())
4356
+ proc_running = bool(job.process and job.process.returncode is None)
4357
+
4358
+ if queue_pos is None and not proc_running and not job.is_processing:
4359
+ logger.warning("Watchdog: limpiando trabajo huérfano %s fuera de cola.", job.job_id)
4360
+ await _force_finish_job(job, "❌ **Trabajo eliminado por limpieza automática.**")
4361
+ continue
4362
+
4363
+ if queue_pos is not None and queue_pos[1] > 0:
4364
+ job.is_processing = False
4365
+ job.queue_name = queue_pos[0]
4366
+ continue
4367
+
4368
+ if proc_running:
4369
+ ffmpeg_progress_at = job.ffmpeg_last_progress_at or job.last_activity_at or now
4370
+ ffmpeg_output_at = job.ffmpeg_last_output_at or ffmpeg_progress_at
4371
+ progress_idle = now - ffmpeg_progress_at
4372
+ output_idle = now - ffmpeg_output_at
4373
+ cpu_busy = (job.cpu_usage_pct or 0.0) >= STALL_CPU_FLOOR_PERCENT
4374
+ watchdog_hard_limit = max(stale_limit, COMPRESS_STALL_SECONDS + FFMPEG_OUTPUT_IDLE_SECONDS + 120)
4375
+ if progress_idle > watchdog_hard_limit and output_idle > FFMPEG_OUTPUT_IDLE_SECONDS and not cpu_busy:
4376
+ logger.warning("Watchdog: trabajo %s cancelado por inactividad real (progress=%ss output=%ss).", job.job_id, int(progress_idle), int(output_idle))
4377
+ reason = "❌ **Trabajo cancelado por inactividad real.**\n\nFFmpeg dejó de dar progreso y salida durante demasiado tiempo.\nReenvía el video para intentarlo otra vez."
4378
+ if job.ffmpeg_last_stderr:
4379
+ reason += f"\n\nÚltimo mensaje FFmpeg:\n`{job.ffmpeg_last_stderr[:160]}`"
4380
+ await _force_finish_job(job, reason)
4381
+ continue
4382
+
4383
+ if job.is_processing and job.stage in {"subiendo", "finalizando"}:
4384
+ upload_ref = job.upload_last_progress_at or job.upload_started_at or job.last_activity_at or now
4385
+ upload_idle = now - upload_ref
4386
+ upload_elapsed = now - (job.upload_started_at or job.started_at or now)
4387
+ if job.stage == "subiendo":
4388
+ if upload_idle > UPLOAD_STALL_SECONDS and upload_elapsed > UPLOAD_STALL_SECONDS:
4389
+ logger.warning("Watchdog: subida atascada para %s (idle=%ss elapsed=%ss bytes=%s/%s).", job.job_id, int(upload_idle), int(upload_elapsed), job.upload_last_bytes, job.upload_total_bytes)
4390
+ if job.task and not task_done:
4391
+ with contextlib.suppress(Exception):
4392
+ job.cancelled = True
4393
+ job.task.cancel()
4394
+ await _force_finish_job(
4395
+ job,
4396
+ "❌ **La subida a Telegram quedó atascada.**\n\nLa compresión terminó, pero el envío final no avanzó durante demasiado tiempo.\nPuedes reenviar el video.",
4397
+ )
4398
+ if _global_currently_processing == job.job_id:
4399
+ _global_currently_processing = None
4400
+ for uq in _user_queues.values():
4401
+ if uq.get("processing") == job.job_id:
4402
+ uq["processing"] = None
4403
+ continue
4404
+ finalize_idle = now - (job.upload_completed_at or job.last_activity_at or now)
4405
+ if finalize_idle > FINALIZE_GRACE_SECONDS:
4406
+ logger.warning("Watchdog: finalización atascada para %s tras enviar video (%ss).", job.job_id, int(finalize_idle))
4407
+ await _force_finish_job(
4408
+ job,
4409
+ "✅ **Video enviado, pero el cierre del trabajo quedó atascado.**\n\nSi ya recibiste el video, puedes ignorar este aviso.",
4410
+ )
4411
  continue
4412
+
4413
+ if job.is_processing and idle_for > stale_limit:
4414
+ logger.warning("Watchdog: trabajo %s atascado en etapa %s sin proceso activo.", job.job_id, job.stage or "desconocida")
4415
+ if job.task and not task_done:
4416
+ with contextlib.suppress(Exception):
4417
+ job.cancelled = True
4418
+ job.task.cancel()
4419
+ await _force_finish_job(
4420
+ job,
4421
+ "❌ **Trabajo atascado y limpiado automáticamente.**\n\nLa cola quedó liberada. Puedes reenviar el video.",
4422
+ )
4423
+ if _global_currently_processing == job.job_id:
4424
+ _global_currently_processing = None
4425
+ for uq in _user_queues.values():
4426
+ if uq.get("processing") == job.job_id:
4427
+ uq["processing"] = None
4428
+
4429
+ if task_done and not proc_running and idle_for > 10:
4430
+ logger.warning("Watchdog: limpiando trabajo %s con task finalizada pero aún registrado.", job.job_id)
4431
+ await _force_finish_job(job, "❌ **Trabajo finalizado con estado inconsistente y fue limpiado.**")
4432
  except Exception as e:
4433
  logger.error("Queue watchdog error: %s", e)
4434
 
4435
+ @bot.on_message(filters.command("version") & (filters.private | filters.group))
4436
+ async def cmd_version(client, msg: Message):
4437
+ await msg.reply_text(
4438
+ f"🧾 **Versión del bot**\n\n"
4439
+ f"🤖 {BOT_VERSION}\n"
4440
+ f"🔒 Modo: `{'Público' if BOT_MODE == 'public' else 'Privado'}`\n"
4441
+ f"🧵 Colas por plan: `{'ON' if INDIVIDUAL_QUEUES_ENABLED else 'OFF'}`\n"
4442
+ f"🛡️ Tope CPU host: `{MAX_CPU_PERCENT}%`\n"
4443
+ f"🧯 Stall watchdog: `{COMPRESS_STALL_SECONDS}s`"
4444
+ )
4445
+
4446
+
4447
+ @bot.on_message(filters.command("misjobs") & (filters.private | filters.group))
4448
+ async def cmd_misjobs(client, msg: Message):
4449
+ uid = msg.from_user.id
4450
+ jobs = [job for job in ACTIVE_JOBS.values() if job.user_id == uid and not job.cancelled]
4451
+ if not jobs:
4452
+ await msg.reply_text("📭 **No tienes trabajos activos ni en cola.**")
4453
+ return
4454
+
4455
+ lines = ["🎞️ **Tus trabajos**", "━━━━━━━━━━━━━━━━━━━━━"]
4456
+ for idx, job in enumerate(sorted(jobs, key=lambda j: j.started_at or 0, reverse=True)[:15], 1):
4457
+ qpos = _job_queue_position(job.job_id)
4458
+ queue_label = _plan_queue_label((qpos[0] if qpos else job.queue_name) or "free")
4459
+ pos_txt = "procesando" if qpos and qpos[1] == 0 else (f"#{qpos[1]}/{qpos[2]}" if qpos else "—")
4460
+ lines.append(
4461
+ f"{idx}. `{job.fname or job.job_id}`\n"
4462
+ f" • Etapa: `{job.stage or 'pendiente'}`\n"
4463
+ f" • Cola: `{queue_label}` | Posición: `{pos_txt}`\n"
4464
+ f" • Progreso: `{job.progress_pct:.1f}%` | Tiempo: `{_job_elapsed(job)}`"
4465
+ )
4466
+ await _send_long(msg, "\n".join(lines))
4467
+
4468
+
4469
+ @bot.on_message(filters.command("limpiaratascos") & filters.private)
4470
+ async def cmd_limpiaratascos(client, msg: Message):
4471
+ global _global_currently_processing
4472
+ if not await is_super_admin(msg.from_user.id):
4473
+ await _no_access(msg)
4474
+ return
4475
+
4476
+ cleaned = []
4477
+ now = time.time()
4478
+ for job in list(ACTIVE_JOBS.values()):
4479
+ qpos = _job_queue_position(job.job_id)
4480
+ idle_for = now - (job.last_activity_at or now)
4481
+ proc_running = bool(job.process and job.process.returncode is None)
4482
+ if job.cancelled or (job.is_processing and not proc_running and idle_for > 30) or (qpos is None and idle_for > 30):
4483
+ cleaned.append(job.job_id)
4484
+ await _force_finish_job(job, "❌ **Trabajo limpiado manualmente por administración.**")
4485
+ if _global_currently_processing == job.job_id:
4486
+ _global_currently_processing = None
4487
+ for uq in _user_queues.values():
4488
+ if uq.get("processing") == job.job_id:
4489
+ uq["processing"] = None
4490
+
4491
+ if _global_queue_list:
4492
+ _global_queue_event.set()
4493
+ for uq in _user_queues.values():
4494
+ if uq.get("list"):
4495
+ uq["event"].set()
4496
+
4497
+ if not cleaned:
4498
+ await msg.reply_text("✅ **No encontré trabajos atascados para limpiar.**")
4499
+ return
4500
+ await msg.reply_text("✅ **Limpieza completada**\n\n" + "\n".join(f"• `{jid}`" for jid in cleaned[:30]))
4501
+
4502
+
4503
  # ========================
4504
  # COMANDOS DE MENÚ
4505
  # ========================
 
4515
  ("cancelar", "❌ Cancelar tu compresión activa"),
4516
  ("reporte", "📝 Reportar un problema"),
4517
  ("ping", "🏓 Verificar si el bot responde"),
4518
+ ("misjobs", "🎞️ Ver tus trabajos activos"),
4519
+ ("version", "🧾 Ver versión y modo del bot"),
4520
  ("velocidad", "⚡ Test de velocidad del servidor"),
4521
  ("id", "🆔 Ver tu ID"),
4522
  ("about", "ℹ️ Información del bot"),
 
4563
  ("importdb", "📥 Importar backup DB"),
4564
  ("logs", "📡 Configurar canal de logs"),
4565
  ("forzarwatchdog", "🛠️ Reparar workers/colas atascadas"),
4566
+ ("limpiaratascos", "🧹 Limpiar trabajos colgados"),
4567
  ("actualizarmenu", "🔄 Actualizar menú de comandos"),
4568
  ]
4569
 
 
4638
  f"🔒 Modo: {BOT_MODE} | 🎬 Log videos: {LOG_VIDEOS}\n"
4639
  f"🧵 Colas por plan: {INDIVIDUAL_QUEUES_ENABLED}"
4640
  )
4641
+ await _ensure_global_worker()
4642
  asyncio.create_task(_plan_expiry_checker())
4643
  asyncio.create_task(_queue_watchdog())
4644
  asyncio.create_task(_set_menus())