# Kiwy-Signage Player Migration Guide
## Updating to DigiServer v2 Authentication

This guide explains how to update your Kiwy-Signage player to use the new secure authentication system with DigiServer v2.

## What Changed?

### Old System (v1)
- Direct API calls with hostname + quickconnect code on every request
- No persistent authentication
- Credentials sent with every API call

### New System (v2)
- **Step 1**: Authenticate once with hostname + password/quickconnect
- **Step 2**: Receive and save auth_code
- **Step 3**: Use auth_code for all subsequent API calls
- **Benefits**: More secure, faster, supports session management

## Migration Steps

### 1. Copy New Files

Copy the authentication modules to your Kiwy-Signage project:

```bash
cd /home/pi/Desktop/Kiwy-Signage/src/

# New files are already created:
# - player_auth.py (authentication module)
# - get_playlists_v2.py (updated playlist fetcher)
```

### 2. Update main.py Imports

In `main.py`, replace the old import:

```python
# OLD:
from get_playlists import (
    update_playlist_if_needed,
    send_playing_status_feedback,
    send_playlist_restart_feedback,
    send_player_error_feedback
)

# NEW:
from get_playlists_v2 import (
    update_playlist_if_needed,
    send_playing_status_feedback,
    send_playlist_restart_feedback,
    send_player_error_feedback
)
```

### 3. Add Authentication on Startup

In `main.py`, add authentication check in the `SignagePlayer` class:

```python
def build(self):
    """Build the application UI"""
    # Load configuration
    self.config = self.load_config()
    
    # NEW: Authenticate with server
    from player_auth import PlayerAuth
    auth = PlayerAuth()
    
    if not auth.is_authenticated():
        Logger.info("First time setup - authenticating...")
        from get_playlists_v2 import ensure_authenticated
        if not ensure_authenticated(self.config):
            Logger.error("❌ Failed to authenticate with server!")
            # Show error popup or retry
    else:
        Logger.info(f"✅ Authenticated as: {auth.get_player_name()}")
    
    # Continue with normal startup...
    return SignagePlayerWidget(config=self.config)
```

### 4. Update Server Configuration

Your existing `app_config.txt` works as-is! The new system uses the same fields:

```json
{
  "server_ip": "your-server-ip",
  "port": "5000",
  "screen_name": "player-001",
  "quickconnect_key": "QUICK123",
  ...
}
```

**Note**: `screen_name` is now used as `hostname` for authentication.

### 5. Testing

1. **Stop the old player**:
```bash
pkill -f main.py
```

2. **Delete old authentication data** (first time only):
```bash
rm -f /home/pi/Desktop/Kiwy-Signage/src/player_auth.json
```

3. **Start the updated player**:
```bash
cd /home/pi/Desktop/Kiwy-Signage/src/
python3 main.py
```

4. **Check logs for authentication**:
- Look for: `✅ Authentication successful`
- Or: `❌ Authentication failed: [error message]`

## Troubleshooting

### Authentication Fails

**Problem**: `❌ Authentication failed: Invalid credentials`

**Solution**:
1. Verify player exists in DigiServer v2:
   - Login to http://your-server:5000
   - Go to Players → check if hostname exists
   
2. Verify quickconnect code:
   - In DigiServer, check player's Quick Connect Code
   - Update `app_config.txt` with correct code

3. Check server URL:
   ```python
   # Test connection
   import requests
   response = requests.get('http://your-server:5000/api/health')
   print(response.json())  # Should show: {'status': 'healthy'}
   ```

### Auth Code Expired

**Problem**: Player was working, now shows auth errors

**Solution**:
```bash
# Clear saved auth and re-authenticate
rm /home/pi/Desktop/Kiwy-Signage/src/player_auth.json
# Restart player - will auto-authenticate
```

### Can't Connect to Server

**Problem**: `Cannot connect to server`

**Solution**:
1. Check server is running:
```bash
curl http://your-server:5000/api/health
```

2. Check network connectivity:
```bash
ping your-server-ip
```

3. Verify server URL in `app_config.txt`

## Configuration Files

### player_auth.json (auto-created)

This file stores the authentication token:

```json
{
  "hostname": "player-001",
  "auth_code": "rrX4JtM99e4e6ni0VCsuIstjTVQQqILXeRmGu_Ek2Ks",
  "player_id": 1,
  "player_name": "Demo Player",
  "group_id": 5,
  "orientation": "Landscape",
  "authenticated": true,
  "server_url": "http://your-server:5000"
}
```

**Important**: Keep this file secure! It contains your player's access token.

## Advanced: Custom Authentication

If you need custom authentication logic:

```python
from player_auth import PlayerAuth

# Initialize
auth = PlayerAuth(config_file='custom_auth.json')

# Authenticate with password instead of quickconnect
success, error = auth.authenticate(
    server_url='http://your-server:5000',
    hostname='player-001',
    password='your_secure_password'  # Use password instead
)

if success:
    print(f"✅ Authenticated as: {auth.get_player_name()}")
    
    # Get playlist
    playlist_data = auth.get_playlist()
    
    # Send heartbeat
    auth.send_heartbeat(status='playing')
    
    # Send feedback
    auth.send_feedback(
        message="Playing video.mp4",
        status="playing",
        playlist_version=5
    )
else:
    print(f"❌ Failed: {error}")
```

## Rollback to Old System

If you need to rollback:

```bash
cd /home/pi/Desktop/Kiwy-Signage/src/

# Rename new files
mv get_playlists_v2.py get_playlists_v2.py.backup
mv player_auth.py player_auth.py.backup

# Use old get_playlists.py (keep as-is)
# Old system will continue working with DigiServer v1
```

## Benefits of New System

✅ **More Secure**: Auth tokens instead of passwords in every request
✅ **Better Performance**: No bcrypt verification on every API call  
✅ **Session Management**: Server tracks player sessions
✅ **Easier Debugging**: Auth failures vs API failures are separate
✅ **Future-Proof**: Ready for token refresh, expiration, etc.

## Next Steps

Once migration is complete:

1. **Monitor player logs** for first 24 hours
2. **Verify playlist updates** are working
3. **Check feedback** is being received in DigiServer
4. **Update other players** one at a time

## Support

If you encounter issues:

1. **Check player logs**: `tail -f player.log`
2. **Check server logs**: DigiServer v2 logs in `instance/logs/`
3. **Test API manually**:
```bash
# Test authentication
curl -X POST http://your-server:5000/api/auth/player \
  -H "Content-Type: application/json" \
  -d '{"hostname":"player-001","quickconnect_code":"QUICK123"}'
```

---

**Migration completed!** Your Kiwy-Signage player now uses secure authentication with DigiServer v2. 🎉
