Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,19 @@
- Separate account backups, including Saved Messages and selectable account data.
- Recurring foreground sync and managed system cron jobs with per-job logs and
protection against overlapping runs of the same job.
- Archive and cron job completion summaries with message totals, media outcomes
by type, active filters, finish times and elapsed time. Counts are also saved
in structured reports and stay accurate across retries and skipped runs.
- Telegram Desktop export assets and formats; supported coverage and remaining
differences are documented in `docs/desktop-compatibility.md`.

### Fixed

- Convert poll answer variants from gotd v0.145.1 so the CLI builds with the
updated Telegram dependency.
- Continue backups after repeated Telegram timeouts for an optional thumbnail,
retaining the original media and reporting the unavailable preview. Existing
thumbnail warnings remain visible until a successful refresh replaces them.

### Removed

Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ Inspired by [tdl](https://github.com/iyear/tdl), ta uses its transfer and sessio
- Desktop-style JSON and offline HTML with local media.
- File-type, date and size filters.
- Parallel downloads with progress, resume and recovery.
- Archive and cron job results with message totals and media counts by type.
- Account data and Saved Messages backups.
- Incremental sync, refresh and cron schedules.
- Multiple saved Telegram accounts with separate cron backups.
Expand Down
21 changes: 20 additions & 1 deletion cmd/account.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"slices"
"strconv"
"strings"
"time"

"github.com/gotd/td/telegram"
"github.com/iyear/tdl/core/storage"
Expand Down Expand Up @@ -74,7 +75,15 @@ func NewAccount() *cobra.Command {
if threads < 1 || threads > 64 || pool < 1 || pool > 64 {
return fmt.Errorf("threads and pool must be between 1 and 64")
}
return tRun(cmd.Context(), func(ctx context.Context, c *telegram.Client, kv storage.Storage) (rerr error) {
recorder, err := archive.NewSummaryRecorder(f.output)
if err != nil {
return err
}
defer recorder.Close()
opts.SummaryRecorder = recorder
started := time.Now().UTC()
var finalReport archive.AccountReport
runErr := 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)) }()
Expand All @@ -89,6 +98,7 @@ func NewAccount() *cobra.Command {
}
dir := filepath.Join(f.output, "AccountExport_"+strconv.FormatInt(source.AccountID(), 10))
report, err := source.ExportAccount(ctx, dir, include, opts)
finalReport = report
for _, section := range report.Sections {
if section.Error != "" {
fmt.Fprintf(cmd.ErrOrStderr(), "%s: failed: %s\n", section.Name, section.Error)
Expand All @@ -99,6 +109,15 @@ func NewAccount() *cobra.Command {
fmt.Fprintln(cmd.OutOrStdout(), dir)
return err
})
status := archive.SummaryStatus(runErr, finalReport.Summary, finalReport.Warnings)
if errors.Is(cmd.Context().Err(), context.Canceled) {
status = "canceled"
}
fmt.Fprint(cmd.ErrOrStderr(), archive.SummaryText("Finished account backup", status, finalReport.Summary, time.Now(), time.Since(started)))
for _, warning := range finalReport.Warnings {
fmt.Fprintln(cmd.ErrOrStderr(), "Export:", warning)
}
return errors.Join(runErr, writeCompletion(completionPath(cmd), "account", started, finalReport.Summary, finalReport.Warnings, runErr, cmd.Context().Err()))
}
return cmd
}
64 changes: 58 additions & 6 deletions cmd/archive.go
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,15 @@ func newArchive(f *archiveFlags) *cobra.Command {
if len(f.chats) == 0 && !f.all {
f.chats = []string{"me"}
}
return tRunArchive(cmd.Context(), f.resume, cmd.ErrOrStderr(), func(ctx context.Context, c *telegram.Client, kv storage.Storage) (rerr error) {
recorder, err := archive.NewSummaryRecorder(f.output)
if err != nil {
return err
}
defer recorder.Close()
opts.SummaryRecorder = recorder
started := time.Now().UTC()
var finalReport archive.RunReport
runErr := 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)
Expand Down Expand Up @@ -165,16 +173,38 @@ func newArchive(f *archiveFlags) *cobra.Command {
progress := newBackupProgress(cmd.ErrOrStderr())
opts.OnPlan = progress.setPlan
opts.OnTransfer = progress.transfer
report, batchErr := archive.RunBatch(ctx, source, f.output, chats, opts, source.Warnings)
newWarnings := len(report.Warnings) != len(source.Warnings)
opts.OnChatFinished = func(entry archive.ChatExport) {
var failure error
if entry.Error != "" {
failure = errors.New(entry.Error)
}
status := archive.SummaryStatus(failure, entry.Summary, nil)
if errors.Is(ctx.Err(), context.Canceled) {
status = "canceled"
}
name := entry.Chat.Name
if name == "" {
name = entry.Chat.Key
}
progress.print(archive.SummaryText(fmt.Sprintf("Finished archive %q", name), status, entry.Summary, entry.Finished, entry.Finished.Sub(entry.Started)))
}
discoveryWarnings := slices.Clone(source.Warnings)
report, batchErr := archive.RunBatch(ctx, source, f.output, chats, opts, discoveryWarnings)
newWarnings := false
for _, warning := range source.Warnings {
if !slices.Contains(report.Warnings, warning) {
report.Warnings = append(report.Warnings, warning)
newWarnings = true
}
}
if newWarnings {
report.Warnings = source.Warnings
batchErr = errors.Join(batchErr, archive.WriteData(filepath.Join(f.output, "run-report.json"), report))
}
finalReport = report
resultErr := errors.Join(batchErr, err, ctx.Err())
progress.finish(resultErr)
if newWarnings {
for _, warning := range source.Warnings {
for _, warning := range report.Warnings {
if !slices.Contains(discoveryWarnings, warning) {
fmt.Fprintln(cmd.ErrOrStderr(), "Export:", warning)
}
}
Expand All @@ -185,6 +215,28 @@ func newArchive(f *archiveFlags) *cobra.Command {
}
return resultErr
})
status := archive.SummaryStatus(runErr, finalReport.Summary, finalReport.Warnings)
if errors.Is(cmd.Context().Err(), context.Canceled) {
status = "canceled"
}
if len(finalReport.Chats) == 0 {
finalReport.Summary = recorder.Total(f.output)
finalReport.Summary.HasMessages = true
finalReport.Summary.MessagesKnown = runErr == nil
finalReport.Summary.Filters = archive.SummaryFilters(opts)
status = archive.SummaryStatus(runErr, finalReport.Summary, finalReport.Warnings)
if errors.Is(cmd.Context().Err(), context.Canceled) {
status = "canceled"
}
fmt.Fprint(cmd.ErrOrStderr(), archive.SummaryText("Finished archive run", status, finalReport.Summary, time.Now(), time.Since(started)))
} else {
unit := "chat"
if len(finalReport.Chats) != 1 {
unit = "chats"
}
fmt.Fprintf(cmd.ErrOrStderr(), "Finished archive run | %s | %d %s | Elapsed %s\n", archive.CompletionLabel(status), len(finalReport.Chats), unit, time.Since(started).Round(time.Second))
}
return errors.Join(runErr, writeCompletion(completionPath(cmd), "archive", started, finalReport.Summary, finalReport.Warnings, runErr, cmd.Context().Err()))
}
flags := cmd.Flags()
flags.BoolVar(&f.refresh, "refresh", false, "refresh existing messages and reactions while retaining archived deletions")
Expand Down
44 changes: 44 additions & 0 deletions cmd/completion.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package cmd

import (
"context"
"encoding/json"
"errors"
"os"
"time"

"github.com/mo1ein/TelegramArchive/internal/archive"
"github.com/spf13/cobra"
)

const flagResultFile = "result-file"

func completionPath(cmd *cobra.Command) string {
flag := cmd.Root().PersistentFlags().Lookup(flagResultFile)
if flag == nil {
return ""
}
return flag.Value.String()
}
func writeCompletion(path, kind string, started time.Time, summary archive.Summary, warnings []string, err, contextErr error) error {
if path == "" {
return nil
}
report := archive.CompletionReport{Kind: kind, Status: archive.SummaryStatus(err, summary, warnings), Started: started, Finished: time.Now().UTC(), Summary: summary, Warnings: warnings}
if errors.Is(contextErr, context.Canceled) {
report.Status = "canceled"
}
if err != nil {
report.Error = err.Error()
}
return archive.WriteData(path, report)
}
func readCompletion(path string) (archive.CompletionReport, error) {
var report archive.CompletionReport
raw, err := os.ReadFile(path)
if err != nil {
return report, err
}
err = json.Unmarshal(raw, &report)
return report, err
}
70 changes: 70 additions & 0 deletions cmd/completion_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
package cmd

import (
"bytes"
"context"
"os"
"path/filepath"
"strings"
"testing"
"time"

"github.com/mo1ein/TelegramArchive/internal/archive"
"github.com/spf13/cobra"
bolt "go.etcd.io/bbolt"
)

func TestBackupCompletionCarriesChildSummaryToParent(t *testing.T) {
dir := t.TempDir()
result := filepath.Join(dir, "parent-result")
root := &cobra.Command{Use: "ta"}
root.PersistentFlags().String(flagResultFile, "", "")
child := newSync(func(_ context.Context, _ *cobra.Command, args []string) error {
var path string
for _, arg := range args {
if value, ok := strings.CutPrefix(arg, "--"+flagResultFile+"="); ok {
path = value
}
}
info, err := os.Stat(path)
if err != nil || info.Size() != 0 {
t.Fatalf("child did not receive a fresh result file: %v", err)
}
return archive.WriteData(path, archive.CompletionReport{Kind: "archive", Status: "complete_with_warnings", Started: time.Now(), Finished: time.Now(), Warnings: []string{"preview unavailable"}, Summary: archive.Summary{HasMessages: true, MessagesKnown: true, Messages: 3, MediaKnown: true, Media: map[string]archive.MediaCounts{"photos": {Downloaded: 2}, "thumbnails": {Unavailable: 1}}}})
})
root.AddCommand(child)
root.SetArgs([]string{"sync", "--chat=demo", "--output=" + dir, "--" + flagResultFile + "=" + result})
if err := root.ExecuteContext(context.Background()); err != nil {
t.Fatal(err)
}
report, err := readCompletion(result)
if err != nil || report.Kind != "backup" || report.Status != "complete_with_warnings" || report.Summary.Messages != 3 || report.Summary.Totals().Downloaded != 2 || report.Summary.Totals().Unavailable != 1 {
t.Fatalf("job lost child outcomes: %+v err=%v", report, err)
}
}

func TestSkippedBackupReportsSkipWithoutReusingOldSummary(t *testing.T) {
dir := t.TempDir()
result := filepath.Join(dir, "parent-result")
lock, err := bolt.Open(filepath.Join(dir, ".backup.lock"), 0600, nil)
if err != nil {
t.Fatal(err)
}
defer lock.Close()
old := []byte("previous active backup report")
if err = os.WriteFile(filepath.Join(dir, "backup-report.json"), old, 0600); err != nil {
t.Fatal(err)
}
root := &cobra.Command{Use: "ta"}
root.PersistentFlags().String(flagResultFile, "", "")
root.AddCommand(newSync(func(context.Context, *cobra.Command, []string) error { t.Fatal("busy backup executed"); return nil }))
root.SetArgs([]string{"sync", "--chat=demo", "--output=" + dir, "--skip-busy", "--" + flagResultFile + "=" + result})
if err = root.ExecuteContext(context.Background()); err != nil {
t.Fatal(err)
}
report, err := readCompletion(result)
current, _ := os.ReadFile(filepath.Join(dir, "backup-report.json"))
if err != nil || report.Status != "skipped" || report.Summary.Totals().Downloaded != 0 || !bytes.Equal(old, current) {
t.Fatalf("skip reused or overwrote active results: %+v err=%v", report, err)
}
}
2 changes: 1 addition & 1 deletion cmd/cron.go
Original file line number Diff line number Diff line change
Expand Up @@ -199,7 +199,7 @@ func cronArguments(cmd *cobra.Command) ([]string, map[string]string, error) {
var args []string
var optionErr error
cmd.Root().PersistentFlags().VisitAll(func(flag *pflag.Flag) {
if flag.Deprecated != "" || flag.Name == "proxy" {
if flag.Deprecated != "" || flag.Name == "proxy" || flag.Name == flagResultFile {
return
}
value := ""
Expand Down
39 changes: 38 additions & 1 deletion cmd/progress.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package cmd

import (
"errors"
"fmt"
"io"
"math"
Expand All @@ -22,6 +23,11 @@ type activeTransfer struct {
order uint64
}

type progressMessage struct {
text string
done chan struct{}
}

type backupProgress struct {
mu sync.Mutex
started, transferStarted time.Time
Expand All @@ -30,15 +36,17 @@ type backupProgress struct {
order uint64
bytes, completeBytes int64
completeFiles int64
unavailableThumbnails int64
finished bool
colorful bool
failure error
stop chan error
stopped, refresh chan struct{}
messages chan progressMessage
}

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)}
p := &backupProgress{started: time.Now(), active: map[string]activeTransfer{}, stop: make(chan error), stopped: make(chan struct{}), refresh: make(chan struct{}, 1), messages: make(chan progressMessage)}
fd, terminal := 0, false
if file, ok := output.(interface{ Fd() uintptr }); ok {
fd = int(file.Fd())
Expand Down Expand Up @@ -77,6 +85,14 @@ func newBackupProgress(output io.Writer) *backupProgress {
render()
for {
select {
case message := <-p.messages:
if terminal && drawn {
fmt.Fprint(output, "\x1b[3A\x1b[J")
}
fmt.Fprint(output, message.text)
drawn = false
render()
close(message.done)
case err := <-p.stop:
p.mu.Lock()
p.finished, p.failure = true, err
Expand All @@ -93,6 +109,12 @@ func newBackupProgress(output io.Writer) *backupProgress {
return p
}

func (p *backupProgress) print(message string) {
request := progressMessage{text: message, done: make(chan struct{})}
p.messages <- request
<-request.done
}

func (p *backupProgress) setPlan(plan archive.DownloadPlan) {
p.mu.Lock()
p.plan = plan
Expand Down Expand Up @@ -129,6 +151,14 @@ func (p *backupProgress) transfer(event archive.TransferEvent) {
if event.Err == nil {
p.completeFiles++
p.completeBytes += t.received
} else if event.File.Field == "thumbnail" && errors.Is(event.Err, archive.ErrThumbnailUnavailable) {
p.unavailableThumbnails++
p.bytes = max(0, p.bytes-t.received)
p.plan.Bytes = max(0, p.plan.Bytes-t.size)
p.plan.Files = max(0, p.plan.Files-1)
if t.size <= 0 {
p.plan.UnknownFiles = max(0, p.plan.UnknownFiles-1)
}
}
delete(p.active, key)
}
Expand Down Expand Up @@ -181,6 +211,13 @@ func (p *backupProgress) lines(now time.Time, width int) []string {
label = "Backup failed"
} else {
percent = 100
if p.unavailableThumbnails > 0 {
label += fmt.Sprintf(" · %d thumbnail", p.unavailableThumbnails)
if p.unavailableThumbnails != 1 {
label += "s"
}
label += " unavailable"
}
}
}
elapsed := max(0, now.Sub(p.started))
Expand Down
Loading
Loading