Skip to content

PasteFerry (隔空贴): clipboard and file sync across macOS, Windows and Linux. Direct-first, end-to-end encrypted. Optional official access: no server to host. Independent self-hosting remains available.

32.5 KB
Raw Blame
// Package sync 是同步引擎:把本机剪贴板变化广播出去,
// 并把对端送来的内容落盘、写入本机剪贴板。
//
// 传输模型(M-1 实测后确定):按体积分流。
//   - 文本 / HTML:内容很小,直接内联在 offer 里,无需二次传输
//   - 图片、小于阈值的文件:随 offer 之后主动推送,对端可立即粘贴
//   - 超过阈值的文件:只发元数据,等用户在界面上点「拉取」
//
// 之所以不是"对方按下粘贴键才传",是因为 macOS 的剪贴板延迟渲染
// 无法感知粘贴动作(详见 spikes/results.md)。
package sync

import (
	"context"
	"crypto/rand"
	"encoding/hex"
	"errors"
	"fmt"
	"io"
	"log/slog"
	"os"
	"path/filepath"
	"sort"
	"strings"
	"sync"
	"sync/atomic"
	"time"

	"github.com/pion/webrtc/v4"

	"github.com/baiyuze/pasteferry/client-core/internal/cache"
	"github.com/baiyuze/pasteferry/client-core/internal/clipboard"
	"github.com/baiyuze/pasteferry/client-core/internal/clipfilter"
	"github.com/baiyuze/pasteferry/client-core/internal/config"
	"github.com/baiyuze/pasteferry/client-core/internal/imagepreview"
	"github.com/baiyuze/pasteferry/client-core/internal/pack"
	"github.com/baiyuze/pasteferry/client-core/internal/store"
	"github.com/baiyuze/pasteferry/client-core/internal/transport/p2p"
	pb "github.com/baiyuze/pasteferry/proto/gen/pasteferry/v1"
)

// 分片大小与发送缓冲的水位见 p2p.ChunkWriter。
const (
	// 预扫描的条目上限。超大目录全扫一遍会让复制动作明显卡顿,
	// 超限时只报概要,进度条退化为未知总量。
	maxScanEntries = 20000

	streamIdleTimeout = 2 * time.Minute
)

type Engine struct {
	log     *slog.Logger
	store   *store.Store
	cache   *cache.Cache
	watcher *clipboard.Watcher
	// favorites 是收藏另存的图片与文件,见 favorite.go。favMu 让收藏操作一个一个来,连点两下不会存两份
	favorites *cache.Cache
	favMu     sync.Mutex

	deviceID   string
	deviceName func() string
	loadConfig func() config.Config

	// 传输层
	send        func(deviceID string, msg *pb.PeerMessage) error
	openStream  func(deviceID, label string) (*webrtc.DataChannel, error)
	pairedPeers func() []string

	// 事件回传给界面
	onRecord            func(*pb.ClipRecord)
	onRemoved           func(clipID string)
	onProgress          func(*pb.TransferProgress)
	onReceive           func(ReceiveEvent)
	onClipboardResult   func(*pb.ClipboardWriteResult)
	onNotice            func(kind string)
	receiveStartTimeout time.Duration
	offerMu             sync.Mutex

	mu sync.Mutex
	// 正在接收中的流:stream_id -> 接收器
	incoming map[string]*receiver
	receives map[string]*receiveAttempt
	// 对端补发来的内容,收完后不写进剪贴板:clip_id 集合,见 PeerReady
	quiet map[string]bool

	// 没送达对端、等连接恢复后补发的内容,见 backlog.go
	backlog backlog
	// pushRetry 是「offer 已发出、数据没送到」的队列,连接恢复后重推,不受补发开关影响
	pushRetry        backlog
	policyGeneration atomic.Uint64
	// 上一次本机复制,用来认出同一次复制引起的重复变化,见 repeat.go
	recentCopy repeatGuard

	// 每次传输上一次上报进度的时间,用于节流,见 emitProgress
	progressMu   sync.Mutex
	lastProgress map[string]time.Time
}

type Options struct {
	Logger     *slog.Logger
	Store      *store.Store
	Cache      *cache.Cache
	Favorites  *cache.Cache
	Watcher    *clipboard.Watcher
	DeviceID   string
	DeviceName func() string
	LoadConfig func() config.Config
	Send       func(deviceID string, msg *pb.PeerMessage) error
	OpenStream func(deviceID, label string) (*webrtc.DataChannel, error)
	// PairedPeers 返回所有已配对设备,不论在线与否:连不上的记进待补发
	PairedPeers func() []string
	OnRecord    func(*pb.ClipRecord)
	// OnRemoved 在引擎自己删掉一条记录时调用(取消收藏时合并掉的原记录等)
	OnRemoved         func(clipID string)
	OnProgress        func(*pb.TransferProgress)
	OnReceive         func(ReceiveEvent)
	OnClipboardResult func(*pb.ClipboardWriteResult)
	// OnNotice 推一条给用户看的提示,kind 是固定代码(目前只有 clipboard_files_unreadable)
	OnNotice            func(kind string)
	ReceiveStartTimeout time.Duration
}

// NoticeClipboardFilesUnreadable:本机复制的文件全都读不到(压缩包预览、邮件附件、
// 网盘占位文件等虚拟路径),这次复制没有同步。界面据此提示用户,不然他们只会觉得「没反应」
const NoticeClipboardFilesUnreadable = "clipboard_files_unreadable"

func New(opts Options) *Engine {
	log := opts.Logger
	if log == nil {
		log = slog.Default()
	}
	return &Engine{
		log:                 log,
		store:               opts.Store,
		cache:               opts.Cache,
		favorites:           opts.Favorites,
		watcher:             opts.Watcher,
		deviceID:            opts.DeviceID,
		deviceName:          opts.DeviceName,
		loadConfig:          opts.LoadConfig,
		send:                opts.Send,
		openStream:          opts.OpenStream,
		pairedPeers:         opts.PairedPeers,
		onRecord:            opts.OnRecord,
		onRemoved:           opts.OnRemoved,
		onProgress:          opts.OnProgress,
		onReceive:           opts.OnReceive,
		onClipboardResult:   opts.OnClipboardResult,
		onNotice:            opts.OnNotice,
		receiveStartTimeout: opts.ReceiveStartTimeout,
		receives:            make(map[string]*receiveAttempt),
		incoming:            make(map[string]*receiver),
		quiet:               make(map[string]bool),
		lastProgress:        make(map[string]time.Time),
	}
}

// ─────────────────────── 本机复制 → 广播 ───────────────────────

// HandleClipboardChange 在本机剪贴板变化时调用。
func (e *Engine) HandleClipboardChange(ctx context.Context, snap clipboard.Snapshot) {
	generation := e.policyGeneration.Load()
	cfg := e.loadConfig()
	if !e.kindEnabled(cfg, snap.Kind) {
		e.log.Debug("该类型已在设置中关闭,跳过", "kind", snap.Kind)
		return
	}

	readCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
	defer cancel()

	content, err := e.watcher.Read(readCtx)
	if err != nil {
		if errors.Is(err, clipboard.ErrPermissionRequired) {
			// 授权缺失是常态而非异常:界面会引导用户去开,这里安静跳过
			e.log.Debug("尚未获得剪贴板授权,跳过本次变化")
			return
		}
		e.log.Warn("读取剪贴板失败", "err", err)
		return
	}

	e.log.Debug("已读取剪贴板内容",
		"kind", content.Kind, "文本长度", len(content.Text),
		"HTML长度", len(content.HTML), "图片字节", len(content.Image), "文件", content.Files)
	if e.recentCopy.seen(content, time.Now()) {
		e.log.Debug("刚复制过同样的内容,跳过")
		return
	}

	clip, err := e.recordOutgoing(content, cfg)
	if errors.Is(err, errRemotePlaceholder) {
		e.log.Debug("跳过远程软件的剪贴板占位文件")
		return
	}
	if err != nil {
		e.log.Warn("记录本机复制失败", "err", err)
		if errors.Is(err, errFilesUnreadable) && e.onNotice != nil {
			e.onNotice(NoticeClipboardFilesUnreadable)
		}
		return
	}

	e.emitRecord(clip)
	if generation != e.policyGeneration.Load() {
		return
	}
	e.offerToPeers(ctx, clip, cfg)
}

// recordOutgoing 把本机复制的内容落库。
var errRemotePlaceholder = errors.New("剪贴板仅包含远程软件占位文件")

// errFilesUnreadable:剪贴板里的文件路径全都打不开,多半是压缩包预览、邮件附件这类虚拟路径
var errFilesUnreadable = errors.New("剪贴板中的文件都不可访问")

func (e *Engine) recordOutgoing(c clipboard.Content, cfg config.Config) (store.Clip, error) {
	return e.recordOutgoingVia(c, cfg, "")
}

// recordOutgoingVia 与 recordOutgoing 相同,via 是内容经由的设备名(见 store.Clip.Via)。
func (e *Engine) recordOutgoingVia(c clipboard.Content, cfg config.Config, via string) (store.Clip, error) {
	if c.Kind == clipboard.KindFile && len(c.Files) > 0 {
		c.Files = clipfilter.UserFiles(c.Files)
		if len(c.Files) == 0 {
			return store.Clip{}, errRemotePlaceholder
		}
	}
	now := time.Now()
	clip := store.Clip{
		ID:               newID(),
		Status:           store.StatusReady,
		OriginDeviceID:   e.deviceID,
		OriginDeviceName: e.deviceName(),
		Outgoing:         true,
		Via:              via,
		CreatedAt:        now,
		ExpiresAt:        now.Add(cfg.HistoryTTL.Std()),
	}

	switch c.Kind {
	case clipboard.KindText, clipboard.KindHTML:
		clip.Kind = store.KindText
		clip.TextContent = c.Text
		if c.Kind == clipboard.KindHTML {
			clip.Kind = store.KindHTML
			clip.TextContent = c.HTML
			clip.TextPlain = c.Text
		}
		clip.TextPreview = preview(plainText(clip))
		clip.TotalSize = int64(len(clip.TextContent))

	case clipboard.KindImage:
		clip.Kind = store.KindImage
		clip.TotalSize = int64(len(c.Image))
		clip.TextPreview = fmt.Sprintf("图片 %s", humanBytes(clip.TotalSize))
		// 图片直接落盘,供对端拉取时复用
		rel, abs, err := e.cache.Dir(clip.ID)
		if err != nil {
			return clip, err
		}
		imgPath := filepath.Join(abs, "image.png")
		if err := os.WriteFile(imgPath, c.Image, 0o600); err != nil {
			return clip, err
		}
		clip.CachePath = rel
		clip.SourcePaths = []string{imgPath}
		clip.Items = []store.Item{{
			Name: "image.png", Size: clip.TotalSize, ContentType: "public.png",
		}}

	case clipboard.KindFile:
		clip.Kind = store.KindFile
		clip.SourcePaths = c.Files
		stats, err := pack.Scan(c.Files, maxScanEntries)
		if err != nil {
			e.log.Debug("预扫描未完成", "err", err)
		}
		clip.TotalSize = stats.Bytes
		for _, p := range c.Files {
			info, err := os.Stat(p)
			if err != nil {
				continue
			}
			clip.Items = append(clip.Items, store.Item{
				Name:  filepath.Base(p),
				Size:  info.Size(),
				IsDir: info.IsDir(),
			})
		}
		if len(clip.Items) == 0 {
			return clip, errFilesUnreadable
		}
		clip.TextPreview = describeItems(clip.Items)

	default:
		return clip, fmt.Errorf("不支持的剪贴板类型: %v", c.Kind)
	}

	clip.DetectLink() // 返回的记录随即推给界面
	if err := e.store.PutClip(clip); err != nil {
		return clip, err
	}
	return clip, nil
}

// buildOffer 决定这条内容是随即推送还是等对方来取。
func (e *Engine) buildOffer(clip store.Clip, cfg config.Config) *pb.ClipOffer {
	offer := &pb.ClipOffer{
		ClipId:        clip.ID,
		Kind:          pb.ClipKind(clip.Kind),
		TotalSize:     clip.TotalSize,
		CreatedAtUnix: clip.CreatedAt.Unix(),
	}
	for _, it := range clip.Items {
		offer.Items = append(offer.Items, &pb.ClipItem{
			Name: it.Name, Size: it.Size, IsDir: it.IsDir, ContentType: it.ContentType,
		})
	}

	switch clip.Kind {
	case store.KindText, store.KindHTML:
		// 文本体积小,直接内联,省掉一次往返
		offer.TextContent = clip.TextContent
		offer.PlainText = clip.TextPlain
		offer.WillPush = false
	default:
		// 超过阈值的不主动推,避免无谓占用带宽和对端磁盘
		offer.WillPush = clip.TotalSize <= cfg.AutoSyncThresholdBytes
	}
	return offer
}

func (e *Engine) kindEnabled(cfg config.Config, k clipboard.Kind) bool {
	switch k {
	case clipboard.KindText:
		return cfg.SyncText
	case clipboard.KindHTML:
		return cfg.SyncHTML
	case clipboard.KindImage:
		return cfg.SyncImage
	case clipboard.KindFile:
		return cfg.SyncFile
	default:
		return false
	}
}

// ─────────────────────── 对端消息处理 ───────────────────────

func (e *Engine) HandlePeerMessage(ctx context.Context, from string, msg *pb.PeerMessage) {
	switch m := msg.GetPayload().(type) {
	case *pb.PeerMessage_Offer:
		e.handleOffer(ctx, from, m.Offer)
	case *pb.PeerMessage_Fetch:
		go e.handleFetch(context.WithoutCancel(ctx), from, m.Fetch.GetClipId())
	case *pb.PeerMessage_Reject:
		e.handleReject(m.Reject)
	case *pb.PeerMessage_Header:
		e.handleHeader(from, m.Header)
	case *pb.PeerMessage_Done:
		e.handleDone(m.Done)
	}
}

func (e *Engine) handleOffer(ctx context.Context, from string, offer *pb.ClipOffer) {
	e.offerMu.Lock()
	defer e.offerMu.Unlock()
	policy := e.loadConfig()
	if !policy.SyncAllowed(from) || (offer.GetBacklog() && !policy.SyncBacklog) {
		return
	}
	if existing, err := e.store.GetClip(offer.GetClipId()); err == nil {
		// Offers are replayed after reconnect. Never erase a cache or an active
		// manual request, and never turn an old record into a new notification.
		if existing.OriginDeviceID != from || existing.Outgoing {
			return
		}
		if offer.GetWillPush() && existing.Status != store.StatusReady && existing.Status != store.StatusFetching {
			e.startAutomaticReceive(existing, offer.GetBacklog())
		}
		return
	}
	// Older clients can still announce UU placeholders. Ignore an all-placeholder
	// offer before it reaches history or the local clipboard. Mixed offers are
	// kept intact because their subsequent archive contains real user files too.
	if offer.GetKind() == pb.ClipKind(store.KindFile) && len(offer.GetItems()) > 0 {
		onlyPlaceholders := true
		for _, item := range offer.GetItems() {
			if !clipfilter.RemotePlaceholder(item.GetName()) {
				onlyPlaceholders = false
				break
			}
		}
		if onlyPlaceholders {
			return
		}
	}
	cfg := e.loadConfig()
	now := time.Now()

	clip := store.Clip{
		ID:               offer.GetClipId(),
		Kind:             store.Kind(offer.GetKind()),
		OriginDeviceID:   from,
		OriginDeviceName: e.peerName(from),
		Outgoing:         false,
		TotalSize:        offer.GetTotalSize(),
		TextContent:      offer.GetTextContent(),
		TextPlain:        offer.GetPlainText(),
		CreatedAt:        time.Unix(offer.GetCreatedAtUnix(), 0),
		ExpiresAt:        now.Add(cfg.HistoryTTL.Std()),
	}
	for _, it := range offer.GetItems() {
		clip.Items = append(clip.Items, store.Item{
			Name: it.GetName(), Size: it.GetSize(),
			IsDir: it.GetIsDir(), ContentType: it.GetContentType(),
		})
	}

	switch {
	case clip.Kind == store.KindText || clip.Kind == store.KindHTML:
		// 文本随 offer 一起到了,立即可用
		clip.Status = store.StatusReady
		clip.TextPreview = preview(plainText(clip))
	case offer.GetWillPush():
		// 对端马上会推流过来,先记为接收中
		clip.Status = store.StatusFetching
		clip.TextPreview = describeItems(clip.Items)
	default:
		// 超过阈值,等用户在界面上点拉取
		clip.Status = store.StatusRemoteOnly
		clip.TextPreview = describeItems(clip.Items)
	}

	clip.DetectLink() // 写入后随即推给界面
	if err := e.store.PutClip(clip); err != nil {
		e.log.Warn("保存对端记录失败", "err", err)
		return
	}
	backlog := offer.GetBacklog()
	if clip.Status == store.StatusFetching {
		e.startAutomaticReceive(clip, backlog)
	} else {
		e.emitRecord(clip)
	}
	if clip.Status == store.StatusRemoteOnly && !backlog {
		e.receiveEvent(clip, ReceivePending, nil)
	}
	e.log.Info("收到对端剪贴板内容",
		"clip", clip.ID, "kind", clip.Kind, "status", clip.Status, "from", from, "补发", backlog)

	// 文本类内容可以马上写进剪贴板;补发来的是旧内容,不覆盖本机剪贴板
	if clip.Status == store.StatusReady && cfg.AutoApplyToClipboard && !backlog {
		if err := e.applyToClipboard(ctx, clip); err != nil {
			e.log.Warn("写入剪贴板失败", "err", err)
		}
	}
}

// handleFetch 响应对端的拉取请求:校验源文件仍在,然后开流发送。
func (e *Engine) handleFetch(ctx context.Context, from, clipID string) {
	clip, err := e.store.GetClip(clipID)
	if err != nil {
		e.reject(from, clipID, "记录不存在")
		return
	}
	if err := e.pushTo(ctx, from, clip); err != nil {
		e.log.Warn("响应拉取失败", "clip", clipID, "err", err)
	}
}

func (e *Engine) handleReject(r *pb.FetchReject) {
	e.failReceive(r.GetClipId(), nil, errors.New(r.GetReason()))
}

func (e *Engine) reject(to, clipID, reason string) {
	_ = e.send(to, &pb.PeerMessage{
		Payload: &pb.PeerMessage_Reject{Reject: &pb.FetchReject{
			ClipId: clipID, Reason: reason,
		}},
	})
}

// ─────────────────────── 发送 ───────────────────────

// pushTo 把某条记录的内容流式发给指定对端。
func (e *Engine) pushTo(ctx context.Context, peer string, clip store.Clip) error {
	paths, err := e.sourcePaths(clip)
	if err != nil {
		e.reject(peer, clip.ID, err.Error())
		return err
	}

	streamID := newID()
	packaging := pb.Packaging_PACKAGING_TAR
	if len(paths) == 1 {
		if info, err := os.Stat(paths[0]); err == nil && !info.IsDir() {
			packaging = pb.Packaging_PACKAGING_RAW
		}
	}

	// 先发头,对端据此准备接收;随后的裸字节都属于这条流
	if err := e.send(peer, &pb.PeerMessage{
		Payload: &pb.PeerMessage_Header{Header: &pb.TransferHeader{
			ClipId:      clip.ID,
			StreamId:    streamID,
			TotalBytes:  clip.TotalSize,
			Compression: pb.Compression_COMPRESSION_ZSTD,
			Packaging:   packaging,
		}},
	}); err != nil {
		return fmt.Errorf("发送传输头: %w", err)
	}

	dc, err := e.openStream(peer, streamID)
	if err != nil {
		return fmt.Errorf("打开数据流: %w", err)
	}

	opened := make(chan struct{})
	dc.OnOpen(func() { close(opened) })
	select {
	case <-opened:
	case <-time.After(30 * time.Second):
		dc.Close()
		return errors.New("数据流打开超时")
	case <-ctx.Done():
		dc.Close()
		return ctx.Err()
	}

	start := time.Now()
	w := p2p.NewChunkWriter(dc, func(sent int64) {
		e.emitProgress(clip.ID, sent, clip.TotalSize, start)
	})

	var packErr error
	if packaging == pb.Packaging_PACKAGING_RAW {
		packErr = packRaw(w, paths[0])
	} else {
		packErr = pack.Pack(w, paths)
	}
	if flushErr := w.Flush(); packErr == nil {
		packErr = flushErr
	}

	// 等发送缓冲排空再关闭,否则尾部数据会被丢弃
	if drainErr := w.WaitDrained(ctx, 60*time.Second); packErr == nil {
		packErr = drainErr
	}
	dc.Close()
	e.forgetProgress(clip.ID)

	ok := packErr == nil
	errMsg := ""
	if packErr != nil {
		errMsg = packErr.Error()
	}
	_ = e.send(peer, &pb.PeerMessage{
		Payload: &pb.PeerMessage_Done{Done: &pb.TransferDone{
			ClipId: clip.ID, StreamId: streamID, Ok: ok, Error: errMsg,
		}},
	})

	if packErr != nil {
		return packErr
	}
	e.log.Info("内容已发送",
		"clip", clip.ID, "to", peer, "字节", w.Sent(), "耗时", time.Since(start).Round(time.Millisecond))
	return nil
}

// sourcePaths 找出这条记录当前可用的源路径。
//
// 优先用原始位置(本机复制的内容),其次用缓存(从对端收来的内容)。
// 两者都没有时说明源文件已被移动或删除。
func (e *Engine) sourcePaths(clip store.Clip) ([]string, error) {
	if len(clip.SourcePaths) > 0 {
		var alive []string
		for _, p := range clip.SourcePaths {
			if _, err := os.Stat(p); err == nil {
				alive = append(alive, p)
			}
		}
		if len(alive) > 0 {
			return alive, nil
		}
	}
	if clip.CachePath != "" && e.cache.Exists(clip.CachePath) {
		return e.cache.Entries(clip.CachePath)
	}
	return nil, errors.New("源文件已不存在")
}

func packRaw(w io.Writer, path string) error {
	f, err := os.Open(path)
	if err != nil {
		return err
	}
	defer f.Close()
	// 单文件也走 zstd,与 tar 分支保持一致的解码路径
	return pack.Pack(w, []string{path})
}

// ─────────────────────── 接收 ───────────────────────

// receiver 承接一条进行中的数据流。
type receiver struct {
	clipID      string
	streamID    string
	from        string
	total       int64
	received    int64
	pipeW       *io.PipeWriter
	done        chan error
	start       time.Time
	attempt     *receiveAttempt
	closeStream func()
	bound       bool
}

func (e *Engine) handleHeader(from string, h *pb.TransferHeader) {
	clip, err := e.store.GetClip(h.GetClipId())
	if err != nil || clip.Outgoing || clip.OriginDeviceID != from || clip.Status != store.StatusFetching {
		return
	}
	e.mu.Lock()
	a := e.receives[clip.ID]
	if a == nil || a.streamID != "" {
		e.mu.Unlock()
		return
	}
	a.streamID = h.GetStreamId()
	// A fresh directory per stream prevents an old failed unpacker from
	// racing a retry or leaving removed files in the retried archive.
	rel, abs, release, err := e.cache.LeaseDir(clip.ID + "-" + newID())
	if err != nil {
		e.mu.Unlock()
		e.failReceive(clip.ID, a, err)
		return
	}
	pr, pw := io.Pipe()
	r := &receiver{clipID: clip.ID, streamID: h.GetStreamId(), from: from,
		total: h.GetTotalBytes(), pipeW: pw, done: make(chan error, 1), start: time.Now(), attempt: a}
	if e.incoming == nil {
		e.incoming = make(map[string]*receiver)
	}
	e.incoming[r.streamID] = r
	e.mu.Unlock()
	go func() {
		defer release()
		defer pr.Close()
		tops, err := pack.Unpack(pr, abs)
		if err != nil {
			e.failReceive(r.clipID, a, err)
			_ = e.cache.Remove(rel)
			r.done <- err
			return
		}
		if !e.finishReceive(r, rel, tops) {
			_ = e.cache.Remove(rel)
		}
		r.done <- nil
	}()
}

// HandlePeerStream 接管对端新开的数据通道。
func (e *Engine) HandlePeerStream(from, label string, stream *p2p.Stream) {
	e.mu.Lock()
	r := e.incoming[label]
	e.mu.Unlock()

	if r == nil {
		// 头还没到就先收到了流。等一小会儿,控制通道与数据通道是两条独立的路,
		// 到达顺序并不保证。
		go func() {
			deadline := time.Now().Add(10 * time.Second)
			for time.Now().Before(deadline) {
				time.Sleep(50 * time.Millisecond)
				e.mu.Lock()
				r = e.incoming[label]
				e.mu.Unlock()
				if r != nil {
					e.bindStream(r, stream)
					return
				}
			}
			e.log.Warn("收到无对应传输头的数据流,已丢弃", "stream", label, "from", from)
			stream.Close()
		}()
		return
	}
	e.bindStream(r, stream)
}

func (e *Engine) bindStream(r *receiver, stream *p2p.Stream) {
	e.mu.Lock()
	if e.receives[r.clipID] != r.attempt || r.bound {
		e.mu.Unlock()
		stream.Close()
		return
	}
	r.bound = true
	r.closeStream = func() { stream.Close() }
	r.attempt.timer.Reset(streamIdleTimeout)
	e.mu.Unlock()
	go func() {
		defer r.pipeW.Close()
		var received int64
		for chunk := range stream.Chunks() {
			if _, err := r.pipeW.Write(chunk); err != nil {
				stream.Close()
				return
			}
			received += int64(len(chunk))
			e.mu.Lock()
			if e.receives[r.clipID] != r.attempt {
				e.mu.Unlock()
				stream.Close()
				return
			}
			r.received = received
			r.attempt.timer.Reset(streamIdleTimeout)
			e.mu.Unlock()
			e.emitProgress(r.clipID, received, r.total, r.start)
		}
	}()
}

func (e *Engine) finishReceive(r *receiver, cacheRel string, tops []string) bool {
	e.mu.Lock()
	a := r.attempt
	if a == nil {
		a = e.receives[r.clipID]
	} // also used by the preview integration test
	if a == nil || e.receives[r.clipID] != a {
		e.mu.Unlock()
		return false
	}
	if err := e.store.SetClipCache(r.clipID, cacheRel, max64(r.total, r.received)); err != nil {
		e.mu.Unlock()
		e.failReceive(r.clipID, a, err)
		return false
	}
	quiet := e.quiet[r.clipID]
	e.retireReceiveLocked(r.clipID, a)
	e.mu.Unlock()
	e.forgetProgress(r.clipID)
	clip, err := e.store.GetClip(r.clipID)
	if err != nil {
		return false
	}
	e.emitRecord(clip)
	e.completePendingFavorites(clip)
	result := &pb.ClipboardWriteResult{ClipId: clip.ID, Outcome: pb.ClipboardWriteOutcome_CLIPBOARD_WRITE_OUTCOME_PRESERVED}
	if cfg := e.loadConfig(); cfg.AutoApplyToClipboard && !quiet && (a.manual || cfg.SyncAllowed(clip.OriginDeviceID) && !cfg.MediaAutoApplyDisabled) {
		ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
		defer cancel()
		if a.manual {
			if a.revision != nil {
				result = e.writeClipboard(ctx, clip, a.revision)
			}
		} else {
			result = e.writeClipboard(ctx, clip, nil)
		}
	}
	if !a.preview {
		e.clipboardResult(result)
		if a.manual {
			e.receiveEvent(clip, ReceiveCompleted, result)
		}
	}
	return true
}

func (e *Engine) handleDone(d *pb.TransferDone) {
	if d.GetOk() {
		return
	}
	e.mu.Lock()
	a := e.receives[d.GetClipId()]
	matches := a != nil && a.streamID == d.GetStreamId()
	e.mu.Unlock()
	if matches {
		e.failReceive(d.GetClipId(), a, errors.New(d.GetError()))
	}
}

// ─────────────────────── 对外操作 ───────────────────────

// Fetch 主动拉取一条仅有元数据的记录。
func (e *Engine) Fetch(ctx context.Context, clipID string) error {
	return e.fetch(ctx, clipID, false)
}

// FetchForPreview 下载旧图片只用于查看,不能覆盖用户刚复制的内容。
func (e *Engine) FetchForPreview(ctx context.Context, clipID string) error {
	return e.fetch(ctx, clipID, true)
}

// ApplyToClipboard 把某条已就绪的记录写入本机剪贴板。
func (e *Engine) ApplyToClipboard(ctx context.Context, clipID string) error {
	return e.ApplyToClipboardAs(ctx, clipID, false)
}

// ApplyToClipboardAs 与 ApplyToClipboard 相同;plain 时文字与网页格式只写纯文本。
func (e *Engine) ApplyToClipboardAs(ctx context.Context, clipID string, plain bool) error {
	clip, err := e.store.GetClip(clipID)
	if err != nil {
		return err
	}
	if plain && (clip.Kind == store.KindHTML || clip.Kind == store.KindText) {
		clip.TextContent, clip.Kind = plainText(clip), store.KindText
	}
	result := e.writeClipboard(ctx, clip, nil)
	e.clipboardResult(result)
	if result.Outcome == pb.ClipboardWriteOutcome_CLIPBOARD_WRITE_OUTCOME_FAILED {
		return errors.New(result.Error)
	}
	return nil
}

func (e *Engine) applyToClipboard(ctx context.Context, clip store.Clip) error {
	result := e.writeClipboard(ctx, clip, nil)
	if result.Outcome == pb.ClipboardWriteOutcome_CLIPBOARD_WRITE_OUTCOME_FAILED {
		return errors.New(result.Error)
	}
	return nil
}

func (e *Engine) clipboardContent(clip store.Clip) (clipboard.Content, error) {
	var content clipboard.Content

	switch clip.Kind {
	case store.KindText:
		content = clipboard.Content{Kind: clipboard.KindText, Text: clip.TextContent}
	case store.KindHTML:
		content = clipboard.Content{
			Kind: clipboard.KindHTML, HTML: clip.TextContent, Text: plainText(clip),
		}
	case store.KindImage, store.KindFile:
		paths, err := e.localPaths(clip)
		if err != nil {
			return content, err
		}
		if clip.Kind == store.KindImage && len(paths) == 1 {
			data, err := os.ReadFile(paths[0])
			if err == nil {
				content = clipboard.Content{Kind: clipboard.KindImage, Image: data}
				break
			}
		}
		content = clipboard.Content{Kind: clipboard.KindFile, Files: paths}
	default:
		return content, fmt.Errorf("不支持写入剪贴板的类型: %v", clip.Kind)
	}

	return content, nil
}

// ImagePreview 解析一条记录里第 index 张图片在本机的位置,不拉取文件、不写剪贴板。
// 剪贴板图片只有一张;文件记录按文件名排序,只看其中的图片文件,不进文件夹。
// 返回界面可以直接解码的路径(HEIC 等格式是转换出来的 PNG)、文件名(剪贴板图片为空)
// 与这条记录在本机能预览的图片数。
func (e *Engine) ImagePreview(_ context.Context, clipID string, index int) (path, name string, count int, err error) {
	clip, err := e.store.GetClip(clipID)
	if err != nil {
		return "", "", 0, errors.New("找不到这条记录")
	}
	if imagepreview.ImageCount(clip) == 0 {
		return "", "", 0, errors.New("这条记录里没有能预览的图片")
	}
	if clip.Status != store.StatusReady {
		return "", "", 0, errors.New("图片尚未下载或已经过期")
	}
	paths, err := e.localPaths(clip)
	if err != nil {
		return "", "", 0, errors.New("图片已不在本机,可能已被清理")
	}
	var images []string
	for _, p := range paths {
		info, err := os.Stat(p)
		if err != nil || !info.Mode().IsRegular() {
			continue
		}
		if clip.Kind == store.KindImage || imagepreview.Previewable(p) {
			images = append(images, p)
		}
	}
	if len(images) == 0 || clip.Kind == store.KindImage && len(images) != 1 {
		return "", "", 0, errors.New("图片已不在本机,可能已被清理")
	}
	if clip.Kind == store.KindImage {
		// 剪贴板图片收发时统一存成 PNG,界面能直接解码
		return images[0], "", 1, nil
	}
	sort.Slice(images, func(i, j int) bool { return filepath.Base(images[i]) < filepath.Base(images[j]) })
	if index < 0 || index >= len(images) {
		index = 0
	}
	path, err = imagepreview.Prepare(images[index])
	if err != nil {
		return "", "", 0, err
	}
	return path, filepath.Base(images[index]), len(images), nil
}

// localPaths 返回这条记录在本机可用的实际路径。
func (e *Engine) localPaths(clip store.Clip) ([]string, error) {
	if clip.Favorite {
		// 收藏另存在收藏目录里;那里的东西被用户手动删掉了,才退回原来的位置
		if clip.CachePath != "" && e.favorites != nil && e.favorites.Exists(clip.CachePath) {
			return e.favorites.Entries(clip.CachePath)
		}
	} else if clip.CachePath != "" && e.cache.Exists(clip.CachePath) {
		return e.cache.Entries(clip.CachePath)
	}
	if len(clip.SourcePaths) > 0 {
		var alive []string
		for _, p := range clip.SourcePaths {
			if _, err := os.Stat(p); err == nil {
				alive = append(alive, p)
			}
		}
		if len(alive) > 0 {
			return alive, nil
		}
	}
	return nil, errors.New("内容已不在本机(可能已过期被清理)")
}

// ─────────────────────── 辅助 ───────────────────────

func (e *Engine) emitRecord(clip store.Clip) {
	if e.onRecord != nil {
		e.onRecord(recordProto(clip))
	}
}

func recordProto(clip store.Clip) *pb.ClipRecord {
	items := make([]*pb.ClipItem, 0, len(clip.Items))
	for _, it := range clip.Items {
		items = append(items, &pb.ClipItem{
			Name: it.Name, Size: it.Size, IsDir: it.IsDir, ContentType: it.ContentType,
		})
	}
	r := &pb.ClipRecord{
		Id:               clip.ID,
		Kind:             pb.ClipKind(clip.Kind),
		Status:           pb.ClipStatus(clip.Status),
		OriginDeviceId:   clip.OriginDeviceID,
		OriginDeviceName: clip.OriginDeviceName,
		Outgoing:         clip.Outgoing,
		Items:            items,
		TotalSize:        clip.TotalSize,
		TextPreview:      clip.TextPreview,
		CreatedAtUnix:    clip.CreatedAt.Unix(),
		ExpiresAtUnix:    clip.ExpiresAt.Unix(),
		Error:            clip.Error,
		ImageCount:       imagepreview.ImageCount(clip),
		Favorite:         clip.Favorite,
		Favorited:        clip.Favorited,
		IsLink:           clip.IsLink,
		ViaName:          clip.Via,
	}
	if clip.Favorite {
		r.ExpiresAtUnix = 0 // 收藏不会过期
		r.FavoritedAtUnix = clip.FavoritedAt.Unix()
		r.Alias = clip.Alias // 取消收藏后别名还留在库里,只是不再显示
	}
	return r
}

// progressInterval 是同一次传输两次进度上报之间的最小间隔。
//
// 进度原本按数据块上报,一个大文件会产生上万条事件。事件队列每个订阅者只缓冲 64 条,
// 满了就丢弃新事件——「传输完成」那条记录更新也可能被挤掉,界面上的进度条就永远停不下来。
const progressInterval = 200 * time.Millisecond

func (e *Engine) emitProgress(clipID string, sent, total int64, start time.Time) {
	if e.onProgress == nil {
		return
	}
	done := total > 0 && sent >= total
	now := time.Now()
	e.progressMu.Lock()
	last, seen := e.lastProgress[clipID]
	if !done && seen && now.Sub(last) < progressInterval {
		e.progressMu.Unlock()
		return
	}
	e.lastProgress[clipID] = now
	e.progressMu.Unlock()
	elapsed := time.Since(start).Seconds()
	var rate float64
	if elapsed > 0 {
		rate = float64(sent) / elapsed
	}
	e.onProgress(&pb.TransferProgress{
		ClipId: clipID, Transferred: sent, Total: total, BytesPerSecond: rate,
	})
}

// forgetProgress 在一次传输结束后清掉它的节流记录。
func (e *Engine) forgetProgress(clipID string) {
	e.progressMu.Lock()
	delete(e.lastProgress, clipID)
	e.progressMu.Unlock()
}

// peerName 取对端设备名用于展示;查不到就退回 ID。
func (e *Engine) peerName(deviceID string) string {
	devices, err := e.store.ListDevices()
	if err != nil {
		return deviceID
	}
	for _, d := range devices {
		if d.ID == deviceID {
			return d.Name
		}
	}
	return deviceID
}

func newID() string {
	b := make([]byte, 12)
	if _, err := rand.Read(b); err != nil {
		return fmt.Sprintf("clip-%d", time.Now().UnixNano())
	}
	return hex.EncodeToString(b)
}

func preview(s string) string {
	s = strings.TrimSpace(strings.ReplaceAll(s, "\n", " "))
	const limit = 120
	if len(s) <= limit {
		return s
	}
	// 按 rune 截断,避免把多字节字符切一半
	runes := []rune(s)
	if len(runes) <= limit {
		return s
	}
	return string(runes[:limit]) + "…"
}

func describeItems(items []store.Item) string {
	switch len(items) {
	case 0:
		return ""
	case 1:
		return items[0].Name
	default:
		return fmt.Sprintf("%s 等 %d 项", items[0].Name, len(items))
	}
}

func humanBytes(n int64) string {
	const unit = 1024
	if n < unit {
		return fmt.Sprintf("%d B", n)
	}
	div, exp := int64(unit), 0
	for v := n / unit; v >= unit; v /= unit {
		div *= unit
		exp++
	}
	return fmt.Sprintf("%.1f %cB", float64(n)/float64(div), "KMGTPE"[exp])
}

func max64(a, b int64) int64 {
	if a > b {
		return a
	}
	return b
}