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.

feat(core): check for, download and install updates

baiyuzed0f00b4fe4e5
diff --git a/client-core/cmd/pasteferryd/main.go b/client-core/cmd/pasteferryd/main.go
index 8dc7200..8136a70 100644
--- a/client-core/cmd/pasteferryd/main.go
+++ b/client-core/cmd/pasteferryd/main.go
@@ -31,6 +31,7 @@ import (
syncengine "github.com/baiyuze/pasteferry/client-core/internal/sync"
"github.com/baiyuze/pasteferry/client-core/internal/transport/lan"
"github.com/baiyuze/pasteferry/client-core/internal/transport/p2p"
+ "github.com/baiyuze/pasteferry/client-core/internal/update"
pb "github.com/baiyuze/pasteferry/proto/gen/pasteferry/v1"
)
@@ -53,8 +54,16 @@ func main() {
"诊断用:在主线程直接读一次剪贴板并打印结果后退出")
supervise = flag.Bool("supervise", false,
"守护模式:拉起后台服务,异常退出时自动重启(Windows、Linux 开机自启用)")
+ applyUpdate = flag.String("apply-update", "", "更新助手:按这个安装计划安装新版本(由后台服务调用)")
+ applyUpdateRun = flag.String("apply-update-run", "", "更新助手脱离进程树之后的第二级,不要直接调用")
)
flag.Parse()
+ if *applyUpdate != "" || *applyUpdateRun != "" {
+ if *applyUpdate != "" {
+ os.Exit(update.RunHelper(*applyUpdate, true))
+ }
+ os.Exit(update.RunHelper(*applyUpdateRun, false))
+ }
if *notificationAction != "" {
if err := activateNotification(*notificationAction); err != nil {
fmt.Fprintln(os.Stderr, err)
@@ -361,7 +370,8 @@ func run(dataDir string) error {
if c.LANDisabled != prev.LANDisabled {
peerMgr.SetLANEnabled(!c.LANDisabled)
}
- if c.EffectiveSignalingURL() != prev.EffectiveSignalingURL() || c.ServiceMode != prev.ServiceMode || c.LANDisabled != prev.LANDisabled {
+ if c.EffectiveSignalingURL() != prev.EffectiveSignalingURL() || c.ServiceMode != prev.ServiceMode || c.LANDisabled != prev.LANDisabled ||
+ c.UpdateCheckDisabled != prev.UpdateCheckDisabled || c.UpdateSkipVersion != prev.UpdateSkipVersion {
select {
case statusDirty <- struct{}{}:
default:
@@ -375,7 +385,13 @@ func run(dataDir string) error {
if err != nil {
return err
}
- srv := rpc.NewServer(rpc.Deps{
+ updater := newUpdater(paths.Root, loadCfg, func() {
+ select {
+ case statusDirty <- struct{}{}:
+ default:
+ }
+ })
+ deps := rpc.Deps{
Store: db,
Paths: paths,
Version: version,
@@ -434,7 +450,12 @@ func run(dataDir string) error {
NotificationStatus: notifier.Status,
RequestNotifications: notifier.Request,
ActivateNotification: notifier.Activate,
- }, hub, token)
+ }
+ wireUpdater(&deps, updater)
+ srv := rpc.NewServer(deps, hub, token)
+ if updater != nil {
+ go updater.Run(ctx)
+ }
// 信令连接与在线对端数的变化推给 UI。Subscribe 只在建立订阅时推一次状态,
// 没有这里的话,UI 会一直停留在它打开那一刻的连接状态。
diff --git a/client-core/cmd/pasteferryd/updates.go b/client-core/cmd/pasteferryd/updates.go
new file mode 100644
index 0000000..48fe053
--- /dev/null
+++ b/client-core/cmd/pasteferryd/updates.go
@@ -0,0 +1,81 @@
+package main
+
+import (
+ "context"
+ "errors"
+ "log/slog"
+
+ "github.com/baiyuze/pasteferry/client-core/internal/config"
+ "github.com/baiyuze/pasteferry/client-core/internal/rpc"
+ "github.com/baiyuze/pasteferry/client-core/internal/update"
+ pb "github.com/baiyuze/pasteferry/proto/gen/pasteferry/v1"
+)
+
+// newUpdater 建更新服务。版本号不是 X.Y.Z 的构建返回 nil,界面会说明不支持检查更新。
+func newUpdater(root string, loadCfg func() config.Config, changed func()) *update.Service {
+ svc, err := update.NewService(version, root, slog.Default().With("part", "update"))
+ if err != nil {
+ slog.Info("这个构建不检查更新", "version", version, "err", err)
+ return nil
+ }
+ svc.AutoCheck = func() bool { return !loadCfg().UpdateCheckDisabled }
+ svc.Skipped = func() string { return loadCfg().UpdateSkipVersion }
+ svc.Changed = changed
+ if r := svc.LastResult(); r != nil {
+ slog.Info("上一次自动更新", "from", r.From, "to", r.To, "ok", r.OK, "err", r.Error)
+ }
+ return svc
+}
+
+// wireUpdater 把更新服务接到 gRPC 上;svc 为 nil 时这些调用返回「不支持」。
+func wireUpdater(deps *rpc.Deps, svc *update.Service) {
+ if svc == nil {
+ return
+ }
+ deps.CheckUpdate = func(ctx context.Context, lang string) (*pb.UpdateInfo, error) {
+ found, err := svc.Check(ctx)
+ if err != nil {
+ return nil, err
+ }
+ return updateInfo(svc, found, lang), nil
+ }
+ deps.DownloadUpdate = svc.Download
+ deps.InstallUpdate = func(version string, uiPID int) error {
+ if uiPID <= 0 {
+ return errors.New("需要界面的进程号")
+ }
+ return svc.Install(version, uiPID)
+ }
+ deps.UpdateNotice = svc.Notice
+ deps.LastUpdate = func() *pb.UpdateResult {
+ r := svc.LastResult()
+ if r == nil {
+ return nil
+ }
+ return &pb.UpdateResult{FromVersion: r.From, ToVersion: r.To, Ok: r.OK, Error: r.Error, AtUnix: r.At}
+ }
+}
+
+func updateInfo(svc *update.Service, found *update.Found, lang string) *pb.UpdateInfo {
+ m := found.Manifest
+ info := &pb.UpdateInfo{
+ CurrentVersion: svc.Current.String(),
+ LatestVersion: m.Latest,
+ InstallBlocker: svc.Target.Blocker,
+ InstallKind: string(svc.Target.Kind),
+ Source: found.Source,
+ CheckedAtUnix: found.At.Unix(),
+ }
+ latest, _ := update.ParseVersion(m.Latest)
+ info.Available = latest.Compare(svc.Current) > 0
+ if a, ok := svc.Asset(m); ok {
+ info.DownloadBytes = a.Size
+ } else if info.InstallBlocker == "" {
+ info.InstallBlocker = update.BlockerUnsupported
+ }
+ for _, r := range m.Newer(svc.Current) {
+ n := r.Localized(lang)
+ info.Releases = append(info.Releases, &pb.UpdateRelease{Version: r.Version, Date: r.Date, Changes: n.Changes, Fixes: n.Fixes})
+ }
+ return info
+}
diff --git a/client-core/cmd/updatesign/main.go b/client-core/cmd/updatesign/main.go
new file mode 100644
index 0000000..146ef4d
--- /dev/null
+++ b/client-core/cmd/updatesign/main.go
@@ -0,0 +1,113 @@
+// updatesign 给更新清单签名,发版时由 tools/release/manifest.py 调用。
+//
+// updatesign -genkey 生成签名密钥:私钥存进 macOS 钥匙串,打印公钥(编进 internal/update/keys.go)
+// updatesign -sign FILE 用钥匙串里的私钥签名,写出 FILE.sig,并用程序内置的公钥回验
+// updatesign -verify FILE 只用内置公钥验证 FILE.sig
+//
+// 私钥只在钥匙串里(服务名 pasteferry-update-signing-key),不落地成文件、不打印。
+// 丢了它就再也发不出能自动更新的版本:备份见 design/auto-update.md。
+package main
+
+import (
+ "crypto/ed25519"
+ "crypto/rand"
+ "encoding/base64"
+ "errors"
+ "flag"
+ "fmt"
+ "os"
+ "os/exec"
+ "strings"
+
+ "github.com/baiyuze/pasteferry/client-core/internal/update"
+)
+
+const keychainService = "pasteferry-update-signing-key"
+
+func main() {
+ genkey := flag.Bool("genkey", false, "生成签名密钥并存进钥匙串")
+ sign := flag.String("sign", "", "给这个文件签名")
+ verify := flag.String("verify", "", "验证这个文件的签名")
+ flag.Parse()
+ var err error
+ switch {
+ case *genkey:
+ err = genKey()
+ case *sign != "":
+ err = signFile(*sign)
+ case *verify != "":
+ err = verifyFile(*verify)
+ default:
+ flag.Usage()
+ os.Exit(2)
+ }
+ if err != nil {
+ fmt.Fprintln(os.Stderr, "错误:", err)
+ os.Exit(1)
+ }
+}
+
+func genKey() error {
+ if _, err := loadKey(); err == nil {
+ return errors.New("钥匙串里已经有签名密钥,不覆盖。确实要换密钥时先在「钥匙串访问」里删掉 " + keychainService)
+ }
+ pub, priv, err := ed25519.GenerateKey(rand.Reader)
+ if err != nil {
+ return err
+ }
+ seed := base64.StdEncoding.EncodeToString(priv.Seed())
+ cmd := exec.Command("security", "add-generic-password", "-a", "pasteferry", "-s", keychainService,
+ "-l", "PasteFerry update signing key", "-w", seed)
+ if out, err := cmd.CombinedOutput(); err != nil {
+ return fmt.Errorf("写入钥匙串: %v %s", err, out)
+ }
+ fmt.Println(base64.StdEncoding.EncodeToString(pub))
+ return nil
+}
+
+func loadKey() (ed25519.PrivateKey, error) {
+ out, err := exec.Command("security", "find-generic-password", "-s", keychainService, "-w").Output()
+ if err != nil {
+ return nil, errors.New("钥匙串里没有 " + keychainService)
+ }
+ seed, err := base64.StdEncoding.DecodeString(strings.TrimSpace(string(out)))
+ if err != nil || len(seed) != ed25519.SeedSize {
+ return nil, errors.New("钥匙串里的签名密钥格式不对")
+ }
+ return ed25519.NewKeyFromSeed(seed), nil
+}
+
+func signFile(path string) error {
+ key, err := loadKey()
+ if err != nil {
+ return err
+ }
+ raw, err := os.ReadFile(path)
+ if err != nil {
+ return err
+ }
+ sig := base64.StdEncoding.EncodeToString(ed25519.Sign(key, raw)) + "\n"
+ if err := update.Verify(raw, []byte(sig), update.PublicKeys()); err != nil {
+ return errors.New("钥匙串里的私钥与程序内置的公钥不配对,签出的清单客户端不会认")
+ }
+ return os.WriteFile(path+".sig", []byte(sig), 0o644)
+}
+
+func verifyFile(path string) error {
+ raw, err := os.ReadFile(path)
+ if err != nil {
+ return err
+ }
+ sig, err := os.ReadFile(path + ".sig")
+ if err != nil {
+ return err
+ }
+ if err := update.Verify(raw, sig, update.PublicKeys()); err != nil {
+ return err
+ }
+ if _, err := update.Parse(raw); err != nil {
+ return err
+ }
+ fmt.Println("签名正确")
+ return nil
+}
diff --git a/client-core/internal/config/config.go b/client-core/internal/config/config.go
index 8c0c6b7..1163120 100644
--- a/client-core/internal/config/config.go
+++ b/client-core/internal/config/config.go
@@ -53,6 +53,11 @@ type Config struct {
// LANDisabled 关掉局域网发现:不在局域网里广播和查找设备,也不接受局域网里的配对请求。
// 写成反向的,旧配置文件没有这一项时就是开启。
LANDisabled bool `json:"lan_disabled,omitempty"`
+
+ // UpdateCheckDisabled 不自动检查更新。写成反向的,旧配置文件没有这一项时就是开启。
+ UpdateCheckDisabled bool `json:"update_check_disabled,omitempty"`
+ // UpdateSkipVersion 是用户选择跳过的版本:自动检查不再提示它
+ UpdateSkipVersion string `json:"update_skip_version,omitempty"`
}
// CurrentVersion 是当前的配置格式版本。
diff --git a/client-core/internal/rpc/convert.go b/client-core/internal/rpc/convert.go
index ef3b4ac..d68822e 100644
--- a/client-core/internal/rpc/convert.go
+++ b/client-core/internal/rpc/convert.go
@@ -57,6 +57,8 @@ func configToProto(c config.Config) *pb.Config {
Language: c.Language,
LanDisabled: c.LANDisabled,
ServiceMode: serviceModeToProto(c), CustomSignalingUrl: c.CustomSignalingURL, OfficialNoticeAck: c.OfficialNoticeAck,
+ UpdateCheckDisabled: c.UpdateCheckDisabled,
+ UpdateSkipVersion: c.UpdateSkipVersion,
}
}
@@ -121,6 +123,8 @@ func configFromProto(in *pb.Config, base config.Config) config.Config {
}
c.OfficialNoticeAck = in.GetOfficialNoticeAck()
c.LANDisabled = in.GetLanDisabled()
+ c.UpdateCheckDisabled = in.GetUpdateCheckDisabled()
+ c.UpdateSkipVersion = in.GetUpdateSkipVersion()
return c
}
diff --git a/client-core/internal/rpc/convert_update_test.go b/client-core/internal/rpc/convert_update_test.go
new file mode 100644
index 0000000..c05c6f0
--- /dev/null
+++ b/client-core/internal/rpc/convert_update_test.go
@@ -0,0 +1,25 @@
+package rpc
+
+import (
+ "testing"
+
+ "github.com/baiyuze/pasteferry/client-core/internal/config"
+)
+
+// 更新相关的两项设置要原样往返:界面每次保存都带全量设置,漏掉就会被清空。
+func TestUpdateSettingsRoundTrip(t *testing.T) {
+ c := config.Default()
+ c.UpdateCheckDisabled = true
+ c.UpdateSkipVersion = "2.3.1"
+ got := configFromProto(configToProto(c), config.Default())
+ if !got.UpdateCheckDisabled || got.UpdateSkipVersion != "2.3.1" {
+ t.Fatalf("round trip lost update settings: %+v", got)
+ }
+ // 界面清空跳过的版本、重新打开自动检查
+ in := configToProto(c)
+ in.UpdateCheckDisabled, in.UpdateSkipVersion = false, ""
+ got = configFromProto(in, c)
+ if got.UpdateCheckDisabled || got.UpdateSkipVersion != "" {
+ t.Fatalf("update settings not cleared: %+v", got)
+ }
+}
diff --git a/client-core/internal/rpc/server.go b/client-core/internal/rpc/server.go
index 851ce77..5ad0872 100644
--- a/client-core/internal/rpc/server.go
+++ b/client-core/internal/rpc/server.go
@@ -77,6 +77,14 @@ type Deps struct {
NotificationStatus func(context.Context) (*pb.NotificationStatus, error)
RequestNotifications func(context.Context) (*pb.NotificationStatus, error)
ActivateNotification func(context.Context, string, string) error
+
+ // 检查与安装更新,见 internal/update。UpdateNotice 是自动检查发现、要提示的新版本;
+ // LastUpdate 是刚完成的那次更新
+ CheckUpdate func(ctx context.Context, language string) (*pb.UpdateInfo, error)
+ DownloadUpdate func(ctx context.Context, version string, progress func(done, total int64)) error
+ InstallUpdate func(version string, uiPID int) error
+ UpdateNotice func() string
+ LastUpdate func() *pb.UpdateResult
}
func (s *Server) GetNotificationStatus(ctx context.Context, _ *pb.Empty) (*pb.NotificationStatus, error) {
@@ -344,6 +352,12 @@ func (s *Server) GetStatus(context.Context, *pb.Empty) (*pb.Status, error) {
if s.deps.OfficialUsage != nil {
st.OfficialUsage = s.deps.OfficialUsage()
}
+ if s.deps.UpdateNotice != nil {
+ st.UpdateAvailable = s.deps.UpdateNotice()
+ }
+ if s.deps.LastUpdate != nil {
+ st.LastUpdate = s.deps.LastUpdate()
+ }
if s.deps.Permission != nil {
st.ClipboardPermission = permissionToProto(s.deps.Permission())
}
@@ -579,6 +593,50 @@ func (s *Server) WatchNearby(_ *pb.Empty, stream grpc.ServerStreamingServer[pb.N
}
}
+func (s *Server) CheckForUpdate(ctx context.Context, req *pb.CheckForUpdateRequest) (*pb.UpdateInfo, error) {
+ if s.deps.CheckUpdate == nil {
+ return nil, status.Error(codes.Unimplemented, "当前版本不支持检查更新")
+ }
+ info, err := s.deps.CheckUpdate(ctx, req.GetLanguage())
+ if err != nil {
+ return nil, status.Error(codes.Unavailable, err.Error())
+ }
+ return info, nil
+}
+
+func (s *Server) DownloadUpdate(req *pb.DownloadUpdateRequest, stream grpc.ServerStreamingServer[pb.UpdateProgress]) error {
+ if s.deps.DownloadUpdate == nil {
+ return status.Error(codes.Unimplemented, "当前版本不支持自动更新")
+ }
+ // 进度最多每 200 毫秒发一次,不然大文件会发出成千上万条消息
+ var last time.Time
+ var sendErr error
+ err := s.deps.DownloadUpdate(stream.Context(), req.GetVersion(), func(done, total int64) {
+ if sendErr != nil || (time.Since(last) < 200*time.Millisecond && done < total) {
+ return
+ }
+ last = time.Now()
+ sendErr = stream.Send(&pb.UpdateProgress{Downloaded: done, Total: total})
+ })
+ if err != nil {
+ if stream.Context().Err() != nil {
+ return status.Error(codes.Canceled, "已取消下载")
+ }
+ return status.Error(codes.Unavailable, err.Error())
+ }
+ return stream.Send(&pb.UpdateProgress{Done: true})
+}
+
+func (s *Server) InstallUpdate(_ context.Context, req *pb.InstallUpdateRequest) (*pb.Empty, error) {
+ if s.deps.InstallUpdate == nil {
+ return nil, status.Error(codes.Unimplemented, "当前版本不支持自动更新")
+ }
+ if err := s.deps.InstallUpdate(req.GetVersion(), int(req.GetUiPid())); err != nil {
+ return nil, status.Error(codes.FailedPrecondition, err.Error())
+ }
+ return &pb.Empty{}, nil
+}
+
func (s *Server) PairNearby(ctx context.Context, req *pb.PairNearbyRequest) (*pb.RedeemPairingCodeResponse, error) {
if s.deps.PairNearby == nil {
return nil, status.Error(codes.Unimplemented, "当前版本不支持搜索附近设备")
diff --git a/client-core/internal/update/apply.go b/client-core/internal/update/apply.go
new file mode 100644
index 0000000..f38a775
--- /dev/null
+++ b/client-core/internal/update/apply.go
@@ -0,0 +1,207 @@
+package update
+
+import (
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "log/slog"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "runtime"
+ "time"
+)
+
+// Plan 是交给更新助手的安装计划。助手是后台服务程序的一份副本(见 Start),
+// 等界面退出后替换文件、写结果,再把后台服务与界面重新拉起来。
+type Plan struct {
+ Kind Kind `json:"kind"`
+ From string `json:"from"`
+ To string `json:"to"`
+ // Package 是下载并校验过的安装包
+ Package string `json:"package"`
+ // Staged 是提前准备好的新程序(Mac 的 .app、便携版与 tar.gz 的文件夹),与 App 在同一个文件夹里,替换只是改名
+ Staged string `json:"staged,omitempty"`
+ App string `json:"app"`
+ // UIPID 是要等它退出的界面;Daemons 是要结束的后台服务与守护进程(只结束位于 App 里的)
+ UIPID int `json:"ui_pid"`
+ Daemons []int `json:"daemons,omitempty"`
+ Result string `json:"result"`
+}
+
+// Result 是一次安装的结果,新版后台服务启动后读出来给界面显示。
+type Result struct {
+ From string `json:"from"`
+ To string `json:"to"`
+ OK bool `json:"ok"`
+ Error string `json:"error,omitempty"`
+ At int64 `json:"at"`
+}
+
+// updaterName 与后台服务的文件名不同:Windows 安装程序按名字结束 pasteferryd.exe,
+// 同名的话会把正在安装的助手也一起结束。
+func updaterName() string {
+ if runtime.GOOS == "windows" {
+ return "pasteferry-updater.exe"
+ }
+ return "pasteferry-updater"
+}
+
+// Prepare 在界面退出之前做完所有能提前做的事(挂载、解压、校验新程序),
+// 这些步骤出错时界面还开着,可以直接告诉用户。
+func Prepare(t Target, pkg, from, to, work string, uiPID int) (*Plan, error) {
+ if t.Blocker != "" {
+ return nil, fmt.Errorf("这种安装方式不能自动更新(%s)", t.Blocker)
+ }
+ p := &Plan{Kind: t.Kind, From: from, To: to, Package: pkg, App: t.App, UIPID: uiPID,
+ Result: filepath.Join(filepath.Dir(work), "result.json")}
+ if err := prepare(p, work); err != nil {
+ return nil, err
+ }
+ return p, nil
+}
+
+// Start 把计划写到 work 里,复制一份自身作为更新助手并启动它。
+// 助手立即再启动一个脱离当前进程树的自己,然后退出:之后结束后台服务(包括按进程树结束)
+// 都不会波及正在安装的那个助手。
+func Start(p *Plan, work string) error {
+ planPath := filepath.Join(work, "plan.json")
+ raw, err := json.MarshalIndent(p, "", " ")
+ if err != nil {
+ return err
+ }
+ if err := os.WriteFile(planPath, raw, 0o600); err != nil {
+ return err
+ }
+ self, err := os.Executable()
+ if err != nil {
+ return err
+ }
+ helper := filepath.Join(work, updaterName())
+ if err := copyFile(self, helper, 0o755); err != nil {
+ return err
+ }
+ cmd := exec.Command(helper, "-apply-update", planPath)
+ if out, err := cmd.CombinedOutput(); err != nil {
+ return fmt.Errorf("启动更新助手: %v %s", err, out)
+ }
+ return nil
+}
+
+// RunHelper 是更新助手的入口(pasteferryd -apply-update / -apply-update-run)。
+// detach 为 true 时只负责启动脱离进程树的第二级,然后退出。
+func RunHelper(planPath string, detach bool) int {
+ if detach {
+ self, err := os.Executable()
+ if err == nil {
+ err = startDetached(self, "-apply-update-run", planPath)
+ }
+ if err != nil {
+ fmt.Fprintln(os.Stderr, err)
+ return 1
+ }
+ return 0
+ }
+ logFile, err := os.OpenFile(filepath.Join(filepath.Dir(planPath), "updater.log"), os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o600)
+ var out io.Writer = io.Discard
+ if err == nil {
+ defer logFile.Close()
+ out = logFile
+ }
+ log := slog.New(slog.NewTextHandler(out, nil))
+ raw, err := os.ReadFile(planPath)
+ var p Plan
+ if err == nil {
+ err = json.Unmarshal(raw, &p)
+ }
+ if err != nil {
+ log.Error("读取更新计划失败", "err", err)
+ return 1
+ }
+ log.Info("开始安装", "from", p.From, "to", p.To, "kind", p.Kind)
+ if p.UIPID > 0 && !waitExit(p.UIPID, time.Minute) {
+ log.Warn("界面没有退出,结束它", "pid", p.UIPID)
+ terminate(p.UIPID)
+ waitExit(p.UIPID, 10*time.Second)
+ }
+ res := Result{From: p.From, To: p.To, At: time.Now().Unix()}
+ if err := apply(&p, log); err != nil {
+ log.Error("安装失败", "err", err)
+ res.Error = err.Error()
+ } else {
+ res.OK = true
+ log.Info("安装完成")
+ }
+ if raw, err := json.Marshal(res); err == nil {
+ _ = os.WriteFile(p.Result, raw, 0o600)
+ }
+ // 无论成败都把后台服务与界面拉起来:失败时是旧版,用户不会落得什么都没有
+ if err := relaunch(&p, log); err != nil {
+ log.Error("重新打开失败", "err", err)
+ }
+ return 0
+}
+
+// ReadResult 读出并删掉上一次安装的结果。没有就返回 nil。
+func ReadResult(dataDir string) *Result {
+ path := filepath.Join(dataDir, "updates", "result.json")
+ raw, err := os.ReadFile(path)
+ if err != nil {
+ return nil
+ }
+ _ = os.Remove(path)
+ var r Result
+ if json.Unmarshal(raw, &r) != nil || r.To == "" {
+ return nil
+ }
+ return &r
+}
+
+func copyFile(src, dst string, mode os.FileMode) error {
+ in, err := os.Open(src)
+ if err != nil {
+ return err
+ }
+ defer in.Close()
+ _ = os.Remove(dst)
+ out, err := os.OpenFile(dst, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, mode)
+ if err != nil {
+ return err
+ }
+ if _, err := io.Copy(out, in); err != nil {
+ out.Close()
+ return err
+ }
+ return out.Close()
+}
+
+// swapDir 把 staged 换到 app 的位置,旧的改名为 old。失败时尽量还原。
+func swapDir(app, staged, old string) error {
+ _ = os.RemoveAll(old)
+ if err := os.Rename(app, old); err != nil {
+ return fmt.Errorf("挪开旧版本: %w", err)
+ }
+ if err := os.Rename(staged, app); err != nil {
+ if rerr := os.Rename(old, app); rerr != nil {
+ return errors.Join(fmt.Errorf("放入新版本: %w", err), fmt.Errorf("还原旧版本: %w", rerr))
+ }
+ return fmt.Errorf("放入新版本: %w", err)
+ }
+ return nil
+}
+
+// stopDaemons 结束计划里位于 App 里的后台服务与守护进程,并等它们退出。
+func stopDaemons(p *Plan, log *slog.Logger) {
+ for _, pid := range p.Daemons {
+ if pid <= 0 || !processInDir(pid, p.App) {
+ continue
+ }
+ log.Info("结束旧的后台服务", "pid", pid)
+ terminate(pid)
+ if !waitExit(pid, 10*time.Second) {
+ kill(pid)
+ waitExit(pid, 5*time.Second)
+ }
+ }
+}
diff --git a/client-core/internal/update/apply_darwin.go b/client-core/internal/update/apply_darwin.go
new file mode 100644
index 0000000..fc86592
--- /dev/null
+++ b/client-core/internal/update/apply_darwin.go
@@ -0,0 +1,100 @@
+package update
+
+import (
+ "fmt"
+ "log/slog"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strings"
+)
+
+// launchdLabel 与界面登记的 LaunchAgent 相同,见 ui/lib/background_service.dart。
+const launchdLabel = "com.pasteferry.daemon"
+
+// prepare 挂载 DMG,把新 App 复制到旧 App 旁边(同一个磁盘,替换时只需改名),
+// 核对版本号、Bundle ID 与签名。
+func prepare(p *Plan, work string) error {
+ mnt := filepath.Join(work, "mnt")
+ _ = exec.Command("hdiutil", "detach", "-force", mnt).Run()
+ if err := os.MkdirAll(mnt, 0o700); err != nil {
+ return err
+ }
+ // 安装包已经按清单校验过 SHA-256,不必再让 hdiutil 校验一遍
+ if out, err := exec.Command("hdiutil", "attach", "-nobrowse", "-readonly", "-noautoopen", "-noverify",
+ "-mountpoint", mnt, p.Package).CombinedOutput(); err != nil {
+ return fmt.Errorf("打开 DMG: %v %s", err, out)
+ }
+ defer exec.Command("hdiutil", "detach", "-force", mnt).Run()
+ apps, _ := filepath.Glob(filepath.Join(mnt, "*.app"))
+ if len(apps) != 1 {
+ return fmt.Errorf("DMG 里应当正好有一个 App,找到 %d 个", len(apps))
+ }
+ staged := filepath.Join(filepath.Dir(p.App), ".PasteFerry-"+p.To+".app")
+ _ = os.RemoveAll(staged)
+ if out, err := exec.Command("ditto", apps[0], staged).CombinedOutput(); err != nil {
+ os.RemoveAll(staged)
+ return fmt.Errorf("复制新版本: %v %s", err, out)
+ }
+ _ = exec.Command("xattr", "-dr", "com.apple.quarantine", staged).Run()
+ if err := checkBundle(staged, p.App, p.To); err != nil {
+ os.RemoveAll(staged)
+ return err
+ }
+ p.Staged = staged
+ return nil
+}
+
+func checkBundle(staged, current, version string) error {
+ got := plistValue(staged, "CFBundleShortVersionString")
+ if got != version {
+ return fmt.Errorf("新 App 的版本是 %q,不是 %s", got, version)
+ }
+ if a, b := plistValue(staged, "CFBundleIdentifier"), plistValue(current, "CFBundleIdentifier"); a == "" || a != b {
+ return fmt.Errorf("新 App 的 Bundle ID 是 %q,与现在的 %q 不同", a, b)
+ }
+ if out, err := exec.Command("codesign", "--verify", "--deep", "--strict", staged).CombinedOutput(); err != nil {
+ return fmt.Errorf("新 App 的签名无效: %s", strings.TrimSpace(string(out)))
+ }
+ return nil
+}
+
+func plistValue(app, key string) string {
+ out, err := exec.Command("/usr/libexec/PlistBuddy", "-c", "Print :"+key, filepath.Join(app, "Contents", "Info.plist")).Output()
+ if err != nil {
+ return ""
+ }
+ return strings.TrimSpace(string(out))
+}
+
+func oldBundle(p *Plan) string {
+ return filepath.Join(filepath.Dir(p.App), ".PasteFerry-"+p.From+".app.old")
+}
+
+func apply(p *Plan, log *slog.Logger) error {
+ if err := swapDir(p.App, p.Staged, oldBundle(p)); err != nil {
+ os.RemoveAll(p.Staged)
+ return err
+ }
+ return nil
+}
+
+// relaunch 让 launchd 按新 App 里的程序重启后台服务(只在 LaunchAgent 指向这个 App 时),再打开界面。
+func relaunch(p *Plan, log *slog.Logger) error {
+ home, _ := os.UserHomeDir()
+ plist := filepath.Join(home, "Library", "LaunchAgents", launchdLabel+".plist")
+ if raw, err := os.ReadFile(plist); err == nil && strings.Contains(string(raw), p.App+"/") {
+ target := fmt.Sprintf("gui/%d/%s", os.Getuid(), launchdLabel)
+ if out, err := exec.Command("launchctl", "kickstart", "-k", target).CombinedOutput(); err != nil {
+ log.Warn("重启后台服务失败", "err", err, "out", string(out))
+ }
+ }
+ // open 启动的 App 不继承这里的环境变量:把 HOME 明确带过去,界面才会连回同一个数据目录。
+ // 平时两者本来就相同;只在系统的 open 不认 --env 时退回普通打开
+ err := exec.Command("open", "--env", "HOME="+home, p.App).Run()
+ if err != nil {
+ err = exec.Command("open", p.App).Run()
+ }
+ _ = os.RemoveAll(oldBundle(p))
+ return err
+}
diff --git a/client-core/internal/update/apply_darwin_test.go b/client-core/internal/update/apply_darwin_test.go
new file mode 100644
index 0000000..e41c11d
--- /dev/null
+++ b/client-core/internal/update/apply_darwin_test.go
@@ -0,0 +1,84 @@
+package update
+
+import (
+ "fmt"
+ "io"
+ "log/slog"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strings"
+ "testing"
+)
+
+// fakeBundle 建一个带签名的最小 App:可执行文件借用系统的 /usr/bin/true,重新做临时签名。
+func fakeBundle(t *testing.T, dir, version, id string) string {
+ t.Helper()
+ app := filepath.Join(dir, "PasteFerry.app")
+ os.MkdirAll(filepath.Join(app, "Contents", "MacOS"), 0o755)
+ plist := fmt.Sprintf(`<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0"><dict>
+<key>CFBundleExecutable</key><string>PasteFerry</string>
+<key>CFBundleIdentifier</key><string>%s</string>
+<key>CFBundleShortVersionString</key><string>%s</string>
+<key>CFBundlePackageType</key><string>APPL</string>
+</dict></plist>`, id, version)
+ os.WriteFile(filepath.Join(app, "Contents", "Info.plist"), []byte(plist), 0o644)
+ raw, err := os.ReadFile("/usr/bin/true")
+ if err != nil {
+ t.Skip(err)
+ }
+ os.WriteFile(filepath.Join(app, "Contents", "MacOS", "PasteFerry"), raw, 0o755)
+ if out, err := exec.Command("codesign", "--force", "-s", "-", app).CombinedOutput(); err != nil {
+ t.Skipf("codesign: %v %s", err, out)
+ }
+ return app
+}
+
+func TestMacPrepareAndSwap(t *testing.T) {
+ if testing.Short() {
+ t.Skip("builds a DMG")
+ }
+ root := t.TempDir()
+ apps := filepath.Join(root, "Applications")
+ os.MkdirAll(apps, 0o755)
+ current := fakeBundle(t, apps, "2.3.0", "com.pasteferry.test")
+ src := filepath.Join(root, "dmg-src")
+ os.MkdirAll(src, 0o755)
+ fakeBundle(t, src, "2.3.1", "com.pasteferry.test")
+ dmg := filepath.Join(root, "new.dmg")
+ if out, err := exec.Command("hdiutil", "create", "-quiet", "-srcfolder", src, "-format", "UDZO", dmg).CombinedOutput(); err != nil {
+ t.Skipf("hdiutil: %v %s", err, out)
+ }
+ work := filepath.Join(root, "work")
+ os.MkdirAll(work, 0o700)
+
+ // 版本号对不上的 DMG 在界面退出前就被拒绝,也不留下复制的东西
+ if _, err := Prepare(Target{Kind: KindMacApp, App: current}, dmg, "2.3.0", "2.3.2", work, 0); err == nil {
+ t.Fatal("accepted a DMG with the wrong version")
+ }
+ if left, _ := filepath.Glob(filepath.Join(apps, ".PasteFerry-*")); len(left) != 0 {
+ t.Fatalf("staged copy left after rejection: %v", left)
+ }
+
+ p, err := Prepare(Target{Kind: KindMacApp, App: current}, dmg, "2.3.0", "2.3.1", work, 0)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if filepath.Dir(p.Staged) != apps {
+ t.Fatalf("staged outside the app's folder: %s", p.Staged)
+ }
+ if err := apply(p, slog.New(slog.NewTextHandler(io.Discard, nil))); err != nil {
+ t.Fatal(err)
+ }
+ if got := plistValue(current, "CFBundleShortVersionString"); got != "2.3.1" {
+ t.Fatalf("installed version %q", got)
+ }
+ if _, err := os.Stat(oldBundle(p)); err != nil {
+ t.Fatalf("old bundle should wait for relaunch to be removed: %v", err)
+ }
+ if out, _ := exec.Command("hdiutil", "info").Output(); strings.Contains(string(out), filepath.Join(work, "mnt")) {
+ t.Fatal("DMG still mounted")
+ }
+}
diff --git a/client-core/internal/update/apply_linux.go b/client-core/internal/update/apply_linux.go
new file mode 100644
index 0000000..0ffb064
--- /dev/null
+++ b/client-core/internal/update/apply_linux.go
@@ -0,0 +1,64 @@
+package update
+
+import (
+ "errors"
+ "fmt"
+ "log/slog"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strings"
+)
+
+func prepare(p *Plan, work string) error {
+ if p.Kind == KindLinuxTar {
+ return stageFolder(p, untar, "pasteferry", "pasteferryd")
+ }
+ return nil
+}
+
+func apply(p *Plan, log *slog.Logger) error {
+ switch p.Kind {
+ case KindLinuxDeb:
+ // /opt 要管理员权限:pkexec 会弹出系统的密码框
+ out, err := exec.Command("pkexec", "dpkg", "-i", p.Package).CombinedOutput()
+ var exit *exec.ExitError
+ if errors.As(err, &exit) && (exit.ExitCode() == 126 || exit.ExitCode() == 127) {
+ return errors.New("没有获得管理员授权,已取消安装")
+ }
+ if err != nil {
+ return fmt.Errorf("安装 .deb 失败: %v %s", err, strings.TrimSpace(string(out)))
+ }
+ stopDaemons(p, log)
+ return nil
+ case KindLinuxTar:
+ stopDaemons(p, log)
+ return swapDir(p.App, p.Staged, oldFolder(p))
+ }
+ return fmt.Errorf("不支持的安装方式 %s", p.Kind)
+}
+
+// relaunch 按开机自启的方式重新拉起后台服务(原先在运行、现在没在运行时),再打开界面。
+func relaunch(p *Plan, log *slog.Logger) error {
+ if len(p.Daemons) > 0 && !anyAlive(p.Daemons) {
+ if err := startDetached(filepath.Join(p.App, "pasteferryd"), "-supervise"); err != nil {
+ log.Warn("启动后台服务失败", "err", err)
+ }
+ }
+ if p.Kind == KindLinuxTar {
+ defer os.RemoveAll(oldFolder(p))
+ if p.Staged != "" {
+ defer os.RemoveAll(stagingRoot(p))
+ }
+ }
+ return startDetached(filepath.Join(p.App, "pasteferry"))
+}
+
+func anyAlive(pids []int) bool {
+ for _, pid := range pids {
+ if pid > 0 && alive(pid) {
+ return true
+ }
+ }
+ return false
+}
diff --git a/client-core/internal/update/apply_windows.go b/client-core/internal/update/apply_windows.go
new file mode 100644
index 0000000..e6b2f95
--- /dev/null
+++ b/client-core/internal/update/apply_windows.go
@@ -0,0 +1,61 @@
+package update
+
+import (
+ "fmt"
+ "log/slog"
+ "os"
+ "os/exec"
+ "path/filepath"
+)
+
+func prepare(p *Plan, work string) error {
+ if p.Kind == KindWindowsPortable {
+ return stageFolder(p, unzip, "PasteFerry.exe", "pasteferryd.exe")
+ }
+ return nil
+}
+
+func apply(p *Plan, log *slog.Logger) error {
+ switch p.Kind {
+ case KindWindowsSetup:
+ // 安装程序自己会结束正在运行的界面与后台服务,装完按开机自启的登记把后台服务拉起来
+ logPath := filepath.Join(filepath.Dir(p.Package), "install.log")
+ cmd := exec.Command(p.Package, "/VERYSILENT", "/SUPPRESSMSGBOXES", "/NORESTART", "/NOCANCEL", "/LOG="+logPath)
+ if err := cmd.Run(); err != nil {
+ return fmt.Errorf("安装程序没有成功(日志 %s): %w", logPath, err)
+ }
+ return nil
+ case KindWindowsPortable:
+ stopDaemons(p, log)
+ if err := swapDir(p.App, p.Staged, oldFolder(p)); err != nil {
+ return err
+ }
+ return nil
+ }
+ return fmt.Errorf("不支持的安装方式 %s", p.Kind)
+}
+
+func relaunch(p *Plan, log *slog.Logger) error {
+ if p.Kind == KindWindowsPortable {
+ // 便携版的后台服务原先在运行、现在没在运行时,按开机自启的方式拉起来
+ if len(p.Daemons) > 0 && !anyAlive(p.Daemons) {
+ if err := startDetached(filepath.Join(p.App, "pasteferryd.exe"), "-supervise"); err != nil {
+ log.Warn("启动后台服务失败", "err", err)
+ }
+ }
+ defer os.RemoveAll(oldFolder(p))
+ if p.Staged != "" {
+ defer os.RemoveAll(stagingRoot(p))
+ }
+ }
+ return startDetached(filepath.Join(p.App, "PasteFerry.exe"))
+}
+
+func anyAlive(pids []int) bool {
+ for _, pid := range pids {
+ if pid > 0 && !waitExit(pid, 0) {
+ return true
+ }
+ }
+ return false
+}
diff --git a/client-core/internal/update/archive.go b/client-core/internal/update/archive.go
new file mode 100644
index 0000000..94e4886
--- /dev/null
+++ b/client-core/internal/update/archive.go
@@ -0,0 +1,149 @@
+package update
+
+import (
+ "archive/tar"
+ "archive/zip"
+ "compress/gzip"
+ "errors"
+ "fmt"
+ "io"
+ "os"
+ "path"
+ "path/filepath"
+ "strings"
+)
+
+// safeJoin 把压缩包里的路径接到 root 下,拒绝绝对路径与 ..(防止解压到外面)。
+// Windows 的便携版 zip 用反斜杠分隔路径,统一换成斜杠。
+func safeJoin(root, name string) (string, error) {
+ name = strings.ReplaceAll(name, `\`, "/")
+ clean := path.Clean("/" + name)
+ if clean == "/" || strings.HasPrefix(name, "/") || strings.Contains(name, "../") || strings.HasSuffix(name, "/..") || name == ".." {
+ return "", fmt.Errorf("压缩包里有不安全的路径 %q", name)
+ }
+ return filepath.Join(root, filepath.FromSlash(strings.TrimPrefix(clean, "/"))), nil
+}
+
+// unzip 把 zip 解压到 root。
+func unzip(zipPath, root string) error {
+ r, err := zip.OpenReader(zipPath)
+ if err != nil {
+ return err
+ }
+ defer r.Close()
+ for _, f := range r.File {
+ dest, err := safeJoin(root, f.Name)
+ if err != nil {
+ return err
+ }
+ if strings.HasSuffix(strings.ReplaceAll(f.Name, `\`, "/"), "/") || f.FileInfo().IsDir() {
+ if err := os.MkdirAll(dest, 0o755); err != nil {
+ return err
+ }
+ continue
+ }
+ if err := os.MkdirAll(filepath.Dir(dest), 0o755); err != nil {
+ return err
+ }
+ in, err := f.Open()
+ if err != nil {
+ return err
+ }
+ err = writeFile(dest, in, f.Mode().Perm()|0o600)
+ in.Close()
+ if err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+// untar 把 tar.gz 解压到 root,保留可执行权限与包里的相对符号链接。
+func untar(tgzPath, root string) error {
+ f, err := os.Open(tgzPath)
+ if err != nil {
+ return err
+ }
+ defer f.Close()
+ gz, err := gzip.NewReader(f)
+ if err != nil {
+ return err
+ }
+ defer gz.Close()
+ tr := tar.NewReader(gz)
+ for {
+ h, err := tr.Next()
+ if errors.Is(err, io.EOF) {
+ return nil
+ }
+ if err != nil {
+ return err
+ }
+ dest, err := safeJoin(root, h.Name)
+ if err != nil {
+ return err
+ }
+ switch h.Typeflag {
+ case tar.TypeDir:
+ if err := os.MkdirAll(dest, 0o755); err != nil {
+ return err
+ }
+ case tar.TypeReg:
+ if err := os.MkdirAll(filepath.Dir(dest), 0o755); err != nil {
+ return err
+ }
+ if err := writeFile(dest, tr, os.FileMode(h.Mode).Perm()|0o600); err != nil {
+ return err
+ }
+ case tar.TypeSymlink:
+ if filepath.IsAbs(h.Linkname) || strings.Contains(h.Linkname, "..") {
+ return fmt.Errorf("压缩包里有不安全的链接 %q", h.Linkname)
+ }
+ if err := os.MkdirAll(filepath.Dir(dest), 0o755); err != nil {
+ return err
+ }
+ if err := os.Symlink(h.Linkname, dest); err != nil {
+ return err
+ }
+ }
+ }
+}
+
+func writeFile(dest string, r io.Reader, mode os.FileMode) error {
+ out, err := os.OpenFile(dest, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, mode)
+ if err != nil {
+ return err
+ }
+ if _, err := io.Copy(out, r); err != nil {
+ out.Close()
+ return err
+ }
+ return out.Close()
+}
+
+// stageFolder 把便携版或 tar.gz 解压到 app 旁边,返回其中的 PasteFerry 文件夹。
+// 解压与 app 在同一个文件夹里,替换时只需改名。
+func stageFolder(p *Plan, extract func(pkg, root string) error, required ...string) error {
+ root := filepath.Join(filepath.Dir(p.App), ".PasteFerry-update-"+p.To)
+ _ = os.RemoveAll(root)
+ if err := extract(p.Package, root); err != nil {
+ os.RemoveAll(root)
+ return fmt.Errorf("解压新版本: %w", err)
+ }
+ staged := filepath.Join(root, "PasteFerry")
+ for _, name := range required {
+ if st, err := os.Stat(filepath.Join(staged, name)); err != nil || st.IsDir() {
+ os.RemoveAll(root)
+ return fmt.Errorf("新版本里缺少 %s", name)
+ }
+ }
+ p.Staged = staged
+ return nil
+}
+
+// stagingRoot 是 stageFolder 建的外层文件夹,替换完成后删掉。
+func stagingRoot(p *Plan) string { return filepath.Dir(p.Staged) }
+
+func oldFolder(p *Plan) string {
+ return filepath.Join(filepath.Dir(p.App), ".PasteFerry-"+p.From+".old")
+}
diff --git a/client-core/internal/update/check.go b/client-core/internal/update/check.go
new file mode 100644
index 0000000..6b12b9c
--- /dev/null
+++ b/client-core/internal/update/check.go
@@ -0,0 +1,168 @@
+package update
+
+import (
+ "context"
+ "crypto/ed25519"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "net/http"
+ "os"
+ "path/filepath"
+ "time"
+)
+
+// Source 是一个提供更新清单的地址;签名在同一地址加 .sig。
+type Source struct {
+ Name string `json:"name"`
+ Manifest string `json:"manifest"`
+}
+
+// DefaultSources 同时请求,谁先返回有效清单用谁:国内用户通常是 Gitee 先到,
+// 之后也先从 Gitee 下载安装包。
+var DefaultSources = []Source{
+ {Name: "github", Manifest: "https://raw.githubusercontent.com/baiyuze/pasteferry/main/updates/latest.json"},
+ {Name: "gitee", Manifest: "https://gitee.com/baiyuze/pasteferry/raw/main/updates/latest.json"},
+}
+
+// testSourcesFile 放在数据目录里时取代默认地址,只用于发版前的端到端测试。
+// 清单照样要用编进程序的公钥验签,所以它改变不了会安装什么。
+const testSourcesFile = "update-sources.json"
+
+// LoadSources 返回要请求的清单地址。
+func LoadSources(dataDir string) []Source {
+ raw, err := os.ReadFile(filepath.Join(dataDir, testSourcesFile))
+ if err != nil {
+ return DefaultSources
+ }
+ var s []Source
+ if json.Unmarshal(raw, &s) != nil || len(s) == 0 {
+ return DefaultSources
+ }
+ return s
+}
+
+// maxManifest 限制清单与签名的大小,免得一个出错的地址把内存吃满。
+const maxManifest = 1 << 20
+
+// Found 是一次检查拿到的已验签清单。
+type Found struct {
+ Manifest *Manifest
+ Source string
+ At time.Time
+}
+
+// Checker 请求各个地址的清单并验签。
+type Checker struct {
+ HTTP *http.Client
+ Sources []Source
+ Keys []ed25519.PublicKey
+ // Settle 是第一份有效清单到了之后,再等其他地址多久:两边版本不同时用新的那份
+ Settle time.Duration
+}
+
+func NewHTTPClient() *http.Client {
+ return &http.Client{Timeout: 30 * time.Second}
+}
+
+// Check 返回版本最新的有效清单。所有地址都失败时返回最后一个错误。
+func (c *Checker) Check(ctx context.Context) (*Found, error) {
+ ctx, cancel := context.WithTimeout(ctx, 25*time.Second)
+ defer cancel()
+ type result struct {
+ found *Found
+ err error
+ }
+ results := make(chan result, len(c.Sources))
+ for _, s := range c.Sources {
+ go func(s Source) {
+ m, err := c.fetch(ctx, s)
+ if err != nil {
+ results <- result{err: fmt.Errorf("%s: %w", s.Name, err)}
+ return
+ }
+ results <- result{found: &Found{Manifest: m, Source: s.Name, At: time.Now()}}
+ }(s)
+ }
+ var best *Found
+ var lastErr error
+ settle := c.Settle
+ if settle == 0 {
+ settle = 2 * time.Second
+ }
+ var deadline <-chan time.Time
+ for pending := len(c.Sources); pending > 0; pending-- {
+ select {
+ case r := <-results:
+ if r.err != nil {
+ lastErr = r.err
+ continue
+ }
+ if best == nil {
+ deadline = time.After(settle)
+ best = r.found
+ continue
+ }
+ a, _ := ParseVersion(best.Manifest.Latest)
+ b, _ := ParseVersion(r.found.Manifest.Latest)
+ if b.Compare(a) > 0 {
+ best = r.found
+ }
+ case <-deadline:
+ return best, nil
+ case <-ctx.Done():
+ if best != nil {
+ return best, nil
+ }
+ return nil, ctx.Err()
+ }
+ }
+ if best == nil {
+ if lastErr == nil {
+ lastErr = errors.New("没有可用的更新地址")
+ }
+ return nil, lastErr
+ }
+ return best, nil
+}
+
+func (c *Checker) fetch(ctx context.Context, s Source) (*Manifest, error) {
+ raw, err := c.get(ctx, s.Manifest)
+ if err != nil {
+ return nil, err
+ }
+ sig, err := c.get(ctx, s.Manifest+".sig")
+ if err != nil {
+ return nil, err
+ }
+ if err := Verify(raw, sig, c.Keys); err != nil {
+ return nil, err
+ }
+ return Parse(raw)
+}
+
+func (c *Checker) get(ctx context.Context, url string) ([]byte, error) {
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
+ if err != nil {
+ return nil, err
+ }
+ // 只是一次普通的下载:不带设备 ID、版本号之类的任何标识
+ req.Header.Set("User-Agent", "PasteFerry")
+ resp, err := c.HTTP.Do(req)
+ if err != nil {
+ return nil, err
+ }
+ defer resp.Body.Close()
+ if resp.StatusCode != http.StatusOK {
+ return nil, fmt.Errorf("HTTP %d", resp.StatusCode)
+ }
+ raw, err := io.ReadAll(io.LimitReader(resp.Body, maxManifest+1))
+ if err != nil {
+ return nil, err
+ }
+ if len(raw) > maxManifest {
+ return nil, errors.New("更新清单太大")
+ }
+ return raw, nil
+}
diff --git a/client-core/internal/update/download.go b/client-core/internal/update/download.go
new file mode 100644
index 0000000..782f294
--- /dev/null
+++ b/client-core/internal/update/download.go
@@ -0,0 +1,146 @@
+package update
+
+import (
+ "context"
+ "crypto/sha256"
+ "encoding/hex"
+ "errors"
+ "fmt"
+ "io"
+ "net/http"
+ "os"
+ "path/filepath"
+ "strings"
+)
+
+// orderedMirrors 把与清单同一来源的镜像排在前面。
+func orderedMirrors(m *Manifest, source string) []Mirror {
+ var first, rest []Mirror
+ for _, x := range m.Mirrors {
+ if x.Source == source {
+ first = append(first, x)
+ } else {
+ rest = append(rest, x)
+ }
+ }
+ return append(first, rest...)
+}
+
+// Download 把安装包下载到 dir 里,大小与 SHA-256 都对上才返回它的路径。
+// 已经下载好的同一个文件直接复用。各个镜像依次尝试,某个镜像的文件不对就换下一个。
+func Download(ctx context.Context, client *http.Client, m *Manifest, source string, a Asset, dir string,
+ progress func(done, total int64)) (string, error) {
+ if err := os.MkdirAll(dir, 0o700); err != nil {
+ return "", err
+ }
+ dest := filepath.Join(dir, a.Name)
+ if ok, _ := matches(dest, a); ok {
+ if progress != nil {
+ progress(a.Size, a.Size)
+ }
+ return dest, nil
+ }
+ var lastErr error
+ for _, mirror := range orderedMirrors(m, source) {
+ if !strings.HasPrefix(mirror.Base, "https://") && !strings.HasPrefix(mirror.Base, "http://") {
+ continue
+ }
+ err := downloadFrom(ctx, client, mirror.Base+a.Name, dest, a, progress)
+ if err == nil {
+ return dest, nil
+ }
+ if ctx.Err() != nil {
+ return "", ctx.Err()
+ }
+ lastErr = fmt.Errorf("%s: %w", mirror.Source, err)
+ }
+ if lastErr == nil {
+ lastErr = errors.New("没有可用的下载地址")
+ }
+ return "", lastErr
+}
+
+func downloadFrom(ctx context.Context, client *http.Client, url, dest string, a Asset, progress func(done, total int64)) error {
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
+ if err != nil {
+ return err
+ }
+ req.Header.Set("User-Agent", "PasteFerry")
+ // 下载大文件不受检查清单时的 30 秒总超时限制,靠 ctx 取消
+ dl := *client
+ dl.Timeout = 0
+ resp, err := dl.Do(req)
+ if err != nil {
+ return err
+ }
+ defer resp.Body.Close()
+ if resp.StatusCode != http.StatusOK {
+ return fmt.Errorf("HTTP %d", resp.StatusCode)
+ }
+ if resp.ContentLength > 0 && resp.ContentLength != a.Size {
+ return fmt.Errorf("文件大小是 %d,清单里是 %d", resp.ContentLength, a.Size)
+ }
+ part := dest + ".part"
+ f, err := os.OpenFile(part, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0o600)
+ if err != nil {
+ return err
+ }
+ h := sha256.New()
+ var done int64
+ buf := make([]byte, 256<<10)
+ for {
+ n, rerr := resp.Body.Read(buf)
+ if n > 0 {
+ if done+int64(n) > a.Size {
+ f.Close()
+ os.Remove(part)
+ return errors.New("文件比清单里的大")
+ }
+ if _, werr := f.Write(buf[:n]); werr != nil {
+ f.Close()
+ os.Remove(part)
+ return werr
+ }
+ h.Write(buf[:n])
+ done += int64(n)
+ if progress != nil {
+ progress(done, a.Size)
+ }
+ }
+ if rerr == io.EOF {
+ break
+ }
+ if rerr != nil {
+ f.Close()
+ os.Remove(part)
+ return rerr
+ }
+ }
+ if err := f.Close(); err != nil {
+ os.Remove(part)
+ return err
+ }
+ if done != a.Size || !strings.EqualFold(hex.EncodeToString(h.Sum(nil)), a.SHA256) {
+ os.Remove(part)
+ return errors.New("下载的文件与更新清单里的校验值不一致")
+ }
+ return os.Rename(part, dest)
+}
+
+// matches 检查已有的文件是否就是清单里的那个。
+func matches(path string, a Asset) (bool, error) {
+ f, err := os.Open(path)
+ if err != nil {
+ return false, err
+ }
+ defer f.Close()
+ st, err := f.Stat()
+ if err != nil || st.Size() != a.Size {
+ return false, err
+ }
+ h := sha256.New()
+ if _, err := io.Copy(h, f); err != nil {
+ return false, err
+ }
+ return strings.EqualFold(hex.EncodeToString(h.Sum(nil)), a.SHA256), nil
+}
diff --git a/client-core/internal/update/keys.go b/client-core/internal/update/keys.go
new file mode 100644
index 0000000..8cb0d3d
--- /dev/null
+++ b/client-core/internal/update/keys.go
@@ -0,0 +1,23 @@
+package update
+
+import (
+ "crypto/ed25519"
+ "encoding/base64"
+)
+
+// publicKeys 是验证更新清单签名的公钥。私钥只在发版用的 Mac 的钥匙串里(cmd/updatesign)。
+// 换密钥时先把新公钥加在这里发一版,等多数用户更新后再去掉旧的。
+var publicKeys = []string{
+ "EWOfsEYPzDLBExiUJblZe26t+jhXNzKNY3CF8lNyvGE=",
+}
+
+// PublicKeys 返回编进程序的公钥。
+func PublicKeys() []ed25519.PublicKey {
+ var out []ed25519.PublicKey
+ for _, k := range publicKeys {
+ if b, err := base64.StdEncoding.DecodeString(k); err == nil && len(b) == ed25519.PublicKeySize {
+ out = append(out, ed25519.PublicKey(b))
+ }
+ }
+ return out
+}
diff --git a/client-core/internal/update/manifest.go b/client-core/internal/update/manifest.go
new file mode 100644
index 0000000..f337923
--- /dev/null
+++ b/client-core/internal/update/manifest.go
@@ -0,0 +1,184 @@
+// Package update 检查、下载并安装新版本。
+//
+// 更新清单 updates/latest.json 放在 GitHub 仓库里,随发版提交更新,Gitee 镜像同步一份;
+// 本地只下载、验签、解析。清单用 Ed25519 签名(updates/latest.json.sig),公钥编进程序:
+// 镜像或 CDN 被篡改时,程序不会安装被替换的安装包。每个安装包再按清单里的 SHA-256 校验。
+// 设计见 design/auto-update.md。
+package update
+
+import (
+ "crypto/ed25519"
+ "encoding/base64"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "strconv"
+ "strings"
+)
+
+// Schema 是清单格式的版本。不认识的格式一律当作没有更新,不去猜。
+const Schema = 1
+
+// Manifest 是 updates/latest.json 的内容。
+type Manifest struct {
+ Schema int `json:"schema"`
+ Latest string `json:"latest"`
+ Date string `json:"date"`
+ // Mirrors 是最新版安装包所在的目录,文件名见 Assets。source 与 Source.Name 对应:
+ // 从哪个源拿到的清单,就先从同一个源下载
+ Mirrors []Mirror `json:"mirrors"`
+ Assets map[string]Asset `json:"assets"`
+ // Releases 按版本从新到旧,最多保留最近 10 个版本的更新日志
+ Releases []Release `json:"releases"`
+}
+
+type Mirror struct {
+ Source string `json:"source"`
+ Base string `json:"base"`
+}
+
+type Asset struct {
+ Name string `json:"name"`
+ Size int64 `json:"size"`
+ SHA256 string `json:"sha256"`
+}
+
+type Release struct {
+ Version string `json:"version"`
+ Date string `json:"date"`
+ // Notes 的键是界面语言:en、zh-Hans、zh-Hant-TW、zh-Hant-HK、ja
+ Notes map[string]Notes `json:"notes"`
+}
+
+type Notes struct {
+ Changes []string `json:"changes,omitempty"`
+ Fixes []string `json:"fixes,omitempty"`
+}
+
+// Languages 是更新日志必须齐全的语言,与界面支持的语言一致。
+var Languages = []string{"en", "zh-Hans", "zh-Hant-TW", "zh-Hant-HK", "ja"}
+
+// fallback 是缺某种语言时依次尝试的语言:香港用台湾的繁体,繁体都没有时用简体,最后用英文。
+var fallback = map[string][]string{
+ "zh-Hant-HK": {"zh-Hant-HK", "zh-Hant-TW", "zh-Hans", "en"},
+ "zh-Hant-TW": {"zh-Hant-TW", "zh-Hant-HK", "zh-Hans", "en"},
+ "zh-Hans": {"zh-Hans", "zh-Hant-TW", "en"},
+ "ja": {"ja", "en"},
+ "en": {"en"},
+}
+
+// Localized 按界面语言挑出这一版的更新日志。
+func (r Release) Localized(lang string) Notes {
+ order, ok := fallback[lang]
+ if !ok {
+ order = fallback["en"]
+ }
+ for _, l := range order {
+ if n, ok := r.Notes[l]; ok && (len(n.Changes) > 0 || len(n.Fixes) > 0) {
+ return n
+ }
+ }
+ return Notes{}
+}
+
+// Verify 用编进程序的公钥验证清单签名。sig 是 base64,允许末尾的换行。
+func Verify(raw, sig []byte, keys []ed25519.PublicKey) error {
+ s, err := base64.StdEncoding.DecodeString(strings.TrimSpace(string(sig)))
+ if err != nil || len(s) != ed25519.SignatureSize {
+ return errors.New("更新清单的签名格式不对")
+ }
+ for _, k := range keys {
+ if ed25519.Verify(k, raw, s) {
+ return nil
+ }
+ }
+ return errors.New("更新清单的签名不对")
+}
+
+// Parse 解析已验签的清单,并检查它自洽:最新版本有安装包、有下载地址。
+func Parse(raw []byte) (*Manifest, error) {
+ var m Manifest
+ if err := json.Unmarshal(raw, &m); err != nil {
+ return nil, fmt.Errorf("解析更新清单: %w", err)
+ }
+ if m.Schema != Schema {
+ return nil, fmt.Errorf("不认识的更新清单格式 %d", m.Schema)
+ }
+ if _, err := ParseVersion(m.Latest); err != nil {
+ return nil, err
+ }
+ if len(m.Mirrors) == 0 || len(m.Assets) == 0 {
+ return nil, errors.New("更新清单里没有安装包")
+ }
+ for key, a := range m.Assets {
+ if a.Name == "" || strings.ContainsAny(a.Name, `/\`) || a.Size <= 0 || len(a.SHA256) != 64 {
+ return nil, fmt.Errorf("更新清单里的安装包 %s 不完整", key)
+ }
+ }
+ return &m, nil
+}
+
+// Newer 返回比 current 新的各版更新日志,从新到旧。
+func (m *Manifest) Newer(current Version) []Release {
+ var out []Release
+ for _, r := range m.Releases {
+ if v, err := ParseVersion(r.Version); err == nil && v.Compare(current) > 0 {
+ out = append(out, r)
+ }
+ }
+ return out
+}
+
+// Version 是 X.Y.Z,可以带 -后缀(开发与测试构建)。带后缀的比同号的正式版旧。
+type Version struct {
+ Major, Minor, Patch int
+ Pre string
+}
+
+func ParseVersion(s string) (Version, error) {
+ core, pre, _ := strings.Cut(strings.TrimPrefix(strings.TrimSpace(s), "v"), "-")
+ parts := strings.Split(core, ".")
+ if len(parts) != 3 {
+ return Version{}, fmt.Errorf("版本号 %q 不是 X.Y.Z", s)
+ }
+ var n [3]int
+ for i, p := range parts {
+ v, err := strconv.Atoi(p)
+ if err != nil || v < 0 {
+ return Version{}, fmt.Errorf("版本号 %q 不是 X.Y.Z", s)
+ }
+ n[i] = v
+ }
+ return Version{n[0], n[1], n[2], pre}, nil
+}
+
+func (v Version) Compare(o Version) int {
+ for _, d := range [][2]int{{v.Major, o.Major}, {v.Minor, o.Minor}, {v.Patch, o.Patch}} {
+ if d[0] != d[1] {
+ if d[0] < d[1] {
+ return -1
+ }
+ return 1
+ }
+ }
+ switch {
+ case v.Pre == o.Pre:
+ return 0
+ case v.Pre == "":
+ return 1
+ case o.Pre == "":
+ return -1
+ case v.Pre < o.Pre:
+ return -1
+ default:
+ return 1
+ }
+}
+
+func (v Version) String() string {
+ s := fmt.Sprintf("%d.%d.%d", v.Major, v.Minor, v.Patch)
+ if v.Pre != "" {
+ s += "-" + v.Pre
+ }
+ return s
+}
diff --git a/client-core/internal/update/proc_other.go b/client-core/internal/update/proc_other.go
new file mode 100644
index 0000000..e2c6869
--- /dev/null
+++ b/client-core/internal/update/proc_other.go
@@ -0,0 +1,18 @@
+//go:build !darwin && !linux && !windows
+
+package update
+
+import (
+ "errors"
+ "log/slog"
+ "time"
+)
+
+func waitExit(int, time.Duration) bool { return true }
+func terminate(int) {}
+func kill(int) {}
+func processInDir(int, string) bool { return false }
+func startDetached(string, ...string) error { return errors.New("unsupported") }
+func prepare(*Plan, string) error { return errors.New("unsupported") }
+func apply(*Plan, *slog.Logger) error { return errors.New("unsupported") }
+func relaunch(*Plan, *slog.Logger) error { return nil }
diff --git a/client-core/internal/update/proc_unix.go b/client-core/internal/update/proc_unix.go
new file mode 100644
index 0000000..da7cca8
--- /dev/null
+++ b/client-core/internal/update/proc_unix.go
@@ -0,0 +1,66 @@
+//go:build darwin || linux
+
+package update
+
+import (
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strconv"
+ "strings"
+ "syscall"
+ "time"
+)
+
+// alive 把僵尸进程也算作已退出:结束守护进程后,它的子进程可能要等一会儿才被收走。
+func alive(pid int) bool {
+ if err := syscall.Kill(pid, 0); err != nil && err != syscall.EPERM {
+ return false
+ }
+ if raw, err := os.ReadFile("/proc/" + itoa(pid) + "/stat"); err == nil {
+ if i := strings.LastIndexByte(string(raw), ')'); i > 0 && i+2 < len(raw) && raw[i+2] == 'Z' {
+ return false
+ }
+ }
+ return true
+}
+
+func waitExit(pid int, timeout time.Duration) bool {
+ deadline := time.Now().Add(timeout)
+ for alive(pid) {
+ if time.Now().After(deadline) {
+ return false
+ }
+ time.Sleep(200 * time.Millisecond)
+ }
+ return true
+}
+
+func terminate(pid int) { _ = syscall.Kill(pid, syscall.SIGTERM) }
+func kill(pid int) { _ = syscall.Kill(pid, syscall.SIGKILL) }
+
+// processInDir 判断进程的程序文件是否在 dir 里。替换后旧程序文件已被删掉,
+// Linux 的 /proc/<pid>/exe 会带上 " (deleted)"。
+func processInDir(pid int, dir string) bool {
+ exe, err := os.Readlink("/proc/" + itoa(pid) + "/exe")
+ if err != nil {
+ out, perr := exec.Command("ps", "-p", itoa(pid), "-o", "comm=").Output()
+ if perr != nil {
+ return false
+ }
+ exe = strings.TrimSpace(string(out))
+ }
+ exe = strings.TrimSuffix(exe, " (deleted)")
+ return strings.HasPrefix(exe, filepath.Clean(dir)+string(filepath.Separator))
+}
+
+func startDetached(path string, args ...string) error {
+ cmd := exec.Command(path, args...)
+ cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true}
+ if err := cmd.Start(); err != nil {
+ return err
+ }
+ return cmd.Process.Release()
+}
+
+func itoa(n int) string { return strconv.Itoa(n) }
diff --git a/client-core/internal/update/proc_windows.go b/client-core/internal/update/proc_windows.go
new file mode 100644
index 0000000..e11c886
--- /dev/null
+++ b/client-core/internal/update/proc_windows.go
@@ -0,0 +1,60 @@
+package update
+
+import (
+ "os/exec"
+ "path/filepath"
+ "strings"
+ "syscall"
+ "time"
+
+ "golang.org/x/sys/windows"
+)
+
+func waitExit(pid int, timeout time.Duration) bool {
+ h, err := windows.OpenProcess(windows.SYNCHRONIZE, false, uint32(pid))
+ if err != nil {
+ return true // 打不开就是已经退出了
+ }
+ defer windows.CloseHandle(h)
+ ev, err := windows.WaitForSingleObject(h, uint32(timeout/time.Millisecond))
+ return err == nil && ev == windows.WAIT_OBJECT_0
+}
+
+// Windows 上没有能让后台服务自己收尾的信号,直接结束;数据库每次写入都已落盘。
+func terminate(pid int) { kill(pid) }
+
+func kill(pid int) {
+ h, err := windows.OpenProcess(windows.PROCESS_TERMINATE, false, uint32(pid))
+ if err != nil {
+ return
+ }
+ defer windows.CloseHandle(h)
+ _ = windows.TerminateProcess(h, 1)
+}
+
+func processInDir(pid int, dir string) bool {
+ h, err := windows.OpenProcess(windows.PROCESS_QUERY_LIMITED_INFORMATION, false, uint32(pid))
+ if err != nil {
+ return false
+ }
+ defer windows.CloseHandle(h)
+ buf := make([]uint16, windows.MAX_LONG_PATH)
+ n := uint32(len(buf))
+ if err := windows.QueryFullProcessImageName(h, 0, &buf[0], &n); err != nil {
+ return false
+ }
+ exe := windows.UTF16ToString(buf[:n])
+ return strings.HasPrefix(strings.ToLower(exe), strings.ToLower(filepath.Clean(dir))+`\`)
+}
+
+func startDetached(path string, args ...string) error {
+ cmd := exec.Command(path, args...)
+ cmd.SysProcAttr = &syscall.SysProcAttr{
+ CreationFlags: windows.DETACHED_PROCESS | windows.CREATE_NEW_PROCESS_GROUP,
+ HideWindow: true,
+ }
+ if err := cmd.Start(); err != nil {
+ return err
+ }
+ return cmd.Process.Release()
+}
diff --git a/client-core/internal/update/service.go b/client-core/internal/update/service.go
new file mode 100644
index 0000000..9f32e24
--- /dev/null
+++ b/client-core/internal/update/service.go
@@ -0,0 +1,232 @@
+package update
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "log/slog"
+ "net/http"
+ "os"
+ "path/filepath"
+ "strings"
+ "sync"
+ "time"
+)
+
+// 自动检查的节奏:启动一分钟后查一次,之后每 24 小时一次。
+const (
+ firstCheckDelay = time.Minute
+ checkInterval = 24 * time.Hour
+ // resultFresh 内界面显示「已更新到 X」,之后不再提
+ resultFresh = 15 * time.Minute
+)
+
+// Service 是后台服务里的更新功能:定时检查、下载、交给更新助手安装。
+type Service struct {
+ Current Version
+ Root string // 数据目录;下载放在 Root/updates/<版本>/ 里
+ Target Target
+ Checker *Checker
+ HTTP *http.Client
+ // AutoCheck 为 false 时不自动检查(设置里关掉了);Skipped 是用户选择跳过的版本
+ AutoCheck func() bool
+ Skipped func() string
+ // Changed 在检查结果变化时调用,让界面刷新状态
+ Changed func()
+ Log *slog.Logger
+
+ mu sync.Mutex
+ found *Found
+ checkedAt time.Time
+ lastAuto time.Time
+ files map[string]string // 版本 → 已下载并校验过的安装包
+ result *Result
+ resultAt time.Time
+}
+
+// NewService 读出上一次安装的结果(如果有)。
+func NewService(current, root string, log *slog.Logger) (*Service, error) {
+ v, err := ParseVersion(current)
+ if err != nil {
+ return nil, err
+ }
+ client := NewHTTPClient()
+ s := &Service{
+ Current: v, Root: root, Target: DetectTarget(), HTTP: client, Log: log,
+ Checker: &Checker{HTTP: client, Sources: LoadSources(root), Keys: PublicKeys()},
+ files: map[string]string{},
+ }
+ if r := ReadResult(root); r != nil {
+ s.result, s.resultAt = r, time.Now()
+ }
+ return s, nil
+}
+
+// Run 按节奏自动检查,直到 ctx 结束。
+func (s *Service) Run(ctx context.Context) {
+ timer := time.NewTimer(firstCheckDelay)
+ defer timer.Stop()
+ for {
+ select {
+ case <-ctx.Done():
+ return
+ case <-timer.C:
+ }
+ s.cleanup()
+ if s.AutoCheck == nil || s.AutoCheck() {
+ s.mu.Lock()
+ due := time.Since(s.lastAuto) >= checkInterval
+ s.mu.Unlock()
+ if due {
+ if _, err := s.Check(ctx); err != nil {
+ s.Log.Info("自动检查更新失败", "err", err)
+ }
+ s.mu.Lock()
+ s.lastAuto = time.Now()
+ s.mu.Unlock()
+ }
+ }
+ timer.Reset(time.Hour)
+ }
+}
+
+// Check 立即检查一次。
+func (s *Service) Check(ctx context.Context) (*Found, error) {
+ found, err := s.Checker.Check(ctx)
+ if err != nil {
+ return nil, err
+ }
+ s.mu.Lock()
+ changed := s.found == nil || s.found.Manifest.Latest != found.Manifest.Latest
+ s.found, s.checkedAt = found, time.Now()
+ s.mu.Unlock()
+ if changed && s.Changed != nil {
+ s.Changed()
+ }
+ return found, nil
+}
+
+// Latest 是最近一次检查拿到的清单与检查时间。
+func (s *Service) Latest() (*Found, time.Time) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ return s.found, s.checkedAt
+}
+
+// Notice 是要在界面上提示的新版本:比当前新、没被跳过、自动检查开着。没有返回空字符串。
+func (s *Service) Notice() string {
+ s.mu.Lock()
+ found := s.found
+ s.mu.Unlock()
+ if found == nil || (s.AutoCheck != nil && !s.AutoCheck()) {
+ return ""
+ }
+ v, err := ParseVersion(found.Manifest.Latest)
+ if err != nil || v.Compare(s.Current) <= 0 {
+ return ""
+ }
+ if s.Skipped != nil && s.Skipped() == v.String() {
+ return ""
+ }
+ return v.String()
+}
+
+// LastResult 是刚完成的那次安装的结果,过了 resultFresh 就不再提。
+func (s *Service) LastResult() *Result {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ if s.result == nil || time.Since(s.resultAt) > resultFresh {
+ return nil
+ }
+ return s.result
+}
+
+// Asset 是这台电脑要下载的安装包。
+func (s *Service) Asset(m *Manifest) (Asset, bool) {
+ a, ok := m.Assets[s.Target.Asset]
+ return a, ok && s.Target.Asset != ""
+}
+
+func (s *Service) workDir(version string) string {
+ return filepath.Join(s.Root, "updates", version)
+}
+
+// Download 下载并校验 version 的安装包。只能下载最近一次检查到的最新版本。
+func (s *Service) Download(ctx context.Context, version string, progress func(done, total int64)) error {
+ found, _ := s.Latest()
+ if found == nil || found.Manifest.Latest != version {
+ return errors.New("先检查更新")
+ }
+ if s.Target.Blocker != "" {
+ return fmt.Errorf("这种安装方式不能自动更新(%s)", s.Target.Blocker)
+ }
+ a, ok := s.Asset(found.Manifest)
+ if !ok {
+ return errors.New("没有这台电脑可用的安装包")
+ }
+ s.removeOtherDownloads(version)
+ path, err := Download(ctx, s.HTTP, found.Manifest, found.Source, a, s.workDir(version), progress)
+ if err != nil {
+ return err
+ }
+ s.mu.Lock()
+ s.files[version] = path
+ s.mu.Unlock()
+ return nil
+}
+
+// Install 准备好新版本并启动更新助手。返回 nil 后界面应当立即退出,助手等它退出后替换文件并重新打开。
+func (s *Service) Install(version string, uiPID int) error {
+ s.mu.Lock()
+ path := s.files[version]
+ s.mu.Unlock()
+ if path == "" {
+ return errors.New("安装包还没有下载好")
+ }
+ work := s.workDir(version)
+ p, err := Prepare(s.Target, path, s.Current.String(), version, work, uiPID)
+ if err != nil {
+ return err
+ }
+ p.Daemons = []int{os.Getpid(), os.Getppid()}
+ if err := Start(p, work); err != nil {
+ return err
+ }
+ s.Log.Info("已启动更新助手", "from", p.From, "to", p.To, "kind", p.Kind)
+ return nil
+}
+
+// removeOtherDownloads 只保留正在下载的版本,旧的安装包不占地方。
+func (s *Service) removeOtherDownloads(keep string) {
+ entries, _ := os.ReadDir(filepath.Join(s.Root, "updates"))
+ for _, e := range entries {
+ if e.IsDir() && e.Name() != keep {
+ _ = os.RemoveAll(filepath.Join(s.Root, "updates", e.Name()))
+ }
+ }
+}
+
+// cleanup 删掉已经装上的版本的下载,以及上次替换时没删干净的旧程序。
+func (s *Service) cleanup() {
+ entries, _ := os.ReadDir(filepath.Join(s.Root, "updates"))
+ for _, e := range entries {
+ if v, err := ParseVersion(e.Name()); err == nil && e.IsDir() && v.Compare(s.Current) <= 0 {
+ _ = os.RemoveAll(filepath.Join(s.Root, "updates", e.Name()))
+ }
+ }
+ if s.Target.App == "" {
+ return
+ }
+ leftovers, _ := filepath.Glob(filepath.Join(filepath.Dir(s.Target.App), ".PasteFerry-*"))
+ for _, l := range leftovers {
+ // 刚准备好、正等界面退出的新版本不能动
+ if st, err := os.Stat(l); err != nil || time.Since(st.ModTime()) < 10*time.Minute {
+ continue
+ }
+ name := filepath.Base(l)
+ if strings.HasSuffix(name, ".old") || strings.HasSuffix(name, ".app.old") ||
+ strings.HasPrefix(name, ".PasteFerry-update-") || strings.HasSuffix(name, ".app") {
+ _ = os.RemoveAll(l)
+ }
+ }
+}
diff --git a/client-core/internal/update/target.go b/client-core/internal/update/target.go
new file mode 100644
index 0000000..ad2410d
--- /dev/null
+++ b/client-core/internal/update/target.go
@@ -0,0 +1,59 @@
+package update
+
+import (
+ "os"
+ "path/filepath"
+)
+
+// Kind 是本机的安装方式,决定下载哪个安装包、怎么装。
+type Kind string
+
+const (
+ KindMacApp Kind = "mac-app" // /Applications 等处的 PasteFerry.app,用 DMG 里的 App 替换
+ KindWindowsSetup Kind = "windows-setup" // 安装程序装的,静默运行新的安装程序
+ KindWindowsPortable Kind = "windows-portable" // 便携版文件夹,解压新的 zip 替换
+ KindLinuxDeb Kind = "linux-deb" // /opt/PasteFerry,用 pkexec 安装新的 .deb
+ KindLinuxTar Kind = "linux-tar" // 解压出来的文件夹,解压新的 tar.gz 替换
+)
+
+// 不能自动安装的原因,界面按它给出说明,并改为打开下载页。
+const (
+ BlockerDev = "dev" // 开发构建,不在发布包里运行
+ BlockerMustMove = "must_move" // Mac 上直接从 DMG 或随机化路径运行
+ BlockerReadOnly = "read_only" // 安装位置没有写权限
+ BlockerUnsupported = "unsupported" // 没有这个系统或芯片的安装包
+)
+
+// Target 描述本机怎么更新。
+type Target struct {
+ Kind Kind
+ // Asset 是清单里安装包的键,如 mac-arm64、windows-setup、linux-amd64-deb
+ Asset string
+ // App 是要替换的位置:Mac 上是 .app,Windows、Linux 上是程序所在的文件夹
+ App string
+ // Blocker 不为空时不能自动安装
+ Blocker string
+}
+
+// DetectTarget 按后台服务自身所在的位置判断安装方式。
+func DetectTarget() Target {
+ exe, err := os.Executable()
+ if err != nil {
+ return Target{Blocker: BlockerUnsupported}
+ }
+ if resolved, err := filepath.EvalSymlinks(exe); err == nil {
+ exe = resolved
+ }
+ return detectTarget(exe)
+}
+
+// writable 判断能否在 dir 里新建与改名文件:替换安装要在同一个文件夹里改名。
+func writable(dir string) bool {
+ f, err := os.CreateTemp(dir, ".pasteferry-write-test-*")
+ if err != nil {
+ return false
+ }
+ name := f.Name()
+ f.Close()
+ return os.Remove(name) == nil
+}
diff --git a/client-core/internal/update/target_darwin.go b/client-core/internal/update/target_darwin.go
new file mode 100644
index 0000000..088410d
--- /dev/null
+++ b/client-core/internal/update/target_darwin.go
@@ -0,0 +1,34 @@
+package update
+
+import (
+ "debug/macho"
+ "path/filepath"
+ "runtime"
+ "strings"
+)
+
+// detectTarget:后台服务在 PasteFerry.app/Contents/Helpers/PasteFerryDaemon.app/Contents/MacOS/ 里。
+func detectTarget(exe string) Target {
+ i := strings.Index(exe, ".app/Contents/Helpers/")
+ if i < 0 {
+ return Target{Kind: KindMacApp, Blocker: BlockerDev}
+ }
+ app := exe[:i+len(".app")]
+ t := Target{Kind: KindMacApp, App: app}
+ switch {
+ case strings.HasPrefix(app, "/Volumes/") || strings.Contains(app, "/AppTranslocation/"):
+ t.Blocker = BlockerMustMove
+ case !writable(filepath.Dir(app)) || !writable(app):
+ t.Blocker = BlockerReadOnly
+ }
+ // 装的是通用版就继续用通用版;单芯片版按本机芯片
+ if f, err := macho.OpenFat(filepath.Join(app, "Contents", "MacOS", "PasteFerry")); err == nil {
+ f.Close()
+ t.Asset = "mac-universal"
+ } else if runtime.GOARCH == "arm64" {
+ t.Asset = "mac-arm64"
+ } else {
+ t.Asset = "mac-x64"
+ }
+ return t
+}
diff --git a/client-core/internal/update/target_linux.go b/client-core/internal/update/target_linux.go
new file mode 100644
index 0000000..28afead
--- /dev/null
+++ b/client-core/internal/update/target_linux.go
@@ -0,0 +1,39 @@
+package update
+
+import (
+ "os"
+ "os/exec"
+ "path/filepath"
+ "runtime"
+ "strings"
+)
+
+// DebDir 是 .deb 的安装位置。
+const DebDir = "/opt/PasteFerry"
+
+// detectTarget:.deb 装在 /opt/PasteFerry 并登记在 dpkg 里;其他位置当作解压出来的 tar.gz。
+func detectTarget(exe string) Target {
+ dir := filepath.Dir(exe)
+ if runtime.GOARCH != "amd64" && runtime.GOARCH != "arm64" {
+ return Target{App: dir, Blocker: BlockerUnsupported}
+ }
+ if dir == DebDir && debInstalled() {
+ t := Target{Kind: KindLinuxDeb, Asset: "linux-" + runtime.GOARCH + "-deb", App: dir}
+ if _, err := exec.LookPath("pkexec"); err != nil {
+ t.Blocker = BlockerReadOnly
+ }
+ return t
+ }
+ t := Target{Kind: KindLinuxTar, Asset: "linux-" + runtime.GOARCH + "-tar", App: dir}
+ if _, err := os.Stat(filepath.Join(dir, "pasteferry")); err != nil {
+ t.Blocker = BlockerDev
+ } else if !writable(dir) || !writable(filepath.Dir(dir)) {
+ t.Blocker = BlockerReadOnly
+ }
+ return t
+}
+
+func debInstalled() bool {
+ out, err := exec.Command("dpkg-query", "-W", "-f=${Status}", "pasteferry").Output()
+ return err == nil && strings.Contains(string(out), "install ok installed")
+}
diff --git a/client-core/internal/update/target_other.go b/client-core/internal/update/target_other.go
new file mode 100644
index 0000000..af7b1dc
--- /dev/null
+++ b/client-core/internal/update/target_other.go
@@ -0,0 +1,5 @@
+//go:build !darwin && !windows && !linux
+
+package update
+
+func detectTarget(string) Target { return Target{Blocker: BlockerUnsupported} }
diff --git a/client-core/internal/update/target_windows.go b/client-core/internal/update/target_windows.go
new file mode 100644
index 0000000..3c2754e
--- /dev/null
+++ b/client-core/internal/update/target_windows.go
@@ -0,0 +1,25 @@
+package update
+
+import (
+ "os"
+ "path/filepath"
+ "runtime"
+)
+
+// detectTarget:安装程序会在程序文件夹里留下卸载程序 unins000.exe,便携版没有。
+func detectTarget(exe string) Target {
+ dir := filepath.Dir(exe)
+ if runtime.GOARCH != "amd64" {
+ return Target{App: dir, Blocker: BlockerUnsupported}
+ }
+ if _, err := os.Stat(filepath.Join(dir, "unins000.exe")); err == nil {
+ return Target{Kind: KindWindowsSetup, Asset: "windows-setup", App: dir}
+ }
+ t := Target{Kind: KindWindowsPortable, Asset: "windows-portable", App: dir}
+ if _, err := os.Stat(filepath.Join(dir, "PasteFerry.exe")); err != nil {
+ t.Blocker = BlockerDev
+ } else if !writable(dir) || !writable(filepath.Dir(dir)) {
+ t.Blocker = BlockerReadOnly
+ }
+ return t
+}
diff --git a/client-core/internal/update/update_test.go b/client-core/internal/update/update_test.go
new file mode 100644
index 0000000..9229faf
--- /dev/null
+++ b/client-core/internal/update/update_test.go
@@ -0,0 +1,345 @@
+package update
+
+import (
+ "archive/tar"
+ "archive/zip"
+ "bytes"
+ "compress/gzip"
+ "context"
+ "crypto/ed25519"
+ "crypto/rand"
+ "crypto/sha256"
+ "encoding/base64"
+ "encoding/hex"
+ "encoding/json"
+ "io"
+ "log/slog"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "strings"
+ "sync/atomic"
+ "testing"
+ "time"
+)
+
+func TestVersionCompare(t *testing.T) {
+ cases := []struct {
+ a, b string
+ want int
+ }{
+ {"2.3.0", "2.2.9", 1}, {"2.3.0", "2.3.0", 0}, {"2.10.0", "2.9.9", 1},
+ {"v2.3.0", "2.3.0", 0}, {"2.3.0-test", "2.3.0", -1}, {"2.3.1-test", "2.3.0", 1},
+ }
+ for _, c := range cases {
+ a, err := ParseVersion(c.a)
+ if err != nil {
+ t.Fatal(err)
+ }
+ b, _ := ParseVersion(c.b)
+ if got := a.Compare(b); got != c.want {
+ t.Errorf("%s vs %s = %d, want %d", c.a, c.b, got, c.want)
+ }
+ }
+ for _, bad := range []string{"", "2.3", "2.3.x", "-1.0.0", "1.2.3.4"} {
+ if _, err := ParseVersion(bad); err == nil {
+ t.Errorf("accepted %q", bad)
+ }
+ }
+}
+
+func TestLocalizedFallsBackByScript(t *testing.T) {
+ r := Release{Notes: map[string]Notes{
+ "en": {Changes: []string{"en"}},
+ "zh-Hans": {Changes: []string{"简"}},
+ "zh-Hant-TW": {Changes: []string{"台"}},
+ }}
+ for lang, want := range map[string]string{"zh-Hant-HK": "台", "zh-Hans": "简", "ja": "en", "fr": "en", "en": "en"} {
+ if got := r.Localized(lang).Changes; len(got) != 1 || got[0] != want {
+ t.Errorf("%s → %v, want %s", lang, got, want)
+ }
+ }
+}
+
+// fixture 建一个签过名的清单与对应的安装包。
+type fixture struct {
+ pub ed25519.PublicKey
+ priv ed25519.PrivateKey
+ payload []byte
+}
+
+func newFixture(t *testing.T) *fixture {
+ pub, priv, err := ed25519.GenerateKey(rand.Reader)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return &fixture{pub: pub, priv: priv, payload: bytes.Repeat([]byte("PasteFerry"), 5000)}
+}
+
+func (f *fixture) manifest(latest string, mirrors ...Mirror) []byte {
+ sum := sha256.Sum256(f.payload)
+ m := Manifest{Schema: Schema, Latest: latest, Date: "2026-10-20", Mirrors: mirrors,
+ Assets: map[string]Asset{"test": {Name: "PasteFerry-test.bin", Size: int64(len(f.payload)), SHA256: hex.EncodeToString(sum[:])}},
+ Releases: []Release{
+ {Version: latest, Notes: map[string]Notes{"en": {Changes: []string{"new " + latest}}}},
+ {Version: "2.2.0", Notes: map[string]Notes{"en": {Fixes: []string{"old"}}}},
+ }}
+ raw, _ := json.Marshal(m)
+ return raw
+}
+
+func (f *fixture) sign(raw []byte) []byte {
+ return []byte(base64.StdEncoding.EncodeToString(ed25519.Sign(f.priv, raw)) + "\n")
+}
+
+// serve 发布一个清单(及签名)与安装包;badPayload 为 true 时安装包内容被替换过。
+func (f *fixture) serve(t *testing.T, manifest, sig []byte, badPayload bool) *httptest.Server {
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ switch {
+ case strings.HasSuffix(r.URL.Path, "latest.json"):
+ w.Write(manifest)
+ case strings.HasSuffix(r.URL.Path, "latest.json.sig"):
+ w.Write(sig)
+ case strings.HasSuffix(r.URL.Path, "PasteFerry-test.bin"):
+ p := f.payload
+ if badPayload {
+ p = bytes.Repeat([]byte("Tampered!!"), 5000)
+ }
+ w.Write(p)
+ default:
+ http.NotFound(w, r)
+ }
+ }))
+ t.Cleanup(srv.Close)
+ return srv
+}
+
+func TestCheckerVerifiesAndPrefersNewest(t *testing.T) {
+ f := newFixture(t)
+ older := f.manifest("2.3.0", Mirror{Source: "a", Base: "https://example.invalid/"})
+ newer := f.manifest("2.3.1", Mirror{Source: "b", Base: "https://example.invalid/"})
+ a := f.serve(t, older, f.sign(older), false)
+ b := f.serve(t, newer, f.sign(newer), false)
+ // 被篡改的清单:内容改了,签名还是原来的
+ tampered := f.serve(t, bytes.Replace(newer, []byte("2.3.1"), []byte("9.9.9"), 1), f.sign(newer), false)
+ c := &Checker{HTTP: NewHTTPClient(), Keys: []ed25519.PublicKey{f.pub}, Settle: 500 * time.Millisecond, Sources: []Source{
+ {Name: "a", Manifest: a.URL + "/latest.json"},
+ {Name: "b", Manifest: b.URL + "/latest.json"},
+ {Name: "x", Manifest: tampered.URL + "/latest.json"},
+ }}
+ found, err := c.Check(context.Background())
+ if err != nil {
+ t.Fatal(err)
+ }
+ if found.Manifest.Latest != "2.3.1" || found.Source != "b" {
+ t.Fatalf("got %s from %s", found.Manifest.Latest, found.Source)
+ }
+ cur, _ := ParseVersion("2.2.0")
+ if n := found.Manifest.Newer(cur); len(n) != 1 || n[0].Version != "2.3.1" {
+ t.Fatalf("newer releases: %+v", n)
+ }
+ // 只有被篡改的源时检查失败,而不是采信它
+ c.Sources = []Source{{Name: "x", Manifest: tampered.URL + "/latest.json"}}
+ if _, err := c.Check(context.Background()); err == nil || !strings.Contains(err.Error(), "签名") {
+ t.Fatalf("tampered manifest accepted: %v", err)
+ }
+}
+
+func TestDownloadFallsBackAndVerifies(t *testing.T) {
+ f := newFixture(t)
+ bad := f.serve(t, nil, nil, true)
+ good := f.serve(t, nil, nil, false)
+ var m Manifest
+ json.Unmarshal(f.manifest("2.3.1",
+ Mirror{Source: "bad", Base: bad.URL + "/"}, Mirror{Source: "good", Base: good.URL + "/"}), &m)
+ dir := t.TempDir()
+ var last int64
+ path, err := Download(context.Background(), NewHTTPClient(), &m, "bad", m.Assets["test"], dir,
+ func(done, total int64) { last = done })
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got, _ := os.ReadFile(path); !bytes.Equal(got, f.payload) || last != int64(len(f.payload)) {
+ t.Fatal("downloaded file differs from the manifest")
+ }
+ if _, err := os.Stat(path + ".part"); !os.IsNotExist(err) {
+ t.Fatal("partial file left behind")
+ }
+ // 只有内容被替换过的镜像时下载失败,不留下文件
+ m.Mirrors = m.Mirrors[:1]
+ os.Remove(path)
+ if _, err := Download(context.Background(), NewHTTPClient(), &m, "bad", m.Assets["test"], dir, nil); err == nil {
+ t.Fatal("tampered package accepted")
+ }
+ if entries, _ := os.ReadDir(dir); len(entries) != 0 {
+ t.Fatalf("files left after a failed download: %v", entries)
+ }
+}
+
+func TestDownloadReusesVerifiedFile(t *testing.T) {
+ f := newFixture(t)
+ var hits atomic.Int32
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ hits.Add(1)
+ w.Write(f.payload)
+ }))
+ defer srv.Close()
+ var m Manifest
+ json.Unmarshal(f.manifest("2.3.1", Mirror{Source: "s", Base: srv.URL + "/"}), &m)
+ dir := t.TempDir()
+ for i := 0; i < 2; i++ {
+ if _, err := Download(context.Background(), NewHTTPClient(), &m, "s", m.Assets["test"], dir, nil); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if hits.Load() != 1 {
+ t.Fatalf("downloaded %d times", hits.Load())
+ }
+}
+
+func TestSafeJoinRejectsEscapes(t *testing.T) {
+ root := t.TempDir()
+ for _, bad := range []string{"../x", "a/../../x", "/etc/passwd", `..\x`, `PasteFerry\..\..\x`, ".."} {
+ if _, err := safeJoin(root, bad); err == nil {
+ t.Errorf("accepted %q", bad)
+ }
+ }
+ got, err := safeJoin(root, `PasteFerry\data\app.so`)
+ if err != nil || got != filepath.Join(root, "PasteFerry", "data", "app.so") {
+ t.Fatalf("backslash path → %q, %v", got, err)
+ }
+}
+
+func TestStageFolderFromZipAndTar(t *testing.T) {
+ dir := t.TempDir()
+ // Windows 便携版的 zip 用反斜杠
+ zipPath := filepath.Join(dir, "p.zip")
+ var zb bytes.Buffer
+ zw := zip.NewWriter(&zb)
+ for _, name := range []string{`PasteFerry\PasteFerry.exe`, `PasteFerry\pasteferryd.exe`, `PasteFerry\data\flutter_assets\x`} {
+ w, _ := zw.Create(name)
+ w.Write([]byte(name))
+ }
+ zw.Close()
+ os.WriteFile(zipPath, zb.Bytes(), 0o600)
+ app := filepath.Join(dir, "PasteFerry")
+ p := &Plan{App: app, To: "2.3.1", Package: zipPath}
+ if err := stageFolder(p, unzip, "PasteFerry.exe", "pasteferryd.exe"); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := os.Stat(filepath.Join(p.Staged, "data", "flutter_assets", "x")); err != nil {
+ t.Fatal(err)
+ }
+
+ tgz := filepath.Join(dir, "p.tar.gz")
+ var tb bytes.Buffer
+ gz := gzip.NewWriter(&tb)
+ tw := tar.NewWriter(gz)
+ for _, h := range []*tar.Header{
+ {Name: "PasteFerry/", Typeflag: tar.TypeDir, Mode: 0o755},
+ {Name: "PasteFerry/pasteferry", Typeflag: tar.TypeReg, Mode: 0o755, Size: 2},
+ {Name: "PasteFerry/pasteferryd", Typeflag: tar.TypeReg, Mode: 0o755, Size: 2},
+ {Name: "PasteFerry/lib/libapp.so.1", Typeflag: tar.TypeSymlink, Linkname: "libapp.so"},
+ } {
+ tw.WriteHeader(h)
+ if h.Size > 0 {
+ tw.Write([]byte("ok"))
+ }
+ }
+ tw.Close()
+ gz.Close()
+ os.WriteFile(tgz, tb.Bytes(), 0o600)
+ p = &Plan{App: app, To: "2.3.2", Package: tgz}
+ if err := stageFolder(p, untar, "pasteferry", "pasteferryd"); err != nil {
+ t.Fatal(err)
+ }
+ if st, err := os.Stat(filepath.Join(p.Staged, "pasteferryd")); err != nil || st.Mode().Perm()&0o100 == 0 {
+ t.Fatalf("executable bit lost: %v %v", st, err)
+ }
+ // 缺少必需的文件时不留下解压的东西
+ p = &Plan{App: app, To: "2.3.3", Package: tgz}
+ if err := stageFolder(p, untar, "pasteferry", "missing"); err == nil {
+ t.Fatal("accepted a package without required files")
+ }
+ if _, err := os.Stat(filepath.Join(dir, ".PasteFerry-update-2.3.3")); !os.IsNotExist(err) {
+ t.Fatal("staging folder left behind")
+ }
+}
+
+func TestSwapDirRestoresOnFailure(t *testing.T) {
+ dir := t.TempDir()
+ app := filepath.Join(dir, "PasteFerry")
+ os.MkdirAll(app, 0o755)
+ os.WriteFile(filepath.Join(app, "v"), []byte("old"), 0o600)
+ // 新版本不存在:改名失败,旧版本必须原样回到原处
+ if err := swapDir(app, filepath.Join(dir, "missing"), filepath.Join(dir, ".old")); err == nil {
+ t.Fatal("swap with a missing staged folder succeeded")
+ }
+ if got, _ := os.ReadFile(filepath.Join(app, "v")); string(got) != "old" {
+ t.Fatal("old version was not restored")
+ }
+ staged := filepath.Join(dir, "new")
+ os.MkdirAll(staged, 0o755)
+ os.WriteFile(filepath.Join(staged, "v"), []byte("new"), 0o600)
+ if err := swapDir(app, staged, filepath.Join(dir, ".old")); err != nil {
+ t.Fatal(err)
+ }
+ if got, _ := os.ReadFile(filepath.Join(app, "v")); string(got) != "new" {
+ t.Fatal("new version not in place")
+ }
+}
+
+func TestServiceNoticeRespectsSettings(t *testing.T) {
+ f := newFixture(t)
+ raw := f.manifest("2.3.1", Mirror{Source: "s", Base: "https://example.invalid/"})
+ srv := f.serve(t, raw, f.sign(raw), false)
+ s, err := NewService("2.3.0", t.TempDir(), slog.New(slog.NewTextHandler(io.Discard, nil)))
+ if err != nil {
+ t.Fatal(err)
+ }
+ s.Checker = &Checker{HTTP: NewHTTPClient(), Keys: []ed25519.PublicKey{f.pub}, Sources: []Source{{Name: "s", Manifest: srv.URL + "/latest.json"}}}
+ auto, skipped := true, ""
+ s.AutoCheck = func() bool { return auto }
+ s.Skipped = func() string { return skipped }
+ changed := 0
+ s.Changed = func() { changed++ }
+ if _, err := s.Check(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ if s.Notice() != "2.3.1" || changed != 1 {
+ t.Fatalf("notice %q, changed %d", s.Notice(), changed)
+ }
+ skipped = "2.3.1"
+ if s.Notice() != "" {
+ t.Fatal("skipped version still noticed")
+ }
+ skipped, auto = "", false
+ if s.Notice() != "" {
+ t.Fatal("noticed with automatic checks off")
+ }
+ s.Current, _ = ParseVersion("2.3.1")
+ auto = true
+ if s.Notice() != "" {
+ t.Fatal("noticed the version already installed")
+ }
+}
+
+func TestReadResultOnce(t *testing.T) {
+ root := t.TempDir()
+ os.MkdirAll(filepath.Join(root, "updates"), 0o700)
+ raw, _ := json.Marshal(Result{From: "2.3.0", To: "2.3.1", OK: true, At: time.Now().Unix()})
+ os.WriteFile(filepath.Join(root, "updates", "result.json"), raw, 0o600)
+ if r := ReadResult(root); r == nil || !r.OK || r.To != "2.3.1" {
+ t.Fatalf("result: %+v", r)
+ }
+ if ReadResult(root) != nil {
+ t.Fatal("result read twice")
+ }
+}
+
+func TestPublicKeyIsValid(t *testing.T) {
+ if len(PublicKeys()) == 0 {
+ t.Fatal("no valid public key compiled in")
+ }
+}
diff --git a/proto/gen/pasteferry/v1/daemon.pb.go b/proto/gen/pasteferry/v1/daemon.pb.go
index b7a2599..6379acb 100644
--- a/proto/gen/pasteferry/v1/daemon.pb.go
+++ b/proto/gen/pasteferry/v1/daemon.pb.go
@@ -1995,8 +1995,12 @@ type Config struct {
ServiceMode ServiceMode `protobuf:"varint,15,opt,name=service_mode,json=serviceMode,proto3,enum=pasteferry.v1.ServiceMode" json:"service_mode,omitempty"`
CustomSignalingUrl string `protobuf:"bytes,16,opt,name=custom_signaling_url,json=customSignalingUrl,proto3" json:"custom_signaling_url,omitempty"`
OfficialNoticeAck string `protobuf:"bytes,17,opt,name=official_notice_ack,json=officialNoticeAck,proto3" json:"official_notice_ack,omitempty"`
- unknownFields protoimpl.UnknownFields
- sizeCache protoimpl.SizeCache
+ // 不自动检查更新。写成反向的:旧配置没有这一项时就是开启
+ UpdateCheckDisabled bool `protobuf:"varint,18,opt,name=update_check_disabled,json=updateCheckDisabled,proto3" json:"update_check_disabled,omitempty"`
+ // 用户选择跳过的版本,自动检查不再提示它;手动检查照常显示
+ UpdateSkipVersion string `protobuf:"bytes,19,opt,name=update_skip_version,json=updateSkipVersion,proto3" json:"update_skip_version,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
}
func (x *Config) Reset() {
@@ -2148,6 +2152,20 @@ func (x *Config) GetOfficialNoticeAck() string {
return ""
}
+func (x *Config) GetUpdateCheckDisabled() bool {
+ if x != nil {
+ return x.UpdateCheckDisabled
+ }
+ return false
+}
+
+func (x *Config) GetUpdateSkipVersion() string {
+ if x != nil {
+ return x.UpdateSkipVersion
+ }
+ return ""
+}
+
type OfficialUsage struct {
state protoimpl.MessageState `protogen:"open.v1"`
Available bool `protobuf:"varint,1,opt,name=available,proto3" json:"available,omitempty"`
@@ -2603,8 +2621,12 @@ type Status struct {
// 详细日志打开到什么时候;0 表示没打开
VerboseLogUntilUnix int64 `protobuf:"varint,11,opt,name=verbose_log_until_unix,json=verboseLogUntilUnix,proto3" json:"verbose_log_until_unix,omitempty"`
OfficialUsage *OfficialUsage `protobuf:"bytes,12,opt,name=official_usage,json=officialUsage,proto3" json:"official_usage,omitempty"`
- unknownFields protoimpl.UnknownFields
- sizeCache protoimpl.SizeCache
+ // 自动检查发现的新版本(没被跳过);空表示没有要提示的
+ UpdateAvailable string `protobuf:"bytes,13,opt,name=update_available,json=updateAvailable,proto3" json:"update_available,omitempty"`
+ // 刚完成的一次自动更新,界面据此提示「已更新到 X」;过一会儿就不再带
+ LastUpdate *UpdateResult `protobuf:"bytes,14,opt,name=last_update,json=lastUpdate,proto3" json:"last_update,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
}
func (x *Status) Reset() {
@@ -2721,6 +2743,482 @@ func (x *Status) GetOfficialUsage() *OfficialUsage {
return nil
}
+func (x *Status) GetUpdateAvailable() string {
+ if x != nil {
+ return x.UpdateAvailable
+ }
+ return ""
+}
+
+func (x *Status) GetLastUpdate() *UpdateResult {
+ if x != nil {
+ return x.LastUpdate
+ }
+ return nil
+}
+
+type CheckForUpdateRequest struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ // 界面语言,用来挑更新日志:"en"、"zh-Hans"、"zh-Hant-TW"、"zh-Hant-HK"、"ja"
+ Language string `protobuf:"bytes,1,opt,name=language,proto3" json:"language,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *CheckForUpdateRequest) Reset() {
+ *x = CheckForUpdateRequest{}
+ mi := &file_pasteferry_v1_daemon_proto_msgTypes[32]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *CheckForUpdateRequest) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*CheckForUpdateRequest) ProtoMessage() {}
+
+func (x *CheckForUpdateRequest) ProtoReflect() protoreflect.Message {
+ mi := &file_pasteferry_v1_daemon_proto_msgTypes[32]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use CheckForUpdateRequest.ProtoReflect.Descriptor instead.
+func (*CheckForUpdateRequest) Descriptor() ([]byte, []int) {
+ return file_pasteferry_v1_daemon_proto_rawDescGZIP(), []int{32}
+}
+
+func (x *CheckForUpdateRequest) GetLanguage() string {
+ if x != nil {
+ return x.Language
+ }
+ return ""
+}
+
+type UpdateRelease struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ Version string `protobuf:"bytes,1,opt,name=version,proto3" json:"version,omitempty"`
+ Date string `protobuf:"bytes,2,opt,name=date,proto3" json:"date,omitempty"`
+ Changes []string `protobuf:"bytes,3,rep,name=changes,proto3" json:"changes,omitempty"`
+ Fixes []string `protobuf:"bytes,4,rep,name=fixes,proto3" json:"fixes,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *UpdateRelease) Reset() {
+ *x = UpdateRelease{}
+ mi := &file_pasteferry_v1_daemon_proto_msgTypes[33]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *UpdateRelease) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*UpdateRelease) ProtoMessage() {}
+
+func (x *UpdateRelease) ProtoReflect() protoreflect.Message {
+ mi := &file_pasteferry_v1_daemon_proto_msgTypes[33]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use UpdateRelease.ProtoReflect.Descriptor instead.
+func (*UpdateRelease) Descriptor() ([]byte, []int) {
+ return file_pasteferry_v1_daemon_proto_rawDescGZIP(), []int{33}
+}
+
+func (x *UpdateRelease) GetVersion() string {
+ if x != nil {
+ return x.Version
+ }
+ return ""
+}
+
+func (x *UpdateRelease) GetDate() string {
+ if x != nil {
+ return x.Date
+ }
+ return ""
+}
+
+func (x *UpdateRelease) GetChanges() []string {
+ if x != nil {
+ return x.Changes
+ }
+ return nil
+}
+
+func (x *UpdateRelease) GetFixes() []string {
+ if x != nil {
+ return x.Fixes
+ }
+ return nil
+}
+
+type UpdateInfo struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ CurrentVersion string `protobuf:"bytes,1,opt,name=current_version,json=currentVersion,proto3" json:"current_version,omitempty"`
+ LatestVersion string `protobuf:"bytes,2,opt,name=latest_version,json=latestVersion,proto3" json:"latest_version,omitempty"`
+ // latest_version 比当前新
+ Available bool `protobuf:"varint,3,opt,name=available,proto3" json:"available,omitempty"`
+ // 比当前新的各版更新日志,从新到旧,已按语言挑好
+ Releases []*UpdateRelease `protobuf:"bytes,4,rep,name=releases,proto3" json:"releases,omitempty"`
+ // 这台电脑要下载的安装包大小
+ DownloadBytes int64 `protobuf:"varint,5,opt,name=download_bytes,json=downloadBytes,proto3" json:"download_bytes,omitempty"`
+ // 为空表示可以自动安装;否则是不能的原因:dev、must_move、read_only、unsupported
+ InstallBlocker string `protobuf:"bytes,6,opt,name=install_blocker,json=installBlocker,proto3" json:"install_blocker,omitempty"`
+ // 清单来自哪里:github 或 gitee
+ Source string `protobuf:"bytes,7,opt,name=source,proto3" json:"source,omitempty"`
+ CheckedAtUnix int64 `protobuf:"varint,8,opt,name=checked_at_unix,json=checkedAtUnix,proto3" json:"checked_at_unix,omitempty"`
+ // 本机的安装方式:mac-app、windows-setup、windows-portable、linux-deb、linux-tar。
+ // linux-deb 安装时系统会要求输入密码,界面提前说明
+ InstallKind string `protobuf:"bytes,9,opt,name=install_kind,json=installKind,proto3" json:"install_kind,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *UpdateInfo) Reset() {
+ *x = UpdateInfo{}
+ mi := &file_pasteferry_v1_daemon_proto_msgTypes[34]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *UpdateInfo) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*UpdateInfo) ProtoMessage() {}
+
+func (x *UpdateInfo) ProtoReflect() protoreflect.Message {
+ mi := &file_pasteferry_v1_daemon_proto_msgTypes[34]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use UpdateInfo.ProtoReflect.Descriptor instead.
+func (*UpdateInfo) Descriptor() ([]byte, []int) {
+ return file_pasteferry_v1_daemon_proto_rawDescGZIP(), []int{34}
+}
+
+func (x *UpdateInfo) GetCurrentVersion() string {
+ if x != nil {
+ return x.CurrentVersion
+ }
+ return ""
+}
+
+func (x *UpdateInfo) GetLatestVersion() string {
+ if x != nil {
+ return x.LatestVersion
+ }
+ return ""
+}
+
+func (x *UpdateInfo) GetAvailable() bool {
+ if x != nil {
+ return x.Available
+ }
+ return false
+}
+
+func (x *UpdateInfo) GetReleases() []*UpdateRelease {
+ if x != nil {
+ return x.Releases
+ }
+ return nil
+}
+
+func (x *UpdateInfo) GetDownloadBytes() int64 {
+ if x != nil {
+ return x.DownloadBytes
+ }
+ return 0
+}
+
+func (x *UpdateInfo) GetInstallBlocker() string {
+ if x != nil {
+ return x.InstallBlocker
+ }
+ return ""
+}
+
+func (x *UpdateInfo) GetSource() string {
+ if x != nil {
+ return x.Source
+ }
+ return ""
+}
+
+func (x *UpdateInfo) GetCheckedAtUnix() int64 {
+ if x != nil {
+ return x.CheckedAtUnix
+ }
+ return 0
+}
+
+func (x *UpdateInfo) GetInstallKind() string {
+ if x != nil {
+ return x.InstallKind
+ }
+ return ""
+}
+
+type DownloadUpdateRequest struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ Version string `protobuf:"bytes,1,opt,name=version,proto3" json:"version,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *DownloadUpdateRequest) Reset() {
+ *x = DownloadUpdateRequest{}
+ mi := &file_pasteferry_v1_daemon_proto_msgTypes[35]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *DownloadUpdateRequest) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*DownloadUpdateRequest) ProtoMessage() {}
+
+func (x *DownloadUpdateRequest) ProtoReflect() protoreflect.Message {
+ mi := &file_pasteferry_v1_daemon_proto_msgTypes[35]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use DownloadUpdateRequest.ProtoReflect.Descriptor instead.
+func (*DownloadUpdateRequest) Descriptor() ([]byte, []int) {
+ return file_pasteferry_v1_daemon_proto_rawDescGZIP(), []int{35}
+}
+
+func (x *DownloadUpdateRequest) GetVersion() string {
+ if x != nil {
+ return x.Version
+ }
+ return ""
+}
+
+type UpdateProgress struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ Downloaded int64 `protobuf:"varint,1,opt,name=downloaded,proto3" json:"downloaded,omitempty"`
+ Total int64 `protobuf:"varint,2,opt,name=total,proto3" json:"total,omitempty"`
+ // 下载完并通过校验
+ Done bool `protobuf:"varint,3,opt,name=done,proto3" json:"done,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *UpdateProgress) Reset() {
+ *x = UpdateProgress{}
+ mi := &file_pasteferry_v1_daemon_proto_msgTypes[36]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *UpdateProgress) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*UpdateProgress) ProtoMessage() {}
+
+func (x *UpdateProgress) ProtoReflect() protoreflect.Message {
+ mi := &file_pasteferry_v1_daemon_proto_msgTypes[36]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use UpdateProgress.ProtoReflect.Descriptor instead.
+func (*UpdateProgress) Descriptor() ([]byte, []int) {
+ return file_pasteferry_v1_daemon_proto_rawDescGZIP(), []int{36}
+}
+
+func (x *UpdateProgress) GetDownloaded() int64 {
+ if x != nil {
+ return x.Downloaded
+ }
+ return 0
+}
+
+func (x *UpdateProgress) GetTotal() int64 {
+ if x != nil {
+ return x.Total
+ }
+ return 0
+}
+
+func (x *UpdateProgress) GetDone() bool {
+ if x != nil {
+ return x.Done
+ }
+ return false
+}
+
+type InstallUpdateRequest struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ Version string `protobuf:"bytes,1,opt,name=version,proto3" json:"version,omitempty"`
+ // 界面的进程号:更新助手等它退出后再替换文件
+ UiPid int32 `protobuf:"varint,2,opt,name=ui_pid,json=uiPid,proto3" json:"ui_pid,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *InstallUpdateRequest) Reset() {
+ *x = InstallUpdateRequest{}
+ mi := &file_pasteferry_v1_daemon_proto_msgTypes[37]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *InstallUpdateRequest) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*InstallUpdateRequest) ProtoMessage() {}
+
+func (x *InstallUpdateRequest) ProtoReflect() protoreflect.Message {
+ mi := &file_pasteferry_v1_daemon_proto_msgTypes[37]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use InstallUpdateRequest.ProtoReflect.Descriptor instead.
+func (*InstallUpdateRequest) Descriptor() ([]byte, []int) {
+ return file_pasteferry_v1_daemon_proto_rawDescGZIP(), []int{37}
+}
+
+func (x *InstallUpdateRequest) GetVersion() string {
+ if x != nil {
+ return x.Version
+ }
+ return ""
+}
+
+func (x *InstallUpdateRequest) GetUiPid() int32 {
+ if x != nil {
+ return x.UiPid
+ }
+ return 0
+}
+
+type UpdateResult struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ FromVersion string `protobuf:"bytes,1,opt,name=from_version,json=fromVersion,proto3" json:"from_version,omitempty"`
+ ToVersion string `protobuf:"bytes,2,opt,name=to_version,json=toVersion,proto3" json:"to_version,omitempty"`
+ Ok bool `protobuf:"varint,3,opt,name=ok,proto3" json:"ok,omitempty"`
+ Error string `protobuf:"bytes,4,opt,name=error,proto3" json:"error,omitempty"`
+ AtUnix int64 `protobuf:"varint,5,opt,name=at_unix,json=atUnix,proto3" json:"at_unix,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *UpdateResult) Reset() {
+ *x = UpdateResult{}
+ mi := &file_pasteferry_v1_daemon_proto_msgTypes[38]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *UpdateResult) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*UpdateResult) ProtoMessage() {}
+
+func (x *UpdateResult) ProtoReflect() protoreflect.Message {
+ mi := &file_pasteferry_v1_daemon_proto_msgTypes[38]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use UpdateResult.ProtoReflect.Descriptor instead.
+func (*UpdateResult) Descriptor() ([]byte, []int) {
+ return file_pasteferry_v1_daemon_proto_rawDescGZIP(), []int{38}
+}
+
+func (x *UpdateResult) GetFromVersion() string {
+ if x != nil {
+ return x.FromVersion
+ }
+ return ""
+}
+
+func (x *UpdateResult) GetToVersion() string {
+ if x != nil {
+ return x.ToVersion
+ }
+ return ""
+}
+
+func (x *UpdateResult) GetOk() bool {
+ if x != nil {
+ return x.Ok
+ }
+ return false
+}
+
+func (x *UpdateResult) GetError() string {
+ if x != nil {
+ return x.Error
+ }
+ return ""
+}
+
+func (x *UpdateResult) GetAtUnix() int64 {
+ if x != nil {
+ return x.AtUnix
+ }
+ return 0
+}
+
type ExportDiagnosticsRequest struct {
state protoimpl.MessageState `protogen:"open.v1"`
LogLines int32 `protobuf:"varint,1,opt,name=log_lines,json=logLines,proto3" json:"log_lines,omitempty"` // 带上最近多少行日志
@@ -2731,7 +3229,7 @@ type ExportDiagnosticsRequest struct {
func (x *ExportDiagnosticsRequest) Reset() {
*x = ExportDiagnosticsRequest{}
- mi := &file_pasteferry_v1_daemon_proto_msgTypes[32]
+ mi := &file_pasteferry_v1_daemon_proto_msgTypes[39]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -2743,7 +3241,7 @@ func (x *ExportDiagnosticsRequest) String() string {
func (*ExportDiagnosticsRequest) ProtoMessage() {}
func (x *ExportDiagnosticsRequest) ProtoReflect() protoreflect.Message {
- mi := &file_pasteferry_v1_daemon_proto_msgTypes[32]
+ mi := &file_pasteferry_v1_daemon_proto_msgTypes[39]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -2756,7 +3254,7 @@ func (x *ExportDiagnosticsRequest) ProtoReflect() protoreflect.Message {
// Deprecated: Use ExportDiagnosticsRequest.ProtoReflect.Descriptor instead.
func (*ExportDiagnosticsRequest) Descriptor() ([]byte, []int) {
- return file_pasteferry_v1_daemon_proto_rawDescGZIP(), []int{32}
+ return file_pasteferry_v1_daemon_proto_rawDescGZIP(), []int{39}
}
func (x *ExportDiagnosticsRequest) GetLogLines() int32 {
@@ -2782,7 +3280,7 @@ type Diagnostics struct {
func (x *Diagnostics) Reset() {
*x = Diagnostics{}
- mi := &file_pasteferry_v1_daemon_proto_msgTypes[33]
+ mi := &file_pasteferry_v1_daemon_proto_msgTypes[40]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -2794,7 +3292,7 @@ func (x *Diagnostics) String() string {
func (*Diagnostics) ProtoMessage() {}
func (x *Diagnostics) ProtoReflect() protoreflect.Message {
- mi := &file_pasteferry_v1_daemon_proto_msgTypes[33]
+ mi := &file_pasteferry_v1_daemon_proto_msgTypes[40]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -2807,7 +3305,7 @@ func (x *Diagnostics) ProtoReflect() protoreflect.Message {
// Deprecated: Use Diagnostics.ProtoReflect.Descriptor instead.
func (*Diagnostics) Descriptor() ([]byte, []int) {
- return file_pasteferry_v1_daemon_proto_rawDescGZIP(), []int{33}
+ return file_pasteferry_v1_daemon_proto_rawDescGZIP(), []int{40}
}
func (x *Diagnostics) GetReport() string {
@@ -2826,7 +3324,7 @@ type SetVerboseLogRequest struct {
func (x *SetVerboseLogRequest) Reset() {
*x = SetVerboseLogRequest{}
- mi := &file_pasteferry_v1_daemon_proto_msgTypes[34]
+ mi := &file_pasteferry_v1_daemon_proto_msgTypes[41]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -2838,7 +3336,7 @@ func (x *SetVerboseLogRequest) String() string {
func (*SetVerboseLogRequest) ProtoMessage() {}
func (x *SetVerboseLogRequest) ProtoReflect() protoreflect.Message {
- mi := &file_pasteferry_v1_daemon_proto_msgTypes[34]
+ mi := &file_pasteferry_v1_daemon_proto_msgTypes[41]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -2851,7 +3349,7 @@ func (x *SetVerboseLogRequest) ProtoReflect() protoreflect.Message {
// Deprecated: Use SetVerboseLogRequest.ProtoReflect.Descriptor instead.
func (*SetVerboseLogRequest) Descriptor() ([]byte, []int) {
- return file_pasteferry_v1_daemon_proto_rawDescGZIP(), []int{34}
+ return file_pasteferry_v1_daemon_proto_rawDescGZIP(), []int{41}
}
func (x *SetVerboseLogRequest) GetMinutes() int32 {
@@ -2871,7 +3369,7 @@ type GetImagePreviewRequest struct {
func (x *GetImagePreviewRequest) Reset() {
*x = GetImagePreviewRequest{}
- mi := &file_pasteferry_v1_daemon_proto_msgTypes[35]
+ mi := &file_pasteferry_v1_daemon_proto_msgTypes[42]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -2883,7 +3381,7 @@ func (x *GetImagePreviewRequest) String() string {
func (*GetImagePreviewRequest) ProtoMessage() {}
func (x *GetImagePreviewRequest) ProtoReflect() protoreflect.Message {
- mi := &file_pasteferry_v1_daemon_proto_msgTypes[35]
+ mi := &file_pasteferry_v1_daemon_proto_msgTypes[42]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -2896,7 +3394,7 @@ func (x *GetImagePreviewRequest) ProtoReflect() protoreflect.Message {
// Deprecated: Use GetImagePreviewRequest.ProtoReflect.Descriptor instead.
func (*GetImagePreviewRequest) Descriptor() ([]byte, []int) {
- return file_pasteferry_v1_daemon_proto_rawDescGZIP(), []int{35}
+ return file_pasteferry_v1_daemon_proto_rawDescGZIP(), []int{42}
}
func (x *GetImagePreviewRequest) GetClipId() string {
@@ -2924,7 +3422,7 @@ type GetImagePreviewResponse struct {
func (x *GetImagePreviewResponse) Reset() {
*x = GetImagePreviewResponse{}
- mi := &file_pasteferry_v1_daemon_proto_msgTypes[36]
+ mi := &file_pasteferry_v1_daemon_proto_msgTypes[43]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -2936,7 +3434,7 @@ func (x *GetImagePreviewResponse) String() string {
func (*GetImagePreviewResponse) ProtoMessage() {}
func (x *GetImagePreviewResponse) ProtoReflect() protoreflect.Message {
- mi := &file_pasteferry_v1_daemon_proto_msgTypes[36]
+ mi := &file_pasteferry_v1_daemon_proto_msgTypes[43]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -2949,7 +3447,7 @@ func (x *GetImagePreviewResponse) ProtoReflect() protoreflect.Message {
// Deprecated: Use GetImagePreviewResponse.ProtoReflect.Descriptor instead.
func (*GetImagePreviewResponse) Descriptor() ([]byte, []int) {
- return file_pasteferry_v1_daemon_proto_rawDescGZIP(), []int{36}
+ return file_pasteferry_v1_daemon_proto_rawDescGZIP(), []int{43}
}
func (x *GetImagePreviewResponse) GetPath() string {
@@ -3092,7 +3590,7 @@ const file_pasteferry_v1_daemon_proto_rawDesc = "" +
"\tdevice_id\x18\x01 \x01(\tR\bdeviceId\"P\n" +
"\x17SetDeviceAddressRequest\x12\x1b\n" +
"\tdevice_id\x18\x01 \x01(\tR\bdeviceId\x12\x18\n" +
- "\aaddress\x18\x02 \x01(\tR\aaddress\"\xbe\x05\n" +
+ "\aaddress\x18\x02 \x01(\tR\aaddress\"\xa2\x06\n" +
"\x06Config\x129\n" +
"\x19auto_sync_threshold_bytes\x18\x01 \x01(\x03R\x16autoSyncThresholdBytes\x12.\n" +
"\x13history_ttl_seconds\x18\x02 \x01(\x03R\x11historyTtlSeconds\x12*\n" +
@@ -3113,7 +3611,9 @@ const file_pasteferry_v1_daemon_proto_rawDesc = "" +
"\flan_disabled\x18\x0e \x01(\bR\vlanDisabled\x12=\n" +
"\fservice_mode\x18\x0f \x01(\x0e2\x1a.pasteferry.v1.ServiceModeR\vserviceMode\x120\n" +
"\x14custom_signaling_url\x18\x10 \x01(\tR\x12customSignalingUrl\x12.\n" +
- "\x13official_notice_ack\x18\x11 \x01(\tR\x11officialNoticeAck\"\xd8\x02\n" +
+ "\x13official_notice_ack\x18\x11 \x01(\tR\x11officialNoticeAck\x122\n" +
+ "\x15update_check_disabled\x18\x12 \x01(\bR\x13updateCheckDisabled\x12.\n" +
+ "\x13update_skip_version\x18\x13 \x01(\tR\x11updateSkipVersion\"\xd8\x02\n" +
"\rOfficialUsage\x12\x1c\n" +
"\tavailable\x18\x01 \x01(\bR\tavailable\x12\x10\n" +
"\x03day\x18\x02 \x01(\tR\x03day\x12\x1f\n" +
@@ -3157,7 +3657,7 @@ const file_pasteferry_v1_daemon_proto_rawDesc = "" +
"\aaddress\x18\x01 \x01(\tR\aaddress\x12%\n" +
"\x0eport_preserved\x18\x02 \x01(\bR\rportPreserved\x12\x18\n" +
"\aguessed\x18\x03 \x01(\bR\aguessed\x12\x10\n" +
- "\x03via\x18\x04 \x03(\tR\x03via\"\x9e\x04\n" +
+ "\x03via\x18\x04 \x03(\tR\x03via\"\x87\x05\n" +
"\x06Status\x12\x1b\n" +
"\tdevice_id\x18\x01 \x01(\tR\bdeviceId\x12\x1f\n" +
"\vdevice_name\x18\x02 \x01(\tR\n" +
@@ -3174,7 +3674,46 @@ const file_pasteferry_v1_daemon_proto_rawDesc = "" +
" \x01(\bR\n" +
"lanBlocked\x123\n" +
"\x16verbose_log_until_unix\x18\v \x01(\x03R\x13verboseLogUntilUnix\x12C\n" +
- "\x0eofficial_usage\x18\f \x01(\v2\x1c.pasteferry.v1.OfficialUsageR\rofficialUsage\"V\n" +
+ "\x0eofficial_usage\x18\f \x01(\v2\x1c.pasteferry.v1.OfficialUsageR\rofficialUsage\x12)\n" +
+ "\x10update_available\x18\r \x01(\tR\x0fupdateAvailable\x12<\n" +
+ "\vlast_update\x18\x0e \x01(\v2\x1b.pasteferry.v1.UpdateResultR\n" +
+ "lastUpdate\"3\n" +
+ "\x15CheckForUpdateRequest\x12\x1a\n" +
+ "\blanguage\x18\x01 \x01(\tR\blanguage\"m\n" +
+ "\rUpdateRelease\x12\x18\n" +
+ "\aversion\x18\x01 \x01(\tR\aversion\x12\x12\n" +
+ "\x04date\x18\x02 \x01(\tR\x04date\x12\x18\n" +
+ "\achanges\x18\x03 \x03(\tR\achanges\x12\x14\n" +
+ "\x05fixes\x18\x04 \x03(\tR\x05fixes\"\xe7\x02\n" +
+ "\n" +
+ "UpdateInfo\x12'\n" +
+ "\x0fcurrent_version\x18\x01 \x01(\tR\x0ecurrentVersion\x12%\n" +
+ "\x0elatest_version\x18\x02 \x01(\tR\rlatestVersion\x12\x1c\n" +
+ "\tavailable\x18\x03 \x01(\bR\tavailable\x128\n" +
+ "\breleases\x18\x04 \x03(\v2\x1c.pasteferry.v1.UpdateReleaseR\breleases\x12%\n" +
+ "\x0edownload_bytes\x18\x05 \x01(\x03R\rdownloadBytes\x12'\n" +
+ "\x0finstall_blocker\x18\x06 \x01(\tR\x0einstallBlocker\x12\x16\n" +
+ "\x06source\x18\a \x01(\tR\x06source\x12&\n" +
+ "\x0fchecked_at_unix\x18\b \x01(\x03R\rcheckedAtUnix\x12!\n" +
+ "\finstall_kind\x18\t \x01(\tR\vinstallKind\"1\n" +
+ "\x15DownloadUpdateRequest\x12\x18\n" +
+ "\aversion\x18\x01 \x01(\tR\aversion\"Z\n" +
+ "\x0eUpdateProgress\x12\x1e\n" +
+ "\n" +
+ "downloaded\x18\x01 \x01(\x03R\n" +
+ "downloaded\x12\x14\n" +
+ "\x05total\x18\x02 \x01(\x03R\x05total\x12\x12\n" +
+ "\x04done\x18\x03 \x01(\bR\x04done\"G\n" +
+ "\x14InstallUpdateRequest\x12\x18\n" +
+ "\aversion\x18\x01 \x01(\tR\aversion\x12\x15\n" +
+ "\x06ui_pid\x18\x02 \x01(\x05R\x05uiPid\"\x8f\x01\n" +
+ "\fUpdateResult\x12!\n" +
+ "\ffrom_version\x18\x01 \x01(\tR\vfromVersion\x12\x1d\n" +
+ "\n" +
+ "to_version\x18\x02 \x01(\tR\ttoVersion\x12\x0e\n" +
+ "\x02ok\x18\x03 \x01(\bR\x02ok\x12\x14\n" +
+ "\x05error\x18\x04 \x01(\tR\x05error\x12\x17\n" +
+ "\aat_unix\x18\x05 \x01(\x03R\x06atUnix\"V\n" +
"\x18ExportDiagnosticsRequest\x12\x1b\n" +
"\tlog_lines\x18\x01 \x01(\x05R\blogLines\x12\x1d\n" +
"\n" +
@@ -3225,7 +3764,7 @@ const file_pasteferry_v1_daemon_proto_rawDesc = "" +
"\x18SERVICE_MODE_UNSPECIFIED\x10\x00\x12\x14\n" +
"\x10SERVICE_MODE_LAN\x10\x01\x12\x19\n" +
"\x15SERVICE_MODE_OFFICIAL\x10\x02\x12\x17\n" +
- "\x13SERVICE_MODE_CUSTOM\x10\x032\x97\x0f\n" +
+ "\x13SERVICE_MODE_CUSTOM\x10\x032\x8f\x11\n" +
"\rDaemonService\x12D\n" +
"\tSubscribe\x12\x1f.pasteferry.v1.SubscribeRequest\x1a\x14.pasteferry.v1.Event0\x01\x12T\n" +
"\vListHistory\x12!.pasteferry.v1.ListHistoryRequest\x1a\".pasteferry.v1.ListHistoryResponse\x12J\n" +
@@ -3253,7 +3792,10 @@ const file_pasteferry_v1_daemon_proto_rawDesc = "" +
"\n" +
"GetNetwork\x12\x14.pasteferry.v1.Empty\x1a\x1a.pasteferry.v1.NetworkInfo\x12X\n" +
"\x11ExportDiagnostics\x12'.pasteferry.v1.ExportDiagnosticsRequest\x1a\x1a.pasteferry.v1.Diagnostics\x12K\n" +
- "\rSetVerboseLog\x12#.pasteferry.v1.SetVerboseLogRequest\x1a\x15.pasteferry.v1.StatusBDZBgithub.com/baiyuze/pasteferry/proto/gen/pasteferry/v1;pasteferryv1b\x06proto3"
+ "\rSetVerboseLog\x12#.pasteferry.v1.SetVerboseLogRequest\x1a\x15.pasteferry.v1.Status\x12Q\n" +
+ "\x0eCheckForUpdate\x12$.pasteferry.v1.CheckForUpdateRequest\x1a\x19.pasteferry.v1.UpdateInfo\x12W\n" +
+ "\x0eDownloadUpdate\x12$.pasteferry.v1.DownloadUpdateRequest\x1a\x1d.pasteferry.v1.UpdateProgress0\x01\x12J\n" +
+ "\rInstallUpdate\x12#.pasteferry.v1.InstallUpdateRequest\x1a\x14.pasteferry.v1.EmptyBDZBgithub.com/baiyuze/pasteferry/proto/gen/pasteferry/v1;pasteferryv1b\x06proto3"
var (
file_pasteferry_v1_daemon_proto_rawDescOnce sync.Once
@@ -3268,7 +3810,7 @@ func file_pasteferry_v1_daemon_proto_rawDescGZIP() []byte {
}
var file_pasteferry_v1_daemon_proto_enumTypes = make([]protoimpl.EnumInfo, 6)
-var file_pasteferry_v1_daemon_proto_msgTypes = make([]protoimpl.MessageInfo, 37)
+var file_pasteferry_v1_daemon_proto_msgTypes = make([]protoimpl.MessageInfo, 44)
var file_pasteferry_v1_daemon_proto_goTypes = []any{
(ClipKind)(0), // 0: pasteferry.v1.ClipKind
(ClipStatus)(0), // 1: pasteferry.v1.ClipStatus
@@ -3308,11 +3850,18 @@ var file_pasteferry_v1_daemon_proto_goTypes = []any{
(*LanPeer)(nil), // 35: pasteferry.v1.LanPeer
(*NetworkEgress)(nil), // 36: pasteferry.v1.NetworkEgress
(*Status)(nil), // 37: pasteferry.v1.Status
- (*ExportDiagnosticsRequest)(nil), // 38: pasteferry.v1.ExportDiagnosticsRequest
- (*Diagnostics)(nil), // 39: pasteferry.v1.Diagnostics
- (*SetVerboseLogRequest)(nil), // 40: pasteferry.v1.SetVerboseLogRequest
- (*GetImagePreviewRequest)(nil), // 41: pasteferry.v1.GetImagePreviewRequest
- (*GetImagePreviewResponse)(nil), // 42: pasteferry.v1.GetImagePreviewResponse
+ (*CheckForUpdateRequest)(nil), // 38: pasteferry.v1.CheckForUpdateRequest
+ (*UpdateRelease)(nil), // 39: pasteferry.v1.UpdateRelease
+ (*UpdateInfo)(nil), // 40: pasteferry.v1.UpdateInfo
+ (*DownloadUpdateRequest)(nil), // 41: pasteferry.v1.DownloadUpdateRequest
+ (*UpdateProgress)(nil), // 42: pasteferry.v1.UpdateProgress
+ (*InstallUpdateRequest)(nil), // 43: pasteferry.v1.InstallUpdateRequest
+ (*UpdateResult)(nil), // 44: pasteferry.v1.UpdateResult
+ (*ExportDiagnosticsRequest)(nil), // 45: pasteferry.v1.ExportDiagnosticsRequest
+ (*Diagnostics)(nil), // 46: pasteferry.v1.Diagnostics
+ (*SetVerboseLogRequest)(nil), // 47: pasteferry.v1.SetVerboseLogRequest
+ (*GetImagePreviewRequest)(nil), // 48: pasteferry.v1.GetImagePreviewRequest
+ (*GetImagePreviewResponse)(nil), // 49: pasteferry.v1.GetImagePreviewResponse
}
var file_pasteferry_v1_daemon_proto_depIdxs = []int32{
0, // 0: pasteferry.v1.ClipRecord.kind:type_name -> pasteferry.v1.ClipKind
@@ -3339,61 +3888,69 @@ var file_pasteferry_v1_daemon_proto_depIdxs = []int32{
35, // 21: pasteferry.v1.LanInfo.peers:type_name -> pasteferry.v1.LanPeer
3, // 22: pasteferry.v1.Status.clipboard_permission:type_name -> pasteferry.v1.ClipboardPermission
32, // 23: pasteferry.v1.Status.official_usage:type_name -> pasteferry.v1.OfficialUsage
- 9, // 24: pasteferry.v1.DaemonService.Subscribe:input_type -> pasteferry.v1.SubscribeRequest
- 16, // 25: pasteferry.v1.DaemonService.ListHistory:input_type -> pasteferry.v1.ListHistoryRequest
- 18, // 26: pasteferry.v1.DaemonService.DeleteHistory:input_type -> pasteferry.v1.DeleteHistoryRequest
- 19, // 27: pasteferry.v1.DaemonService.Fetch:input_type -> pasteferry.v1.FetchRequest
- 20, // 28: pasteferry.v1.DaemonService.ApplyToClipboard:input_type -> pasteferry.v1.ApplyToClipboardRequest
- 41, // 29: pasteferry.v1.DaemonService.GetImagePreview:input_type -> pasteferry.v1.GetImagePreviewRequest
- 6, // 30: pasteferry.v1.DaemonService.ListDevices:input_type -> pasteferry.v1.Empty
- 6, // 31: pasteferry.v1.DaemonService.CreatePairingCode:input_type -> pasteferry.v1.Empty
- 23, // 32: pasteferry.v1.DaemonService.RedeemPairingCode:input_type -> pasteferry.v1.RedeemPairingCodeRequest
- 25, // 33: pasteferry.v1.DaemonService.ConfirmPairing:input_type -> pasteferry.v1.ConfirmPairingRequest
- 29, // 34: pasteferry.v1.DaemonService.Unpair:input_type -> pasteferry.v1.UnpairRequest
- 30, // 35: pasteferry.v1.DaemonService.SetDeviceAddress:input_type -> pasteferry.v1.SetDeviceAddressRequest
- 6, // 36: pasteferry.v1.DaemonService.WatchNearby:input_type -> pasteferry.v1.Empty
- 28, // 37: pasteferry.v1.DaemonService.PairNearby:input_type -> pasteferry.v1.PairNearbyRequest
- 6, // 38: pasteferry.v1.DaemonService.GetConfig:input_type -> pasteferry.v1.Empty
- 31, // 39: pasteferry.v1.DaemonService.UpdateConfig:input_type -> pasteferry.v1.Config
- 6, // 40: pasteferry.v1.DaemonService.GetStatus:input_type -> pasteferry.v1.Empty
- 6, // 41: pasteferry.v1.DaemonService.RequestClipboardPermission:input_type -> pasteferry.v1.Empty
- 6, // 42: pasteferry.v1.DaemonService.RequestLocalNetworkPermission:input_type -> pasteferry.v1.Empty
- 6, // 43: pasteferry.v1.DaemonService.GetNotificationStatus:input_type -> pasteferry.v1.Empty
- 6, // 44: pasteferry.v1.DaemonService.RequestNotificationPermission:input_type -> pasteferry.v1.Empty
- 14, // 45: pasteferry.v1.DaemonService.ActivateNotification:input_type -> pasteferry.v1.NotificationAction
- 6, // 46: pasteferry.v1.DaemonService.GetNetwork:input_type -> pasteferry.v1.Empty
- 38, // 47: pasteferry.v1.DaemonService.ExportDiagnostics:input_type -> pasteferry.v1.ExportDiagnosticsRequest
- 40, // 48: pasteferry.v1.DaemonService.SetVerboseLog:input_type -> pasteferry.v1.SetVerboseLogRequest
- 12, // 49: pasteferry.v1.DaemonService.Subscribe:output_type -> pasteferry.v1.Event
- 17, // 50: pasteferry.v1.DaemonService.ListHistory:output_type -> pasteferry.v1.ListHistoryResponse
- 6, // 51: pasteferry.v1.DaemonService.DeleteHistory:output_type -> pasteferry.v1.Empty
- 6, // 52: pasteferry.v1.DaemonService.Fetch:output_type -> pasteferry.v1.Empty
- 6, // 53: pasteferry.v1.DaemonService.ApplyToClipboard:output_type -> pasteferry.v1.Empty
- 42, // 54: pasteferry.v1.DaemonService.GetImagePreview:output_type -> pasteferry.v1.GetImagePreviewResponse
- 21, // 55: pasteferry.v1.DaemonService.ListDevices:output_type -> pasteferry.v1.ListDevicesResponse
- 22, // 56: pasteferry.v1.DaemonService.CreatePairingCode:output_type -> pasteferry.v1.CreatePairingCodeResponse
- 24, // 57: pasteferry.v1.DaemonService.RedeemPairingCode:output_type -> pasteferry.v1.RedeemPairingCodeResponse
- 6, // 58: pasteferry.v1.DaemonService.ConfirmPairing:output_type -> pasteferry.v1.Empty
- 6, // 59: pasteferry.v1.DaemonService.Unpair:output_type -> pasteferry.v1.Empty
- 6, // 60: pasteferry.v1.DaemonService.SetDeviceAddress:output_type -> pasteferry.v1.Empty
- 27, // 61: pasteferry.v1.DaemonService.WatchNearby:output_type -> pasteferry.v1.NearbyDevices
- 24, // 62: pasteferry.v1.DaemonService.PairNearby:output_type -> pasteferry.v1.RedeemPairingCodeResponse
- 31, // 63: pasteferry.v1.DaemonService.GetConfig:output_type -> pasteferry.v1.Config
- 31, // 64: pasteferry.v1.DaemonService.UpdateConfig:output_type -> pasteferry.v1.Config
- 37, // 65: pasteferry.v1.DaemonService.GetStatus:output_type -> pasteferry.v1.Status
- 6, // 66: pasteferry.v1.DaemonService.RequestClipboardPermission:output_type -> pasteferry.v1.Empty
- 6, // 67: pasteferry.v1.DaemonService.RequestLocalNetworkPermission:output_type -> pasteferry.v1.Empty
- 13, // 68: pasteferry.v1.DaemonService.GetNotificationStatus:output_type -> pasteferry.v1.NotificationStatus
- 13, // 69: pasteferry.v1.DaemonService.RequestNotificationPermission:output_type -> pasteferry.v1.NotificationStatus
- 6, // 70: pasteferry.v1.DaemonService.ActivateNotification:output_type -> pasteferry.v1.Empty
- 33, // 71: pasteferry.v1.DaemonService.GetNetwork:output_type -> pasteferry.v1.NetworkInfo
- 39, // 72: pasteferry.v1.DaemonService.ExportDiagnostics:output_type -> pasteferry.v1.Diagnostics
- 37, // 73: pasteferry.v1.DaemonService.SetVerboseLog:output_type -> pasteferry.v1.Status
- 49, // [49:74] is the sub-list for method output_type
- 24, // [24:49] is the sub-list for method input_type
- 24, // [24:24] is the sub-list for extension type_name
- 24, // [24:24] is the sub-list for extension extendee
- 0, // [0:24] is the sub-list for field type_name
+ 44, // 24: pasteferry.v1.Status.last_update:type_name -> pasteferry.v1.UpdateResult
+ 39, // 25: pasteferry.v1.UpdateInfo.releases:type_name -> pasteferry.v1.UpdateRelease
+ 9, // 26: pasteferry.v1.DaemonService.Subscribe:input_type -> pasteferry.v1.SubscribeRequest
+ 16, // 27: pasteferry.v1.DaemonService.ListHistory:input_type -> pasteferry.v1.ListHistoryRequest
+ 18, // 28: pasteferry.v1.DaemonService.DeleteHistory:input_type -> pasteferry.v1.DeleteHistoryRequest
+ 19, // 29: pasteferry.v1.DaemonService.Fetch:input_type -> pasteferry.v1.FetchRequest
+ 20, // 30: pasteferry.v1.DaemonService.ApplyToClipboard:input_type -> pasteferry.v1.ApplyToClipboardRequest
+ 48, // 31: pasteferry.v1.DaemonService.GetImagePreview:input_type -> pasteferry.v1.GetImagePreviewRequest
+ 6, // 32: pasteferry.v1.DaemonService.ListDevices:input_type -> pasteferry.v1.Empty
+ 6, // 33: pasteferry.v1.DaemonService.CreatePairingCode:input_type -> pasteferry.v1.Empty
+ 23, // 34: pasteferry.v1.DaemonService.RedeemPairingCode:input_type -> pasteferry.v1.RedeemPairingCodeRequest
+ 25, // 35: pasteferry.v1.DaemonService.ConfirmPairing:input_type -> pasteferry.v1.ConfirmPairingRequest
+ 29, // 36: pasteferry.v1.DaemonService.Unpair:input_type -> pasteferry.v1.UnpairRequest
+ 30, // 37: pasteferry.v1.DaemonService.SetDeviceAddress:input_type -> pasteferry.v1.SetDeviceAddressRequest
+ 6, // 38: pasteferry.v1.DaemonService.WatchNearby:input_type -> pasteferry.v1.Empty
+ 28, // 39: pasteferry.v1.DaemonService.PairNearby:input_type -> pasteferry.v1.PairNearbyRequest
+ 6, // 40: pasteferry.v1.DaemonService.GetConfig:input_type -> pasteferry.v1.Empty
+ 31, // 41: pasteferry.v1.DaemonService.UpdateConfig:input_type -> pasteferry.v1.Config
+ 6, // 42: pasteferry.v1.DaemonService.GetStatus:input_type -> pasteferry.v1.Empty
+ 6, // 43: pasteferry.v1.DaemonService.RequestClipboardPermission:input_type -> pasteferry.v1.Empty
+ 6, // 44: pasteferry.v1.DaemonService.RequestLocalNetworkPermission:input_type -> pasteferry.v1.Empty
+ 6, // 45: pasteferry.v1.DaemonService.GetNotificationStatus:input_type -> pasteferry.v1.Empty
+ 6, // 46: pasteferry.v1.DaemonService.RequestNotificationPermission:input_type -> pasteferry.v1.Empty
+ 14, // 47: pasteferry.v1.DaemonService.ActivateNotification:input_type -> pasteferry.v1.NotificationAction
+ 6, // 48: pasteferry.v1.DaemonService.GetNetwork:input_type -> pasteferry.v1.Empty
+ 45, // 49: pasteferry.v1.DaemonService.ExportDiagnostics:input_type -> pasteferry.v1.ExportDiagnosticsRequest
+ 47, // 50: pasteferry.v1.DaemonService.SetVerboseLog:input_type -> pasteferry.v1.SetVerboseLogRequest
+ 38, // 51: pasteferry.v1.DaemonService.CheckForUpdate:input_type -> pasteferry.v1.CheckForUpdateRequest
+ 41, // 52: pasteferry.v1.DaemonService.DownloadUpdate:input_type -> pasteferry.v1.DownloadUpdateRequest
+ 43, // 53: pasteferry.v1.DaemonService.InstallUpdate:input_type -> pasteferry.v1.InstallUpdateRequest
+ 12, // 54: pasteferry.v1.DaemonService.Subscribe:output_type -> pasteferry.v1.Event
+ 17, // 55: pasteferry.v1.DaemonService.ListHistory:output_type -> pasteferry.v1.ListHistoryResponse
+ 6, // 56: pasteferry.v1.DaemonService.DeleteHistory:output_type -> pasteferry.v1.Empty
+ 6, // 57: pasteferry.v1.DaemonService.Fetch:output_type -> pasteferry.v1.Empty
+ 6, // 58: pasteferry.v1.DaemonService.ApplyToClipboard:output_type -> pasteferry.v1.Empty
+ 49, // 59: pasteferry.v1.DaemonService.GetImagePreview:output_type -> pasteferry.v1.GetImagePreviewResponse
+ 21, // 60: pasteferry.v1.DaemonService.ListDevices:output_type -> pasteferry.v1.ListDevicesResponse
+ 22, // 61: pasteferry.v1.DaemonService.CreatePairingCode:output_type -> pasteferry.v1.CreatePairingCodeResponse
+ 24, // 62: pasteferry.v1.DaemonService.RedeemPairingCode:output_type -> pasteferry.v1.RedeemPairingCodeResponse
+ 6, // 63: pasteferry.v1.DaemonService.ConfirmPairing:output_type -> pasteferry.v1.Empty
+ 6, // 64: pasteferry.v1.DaemonService.Unpair:output_type -> pasteferry.v1.Empty
+ 6, // 65: pasteferry.v1.DaemonService.SetDeviceAddress:output_type -> pasteferry.v1.Empty
+ 27, // 66: pasteferry.v1.DaemonService.WatchNearby:output_type -> pasteferry.v1.NearbyDevices
+ 24, // 67: pasteferry.v1.DaemonService.PairNearby:output_type -> pasteferry.v1.RedeemPairingCodeResponse
+ 31, // 68: pasteferry.v1.DaemonService.GetConfig:output_type -> pasteferry.v1.Config
+ 31, // 69: pasteferry.v1.DaemonService.UpdateConfig:output_type -> pasteferry.v1.Config
+ 37, // 70: pasteferry.v1.DaemonService.GetStatus:output_type -> pasteferry.v1.Status
+ 6, // 71: pasteferry.v1.DaemonService.RequestClipboardPermission:output_type -> pasteferry.v1.Empty
+ 6, // 72: pasteferry.v1.DaemonService.RequestLocalNetworkPermission:output_type -> pasteferry.v1.Empty
+ 13, // 73: pasteferry.v1.DaemonService.GetNotificationStatus:output_type -> pasteferry.v1.NotificationStatus
+ 13, // 74: pasteferry.v1.DaemonService.RequestNotificationPermission:output_type -> pasteferry.v1.NotificationStatus
+ 6, // 75: pasteferry.v1.DaemonService.ActivateNotification:output_type -> pasteferry.v1.Empty
+ 33, // 76: pasteferry.v1.DaemonService.GetNetwork:output_type -> pasteferry.v1.NetworkInfo
+ 46, // 77: pasteferry.v1.DaemonService.ExportDiagnostics:output_type -> pasteferry.v1.Diagnostics
+ 37, // 78: pasteferry.v1.DaemonService.SetVerboseLog:output_type -> pasteferry.v1.Status
+ 40, // 79: pasteferry.v1.DaemonService.CheckForUpdate:output_type -> pasteferry.v1.UpdateInfo
+ 42, // 80: pasteferry.v1.DaemonService.DownloadUpdate:output_type -> pasteferry.v1.UpdateProgress
+ 6, // 81: pasteferry.v1.DaemonService.InstallUpdate:output_type -> pasteferry.v1.Empty
+ 54, // [54:82] is the sub-list for method output_type
+ 26, // [26:54] is the sub-list for method input_type
+ 26, // [26:26] is the sub-list for extension type_name
+ 26, // [26:26] is the sub-list for extension extendee
+ 0, // [0:26] is the sub-list for field type_name
}
func init() { file_pasteferry_v1_daemon_proto_init() }
@@ -3417,7 +3974,7 @@ func file_pasteferry_v1_daemon_proto_init() {
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: unsafe.Slice(unsafe.StringData(file_pasteferry_v1_daemon_proto_rawDesc), len(file_pasteferry_v1_daemon_proto_rawDesc)),
NumEnums: 6,
- NumMessages: 37,
+ NumMessages: 44,
NumExtensions: 0,
NumServices: 1,
},
diff --git a/proto/gen/pasteferry/v1/daemon_grpc.pb.go b/proto/gen/pasteferry/v1/daemon_grpc.pb.go
index 58a1f7b..3fecc4a 100644
--- a/proto/gen/pasteferry/v1/daemon_grpc.pb.go
+++ b/proto/gen/pasteferry/v1/daemon_grpc.pb.go
@@ -49,6 +49,9 @@ const (
DaemonService_GetNetwork_FullMethodName = "/pasteferry.v1.DaemonService/GetNetwork"
DaemonService_ExportDiagnostics_FullMethodName = "/pasteferry.v1.DaemonService/ExportDiagnostics"
DaemonService_SetVerboseLog_FullMethodName = "/pasteferry.v1.DaemonService/SetVerboseLog"
+ DaemonService_CheckForUpdate_FullMethodName = "/pasteferry.v1.DaemonService/CheckForUpdate"
+ DaemonService_DownloadUpdate_FullMethodName = "/pasteferry.v1.DaemonService/DownloadUpdate"
+ DaemonService_InstallUpdate_FullMethodName = "/pasteferry.v1.DaemonService/InstallUpdate"
)
// DaemonServiceClient is the client API for DaemonService service.
@@ -97,6 +100,12 @@ type DaemonServiceClient interface {
ExportDiagnostics(ctx context.Context, in *ExportDiagnosticsRequest, opts ...grpc.CallOption) (*Diagnostics, error)
// 临时打开详细日志(调试级别),到时间自动关回去;minutes 为 0 立即关闭
SetVerboseLog(ctx context.Context, in *SetVerboseLogRequest, opts ...grpc.CallOption) (*Status, error)
+ // 检查更新:从 GitHub 与 Gitee 同时取更新清单,验签后返回比当前新的各版更新日志。见 design/auto-update.md
+ CheckForUpdate(ctx context.Context, in *CheckForUpdateRequest, opts ...grpc.CallOption) (*UpdateInfo, error)
+ // 下载并校验最近一次检查到的新版本。取消调用即停止下载
+ DownloadUpdate(ctx context.Context, in *DownloadUpdateRequest, opts ...grpc.CallOption) (grpc.ServerStreamingClient[UpdateProgress], error)
+ // 准备好新版本并启动更新助手。返回后界面应当立即退出:助手等它退出后替换文件,再重新打开
+ InstallUpdate(ctx context.Context, in *InstallUpdateRequest, opts ...grpc.CallOption) (*Empty, error)
}
type daemonServiceClient struct {
@@ -375,6 +384,45 @@ func (c *daemonServiceClient) SetVerboseLog(ctx context.Context, in *SetVerboseL
return out, nil
}
+func (c *daemonServiceClient) CheckForUpdate(ctx context.Context, in *CheckForUpdateRequest, opts ...grpc.CallOption) (*UpdateInfo, error) {
+ cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
+ out := new(UpdateInfo)
+ err := c.cc.Invoke(ctx, DaemonService_CheckForUpdate_FullMethodName, in, out, cOpts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+func (c *daemonServiceClient) DownloadUpdate(ctx context.Context, in *DownloadUpdateRequest, opts ...grpc.CallOption) (grpc.ServerStreamingClient[UpdateProgress], error) {
+ cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
+ stream, err := c.cc.NewStream(ctx, &DaemonService_ServiceDesc.Streams[2], DaemonService_DownloadUpdate_FullMethodName, cOpts...)
+ if err != nil {
+ return nil, err
+ }
+ x := &grpc.GenericClientStream[DownloadUpdateRequest, UpdateProgress]{ClientStream: stream}
+ if err := x.ClientStream.SendMsg(in); err != nil {
+ return nil, err
+ }
+ if err := x.ClientStream.CloseSend(); err != nil {
+ return nil, err
+ }
+ return x, nil
+}
+
+// This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name.
+type DaemonService_DownloadUpdateClient = grpc.ServerStreamingClient[UpdateProgress]
+
+func (c *daemonServiceClient) InstallUpdate(ctx context.Context, in *InstallUpdateRequest, opts ...grpc.CallOption) (*Empty, error) {
+ cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
+ out := new(Empty)
+ err := c.cc.Invoke(ctx, DaemonService_InstallUpdate_FullMethodName, in, out, cOpts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
// DaemonServiceServer is the server API for DaemonService service.
// All implementations must embed UnimplementedDaemonServiceServer
// for forward compatibility.
@@ -421,6 +469,12 @@ type DaemonServiceServer interface {
ExportDiagnostics(context.Context, *ExportDiagnosticsRequest) (*Diagnostics, error)
// 临时打开详细日志(调试级别),到时间自动关回去;minutes 为 0 立即关闭
SetVerboseLog(context.Context, *SetVerboseLogRequest) (*Status, error)
+ // 检查更新:从 GitHub 与 Gitee 同时取更新清单,验签后返回比当前新的各版更新日志。见 design/auto-update.md
+ CheckForUpdate(context.Context, *CheckForUpdateRequest) (*UpdateInfo, error)
+ // 下载并校验最近一次检查到的新版本。取消调用即停止下载
+ DownloadUpdate(*DownloadUpdateRequest, grpc.ServerStreamingServer[UpdateProgress]) error
+ // 准备好新版本并启动更新助手。返回后界面应当立即退出:助手等它退出后替换文件,再重新打开
+ InstallUpdate(context.Context, *InstallUpdateRequest) (*Empty, error)
mustEmbedUnimplementedDaemonServiceServer()
}
@@ -506,6 +560,15 @@ func (UnimplementedDaemonServiceServer) ExportDiagnostics(context.Context, *Expo
func (UnimplementedDaemonServiceServer) SetVerboseLog(context.Context, *SetVerboseLogRequest) (*Status, error) {
return nil, status.Error(codes.Unimplemented, "method SetVerboseLog not implemented")
}
+func (UnimplementedDaemonServiceServer) CheckForUpdate(context.Context, *CheckForUpdateRequest) (*UpdateInfo, error) {
+ return nil, status.Error(codes.Unimplemented, "method CheckForUpdate not implemented")
+}
+func (UnimplementedDaemonServiceServer) DownloadUpdate(*DownloadUpdateRequest, grpc.ServerStreamingServer[UpdateProgress]) error {
+ return status.Error(codes.Unimplemented, "method DownloadUpdate not implemented")
+}
+func (UnimplementedDaemonServiceServer) InstallUpdate(context.Context, *InstallUpdateRequest) (*Empty, error) {
+ return nil, status.Error(codes.Unimplemented, "method InstallUpdate not implemented")
+}
func (UnimplementedDaemonServiceServer) mustEmbedUnimplementedDaemonServiceServer() {}
func (UnimplementedDaemonServiceServer) testEmbeddedByValue() {}
@@ -963,6 +1026,53 @@ func _DaemonService_SetVerboseLog_Handler(srv interface{}, ctx context.Context,
return interceptor(ctx, in, info, handler)
}
+func _DaemonService_CheckForUpdate_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(CheckForUpdateRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(DaemonServiceServer).CheckForUpdate(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: DaemonService_CheckForUpdate_FullMethodName,
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(DaemonServiceServer).CheckForUpdate(ctx, req.(*CheckForUpdateRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+func _DaemonService_DownloadUpdate_Handler(srv interface{}, stream grpc.ServerStream) error {
+ m := new(DownloadUpdateRequest)
+ if err := stream.RecvMsg(m); err != nil {
+ return err
+ }
+ return srv.(DaemonServiceServer).DownloadUpdate(m, &grpc.GenericServerStream[DownloadUpdateRequest, UpdateProgress]{ServerStream: stream})
+}
+
+// This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name.
+type DaemonService_DownloadUpdateServer = grpc.ServerStreamingServer[UpdateProgress]
+
+func _DaemonService_InstallUpdate_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(InstallUpdateRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(DaemonServiceServer).InstallUpdate(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: DaemonService_InstallUpdate_FullMethodName,
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(DaemonServiceServer).InstallUpdate(ctx, req.(*InstallUpdateRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
// DaemonService_ServiceDesc is the grpc.ServiceDesc for DaemonService service.
// It's only intended for direct use with grpc.RegisterService,
// and not to be introspected or modified (even as a copy)
@@ -1062,6 +1172,14 @@ var DaemonService_ServiceDesc = grpc.ServiceDesc{
MethodName: "SetVerboseLog",
Handler: _DaemonService_SetVerboseLog_Handler,
},
+ {
+ MethodName: "CheckForUpdate",
+ Handler: _DaemonService_CheckForUpdate_Handler,
+ },
+ {
+ MethodName: "InstallUpdate",
+ Handler: _DaemonService_InstallUpdate_Handler,
+ },
},
Streams: []grpc.StreamDesc{
{
@@ -1074,6 +1192,11 @@ var DaemonService_ServiceDesc = grpc.ServiceDesc{
Handler: _DaemonService_WatchNearby_Handler,
ServerStreams: true,
},
+ {
+ StreamName: "DownloadUpdate",
+ Handler: _DaemonService_DownloadUpdate_Handler,
+ ServerStreams: true,
+ },
},
Metadata: "pasteferry/v1/daemon.proto",
}
diff --git a/proto/pasteferry/v1/daemon.proto b/proto/pasteferry/v1/daemon.proto
index 7d86287..97a8c9f 100644
--- a/proto/pasteferry/v1/daemon.proto
+++ b/proto/pasteferry/v1/daemon.proto
@@ -60,6 +60,13 @@ service DaemonService {
rpc ExportDiagnostics(ExportDiagnosticsRequest) returns (Diagnostics);
// 临时打开详细日志(调试级别),到时间自动关回去;minutes 为 0 立即关闭
rpc SetVerboseLog(SetVerboseLogRequest) returns (Status);
+
+ // 检查更新:从 GitHub 与 Gitee 同时取更新清单,验签后返回比当前新的各版更新日志。见 design/auto-update.md
+ rpc CheckForUpdate(CheckForUpdateRequest) returns (UpdateInfo);
+ // 下载并校验最近一次检查到的新版本。取消调用即停止下载
+ rpc DownloadUpdate(DownloadUpdateRequest) returns (stream UpdateProgress);
+ // 准备好新版本并启动更新助手。返回后界面应当立即退出:助手等它退出后替换文件,再重新打开
+ rpc InstallUpdate(InstallUpdateRequest) returns (Empty);
}
message Empty {}
@@ -325,6 +332,11 @@ message Config {
ServiceMode service_mode = 15;
string custom_signaling_url = 16;
string official_notice_ack = 17;
+
+ // 不自动检查更新。写成反向的:旧配置没有这一项时就是开启
+ bool update_check_disabled = 18;
+ // 用户选择跳过的版本,自动检查不再提示它;手动检查照常显示
+ string update_skip_version = 19;
}
enum ServiceMode {
@@ -399,6 +411,66 @@ message Status {
// 详细日志打开到什么时候;0 表示没打开
int64 verbose_log_until_unix = 11;
OfficialUsage official_usage = 12;
+ // 自动检查发现的新版本(没被跳过);空表示没有要提示的
+ string update_available = 13;
+ // 刚完成的一次自动更新,界面据此提示「已更新到 X」;过一会儿就不再带
+ UpdateResult last_update = 14;
+}
+
+message CheckForUpdateRequest {
+ // 界面语言,用来挑更新日志:"en"、"zh-Hans"、"zh-Hant-TW"、"zh-Hant-HK"、"ja"
+ string language = 1;
+}
+
+message UpdateRelease {
+ string version = 1;
+ string date = 2;
+ repeated string changes = 3;
+ repeated string fixes = 4;
+}
+
+message UpdateInfo {
+ string current_version = 1;
+ string latest_version = 2;
+ // latest_version 比当前新
+ bool available = 3;
+ // 比当前新的各版更新日志,从新到旧,已按语言挑好
+ repeated UpdateRelease releases = 4;
+ // 这台电脑要下载的安装包大小
+ int64 download_bytes = 5;
+ // 为空表示可以自动安装;否则是不能的原因:dev、must_move、read_only、unsupported
+ string install_blocker = 6;
+ // 清单来自哪里:github 或 gitee
+ string source = 7;
+ int64 checked_at_unix = 8;
+ // 本机的安装方式:mac-app、windows-setup、windows-portable、linux-deb、linux-tar。
+ // linux-deb 安装时系统会要求输入密码,界面提前说明
+ string install_kind = 9;
+}
+
+message DownloadUpdateRequest {
+ string version = 1;
+}
+
+message UpdateProgress {
+ int64 downloaded = 1;
+ int64 total = 2;
+ // 下载完并通过校验
+ bool done = 3;
+}
+
+message InstallUpdateRequest {
+ string version = 1;
+ // 界面的进程号:更新助手等它退出后再替换文件
+ int32 ui_pid = 2;
+}
+
+message UpdateResult {
+ string from_version = 1;
+ string to_version = 2;
+ bool ok = 3;
+ string error = 4;
+ int64 at_unix = 5;
}
message ExportDiagnosticsRequest {
diff --git a/ui/lib/gen/pasteferry/v1/daemon.pb.dart b/ui/lib/gen/pasteferry/v1/daemon.pb.dart
index 30c6dd6..2cbe7e1 100644
--- a/ui/lib/gen/pasteferry/v1/daemon.pb.dart
+++ b/ui/lib/gen/pasteferry/v1/daemon.pb.dart
@@ -2156,6 +2156,8 @@ class Config extends $pb.GeneratedMessage {
ServiceMode? serviceMode,
$core.String? customSignalingUrl,
$core.String? officialNoticeAck,
+ $core.bool? updateCheckDisabled,
+ $core.String? updateSkipVersion,
}) {
final result = Config._();
if (autoSyncThresholdBytes != null)
@@ -2178,6 +2180,9 @@ class Config extends $pb.GeneratedMessage {
if (customSignalingUrl != null)
result.customSignalingUrl = customSignalingUrl;
if (officialNoticeAck != null) result.officialNoticeAck = officialNoticeAck;
+ if (updateCheckDisabled != null)
+ result.updateCheckDisabled = updateCheckDisabled;
+ if (updateSkipVersion != null) result.updateSkipVersion = updateSkipVersion;
return result;
}
@@ -2212,6 +2217,8 @@ class Config extends $pb.GeneratedMessage {
enumValues: ServiceMode.values)
..aOS(16, _omitFieldNames ? '' : 'customSignalingUrl')
..aOS(17, _omitFieldNames ? '' : 'officialNoticeAck')
+ ..aOB(18, _omitFieldNames ? '' : 'updateCheckDisabled')
+ ..aOS(19, _omitFieldNames ? '' : 'updateSkipVersion')
..hasRequiredFields = false;
@$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')
@@ -2395,6 +2402,26 @@ class Config extends $pb.GeneratedMessage {
$core.bool hasOfficialNoticeAck() => $_has(16);
@$pb.TagNumber(17)
void clearOfficialNoticeAck() => $_clearField(17);
+
+ /// 不自动检查更新。写成反向的:旧配置没有这一项时就是开启
+ @$pb.TagNumber(18)
+ $core.bool get updateCheckDisabled => $_getBF(17);
+ @$pb.TagNumber(18)
+ set updateCheckDisabled($core.bool value) => $_setBool(17, value);
+ @$pb.TagNumber(18)
+ $core.bool hasUpdateCheckDisabled() => $_has(17);
+ @$pb.TagNumber(18)
+ void clearUpdateCheckDisabled() => $_clearField(18);
+
+ /// 用户选择跳过的版本,自动检查不再提示它;手动检查照常显示
+ @$pb.TagNumber(19)
+ $core.String get updateSkipVersion => $_getSZ(18);
+ @$pb.TagNumber(19)
+ set updateSkipVersion($core.String value) => $_setString(18, value);
+ @$pb.TagNumber(19)
+ $core.bool hasUpdateSkipVersion() => $_has(18);
+ @$pb.TagNumber(19)
+ void clearUpdateSkipVersion() => $_clearField(19);
}
class OfficialUsage extends $pb.GeneratedMessage {
@@ -2993,6 +3020,8 @@ class Status extends $pb.GeneratedMessage {
$core.bool? lanBlocked,
$fixnum.Int64? verboseLogUntilUnix,
OfficialUsage? officialUsage,
+ $core.String? updateAvailable,
+ UpdateResult? lastUpdate,
}) {
final result = Status._();
if (deviceId != null) result.deviceId = deviceId;
@@ -3010,6 +3039,8 @@ class Status extends $pb.GeneratedMessage {
if (verboseLogUntilUnix != null)
result.verboseLogUntilUnix = verboseLogUntilUnix;
if (officialUsage != null) result.officialUsage = officialUsage;
+ if (updateAvailable != null) result.updateAvailable = updateAvailable;
+ if (lastUpdate != null) result.lastUpdate = lastUpdate;
return result;
}
@@ -3040,6 +3071,9 @@ class Status extends $pb.GeneratedMessage {
..aInt64(11, _omitFieldNames ? '' : 'verboseLogUntilUnix')
..aOM<OfficialUsage>(12, _omitFieldNames ? '' : 'officialUsage',
subBuilder: OfficialUsage.$_createMessage)
+ ..aOS(13, _omitFieldNames ? '' : 'updateAvailable')
+ ..aOM<UpdateResult>(14, _omitFieldNames ? '' : 'lastUpdate',
+ subBuilder: UpdateResult.$_createMessage)
..hasRequiredFields = false;
@$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')
@@ -3174,6 +3208,639 @@ class Status extends $pb.GeneratedMessage {
void clearOfficialUsage() => $_clearField(12);
@$pb.TagNumber(12)
OfficialUsage ensureOfficialUsage() => $_ensure(11);
+
+ /// 自动检查发现的新版本(没被跳过);空表示没有要提示的
+ @$pb.TagNumber(13)
+ $core.String get updateAvailable => $_getSZ(12);
+ @$pb.TagNumber(13)
+ set updateAvailable($core.String value) => $_setString(12, value);
+ @$pb.TagNumber(13)
+ $core.bool hasUpdateAvailable() => $_has(12);
+ @$pb.TagNumber(13)
+ void clearUpdateAvailable() => $_clearField(13);
+
+ /// 刚完成的一次自动更新,界面据此提示「已更新到 X」;过一会儿就不再带
+ @$pb.TagNumber(14)
+ UpdateResult get lastUpdate => $_getN(13);
+ @$pb.TagNumber(14)
+ set lastUpdate(UpdateResult value) => $_setField(14, value);
+ @$pb.TagNumber(14)
+ $core.bool hasLastUpdate() => $_has(13);
+ @$pb.TagNumber(14)
+ void clearLastUpdate() => $_clearField(14);
+ @$pb.TagNumber(14)
+ UpdateResult ensureLastUpdate() => $_ensure(13);
+}
+
+class CheckForUpdateRequest extends $pb.GeneratedMessage {
+ factory CheckForUpdateRequest({
+ $core.String? language,
+ }) {
+ final result = CheckForUpdateRequest._();
+ if (language != null) result.language = language;
+ return result;
+ }
+
+ CheckForUpdateRequest._();
+
+ factory CheckForUpdateRequest.fromBuffer($core.List<$core.int> data,
+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>
+ CheckForUpdateRequest()..mergeFromBuffer(data, registry);
+ factory CheckForUpdateRequest.fromJson($core.String json,
+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>
+ CheckForUpdateRequest()..mergeFromJson(json, registry);
+
+ static final $pb.BuilderInfo _i = $pb.BuilderInfo(
+ _omitMessageNames ? '' : 'CheckForUpdateRequest',
+ package: const $pb.PackageName(_omitMessageNames ? '' : 'pasteferry.v1'),
+ createEmptyInstance: CheckForUpdateRequest.$_createMessage)
+ ..aOS(1, _omitFieldNames ? '' : 'language')
+ ..hasRequiredFields = false;
+
+ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')
+ CheckForUpdateRequest clone() => deepCopy();
+ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')
+ CheckForUpdateRequest copyWith(
+ void Function(CheckForUpdateRequest) updates) =>
+ super.copyWith((message) => updates(message as CheckForUpdateRequest))
+ as CheckForUpdateRequest;
+
+ @$core.override
+ $pb.BuilderInfo get info_ => _i;
+
+ @$core.pragma('dart2js:noInline')
+ @$core.Deprecated(
+ 'Use CheckForUpdateRequest() / CheckForUpdateRequest.new instead')
+ static CheckForUpdateRequest create() => CheckForUpdateRequest._();
+ static $pb.GeneratedMessage $_createMessage() => CheckForUpdateRequest._();
+ @$core.override
+ CheckForUpdateRequest createEmptyInstance() => CheckForUpdateRequest._();
+ @$core.pragma('dart2js:noInline')
+ static CheckForUpdateRequest getDefault() => _defaultInstance ??=
+ $pb.GeneratedMessage.$_defaultFor<CheckForUpdateRequest>(
+ CheckForUpdateRequest.$_createMessage);
+ static CheckForUpdateRequest? _defaultInstance;
+
+ /// 界面语言,用来挑更新日志:"en"、"zh-Hans"、"zh-Hant-TW"、"zh-Hant-HK"、"ja"
+ @$pb.TagNumber(1)
+ $core.String get language => $_getSZ(0);
+ @$pb.TagNumber(1)
+ set language($core.String value) => $_setString(0, value);
+ @$pb.TagNumber(1)
+ $core.bool hasLanguage() => $_has(0);
+ @$pb.TagNumber(1)
+ void clearLanguage() => $_clearField(1);
+}
+
+class UpdateRelease extends $pb.GeneratedMessage {
+ factory UpdateRelease({
+ $core.String? version,
+ $core.String? date,
+ $core.Iterable<$core.String>? changes,
+ $core.Iterable<$core.String>? fixes,
+ }) {
+ final result = UpdateRelease._();
+ if (version != null) result.version = version;
+ if (date != null) result.date = date;
+ if (changes != null) result.changes.addAll(changes);
+ if (fixes != null) result.fixes.addAll(fixes);
+ return result;
+ }
+
+ UpdateRelease._();
+
+ factory UpdateRelease.fromBuffer($core.List<$core.int> data,
+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>
+ UpdateRelease()..mergeFromBuffer(data, registry);
+ factory UpdateRelease.fromJson($core.String json,
+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>
+ UpdateRelease()..mergeFromJson(json, registry);
+
+ static final $pb.BuilderInfo _i = $pb.BuilderInfo(
+ _omitMessageNames ? '' : 'UpdateRelease',
+ package: const $pb.PackageName(_omitMessageNames ? '' : 'pasteferry.v1'),
+ createEmptyInstance: UpdateRelease.$_createMessage)
+ ..aOS(1, _omitFieldNames ? '' : 'version')
+ ..aOS(2, _omitFieldNames ? '' : 'date')
+ ..pPS(3, _omitFieldNames ? '' : 'changes')
+ ..pPS(4, _omitFieldNames ? '' : 'fixes')
+ ..hasRequiredFields = false;
+
+ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')
+ UpdateRelease clone() => deepCopy();
+ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')
+ UpdateRelease copyWith(void Function(UpdateRelease) updates) =>
+ super.copyWith((message) => updates(message as UpdateRelease))
+ as UpdateRelease;
+
+ @$core.override
+ $pb.BuilderInfo get info_ => _i;
+
+ @$core.pragma('dart2js:noInline')
+ @$core.Deprecated('Use UpdateRelease() / UpdateRelease.new instead')
+ static UpdateRelease create() => UpdateRelease._();
+ static $pb.GeneratedMessage $_createMessage() => UpdateRelease._();
+ @$core.override
+ UpdateRelease createEmptyInstance() => UpdateRelease._();
+ @$core.pragma('dart2js:noInline')
+ static UpdateRelease getDefault() =>
+ _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor<UpdateRelease>(
+ UpdateRelease.$_createMessage);
+ static UpdateRelease? _defaultInstance;
+
+ @$pb.TagNumber(1)
+ $core.String get version => $_getSZ(0);
+ @$pb.TagNumber(1)
+ set version($core.String value) => $_setString(0, value);
+ @$pb.TagNumber(1)
+ $core.bool hasVersion() => $_has(0);
+ @$pb.TagNumber(1)
+ void clearVersion() => $_clearField(1);
+
+ @$pb.TagNumber(2)
+ $core.String get date => $_getSZ(1);
+ @$pb.TagNumber(2)
+ set date($core.String value) => $_setString(1, value);
+ @$pb.TagNumber(2)
+ $core.bool hasDate() => $_has(1);
+ @$pb.TagNumber(2)
+ void clearDate() => $_clearField(2);
+
+ @$pb.TagNumber(3)
+ $pb.PbList<$core.String> get changes => $_getList(2);
+
+ @$pb.TagNumber(4)
+ $pb.PbList<$core.String> get fixes => $_getList(3);
+}
+
+class UpdateInfo extends $pb.GeneratedMessage {
+ factory UpdateInfo({
+ $core.String? currentVersion,
+ $core.String? latestVersion,
+ $core.bool? available,
+ $core.Iterable<UpdateRelease>? releases,
+ $fixnum.Int64? downloadBytes,
+ $core.String? installBlocker,
+ $core.String? source,
+ $fixnum.Int64? checkedAtUnix,
+ $core.String? installKind,
+ }) {
+ final result = UpdateInfo._();
+ if (currentVersion != null) result.currentVersion = currentVersion;
+ if (latestVersion != null) result.latestVersion = latestVersion;
+ if (available != null) result.available = available;
+ if (releases != null) result.releases.addAll(releases);
+ if (downloadBytes != null) result.downloadBytes = downloadBytes;
+ if (installBlocker != null) result.installBlocker = installBlocker;
+ if (source != null) result.source = source;
+ if (checkedAtUnix != null) result.checkedAtUnix = checkedAtUnix;
+ if (installKind != null) result.installKind = installKind;
+ return result;
+ }
+
+ UpdateInfo._();
+
+ factory UpdateInfo.fromBuffer($core.List<$core.int> data,
+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>
+ UpdateInfo()..mergeFromBuffer(data, registry);
+ factory UpdateInfo.fromJson($core.String json,
+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>
+ UpdateInfo()..mergeFromJson(json, registry);
+
+ static final $pb.BuilderInfo _i = $pb.BuilderInfo(
+ _omitMessageNames ? '' : 'UpdateInfo',
+ package: const $pb.PackageName(_omitMessageNames ? '' : 'pasteferry.v1'),
+ createEmptyInstance: UpdateInfo.$_createMessage)
+ ..aOS(1, _omitFieldNames ? '' : 'currentVersion')
+ ..aOS(2, _omitFieldNames ? '' : 'latestVersion')
+ ..aOB(3, _omitFieldNames ? '' : 'available')
+ ..pPM<UpdateRelease>(4, _omitFieldNames ? '' : 'releases',
+ subBuilder: UpdateRelease.$_createMessage)
+ ..aInt64(5, _omitFieldNames ? '' : 'downloadBytes')
+ ..aOS(6, _omitFieldNames ? '' : 'installBlocker')
+ ..aOS(7, _omitFieldNames ? '' : 'source')
+ ..aInt64(8, _omitFieldNames ? '' : 'checkedAtUnix')
+ ..aOS(9, _omitFieldNames ? '' : 'installKind')
+ ..hasRequiredFields = false;
+
+ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')
+ UpdateInfo clone() => deepCopy();
+ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')
+ UpdateInfo copyWith(void Function(UpdateInfo) updates) =>
+ super.copyWith((message) => updates(message as UpdateInfo)) as UpdateInfo;
+
+ @$core.override
+ $pb.BuilderInfo get info_ => _i;
+
+ @$core.pragma('dart2js:noInline')
+ @$core.Deprecated('Use UpdateInfo() / UpdateInfo.new instead')
+ static UpdateInfo create() => UpdateInfo._();
+ static $pb.GeneratedMessage $_createMessage() => UpdateInfo._();
+ @$core.override
+ UpdateInfo createEmptyInstance() => UpdateInfo._();
+ @$core.pragma('dart2js:noInline')
+ static UpdateInfo getDefault() => _defaultInstance ??=
+ $pb.GeneratedMessage.$_defaultFor<UpdateInfo>(UpdateInfo.$_createMessage);
+ static UpdateInfo? _defaultInstance;
+
+ @$pb.TagNumber(1)
+ $core.String get currentVersion => $_getSZ(0);
+ @$pb.TagNumber(1)
+ set currentVersion($core.String value) => $_setString(0, value);
+ @$pb.TagNumber(1)
+ $core.bool hasCurrentVersion() => $_has(0);
+ @$pb.TagNumber(1)
+ void clearCurrentVersion() => $_clearField(1);
+
+ @$pb.TagNumber(2)
+ $core.String get latestVersion => $_getSZ(1);
+ @$pb.TagNumber(2)
+ set latestVersion($core.String value) => $_setString(1, value);
+ @$pb.TagNumber(2)
+ $core.bool hasLatestVersion() => $_has(1);
+ @$pb.TagNumber(2)
+ void clearLatestVersion() => $_clearField(2);
+
+ /// latest_version 比当前新
+ @$pb.TagNumber(3)
+ $core.bool get available => $_getBF(2);
+ @$pb.TagNumber(3)
+ set available($core.bool value) => $_setBool(2, value);
+ @$pb.TagNumber(3)
+ $core.bool hasAvailable() => $_has(2);
+ @$pb.TagNumber(3)
+ void clearAvailable() => $_clearField(3);
+
+ /// 比当前新的各版更新日志,从新到旧,已按语言挑好
+ @$pb.TagNumber(4)
+ $pb.PbList<UpdateRelease> get releases => $_getList(3);
+
+ /// 这台电脑要下载的安装包大小
+ @$pb.TagNumber(5)
+ $fixnum.Int64 get downloadBytes => $_getI64(4);
+ @$pb.TagNumber(5)
+ set downloadBytes($fixnum.Int64 value) => $_setInt64(4, value);
+ @$pb.TagNumber(5)
+ $core.bool hasDownloadBytes() => $_has(4);
+ @$pb.TagNumber(5)
+ void clearDownloadBytes() => $_clearField(5);
+
+ /// 为空表示可以自动安装;否则是不能的原因:dev、must_move、read_only、unsupported
+ @$pb.TagNumber(6)
+ $core.String get installBlocker => $_getSZ(5);
+ @$pb.TagNumber(6)
+ set installBlocker($core.String value) => $_setString(5, value);
+ @$pb.TagNumber(6)
+ $core.bool hasInstallBlocker() => $_has(5);
+ @$pb.TagNumber(6)
+ void clearInstallBlocker() => $_clearField(6);
+
+ /// 清单来自哪里:github 或 gitee
+ @$pb.TagNumber(7)
+ $core.String get source => $_getSZ(6);
+ @$pb.TagNumber(7)
+ set source($core.String value) => $_setString(6, value);
+ @$pb.TagNumber(7)
+ $core.bool hasSource() => $_has(6);
+ @$pb.TagNumber(7)
+ void clearSource() => $_clearField(7);
+
+ @$pb.TagNumber(8)
+ $fixnum.Int64 get checkedAtUnix => $_getI64(7);
+ @$pb.TagNumber(8)
+ set checkedAtUnix($fixnum.Int64 value) => $_setInt64(7, value);
+ @$pb.TagNumber(8)
+ $core.bool hasCheckedAtUnix() => $_has(7);
+ @$pb.TagNumber(8)
+ void clearCheckedAtUnix() => $_clearField(8);
+
+ /// 本机的安装方式:mac-app、windows-setup、windows-portable、linux-deb、linux-tar。
+ /// linux-deb 安装时系统会要求输入密码,界面提前说明
+ @$pb.TagNumber(9)
+ $core.String get installKind => $_getSZ(8);
+ @$pb.TagNumber(9)
+ set installKind($core.String value) => $_setString(8, value);
+ @$pb.TagNumber(9)
+ $core.bool hasInstallKind() => $_has(8);
+ @$pb.TagNumber(9)
+ void clearInstallKind() => $_clearField(9);
+}
+
+class DownloadUpdateRequest extends $pb.GeneratedMessage {
+ factory DownloadUpdateRequest({
+ $core.String? version,
+ }) {
+ final result = DownloadUpdateRequest._();
+ if (version != null) result.version = version;
+ return result;
+ }
+
+ DownloadUpdateRequest._();
+
+ factory DownloadUpdateRequest.fromBuffer($core.List<$core.int> data,
+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>
+ DownloadUpdateRequest()..mergeFromBuffer(data, registry);
+ factory DownloadUpdateRequest.fromJson($core.String json,
+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>
+ DownloadUpdateRequest()..mergeFromJson(json, registry);
+
+ static final $pb.BuilderInfo _i = $pb.BuilderInfo(
+ _omitMessageNames ? '' : 'DownloadUpdateRequest',
+ package: const $pb.PackageName(_omitMessageNames ? '' : 'pasteferry.v1'),
+ createEmptyInstance: DownloadUpdateRequest.$_createMessage)
+ ..aOS(1, _omitFieldNames ? '' : 'version')
+ ..hasRequiredFields = false;
+
+ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')
+ DownloadUpdateRequest clone() => deepCopy();
+ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')
+ DownloadUpdateRequest copyWith(
+ void Function(DownloadUpdateRequest) updates) =>
+ super.copyWith((message) => updates(message as DownloadUpdateRequest))
+ as DownloadUpdateRequest;
+
+ @$core.override
+ $pb.BuilderInfo get info_ => _i;
+
+ @$core.pragma('dart2js:noInline')
+ @$core.Deprecated(
+ 'Use DownloadUpdateRequest() / DownloadUpdateRequest.new instead')
+ static DownloadUpdateRequest create() => DownloadUpdateRequest._();
+ static $pb.GeneratedMessage $_createMessage() => DownloadUpdateRequest._();
+ @$core.override
+ DownloadUpdateRequest createEmptyInstance() => DownloadUpdateRequest._();
+ @$core.pragma('dart2js:noInline')
+ static DownloadUpdateRequest getDefault() => _defaultInstance ??=
+ $pb.GeneratedMessage.$_defaultFor<DownloadUpdateRequest>(
+ DownloadUpdateRequest.$_createMessage);
+ static DownloadUpdateRequest? _defaultInstance;
+
+ @$pb.TagNumber(1)
+ $core.String get version => $_getSZ(0);
+ @$pb.TagNumber(1)
+ set version($core.String value) => $_setString(0, value);
+ @$pb.TagNumber(1)
+ $core.bool hasVersion() => $_has(0);
+ @$pb.TagNumber(1)
+ void clearVersion() => $_clearField(1);
+}
+
+class UpdateProgress extends $pb.GeneratedMessage {
+ factory UpdateProgress({
+ $fixnum.Int64? downloaded,
+ $fixnum.Int64? total,
+ $core.bool? done,
+ }) {
+ final result = UpdateProgress._();
+ if (downloaded != null) result.downloaded = downloaded;
+ if (total != null) result.total = total;
+ if (done != null) result.done = done;
+ return result;
+ }
+
+ UpdateProgress._();
+
+ factory UpdateProgress.fromBuffer($core.List<$core.int> data,
+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>
+ UpdateProgress()..mergeFromBuffer(data, registry);
+ factory UpdateProgress.fromJson($core.String json,
+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>
+ UpdateProgress()..mergeFromJson(json, registry);
+
+ static final $pb.BuilderInfo _i = $pb.BuilderInfo(
+ _omitMessageNames ? '' : 'UpdateProgress',
+ package: const $pb.PackageName(_omitMessageNames ? '' : 'pasteferry.v1'),
+ createEmptyInstance: UpdateProgress.$_createMessage)
+ ..aInt64(1, _omitFieldNames ? '' : 'downloaded')
+ ..aInt64(2, _omitFieldNames ? '' : 'total')
+ ..aOB(3, _omitFieldNames ? '' : 'done')
+ ..hasRequiredFields = false;
+
+ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')
+ UpdateProgress clone() => deepCopy();
+ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')
+ UpdateProgress copyWith(void Function(UpdateProgress) updates) =>
+ super.copyWith((message) => updates(message as UpdateProgress))
+ as UpdateProgress;
+
+ @$core.override
+ $pb.BuilderInfo get info_ => _i;
+
+ @$core.pragma('dart2js:noInline')
+ @$core.Deprecated('Use UpdateProgress() / UpdateProgress.new instead')
+ static UpdateProgress create() => UpdateProgress._();
+ static $pb.GeneratedMessage $_createMessage() => UpdateProgress._();
+ @$core.override
+ UpdateProgress createEmptyInstance() => UpdateProgress._();
+ @$core.pragma('dart2js:noInline')
+ static UpdateProgress getDefault() =>
+ _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor<UpdateProgress>(
+ UpdateProgress.$_createMessage);
+ static UpdateProgress? _defaultInstance;
+
+ @$pb.TagNumber(1)
+ $fixnum.Int64 get downloaded => $_getI64(0);
+ @$pb.TagNumber(1)
+ set downloaded($fixnum.Int64 value) => $_setInt64(0, value);
+ @$pb.TagNumber(1)
+ $core.bool hasDownloaded() => $_has(0);
+ @$pb.TagNumber(1)
+ void clearDownloaded() => $_clearField(1);
+
+ @$pb.TagNumber(2)
+ $fixnum.Int64 get total => $_getI64(1);
+ @$pb.TagNumber(2)
+ set total($fixnum.Int64 value) => $_setInt64(1, value);
+ @$pb.TagNumber(2)
+ $core.bool hasTotal() => $_has(1);
+ @$pb.TagNumber(2)
+ void clearTotal() => $_clearField(2);
+
+ /// 下载完并通过校验
+ @$pb.TagNumber(3)
+ $core.bool get done => $_getBF(2);
+ @$pb.TagNumber(3)
+ set done($core.bool value) => $_setBool(2, value);
+ @$pb.TagNumber(3)
+ $core.bool hasDone() => $_has(2);
+ @$pb.TagNumber(3)
+ void clearDone() => $_clearField(3);
+}
+
+class InstallUpdateRequest extends $pb.GeneratedMessage {
+ factory InstallUpdateRequest({
+ $core.String? version,
+ $core.int? uiPid,
+ }) {
+ final result = InstallUpdateRequest._();
+ if (version != null) result.version = version;
+ if (uiPid != null) result.uiPid = uiPid;
+ return result;
+ }
+
+ InstallUpdateRequest._();
+
+ factory InstallUpdateRequest.fromBuffer($core.List<$core.int> data,
+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>
+ InstallUpdateRequest()..mergeFromBuffer(data, registry);
+ factory InstallUpdateRequest.fromJson($core.String json,
+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>
+ InstallUpdateRequest()..mergeFromJson(json, registry);
+
+ static final $pb.BuilderInfo _i = $pb.BuilderInfo(
+ _omitMessageNames ? '' : 'InstallUpdateRequest',
+ package: const $pb.PackageName(_omitMessageNames ? '' : 'pasteferry.v1'),
+ createEmptyInstance: InstallUpdateRequest.$_createMessage)
+ ..aOS(1, _omitFieldNames ? '' : 'version')
+ ..aI(2, _omitFieldNames ? '' : 'uiPid')
+ ..hasRequiredFields = false;
+
+ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')
+ InstallUpdateRequest clone() => deepCopy();
+ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')
+ InstallUpdateRequest copyWith(void Function(InstallUpdateRequest) updates) =>
+ super.copyWith((message) => updates(message as InstallUpdateRequest))
+ as InstallUpdateRequest;
+
+ @$core.override
+ $pb.BuilderInfo get info_ => _i;
+
+ @$core.pragma('dart2js:noInline')
+ @$core.Deprecated(
+ 'Use InstallUpdateRequest() / InstallUpdateRequest.new instead')
+ static InstallUpdateRequest create() => InstallUpdateRequest._();
+ static $pb.GeneratedMessage $_createMessage() => InstallUpdateRequest._();
+ @$core.override
+ InstallUpdateRequest createEmptyInstance() => InstallUpdateRequest._();
+ @$core.pragma('dart2js:noInline')
+ static InstallUpdateRequest getDefault() => _defaultInstance ??=
+ $pb.GeneratedMessage.$_defaultFor<InstallUpdateRequest>(
+ InstallUpdateRequest.$_createMessage);
+ static InstallUpdateRequest? _defaultInstance;
+
+ @$pb.TagNumber(1)
+ $core.String get version => $_getSZ(0);
+ @$pb.TagNumber(1)
+ set version($core.String value) => $_setString(0, value);
+ @$pb.TagNumber(1)
+ $core.bool hasVersion() => $_has(0);
+ @$pb.TagNumber(1)
+ void clearVersion() => $_clearField(1);
+
+ /// 界面的进程号:更新助手等它退出后再替换文件
+ @$pb.TagNumber(2)
+ $core.int get uiPid => $_getIZ(1);
+ @$pb.TagNumber(2)
+ set uiPid($core.int value) => $_setSignedInt32(1, value);
+ @$pb.TagNumber(2)
+ $core.bool hasUiPid() => $_has(1);
+ @$pb.TagNumber(2)
+ void clearUiPid() => $_clearField(2);
+}
+
+class UpdateResult extends $pb.GeneratedMessage {
+ factory UpdateResult({
+ $core.String? fromVersion,
+ $core.String? toVersion,
+ $core.bool? ok,
+ $core.String? error,
+ $fixnum.Int64? atUnix,
+ }) {
+ final result = UpdateResult._();
+ if (fromVersion != null) result.fromVersion = fromVersion;
+ if (toVersion != null) result.toVersion = toVersion;
+ if (ok != null) result.ok = ok;
+ if (error != null) result.error = error;
+ if (atUnix != null) result.atUnix = atUnix;
+ return result;
+ }
+
+ UpdateResult._();
+
+ factory UpdateResult.fromBuffer($core.List<$core.int> data,
+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>
+ UpdateResult()..mergeFromBuffer(data, registry);
+ factory UpdateResult.fromJson($core.String json,
+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>
+ UpdateResult()..mergeFromJson(json, registry);
+
+ static final $pb.BuilderInfo _i = $pb.BuilderInfo(
+ _omitMessageNames ? '' : 'UpdateResult',
+ package: const $pb.PackageName(_omitMessageNames ? '' : 'pasteferry.v1'),
+ createEmptyInstance: UpdateResult.$_createMessage)
+ ..aOS(1, _omitFieldNames ? '' : 'fromVersion')
+ ..aOS(2, _omitFieldNames ? '' : 'toVersion')
+ ..aOB(3, _omitFieldNames ? '' : 'ok')
+ ..aOS(4, _omitFieldNames ? '' : 'error')
+ ..aInt64(5, _omitFieldNames ? '' : 'atUnix')
+ ..hasRequiredFields = false;
+
+ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')
+ UpdateResult clone() => deepCopy();
+ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')
+ UpdateResult copyWith(void Function(UpdateResult) updates) =>
+ super.copyWith((message) => updates(message as UpdateResult))
+ as UpdateResult;
+
+ @$core.override
+ $pb.BuilderInfo get info_ => _i;
+
+ @$core.pragma('dart2js:noInline')
+ @$core.Deprecated('Use UpdateResult() / UpdateResult.new instead')
+ static UpdateResult create() => UpdateResult._();
+ static $pb.GeneratedMessage $_createMessage() => UpdateResult._();
+ @$core.override
+ UpdateResult createEmptyInstance() => UpdateResult._();
+ @$core.pragma('dart2js:noInline')
+ static UpdateResult getDefault() =>
+ _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor<UpdateResult>(
+ UpdateResult.$_createMessage);
+ static UpdateResult? _defaultInstance;
+
+ @$pb.TagNumber(1)
+ $core.String get fromVersion => $_getSZ(0);
+ @$pb.TagNumber(1)
+ set fromVersion($core.String value) => $_setString(0, value);
+ @$pb.TagNumber(1)
+ $core.bool hasFromVersion() => $_has(0);
+ @$pb.TagNumber(1)
+ void clearFromVersion() => $_clearField(1);
+
+ @$pb.TagNumber(2)
+ $core.String get toVersion => $_getSZ(1);
+ @$pb.TagNumber(2)
+ set toVersion($core.String value) => $_setString(1, value);
+ @$pb.TagNumber(2)
+ $core.bool hasToVersion() => $_has(1);
+ @$pb.TagNumber(2)
+ void clearToVersion() => $_clearField(2);
+
+ @$pb.TagNumber(3)
+ $core.bool get ok => $_getBF(2);
+ @$pb.TagNumber(3)
+ set ok($core.bool value) => $_setBool(2, value);
+ @$pb.TagNumber(3)
+ $core.bool hasOk() => $_has(2);
+ @$pb.TagNumber(3)
+ void clearOk() => $_clearField(3);
+
+ @$pb.TagNumber(4)
+ $core.String get error => $_getSZ(3);
+ @$pb.TagNumber(4)
+ set error($core.String value) => $_setString(3, value);
+ @$pb.TagNumber(4)
+ $core.bool hasError() => $_has(3);
+ @$pb.TagNumber(4)
+ void clearError() => $_clearField(4);
+
+ @$pb.TagNumber(5)
+ $fixnum.Int64 get atUnix => $_getI64(4);
+ @$pb.TagNumber(5)
+ set atUnix($fixnum.Int64 value) => $_setInt64(4, value);
+ @$pb.TagNumber(5)
+ $core.bool hasAtUnix() => $_has(4);
+ @$pb.TagNumber(5)
+ void clearAtUnix() => $_clearField(5);
}
class ExportDiagnosticsRequest extends $pb.GeneratedMessage {
diff --git a/ui/lib/gen/pasteferry/v1/daemon.pbgrpc.dart b/ui/lib/gen/pasteferry/v1/daemon.pbgrpc.dart
index 7f0f219..12872d4 100644
--- a/ui/lib/gen/pasteferry/v1/daemon.pbgrpc.dart
+++ b/ui/lib/gen/pasteferry/v1/daemon.pbgrpc.dart
@@ -231,6 +231,32 @@ class DaemonServiceClient extends $grpc.Client {
return $createUnaryCall(_$setVerboseLog, request, options: options);
}
+ /// 检查更新:从 GitHub 与 Gitee 同时取更新清单,验签后返回比当前新的各版更新日志。见 design/auto-update.md
+ $grpc.ResponseFuture<$0.UpdateInfo> checkForUpdate(
+ $0.CheckForUpdateRequest request, {
+ $grpc.CallOptions? options,
+ }) {
+ return $createUnaryCall(_$checkForUpdate, request, options: options);
+ }
+
+ /// 下载并校验最近一次检查到的新版本。取消调用即停止下载
+ $grpc.ResponseStream<$0.UpdateProgress> downloadUpdate(
+ $0.DownloadUpdateRequest request, {
+ $grpc.CallOptions? options,
+ }) {
+ return $createStreamingCall(
+ _$downloadUpdate, $async.Stream.fromIterable([request]),
+ options: options);
+ }
+
+ /// 准备好新版本并启动更新助手。返回后界面应当立即退出:助手等它退出后替换文件,再重新打开
+ $grpc.ResponseFuture<$0.Empty> installUpdate(
+ $0.InstallUpdateRequest request, {
+ $grpc.CallOptions? options,
+ }) {
+ return $createUnaryCall(_$installUpdate, request, options: options);
+ }
+
// method descriptors
static final _$subscribe = $grpc.ClientMethod<$0.SubscribeRequest, $0.Event>(
@@ -350,6 +376,21 @@ class DaemonServiceClient extends $grpc.Client {
'/pasteferry.v1.DaemonService/SetVerboseLog',
($0.SetVerboseLogRequest value) => value.writeToBuffer(),
$0.Status.fromBuffer);
+ static final _$checkForUpdate =
+ $grpc.ClientMethod<$0.CheckForUpdateRequest, $0.UpdateInfo>(
+ '/pasteferry.v1.DaemonService/CheckForUpdate',
+ ($0.CheckForUpdateRequest value) => value.writeToBuffer(),
+ $0.UpdateInfo.fromBuffer);
+ static final _$downloadUpdate =
+ $grpc.ClientMethod<$0.DownloadUpdateRequest, $0.UpdateProgress>(
+ '/pasteferry.v1.DaemonService/DownloadUpdate',
+ ($0.DownloadUpdateRequest value) => value.writeToBuffer(),
+ $0.UpdateProgress.fromBuffer);
+ static final _$installUpdate =
+ $grpc.ClientMethod<$0.InstallUpdateRequest, $0.Empty>(
+ '/pasteferry.v1.DaemonService/InstallUpdate',
+ ($0.InstallUpdateRequest value) => value.writeToBuffer(),
+ $0.Empty.fromBuffer);
}
@$pb.GrpcServiceName('pasteferry.v1.DaemonService')
@@ -547,6 +588,30 @@ abstract class DaemonServiceBase extends $grpc.Service {
($core.List<$core.int> value) =>
$0.SetVerboseLogRequest.fromBuffer(value),
($0.Status value) => value.writeToBuffer()));
+ $addMethod($grpc.ServiceMethod<$0.CheckForUpdateRequest, $0.UpdateInfo>(
+ 'CheckForUpdate',
+ checkForUpdate_Pre,
+ false,
+ false,
+ ($core.List<$core.int> value) =>
+ $0.CheckForUpdateRequest.fromBuffer(value),
+ ($0.UpdateInfo value) => value.writeToBuffer()));
+ $addMethod($grpc.ServiceMethod<$0.DownloadUpdateRequest, $0.UpdateProgress>(
+ 'DownloadUpdate',
+ downloadUpdate_Pre,
+ false,
+ true,
+ ($core.List<$core.int> value) =>
+ $0.DownloadUpdateRequest.fromBuffer(value),
+ ($0.UpdateProgress value) => value.writeToBuffer()));
+ $addMethod($grpc.ServiceMethod<$0.InstallUpdateRequest, $0.Empty>(
+ 'InstallUpdate',
+ installUpdate_Pre,
+ false,
+ false,
+ ($core.List<$core.int> value) =>
+ $0.InstallUpdateRequest.fromBuffer(value),
+ ($0.Empty value) => value.writeToBuffer()));
}
$async.Stream<$0.Event> subscribe_Pre($grpc.ServiceCall $call,
@@ -749,4 +814,28 @@ abstract class DaemonServiceBase extends $grpc.Service {
$async.Future<$0.Status> setVerboseLog(
$grpc.ServiceCall call, $0.SetVerboseLogRequest request);
+
+ $async.Future<$0.UpdateInfo> checkForUpdate_Pre($grpc.ServiceCall $call,
+ $async.Future<$0.CheckForUpdateRequest> $request) async {
+ return checkForUpdate($call, await $request);
+ }
+
+ $async.Future<$0.UpdateInfo> checkForUpdate(
+ $grpc.ServiceCall call, $0.CheckForUpdateRequest request);
+
+ $async.Stream<$0.UpdateProgress> downloadUpdate_Pre($grpc.ServiceCall $call,
+ $async.Future<$0.DownloadUpdateRequest> $request) async* {
+ yield* downloadUpdate($call, await $request);
+ }
+
+ $async.Stream<$0.UpdateProgress> downloadUpdate(
+ $grpc.ServiceCall call, $0.DownloadUpdateRequest request);
+
+ $async.Future<$0.Empty> installUpdate_Pre($grpc.ServiceCall $call,
+ $async.Future<$0.InstallUpdateRequest> $request) async {
+ return installUpdate($call, await $request);
+ }
+
+ $async.Future<$0.Empty> installUpdate(
+ $grpc.ServiceCall call, $0.InstallUpdateRequest request);
}
diff --git a/ui/lib/gen/pasteferry/v1/daemon.pbjson.dart b/ui/lib/gen/pasteferry/v1/daemon.pbjson.dart
index a010e02..f23ef0e 100644
--- a/ui/lib/gen/pasteferry/v1/daemon.pbjson.dart
+++ b/ui/lib/gen/pasteferry/v1/daemon.pbjson.dart
@@ -741,6 +741,20 @@ const Config$json = {
'5': 9,
'10': 'officialNoticeAck'
},
+ {
+ '1': 'update_check_disabled',
+ '3': 18,
+ '4': 1,
+ '5': 8,
+ '10': 'updateCheckDisabled'
+ },
+ {
+ '1': 'update_skip_version',
+ '3': 19,
+ '4': 1,
+ '5': 9,
+ '10': 'updateSkipVersion'
+ },
],
};
@@ -758,7 +772,9 @@ final $typed_data.Uint8List configDescriptor = $convert.base64Decode(
'FuZ3VhZ2USIQoMbGFuX2Rpc2FibGVkGA4gASgIUgtsYW5EaXNhYmxlZBI9CgxzZXJ2aWNlX21v'
'ZGUYDyABKA4yGi5wYXN0ZWZlcnJ5LnYxLlNlcnZpY2VNb2RlUgtzZXJ2aWNlTW9kZRIwChRjdX'
'N0b21fc2lnbmFsaW5nX3VybBgQIAEoCVISY3VzdG9tU2lnbmFsaW5nVXJsEi4KE29mZmljaWFs'
- 'X25vdGljZV9hY2sYESABKAlSEW9mZmljaWFsTm90aWNlQWNr');
+ 'X25vdGljZV9hY2sYESABKAlSEW9mZmljaWFsTm90aWNlQWNrEjIKFXVwZGF0ZV9jaGVja19kaX'
+ 'NhYmxlZBgSIAEoCFITdXBkYXRlQ2hlY2tEaXNhYmxlZBIuChN1cGRhdGVfc2tpcF92ZXJzaW9u'
+ 'GBMgASgJUhF1cGRhdGVTa2lwVmVyc2lvbg==');
@$core.Deprecated('Use officialUsageDescriptor instead')
const OfficialUsage$json = {
@@ -934,6 +950,15 @@ const Status$json = {
'6': '.pasteferry.v1.OfficialUsage',
'10': 'officialUsage'
},
+ {'1': 'update_available', '3': 13, '4': 1, '5': 9, '10': 'updateAvailable'},
+ {
+ '1': 'last_update',
+ '3': 14,
+ '4': 1,
+ '5': 11,
+ '6': '.pasteferry.v1.UpdateResult',
+ '10': 'lastUpdate'
+ },
],
};
@@ -948,7 +973,131 @@ final $typed_data.Uint8List statusDescriptor = $convert.base64Decode(
'ASgIUhBzZXJ2ZXJDb25maWd1cmVkEh8KC2xhbl9lbmFibGVkGAkgASgIUgpsYW5FbmFibGVkEh'
'8KC2xhbl9ibG9ja2VkGAogASgIUgpsYW5CbG9ja2VkEjMKFnZlcmJvc2VfbG9nX3VudGlsX3Vu'
'aXgYCyABKANSE3ZlcmJvc2VMb2dVbnRpbFVuaXgSQwoOb2ZmaWNpYWxfdXNhZ2UYDCABKAsyHC'
- '5wYXN0ZWZlcnJ5LnYxLk9mZmljaWFsVXNhZ2VSDW9mZmljaWFsVXNhZ2U=');
+ '5wYXN0ZWZlcnJ5LnYxLk9mZmljaWFsVXNhZ2VSDW9mZmljaWFsVXNhZ2USKQoQdXBkYXRlX2F2'
+ 'YWlsYWJsZRgNIAEoCVIPdXBkYXRlQXZhaWxhYmxlEjwKC2xhc3RfdXBkYXRlGA4gASgLMhsucG'
+ 'FzdGVmZXJyeS52MS5VcGRhdGVSZXN1bHRSCmxhc3RVcGRhdGU=');
+
+@$core.Deprecated('Use checkForUpdateRequestDescriptor instead')
+const CheckForUpdateRequest$json = {
+ '1': 'CheckForUpdateRequest',
+ '2': [
+ {'1': 'language', '3': 1, '4': 1, '5': 9, '10': 'language'},
+ ],
+};
+
+/// Descriptor for `CheckForUpdateRequest`. Decode as a `google.protobuf.DescriptorProto`.
+final $typed_data.Uint8List checkForUpdateRequestDescriptor =
+ $convert.base64Decode(
+ 'ChVDaGVja0ZvclVwZGF0ZVJlcXVlc3QSGgoIbGFuZ3VhZ2UYASABKAlSCGxhbmd1YWdl');
+
+@$core.Deprecated('Use updateReleaseDescriptor instead')
+const UpdateRelease$json = {
+ '1': 'UpdateRelease',
+ '2': [
+ {'1': 'version', '3': 1, '4': 1, '5': 9, '10': 'version'},
+ {'1': 'date', '3': 2, '4': 1, '5': 9, '10': 'date'},
+ {'1': 'changes', '3': 3, '4': 3, '5': 9, '10': 'changes'},
+ {'1': 'fixes', '3': 4, '4': 3, '5': 9, '10': 'fixes'},
+ ],
+};
+
+/// Descriptor for `UpdateRelease`. Decode as a `google.protobuf.DescriptorProto`.
+final $typed_data.Uint8List updateReleaseDescriptor = $convert.base64Decode(
+ 'Cg1VcGRhdGVSZWxlYXNlEhgKB3ZlcnNpb24YASABKAlSB3ZlcnNpb24SEgoEZGF0ZRgCIAEoCV'
+ 'IEZGF0ZRIYCgdjaGFuZ2VzGAMgAygJUgdjaGFuZ2VzEhQKBWZpeGVzGAQgAygJUgVmaXhlcw==');
+
+@$core.Deprecated('Use updateInfoDescriptor instead')
+const UpdateInfo$json = {
+ '1': 'UpdateInfo',
+ '2': [
+ {'1': 'current_version', '3': 1, '4': 1, '5': 9, '10': 'currentVersion'},
+ {'1': 'latest_version', '3': 2, '4': 1, '5': 9, '10': 'latestVersion'},
+ {'1': 'available', '3': 3, '4': 1, '5': 8, '10': 'available'},
+ {
+ '1': 'releases',
+ '3': 4,
+ '4': 3,
+ '5': 11,
+ '6': '.pasteferry.v1.UpdateRelease',
+ '10': 'releases'
+ },
+ {'1': 'download_bytes', '3': 5, '4': 1, '5': 3, '10': 'downloadBytes'},
+ {'1': 'install_blocker', '3': 6, '4': 1, '5': 9, '10': 'installBlocker'},
+ {'1': 'source', '3': 7, '4': 1, '5': 9, '10': 'source'},
+ {'1': 'checked_at_unix', '3': 8, '4': 1, '5': 3, '10': 'checkedAtUnix'},
+ {'1': 'install_kind', '3': 9, '4': 1, '5': 9, '10': 'installKind'},
+ ],
+};
+
+/// Descriptor for `UpdateInfo`. Decode as a `google.protobuf.DescriptorProto`.
+final $typed_data.Uint8List updateInfoDescriptor = $convert.base64Decode(
+ 'CgpVcGRhdGVJbmZvEicKD2N1cnJlbnRfdmVyc2lvbhgBIAEoCVIOY3VycmVudFZlcnNpb24SJQ'
+ 'oObGF0ZXN0X3ZlcnNpb24YAiABKAlSDWxhdGVzdFZlcnNpb24SHAoJYXZhaWxhYmxlGAMgASgI'
+ 'UglhdmFpbGFibGUSOAoIcmVsZWFzZXMYBCADKAsyHC5wYXN0ZWZlcnJ5LnYxLlVwZGF0ZVJlbG'
+ 'Vhc2VSCHJlbGVhc2VzEiUKDmRvd25sb2FkX2J5dGVzGAUgASgDUg1kb3dubG9hZEJ5dGVzEicK'
+ 'D2luc3RhbGxfYmxvY2tlchgGIAEoCVIOaW5zdGFsbEJsb2NrZXISFgoGc291cmNlGAcgASgJUg'
+ 'Zzb3VyY2USJgoPY2hlY2tlZF9hdF91bml4GAggASgDUg1jaGVja2VkQXRVbml4EiEKDGluc3Rh'
+ 'bGxfa2luZBgJIAEoCVILaW5zdGFsbEtpbmQ=');
+
+@$core.Deprecated('Use downloadUpdateRequestDescriptor instead')
+const DownloadUpdateRequest$json = {
+ '1': 'DownloadUpdateRequest',
+ '2': [
+ {'1': 'version', '3': 1, '4': 1, '5': 9, '10': 'version'},
+ ],
+};
+
+/// Descriptor for `DownloadUpdateRequest`. Decode as a `google.protobuf.DescriptorProto`.
+final $typed_data.Uint8List downloadUpdateRequestDescriptor =
+ $convert.base64Decode(
+ 'ChVEb3dubG9hZFVwZGF0ZVJlcXVlc3QSGAoHdmVyc2lvbhgBIAEoCVIHdmVyc2lvbg==');
+
+@$core.Deprecated('Use updateProgressDescriptor instead')
+const UpdateProgress$json = {
+ '1': 'UpdateProgress',
+ '2': [
+ {'1': 'downloaded', '3': 1, '4': 1, '5': 3, '10': 'downloaded'},
+ {'1': 'total', '3': 2, '4': 1, '5': 3, '10': 'total'},
+ {'1': 'done', '3': 3, '4': 1, '5': 8, '10': 'done'},
+ ],
+};
+
+/// Descriptor for `UpdateProgress`. Decode as a `google.protobuf.DescriptorProto`.
+final $typed_data.Uint8List updateProgressDescriptor = $convert.base64Decode(
+ 'Cg5VcGRhdGVQcm9ncmVzcxIeCgpkb3dubG9hZGVkGAEgASgDUgpkb3dubG9hZGVkEhQKBXRvdG'
+ 'FsGAIgASgDUgV0b3RhbBISCgRkb25lGAMgASgIUgRkb25l');
+
+@$core.Deprecated('Use installUpdateRequestDescriptor instead')
+const InstallUpdateRequest$json = {
+ '1': 'InstallUpdateRequest',
+ '2': [
+ {'1': 'version', '3': 1, '4': 1, '5': 9, '10': 'version'},
+ {'1': 'ui_pid', '3': 2, '4': 1, '5': 5, '10': 'uiPid'},
+ ],
+};
+
+/// Descriptor for `InstallUpdateRequest`. Decode as a `google.protobuf.DescriptorProto`.
+final $typed_data.Uint8List installUpdateRequestDescriptor = $convert.base64Decode(
+ 'ChRJbnN0YWxsVXBkYXRlUmVxdWVzdBIYCgd2ZXJzaW9uGAEgASgJUgd2ZXJzaW9uEhUKBnVpX3'
+ 'BpZBgCIAEoBVIFdWlQaWQ=');
+
+@$core.Deprecated('Use updateResultDescriptor instead')
+const UpdateResult$json = {
+ '1': 'UpdateResult',
+ '2': [
+ {'1': 'from_version', '3': 1, '4': 1, '5': 9, '10': 'fromVersion'},
+ {'1': 'to_version', '3': 2, '4': 1, '5': 9, '10': 'toVersion'},
+ {'1': 'ok', '3': 3, '4': 1, '5': 8, '10': 'ok'},
+ {'1': 'error', '3': 4, '4': 1, '5': 9, '10': 'error'},
+ {'1': 'at_unix', '3': 5, '4': 1, '5': 3, '10': 'atUnix'},
+ ],
+};
+
+/// Descriptor for `UpdateResult`. Decode as a `google.protobuf.DescriptorProto`.
+final $typed_data.Uint8List updateResultDescriptor = $convert.base64Decode(
+ 'CgxVcGRhdGVSZXN1bHQSIQoMZnJvbV92ZXJzaW9uGAEgASgJUgtmcm9tVmVyc2lvbhIdCgp0b1'
+ '92ZXJzaW9uGAIgASgJUgl0b1ZlcnNpb24SDgoCb2sYAyABKAhSAm9rEhQKBWVycm9yGAQgASgJ'
+ 'UgVlcnJvchIXCgdhdF91bml4GAUgASgDUgZhdFVuaXg=');
@$core.Deprecated('Use exportDiagnosticsRequestDescriptor instead')
const ExportDiagnosticsRequest$json = {