diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..3c2697c --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,29 @@ +name: CI + +on: + push: + branches: [main] + pull_request: + +permissions: + contents: read + +jobs: + check: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + persist-credentials: false + - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7 + with: + go-version-file: go.mod + - run: go mod verify + - run: go vet ./... + - run: go test -race ./... + - run: make build + - run: sh -n install.sh + - uses: goreleaser/goreleaser-action@a4f02ab5355a589de60d917a659ce617ed19b3de # v7 + with: + version: v2.20.0 + args: check diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..9256a99 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,31 @@ +name: Release + +on: + push: + tags: ["v[0-9]*"] + +permissions: + contents: read + +jobs: + release: + runs-on: ubuntu-latest + permissions: + contents: write + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + fetch-depth: 0 + persist-credentials: false + - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7 + with: + go-version-file: go.mod + - run: go mod verify + - run: go vet ./... + - run: go test -race ./... + - uses: goreleaser/goreleaser-action@a4f02ab5355a589de60d917a659ce617ed19b3de # v7 + with: + version: v2.20.0 + args: release --clean --parallelism 2 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/.goreleaser.yaml b/.goreleaser.yaml new file mode 100644 index 0000000..55bc033 --- /dev/null +++ b/.goreleaser.yaml @@ -0,0 +1,34 @@ +version: 2 +project_name: ta + +builds: + - main: ./cmd/ta + binary: ta + env: + - CGO_ENABLED=0 + goos: [linux, darwin, windows] + goarch: [amd64, arm64] + flags: [-trimpath] + ldflags: + - >- + -s -w + -X github.com/mo1ein/TelegramArchive/consts.Version={{.Version}} + -X github.com/mo1ein/TelegramArchive/consts.Commit={{.Commit}} + -X github.com/mo1ein/TelegramArchive/consts.CommitDate={{.CommitDate}} + +archives: + - formats: [tar.gz] + name_template: "{{ .ProjectName }}_{{ .Version }}_{{ .Os }}_{{ .Arch }}" + format_overrides: + - goos: windows + formats: [zip] + files: + - README.md + - LICENSE + - licenses/* + +checksum: + name_template: checksums.txt + +changelog: + disable: true diff --git a/README.md b/README.md index 497f8d6..c588890 100644 --- a/README.md +++ b/README.md @@ -16,6 +16,7 @@ Inspired by [tdl](https://github.com/iyear/tdl), ta uses its transfer and sessio - Parallel downloads with progress, resume and recovery. - Account data and Saved Messages backups. - Incremental sync, refresh and cron schedules. +- Multiple saved Telegram accounts with separate cron backups. - Offline rendering, statistics, uploads and forwarding. ## Installation @@ -79,6 +80,9 @@ Use `--output` to choose a destination. Keep the same destination and filters wh Use a separate output root for each Telegram account. Cron requires a working cron service and the `crontab` command. +See [Cron jobs for different accounts](docs/backups.md#cron-jobs-for-different-accounts) +for separate saved logins and schedules. + ## HTML preview Fictional meme demo in Telegram Desktop's export style. Profile photos added for illustration. diff --git a/cmd/account.go b/cmd/account.go index 6e9637b..1e5de5c 100644 --- a/cmd/account.go +++ b/cmd/account.go @@ -76,6 +76,7 @@ func NewAccount() *cobra.Command { } return tRun(cmd.Context(), func(ctx context.Context, c *telegram.Client, kv storage.Storage) (rerr error) { source := transport.New(ctx, c, kv, pool, threads, viper.GetDuration(consts.FlagReconnectTimeout), since, until) + source.DownloadTimeout = viper.GetDuration(flagDownloadTimeout) defer func() { rerr = errors.Join(rerr, source.Close(rerr == nil)) }() source.DownloadCustomEmoji = slices.Contains(f.media, "stickers") if err := source.Identity(ctx); err != nil { diff --git a/cmd/archive.go b/cmd/archive.go index 1c1bf5d..f726d06 100644 --- a/cmd/archive.go +++ b/cmd/archive.go @@ -8,15 +8,11 @@ import ( "slices" "strconv" "strings" - "sync" - "sync/atomic" "time" "github.com/gotd/td/telegram" "github.com/iyear/tdl/core/storage" "github.com/iyear/tdl/pkg/consts" - transferprog "github.com/iyear/tdl/pkg/prog" - "github.com/iyear/tdl/pkg/utils" "github.com/spf13/cobra" "github.com/spf13/viper" @@ -93,6 +89,7 @@ func newArchive(f *archiveFlags) *cobra.Command { return tRunArchive(cmd.Context(), f.resume, cmd.ErrOrStderr(), func(ctx context.Context, c *telegram.Client, kv storage.Storage) (rerr error) { var err error source := transport.New(ctx, c, kv, pool, threads, viper.GetDuration(consts.FlagReconnectTimeout), since, until) + source.DownloadTimeout = viper.GetDuration(flagDownloadTimeout) defer func() { rerr = errors.Join(rerr, source.Close(rerr == nil)) }() source.DownloadCustomEmoji = slices.Contains(f.media, "stickers") if err := source.Identity(ctx); err != nil { @@ -165,68 +162,25 @@ func newArchive(f *archiveFlags) *cobra.Command { for _, warning := range source.Warnings { fmt.Fprintln(cmd.ErrOrStderr(), "Discovery:", warning) } - progress := transferprog.New(utils.Byte.FormatBinaryBytes) - progress.SetOutputWriter(cmd.ErrOrStderr()) - progress.SetNumTrackersExpected(1) - tracker := transferprog.AppendTracker(progress, utils.Byte.FormatBinaryBytes, "Telegram archive", 0) - tracker.Start() - var messages, files, active atomic.Int64 - var expectedMu sync.Mutex - var expectedBytes int64 - updateMessage := func() { - tracker.UpdateMessage(fmt.Sprintf("Archive · %d messages · %d files · %d active", messages.Load(), files.Load(), active.Load())) - } - opts.Progress = func(n int) { - messages.Add(int64(n)) - updateMessage() - } - opts.OnTransfer = func(event archive.TransferEvent) { - switch event.Kind { - case archive.TransferStarted: - files.Add(1) - active.Add(1) - if event.File.Size > 0 { - expectedMu.Lock() - expectedBytes += event.File.Size - tracker.UpdateTotal(expectedBytes + 1) - expectedMu.Unlock() - } - updateMessage() - case archive.TransferProgressed: - tracker.Increment(event.Delta) - case archive.TransferFinished: - active.Add(-1) - updateMessage() - } - } - go progress.Render() - for !progress.IsRenderInProgress() { - time.Sleep(time.Millisecond) - } + progress := newBackupProgress(cmd.ErrOrStderr()) + opts.OnPlan = progress.setPlan + opts.OnTransfer = progress.transfer report, batchErr := archive.RunBatch(ctx, source, f.output, chats, opts, source.Warnings) - if len(report.Warnings) != len(source.Warnings) { + newWarnings := len(report.Warnings) != len(source.Warnings) + if newWarnings { report.Warnings = source.Warnings batchErr = errors.Join(batchErr, archive.WriteData(filepath.Join(f.output, "run-report.json"), report)) + } + resultErr := errors.Join(batchErr, err, ctx.Err()) + progress.finish(resultErr) + if newWarnings { for _, warning := range source.Warnings { fmt.Fprintln(cmd.ErrOrStderr(), "Export:", warning) } } - resultErr := errors.Join(batchErr, err) - if resultErr != nil { - tracker.MarkAsErrored() - } else { - tracker.UpdateTotal(tracker.Value()) - tracker.MarkAsDone() - } - transferprog.Wait(context.Background(), progress) - if ctx.Err() != nil { - return ctx.Err() - } for _, entry := range report.Chats { if entry.Error != "" { fmt.Fprintf(cmd.ErrOrStderr(), "%s: failed: %s\n", entry.Chat.Name, entry.Error) - } else { - fmt.Fprintf(cmd.OutOrStdout(), "%s: %d messages, %d output file(s)\n", entry.Chat.Name, entry.Stats.Messages, len(entry.Paths)) } } return resultErr @@ -242,7 +196,7 @@ func newArchive(f *archiveFlags) *cobra.Command { flags.StringSliceVar(&f.mimes, "mime", nil, "MIME filters, such as application/pdf or video/*") flags.Int64Var(&f.minFile, "min-file-size", 0, "minimum media file size in bytes (inclusive)") flags.BoolVar(&f.onlyMedia, "only-media", false, "include only messages with a file matching all download filters") - flags.StringSliceVarP(&f.chats, "chat", "c", nil, "chat usernames, joined-dialog names, URLs or IDs (repeat or comma-separate; defaults to me)") + flags.StringSliceVarP(&f.chats, "chat", "c", nil, "chat display names, @usernames, URLs or IDs (repeat or comma-separate; defaults to me)") flags.StringVar(&f.exportName, "export-name", "", "custom display name and folder label for one selected chat (defaults to its username for new folders)") flags.BoolVar(&f.all, "all", false, "archive account dialogs selected by --types") flags.StringSliceVar(&f.types, "types", []string{"personal", "bots", "groups", "channels"}, "chat types: "+strings.Join(transport.ChatTypes, ", ")) diff --git a/cmd/backup_lock.go b/cmd/backup_lock.go new file mode 100644 index 0000000..f18f614 --- /dev/null +++ b/cmd/backup_lock.go @@ -0,0 +1,43 @@ +package cmd + +import ( + "context" + "errors" + "fmt" + "io" + "path/filepath" + "time" + + bolt "go.etcd.io/bbolt" +) + +func lockBackupOutput(ctx context.Context, dir string, skipBusy bool, output io.Writer) (*bolt.DB, error) { + notified := false + for { + if err := ctx.Err(); err != nil { + return nil, err + } + lock, err := bolt.Open(filepath.Join(dir, ".backup.lock"), 0600, &bolt.Options{Timeout: 100 * time.Millisecond}) + if !errors.Is(err, bolt.ErrTimeout) { + if err != nil { + return nil, fmt.Errorf("open backup lock in %s: %w", dir, err) + } + return lock, nil + } + if skipBusy { + fmt.Fprintf(output, "Another backup is using %s; skipping this cycle.\n", dir) + return nil, nil + } + if !notified { + fmt.Fprintf(output, "Waiting for the current backup in %s to finish; Ctrl+C cancels waiting.\n", dir) + notified = true + } + timer := time.NewTimer(200 * time.Millisecond) + select { + case <-ctx.Done(): + timer.Stop() + return nil, ctx.Err() + case <-timer.C: + } + } +} diff --git a/cmd/cmd_test.go b/cmd/cmd_test.go index 9c21c52..9fb8832 100644 --- a/cmd/cmd_test.go +++ b/cmd/cmd_test.go @@ -9,12 +9,37 @@ import ( "reflect" "strings" "testing" + "time" "github.com/mo1ein/TelegramArchive/internal/archive" "github.com/spf13/cobra" "github.com/spf13/viper" ) +func TestDownloadTimeoutConfiguration(t *testing.T) { + viper.Reset() + defer viper.Reset() + t.Setenv("TA_DOWNLOAD_TIMEOUT", "") + root := New() + if got := viper.GetDuration(flagDownloadTimeout); got != 2*time.Minute { + t.Fatalf("default timeout=%s", got) + } + t.Setenv("TA_DOWNLOAD_TIMEOUT", "90s") + if got := viper.GetDuration(flagDownloadTimeout); got != 90*time.Second { + t.Fatalf("environment timeout=%s", got) + } + if err := root.PersistentFlags().Set(flagDownloadTimeout, "0"); err != nil { + t.Fatal(err) + } + if got := viper.GetDuration(flagDownloadTimeout); got != 0 { + t.Fatalf("explicit disabling did not override environment: %s", got) + } + root.SetArgs([]string{"--download-timeout=-1s", "sync", "--output", t.TempDir()}) + if err := root.ExecuteContext(context.Background()); err == nil || !strings.Contains(err.Error(), "download-timeout cannot be negative") { + t.Fatalf("invalid timeout did not fail before starting a backup: %v", err) + } +} + func TestArchiveIgnoresConfigurationFiles(t *testing.T) { viper.Reset() defer viper.Reset() diff --git a/cmd/cron.go b/cmd/cron.go index 21c3f7d..75d3294 100644 --- a/cmd/cron.go +++ b/cmd/cron.go @@ -1,10 +1,12 @@ package cmd import ( + "context" "fmt" "io" "os" "path/filepath" + "slices" "sort" "strings" "text/tabwriter" @@ -54,7 +56,8 @@ func newCron(manager managedcron.Manager, execute managedcron.Runner) *cobra.Com } fmt.Fprintf(cmd.OutOrStdout(), "Installed cron job %q: %s (cron's timezone)\nOutput: %s\nLog: %s\nTa can exit; cron will launch each backup.\n", name, expression, dir, job.Log) if runNow { - return managedcron.Run(cmd.Context(), manager.File(name), cmd.OutOrStdout(), execute) + skipBusy, _ := cmd.Flags().GetBool("skip-busy") + return managedcron.Run(cmd.Context(), manager.File(name), cmd.OutOrStdout(), cronRunWithSkipBusy(execute, cmd.Flags().Changed("skip-busy") && skipBusy)) } fmt.Fprintf(cmd.OutOrStdout(), "Run the first backup now with: ta cron run %s\n", name) return nil @@ -99,6 +102,7 @@ func newCron(manager managedcron.Manager, execute managedcron.Runner) *cobra.Com return nil }} var file string + var skipBusy bool run := &cobra.Command{Use: "run NAME", Short: "Run an installed cron backup now", Args: cobra.MaximumNArgs(1), Annotations: map[string]string{"offline": "true"}, RunE: func(cmd *cobra.Command, args []string) error { jobFile := file if jobFile != "" { @@ -114,10 +118,26 @@ func newCron(manager managedcron.Manager, execute managedcron.Runner) *cobra.Com } jobFile = manager.File(args[0]) } - return managedcron.Run(cmd.Context(), jobFile, cmd.OutOrStdout(), execute) + runner := execute + if file == "" || cmd.Flags().Changed("skip-busy") { + runner = cronRunWithSkipBusy(execute, skipBusy) + } else { + // Older saved jobs predate --skip-busy. Automatic runs must still + // skip an occupied output folder instead of building a queue. + runner = func(ctx context.Context, job managedcron.Job, output io.Writer) error { + for _, arg := range job.Arguments { + if arg == "--skip-busy" || strings.HasPrefix(arg, "--skip-busy=") { + return execute(ctx, job, output) + } + } + return cronRunWithSkipBusy(execute, true)(ctx, job, output) + } + } + return managedcron.Run(cmd.Context(), jobFile, cmd.OutOrStdout(), runner) }} run.Flags().StringVar(&file, "file", "", "saved cron job path") run.Flags().MarkHidden("file") + run.Flags().BoolVar(&skipBusy, "skip-busy", false, "skip a busy output folder instead of waiting") logs := &cobra.Command{Use: "logs NAME", Short: "Show recent output from a cron backup", Args: cobra.ExactArgs(1), Annotations: map[string]string{"offline": "true"}, RunE: func(cmd *cobra.Command, args []string) error { if err := managedcron.ValidateName(args[0]); err != nil { return err @@ -157,6 +177,16 @@ func newCron(manager managedcron.Manager, execute managedcron.Runner) *cobra.Com return group } +func cronRunWithSkipBusy(execute managedcron.Runner, skipBusy bool) managedcron.Runner { + return func(ctx context.Context, job managedcron.Job, output io.Writer) error { + args := slices.DeleteFunc(slices.Clone(job.Arguments), func(arg string) bool { + return arg == "--skip-busy" || strings.HasPrefix(arg, "--skip-busy=") + }) + job.Arguments = append(args, fmt.Sprintf("--skip-busy=%t", skipBusy)) + return execute(ctx, job, output) + } +} + // Freeze effective settings rather than relying on cron inheriting a terminal's // environment. Proxy credentials stay in the 0600 job file, not in crontab. func cronArguments(cmd *cobra.Command) ([]string, map[string]string, error) { diff --git a/cmd/cron_test.go b/cmd/cron_test.go index b975754..e1503e3 100644 --- a/cmd/cron_test.go +++ b/cmd/cron_test.go @@ -46,11 +46,18 @@ func TestCronInstallCapturesSettingsAndRunsSyncOnlyOnce(t *testing.T) { dir := t.TempDir() t.Chdir(dir) t.Setenv("TA_NS", "personal") + t.Setenv("TA_DOWNLOAD_TIMEOUT", "90s") t.Setenv("TA_PROXY", "socks5://user:private@127.0.0.1:1080") table := &testCronTable{content: "# unrelated\n0 1 * * * /usr/bin/true\n"} manager := managedcron.Manager{Directory: filepath.Join(dir, "jobs"), Table: table} calls := 0 - root := cronRoot(manager, func(ctx context.Context, job managedcron.Job, out io.Writer) error { calls++; return nil }) + root := cronRoot(manager, func(ctx context.Context, job managedcron.Job, out io.Writer) error { + calls++ + if !slices.Contains(job.Arguments, "--skip-busy=false") { + t.Fatalf("--run-now should wait for the output folder: %v", job.Arguments) + } + return nil + }) var output bytes.Buffer root.SetOut(&output) args := []string{"--storage=type=bolt,path=sessions", "cron", "add", "channel", "--chat=Private group", "--every=6h", "--media=all", "--format=both", "--output=backup", "--run-now"} @@ -74,7 +81,7 @@ func TestCronInstallCapturesSettingsAndRunsSyncOnlyOnce(t *testing.T) { if job.Environment["TA_PROXY"] != "socks5://user:private@127.0.0.1:1080" || job.Environment["ALL_PROXY"] != "" { t.Fatal("proxy snapshot was not preserved") } - for _, value := range []string{"--ns=personal", "--storage=path=" + filepath.Join(dir, "sessions") + ",type=bolt", "--output=" + filepath.Join(dir, "backup"), "--resume=true", "--chat=Private group"} { + for _, value := range []string{"--ns=personal", "--storage=path=" + filepath.Join(dir, "sessions") + ",type=bolt", "--output=" + filepath.Join(dir, "backup"), "--resume=true", "--chat=Private group", "--skip-busy=true", "--download-timeout=1m30s"} { if !slices.Contains(job.Arguments, value) { t.Fatalf("missing %s in %v", value, job.Arguments) } @@ -113,6 +120,51 @@ func TestCronInstallCapturesSettingsAndRunsSyncOnlyOnce(t *testing.T) { } } +func TestCronManualRunWaitsAndAutomaticRunSkipsBusyFolder(t *testing.T) { + for _, test := range []struct { + name, want string + args []string + legacy bool + }{ + {name: "manual", args: []string{"run", "channel"}, want: "--skip-busy=false"}, + {name: "automatic", args: []string{"run", "--file"}, want: "--skip-busy=true"}, + {name: "automatic legacy job", args: []string{"run", "--file"}, want: "--skip-busy=true", legacy: true}, + {name: "manual skip", args: []string{"run", "channel", "--skip-busy"}, want: "--skip-busy=true"}, + } { + t.Run(test.name, func(t *testing.T) { + dir := t.TempDir() + manager := managedcron.Manager{Directory: filepath.Join(dir, "jobs"), Table: &testCronTable{}} + job := managedcron.Job{Name: "channel", Schedule: "0 */6 * * *", Executable: "/usr/bin/true", Directory: dir, Arguments: []string{"sync", "--skip-busy=true"}, Log: filepath.Join(dir, "channel.log")} + if test.legacy { + job.Arguments = []string{"sync"} + } + if err := manager.Install(context.Background(), job); err != nil { + t.Fatal(err) + } + called := false + command := newCron(manager, func(ctx context.Context, job managedcron.Job, output io.Writer) error { + called = true + if !slices.Contains(job.Arguments, test.want) { + t.Fatalf("incorrect lock policy: %v", job.Arguments) + } + return nil + }) + args := slices.Clone(test.args) + if strings.HasPrefix(test.name, "automatic") { + args = append(args, manager.File(job.Name)) + } + command.SetArgs(args) + if err := command.ExecuteContext(context.Background()); err != nil || !called { + t.Fatalf("called=%v err=%v", called, err) + } + saved, err := managedcron.ReadJob(manager.File(job.Name)) + if err != nil || !slices.Equal(saved.Arguments, job.Arguments) { + t.Fatalf("manual override changed the installed job: job=%+v err=%v", saved, err) + } + }) + } +} + func TestCronRejectsInvalidSetupBeforeWriting(t *testing.T) { for _, flags := range [][]string{{"--every=90m"}, {"--every=0"}, {"--every=1s"}, {"--resume=false"}, {"--format=invalid"}, {"--runs=2"}, {"--since=invalid"}, {"--all", "--chat=someone"}} { viper.Reset() diff --git a/cmd/identity.go b/cmd/identity.go index 1718b9a..68ac419 100644 --- a/cmd/identity.go +++ b/cmd/identity.go @@ -2,6 +2,7 @@ package cmd import ( "context" + "errors" "fmt" "time" @@ -44,44 +45,74 @@ func printCurrentIdentity(cmd *cobra.Command) error { } func NewAccounts() *cobra.Command { + return newAccounts(func(ctx context.Context) ([]string, error) { + return sessionkv.From(ctx).Namespaces() + }, readSavedAccount) +} + +func newAccounts(list func(context.Context) ([]string, error), lookup func(context.Context, string) (int64, string, error)) *cobra.Command { return &cobra.Command{ Use: "accounts", Short: "List saved Telegram accounts and their namespaces", - Long: "List saved Telegram accounts. Choose one for a command with -n .", + Long: "List saved Telegram accounts. Busy sessions are marked and skipped. Choose an account with -n .", Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, _ []string) error { - namespaces, err := sessionkv.From(cmd.Context()).Namespaces() + namespaces, err := list(cmd.Context()) if err != nil { return err } selected := viper.GetString("ns") + var failures []error for _, namespace := range namespaces { - viper.Set("ns", namespace) - err := tRun(cmd.Context(), func(ctx context.Context, client *tdclient.Client, kv storage.Storage) error { - source := archiveTelegram.New(ctx, client, kv, viper.GetInt("pool"), viper.GetInt("threads"), viper.GetDuration("reconnect-timeout"), time.Time{}, time.Time{}) - defer source.Close(true) - if err := source.Identity(ctx); err != nil { - return err - } - marker := "" - if namespace == selected { - marker = " [selected]" - } - fmt.Fprintf(cmd.OutOrStdout(), "%s %d %s%s\n", namespace, source.AccountID(), usernameOrPlaceholder(source.Username()), marker) - return nil - }) + if err := cmd.Context().Err(); err != nil { + return err + } + marker := "" + if namespace == selected { + marker = " [selected]" + } + id, username, err := lookup(cmd.Context(), namespace) + if canceled := cmd.Context().Err(); canceled != nil { + return canceled + } if err != nil { - return fmt.Errorf("read account in namespace %q: %w", namespace, err) + var busy *sessionBusyError + if errors.As(err, &busy) { + fmt.Fprintf(cmd.OutOrStdout(), "%s [busy]%s\n", namespace, marker) + continue + } + fmt.Fprintf(cmd.OutOrStdout(), "%s [unavailable]%s\n", namespace, marker) + failures = append(failures, fmt.Errorf("read account in namespace %q: %w", namespace, err)) + continue } + fmt.Fprintf(cmd.OutOrStdout(), "%s %d %s%s\n", namespace, id, usernameOrPlaceholder(username), marker) } if len(namespaces) == 0 { fmt.Fprintln(cmd.OutOrStdout(), "No saved accounts. Log in with ta login -T qr.") } - return nil + return errors.Join(failures...) }, } } +func readSavedAccount(ctx context.Context, namespace string) (int64, string, error) { + selected := viper.GetString("ns") + viper.Set("ns", namespace) + defer viper.Set("ns", selected) + var id int64 + var username string + err := tRun(ctx, func(ctx context.Context, client *tdclient.Client, kv storage.Storage) error { + source := archiveTelegram.New(ctx, client, kv, viper.GetInt("pool"), viper.GetInt("threads"), viper.GetDuration("reconnect-timeout"), time.Time{}, time.Time{}) + defer source.Close(true) + if err := source.Identity(ctx); err != nil { + return err + } + id, username = source.AccountID(), source.Username() + return nil + }) + return id, username, err +} + func usernameOrPlaceholder(username string) string { if username == "" { return "(no username)" diff --git a/cmd/identity_test.go b/cmd/identity_test.go new file mode 100644 index 0000000..f7ffa4e --- /dev/null +++ b/cmd/identity_test.go @@ -0,0 +1,91 @@ +package cmd + +import ( + "bytes" + "context" + "errors" + "fmt" + "strings" + "testing" + + "github.com/iyear/tdl/core/storage" + sessionkv "github.com/iyear/tdl/pkg/kv" + "github.com/spf13/viper" + bolt "go.etcd.io/bbolt" +) + +func TestAccountsListsRemainingNamespacesWhenOneIsBusy(t *testing.T) { + viper.Reset() + defer viper.Reset() + viper.Set("ns", "default") + command := newAccounts(func(context.Context) ([]string, error) { + return []string{"default", "moein", "moein2", "moein3"}, nil + }, func(ctx context.Context, namespace string) (int64, string, error) { + if namespace == "moein2" { + return 0, "", fmt.Errorf("open session: %w", explainSessionLock(bolt.ErrTimeout, "bolt", namespace)) + } + return 579119220, "mo_ein", nil + }) + var output bytes.Buffer + command.SetOut(&output) + if err := command.ExecuteContext(context.Background()); err != nil { + t.Fatal(err) + } + text := output.String() + for _, want := range []string{"default 579119220 @mo_ein [selected]", "moein2 [busy]", "moein3 579119220 @mo_ein"} { + if !strings.Contains(text, want) { + t.Fatalf("missing %q in:\n%s", want, text) + } + } + if strings.Contains(text, "login -T") || viper.GetString("ns") != "default" { + t.Fatalf("listing changed the selected login or printed login instructions: %s", text) + } +} + +func TestAccountsReportsRealErrorsAfterListingOtherNamespaces(t *testing.T) { + failure := errors.New("authorization revoked") + command := newAccounts(func(context.Context) ([]string, error) { return []string{"expired", "usable"}, nil }, func(ctx context.Context, namespace string) (int64, string, error) { + if namespace == "expired" { + return 0, "", failure + } + return 42, "usable", nil + }) + var output bytes.Buffer + command.SetOut(&output) + err := command.ExecuteContext(context.Background()) + if !errors.Is(err, failure) || !strings.Contains(output.String(), "usable 42 @usable") || !strings.Contains(output.String(), "expired [unavailable]") { + t.Fatalf("err=%v output=%s", err, output.String()) + } +} + +func TestAccountsDoesNotContinueAfterCancellation(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + calls := 0 + command := newAccounts(func(context.Context) ([]string, error) { return []string{"first", "second"}, nil }, func(ctx context.Context, namespace string) (int64, string, error) { + calls++ + cancel() + return 0, "", ctx.Err() + }) + command.SetOut(&bytes.Buffer{}) + if err := command.ExecuteContext(ctx); !errors.Is(err, context.Canceled) || calls != 1 { + t.Fatalf("err=%v lookups=%d", err, calls) + } +} + +type busyIdentityStorage struct{ sessionkv.Storage } + +func (busyIdentityStorage) Open(namespace string) (storage.Storage, error) { + return nil, explainSessionLock(bolt.ErrTimeout, "bolt", namespace) +} + +func TestAccountLookupRestoresSelectedNamespaceAfterBusySession(t *testing.T) { + viper.Reset() + defer viper.Reset() + viper.Set("ns", "default") + ctx := sessionkv.With(context.Background(), busyIdentityStorage{}) + _, _, err := readSavedAccount(ctx, "moein2") + var busy *sessionBusyError + if !errors.As(err, &busy) || viper.GetString("ns") != "default" { + t.Fatalf("err=%v selected=%s", err, viper.GetString("ns")) + } +} diff --git a/cmd/progress.go b/cmd/progress.go new file mode 100644 index 0000000..f06ff87 --- /dev/null +++ b/cmd/progress.go @@ -0,0 +1,251 @@ +package cmd + +import ( + "fmt" + "io" + "math" + "os" + "path/filepath" + "strings" + "sync" + "time" + "unicode" + + "github.com/jedib0t/go-pretty/v6/text" + "github.com/mattn/go-runewidth" + "github.com/mo1ein/TelegramArchive/internal/archive" + "golang.org/x/term" +) + +type activeTransfer struct { + size, received int64 + order uint64 +} + +type backupProgress struct { + mu sync.Mutex + started, transferStarted time.Time + plan archive.DownloadPlan + active map[string]activeTransfer + order uint64 + bytes, completeBytes int64 + completeFiles int64 + finished bool + colorful bool + failure error + stop chan error + stopped, refresh chan struct{} +} + +func newBackupProgress(output io.Writer) *backupProgress { + p := &backupProgress{started: time.Now(), active: map[string]activeTransfer{}, stop: make(chan error), stopped: make(chan struct{}), refresh: make(chan struct{}, 1)} + fd, terminal := 0, false + if file, ok := output.(interface{ Fd() uintptr }); ok { + fd = int(file.Fd()) + terminal = term.IsTerminal(fd) + } + p.colorful = terminal && os.Getenv("NO_COLOR") == "" && os.Getenv("TERM") != "dumb" + go func() { + defer close(p.stopped) + interval := 10 * time.Second + if terminal { + interval = 100 * time.Millisecond + } + ticker := time.NewTicker(interval) + defer ticker.Stop() + drawn := false + render := func() { + width := 80 + if terminal { + if columns, _, err := term.GetSize(fd); err == nil { + width = columns + } + } + lines := p.lines(time.Now(), width) + if terminal { + if drawn { + fmt.Fprint(output, "\x1b[3A") + } + for _, line := range lines { + fmt.Fprintf(output, "\r\x1b[2K%s\n", line) + } + } else { + fmt.Fprintln(output, strings.Join(lines, " | ")) + } + drawn = true + } + render() + for { + select { + case err := <-p.stop: + p.mu.Lock() + p.finished, p.failure = true, err + p.mu.Unlock() + render() + return + case <-p.refresh: + render() + case <-ticker.C: + render() + } + } + }() + return p +} + +func (p *backupProgress) setPlan(plan archive.DownloadPlan) { + p.mu.Lock() + p.plan = plan + if plan.Ready { + p.transferStarted = time.Now() + } + p.mu.Unlock() + if plan.Ready { + select { + case p.refresh <- struct{}{}: + default: + } + } +} + +func (p *backupProgress) transfer(event archive.TransferEvent) { + p.mu.Lock() + defer p.mu.Unlock() + key := event.File.Path + t := p.active[key] + switch event.Kind { + case archive.TransferStarted: + p.order++ + t = activeTransfer{size: event.File.Size, order: p.order} + if event.File.Data != nil { + t.size = int64(len(event.File.Data)) + } + p.active[key] = t + case archive.TransferProgressed: + p.bytes += event.Delta + t.received += event.Delta + p.active[key] = t + case archive.TransferFinished: + if event.Err == nil { + p.completeFiles++ + p.completeBytes += t.received + } + delete(p.active, key) + } +} + +func (p *backupProgress) finish(err error) { + p.stop <- err + <-p.stopped +} + +func (p *backupProgress) lines(now time.Time, width int) []string { + p.mu.Lock() + defer p.mu.Unlock() + paint := func(color text.Color, value string) string { + if p.colorful { + return color.Sprint(value) + } + return value + } + label := "Scanning chat history" + if p.plan.Chat != "" { + label = "Scanning " + p.plan.Chat + } + percent, completed := 0.0, float64(p.completeBytes) + var latest uint64 + for path, file := range p.active { + completed += float64(min(file.received, max(0, file.size))) + if file.order > latest { + label, latest = filepath.Base(path), file.order + } + } + if p.plan.Ready { + if latest == 0 { + label = "Preparing next file" + if p.completeFiles >= p.plan.Files { + label = "Finishing backup" + } + } + if p.plan.UnknownFiles > 0 { + completed = float64(p.completeFiles) + percent = completed / float64(max(1, p.plan.Files)) * 100 + } else if p.plan.Bytes > 0 { + percent = completed / float64(p.plan.Bytes) * 100 + } + } + percent = min(99.9, max(0, percent)) + if p.finished { + label = "Backup complete" + if p.failure != nil { + label = "Backup failed" + } else { + percent = 100 + } + } + elapsed := max(0, now.Sub(p.started)) + transferTime := now.Sub(p.transferStarted).Seconds() + speed := 0.0 + if !p.transferStarted.IsZero() && transferTime > 0 { + speed = float64(p.bytes) / transferTime + } + eta := "--" + if percent > 0 && percent < 100 && !p.transferStarted.IsZero() { + eta = (time.Duration(transferTime*(100-percent)/percent) * time.Second).String() + } + if p.finished && p.failure == nil { + eta = "0s" + } + size := formatProgressBytes(p.bytes) + if p.plan.Ready && p.plan.UnknownFiles == 0 { + size += " / " + formatProgressBytes(p.plan.Bytes) + } + metrics := paint(text.FgGreen, fmt.Sprintf("Elapsed %s · ETA %s", elapsed.Round(time.Second), eta)) + + " · " + paint(text.FgMagenta, formatProgressBytes(int64(speed))+"/s") + if !p.plan.Ready { + size = formatProgressBytes(p.plan.Bytes) + " found" + metrics = paint(text.FgGreen, fmt.Sprintf("Elapsed %s", elapsed.Round(time.Second))) + + " · " + paint(text.FgCyan, fmt.Sprintf("%d messages scanned · %d files found", p.plan.Messages, p.plan.Files)) + } + barWidth := max(3, min(32, width-runewidth.StringWidth(size)-13)) + fill := int(math.Floor(float64(barWidth) * percent / 100)) + percentage := fmt.Sprintf("%5.1f%%", percent) + if !p.plan.Ready && !p.finished { + percentage = " --" + } + bar := paint(text.FgYellow, "["+strings.Repeat("#", fill)+strings.Repeat(".", barWidth-fill)+"]") + + " " + paint(text.FgHiRed, percentage) + " " + paint(text.FgCyan, size) + label = strings.Map(func(r rune) rune { + if unicode.IsControl(r) { + return -1 + } + return r + }, label) + labelColor := text.FgBlue + if p.finished { + labelColor = text.FgGreen + if p.failure != nil { + labelColor = text.FgRed + } + } + limit := max(1, width-1) + return []string{ + paint(labelColor, runewidth.Truncate(label, limit, "…")), + text.Snip(bar, limit, "…"), + text.Snip(metrics, limit, "…"), + } +} + +func formatProgressBytes(bytes int64) string { + if bytes < 1024 { + return fmt.Sprintf("%d B", bytes) + } + value := float64(bytes) + for _, unit := range []string{"KiB", "MiB", "GiB", "TiB"} { + value /= 1024 + if value < 1024 || unit == "TiB" { + return fmt.Sprintf("%.1f %s", value, unit) + } + } + return "" +} diff --git a/cmd/progress_test.go b/cmd/progress_test.go new file mode 100644 index 0000000..4477695 --- /dev/null +++ b/cmd/progress_test.go @@ -0,0 +1,113 @@ +package cmd + +import ( + "bytes" + "context" + "errors" + "strings" + "testing" + "time" + + "github.com/mattn/go-runewidth" + "github.com/mo1ein/TelegramArchive/internal/archive" +) + +func TestBackupProgressShowsOneOverallBarAndCurrentFile(t *testing.T) { + start := time.Now().Add(-10 * time.Second) + p := &backupProgress{started: start, transferStarted: start, active: map[string]activeTransfer{}} + p.setPlan(archive.DownloadPlan{Ready: true, Bytes: 100, Files: 2}) + p.transferStarted = start + first := archive.File{Path: "files/first.zip", Size: 40} + second := archive.File{Path: "files/second.mp4", Size: 60} + p.transfer(archive.TransferEvent{Kind: archive.TransferStarted, File: first}) + p.transfer(archive.TransferEvent{Kind: archive.TransferProgressed, File: first, Delta: 20}) + p.transfer(archive.TransferEvent{Kind: archive.TransferStarted, File: second}) + p.transfer(archive.TransferEvent{Kind: archive.TransferProgressed, File: second, Delta: 10}) + text := strings.Join(p.lines(start.Add(10*time.Second), 80), "\n") + for _, want := range []string{"second.mp4", "30.0%", "30 B / 100 B", "Elapsed", "ETA", "/s"} { + if !strings.Contains(text, want) { + t.Fatalf("missing %q in:\n%s", want, text) + } + } + if strings.Count(text, "[") != 1 || strings.Contains(text, "messages") || strings.Contains(text, "active") { + t.Fatalf("noisy or duplicate progress:\n%s", text) + } + p.transfer(archive.TransferEvent{Kind: archive.TransferFinished, File: second}) + if got := p.lines(start.Add(10*time.Second), 80)[0]; got != "first.zip" { + t.Fatalf("completed filename remained visible: %s", got) + } +} + +func TestBackupProgressShowsHistoryScanWork(t *testing.T) { + start := time.Now() + p := &backupProgress{started: start, active: map[string]activeTransfer{}} + p.setPlan(archive.DownloadPlan{Chat: "Fadi", Messages: 23500, Files: 900, Bytes: 1024 * 1024 * 1024}) + output := strings.Join(p.lines(start.Add(3*time.Minute), 80), "\n") + for _, want := range []string{"Scanning Fadi", "23500 messages scanned", "900 files found", "1.0 GiB found", "Elapsed 3m0s"} { + if !strings.Contains(output, want) { + t.Fatalf("missing %q in preparation:\n%s", want, output) + } + } + if strings.Count(output, "[") != 1 || strings.Contains(output, "%") || strings.Contains(output, "ETA") || strings.Contains(output, "/s") { + t.Fatalf("history scan invented download progress:\n%s", output) + } + // Chat titles are untrusted, just like filenames. + p.setPlan(archive.DownloadPlan{Chat: "Fadi\n\x1b[31m" + strings.Repeat("名字", 30)}) + for _, line := range p.lines(start, 40) { + if runewidth.StringWidth(line) >= 40 || strings.ContainsAny(line, "\n\r\x1b") { + t.Fatalf("unsafe or overflowing preparation: %q", line) + } + } +} + +func TestBackupProgressFinishesOnlyAfterArchiveSucceeds(t *testing.T) { + start := time.Now() + p := &backupProgress{started: start, active: map[string]activeTransfer{}} + p.setPlan(archive.DownloadPlan{Ready: true, Bytes: 4, Files: 1}) + file := archive.File{Path: "files/one.zip", Size: 4} + p.transfer(archive.TransferEvent{Kind: archive.TransferStarted, File: file}) + p.transfer(archive.TransferEvent{Kind: archive.TransferProgressed, File: file, Delta: 4}) + p.transfer(archive.TransferEvent{Kind: archive.TransferFinished, File: file}) + if text := strings.Join(p.lines(start.Add(time.Second), 80), "\n"); strings.Contains(text, "100.0%") { + t.Fatalf("reported completion before rendering finished: %s", text) + } + p.finished, p.failure = true, errors.New("render failed") + if text := strings.Join(p.lines(start.Add(time.Second), 80), "\n"); !strings.Contains(text, "failed") || strings.Contains(text, "100.0%") { + t.Fatalf("failure reported success: %s", text) + } + p.failure = nil + if text := strings.Join(p.lines(start.Add(time.Second), 80), "\n"); !strings.Contains(text, "100.0%") { + t.Fatalf("missing completion: %s", text) + } +} + +func TestBackupProgressFitsNarrowTerminalsAndSanitizesFilenames(t *testing.T) { + p := &backupProgress{started: time.Now(), active: map[string]activeTransfer{}} + if text := strings.Join(p.lines(time.Now(), 40), "\n"); strings.Contains(text, "%") || !strings.Contains(text, "Scanning") { + t.Fatalf("preparation invented a percentage: %s", text) + } + p.setPlan(archive.DownloadPlan{Ready: true, Files: 1, UnknownFiles: 1}) + p.transfer(archive.TransferEvent{Kind: archive.TransferStarted, File: archive.File{Path: "files/خیلی_طولانی_" + strings.Repeat("名字", 30) + "\n\x1b[31m.zip"}}) + for _, line := range p.lines(time.Now(), 40) { + if runewidth.StringWidth(line) >= 40 || strings.ContainsAny(line, "\n\r\x1b") { + t.Fatalf("unsafe or overflowing progress line: %q", line) + } + } +} + +func TestBackupProgressRunsWithArchiveAndWritesPlainLogs(t *testing.T) { + var output bytes.Buffer + progress := newBackupProgress(&output) + source := &reconnectArchiveSource{downloads: map[string]int{}} + _, err := archive.RunBatch(context.Background(), source, t.TempDir(), []archive.Chat{{ID: 1, Key: "user_1"}}, archive.Options{ + Concurrency: 1, Media: []string{"videos"}, OnPlan: progress.setPlan, OnTransfer: progress.transfer, + }, nil) + progress.finish(err) + if err != nil { + t.Fatal(err) + } + text := output.String() + if strings.Contains(text, "\x1b") || strings.Count(text, "100.0%") != 1 || !strings.Contains(text, "16 B / 16 B") { + t.Fatalf("invalid progress log:\n%s", text) + } +} diff --git a/cmd/root.go b/cmd/root.go index e886535..4fcc36b 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -1,8 +1,11 @@ package cmd import ( + "fmt" + upstreamcmd "github.com/iyear/tdl/cmd" sessionkv "github.com/iyear/tdl/pkg/kv" + transport "github.com/mo1ein/TelegramArchive/internal/telegram" "github.com/spf13/cobra" "github.com/spf13/viper" ) @@ -14,6 +17,8 @@ func New() *cobra.Command { root.Use = "ta" root.Short = "Back up Telegram chats and account data as JSON or offline HTML" root.Version = version() + root.PersistentFlags().Duration(flagDownloadTimeout, transport.DefaultDownloadTimeout, "inactivity limit for archive history reads and media transfers; 0 disables") + _ = viper.BindPFlag(flagDownloadTimeout, root.PersistentFlags().Lookup(flagDownloadTimeout)) for _, command := range root.Commands() { if command.Name() == "version" || command.Name() == "recover" { root.RemoveCommand(command) @@ -27,6 +32,9 @@ func New() *cobra.Command { wrapLoginIdentity(root) pre, post := root.PersistentPreRunE, root.PersistentPostRunE root.PersistentPreRunE = func(cmd *cobra.Command, args []string) error { + if viper.GetDuration(flagDownloadTimeout) < 0 { + return fmt.Errorf("download-timeout cannot be negative") + } if cmd.Name() == "stats" || cmd.Annotations["offline"] == "true" { return nil } diff --git a/cmd/sync.go b/cmd/sync.go index 5d46a27..2b1a6d5 100644 --- a/cmd/sync.go +++ b/cmd/sync.go @@ -14,7 +14,6 @@ import ( transport "github.com/mo1ein/TelegramArchive/internal/telegram" "github.com/spf13/cobra" "github.com/spf13/pflag" - bolt "go.etcd.io/bbolt" ) type backupComponent struct { @@ -47,10 +46,10 @@ func newSyncPlan(run childRunner, planned func(*cobra.Command, string, schedule. cmd.Short = "Sync selected Telegram data once or on a recurring interval" cmd.Long = "Back up selected Telegram content, merging new messages into existing archives.\nAccount data and Saved Messages stay in a separate directory.\nAdd --every to repeat; use --refresh to update older message edits too." cmd.Annotations = map[string]string{"offline": "true"} - cmd.Flags().Lookup("chat").Usage = "explicit chat usernames, URLs or IDs; defaults to all matching chats" + cmd.Flags().Lookup("chat").Usage = "chat display names, usernames, URLs or IDs; defaults to all matching chats" cmd.Flags().Lookup("takeout").Usage = "use bulk export sessions; account sections use takeout by default" cmd.Example = " ta sync --everything --every 6h --format both\n ta sync --all --types channels --media all --every 1h" - var everything, account bool + var everything, account, skipBusy bool var chats bool var include []string var timing schedule.Options @@ -62,6 +61,7 @@ func newSyncPlan(run childRunner, planned func(*cobra.Command, string, schedule. cmd.Flags().IntVar(&timing.Runs, "runs", 0, "number of recurring cycles; 0 keeps running") cmd.Flags().DurationVar(&timing.Timeout, "job-timeout", 0, "maximum duration per entire backup cycle") cmd.Flags().BoolVar(&timing.StopOnError, "stop-on-error", false, "stop recurring backups after a failed cycle") + cmd.Flags().BoolVar(&skipBusy, "skip-busy", false, "skip a busy output folder instead of waiting (automatic for recurring runs)") cmd.RunE = func(cmd *cobra.Command, _ []string) error { if !cmd.Flags().Changed("all") && !cmd.Flags().Changed("chat") { cmd.Flags().Set("all", "true") @@ -88,6 +88,9 @@ func newSyncPlan(run childRunner, planned func(*cobra.Command, string, schedule. if timing.Every > 0 && !f.resume { return fmt.Errorf("recurring backups require --resume=true to sync existing archives") } + if timing.Every > 0 && !cmd.Flags().Changed("skip-busy") { + skipBusy = true + } if len(include) != 1 || include[0] != "all" { if len(include) == 0 { return fmt.Errorf("select at least one account section") @@ -135,23 +138,23 @@ func newSyncPlan(run childRunner, planned func(*cobra.Command, string, schedule. } setScheduleLogging(cmd, &timing) return schedule.Run(cmd.Context(), timing, func(ctx context.Context) error { - return runBackupCycle(ctx, cmd, dir, commands, run) + return runBackupCycle(ctx, cmd, dir, commands, run, skipBusy) }) } return cmd } -func runBackupCycle(ctx context.Context, cmd *cobra.Command, dir string, commands [][]string, run childRunner) error { +func runBackupCycle(ctx context.Context, cmd *cobra.Command, dir string, commands [][]string, run childRunner, skipBusy bool) error { if err := os.MkdirAll(dir, 0700); err != nil { return err } - lock, err := bolt.Open(filepath.Join(dir, ".backup.lock"), 0600, &bolt.Options{Timeout: 100 * time.Millisecond}) - if errors.Is(err, bolt.ErrTimeout) { - return fmt.Errorf("another backup is using %s; retry after it finishes", dir) - } + lock, err := lockBackupOutput(ctx, dir, skipBusy, cmd.ErrOrStderr()) if err != nil { return err } + if lock == nil { + return nil + } defer lock.Close() report := backupReport{Started: time.Now().UTC(), Status: "running"} path := filepath.Join(dir, "backup-report.json") diff --git a/cmd/sync_test.go b/cmd/sync_test.go index dbd84da..add7fb0 100644 --- a/cmd/sync_test.go +++ b/cmd/sync_test.go @@ -1,6 +1,7 @@ package cmd import ( + "bytes" "context" "encoding/json" "errors" @@ -9,6 +10,7 @@ import ( "slices" "strings" "testing" + "time" "github.com/spf13/cobra" ) @@ -68,9 +70,17 @@ func TestRecurringBackupDefaultsToIncrementalAndDoesNotOverlap(t *testing.T) { t.Fatal("overlapping backup was started") return nil }) - other.SetArgs([]string{"--output", dir}) - if err := other.ExecuteContext(ctx); err == nil || !strings.Contains(err.Error(), "another backup") { - t.Fatalf("missing cross-process lock: %v", err) + previous, err := os.ReadFile(filepath.Join(dir, "backup-report.json")) + if err != nil { + t.Fatal(err) + } + other.SetArgs([]string{"--output", dir, "--skip-busy"}) + if err := other.ExecuteContext(ctx); err != nil { + t.Fatalf("busy cycle was not skipped: %v", err) + } + current, err := os.ReadFile(filepath.Join(dir, "backup-report.json")) + if err != nil || !bytes.Equal(previous, current) { + t.Fatalf("skipped cycle changed the active backup report: %v", err) } return nil }) @@ -83,6 +93,74 @@ func TestRecurringBackupDefaultsToIncrementalAndDoesNotOverlap(t *testing.T) { } } +func TestBackupLockErrorsAreNotReportedAsContention(t *testing.T) { + dir := t.TempDir() + if err := os.Mkdir(filepath.Join(dir, ".backup.lock"), 0700); err != nil { + t.Fatal(err) + } + command := newSync(func(context.Context, *cobra.Command, []string) error { + t.Fatal("backup ran without a lock") + return nil + }) + var output bytes.Buffer + command.SetErr(&output) + command.SetArgs([]string{"--output", dir}) + if err := command.ExecuteContext(context.Background()); err == nil || strings.Contains(output.String(), "Waiting") { + t.Fatalf("storage failure treated as contention: err=%v log=%s", err, output.String()) + } +} + +func TestManualSyncWaitsForBusyOutputAndHonorsCancellation(t *testing.T) { + for _, cancelWaiting := range []bool{false, true} { + t.Run(map[bool]string{false: "wait then run", true: "cancel waiting"}[cancelWaiting], func(t *testing.T) { + dir := t.TempDir() + started, release := make(chan struct{}), make(chan struct{}) + firstDone := make(chan error, 1) + first := newSync(func(context.Context, *cobra.Command, []string) error { + close(started) + <-release + return nil + }) + first.SetArgs([]string{"--output", dir}) + go func() { firstDone <- first.ExecuteContext(context.Background()) }() + <-started + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + called := make(chan struct{}, 1) + second := newSync(func(context.Context, *cobra.Command, []string) error { called <- struct{}{}; return nil }) + var log bytes.Buffer + second.SetErr(&log) + second.SetArgs([]string{"--output", dir}) + secondDone := make(chan error, 1) + go func() { secondDone <- second.ExecuteContext(ctx) }() + select { + case err := <-secondDone: + close(release) + <-firstDone + t.Fatalf("manual sync did not wait: %v", err) + case <-called: + t.Fatal("overlapping sync started") + case <-time.After(200 * time.Millisecond): + } + if cancelWaiting { + cancel() + } + close(release) + if err := <-firstDone; err != nil { + t.Fatal(err) + } + err := <-secondDone + if cancelWaiting { + if !errors.Is(err, context.Canceled) || len(called) != 0 { + t.Fatalf("waiting did not cancel: err=%v calls=%d", err, len(called)) + } + } else if err != nil || len(called) != 1 || !strings.Contains(log.String(), "Waiting") { + t.Fatalf("wait did not resume cleanly: err=%v calls=%d log=%s", err, len(called), log.String()) + } + }) + } +} + func TestBackupValidatesBeforeStartingAndPreservesInheritedFlags(t *testing.T) { for _, args := range [][]string{ {"--every=-1s"}, {"--every=1s", "--resume=false"}, {"--account-include=typo"}, {"--everything", "--chat=someone"}, diff --git a/cmd/telegram.go b/cmd/telegram.go index debf3f5..c01ff5c 100644 --- a/cmd/telegram.go +++ b/cmd/telegram.go @@ -18,11 +18,14 @@ import ( "github.com/iyear/tdl/pkg/consts" "github.com/iyear/tdl/pkg/kv" "github.com/iyear/tdl/pkg/tclient" + transport "github.com/mo1ein/TelegramArchive/internal/telegram" "github.com/spf13/viper" ) const maxArchiveReconnects = 5 +const flagDownloadTimeout = "download-timeout" + // A dead gotd client cannot be reused. Recreate the client and transport pools; // the archive callback resumes its on-disk checkpoints with fresh file references. func tRunArchive(ctx context.Context, resume bool, output io.Writer, f func(context.Context, *telegram.Client, storage.Storage) error) error { @@ -35,7 +38,6 @@ func tRunArchive(ctx context.Context, resume bool, output io.Writer, f func(cont retries := uint64(0) if resume { retries = maxArchiveReconnects - fmt.Fprintf(output, "Automatic connection recovery enabled (up to %d reconnects); completed media will be reused.\n", retries) } attempt := 0 return retryTelegram(ctx, backoff.WithMaxRetries(policy, retries), func() error { @@ -108,7 +110,7 @@ func tRun(ctx context.Context, f func(context.Context, *telegram.Client, storage return fmt.Errorf("open session: %w", err) } proxyURL := telegramProxy() - c, err := tclient.New(ctx, tclient.Options{KV: kvd, Proxy: proxyURL, NTP: viper.GetString(consts.FlagNTP), ReconnectTimeout: viper.GetDuration(consts.FlagReconnectTimeout)}, false) + c, err := tclient.New(ctx, tclient.Options{KV: kvd, Proxy: proxyURL, NTP: viper.GetString(consts.FlagNTP), ReconnectTimeout: viper.GetDuration(consts.FlagReconnectTimeout)}, false, transport.DownloadActivityMiddleware()) if err != nil { return err } diff --git a/cmd/telegram_test.go b/cmd/telegram_test.go index a16500a..253bdac 100644 --- a/cmd/telegram_test.go +++ b/cmd/telegram_test.go @@ -19,11 +19,13 @@ import ( "github.com/gotd/td/tdsync" "github.com/gotd/td/tgerr" "github.com/mo1ein/TelegramArchive/internal/archive" + transport "github.com/mo1ein/TelegramArchive/internal/telegram" "go.uber.org/zap" ) func TestRetryTelegramTransportFailures(t *testing.T) { for _, failure := range []error{ + &transport.DownloadStalledError{Path: "video_files/thumbnail.jpg", IdleTimeout: time.Minute}, fmt.Errorf("group: task readLoop: read intermediate: read length: %w", io.EOF), io.ErrUnexpectedEOF, io.ErrClosedPipe, diff --git a/docs/archiving.md b/docs/archiving.md index 3e2c43e..d7d6947 100644 --- a/docs/archiving.md +++ b/docs/archiving.md @@ -36,15 +36,19 @@ Checkpoints verify the logged-in account. Use a separate output root for each ac ## Archive chats and media `archive` defaults to Saved Messages (`me`), JSON, photos and `--resume=true`. -Choose chats by username, Telegram URL, ID or a joined group/channel name. +Choose chats by displayed name, username, Telegram URL or ID. Repeat `--chat` or separate values with commas. ```sh # Usernames and Saved Messages. ta archive --chat me,telegram --media all -# Private groups work by name. Use ta chat ls to find their IDs. +# People and private groups work by their displayed chat name. +ta archive --chat "mammad" --media all ta archive --chat "Book Club" --media all +# An @ prefix explicitly selects a username instead of a displayed name. +ta archive --chat "@mammad" --media all +# Use ta chat ls to find chat IDs. ta archive --chat=-1001234567890 --media none # Custom display name and folder label for one chat. @@ -71,8 +75,12 @@ ta archive --chat me --since 2026-01-01 --until 2026-02-01 \ ta --proxy socks5://127.0.0.1:1080 -n personal archive --chat me ``` -Name matching ignores case and searches main and archived dialogs. -Use a numeric ID when several chats share a name. `ta chat ls` lists names and IDs. +Name matching ignores case and extra spaces and searches main and archived chats, +including personal conversations. Bare names first match the full displayed chat +name, then fall back to usernames if no displayed name matches. Prefix a username +with `@`, or use a Telegram URL, to select it explicitly. +When several chats share a displayed name, ta lists their IDs and asks you to +choose an ID or `@username`. `ta chat ls` lists names and IDs. `--export-name` changes the display name and folder label for one chat. The original username stays in `archive-metadata.json`. This option does not anonymize the backup. @@ -104,7 +112,9 @@ That history gets a separate linked folder with its original IDs. `--include-left --all --takeout` also looks for left channels. Telegram may restrict these to your own messages; the export records that limit. -A failed chat does not stop the others. `run-report.json` lists results and discovery warnings. +A failed chat does not stop the others. With resume enabled, a stalled transfer +returns early so ta can recreate the connection before continuing other chats. +`run-report.json` lists results and discovery warnings. The command returns a nonzero exit status if any chat fails. ## Resume, refresh and speed @@ -135,6 +145,15 @@ Published files remain available until their replacements are ready. With resume enabled, `archive` retries dropped connections up to five times. Each fresh session fetches new file references and reuses completed work. +History pages and media requests that stop responding also trigger this recovery +after two minutes without data or a server response. This includes connecting to +a media data center. +Successful responses and downloaded chunks reset the inactivity timer; Telegram's +explicit flood waits extend it. Set `--download-timeout 5m` for a longer limit or +`--download-timeout 0` to disable it. The timer does not limit the total duration of +a healthy download or history scan; each history page gets a fresh timer. +A running cron process uses the version it started with; +restart a stalled run after upgrading to enable this behavior. Ctrl+C, authorization errors and local file errors stop the run. `--resume=false` disables these session retries. @@ -150,7 +169,38 @@ ta reads history in pages of 100 messages. Downloads run in parallel: ta -l 4 -t 4 --pool 8 archive --chat me --media all ``` -The progress bar shows transferred bytes, processed messages and active downloads. +Before downloading, ta scans the pending history across all selected chats to +calculate the total download size. Completed local files and excluded media do +not count toward the remaining work. This preparation adds a history scan before +downloads start; it does not download media twice. A large first backup can spend +several minutes here. During this scan, progress shows the current chat, messages +scanned, files found and pending bytes found: + +```text +Scanning Fadi +[................................] -- 1.0 GiB found +Elapsed 3m0s · 23500 messages scanned · 900 files found +``` + +The byte count grows as more pending files are found. Download percentage, speed +and ETA appear after the scan completes and the total size is known. Incremental +backups scan new or unfinished history; `--refresh` also revisits older messages. + +One progress bar covers the entire selected chat backup. It shows a current +download's filename, downloaded/total bytes, speed, elapsed time and ETA: + +```text +123_document.pdf +[############....................] 38.0% 114 MiB / 300 MiB +Elapsed 28s · ETA 46s · 4.1 MiB/s +``` + +With parallel downloads, the filename is the most recently started file that is +still downloading. The bar reaches 100% after the archive output is written. +Messages arriving after preparation are left for the next sync. If Telegram does +not report a file size, progress uses completed files and omits the total byte +size. Cron and redirected output receive periodic plain text updates. + History stays on disk; output streams in date order. Memory holds a history page, transfer buffers and statistics maps. Account photo, story and contact lists keep their metadata in memory. diff --git a/docs/backups.md b/docs/backups.md index 4b729b5..aca37ad 100644 --- a/docs/backups.md +++ b/docs/backups.md @@ -61,8 +61,11 @@ ta cron remove my-channel `cron add` installs or updates a named job in your user crontab. Other cron entries stay intact. Each trigger runs one incremental `sync` and exits. You can close ta between runs. -`--run-now` starts the first backup immediately; omit it to install and exit. -A trigger is skipped while the same job is running. Failed jobs retry at the next scheduled time. +`--run-now` starts the first backup after installation; omit it to install and exit. +If another backup is using the same output folder, `--run-now` and `ta cron run NAME` +wait for it to finish. Ctrl+C cancels waiting and keeps the installed cron job. +Automatic cron runs skip a busy output folder, and triggers are also skipped while +the same job is running. Failed jobs retry at the next scheduled time. `--every 6h` means 00:00, 06:00, 12:00 and 18:00 in cron's timezone. Use whole minutes that divide an hour, or whole hours that divide a day. @@ -75,6 +78,34 @@ Keep the binary and working directory in place. Removing a job keeps its archive For several channels on one account, use one job with `--chat first,second` or `--all --types channels`. Concurrent jobs need separate saved logins and output roots. +#### Cron jobs for different accounts + +Use a separate saved login namespace (`-n`) for each Telegram account. +Each cron job saves its selected namespace, so jobs for different accounts can run independently. + +```sh +# List existing accounts and namespaces. +ta accounts + +# Log in once per account; scan each QR with the matching Telegram account. +ta -n account1 login -T qr +ta -n account2 login -T qr + +# Schedule one chat from each account with different job names and output roots. +ta -n account1 cron add account1-chat --chat "first_channel" --every 6h \ + --media all --format both --output "$HOME/backups/account1" + +ta -n account2 cron add account2-chat --chat "second_channel" --every 6h \ + --media all --format both --output "$HOME/backups/account2" + +ta cron list +``` + +Replace `first_channel` and `second_channel` with the desired chat usernames, URLs or IDs. +If an account is already saved under `default`, use `-n default` for its job and skip that login step. +Job names are shared across namespaces: reusing a name updates the existing job. +Keep a separate output root for each account. Add `--run-now` to also start a backup immediately. + ### Foreground sync `sync` runs once unless you add `--every`. With an interval, keep the process running. @@ -113,7 +144,12 @@ Unchanged chats reuse their JSON, HTML and statistics. Each cycle runs chats first, then account sections. A failed chat phase does not prevent the account phase. `backup-report.json` records the latest cycle. Per-chat and account reports provide the details. -An output-root lock prevents overlapping syncs. +An output-root lock prevents overlapping syncs, even with separate login namespaces. +One-time syncs wait for a busy output folder; recurring syncs skip the busy cycle +by default. `--skip-busy` makes a one-time sync skip too; `--skip-busy=false` +makes recurring runs wait. `--job-timeout` also limits time spent waiting. +The `.backup.lock` file remains between runs; its presence does not mean a backup +is active. The operating system releases the lock when the process exits. The login is released between phases and while waiting. Failed cycles retry at the next interval. Missed intervals are skipped. Ctrl+C or SIGTERM cancels the current cycle; restarting continues from checkpoints. diff --git a/docs/configuration.md b/docs/configuration.md index 6bd9294..047d7e0 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -18,6 +18,16 @@ ta -n work login -T qr ``` `accounts` lists saved namespaces, account IDs and usernames. +Sessions already used by another process appear as `[busy]`; the command keeps +listing the remaining namespaces. Other account errors appear as `[unavailable]` +and are reported after the list. An active session's identity becomes available +when its current command finishes. + +Different namespaces can log in to the same Telegram account. Matching account +IDs mean the same account, even when the namespace names differ. Existing archives +belong to the recorded Telegram account ID; use that account to resume them or +choose a separate output folder for another account. + Login also prints your account ID and username. Choose QR, phone/code or Desktop session import with `-T`. Fresh sessions and logs go under `~/.ta/`. Existing ta session stores are reused. Commands accept flags and exported `TA_*` settings. Explicit flags take priority. diff --git a/docs/global-options.md b/docs/global-options.md index c0e670e..3e28267 100644 --- a/docs/global-options.md +++ b/docs/global-options.md @@ -56,6 +56,7 @@ See [session backup and recovery](session-tools.md) to move saved logins. | `--pool` | `8` | Connections per Telegram data center | | `--delay` | `0s` | Pause between tasks | | `--reconnect-timeout` | `5m` | Reconnection backoff limit; `0` removes this time limit | +| `--download-timeout` | `2m` | Inactivity limit for archive history reads and archive/account media transfers; `0` disables. Telegram flood waits extend the deadline. | | `--ntp` | Empty | Optional time server; empty uses the system clock | | `--debug` | `false` | Diagnostic logging | | `--disable-progress-ps` | `false` | Hide CPU/memory statistics in the progress display | @@ -85,6 +86,7 @@ ta --disable-progress-ps dl -f ta-export.json | `TA_DELAY` | `--delay` | | `TA_NTP` | `--ntp` | | `TA_RECONNECT_TIMEOUT` | `--reconnect-timeout` | +| `TA_DOWNLOAD_TIMEOUT` | `--download-timeout` | | `TA_DISABLE_PROGRESS_PS` | `--disable-progress-ps` | | `TA_TEMPLATE` | Download `--template` | diff --git a/install.sh b/install.sh new file mode 100644 index 0000000..26a8067 --- /dev/null +++ b/install.sh @@ -0,0 +1,83 @@ +#!/bin/sh +set -eu + +fail() { printf 'ta install: %s\n' "$*" >&2; exit 1; } + +install_dir=${HOME:?HOME is not set}/.local/bin +version=latest +while [ "$#" -gt 0 ]; do + case "$1" in + --dir|--version) + option=$1 + [ "$#" -ge 2 ] && [ -n "$2" ] || fail "$option requires a value" + case "$option" in --dir) install_dir=$2;; --version) version=$2;; esac + shift 2;; + -h|--help) + printf 'Usage: sh install.sh [--dir DIRECTORY] [--version vX.Y.Z]\nInstalls ta in ~/.local/bin by default.\n' + exit 0;; + *) fail "unknown option: $1";; + esac +done + +case "$(uname -s)" in + Linux) platform=linux;; + Darwin) platform=darwin;; + *) fail 'unsupported operating system; download a binary from GitHub Releases';; +esac +case "$(uname -m)" in + x86_64|amd64) arch=amd64;; + aarch64|arm64) arch=arm64;; + *) fail 'unsupported architecture; use go install or build from source';; +esac +for tool in curl tar awk grep install; do + command -v "$tool" >/dev/null 2>&1 || fail "$tool is required" +done +if command -v sha256sum >/dev/null 2>&1; then + hash_tool=sha256sum +elif command -v shasum >/dev/null 2>&1; then + hash_tool=shasum +else + fail 'sha256sum or shasum is required' +fi + +releases=https://github.com/mo1ein/TelegramArchive/releases +if [ "$version" = latest ]; then + release_url=$(curl --fail --silent --show-error --location --proto '=https' --proto-redir '=https' \ + --connect-timeout 15 --output /dev/null --write-out '%{url_effective}' "$releases/latest") \ + || fail 'cannot find the latest release; check GitHub Releases or install from source' + version=${release_url##*/} +fi +printf '%s\n' "$version" | grep -Eq '^v[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?$' \ + || fail "invalid version: $version (expected vX.Y.Z)" + +archive=ta_${version#v}_${platform}_${arch}.tar.gz +tmp_dir=$(mktemp -d "${TMPDIR:-/tmp}/ta-install.XXXXXX") +trap 'rm -rf "$tmp_dir"' 0 +trap 'exit 1' 1 2 15 +download() { + curl --fail --silent --show-error --location --proto '=https' --proto-redir '=https' \ + --retry 3 --connect-timeout 15 --output "$2" "$1" +} +printf 'Downloading ta %s for %s/%s...\n' "$version" "$platform" "$arch" +download "$releases/download/$version/$archive" "$tmp_dir/$archive" \ + || fail 'binary download failed; check the release version and your connection' +download "$releases/download/$version/checksums.txt" "$tmp_dir/checksums.txt" \ + || fail 'checksum download failed' +expected=$(awk -v name="$archive" '$2 == name {print $1}' "$tmp_dir/checksums.txt") +[ "${#expected}" -eq 64 ] || fail 'missing or invalid checksum' +case "$expected" in *[!0-9a-f]*) fail 'missing or invalid checksum';; esac +if [ "$hash_tool" = sha256sum ]; then + actual=$(sha256sum "$tmp_dir/$archive" | awk '{print $1}') +else + actual=$(shasum -a 256 "$tmp_dir/$archive" | awk '{print $1}') +fi +[ "$actual" = "$expected" ] || fail 'checksum mismatch; existing installation was not changed' + +tar -xzf "$tmp_dir/$archive" -C "$tmp_dir" ta +mkdir -p "$install_dir" +install -m 755 "$tmp_dir/ta" "$install_dir/ta" +printf 'Installed ta %s to %s/ta\n' "$version" "$install_dir" +case ":$PATH:" in + *":$install_dir:"*) ;; + *) printf 'Add %s to your PATH, then run: ta --help\n' "$install_dir";; +esac diff --git a/internal/archive/batch.go b/internal/archive/batch.go index 0a67155..f6e81b3 100644 --- a/internal/archive/batch.go +++ b/internal/archive/batch.go @@ -4,6 +4,7 @@ import ( "context" "errors" "fmt" + "net" "os" "path/filepath" "slices" @@ -49,6 +50,13 @@ func RunBatch(ctx context.Context, source Source, root string, chats []Chat, opt directories = append(directories, entry.Name()) } } + var plans map[string]plannedChat + if opts.OnPlan != nil { + plans, err = planBatch(ctx, source, root, directories, chats, opts) + if err != nil { + return report, err + } + } seen := map[string]bool{} for _, chat := range chats { if err := ctx.Err(); err != nil { @@ -75,7 +83,15 @@ func RunBatch(ctx context.Context, source Source, root string, chats []Chat, opt continue } dir := filepath.Join(root, name) - result, err := Run(ctx, source, dir, chat, opts) + chatOpts := opts + var result Result + if plan, exists := plans[chat.Key]; exists { + chatOpts.snapshotNewest = &plan.newest + err = plan.err + } + if err == nil { + result, err = Run(ctx, source, dir, chat, chatOpts) + } if err != nil { record.Error = err.Error() failures = append(failures, fmt.Errorf("%s: %w", chat.Name, err)) @@ -93,6 +109,12 @@ func RunBatch(ctx context.Context, source Source, root string, chats []Chat, opt } } report.Chats = append(report.Chats, record) + // Recreate a stalled connection before trying the remaining chats. + // Permanent per-chat failures still leave other chats independent. + var timeout net.Error + if opts.Resume && errors.As(err, &timeout) && timeout.Timeout() { + break + } } report.Finished = time.Now().UTC() if err := writeJSON(filepath.Join(root, "run-report.json"), report); err != nil { diff --git a/internal/archive/batch_test.go b/internal/archive/batch_test.go index 9c7aee0..16bbeac 100644 --- a/internal/archive/batch_test.go +++ b/internal/archive/batch_test.go @@ -12,6 +12,26 @@ import ( type batchSource struct{ fakeSource } +type timedOutBatchSource struct{ fakeSource } + +func (*timedOutBatchSource) Download(context.Context, File, string) error { + return os.ErrDeadlineExceeded +} + +func TestBatchReturnsTransferTimeoutForSessionRecovery(t *testing.T) { + for _, resume := range []bool{false, true} { + source := &timedOutBatchSource{fakeSource: fakeSource{items: fakeItems(1), pageSize: 2}} + report, err := RunBatch(context.Background(), source, t.TempDir(), []Chat{{ID: 1, Key: "user_1"}, {ID: 2, Key: "user_2"}}, Options{Concurrency: 1, Media: []string{"photos"}, Resume: resume}, nil) + want := 2 + if resume { + want = 1 + } + if !errors.Is(err, os.ErrDeadlineExceeded) || len(report.Chats) != want { + t.Fatalf("resume=%v report=%+v err=%v", resume, report, err) + } + } +} + func (s *batchSource) History(ctx context.Context, chat Chat, cursor string) (Page, error) { if chat.ID == 1 { return Page{}, errors.New("channel unavailable") diff --git a/internal/archive/engine.go b/internal/archive/engine.go index 8527be7..bf0acd5 100644 --- a/internal/archive/engine.go +++ b/internal/archive/engine.go @@ -12,6 +12,7 @@ import ( "path/filepath" "slices" "strconv" + "sync/atomic" "time" bolt "go.etcd.io/bbolt" @@ -68,24 +69,26 @@ type TransferEvent struct { } type Options struct { - Media []string - Concurrency int - MaxFileSize int64 - MinFileSize int64 - Extensions []string - MIMETypes []string - OnlyMedia bool - Format string - ExportName string - HTMLPageSize int - PartSize int64 - Since time.Time - Until time.Time - Resume bool - Refresh bool - Takeout bool - Progress func(int) - OnTransfer func(TransferEvent) + Media []string + Concurrency int + MaxFileSize int64 + MinFileSize int64 + Extensions []string + MIMETypes []string + OnlyMedia bool + Format string + ExportName string + HTMLPageSize int + PartSize int64 + Since time.Time + Until time.Time + Resume bool + Refresh bool + Takeout bool + Progress func(int) + OnTransfer func(TransferEvent) + OnPlan func(DownloadPlan) + snapshotNewest *int } func (o Options) Validate() error { @@ -155,27 +158,12 @@ func Run(ctx context.Context, source Source, dir string, chat Chat, opts Options return Result{}, fmt.Errorf("open archive checkpoint: %w", err) } defer db.Close() - media := slices.Clone(opts.Media) - slices.Sort(media) - media = slices.Compact(media) - exts, mimes := normalizedFilters(opts.Extensions), normalizedFilters(opts.MIMETypes) - settings, _ := json.Marshal(struct { - ChatID, AccountID int64 - Takeout bool - Media []string - Max int64 - Since, Until time.Time - Min int64 `json:",omitempty"` - Extensions []string `json:",omitempty"` - MIMETypes []string `json:",omitempty"` - OnlyMedia bool `json:",omitempty"` - }{chat.ID, chat.AccountID, opts.Takeout, media, opts.MaxFileSize, opts.Since, opts.Until, opts.MinFileSize, exts, mimes, opts.OnlyMedia}) - state := checkpoint{Settings: fmt.Sprintf("%x", sha256.Sum256(settings))} + state := checkpoint{Settings: checkpointSettings(chat, opts)} err = db.Update(func(tx *bolt.Tx) error { owner := strconv.FormatInt(chat.AccountID, 10) if meta := tx.Bucket(metaBucket); meta != nil { if saved := meta.Get([]byte("account")); saved != nil && string(saved) != owner { - return fmt.Errorf("archive belongs to a different Telegram account; choose a different --output directory") + return fmt.Errorf("archive belongs to a different Telegram account (archive: %s; current login: %s); choose the matching -n namespace or a different --output directory", saved, owner) } } if !opts.Resume { @@ -267,15 +255,59 @@ func Run(ctx context.Context, source Source, dir string, chat Chat, opts Options return tx.Bucket(metaBucket).Put(stateKey, b) }) } - process := func(items []Item) ([]Item, error) { + err = walkHistory(ctx, source, chat, &state, opts, func(items []Item) error { selected := FilterItems(items, opts) if err := downloadPage(ctx, source, dir, selected, opts); err != nil { - return nil, err + return err } if opts.Progress != nil { opts.Progress(len(selected)) } - return selected, nil + return save(selected) + }) + if err != nil { + return Result{}, err + } + return renderOrReuse(ctx, db, dir, chat, opts, state.Revision) +} + +func checkpointSettings(chat Chat, opts Options) string { + media := slices.Clone(opts.Media) + slices.Sort(media) + media = slices.Compact(media) + exts, mimes := normalizedFilters(opts.Extensions), normalizedFilters(opts.MIMETypes) + settings, _ := json.Marshal(struct { + ChatID, AccountID int64 + Takeout bool + Media []string + Max int64 + Since, Until time.Time + Min int64 `json:",omitempty"` + Extensions []string `json:",omitempty"` + MIMETypes []string `json:",omitempty"` + OnlyMedia bool `json:",omitempty"` + }{chat.ID, chat.AccountID, opts.Takeout, media, opts.MaxFileSize, opts.Since, opts.Until, opts.MinFileSize, exts, mimes, opts.OnlyMedia}) + return fmt.Sprintf("%x", sha256.Sum256(settings)) +} + +// Planning and execution visit the same pending history. The snapshot bound +// leaves messages arriving after planning for the next sync. +func walkHistory(ctx context.Context, source Source, chat Chat, state *checkpoint, opts Options, process func([]Item) error) error { + history := func(cursor string) (Page, error) { + if err := ctx.Err(); err != nil { + return Page{}, err + } + page, err := source.History(ctx, chat, cursor) + if opts.snapshotNewest != nil { + items := make([]Item, 0, len(page.Items)) + for _, item := range page.Items { + if item.Message.ID <= *opts.snapshotNewest { + items = append(items, item) + } + } + page.Items = items + } + return page, err } if state.Complete && state.Newest == 0 { state.Complete = false @@ -284,8 +316,8 @@ func Run(ctx context.Context, source Source, dir string, chat Chat, opts Options state.Cursor = "" state.Complete = false state.Refreshing = true - if err := save(nil); err != nil { - return Result{}, err + if err := process(nil); err != nil { + return err } } // Collect new messages first, but don't advance Newest until this whole @@ -293,9 +325,9 @@ func Run(ctx context.Context, source Source, dir string, chat Chat, opts Options if state.Newest > 0 && !state.Refreshing { boundary, latest, offset := state.Newest, state.Newest, "" for { - page, err := source.History(ctx, chat, offset) + page, err := history(offset) if err != nil { - return Result{}, err + return err } var items []Item reached := false @@ -309,53 +341,45 @@ func Run(ctx context.Context, source Source, dir string, chat Chat, opts Options } items = append(items, item) } - items, err = process(items) - if err != nil { - return Result{}, err - } - if err := save(items); err != nil { - return Result{}, err + if err := process(items); err != nil { + return err } if page.Done || reached { break } if page.Next == "" || page.Next == offset { - return Result{}, fmt.Errorf("history pagination did not advance") + return fmt.Errorf("history pagination did not advance") } offset = page.Next } state.Newest = latest - if err := save(nil); err != nil { - return Result{}, err + if err := process(nil); err != nil { + return err } } for !state.Complete { - page, err := source.History(ctx, chat, state.Cursor) + page, err := history(state.Cursor) if err != nil { - return Result{}, err + return err } if !page.Done && (page.Next == "" || page.Next == state.Cursor) { - return Result{}, fmt.Errorf("history pagination did not advance") + return fmt.Errorf("history pagination did not advance") } for _, item := range page.Items { if item.Message.ID > state.Newest { state.Newest = item.Message.ID } } - items, err := process(page.Items) - if err != nil { - return Result{}, err - } state.Cursor = page.Next state.Complete = page.Done if page.Done { state.Refreshing = false } - if err := save(items); err != nil { - return Result{}, err + if err := process(page.Items); err != nil { + return err } } - return renderOrReuse(ctx, db, dir, chat, opts, state.Revision) + return nil } func downloadPage(ctx context.Context, source Source, dir string, items []Item, opts Options) error { @@ -415,7 +439,7 @@ func downloadPage(ctx context.Context, source Source, dir string, items []Item, func downloadFile(ctx context.Context, source Source, dir string, file File, opts Options) (rerr error) { dest := filepath.Join(dir, filepath.FromSlash(file.Path)) - if st, err := os.Stat(dest); err == nil && st.Mode().IsRegular() && file.Size > 0 && st.Size() == file.Size { + if completedFile(dir, file) { return nil } if err := os.MkdirAll(filepath.Dir(dest), 0700); err != nil { @@ -428,14 +452,19 @@ func downloadFile(ctx context.Context, source Source, dir string, file File, opt tmp := f.Name() f.Close() defer os.Remove(tmp) + var reported atomic.Int64 + if opts.OnTransfer != nil { + opts.OnTransfer(TransferEvent{Kind: TransferStarted, File: file}) + defer func() { opts.OnTransfer(TransferEvent{Kind: TransferFinished, File: file, Err: rerr}) }() + } if file.Data != nil { err = os.WriteFile(tmp, file.Data, 0600) } else { if progressSource, ok := source.(ProgressSource); ok && opts.OnTransfer != nil { - opts.OnTransfer(TransferEvent{Kind: TransferStarted, File: file}) - defer func() { opts.OnTransfer(TransferEvent{Kind: TransferFinished, File: file, Err: rerr}) }() err = progressSource.DownloadWithProgress(ctx, file, tmp, func(delta int64) { if delta > 0 { + // A source may write parallel chunks. + reported.Add(delta) opts.OnTransfer(TransferEvent{Kind: TransferProgressed, File: file, Delta: delta}) } }) @@ -453,6 +482,9 @@ func downloadFile(ctx context.Context, source Source, dir string, file File, opt if file.Size > 0 && st.Size() != file.Size { return fmt.Errorf("size mismatch: got %d, expected %d", st.Size(), file.Size) } + if opts.OnTransfer != nil && st.Size() > reported.Load() { + opts.OnTransfer(TransferEvent{Kind: TransferProgressed, File: file, Delta: st.Size() - reported.Load()}) + } return os.Rename(tmp, dest) } diff --git a/internal/archive/planning.go b/internal/archive/planning.go new file mode 100644 index 0000000..add0b26 --- /dev/null +++ b/internal/archive/planning.go @@ -0,0 +1,188 @@ +package archive + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "net" + "os" + "path/filepath" + "strconv" + "time" + + bolt "go.etcd.io/bbolt" +) + +// DownloadPlan reports the history scan and pending transfers, excluding +// completed local files. Ready becomes true after every selected chat is scanned. +type DownloadPlan struct { + Bytes int64 + Files int64 + UnknownFiles int64 + Messages int64 + Chat string + Ready bool +} + +type plannedChat struct { + newest int + err error +} + +// Keep deduplication on disk so planning a large archive still uses one page of +// history in memory. File references are fetched again immediately before use. +func planBatch(ctx context.Context, source Source, root string, directories []string, chats []Chat, opts Options) (map[string]plannedChat, error) { + f, err := os.CreateTemp(root, ".progress-plan-*") + if err != nil { + return nil, err + } + name := f.Name() + f.Close() + defer os.Remove(name) + db, err := bolt.Open(name, 0600, nil) + if err != nil { + return nil, err + } + defer db.Close() + if err := db.Update(func(tx *bolt.Tx) error { _, err := tx.CreateBucket([]byte("files")); return err }); err != nil { + return nil, err + } + plans := map[string]plannedChat{} + total := DownloadPlan{} + opts.OnPlan(total) + for _, chat := range chats { + if err := ctx.Err(); err != nil { + return nil, err + } + if chat.Key == "" { + chat.Key = fmt.Sprintf("chat_%d", chat.ID) + } + if _, exists := plans[chat.Key]; exists { + continue + } + if !filepath.IsLocal(chat.Key) { + plans[chat.Key] = plannedChat{err: fmt.Errorf("unsafe chat key")} + continue + } + folder, err := exportDirectory(chat, opts.ExportName, directories) + if err != nil { + plans[chat.Key] = plannedChat{err: err} + continue + } + dir := filepath.Join(root, folder) + state, err := planningCheckpoint(dir, chat, opts) + if err != nil { + plans[chat.Key] = plannedChat{err: err} + continue + } + pending := DownloadPlan{} + total.Chat = chat.Name + opts.OnPlan(total) + err = walkHistory(ctx, source, chat, &state, opts, func(items []Item) error { + if err := ctx.Err(); err != nil { + return err + } + total.Messages += int64(len(items)) + err := db.Update(func(tx *bolt.Tx) error { + files := tx.Bucket([]byte("files")) + for _, item := range FilterItems(items, opts) { + for _, file := range item.Files { + if fileSkipReason(file, item.Message, opts) != "" { + continue + } + if !filepath.IsLocal(file.Path) { + return fmt.Errorf("unsafe media path %q", file.Path) + } + key := []byte(filepath.Join(dir, filepath.FromSlash(file.Path))) + if files.Get(key) != nil || completedFile(dir, file) { + continue + } + if err := files.Put(key, []byte{1}); err != nil { + return err + } + pending.Files++ + pending.Bytes += downloadSize(file) + if downloadSize(file) == 0 { + pending.UnknownFiles++ + } + } + } + return nil + }) + update := total + update.Bytes += pending.Bytes + update.Files += pending.Files + update.UnknownFiles += pending.UnknownFiles + opts.OnPlan(update) + return err + }) + // A fresh session can recover an unresponsive history request. Avoid + // spending another timeout on every remaining chat first. + var timeout net.Error + if opts.Resume && errors.As(err, &timeout) && timeout.Timeout() { + return nil, err + } + plans[chat.Key] = plannedChat{newest: state.Newest, err: err} + if err == nil { + total.Bytes += pending.Bytes + total.Files += pending.Files + total.UnknownFiles += pending.UnknownFiles + } + } + if err := ctx.Err(); err != nil { + return nil, err + } + total.Ready = true + opts.OnPlan(total) + return plans, nil +} + +func planningCheckpoint(dir string, chat Chat, opts Options) (checkpoint, error) { + state := checkpoint{Settings: checkpointSettings(chat, opts)} + name := filepath.Join(dir, "archive.db") + if _, err := os.Stat(name); os.IsNotExist(err) { + return state, nil + } else if err != nil { + return state, err + } + db, err := bolt.Open(name, 0600, &bolt.Options{ReadOnly: true, Timeout: time.Second}) + if err != nil { + return state, fmt.Errorf("open archive checkpoint: %w", err) + } + defer db.Close() + err = db.View(func(tx *bolt.Tx) error { + meta := tx.Bucket(metaBucket) + if meta == nil { + return nil + } + if owner := meta.Get([]byte("account")); owner != nil && string(owner) != strconv.FormatInt(chat.AccountID, 10) { + return fmt.Errorf("archive belongs to a different Telegram account (archive: %s; current login: %d); choose the matching -n namespace or a different --output directory", owner, chat.AccountID) + } + if saved := meta.Get(stateKey); opts.Resume && saved != nil { + var old checkpoint + if err := json.Unmarshal(saved, &old); err != nil { + return err + } + if old.Settings != state.Settings { + return fmt.Errorf("archive settings changed; use --resume=false to rebuild with the new settings") + } + state = old + } + return nil + }) + return state, err +} + +func downloadSize(file File) int64 { + if file.Data != nil { + return int64(len(file.Data)) + } + return max(0, file.Size) +} + +func completedFile(dir string, file File) bool { + st, err := os.Stat(filepath.Join(dir, filepath.FromSlash(file.Path))) + size := downloadSize(file) + return err == nil && st.Mode().IsRegular() && size > 0 && st.Size() == size +} diff --git a/internal/archive/progress_test.go b/internal/archive/progress_test.go new file mode 100644 index 0000000..5594a8b --- /dev/null +++ b/internal/archive/progress_test.go @@ -0,0 +1,223 @@ +package archive + +import ( + "context" + "errors" + "os" + "path/filepath" + "sync" + "testing" +) + +func TestPlanningReportsScannedMessagesWithoutMedia(t *testing.T) { + source := &fakeSource{items: fakeItems(3, 2, 1), pageSize: 2} + for i := range source.items { + source.items[i].Files = nil + } + chats := []Chat{{ID: 1, Key: "user_1", Name: "Fadi"}, {ID: 2, Key: "user_2", Name: "Other"}} + var updates []DownloadPlan + _, err := RunBatch(context.Background(), source, t.TempDir(), chats, Options{ + Concurrency: 1, OnPlan: func(p DownloadPlan) { updates = append(updates, p) }, + }, nil) + if err != nil { + t.Fatal(err) + } + var first, second bool + for _, p := range updates { + if p.Ready { + continue + } + first = first || (p.Chat == "Fadi" && p.Messages == 2) + second = second || (p.Chat == "Other" && p.Messages == 5) + } + last := updates[len(updates)-1] + if !first || !second || !last.Ready || last.Messages != 6 || last.Files != 0 || last.Bytes != 0 { + t.Fatalf("missing scan progress when no media was found: %+v", updates) + } +} + +type timedOutHistorySource struct { + fakeSource + calls int +} + +func (s *timedOutHistorySource) History(context.Context, Chat, string) (Page, error) { + s.calls++ + return Page{}, os.ErrDeadlineExceeded +} + +func TestPlanningReturnsHistoryTimeoutForSessionRecovery(t *testing.T) { + for _, resume := range []bool{false, true} { + source := &timedOutHistorySource{} + _, err := RunBatch(context.Background(), source, t.TempDir(), []Chat{{ID: 1}, {ID: 2}}, Options{ + Concurrency: 1, Resume: resume, OnPlan: func(DownloadPlan) {}, + }, nil) + want := 2 + if resume { + want = 1 + } + if !errors.Is(err, os.ErrDeadlineExceeded) || source.calls != want || source.downloads.Load() != 0 { + t.Fatalf("resume=%v err=%v history calls=%d downloads=%d", resume, err, source.calls, source.downloads.Load()) + } + } +} + +func TestBatchPlansWholeBackupBeforeDownloading(t *testing.T) { + root := t.TempDir() + source := &fakeSource{items: fakeItems(3, 2, 1), pageSize: 2} + // A shared attachment must count once per chat, including across pages. + source.items[2].Files = source.items[0].Files + chats := []Chat{{ID: 1, Key: "user_1"}, {ID: 2, Key: "user_2"}} + var plan DownloadPlan + ready := false + var transferred int64 + opts := Options{Concurrency: 1, Resume: true, Media: []string{"photos"}, OnPlan: func(p DownloadPlan) { + if source.downloads.Load() != 0 { + t.Fatal("planning continued after downloads started") + } + plan, ready = p, p.Ready + }, OnTransfer: func(event TransferEvent) { + if !ready { + t.Error("download started before the whole backup was planned") + } + if event.Kind == TransferProgressed { + transferred += event.Delta + } + }} + if _, err := RunBatch(context.Background(), source, root, chats, opts, nil); err != nil { + t.Fatal(err) + } + if !plan.Ready || plan.Bytes != 16 || plan.Files != 4 || transferred != 16 { + t.Fatalf("plan=%+v transferred=%d", plan, transferred) + } + // Incremental planning excludes both old history and a completed file from + // an interrupted page, but includes an incomplete local file in full. + source.items = fakeItems(5, 4, 3, 2, 1) + for _, chat := range chats { + dir := filepath.Join(root, "ChatExport_"+chat.Key, "photos") + if err := os.WriteFile(filepath.Join(dir, "5.jpg"), []byte("file"), 0600); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, "4.jpg"), []byte("x"), 0600); err != nil { + t.Fatal(err) + } + } + before := source.downloads.Load() + opts.OnPlan = func(p DownloadPlan) { plan = p } + if _, err := RunBatch(context.Background(), source, root, chats, opts, nil); err != nil { + t.Fatal(err) + } + if plan.Bytes != 8 || plan.Files != 2 || source.downloads.Load()-before != 2 { + t.Fatalf("incremental plan=%+v downloads=%d", plan, source.downloads.Load()-before) + } +} + +func TestBatchPlanningPreservesIndependentChatFailures(t *testing.T) { + source := &batchSource{fakeSource: fakeSource{items: fakeItems(1), pageSize: 2}} + var plan DownloadPlan + report, err := RunBatch(context.Background(), source, t.TempDir(), []Chat{{ID: 1, Key: "user_1"}, {ID: 2, Key: "user_2"}}, Options{ + Concurrency: 1, Media: []string{"photos"}, OnPlan: func(p DownloadPlan) { plan = p }, + }, nil) + if err == nil || len(report.Chats) != 2 || report.Chats[0].Error == "" || report.Chats[1].Error != "" { + t.Fatalf("report=%+v err=%v", report, err) + } + if !plan.Ready || plan.Bytes != 4 || plan.Files != 1 { + t.Fatalf("plan=%+v", plan) + } +} + +func TestBatchPlanningCancellationDoesNotDownload(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + source := &fakeSource{items: fakeItems(2, 1), pageSize: 1} + _, err := RunBatch(ctx, source, t.TempDir(), []Chat{{ID: 1}}, Options{ + Concurrency: 1, Media: []string{"photos"}, OnPlan: func(DownloadPlan) { cancel() }, + }, nil) + if !errors.Is(err, context.Canceled) || source.downloads.Load() != 0 { + t.Fatalf("err=%v downloads=%d", err, source.downloads.Load()) + } +} + +func TestPlanningSnapshotLeavesNewMessagesForNextSync(t *testing.T) { + source := &fakeSource{items: fakeItems(3, 2, 1), pageSize: 2} + root := t.TempDir() + chats := []Chat{{ID: 1, Key: "user_1"}} + opts := Options{Concurrency: 1, Resume: true, Media: []string{"photos"}, OnPlan: func(plan DownloadPlan) { + if plan.Ready { + source.items = fakeItems(4, 3, 2, 1) + } + }} + report, err := RunBatch(context.Background(), source, root, chats, opts, nil) + if err != nil || report.Chats[0].Stats.Messages != 3 { + t.Fatalf("snapshot report=%+v err=%v", report, err) + } + report, err = RunBatch(context.Background(), source, root, chats, opts, nil) + if err != nil || report.Chats[0].Stats.Messages != 4 || source.downloads.Load() != 4 { + t.Fatalf("next sync report=%+v err=%v downloads=%d", report, err, source.downloads.Load()) + } +} + +func TestPlanningUsesDownloadFiltersAndCountsGeneratedFiles(t *testing.T) { + source := &fakeSource{items: fakeItems(3, 2, 1), pageSize: 2} + source.items[0].Files = []File{{Kind: "documents", Field: "file", Path: "files/document.pdf", Size: 4}, {Kind: "documents", Field: "file", Path: "files/large.pdf", Size: 10}} + source.items[1].Files = []File{{Kind: "contacts", Field: "contact_vcard", Path: "contacts/person.vcf", Data: []byte("card")}} + var plan DownloadPlan + opts := Options{Concurrency: 1, Resume: true, Media: []string{"documents", "contacts"}, MaxFileSize: 5, OnlyMedia: true, OnPlan: func(p DownloadPlan) { plan = p }} + root := t.TempDir() + chats := []Chat{{ID: 1, Key: "user_1"}} + for _, refresh := range []bool{false, true} { + opts.Refresh = refresh + if _, err := RunBatch(context.Background(), source, root, chats, opts, nil); err != nil { + t.Fatal(err) + } + want := int64(8) + if refresh { + want = 0 + } + if !plan.Ready || plan.Bytes != want || plan.Files != want/4 { + t.Fatalf("refresh=%v plan=%+v", refresh, plan) + } + } +} + +type chunkProgressSource struct{ fakeSource } + +func (s *chunkProgressSource) DownloadWithProgress(ctx context.Context, file File, dest string, progress func(int64)) error { + if err := s.Download(ctx, file, dest); err != nil { + return err + } + var chunks sync.WaitGroup + for range 2 { + chunks.Go(func() { progress(2) }) + } + chunks.Wait() + return nil +} + +func TestProgressReportsParallelChunksOnceAndIntegrityFailures(t *testing.T) { + source := &chunkProgressSource{fakeSource: fakeSource{items: fakeItems(2, 1), pageSize: 2}} + var mu sync.Mutex + var transferred int64 + var finished []TransferEvent + opts := Options{Concurrency: 2, Media: []string{"photos"}, OnTransfer: func(event TransferEvent) { + mu.Lock() + defer mu.Unlock() + if event.Kind == TransferProgressed { + transferred += event.Delta + } + if event.Kind == TransferFinished { + finished = append(finished, event) + } + }} + if _, err := Run(context.Background(), source, t.TempDir(), Chat{ID: 1}, opts); err != nil { + t.Fatal(err) + } + if transferred != 8 || len(finished) != 2 || finished[0].Err != nil || finished[1].Err != nil { + t.Fatalf("bytes=%d finished=%+v", transferred, finished) + } + source.items = fakeItems(1) + source.items[0].Files[0].Size = 5 + finished = nil + if _, err := Run(context.Background(), source, t.TempDir(), Chat{ID: 1}, opts); err == nil || len(finished) != 1 || finished[0].Err == nil { + t.Fatalf("integrity failure lost: err=%v finished=%+v", err, finished) + } +} diff --git a/internal/telegram/download_timeout.go b/internal/telegram/download_timeout.go new file mode 100644 index 0000000..d25b92d --- /dev/null +++ b/internal/telegram/download_timeout.go @@ -0,0 +1,125 @@ +package telegram + +import ( + "context" + "errors" + "fmt" + "sync" + "time" + + "github.com/gotd/td/bin" + tgclient "github.com/gotd/td/telegram" + "github.com/gotd/td/tg" + "github.com/gotd/td/tgerr" +) + +const DefaultDownloadTimeout = 2 * time.Minute + +// DownloadStalledError lets the archive retry with a fresh Telegram session. +type DownloadStalledError struct { + Path string + IdleTimeout time.Duration +} + +func (e *DownloadStalledError) Error() string { + return fmt.Sprintf("Telegram request stalled for %s without data or a server response: %s", e.IdleTimeout, e.Path) +} + +func (*DownloadStalledError) Timeout() bool { return true } +func (*DownloadStalledError) Temporary() bool { return true } + +type downloadActivityKey struct{} + +type downloadActivity struct { + mu sync.Mutex + ctx context.Context + cancel context.CancelCauseFunc + timer *time.Timer + timeout time.Duration + deadline time.Time + waitUntil time.Time + stopped bool + failure *DownloadStalledError +} + +func watchDownload(parent context.Context, path string, timeout time.Duration) (context.Context, *downloadActivity) { + if timeout <= 0 { + return parent, nil + } + ctx, cancel := context.WithCancelCause(parent) + a := &downloadActivity{ctx: ctx, cancel: cancel, timeout: timeout, deadline: time.Now().Add(timeout), failure: &DownloadStalledError{Path: path, IdleTimeout: timeout}} + // The callback must not see an uninitialized timer, even with tiny timeouts. + a.mu.Lock() + a.timer = time.AfterFunc(timeout, a.expire) + a.mu.Unlock() + return context.WithValue(ctx, downloadActivityKey{}, a), a +} + +func (a *downloadActivity) expire() { + a.mu.Lock() + defer a.mu.Unlock() + if a.stopped { + return + } + if remaining := time.Until(a.deadline); remaining > 0 { + a.timer.Reset(remaining) + return + } + a.cancel(a.failure) +} + +func (a *downloadActivity) touch() { a.wait(0) } + +func (a *downloadActivity) wait(duration time.Duration) { + if a == nil { + return + } + a.mu.Lock() + defer a.mu.Unlock() + if a.stopped { + return + } + now := time.Now() + if until := now.Add(duration); until.After(a.waitUntil) { + a.waitUntil = until + } + // Bytes from one worker must not shorten a flood wait in another worker. + a.deadline = a.waitUntil.Add(a.timeout) + a.timer.Reset(time.Until(a.deadline)) +} + +func (a *downloadActivity) finish(err error) error { + if a == nil { + return err + } + a.mu.Lock() + a.stopped = true + a.timer.Stop() + stalled := context.Cause(a.ctx) == a.failure + a.mu.Unlock() + a.cancel(nil) + if stalled { + return errors.Join(a.failure, err) + } + return err +} + +// DownloadActivityMiddleware observes replies inside the automatic flood-wait +// handler, so a requested Telegram wait is not mistaken for a stalled transfer. +// Requests outside a watched history read or download are unaffected. +func DownloadActivityMiddleware() tgclient.Middleware { + return tgclient.MiddlewareFunc(func(next tg.Invoker) tgclient.InvokeFunc { + return func(ctx context.Context, input bin.Encoder, output bin.Decoder) error { + err := next.Invoke(ctx, input, output) + if activity, _ := ctx.Value(downloadActivityKey{}).(*downloadActivity); activity != nil { + if wait, ok := tgerr.AsFloodWait(err); ok { + // The downloader's own flood handler adds one second of slack. + activity.wait(max(wait, time.Second) + time.Second) + } else if err == nil { + activity.touch() + } + } + return err + } + }) +} diff --git a/internal/telegram/download_timeout_test.go b/internal/telegram/download_timeout_test.go new file mode 100644 index 0000000..957d4b8 --- /dev/null +++ b/internal/telegram/download_timeout_test.go @@ -0,0 +1,213 @@ +package telegram + +import ( + "bytes" + "context" + "errors" + "fmt" + "net" + "os" + "path/filepath" + "sync/atomic" + "testing" + "time" + + "github.com/gotd/contrib/middleware/floodwait" + "github.com/gotd/td/bin" + tgclient "github.com/gotd/td/telegram" + "github.com/gotd/td/tg" + "github.com/gotd/td/tgerr" + transferdownload "github.com/iyear/tdl/core/downloader" + "github.com/iyear/tdl/core/tmedia" + "github.com/mo1ein/TelegramArchive/internal/archive" +) + +type watchdogTestPool struct { + client func(context.Context, int) *tg.Client +} + +func (p watchdogTestPool) Client(ctx context.Context, dc int) *tg.Client { return p.client(ctx, dc) } +func (p watchdogTestPool) Default(ctx context.Context) *tg.Client { return p.Client(ctx, 4) } +func (p watchdogTestPool) Takeout(ctx context.Context, dc int) *tg.Client { + return p.Client(ctx, dc) +} +func (watchdogTestPool) Close() error { return nil } + +func watchdogTestFile(t *testing.T, size int64) (archive.File, string) { + t.Helper() + file := archive.File{Path: "files/stalled.bin", Size: size, Remote: &tmedia.Media{ + DC: 4, Size: size, InputFileLoc: &tg.InputDocumentFileLocation{ID: 123}, + }} + dest := filepath.Join(t.TempDir(), "partial") + if err := os.WriteFile(dest, nil, 0600); err != nil { + t.Fatal(err) + } + return file, dest +} + +func TestDownloadWatchdogStopsStalledSetupAndFileRequests(t *testing.T) { + for _, stallSetup := range []bool{false, true} { + t.Run(map[bool]string{false: "file request", true: "data center setup"}[stallSetup], func(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + api := tg.NewClient(DownloadActivityMiddleware().Handle(tgclient.InvokeFunc(func(ctx context.Context, _ bin.Encoder, _ bin.Decoder) error { + <-ctx.Done() + return ctx.Err() + }))) + source := &Source{threads: 1, DownloadTimeout: 60 * time.Millisecond, pool: watchdogTestPool{ + client: func(ctx context.Context, dc int) *tg.Client { + if stallSetup { + <-ctx.Done() + } + return api + }, + }} + file, dest := watchdogTestFile(t, 4) + err := source.DownloadWithProgress(ctx, file, dest, nil) + var stalled *DownloadStalledError + var network net.Error + if !errors.As(err, &stalled) || !errors.As(err, &network) || !network.Timeout() { + t.Fatalf("stalled transfer did not produce a retryable timeout: %v", err) + } + if stalled.Path != file.Path || stalled.IdleTimeout != source.DownloadTimeout { + t.Fatalf("timeout lost its filename or configured duration: %+v", stalled) + } + if ctx.Err() != nil { + t.Fatal("watchdog waited for the whole operation's deadline") + } + }) + } +} + +func TestDownloadWatchdogResetsForHealthyChunks(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 4*time.Second) + defer cancel() + body := bytes.Repeat([]byte{'x'}, transferdownload.MaxPartSize*3+1) + api := tg.NewClient(DownloadActivityMiddleware().Handle(tgclient.InvokeFunc(func(ctx context.Context, input bin.Encoder, output bin.Decoder) error { + request := input.(*tg.UploadGetFileRequest) + timer := time.NewTimer(100 * time.Millisecond) + defer timer.Stop() + select { + case <-ctx.Done(): + return ctx.Err() + case <-timer.C: + } + start := min(int(request.Offset), len(body)) + end := min(start+request.Limit, len(body)) + output.(*tg.UploadFileBox).File = &tg.UploadFile{Type: &tg.StorageFileUnknown{}, Bytes: body[start:end]} + return nil + }))) + source := &Source{threads: 1, DownloadTimeout: 250 * time.Millisecond, pool: watchdogTestPool{client: func(context.Context, int) *tg.Client { return api }}} + file, dest := watchdogTestFile(t, int64(len(body))) + var transferred atomic.Int64 + if err := source.DownloadWithProgress(ctx, file, dest, func(n int64) { transferred.Add(n) }); err != nil { + t.Fatal(err) + } + data, err := os.ReadFile(dest) + if err != nil || !bytes.Equal(data, body) || transferred.Load() != int64(len(body)) { + t.Fatalf("healthy transfer was truncated: len=%d reported=%d err=%v", len(data), transferred.Load(), err) + } +} + +func TestDownloadWatchdogHonorsTelegramFloodWait(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 4*time.Second) + defer cancel() + var calls atomic.Int32 + rpc := tgclient.InvokeFunc(func(ctx context.Context, input bin.Encoder, output bin.Decoder) error { + if calls.Add(1) == 1 { + return fmt.Errorf("media request: %w", tgerr.New(420, "FLOOD_WAIT_1")) + } + output.(*tg.UploadFileBox).File = &tg.UploadFile{Type: &tg.StorageFileUnknown{}, Bytes: []byte("data")} + return nil + }) + // The observer must see FLOOD_WAIT before the waiter consumes it. A + // legitimate one-second server delay exceeds this transfer's idle budget. + api := tg.NewClient(floodwait.NewSimpleWaiter().Handle(DownloadActivityMiddleware().Handle(rpc))) + source := &Source{threads: 1, DownloadTimeout: 150 * time.Millisecond, pool: watchdogTestPool{client: func(context.Context, int) *tg.Client { return api }}} + file, dest := watchdogTestFile(t, 4) + if err := source.DownloadWithProgress(ctx, file, dest, nil); err != nil { + t.Fatalf("Telegram flood wait was mistaken for a stalled connection: %v", err) + } + data, err := os.ReadFile(dest) + if err != nil || string(data) != "data" || calls.Load() != 2 { + t.Fatalf("flood-wait retry did not finish: data=%q calls=%d err=%v", data, calls.Load(), err) + } +} + +func TestDownloadWatchdogKeepsAnotherWorkersFloodWaitWhenBytesArrive(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 4*time.Second) + defer cancel() + body := bytes.Repeat([]byte{'x'}, transferdownload.MaxPartSize+4) + floodIssued := make(chan struct{}) + var flooded atomic.Bool + rpc := tgclient.InvokeFunc(func(ctx context.Context, input bin.Encoder, output bin.Decoder) error { + request := input.(*tg.UploadGetFileRequest) + if request.Offset == 0 && flooded.CompareAndSwap(false, true) { + close(floodIssued) + return tgerr.New(420, "FLOOD_WAIT_1") + } + if request.Offset > 0 { + select { + case <-ctx.Done(): + return ctx.Err() + case <-floodIssued: + } + // Let the first worker record its flood wait, then deliver bytes in + // the second worker while that server-requested wait is still active. + timer := time.NewTimer(100 * time.Millisecond) + defer timer.Stop() + select { + case <-ctx.Done(): + return ctx.Err() + case <-timer.C: + } + } + start := min(int(request.Offset), len(body)) + end := min(start+request.Limit, len(body)) + output.(*tg.UploadFileBox).File = &tg.UploadFile{Type: &tg.StorageFileUnknown{}, Bytes: body[start:end]} + return nil + }) + api := tg.NewClient(floodwait.NewSimpleWaiter().Handle(DownloadActivityMiddleware().Handle(rpc))) + source := &Source{threads: 2, DownloadTimeout: 400 * time.Millisecond, pool: watchdogTestPool{client: func(context.Context, int) *tg.Client { return api }}} + file, dest := watchdogTestFile(t, int64(len(body))) + if err := source.DownloadWithProgress(ctx, file, dest, nil); err != nil { + t.Fatalf("a concurrent worker shortened the pending flood wait: %v", err) + } + data, err := os.ReadFile(dest) + if err != nil || !bytes.Equal(data, body) { + t.Fatalf("parallel transfer after flood wait was truncated: len=%d err=%v", len(data), err) + } +} + +func TestDownloadWatchdogPreservesParentCancellation(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + api := tg.NewClient(tgclient.InvokeFunc(func(ctx context.Context, input bin.Encoder, output bin.Decoder) error { + cancel() + <-ctx.Done() + return ctx.Err() + })) + source := &Source{threads: 1, DownloadTimeout: time.Second, pool: watchdogTestPool{client: func(context.Context, int) *tg.Client { return api }}} + file, dest := watchdogTestFile(t, 4) + err := source.DownloadWithProgress(ctx, file, dest, nil) + var stalled *DownloadStalledError + if !errors.Is(err, context.Canceled) || errors.As(err, &stalled) { + t.Fatalf("parent cancellation became a transfer timeout: %v", err) + } +} + +func TestDownloadWatchdogCanBeDisabled(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 80*time.Millisecond) + defer cancel() + api := tg.NewClient(tgclient.InvokeFunc(func(ctx context.Context, input bin.Encoder, output bin.Decoder) error { + <-ctx.Done() + return ctx.Err() + })) + source := &Source{threads: 1, DownloadTimeout: 0, pool: watchdogTestPool{client: func(context.Context, int) *tg.Client { return api }}} + file, dest := watchdogTestFile(t, 4) + err := source.DownloadWithProgress(ctx, file, dest, nil) + var stalled *DownloadStalledError + if !errors.Is(err, context.DeadlineExceeded) || errors.As(err, &stalled) { + t.Fatalf("disabled watchdog ignored the caller's deadline: %v", err) + } +} diff --git a/internal/telegram/history_timeout_test.go b/internal/telegram/history_timeout_test.go new file mode 100644 index 0000000..b5d9a66 --- /dev/null +++ b/internal/telegram/history_timeout_test.go @@ -0,0 +1,126 @@ +package telegram + +import ( + "context" + "errors" + "net" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/gotd/contrib/middleware/floodwait" + "github.com/gotd/td/bin" + tgclient "github.com/gotd/td/telegram" + "github.com/gotd/td/tg" + "github.com/gotd/td/tgerr" + "github.com/mo1ein/TelegramArchive/internal/archive" +) + +func TestHistoryWatchdogStopsStalledPage(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), time.Second) + defer cancel() + api := tg.NewClient(DownloadActivityMiddleware().Handle(tgclient.InvokeFunc(func(ctx context.Context, input bin.Encoder, output bin.Decoder) error { + <-ctx.Done() + return ctx.Err() + }))) + chat := archive.Chat{Key: "user_10", Name: "Fadi"} + source := &Source{api: api, DownloadTimeout: 60 * time.Millisecond, chats: map[string]tg.InputPeerClass{chat.Key: &tg.InputPeerSelf{}}} + _, err := source.History(ctx, chat, "") + var stalled *DownloadStalledError + var network net.Error + if !errors.As(err, &stalled) || !errors.As(err, &network) || !network.Timeout() { + t.Fatalf("history request did not report a retryable idle timeout: %v", err) + } + if !strings.Contains(strings.ToLower(stalled.Path), "history") || (!strings.Contains(stalled.Path, chat.Name) && !strings.Contains(stalled.Path, chat.Key)) { + t.Fatalf("timeout did not identify the chat's history: %+v", stalled) + } + if ctx.Err() != nil { + t.Fatal("history watchdog expired the parent context") + } +} + +func TestHistoryWatchdogPreservesParentCancellation(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + api := tg.NewClient(tgclient.InvokeFunc(func(ctx context.Context, input bin.Encoder, output bin.Decoder) error { + cancel() + return ctx.Err() + })) + chat := archive.Chat{Key: "user_10", Name: "Fadi"} + source := &Source{api: api, DownloadTimeout: time.Second, chats: map[string]tg.InputPeerClass{chat.Key: &tg.InputPeerSelf{}}} + _, err := source.History(ctx, chat, "") + var stalled *DownloadStalledError + if !errors.Is(err, context.Canceled) || errors.As(err, &stalled) { + t.Fatalf("parent cancellation became a history timeout: %v", err) + } +} + +func TestHistoryWatchdogGivesEachPageAFreshBudget(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 4*time.Second) + defer cancel() + var calls atomic.Int32 + api := tg.NewClient(DownloadActivityMiddleware().Handle(tgclient.InvokeFunc(func(ctx context.Context, input bin.Encoder, output bin.Decoder) error { + request := input.(*tg.MessagesGetHistoryRequest) + calls.Add(1) + timer := time.NewTimer(100 * time.Millisecond) + defer timer.Stop() + select { + case <-ctx.Done(): + return ctx.Err() + case <-timer.C: + } + top := 300 + if request.OffsetID > 0 { + top = request.OffsetID - 1 + } + result := &tg.MessagesMessagesSlice{} + for id := top; id > 0 && len(result.Messages) < 100; id-- { + result.Messages = append(result.Messages, &tg.Message{ID: id, Message: "test"}) + } + output.(*tg.MessagesMessagesBox).Messages = result + return nil + }))) + chat := archive.Chat{Key: "user_10", Name: "Fadi"} + source := &Source{api: api, DownloadTimeout: 250 * time.Millisecond, chats: map[string]tg.InputPeerClass{chat.Key: &tg.InputPeerSelf{}}} + // Four individually responsive pages take longer than one idle budget. + // A single timeout around the whole scan would incorrectly cancel it. + cursor, messages := "", 0 + for iteration := 0; ; iteration++ { + if iteration > 4 { + t.Fatal("history pagination did not finish") + } + page, err := source.History(ctx, chat, cursor) + if err != nil { + t.Fatal(err) + } + messages += len(page.Items) + if page.Done { + break + } + cursor = page.Next + } + if messages != 300 || calls.Load() != 4 || ctx.Err() != nil { + t.Fatalf("history scan was truncated: messages=%d pages=%d parent=%v", messages, calls.Load(), ctx.Err()) + } +} + +func TestHistoryWatchdogHonorsTelegramFloodWait(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 4*time.Second) + defer cancel() + var calls atomic.Int32 + rpc := tgclient.InvokeFunc(func(ctx context.Context, input bin.Encoder, output bin.Decoder) error { + if calls.Add(1) == 1 { + return tgerr.New(420, "FLOOD_WAIT_1") + } + output.(*tg.MessagesMessagesBox).Messages = &tg.MessagesMessages{Messages: []tg.MessageClass{&tg.Message{ID: 1, Message: "test"}}} + return nil + }) + api := tg.NewClient(floodwait.NewSimpleWaiter().Handle(DownloadActivityMiddleware().Handle(rpc))) + chat := archive.Chat{Key: "user_10", Name: "Fadi"} + source := &Source{api: api, DownloadTimeout: 150 * time.Millisecond, chats: map[string]tg.InputPeerClass{chat.Key: &tg.InputPeerSelf{}}} + page, err := source.History(ctx, chat, "") + if err != nil || len(page.Items) != 1 || page.Items[0].Message.ID != 1 || calls.Load() != 2 { + t.Fatalf("history flood-wait retry did not finish: page=%+v calls=%d err=%v", page, calls.Load(), err) + } +} diff --git a/internal/telegram/resolve.go b/internal/telegram/resolve.go new file mode 100644 index 0000000..96c4202 --- /dev/null +++ b/internal/telegram/resolve.go @@ -0,0 +1,44 @@ +package telegram + +import ( + "context" + "fmt" + "strings" + + "github.com/gotd/td/telegram/deeplink" + "github.com/mo1ein/TelegramArchive/internal/archive" +) + +func isDisplayNameReference(ref string) bool { + return !strings.HasPrefix(ref, "@") && !strings.HasPrefix(ref, "+") && !deeplink.IsDeeplinkLike(ref) +} + +// Bare references prefer the name visible in the user's chat list. Explicit +// @usernames and Telegram links bypass this search. +func (s *Source) resolveNamedChat(ctx context.Context, ref string) (archive.Chat, bool, error) { + if !s.namesLoaded { + chats, err := s.Dialogs(ctx, []string{"personal", "bots", "groups", "channels"}) + if err != nil { + return archive.Chat{}, false, fmt.Errorf("search chats for display name %q: %w; use @username for an explicit username", ref, err) + } + s.nameDialogs, s.namesLoaded = chats, true + } + name := strings.Join(strings.Fields(ref), " ") + var found []archive.Chat + for _, chat := range s.nameDialogs { + if strings.EqualFold(strings.Join(strings.Fields(chat.Name), " "), name) { + found = append(found, chat) + } + } + if len(found) == 1 { + return found[0], true, nil + } + if len(found) > 1 { + ids := make([]string, 0, len(found)) + for _, chat := range found { + ids = append(ids, fmt.Sprintf("%d (%s)", chat.ID, chat.Type)) + } + return archive.Chat{}, false, fmt.Errorf("chat display name %q matches multiple chats: %s; select by ID or @username", ref, strings.Join(ids, ", ")) + } + return archive.Chat{}, false, nil +} diff --git a/internal/telegram/resolve_test.go b/internal/telegram/resolve_test.go new file mode 100644 index 0000000..49aeae7 --- /dev/null +++ b/internal/telegram/resolve_test.go @@ -0,0 +1,93 @@ +package telegram + +import ( + "context" + "strings" + "testing" + + "github.com/gotd/td/bin" + tgclient "github.com/gotd/td/telegram" + "github.com/gotd/td/telegram/peers" + "github.com/gotd/td/tg" + "github.com/gotd/td/tgerr" +) + +func nameResolver(t *testing.T, users ...*tg.User) *Source { + t.Helper() + api := tg.NewClient(tgclient.InvokeFunc(func(ctx context.Context, input bin.Encoder, output bin.Decoder) error { + switch request := input.(type) { + case *tg.MessagesGetDialogsRequest: + result := &tg.MessagesDialogs{} + folder, _ := request.GetFolderID() + for _, user := range users { + // Put personal chats in the archive folder to exercise both folders. + if folder == 1 { + result.Dialogs = append(result.Dialogs, &tg.Dialog{Peer: &tg.PeerUser{UserID: user.ID}}) + result.Users = append(result.Users, user) + } + } + output.(*tg.MessagesDialogsBox).Dialogs = result + case *tg.ContactsResolveUsernameRequest: + if request.Username != "mammad" { + return tgerr.New(400, "USERNAME_NOT_OCCUPIED") + } + *output.(*tg.ContactsResolvedPeer) = tg.ContactsResolvedPeer{ + Peer: &tg.PeerUser{UserID: 99}, Users: []tg.UserClass{&tg.User{ID: 99, AccessHash: 999, FirstName: "Public username owner", Username: "mammad"}}, + } + default: + t.Fatalf("unexpected lookup: %T", input) + } + return nil + })) + return &Source{api: api, manager: peers.Options{}.Build(api), chats: map[string]tg.InputPeerClass{}} +} + +func TestResolvePrefersDisplayedNameOverPublicUsername(t *testing.T) { + for _, ref := range []string{"mammad", " MAMMAD "} { + source := nameResolver(t, &tg.User{ID: 10, AccessHash: 100, FirstName: "mammad", Username: "my_friend", Contact: true}) + chat, err := source.Resolve(context.Background(), ref) + if err != nil || chat.ID != 10 || chat.Name != "mammad" { + t.Fatalf("ref=%q resolved=%+v err=%v", ref, chat, err) + } + if source.chats[chat.Key] == nil { + t.Fatal("display-name match did not retain its access hash") + } + } +} + +func TestResolveExplicitUsernameAndURLKeepTheirMeaning(t *testing.T) { + for _, ref := range []string{"@mammad", "https://t.me/mammad"} { + source := nameResolver(t, &tg.User{ID: 10, AccessHash: 100, FirstName: "mammad"}) + chat, err := source.Resolve(context.Background(), ref) + if err != nil || chat.ID != 99 { + t.Fatalf("ref=%q resolved=%+v err=%v", ref, chat, err) + } + } +} + +func TestResolveContactWithoutUsernameByFullDisplayName(t *testing.T) { + for _, name := range []string{"mammad", "Mammad Ahmadi"} { + first, last, _ := strings.Cut(name, " ") + source := nameResolver(t, &tg.User{ID: 10, AccessHash: 100, FirstName: first, LastName: last, Contact: true}) + chat, err := source.Resolve(context.Background(), " "+strings.ReplaceAll(strings.ToUpper(name), " ", " ")+" ") + if err != nil || chat.ID != 10 || chat.Username != "" { + t.Fatalf("name=%q resolved=%+v err=%v", name, chat, err) + } + } +} + +func TestResolveUnmatchedDisplayedNameFallsBackToUsername(t *testing.T) { + source := nameResolver(t, &tg.User{ID: 10, AccessHash: 100, FirstName: "Someone else"}) + chat, err := source.Resolve(context.Background(), "mammad") + if err != nil || chat.ID != 99 { + t.Fatalf("username fallback failed: chat=%+v err=%v", chat, err) + } +} + +func TestResolveAmbiguousDisplayedNameDoesNotChoosePublicUsername(t *testing.T) { + source := nameResolver(t, &tg.User{ID: 10, AccessHash: 100, FirstName: "mammad"}, &tg.User{ID: 11, AccessHash: 110, FirstName: "mammad"}) + _, err := source.Resolve(context.Background(), "mammad") + if err == nil || !strings.Contains(err.Error(), "multiple") || !strings.Contains(err.Error(), "10") || !strings.Contains(err.Error(), "11") { + t.Fatalf("ambiguous name was not explained: %v", err) + } +} diff --git a/internal/telegram/source.go b/internal/telegram/source.go index fb834eb..f545822 100644 --- a/internal/telegram/source.go +++ b/internal/telegram/source.go @@ -32,22 +32,27 @@ import ( type Source struct { DownloadCustomEmoji bool - api *tg.Client - pool dcpool.Pool - manager *peers.Manager - chats map[string]tg.InputPeerClass - threads int - takeoutID int64 - ranges []tg.MessageRange - accountID int64 - self *tg.User - Warnings []string - since time.Time - until time.Time + // DownloadTimeout limits inactivity during history reads and media transfers. + DownloadTimeout time.Duration + api *tg.Client + pool dcpool.Pool + manager *peers.Manager + chats map[string]tg.InputPeerClass + nameDialogs []archive.Chat + namesLoaded bool + threads int + takeoutID int64 + ranges []tg.MessageRange + accountID int64 + self *tg.User + Warnings []string + since time.Time + until time.Time } func New(ctx context.Context, c *telegram.Client, kv storage.Storage, poolSize, threads int, timeout time.Duration, since, until time.Time) *Source { - return &Source{api: c.API(), pool: dcpool.NewPool(c, int64(poolSize), tclient.NewDefaultMiddlewares(ctx, timeout)...), manager: peers.Options{Storage: storage.NewPeers(kv)}.Build(c.API()), chats: map[string]tg.InputPeerClass{}, threads: threads, since: since, until: until} + middlewares := append(tclient.NewDefaultMiddlewares(ctx, timeout), DownloadActivityMiddleware()) + return &Source{api: c.API(), pool: dcpool.NewPool(c, int64(poolSize), middlewares...), manager: peers.Options{Storage: storage.NewPeers(kv)}.Build(c.API()), chats: map[string]tg.InputPeerClass{}, threads: threads, since: since, until: until, DownloadTimeout: DefaultDownloadTimeout} } // EnableTakeout explicitly starts Desktop's bulk export session. Do not use @@ -144,6 +149,10 @@ func (s *Source) Close(success bool) error { } func (s *Source) Resolve(ctx context.Context, ref string) (archive.Chat, error) { + ref = strings.TrimSpace(ref) + if ref == "" { + return archive.Chat{}, fmt.Errorf("chat reference cannot be empty") + } var p peers.Peer var err error if ref == "me" || ref == "self" { @@ -178,34 +187,19 @@ func (s *Source) Resolve(ctx context.Context, ref string) (archive.Chat, error) } } } else { - p, err = s.manager.Resolve(ctx, ref) - if err != nil { - dialogs, listErr := s.Dialogs(ctx, []string{"personal", "bots", "groups", "channels"}) - if listErr != nil { - return archive.Chat{}, fmt.Errorf("resolve chat %q: %w (search joined dialogs: %v)", ref, err, listErr) + if isDisplayNameReference(ref) { + chat, found, nameErr := s.resolveNamedChat(ctx, ref) + if nameErr != nil { + return archive.Chat{}, nameErr } - refName := strings.TrimPrefix(strings.TrimSpace(ref), "@") - var found []archive.Chat - for _, chat := range dialogs { - if strings.EqualFold(strings.TrimSpace(chat.Name), strings.TrimSpace(ref)) || - chat.Username != "" && strings.EqualFold(chat.Username, refName) { - found = append(found, chat) - } - } - if len(found) == 1 { - return found[0], nil - } - if len(found) > 1 { - ids := make([]string, 0, len(found)) - for _, chat := range found { - ids = append(ids, fmt.Sprintf("%d (%s)", chat.ID, chat.Type)) - } - return archive.Chat{}, fmt.Errorf("chat name %q matches multiple joined dialogs: %s; select by ID", ref, strings.Join(ids, ", ")) + if found { + return chat, nil } } + p, err = s.manager.Resolve(ctx, ref) } if err != nil { - return archive.Chat{}, fmt.Errorf("resolve chat %q: %w; for a private group, use its exact joined-dialog name or numeric ID", ref, err) + return archive.Chat{}, fmt.Errorf("resolve chat %q: %w; use the full displayed chat name, @username, Telegram URL or numeric ID", ref, err) } return s.addChat(p), nil } @@ -328,11 +322,17 @@ func (s *Source) Dialogs(ctx context.Context, types []string) ([]archive.Chat, e return chats, errors.Join(failures...) } -func (s *Source) History(ctx context.Context, chat archive.Chat, cursor string) (archive.Page, error) { +func (s *Source) History(ctx context.Context, chat archive.Chat, cursor string) (result archive.Page, rerr error) { p, ok := s.chats[chat.Key] if !ok { return archive.Page{}, fmt.Errorf("unresolved chat %q", chat.Key) } + name := chat.Name + if name == "" { + name = chat.Key + } + ctx, activity := watchDownload(ctx, "history for "+name, s.DownloadTimeout) + defer func() { rerr = activity.finish(rerr) }() offset := 0 rangeIndex := len(s.ranges) - 1 api := s.api @@ -459,6 +459,8 @@ func (s *Source) DownloadWithProgress(ctx context.Context, file archive.File, de if !ok { return fmt.Errorf("missing remote file location") } + ctx, activity := watchDownload(ctx, file.Path, s.DownloadTimeout) + defer func() { rerr = activity.finish(rerr) }() api := s.pool.Client(ctx, media.DC) if s.takeoutID != 0 { api = tg.NewClient(takeout.Middleware(s.takeoutID).Handle(api.Invoker())) @@ -469,8 +471,13 @@ func (s *Source) DownloadWithProgress(ctx context.Context, file archive.File, de } defer func() { rerr = errors.Join(rerr, f.Close()) }() var output io.WriterAt = f - if progress != nil { - output = downloadProgressWriter{output: f, progress: progress} + if activity != nil || progress != nil { + output = downloadProgressWriter{output: f, progress: func(n int64) { + activity.touch() + if progress != nil { + progress(n) + } + }} } _, err = downloader.NewDownloader().WithPartSize(transferdownload.MaxPartSize).Download(api, media.InputFileLoc).WithThreads(tutil.BestThreads(media.Size, s.threads)).Parallel(ctx, output) return err