增加emby支持
This commit is contained in:
184
src/app/api/admin/emby/route.ts
Normal file
184
src/app/api/admin/emby/route.ts
Normal file
@@ -0,0 +1,184 @@
|
||||
/* eslint-disable no-console */
|
||||
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
|
||||
import { getAuthInfoFromCookie } from '@/lib/auth';
|
||||
import { getConfig } from '@/lib/config';
|
||||
import { db } from '@/lib/db';
|
||||
import { EmbyClient } from '@/lib/emby.client';
|
||||
|
||||
export const runtime = 'nodejs';
|
||||
|
||||
/**
|
||||
* POST /api/admin/emby
|
||||
* 保存 Emby 配置
|
||||
*/
|
||||
export async function POST(request: NextRequest) {
|
||||
const storageType = process.env.NEXT_PUBLIC_STORAGE_TYPE || 'localstorage';
|
||||
if (storageType === 'localstorage') {
|
||||
return NextResponse.json(
|
||||
{ error: '不支持本地存储进行管理员配置' },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
const body = await request.json();
|
||||
const { action, Enabled, ServerURL, ApiKey, Username, Password, UserId, Libraries } = body;
|
||||
|
||||
const authInfo = getAuthInfoFromCookie(request);
|
||||
if (!authInfo || !authInfo.username) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
||||
}
|
||||
const username = authInfo.username;
|
||||
|
||||
// 获取配置
|
||||
const adminConfig = await getConfig();
|
||||
|
||||
// 权限检查
|
||||
if (username !== process.env.USERNAME) {
|
||||
const userInfo = await db.getUserInfoV2(username);
|
||||
if (!userInfo || userInfo.role !== 'admin' || userInfo.banned) {
|
||||
return NextResponse.json({ error: '权限不足' }, { status: 401 });
|
||||
}
|
||||
}
|
||||
|
||||
if (action === 'save') {
|
||||
// 如果功能未启用,允许保存空配置
|
||||
if (!Enabled) {
|
||||
adminConfig.EmbyConfig = {
|
||||
Enabled: false,
|
||||
ServerURL: ServerURL || '',
|
||||
ApiKey: ApiKey || '',
|
||||
Username: Username || '',
|
||||
Password: Password || '',
|
||||
Libraries: Libraries || [],
|
||||
};
|
||||
await db.saveAdminConfig(adminConfig);
|
||||
return NextResponse.json({ success: true, message: 'Emby 配置已保存(未启用)' });
|
||||
}
|
||||
|
||||
// 验证必填字段
|
||||
if (!ServerURL) {
|
||||
return NextResponse.json({ error: '请填写 Emby 服务器地址' }, { status: 400 });
|
||||
}
|
||||
|
||||
if (!ApiKey && (!Username || !Password)) {
|
||||
return NextResponse.json(
|
||||
{ error: '请填写 API Key 或用户名密码' },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
// 测试连接
|
||||
const testConfig = {
|
||||
ServerURL,
|
||||
ApiKey,
|
||||
Username,
|
||||
Password,
|
||||
UserId,
|
||||
};
|
||||
|
||||
const client = new EmbyClient(testConfig);
|
||||
|
||||
// 如果使用用户名密码,先认证
|
||||
let finalUserId: string | undefined = UserId; // 使用用户提供的 UserId
|
||||
if (!ApiKey && Username && Password) {
|
||||
try {
|
||||
const authResult = await client.authenticate(Username, Password);
|
||||
finalUserId = authResult.User.Id;
|
||||
} catch (error) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Emby 认证失败: ' + (error as Error).message },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// <20><>试连接
|
||||
const isConnected = await client.checkConnectivity();
|
||||
if (!isConnected) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Emby 连接失败,请检查服务器地址和认证信息' },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
// 保存配置
|
||||
adminConfig.EmbyConfig = {
|
||||
Enabled: true,
|
||||
ServerURL,
|
||||
ApiKey: ApiKey || undefined,
|
||||
Username: Username || undefined,
|
||||
Password: Password || undefined,
|
||||
UserId: finalUserId,
|
||||
Libraries: Libraries || [],
|
||||
LastSyncTime: Date.now(),
|
||||
};
|
||||
|
||||
await db.saveAdminConfig(adminConfig);
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
message: 'Emby 配置已保存并测试成功',
|
||||
});
|
||||
}
|
||||
|
||||
if (action === 'test') {
|
||||
// 测试连接
|
||||
if (!ServerURL) {
|
||||
return NextResponse.json({ error: '请填写 Emby 服务器地址' }, { status: 400 });
|
||||
}
|
||||
|
||||
if (!ApiKey && (!Username || !Password)) {
|
||||
return NextResponse.json(
|
||||
{ error: '请填写 API Key 或用户名密码' },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const testConfig = {
|
||||
ServerURL,
|
||||
ApiKey,
|
||||
Username,
|
||||
Password,
|
||||
};
|
||||
|
||||
const client = new EmbyClient(testConfig);
|
||||
|
||||
// 如果使用用户名密码,先认证
|
||||
if (!ApiKey && Username && Password) {
|
||||
try {
|
||||
await client.authenticate(Username, Password);
|
||||
} catch (error) {
|
||||
return NextResponse.json(
|
||||
{ success: false, message: 'Emby 认证失败: ' + (error as Error).message },
|
||||
{ status: 200 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// 测试连接
|
||||
const isConnected = await client.checkConnectivity();
|
||||
if (!isConnected) {
|
||||
return NextResponse.json(
|
||||
{ success: false, message: 'Emby 连接失败,请检查服务器地址和认证信息' },
|
||||
{ status: 200 }
|
||||
);
|
||||
}
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
message: 'Emby 连接测试成功',
|
||||
});
|
||||
}
|
||||
|
||||
return NextResponse.json({ error: '不支持的操作' }, { status: 400 });
|
||||
} catch (error) {
|
||||
console.error('Emby 配置保存失败:', error);
|
||||
return NextResponse.json(
|
||||
{ error: 'Emby 配置保存失败: ' + (error as Error).message },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
252
src/app/api/emby/cms-proxy/[token]/route.ts
Normal file
252
src/app/api/emby/cms-proxy/[token]/route.ts
Normal file
@@ -0,0 +1,252 @@
|
||||
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
|
||||
import { getConfig } from '@/lib/config';
|
||||
import { EmbyClient } from '@/lib/emby.client';
|
||||
|
||||
export const runtime = 'nodejs';
|
||||
|
||||
/**
|
||||
* Emby CMS 代理接口(动态路由)
|
||||
* 将 Emby 媒体库转换为 TVBox 兼容的 CMS API 格式
|
||||
* 路径格式:/api/emby/cms-proxy/{token}?ac=videolist&...
|
||||
*/
|
||||
export async function GET(
|
||||
request: NextRequest,
|
||||
{ params }: { params: { token: string } }
|
||||
) {
|
||||
const { searchParams } = new URL(request.url);
|
||||
const ac = searchParams.get('ac');
|
||||
const wd = searchParams.get('wd'); // 搜索关键词
|
||||
const ids = searchParams.get('ids'); // 视频ID
|
||||
|
||||
// 检查必要参数
|
||||
if (ac !== 'videolist' && ac !== 'list' && ac !== 'detail') {
|
||||
return NextResponse.json(
|
||||
{ code: 400, msg: '不支持的操作' },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
// 验证 TVBox Token
|
||||
const requestToken = params.token;
|
||||
const subscribeToken = process.env.TVBOX_SUBSCRIBE_TOKEN;
|
||||
|
||||
if (!subscribeToken || requestToken !== subscribeToken) {
|
||||
return NextResponse.json({
|
||||
code: 401,
|
||||
msg: '无效的访问token',
|
||||
page: 1,
|
||||
pagecount: 0,
|
||||
limit: 0,
|
||||
total: 0,
|
||||
list: [],
|
||||
});
|
||||
}
|
||||
|
||||
try {
|
||||
const config = await getConfig();
|
||||
const embyConfig = config.EmbyConfig;
|
||||
|
||||
// 验证 Emby 配置
|
||||
if (!embyConfig?.Enabled || !embyConfig.ServerURL) {
|
||||
return NextResponse.json({
|
||||
code: 0,
|
||||
msg: 'Emby 未配置或未启用',
|
||||
page: 1,
|
||||
pagecount: 0,
|
||||
limit: 0,
|
||||
total: 0,
|
||||
list: [],
|
||||
});
|
||||
}
|
||||
|
||||
const client = new EmbyClient(embyConfig);
|
||||
|
||||
// 如果没有 UserId,需要先认证
|
||||
if (!embyConfig.UserId && embyConfig.Username && embyConfig.Password) {
|
||||
const authResult = await client.authenticate(embyConfig.Username, embyConfig.Password);
|
||||
embyConfig.UserId = authResult.User.Id;
|
||||
}
|
||||
|
||||
if (!embyConfig.UserId) {
|
||||
return NextResponse.json({
|
||||
code: 0,
|
||||
msg: 'Emby 认证失败',
|
||||
page: 1,
|
||||
pagecount: 0,
|
||||
limit: 0,
|
||||
total: 0,
|
||||
list: [],
|
||||
});
|
||||
}
|
||||
|
||||
// 路由处理
|
||||
if (wd) {
|
||||
// 搜索模式
|
||||
if (ac === 'detail') {
|
||||
return await handleDetailBySearch(client, wd, requestToken, request);
|
||||
}
|
||||
return await handleSearch(client, wd);
|
||||
} else if (ids || ac === 'detail') {
|
||||
// 详情模式
|
||||
if (!ids) {
|
||||
return NextResponse.json({
|
||||
code: 0,
|
||||
msg: '缺少视频ID',
|
||||
page: 1,
|
||||
pagecount: 0,
|
||||
limit: 0,
|
||||
total: 0,
|
||||
list: [],
|
||||
});
|
||||
}
|
||||
return await handleDetail(client, ids, requestToken, request);
|
||||
} else {
|
||||
// 列表模式
|
||||
return await handleSearch(client, '');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('[Emby CMS Proxy] 错误:', error);
|
||||
return NextResponse.json({
|
||||
code: 500,
|
||||
msg: (error as Error).message,
|
||||
page: 1,
|
||||
pagecount: 0,
|
||||
limit: 0,
|
||||
total: 0,
|
||||
list: [],
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理搜索请求
|
||||
*/
|
||||
async function handleSearch(client: EmbyClient, query: string) {
|
||||
const result = await client.getItems({
|
||||
searchTerm: query || undefined,
|
||||
IncludeItemTypes: 'Movie,Series',
|
||||
Recursive: true,
|
||||
Fields: 'Overview,ProductionYear',
|
||||
Limit: 100,
|
||||
});
|
||||
|
||||
const list = result.Items.map((item) => ({
|
||||
vod_id: item.Id,
|
||||
vod_name: item.Name,
|
||||
vod_pic: client.getImageUrl(item.Id, 'Primary'),
|
||||
vod_remarks: item.Type === 'Movie' ? '电影' : '剧集',
|
||||
vod_year: item.ProductionYear?.toString() || '',
|
||||
vod_content: item.Overview || '',
|
||||
type_name: item.Type === 'Movie' ? '电影' : '电视剧',
|
||||
}));
|
||||
|
||||
return NextResponse.json({
|
||||
code: 1,
|
||||
msg: '数据列表',
|
||||
page: 1,
|
||||
pagecount: 1,
|
||||
limit: list.length,
|
||||
total: list.length,
|
||||
list,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理通过搜索关键词获取详情的请求
|
||||
*/
|
||||
async function handleDetailBySearch(
|
||||
client: EmbyClient,
|
||||
query: string,
|
||||
token: string,
|
||||
request: NextRequest
|
||||
) {
|
||||
const result = await client.getItems({
|
||||
searchTerm: query,
|
||||
IncludeItemTypes: 'Movie,Series',
|
||||
Recursive: true,
|
||||
Fields: 'Overview,ProductionYear',
|
||||
Limit: 1,
|
||||
});
|
||||
|
||||
if (result.Items.length === 0) {
|
||||
return NextResponse.json({
|
||||
code: 0,
|
||||
msg: '未找到该视频',
|
||||
page: 1,
|
||||
pagecount: 0,
|
||||
limit: 0,
|
||||
total: 0,
|
||||
list: [],
|
||||
});
|
||||
}
|
||||
|
||||
return await handleDetail(client, result.Items[0].Id, token, request);
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理详情请求
|
||||
*/
|
||||
async function handleDetail(
|
||||
client: EmbyClient,
|
||||
itemId: string,
|
||||
token: string,
|
||||
request: NextRequest
|
||||
) {
|
||||
const item = await client.getItem(itemId);
|
||||
|
||||
// 获取当前请求的 baseUrl
|
||||
const host = request.headers.get('host') || request.headers.get('x-forwarded-host');
|
||||
const proto = request.headers.get('x-forwarded-proto') ||
|
||||
(host?.includes('localhost') || host?.includes('127.0.0.1') ? 'http' : 'https');
|
||||
const baseUrl = process.env.SITE_BASE || `${proto}://${host}`;
|
||||
|
||||
let vodPlayUrl = '';
|
||||
|
||||
if (item.Type === 'Movie') {
|
||||
// 电影:单个播放链接
|
||||
vodPlayUrl = `正片$${client.getStreamUrl(item.Id)}`;
|
||||
} else if (item.Type === 'Series') {
|
||||
// 剧集:获取所有集
|
||||
const allEpisodes = await client.getEpisodes(itemId);
|
||||
|
||||
const episodes = allEpisodes
|
||||
.sort((a, b) => {
|
||||
if (a.ParentIndexNumber !== b.ParentIndexNumber) {
|
||||
return (a.ParentIndexNumber || 0) - (b.ParentIndexNumber || 0);
|
||||
}
|
||||
return (a.IndexNumber || 0) - (b.IndexNumber || 0);
|
||||
})
|
||||
.map((ep) => {
|
||||
const title = `第${ep.IndexNumber}集`;
|
||||
const playUrl = client.getStreamUrl(ep.Id);
|
||||
return `${title}$${playUrl}`;
|
||||
});
|
||||
|
||||
vodPlayUrl = episodes.join('#');
|
||||
}
|
||||
|
||||
return NextResponse.json({
|
||||
code: 1,
|
||||
msg: '数据列表',
|
||||
page: 1,
|
||||
pagecount: 1,
|
||||
limit: 1,
|
||||
total: 1,
|
||||
list: [
|
||||
{
|
||||
vod_id: item.Id,
|
||||
vod_name: item.Name,
|
||||
vod_pic: client.getImageUrl(item.Id, 'Primary'),
|
||||
vod_remarks: item.Type === 'Movie' ? '电影' : '剧集',
|
||||
vod_year: item.ProductionYear?.toString() || '',
|
||||
vod_content: item.Overview || '',
|
||||
type_name: item.Type === 'Movie' ? '电影' : '电视剧',
|
||||
vod_play_url: vodPlayUrl,
|
||||
vod_play_from: 'Emby',
|
||||
},
|
||||
],
|
||||
});
|
||||
}
|
||||
85
src/app/api/emby/detail/route.ts
Normal file
85
src/app/api/emby/detail/route.ts
Normal file
@@ -0,0 +1,85 @@
|
||||
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
|
||||
import { getConfig } from '@/lib/config';
|
||||
import { EmbyClient } from '@/lib/emby.client';
|
||||
|
||||
export const runtime = 'nodejs';
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
const { searchParams } = new URL(request.url);
|
||||
const itemId = searchParams.get('id');
|
||||
|
||||
if (!itemId) {
|
||||
return NextResponse.json({ error: '缺少媒体ID' }, { status: 400 });
|
||||
}
|
||||
|
||||
try {
|
||||
const config = await getConfig();
|
||||
const embyConfig = config.EmbyConfig;
|
||||
|
||||
if (!embyConfig?.Enabled || !embyConfig.ServerURL) {
|
||||
return NextResponse.json({ error: 'Emby 未配置或未启用' }, { status: 400 });
|
||||
}
|
||||
|
||||
const client = new EmbyClient(embyConfig);
|
||||
|
||||
// 如果没有 UserId,需要先认证
|
||||
if (!embyConfig.UserId && embyConfig.Username && embyConfig.Password) {
|
||||
const authResult = await client.authenticate(embyConfig.Username, embyConfig.Password);
|
||||
embyConfig.UserId = authResult.User.Id;
|
||||
}
|
||||
|
||||
if (!embyConfig.UserId) {
|
||||
return NextResponse.json({ error: 'Emby 认证失败' }, { status: 401 });
|
||||
}
|
||||
|
||||
// 获取媒体详情
|
||||
const item = await client.getItem(itemId);
|
||||
|
||||
let episodes: any[] = [];
|
||||
|
||||
if (item.Type === 'Series') {
|
||||
// 获取所有剧集
|
||||
const allEpisodes = await client.getEpisodes(itemId);
|
||||
|
||||
episodes = allEpisodes
|
||||
.sort((a, b) => {
|
||||
if (a.ParentIndexNumber !== b.ParentIndexNumber) {
|
||||
return (a.ParentIndexNumber || 0) - (b.ParentIndexNumber || 0);
|
||||
}
|
||||
return (a.IndexNumber || 0) - (b.IndexNumber || 0);
|
||||
})
|
||||
.map((ep) => ({
|
||||
id: ep.Id,
|
||||
title: ep.Name,
|
||||
episode: ep.IndexNumber || 0,
|
||||
season: ep.ParentIndexNumber || 1,
|
||||
overview: ep.Overview || '',
|
||||
playUrl: client.getStreamUrl(ep.Id),
|
||||
}));
|
||||
}
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
item: {
|
||||
id: item.Id,
|
||||
title: item.Name,
|
||||
type: item.Type === 'Movie' ? 'movie' : 'tv',
|
||||
overview: item.Overview || '',
|
||||
poster: client.getImageUrl(item.Id, 'Primary'),
|
||||
year: item.ProductionYear?.toString() || '',
|
||||
rating: item.CommunityRating || 0,
|
||||
playUrl: item.Type === 'Movie' ? client.getStreamUrl(item.Id) : undefined,
|
||||
},
|
||||
episodes: item.Type === 'Series' ? episodes : [],
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('获取 Emby 详情失败:', error);
|
||||
return NextResponse.json(
|
||||
{ error: '获取 Emby 详情失败: ' + (error as Error).message },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
100
src/app/api/emby/list/route.ts
Normal file
100
src/app/api/emby/list/route.ts
Normal file
@@ -0,0 +1,100 @@
|
||||
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
|
||||
import { getConfig } from '@/lib/config';
|
||||
import { EmbyClient } from '@/lib/emby.client';
|
||||
|
||||
export const runtime = 'nodejs';
|
||||
|
||||
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');
|
||||
|
||||
try {
|
||||
const config = await getConfig();
|
||||
const embyConfig = config.EmbyConfig;
|
||||
|
||||
console.log('[Emby List] EmbyConfig:', JSON.stringify(embyConfig, null, 2));
|
||||
|
||||
if (!embyConfig?.Enabled || !embyConfig.ServerURL) {
|
||||
return NextResponse.json({
|
||||
error: 'Emby 未配置或未启用',
|
||||
list: [],
|
||||
totalPages: 0,
|
||||
currentPage: page,
|
||||
total: 0,
|
||||
});
|
||||
}
|
||||
|
||||
// 创建 Emby 客户端
|
||||
const client = new EmbyClient(embyConfig);
|
||||
|
||||
// 如果使用用户名密码且没有 UserId,需要先认证
|
||||
if (!embyConfig.ApiKey && !embyConfig.UserId && embyConfig.Username && embyConfig.Password) {
|
||||
try {
|
||||
const authResult = await client.authenticate(embyConfig.Username, embyConfig.Password);
|
||||
embyConfig.UserId = authResult.User.Id;
|
||||
} catch (error) {
|
||||
return NextResponse.json({
|
||||
error: 'Emby 认证失败: ' + (error as Error).message,
|
||||
list: [],
|
||||
totalPages: 0,
|
||||
currentPage: page,
|
||||
total: 0,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// 验证认证信息:必须有 ApiKey 或 UserId
|
||||
if (!embyConfig.ApiKey && !embyConfig.UserId) {
|
||||
return NextResponse.json({
|
||||
error: 'Emby 认证失败,请检查配置',
|
||||
list: [],
|
||||
totalPages: 0,
|
||||
currentPage: page,
|
||||
total: 0,
|
||||
});
|
||||
}
|
||||
|
||||
// 获取媒体列表
|
||||
const result = await client.getItems({
|
||||
IncludeItemTypes: 'Movie,Series',
|
||||
Recursive: true,
|
||||
Fields: 'Overview,ProductionYear',
|
||||
SortBy: 'SortName',
|
||||
SortOrder: 'Ascending',
|
||||
StartIndex: (page - 1) * pageSize,
|
||||
Limit: pageSize,
|
||||
});
|
||||
|
||||
const list = result.Items.map((item) => ({
|
||||
id: item.Id,
|
||||
title: item.Name,
|
||||
poster: client.getImageUrl(item.Id, 'Primary'),
|
||||
year: item.ProductionYear?.toString() || '',
|
||||
rating: item.CommunityRating || 0,
|
||||
mediaType: item.Type === 'Movie' ? 'movie' : 'tv',
|
||||
}));
|
||||
|
||||
const totalPages = Math.ceil(result.TotalRecordCount / pageSize);
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
list,
|
||||
totalPages,
|
||||
currentPage: page,
|
||||
total: result.TotalRecordCount,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('获取 Emby 列表失败:', error);
|
||||
return NextResponse.json({
|
||||
error: '获取 Emby 列表失败: ' + (error as Error).message,
|
||||
list: [],
|
||||
totalPages: 0,
|
||||
currentPage: page,
|
||||
total: 0,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -44,6 +44,46 @@ export async function GET(request: NextRequest) {
|
||||
config.OpenListConfig?.Password
|
||||
);
|
||||
|
||||
// 检查是否配置了 Emby
|
||||
const hasEmby = !!(
|
||||
config.EmbyConfig?.Enabled &&
|
||||
config.EmbyConfig?.ServerURL &&
|
||||
config.EmbyConfig?.UserId
|
||||
);
|
||||
|
||||
// 搜索 Emby(如果配置了)
|
||||
let embyResults: any[] = [];
|
||||
if (hasEmby) {
|
||||
try {
|
||||
const { EmbyClient } = await import('@/lib/emby.client');
|
||||
const client = new EmbyClient(config.EmbyConfig!);
|
||||
|
||||
const searchResult = await client.getItems({
|
||||
searchTerm: query,
|
||||
IncludeItemTypes: 'Movie,Series',
|
||||
Recursive: true,
|
||||
Fields: 'Overview,ProductionYear',
|
||||
Limit: 50,
|
||||
});
|
||||
|
||||
embyResults = searchResult.Items.map((item) => ({
|
||||
id: item.Id,
|
||||
source: 'emby',
|
||||
source_name: 'Emby',
|
||||
title: item.Name,
|
||||
poster: client.getImageUrl(item.Id, 'Primary'),
|
||||
episodes: [],
|
||||
episodes_titles: [],
|
||||
year: item.ProductionYear?.toString() || '',
|
||||
desc: item.Overview || '',
|
||||
type_name: item.Type === 'Movie' ? '电影' : '电视剧',
|
||||
douban_id: 0,
|
||||
}));
|
||||
} catch (error) {
|
||||
console.error('[Search] 搜索 Emby 失败:', error);
|
||||
}
|
||||
}
|
||||
|
||||
// 搜索 OpenList(如果配置了)
|
||||
let openlistResults: any[] = [];
|
||||
if (hasOpenList) {
|
||||
@@ -114,7 +154,7 @@ export async function GET(request: NextRequest) {
|
||||
const successResults = results
|
||||
.filter((result) => result.status === 'fulfilled')
|
||||
.map((result) => (result as PromiseFulfilledResult<any>).value);
|
||||
let flattenedResults = [...openlistResults, ...successResults.flat()];
|
||||
let flattenedResults = [...embyResults, ...openlistResults, ...successResults.flat()];
|
||||
if (!config.SiteConfig.DisableYellowFilter) {
|
||||
flattenedResults = flattenedResults.filter((result) => {
|
||||
const typeName = result.type_name || '';
|
||||
|
||||
@@ -41,6 +41,13 @@ export async function GET(request: NextRequest) {
|
||||
config.OpenListConfig?.Password
|
||||
);
|
||||
|
||||
// 检查是否配置了 Emby
|
||||
const hasEmby = !!(
|
||||
config.EmbyConfig?.Enabled &&
|
||||
config.EmbyConfig?.ServerURL &&
|
||||
config.EmbyConfig?.UserId
|
||||
);
|
||||
|
||||
// 共享状态
|
||||
let streamClosed = false;
|
||||
|
||||
@@ -70,7 +77,7 @@ export async function GET(request: NextRequest) {
|
||||
const startEvent = `data: ${JSON.stringify({
|
||||
type: 'start',
|
||||
query,
|
||||
totalSources: apiSites.length + (hasOpenList ? 1 : 0),
|
||||
totalSources: apiSites.length + (hasOpenList ? 1 : 0) + (hasEmby ? 1 : 0),
|
||||
timestamp: Date.now()
|
||||
})}\n\n`;
|
||||
|
||||
@@ -82,6 +89,75 @@ export async function GET(request: NextRequest) {
|
||||
let completedSources = 0;
|
||||
const allResults: any[] = [];
|
||||
|
||||
// 搜索 Emby(如果配置了)
|
||||
if (hasEmby) {
|
||||
try {
|
||||
const { EmbyClient } = await import('@/lib/emby.client');
|
||||
const client = new EmbyClient(config.EmbyConfig!);
|
||||
|
||||
const searchResult = await client.getItems({
|
||||
searchTerm: query,
|
||||
IncludeItemTypes: 'Movie,Series',
|
||||
Recursive: true,
|
||||
Fields: 'Overview,ProductionYear',
|
||||
Limit: 50,
|
||||
});
|
||||
|
||||
const embyResults = searchResult.Items.map((item) => ({
|
||||
id: item.Id,
|
||||
source: 'emby',
|
||||
source_name: 'Emby',
|
||||
title: item.Name,
|
||||
poster: client.getImageUrl(item.Id, 'Primary'),
|
||||
episodes: [],
|
||||
episodes_titles: [],
|
||||
year: item.ProductionYear?.toString() || '',
|
||||
desc: item.Overview || '',
|
||||
type_name: item.Type === 'Movie' ? '电影' : '电视剧',
|
||||
douban_id: 0,
|
||||
}));
|
||||
|
||||
completedSources++;
|
||||
|
||||
if (!streamClosed) {
|
||||
const sourceEvent = `data: ${JSON.stringify({
|
||||
type: 'source_result',
|
||||
source: 'emby',
|
||||
sourceName: 'Emby',
|
||||
results: embyResults,
|
||||
timestamp: Date.now()
|
||||
})}\n\n`;
|
||||
|
||||
if (!safeEnqueue(encoder.encode(sourceEvent))) {
|
||||
streamClosed = true;
|
||||
return;
|
||||
}
|
||||
|
||||
if (embyResults.length > 0) {
|
||||
allResults.push(...embyResults);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('[Search WS] 搜索 Emby 失败:', error);
|
||||
completedSources++;
|
||||
|
||||
if (!streamClosed) {
|
||||
const errorEvent = `data: ${JSON.stringify({
|
||||
type: 'source_error',
|
||||
source: 'emby',
|
||||
sourceName: 'Emby',
|
||||
error: error instanceof Error ? error.message : '搜索失败',
|
||||
timestamp: Date.now()
|
||||
})}\n\n`;
|
||||
|
||||
if (!safeEnqueue(encoder.encode(errorEvent))) {
|
||||
streamClosed = true;
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 搜索 OpenList(如果配置了)
|
||||
if (hasOpenList) {
|
||||
try {
|
||||
@@ -254,7 +330,7 @@ export async function GET(request: NextRequest) {
|
||||
}
|
||||
|
||||
// 检查是否所有源都已完成
|
||||
if (completedSources === apiSites.length + (hasOpenList ? 1 : 0)) {
|
||||
if (completedSources === apiSites.length + (hasOpenList ? 1 : 0) + (hasEmby ? 1 : 0)) {
|
||||
if (!streamClosed) {
|
||||
// 发送最终完成事件
|
||||
const completeEvent = `data: ${JSON.stringify({
|
||||
|
||||
@@ -27,6 +27,92 @@ export async function GET(request: NextRequest) {
|
||||
return NextResponse.json({ error: '缺少必要参数' }, { status: 400 });
|
||||
}
|
||||
|
||||
// 特殊处理 emby 源
|
||||
if (sourceCode === 'emby') {
|
||||
try {
|
||||
const config = await getConfig();
|
||||
const embyConfig = config.EmbyConfig;
|
||||
|
||||
if (!embyConfig || !embyConfig.Enabled || !embyConfig.ServerURL) {
|
||||
throw new Error('Emby 未配置或未启用');
|
||||
}
|
||||
|
||||
const { EmbyClient } = await import('@/lib/emby.client');
|
||||
const client = new EmbyClient(embyConfig);
|
||||
|
||||
// 获取媒体详情
|
||||
const item = await client.getItem(id);
|
||||
|
||||
// 根据类型处理
|
||||
if (item.Type === 'Movie') {
|
||||
// 电影
|
||||
const subtitles = client.getSubtitles(item);
|
||||
|
||||
const result = {
|
||||
source: 'emby',
|
||||
source_name: 'Emby',
|
||||
id: item.Id,
|
||||
title: item.Name,
|
||||
poster: client.getImageUrl(item.Id, 'Primary'),
|
||||
year: item.ProductionYear?.toString() || '',
|
||||
douban_id: 0,
|
||||
desc: item.Overview || '',
|
||||
episodes: [client.getStreamUrl(item.Id)],
|
||||
episodes_titles: [item.Name],
|
||||
subtitles: subtitles.length > 0 ? [subtitles] : [],
|
||||
proxyMode: false,
|
||||
};
|
||||
|
||||
return NextResponse.json(result);
|
||||
} else if (item.Type === 'Series') {
|
||||
// 剧集 - 获取所有季和集
|
||||
const seasons = await client.getSeasons(item.Id);
|
||||
const allEpisodes: any[] = [];
|
||||
|
||||
for (const season of seasons) {
|
||||
const episodes = await client.getEpisodes(item.Id, season.Id);
|
||||
allEpisodes.push(...episodes);
|
||||
}
|
||||
|
||||
// 按季和集排序
|
||||
allEpisodes.sort((a, b) => {
|
||||
if (a.ParentIndexNumber !== b.ParentIndexNumber) {
|
||||
return (a.ParentIndexNumber || 0) - (b.ParentIndexNumber || 0);
|
||||
}
|
||||
return (a.IndexNumber || 0) - (b.IndexNumber || 0);
|
||||
});
|
||||
|
||||
const result = {
|
||||
source: 'emby',
|
||||
source_name: 'Emby',
|
||||
id: item.Id,
|
||||
title: item.Name,
|
||||
poster: client.getImageUrl(item.Id, 'Primary'),
|
||||
year: item.ProductionYear?.toString() || '',
|
||||
douban_id: 0,
|
||||
desc: item.Overview || '',
|
||||
episodes: allEpisodes.map((ep) => client.getStreamUrl(ep.Id)),
|
||||
episodes_titles: allEpisodes.map((ep) => {
|
||||
const seasonNum = ep.ParentIndexNumber || 1;
|
||||
const episodeNum = ep.IndexNumber || 1;
|
||||
return `S${seasonNum.toString().padStart(2, '0')}E${episodeNum.toString().padStart(2, '0')}`;
|
||||
}),
|
||||
subtitles: allEpisodes.map((ep) => client.getSubtitles(ep)),
|
||||
proxyMode: false,
|
||||
};
|
||||
|
||||
return NextResponse.json(result);
|
||||
} else {
|
||||
throw new Error('不支持的媒体类型');
|
||||
}
|
||||
} catch (error) {
|
||||
return NextResponse.json(
|
||||
{ error: (error as Error).message },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// 特殊处理 openlist 源 - 直接调用 /api/detail
|
||||
if (sourceCode === 'openlist') {
|
||||
try {
|
||||
|
||||
Reference in New Issue
Block a user