mirror of
https://github.com/MoonTechLab/LunaTV.git
synced 2026-02-27 06:54:43 +08:00
feat: data export and import
This commit is contained in:
@@ -32,7 +32,7 @@ export async function POST(request: NextRequest) {
|
||||
if (username !== process.env.USERNAME) {
|
||||
return NextResponse.json(
|
||||
{ error: '权限不足,只有站长可以修改配置文件' },
|
||||
{ status: 403 }
|
||||
{ status: 401 }
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -15,7 +15,7 @@ export async function POST(request: NextRequest) {
|
||||
if (authInfo.username !== process.env.USERNAME) {
|
||||
return NextResponse.json(
|
||||
{ error: '权限不足,只有站长可以拉取配置订阅' },
|
||||
{ status: 403 }
|
||||
{ status: 401 }
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
131
src/app/api/admin/data_migration/export/route.ts
Normal file
131
src/app/api/admin/data_migration/export/route.ts
Normal file
@@ -0,0 +1,131 @@
|
||||
/* eslint-disable @typescript-eslint/no-explicit-any,no-console */
|
||||
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { promisify } from 'util';
|
||||
import { gzip } from 'zlib';
|
||||
|
||||
import { getAuthInfoFromCookie } from '@/lib/auth';
|
||||
import { SimpleCrypto } from '@/lib/crypto';
|
||||
import { db } from '@/lib/db';
|
||||
import { CURRENT_VERSION } from '@/lib/version';
|
||||
|
||||
const gzipAsync = promisify(gzip);
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
try {
|
||||
// 检查存储类型
|
||||
const storageType = process.env.NEXT_PUBLIC_STORAGE_TYPE || 'localstorage';
|
||||
if (storageType === 'localstorage') {
|
||||
return NextResponse.json(
|
||||
{ error: '不支持本地存储进行数据迁移' },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
// 验证身份和权限
|
||||
const authInfo = getAuthInfoFromCookie(req);
|
||||
if (!authInfo || !authInfo.username) {
|
||||
return NextResponse.json({ error: '未登录' }, { status: 401 });
|
||||
}
|
||||
|
||||
// 检查用户权限(只有站长可以导出数据)
|
||||
if (authInfo.username !== process.env.USERNAME) {
|
||||
return NextResponse.json({ error: '权限不足,只有站长可以导出数据' }, { status: 401 });
|
||||
}
|
||||
|
||||
const config = await db.getAdminConfig();
|
||||
if (!config) {
|
||||
return NextResponse.json({ error: '无法获取配置' }, { status: 500 });
|
||||
}
|
||||
|
||||
// 解析请求体获取密码
|
||||
const { password } = await req.json();
|
||||
if (!password || typeof password !== 'string') {
|
||||
return NextResponse.json({ error: '请提供加密密码' }, { status: 400 });
|
||||
}
|
||||
|
||||
// 收集所有数据
|
||||
const exportData = {
|
||||
timestamp: new Date().toISOString(),
|
||||
serverVersion: CURRENT_VERSION,
|
||||
data: {
|
||||
// 管理员配置
|
||||
adminConfig: config,
|
||||
// 所有用户数据
|
||||
userData: {} as { [username: string]: any }
|
||||
}
|
||||
};
|
||||
|
||||
// 获取所有用户
|
||||
let allUsers = await db.getAllUsers();
|
||||
// 添加站长用户
|
||||
allUsers.push(process.env.USERNAME);
|
||||
allUsers = Array.from(new Set(allUsers));
|
||||
|
||||
// 为每个用户收集数据
|
||||
for (const username of allUsers) {
|
||||
const userData = {
|
||||
// 播放记录
|
||||
playRecords: await db.getAllPlayRecords(username),
|
||||
// 收藏夹
|
||||
favorites: await db.getAllFavorites(username),
|
||||
// 搜索历史
|
||||
searchHistory: await db.getSearchHistory(username),
|
||||
// 跳过片头片尾配置
|
||||
skipConfigs: await db.getAllSkipConfigs(username),
|
||||
// 用户密码(通过验证空密码来检查用户是否存在,然后获取密码)
|
||||
password: await getUserPassword(username)
|
||||
};
|
||||
|
||||
exportData.data.userData[username] = userData;
|
||||
}
|
||||
|
||||
// 将数据转换为JSON字符串
|
||||
const jsonData = JSON.stringify(exportData);
|
||||
|
||||
// 先压缩数据
|
||||
const compressedData = await gzipAsync(jsonData);
|
||||
|
||||
// 使用提供的密码加密压缩后的数据
|
||||
const encryptedData = SimpleCrypto.encrypt(compressedData.toString('base64'), password);
|
||||
|
||||
// 生成文件名
|
||||
const now = new Date();
|
||||
const timestamp = `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}-${String(now.getHours()).padStart(2, '0')}${String(now.getMinutes()).padStart(2, '0')}${String(now.getSeconds()).padStart(2, '0')}`;
|
||||
const filename = `moontv-backup-${timestamp}.dat`;
|
||||
|
||||
// 返回加密的数据作为文件下载
|
||||
return new NextResponse(encryptedData, {
|
||||
status: 200,
|
||||
headers: {
|
||||
'Content-Type': 'application/octet-stream',
|
||||
'Content-Disposition': `attachment; filename="${filename}"`,
|
||||
'Content-Length': encryptedData.length.toString(),
|
||||
},
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
console.error('数据导出失败:', error);
|
||||
return NextResponse.json(
|
||||
{ error: error instanceof Error ? error.message : '导出失败' },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// 辅助函数:获取用户密码(通过数据库直接访问)
|
||||
async function getUserPassword(username: string): Promise<string | null> {
|
||||
try {
|
||||
// 使用 Redis 存储的直接访问方法
|
||||
const storage = (db as any).storage;
|
||||
if (storage && typeof storage.client?.get === 'function') {
|
||||
const passwordKey = `u:${username}:pwd`;
|
||||
const password = await storage.client.get(passwordKey);
|
||||
return password;
|
||||
}
|
||||
return null;
|
||||
} catch (error) {
|
||||
console.error(`获取用户 ${username} 密码失败:`, error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
139
src/app/api/admin/data_migration/import/route.ts
Normal file
139
src/app/api/admin/data_migration/import/route.ts
Normal file
@@ -0,0 +1,139 @@
|
||||
/* eslint-disable @typescript-eslint/no-explicit-any,no-console */
|
||||
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { promisify } from 'util';
|
||||
import { gunzip } from 'zlib';
|
||||
|
||||
import { getAuthInfoFromCookie } from '@/lib/auth';
|
||||
import { SimpleCrypto } from '@/lib/crypto';
|
||||
import { db } from '@/lib/db';
|
||||
|
||||
const gunzipAsync = promisify(gunzip);
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
try {
|
||||
// 检查存储类型
|
||||
const storageType = process.env.NEXT_PUBLIC_STORAGE_TYPE || 'localstorage';
|
||||
if (storageType === 'localstorage') {
|
||||
return NextResponse.json(
|
||||
{ error: '不支持本地存储进行数据迁移' },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
// 验证身份和权限
|
||||
const authInfo = getAuthInfoFromCookie(req);
|
||||
if (!authInfo || !authInfo.username) {
|
||||
return NextResponse.json({ error: '未登录' }, { status: 401 });
|
||||
}
|
||||
|
||||
// 检查用户权限(只有站长可以导入数据)
|
||||
if (authInfo.username !== process.env.USERNAME) {
|
||||
return NextResponse.json({ error: '权限不足,只有站长可以导入数据' }, { status: 401 });
|
||||
}
|
||||
|
||||
// 解析表单数据
|
||||
const formData = await req.formData();
|
||||
const file = formData.get('file') as File;
|
||||
const password = formData.get('password') as string;
|
||||
|
||||
if (!file) {
|
||||
return NextResponse.json({ error: '请选择备份文件' }, { status: 400 });
|
||||
}
|
||||
|
||||
if (!password) {
|
||||
return NextResponse.json({ error: '请提供解密密码' }, { status: 400 });
|
||||
}
|
||||
|
||||
// 读取文件内容
|
||||
const encryptedData = await file.text();
|
||||
|
||||
// 解密数据
|
||||
let decryptedData: string;
|
||||
try {
|
||||
decryptedData = SimpleCrypto.decrypt(encryptedData, password);
|
||||
} catch (error) {
|
||||
return NextResponse.json({ error: '解密失败,请检查密码是否正确' }, { status: 400 });
|
||||
}
|
||||
|
||||
// 解压缩数据
|
||||
const compressedBuffer = Buffer.from(decryptedData, 'base64');
|
||||
const decompressedBuffer = await gunzipAsync(compressedBuffer);
|
||||
const decompressedData = decompressedBuffer.toString();
|
||||
|
||||
// 解析JSON数据
|
||||
let importData: any;
|
||||
try {
|
||||
importData = JSON.parse(decompressedData);
|
||||
} catch (error) {
|
||||
return NextResponse.json({ error: '备份文件格式错误' }, { status: 400 });
|
||||
}
|
||||
|
||||
// 验证数据格式
|
||||
if (!importData.data || !importData.data.adminConfig || !importData.data.userData) {
|
||||
return NextResponse.json({ error: '备份文件格式无效' }, { status: 400 });
|
||||
}
|
||||
|
||||
// 开始导入数据 - 先清空现有数据
|
||||
await db.clearAllData();
|
||||
|
||||
// 导入管理员配置
|
||||
await db.saveAdminConfig(importData.data.adminConfig);
|
||||
|
||||
// 导入用户数据
|
||||
const userData = importData.data.userData;
|
||||
for (const username in userData) {
|
||||
const user = userData[username];
|
||||
|
||||
// 重新注册用户(包含密码)
|
||||
if (user.password) {
|
||||
await db.registerUser(username, user.password);
|
||||
}
|
||||
|
||||
// 导入播放记录
|
||||
if (user.playRecords) {
|
||||
for (const [key, record] of Object.entries(user.playRecords)) {
|
||||
await (db as any).storage.setPlayRecord(username, key, record);
|
||||
}
|
||||
}
|
||||
|
||||
// 导入收藏夹
|
||||
if (user.favorites) {
|
||||
for (const [key, favorite] of Object.entries(user.favorites)) {
|
||||
await (db as any).storage.setFavorite(username, key, favorite);
|
||||
}
|
||||
}
|
||||
|
||||
// 导入搜索历史
|
||||
if (user.searchHistory && Array.isArray(user.searchHistory)) {
|
||||
for (const keyword of user.searchHistory.reverse()) { // 反转以保持顺序
|
||||
await db.addSearchHistory(username, keyword);
|
||||
}
|
||||
}
|
||||
|
||||
// 导入跳过片头片尾配置
|
||||
if (user.skipConfigs) {
|
||||
for (const [key, skipConfig] of Object.entries(user.skipConfigs)) {
|
||||
const [source, id] = key.split('+');
|
||||
if (source && id) {
|
||||
await db.setSkipConfig(username, source, id, skipConfig as any);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return NextResponse.json({
|
||||
message: '数据导入成功',
|
||||
importedUsers: Object.keys(userData).length,
|
||||
timestamp: importData.timestamp,
|
||||
serverVersion: typeof importData.serverVersion === 'string' ? importData.serverVersion : '未知版本'
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
console.error('数据导入失败:', error);
|
||||
return NextResponse.json(
|
||||
{ error: error instanceof Error ? error.message : '导入失败' },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user