# WebRTC Connection Troubleshooting Guide

## Error: "Unable to Load Translators - Failed to fetch"

This error occurs when the frontend cannot connect to the WebRTC backend API.

### Quick Diagnostics

#### 1. Check Backend API Status
Open your browser console and run:
```javascript
fetch('https://ministryprogs.tniglobal.org/webrtc/public/active-translators')
  .then(res => res.json())
  .then(data => console.log('✅ API is working:', data))
  .catch(err => console.error('❌ API error:', err));
```

#### 2. Check Backend Server
```bash
# SSH into server
ssh user@ministryprogs.tniglobal.org

# Check if WebRTC server is running
pm2 list | grep webrtc
# or
netstat -tulpn | grep 3001

# Check server logs
pm2 logs webrtc-server
```

#### 3. Test API Endpoints Directly
```bash
# Test router capabilities
curl https://ministryprogs.tniglobal.org/webrtc/public/router-capabilities

# Test active translators
curl https://ministryprogs.tniglobal.org/webrtc/public/active-translators

# Expected response:
# {"translators": [...]}
```

### Common Causes & Solutions

#### 1. Backend Server Not Running
**Symptoms:**
- Connection refused errors
- "Failed to fetch" in console
- No response from API endpoints

**Solution:**
```bash
# Navigate to backend directory
cd ~/public_html/webrtc/browser-based-translation

# Check if server is running
pm2 list

# Start/restart the server
pm2 start ecosystem.config.js
# or
pm2 restart webrtc-server
```

#### 2. CORS Not Configured
**Symptoms:**
- "CORS policy" error in browser console
- Network tab shows OPTIONS request failing

**Solution:**
Check backend CORS configuration allows your frontend domain:
```javascript
// Backend should have:
app.use(cors({
  origin: [
    'http://localhost:3000',
    'https://yourdomain.com',
    'https://livestream.tniglobal.org'
  ],
  credentials: true
}));
```

#### 3. Firewall Blocking Port 3001
**Symptoms:**
- Timeout errors
- Connection hangs

**Solution:**
```bash
# Check if port is open
sudo ufw status
sudo ufw allow 3001

# Check if nginx proxy is configured
sudo nano /etc/nginx/sites-available/ministryprogs.tniglobal.org
```

#### 4. SSL/HTTPS Certificate Issues
**Symptoms:**
- "Mixed content" errors
- Certificate warnings

**Solution:**
- Ensure backend uses HTTPS (not HTTP)
- Check SSL certificate is valid
- Both frontend and backend should use same protocol

#### 5. No Active Translators
**Symptoms:**
- API returns empty array `{"translators": []}`
- No error, just no translators

**Solution:**
- Translators need to be actively streaming from the translation app
- Check translation app at: `~/public_html/webrtc/browser-based-translation/frontend-react`
- Verify translator has started their session

### Development Workarounds

#### Use Test Mode (Development Only)
If backend is unavailable during development:

1. Click "🧪 Enable Test Mode" button in the page header
2. This loads mock translator data
3. Allows testing UI without backend connection

#### Environment Variables
Create `.env.local` file:
```env
# For local development with different API
REACT_APP_WEBRTC_API_URL=http://localhost:3001
REACT_APP_ENABLE_TEST_MODE=true
```

Update `webrtc-consumer.ts`:
```typescript
const API_BASE_URL = process.env.REACT_APP_WEBRTC_API_URL || 'https://ministryprogs.tniglobal.org';
```

### Verify Network Connectivity

#### From Browser Console:
```javascript
// Test DNS resolution
fetch('https://ministryprogs.tniglobal.org')
  .then(() => console.log('✅ Server reachable'))
  .catch(err => console.error('❌ Cannot reach server:', err));

// Check CORS
fetch('https://ministryprogs.tniglobal.org/webrtc/public/router-capabilities', {
  method: 'GET',
  mode: 'cors',
  headers: { 'Content-Type': 'application/json' }
})
  .then(res => console.log('✅ CORS OK, Status:', res.status))
  .catch(err => console.error('❌ CORS Error:', err));
```

#### From Server:
```bash
# Check nginx is running
sudo systemctl status nginx

# Check backend logs
pm2 logs webrtc-server --lines 50

# Test API locally on server
curl http://localhost:3001/webrtc/public/active-translators
```

### Backend Server Setup Checklist

- [ ] MediaSoup server is running (port 3001)
- [ ] CORS is configured with frontend domain
- [ ] SSL certificates are valid
- [ ] Firewall allows port 3001 (or nginx proxy configured)
- [ ] Public routes are accessible without authentication
- [ ] At least one translator is actively streaming
- [ ] Environment variables are set correctly
- [ ] MongoDB connection is working (for translator data)

### Additional Debugging

Enable verbose logging in browser console:
```javascript
// In browser console, before loading page:
localStorage.setItem('debug', 'webrtc:*');
```

Check Network Tab in DevTools:
1. Open DevTools (F12)
2. Go to Network tab
3. Filter by "active-translators"
4. Check request/response details
5. Look for error codes (404, 500, 503)

### Contact Information

If issue persists after trying above solutions:

1. **Check Backend Server Status**
   - Server: ministryprogs.tniglobal.org
   - Port: 3001
   - Protocol: HTTPS

2. **Collect Error Information**
   - Browser console errors (full stack trace)
   - Network tab request/response
   - Backend server logs
   - PM2 process status

3. **Verify Translation App**
   - Location: `~/public_html/webrtc/browser-based-translation`
   - Frontend: `frontend-react/`
   - Backend: Check if using same port/domain

### Quick Fix Commands

```bash
# Restart WebRTC backend
cd ~/public_html/webrtc/browser-based-translation
pm2 restart all

# Check logs
pm2 logs --lines 100

# Restart nginx (if using proxy)
sudo systemctl restart nginx

# Check port availability
netstat -tulpn | grep 3001
```

### Testing Checklist

- [ ] Backend API responds to curl/fetch
- [ ] CORS headers present in response
- [ ] Active translators endpoint returns data
- [ ] Router capabilities endpoint returns data
- [ ] Frontend can fetch without errors
- [ ] Test mode works in development
- [ ] Production build works

---

**Last Updated:** January 13, 2026  
**Related Files:**
- `/src/utils/webrtc-consumer.ts`
- `/src/pages/streamspace/GeneralStreamWebRTC.tsx`
- Backend: `~/public_html/webrtc/browser-based-translation`
