import { redirect } from "next/navigation"; import { getSession } from "@/lib/auth"; import { db } from "@/lib/db"; import { PublishForm } from "./publish-form"; import { WebhookControl } from "./webhook-control";
export const dynamic="force-dynamic";
export default async function Dashboard({searchParams}:{searchParams:Promise<{error?:string;source?:string}>}){const query=await searchParams;const user=await getSession();if(!user)redirect('/login');const sources=db.prepare('SELECT s.id,s.name,s.base_url,s.sync_status,s.last_synced_at,s.last_error,s.webhook_secret_hash,s.last_webhook_at,s.user_id AS owner_id FROM sources s JOIN source_members sm ON sm.source_id=s.id WHERE sm.user_id=? ORDER BY s.id DESC').all(user.id) as any[];return <><h1>控制台</h1>{query.error&&<p className="error">{query.error}</p>}{query.source==='shared'?<p>你已加入既有的共享 Memos 來源，不會重複同步貼文。</p>:query.source&&<p>來源已連接，首次同步已排入佇列。</p>}<section className="card"><h2>發佈到自己的 Memos</h2>{sources.length?<PublishForm sources={sources}/>:<p className="muted">請先連接一個 Memos 來源。</p>}</section><section className="card"><h2>連接 Memos</h2><form action="/api/sources" method="post"><label>顯示名稱<input name="name" required placeholder="我的 Memos"/></label><label>Memos 網址<input name="baseUrl" type="url" required placeholder="https://memos.example.com"/></label><label>Personal Access Token<input name="token" type="password" required/></label><button>驗證並連接</button></form><p className="muted">Token 會使用伺服器金鑰加密保存。同一個 Memos 帳號與網址會自動共用來源，不會建立重複貼文。</p></section><section><h2>已連接來源</h2>{sources.map(s=><article className="card" key={s.id}><div className="space"><strong>{s.name}</strong><span className="tag">{s.sync_status}</span></div><p className="meta">來源 ID：{s.id}<br/>{s.base_url}<br/>上次同步：{s.last_synced_at||'尚未完成'}<br/>Webhook：{s.webhook_secret_hash?(s.last_webhook_at?`最近收到：${new Date(s.last_webhook_at+'Z').toLocaleString('zh-TW')}`:'已建立 URL，尚未收到呼叫'):'尚未建立 URL'}{s.last_error&&<><br/><span className="error">{s.last_error}</span></>}</p>{s.owner_id===user.id?<WebhookControl sourceId={s.id} configured={Boolean(s.webhook_secret_hash)}/>:<p className="meta">這是共享來源；只有建立者可以管理 webhook。</p>}<form action="/api/sync" method="post"><input type="hidden" name="sourceId" value={s.id}/><button>立即同步</button></form></article>)}</section></>}
