Exemplos Práticos

Casos de uso reais com código pronto para implementar

Criar Usuário

Exemplo completo de como criar um novo usuário no sistema On-Next TV.

baseUrl = rtrim($baseUrl, '/');
        $this->username = $username;
        $this->password = $password;
    }
    
    public function createUser($userData) {
        $url = $this->baseUrl . '/panel_api.php';
        
        $postData = array_merge([
            'username' => $this->username,
            'password' => $this->password,
            'action' => 'user',
            'sub' => 'create'
        ], $userData);
        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        
        if ($httpCode !== 200) {
            throw new Exception("HTTP Error: $httpCode");
        }
        
        return json_decode($response, true);
    }
}

// Uso prático
try {
    $api = new OnNextTVAPI(
        'https://dominio_da_instancia:25500',
        'admin',
        'admin'
    );
    
    $newUser = [
        'username' => 'novo_usuario',
        'password' => 'senha123',
        'email' => 'usuario@email.com',
        'max_connections' => 2,
        'is_trial' => 0,
        'exp_date' => '2025-12-31',
        'bouquet' => json_encode([1, 2, 3]) // IDs dos bouquets
    ];
    
    $result = $api->createUser($newUser);
    
    if ($result['success']) {
        echo "Usuário criado com sucesso! ID: " . $result['user_id'];
    } else {
        echo "Erro: " . $result['message'];
    }
    
} catch (Exception $e) {
    echo "Erro na requisição: " . $e->getMessage();
}
?>
import requests
import json
from datetime import datetime, timedelta

class OnNextTVAPI:
    def __init__(self, base_url, username, password):
        self.base_url = base_url.rstrip('/')
        self.username = username
        self.password = password
        self.session = requests.Session()
        
    def create_user(self, user_data):
        """Criar novo usuário no sistema"""
        url = f"{self.base_url}/panel_api.php"
        
        data = {
            'username': self.username,
            'password': self.password,
            'action': 'user',
            'sub': 'create',
            **user_data
        }
        
        try:
            response = self.session.post(url, data=data, verify=False)
            response.raise_for_status()
            return response.json()
        except requests.exceptions.RequestException as e:
            raise Exception(f"Erro na requisição: {e}")
        except json.JSONDecodeError:
            raise Exception("Resposta inválida do servidor")

# Uso prático
def main():
    api = OnNextTVAPI(
        'https://dominio_da_instancia:25500',
        'admin',
        'admin'
    )
    
    # Data de expiração (1 ano a partir de hoje)
    exp_date = (datetime.now() + timedelta(days=365)).strftime('%Y-%m-%d')
    
    new_user = {
        'username': 'novo_usuario',
        'password': 'senha123',
        'email': 'usuario@email.com',
        'max_connections': 2,
        'is_trial': 0,
        'exp_date': exp_date,
        'bouquet': json.dumps([1, 2, 3])  # IDs dos bouquets
    }
    
    try:
        result = api.create_user(new_user)
        
        if result.get('success'):
            print(f"Usuário criado com sucesso! ID: {result.get('user_id')}")
        else:
            print(f"Erro: {result.get('message')}")
            
    except Exception as e:
        print(f"Erro: {e}")

if __name__ == "__main__":
    main()
class OnNextTVAPI {
    constructor(baseUrl, username, password) {
        this.baseUrl = baseUrl.replace(/\/$/, '');
        this.username = username;
        this.password = password;
    }
    
    async createUser(userData) {
        const url = `${this.baseUrl}/panel_api.php`;
        
        const formData = new FormData();
        formData.append('username', this.username);
        formData.append('password', this.password);
        formData.append('action', 'user');
        formData.append('sub', 'create');
        
        // Adicionar dados do usuário
        Object.keys(userData).forEach(key => {
            formData.append(key, userData[key]);
        });
        
        try {
            const response = await fetch(url, {
                method: 'POST',
                body: formData
            });
            
            if (!response.ok) {
                throw new Error(`HTTP Error: ${response.status}`);
            }
            
            return await response.json();
        } catch (error) {
            throw new Error(`Erro na requisição: ${error.message}`);
        }
    }
}

// Uso prático
async function exemploCreateUser() {
    const api = new OnNextTVAPI(
        'https://dominio_da_instancia:25500',
        'admin',
        'admin'
    );
    
    // Data de expiração (1 ano a partir de hoje)
    const expDate = new Date();
    expDate.setFullYear(expDate.getFullYear() + 1);
    
    const newUser = {
        username: 'novo_usuario',
        password: 'senha123',
        email: 'usuario@email.com',
        max_connections: 2,
        is_trial: 0,
        exp_date: expDate.toISOString().split('T')[0],
        bouquet: JSON.stringify([1, 2, 3]) // IDs dos bouquets
    };
    
    try {
        const result = await api.createUser(newUser);
        
        if (result.success) {
            console.log(`Usuário criado com sucesso! ID: ${result.user_id}`);
        } else {
            console.error(`Erro: ${result.message}`);
        }
    } catch (error) {
        console.error(`Erro: ${error.message}`);
    }
}

// Executar exemplo
exemploCreateUser();
# Criar usuário via cURL
curl -X POST "https://dominio_da_instancia:25500/panel_api.php" \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "username=admin" \
  -d "password=admin" \
  -d "action=user" \
  -d "sub=create" \
  -d "username=novo_usuario" \
  -d "password=senha123" \
  -d "email=usuario@email.com" \
  -d "max_connections=2" \
  -d "is_trial=0" \
  -d "exp_date=2025-12-31" \
  -d "bouquet=[1,2,3]"

# Resposta esperada:
# {
#   "success": true,
#   "user_id": 123,
#   "message": "Usuário criado com sucesso"
# }

Listar Canais

Como obter e filtrar a lista completa de canais disponíveis.

api = new OnNextTVAPI($baseUrl, $username, $password);
    }
    
    public function getAllChannels() {
        return $this->makeRequest('get_live_streams');
    }
    
    public function getChannelsByCategory($categoryId) {
        return $this->makeRequest('get_live_streams', ['category_id' => $categoryId]);
    }
    
    public function getChannelCategories() {
        return $this->makeRequest('get_live_categories');
    }
    
    public function searchChannels($searchTerm) {
        $allChannels = $this->getAllChannels();
        
        return array_filter($allChannels, function($channel) use ($searchTerm) {
            return stripos($channel['name'], $searchTerm) !== false;
        });
    }
    
    public function getChannelsWithArchive() {
        $allChannels = $this->getAllChannels();
        
        return array_filter($allChannels, function($channel) {
            return isset($channel['tv_archive']) && $channel['tv_archive'] == 1;
        });
    }
    
    private function makeRequest($action, $params = []) {
        $url = $this->api->baseUrl . '/player_api.php';
        
        $postData = array_merge([
            'username' => $this->api->username,
            'password' => $this->api->password,
            'action' => $action
        ], $params);
        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        
        $response = curl_exec($ch);
        curl_close($ch);
        
        return json_decode($response, true);
    }
}

// Exemplo de uso
$channelManager = new ChannelManager(
    'https://dominio_da_instancia:25500',
    'admin',
    'admin'
);

// Listar todas as categorias
$categories = $channelManager->getChannelCategories();
echo "Categorias disponíveis:\n";
foreach ($categories as $category) {
    echo "- {$category['category_name']} (ID: {$category['category_id']})\n";
}

// Listar canais de uma categoria específica
$sportsChannels = $channelManager->getChannelsByCategory(2); // ID da categoria Esportes
echo "\nCanais de Esportes:\n";
foreach ($sportsChannels as $channel) {
    echo "- {$channel['name']} (ID: {$channel['stream_id']})\n";
}

// Buscar canais por nome
$globoChannels = $channelManager->searchChannels('Globo');
echo "\nCanais com 'Globo' no nome:\n";
foreach ($globoChannels as $channel) {
    echo "- {$channel['name']}\n";
}

// Canais com arquivo de TV (replay)
$archiveChannels = $channelManager->getChannelsWithArchive();
echo "\nCanais com Arquivo de TV:\n";
foreach ($archiveChannels as $channel) {
    echo "- {$channel['name']} ({$channel['tv_archive_duration']} dias)\n";
}
?>
import requests
import json
from typing import List, Dict, Optional

class ChannelManager:
    def __init__(self, base_url: str, username: str, password: str):
        self.base_url = base_url.rstrip('/')
        self.username = username
        self.password = password
        
    def get_all_channels(self) -> List[Dict]:
        """Obter todos os canais disponíveis"""
        return self._make_request('get_live_streams')
        
    def get_channels_by_category(self, category_id: int) -> List[Dict]:
        """Obter canais de uma categoria específica"""
        return self._make_request('get_live_streams', {'category_id': category_id})
        
    def get_channel_categories(self) -> List[Dict]:
        """Obter todas as categorias de canais"""
        return self._make_request('get_live_categories')
        
    def search_channels(self, search_term: str) -> List[Dict]:
        """Buscar canais por nome"""
        all_channels = self.get_all_channels()
        
        return [
            channel for channel in all_channels
            if search_term.lower() in channel['name'].lower()
        ]
        
    def get_channels_with_archive(self) -> List[Dict]:
        """Obter canais que possuem arquivo de TV"""
        all_channels = self.get_all_channels()
        
        return [
            channel for channel in all_channels
            if channel.get('tv_archive') == 1
        ]
        
    def get_channel_info(self, stream_id: int) -> Optional[Dict]:
        """Obter informações detalhadas de um canal"""
        channels = self.get_all_channels()
        
        for channel in channels:
            if channel['stream_id'] == stream_id:
                return channel
        return None
        
    def _make_request(self, action: str, params: Dict = None) -> List[Dict]:
        """Fazer requisição para a API"""
        url = f"{self.base_url}/player_api.php"
        
        data = {
            'username': self.username,
            'password': self.password,
            'action': action
        }
        
        if params:
            data.update(params)
            
        try:
            response = requests.post(url, data=data, verify=False)
            response.raise_for_status()
            return response.json()
        except Exception as e:
            print(f"Erro na requisição: {e}")
            return []

# Exemplo de uso
def main():
    channel_manager = ChannelManager(
        'https://dominio_da_instancia:25500',
        'admin',
        'admin'
    )
    
    # Listar categorias
    categories = channel_manager.get_channel_categories()
    print("Categorias disponíveis:")
    for category in categories:
        print(f"- {category['category_name']} (ID: {category['category_id']})")
    
    # Canais de esportes
    sports_channels = channel_manager.get_channels_by_category(2)
    print(f"\nEncontrados {len(sports_channels)} canais de esportes")
    
    # Buscar canais específicos
    globo_channels = channel_manager.search_channels('Globo')
    print(f"\nCanais com 'Globo': {len(globo_channels)}")
    for channel in globo_channels:
        print(f"- {channel['name']} (ID: {channel['stream_id']})")
    
    # Canais com arquivo
    archive_channels = channel_manager.get_channels_with_archive()
    print(f"\nCanais com arquivo de TV: {len(archive_channels)}")

if __name__ == "__main__":
    main()
class ChannelManager {
    constructor(baseUrl, username, password) {
        this.baseUrl = baseUrl.replace(/\/$/, '');
        this.username = username;
        this.password = password;
    }
    
    async getAllChannels() {
        return await this.makeRequest('get_live_streams');
    }
    
    async getChannelsByCategory(categoryId) {
        return await this.makeRequest('get_live_streams', { category_id: categoryId });
    }
    
    async getChannelCategories() {
        return await this.makeRequest('get_live_categories');
    }
    
    async searchChannels(searchTerm) {
        const allChannels = await this.getAllChannels();
        
        return allChannels.filter(channel => 
            channel.name.toLowerCase().includes(searchTerm.toLowerCase())
        );
    }
    
    async getChannelsWithArchive() {
        const allChannels = await this.getAllChannels();
        
        return allChannels.filter(channel => 
            channel.tv_archive === 1
        );
    }
    
    async getChannelInfo(streamId) {
        const channels = await this.getAllChannels();
        return channels.find(channel => channel.stream_id == streamId);
    }
    
    async makeRequest(action, params = {}) {
        const url = `${this.baseUrl}/player_api.php`;
        
        const formData = new FormData();
        formData.append('username', this.username);
        formData.append('password', this.password);
        formData.append('action', action);
        
        Object.keys(params).forEach(key => {
            formData.append(key, params[key]);
        });
        
        try {
            const response = await fetch(url, {
                method: 'POST',
                body: formData
            });
            
            if (!response.ok) {
                throw new Error(`HTTP Error: ${response.status}`);
            }
            
            return await response.json();
        } catch (error) {
            console.error(`Erro na requisição: ${error.message}`);
            return [];
        }
    }
}

// Exemplo de uso
async function exemploListarCanais() {
    const channelManager = new ChannelManager(
        'https://dominio_da_instancia:25500',
        'admin',
        'admin'
    );
    
    try {
        // Listar categorias
        const categories = await channelManager.getChannelCategories();
        console.log('Categorias disponíveis:');
        categories.forEach(category => {
            console.log(`- ${category.category_name} (ID: ${category.category_id})`);
        });
        
        // Canais de uma categoria específica
        const sportsChannels = await channelManager.getChannelsByCategory(2);
        console.log(`\nCanais de esportes: ${sportsChannels.length}`);
        
        // Buscar canais específicos
        const globoChannels = await channelManager.searchChannels('Globo');
        console.log('\nCanais com "Globo":');
        globoChannels.forEach(channel => {
            console.log(`- ${channel.name} (ID: ${channel.stream_id})`);
        });
        
        // Canais com arquivo de TV
        const archiveChannels = await channelManager.getChannelsWithArchive();
        console.log(`\nCanais com arquivo: ${archiveChannels.length}`);
        
    } catch (error) {
        console.error(`Erro: ${error.message}`);
    }
}

// Executar exemplo
exemploListarCanais();

Relatórios e Estatísticas

Gerar relatórios de uso e estatísticas de conexões do sistema.

api = new OnNextTVAPI($baseUrl, $username, $password);
    }
    
    public function getSystemStats() {
        $url = $this->api->baseUrl . '/api/extended/stats.php';
        $params = [
            'username' => $this->api->username,
            'password' => $this->api->password,
            'action' => 'stats'
        ];
        
        return $this->makeRequest($url, $params);
    }
    
    public function getUsersList($limit = 50, $offset = 0) {
        $url = $this->api->baseUrl . '/api/extended/stats.php';
        $params = [
            'username' => $this->api->username,
            'password' => $this->api->password,
            'action' => 'users',
            'limit' => $limit,
            'offset' => $offset
        ];
        
        return $this->makeRequest($url, $params);
    }
    
    public function getStreamsList($status = 'all', $limit = 50) {
        $url = $this->api->baseUrl . '/api/extended/stats.php';
        $params = [
            'username' => $this->api->username,
            'password' => $this->api->password,
            'action' => 'streams',
            'status' => $status,
            'limit' => $limit
        ];
        
        return $this->makeRequest($url, $params);
    }
    
    public function generateDashboardReport() {
        $stats = $this->getSystemStats();
        
        return [
            'resumo' => [
                'usuarios_ativos' => $stats['data']['users_active'],
                'usuarios_total' => $stats['data']['users_total'],
                'streams_ativos' => $stats['data']['streams_active'],
                'conexoes_ativas' => $stats['data']['connections_active'],
                'load_servidor' => $stats['data']['server_load'],
                'uptime' => $stats['data']['server_uptime']
            ],
            'percentuais' => [
                'usuarios_atividade' => round(($stats['data']['users_active'] / $stats['data']['users_total']) * 100, 2),
                'streams_funcionando' => round(($stats['data']['streams_active'] / $stats['data']['streams_total']) * 100, 2)
            ],
            'alertas' => $this->generateAlerts($stats['data'])
        ];
    }
    
    private function generateAlerts($stats) {
        $alerts = [];
        
        if ($stats['server_load'] > 2.0) {
            $alerts[] = [
                'tipo' => 'warning',
                'mensagem' => 'Load do servidor alto: ' . $stats['server_load']
            ];
        }
        
        if ($stats['connections_active'] > ($stats['users_total'] * 1.5)) {
            $alerts[] = [
                'tipo' => 'info',
                'mensagem' => 'Muitas conexões simultâneas detectadas'
            ];
        }
        
        $usage_percent = ($stats['users_active'] / $stats['users_total']) * 100;
        if ($usage_percent < 20) {
            $alerts[] = [
                'tipo' => 'info',
                'mensagem' => 'Baixa utilização do sistema: ' . round($usage_percent, 1) . '%'
            ];
        }
        
        return $alerts;
    }
    
    private function makeRequest($url, $params) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        
        $response = curl_exec($ch);
        curl_close($ch);
        
        return json_decode($response, true);
    }
}

// Exemplo de uso - Relatório Dashboard
$reports = new ReportsManager(
    'https://dominio_da_instancia:25500',
    'admin',
    'admin'
);

$dashboardData = $reports->generateDashboardReport();

echo "=== RELATÓRIO DO SISTEMA ===\n";
echo "Usuários Ativos: {$dashboardData['resumo']['usuarios_ativos']}/{$dashboardData['resumo']['usuarios_total']}\n";
echo "Taxa de Atividade: {$dashboardData['percentuais']['usuarios_atividade']}%\n";
echo "Streams Funcionando: {$dashboardData['resumo']['streams_ativos']}\n";
echo "Conexões Ativas: {$dashboardData['resumo']['conexoes_ativas']}\n";
echo "Load do Servidor: {$dashboardData['resumo']['load_servidor']}\n";
echo "Uptime: {$dashboardData['resumo']['uptime']}\n";

if (!empty($dashboardData['alertas'])) {
    echo "\n=== ALERTAS ===\n";
    foreach ($dashboardData['alertas'] as $alert) {
        echo "[{$alert['tipo']}] {$alert['mensagem']}\n";
    }
}
?>
import requests
import json
from datetime import datetime
from typing import Dict, List

class ReportsManager:
    def __init__(self, base_url: str, username: str, password: str):
        self.base_url = base_url.rstrip('/')
        self.username = username
        self.password = password
        
    def get_system_stats(self) -> Dict:
        """Obter estatísticas gerais do sistema"""
        return self._make_request('/api/extended/stats.php', {'action': 'stats'})
        
    def get_users_list(self, limit: int = 50, offset: int = 0) -> Dict:
        """Obter lista de usuários"""
        return self._make_request('/api/extended/stats.php', {
            'action': 'users',
            'limit': limit,
            'offset': offset
        })
        
    def get_streams_list(self, status: str = 'all', limit: int = 50) -> Dict:
        """Obter lista de streams"""
        return self._make_request('/api/extended/stats.php', {
            'action': 'streams',
            'status': status,
            'limit': limit
        })
        
    def generate_dashboard_report(self) -> Dict:
        """Gerar relatório completo do dashboard"""
        stats = self.get_system_stats()
        
        if not stats or 'data' not in stats:
            return {'error': 'Não foi possível obter estatísticas'}
            
        data = stats['data']
        
        return {
            'resumo': {
                'usuarios_ativos': data.get('users_active', 0),
                'usuarios_total': data.get('users_total', 0),
                'streams_ativos': data.get('streams_active', 0),
                'streams_total': data.get('streams_total', 0),
                'conexoes_ativas': data.get('connections_active', 0),
                'load_servidor': data.get('server_load', 0),
                'uptime': data.get('server_uptime', 'N/A'),
                'memoria_uso': data.get('memory_usage', 'N/A')
            },
            'percentuais': self._calculate_percentages(data),
            'alertas': self._generate_alerts(data),
            'gerado_em': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        }
        
    def generate_users_report(self) -> Dict:
        """Gerar relatório detalhado de usuários"""
        users_data = self.get_users_list(limit=500)
        
        if not users_data or 'data' not in users_data:
            return {'error': 'Não foi possível obter dados dos usuários'}
            
        users = users_data['data']
        
        # Análise dos usuários
        total_users = len(users)
        active_users = sum(1 for user in users if user.get('enabled'))
        expired_users = sum(1 for user in users if self._is_expired(user.get('expires', 0)))
        
        return {
            'total_usuarios': total_users,
            'usuarios_ativos': active_users,
            'usuarios_expirados': expired_users,
            'taxa_ativacao': round((active_users / total_users) * 100, 2) if total_users > 0 else 0,
            'usuarios_recentes': self._get_recent_users(users),
            'usuarios_expirando': self._get_expiring_users(users)
        }
        
    def _calculate_percentages(self, data: Dict) -> Dict:
        """Calcular percentuais"""
        percentages = {}
        
        if data.get('users_total', 0) > 0:
            percentages['usuarios_atividade'] = round(
                (data.get('users_active', 0) / data['users_total']) * 100, 2
            )
            
        if data.get('streams_total', 0) > 0:
            percentages['streams_funcionando'] = round(
                (data.get('streams_active', 0) / data['streams_total']) * 100, 2
            )
            
        return percentages
        
    def _generate_alerts(self, data: Dict) -> List[Dict]:
        """Gerar alertas baseados nos dados"""
        alerts = []
        
        # Alerta de load alto
        server_load = data.get('server_load', 0)
        if server_load > 2.0:
            alerts.append({
                'tipo': 'warning',
                'mensagem': f'Load do servidor alto: {server_load}'
            })
            
        # Alerta de muitas conexões
        connections = data.get('connections_active', 0)
        total_users = data.get('users_total', 0)
        if connections > (total_users * 1.5):
            alerts.append({
                'tipo': 'info',
                'mensagem': 'Muitas conexões simultâneas detectadas'
            })
            
        # Alerta de baixa utilização
        if total_users > 0:
            usage_percent = (data.get('users_active', 0) / total_users) * 100
            if usage_percent < 20:
                alerts.append({
                    'tipo': 'info',
                    'mensagem': f'Baixa utilização do sistema: {usage_percent:.1f}%'
                })
                
        return alerts
        
    def _is_expired(self, exp_timestamp: int) -> bool:
        """Verificar se usuário está expirado"""
        if not exp_timestamp:
            return False
        return exp_timestamp < datetime.now().timestamp()
        
    def _get_recent_users(self, users: List[Dict]) -> List[Dict]:
        """Obter usuários criados recentemente (últimos 7 dias)"""
        week_ago = datetime.now().timestamp() - (7 * 24 * 3600)
        
        return [
            user for user in users 
            if user.get('created', 0) > week_ago
        ]
        
    def _get_expiring_users(self, users: List[Dict]) -> List[Dict]:
        """Obter usuários que expiram em breve (próximos 7 dias)"""
        week_from_now = datetime.now().timestamp() + (7 * 24 * 3600)
        
        return [
            user for user in users 
            if 0 < user.get('expires', 0) < week_from_now
        ]
        
    def _make_request(self, endpoint: str, params: Dict) -> Dict:
        """Fazer requisição para a API"""
        url = f"{self.base_url}{endpoint}"
        
        data = {
            'username': self.username,
            'password': self.password,
            **params
        }
        
        try:
            response = requests.post(url, data=data, verify=False)
            response.raise_for_status()
            return response.json()
        except Exception as e:
            print(f"Erro na requisição: {e}")
            return {}

# Exemplo de uso
def main():
    reports = ReportsManager(
        'https://dominio_da_instancia:25500',
        'admin',
        'admin'
    )
    
    # Relatório do dashboard
    dashboard = reports.generate_dashboard_report()
    
    print("=== RELATÓRIO DO SISTEMA ===")
    print(f"Usuários Ativos: {dashboard['resumo']['usuarios_ativos']}/{dashboard['resumo']['usuarios_total']}")
    print(f"Streams Funcionando: {dashboard['resumo']['streams_ativos']}/{dashboard['resumo']['streams_total']}")
    print(f"Conexões Ativas: {dashboard['resumo']['conexoes_ativas']}")
    print(f"Load do Servidor: {dashboard['resumo']['load_servidor']}")
    print(f"Uptime: {dashboard['resumo']['uptime']}")
    
    if dashboard['alertas']:
        print("\n=== ALERTAS ===")
        for alert in dashboard['alertas']:
            print(f"[{alert['tipo']}] {alert['mensagem']}")
    
    # Relatório de usuários
    users_report = reports.generate_users_report()
    print(f"\n=== RELATÓRIO DE USUÁRIOS ===")
    print(f"Total: {users_report['total_usuarios']}")
    print(f"Ativos: {users_report['usuarios_ativos']}")
    print(f"Taxa de Ativação: {users_report['taxa_ativacao']}%")

if __name__ == "__main__":
    main()

Integração ERP

Como integrar com sistemas ERP externos como HubSoft.

Fluxo da Integração: HubSoft gera URL → On-Next TV consulta URL → Processa dados dos usuários
baseUrl = rtrim($baseUrl, '/');
        $this->username = $username;
        $this->password = $password;
    }
    
    public function syncWithHubSoft() {
        $url = $this->baseUrl . '/admin/api_erp_sync.php';
        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        
        if ($httpCode !== 200) {
            throw new Exception("HTTP Error: $httpCode");
        }
        
        return json_decode($response, true);
    }
    
    public function getERPLogs() {
        $url = $this->baseUrl . '/admin/api_erp_logs.php';
        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        
        $response = curl_exec($ch);
        return json_decode($response, true);
    }
    
    public function processHubSoftData($hubsoftData) {
        $processedUsers = [];
        
        foreach ($hubsoftData as $userData) {
            // Mapear dados do HubSoft para formato do On-Next TV
            $mappedUser = [
                'username' => $userData['login_autenticacao'] ?? $userData['cpf_cnpj'],
                'password' => $userData['senha_usuario_login_autenticacao'] ?? $this->generatePassword(),
                'email' => $userData['email_primario'] ?? '',
                'max_connections' => 2,
                'is_trial' => 0,
                'exp_date' => $this->formatExpDate($userData['data_vencimento'] ?? null),
                'enabled' => $userData['ativo'] ?? 1
            ];
            
            $processedUsers[] = $mappedUser;
        }
        
        return $processedUsers;
    }
    
    public function createUsersFromERP($users) {
        $results = [];
        
        foreach ($users as $userData) {
            try {
                $result = $this->createUser($userData);
                $results[] = [
                    'username' => $userData['username'],
                    'status' => 'success',
                    'user_id' => $result['user_id'] ?? null
                ];
            } catch (Exception $e) {
                $results[] = [
                    'username' => $userData['username'],
                    'status' => 'error',
                    'message' => $e->getMessage()
                ];
            }
        }
        
        return $results;
    }
    
    private function createUser($userData) {
        $url = $this->baseUrl . '/panel_api.php';
        
        $postData = array_merge([
            'username' => $this->username,
            'password' => $this->password,
            'action' => 'user',
            'sub' => 'create'
        ], $userData);
        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        
        $response = curl_exec($ch);
        curl_close($ch);
        
        $result = json_decode($response, true);
        
        if (!$result['success']) {
            throw new Exception($result['message'] ?? 'Erro ao criar usuário');
        }
        
        return $result;
    }
    
    private function generatePassword($length = 8) {
        return substr(str_shuffle('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'), 0, $length);
    }
    
    private function formatExpDate($date) {
        if (!$date) {
            // 1 ano a partir de hoje se não especificado
            return date('Y-m-d', strtotime('+1 year'));
        }
        
        // Converter diferentes formatos de data para Y-m-d
        $timestamp = strtotime($date);
        return $timestamp ? date('Y-m-d', $timestamp) : date('Y-m-d', strtotime('+1 year'));
    }
}

// Exemplo de uso completo
try {
    $erp = new ERPIntegration(
        'https://dominio_da_instancia:25500',
        'admin',
        'admin'
    );
    
    echo "Iniciando sincronização com HubSoft...\n";
    
    // Executar sincronização
    $syncResult = $erp->syncWithHubSoft();
    
    if ($syncResult['status'] === 'success') {
        echo "Sincronização realizada com sucesso!\n";
        echo "Total de usuários encontrados: {$syncResult['total_users']}\n";
        
        // Processar dados se houver usuários
        if (!empty($syncResult['data']) && is_array($syncResult['data'])) {
            $processedUsers = $erp->processHubSoftData($syncResult['data']);
            
            echo "Processando " . count($processedUsers) . " usuários...\n";
            
            // Criar usuários no sistema
            $creationResults = $erp->createUsersFromERP($processedUsers);
            
            $success = 0;
            $errors = 0;
            
            foreach ($creationResults as $result) {
                if ($result['status'] === 'success') {
                    $success++;
                    echo "✓ Usuário {$result['username']} criado com sucesso\n";
                } else {
                    $errors++;
                    echo "✗ Erro ao criar {$result['username']}: {$result['message']}\n";
                }
            }
            
            echo "\nResumo: $success usuários criados, $errors erros\n";
        } else {
            echo "Nenhum usuário encontrado para processar.\n";
        }
        
    } else {
        echo "Erro na sincronização: {$syncResult['error']}\n";
        
        // Mostrar logs para debug
        $logs = $erp->getERPLogs();
        if ($logs['status'] === 'success' && !empty($logs['logs'])) {
            echo "\nÚltimos logs:\n";
            foreach (array_slice($logs['logs'], -5) as $log) {
                echo "- $log\n";
            }
        }
    }
    
} catch (Exception $e) {
    echo "Erro fatal: " . $e->getMessage() . "\n";
}
?>