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
29 changes: 29 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -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
31 changes: 31 additions & 0 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
@@ -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 }}
34 changes: 34 additions & 0 deletions .goreleaser.yaml
Original file line number Diff line number Diff line change
@@ -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
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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.
Expand Down
1 change: 1 addition & 0 deletions cmd/account.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
68 changes: 11 additions & 57 deletions cmd/archive.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"

Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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
Expand All @@ -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, ", "))
Expand Down
43 changes: 43 additions & 0 deletions cmd/backup_lock.go
Original file line number Diff line number Diff line change
@@ -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:
}
}
}
25 changes: 25 additions & 0 deletions cmd/cmd_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
34 changes: 32 additions & 2 deletions cmd/cron.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
package cmd

import (
"context"
"fmt"
"io"
"os"
"path/filepath"
"slices"
"sort"
"strings"
"text/tabwriter"
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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 != "" {
Expand All @@ -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
Expand Down Expand Up @@ -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) {
Expand Down
Loading
Loading