Feature: preview remote files on file manager double-click

Double-clicking a local file now opens it, and a remote file is fetched
through the existing V2 transfer into Preview\<clientKey>\<hash16>_<basename>
and opened with the default program. The cache index is checked first by
remote path + size/mtime; a transfer records the complete packet's SHA-256
and verifies it before moving the file into the cache.

Hook both V2 receive paths: the Windows stream sub-connection observes
the first chunk in MessageHandle and later chunks in CDlgFileSend; the
Unix/Android same-connection path observes in OnRecvFileV2Chunk. A failed
basename bound or path escape cancels the stream. The filename is now
bounded by the packet's nameLength (it is not NUL-terminated), which also
fixes the 1 MiB transfer case where trailing bytes were misread as a path.

Search-result lists use column 3 as the directory and get their own
result flag; the exact size/FILETIME from the listing feeds the 8 MiB gate.
Remote executables require a confirmation before ShellExecute. A Debug-only
WM_APP+0x123 hook drives the same double-click handler for end-to-end tests.

Verified with a Debug x64 server and client: a 1 MiB remote file was
transferred, SHA-256 verified, cached and indexed; a second double-click
hit the cache without a transfer.

Co-Authored-By: deepseek-flash
This commit is contained in:
yuanyuanxianganddeepseek-flash committed 2026-12-05 15:30:26 +01:00
1 parent 02c22b82a7
commit 3b945d1992
6 files changed
+329 -10

No files matched your search

+275 -7
View File
@@ -9,12 +9,24 @@
#include "ZstdArchive.h"
#include "2015RemoteDlg.h"
#include "CDlgFileSend.h"
#include "FilePreview.h"
#include <Shlobj.h>
#include <ws2tcpip.h>
// V2 接收用:定义在 CPasswordDlg.cpp,按本仓约定就地前置声明
std::string GetPwdHash();
std::string GetHMAC(int offset);
static uint64_t FileTimeToUnixMs(const FILETIME& ft)
{
ULARGE_INTEGER u;
u.LowPart = ft.dwLowDateTime;
u.HighPart = ft.dwHighDateTime;
const uint64_t kEpochDiff = 116444736000000000ULL;
if (u.QuadPart < kEpochDiff) return 0;
return (u.QuadPart - kEpochDiff) / 10000ULL;
}
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
@@ -240,6 +252,10 @@ BEGIN_MESSAGE_MAP(CFileManagerDlg, CDialog)
ON_MESSAGE(WM_LOCAL_SEARCH_PROGRESS, OnLocalSearchProgress)
ON_MESSAGE(WM_RECVFILEV2_CHUNK, &CFileManagerDlg::OnRecvFileV2Chunk)
ON_MESSAGE(WM_RECVFILEV2_COMPLETE, &CFileManagerDlg::OnRecvFileV2Complete)
ON_MESSAGE(WM_PREVIEW_RESULT, &CFileManagerDlg::OnPreviewResult)
#ifdef _DEBUG
ON_MESSAGE(WM_APP + 0x123, &CFileManagerDlg::OnPreviewTest)
#endif
//}}AFX_MSG_MAP
ON_COMMAND(ID_FILEMANGER_COMPRESS, &CFileManagerDlg::OnFilemangerCompress)
ON_COMMAND(ID_FILEMANGER_UNCOMPRESS, &CFileManagerDlg::OnFilemangerUncompress)
@@ -503,15 +519,42 @@ void CFileManagerDlg::FixedLocalDriveList()
void CFileManagerDlg::OnDblclkListLocal(NMHDR* pNMHDR, LRESULT* pResult)
{
// TODO: Add your control notification handler code here
if (m_list_local.GetSelectedCount() == 0 || m_list_local.GetItemData(m_list_local.GetSelectionMark()) != 1)
NMITEMACTIVATE* ia = (NMITEMACTIVATE*)pNMHDR;
int nItem = ia ? ia->iItem : -1;
if (nItem < 0) nItem = m_list_local.GetSelectionMark();
if (nItem < 0) {
*pResult = 0;
return;
FixedLocalFileList();
}
// 目录:仍进入子目录
if (m_list_local.GetItemData(nItem) == 1) {
Mprintf("[Preview] local dblclick dir item=%d\n", nItem);
FixedLocalFileList();
*pResult = 0;
return;
}
// 文件:本地直接打开。搜索结果第 3 列是目录,普通列表第 3 列是修改日期。
CString name = m_list_local.GetItemText(nItem, 0);
CString full;
if (m_bLocalSearchResults) {
full = m_list_local.GetItemText(nItem, 3);
if (!full.IsEmpty() && full.Right(1) != "\\") full += "\\";
full += name;
} else {
full = m_Local_Path + name;
}
Mprintf("[Preview] local dblclick item=%d search=%d full=%s\n",
nItem, (int)m_bLocalSearchResults, (LPCSTR)full);
OpenLocalPath(full);
*pResult = 0;
}
void CFileManagerDlg::FixedLocalFileList(CString directory)
{
m_bLocalSearchResults = false;
// 导航时停止正在进行的本地搜索
if (m_bLocalSearching) {
m_bLocalSearching = false;
@@ -971,6 +1014,7 @@ void CFileManagerDlg::OnClose()
ShowWindow(SW_HIDE);
return;
}
CFilePreviewMgr::Instance().CancelForHwnd(m_hWnd);
CoUninitialize();
DialogBase::OnClose();
@@ -1103,6 +1147,9 @@ void CFileManagerDlg::OnReceiveComplete()
void CFileManagerDlg::GetRemoteFileList(CString directory)
{
m_bRemoteSearchResults = false;
m_RemoteMeta.clear();
// 导航到目录时停止正在进行的远程搜索
if (m_bSearching) {
BYTE bStop = COMMAND_FILES_SEARCH_STOP;
@@ -1160,15 +1207,197 @@ void CFileManagerDlg::GetRemoteFileList(CString directory)
void CFileManagerDlg::OnDblclkListRemote(NMHDR* pNMHDR, LRESULT* pResult)
{
if (m_list_remote.GetSelectedCount() == 0 || m_list_remote.GetItemData(m_list_remote.GetSelectionMark()) != 1)
NMITEMACTIVATE* ia = (NMITEMACTIVATE*)pNMHDR;
int nItem = ia ? ia->iItem : -1;
if (nItem < 0) nItem = m_list_remote.GetSelectionMark();
if (nItem < 0) {
*pResult = 0;
return;
// TODO: Add your control notification handler code here
GetRemoteFileList();
}
// 目录:仍进入子目录
if (m_list_remote.GetItemData(nItem) == 1) {
Mprintf("[Preview] remote dblclick dir item=%d\n", nItem);
GetRemoteFileList();
*pResult = 0;
return;
}
// 文件:拉回本地预览。搜索结果第 3 列是目录,普通列表第 3 列是修改日期。
CString name = m_list_remote.GetItemText(nItem, 0);
CString full;
if (m_bRemoteSearchResults) {
full = m_list_remote.GetItemText(nItem, 3);
if (!full.IsEmpty() && full.Right(1) != "\\") full += "\\";
full += name;
} else {
full = m_Remote_Path + name;
}
Mprintf("[Preview] remote dblclick item=%d search=%d full=%s\n",
nItem, (int)m_bRemoteSearchResults, (LPCSTR)full);
BeginRemotePreview(full);
*pResult = 0;
}
bool CFileManagerDlg::GetRemoteFileMeta(const CString& fullPath, RemoteMeta& meta)
{
auto it = m_RemoteMeta.find(std::string((LPCSTR)fullPath));
if (it == m_RemoteMeta.end())
return false;
meta = it->second;
return true;
}
std::string CFileManagerDlg::GetPreviewClientKey(uint64_t clientID)
{
if (clientID != 0) return std::to_string(clientID);
SOCKET s = m_ContextObject ? m_ContextObject->sClientSocket : INVALID_SOCKET;
if (s != INVALID_SOCKET) {
sockaddr_storage ss = {};
int len = (int)sizeof(ss);
if (getpeername(s, (sockaddr*)&ss, &len) == 0) {
char host[INET6_ADDRSTRLEN] = {};
int port = 0;
if (ss.ss_family == AF_INET) {
sockaddr_in* a = (sockaddr_in*)&ss;
inet_ntop(AF_INET, &a->sin_addr, host, sizeof(host));
port = ntohs(a->sin_port);
} else if (ss.ss_family == AF_INET6) {
sockaddr_in6* a = (sockaddr_in6*)&ss;
inet_ntop(AF_INET6, &a->sin6_addr, host, sizeof(host));
port = ntohs(a->sin6_port);
}
if (host[0])
return std::string("peer_") + host + "_" + std::to_string(port);
}
}
return std::string("peer_") + (m_ContextObject ? m_ContextObject->GetPeerName() : std::string("unknown"));
}
void CFileManagerDlg::OpenLocalPath(const CString& path)
{
if (path.IsEmpty()) return;
Mprintf("[Preview] open local: %s\n", (LPCSTR)path);
HINSTANCE r = ShellExecute(m_hWnd, "open", path, NULL, NULL, SW_SHOW);
if ((INT_PTR)r <= 32) {
CString msg;
msg.FormatL("无法打开文件:%s(可能没有关联程序)", path);
::MessageBox(m_hWnd, msg, _TR("提示"), MB_OK | MB_ICONWARNING);
}
}
void CFileManagerDlg::BeginRemotePreview(const CString& fullPath)
{
if (THIS_CFG.GetInt("settings", "PreviewEnabled", 1) == 0)
return;
uint64_t clientID = GetClientID();
context* mainCtx = nullptr;
if (g_2015RemoteDlg) {
if (clientID != 0) mainCtx = g_2015RemoteDlg->FindHostByClientID(clientID);
if (!mainCtx) mainCtx = g_2015RemoteDlg->FindHostByIP(m_ContextObject->GetPeerName());
}
if (!mainCtx || !SupportsFileTransferV2(mainCtx)) {
Mprintf("[Preview] capability reject: cid=%llu mainCtx=%p v2=%d\n",
(unsigned long long)clientID, mainCtx,
mainCtx ? (int)SupportsFileTransferV2(mainCtx) : -1);
::MessageBox(m_hWnd, _TR("客户端或 V2 开关不支持文件预览(参数 → 文件传输 V2)"),
_TR("提示"), MB_OK | MB_ICONINFORMATION);
return;
}
RemoteMeta meta;
if (!GetRemoteFileMeta(fullPath, meta)) {
Mprintf("[Preview] no meta for %s\n", (LPCSTR)fullPath);
::MessageBox(m_hWnd, _TR("无法获取文件信息,请刷新目录后重试"),
_TR("提示"), MB_OK | MB_ICONWARNING);
return;
}
Mprintf("[Preview] begin full=%s size=%llu mtime=%llu\n",
(LPCSTR)fullPath, (unsigned long long)meta.size, (unsigned long long)meta.mtimeMs);
if (meta.size > FILE_PREVIEW_MAX_BYTES) {
CString msg;
msg.FormatL("文件较大,不支持预览:%s(%llu MB,上限 %u MB)",
fullPath, (unsigned long long)(meta.size / 1024 / 1024),
(unsigned)(FILE_PREVIEW_MAX_BYTES / 1024 / 1024));
::MessageBox(m_hWnd, msg, _TR("提示"), MB_OK | MB_ICONINFORMATION);
return;
}
std::string remotePath((LPCSTR)fullPath);
size_t pos = remotePath.find_last_of("\\/");
std::string basename = (pos == std::string::npos) ? remotePath : remotePath.substr(pos + 1);
std::string clientKey = GetPreviewClientKey(clientID);
std::string outPath, error;
CFilePreviewMgr::PrepareResult pr = CFilePreviewMgr::Instance().Prepare(
clientID, clientKey, remotePath, basename, meta.size, meta.mtimeMs,
std::string(), m_hWnd, outPath, error);
Mprintf("[Preview] prepare result=%d out=%s err=%s\n", (int)pr, outPath.c_str(), error.c_str());
if (pr == CFilePreviewMgr::PrepareCached) {
CFilePreviewMgr::OpenLocalFile(m_hWnd, outPath, remotePath, meta.size, std::string());
return;
}
if (pr != CFilePreviewMgr::PrepareTransfer) {
CString msg(error.c_str());
::MessageBox(m_hWnd, msg, _TR("提示"), MB_OK | MB_ICONWARNING);
return;
}
// 下发 V2 下载:targetDir = 本次预览的临时目录,客户端把文件写回这里。
std::vector<BYTE> pkt;
pkt.reserve(1 + outPath.size() + 1 + remotePath.size() + 2);
pkt.push_back(CMD_DOWN_FILES_V2);
pkt.insert(pkt.end(), outPath.begin(), outPath.end());
pkt.push_back(0);
pkt.insert(pkt.end(), remotePath.begin(), remotePath.end());
pkt.push_back(0);
pkt.push_back(0);
m_ContextObject->Send2Client(pkt.data(), (DWORD)pkt.size());
ShowMessage(_TRF("正在预览 %s ..."), fullPath);
}
LRESULT CFileManagerDlg::OnPreviewResult(WPARAM /*wParam*/, LPARAM lParam)
{
CFilePreviewMgr::Result* r = (CFilePreviewMgr::Result*)lParam;
if (!r) return 0;
if (r->ok) {
CFilePreviewMgr::OpenLocalFile(m_hWnd, r->localPath, r->remotePath, r->size, r->sha256);
} else if (!r->message.empty()) {
CString msg(r->message.c_str());
::MessageBox(m_hWnd, msg, _TR("提示"), MB_OK | MB_ICONWARNING);
}
delete r;
return 0;
}
#ifdef _DEBUG
// 无鼠标端到端测试:直接以 NM_DBLCLK 调同一个处理函数,避免跨进程鼠标注入。
LRESULT CFileManagerDlg::OnPreviewTest(WPARAM wParam, LPARAM lParam)
{
int nItem = (int)wParam;
bool remote = (lParam != 0);
NMITEMACTIVATE ia = {};
ia.hdr.hwndFrom = remote ? m_list_remote.m_hWnd : m_list_local.m_hWnd;
ia.hdr.idFrom = remote ? IDC_LIST_REMOTE : IDC_LIST_LOCAL;
ia.hdr.code = NM_DBLCLK;
ia.iItem = nItem;
LRESULT result = 0;
if (remote)
OnDblclkListRemote((NMHDR*)&ia, &result);
else
OnDblclkListLocal((NMHDR*)&ia, &result);
return result;
}
#endif
void CFileManagerDlg::FixedRemoteFileList(BYTE *pbBuffer, DWORD dwBufferLen)
{
m_bRemoteSearchResults = false;
m_RemoteMeta.clear();
CString clientType = m_ContextObject->GetAdditionalData(RES_CLIENT_TYPE);
UINT cp = (clientType == _T("LNX") || clientType == _T("MAC")) ? CP_UTF8 : 936;
@@ -1238,6 +1467,14 @@ void CFileManagerDlg::FixedRemoteFileList(BYTE *pbBuffer, DWORD dwBufferLen)
memcpy(&ftm_strReceiveLocalFileTime, pList + 8, sizeof(FILETIME));
CTime time(ftm_strReceiveLocalFileTime);
m_list_remote.SetItemText(nItem, 3, time.FormatL("%Y-%m-%d %H:%M"));
if (nType != FILE_ATTRIBUTE_DIRECTORY) {
RemoteMeta meta;
meta.size = (uint64_t)dwFileSizeHigh * (MAXDWORD + 1ULL) + dwFileSizeLow;
meta.mtimeMs = FileTimeToUnixMs(ftm_strReceiveLocalFileTime);
CString full = m_Remote_Path + pszFileName;
m_RemoteMeta[std::string((LPCSTR)full)] = meta;
}
}
pList += 16;
}
@@ -1261,6 +1498,8 @@ void CFileManagerDlg::FixedRemoteSearchFileList(BYTE *pbBuffer, DWORD dwBufferLe
m_bSearching = true;
m_nSearchResultCount = 0;
m_IconCache.clear();
m_RemoteMeta.clear();
m_bRemoteSearchResults = true;
// 预缓存文件夹图标
m_IconCache["*folder*"] = GetIconIndex(NULL, FILE_ATTRIBUTE_DIRECTORY);
@@ -1336,6 +1575,13 @@ void CFileManagerDlg::FixedRemoteSearchFileList(BYTE *pbBuffer, DWORD dwBufferLe
// 路径
SetFileTextItem(m_list_remote, nItem, 3, csDir, cp);
if (nType != FILE_ATTRIBUTE_DIRECTORY) {
RemoteMeta meta;
meta.size = (uint64_t)dwFileSizeHigh * (MAXDWORD + 1ULL) + dwFileSizeLow;
meta.mtimeMs = FileTimeToUnixMs(ftLastWrite);
m_RemoteMeta[std::string((LPCSTR)csFullPath)] = meta;
}
pList += 16;
m_nSearchResultCount++;
}
@@ -1549,6 +1795,7 @@ LRESULT CFileManagerDlg::OnLocalSearchDone(WPARAM wParam, LPARAM lParam)
}
// 插入所有结果
m_bLocalSearchResults = true;
m_list_local.SetRedraw(FALSE);
for (size_t i = 0; i < pResults->size(); i++) {
const LocalSearchItem &item = (*pResults)[i];
@@ -2787,6 +3034,7 @@ void CFileManagerDlg::PostNcDestroy()
}
}
m_FileRecvDlgs.clear();
CFilePreviewMgr::Instance().CancelForHwnd(m_hWnd);
__super::PostNcDestroy();
}
@@ -2799,7 +3047,23 @@ LRESULT CFileManagerDlg::OnRecvFileV2Chunk(WPARAM wParam, LPARAM /*lParam*/)
BYTE* szBuffer = payload->first.data();
size_t len = payload->first.size();
uint64_t transferID = payload->second;
if (len < sizeof(FileChunkPacketV2)) { delete payload; return 0; }
FileChunkPacketV2* pkt = (FileChunkPacketV2*)szBuffer;
if (pkt->nameLength > len - sizeof(FileChunkPacketV2)) { delete payload; return 0; }
BYTE* name = szBuffer + sizeof(FileChunkPacketV2);
// 预览:逐块路径约束/首包门限。失败时不要创建进度框、不要落盘。
uint64_t previewTid = 0;
if (!CFilePreviewMgr::Instance().ObserveChunk(m_ContextObject, pkt, (const char*)name,
(ULONG)len, &previewTid)) {
auto it = m_FileRecvDlgs.find(transferID);
if (it != m_FileRecvDlgs.end()) {
if (::IsWindow(it->second.first)) ::PostMessage(it->second.first, WM_CLOSE, 0, 0);
m_FileRecvDlgs.erase(it);
}
delete payload;
return 0;
}
// 按 transferID 懒加载/复用进度框
// 注意:CDlgFileSend 的 PostNcDestroy 自删(CDialogBase 默认行为),
@@ -2825,7 +3089,6 @@ LRESULT CFileManagerDlg::OnRecvFileV2Chunk(WPARAM wParam, LPARAM /*lParam*/)
}
// 进度
BYTE* name = szBuffer + sizeof(FileChunkPacketV2);
dlg->UpdateProgress(CString((char*)name, (int)pkt->nameLength), FileProgressInfo(pkt));
delete payload;
@@ -2845,6 +3108,11 @@ LRESULT CFileManagerDlg::OnRecvFileV2Complete(WPARAM wParam, LPARAM /*lParam*/)
bool verifyOk = HandleFileCompleteV2((const char*)szBuffer, len, 0);
Mprintf("[FileManager] V2 文件校验%s\n", verifyOk ? "通过" : "失败");
if (len >= sizeof(FileCompletePacketV2)) {
CFilePreviewMgr::Instance().OnComplete(m_ContextObject,
(const FileCompletePacketV2*)szBuffer, verifyOk);
}
// 关闭对应进度框
auto it = m_FileRecvDlgs.find(transferID);
if (it != m_FileRecvDlgs.end()) {