feat:
All checks were successful
/ build ushare (push) Successful in 45s
/ clean (push) Successful in 0s

1. local msg/file share by webrtc
fix:
  1. meta clean goroutine walk error
  2. clean interval to args(--clean)
This commit is contained in:
loveuer
2025-05-16 16:48:28 +08:00
parent 7c089bbe84
commit f8372b8de8
30 changed files with 1793 additions and 526 deletions

View File

@@ -0,0 +1,75 @@
import {Bubble, Client} from "./types.ts";
// 生成随机颜色
export const generateColor = () => {
const hue = Math.random() * 360;
return `hsla(${hue},
${Math.random() * 30 + 40}%,
${Math.random() * 10 + 75}%, 0.9)`;
};
// 防碰撞位置生成
export const generateBubbles = (clients: Client[], currentUserId: string): Bubble[] => {
if (!clients) return [];
const BUBBLE_SIZE = 100;
const centerX = window.innerWidth / 2;
const centerY = window.innerHeight / 2;
const bubbles: Bubble[] = [];
let currentRadius = 0;
let angleStep = (2 * Math.PI) / 6; // 初始6个位置
for (let index = 0; index < clients.length; index++) {
let attempt = 0;
let validPosition = false;
if (clients[index].id === currentUserId) {
continue;
}
while (!validPosition && attempt < 100) {
// 螺旋布局算法
const angle = angleStep * (index + attempt);
const radius = currentRadius + (attempt * BUBBLE_SIZE * 0.8);
// 极坐标转笛卡尔坐标
const x = centerX + radius * Math.cos(angle);
const y = centerY + radius * Math.sin(angle);
// 边界检测
const inBounds = x >= 0 && x <= window.innerWidth - BUBBLE_SIZE &&
y >= 0 && y <= window.innerHeight - BUBBLE_SIZE;
// 碰撞检测
const collision = bubbles.some(pos => {
const distance = Math.sqrt(
Math.pow(pos.x - x, 2) +
Math.pow(pos.y - y, 2)
);
return distance < BUBBLE_SIZE * 1.5;
});
if (inBounds && !collision) {
bubbles.push({
id: clients[index].id,
name: clients[index].name,
x: x,
y: y,
color: generateColor(),
radius: 0,
angle: 0
});
// 动态调整布局参数
currentRadius = Math.max(currentRadius, radius);
angleStep = (2 * Math.PI) / Math.max(6, bubbles.length * 0.7);
validPosition = true;
}
attempt++;
}
}
return bubbles;
};

View File

@@ -0,0 +1,163 @@
import React, {useState} from 'react';
import {Dialog} from "../../../component/dialog/dialog.tsx";
import {ReceivedMessage} from "./types.ts";
import {createUseStyles} from "react-jss";
const useStyles = createUseStyles({
root: {
marginBottom: '1rem',
},
sender: {
margin: '0 0 0.5rem 0',
fontSize: '0.9rem',
color: '#666',
},
msgBox: {
background: 'rgba(255,255,255,0.96)',
color: '#222',
padding: '1rem',
borderRadius: '4px',
border: '1px solid #ddd',
maxHeight: '400px',
minHeight: '80px',
overflowY: 'auto',
whiteSpace: 'pre-wrap',
wordBreak: 'break-word',
},
downloadLink: {
color: '#007aff',
textDecoration: 'underline',
},
btnRow: {
display: 'flex',
flexDirection: 'row',
gap: '0.5rem',
justifyContent: 'flex-end',
alignItems: 'center',
marginTop: '8px',
},
copySuccess: {
color: '#28a745',
fontSize: '0.9rem',
marginRight: '0.5rem',
animation: 'fadeIn 0.3s ease-in',
},
copyBtn: {
padding: '8px 16px',
background: '#007aff',
color: 'white',
border: 'none',
borderRadius: '4px',
cursor: 'pointer',
fontSize: '0.9rem',
transition: 'all 0.2s',
'&:hover': {
background: '#0056b3',
},
},
copyBtnSuccess: {
background: '#28a745',
},
closeBtn: {
padding: '8px 16px',
background: '#6c757d',
color: 'white',
border: 'none',
borderRadius: '4px',
cursor: 'pointer',
fontSize: '0.9rem',
transition: 'all 0.2s',
},
progressBar: {
width: '100%',
height: 8,
background: '#eee',
borderRadius: 4,
margin: '12px 0',
overflow: 'hidden',
},
progressInner: {
height: '100%',
background: '#4dabf7',
transition: 'width 0.3s',
},
});
interface MessageDialogProps {
open: boolean;
message: ReceivedMessage | null;
onClose: () => void;
}
export const MessageDialog: React.FC<MessageDialogProps> = ({open, message, onClose}) => {
const [copySuccess, setCopySuccess] = useState(false);
const classes = useStyles();
const handleCopyMessage = () => {
if (message) {
navigator.clipboard.writeText(message.text || '').then(() => {
setCopySuccess(true);
setTimeout(() => setCopySuccess(false), 2000);
}).catch(() => {
alert('复制失败,请手动复制');
});
}
};
return (
<Dialog
open={open}
title="收到新消息"
onClose={onClose}
footer={false}
>
<div className={classes.root}>
<p className={classes.sender}>
: {message?.sender}
</p>
<div className={classes.msgBox}>
{message?.isFile ? (
<>
<div>📎 : {message.fileName} ({message.fileSize ? (message.fileSize/1024).toFixed(1) : ''} KB)</div>
{message.receiving ? (
<>
<div style={{fontSize: '0.95em', color: '#888'}}>... {Math.round((message.progress||0)*100)}%</div>
<div className={classes.progressBar}>
<div className={classes.progressInner} style={{width: `${Math.round((message.progress||0)*100)}%`}} />
</div>
</>
) : (
<a href={message.fileBlobUrl} download={message.fileName} className={classes.downloadLink}>
</a>
)}
</>
) : (
message?.text
)}
</div>
</div>
<div className={classes.btnRow}>
{copySuccess && (
<span className={classes.copySuccess}>
</span>
)}
{!message?.isFile && (
<button
onClick={handleCopyMessage}
className={copySuccess ? `${classes.copyBtn} ${classes.copyBtnSuccess}` : classes.copyBtn}
>
{copySuccess ? '已复制' : '复制消息'}
</button>
)}
<button
onClick={onClose}
className={classes.closeBtn}
>
</button>
</div>
</Dialog>
);
};

View File

@@ -0,0 +1,323 @@
import { WSMessage, ReceivedMessage} from "./types.ts";
import {useLocalStore} from "../../../store/local.ts";
// 文件接收缓存
const fileReceiveCache: Record<string, {chunks: ArrayBuffer[], total: number, received: number, name: string, size: number, sender: string, timestamp: number}> = {};
export const handleFileChunk = (chunk: any, onFileReceived: (msg: import("./types").ReceivedMessage) => void) => {
if (chunk.type === 'file') {
// 文件元信息,初始化缓存
fileReceiveCache[chunk.name + '_' + chunk.timestamp] = {
chunks: new Array(chunk.totalChunks),
total: chunk.totalChunks,
received: 0,
name: chunk.name,
size: chunk.size,
sender: chunk.sender,
timestamp: chunk.timestamp
};
// 首次弹出进度
onFileReceived({
sender: chunk.sender,
timestamp: chunk.timestamp,
fileName: chunk.name,
fileSize: chunk.size,
isFile: true,
progress: 0,
receiving: true
});
} else if (chunk.type === 'file-chunk') {
const key = chunk.name + '_' + chunk.timestamp;
const cache = fileReceiveCache[key];
if (cache) {
// 将 data 数组还原为 ArrayBuffer
const uint8 = new Uint8Array(chunk.data);
cache.chunks[chunk.chunkIndex] = uint8.buffer;
cache.received++;
// 实时回调进度
if (cache.received < cache.total) {
onFileReceived({
sender: cache.sender,
timestamp: cache.timestamp,
fileName: cache.name,
fileSize: cache.size,
isFile: true,
progress: cache.received / cache.total,
receiving: true
});
}
}
} else if (chunk.type === 'file-end') {
const key = chunk.name + '_' + chunk.timestamp;
const cache = fileReceiveCache[key];
if (cache && cache.received === cache.total) {
const blob = new Blob(cache.chunks);
const url = URL.createObjectURL(blob);
onFileReceived({
sender: cache.sender,
timestamp: cache.timestamp,
fileName: cache.name,
fileSize: cache.size,
fileBlobUrl: url,
isFile: true,
progress: 1,
receiving: false
});
delete fileReceiveCache[key];
} else if (cache) {
// 分块未齐全,提示异常
onFileReceived({
sender: cache.sender,
timestamp: cache.timestamp,
fileName: cache.name,
fileSize: cache.size,
isFile: true,
progress: cache.received / cache.total,
receiving: true,
text: '文件分块未齐全,接收失败'
});
}
}
};
export interface RTCHandlerCallbacks {
onChannelOpen: (type: 'sender' | 'receiver') => void;
onMessageReceived: (message: ReceivedMessage) => void;
onChannelClose: () => void;
}
export class RTCHandler {
private rtcRef: React.MutableRefObject<RTCPeerConnection | null>;
private callbacks: RTCHandlerCallbacks;
constructor(rtcRef: React.MutableRefObject<RTCPeerConnection | null>, callbacks: RTCHandlerCallbacks) {
this.rtcRef = rtcRef;
this.callbacks = callbacks;
}
// 更新回调函数的方法
updateCallbacks = (newCallbacks: RTCHandlerCallbacks) => {
this.callbacks = newCallbacks;
};
setupDataChannel = async (ch: RTCDataChannel, type: 'sender' | 'receiver') => {
ch.onopen = () => {
console.log(`[D] 通道已打开!类型: ${type}`);
this.callbacks.onChannelOpen(type);
useLocalStore.getState().setChannel(ch);
};
ch.onmessage = (e) => {
// console.log('[D] Received message:', e.data);
try {
const data = JSON.parse(e.data);
if (data.type === 'message') {
// 处理文本消息
const message: ReceivedMessage = {
text: data.content,
timestamp: Date.now(),
sender: data.sender || '未知用户'
};
this.callbacks.onMessageReceived(message);
} else if (data.type === 'file' || data.type === 'file-chunk' || data.type === 'file-end') {
// 处理文件相关消息
handleFileChunk(data, this.callbacks.onMessageReceived);
}
} catch (error) {
// 如果不是JSON格式当作普通文本处理
const message: ReceivedMessage = {
text: e.data,
timestamp: Date.now(),
sender: '未知用户'
};
this.callbacks.onMessageReceived(message);
}
};
ch.onclose = () => {
console.log('[D] 通道关闭');
this.callbacks.onChannelClose();
useLocalStore.getState().setChannel();
};
};
handleBubbleClick = async (bubbleId: string, currentUserId: string) => {
const current_rtc = this.rtcRef.current;
if (!current_rtc) return;
current_rtc.onnegotiationneeded = async () => {
const offer = await current_rtc.createOffer();
await current_rtc.setLocalDescription(offer);
const data = {
id: bubbleId,
from: currentUserId,
offer: offer,
};
await fetch('/api/ulocal/offer', {
method: 'POST',
headers: {"Content-Type": "application/json"},
body: JSON.stringify(data)
});
};
current_rtc.onicecandidate = async (e) => {
await fetch('/api/ulocal/candidate', {
method: 'POST',
headers: {"Content-Type": "application/json"},
body: JSON.stringify({candidate: e.candidate, id: currentUserId})
});
};
const ch = current_rtc.createDataChannel('local', {ordered: true});
await this.setupDataChannel(ch, 'sender');
};
handleWSEvent = async (e: MessageEvent) => {
let current_id: string;
let current_rtc: RTCPeerConnection | null;
const msg = JSON.parse(e.data) as WSMessage;
// console.log('[D] ws event msg =', msg);
switch (msg.type) {
case "enter":
case "leave":
// 这些事件由父组件处理
return;
case "offer":
const offer_data = msg.data as { id: string; from: string; offer: RTCSessionDescriptionInit };
current_id = useLocalStore.getState().id;
if (offer_data.id !== current_id) {
console.warn(`[W] wrong offer id, want = ${current_id}, got = ${offer_data.id}, data =`, offer_data);
return;
}
current_rtc = this.rtcRef.current;
if (!current_rtc) {
console.warn('[W] rtc undefined');
return;
}
await current_rtc.setRemoteDescription(offer_data.offer);
const answer = await current_rtc.createAnswer();
if (!answer) {
console.log('[W] answer undefined');
return;
}
await current_rtc.setLocalDescription(answer);
current_rtc.ondatachannel = (e) => {
this.setupDataChannel(e.channel, 'receiver');
};
await fetch('/api/ulocal/answer', {
method: 'POST',
headers: {"Content-Type": "application/json"},
body: JSON.stringify({id: offer_data.from, answer: answer})
});
return;
case "answer":
const answer_data = msg.data as { answer: RTCSessionDescriptionInit; id: string };
current_id = useLocalStore.getState().id;
if (answer_data.id !== current_id) {
console.warn(`[W] wrong answer id, want = ${current_id}, got = ${answer_data.id}, data =`, answer_data);
}
current_rtc = this.rtcRef.current;
if (!current_rtc) {
console.warn('[W] rtc undefined');
return;
}
await current_rtc.setRemoteDescription(answer_data.answer);
return;
case "candidate":
const candidate_data = msg.data as { candidate: RTCIceCandidateInit };
current_rtc = this.rtcRef.current;
if (!current_rtc) {
console.warn('[W] rtc undefined');
return;
}
if (!candidate_data.candidate) {
return;
}
await current_rtc.addIceCandidate(candidate_data.candidate);
return;
}
};
sendMessage = (msg: string, files: File[], senderName: string) => {
const ch = useLocalStore.getState().channel;
const CHUNK_SIZE = 64 * 1024; // 64KB
const BUFFERED_AMOUNT_THRESHOLD = 1 * 1024 * 1024; // 1MB
if (ch && ch.readyState === 'open') {
if (msg.trim()) {
// 发送文本消息
const messageData = {
type: 'message',
content: msg,
sender: senderName,
timestamp: Date.now()
};
ch.send(JSON.stringify(messageData));
}
if (files && files.length > 0) {
files.forEach(file => {
const totalChunks = Math.ceil(file.size / CHUNK_SIZE);
const timestamp = Date.now();
// 先发送文件元信息
const fileData = {
type: 'file',
name: file.name,
size: file.size,
sender: senderName,
timestamp,
totalChunks
};
ch.send(JSON.stringify(fileData));
let offset = 0;
let chunkIndex = 0;
const reader = new FileReader();
const sendNextChunk = () => {
if (offset >= file.size) {
// 分块全部发送完毕,发送 file-end
ch.send(JSON.stringify({
type: 'file-end',
name: file.name,
timestamp,
}));
return;
}
if (ch.bufferedAmount > BUFFERED_AMOUNT_THRESHOLD) {
ch.addEventListener('bufferedamountlow', sendNextChunk, { once: true });
return;
}
const slice = file.slice(offset, offset + CHUNK_SIZE);
reader.onload = (e) => {
if (e.target?.result) {
ch.send(JSON.stringify({
type: 'file-chunk',
name: file.name,
timestamp,
chunkIndex,
totalChunks,
data: Array.from(new Uint8Array(e.target.result as ArrayBuffer)),
}));
offset += CHUNK_SIZE;
chunkIndex++;
sendNextChunk();
}
};
reader.readAsArrayBuffer(slice);
};
sendNextChunk();
});
}
}
};
}

View File

@@ -0,0 +1,18 @@
import React from 'react';
import {Dialog} from '../../../component/dialog/dialog.tsx';
import {Sender} from './sender.tsx';
interface SendDialogProps {
open: boolean;
onSend: (msg: string, files: File[]) => void;
onClose: () => void;
name: string;
}
export const SendDialog: React.FC<SendDialogProps> = ({open, onSend, onClose, name}) => {
return (
<Dialog open={open} title={`发送消息给${name}`} onClose={onClose}>
<Sender onSend={onSend} />
</Dialog>
);
};

View File

@@ -0,0 +1,161 @@
import React, {useRef, useState} from 'react';
import {createUseStyles} from "react-jss";
import { message } from '../../../hook/message/u-message.tsx';
const useClass = createUseStyles({
container: {
width: "100%",
minHeight: "260px",
margin: "0",
border: "1px solid #ddd",
borderRadius: "8px",
overflow: "hidden",
position: "relative",
background: "#fff",
boxSizing: "border-box",
padding: "20px 16px 60px 16px"
},
input_box: {
width: "100%",
minHeight: "180px",
padding: "12px",
boxSizing: "border-box",
border: "none",
resize: "vertical",
outline: "none",
fontFamily: "Arial, sans-serif",
fontSize: "1.1rem",
transition: "padding 0.3s ease",
background: "#f8fafd",
borderRadius: "6px"
},
input_has_files: {
paddingTop: '50px',
},
file_list: {
position: "absolute",
top: "0",
left: "0",
right: "0",
padding: "8px 10px",
background: "rgba(255, 255, 255, 0.95)",
borderBottom: "1px solid #eee",
display: "none",
flexWrap: "wrap",
gap: "6px",
maxHeight: "60px",
overflowY: "auto",
},
list_has_files: {
display: 'flex'
},
"@keyframes slideIn": {
from: {transform: "translateY(-10px)", opacity: 0},
to: {transform: "translateY(0)", opacity: 1}
},
file_item: {
display: "flex",
alignItems: "center",
background: "#f0f6ff",
color: '#1661ab',
border: "1px solid #c2d9ff",
borderRadius: "15px",
padding: "4px 12px",
fontSize: "13px",
animation: "$slideIn 0.2s ease"
},
delete_btn: {
width: "16px",
height: "16px",
border: "none",
background: "#ff6b6b",
color: "white",
borderRadius: "50%",
marginLeft: "8px",
cursor: "pointer",
display: "flex",
alignItems: "center",
justifyContent: "center",
fontSize: "12px",
"&:hover": {background: "#ff5252"},
},
buttons: {
position: "absolute",
bottom: "16px",
right: "16px",
display: "flex",
gap: "12px"
},
action_btn: {
padding: "10px 22px",
background: "#4dabf7",
color: "white",
border: "none",
borderRadius: "20px",
cursor: "pointer",
fontSize: "1rem",
transition: "all 0.2s",
"&:hover": {background: "#339af0", transform: "translateY(-1px)"}
},
})
export interface SenderProps {
onSend: (message: string, files: File[]) => void;
}
export const Sender: React.FC<SenderProps> = ({onSend}) => {
const classes = useClass();
const [inputMessage, setInputMessage] = useState('');
const [files, setFiles] = useState<File | null>(null);
const fileInputRef = useRef<HTMLInputElement>(null)
const handleTextInput = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
setInputMessage(e.target.value)
}
const handleFileSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
if (e.target.files) {
setFiles(e.target.files[0]);
} else {
message.warning('未能选择文件');
}
};
const handleSubmit = () => {
if (!(inputMessage.trim() || files)) {
message.warning('请输入内容或选择文件');
return;
}
try {
onSend(inputMessage, files ? [files] : []);
setInputMessage('');
setFiles(null);
} catch (e) {
message.error('发送失败,请重试');
}
};
return (
<div className={classes.container}>
<textarea className={files?`${classes.input_box} ${classes.input_has_files}`:`${classes.input_box}`} placeholder="开始输入..."
onChange={handleTextInput} value={inputMessage}></textarea>
<div className={files? `${classes.file_list} ${classes.list_has_files}` : `${classes.file_list}`}>
{files && <div className={classes.file_item}>
<span>{files.name}</span>
<button className={classes.delete_btn} onClick={() => {
setFiles(null)
}}>×
</button>
</div>}
</div>
<div className={classes.buttons}>
<input type="file" ref={fileInputRef} hidden onChange={handleFileSelect}/>
<button className={classes.action_btn} onClick={() => {
fileInputRef.current && fileInputRef.current.click()
}}>📁
</button>
<button className={classes.action_btn} onClick={handleSubmit}> </button>
</div>
</div>
);
};

View File

@@ -0,0 +1,38 @@
export interface Bubble {
id: string;
name: string;
x: number;
y: number;
color: string;
radius: number;
angle: number;
}
export interface WSMessage {
data: any;
time: number;
type: "register" | "enter" | "leave" | "offer" | "answer" | "candidate"
}
export interface Client {
client_type: 'desktop' | 'mobile' | 'tablet';
app_type: 'web';
ip: number;
name: string;
id: string;
register_at: string;
offer: RTCSessionDescription;
candidate: RTCIceCandidateInit;
}
export interface ReceivedMessage {
text?: string;
timestamp: number;
sender: string;
fileName?: string;
fileSize?: number;
fileBlobUrl?: string;
isFile?: boolean;
progress?: number; // 0-1
receiving?: boolean; // 是否正在接收
}

View File

@@ -0,0 +1,51 @@
import React from 'react';
import {createUseStyles} from "react-jss";
import {Bubble} from "./types.ts";
const useClass = createUseStyles({
bubble: {
position: "absolute",
width: "100px",
height: "100px",
borderRadius: "50%",
display: "flex",
justifyContent: "center",
alignItems: "center",
textAlign: "center",
cursor: "pointer",
fontFamily: "'Microsoft Yahei', sans-serif",
fontSize: "14px",
color: "rgba(255, 255, 255, 0.9)",
textShadow: "1px 1px 3px rgba(0,0,0,0.3)",
transition: "transform 0.3s ease",
transform: 'translate(-50%, -50%)',
animation: 'emerge 0.5s ease-out forwards,float 6s 0.5s ease-in-out infinite',
background: "radial-gradient(circle at 30% 30%,rgba(255, 255, 255, 0.8) 10%,rgba(255, 255, 255, 0.3) 50%,transparent 100%)",
border: "2px solid rgba(255, 255, 255, 0.5)",
boxShadow: "inset 0 -5px 15px rgba(255,255,255,0.3),0 5px 15px rgba(0,0,0,0.1)",
}
});
interface UserBubbleProps {
bubble: Bubble;
onClick: (bubble: Bubble) => void;
}
export const UserBubble: React.FC<UserBubbleProps> = ({bubble, onClick}) => {
const classes = useClass();
return (
<div
className={classes.bubble}
style={{
left: bubble.x,
top: bubble.y,
backgroundColor: bubble.color,
animationDelay: `${Math.random() * 0.5}s, ${0.5 + Math.random() * 2}s`
}}
onClick={() => onClick(bubble)}
>
{bubble.name}
</div>
);
};