# HTTPS Implementation Quick Reference

## Configuration

### app_config.json Settings

```json
{
  "use_https": true,      // Enable HTTPS connections (default: true)
  "verify_ssl": true,     // Verify SSL certificates (default: true, false for dev)
  "server_ip": "your-server.com",
  "port": "443"          // Use 443 for HTTPS, 5000 for HTTP
}
```

---

## Code Usage Examples

### 1. Authentication with HTTPS

```python
from player_auth import PlayerAuth

# Create auth instance with HTTPS enabled
auth = PlayerAuth(
    config_file='player_auth.json',
    use_https=True,
    verify_ssl=True
)

# Authenticate with server
success, error = auth.authenticate(
    server_url='https://your-server.com',
    hostname='player-001',
    quickconnect_code='ABC123XYZ'
)

if success:
    print(f"Connected: {auth.get_player_name()}")
else:
    print(f"Error: {error}")
```

### 2. Fetching Playlists with HTTPS

```python
from get_playlists_v2 import update_playlist_if_needed

config = {
    'server_ip': 'your-server.com',
    'port': '443',
    'screen_name': 'player-001',
    'quickconnect_key': 'ABC123XYZ',
    'use_https': True,
    'verify_ssl': True
}

# This will automatically handle HTTPS and SSL verification
playlist_file = update_playlist_if_needed(
    config=config,
    playlist_dir='./playlists',
    media_dir='./media'
)
```

### 3. Manual SSL Setup

```python
from ssl_utils import SSLManager, setup_ssl_for_requests

# Option A: Use SSLManager directly
ssl_manager = SSLManager(verify_ssl=True)

# Download server certificate
success, error = ssl_manager.download_server_certificate(
    server_url='https://your-server.com'
)

if success:
    # Use session for requests
    session = ssl_manager.get_session()
    response = session.get('https://your-server.com/api/data')

# Option B: Quick setup
session, success = setup_ssl_for_requests(
    server_url='your-server.com',
    use_https=True,
    verify_ssl=True
)
```

### 4. Handling SSL Errors

```python
try:
    response = session.get('https://your-server.com/api/data')
except requests.exceptions.SSLError as e:
    print(f"SSL Error: {e}")
    # Options:
    # 1. Ensure certificate is valid
    # 2. Download certificate from /api/certificate
    # 3. Set verify_ssl=False for testing only
except requests.exceptions.ConnectionError as e:
    print(f"Connection Error: {e}")
```

---

## Common Configuration Scenarios

### Scenario 1: Production with Proper Certificate
```json
{
  "server_ip": "production-server.com",
  "port": "443",
  "use_https": true,
  "verify_ssl": true
}
```
✓ Most secure, requires valid certificate from trusted CA

### Scenario 2: Self-Signed Certificate (Test)
```json
{
  "server_ip": "test-server.local",
  "port": "443",
  "use_https": true,
  "verify_ssl": true
}
```
- First run: certificate will be downloaded automatically
- Subsequent runs: saved certificate will be used

### Scenario 3: Development Mode (No SSL)
```json
{
  "server_ip": "localhost",
  "port": "5000",
  "use_https": false,
  "verify_ssl": false
}
```
⚠️ Not secure - development only!

### Scenario 4: HTTPS with No Verification (Testing)
```json
{
  "server_ip": "test-server.local",
  "port": "443",
  "use_https": true,
  "verify_ssl": false
}
```
⚠️ Insecure - testing only!

---

## Certificate Management

### View Saved Certificate Info
```python
from ssl_utils import SSLManager

ssl_mgr = SSLManager()
cert_info = ssl_mgr.get_certificate_info()
print(cert_info)
# Output: {
#   'subject': '...',
#   'issuer': '...',
#   'valid_from': '...',
#   'valid_until': '...',
#   'fingerprint': '...'
# }
```

### Re-download Certificate
```python
from ssl_utils import SSLManager

ssl_mgr = SSLManager()
success, error = ssl_mgr.download_server_certificate(
    server_url='https://your-server.com'
)

if success:
    print("✓ Certificate updated")
else:
    print(f"✗ Failed: {error}")
```

### Certificate Location
```
~/.kiwy-signage/
├── server_cert.pem      # The actual certificate
└── cert_info.json       # Certificate metadata
```

---

## Troubleshooting

### Problem: `SSL: CERTIFICATE_VERIFY_FAILED`

**Cause:** Certificate validation failed

**Solutions:**
1. Ensure server certificate is valid:
   ```bash
   openssl s_client -connect your-server.com:443
   ```

2. For self-signed certs, let player download it:
   - First connection will attempt download from `/api/certificate`
   - Subsequent connections use saved cert

3. Temporarily disable verification (testing only):
   ```json
   {"verify_ssl": false}
   ```

### Problem: `Connection refused` on HTTPS

**Cause:** HTTPS port (443) not accessible

**Solutions:**
1. Verify HTTPS is enabled on server
2. Check firewall rules allow port 443
3. Verify nginx/server is running:
   ```bash
   netstat -tuln | grep 443
   ```

### Problem: Certificate endpoint returns 404

**Cause:** `/api/certificate` endpoint not available

**Solutions:**
1. Verify server has certificate endpoint implemented
2. Check server URL is correct
3. Ensure CORS is enabled (if cross-origin)

### Problem: Slow HTTPS connections

**Possible Causes:**
1. SSL handshake timeout - increase timeout:
   ```python
   auth.authenticate(..., timeout=60)
   ```

2. Certificate revocation check - disable if not needed:
   - Not controlled by app, check system settings

---

## Migration Checklist

- [ ] Update `app_config.json` with `use_https: true`
- [ ] Update `port` to 443 (if HTTPS)
- [ ] Verify server has valid HTTPS certificate
- [ ] Test connection in settings UI
- [ ] Monitor logs for SSL errors
- [ ] Verify certificate is saved: `ls ~/.kiwy-signage/`
- [ ] Test playlist fetch works
- [ ] Test media downloads work
- [ ] Test status feedback works

---

## Debug Logging

Enable detailed logging for debugging HTTPS issues:

```python
import logging

# Enable debug logging
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger('ssl_utils')
logger.setLevel(logging.DEBUG)

# Now run your code and check logs
auth = PlayerAuth(use_https=True, verify_ssl=True)
auth.authenticate(...)
```

Look for messages like:
- `Using saved certificate: ~/.kiwy-signage/server_cert.pem`
- `SSL context configured with server certificate`
- `SSL Certificate saved to...`
- `SSL Error: ...` (if there are issues)

---

## Key Files

| File | Purpose |
|------|---------|
| `src/ssl_utils.py` | SSL/HTTPS utilities and certificate management |
| `src/player_auth.py` | Player authentication with HTTPS support |
| `src/get_playlists_v2.py` | Playlist fetching with HTTPS |
| `src/main.py` | Main app with HTTPS configuration |
| `config/app_config.json` | Configuration with HTTPS settings |

---

## Additional Resources

- [integration_guide.md](integration_guide.md) - Full server-side requirements
- [HTTPS_IMPLEMENTATION.md](HTTPS_IMPLEMENTATION.md) - Detailed implementation guide
- [SSL Certificate Files](~/.kiwy-signage/) - Local certificate storage

