ipmpv/channel_updater.py

84 lines
2.2 KiB
Python

#!/usr/bin/python
"""Channel update functionality for IPMPV.
This module provides functionality to periodically update the channel list
without requiring application restart."""
import threading
import time
class ChannelUpdater:
"""Class to handle periodic channel list updates."""
def __init__(self, server, update_interval=3600):
"""
Initialize the channel updater.
Args:
server: The IPMPVServer instance
update_interval: Update interval in seconds (default: 1 hour)
"""
self.server = server
self.update_interval = update_interval
self.running = False
self.update_thread = None
def start(self):
"""Start the periodic update thread."""
if self.update_thread is not None and self.update_thread.is_alive():
return # Already running
self.running = True
self.update_thread = threading.Thread(
target=self._update_loop,
daemon=True
)
self.update_thread.start()
print(f"Channel updater started with {self.update_interval}s interval")
def stop(self):
"""Stop the periodic update thread."""
self.running = False
if self.update_thread:
self.update_thread.join(timeout=1)
self.update_thread = None
def _update_loop(self):
"""Background loop to update channels periodically."""
while self.running:
# Sleep first to avoid immediate update after startup
for _ in range(self.update_interval):
if not self.running:
return
time.sleep(1)
# Perform the update
try:
self._update_channels()
except Exception as e:
print(f"Error updating channels: {e}")
def _update_channels(self):
"""Update the channel list."""
from channels import get_channels
print("Updating channel list...")
new_channels = get_channels()
# Only update if we got valid channels
if new_channels:
# Update the server's channel list
self.server.channels = new_channels
print(f"Channel list updated: {len(new_channels)} channels")
else:
print("Channel update failed or returned empty list")
def force_update(self):
"""Force an immediate channel list update."""
try:
self._update_channels()
return True
except Exception as e:
print(f"Error during forced channel update: {e}")
return False