| .gitignore | ●●●●● patch | view | raw | blame | history | |
| fluttergamebox/lib/api/api_client.dart | ●●●●● patch | view | raw | blame | history | |
| server/admin/index.html | ●●●●● patch | view | raw | blame | history | |
| server/build-linux.ps1 | ●●●●● patch | view | raw | blame | history | |
| server/config.yaml | ●●●●● patch | view | raw | blame | history | |
| server/config/config.go | ●●●●● patch | view | raw | blame | history | |
| server/config/db.go | ●●●●● patch | view | raw | blame | history | |
| server/download/index.html | ●●●●● patch | view | raw | blame | history | |
| server/go.mod | ●●●●● patch | view | raw | blame | history | |
| server/handlers/versions.go | ●●●●● patch | view | raw | blame | history | |
| server/main.go | ●●●●● patch | view | raw | blame | history | |
| server/models/models.go | ●●●●● patch | view | raw | blame | history | |
| server/showcase/index.html | ●●●●● patch | view | raw | blame | history |
.gitignore
@@ -103,6 +103,7 @@ # Go 服务端相关 server/*.exe server/gamebox-server server/dist/ # 运行时上传目录(封面、游戏包等,不入库) server/uploads/ fluttergamebox/lib/api/api_client.dart
@@ -1,8 +1,11 @@ import 'package:dio/dio.dart'; import 'package:flutter/foundation.dart'; import 'package:shared_preferences/shared_preferences.dart'; class ApiClient { static const baseUrl = 'http://localhost:8080'; // 生产环境(release 包)用线上地址,测试环境(debug 运行)用本地地址 static final baseUrl = kReleaseMode ? 'http://117.72.199.143:8091' : 'http://localhost:8080'; static final Dio dio = Dio(BaseOptions( baseUrl: baseUrl, connectTimeout: const Duration(seconds: 10), server/admin/index.html
@@ -100,6 +100,7 @@ <button data-tab="cats" onclick="switchTab('cats')">类别管理</button> <button data-tab="ann" onclick="switchTab('ann')">公告设置</button> <button data-tab="reset" onclick="switchTab('reset')">密码重置</button> <button data-tab="versions" onclick="switchTab('versions')">版本管理</button> </div> <button id="logoutBtn" onclick="logout()">退出登录</button> </div> @@ -186,6 +187,19 @@ <tbody id="resetTable"></tbody> </table> </div> <!-- 客户端版本管理 --> <div id="tab-versions" class="panel hidden"> <h2>客户端版本管理</h2> <p style="color:#888;font-size:12px;margin-bottom:14px">上传客户端安装包(整个 Release 目录打成的 zip)。最新一条记录会展示在公开下载页 <a href="/download" target="_blank" style="color:#4a92ff">/download</a>,用户无需登录即可下载。</p> <div class="toolbar"> <button class="btn" onclick="showVersionModal()">+ 上传新版本</button> </div> <table> <thead><tr><th>ID</th><th>版本号</th><th>文件大小</th><th>更新说明</th><th>下载次数</th><th>发布时间</th><th>操作</th></tr></thead> <tbody id="versionTable"></tbody> </table> </div> </div> </div> @@ -241,6 +255,27 @@ <div id="toast" class="toast"></div> <!-- 版本编辑弹窗 --> <div id="versionModal" class="modal-mask hidden"> <div class="modal"> <h3 id="versionModalTitle">上传新版本</h3> <input type="hidden" id="v_id"> <div class="form-row"><label>版本号 *(如 1.0.0)</label><input id="v_version" placeholder="1.0.0"></div> <div class="form-row"><label>更新说明(换行分隔,展示在下载页)</label><textarea id="v_notes" placeholder="新增xxx功能 修复xxx问题"></textarea></div> <div class="upload-box"> <div class="hint">客户端安装包(整个 Release 目录打成的 zip)</div> <input type="file" accept=".zip" onchange="uploadVersionFile(this)"> <div id="v_file_list"></div> <input type="hidden" id="v_file_url"> <input type="hidden" id="v_file_size"> </div> <div style="display:flex;gap:10px;justify-content:flex-end;margin-top:16px"> <button class="btn btn-gray" onclick="hideVersionModal()">取消</button> <button class="btn" id="saveVersionBtn" onclick="saveVersion()">保存</button> </div> </div> </div> <!-- 工具编辑弹窗 --> <div id="toolModal" class="modal-mask hidden"> <div class="modal"> @@ -309,11 +344,11 @@ function enterPanel() { document.getElementById('loginPage').style.display = 'none'; document.getElementById('mainPage').style.display = 'flex'; loadStats(); loadKeys(1); loadGames(); loadCategories(); loadAnnouncement(); loadTools(); loadResetRequests(); loadStats(); loadKeys(1); loadGames(); loadCategories(); loadAnnouncement(); loadTools(); loadResetRequests(); loadVersions(); } function switchTab(tab) { document.querySelectorAll('.nav-tabs button').forEach(b => b.classList.toggle('active', b.dataset.tab === tab)); ['keys','games','cats','ann','tools','reset'].forEach(t => document.getElementById('tab-' + t).classList.toggle('hidden', t !== tab)); ['keys','games','cats','ann','tools','reset','versions'].forEach(t => document.getElementById('tab-' + t).classList.toggle('hidden', t !== tab)); } async function loadStats() { @@ -644,6 +679,97 @@ loadTools(); } /* ---------- 客户端版本管理 ---------- */ async function loadVersions() { const res = await api('/admin/api/versions'); if (res.code !== 0) return; const rows = res.data.map((v, i) => `<tr> <td>${v.id}</td> <td><span class="tag ${i===0?'tag-green':'tag-gray'}">${v.version}${i===0?' · 最新':''}</span></td> <td>${v.file_size || '-'}</td> <td style="max-width:260px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap" title="${(v.notes||'').replace(/"/g,'"')}">${(v.notes||'-').replace(/\n/g,';')}</td> <td>${v.download_count}</td> <td>${(v.created_at || '').replace('T', ' ').slice(0, 19)}</td> <td> <button class="btn btn-sm" onclick='showVersionModal(${JSON.stringify(v).replace(/'/g,"'")})'>修改</button> <button class="btn btn-sm btn-danger" onclick="deleteVersion(${v.id})">删除</button> </td></tr>`).join(''); document.getElementById('versionTable').innerHTML = rows || '<tr><td colspan="7" style="text-align:center;color:#666">暂无版本,请上传第一个客户端版本</td></tr>'; } function showVersionModal(v) { document.getElementById('versionModalTitle').innerText = v ? '修改版本' : '上传新版本'; document.getElementById('v_id').value = v ? v.id : ''; document.getElementById('v_version').value = v ? v.version : ''; document.getElementById('v_notes').value = v ? (v.notes || '') : ''; document.getElementById('v_file_url').value = v ? (v.file_url || '') : ''; document.getElementById('v_file_size').value = v ? (v.file_size || '') : ''; renderVersionFile(); document.getElementById('versionModal').classList.remove('hidden'); } function hideVersionModal() { document.getElementById('versionModal').classList.add('hidden'); } function renderVersionFile(name, pct) { const url = document.getElementById('v_file_url').value; const size = document.getElementById('v_file_size').value; if (pct !== undefined) { document.getElementById('v_file_list').innerHTML = `<div class="file-item"><span>${name} 上传中 ${pct}%</span></div>`; } else { document.getElementById('v_file_list').innerHTML = url ? `<div class="file-item"><span>${url}${size ? '(' + size + ')' : ''}</span></div>` : ''; } } async function uploadVersionFile(input) { if (!input.files.length) return; const f = input.files[0]; const fd = new FormData(); fd.append('file', f); fd.append('type', 'file'); const btn = document.getElementById('saveVersionBtn'); btn.disabled = true; btn.style.opacity = '0.5'; try { const res = await new Promise((resolve, reject) => { const xhr = new XMLHttpRequest(); xhr.open('POST', '/admin/api/upload'); if (token) xhr.setRequestHeader('Authorization', 'Bearer ' + token); xhr.upload.onprogress = e => { if (e.lengthComputable) renderVersionFile(f.name, Math.floor(e.loaded / e.total * 100)); }; xhr.onload = () => { try { resolve(JSON.parse(xhr.responseText)); } catch (err) { reject(err); } }; xhr.onerror = () => reject(new Error('网络错误')); xhr.send(fd); }); if (res.code !== 0) return toast(res.msg || '上传失败', true); document.getElementById('v_file_url').value = res.data.url; document.getElementById('v_file_size').value = res.data.size; // 未填版本号时用文件名里的版本号(如 gamebox-1.0.0.zip) if (!document.getElementById('v_version').value.trim()) { const m = f.name.match(/(\d+\.\d+(\.\d+)?)/); if (m) document.getElementById('v_version').value = m[1]; } toast('上传成功'); } catch (e) { toast('上传失败(' + e.message + ')', true); } finally { btn.disabled = false; btn.style.opacity = ''; renderVersionFile(); } } async function saveVersion() { const body = { id: parseInt(document.getElementById('v_id').value) || 0, version: document.getElementById('v_version').value.trim(), notes: document.getElementById('v_notes').value, file_url: document.getElementById('v_file_url').value.trim(), file_size: document.getElementById('v_file_size').value.trim(), }; if (!body.version) return toast('请填写版本号', true); if (!body.file_url) return toast('请上传客户端安装包', true); const res = await api('/admin/api/versions', {method: 'POST', body}); toast(res.msg, res.code !== 0); if (res.code === 0) { hideVersionModal(); loadVersions(); } } async function deleteVersion(id) { if (!confirm('确定删除该版本?')) return; const res = await api(`/admin/api/versions/${id}`, {method: 'DELETE'}); toast(res.msg, res.code !== 0); loadVersions(); } /* ---------- 密码重置申请 ---------- */ async function loadResetRequests() { const res = await api('/admin/api/reset_requests'); server/build-linux.ps1
New file @@ -0,0 +1,75 @@ # 打包 gamebox-server 为 Linux 部署包 # 用法:在 server 目录下执行 .\build-linux.ps1 [-Arch amd64|arm64] [-WithFiles] # -WithFiles: 一并打包游戏安装包(uploads/file,体积大,默认不带) param( [ValidateSet('amd64', 'arm64')] [string]$Arch = 'amd64', [switch]$WithFiles ) $ErrorActionPreference = 'Stop' $root = $PSScriptRoot $name = "gamebox-linux-$Arch" $dist = Join-Path $root 'dist' $stage = Join-Path $dist $name Write-Host "==> 清理旧目录" Remove-Item -Recurse -Force $stage -ErrorAction SilentlyContinue New-Item -ItemType Directory -Force -Path $stage | Out-Null Write-Host "==> 交叉编译 linux/$Arch" $env:GOOS = 'linux' $env:GOARCH = $Arch $env:CGO_ENABLED = '0' Push-Location $root try { go build -trimpath -ldflags '-s -w' -o (Join-Path $stage 'gamebox-server') . if ($LASTEXITCODE -ne 0) { throw 'go build 失败' } } finally { Pop-Location Remove-Item Env:GOOS, Env:GOARCH, Env:CGO_ENABLED -ErrorAction SilentlyContinue } Write-Host "==> 拷贝静态页面与配置" Copy-Item (Join-Path $root 'admin') $stage -Recurse Copy-Item (Join-Path $root 'showcase') $stage -Recurse Copy-Item (Join-Path $root 'download') $stage -Recurse Copy-Item (Join-Path $root 'config.yaml') $stage Write-Host "==> 拷贝图片资源(封面/截图,数据库里的 /static/... 均指向这些文件)" foreach ($d in 'cover', 'covers', 'image') { $src = Join-Path $root "uploads/$d" if (Test-Path $src) { Copy-Item $src (Join-Path $stage 'uploads') -Recurse } else { New-Item -ItemType Directory -Force -Path (Join-Path $stage "uploads/$d") | Out-Null } } if ($WithFiles) { Write-Host "==> 拷贝游戏安装包(uploads/file)" $src = Join-Path $root 'uploads/file' if (Test-Path $src) { Copy-Item $src (Join-Path $stage 'uploads') -Recurse } } Write-Host "==> 创建其余空目录" foreach ($d in 'file', 'tmp') { New-Item -ItemType Directory -Force -Path (Join-Path $stage "uploads/$d") | Out-Null } Write-Host "==> 生成启动脚本" $start = @( '#!/bin/sh', 'cd "$(dirname "$0")"', 'exec ./gamebox-server' ) -join "`n" [System.IO.File]::WriteAllText((Join-Path $stage 'start.sh'), $start + "`n", (New-Object System.Text.UTF8Encoding($false))) Write-Host "==> 打包 tar.gz" $pkg = Join-Path $dist "$name.tar.gz" Remove-Item -Force $pkg -ErrorAction SilentlyContinue tar -czf $pkg -C $dist $name if ($LASTEXITCODE -ne 0) { throw 'tar 打包失败' } $size = [math]::Round((Get-Item $pkg).Length / 1MB, 1) Write-Host "==> 完成: $pkg (${size} MB)" server/config.yaml
New file @@ -0,0 +1,11 @@ # 服务端配置 server: port: 8080 mysql: host: 127.0.0.1 port: 3306 user: root password: "123qwe" database: gamebox charset: utf8mb4 server/config/config.go
New file @@ -0,0 +1,60 @@ package config import ( "fmt" "log" "os" "gopkg.in/yaml.v3" ) // ServerConfig 服务相关配置 type ServerConfig struct { Port int `yaml:"port"` } // MySQLConfig 数据库相关配置 type MySQLConfig struct { Host string `yaml:"host"` Port int `yaml:"port"` User string `yaml:"user"` Password string `yaml:"password"` Database string `yaml:"database"` Charset string `yaml:"charset"` } // Config 配置文件结构 type Config struct { Server ServerConfig `yaml:"server"` MySQL MySQLConfig `yaml:"mysql"` } // App 全局配置 var App Config // Load 读取并解析配置文件 func Load(path string) { data, err := os.ReadFile(path) if err != nil { log.Fatalf("读取配置文件失败: %v", err) } if err := yaml.Unmarshal(data, &App); err != nil { log.Fatalf("解析配置文件失败: %v", err) } // 缺省值 if App.Server.Port == 0 { App.Server.Port = 8080 } if App.MySQL.Port == 0 { App.MySQL.Port = 3306 } if App.MySQL.Charset == "" { App.MySQL.Charset = "utf8mb4" } } // DSN 拼接 MySQL 连接串 func (m MySQLConfig) DSN() string { return fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=%s&parseTime=True&loc=Local", m.User, m.Password, m.Host, m.Port, m.Database, m.Charset) } server/config/db.go
@@ -16,7 +16,7 @@ var DB *gorm.DB func InitDB() { dsn := "root:123qwe@tcp(127.0.0.1:3306)/gamebox?charset=utf8mb4&parseTime=True&loc=Local" dsn := App.MySQL.DSN() db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{ Logger: logger.Default.LogMode(logger.Warn), }) @@ -29,6 +29,7 @@ &models.Admin{}, &models.User{}, &models.Category{}, &models.Game{}, &models.Tool{}, &models.MemberKey{}, &models.Favorite{}, &models.LibraryItem{}, &models.Announcement{}, &models.PasswordResetRequest{}, &models.ClientVersion{}, ) if err != nil { log.Fatalf("数据库迁移失败: %v", err) server/download/index.html
New file @@ -0,0 +1,220 @@ <!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> * { margin:0; padding:0; box-sizing:border-box; } html, body { height:100%; } body { font-family:"Microsoft YaHei","PingFang SC",sans-serif; background:#07070f; color:#e8e8f0; overflow-x:hidden; min-height:100vh; display:flex; flex-direction:column; align-items:center; } /* ---------- 动态背景 ---------- */ #bgCanvas { position:fixed; inset:0; z-index:0; pointer-events:none; } .bg-glow { position:fixed; border-radius:50%; filter:blur(120px); opacity:.35; z-index:0; pointer-events:none; animation:drift 14s ease-in-out infinite alternate; } .glow-1 { width:520px; height:520px; background:#7b2ff7; top:-160px; left:-120px; } .glow-2 { width:460px; height:460px; background:#00c6ff; bottom:-140px; right:-100px; animation-delay:-7s; } @keyframes drift { from { transform:translate(0,0) scale(1); } to { transform:translate(60px,40px) scale(1.15); } } .wrap { position:relative; z-index:1; width:100%; max-width:860px; padding:48px 24px 40px; display:flex; flex-direction:column; align-items:center; } /* ---------- 品牌 ---------- */ .brand { display:flex; align-items:center; gap:14px; margin-bottom:10px; } .brand .logo { width:52px; height:52px; border-radius:14px; display:flex; align-items:center; justify-content:center; background:linear-gradient(135deg,#7b2ff7,#00c6ff); font-size:26px; box-shadow:0 0 30px rgba(123,47,247,.55); animation:logoPulse 2.6s ease-in-out infinite; } @keyframes logoPulse { 0%,100% { box-shadow:0 0 22px rgba(123,47,247,.45); } 50% { box-shadow:0 0 44px rgba(0,198,255,.65); } } .brand h1 { font-size:34px; font-weight:800; letter-spacing:2px; background:linear-gradient(90deg,#c56bff,#00c6ff,#c56bff); background-size:200% auto; -webkit-background-clip:text; background-clip:text; -webkit-text-fill-color:transparent; animation:shine 4s linear infinite; } @keyframes shine { to { background-position:200% center; } } .slogan { color:#8a8aa3; font-size:14px; letter-spacing:6px; margin-bottom:44px; } /* ---------- 版本卡片 ---------- */ .card { width:100%; border-radius:22px; padding:40px 44px 36px; position:relative; background:linear-gradient(160deg, rgba(30,26,58,.72), rgba(10,12,24,.78)); border:1px solid rgba(140,120,255,.22); box-shadow:0 24px 70px rgba(0,0,0,.55), inset 0 1px 0 rgba(255,255,255,.06); backdrop-filter:blur(14px); } .card::before { content:""; position:absolute; inset:-1px; border-radius:23px; padding:1px; z-index:-1; background:linear-gradient(120deg,#7b2ff7,#00c6ff,transparent 60%); -webkit-mask:linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0); -webkit-mask-composite:xor; mask-composite:exclude; opacity:.55; } .card-head { display:flex; align-items:flex-end; justify-content:space-between; flex-wrap:wrap; gap:12px; margin-bottom:8px; } .ver-label { color:#9d9db8; font-size:13px; letter-spacing:3px; margin-bottom:6px; } .ver-num { font-size:44px; font-weight:800; font-family:Consolas,monospace; line-height:1; background:linear-gradient(90deg,#00c6ff,#7bfff2); -webkit-background-clip:text; background-clip:text; -webkit-text-fill-color:transparent; } .badge { display:inline-flex; align-items:center; gap:7px; padding:7px 16px; border-radius:999px; font-size:13px; border:1px solid rgba(0,198,255,.35); color:#7bfff2; background:rgba(0,198,255,.08); } .badge .dot { width:8px; height:8px; border-radius:50%; background:#2bff9e; box-shadow:0 0 10px #2bff9e; animation:blink 1.6s infinite; } @keyframes blink { 50% { opacity:.35; } } .meta { display:flex; gap:26px; flex-wrap:wrap; margin:22px 0 4px; padding:16px 0; border-top:1px solid rgba(255,255,255,.07); border-bottom:1px solid rgba(255,255,255,.07); } .meta .item { display:flex; flex-direction:column; gap:5px; } .meta .k { font-size:12px; color:#7d7d99; letter-spacing:1px; } .meta .v { font-size:16px; font-weight:600; color:#dcdcf0; } .notes { margin:20px 0 6px; } .notes h3 { font-size:14px; color:#9d9db8; letter-spacing:2px; margin-bottom:12px; } .notes ul { list-style:none; } .notes li { position:relative; padding:5px 0 5px 24px; color:#c3c3d6; font-size:14px; line-height:1.7; } .notes li::before { content:""; position:absolute; left:2px; top:13px; width:9px; height:9px; border-radius:3px; background:linear-gradient(135deg,#7b2ff7,#00c6ff); box-shadow:0 0 8px rgba(123,47,247,.7); } /* ---------- 下载按钮 ---------- */ .dl-zone { display:flex; align-items:center; justify-content:center; margin-top:30px; } .dl-btn { position:relative; display:flex; align-items:center; gap:12px; text-decoration:none; padding:18px 58px; border-radius:999px; font-size:19px; font-weight:700; letter-spacing:3px; color:#fff; background:linear-gradient(90deg,#7b2ff7,#4a6bff,#00c6ff); background-size:200% auto; box-shadow:0 10px 34px rgba(90,90,255,.45); transition:all .3s; overflow:visible; } .dl-btn:hover { background-position:right center; transform:translateY(-3px); box-shadow:0 16px 44px rgba(90,90,255,.65); } .dl-btn svg { width:22px; height:22px; } .dl-btn::after { content:""; position:absolute; inset:-4px; border-radius:999px; z-index:-1; border:2px solid rgba(123,47,247,.6); animation:ring 2s ease-out infinite; } @keyframes ring { 0% { transform:scale(.96); opacity:1; } 100% { transform:scale(1.14); opacity:0; } } .dl-hint { margin-top:16px; text-align:center; color:#6d6d87; font-size:12px; line-height:1.9; } /* ---------- 空状态 / 加载 ---------- */ .loading { text-align:center; color:#7d7d99; padding:90px 0; font-size:15px; letter-spacing:2px; } .loading .spin { display:block; width:44px; height:44px; margin:0 auto 18px; border-radius:50%; border:3px solid rgba(255,255,255,.12); border-top-color:#00c6ff; animation:rot 1s linear infinite; } @keyframes rot { to { transform:rotate(360deg); } } .empty { text-align:center; padding:70px 0; color:#7d7d99; font-size:15px; line-height:2.2; } .empty .icon { font-size:44px; display:block; margin-bottom:8px; filter:grayscale(.4); } /* ---------- 页脚 ---------- */ .footer { position:relative; z-index:1; margin-top:auto; padding:26px 0 30px; text-align:center; color:#6d6d87; font-size:16px; letter-spacing:1px; } .footer a { color:#7b8bd0; text-decoration:none; } .footer a:hover { color:#00c6ff; } @media (max-width:560px) { .card { padding:30px 24px; } .ver-num { font-size:34px; } .dl-btn { padding:16px 40px; font-size:17px; } .meta { gap:18px; } } </style> </head> <body> <canvas id="bgCanvas"></canvas> <div class="bg-glow glow-1"></div> <div class="bg-glow glow-2"></div> <div class="wrap"> <div class="brand"> <div class="logo">🎮</div> <h1>游趣电玩</h1> </div> <div class="slogan">GAMEBOX · 极致游戏体验</div> <div class="card" id="verCard" style="display:none"></div> <div class="loading" id="verLoading"><span class="spin"></span>正在获取最新版本…</div> </div> <div class="footer"> <a href="/showcase">浏览游戏目录</a> · 游趣电玩 GameBox · Windows 10 及以上系统 </div> <script> /* ---------- 背景粒子 ---------- */ (function () { const cv = document.getElementById('bgCanvas'), ctx = cv.getContext('2d'); let W, H, pts = []; function resize() { W = cv.width = innerWidth; H = cv.height = innerHeight; const n = Math.min(90, Math.floor(W * H / 16000)); pts = Array.from({length: n}, () => ({ x: Math.random() * W, y: Math.random() * H, vx: (Math.random() - .5) * .35, vy: (Math.random() - .5) * .35, r: Math.random() * 1.6 + .4 })); } addEventListener('resize', resize); resize(); (function tick() { ctx.clearRect(0, 0, W, H); for (const p of pts) { p.x += p.vx; p.y += p.vy; if (p.x < 0 || p.x > W) p.vx *= -1; if (p.y < 0 || p.y > H) p.vy *= -1; ctx.beginPath(); ctx.arc(p.x, p.y, p.r, 0, 7); ctx.fillStyle = 'rgba(150,160,255,.5)'; ctx.fill(); } for (let i = 0; i < pts.length; i++) for (let j = i + 1; j < pts.length; j++) { const a = pts[i], b = pts[j], dx = a.x - b.x, dy = a.y - b.y, d = dx * dx + dy * dy; if (d < 13000) { ctx.strokeStyle = 'rgba(110,120,255,' + (0.16 * (1 - d / 13000)) + ')'; ctx.beginPath(); ctx.moveTo(a.x, a.y); ctx.lineTo(b.x, b.y); ctx.stroke(); } } requestAnimationFrame(tick); })(); })(); /* ---------- 加载版本信息 ---------- */ (async function () { const card = document.getElementById('verCard'), loading = document.getElementById('verLoading'); let v = null; try { const res = await fetch('/api/client/latest'); const j = await res.json(); if (j.code === 0) v = j.data; } catch (e) {} loading.style.display = 'none'; if (!v) { card.style.display = 'block'; card.innerHTML = '<div class="empty"><span class="icon">🛠️</span>暂未发布客户端版本<br>请稍后再来查看</div>'; return; } const notes = (v.notes || '').split('\n').map(s => s.trim()).filter(Boolean); card.innerHTML = ` <div class="card-head"> <div> <div class="ver-label">LATEST VERSION · 最新版本</div> <div class="ver-num">v${escapeHtml(v.version)}</div> </div> <span class="badge"><span class="dot"></span>Windows 客户端</span> </div> <div class="meta"> <div class="item"><span class="k">文件大小</span><span class="v">${escapeHtml(v.file_size || '-')}</span></div> <div class="item"><span class="k">运行平台</span><span class="v">Windows 10 及以上</span></div> </div> ${notes.length ? `<div class="notes"><h3>更新内容 / WHAT'S NEW</h3><ul>${notes.map(n => `<li>${escapeHtml(n)}</li>`).join('')}</ul></div>` : ''} <div class="dl-zone"> <a class="dl-btn" href="/api/client/download"> <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round"> <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/> </svg>立即下载 </a> </div> <div class="dl-hint">下载得到 zip 压缩包,解压后运行「fluttergamebox.exe」即可 · 无需安装 · 下载页面无需登录</div>`; card.style.display = 'block'; })(); function escapeHtml(s) { return String(s == null ? '' : s).replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c])); } </script> </body> </html> server/go.mod
@@ -7,6 +7,7 @@ github.com/golang-jwt/jwt/v5 v5.2.1 github.com/mojocn/base64Captcha v1.3.6 golang.org/x/crypto v0.31.0 gopkg.in/yaml.v3 v3.0.1 gorm.io/driver/mysql v1.5.7 gorm.io/gorm v1.25.12 ) @@ -41,5 +42,4 @@ golang.org/x/sys v0.28.0 // indirect golang.org/x/text v0.21.0 // indirect google.golang.org/protobuf v1.34.1 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect ) server/handlers/versions.go
New file @@ -0,0 +1,87 @@ package handlers import ( "net/http" "strings" "gamebox-server/config" "gamebox-server/models" "github.com/gin-gonic/gin" ) // ---------- 管理端:版本管理 ---------- // AdminListVersions 客户端版本列表 func AdminListVersions(c *gin.Context) { var versions []models.ClientVersion config.DB.Order("id DESC").Find(&versions) c.JSON(http.StatusOK, gin.H{"code": 0, "data": versions}) } // AdminSaveVersion 新增/编辑客户端版本 func AdminSaveVersion(c *gin.Context) { var req struct { ID uint `json:"id"` Version string `json:"version"` Notes string `json:"notes"` FileURL string `json:"file_url"` FileSize string `json:"file_size"` } if err := c.ShouldBindJSON(&req); err != nil || strings.TrimSpace(req.Version) == "" { c.JSON(http.StatusOK, gin.H{"code": 1, "msg": "请填写版本号"}) return } if strings.TrimSpace(req.FileURL) == "" { c.JSON(http.StatusOK, gin.H{"code": 1, "msg": "请上传客户端安装包"}) return } var v models.ClientVersion if req.ID > 0 { if err := config.DB.First(&v, req.ID).Error; err != nil { c.JSON(http.StatusOK, gin.H{"code": 1, "msg": "版本不存在"}) return } } else { v = models.ClientVersion{} } v.Version = strings.TrimSpace(req.Version) v.Notes = req.Notes v.FileURL = req.FileURL v.FileSize = req.FileSize if req.ID > 0 { config.DB.Save(&v) } else { config.DB.Create(&v) } c.JSON(http.StatusOK, gin.H{"code": 0, "msg": "已保存"}) } // AdminDeleteVersion 删除客户端版本 func AdminDeleteVersion(c *gin.Context) { config.DB.Delete(&models.ClientVersion{}, c.Param("id")) c.JSON(http.StatusOK, gin.H{"code": 0, "msg": "已删除"}) } // ---------- 公开端:最新版本查询与下载(无需登录) ---------- // GetClientLatest 最新客户端版本信息(下载页使用) func GetClientLatest(c *gin.Context) { var v models.ClientVersion if err := config.DB.Order("id DESC").First(&v).Error; err != nil { c.JSON(http.StatusOK, gin.H{"code": 1, "msg": "暂无可用版本"}) return } c.JSON(http.StatusOK, gin.H{"code": 0, "data": v}) } // ClientDownload 客户端安装包下载(302 跳转到文件并累计下载次数) func ClientDownload(c *gin.Context) { var v models.ClientVersion if err := config.DB.Order("id DESC").First(&v).Error; err != nil || v.FileURL == "" { c.JSON(http.StatusOK, gin.H{"code": 1, "msg": "暂无可下载的客户端"}) return } config.DB.Model(&v).UpdateColumn("download_count", v.DownloadCount+1) c.Redirect(http.StatusFound, v.FileURL) } server/main.go
@@ -1,6 +1,7 @@ package main import ( "fmt" "net/http" "os" "path/filepath" @@ -13,6 +14,8 @@ ) func main() { config.Load("config.yaml") // 大文件上传时 multipart 会先写系统临时目录(C盘), // 系统盘空间不足会导致大压缩包上传失败,这里指到程序目录下的 uploads/tmp if abs, err := filepath.Abs(filepath.Join("uploads", "tmp")); err == nil { @@ -42,6 +45,8 @@ api.GET("/tools", handlers.GetTools) api.GET("/tools/:id/download", handlers.ToolDownloadInfo) api.GET("/announcements", handlers.GetAnnouncements) api.GET("/client/latest", handlers.GetClientLatest) // 客户端下载页:最新版本信息(公开) api.GET("/client/download", handlers.ClientDownload) // 客户端下载页:下载最新版(公开,累计下载次数) api.GET("/games/:id", middleware.OptionalUserAuth(), handlers.GetGameDetail) // 支持可选登录:登录后返回收藏/资源库状态 auth := api.Group("", middleware.UserAuth()) @@ -65,6 +70,11 @@ c.Redirect(http.StatusFound, "/showcase") }) // ---------- 客户端下载页(公开,无需登录) ---------- r.GET("/download", func(c *gin.Context) { c.File("./download/index.html") }) // ---------- 管理后台 ---------- r.GET("/admin", func(c *gin.Context) { c.File("./admin/index.html") @@ -86,6 +96,10 @@ a.POST("/tools", handlers.AdminSaveTool) a.DELETE("/tools/:id", handlers.AdminDeleteTool) a.GET("/versions", handlers.AdminListVersions) a.POST("/versions", handlers.AdminSaveVersion) a.DELETE("/versions/:id", handlers.AdminDeleteVersion) a.GET("/games", handlers.AdminListGames) a.POST("/games", handlers.AdminSaveGame) a.DELETE("/games/:id", handlers.AdminDeleteGame) @@ -106,5 +120,5 @@ } } r.Run(":8080") r.Run(fmt.Sprintf(":%d", config.App.Server.Port)) } server/models/models.go
@@ -118,3 +118,14 @@ HandledAt *time.Time `json:"handled_at"` CreatedAt time.Time `json:"created_at"` } // ClientVersion 客户端版本(管理后台上传,下载页展示最新版供用户下载) type ClientVersion struct { ID uint `gorm:"primaryKey" json:"id"` Version string `gorm:"size:50" json:"version"` // 版本号,如 1.0.0 Notes string `gorm:"size:1000" json:"notes"` // 更新说明 FileURL string `gorm:"size:255" json:"file_url"` // 安装包URL(zip) FileSize string `gorm:"size:20" json:"file_size"` // 展示大小,如 30.6 MB DownloadCount int `json:"download_count"` CreatedAt time.Time `json:"created_at"` } server/showcase/index.html
@@ -1,361 +1,343 @@ <!DOCTYPE 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> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"> <title>游戏目录 · 游趣电玩</title> <style> * { margin: 0; padding: 0; box-sizing: border-box; } html, body { height: 100%; } body { background: #14161f; color: #fff; font-family: "Microsoft YaHei", "PingFang SC", sans-serif; min-height: 100vh; font-family: -apple-system, BlinkMacSystemFont, "Helvetica Neue", Helvetica, "Segoe UI", Arial, "Microsoft YaHei", "PingFang SC", sans-serif; background: #fff; color: #000; overflow: hidden; } img { display: block; } /* 顶部栏 */ header { position: sticky; top: 0; z-index: 100; background: rgba(20, 22, 31, .95); backdrop-filter: blur(10px); border-bottom: 1px solid #252a3a; padding: 14px 24px; display: flex; align-items: center; gap: 14px; flex-wrap: wrap; .page { height: 100vh; padding: 4px; display: flex; flex-direction: column; background: #fff; } .logo { width: 42px; height: 42px; border-radius: 50%; background: linear-gradient(135deg, #ff5c8a, #b44dff); display: flex; align-items: center; justify-content: center; font-size: 18px; font-weight: bold; flex-shrink: 0; box-shadow: 0 0 18px rgba(255, 92, 138, .45); /* 顶部搜索 */ .search { flex-shrink: 0; display: flex; align-items: center; padding: 9px 11px; border-bottom: 1px solid #f3f4f6; } .brand { display: flex; flex-direction: column; margin-right: 8px; } .brand b { font-size: 17px; letter-spacing: 1px; } .brand span { font-size: 11px; color: #7d8598; } .search-box { flex: 1; min-width: 200px; max-width: 420px; position: relative; margin-left: auto; flex: 1; display: flex; align-items: center; height: 31px; padding: 0 11px; background: #f7f8fa; border-radius: 2px; min-width: 0; } .search-box input { width: 100%; height: 38px; padding: 0 40px 0 16px; background: #1c1f2e; border: 1px solid #2c3247; border-radius: 19px; color: #fff; font-size: 13px; outline: none; .search-icon { width: 16px; height: 16px; flex-shrink: 0; margin-right: 8px; } .search-icon svg { width: 100%; height: 100%; display: block; } #kw { flex: 1; min-width: 0; height: 100%; border: 0; outline: 0; background: transparent; font-size: 13px; color: #323233; font-family: inherit; } .search-box input:focus { border-color: #ff5c8a; } .search-box .icon { position: absolute; right: 14px; top: 50%; transform: translateY(-50%); color: #7d8598; font-size: 14px; font-style: normal; #kw::placeholder { color: #969799; } .clear-btn { flex-shrink: 0; width: 16px; height: 16px; margin-left: 6px; border: 0; padding: 0; background: transparent; cursor: pointer; display: none; } .client-tip { font-size: 12px; color: #7d8598; padding: 7px 14px; border: 1px solid #2c3247; border-radius: 16px; .clear-btn.show { display: block; } .clear-btn svg { width: 100%; height: 100%; display: block; } /* 游戏列表 */ .list { flex: 1; overflow-y: auto; } .row { display: flex; padding: 8px; border-bottom: 1px solid #f8f8f8; } .cover { width: 124px; height: 73px; flex-shrink: 0; border-radius: 4px; background: #f5f5f5; overflow: hidden; } .cover img { width: 100%; height: 100%; object-fit: cover; } .meta { flex: 1; min-width: 0; padding-left: 8px; display: flex; flex-direction: column; justify-content: space-between; } .name { font-size: 16px; line-height: 28px; font-weight: 400; color: #000; overflow: hidden; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; word-break: break-all; } .line { display: flex; align-items: center; min-width: 0; } .tags { flex: 1; min-width: 0; overflow: hidden; white-space: nowrap; } .tag { display: inline-flex; align-items: center; height: 15px; padding: 0 4px; margin-right: 4px; background: #ff0000; color: #fff; font-size: 11px; line-height: 15px; border-radius: 2px; vertical-align: middle; } .size { flex-shrink: 0; margin-left: 8px; font-size: 12px; color: #9ca3af; white-space: nowrap; } /* 类别栏 */ .cats { display: flex; gap: 10px; overflow-x: auto; padding: 16px 24px 4px; scrollbar-width: none; } .cats::-webkit-scrollbar { display: none; } .cat-chip { padding: 8px 18px; border-radius: 16px; white-space: nowrap; background: #1c1f2e; color: #aab2c5; font-size: 13px; cursor: pointer; border: 1px solid transparent; user-select: none; transition: all .2s; } .cat-chip:hover { color: #fff; } .cat-chip.active { background: linear-gradient(135deg, #ff5c8a, #ff7e5a); color: #fff; font-weight: bold; } /* 游戏网格 */ main { max-width: 1280px; margin: 0 auto; padding: 20px 24px 60px; display: grid; grid-template-columns: repeat(auto-fill, minmax(190px, 1fr)); gap: 22px 18px; } .card { border-radius: 10px; overflow: hidden; cursor: pointer; background: #1c1f2e; border: 1px solid #262b3d; transition: transform .25s, box-shadow .25s, border-color .25s; } .card:hover { transform: translateY(-5px); box-shadow: 0 10px 28px rgba(0, 0, 0, .5); border-color: #ff5c8a; } .cover { aspect-ratio: 3/4; background: #10121c; position: relative; overflow: hidden; } .cover img { width: 100%; height: 100%; object-fit: cover; transition: transform .3s; } .card:hover .cover img { transform: scale(1.05); } .cover .size-tag { position: absolute; right: 0; bottom: 0; background: rgba(0, 0, 0, .65); color: #e7eaf3; font-size: 11px; padding: 3px 8px; border-radius: 6px 0 0 0; } .card .info { padding: 10px 12px 12px; } .card .title { font-size: 13px; font-weight: bold; line-height: 1.45; height: 2.9em; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; margin-bottom: 8px; } .tags { display: flex; flex-wrap: wrap; gap: 5px; } .tag { font-size: 11px; color: #9aa3b8; background: #262b3d; padding: 2px 8px; border-radius: 4px; } .tag.cat { color: #4a92ff; } .empty { grid-column: 1 / -1; text-align: center; color: #5c6478; padding: 80px 0; font-size: 14px; } .loading { grid-column: 1 / -1; text-align: center; color: #5c6478; padding: 80px 0; } .loading .spin { display: inline-block; width: 28px; height: 28px; border: 3px solid #2c3247; border-top-color: #ff5c8a; border-radius: 50%; animation: spin .8s linear infinite; /* 状态 */ .footer, .loading, .empty { text-align: center; color: #969799; } .footer { font-size: 14px; padding: 14px 0; } .loading { padding: 24px 0 14px; } .loading .spinner { display: inline-block; width: 20px; height: 20px; border: 2px solid #ebedf0; border-top-color: #c8c9cc; border-radius: 50%; animation: spin .8s linear infinite; } @keyframes spin { to { transform: rotate(360deg); } } .empty { padding: 90px 0; font-size: 14px; } .empty svg { width: 100px; height: 100px; margin: 0 auto 12px; display: block; } .empty .desc { line-height: 20px; } /* 详情弹窗 */ .modal-mask { position: fixed; inset: 0; z-index: 200; background: rgba(5, 6, 10, .8); backdrop-filter: blur(4px); display: none; align-items: flex-start; justify-content: center; padding: 4vh 16px; overflow-y: auto; /* 右下角重置气泡 */ .bubble { position: fixed; right: 16px; bottom: 16px; width: 44px; height: 44px; border: 0; padding: 0; border-radius: 50%; background: #ff0000; box-shadow: 0 3px 10px rgba(0, 0, 0, .18); display: none; align-items: center; justify-content: center; cursor: pointer; z-index: 20; } .modal-mask.show { display: flex; } .modal { width: 860px; max-width: 100%; background: #1b1e2e; border: 1px solid #2c3247; border-radius: 12px; padding: 26px; position: relative; animation: pop .25s ease; } @keyframes pop { from { opacity: 0; transform: translateY(18px); } } .close-btn { position: absolute; top: 14px; right: 14px; width: 32px; height: 32px; border-radius: 50%; background: #262b3d; color: #aab2c5; border: none; cursor: pointer; font-size: 16px; line-height: 32px; text-align: center; } .close-btn:hover { background: #ff5c8a; color: #fff; } .detail-top { display: flex; gap: 24px; } .detail-cover { width: 240px; flex-shrink: 0; aspect-ratio: 3/4; border-radius: 10px; overflow: hidden; background: #10121c; } .detail-cover img { width: 100%; height: 100%; object-fit: cover; } .detail-meta { flex: 1; min-width: 0; } .detail-meta h2 { font-size: 20px; margin-bottom: 12px; line-height: 1.4; padding-right: 36px; } .meta-rows { display: flex; flex-direction: column; gap: 9px; margin-bottom: 14px; } .meta-row { display: flex; font-size: 13px; } .meta-row .k { color: #7d8598; width: 70px; flex-shrink: 0; } .meta-row .v { color: #dfe3ee; word-break: break-all; } .desc { font-size: 13px; color: #aab2c5; line-height: 1.8; max-height: 180px; overflow-y: auto; white-space: pre-wrap; } .shots { margin-top: 20px; } .shots h3 { font-size: 14px; color: #dfe3ee; margin-bottom: 10px; } .shot-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(230px, 1fr)); gap: 10px; } .shot-grid img, .shot-grid video { width: 100%; border-radius: 8px; background: #10121c; } .video-box { margin-top: 20px; } .video-box video { width: 100%; border-radius: 8px; background: #000; } .only-view { margin-top: 22px; padding: 12px 16px; border-radius: 8px; background: rgba(255, 92, 138, .08); border: 1px solid rgba(255, 92, 138, .3); color: #ff8aa8; font-size: 13px; text-align: center; } footer { text-align: center; color: #5c6478; font-size: 12px; padding: 30px 0 40px; border-top: 1px solid #1e2231; } @media (max-width: 640px) { header { padding: 12px 14px; } .client-tip { display: none; } .cats { padding: 12px 14px 4px; } main { padding: 14px 14px 50px; grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); gap: 16px 12px; } .modal { padding: 18px; } .detail-top { flex-direction: column; } .detail-cover { width: 170px; margin: 0 auto; } .detail-meta h2 { padding-right: 30px; } } .bubble.show { display: flex; } .bubble svg { width: 20px; height: 20px; display: block; } </style> </head> <body> <header> <div class="logo">99</div> <div class="brand"><b>游趣电玩</b><span>游戏目录 · 精选游戏一览</span></div> <div class="page"> <div class="search"> <div class="search-box"> <input id="kw" type="text" placeholder="搜索游戏名称..." /> <i class="icon">🔍</i> </div> <div class="client-tip">本页面仅用于浏览,下载游戏请使用游趣电玩客户端</div> </header> <nav class="cats" id="cats"></nav> <main id="grid"> <div class="loading"><span class="spin"></span></div> </main> <footer>游趣电玩 · 游戏盒子 © 2026 | 本目录仅供展示,具体游戏以客户端为准</footer> <!-- 详情弹窗 --> <div class="modal-mask" id="mask"> <div class="modal"> <button class="close-btn" onclick="closeDetail()">✕</button> <div id="detailBody"></div> <span class="search-icon"> <svg viewBox="0 0 1024 1024" fill="#969799"><path d="M459.094 786.667c-180.107 0-326.667-146.56-326.667-326.667S278.987 133.333 459.094 133.333 785.761 279.893 785.761 460s-146.56 326.667-326.667 326.667z m0-57.6c148.587 0 269.067-120.48 269.067-269.067S607.681 190.933 459.094 190.933 190.027 311.413 190.027 460s120.48 269.067 269.067 269.067z"></path><path d="M665.579 601.259a28.8 28.8 0 0 1 40.704 40.704l-71.723 71.723a28.8 28.8 0 1 1-40.704-40.704l71.723-71.723z"></path><path d="M662.486 662.486a28.8 28.8 0 0 1 40.704 0l133.76 133.76a28.8 28.8 0 0 1-40.704 40.704L662.486 703.19a28.8 28.8 0 0 1 0-40.704z"></path></svg> </span> <input id="kw" type="text" placeholder="请输入搜索关键词" autocomplete="off"> <button class="clear-btn" id="clearBtn" type="button" aria-label="清空"> <svg viewBox="0 0 1024 1024" fill="#c8c9cc"><path d="M512 85.333c235.648 0 426.667 191.019 426.667 426.667S747.648 938.667 512 938.667 85.333 747.648 85.333 512 276.352 85.333 512 85.333z m149.333 240.213a35.925 35.925 0 0 0-50.773 0L512 424.107 413.397 325.504a35.925 35.925 0 0 0-50.773 50.773L461.227 512 362.624 610.603a35.925 35.925 0 0 0 50.773 50.773L512 562.773l98.603 98.603a35.925 35.925 0 0 0 50.773-50.773L562.773 512l98.603-98.603a35.925 35.925 0 0 0 0-50.773z"></path></svg> </button> </div> </div> <div class="list" id="list"> <div class="loading"><span class="spinner"></span></div> </div> </div> <button class="bubble" id="bubble" type="button" aria-label="重置搜索"> <svg viewBox="0 0 1024 1024" fill="#fff"><path d="M512 85.333c235.648 0 426.667 191.019 426.667 426.667S747.648 938.667 512 938.667 85.333 747.648 85.333 512 276.352 85.333 512 85.333z m149.333 240.213a35.925 35.925 0 0 0-50.773 0L512 424.107 413.397 325.504a35.925 35.925 0 0 0-50.773 50.773L461.227 512 362.624 610.603a35.925 35.925 0 0 0 50.773 50.773L512 562.773l98.603 98.603a35.925 35.925 0 0 0 50.773-50.773L562.773 512l98.603-98.603a35.925 35.925 0 0 0 0-50.773z"></path></svg> </button> <template id="emptyTpl"> <div class="empty"> <svg viewBox="0 0 1024 1024"> <ellipse cx="512" cy="700" rx="260" ry="34" fill="#f2f3f5"></ellipse> <rect x="292" y="238" width="440" height="374" rx="28" fill="#f7f8fa" stroke="#e5e7eb"></rect> <circle cx="470" cy="404" r="76" fill="#fff" stroke="#dcdfe6"></circle> <path d="M530 464l72 72" stroke="#dcdfe6" stroke-width="18" stroke-linecap="round"></path> </svg> <div class="desc"></div> </div> </template> <script> const API = ''; let allGames = []; let categories = []; let curCat = 0; let curKw = ''; let debounceTimer = null; const PAGE_SIZE = 20; const listEl = document.getElementById('list'); const kwEl = document.getElementById('kw'); const clearBtn = document.getElementById('clearBtn'); const bubble = document.getElementById('bubble'); const emptyTpl = document.getElementById('emptyTpl'); function gbLabel(s) { if (!s) return '未知大小'; const t = String(s).trim(); return /[a-zA-Z]/.test(t) ? t : t + ' GB'; } let allGames = []; let shownCount = 0; let loading = false; let keyword = ''; function esc(s) { return String(s == null ? '' : s).replace(/[&<>"']/g, m => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[m])); } async function loadCategories() { try { const res = await fetch(API + '/api/categories').then(r => r.json()); if (res.code === 0) categories = res.data || []; } catch (e) {} const el = document.getElementById('cats'); let html = `<div class="cat-chip active" data-id="0" onclick="pickCat(0)">全部</div>`; html += categories.map(c => `<div class="cat-chip" data-id="${c.id}" onclick="pickCat(${c.id})">${esc(c.name)}</div>`).join(''); el.innerHTML = html; // 与对标页一致:数值 + 空格 + 单位 function formatSize(v) { if (!v) return ''; const t = String(v).trim(); const m = t.match(/^([0-9]+(?:\.[0-9]+)?)\s*(TB|GB|MB|KB|B)$/i); if (m) return m[1] + ' ' + m[2].toUpperCase(); return /[a-zA-Z]/.test(t) ? t : t + ' GB'; } async function loadGames() { const grid = document.getElementById('grid'); grid.innerHTML = '<div class="loading"><span class="spin"></span></div>'; function tagList(g) { const out = []; const push = v => { String(v || '').split(/[,,、/\s]+/).map(s => s.trim()).forEach(s => { if (s && !out.includes(s)) out.push(s); }); }; push(g.category_name); push(g.tags); return out; } function rowHtml(g) { const tags = tagList(g).map(t => `<span class="tag">${esc(t)}</span>`).join(''); return `<div class="row"> <div class="cover">${g.cover ? `<img src="${esc(g.cover)}" alt="${esc(g.title)}" loading="lazy" onerror="this.remove()">` : ''}</div> <div class="meta"> <div class="name">${esc(g.title)}</div> <div class="line"> <div class="tags">${tags}</div> <div class="size">${esc(formatSize(g.size))}</div> </div> </div> </div>`; } function showLoading() { listEl.innerHTML = '<div class="loading"><span class="spinner"></span></div>'; } function showEmpty(msg) { const node = emptyTpl.content.cloneNode(true); node.querySelector('.desc').textContent = msg || '暂无数据'; listEl.innerHTML = ''; listEl.appendChild(node); } function appendPage() { const next = allGames.slice(shownCount, shownCount + PAGE_SIZE); if (!next.length) return; const frag = document.createDocumentFragment(); const wrap = document.createElement('div'); wrap.innerHTML = next.map(rowHtml).join(''); while (wrap.firstChild) frag.appendChild(wrap.firstChild); const oldFooter = listEl.querySelector('.footer'); if (oldFooter) oldFooter.remove(); listEl.appendChild(frag); shownCount += next.length; if (shownCount >= allGames.length && allGames.length) { const footer = document.createElement('div'); footer.className = 'footer'; footer.textContent = '没有更多了~'; listEl.appendChild(footer); } } async function loadGames(kw) { if (loading) return; loading = true; showLoading(); try { const p = new URLSearchParams({ platform: 'all', category: '0', keyword: curKw, sort: 'updated' }); const res = await fetch(API + '/api/games?' + p).then(r => r.json()); if (res.code !== 0) throw 0; const p = new URLSearchParams({ platform: 'all', category: '0', keyword: kw || '', sort: 'updated' }); const res = await fetch('/api/games?' + p.toString()).then(r => r.json()); if (res.code !== 0) throw new Error(res.msg || '加载失败'); allGames = res.data || []; render(); shownCount = 0; listEl.innerHTML = ''; if (!allGames.length) showEmpty('暂无数据'); else appendPage(); } catch (e) { grid.innerHTML = '<div class="empty">加载失败,请刷新重试</div>'; showEmpty(e.message || '加载失败'); } finally { loading = false; } } function render() { const grid = document.getElementById('grid'); if (!allGames.length) { grid.innerHTML = '<div class="empty">暂无游戏</div>'; return; } const list = curCat > 0 ? allGames.filter(g => g.category_id === curCat) : allGames; if (!list.length) { grid.innerHTML = '<div class="empty">该类别下暂无游戏</div>'; return; } grid.innerHTML = list.map(g => ` <div class="card" onclick="openDetail(${g.id})"> <div class="cover"> ${g.cover_url ? `<img src="${esc(g.cover_url)}" loading="lazy" alt="${esc(g.title)}" onerror="this.style.display='none'">` : ''} <span class="size-tag">${esc(gbLabel(g.size))}</span> </div> <div class="info"> <div class="title">${esc(g.title)}</div> <div class="tags"> ${g.category_name ? `<span class="tag cat">${esc(g.category_name)}</span>` : ''} ${(g.tags || '').split(/[,,\s]+/).filter(Boolean).slice(0, 2).map(t => `<span class="tag">${esc(t)}</span>`).join('')} </div> </div> </div>`).join(''); // 回车 / 点击放大镜触发搜索;清空与右下气泡可重置 function doSearch() { keyword = kwEl.value.trim(); bubble.classList.toggle('show', !!keyword); loadGames(keyword); } function pickCat(id) { curCat = id; document.querySelectorAll('.cat-chip').forEach(c => c.classList.toggle('active', +c.dataset.id === id)); render(); function resetSearch() { kwEl.value = ''; keyword = ''; clearBtn.classList.remove('show'); bubble.classList.remove('show'); loadGames(''); } document.getElementById('kw').addEventListener('input', e => { clearTimeout(debounceTimer); debounceTimer = setTimeout(() => { curKw = e.target.value.trim(); loadGames(); }, 350); kwEl.addEventListener('input', () => { clearBtn.classList.toggle('show', !!kwEl.value); }); kwEl.addEventListener('keydown', e => { if (e.key === 'Enter') doSearch(); }); document.querySelector('.search-icon').addEventListener('click', doSearch); clearBtn.addEventListener('click', resetSearch); bubble.addEventListener('click', resetSearch); listEl.addEventListener('scroll', () => { if (loading) return; const rest = listEl.scrollHeight - listEl.scrollTop - listEl.clientHeight; if (rest < 100 && shownCount < allGames.length) appendPage(); }); async function openDetail(id) { const mask = document.getElementById('mask'); const body = document.getElementById('detailBody'); body.innerHTML = '<div class="loading"><span class="spin"></span></div>'; mask.classList.add('show'); mask.onclick = e => { if (e.target === mask) closeDetail(); }; try { const res = await fetch(API + '/api/games/' + id).then(r => r.json()); if (res.code !== 0) throw 0; const g = res.data; let shots = []; try { shots = JSON.parse(g.screenshots || '[]'); } catch (e) {} const tagList = (g.tags || '').split(/[,,\s]+/).filter(Boolean); body.innerHTML = ` <div class="detail-top"> <div class="detail-cover"> ${g.cover_url ? `<img src="${esc(g.cover_url)}" alt="${esc(g.title)}">` : ''} </div> <div class="detail-meta"> <h2>${esc(g.title)}</h2> <div class="meta-rows"> ${g.category_name ? `<div class="meta-row"><span class="k">类别</span><span class="v">${esc(g.category_name)}</span></div>` : ''} ${tagList.length ? `<div class="meta-row"><span class="k">标签</span><span class="v">${tagList.map(esc).join(' / ')}</span></div>` : ''} <div class="meta-row"><span class="k">游戏大小</span><span class="v">${esc(gbLabel(g.size))}</span></div> ${g.install_size ? `<div class="meta-row"><span class="k">磁盘占用</span><span class="v">${esc(gbLabel(g.install_size))}</span></div>` : ''} <div class="meta-row"><span class="k">平台</span><span class="v">${esc(g.platform === 'switch' ? 'Switch 资源' : 'PC 资源')}</span></div> </div> <div class="desc">${esc(g.description || '暂无简介')}</div> </div> </div> ${g.video_url ? `<div class="video-box"><video src="${esc(g.video_url)}" controls preload="none" poster="${esc(g.cover_url || '')}"></video></div>` : ''} ${shots.length ? `<div class="shots"><h3>游戏截图</h3><div class="shot-grid"> ${shots.map(s => `<img src="${esc(s)}" loading="lazy" onerror="this.style.display='none'">`).join('')} </div></div>` : ''} <div class="only-view">本页面仅提供游戏预览,如需下载游戏请在游趣电玩客户端中操作</div> `; } catch (e) { body.innerHTML = '<div class="empty">详情加载失败</div>'; } } function closeDetail() { document.getElementById('mask').classList.remove('show'); const v = document.querySelector('#detailBody video'); if (v) v.pause(); } document.addEventListener('keydown', e => { if (e.key === 'Escape') closeDetail(); }); loadCategories(); loadGames(); loadGames(''); </script> </body> </html>