Files
SimpleRemoter/server/2015Remote/FilePreview.h
T
yuanyuanxiangandQoder 4bc51d2498 Feature: add a remote Open command with large-file confirmation
Add an Open item atop the remote file list context menu: a single file is
pulled back and previewed through the existing flow, a single folder
navigates into its subdirectory, and multi-selection disables it. Files
over the 8 MiB preview limit ask for confirmation; once confirmed the
explicit-open path caps the first-packet size gate at the confirmed size
and relaxes the hash query, total timeout and cache eviction so even very
large files transfer and open. When preview is disabled the explicit Open
shows a message instead of doing nothing. Double-click preview behavior is
unchanged. Localize the new menu item and dialogs in en_US/zh_TW/de_DE.

Co-Authored-By: Qoder
2026-12-05 19:55:51 +01:00

221 lines
9.5 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// FilePreview.h — 文件管理器双击预览:设备传输闸门、平铺缓存、索引与接收挂钩
//
// 设计见 docs/FilePreview_Design.md。本文件只负责“非 UI”部分:
// - DeviceTransferGate:预览与 MCP 三个文件传输入口共用的设备级原子闸门;
// - 平铺缓存/索引:Preview\<clientKey>\<hash16>_<basename> + index.txt;
// - 接收钩子:ObserveChunk / OnComplete(Windows 流式子连接与 Unix 同连接两处调用);
// - 结果通过 WM_PREVIEW_RESULT 投递回文件管理器对话框,由 UI 线程确认并打开。
#pragma once
#include "StdAfx.h"
#include <common/file_upload.h>
#include <atomic>
#include <chrono>
#include <map>
#include <mutex>
#include <string>
#include <vector>
class CONTEXT_OBJECT;
// 预览完成/失败:lParam 是 new 出来的 CFilePreviewMgr::Result,由对话框 delete。
#define WM_PREVIEW_RESULT (WM_USER + 0x306)
// 哈希查询响应:lParam 是 new 出来的 FilePreviewHashResult,由对话框 delete。
#define WM_PREVIEW_HASH_RESP (WM_USER + 0x307)
// COMMAND_FILE_HASH 响应的解析结果(对话框 UI 线程消费)。
struct FilePreviewHashResult {
std::string path; // 请求里原样回显的路径(GBK)
uint32_t status = 0;
uint32_t err = 0;
uint64_t size = 0;
uint64_t mtimeMs = 0;
std::string sha256; // 64 位小写十六进制;status != FILE_HASH_OK 时为空
};
// 设备级文件传输闸门:预览与 MCP 的 download/read、upload、C2C 都在同一临界区认领设备。
// C2C 需要原子认领 src+dst 两个键。owner 只用于释放校验,避免旧会话误放新会话。
class DeviceTransferGate
{
public:
static DeviceTransferGate& Instance();
bool TryClaim(uint64_t key, uint64_t owner);
bool TryClaimPair(uint64_t a, uint64_t b, uint64_t owner);
void Release(uint64_t key, uint64_t owner);
void ReleasePair(uint64_t a, uint64_t b, uint64_t owner);
bool IsBusy(uint64_t key) const;
private:
DeviceTransferGate() {}
mutable std::mutex m_mtx;
std::map<uint64_t, uint64_t> m_owner;
};
class CFilePreviewMgr
{
public:
enum PrepareResult
{
PrepareError = 0,
PrepareCached = 1, // outPath 是可直接打开的本地缓存
PrepareTransfer = 2, // outPath 是本次预览的 tempDir(需要下发 CMD_DOWN_FILES_V2)
};
struct Result
{
bool ok = false;
bool cached = false;
std::string localPath; // 成功时的本地完整路径
std::string remotePath; // 远程完整路径(GBK 原始字节)
std::string message; // 失败原因(已翻译前的 key/格式化文本)
uint64_t size = 0;
std::string sha256; // 64 位小写十六进制,可能为空
};
static CFilePreviewMgr& Instance();
// UI 线程调用。sha256 为空表示 P1(没有预取哈希,按 size+mtime 命中)。
// 失败时 error 给出可直接展示的文本。
PrepareResult Prepare(uint64_t clientID, const std::string& clientKey,
const std::string& remotePath, const std::string& basename,
uint64_t size, uint64_t mtimeMs, const std::string& sha256,
HWND notifyHwnd, std::string& outPath, std::string& error,
std::string* outSha = nullptr, bool allowLarge = false);
// UI 线程:对话框关闭时放弃本窗口的所有预览请求。
void CancelForHwnd(HWND hwnd);
// UI 线程:用明确的失败原因结束本窗口当前请求(如客户端 TOKEN_DOWNLOAD_ERROR)。
void FailForHwnd(HWND hwnd, const std::string& message);
// 接收钩子(任意线程)。返回 false 表示该 chunk 属于已失败/越界的预览,调用方必须
// 取消连接并跳过写盘;返回 true 时原流程不变(非预览包也返回 true)。
bool ObserveChunk(CONTEXT_OBJECT* ctx, const FileChunkPacketV2* pkt,
const char* name, ULONG len, uint64_t* transferID);
// Windows 流式路径:创建 CDlgFileSend 后把进度框 HWND 绑到请求(超时取消用)。
void BindProgressWindow(CONTEXT_OBJECT* ctx, HWND hwnd);
// 完成包:两条接收路径在 HandleFileCompleteV2 之后调用。幂等。
void OnComplete(CONTEXT_OBJECT* ctx, const FileCompletePacketV2* pkt, bool verifyOk);
// UI 线程:确认(可执行文件)并 ShellExecute 打开。成功返回 true。
static bool OpenLocalFile(HWND owner, const std::string& localPath,
const std::string& remotePath, uint64_t size,
const std::string& sha256);
static void PostResult(HWND hwnd, Result* r);
// 供日志/测试:实际使用的预览根目录(GBK),失败时为空。
static std::string RootDir();
private:
struct Meta
{
std::string remotePath;
uint64_t size = 0;
uint64_t mtimeMs = 0;
std::string sha256;
std::string localName;
uint64_t lastUsed = 0;
};
struct Request
{
enum State { WaitFirst, Transferring, Done, Failed, Abandoned };
uint64_t id = 0; // 随机请求 ID,同时是闸门 owner
uint64_t gateKey = 0; // 设备闸门键
uint64_t clientID = 0;
uint64_t transferID = 0;
uint64_t size = 0;
uint64_t mtimeMs = 0;
bool allowLarge = false; // 显式"打开":放宽大小闸门/总超时,并保护本次缓存不被淘汰
std::string clientKey;
std::string clientDir;
std::string remotePath;
std::string basename;
std::string sha256; // P2 预取哈希(P1 为空)
std::string tempDir;
std::string recvName; // 首包实际回填的完整路径
HWND notifyHwnd = nullptr;
HWND progressHwnd = nullptr;
CONTEXT_OBJECT* ctx = nullptr;
State state = WaitFirst;
std::chrono::steady_clock::time_point startAt;
std::chrono::steady_clock::time_point lastDataAt;
};
struct FinalizeJob
{
uint64_t requestID = 0;
std::string clientDir;
std::string remotePath;
std::string basename;
std::string tempDir;
std::string recvName;
uint64_t size = 0;
uint64_t mtimeMs = 0;
bool allowLarge = false;
std::string requestedSha;
std::string packetSha;
HWND notifyHwnd = nullptr;
};
CFilePreviewMgr();
CFilePreviewMgr(const CFilePreviewMgr&) = delete;
CFilePreviewMgr& operator=(const CFilePreviewMgr&) = delete;
void WatchdogLoop();
void CheckTimeoutsLocked(std::chrono::steady_clock::time_point now);
void FailLocked(Request& req, const std::string& message);
void PostResultLocked(const Request& req, bool ok, const std::string& localPath,
const std::string& message);
void CleanupRequestLocked(Request& req);
void TombstoneLocked(const std::string& tempDir);
bool IsTombstonedLocked(const std::string& name) const;
Request* FindByTransferLocked(CONTEXT_OBJECT* ctx, uint64_t transferID);
Request* FindByPrefixLocked(const std::string& name);
static void FinalizeThread(FinalizeJob job);
// ---- 缓存/索引 ----
static std::string ClientDir(const std::string& clientKey);
static std::string IndexPath(const std::string& clientDir);
static bool EnsureDirA(const std::string& dir);
static bool LoadIndex(const std::string& clientDir, std::vector<Meta>& out);
static bool SaveIndex(const std::string& clientDir, const std::vector<Meta>& v);
static bool FindByPath(const std::vector<Meta>& v, const std::string& remotePath,
uint64_t size, uint64_t mtimeMs, Meta& out);
static bool FindBySha(const std::vector<Meta>& v, const std::string& sha256, Meta& out);
static bool VerifyLocalFile(const std::string& path, uint64_t size, const std::string& sha256);
static std::string MakeLocalName(const std::string& sha256, const std::string& basename,
const std::vector<Meta>& index,
const std::string& remotePath);
static bool WriteEmptyFile(const std::string& path);
static void EnforceCacheLimits(const std::string& clientDir, std::vector<Meta>& index,
const std::string& protectName = std::string());
static bool MoveOrCopy(const std::string& from, const std::string& to);
static void RemoveTempDir(const std::string& tempDir);
static std::string SanitizeBaseName(const std::string& name);
static std::string HexLower(const BYTE* data, size_t len);
static std::string RandomHex(size_t bytes);
static uint64_t Fnv1a64(const std::string& s);
static bool IsSingleFileUnder(const std::string& tempDir, const std::string& fullName);
static bool IsExecutableExtension(const std::string& path);
static bool IsGbkRepresentable(const std::wstring& w);
static std::string WideToGbk(const std::wstring& w);
static std::wstring GbkToWide(const std::string& s);
static std::string GbkToUtf8(const std::string& s);
static std::string Utf8ToGbk(const std::string& s);
static std::string PctEncode(const std::string& s);
static std::string PctDecode(const std::string& s);
static bool HashFileSha256(const std::string& path, BYTE out[32]);
std::mutex m_mtx;
std::vector<Request> m_reqs;
std::map<std::string, std::chrono::steady_clock::time_point> m_tombstones;
};