This commit is contained in:
2025-12-09 16:33:44 +08:00
parent 345af5e2a3
commit 1d42f5ea50
49 changed files with 12015 additions and 1 deletions

1
theme/.gitignore vendored Normal file
View File

@@ -0,0 +1 @@

465
theme/device-bind.html Normal file
View File

@@ -0,0 +1,465 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>设备绑定 - Meow Music</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Arial, sans-serif;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
min-height: 100vh;
display: flex;
justify-content: center;
align-items: center;
padding: 20px;
}
.container {
background: white;
border-radius: 20px;
padding: 40px;
box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
max-width: 500px;
width: 100%;
}
h1 {
text-align: center;
color: #333;
margin-bottom: 10px;
font-size: 28px;
}
.subtitle {
text-align: center;
color: #666;
margin-bottom: 30px;
font-size: 14px;
}
.form-group {
margin-bottom: 25px;
}
label {
display: block;
margin-bottom: 8px;
color: #333;
font-weight: 500;
font-size: 14px;
}
input[type="text"] {
width: 100%;
padding: 12px 15px;
border: 2px solid #e0e0e0;
border-radius: 10px;
font-size: 16px;
transition: border-color 0.3s;
font-family: 'Courier New', monospace;
}
input[type="text"]:focus {
outline: none;
border-color: #667eea;
}
.hint {
margin-top: 8px;
font-size: 13px;
color: #999;
}
.hint code {
background: #f5f5f5;
padding: 2px 6px;
border-radius: 4px;
font-family: 'Courier New', monospace;
}
.btn {
width: 100%;
padding: 14px;
border: none;
border-radius: 10px;
font-size: 16px;
font-weight: 600;
cursor: pointer;
transition: all 0.3s;
margin-top: 10px;
}
.btn-primary {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
}
.btn-primary:hover {
transform: translateY(-2px);
box-shadow: 0 10px 20px rgba(102, 126, 234, 0.3);
}
.btn-secondary {
background: #f5f5f5;
color: #666;
}
.btn-secondary:hover {
background: #e0e0e0;
}
.device-list {
margin-top: 40px;
padding-top: 30px;
border-top: 2px solid #f0f0f0;
}
.device-list h2 {
font-size: 20px;
color: #333;
margin-bottom: 20px;
}
.device-item {
background: #f9f9f9;
padding: 15px;
border-radius: 10px;
margin-bottom: 10px;
display: flex;
justify-content: space-between;
align-items: center;
}
.device-info {
flex: 1;
}
.device-name {
font-weight: 600;
color: #333;
margin-bottom: 5px;
}
.device-mac {
font-size: 13px;
color: #999;
font-family: 'Courier New', monospace;
}
.device-status {
display: inline-block;
padding: 4px 12px;
border-radius: 20px;
font-size: 12px;
font-weight: 600;
}
.status-online {
background: #e8f5e9;
color: #4caf50;
}
.status-offline {
background: #ffebee;
color: #f44336;
}
.btn-unbind {
padding: 6px 16px;
background: #f44336;
color: white;
border: none;
border-radius: 6px;
cursor: pointer;
font-size: 13px;
margin-left: 10px;
}
.btn-unbind:hover {
background: #d32f2f;
}
.alert {
padding: 15px;
border-radius: 10px;
margin-bottom: 20px;
font-size: 14px;
}
.alert-success {
background: #e8f5e9;
color: #2e7d32;
border-left: 4px solid #4caf50;
}
.alert-error {
background: #ffebee;
color: #c62828;
border-left: 4px solid #f44336;
}
.alert-info {
background: #e3f2fd;
color: #1565c0;
border-left: 4px solid #2196f3;
}
.loading {
display: inline-block;
width: 16px;
height: 16px;
border: 2px solid #f3f3f3;
border-top: 2px solid #667eea;
border-radius: 50%;
animation: spin 1s linear infinite;
margin-right: 8px;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
.empty-state {
text-align: center;
padding: 40px 20px;
color: #999;
}
.back-link {
display: block;
text-align: center;
margin-top: 20px;
color: #667eea;
text-decoration: none;
font-size: 14px;
}
.back-link:hover {
text-decoration: underline;
}
</style>
</head>
<body>
<div class="container">
<h1>🎵 设备绑定</h1>
<p class="subtitle">将您的ESP32音乐播放器绑定到账号</p>
<div id="alertContainer"></div>
<form id="bindForm">
<div class="form-group">
<label for="macAddress">MAC地址 *</label>
<input
type="text"
id="macAddress"
placeholder="例如: AA:BB:CC:DD:EE:FF"
pattern="[A-Fa-f0-9:]{17}"
required
>
<div class="hint">
💡 在ESP32串口日志中查找格式如<code>80:b5:4e:d4:fa:80</code>
</div>
</div>
<div class="form-group">
<label for="deviceName">设备名称(可选)</label>
<input
type="text"
id="deviceName"
placeholder="例如: 客厅音响"
>
<div class="hint">
给设备起个名字,方便识别
</div>
</div>
<button type="submit" class="btn btn-primary" id="bindBtn">
绑定设备
</button>
<button type="button" class="btn btn-secondary" onclick="loadDevices()">
刷新设备列表
</button>
</form>
<div class="device-list">
<h2>已绑定设备</h2>
<div id="deviceListContainer">
<div class="loading"></div> 正在加载...
</div>
</div>
<a href="/" class="back-link">← 返回首页</a>
</div>
<script>
// 显示提示消息
function showAlert(message, type = 'info') {
const container = document.getElementById('alertContainer');
const alert = document.createElement('div');
alert.className = `alert alert-${type}`;
alert.textContent = message;
container.innerHTML = '';
container.appendChild(alert);
// 3秒后自动消失
setTimeout(() => {
alert.style.opacity = '0';
alert.style.transition = 'opacity 0.3s';
setTimeout(() => alert.remove(), 300);
}, 3000);
}
// 格式化MAC地址
function formatMac(mac) {
// 移除所有非字母数字字符
let cleaned = mac.replace(/[^A-Fa-f0-9]/g, '');
// 如果长度不是12返回原值
if (cleaned.length !== 12) {
return mac;
}
// 每2个字符加一个冒号
return cleaned.match(/.{2}/g).join(':').toUpperCase();
}
// 绑定设备
document.getElementById('bindForm').addEventListener('submit', async (e) => {
e.preventDefault();
const macInput = document.getElementById('macAddress');
const deviceNameInput = document.getElementById('deviceName');
const bindBtn = document.getElementById('bindBtn');
// 格式化MAC地址
const mac = formatMac(macInput.value);
const deviceName = deviceNameInput.value.trim() || 'ESP32音乐播放器';
// 禁用按钮
bindBtn.disabled = true;
bindBtn.innerHTML = '<span class="loading"></span> 绑定中...';
try {
const response = await fetch('/api/device/bind-direct', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
mac: mac,
device_name: deviceName
})
});
const data = await response.json();
if (response.ok && data.success) {
showAlert('✅ 设备绑定成功!', 'success');
macInput.value = '';
deviceNameInput.value = '';
// 刷新设备列表
setTimeout(() => loadDevices(), 500);
} else {
showAlert('❌ ' + (data.message || '绑定失败'), 'error');
}
} catch (error) {
showAlert('❌ 网络错误:' + error.message, 'error');
} finally {
bindBtn.disabled = false;
bindBtn.innerHTML = '绑定设备';
}
});
// 加载设备列表
async function loadDevices() {
const container = document.getElementById('deviceListContainer');
container.innerHTML = '<div class="loading"></div> 正在加载...';
try {
const response = await fetch('/api/device/list');
const data = await response.json();
if (data.success && data.devices && data.devices.length > 0) {
container.innerHTML = '';
data.devices.forEach(device => {
const item = document.createElement('div');
item.className = 'device-item';
item.innerHTML = `
<div class="device-info">
<div class="device-name">${device.device_name || 'ESP32音乐播放器'}</div>
<div class="device-mac">MAC: ${device.mac}</div>
</div>
<span class="device-status ${device.is_active ? 'status-online' : 'status-offline'}">
${device.is_active ? '🟢 在线' : '🔴 离线'}
</span>
<button class="btn-unbind" onclick="unbindDevice('${device.mac}')">
解绑
</button>
`;
container.appendChild(item);
});
} else {
container.innerHTML = `
<div class="empty-state">
<p>📱 还没有绑定的设备</p>
<p style="margin-top: 10px; font-size: 13px;">请输入ESP32的MAC地址来绑定设备</p>
</div>
`;
}
} catch (error) {
container.innerHTML = `<div class="alert alert-error">加载失败: ${error.message}</div>`;
}
}
// 解绑设备
async function unbindDevice(mac) {
if (!confirm(`确定要解绑设备 ${mac} 吗?`)) {
return;
}
try {
const response = await fetch('/api/device/unbind', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ mac: mac })
});
const data = await response.json();
if (response.ok && data.success) {
showAlert('✅ 设备已解绑', 'success');
loadDevices();
} else {
showAlert('❌ ' + (data.message || '解绑失败'), 'error');
}
} catch (error) {
showAlert('❌ 网络错误:' + error.message, 'error');
}
}
// 页面加载时获取设备列表
loadDevices();
// MAC地址输入时自动格式化
document.getElementById('macAddress').addEventListener('input', (e) => {
const value = e.target.value;
// 只在输入完整时格式化
if (value.replace(/[^A-Fa-f0-9]/g, '').length === 12) {
e.target.value = formatMac(value);
}
});
</script>
</body>
</html>

2182
theme/full-app.html Normal file

File diff suppressed because it is too large Load Diff

720
theme/index.html Normal file
View File

@@ -0,0 +1,720 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>喵音乐 - Meow Music</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Helvetica', 'Arial', sans-serif;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
min-height: 100vh;
display: flex;
justify-content: center;
align-items: center;
padding: 20px;
}
.container {
width: 100%;
max-width: 1200px;
background: rgba(255, 255, 255, 0.95);
border-radius: 20px;
box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
overflow: hidden;
display: flex;
flex-direction: column;
height: 90vh;
}
.header {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
padding: 30px;
text-align: center;
}
.header h1 {
font-size: 2.5em;
margin-bottom: 10px;
text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.2);
}
.header p {
opacity: 0.9;
font-size: 1.1em;
}
.search-section {
padding: 30px;
background: #f8f9fa;
border-bottom: 1px solid #e0e0e0;
}
.search-box {
display: flex;
gap: 10px;
max-width: 600px;
margin: 0 auto;
}
.search-box input {
flex: 1;
padding: 15px 20px;
border: 2px solid #e0e0e0;
border-radius: 10px;
font-size: 1em;
transition: all 0.3s;
}
.search-box input:focus {
outline: none;
border-color: #667eea;
box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}
.search-box button {
padding: 15px 30px;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
border: none;
border-radius: 10px;
font-size: 1em;
cursor: pointer;
transition: all 0.3s;
font-weight: bold;
}
.search-box button:hover {
transform: translateY(-2px);
box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
}
.tabs {
display: flex;
padding: 0 30px;
background: white;
border-bottom: 2px solid #e0e0e0;
}
.tab {
padding: 20px 30px;
cursor: pointer;
font-size: 1.1em;
font-weight: 500;
color: #666;
transition: all 0.3s;
border-bottom: 3px solid transparent;
}
.tab.active {
color: #667eea;
border-bottom-color: #667eea;
}
.tab:hover {
color: #667eea;
}
.content {
flex: 1;
overflow-y: auto;
padding: 30px;
}
.music-list {
display: none;
}
.music-list.active {
display: block;
}
.music-item {
background: white;
border-radius: 12px;
padding: 20px;
margin-bottom: 15px;
display: flex;
align-items: center;
gap: 20px;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
transition: all 0.3s;
cursor: pointer;
}
.music-item:hover {
transform: translateY(-3px);
box-shadow: 0 5px 20px rgba(0, 0, 0, 0.15);
}
.music-item.playing {
background: linear-gradient(135deg, rgba(102, 126, 234, 0.1) 0%, rgba(118, 75, 162, 0.1) 100%);
border: 2px solid #667eea;
}
.music-cover {
width: 60px;
height: 60px;
border-radius: 8px;
object-fit: cover;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}
.music-info {
flex: 1;
}
.music-title {
font-size: 1.2em;
font-weight: 600;
margin-bottom: 5px;
color: #333;
}
.music-artist {
color: #666;
font-size: 0.95em;
}
.music-duration {
color: #999;
font-size: 0.9em;
}
.favorite-btn {
background: none;
border: 3px solid #e0e0e0;
width: 50px;
height: 50px;
border-radius: 50%;
font-size: 1.5em;
cursor: pointer;
transition: all 0.3s;
color: #ccc;
display: flex;
align-items: center;
justify-content: center;
}
.favorite-btn:hover {
transform: scale(1.15);
border-color: #ff4757;
}
.favorite-btn.favorited {
background: linear-gradient(135deg, #ff4757 0%, #ff6b81 100%);
color: white;
border-color: #ff4757;
box-shadow: 0 4px 15px rgba(255, 71, 87, 0.4);
}
.favorite-btn.favorited:hover {
box-shadow: 0 6px 20px rgba(255, 71, 87, 0.6);
}
.favorite-btn:disabled {
opacity: 0.6;
cursor: not-allowed;
}
.play-btn {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
border: none;
padding: 10px 20px;
border-radius: 8px;
cursor: pointer;
font-size: 1em;
transition: all 0.3s;
}
.play-btn:hover {
transform: scale(1.05);
box-shadow: 0 3px 10px rgba(102, 126, 234, 0.3);
}
.loading {
text-align: center;
padding: 50px;
color: #666;
font-size: 1.2em;
}
.empty-state {
text-align: center;
padding: 50px;
color: #999;
}
.empty-state-icon {
font-size: 5em;
margin-bottom: 20px;
opacity: 0.3;
}
.player {
background: white;
padding: 20px 30px;
border-top: 2px solid #e0e0e0;
display: none;
}
.player.active {
display: block;
}
.player-info {
display: flex;
align-items: center;
gap: 20px;
margin-bottom: 15px;
}
.player-cover {
width: 50px;
height: 50px;
border-radius: 8px;
object-fit: cover;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}
.player-controls {
display: flex;
gap: 10px;
align-items: center;
}
.player-controls button {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
border: none;
padding: 10px 15px;
border-radius: 8px;
cursor: pointer;
font-size: 1em;
}
.error-message {
background: #ff4757;
color: white;
padding: 15px;
border-radius: 8px;
margin-bottom: 20px;
display: none;
}
.error-message.show {
display: block;
}
.success-message {
background: linear-gradient(135deg, #5CDB95 0%, #05C46B 100%);
color: white;
padding: 15px 20px;
border-radius: 8px;
margin-bottom: 20px;
display: none;
animation: slideIn 0.3s ease;
font-weight: 500;
text-align: center;
}
.success-message.show {
display: block;
}
@keyframes slideIn {
from {
transform: translateY(-20px);
opacity: 0;
}
to {
transform: translateY(0);
opacity: 1;
}
}
@media (max-width: 768px) {
.container {
height: 100vh;
border-radius: 0;
}
.music-item {
flex-direction: column;
align-items: flex-start;
}
.search-box {
flex-direction: column;
}
}
</style>
</head>
<body>
<div class="container">
<div class="header">
<h1>🎵 喵音乐</h1>
<p>探索音乐世界,收藏你的最爱</p>
</div>
<div class="search-section">
<div class="search-box">
<input type="text" id="songInput" placeholder="输入歌曲名称..." />
<input type="text" id="artistInput" placeholder="歌手(可选)" />
<button onclick="searchMusic()">🔍 搜索</button>
</div>
</div>
<div class="tabs">
<div class="tab active" onclick="switchTab('search')">搜索结果</div>
<div class="tab" onclick="switchTab('favorites')">我喜欢</div>
</div>
<div class="content">
<div id="errorMessage" class="error-message"></div>
<div id="successMessage" class="success-message"></div>
<div id="searchResults" class="music-list active">
<div class="empty-state">
<div class="empty-state-icon">🎵</div>
<p>搜索你喜欢的音乐吧!</p>
</div>
</div>
<div id="favoritesList" class="music-list">
<div class="loading">正在加载收藏列表...</div>
</div>
</div>
<div id="player" class="player">
<div class="player-info">
<img id="playerCover" class="player-cover" src="" alt="">
<div>
<div id="playerTitle" class="music-title"></div>
<div id="playerArtist" class="music-artist"></div>
</div>
</div>
<audio id="audioPlayer" controls style="width: 100%;"></audio>
</div>
</div>
<script>
let currentTab = 'search';
let currentMusic = null;
let searchResults = [];
let favoritesList = [];
// 页面加载时获取收藏列表
window.addEventListener('DOMContentLoaded', () => {
loadFavorites();
});
// 切换标签页
function switchTab(tab) {
currentTab = tab;
// 更新标签样式
document.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));
event.target.classList.add('active');
// 更新内容显示
document.querySelectorAll('.music-list').forEach(list => list.classList.remove('active'));
if (tab === 'search') {
document.getElementById('searchResults').classList.add('active');
} else if (tab === 'favorites') {
document.getElementById('favoritesList').classList.add('active');
loadFavorites();
}
}
// 搜索音乐
async function searchMusic() {
const song = document.getElementById('songInput').value.trim();
const artist = document.getElementById('artistInput').value.trim();
if (!song) {
showError('请输入歌曲名称');
return;
}
const resultsDiv = document.getElementById('searchResults');
resultsDiv.innerHTML = '<div class="loading">正在搜索...</div>';
try {
const url = `/stream_pcm?song=${encodeURIComponent(song)}&artist=${encodeURIComponent(artist)}`;
const response = await fetch(url);
const data = await response.json();
if (data.title) {
searchResults = [data];
displayResults(searchResults, 'searchResults');
} else {
resultsDiv.innerHTML = `
<div class="empty-state">
<div class="empty-state-icon">😢</div>
<p>未找到相关音乐</p>
</div>
`;
}
} catch (error) {
console.error('Search error:', error);
showError('搜索失败,请重试');
resultsDiv.innerHTML = `
<div class="empty-state">
<div class="empty-state-icon">❌</div>
<p>搜索出错了</p>
</div>
`;
}
}
// 加载收藏列表
async function loadFavorites() {
const favoritesDiv = document.getElementById('favoritesList');
// 只在我喜欢标签页显示加载状态
if (currentTab === 'favorites') {
favoritesDiv.innerHTML = '<div class="loading">正在加载...</div>';
}
try {
const response = await fetch('/api/favorite/list');
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
console.log('Favorites data:', data); // 调试信息
favoritesList = data.songs || [];
// 只在我喜欢标签页更新显示
if (currentTab === 'favorites') {
if (favoritesList.length === 0) {
favoritesDiv.innerHTML = `
<div class="empty-state">
<div class="empty-state-icon">💔</div>
<p>还没有收藏任何音乐</p>
</div>
`;
} else {
displayResults(favoritesList, 'favoritesList');
}
}
} catch (error) {
console.error('Load favorites error:', error);
if (currentTab === 'favorites') {
favoritesDiv.innerHTML = `
<div class="empty-state">
<div class="empty-state-icon">❌</div>
<p>加载失败: ${error.message}</p>
</div>
`;
}
}
}
// 显示音乐列表
function displayResults(songs, containerId) {
const container = document.getElementById(containerId);
container.innerHTML = '';
songs.forEach(song => {
const isFavorited = checkIfFavorited(song.title, song.artist);
const item = createMusicItem(song, isFavorited);
container.appendChild(item);
});
}
// 创建音乐项
function createMusicItem(song, isFavorited) {
const div = document.createElement('div');
div.className = 'music-item';
const coverUrl = song.cover_url || '';
const duration = formatDuration(song.duration);
div.innerHTML = `
<img class="music-cover" src="${coverUrl}" alt="${song.title}" onerror="this.style.display='none'">
<div class="music-info">
<div class="music-title">${song.title || '未知歌曲'}</div>
<div class="music-artist">${song.artist || '未知歌手'}</div>
<div class="music-duration">${duration}</div>
</div>
<button class="favorite-btn ${isFavorited ? 'favorited' : ''}" data-song='${JSON.stringify(song)}'>
${isFavorited ? '❤️' : '🤍'}
</button>
<button class="play-btn" data-song='${JSON.stringify(song)}'>
▶️ 播放
</button>
`;
// 绑定收藏按钮事件
const favoriteBtn = div.querySelector('.favorite-btn');
favoriteBtn.addEventListener('click', function(e) {
e.stopPropagation();
const songData = JSON.parse(this.getAttribute('data-song'));
toggleFavorite(e, songData, this);
});
// 绑定播放按钮事件
const playBtn = div.querySelector('.play-btn');
playBtn.addEventListener('click', function(e) {
e.stopPropagation();
const songData = JSON.parse(this.getAttribute('data-song'));
playMusic(e, songData);
});
return div;
}
// 播放音乐
function playMusic(event, song) {
event.stopPropagation();
currentMusic = song;
const player = document.getElementById('player');
const audioPlayer = document.getElementById('audioPlayer');
const playerCover = document.getElementById('playerCover');
const playerTitle = document.getElementById('playerTitle');
const playerArtist = document.getElementById('playerArtist');
// 更新播放器信息
playerCover.src = song.cover_url || '';
playerTitle.textContent = song.title || '未知歌曲';
playerArtist.textContent = song.artist || '未知歌手';
// 设置音频源
const audioUrl = song.audio_url || song.audio_full_url || '';
audioPlayer.src = audioUrl;
// 显示播放器并播放
player.classList.add('active');
audioPlayer.play();
// 更新播放状态样式
document.querySelectorAll('.music-item').forEach(item => {
item.classList.remove('playing');
});
event.target.closest('.music-item').classList.add('playing');
}
// 切换收藏状态
async function toggleFavorite(event, song, btnElement) {
event.stopPropagation();
const btn = btnElement;
const isFavorited = btn.classList.contains('favorited');
// 禁用按钮防止重复点击
btn.disabled = true;
try {
if (isFavorited) {
// 取消收藏
const response = await fetch(`/api/favorite/remove?title=${encodeURIComponent(song.title)}&artist=${encodeURIComponent(song.artist)}`, {
method: 'POST'
});
if (response.ok) {
btn.classList.remove('favorited');
btn.textContent = '🤍';
showSuccess('✅ 已取消收藏');
// 重新加载收藏列表
await loadFavorites();
// 如果在收藏列表中,重新显示
if (currentTab === 'favorites') {
setTimeout(() => {
displayResults(favoritesList, 'favoritesList');
}, 100);
}
} else {
showError('❌ 取消收藏失败');
}
} else {
// 添加收藏
const response = await fetch('/api/favorite/add', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(song)
});
if (response.ok) {
btn.classList.add('favorited');
btn.textContent = '❤️';
showSuccess('❤️ 收藏成功!点击"我喜欢"查看');
// 重新加载收藏列表
await loadFavorites();
} else {
showError('❌ 收藏失败');
}
}
} catch (error) {
console.error('Toggle favorite error:', error);
showError('❌ 操作失败,请重试');
} finally {
// 重新启用按钮
btn.disabled = false;
}
}
// 检查是否已收藏
function checkIfFavorited(title, artist) {
return favoritesList.some(song =>
song.title === title && song.artist === artist
);
}
// 格式化时长
function formatDuration(seconds) {
if (!seconds) return '';
const mins = Math.floor(seconds / 60);
const secs = Math.floor(seconds % 60);
return `${mins}:${secs.toString().padStart(2, '0')}`;
}
// 显示错误信息
function showError(message) {
const errorDiv = document.getElementById('errorMessage');
errorDiv.textContent = message;
errorDiv.classList.add('show');
setTimeout(() => {
errorDiv.classList.remove('show');
}, 3000);
}
// 显示成功信息
function showSuccess(message) {
const successDiv = document.getElementById('successMessage');
successDiv.textContent = message;
successDiv.classList.add('show');
setTimeout(() => {
successDiv.classList.remove('show');
}, 2000);
}
// 支持回车搜索
document.getElementById('songInput').addEventListener('keypress', (e) => {
if (e.key === 'Enter') searchMusic();
});
document.getElementById('artistInput').addEventListener('keypress', (e) => {
if (e.key === 'Enter') searchMusic();
});
</script>
</body>
</html>

367
theme/music-app.html Normal file
View File

@@ -0,0 +1,367 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport"="width=device-width, initial-scale=1.0">
<title>Meow Music - 音乐播放器</title>
<script crossorigin src="https://cdn.jsdelivr.net/npm/react@18/umd/react.production.min.js"></script>
<script crossorigin src="https://cdn.jsdelivr.net/npm/react-dom@18/umd/react-dom.production.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@babel/standalone@7/babel.min.js"></script>
<script src="https://cdn.tailwindcss.com"></script>
<style>
body { margin: 0; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif; }
.gradient-bg { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); }
.glass { background: rgba(255, 255, 255, 0.1); backdrop-filter: blur(10px); border: 1px solid rgba(255, 255, 255, 0.2); }
</style>
</head>
<body>
<div id="root"></div>
<script type="text/babel">
const { useState, useEffect } = React;
// API 配置
const API_BASE = '';
// 本地存储工具
const storage = {
getToken: () => localStorage.getItem('token'),
setToken: (token) => localStorage.setItem('token', token),
removeToken: () => localStorage.removeItem('token'),
getUser: () => JSON.parse(localStorage.getItem('user') || 'null'),
setUser: (user) => localStorage.setItem('user', JSON.stringify(user)),
removeUser: () => localStorage.removeItem('user')
};
// API 请求工具
const api = {
async request(url, options = {}) {
const token = storage.getToken();
const headers = {
'Content-Type': 'application/json',
...(token && { 'Authorization': `Bearer ${token}` }),
...options.headers
};
const response = await fetch(API_BASE + url, { ...options, headers });
if (!response.ok) throw new Error(await response.text());
return response.json();
},
// 认证
register: (data) => api.request('/api/auth/register', { method: 'POST', body: JSON.stringify(data) }),
login: (data) => api.request('/api/auth/login', { method: 'POST', body: JSON.stringify(data) }),
logout: () => api.request('/api/auth/logout', { method: 'POST' }),
getCurrentUser: () => api.request('/api/auth/me'),
// 音乐搜索
searchMusic: (song, artist = '') => api.request(`/stream_pcm?song=${encodeURIComponent(song)}&singer=${encodeURIComponent(artist)}`),
// 歌单管理
getPlaylists: () => api.request('/api/user/playlists'),
createPlaylist: (data) => api.request('/api/user/playlists/create', { method: 'POST', body: JSON.stringify(data) }),
addToPlaylist: (playlistId, song) => api.request(`/api/user/playlists/add-song?playlist_id=${playlistId}`, { method: 'POST', body: JSON.stringify(song) }),
removeFromPlaylist: (playlistId, title, artist) => api.request(`/api/user/playlists/remove-song?playlist_id=${playlistId}&title=${encodeURIComponent(title)}&artist=${encodeURIComponent(artist)}`, { method: 'DELETE' }),
deletePlaylist: (playlistId) => api.request(`/api/user/playlists/delete?playlist_id=${playlistId}`, { method: 'DELETE' })
};
// 登录/注册页面
function AuthPage({ onLogin }) {
const [isLogin, setIsLogin] = useState(true);
const [formData, setFormData] = useState({ username: '', email: '', password: '' });
const [error, setError] = useState('');
const [loading, setLoading] = useState(false);
const handleSubmit = async (e) => {
e.preventDefault();
setError('');
setLoading(true);
try {
const data = isLogin
? await api.login({ username: formData.username, password: formData.password })
: await api.register(formData);
storage.setToken(data.token);
storage.setUser(data.user);
onLogin(data.user);
} catch (err) {
setError(err.message || '操作失败,请重试');
} finally {
setLoading(false);
}
};
return (
<div className="min-h-screen gradient-bg flex items-center justify-center p-4">
<div className="glass rounded-2xl p-8 w-full max-w-md text-white">
<h1 className="text-3xl font-bold mb-6 text-center">🎵 Meow Music</h1>
<div className="flex gap-4 mb-6">
<button onClick={() => setIsLogin(true)} className={`flex-1 py-2 rounded-lg ${isLogin ? 'bg-white text-purple-600' : 'bg-white/20'}`}>
登录
</button>
<button onClick={() => setIsLogin(false)} className={`flex-1 py-2 rounded-lg ${!isLogin ? 'bg-white text-purple-600' : 'bg-white/20'}`}>
注册
</button>
</div>
<form onSubmit={handleSubmit} className="space-y-4">
<input
type="text"
placeholder="用户名"
value={formData.username}
onChange={(e) => setFormData({ ...formData, username: e.target.value })}
className="w-full px-4 py-3 rounded-lg bg-white/20 border border-white/30 text-white placeholder-white/60 focus:outline-none focus:ring-2 focus:ring-white/50"
required
/>
{!isLogin && (
<input
type="email"
placeholder="邮箱"
value={formData.email}
onChange={(e) => setFormData({ ...formData, email: e.target.value })}
className="w-full px-4 py-3 rounded-lg bg-white/20 border border-white/30 text-white placeholder-white/60 focus:outline-none focus:ring-2 focus:ring-white/50"
required
/>
)}
<input
type="password"
placeholder="密码"
value={formData.password}
onChange={(e) => setFormData({ ...formData, password: e.target.value })}
className="w-full px-4 py-3 rounded-lg bg-white/20 border border-white/30 text-white placeholder-white/60 focus:outline-none focus:ring-2 focus:ring-white/50"
required
/>
{error && <div className="bg-red-500/20 border border-red-500 text-white px-4 py-2 rounded-lg">{error}</div>}
<button
type="submit"
disabled={loading}
className="w-full py-3 bg-white text-purple-600 rounded-lg font-semibold hover:bg-white/90 transition disabled:opacity-50"
>
{loading ? '处理中...' : (isLogin ? '登录' : '注册')}
</button>
</form>
</div>
</div>
);
}
// 主应用页面
function MusicApp({ user, onLogout }) {
const [currentView, setCurrentView] = useState('search');
const [searchQuery, setSearchQuery] = useState('');
const [searchResult, setSearchResult] = useState(null);
const [playlists, setPlaylists] = useState([]);
const [selectedPlaylist, setSelectedPlaylist] = useState(null);
const [loading, setLoading] = useState(false);
const [audio, setAudio] = useState(null);
const [isPlaying, setIsPlaying] = useState(false);
useEffect(() => {
loadPlaylists();
}, []);
const loadPlaylists = async () => {
try {
const data = await api.getPlaylists();
setPlaylists(data || []);
} catch (err) {
console.error('加载歌单失败:', err);
}
};
const handleSearch = async (e) => {
e.preventDefault();
if (!searchQuery.trim()) return;
setLoading(true);
try {
const result = await api.searchMusic(searchQuery);
setSearchResult(result);
} catch (err) {
alert('搜索失败: ' + err.message);
} finally {
setLoading(false);
}
};
const handlePlay = (song) => {
if (audio) {
audio.pause();
}
const newAudio = new Audio(song.audio_full_url);
newAudio.play();
setAudio(newAudio);
setIsPlaying(true);
newAudio.onended = () => setIsPlaying(false);
};
const handleAddToPlaylist = async (playlistId, song) => {
try {
await api.addToPlaylist(playlistId, song);
alert('添加成功');
loadPlaylists();
} catch (err) {
alert('添加失败: ' + err.message);
}
};
const handleCreatePlaylist = async () => {
const name = prompt('请输入歌单名称:');
if (!name) return;
try {
await api.createPlaylist({ name, description: '' });
loadPlaylists();
} catch (err) {
alert('创建失败: ' + err.message);
}
};
return (
<div className="min-h-screen bg-gray-50">
{/* 顶部导航栏 */}
<nav className="gradient-bg text-white p-4 shadow-lg">
<div className="container mx-auto flex justify-between items-center">
<h1 className="text-2xl font-bold">🎵 Meow Music</h1>
<div className="flex items-center gap-4">
<span>欢迎, {user.username}</span>
<button onClick={onLogout} className="bg-white/20 px-4 py-2 rounded-lg hover:bg-white/30 transition">
退出
</button>
</div>
</div>
</nav>
<div className="container mx-auto p-4 flex gap-4">
{/* 侧边栏 */}
<div className="w-64 bg-white rounded-lg shadow p-4">
<button onClick={() => setCurrentView('search')} className={`w-full text-left px-4 py-2 rounded-lg mb-2 ${currentView === 'search' ? 'bg-purple-100 text-purple-600' : 'hover:bg-gray-100'}`}>
🔍 搜索音乐
</button>
<div className="mt-6">
<div className="flex justify-between items-center mb-2">
<h3 className="font-semibold text-gray-700">我的歌单</h3>
<button onClick={handleCreatePlaylist} className="text-purple-600 hover:text-purple-700">+</button>
</div>
{playlists.map(playlist => (
<button
key={playlist.id}
onClick={() => { setCurrentView('playlist'); setSelectedPlaylist(playlist); }}
className={`w-full text-left px-4 py-2 rounded-lg mb-1 ${selectedPlaylist?.id === playlist.id ? 'bg-purple-100 text-purple-600' : 'hover:bg-gray-100'}`}
>
{playlist.name} ({playlist.songs?.length || 0})
</button>
))}
</div>
</div>
{/* 主内容区 */}
<div className="flex-1 bg-white rounded-lg shadow p-6">
{currentView === 'search' && (
<div>
<h2 className="text-2xl font-bold mb-4">搜索音乐</h2>
<form onSubmit={handleSearch} className="mb-6">
<div className="flex gap-2">
<input
type="text"
placeholder="输入歌曲名称..."
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
className="flex-1 px-4 py-3 border rounded-lg focus:outline-none focus:ring-2 focus:ring-purple-600"
/>
<button type="submit" disabled={loading} className="px-6 py-3 bg-purple-600 text-white rounded-lg hover:bg-purple-700 transition disabled:opacity-50">
{loading ? '搜索中...' : '搜索'}
</button>
</div>
</form>
{searchResult && searchResult.title && (
<div className="border rounded-lg p-4 bg-gradient-to-r from-purple-50 to-pink-50">
<div className="flex justify-between items-start">
<div className="flex-1">
<h3 className="text-xl font-bold">{searchResult.title}</h3>
<p className="text-gray-600">👤 {searchResult.artist}</p>
{searchResult.from_cache && <span className="inline-block mt-2 px-2 py-1 bg-blue-100 text-blue-600 text-sm rounded">缓存</span>}
</div>
<div className="flex gap-2">
<button onClick={() => handlePlay(searchResult)} className="px-4 py-2 bg-purple-600 text-white rounded-lg hover:bg-purple-700">
播放
</button>
{playlists.length > 0 && (
<select onChange={(e) => handleAddToPlaylist(e.target.value, searchResult)} className="px-4 py-2 border rounded-lg">
<option value="">添加到...</option>
{playlists.map(p => (
<option key={p.id} value={p.id}>{p.name}</option>
))}
</select>
)}
</div>
</div>
</div>
)}
</div>
)}
{currentView === 'playlist' && selectedPlaylist && (
<div>
<h2 className="text-2xl font-bold mb-4">{selectedPlaylist.name}</h2>
<p className="text-gray-600 mb-6">{selectedPlaylist.description || '暂无描述'}</p>
{selectedPlaylist.songs && selectedPlaylist.songs.length > 0 ? (
<div className="space-y-2">
{selectedPlaylist.songs.map((song, index) => (
<div key={index} className="border rounded-lg p-4 flex justify-between items-center hover:bg-gray-50">
<div>
<h4 className="font-semibold">{song.title}</h4>
<p className="text-sm text-gray-600">{song.artist}</p>
</div>
<button onClick={() => handlePlay(song)} className="px-4 py-2 bg-purple-600 text-white rounded-lg hover:bg-purple-700">
播放
</button>
</div>
))}
</div>
) : (
<p className="text-gray-500 text-center py-8">暂无歌曲</p>
)}
</div>
)}
</div>
</div>
</div>
);
}
// 根组件
function App() {
const [user, setUser] = useState(storage.getUser());
const handleLogin = (userData) => {
setUser(userData);
};
const handleLogout = () => {
storage.removeToken();
storage.removeUser();
setUser(null);
};
return user ? <MusicApp user={user} onLogout={handleLogout} /> : <AuthPage onLogin={handleLogin} />;
}
// 渲染应用
ReactDOM.render(<App />, document.getElementById('root'));
</script>
</body>
</html>

476
theme/simple-app.html Normal file
View File

@@ -0,0 +1,476 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Meow Music - 音乐播放器</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Microsoft YaHei', sans-serif;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
min-height: 100vh;
display: flex;
align-items: center;
justify-content: center;
}
.container {
background: rgba(255, 255, 255, 0.95);
border-radius: 20px;
padding: 40px;
width: 90%;
max-width: 450px;
box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
}
h1 {
text-align: center;
color: #667eea;
margin-bottom: 30px;
font-size: 32px;
}
.tabs {
display: flex;
gap: 10px;
margin-bottom: 30px;
}
.tab {
flex: 1;
padding: 12px;
border: none;
background: #f0f0f0;
border-radius: 8px;
cursor: pointer;
font-size: 16px;
transition: all 0.3s;
}
.tab.active {
background: #667eea;
color: white;
}
.form {
display: none;
}
.form.active {
display: block;
}
.input-group {
margin-bottom: 20px;
}
label {
display: block;
margin-bottom: 8px;
color: #333;
font-weight: 500;
}
input {
width: 100%;
padding: 12px;
border: 2px solid #e0e0e0;
border-radius: 8px;
font-size: 14px;
transition: border-color 0.3s;
}
input:focus {
outline: none;
border-color: #667eea;
}
button[type="submit"] {
width: 100%;
padding: 14px;
background: #667eea;
color: white;
border: none;
border-radius: 8px;
font-size: 16px;
font-weight: 600;
cursor: pointer;
transition: background 0.3s;
}
button[type="submit"]:hover {
background: #5568d3;
}
button[type="submit"]:disabled {
background: #ccc;
cursor: not-allowed;
}
.message {
padding: 12px;
border-radius: 8px;
margin-bottom: 20px;
text-align: center;
}
.message.error {
background: #fee;
color: #c33;
border: 1px solid #fcc;
}
.message.success {
background: #efe;
color: #3c3;
border: 1px solid #cfc;
}
.app-container {
display: none;
}
.app-container.active {
display: block;
}
.header {
background: white;
padding: 20px;
margin: -20px -20px 20px -20px;
border-radius: 20px 20px 0 0;
display: flex;
justify-content: space-between;
align-items: center;
}
.search-box {
margin-bottom: 20px;
}
.search-form {
display: flex;
gap: 10px;
}
.search-form input {
flex: 1;
}
.search-form button {
padding: 12px 24px;
background: #667eea;
color: white;
border: none;
border-radius: 8px;
cursor: pointer;
}
.result {
background: white;
padding: 20px;
border-radius: 12px;
margin-top: 20px;
}
.result h3 {
color: #333;
margin-bottom: 10px;
}
.result-actions {
margin-top: 15px;
display: flex;
gap: 10px;
}
.result-actions button {
padding: 10px 20px;
border: none;
border-radius: 8px;
cursor: pointer;
background: #667eea;
color: white;
}
</style>
</head>
<body>
<!-- 登录/注册界面 -->
<div class="container" id="authContainer">
<h1>🎵 Meow Music</h1>
<div class="tabs">
<button class="tab active" onclick="switchTab('login')">登录</button>
<button class="tab" onclick="switchTab('register')">注册</button>
</div>
<div id="message"></div>
<!-- 登录表单 -->
<form class="form active" id="loginForm" onsubmit="handleLogin(event)">
<div class="input-group">
<label>用户名</label>
<input type="text" name="username" required placeholder="请输入用户名">
</div>
<div class="input-group">
<label>密码</label>
<input type="password" name="password" required placeholder="请输入密码">
</div>
<button type="submit" id="loginBtn">登录</button>
</form>
<!-- 注册表单 -->
<form class="form" id="registerForm" onsubmit="handleRegister(event)">
<div class="input-group">
<label>用户名</label>
<input type="text" name="username" required placeholder="请输入用户名">
</div>
<div class="input-group">
<label>邮箱</label>
<input type="email" name="email" required placeholder="请输入邮箱">
</div>
<div class="input-group">
<label>密码</label>
<input type="password" name="password" required minlength="6" placeholder="至少6位密码">
</div>
<button type="submit" id="registerBtn">注册</button>
</form>
</div>
<!-- 主应用界面 -->
<div class="container app-container" id="appContainer" style="max-width: 800px;">
<div class="header">
<h2>🎵 Meow Music</h2>
<button onclick="handleLogout()" style="padding: 8px 16px; background: #667eea; color: white; border: none; border-radius: 6px; cursor: pointer;">
退出
</button>
</div>
<div class="search-box">
<form class="search-form" onsubmit="handleSearch(event)">
<input type="text" id="searchInput" placeholder="输入歌曲名称..." required>
<button type="submit">搜索</button>
</form>
</div>
<div id="searchResult"></div>
</div>
<script>
// 全局状态
let currentUser = null;
let token = localStorage.getItem('token');
// 页面加载时检查登录状态
window.onload = function() {
if (token) {
checkAuth();
}
};
// 切换标签
function switchTab(tab) {
const tabs = document.querySelectorAll('.tab');
const forms = document.querySelectorAll('.form');
tabs.forEach(t => t.classList.remove('active'));
forms.forEach(f => f.classList.remove('active'));
if (tab === 'login') {
tabs[0].classList.add('active');
document.getElementById('loginForm').classList.add('active');
} else {
tabs[1].classList.add('active');
document.getElementById('registerForm').classList.add('active');
}
document.getElementById('message').innerHTML = '';
}
// 显示消息
function showMessage(msg, type) {
const messageDiv = document.getElementById('message');
messageDiv.innerHTML = `<div class="message ${type}">${msg}</div>`;
}
// 注册
async function handleRegister(e) {
e.preventDefault();
console.log('开始注册...');
const btn = document.getElementById('registerBtn');
btn.disabled = true;
btn.textContent = '注册中...';
const formData = new FormData(e.target);
const data = {
username: formData.get('username'),
email: formData.get('email'),
password: formData.get('password')
};
console.log('注册数据:', data);
try {
console.log('发送请求到: /api/auth/register');
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 10000); // 10秒超时
const response = await fetch('/api/auth/register', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data),
signal: controller.signal
});
clearTimeout(timeoutId);
console.log('收到响应:', response.status);
const result = await response.json();
console.log('解析结果:', result);
if (response.ok) {
token = result.token;
localStorage.setItem('token', token);
currentUser = result.user;
showMessage('注册成功!', 'success');
setTimeout(() => showApp(), 1000);
} else {
showMessage(result.error || '注册失败', 'error');
}
} catch (error) {
console.error('注册错误:', error);
if (error.name === 'AbortError') {
showMessage('请求超时,请检查网络连接', 'error');
} else {
showMessage('网络错误: ' + error.message, 'error');
}
} finally {
btn.disabled = false;
btn.textContent = '注册';
}
}
// 登录
async function handleLogin(e) {
e.preventDefault();
const btn = document.getElementById('loginBtn');
btn.disabled = true;
btn.textContent = '登录中...';
const formData = new FormData(e.target);
const data = {
username: formData.get('username'),
password: formData.get('password')
};
try {
const response = await fetch('/api/auth/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
});
const result = await response.json();
if (response.ok) {
token = result.token;
localStorage.setItem('token', token);
currentUser = result.user;
showApp();
} else {
showMessage(result.error || '登录失败', 'error');
}
} catch (error) {
showMessage('网络错误: ' + error.message, 'error');
} finally {
btn.disabled = false;
btn.textContent = '登录';
}
}
// 检查认证
async function checkAuth() {
try {
const response = await fetch('/api/auth/me', {
headers: { 'Authorization': 'Bearer ' + token }
});
if (response.ok) {
currentUser = await response.json();
showApp();
} else {
localStorage.removeItem('token');
token = null;
}
} catch (error) {
console.error('Auth check failed:', error);
}
}
// 显示应用界面
function showApp() {
document.getElementById('authContainer').classList.remove('active');
document.getElementById('authContainer').style.display = 'none';
document.getElementById('appContainer').classList.add('active');
}
// 退出登录
function handleLogout() {
localStorage.removeItem('token');
token = null;
currentUser = null;
document.getElementById('authContainer').style.display = 'flex';
document.getElementById('appContainer').classList.remove('active');
location.reload();
}
// 搜索音乐
async function handleSearch(e) {
e.preventDefault();
const query = document.getElementById('searchInput').value;
const resultDiv = document.getElementById('searchResult');
resultDiv.innerHTML = '<p style="text-align:center; padding:20px;">搜索中...</p>';
try {
const response = await fetch(`/stream_pcm?song=${encodeURIComponent(query)}`);
const result = await response.json();
if (result.title) {
resultDiv.innerHTML = `
<div class="result">
<h3>${result.title}</h3>
<p style="color:#666; margin-bottom:10px;">👤 ${result.artist}</p>
${result.from_cache ? '<span style="background:#e3f2fd; color:#1976d2; padding:4px 8px; border-radius:4px; font-size:12px;">缓存</span>' : ''}
<div class="result-actions">
<button onclick="playMusic('${result.audio_full_url}')">▶ 播放</button>
</div>
<audio id="player" controls style="width:100%; margin-top:15px;">
<source src="${result.audio_full_url}" type="audio/mpeg">
</audio>
</div>
`;
} else {
resultDiv.innerHTML = '<p style="text-align:center; color:#999;">未找到歌曲</p>';
}
} catch (error) {
resultDiv.innerHTML = '<p style="text-align:center; color:red;">搜索失败: ' + error.message + '</p>';
}
}
// 播放音乐
function playMusic(url) {
const player = document.getElementById('player');
if (player) {
player.play();
}
}
</script>
</body>
</html>

270
theme/test-app.html Normal file
View File

@@ -0,0 +1,270 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Meow Music - 测试版</title>
<style>
body {
font-family: Arial, sans-serif;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
min-height: 100vh;
display: flex;
align-items: center;
justify-content: center;
margin: 0;
}
.container {
background: white;
padding: 40px;
border-radius: 20px;
width: 400px;
box-shadow: 0 10px 40px rgba(0,0,0,0.3);
}
h1 { text-align: center; color: #667eea; margin-bottom: 30px; }
input, button {
width: 100%;
padding: 12px;
margin: 10px 0;
border: 1px solid #ddd;
border-radius: 8px;
box-sizing: border-box;
font-size: 14px;
}
button {
background: #667eea;
color: white;
border: none;
cursor: pointer;
font-size: 16px;
font-weight: bold;
}
button:hover { background: #5568d3; }
button:disabled { background: #ccc; cursor: not-allowed; }
.msg {
padding: 10px;
margin: 10px 0;
border-radius: 8px;
text-align: center;
}
.error { background: #fee; color: #c33; border: 1px solid #fcc; }
.success { background: #efe; color: #3c3; border: 1px solid #cfc; }
.info { background: #e3f2fd; color: #1976d2; border: 1px solid #90caf9; }
.tabs {
display: flex;
gap: 10px;
margin-bottom: 20px;
}
.tab {
flex: 1;
padding: 10px;
background: #f0f0f0;
border: none;
border-radius: 8px;
cursor: pointer;
}
.tab.active { background: #667eea; color: white; }
.form { display: none; }
.form.active { display: block; }
#debug {
margin-top: 20px;
padding: 10px;
background: #f5f5f5;
border-radius: 8px;
font-size: 12px;
max-height: 200px;
overflow-y: auto;
}
</style>
</head>
<body>
<div class="container">
<h1>🎵 Meow Music</h1>
<div class="tabs">
<button class="tab active" onclick="switchTab('login')">登录</button>
<button class="tab" onclick="switchTab('register')">注册</button>
</div>
<div id="message"></div>
<div id="loginForm" class="form active">
<input type="text" id="loginUsername" placeholder="用户名" required>
<input type="password" id="loginPassword" placeholder="密码" required>
<button onclick="doLogin()">登录</button>
</div>
<div id="registerForm" class="form">
<input type="text" id="regUsername" placeholder="用户名" required>
<input type="email" id="regEmail" placeholder="邮箱" required>
<input type="password" id="regPassword" placeholder="密码至少6位" required>
<button onclick="doRegister()">注册</button>
</div>
<div id="debug" style="display:none;"></div>
<button onclick="toggleDebug()" style="background:#888;margin-top:10px;">显示/隐藏调试信息</button>
</div>
<script>
let debugMode = false;
function log(msg) {
console.log(msg);
if (debugMode) {
const debug = document.getElementById('debug');
debug.innerHTML += '<div>' + new Date().toLocaleTimeString() + ': ' + msg + '</div>';
debug.scrollTop = debug.scrollHeight;
}
}
function toggleDebug() {
debugMode = !debugMode;
document.getElementById('debug').style.display = debugMode ? 'block' : 'none';
}
function switchTab(tab) {
document.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));
document.querySelectorAll('.form').forEach(f => f.classList.remove('active'));
if (tab === 'login') {
document.querySelectorAll('.tab')[0].classList.add('active');
document.getElementById('loginForm').classList.add('active');
} else {
document.querySelectorAll('.tab')[1].classList.add('active');
document.getElementById('registerForm').classList.add('active');
}
showMessage('', '');
}
function showMessage(msg, type) {
const msgDiv = document.getElementById('message');
if (msg) {
msgDiv.innerHTML = '<div class="msg ' + type + '">' + msg + '</div>';
} else {
msgDiv.innerHTML = '';
}
}
async function doRegister() {
const username = document.getElementById('regUsername').value.trim();
const email = document.getElementById('regEmail').value.trim();
const password = document.getElementById('regPassword').value;
if (!username || !email || !password) {
showMessage('请填写所有字段', 'error');
return;
}
if (password.length < 6) {
showMessage('密码至少6位', 'error');
return;
}
log('开始注册: ' + username);
showMessage('注册中...', 'info');
try {
const data = JSON.stringify({
username: username,
email: email,
password: password
});
log('发送数据: ' + data);
const response = await fetch('/api/auth/register', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: data
});
log('响应状态: ' + response.status);
const text = await response.text();
log('响应内容: ' + text);
let result;
try {
result = JSON.parse(text);
} catch (e) {
throw new Error('服务器返回了非JSON数据: ' + text.substring(0, 100));
}
if (response.ok) {
showMessage('注册成功!请登录', 'success');
setTimeout(() => {
switchTab('login');
document.getElementById('loginUsername').value = username;
}, 1500);
} else {
showMessage(result.error || '注册失败', 'error');
}
} catch (error) {
log('错误: ' + error.message);
showMessage('错误: ' + error.message, 'error');
}
}
async function doLogin() {
const username = document.getElementById('loginUsername').value.trim();
const password = document.getElementById('loginPassword').value;
if (!username || !password) {
showMessage('请填写用户名和密码', 'error');
return;
}
log('开始登录: ' + username);
showMessage('登录中...', 'info');
try {
const data = JSON.stringify({
username: username,
password: password
});
log('发送数据: ' + data);
const response = await fetch('/api/auth/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: data
});
log('响应状态: ' + response.status);
const text = await response.text();
log('响应内容: ' + text);
let result;
try {
result = JSON.parse(text);
} catch (e) {
throw new Error('服务器返回了非JSON数据: ' + text.substring(0, 100));
}
if (response.ok) {
localStorage.setItem('token', result.token);
showMessage('登录成功!', 'success');
log('Token已保存');
setTimeout(() => {
alert('登录成功Token: ' + result.token.substring(0, 20) + '...\n\n现在可以使用API了\n\n实际应用中会跳转到主界面');
}, 500);
} else {
showMessage(result.error || '登录失败', 'error');
}
} catch (error) {
log('错误: ' + error.message);
showMessage('错误: ' + error.message, 'error');
}
}
log('页面加载完成');
</script>
</body>
</html>