import logging import os import streamlit as st from twilio.base.exceptions import TwilioRestException from twilio.rest import Client import requests logger = logging.getLogger(__name__) def check_connectivity(): try: response = requests.get("https://api.twilio.com") if response.status_code == 200: logger.info("Twilio API is reachable.") else: logger.warning(f"Twilio API returned status code {response.status_code}") except requests.RequestException as e: logger.error(f"Failed to reach Twilio API: {e}") try: response = requests.get("https://stun.l.google.com:19302") if response.status_code == 200: logger.info("Google STUN server is reachable.") else: logger.warning(f"Google STUN server returned status code {response.status_code}") except requests.RequestException as e: logger.error(f"Failed to reach Google STUN server: {e}") def get_ice_servers(): """Use Twilio's TURN server because Streamlit Community Cloud has changed its infrastructure and WebRTC connection cannot be established without TURN server now. """ check_connectivity() try: account_sid = os.environ["TWILIO_ACCOUNT_SID"] auth_token = os.environ["TWILIO_AUTH_TOKEN"] logger.info(f"Twilio SID: {account_sid}, Auth Token: {auth_token[:4]}...") # Log partial token for security except KeyError: logger.warning( "Twilio credentials are not set. Fallback to a free STUN server from Google." ) return [{"urls": ["stun:stun.l.google.com:19302"]}] client = Client(account_sid, auth_token) try: token = client.tokens.create() except TwilioRestException as e: logger.error(f"Twilio API error: {e}") st.warning( f"Error occurred while accessing Twilio API. Fallback to a free STUN server from Google. ({e})" ) return [{"urls": ["stun:stun.l.google.com:19302"]}] return token.ice_servers