import re import time import logging import requests from selenium import webdriver from selenium.webdriver.chrome.service import Service from selenium.webdriver.chrome.options import Options from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC # Configure logging logging.basicConfig( level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s' ) # Configuration STREAM_URL = "https://www.2ix2.com/rtl-live/" OUTPUT_FILE = "/home/pi/stream_playlist.m3u" CHROMEDRIVER_PATH = "/usr/bin/chromedriver" CHROME_BIN_PATH = "/usr/bin/chromium-browser" REFRESH_INTERVAL = 300 # 5 minutes def setup_driver(): """Configure headless Chrome for Raspberry Pi""" chrome_options = Options() chrome_options.binary_location = CHROME_BIN_PATH chrome_options.add_argument("--headless") chrome_options.add_argument("--disable-gpu") chrome_options.add_argument("--no-sandbox") chrome_options.add_argument("--disable-dev-shm-usage") service = Service(executable_path=CHROMEDRIVER_PATH) return webdriver.Chrome(service=service, options=chrome_options) def extract_m3u8_url(driver): """Extract the latest M3U8 URL with fresh token""" try: # Wait for player to load WebDriverWait(driver, 20).until( EC.presence_of_element_located((By.TAG_NAME, "video")) ) # Get network requests using JavaScript requests = driver.execute_script( "var performance = window.performance || window.webkitPerformance || {};" "var network = performance.getEntries() || [];" "return network;" ) # Find the latest M3U8 URL with token m3u8_pattern = re.compile(r'.*\.m3u8.*token=') for entry in reversed(requests): if m3u8_pattern.search(entry['name']): return entry['name'] except Exception as e: logging.error(f"Error extracting URL: {str(e)}") return None def update_playlist(): """Main function to refresh the stream URL""" driver = setup_driver() try: driver.get(STREAM_URL) time.sleep(10) # Allow player to initialize m3u8_url = extract_m3u8_url(driver) if m3u8_url: with open(OUTPUT_FILE, "w") as f: f.write("#EXTM3U\n") f.write(f"#EXTINF:-1, Live Stream\n{m3u8_url}\n") logging.info(f"Updated stream URL: {m3u8_url[:60]}...") else: logging.warning("No valid stream URL found") finally: driver.quit() def main(): """Continuous refresh loop""" while True: update_playlist() logging.info(f"Next update in {REFRESH_INTERVAL//60} minutes...") time.sleep(REFRESH_INTERVAL) if __name__ == "__main__": try: main() except KeyboardInterrupt: logging.info("Script stopped by user") except Exception as e: logging.error(f"Critical error: {str(e)}")