import { NextResponse } from "next/server"; import { getLatestTiktokVideo, getTiktokProfile } from "@/lib/followers/tiktok"; import { getRedisClient } from "@/lib/redis"; import { sendDiscordNotification } from "@/lib/discord"; export async function GET(req: Request) { try { const { searchParams } = new URL(req.url); // 1. Verify cron secret const cronSecret = process.env.CRON_SECRET; if (!cronSecret || searchParams.get("secret") !== cronSecret) { return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); } // 2. Fetch the latest video from TikTok API const latestVideo = await getLatestTiktokVideo(); if (!latestVideo) { return NextResponse.json({ message: "No videos found or failed to fetch." }, { status: 200 }); } // 3. Check Redis to see if we've already notified about this video const redis = await getRedisClient(); const redisKey = "erika:tiktok_last_video_id"; const lastVideoId = await redis.get(redisKey); if (lastVideoId === latestVideo.id) { // Already notified return NextResponse.json({ message: "No new videos.", id: latestVideo.id }, { status: 200 }); } // 4. We have a new video! Prepare the notification let officialAuthorName = "TikTok"; let officialAvatarUrl: string | undefined = undefined; try { const profile = await getTiktokProfile(); if (profile.displayName) officialAuthorName = profile.displayName; if (profile.avatarUrl) officialAvatarUrl = profile.avatarUrl; } catch (e) { console.error("[TikTok Cron] Failed to fetch profile:", e); } const message = `ลงคลิปใหม่แล้วววสสสสส ${latestVideo.shareUrl}`; const embed = { title: latestVideo.title || "คลิปใหม่จาก TikTok", url: latestVideo.shareUrl || undefined, color: 0xff0050, author: { name: officialAuthorName, url: latestVideo.shareUrl || "https://www.tiktok.com/", icon_url: officialAvatarUrl || undefined }, image: latestVideo.coverImageUrl ? { url: latestVideo.coverImageUrl } : undefined }; // 5. Send Discord notification await sendDiscordNotification(message, embed); // 6. Update Redis with the new video ID // We don't set an expiry because we want to remember it forever (until the next video) await redis.set(redisKey, latestVideo.id); return NextResponse.json({ success: true, message: "New video notified!", id: latestVideo.id }, { status: 200 }); } catch (error) { console.error("[TikTok Cron] Error processing request:", error); return NextResponse.json({ error: "Internal Server Error" }, { status: 500 }); } }