This commit is contained in:
ditiqi 2025-01-26 20:26:12 +08:00
parent fe4a7cfae3
commit b101cc8e3b
12 changed files with 101 additions and 73 deletions

View File

@ -11,7 +11,7 @@ import { env } from '@server/env';
import { redis } from '@server/utils/redis/redis.service'; import { redis } from '@server/utils/redis/redis.service';
import EventBus from '@server/utils/event-bus'; import EventBus from '@server/utils/event-bus';
import { RoleMapService } from '@server/models/rbac/rolemap.service'; import { RoleMapService } from '@server/models/rbac/rolemap.service';
import { Request } from "express" import { Request } from 'express';
interface ProfileResult { interface ProfileResult {
staff: UserProfile | undefined; staff: UserProfile | undefined;
error?: string; error?: string;
@ -22,9 +22,11 @@ interface TokenVerifyResult {
error?: string; error?: string;
} }
export function extractTokenFromHeader(request: Request): string | undefined { export function extractTokenFromHeader(request: Request): string | undefined {
return extractTokenFromAuthorization(request.headers.authorization) return extractTokenFromAuthorization(request.headers.authorization);
} }
export function extractTokenFromAuthorization(authorization: string): string | undefined { export function extractTokenFromAuthorization(
authorization: string,
): string | undefined {
const [type, token] = authorization?.split(' ') ?? []; const [type, token] = authorization?.split(' ') ?? [];
return type === 'Bearer' ? token : undefined; return type === 'Bearer' ? token : undefined;
} }
@ -40,7 +42,7 @@ export class UserProfileService {
this.jwtService = new JwtService(); this.jwtService = new JwtService();
this.departmentService = new DepartmentService(); this.departmentService = new DepartmentService();
this.roleMapService = new RoleMapService(this.departmentService); this.roleMapService = new RoleMapService(this.departmentService);
EventBus.on("dataChanged", ({ type, data }) => { EventBus.on('dataChanged', ({ type, data }) => {
if (type === ObjectType.STAFF) { if (type === ObjectType.STAFF) {
// 确保 data 是数组,如果不是则转换为数组 // 确保 data 是数组,如果不是则转换为数组
const dataArray = Array.isArray(data) ? data : [data]; const dataArray = Array.isArray(data) ? data : [data];
@ -51,7 +53,6 @@ export class UserProfileService {
} }
} }
}); });
} }
public getProfileCacheKey(id: string) { public getProfileCacheKey(id: string) {
return `user-profile-${id}`; return `user-profile-${id}`;
@ -162,6 +163,7 @@ export class UserProfileService {
showname: true, showname: true,
username: true, username: true,
phoneNumber: true, phoneNumber: true,
meta: true,
}, },
})) as unknown as UserProfile; })) as unknown as UserProfile;
} }
@ -174,9 +176,7 @@ export class UserProfileService {
staff.deptId staff.deptId
? this.departmentService.getDescendantIdsInDomain(staff.deptId) ? this.departmentService.getDescendantIdsInDomain(staff.deptId)
: [], : [],
staff.deptId staff.deptId ? this.departmentService.getAncestorIds([staff.deptId]) : [],
? this.departmentService.getAncestorIds([staff.deptId])
: [],
this.roleMapService.getPermsForObject({ this.roleMapService.getPermsForObject({
domainId: staff.domainId, domainId: staff.domainId,
staffId: staff.id, staffId: staff.id,

View File

@ -9,6 +9,7 @@ export interface AvatarUploaderProps {
placeholder?: string; placeholder?: string;
className?: string; className?: string;
onChange?: (value: string) => void; onChange?: (value: string) => void;
compressed?: boolean;
style?: React.CSSProperties; // 添加style属性 style?: React.CSSProperties; // 添加style属性
} }
@ -18,12 +19,14 @@ interface UploadingFile {
status: "uploading" | "done" | "error"; status: "uploading" | "done" | "error";
fileId?: string; fileId?: string;
url?: string; url?: string;
compressedUrl?: string;
fileKey?: string; fileKey?: string;
} }
const AvatarUploader: React.FC<AvatarUploaderProps> = ({ const AvatarUploader: React.FC<AvatarUploaderProps> = ({
value, value,
onChange, onChange,
compressed = true,
className, className,
placeholder = "点击上传", placeholder = "点击上传",
style, // 解构style属性 style, // 解构style属性
@ -32,6 +35,7 @@ const AvatarUploader: React.FC<AvatarUploaderProps> = ({
const [file, setFile] = useState<UploadingFile | null>(null); const [file, setFile] = useState<UploadingFile | null>(null);
const [previewUrl, setPreviewUrl] = useState<string>(value || ""); const [previewUrl, setPreviewUrl] = useState<string>(value || "");
const [url, setUrl] = useState<string>(value || "");
const [uploading, setUploading] = useState(false); const [uploading, setUploading] = useState(false);
const inputRef = useRef<HTMLInputElement>(null); const inputRef = useRef<HTMLInputElement>(null);
@ -50,7 +54,7 @@ const AvatarUploader: React.FC<AvatarUploaderProps> = ({
setUploading(true); setUploading(true);
try { try {
const fileId = await new Promise<string>((resolve, reject) => { const uploadedUrl = await new Promise<string>((resolve, reject) => {
handleFileUpload( handleFileUpload(
selectedFile, selectedFile,
(result) => { (result) => {
@ -59,10 +63,13 @@ const AvatarUploader: React.FC<AvatarUploaderProps> = ({
progress: 100, progress: 100,
status: "done", status: "done",
fileId: result.fileId, fileId: result.fileId,
url: result?.url, url: result.url,
compressedUrl: result.compressedUrl,
})); }));
setPreviewUrl(result?.url); setUrl(result.url);
resolve(result.fileId); setPreviewUrl(result.compressedUrl);
// 直接使用 result 中的最新值
resolve(compressed ? result.compressedUrl : result.url);
}, },
(error) => { (error) => {
reject(error); reject(error);
@ -70,7 +77,8 @@ const AvatarUploader: React.FC<AvatarUploaderProps> = ({
file?.fileKey file?.fileKey
); );
}); });
onChange?.(fileId); // 使用 resolved 的最新值调用 onChange
onChange?.(uploadedUrl);
message.success("头像上传成功"); message.success("头像上传成功");
} catch (error) { } catch (error) {
console.error("上传错误:", error); console.error("上传错误:", error);

View File

@ -8,7 +8,7 @@ import { Upload, Progress, Button } from "antd";
import type { UploadFile } from "antd"; import type { UploadFile } from "antd";
import { useTusUpload } from "@web/src/hooks/useTusUpload"; import { useTusUpload } from "@web/src/hooks/useTusUpload";
import toast from "react-hot-toast"; import toast from "react-hot-toast";
import { getCompressedImageUrl } from "@nice/utils";
export interface TusUploaderProps { export interface TusUploaderProps {
value?: string[]; value?: string[];
onChange?: (value: string[]) => void; onChange?: (value: string[]) => void;

View File

@ -47,6 +47,7 @@ export default function StaffForm() {
rank, rank,
office, office,
} = values; } = values;
console.log("photoUrl", photoUrl);
setFormLoading(true); setFormLoading(true);
try { try {
if (data && user?.id) { if (data && user?.id) {
@ -120,6 +121,9 @@ export default function StaffForm() {
<AvatarUploader <AvatarUploader
placeholder="点击上传头像" placeholder="点击上传头像"
className="rounded-lg" className="rounded-lg"
onChange={(value) => {
console.log(value);
}}
style={{ style={{
width: "120px", width: "120px",
height: "150px", height: "150px",

View File

@ -142,10 +142,9 @@ export function UserMenu() {
onClick={toggleMenu} onClick={toggleMenu}
className="flex items-center rounded-full transition-all duration-200 ease-in-out"> className="flex items-center rounded-full transition-all duration-200 ease-in-out">
{/* Avatar 容器,相对定位 */} {/* Avatar 容器,相对定位 */}
<div className="relative"> <div className="relative">
<Avatar <Avatar
src={(user?.meta as any)?.photoUrl} src={user?.meta?.photoUrl}
name={user?.showname || user?.username} name={user?.showname || user?.username}
size={40} size={40}
className="ring-2 ring-white hover:ring-[#00538E]/90 className="ring-2 ring-white hover:ring-[#00538E]/90
@ -196,7 +195,7 @@ export function UserMenu() {
border-b border-[#E5EDF5] "> border-b border-[#E5EDF5] ">
<div className="flex items-center space-x-4"> <div className="flex items-center space-x-4">
<Avatar <Avatar
src={user?.avatar} src={user?.meta?.photoUrl}
name={user?.showname || user?.username} name={user?.showname || user?.username}
size={40} size={40}
className="ring-2 ring-white shadow-sm" className="ring-2 ring-white shadow-sm"

View File

@ -17,6 +17,7 @@ import { CustomAvatar } from "@web/src/components/presentation/CustomAvatar";
import PostResources from "./PostResources"; import PostResources from "./PostResources";
import PostHateButton from "./PostHeader/PostHateButton"; import PostHateButton from "./PostHeader/PostHateButton";
import PostSendButton from "./PostHeader/PostSendButton"; import PostSendButton from "./PostHeader/PostSendButton";
import { getCompressedImageUrl } from "@nice/utils";
export default function PostCommentCard({ export default function PostCommentCard({
post, post,
@ -36,7 +37,10 @@ export default function PostCommentCard({
<CustomAvatar <CustomAvatar
src={post.author?.meta?.photoUrl} src={post.author?.meta?.photoUrl}
size={50} size={50}
name={!post.author?.meta?.photoUrl && post.author?.showname} name={
!post.author?.meta?.photoUrl &&
post.author?.showname
}
randomString={ randomString={
post?.meta?.signature || post?.meta?.ip post?.meta?.signature || post?.meta?.ip
}></CustomAvatar> }></CustomAvatar>

View File

@ -3,7 +3,7 @@ import { motion } from "framer-motion";
import { Button, Input, Tabs } from "antd"; import { Button, Input, Tabs } from "antd";
import QuillEditor from "@web/src/components/common/editor/quill/QuillEditor"; import QuillEditor from "@web/src/components/common/editor/quill/QuillEditor";
import { PostDetailContext } from "./context/PostDetailContext"; import { PostDetailContext } from "./context/PostDetailContext";
import { useEntity } from "@nice/client"; import { usePost } from "@nice/client";
import { PostType } from "@nice/common"; import { PostType } from "@nice/common";
import toast from "react-hot-toast"; import toast from "react-hot-toast";
import { isContentEmpty } from "./utils"; import { isContentEmpty } from "./utils";
@ -18,7 +18,8 @@ export default function PostCommentEditor() {
const [content, setContent] = useState(""); const [content, setContent] = useState("");
const [signature, setSignature] = useState<string | undefined>(undefined); const [signature, setSignature] = useState<string | undefined>(undefined);
const [fileIds, setFileIds] = useState<string[]>([]); const [fileIds, setFileIds] = useState<string[]>([]);
const { create } = useEntity("post") const { create } = usePost();
const handleSubmit = async (e: React.FormEvent) => { const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault(); e.preventDefault();
if (isContentEmpty(content)) { if (isContentEmpty(content)) {
@ -98,14 +99,14 @@ export default function PostCommentEditor() {
<div className="flex items-center justify-end gap-2"> <div className="flex items-center justify-end gap-2">
<CustomAvatar randomString={signature}></CustomAvatar> <CustomAvatar randomString={signature}></CustomAvatar>
<Input <Input
maxLength={10} maxLength={15}
style={{ style={{
width: 150, width: 150,
}} }}
onChange={(e) => { onChange={(e) => {
setSignature(e.target.value); setSignature(e.target.value);
}} }}
showCount // showCount
placeholder="签名" placeholder="签名"
/> />
<div> <div>

View File

@ -102,11 +102,11 @@ export function LetterBasicForm() {
<div className="flex gap-2 "> <div className="flex gap-2 ">
<Form.Item name={["meta", "signature"]}> <Form.Item name={["meta", "signature"]}>
<Input <Input
maxLength={10} maxLength={15}
style={{ style={{
width: 150, width: 150,
}} }}
showCount // showCount
placeholder="签名" placeholder="签名"
/> />
</Form.Item> </Form.Item>

View File

@ -1,7 +1,7 @@
import { useState } from "react"; import { useState } from "react";
import * as tus from "tus-js-client"; import * as tus from "tus-js-client";
import { env } from "../env"; import { env } from "../env";
import { getCompressedImageUrl } from "@nice/utils";
// useTusUpload.ts // useTusUpload.ts
interface UploadProgress { interface UploadProgress {
fileId: string; fileId: string;
@ -9,6 +9,7 @@ interface UploadProgress {
} }
interface UploadResult { interface UploadResult {
compressedUrl: string;
url: string; url: string;
fileId: string; fileId: string;
} }
@ -35,7 +36,7 @@ export function useTusUpload() {
throw new Error("Invalid upload URL format"); throw new Error("Invalid upload URL format");
} }
const resUrl = `http://${env.SERVER_IP}/uploads/${parts.slice(uploadIndex + 1, uploadIndex + 6).join("/")}`; const resUrl = `http://${env.SERVER_IP}/uploads/${parts.slice(uploadIndex + 1, uploadIndex + 6).join("/")}`;
console.log(resUrl);
return resUrl; return resUrl;
}; };
const handleFileUpload = async ( const handleFileUpload = async (
@ -84,6 +85,7 @@ export function useTusUpload() {
[fileKey]: 100, [fileKey]: 100,
})); }));
onSuccess({ onSuccess({
compressedUrl: getCompressedImageUrl(url),
url, url,
fileId, fileId,
}); });

View File

@ -29,6 +29,7 @@ export const postDetailSelect: Prisma.PostSelect = {
name: true, name: true,
}, },
}, },
meta: true,
}, },
}, },
receivers: { receivers: {

View File

@ -35,15 +35,16 @@ export type AppLocalSettings = {
important?: number; important?: number;
exploreTime?: Date; exploreTime?: Date;
}; };
export type StaffDto = Staff & { export type StaffMeta = {
domain?: Department;
department?: Department;
meta?: {
photoUrl?: string; photoUrl?: string;
office?: string; office?: string;
email?: string; email?: string;
rank?: string; rank?: string;
}; };
export type StaffDto = Staff & {
domain?: Department;
department?: Department;
meta?: StaffMeta;
}; };
export interface AuthDto { export interface AuthDto {
token: string; token: string;
@ -57,6 +58,7 @@ export type UserProfile = Staff & {
parentDeptIds: string[]; parentDeptIds: string[];
domain: Department; domain: Department;
department: Department; department: Department;
meta?: StaffMeta;
}; };
export interface DataNode { export interface DataNode {
@ -132,11 +134,11 @@ export type PostComment = {
}; };
export interface BaseMetadata { export interface BaseMetadata {
size: number size: number;
filetype: string filetype: string;
filename: string filename: string;
extension: string extension: string;
modifiedAt: Date modifiedAt: Date;
} }
/** /**
* *
@ -159,7 +161,7 @@ export interface VideoMetadata {
duration?: number; duration?: number;
videoCodec?: string; videoCodec?: string;
audioCodec?: string; audioCodec?: string;
coverUrl?: string coverUrl?: string;
} }
/** /**
@ -173,12 +175,14 @@ export interface AudioMetadata {
codec?: string; // 音频编码格式 codec?: string; // 音频编码格式
} }
export type FileMetadata = ImageMetadata &
export type FileMetadata = ImageMetadata & VideoMetadata & AudioMetadata & BaseMetadata VideoMetadata &
AudioMetadata &
BaseMetadata;
export type ResourceDto = Resource & { export type ResourceDto = Resource & {
meta: FileMetadata meta: FileMetadata;
} };
export type PostDto = Post & { export type PostDto = Post & {
readed: boolean; readed: boolean;
liked: boolean; liked: boolean;

View File

@ -11,9 +11,10 @@ export function generateUniqueId(prefix?: string): string {
const randomPart = Math.random().toString(36).substring(2, 8); const randomPart = Math.random().toString(36).substring(2, 8);
// 获取环境特定的额外随机性 // 获取环境特定的额外随机性
const environmentPart = typeof window !== 'undefined' const environmentPart =
typeof window !== "undefined"
? window.crypto.getRandomValues(new Uint32Array(1))[0].toString(36) ? window.crypto.getRandomValues(new Uint32Array(1))[0].toString(36)
: require('crypto').randomBytes(4).toString('hex'); : require("crypto").randomBytes(4).toString("hex");
// 组合所有部分 // 组合所有部分
const uniquePart = `${timestamp}${randomPart}${environmentPart}`; const uniquePart = `${timestamp}${randomPart}${environmentPart}`;
@ -24,13 +25,17 @@ export function generateUniqueId(prefix?: string): string {
export const formatFileSize = (bytes: number) => { export const formatFileSize = (bytes: number) => {
if (bytes < 1024) return `${bytes} B`; if (bytes < 1024) return `${bytes} B`;
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`; if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
if (bytes < 1024 * 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(1)} MB`; if (bytes < 1024 * 1024 * 1024)
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
return `${(bytes / (1024 * 1024 * 1024)).toFixed(2)} GB`; return `${(bytes / (1024 * 1024 * 1024)).toFixed(2)} GB`;
}; };
// 压缩图片路径生成函数 // 压缩图片路径生成函数
export const getCompressedImageUrl = (originalUrl: string): string => { export const getCompressedImageUrl = (originalUrl: string): string => {
const cleanUrl = originalUrl.split(/[?#]/)[0] // 移除查询参数和哈希 if (!originalUrl) {
const lastSlashIndex = cleanUrl.lastIndexOf('/') return originalUrl;
return `${cleanUrl.slice(0, lastSlashIndex)}/compressed/${cleanUrl.slice(lastSlashIndex + 1).replace(/\.[^.]+$/, '.webp')}`
} }
export * from "./types" const cleanUrl = originalUrl.split(/[?#]/)[0]; // 移除查询参数和哈希
const lastSlashIndex = cleanUrl.lastIndexOf("/");
return `${cleanUrl.slice(0, lastSlashIndex)}/compressed/${cleanUrl.slice(lastSlashIndex + 1).replace(/\.[^.]+$/, ".webp")}`;
};
export * from "./types";