This commit is contained in:
2026-02-03 20:29:55 +08:00
parent d5dde77ee9
commit 9d42a45bb1
18 changed files with 484 additions and 186 deletions

View File

@@ -1,5 +1,4 @@
import { SubtitleEntry } from "../types/subtitle";
import { logger } from "@/lib/logger";
export function parseSrt(data: string): SubtitleEntry[] {
const lines = data.split(/\r?\n/);
@@ -94,7 +93,7 @@ export async function loadSubtitle(url: string): Promise<SubtitleEntry[]> {
const data = await response.text();
return parseSrt(data);
} catch (error) {
logger.error('加载字幕失败', error);
console.error('加载字幕失败', error);
return [];
}
}

View File

@@ -15,7 +15,6 @@ import { SaveList } from "./SaveList";
import { useTranslations } from "next-intl";
import { getLocalStorageOperator } from "@/lib/browser/localStorageOperators";
import { genIPA, genLanguage } from "@/modules/translator/translator-action";
import { logger } from "@/lib/logger";
import { PageLayout } from "@/components/ui/PageLayout";
import { getTTSUrl, TTS_SUPPORTED_LANGUAGES } from "@/lib/bigmodel/tts";
@@ -75,7 +74,7 @@ export default function TextSpeakerPage() {
setIPA(data.ipa);
})
.catch((e) => {
logger.error("生成 IPA 失败", e);
console.error("生成 IPA 失败", e);
setIPA("");
});
}
@@ -120,7 +119,7 @@ export default function TextSpeakerPage() {
load(objurlRef.current);
play();
} catch (e) {
logger.error("播放音频失败", e);
console.error("播放音频失败", e);
setPause(true);
setLanguage(null);
setProcessing(false);
@@ -212,7 +211,7 @@ export default function TextSpeakerPage() {
}
setIntoLocalStorage(save);
} catch (e) {
logger.error("保存到本地存储失败", e);
console.error("保存到本地存储失败", e);
setLanguage(null);
} finally {
setSaving(false);

View File

@@ -1,49 +1,16 @@
import Image from "next/image";
import { PageLayout } from "@/components/ui/PageLayout";
import { PageHeader } from "@/components/ui/PageHeader";
import { auth } from "@/auth";
import { getTranslations } from "next-intl/server";
import { redirect } from "next/navigation";
import { headers } from "next/headers";
import { LogoutButton } from "./LogoutButton";
export default async function ProfilePage() {
const t = await getTranslations("profile");
const session = await auth.api.getSession({ headers: await headers() });
if (!session) {
redirect("/auth?redirect=/profile");
}
return (
<PageLayout>
<PageHeader title={t("myProfile")} />
{/* 用户信息区域 */}
<div className="flex flex-col items-center gap-4">
{/* 用户头像 */}
{session.user.image && (
<Image
width={80}
height={80}
alt="User Avatar"
src={session.user.image as string}
className="rounded-full"
/>
)}
{/* 用户名和邮箱 */}
<div className="text-center">
<h2 className="text-xl font-semibold text-gray-800">
{session.user.name}
</h2>
<p className="text-gray-600">{t("email", { email: session.user.email })}</p>
</div>
{/* 登出按钮 */}
<LogoutButton />
</div>
</PageLayout>
);
// 已登录,跳转到用户资料页面
// 优先使用 username如果没有则使用 email
const username = (session.user.username as string) || (session.user.email as string);
redirect(`/users/${username}`);
}

View File

@@ -1,8 +0,0 @@
interface UserPageProps {
params: Promise<{ username: string}>;
}
export default async function UserPage({params}: UserPageProps) {
const {username} = await params;
}

View File

@@ -0,0 +1,126 @@
import Image from "next/image";
import { Container } from "@/components/ui/Container";
import { actionGetUserProfileByUsername } from "@/modules/auth/auth-action";
import { notFound } from "next/navigation";
import { getTranslations } from "next-intl/server";
interface UserPageProps {
params: Promise<{ username: string; }>;
}
export default async function UserPage({ params }: UserPageProps) {
const { username } = await params;
const t = await getTranslations("user_profile");
// Get user profile
const result = await actionGetUserProfileByUsername({ username });
if (!result.success || !result.data) {
notFound();
}
const user = result.data;
return (
<div className="min-h-[calc(100vh-64px)] bg-gray-50 py-8">
<Container className="max-w-3xl mx-auto">
{/* Header */}
<div className="bg-white rounded-lg shadow-md p-6 mb-6">
<div className="flex items-center space-x-6">
{/* Avatar */}
{user.image ? (
<div className="relative w-24 h-24 rounded-full border-4 border-[#35786f] overflow-hidden">
<Image
src={user.image}
alt={user.displayUsername || user.username || user.email}
fill
className="object-cover"
unoptimized
/>
</div>
) : (
<div className="w-24 h-24 rounded-full bg-[#35786f] border-4 border-[#35786f] flex items-center justify-center">
<span className="text-3xl font-bold text-white">
{(user.displayUsername || user.username || user.email)[0].toUpperCase()}
</span>
</div>
)}
{/* User Info */}
<div className="flex-1">
<h1 className="text-3xl font-bold text-gray-800 mb-2">
{user.displayUsername || user.username || t("anonymous")}
</h1>
{user.username && (
<p className="text-gray-600 text-sm mb-1">
@{user.username}
</p>
)}
<div className="flex items-center space-x-4 text-sm">
<span className="text-gray-500">
Joined: {new Date(user.createdAt).toLocaleDateString()}
</span>
{user.emailVerified && (
<span className="flex items-center text-green-600">
<svg className="w-4 h-4 mr-1" fill="currentColor" viewBox="0 0 20 20">
<path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 00016zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.293 12.293a1 1 0 101.414 1.414l2 2a1 1 0 001.414 0l4-4z" clipRule="evenodd" />
</svg>
Verified
</span>
)}
</div>
</div>
</div>
</div>
{/* Email Section */}
<div className="bg-white rounded-lg shadow-md p-6 mb-6">
<h2 className="text-xl font-semibold text-gray-800 mb-4">{t("email")}</h2>
<div className="flex items-center justify-between">
<div className="flex items-center space-x-3">
<span className="text-gray-700">{user.email}</span>
</div>
{user.emailVerified ? (
<span className="inline-flex items-center px-3 py-1 rounded-full text-sm font-medium bg-green-100 text-green-800">
{t("verified")}
</span>
) : (
<span className="inline-flex items-center px-3 py-1 rounded-full text-sm font-medium bg-yellow-100 text-yellow-800">
{t("unverified")}
</span>
)}
</div>
</div>
{/* Account Info */}
<div className="bg-white rounded-lg shadow-md p-6">
<h2 className="text-xl font-semibold text-gray-800 mb-4">{t("accountInfo")}</h2>
<dl className="grid grid-cols-1 gap-4 sm:grid-cols-2">
<div>
<dt className="text-sm font-medium text-gray-500">{t("userId")}</dt>
<dd className="mt-1 text-sm text-gray-900 font-mono break-all">{user.id}</dd>
</div>
<div>
<dt className="text-sm font-medium text-gray-500">{t("username")}</dt>
<dd className="mt-1 text-sm text-gray-900">
{user.username || <span className="text-gray-400">{t("notSet")}</span>}
</dd>
</div>
<div>
<dt className="text-sm font-medium text-gray-500">{t("displayName")}</dt>
<dd className="mt-1 text-sm text-gray-900">
{user.displayUsername || <span className="text-gray-400">{t("notSet")}</span>}
</dd>
</div>
<div>
<dt className="text-sm font-medium text-gray-500">{t("memberSince")}</dt>
<dd className="mt-1 text-sm text-gray-900">
{new Date(user.createdAt).toLocaleDateString()}
</dd>
</div>
</dl>
</div>
</Container>
</div>
);
}

View File

@@ -1,25 +0,0 @@
class Logger {
error(message: string, error?: unknown): void {
if (error instanceof Error) {
console.error(`[ERROR] ${message}:`, error.message, error.stack);
} else {
console.error(`[ERROR] ${message}:`, error);
}
}
warn(message: string, ...args: unknown[]): void {
console.warn(`[WARN] ${message}`, ...args);
}
info(message: string, ...args: unknown[]): void {
console.info(`[INFO] ${message}`, ...args);
}
debug(message: string, ...args: unknown[]): void {
if (process.env.NODE_ENV === "development") {
console.debug(`[DEBUG] ${message}`, ...args);
}
}
}
export const logger = new Logger();

View File

@@ -1,12 +1,12 @@
import z from "zod";
import { generateValidator } from "@/utils/validate";
import { LENGTH_MAX_PASSWORD, LENGTH_MAX_USERNAME, LENGTH_MIN_PASSWORD, LENGTH_MIN_USERNAME } from "@/shared/constant";
import { LENGTH_MAX_USERNAME, LENGTH_MIN_USERNAME } from "@/shared/constant";
// Schema for sign up
const schemaActionInputSignUp = z.object({
email: z.string().regex(/^[^\s@]+@[^\s@]+\.[^\s@]+$/, "Invalid email address"),
username: z.string().min(LENGTH_MIN_USERNAME).max(LENGTH_MAX_USERNAME).regex(/^[a-zA-Z0-9_]+$/, "Username can only contain letters, numbers, and underscores"),
password: z.string().min(LENGTH_MIN_PASSWORD).max(LENGTH_MAX_PASSWORD),
password: z.string().min(8).max(100),
redirectTo: z.string().nullish(),
});
@@ -17,7 +17,7 @@ export const validateActionInputSignUp = generateValidator(schemaActionInputSign
// Schema for sign in
const schemaActionInputSignIn = z.object({
identifier: z.string().min(1), // Can be email or username
password: z.string().min(LENGTH_MIN_PASSWORD).max(LENGTH_MAX_PASSWORD),
password: z.string().min(8).max(100),
redirectTo: z.string().nullish(),
});
@@ -25,14 +25,14 @@ export type ActionInputSignIn = z.infer<typeof schemaActionInputSignIn>;
export const validateActionInputSignIn = generateValidator(schemaActionInputSignIn);
// Schema for sign out
const schemaActionInputSignOut = z.object({
redirectTo: z.string().nullish(),
// Schema for get user profile by username
const schemaActionInputGetUserProfileByUsername = z.object({
username: z.string().min(LENGTH_MIN_USERNAME).max(LENGTH_MAX_USERNAME),
});
export type ActionInputSignOut = z.infer<typeof schemaActionInputSignOut>;
export type ActionInputGetUserProfileByUsername = z.infer<typeof schemaActionInputGetUserProfileByUsername>;
export const validateActionInputSignOut = generateValidator(schemaActionInputSignOut);
export const validateActionInputGetUserProfileByUsername = generateValidator(schemaActionInputGetUserProfileByUsername);
// Output types
export type ActionOutputAuth = {
@@ -45,3 +45,18 @@ export type ActionOutputAuth = {
identifier?: string[];
};
};
export type ActionOutputUserProfile = {
success: boolean;
message: string;
data?: {
id: string;
email: string;
emailVerified: boolean;
username: string | null;
displayUsername: string | null;
image: string | null;
createdAt: Date;
updatedAt: Date;
};
};

View File

@@ -5,19 +5,23 @@ import { headers } from "next/headers";
import { redirect } from "next/navigation";
import { ValidateError } from "@/lib/errors";
import {
ActionInputGetUserProfileByUsername,
ActionInputSignIn,
ActionInputSignUp,
ActionOutputAuth,
ActionOutputUserProfile,
validateActionInputGetUserProfileByUsername,
validateActionInputSignIn,
validateActionInputSignUp
} from "./auth-action-dto";
import {
serviceGetUserProfileByUsername,
serviceSignIn,
serviceSignUp
} from "./auth-service";
// Re-export types for use in components
export type { ActionOutputAuth } from "./auth-action-dto";
export type { ActionOutputAuth, ActionOutputUserProfile } from "./auth-action-dto";
/**
* Sign up action
@@ -144,3 +148,32 @@ export async function signOutAction() {
redirect("/auth");
}
}
/**
* Get user profile by username
* Returns user profile data for display
*/
export async function actionGetUserProfileByUsername(dto: ActionInputGetUserProfileByUsername): Promise<ActionOutputUserProfile> {
try {
const userProfile = await serviceGetUserProfileByUsername(dto);
if (!userProfile) {
return {
success: false,
message: "User not found",
};
}
return {
success: true,
message: "User profile retrieved successfully",
data: userProfile,
};
} catch (e) {
console.error("Get user profile error:", e);
return {
success: false,
message: "Failed to retrieve user profile",
};
}
}

View File

@@ -0,0 +1,26 @@
// Repository layer DTOs for auth module - User profile operations
// User profile data types
export type RepoOutputUserProfile = {
id: string;
email: string;
emailVerified: boolean;
username: string | null;
displayUsername: string | null;
image: string | null;
createdAt: Date;
updatedAt: Date;
} | null;
// Input types
export type RepoInputFindUserByUsername = {
username: string;
};
export type RepoInputFindUserById = {
id: string;
};
export type RepoInputFindUserByEmail = {
email: string;
};

View File

@@ -0,0 +1,70 @@
import { prisma } from "@/lib/db";
import {
RepoInputFindUserByEmail,
RepoInputFindUserById,
RepoInputFindUserByUsername,
RepoOutputUserProfile
} from "./auth-repository-dto";
/**
* Find user by username
*/
export async function repoFindUserByUsername(dto: RepoInputFindUserByUsername): Promise<RepoOutputUserProfile> {
const user = await prisma.user.findUnique({
where: { username: dto.username },
select: {
id: true,
email: true,
emailVerified: true,
username: true,
displayUsername: true,
image: true,
createdAt: true,
updatedAt: true,
}
});
return user;
}
/**
* Find user by ID
*/
export async function repoFindUserById(dto: RepoInputFindUserById): Promise<RepoOutputUserProfile> {
const user = await prisma.user.findUnique({
where: { id: dto.id },
select: {
id: true,
email: true,
emailVerified: true,
username: true,
displayUsername: true,
image: true,
createdAt: true,
updatedAt: true,
}
});
return user;
}
/**
* Find user by email
*/
export async function repoFindUserByEmail(dto: RepoInputFindUserByEmail): Promise<RepoOutputUserProfile> {
const user = await prisma.user.findUnique({
where: { email: dto.email },
select: {
id: true,
email: true,
emailVerified: true,
username: true,
displayUsername: true,
image: true,
createdAt: true,
updatedAt: true,
}
});
return user;
}

View File

@@ -1,50 +1,39 @@
// Service layer DTOs for auth module
// Service layer DTOs for auth module - User profile operations
// Sign up input/output
export type ServiceInputSignUp = {
email: string;
username: string;
password: string; // plain text, will be hashed by better-auth
password: string;
name: string;
};
export type ServiceOutputSignUp = {
export type ServiceOutputAuth = {
success: boolean;
userId?: string;
email?: string;
username?: string;
};
// Sign in input/output
export type ServiceInputSignIn = {
identifier: string; // email or username
identifier: string;
password: string;
};
export type ServiceOutputSignIn = {
success: boolean;
userId?: string;
email?: string;
username?: string;
sessionToken?: string;
// Get user profile input/output
export type ServiceInputGetUserProfileByUsername = {
username: string;
};
// Sign out input/output
export type ServiceInputSignOut = {
sessionId?: string;
export type ServiceInputGetUserProfileById = {
id: string;
};
export type ServiceOutputSignOut = {
success: boolean;
};
// User existence check
export type ServiceInputCheckUserExists = {
email?: string;
username?: string;
};
export type ServiceOutputCheckUserExists = {
emailExists: boolean;
usernameExists: boolean;
};
export type ServiceOutputUserProfile = {
id: string;
email: string;
emailVerified: boolean;
username: string | null;
displayUsername: string | null;
image: string | null;
createdAt: Date;
updatedAt: Date;
} | null;

View File

@@ -1,76 +1,94 @@
import { auth } from "@/auth";
import {
ServiceInputSignUp,
repoFindUserByUsername,
repoFindUserById
} from "./auth-repository";
import {
ServiceInputGetUserProfileByUsername,
ServiceInputGetUserProfileById,
ServiceInputSignIn,
ServiceOutputSignUp,
ServiceOutputSignIn
ServiceInputSignUp,
ServiceOutputAuth,
ServiceOutputUserProfile
} from "./auth-service-dto";
/**
* Sign up a new user
* Calls better-auth's signUp.email with username support
* Sign up service
*/
export async function serviceSignUp(dto: ServiceInputSignUp): Promise<ServiceOutputSignUp> {
try {
await auth.api.signUpEmail({
body: {
email: dto.email,
password: dto.password,
username: dto.username,
name: dto.name,
}
});
return {
success: true,
export async function serviceSignUp(dto: ServiceInputSignUp): Promise<ServiceOutputAuth> {
// Better-auth handles user creation internally
const result = await auth.api.signUpEmail({
body: {
email: dto.email,
password: dto.password,
name: dto.name,
username: dto.username,
};
} catch (error) {
// better-auth handles duplicates and validation errors
}
});
if (!result.user) {
return {
success: false,
};
}
return {
success: true,
};
}
/**
* Sign in user
* Uses better-auth's signIn.username for username-based authentication
* Sign in service
*/
export async function serviceSignIn(dto: ServiceInputSignIn): Promise<ServiceOutputSignIn> {
try {
// Determine if identifier is email or username
const isEmail = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(dto.identifier);
export async function serviceSignIn(dto: ServiceInputSignIn): Promise<ServiceOutputAuth> {
// Try to sign in with username first
const userResult = await repoFindUserByUsername({ username: dto.identifier });
let session;
if (userResult) {
// User found by username, use email signIn with the user's email
const result = await auth.api.signInEmail({
body: {
email: userResult.email,
password: dto.password,
}
});
if (isEmail) {
// Use email sign in
session = await auth.api.signInEmail({
body: {
email: dto.identifier,
password: dto.password,
}
});
} else {
// Use username sign in (requires username plugin)
session = await auth.api.signInUsername({
body: {
username: dto.identifier,
password: dto.password,
}
});
if (result.user) {
return {
success: true,
};
}
} else {
// Try as email
const result = await auth.api.signInEmail({
body: {
email: dto.identifier,
password: dto.password,
}
});
return {
success: true,
sessionToken: session?.token,
};
} catch (error) {
// better-auth throws on invalid credentials
return {
success: false,
};
if (result.user) {
return {
success: true,
};
}
}
return {
success: false,
};
}
/**
* Get user profile by username
*/
export async function serviceGetUserProfileByUsername(dto: ServiceInputGetUserProfileByUsername): Promise<ServiceOutputUserProfile> {
return await repoFindUserByUsername(dto);
}
/**
* Get user profile by ID
*/
export async function serviceGetUserProfileById(dto: ServiceInputGetUserProfileById): Promise<ServiceOutputUserProfile> {
return await repoFindUserById(dto);
}