Waits for api to return status until stream is running.

This commit is contained in:
SergeantPanda 2025-03-04 12:03:09 -06:00
parent 0750b7dd80
commit 3b3e5f7b52
3 changed files with 46 additions and 3 deletions

View file

@ -21,4 +21,6 @@ class HLSConfig(BaseConfig):
class TSConfig(BaseConfig):
BUFFER_SIZE = 1000
RECONNECT_DELAY = 5
RECONNECT_DELAY = 5
CLIENT_TIMEOUT = 15 # Seconds before stopping idle channel
CONNECTION_TIMEOUT = 10 # Seconds to wait for initial connection

View file

@ -72,6 +72,27 @@ class ClientManager:
def __init__(self):
self.active_clients: Set[int] = set()
self.lock: threading.Lock = threading.Lock()
self.last_client_time: float = time.time()
self.cleanup_timer: Optional[threading.Timer] = None
def start_cleanup_timer(self, proxy_server, channel_id):
"""Start timer to cleanup idle channels"""
if self.cleanup_timer:
self.cleanup_timer.cancel()
self.cleanup_timer = threading.Timer(
Config.CLIENT_TIMEOUT,
self._cleanup_idle_channel,
args=[proxy_server, channel_id]
)
self.cleanup_timer.daemon = True
self.cleanup_timer.start()
def _cleanup_idle_channel(self, proxy_server, channel_id):
"""Stop channel if no clients connected"""
with self.lock:
if not self.active_clients:
logging.info(f"No clients connected for {Config.CLIENT_TIMEOUT}s, stopping channel {channel_id}")
proxy_server.stop_channel(channel_id)
def add_client(self, client_id: int) -> None:
"""Add new client connection"""

View file

@ -1,9 +1,11 @@
import json
import threading
import logging
import time
from django.http import StreamingHttpResponse, JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods
from apps.proxy.config import TSConfig as Config # Change this line
from .server import ProxyServer
logger = logging.getLogger(__name__)
@ -18,10 +20,28 @@ def initialize_stream(request, channel_id):
url = data.get('url')
if not url:
return JsonResponse({'error': 'No URL provided'}, status=400)
# Start the channel
proxy_server.initialize_channel(url, channel_id)
# Wait for connection to be established
manager = proxy_server.stream_managers[channel_id]
wait_start = time.time()
while not manager.connected:
if time.time() - wait_start > Config.CONNECTION_TIMEOUT:
proxy_server.stop_channel(channel_id)
return JsonResponse({
'error': 'Connection timeout'
}, status=504)
if not manager.should_retry():
proxy_server.stop_channel(channel_id)
return JsonResponse({
'error': 'Failed to connect'
}, status=502)
time.sleep(0.1)
return JsonResponse({
'message': 'Stream initialized',
'message': 'Stream initialized and connected',
'channel': channel_id,
'url': url
})