-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtg.py
More file actions
6418 lines (5551 loc) · 288 KB
/
tg.py
File metadata and controls
6418 lines (5551 loc) · 288 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import logging
import sys
import html
from collections import defaultdict
from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import Application, CommandHandler, MessageHandler, CallbackQueryHandler, ContextTypes, filters
import os
import subprocess
import asyncio
import re
import time
import threading
import signal
import http.server
import socketserver
import json
import concurrent.futures
import cgi
from typing import Union, Optional, Any, Dict, Callable, Awaitable
import requests
import jwt # New import for JWT
import datetime # New import for JWT expiry
import socket # Added: Import the socket module for socket.timeout
import base64 # For encoding preview images
import uuid # For generating unique session IDs
import shutil # For moving cached preview files
import mimetypes
import atexit
from urllib.parse import urlparse, parse_qs
from env_config import get_env
# Import the gh.py script
from gh import update_github_pages_with_video, delete_video_from_drive_and_github, get_commit_details
from production_benchmark import run_production_benchmark, BENCHMARKING_ENABLED, _save_json_and_csv
from recon_integration import update_recon_index_scores
# Import admin_auth.py for authentication and session management
from admin_auth import authenticate_admin, get_session_expiry_time, update_admin_credential_in_file, verify_password, ADMIN_CREDENTIALS, SESSION_TIMEOUT_ENABLED, SESSION_DURATION_DAYS
# --- Configuration ---
TELEGRAM_BOT_TOKEN = get_env("TELEGRAM_BOT_TOKEN")
TELEGRAM_BOT_API_BASE_URL = get_env("TELEGRAM_BOT_API_BASE_URL", "").strip()
TELEGRAM_BOT_API_BASE_FILE_URL = get_env("TELEGRAM_BOT_API_BASE_FILE_URL", "").strip()
TELEGRAM_BOT_API_LOCAL_MODE = get_env("TELEGRAM_BOT_API_LOCAL_MODE", "false").strip().lower() in {"1", "true", "yes", "on"}
USE_GITHUB_PAGES = True # Switch to enable/disable GitHub Pages integration (set to True to use gh.py)
PUBLIC_WEBSITE_URL = get_env("PUBLIC_WEBSITE_URL", "https://projectglyphmotion.github.io/")
OUTPUT_SUBDIRECTORY = "output"
INPUT_SUBDIRECTORY = "input"
WEB_SERVER_PORT = 5000 # Port for the local web server
TRACKING_SUBDIRECTORY = "tracking"
LEGACY_TRACKING_DATA_FILE = 'tracking_data.json'
TRACKING_DATA_FILE = os.path.join(TRACKING_SUBDIRECTORY, 'tracking_data.json')
UPTIME_DATA_FILE = os.path.join(TRACKING_SUBDIRECTORY, 'uptime_data.json')
TELEGRAM_CHAT_LOG_FILE = os.path.join(TRACKING_SUBDIRECTORY, 'telegram_chat_logs.jsonl')
UPTIME_MAX_EVENTS = 200000
UPTIME_HEARTBEAT_INTERVAL_SECONDS = 5
UPTIME_OFFLINE_INFER_MULTIPLIER = 2.5
UPTIME_EVENT_DEDUPE_TOLERANCE_SECONDS = 2.0
UPTIME_SHUTDOWN_BROADCAST_GRACE_SECONDS = 0.75
# Frame Restriction Configuration
FRAME_RESTRICTION_ENABLED = True # Set to True to enable frame count restriction
FRAME_RESTRICTION_VALUE = 20000 # Max allowed frames for video processing
FFPROBE_TIMEOUT_SECONDS = 10 # Timeout for ffprobe command in seconds
# JWT Secret Key (VERY IMPORTANT: Replace with a strong, random key in production!)
JWT_SECRET_KEY = get_env("JWT_SECRET_KEY", "")
# Master Admin Usernames (only these users can trigger global logout and other master actions)
# These users must also exist in ADMIN_CREDENTIALS in admin_auth.py
# FIX: Changed this to a set of individual strings for each master admin.
MASTER_ADMIN_USERNAMES = {"SHITIJ.dev", "sayann70"} # Add more usernames to this set if you have multiple master admins, e.g., {"ExampleAdmin1", "another_master_admin"}
MASTER_ADMIN_USER_IDS = {188357894, 1883578947, 915418821}
# --- AdSense Configuration (New) ---
# Global flag to enable/disable ads for all users (including non-admins)
_ADS_ENABLED_GLOBALLY = False # Default to False, can be changed by master admin
# Flag to determine if ads should be shown to admins when _ADS_ENABLED_GLOBALLY is True
_SHOW_ADS_TO_ADMINS = False # Default to False, can be changed by master admin
# File to persist ad settings
AD_SETTINGS_FILE = 'ad_settings.json'
# --- ROI Preview Configuration ---
# Directory to store temporary preview files
PREVIEW_SUBDIRECTORY = "preview_temp"
# Directory for chunked upload session files
CHUNK_UPLOAD_SUBDIRECTORY = "chunk_uploads"
# Time in seconds before an abandoned preview is cleaned up (5 minutes)
PREVIEW_CLEANUP_TIMEOUT_SECONDS = 300
# Interval for preview cleanup check (60 seconds)
PREVIEW_CLEANUP_INTERVAL_SECONDS = 60
# Ensure input and output directories exist
os.makedirs(OUTPUT_SUBDIRECTORY, exist_ok=True)
os.makedirs(INPUT_SUBDIRECTORY, exist_ok=True)
os.makedirs(PREVIEW_SUBDIRECTORY, exist_ok=True)
os.makedirs(CHUNK_UPLOAD_SUBDIRECTORY, exist_ok=True)
os.makedirs(TRACKING_SUBDIRECTORY, exist_ok=True)
# --- Logging ---
logging.basicConfig(format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO)
logger = logging.getLogger(__name__)
# Suppress polling/request spam while keeping bot interaction logs from this module visible.
logging.getLogger("httpx").setLevel(logging.WARNING)
logging.getLogger("telegram.ext.Application").setLevel(logging.WARNING)
logging.getLogger("telegram").setLevel(logging.WARNING)
# --- Global variable for web server status and tracking data ---
_current_processing_status: Union[str, None] = None # Start with None, so frontend hides initially
_status_lock = threading.Lock() # To protect _current_processing_status from race conditions
_tracking_data: list = [] # List to hold processed video tracking data
_tracking_data_lock = threading.RLock() # Re-entrant lock to avoid deadlocks in nested save paths
_uptime_data: dict = {}
_uptime_data_lock = threading.Lock()
_uptime_monitor_stop_event = threading.Event()
_uptime_monitor_thread: Optional[threading.Thread] = None
_admin_tracker_landing_sessions: Dict[str, float] = {}
_admin_tracker_landing_sessions_lock = threading.Lock()
_telegram_chat_log_lock = threading.Lock()
# List to keep track of invalidated JWTs (for immediate logout)
# In a real-world app, this would be a persistent store like a database or Redis.
_invalidated_tokens = set()
_token_invalidation_lock = threading.Lock()
def _record_admin_tracker_landing_once(session_id: str, admin_username: str, source_ip: str) -> bool:
"""Returns True only the first time a landing session ID is seen."""
clean_session = (session_id or '').strip()
if not clean_session:
return False
now = time.time()
cutoff = now - 86400
with _admin_tracker_landing_sessions_lock:
stale_keys = [k for k, ts in _admin_tracker_landing_sessions.items() if ts < cutoff]
for stale_key in stale_keys:
_admin_tracker_landing_sessions.pop(stale_key, None)
if clean_session in _admin_tracker_landing_sessions:
return False
_admin_tracker_landing_sessions[clean_session] = now
logger.info(f"Admin landed on tracker page: {admin_username} ({source_ip})")
return True
# --- Preview Session Management ---
# Stores preview sessions: {session_id: {'video_path': str, 'created_at': float, 'used': bool}}
_preview_sessions = {}
_preview_sessions_lock = threading.Lock()
_benchmark_lock = threading.Lock()
_benchmark_in_progress = False
_benchmarking_enabled_runtime = BENCHMARKING_ENABLED
_benchmarking_enabled_lock = threading.Lock()
_active_benchmark_task = None
_benchmark_progress: Dict[str, Any] = {
"runId": "",
"progressPct": 0,
"stage": "idle",
"detail": "",
"etaSeconds": None,
"updatedAt": 0,
}
_processing_job_lock = threading.Lock()
_active_processing_job: Dict[str, Any] = {
"jobId": "",
"future": None,
"startedAt": 0,
"cancelRequested": False,
"ownerClientId": "",
"ownerClientIp": "",
"ownerUsername": "",
"ownerIsAdmin": False,
"ownerSource": "",
}
_last_processing_cancellation_ts = 0.0
_telegram_network_error_last_logged_at = 0.0
_telegram_network_error_suppressed_count = 0
_processing_queue_lock = threading.Lock()
_processing_request_queue: list = []
_processing_queue_worker_running = False
_processing_duration_history_seconds: list[float] = []
_processing_duration_history_limit = 20
_active_async_processes_lock = threading.Lock()
_active_async_processes: Dict[int, Dict[str, Any]] = {}
# Deletion queue state: serialize delete operations to avoid concurrent GitHub/Drive mutation races.
_delete_queue_lock = threading.Lock()
_delete_request_queue: list = []
_delete_worker_running = False
def _enqueue_delete_request(job: Dict[str, Any]) -> int:
"""Appends a delete job and returns its 1-based queue position."""
with _delete_queue_lock:
_delete_request_queue.append(job)
# Include active in-flight worker job in position so queued status is intuitive.
in_flight = 1 if _delete_worker_running else 0
return len(_delete_request_queue) + in_flight
def _try_start_delete_worker() -> bool:
"""Marks delete worker as running if not already active."""
global _delete_worker_running
with _delete_queue_lock:
if _delete_worker_running:
return False
_delete_worker_running = True
return True
def _stop_delete_worker() -> None:
"""Marks delete worker as stopped."""
global _delete_worker_running
with _delete_queue_lock:
_delete_worker_running = False
def is_benchmarking_enabled() -> bool:
"""Returns current runtime benchmark enable state."""
with _benchmarking_enabled_lock:
return bool(_benchmarking_enabled_runtime)
def set_benchmarking_enabled(enabled: bool) -> bool:
"""Sets runtime benchmark enable state and returns updated value."""
global _benchmarking_enabled_runtime
with _benchmarking_enabled_lock:
_benchmarking_enabled_runtime = bool(enabled)
return _benchmarking_enabled_runtime
def _new_processing_job_id() -> str:
return str(uuid.uuid4())
def _new_benchmark_run_id() -> str:
return f"bench-{int(time.time() * 1000)}"
def _set_benchmark_progress(
*,
progress_pct: Optional[int] = None,
stage: Optional[str] = None,
detail: Optional[str] = None,
eta_seconds: Optional[int] = None,
run_id: Optional[str] = None,
) -> None:
with _benchmark_lock:
if run_id is not None:
_benchmark_progress["runId"] = run_id
if progress_pct is not None:
_benchmark_progress["progressPct"] = max(0, min(100, int(progress_pct)))
if stage is not None:
_benchmark_progress["stage"] = stage
if detail is not None:
_benchmark_progress["detail"] = detail
_benchmark_progress["etaSeconds"] = eta_seconds
_benchmark_progress["updatedAt"] = int(time.time())
def _reset_benchmark_progress() -> None:
with _benchmark_lock:
_benchmark_progress.update({
"runId": "",
"progressPct": 0,
"stage": "idle",
"detail": "",
"etaSeconds": None,
"updatedAt": int(time.time()),
})
def _set_active_benchmark_task(task) -> None:
global _active_benchmark_task
with _benchmark_lock:
_active_benchmark_task = task
def _clear_active_benchmark_task(task=None) -> None:
global _active_benchmark_task
with _benchmark_lock:
if task is None or _active_benchmark_task is task:
_active_benchmark_task = None
def _cancel_active_benchmark_task(main_loop: asyncio.AbstractEventLoop) -> bool:
with _benchmark_lock:
task = _active_benchmark_task
if not task or task.done():
return False
def _cancel():
try:
if task and not task.done():
task.cancel()
except Exception as cancel_error:
logger.warning(f"Failed to cancel active benchmark task: {cancel_error}")
main_loop.call_soon_threadsafe(_cancel)
return True
def _snapshot_active_processing_job() -> Dict[str, Any]:
with _processing_job_lock:
job_id = _active_processing_job.get("jobId") or ""
future = _active_processing_job.get("future")
started_at = int(_active_processing_job.get("startedAt") or 0)
cancel_requested = bool(_active_processing_job.get("cancelRequested"))
owner_client_id = (_active_processing_job.get("ownerClientId") or "").strip()
owner_client_ip = (_active_processing_job.get("ownerClientIp") or "").strip()
owner_username = (_active_processing_job.get("ownerUsername") or "").strip()
owner_is_admin = bool(_active_processing_job.get("ownerIsAdmin"))
owner_source = (_active_processing_job.get("ownerSource") or "").strip().lower()
is_active = bool(job_id and future and not future.done())
return {
"jobId": job_id if is_active else "",
"isActive": is_active,
"startedAt": started_at if is_active else 0,
"cancelRequested": cancel_requested if is_active else False,
"ownerClientId": owner_client_id if is_active else "",
"ownerClientIp": owner_client_ip if is_active else "",
"ownerUsername": owner_username if is_active else "",
"ownerIsAdmin": owner_is_admin if is_active else False,
"ownerSource": owner_source if is_active else "",
}
def _clear_active_processing_job_if_matches(job_id: str) -> None:
with _processing_job_lock:
if (_active_processing_job.get("jobId") or "") != job_id:
return
_active_processing_job.update({
"jobId": "",
"future": None,
"startedAt": 0,
"cancelRequested": False,
"ownerClientId": "",
"ownerClientIp": "",
"ownerUsername": "",
"ownerIsAdmin": False,
"ownerSource": "",
})
def _register_processing_future(
job_id: str,
future: concurrent.futures.Future,
owner_client_id: str = "",
owner_client_ip: str = "",
owner_username: str = "",
owner_is_admin: bool = False,
owner_source: str = "",
) -> None:
with _processing_job_lock:
_active_processing_job.update({
"jobId": job_id,
"future": future,
"startedAt": int(time.time()),
"cancelRequested": False,
"ownerClientId": (owner_client_id or "").strip(),
"ownerClientIp": (owner_client_ip or "").strip(),
"ownerUsername": (owner_username or "").strip(),
"ownerIsAdmin": bool(owner_is_admin),
"ownerSource": (owner_source or "").strip().lower(),
})
def _on_done(done_future: concurrent.futures.Future):
cancelled = done_future.cancelled()
_clear_active_processing_job_if_matches(job_id)
if cancelled:
set_processing_status("⛔ Processing cancelled. Server is ready for the next video.")
reset_status_after_delay(4)
future.add_done_callback(_on_done)
def _record_processing_duration(duration_seconds: float) -> None:
duration = float(duration_seconds or 0)
if duration <= 0:
return
with _processing_queue_lock:
_processing_duration_history_seconds.append(duration)
if len(_processing_duration_history_seconds) > _processing_duration_history_limit:
del _processing_duration_history_seconds[:-_processing_duration_history_limit]
def _average_processing_duration_seconds() -> int:
with _processing_queue_lock:
values = list(_processing_duration_history_seconds)
if not values:
return 420
return max(30, int(sum(values) / len(values)))
def _snapshot_processing_queue(requester_client_id: str = "", requester_client_ip: str = "") -> Dict[str, Any]:
active_job = _snapshot_active_processing_job()
requester_id = (requester_client_id or "").strip()
requester_ip = (requester_client_ip or "").strip()
with _processing_queue_lock:
queue_copy = [
{
"requestId": item.get("requestId", ""),
"ownerClientId": item.get("ownerClientId", ""),
"ownerClientIp": item.get("ownerClientIp", ""),
"ownerUsername": item.get("ownerUsername", ""),
"queuedAt": int(item.get("queuedAt") or 0),
}
for item in _processing_request_queue
]
waiting_count = len(queue_copy)
active_in_flight = 1 if active_job.get("isActive") else 0
requester_queue_index = -1
if requester_id or requester_ip:
for idx, item in enumerate(queue_copy):
owner_id = (item.get("ownerClientId") or "").strip()
owner_ip = (item.get("ownerClientIp") or "").strip()
id_match = bool(requester_id and owner_id and owner_id == requester_id)
ip_match = bool(requester_ip and owner_ip and owner_ip == requester_ip)
if id_match or ip_match:
requester_queue_index = idx
break
requester_queue_position = 0
requester_jobs_ahead = 0
active_owner_id = (active_job.get("ownerClientId") or "").strip()
active_owner_ip = (active_job.get("ownerClientIp") or "").strip()
active_id_match = bool(requester_id and active_owner_id and active_owner_id == requester_id)
active_ip_match = bool(requester_ip and active_owner_ip and active_owner_ip == requester_ip)
if active_in_flight and (active_id_match or active_ip_match):
requester_queue_position = 1
requester_jobs_ahead = 0
elif requester_queue_index >= 0:
requester_queue_position = requester_queue_index + 1 + active_in_flight
requester_jobs_ahead = requester_queue_index + active_in_flight
avg_seconds = _average_processing_duration_seconds()
active_remaining_seconds = 0
if active_in_flight:
started_at = int(active_job.get("startedAt") or 0)
if started_at > 0:
elapsed = max(0, int(time.time()) - started_at)
active_remaining_seconds = max(0, avg_seconds - elapsed)
else:
active_remaining_seconds = max(1, avg_seconds)
benchmark_in_progress = False
benchmark_eta_seconds = 0
with _benchmark_lock:
benchmark_in_progress = bool(_benchmark_in_progress)
try:
benchmark_eta_seconds = max(0, int(_benchmark_progress.get("etaSeconds") or 0))
except Exception:
benchmark_eta_seconds = 0
benchmark_stage = str(_benchmark_progress.get("stage") or "idle")
benchmark_pct = int(_benchmark_progress.get("progressPct") or 0)
# If benchmark ETA is unknown but benchmark is running, keep a conservative floor.
if benchmark_in_progress and benchmark_eta_seconds <= 0:
benchmark_eta_seconds = 90
estimated_wait_seconds = (waiting_count * avg_seconds) + active_remaining_seconds + benchmark_eta_seconds
requester_wait_seconds = 0
if requester_queue_position > 0:
if requester_queue_position == 1:
requester_wait_seconds = benchmark_eta_seconds
elif requester_queue_index >= 0:
requester_wait_seconds = (requester_queue_index * avg_seconds) + active_remaining_seconds + benchmark_eta_seconds
queue_status_line = ""
if waiting_count > 0:
if requester_queue_position > 0:
queue_status_line = (
f"Queue active: {waiting_count} waiting | Your position: {requester_queue_position} "
f"(~{_format_eta_seconds(requester_wait_seconds) or 'soon'})"
)
else:
queue_status_line = (
f"Queue active: {waiting_count} waiting "
f"(~{_format_eta_seconds(estimated_wait_seconds) or 'soon'} total)"
)
return {
"activeInFlight": active_in_flight,
"waitingCount": waiting_count,
"queueTotal": waiting_count + active_in_flight,
"estimatedWaitSeconds": estimated_wait_seconds,
"activeRemainingSeconds": active_remaining_seconds,
"averageJobSeconds": avg_seconds,
"benchmarkInProgress": benchmark_in_progress,
"benchmarkEtaSeconds": benchmark_eta_seconds,
"benchmarkStage": benchmark_stage,
"benchmarkProgressPct": benchmark_pct,
"requesterQueuePosition": requester_queue_position,
"requesterJobsAhead": requester_jobs_ahead,
"requesterEstimatedWaitSeconds": requester_wait_seconds,
"queueStatusLine": queue_status_line,
}
def _cancel_processing_job(job_id: Optional[str]) -> Dict[str, Any]:
global _last_processing_cancellation_ts
active_future = None
active_job_id = ""
with _processing_job_lock:
active_job_id = _active_processing_job.get("jobId") or ""
active_future = _active_processing_job.get("future")
if not active_job_id or not active_future or active_future.done():
return {"ok": False, "reason": "no_active_job", "jobId": ""}
if job_id and job_id != active_job_id:
return {"ok": False, "reason": "job_id_mismatch", "jobId": active_job_id}
_active_processing_job["cancelRequested"] = True
# Important: call cancel outside the lock to avoid deadlock from done-callback lock reentry.
cancelled = active_future.cancel()
if not cancelled:
set_processing_status("⛔ Cancellation requested. Stopping current processing...")
_last_processing_cancellation_ts = time.time()
return {
"ok": True,
"reason": "cancel_requested",
"jobId": active_job_id,
"cancelSignalAccepted": bool(cancelled),
}
def _sanitize_client_id(raw_client_id: str) -> str:
candidate = (raw_client_id or "").strip()
if not candidate:
return ""
candidate = re.sub(r'[^A-Za-z0-9._-]', '', candidate)
return candidate[:96]
def _can_requester_cancel_active_job(active_job_snapshot: Dict[str, Any], requester: Dict[str, Any]) -> bool:
if not active_job_snapshot.get("isActive"):
return False
if requester.get("isAdmin"):
return True
owner_client_id = (active_job_snapshot.get("ownerClientId") or "").strip()
owner_client_ip = (active_job_snapshot.get("ownerClientIp") or "").strip()
requester_client_id = (requester.get("clientId") or "").strip()
requester_client_ip = (requester.get("clientIp") or "").strip()
id_match = bool(owner_client_id and requester_client_id and owner_client_id == requester_client_id)
ip_match = bool(owner_client_ip and requester_client_ip and owner_client_ip == requester_client_ip)
return id_match or ip_match
def run_async_loop(loop: asyncio.AbstractEventLoop):
"""Runs an asyncio event loop forever in a dedicated daemon thread."""
asyncio.set_event_loop(loop)
loop.run_forever()
def _log_scheduled_future_error(future, operation_name: str):
"""Logs unhandled exceptions from run_coroutine_threadsafe futures."""
try:
if future.cancelled():
logger.debug(f"Scheduled async operation '{operation_name}' was cancelled.")
return
exc = future.exception()
if exc:
logger.error(f"Scheduled async operation '{operation_name}' failed: {exc}", exc_info=True)
except Exception as callback_error:
logger.error(f"Error while checking future for '{operation_name}': {callback_error}", exc_info=True)
def _schedule_processing_job(
main_loop: asyncio.AbstractEventLoop,
coroutine,
operation_name: str,
owner_client_id: str = "",
owner_client_ip: str = "",
owner_username: str = "",
owner_is_admin: bool = False,
owner_source: str = "web",
) -> tuple[Optional[str], Optional[concurrent.futures.Future], Optional[str]]:
"""
Enqueues a processing coroutine into the global FIFO worker.
Returns (job_id, future, error_message). Future is attached once execution starts.
"""
global _processing_queue_worker_running
if not coroutine:
return None, None, "No processing coroutine provided."
request_id = _new_processing_job_id()
queued_job = {
"requestId": request_id,
"mainLoop": main_loop,
"coroutine": coroutine,
"operationName": operation_name,
"ownerClientId": (owner_client_id or "").strip(),
"ownerClientIp": (owner_client_ip or "").strip(),
"ownerUsername": (owner_username or "").strip(),
"ownerIsAdmin": bool(owner_is_admin),
"ownerSource": (owner_source or "web").strip().lower(),
"queuedAt": int(time.time()),
}
with _processing_queue_lock:
_processing_request_queue.append(queued_job)
def _queue_worker() -> None:
global _processing_queue_worker_running
while True:
with _processing_queue_lock:
has_waiting_jobs = bool(_processing_request_queue)
if not has_waiting_jobs:
_processing_queue_worker_running = False
return
with _benchmark_lock:
benchmark_busy = bool(_benchmark_in_progress)
if benchmark_busy:
# Hold queued processing until benchmark fully completes.
time.sleep(0.4)
continue
with _processing_queue_lock:
next_job = _processing_request_queue.pop(0)
started_at = time.time()
job_loop = next_job.get("mainLoop")
job_coro = next_job.get("coroutine")
job_id = next_job.get("requestId") or _new_processing_job_id()
op_name = next_job.get("operationName") or "queued_processing_job"
future = asyncio.run_coroutine_threadsafe(job_coro, job_loop)
_register_processing_future(
job_id,
future,
owner_client_id=next_job.get("ownerClientId") or "",
owner_client_ip=next_job.get("ownerClientIp") or "",
owner_username=next_job.get("ownerUsername") or "",
owner_is_admin=bool(next_job.get("ownerIsAdmin")),
owner_source=next_job.get("ownerSource") or "web",
)
if time.time() - float(_last_processing_cancellation_ts or 0) <= 30:
owner_name = (next_job.get("ownerUsername") or "requester").strip() or "requester"
set_processing_status(f"Previous video cancelled. Starting next queued video for {owner_name}...")
future.add_done_callback(lambda f, name=op_name: _log_scheduled_future_error(f, name))
try:
future.result()
except concurrent.futures.CancelledError:
logger.info(f"Queued processing job '{job_id}' cancelled.")
except Exception as queue_job_error:
logger.error(
f"Queued processing job '{job_id}' failed: {queue_job_error}",
exc_info=True,
)
finally:
_record_processing_duration(time.time() - started_at)
with _processing_queue_lock:
should_start_worker = not _processing_queue_worker_running
if should_start_worker:
_processing_queue_worker_running = True
if should_start_worker:
threading.Thread(target=_queue_worker, daemon=True).start()
return request_id, None, None
def _register_async_process(process: asyncio.subprocess.Process, label: str) -> None:
if not process:
return
with _active_async_processes_lock:
_active_async_processes[id(process)] = {
"process": process,
"label": label,
"pid": process.pid,
"registeredAt": int(time.time()),
}
def _unregister_async_process(process: asyncio.subprocess.Process) -> None:
if not process:
return
with _active_async_processes_lock:
_active_async_processes.pop(id(process), None)
def _snapshot_async_processes() -> list:
with _active_async_processes_lock:
return list(_active_async_processes.values())
def _start_new_session_kwargs() -> Dict[str, Any]:
# Put spawned subprocesses in independent process groups for reliable cancel semantics.
return {"start_new_session": True} if os.name == "posix" else {}
def _is_pid_alive(pid: int) -> bool:
if not pid or pid <= 0:
return False
try:
os.kill(pid, 0)
return True
except ProcessLookupError:
return False
except Exception:
return False
def _terminate_pid_tree_sync(pid: int, label: str) -> bool:
if not pid or pid <= 0:
return False
try:
if os.name == "posix":
try:
pgid = os.getpgid(pid)
logger.debug(f"SIGTERM process group for '{label}' (pid={pid}, pgid={pgid})")
os.killpg(pgid, signal.SIGTERM)
except ProcessLookupError:
return False
else:
logger.debug(f"SIGTERM process for '{label}' (pid={pid})")
os.kill(pid, signal.SIGTERM)
except ProcessLookupError:
return False
except Exception as term_error:
logger.warning(f"Failed to SIGTERM '{label}' (pid={pid}): {term_error}")
return False
for _ in range(10):
if not _is_pid_alive(pid):
return True
time.sleep(0.1)
try:
if os.name == "posix":
try:
pgid = os.getpgid(pid)
logger.debug(f"SIGKILL process group for '{label}' (pid={pid}, pgid={pgid})")
os.killpg(pgid, signal.SIGKILL)
except ProcessLookupError:
return True
else:
logger.debug(f"SIGKILL process for '{label}' (pid={pid})")
os.kill(pid, signal.SIGKILL)
except ProcessLookupError:
return True
except Exception as kill_error:
logger.warning(f"Failed to SIGKILL '{label}' (pid={pid}): {kill_error}")
return False
for _ in range(10):
if not _is_pid_alive(pid):
return True
time.sleep(0.1)
return not _is_pid_alive(pid)
def _terminate_registered_async_processes_sync() -> int:
snapshot = _snapshot_async_processes()
if not snapshot:
return 0
terminated = 0
for item in snapshot:
process = item.get("process")
pid = int(item.get("pid") or 0)
label = item.get("label") or "subprocess"
stopped = _terminate_pid_tree_sync(pid, label)
if stopped:
terminated += 1
if stopped and process:
_unregister_async_process(process)
return terminated
def _list_child_pids(pid: int) -> list[int]:
if not pid or pid <= 0:
return []
try:
output = subprocess.check_output(["ps", "-o", "pid=", "--ppid", str(pid)], text=True)
return [int(line.strip()) for line in output.splitlines() if line.strip().isdigit()]
except Exception:
return []
def _collect_descendant_pids(root_pid: int) -> list[int]:
stack = [root_pid]
descendants: list[int] = []
seen: set[int] = set()
while stack:
current = stack.pop()
if current in seen:
continue
seen.add(current)
children = _list_child_pids(current)
for child in children:
if child not in seen:
descendants.append(child)
stack.append(child)
return descendants
def _force_kill_pid_family_sync(root_pid: int, label: str) -> int:
if not root_pid or root_pid <= 0:
return 0
killed = 0
descendants = _collect_descendant_pids(root_pid)
# Kill descendants first, then root.
for pid in descendants:
try:
os.kill(pid, signal.SIGKILL)
killed += 1
logger.debug(f"Force-killed descendant process for '{label}' (pid={pid}, root={root_pid})")
except Exception:
pass
try:
os.kill(root_pid, signal.SIGKILL)
killed += 1
logger.debug(f"Force-killed root process for '{label}' (pid={root_pid})")
except Exception:
pass
return killed
def _force_kill_registered_process_families_sync() -> int:
snapshot = _snapshot_async_processes()
killed = 0
for item in snapshot:
process = item.get("process")
pid = int(item.get("pid") or 0)
label = item.get("label") or "subprocess"
if pid > 0:
killed += _force_kill_pid_family_sync(pid, label)
if process:
_unregister_async_process(process)
return killed
def _emergency_kill_registered_processes_sync() -> int:
"""Immediate best-effort kill for tracked subprocesses.
This is used in cancel handler before any potentially blocking cancellation flows.
"""
snapshot = _snapshot_async_processes()
if not snapshot:
return 0
killed = 0
for item in snapshot:
process = item.get("process")
pid = int(item.get("pid") or 0)
label = item.get("label") or "subprocess"
# Fast path: kill through process handle when available.
try:
if process and process.returncode is None:
process.kill()
killed += 1
logger.debug(f"Emergency process.kill() for '{label}' (pid={pid})")
except Exception as kill_handle_error:
logger.warning(f"Emergency process.kill() failed for '{label}' (pid={pid}): {kill_handle_error}")
# Fallback path: kill process group/root pid directly.
try:
if pid > 0:
if os.name == "posix":
try:
pgid = os.getpgid(pid)
os.killpg(pgid, signal.SIGKILL)
logger.debug(f"Emergency SIGKILL process group for '{label}' (pid={pid}, pgid={pgid})")
except Exception:
os.kill(pid, signal.SIGKILL)
logger.debug(f"Emergency SIGKILL process for '{label}' (pid={pid})")
else:
os.kill(pid, signal.SIGKILL)
logger.debug(f"Emergency SIGKILL process for '{label}' (pid={pid})")
except Exception as direct_kill_error:
logger.warning(f"Emergency direct kill failed for '{label}' (pid={pid}): {direct_kill_error}")
if not _is_pid_alive(pid):
if process:
_unregister_async_process(process)
return killed
async def _terminate_all_registered_async_processes() -> int:
snapshot = _snapshot_async_processes()
if not snapshot:
return 0
terminated = 0
for item in snapshot:
process = item.get("process")
label = item.get("label") or "subprocess"
if process:
await _terminate_async_process(process, label)
terminated += 1
return terminated
def generate_preview_session_id():
"""Generates a unique preview session ID."""
import uuid
return str(uuid.uuid4())
def create_preview_session(video_path: str, original_filename: str = None) -> str:
"""Creates a new preview session and returns the session ID."""
session_id = generate_preview_session_id()
# If no original filename provided, try to extract from path
if original_filename is None:
original_filename = os.path.basename(video_path)
with _preview_sessions_lock:
_preview_sessions[session_id] = {
'video_path': video_path,
'original_filename': original_filename,
'created_at': time.time(),
'used': False # Set to True when processing starts
}
logger.info(f"Created preview session {session_id} for {video_path} (original: {original_filename})")
return session_id
def get_preview_session(session_id: str) -> dict:
"""Gets a preview session by ID."""
with _preview_sessions_lock:
return _preview_sessions.get(session_id)
def mark_preview_session_used(session_id: str):
"""Marks a preview session as used (processing started)."""
with _preview_sessions_lock:
if session_id in _preview_sessions:
_preview_sessions[session_id]['used'] = True
logger.info(f"Preview session {session_id} marked as used")
def remove_preview_session(session_id: str):
"""Removes a preview session."""
with _preview_sessions_lock:
if session_id in _preview_sessions:
del _preview_sessions[session_id]
logger.info(f"Removed preview session {session_id}")
def cleanup_abandoned_previews():
"""Cleans up preview sessions that have been abandoned (not used within timeout)."""
current_time = time.time()
sessions_to_remove = []
with _preview_sessions_lock:
for session_id, session_data in list(_preview_sessions.items()):
age = current_time - session_data['created_at']
if age > PREVIEW_CLEANUP_TIMEOUT_SECONDS and not session_data['used']:
sessions_to_remove.append((session_id, session_data['video_path']))
# Clean up outside the lock to avoid holding it too long
for session_id, video_path in sessions_to_remove:
try:
if os.path.exists(video_path):
os.remove(video_path)
logger.info(f"Cleaned up abandoned preview file: {video_path}")
except Exception as e:
logger.error(f"Error cleaning up preview file {video_path}: {e}")
remove_preview_session(session_id)
if sessions_to_remove:
logger.info(f"Cleaned up {len(sessions_to_remove)} abandoned preview sessions")
def start_preview_cleanup_scheduler():
"""Starts a background thread to periodically clean up abandoned previews."""
def cleanup_loop():
while True:
time.sleep(PREVIEW_CLEANUP_INTERVAL_SECONDS)
cleanup_abandoned_previews()
cleanup_thread = threading.Thread(target=cleanup_loop, daemon=True)
cleanup_thread.start()
logger.info("Preview cleanup scheduler started")
def extract_video_frame(video_path: str, output_image_path: str, seek_time: float = 1.0) -> bool:
"""
Extracts a single frame from a video using FFmpeg.
Args:
video_path: Path to the video file
output_image_path: Path to save the extracted frame (JPEG)
seek_time: Time in seconds to seek to (default 1 second)