feat(init): Phase 1 — 基础架构搭建
- 完成 T-001: Next.js 14+ App Router 项目初始化,配置图片域名白名单 - 完成 T-002: TypeScript 类型定义(ContentItem, Platform, PlatformAdapter) - 完成 T-003: API 代理层路由(热榜 + 详情) - 完成 T-004: TikHub API 客户端与滑动窗口限流器 - 完成 T-005: 抖音平台适配器 - 完成 T-006: TikTok 平台适配器 - 完成 T-007: 小红书平台适配器 - 完成 T-008: 适配器注册表与平台配置 - 完成 T-009: Zustand Store(settings + favorites) - 完成 T-010: 全局布局组件(Header + PlatformTabs) Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,29 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { setRuntimeApiKey, getApiKey } from "@/lib/tikhub";
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const body = await request.json();
|
||||
const { apiKey } = body;
|
||||
|
||||
if (!apiKey || typeof apiKey !== "string" || apiKey.trim() === "") {
|
||||
return NextResponse.json(
|
||||
{ error: "请输入有效的 API Key" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
setRuntimeApiKey(apiKey.trim());
|
||||
return NextResponse.json({ success: true, message: "API Key 已保存" });
|
||||
} catch {
|
||||
return NextResponse.json(
|
||||
{ error: "保存失败,请重试" },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export async function GET() {
|
||||
const hasKey = !!getApiKey();
|
||||
return NextResponse.json({ hasKey });
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { getAdapter } from "@/lib/adapters";
|
||||
import { TikHubError } from "@/lib/tikhub";
|
||||
import type { Platform } from "@/types/content";
|
||||
|
||||
export async function GET(
|
||||
request: NextRequest,
|
||||
{ params }: { params: Promise<{ platform: string }> }
|
||||
) {
|
||||
try {
|
||||
const { platform } = await params;
|
||||
const { searchParams } = request.nextUrl;
|
||||
const id = searchParams.get("id");
|
||||
|
||||
if (!id) {
|
||||
return NextResponse.json(
|
||||
{ error: "缺少参数: id" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const adapter = getAdapter(platform as Platform);
|
||||
if (!adapter) {
|
||||
return NextResponse.json(
|
||||
{ error: `不支持的平台: ${platform}` },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const item = await adapter.fetchDetail(id);
|
||||
return NextResponse.json({ data: item });
|
||||
} catch (error) {
|
||||
if (error instanceof TikHubError) {
|
||||
return NextResponse.json(
|
||||
{ error: error.message },
|
||||
{ status: error.statusCode }
|
||||
);
|
||||
}
|
||||
return NextResponse.json(
|
||||
{ error: "服务器内部错误" },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { getAdapter } from "@/lib/adapters";
|
||||
import { TikHubError } from "@/lib/tikhub";
|
||||
import type { Platform } from "@/types/content";
|
||||
|
||||
export async function GET(
|
||||
request: NextRequest,
|
||||
{ params }: { params: Promise<{ platform: string }> }
|
||||
) {
|
||||
try {
|
||||
const { platform } = await params;
|
||||
const { searchParams } = request.nextUrl;
|
||||
const count = parseInt(searchParams.get("count") || "20", 10);
|
||||
|
||||
const adapter = getAdapter(platform as Platform);
|
||||
if (!adapter) {
|
||||
return NextResponse.json(
|
||||
{ error: `不支持的平台: ${platform}` },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const items = await adapter.fetchTrending(count);
|
||||
return NextResponse.json({ data: items });
|
||||
} catch (error) {
|
||||
if (error instanceof TikHubError) {
|
||||
return NextResponse.json(
|
||||
{ error: error.message },
|
||||
{ status: error.statusCode }
|
||||
);
|
||||
}
|
||||
return NextResponse.json(
|
||||
{ error: "服务器内部错误" },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 25 KiB |
@@ -0,0 +1,126 @@
|
||||
@import "tailwindcss";
|
||||
@import "tw-animate-css";
|
||||
@import "shadcn/tailwind.css";
|
||||
|
||||
@custom-variant dark (&:is(.dark *));
|
||||
|
||||
@theme inline {
|
||||
--color-background: var(--background);
|
||||
--color-foreground: var(--foreground);
|
||||
--font-sans: var(--font-geist-sans);
|
||||
--font-mono: var(--font-geist-mono);
|
||||
--color-sidebar-ring: var(--sidebar-ring);
|
||||
--color-sidebar-border: var(--sidebar-border);
|
||||
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
|
||||
--color-sidebar-accent: var(--sidebar-accent);
|
||||
--color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
|
||||
--color-sidebar-primary: var(--sidebar-primary);
|
||||
--color-sidebar-foreground: var(--sidebar-foreground);
|
||||
--color-sidebar: var(--sidebar);
|
||||
--color-chart-5: var(--chart-5);
|
||||
--color-chart-4: var(--chart-4);
|
||||
--color-chart-3: var(--chart-3);
|
||||
--color-chart-2: var(--chart-2);
|
||||
--color-chart-1: var(--chart-1);
|
||||
--color-ring: var(--ring);
|
||||
--color-input: var(--input);
|
||||
--color-border: var(--border);
|
||||
--color-destructive: var(--destructive);
|
||||
--color-accent-foreground: var(--accent-foreground);
|
||||
--color-accent: var(--accent);
|
||||
--color-muted-foreground: var(--muted-foreground);
|
||||
--color-muted: var(--muted);
|
||||
--color-secondary-foreground: var(--secondary-foreground);
|
||||
--color-secondary: var(--secondary);
|
||||
--color-primary-foreground: var(--primary-foreground);
|
||||
--color-primary: var(--primary);
|
||||
--color-popover-foreground: var(--popover-foreground);
|
||||
--color-popover: var(--popover);
|
||||
--color-card-foreground: var(--card-foreground);
|
||||
--color-card: var(--card);
|
||||
--radius-sm: calc(var(--radius) - 4px);
|
||||
--radius-md: calc(var(--radius) - 2px);
|
||||
--radius-lg: var(--radius);
|
||||
--radius-xl: calc(var(--radius) + 4px);
|
||||
--radius-2xl: calc(var(--radius) + 8px);
|
||||
--radius-3xl: calc(var(--radius) + 12px);
|
||||
--radius-4xl: calc(var(--radius) + 16px);
|
||||
}
|
||||
|
||||
:root {
|
||||
--radius: 0.625rem;
|
||||
--background: oklch(1 0 0);
|
||||
--foreground: oklch(0.145 0 0);
|
||||
--card: oklch(1 0 0);
|
||||
--card-foreground: oklch(0.145 0 0);
|
||||
--popover: oklch(1 0 0);
|
||||
--popover-foreground: oklch(0.145 0 0);
|
||||
--primary: oklch(0.205 0 0);
|
||||
--primary-foreground: oklch(0.985 0 0);
|
||||
--secondary: oklch(0.97 0 0);
|
||||
--secondary-foreground: oklch(0.205 0 0);
|
||||
--muted: oklch(0.97 0 0);
|
||||
--muted-foreground: oklch(0.556 0 0);
|
||||
--accent: oklch(0.97 0 0);
|
||||
--accent-foreground: oklch(0.205 0 0);
|
||||
--destructive: oklch(0.577 0.245 27.325);
|
||||
--border: oklch(0.922 0 0);
|
||||
--input: oklch(0.922 0 0);
|
||||
--ring: oklch(0.708 0 0);
|
||||
--chart-1: oklch(0.646 0.222 41.116);
|
||||
--chart-2: oklch(0.6 0.118 184.704);
|
||||
--chart-3: oklch(0.398 0.07 227.392);
|
||||
--chart-4: oklch(0.828 0.189 84.429);
|
||||
--chart-5: oklch(0.769 0.188 70.08);
|
||||
--sidebar: oklch(0.985 0 0);
|
||||
--sidebar-foreground: oklch(0.145 0 0);
|
||||
--sidebar-primary: oklch(0.205 0 0);
|
||||
--sidebar-primary-foreground: oklch(0.985 0 0);
|
||||
--sidebar-accent: oklch(0.97 0 0);
|
||||
--sidebar-accent-foreground: oklch(0.205 0 0);
|
||||
--sidebar-border: oklch(0.922 0 0);
|
||||
--sidebar-ring: oklch(0.708 0 0);
|
||||
}
|
||||
|
||||
.dark {
|
||||
--background: oklch(0.145 0 0);
|
||||
--foreground: oklch(0.985 0 0);
|
||||
--card: oklch(0.205 0 0);
|
||||
--card-foreground: oklch(0.985 0 0);
|
||||
--popover: oklch(0.205 0 0);
|
||||
--popover-foreground: oklch(0.985 0 0);
|
||||
--primary: oklch(0.922 0 0);
|
||||
--primary-foreground: oklch(0.205 0 0);
|
||||
--secondary: oklch(0.269 0 0);
|
||||
--secondary-foreground: oklch(0.985 0 0);
|
||||
--muted: oklch(0.269 0 0);
|
||||
--muted-foreground: oklch(0.708 0 0);
|
||||
--accent: oklch(0.269 0 0);
|
||||
--accent-foreground: oklch(0.985 0 0);
|
||||
--destructive: oklch(0.704 0.191 22.216);
|
||||
--border: oklch(1 0 0 / 10%);
|
||||
--input: oklch(1 0 0 / 15%);
|
||||
--ring: oklch(0.556 0 0);
|
||||
--chart-1: oklch(0.488 0.243 264.376);
|
||||
--chart-2: oklch(0.696 0.17 162.48);
|
||||
--chart-3: oklch(0.769 0.188 70.08);
|
||||
--chart-4: oklch(0.627 0.265 303.9);
|
||||
--chart-5: oklch(0.645 0.246 16.439);
|
||||
--sidebar: oklch(0.205 0 0);
|
||||
--sidebar-foreground: oklch(0.985 0 0);
|
||||
--sidebar-primary: oklch(0.488 0.243 264.376);
|
||||
--sidebar-primary-foreground: oklch(0.985 0 0);
|
||||
--sidebar-accent: oklch(0.269 0 0);
|
||||
--sidebar-accent-foreground: oklch(0.985 0 0);
|
||||
--sidebar-border: oklch(1 0 0 / 10%);
|
||||
--sidebar-ring: oklch(0.556 0 0);
|
||||
}
|
||||
|
||||
@layer base {
|
||||
* {
|
||||
@apply border-border outline-ring/50;
|
||||
}
|
||||
body {
|
||||
@apply bg-background text-foreground;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import type { Metadata } from "next";
|
||||
import { Geist, Geist_Mono } from "next/font/google";
|
||||
import { Toaster } from "sonner";
|
||||
import { QueryProvider } from "@/components/providers/QueryProvider";
|
||||
import "./globals.css";
|
||||
|
||||
const geistSans = Geist({
|
||||
variable: "--font-geist-sans",
|
||||
subsets: ["latin"],
|
||||
});
|
||||
|
||||
const geistMono = Geist_Mono({
|
||||
variable: "--font-geist-mono",
|
||||
subsets: ["latin"],
|
||||
});
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: "Muse Creative Hotspots",
|
||||
description: "全平台热点内容聚合浏览器",
|
||||
};
|
||||
|
||||
export default function RootLayout({
|
||||
children,
|
||||
}: Readonly<{
|
||||
children: React.ReactNode;
|
||||
}>) {
|
||||
return (
|
||||
<html lang="zh-CN">
|
||||
<body
|
||||
className={`${geistSans.variable} ${geistMono.variable} antialiased bg-white`}
|
||||
>
|
||||
<QueryProvider>
|
||||
{children}
|
||||
<Toaster position="top-right" richColors closeButton />
|
||||
</QueryProvider>
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
import Image from "next/image";
|
||||
|
||||
export default function Home() {
|
||||
return (
|
||||
<div className="flex min-h-screen items-center justify-center bg-zinc-50 font-sans dark:bg-black">
|
||||
<main className="flex min-h-screen w-full max-w-3xl flex-col items-center justify-between py-32 px-16 bg-white dark:bg-black sm:items-start">
|
||||
<Image
|
||||
className="dark:invert"
|
||||
src="/next.svg"
|
||||
alt="Next.js logo"
|
||||
width={100}
|
||||
height={20}
|
||||
priority
|
||||
/>
|
||||
<div className="flex flex-col items-center gap-6 text-center sm:items-start sm:text-left">
|
||||
<h1 className="max-w-xs text-3xl font-semibold leading-10 tracking-tight text-black dark:text-zinc-50">
|
||||
To get started, edit the page.tsx file.
|
||||
</h1>
|
||||
<p className="max-w-md text-lg leading-8 text-zinc-600 dark:text-zinc-400">
|
||||
Looking for a starting point or more instructions? Head over to{" "}
|
||||
<a
|
||||
href="https://vercel.com/templates?framework=next.js&utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
|
||||
className="font-medium text-zinc-950 dark:text-zinc-50"
|
||||
>
|
||||
Templates
|
||||
</a>{" "}
|
||||
or the{" "}
|
||||
<a
|
||||
href="https://nextjs.org/learn?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
|
||||
className="font-medium text-zinc-950 dark:text-zinc-50"
|
||||
>
|
||||
Learning
|
||||
</a>{" "}
|
||||
center.
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex flex-col gap-4 text-base font-medium sm:flex-row">
|
||||
<a
|
||||
className="flex h-12 w-full items-center justify-center gap-2 rounded-full bg-foreground px-5 text-background transition-colors hover:bg-[#383838] dark:hover:bg-[#ccc] md:w-[158px]"
|
||||
href="https://vercel.com/new?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
<Image
|
||||
className="dark:invert"
|
||||
src="/vercel.svg"
|
||||
alt="Vercel logomark"
|
||||
width={16}
|
||||
height={16}
|
||||
/>
|
||||
Deploy Now
|
||||
</a>
|
||||
<a
|
||||
className="flex h-12 w-full items-center justify-center rounded-full border border-solid border-black/[.08] px-5 transition-colors hover:border-transparent hover:bg-black/[.04] dark:border-white/[.145] dark:hover:bg-[#1a1a1a] md:w-[158px]"
|
||||
href="https://nextjs.org/docs?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
Documentation
|
||||
</a>
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
import { usePathname } from "next/navigation";
|
||||
import { Heart, Settings } from "lucide-react";
|
||||
import { PlatformTabs } from "./PlatformTabs";
|
||||
|
||||
interface HeaderProps {
|
||||
activePlatform?: string;
|
||||
onPlatformChange?: (platform: string) => void;
|
||||
}
|
||||
|
||||
export function Header({ activePlatform, onPlatformChange }: HeaderProps) {
|
||||
const pathname = usePathname();
|
||||
const isHome = pathname === "/";
|
||||
|
||||
return (
|
||||
<header className="sticky top-0 z-50 w-full bg-white border-b border-slate-200">
|
||||
<div className="mx-auto max-w-7xl px-4 sm:px-6 lg:px-8">
|
||||
<div className="flex h-14 items-center justify-between">
|
||||
{/* Logo */}
|
||||
<Link href="/" className="text-xl font-bold text-slate-800 shrink-0">
|
||||
Muse
|
||||
</Link>
|
||||
|
||||
{/* Platform Tabs - only on home page */}
|
||||
{isHome && onPlatformChange && (
|
||||
<div className="flex-1 flex justify-center mx-4 overflow-x-auto">
|
||||
<PlatformTabs
|
||||
active={activePlatform || "all"}
|
||||
onChange={onPlatformChange}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Right actions */}
|
||||
<div className="flex items-center gap-2 shrink-0">
|
||||
<Link
|
||||
href="/favorites"
|
||||
className="inline-flex items-center justify-center w-9 h-9 rounded-md text-slate-500 hover:text-slate-800 hover:bg-slate-100 transition-colors"
|
||||
>
|
||||
<Heart className="w-5 h-5" />
|
||||
</Link>
|
||||
<Link
|
||||
href="/settings"
|
||||
className="inline-flex items-center justify-center w-9 h-9 rounded-md text-slate-500 hover:text-slate-800 hover:bg-slate-100 transition-colors"
|
||||
>
|
||||
<Settings className="w-5 h-5" />
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
"use client";
|
||||
|
||||
import { MVP_PLATFORMS } from "@/lib/platforms";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
interface PlatformTabsProps {
|
||||
active: string;
|
||||
onChange: (platform: string) => void;
|
||||
}
|
||||
|
||||
const ALL_TAB = { id: "all", name: "全部", icon: "🌐", color: "#2563EB" };
|
||||
|
||||
export function PlatformTabs({ active, onChange }: PlatformTabsProps) {
|
||||
const tabs = [ALL_TAB, ...MVP_PLATFORMS.map((p) => ({ id: p.id, name: p.name, icon: p.icon, color: p.color }))];
|
||||
|
||||
return (
|
||||
<div className="flex items-center gap-1">
|
||||
{tabs.map((tab) => (
|
||||
<button
|
||||
key={tab.id}
|
||||
onClick={() => onChange(tab.id)}
|
||||
className={cn(
|
||||
"relative px-3 py-1.5 text-sm font-medium rounded-md transition-colors whitespace-nowrap",
|
||||
active === tab.id
|
||||
? "text-slate-800"
|
||||
: "text-slate-500 hover:text-slate-700 hover:bg-slate-50"
|
||||
)}
|
||||
>
|
||||
<span className="mr-1">{tab.icon}</span>
|
||||
{tab.name}
|
||||
{active === tab.id && (
|
||||
<span
|
||||
className="absolute bottom-0 left-1/2 -translate-x-1/2 w-6 h-0.5 rounded-full"
|
||||
style={{ backgroundColor: tab.color }}
|
||||
/>
|
||||
)}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
"use client";
|
||||
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { useState } from "react";
|
||||
|
||||
export function QueryProvider({ children }: { children: React.ReactNode }) {
|
||||
const [queryClient] = useState(
|
||||
() =>
|
||||
new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: {
|
||||
staleTime: 1000 * 60 * 5, // 5 minutes
|
||||
retry: 1,
|
||||
},
|
||||
},
|
||||
})
|
||||
);
|
||||
|
||||
return (
|
||||
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
import * as React from "react"
|
||||
import { cva, type VariantProps } from "class-variance-authority"
|
||||
import { Slot } from "radix-ui"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
const buttonVariants = cva(
|
||||
"inline-flex shrink-0 items-center justify-center gap-2 rounded-md text-sm font-medium whitespace-nowrap transition-all outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: "bg-primary text-primary-foreground hover:bg-primary/90",
|
||||
destructive:
|
||||
"bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:bg-destructive/60 dark:focus-visible:ring-destructive/40",
|
||||
outline:
|
||||
"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:border-input dark:bg-input/30 dark:hover:bg-input/50",
|
||||
secondary:
|
||||
"bg-secondary text-secondary-foreground hover:bg-secondary/80",
|
||||
ghost:
|
||||
"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",
|
||||
link: "text-primary underline-offset-4 hover:underline",
|
||||
},
|
||||
size: {
|
||||
default: "h-9 px-4 py-2 has-[>svg]:px-3",
|
||||
xs: "h-6 gap-1 rounded-md px-2 text-xs has-[>svg]:px-1.5 [&_svg:not([class*='size-'])]:size-3",
|
||||
sm: "h-8 gap-1.5 rounded-md px-3 has-[>svg]:px-2.5",
|
||||
lg: "h-10 rounded-md px-6 has-[>svg]:px-4",
|
||||
icon: "size-9",
|
||||
"icon-xs": "size-6 rounded-md [&_svg:not([class*='size-'])]:size-3",
|
||||
"icon-sm": "size-8",
|
||||
"icon-lg": "size-10",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
size: "default",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
function Button({
|
||||
className,
|
||||
variant = "default",
|
||||
size = "default",
|
||||
asChild = false,
|
||||
...props
|
||||
}: React.ComponentProps<"button"> &
|
||||
VariantProps<typeof buttonVariants> & {
|
||||
asChild?: boolean
|
||||
}) {
|
||||
const Comp = asChild ? Slot.Root : "button"
|
||||
|
||||
return (
|
||||
<Comp
|
||||
data-slot="button"
|
||||
data-variant={variant}
|
||||
data-size={size}
|
||||
className={cn(buttonVariants({ variant, size, className }))}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Button, buttonVariants }
|
||||
@@ -0,0 +1,21 @@
|
||||
import * as React from "react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Input({ className, type, ...props }: React.ComponentProps<"input">) {
|
||||
return (
|
||||
<input
|
||||
type={type}
|
||||
data-slot="input"
|
||||
className={cn(
|
||||
"h-9 w-full min-w-0 rounded-md border border-input bg-transparent px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none selection:bg-primary selection:text-primary-foreground file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm dark:bg-input/30",
|
||||
"focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50",
|
||||
"aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Input }
|
||||
@@ -0,0 +1,190 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { CheckIcon, ChevronDownIcon, ChevronUpIcon } from "lucide-react"
|
||||
import { Select as SelectPrimitive } from "radix-ui"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Select({
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Root>) {
|
||||
return <SelectPrimitive.Root data-slot="select" {...props} />
|
||||
}
|
||||
|
||||
function SelectGroup({
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Group>) {
|
||||
return <SelectPrimitive.Group data-slot="select-group" {...props} />
|
||||
}
|
||||
|
||||
function SelectValue({
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Value>) {
|
||||
return <SelectPrimitive.Value data-slot="select-value" {...props} />
|
||||
}
|
||||
|
||||
function SelectTrigger({
|
||||
className,
|
||||
size = "default",
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Trigger> & {
|
||||
size?: "sm" | "default"
|
||||
}) {
|
||||
return (
|
||||
<SelectPrimitive.Trigger
|
||||
data-slot="select-trigger"
|
||||
data-size={size}
|
||||
className={cn(
|
||||
"flex w-fit items-center justify-between gap-2 rounded-md border border-input bg-transparent px-3 py-2 text-sm whitespace-nowrap shadow-xs transition-[color,box-shadow] outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 data-[placeholder]:text-muted-foreground data-[size=default]:h-9 data-[size=sm]:h-8 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2 dark:bg-input/30 dark:hover:bg-input/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<SelectPrimitive.Icon asChild>
|
||||
<ChevronDownIcon className="size-4 opacity-50" />
|
||||
</SelectPrimitive.Icon>
|
||||
</SelectPrimitive.Trigger>
|
||||
)
|
||||
}
|
||||
|
||||
function SelectContent({
|
||||
className,
|
||||
children,
|
||||
position = "item-aligned",
|
||||
align = "center",
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Content>) {
|
||||
return (
|
||||
<SelectPrimitive.Portal>
|
||||
<SelectPrimitive.Content
|
||||
data-slot="select-content"
|
||||
className={cn(
|
||||
"relative z-50 max-h-(--radix-select-content-available-height) min-w-[8rem] origin-(--radix-select-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border bg-popover text-popover-foreground shadow-md data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",
|
||||
position === "popper" &&
|
||||
"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",
|
||||
className
|
||||
)}
|
||||
position={position}
|
||||
align={align}
|
||||
{...props}
|
||||
>
|
||||
<SelectScrollUpButton />
|
||||
<SelectPrimitive.Viewport
|
||||
className={cn(
|
||||
"p-1",
|
||||
position === "popper" &&
|
||||
"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)] scroll-my-1"
|
||||
)}
|
||||
>
|
||||
{children}
|
||||
</SelectPrimitive.Viewport>
|
||||
<SelectScrollDownButton />
|
||||
</SelectPrimitive.Content>
|
||||
</SelectPrimitive.Portal>
|
||||
)
|
||||
}
|
||||
|
||||
function SelectLabel({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Label>) {
|
||||
return (
|
||||
<SelectPrimitive.Label
|
||||
data-slot="select-label"
|
||||
className={cn("px-2 py-1.5 text-xs text-muted-foreground", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SelectItem({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Item>) {
|
||||
return (
|
||||
<SelectPrimitive.Item
|
||||
data-slot="select-item"
|
||||
className={cn(
|
||||
"relative flex w-full cursor-default items-center gap-2 rounded-sm py-1.5 pr-8 pl-2 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<span
|
||||
data-slot="select-item-indicator"
|
||||
className="absolute right-2 flex size-3.5 items-center justify-center"
|
||||
>
|
||||
<SelectPrimitive.ItemIndicator>
|
||||
<CheckIcon className="size-4" />
|
||||
</SelectPrimitive.ItemIndicator>
|
||||
</span>
|
||||
<SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
|
||||
</SelectPrimitive.Item>
|
||||
)
|
||||
}
|
||||
|
||||
function SelectSeparator({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Separator>) {
|
||||
return (
|
||||
<SelectPrimitive.Separator
|
||||
data-slot="select-separator"
|
||||
className={cn("pointer-events-none -mx-1 my-1 h-px bg-border", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SelectScrollUpButton({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.ScrollUpButton>) {
|
||||
return (
|
||||
<SelectPrimitive.ScrollUpButton
|
||||
data-slot="select-scroll-up-button"
|
||||
className={cn(
|
||||
"flex cursor-default items-center justify-center py-1",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<ChevronUpIcon className="size-4" />
|
||||
</SelectPrimitive.ScrollUpButton>
|
||||
)
|
||||
}
|
||||
|
||||
function SelectScrollDownButton({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.ScrollDownButton>) {
|
||||
return (
|
||||
<SelectPrimitive.ScrollDownButton
|
||||
data-slot="select-scroll-down-button"
|
||||
className={cn(
|
||||
"flex cursor-default items-center justify-center py-1",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<ChevronDownIcon className="size-4" />
|
||||
</SelectPrimitive.ScrollDownButton>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectGroup,
|
||||
SelectItem,
|
||||
SelectLabel,
|
||||
SelectScrollDownButton,
|
||||
SelectScrollUpButton,
|
||||
SelectSeparator,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
"use client"
|
||||
|
||||
import {
|
||||
CircleCheckIcon,
|
||||
InfoIcon,
|
||||
Loader2Icon,
|
||||
OctagonXIcon,
|
||||
TriangleAlertIcon,
|
||||
} from "lucide-react"
|
||||
import { useTheme } from "next-themes"
|
||||
import { Toaster as Sonner, type ToasterProps } from "sonner"
|
||||
|
||||
const Toaster = ({ ...props }: ToasterProps) => {
|
||||
const { theme = "system" } = useTheme()
|
||||
|
||||
return (
|
||||
<Sonner
|
||||
theme={theme as ToasterProps["theme"]}
|
||||
className="toaster group"
|
||||
icons={{
|
||||
success: <CircleCheckIcon className="size-4" />,
|
||||
info: <InfoIcon className="size-4" />,
|
||||
warning: <TriangleAlertIcon className="size-4" />,
|
||||
error: <OctagonXIcon className="size-4" />,
|
||||
loading: <Loader2Icon className="size-4 animate-spin" />,
|
||||
}}
|
||||
style={
|
||||
{
|
||||
"--normal-bg": "var(--popover)",
|
||||
"--normal-text": "var(--popover-foreground)",
|
||||
"--normal-border": "var(--border)",
|
||||
"--border-radius": "var(--radius)",
|
||||
} as React.CSSProperties
|
||||
}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Toaster }
|
||||
@@ -0,0 +1,68 @@
|
||||
import type { ContentItem, PlatformAdapter } from "@/types/content";
|
||||
import { tikhubFetch } from "@/lib/tikhub";
|
||||
|
||||
export class DouyinAdapter implements PlatformAdapter {
|
||||
async fetchTrending(count: number): Promise<ContentItem[]> {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const data = await tikhubFetch<any>(
|
||||
"/api/v1/douyin/web/fetch_hot_search_result"
|
||||
);
|
||||
|
||||
const list =
|
||||
data?.data?.word_list ||
|
||||
data?.data?.trending_list ||
|
||||
data?.data ||
|
||||
[];
|
||||
|
||||
const items = Array.isArray(list) ? list : [];
|
||||
|
||||
return items.slice(0, count).map((item: Record<string, unknown>, index: number) =>
|
||||
this.mapToContentItem(item, index)
|
||||
);
|
||||
}
|
||||
|
||||
async fetchDetail(id: string): Promise<ContentItem> {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const data = await tikhubFetch<any>(
|
||||
"/api/v1/douyin/web/fetch_one_video",
|
||||
{ aweme_id: id }
|
||||
);
|
||||
|
||||
const videoData = data?.data?.aweme_detail || data?.data || {};
|
||||
return this.mapToContentItem(videoData, 0);
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
private mapToContentItem(raw: any, index: number): ContentItem {
|
||||
const stats = raw?.statistics || raw?.stats || {};
|
||||
const author = raw?.author || {};
|
||||
|
||||
return {
|
||||
id: String(raw?.aweme_id || raw?.id || raw?.word || `douyin-${index}`),
|
||||
title: raw?.desc || raw?.word || raw?.sentence || raw?.title || "无标题",
|
||||
cover_url:
|
||||
raw?.video?.cover?.url_list?.[0] ||
|
||||
raw?.video?.dynamic_cover?.url_list?.[0] ||
|
||||
raw?.cover ||
|
||||
undefined,
|
||||
video_url: raw?.video?.play_addr?.url_list?.[0] || undefined,
|
||||
author_name: author?.nickname || raw?.author_name || "未知作者",
|
||||
author_avatar: author?.avatar_thumb?.url_list?.[0] || undefined,
|
||||
play_count: stats?.play_count ?? raw?.hot_value ?? undefined,
|
||||
like_count: stats?.digg_count ?? undefined,
|
||||
comment_count: stats?.comment_count ?? undefined,
|
||||
share_count: stats?.share_count ?? undefined,
|
||||
publish_time: raw?.create_time
|
||||
? new Date(raw.create_time * 1000).toISOString()
|
||||
: new Date().toISOString(),
|
||||
platform: "douyin",
|
||||
original_url:
|
||||
raw?.share_url ||
|
||||
`https://www.douyin.com/video/${raw?.aweme_id || raw?.id || ""}`,
|
||||
tags:
|
||||
raw?.text_extra?.map(
|
||||
(t: { hashtag_name?: string }) => t.hashtag_name
|
||||
).filter(Boolean) || undefined,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import type { Platform, PlatformAdapter } from "@/types/content";
|
||||
import { DouyinAdapter } from "./douyin";
|
||||
import { TikTokAdapter } from "./tiktok";
|
||||
import { XiaohongshuAdapter } from "./xiaohongshu";
|
||||
|
||||
const adapters: Partial<Record<Platform, PlatformAdapter>> = {
|
||||
douyin: new DouyinAdapter(),
|
||||
tiktok: new TikTokAdapter(),
|
||||
xiaohongshu: new XiaohongshuAdapter(),
|
||||
};
|
||||
|
||||
export function getAdapter(platform: Platform): PlatformAdapter | null {
|
||||
const adapter = adapters[platform];
|
||||
if (!adapter) {
|
||||
console.warn(`[adapters] 未找到平台适配器: ${platform}`);
|
||||
return null;
|
||||
}
|
||||
return adapter;
|
||||
}
|
||||
|
||||
export function getSupportedPlatforms(): Platform[] {
|
||||
return Object.keys(adapters) as Platform[];
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
import type { ContentItem, PlatformAdapter } from "@/types/content";
|
||||
import { tikhubFetch } from "@/lib/tikhub";
|
||||
|
||||
export class TikTokAdapter implements PlatformAdapter {
|
||||
async fetchTrending(count: number): Promise<ContentItem[]> {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const data = await tikhubFetch<any>(
|
||||
"/api/v1/tiktok/web/fetch_trending_post"
|
||||
);
|
||||
|
||||
const list =
|
||||
data?.data?.aweme_list ||
|
||||
data?.data?.items ||
|
||||
data?.data ||
|
||||
[];
|
||||
|
||||
const items = Array.isArray(list) ? list : [];
|
||||
|
||||
return items.slice(0, count).map((item: Record<string, unknown>, index: number) =>
|
||||
this.mapToContentItem(item, index)
|
||||
);
|
||||
}
|
||||
|
||||
async fetchDetail(id: string): Promise<ContentItem> {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const data = await tikhubFetch<any>(
|
||||
"/api/v1/tiktok/web/fetch_post_detail",
|
||||
{ aweme_id: id }
|
||||
);
|
||||
|
||||
const videoData =
|
||||
data?.data?.aweme_detail || data?.data?.itemInfo?.itemStruct || data?.data || {};
|
||||
return this.mapToContentItem(videoData, 0);
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
private mapToContentItem(raw: any, index: number): ContentItem {
|
||||
const stats = raw?.statistics || raw?.stats || {};
|
||||
const author = raw?.author || {};
|
||||
|
||||
return {
|
||||
id: String(raw?.aweme_id || raw?.id || `tiktok-${index}`),
|
||||
title: raw?.desc || raw?.title || "Untitled",
|
||||
cover_url:
|
||||
raw?.video?.cover?.url_list?.[0] ||
|
||||
raw?.video?.origin_cover?.url_list?.[0] ||
|
||||
raw?.cover ||
|
||||
undefined,
|
||||
video_url: raw?.video?.play_addr?.url_list?.[0] || undefined,
|
||||
author_name:
|
||||
author?.nickname || author?.unique_id || raw?.author_name || "Unknown",
|
||||
author_avatar:
|
||||
author?.avatar_thumb?.url_list?.[0] ||
|
||||
author?.avatar_medium?.url_list?.[0] ||
|
||||
undefined,
|
||||
play_count: stats?.play_count ?? undefined,
|
||||
like_count: stats?.digg_count ?? undefined,
|
||||
comment_count: stats?.comment_count ?? undefined,
|
||||
share_count: stats?.share_count ?? undefined,
|
||||
publish_time: raw?.create_time
|
||||
? new Date(raw.create_time * 1000).toISOString()
|
||||
: new Date().toISOString(),
|
||||
platform: "tiktok",
|
||||
original_url:
|
||||
raw?.share_url ||
|
||||
`https://www.tiktok.com/@${author?.unique_id || "user"}/video/${raw?.aweme_id || raw?.id || ""}`,
|
||||
tags:
|
||||
raw?.text_extra
|
||||
?.map((t: { hashtag_name?: string }) => t.hashtag_name)
|
||||
.filter(Boolean) || undefined,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
import type { ContentItem, PlatformAdapter } from "@/types/content";
|
||||
import { tikhubFetch } from "@/lib/tikhub";
|
||||
|
||||
export class XiaohongshuAdapter implements PlatformAdapter {
|
||||
async fetchTrending(count: number): Promise<ContentItem[]> {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const data = await tikhubFetch<any>(
|
||||
"/api/v1/xiaohongshu/app/v2/fetch_feed"
|
||||
);
|
||||
|
||||
const list =
|
||||
data?.data?.items ||
|
||||
data?.data?.notes ||
|
||||
data?.data ||
|
||||
[];
|
||||
|
||||
const items = Array.isArray(list) ? list : [];
|
||||
|
||||
return items.slice(0, count).map((item: Record<string, unknown>, index: number) =>
|
||||
this.mapToContentItem(item, index)
|
||||
);
|
||||
}
|
||||
|
||||
async fetchDetail(id: string): Promise<ContentItem> {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const data = await tikhubFetch<any>(
|
||||
"/api/v1/xiaohongshu/app/v2/fetch_note_detail",
|
||||
{ note_id: id }
|
||||
);
|
||||
|
||||
const noteData =
|
||||
data?.data?.note_list?.[0] ||
|
||||
data?.data?.items?.[0] ||
|
||||
data?.data || {};
|
||||
return this.mapToContentItem(noteData, 0);
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
private mapToContentItem(raw: any, index: number): ContentItem {
|
||||
const note = raw?.note_card || raw?.note || raw;
|
||||
const user = note?.user || raw?.user || {};
|
||||
const interactInfo = note?.interact_info || {};
|
||||
|
||||
return {
|
||||
id: String(note?.note_id || raw?.id || `xhs-${index}`),
|
||||
title:
|
||||
note?.display_title || note?.title || note?.desc || raw?.title || "无标题",
|
||||
cover_url:
|
||||
note?.cover?.url ||
|
||||
note?.cover?.url_default ||
|
||||
note?.image_list?.[0]?.url ||
|
||||
raw?.cover?.url ||
|
||||
undefined,
|
||||
video_url: note?.video?.url || undefined,
|
||||
author_name: user?.nickname || user?.name || "未知作者",
|
||||
author_avatar: user?.avatar || user?.image || undefined,
|
||||
play_count: undefined, // 小红书通常不展示播放量
|
||||
like_count:
|
||||
interactInfo?.liked_count ??
|
||||
note?.liked_count ??
|
||||
raw?.likes ??
|
||||
undefined,
|
||||
comment_count:
|
||||
interactInfo?.comment_count ??
|
||||
note?.comment_count ??
|
||||
undefined,
|
||||
share_count:
|
||||
interactInfo?.share_count ??
|
||||
note?.share_count ??
|
||||
undefined,
|
||||
publish_time: note?.time
|
||||
? new Date(note.time * 1000).toISOString()
|
||||
: raw?.timestamp
|
||||
? new Date(raw.timestamp * 1000).toISOString()
|
||||
: new Date().toISOString(),
|
||||
platform: "xiaohongshu",
|
||||
original_url: `https://www.xiaohongshu.com/explore/${note?.note_id || raw?.id || ""}`,
|
||||
tags:
|
||||
note?.tag_list?.map(
|
||||
(t: { name?: string }) => t.name
|
||||
).filter(Boolean) || undefined,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import type { PlatformConfig } from "@/types/content";
|
||||
|
||||
export const MVP_PLATFORMS: PlatformConfig[] = [
|
||||
{
|
||||
id: "douyin",
|
||||
name: "抖音",
|
||||
icon: "📱",
|
||||
color: "#000000",
|
||||
enabled: true,
|
||||
endpoints: {
|
||||
trending: "/api/v1/douyin/web/fetch_hot_search_result",
|
||||
detail: "/api/v1/douyin/web/fetch_one_video",
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "tiktok",
|
||||
name: "TikTok",
|
||||
icon: "🎵",
|
||||
color: "#00F2EA",
|
||||
enabled: true,
|
||||
endpoints: {
|
||||
trending: "/api/v1/tiktok/web/fetch_trending_post",
|
||||
detail: "/api/v1/tiktok/web/fetch_post_detail",
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "xiaohongshu",
|
||||
name: "小红书",
|
||||
icon: "📕",
|
||||
color: "#FF2442",
|
||||
enabled: true,
|
||||
endpoints: {
|
||||
trending: "/api/v1/xiaohongshu/app/v2/fetch_feed",
|
||||
detail: "/api/v1/xiaohongshu/app/v2/fetch_note_detail",
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
export function getPlatformConfig(platformId: string): PlatformConfig | undefined {
|
||||
return MVP_PLATFORMS.find((p) => p.id === platformId);
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
const WINDOW_MS = 1000;
|
||||
const MAX_REQUESTS = 10;
|
||||
|
||||
const timestamps: number[] = [];
|
||||
|
||||
export function canMakeRequest(): boolean {
|
||||
const now = Date.now();
|
||||
// Remove timestamps outside the window
|
||||
while (timestamps.length > 0 && timestamps[0] <= now - WINDOW_MS) {
|
||||
timestamps.shift();
|
||||
}
|
||||
return timestamps.length < MAX_REQUESTS;
|
||||
}
|
||||
|
||||
export function recordRequest(): void {
|
||||
timestamps.push(Date.now());
|
||||
}
|
||||
|
||||
export async function waitForSlot(): Promise<void> {
|
||||
while (!canMakeRequest()) {
|
||||
await new Promise((resolve) => setTimeout(resolve, 100));
|
||||
}
|
||||
recordRequest();
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import { waitForSlot } from "./rate-limiter";
|
||||
|
||||
const TIKHUB_BASE_URL = "https://api.tikhub.io";
|
||||
|
||||
// Runtime API Key (set via POST /api/settings)
|
||||
let runtimeApiKey: string | null = null;
|
||||
|
||||
export function setRuntimeApiKey(key: string) {
|
||||
runtimeApiKey = key;
|
||||
}
|
||||
|
||||
export function getApiKey(): string | null {
|
||||
return runtimeApiKey || process.env.TIKHUB_API_KEY || null;
|
||||
}
|
||||
|
||||
export async function tikhubFetch<T>(
|
||||
endpoint: string,
|
||||
params?: Record<string, string>
|
||||
): Promise<T> {
|
||||
const apiKey = getApiKey();
|
||||
if (!apiKey) {
|
||||
throw new TikHubError(401, "API Key 未配置,请在设置页面配置 TikHub API Key");
|
||||
}
|
||||
|
||||
await waitForSlot();
|
||||
|
||||
const url = new URL(endpoint, TIKHUB_BASE_URL);
|
||||
if (params) {
|
||||
Object.entries(params).forEach(([k, v]) => url.searchParams.set(k, v));
|
||||
}
|
||||
|
||||
const res = await fetch(url.toString(), {
|
||||
headers: {
|
||||
Authorization: `Bearer ${apiKey}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
cache: "no-store",
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
if (res.status === 401) {
|
||||
throw new TikHubError(401, "API Key 无效,请检查配置");
|
||||
}
|
||||
if (res.status === 429) {
|
||||
throw new TikHubError(429, "请求过于频繁,请稍后重试");
|
||||
}
|
||||
throw new TikHubError(res.status, `TikHub API 错误: ${res.status}`);
|
||||
}
|
||||
|
||||
return res.json();
|
||||
}
|
||||
|
||||
export class TikHubError extends Error {
|
||||
constructor(
|
||||
public statusCode: number,
|
||||
message: string
|
||||
) {
|
||||
super(message);
|
||||
this.name = "TikHubError";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
import { clsx, type ClassValue } from "clsx"
|
||||
import { twMerge } from "tailwind-merge"
|
||||
|
||||
export function cn(...inputs: ClassValue[]) {
|
||||
return twMerge(clsx(inputs))
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
"use client";
|
||||
|
||||
import { create } from "zustand";
|
||||
import { persist } from "zustand/middleware";
|
||||
import type { ContentItem, Platform } from "@/types/content";
|
||||
|
||||
interface FavoritesStore {
|
||||
items: ContentItem[];
|
||||
addFavorite: (item: ContentItem) => void;
|
||||
removeFavorite: (id: string, platform: Platform) => void;
|
||||
isFavorited: (id: string, platform: Platform) => boolean;
|
||||
}
|
||||
|
||||
export const useFavoritesStore = create<FavoritesStore>()(
|
||||
persist(
|
||||
(set, get) => ({
|
||||
items: [],
|
||||
addFavorite: (item) =>
|
||||
set((state) => {
|
||||
// Dedup by id + platform
|
||||
const exists = state.items.some(
|
||||
(i) => i.id === item.id && i.platform === item.platform
|
||||
);
|
||||
if (exists) return state;
|
||||
return { items: [...state.items, item] };
|
||||
}),
|
||||
removeFavorite: (id, platform) =>
|
||||
set((state) => ({
|
||||
items: state.items.filter(
|
||||
(i) => !(i.id === id && i.platform === platform)
|
||||
),
|
||||
})),
|
||||
isFavorited: (id, platform) =>
|
||||
get().items.some((i) => i.id === id && i.platform === platform),
|
||||
}),
|
||||
{
|
||||
name: "muse-favorites",
|
||||
// Handle data corruption
|
||||
onRehydrateStorage: () => (state) => {
|
||||
if (state && !Array.isArray(state.items)) {
|
||||
state.items = [];
|
||||
}
|
||||
},
|
||||
}
|
||||
)
|
||||
);
|
||||
@@ -0,0 +1,44 @@
|
||||
"use client";
|
||||
|
||||
import { create } from "zustand";
|
||||
import { persist } from "zustand/middleware";
|
||||
import type { Platform } from "@/types/content";
|
||||
|
||||
interface SettingsStore {
|
||||
apiKey: string;
|
||||
refreshInterval: 5 | 10 | 15 | 30 | 60;
|
||||
enabledPlatforms: Record<string, boolean>;
|
||||
displayCount: number;
|
||||
setApiKey: (key: string) => void;
|
||||
setRefreshInterval: (minutes: 5 | 10 | 15 | 30 | 60) => void;
|
||||
togglePlatform: (platform: Platform) => void;
|
||||
setDisplayCount: (count: number) => void;
|
||||
}
|
||||
|
||||
export const useSettingsStore = create<SettingsStore>()(
|
||||
persist(
|
||||
(set) => ({
|
||||
apiKey: "",
|
||||
refreshInterval: 30,
|
||||
enabledPlatforms: {
|
||||
douyin: true,
|
||||
tiktok: true,
|
||||
xiaohongshu: true,
|
||||
},
|
||||
displayCount: 20,
|
||||
setApiKey: (key) => set({ apiKey: key }),
|
||||
setRefreshInterval: (minutes) => set({ refreshInterval: minutes }),
|
||||
togglePlatform: (platform) =>
|
||||
set((state) => ({
|
||||
enabledPlatforms: {
|
||||
...state.enabledPlatforms,
|
||||
[platform]: !state.enabledPlatforms[platform],
|
||||
},
|
||||
})),
|
||||
setDisplayCount: (count) => set({ displayCount: count }),
|
||||
}),
|
||||
{
|
||||
name: "muse-settings",
|
||||
}
|
||||
)
|
||||
);
|
||||
@@ -0,0 +1,43 @@
|
||||
export type Platform =
|
||||
| "douyin"
|
||||
| "tiktok"
|
||||
| "xiaohongshu"
|
||||
| "youtube"
|
||||
| "instagram"
|
||||
| "twitter"
|
||||
| "bilibili"
|
||||
| "weibo";
|
||||
|
||||
export interface ContentItem {
|
||||
id: string;
|
||||
title: string;
|
||||
cover_url?: string;
|
||||
video_url?: string;
|
||||
author_name: string;
|
||||
author_avatar?: string;
|
||||
play_count?: number;
|
||||
like_count?: number;
|
||||
comment_count?: number;
|
||||
share_count?: number;
|
||||
publish_time: string;
|
||||
platform: Platform;
|
||||
original_url: string;
|
||||
tags?: string[];
|
||||
}
|
||||
|
||||
export interface PlatformConfig {
|
||||
id: Platform;
|
||||
name: string;
|
||||
icon: string;
|
||||
color: string;
|
||||
enabled: boolean;
|
||||
endpoints: {
|
||||
trending: string;
|
||||
detail: string;
|
||||
};
|
||||
}
|
||||
|
||||
export interface PlatformAdapter {
|
||||
fetchTrending(count: number): Promise<ContentItem[]>;
|
||||
fetchDetail(id: string): Promise<ContentItem>;
|
||||
}
|
||||
Reference in New Issue
Block a user