增加收藏更新邮件发送
This commit is contained in:
190
src/app/api/admin/email/route.ts
Normal file
190
src/app/api/admin/email/route.ts
Normal file
@@ -0,0 +1,190 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
|
||||
import { getAuthInfoFromCookie } from '@/lib/auth';
|
||||
import { getStorage } from '@/lib/db';
|
||||
import { getConfig } from '@/lib/config';
|
||||
import { EmailService } from '@/lib/email.service';
|
||||
import type { AdminConfig } from '@/lib/admin.types';
|
||||
|
||||
export const runtime = 'nodejs';
|
||||
|
||||
/**
|
||||
* GET - 获取邮件配置
|
||||
*/
|
||||
export async function GET(request: NextRequest) {
|
||||
const authInfo = getAuthInfoFromCookie(request);
|
||||
if (!authInfo || !authInfo.username) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
||||
}
|
||||
|
||||
try {
|
||||
const storage = getStorage();
|
||||
const userInfo = await storage.getUserInfoV2?.(authInfo.username);
|
||||
|
||||
// 只有管理员和站长可以访问
|
||||
if (!userInfo || (userInfo.role !== 'admin' && userInfo.role !== 'owner')) {
|
||||
return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
|
||||
}
|
||||
|
||||
const adminConfig = await getConfig();
|
||||
const emailConfig = adminConfig?.EmailConfig || {
|
||||
enabled: false,
|
||||
provider: 'smtp' as const,
|
||||
};
|
||||
|
||||
// 不返回敏感信息(密码、API Key)
|
||||
const safeConfig = {
|
||||
enabled: emailConfig.enabled,
|
||||
provider: emailConfig.provider,
|
||||
smtp: emailConfig.smtp
|
||||
? {
|
||||
host: emailConfig.smtp.host,
|
||||
port: emailConfig.smtp.port,
|
||||
secure: emailConfig.smtp.secure,
|
||||
user: emailConfig.smtp.user,
|
||||
from: emailConfig.smtp.from,
|
||||
password: emailConfig.smtp.password ? '******' : '',
|
||||
}
|
||||
: undefined,
|
||||
resend: emailConfig.resend
|
||||
? {
|
||||
from: emailConfig.resend.from,
|
||||
apiKey: emailConfig.resend.apiKey ? '******' : '',
|
||||
}
|
||||
: undefined,
|
||||
};
|
||||
|
||||
return NextResponse.json(safeConfig);
|
||||
} catch (error) {
|
||||
console.error('获取邮件配置失败:', error);
|
||||
return NextResponse.json(
|
||||
{ error: (error as Error).message },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* POST - 保存邮件配置或发送测试邮件
|
||||
*/
|
||||
export async function POST(request: NextRequest) {
|
||||
const authInfo = getAuthInfoFromCookie(request);
|
||||
if (!authInfo || !authInfo.username) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
||||
}
|
||||
|
||||
try {
|
||||
const storage = getStorage();
|
||||
const userInfo = await storage.getUserInfoV2?.(authInfo.username);
|
||||
|
||||
// 只有管理员和站长可以访问
|
||||
if (!userInfo || (userInfo.role !== 'admin' && userInfo.role !== 'owner')) {
|
||||
return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
|
||||
}
|
||||
|
||||
const body = await request.json();
|
||||
const { action, config, testEmail } = body;
|
||||
|
||||
// 发送测试邮件
|
||||
if (action === 'test') {
|
||||
if (!testEmail) {
|
||||
return NextResponse.json(
|
||||
{ error: '请提供测试邮箱地址' },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const emailConfig = config as AdminConfig['EmailConfig'];
|
||||
if (!emailConfig || !emailConfig.enabled) {
|
||||
return NextResponse.json(
|
||||
{ error: '邮件配置未启用' },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
const adminConfig = await getConfig();
|
||||
const siteName = adminConfig?.SiteConfig?.SiteName || 'MoonTVPlus';
|
||||
await EmailService.sendTestEmail(emailConfig, testEmail, siteName);
|
||||
return NextResponse.json({ success: true, message: '测试邮件发送成功' });
|
||||
} catch (error) {
|
||||
console.error('发送测试邮件失败:', error);
|
||||
return NextResponse.json(
|
||||
{ error: `发送失败: ${(error as Error).message}` },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// 保存邮件配置
|
||||
if (action === 'save') {
|
||||
const emailConfig = config as AdminConfig['EmailConfig'];
|
||||
if (!emailConfig) {
|
||||
return NextResponse.json(
|
||||
{ error: '邮件配置不能为空' },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
// 验证配置
|
||||
if (emailConfig.enabled) {
|
||||
if (emailConfig.provider === 'smtp') {
|
||||
if (!emailConfig.smtp?.host || !emailConfig.smtp?.port || !emailConfig.smtp?.user || !emailConfig.smtp?.from) {
|
||||
return NextResponse.json(
|
||||
{ error: 'SMTP配置不完整' },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
} else if (emailConfig.provider === 'resend') {
|
||||
if (!emailConfig.resend?.apiKey || !emailConfig.resend?.from) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Resend配置不完整' },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 获取现有配置
|
||||
const adminConfig = await getConfig();
|
||||
if (!adminConfig) {
|
||||
return NextResponse.json(
|
||||
{ error: '管理员配置不存在' },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
|
||||
// 如果密码或API Key是占位符,保留原有值
|
||||
if (emailConfig.smtp?.password === '******') {
|
||||
const oldConfig = adminConfig.EmailConfig;
|
||||
if (oldConfig?.smtp?.password) {
|
||||
emailConfig.smtp.password = oldConfig.smtp.password;
|
||||
}
|
||||
}
|
||||
|
||||
if (emailConfig.resend?.apiKey === '******') {
|
||||
const oldConfig = adminConfig.EmailConfig;
|
||||
if (oldConfig?.resend?.apiKey) {
|
||||
emailConfig.resend.apiKey = oldConfig.resend.apiKey;
|
||||
}
|
||||
}
|
||||
|
||||
// 更新配置
|
||||
adminConfig.EmailConfig = emailConfig;
|
||||
await storage.setAdminConfig(adminConfig);
|
||||
|
||||
return NextResponse.json({ success: true, message: '邮件配置保存成功' });
|
||||
}
|
||||
|
||||
return NextResponse.json(
|
||||
{ error: '无效的操作' },
|
||||
{ status: 400 }
|
||||
);
|
||||
} catch (error) {
|
||||
console.error('处理邮件配置失败:', error);
|
||||
return NextResponse.json(
|
||||
{ error: (error as Error).message },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,8 @@ import { fetchVideoDetail } from '@/lib/fetchVideoDetail';
|
||||
import { refreshLiveChannels } from '@/lib/live';
|
||||
import { startOpenListRefresh } from '@/lib/openlist-refresh';
|
||||
import { SearchResult } from '@/lib/types';
|
||||
import { EmailService } from '@/lib/email.service';
|
||||
import { getBatchFavoriteUpdateEmailTemplate, FavoriteUpdate } from '@/lib/email.templates';
|
||||
|
||||
export const runtime = 'nodejs';
|
||||
|
||||
@@ -230,6 +232,7 @@ async function refreshRecordAndFavorites() {
|
||||
const totalFavorites = Object.keys(favorites).length;
|
||||
let processedFavorites = 0;
|
||||
const now = Date.now();
|
||||
const userUpdates: FavoriteUpdate[] = []; // 收集该用户的所有更新
|
||||
|
||||
for (const [key, fav] of Object.entries(favorites)) {
|
||||
try {
|
||||
@@ -279,6 +282,17 @@ async function refreshRecordAndFavorites() {
|
||||
|
||||
await storage.addNotification(user, notification);
|
||||
console.log(`已为用户 ${user} 创建收藏更新通知: ${fav.title}`);
|
||||
|
||||
// 收集更新信息用于邮件
|
||||
const siteUrl = process.env.NEXT_PUBLIC_SITE_URL || 'http://localhost:3000';
|
||||
const playUrl = `${siteUrl}/play?source=${source}&id=${id}`;
|
||||
userUpdates.push({
|
||||
title: fav.title,
|
||||
oldEpisodes: fav.total_episodes,
|
||||
newEpisodes: favEpisodeCount,
|
||||
url: playUrl,
|
||||
cover: favDetail.poster || fav.cover,
|
||||
});
|
||||
}
|
||||
|
||||
processedFavorites++;
|
||||
@@ -289,6 +303,42 @@ async function refreshRecordAndFavorites() {
|
||||
}
|
||||
|
||||
console.log(`收藏处理完成: ${processedFavorites}/${totalFavorites}`);
|
||||
|
||||
// 如果有更新,发送汇总邮件
|
||||
if (userUpdates.length > 0) {
|
||||
try {
|
||||
const userEmail = storage.getUserEmail ? await storage.getUserEmail(user) : null;
|
||||
const emailNotifications = storage.getEmailNotificationPreference
|
||||
? await storage.getEmailNotificationPreference(user)
|
||||
: false;
|
||||
|
||||
if (userEmail && emailNotifications) {
|
||||
const config = await getConfig();
|
||||
const emailConfig = config?.EmailConfig;
|
||||
|
||||
if (emailConfig?.enabled) {
|
||||
const siteUrl = process.env.NEXT_PUBLIC_SITE_URL || 'http://localhost:3000';
|
||||
const siteName = config?.SiteConfig?.SiteName || 'MoonTVPlus';
|
||||
|
||||
await EmailService.send(emailConfig, {
|
||||
to: userEmail,
|
||||
subject: `📺 收藏更新汇总 - ${userUpdates.length} 部影片有更新`,
|
||||
html: getBatchFavoriteUpdateEmailTemplate(
|
||||
user,
|
||||
userUpdates,
|
||||
siteUrl,
|
||||
siteName
|
||||
),
|
||||
});
|
||||
|
||||
console.log(`邮件汇总已发送至: ${userEmail} (${userUpdates.length} 个更新)`);
|
||||
}
|
||||
}
|
||||
} catch (emailError) {
|
||||
console.error(`发送邮件汇总失败 (${user}):`, emailError);
|
||||
// 邮件发送失败不影响主流程
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(`获取用户收藏失败 (${user}):`, err);
|
||||
}
|
||||
|
||||
@@ -1,159 +0,0 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
|
||||
import { getAuthInfoFromCookie } from '@/lib/auth';
|
||||
import { getStorage } from '@/lib/db';
|
||||
import { getAvailableApiSites } from '@/lib/config';
|
||||
import { getDetailFromApi } from '@/lib/downstream';
|
||||
import { Notification } from '@/lib/types';
|
||||
|
||||
export const runtime = 'nodejs';
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
const authInfo = getAuthInfoFromCookie(request);
|
||||
if (!authInfo || !authInfo.username) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
||||
}
|
||||
|
||||
try {
|
||||
const storage = getStorage();
|
||||
const username = authInfo.username;
|
||||
const now = Date.now();
|
||||
|
||||
console.log(`用户 ${username} 请求检查收藏更新`);
|
||||
console.log(`当前时间: ${new Date(now).toLocaleString('zh-CN')}`);
|
||||
console.log(`开始检查收藏更新...`);
|
||||
|
||||
// 获取所有收藏
|
||||
const favorites = await storage.getAllFavorites(username);
|
||||
const favoriteKeys = Object.keys(favorites);
|
||||
|
||||
if (favoriteKeys.length === 0) {
|
||||
return NextResponse.json({
|
||||
message: '没有收藏',
|
||||
updates: [],
|
||||
});
|
||||
}
|
||||
|
||||
// 获取可用的 API 站点
|
||||
const apiSites = await getAvailableApiSites(username);
|
||||
|
||||
// 检查每个收藏的更新
|
||||
const updates: Array<{
|
||||
source: string;
|
||||
id: string;
|
||||
title: string;
|
||||
old_episodes: number;
|
||||
new_episodes: number;
|
||||
}> = [];
|
||||
|
||||
// 限制并发请求数量,避免过载
|
||||
const BATCH_SIZE = 5;
|
||||
for (let i = 0; i < favoriteKeys.length; i += BATCH_SIZE) {
|
||||
const batch = favoriteKeys.slice(i, i + BATCH_SIZE);
|
||||
|
||||
await Promise.all(
|
||||
batch.map(async (key) => {
|
||||
try {
|
||||
const favorite = favorites[key];
|
||||
|
||||
// 跳过 live 类型的收藏
|
||||
if (favorite.origin === 'live') {
|
||||
return;
|
||||
}
|
||||
|
||||
// 跳过已完结的收藏
|
||||
if (favorite.is_completed) {
|
||||
console.log(`跳过已完结的收藏: ${favorite.title}`);
|
||||
return;
|
||||
}
|
||||
|
||||
// 解析 source 和 id
|
||||
const [source, id] = key.split('+');
|
||||
if (!source || !id) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 查找对应的 API 站点
|
||||
const apiSite = apiSites.find((site) => site.key === source);
|
||||
if (!apiSite) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 获取最新详情
|
||||
const detail = await getDetailFromApi(apiSite, id);
|
||||
|
||||
// 比较集数
|
||||
const oldEpisodes = favorite.total_episodes;
|
||||
const newEpisodes = detail.episodes.length;
|
||||
|
||||
console.log(`检查收藏: ${favorite.title} (${source}+${id})`);
|
||||
console.log(` 旧集数: ${oldEpisodes}, 新集数: ${newEpisodes}`);
|
||||
console.log(` 是否完结: ${favorite.is_completed}, 备注: ${favorite.vod_remarks}`);
|
||||
|
||||
if (newEpisodes > oldEpisodes) {
|
||||
updates.push({
|
||||
source,
|
||||
id,
|
||||
title: favorite.title,
|
||||
old_episodes: oldEpisodes,
|
||||
new_episodes: newEpisodes,
|
||||
});
|
||||
|
||||
// 更新收藏的集数和完结状态
|
||||
await storage.setFavorite(username, key, {
|
||||
...favorite,
|
||||
total_episodes: newEpisodes,
|
||||
is_completed: detail.vod_remarks
|
||||
? ['全', '完结', '大结局', 'end', '完'].some((keyword) =>
|
||||
detail.vod_remarks!.toLowerCase().includes(keyword)
|
||||
)
|
||||
: false,
|
||||
vod_remarks: detail.vod_remarks,
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(`检查收藏更新失败 (${key}):`, error);
|
||||
// 继续处理其他收藏
|
||||
}
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
console.log(`检查完成,发现 ${updates.length} 个更新`);
|
||||
|
||||
// 如果有更新,创建通知
|
||||
if (updates.length > 0) {
|
||||
for (const update of updates) {
|
||||
const notification: Notification = {
|
||||
id: `fav_update_${update.source}_${update.id}_${now}`,
|
||||
type: 'favorite_update',
|
||||
title: '收藏更新',
|
||||
message: `《${update.title}》有新集数更新!从 ${update.old_episodes} 集更新到 ${update.new_episodes} 集`,
|
||||
timestamp: now,
|
||||
read: false,
|
||||
metadata: {
|
||||
source: update.source,
|
||||
id: update.id,
|
||||
title: update.title,
|
||||
old_episodes: update.old_episodes,
|
||||
new_episodes: update.new_episodes,
|
||||
},
|
||||
};
|
||||
|
||||
await storage.addNotification(username, notification);
|
||||
}
|
||||
}
|
||||
|
||||
return NextResponse.json({
|
||||
message: updates.length > 0 ? `发现 ${updates.length} 个更新` : '没有更新',
|
||||
updates,
|
||||
checked: favoriteKeys.length,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('检查收藏更新失败:', error);
|
||||
return NextResponse.json(
|
||||
{ error: (error as Error).message },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
90
src/app/api/user/email-settings/route.ts
Normal file
90
src/app/api/user/email-settings/route.ts
Normal file
@@ -0,0 +1,90 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
|
||||
import { getAuthInfoFromCookie } from '@/lib/auth';
|
||||
import { getStorage } from '@/lib/db';
|
||||
|
||||
export const runtime = 'nodejs';
|
||||
|
||||
/**
|
||||
* GET - 获取用户邮箱设置
|
||||
*/
|
||||
export async function GET(request: NextRequest) {
|
||||
const authInfo = getAuthInfoFromCookie(request);
|
||||
if (!authInfo || !authInfo.username) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
||||
}
|
||||
|
||||
try {
|
||||
const storage = getStorage();
|
||||
const username = authInfo.username;
|
||||
|
||||
const email = storage.getUserEmail
|
||||
? await storage.getUserEmail(username)
|
||||
: null;
|
||||
|
||||
const emailNotifications = storage.getEmailNotificationPreference
|
||||
? await storage.getEmailNotificationPreference(username)
|
||||
: false;
|
||||
|
||||
return NextResponse.json({
|
||||
email: email || '',
|
||||
emailNotifications,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('获取用户邮箱设置失败:', error);
|
||||
return NextResponse.json(
|
||||
{ error: (error as Error).message },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* POST - 保存用户邮箱设置
|
||||
*/
|
||||
export async function POST(request: NextRequest) {
|
||||
const authInfo = getAuthInfoFromCookie(request);
|
||||
if (!authInfo || !authInfo.username) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
||||
}
|
||||
|
||||
try {
|
||||
const storage = getStorage();
|
||||
const username = authInfo.username;
|
||||
const body = await request.json();
|
||||
const { email, emailNotifications } = body;
|
||||
|
||||
// 验证邮箱格式
|
||||
if (email && typeof email === 'string') {
|
||||
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
||||
if (!emailRegex.test(email)) {
|
||||
return NextResponse.json(
|
||||
{ error: '邮箱格式不正确' },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
if (storage.setUserEmail) {
|
||||
await storage.setUserEmail(username, email);
|
||||
}
|
||||
}
|
||||
|
||||
// 保存邮件通知偏好
|
||||
if (typeof emailNotifications === 'boolean') {
|
||||
if (storage.setEmailNotificationPreference) {
|
||||
await storage.setEmailNotificationPreference(username, emailNotifications);
|
||||
}
|
||||
}
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
message: '邮箱设置保存成功',
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('保存用户邮箱设置失败:', error);
|
||||
return NextResponse.json(
|
||||
{ error: (error as Error).message },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user