扫描修改为后台扫描,openlist登录增加账号密码

This commit is contained in:
mtvpls
2025-12-22 01:28:56 +08:00
parent 3c55bc9d1a
commit 7ca6379d93
18 changed files with 1157 additions and 67 deletions

View File

@@ -5,6 +5,7 @@ import { NextRequest, NextResponse } from 'next/server';
import { getAuthInfoFromCookie } from '@/lib/auth';
import { getConfig } from '@/lib/config';
import { db } from '@/lib/db';
import { OpenListClient } from '@/lib/openlist.client';
export const runtime = 'nodejs';
@@ -25,7 +26,7 @@ export async function POST(request: NextRequest) {
try {
const body = await request.json();
const { action, URL, Token, RootPath } = body;
const { action, URL, Token, Username, Password, RootPath } = body;
const authInfo = getAuthInfoFromCookie(request);
if (!authInfo || !authInfo.username) {
@@ -48,13 +49,40 @@ export async function POST(request: NextRequest) {
if (action === 'save') {
// 保存配置
if (!URL || !Token) {
return NextResponse.json({ error: '缺少必要参数' }, { status: 400 });
if (!URL) {
return NextResponse.json({ error: '缺少URL参数' }, { status: 400 });
}
let finalToken = Token;
// 如果没有Token但有账号密码尝试登录获取Token
if (!finalToken && Username && Password) {
try {
console.log('[OpenList Config] 使用账号密码登录获取Token');
finalToken = await OpenListClient.login(URL, Username, Password);
console.log('[OpenList Config] 登录成功获取到Token');
} catch (error) {
console.error('[OpenList Config] 登录失败:', error);
return NextResponse.json(
{ error: '使用账号密码登录失败: ' + (error as Error).message },
{ status: 400 }
);
}
}
// 检查是否有Token
if (!finalToken) {
return NextResponse.json(
{ error: '请提供Token或账号密码' },
{ status: 400 }
);
}
adminConfig.OpenListConfig = {
URL,
Token,
Token: finalToken,
Username: Username || undefined,
Password: Password || undefined,
RootPath: RootPath || '/',
LastRefreshTime: adminConfig.OpenListConfig?.LastRefreshTime,
ResourceCount: adminConfig.OpenListConfig?.ResourceCount,

View File

@@ -291,7 +291,7 @@ async function handleOpenListProxy(request: NextRequest) {
},
});
const content = await contentResponse.text();
metaInfo = JSON.parse(content);
metaInfo = JSON.parse(content) as MetaInfo;
setCachedMetaInfo(rootPath, metaInfo);
}
} catch (error) {

View File

@@ -0,0 +1,131 @@
/* eslint-disable @typescript-eslint/no-explicit-any, no-console */
import { NextRequest, NextResponse } from 'next/server';
import { getAuthInfoFromCookie } from '@/lib/auth';
import { getConfig } from '@/lib/config';
import { OpenListClient } from '@/lib/openlist.client';
import {
getCachedMetaInfo,
invalidateMetaInfoCache,
MetaInfo,
setCachedMetaInfo,
} from '@/lib/openlist-cache';
export const runtime = 'nodejs';
/**
* POST /api/openlist/correct
* 纠正视频的TMDB映射
*/
export async function POST(request: NextRequest) {
try {
const authInfo = getAuthInfoFromCookie(request);
if (!authInfo || !authInfo.username) {
return NextResponse.json({ error: '未授权' }, { status: 401 });
}
const body = await request.json();
const { folder, tmdbId, title, posterPath, releaseDate, overview, voteAverage, mediaType } = body;
if (!folder || !tmdbId) {
return NextResponse.json(
{ error: '缺少必要参数' },
{ status: 400 }
);
}
const config = await getConfig();
const openListConfig = config.OpenListConfig;
if (!openListConfig || !openListConfig.URL || !openListConfig.Token) {
return NextResponse.json(
{ error: 'OpenList 未配置' },
{ status: 400 }
);
}
const rootPath = openListConfig.RootPath || '/';
const client = new OpenListClient(
openListConfig.URL,
openListConfig.Token,
openListConfig.Username,
openListConfig.Password
);
// 读取现有 metainfo.json
let metaInfo: MetaInfo | null = getCachedMetaInfo(rootPath);
if (!metaInfo) {
try {
const metainfoPath = `${rootPath}${rootPath.endsWith('/') ? '' : '/'}metainfo.json`;
const fileResponse = await client.getFile(metainfoPath);
if (fileResponse.code === 200 && fileResponse.data.raw_url) {
const downloadUrl = fileResponse.data.raw_url;
const contentResponse = await fetch(downloadUrl, {
headers: {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
'Accept': '*/*',
'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
},
});
if (!contentResponse.ok) {
throw new Error(`下载失败: ${contentResponse.status}`);
}
const content = await contentResponse.text();
metaInfo = JSON.parse(content);
}
} catch (error) {
console.error('[OpenList Correct] 读取 metainfo.json 失败:', error);
return NextResponse.json(
{ error: 'metainfo.json 读取失败' },
{ status: 500 }
);
}
}
if (!metaInfo) {
return NextResponse.json(
{ error: 'metainfo.json 不存在' },
{ status: 404 }
);
}
// 更新视频信息
metaInfo.folders[folder] = {
tmdb_id: tmdbId,
title: title,
poster_path: posterPath,
release_date: releaseDate || '',
overview: overview || '',
vote_average: voteAverage || 0,
media_type: mediaType,
last_updated: Date.now(),
failed: false, // 纠错后标记为成功
};
// 保存 metainfo.json
const metainfoPath = `${rootPath}${rootPath.endsWith('/') ? '' : '/'}metainfo.json`;
const metainfoContent = JSON.stringify(metaInfo, null, 2);
await client.uploadFile(metainfoPath, metainfoContent);
// 更新缓存
invalidateMetaInfoCache(rootPath);
setCachedMetaInfo(rootPath, metaInfo);
return NextResponse.json({
success: true,
message: '纠错成功',
});
} catch (error) {
console.error('视频纠错失败:', error);
return NextResponse.json(
{ error: '纠错失败', details: (error as Error).message },
{ status: 500 }
);
}
}

View File

@@ -41,7 +41,12 @@ export async function GET(request: NextRequest) {
const rootPath = openListConfig.RootPath || '/';
const folderPath = `${rootPath}${rootPath.endsWith('/') ? '' : '/'}${folderName}`;
const client = new OpenListClient(openListConfig.URL, openListConfig.Token);
const client = new OpenListClient(
openListConfig.URL,
openListConfig.Token,
openListConfig.Username,
openListConfig.Password
);
// 1. 尝试读取缓存的 videoinfo.json
let videoInfo: VideoInfo | null = getCachedVideoInfo(folderPath);

View File

@@ -15,7 +15,7 @@ import { getTMDBImageUrl } from '@/lib/tmdb.search';
export const runtime = 'nodejs';
/**
* GET /api/openlist/list?page=1&pageSize=20
* GET /api/openlist/list?page=1&pageSize=20&includeFailed=false
* 获取私人影库视频列表
*/
export async function GET(request: NextRequest) {
@@ -28,6 +28,7 @@ export async function GET(request: NextRequest) {
const { searchParams } = new URL(request.url);
const page = parseInt(searchParams.get('page') || '1');
const pageSize = parseInt(searchParams.get('pageSize') || '20');
const includeFailed = searchParams.get('includeFailed') === 'true';
const config = await getConfig();
const openListConfig = config.OpenListConfig;
@@ -40,7 +41,12 @@ export async function GET(request: NextRequest) {
}
const rootPath = openListConfig.RootPath || '/';
const client = new OpenListClient(openListConfig.URL, openListConfig.Token);
const client = new OpenListClient(
openListConfig.URL,
openListConfig.Token,
openListConfig.Username,
openListConfig.Password
);
// 读取 metainfo.json
let metaInfo: MetaInfo | null = getCachedMetaInfo(rootPath);
@@ -153,19 +159,23 @@ export async function GET(request: NextRequest) {
console.log('[OpenList List] 开始转换视频列表,视频数:', Object.keys(metaInfo.folders).length);
// 转换为数组并分页
const allVideos = Object.entries(metaInfo.folders).map(
([folderName, info]) => ({
id: folderName,
folder: folderName,
title: info.title,
poster: getTMDBImageUrl(info.poster_path),
releaseDate: info.release_date,
overview: info.overview,
voteAverage: info.vote_average,
mediaType: info.media_type,
lastUpdated: info.last_updated,
})
);
const allVideos = Object.entries(metaInfo.folders)
.filter(([, info]) => includeFailed || !info.failed) // 根据参数过滤失败的视频
.map(
([folderName, info]) => ({
id: folderName,
folder: folderName,
tmdbId: info.tmdb_id,
title: info.title,
poster: getTMDBImageUrl(info.poster_path),
releaseDate: info.release_date,
overview: info.overview,
voteAverage: info.vote_average,
mediaType: info.media_type,
lastUpdated: info.last_updated,
failed: info.failed || false,
})
);
// 按更新时间倒序排序
allVideos.sort((a, b) => b.lastUpdated - a.lastUpdated);

View File

@@ -39,7 +39,12 @@ export async function GET(request: NextRequest) {
const folderPath = `${rootPath}${rootPath.endsWith('/') ? '' : '/'}${folderName}`;
const filePath = `${folderPath}/${fileName}`;
const client = new OpenListClient(openListConfig.URL, openListConfig.Token);
const client = new OpenListClient(
openListConfig.URL,
openListConfig.Token,
openListConfig.Username,
openListConfig.Password
);
// 获取文件的播放链接
const fileResponse = await client.getFile(filePath);

View File

@@ -36,7 +36,12 @@ export async function POST(request: NextRequest) {
const rootPath = openListConfig.RootPath || '/';
const folderPath = `${rootPath}${rootPath.endsWith('/') ? '' : '/'}${folder}`;
const client = new OpenListClient(openListConfig.URL, openListConfig.Token);
const client = new OpenListClient(
openListConfig.URL,
openListConfig.Token,
openListConfig.Username,
openListConfig.Password
);
// 删除 videoinfo.json
const videoinfoPath = `${folderPath}/videoinfo.json`;

View File

@@ -12,13 +12,20 @@ import {
MetaInfo,
setCachedMetaInfo,
} from '@/lib/openlist-cache';
import {
cleanupOldTasks,
completeScanTask,
createScanTask,
failScanTask,
updateScanTaskProgress,
} from '@/lib/scan-task';
import { searchTMDB } from '@/lib/tmdb.search';
export const runtime = 'nodejs';
/**
* POST /api/openlist/refresh
* 刷新私人影库元数据
* 刷新私人影库元数据(后台任务模式)
*/
export async function POST(request: NextRequest) {
try {
@@ -49,15 +56,67 @@ export async function POST(request: NextRequest) {
);
}
const rootPath = openListConfig.RootPath || '/';
const client = new OpenListClient(openListConfig.URL, openListConfig.Token);
// 清理旧任务
cleanupOldTasks();
console.log('[OpenList Refresh] 开始刷新:', {
rootPath,
url: openListConfig.URL,
hasToken: !!openListConfig.Token,
// 创建后台任务
const taskId = createScanTask();
// 启动后台扫描
performScan(
taskId,
openListConfig.URL,
openListConfig.Token,
openListConfig.RootPath || '/',
tmdbApiKey,
tmdbProxy,
openListConfig.Username,
openListConfig.Password
).catch((error) => {
console.error('[OpenList Refresh] 后台扫描失败:', error);
failScanTask(taskId, (error as Error).message);
});
return NextResponse.json({
success: true,
taskId,
message: '扫描任务已启动',
});
} catch (error) {
console.error('启动刷新任务失败:', error);
return NextResponse.json(
{ error: '启动失败', details: (error as Error).message },
{ status: 500 }
);
}
}
/**
* 执行扫描任务
*/
async function performScan(
taskId: string,
url: string,
token: string,
rootPath: string,
tmdbApiKey: string,
tmdbProxy?: string,
username?: string,
password?: string
): Promise<void> {
const client = new OpenListClient(url, token, username, password);
console.log('[OpenList Refresh] 开始扫描:', {
taskId,
rootPath,
url,
hasToken: !!token,
});
// 立即更新进度,确保任务可被查询
updateScanTaskProgress(taskId, 0, 0);
try {
// 1. 读取现有 metainfo.json (如果存在)
let existingMetaInfo: MetaInfo | null = getCachedMetaInfo(rootPath);
@@ -132,10 +191,7 @@ export async function POST(request: NextRequest) {
const listResponse = await client.listDirectory(rootPath);
if (listResponse.code !== 200) {
return NextResponse.json(
{ error: 'OpenList 列表获取失败' },
{ status: 500 }
);
throw new Error('OpenList 列表获取失败');
}
const folders = listResponse.data.content.filter((item) => item.is_dir);
@@ -145,13 +201,20 @@ export async function POST(request: NextRequest) {
names: folders.map(f => f.name),
});
// 更新任务进度
updateScanTaskProgress(taskId, 0, folders.length);
// 3. 遍历文件夹,搜索 TMDB
let newCount = 0;
let errorCount = 0;
for (const folder of folders) {
for (let i = 0; i < folders.length; i++) {
const folder = folders[i];
console.log('[OpenList Refresh] 处理文件夹:', folder.name);
// 更新进度
updateScanTaskProgress(taskId, i + 1, folders.length, folder.name);
// 跳过已搜索过的文件夹
if (metaInfo.folders[folder.name]) {
console.log('[OpenList Refresh] 跳过已存在的文件夹:', folder.name);
@@ -185,6 +248,7 @@ export async function POST(request: NextRequest) {
vote_average: result.vote_average,
media_type: result.media_type,
last_updated: Date.now(),
failed: false,
};
console.log('[OpenList Refresh] 添加成功:', {
@@ -195,6 +259,18 @@ export async function POST(request: NextRequest) {
newCount++;
} else {
console.warn(`[OpenList Refresh] TMDB 搜索失败: ${folder.name}`);
// 记录失败的文件夹
metaInfo.folders[folder.name] = {
tmdb_id: 0,
title: folder.name,
poster_path: null,
release_date: '',
overview: '',
vote_average: 0,
media_type: 'movie',
last_updated: Date.now(),
failed: true,
};
errorCount++;
}
@@ -202,6 +278,18 @@ export async function POST(request: NextRequest) {
await new Promise((resolve) => setTimeout(resolve, 300));
} catch (error) {
console.error(`[OpenList Refresh] 处理文件夹失败: ${folder.name}`, error);
// 记录失败的文件夹
metaInfo.folders[folder.name] = {
tmdb_id: 0,
title: folder.name,
poster_path: null,
release_date: '',
overview: '',
vote_average: 0,
media_type: 'movie',
last_updated: Date.now(),
failed: true,
};
errorCount++;
}
}
@@ -258,23 +346,29 @@ export async function POST(request: NextRequest) {
console.log('[OpenList Refresh] 缓存已更新');
// 6. 更新配置
const config = await getConfig();
config.OpenListConfig!.LastRefreshTime = Date.now();
config.OpenListConfig!.ResourceCount = Object.keys(metaInfo.folders).length;
await db.saveAdminConfig(config);
return NextResponse.json({
success: true,
// 完成任务
completeScanTask(taskId, {
total: folders.length,
new: newCount,
existing: Object.keys(metaInfo.folders).length - newCount,
errors: errorCount,
});
console.log('[OpenList Refresh] 扫描完成:', {
taskId,
total: folders.length,
new: newCount,
existing: Object.keys(metaInfo.folders).length - newCount,
errors: errorCount,
last_refresh: metaInfo.last_refresh,
});
} catch (error) {
console.error('刷新私人影库失败:', error);
return NextResponse.json(
{ error: '刷新失败', details: (error as Error).message },
{ status: 500 }
);
console.error('[OpenList Refresh] 扫描失败:', error);
failScanTask(taskId, (error as Error).message);
throw error;
}
}

View File

@@ -0,0 +1,45 @@
/* eslint-disable no-console */
import { NextRequest, NextResponse } from 'next/server';
import { getAuthInfoFromCookie } from '@/lib/auth';
import { getScanTask } from '@/lib/scan-task';
export const runtime = 'nodejs';
/**
* GET /api/openlist/scan-progress?taskId=xxx
* 获取扫描任务进度
*/
export async function GET(request: NextRequest) {
try {
const authInfo = getAuthInfoFromCookie(request);
if (!authInfo || !authInfo.username) {
return NextResponse.json({ error: '未授权' }, { status: 401 });
}
const { searchParams } = new URL(request.url);
const taskId = searchParams.get('taskId');
if (!taskId) {
return NextResponse.json({ error: '缺少 taskId' }, { status: 400 });
}
const task = getScanTask(taskId);
if (!task) {
return NextResponse.json({ error: '任务不存在' }, { status: 404 });
}
return NextResponse.json({
success: true,
task,
});
} catch (error) {
console.error('获取扫描进度失败:', error);
return NextResponse.json(
{ error: '获取失败', details: (error as Error).message },
{ status: 500 }
);
}
}

View File

@@ -0,0 +1,98 @@
/* eslint-disable @typescript-eslint/no-explicit-any, no-console */
import { NextRequest, NextResponse } from 'next/server';
import { getAuthInfoFromCookie } from '@/lib/auth';
import { getConfig } from '@/lib/config';
import { HttpsProxyAgent } from 'https-proxy-agent';
export const runtime = 'nodejs';
// 代理 agent 缓存
const proxyAgentCache = new Map<string, HttpsProxyAgent<string>>();
function getProxyAgent(proxy: string): HttpsProxyAgent<string> {
if (!proxyAgentCache.has(proxy)) {
const agent = new HttpsProxyAgent(proxy, {
timeout: 30000,
keepAlive: true,
keepAliveMsecs: 60000,
maxSockets: 10,
maxFreeSockets: 5,
});
proxyAgentCache.set(proxy, agent);
}
return proxyAgentCache.get(proxy)!;
}
/**
* GET /api/tmdb/search?query=xxx
* 搜索TMDB返回多个结果供用户选择
*/
export async function GET(request: NextRequest) {
try {
const authInfo = getAuthInfoFromCookie(request);
if (!authInfo || !authInfo.username) {
return NextResponse.json({ error: '未授权' }, { status: 401 });
}
const { searchParams } = new URL(request.url);
const query = searchParams.get('query');
if (!query) {
return NextResponse.json({ error: '缺少查询参数' }, { status: 400 });
}
const config = await getConfig();
const tmdbApiKey = config.SiteConfig.TMDBApiKey;
const tmdbProxy = config.SiteConfig.TMDBProxy;
if (!tmdbApiKey) {
return NextResponse.json(
{ error: 'TMDB API Key 未配置' },
{ status: 400 }
);
}
// 使用 multi search 同时搜索电影和电视剧
const url = `https://api.themoviedb.org/3/search/multi?api_key=${tmdbApiKey}&language=zh-CN&query=${encodeURIComponent(query)}&page=1`;
const fetchOptions: any = tmdbProxy
? {
agent: getProxyAgent(tmdbProxy),
signal: AbortSignal.timeout(30000),
}
: {
signal: AbortSignal.timeout(15000),
};
const response = await fetch(url, fetchOptions);
if (!response.ok) {
console.error('TMDB 搜索失败:', response.status, response.statusText);
return NextResponse.json(
{ error: 'TMDB 搜索失败', code: response.status },
{ status: response.status }
);
}
const data: any = await response.json();
// 过滤出电影和电视剧
const validResults = data.results.filter(
(item: any) => item.media_type === 'movie' || item.media_type === 'tv'
);
return NextResponse.json({
success: true,
results: validResults,
total: validResults.length,
});
} catch (error) {
console.error('TMDB搜索失败:', error);
return NextResponse.json(
{ error: '搜索失败', details: (error as Error).message },
{ status: 500 }
);
}
}