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.

17.6 KB
Raw Blame
// Package config 管理 daemon 的持久化配置与数据目录布局。
package config

import (
	"encoding/json"
	"errors"
	"fmt"
	"io/fs"
	"net/url"
	"os"
	"path/filepath"
	"runtime"
	"time"
)

// Config 是用户可调的全部设置。字段与 proto 的 pasteferry.v1.Config 一一对应。
type Config struct {
	// Version 是配置文件的格式版本,见 migrate。
	Version    int    `json:"config_version"`
	DeviceID   string `json:"device_id"`
	DeviceName string `json:"device_name"`
	// SignalingURL 是信令服务器地址。可以为空:同一局域网里的设备不需要服务器,
	// 只有跨网络同步时才要填。
	SignalingURL       string `json:"signaling_url"`
	ServiceMode        string `json:"service_mode,omitempty"`
	CustomSignalingURL string `json:"custom_signaling_url,omitempty"`
	OfficialNoticeAck  string `json:"official_notice_ack,omitempty"`

	// 小于此值的内容在复制时自动推送给对端;大于则只同步元数据,
	// 等用户在 UI 里手动拉取。这是 M-1 否决纯懒模式后的折中点。
	AutoSyncThresholdBytes int64 `json:"auto_sync_threshold_bytes"`

	HistoryTTL Duration `json:"history_ttl"` // 历史记录元数据保留期
	CacheTTL   Duration `json:"cache_ttl"`   // 已落盘内容的保留期

	// Sync controls affect automatic clipboard sharing, not local history or Send Files.
	RealtimeSyncDisabled bool     `json:"realtime_sync_disabled,omitempty"`
	SyncBacklog          bool     `json:"sync_backlog,omitempty"`
	SyncDisabledPeers    []string `json:"sync_disabled_peers,omitempty"`

	SyncText  bool `json:"sync_text"`
	SyncHTML  bool `json:"sync_html"`
	SyncImage bool `json:"sync_image"`
	SyncFile  bool `json:"sync_file"`

	AutoApplyToClipboard bool `json:"auto_apply_to_clipboard"`
	LaunchAtLogin        bool `json:"launch_at_login"`

	// OnlyOwnSTUN 只用自己的服务器探测网络出口。公共 STUN 服务器能看到本机的公网 IP
	// (与任何 WebRTC 应用一样,看不到内容),介意的用户可以关掉;代价是多出口网络里
	// 可能探测不全,直连机会变小。
	OnlyOwnSTUN bool `json:"only_own_stun"`

	// Language 是界面语言:空字符串跟随系统,否则为 "zh-Hans"、"zh-Hant-TW"、"zh-Hant-HK"、"en"、"ja" 之一。
	// 托盘菜单(Windows)也按它显示
	Language string `json:"language,omitempty"`

	// LANDisabled 关掉局域网发现:不在局域网里广播和查找设备,也不接受局域网里的配对请求。
	// 写成反向的,旧配置文件没有这一项时就是开启。
	LANDisabled bool `json:"lan_disabled,omitempty"`

	// UpdateCheckDisabled 不自动检查更新。写成反向的,旧配置文件没有这一项时就是开启。
	UpdateCheckDisabled bool `json:"update_check_disabled,omitempty"`
	// UpdateSkipVersion 是用户选择跳过的版本:自动检查不再提示它
	UpdateSkipVersion string `json:"update_skip_version,omitempty"`

	// QuickPasteDisabled 关掉快捷粘贴窗口。写成反向的,旧配置文件没有这一项时就是开启。
	QuickPasteDisabled bool `json:"quick_paste_disabled,omitempty"`
	// WebShareEnabled 打开手机网页传输:后台服务在局域网里提供网页,手机扫码后用浏览器互传。默认关
	WebShareEnabled bool `json:"web_share_enabled,omitempty"`
	// MediaAutoApplyDisabled:对端自动推送来的图片和文件收完后不写进剪贴板,只进复制记录,
	// 用户点了「复制」才写。Android App 默认这样;桌面默认写入(写成反向的,旧配置不变)。
	// 文字仍由 AutoApplyToClipboard 决定
	MediaAutoApplyDisabled bool `json:"media_auto_apply_disabled,omitempty"`
	// QuickPasteHotkey 是呼出快捷窗口的快捷键,写法见 NormalizeHotkey;
	// 空字符串表示默认:Mac 上 ⌥V,其他平台 Alt+V
	QuickPasteHotkey string `json:"quick_paste_hotkey,omitempty"`
	// QuickPasteCopyOnly 选中后只放进剪贴板,不模拟粘贴
	QuickPasteCopyOnly bool `json:"quick_paste_copy_only,omitempty"`
	// QuickPasteIndexModifier 是快捷窗口里按住它再按 1–9 粘贴对应那一条的修饰键:"alt"、"meta"、"ctrl"。
	// 空字符串表示默认的 alt(Mac 上是 ⌥)
	QuickPasteIndexModifier string `json:"quick_paste_index_modifier,omitempty"`
	// SentRetentionDays 是手机上「发送记录」显示最近几天的发出内容;0 或负表示默认 3 天
	SentRetentionDays int `json:"sent_retention_days,omitempty"`

	// ReceiveDir 是隔空传送收到的文件存放的位置,空字符串表示系统的「下载」文件夹(见 DownloadsDir)
	ReceiveDir string `json:"receive_dir,omitempty"`
	// ReceiveDisabled 不接收其他设备隔空传送过来的文件。写成反向的,旧配置文件没有这一项时就是开启。
	ReceiveDisabled bool `json:"receive_disabled,omitempty"`
	// ReceiveNotifyDisabled 收到隔空传送的文件时不发系统通知
	ReceiveNotifyDisabled bool `json:"receive_notify_disabled,omitempty"`
	// SendLayoutStacked 让隔空传送页上下排:传输列表放在雷达下面。默认左右排,只有界面用
	SendLayoutStacked bool `json:"send_layout_stacked,omitempty"`

	// ReceiveFrom 是谁可以给我发文件(只管别人,自己的设备看 ReceiveDisabled),见 design/friends-send.md:
	// "off"(均不允许)、"friends"(仅限好友)、"everyone"(所有人,只在局域网)。空字符串表示默认的仅限好友
	ReceiveFrom string `json:"receive_from,omitempty"`
	// EveryoneUntil 是「所有人」自动回到「仅限好友」的时间(Unix 秒),打开「所有人」时设为 10 分钟后
	EveryoneUntil int64 `json:"everyone_until,omitempty"`
	// DisplayName 是好友看到的名字,空字符串表示系统的用户全名
	DisplayName string `json:"display_name,omitempty"`

	// ThemeID 是界面用的主题(design/themes.md):空字符串表示默认主题,否则是内置或自定义主题的 id
	ThemeID string `json:"theme_id,omitempty"`
	// ThemeMode 是浅色还是深色:"light"、"dark";空字符串表示跟随系统
	ThemeMode string `json:"theme_mode,omitempty"`
	// ThemeScanlines 打开像素主题的 CRT 扫描线效果,默认关
	ThemeScanlines bool `json:"theme_scanlines,omitempty"`
}

// 谁可以给我发文件
const (
	ReceiveFromOff      = "off"
	ReceiveFromFriends  = "friends"
	ReceiveFromEveryone = "everyone"
)

// EveryoneWindow 是「所有人」打开多久后自动关掉
const EveryoneWindow = 10 * time.Minute

// EffectiveReceiveFrom 返回此刻实际的接收范围:「所有人」过了时间就算「仅限好友」。
func (c Config) EffectiveReceiveFrom(now time.Time) string {
	switch c.ReceiveFrom {
	case ReceiveFromOff:
		return ReceiveFromOff
	case ReceiveFromEveryone:
		if c.EveryoneUntil > now.Unix() {
			return ReceiveFromEveryone
		}
	}
	return ReceiveFromFriends
}

// EffectiveReceiveDir 返回隔空传送实际的保存位置。
func (c Config) EffectiveReceiveDir() string {
	if c.ReceiveDir != "" {
		return c.ReceiveDir
	}
	return DownloadsDir()
}

// CurrentVersion 是当前的配置格式版本。
//
// 版本 2(1.4.0):服务器变成可选,默认地址从 ws://127.0.0.1:8787/signal 改为空。
const CurrentVersion = 3

const OfficialSignalURL = "wss://rtccpwsapi1.pasteferry.cc/signal"

func (c Config) Official() bool { return c.ServiceMode == "official" }

// UsesOfficialEndpoint hides system metadata even when an official address was
// manually entered in custom mode. It does not enable gateway authorization.
func (c Config) UsesOfficialEndpoint() bool {
	u, err := url.Parse(c.EffectiveSignalingURL())
	return err == nil && (u.Hostname() == "rtccpwsapi1.pasteferry.cc" || u.Hostname() == "pasteferry.cc")
}
func (c Config) EffectiveSignalingURL() string {
	switch c.ServiceMode {
	case "official":
		return OfficialSignalURL
	case "lan":
		return ""
	case "custom":
		return c.CustomSignalingURL
	default:
		return c.SignalingURL
	}
}

// legacyDefaultURL 是 1.4.0 之前的默认服务器地址。没改过它的用户其实没有服务器,
// 升级后应当直接进入局域网模式,而不是一直显示「服务器连不上」。
const legacyDefaultURL = "ws://127.0.0.1:8787/signal"

func Default() Config {
	host, _ := os.Hostname()
	if host == "" {
		host = "未命名设备"
	}
	return Config{
		Version:                CurrentVersion,
		DeviceName:             host,
		AutoSyncThresholdBytes: 50 << 20, // 50 MiB
		HistoryTTL:             Duration(3 * 24 * time.Hour),
		CacheTTL:               Duration(3 * 24 * time.Hour),
		SyncText:               true,
		SyncHTML:               true,
		SyncImage:              true,
		SyncFile:               true,
		AutoApplyToClipboard:   true,
		LaunchAtLogin:          false,
	}
}

// Validate 修正越界值,避免用户或损坏的配置文件把 daemon 带进坏状态。
func (c *Config) Validate() {
	d := Default()
	if c.ServiceMode != "" && c.ServiceMode != "lan" && c.ServiceMode != "official" && c.ServiceMode != "custom" {
		c.ServiceMode = "lan"
	}
	if c.ServiceMode == "custom" {
		c.SignalingURL = c.CustomSignalingURL
	} else if c.ServiceMode == "official" || c.ServiceMode == "lan" {
		c.SignalingURL = ""
	}
	if c.DeviceName == "" {
		c.DeviceName = d.DeviceName
	}
	if c.AutoSyncThresholdBytes <= 0 {
		c.AutoSyncThresholdBytes = d.AutoSyncThresholdBytes
	}
	// TTL 至少一分钟,否则 GC 会把刚写入的记录立刻删掉
	if time.Duration(c.HistoryTTL) < time.Minute {
		c.HistoryTTL = d.HistoryTTL
	}
	if time.Duration(c.CacheTTL) < time.Minute {
		c.CacheTTL = d.CacheTTL
	}
	// 缓存活得比历史记录久没有意义:记录没了就找不到那些文件了
	if c.CacheTTL > c.HistoryTTL {
		c.CacheTTL = c.HistoryTTL
	}
	// 不认识的语言(比如更新版本的界面写进来的)当作跟随系统
	switch c.Language {
	case "", "zh-Hans", "zh-Hant-TW", "zh-Hant-HK", "en", "ja":
	default:
		c.Language = ""
	}
	// 写不对的快捷键当作默认的
	c.QuickPasteHotkey = NormalizeHotkey(c.QuickPasteHotkey)
	switch c.QuickPasteIndexModifier {
	case "", "alt", "meta", "ctrl":
	default:
		c.QuickPasteIndexModifier = ""
	}
	switch c.ReceiveFrom {
	case ReceiveFromOff, ReceiveFromFriends, ReceiveFromEveryone:
	default:
		c.ReceiveFrom = ""
	}
	if c.ReceiveFrom != ReceiveFromEveryone {
		c.EveryoneUntil = 0
	}
	if len(c.DisplayName) > 64 {
		c.DisplayName = c.DisplayName[:64]
	}
	if !ValidThemeID(c.ThemeID) || c.ThemeID == "default" {
		c.ThemeID = ""
	}
	switch c.ThemeMode {
	case "", "light", "dark":
	default:
		c.ThemeMode = ""
	}
}

// ValidThemeID 报告 id 能不能当主题的 id 用:小写字母、数字和连字符,最长 40 个字符。空字符串也算(默认主题)
func ValidThemeID(id string) bool {
	if len(id) > 40 {
		return false
	}
	for _, r := range id {
		if !(r >= 'a' && r <= 'z' || r >= '0' && r <= '9' || r == '-') {
			return false
		}
	}
	return true
}

// ─────────────────────────── 目录布局 ───────────────────────────

// Paths 是 daemon 用到的全部路径。集中在一处,便于测试时重定向。
type Paths struct {
	Root  string // 配置与数据库
	Cache string // 收到的文件内容
	// 收藏另存的图片与文件。不能放在 Cache 里面:GC 会把缓存目录里不认识的文件夹当成孤儿删掉
	Favorites string
	Config    string
	DB        string
	// daemon 启动后把 gRPC 端口和一次性 token 写在这里,供 UI 发现
	Endpoint string
	// 自定义主题(<id>.json)与导入的背景图,见 design/themes.md
	Themes      string
	Backgrounds string
}

func DefaultPaths() (Paths, error) {
	var root string
	switch runtime.GOOS {
	case "darwin":
		home, err := os.UserHomeDir()
		if err != nil {
			return Paths{}, err
		}
		root = filepath.Join(home, "Library", "Application Support", "PasteFerry")
	case "windows":
		base := os.Getenv("LOCALAPPDATA")
		if base == "" {
			var err error
			if base, err = os.UserConfigDir(); err != nil {
				return Paths{}, err
			}
		}
		root = filepath.Join(base, "PasteFerry")
	default:
		// Linux 等:数据库、缓存、身份都是数据而不是配置,按 XDG 放在 ~/.local/share 下。
		// 界面要找到同一个位置,见 ui/lib/daemon_client.dart 的 defaultDataDir
		base := os.Getenv("XDG_DATA_HOME")
		if !filepath.IsAbs(base) {
			home, err := os.UserHomeDir()
			if err != nil {
				return Paths{}, err
			}
			base = filepath.Join(home, ".local", "share")
		}
		root = filepath.Join(base, "pasteferry")
	}
	return pathsUnder(root), nil
}

func pathsUnder(root string) Paths {
	return Paths{
		Root:      root,
		Cache:     filepath.Join(root, "cache"),
		Favorites: filepath.Join(root, "favorites"),
		Config:    filepath.Join(root, "config.json"),
		DB:        filepath.Join(root, "pasteferry.db"),
		Endpoint:  filepath.Join(root, "daemon.json"),

		Themes:      filepath.Join(root, "themes"),
		Backgrounds: filepath.Join(root, "backgrounds"),
	}
}

// PathsUnder 让测试把整套目录指到临时位置。
func PathsUnder(root string) Paths { return pathsUnder(root) }

// MigrateLegacy 把 2.0.0 之前产品叫 CopySync 时的数据目录整个挪到新位置:身份、配对关系、
// 复制记录与设置都在里面,丢了就得重新配对。新目录已经存在、或者没有旧目录时什么都不做。
// 要在任何东西写进新目录之前调用(守护进程的日志与锁文件也在数据目录里)。
// 旧的后台服务由界面先停掉,见 ui/lib/background_service.dart 的 removeLegacy。
func MigrateLegacy(p Paths) (bool, error) {
	old := legacyRoot(p.Root)
	if old == "" {
		return false, nil
	}
	if _, err := os.Stat(p.Root); !errors.Is(err, fs.ErrNotExist) {
		return false, err
	}
	if _, err := os.Stat(old); err != nil {
		if errors.Is(err, fs.ErrNotExist) {
			return false, nil
		}
		return false, err
	}
	if err := os.Rename(old, p.Root); err != nil {
		return false, err
	}
	for _, suffix := range []string{"", "-wal", "-shm"} {
		from := filepath.Join(p.Root, "copysync.db"+suffix)
		if _, err := os.Stat(from); err == nil {
			if err := os.Rename(from, p.DB+suffix); err != nil {
				return true, err
			}
		}
	}
	return true, nil
}

func legacyRoot(root string) string {
	switch filepath.Base(root) {
	case "PasteFerry":
		return filepath.Join(filepath.Dir(root), "CopySync")
	case "pasteferry":
		return filepath.Join(filepath.Dir(root), "copysync")
	}
	return ""
}

func (p Paths) EnsureDirs() error {
	for _, d := range []string{p.Root, p.Cache, p.Favorites} {
		if err := os.MkdirAll(d, 0o700); err != nil {
			return fmt.Errorf("创建目录 %s: %w", d, err)
		}
	}
	return nil
}

// ─────────────────────────── 读写 ───────────────────────────

// Load 读取配置;文件不存在时写入并返回默认配置。
func Load(p Paths) (Config, error) {
	data, err := os.ReadFile(p.Config)
	if os.IsNotExist(err) {
		c := Default()
		if err := Save(p, c); err != nil {
			return c, err
		}
		return c, nil
	}
	if err != nil {
		return Config{}, fmt.Errorf("读取配置: %w", err)
	}

	c := Default() // 以默认值打底,缺失字段自动继承
	c.Version = 0  // 旧文件没有版本号,要能认出来
	if err := json.Unmarshal(data, &c); err != nil {
		return Config{}, fmt.Errorf("解析配置 %s: %w", p.Config, err)
	}
	migrated := c.migrate()
	c.Validate()
	if migrated {
		// 存回去,免得用户之后特意填回旧默认地址时又被清掉
		_ = Save(p, c)
	}
	return c, nil
}

// migrate 把旧格式的配置升级到 CurrentVersion,返回是否有改动。
func (c *Config) migrate() bool {
	if c.Version >= CurrentVersion {
		return false
	}
	if c.Version < 2 && c.SignalingURL == legacyDefaultURL {
		c.SignalingURL = ""
	}
	if c.Version < 3 {
		switch c.SignalingURL {
		case OfficialSignalURL, "wss://pasteferry.cc/signal":
			c.ServiceMode = "official"
			c.SignalingURL = ""
		case "":
			c.ServiceMode = "lan"
		default:
			c.ServiceMode = "custom"
			c.CustomSignalingURL = c.SignalingURL
		}
	}
	c.Version = CurrentVersion
	return true
}

func Save(p Paths, c Config) error {
	if err := p.EnsureDirs(); err != nil {
		return err
	}
	data, err := json.MarshalIndent(c, "", "  ")
	if err != nil {
		return err
	}
	// 先写临时文件再改名,避免写一半断电留下损坏的配置
	tmp := p.Config + ".tmp"
	if err := os.WriteFile(tmp, data, 0o600); err != nil {
		return err
	}
	return os.Rename(tmp, p.Config)
}

// ─────────────────────────── Duration ───────────────────────────

// Duration 让 time.Duration 在 JSON 里表现为 "72h" 这样的可读字符串,
// 而不是一长串纳秒整数——配置文件是给人看的。
type Duration time.Duration

func (d Duration) MarshalJSON() ([]byte, error) {
	return json.Marshal(time.Duration(d).String())
}

func (d *Duration) UnmarshalJSON(b []byte) error {
	var v any
	if err := json.Unmarshal(b, &v); err != nil {
		return err
	}
	switch value := v.(type) {
	case string:
		parsed, err := time.ParseDuration(value)
		if err != nil {
			return fmt.Errorf("无法解析时长 %q: %w", value, err)
		}
		*d = Duration(parsed)
	case float64: // 兼容手写成秒数的情况
		*d = Duration(time.Duration(value) * time.Second)
	default:
		return fmt.Errorf("时长字段类型不支持: %T", v)
	}
	return nil
}

func (d Duration) Std() time.Duration { return time.Duration(d) }

// SyncAllowed reports whether automatic clipboard sharing with peer is enabled.
func (c Config) SyncAllowed(peer string) bool {
	if c.RealtimeSyncDisabled {
		return false
	}
	for _, id := range c.SyncDisabledPeers {
		if id == peer {
			return false
		}
	}
	return true
}