From c309be102cd17af50a4436d1beb47a6aa4e93fa1 Mon Sep 17 00:00:00 2001 From: caprain Date: Wed, 13 May 2026 18:52:30 +0800 Subject: [PATCH] =?UTF-8?q?=E5=AE=8C=E5=96=84web=E7=AB=AF=E6=B6=88?= =?UTF-8?q?=E6=81=AF=E8=A1=A5=E5=8F=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src-tauri/src/db.rs | 25 ++++---- src-tauri/src/network/discovery.rs | 32 ++++++---- src-tauri/src/web_server.rs | 36 +++++++----- src/js/app.js | 94 +++++++++++++++--------------- src/js/ui.js | 4 ++ 5 files changed, 109 insertions(+), 82 deletions(-) diff --git a/src-tauri/src/db.rs b/src-tauri/src/db.rs index 8ddf843..518cde8 100644 --- a/src-tauri/src/db.rs +++ b/src-tauri/src/db.rs @@ -359,26 +359,31 @@ pub async fn create_upload_record( pool: &sqlx::Pool, receiver_id: String, file_name: String, + file_size: u64, timestamp: i64, + file_status: String, + overall_status: String, ) -> Result { println!( - "[DB] 创建上传记录: 接收者={}, 文件={}", - receiver_id, file_name + "[DB] 创建上传记录: 接收者={}, 文件={}, 状态={}", + receiver_id, file_name, overall_status ); let result = sqlx::query( - "INSERT INTO messages (sender_id, receiver_id, content, msg_type, timestamp, file_path, file_status) VALUES ('me', ?, ?, 'file', ?, '', 'uploading')" + "INSERT INTO messages (sender_id, receiver_id, content, msg_type, timestamp, file_path, file_status, file_size, status) + VALUES ('me', ?, ?, 'file', ?, '', ?, ?, ?)" ) .bind(&receiver_id) .bind(&file_name) .bind(timestamp) + .bind(&file_status) + .bind(file_size as i64) + .bind(&overall_status) .execute(pool) .await .map_err(|e| format!("创建记录失败: {}", e))?; - let msg_id = result.last_insert_rowid(); - println!("[DB] 上传记录已创建,ID: {}", msg_id); - Ok(msg_id) + Ok(result.last_insert_rowid()) } /// 更新上传状态 @@ -387,10 +392,10 @@ pub async fn update_upload_status( file_name: String, status: String, ) -> Result<(), String> { - println!("[DB] 更新上传状态: {} -> {}", file_name, status); - + println!("[DB] Web前端确认发送完毕,强制同步更新状态: {} -> {}", file_name, status); + // 只要前端说传完了,不管后端之前以为它是 pending 还是 uploading,统统强制标为已发送! sqlx::query( - "UPDATE messages SET file_status = ? WHERE sender_id = 'me' AND content = ? AND file_status = 'uploading'" + "UPDATE messages SET file_status = ?, status = 'sent' WHERE sender_id = 'me' AND content = ?" ) .bind(&status) .bind(&file_name) @@ -398,7 +403,7 @@ pub async fn update_upload_status( .await .map_err(|e| format!("更新状态失败: {}", e))?; - println!("[DB] 上传状态已更新"); + println!("[DB] 上传状态已强制更新为 sent,移出补发队列"); Ok(()) } diff --git a/src-tauri/src/network/discovery.rs b/src-tauri/src/network/discovery.rs index 5fd082a..3e11522 100644 --- a/src-tauri/src/network/discovery.rs +++ b/src-tauri/src/network/discovery.rs @@ -452,19 +452,29 @@ async fn resend_pending_messages( } // 加入了文件补发逻辑分支 else if msg_type == "file" { - if let (Some(path), Some(size)) = (file_path, file_size) { - match resend_file_background(&my_id, peer_addr, &content, &path, size).await - { - Ok(_) => { - println!("[UDP] ✓ 文件消息 {} 补发成功", msg_id); - msg_ids_to_mark.push(msg_id); - } - Err(e) => { - eprintln!("[UDP] ✗ 文件消息 {} 补发失败: {}", msg_id, e); + match (file_path.as_ref(), file_size) { + (Some(path), Some(size)) if !path.trim().is_empty() => { + // 只有路径非空时,才尝试读取文件补发 + match resend_file_background(&my_id, peer_addr, &content, path, size) + .await + { + Ok(_) => { + println!("[UDP] ✓ 文件消息 {} 补发成功", msg_id); + msg_ids_to_mark.push(msg_id); + } + Err(e) => { + eprintln!("[UDP] ✗ 文件消息 {} 补发失败: {}", msg_id, e); + } } } - } else { - eprintln!("[UDP] ✗ 无法补发文件消息 {},缺少路径或大小信息", msg_id); + _ => { + // 如果文件路径为空(Web端发送)或信息不全 + // 我们不能让它一直卡在 pending 状态不停报错 + eprintln!("[UDP] ⚠ 跳过无法补发的文件消息 {}: 路径缺失(Web端记录或数据异常)。将其移出挂起队列。", msg_id); + // 把它加入“待标记”列表,让数据库把它状态改成 sent, + // 这样它就再也不会进入补发循环了。 + msg_ids_to_mark.push(msg_id); + } } } } diff --git a/src-tauri/src/web_server.rs b/src-tauri/src/web_server.rs index febb999..30f7a22 100644 --- a/src-tauri/src/web_server.rs +++ b/src-tauri/src/web_server.rs @@ -1121,6 +1121,7 @@ async fn get_download_dir(pool: &Pool) -> std::path::PathBuf { #[derive(Deserialize)] struct CreateUploadRecordRequest { file_name: String, + file_size: u64, // 新增 timestamp: i64, receiver_id: String, } @@ -1129,30 +1130,37 @@ async fn create_upload_record_http( State(state): State>, Json(payload): Json, ) -> impl IntoResponse { - println!("[Web Server] 创建上传记录: {}", payload.file_name); + let is_online = state + .peer_manager + .get_active_peers() + .iter() + .any(|p| p.id == payload.receiver_id); + + let (file_status, overall_status) = if is_online { + ("uploading".to_string(), "sent".to_string()) + } else { + ("accepted".to_string(), "pending".to_string()) + }; match crate::db::create_upload_record( &state.pool, payload.receiver_id.clone(), payload.file_name.clone(), + payload.file_size, payload.timestamp, + file_status, + overall_status, ) .await { - Ok(_) => { - println!("[Web Server] ✓ 上传记录已创建"); - Json(serde_json::json!({ "success": true })).into_response() - } - Err(e) => { - eprintln!("[Web Server] ✗ 创建上传记录失败: {}", e); - ( - StatusCode::INTERNAL_SERVER_ERROR, - Json(ErrorResponse { - error: format!("创建记录失败: {}", e), - }), - ) - .into_response() + Ok(msg_id) => { + Json(serde_json::json!({ "success": true, "msg_id": msg_id })).into_response() } + Err(e) => ( + StatusCode::INTERNAL_SERVER_ERROR, + Json(serde_json::json!({"error": e})), + ) + .into_response(), } } diff --git a/src/js/app.js b/src/js/app.js index b631c90..c09f925 100644 --- a/src/js/app.js +++ b/src/js/app.js @@ -326,83 +326,83 @@ function formatFileSize(bytes) { document.addEventListener("DOMContentLoaded", renderPage); -// Web 端轮询新消息 -// Web 端轮询新消息 // Web 端轮询新消息 async function startMessagePolling() { const pollInterval = 1000; - - // 初始化轮询开关 window.messagePollingEnabled = true; const checkNewMessages = async () => { - // 如果轮询被禁用,或者当前没有聊天对象,直接跳过 - if (!window.messagePollingEnabled || !window.currentChatPeer) { - return; - } + if (!window.messagePollingEnabled || !window.currentChatPeer) return; try { const chatMessages = document.getElementById("chat-messages"); - const scrollTop = chatMessages.scrollTop; - const scrollHeight = chatMessages.scrollHeight; - const clientHeight = chatMessages.clientHeight; - const isAtBottom = scrollHeight - scrollTop - clientHeight < 100; + if (!chatMessages) return; - // 只获取最新的 20 条消息 + const isAtBottom = + chatMessages.scrollHeight - chatMessages.scrollTop - + chatMessages.clientHeight < 150; + + // 1. 获取最近 20 条消息(包含可能状态已改变的旧消息) const latestMessages = await apiGetChatHistory( window.currentChatPeer.id, 20, 0, ); - if (!latestMessages || latestMessages.length === 0) return; - // 通过时间戳判断真正的"新消息",而不是通过 DOM 节点数量对比 + // 2. 筛选出:真正的时间戳新消息 const newMessages = latestMessages.filter((msg) => msg.timestamp > (window.lastMessageTimestamp || 0) ); - // 如果确实有新消息 - if (newMessages.length > 0) { - // 如果在底部,直接添加消息并滚动 + // 3. 筛选出:时间戳没变但状态变了的消息 + const statusChangedMessages = latestMessages.filter((msg) => { + // 如果是已经判定为新消息的,就不在这里处理了 + if (msg.timestamp > (window.lastMessageTimestamp || 0)) return false; + + const domEl = document.querySelector(`[data-msg-id="${msg.id}"]`); + if (!domEl) return false; + + // 对比 DOM 中的状态与后端返回的状态 + // 如果后端变成了 'sent' 而 DOM 里还是 'pending',说明补发成功了 + return domEl.dataset.status !== msg.status; + }); + + // 4. 执行更新 + if (newMessages.length > 0 || statusChangedMessages.length > 0) { + // 更新所有状态变了的消息(addMessageToChat 内部会自动 existing.remove()) + for (const msg of statusChangedMessages) { + console.log( + "[JS-App] 检测到消息状态变更,更新 UI:", + msg.id, + msg.status, + ); + addMessageToChat(msg, msg.from_id === "me"); + } + + // 添加全新的消息 + for (const msg of newMessages) { + addMessageToChat(msg, msg.from_id === "me"); + if (msg.timestamp > (window.lastMessageTimestamp || 0)) { + window.lastMessageTimestamp = msg.timestamp; + } + } + + // 如果用户在底部,保持滚动 if (isAtBottom) { - for (const msg of newMessages) { - addMessageToChat(msg, msg.from_id === "me"); - - // 动态更新最后一条消息的时间戳 - if (msg.timestamp > (window.lastMessageTimestamp || 0)) { - window.lastMessageTimestamp = msg.timestamp; - } - } - - // 维护懒加载的总数量计数器 - if (window.currentChatMessages) { - window.currentChatMessages.loadedCount += newMessages.length; - window.currentChatMessages.totalCount += newMessages.length; - } - - // 滚动到底部 await scrollToBottom(); - } else { - // 如果不在底部,只显示红点,不更新时间戳,不添加消息 - // 这样当用户滚动到底部时,轮询会自动检测到这些消息并添加 - console.log("[JS-App] 用户不在底部,显示未读红点(不更新时间戳)"); + } - const unreadDot = document.getElementById("unread-dot"); - const scrollBtn = document.getElementById("scroll-to-bottom-btn"); - if (unreadDot && scrollBtn) { - scrollBtn.classList.add("show"); - unreadDot.classList.add("show"); - console.log("[JS-App] 已显示未读红点"); - } + // 更新懒加载计数器 + if (window.currentChatMessages && newMessages.length > 0) { + window.currentChatMessages.loadedCount += newMessages.length; } } } catch (e) { - console.error("[JS-App] 轮询消息失败:", e); + console.error("[JS-App] 轮询失败:", e); } }; - // 定时轮询 setInterval(checkNewMessages, pollInterval); } diff --git a/src/js/ui.js b/src/js/ui.js index c7deb50..133f3d8 100644 --- a/src/js/ui.js +++ b/src/js/ui.js @@ -874,6 +874,9 @@ function createMessageElement(message, isSent) { messageDiv.className = `message ${isSent ? "sent" : "received"}`; if (message.id) messageDiv.dataset.msgId = message.id; + // 把当前状态存入数据集,方便轮询检测 + messageDiv.dataset.status = message.status || 'sent'; + const contentDiv = document.createElement("div"); contentDiv.className = "message-content"; @@ -1208,6 +1211,7 @@ async function sendFile(file) { headers: { "Content-Type": "application/json" }, body: JSON.stringify({ file_name: file.name, + file_size: file.size, timestamp: timestamp, receiver_id: window.currentChatPeer.id, }),