Update stream URL and reconnect with proper cleanup for both HTTP and transcode sessions
(self, new_url, stream_id=None, m3u_profile_id=None)
| 1315 | logger.debug(f"Error flushing final bitrate to DB for channel {self.channel_id}: {e}") |
| 1316 | |
| 1317 | def update_url(self, new_url, stream_id=None, m3u_profile_id=None): |
| 1318 | """Update stream URL and reconnect with proper cleanup for both HTTP and transcode sessions""" |
| 1319 | if new_url == self.url: |
| 1320 | logger.info(f"URL unchanged: {new_url}") |
| 1321 | return False |
| 1322 | |
| 1323 | logger.info(f"Switching stream URL from {self.url} to {new_url} for channel {self.channel_id}") |
| 1324 | |
| 1325 | # Import both models for proper resource management |
| 1326 | from apps.channels.models import Stream, Channel |
| 1327 | from django.db import connection |
| 1328 | |
| 1329 | # Update stream profile if we're switching streams |
| 1330 | if self.current_stream_id and stream_id and self.current_stream_id != stream_id: |
| 1331 | try: |
| 1332 | # Get the channel by UUID |
| 1333 | channel = Channel.objects.get(uuid=self.channel_id) |
| 1334 | |
| 1335 | # Get stream to find its profile |
| 1336 | #new_stream = Stream.objects.get(pk=stream_id) |
| 1337 | |
| 1338 | # Use the new method to update the profile and manage connection counts |
| 1339 | if m3u_profile_id: |
| 1340 | success = channel.update_stream_profile(m3u_profile_id) |
| 1341 | if success: |
| 1342 | logger.debug(f"Updated m3u profile for channel {self.channel_id} to use profile from stream {stream_id}") |
| 1343 | else: |
| 1344 | logger.warning(f"Failed to update stream profile for channel {self.channel_id}") |
| 1345 | |
| 1346 | except Exception as e: |
| 1347 | logger.error(f"Error updating stream profile for channel {self.channel_id}: {e}") |
| 1348 | |
| 1349 | finally: |
| 1350 | # Always close database connection after profile update |
| 1351 | try: |
| 1352 | connection.close() |
| 1353 | except Exception: |
| 1354 | pass |
| 1355 | |
| 1356 | # CRITICAL: Set a flag to prevent immediate reconnection with old URL |
| 1357 | self.url_switching = True |
| 1358 | self.url_switch_start_time = time.time() |
| 1359 | |
| 1360 | try: |
| 1361 | # Check which type of connection we're using and close it properly |
| 1362 | if self.transcode or self.socket: |
| 1363 | logger.debug(f"Closing transcode process before URL change for channel {self.channel_id}") |
| 1364 | self._close_socket() |
| 1365 | else: |
| 1366 | logger.debug(f"Closing HTTP connection before URL change for channel {self.channel_id}") |
| 1367 | self._close_connection() |
| 1368 | |
| 1369 | # Update URL and reset connection state |
| 1370 | old_url = self.url |
| 1371 | self.url = new_url |
| 1372 | self.connected = False |
| 1373 | |
| 1374 | # Reset bitrate EMA on every URL change so stale data never carries over |
no test coverage detected