mirror of
https://github.com/MatrixSeven/file-transfer-go.git
synced 2026-02-04 03:25:03 +08:00
feat:文件传输优化
This commit is contained in:
90
chuan-next/package-lock.json
generated
90
chuan-next/package-lock.json
generated
@@ -5844,6 +5844,96 @@
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/sindresorhus"
|
||||
}
|
||||
},
|
||||
"node_modules/@next/swc-darwin-arm64": {
|
||||
"version": "15.4.4",
|
||||
"resolved": "https://registry.npmmirror.com/@next/swc-darwin-arm64/-/swc-darwin-arm64-15.4.4.tgz",
|
||||
"integrity": "sha512-eVG55dnGwfUuG+TtnUCt+mEJ+8TGgul6nHEvdb8HEH7dmJIFYOCApAaFrIrxwtEq2Cdf+0m5sG1Np8cNpw9EAw==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"optional": true,
|
||||
"os": [
|
||||
"darwin"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">= 10"
|
||||
}
|
||||
},
|
||||
"node_modules/@next/swc-darwin-x64": {
|
||||
"version": "15.4.4",
|
||||
"resolved": "https://registry.npmmirror.com/@next/swc-darwin-x64/-/swc-darwin-x64-15.4.4.tgz",
|
||||
"integrity": "sha512-zqG+/8apsu49CltEj4NAmCGZvHcZbOOOsNoTVeIXphYWIbE4l6A/vuQHyqll0flU2o3dmYCXsBW5FmbrGDgljQ==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"optional": true,
|
||||
"os": [
|
||||
"darwin"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">= 10"
|
||||
}
|
||||
},
|
||||
"node_modules/@next/swc-linux-arm64-gnu": {
|
||||
"version": "15.4.4",
|
||||
"resolved": "https://registry.npmmirror.com/@next/swc-linux-arm64-gnu/-/swc-linux-arm64-gnu-15.4.4.tgz",
|
||||
"integrity": "sha512-LRD4l2lq4R+2QCHBQVC0wjxxkLlALGJCwigaJ5FSRSqnje+MRKHljQNZgDCaKUZQzO/TXxlmUdkZP/X3KNGZaw==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">= 10"
|
||||
}
|
||||
},
|
||||
"node_modules/@next/swc-linux-arm64-musl": {
|
||||
"version": "15.4.4",
|
||||
"resolved": "https://registry.npmmirror.com/@next/swc-linux-arm64-musl/-/swc-linux-arm64-musl-15.4.4.tgz",
|
||||
"integrity": "sha512-LsGUCTvuZ0690fFWerA4lnQvjkYg9gHo12A3wiPUR4kCxbx/d+SlwmonuTH2SWZI+RVGA9VL3N0S03WTYv6bYg==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">= 10"
|
||||
}
|
||||
},
|
||||
"node_modules/@next/swc-win32-arm64-msvc": {
|
||||
"version": "15.4.4",
|
||||
"resolved": "https://registry.npmmirror.com/@next/swc-win32-arm64-msvc/-/swc-win32-arm64-msvc-15.4.4.tgz",
|
||||
"integrity": "sha512-eEdNW/TXwjYhOulQh0pffTMMItWVwKCQpbziSBmgBNFZIIRn2GTXrhrewevs8wP8KXWYMx8Z+mNU0X+AfvtrRg==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"optional": true,
|
||||
"os": [
|
||||
"win32"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">= 10"
|
||||
}
|
||||
},
|
||||
"node_modules/@next/swc-win32-x64-msvc": {
|
||||
"version": "15.4.4",
|
||||
"resolved": "https://registry.npmmirror.com/@next/swc-win32-x64-msvc/-/swc-win32-x64-msvc-15.4.4.tgz",
|
||||
"integrity": "sha512-SE5pYNbn/xZKMy1RE3pAs+4xD32OI4rY6mzJa4XUkp/ItZY+OMjIgilskmErt8ls/fVJ+Ihopi2QIeW6O3TrMw==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"optional": true,
|
||||
"os": [
|
||||
"win32"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">= 10"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -537,7 +537,19 @@ export default function HomePage() {
|
||||
}
|
||||
}, [pickupCode, updateFileList]);
|
||||
|
||||
// 重置状态
|
||||
// 清空文件列表但保持房间连接
|
||||
const handleClearFiles = useCallback(() => {
|
||||
setSelectedFiles([]);
|
||||
setTransferProgresses([]);
|
||||
setFileTransfers(new Map());
|
||||
// 保持 pickupCode, pickupLink, roomStatus 和 websocket 连接
|
||||
if (pickupCode) {
|
||||
updateFileList([]);
|
||||
showNotification('文件列表已清空,房间保持连接', 'success');
|
||||
}
|
||||
}, [pickupCode, updateFileList, showNotification]);
|
||||
|
||||
// 完全重置状态(关闭房间)
|
||||
const handleReset = useCallback(() => {
|
||||
setSelectedFiles([]);
|
||||
setPickupCode('');
|
||||
@@ -547,7 +559,8 @@ export default function HomePage() {
|
||||
setRoomStatus(null);
|
||||
setFileTransfers(new Map());
|
||||
disconnect();
|
||||
}, [disconnect]);
|
||||
showNotification('已断开连接', 'info');
|
||||
}, [disconnect, showNotification]);
|
||||
|
||||
// 复制到剪贴板
|
||||
const copyToClipboard = useCallback(async (text: string, successMessage: string) => {
|
||||
@@ -628,6 +641,7 @@ export default function HomePage() {
|
||||
input.click();
|
||||
}}
|
||||
onRemoveFile={handleRemoveFile}
|
||||
onClearFiles={handleClearFiles}
|
||||
onReset={handleReset}
|
||||
onJoinRoom={handleJoinRoom}
|
||||
receiverFiles={receiverFiles}
|
||||
@@ -668,14 +682,67 @@ export default function HomePage() {
|
||||
<TabsContent value="text" className="mt-6 animate-fade-in-up">
|
||||
<TextTransfer
|
||||
onSendText={async (text: string) => {
|
||||
// TODO: 实现文字传输功能
|
||||
showNotification('文字传输功能开发中', 'info');
|
||||
return 'ABC123'; // 模拟返回取件码
|
||||
try {
|
||||
const response = await fetch('/api/create-text-room', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({ text }),
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
if (!response.ok) {
|
||||
const errorMessage = data.error || '创建文字传输房间失败';
|
||||
showNotification(errorMessage, 'error');
|
||||
return ''; // 返回空字符串而不是抛出错误
|
||||
}
|
||||
|
||||
showNotification('文字传输房间创建成功!', 'success');
|
||||
return data.code;
|
||||
} catch (error) {
|
||||
console.error('创建文字传输房间失败:', error);
|
||||
showNotification('网络错误,请重试', 'error');
|
||||
return ''; // 返回空字符串而不是抛出错误
|
||||
}
|
||||
}}
|
||||
onReceiveText={async (code: string) => {
|
||||
// TODO: 实现文字接收功能
|
||||
showNotification('文字传输功能开发中', 'info');
|
||||
return '示例文本内容'; // 模拟返回文本
|
||||
try {
|
||||
const response = await fetch('/api/get-text-content', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({ code }),
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
if (!response.ok) {
|
||||
const errorMessage = data.error || '获取文字内容失败';
|
||||
showNotification(errorMessage, 'error');
|
||||
return ''; // 返回空字符串而不是抛出错误
|
||||
}
|
||||
|
||||
return data.text;
|
||||
} catch (error) {
|
||||
console.error('获取文字内容失败:', error);
|
||||
showNotification('网络错误,请重试', 'error');
|
||||
return ''; // 返回空字符串而不是抛出错误
|
||||
}
|
||||
}}
|
||||
websocket={websocket}
|
||||
isConnected={isConnected}
|
||||
currentRole={currentRole}
|
||||
onCreateWebSocket={(code: string, role: 'sender' | 'receiver') => {
|
||||
// 如果已有连接,先关闭
|
||||
if (websocket) {
|
||||
disconnect();
|
||||
}
|
||||
|
||||
// 创建新的WebSocket连接
|
||||
connect(code, role);
|
||||
}}
|
||||
/>
|
||||
</TabsContent>
|
||||
|
||||
43
chuan-next/src/app/api/create-text-room/route.ts
Normal file
43
chuan-next/src/app/api/create-text-room/route.ts
Normal file
@@ -0,0 +1,43 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
try {
|
||||
const { text } = await req.json();
|
||||
|
||||
if (!text || text.trim().length === 0) {
|
||||
return NextResponse.json({ error: '文本内容不能为空' }, { status: 400 });
|
||||
}
|
||||
|
||||
if (text.length > 50000) {
|
||||
return NextResponse.json({ error: '文本内容过长,最大支持50,000字符' }, { status: 400 });
|
||||
}
|
||||
|
||||
// 调用后端API创建文字传输房间
|
||||
const response = await fetch('http://localhost:8080/api/create-text-room', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({ text }),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error('创建文字传输房间失败');
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
code: data.code,
|
||||
message: '文字传输房间创建成功'
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
console.error('创建文字传输房间错误:', error);
|
||||
return NextResponse.json(
|
||||
{ error: '服务器错误,请重试' },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
41
chuan-next/src/app/api/get-text-content/route.ts
Normal file
41
chuan-next/src/app/api/get-text-content/route.ts
Normal file
@@ -0,0 +1,41 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
try {
|
||||
const { code } = await req.json();
|
||||
|
||||
if (!code || code.length !== 6) {
|
||||
return NextResponse.json({ error: '请输入正确的6位房间码' }, { status: 400 });
|
||||
}
|
||||
|
||||
// 调用后端API获取文字内容
|
||||
const response = await fetch(`http://localhost:8080/api/get-text-content/${code}`, {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
if (response.status === 404) {
|
||||
return NextResponse.json({ error: '房间不存在或已过期' }, { status: 404 });
|
||||
}
|
||||
throw new Error('获取文字内容失败');
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
text: data.text,
|
||||
message: '文字内容获取成功'
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
console.error('获取文字内容错误:', error);
|
||||
return NextResponse.json(
|
||||
{ error: '服务器错误,请重试' },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -57,6 +57,50 @@ export function FileReceive({
|
||||
}
|
||||
}, []);
|
||||
|
||||
// 如果已经连接但没有文件,显示等待界面
|
||||
if ((isConnected || isConnecting) && files.length === 0) {
|
||||
return (
|
||||
<div className="glass-card rounded-2xl p-4 sm:p-6 md:p-8 animate-fade-in-up">
|
||||
<div className="text-center">
|
||||
<div className="w-12 h-12 sm:w-16 sm:h-16 mx-auto mb-4 bg-gradient-to-br from-blue-500 to-indigo-500 rounded-2xl flex items-center justify-center animate-float">
|
||||
<Download className="w-6 h-6 sm:w-8 sm:h-8 text-white" />
|
||||
</div>
|
||||
<h2 className="text-xl sm:text-2xl font-semibold text-slate-800 mb-2">等待文件</h2>
|
||||
<p className="text-sm sm:text-base text-slate-600 mb-6">
|
||||
{isConnected ? '已连接到房间,等待发送方选择文件...' : '正在连接到房间...'}
|
||||
</p>
|
||||
|
||||
{/* 连接状态指示器 */}
|
||||
<div className="flex items-center justify-center space-x-4 mb-6">
|
||||
<div className="flex items-center">
|
||||
<div className={`w-3 h-3 rounded-full mr-2 ${isConnected ? 'bg-emerald-500 animate-pulse' : 'bg-orange-500 animate-spin'}`}></div>
|
||||
<span className={`text-sm font-medium ${isConnected ? 'text-emerald-600' : 'text-orange-600'}`}>
|
||||
{isConnected ? '连接已建立' : '连接中...'}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 等待动画 */}
|
||||
<div className="flex justify-center space-x-1 mb-6">
|
||||
{[...Array(3)].map((_, i) => (
|
||||
<div
|
||||
key={i}
|
||||
className="w-2 h-2 bg-blue-500 rounded-full animate-bounce"
|
||||
style={{ animationDelay: `${i * 0.1}s` }}
|
||||
></div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="p-4 bg-gradient-to-r from-blue-50 to-indigo-50 rounded-xl border border-blue-200">
|
||||
<p className="text-xs sm:text-sm text-slate-600 text-center">
|
||||
💡 <span className="font-medium">提示:</span>房间已连接,发送方清空文件列表后您会看到此界面,等待对方重新选择文件
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// 如果已经连接并且有文件列表,显示文件列表
|
||||
if (files.length > 0) {
|
||||
return (
|
||||
|
||||
@@ -19,6 +19,7 @@ interface FileTransferProps {
|
||||
onCopyLink: () => void;
|
||||
onAddMoreFiles: () => void;
|
||||
onRemoveFile: (updatedFiles: File[]) => void;
|
||||
onClearFiles?: () => void;
|
||||
onReset: () => void;
|
||||
|
||||
// 接收方相关
|
||||
@@ -43,6 +44,7 @@ export default function FileTransfer({
|
||||
onCopyLink,
|
||||
onAddMoreFiles,
|
||||
onRemoveFile,
|
||||
onClearFiles,
|
||||
onReset,
|
||||
onJoinRoom,
|
||||
receiverFiles,
|
||||
@@ -111,6 +113,7 @@ export default function FileTransfer({
|
||||
onCopyLink={onCopyLink}
|
||||
onAddMoreFiles={onAddMoreFiles}
|
||||
onRemoveFile={onRemoveFile}
|
||||
onClearFiles={onClearFiles}
|
||||
onReset={onReset}
|
||||
disabled={disabled}
|
||||
/>
|
||||
|
||||
@@ -15,6 +15,7 @@ interface FileUploadProps {
|
||||
onCopyLink?: () => void;
|
||||
onAddMoreFiles?: () => void;
|
||||
onRemoveFile?: (updatedFiles: File[]) => void;
|
||||
onClearFiles?: () => void;
|
||||
onReset?: () => void;
|
||||
disabled?: boolean;
|
||||
}
|
||||
@@ -45,8 +46,9 @@ export default function FileUpload({
|
||||
onCopyLink,
|
||||
onAddMoreFiles,
|
||||
onRemoveFile,
|
||||
onClearFiles,
|
||||
onReset,
|
||||
disabled = false,
|
||||
disabled = false
|
||||
}: FileUploadProps) {
|
||||
const [isDragOver, setIsDragOver] = useState(false);
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
@@ -66,7 +68,6 @@ export default function FileUpload({
|
||||
const handleDrop = useCallback((e: React.DragEvent) => {
|
||||
e.preventDefault();
|
||||
setIsDragOver(false);
|
||||
|
||||
const files = Array.from(e.dataTransfer.files);
|
||||
if (files.length > 0) {
|
||||
onFilesChange([...selectedFiles, ...files]);
|
||||
@@ -81,22 +82,24 @@ export default function FileUpload({
|
||||
}, [selectedFiles, onFilesChange]);
|
||||
|
||||
const removeFile = useCallback((index: number) => {
|
||||
const newFiles = selectedFiles.filter((_, i) => i !== index);
|
||||
onFilesChange(newFiles);
|
||||
// 如果已经生成了取件码,同步删除操作到接收端
|
||||
const updatedFiles = selectedFiles.filter((_, i) => i !== index);
|
||||
onFilesChange(updatedFiles);
|
||||
if (onRemoveFile) {
|
||||
onRemoveFile(newFiles);
|
||||
onRemoveFile(updatedFiles);
|
||||
}
|
||||
}, [selectedFiles, onFilesChange, onRemoveFile]);
|
||||
|
||||
const handleClick = useCallback(() => {
|
||||
fileInputRef.current?.click();
|
||||
if (fileInputRef.current) {
|
||||
fileInputRef.current.click();
|
||||
}
|
||||
}, []);
|
||||
|
||||
if (selectedFiles.length === 0) {
|
||||
// 如果没有选择文件,显示上传区域
|
||||
if (selectedFiles.length === 0 && !pickupCode) {
|
||||
return (
|
||||
<div className="glass-card rounded-2xl p-8 animate-fade-in-up">
|
||||
<div className="text-center mb-6">
|
||||
<div className="space-y-6">
|
||||
<div className="text-center">
|
||||
<div className="w-16 h-16 mx-auto mb-4 bg-gradient-to-br from-blue-500 to-indigo-500 rounded-2xl flex items-center justify-center animate-float">
|
||||
<Upload className="w-8 h-8 text-white" />
|
||||
</div>
|
||||
@@ -220,23 +223,36 @@ export default function FileUpload({
|
||||
)}
|
||||
|
||||
{pickupCode && (
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={onAddMoreFiles}
|
||||
disabled={disabled}
|
||||
className="px-6 py-3 rounded-xl border-slate-300 text-slate-600 hover:bg-slate-50 flex-1"
|
||||
>
|
||||
添加更多文件
|
||||
</Button>
|
||||
<>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={onAddMoreFiles}
|
||||
disabled={disabled}
|
||||
className="px-6 py-3 rounded-xl border-slate-300 text-slate-600 hover:bg-slate-50 flex-1"
|
||||
>
|
||||
添加更多文件
|
||||
</Button>
|
||||
|
||||
{selectedFiles.length > 0 && onClearFiles && (
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={onClearFiles}
|
||||
disabled={disabled}
|
||||
className="px-6 py-3 rounded-xl border-orange-300 text-orange-600 hover:bg-orange-50"
|
||||
>
|
||||
清空文件
|
||||
</Button>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={onReset}
|
||||
disabled={disabled}
|
||||
className="px-6 py-3 rounded-xl border-slate-300 text-slate-600 hover:bg-slate-50"
|
||||
className="px-6 py-3 rounded-xl border-red-300 text-red-600 hover:bg-red-50"
|
||||
>
|
||||
重置
|
||||
关闭房间
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
468
chuan-next/src/components/TextTransfer-new.tsx
Normal file
468
chuan-next/src/components/TextTransfer-new.tsx
Normal file
@@ -0,0 +1,468 @@
|
||||
"use client";
|
||||
|
||||
import React, { useState, useCallback, useEffect, useRef } from 'react';
|
||||
import { useSearchParams, useRouter } from 'next/navigation';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { MessageSquare, Copy, Send, Download, Image, Users } from 'lucide-react';
|
||||
import { useToast } from '@/components/ui/toast-simple';
|
||||
|
||||
interface TextTransferProps {
|
||||
onSendText?: (text: string) => Promise<string>; // 返回取件码
|
||||
onReceiveText?: (code: string) => Promise<string>; // 返回文本内容
|
||||
websocket?: WebSocket | null;
|
||||
isConnected?: boolean;
|
||||
currentRole?: 'sender' | 'receiver';
|
||||
pickupCode?: string;
|
||||
}
|
||||
|
||||
export default function TextTransfer({
|
||||
onSendText,
|
||||
onReceiveText,
|
||||
websocket,
|
||||
isConnected = false,
|
||||
currentRole,
|
||||
pickupCode
|
||||
}: TextTransferProps) {
|
||||
const searchParams = useSearchParams();
|
||||
const router = useRouter();
|
||||
const [mode, setMode] = useState<'send' | 'receive'>('send');
|
||||
const [textContent, setTextContent] = useState('');
|
||||
const [roomCode, setRoomCode] = useState('');
|
||||
const [receivedText, setReceivedText] = useState('');
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [isRoomCreated, setIsRoomCreated] = useState(false);
|
||||
const [connectedUsers, setConnectedUsers] = useState(0);
|
||||
const [images, setImages] = useState<string[]>([]);
|
||||
const { showToast } = useToast();
|
||||
const textareaRef = useRef<HTMLTextAreaElement>(null);
|
||||
const updateTimeoutRef = useRef<NodeJS.Timeout | null>(null);
|
||||
|
||||
// 从URL参数中获取初始模式
|
||||
useEffect(() => {
|
||||
const urlMode = searchParams.get('mode') as 'send' | 'receive';
|
||||
const type = searchParams.get('type');
|
||||
|
||||
if (type === 'text' && urlMode && ['send', 'receive'].includes(urlMode)) {
|
||||
setMode(urlMode);
|
||||
}
|
||||
}, [searchParams]);
|
||||
|
||||
// 监听WebSocket消息
|
||||
useEffect(() => {
|
||||
if (!websocket) return;
|
||||
|
||||
const handleMessage = (event: MessageEvent) => {
|
||||
try {
|
||||
const message = JSON.parse(event.data);
|
||||
console.log('TextTransfer收到消息:', message);
|
||||
|
||||
switch (message.type) {
|
||||
case 'text-update':
|
||||
// 实时更新文字内容
|
||||
if (message.payload?.text !== undefined) {
|
||||
setReceivedText(message.payload.text);
|
||||
if (currentRole === 'receiver') {
|
||||
setTextContent(message.payload.text);
|
||||
}
|
||||
}
|
||||
break;
|
||||
|
||||
case 'text-send':
|
||||
// 接收到发送的文字
|
||||
if (message.payload?.text) {
|
||||
setReceivedText(message.payload.text);
|
||||
showToast('收到新的文字内容!', 'success');
|
||||
}
|
||||
break;
|
||||
|
||||
case 'image-send':
|
||||
// 接收到发送的图片
|
||||
if (message.payload?.imageData) {
|
||||
setImages(prev => [...prev, message.payload.imageData]);
|
||||
showToast('收到新的图片!', 'success');
|
||||
}
|
||||
break;
|
||||
|
||||
case 'room-status':
|
||||
// 更新房间状态
|
||||
if (message.payload?.sender_count !== undefined && message.payload?.receiver_count !== undefined) {
|
||||
setConnectedUsers(message.payload.sender_count + message.payload.receiver_count);
|
||||
}
|
||||
break;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('解析WebSocket消息失败:', error);
|
||||
}
|
||||
};
|
||||
|
||||
websocket.addEventListener('message', handleMessage);
|
||||
return () => websocket.removeEventListener('message', handleMessage);
|
||||
}, [websocket, currentRole, showToast]);
|
||||
|
||||
// 更新URL参数
|
||||
const updateMode = useCallback((newMode: 'send' | 'receive') => {
|
||||
setMode(newMode);
|
||||
const params = new URLSearchParams(searchParams.toString());
|
||||
params.set('type', 'text');
|
||||
params.set('mode', newMode);
|
||||
router.push(`?${params.toString()}`, { scroll: false });
|
||||
}, [searchParams, router]);
|
||||
|
||||
// 发送实时文字更新
|
||||
const sendTextUpdate = useCallback((text: string) => {
|
||||
if (!websocket || !isConnected || !isRoomCreated) return;
|
||||
|
||||
// 清除之前的定时器
|
||||
if (updateTimeoutRef.current) {
|
||||
clearTimeout(updateTimeoutRef.current);
|
||||
}
|
||||
|
||||
// 设置新的定时器,防抖动
|
||||
updateTimeoutRef.current = setTimeout(() => {
|
||||
websocket.send(JSON.stringify({
|
||||
type: 'text-update',
|
||||
payload: { text }
|
||||
}));
|
||||
}, 300); // 300ms防抖
|
||||
}, [websocket, isConnected, isRoomCreated]);
|
||||
|
||||
// 处理文字输入
|
||||
const handleTextChange = useCallback((e: React.ChangeEvent<HTMLTextAreaElement>) => {
|
||||
const newText = e.target.value;
|
||||
setTextContent(newText);
|
||||
|
||||
// 如果是发送方且房间已创建,发送实时更新
|
||||
if (currentRole === 'sender' && isRoomCreated) {
|
||||
sendTextUpdate(newText);
|
||||
}
|
||||
}, [currentRole, isRoomCreated, sendTextUpdate]);
|
||||
|
||||
// 创建文字传输房间
|
||||
const handleCreateRoom = useCallback(async () => {
|
||||
if (!textContent.trim()) {
|
||||
showToast('请输入要传输的文字内容', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
setIsLoading(true);
|
||||
try {
|
||||
if (onSendText) {
|
||||
const code = await onSendText(textContent);
|
||||
setRoomCode(code);
|
||||
setIsRoomCreated(true);
|
||||
showToast('房间创建成功!', 'success');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('创建房间失败:', error);
|
||||
showToast('创建房间失败,请重试', 'error');
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, [textContent, onSendText, showToast]);
|
||||
|
||||
// 加入房间
|
||||
const handleJoinRoom = useCallback(async () => {
|
||||
if (!roomCode.trim() || roomCode.length !== 6) {
|
||||
showToast('请输入正确的6位房间码', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
setIsLoading(true);
|
||||
try {
|
||||
if (onReceiveText) {
|
||||
const text = await onReceiveText(roomCode);
|
||||
setReceivedText(text);
|
||||
showToast('成功加入房间!', 'success');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('加入房间失败:', error);
|
||||
showToast('加入房间失败,请检查房间码', 'error');
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, [roomCode, onReceiveText, showToast]);
|
||||
|
||||
// 发送文字
|
||||
const handleSendText = useCallback(() => {
|
||||
if (!websocket || !isConnected || !textContent.trim()) return;
|
||||
|
||||
websocket.send(JSON.stringify({
|
||||
type: 'text-send',
|
||||
payload: { text: textContent }
|
||||
}));
|
||||
|
||||
showToast('文字已发送!', 'success');
|
||||
}, [websocket, isConnected, textContent, showToast]);
|
||||
|
||||
// 处理图片粘贴
|
||||
const handlePaste = useCallback((e: React.ClipboardEvent) => {
|
||||
const items = e.clipboardData?.items;
|
||||
if (!items) return;
|
||||
|
||||
for (let i = 0; i < items.length; i++) {
|
||||
const item = items[i];
|
||||
if (item.type.indexOf('image') !== -1) {
|
||||
const file = item.getAsFile();
|
||||
if (file) {
|
||||
const reader = new FileReader();
|
||||
reader.onload = (event) => {
|
||||
const imageData = event.target?.result as string;
|
||||
setImages(prev => [...prev, imageData]);
|
||||
|
||||
// 发送图片给其他用户
|
||||
if (websocket && isConnected) {
|
||||
websocket.send(JSON.stringify({
|
||||
type: 'image-send',
|
||||
payload: { imageData }
|
||||
}));
|
||||
showToast('图片已发送!', 'success');
|
||||
}
|
||||
};
|
||||
reader.readAsDataURL(file);
|
||||
}
|
||||
}
|
||||
}
|
||||
}, [websocket, isConnected, showToast]);
|
||||
|
||||
const copyToClipboard = useCallback(async (text: string) => {
|
||||
try {
|
||||
await navigator.clipboard.writeText(text);
|
||||
showToast('已复制到剪贴板!', 'success');
|
||||
} catch (err) {
|
||||
showToast('复制失败', 'error');
|
||||
}
|
||||
}, [showToast]);
|
||||
|
||||
return (
|
||||
<div className="space-y-4 sm:space-y-6">
|
||||
{/* 模式切换 */}
|
||||
<div className="flex justify-center mb-6">
|
||||
<div className="bg-white/80 backdrop-blur-sm rounded-xl p-1 shadow-lg">
|
||||
<Button
|
||||
variant={mode === 'send' ? 'default' : 'ghost'}
|
||||
onClick={() => updateMode('send')}
|
||||
className="px-6 py-2 rounded-lg"
|
||||
>
|
||||
<Send className="w-4 h-4 mr-2" />
|
||||
发送文字
|
||||
</Button>
|
||||
<Button
|
||||
variant={mode === 'receive' ? 'default' : 'ghost'}
|
||||
onClick={() => updateMode('receive')}
|
||||
className="px-6 py-2 rounded-lg"
|
||||
>
|
||||
<Download className="w-4 h-4 mr-2" />
|
||||
接收文字
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{mode === 'send' ? (
|
||||
<div className="glass-card rounded-2xl p-4 sm:p-6 animate-fade-in-up">
|
||||
<div className="text-center mb-6">
|
||||
<div className="w-12 h-12 sm:w-16 sm:h-16 mx-auto mb-4 bg-gradient-to-br from-blue-500 to-indigo-500 rounded-2xl flex items-center justify-center animate-float">
|
||||
<MessageSquare className="w-6 h-6 sm:w-8 sm:h-8 text-white" />
|
||||
</div>
|
||||
<h2 className="text-xl sm:text-2xl font-semibold text-slate-800 mb-2">传送文字</h2>
|
||||
<p className="text-sm sm:text-base text-slate-600">
|
||||
{isRoomCreated ? '实时编辑,对方可以同步看到' : '输入要传输的文本内容'}
|
||||
</p>
|
||||
{connectedUsers > 1 && (
|
||||
<div className="flex items-center justify-center mt-2 text-sm text-emerald-600">
|
||||
<Users className="w-4 h-4 mr-1" />
|
||||
{connectedUsers} 人在线
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="space-y-4">
|
||||
<div className="relative">
|
||||
<textarea
|
||||
ref={textareaRef}
|
||||
value={textContent}
|
||||
onChange={handleTextChange}
|
||||
onPaste={handlePaste}
|
||||
placeholder="在这里输入要传输的文本内容... 💡 提示: • 支持实时同步编辑 • 可以直接粘贴图片 (Ctrl+V)"
|
||||
className="w-full min-h-[300px] p-4 border-2 border-slate-200 rounded-xl focus:border-blue-500 focus:ring-blue-500 bg-white/80 backdrop-blur-sm resize-none"
|
||||
disabled={isLoading}
|
||||
/>
|
||||
{isRoomCreated && (
|
||||
<div className="absolute top-2 right-2">
|
||||
<div className="flex items-center space-x-1 bg-emerald-100 text-emerald-700 px-2 py-1 rounded-lg text-xs">
|
||||
<div className="w-2 h-2 bg-emerald-500 rounded-full animate-pulse"></div>
|
||||
<span>实时同步</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex justify-between text-sm text-slate-500">
|
||||
<span>{textContent.length} 字符</span>
|
||||
<span>最大 50,000 字符</span>
|
||||
</div>
|
||||
|
||||
{!isRoomCreated ? (
|
||||
<Button
|
||||
onClick={handleCreateRoom}
|
||||
disabled={!textContent.trim() || textContent.length > 50000 || isLoading}
|
||||
className="w-full h-12 bg-gradient-to-r from-blue-500 to-indigo-500 hover:from-blue-600 hover:to-indigo-600 text-white text-lg font-medium rounded-xl shadow-lg"
|
||||
>
|
||||
{isLoading ? (
|
||||
<>
|
||||
<div className="animate-spin rounded-full h-5 w-5 border-b-2 border-white mr-2"></div>
|
||||
创建房间...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Send className="w-5 h-5 mr-2" />
|
||||
创建文字传输房间
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
) : (
|
||||
<div className="space-y-4">
|
||||
<div className="p-4 bg-gradient-to-r from-emerald-50 to-teal-50 rounded-xl border border-emerald-200">
|
||||
<div className="text-center">
|
||||
<p className="text-sm text-emerald-700 mb-2">房间码</p>
|
||||
<div className="text-2xl font-bold font-mono text-emerald-600 mb-3">{roomCode}</div>
|
||||
<Button
|
||||
onClick={() => copyToClipboard(roomCode)}
|
||||
size="sm"
|
||||
className="bg-emerald-500 hover:bg-emerald-600 text-white mr-2"
|
||||
>
|
||||
<Copy className="w-4 h-4 mr-2" />
|
||||
复制房间码
|
||||
</Button>
|
||||
<Button
|
||||
onClick={handleSendText}
|
||||
size="sm"
|
||||
className="bg-blue-500 hover:bg-blue-600 text-white"
|
||||
disabled={!textContent.trim()}
|
||||
>
|
||||
<Send className="w-4 h-4 mr-2" />
|
||||
发送文字
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 图片展示区域 */}
|
||||
{images.length > 0 && (
|
||||
<div className="mt-6">
|
||||
<h3 className="text-lg font-medium text-slate-800 mb-3 flex items-center">
|
||||
<Image className="w-5 h-5 mr-2" />
|
||||
已发送的图片 ({images.length})
|
||||
</h3>
|
||||
<div className="grid grid-cols-2 sm:grid-cols-3 gap-3">
|
||||
{images.map((img, index) => (
|
||||
<div key={index} className="relative group">
|
||||
<img
|
||||
src={img}
|
||||
alt={`图片 ${index + 1}`}
|
||||
className="w-full h-24 object-cover rounded-lg border-2 border-slate-200 hover:border-blue-400 transition-colors cursor-pointer"
|
||||
onClick={() => window.open(img, '_blank')}
|
||||
/>
|
||||
<div className="absolute inset-0 bg-black bg-opacity-0 group-hover:bg-opacity-20 transition-opacity rounded-lg"></div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="glass-card rounded-2xl p-4 sm:p-6 animate-fade-in-up">
|
||||
<div className="text-center mb-6">
|
||||
<div className="w-12 h-12 sm:w-16 sm:h-16 mx-auto mb-4 bg-gradient-to-br from-emerald-500 to-teal-500 rounded-2xl flex items-center justify-center animate-float">
|
||||
<Download className="w-6 h-6 sm:w-8 sm:h-8 text-white" />
|
||||
</div>
|
||||
<h2 className="text-xl sm:text-2xl font-semibold text-slate-800 mb-2">接收文字</h2>
|
||||
<p className="text-sm sm:text-base text-slate-600">输入6位房间码来获取文字内容</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-4">
|
||||
<Input
|
||||
value={roomCode}
|
||||
onChange={(e) => setRoomCode(e.target.value.toUpperCase().slice(0, 6))}
|
||||
placeholder="请输入房间码"
|
||||
className="text-center text-2xl sm:text-3xl tracking-[0.3em] sm:tracking-[0.5em] font-mono h-12 sm:h-16 border-2 border-slate-200 rounded-xl focus:border-emerald-500 focus:ring-emerald-500 bg-white/80 backdrop-blur-sm"
|
||||
maxLength={6}
|
||||
disabled={isLoading}
|
||||
/>
|
||||
|
||||
<Button
|
||||
onClick={handleJoinRoom}
|
||||
disabled={roomCode.length !== 6 || isLoading}
|
||||
className="w-full h-12 bg-gradient-to-r from-emerald-500 to-teal-500 hover:from-emerald-600 hover:to-teal-600 text-white text-lg font-medium rounded-xl shadow-lg"
|
||||
>
|
||||
{isLoading ? (
|
||||
<>
|
||||
<div className="animate-spin rounded-full h-5 w-5 border-b-2 border-white mr-2"></div>
|
||||
连接中...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Download className="w-5 h-5 mr-2" />
|
||||
获取文字
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
|
||||
{(receivedText || textContent) && (
|
||||
<div className="mt-6 space-y-4">
|
||||
<div className="relative">
|
||||
<textarea
|
||||
value={receivedText || textContent}
|
||||
readOnly={currentRole !== 'receiver'}
|
||||
onChange={currentRole === 'receiver' ? handleTextChange : undefined}
|
||||
className="w-full min-h-[300px] p-4 border-2 border-emerald-200 rounded-xl bg-emerald-50/50 backdrop-blur-sm resize-none"
|
||||
/>
|
||||
{currentRole === 'receiver' && isConnected && (
|
||||
<div className="absolute top-2 right-2">
|
||||
<div className="flex items-center space-x-1 bg-emerald-100 text-emerald-700 px-2 py-1 rounded-lg text-xs">
|
||||
<div className="w-2 h-2 bg-emerald-500 rounded-full animate-pulse"></div>
|
||||
<span>实时同步</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<Button
|
||||
onClick={() => copyToClipboard(receivedText || textContent)}
|
||||
className="w-full h-12 bg-gradient-to-r from-emerald-500 to-teal-500 hover:from-emerald-600 hover:to-teal-600 text-white text-lg font-medium rounded-xl shadow-lg"
|
||||
>
|
||||
<Copy className="w-5 h-5 mr-2" />
|
||||
复制文字
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 接收到的图片展示 */}
|
||||
{images.length > 0 && (
|
||||
<div className="mt-6">
|
||||
<h3 className="text-lg font-medium text-slate-800 mb-3 flex items-center">
|
||||
<Image className="w-5 h-5 mr-2" />
|
||||
接收到的图片 ({images.length})
|
||||
</h3>
|
||||
<div className="grid grid-cols-2 sm:grid-cols-3 gap-3">
|
||||
{images.map((img, index) => (
|
||||
<div key={index} className="relative group">
|
||||
<img
|
||||
src={img}
|
||||
alt={`图片 ${index + 1}`}
|
||||
className="w-full h-24 object-cover rounded-lg border-2 border-slate-200 hover:border-emerald-400 transition-colors cursor-pointer"
|
||||
onClick={() => window.open(img, '_blank')}
|
||||
/>
|
||||
<div className="absolute inset-0 bg-black bg-opacity-0 group-hover:bg-opacity-20 transition-opacity rounded-lg"></div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,37 +1,145 @@
|
||||
"use client";
|
||||
|
||||
import React, { useState, useCallback, useEffect } from 'react';
|
||||
import React, { useState, useCallback, useEffect, useRef } from 'react';
|
||||
import { useSearchParams, useRouter } from 'next/navigation';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { MessageSquare, Copy, Send, Download } from 'lucide-react';
|
||||
import { MessageSquare, Copy, Send, Download, Image, Users, Link } from 'lucide-react';
|
||||
import { useToast } from '@/components/ui/toast-simple';
|
||||
|
||||
interface TextTransferProps {
|
||||
onSendText?: (text: string) => Promise<string>; // 返回取件码
|
||||
onReceiveText?: (code: string) => Promise<string>; // 返回文本内容
|
||||
websocket?: WebSocket | null;
|
||||
isConnected?: boolean;
|
||||
currentRole?: 'sender' | 'receiver';
|
||||
pickupCode?: string;
|
||||
onCreateWebSocket?: (code: string, role: 'sender' | 'receiver') => void; // 创建WebSocket连接
|
||||
}
|
||||
|
||||
export default function TextTransfer({ onSendText, onReceiveText }: TextTransferProps) {
|
||||
export default function TextTransfer({
|
||||
onSendText,
|
||||
onReceiveText,
|
||||
websocket,
|
||||
isConnected = false,
|
||||
currentRole,
|
||||
pickupCode,
|
||||
onCreateWebSocket
|
||||
}: TextTransferProps) {
|
||||
const searchParams = useSearchParams();
|
||||
const router = useRouter();
|
||||
const [mode, setMode] = useState<'send' | 'receive'>('send');
|
||||
const [textContent, setTextContent] = useState('');
|
||||
const [pickupCode, setPickupCode] = useState('');
|
||||
const [roomCode, setRoomCode] = useState('');
|
||||
const [receivedText, setReceivedText] = useState('');
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [isRoomCreated, setIsRoomCreated] = useState(false);
|
||||
const [connectedUsers, setConnectedUsers] = useState(0);
|
||||
const [images, setImages] = useState<string[]>([]);
|
||||
const { showToast } = useToast();
|
||||
const textareaRef = useRef<HTMLTextAreaElement>(null);
|
||||
const updateTimeoutRef = useRef<NodeJS.Timeout | null>(null);
|
||||
|
||||
// 从URL参数中获取初始模式
|
||||
// 从URL参数中获取初始模式和房间码
|
||||
useEffect(() => {
|
||||
const urlMode = searchParams.get('mode') as 'send' | 'receive';
|
||||
const type = searchParams.get('type');
|
||||
const urlCode = searchParams.get('code');
|
||||
|
||||
if (type === 'text' && urlMode && ['send', 'receive'].includes(urlMode)) {
|
||||
setMode(urlMode);
|
||||
|
||||
// 如果URL中有房间码且是接收模式,自动填入房间码
|
||||
if (urlMode === 'receive' && urlCode && urlCode.length === 6) {
|
||||
setRoomCode(urlCode.toUpperCase());
|
||||
// 自动尝试加入房间
|
||||
setTimeout(() => {
|
||||
if (onReceiveText) {
|
||||
handleJoinRoomWithCode(urlCode.toUpperCase());
|
||||
}
|
||||
}, 500); // 延迟500ms确保组件完全初始化
|
||||
}
|
||||
}
|
||||
}, [searchParams]);
|
||||
|
||||
// 处理通过URL参数自动加入房间
|
||||
const handleJoinRoomWithCode = useCallback(async (code: string) => {
|
||||
if (!code || code.length !== 6) return;
|
||||
|
||||
setIsLoading(true);
|
||||
try {
|
||||
if (onReceiveText) {
|
||||
const text = await onReceiveText(code);
|
||||
if (text) {
|
||||
setReceivedText(text);
|
||||
showToast('自动加入房间成功!', 'success');
|
||||
|
||||
// 创建WebSocket连接用于实时同步
|
||||
if (onCreateWebSocket) {
|
||||
onCreateWebSocket(code, 'receiver');
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('自动加入房间失败:', error);
|
||||
// 错误信息已经在HomePage中处理了
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, [onReceiveText, onCreateWebSocket, showToast]);
|
||||
|
||||
// 监听WebSocket消息
|
||||
useEffect(() => {
|
||||
if (!websocket) return;
|
||||
|
||||
const handleMessage = (event: MessageEvent) => {
|
||||
try {
|
||||
const message = JSON.parse(event.data);
|
||||
console.log('TextTransfer收到消息:', message);
|
||||
|
||||
switch (message.type) {
|
||||
case 'text-update':
|
||||
// 实时更新文字内容
|
||||
if (message.payload?.text !== undefined) {
|
||||
setReceivedText(message.payload.text);
|
||||
if (currentRole === 'receiver') {
|
||||
setTextContent(message.payload.text);
|
||||
}
|
||||
}
|
||||
break;
|
||||
|
||||
case 'text-send':
|
||||
// 接收到发送的文字
|
||||
if (message.payload?.text) {
|
||||
setReceivedText(message.payload.text);
|
||||
showToast('收到新的文字内容!', 'success');
|
||||
}
|
||||
break;
|
||||
|
||||
case 'image-send':
|
||||
// 接收到发送的图片
|
||||
if (message.payload?.imageData) {
|
||||
setImages(prev => [...prev, message.payload.imageData]);
|
||||
showToast('收到新的图片!', 'success');
|
||||
}
|
||||
break;
|
||||
|
||||
case 'room-status':
|
||||
// 更新房间状态
|
||||
if (message.payload?.sender_count !== undefined && message.payload?.receiver_count !== undefined) {
|
||||
setConnectedUsers(message.payload.sender_count + message.payload.receiver_count);
|
||||
}
|
||||
break;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('解析WebSocket消息失败:', error);
|
||||
}
|
||||
};
|
||||
|
||||
websocket.addEventListener('message', handleMessage);
|
||||
return () => websocket.removeEventListener('message', handleMessage);
|
||||
}, [websocket, currentRole, showToast]);
|
||||
|
||||
// 更新URL参数
|
||||
const updateMode = useCallback((newMode: 'send' | 'receive') => {
|
||||
setMode(newMode);
|
||||
@@ -41,37 +149,135 @@ export default function TextTransfer({ onSendText, onReceiveText }: TextTransfer
|
||||
router.push(`?${params.toString()}`, { scroll: false });
|
||||
}, [searchParams, router]);
|
||||
|
||||
const handleSendText = useCallback(async () => {
|
||||
if (!textContent.trim() || !onSendText) return;
|
||||
|
||||
setIsLoading(true);
|
||||
try {
|
||||
const code = await onSendText(textContent);
|
||||
setPickupCode(code);
|
||||
showToast('文本已生成取件码!', 'success');
|
||||
} catch (error) {
|
||||
console.error('发送文本失败:', error);
|
||||
showToast('发送失败,请重试', 'error');
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, [textContent, onSendText, showToast]);
|
||||
// 发送实时文字更新
|
||||
const sendTextUpdate = useCallback((text: string) => {
|
||||
if (!websocket || !isConnected || !isRoomCreated) return;
|
||||
|
||||
const handleReceiveText = useCallback(async () => {
|
||||
if (!pickupCode.trim() || !onReceiveText) return;
|
||||
// 清除之前的定时器
|
||||
if (updateTimeoutRef.current) {
|
||||
clearTimeout(updateTimeoutRef.current);
|
||||
}
|
||||
|
||||
// 设置新的定时器,防抖动
|
||||
updateTimeoutRef.current = setTimeout(() => {
|
||||
websocket.send(JSON.stringify({
|
||||
type: 'text-update',
|
||||
payload: { text }
|
||||
}));
|
||||
}, 300); // 300ms防抖
|
||||
}, [websocket, isConnected, isRoomCreated]);
|
||||
|
||||
// 处理文字输入
|
||||
const handleTextChange = useCallback((e: React.ChangeEvent<HTMLTextAreaElement>) => {
|
||||
const newText = e.target.value;
|
||||
setTextContent(newText);
|
||||
|
||||
// 如果是发送方且房间已创建,发送实时更新
|
||||
if (currentRole === 'sender' && isRoomCreated) {
|
||||
sendTextUpdate(newText);
|
||||
}
|
||||
}, [currentRole, isRoomCreated, sendTextUpdate]);
|
||||
|
||||
// 创建文字传输房间
|
||||
const handleCreateRoom = useCallback(async () => {
|
||||
if (!textContent.trim()) {
|
||||
showToast('请输入要传输的文字内容', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
setIsLoading(true);
|
||||
try {
|
||||
const text = await onReceiveText(pickupCode);
|
||||
setReceivedText(text);
|
||||
showToast('文本接收成功!', 'success');
|
||||
if (onSendText) {
|
||||
const code = await onSendText(textContent);
|
||||
if (code) { // 只有在成功创建房间时才设置状态和显示成功消息
|
||||
setRoomCode(code);
|
||||
setIsRoomCreated(true);
|
||||
showToast('房间创建成功!', 'success');
|
||||
|
||||
// 创建WebSocket连接用于实时同步
|
||||
if (onCreateWebSocket) {
|
||||
onCreateWebSocket(code, 'sender');
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('接收文本失败:', error);
|
||||
showToast('接收失败,请检查取件码', 'error');
|
||||
console.error('创建房间失败:', error);
|
||||
// 错误信息已经在HomePage中处理了,这里不再重复显示
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, [pickupCode, onReceiveText, showToast]);
|
||||
}, [textContent, onSendText, onCreateWebSocket, showToast]);
|
||||
|
||||
// 加入房间
|
||||
const handleJoinRoom = useCallback(async () => {
|
||||
if (!roomCode.trim() || roomCode.length !== 6) {
|
||||
showToast('请输入正确的6位房间码', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
setIsLoading(true);
|
||||
try {
|
||||
if (onReceiveText) {
|
||||
const text = await onReceiveText(roomCode);
|
||||
if (text) { // 只有在成功获取到文字时才设置状态和显示成功消息
|
||||
setReceivedText(text);
|
||||
showToast('成功加入房间!', 'success');
|
||||
|
||||
// 创建WebSocket连接用于实时同步
|
||||
if (onCreateWebSocket) {
|
||||
onCreateWebSocket(roomCode, 'receiver');
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('加入房间失败:', error);
|
||||
// 错误信息已经在HomePage中处理了,这里不再重复显示
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, [roomCode, onReceiveText, onCreateWebSocket, showToast]);
|
||||
|
||||
// 发送文字
|
||||
const handleSendText = useCallback(() => {
|
||||
if (!websocket || !isConnected || !textContent.trim()) return;
|
||||
|
||||
websocket.send(JSON.stringify({
|
||||
type: 'text-send',
|
||||
payload: { text: textContent }
|
||||
}));
|
||||
|
||||
showToast('文字已发送!', 'success');
|
||||
}, [websocket, isConnected, textContent, showToast]);
|
||||
|
||||
// 处理图片粘贴
|
||||
const handlePaste = useCallback((e: React.ClipboardEvent) => {
|
||||
const items = e.clipboardData?.items;
|
||||
if (!items) return;
|
||||
|
||||
for (let i = 0; i < items.length; i++) {
|
||||
const item = items[i];
|
||||
if (item.type.indexOf('image') !== -1) {
|
||||
const file = item.getAsFile();
|
||||
if (file) {
|
||||
const reader = new FileReader();
|
||||
reader.onload = (event) => {
|
||||
const imageData = event.target?.result as string;
|
||||
setImages(prev => [...prev, imageData]);
|
||||
|
||||
// 发送图片给其他用户
|
||||
if (websocket && isConnected) {
|
||||
websocket.send(JSON.stringify({
|
||||
type: 'image-send',
|
||||
payload: { imageData }
|
||||
}));
|
||||
showToast('图片已发送!', 'success');
|
||||
}
|
||||
};
|
||||
reader.readAsDataURL(file);
|
||||
}
|
||||
}
|
||||
}
|
||||
}, [websocket, isConnected, showToast]);
|
||||
|
||||
const copyToClipboard = useCallback(async (text: string) => {
|
||||
try {
|
||||
@@ -82,6 +288,13 @@ export default function TextTransfer({ onSendText, onReceiveText }: TextTransfer
|
||||
}
|
||||
}, [showToast]);
|
||||
|
||||
// 复制传输链接
|
||||
const copyTransferLink = useCallback(async (code: string) => {
|
||||
const currentUrl = window.location.origin + window.location.pathname;
|
||||
const transferLink = `${currentUrl}?type=text&mode=receive&code=${code}`;
|
||||
await copyToClipboard(transferLink);
|
||||
}, [copyToClipboard]);
|
||||
|
||||
return (
|
||||
<div className="space-y-4 sm:space-y-6">
|
||||
{/* 模式切换 */}
|
||||
@@ -93,7 +306,7 @@ export default function TextTransfer({ onSendText, onReceiveText }: TextTransfer
|
||||
className="px-6 py-2 rounded-lg"
|
||||
>
|
||||
<Send className="w-4 h-4 mr-2" />
|
||||
发送文本
|
||||
发送文字
|
||||
</Button>
|
||||
<Button
|
||||
variant={mode === 'receive' ? 'default' : 'ghost'}
|
||||
@@ -101,7 +314,7 @@ export default function TextTransfer({ onSendText, onReceiveText }: TextTransfer
|
||||
className="px-6 py-2 rounded-lg"
|
||||
>
|
||||
<Download className="w-4 h-4 mr-2" />
|
||||
接收文本
|
||||
接收文字
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -113,54 +326,139 @@ export default function TextTransfer({ onSendText, onReceiveText }: TextTransfer
|
||||
<MessageSquare className="w-6 h-6 sm:w-8 sm:h-8 text-white" />
|
||||
</div>
|
||||
<h2 className="text-xl sm:text-2xl font-semibold text-slate-800 mb-2">传送文字</h2>
|
||||
<p className="text-sm sm:text-base text-slate-600">输入要传输的文本内容</p>
|
||||
<p className="text-sm sm:text-base text-slate-600">
|
||||
{isRoomCreated ? '实时编辑,对方可以同步看到' : '输入要传输的文本内容'}
|
||||
</p>
|
||||
{/* 连接状态显示 */}
|
||||
<div className="mt-2 space-y-1">
|
||||
{isRoomCreated && (
|
||||
<div className="flex items-center justify-center space-x-4 text-sm">
|
||||
<div className="flex items-center">
|
||||
<div className={`w-2 h-2 rounded-full mr-2 ${isConnected ? 'bg-emerald-500 animate-pulse' : 'bg-red-500'}`}></div>
|
||||
<span className={isConnected ? 'text-emerald-600' : 'text-red-600'}>
|
||||
{isConnected ? '实时连接已建立' : '连接断开'}
|
||||
</span>
|
||||
</div>
|
||||
{connectedUsers > 0 && (
|
||||
<div className="flex items-center text-blue-600">
|
||||
<Users className="w-4 h-4 mr-1" />
|
||||
{connectedUsers} 人在线
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-4">
|
||||
<textarea
|
||||
value={textContent}
|
||||
onChange={(e) => setTextContent(e.target.value)}
|
||||
placeholder="在这里输入要传输的文本内容..."
|
||||
className="w-full min-h-[200px] p-4 border-2 border-slate-200 rounded-xl focus:border-blue-500 focus:ring-blue-500 bg-white/80 backdrop-blur-sm resize-none"
|
||||
disabled={isLoading}
|
||||
/>
|
||||
<div className="relative">
|
||||
<textarea
|
||||
ref={textareaRef}
|
||||
value={textContent}
|
||||
onChange={handleTextChange}
|
||||
onPaste={handlePaste}
|
||||
placeholder="在这里输入要传输的文本内容... 💡 提示:支持实时同步编辑,可以直接粘贴图片 (Ctrl+V)"
|
||||
className="w-full min-h-[150px] p-4 border-2 border-slate-200 rounded-xl focus:border-blue-500 focus:ring-blue-500 bg-white/80 backdrop-blur-sm resize-none"
|
||||
disabled={isLoading}
|
||||
/>
|
||||
{isRoomCreated && isConnected && (
|
||||
<div className="absolute top-2 right-2">
|
||||
<div className="flex items-center space-x-1 bg-emerald-100 text-emerald-700 px-2 py-1 rounded-lg text-xs">
|
||||
<div className="w-2 h-2 bg-emerald-500 rounded-full animate-pulse"></div>
|
||||
<span>实时同步</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{isRoomCreated && !isConnected && (
|
||||
<div className="absolute top-2 right-2">
|
||||
<div className="flex items-center space-x-1 bg-orange-100 text-orange-700 px-2 py-1 rounded-lg text-xs">
|
||||
<div className="w-2 h-2 bg-orange-500 rounded-full"></div>
|
||||
<span>连接中...</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex justify-between text-sm text-slate-500">
|
||||
<span>{textContent.length} 字符</span>
|
||||
<span>最大 10,000 字符</span>
|
||||
<span>最大 50,000 字符</span>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
onClick={handleSendText}
|
||||
disabled={!textContent.trim() || textContent.length > 10000 || isLoading}
|
||||
className="w-full h-12 bg-gradient-to-r from-blue-500 to-indigo-500 hover:from-blue-600 hover:to-indigo-600 text-white text-lg font-medium rounded-xl shadow-lg"
|
||||
>
|
||||
{isLoading ? (
|
||||
<>
|
||||
<div className="animate-spin rounded-full h-5 w-5 border-b-2 border-white mr-2"></div>
|
||||
生成中...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Send className="w-5 h-5 mr-2" />
|
||||
生成取件码
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
{!isRoomCreated ? (
|
||||
<Button
|
||||
onClick={handleCreateRoom}
|
||||
disabled={!textContent.trim() || textContent.length > 50000 || isLoading}
|
||||
className="w-full h-12 bg-gradient-to-r from-blue-500 to-indigo-500 hover:from-blue-600 hover:to-indigo-600 text-white text-lg font-medium rounded-xl shadow-lg"
|
||||
>
|
||||
{isLoading ? (
|
||||
<>
|
||||
<div className="animate-spin rounded-full h-5 w-5 border-b-2 border-white mr-2"></div>
|
||||
创建房间...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Send className="w-5 h-5 mr-2" />
|
||||
创建文字传输房间
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
) : (
|
||||
<div className="space-y-4">
|
||||
<div className="p-4 bg-gradient-to-r from-emerald-50 to-teal-50 rounded-xl border border-emerald-200">
|
||||
<div className="text-center">
|
||||
<p className="text-sm text-emerald-700 mb-2">房间码</p>
|
||||
<div className="text-2xl font-bold font-mono text-emerald-600 mb-3">{roomCode}</div>
|
||||
<div className="flex flex-wrap gap-2 justify-center">
|
||||
<Button
|
||||
onClick={() => copyToClipboard(roomCode)}
|
||||
size="sm"
|
||||
className="bg-emerald-500 hover:bg-emerald-600 text-white"
|
||||
>
|
||||
<Copy className="w-4 h-4 mr-2" />
|
||||
复制房间码
|
||||
</Button>
|
||||
<Button
|
||||
onClick={() => copyTransferLink(roomCode)}
|
||||
size="sm"
|
||||
className="bg-purple-500 hover:bg-purple-600 text-white"
|
||||
>
|
||||
<Link className="w-4 h-4 mr-2" />
|
||||
复制链接
|
||||
</Button>
|
||||
<Button
|
||||
onClick={handleSendText}
|
||||
size="sm"
|
||||
className="bg-blue-500 hover:bg-blue-600 text-white"
|
||||
disabled={!textContent.trim()}
|
||||
>
|
||||
<Send className="w-4 h-4 mr-2" />
|
||||
发送文字
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{pickupCode && (
|
||||
<div className="mt-6 p-4 bg-gradient-to-r from-emerald-50 to-teal-50 rounded-xl border border-emerald-200">
|
||||
<div className="text-center">
|
||||
<p className="text-sm text-emerald-700 mb-2">取件码生成成功!</p>
|
||||
<div className="text-2xl font-bold font-mono text-emerald-600 mb-3">{pickupCode}</div>
|
||||
<Button
|
||||
onClick={() => copyToClipboard(pickupCode)}
|
||||
size="sm"
|
||||
className="bg-emerald-500 hover:bg-emerald-600 text-white"
|
||||
>
|
||||
<Copy className="w-4 h-4 mr-2" />
|
||||
复制取件码
|
||||
</Button>
|
||||
{/* 图片展示区域 */}
|
||||
{images.length > 0 && (
|
||||
<div className="mt-6">
|
||||
<h3 className="text-lg font-medium text-slate-800 mb-3 flex items-center">
|
||||
<Image className="w-5 h-5 mr-2" />
|
||||
已发送的图片 ({images.length})
|
||||
</h3>
|
||||
<div className="grid grid-cols-2 sm:grid-cols-3 gap-3">
|
||||
{images.map((img, index) => (
|
||||
<div key={index} className="relative group">
|
||||
<img
|
||||
src={img}
|
||||
alt={`图片 ${index + 1}`}
|
||||
className="w-full h-24 object-cover rounded-lg border-2 border-slate-200 hover:border-blue-400 transition-colors cursor-pointer"
|
||||
onClick={() => window.open(img, '_blank')}
|
||||
/>
|
||||
<div className="absolute inset-0 bg-black bg-opacity-0 group-hover:bg-opacity-20 transition-opacity rounded-lg"></div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
@@ -173,53 +471,115 @@ export default function TextTransfer({ onSendText, onReceiveText }: TextTransfer
|
||||
<Download className="w-6 h-6 sm:w-8 sm:h-8 text-white" />
|
||||
</div>
|
||||
<h2 className="text-xl sm:text-2xl font-semibold text-slate-800 mb-2">接收文字</h2>
|
||||
<p className="text-sm sm:text-base text-slate-600">输入6位取件码来获取文本</p>
|
||||
<p className="text-sm sm:text-base text-slate-600">输入6位房间码来获取文字内容</p>
|
||||
|
||||
{/* 连接状态显示 */}
|
||||
{(receivedText || textContent) && (
|
||||
<div className="mt-2 space-y-1">
|
||||
<div className="flex items-center justify-center space-x-4 text-sm">
|
||||
<div className="flex items-center">
|
||||
<div className={`w-2 h-2 rounded-full mr-2 ${isConnected ? 'bg-emerald-500 animate-pulse' : 'bg-red-500'}`}></div>
|
||||
<span className={isConnected ? 'text-emerald-600' : 'text-red-600'}>
|
||||
{isConnected ? '实时连接已建立' : '连接断开'}
|
||||
</span>
|
||||
</div>
|
||||
{connectedUsers > 0 && (
|
||||
<div className="flex items-center text-blue-600">
|
||||
<Users className="w-4 h-4 mr-1" />
|
||||
{connectedUsers} 人在线
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="space-y-4">
|
||||
<Input
|
||||
value={pickupCode}
|
||||
onChange={(e) => setPickupCode(e.target.value.toUpperCase().slice(0, 6))}
|
||||
placeholder="请输入取件码"
|
||||
value={roomCode}
|
||||
onChange={(e) => setRoomCode(e.target.value.toUpperCase().slice(0, 6))}
|
||||
placeholder="请输入房间码"
|
||||
className="text-center text-2xl sm:text-3xl tracking-[0.3em] sm:tracking-[0.5em] font-mono h-12 sm:h-16 border-2 border-slate-200 rounded-xl focus:border-emerald-500 focus:ring-emerald-500 bg-white/80 backdrop-blur-sm"
|
||||
maxLength={6}
|
||||
disabled={isLoading}
|
||||
/>
|
||||
|
||||
<Button
|
||||
onClick={handleReceiveText}
|
||||
disabled={pickupCode.length !== 6 || isLoading}
|
||||
onClick={handleJoinRoom}
|
||||
disabled={roomCode.length !== 6 || isLoading}
|
||||
className="w-full h-12 bg-gradient-to-r from-emerald-500 to-teal-500 hover:from-emerald-600 hover:to-teal-600 text-white text-lg font-medium rounded-xl shadow-lg"
|
||||
>
|
||||
{isLoading ? (
|
||||
<>
|
||||
<div className="animate-spin rounded-full h-5 w-5 border-b-2 border-white mr-2"></div>
|
||||
获取中...
|
||||
连接中...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Download className="w-5 h-5 mr-2" />
|
||||
获取文本
|
||||
获取文字
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
|
||||
{receivedText && (
|
||||
{(receivedText || textContent) && (
|
||||
<div className="mt-6 space-y-4">
|
||||
<textarea
|
||||
value={receivedText}
|
||||
readOnly
|
||||
className="w-full min-h-[200px] p-4 border-2 border-emerald-200 rounded-xl bg-emerald-50/50 backdrop-blur-sm resize-none"
|
||||
/>
|
||||
<div className="relative">
|
||||
<textarea
|
||||
value={receivedText || textContent}
|
||||
readOnly={currentRole !== 'receiver'}
|
||||
onChange={currentRole === 'receiver' ? handleTextChange : undefined}
|
||||
className="w-full min-h-[150px] p-4 border-2 border-emerald-200 rounded-xl bg-emerald-50/50 backdrop-blur-sm resize-none"
|
||||
/>
|
||||
{currentRole === 'receiver' && isConnected && (
|
||||
<div className="absolute top-2 right-2">
|
||||
<div className="flex items-center space-x-1 bg-emerald-100 text-emerald-700 px-2 py-1 rounded-lg text-xs">
|
||||
<div className="w-2 h-2 bg-emerald-500 rounded-full animate-pulse"></div>
|
||||
<span>实时同步</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{currentRole === 'receiver' && !isConnected && (
|
||||
<div className="absolute top-2 right-2">
|
||||
<div className="flex items-center space-x-1 bg-orange-100 text-orange-700 px-2 py-1 rounded-lg text-xs">
|
||||
<div className="w-2 h-2 bg-orange-500 rounded-full"></div>
|
||||
<span>连接中...</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<Button
|
||||
onClick={() => copyToClipboard(receivedText)}
|
||||
onClick={() => copyToClipboard(receivedText || textContent)}
|
||||
className="w-full h-12 bg-gradient-to-r from-emerald-500 to-teal-500 hover:from-emerald-600 hover:to-teal-600 text-white text-lg font-medium rounded-xl shadow-lg"
|
||||
>
|
||||
<Copy className="w-5 h-5 mr-2" />
|
||||
复制文本
|
||||
复制文字
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 接收到的图片展示 */}
|
||||
{images.length > 0 && (
|
||||
<div className="mt-6">
|
||||
<h3 className="text-lg font-medium text-slate-800 mb-3 flex items-center">
|
||||
<Image className="w-5 h-5 mr-2" />
|
||||
接收到的图片 ({images.length})
|
||||
</h3>
|
||||
<div className="grid grid-cols-2 sm:grid-cols-3 gap-3">
|
||||
{images.map((img, index) => (
|
||||
<div key={index} className="relative group">
|
||||
<img
|
||||
src={img}
|
||||
alt={`图片 ${index + 1}`}
|
||||
className="w-full h-24 object-cover rounded-lg border-2 border-slate-200 hover:border-emerald-400 transition-colors cursor-pointer"
|
||||
onClick={() => window.open(img, '_blank')}
|
||||
/>
|
||||
<div className="absolute inset-0 bg-black bg-opacity-0 group-hover:bg-opacity-20 transition-opacity rounded-lg"></div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -56,6 +56,10 @@ func main() {
|
||||
r.Get("/api/room-status", h.GetRoomStatusHandler)
|
||||
r.Post("/api/update-room-files", h.UpdateRoomFilesHandler)
|
||||
|
||||
// 文字传输API路由
|
||||
r.Post("/api/create-text-room", h.CreateTextRoomHandler)
|
||||
r.Get("/api/get-text-content/*", h.GetTextContentHandler)
|
||||
|
||||
// 启动服务器
|
||||
srv := &http.Server{
|
||||
Addr: ":8080",
|
||||
|
||||
@@ -186,6 +186,78 @@ func (h *Handler) UpdateRoomFilesHandler(w http.ResponseWriter, r *http.Request)
|
||||
json.NewEncoder(w).Encode(response)
|
||||
}
|
||||
|
||||
// CreateTextRoomHandler 创建文字传输房间API
|
||||
func (h *Handler) CreateTextRoomHandler(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
http.Error(w, "方法不允许", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
var req struct {
|
||||
Text string `json:"text"`
|
||||
}
|
||||
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
http.Error(w, "解析请求失败", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
if req.Text == "" {
|
||||
http.Error(w, "文本内容不能为空", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
if len(req.Text) > 50000 {
|
||||
http.Error(w, "文本内容过长,最大支持50,000字符", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
// 创建文字传输房间
|
||||
code := h.p2pService.CreateTextRoom(req.Text)
|
||||
|
||||
response := map[string]interface{}{
|
||||
"success": true,
|
||||
"code": code,
|
||||
"message": "文字传输房间创建成功",
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(response)
|
||||
}
|
||||
|
||||
// GetTextContentHandler 获取文字内容API
|
||||
func (h *Handler) GetTextContentHandler(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet {
|
||||
http.Error(w, "方法不允许", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
// 从URL路径中提取code
|
||||
path := r.URL.Path
|
||||
code := path[len("/api/get-text-content/"):]
|
||||
|
||||
if code == "" || len(code) != 6 {
|
||||
http.Error(w, "请提供正确的6位房间码", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
// 获取文字内容
|
||||
text, exists := h.p2pService.GetTextContent(code)
|
||||
if !exists {
|
||||
http.Error(w, "房间不存在或已过期", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
response := map[string]interface{}{
|
||||
"success": true,
|
||||
"text": text,
|
||||
"message": "文字内容获取成功",
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(response)
|
||||
}
|
||||
|
||||
// HandleP2PWebSocket 处理P2P WebSocket连接
|
||||
func (h *Handler) HandleP2PWebSocket(w http.ResponseWriter, r *http.Request) {
|
||||
h.p2pService.HandleWebSocket(w, r)
|
||||
|
||||
@@ -16,12 +16,14 @@ import (
|
||||
)
|
||||
|
||||
type FileTransferRoom struct {
|
||||
ID string
|
||||
Code string // 取件码
|
||||
Files []models.FileTransferInfo // 待传输文件信息
|
||||
Clients map[string]*models.ClientInfo // 所有连接的客户端 (客户端ID -> ClientInfo)
|
||||
CreatedAt time.Time // 创建时间
|
||||
mutex sync.RWMutex
|
||||
ID string
|
||||
Code string // 取件码
|
||||
Files []models.FileTransferInfo // 待传输文件信息
|
||||
Clients map[string]*models.ClientInfo // 所有连接的客户端 (客户端ID -> ClientInfo)
|
||||
CreatedAt time.Time // 创建时间
|
||||
TextContent string // 文字内容
|
||||
IsTextRoom bool // 是否是文字传输房间
|
||||
mutex sync.RWMutex
|
||||
}
|
||||
|
||||
type P2PService struct {
|
||||
@@ -77,6 +79,42 @@ func (p *P2PService) GetRoomByCode(code string) (*FileTransferRoom, bool) {
|
||||
return room, exists
|
||||
}
|
||||
|
||||
// CreateTextRoom 创建文字传输房间并返回取件码
|
||||
func (p *P2PService) CreateTextRoom(text string) string {
|
||||
code := generatePickupCode()
|
||||
|
||||
p.roomsMux.Lock()
|
||||
defer p.roomsMux.Unlock()
|
||||
|
||||
room := &FileTransferRoom{
|
||||
ID: "text_room_" + code,
|
||||
Code: code,
|
||||
Files: []models.FileTransferInfo{}, // 文字房间不需要文件
|
||||
Clients: make(map[string]*models.ClientInfo),
|
||||
CreatedAt: time.Now(),
|
||||
TextContent: text,
|
||||
IsTextRoom: true,
|
||||
}
|
||||
|
||||
p.rooms[code] = room
|
||||
log.Printf("创建文字传输房间,取件码: %s,文字长度: %d", code, len(text))
|
||||
|
||||
return code
|
||||
}
|
||||
|
||||
// GetTextContent 根据取件码获取文字内容
|
||||
func (p *P2PService) GetTextContent(code string) (string, bool) {
|
||||
p.roomsMux.RLock()
|
||||
defer p.roomsMux.RUnlock()
|
||||
|
||||
room, exists := p.rooms[code]
|
||||
if !exists || !room.IsTextRoom {
|
||||
return "", false
|
||||
}
|
||||
|
||||
return room.TextContent, true
|
||||
}
|
||||
|
||||
// generateClientID 生成客户端唯一标识
|
||||
func generateClientID() string {
|
||||
b := make([]byte, 8)
|
||||
@@ -202,6 +240,15 @@ func (p *P2PService) HandleWebSocket(w http.ResponseWriter, r *http.Request) {
|
||||
case "file-info", "file-chunk", "file-complete":
|
||||
// 处理文件传输相关消息,直接转发给接收方
|
||||
p.forwardMessage(room, clientID, msg)
|
||||
case "text-update":
|
||||
// 处理实时文字更新
|
||||
p.handleTextUpdate(room, clientID, msg)
|
||||
case "text-send":
|
||||
// 处理文字发送
|
||||
p.handleTextSend(room, clientID, msg)
|
||||
case "image-send":
|
||||
// 处理图片发送
|
||||
p.handleImageSend(room, clientID, msg)
|
||||
default:
|
||||
// 转发消息到对应的客户端
|
||||
p.forwardMessage(room, clientID, msg)
|
||||
@@ -539,3 +586,50 @@ func (p *P2PService) UpdateRoomFiles(code string, files []models.FileTransferInf
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
// handleTextUpdate 处理实时文字更新
|
||||
func (p *P2PService) handleTextUpdate(room *FileTransferRoom, senderID string, msg models.VideoMessage) {
|
||||
log.Printf("处理文字更新: 来自客户端 %s", senderID)
|
||||
|
||||
// 转发文字更新给房间内其他所有客户端
|
||||
room.mutex.RLock()
|
||||
defer room.mutex.RUnlock()
|
||||
|
||||
for clientID, client := range room.Clients {
|
||||
if clientID != senderID { // 不发送给发送者自己
|
||||
if err := client.Connection.WriteJSON(msg); err != nil {
|
||||
log.Printf("转发文字更新失败 %s: %v", clientID, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// handleTextSend 处理文字发送
|
||||
func (p *P2PService) handleTextSend(room *FileTransferRoom, senderID string, msg models.VideoMessage) {
|
||||
log.Printf("处理文字发送: 来自客户端 %s", senderID)
|
||||
|
||||
// 转发文字发送给房间内所有客户端
|
||||
room.mutex.RLock()
|
||||
defer room.mutex.RUnlock()
|
||||
|
||||
for _, client := range room.Clients {
|
||||
if err := client.Connection.WriteJSON(msg); err != nil {
|
||||
log.Printf("转发文字发送失败 %s: %v", client.ID, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// handleImageSend 处理图片发送
|
||||
func (p *P2PService) handleImageSend(room *FileTransferRoom, senderID string, msg models.VideoMessage) {
|
||||
log.Printf("处理图片发送: 来自客户端 %s", senderID)
|
||||
|
||||
// 转发图片发送给房间内所有客户端
|
||||
room.mutex.RLock()
|
||||
defer room.mutex.RUnlock()
|
||||
|
||||
for _, client := range room.Clients {
|
||||
if err := client.Connection.WriteJSON(msg); err != nil {
|
||||
log.Printf("转发图片发送失败 %s: %v", client.ID, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user