私人影库增加追番订阅功能
This commit is contained in:
@@ -25,6 +25,7 @@ import {
|
||||
AlertCircle,
|
||||
AlertTriangle,
|
||||
Bot,
|
||||
Cat,
|
||||
Check,
|
||||
CheckCircle,
|
||||
ChevronDown,
|
||||
@@ -50,6 +51,7 @@ import { createPortal } from 'react-dom';
|
||||
import { AdminConfig, AdminConfigResult } from '@/lib/admin.types';
|
||||
import { getAuthInfoFromBrowserCookie } from '@/lib/auth';
|
||||
|
||||
import AnimeSubscriptionComponent from '@/components/AnimeSubscriptionComponent';
|
||||
import CorrectDialog from '@/components/CorrectDialog';
|
||||
import DataMigration from '@/components/DataMigration';
|
||||
import PageLayout from '@/components/PageLayout';
|
||||
@@ -11597,6 +11599,7 @@ function AdminPageClient() {
|
||||
openListConfig: false,
|
||||
embyConfig: false,
|
||||
xiaoyaConfig: false,
|
||||
animeSubscription: false,
|
||||
aiConfig: false,
|
||||
liveSource: false,
|
||||
webLive: false,
|
||||
@@ -12049,6 +12052,18 @@ function AdminPageClient() {
|
||||
>
|
||||
<MovieRequestsComponent config={config} refreshConfig={fetchConfig} />
|
||||
</CollapsibleTab>
|
||||
|
||||
{/* 追番订阅子标签 */}
|
||||
<CollapsibleTab
|
||||
title='追番订阅'
|
||||
icon={
|
||||
<Cat size={20} className='text-gray-600 dark:text-gray-400' />
|
||||
}
|
||||
isExpanded={expandedTabs.animeSubscription}
|
||||
onToggle={() => toggleTab('animeSubscription')}
|
||||
>
|
||||
<AnimeSubscriptionComponent config={config} refreshConfig={fetchConfig} />
|
||||
</CollapsibleTab>
|
||||
</div>
|
||||
</CollapsibleTab>
|
||||
|
||||
|
||||
51
src/app/api/admin/anime-subscription/[id]/check/route.ts
Normal file
51
src/app/api/admin/anime-subscription/[id]/check/route.ts
Normal file
@@ -0,0 +1,51 @@
|
||||
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
|
||||
import { checkSubscription } from '@/lib/anime-subscription';
|
||||
import { getAuthInfoFromCookie } from '@/lib/auth';
|
||||
import { getConfig } from '@/lib/config';
|
||||
import { db } from '@/lib/db';
|
||||
|
||||
export const runtime = 'nodejs';
|
||||
|
||||
/**
|
||||
* POST /api/admin/anime-subscription/[id]/check
|
||||
* 手动触发检查单个订阅
|
||||
*/
|
||||
export async function POST(
|
||||
req: NextRequest,
|
||||
{ params }: { params: { id: string } }
|
||||
) {
|
||||
try {
|
||||
// 权限检查
|
||||
const authInfo = getAuthInfoFromCookie(req);
|
||||
if (!authInfo || (authInfo.role !== 'admin' && authInfo.role !== 'owner')) {
|
||||
return NextResponse.json({ error: '无权限访问' }, { status: 403 });
|
||||
}
|
||||
|
||||
const config = await getConfig();
|
||||
const subscriptions = config.AnimeSubscriptionConfig?.Subscriptions || [];
|
||||
|
||||
const subscription = subscriptions.find((sub) => sub.id === params.id);
|
||||
if (!subscription) {
|
||||
return NextResponse.json({ error: '订阅不存在' }, { status: 404 });
|
||||
}
|
||||
|
||||
// 执行检查逻辑(忽略时间间隔限制)
|
||||
const result = await checkSubscription(subscription);
|
||||
|
||||
// 保存配置
|
||||
await db.saveAdminConfig(config);
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
...result,
|
||||
});
|
||||
} catch (error: any) {
|
||||
console.error('检查追番订阅失败:', error);
|
||||
return NextResponse.json(
|
||||
{ error: error.message || '检查失败' },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
112
src/app/api/admin/anime-subscription/[id]/route.ts
Normal file
112
src/app/api/admin/anime-subscription/[id]/route.ts
Normal file
@@ -0,0 +1,112 @@
|
||||
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
|
||||
import { getAuthInfoFromCookie } from '@/lib/auth';
|
||||
import { getConfig } from '@/lib/config';
|
||||
import { db } from '@/lib/db';
|
||||
|
||||
export const runtime = 'nodejs';
|
||||
|
||||
/**
|
||||
* PUT /api/admin/anime-subscription/[id]
|
||||
* 更新订阅
|
||||
*/
|
||||
export async function PUT(
|
||||
req: NextRequest,
|
||||
{ params }: { params: { id: string } }
|
||||
) {
|
||||
try {
|
||||
// 权限检查
|
||||
const authInfo = getAuthInfoFromCookie(req);
|
||||
if (!authInfo || (authInfo.role !== 'admin' && authInfo.role !== 'owner')) {
|
||||
return NextResponse.json({ error: '无权限访问' }, { status: 403 });
|
||||
}
|
||||
|
||||
const config = await getConfig();
|
||||
const subscriptions = config.AnimeSubscriptionConfig?.Subscriptions || [];
|
||||
|
||||
const index = subscriptions.findIndex((sub) => sub.id === params.id);
|
||||
if (index === -1) {
|
||||
return NextResponse.json({ error: '订阅不存在' }, { status: 404 });
|
||||
}
|
||||
|
||||
const updates = await req.json();
|
||||
const subscription = subscriptions[index];
|
||||
|
||||
// 更新字段
|
||||
if (updates.title !== undefined) {
|
||||
subscription.title = updates.title.trim();
|
||||
}
|
||||
if (updates.filterText !== undefined) {
|
||||
subscription.filterText = updates.filterText.trim();
|
||||
}
|
||||
if (updates.source !== undefined) {
|
||||
if (!['acgrip', 'mikan', 'dmhy'].includes(updates.source)) {
|
||||
return NextResponse.json({ error: '无效的搜索源' }, { status: 400 });
|
||||
}
|
||||
subscription.source = updates.source;
|
||||
}
|
||||
if (updates.enabled !== undefined) {
|
||||
subscription.enabled = updates.enabled;
|
||||
}
|
||||
if (updates.lastEpisode !== undefined) {
|
||||
// 验证集数为非负整数
|
||||
const episode = parseInt(String(updates.lastEpisode), 10);
|
||||
if (isNaN(episode) || episode < 0) {
|
||||
return NextResponse.json(
|
||||
{ error: '集数必须是非负整数' },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
subscription.lastEpisode = episode;
|
||||
}
|
||||
|
||||
subscription.updatedAt = Date.now();
|
||||
|
||||
await db.saveAdminConfig(config);
|
||||
|
||||
return NextResponse.json(subscription);
|
||||
} catch (error: any) {
|
||||
console.error('更新追番订阅失败:', error);
|
||||
return NextResponse.json(
|
||||
{ error: error.message || '更新订阅失败' },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* DELETE /api/admin/anime-subscription/[id]
|
||||
* 删除订阅
|
||||
*/
|
||||
export async function DELETE(
|
||||
req: NextRequest,
|
||||
{ params }: { params: { id: string } }
|
||||
) {
|
||||
try {
|
||||
// 权限检查
|
||||
const authInfo = getAuthInfoFromCookie(req);
|
||||
if (!authInfo || (authInfo.role !== 'admin' && authInfo.role !== 'owner')) {
|
||||
return NextResponse.json({ error: '无权限访问' }, { status: 403 });
|
||||
}
|
||||
|
||||
const config = await getConfig();
|
||||
const subscriptions = config.AnimeSubscriptionConfig?.Subscriptions || [];
|
||||
|
||||
const index = subscriptions.findIndex((sub) => sub.id === params.id);
|
||||
if (index === -1) {
|
||||
return NextResponse.json({ error: '订阅不存在' }, { status: 404 });
|
||||
}
|
||||
|
||||
subscriptions.splice(index, 1);
|
||||
await db.saveAdminConfig(config);
|
||||
|
||||
return NextResponse.json({ success: true });
|
||||
} catch (error: any) {
|
||||
console.error('删除追番订阅失败:', error);
|
||||
return NextResponse.json(
|
||||
{ error: error.message || '删除订阅失败' },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
106
src/app/api/admin/anime-subscription/route.ts
Normal file
106
src/app/api/admin/anime-subscription/route.ts
Normal file
@@ -0,0 +1,106 @@
|
||||
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
|
||||
import { getAuthInfoFromCookie } from '@/lib/auth';
|
||||
import { getConfig } from '@/lib/config';
|
||||
import { db } from '@/lib/db';
|
||||
import { AnimeSubscription } from '@/types/anime-subscription';
|
||||
|
||||
export const runtime = 'nodejs';
|
||||
|
||||
/**
|
||||
* GET /api/admin/anime-subscription
|
||||
* 获取订阅列表和配置
|
||||
*/
|
||||
export async function GET(req: NextRequest) {
|
||||
try {
|
||||
// 权限检查
|
||||
const authInfo = getAuthInfoFromCookie(req);
|
||||
if (!authInfo || (authInfo.role !== 'admin' && authInfo.role !== 'owner')) {
|
||||
return NextResponse.json({ error: '无权限访问' }, { status: 403 });
|
||||
}
|
||||
|
||||
const config = await getConfig();
|
||||
const animeConfig = config.AnimeSubscriptionConfig || {
|
||||
Enabled: false,
|
||||
Subscriptions: [],
|
||||
};
|
||||
|
||||
return NextResponse.json(animeConfig);
|
||||
} catch (error: any) {
|
||||
console.error('获取追番订阅配置失败:', error);
|
||||
return NextResponse.json(
|
||||
{ error: error.message || '获取配置失败' },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* POST /api/admin/anime-subscription
|
||||
* 创建新订阅
|
||||
*/
|
||||
export async function POST(req: NextRequest) {
|
||||
try {
|
||||
// 权限检查
|
||||
const authInfo = getAuthInfoFromCookie(req);
|
||||
if (!authInfo || (authInfo.role !== 'admin' && authInfo.role !== 'owner')) {
|
||||
return NextResponse.json({ error: '无权限访问' }, { status: 403 });
|
||||
}
|
||||
|
||||
const { title, filterText, source, enabled, lastEpisode } =
|
||||
await req.json();
|
||||
|
||||
// 验证必填字段
|
||||
if (!title || !filterText || !source) {
|
||||
return NextResponse.json({ error: '缺少必填字段' }, { status: 400 });
|
||||
}
|
||||
|
||||
// 验证 source
|
||||
if (!['acgrip', 'mikan', 'dmhy'].includes(source)) {
|
||||
return NextResponse.json({ error: '无效的搜索源' }, { status: 400 });
|
||||
}
|
||||
|
||||
const config = await getConfig();
|
||||
if (!config.AnimeSubscriptionConfig) {
|
||||
config.AnimeSubscriptionConfig = { Enabled: false, Subscriptions: [] };
|
||||
}
|
||||
|
||||
// 验证集数
|
||||
let episodeNum = 0;
|
||||
if (lastEpisode !== undefined) {
|
||||
episodeNum = parseInt(String(lastEpisode), 10);
|
||||
if (isNaN(episodeNum) || episodeNum < 0) {
|
||||
return NextResponse.json(
|
||||
{ error: '集数必须是非负整数' },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// 创建新订阅
|
||||
const newSubscription: AnimeSubscription = {
|
||||
id: crypto.randomUUID(),
|
||||
title: title.trim(),
|
||||
filterText: filterText.trim(),
|
||||
source,
|
||||
enabled: enabled ?? true,
|
||||
lastCheckTime: 0,
|
||||
lastEpisode: episodeNum,
|
||||
createdAt: Date.now(),
|
||||
updatedAt: Date.now(),
|
||||
createdBy: authInfo.username || 'unknown',
|
||||
};
|
||||
|
||||
config.AnimeSubscriptionConfig.Subscriptions.push(newSubscription);
|
||||
await db.saveAdminConfig(config);
|
||||
|
||||
return NextResponse.json(newSubscription);
|
||||
} catch (error: any) {
|
||||
console.error('创建追番订阅失败:', error);
|
||||
return NextResponse.json(
|
||||
{ error: error.message || '创建订阅失败' },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
47
src/app/api/admin/anime-subscription/toggle/route.ts
Normal file
47
src/app/api/admin/anime-subscription/toggle/route.ts
Normal file
@@ -0,0 +1,47 @@
|
||||
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
|
||||
import { getAuthInfoFromCookie } from '@/lib/auth';
|
||||
import { getConfig } from '@/lib/config';
|
||||
import { db } from '@/lib/db';
|
||||
|
||||
export const runtime = 'nodejs';
|
||||
|
||||
/**
|
||||
* PUT /api/admin/anime-subscription/toggle
|
||||
* 切换追番功能启用状态
|
||||
*/
|
||||
export async function PUT(req: NextRequest) {
|
||||
try {
|
||||
// 权限检查
|
||||
const authInfo = getAuthInfoFromCookie(req);
|
||||
if (!authInfo || (authInfo.role !== 'admin' && authInfo.role !== 'owner')) {
|
||||
return NextResponse.json({ error: '无权限访问' }, { status: 403 });
|
||||
}
|
||||
|
||||
const { enabled } = await req.json();
|
||||
|
||||
if (typeof enabled !== 'boolean') {
|
||||
return NextResponse.json(
|
||||
{ error: 'enabled 必须是布尔值' },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const config = await getConfig();
|
||||
if (!config.AnimeSubscriptionConfig) {
|
||||
config.AnimeSubscriptionConfig = { Enabled: false, Subscriptions: [] };
|
||||
}
|
||||
|
||||
config.AnimeSubscriptionConfig.Enabled = enabled;
|
||||
await db.saveAdminConfig(config);
|
||||
|
||||
return NextResponse.json({ success: true, enabled });
|
||||
} catch (error: any) {
|
||||
console.error('切换追番功能状态失败:', error);
|
||||
return NextResponse.json(
|
||||
{ error: error.message || '切换状态失败' },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
|
||||
import { checkAnimeSubscriptions } from '@/lib/anime-subscription';
|
||||
import { getConfig, refineConfig } from '@/lib/config';
|
||||
import { db, getStorage } from '@/lib/db';
|
||||
import { EmailService } from '@/lib/email.service';
|
||||
@@ -57,6 +58,7 @@ async function cronJob() {
|
||||
await refreshAllLiveChannels();
|
||||
await refreshOpenList();
|
||||
await refreshRecordAndFavorites();
|
||||
await checkAnimeSubscriptions();
|
||||
}
|
||||
|
||||
async function refreshAllLiveChannels() {
|
||||
|
||||
691
src/components/AnimeSubscriptionComponent.tsx
Normal file
691
src/components/AnimeSubscriptionComponent.tsx
Normal file
@@ -0,0 +1,691 @@
|
||||
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||
'use client';
|
||||
|
||||
import { AlertCircle, Loader2, Plus, RefreshCw, Trash2, X } from 'lucide-react';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { createPortal } from 'react-dom';
|
||||
|
||||
import { AdminConfig } from '@/lib/admin.types';
|
||||
import { AnimeSubscription } from '@/types/anime-subscription';
|
||||
|
||||
interface AnimeSubscriptionComponentProps {
|
||||
config: AdminConfig | null;
|
||||
refreshConfig: () => Promise<void>;
|
||||
}
|
||||
|
||||
// Switch 组件
|
||||
const Switch = ({ checked, onChange, disabled }: { checked: boolean; onChange: (checked: boolean) => void; disabled?: boolean }) => (
|
||||
<button
|
||||
type='button'
|
||||
role='switch'
|
||||
aria-checked={checked}
|
||||
disabled={disabled}
|
||||
onClick={() => onChange(!checked)}
|
||||
className={`
|
||||
relative inline-flex h-6 w-11 items-center rounded-full transition-colors
|
||||
${checked ? 'bg-green-600' : 'bg-gray-200 dark:bg-gray-700'}
|
||||
${disabled ? 'opacity-50 cursor-not-allowed' : 'cursor-pointer'}
|
||||
`}
|
||||
>
|
||||
<span
|
||||
className={`
|
||||
inline-block h-4 w-4 transform rounded-full bg-white transition-transform
|
||||
${checked ? 'translate-x-6' : 'translate-x-1'}
|
||||
`}
|
||||
/>
|
||||
</button>
|
||||
);
|
||||
|
||||
// AlertModal 组件
|
||||
interface AlertModalProps {
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
type: 'success' | 'error' | 'warning' | 'info';
|
||||
title: string;
|
||||
message?: string;
|
||||
confirmText?: string;
|
||||
onConfirm?: () => void;
|
||||
showConfirm?: boolean;
|
||||
}
|
||||
|
||||
const AlertModal = ({
|
||||
isOpen,
|
||||
onClose,
|
||||
type,
|
||||
title,
|
||||
message,
|
||||
confirmText = '确定',
|
||||
onConfirm,
|
||||
showConfirm = false,
|
||||
}: AlertModalProps) => {
|
||||
const [isVisible, setIsVisible] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (isOpen) {
|
||||
setIsVisible(true);
|
||||
} else {
|
||||
setIsVisible(false);
|
||||
}
|
||||
}, [isOpen]);
|
||||
|
||||
if (!isOpen) return null;
|
||||
|
||||
const icons = {
|
||||
success: <AlertCircle className="w-12 h-12 text-green-500" />,
|
||||
error: <AlertCircle className="w-12 h-12 text-red-500" />,
|
||||
warning: <AlertCircle className="w-12 h-12 text-yellow-500" />,
|
||||
info: <AlertCircle className="w-12 h-12 text-blue-500" />,
|
||||
};
|
||||
|
||||
return createPortal(
|
||||
<div className="fixed inset-0 z-[9999] flex items-center justify-center">
|
||||
<div
|
||||
className={`absolute inset-0 bg-black transition-opacity duration-300 ${
|
||||
isVisible ? 'opacity-50' : 'opacity-0'
|
||||
}`}
|
||||
onClick={onClose}
|
||||
/>
|
||||
<div
|
||||
className={`relative bg-white dark:bg-gray-800 rounded-lg shadow-xl max-w-md w-full mx-4 p-6 transition-all duration-300 ${
|
||||
isVisible ? 'opacity-100 scale-100' : 'opacity-0 scale-95'
|
||||
}`}
|
||||
>
|
||||
<div className="flex flex-col items-center text-center">
|
||||
{icons[type]}
|
||||
<h3 className="mt-4 text-lg font-semibold text-gray-900 dark:text-white">
|
||||
{title}
|
||||
</h3>
|
||||
{message && (
|
||||
<p className="mt-2 text-sm text-gray-600 dark:text-gray-400">
|
||||
{message}
|
||||
</p>
|
||||
)}
|
||||
|
||||
<div className="flex justify-center space-x-3 mt-6">
|
||||
{showConfirm && onConfirm ? (
|
||||
<>
|
||||
<button
|
||||
onClick={onClose}
|
||||
className="px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 bg-gray-100 dark:bg-gray-700 hover:bg-gray-200 dark:hover:bg-gray-600 rounded-lg transition-colors"
|
||||
>
|
||||
取消
|
||||
</button>
|
||||
<button
|
||||
onClick={() => {
|
||||
onConfirm();
|
||||
onClose();
|
||||
}}
|
||||
className="px-4 py-2 text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 rounded-lg transition-colors"
|
||||
>
|
||||
{confirmText}
|
||||
</button>
|
||||
</>
|
||||
) : (
|
||||
<button
|
||||
onClick={onClose}
|
||||
className="px-4 py-2 text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 rounded-lg transition-colors"
|
||||
>
|
||||
{confirmText}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>,
|
||||
document.body
|
||||
);
|
||||
};
|
||||
|
||||
export default function AnimeSubscriptionComponent({
|
||||
config,
|
||||
refreshConfig,
|
||||
}: AnimeSubscriptionComponentProps) {
|
||||
const [enabled, setEnabled] = useState(false);
|
||||
const [subscriptions, setSubscriptions] = useState<AnimeSubscription[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [showAddForm, setShowAddForm] = useState(false);
|
||||
const [editingSubscription, setEditingSubscription] = useState<AnimeSubscription | null>(null);
|
||||
const [checkingId, setCheckingId] = useState<string | null>(null);
|
||||
const [alertModal, setAlertModal] = useState<{
|
||||
isOpen: boolean;
|
||||
type: 'success' | 'error' | 'warning' | 'info';
|
||||
title: string;
|
||||
message?: string;
|
||||
confirmText?: string;
|
||||
onConfirm?: () => void;
|
||||
showConfirm?: boolean;
|
||||
}>({
|
||||
isOpen: false,
|
||||
type: 'success',
|
||||
title: '',
|
||||
});
|
||||
|
||||
const showAlert = (config: Omit<typeof alertModal, 'isOpen'>) => {
|
||||
setAlertModal({ ...config, isOpen: true });
|
||||
};
|
||||
|
||||
const hideAlert = () => {
|
||||
setAlertModal(prev => ({ ...prev, isOpen: false }));
|
||||
};
|
||||
|
||||
// 表单状态
|
||||
const [formData, setFormData] = useState({
|
||||
title: '',
|
||||
filterText: '',
|
||||
source: 'mikan' as 'acgrip' | 'mikan' | 'dmhy',
|
||||
lastEpisode: 0,
|
||||
enabled: true,
|
||||
});
|
||||
|
||||
// 加载配置
|
||||
useEffect(() => {
|
||||
if (config?.AnimeSubscriptionConfig) {
|
||||
setEnabled(config.AnimeSubscriptionConfig.Enabled || false);
|
||||
setSubscriptions(config.AnimeSubscriptionConfig.Subscriptions || []);
|
||||
}
|
||||
}, [config]);
|
||||
|
||||
// 重置表单
|
||||
const resetForm = () => {
|
||||
setFormData({
|
||||
title: '',
|
||||
filterText: '',
|
||||
source: 'mikan',
|
||||
lastEpisode: 0,
|
||||
enabled: true,
|
||||
});
|
||||
setEditingSubscription(null);
|
||||
setShowAddForm(false);
|
||||
};
|
||||
|
||||
// 切换启用状态
|
||||
const handleToggleEnabled = async (newEnabled: boolean) => {
|
||||
try {
|
||||
setLoading(true);
|
||||
const response = await fetch('/api/admin/anime-subscription/toggle', {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ enabled: newEnabled }),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error('切换状态失败');
|
||||
}
|
||||
|
||||
setEnabled(newEnabled);
|
||||
await refreshConfig();
|
||||
} catch (error) {
|
||||
showAlert({
|
||||
type: 'error',
|
||||
title: '切换状态失败',
|
||||
message: error instanceof Error ? error.message : '切换状态失败',
|
||||
});
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
// 开始添加
|
||||
const handleAdd = () => {
|
||||
resetForm();
|
||||
setShowAddForm(true);
|
||||
};
|
||||
|
||||
// 开始编辑
|
||||
const handleEdit = (sub: AnimeSubscription) => {
|
||||
setFormData({
|
||||
title: sub.title,
|
||||
filterText: sub.filterText,
|
||||
source: sub.source,
|
||||
lastEpisode: sub.lastEpisode,
|
||||
enabled: sub.enabled,
|
||||
});
|
||||
setEditingSubscription(sub);
|
||||
setShowAddForm(false);
|
||||
};
|
||||
|
||||
// 保存订阅
|
||||
const handleSave = async () => {
|
||||
if (!formData.title.trim() || !formData.filterText.trim()) {
|
||||
showAlert({
|
||||
type: 'warning',
|
||||
title: '请填写必填字段',
|
||||
message: '番剧名称和过滤关键词不能为空',
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
setLoading(true);
|
||||
|
||||
if (editingSubscription) {
|
||||
// 更新
|
||||
const response = await fetch(`/api/admin/anime-subscription/${editingSubscription.id}`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(formData),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error('更新订阅失败');
|
||||
}
|
||||
} else {
|
||||
// 创建
|
||||
const response = await fetch('/api/admin/anime-subscription', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(formData),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error('创建订阅失败');
|
||||
}
|
||||
}
|
||||
|
||||
resetForm();
|
||||
await refreshConfig();
|
||||
showAlert({
|
||||
type: 'success',
|
||||
title: editingSubscription ? '订阅已更新' : '订阅已创建',
|
||||
});
|
||||
} catch (error) {
|
||||
showAlert({
|
||||
type: 'error',
|
||||
title: '保存失败',
|
||||
message: error instanceof Error ? error.message : '保存失败',
|
||||
});
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
// 删除订阅
|
||||
const handleDelete = async (id: string, title: string) => {
|
||||
showAlert({
|
||||
type: 'warning',
|
||||
title: '确认删除',
|
||||
message: `确定要删除订阅"${title}"吗?`,
|
||||
confirmText: '删除',
|
||||
showConfirm: true,
|
||||
onConfirm: async () => {
|
||||
try {
|
||||
setLoading(true);
|
||||
const response = await fetch(`/api/admin/anime-subscription/${id}`, {
|
||||
method: 'DELETE',
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error('删除订阅失败');
|
||||
}
|
||||
|
||||
await refreshConfig();
|
||||
showAlert({
|
||||
type: 'success',
|
||||
title: '订阅已删除',
|
||||
});
|
||||
} catch (error) {
|
||||
showAlert({
|
||||
type: 'error',
|
||||
title: '删除失败',
|
||||
message: error instanceof Error ? error.message : '删除失败',
|
||||
});
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
// 手动检查更新
|
||||
const handleCheckSubscription = async (id: string) => {
|
||||
try {
|
||||
setCheckingId(id);
|
||||
const response = await fetch(`/api/admin/anime-subscription/${id}/check`, {
|
||||
method: 'POST',
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error('检查失败');
|
||||
}
|
||||
|
||||
const result = await response.json();
|
||||
showAlert({
|
||||
type: 'success',
|
||||
title: '检查完成',
|
||||
message: `发现 ${result.found} 个新集数,已下载 ${result.downloaded} 个`,
|
||||
});
|
||||
await refreshConfig();
|
||||
} catch (error) {
|
||||
showAlert({
|
||||
type: 'error',
|
||||
title: '检查失败',
|
||||
message: error instanceof Error ? error.message : '检查失败',
|
||||
});
|
||||
} finally {
|
||||
setCheckingId(null);
|
||||
}
|
||||
};
|
||||
|
||||
// 切换订阅启用状态
|
||||
const handleToggleSubscription = async (sub: AnimeSubscription) => {
|
||||
try {
|
||||
setLoading(true);
|
||||
const response = await fetch(`/api/admin/anime-subscription/${sub.id}`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ enabled: !sub.enabled }),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error('切换状态失败');
|
||||
}
|
||||
|
||||
await refreshConfig();
|
||||
} catch (error) {
|
||||
showAlert({
|
||||
type: 'error',
|
||||
title: '切换状态失败',
|
||||
message: error instanceof Error ? error.message : '切换状态失败',
|
||||
});
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const formatTime = (timestamp: number) => {
|
||||
if (!timestamp) return '从未';
|
||||
const now = Date.now();
|
||||
const diff = now - timestamp;
|
||||
const minutes = Math.floor(diff / 60000);
|
||||
if (minutes < 1) return '刚刚';
|
||||
if (minutes < 60) return `${minutes}分钟前`;
|
||||
const hours = Math.floor(minutes / 60);
|
||||
if (hours < 24) return `${hours}小时前`;
|
||||
const days = Math.floor(hours / 24);
|
||||
return `${days}天前`;
|
||||
};
|
||||
|
||||
return (
|
||||
<div className='space-y-6'>
|
||||
{/* 顶部控制 */}
|
||||
<div className='flex items-center justify-between'>
|
||||
<div className='flex items-center gap-3'>
|
||||
<span className='text-sm font-medium text-gray-700 dark:text-gray-300'>
|
||||
启用追番功能
|
||||
</span>
|
||||
<Switch checked={enabled} onChange={handleToggleEnabled} disabled={loading} />
|
||||
</div>
|
||||
<button
|
||||
onClick={handleAdd}
|
||||
disabled={loading || showAddForm}
|
||||
className='flex items-center gap-2 px-4 py-2 bg-green-600 hover:bg-green-700 text-white rounded-lg transition-colors disabled:opacity-50'
|
||||
>
|
||||
<Plus size={16} />
|
||||
添加订阅
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* 说明 */}
|
||||
<div className='bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-lg p-4'>
|
||||
<div className='flex gap-2'>
|
||||
<AlertCircle className='w-5 h-5 text-blue-600 dark:text-blue-400 flex-shrink-0 mt-0.5' />
|
||||
<div className='text-sm text-blue-800 dark:text-blue-200 space-y-1'>
|
||||
<p>• 定时任务会自动检查订阅更新</p>
|
||||
<p>• 下载路径:OpenList离线下载根目录/番剧名称/</p>
|
||||
<p>• 过滤关键词支持多个,用逗号分隔,只会下载包含这些关键字的资源,可以用来过滤字幕组或是字幕种类</p>
|
||||
<p>• 当前集数:已看到第几集,只下载更新的集数</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 添加/编辑表单 */}
|
||||
{(showAddForm || editingSubscription) && (
|
||||
<div className='bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg p-6'>
|
||||
<div className='flex items-center justify-between mb-4'>
|
||||
<h3 className='text-lg font-semibold text-gray-900 dark:text-gray-100'>
|
||||
{editingSubscription ? '编辑订阅' : '添加订阅'}
|
||||
</h3>
|
||||
<button
|
||||
onClick={resetForm}
|
||||
className='text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200'
|
||||
>
|
||||
<X size={20} />
|
||||
</button>
|
||||
</div>
|
||||
<div className='space-y-4'>
|
||||
<div className='grid grid-cols-1 md:grid-cols-2 gap-4'>
|
||||
<div>
|
||||
<label className='block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1'>
|
||||
番剧名称 *
|
||||
</label>
|
||||
<input
|
||||
type='text'
|
||||
value={formData.title}
|
||||
onChange={(e) => setFormData({ ...formData, title: e.target.value })}
|
||||
placeholder='葬送的芙莉莲'
|
||||
className='w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 focus:outline-none focus:ring-2 focus:ring-green-500'
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className='block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1'>
|
||||
过滤关键词 *
|
||||
</label>
|
||||
<input
|
||||
type='text'
|
||||
value={formData.filterText}
|
||||
onChange={(e) => setFormData({ ...formData, filterText: e.target.value })}
|
||||
placeholder='简体,喵萌奶茶屋'
|
||||
className='w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 focus:outline-none focus:ring-2 focus:ring-green-500'
|
||||
/>
|
||||
<p className='mt-1 text-xs text-gray-500 dark:text-gray-400'>
|
||||
多个关键词用逗号分隔
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className='grid grid-cols-1 md:grid-cols-2 gap-4'>
|
||||
<div>
|
||||
<label className='block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1'>
|
||||
搜索源
|
||||
</label>
|
||||
<select
|
||||
value={formData.source}
|
||||
onChange={(e) => setFormData({ ...formData, source: e.target.value as any })}
|
||||
className='w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 focus:outline-none focus:ring-2 focus:ring-green-500'
|
||||
>
|
||||
<option value='mikan'>蜜柑 (Mikan)</option>
|
||||
<option value='acgrip'>ACG.RIP</option>
|
||||
<option value='dmhy'>动漫花园 (DMHY)</option>
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className='block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1'>
|
||||
当前集数
|
||||
</label>
|
||||
<input
|
||||
type='number'
|
||||
min='0'
|
||||
value={formData.lastEpisode}
|
||||
onChange={(e) => setFormData({ ...formData, lastEpisode: parseInt(e.target.value) || 0 })}
|
||||
className='w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 focus:outline-none focus:ring-2 focus:ring-green-500'
|
||||
/>
|
||||
<p className='mt-1 text-xs text-gray-500 dark:text-gray-400'>
|
||||
已看到第几集
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className='flex items-center gap-3'>
|
||||
<span className='text-sm font-medium text-gray-700 dark:text-gray-300'>
|
||||
启用此订阅
|
||||
</span>
|
||||
<Switch
|
||||
checked={formData.enabled}
|
||||
onChange={(checked) => setFormData({ ...formData, enabled: checked })}
|
||||
/>
|
||||
</div>
|
||||
<div className='flex gap-2 justify-end pt-2'>
|
||||
<button
|
||||
onClick={resetForm}
|
||||
disabled={loading}
|
||||
className='px-4 py-2 rounded-lg bg-gray-200 text-gray-700 hover:bg-gray-300 dark:bg-gray-700 dark:text-gray-300 dark:hover:bg-gray-600 transition-colors disabled:opacity-50'
|
||||
>
|
||||
取消
|
||||
</button>
|
||||
<button
|
||||
onClick={handleSave}
|
||||
disabled={loading}
|
||||
className='px-4 py-2 rounded-lg bg-green-600 text-white hover:bg-green-700 transition-colors disabled:opacity-50 flex items-center gap-2'
|
||||
>
|
||||
{loading && <Loader2 size={16} className='animate-spin' />}
|
||||
{editingSubscription ? '更新' : '添加'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 订阅列表 */}
|
||||
{subscriptions.length === 0 ? (
|
||||
<div className='text-center py-12 text-gray-500 dark:text-gray-400'>
|
||||
暂无订阅,点击"添加订阅"开始追番
|
||||
</div>
|
||||
) : (
|
||||
<div className='space-y-3'>
|
||||
{subscriptions.map((sub) => (
|
||||
<div
|
||||
key={sub.id}
|
||||
className='bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg p-4'
|
||||
>
|
||||
{/* 桌面端布局 */}
|
||||
<div className='hidden md:flex items-start justify-between gap-4'>
|
||||
<div className='flex-1 space-y-2'>
|
||||
<div className='flex items-center gap-3'>
|
||||
<h3 className='text-lg font-medium text-gray-900 dark:text-gray-100'>
|
||||
{sub.title}
|
||||
</h3>
|
||||
<span className='px-2 py-0.5 text-xs rounded-full bg-blue-100 text-blue-800 dark:bg-blue-900/40 dark:text-blue-200'>
|
||||
{sub.source === 'acgrip' ? 'ACG.RIP' : sub.source === 'mikan' ? '蜜柑' : '动漫花园'}
|
||||
</span>
|
||||
</div>
|
||||
<div className='text-sm text-gray-600 dark:text-gray-400 space-y-1'>
|
||||
<p>过滤条件:{sub.filterText}</p>
|
||||
<p>当前集数:第 {sub.lastEpisode} 集</p>
|
||||
<p>上次检查:{formatTime(sub.lastCheckTime)}</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className='flex items-center gap-2'>
|
||||
<Switch
|
||||
checked={sub.enabled}
|
||||
onChange={() => handleToggleSubscription(sub)}
|
||||
disabled={loading}
|
||||
/>
|
||||
<button
|
||||
onClick={() => handleCheckSubscription(sub.id)}
|
||||
disabled={checkingId === sub.id}
|
||||
className='p-2 text-blue-600 hover:bg-blue-50 dark:text-blue-400 dark:hover:bg-blue-900/20 rounded-lg transition-colors disabled:opacity-50'
|
||||
title='立即检查'
|
||||
>
|
||||
{checkingId === sub.id ? (
|
||||
<Loader2 size={18} className='animate-spin' />
|
||||
) : (
|
||||
<RefreshCw size={18} />
|
||||
)}
|
||||
</button>
|
||||
<button
|
||||
onClick={() => handleEdit(sub)}
|
||||
disabled={loading}
|
||||
className='p-2 text-green-600 hover:bg-green-50 dark:text-green-400 dark:hover:bg-green-900/20 rounded-lg transition-colors disabled:opacity-50'
|
||||
title='编辑'
|
||||
>
|
||||
<svg className='w-[18px] h-[18px]' fill='none' stroke='currentColor' viewBox='0 0 24 24'>
|
||||
<path strokeLinecap='round' strokeLinejoin='round' strokeWidth={2} d='M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z' />
|
||||
</svg>
|
||||
</button>
|
||||
<button
|
||||
onClick={() => handleDelete(sub.id, sub.title)}
|
||||
disabled={loading}
|
||||
className='p-2 text-red-600 hover:bg-red-50 dark:text-red-400 dark:hover:bg-red-900/20 rounded-lg transition-colors disabled:opacity-50'
|
||||
title='删除'
|
||||
>
|
||||
<Trash2 size={18} />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 移动端布局 */}
|
||||
<div className='md:hidden space-y-3'>
|
||||
<div className='flex items-start justify-between gap-2'>
|
||||
<div className='flex-1 min-w-0'>
|
||||
<h3 className='text-base font-medium text-gray-900 dark:text-gray-100 truncate'>
|
||||
{sub.title}
|
||||
</h3>
|
||||
<span className='inline-block mt-1 px-2 py-0.5 text-xs rounded-full bg-blue-100 text-blue-800 dark:bg-blue-900/40 dark:text-blue-200'>
|
||||
{sub.source === 'acgrip' ? 'ACG.RIP' : sub.source === 'mikan' ? '蜜柑' : '动漫花园'}
|
||||
</span>
|
||||
</div>
|
||||
<Switch
|
||||
checked={sub.enabled}
|
||||
onChange={() => handleToggleSubscription(sub)}
|
||||
disabled={loading}
|
||||
/>
|
||||
</div>
|
||||
<div className='text-sm text-gray-600 dark:text-gray-400 space-y-1'>
|
||||
<p className='break-all'>过滤:{sub.filterText}</p>
|
||||
<p>集数:第 {sub.lastEpisode} 集 · {formatTime(sub.lastCheckTime)}</p>
|
||||
</div>
|
||||
<div className='flex items-center gap-2 pt-1'>
|
||||
<button
|
||||
onClick={() => handleCheckSubscription(sub.id)}
|
||||
disabled={checkingId === sub.id}
|
||||
className='flex-1 flex items-center justify-center gap-1.5 px-3 py-2 text-sm text-blue-600 bg-blue-50 hover:bg-blue-100 dark:text-blue-400 dark:bg-blue-900/20 dark:hover:bg-blue-900/30 rounded-lg transition-colors disabled:opacity-50'
|
||||
>
|
||||
{checkingId === sub.id ? (
|
||||
<>
|
||||
<Loader2 size={16} className='animate-spin' />
|
||||
<span>检查中</span>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<RefreshCw size={16} />
|
||||
<span>检查</span>
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
<button
|
||||
onClick={() => handleEdit(sub)}
|
||||
disabled={loading}
|
||||
className='flex-1 flex items-center justify-center gap-1.5 px-3 py-2 text-sm text-green-600 bg-green-50 hover:bg-green-100 dark:text-green-400 dark:bg-green-900/20 dark:hover:bg-green-900/30 rounded-lg transition-colors disabled:opacity-50'
|
||||
>
|
||||
<svg className='w-4 h-4' fill='none' stroke='currentColor' viewBox='0 0 24 24'>
|
||||
<path strokeLinecap='round' strokeLinejoin='round' strokeWidth={2} d='M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z' />
|
||||
</svg>
|
||||
<span>编辑</span>
|
||||
</button>
|
||||
<button
|
||||
onClick={() => handleDelete(sub.id, sub.title)}
|
||||
disabled={loading}
|
||||
className='flex-1 flex items-center justify-center gap-1.5 px-3 py-2 text-sm text-red-600 bg-red-50 hover:bg-red-100 dark:text-red-400 dark:bg-red-900/20 dark:hover:bg-red-900/30 rounded-lg transition-colors disabled:opacity-50'
|
||||
>
|
||||
<Trash2 size={16} />
|
||||
<span>删除</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* AlertModal */}
|
||||
<AlertModal
|
||||
isOpen={alertModal.isOpen}
|
||||
onClose={hideAlert}
|
||||
type={alertModal.type}
|
||||
title={alertModal.title}
|
||||
message={alertModal.message}
|
||||
confirmText={alertModal.confirmText}
|
||||
onConfirm={alertModal.onConfirm}
|
||||
showConfirm={alertModal.showConfirm}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -249,6 +249,21 @@ export interface AdminConfig {
|
||||
OpenListCachePath?: string; // OpenList缓存目录路径
|
||||
OpenListCacheProxyEnabled?: boolean; // 启用缓存代理返回(默认开启)
|
||||
};
|
||||
AnimeSubscriptionConfig?: {
|
||||
Enabled: boolean; // 是否启用追番功能
|
||||
Subscriptions: Array<{
|
||||
id: string;
|
||||
title: string;
|
||||
filterText: string;
|
||||
source: 'acgrip' | 'mikan' | 'dmhy';
|
||||
enabled: boolean;
|
||||
lastCheckTime: number;
|
||||
lastEpisode: number;
|
||||
createdAt: number;
|
||||
updatedAt: number;
|
||||
createdBy: string;
|
||||
}>;
|
||||
};
|
||||
}
|
||||
|
||||
export interface AdminConfigResult {
|
||||
|
||||
397
src/lib/anime-subscription.ts
Normal file
397
src/lib/anime-subscription.ts
Normal file
@@ -0,0 +1,397 @@
|
||||
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||
import parseTorrentName from 'parse-torrent-name';
|
||||
import { parseStringPromise } from 'xml2js';
|
||||
|
||||
import { getConfig, setCachedConfig } from '@/lib/config';
|
||||
import { db, getStorage } from '@/lib/db';
|
||||
import { EmailService } from '@/lib/email.service';
|
||||
import { OpenListClient } from '@/lib/openlist.client';
|
||||
import { AnimeSubscription } from '@/types/anime-subscription';
|
||||
|
||||
/**
|
||||
* 从标题中提取集数
|
||||
*/
|
||||
export function extractEpisode(title: string): number | null {
|
||||
const parsed = parseTorrentName(title);
|
||||
|
||||
if (parsed.episode) {
|
||||
return parsed.episode;
|
||||
}
|
||||
|
||||
// 备用正则匹配
|
||||
const patterns = [
|
||||
/\[(\d+)\]/, // [01]
|
||||
/第(\d+)[集话]/, // 第01集
|
||||
/EP?(\d+)/i, // EP01, E01
|
||||
/\s(\d+)\s/, // 空格01空格
|
||||
];
|
||||
|
||||
for (const pattern of patterns) {
|
||||
const match = title.match(pattern);
|
||||
if (match) {
|
||||
return parseInt(match[1], 10);
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查标题是否匹配过滤条件
|
||||
*/
|
||||
export function matchesFilter(title: string, filterText: string): boolean {
|
||||
if (!filterText) return true;
|
||||
|
||||
// 支持多个关键词,用逗号分隔,必须全部匹配
|
||||
const keywords = filterText.split(',').map((k) => k.trim()).filter(Boolean);
|
||||
|
||||
return keywords.every((keyword) => title.includes(keyword));
|
||||
}
|
||||
|
||||
/**
|
||||
* 搜索 ACG 资源(直接调用搜索逻辑,不通过 HTTP)
|
||||
*/
|
||||
export async function searchACG(
|
||||
keyword: string,
|
||||
source: 'acgrip' | 'mikan' | 'dmhy'
|
||||
) {
|
||||
const trimmedKeyword = keyword.trim();
|
||||
|
||||
let searchUrl: string;
|
||||
|
||||
switch (source) {
|
||||
case 'mikan':
|
||||
searchUrl = `https://mikanani.me/RSS/Search?searchstr=${encodeURIComponent(trimmedKeyword)}`;
|
||||
break;
|
||||
case 'dmhy':
|
||||
searchUrl = `http://share.dmhy.org/topics/rss/rss.xml?keyword=${encodeURIComponent(trimmedKeyword)}`;
|
||||
break;
|
||||
case 'acgrip':
|
||||
default:
|
||||
searchUrl = `https://acg.rip/page/1.xml?term=${encodeURIComponent(trimmedKeyword)}`;
|
||||
break;
|
||||
}
|
||||
|
||||
const response = await fetch(searchUrl, {
|
||||
headers: {
|
||||
'User-Agent':
|
||||
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
|
||||
},
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`${source} API 请求失败: ${response.status}`);
|
||||
}
|
||||
|
||||
const xmlData = await response.text();
|
||||
const parsed = await parseStringPromise(xmlData);
|
||||
|
||||
if (!parsed?.rss?.channel?.[0]?.item) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const items = parsed.rss.channel[0].item;
|
||||
|
||||
// 统一格式
|
||||
return items.map((item: any) => {
|
||||
const title = item.title?.[0] || '';
|
||||
const link = item.link?.[0] || '';
|
||||
const guid = item.guid?.[0] || link || `${title}-${item.pubDate?.[0] || ''}`;
|
||||
const pubDate = item.pubDate?.[0] || '';
|
||||
const torrentUrl = item.enclosure?.[0]?.$?.url || '';
|
||||
const description = item.description?.[0] || '';
|
||||
|
||||
return {
|
||||
title,
|
||||
link,
|
||||
guid,
|
||||
pubDate,
|
||||
torrentUrl,
|
||||
description,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 添加离线下载任务
|
||||
*/
|
||||
export async function addOfflineDownload(
|
||||
torrentUrl: string,
|
||||
downloadPath: string
|
||||
) {
|
||||
const config = await getConfig();
|
||||
const openlistConfig = config.OpenListConfig;
|
||||
|
||||
if (!openlistConfig?.Enabled) {
|
||||
throw new Error('私人影库功能未启用');
|
||||
}
|
||||
|
||||
if (
|
||||
!openlistConfig.URL ||
|
||||
!openlistConfig.Username ||
|
||||
!openlistConfig.Password
|
||||
) {
|
||||
throw new Error('OpenList 配置不完整');
|
||||
}
|
||||
|
||||
const client = new OpenListClient(
|
||||
openlistConfig.URL,
|
||||
openlistConfig.Username,
|
||||
openlistConfig.Password
|
||||
);
|
||||
|
||||
const token = await (client as any).getToken();
|
||||
const openlistUrl = `${openlistConfig.URL.replace(/\/$/, '')}/api/fs/add_offline_download`;
|
||||
|
||||
const response = await fetch(openlistUrl, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: token,
|
||||
},
|
||||
body: JSON.stringify({
|
||||
path: downloadPath,
|
||||
urls: [torrentUrl],
|
||||
tool: 'aria2',
|
||||
}),
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
if (!response.ok || data.code !== 200) {
|
||||
throw new Error(data.message || '添加离线下载任务失败');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送追番更新通知和邮件
|
||||
*/
|
||||
async function sendAnimeUpdateNotifications(
|
||||
subscription: AnimeSubscription,
|
||||
episodes: number[]
|
||||
) {
|
||||
const config = await getConfig();
|
||||
const storage = getStorage();
|
||||
|
||||
// 获取站长用户名 - 从用户列表中查找 owner 角色
|
||||
let ownerUsername: string | null = null;
|
||||
try {
|
||||
const allUsers = await db.getAllUsers();
|
||||
for (const username of allUsers) {
|
||||
const userInfo = await db.getUserInfoV2(username);
|
||||
if (userInfo?.role === 'owner') {
|
||||
ownerUsername = username;
|
||||
break;
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('[AnimeSubscription] 获取站长用户名失败:', error);
|
||||
}
|
||||
|
||||
if (!ownerUsername) {
|
||||
console.warn('[AnimeSubscription] 未找到站长用户,跳过通知');
|
||||
return;
|
||||
}
|
||||
|
||||
// 准备通知内容
|
||||
const episodeList = episodes.join('、');
|
||||
const notificationTitle = `追番更新:${subscription.title}`;
|
||||
const notificationMessage = `您订阅的番剧《${subscription.title}》有新集数更新:第 ${episodeList} 集,已下载到私人影库`;
|
||||
|
||||
// 需要通知的用户列表(去重)
|
||||
const usersToNotify: string[] = [ownerUsername];
|
||||
|
||||
// 如果创建者不是站长,也通知创建者
|
||||
if (subscription.createdBy && subscription.createdBy !== ownerUsername) {
|
||||
usersToNotify.push(subscription.createdBy);
|
||||
}
|
||||
|
||||
// 发送站内通知
|
||||
for (const username of usersToNotify) {
|
||||
try {
|
||||
await storage.addNotification(username, {
|
||||
id: crypto.randomUUID(),
|
||||
type: 'anime_subscription_update',
|
||||
title: notificationTitle,
|
||||
message: notificationMessage,
|
||||
timestamp: Date.now(),
|
||||
read: false,
|
||||
metadata: {
|
||||
subscriptionId: subscription.id,
|
||||
subscriptionTitle: subscription.title,
|
||||
episodes: episodes,
|
||||
},
|
||||
});
|
||||
console.log(`[AnimeSubscription] 已发送站内通知给用户: ${username}`);
|
||||
} catch (error) {
|
||||
console.error(`[AnimeSubscription] 发送站内通知失败 (${username}):`, error);
|
||||
}
|
||||
}
|
||||
|
||||
// 发送邮件通知(如果已启用)
|
||||
const emailConfig = config.EmailConfig;
|
||||
if (!emailConfig?.enabled) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 获取需要发送邮件的用户邮箱
|
||||
const emailsToSend: Array<{ username: string; email: string }> = [];
|
||||
|
||||
for (const username of usersToNotify) {
|
||||
try {
|
||||
const userInfo = await db.getUserInfoV2(username);
|
||||
// 使用可选的 email 字段
|
||||
const email = (userInfo as any)?.email;
|
||||
if (email) {
|
||||
emailsToSend.push({ username, email });
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(`[AnimeSubscription] 获取用户邮箱失败 (${username}):`, error);
|
||||
}
|
||||
}
|
||||
|
||||
// 发送邮件
|
||||
for (const { username, email } of emailsToSend) {
|
||||
try {
|
||||
const emailHtml = `
|
||||
<div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;">
|
||||
<h2 style="color: #333;">追番更新通知</h2>
|
||||
<p>您好,${username}!</p>
|
||||
<p>您订阅的番剧有新集数更新:</p>
|
||||
<div style="background-color: #f5f5f5; padding: 15px; border-radius: 5px; margin: 20px 0;">
|
||||
<h3 style="margin-top: 0; color: #2563eb;">${subscription.title}</h3>
|
||||
<p style="margin: 10px 0;">新增集数:第 ${episodeList} 集</p>
|
||||
<p style="margin: 10px 0; color: #666;">搜索源:${subscription.source === 'acgrip' ? 'ACG.RIP' : subscription.source === 'mikan' ? '蜜柑' : '动漫花园'}</p>
|
||||
</div>
|
||||
<p style="color: #666; font-size: 14px;">这些集数已自动添加到 OpenList 离线下载队列。</p>
|
||||
<hr style="border: none; border-top: 1px solid #eee; margin: 20px 0;">
|
||||
<p style="color: #999; font-size: 12px;">此邮件由系统自动发送,请勿回复。</p>
|
||||
</div>
|
||||
`;
|
||||
|
||||
if (emailConfig.provider === 'smtp' && emailConfig.smtp) {
|
||||
await EmailService.sendViaSMTP(emailConfig.smtp, {
|
||||
to: email,
|
||||
subject: notificationTitle,
|
||||
html: emailHtml,
|
||||
});
|
||||
} else if (emailConfig.provider === 'resend' && emailConfig.resend) {
|
||||
await EmailService.sendViaResend(emailConfig.resend, {
|
||||
to: email,
|
||||
subject: notificationTitle,
|
||||
html: emailHtml,
|
||||
});
|
||||
}
|
||||
|
||||
console.log(`[AnimeSubscription] 已发送邮件通知给: ${email}`);
|
||||
} catch (error) {
|
||||
console.error(`[AnimeSubscription] 发送邮件失败 (${email}):`, error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查单个订阅的更新
|
||||
*/
|
||||
export async function checkSubscription(subscription: AnimeSubscription) {
|
||||
const config = await getConfig();
|
||||
const openlistConfig = config.OpenListConfig;
|
||||
|
||||
if (!openlistConfig?.OfflineDownloadPath) {
|
||||
throw new Error('OpenList 离线下载路径未配置');
|
||||
}
|
||||
|
||||
// 1. 搜索资源
|
||||
const results = await searchACG(subscription.title, subscription.source);
|
||||
|
||||
// 2. 过滤并解析集数
|
||||
const newEpisodes = results
|
||||
.filter((item: any) => matchesFilter(item.title, subscription.filterText))
|
||||
.map((item: any) => ({
|
||||
episode: extractEpisode(item.title),
|
||||
...item,
|
||||
}))
|
||||
.filter((item: any) => item.episode && item.episode > subscription.lastEpisode)
|
||||
.sort((a: any, b: any) => a.episode! - b.episode!);
|
||||
|
||||
// 3. 下载新集数
|
||||
const downloaded = [];
|
||||
for (const item of newEpisodes) {
|
||||
try {
|
||||
const downloadPath = `${openlistConfig.OfflineDownloadPath.replace(/\/$/, '')}/${subscription.title}`;
|
||||
await addOfflineDownload(item.torrentUrl, downloadPath);
|
||||
|
||||
// 成功后更新 lastEpisode
|
||||
subscription.lastEpisode = item.episode!;
|
||||
downloaded.push(item.episode);
|
||||
|
||||
console.log(
|
||||
`[AnimeSubscription] ${subscription.title}: 已添加第${item.episode}集到下载队列`
|
||||
);
|
||||
} catch (error) {
|
||||
// 失败则停止,下次继续尝试这一集
|
||||
console.error(
|
||||
`[AnimeSubscription] ${subscription.title}: 下载第${item.episode}集失败`,
|
||||
error
|
||||
);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// 4. 更新检查时间
|
||||
subscription.lastCheckTime = Date.now();
|
||||
|
||||
// 5. 发送通知和邮件(如果有下载成功的集数)
|
||||
if (downloaded.length > 0) {
|
||||
try {
|
||||
await sendAnimeUpdateNotifications(subscription, downloaded);
|
||||
} catch (error) {
|
||||
console.error(`[AnimeSubscription] ${subscription.title}: 发送通知失败`, error);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
found: newEpisodes.length,
|
||||
downloaded: downloaded.length,
|
||||
episodes: downloaded,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查所有订阅(定时任务调用)
|
||||
*/
|
||||
export async function checkAnimeSubscriptions() {
|
||||
const config = await getConfig();
|
||||
const animeConfig = config.AnimeSubscriptionConfig;
|
||||
|
||||
if (!animeConfig?.Enabled) {
|
||||
return;
|
||||
}
|
||||
|
||||
const subscriptions = animeConfig.Subscriptions || [];
|
||||
const now = Date.now();
|
||||
const MIN_CHECK_INTERVAL = 30 * 60 * 1000; // 30分钟
|
||||
let configChanged = false;
|
||||
|
||||
for (const sub of subscriptions) {
|
||||
if (!sub.enabled) continue;
|
||||
|
||||
// 检查是否距离上次检查超过30分钟
|
||||
if (now - sub.lastCheckTime < MIN_CHECK_INTERVAL) {
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
await checkSubscription(sub);
|
||||
configChanged = true;
|
||||
} catch (error) {
|
||||
console.error(`[AnimeSubscription] ${sub.title}: 检查失败`, error);
|
||||
}
|
||||
}
|
||||
|
||||
// 5. 保存配置并刷新缓存
|
||||
if (configChanged) {
|
||||
await db.saveAdminConfig(config);
|
||||
await setCachedConfig(config);
|
||||
}
|
||||
}
|
||||
@@ -240,7 +240,8 @@ export type NotificationType =
|
||||
| 'system' // 系统通知
|
||||
| 'announcement' // 公告
|
||||
| 'movie_request' // 新求片通知(给管理员)
|
||||
| 'request_fulfilled'; // 求片已上架通知(给求片用户)
|
||||
| 'request_fulfilled' // 求片已上架通知(给求片用户)
|
||||
| 'anime_subscription_update'; // 追番订阅更新
|
||||
|
||||
// 通知数据结构
|
||||
export interface Notification {
|
||||
|
||||
17
src/types/anime-subscription.ts
Normal file
17
src/types/anime-subscription.ts
Normal file
@@ -0,0 +1,17 @@
|
||||
export interface AnimeSubscription {
|
||||
id: string;
|
||||
title: string;
|
||||
filterText: string;
|
||||
source: 'acgrip' | 'mikan' | 'dmhy';
|
||||
enabled: boolean;
|
||||
lastCheckTime: number;
|
||||
lastEpisode: number;
|
||||
createdAt: number;
|
||||
updatedAt: number;
|
||||
createdBy: string;
|
||||
}
|
||||
|
||||
export interface AnimeSubscriptionConfig {
|
||||
Enabled: boolean;
|
||||
Subscriptions: AnimeSubscription[];
|
||||
}
|
||||
Reference in New Issue
Block a user