This commit is contained in:
eric
2026-06-07 01:17:46 -05:00
parent 283d65d1d1
commit cd885f5fcd
110 changed files with 17876 additions and 11 deletions

View File

@@ -0,0 +1,34 @@
/**
* 认证 Cookie 配置
* 生产环境设置 AUTH_COOKIE_DOMAIN 实现跨子域 SSO如 .hackrobot.cn
* 本地开发不设置 domain避免 IP 访问时 cookie 失效
*/
const COOKIE_NAME = "pb_session";
const COOKIE_MAX_AGE = 60 * 60 * 24 * 365;
export { COOKIE_NAME, COOKIE_MAX_AGE };
/** 从请求 Host 头提取 hostname不含端口 */
export function getHostFromRequest(request: { headers: { get: (k: string) => string | null } }): string {
const host = request.headers.get("host") || request.headers.get("x-forwarded-host") || "";
return host.split(",")[0].trim().replace(/:\d+$/, "");
}
export function getCookieOptions(clear = false, requestHost?: string) {
const isProd = process.env.NODE_ENV === "production";
const domain = process.env.AUTH_COOKIE_DOMAIN?.trim();
const opts: Record<string, unknown> = {
path: "/",
maxAge: clear ? 0 : COOKIE_MAX_AGE,
secure: isProd,
sameSite: "lax" as const,
httpOnly: true,
};
if (domain && isProd) {
opts.domain = domain;
} else if (!isProd && requestHost && /^(\d{1,3}\.){3}\d{1,3}$/.test(requestHost)) {
opts.domain = requestHost;
}
return opts;
}

View File

@@ -0,0 +1,19 @@
/**
* 课程解锁 - 校验登录态 + VIP/api/digital/vip/check
* 与 join 报名支付分离,课程解锁用 VIP 状态
*/
/** 前 2 章试看(暂时关闭,全部需 VIP 解锁) */
export function isFreeTrial(_moduleIndex: number, _lessonIndex: number): boolean {
return false;
}
/** 章节是否可观看(需传入 vip 状态,来自 useAuthAndVip 或 /api/digital/vip/check */
export function canWatchLesson(
moduleIndex: number,
lessonIndex: number,
vip: boolean
): boolean {
if (isFreeTrial(moduleIndex, lessonIndex)) return true;
return vip;
}

43
app/digital/lib/ebook.ts Normal file
View File

@@ -0,0 +1,43 @@
import { marked } from "marked";
export interface EbookChunk {
html: string;
estimatedHeight: number;
}
export interface EbookData {
chunks: EbookChunk[];
headers: string[];
}
export function parseEbookMarkdown(source: string): EbookData {
const html = marked.parse(source, { breaks: true, gfm: true }) as string;
const lazyHtml = html.replace(/<img /g, '<img loading="lazy" decoding="async" ');
let rawChunks = lazyHtml.split(/(?=<h1[\s>])/i).filter((c) => c.trim());
if (rawChunks.length <= 1) {
rawChunks = lazyHtml.split(/(?=<h2[\s>])/i).filter((c) => c.trim());
}
const headers: string[] = [];
const headerRegex = /<h1[^>]*>(.*?)<\/h1>/gi;
let m;
while ((m = headerRegex.exec(lazyHtml)) !== null) {
headers.push(m[1].replace(/<[^>]+>/g, ""));
}
if (headers.length === 0) {
const h2Regex = /<h2[^>]*>(.*?)<\/h2>/gi;
while ((m = h2Regex.exec(lazyHtml)) !== null) {
headers.push(m[1].replace(/<[^>]+>/g, ""));
}
}
const chunks: EbookChunk[] = rawChunks.map((chunkHtml) => {
const imgCount = (chunkHtml.match(/<img\b/g) || []).length;
const textLen = chunkHtml.replace(/<[^>]+>/g, "").length;
const estimatedHeight = Math.max(300, Math.round(textLen * 0.6 + imgCount * 350));
return { html: chunkHtml, estimatedHeight };
});
return { chunks, headers };
}

17
app/digital/lib/env.ts Normal file
View File

@@ -0,0 +1,17 @@
/**
* 环境配置:区分本地调试与生产部署
* 域名更换:设置 ROOT_DOMAIN如 nomadro.com可推导默认值
*/
import { DEFAULT_PAYMENT_API_URL, DEFAULT_SITE_URL } from "@/config/digital/domain.config";
/** 支付 API 地址payjsapi */
export const PAYMENT_API_URL =
process.env.PAYMENT_API_URL || DEFAULT_PAYMENT_API_URL;
/** 站点根地址(用于 return_url 等回跳,生产需配置) */
export const SITE_URL =
process.env.NEXT_PUBLIC_SITE_URL || DEFAULT_SITE_URL;
/** 是否为本地开发 */
export const IS_DEV = process.env.NODE_ENV === "development";

141
app/digital/lib/learning.ts Normal file
View File

@@ -0,0 +1,141 @@
/**
* 学习进度、继续学习、收藏、笔记 - localStorage来自 nomadlms
*/
const PREFIX = "lms-";
const KEY_LAST = `${PREFIX}last`;
const KEY_COMPLETED = `${PREFIX}completed`;
const KEY_BOOKMARKS = `${PREFIX}bookmarks`;
const KEY_NOTES = `${PREFIX}notes`;
const KEY_RATING = `${PREFIX}rating`;
export type LastWatched = { moduleIndex: number; lessonIndex: number; name: string };
export function getLastWatched(): LastWatched | null {
if (typeof window === "undefined") return null;
try {
const raw = localStorage.getItem(KEY_LAST);
if (!raw) return null;
const d = JSON.parse(raw);
if (typeof d?.moduleIndex !== "number" || typeof d?.lessonIndex !== "number") return null;
return { moduleIndex: d.moduleIndex, lessonIndex: d.lessonIndex, name: d.name || "" };
} catch {
return null;
}
}
export function setLastWatched(m: number, l: number, name: string): void {
if (typeof window === "undefined") return;
try {
localStorage.setItem(KEY_LAST, JSON.stringify({ moduleIndex: m, lessonIndex: l, name }));
} catch {
/* ignore */
}
}
export function getCompletedLessons(): Set<string> {
if (typeof window === "undefined") return new Set();
try {
const raw = localStorage.getItem(KEY_COMPLETED);
if (!raw) return new Set();
const arr = JSON.parse(raw);
return new Set(Array.isArray(arr) ? arr : []);
} catch {
return new Set();
}
}
export function markCompleted(moduleIndex: number, lessonIndex: number): void {
if (typeof window === "undefined") return;
try {
const set = getCompletedLessons();
set.add(`${moduleIndex}-${lessonIndex}`);
localStorage.setItem(KEY_COMPLETED, JSON.stringify([...set]));
window.dispatchEvent(new CustomEvent("learning:progress"));
} catch {
/* ignore */
}
}
export function getProgress(totalLessons: number): { completed: number; percent: number } {
const set = getCompletedLessons();
const completed = set.size;
return { completed, percent: totalLessons > 0 ? Math.round((completed / totalLessons) * 100) : 0 };
}
export function getBookmarks(): Set<string> {
if (typeof window === "undefined") return new Set();
try {
const raw = localStorage.getItem(KEY_BOOKMARKS);
if (!raw) return new Set();
const arr = JSON.parse(raw);
return new Set(Array.isArray(arr) ? arr : []);
} catch {
return new Set();
}
}
export function toggleBookmark(moduleIndex: number, lessonIndex: number): boolean {
if (typeof window === "undefined") return false;
try {
const set = getBookmarks();
const key = `${moduleIndex}-${lessonIndex}`;
if (set.has(key)) set.delete(key);
else set.add(key);
localStorage.setItem(KEY_BOOKMARKS, JSON.stringify([...set]));
window.dispatchEvent(new CustomEvent("learning:bookmarks"));
return set.has(key);
} catch {
return false;
}
}
export function isBookmarked(moduleIndex: number, lessonIndex: number): boolean {
return getBookmarks().has(`${moduleIndex}-${lessonIndex}`);
}
export function getNote(moduleIndex: number, lessonIndex: number): string {
if (typeof window === "undefined") return "";
try {
const raw = localStorage.getItem(KEY_NOTES);
if (!raw) return "";
const map = JSON.parse(raw);
return map[`${moduleIndex}-${lessonIndex}`] ?? "";
} catch {
return "";
}
}
export function setNote(moduleIndex: number, lessonIndex: number, text: string): void {
if (typeof window === "undefined") return;
try {
const raw = localStorage.getItem(KEY_NOTES);
const map = raw ? JSON.parse(raw) : {};
map[`${moduleIndex}-${lessonIndex}`] = text;
localStorage.setItem(KEY_NOTES, JSON.stringify(map));
} catch {
/* ignore */
}
}
export function getRating(): { stars: number; comment: string } | null {
if (typeof window === "undefined") return null;
try {
const raw = localStorage.getItem(KEY_RATING);
if (!raw) return null;
const d = JSON.parse(raw);
return { stars: d?.stars ?? 0, comment: d?.comment ?? "" };
} catch {
return null;
}
}
export function setRating(stars: number, comment: string): void {
if (typeof window === "undefined") return;
try {
localStorage.setItem(KEY_RATING, JSON.stringify({ stars, comment }));
window.dispatchEvent(new CustomEvent("learning:rating"));
} catch {
/* ignore */
}
}

View File

@@ -0,0 +1,25 @@
"use client";
import NextLink from "next/link";
import { usePathname as useNextPathname } from "next/navigation";
import { useLocale } from "../context/LocaleContext";
type LocaleLinkProps = React.ComponentProps<typeof NextLink>;
export function LocaleLink({ href, ...props }: LocaleLinkProps) {
const locale = useLocale();
const hrefStr = typeof href === "string" ? href : href.pathname ?? "/";
const localeHref =
hrefStr.startsWith("/api/") || hrefStr.startsWith("/_next")
? hrefStr
: hrefStr.startsWith("/")
? `/${locale}/digital${hrefStr === "/" ? "" : hrefStr}`
: hrefStr;
return <NextLink href={localeHref} {...props} />;
}
export function usePathname() {
const path = useNextPathname();
const match = path?.match(/^\/(zh|en)\/digital(\/.*)?$/);
return match ? (match[2] ?? "/") : path ?? "/";
}

View File

@@ -0,0 +1,67 @@
/**
* MinIO 客户端封装 - 上传、下载等操作
* 通过 getMinioConfig() 获取配置,支持主题覆盖
*/
import * as Minio from "minio";
import { getMinioConfig } from "./config";
import { getThemeConfig } from "@/config/digital/site.config";
/** 获取 MinIO 客户端实例(使用主题配置) */
export function getMinioClient(): Minio.Client {
const theme = getThemeConfig();
const cfg = getMinioConfig(theme.services?.minio);
return new Minio.Client({
endPoint: cfg.endPoint,
port: cfg.port,
useSSL: cfg.useSSL,
accessKey: cfg.accessKey,
secretKey: cfg.secretKey,
pathStyle: true,
region: cfg.region,
});
}
export interface UploadResult {
url: string;
objectKey: string;
}
/**
* 上传文件到 MinIO
* @param buffer 文件内容
* @param objectKey 对象键(含路径,如 joins/xxx.jpg
* @param contentType MIME 类型
*/
export async function uploadBuffer(
buffer: Buffer,
objectKey: string,
contentType: string = "application/octet-stream"
): Promise<UploadResult> {
const theme = getThemeConfig();
const cfg = getMinioConfig(theme.services?.minio);
if (!cfg.enabled) {
throw new Error("MinIO 存储未启用");
}
const client = getMinioClient();
await client.putObject(cfg.bucket, objectKey, buffer, buffer.length, {
"Content-Type": contentType,
});
const url = `${cfg.publicUrl}/${objectKey}`;
return { url, objectKey };
}
/**
* 生成上传用的对象键
* @param ext 文件扩展名
*/
export function generateObjectKey(ext: string): string {
const theme = getThemeConfig();
const cfg = getMinioConfig(theme.services?.minio);
const prefix = cfg.uploadPrefix.replace(/\/$/, "");
return `${prefix}/${Date.now()}_${Math.random().toString(36).slice(2)}.${ext}`;
}

View File

@@ -0,0 +1,2 @@
export { getMinioConfig } from "@/config/digital/services.config";
export type { MinioConfig } from "@/config/digital/services.config";

View File

@@ -0,0 +1,13 @@
/**
* MinIO 存储组件化封装
* 通过 config/services.config 和主题配置,支持多环境、多主题
*/
export { getMinioConfig } from "./config";
export type { MinioConfig } from "./config";
export {
getMinioClient,
uploadBuffer,
generateObjectKey,
} from "./client";
export type { UploadResult } from "./client";

49
app/digital/lib/payEnv.ts Normal file
View File

@@ -0,0 +1,49 @@
/**
* 支付环境检测PC / H5 / 微信浏览器
* 用于 ZPAY 等聚合支付,需区分环境以选择正确的支付通道
* 参考https://juejin.cn/post/7122720360683798542
*/
export type PayEnv = "pc" | "h5" | "wechat";
export type PayChannel = "alipay" | "wxpay";
/** 是否在微信内置浏览器 */
export function isWeChat(): boolean {
if (typeof navigator === "undefined") return false;
return /MicroMessenger/i.test(navigator.userAgent);
}
/** 是否在支付宝内置浏览器 */
export function isAlipay(): boolean {
if (typeof navigator === "undefined") return false;
return /AlipayClient|Alipay/i.test(navigator.userAgent);
}
/** 是否移动设备(含平板) */
export function isMobile(): boolean {
if (typeof navigator === "undefined") return false;
return /AppleWebKit.*Mobile|Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(
navigator.userAgent
);
}
/** 当前支付环境 */
export function getPayEnv(): PayEnv {
if (isWeChat()) return "wechat";
if (isMobile()) return "h5";
return "pc";
}
/**
* 根据环境推荐支付通道
* 所有支付默认微信支付,支付宝暂不提供
*/
export function getRecommendedChannel(_env: PayEnv): PayChannel {
return "wxpay";
}
/** 微信内是否只能选微信支付 */
export function mustUseWxPay(env: PayEnv): boolean {
return env === "wechat";
}

View File

@@ -0,0 +1,57 @@
/**
* 支付客户端 - 封装支付 API 调用
* 用于前端发起支付、跳转支付页
*/
import { getPaymentConfig, getJoinPaymentConfig } from "@/config/digital/services.config";
import type { PayChannel, PayEnv } from "./types";
/** 发起支付并跳转(表单 POST 到 /api/digital/pay */
export function redirectToPay(params: {
user_id: string;
return_url: string;
total_fee?: number;
type?: string;
channel: PayChannel;
device: "pc" | "h5" | "wechat";
/** 是否使用「加入」场景配置(主题覆盖) */
useJoinConfig?: boolean;
}): void {
const baseConfig = getPaymentConfig();
const joinConfig = params.useJoinConfig ? getJoinPaymentConfig() : null;
const total_fee = params.total_fee ?? joinConfig?.amount ?? baseConfig.defaultAmount;
const type = params.type ?? joinConfig?.type ?? baseConfig.defaultType;
const payForm = document.createElement("form");
payForm.method = "POST";
payForm.action = "/api/digital/pay";
payForm.target = "_self";
payForm.style.display = "none";
const fields: [string, string][] = [
["user_id", params.user_id],
["return_url", params.return_url],
["total_fee", String(total_fee)],
["type", type],
["channel", params.channel],
["device", params.device],
["html", "1"],
];
fields.forEach(([k, v]) => {
const input = document.createElement("input");
input.type = "hidden";
input.name = k;
input.value = v;
payForm.appendChild(input);
});
document.body.appendChild(payForm);
payForm.submit();
}
/** 根据 PayEnv 确定 device微信内用 wechat 走收银台表单payurl2 仅支持微信外 */
export function getDeviceFromEnv(env: PayEnv): "pc" | "h5" | "wechat" {
if (env === "wechat") return "wechat";
return env === "pc" ? "pc" : "h5";
}

View File

@@ -0,0 +1,2 @@
export { getPaymentConfig, getServicesConfig } from "@/config/digital/services.config";
export type { PaymentConfig } from "@/config/digital/services.config";

View File

@@ -0,0 +1,4 @@
export { redirectToPay, getDeviceFromEnv } from "./client";
export { getPayEnv, getRecommendedChannel, mustUseWxPay } from "../payEnv";
export type { PayChannel, PayEnv, CreatePayParams, PayRedirectParams } from "./types";
export { getPaymentConfig } from "./config";

View File

@@ -0,0 +1,21 @@
export type PayChannel = "alipay" | "wxpay";
export type PayEnv = "pc" | "h5" | "wechat";
export interface CreatePayParams {
user_id: string;
return_url: string;
total_fee?: number;
type?: string;
channel?: PayChannel;
device?: "pc" | "h5" | "wechat";
}
export interface PayRedirectParams {
user_id: string;
total_fee: number;
type: string;
channel: PayChannel;
return_url: string;
device: "pc" | "h5" | "wechat";
html?: "1";
}

View File

@@ -0,0 +1,179 @@
import { useEffect, useRef, useState } from "react";
const COOKIE_NAME = "join_pay_order";
const STORAGE_NAME = "join_pay_order";
const POLL_INTERVAL_MS = 1200;
const MAX_POLLS = 60;
const MAX_AGE_MS = 15 * 60 * 1000;
function getCookie(name: string): string | null {
if (typeof document === "undefined") return null;
const match = document.cookie.match(new RegExp(`(?:^|; )${name}=([^;]*)`));
return match ? decodeURIComponent(match[1]) : null;
}
function clearCookie(name: string): void {
if (typeof document === "undefined") return;
document.cookie = `${name}=; path=/; max-age=0`;
}
function getStorage(name: string): string | null {
if (typeof window === "undefined") return null;
return window.localStorage.getItem(name);
}
function removeStorage(name: string): void {
if (typeof window === "undefined") return;
window.localStorage.removeItem(name);
}
function clearPendingOrder(): void {
clearCookie(COOKIE_NAME);
removeStorage(STORAGE_NAME);
}
function persistPendingOrder(raw: string): void {
if (typeof document !== "undefined") {
document.cookie = `${COOKIE_NAME}=${encodeURIComponent(raw)}; path=/; max-age=900`;
}
if (typeof window !== "undefined") {
try {
window.localStorage.setItem(STORAGE_NAME, raw);
} catch {}
}
}
function parsePendingOrder(raw: string | null): [string | null, boolean] {
if (!raw?.trim()) return [null, false];
const parts = raw.split("|");
const orderId = parts[0]?.trim() || raw.trim();
const ts = parts[1] ? parseInt(parts[1], 10) : NaN;
if (!orderId) return [null, false];
if (Number.isNaN(ts)) return [orderId, false];
if (Date.now() - ts > MAX_AGE_MS) return [orderId, false];
return [orderId, true];
}
export function usePayStatusPoll(onPaid: (orderId: string) => void): boolean {
const [polling, setPolling] = useState(false);
const onPaidRef = useRef(onPaid);
onPaidRef.current = onPaid;
useEffect(() => {
const urlOrderId =
typeof window !== "undefined"
? new URLSearchParams(window.location.search).get("order_id") || ""
: "";
const cookieRaw = getCookie(COOKIE_NAME);
const [cookieOrderId, cookieValid] = parsePendingOrder(cookieRaw);
const storageRaw = getStorage(STORAGE_NAME);
const [storageOrderId, storageValid] = parsePendingOrder(storageRaw);
let orderId = cookieValid ? cookieOrderId : storageValid ? storageOrderId : null;
let activeRaw = cookieValid ? cookieRaw : storageValid ? storageRaw : null;
if (!orderId && urlOrderId.trim()) {
orderId = urlOrderId.trim();
activeRaw = `${orderId}|${Date.now()}`;
persistPendingOrder(activeRaw);
}
if (!orderId) {
if (cookieRaw || storageRaw) {
clearPendingOrder();
}
return;
}
if (activeRaw) {
persistPendingOrder(activeRaw);
}
setPolling(true);
let attempts = 0;
let stopped = false;
let timer: number | undefined;
let inFlight = false;
const stop = () => {
stopped = true;
if (timer) window.clearTimeout(timer);
};
const scheduleNext = () => {
if (stopped) return;
timer = window.setTimeout(tick, POLL_INTERVAL_MS);
};
const tick = async () => {
if (stopped) return;
if (inFlight) {
scheduleNext();
return;
}
attempts += 1;
if (attempts > MAX_POLLS) {
stop();
clearPendingOrder();
setPolling(false);
return;
}
inFlight = true;
try {
const res = await fetch(
`/api/digital/pay/status?order_id=${encodeURIComponent(orderId)}`,
{ cache: "no-store" }
);
const data = await res.json().catch(() => ({}));
if (data?.ok && data?.paid) {
stop();
clearPendingOrder();
setPolling(false);
// 对齐 nomadvip调用 confirm 写入 PocketBase site_vip不依赖 payjsapi 异步 notify
try {
const confirmRes = await fetch("/api/digital/pay/confirm", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ order_id: orderId }),
cache: "no-store",
});
if (confirmRes.ok && typeof window !== "undefined") {
window.dispatchEvent(new CustomEvent("vip:updated"));
}
} catch {
/* 忽略,不影响跳转 */
}
onPaidRef.current(orderId);
return;
}
} catch {
// keep polling
} finally {
inFlight = false;
}
scheduleNext();
};
const handleResume = () => {
if (typeof document !== "undefined" && document.visibilityState === "hidden") {
return;
}
void tick();
};
document.addEventListener("visibilitychange", handleResume);
window.addEventListener("pageshow", handleResume);
window.addEventListener("focus", handleResume);
void tick();
return () => {
document.removeEventListener("visibilitychange", handleResume);
window.removeEventListener("pageshow", handleResume);
window.removeEventListener("focus", handleResume);
stop();
};
}, []);
return polling;
}

View File

@@ -0,0 +1,49 @@
import { createHash } from "crypto";
const XORPAY_AID = process.env.XORPAY_AID || "8220";
const XORPAY_SECRET =
process.env.XORPAY_SECRET || "afcacd99570945f88de62624aaa3578e";
const XORPAY_QUERY_URL =
process.env.XORPAY_QUERY_URL || "https://xorpay.com/api/query2";
export async function queryXorPayOrderStatus(
orderId: string,
timeoutMs = 5000
): Promise<{ paid: boolean; status?: string; error?: string; url: string } | null> {
const normalizedOrderId = orderId.trim();
if (!normalizedOrderId || !XORPAY_AID || !XORPAY_SECRET) {
return null;
}
const sign = createHash("md5")
.update(`${normalizedOrderId}${XORPAY_SECRET}`, "utf8")
.digest("hex")
.toLowerCase();
const url = new URL(
`${XORPAY_QUERY_URL.replace(/\/$/, "")}/${encodeURIComponent(XORPAY_AID)}`
);
url.searchParams.set("order_id", normalizedOrderId);
url.searchParams.set("sign", sign);
try {
const res = await fetch(url.toString(), {
cache: "no-store",
signal: AbortSignal.timeout(timeoutMs),
});
const data = await res.json().catch(() => ({}));
const status = String(data?.status || "").trim().toLowerCase();
return {
paid: res.ok && (status === "payed" || status === "success"),
status,
url: url.toString(),
error: res.ok ? undefined : `status=${res.status}`,
};
} catch (error) {
return {
paid: false,
url: url.toString(),
error: error instanceof Error ? error.message : String(error),
};
}
}

View File

@@ -0,0 +1,45 @@
const ZPAY_PID = process.env.ZPAY_PID || "2025121809351743";
const ZPAY_KEY = process.env.ZPAY_KEY || "tpEi7wWIWI2kXiYVTpIG6j7it0mjVW89";
const ZPAY_QUERY_URL =
process.env.ZPAY_QUERY_URL || "https://zpayz.cn/api.php";
export async function queryZPayOrderStatus(
orderId: string,
timeoutMs = 5000
): Promise<{ paid: boolean; status?: string; error?: string; url: string } | null> {
const normalizedOrderId = orderId.trim();
if (!normalizedOrderId || !ZPAY_PID || !ZPAY_KEY) {
return null;
}
const url = new URL(ZPAY_QUERY_URL);
url.searchParams.set("act", "order");
url.searchParams.set("pid", ZPAY_PID);
url.searchParams.set("key", ZPAY_KEY);
url.searchParams.set("out_trade_no", normalizedOrderId);
try {
const res = await fetch(url.toString(), {
cache: "no-store",
signal: AbortSignal.timeout(timeoutMs),
});
const data = await res.json().catch(() => ({}));
const code = String(data?.code || "").trim();
const status = String(data?.status || "").trim();
return {
paid: res.ok && code === "1" && status === "1",
status,
url: url.toString(),
error:
res.ok && code === "1"
? undefined
: String(data?.msg || `status=${res.status}`),
};
} catch (error) {
return {
paid: false,
url: url.toString(),
error: error instanceof Error ? error.message : String(error),
};
}
}

View File

@@ -0,0 +1,112 @@
/**
* PocketBase 认证服务 - 客户端使用
* 登录、注册、登出、获取当前用户
*/
import { getPocketBaseConfig } from "@/config/digital/services.config";
import { PB_STORAGE_KEYS } from "./constants";
export interface AuthUser {
id: string;
email: string;
[key: string]: unknown;
}
export interface AuthResult {
token: string;
record: AuthUser;
}
/** 获取 PocketBase 基础 URL客户端用 NEXT_PUBLIC_ 前缀) */
function getPBUrl(): string {
return getPocketBaseConfig().url;
}
/** 登录 */
export async function pbLogin(identity: string, password: string): Promise<AuthResult> {
const url = getPBUrl();
const res = await fetch(`${url}/api/collections/users/auth-with-password`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ identity, password }),
});
if (!res.ok) {
const err = await res.json();
throw new Error(err?.message || "登录失败");
}
const data = await res.json();
if (!data?.token) throw new Error("登录响应异常");
return { token: data.token, record: data.record };
}
/** 注册 */
export async function pbRegister(
email: string,
password: string,
passwordConfirm: string
): Promise<AuthResult> {
const url = getPBUrl();
const config = getPocketBaseConfig();
const res = await fetch(`${url}/api/collections/${config.usersCollection}/records`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ email, password, passwordConfirm }),
});
if (!res.ok) {
const err = await res.json();
throw new Error(err?.message || "注册失败");
}
// 注册成功后自动登录
return pbLogin(email, password);
}
/** 保存认证信息到 localStorage */
export function pbSaveAuth(token: string, record: AuthUser): void {
if (typeof window === "undefined") return;
localStorage.setItem(PB_STORAGE_KEYS.token, token);
localStorage.setItem(PB_STORAGE_KEYS.user, JSON.stringify(record));
}
/** 登出 - 清除本地存储、支付订单 cookie 和根域 Cookie */
export async function pbLogout(): Promise<void> {
if (typeof window === "undefined") return;
localStorage.removeItem(PB_STORAGE_KEYS.token);
localStorage.removeItem(PB_STORAGE_KEYS.user);
localStorage.removeItem("join_pay_order");
try {
document.cookie = "join_pay_order=; path=/; max-age=0";
} catch {
/* ignore */
}
try {
await fetch("/api/digital/auth/logout", { method: "POST" });
} catch {
/* ignore */
}
}
/** 获取当前存储的用户id + email */
export function getStoredUser(): AuthUser | null {
if (typeof window === "undefined") return null;
try {
const raw = localStorage.getItem(PB_STORAGE_KEYS.user);
if (!raw) return null;
const user = JSON.parse(raw);
if (!user?.id || !user?.email) return null;
return { id: user.id, email: user.email };
} catch {
return null;
}
}
/** 获取当前存储的用户邮箱 */
export function getStoredUserEmail(): string | null {
const user = getStoredUser();
return user?.email ?? null;
}
/** 获取存储的 token用于 API 请求) */
export function getStoredToken(): string | null {
if (typeof window === "undefined") return null;
return localStorage.getItem(PB_STORAGE_KEYS.token);
}

View File

@@ -0,0 +1,2 @@
export { getPocketBaseConfig, getServicesConfig } from "@/config/digital/services.config";
export type { PocketBaseConfig } from "@/config/digital/services.config";

View File

@@ -0,0 +1,5 @@
/** localStorage 存储 key */
export const PB_STORAGE_KEYS = {
token: "pb_token",
user: "pb_user",
} as const;

View File

@@ -0,0 +1,12 @@
export {
pbLogin,
pbRegister,
pbSaveAuth,
pbLogout,
getStoredUser,
getStoredUserEmail,
getStoredToken,
} from "./auth";
export type { AuthUser, AuthResult } from "./auth";
export { PB_STORAGE_KEYS } from "./constants";
export { getPocketBaseConfig } from "./config";

View File

@@ -0,0 +1,130 @@
/**
* 主题数据加载器 - 根据 CURRENT_THEME 加载对应主题的内容
* 新增主题1. 在 config/site.config.ts 添加 THEME_CONFIGS
* 2. 在 content/themes/[theme-id]/ 下添加 messages 和 data
* 3. 在本文件 switch 中添加 case
*/
import { CURRENT_THEME, THEME_IDS, type ThemeId } from "@/config/digital";
export type Locale = "zh" | "en";
export type ToolsCategory = {
id: string;
icon: string;
title: string;
color: string;
bg: string;
text: string;
tools: Array<{ name: string; desc: string; href: string }>;
};
/** 加载当前主题的 messages */
export async function getThemeMessages(
locale: Locale
): Promise<Record<string, unknown>> {
const theme = CURRENT_THEME;
switch (theme) {
case "digital-nomad": {
const mod =
locale === "zh"
? await import("@/content/digital/themes/digital-nomad/messages/zh.json")
: await import("@/content/digital/themes/digital-nomad/messages/en.json");
return mod.default;
}
case "solo-company":
case "tiktok-ops":
case "indie-dev":
// 新主题暂无内容时回退到 digital-nomad
return getThemeMessagesFallback(locale);
default:
return getThemeMessagesFallback(locale);
}
}
async function getThemeMessagesFallback(
locale: Locale
): Promise<Record<string, unknown>> {
const mod =
locale === "zh"
? await import("@/content/digital/themes/digital-nomad/messages/zh.json")
: await import("@/content/digital/themes/digital-nomad/messages/en.json");
return mod.default;
}
/** 加载当前主题的 tools 数据 */
export async function getThemeToolsData(): Promise<{
categories: ToolsCategory[];
}> {
const theme = CURRENT_THEME;
switch (theme) {
case "digital-nomad": {
const mod = await import(
"@/content/digital/themes/digital-nomad/data/tools.json"
);
return mod.default;
}
case "solo-company":
case "tiktok-ops":
case "indie-dev":
return getThemeToolsDataFallback();
default:
return getThemeToolsDataFallback();
}
}
async function getThemeToolsDataFallback(): Promise<{
categories: ToolsCategory[];
}> {
const mod = await import(
"@/content/digital/themes/digital-nomad/data/tools.json"
);
return mod.default;
}
export type ResourceData = {
books: Array<{ cover: string; title: string; href: string }>;
products: Array<{ image: string; name: string; href: string }>;
pan: {
categories: Array<{
id: string;
title: string;
icon: string;
items: Array<{ name: string; desc: string; href: string }>;
}>;
};
};
/** 加载资源导航数据:图书、商业数码、网盘 */
export async function getResourceData(): Promise<ResourceData> {
const theme = CURRENT_THEME;
if (theme === "digital-nomad") {
const [booksMod, productsMod, panMod] = await Promise.all([
import("@/content/digital/themes/digital-nomad/data/books.json"),
import("@/content/digital/themes/digital-nomad/data/products.json"),
import("@/content/digital/themes/digital-nomad/data/pan.json"),
]);
return {
books: booksMod.default.books,
products: productsMod.default.products,
pan: panMod.default,
};
}
return getResourceDataFallback();
}
async function getResourceDataFallback(): Promise<ResourceData> {
const [booksMod, productsMod, panMod] = await Promise.all([
import("@/content/digital/themes/digital-nomad/data/books.json"),
import("@/content/digital/themes/digital-nomad/data/products.json"),
import("@/content/digital/themes/digital-nomad/data/pan.json"),
]);
return {
books: booksMod.default.books,
products: productsMod.default.products,
pan: panMod.default,
};
}
export { CURRENT_THEME, THEME_IDS };
export type { ThemeId };

View File

@@ -0,0 +1,68 @@
"use client";
import { useState, useEffect, useCallback } from "react";
import { getStoredUser, getStoredToken } from "@/app/digital/lib/pocketbase";
export interface AuthAndVipState {
user: { id: string; email: string } | null;
vip: boolean;
loading: boolean;
refetch: () => Promise<{ user: { id: string; email: string } | null; vip: boolean }>;
}
export function useAuthAndVip(): AuthAndVipState {
const [user, setUser] = useState<{ id: string; email: string } | null>(null);
const [vip, setVip] = useState(false);
const [loading, setLoading] = useState(true);
const refetch = useCallback(async (): Promise<{ user: { id: string; email: string } | null; vip: boolean }> => {
setLoading(true);
try {
const meRes = await fetch("/api/digital/auth/me", { credentials: "include" });
const meData = await meRes.json();
let newUser = meData?.user ?? null;
if (!newUser) {
const storedUser = getStoredUser();
const storedToken = getStoredToken();
if (storedUser && storedToken) {
newUser = storedUser;
try {
await fetch("/api/digital/auth/sync-session", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ token: storedToken, record: storedUser }),
credentials: "include",
});
} catch {
/* ignore */
}
}
}
let newVip = false;
if (newUser?.email) {
const vipRes = await fetch(`/api/digital/vip/check?email=${encodeURIComponent(newUser.email)}`, { credentials: "include" });
const vipData = await vipRes.json();
newVip = vipData?.vip === true;
}
setUser(newUser);
setVip(newVip);
return { user: newUser, vip: newVip };
} catch {
const storedUser = getStoredUser();
setUser(storedUser);
setVip(false);
return { user: storedUser, vip: false };
} finally {
setLoading(false);
}
}, []);
useEffect(() => {
refetch();
}, [refetch]);
return { user, vip, loading, refetch };
}

View File

@@ -0,0 +1,5 @@
import { MEETUP_URL, VIP_URL } from "@/config/digital/domain.config";
export function useCrossSiteUrls(): { meetupUrl: string; vipUrl: string } {
return { meetupUrl: MEETUP_URL, vipUrl: VIP_URL };
}