v0.0.2 init
This commit is contained in:
50
.github/workflows/test-and-build.yml
vendored
50
.github/workflows/test-and-build.yml
vendored
@@ -27,8 +27,58 @@ jobs:
|
||||
run: |
|
||||
echo "Building version ${{ github.event.inputs.version_number }}"
|
||||
go mod tidy
|
||||
echo "Build linux i386 binary"
|
||||
CGO_ENABLED=0 GOOS=linux GOARCH=386 go build -ldflags "-s -w" -trimpath -o MeowEmbeddedMusicServer-Linux-i386 . && upx -9 MeowEmbeddedMusicServer-Linux-i386
|
||||
echo "Build linux amd64 binary"
|
||||
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags "-s -w" -trimpath -o MeowEmbeddedMusicServer-Linux-amd64 . && upx -9 MeowEmbeddedMusicServer-Linux-amd64
|
||||
echo "Build linux arm64 binary"
|
||||
CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build -ldflags "-s -w" -trimpath -o MeowEmbeddedMusicServer-Linux-arm64 . && upx -9 MeowEmbeddedMusicServer-Linux-arm64
|
||||
echo "Build windows i386 binary"
|
||||
CGO_ENABLED=0 GOOS=windows GOARCH=386 go build -ldflags "-s -w" -trimpath -o MeowEmbeddedMusicServer-Windows-i386.exe . && upx -9 MeowEmbeddedMusicServer-Windows-i386.exe
|
||||
echo "Build windows amd64 binary"
|
||||
CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build -ldflags "-s -w" -trimpath -o MeowEmbeddedMusicServer-Windows-amd64.exe . && upx -9 MeowEmbeddedMusicServer-Windows-amd64.exe
|
||||
echo "Build windows arm64 binary"
|
||||
CGO_ENABLED=0 GOOS=windows GOARCH=arm64 go build -ldflags "-s -w" -trimpath -o MeowEmbeddedMusicServer-Windows-arm64.exe . && upx -9 MeowEmbeddedMusicServer- Windows-arm64.exe
|
||||
echo "Build darwin amd64 binary"
|
||||
CGO_ENABLED=0 GOOS=darwin GOARCH=amd64 go build -ldflags "-s -w" -trimpath -o MeowEmbeddedMusicServer-Darwin-amd64 .
|
||||
echo "Build darwin arm64 binary"
|
||||
CGO_ENABLED=0 GOOS=darwin GOARCH=arm64 go build -ldflags "-s -w" -trimpath -o MeowEmbeddedMusicServer-Darwin-arm64 .
|
||||
- name: Build pre-release
|
||||
if: ${{ github.event.inputs.build_type == 'pre' }}
|
||||
run: |
|
||||
echo "Building pre-release ${{ github.event.inputs.version_number }}"
|
||||
go mod tidy
|
||||
echo "Build linux i386 binary"
|
||||
CGO_ENABLED=0 GOOS=linux GOARCH=386 go build -ldflags "-s -w" -trimpath -o MeowEmbeddedMusicServer-Linux-i386 . && upx -9 MeowEmbeddedMusicServer-Linux-i386
|
||||
echo "Build linux amd64 binary"
|
||||
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags "-s -w" -trimpath -o MeowEmbeddedMusicServer-Linux-amd64 . && upx -9 MeowEmbeddedMusicServer-Linux-amd64
|
||||
echo "Build linux arm64 binary"
|
||||
CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build -ldflags "-s -w" -trimpath -o MeowEmbeddedMusicServer-Linux-arm64 . && upx -9 MeowEmbeddedMusicServer-Linux-arm64
|
||||
echo "Build windows i386 binary"
|
||||
CGO_ENABLED=0 GOOS=windows GOARCH=386 go build -ldflags "-s -w" -trimpath -o MeowEmbeddedMusicServer-Windows-i386.exe . && upx -9 MeowEmbeddedMusicServer-Windows-i386.exe
|
||||
echo "Build windows amd64 binary"
|
||||
CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build -ldflags "-s -w" -trimpath -o MeowEmbeddedMusicServer-Windows-amd64.exe . && upx -9 MeowEmbeddedMusicServer-Windows-amd64.exe
|
||||
echo "Build windows arm64 binary"
|
||||
CGO_ENABLED=0 GOOS=windows GOARCH=arm64 go build -ldflags "-s -w" -trimpath -o MeowEmbeddedMusicServer-Windows-arm64.exe . && upx -9 MeowEmbeddedMusicServer-Windows-arm64.exe
|
||||
echo "Build darwin amd64 binary"
|
||||
CGO_ENABLED=0 GOOS=darwin GOARCH=amd64 go build -ldflags "-s -w" -trimpath -o MeowEmbeddedMusicServer-Darwin-amd64 .
|
||||
echo "Build darwin arm64 binary"
|
||||
CGO_ENABLED=0 GOOS=darwin GOARCH=arm64 go build -ldflags "-s -w" -trimpath -o MeowEmbeddedMusicServer-Darwin-arm64 .
|
||||
- name: Upload binaries
|
||||
uses: softprops/action-gh-release@v1
|
||||
with:
|
||||
tag_name: ${{ github.event.inputs.version_number }}
|
||||
name: ${{ github.event.inputs.version_number }}
|
||||
files: |
|
||||
MeowEmbeddedMusicServer-Linux-i386
|
||||
MeowEmbeddedMusicServer-Linux-amd64
|
||||
MeowEmbeddedMusicServer-Linux-arm64
|
||||
MeowEmbeddedMusicServer-Windows-i386.exe
|
||||
MeowEmbeddedMusicServer-Windows-amd64.exe
|
||||
MeowEmbeddedMusicServer-Windows-arm64.exe
|
||||
MeowEmbeddedMusicServer-Darwin-amd64
|
||||
MeowEmbeddedMusicServer-Darwin-arm64
|
||||
prerelease: ${{ github.event.inputs.build_type == 'pre' }}
|
||||
make_latest: ${{ github.event.inputs.build_type != 'pre' }}
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
321
DEVICE_BINDING_GUIDE.md
Executable file
321
DEVICE_BINDING_GUIDE.md
Executable file
@@ -0,0 +1,321 @@
|
||||
# ESP32设备绑定功能使用指南
|
||||
|
||||
## 📋 功能概述
|
||||
|
||||
ESP32音乐播放器现在支持绑定到用户账号,实现个性化功能:
|
||||
- ✅ 设备与用户账号绑定
|
||||
- ✅ 安全的Token认证机制
|
||||
- ✅ 通过语音命令完成绑定
|
||||
- ✅ 为后续歌单功能奠定基础
|
||||
|
||||
---
|
||||
|
||||
## 🚀 快速开始
|
||||
|
||||
### **第1步:启动服务器**
|
||||
|
||||
```powershell
|
||||
cd d:\esp32-music-server\Meow\MeowEmbeddedMusicServer
|
||||
go run .
|
||||
```
|
||||
|
||||
服务器将在 `http://localhost:2233` 启动
|
||||
|
||||
---
|
||||
|
||||
### **第2步:用户登录**
|
||||
|
||||
访问:`http://localhost:2233`
|
||||
|
||||
使用测试账号登录:
|
||||
- 用户名:`test`
|
||||
- 密码:`123456`
|
||||
|
||||
---
|
||||
|
||||
### **第3步:生成绑定码**
|
||||
|
||||
**方式1:使用命令行工具(临时)**
|
||||
|
||||
```powershell
|
||||
# 向服务器请求生成绑定码
|
||||
curl -X POST http://localhost:2233/api/device/generate-code `
|
||||
-H "Content-Type: application/json" `
|
||||
-H "Cookie: session_token=YOUR_SESSION_TOKEN"
|
||||
```
|
||||
|
||||
**方式2:使用浏览器控制台(推荐)**
|
||||
|
||||
1. 登录后按 `F12` 打开开发者工具
|
||||
2. 切换到 **Console** 标签
|
||||
3. 输入以下代码:
|
||||
|
||||
```javascript
|
||||
fetch('/api/device/generate-code', {
|
||||
method: 'POST',
|
||||
headers: {'Content-Type': 'application/json'}
|
||||
})
|
||||
.then(r => r.json())
|
||||
.then(data => {
|
||||
console.log('绑定码:', data.code);
|
||||
alert('绑定码:' + data.code + '\n有效期:5分钟');
|
||||
});
|
||||
```
|
||||
|
||||
4. 记下显示的6位数字绑定码,例如:`123456`
|
||||
|
||||
---
|
||||
|
||||
### **第4步:ESP32端绑定**
|
||||
|
||||
对ESP32说:
|
||||
|
||||
```
|
||||
"小智,绑定设备,绑定码123456"
|
||||
```
|
||||
|
||||
或者:
|
||||
|
||||
```
|
||||
"小智,bind device, binding code is 123456"
|
||||
```
|
||||
|
||||
ESP32会回复:
|
||||
|
||||
```
|
||||
✅ 设备绑定成功!
|
||||
已绑定到用户: test
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### **第5步:验证绑定状态**
|
||||
|
||||
对ESP32说:
|
||||
|
||||
```
|
||||
"小智,查询设备状态"
|
||||
```
|
||||
|
||||
ESP32会显示:
|
||||
|
||||
```
|
||||
📱 设备信息:
|
||||
|
||||
MAC地址: AA:BB:CC:DD:EE:FF
|
||||
绑定状态: ✅ 已绑定
|
||||
绑定用户: test
|
||||
服务器验证: ✅ 通过
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🔧 高级功能
|
||||
|
||||
### **解绑设备**
|
||||
|
||||
对ESP32说:
|
||||
|
||||
```
|
||||
"小智,解绑设备"
|
||||
```
|
||||
|
||||
### **自定义设备名称**
|
||||
|
||||
对ESP32说:
|
||||
|
||||
```
|
||||
"小智,绑定设备,绑定码123456,设备名称客厅音响"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📊 数据存储
|
||||
|
||||
### **服务器端**
|
||||
|
||||
设备信息存储在:`d:\esp32-music-server\Meow\MeowEmbeddedMusicServer\devices.json`
|
||||
|
||||
```json
|
||||
{
|
||||
"devices": {
|
||||
"AA:BB:CC:DD:EE:FF": {
|
||||
"mac": "AA:BB:CC:DD:EE:FF",
|
||||
"username": "test",
|
||||
"device_name": "ESP32音乐播放器",
|
||||
"token": "a1b2c3d4e5f6...",
|
||||
"bind_time": "2025-11-24T16:00:00Z",
|
||||
"last_seen": "2025-11-24T16:30:00Z",
|
||||
"is_active": true
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### **ESP32端**
|
||||
|
||||
Token存储在NVS(非易失性存储)中:
|
||||
- 命名空间:`device`
|
||||
- Key: `token` - 设备Token
|
||||
- Key: `username` - 绑定的用户名
|
||||
|
||||
---
|
||||
|
||||
## 🔌 API文档
|
||||
|
||||
### **1. 生成绑定码**
|
||||
|
||||
```
|
||||
POST /api/device/generate-code
|
||||
Authorization: 需要登录
|
||||
```
|
||||
|
||||
**响应:**
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"code": "123456",
|
||||
"expires_in": 300
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### **2. ESP32绑定设备**
|
||||
|
||||
```
|
||||
POST /api/esp32/bind
|
||||
Content-Type: application/json
|
||||
```
|
||||
|
||||
**请求体:**
|
||||
```json
|
||||
{
|
||||
"mac": "AA:BB:CC:DD:EE:FF",
|
||||
"binding_code": "123456",
|
||||
"device_name": "ESP32音乐播放器"
|
||||
}
|
||||
```
|
||||
|
||||
**响应:**
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"message": "设备绑定成功",
|
||||
"token": "a1b2c3d4e5f6...",
|
||||
"username": "test"
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### **3. 验证设备Token**
|
||||
|
||||
```
|
||||
GET /api/esp32/verify
|
||||
X-Device-Token: a1b2c3d4e5f6...
|
||||
```
|
||||
|
||||
**响应:**
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"device": {
|
||||
"mac": "AA:BB:CC:DD:EE:FF",
|
||||
"username": "test",
|
||||
"device_name": "ESP32音乐播放器",
|
||||
"bind_time": "2025-11-24T16:00:00Z",
|
||||
"last_seen": "2025-11-24T16:30:00Z"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🧪 测试流程
|
||||
|
||||
### **完整测试步骤**
|
||||
|
||||
1. **启动服务器**
|
||||
```powershell
|
||||
go run .
|
||||
```
|
||||
|
||||
2. **生成绑定码**(使用浏览器控制台)
|
||||
|
||||
3. **ESP32绑定**
|
||||
- 对ESP32说:"小智,绑定设备,绑定码123456"
|
||||
- 观察ESP32日志:
|
||||
```
|
||||
[DeviceManager] Starting device binding with code: 123456
|
||||
[DeviceManager] Sending bind request to: http://...
|
||||
[DeviceManager] Bind request status code: 200
|
||||
[DeviceManager] Device successfully bound to user: test
|
||||
```
|
||||
|
||||
4. **查询状态**
|
||||
- 对ESP32说:"小智,查询设备状态"
|
||||
|
||||
5. **验证服务器数据**
|
||||
- 检查 `devices.json` 文件是否包含设备信息
|
||||
|
||||
6. **测试解绑**
|
||||
- 对ESP32说:"小智,解绑设备"
|
||||
- 再次查询状态,应显示未绑定
|
||||
|
||||
---
|
||||
|
||||
## 🐛 故障排除
|
||||
|
||||
### **问题1:绑定码无效**
|
||||
|
||||
**现象**:ESP32提示"绑定失败"
|
||||
|
||||
**解决方案**:
|
||||
- 检查绑定码是否输入正确
|
||||
- 绑定码有效期为5分钟,请重新生成
|
||||
- 确认网络连接正常
|
||||
|
||||
---
|
||||
|
||||
### **问题2:设备已绑定**
|
||||
|
||||
**现象**:提示"设备已绑定到用户XXX"
|
||||
|
||||
**解决方案**:
|
||||
- 先解绑设备:对ESP32说"小智,解绑设备"
|
||||
- 或者在服务器端删除 `devices.json` 中的设备记录
|
||||
|
||||
---
|
||||
|
||||
### **问题3:网络连接失败**
|
||||
|
||||
**现象**:ESP32无法连接到服务器
|
||||
|
||||
**解决方案**:
|
||||
- 检查ESP32是否连接到WiFi
|
||||
- 确认服务器地址是否正确:`http://http-embedded-music.miao-lab.top:2233`
|
||||
- 检查防火墙设置
|
||||
|
||||
---
|
||||
|
||||
## 📝 下一步
|
||||
|
||||
绑定功能完成后,可以继续开发:
|
||||
|
||||
✅ **阶段1:基础绑定** - 已完成
|
||||
⏳ **阶段2:歌单系统** - 待开发
|
||||
⏳ **阶段3:Web管理界面** - 待开发
|
||||
|
||||
---
|
||||
|
||||
## 💡 提示
|
||||
|
||||
- 绑定码每次生成后只能使用一次
|
||||
- 一个设备只能绑定到一个用户
|
||||
- Token存储在ESP32的NVS中,断电不丢失
|
||||
- 可以通过解绑并重新绑定来更换用户
|
||||
|
||||
---
|
||||
|
||||
**🎉 享受您的个性化ESP32音乐播放器!**
|
||||
705
LICENSE
Normal file → Executable file
705
LICENSE
Normal file → Executable file
@@ -1,504 +1,201 @@
|
||||
GNU LESSER GENERAL PUBLIC LICENSE
|
||||
Version 2.1, February 1999
|
||||
|
||||
Copyright (C) 1991, 1999 Free Software Foundation, Inc.
|
||||
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
[This is the first released version of the Lesser GPL. It also counts
|
||||
as the successor of the GNU Library Public License, version 2, hence
|
||||
the version number 2.1.]
|
||||
|
||||
Preamble
|
||||
|
||||
The licenses for most software are designed to take away your
|
||||
freedom to share and change it. By contrast, the GNU General Public
|
||||
Licenses are intended to guarantee your freedom to share and change
|
||||
free software--to make sure the software is free for all its users.
|
||||
|
||||
This license, the Lesser General Public License, applies to some
|
||||
specially designated software packages--typically libraries--of the
|
||||
Free Software Foundation and other authors who decide to use it. You
|
||||
can use it too, but we suggest you first think carefully about whether
|
||||
this license or the ordinary General Public License is the better
|
||||
strategy to use in any particular case, based on the explanations below.
|
||||
|
||||
When we speak of free software, we are referring to freedom of use,
|
||||
not price. Our General Public Licenses are designed to make sure that
|
||||
you have the freedom to distribute copies of free software (and charge
|
||||
for this service if you wish); that you receive source code or can get
|
||||
it if you want it; that you can change the software and use pieces of
|
||||
it in new free programs; and that you are informed that you can do
|
||||
these things.
|
||||
|
||||
To protect your rights, we need to make restrictions that forbid
|
||||
distributors to deny you these rights or to ask you to surrender these
|
||||
rights. These restrictions translate to certain responsibilities for
|
||||
you if you distribute copies of the library or if you modify it.
|
||||
|
||||
For example, if you distribute copies of the library, whether gratis
|
||||
or for a fee, you must give the recipients all the rights that we gave
|
||||
you. You must make sure that they, too, receive or can get the source
|
||||
code. If you link other code with the library, you must provide
|
||||
complete object files to the recipients, so that they can relink them
|
||||
with the library after making changes to the library and recompiling
|
||||
it. And you must show them these terms so they know their rights.
|
||||
|
||||
We protect your rights with a two-step method: (1) we copyright the
|
||||
library, and (2) we offer you this license, which gives you legal
|
||||
permission to copy, distribute and/or modify the library.
|
||||
|
||||
To protect each distributor, we want to make it very clear that
|
||||
there is no warranty for the free library. Also, if the library is
|
||||
modified by someone else and passed on, the recipients should know
|
||||
that what they have is not the original version, so that the original
|
||||
author's reputation will not be affected by problems that might be
|
||||
introduced by others.
|
||||
|
||||
Finally, software patents pose a constant threat to the existence of
|
||||
any free program. We wish to make sure that a company cannot
|
||||
effectively restrict the users of a free program by obtaining a
|
||||
restrictive license from a patent holder. Therefore, we insist that
|
||||
any patent license obtained for a version of the library must be
|
||||
consistent with the full freedom of use specified in this license.
|
||||
|
||||
Most GNU software, including some libraries, is covered by the
|
||||
ordinary GNU General Public License. This license, the GNU Lesser
|
||||
General Public License, applies to certain designated libraries, and
|
||||
is quite different from the ordinary General Public License. We use
|
||||
this license for certain libraries in order to permit linking those
|
||||
libraries into non-free programs.
|
||||
|
||||
When a program is linked with a library, whether statically or using
|
||||
a shared library, the combination of the two is legally speaking a
|
||||
combined work, a derivative of the original library. The ordinary
|
||||
General Public License therefore permits such linking only if the
|
||||
entire combination fits its criteria of freedom. The Lesser General
|
||||
Public License permits more lax criteria for linking other code with
|
||||
the library.
|
||||
|
||||
We call this license the "Lesser" General Public License because it
|
||||
does Less to protect the user's freedom than the ordinary General
|
||||
Public License. It also provides other free software developers Less
|
||||
of an advantage over competing non-free programs. These disadvantages
|
||||
are the reason we use the ordinary General Public License for many
|
||||
libraries. However, the Lesser license provides advantages in certain
|
||||
special circumstances.
|
||||
|
||||
For example, on rare occasions, there may be a special need to
|
||||
encourage the widest possible use of a certain library, so that it becomes
|
||||
a de-facto standard. To achieve this, non-free programs must be
|
||||
allowed to use the library. A more frequent case is that a free
|
||||
library does the same job as widely used non-free libraries. In this
|
||||
case, there is little to gain by limiting the free library to free
|
||||
software only, so we use the Lesser General Public License.
|
||||
|
||||
In other cases, permission to use a particular library in non-free
|
||||
programs enables a greater number of people to use a large body of
|
||||
free software. For example, permission to use the GNU C Library in
|
||||
non-free programs enables many more people to use the whole GNU
|
||||
operating system, as well as its variant, the GNU/Linux operating
|
||||
system.
|
||||
|
||||
Although the Lesser General Public License is Less protective of the
|
||||
users' freedom, it does ensure that the user of a program that is
|
||||
linked with the Library has the freedom and the wherewithal to run
|
||||
that program using a modified version of the Library.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow. Pay close attention to the difference between a
|
||||
"work based on the library" and a "work that uses the library". The
|
||||
former contains code derived from the library, whereas the latter must
|
||||
be combined with the library in order to run.
|
||||
|
||||
GNU LESSER GENERAL PUBLIC LICENSE
|
||||
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
|
||||
|
||||
0. This License Agreement applies to any software library or other
|
||||
program which contains a notice placed by the copyright holder or
|
||||
other authorized party saying it may be distributed under the terms of
|
||||
this Lesser General Public License (also called "this License").
|
||||
Each licensee is addressed as "you".
|
||||
|
||||
A "library" means a collection of software functions and/or data
|
||||
prepared so as to be conveniently linked with application programs
|
||||
(which use some of those functions and data) to form executables.
|
||||
|
||||
The "Library", below, refers to any such software library or work
|
||||
which has been distributed under these terms. A "work based on the
|
||||
Library" means either the Library or any derivative work under
|
||||
copyright law: that is to say, a work containing the Library or a
|
||||
portion of it, either verbatim or with modifications and/or translated
|
||||
straightforwardly into another language. (Hereinafter, translation is
|
||||
included without limitation in the term "modification".)
|
||||
|
||||
"Source code" for a work means the preferred form of the work for
|
||||
making modifications to it. For a library, complete source code means
|
||||
all the source code for all modules it contains, plus any associated
|
||||
interface definition files, plus the scripts used to control compilation
|
||||
and installation of the library.
|
||||
|
||||
Activities other than copying, distribution and modification are not
|
||||
covered by this License; they are outside its scope. The act of
|
||||
running a program using the Library is not restricted, and output from
|
||||
such a program is covered only if its contents constitute a work based
|
||||
on the Library (independent of the use of the Library in a tool for
|
||||
writing it). Whether that is true depends on what the Library does
|
||||
and what the program that uses the Library does.
|
||||
|
||||
1. You may copy and distribute verbatim copies of the Library's
|
||||
complete source code as you receive it, in any medium, provided that
|
||||
you conspicuously and appropriately publish on each copy an
|
||||
appropriate copyright notice and disclaimer of warranty; keep intact
|
||||
all the notices that refer to this License and to the absence of any
|
||||
warranty; and distribute a copy of this License along with the
|
||||
Library.
|
||||
|
||||
You may charge a fee for the physical act of transferring a copy,
|
||||
and you may at your option offer warranty protection in exchange for a
|
||||
fee.
|
||||
|
||||
2. You may modify your copy or copies of the Library or any portion
|
||||
of it, thus forming a work based on the Library, and copy and
|
||||
distribute such modifications or work under the terms of Section 1
|
||||
above, provided that you also meet all of these conditions:
|
||||
|
||||
a) The modified work must itself be a software library.
|
||||
|
||||
b) You must cause the files modified to carry prominent notices
|
||||
stating that you changed the files and the date of any change.
|
||||
|
||||
c) You must cause the whole of the work to be licensed at no
|
||||
charge to all third parties under the terms of this License.
|
||||
|
||||
d) If a facility in the modified Library refers to a function or a
|
||||
table of data to be supplied by an application program that uses
|
||||
the facility, other than as an argument passed when the facility
|
||||
is invoked, then you must make a good faith effort to ensure that,
|
||||
in the event an application does not supply such function or
|
||||
table, the facility still operates, and performs whatever part of
|
||||
its purpose remains meaningful.
|
||||
|
||||
(For example, a function in a library to compute square roots has
|
||||
a purpose that is entirely well-defined independent of the
|
||||
application. Therefore, Subsection 2d requires that any
|
||||
application-supplied function or table used by this function must
|
||||
be optional: if the application does not supply it, the square
|
||||
root function must still compute square roots.)
|
||||
|
||||
These requirements apply to the modified work as a whole. If
|
||||
identifiable sections of that work are not derived from the Library,
|
||||
and can be reasonably considered independent and separate works in
|
||||
themselves, then this License, and its terms, do not apply to those
|
||||
sections when you distribute them as separate works. But when you
|
||||
distribute the same sections as part of a whole which is a work based
|
||||
on the Library, the distribution of the whole must be on the terms of
|
||||
this License, whose permissions for other licensees extend to the
|
||||
entire whole, and thus to each and every part regardless of who wrote
|
||||
it.
|
||||
|
||||
Thus, it is not the intent of this section to claim rights or contest
|
||||
your rights to work written entirely by you; rather, the intent is to
|
||||
exercise the right to control the distribution of derivative or
|
||||
collective works based on the Library.
|
||||
|
||||
In addition, mere aggregation of another work not based on the Library
|
||||
with the Library (or with a work based on the Library) on a volume of
|
||||
a storage or distribution medium does not bring the other work under
|
||||
the scope of this License.
|
||||
|
||||
3. You may opt to apply the terms of the ordinary GNU General Public
|
||||
License instead of this License to a given copy of the Library. To do
|
||||
this, you must alter all the notices that refer to this License, so
|
||||
that they refer to the ordinary GNU General Public License, version 2,
|
||||
instead of to this License. (If a newer version than version 2 of the
|
||||
ordinary GNU General Public License has appeared, then you can specify
|
||||
that version instead if you wish.) Do not make any other change in
|
||||
these notices.
|
||||
|
||||
Once this change is made in a given copy, it is irreversible for
|
||||
that copy, so the ordinary GNU General Public License applies to all
|
||||
subsequent copies and derivative works made from that copy.
|
||||
|
||||
This option is useful when you wish to copy part of the code of
|
||||
the Library into a program that is not a library.
|
||||
|
||||
4. You may copy and distribute the Library (or a portion or
|
||||
derivative of it, under Section 2) in object code or executable form
|
||||
under the terms of Sections 1 and 2 above provided that you accompany
|
||||
it with the complete corresponding machine-readable source code, which
|
||||
must be distributed under the terms of Sections 1 and 2 above on a
|
||||
medium customarily used for software interchange.
|
||||
|
||||
If distribution of object code is made by offering access to copy
|
||||
from a designated place, then offering equivalent access to copy the
|
||||
source code from the same place satisfies the requirement to
|
||||
distribute the source code, even though third parties are not
|
||||
compelled to copy the source along with the object code.
|
||||
|
||||
5. A program that contains no derivative of any portion of the
|
||||
Library, but is designed to work with the Library by being compiled or
|
||||
linked with it, is called a "work that uses the Library". Such a
|
||||
work, in isolation, is not a derivative work of the Library, and
|
||||
therefore falls outside the scope of this License.
|
||||
|
||||
However, linking a "work that uses the Library" with the Library
|
||||
creates an executable that is a derivative of the Library (because it
|
||||
contains portions of the Library), rather than a "work that uses the
|
||||
library". The executable is therefore covered by this License.
|
||||
Section 6 states terms for distribution of such executables.
|
||||
|
||||
When a "work that uses the Library" uses material from a header file
|
||||
that is part of the Library, the object code for the work may be a
|
||||
derivative work of the Library even though the source code is not.
|
||||
Whether this is true is especially significant if the work can be
|
||||
linked without the Library, or if the work is itself a library. The
|
||||
threshold for this to be true is not precisely defined by law.
|
||||
|
||||
If such an object file uses only numerical parameters, data
|
||||
structure layouts and accessors, and small macros and small inline
|
||||
functions (ten lines or less in length), then the use of the object
|
||||
file is unrestricted, regardless of whether it is legally a derivative
|
||||
work. (Executables containing this object code plus portions of the
|
||||
Library will still fall under Section 6.)
|
||||
|
||||
Otherwise, if the work is a derivative of the Library, you may
|
||||
distribute the object code for the work under the terms of Section 6.
|
||||
Any executables containing that work also fall under Section 6,
|
||||
whether or not they are linked directly with the Library itself.
|
||||
|
||||
6. As an exception to the Sections above, you may also combine or
|
||||
link a "work that uses the Library" with the Library to produce a
|
||||
work containing portions of the Library, and distribute that work
|
||||
under terms of your choice, provided that the terms permit
|
||||
modification of the work for the customer's own use and reverse
|
||||
engineering for debugging such modifications.
|
||||
|
||||
You must give prominent notice with each copy of the work that the
|
||||
Library is used in it and that the Library and its use are covered by
|
||||
this License. You must supply a copy of this License. If the work
|
||||
during execution displays copyright notices, you must include the
|
||||
copyright notice for the Library among them, as well as a reference
|
||||
directing the user to the copy of this License. Also, you must do one
|
||||
of these things:
|
||||
|
||||
a) Accompany the work with the complete corresponding
|
||||
machine-readable source code for the Library including whatever
|
||||
changes were used in the work (which must be distributed under
|
||||
Sections 1 and 2 above); and, if the work is an executable linked
|
||||
with the Library, with the complete machine-readable "work that
|
||||
uses the Library", as object code and/or source code, so that the
|
||||
user can modify the Library and then relink to produce a modified
|
||||
executable containing the modified Library. (It is understood
|
||||
that the user who changes the contents of definitions files in the
|
||||
Library will not necessarily be able to recompile the application
|
||||
to use the modified definitions.)
|
||||
|
||||
b) Use a suitable shared library mechanism for linking with the
|
||||
Library. A suitable mechanism is one that (1) uses at run time a
|
||||
copy of the library already present on the user's computer system,
|
||||
rather than copying library functions into the executable, and (2)
|
||||
will operate properly with a modified version of the library, if
|
||||
the user installs one, as long as the modified version is
|
||||
interface-compatible with the version that the work was made with.
|
||||
|
||||
c) Accompany the work with a written offer, valid for at
|
||||
least three years, to give the same user the materials
|
||||
specified in Subsection 6a, above, for a charge no more
|
||||
than the cost of performing this distribution.
|
||||
|
||||
d) If distribution of the work is made by offering access to copy
|
||||
from a designated place, offer equivalent access to copy the above
|
||||
specified materials from the same place.
|
||||
|
||||
e) Verify that the user has already received a copy of these
|
||||
materials or that you have already sent this user a copy.
|
||||
|
||||
For an executable, the required form of the "work that uses the
|
||||
Library" must include any data and utility programs needed for
|
||||
reproducing the executable from it. However, as a special exception,
|
||||
the materials to be distributed need not include anything that is
|
||||
normally distributed (in either source or binary form) with the major
|
||||
components (compiler, kernel, and so on) of the operating system on
|
||||
which the executable runs, unless that component itself accompanies
|
||||
the executable.
|
||||
|
||||
It may happen that this requirement contradicts the license
|
||||
restrictions of other proprietary libraries that do not normally
|
||||
accompany the operating system. Such a contradiction means you cannot
|
||||
use both them and the Library together in an executable that you
|
||||
distribute.
|
||||
|
||||
7. You may place library facilities that are a work based on the
|
||||
Library side-by-side in a single library together with other library
|
||||
facilities not covered by this License, and distribute such a combined
|
||||
library, provided that the separate distribution of the work based on
|
||||
the Library and of the other library facilities is otherwise
|
||||
permitted, and provided that you do these two things:
|
||||
|
||||
a) Accompany the combined library with a copy of the same work
|
||||
based on the Library, uncombined with any other library
|
||||
facilities. This must be distributed under the terms of the
|
||||
Sections above.
|
||||
|
||||
b) Give prominent notice with the combined library of the fact
|
||||
that part of it is a work based on the Library, and explaining
|
||||
where to find the accompanying uncombined form of the same work.
|
||||
|
||||
8. You may not copy, modify, sublicense, link with, or distribute
|
||||
the Library except as expressly provided under this License. Any
|
||||
attempt otherwise to copy, modify, sublicense, link with, or
|
||||
distribute the Library is void, and will automatically terminate your
|
||||
rights under this License. However, parties who have received copies,
|
||||
or rights, from you under this License will not have their licenses
|
||||
terminated so long as such parties remain in full compliance.
|
||||
|
||||
9. You are not required to accept this License, since you have not
|
||||
signed it. However, nothing else grants you permission to modify or
|
||||
distribute the Library or its derivative works. These actions are
|
||||
prohibited by law if you do not accept this License. Therefore, by
|
||||
modifying or distributing the Library (or any work based on the
|
||||
Library), you indicate your acceptance of this License to do so, and
|
||||
all its terms and conditions for copying, distributing or modifying
|
||||
the Library or works based on it.
|
||||
|
||||
10. Each time you redistribute the Library (or any work based on the
|
||||
Library), the recipient automatically receives a license from the
|
||||
original licensor to copy, distribute, link with or modify the Library
|
||||
subject to these terms and conditions. You may not impose any further
|
||||
restrictions on the recipients' exercise of the rights granted herein.
|
||||
You are not responsible for enforcing compliance by third parties with
|
||||
this License.
|
||||
|
||||
11. If, as a consequence of a court judgment or allegation of patent
|
||||
infringement or for any other reason (not limited to patent issues),
|
||||
conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot
|
||||
distribute so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you
|
||||
may not distribute the Library at all. For example, if a patent
|
||||
license would not permit royalty-free redistribution of the Library by
|
||||
all those who receive copies directly or indirectly through you, then
|
||||
the only way you could satisfy both it and this License would be to
|
||||
refrain entirely from distribution of the Library.
|
||||
|
||||
If any portion of this section is held invalid or unenforceable under any
|
||||
particular circumstance, the balance of the section is intended to apply,
|
||||
and the section as a whole is intended to apply in other circumstances.
|
||||
|
||||
It is not the purpose of this section to induce you to infringe any
|
||||
patents or other property right claims or to contest validity of any
|
||||
such claims; this section has the sole purpose of protecting the
|
||||
integrity of the free software distribution system which is
|
||||
implemented by public license practices. Many people have made
|
||||
generous contributions to the wide range of software distributed
|
||||
through that system in reliance on consistent application of that
|
||||
system; it is up to the author/donor to decide if he or she is willing
|
||||
to distribute software through any other system and a licensee cannot
|
||||
impose that choice.
|
||||
|
||||
This section is intended to make thoroughly clear what is believed to
|
||||
be a consequence of the rest of this License.
|
||||
|
||||
12. If the distribution and/or use of the Library is restricted in
|
||||
certain countries either by patents or by copyrighted interfaces, the
|
||||
original copyright holder who places the Library under this License may add
|
||||
an explicit geographical distribution limitation excluding those countries,
|
||||
so that distribution is permitted only in or among countries not thus
|
||||
excluded. In such case, this License incorporates the limitation as if
|
||||
written in the body of this License.
|
||||
|
||||
13. The Free Software Foundation may publish revised and/or new
|
||||
versions of the Lesser General Public License from time to time.
|
||||
Such new versions will be similar in spirit to the present version,
|
||||
but may differ in detail to address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the Library
|
||||
specifies a version number of this License which applies to it and
|
||||
"any later version", you have the option of following the terms and
|
||||
conditions either of that version or of any later version published by
|
||||
the Free Software Foundation. If the Library does not specify a
|
||||
license version number, you may choose any version ever published by
|
||||
the Free Software Foundation.
|
||||
|
||||
14. If you wish to incorporate parts of the Library into other free
|
||||
programs whose distribution conditions are incompatible with these,
|
||||
write to the author to ask for permission. For software which is
|
||||
copyrighted by the Free Software Foundation, write to the Free
|
||||
Software Foundation; we sometimes make exceptions for this. Our
|
||||
decision will be guided by the two goals of preserving the free status
|
||||
of all derivatives of our free software and of promoting the sharing
|
||||
and reuse of software generally.
|
||||
|
||||
NO WARRANTY
|
||||
|
||||
15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
|
||||
WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
|
||||
EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
|
||||
OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
|
||||
KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
|
||||
LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
|
||||
THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
|
||||
WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
|
||||
AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
|
||||
FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
|
||||
CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
|
||||
LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
|
||||
RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
|
||||
FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
|
||||
SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
|
||||
DAMAGES.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Libraries
|
||||
|
||||
If you develop a new library, and you want it to be of the greatest
|
||||
possible use to the public, we recommend making it free software that
|
||||
everyone can redistribute and change. You can do so by permitting
|
||||
redistribution under these terms (or, alternatively, under the terms of the
|
||||
ordinary General Public License).
|
||||
|
||||
To apply these terms, attach the following notices to the library. It is
|
||||
safest to attach them to the start of each source file to most effectively
|
||||
convey the exclusion of warranty; and each file should have at least the
|
||||
"copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the library's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
License as published by the Free Software Foundation; either
|
||||
version 2.1 of the License, or (at your option) any later version.
|
||||
|
||||
This library is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public
|
||||
License along with this library; if not, write to the Free Software
|
||||
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
|
||||
USA
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
You should also get your employer (if you work as a programmer) or your
|
||||
school, if any, to sign a "copyright disclaimer" for the library, if
|
||||
necessary. Here is a sample; alter the names:
|
||||
|
||||
Yoyodyne, Inc., hereby disclaims all copyright interest in the
|
||||
library `Frob' (a library for tweaking knobs) written by James Random
|
||||
Hacker.
|
||||
|
||||
<signature of Ty Coon>, 1 April 1990
|
||||
Ty Coon, President of Vice
|
||||
|
||||
That's all there is to it!
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [2025] [YooTrans]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
|
||||
12
NOTICE
Executable file
12
NOTICE
Executable file
@@ -0,0 +1,12 @@
|
||||
This project is licensed under the Apache 2.0 license.
|
||||
However,
|
||||
we need to provide you with some additional notices based on this license!
|
||||
You may distribute copies of this work or its derivative works in any medium,
|
||||
in source or object form, with or without modifications.
|
||||
If you make modifications,
|
||||
you must make your modified source copies publicly available.
|
||||
You may add your own copyright notice to your modified works and may provide additional or
|
||||
different licensing terms and conditions
|
||||
for the use, copying, or distribution of your modified works,
|
||||
or for any such derivative works as a whole,
|
||||
but you must not remove the copyright notice from the original work.
|
||||
54
README.md
Normal file → Executable file
54
README.md
Normal file → Executable file
@@ -1,33 +1,23 @@
|
||||
<p align="center"><a href="https://github.com/OmniX-Space/MeowBox-Core"><img src="README/images/logo.png" height="128px" alt="MeowBox"></a></p>
|
||||
<h3 align="center">Meow~ Music Go !</h3>
|
||||
<p align="center"><a href="https://github.com/OmniX-Space/MeowBox-Core/blob/master/LICENSE"><img src="https://img.shields.io/github/license/OmniX-Space/MeowBox-Core?style=flat-square&label=license&color=blue" alt="LICENSE"></a>
|
||||
<a href="https://github.com/OmniX-Space/MeowBox-Core"><img src="https://img.shields.io/github/stars/OmniX-Space/MeowBox-Core?style=flat-square&label=stars" alt="stars"></a>
|
||||
<a href="https://github.com/OmniX-Space/MeowBox-Core/releases"><img src="https://img.shields.io/github/v/release/OmniX-Space/MeowBox-Core?style=flat-square&label=release" alt="release"></a></p>
|
||||
<p align="center">
|
||||
<a href="README.md"><img src="https://img.shields.io/badge/-English-grey.svg?style=popout" alt="English"></a>
|
||||
<a href="README/README_zh-CN.md"><img src="https://img.shields.io/badge/-中文(简体)-grey.svg?style=popout" alt="中文(简体)"></a></p>
|
||||
|
||||
## What is MeowBox?
|
||||
MeowBox is a music streaming server that allows you to stream your favorite music to any device on the internet. It is built using Go programming language and can be easily deployed on any platform that supports Go.
|
||||
|
||||
### Features
|
||||
- Play music from your server
|
||||
- Music streaming for your embedded devices
|
||||
- Music library management
|
||||
- Music search and cache
|
||||
- User authentication and authorization
|
||||
- Music collection function
|
||||
|
||||
### Supported databases
|
||||
- MySQL
|
||||
- PostgreSQL (coming soon)
|
||||
|
||||
## Star History
|
||||
|
||||
<a href="https://star-history.com/#OmniX-Space/MeowBox-Core&Date">
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=OmniX-Space/MeowBox-Core&type=Date&theme=dark" />
|
||||
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=OmniX-Space/MeowBox-Core&type=Date" />
|
||||
<img alt="Star History Chart" src="https://api.star-history.com/svg?repos=OmniX-Space/MeowBox-Core&type=Date" />
|
||||
</picture>
|
||||
# MeowEmbeddedMusicServer
|
||||
[English](README.md) | [简体中文](README_zh-CN.md)
|
||||
|
||||
Your Embedded Music Server for you.
|
||||
|
||||
## Features
|
||||
- Play music from your server
|
||||
- Music streaming for your embedded devices
|
||||
- Music library management
|
||||
- Music search and cache
|
||||
|
||||
# Tutorial document
|
||||
Docs comming soon.
|
||||
|
||||
## Star History
|
||||
|
||||
<a href="https://star-history.com/#OmniX-Space/MeowBox-Core&Date">
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=OmniX-Space/MeowBox-Core&type=Date&theme=dark" />
|
||||
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=OmniX-Space/MeowBox-Core&type=Date" />
|
||||
<img alt="Star History Chart" src="https://api.star-history.com/svg?repos=OmniX-Space/MeowBox-Core&type=Date" />
|
||||
</picture>
|
||||
</a>
|
||||
71
README_zh-CN.md
Executable file
71
README_zh-CN.md
Executable file
@@ -0,0 +1,71 @@
|
||||
# Meow 为嵌入式设备制作的音乐串流服务 v2.0
|
||||
[English](README.md) | [简体中文](README_zh-CN.md)
|
||||
|
||||
MeowEmbeddedMusicServer 是一个为嵌入式设备制作的音乐串流服务。
|
||||
它可以播放来自你的服务器的音乐,也可以为你的嵌入式设备提供音乐流媒体服务。
|
||||
现在支持完整的用户系统和个人歌单管理!
|
||||
|
||||
## ✨ 新版特性 (v2.0)
|
||||
|
||||
### 🔐 用户系统
|
||||
- ✅ 用户注册和登录
|
||||
- ✅ 安全的密码加密存储
|
||||
- ✅ 基于Token的会话管理
|
||||
|
||||
### 🎵 个人音乐空间
|
||||
- ✅ 每个用户独立的"我喜欢"歌单
|
||||
- ✅ 创建自定义歌单
|
||||
- ✅ 添加/删除歌曲到歌单
|
||||
- ✅ 在线搜索和播放音乐
|
||||
|
||||
### 💎 现代化界面
|
||||
- ✅ React + TailwindCSS 美观UI
|
||||
- ✅ 响应式设计,支持移动设备
|
||||
- ✅ 类似QQ音乐的用户体验
|
||||
|
||||
### 🎯 核心功能
|
||||
- ✅ 在线听音乐
|
||||
- ✅ 为嵌入式设备提供音乐串流服务
|
||||
- ✅ 管理音乐库
|
||||
- ✅ 搜索和缓存音乐
|
||||
- ✅ 个人歌单管理
|
||||
|
||||
## 🚀 快速开始
|
||||
|
||||
### Windows 用户
|
||||
|
||||
1. **确保已安装 Go**(1.19或更高版本)
|
||||
2. **双击启动**:`start.bat`
|
||||
3. **访问应用**:http://localhost:2233/app
|
||||
|
||||
### Linux/macOS 用户
|
||||
|
||||
```bash
|
||||
# 添加执行权限
|
||||
chmod +x start.sh
|
||||
|
||||
# 启动服务器
|
||||
./start.sh
|
||||
```
|
||||
|
||||
然后访问:http://localhost:2233/app
|
||||
|
||||
### 详细文档
|
||||
|
||||
- 📖 **[快速开始](快速开始.md)** - 3分钟快速部署
|
||||
- 📚 **[本地部署指南](本地部署指南.md)** - 详细部署步骤
|
||||
- 🔧 **[用户系统使用指南](USER_SYSTEM_README.md)** - API文档
|
||||
- ✨ **[新功能说明](新功能说明.md)** - 功能概览
|
||||
|
||||
# 教程文档
|
||||
相关文档正在编写中...
|
||||
|
||||
## Star 历史
|
||||
|
||||
<a href="https://star-history.com/#OmniX-Space/MeowBox-Core&Date">
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=OmniX-Space/MeowBox-Core&type=Date&theme=dark" />
|
||||
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=OmniX-Space/MeowBox-Core&type=Date" />
|
||||
<img alt="Star History Chart" src="https://api.star-history.com/svg?repos=OmniX-Space/MeowBox-Core&type=Date" />
|
||||
</picture>
|
||||
</a>
|
||||
262
USER_SYSTEM_README.md
Executable file
262
USER_SYSTEM_README.md
Executable file
@@ -0,0 +1,262 @@
|
||||
# 用户系统使用指南
|
||||
|
||||
## 新功能概述
|
||||
|
||||
已为 Meow Embedded Music Server 添加完整的用户系统,支持:
|
||||
|
||||
### ✨ 核心功能
|
||||
|
||||
1. **用户认证**
|
||||
- 用户注册(用户名 + 邮箱 + 密码)
|
||||
- 用户登录
|
||||
- 会话管理(基于Token)
|
||||
- 安全的密码加密存储
|
||||
|
||||
2. **个人歌单管理**
|
||||
- 每个用户独立的"我喜欢"歌单
|
||||
- 创建自定义歌单
|
||||
- 添加/删除歌曲到歌单
|
||||
- 删除自定义歌单
|
||||
|
||||
3. **音乐搜索和播放**
|
||||
- 在线搜索音乐
|
||||
- 实时播放音乐
|
||||
- 添加到个人歌单
|
||||
- 查看歌单歌曲列表
|
||||
|
||||
## 快速开始
|
||||
|
||||
### 1. 安装依赖
|
||||
|
||||
```bash
|
||||
go mod tidy
|
||||
```
|
||||
|
||||
### 2. 启动服务器
|
||||
|
||||
```bash
|
||||
go run .
|
||||
```
|
||||
|
||||
### 3. 访问应用
|
||||
|
||||
打开浏览器访问:
|
||||
- **新版应用(推荐)**: `http://localhost:2233/app`
|
||||
- **旧版界面(兼容)**: `http://localhost:2233/`
|
||||
|
||||
## API 文档
|
||||
|
||||
### 认证相关
|
||||
|
||||
#### 注册
|
||||
```http
|
||||
POST /api/auth/register
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"username": "testuser",
|
||||
"email": "test@example.com",
|
||||
"password": "password123"
|
||||
}
|
||||
```
|
||||
|
||||
**响应**:
|
||||
```json
|
||||
{
|
||||
"token": "session_token_here",
|
||||
"user": {
|
||||
"id": "user_id",
|
||||
"username": "testuser",
|
||||
"email": "test@example.com",
|
||||
"created_at": "2024-01-01T00:00:00Z",
|
||||
"updated_at": "2024-01-01T00:00:00Z"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### 登录
|
||||
```http
|
||||
POST /api/auth/login
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"username": "testuser",
|
||||
"password": "password123"
|
||||
}
|
||||
```
|
||||
|
||||
#### 登出
|
||||
```http
|
||||
POST /api/auth/logout
|
||||
Authorization: Bearer <token>
|
||||
```
|
||||
|
||||
#### 获取当前用户信息
|
||||
```http
|
||||
GET /api/auth/me
|
||||
Authorization: Bearer <token>
|
||||
```
|
||||
|
||||
### 歌单管理(需要认证)
|
||||
|
||||
#### 获取用户所有歌单
|
||||
```http
|
||||
GET /api/user/playlists
|
||||
Authorization: Bearer <token>
|
||||
```
|
||||
|
||||
#### 创建歌单
|
||||
```http
|
||||
POST /api/user/playlists/create
|
||||
Authorization: Bearer <token>
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"name": "我的歌单",
|
||||
"description": "这是我的歌单描述"
|
||||
}
|
||||
```
|
||||
|
||||
#### 添加歌曲到歌单
|
||||
```http
|
||||
POST /api/user/playlists/add-song?playlist_id=<playlist_id>
|
||||
Authorization: Bearer <token>
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"title": "歌曲名",
|
||||
"artist": "歌手名",
|
||||
"audio_url": "/path/to/audio",
|
||||
"audio_full_url": "/path/to/full/audio",
|
||||
"cover_url": "/path/to/cover",
|
||||
"lyric_url": "/path/to/lyric",
|
||||
"duration": 240
|
||||
}
|
||||
```
|
||||
|
||||
#### 从歌单移除歌曲
|
||||
```http
|
||||
DELETE /api/user/playlists/remove-song?playlist_id=<playlist_id>&title=<song_title>&artist=<artist_name>
|
||||
Authorization: Bearer <token>
|
||||
```
|
||||
|
||||
#### 删除歌单
|
||||
```http
|
||||
DELETE /api/user/playlists/delete?playlist_id=<playlist_id>
|
||||
Authorization: Bearer <token>
|
||||
```
|
||||
|
||||
### 音乐搜索
|
||||
|
||||
```http
|
||||
GET /stream_pcm?song=<歌曲名>&singer=<歌手名>
|
||||
```
|
||||
|
||||
## 数据存储
|
||||
|
||||
用户数据存储在以下文件中:
|
||||
|
||||
- `./files/users.json` - 用户账户信息
|
||||
- `./files/user_playlists.json` - 用户歌单数据
|
||||
- `./files/playlists.json` - 旧版全局歌单(向后兼容)
|
||||
|
||||
## 功能特性
|
||||
|
||||
### 🔒 安全性
|
||||
|
||||
- 密码使用 bcrypt 加密存储
|
||||
- 基于 Token 的会话管理
|
||||
- API 请求认证保护
|
||||
|
||||
### 📱 响应式设计
|
||||
|
||||
- 现代化 UI 界面
|
||||
- 支持桌面和移动设备
|
||||
- 流畅的用户体验
|
||||
|
||||
### 🎵 音乐功能
|
||||
|
||||
- 实时搜索音乐
|
||||
- 在线播放
|
||||
- 个人收藏管理
|
||||
- 自定义歌单
|
||||
|
||||
### 🔄 向后兼容
|
||||
|
||||
- 保留旧版 API 端点
|
||||
- 支持旧版界面访问
|
||||
- 平滑升级路径
|
||||
|
||||
## 使用示例
|
||||
|
||||
### JavaScript 示例
|
||||
|
||||
```javascript
|
||||
// 注册用户
|
||||
const registerResponse = await fetch('/api/auth/register', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
username: 'myuser',
|
||||
email: 'user@example.com',
|
||||
password: 'securepass123'
|
||||
})
|
||||
});
|
||||
const { token, user } = await registerResponse.json();
|
||||
|
||||
// 获取歌单
|
||||
const playlistsResponse = await fetch('/api/user/playlists', {
|
||||
headers: { 'Authorization': `Bearer ${token}` }
|
||||
});
|
||||
const playlists = await playlistsResponse.json();
|
||||
|
||||
// 搜索音乐
|
||||
const musicResponse = await fetch('/stream_pcm?song=告白气球&singer=周杰伦');
|
||||
const song = await musicResponse.json();
|
||||
|
||||
// 添加到歌单
|
||||
await fetch(`/api/user/playlists/add-song?playlist_id=${playlists[0].id}`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Authorization': `Bearer ${token}`,
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify(song)
|
||||
});
|
||||
```
|
||||
|
||||
## 故障排除
|
||||
|
||||
### 问题:无法登录
|
||||
- 检查用户名和密码是否正确
|
||||
- 确认用户已注册
|
||||
- 检查服务器日志
|
||||
|
||||
### 问题:Token 过期
|
||||
- 重新登录获取新 Token
|
||||
- Token 存储在 localStorage 中,清除浏览器缓存后需要重新登录
|
||||
|
||||
### 问题:添加歌曲失败
|
||||
- 确认已登录并有有效 Token
|
||||
- 检查歌单 ID 是否正确
|
||||
- 确认歌曲信息完整
|
||||
|
||||
## 开发者信息
|
||||
|
||||
- 后端框架:Go (Golang)
|
||||
- 前端框架:React 18 + TailwindCSS
|
||||
- 认证方式:Token-based
|
||||
- 数据存储:JSON 文件
|
||||
|
||||
## 更新日志
|
||||
|
||||
### v2.0.0 (当前版本)
|
||||
- ✅ 添加用户注册和登录功能
|
||||
- ✅ 实现个人歌单管理
|
||||
- ✅ 创建现代化 Web 界面
|
||||
- ✅ 支持在线音乐搜索和播放
|
||||
- ✅ 向后兼容旧版 API
|
||||
|
||||
---
|
||||
|
||||
**享受您的音乐之旅! 🎵**
|
||||
325
WEB_DEVICE_BIND_GUIDE.md
Executable file
325
WEB_DEVICE_BIND_GUIDE.md
Executable file
@@ -0,0 +1,325 @@
|
||||
# Web端设备绑定指南
|
||||
|
||||
## 🎉 **简化的绑定流程**
|
||||
|
||||
不需要语音绑定码!直接在Web界面输入MAC地址即可。
|
||||
|
||||
---
|
||||
|
||||
## 🚀 **快速开始**
|
||||
|
||||
### **步骤1:启动服务器**
|
||||
|
||||
```powershell
|
||||
cd d:\esp32-music-server\Meow\MeowEmbeddedMusicServer
|
||||
go run .
|
||||
```
|
||||
|
||||
### **步骤2:登录Web界面**
|
||||
|
||||
访问:`http://localhost:2233`
|
||||
|
||||
登录账号:
|
||||
- 用户名:`test`
|
||||
- 密码:`123456`
|
||||
|
||||
### **步骤3:打开设备绑定页面**
|
||||
|
||||
访问:`http://localhost:2233/device-bind`
|
||||
|
||||
或者在登录后,点击导航菜单中的"设备管理"。
|
||||
|
||||
### **步骤4:查看ESP32的MAC地址**
|
||||
|
||||
ESP32启动时会在串口日志中显示MAC地址:
|
||||
|
||||
```
|
||||
I (1024) wifi:mode : sta (80:b5:4e:d4:fa:80)
|
||||
↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑
|
||||
这就是MAC地址!
|
||||
```
|
||||
|
||||
在您的日志中找到这一行:
|
||||
```
|
||||
I (1024) wifi:mode : sta (80:b5:4e:d4:fa:80)
|
||||
```
|
||||
|
||||
MAC地址是:`80:b5:4e:d4:fa:80`
|
||||
|
||||
### **步骤5:在Web界面输入MAC地址**
|
||||
|
||||
1. 在"MAC地址"输入框中输入:`80:b5:4e:d4:fa:80`
|
||||
2. (可选)在"设备名称"输入框中输入设备名称,例如:`客厅音响`
|
||||
3. 点击"绑定设备"按钮
|
||||
|
||||
### **步骤6:完成!**
|
||||
|
||||
绑定成功后,页面会显示:
|
||||
```
|
||||
✅ 设备绑定成功!
|
||||
```
|
||||
|
||||
已绑定设备列表会自动刷新,显示您的设备。
|
||||
|
||||
---
|
||||
|
||||
## 📱 **设备管理功能**
|
||||
|
||||
### **查看已绑定设备**
|
||||
|
||||
在设备绑定页面下方,会显示所有已绑定的设备:
|
||||
|
||||
```
|
||||
┌──────────────────────────────────────┐
|
||||
│ 客厅音响 │
|
||||
│ MAC: 80:b5:4e:d4:fa:80 │
|
||||
│ 🟢 在线 [解绑] │
|
||||
└──────────────────────────────────────┘
|
||||
```
|
||||
|
||||
### **解绑设备**
|
||||
|
||||
点击设备卡片右侧的"解绑"按钮,确认后即可解绑。
|
||||
|
||||
### **刷新设备列表**
|
||||
|
||||
点击"刷新设备列表"按钮,更新设备状态。
|
||||
|
||||
---
|
||||
|
||||
## 🆚 **新旧方案对比**
|
||||
|
||||
### **旧方案(语音绑定码)**
|
||||
|
||||
```
|
||||
1. Web端生成绑定码 → 123456
|
||||
2. 对ESP32说:"小智,绑定设备,绑定码123456"
|
||||
3. ESP32识别语音 → 调用MCP工具 → 发送请求
|
||||
4. 完成绑定
|
||||
```
|
||||
|
||||
**缺点**:
|
||||
- ❌ 语音识别可能出错
|
||||
- ❌ 绑定码需要记忆5分钟
|
||||
- ❌ 流程复杂,容易失败
|
||||
|
||||
### **新方案(Web直接绑定)**
|
||||
|
||||
```
|
||||
1. 查看ESP32串口日志 → 复制MAC地址
|
||||
2. 在Web界面粘贴MAC地址
|
||||
3. 点击绑定按钮
|
||||
4. 完成!
|
||||
```
|
||||
|
||||
**优点**:
|
||||
- ✅ 一次复制粘贴搞定
|
||||
- ✅ 不需要语音识别
|
||||
- ✅ 操作简单明了
|
||||
- ✅ 立即生效,无需等待
|
||||
|
||||
---
|
||||
|
||||
## 📋 **API文档**
|
||||
|
||||
### **1. 直接绑定设备**
|
||||
|
||||
```
|
||||
POST /api/device/bind-direct
|
||||
Authorization: 需要登录
|
||||
Content-Type: application/json
|
||||
```
|
||||
|
||||
**请求体**:
|
||||
```json
|
||||
{
|
||||
"mac": "80:b5:4e:d4:fa:80",
|
||||
"device_name": "客厅音响"
|
||||
}
|
||||
```
|
||||
|
||||
**响应**:
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"message": "设备绑定成功",
|
||||
"device": {
|
||||
"mac": "80:b5:4e:d4:fa:80",
|
||||
"device_name": "客厅音响",
|
||||
"bind_time": "2025-11-24T17:00:00Z"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### **2. 列出用户设备**
|
||||
|
||||
```
|
||||
GET /api/device/list
|
||||
Authorization: 需要登录
|
||||
```
|
||||
|
||||
**响应**:
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"devices": [
|
||||
{
|
||||
"mac": "80:b5:4e:d4:fa:80",
|
||||
"username": "test",
|
||||
"device_name": "客厅音响",
|
||||
"token": "a1b2c3...",
|
||||
"bind_time": "2025-11-24T17:00:00Z",
|
||||
"last_seen": "2025-11-24T17:30:00Z",
|
||||
"is_active": true
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### **3. 解绑设备**
|
||||
|
||||
```
|
||||
POST /api/device/unbind
|
||||
Authorization: 需要登录
|
||||
Content-Type: application/json
|
||||
```
|
||||
|
||||
**请求体**:
|
||||
```json
|
||||
{
|
||||
"mac": "80:b5:4e:d4:fa:80"
|
||||
}
|
||||
```
|
||||
|
||||
**响应**:
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"message": "设备已解绑"
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🔍 **如何查看ESP32的MAC地址**
|
||||
|
||||
### **方法1:串口监视器(推荐)**
|
||||
|
||||
使用ESP-IDF监视器:
|
||||
```bash
|
||||
idf.py monitor
|
||||
```
|
||||
|
||||
或者任何串口工具(PuTTY、Arduino Serial Monitor等),波特率115200。
|
||||
|
||||
启动日志中会显示:
|
||||
```
|
||||
I (1024) wifi:mode : sta (80:b5:4e:d4:fa:80)
|
||||
```
|
||||
|
||||
### **方法2:Web API查询**
|
||||
|
||||
如果ESP32已连接到网络,可以通过API查询(需要先知道IP):
|
||||
```
|
||||
http://ESP32的IP地址/api/system/info
|
||||
```
|
||||
|
||||
### **方法3:标签贴纸**
|
||||
|
||||
在ESP32开发板上贴一个标签,写上MAC地址,方便以后查找。
|
||||
|
||||
---
|
||||
|
||||
## 💡 **常见问题**
|
||||
|
||||
### **Q1:MAC地址格式错误**
|
||||
|
||||
**A**:MAC地址应该是6组2位十六进制数,用冒号分隔,例如:
|
||||
- ✅ 正确:`80:b5:4e:d4:fa:80`
|
||||
- ✅ 正确:`80:B5:4E:D4:FA:80` (大小写都可以)
|
||||
- ❌ 错误:`80b54ed4fa80` (缺少冒号)
|
||||
- ❌ 错误:`80-b5-4e-d4-fa-80` (使用了连字符)
|
||||
|
||||
Web界面会自动格式化MAC地址。
|
||||
|
||||
### **Q2:提示"设备已绑定"**
|
||||
|
||||
**A**:这个MAC地址已经绑定到某个账号了。
|
||||
|
||||
解决方法:
|
||||
1. 登录原账号,解绑设备
|
||||
2. 或者在设备管理页面删除旧绑定
|
||||
3. 然后重新绑定
|
||||
|
||||
### **Q3:未登录提示**
|
||||
|
||||
**A**:请先登录系统,然后访问设备绑定页面。
|
||||
|
||||
### **Q4:设备显示离线**
|
||||
|
||||
**A**:
|
||||
- 检查ESP32是否开机
|
||||
- 检查WiFi连接
|
||||
- 查看ESP32串口日志是否有错误
|
||||
|
||||
---
|
||||
|
||||
## 🎨 **页面截图说明**
|
||||
|
||||
### **绑定页面**
|
||||
|
||||
```
|
||||
┌────────────────────────────────────────────┐
|
||||
│ 🎵 设备绑定 │
|
||||
│ 将您的ESP32音乐播放器绑定到账号 │
|
||||
├────────────────────────────────────────────┤
|
||||
│ │
|
||||
│ MAC地址 * │
|
||||
│ ┌──────────────────────────────────────┐ │
|
||||
│ │ 例如: AA:BB:CC:DD:EE:FF │ │
|
||||
│ └──────────────────────────────────────┘ │
|
||||
│ 💡 在ESP32串口日志中查找 │
|
||||
│ │
|
||||
│ 设备名称(可选) │
|
||||
│ ┌──────────────────────────────────────┐ │
|
||||
│ │ 例如: 客厅音响 │ │
|
||||
│ └──────────────────────────────────────┘ │
|
||||
│ 给设备起个名字,方便识别 │
|
||||
│ │
|
||||
│ ┌──────────────────────────────────────┐ │
|
||||
│ │ 绑定设备 │ │
|
||||
│ └──────────────────────────────────────┘ │
|
||||
│ │
|
||||
│ ┌──────────────────────────────────────┐ │
|
||||
│ │ 刷新设备列表 │ │
|
||||
│ └──────────────────────────────────────┘ │
|
||||
│ │
|
||||
├────────────────────────────────────────────┤
|
||||
│ 已绑定设备 │
|
||||
│ │
|
||||
│ ┌──────────────────────────────────────┐ │
|
||||
│ │ 客厅音响 │ │
|
||||
│ │ MAC: 80:b5:4e:d4:fa:80 │ │
|
||||
│ │ 🟢 在线 [解绑] │ │
|
||||
│ └──────────────────────────────────────┘ │
|
||||
│ │
|
||||
│ ← 返回首页 │
|
||||
└────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## ✅ **总结**
|
||||
|
||||
**新的Web绑定方式让设备管理变得超级简单!**
|
||||
|
||||
1. 📋 复制ESP32的MAC地址
|
||||
2. 🖱️ 在Web界面粘贴
|
||||
3. ✅ 点击绑定
|
||||
4. 🎉 完成!
|
||||
|
||||
不需要语音,不需要绑定码,一次复制粘贴搞定!
|
||||
|
||||
---
|
||||
|
||||
**喵波音律QQ交流群:865754861** 🎵
|
||||
239
api.go
Executable file
239
api.go
Executable file
@@ -0,0 +1,239 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// APIHandler handles API requests.
|
||||
func apiHandler(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Server", "MeowMusicEmbeddedServer")
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
|
||||
queryParams := r.URL.Query()
|
||||
fmt.Printf("[Web Access] Handling request for %s?%s\n", r.URL.Path, queryParams.Encode())
|
||||
song := queryParams.Get("song")
|
||||
singer := queryParams.Get("singer")
|
||||
|
||||
ip, err := IPhandler(r)
|
||||
if err != nil {
|
||||
ip = "0.0.0.0"
|
||||
}
|
||||
|
||||
if song == "" {
|
||||
musicItem := MusicItem{
|
||||
FromCache: false,
|
||||
IP: ip,
|
||||
}
|
||||
json.NewEncoder(w).Encode(musicItem)
|
||||
return
|
||||
}
|
||||
|
||||
// Attempt to retrieve music items from sources.json
|
||||
sources := readSources()
|
||||
|
||||
var musicItem MusicItem
|
||||
var found bool = false
|
||||
|
||||
// Build request scheme
|
||||
var scheme string
|
||||
if r.TLS == nil {
|
||||
scheme = "http"
|
||||
} else {
|
||||
scheme = "https"
|
||||
}
|
||||
|
||||
for _, source := range sources {
|
||||
if source.Title == song {
|
||||
if singer == "" || source.Artist == singer {
|
||||
// Determine the protocol for each URL and build accordingly
|
||||
var audioURL, audioFullURL, m3u8URL, lyricURL, coverURL string
|
||||
if strings.HasPrefix(source.AudioURL, "http://") {
|
||||
audioURL = scheme + "://" + r.Host + "/url/http/" + url.QueryEscape(strings.TrimPrefix(source.AudioURL, "http://"))
|
||||
} else if strings.HasPrefix(source.AudioURL, "https://") {
|
||||
audioURL = scheme + "://" + r.Host + "/url/https/" + url.QueryEscape(strings.TrimPrefix(source.AudioURL, "https://"))
|
||||
} else {
|
||||
audioURL = scheme + "://" + r.Host + "/" + url.QueryEscape(source.AudioURL)
|
||||
}
|
||||
if strings.HasPrefix(source.AudioFullURL, "http://") {
|
||||
audioFullURL = scheme + "://" + r.Host + "/url/http/" + url.QueryEscape(strings.TrimPrefix(source.AudioFullURL, "http://"))
|
||||
} else if strings.HasPrefix(source.AudioFullURL, "https://") {
|
||||
audioFullURL = scheme + "://" + r.Host + "/url/https/" + url.QueryEscape(strings.TrimPrefix(source.AudioFullURL, "https://"))
|
||||
} else {
|
||||
audioFullURL = scheme + "://" + r.Host + "/" + url.QueryEscape(source.AudioFullURL)
|
||||
}
|
||||
if strings.HasPrefix(source.M3U8URL, "http://") {
|
||||
m3u8URL = scheme + "://" + r.Host + "/url/http/" + url.QueryEscape(strings.TrimPrefix(source.M3U8URL, "http://"))
|
||||
} else if strings.HasPrefix(source.M3U8URL, "https://") {
|
||||
m3u8URL = scheme + "://" + r.Host + "/url/https/" + url.QueryEscape(strings.TrimPrefix(source.M3U8URL, "https://"))
|
||||
} else {
|
||||
m3u8URL = scheme + "://" + r.Host + "/" + url.QueryEscape(source.M3U8URL)
|
||||
}
|
||||
if strings.HasPrefix(source.LyricURL, "http://") {
|
||||
lyricURL = scheme + "://" + r.Host + "/url/http/" + url.QueryEscape(strings.TrimPrefix(source.LyricURL, "http://"))
|
||||
} else if strings.HasPrefix(source.LyricURL, "https://") {
|
||||
lyricURL = scheme + "://" + r.Host + "/url/https/" + url.QueryEscape(strings.TrimPrefix(source.LyricURL, "https://"))
|
||||
} else {
|
||||
lyricURL = scheme + "://" + r.Host + "/" + url.QueryEscape(source.LyricURL)
|
||||
}
|
||||
if strings.HasPrefix(source.CoverURL, "http://") {
|
||||
coverURL = scheme + "://" + r.Host + "/url/http/" + url.QueryEscape(strings.TrimPrefix(source.CoverURL, "http://"))
|
||||
} else if strings.HasPrefix(source.CoverURL, "https://") {
|
||||
coverURL = scheme + "://" + r.Host + "/url/https/" + url.QueryEscape(strings.TrimPrefix(source.CoverURL, "https://"))
|
||||
} else {
|
||||
coverURL = scheme + "://" + r.Host + "/" + url.QueryEscape(source.CoverURL)
|
||||
}
|
||||
musicItem = MusicItem{
|
||||
Title: source.Title,
|
||||
Artist: source.Artist,
|
||||
AudioURL: audioURL,
|
||||
AudioFullURL: audioFullURL,
|
||||
M3U8URL: m3u8URL,
|
||||
LyricURL: lyricURL,
|
||||
CoverURL: coverURL,
|
||||
Duration: source.Duration,
|
||||
FromCache: false,
|
||||
}
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// If not found in sources.json, attempt to retrieve from local folder
|
||||
if !found {
|
||||
musicItem = getLocalMusicItem(song, singer)
|
||||
musicItem.FromCache = false
|
||||
if musicItem.Title != "" {
|
||||
if musicItem.AudioURL != "" {
|
||||
musicItem.AudioURL = scheme + "://" + r.Host + musicItem.AudioURL
|
||||
}
|
||||
if musicItem.AudioFullURL != "" {
|
||||
musicItem.AudioFullURL = scheme + "://" + r.Host + musicItem.AudioFullURL
|
||||
}
|
||||
if musicItem.M3U8URL != "" {
|
||||
musicItem.M3U8URL = scheme + "://" + r.Host + musicItem.M3U8URL
|
||||
}
|
||||
if musicItem.LyricURL != "" {
|
||||
musicItem.LyricURL = scheme + "://" + r.Host + musicItem.LyricURL
|
||||
}
|
||||
if musicItem.CoverURL != "" {
|
||||
musicItem.CoverURL = scheme + "://" + r.Host + musicItem.CoverURL
|
||||
}
|
||||
found = true
|
||||
}
|
||||
}
|
||||
|
||||
// If still not found, attempt to retrieve from cache file
|
||||
if !found {
|
||||
fmt.Println("[Info] Reading music from cache.")
|
||||
// Fuzzy matching for singer and song
|
||||
files, err := filepath.Glob("./cache/*.json")
|
||||
if err != nil {
|
||||
fmt.Println("[Error] Error reading cache directory:", err)
|
||||
return
|
||||
}
|
||||
for _, file := range files {
|
||||
if strings.Contains(filepath.Base(file), song) && (singer == "" || strings.Contains(filepath.Base(file), singer)) {
|
||||
musicItem, found = readFromCache(file)
|
||||
if found {
|
||||
if musicItem.AudioURL != "" {
|
||||
musicItem.AudioURL = scheme + "://" + r.Host + musicItem.AudioURL
|
||||
}
|
||||
if musicItem.AudioFullURL != "" {
|
||||
musicItem.AudioFullURL = scheme + "://" + r.Host + musicItem.AudioFullURL
|
||||
}
|
||||
if musicItem.M3U8URL != "" {
|
||||
musicItem.M3U8URL = scheme + "://" + r.Host + musicItem.M3U8URL
|
||||
}
|
||||
if musicItem.LyricURL != "" {
|
||||
musicItem.LyricURL = scheme + "://" + r.Host + musicItem.LyricURL
|
||||
}
|
||||
if musicItem.CoverURL != "" {
|
||||
musicItem.CoverURL = scheme + "://" + r.Host + musicItem.CoverURL
|
||||
}
|
||||
musicItem.FromCache = true
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// If still not found, request and cache the music item in a separate goroutine
|
||||
if !found {
|
||||
fmt.Println("[Info] Updating music item cache from API request.")
|
||||
musicItem = requestAndCacheMusic(song, singer)
|
||||
fmt.Println("[Info] Music item cache updated.")
|
||||
musicItem.FromCache = false
|
||||
musicItem.AudioURL = scheme + "://" + r.Host + musicItem.AudioURL
|
||||
musicItem.AudioFullURL = scheme + "://" + r.Host + musicItem.AudioFullURL
|
||||
musicItem.M3U8URL = scheme + "://" + r.Host + musicItem.M3U8URL
|
||||
musicItem.LyricURL = scheme + "://" + r.Host + musicItem.LyricURL
|
||||
musicItem.CoverURL = scheme + "://" + r.Host + musicItem.CoverURL
|
||||
found = true
|
||||
}
|
||||
|
||||
// If still not found, return an empty MusicItem
|
||||
if !found {
|
||||
musicItem = MusicItem{
|
||||
FromCache: false,
|
||||
IP: ip,
|
||||
}
|
||||
} else {
|
||||
musicItem.IP = ip
|
||||
}
|
||||
|
||||
json.NewEncoder(w).Encode(musicItem)
|
||||
}
|
||||
|
||||
// streamLiveHandler 实时流式转码接口 - 边下载边播放,无需等待!
|
||||
func streamLiveHandler(w http.ResponseWriter, r *http.Request) {
|
||||
// 设置 CORS 和音频相关头
|
||||
w.Header().Set("Access-Control-Allow-Origin", "*")
|
||||
w.Header().Set("Accept-Ranges", "bytes")
|
||||
|
||||
queryParams := r.URL.Query()
|
||||
song := queryParams.Get("song")
|
||||
singer := queryParams.Get("singer")
|
||||
|
||||
fmt.Printf("[Stream Live] Request: song=%s, singer=%s\n", song, singer)
|
||||
|
||||
if song == "" {
|
||||
http.Error(w, "Missing song parameter", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
// 1. 检查缓存是否存在
|
||||
dirName := fmt.Sprintf("./files/cache/music/%s-%s", singer, song)
|
||||
cachedFile := filepath.Join(dirName, "music.mp3")
|
||||
if _, err := os.Stat(cachedFile); err == nil {
|
||||
// 缓存存在,直接返回文件
|
||||
fmt.Printf("[Stream Live] Serving from cache: %s\n", cachedFile)
|
||||
w.Header().Set("Content-Type", "audio/mpeg")
|
||||
http.ServeFile(w, r, cachedFile)
|
||||
return
|
||||
}
|
||||
|
||||
// 2. 缓存不存在,获取远程URL并实时流式转码
|
||||
fmt.Printf("[Stream Live] Cache miss, fetching from API...\n")
|
||||
|
||||
// 调用枫雨API获取远程音乐URL(不下载,只获取URL)
|
||||
remoteURL := getRemoteMusicURLOnly(song, singer)
|
||||
if remoteURL == "" {
|
||||
http.Error(w, "Failed to get remote music URL", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
fmt.Printf("[Stream Live] Starting live stream from: %s\n", remoteURL)
|
||||
|
||||
// 4. 实时流式转码
|
||||
if err := streamConvertToWriter(remoteURL, w); err != nil {
|
||||
fmt.Printf("[Stream Live] Error: %v\n", err)
|
||||
// 错误可能已经发送了部分数据,无法再发送错误响应
|
||||
}
|
||||
}
|
||||
0
cache/.gitignore
vendored
Normal file
0
cache/.gitignore
vendored
Normal file
740
device.go
Executable file
740
device.go
Executable file
@@ -0,0 +1,740 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"math/big"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Device 设备信息结构
|
||||
type Device struct {
|
||||
MAC string `json:"mac"`
|
||||
Username string `json:"username"`
|
||||
DeviceName string `json:"device_name"`
|
||||
Token string `json:"token"`
|
||||
BindTime time.Time `json:"bind_time"`
|
||||
LastSeen time.Time `json:"last_seen"`
|
||||
IsActive bool `json:"is_active"`
|
||||
}
|
||||
|
||||
// BindingCode 绑定码结构
|
||||
type BindingCode struct {
|
||||
Code string `json:"code"`
|
||||
Username string `json:"username"`
|
||||
ExpiresAt time.Time `json:"expires_at"`
|
||||
Used bool `json:"used"`
|
||||
}
|
||||
|
||||
// DeviceManager 设备管理器
|
||||
type DeviceManager struct {
|
||||
devices map[string]*Device // MAC -> Device
|
||||
bindingCodes map[string]*BindingCode // Code -> BindingCode
|
||||
tokens map[string]string // Token -> MAC
|
||||
mu sync.RWMutex
|
||||
filePath string
|
||||
}
|
||||
|
||||
var deviceManager *DeviceManager
|
||||
var deviceManagerOnce sync.Once
|
||||
|
||||
// GetDeviceManager 获取设备管理器单例
|
||||
func GetDeviceManager() *DeviceManager {
|
||||
deviceManagerOnce.Do(func() {
|
||||
deviceManager = &DeviceManager{
|
||||
devices: make(map[string]*Device),
|
||||
bindingCodes: make(map[string]*BindingCode),
|
||||
tokens: make(map[string]string),
|
||||
filePath: "./devices.json",
|
||||
}
|
||||
deviceManager.LoadFromFile()
|
||||
})
|
||||
return deviceManager
|
||||
}
|
||||
|
||||
// GenerateBindingCode 生成6位数字绑定码
|
||||
func (dm *DeviceManager) GenerateBindingCode(username string) (string, error) {
|
||||
dm.mu.Lock()
|
||||
defer dm.mu.Unlock()
|
||||
|
||||
// 生成6位随机数字
|
||||
var code string
|
||||
for i := 0; i < 6; i++ {
|
||||
n, err := rand.Int(rand.Reader, big.NewInt(10))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
code += fmt.Sprintf("%d", n.Int64())
|
||||
}
|
||||
|
||||
// 检查是否已存在(小概率)
|
||||
if _, exists := dm.bindingCodes[code]; exists {
|
||||
// 递归重新生成
|
||||
return dm.GenerateBindingCode(username)
|
||||
}
|
||||
|
||||
// 创建绑定码,5分钟有效
|
||||
bindingCode := &BindingCode{
|
||||
Code: code,
|
||||
Username: username,
|
||||
ExpiresAt: time.Now().Add(5 * time.Minute),
|
||||
Used: false,
|
||||
}
|
||||
|
||||
dm.bindingCodes[code] = bindingCode
|
||||
fmt.Printf("[Device] Generated binding code %s for user %s\n", code, username)
|
||||
|
||||
return code, nil
|
||||
}
|
||||
|
||||
// generateDeviceToken 生成设备Token
|
||||
func generateDeviceToken() string {
|
||||
b := make([]byte, 32)
|
||||
rand.Read(b)
|
||||
return fmt.Sprintf("%x", b)
|
||||
}
|
||||
|
||||
// BindDevice 绑定设备
|
||||
func (dm *DeviceManager) BindDevice(mac, bindingCode, deviceName string) (*Device, error) {
|
||||
dm.mu.Lock()
|
||||
defer dm.mu.Unlock()
|
||||
|
||||
// 验证绑定码
|
||||
code, exists := dm.bindingCodes[bindingCode]
|
||||
if !exists {
|
||||
return nil, fmt.Errorf("绑定码不存在")
|
||||
}
|
||||
|
||||
if code.Used {
|
||||
return nil, fmt.Errorf("绑定码已使用")
|
||||
}
|
||||
|
||||
if time.Now().After(code.ExpiresAt) {
|
||||
return nil, fmt.Errorf("绑定码已过期")
|
||||
}
|
||||
|
||||
// 检查设备是否已绑定
|
||||
if existingDevice, exists := dm.devices[mac]; exists {
|
||||
return nil, fmt.Errorf("设备已绑定到用户 %s", existingDevice.Username)
|
||||
}
|
||||
|
||||
// 生成Token
|
||||
token := generateDeviceToken()
|
||||
|
||||
// 创建设备
|
||||
device := &Device{
|
||||
MAC: mac,
|
||||
Username: code.Username,
|
||||
DeviceName: deviceName,
|
||||
Token: token,
|
||||
BindTime: time.Now(),
|
||||
LastSeen: time.Now(),
|
||||
IsActive: true,
|
||||
}
|
||||
|
||||
// 保存设备信息
|
||||
dm.devices[mac] = device
|
||||
dm.tokens[token] = mac
|
||||
|
||||
// 标记绑定码已使用
|
||||
code.Used = true
|
||||
|
||||
// 保存到文件
|
||||
dm.SaveToFile()
|
||||
|
||||
fmt.Printf("[Device] Device %s bound to user %s\n", mac, code.Username)
|
||||
|
||||
return device, nil
|
||||
}
|
||||
|
||||
// VerifyToken 验证设备Token
|
||||
func (dm *DeviceManager) VerifyToken(token string) (*Device, error) {
|
||||
dm.mu.RLock()
|
||||
defer dm.mu.RUnlock()
|
||||
|
||||
mac, exists := dm.tokens[token]
|
||||
if !exists {
|
||||
return nil, fmt.Errorf("无效的Token")
|
||||
}
|
||||
|
||||
device, exists := dm.devices[mac]
|
||||
if !exists {
|
||||
return nil, fmt.Errorf("设备不存在")
|
||||
}
|
||||
|
||||
if !device.IsActive {
|
||||
return nil, fmt.Errorf("设备已停用")
|
||||
}
|
||||
|
||||
return device, nil
|
||||
}
|
||||
|
||||
// GetDeviceByMAC 根据MAC地址获取设备
|
||||
func (dm *DeviceManager) GetDeviceByMAC(mac string) (*Device, error) {
|
||||
dm.mu.RLock()
|
||||
defer dm.mu.RUnlock()
|
||||
|
||||
device, exists := dm.devices[mac]
|
||||
if !exists {
|
||||
return nil, fmt.Errorf("设备未绑定")
|
||||
}
|
||||
|
||||
return device, nil
|
||||
}
|
||||
|
||||
// UpdateLastSeen 更新设备最后在线时间
|
||||
func (dm *DeviceManager) UpdateLastSeen(mac string) {
|
||||
dm.mu.Lock()
|
||||
defer dm.mu.Unlock()
|
||||
|
||||
if device, exists := dm.devices[mac]; exists {
|
||||
device.LastSeen = time.Now()
|
||||
dm.SaveToFile()
|
||||
}
|
||||
}
|
||||
|
||||
// DirectBindDevice 直接绑定设备(不需要绑定码)
|
||||
func (dm *DeviceManager) DirectBindDevice(mac, username, deviceName string) (*Device, error) {
|
||||
dm.mu.Lock()
|
||||
defer dm.mu.Unlock()
|
||||
|
||||
// 检查设备是否已绑定
|
||||
if existingDevice, exists := dm.devices[mac]; exists {
|
||||
return nil, fmt.Errorf("设备已绑定到用户 %s", existingDevice.Username)
|
||||
}
|
||||
|
||||
// 生成Token
|
||||
token := generateDeviceToken()
|
||||
|
||||
// 创建设备
|
||||
device := &Device{
|
||||
MAC: mac,
|
||||
Username: username,
|
||||
DeviceName: deviceName,
|
||||
Token: token,
|
||||
BindTime: time.Now(),
|
||||
LastSeen: time.Now(),
|
||||
IsActive: true,
|
||||
}
|
||||
|
||||
dm.devices[mac] = device
|
||||
dm.tokens[token] = mac
|
||||
|
||||
dm.SaveToFile()
|
||||
|
||||
fmt.Printf("[Device] Device %s directly bound to user %s\n", mac, username)
|
||||
return device, nil
|
||||
}
|
||||
|
||||
// UnbindDevice 解绑设备
|
||||
func (dm *DeviceManager) UnbindDevice(mac string) error {
|
||||
dm.mu.Lock()
|
||||
defer dm.mu.Unlock()
|
||||
|
||||
device, exists := dm.devices[mac]
|
||||
if !exists {
|
||||
return fmt.Errorf("设备不存在")
|
||||
}
|
||||
|
||||
// 删除Token映射
|
||||
delete(dm.tokens, device.Token)
|
||||
// 删除设备
|
||||
delete(dm.devices, mac)
|
||||
|
||||
dm.SaveToFile()
|
||||
|
||||
fmt.Printf("[Device] Device %s unbound\n", mac)
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetDevice 获取单个设备信息
|
||||
func (dm *DeviceManager) GetDevice(mac string) (*Device, error) {
|
||||
dm.mu.RLock()
|
||||
defer dm.mu.RUnlock()
|
||||
|
||||
device, exists := dm.devices[mac]
|
||||
if !exists {
|
||||
return nil, fmt.Errorf("设备不存在")
|
||||
}
|
||||
|
||||
return device, nil
|
||||
}
|
||||
|
||||
// GetUserDevices 获取用户的所有设备
|
||||
func (dm *DeviceManager) GetUserDevices(username string) []*Device {
|
||||
dm.mu.RLock()
|
||||
defer dm.mu.RUnlock()
|
||||
|
||||
var devices []*Device
|
||||
for _, device := range dm.devices {
|
||||
if device.Username == username {
|
||||
devices = append(devices, device)
|
||||
}
|
||||
}
|
||||
|
||||
return devices
|
||||
}
|
||||
|
||||
// SaveToFile 保存设备信息到文件
|
||||
func (dm *DeviceManager) SaveToFile() error {
|
||||
data := struct {
|
||||
Devices map[string]*Device `json:"devices"`
|
||||
}{
|
||||
Devices: dm.devices,
|
||||
}
|
||||
|
||||
jsonData, err := json.MarshalIndent(data, "", " ")
|
||||
if err != nil {
|
||||
fmt.Println("[Error] Failed to marshal devices:", err)
|
||||
return err
|
||||
}
|
||||
|
||||
err = os.WriteFile(dm.filePath, jsonData, 0644)
|
||||
if err != nil {
|
||||
fmt.Println("[Error] Failed to write devices.json:", err)
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// LoadFromFile 从文件加载设备信息
|
||||
func (dm *DeviceManager) LoadFromFile() error {
|
||||
file, err := os.Open(dm.filePath)
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
fmt.Println("[Info] devices.json not found, creating new file")
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
data, err := io.ReadAll(file)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var fileData struct {
|
||||
Devices map[string]*Device `json:"devices"`
|
||||
}
|
||||
|
||||
err = json.Unmarshal(data, &fileData)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
dm.devices = fileData.Devices
|
||||
if dm.devices == nil {
|
||||
dm.devices = make(map[string]*Device)
|
||||
}
|
||||
|
||||
// 重建Token索引
|
||||
for mac, device := range dm.devices {
|
||||
dm.tokens[device.Token] = mac
|
||||
}
|
||||
|
||||
fmt.Printf("[Info] Loaded %d devices from file\n", len(dm.devices))
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// HTTP处理器
|
||||
|
||||
// GenerateBindingCodeHandler 生成绑定码
|
||||
func GenerateBindingCodeHandler(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
// 获取当前登录用户
|
||||
username := GetCurrentUser(r) // 需要从session获取
|
||||
if username == "" {
|
||||
http.Error(w, "Unauthorized", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
dm := GetDeviceManager()
|
||||
code, err := dm.GenerateBindingCode(username)
|
||||
if err != nil {
|
||||
http.Error(w, "Failed to generate binding code", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(map[string]interface{}{
|
||||
"success": true,
|
||||
"code": code,
|
||||
"expires_in": 300, // 5分钟
|
||||
})
|
||||
}
|
||||
|
||||
// BindDeviceHandler ESP32设备绑定接口
|
||||
func BindDeviceHandler(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
fmt.Println("[API] ESP32 device bind request received from", r.RemoteAddr)
|
||||
|
||||
// 解析请求
|
||||
var req struct {
|
||||
MAC string `json:"mac"`
|
||||
BindingCode string `json:"binding_code"`
|
||||
DeviceName string `json:"device_name"`
|
||||
}
|
||||
|
||||
err := json.NewDecoder(r.Body).Decode(&req)
|
||||
if err != nil {
|
||||
http.Error(w, "Invalid request body", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
if req.MAC == "" || req.BindingCode == "" {
|
||||
http.Error(w, "Missing required fields", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
// 如果没有提供设备名称,使用默认名称
|
||||
if req.DeviceName == "" {
|
||||
req.DeviceName = "ESP32音乐播放器"
|
||||
}
|
||||
|
||||
dm := GetDeviceManager()
|
||||
device, err := dm.BindDevice(req.MAC, req.BindingCode, req.DeviceName)
|
||||
if err != nil {
|
||||
fmt.Printf("[Error] Device bind failed: %v\n", err)
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(map[string]interface{}{
|
||||
"success": true,
|
||||
"message": "设备绑定成功",
|
||||
"token": device.Token,
|
||||
"username": device.Username,
|
||||
})
|
||||
}
|
||||
|
||||
// VerifyDeviceHandler 验证设备Token
|
||||
func VerifyDeviceHandler(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet {
|
||||
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
token := r.Header.Get("X-Device-Token")
|
||||
if token == "" {
|
||||
token = r.URL.Query().Get("token")
|
||||
}
|
||||
|
||||
if token == "" {
|
||||
http.Error(w, "Missing token", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
dm := GetDeviceManager()
|
||||
device, err := dm.VerifyToken(token)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
// 更新最后在线时间
|
||||
dm.UpdateLastSeen(device.MAC)
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(map[string]interface{}{
|
||||
"success": true,
|
||||
"device": map[string]interface{}{
|
||||
"mac": device.MAC,
|
||||
"username": device.Username,
|
||||
"device_name": device.DeviceName,
|
||||
"bind_time": device.BindTime,
|
||||
"last_seen": device.LastSeen,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// GetCurrentUser 从请求中获取当前登录用户
|
||||
func GetCurrentUser(r *http.Request) string {
|
||||
userStore := GetUserStore()
|
||||
|
||||
// 1. 尝试从 Authorization Header 获取 (Bearer Token)
|
||||
authHeader := r.Header.Get("Authorization")
|
||||
if authHeader != "" {
|
||||
token := strings.TrimPrefix(authHeader, "Bearer ")
|
||||
// 直接从UserStore验证Token
|
||||
user, err := userStore.GetUserByToken(token)
|
||||
if err == nil && user != nil {
|
||||
return user.Username
|
||||
}
|
||||
}
|
||||
|
||||
// 2. 尝试从 Cookie 获取 session_token
|
||||
cookie, err := r.Cookie("session_token")
|
||||
if err == nil {
|
||||
username := userStore.GetUsernameByToken(cookie.Value)
|
||||
if username != "" {
|
||||
return username
|
||||
}
|
||||
}
|
||||
|
||||
// 3. 尝试从 X-Device-Token Header 获取 (用于ESP32设备)
|
||||
deviceToken := r.Header.Get("X-Device-Token")
|
||||
if deviceToken != "" {
|
||||
dm := GetDeviceManager()
|
||||
device, err := dm.VerifyToken(deviceToken)
|
||||
if err == nil && device != nil {
|
||||
// 更新最后在线时间
|
||||
dm.UpdateLastSeen(device.MAC)
|
||||
return device.Username
|
||||
}
|
||||
}
|
||||
|
||||
return ""
|
||||
}
|
||||
|
||||
// DirectBindDeviceHandler Web端直接绑定设备(不需要绑定码)
|
||||
func DirectBindDeviceHandler(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
// 获取当前用户
|
||||
username := GetCurrentUser(r)
|
||||
if username == "" {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
json.NewEncoder(w).Encode(map[string]interface{}{
|
||||
"success": false,
|
||||
"message": "未登录",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// 解析请求
|
||||
var req struct {
|
||||
MAC string `json:"mac"`
|
||||
DeviceName string `json:"device_name"`
|
||||
}
|
||||
|
||||
err := json.NewDecoder(r.Body).Decode(&req)
|
||||
if err != nil {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(map[string]interface{}{
|
||||
"success": false,
|
||||
"message": "请求格式错误",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
if req.MAC == "" {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(map[string]interface{}{
|
||||
"success": false,
|
||||
"message": "MAC地址不能为空",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// 如果没有提供设备名称,使用默认名称
|
||||
if req.DeviceName == "" {
|
||||
req.DeviceName = "ESP32音乐播放器"
|
||||
}
|
||||
|
||||
dm := GetDeviceManager()
|
||||
device, err := dm.DirectBindDevice(req.MAC, username, req.DeviceName)
|
||||
if err != nil {
|
||||
fmt.Printf("[Error] Direct bind failed: %v\n", err)
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(map[string]interface{}{
|
||||
"success": false,
|
||||
"message": err.Error(),
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(map[string]interface{}{
|
||||
"success": true,
|
||||
"message": "设备绑定成功",
|
||||
"device": map[string]interface{}{
|
||||
"mac": device.MAC,
|
||||
"device_name": device.DeviceName,
|
||||
"bind_time": device.BindTime,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// ListUserDevicesHandler 列出用户的所有设备
|
||||
func ListUserDevicesHandler(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet {
|
||||
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
// 获取当前用户
|
||||
username := GetCurrentUser(r)
|
||||
if username == "" {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
json.NewEncoder(w).Encode(map[string]interface{}{
|
||||
"success": false,
|
||||
"message": "未登录",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
dm := GetDeviceManager()
|
||||
devices := dm.GetUserDevices(username)
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(map[string]interface{}{
|
||||
"success": true,
|
||||
"devices": devices,
|
||||
})
|
||||
}
|
||||
|
||||
// UnbindDeviceHandler 解绑设备
|
||||
func UnbindDeviceHandler(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
// 获取当前用户
|
||||
username := GetCurrentUser(r)
|
||||
if username == "" {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
json.NewEncoder(w).Encode(map[string]interface{}{
|
||||
"success": false,
|
||||
"message": "未登录",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// 解析请求
|
||||
var req struct {
|
||||
MAC string `json:"mac"`
|
||||
}
|
||||
|
||||
err := json.NewDecoder(r.Body).Decode(&req)
|
||||
if err != nil {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(map[string]interface{}{
|
||||
"success": false,
|
||||
"message": "请求格式错误",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
if req.MAC == "" {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(map[string]interface{}{
|
||||
"success": false,
|
||||
"message": "MAC地址不能为空",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
dm := GetDeviceManager()
|
||||
|
||||
// 检查设备是否属于当前用户
|
||||
device, err := dm.GetDevice(req.MAC)
|
||||
if err != nil {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(map[string]interface{}{
|
||||
"success": false,
|
||||
"message": "设备不存在",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
if device.Username != username {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(map[string]interface{}{
|
||||
"success": false,
|
||||
"message": "无权解绑此设备",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// 解绑设备
|
||||
err = dm.UnbindDevice(req.MAC)
|
||||
if err != nil {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(map[string]interface{}{
|
||||
"success": false,
|
||||
"message": err.Error(),
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(map[string]interface{}{
|
||||
"success": true,
|
||||
"message": "设备已解绑",
|
||||
})
|
||||
}
|
||||
|
||||
// SyncDeviceHandler ESP32用MAC地址同步Token(用于网页端绑定后自动获取token)
|
||||
func SyncDeviceHandler(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
var req struct {
|
||||
MAC string `json:"mac"`
|
||||
}
|
||||
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
http.Error(w, "Invalid request body", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
if req.MAC == "" {
|
||||
http.Error(w, "Missing MAC address", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
dm := GetDeviceManager()
|
||||
device, err := dm.GetDevice(req.MAC)
|
||||
|
||||
if err != nil || device == nil {
|
||||
// 设备未绑定
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
json.NewEncoder(w).Encode(map[string]interface{}{
|
||||
"success": false,
|
||||
"message": "设备未绑定",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// 更新最后在线时间
|
||||
dm.UpdateLastSeen(device.MAC)
|
||||
|
||||
// 返回 token 和用户名
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(map[string]interface{}{
|
||||
"success": true,
|
||||
"token": device.Token,
|
||||
"username": device.Username,
|
||||
"message": "同步成功",
|
||||
})
|
||||
|
||||
fmt.Printf("[Info] Device %s synced token for user: %s\n", device.MAC, device.Username)
|
||||
}
|
||||
13
devices.json
Executable file
13
devices.json
Executable file
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"devices": {
|
||||
"80:B5:4E:D4:F9:04": {
|
||||
"mac": "80:B5:4E:D4:F9:04",
|
||||
"username": "test",
|
||||
"device_name": "ESP32音乐播放器",
|
||||
"token": "c31ad4f9c77d991b2d2b572bb7af9b1fc0a256ede2cf05a3cf51431ffaa1b0f2",
|
||||
"bind_time": "2025-11-26T12:41:13.9407887+08:00",
|
||||
"last_seen": "2025-11-26T12:41:13.9407887+08:00",
|
||||
"is_active": true
|
||||
}
|
||||
}
|
||||
}
|
||||
262
file.go
Executable file
262
file.go
Executable file
@@ -0,0 +1,262 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// ListFiles function: Traverse all files in the specified directory and return a slice of the file path
|
||||
func ListFiles(dir string) ([]string, error) {
|
||||
var files []string
|
||||
err := filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !info.IsDir() {
|
||||
files = append(files, path)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
return files, err
|
||||
}
|
||||
|
||||
// Get Content function: Read the content of a specified file and return it
|
||||
func GetFileContent(filePath string) ([]byte, error) {
|
||||
file, err := os.Open(filePath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
// Get File Size
|
||||
fileInfo, err := file.Stat()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
fileSize := fileInfo.Size()
|
||||
|
||||
// Read File Content
|
||||
fileContent := make([]byte, fileSize)
|
||||
_, err = file.Read(fileContent)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return fileContent, nil
|
||||
}
|
||||
|
||||
// fileHandler function: Handle file requests
|
||||
func fileHandler(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Server", "MeowMusicEmbeddedServer")
|
||||
// Obtain the path of the request
|
||||
filePath := r.URL.Path
|
||||
|
||||
// Check if the request path starts with "/url/"
|
||||
if strings.HasPrefix(filePath, "/url/") {
|
||||
// Extract the URL after "/url/"
|
||||
urlPath := filePath[len("/url/"):]
|
||||
// Decode the URL path in case it's URL encoded
|
||||
decodedURL, err := url.QueryUnescape(urlPath)
|
||||
if err != nil {
|
||||
NotFoundHandler(w, r)
|
||||
return
|
||||
}
|
||||
// Determine the protocol based on the URL path
|
||||
var protocol string
|
||||
if strings.HasPrefix(decodedURL, "http/") {
|
||||
protocol = "http://"
|
||||
} else if strings.HasPrefix(decodedURL, "https/") {
|
||||
protocol = "https://"
|
||||
} else {
|
||||
NotFoundHandler(w, r)
|
||||
return
|
||||
}
|
||||
// Remove the protocol part from the decoded URL
|
||||
decodedURL = strings.TrimPrefix(decodedURL, "http/")
|
||||
decodedURL = strings.TrimPrefix(decodedURL, "https/")
|
||||
// Correctly concatenate the protocol with the decoded URL
|
||||
decodedURL = protocol + decodedURL
|
||||
// Create a new HTTP request to the decoded URL, without copying headers
|
||||
req, err := http.NewRequest("GET", decodedURL, nil)
|
||||
if err != nil {
|
||||
NotFoundHandler(w, r)
|
||||
return
|
||||
}
|
||||
// Send the request and get the response
|
||||
client := &http.Client{}
|
||||
resp, err := client.Do(req)
|
||||
if err != nil || resp.StatusCode != http.StatusOK {
|
||||
NotFoundHandler(w, r)
|
||||
return
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
// Read the response body into a byte slice
|
||||
fileContent, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
NotFoundHandler(w, r)
|
||||
return
|
||||
}
|
||||
// Set appropriate Content-Type based on file extension
|
||||
ext := filepath.Ext(decodedURL)
|
||||
switch ext {
|
||||
case ".mp3":
|
||||
w.Header().Set("Content-Type", "audio/mpeg")
|
||||
case ".wav":
|
||||
w.Header().Set("Content-Type", "audio/wav")
|
||||
case ".flac":
|
||||
w.Header().Set("Content-Type", "audio/flac")
|
||||
case ".aac":
|
||||
w.Header().Set("Content-Type", "audio/aac")
|
||||
case ".ogg":
|
||||
w.Header().Set("Content-Type", "audio/ogg")
|
||||
case ".m4a":
|
||||
w.Header().Set("Content-Type", "audio/mp4")
|
||||
case ".amr":
|
||||
w.Header().Set("Content-Type", "audio/amr")
|
||||
case ".jpg", ".jpeg":
|
||||
w.Header().Set("Content-Type", "image/jpeg")
|
||||
case ".png":
|
||||
w.Header().Set("Content-Type", "image/png")
|
||||
case ".gif":
|
||||
w.Header().Set("Content-Type", "image/gif")
|
||||
case ".bmp":
|
||||
w.Header().Set("Content-Type", "image/bmp")
|
||||
case ".svg":
|
||||
w.Header().Set("Content-Type", "image/svg+xml")
|
||||
case ".webp":
|
||||
w.Header().Set("Content-Type", "image/webp")
|
||||
case ".txt":
|
||||
w.Header().Set("Content-Type", "text/plain")
|
||||
case ".lrc":
|
||||
w.Header().Set("Content-Type", "text/plain")
|
||||
case ".mrc":
|
||||
w.Header().Set("Content-Type", "text/plain")
|
||||
case ".json":
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
default:
|
||||
w.Header().Set("Content-Type", "application/octet-stream")
|
||||
}
|
||||
// Write file content to response
|
||||
w.Write(fileContent)
|
||||
return
|
||||
}
|
||||
|
||||
// Construct the complete file path
|
||||
fullFilePath := filepath.Join("./files", filePath)
|
||||
|
||||
// Try replacing '+' with ' ' and check if the file exists
|
||||
tempFilePath := strings.ReplaceAll(fullFilePath, "+", " ")
|
||||
if _, err := os.Stat(tempFilePath); err == nil {
|
||||
fullFilePath = tempFilePath
|
||||
}
|
||||
|
||||
// Get file content
|
||||
fileContent, err := GetFileContent(fullFilePath)
|
||||
|
||||
// 检查是否为空文件(特别是 music.mp3,如果是空的也视为不存在,需要等待转码)
|
||||
if err == nil && len(fileContent) == 0 && strings.HasSuffix(filePath, "/music.mp3") {
|
||||
err = fmt.Errorf("file is empty")
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
// If file not found, try replacing ' ' with '+' and check again
|
||||
tempFilePath = strings.ReplaceAll(fullFilePath, " ", "+")
|
||||
fileContent, err = GetFileContent(tempFilePath)
|
||||
|
||||
// 同样检查带 + 的路径是否为空
|
||||
if err == nil && len(fileContent) == 0 && strings.HasSuffix(filePath, "/music.mp3") {
|
||||
err = fmt.Errorf("file is empty")
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
// 特殊处理:如果请求的是缓存中的文件,等待后台处理完成
|
||||
fmt.Printf("[Web Access] File not found, checking path prefix: %s\n", filePath)
|
||||
if strings.HasPrefix(filePath, "/cache/music/") {
|
||||
// music.mp3 等待最多 60 秒,歌词等待最多 10 秒
|
||||
maxWait := 10
|
||||
if strings.HasSuffix(filePath, "/music.mp3") {
|
||||
maxWait = 60
|
||||
}
|
||||
|
||||
// URL 解码路径(处理中文文件名)
|
||||
decodedPath, _ := url.QueryUnescape(filePath)
|
||||
decodedPath = strings.ReplaceAll(decodedPath, "+", " ") // + 转空格
|
||||
decodedFullPath := filepath.Join("./files", decodedPath)
|
||||
|
||||
fmt.Printf("[Web Access] Waiting for file: %s (max %d seconds)\n", decodedFullPath, maxWait)
|
||||
for i := 0; i < maxWait; i++ {
|
||||
time.Sleep(1 * time.Second)
|
||||
// 检查 URL 解码后的路径
|
||||
if _, err := os.Stat(decodedFullPath); err == nil {
|
||||
fmt.Printf("[Web Access] File ready after %d seconds: %s\n", i+1, decodedFullPath)
|
||||
http.ServeFile(w, r, decodedFullPath)
|
||||
return
|
||||
}
|
||||
// 检查原始路径
|
||||
if _, err := os.Stat(fullFilePath); err == nil {
|
||||
http.ServeFile(w, r, fullFilePath)
|
||||
return
|
||||
}
|
||||
// 检查带 + 的路径
|
||||
tempPath := strings.ReplaceAll(fullFilePath, " ", "+")
|
||||
if _, err := os.Stat(tempPath); err == nil {
|
||||
http.ServeFile(w, r, tempPath)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
NotFoundHandler(w, r)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// Set appropriate Content-Type based on file extension
|
||||
ext := filepath.Ext(filePath)
|
||||
switch ext {
|
||||
case ".mp3":
|
||||
w.Header().Set("Content-Type", "audio/mpeg")
|
||||
case ".wav":
|
||||
w.Header().Set("Content-Type", "audio/wav")
|
||||
case ".flac":
|
||||
w.Header().Set("Content-Type", "audio/flac")
|
||||
case ".aac":
|
||||
w.Header().Set("Content-Type", "audio/aac")
|
||||
case ".ogg":
|
||||
w.Header().Set("Content-Type", "audio/ogg")
|
||||
case ".m4a":
|
||||
w.Header().Set("Content-Type", "audio/mp4")
|
||||
case ".amr":
|
||||
w.Header().Set("Content-Type", "audio/amr")
|
||||
case ".jpg", ".jpeg":
|
||||
w.Header().Set("Content-Type", "image/jpeg")
|
||||
case ".png":
|
||||
w.Header().Set("Content-Type", "image/png")
|
||||
case ".gif":
|
||||
w.Header().Set("Content-Type", "image/gif")
|
||||
case ".bmp":
|
||||
w.Header().Set("Content-Type", "image/bmp")
|
||||
case ".svg":
|
||||
w.Header().Set("Content-Type", "image/svg+xml")
|
||||
case ".webp":
|
||||
w.Header().Set("Content-Type", "image/webp")
|
||||
case ".txt":
|
||||
w.Header().Set("Content-Type", "text/plain")
|
||||
case ".lrc":
|
||||
w.Header().Set("Content-Type", "text/plain")
|
||||
case ".mrc":
|
||||
w.Header().Set("Content-Type", "text/plain")
|
||||
case ".json":
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
default:
|
||||
w.Header().Set("Content-Type", "application/octet-stream")
|
||||
}
|
||||
|
||||
// Write file content to response
|
||||
w.Write(fileContent)
|
||||
}
|
||||
BIN
files/background.webp
Normal file
BIN
files/background.webp
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 710 KiB |
0
files/cache/music/.gitignore
vendored
Normal file
0
files/cache/music/.gitignore
vendored
Normal file
1
files/playlists.json
Normal file
1
files/playlists.json
Normal file
@@ -0,0 +1 @@
|
||||
{}
|
||||
1
files/user_playlists.json
Normal file
1
files/user_playlists.json
Normal file
@@ -0,0 +1 @@
|
||||
{}
|
||||
1
files/users.json
Normal file
1
files/users.json
Normal file
@@ -0,0 +1 @@
|
||||
[]
|
||||
22
frontend/package.json
Normal file
22
frontend/package.json
Normal file
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"name": "meow-music-frontend",
|
||||
"version": "1.0.0",
|
||||
"description": "Modern music streaming web app",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "vite build",
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
"react": "^18.2.0",
|
||||
"react-dom": "^18.2.0",
|
||||
"lucide-react": "^0.263.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@vitejs/plugin-react": "^4.0.3",
|
||||
"vite": "^4.4.5",
|
||||
"autoprefixer": "^10.4.14",
|
||||
"postcss": "^8.4.27",
|
||||
"tailwindcss": "^3.3.3"
|
||||
}
|
||||
}
|
||||
13
go.mod
Normal file → Executable file
13
go.mod
Normal file → Executable file
@@ -1,13 +1,8 @@
|
||||
module github.com/OmniX-Space/MeowBox-Core
|
||||
module MeowEmbedded-MusicServer
|
||||
|
||||
go 1.25.4
|
||||
go 1.25.0
|
||||
|
||||
require (
|
||||
github.com/go-sql-driver/mysql v1.9.3
|
||||
golang.org/x/crypto v0.45.0
|
||||
)
|
||||
|
||||
require (
|
||||
filippo.io/edwards25519 v1.1.0 // indirect
|
||||
golang.org/x/sys v0.38.0 // indirect
|
||||
github.com/joho/godotenv v1.5.1
|
||||
golang.org/x/crypto v0.31.0
|
||||
)
|
||||
|
||||
4
go.sum
Normal file
4
go.sum
Normal file
@@ -0,0 +1,4 @@
|
||||
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
|
||||
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
|
||||
golang.org/x/crypto v0.31.0 h1:ihbySMvVjLAeSH1IbfcRTkD/iNscyz8rGzjF/E5hV6U=
|
||||
golang.org/x/crypto v0.31.0/go.mod h1:kDsLvtWBEx7MV9tJOj9bnXsPbxwJQ6csT/x4KIN4Ssk=
|
||||
350
helper.go
Executable file
350
helper.go
Executable file
@@ -0,0 +1,350 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"mime"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Source is an alias for MusicItem (used in sources.json)
|
||||
type Source = MusicItem
|
||||
|
||||
// Download file from URL
|
||||
func downloadFile(filepath string, url string) error {
|
||||
// Create the file
|
||||
out, err := os.Create(filepath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer out.Close()
|
||||
|
||||
// Get the data
|
||||
resp, err := http.Get(url)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
// Check server response
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return fmt.Errorf("bad status: %s", resp.Status)
|
||||
}
|
||||
|
||||
// Write the body to file
|
||||
_, err = io.Copy(out, resp.Body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Get IP address from request
|
||||
func IPhandler(r *http.Request) (string, error) {
|
||||
ip := r.Header.Get("X-Real-IP")
|
||||
if ip == "" {
|
||||
ip = r.Header.Get("X-Forwarded-For")
|
||||
}
|
||||
if ip == "" {
|
||||
ip, _, _ = net.SplitHostPort(r.RemoteAddr)
|
||||
}
|
||||
return ip, nil
|
||||
}
|
||||
|
||||
// Read sources from sources.json
|
||||
func readSources() []Source {
|
||||
file, err := os.Open("sources.json")
|
||||
if err != nil {
|
||||
return []Source{}
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
var sources []Source
|
||||
decoder := json.NewDecoder(file)
|
||||
err = decoder.Decode(&sources)
|
||||
if err != nil {
|
||||
return []Source{}
|
||||
}
|
||||
return sources
|
||||
}
|
||||
|
||||
// Read music from cache
|
||||
func readFromCache(path string) (MusicItem, bool) {
|
||||
// Logic to read music item from a cached folder path
|
||||
// This assumes path is like "files/cache/music/Artist-Song"
|
||||
info, err := os.Stat(path)
|
||||
if err != nil || !info.IsDir() {
|
||||
return MusicItem{}, false
|
||||
}
|
||||
|
||||
dirName := filepath.Base(path)
|
||||
parts := strings.SplitN(dirName, "-", 2)
|
||||
var artist, title string
|
||||
if len(parts) == 2 {
|
||||
artist = parts[0]
|
||||
title = parts[1]
|
||||
} else {
|
||||
title = dirName
|
||||
}
|
||||
|
||||
return getLocalMusicItem(title, artist), true
|
||||
}
|
||||
|
||||
// Request and cache music from API
|
||||
func requestAndCacheMusic(song, singer string) MusicItem {
|
||||
// Try different sources in priority order
|
||||
sources := []string{"kuwo", "netease", "migu", "baidu"}
|
||||
for _, source := range sources {
|
||||
item := YuafengAPIResponseHandler(source, song, singer)
|
||||
if item.Title != "" {
|
||||
return item
|
||||
}
|
||||
}
|
||||
return MusicItem{}
|
||||
}
|
||||
|
||||
// 直接从远程URL流式转码(边下载边转码,超快!)
|
||||
func streamConvertAudio(inputURL, outputFile string) error {
|
||||
fmt.Printf("[Info] Stream converting from URL (fast mode)\n")
|
||||
|
||||
// 先写入临时文件,完成后再重命名(避免读取到不完整的文件)
|
||||
tempFile := outputFile + ".tmp"
|
||||
|
||||
// ffmpeg 直接读取远程 URL 并转码
|
||||
// -t 600: 只下载前10分钟,减少80%下载量!
|
||||
// 移除 reconnect 参数,避免兼容性问题
|
||||
// 添加 -bufsize 以提高稳定性
|
||||
cmd := exec.Command("ffmpeg", "-y",
|
||||
"-t", "600",
|
||||
"-i", inputURL,
|
||||
"-threads", "0",
|
||||
"-ac", "1", "-ar", "24000", "-b:a", "32k", "-q:a", "9",
|
||||
"-bufsize", "64k",
|
||||
tempFile)
|
||||
|
||||
err := cmd.Run()
|
||||
if err != nil {
|
||||
fmt.Printf("[Error] Stream convert failed: %v\n", err)
|
||||
os.Remove(tempFile) // 清理临时文件
|
||||
return err
|
||||
}
|
||||
|
||||
// 检查生成的文件大小
|
||||
fileInfo, err := os.Stat(tempFile)
|
||||
if err != nil || fileInfo.Size() < 1024 {
|
||||
fmt.Printf("[Error] Stream converted file is too small or empty\n")
|
||||
os.Remove(tempFile)
|
||||
return fmt.Errorf("converted file is too small")
|
||||
}
|
||||
|
||||
// 转码完成后重命名为最终文件
|
||||
err = os.Rename(tempFile, outputFile)
|
||||
if err != nil {
|
||||
fmt.Printf("[Error] Failed to rename temp file: %v\n", err)
|
||||
return err
|
||||
}
|
||||
|
||||
fmt.Printf("[Success] Stream convert completed: %s\n", outputFile)
|
||||
return nil
|
||||
}
|
||||
|
||||
// 实时流式转码到 HTTP Writer(边下载边播放!)
|
||||
func streamConvertToWriter(inputURL string, w http.ResponseWriter) error {
|
||||
fmt.Printf("[Info] Live streaming from URL: %s\n", inputURL)
|
||||
|
||||
// ffmpeg 边下载边转码,输出到 stdout
|
||||
cmd := exec.Command("ffmpeg",
|
||||
"-i", inputURL,
|
||||
"-threads", "0",
|
||||
"-ac", "1", "-ar", "24000", "-b:a", "32k", "-q:a", "9",
|
||||
"-f", "mp3",
|
||||
"pipe:1") // 输出到 stdout
|
||||
|
||||
// 获取 stdout pipe
|
||||
stdout, err := cmd.StdoutPipe()
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to get stdout pipe: %v", err)
|
||||
}
|
||||
|
||||
// 启动 ffmpeg
|
||||
if err := cmd.Start(); err != nil {
|
||||
return fmt.Errorf("failed to start ffmpeg: %v", err)
|
||||
}
|
||||
|
||||
// 设置响应头
|
||||
w.Header().Set("Content-Type", "audio/mpeg")
|
||||
// 移除 Transfer-Encoding: chunked,让 Go 自动处理
|
||||
|
||||
// 边读边写到 HTTP response
|
||||
buf := make([]byte, 8192)
|
||||
for {
|
||||
n, err := stdout.Read(buf)
|
||||
if n > 0 {
|
||||
w.Write(buf[:n])
|
||||
if f, ok := w.(http.Flusher); ok {
|
||||
f.Flush() // 立即发送给客户端
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
cmd.Wait()
|
||||
fmt.Printf("[Success] Live streaming completed\n")
|
||||
return nil
|
||||
}
|
||||
|
||||
// Helper function for identifying file formats
|
||||
func getMusicFileExtension(url string) (string, error) {
|
||||
resp, err := http.Head(url)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
// Get file format from Content-Type header
|
||||
contentType := resp.Header.Get("Content-Type")
|
||||
ext, _, err := mime.ParseMediaType(contentType)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
// Identify file extension based on file format
|
||||
switch ext {
|
||||
case "audio/mpeg":
|
||||
return ".mp3", nil
|
||||
case "audio/flac":
|
||||
return ".flac", nil
|
||||
case "audio/x-flac":
|
||||
return ".flac", nil
|
||||
case "audio/wav":
|
||||
return ".wav", nil
|
||||
case "audio/aac":
|
||||
return ".aac", nil
|
||||
case "audio/ogg":
|
||||
return ".ogg", nil
|
||||
case "application/octet-stream":
|
||||
// Try to guess file format from URL or other information
|
||||
if strings.Contains(url, ".mp3") {
|
||||
return ".mp3", nil
|
||||
} else if strings.Contains(url, ".flac") {
|
||||
return ".flac", nil
|
||||
} else if strings.Contains(url, ".wav") {
|
||||
return ".wav", nil
|
||||
} else if strings.Contains(url, ".aac") {
|
||||
return ".aac", nil
|
||||
} else if strings.Contains(url, ".ogg") {
|
||||
return ".ogg", nil
|
||||
} else {
|
||||
return "", fmt.Errorf("unknown file format from Content-Type and URL: %s", contentType)
|
||||
}
|
||||
default:
|
||||
return "", fmt.Errorf("unknown file format: %s", ext)
|
||||
}
|
||||
}
|
||||
|
||||
// Helper function for identifying file formats
|
||||
func GetDuration(filePath string) int {
|
||||
fmt.Printf("[Info] Get duration of obtaining music file %s\n", filePath)
|
||||
// Use ffprobe to get audio duration
|
||||
output, err := exec.Command("ffprobe", "-v", "error", "-show_entries", "format=duration", "-of", "default=noprint_wrappers=1:nokey=1", filePath).Output()
|
||||
if err != nil {
|
||||
fmt.Println("[Error] Error getting audio duration:", err)
|
||||
return 0
|
||||
}
|
||||
|
||||
duration, err := strconv.ParseFloat(strings.TrimSpace(string(output)), 64)
|
||||
if err != nil {
|
||||
fmt.Println("[Error] Error converting duration to float:", err)
|
||||
return 0
|
||||
}
|
||||
|
||||
return int(duration)
|
||||
}
|
||||
|
||||
// Helper function to compress and segment audio file
|
||||
func compressAndSegmentAudio(inputFile, outputDir string) error {
|
||||
fmt.Printf("[Info] Compress and segment audio file %s\n", inputFile)
|
||||
// Compress music files
|
||||
outputFile := filepath.Join(outputDir, "music.mp3")
|
||||
cmd := exec.Command("ffmpeg", "-i", inputFile, "-ac", "1", "-ab", "32k", "-ar", "24000", outputFile)
|
||||
err := cmd.Run()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Helper function to obtain music data from local folder
|
||||
func getLocalMusicItem(song, singer string) MusicItem {
|
||||
musicDir := "./files/music"
|
||||
fmt.Println("[Info] Reading local folder music.")
|
||||
files, err := os.ReadDir(musicDir)
|
||||
if err != nil {
|
||||
fmt.Println("[Error] Failed to read local music directory:", err)
|
||||
return MusicItem{}
|
||||
}
|
||||
|
||||
for _, file := range files {
|
||||
if file.IsDir() {
|
||||
if singer == "" {
|
||||
if strings.Contains(file.Name(), song) {
|
||||
dirPath := filepath.Join(musicDir, file.Name())
|
||||
// Extract artist and title from the directory name
|
||||
parts := strings.SplitN(file.Name(), "-", 2)
|
||||
var artist, title string
|
||||
if len(parts) == 2 {
|
||||
artist = parts[0]
|
||||
title = parts[1]
|
||||
} else {
|
||||
title = file.Name()
|
||||
}
|
||||
basePath := "/cache/music/" + url.QueryEscape(file.Name())
|
||||
return MusicItem{
|
||||
Title: title,
|
||||
Artist: artist,
|
||||
CoverURL: basePath + "/cover.jpg",
|
||||
LyricURL: basePath + "/lyric.lrc",
|
||||
AudioFullURL: basePath + "/music.mp3",
|
||||
AudioURL: basePath + "/music.mp3",
|
||||
M3U8URL: basePath + "/music.m3u8",
|
||||
Duration: GetDuration(filepath.Join(dirPath, "music.mp3")),
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if strings.Contains(file.Name(), song) && strings.Contains(file.Name(), singer) {
|
||||
dirPath := filepath.Join(musicDir, file.Name())
|
||||
// Extract artist and title from the directory name
|
||||
parts := strings.SplitN(file.Name(), "-", 2)
|
||||
var artist, title string
|
||||
if len(parts) == 2 {
|
||||
artist = parts[0]
|
||||
title = parts[1]
|
||||
} else {
|
||||
title = file.Name()
|
||||
}
|
||||
basePath := "/cache/music/" + url.QueryEscape(file.Name())
|
||||
return MusicItem{
|
||||
Title: title,
|
||||
Artist: artist,
|
||||
CoverURL: basePath + "/cover.jpg",
|
||||
LyricURL: basePath + "/lyric.lrc",
|
||||
AudioFullURL: basePath + "/music.mp3",
|
||||
AudioURL: basePath + "/music.mp3",
|
||||
M3U8URL: basePath + "/music.m3u8",
|
||||
Duration: GetDuration(filepath.Join(dirPath, "music.mp3")),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return MusicItem{}
|
||||
}
|
||||
17
httperr.go
Executable file
17
httperr.go
Executable file
@@ -0,0 +1,17 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"os"
|
||||
)
|
||||
|
||||
func NotFoundHandler(w http.ResponseWriter, r *http.Request) {
|
||||
home_url := os.Getenv("HOME_URL")
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
w.Header().Set("Server", "MeowMusicServer")
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
fmt.Fprint(w, "<head><meta charset=\"UTF-8\"><meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"><meta http-equiv=\"X-UA-Compatible\" content=\"ie=edge\"><link rel=\"icon\" href=\"favicon.ico\"><title>404 Music Lost!</title><style>@import url('https://fonts.googleapis.com/css?family=Montserrat:400,600,700');@import url('https://fonts.googleapis.com/css?family=Catamaran:400,800');.error-container {text-align: center;font-size: 106px;font-family: 'Catamaran', sans-serif;font-weight: 800;margin: 70px 15px;}.error-container>span {display: inline-block;position: relative;}.error-container>span.four {width: 136px;height: 43px;border-radius: 999px;background:linear-gradient(140deg, rgba(0, 0, 0, 0.1) 0%, rgba(0, 0, 0, 0.07) 43%, transparent 44%, transparent 100%),linear-gradient(105deg, transparent 0%, transparent 40%, rgba(0, 0, 0, 0.06) 41%, rgba(0, 0, 0, 0.07) 76%, transparent 77%, transparent 100%),linear-gradient(to right, #d89ca4, #e27b7e);}.error-container>span.four:before,.error-container>span.four:after {content: '';display: block;position: absolute;border-radius: 999px;}.error-container>span.four:before {width: 43px;height: 156px;left: 60px;bottom: -43px;background:linear-gradient(128deg, rgba(0, 0, 0, 0.1) 0%, rgba(0, 0, 0, 0.07) 40%, transparent 41%, transparent 100%),linear-gradient(116deg, rgba(0, 0, 0, 0.1) 0%, rgba(0, 0, 0, 0.07) 50%, transparent 51%, transparent 100%),linear-gradient(to top, #99749D, #B895AB, #CC9AA6, #D7969E, #E0787F);}.error-container>span.four:after {width: 137px;height: 43px;transform: rotate(-49.5deg);left: -18px;bottom: 36px;background: linear-gradient(to right, #99749D, #B895AB, #CC9AA6, #D7969E, #E0787F);}.error-container>span.zero {vertical-align: text-top;width: 156px;height: 156px;border-radius: 999px;background: linear-gradient(-45deg, transparent 0%, rgba(0, 0, 0, 0.06) 50%, transparent 51%, transparent 100%),linear-gradient(to top right, #99749D, #99749D, #B895AB, #CC9AA6, #D7969E, #ED8687, #ED8687);overflow: hidden;animation: bgshadow 5s infinite;}.error-container>span.zero:before {content: '';display: block;position: absolute;transform: rotate(45deg);width: 90px;height: 90px;background-color: transparent;left: 0px;bottom: 0px;background:linear-gradient(95deg, transparent 0%, transparent 8%, rgba(0, 0, 0, 0.07) 9%, transparent 50%, transparent 100%),linear-gradient(85deg, transparent 0%, transparent 19%, rgba(0, 0, 0, 0.05) 20%, rgba(0, 0, 0, 0.07) 91%, transparent 92%, transparent 100%);}.error-container>span.zero:after {content: '';display: block;position: absolute;border-radius: 999px;width: 70px;height: 70px;left: 43px;bottom: 43px;background: #FDFAF5;box-shadow: -2px 2px 2px 0px rgba(0, 0, 0, 0.1);}.screen-reader-text {position: absolute;top: -9999em;left: -9999em;}@keyframes bgshadow {0% {box-shadow: inset -160px 160px 0px 5px rgba(0, 0, 0, 0.4);}45% {box-shadow: inset 0px 0px 0px 0px rgba(0, 0, 0, 0.1);}55% {box-shadow: inset 0px 0px 0px 0px rgba(0, 0, 0, 0.1);}100% {box-shadow: inset 160px -160px 0px 5px rgba(0, 0, 0, 0.4);}}* {-webkit-box-sizing: border-box;-moz-box-sizing: border-box;box-sizing: border-box;}body {background-color: #FDFAF5;margin-bottom: 50px;}html,button,input,select,textarea {font-family: 'Montserrat', Helvetica, sans-serif;color: #bbb;}h1 {text-align: center;margin: 30px 15px;}.zoom-area {max-width: 490px;margin: 30px auto 30px;font-size: 19px;text-align: center;}.link-container {text-align: center;}a.more-link {text-transform: uppercase;font-size: 13px;background-color: #de7e85;padding: 10px 15px;border-radius: 0;color: #fff;display: inline-block;margin-right: 5px;margin-bottom: 5px;line-height: 1.5;text-decoration: none;margin-top: 50px;letter-spacing: 1px;}</style></head><body><h1>404 Music Lost!</h1><p class=\"zoom-area\">We couldn't find the content you were looking for.</p><section class=\"error-container\"><span class=\"four\"><span class=\"screen-reader-text\">4</span></span><span class=\"zero\"><span class=\"screen-reader-text\">0</span></span><span class=\"four\"><span class=\"screen-reader-text\">4</span></span></section>")
|
||||
fmt.Fprintf(w, "<div class=\"link-container\"><a href=\"%s\" class=\"more-link\">Go Home</a></div></body>", home_url)
|
||||
fmt.Printf("[Web Access] Return 404 Not Found\n")
|
||||
}
|
||||
410
index.go
Executable file
410
index.go
Executable file
@@ -0,0 +1,410 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
)
|
||||
|
||||
func indexHandler(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Server", "MeowMusicEmbeddedServer")
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
fmt.Printf("[Web Access] Handling request for %s\n", r.URL.Path)
|
||||
|
||||
// Serve full music app for both / and /app
|
||||
if r.URL.Path == "/" || r.URL.Path == "/app" {
|
||||
appPath := filepath.Join("theme", "full-app.html")
|
||||
if _, err := os.Stat(appPath); err == nil {
|
||||
http.ServeFile(w, r, appPath)
|
||||
fmt.Printf("[Web Access] Return full music app page\n")
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// Test version available at /test
|
||||
if r.URL.Path == "/test" {
|
||||
testPath := filepath.Join("theme", "test-app.html")
|
||||
if _, err := os.Stat(testPath); err == nil {
|
||||
http.ServeFile(w, r, testPath)
|
||||
fmt.Printf("[Web Access] Return test app page\n")
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// Access classic interface via /classic
|
||||
if r.URL.Path == "/classic" {
|
||||
indexPath := filepath.Join("theme", "index.html")
|
||||
if _, err := os.Stat(indexPath); err == nil {
|
||||
http.ServeFile(w, r, indexPath)
|
||||
fmt.Printf("[Web Access] Return classic index page\n")
|
||||
return
|
||||
}
|
||||
defaultIndexPage(w)
|
||||
return
|
||||
}
|
||||
|
||||
if r.URL.Path != "/" {
|
||||
fileHandler(w, r)
|
||||
return
|
||||
}
|
||||
// Fallback to index.html
|
||||
indexPath := filepath.Join("theme", "index.html")
|
||||
|
||||
// Check if index.html exists in theme directory
|
||||
if _, err := os.Stat(indexPath); os.IsNotExist(err) {
|
||||
defaultIndexPage(w)
|
||||
} else if err != nil {
|
||||
defaultIndexPage(w)
|
||||
} else {
|
||||
http.ServeFile(w, r, indexPath)
|
||||
fmt.Printf("[Web Access] Return custom index pages\n")
|
||||
}
|
||||
}
|
||||
|
||||
func defaultIndexPage(w http.ResponseWriter) {
|
||||
websiteVersion := "0.0.1-rc-1"
|
||||
websiteNameCN := os.Getenv("WEBSITE_NAME_CN")
|
||||
if websiteNameCN == "" {
|
||||
websiteNameCN = "🎵 音乐搜索"
|
||||
}
|
||||
websiteNameEN := os.Getenv("WEBSITE_NAME_EN")
|
||||
if websiteNameEN == "" {
|
||||
websiteNameEN = "🎵 Music Search"
|
||||
}
|
||||
websiteTitleCN := os.Getenv("WEBSITE_TITLE_CN")
|
||||
if websiteTitleCN == "" {
|
||||
websiteTitleCN = "为嵌入式设备设计的音乐搜索服务器"
|
||||
}
|
||||
websiteTitleEN := os.Getenv("WEBSITE_TITLE_EN")
|
||||
if websiteTitleEN == "" {
|
||||
websiteTitleEN = "Music Search Server for Embedded Devices"
|
||||
}
|
||||
websiteDescCN := os.Getenv("WEBSITE_DESC_CN")
|
||||
if websiteDescCN == "" {
|
||||
websiteDescCN = "搜索并播放您喜爱的音乐"
|
||||
}
|
||||
websiteDescEN := os.Getenv("WEBSITE_DESC_EN")
|
||||
if websiteDescEN == "" {
|
||||
websiteDescEN = "Search and play your favorite music"
|
||||
}
|
||||
websiteKeywordsCN := os.Getenv("WEBSITE_KEYWORDS_CN")
|
||||
if websiteKeywordsCN == "" {
|
||||
websiteKeywordsCN = "音乐, 搜索, 嵌入式"
|
||||
}
|
||||
websiteKeywordsEN := os.Getenv("WEBSITE_KEYWORDS_EN")
|
||||
if websiteKeywordsEN == "" {
|
||||
websiteKeywordsEN = "music, search, embedded"
|
||||
}
|
||||
websiteFavicon := os.Getenv("WEBSITE_FAVICON")
|
||||
if websiteFavicon == "" {
|
||||
websiteFavicon = "/favicon.ico"
|
||||
}
|
||||
websiteBackground := os.Getenv("WEBSITE_BACKGROUND")
|
||||
if websiteBackground == "" {
|
||||
websiteBackground = "/background.webp"
|
||||
}
|
||||
fontawesomeCDN := os.Getenv("FONTAWESOME_CDN")
|
||||
if fontawesomeCDN == "" {
|
||||
fontawesomeCDN = "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"
|
||||
}
|
||||
|
||||
// Build HTML
|
||||
fmt.Fprintf(w, "<!DOCTYPE html><html>")
|
||||
fmt.Fprintf(w, "<head>")
|
||||
fmt.Fprintf(w, "<meta charset=\"UTF-8\">")
|
||||
fmt.Fprintf(w, "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">")
|
||||
fmt.Fprintf(w, "<meta http-equiv=\"X-UA-Compatible\" content=\"ie=edge\">")
|
||||
fmt.Fprintf(w, "<link rel=\"icon\" href=\"%s\">", websiteFavicon)
|
||||
fmt.Fprintf(w, "<link rel=\"stylesheet\" href=\"%s\">", fontawesomeCDN)
|
||||
fmt.Fprintf(w, "<title></title><style>")
|
||||
// HTML style
|
||||
fmt.Fprintf(w, "body {background-image: url('%s');background-size: cover;background-repeat: no-repeat;background-attachment: fixed;display: flex;justify-content: center;align-items: center;margin: 60px 0;}", websiteBackground)
|
||||
fmt.Fprintf(w, ".container {background: rgba(255, 255, 255, 0.4);width: 65%%;border-radius: 20px;box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);backdrop-filter: blur(10px);display: flex;flex-direction: column;}")
|
||||
fmt.Fprintf(w, ".title {font-size: 36px;font-weight: bold;margin: 25px auto 0px auto;text-align: center;}.description {font-size: 1.1rem;color: #4f596b;margin: 10px auto;text-align: center;}")
|
||||
fmt.Fprintf(w, ".search-form {display: flex;justify-content: center;align-items: center;width: 100%%;margin-bottom: 20px;}.songContainer,.singerContainer,.searchContainer {display: flex;align-items: center;margin: 0 10px;}")
|
||||
fmt.Fprintf(w, ".songInput {padding: 10px;border: 2px solid #ccc;border-radius: 20px;height: 45px;margin-left: -6%%;margin-right: 10px;font-size: 1.1rem;width: 110%%;background-color: rgba(255, 255, 255, 0.4);}")
|
||||
fmt.Fprintf(w, ".artistInput {padding: 10px;border: 2px solid #ccc;border-radius: 20px;height: 45px;margin-left: 7%%;margin-right: 10px;font-size: 1.1rem;width: 80%%;background-color: rgba(255, 255, 255, 0.4);}")
|
||||
fmt.Fprintf(w, ".searchBtn {padding: 10px 20px;border: none;background-image: linear-gradient(to right, pink, deeppink);color: white;margin-left: -20%%;font-size: 1.1rem;border-radius: 20px;width: 128%%;height: 60px;cursor: pointer;transition: all 0.3s ease;}")
|
||||
fmt.Fprintf(w, "@media (max-width: 768px) {.search-form {flex-direction: column;align-items: flex-start;text-align: center;}.songContainer,.singerContainer,.searchContainer {display: block;margin: 4px 12%% 0 auto;width: 80%%;}.songInput {margin: 0;width: 100%%;}.artistInput {margin: 0;width: 100%%;}.searchBtn {margin: 0;width: 106%%;height: 40px;}}")
|
||||
fmt.Fprintf(w, ".songInput:hover,.artistInput:hover,.songInput:focus,.artistInput:focus {outline: none;border: 2px solid deeppink;}.song-item:hover,.searchBtn:hover {box-shadow: 0 4px 8px rgba(255, 182, 193, 0.7);transform: translateY(-5px);}")
|
||||
fmt.Fprintf(w, ".getError,.no-enter,.no-result {width: 80%%;margin: 4px auto;padding: 20px;background-color: rgba(255, 0, 38, 0.4);text-align: center;border: 1px solid rgb(255, 75, 75);border-radius: 15px;color: rgb(205, 0, 0);}")
|
||||
fmt.Fprintf(w, ".loading {width: 80%%;margin: 4px auto;padding: 20px;text-align: center;color: deeppink;font-size: 45px;animation: spin 2s linear infinite;}@keyframes spin {from {transform: rotate(0deg);}to {transform: rotate(360deg);}}")
|
||||
fmt.Fprintf(w, ".result {width: 85%%;margin: 4px auto;}.result-title {font-size: 24px;font-weight: bold;}.song-item {background-color: rgba(255, 255, 255, 0.4);border: 2px solid deeppink;border-radius: 15px;transition: all 0.3s ease;padding: 10px;}")
|
||||
fmt.Fprintf(w, ".song-title-container {display: flex;align-items: center;}.song-name {font-size: 18px;font-weight: bold;}.cache {width: 45px;background-color: deepskyblue;color: #000;font-size: 14px;text-align: center;border-radius: 15px;}")
|
||||
fmt.Fprintf(w, ".singer-name-icon,.lyric-icon {font-size: 18px;color: deeppink;}.singer-name,.lyric {font-size: 16px;color: #4f596b;}.playBtn,.pauseBtn {border: none;background-image: linear-gradient(to right, skyblue, deepskyblue);border-radius: 5px;padding: 5px 10px;font-size: 15px;transition: all 0.3s ease;}.playBtn:hover,.pauseBtn:hover {box-shadow: 0 4px 8px rgba(182, 232, 255, 0.7);transform: translateY(-5px);}")
|
||||
fmt.Fprintf(w, ".audio-player-container {display: flex;align-items: center;}.audio {display: none;}.progress-bar {width: 70%%;margin: 4px auto;padding: 8px;background-color: rgba(255, 255, 255, 0.4);border: 1px solid deeppink;border-radius: 5px;display: flex;justify-content: space-between;align-items: center;}.progress {width: 0;height: 10px;background-color: deeppink;}.time {margin-left: auto;}")
|
||||
fmt.Fprintf(w, ".stream_pcm {width: 80%%;margin: 4px auto;padding: 20px;background-color: rgba(135, 206, 235, 0.4);border: 1px solid skyblue;border-radius: 15px;}.stream_pcm_title {color: rgb(0, 100, 100);font-size: 16px;font-weight: bold;}.stream_pcm_content {margin-top: 10px;font-size: 14px;color: #555;}")
|
||||
fmt.Fprintf(w, ".stream_pcm_type_title,.stream_pcm_content_num_title,.stream_pcm_content_time_title,.stream_pcm_response_title {font-weight: bold;}.stream_pcm_response_value {width: 100%%;background-color: rgba(255, 255, 255, 0.4);display: block;white-space: pre-wrap;overflow: auto;height: 200px;border-radius: 6px;padding: 10px;}")
|
||||
fmt.Fprintf(w, ".info {width: 80%%;margin: 4px auto;padding: 20px;text-align: center;color: #4f596b;}.info strong {font-weight: bolder;color: #000;}.showStreamPcmBtnContainer,.hideStreamPcmBtnContainer {margin: 0 auto;width: 80%%;display: flex;justify-content: center;}")
|
||||
fmt.Fprintf(w, ".showStreamPcmBtn {border: 1px solid deepskyblue;color: deepskyblue;}.showStreamPcmBtn:hover {background-color: deepskyblue;color: #000;}.hideStreamPcmBtn {border: 1px solid deeppink;color: deeppink;}.hideStreamPcmBtn:hover {background-color: deeppink;color: #000;}.showStreamPcmBtn,.hideStreamPcmBtn {background: none;padding: 2px 6px;}")
|
||||
fmt.Fprintf(w, ".footer {text-align: center;margin: 10px auto;justify-content: center;align-items: center;width: 80%%;border-top: 1px solid #ccc;}.language-select {background-color: rgba(255, 255, 255, 0.4);border: 1px solid #ccc;text-align: center;width: 120px;height: 40px;border-radius: 10px;margin: 10px auto;}")
|
||||
fmt.Fprintf(w, ".language-select:focus,.language-select:hover {outline: none;border: 1px solid deeppink;}.copyright {font-size: 14px;color: #4f596b;}")
|
||||
fmt.Fprintf(w, "</style></head>")
|
||||
// Build body
|
||||
fmt.Fprintf(w, "<body><div class=\"container\"><div id=\"title\" class=\"title\"></div><div id=\"description\" class=\"description\"></div>")
|
||||
fmt.Fprintf(w, "<div class=\"search-form\"><div class=\"songContainer\"><div class=\"song\"><input type=\"text\" id=\"songInput\" class=\"songInput\" autocomplete=\"off\"></div></div>")
|
||||
fmt.Fprintf(w, "<div class=\"singerContainer\"><div class=\"singer\"><input type=\"text\" id=\"artistInput\" class=\"artistInput\" autocomplete=\"off\"></div></div><div class=\"searchContainer\"><div class=\"search\"><button type=\"button\" id=\"searchBtn\" class=\"searchBtn\"></button></div></div></div>")
|
||||
fmt.Fprintf(w, "<div class=\"getError\" id=\"getError\"></div><div class=\"no-enter\" id=\"noEnter\"></div><div class=\"no-result\" id=\"noResult\"></div><div class=\"loading\" id=\"loading\"><i class=\"fa fa-circle-o-notch\"></i></div>")
|
||||
fmt.Fprintf(w, "<div class=\"result\" id=\"result\"><div class=\"result-title\" id=\"resultTitle\"></div><div class=\"result-list\"><div class=\"song-item\"><div class=\"song-title-container\"><div class=\"song-name\" id=\"songName\"></div><div class=\"cache\" id=\"cache\"></div></div><div class=\"singer-name\"><span class=\"singer-name-icon\" id=\"singerNameIcon\"><i class=\"fa fa-user-o\"></i></span><span class=\"singer-name-value\" id=\"singerName\"></span></div><div class=\"lyric\"><span class=\"lyric-icon\" id=\"lyricIcon\"><i class=\"fa fa-file-text-o\"></i></span><span class=\"lyric-value\" id=\"noLyric\"></span><span class=\"lyric-value\" id=\"lyric\"></span></div><div class=\"audio-player-container\"><button type=\"button\" class=\"playBtn\" id=\"playBtn\"></button><button type=\"button\" class=\"pauseBtn\" id=\"pauseBtn\"></button><audio class=\"audio\" id=\"audio\"></audio><div class=\"progress-bar\"><div class=\"progress\" id=\"progress\"></div><div class=\"time\" id=\"time\"></div></div></div></div></div></div>")
|
||||
fmt.Fprintf(w, "<div class=\"stream_pcm\" id=\"streamPcm\"><div class=\"stream_pcm_title\" id=\"streamPcmTitle\"></div><div class=\"stream_pcm_content\"><div class=\"stream_pcm_type\"><span class=\"stream_pcm_type_title\" id=\"streamPcmTypeTitle\"></span><span class=\"stream_pcm_type_value\" id=\"streamPcmTypeValue\"></span></div><div class=\"stream_pcm_content_num\"><span class=\"stream_pcm_content_num_title\" id=\"streamPcmContentNumTitle\"></span><span class=\"stream_pcm_content_num_value\">1</span></div><div class=\"stream_pcm_content_time\"><span class=\"stream_pcm_content_time_title\" id=\"streamPcmContentTimeTitle\"></span><span class=\"stream_pcm_content_time_value\" id=\"streamPcmContentTimeValue\"></span></div><div class=\"stream_pcm_response\"><span class=\"stream_pcm_response_title\" id=\"streamPcmResponseTitle\"></span><br><span class=\"stream_pcm_response_value\" id=\"streamPcmResponseValue\"></span></div></div></div>")
|
||||
fmt.Fprintf(w, "<div class=\"info\" id=\"info\"></div><div class=\"showStreamPcmBtnContainer\" id=\"showStreamPcmBtnContainer\"><button type=\"button\" id=\"showStreamPcmBtn\" class=\"showStreamPcmBtn\"></button></div><div class=\"hideStreamPcmBtnContainer\" id=\"hideStreamPcmBtnContainer\"><button type=\"button\" id=\"hideStreamPcmBtn\" class=\"hideStreamPcmBtn\"></button></div><div class=\"footer\"><select id=\"languageSelect\" class=\"language-select\"><option value=\"zh-CN\">简体中文</option><option value=\"en\">English</option></select><div class=\"copyright\" id=\"copyright\"></div></div></div>")
|
||||
fmt.Fprintf(w, "<script>")
|
||||
// Set copyright year and read head meta tags
|
||||
fmt.Fprintf(w, "const currentYear = new Date().getFullYear();var head = document.getElementsByTagName('head')[0];")
|
||||
// language definition
|
||||
fmt.Fprintf(w, "const titles = {'zh-CN': '%s','en': '%s'};", websiteNameCN, websiteNameEN)
|
||||
fmt.Fprintf(w, "const titles2 = {'zh-CN': '%s','en': '%s'};", websiteTitleCN, websiteTitleEN)
|
||||
fmt.Fprintf(w, "const descriptions = {'zh-CN': '%s','en': '%s'};", websiteDescCN, websiteDescEN)
|
||||
fmt.Fprintf(w, "const keywords = {'zh-CN': '%s','en': '%s'};", websiteKeywordsCN, websiteKeywordsEN)
|
||||
fmt.Fprintf(w, "const songInputs = {'zh-CN': '输入歌曲名称...','en': 'Enter song name...'};")
|
||||
fmt.Fprintf(w, "const singerInputs = {'zh-CN': '歌手名称(可选)','en': 'Singer name(optional)'};")
|
||||
fmt.Fprintf(w, "const searchBtns = {'zh-CN': '<i class=\"fa fa-search\"></i> 搜索','en': '<i class=\"fa fa-search\"></i> Search'};")
|
||||
fmt.Fprintf(w, "const getErrors = {'zh-CN': '获取数据失败<br>可能是因为网络响应出错或其它原因<br>请检查您的网络并稍后再试','en': 'Failed to get data<br>It may be because of network response error or other reasons<br>Please check your network and try again later'};")
|
||||
fmt.Fprintf(w, "const noEnters = {'zh-CN': '请输入歌曲名称','en': 'Please enter song name'};")
|
||||
fmt.Fprintf(w, "const noResults = {'zh-CN': '没有找到相关歌曲','en': 'No related songs found'};")
|
||||
fmt.Fprintf(w, "const resultTitles = {'zh-CN': '<i class=\"fa fa-list-ul\"></i> 搜索结果','en': '<i class=\"fa fa-list-ul\"></i> Search Result'};")
|
||||
fmt.Fprintf(w, "const caches = {'zh-CN': '缓存','en': 'Cache'};")
|
||||
fmt.Fprintf(w, "const noLyrics = {'zh-CN': '暂无歌词','en': 'No lyrics'};")
|
||||
fmt.Fprintf(w, "const playBtns = {'zh-CN': '<i class=\"fa fa-play-circle-o\"></i> 播放','en': '<i class=\"fa fa-play-circle-o\"></i> Play'};")
|
||||
fmt.Fprintf(w, "const pauseBtns = {'zh-CN': '<i class=\"fa fa-pause-circle-o\"></i> 暂停','en': '<i class=\"fa fa-pause-circle-o\"></i> Pause'};")
|
||||
fmt.Fprintf(w, "const streamPcmTitle = {'zh-CN': '<i class=\"fa fa-info-circle\"></i> stream_pcm 响应讯息:','en': '<i class=\"fa fa-info-circle\"></i> stream_pcm response: '};")
|
||||
fmt.Fprintf(w, "const streamPcmTypeTitle = {'zh-CN': '响应类型:','en': 'Response type: '};")
|
||||
fmt.Fprintf(w, "const streamPcmTypeValue = {'zh-CN': '单曲播放讯息','en': 'Single song playback message'};")
|
||||
fmt.Fprintf(w, "const streamPcmContentNumTitle = {'zh-CN': '响应数量:','en': 'Response number: '};")
|
||||
fmt.Fprintf(w, "const streamPcmContentTimeTitle = {'zh-CN': '响应时间:','en': 'Response time: '};")
|
||||
fmt.Fprintf(w, "const streamPcmResponseTitle = {'zh-CN': '完整响应:','en': 'Full response: '};")
|
||||
fmt.Fprintf(w, "const info = {'zh-CN': '<strong><i class=\"fa fa-info-circle\"></i> 系统讯息</strong><br>嵌入式音乐搜索服务器 | Ver %s<br>支持云端/本地音乐搜索,支持多种音乐格式播放,支持多种语言<br>基于聚合API,支持本地音乐缓存','en': '<strong><i class=\"fa fa-info-circle\"></i> System Information</strong><br>Embedded Music Search Server | Ver %s<br>Support cloud/local music search, support various music formats, support various languages<br>Based on aggregation API, support local music cache'};", websiteVersion, websiteVersion)
|
||||
fmt.Fprintf(w, "const showStreamPcmBtns = {'zh-CN': '<i class=\"fa fa-eye\"></i> 显示 stream_pcm 响应','en': '<i class=\"fa fa-eye\"></i> Show stream_pcm response'};")
|
||||
fmt.Fprintf(w, "const hideStreamPcmBtns = {'zh-CN': '<i class=\"fa fa-eye-slash\"></i> 隐藏 stream_pcm 响应','en': '<i class=\"fa fa-eye-slash\"></i> Hide stream_pcm response'};")
|
||||
// Get browser language, set HTML lang attribute and Set default language
|
||||
fmt.Fprintf(w, "const browserLang = navigator.language || 'en';document.documentElement.lang = browserLang || \"en\";document.getElementById('languageSelect').value = browserLang;")
|
||||
// Initialize title
|
||||
fmt.Fprintf(w, "document.title = (titles[browserLang] || '%s') + \" - \" + (titles2[browserLang] || '%s');", websiteNameEN, websiteTitleEN)
|
||||
// Initialize meta description
|
||||
fmt.Fprintf(w, "var existingMetaDescription = document.querySelector('meta[name=\"description\"]');if (existingMetaDescription) {existingMetaDescription.content = descriptions[browserLang] || '%s';} else {var metaDescription = document.createElement('meta');metaDescription.name = 'description';metaDescription.content = descriptions[browserLang] || '%s';head.appendChild(metaDescription);};", websiteDescEN, websiteDescEN)
|
||||
// Initialize meta keywords
|
||||
fmt.Fprintf(w, "var existingMetaKeywords = document.querySelector('meta[name=\"keywords\"]');if (existingMetaKeywords) {existingMetaKeywords.content = keywords[browserLang] || '%s';} else {var metaKeywords = document.createElement('meta');metaKeywords.name = 'keywords';metaKeywords.content = keywords[browserLang] || '%s';head.appendChild(metaKeywords);};", websiteKeywordsEN, websiteKeywordsEN)
|
||||
// Set default language content
|
||||
fmt.Fprintf(w, "document.getElementById('title').innerHTML = titles[browserLang] || '%s';", websiteNameEN)
|
||||
fmt.Fprintf(w, "document.getElementById('copyright').innerHTML = \"©\" + currentYear + \" \" + (titles[browserLang] || '%s');", websiteNameEN)
|
||||
fmt.Fprintf(w, "document.getElementById('description').innerHTML = descriptions[browserLang] || '%s';", websiteDescEN)
|
||||
fmt.Fprintf(w, "document.getElementById('songInput').placeholder = songInputs[browserLang] || 'Enter song name...';")
|
||||
fmt.Fprintf(w, "document.getElementById('artistInput').placeholder = singerInputs[browserLang] || 'Singer name(optional)';")
|
||||
fmt.Fprintf(w, "document.getElementById('searchBtn').innerHTML = searchBtns[browserLang] || '<i class=\"fa fa-search\"></i> Search';")
|
||||
fmt.Fprintf(w, "document.getElementById('getError').innerHTML = getErrors[browserLang] || 'Failed to get data<br>It may be because of network response error or other reasons<br>Please check your network and try again later';")
|
||||
fmt.Fprintf(w, "document.getElementById('noEnter').innerHTML = noEnters[browserLang] || 'Please enter song name';")
|
||||
fmt.Fprintf(w, "document.getElementById('noResult').innerHTML = noResults[browserLang] || 'No related songs found';")
|
||||
fmt.Fprintf(w, "document.getElementById('resultTitle').innerHTML = resultTitles[browserLang] || '<i class=\"fa fa-list-ul\"></i> Search Result';")
|
||||
fmt.Fprintf(w, "document.getElementById('cache').innerHTML = caches[browserLang] || 'Cache';")
|
||||
fmt.Fprintf(w, "document.getElementById('noLyric').innerHTML = noLyrics[browserLang] || 'No lyrics';")
|
||||
fmt.Fprintf(w, "document.getElementById('playBtn').innerHTML = playBtns[browserLang] || '<i class=\"fa fa-play-circle-o\"></i> Play';")
|
||||
fmt.Fprintf(w, "document.getElementById('pauseBtn').innerHTML = pauseBtns[browserLang] || '<i class=\"fa fa-pause-circle-o\"></i> Pause';")
|
||||
fmt.Fprintf(w, "document.getElementById('streamPcmTitle').innerHTML = streamPcmTitle[browserLang] || '<i class=\"fa fa-info-circle\"></i> stream_pcm response: ';")
|
||||
fmt.Fprintf(w, "document.getElementById('streamPcmTypeTitle').innerHTML = streamPcmTypeTitle[browserLang] || 'Response type: ';")
|
||||
fmt.Fprintf(w, "document.getElementById('streamPcmTypeValue').innerHTML = streamPcmTypeValue[browserLang] || 'Single song playback message';")
|
||||
fmt.Fprintf(w, "document.getElementById('streamPcmContentNumTitle').innerHTML = streamPcmContentNumTitle[browserLang] || 'Response number: ';")
|
||||
fmt.Fprintf(w, "document.getElementById('streamPcmContentTimeTitle').innerHTML = streamPcmContentTimeTitle[browserLang] || 'Response time: ';")
|
||||
fmt.Fprintf(w, "document.getElementById('streamPcmResponseTitle').innerHTML = streamPcmResponseTitle[browserLang] || 'Full response: ';")
|
||||
fmt.Fprintf(w, "document.getElementById('info').innerHTML = info[browserLang] || '<strong><i class=\"fa fa-info-circle\"></i> System Information</strong><br>Embedded Music Search Server | Ver %s<br>Support cloud/local music search, support various music formats, support various languages<br>Based on aggregation API, support local music cache';", websiteVersion)
|
||||
fmt.Fprintf(w, "document.getElementById('showStreamPcmBtn').innerHTML = showStreamPcmBtns[browserLang] || '<i class=\"fa fa-eye\"></i> Show stream_pcm response';")
|
||||
fmt.Fprintf(w, "document.getElementById('hideStreamPcmBtn').innerHTML = hideStreamPcmBtns[browserLang] || '<i class=\"fa fa-eye-slash\"></i> Hide stream_pcm response';")
|
||||
// Listen language selection change and update title
|
||||
fmt.Fprintf(w, "document.getElementById('languageSelect').addEventListener('change', function () {")
|
||||
fmt.Fprintf(w, "const selectedLang = this.value;")
|
||||
// Set HTML lang attribute
|
||||
fmt.Fprintf(w, "document.documentElement.lang = selectedLang || \"en\";")
|
||||
// Set title
|
||||
fmt.Fprintf(w, "document.title = (titles[selectedLang] || '%s') + \" - \" + (titles2[selectedLang] || '%s');", websiteNameEN, websiteTitleEN)
|
||||
// Initialize meta description
|
||||
fmt.Fprintf(w, "var existingMetaDescription = document.querySelector('meta[name=\"description\"]');if (existingMetaDescription) {existingMetaDescription.content = descriptions[selectedLang] || '%s';} else {var metaDescription = document.createElement('meta');metaDescription.name = 'description';metaDescription.content = descriptions[selectedLang] || '%s';head.appendChild(metaDescription);};", websiteDescEN, websiteDescEN)
|
||||
// Initialize meta keywords
|
||||
fmt.Fprintf(w, "var existingMetaKeywords = document.querySelector('meta[name=\"keywords\"]');if (existingMetaKeywords) {existingMetaKeywords.content = keywords[selectedLang] || '%s';} else {var metaKeywords = document.createElement('meta');metaKeywords.name = 'keywords';metaKeywords.content = keywords[selectedLang] || '%s';head.appendChild(metaKeywords);};", websiteKeywordsEN, websiteKeywordsEN)
|
||||
// Set default language content
|
||||
fmt.Fprintf(w, "document.getElementById('title').innerHTML = titles[selectedLang] || '%s';", websiteNameEN)
|
||||
fmt.Fprintf(w, "document.getElementById('copyright').innerHTML = \"©\" + currentYear + \" \" + (titles[selectedLang] || '%s');", websiteNameEN)
|
||||
fmt.Fprintf(w, "document.getElementById('description').innerHTML = descriptions[selectedLang] || '%s';", websiteDescEN)
|
||||
fmt.Fprintf(w, "document.getElementById('songInput').placeholder = songInputs[selectedLang] || 'Enter song name...';")
|
||||
fmt.Fprintf(w, "document.getElementById('artistInput').placeholder = singerInputs[selectedLang] || 'Singer name(optional)';")
|
||||
fmt.Fprintf(w, "document.getElementById('searchBtn').innerHTML = searchBtns[selectedLang] || '<i class=\"fa fa-search\"></i> Search';")
|
||||
fmt.Fprintf(w, "document.getElementById('getError').innerHTML = getErrors[selectedLang] || 'Failed to get data<br>It may be because of network response error or other reasons<br>Please check your network and try again later';")
|
||||
fmt.Fprintf(w, "document.getElementById('noEnter').innerHTML = noEnters[selectedLang] || 'Please enter song name';")
|
||||
fmt.Fprintf(w, "document.getElementById('noResult').innerHTML = noResults[selectedLang] || 'No related songs found';")
|
||||
fmt.Fprintf(w, "document.getElementById('resultTitle').innerHTML = resultTitles[selectedLang] || '<i class=\"fa fa-list-ul\"></i> Search Result';")
|
||||
fmt.Fprintf(w, "document.getElementById('cache').innerHTML = caches[selectedLang] || 'Cache';")
|
||||
fmt.Fprintf(w, "document.getElementById('noLyric').innerHTML = noLyrics[selectedLang] || 'No lyrics';")
|
||||
fmt.Fprintf(w, "document.getElementById('playBtn').innerHTML = playBtns[selectedLang] || '<i class=\"fa fa-play-circle-o\"></i> Play';")
|
||||
fmt.Fprintf(w, "document.getElementById('pauseBtn').innerHTML = pauseBtns[selectedLang] || '<i class=\"fa fa-pause-circle-o\"></i> Pause';")
|
||||
fmt.Fprintf(w, "document.getElementById('streamPcmTitle').innerHTML = streamPcmTitle[selectedLang] || '<i class=\"fa fa-info-circle\"></i> stream_pcm response: ';")
|
||||
fmt.Fprintf(w, "document.getElementById('streamPcmTypeTitle').innerHTML = streamPcmTypeTitle[selectedLang] || 'Response type: ';")
|
||||
fmt.Fprintf(w, "document.getElementById('streamPcmTypeValue').innerHTML = streamPcmTypeValue[selectedLang] || 'Single song playback message';")
|
||||
fmt.Fprintf(w, "document.getElementById('streamPcmContentNumTitle').innerHTML = streamPcmContentNumTitle[selectedLang] || 'Response number: ';")
|
||||
fmt.Fprintf(w, "document.getElementById('streamPcmContentTimeTitle').innerHTML = streamPcmContentTimeTitle[selectedLang] || 'Response time: ';")
|
||||
fmt.Fprintf(w, "document.getElementById('streamPcmResponseTitle').innerHTML = streamPcmResponseTitle[selectedLang] || 'Full response: ';")
|
||||
fmt.Fprintf(w, "document.getElementById('info').innerHTML = info[selectedLang] || '<strong><i class=\"fa fa-info-circle\"></i> System Information</strong><br>Embedded Music Search Server | Ver %s<br>Support cloud/local music search, support various music formats, support various languages<br>Based on aggregation API, support local music cache';", websiteVersion)
|
||||
fmt.Fprintf(w, "document.getElementById('showStreamPcmBtn').innerHTML = showStreamPcmBtns[selectedLang] || '<i class=\"fa fa-eye\"></i> Show stream_pcm response';")
|
||||
fmt.Fprintf(w, "document.getElementById('hideStreamPcmBtn').innerHTML = hideStreamPcmBtns[selectedLang] || '<i class=\"fa fa-eye-slash\"></i> Hide stream_pcm response';")
|
||||
fmt.Fprintf(w, "});")
|
||||
// Getting Elements
|
||||
fmt.Fprintf(w, "const songInput = document.getElementById('songInput');")
|
||||
fmt.Fprintf(w, "const artistInput = document.getElementById('artistInput');")
|
||||
fmt.Fprintf(w, "const searchBtn = document.getElementById('searchBtn');")
|
||||
fmt.Fprintf(w, "const getError = document.getElementById('getError');")
|
||||
fmt.Fprintf(w, "const noEnter = document.getElementById('noEnter');")
|
||||
fmt.Fprintf(w, "const noResult = document.getElementById('noResult');")
|
||||
fmt.Fprintf(w, "const loading = document.getElementById('loading');")
|
||||
fmt.Fprintf(w, "const result = document.getElementById('result');")
|
||||
fmt.Fprintf(w, "const songName = document.getElementById('songName');")
|
||||
fmt.Fprintf(w, "const cache = document.getElementById('cache');")
|
||||
fmt.Fprintf(w, "const singerName = document.getElementById('singerName');")
|
||||
fmt.Fprintf(w, "const noLyric = document.getElementById('noLyric');")
|
||||
fmt.Fprintf(w, "const playBtn = document.getElementById('playBtn');")
|
||||
fmt.Fprintf(w, "const pauseBtn = document.getElementById('pauseBtn');")
|
||||
fmt.Fprintf(w, "const lyric = document.getElementById('lyric');")
|
||||
fmt.Fprintf(w, "const streamPcm = document.getElementById('streamPcm');")
|
||||
fmt.Fprintf(w, "const streamPcmContentTimeValue = document.getElementById('streamPcmContentTimeValue');")
|
||||
fmt.Fprintf(w, "const streamPcmResponseValue = document.getElementById('streamPcmResponseValue');")
|
||||
fmt.Fprintf(w, "const showStreamPcmBtn = document.getElementById('showStreamPcmBtn');")
|
||||
fmt.Fprintf(w, "const hideStreamPcmBtn = document.getElementById('hideStreamPcmBtn');")
|
||||
// Hide content that should not be displayed before searching
|
||||
fmt.Fprintf(w, "getError.style.display = 'none';")
|
||||
fmt.Fprintf(w, "noEnter.style.display = 'none';")
|
||||
fmt.Fprintf(w, "noResult.style.display = 'none';")
|
||||
fmt.Fprintf(w, "loading.style.display = 'none';")
|
||||
fmt.Fprintf(w, "result.style.display = 'none';")
|
||||
fmt.Fprintf(w, "cache.style.display = 'none';")
|
||||
fmt.Fprintf(w, "noLyric.style.display = 'none';")
|
||||
fmt.Fprintf(w, "playBtn.style.display = 'none';")
|
||||
fmt.Fprintf(w, "pauseBtn.style.display = 'none';")
|
||||
fmt.Fprintf(w, "streamPcm.style.display = 'none';")
|
||||
fmt.Fprintf(w, "showStreamPcmBtn.style.display = 'none';")
|
||||
fmt.Fprintf(w, "hideStreamPcmBtn.style.display = 'none';")
|
||||
// Empty song name processing
|
||||
fmt.Fprintf(w, "searchBtn.addEventListener('click', function () {if (songInput.value.trim() === '') {noEnter.style.display = 'block';} else {noEnter.style.display = 'none';search();}});")
|
||||
fmt.Fprintf(w, "songInput.addEventListener('keydown', function (event) {if (event.key === 'Enter') {if (songInput.value.trim() === '') {noEnter.style.display = 'block';} else {noEnter.style.display = 'none';search();}}});")
|
||||
fmt.Fprintf(w, "artistInput.addEventListener('keydown', function (event) {if (event.key === 'Enter') {if (songInput.value.trim() === '') {noEnter.style.display = 'block';} else {noEnter.style.display = 'none';search();}}});")
|
||||
// Searching for songs
|
||||
fmt.Fprintf(w, "function search() {")
|
||||
// Show loading
|
||||
fmt.Fprintf(w, "loading.style.display = 'block';")
|
||||
// Hide error
|
||||
fmt.Fprintf(w, "getError.style.display = 'none';")
|
||||
// Build request URL, urlencode song name and artist name
|
||||
fmt.Fprintf(w, "const song = encodeURIComponent(songInput.value);")
|
||||
fmt.Fprintf(w, "const artist = encodeURIComponent(artistInput.value);")
|
||||
fmt.Fprintf(w, "const requestUrl = `/stream_pcm?song=${song}&artist=${artist}`;")
|
||||
// Send request to server
|
||||
fmt.Fprintf(w, "fetch(requestUrl)")
|
||||
fmt.Fprintf(w, ".then(response => {if (!response.ok) {getError.style.display = 'block';throw new Error('Network response was not ok');}return response.json();})")
|
||||
fmt.Fprintf(w, ".then(data => {")
|
||||
// Fill in all the obtained content into streamPcmResponseValue
|
||||
fmt.Fprintf(w, "streamPcmResponseValue.innerHTML = JSON.stringify(data, null, 2);")
|
||||
// Get the current time and fill in streamPcmCntentTimeValue
|
||||
fmt.Fprintf(w, "streamPcmContentTimeValue.innerHTML = new Date().toISOString();")
|
||||
// Display result
|
||||
fmt.Fprintf(w, "result.style.display = 'block';")
|
||||
// Display Play button
|
||||
fmt.Fprintf(w, "playBtn.style.display = 'block';")
|
||||
// Display showStreamPcmBtn
|
||||
fmt.Fprintf(w, "showStreamPcmBtn.style.display = 'block';")
|
||||
// Hide hideStreamPcmBtn
|
||||
fmt.Fprintf(w, "hideStreamPcmBtn.style.display = 'none';")
|
||||
// Fill the title into the songName field
|
||||
fmt.Fprintf(w, "if (data.title === \"\") {noResult.style.display = 'block';result.style.display = 'none';} else {noResult.style.display = 'none';songName.textContent = data.title;};")
|
||||
// Fill the artist into the singerName field
|
||||
fmt.Fprintf(w, "singerName.textContent = data.artist;")
|
||||
// Set parsed lyrics to an empty array
|
||||
fmt.Fprintf(w, "let parsedLyrics = [];")
|
||||
// Check if the link 'lyric_url' is empty
|
||||
fmt.Fprintf(w, "if (data.lyric_url) {")
|
||||
// Visit lyric_url
|
||||
fmt.Fprintf(w, "fetch(data.lyric_url)")
|
||||
fmt.Fprintf(w, ".then(response => {if (!response.ok) {throw new Error('Lyrics request error');}return response.text();})")
|
||||
fmt.Fprintf(w, ".then(lyricText => {")
|
||||
// Show lyric
|
||||
fmt.Fprintf(w, "lyric.style.display = 'block';")
|
||||
// Parse lyrics
|
||||
fmt.Fprintf(w, "parsedLyrics = parseLyrics(lyricText);")
|
||||
fmt.Fprintf(w, "})")
|
||||
fmt.Fprintf(w, ".catch(error => {")
|
||||
// Show noLyric
|
||||
fmt.Fprintf(w, "noLyric.style.display = 'block';")
|
||||
// Hide lyric
|
||||
fmt.Fprintf(w, "lyric.style.display = 'none';")
|
||||
fmt.Fprintf(w, "});")
|
||||
fmt.Fprintf(w, "} else {")
|
||||
// If lyric_url is empty, display noLyric
|
||||
fmt.Fprintf(w, "noLyric.style.display = 'block';")
|
||||
// Hide lyric
|
||||
fmt.Fprintf(w, "lyric.style.display = 'none';")
|
||||
fmt.Fprintf(w, "};")
|
||||
// Check cache
|
||||
fmt.Fprintf(w, "if (data.from_cache === true) {")
|
||||
// If the song is obtained from cache, display cache
|
||||
fmt.Fprintf(w, "cache.style.display = 'block';")
|
||||
fmt.Fprintf(w, "} else {")
|
||||
// If the song is not obtained from cache, hide cache
|
||||
fmt.Fprintf(w, "cache.style.display = 'none';")
|
||||
fmt.Fprintf(w, "};")
|
||||
// Create audio player
|
||||
fmt.Fprintf(w, "const audioPlayer = document.getElementById('audio');")
|
||||
fmt.Fprintf(w, "const customProgress = document.getElementById('progress');")
|
||||
fmt.Fprintf(w, "const timeDisplay = document.getElementById('time');")
|
||||
// Set audio source
|
||||
fmt.Fprintf(w, "audioPlayer.src = data.audio_full_url;")
|
||||
fmt.Fprintf(w, "audio.addEventListener('timeupdate', function () {")
|
||||
fmt.Fprintf(w, "const currentTime = formatTime(audioPlayer.currentTime);")
|
||||
fmt.Fprintf(w, "const duration = formatTime(audioPlayer.duration);")
|
||||
fmt.Fprintf(w, "timeDisplay.textContent = `${currentTime}/${duration}`;")
|
||||
fmt.Fprintf(w, "const progress = (audioPlayer.currentTime / audioPlayer.duration) * 100;")
|
||||
fmt.Fprintf(w, "customProgress.style.width = progress + '%%';")
|
||||
// Find current lyric
|
||||
fmt.Fprintf(w, "let currentLyric = parsedLyrics.find((lyric, index, arr) =>")
|
||||
fmt.Fprintf(w, "lyric.timestamp > audioPlayer.currentTime && (index === 0 || arr[index - 1].timestamp <= audioPlayer.currentTime));")
|
||||
fmt.Fprintf(w, "lyric.textContent = currentLyric ? currentLyric.lyricLine : '';")
|
||||
fmt.Fprintf(w, "});")
|
||||
// Save current time before playing audio
|
||||
fmt.Fprintf(w, "let savedCurrentTime = 0;")
|
||||
// PlayBtn click event
|
||||
fmt.Fprintf(w, "playBtn.addEventListener('click', function () {")
|
||||
// Save current time
|
||||
fmt.Fprintf(w, "audioPlayer.currentTime = savedCurrentTime;")
|
||||
// Play audio
|
||||
fmt.Fprintf(w, "audioPlayer.play();")
|
||||
// Hide playBtn
|
||||
fmt.Fprintf(w, "playBtn.style.display = 'none';")
|
||||
// Show pauseBtn
|
||||
fmt.Fprintf(w, "pauseBtn.style.display = 'block';")
|
||||
fmt.Fprintf(w, "});")
|
||||
// PauseBtn click event
|
||||
fmt.Fprintf(w, "pauseBtn.addEventListener('click', function () {")
|
||||
// Save current time
|
||||
fmt.Fprintf(w, "savedCurrentTime = audioPlayer.currentTime;")
|
||||
// Pause audio
|
||||
fmt.Fprintf(w, "audioPlayer.pause();")
|
||||
// Hide pauseBtn
|
||||
fmt.Fprintf(w, "pauseBtn.style.display = 'none';")
|
||||
// Show playBtn
|
||||
fmt.Fprintf(w, "playBtn.style.display = 'block';")
|
||||
fmt.Fprintf(w, "});")
|
||||
fmt.Fprintf(w, "})")
|
||||
fmt.Fprintf(w, ".catch(error => {")
|
||||
fmt.Fprintf(w, "console.error('Error requesting song information:', error);")
|
||||
// When there is an error in the request, you can also consider displaying a prompt message or other content
|
||||
fmt.Fprintf(w, "getError.style.display = 'block';")
|
||||
fmt.Fprintf(w, "})")
|
||||
fmt.Fprintf(w, ".finally(() => {")
|
||||
// Regardless of the request result, the loading display should be turned off in the end
|
||||
fmt.Fprintf(w, "loading.style.display = 'none';")
|
||||
fmt.Fprintf(w, "});};")
|
||||
// Format time
|
||||
fmt.Fprintf(w, "function formatTime(seconds) {const minutes = Math.floor(seconds / 60);const secondsRemainder = Math.floor(seconds %% 60);return minutes.toString().padStart(2, '0') + ':' +secondsRemainder.toString().padStart(2, '0');};")
|
||||
// Function to parse lyrics
|
||||
fmt.Fprintf(w, "function parseLyrics(lyricText) {const lines = lyricText.split('\\n');const lyrics = [];for (let line of lines) {const match = line.match(/\\[(\\d{2}:\\d{2})(?:\\.\\d{2})?\\](.*)/);if (match) {const timestamp = match[1]; const lyricLine = match[2].trim();const [minutes, seconds] = timestamp.split(':');const timeInSeconds = (parseInt(minutes) * 60) + parseInt(seconds);lyrics.push({ timestamp: timeInSeconds, lyricLine });}}return lyrics;};")
|
||||
// Show stream_pcm response
|
||||
fmt.Fprintf(w, "showStreamPcmBtn.addEventListener('click', function () {streamPcm.style.display = 'block';showStreamPcmBtn.style.display = 'none';hideStreamPcmBtn.style.display = 'block';});")
|
||||
// Hide stream_pcm response
|
||||
fmt.Fprintf(w, "hideStreamPcmBtn.addEventListener('click', function () {streamPcm.style.display = 'none';showStreamPcmBtn.style.display = 'block';hideStreamPcmBtn.style.display = 'none';});")
|
||||
fmt.Fprintf(w, "</script></body></html>")
|
||||
fmt.Printf("[Web Access] Return default index pages\n")
|
||||
}
|
||||
134
main.go
Executable file
134
main.go
Executable file
@@ -0,0 +1,134 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/joho/godotenv"
|
||||
)
|
||||
|
||||
const (
|
||||
TAG = "MeowEmbeddedMusicServer"
|
||||
)
|
||||
|
||||
func main() {
|
||||
err := godotenv.Load()
|
||||
if err != nil {
|
||||
fmt.Printf("[Warning] %s Loading .env file failed: %v\nUse the default configuration instead.\n", TAG, err)
|
||||
}
|
||||
|
||||
port := os.Getenv("PORT")
|
||||
if port == "" {
|
||||
fmt.Printf("[Warning] %s PORT environment variable not set\nUse the default port 2233 instead.\n", TAG)
|
||||
port = "2233"
|
||||
}
|
||||
|
||||
// Initialize user store
|
||||
InitUserStore()
|
||||
|
||||
// Initialize playlist manager
|
||||
InitPlaylistManager()
|
||||
|
||||
// Initialize device manager
|
||||
GetDeviceManager()
|
||||
|
||||
// Register handlers
|
||||
http.HandleFunc("/", indexHandler)
|
||||
http.HandleFunc("/stream_pcm", apiHandler)
|
||||
http.HandleFunc("/stream_live", streamLiveHandler) // 实时流式转码,边下载边播放
|
||||
http.HandleFunc("/api/search", HandleSearch) // Search API
|
||||
|
||||
// Legacy favorite API (backward compatible)
|
||||
http.HandleFunc("/api/favorite/add", HandleAddToFavorite)
|
||||
http.HandleFunc("/api/favorite/remove", HandleRemoveFromFavorite)
|
||||
http.HandleFunc("/api/favorite/list", HandleGetFavorites)
|
||||
http.HandleFunc("/api/favorite/check", HandleCheckFavorite)
|
||||
|
||||
// User authentication API
|
||||
http.HandleFunc("/api/auth/register", HandleRegister)
|
||||
http.HandleFunc("/api/auth/login", HandleLogin)
|
||||
http.HandleFunc("/api/auth/logout", HandleLogout)
|
||||
http.HandleFunc("/api/auth/me", HandleGetCurrentUser)
|
||||
|
||||
// User playlist API (requires authentication)
|
||||
http.HandleFunc("/api/user/playlists", AuthMiddleware(HandleGetUserPlaylists))
|
||||
http.HandleFunc("/api/user/playlists/create", AuthMiddleware(HandleCreateUserPlaylist))
|
||||
http.HandleFunc("/api/user/playlists/add-song", AuthMiddleware(HandleAddSongToUserPlaylist))
|
||||
http.HandleFunc("/api/user/playlists/remove-song", AuthMiddleware(HandleRemoveSongFromUserPlaylist))
|
||||
http.HandleFunc("/api/user/playlists/delete", AuthMiddleware(HandleDeleteUserPlaylist))
|
||||
|
||||
// ESP32 Device management API
|
||||
http.HandleFunc("/api/device/generate-code", AuthMiddleware(GenerateBindingCodeHandler)) // 生成绑定码(需要登录)
|
||||
http.HandleFunc("/api/device/bind-direct", DirectBindDeviceHandler) // Web端直接绑定设备(需要登录)
|
||||
http.HandleFunc("/api/device/list", ListUserDevicesHandler) // 列出用户设备(需要登录)
|
||||
http.HandleFunc("/api/device/unbind", UnbindDeviceHandler) // 解绑设备(需要登录)
|
||||
http.HandleFunc("/api/esp32/bind", BindDeviceHandler) // ESP32绑定设备
|
||||
http.HandleFunc("/api/esp32/verify", VerifyDeviceHandler) // 验证设备Token
|
||||
http.HandleFunc("/api/esp32/sync", SyncDeviceHandler) // ESP32同步Token(用MAC地址)
|
||||
|
||||
// Device binding page
|
||||
http.HandleFunc("/device-bind", func(w http.ResponseWriter, r *http.Request) {
|
||||
http.ServeFile(w, r, "./theme/device-bind.html")
|
||||
})
|
||||
// 兼容用户常见的拼写错误
|
||||
http.HandleFunc("/device-bin", func(w http.ResponseWriter, r *http.Request) {
|
||||
http.Redirect(w, r, "/device-bind", http.StatusMovedPermanently)
|
||||
})
|
||||
|
||||
fmt.Printf("[Info] %s Started.\n喵波音律-音乐家园QQ交流群:865754861\n", TAG)
|
||||
fmt.Printf("[Info] Starting music server at port %s\n", port)
|
||||
|
||||
// Create a channel to listen for signals
|
||||
sigChan := make(chan os.Signal, 1)
|
||||
signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
|
||||
|
||||
// Create a server instance
|
||||
srv := &http.Server{
|
||||
Addr: ":" + port,
|
||||
ReadTimeout: 30 * time.Second,
|
||||
WriteTimeout: 0, // Disable the timeout for the response writer
|
||||
IdleTimeout: 30 * time.Minute, // Set the maximum duration for idle connections
|
||||
ReadHeaderTimeout: 10 * time.Second, // Limit the maximum duration for reading the headers of the request
|
||||
MaxHeaderBytes: 1 << 16, // Limit the maximum request header size to 64KB
|
||||
}
|
||||
|
||||
// Start the server
|
||||
go func() {
|
||||
if err := srv.ListenAndServe(); err != nil {
|
||||
fmt.Println(err)
|
||||
sigChan <- syscall.SIGINT // Send a signal to shut down the server
|
||||
}
|
||||
}()
|
||||
|
||||
// Create a channel to listen for standard input
|
||||
exitChan := make(chan struct{})
|
||||
|
||||
go func() {
|
||||
for {
|
||||
var input string
|
||||
fmt.Scanln(&input)
|
||||
if input == "exit" {
|
||||
exitChan <- struct{}{}
|
||||
return
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
// Monitor signals or exit signals from standard inputs
|
||||
select {
|
||||
case <-sigChan:
|
||||
fmt.Printf("[Info] Server is shutting down.\nGoodbye!\n")
|
||||
case <-exitChan:
|
||||
fmt.Printf("[Info] Server is shutting down.\nGoodbye!\n")
|
||||
}
|
||||
|
||||
// Shut down the server
|
||||
if err := srv.Shutdown(context.Background()); err != nil {
|
||||
fmt.Println(err)
|
||||
}
|
||||
}
|
||||
842
playlist.go
Executable file
842
playlist.go
Executable file
@@ -0,0 +1,842 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Playlist represents a user's playlist
|
||||
type Playlist struct {
|
||||
Name string `json:"name"`
|
||||
Songs []MusicItem `json:"songs"`
|
||||
}
|
||||
|
||||
// PlaylistManager manages all playlists
|
||||
type PlaylistManager struct {
|
||||
mu sync.RWMutex
|
||||
Playlists map[string]*Playlist // Legacy playlists (backward compatible)
|
||||
UserPlaylists map[string][]*UserPlaylist // key: user ID, value: user's playlists
|
||||
filePath string
|
||||
userFilePath string
|
||||
}
|
||||
|
||||
var playlistManager *PlaylistManager
|
||||
|
||||
// InitPlaylistManager initializes the playlist manager
|
||||
func InitPlaylistManager() {
|
||||
playlistManager = &PlaylistManager{
|
||||
Playlists: make(map[string]*Playlist),
|
||||
UserPlaylists: make(map[string][]*UserPlaylist),
|
||||
filePath: "./files/playlists.json",
|
||||
userFilePath: "./files/user_playlists.json",
|
||||
}
|
||||
|
||||
// Create files directory if it doesn't exist
|
||||
os.MkdirAll("./files", 0755)
|
||||
|
||||
// Load existing playlists (backward compatible)
|
||||
playlistManager.loadFromFile()
|
||||
|
||||
// Load user playlists
|
||||
playlistManager.loadUserPlaylists()
|
||||
|
||||
// Initialize "我喜欢" playlist if it doesn't exist (backward compatible)
|
||||
if _, exists := playlistManager.Playlists["favorite"]; !exists {
|
||||
playlistManager.Playlists["favorite"] = &Playlist{
|
||||
Name: "我喜欢",
|
||||
Songs: []MusicItem{},
|
||||
}
|
||||
playlistManager.saveToFile()
|
||||
}
|
||||
}
|
||||
|
||||
// loadFromFile loads playlists from JSON file
|
||||
func (pm *PlaylistManager) loadFromFile() error {
|
||||
pm.mu.Lock()
|
||||
defer pm.mu.Unlock()
|
||||
|
||||
data, err := os.ReadFile(pm.filePath)
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
return nil // File doesn't exist yet, that's ok
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
return json.Unmarshal(data, &pm.Playlists)
|
||||
}
|
||||
|
||||
// saveToFile saves playlists to JSON file
|
||||
// NOTE: Caller must hold the lock!
|
||||
func (pm *PlaylistManager) saveToFile() error {
|
||||
data, err := json.MarshalIndent(pm.Playlists, "", " ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return os.WriteFile(pm.filePath, data, 0644)
|
||||
}
|
||||
|
||||
// AddToPlaylist adds a song to a playlist
|
||||
func (pm *PlaylistManager) AddToPlaylist(playlistName string, song MusicItem) error {
|
||||
pm.mu.Lock()
|
||||
defer pm.mu.Unlock()
|
||||
|
||||
playlist, exists := pm.Playlists[playlistName]
|
||||
if !exists {
|
||||
playlist = &Playlist{
|
||||
Name: playlistName,
|
||||
Songs: []MusicItem{},
|
||||
}
|
||||
pm.Playlists[playlistName] = playlist
|
||||
}
|
||||
|
||||
// Check if song already exists in playlist
|
||||
for _, s := range playlist.Songs {
|
||||
if s.Title == song.Title && s.Artist == song.Artist {
|
||||
return fmt.Errorf("song already exists in playlist")
|
||||
}
|
||||
}
|
||||
|
||||
playlist.Songs = append(playlist.Songs, song)
|
||||
return pm.saveToFile()
|
||||
}
|
||||
|
||||
// RemoveFromPlaylist removes a song from a playlist
|
||||
func (pm *PlaylistManager) RemoveFromPlaylist(playlistName string, title, artist string) error {
|
||||
pm.mu.Lock()
|
||||
defer pm.mu.Unlock()
|
||||
|
||||
playlist, exists := pm.Playlists[playlistName]
|
||||
if !exists {
|
||||
return fmt.Errorf("playlist not found")
|
||||
}
|
||||
|
||||
for i, song := range playlist.Songs {
|
||||
if song.Title == title && song.Artist == artist {
|
||||
playlist.Songs = append(playlist.Songs[:i], playlist.Songs[i+1:]...)
|
||||
return pm.saveToFile()
|
||||
}
|
||||
}
|
||||
|
||||
return fmt.Errorf("song not found in playlist")
|
||||
}
|
||||
|
||||
// GetPlaylist returns a playlist
|
||||
func (pm *PlaylistManager) GetPlaylist(playlistName string) (*Playlist, error) {
|
||||
pm.mu.RLock()
|
||||
defer pm.mu.RUnlock()
|
||||
|
||||
playlist, exists := pm.Playlists[playlistName]
|
||||
if !exists {
|
||||
return nil, fmt.Errorf("playlist not found")
|
||||
}
|
||||
|
||||
return playlist, nil
|
||||
}
|
||||
|
||||
// HTTP Handlers
|
||||
|
||||
// HandleAddToFavorite handles adding a song to favorites (user-specific)
|
||||
func HandleAddToFavorite(w http.ResponseWriter, r *http.Request) {
|
||||
fmt.Printf("[API] Add to favorite request received from %s\n", r.RemoteAddr)
|
||||
|
||||
if r.Method != http.MethodPost {
|
||||
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
var userID string
|
||||
|
||||
// First, check for ESP32 device token (X-Device-Token header)
|
||||
deviceToken := r.Header.Get("X-Device-Token")
|
||||
if deviceToken != "" {
|
||||
dm := GetDeviceManager()
|
||||
device, err := dm.VerifyToken(deviceToken)
|
||||
if err == nil {
|
||||
userID = userStore.GetUserIDByUsername(device.Username)
|
||||
fmt.Printf("[API] ESP32 device adding favorite (user: %s, userID: %s)\n", device.Username, userID)
|
||||
}
|
||||
}
|
||||
|
||||
// If not ESP32, check for web user token (Authorization header)
|
||||
if userID == "" {
|
||||
token := r.Header.Get("Authorization")
|
||||
if token != "" {
|
||||
token = strings.TrimPrefix(token, "Bearer ")
|
||||
user, err := userStore.GetUserByToken(token)
|
||||
if err == nil {
|
||||
userID = user.ID
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
body, err := io.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
fmt.Printf("[API] Error reading body: %v\n", err)
|
||||
http.Error(w, "Error reading request body", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
defer r.Body.Close()
|
||||
|
||||
fmt.Printf("[API] Received body: %s\n", string(body))
|
||||
|
||||
var song MusicItem
|
||||
err = json.Unmarshal(body, &song)
|
||||
if err != nil {
|
||||
fmt.Printf("[API] Error parsing JSON: %v\n", err)
|
||||
http.Error(w, "Invalid JSON", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
fmt.Printf("[API] Adding to favorites: %s - %s (userID: %s)\n", song.Artist, song.Title, userID)
|
||||
|
||||
// If user is authenticated, add to user's "我喜欢" playlist
|
||||
if userID != "" {
|
||||
// Get user's "我喜欢" playlist (first playlist)
|
||||
playlists := playlistManager.GetUserPlaylists(userID)
|
||||
|
||||
// If user has no playlists, initialize them first
|
||||
if len(playlists) == 0 {
|
||||
fmt.Printf("[API] User %s has no playlists, initializing...\n", userID)
|
||||
playlistManager.InitializeUserPlaylists(userID)
|
||||
playlists = playlistManager.GetUserPlaylists(userID)
|
||||
}
|
||||
|
||||
if len(playlists) > 0 {
|
||||
favoritePlaylist := playlists[0] // "我喜欢" is always the first playlist
|
||||
err = playlistManager.AddSongToUserPlaylist(userID, favoritePlaylist.ID, song)
|
||||
if err != nil {
|
||||
if err.Error() == "song already exists in playlist" {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
json.NewEncoder(w).Encode(map[string]string{
|
||||
"status": "success",
|
||||
"message": "歌曲已在收藏列表中",
|
||||
})
|
||||
return
|
||||
}
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
} else {
|
||||
// Playlist initialization failed
|
||||
fmt.Printf("[Error] Failed to initialize playlists for user %s\n", userID)
|
||||
http.Error(w, "Failed to initialize user playlists", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
} else {
|
||||
// Fallback to global favorite playlist for anonymous users
|
||||
err = playlistManager.AddToPlaylist("favorite", song)
|
||||
if err != nil {
|
||||
if err.Error() == "song already exists in playlist" {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
json.NewEncoder(w).Encode(map[string]string{
|
||||
"status": "success",
|
||||
"message": "歌曲已在收藏列表中",
|
||||
})
|
||||
return
|
||||
}
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
fmt.Printf("[Info] Added to favorites: %s - %s\n", song.Artist, song.Title)
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
json.NewEncoder(w).Encode(map[string]string{
|
||||
"status": "success",
|
||||
"message": "收藏成功",
|
||||
})
|
||||
}
|
||||
|
||||
// HandleRemoveFromFavorite handles removing a song from favorites (user-specific)
|
||||
func HandleRemoveFromFavorite(w http.ResponseWriter, r *http.Request) {
|
||||
fmt.Printf("[API] Remove from favorite request received from %s\n", r.RemoteAddr)
|
||||
|
||||
if r.Method != http.MethodPost {
|
||||
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
var userID string
|
||||
|
||||
// First, check for ESP32 device token (X-Device-Token header)
|
||||
deviceToken := r.Header.Get("X-Device-Token")
|
||||
if deviceToken != "" {
|
||||
dm := GetDeviceManager()
|
||||
device, err := dm.VerifyToken(deviceToken)
|
||||
if err == nil {
|
||||
userID = userStore.GetUserIDByUsername(device.Username)
|
||||
fmt.Printf("[API] ESP32 device removing favorite (user: %s, userID: %s)\n", device.Username, userID)
|
||||
}
|
||||
}
|
||||
|
||||
// If not ESP32, check for web user token (Authorization header)
|
||||
if userID == "" {
|
||||
token := r.Header.Get("Authorization")
|
||||
if token != "" {
|
||||
token = strings.TrimPrefix(token, "Bearer ")
|
||||
user, err := userStore.GetUserByToken(token)
|
||||
if err == nil {
|
||||
userID = user.ID
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Read song info from body
|
||||
body, err := io.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
http.Error(w, "Error reading request body", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
defer r.Body.Close()
|
||||
|
||||
var song MusicItem
|
||||
err = json.Unmarshal(body, &song)
|
||||
if err != nil {
|
||||
http.Error(w, "Invalid JSON", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
title := song.Title
|
||||
artist := song.Artist
|
||||
|
||||
if title == "" || artist == "" {
|
||||
http.Error(w, "Missing title or artist", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
fmt.Printf("[API] Removing from favorites: %s - %s (userID: %s)\n", artist, title, userID)
|
||||
|
||||
// If user is authenticated, remove from user's "我喜欢" playlist
|
||||
if userID != "" {
|
||||
playlists := playlistManager.GetUserPlaylists(userID)
|
||||
|
||||
// If user has no playlists, nothing to remove
|
||||
if len(playlists) == 0 {
|
||||
fmt.Printf("[API] User %s has no playlists, nothing to remove\n", userID)
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
json.NewEncoder(w).Encode(map[string]string{
|
||||
"status": "success",
|
||||
"message": "歌曲不在收藏列表中",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
favoritePlaylist := playlists[0]
|
||||
err = playlistManager.RemoveSongFromUserPlaylist(userID, favoritePlaylist.ID, title, artist)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
} else {
|
||||
// Fallback to global favorite playlist
|
||||
err = playlistManager.RemoveFromPlaylist("favorite", title, artist)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
fmt.Printf("[Info] Removed from favorites: %s - %s\n", artist, title)
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
json.NewEncoder(w).Encode(map[string]string{
|
||||
"status": "success",
|
||||
"message": "取消收藏成功",
|
||||
})
|
||||
}
|
||||
|
||||
// HandleGetFavorites handles getting the favorite playlist (user-specific)
|
||||
func HandleGetFavorites(w http.ResponseWriter, r *http.Request) {
|
||||
fmt.Printf("[API] Get favorites request received from %s\n", r.RemoteAddr)
|
||||
|
||||
var userID string
|
||||
|
||||
// First, check for ESP32 device token (X-Device-Token header)
|
||||
deviceToken := r.Header.Get("X-Device-Token")
|
||||
if deviceToken != "" {
|
||||
dm := GetDeviceManager()
|
||||
device, err := dm.VerifyToken(deviceToken)
|
||||
if err == nil {
|
||||
// Device.Username is the username, need to convert to userID
|
||||
userID = userStore.GetUserIDByUsername(device.Username)
|
||||
fmt.Printf("[API] ESP32 device authenticated: %s (user: %s, userID: %s)\n", device.MAC, device.Username, userID)
|
||||
} else {
|
||||
fmt.Printf("[API] Invalid device token: %v\n", err)
|
||||
}
|
||||
}
|
||||
|
||||
// If not ESP32, check for web user token (Authorization header)
|
||||
if userID == "" {
|
||||
token := r.Header.Get("Authorization")
|
||||
if token != "" {
|
||||
token = strings.TrimPrefix(token, "Bearer ")
|
||||
user, err := userStore.GetUserByToken(token)
|
||||
if err == nil {
|
||||
userID = user.ID
|
||||
fmt.Printf("[API] Web user authenticated: %s\n", userID)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// If user is authenticated, return user's "我喜欢" playlist
|
||||
if userID != "" {
|
||||
playlists := playlistManager.GetUserPlaylists(userID)
|
||||
|
||||
// If user has no playlists, initialize them first
|
||||
if len(playlists) == 0 {
|
||||
fmt.Printf("[API] User %s has no playlists, initializing...\n", userID)
|
||||
playlistManager.InitializeUserPlaylists(userID)
|
||||
playlists = playlistManager.GetUserPlaylists(userID)
|
||||
}
|
||||
|
||||
if len(playlists) > 0 {
|
||||
favoritePlaylist := playlists[0] // "我喜欢" is always the first playlist
|
||||
fmt.Printf("[API] Returning user %s favorites: %d songs\n", userID, len(favoritePlaylist.Songs))
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
// Return just the songs array for frontend compatibility
|
||||
json.NewEncoder(w).Encode(favoritePlaylist.Songs)
|
||||
return
|
||||
}
|
||||
|
||||
// If still no playlists (initialization failed), return empty array
|
||||
fmt.Printf("[API] User %s playlists initialization failed, returning empty\n", userID)
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
json.NewEncoder(w).Encode([]MusicItem{})
|
||||
return
|
||||
}
|
||||
|
||||
// Only return global favorite playlist if user is NOT authenticated
|
||||
fmt.Printf("[API] No authentication found, returning global favorites\n")
|
||||
playlist, err := playlistManager.GetPlaylist("favorite")
|
||||
if err != nil {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
json.NewEncoder(w).Encode([]MusicItem{}) // Return empty array
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
json.NewEncoder(w).Encode(playlist.Songs)
|
||||
}
|
||||
|
||||
// HandleCheckFavorite checks if a song is in favorites
|
||||
func HandleCheckFavorite(w http.ResponseWriter, r *http.Request) {
|
||||
title := r.URL.Query().Get("title")
|
||||
artist := r.URL.Query().Get("artist")
|
||||
|
||||
if title == "" || artist == "" {
|
||||
http.Error(w, "Missing title or artist", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
playlist, err := playlistManager.GetPlaylist("favorite")
|
||||
if err != nil {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
json.NewEncoder(w).Encode(map[string]bool{"is_favorite": false})
|
||||
return
|
||||
}
|
||||
|
||||
for _, song := range playlist.Songs {
|
||||
if song.Title == title && song.Artist == artist {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
json.NewEncoder(w).Encode(map[string]bool{"is_favorite": true})
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
json.NewEncoder(w).Encode(map[string]bool{"is_favorite": false})
|
||||
}
|
||||
|
||||
// User Playlist Management Functions
|
||||
|
||||
// loadUserPlaylists loads user playlists from JSON file
|
||||
func (pm *PlaylistManager) loadUserPlaylists() error {
|
||||
pm.mu.Lock()
|
||||
defer pm.mu.Unlock()
|
||||
|
||||
data, err := os.ReadFile(pm.userFilePath)
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
return nil // File doesn't exist yet, that's ok
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
return json.Unmarshal(data, &pm.UserPlaylists)
|
||||
}
|
||||
|
||||
// saveUserPlaylists saves user playlists to JSON file
|
||||
// NOTE: Caller must hold the lock!
|
||||
func (pm *PlaylistManager) saveUserPlaylists() error {
|
||||
data, err := json.MarshalIndent(pm.UserPlaylists, "", " ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return os.WriteFile(pm.userFilePath, data, 0644)
|
||||
}
|
||||
|
||||
// InitializeUserPlaylists creates default playlists for a new user
|
||||
func (pm *PlaylistManager) InitializeUserPlaylists(userID string) {
|
||||
pm.mu.Lock()
|
||||
defer pm.mu.Unlock()
|
||||
|
||||
if _, exists := pm.UserPlaylists[userID]; exists {
|
||||
return // Already initialized
|
||||
}
|
||||
|
||||
// Create "我喜欢" playlist for the user
|
||||
favoritePlaylist := &UserPlaylist{
|
||||
ID: generateID(),
|
||||
UserID: userID,
|
||||
Name: "我喜欢",
|
||||
Description: "我喜欢的音乐",
|
||||
Songs: []MusicItem{},
|
||||
IsPublic: false,
|
||||
CreatedAt: time.Now(),
|
||||
UpdatedAt: time.Now(),
|
||||
}
|
||||
|
||||
pm.UserPlaylists[userID] = []*UserPlaylist{favoritePlaylist}
|
||||
pm.saveUserPlaylists()
|
||||
}
|
||||
|
||||
// CreateUserPlaylist creates a new playlist for a user
|
||||
func (pm *PlaylistManager) CreateUserPlaylist(userID, name, description string) (*UserPlaylist, error) {
|
||||
pm.mu.Lock()
|
||||
defer pm.mu.Unlock()
|
||||
|
||||
playlist := &UserPlaylist{
|
||||
ID: generateID(),
|
||||
UserID: userID,
|
||||
Name: name,
|
||||
Description: description,
|
||||
Songs: []MusicItem{},
|
||||
IsPublic: false,
|
||||
CreatedAt: time.Now(),
|
||||
UpdatedAt: time.Now(),
|
||||
}
|
||||
|
||||
pm.UserPlaylists[userID] = append(pm.UserPlaylists[userID], playlist)
|
||||
pm.saveUserPlaylists()
|
||||
|
||||
return playlist, nil
|
||||
}
|
||||
|
||||
// GetUserPlaylists returns all playlists for a user
|
||||
func (pm *PlaylistManager) GetUserPlaylists(userID string) []*UserPlaylist {
|
||||
pm.mu.RLock()
|
||||
defer pm.mu.RUnlock()
|
||||
|
||||
return pm.UserPlaylists[userID]
|
||||
}
|
||||
|
||||
// GetUserPlaylistByID returns a specific playlist
|
||||
func (pm *PlaylistManager) GetUserPlaylistByID(userID, playlistID string) (*UserPlaylist, error) {
|
||||
pm.mu.RLock()
|
||||
defer pm.mu.RUnlock()
|
||||
|
||||
playlists, exists := pm.UserPlaylists[userID]
|
||||
if !exists {
|
||||
return nil, fmt.Errorf("no playlists found for user")
|
||||
}
|
||||
|
||||
for _, playlist := range playlists {
|
||||
if playlist.ID == playlistID {
|
||||
return playlist, nil
|
||||
}
|
||||
}
|
||||
|
||||
return nil, fmt.Errorf("playlist not found")
|
||||
}
|
||||
|
||||
// AddSongToUserPlaylist adds a song to a user's playlist
|
||||
func (pm *PlaylistManager) AddSongToUserPlaylist(userID, playlistID string, song MusicItem) error {
|
||||
pm.mu.Lock()
|
||||
defer pm.mu.Unlock()
|
||||
|
||||
playlists, exists := pm.UserPlaylists[userID]
|
||||
if !exists {
|
||||
return fmt.Errorf("no playlists found for user")
|
||||
}
|
||||
|
||||
for _, playlist := range playlists {
|
||||
if playlist.ID == playlistID {
|
||||
// Check if song already exists
|
||||
for _, s := range playlist.Songs {
|
||||
if s.Title == song.Title && s.Artist == song.Artist {
|
||||
return fmt.Errorf("song already exists in playlist")
|
||||
}
|
||||
}
|
||||
|
||||
playlist.Songs = append(playlist.Songs, song)
|
||||
playlist.UpdatedAt = time.Now()
|
||||
return pm.saveUserPlaylists()
|
||||
}
|
||||
}
|
||||
|
||||
return fmt.Errorf("playlist not found")
|
||||
}
|
||||
|
||||
// RemoveSongFromUserPlaylist removes a song from a user's playlist
|
||||
func (pm *PlaylistManager) RemoveSongFromUserPlaylist(userID, playlistID, title, artist string) error {
|
||||
pm.mu.Lock()
|
||||
defer pm.mu.Unlock()
|
||||
|
||||
playlists, exists := pm.UserPlaylists[userID]
|
||||
if !exists {
|
||||
return fmt.Errorf("no playlists found for user")
|
||||
}
|
||||
|
||||
for _, playlist := range playlists {
|
||||
if playlist.ID == playlistID {
|
||||
for i, song := range playlist.Songs {
|
||||
if song.Title == title && song.Artist == artist {
|
||||
playlist.Songs = append(playlist.Songs[:i], playlist.Songs[i+1:]...)
|
||||
playlist.UpdatedAt = time.Now()
|
||||
return pm.saveUserPlaylists()
|
||||
}
|
||||
}
|
||||
return fmt.Errorf("song not found in playlist")
|
||||
}
|
||||
}
|
||||
|
||||
return fmt.Errorf("playlist not found")
|
||||
}
|
||||
|
||||
// DeleteUserPlaylist deletes a user's playlist
|
||||
func (pm *PlaylistManager) DeleteUserPlaylist(userID, playlistID string) error {
|
||||
pm.mu.Lock()
|
||||
defer pm.mu.Unlock()
|
||||
|
||||
playlists, exists := pm.UserPlaylists[userID]
|
||||
if !exists {
|
||||
return fmt.Errorf("no playlists found for user")
|
||||
}
|
||||
|
||||
for i, playlist := range playlists {
|
||||
if playlist.ID == playlistID {
|
||||
// Don't allow deleting "我喜欢" playlist
|
||||
if playlist.Name == "我喜欢" && i == 0 {
|
||||
return fmt.Errorf("cannot delete favorite playlist")
|
||||
}
|
||||
|
||||
pm.UserPlaylists[userID] = append(playlists[:i], playlists[i+1:]...)
|
||||
return pm.saveUserPlaylists()
|
||||
}
|
||||
}
|
||||
|
||||
return fmt.Errorf("playlist not found")
|
||||
}
|
||||
|
||||
// User Playlist HTTP Handlers
|
||||
|
||||
// HandleCreateUserPlaylist handles creating a new playlist
|
||||
func HandleCreateUserPlaylist(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
userID := r.Header.Get("X-User-ID")
|
||||
if userID == "" {
|
||||
http.Error(w, "Unauthorized", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
body, err := io.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
http.Error(w, "Error reading request body", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
defer r.Body.Close()
|
||||
|
||||
var req struct {
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description"`
|
||||
}
|
||||
if err := json.Unmarshal(body, &req); err != nil {
|
||||
http.Error(w, "Invalid JSON", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
if req.Name == "" {
|
||||
http.Error(w, "Playlist name is required", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
playlist, err := playlistManager.CreateUserPlaylist(userID, req.Name, req.Description)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
fmt.Printf("[Info] User %s created playlist: %s\n", userID, req.Name)
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
json.NewEncoder(w).Encode(playlist)
|
||||
}
|
||||
|
||||
// HandleGetUserPlaylists handles getting all user playlists
|
||||
func HandleGetUserPlaylists(w http.ResponseWriter, r *http.Request) {
|
||||
userID := r.Header.Get("X-User-ID")
|
||||
if userID == "" {
|
||||
http.Error(w, "Unauthorized", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
playlists := playlistManager.GetUserPlaylists(userID)
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(playlists)
|
||||
}
|
||||
|
||||
// HandleAddSongToUserPlaylist handles adding a song to a playlist
|
||||
func HandleAddSongToUserPlaylist(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
userID := r.Header.Get("X-User-ID")
|
||||
if userID == "" {
|
||||
http.Error(w, "Unauthorized", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
playlistID := r.URL.Query().Get("playlist_id")
|
||||
if playlistID == "" {
|
||||
http.Error(w, "Missing playlist_id parameter", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
body, err := io.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
http.Error(w, "Error reading request body", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
defer r.Body.Close()
|
||||
|
||||
var song MusicItem
|
||||
if err := json.Unmarshal(body, &song); err != nil {
|
||||
http.Error(w, "Invalid JSON", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
err = playlistManager.AddSongToUserPlaylist(userID, playlistID, song)
|
||||
if err != nil {
|
||||
if err.Error() == "song already exists in playlist" {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(map[string]string{
|
||||
"status": "success",
|
||||
"message": "歌曲已在歌单中",
|
||||
})
|
||||
return
|
||||
}
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
fmt.Printf("[Info] User %s added song to playlist %s: %s - %s\n", userID, playlistID, song.Artist, song.Title)
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(map[string]string{
|
||||
"status": "success",
|
||||
"message": "添加成功",
|
||||
})
|
||||
}
|
||||
|
||||
// HandleRemoveSongFromUserPlaylist handles removing a song from a playlist
|
||||
func HandleRemoveSongFromUserPlaylist(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodDelete {
|
||||
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
userID := r.Header.Get("X-User-ID")
|
||||
if userID == "" {
|
||||
http.Error(w, "Unauthorized", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
playlistID := r.URL.Query().Get("playlist_id")
|
||||
title := r.URL.Query().Get("title")
|
||||
artist := r.URL.Query().Get("artist")
|
||||
|
||||
if playlistID == "" || title == "" || artist == "" {
|
||||
http.Error(w, "Missing required parameters", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
err := playlistManager.RemoveSongFromUserPlaylist(userID, playlistID, title, artist)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
fmt.Printf("[Info] User %s removed song from playlist %s: %s - %s\n", userID, playlistID, artist, title)
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(map[string]string{
|
||||
"status": "success",
|
||||
"message": "移除成功",
|
||||
})
|
||||
}
|
||||
|
||||
// HandleDeleteUserPlaylist handles deleting a playlist
|
||||
func HandleDeleteUserPlaylist(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodDelete {
|
||||
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
userID := r.Header.Get("X-User-ID")
|
||||
if userID == "" {
|
||||
http.Error(w, "Unauthorized", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
playlistID := r.URL.Query().Get("playlist_id")
|
||||
if playlistID == "" {
|
||||
http.Error(w, "Missing playlist_id parameter", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
err := playlistManager.DeleteUserPlaylist(userID, playlistID)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
fmt.Printf("[Info] User %s deleted playlist %s\n", userID, playlistID)
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(map[string]string{
|
||||
"status": "success",
|
||||
"message": "删除成功",
|
||||
})
|
||||
}
|
||||
|
||||
168
search.go
Executable file
168
search.go
Executable file
@@ -0,0 +1,168 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// SearchResult represents a search result with frontend-compatible fields
|
||||
type SearchResult struct {
|
||||
Title string `json:"title"`
|
||||
Artist string `json:"artist"`
|
||||
URL string `json:"url"` // For frontend compatibility
|
||||
Link string `json:"link"` // Alternative field
|
||||
LyricURL string `json:"lyric_url"` // Lyrics URL
|
||||
CoverURL string `json:"cover_url"`
|
||||
Duration int `json:"duration"` // Duration in seconds
|
||||
}
|
||||
|
||||
// HandleSearch handles music search requests
|
||||
func HandleSearch(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.Header().Set("Access-Control-Allow-Origin", "*")
|
||||
|
||||
query := r.URL.Query().Get("query")
|
||||
fmt.Printf("[API] Search request: query=%s\n", query)
|
||||
|
||||
if query == "" {
|
||||
json.NewEncoder(w).Encode([]SearchResult{})
|
||||
return
|
||||
}
|
||||
|
||||
// Search from multiple sources
|
||||
items := searchFromAllSources(query)
|
||||
|
||||
// Convert to frontend-compatible format
|
||||
results := make([]SearchResult, len(items))
|
||||
for i, item := range items {
|
||||
// Use AudioFullURL as primary, fallback to AudioURL
|
||||
audioURL := item.AudioFullURL
|
||||
if audioURL == "" {
|
||||
audioURL = item.AudioURL
|
||||
}
|
||||
|
||||
results[i] = SearchResult{
|
||||
Title: item.Title,
|
||||
Artist: item.Artist,
|
||||
URL: audioURL,
|
||||
Link: audioURL,
|
||||
LyricURL: item.LyricURL,
|
||||
CoverURL: item.CoverURL,
|
||||
Duration: item.Duration,
|
||||
}
|
||||
|
||||
fmt.Printf("[API] Result %d: title=%s, artist=%s, url=%s, lyric=%s\n", i+1, item.Title, item.Artist, audioURL, item.LyricURL)
|
||||
}
|
||||
|
||||
fmt.Printf("[API] Search completed: %d results found\n", len(results))
|
||||
json.NewEncoder(w).Encode(results)
|
||||
}
|
||||
|
||||
// searchFromAllSources searches music from all available sources
|
||||
func searchFromAllSources(query string) []MusicItem {
|
||||
var results []MusicItem
|
||||
|
||||
// Source 1: Search from sources.json (local config)
|
||||
sources := readSources()
|
||||
for _, source := range sources {
|
||||
if containsIgnoreCase(source.Title, query) || containsIgnoreCase(source.Artist, query) {
|
||||
item := MusicItem{
|
||||
Title: source.Title,
|
||||
Artist: source.Artist,
|
||||
AudioURL: source.AudioURL,
|
||||
AudioFullURL: source.AudioFullURL,
|
||||
M3U8URL: source.M3U8URL,
|
||||
LyricURL: source.LyricURL,
|
||||
CoverURL: source.CoverURL,
|
||||
Duration: source.Duration,
|
||||
FromCache: false,
|
||||
}
|
||||
results = append(results, item)
|
||||
|
||||
// Limit results to prevent too many items
|
||||
if len(results) >= 20 {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Source 2: Search from local files
|
||||
localItems := searchLocalMusic(query)
|
||||
results = append(results, localItems...)
|
||||
|
||||
// If no local results, try API search
|
||||
if len(results) == 0 {
|
||||
apiResults := searchFromAPI(query)
|
||||
results = append(results, apiResults...)
|
||||
}
|
||||
|
||||
// Limit total results
|
||||
if len(results) > 20 {
|
||||
results = results[:20]
|
||||
}
|
||||
|
||||
return results
|
||||
}
|
||||
|
||||
// searchLocalMusic searches music from local files
|
||||
func searchLocalMusic(query string) []MusicItem {
|
||||
// This function would search from local music files
|
||||
// For now, return empty array
|
||||
// TODO: Implement local file search
|
||||
return []MusicItem{}
|
||||
}
|
||||
|
||||
// searchFromAPI searches music from external APIs
|
||||
func searchFromAPI(query string) []MusicItem {
|
||||
var results []MusicItem
|
||||
|
||||
// Try different sources in priority order: 酷我 > 网易云 > 咪咕 > 百度
|
||||
// 酷我的搜索结果更准确,原唱版本更容易排在前面
|
||||
sources := []string{"kuwo", "netease", "migu", "baidu"}
|
||||
|
||||
for _, source := range sources {
|
||||
item := YuafengAPIResponseHandler(source, query, "")
|
||||
if item.Title != "" {
|
||||
results = append(results, item)
|
||||
break // Return first successful result
|
||||
}
|
||||
}
|
||||
|
||||
return results
|
||||
}
|
||||
|
||||
// containsIgnoreCase checks if a string contains substring (case insensitive)
|
||||
func containsIgnoreCase(s, substr string) bool {
|
||||
s = toLower(s)
|
||||
substr = toLower(substr)
|
||||
return contains(s, substr)
|
||||
}
|
||||
|
||||
func toLower(s string) string {
|
||||
var result []rune
|
||||
for _, r := range s {
|
||||
if r >= 'A' && r <= 'Z' {
|
||||
r += 32
|
||||
}
|
||||
result = append(result, r)
|
||||
}
|
||||
return string(result)
|
||||
}
|
||||
|
||||
func contains(s, substr string) bool {
|
||||
return len(substr) == 0 || indexString(s, substr) >= 0
|
||||
}
|
||||
|
||||
func indexString(s, substr string) int {
|
||||
n := len(substr)
|
||||
if n == 0 {
|
||||
return 0
|
||||
}
|
||||
for i := 0; i+n <= len(s); i++ {
|
||||
if s[i:i+n] == substr {
|
||||
return i
|
||||
}
|
||||
}
|
||||
return -1
|
||||
}
|
||||
1
sources.json
Executable file
1
sources.json
Executable file
@@ -0,0 +1 @@
|
||||
[]
|
||||
22
sources.json.example
Executable file
22
sources.json.example
Executable file
@@ -0,0 +1,22 @@
|
||||
[
|
||||
{
|
||||
"title": "",
|
||||
"artist": "",
|
||||
"audio_url": "",
|
||||
"audio_full_url": "",
|
||||
"m3u8_url": "",
|
||||
"lyric_url": "",
|
||||
"cover_url": "",
|
||||
"duration": 0
|
||||
},
|
||||
{
|
||||
"title": "",
|
||||
"artist": "",
|
||||
"audio_url": "",
|
||||
"audio_full_url": "",
|
||||
"m3u8_url": "",
|
||||
"lyric_url": "",
|
||||
"cover_url": "",
|
||||
"duration": 0
|
||||
}
|
||||
]
|
||||
73
start.bat
Executable file
73
start.bat
Executable file
@@ -0,0 +1,73 @@
|
||||
@echo off
|
||||
chcp 65001 >nul
|
||||
title Meow Music Server - 启动中...
|
||||
|
||||
echo.
|
||||
echo ╔═══════════════════════════════════════════════╗
|
||||
echo ║ 🎵 Meow Embedded Music Server v2.0 ║
|
||||
echo ║ 喵波音律 - 专为ESP32设计的音乐服务器 ║
|
||||
echo ╚═══════════════════════════════════════════════╝
|
||||
echo.
|
||||
|
||||
REM 检查Go是否安装
|
||||
where go >nul 2>nul
|
||||
if %errorlevel% neq 0 (
|
||||
echo [错误] 未找到Go语言环境!
|
||||
echo.
|
||||
echo 请先安装 Go: https://golang.org/dl/
|
||||
echo.
|
||||
pause
|
||||
exit /b 1
|
||||
)
|
||||
|
||||
echo [✓] Go环境检测成功
|
||||
go version
|
||||
echo.
|
||||
|
||||
echo [步骤 1/3] 检查配置文件...
|
||||
if not exist .env (
|
||||
if exist .env.example (
|
||||
echo [提示] 未找到.env文件,正在从.env.example创建...
|
||||
copy .env.example .env >nul
|
||||
echo [✓] 配置文件已创建
|
||||
) else (
|
||||
echo [提示] 将使用默认配置
|
||||
)
|
||||
) else (
|
||||
echo [✓] 配置文件已存在
|
||||
)
|
||||
echo.
|
||||
|
||||
echo [步骤 2/3] 安装/更新依赖...
|
||||
go mod tidy
|
||||
if %errorlevel% neq 0 (
|
||||
echo [错误] 依赖安装失败!
|
||||
echo.
|
||||
echo 可能需要配置Go代理(中国大陆用户):
|
||||
echo go env -w GOPROXY=https://goproxy.cn,direct
|
||||
echo.
|
||||
pause
|
||||
exit /b 1
|
||||
)
|
||||
echo [✓] 依赖安装完成
|
||||
echo.
|
||||
|
||||
echo [步骤 3/3] 启动服务器...
|
||||
echo.
|
||||
echo ╔═══════════════════════════════════════════════╗
|
||||
echo ║ 访问地址 ║
|
||||
echo ╠═══════════════════════════════════════════════╣
|
||||
echo ║ 新版应用: http://localhost:2233/app ║
|
||||
echo ║ 经典界面: http://localhost:2233/ ║
|
||||
echo ╚═══════════════════════════════════════════════╝
|
||||
echo.
|
||||
echo [✓] 服务器正在启动,请稍候...
|
||||
echo.
|
||||
echo ┌───────────────────────────────────────────────┐
|
||||
echo │ 提示:按 Ctrl+C 可以停止服务器 │
|
||||
echo │ 首次使用请访问 /app 注册账户 │
|
||||
echo └───────────────────────────────────────────────┘
|
||||
echo.
|
||||
|
||||
title Meow Music Server - 运行中
|
||||
go run .
|
||||
81
start.sh
Executable file
81
start.sh
Executable file
@@ -0,0 +1,81 @@
|
||||
#!/bin/bash
|
||||
|
||||
# 颜色定义
|
||||
GREEN='\033[0;32m'
|
||||
BLUE='\033[0;34m'
|
||||
RED='\033[0;31m'
|
||||
YELLOW='\033[1;33m'
|
||||
NC='\033[0m' # No Color
|
||||
|
||||
echo ""
|
||||
echo "╔═══════════════════════════════════════════════╗"
|
||||
echo "║ 🎵 Meow Embedded Music Server v2.0 ║"
|
||||
echo "║ 喵波音律 - 专为ESP32设计的音乐服务器 ║"
|
||||
echo "╚═══════════════════════════════════════════════╝"
|
||||
echo ""
|
||||
|
||||
# 检查Go是否安装
|
||||
if ! command -v go &> /dev/null; then
|
||||
echo -e "${RED}[错误]${NC} 未找到Go语言环境!"
|
||||
echo ""
|
||||
echo "请先安装 Go:"
|
||||
echo " Ubuntu/Debian: sudo apt install golang-go"
|
||||
echo " macOS: brew install go"
|
||||
echo " CentOS/RHEL: sudo yum install golang"
|
||||
echo ""
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo -e "${GREEN}[✓]${NC} Go环境检测成功"
|
||||
go version
|
||||
echo ""
|
||||
|
||||
# 检查配置文件
|
||||
echo -e "${BLUE}[步骤 1/3]${NC} 检查配置文件..."
|
||||
if [ ! -f .env ]; then
|
||||
if [ -f .env.example ]; then
|
||||
echo -e "${YELLOW}[提示]${NC} 未找到.env文件,正在从.env.example创建..."
|
||||
cp .env.example .env
|
||||
echo -e "${GREEN}[✓]${NC} 配置文件已创建"
|
||||
else
|
||||
echo -e "${YELLOW}[提示]${NC} 将使用默认配置"
|
||||
fi
|
||||
else
|
||||
echo -e "${GREEN}[✓]${NC} 配置文件已存在"
|
||||
fi
|
||||
echo ""
|
||||
|
||||
# 安装依赖
|
||||
echo -e "${BLUE}[步骤 2/3]${NC} 安装/更新依赖..."
|
||||
if ! go mod tidy; then
|
||||
echo -e "${RED}[错误]${NC} 依赖安装失败!"
|
||||
echo ""
|
||||
echo "可能需要配置Go代理(中国大陆用户):"
|
||||
echo " export GOPROXY=https://goproxy.cn,direct"
|
||||
echo "或永久设置:"
|
||||
echo " go env -w GOPROXY=https://goproxy.cn,direct"
|
||||
echo ""
|
||||
exit 1
|
||||
fi
|
||||
echo -e "${GREEN}[✓]${NC} 依赖安装完成"
|
||||
echo ""
|
||||
|
||||
# 启动服务器
|
||||
echo -e "${BLUE}[步骤 3/3]${NC} 启动服务器..."
|
||||
echo ""
|
||||
echo "╔═══════════════════════════════════════════════╗"
|
||||
echo "║ 访问地址 ║"
|
||||
echo "╠═══════════════════════════════════════════════╣"
|
||||
echo "║ 新版应用: http://localhost:2233/app ║"
|
||||
echo "║ 经典界面: http://localhost:2233/ ║"
|
||||
echo "╚═══════════════════════════════════════════════╝"
|
||||
echo ""
|
||||
echo -e "${GREEN}[✓]${NC} 服务器正在启动,请稍候..."
|
||||
echo ""
|
||||
echo "┌───────────────────────────────────────────────┐"
|
||||
echo "│ 提示:按 Ctrl+C 可以停止服务器 │"
|
||||
echo "│ 首次使用请访问 /app 注册账户 │"
|
||||
echo "└───────────────────────────────────────────────┘"
|
||||
echo ""
|
||||
|
||||
go run .
|
||||
59
struct.go
Executable file
59
struct.go
Executable file
@@ -0,0 +1,59 @@
|
||||
package main
|
||||
|
||||
import "time"
|
||||
|
||||
// MusicItem represents a music item.
|
||||
type MusicItem struct {
|
||||
Title string `json:"title"`
|
||||
Artist string `json:"artist"`
|
||||
AudioURL string `json:"audio_url"`
|
||||
AudioFullURL string `json:"audio_full_url"`
|
||||
M3U8URL string `json:"m3u8_url"`
|
||||
LyricURL string `json:"lyric_url"`
|
||||
CoverURL string `json:"cover_url"`
|
||||
Duration int `json:"duration"`
|
||||
FromCache bool `json:"from_cache"`
|
||||
IP string `json:"ip"`
|
||||
}
|
||||
|
||||
// User represents a user account
|
||||
type User struct {
|
||||
ID string `json:"id"`
|
||||
Username string `json:"username"`
|
||||
Email string `json:"email"`
|
||||
Password string `json:"-"` // Never expose password in JSON
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
// UserPlaylist represents a user's custom playlist
|
||||
type UserPlaylist struct {
|
||||
ID string `json:"id"`
|
||||
UserID string `json:"user_id"`
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description"`
|
||||
CoverURL string `json:"cover_url"`
|
||||
Songs []MusicItem `json:"songs"`
|
||||
IsPublic bool `json:"is_public"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
// LoginRequest represents login credentials
|
||||
type LoginRequest struct {
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
|
||||
// RegisterRequest represents registration data
|
||||
type RegisterRequest struct {
|
||||
Username string `json:"username"`
|
||||
Email string `json:"email"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
|
||||
// AuthResponse represents authentication response
|
||||
type AuthResponse struct {
|
||||
Token string `json:"token"`
|
||||
User User `json:"user"`
|
||||
}
|
||||
1
theme/.gitignore
vendored
Normal file
1
theme/.gitignore
vendored
Normal file
@@ -0,0 +1 @@
|
||||
|
||||
465
theme/device-bind.html
Normal file
465
theme/device-bind.html
Normal 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
2182
theme/full-app.html
Normal file
File diff suppressed because it is too large
Load Diff
720
theme/index.html
Normal file
720
theme/index.html
Normal 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
367
theme/music-app.html
Normal 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
476
theme/simple-app.html
Normal 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
270
theme/test-app.html
Normal 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>
|
||||
479
user.go
Executable file
479
user.go
Executable file
@@ -0,0 +1,479 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
// UserStore manages user data
|
||||
type UserStore struct {
|
||||
mu sync.RWMutex
|
||||
Users map[string]*User // key: user ID
|
||||
Usernames map[string]string // key: username, value: user ID
|
||||
Emails map[string]string // key: email, value: user ID
|
||||
Sessions map[string]string // key: session token, value: user ID
|
||||
filePath string
|
||||
}
|
||||
|
||||
var userStore *UserStore
|
||||
|
||||
// InitUserStore initializes the user store
|
||||
func InitUserStore() {
|
||||
userStore = &UserStore{
|
||||
Users: make(map[string]*User),
|
||||
Usernames: make(map[string]string),
|
||||
Emails: make(map[string]string),
|
||||
Sessions: make(map[string]string),
|
||||
filePath: "./files/users.json",
|
||||
}
|
||||
|
||||
// Create files directory if it doesn't exist
|
||||
os.MkdirAll("./files", 0755)
|
||||
|
||||
// Load existing users
|
||||
userStore.loadFromFile()
|
||||
}
|
||||
|
||||
// loadFromFile loads users from JSON file
|
||||
func (us *UserStore) loadFromFile() error {
|
||||
us.mu.Lock()
|
||||
defer us.mu.Unlock()
|
||||
|
||||
data, err := os.ReadFile(us.filePath)
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
return nil // File doesn't exist yet, that's ok
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
var storageUsers []*userStorage
|
||||
if err := json.Unmarshal(data, &storageUsers); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Convert from storage format to User struct and rebuild indexes
|
||||
for _, su := range storageUsers {
|
||||
user := &User{
|
||||
ID: su.ID,
|
||||
Username: su.Username,
|
||||
Email: su.Email,
|
||||
Password: su.Password, // Restore password
|
||||
CreatedAt: su.CreatedAt,
|
||||
UpdatedAt: su.UpdatedAt,
|
||||
}
|
||||
us.Users[user.ID] = user
|
||||
us.Usernames[strings.ToLower(user.Username)] = user.ID
|
||||
us.Emails[strings.ToLower(user.Email)] = user.ID
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// userStorage is used for saving/loading users with passwords
|
||||
type userStorage struct {
|
||||
ID string `json:"id"`
|
||||
Username string `json:"username"`
|
||||
Email string `json:"email"`
|
||||
Password string `json:"password"` // Include password for storage
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
// saveToFile saves users to JSON file
|
||||
// NOTE: Caller must hold the lock!
|
||||
func (us *UserStore) saveToFile() error {
|
||||
// Convert map to slice of storage struct (with passwords)
|
||||
users := make([]*userStorage, 0, len(us.Users))
|
||||
for _, user := range us.Users {
|
||||
users = append(users, &userStorage{
|
||||
ID: user.ID,
|
||||
Username: user.Username,
|
||||
Email: user.Email,
|
||||
Password: user.Password,
|
||||
CreatedAt: user.CreatedAt,
|
||||
UpdatedAt: user.UpdatedAt,
|
||||
})
|
||||
}
|
||||
|
||||
data, err := json.MarshalIndent(users, "", " ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return os.WriteFile(us.filePath, data, 0644)
|
||||
}
|
||||
|
||||
// generateID generates a random ID
|
||||
func generateID() string {
|
||||
bytes := make([]byte, 16)
|
||||
rand.Read(bytes)
|
||||
return hex.EncodeToString(bytes)
|
||||
}
|
||||
|
||||
// generateToken generates a session token
|
||||
func generateToken() string {
|
||||
bytes := make([]byte, 32)
|
||||
rand.Read(bytes)
|
||||
return hex.EncodeToString(bytes)
|
||||
}
|
||||
|
||||
// CreateUser creates a new user
|
||||
func (us *UserStore) CreateUser(username, email, password string) (*User, error) {
|
||||
// Hash password BEFORE acquiring lock (this is slow!)
|
||||
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
us.mu.Lock()
|
||||
defer us.mu.Unlock()
|
||||
|
||||
// Check if username already exists
|
||||
if _, exists := us.Usernames[strings.ToLower(username)]; exists {
|
||||
return nil, fmt.Errorf("username already exists")
|
||||
}
|
||||
|
||||
// Check if email already exists
|
||||
if _, exists := us.Emails[strings.ToLower(email)]; exists {
|
||||
return nil, fmt.Errorf("email already exists")
|
||||
}
|
||||
|
||||
// Create user
|
||||
user := &User{
|
||||
ID: generateID(),
|
||||
Username: username,
|
||||
Email: email,
|
||||
Password: string(hashedPassword),
|
||||
CreatedAt: time.Now(),
|
||||
UpdatedAt: time.Now(),
|
||||
}
|
||||
|
||||
// Store user
|
||||
us.Users[user.ID] = user
|
||||
us.Usernames[strings.ToLower(username)] = user.ID
|
||||
us.Emails[strings.ToLower(email)] = user.ID
|
||||
|
||||
// Save to file
|
||||
if err := us.saveToFile(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return user, nil
|
||||
}
|
||||
|
||||
// AuthenticateUser authenticates a user by username and password
|
||||
func (us *UserStore) AuthenticateUser(username, password string) (*User, string, error) {
|
||||
us.mu.RLock()
|
||||
userID, exists := us.Usernames[strings.ToLower(username)]
|
||||
us.mu.RUnlock()
|
||||
|
||||
if !exists {
|
||||
return nil, "", fmt.Errorf("invalid username or password")
|
||||
}
|
||||
|
||||
us.mu.RLock()
|
||||
user := us.Users[userID]
|
||||
us.mu.RUnlock()
|
||||
|
||||
// Compare password
|
||||
if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password)); err != nil {
|
||||
return nil, "", fmt.Errorf("invalid username or password")
|
||||
}
|
||||
|
||||
// Generate session token
|
||||
token := generateToken()
|
||||
us.mu.Lock()
|
||||
us.Sessions[token] = user.ID
|
||||
us.mu.Unlock()
|
||||
|
||||
return user, token, nil
|
||||
}
|
||||
|
||||
// GetUserByToken retrieves a user by session token
|
||||
func (us *UserStore) GetUserByToken(token string) (*User, error) {
|
||||
us.mu.RLock()
|
||||
defer us.mu.RUnlock()
|
||||
|
||||
userID, exists := us.Sessions[token]
|
||||
if !exists {
|
||||
return nil, fmt.Errorf("invalid session token")
|
||||
}
|
||||
|
||||
user, exists := us.Users[userID]
|
||||
if !exists {
|
||||
return nil, fmt.Errorf("user not found")
|
||||
}
|
||||
|
||||
return user, nil
|
||||
}
|
||||
|
||||
// Logout removes a session token
|
||||
func (us *UserStore) Logout(token string) {
|
||||
us.mu.Lock()
|
||||
defer us.mu.Unlock()
|
||||
delete(us.Sessions, token)
|
||||
}
|
||||
|
||||
// HTTP Handlers
|
||||
|
||||
// HandleRegister handles user registration
|
||||
func HandleRegister(w http.ResponseWriter, r *http.Request) {
|
||||
fmt.Printf("[API] Register request received from %s\n", r.RemoteAddr)
|
||||
|
||||
if r.Method != http.MethodPost {
|
||||
fmt.Printf("[API] Register: Method not allowed: %s\n", r.Method)
|
||||
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
fmt.Printf("[API] Reading request body...\n")
|
||||
body, err := io.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
fmt.Printf("[API] Error reading body: %v\n", err)
|
||||
http.Error(w, "Error reading request body", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
defer r.Body.Close()
|
||||
fmt.Printf("[API] Body received: %s\n", string(body))
|
||||
|
||||
var req RegisterRequest
|
||||
if err := json.Unmarshal(body, &req); err != nil {
|
||||
fmt.Printf("[API] Error parsing JSON: %v\n", err)
|
||||
http.Error(w, "Invalid JSON", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
fmt.Printf("[API] Parsed: username=%s, email=%s\n", req.Username, req.Email)
|
||||
|
||||
// Validate input
|
||||
if req.Username == "" || req.Email == "" || req.Password == "" {
|
||||
fmt.Printf("[API] Validation failed: missing fields\n")
|
||||
http.Error(w, "All fields are required", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
if len(req.Password) < 6 {
|
||||
fmt.Printf("[API] Validation failed: password too short\n")
|
||||
http.Error(w, "Password must be at least 6 characters", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
// Create user
|
||||
fmt.Printf("[API] Creating user...\n")
|
||||
user, err := userStore.CreateUser(req.Username, req.Email, req.Password)
|
||||
if err != nil {
|
||||
fmt.Printf("[API] Error creating user: %v\n", err)
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
fmt.Printf("[API] User created successfully! ID=%s\n", user.ID)
|
||||
|
||||
// Generate session token
|
||||
token := generateToken()
|
||||
userStore.mu.Lock()
|
||||
userStore.Sessions[token] = user.ID
|
||||
userStore.mu.Unlock()
|
||||
|
||||
// Initialize user's favorite playlist
|
||||
if playlistManager != nil {
|
||||
playlistManager.InitializeUserPlaylists(user.ID)
|
||||
}
|
||||
|
||||
fmt.Printf("[Info] User registered: %s\n", user.Username)
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
json.NewEncoder(w).Encode(AuthResponse{
|
||||
Token: token,
|
||||
User: *user,
|
||||
})
|
||||
}
|
||||
|
||||
// HandleLogin handles user login
|
||||
func HandleLogin(w http.ResponseWriter, r *http.Request) {
|
||||
fmt.Printf("[API] Login request received from %s\n", r.RemoteAddr)
|
||||
|
||||
if r.Method != http.MethodPost {
|
||||
fmt.Printf("[API] Login: Method not allowed: %s\n", r.Method)
|
||||
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
fmt.Printf("[API] Reading login body...\n")
|
||||
body, err := io.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
fmt.Printf("[API] Error reading body: %v\n", err)
|
||||
http.Error(w, "Error reading request body", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
defer r.Body.Close()
|
||||
fmt.Printf("[API] Login body: %s\n", string(body))
|
||||
|
||||
var req LoginRequest
|
||||
if err := json.Unmarshal(body, &req); err != nil {
|
||||
fmt.Printf("[API] Error parsing JSON: %v\n", err)
|
||||
http.Error(w, "Invalid JSON", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
fmt.Printf("[API] Login username: %s\n", req.Username)
|
||||
|
||||
// Authenticate user
|
||||
fmt.Printf("[API] Authenticating...\n")
|
||||
user, token, err := userStore.AuthenticateUser(req.Username, req.Password)
|
||||
fmt.Printf("[API] Authentication result: %v\n", err)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
fmt.Printf("[Info] User logged in: %s\n", user.Username)
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(AuthResponse{
|
||||
Token: token,
|
||||
User: *user,
|
||||
})
|
||||
}
|
||||
|
||||
// HandleLogout handles user logout
|
||||
func HandleLogout(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
token := r.Header.Get("Authorization")
|
||||
if token == "" {
|
||||
http.Error(w, "Missing authorization token", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
// Remove "Bearer " prefix if present
|
||||
token = strings.TrimPrefix(token, "Bearer ")
|
||||
|
||||
userStore.Logout(token)
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(map[string]string{
|
||||
"status": "success",
|
||||
"message": "Logged out successfully",
|
||||
})
|
||||
}
|
||||
|
||||
// HandleGetCurrentUser returns current user info
|
||||
func HandleGetCurrentUser(w http.ResponseWriter, r *http.Request) {
|
||||
token := r.Header.Get("Authorization")
|
||||
if token == "" {
|
||||
http.Error(w, "Missing authorization token", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
// Remove "Bearer " prefix if present
|
||||
token = strings.TrimPrefix(token, "Bearer ")
|
||||
|
||||
user, err := userStore.GetUserByToken(token)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(user)
|
||||
}
|
||||
|
||||
// AuthMiddleware authenticates requests
|
||||
func AuthMiddleware(next http.HandlerFunc) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
// 1. 尝试从 Authorization Header 获取
|
||||
token := r.Header.Get("Authorization")
|
||||
if token != "" {
|
||||
token = strings.TrimPrefix(token, "Bearer ")
|
||||
user, err := userStore.GetUserByToken(token)
|
||||
if err == nil {
|
||||
r.Header.Set("X-User-ID", user.ID)
|
||||
next(w, r)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// 2. 尝试从 X-Device-Token 获取 (ESP32设备)
|
||||
deviceToken := r.Header.Get("X-Device-Token")
|
||||
if deviceToken != "" {
|
||||
// 这里需要调用DeviceManager,但为了避免循环依赖(如果user包独立),我们使用全局函数或接口
|
||||
// 假设GetDeviceManager()是全局可用的
|
||||
dm := GetDeviceManager()
|
||||
device, err := dm.VerifyToken(deviceToken)
|
||||
if err == nil {
|
||||
// 找到了设备,现在需要找到对应的用户
|
||||
// Device结构体中有Username,我们需要根据Username找到User对象
|
||||
userID := userStore.GetUserIDByUsername(device.Username)
|
||||
if userID != "" {
|
||||
r.Header.Set("X-User-ID", userID)
|
||||
|
||||
// 更新设备最后在线时间
|
||||
dm.UpdateLastSeen(device.MAC)
|
||||
|
||||
next(w, r)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 3. 尝试从 Cookie 获取 (Web Session)
|
||||
cookie, err := r.Cookie("session_token")
|
||||
if err == nil {
|
||||
username := userStore.GetUsernameByToken(cookie.Value)
|
||||
if username != "" {
|
||||
userID := userStore.GetUserIDByUsername(username)
|
||||
if userID != "" {
|
||||
r.Header.Set("X-User-ID", userID)
|
||||
next(w, r)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
http.Error(w, "Invalid or expired token", http.StatusUnauthorized)
|
||||
}
|
||||
}
|
||||
|
||||
// GetUserStore 返回UserStore单例
|
||||
func GetUserStore() *UserStore {
|
||||
return userStore
|
||||
}
|
||||
|
||||
// GetUserIDByUsername returns user ID by username
|
||||
func (us *UserStore) GetUserIDByUsername(username string) string {
|
||||
us.mu.RLock()
|
||||
defer us.mu.RUnlock()
|
||||
|
||||
return us.Usernames[username]
|
||||
}
|
||||
|
||||
// GetUsernameByToken 通过session token获取用户名
|
||||
func (us *UserStore) GetUsernameByToken(token string) string {
|
||||
us.mu.RLock()
|
||||
defer us.mu.RUnlock()
|
||||
|
||||
userID, exists := us.Sessions[token]
|
||||
if !exists {
|
||||
return ""
|
||||
}
|
||||
|
||||
user, exists := us.Users[userID]
|
||||
if !exists {
|
||||
return ""
|
||||
}
|
||||
|
||||
return user.Username
|
||||
}
|
||||
418
yuafengfreeapi.go
Executable file
418
yuafengfreeapi.go
Executable file
@@ -0,0 +1,418 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
type YuafengAPIFreeResponse struct {
|
||||
Data struct {
|
||||
Song string `json:"song"`
|
||||
Singer string `json:"singer"`
|
||||
Cover string `json:"cover"`
|
||||
AlbumName string `json:"album_name"`
|
||||
Music string `json:"music"`
|
||||
Lyric string `json:"lyric"`
|
||||
} `json:"data"`
|
||||
}
|
||||
|
||||
// 枫雨API response handler with multiple API fallback
|
||||
func YuafengAPIResponseHandler(sources, song, singer string) MusicItem {
|
||||
fmt.Printf("[Info] Fetching music data for %s by %s\n", song, singer)
|
||||
|
||||
// API hosts to try in order
|
||||
apiHosts := []string{
|
||||
"https://api.yuafeng.cn",
|
||||
"https://api-v2.yuafeng.cn",
|
||||
"https://api.yaohud.cn",
|
||||
}
|
||||
|
||||
var pathSuffix string
|
||||
switch sources {
|
||||
case "kuwo":
|
||||
pathSuffix = "/API/ly/kwmusic.php"
|
||||
case "netease":
|
||||
pathSuffix = "/API/ly/wymusic.php"
|
||||
case "migu":
|
||||
pathSuffix = "/API/ly/mgmusic.php"
|
||||
case "baidu":
|
||||
pathSuffix = "/API/ly/bdmusic.php"
|
||||
default:
|
||||
return MusicItem{}
|
||||
}
|
||||
|
||||
var fallbackItem MusicItem // 保存第一个有音乐但没歌词的结果
|
||||
|
||||
// Try each API host - 尝试所有API直到找到歌词
|
||||
for i, host := range apiHosts {
|
||||
fmt.Printf("[Info] Trying API %d/%d: %s\n", i+1, len(apiHosts), host)
|
||||
item := tryFetchFromAPI(host+pathSuffix, song, singer)
|
||||
if item.Title != "" {
|
||||
// 如果有歌词,立即返回
|
||||
if item.LyricURL != "" {
|
||||
fmt.Printf("[Success] ✓ Found music WITH lyrics from %s\n", host)
|
||||
return item
|
||||
}
|
||||
// 如果没有歌词但有音乐,保存作为fallback并继续尝试
|
||||
if fallbackItem.Title == "" {
|
||||
fallbackItem = item
|
||||
fmt.Printf("[Info] ○ Got music WITHOUT lyrics from %s, saved as fallback, continuing...\n", host)
|
||||
} else {
|
||||
fmt.Printf("[Info] ○ Got music WITHOUT lyrics from %s, trying next API...\n", host)
|
||||
}
|
||||
} else {
|
||||
fmt.Printf("[Warning] × API %s failed, trying next...\n", host)
|
||||
}
|
||||
}
|
||||
|
||||
// 所有API都试完了
|
||||
if fallbackItem.Title != "" {
|
||||
fmt.Println("[Info] ▶ All 3 APIs tried - no lyrics found, returning music without lyrics")
|
||||
return fallbackItem
|
||||
}
|
||||
|
||||
fmt.Println("[Error] ✗ All 3 APIs failed completely")
|
||||
return MusicItem{}
|
||||
}
|
||||
|
||||
// tryFetchFromAPI attempts to fetch music data from a single API endpoint
|
||||
func tryFetchFromAPI(APIurl, song, singer string) MusicItem {
|
||||
resp, err := http.Get(APIurl + "?msg=" + song + "&n=1")
|
||||
if err != nil {
|
||||
fmt.Println("[Error] Error fetching the data from API:", err)
|
||||
return MusicItem{}
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
fmt.Println("[Error] Error reading the response body:", err)
|
||||
return MusicItem{}
|
||||
}
|
||||
|
||||
// Check if response is HTML (starts with < character)
|
||||
bodyStr := string(body)
|
||||
if len(bodyStr) > 0 && bodyStr[0] == '<' {
|
||||
fmt.Println("[Warning] API returned HTML instead of JSON")
|
||||
fmt.Printf("[Debug] Saving HTML response to debug.html for inspection\n")
|
||||
|
||||
// Save HTML to file for debugging
|
||||
os.WriteFile("debug_api_response.html", body, 0644)
|
||||
fmt.Println("[Info] HTML response saved to debug_api_response.html")
|
||||
|
||||
// Try to extract JSON from HTML if embedded
|
||||
// Look for common patterns where JSON might be embedded
|
||||
if strings.Contains(bodyStr, `"song"`) && strings.Contains(bodyStr, `"singer"`) {
|
||||
fmt.Println("[Info] Attempting to extract JSON from HTML...")
|
||||
// Try to find JSON block in HTML
|
||||
jsonStart := strings.Index(bodyStr, "{")
|
||||
jsonEnd := strings.LastIndex(bodyStr, "}")
|
||||
if jsonStart != -1 && jsonEnd != -1 && jsonEnd > jsonStart {
|
||||
jsonStr := bodyStr[jsonStart : jsonEnd+1]
|
||||
var response YuafengAPIFreeResponse
|
||||
err = json.Unmarshal([]byte(jsonStr), &response)
|
||||
if err == nil {
|
||||
fmt.Println("[Success] Extracted JSON from HTML successfully")
|
||||
body = []byte(jsonStr)
|
||||
goto parseSuccess
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fmt.Println("[Error] Cannot parse HTML response - API may be unavailable")
|
||||
return MusicItem{}
|
||||
}
|
||||
|
||||
parseSuccess:
|
||||
var response YuafengAPIFreeResponse
|
||||
err = json.Unmarshal(body, &response)
|
||||
if err != nil {
|
||||
fmt.Println("[Error] Error parsing API response:", err)
|
||||
return MusicItem{}
|
||||
}
|
||||
|
||||
// Create directory
|
||||
dirName := fmt.Sprintf("./files/cache/music/%s-%s", response.Data.Singer, response.Data.Song)
|
||||
err = os.MkdirAll(dirName, 0755)
|
||||
if err != nil {
|
||||
fmt.Println("[Error] Error creating directory:", err)
|
||||
return MusicItem{}
|
||||
}
|
||||
|
||||
if response.Data.Music == "" {
|
||||
fmt.Println("[Warning] Music URL is empty")
|
||||
return MusicItem{}
|
||||
}
|
||||
|
||||
// 获取封面扩展名
|
||||
ext := filepath.Ext(response.Data.Cover)
|
||||
|
||||
// 保存远程 URL 到文件,供 file.go 流式转码使用
|
||||
remoteURLFile := filepath.Join(dirName, "remote_url.txt")
|
||||
os.WriteFile(remoteURLFile, []byte(response.Data.Music), 0644)
|
||||
|
||||
// ========== 关键优化:先返回,后台异步处理 ==========
|
||||
// 把下载、转码等耗时操作放到 goroutine 异步执行
|
||||
go func() {
|
||||
fmt.Printf("[Async] Starting background processing for: %s - %s\n", response.Data.Singer, response.Data.Song)
|
||||
var wg sync.WaitGroup
|
||||
|
||||
// ========== 1. 歌词处理 ==========
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
lyricData := response.Data.Lyric
|
||||
if lyricData == "获取歌词失败" {
|
||||
fetchLyricFromYaohu(response.Data.Song, response.Data.Singer, dirName)
|
||||
} else if !strings.HasPrefix(lyricData, "http://") && !strings.HasPrefix(lyricData, "https://") {
|
||||
// 直接写入歌词内容
|
||||
lines := strings.Split(lyricData, "\n")
|
||||
lyricFilePath := filepath.Join(dirName, "lyric.lrc")
|
||||
file, err := os.Create(lyricFilePath)
|
||||
if err == nil {
|
||||
timeTagRegex := regexp.MustCompile(`^\[(\d+(?:\.\d+)?)\]`)
|
||||
for _, line := range lines {
|
||||
match := timeTagRegex.FindStringSubmatch(line)
|
||||
if match != nil {
|
||||
timeInSeconds, _ := strconv.ParseFloat(match[1], 64)
|
||||
minutes := int(timeInSeconds / 60)
|
||||
seconds := int(timeInSeconds) % 60
|
||||
milliseconds := int((timeInSeconds-float64(seconds))*1000) / 100 % 100
|
||||
formattedTimeTag := fmt.Sprintf("[%02d:%02d.%02d]", minutes, seconds, milliseconds)
|
||||
line = timeTagRegex.ReplaceAllString(line, formattedTimeTag)
|
||||
}
|
||||
file.WriteString(line + "\r\n")
|
||||
}
|
||||
file.Close()
|
||||
fmt.Printf("[Async] Lyrics saved for: %s - %s\n", response.Data.Singer, response.Data.Song)
|
||||
}
|
||||
} else {
|
||||
downloadFile(filepath.Join(dirName, "lyric.lrc"), lyricData)
|
||||
}
|
||||
}()
|
||||
|
||||
// ========== 2. 封面处理 ==========
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
downloadFile(filepath.Join(dirName, "cover"+ext), response.Data.Cover)
|
||||
}()
|
||||
|
||||
// ========== 3. 音频转码 ==========
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
musicExt, err := getMusicFileExtension(response.Data.Music)
|
||||
if err != nil {
|
||||
fmt.Println("[Async Warning] Cannot identify music format, using default .mp3:", err)
|
||||
musicExt = ".mp3"
|
||||
}
|
||||
|
||||
outputMp3 := filepath.Join(dirName, "music.mp3")
|
||||
err = streamConvertAudio(response.Data.Music, outputMp3)
|
||||
if err != nil {
|
||||
fmt.Println("[Async Error] Error stream converting audio:", err)
|
||||
// 备用方案
|
||||
err = downloadFile(filepath.Join(dirName, "music_full"+musicExt), response.Data.Music)
|
||||
if err == nil {
|
||||
compressAndSegmentAudio(filepath.Join(dirName, "music_full"+musicExt), dirName)
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
wg.Wait() // 等待所有任务完成
|
||||
fmt.Printf("[Async] Background processing completed for: %s - %s\n", response.Data.Singer, response.Data.Song)
|
||||
}()
|
||||
|
||||
// ========== 立即返回 JSON,使用标准 .mp3 URL ==========
|
||||
// 注意:返回标准的 .mp3 URL,file.go 会在文件不存在时自动触发流式转码
|
||||
basePath := "/cache/music/" + url.QueryEscape(response.Data.Singer+"-"+response.Data.Song)
|
||||
|
||||
return MusicItem{
|
||||
Title: response.Data.Song,
|
||||
Artist: response.Data.Singer,
|
||||
CoverURL: basePath + "/cover" + ext,
|
||||
LyricURL: basePath + "/lyric.lrc",
|
||||
AudioFullURL: basePath + "/music.mp3", // 标准 .mp3 URL
|
||||
AudioURL: basePath + "/music.mp3",
|
||||
M3U8URL: basePath + "/music.m3u8",
|
||||
Duration: 0, // 时长后台获取,先返回0
|
||||
}
|
||||
}
|
||||
|
||||
// YaohuQQMusicResponse 妖狐QQ音乐API响应结构
|
||||
type YaohuQQMusicResponse struct {
|
||||
Code int `json:"code"`
|
||||
Msg string `json:"msg"`
|
||||
Data struct {
|
||||
Songname string `json:"songname"`
|
||||
Name string `json:"name"`
|
||||
Picture string `json:"picture"`
|
||||
Musicurl string `json:"musicurl"`
|
||||
Viplrc string `json:"viplrc"` // VIP歌词URL链接
|
||||
} `json:"data"`
|
||||
}
|
||||
|
||||
// YaohuLyricResponse 妖狐歌词API响应结构
|
||||
type YaohuLyricResponse struct {
|
||||
Code int `json:"code"`
|
||||
Data struct {
|
||||
Lyric string `json:"lyric"`
|
||||
} `json:"data"`
|
||||
}
|
||||
|
||||
// fetchLyricFromYaohu 从妖狐数据QQ音乐VIP API获取歌词(备用方案)
|
||||
func fetchLyricFromYaohu(songName, artistName, dirPath string) bool {
|
||||
apiKey := "bXO9eq1pomwR1cyVhzX"
|
||||
apiURL := "https://api.yaohud.cn/api/music/qq"
|
||||
|
||||
// 构建请求URL - QQ音乐VIP接口
|
||||
requestURL := fmt.Sprintf("%s?key=%s&msg=%s&n=1&size=hq",
|
||||
apiURL,
|
||||
apiKey,
|
||||
url.QueryEscape(songName))
|
||||
|
||||
fmt.Printf("[Info] 🎵 Trying to fetch lyric from Yaohu QQ Music VIP API for: %s - %s\n", artistName, songName)
|
||||
|
||||
// 创建带超时的HTTP客户端
|
||||
client := &http.Client{
|
||||
Timeout: 10 * time.Second,
|
||||
}
|
||||
|
||||
resp, err := client.Get(requestURL)
|
||||
if err != nil {
|
||||
fmt.Printf("[Error] Yaohu QQ Music API request failed: %v\n", err)
|
||||
return false
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
fmt.Printf("[Error] Failed to read API response: %v\n", err)
|
||||
return false
|
||||
}
|
||||
|
||||
var qqResp YaohuQQMusicResponse
|
||||
err = json.Unmarshal(body, &qqResp)
|
||||
if err != nil {
|
||||
fmt.Printf("[Error] Failed to parse API response: %v\n", err)
|
||||
return false
|
||||
}
|
||||
|
||||
// 检查响应状态
|
||||
if qqResp.Code != 200 {
|
||||
fmt.Printf("[Warning] API returned error (code: %d, msg: %s)\n", qqResp.Code, qqResp.Msg)
|
||||
return false
|
||||
}
|
||||
|
||||
// 检查viplrc URL是否存在
|
||||
if qqResp.Data.Viplrc == "" {
|
||||
fmt.Printf("[Warning] No lyric URL available for: %s\n", songName)
|
||||
return false
|
||||
}
|
||||
|
||||
fmt.Printf("[Info] 🔍 Found song: %s - %s\n", qqResp.Data.Songname, qqResp.Data.Name)
|
||||
fmt.Printf("[Info] 📝 Fetching lyric from: %s\n", qqResp.Data.Viplrc)
|
||||
|
||||
// Step 2: 获取实际歌词内容
|
||||
resp2, err := client.Get(qqResp.Data.Viplrc)
|
||||
if err != nil {
|
||||
fmt.Printf("[Error] Failed to fetch lyric from viplrc URL: %v\n", err)
|
||||
return false
|
||||
}
|
||||
defer resp2.Body.Close()
|
||||
|
||||
body2, err := io.ReadAll(resp2.Body)
|
||||
if err != nil {
|
||||
fmt.Printf("[Error] Failed to read lyric response: %v\n", err)
|
||||
return false
|
||||
}
|
||||
|
||||
// viplrc URL直接返回LRC文本,不是JSON
|
||||
lyricText := string(body2)
|
||||
|
||||
// 检查歌词内容
|
||||
if lyricText == "" || len(lyricText) < 10 {
|
||||
fmt.Printf("[Warning] No lyrics returned from viplrc URL\n")
|
||||
return false
|
||||
}
|
||||
|
||||
// 将歌词写入文件
|
||||
lyricFilePath := filepath.Join(dirPath, "lyric.lrc")
|
||||
file, err := os.Create(lyricFilePath)
|
||||
if err != nil {
|
||||
fmt.Printf("[Error] Failed to create lyric file: %v\n", err)
|
||||
return false
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
// 写入歌词内容(LRC文本格式)
|
||||
_, err = file.WriteString(lyricText)
|
||||
if err != nil {
|
||||
fmt.Printf("[Error] Failed to write lyric content: %v\n", err)
|
||||
return false
|
||||
}
|
||||
|
||||
fmt.Printf("[Success] ✅ Lyric fetched from Yaohu QQ Music VIP API and saved to %s\n", lyricFilePath)
|
||||
return true
|
||||
}
|
||||
|
||||
// getRemoteMusicURLOnly 只获取远程音乐URL,不下载不处理(用于实时流式播放)
|
||||
func getRemoteMusicURLOnly(song, singer string) string {
|
||||
fmt.Printf("[Info] Getting remote music URL for: %s - %s\n", singer, song)
|
||||
|
||||
// 尝试多个 API
|
||||
apiHosts := []string{
|
||||
"https://api.yuafeng.cn",
|
||||
"https://api-v2.yuafeng.cn",
|
||||
}
|
||||
|
||||
sources := []string{"kuwo", "netease", "migu"}
|
||||
pathMap := map[string]string{
|
||||
"kuwo": "/API/ly/kwmusic.php",
|
||||
"netease": "/API/ly/wymusic.php",
|
||||
"migu": "/API/ly/mgmusic.php",
|
||||
}
|
||||
|
||||
client := &http.Client{Timeout: 15 * time.Second}
|
||||
|
||||
for _, host := range apiHosts {
|
||||
for _, source := range sources {
|
||||
path := pathMap[source]
|
||||
apiURL := fmt.Sprintf("%s%s?song=%s&singer=%s", host, path, url.QueryEscape(song), url.QueryEscape(singer))
|
||||
|
||||
resp, err := client.Get(apiURL)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
var response YuafengAPIFreeResponse
|
||||
if err := json.Unmarshal(body, &response); err != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
if response.Data.Music != "" {
|
||||
fmt.Printf("[Success] Got remote URL from %s: %s\n", source, response.Data.Music)
|
||||
return response.Data.Music
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fmt.Println("[Error] Failed to get remote music URL from all APIs")
|
||||
return ""
|
||||
}
|
||||
363
使用说明.md
Executable file
363
使用说明.md
Executable file
@@ -0,0 +1,363 @@
|
||||
# 🎵 Meow Music 使用说明
|
||||
|
||||
## 📋 功能概览
|
||||
|
||||
Meow Music 是一个完整的音乐播放和管理系统,包含以下功能:
|
||||
|
||||
### ✨ 核心功能
|
||||
|
||||
1. **用户系统**
|
||||
- 用户注册和登录
|
||||
- 密码加密存储(bcrypt)
|
||||
- Token认证机制
|
||||
|
||||
2. **音乐搜索**
|
||||
- 实时搜索音乐
|
||||
- 显示歌曲标题和艺术家
|
||||
- 搜索结果缓存
|
||||
|
||||
3. **在线播放**
|
||||
- 内置音频播放器
|
||||
- 显示当前播放信息
|
||||
- 支持标准音频控制
|
||||
|
||||
4. **我喜欢**
|
||||
- 快速收藏喜欢的歌曲
|
||||
- 查看收藏列表
|
||||
- 移除收藏
|
||||
|
||||
5. **歌单管理**
|
||||
- 创建自定义歌单
|
||||
- 添加/删除歌曲
|
||||
- 查看歌单详情
|
||||
|
||||
---
|
||||
|
||||
## 🚀 快速开始
|
||||
|
||||
### 1. 启动服务器
|
||||
|
||||
#### Windows:
|
||||
```powershell
|
||||
# 方式1:双击启动
|
||||
双击 start.bat
|
||||
|
||||
# 方式2:命令行启动
|
||||
cd d:\esp32-music-server\Meow\MeowEmbeddedMusicServer
|
||||
go run .
|
||||
```
|
||||
|
||||
#### Linux/macOS:
|
||||
```bash
|
||||
cd /path/to/MeowEmbeddedMusicServer
|
||||
./start.sh
|
||||
# 或
|
||||
go run .
|
||||
```
|
||||
|
||||
### 2. 访问应用
|
||||
|
||||
打开浏览器,访问:
|
||||
- **主应用**: http://localhost:2233
|
||||
- **测试版本**: http://localhost:2233/test
|
||||
- **经典界面**: http://localhost:2233/classic
|
||||
|
||||
---
|
||||
|
||||
## 📖 使用指南
|
||||
|
||||
### 第一次使用
|
||||
|
||||
1. **注册账户**
|
||||
- 访问 http://localhost:2233
|
||||
- 点击"注册"标签
|
||||
- 填写:用户名、邮箱、密码(至少6位)
|
||||
- 点击"注册"按钮
|
||||
- 注册成功后会自动进入主界面
|
||||
|
||||
2. **登录**
|
||||
- 使用注册的用户名和密码登录
|
||||
- **注意**:登录时使用**用户名**,不是邮箱
|
||||
|
||||
### 搜索音乐
|
||||
|
||||
1. 在搜索框输入歌曲名或艺术家名
|
||||
2. 按回车键开始搜索
|
||||
3. 搜索结果会显示在下方
|
||||
|
||||
### 播放音乐
|
||||
|
||||
1. 在搜索结果中点击"播放"按钮
|
||||
2. 底部会出现播放器
|
||||
3. 使用播放器控制播放、暂停、音量等
|
||||
|
||||
### 收藏音乐
|
||||
|
||||
1. 点击歌曲旁边的"喜欢"按钮
|
||||
2. 歌曲会自动添加到"我喜欢"列表
|
||||
3. 切换到"我喜欢"标签查看所有收藏
|
||||
|
||||
### 管理歌单
|
||||
|
||||
1. 切换到"我的歌单"标签
|
||||
2. 点击"+ 新建歌单"创建新歌单
|
||||
3. 输入歌单名称和描述
|
||||
4. 点击歌单查看详情(开发中)
|
||||
|
||||
---
|
||||
|
||||
## 🔧 API接口
|
||||
|
||||
### 用户认证
|
||||
|
||||
#### 注册
|
||||
```http
|
||||
POST /api/auth/register
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"username": "用户名",
|
||||
"email": "邮箱",
|
||||
"password": "密码"
|
||||
}
|
||||
```
|
||||
|
||||
#### 登录
|
||||
```http
|
||||
POST /api/auth/login
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"username": "用户名",
|
||||
"password": "密码"
|
||||
}
|
||||
```
|
||||
|
||||
#### 获取当前用户
|
||||
```http
|
||||
GET /api/auth/me
|
||||
Authorization: Bearer {token}
|
||||
```
|
||||
|
||||
#### 登出
|
||||
```http
|
||||
POST /api/auth/logout
|
||||
Authorization: Bearer {token}
|
||||
```
|
||||
|
||||
### 音乐搜索
|
||||
|
||||
#### 搜索歌曲
|
||||
```http
|
||||
GET /api/search?query={关键词}
|
||||
```
|
||||
|
||||
### 收藏管理
|
||||
|
||||
#### 添加到收藏
|
||||
```http
|
||||
POST /api/favorite/add
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"title": "歌曲名",
|
||||
"artist": "艺术家",
|
||||
"url": "播放链接"
|
||||
}
|
||||
```
|
||||
|
||||
#### 获取收藏列表
|
||||
```http
|
||||
GET /api/favorite/list
|
||||
```
|
||||
|
||||
#### 从收藏移除
|
||||
```http
|
||||
POST /api/favorite/remove
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"title": "歌曲名",
|
||||
"artist": "艺术家"
|
||||
}
|
||||
```
|
||||
|
||||
### 歌单管理
|
||||
|
||||
#### 获取用户歌单
|
||||
```http
|
||||
GET /api/user/playlists
|
||||
Authorization: Bearer {token}
|
||||
```
|
||||
|
||||
#### 创建歌单
|
||||
```http
|
||||
POST /api/user/playlists/create
|
||||
Authorization: Bearer {token}
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"name": "歌单名称",
|
||||
"description": "歌单描述"
|
||||
}
|
||||
```
|
||||
|
||||
#### 添加歌曲到歌单
|
||||
```http
|
||||
POST /api/user/playlists/add-song?playlist_id={歌单ID}
|
||||
Authorization: Bearer {token}
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"title": "歌曲名",
|
||||
"artist": "艺术家",
|
||||
"url": "播放链接"
|
||||
}
|
||||
```
|
||||
|
||||
#### 从歌单移除歌曲
|
||||
```http
|
||||
DELETE /api/user/playlists/remove-song?playlist_id={歌单ID}&title={歌曲名}&artist={艺术家}
|
||||
Authorization: Bearer {token}
|
||||
```
|
||||
|
||||
#### 删除歌单
|
||||
```http
|
||||
DELETE /api/user/playlists/delete?playlist_id={歌单ID}
|
||||
Authorization: Bearer {token}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📁 文件结构
|
||||
|
||||
```
|
||||
MeowEmbeddedMusicServer/
|
||||
├── main.go # 主程序入口
|
||||
├── user.go # 用户管理
|
||||
├── playlist.go # 歌单管理
|
||||
├── index.go # 路由处理
|
||||
├── struct.go # 数据结构
|
||||
├── start.bat # Windows启动脚本
|
||||
├── start.sh # Linux/macOS启动脚本
|
||||
├── files/ # 数据文件目录
|
||||
│ ├── users.json # 用户数据
|
||||
│ ├── user_playlists.json # 用户歌单数据
|
||||
│ └── playlists.json # 遗留歌单数据
|
||||
└── theme/ # 前端文件
|
||||
├── full-app.html # 完整应用(主界面)
|
||||
├── test-app.html # 测试版本
|
||||
├── simple-app.html # 简化版本
|
||||
└── index.html # 经典界面
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## ⚙️ 配置
|
||||
|
||||
### 修改端口
|
||||
|
||||
编辑 `main.go`,找到:
|
||||
```go
|
||||
port := "2233"
|
||||
```
|
||||
修改为您想要的端口号。
|
||||
|
||||
### 数据存储位置
|
||||
|
||||
所有数据存储在 `./files/` 目录下:
|
||||
- `users.json` - 用户账户信息(包含加密密码)
|
||||
- `user_playlists.json` - 用户创建的歌单
|
||||
- `playlists.json` - 遗留的公共歌单
|
||||
|
||||
---
|
||||
|
||||
## 🐛 故障排除
|
||||
|
||||
### 问题1:端口被占用
|
||||
```
|
||||
listen tcp :2233: bind: Only one usage of each socket address...
|
||||
```
|
||||
|
||||
**解决方法:**
|
||||
```powershell
|
||||
# 查找占用端口的进程
|
||||
netstat -ano | findstr :2233
|
||||
|
||||
# 关闭进程(替换{PID}为实际进程ID)
|
||||
taskkill /F /PID {PID}
|
||||
```
|
||||
|
||||
### 问题2:登录失败
|
||||
```
|
||||
invalid username or password
|
||||
```
|
||||
|
||||
**可能原因:**
|
||||
1. 用户名或密码错误
|
||||
2. 使用了邮箱而不是用户名登录
|
||||
3. 服务器重启后数据未正确加载
|
||||
|
||||
**解决方法:**
|
||||
- 确认使用**用户名**登录,不是邮箱
|
||||
- 检查 `files/users.json` 是否存在且格式正确
|
||||
- 重新注册一个新账户测试
|
||||
|
||||
### 问题3:搜索无结果
|
||||
**可能原因:**
|
||||
- 网络连接问题
|
||||
- 搜索关键词不正确
|
||||
- 音乐源服务不可用
|
||||
|
||||
**解决方法:**
|
||||
- 检查网络连接
|
||||
- 尝试更常见的歌曲名
|
||||
- 查看服务器日志
|
||||
|
||||
### 问题4:无法播放音乐
|
||||
**可能原因:**
|
||||
- 音乐链接失效
|
||||
- 浏览器不支持音频格式
|
||||
- 跨域问题
|
||||
|
||||
**解决方法:**
|
||||
- 尝试播放其他歌曲
|
||||
- 使用Chrome或Firefox浏览器
|
||||
- 检查浏览器控制台错误信息
|
||||
|
||||
---
|
||||
|
||||
## 🔒 安全建议
|
||||
|
||||
1. **不要在公网暴露此服务** - 仅供本地或局域网使用
|
||||
2. **定期备份数据** - 备份 `files/` 目录
|
||||
3. **使用强密码** - 建议至少8位,包含字母和数字
|
||||
4. **不要共享Token** - 登录凭证是私密的
|
||||
|
||||
---
|
||||
|
||||
## 📞 支持
|
||||
|
||||
- **QQ交流群**: 865754861(喵波音律-音乐家园)
|
||||
- **项目问题**: 查看服务器日志进行调试
|
||||
|
||||
---
|
||||
|
||||
## 🎉 更新日志
|
||||
|
||||
### v2.0.0 (2025-11-23)
|
||||
- ✅ 添加完整的用户系统
|
||||
- ✅ 实现歌单管理功能
|
||||
- ✅ 修复死锁问题
|
||||
- ✅ 修复密码存储问题
|
||||
- ✅ 创建完整的Web界面
|
||||
- ✅ 优化用户体验
|
||||
|
||||
### v1.0.0 (初始版本)
|
||||
- 基础音乐搜索和播放
|
||||
- ESP32设备支持
|
||||
- 简单收藏功能
|
||||
|
||||
---
|
||||
|
||||
**祝您使用愉快!** 🎵
|
||||
231
快速开始.md
Executable file
231
快速开始.md
Executable file
@@ -0,0 +1,231 @@
|
||||
# 🚀 快速开始 - 3分钟部署指南
|
||||
|
||||
## 📦 准备工作
|
||||
|
||||
### 1. 确认 Go 已安装
|
||||
|
||||
打开终端,输入:
|
||||
```bash
|
||||
go version
|
||||
```
|
||||
|
||||
✅ 看到版本号(如 `go version go1.21.x`)- 已安装,继续下一步
|
||||
❌ 提示未找到命令 - 需要先安装Go
|
||||
|
||||
**安装 Go:**
|
||||
- Windows: https://golang.org/dl/ (下载安装包)
|
||||
- macOS: `brew install go`
|
||||
- Linux: `sudo apt install golang-go`
|
||||
|
||||
---
|
||||
|
||||
## 🎯 三步部署
|
||||
|
||||
### Windows 用户
|
||||
|
||||
#### 第一步:打开项目目录
|
||||
```bash
|
||||
cd d:\esp32-music-server\Meow\MeowEmbeddedMusicServer
|
||||
```
|
||||
|
||||
#### 第二步:双击启动
|
||||
找到 `start.bat` 文件,双击运行
|
||||
|
||||
#### 第三步:访问应用
|
||||
浏览器打开:http://localhost:2233/app
|
||||
|
||||
**就这么简单!** 🎉
|
||||
|
||||
---
|
||||
|
||||
### Linux / macOS 用户
|
||||
|
||||
#### 第一步:进入项目目录
|
||||
```bash
|
||||
cd /path/to/MeowEmbeddedMusicServer
|
||||
```
|
||||
|
||||
#### 第二步:添加执行权限并启动
|
||||
```bash
|
||||
chmod +x start.sh
|
||||
./start.sh
|
||||
```
|
||||
|
||||
#### 第三步:访问应用
|
||||
浏览器打开:http://localhost:2233/app
|
||||
|
||||
**完成!** 🎉
|
||||
|
||||
---
|
||||
|
||||
## 🎵 首次使用
|
||||
|
||||
1. **注册账户**
|
||||
- 访问 http://localhost:2233/app
|
||||
- 点击右侧"注册"标签
|
||||
- 填写:用户名、邮箱、密码
|
||||
- 点击"注册"按钮
|
||||
|
||||
2. **搜索音乐**
|
||||
- 登录后,在搜索框输入歌曲名
|
||||
- 例如:"告白气球"
|
||||
- 点击"搜索"
|
||||
|
||||
3. **播放音乐**
|
||||
- 搜索结果出现后
|
||||
- 点击"▶ 播放"按钮
|
||||
|
||||
4. **添加收藏**
|
||||
- 在搜索结果页
|
||||
- 使用下拉菜单选择"我喜欢"
|
||||
- 歌曲自动添加到收藏
|
||||
|
||||
5. **创建歌单**
|
||||
- 左侧边栏"我的歌单"旁
|
||||
- 点击"+"号
|
||||
- 输入歌单名称
|
||||
- 确认创建
|
||||
|
||||
---
|
||||
|
||||
## 🔧 常见问题
|
||||
|
||||
### Q: 端口被占用怎么办?
|
||||
|
||||
**Windows:**
|
||||
```bash
|
||||
netstat -ano | findstr :2233
|
||||
taskkill /PID <进程ID> /F
|
||||
```
|
||||
|
||||
**Linux/macOS:**
|
||||
```bash
|
||||
lsof -i :2233
|
||||
kill -9 <PID>
|
||||
```
|
||||
|
||||
或修改端口:编辑 `.env` 文件,将 `PORT=2233` 改为 `PORT=3000`
|
||||
|
||||
---
|
||||
|
||||
### Q: 依赖下载失败?
|
||||
|
||||
**中国大陆用户**需要配置Go代理:
|
||||
|
||||
```bash
|
||||
go env -w GOPROXY=https://goproxy.cn,direct
|
||||
```
|
||||
|
||||
然后重新运行启动脚本
|
||||
|
||||
---
|
||||
|
||||
### Q: 如何停止服务器?
|
||||
|
||||
在启动的终端窗口中按 `Ctrl + C`
|
||||
|
||||
---
|
||||
|
||||
### Q: 如何让局域网其他设备访问?
|
||||
|
||||
1. 找到本机IP(Windows: `ipconfig`,Linux/Mac: `ifconfig`)
|
||||
2. 修改 `.env` 文件:
|
||||
```env
|
||||
WEBSITE_URL=http://你的IP:2233
|
||||
```
|
||||
3. 重启服务器
|
||||
4. 其他设备访问:`http://你的IP:2233/app`
|
||||
|
||||
---
|
||||
|
||||
## 📚 更多文档
|
||||
|
||||
- **详细部署指南**: 查看 `本地部署指南.md`
|
||||
- **API文档**: 查看 `USER_SYSTEM_README.md`
|
||||
- **功能说明**: 查看 `新功能说明.md`
|
||||
|
||||
---
|
||||
|
||||
## 💡 使用技巧
|
||||
|
||||
### 快捷键
|
||||
- 搜索框按 `Enter` 键可以快速搜索
|
||||
- `Ctrl + C` 停止服务器
|
||||
|
||||
### 推荐浏览器
|
||||
- Chrome / Edge
|
||||
- Firefox
|
||||
- Safari
|
||||
|
||||
### 数据备份
|
||||
定期备份 `files/` 目录,保存用户数据和歌单
|
||||
|
||||
---
|
||||
|
||||
## 🎯 目录结构
|
||||
|
||||
```
|
||||
MeowEmbeddedMusicServer/
|
||||
├── start.bat ← Windows启动(双击)
|
||||
├── start.sh ← Linux/Mac启动
|
||||
├── .env ← 配置文件(可选)
|
||||
├── theme/
|
||||
│ └── music-app.html ← 新版界面
|
||||
└── files/ ← 数据存储(自动创建)
|
||||
├── users.json ← 用户数据
|
||||
└── user_playlists.json ← 歌单数据
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## ✅ 快速检查清单
|
||||
|
||||
部署前:
|
||||
- [ ] Go 已安装(1.19+)
|
||||
- [ ] 项目已下载到本地
|
||||
- [ ] 端口 2233 未被占用
|
||||
|
||||
部署后:
|
||||
- [ ] 启动脚本运行成功
|
||||
- [ ] 浏览器可以打开 http://localhost:2233/app
|
||||
- [ ] 可以注册新账户
|
||||
- [ ] 可以搜索音乐
|
||||
|
||||
全部打勾 = 部署成功!🎉
|
||||
|
||||
---
|
||||
|
||||
## 🆘 需要帮助?
|
||||
|
||||
### 查看日志
|
||||
启动后的终端窗口会显示所有日志信息
|
||||
|
||||
### 社区支持
|
||||
- QQ群:865754861(喵波音律-音乐家园)
|
||||
- 查看详细文档:`本地部署指南.md`
|
||||
|
||||
### 重新开始
|
||||
如果遇到问题,可以:
|
||||
1. 关闭服务器(Ctrl+C)
|
||||
2. 删除 `files/` 目录
|
||||
3. 重新运行启动脚本
|
||||
|
||||
---
|
||||
|
||||
## 🎉 恭喜!
|
||||
|
||||
你现在拥有一个属于自己的音乐服务器了!
|
||||
|
||||
**开始享受音乐吧!** 🎵✨
|
||||
|
||||
```
|
||||
╔═══════════════════════════════════╗
|
||||
║ 新版应用地址 ║
|
||||
║ http://localhost:2233/app ║
|
||||
╚═══════════════════════════════════╝
|
||||
```
|
||||
|
||||
**下一步:**
|
||||
1. 🎵 搜索你喜欢的音乐
|
||||
2. ❤️ 创建你的收藏歌单
|
||||
3. 📱 让朋友也来试试(局域网访问)
|
||||
222
新功能说明.md
Executable file
222
新功能说明.md
Executable file
@@ -0,0 +1,222 @@
|
||||
# 🎵 Meow Music - 用户系统升级完成
|
||||
|
||||
## 🎉 新增功能
|
||||
|
||||
### 1. 完整的用户认证系统
|
||||
- ✅ **用户注册** - 使用用户名、邮箱和密码注册账户
|
||||
- ✅ **用户登录** - 安全的登录验证
|
||||
- ✅ **会话管理** - 基于Token的身份认证
|
||||
- ✅ **密码加密** - 使用bcrypt加密存储密码
|
||||
|
||||
### 2. 个人歌单管理
|
||||
- ✅ **我喜欢** - 每个用户独立的收藏夹
|
||||
- ✅ **创建歌单** - 自定义歌单名称和描述
|
||||
- ✅ **添加歌曲** - 将搜索到的歌曲添加到歌单
|
||||
- ✅ **删除歌曲** - 从歌单中移除歌曲
|
||||
- ✅ **删除歌单** - 删除自定义歌单("我喜欢"除外)
|
||||
|
||||
### 3. 现代化前端界面
|
||||
- ✅ **React + TailwindCSS** - 现代化UI设计
|
||||
- ✅ **响应式布局** - 完美支持桌面和移动设备
|
||||
- ✅ **实时搜索** - 快速搜索在线音乐
|
||||
- ✅ **在线播放** - 直接在浏览器中播放音乐
|
||||
- ✅ **渐变背景** - 美观的紫色渐变主题
|
||||
|
||||
## 📁 新增文件
|
||||
|
||||
### 后端文件
|
||||
```
|
||||
MeowEmbeddedMusicServer/
|
||||
├── struct.go (更新) 新增用户和歌单数据结构
|
||||
├── user.go (新增) 用户认证和管理
|
||||
├── playlist.go (更新) 扩展歌单管理功能
|
||||
├── main.go (更新) 添加新的API路由
|
||||
├── go.mod (更新) 添加bcrypt依赖
|
||||
└── index.go (更新) 支持新应用路由
|
||||
```
|
||||
|
||||
### 前端文件
|
||||
```
|
||||
theme/
|
||||
└── music-app.html (新增) 完整的React单页应用
|
||||
```
|
||||
|
||||
### 配置和文档
|
||||
```
|
||||
├── USER_SYSTEM_README.md (新增) 详细使用文档
|
||||
├── 新功能说明.md (新增) 功能概览
|
||||
└── start.bat (新增) 快速启动脚本
|
||||
```
|
||||
|
||||
### 数据文件(运行时自动创建)
|
||||
```
|
||||
files/
|
||||
├── users.json 用户账户数据
|
||||
├── user_playlists.json 用户歌单数据
|
||||
└── playlists.json 旧版歌单(兼容)
|
||||
```
|
||||
|
||||
## 🚀 快速开始
|
||||
|
||||
### 方法1:使用启动脚本(推荐)
|
||||
```batch
|
||||
# Windows
|
||||
start.bat
|
||||
```
|
||||
|
||||
### 方法2:手动启动
|
||||
```bash
|
||||
# 安装依赖
|
||||
go mod tidy
|
||||
|
||||
# 启动服务器
|
||||
go run .
|
||||
```
|
||||
|
||||
### 访问应用
|
||||
1. **新版应用(推荐)**: http://localhost:2233/app
|
||||
2. **旧版界面**: http://localhost:2233/
|
||||
|
||||
## 🎨 界面预览
|
||||
|
||||
### 登录/注册页面
|
||||
- 渐变紫色背景
|
||||
- 玻璃拟态效果
|
||||
- 切换登录/注册模式
|
||||
- 实时表单验证
|
||||
|
||||
### 主应用界面
|
||||
- **侧边栏**:显示搜索、我喜欢、自定义歌单
|
||||
- **主内容区**:
|
||||
- 搜索音乐界面
|
||||
- 歌单详情展示
|
||||
- 音乐播放控制
|
||||
- **顶部导航**:用户信息、退出登录
|
||||
|
||||
### 功能特性
|
||||
- 🎵 实时音乐搜索
|
||||
- ▶️ 在线播放音乐
|
||||
- ❤️ 添加到"我喜欢"
|
||||
- 📋 创建自定义歌单
|
||||
- 🎯 快速添加到歌单
|
||||
- 🗑️ 删除歌曲/歌单
|
||||
|
||||
## 🔌 API端点
|
||||
|
||||
### 用户认证
|
||||
```
|
||||
POST /api/auth/register 注册
|
||||
POST /api/auth/login 登录
|
||||
POST /api/auth/logout 登出
|
||||
GET /api/auth/me 获取当前用户
|
||||
```
|
||||
|
||||
### 歌单管理(需要登录)
|
||||
```
|
||||
GET /api/user/playlists 获取所有歌单
|
||||
POST /api/user/playlists/create 创建歌单
|
||||
POST /api/user/playlists/add-song 添加歌曲
|
||||
DELETE /api/user/playlists/remove-song 移除歌曲
|
||||
DELETE /api/user/playlists/delete 删除歌单
|
||||
```
|
||||
|
||||
### 音乐搜索
|
||||
```
|
||||
GET /stream_pcm?song=歌名&singer=歌手 搜索音乐
|
||||
```
|
||||
|
||||
### 旧版API(向后兼容)
|
||||
```
|
||||
POST /api/favorite/add 添加收藏
|
||||
POST /api/favorite/remove 移除收藏
|
||||
GET /api/favorite/list 收藏列表
|
||||
GET /api/favorite/check 检查收藏
|
||||
```
|
||||
|
||||
## 💡 使用示例
|
||||
|
||||
### 1. 注册新用户
|
||||
访问 http://localhost:2233/app,点击"注册":
|
||||
- 输入用户名:`musiclover`
|
||||
- 输入邮箱:`lover@music.com`
|
||||
- 输入密码:`password123`
|
||||
- 点击"注册"
|
||||
|
||||
### 2. 搜索音乐
|
||||
登录后,在搜索框输入:
|
||||
- 歌曲名:`告白气球`
|
||||
- 点击"搜索"
|
||||
|
||||
### 3. 播放音乐
|
||||
搜索结果显示后:
|
||||
- 点击"▶ 播放"按钮即可播放
|
||||
|
||||
### 4. 添加到歌单
|
||||
搜索到音乐后:
|
||||
- 使用下拉菜单选择"我喜欢"
|
||||
- 歌曲自动添加到歌单
|
||||
|
||||
### 5. 创建自定义歌单
|
||||
在侧边栏"我的歌单"旁:
|
||||
- 点击"+"按钮
|
||||
- 输入歌单名称
|
||||
- 确认创建
|
||||
|
||||
## 🔒 安全特性
|
||||
|
||||
- ✅ 密码使用bcrypt加密
|
||||
- ✅ Token-based会话管理
|
||||
- ✅ API请求认证保护
|
||||
- ✅ 用户数据隔离
|
||||
- ✅ 安全的密码存储
|
||||
|
||||
## 📱 兼容性
|
||||
|
||||
- ✅ 现代浏览器(Chrome, Firefox, Safari, Edge)
|
||||
- ✅ 移动设备浏览器
|
||||
- ✅ 向后兼容旧版API
|
||||
- ✅ ESP32设备访问支持
|
||||
|
||||
## 🎯 技术栈
|
||||
|
||||
### 后端
|
||||
- Go 1.25
|
||||
- bcrypt 密码加密
|
||||
- JSON 数据存储
|
||||
- Token 认证
|
||||
|
||||
### 前端
|
||||
- React 18
|
||||
- TailwindCSS
|
||||
- 原生JavaScript
|
||||
- 单文件应用(无需构建)
|
||||
|
||||
## 🐛 已知限制
|
||||
|
||||
1. **数据存储**:使用JSON文件存储,适合小规模使用
|
||||
2. **Token过期**:Token不会自动过期,关闭浏览器需重新登录
|
||||
3. **并发**:多用户同时操作时有文件锁保护
|
||||
|
||||
## 🔮 未来计划
|
||||
|
||||
- [ ] SQLite数据库支持
|
||||
- [ ] Token自动刷新
|
||||
- [ ] 歌单分享功能
|
||||
- [ ] 播放历史记录
|
||||
- [ ] 歌词同步显示
|
||||
- [ ] 主题切换(暗色/亮色)
|
||||
- [ ] 社交功能(关注、评论)
|
||||
|
||||
## 📞 技术支持
|
||||
|
||||
遇到问题?
|
||||
1. 查看 `USER_SYSTEM_README.md` 详细文档
|
||||
2. 检查服务器控制台日志
|
||||
3. 确认所有依赖已安装
|
||||
4. 验证端口2233未被占用
|
||||
|
||||
---
|
||||
|
||||
**开始享受您的专属音乐平台吧!** 🎵✨
|
||||
|
||||
喵波音律-音乐家园QQ交流群:865754861
|
||||
493
本地部署指南.md
Executable file
493
本地部署指南.md
Executable file
@@ -0,0 +1,493 @@
|
||||
# 🚀 Meow Music Server - 本地部署指南
|
||||
|
||||
## 📋 系统要求
|
||||
|
||||
### 必需环境
|
||||
- **Go语言**: 1.19 或更高版本
|
||||
- **操作系统**: Windows / Linux / macOS
|
||||
- **浏览器**: Chrome / Firefox / Edge / Safari (现代浏览器)
|
||||
|
||||
### 可选工具(用于音频处理功能)
|
||||
- **FFmpeg**: 用于音频压缩和转换
|
||||
- **FFprobe**: 用于获取音频时长
|
||||
|
||||
---
|
||||
|
||||
## 🔧 Windows 本地部署
|
||||
|
||||
### 步骤 1: 检查 Go 环境
|
||||
|
||||
打开命令提示符(CMD)或 PowerShell,检查 Go 是否已安装:
|
||||
|
||||
```bash
|
||||
go version
|
||||
```
|
||||
|
||||
**如果未安装 Go:**
|
||||
1. 访问 https://golang.org/dl/
|
||||
2. 下载 Windows 安装包
|
||||
3. 运行安装程序
|
||||
4. 重新打开终端验证安装
|
||||
|
||||
### 步骤 2: 进入项目目录
|
||||
|
||||
```bash
|
||||
cd d:\esp32-music-server\Meow\MeowEmbeddedMusicServer
|
||||
```
|
||||
|
||||
### 步骤 3: 安装依赖
|
||||
|
||||
```bash
|
||||
go mod tidy
|
||||
```
|
||||
|
||||
### 步骤 4: 配置环境变量(可选)
|
||||
|
||||
复制配置文件模板:
|
||||
```bash
|
||||
copy .env.example .env
|
||||
```
|
||||
|
||||
编辑 `.env` 文件(使用记事本或其他编辑器):
|
||||
```env
|
||||
# 服务器端口
|
||||
PORT=2233
|
||||
|
||||
# 网站信息
|
||||
WEBSITE_NAME_CN=我的音乐服务器
|
||||
WEBSITE_NAME_EN=My Music Server
|
||||
|
||||
# API 源(默认已配置,无需修改)
|
||||
API_SOURCES=kuwo
|
||||
API_SOURCES_1=netease
|
||||
API_SOURCES_2=migu
|
||||
API_SOURCES_3=baidu
|
||||
```
|
||||
|
||||
### 步骤 5: 启动服务器
|
||||
|
||||
**方式 1:使用启动脚本(推荐)**
|
||||
```bash
|
||||
start.bat
|
||||
```
|
||||
|
||||
**方式 2:手动启动**
|
||||
```bash
|
||||
go run .
|
||||
```
|
||||
|
||||
### 步骤 6: 访问应用
|
||||
|
||||
服务器启动后,在浏览器中访问:
|
||||
|
||||
- **新版用户界面**: http://localhost:2233/app
|
||||
- **经典界面**: http://localhost:2233/
|
||||
|
||||
### 步骤 7: 首次使用
|
||||
|
||||
1. 打开浏览器访问 http://localhost:2233/app
|
||||
2. 点击"注册"创建账户
|
||||
3. 填写用户名、邮箱和密码
|
||||
4. 注册成功后自动登录
|
||||
5. 开始搜索和收藏音乐!
|
||||
|
||||
---
|
||||
|
||||
## 🐧 Linux / macOS 部署
|
||||
|
||||
### 步骤 1: 检查 Go 环境
|
||||
|
||||
```bash
|
||||
go version
|
||||
```
|
||||
|
||||
**如果未安装:**
|
||||
```bash
|
||||
# Ubuntu/Debian
|
||||
sudo apt update
|
||||
sudo apt install golang-go
|
||||
|
||||
# macOS (使用 Homebrew)
|
||||
brew install go
|
||||
|
||||
# CentOS/RHEL
|
||||
sudo yum install golang
|
||||
```
|
||||
|
||||
### 步骤 2: 进入项目目录
|
||||
|
||||
```bash
|
||||
cd /path/to/MeowEmbeddedMusicServer
|
||||
```
|
||||
|
||||
### 步骤 3: 安装依赖
|
||||
|
||||
```bash
|
||||
go mod tidy
|
||||
```
|
||||
|
||||
### 步骤 4: 配置环境
|
||||
|
||||
```bash
|
||||
cp .env.example .env
|
||||
nano .env # 或使用 vim/其他编辑器
|
||||
```
|
||||
|
||||
### 步骤 5: 启动服务器
|
||||
|
||||
```bash
|
||||
go run .
|
||||
```
|
||||
|
||||
或者后台运行:
|
||||
```bash
|
||||
nohup go run . > server.log 2>&1 &
|
||||
```
|
||||
|
||||
### 步骤 6: 访问应用
|
||||
|
||||
在浏览器中打开:
|
||||
- http://localhost:2233/app
|
||||
|
||||
---
|
||||
|
||||
## 🏗️ 生产环境部署
|
||||
|
||||
### 编译可执行文件
|
||||
|
||||
**Windows:**
|
||||
```bash
|
||||
go build -o meow-music-server.exe
|
||||
meow-music-server.exe
|
||||
```
|
||||
|
||||
**Linux/macOS:**
|
||||
```bash
|
||||
go build -o meow-music-server
|
||||
./meow-music-server
|
||||
```
|
||||
|
||||
### 使用 systemd 服务(Linux)
|
||||
|
||||
创建服务文件 `/etc/systemd/system/meow-music.service`:
|
||||
|
||||
```ini
|
||||
[Unit]
|
||||
Description=Meow Music Server
|
||||
After=network.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
User=your_username
|
||||
WorkingDirectory=/path/to/MeowEmbeddedMusicServer
|
||||
ExecStart=/path/to/MeowEmbeddedMusicServer/meow-music-server
|
||||
Restart=on-failure
|
||||
RestartSec=10
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
```
|
||||
|
||||
启动服务:
|
||||
```bash
|
||||
sudo systemctl daemon-reload
|
||||
sudo systemctl start meow-music
|
||||
sudo systemctl enable meow-music
|
||||
```
|
||||
|
||||
查看状态:
|
||||
```bash
|
||||
sudo systemctl status meow-music
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🌐 局域网访问配置
|
||||
|
||||
### 步骤 1: 找到本机 IP 地址
|
||||
|
||||
**Windows:**
|
||||
```bash
|
||||
ipconfig
|
||||
```
|
||||
查找 "IPv4 地址",例如:192.168.1.100
|
||||
|
||||
**Linux/macOS:**
|
||||
```bash
|
||||
ifconfig
|
||||
# 或
|
||||
ip addr show
|
||||
```
|
||||
|
||||
### 步骤 2: 修改 .env 配置
|
||||
|
||||
```env
|
||||
WEBSITE_URL=http://192.168.1.100:2233
|
||||
EMBEDDED_WEBSITE_URL=http://192.168.1.100:2233
|
||||
```
|
||||
|
||||
### 步骤 3: 防火墙设置
|
||||
|
||||
**Windows 防火墙:**
|
||||
1. 控制面板 → Windows Defender 防火墙
|
||||
2. 高级设置 → 入站规则 → 新建规则
|
||||
3. 选择"端口" → TCP → 特定本地端口 → 2233
|
||||
4. 允许连接 → 完成
|
||||
|
||||
**Linux (UFW):**
|
||||
```bash
|
||||
sudo ufw allow 2233/tcp
|
||||
sudo ufw reload
|
||||
```
|
||||
|
||||
### 步骤 4: 其他设备访问
|
||||
|
||||
在同一局域网的其他设备浏览器中访问:
|
||||
```
|
||||
http://192.168.1.100:2233/app
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📁 目录结构说明
|
||||
|
||||
部署后的目录结构:
|
||||
|
||||
```
|
||||
MeowEmbeddedMusicServer/
|
||||
├── main.go # 主程序入口
|
||||
├── user.go # 用户认证模块
|
||||
├── playlist.go # 歌单管理
|
||||
├── api.go # 音乐搜索API
|
||||
├── helper.go # 工具函数
|
||||
├── struct.go # 数据结构
|
||||
├── go.mod # Go依赖配置
|
||||
├── .env # 环境配置(需创建)
|
||||
├── start.bat # Windows启动脚本
|
||||
│
|
||||
├── theme/ # 前端界面
|
||||
│ ├── music-app.html # 新版用户界面
|
||||
│ └── index.html # 经典界面
|
||||
│
|
||||
├── files/ # 数据存储目录(自动创建)
|
||||
│ ├── users.json # 用户数据
|
||||
│ ├── user_playlists.json # 用户歌单
|
||||
│ └── playlists.json # 全局歌单(兼容)
|
||||
│
|
||||
└── cache/ # 音乐缓存(自动创建)
|
||||
└── music/ # 下载的音乐文件
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🔍 故障排除
|
||||
|
||||
### 问题 1: 端口被占用
|
||||
|
||||
**错误信息**: `bind: address already in use`
|
||||
|
||||
**解决方法**:
|
||||
|
||||
**Windows:**
|
||||
```bash
|
||||
# 查看占用端口的进程
|
||||
netstat -ano | findstr :2233
|
||||
|
||||
# 结束进程(替换PID)
|
||||
taskkill /PID <进程ID> /F
|
||||
```
|
||||
|
||||
**Linux/macOS:**
|
||||
```bash
|
||||
# 查看占用端口的进程
|
||||
lsof -i :2233
|
||||
|
||||
# 结束进程
|
||||
kill -9 <PID>
|
||||
```
|
||||
|
||||
或者修改 `.env` 文件使用其他端口:
|
||||
```env
|
||||
PORT=3000
|
||||
```
|
||||
|
||||
### 问题 2: 无法访问页面
|
||||
|
||||
**检查清单**:
|
||||
- [ ] 服务器是否正常启动?
|
||||
- [ ] 浏览器地址是否正确?
|
||||
- [ ] 防火墙是否允许端口访问?
|
||||
- [ ] 端口号是否正确(默认2233)?
|
||||
|
||||
### 问题 3: 依赖下载失败
|
||||
|
||||
**错误信息**: `go: downloading ... failed`
|
||||
|
||||
**解决方法**:
|
||||
|
||||
设置 Go 代理(中国大陆用户):
|
||||
```bash
|
||||
# Windows PowerShell
|
||||
$env:GOPROXY="https://goproxy.cn,direct"
|
||||
|
||||
# Windows CMD
|
||||
set GOPROXY=https://goproxy.cn,direct
|
||||
|
||||
# Linux/macOS
|
||||
export GOPROXY=https://goproxy.cn,direct
|
||||
```
|
||||
|
||||
永久设置:
|
||||
```bash
|
||||
go env -w GOPROXY=https://goproxy.cn,direct
|
||||
```
|
||||
|
||||
### 问题 4: 找不到 .env 文件
|
||||
|
||||
**解决方法**:
|
||||
|
||||
如果 `.env` 文件不存在,服务器会使用默认配置。可以手动创建:
|
||||
|
||||
```bash
|
||||
# Windows
|
||||
copy .env.example .env
|
||||
|
||||
# Linux/macOS
|
||||
cp .env.example .env
|
||||
```
|
||||
|
||||
### 问题 5: 搜索不到音乐
|
||||
|
||||
**可能原因**:
|
||||
- API源暂时不可用
|
||||
- 网络连接问题
|
||||
- 歌曲名称输入错误
|
||||
|
||||
**解决方法**:
|
||||
1. 检查网络连接
|
||||
2. 尝试不同的歌曲名称
|
||||
3. 等待片刻后重试
|
||||
4. 查看服务器日志确认API响应
|
||||
|
||||
---
|
||||
|
||||
## 📊 性能优化
|
||||
|
||||
### 1. 编译优化
|
||||
|
||||
```bash
|
||||
# 编译时优化
|
||||
go build -ldflags="-s -w" -o meow-music-server
|
||||
```
|
||||
|
||||
### 2. 缓存目录
|
||||
|
||||
定期清理 `cache/` 目录中的旧文件,避免占用过多磁盘空间。
|
||||
|
||||
### 3. 数据备份
|
||||
|
||||
定期备份 `files/` 目录:
|
||||
```bash
|
||||
# Windows
|
||||
xcopy /E /I files files_backup
|
||||
|
||||
# Linux/macOS
|
||||
cp -r files files_backup
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🔒 安全建议
|
||||
|
||||
### 1. 修改默认端口
|
||||
|
||||
编辑 `.env` 文件:
|
||||
```env
|
||||
PORT=8080 # 使用非默认端口
|
||||
```
|
||||
|
||||
### 2. 使用强密码
|
||||
|
||||
注册时使用:
|
||||
- 至少8个字符
|
||||
- 包含大小写字母
|
||||
- 包含数字和特殊字符
|
||||
|
||||
### 3. 局域网隔离
|
||||
|
||||
如果仅本机使用,不要配置局域网访问。
|
||||
|
||||
### 4. 定期更新
|
||||
|
||||
```bash
|
||||
git pull origin main
|
||||
go mod tidy
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📞 获取帮助
|
||||
|
||||
### 遇到问题?
|
||||
|
||||
1. **查看日志**: 服务器启动后的控制台输出
|
||||
2. **检查文档**: 阅读 `USER_SYSTEM_README.md`
|
||||
3. **社区支持**: 喵波音律-音乐家园QQ群:865754861
|
||||
4. **GitHub Issues**: 在项目仓库提交问题
|
||||
|
||||
### 常用命令
|
||||
|
||||
```bash
|
||||
# 查看Go版本
|
||||
go version
|
||||
|
||||
# 查看项目依赖
|
||||
go list -m all
|
||||
|
||||
# 清理编译缓存
|
||||
go clean -cache
|
||||
|
||||
# 重新下载依赖
|
||||
go mod download
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## ✅ 部署检查清单
|
||||
|
||||
部署前请确认:
|
||||
|
||||
- [ ] Go 已安装(1.19+)
|
||||
- [ ] 项目代码已下载
|
||||
- [ ] 依赖已安装(go mod tidy)
|
||||
- [ ] .env 文件已配置(可选)
|
||||
- [ ] 端口 2233 未被占用
|
||||
- [ ] 防火墙允许端口访问
|
||||
- [ ] 浏览器版本较新
|
||||
|
||||
部署后验证:
|
||||
|
||||
- [ ] 服务器成功启动
|
||||
- [ ] 可以访问 http://localhost:2233/app
|
||||
- [ ] 可以注册新用户
|
||||
- [ ] 可以搜索音乐
|
||||
- [ ] 可以创建歌单
|
||||
- [ ] 可以播放音乐
|
||||
|
||||
---
|
||||
|
||||
## 🎉 开始使用
|
||||
|
||||
部署完成后,按照以下步骤开始:
|
||||
|
||||
1. ✅ 访问 http://localhost:2233/app
|
||||
2. ✅ 注册您的账户
|
||||
3. ✅ 搜索喜欢的音乐
|
||||
4. ✅ 创建个人歌单
|
||||
5. ✅ 享受音乐!
|
||||
|
||||
---
|
||||
|
||||
**祝您使用愉快!** 🎵✨
|
||||
|
||||
有问题随时查看文档或联系社区支持!
|
||||
356
部署完成检查.md
Executable file
356
部署完成检查.md
Executable file
@@ -0,0 +1,356 @@
|
||||
# ✅ 部署完成检查清单
|
||||
|
||||
## 🎉 恭喜!所有文件已准备就绪
|
||||
|
||||
您的 Meow Music Server v2.0 已经配置完成,现在可以开始部署了!
|
||||
|
||||
---
|
||||
|
||||
## 📦 已创建的文件
|
||||
|
||||
### 后端系统
|
||||
- ✅ `user.go` - 用户认证系统
|
||||
- ✅ `struct.go` - 数据结构(已更新)
|
||||
- ✅ `playlist.go` - 歌单管理(已扩展)
|
||||
- ✅ `main.go` - 主程序(已更新路由)
|
||||
- ✅ `index.go` - 路由处理(已更新)
|
||||
- ✅ `go.mod` - 依赖配置(已添加bcrypt)
|
||||
|
||||
### 前端界面
|
||||
- ✅ `theme/music-app.html` - 现代化React应用
|
||||
|
||||
### 启动脚本
|
||||
- ✅ `start.bat` - Windows一键启动
|
||||
- ✅ `start.sh` - Linux/macOS一键启动
|
||||
|
||||
### 文档
|
||||
- ✅ `快速开始.md` - 3分钟快速部署
|
||||
- ✅ `本地部署指南.md` - 详细部署教程
|
||||
- ✅ `USER_SYSTEM_README.md` - API使用文档
|
||||
- ✅ `新功能说明.md` - 功能特性说明
|
||||
- ✅ `README_zh-CN.md` - 项目主文档(已更新)
|
||||
|
||||
---
|
||||
|
||||
## 🚀 现在开始部署
|
||||
|
||||
### Windows 用户
|
||||
|
||||
#### 方式一:一键启动(推荐)
|
||||
|
||||
1. 找到 `start.bat` 文件
|
||||
2. **双击运行**
|
||||
3. 等待启动完成
|
||||
4. 浏览器访问:http://localhost:2233/app
|
||||
|
||||
#### 方式二:命令行启动
|
||||
|
||||
```bash
|
||||
# 打开 PowerShell 或 CMD
|
||||
cd d:\esp32-music-server\Meow\MeowEmbeddedMusicServer
|
||||
|
||||
# 运行启动脚本
|
||||
start.bat
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Linux/macOS 用户
|
||||
|
||||
```bash
|
||||
# 1. 进入项目目录
|
||||
cd /path/to/MeowEmbeddedMusicServer
|
||||
|
||||
# 2. 给脚本添加执行权限
|
||||
chmod +x start.sh
|
||||
|
||||
# 3. 运行启动脚本
|
||||
./start.sh
|
||||
|
||||
# 4. 浏览器访问
|
||||
# http://localhost:2233/app
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🎯 启动后的操作
|
||||
|
||||
### 1️⃣ 验证服务器启动
|
||||
|
||||
启动后你应该看到:
|
||||
|
||||
```
|
||||
╔═══════════════════════════════════════════════╗
|
||||
║ 🎵 Meow Embedded Music Server v2.0 ║
|
||||
║ 喵波音律 - 专为ESP32设计的音乐服务器 ║
|
||||
╚═══════════════════════════════════════════════╝
|
||||
|
||||
[✓] Go环境检测成功
|
||||
[✓] 配置文件已创建/存在
|
||||
[✓] 依赖安装完成
|
||||
[✓] 服务器正在启动...
|
||||
|
||||
访问地址:
|
||||
新版应用: http://localhost:2233/app
|
||||
经典界面: http://localhost:2233/
|
||||
```
|
||||
|
||||
### 2️⃣ 访问应用
|
||||
|
||||
在浏览器中打开:**http://localhost:2233/app**
|
||||
|
||||
你应该看到登录/注册页面,紫色渐变背景。
|
||||
|
||||
### 3️⃣ 注册第一个账户
|
||||
|
||||
1. 点击"注册"标签
|
||||
2. 填写信息:
|
||||
- 用户名:`admin`
|
||||
- 邮箱:`admin@music.com`
|
||||
- 密码:`password123`(至少6位)
|
||||
3. 点击"注册"按钮
|
||||
4. 自动登录进入主界面
|
||||
|
||||
### 4️⃣ 测试功能
|
||||
|
||||
**搜索音乐:**
|
||||
1. 在搜索框输入:`告白气球`
|
||||
2. 点击"搜索"
|
||||
3. 等待搜索结果
|
||||
|
||||
**播放音乐:**
|
||||
1. 搜索结果显示后
|
||||
2. 点击"▶ 播放"按钮
|
||||
|
||||
**添加到收藏:**
|
||||
1. 在搜索结果页
|
||||
2. 下拉菜单选择"我喜欢"
|
||||
3. 歌曲自动添加
|
||||
|
||||
**创建歌单:**
|
||||
1. 左侧边栏点击"+"号
|
||||
2. 输入歌单名:`我的最爱`
|
||||
3. 确认创建
|
||||
|
||||
---
|
||||
|
||||
## ✅ 功能验证清单
|
||||
|
||||
请确认以下功能都正常工作:
|
||||
|
||||
### 基础功能
|
||||
- [ ] 服务器成功启动,无错误提示
|
||||
- [ ] 可以访问 http://localhost:2233/app
|
||||
- [ ] 可以看到登录/注册界面
|
||||
- [ ] 界面显示正常(紫色渐变背景)
|
||||
|
||||
### 用户系统
|
||||
- [ ] 可以注册新用户
|
||||
- [ ] 注册后自动登录
|
||||
- [ ] 可以退出登录
|
||||
- [ ] 可以重新登录
|
||||
|
||||
### 音乐功能
|
||||
- [ ] 可以搜索音乐
|
||||
- [ ] 搜索结果正常显示
|
||||
- [ ] 可以播放音乐
|
||||
- [ ] 音频播放正常
|
||||
|
||||
### 歌单功能
|
||||
- [ ] 可以看到"我喜欢"歌单
|
||||
- [ ] 可以创建新歌单
|
||||
- [ ] 可以添加歌曲到歌单
|
||||
- [ ] 可以查看歌单歌曲列表
|
||||
- [ ] 可以播放歌单中的歌曲
|
||||
|
||||
---
|
||||
|
||||
## 🔧 常见问题快速解决
|
||||
|
||||
### ❌ 启动失败:端口被占用
|
||||
|
||||
**现象**:提示 `address already in use`
|
||||
|
||||
**解决**:
|
||||
```bash
|
||||
# Windows
|
||||
netstat -ano | findstr :2233
|
||||
taskkill /PID <进程ID> /F
|
||||
|
||||
# Linux/macOS
|
||||
lsof -i :2233
|
||||
kill -9 <PID>
|
||||
```
|
||||
|
||||
### ❌ 依赖下载失败
|
||||
|
||||
**现象**:提示 `go: downloading ... failed`
|
||||
|
||||
**解决**(中国大陆用户):
|
||||
```bash
|
||||
go env -w GOPROXY=https://goproxy.cn,direct
|
||||
```
|
||||
|
||||
然后重新运行启动脚本
|
||||
|
||||
### ❌ 找不到 Go 命令
|
||||
|
||||
**解决**:
|
||||
- 安装 Go: https://golang.org/dl/
|
||||
- 安装后重新打开终端
|
||||
|
||||
### ❌ 页面无法访问
|
||||
|
||||
**检查**:
|
||||
1. 服务器是否成功启动?
|
||||
2. 浏览器地址是否正确?
|
||||
3. 防火墙是否阻止了端口?
|
||||
|
||||
---
|
||||
|
||||
## 📁 数据文件位置
|
||||
|
||||
服务器运行后会自动创建:
|
||||
|
||||
```
|
||||
files/
|
||||
├── users.json # 用户账户数据
|
||||
├── user_playlists.json # 用户歌单数据
|
||||
└── playlists.json # 全局歌单(兼容旧版)
|
||||
|
||||
cache/
|
||||
└── music/ # 缓存的音乐文件
|
||||
```
|
||||
|
||||
**重要提示**:
|
||||
- ⚠️ 不要手动编辑这些文件
|
||||
- 💾 定期备份 `files/` 目录
|
||||
- 🗑️ 可以删除 `cache/` 目录清理空间
|
||||
|
||||
---
|
||||
|
||||
## 🌐 局域网访问配置
|
||||
|
||||
如果需要让同一WiFi下的其他设备访问:
|
||||
|
||||
### 1. 查找本机IP
|
||||
|
||||
**Windows:**
|
||||
```bash
|
||||
ipconfig
|
||||
```
|
||||
查找 "IPv4 地址",如:`192.168.1.100`
|
||||
|
||||
**Linux/macOS:**
|
||||
```bash
|
||||
ifconfig
|
||||
# 或
|
||||
ip addr show
|
||||
```
|
||||
|
||||
### 2. 修改配置
|
||||
|
||||
编辑 `.env` 文件(如果不存在则创建):
|
||||
```env
|
||||
WEBSITE_URL=http://192.168.1.100:2233
|
||||
EMBEDDED_WEBSITE_URL=http://192.168.1.100:2233
|
||||
```
|
||||
|
||||
### 3. 配置防火墙
|
||||
|
||||
**Windows:**
|
||||
- 控制面板 → Windows防火墙 → 高级设置
|
||||
- 入站规则 → 新建规则 → 端口 → TCP → 2233
|
||||
|
||||
**Linux:**
|
||||
```bash
|
||||
sudo ufw allow 2233/tcp
|
||||
```
|
||||
|
||||
### 4. 重启服务器
|
||||
|
||||
按 `Ctrl+C` 停止,然后重新运行启动脚本
|
||||
|
||||
### 5. 其他设备访问
|
||||
|
||||
在同一WiFi下的设备浏览器访问:
|
||||
```
|
||||
http://192.168.1.100:2233/app
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📚 进阶使用
|
||||
|
||||
### 编译可执行文件
|
||||
|
||||
```bash
|
||||
# Windows
|
||||
go build -o meow-music.exe
|
||||
|
||||
# Linux/macOS
|
||||
go build -o meow-music
|
||||
```
|
||||
|
||||
### 后台运行(Linux/macOS)
|
||||
|
||||
```bash
|
||||
nohup ./start.sh > server.log 2>&1 &
|
||||
```
|
||||
|
||||
### 查看日志
|
||||
|
||||
```bash
|
||||
tail -f server.log
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📞 获取帮助
|
||||
|
||||
### 查看详细文档
|
||||
- 📖 `快速开始.md` - 基础使用
|
||||
- 📚 `本地部署指南.md` - 详细教程
|
||||
- 🔧 `USER_SYSTEM_README.md` - API文档
|
||||
|
||||
### 社区支持
|
||||
- QQ群:865754861(喵波音律-音乐家园)
|
||||
|
||||
### 问题排查
|
||||
1. 查看启动窗口的日志输出
|
||||
2. 检查 `files/` 目录权限
|
||||
3. 确认Go版本 >= 1.19
|
||||
4. 尝试删除 `files/` 目录重新启动
|
||||
|
||||
---
|
||||
|
||||
## 🎉 部署成功!
|
||||
|
||||
如果上面的功能验证清单都打勾了,恭喜你!
|
||||
|
||||
**你现在拥有一个完整的音乐服务器了!** 🎵✨
|
||||
|
||||
### 下一步可以做什么?
|
||||
|
||||
- 🎵 搜索并收藏你喜欢的音乐
|
||||
- 📋 创建不同主题的歌单
|
||||
- 📱 配置局域网访问,让朋友也能用
|
||||
- 💾 定期备份用户数据
|
||||
- 🎨 自定义网站信息(修改 .env 文件)
|
||||
|
||||
---
|
||||
|
||||
## 🔄 版本信息
|
||||
|
||||
```
|
||||
Meow Embedded Music Server
|
||||
Version: 2.0.0
|
||||
Release Date: 2024
|
||||
Features: User System + Playlist Management
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
**开始享受您的音乐之旅吧!** 🎵
|
||||
|
||||
有任何问题随时查看文档或联系社区!
|
||||
181
部署歌单功能指南.md
Executable file
181
部署歌单功能指南.md
Executable file
@@ -0,0 +1,181 @@
|
||||
# 🎵 歌单功能部署指南
|
||||
|
||||
## ✨ 新增功能
|
||||
|
||||
### 1. 后端 API
|
||||
- ✅ **POST /api/favorite/add** - 添加歌曲到"我喜欢"
|
||||
- ✅ **POST /api/favorite/remove** - 从"我喜欢"移除歌曲
|
||||
- ✅ **GET /api/favorite/list** - 获取"我喜欢"列表
|
||||
- ✅ **GET /api/favorite/check** - 检查歌曲是否已收藏
|
||||
|
||||
### 2. 前端界面
|
||||
- ✅ 现代化的音乐播放器界面(类似 QQ 音乐风格)
|
||||
- ✅ 搜索功能
|
||||
- ✅ "我喜欢"歌单管理
|
||||
- ✅ 在线播放功能
|
||||
- ✅ 收藏/取消收藏功能
|
||||
- ✅ 响应式设计,支持手机和电脑
|
||||
|
||||
### 3. 新增文件
|
||||
- `playlist.go` - 歌单管理后端
|
||||
- `themes/index.html` - 现代化前端界面
|
||||
- `files/playlists.json` - 歌单数据存储(自动生成)
|
||||
|
||||
---
|
||||
|
||||
## 📦 部署步骤
|
||||
|
||||
### 第一步:上传更新文件到云服务器
|
||||
|
||||
#### 方法 1:通过远程桌面
|
||||
1. **连接到阿里云服务器**的远程桌面
|
||||
2. **复制文件** `D:\music-server-update.zip` 到云服务器
|
||||
3. **解压到** `C:\music-server\MeowEmbeddedMusicServer`
|
||||
|
||||
#### 方法 2:通过 PowerShell(本地)
|
||||
```powershell
|
||||
# 如果有 SSH 访问权限
|
||||
scp D:\music-server-update.zip Administrator@你的服务器IP:C:\music-server\
|
||||
```
|
||||
|
||||
### 第二步:在云服务器上部署
|
||||
|
||||
**连接到云服务器 PowerShell**,运行:
|
||||
|
||||
```powershell
|
||||
# 1. 进入项目目录
|
||||
cd C:\music-server\MeowEmbeddedMusicServer
|
||||
|
||||
# 2. 停止当前运行的服务器(如果在运行)
|
||||
# 按 Ctrl+C 停止,或者找到进程并结束
|
||||
Get-Process | Where-Object {$_.ProcessName -like "*go*"} | Stop-Process -Force
|
||||
|
||||
# 3. 解压更新文件(如果使用远程桌面复制的 zip)
|
||||
Expand-Archive -Path C:\music-server\music-server-update.zip -DestinationPath C:\music-server\MeowEmbeddedMusicServer -Force
|
||||
|
||||
# 4. 确认新文件已存在
|
||||
Test-Path .\playlist.go
|
||||
Test-Path .\themes\index.html
|
||||
|
||||
# 5. 重新编译和运行
|
||||
go run .
|
||||
```
|
||||
|
||||
### 第三步:测试功能
|
||||
|
||||
#### 1. 打开浏览器访问
|
||||
```
|
||||
http://你的服务器IP:2233
|
||||
```
|
||||
|
||||
#### 2. 测试流程
|
||||
1. ✅ 在搜索框输入歌曲名(如:晴天)
|
||||
2. ✅ 点击"搜索"按钮
|
||||
3. ✅ 点击"❤️"按钮收藏歌曲
|
||||
4. ✅ 切换到"我喜欢"标签页
|
||||
5. ✅ 查看收藏的歌曲
|
||||
6. ✅ 点击"播放"按钮测试播放
|
||||
7. ✅ 再次点击"❤️"取消收藏
|
||||
|
||||
---
|
||||
|
||||
## 🎨 界面预览
|
||||
|
||||
### 搜索页面
|
||||
- 顶部:紫色渐变背景
|
||||
- 搜索框:支持歌曲名 + 歌手名搜索
|
||||
- 搜索结果:卡片式显示,包含封面、标题、歌手、时长
|
||||
- 操作按钮:收藏 ❤️ + 播放 ▶️
|
||||
|
||||
### 我喜欢页面
|
||||
- 显示所有收藏的歌曲
|
||||
- 支持取消收藏
|
||||
- 支持直接播放
|
||||
|
||||
### 播放器
|
||||
- 底部固定播放器
|
||||
- 显示当前播放的歌曲信息
|
||||
- HTML5 音频播放器,支持进度控制
|
||||
|
||||
---
|
||||
|
||||
## 📁 数据存储
|
||||
|
||||
歌单数据保存在:
|
||||
```
|
||||
C:\music-server\MeowEmbeddedMusicServer\files\playlists.json
|
||||
```
|
||||
|
||||
格式示例:
|
||||
```json
|
||||
{
|
||||
"favorite": {
|
||||
"name": "我喜欢",
|
||||
"songs": [
|
||||
{
|
||||
"title": "晴天",
|
||||
"artist": "周杰伦",
|
||||
"audio_url": "/cache/music/周杰伦-晴天/music.mp3",
|
||||
"cover_url": "/cache/music/周杰伦-晴天/cover.jpg",
|
||||
"lyric_url": "/cache/music/周杰伦-晴天/lyric.lrc",
|
||||
"duration": 267
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🔧 常见问题
|
||||
|
||||
### Q1: 界面显示不正常?
|
||||
**A:** 确保 `themes/index.html` 文件已正确上传,浏览器清除缓存后重新访问。
|
||||
|
||||
### Q2: 收藏功能不工作?
|
||||
**A:**
|
||||
1. 检查 `playlist.go` 是否已上传
|
||||
2. 确认服务器已重启
|
||||
3. 查看服务器日志是否有错误
|
||||
|
||||
### Q3: 播放器无法播放?
|
||||
**A:**
|
||||
1. 检查音频文件是否正确缓存
|
||||
2. 确认防火墙允许端口 2233
|
||||
3. 查看浏览器控制台是否有错误信息
|
||||
|
||||
### Q4: 如何备份收藏数据?
|
||||
**A:** 定期备份 `files/playlists.json` 文件
|
||||
|
||||
---
|
||||
|
||||
## 🚀 后续优化建议
|
||||
|
||||
### 1. 添加更多歌单
|
||||
修改 `playlist.go`,支持创建多个自定义歌单
|
||||
|
||||
### 2. 歌词滚动显示
|
||||
在前端添加歌词解析和滚动显示功能
|
||||
|
||||
### 3. 播放历史
|
||||
记录播放历史,方便快速重播
|
||||
|
||||
### 4. 推荐系统
|
||||
根据收藏和播放历史推荐相似音乐
|
||||
|
||||
### 5. 用户系统
|
||||
添加多用户支持,每个用户有独立歌单
|
||||
|
||||
---
|
||||
|
||||
## 📞 技术支持
|
||||
|
||||
如遇问题,请检查:
|
||||
1. 服务器日志输出
|
||||
2. 浏览器开发者工具(F12)的控制台
|
||||
3. 网络请求是否正常
|
||||
|
||||
---
|
||||
|
||||
**祝您使用愉快!🎵**
|
||||
|
||||
Reference in New Issue
Block a user