<?php
// 斗鱼一起看房间爬虫（完整可用版）
header('Content-Type: text/html; charset=utf-8');

// 错误报告设置
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);

// 输出缓冲设置
while (ob_get_level()) ob_end_clean();
ini_set('zlib.output_compression', 0);
ini_set('implicit_flush', 1);

// 下载功能处理
if (isset($_GET['download']) && $_GET['download'] == '1') {
    $filename = '斗鱼ID.txt';
    if (file_exists($filename)) {
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename="'.basename($filename).'"');
        header('Content-Length: ' . filesize($filename));
        readfile($filename);
        exit;
    }
}

// 爬虫功能
if (isset($_GET['action']) && $_GET['action'] == 'start') {
    header('Content-Type: text/event-stream');
    header('Cache-Control: no-cache');
    
    function sendMessage($type, $content = '', $progress = 0) {
        echo "event: message\n";
        echo "data: " . json_encode([
            'type' => $type,
            'content' => $content,
            'progress' => $progress
        ]) . "\n\n";
        flush();
    }
    
    function getDouyuYqkRooms() {
        $baseUrl = "https://www.douyu.com/gapi/rkc/directory/2_208/";
        $page = 1;
        $roomList = [];
        $userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36";
        $maxPages = 10; // 安全限制
        $totalRooms = 0;
        
        sendMessage('log', '开始爬取斗鱼一起看房间信息...', 0);
        sendMessage('log', '注意：这将覆盖原有的斗鱼ID.txt文件内容', 0);
        
        while ($page <= $maxPages) {
            $url = $baseUrl . $page;
            $ch = curl_init();
            
            curl_setopt_array($ch, [
                CURLOPT_URL => $url,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_USERAGENT => $userAgent,
                CURLOPT_REFERER => 'https://www.douyu.com',
                CURLOPT_TIMEOUT => 15,
                CURLOPT_SSL_VERIFYPEER => false,
                CURLOPT_SSL_VERIFYHOST => false
            ]);
            
            $response = curl_exec($ch);
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            
            if ($httpCode != 200 || curl_errno($ch)) {
                sendMessage('error', '请求第 '.$page.' 页失败: '.curl_error($ch));
                break;
            }
            
            $data = json_decode($response, true);
            
            if (!isset($data['data']['rl']) || empty($data['data']['rl'])) {
                sendMessage('log', '没有更多数据了');
                break;
            }
            
            $pageRooms = count($data['data']['rl']);
            $totalRooms += $pageRooms;
            
            foreach ($data['data']['rl'] as $room) {
                if (!isset($room['rid']) || !isset($room['rn'])) continue;
                
                $roomInfo = $room['rn'] . "," . $room['rid'] . "\n";
                $roomList[] = $roomInfo;
                sendMessage('room', '获取房间: ' . $room['rn'] . ',' . $room['rid']);
            }
            
            $progress = min(100, (int)(($page / $maxPages) * 100));
            sendMessage('progress', '第 '.$page.' 页完成，获取 '.$pageRooms.' 个房间', $progress);
            
            $page++;
            sleep(1);
            curl_close($ch);
        }
        
        return $roomList;
    }
    
    $rooms = getDouyuYqkRooms();
    
    if (!empty($rooms)) {
        $filename = '斗鱼ID.txt';
        file_put_contents($filename, implode('', $rooms));
        sendMessage('success', '数据已保存到: '.$filename.'，共 '.count($rooms).' 个房间');
        
        // 发送样本数据
        $sample = array_slice($rooms, 0, 5);
        foreach ($sample as $room) {
            sendMessage('sample', trim($room));
        }
    } else {
        sendMessage('error', '未能获取任何房间信息');
    }
    
    sendMessage('complete');
    exit;
}

// 主界面HTML
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>斗鱼一起看房间爬虫</title>
    <style>
        body {
            font-family: "Microsoft YaHei", sans-serif;
            padding: 20px;
            background-color: #f5f5f5;
            color: #333;
            line-height: 1.6;
        }
        .container {
            max-width: 1000px;
            margin: 0 auto;
            background-color: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        h1 {
            color: #ff6b00;
            text-align: center;
            margin-bottom: 20px;
        }
        .btn-container {
            text-align: center;
            margin: 20px 0;
        }
        .start-btn {
            padding: 12px 24px;
            background-color: #ff6b00;
            color: white;
            border: none;
            border-radius: 5px;
            font-size: 16px;
            cursor: pointer;
            transition: background-color 0.3s;
        }
        .start-btn:hover {
            background-color: #e05d00;
        }
        .start-btn:disabled {
            background-color: #cccccc;
            cursor: not-allowed;
        }
        .log-container {
            border: 1px solid #ddd;
            padding: 15px;
            margin-top: 20px;
            background-color: #f9f9f9;
            max-height: 500px;
            overflow-y: auto;
            border-radius: 5px;
            font-family: Consolas, monospace;
            display: none;
        }
        .progress-container {
            width: 100%;
            background-color: #f1f1f1;
            border-radius: 5px;
            margin: 15px 0;
            display: none;
        }
        .progress-bar {
            width: 0%;
            height: 30px;
            background-color: #4CAF50;
            text-align: center;
            line-height: 30px;
            color: white;
            border-radius: 5px;
            transition: width 0.3s;
        }
        .message {
            padding: 5px 0;
            border-bottom: 1px solid #eee;
        }
        .log {
            color: #333;
        }
        .error {
            color: #d9534f;
            font-weight: bold;
        }
        .success {
            color: #5cb85c;
            font-weight: bold;
        }
        .sample {
            color: #337ab7;
            padding-left: 20px;
        }
        .download-container {
            text-align: center;
            margin: 20px 0;
            display: none;
        }
        .download-btn {
            display: inline-block;
            padding: 10px 20px;
            background-color: #ff6b00;
            color: white;
            text-decoration: none;
            border-radius: 5px;
            transition: background-color 0.3s;
        }
        .download-btn:hover {
            background-color: #e05d00;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>斗鱼一起看房间爬虫</h1>
        <div class="btn-container">
            <button class="start-btn" id="start-btn">一键获取斗鱼一起看房间</button>
        </div>
        <div class="progress-container" id="progress-container">
            <div class="progress-bar" id="progress-bar">0%</div>
        </div>
        <div class="log-container" id="log-container"></div>
        <div class="download-container" id="download-container">
            <a href="?download=1" class="download-btn" id="download-btn">下载斗鱼ID.txt</a>
        </div>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const startBtn = document.getElementById('start-btn');
            const logContainer = document.getElementById('log-container');
            const progressContainer = document.getElementById('progress-container');
            const progressBar = document.getElementById('progress-bar');
            const downloadContainer = document.getElementById('download-container');
            
            startBtn.addEventListener('click', function() {
                this.disabled = true;
                logContainer.style.display = 'block';
                progressContainer.style.display = 'block';
                logContainer.innerHTML = '';
                
                const eventSource = new EventSource('?action=start');
                
                eventSource.addEventListener('message', function(e) {
                    const data = JSON.parse(e.data);
                    
                    const div = document.createElement('div');
                    div.className = 'message ' + data.type;
                    
                    switch(data.type) {
                        case 'progress':
                            progressBar.style.width = data.progress + '%';
                            progressBar.textContent = data.progress + '%';
                            div.textContent = data.content;
                            break;
                        case 'room':
                            div.textContent = '🎬 ' + data.content;
                            break;
                        default:
                            div.textContent = data.content;
                    }
                    
                    logContainer.appendChild(div);
                    logContainer.scrollTop = logContainer.scrollHeight;
                });
                
                eventSource.addEventListener('error', function() {
                    eventSource.close();
                    startBtn.disabled = false;
                    downloadContainer.style.display = 'block';
                });
            });
        });
    </script>
</body>
</html>