From 0d979e1b1520ce48de7c2942d226c8917f114a00 Mon Sep 17 00:00:00 2001 From: moein Date: Fri, 13 Nov 2026 21:17:07 +0330 Subject: [PATCH] feat: add interactive workspace and native macOS login Add a Bubble Tea workspace with guided commands, account and chat browsers, embedded task progress, prompts, and cancellation. Import native Telegram for macOS sessions with read-only readers and an offline verification mode. Stream dialog pages, expose structured account and cron output, and document setup and performance guidance. Require Go 1.26 for the terminal UI. --- CHANGELOG.md | 23 +- CONTRIBUTING.md | 2 +- README.md | 19 +- cmd/branding.go | 1 + cmd/cron.go | 10 + cmd/cron_test.go | 27 + cmd/desktop_login.go | 110 ++++ cmd/desktop_login_test.go | 109 ++++ cmd/identity.go | 56 +- cmd/identity_test.go | 26 + cmd/login_test.go | 116 ++++ cmd/native_login.go | 142 ++++ cmd/native_login_test.go | 189 ++++++ cmd/progress.go | 5 + cmd/progress_test.go | 10 + cmd/root.go | 10 +- cmd/tui.go | 47 ++ cmd/tui_chats.go | 115 ++++ cmd/tui_chats_test.go | 47 ++ cmd/tui_test.go | 93 +++ docs/README.md | 4 +- docs/configuration.md | 58 +- docs/macos.md | 161 +++++ docs/troubleshooting.md | 23 + docs/tui.md | 179 +++++ go.mod | 28 +- go.sum | 42 ++ internal/macsession/SOURCES.txt | 28 + internal/macsession/crypto.go | 116 ++++ internal/macsession/database.go | 237 +++++++ internal/macsession/plist.go | 278 ++++++++ internal/macsession/postbox.go | 98 +++ internal/macsession/read.go | 225 +++++++ internal/macsession/read_test.go | 266 ++++++++ internal/macsession/testdata/README.txt | 13 + .../macsession/testdata/authorization.bplist | Bin 0 -> 629 bytes .../testdata/foundation-authorization.bplist | Bin 0 -> 789 bytes .../testdata/foundation-authorization.m | 26 + .../foundation-mutable-authorization.bplist | Bin 0 -> 849 bytes internal/macsession/testdata/sqlcipher3.bin | Bin 0 -> 12288 bytes internal/macsession/testdata/sqlcipher4.bin | Bin 0 -> 12288 bytes internal/macsession/testdata/tempkey.enc | Bin 0 -> 64 bytes internal/macsession/wal.go | 97 +++ internal/taskui/chats.go | 9 + internal/taskui/progress.go | 18 + internal/telegram/dialogs.go | 17 +- internal/telegram/dialogs_test.go | 43 ++ internal/telegram/source.go | 43 +- internal/tui/catalog.go | 241 +++++++ internal/tui/failure.go | 29 + internal/tui/interaction.go | 384 +++++++++++ internal/tui/model.go | 612 ++++++++++++++++++ internal/tui/plan.go | 200 ++++++ internal/tui/pty_darwin.go | 36 ++ internal/tui/pty_linux.go | 34 + internal/tui/pty_other.go | 17 + internal/tui/pty_unix.go | 32 + internal/tui/results.go | 270 ++++++++ internal/tui/runner.go | 248 +++++++ internal/tui/task_test.go | 359 ++++++++++ internal/tui/task_view.go | 157 +++++ internal/tui/transcript.go | 185 ++++++ internal/tui/tui_test.go | 387 +++++++++++ internal/tui/view.go | 316 +++++++++ performance.md | 36 ++ 65 files changed, 6682 insertions(+), 27 deletions(-) create mode 100644 cmd/desktop_login.go create mode 100644 cmd/desktop_login_test.go create mode 100644 cmd/login_test.go create mode 100644 cmd/native_login.go create mode 100644 cmd/native_login_test.go create mode 100644 cmd/tui.go create mode 100644 cmd/tui_chats.go create mode 100644 cmd/tui_chats_test.go create mode 100644 cmd/tui_test.go create mode 100644 docs/macos.md create mode 100644 docs/tui.md create mode 100644 internal/macsession/SOURCES.txt create mode 100644 internal/macsession/crypto.go create mode 100644 internal/macsession/database.go create mode 100644 internal/macsession/plist.go create mode 100644 internal/macsession/postbox.go create mode 100644 internal/macsession/read.go create mode 100644 internal/macsession/read_test.go create mode 100644 internal/macsession/testdata/README.txt create mode 100644 internal/macsession/testdata/authorization.bplist create mode 100644 internal/macsession/testdata/foundation-authorization.bplist create mode 100644 internal/macsession/testdata/foundation-authorization.m create mode 100644 internal/macsession/testdata/foundation-mutable-authorization.bplist create mode 100644 internal/macsession/testdata/sqlcipher3.bin create mode 100644 internal/macsession/testdata/sqlcipher4.bin create mode 100644 internal/macsession/testdata/tempkey.enc create mode 100644 internal/macsession/wal.go create mode 100644 internal/taskui/chats.go create mode 100644 internal/taskui/progress.go create mode 100644 internal/tui/catalog.go create mode 100644 internal/tui/failure.go create mode 100644 internal/tui/interaction.go create mode 100644 internal/tui/model.go create mode 100644 internal/tui/plan.go create mode 100644 internal/tui/pty_darwin.go create mode 100644 internal/tui/pty_linux.go create mode 100644 internal/tui/pty_other.go create mode 100644 internal/tui/pty_unix.go create mode 100644 internal/tui/results.go create mode 100644 internal/tui/runner.go create mode 100644 internal/tui/task_test.go create mode 100644 internal/tui/task_view.go create mode 100644 internal/tui/transcript.go create mode 100644 internal/tui/tui_test.go create mode 100644 internal/tui/view.go create mode 100644 performance.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 4c8b45e..9d2cc9b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,12 +4,23 @@ ### Changed +- Require Go 1.26 or newer for the Bubble Tea v2 terminal interface. +- Open the interactive workspace when `ta` runs without arguments in a terminal; + piped invocations and `ta --help` continue to display command help. - **Breaking:** replace the Python application with the Go `ta` CLI. Build with - Go 1.25.8 or newer and log in again when moving from a Python/Telethon session. + Go 1.26 or newer and log in again when moving from a Python/Telethon session. - Use command flags and optional exported `TA_*` settings for configuration. ### Added +- `ta tui`: a responsive Bubble Tea workspace covering public commands and their + options, including installed extensions. Includes quick-start presets, + command and option search, common/advanced forms, inline validation, command + previews, path completion and keyboard help. Tasks stay in the TUI with + retained results, live progress, input prompts and cancellation. Native account, + chat and schedule browsers provide searchable lists, details and action + buttons; offline statistics show summary cards. Mouse and keyboard navigation + preserve list selection when opening follow-up workflows. - Install ta with `go install github.com/mo1ein/TelegramArchive/cmd/ta@latest` or `make install` from a local checkout. - Incremental JSON and offline HTML chat exports with local media, checkpoints, @@ -25,6 +36,16 @@ ### Fixed +- Stream chat-browser pages into the TUI before loading finishes, with visible + connection stages, bounded requests, proxy fallback support and partial + results retained when loading is stopped. Avoid fetching every forum's topics + before showing chats. +- Import native Telegram for macOS sessions, including the website-installed + client, with read-only SQLCipher/Postbox readers, local passcode support and + committed WAL snapshots. Preserve the native API profile and the Desktop + default. `ta login --check` verifies data without saving a login or connecting. +- Recognize sandboxed Telegram Desktop data on macOS and report access errors + with macOS permission guidance. - 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, diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index c8011a2..8a36004 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,6 +1,6 @@ # Contributing -ta is a Go CLI. Building requires Go 1.25.8 or newer. +ta is a Go CLI with a Bubble Tea v2 workspace. Building requires Go 1.26 or newer. Create a short-lived branch from `main` and keep each commit focused on one change. Describe the problem, resulting behavior and verification in your pull diff --git a/README.md b/README.md index 08a6d9a..d9ba258 100644 --- a/README.md +++ b/README.md @@ -19,14 +19,15 @@ Inspired by [tdl](https://github.com/iyear/tdl), ta uses its transfer and sessio - Incremental sync, refresh and cron schedules. - Multiple saved Telegram accounts with separate cron backups. - Offline rendering, statistics, uploads and forwarding. +- Interactive Bubble Tea workspace with chat/account browsers, action buttons and live task results. ## Installation -With Go 1.25.8 or newer installed, run: +With Go 1.26 or newer installed, run: ```sh go install github.com/mo1ein/TelegramArchive/cmd/ta@latest -ta --help +ta ``` Run the same `go install` command to update ta. Go installs the binary into @@ -46,11 +47,23 @@ To install a local checkout, including unpublished changes, run ## Quick start +Run `ta` or `ta tui` in a terminal to open the interactive workspace. Choose a +quick-start workflow or search every command with `/`. Edit options, press +`Ctrl+R` to review, then `Enter` to run. Login prompts and transfer progress +stay inside the workspace. Browse chats, switch accounts and manage schedules +from selectable lists with action buttons. [Workspace guide and shortcuts](docs/tui.md). + +The commands below also work directly: + ```sh ta login -T qr # use -T code for phone/code login ta archive --all --types channels --media all --format both ``` +On macOS, you can also import the login from your existing native Telegram app, +including the website download. See [macOS login setup](docs/macos.md) for Full +Disk Access, local passcodes, verification and import commands. + This exports every joined channel, including private channels and archived dialogs. Files go to `./data`. Open `data/export_results.html` to browse them. Resume is on by default. Rerun the same command to continue or fetch new messages. @@ -101,9 +114,11 @@ Click a preview to enlarge it. | Guide | Covers | | --- | --- | +| [Interactive workspace](docs/tui.md) | Search, guided forms, presets, advanced options, review and keyboard shortcuts | | [Archiving](docs/archiving.md) | Chat selection, media/date/size filters, custom names, resume, refresh, progress, JSON/HTML, offline rendering and statistics | | [Backups](docs/backups.md) | Account sections, Saved Messages, one-time sync, recurring sync, cron jobs and logs | | [Accounts and settings](docs/configuration.md) | Login, multiple terminals, proxies, storage, environment settings, transfer commands and build checks | +| [macOS login setup](docs/macos.md) | Native website client, data paths, Full Disk Access, passcodes, import and troubleshooting | | [Transfers and tools](docs/README.md#transfers-and-tools) | Downloads, uploads, forwarding, chat tools, templates, session tools, extensions and shell completion | | [Desktop export coverage](docs/desktop-compatibility.md) | Supported formats, fields and API limits | | [Contributing](CONTRIBUTING.md) | Development workflow and privacy checks | diff --git a/cmd/branding.go b/cmd/branding.go index 4007d2e..aeea38b 100644 --- a/cmd/branding.go +++ b/cmd/branding.go @@ -19,6 +19,7 @@ import ( ) func configureProductPaths() { + configureNativeApp() upstreamconsts.DataDir = consts.DataDir upstreamconsts.LogPath = consts.LogPath upstreamconsts.ExtensionsPath = filepath.Join(consts.DataDir, "extensions") diff --git a/cmd/cron.go b/cmd/cron.go index 092df7a..f65cf68 100644 --- a/cmd/cron.go +++ b/cmd/cron.go @@ -2,6 +2,7 @@ package cmd import ( "context" + "encoding/json" "fmt" "io" "os" @@ -74,11 +75,19 @@ func newCron(manager managedcron.Manager, execute managedcron.Runner) *cobra.Com add.Flags().MarkHidden("runs") add.Flags().MarkHidden("stop-on-error") + var listJSON bool list := &cobra.Command{Use: "list", Short: "List ta's cron backups", Args: cobra.NoArgs, Annotations: map[string]string{"offline": "true"}, RunE: func(cmd *cobra.Command, _ []string) error { jobs, err := manager.List(cmd.Context()) if err != nil { return err } + if listJSON { + rows := make([]map[string]any, 0, len(jobs)) + for _, job := range jobs { + rows = append(rows, map[string]any{"name": job.Name, "schedule": job.Schedule, "installed": job.Installed, "log": job.Log}) + } + return json.NewEncoder(cmd.OutOrStdout()).Encode(rows) + } if len(jobs) == 0 { fmt.Fprintln(cmd.OutOrStdout(), "No ta cron jobs. Add one with: ta cron add NAME --chat channel_username --every 6h") return nil @@ -94,6 +103,7 @@ func newCron(manager managedcron.Manager, execute managedcron.Runner) *cobra.Com } return out.Flush() }} + list.Flags().BoolVar(&listJSON, "json", false, "output scheduled backups as JSON") remove := &cobra.Command{Use: "remove NAME", Aliases: []string{"rm"}, Short: "Remove a cron backup; keep its archives and logs", Args: cobra.ExactArgs(1), Annotations: map[string]string{"offline": "true"}, RunE: func(cmd *cobra.Command, args []string) error { if err := manager.Remove(cmd.Context(), args[0]); err != nil { return err diff --git a/cmd/cron_test.go b/cmd/cron_test.go index e1503e3..fa92d69 100644 --- a/cmd/cron_test.go +++ b/cmd/cron_test.go @@ -3,6 +3,7 @@ package cmd import ( "bytes" "context" + "encoding/json" "errors" "io" "path/filepath" @@ -197,3 +198,29 @@ func TestCronInitialFailureKeepsInstalledSchedule(t *testing.T) { t.Fatal("initial failure removed retries", jobs, err) } } + +func TestCronJSONListDoesNotExposeExecutionCredentials(t *testing.T) { + viper.Reset() + defer viper.Reset() + dir := t.TempDir() + table := &testCronTable{} + manager := managedcron.Manager{Directory: filepath.Join(dir, "jobs"), Table: table} + job := managedcron.Job{Name: "synthetic", Schedule: "0 */6 * * *", Executable: "/usr/bin/true", Directory: dir, Arguments: []string{"sync", "--proxy=socks5://private-password@invalid"}, Environment: map[string]string{"TA_PROXY": "private-password"}, Log: filepath.Join(dir, "synthetic.log")} + if err := manager.Install(context.Background(), job); err != nil { + t.Fatal(err) + } + root := cronRoot(manager, nil) + root.SetArgs([]string{"cron", "list", "--json"}) + var output bytes.Buffer + root.SetOut(&output) + if err := root.ExecuteContext(context.Background()); err != nil { + t.Fatal(err) + } + var rows []map[string]any + if err := json.Unmarshal(output.Bytes(), &rows); err != nil { + t.Fatal(err) + } + if len(rows) != 1 || rows[0]["name"] != "synthetic" || strings.Contains(output.String(), "private-password") || rows[0]["environment"] != nil || rows[0]["arguments"] != nil { + t.Fatal("unsafe schedule summary") + } +} diff --git a/cmd/desktop_login.go b/cmd/desktop_login.go new file mode 100644 index 0000000..88246f5 --- /dev/null +++ b/cmd/desktop_login.go @@ -0,0 +1,110 @@ +package cmd + +import ( + "fmt" + "os" + "path/filepath" + "runtime" + + "github.com/mo1ein/TelegramArchive/consts" + "github.com/spf13/cobra" +) + +// Resolve macOS data locations before calling the transfer core's importer. +// The core only searches the unsandboxed Desktop location on macOS. +func prepareDesktopLogin(cmd *cobra.Command) (bool, error) { + if runtime.GOOS != "darwin" { + return false, nil + } + mode := cmd.Flags().Lookup("type") + if mode == nil || mode.Value.String() != "desktop" { + return false, nil + } + // The deprecated --code flag still bypasses Desktop import upstream. + if legacy := cmd.Flags().Lookup("code"); legacy != nil && legacy.Value.String() == "true" { + return false, nil + } + desktop := cmd.Flags().Lookup("desktop") + if desktop == nil { + return false, nil + } + source, err := findMacLoginSource(consts.HomeDir, desktop.Value.String()) + if err != nil { + return false, err + } + // This updates the actual options bound to the inherited login handler. + // Leave Changed intact: automatic discovery is not a user-supplied flag. + return source.native, desktop.Value.Set(source.path) +} + +type desktopSource struct { + path string + native bool +} + +// Only inspect directory metadata here, never session keys or message data. +func findMacDesktopData(home, explicit string) (string, error) { + source, err := findMacLoginSource(home, explicit) + return source.path, err +} + +func findMacLoginSource(home, explicit string) (desktopSource, error) { + candidates := []string{ + filepath.Join(home, "Library", "Application Support", "Telegram Desktop"), + filepath.Join(home, "Library", "Containers", "org.telegram.desktop", "Data", "Library", "Application Support", "Telegram Desktop"), + } + if explicit != "" { + candidates = []string{explicit} + } + var inaccessible error + for _, candidate := range candidates { + path := candidate + if filepath.Base(path) != "tdata" { + path = filepath.Join(path, "tdata") + } + info, err := os.Stat(path) + if err == nil && info.IsDir() { + return desktopSource{path: path}, nil + } + if err != nil && !os.IsNotExist(err) && inaccessible == nil { + inaccessible = fmt.Errorf("cannot access Telegram Desktop data at %q: %w", path, err) + } + } + if inaccessible != nil { + return desktopSource{}, inaccessible + } + native := []string{ + filepath.Join(home, "Library", "Group Containers", "6N38VWS5BX.ru.keepcoder.Telegram"), + filepath.Join(home, "Library", "Containers", "ru.keepcoder.Telegram"), + } + if explicit != "" { + root := explicit + if filepath.Base(root) == "atomic-state" { + root = filepath.Dir(filepath.Dir(root)) + } else if filepath.Base(root) == "accounts-metadata" { + root = filepath.Dir(root) + } + native = []string{root} + } + for _, root := range native { + for _, channel := range []string{"", "stable", "appstore", "beta"} { + path := filepath.Join(root, channel) + info, err := os.Stat(filepath.Join(path, "accounts-metadata", "atomic-state")) + if err == nil && info.Mode().IsRegular() { + return desktopSource{path: path, native: true}, nil + } + if err != nil && !os.IsNotExist(err) { + return desktopSource{}, fmt.Errorf("cannot read native Telegram metadata; give the app running ta Full Disk Access in macOS Privacy & Security, reopen it and retry: %w", err) + } + } + } + if explicit != "" { + return desktopSource{}, fmt.Errorf("no Telegram session data found at %q; -d must point to tdata, its parent data directory, or the native client's stable/appstore data directory, not the application bundle", explicit) + } + for _, path := range native { + if _, err := os.Stat(path); err == nil { + return desktopSource{}, fmt.Errorf("native Telegram for macOS was found but has no signed-in account metadata; open Telegram and sign in, then retry ta login") + } + } + return desktopSource{}, fmt.Errorf("no Telegram session data found in the standard or sandboxed macOS data locations; open Telegram and sign in, or specify its data directory with -d (not the application bundle)") +} diff --git a/cmd/desktop_login_test.go b/cmd/desktop_login_test.go new file mode 100644 index 0000000..16d9c5f --- /dev/null +++ b/cmd/desktop_login_test.go @@ -0,0 +1,109 @@ +package cmd + +import ( + "os" + "path/filepath" + "strings" + "testing" +) + +func TestMacDesktopDataDiscovery(t *testing.T) { + for _, location := range []string{ + "Library/Application Support/Telegram Desktop/tdata", + "Library/Containers/org.telegram.desktop/Data/Library/Application Support/Telegram Desktop/tdata", + } { + t.Run(location, func(t *testing.T) { + home := t.TempDir() + want := filepath.Join(home, filepath.FromSlash(location)) + if err := os.MkdirAll(want, 0700); err != nil { + t.Fatal(err) + } + got, err := findMacDesktopData(home, "") + if err != nil || got != want { + t.Fatalf("got=%q want=%q err=%v", got, want, err) + } + }) + } +} + +func TestMacDesktopExplicitPath(t *testing.T) { + home := t.TempDir() + parent := filepath.Join(home, "Custom Desktop") + want := filepath.Join(parent, "tdata") + if err := os.MkdirAll(want, 0700); err != nil { + t.Fatal(err) + } + for _, input := range []string{parent, want} { + got, err := findMacDesktopData(home, input) + if err != nil || got != want { + t.Fatalf("input=%q got=%q err=%v", input, got, err) + } + } + if _, err := findMacDesktopData(home, filepath.Join(home, "Telegram.app")); err == nil || !strings.Contains(err.Error(), "not the application bundle") { + t.Fatal(err) + } +} + +func TestMacNativeTelegramHasSpecificDiagnostic(t *testing.T) { + for _, location := range []string{ + "Library/Group Containers/6N38VWS5BX.ru.keepcoder.Telegram", + "Library/Containers/ru.keepcoder.Telegram", + } { + t.Run(location, func(t *testing.T) { + home := t.TempDir() + native := filepath.Join(home, filepath.FromSlash(location)) + if err := os.MkdirAll(native, 0700); err != nil { + t.Fatal(err) + } + _, err := findMacDesktopData(home, "") + if err == nil { + t.Fatal("native format must not be sent to the tdata decoder") + } + for _, want := range []string{"native Telegram for macOS", "no signed-in account metadata"} { + if !strings.Contains(err.Error(), want) { + t.Fatalf("missing %q: %v", want, err) + } + } + entries, err := os.ReadDir(native) + if err != nil || len(entries) != 0 { + t.Fatalf("discovery modified native data: %v", err) + } + }) + } +} + +func TestMacDesktopDataTakesPriorityOverNativeClient(t *testing.T) { + home := t.TempDir() + want := filepath.Join(home, "Library", "Application Support", "Telegram Desktop", "tdata") + for _, path := range []string{want, filepath.Join(home, "Library", "Containers", "ru.keepcoder.Telegram")} { + if err := os.MkdirAll(path, 0700); err != nil { + t.Fatal(err) + } + } + got, err := findMacDesktopData(home, "") + if err != nil || got != want { + t.Fatalf("got=%q err=%v", got, err) + } +} + +func TestMacDesktopMissingData(t *testing.T) { + _, err := findMacDesktopData(t.TempDir(), "") + if err == nil || !strings.Contains(err.Error(), "standard or sandboxed macOS") { + t.Fatal(err) + } +} + +func TestMacNativeClientSessionIsDiscoverable(t *testing.T) { + home := t.TempDir() + root := filepath.Join(home, "Library", "Group Containers", "6N38VWS5BX.ru.keepcoder.Telegram", "stable") + if err := os.MkdirAll(filepath.Join(root, "accounts-metadata"), 0700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(root, "accounts-metadata", "atomic-state"), []byte(`{"records":[]}`), 0600); err != nil { + t.Fatal(err) + } + got, err := findMacDesktopData(home, "") + if err != nil || got != root { + t.Fatalf("native client session root: got=%q err=%v", got, err) + } +} diff --git a/cmd/identity.go b/cmd/identity.go index 68ac419..ed3b11c 100644 --- a/cmd/identity.go +++ b/cmd/identity.go @@ -2,6 +2,7 @@ package cmd import ( "context" + "encoding/json" "errors" "fmt" "time" @@ -20,9 +21,27 @@ func wrapLoginIdentity(root *cobra.Command) { continue } login := command.RunE + command.Flags().Bool("check", false, "verify imported session data without saving a login or connecting to Telegram") + command.Flags().Lookup("desktop").Usage = "Telegram Desktop tdata or native macOS data directory; auto-detect if empty" command.Short = "Log in to the selected Telegram account namespace" - command.Long = "Log in to the selected namespace. Use ta accounts to see saved accounts and -n to choose one." + command.Long = "Log in to the selected namespace. Desktop session import is the default and supports Telegram Desktop tdata and the native Telegram for macOS client. Use --check to verify session data without saving it, -T qr for QR login, or -T code for phone/code login. Use ta accounts to see saved accounts and -n to choose one." command.RunE = func(cmd *cobra.Command, args []string) error { + check, _ := cmd.Flags().GetBool("check") + mode := cmd.Flags().Lookup("type") + legacy, _ := cmd.Flags().GetBool("code") + if check && (mode == nil || mode.Value.String() != "desktop" || legacy) { + return fmt.Errorf("--check applies to Desktop/native session imports; omit -T qr, -T code and --code") + } + native, err := prepareDesktopLogin(cmd) + if err != nil { + return err + } + if native { + return runNativeLogin(cmd, check) + } + if check { + return checkDesktopLogin(cmd) + } if err := login(cmd, args); err != nil { return err } @@ -51,18 +70,24 @@ func NewAccounts() *cobra.Command { } func newAccounts(list func(context.Context) ([]string, error), lookup func(context.Context, string) (int64, string, error)) *cobra.Command { - return &cobra.Command{ + var asJSON bool + command := &cobra.Command{ Use: "accounts", Short: "List saved Telegram accounts and their namespaces", 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 { + if asJSON { + // Keep partial rows machine-readable even when one account fails. + cmd.SilenceUsage = true + } namespaces, err := list(cmd.Context()) if err != nil { return err } selected := viper.GetString("ns") var failures []error + rows := []map[string]any{} for _, namespace := range namespaces { if err := cmd.Context().Err(); err != nil { return err @@ -78,21 +103,40 @@ func newAccounts(list func(context.Context) ([]string, error), lookup func(conte if err != nil { var busy *sessionBusyError if errors.As(err, &busy) { - fmt.Fprintf(cmd.OutOrStdout(), "%s [busy]%s\n", namespace, marker) + if asJSON { + rows = append(rows, map[string]any{"namespace": namespace, "status": "busy"}) + } else { + fmt.Fprintf(cmd.OutOrStdout(), "%s [busy]%s\n", namespace, marker) + } continue } - fmt.Fprintf(cmd.OutOrStdout(), "%s [unavailable]%s\n", namespace, marker) + if asJSON { + rows = append(rows, map[string]any{"namespace": namespace, "status": "unavailable"}) + } else { + 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 asJSON { + rows = append(rows, map[string]any{"namespace": namespace, "id": id, "username": username, "status": "ready"}) + } else { + fmt.Fprintf(cmd.OutOrStdout(), "%s %d %s%s\n", namespace, id, usernameOrPlaceholder(username), marker) + } } - if len(namespaces) == 0 { + if len(namespaces) == 0 && !asJSON { fmt.Fprintln(cmd.OutOrStdout(), "No saved accounts. Log in with ta login -T qr.") } + if asJSON { + if err := json.NewEncoder(cmd.OutOrStdout()).Encode(rows); err != nil { + return err + } + } return errors.Join(failures...) }, } + command.Flags().BoolVar(&asJSON, "json", false, "output saved accounts as JSON") + return command } func readSavedAccount(ctx context.Context, namespace string) (int64, string, error) { diff --git a/cmd/identity_test.go b/cmd/identity_test.go index f7ffa4e..a5cd692 100644 --- a/cmd/identity_test.go +++ b/cmd/identity_test.go @@ -3,6 +3,7 @@ package cmd import ( "bytes" "context" + "encoding/json" "errors" "fmt" "strings" @@ -89,3 +90,28 @@ func TestAccountLookupRestoresSelectedNamespaceAfterBusySession(t *testing.T) { t.Fatalf("err=%v selected=%s", err, viper.GetString("ns")) } } + +func TestAccountsJSONKeepsPartialRowsOnFailure(t *testing.T) { + command := newAccounts(func(context.Context) ([]string, error) { return []string{"ready", "expired"}, nil }, func(_ context.Context, name string) (int64, string, error) { + if name == "expired" { + return 0, "", errors.New("revoked") + } + return 42, "synthetic", nil + }) + var output bytes.Buffer + command.SetOut(&output) + command.SetArgs([]string{"--json"}) + if err := command.ExecuteContext(context.Background()); err == nil { + t.Fatal("partial failure was hidden") + } + var rows []struct { + Namespace, Status string + ID int64 + } + if err := json.Unmarshal(output.Bytes(), &rows); err != nil { + t.Fatal(err) + } + if len(rows) != 2 || rows[0].ID != 42 || rows[1].Status != "unavailable" { + t.Fatal("partial rows lost") + } +} diff --git a/cmd/login_test.go b/cmd/login_test.go new file mode 100644 index 0000000..ef80ade --- /dev/null +++ b/cmd/login_test.go @@ -0,0 +1,116 @@ +package cmd + +import ( + "errors" + "io" + "os" + "path/filepath" + "runtime" + "strings" + "testing" + + upstreamcmd "github.com/iyear/tdl/cmd" + "github.com/mo1ein/TelegramArchive/consts" + "github.com/spf13/cobra" + "github.com/spf13/viper" +) + +func TestLoginDefaultsToDesktop(t *testing.T) { + viper.Reset() + defer viper.Reset() + command, _, err := New().Find([]string{"login"}) + if err != nil { + t.Fatal(err) + } + mode := command.Flags().Lookup("type") + if mode.Value.String() != "desktop" || mode.DefValue != "desktop" { + t.Fatalf("plain ta login selects %s (documented default %s); want desktop", mode.Value.String(), mode.DefValue) + } + if mode.Changed { + t.Fatal("the default must not count as an explicit login-method choice") + } +} + +func TestLoginMethodSelection(t *testing.T) { + home := t.TempDir() + previousHome := consts.HomeDir + consts.HomeDir = home + t.Cleanup(func() { consts.HomeDir = previousHome }) + desktopPath := filepath.Join(home, "Library", "Application Support", "Telegram Desktop") + if err := os.MkdirAll(filepath.Join(desktopPath, "tdata"), 0700); err != nil { + t.Fatal(err) + } + for _, tc := range []struct { + name string + args []string + want string + }{ + {"desktop default", nil, "desktop"}, + {"phone login", []string{"-T", "code"}, "code"}, + {"explicit QR", []string{"-T", "qr"}, "qr"}, + {"legacy code bypasses Desktop", []string{"--code"}, "desktop"}, + {"desktop discovery", []string{"-T", "desktop"}, "desktop"}, + {"desktop path", []string{"-d", desktopPath}, "desktop"}, + {"desktop passcode", []string{"-p", "synthetic-passcode"}, "desktop"}, + {"explicit QR wins", []string{"-T", "qr", "-d", "/synthetic/Telegram Desktop"}, "qr"}, + } { + t.Run(tc.name, func(t *testing.T) { + root := &cobra.Command{Use: "ta"} + root.AddGroup(&cobra.Group{ID: "account", Title: "Accounts"}) + login := upstreamcmd.NewLogin() + // Stop at the authentication boundary, without reading or overwriting + // a real session or attempting to connect to Telegram. + stopped := errors.New("authentication boundary reached") + called := false + login.RunE = func(cmd *cobra.Command, _ []string) error { + called = true + if got := cmd.Flags().Lookup("type").Value.String(); got != tc.want { + t.Errorf("selected %s, want %s", got, tc.want) + } + legacy, _ := cmd.Flags().GetBool("code") + if runtime.GOOS == "darwin" && tc.want == "desktop" && !legacy { + if got, _ := cmd.Flags().GetString("desktop"); got != filepath.Join(desktopPath, "tdata") { + t.Errorf("Desktop importer received %q", got) + } + } + return stopped + } + root.AddCommand(login) + wrapLoginIdentity(root) + root.SetOut(io.Discard) + root.SetErr(io.Discard) + root.SetArgs(append([]string{"login"}, tc.args...)) + if err := root.Execute(); !errors.Is(err, stopped) || !called { + t.Fatalf("called=%v err=%v", called, err) + } + }) + } +} + +func TestMacNativeDesktopStopsBeforeImport(t *testing.T) { + if runtime.GOOS != "darwin" { + t.Skip("macOS login adapter") + } + home := t.TempDir() + if err := os.MkdirAll(filepath.Join(home, "Library", "Containers", "ru.keepcoder.Telegram"), 0700); err != nil { + t.Fatal(err) + } + previousHome := consts.HomeDir + consts.HomeDir = home + t.Cleanup(func() { consts.HomeDir = previousHome }) + root := &cobra.Command{Use: "ta"} + root.AddGroup(&cobra.Group{ID: "account", Title: "Accounts"}) + login := upstreamcmd.NewLogin() + login.RunE = func(*cobra.Command, []string) error { + t.Fatal("unsupported native data reached the session importer") + return nil + } + root.AddCommand(login) + wrapLoginIdentity(root) + root.SetOut(io.Discard) + root.SetErr(io.Discard) + root.SetArgs([]string{"login"}) + if err := root.Execute(); err == nil || !strings.Contains(err.Error(), "native Telegram for macOS") { + t.Fatal(err) + } +} diff --git a/cmd/native_login.go b/cmd/native_login.go new file mode 100644 index 0000000..769593b --- /dev/null +++ b/cmd/native_login.go @@ -0,0 +1,142 @@ +package cmd + +import ( + "context" + "errors" + "fmt" + "os" + "path/filepath" + "strconv" + + "github.com/AlecAivazis/survey/v2" + "github.com/gotd/td/session" + "github.com/gotd/td/session/tdesktop" + "github.com/iyear/tdl/core/storage" + "github.com/iyear/tdl/pkg/key" + sessionkv "github.com/iyear/tdl/pkg/kv" + client "github.com/iyear/tdl/pkg/tclient" + "github.com/iyear/tdl/pkg/tpath" + "github.com/mo1ein/TelegramArchive/consts" + "github.com/mo1ein/TelegramArchive/internal/macsession" + "github.com/spf13/cobra" + "github.com/spf13/viper" +) + +const nativeApp = "macos-native" + +// The direct-download native client uses this public application profile. +// Keeping it with the saved session avoids switching its API identity to tdata's. +func configureNativeApp() { + client.Apps[nativeApp] = client.App{AppID: 9, AppHash: "3975f648bb682ee889f35483bc618d1c"} +} + +func offlineCommand(cmd *cobra.Command) bool { + if cmd.Name() == "stats" || cmd.Annotations["offline"] == "true" { + return true + } + if cmd.Name() == "login" { + check, _ := cmd.Flags().GetBool("check") + return check + } + return false +} + +func runNativeLogin(cmd *cobra.Command, check bool) error { + path, _ := cmd.Flags().GetString("desktop") + passcode, _ := cmd.Flags().GetString("passcode") + var prompt func() (string, error) + if terminalFile(cmd.InOrStdin()) && terminalFile(cmd.ErrOrStderr()) { + prompt = func() (string, error) { + var value string + err := survey.AskOne(&survey.Password{Message: "Telegram local app passcode (not your two-step verification password):"}, &value, + survey.WithStdio(cmd.InOrStdin().(*os.File), cmd.ErrOrStderr().(*os.File), cmd.ErrOrStderr().(*os.File))) + return value, err + } + } + accounts, err := readNativeAccounts(cmd.Context(), path, passcode, prompt) + if err != nil { + return fmt.Errorf("read native Telegram session: %w", err) + } + defer func() { + for _, account := range accounts { + account.Clear() + } + }() + if check { + fmt.Fprintf(cmd.OutOrStdout(), "Native Telegram session data verified: %d authorized account(s). No login saved; no network connection made.\n", len(accounts)) + return nil + } + selected := 0 + if len(accounts) > 1 { + options := make([]string, len(accounts)) + for i, account := range accounts { + options[i] = strconv.FormatInt(account.UserID, 10) + } + if err := survey.AskOne(&survey.Select{Message: "Choose a native Telegram account:", Options: options}, &selected); err != nil { + return err + } + } + if err := cmd.Context().Err(); err != nil { + return err + } + namespace := viper.GetString("ns") + kv, err := sessionkv.From(cmd.Context()).Open(namespace) + if err != nil { + return err + } + fmt.Fprintln(cmd.ErrOrStderr(), "WARN: Existing ta login data in this namespace will be overwritten.") + loader := session.Loader{Storage: storage.NewSession(kv, true)} + if err := loader.Save(cmd.Context(), accounts[selected].Data); err != nil { + return err + } + if err := kv.Set(cmd.Context(), key.App(), []byte(nativeApp)); err != nil { + return err + } + fmt.Fprintf(cmd.OutOrStdout(), "Imported native Telegram account %d into namespace %q.\n", accounts[selected].UserID, namespace) + fmt.Fprintln(cmd.OutOrStdout(), "Quit Telegram for macOS before running other ta commands with this imported login; both use the same authorization. The source app's files were left unchanged.") + return nil +} + +// Prompt only when the default key fails. Explicit passcodes and noninteractive +// invocations keep their existing behavior; a failed retry never loops. +func readNativeAccounts(ctx context.Context, path, passcode string, prompt func() (string, error)) ([]macsession.Account, error) { + accounts, err := macsession.Read(ctx, path, passcode) + if !errors.Is(err, macsession.ErrPasscode) || passcode != "" || prompt == nil { + return accounts, err + } + if err := ctx.Err(); err != nil { + return nil, err + } + passcode, err = prompt() + if err != nil { + return nil, err + } + if passcode == "" { + return nil, macsession.ErrPasscode + } + return macsession.Read(ctx, path, passcode) +} + +func checkDesktopLogin(cmd *cobra.Command) error { + path, _ := cmd.Flags().GetString("desktop") + passcode, _ := cmd.Flags().GetString("passcode") + if path == "" { + for _, candidate := range tpath.Desktop.AppData(consts.HomeDir) { + accounts, err := tdesktop.Read(filepath.Join(candidate, "tdata"), []byte(passcode)) + if err == nil { + fmt.Fprintf(cmd.OutOrStdout(), "Telegram Desktop session data verified: %d account(s). No login saved.\n", len(accounts)) + return nil + } + } + return fmt.Errorf("no readable Telegram Desktop session data found; specify its directory with -d") + } + if filepath.Base(path) != "tdata" { + path = filepath.Join(path, "tdata") + } + accounts, err := tdesktop.Read(path, []byte(passcode)) + if err != nil { + return err + } + fmt.Fprintf(cmd.OutOrStdout(), "Telegram Desktop session data verified: %d account(s). No login saved.\n", len(accounts)) + return nil +} diff --git a/cmd/native_login_test.go b/cmd/native_login_test.go new file mode 100644 index 0000000..b313d3c --- /dev/null +++ b/cmd/native_login_test.go @@ -0,0 +1,189 @@ +package cmd + +import ( + "bytes" + "context" + "crypto/aes" + "crypto/cipher" + "crypto/sha512" + "errors" + "os" + "path/filepath" + "runtime" + "strings" + "testing" + + "github.com/gotd/td/session" + "github.com/iyear/tdl/core/storage" + sessionkv "github.com/iyear/tdl/pkg/kv" + client "github.com/iyear/tdl/pkg/tclient" + "github.com/mo1ein/TelegramArchive/internal/macsession" + "github.com/spf13/cobra" + "github.com/spf13/viper" +) + +func TestNativeLoginLocalPasscodePrompt(t *testing.T) { + path := nativeFixture(t) + file := filepath.Join(path, ".tempkeyEncrypted") + wrapped, err := os.ReadFile(file) + if err != nil { + t.Fatal(err) + } + // Rewrap the independent synthetic fixture with a local app passcode. + digest := sha512.Sum512([]byte("no-matter-key")) + block, _ := aes.NewCipher(digest[:32]) + plain := make([]byte, len(wrapped)) + cipher.NewCBCDecrypter(block, digest[48:]).CryptBlocks(plain, wrapped) + digest = sha512.Sum512([]byte("synthetic local passcode")) + block, _ = aes.NewCipher(digest[:32]) + cipher.NewCBCEncrypter(block, digest[48:]).CryptBlocks(wrapped, plain) + clear(plain) + if err := os.WriteFile(file, wrapped, 0600); err != nil { + t.Fatal(err) + } + for _, tc := range []struct { + name, supplied, entered string + interactive, wantPrompt, wantSuccess bool + }{ + {"prompt unlocks session", "", "synthetic local passcode", true, true, true}, + {"explicit passcode", "synthetic local passcode", "", true, false, true}, + {"wrong explicit passcode", "wrong", "", true, false, false}, + {"wrong prompt stops", "", "wrong", true, true, false}, + {"empty prompt cancels", "", "", true, true, false}, + {"noninteractive returns error", "", "", false, false, false}, + } { + t.Run(tc.name, func(t *testing.T) { + calls := 0 + var prompt func() (string, error) + if tc.interactive { + prompt = func() (string, error) { calls++; return tc.entered, nil } + } + accounts, err := readNativeAccounts(context.Background(), path, tc.supplied, prompt) + for _, account := range accounts { + account.Clear() + } + if tc.wantSuccess && (err != nil || len(accounts) != 1) { + t.Fatalf("expected authorized session: %v", err) + } + if !tc.wantSuccess && !errors.Is(err, macsession.ErrPasscode) { + t.Fatalf("expected passcode error: %v", err) + } + if (calls == 1) != tc.wantPrompt || calls > 1 { + t.Fatalf("unexpected prompt count: %d", calls) + } + }) + } + cancelled := errors.New("prompt cancelled") + if _, err := readNativeAccounts(context.Background(), path, "", func() (string, error) { return "", cancelled }); !errors.Is(err, cancelled) { + t.Fatalf("prompt cancellation lost: %v", err) + } + // Unprotected sessions never ask for a passcode. + accounts, err := readNativeAccounts(context.Background(), nativeFixture(t), "", func() (string, error) { + t.Fatal("unprotected session prompted") + return "", nil + }) + for _, account := range accounts { + account.Clear() + } + if err != nil { + t.Fatal(err) + } +} + +func nativeFixture(t *testing.T) string { + t.Helper() + root := t.TempDir() + for _, dir := range []string{"accounts-metadata", "account-123/postbox/db"} { + if err := os.MkdirAll(filepath.Join(root, dir), 0700); err != nil { + t.Fatal(err) + } + } + for source, dest := range map[string]string{"tempkey.enc": ".tempkeyEncrypted", "sqlcipher4.bin": "account-123/postbox/db/db_sqlite"} { + data, err := os.ReadFile(filepath.Join("..", "internal", "macsession", "testdata", source)) + if err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(root, dest), data, 0600); err != nil { + t.Fatal(err) + } + } + if err := os.WriteFile(filepath.Join(root, "accounts-metadata", "atomic-state"), []byte(`{"records":[{"id":"123","attributes":[]}]}`), 0600); err != nil { + t.Fatal(err) + } + return root +} + +func TestNativeLoginCheckDoesNotInitializeStorage(t *testing.T) { + if runtime.GOOS != "darwin" { + t.Skip("macOS discovery") + } + viper.Reset() + defer viper.Reset() + root := New() + var out bytes.Buffer + root.SetOut(&out) + root.SetErr(&out) + // An invalid storage driver proves --check never reaches storage setup. + root.SetArgs([]string{"--storage=type=invalid", "login", "--check", "-d", nativeFixture(t)}) + if err := root.ExecuteContext(context.Background()); err != nil { + t.Fatal(err) + } + if !strings.Contains(out.String(), "Native Telegram session data verified: 1") || strings.Contains(out.String(), "42") { + t.Fatal("check must report counts, not credentials or account identities") + } +} + +func TestNativeLoginStoresReadableSessionAndMatchingAPIProfile(t *testing.T) { + viper.Reset() + defer viper.Reset() + viper.Set("ns", "synthetic") + configureNativeApp() + store, err := sessionkv.New(sessionkv.DriverBolt, map[string]any{"path": t.TempDir()}) + if err != nil { + t.Fatal(err) + } + defer store.Close() + command := &cobra.Command{Use: "login"} + command.Flags().String("desktop", nativeFixture(t), "") + command.Flags().String("passcode", "", "") + command.SetContext(sessionkv.With(context.Background(), store)) + var output bytes.Buffer + command.SetOut(&output) + command.SetErr(&output) + if err := runNativeLogin(command, false); err != nil { + t.Fatal(err) + } + kv, err := store.Open("synthetic") + if err != nil { + t.Fatal(err) + } + loader := session.Loader{Storage: storage.NewSession(kv, false)} + data, err := loader.Load(context.Background()) + if err != nil { + t.Fatal(err) + } + if data.DC != 2 || len(data.AuthKey) != 256 { + t.Fatal("saved authorization is not readable by ta's client") + } + profile, err := client.GetApp(kv) + if err != nil || profile.AppID != 9 { + t.Fatal("native application identity was not preserved") + } + if !strings.Contains(output.String(), "Quit Telegram for macOS") { + t.Fatal("shared-session instructions missing") + } +} + +func TestLoginCheckRejectsInteractiveMethodsBeforeStorage(t *testing.T) { + for _, method := range []string{"qr", "code"} { + viper.Reset() + root := New() + root.SetOut(&bytes.Buffer{}) + root.SetErr(&bytes.Buffer{}) + root.SetArgs([]string{"--storage=type=invalid", "login", "--check", "-T", method}) + if err := root.ExecuteContext(context.Background()); err == nil || !strings.Contains(err.Error(), "--check applies") { + t.Fatal(err) + } + } + viper.Reset() +} diff --git a/cmd/progress.go b/cmd/progress.go index a5b01aa..d7622b8 100644 --- a/cmd/progress.go +++ b/cmd/progress.go @@ -15,6 +15,7 @@ import ( "github.com/jedib0t/go-pretty/v6/text" "github.com/mattn/go-runewidth" "github.com/mo1ein/TelegramArchive/internal/archive" + "github.com/mo1ein/TelegramArchive/internal/taskui" "golang.org/x/term" ) @@ -70,6 +71,10 @@ func newBackupProgress(output io.Writer) *backupProgress { } } lines := p.lines(time.Now(), width) + if terminal && os.Getenv("TA_TUI_CHILD") == "1" { + taskui.WriteProgress(output, lines) + return + } if terminal { if drawn { fmt.Fprint(output, "\x1b[3A") diff --git a/cmd/progress_test.go b/cmd/progress_test.go index b2b9803..0bb38b3 100644 --- a/cmd/progress_test.go +++ b/cmd/progress_test.go @@ -142,3 +142,13 @@ func TestBackupProgressKeepsArchiveSummaryVisible(t *testing.T) { t.Fatalf("summary was lost or corrupted in progress output: %q", text) } } + +func TestTUIProgressDoesNotWritePrivateFramesToPipedLogs(t *testing.T) { + t.Setenv("TA_TUI_CHILD", "1") + var output bytes.Buffer + progress := newBackupProgress(&output) + progress.finish(nil) + if strings.Contains(output.String(), "\x1b]777;") || !strings.Contains(output.String(), "Backup complete") { + t.Fatal("private UI progress escaped into a plain log") + } +} diff --git a/cmd/root.go b/cmd/root.go index 004c5f1..d4d77ea 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -17,6 +17,9 @@ 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.Args = cobra.NoArgs + root.RunE = runDefault + root.Annotations = map[string]string{"offline": "true"} root.PersistentFlags().String(flagResultFile, "", "private completion report for a parent backup process") root.PersistentFlags().MarkHidden(flagResultFile) root.PersistentFlags().Duration(flagDownloadTimeout, transport.DefaultDownloadTimeout, "inactivity limit for archive history reads and media transfers; 0 disables") @@ -27,17 +30,18 @@ func New() *cobra.Command { } } root.PersistentFlags().Lookup("ns").Usage = "saved Telegram login; concurrent terminals need separate namespaces (the same account is supported); list with ta accounts" - root.AddCommand(NewArchive(), NewStats(), NewRender(), NewSchedule(), NewAccount(), NewSync(), NewCron(), NewAccounts(), NewVersion(), newSessionRecover()) + root.AddCommand(NewArchive(), NewStats(), NewRender(), NewSchedule(), NewAccount(), NewSync(), NewCron(), NewAccounts(), NewVersion(), newSessionRecover(), NewTUI()) viper.SetEnvPrefix("TA") bindProductEnvironment(root) brandCommands(root) wrapLoginIdentity(root) + wrapTUIChatBrowser(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" { + if offlineCommand(cmd) { return nil } if err := prepareProductStorage(cmd); err != nil { @@ -56,7 +60,7 @@ func New() *cobra.Command { return nil } root.PersistentPostRunE = func(cmd *cobra.Command, args []string) error { - if cmd.Name() == "stats" || cmd.Annotations["offline"] == "true" { + if offlineCommand(cmd) { return nil } return post(cmd, args) diff --git a/cmd/tui.go b/cmd/tui.go new file mode 100644 index 0000000..49860e4 --- /dev/null +++ b/cmd/tui.go @@ -0,0 +1,47 @@ +package cmd + +import ( + "context" + "fmt" + "os" + + tea "charm.land/bubbletea/v2" + "github.com/mo1ein/TelegramArchive/internal/tui" + "github.com/spf13/cobra" + "github.com/spf13/viper" + "golang.org/x/term" +) + +func NewTUI() *cobra.Command { + return &cobra.Command{ + Use: "tui", Short: "Open the interactive command workspace", Args: cobra.NoArgs, + Annotations: map[string]string{"offline": "true"}, + RunE: runTUI, + } +} + +func terminalFile(stream any) bool { + file, ok := stream.(*os.File) + return ok && term.IsTerminal(int(file.Fd())) +} + +func runTUI(cmd *cobra.Command, _ []string) error { + if !terminalFile(cmd.InOrStdin()) || !terminalFile(cmd.OutOrStdout()) { + return fmt.Errorf("the interactive workspace needs a terminal; run ta tui in a terminal, or use ta --help for commands") + } + root := cmd.Root() + root.InitDefaultCompletionCmd() + taskCtx, cancel := context.WithCancel(cmd.Context()) + defer cancel() + model := tui.New(tui.Catalog(root), inheritedArguments(cmd), viper.GetString("ns"), taskCtx) + _, err := tea.NewProgram(model, tea.WithContext(cmd.Context()), tea.WithInput(cmd.InOrStdin()), tea.WithOutput(cmd.OutOrStdout())).Run() + return err +} + +func runDefault(cmd *cobra.Command, args []string) error { + if terminalFile(cmd.InOrStdin()) && terminalFile(cmd.OutOrStdout()) { + return runTUI(cmd, args) + } + // Piped invocations retain useful, script-friendly help output. + return cmd.Help() +} diff --git a/cmd/tui_chats.go b/cmd/tui_chats.go new file mode 100644 index 0000000..170bf22 --- /dev/null +++ b/cmd/tui_chats.go @@ -0,0 +1,115 @@ +package cmd + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "io" + "strings" + "time" + + "github.com/expr-lang/expr" + "github.com/gotd/td/telegram" + "github.com/iyear/tdl/app/chat" + "github.com/iyear/tdl/core/storage" + "github.com/iyear/tdl/pkg/texpr" + "github.com/mo1ein/TelegramArchive/internal/archive" + "github.com/mo1ein/TelegramArchive/internal/taskui" + transport "github.com/mo1ein/TelegramArchive/internal/telegram" + "github.com/spf13/cobra" + "github.com/spf13/viper" +) + +func wrapTUIChatBrowser(root *cobra.Command) { + command, _, err := root.Find([]string{"chat", "ls"}) + if err != nil || command.Name() != "ls" { + return + } + original := command.RunE + var stream bool + command.Flags().BoolVar(&stream, "tui-stream", false, "stream chat pages to the interactive workspace") + _ = command.Flags().MarkHidden("tui-stream") + command.RunE = func(cmd *cobra.Command, args []string) error { + if !stream { + return original(cmd, args) + } + cmd.SilenceUsage = true + filter, _ := cmd.Flags().GetString("filter") + return browseTUIChats(cmd.Context(), cmd.OutOrStdout(), filter, 90*time.Second, tRun) + } +} + +type chatBrowserRun func(context.Context, func(context.Context, *telegram.Client, storage.Storage) error) error + +func browseTUIChats(parent context.Context, out io.Writer, filter string, timeout time.Duration, run chatBrowserRun) error { + program, err := expr.Compile(filter, expr.AsBool()) + if err != nil { + return fmt.Errorf("chat filter: %w", err) + } + ctx, cancel := context.WithTimeout(parent, timeout) + defer cancel() + events := json.NewEncoder(out) + emit := func(stage string, items []*chat.Dialog) error { + var payload []byte + if items != nil { + var err error + payload, err = json.Marshal(items) + if err != nil { + return err + } + } + return events.Encode(taskui.ChatEvent{Kind: "chat-page", Stage: stage, Items: payload}) + } + if err := emit("Connecting to Telegram (up to 30 seconds)…", nil); err != nil { + return err + } + // A separate connection deadline stops silent reconnect loops before pages + // begin. Once connected, the full browse and individual pages stay bounded. + connectCtx, connectCancel := context.WithCancel(ctx) + defer connectCancel() + timer := time.AfterFunc(min(timeout, 30*time.Second), connectCancel) + defer timer.Stop() + count := 0 + err = run(connectCtx, func(child context.Context, client *telegram.Client, kv storage.Storage) error { + if !timer.Stop() { + return context.DeadlineExceeded + } + if err := emit("Connected · loading recent and archived chats…", nil); err != nil { + return err + } + source := transport.New(child, client, kv, viper.GetInt("pool"), viper.GetInt("threads"), viper.GetDuration("reconnect-timeout"), time.Time{}, time.Time{}) + defer source.Close(true) + return source.StreamDialogs(child, []string{"personal", "bots", "groups", "channels"}, func(page []archive.Chat) error { + rows := make([]*chat.Dialog, 0, len(page)) + for _, value := range page { + kind := "private" + if strings.HasSuffix(value.Type, "_channel") { + kind = "channel" + } else if strings.Contains(value.Type, "group") { + kind = "group" + } + row := &chat.Dialog{ID: value.ID, Type: kind, VisibleName: value.Name, Username: value.Username} + accepted, err := texpr.Run(program, row) + if err != nil { + return fmt.Errorf("chat filter: %w", err) + } + if accepted.(bool) { + rows = append(rows, row) + } + } + count += len(rows) + return emit(fmt.Sprintf("%d chats loaded · fetching next page…", count), rows) + }) + }) + if err != nil { + if parent.Err() != nil { + return parent.Err() + } + if ctx.Err() != nil || connectCtx.Err() != nil || errors.Is(err, context.DeadlineExceeded) { + return fmt.Errorf("chat loading timed out after %d chats; check your connection or set --proxy / TA_PROXY / ALL_PROXY, then retry", count) + } + return err + } + return emit(fmt.Sprintf("Loaded %d chats", count), nil) +} diff --git a/cmd/tui_chats_test.go b/cmd/tui_chats_test.go new file mode 100644 index 0000000..73de72b --- /dev/null +++ b/cmd/tui_chats_test.go @@ -0,0 +1,47 @@ +package cmd + +import ( + "bytes" + "context" + "encoding/json" + "strings" + "testing" + "time" + + "github.com/gotd/td/telegram" + "github.com/iyear/tdl/core/storage" + "github.com/mo1ein/TelegramArchive/internal/taskui" + "github.com/spf13/viper" +) + +func TestChatBrowserConnectionTimeoutExplainsFailure(t *testing.T) { + var output bytes.Buffer + started := time.Now() + err := browseTUIChats(context.Background(), &output, "true", 25*time.Millisecond, func(ctx context.Context, _ func(context.Context, *telegram.Client, storage.Storage) error) error { + <-ctx.Done() + return ctx.Err() + }) + if err == nil || !strings.Contains(err.Error(), "timed out") || !strings.Contains(err.Error(), "ALL_PROXY") { + t.Fatalf("unhelpful timeout: %v", err) + } + if time.Since(started) > time.Second { + t.Fatal("connection timeout not enforced") + } + var event taskui.ChatEvent + if json.Unmarshal(bytes.Split(output.Bytes(), []byte{'\n'})[0], &event) != nil || !strings.Contains(event.Stage, "Connecting") { + t.Fatal("connection stage was not published before waiting") + } +} +func TestTUIChatStreamIsHiddenAndOrdinaryCLIUnchanged(t *testing.T) { + viper.Reset() + defer viper.Reset() + root := New() + command, _, err := root.Find([]string{"chat", "ls"}) + if err != nil { + t.Fatal(err) + } + flag := command.Flags().Lookup("tui-stream") + if flag == nil || !flag.Hidden || flag.DefValue != "false" { + t.Fatal("stream flag exposed or default CLI altered") + } +} diff --git a/cmd/tui_test.go b/cmd/tui_test.go new file mode 100644 index 0000000..8384a69 --- /dev/null +++ b/cmd/tui_test.go @@ -0,0 +1,93 @@ +package cmd + +import ( + "bytes" + "context" + "strings" + "testing" + + "github.com/mo1ein/TelegramArchive/internal/tui" + "github.com/spf13/cobra" + "github.com/spf13/pflag" + "github.com/spf13/viper" +) + +func TestTUICoversPublicCommandsAndOptions(t *testing.T) { + viper.Reset() + defer viper.Reset() + root := New() + root.InitDefaultCompletionCmd() + actions := tui.Catalog(root) + found := map[string]bool{} + for _, action := range actions { + path := strings.Join(action.Path, " ") + found[path] = true + form := tui.NewForm(action, nil) + fields := map[string]bool{} + for _, f := range form.Fields { + fields[f.Name] = true + } + flags := pflag.NewFlagSet("check", pflag.ContinueOnError) + flags.AddFlagSet(action.Command.InheritedFlags()) + flags.AddFlagSet(action.Command.Flags()) + flags.VisitAll(func(f *pflag.Flag) { + if !f.Hidden && f.Deprecated == "" && f.Name != "help" && f.Name != "version" && !fields[f.Name] { + t.Errorf("%s missing --%s", path, f.Name) + } + }) + if action.Group == "Quick start" && path != "cron add" { + plan, err := form.Plan(nil) + if err != nil { + t.Fatalf("preset %s: %v", action.Title, err) + } + // Parse presets through the real definitions without running hooks or Telegram. + clone := New() + leaf, args, err := clone.Find(plan.Args) + if err != nil { + t.Fatal(err) + } + if err := leaf.ParseFlags(args); err != nil { + t.Fatal(action.Title, err) + } + } + } + for _, path := range []string{"archive", "account", "sync", "cron add", "cron list", "cron logs", "cron remove", "cron run", "schedule", "login", "accounts", "download", "upload", "forward", "chat ls", "chat export", "chat users", "render", "stats", "backup", "recover", "migrate", "extension install", "extension list", "extension remove", "extension upgrade", "completion bash", "completion zsh", "completion fish", "completion powershell", "version"} { + if !found[path] { + t.Errorf("missing %s", path) + } + } + if found["tui"] { + t.Fatal("workspace must not recursively launch itself") + } +} + +func TestTUIAndRootDoNotOpenSessionForHelpOrPipes(t *testing.T) { + for _, args := range [][]string{nil, {"tui", "--help"}, {"tui"}, {"typo-command"}} { + viper.Reset() + root := New() + root.SetIn(strings.NewReader("")) + var out bytes.Buffer + root.SetOut(&out) + root.SetErr(&out) + root.SetArgs(args) + root.PersistentPreRunE = func(cmd *cobra.Command, _ []string) error { + if cmd.Annotations["offline"] != "true" { + t.Fatal("TUI initialized Telegram storage") + } + return nil + } + err := root.ExecuteContext(context.Background()) + if len(args) == 1 && args[0] == "tui" { + if err == nil || !strings.Contains(err.Error(), "needs a terminal") { + t.Fatal(err) + } + } else if len(args) == 1 && args[0] == "typo-command" { + if err == nil { + t.Fatal("unknown command opened the UI") + } + } else if err != nil || !strings.Contains(out.String(), "tui") { + t.Fatalf("args=%v err=%v output=%s", args, err, out.String()) + } + } + viper.Reset() +} diff --git a/docs/README.md b/docs/README.md index 82f75cd..ce32269 100644 --- a/docs/README.md +++ b/docs/README.md @@ -2,7 +2,7 @@ [Project README](../README.md) -Install ta with Go 1.25.8 or newer: +Install ta with Go 1.26 or newer: ```sh go install github.com/mo1ein/TelegramArchive/cmd/ta@latest @@ -16,9 +16,11 @@ See [installation and PATH setup](../README.md#installation), or run | Guide | Covers | | --- | --- | +| [Interactive workspace](tui.md) | Native result lists, account/chat browsers, action buttons, live progress and keyboard shortcuts | | [Archiving](archiving.md) | Chat selection, media filters, resume, refresh, progress, JSON/HTML, rendering and statistics | | [Backups](backups.md) | Account data, Saved Messages, incremental sync, cron jobs and scheduling | | [Accounts and settings](configuration.md) | Login modes, namespaces, concurrent terminals and development checks | +| [macOS login setup](macos.md) | Native website client, Full Disk Access, data paths, local passcodes and import troubleshooting | | [Global options](global-options.md) | Proxy, storage, concurrency, connection settings and environment variables | | [Desktop coverage](desktop-compatibility.md) | Supported formats, fields and API limits | diff --git a/docs/configuration.md b/docs/configuration.md index 047d7e0..37cc7f3 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -2,7 +2,7 @@ [Back to README](../README.md) -Log in with QR, phone/code or a Telegram Desktop session: +Log in with QR, phone/code or a Telegram Desktop session (the default): ```sh ta login -T qr @@ -10,6 +10,54 @@ ta login -T code ta login -T desktop ``` +Desktop import supports both the `tdata` format from +[Telegram Desktop](https://desktop.telegram.org/) and the Postbox session format +of native [Telegram for macOS](https://macos.telegram.org/), including the website +download. It discovers the installed client's data without changing the default +login method. + +For the native website client on macOS, follow the +[macOS login guide](macos.md) for Full Disk Access and the full import process. +Verify its session before saving a login, using an explicit path to select it +when Telegram Desktop is also installed: + +```sh +ta login --check -d "$HOME/Library/Group Containers/6N38VWS5BX.ru.keepcoder.Telegram/stable" +ta login -d "$HOME/Library/Group Containers/6N38VWS5BX.ru.keepcoder.Telegram/stable" +``` + +`--check` decrypts and validates the saved authorization locally, reports the +number of usable accounts, and exits without writing a ta login or connecting +to Telegram. If the native client has a local app passcode, an interactive +terminal asks for it with a masked prompt. This is the local app passcode, not +the two-step verification password. Scripts can supply it with `-p`. +The TUI masks this field and hides it in command previews. + +Import opens Telegram's files read-only, authenticates encrypted database pages, +and reads only account metadata and authorization tables. It leaves the source +session intact. Quit the native Telegram app before using the imported login in +other ta commands: the two clients share its authorization key. + +If macOS denies access to the Group Containers directory, enable **Full Disk +Access** for the app running the command (Terminal, iTerm or Codex), quit and +reopen that app, then retry. This is an operating-system permission; choosing a +different directory cannot grant it. + +To import Desktop data from a custom location, use +`ta login -d "/path/to/Telegram Desktop"` (the `tdata` directory itself is also +accepted). A native data directory can also be supplied with +`ta login -d "$HOME/Library/Group Containers/6N38VWS5BX.ru.keepcoder.Telegram/stable"`. +The group directory, `accounts-metadata` directory and `atomic-state` file are +accepted too. QR and phone/code login do not require either desktop app. + +On macOS, discovery checks both `~/Library/Application Support/Telegram Desktop` +and `~/Library/Containers/org.telegram.desktop/Data/Library/Application Support/Telegram Desktop`. +It also checks the native client's `stable`, `appstore` and `beta` data channels +under its Group Containers directory. Read permission errors are reported +instead of being treated as missing data. Synthetic SQLCipher 3/4 fixtures cover +passcodes, integrity checks, committed WAL snapshots and session storage; client +database/schema changes that are not recognized fail without modifying the source. + List saved logins or choose a namespace: ```sh @@ -28,7 +76,8 @@ IDs mean the same account, even when the namespace names differ. Existing archiv 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`. +Native macOS import prints the imported account ID. Other login methods also +retrieve the 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. There is no `.env` loading. Docker and Python are not required. @@ -69,6 +118,11 @@ Update `--storage` or `TA_STORAGE` too if you set either explicitly. ## Other commands and development +Run `ta` or `ta tui` to configure and run commands in the +[interactive workspace](tui.md). Start it with `ta --ns work tui` to select a +saved account, or edit the namespace field in any workflow. The workspace opens +without connecting to Telegram or locking a saved session. + | Command | Purpose | | --- | --- | | `chat ls`, `chat users` | List chats or export channel users | diff --git a/docs/macos.md b/docs/macos.md new file mode 100644 index 0000000..b500a35 --- /dev/null +++ b/docs/macos.md @@ -0,0 +1,161 @@ +# Telegram login on macOS + +[Documentation index](README.md) · [Accounts and settings](configuration.md) + +ta can import an existing login from both Telegram Desktop (`tdata`) and the +native Telegram for macOS client (Postbox). The native client downloaded from +the Telegram website is supported; you do not need to install the App Store +version or switch clients. Desktop session import remains the default login +method. + +This guide uses `./bin/ta` from a local checkout. Build it with `make build` from +the repository root. If you installed ta on your PATH, use `ta` in place of +`./bin/ta` and make sure that installation includes native macOS import support. + +## 1. Find the client's data directory + +Open Telegram and sign in before importing. The native website client's stable +data directory is: + +```text +~/Library/Group Containers/6N38VWS5BX.ru.keepcoder.Telegram/stable +``` + +Use `$HOME` inside double quotes in commands. The `-d` flag takes the **data +directory**, not `/Applications/Telegram.app`. + +Automatic discovery checks Telegram Desktop's `tdata` locations first, then the +native client's `stable`, `appstore` and `beta` channels. If you have both +clients, use an explicit `-d` path to select the native one. Other detected +locations include: + +| Client | Data location | +| --- | --- | +| Telegram Desktop | `~/Library/Application Support/Telegram Desktop/tdata` | +| Sandboxed Telegram Desktop | `~/Library/Containers/org.telegram.desktop/Data/Library/Application Support/Telegram Desktop/tdata` | +| Native Telegram channels | `~/Library/Group Containers/6N38VWS5BX.ru.keepcoder.Telegram/{stable,appstore,beta}` | + +The braces in the last row describe alternatives; choose the directory your +client actually uses. No data needs to be moved or copied. + +## 2. Allow access to protected Telegram files + +If the command reports `operation not permitted`, `PermissionError` or +`macOS denied access`, open **System Settings → Privacy & Security → Full Disk +Access**. + +1. Enable the application running ta: Terminal, iTerm, Ghostty, or the app + providing your integrated terminal. +2. If it is missing, use **+** to add it. Apple's Terminal is at + `/System/Applications/Utilities/Terminal.app`. +3. Fully quit and reopen that application before retrying. Closing a terminal + window alone may leave the application running. + +Full Disk Access grants that application access to protected user files beyond +Telegram. Enable it for the application you intend to run ta from. An entry +that is listed with its switch off does not have access. + +For Codex or another coding agent, grant access to the process that actually +runs the command. Permission for ChatGPT or a terminal does not automatically +cover a separate Codex background executable. In the setup verified during +development, that executable was installed under: + +```text +~/.codex/packages/app-server-daemon/releases//bin/codex +``` + +Use the current executable for your installation, not the literal `` +placeholder. In the add-file dialog, **Command+Shift+G** lets you enter a hidden +path. Restart the owning app or background service after granting access; an +already running background process may still be denied. You can instead run +the check in a freshly reopened Terminal with its own Full Disk Access enabled. + +Changing `-d`, rebuilding ta, or using `sudo` is not a substitute for granting +the correct application's macOS privacy permission. + +## 3. Verify the native session without saving it + +Run only the command in this block: + +```sh +./bin/ta login --check -d "$HOME/Library/Group Containers/6N38VWS5BX.ru.keepcoder.Telegram/stable" +``` + +If Telegram has a local app passcode, ta asks for it with a masked prompt. Enter +the passcode that unlocks the native Telegram app. This is separate from your +Telegram two-step verification password and your macOS login password. You do +not need to disable Telegram's passcode protection. + +Use the prompt to keep the passcode out of shell history. Scripts can supply +`-p`, but command-line arguments can be visible to other processes. Do not +include the passcode in shared commands, logs or bug reports. + +A successful check looks like this: + +```text +Native Telegram session data verified: 1 authorized account(s). No login saved; no network connection made. +``` + +The count depends on your signed-in accounts. `--check` decrypts and validates +authorization locally. It does not save a ta login, connect to Telegram, or +prove that the server will accept a later connection. + +## 4. Import, then use ta + +Once verification succeeds, remove `--check`: + +```sh +./bin/ta login -d "$HOME/Library/Group Containers/6N38VWS5BX.ru.keepcoder.Telegram/stable" +``` + +Enter the local passcode again when prompted. If multiple usable accounts are +found, choose one. Import saves the authorization into the selected namespace +(`default` unless you set `-n`). It overwrites an existing ta login there; choose +a separate namespace if you want to keep it: + +```sh +./bin/ta -n native login -d "$HOME/Library/Group Containers/6N38VWS5BX.ru.keepcoder.Telegram/stable" +``` + +Quit Telegram for macOS before running other ta commands with the imported +login. The app and ta share the imported authorization key; concurrent main +connections can cause Telegram to invalidate it. Import reads Telegram's files +without changing them or logging the source app out. + +Import saves authorization, not the native app's proxy configuration. If +Telegram needs a proxy on your network, supply one to ta with `--proxy` or +`TA_PROXY`. For a local SOCKS5 proxy listening on port 10808, open the TUI with +`./bin/ta --proxy=socks5://127.0.0.1:10808`. Use your proxy's actual port. + +For the default namespace, open the TUI with: + +```sh +./bin/ta +``` + +If you imported into `native`, keep selecting that namespace: + +```sh +./bin/ta -n native tui +``` + +Use [independent logins](configuration.md) for concurrent sessions. You can +later remove the temporary Full Disk Access grant from System Settings if you +no longer need to read Telegram's protected source files. Reimporting requires +access again. + +## Troubleshooting + +| Symptom | Next step | +| --- | --- | +| `no data found in possible paths` or `no Telegram session data found` | Use a current build, open Telegram and sign in, then supply its data directory with `-d`. The native client does not use `tdata`. | +| `operation not permitted` or `macOS denied access` | Check that Full Disk Access is on for the actual command host, then fully quit and reopen it. A background agent may need its own grant and restart. | +| `native Telegram database key could not be unlocked` | Verify the passcode by unlocking Telegram itself, then retry and enter it in ta's prompt. If that same passcode still fails, report the error; it can also indicate a damaged or unsupported key wrapper. | +| `unsupported or malformed native authorization archive` | Update/rebuild ta and retry. The importer supports direct `NSData` and `NSMutableData` wrappers. If it still fails, share the final error line, including its field/type/size diagnostic, without session files or passcodes. | +| `Telegram database changed during import` or a transaction/snapshot error | Quit Telegram completely, then retry the check against a stable snapshot. | +| `zsh: no matches found: ?` | A prompt/output line was pasted into the shell. Copy only commands from `sh` blocks; type the passcode when ta displays its prompt. | + +The native website client was verified on macOS with a local passcode: both the +read-only check and import into a ta namespace succeeded. That verification did +not test a subsequent live Telegram connection. New client database formats may +need importer updates; ta rejects unsupported data without modifying the source. diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index f468238..9c2ce20 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -2,8 +2,31 @@ [Documentation index](README.md) +## Telegram login on macOS + +See [macOS login setup](macos.md) for the native website client's data directory, +Full Disk Access for Terminal or a coding agent, masked local passcode prompts, +and read-only verification before import. Its +[troubleshooting table](macos.md#troubleshooting) covers permission errors, +key-unlock failures, unsupported authorization archives and pasted shell prompts. + ## Connection timeouts or EOF +If **Browse your chats** stays on a loading screen, use a current build. The +browser reports its connection stage and shows each chat page as it arrives. +Connection setup times out after 30 seconds. On failure, Activity shows the +reason and **Connection settings** opens the proxy field. If some chats have +arrived, **Stop loading** keeps them and enables their action buttons. Quit +native Telegram while using a login imported from it. + +A successful `ping telegram.org` tests ICMP reachability to that address. It does +not test Telegram's API connection: ta uses MTProto to a data-centre endpoint +over TCP. Website traffic, ICMP and API traffic can have different routes or +filtering. See Telegram's [transport](https://core.telegram.org/mtproto/transports) +and [data-centre](https://core.telegram.org/api/datacenter) documentation. A direct +timeout that succeeds through a proxy points to a problem with the direct route; +ping alone does not identify where the problem is. + Check your connection and proxy. These are examples; replace the proxy address with your own: ```sh diff --git a/docs/tui.md b/docs/tui.md new file mode 100644 index 0000000..b8da0e3 --- /dev/null +++ b/docs/tui.md @@ -0,0 +1,179 @@ +# Interactive workspace + +[Documentation index](README.md) + +The Bubble Tea interface keeps browsing, task progress, prompts and results in +one screen. Select accounts and chats from lists, use action buttons, and inspect +results without returning to a CLI prompt. + +```sh +ta # open the workspace +ta tui # open it explicitly +ta --ns work tui # start with a saved account namespace +ta --proxy socks5://localhost:1080 tui +``` + +From a local checkout, build with `make build` and run `./bin/ta`. Opening the +workspace does not connect to Telegram or lock a saved session. Selecting an +account or chat browser starts its read operation; backups and other changes go +through configuration and review. Ordinary CLI commands remain available, and +`ta` displays help when its input or output is redirected. + +## Browse and act + +Start with the dashboard's buttons or the first three Quick start workflows: + +| Browser | Results and actions | +| --- | --- | +| Chats | Search and select chats, inspect details, then choose Archive, Export or Members. The selected chat ID is filled in for you. | +| Accounts | See saved namespaces and their status. Use account applies the selected namespace to subsequent workflows. Busy or unavailable accounts cannot be activated. | +| Scheduled backups | Select a schedule to run its backup, view logs or remove the schedule. Running and removal require review; removal keeps archives and logs. | + +The chat browser shows each page as it arrives, including archived chats. It +reports connection and loading stages instead of waiting for every chat and +forum topic. Connection setup is limited to 30 seconds, page requests to 20 +seconds, and a browse to 90 seconds. If loading is slow, **Stop loading** keeps +received chats and enables their action buttons. Errors with no results open +Activity so the reason is visible. The browser uses the same proxy settings and +fallback environment variables as archive operations. + +Lists support ↑/↓, mouse selection, wheel scrolling and `/` search. Enter or the +Details button opens the selected item's details. The **Results**, **Activity** +and **Details** tabs are also clickable. Account results remain available when +another saved account fails to load. + +After opening an archive, export or schedule action from a list, **Back to list** +restores the original results, search and selection. You do not need to fetch the +list again. Follow-up forms use the current account namespace. + +Reopening the same chat browser in this workspace shows its last successful +list immediately, with a saved time. Choose **Refresh** to fetch current chats. +The cache holds up to eight lists in memory, keyed by account, filters and +connection settings. Nothing is saved to a chat-cache file, and restarting ta +requires a fresh load. Login, recovery and migration tasks clear cached lists. + +Offline statistics have summary cards and selectable totals and breakdowns. +Other tools retain their output in the Activity view. You can edit settings, +review another run, or return Home from the result screen. + +## Buttons and navigation + +Click a bottom action button, or use **F6** to move focus between the current +panel and its buttons. When buttons have focus, Tab/Shift+Tab or ←/→ selects one +and Enter activates it. On task and result screens, Tab also focuses the buttons. +Narrow terminals scroll the button row to keep the focused action visible. + +The workspace keeps every public command, including extensions, in its command +catalogue. Tab or ←/→ changes dashboard sections; `/` searches every section. +Installed extensions appear when the workspace starts; reopen it after changing +the installed extensions. + +Quick start also includes QR login, a single-chat archive, all joined channels, +a complete incremental backup, account data and recurring backups. Presets fill +in options for you to review and change. + +## Configure and review + +In a form, select a field and press Enter to edit it. Boolean switches toggle +immediately. Space or ←/→ cycles fixed choices, such as an output format or +login method. A dot marks explicitly set options; an asterisk marks required +fields. Ctrl+D restores the default. + +Common options appear first. Ctrl+A shows every public option, including proxy, +storage, concurrency, filters and connection settings. `/` searches all options, +including advanced ones. Descriptions appear below the selected field. + +List options use commas, for example `photos,videos` or `pdf,zip`. Quote a list +item containing a comma: `"Friends, family",telegram`. For positional arguments, +separate values with spaces and quote paths containing spaces: +`"exports/Book Club/result.json" "exports/Work/result.json"`. + +While editing a path, Tab completes a unique matching file or directory name. +`~/` can be expanded this way. Paths are passed as typed; shell variables, +wildcards, command substitution and pipes are not evaluated. + +Choose **Review** or press Ctrl+R to validate inputs, dates and supported choices. +The review shows the task and edited settings. **Run** or Enter starts it; +**Edit** or Esc returns to the form. Press `c` to show or hide an optional command +preview. Proxy credentials, passcodes, passwords and tokens are hidden in forms +and previews. + +Unchanged settings inherit startup flags and exported `TA_*` settings. Edited +global options apply to later workflows in this workspace session. Nothing is +saved as a new configuration file. + +## Tasks, prompts and cancellation + +Tasks run inside the workspace. Archive progress shows the current file or +history scan, completion, speed and ETA when available. Activity output updates +without taking over the terminal. When a task finishes, its result stays visible; +there is no extra Enter-to-return prompt. + +If a login or another task asks for input, choose **Respond** or press `i`. +Type into the displayed prompt and press Enter. Password prompts mask their +input; account choices accept arrow keys. Press Esc to return to workspace +controls. QR codes also appear in the task panel; enlarge the terminal enough +to show the entire code when logging in by QR. + +Choose **Cancel**, press Esc outside input mode, or press Ctrl+C to stop the +active task. The workspace remains open and retains its output. Cancellation +allows a short graceful shutdown before stopping an unresponsive worker. A +cancelled backup can be resumed using its normal checkpoints. + +↑/↓ or the mouse wheel scrolls activity; **Follow latest** or `f` resumes following +new output. Activity retains the latest 2,000 lines in memory. Structured list +results are limited to 4 MiB; refine the query if a list exceeds that limit. +Exported archive files are unaffected by these display limits. + +Embedded interactive prompts are tested on macOS and Linux. Windows uses piped +task output; prompts that require a terminal may need explicit form values or +the corresponding direct CLI command. + +For the native Telegram client on macOS, follow the +[macOS login guide](macos.md) for Full Disk Access and local app passcodes. Quit +native Telegram before using a login imported from it. + +Importing a login does not copy Telegram's proxy settings. If direct connections +are blocked, start the workspace with a working SOCKS5 or HTTP proxy. For +example, if your local proxy listens on port 10808: + +```sh +./bin/ta --proxy=socks5://127.0.0.1:10808 +``` + +The setting carries into the chat browser and other workflows. You can also set +`TA_PROXY` before launching ta, or use **Connection settings** after a failure to +edit the proxy for the current workspace session. + +## Keyboard shortcuts + +| Context | Key | Action | +| --- | --- | --- | +| Workspace | ↑/↓ or j/k | Select a workflow | +| Workspace | Tab, Shift+Tab, ←/→ | Change section | +| Workspace or result list | / | Search | +| Workspace | Enter | Browse or open options | +| Workspace | q | Quit | +| Panels | F6 | Focus/unfocus bottom buttons | +| Buttons | Tab/Shift+Tab, ←/→ | Select an action | +| Buttons | Enter | Activate | +| Options | ↑/↓, Tab/Shift+Tab | Select a field | +| Options | Enter | Edit text or toggle a switch | +| Options | Space or ←/→ | Toggle or cycle choices | +| Options | Ctrl+A / Ctrl+D | All options / reset field | +| Options | Ctrl+R | Validate and review | +| Editing | Enter / Esc | Save / cancel an edit | +| Editing | Ctrl+U / Ctrl+K / Ctrl+W | Clear / delete to end / delete a word | +| Editing | Home/End, ←/→ | Move cursor | +| Editing | Tab | Complete a unique path | +| Search | Enter / Esc | Finish / clear search | +| Review | Enter / Esc / c | Run / edit / toggle command preview | +| Results | ↑/↓, PageUp/PageDown | Select a row or scroll | +| Results | Enter / t / l / d | Details / Results / Activity / Details | +| Results | a / s | Archive selected chat / use selected account | +| Results | e / r / Esc | Edit / review another run / return Home | +| Active task | i / Esc | Respond to a prompt / leave input mode | +| Active task | Ctrl+C | Cancel and keep workspace open | +| Active task | f | Follow latest output | +| Idle screens | Ctrl+C | Quit | +| Panels | ? | Open keyboard help when not editing or responding | diff --git a/go.mod b/go.mod index 91079af..72b4f69 100644 --- a/go.mod +++ b/go.mod @@ -1,15 +1,19 @@ module github.com/mo1ein/TelegramArchive -go 1.25.8 +go 1.26.0 require ( + charm.land/bubbletea/v2 v2.0.10 + charm.land/lipgloss/v2 v2.0.6 github.com/AlecAivazis/survey/v2 v2.3.7 github.com/cenkalti/backoff/v4 v4.3.0 + github.com/charmbracelet/x/ansi v0.11.8 github.com/fatih/color v1.19.0 github.com/go-faster/errors v0.8.0 github.com/gotd/td v0.145.1 github.com/iyear/tdl v0.20.4 github.com/iyear/tdl/core v0.20.4 + github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51 github.com/klauspost/compress v1.19.2 github.com/mitchellh/mapstructure v1.5.0 github.com/pkg/errors v0.9.1 @@ -20,17 +24,26 @@ require ( go.etcd.io/bbolt v1.3.11 go.uber.org/multierr v1.11.0 go.uber.org/zap v1.28.0 + golang.org/x/crypto v0.55.0 golang.org/x/sync v0.22.0 + modernc.org/sqlite v1.55.0 ) require ( github.com/bcicen/jstream v1.0.1 // indirect github.com/beevik/ntp v1.5.0 // indirect github.com/cespare/xxhash/v2 v2.3.0 // indirect - github.com/clipperhouse/uax29/v2 v2.2.0 // indirect + github.com/charmbracelet/colorprofile v0.4.3 // indirect + github.com/charmbracelet/ultraviolet v0.0.0-20260811164956-006e29f97886 // indirect + github.com/charmbracelet/x/term v0.2.2 // indirect + github.com/charmbracelet/x/termios v0.1.1 // indirect + github.com/charmbracelet/x/windows v0.2.2 // indirect + github.com/clipperhouse/displaywidth v0.11.0 // indirect + github.com/clipperhouse/uax29/v2 v2.7.0 // indirect github.com/coder/websocket v1.8.14 // indirect github.com/cpuguy83/go-md2man/v2 v2.0.6 // indirect github.com/dlclark/regexp2 v1.11.5 // indirect + github.com/dustin/go-humanize v1.0.1 // indirect github.com/expr-lang/expr v1.17.8 // indirect github.com/flytam/filenamify v1.2.0 // indirect github.com/fsnotify/fsnotify v1.9.0 // indirect @@ -57,17 +70,21 @@ require ( github.com/iyear/connectproxy v0.1.1 // indirect github.com/iyear/tdl/extension v0.20.4 // indirect github.com/jedib0t/go-pretty/v6 v6.5.0 // indirect - github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51 // indirect github.com/kopoli/go-terminal-size v0.0.0-20170219200355-5c97524c8b54 // indirect github.com/leodido/go-urn v1.4.0 // indirect + github.com/lucasb-eyer/go-colorful v1.4.1 // indirect github.com/lufia/plan9stats v0.0.0-20230326075908-cb1d2100619a // indirect github.com/mattn/go-colorable v0.1.14 // indirect github.com/mattn/go-isatty v0.0.20 // indirect github.com/mattn/go-runewidth v0.0.28 // indirect github.com/mgutz/ansi v0.0.0-20200706080929-d51e80ef957d // indirect + github.com/muesli/cancelreader v0.2.2 // indirect + github.com/ncruces/go-strftime v1.0.0 // indirect github.com/ogen-go/ogen v1.20.3 // indirect github.com/pelletier/go-toml/v2 v2.2.4 // indirect github.com/power-devops/perfstat v0.0.0-20221212215047-62379fc7944b // indirect + github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect + github.com/rivo/uniseg v0.4.7 // indirect github.com/russross/blackfriday/v2 v2.1.0 // indirect github.com/sagikazarmark/locafero v0.11.0 // indirect github.com/samber/lo v1.53.0 // indirect @@ -82,6 +99,7 @@ require ( github.com/subosito/gotenv v1.6.0 // indirect github.com/tklauser/go-sysconf v0.3.12 // indirect github.com/tklauser/numcpus v0.6.1 // indirect + github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect github.com/yapingcat/gomedia v0.0.0-20240601043430-920523f8e5c7 // indirect github.com/yusufpapurcu/wmi v1.2.4 // indirect go.opentelemetry.io/otel v1.42.0 // indirect @@ -89,7 +107,6 @@ require ( go.opentelemetry.io/otel/trace v1.42.0 // indirect go.uber.org/atomic v1.11.0 // indirect go.yaml.in/yaml/v3 v3.0.5 // indirect - golang.org/x/crypto v0.55.0 // indirect golang.org/x/exp v0.0.0-20240719175910-8a7402abbf56 // indirect golang.org/x/mod v0.38.0 // indirect golang.org/x/net v0.58.0 // indirect @@ -100,5 +117,8 @@ require ( golang.org/x/tools v0.48.0 // indirect gopkg.in/natefinch/lumberjack.v2 v2.2.1 // indirect gopkg.in/yaml.v2 v2.4.0 // indirect + modernc.org/libc v1.74.1 // indirect + modernc.org/mathutil v1.7.1 // indirect + modernc.org/memory v1.11.0 // indirect rsc.io/qr v0.2.0 // indirect ) diff --git a/go.sum b/go.sum index c598a92..db3b6d0 100644 --- a/go.sum +++ b/go.sum @@ -1,3 +1,7 @@ +charm.land/bubbletea/v2 v2.0.10 h1:oolvo20VBpI0PfqE7iFjkZ1bx0WpmXGfnKz5Yldjq5o= +charm.land/bubbletea/v2 v2.0.10/go.mod h1:QOatcnhOjYIfxzUSTz6raF7Ex4R/rIuHa3SnBdCCpMc= +charm.land/lipgloss/v2 v2.0.6 h1:EaGKeuA8FvF+v2BT5VmZd2LoYLaMZJXA5n34th8nCIQ= +charm.land/lipgloss/v2 v2.0.6/go.mod h1:ipDDJNSGa1hlwDtSfW1s2/xR8Vdhbut4PXh2zEKZd0Q= github.com/AlecAivazis/survey/v2 v2.3.7 h1:6I/u8FvytdGsgonrYsVn2t8t4QiRnh6QSTqkkhIiSjQ= github.com/AlecAivazis/survey/v2 v2.3.7/go.mod h1:xUTIdE4KCOIjsBAE1JYsUPoCqYdZ1reCfTwbto0Fduo= github.com/Netflix/go-expect v0.0.0-20220104043353-73e0943537d2 h1:+vx7roKuyA63nhn5WAunQHLTznkw5W8b1Xc0dNjp83s= @@ -10,8 +14,24 @@ github.com/cenkalti/backoff/v4 v4.3.0 h1:MyRJ/UdXutAwSAT+s3wNd7MfTIcy71VQueUuFK3 github.com/cenkalti/backoff/v4 v4.3.0/go.mod h1:Y3VNntkOUPxTVeUxJ/G5vcM//AlwfmyYozVcomhLiZE= github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/charmbracelet/colorprofile v0.4.3 h1:QPa1IWkYI+AOB+fE+mg/5/4HRMZcaXex9t5KX76i20Q= +github.com/charmbracelet/colorprofile v0.4.3/go.mod h1:/zT4BhpD5aGFpqQQqw7a+VtHCzu+zrQtt1zhMt9mR4Q= +github.com/charmbracelet/ultraviolet v0.0.0-20260811164956-006e29f97886 h1:rdnVWKgJpTVXKuKuJyxDJ+NFJdUaUqGvyGy61OcvlbA= +github.com/charmbracelet/ultraviolet v0.0.0-20260811164956-006e29f97886/go.mod h1:nAw0d9PhFp1qdzi2xhQU5YOu5sVpDIHWlaW2Uz/bCro= +github.com/charmbracelet/x/ansi v0.11.8 h1:JMFwp0CgDC2+jcOB162HH5k7I3FVbgFSMMYg7dSPBQQ= +github.com/charmbracelet/x/ansi v0.11.8/go.mod h1:ZNN+3mXny/516oTQPLMPIBeSINvNJJQ8uQXDgbeJxY0= +github.com/charmbracelet/x/term v0.2.2 h1:xVRT/S2ZcKdhhOuSP4t5cLi5o+JxklsoEObBSgfgZRk= +github.com/charmbracelet/x/term v0.2.2/go.mod h1:kF8CY5RddLWrsgVwpw4kAa6TESp6EB5y3uxGLeCqzAI= +github.com/charmbracelet/x/termios v0.1.1 h1:o3Q2bT8eqzGnGPOYheoYS8eEleT5ZVNYNy8JawjaNZY= +github.com/charmbracelet/x/termios v0.1.1/go.mod h1:rB7fnv1TgOPOyyKRJ9o+AsTU/vK5WHJ2ivHeut/Pcwo= +github.com/charmbracelet/x/windows v0.2.2 h1:IofanmuvaxnKHuV04sC0eBy/smG6kIKrWG2/jYn2GuM= +github.com/charmbracelet/x/windows v0.2.2/go.mod h1:/8XtdKZzedat74NQFn0NGlGL4soHB0YQZrETF96h75k= +github.com/clipperhouse/displaywidth v0.11.0 h1:lBc6kY44VFw+TDx4I8opi/EtL9m20WSEFgwIwO+UVM8= +github.com/clipperhouse/displaywidth v0.11.0/go.mod h1:bkrFNkf81G8HyVqmKGxsPufD3JhNl3dSqnGhOoSD/o0= github.com/clipperhouse/uax29/v2 v2.2.0 h1:ChwIKnQN3kcZteTXMgb1wztSgaU+ZemkgWdohwgs8tY= github.com/clipperhouse/uax29/v2 v2.2.0/go.mod h1:EFJ2TJMRUaplDxHKj1qAEhCtQPW2tJSwu5BF98AuoVM= +github.com/clipperhouse/uax29/v2 v2.7.0 h1:+gs4oBZ2gPfVrKPthwbMzWZDaAFPGYK72F0NJv2v7Vk= +github.com/clipperhouse/uax29/v2 v2.7.0/go.mod h1:EFJ2TJMRUaplDxHKj1qAEhCtQPW2tJSwu5BF98AuoVM= github.com/coder/websocket v1.8.14 h1:9L0p0iKiNOibykf283eHkKUHHrpG7f65OE3BhhO7v9g= github.com/coder/websocket v1.8.14/go.mod h1:NX3SzP+inril6yawo5CQXx8+fk145lPDC6pumgx0mVg= github.com/cpuguy83/go-md2man/v2 v2.0.1/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= @@ -25,6 +45,8 @@ github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1 github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/dlclark/regexp2 v1.11.5 h1:Q/sSnsKerHeCkc/jSTNq1oCm7KiVgUMZRDUoRu0JQZQ= github.com/dlclark/regexp2 v1.11.5/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8= +github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY= +github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= github.com/expr-lang/expr v1.17.8 h1:W1loDTT+0PQf5YteHSTpju2qfUfNoBt4yw9+wOEU9VM= github.com/expr-lang/expr v1.17.8/go.mod h1:8/vRC7+7HBzESEqt5kKpYXxrxkr31SaO8r40VO/1IT4= github.com/fatih/color v1.13.0/go.mod h1:kLAiJbzzSOZDVNGyDpeOxJ47H46qBXwg5ILebYFFOfk= @@ -116,6 +138,8 @@ github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ= github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI= +github.com/lucasb-eyer/go-colorful v1.4.1 h1:1EO+WB73+EH8EVbzlrG3KLAfEypQWVHIBqlTf+2hNss= +github.com/lucasb-eyer/go-colorful v1.4.1/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0= github.com/lufia/plan9stats v0.0.0-20230326075908-cb1d2100619a h1:N9zuLhTvBSRt0gWSiJswwQ2HqDmtX/ZCDJURnKUt1Ik= github.com/lufia/plan9stats v0.0.0-20230326075908-cb1d2100619a/go.mod h1:JKx41uQRwqlTZabZc+kILPrO/3jlKnQ2Z8b7YiVw5cE= github.com/mattn/go-colorable v0.1.2/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE= @@ -135,6 +159,10 @@ github.com/mgutz/ansi v0.0.0-20200706080929-d51e80ef957d h1:5PJl274Y63IEHC+7izoQ github.com/mgutz/ansi v0.0.0-20200706080929-d51e80ef957d/go.mod h1:01TrycV0kFyexm33Z7vhZRXopbI8J3TDReVlkTgMUxE= github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY= github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= +github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELUXHmA= +github.com/muesli/cancelreader v0.2.2/go.mod h1:3XuTXfFS2VjM+HTLZY9Ak0l6eUKfijIfMUZ4EgX0QYo= +github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w= +github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls= github.com/ogen-go/ogen v1.20.3 h1:1tvJuJE0BnQ7Nukd6ykiTOP0ucfL0yrAjHUg3S1DCQk= github.com/ogen-go/ogen v1.20.3/go.mod h1:sJ1pJVp4S1RcSZlYIiMLo0QSMSt2pls4zfrc+hNKnzk= github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4= @@ -145,7 +173,11 @@ github.com/pkg/profile v1.6.0/go.mod h1:qBsxPvzyUincmltOk6iyRVxHYg4adc0OFOv72ZdL github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/power-devops/perfstat v0.0.0-20221212215047-62379fc7944b h1:0LFwY6Q3gMACTjAbMZBjXAqTOzOwFaj2Ld6cjeQ7Rig= github.com/power-devops/perfstat v0.0.0-20221212215047-62379fc7944b/go.mod h1:OmDBASR4679mdNQnz2pUhc2G8CO2JrUAVFDRBDP/hJE= +github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE= +github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= +github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ= +github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88= github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ= github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc= github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk= @@ -194,6 +226,8 @@ github.com/tklauser/go-sysconf v0.3.12 h1:0QaGUFOdQaIVdPgfITYzaTegZvdCjmYO52cSFA github.com/tklauser/go-sysconf v0.3.12/go.mod h1:Ho14jnntGE1fpdOqQEEaiKRpvIavV0hSfmBq8nJbHYI= github.com/tklauser/numcpus v0.6.1 h1:ng9scYS7az0Bk4OZLvrNXNSAO2Pxr1XXRAPyjhIx+Fk= github.com/tklauser/numcpus v0.6.1/go.mod h1:1XfjsgE2zo8GVw7POkMbHENHzVg3GzmoZ9fESEdAacY= +github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e h1:JVG44RsyaB9T2KIHavMF/ppJZNG9ZpyihvCd0w101no= +github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e/go.mod h1:RbqR21r5mrJuqunuUZ/Dhy/avygyECGrLceyNeo4LiM= github.com/yapingcat/gomedia v0.0.0-20240601043430-920523f8e5c7 h1:e9n2WNcfvs20aLgpDhKoaJgrU/EeAvuNnWLBm31Q5Fw= github.com/yapingcat/gomedia v0.0.0-20240601043430-920523f8e5c7/go.mod h1:WSZ59bidJOO40JSJmLqlkBJrjZCtjbKKkygEMfzY/kc= github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= @@ -284,6 +318,14 @@ gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +modernc.org/libc v1.74.1 h1:bdR4VTKFMC4966QSNZ05XLGI/VwzVa2kTUX51Dm0riQ= +modernc.org/libc v1.74.1/go.mod h1:uH4t5bOx3G3g9Xcmj10YKlTcVISlRDwv8VoQJG9n8Os= +modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU= +modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg= +modernc.org/memory v1.11.0 h1:o4QC8aMQzmcwCK3t3Ux/ZHmwFPzE6hf2Y5LbkRs+hbI= +modernc.org/memory v1.11.0/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw= +modernc.org/sqlite v1.55.0 h1:hIFh0MCH0rGinQ/4KYb5/UbCkRkb+UP+OkLCVWa5MTM= +modernc.org/sqlite v1.55.0/go.mod h1:4ntCLuNmnH8+GNqjka1wNg7KJd5/Hi5FYp8K+XQ7GZw= nhooyr.io/websocket v1.8.17 h1:KEVeLJkUywCKVsnLIDlD/5gtayKp8VoCkksHCGGfT9Y= nhooyr.io/websocket v1.8.17/go.mod h1:rN9OFWIUwuxg4fR5tELlYC04bXYowCP9GX47ivo2l+c= rsc.io/qr v0.2.0 h1:6vBLea5/NRMVTz8V66gipeLycZMl/+UlFmk8DvqQ6WY= diff --git a/internal/macsession/SOURCES.txt b/internal/macsession/SOURCES.txt new file mode 100644 index 0000000..b4f057b --- /dev/null +++ b/internal/macsession/SOURCES.txt @@ -0,0 +1,28 @@ +Native session format references (the Go reader is an independent implementation): + +Telegram's native client: +https://github.com/TelegramMessenger/telegram-macos + +Postbox account metadata, coding and authorization state: +https://github.com/TelegramMessenger/Telegram-iOS/blob/master/submodules/TelegramCore/Sources/AccountManager/AccountManagerAtomicState.swift +https://github.com/TelegramMessenger/Telegram-iOS/blob/master/submodules/TelegramCore/Sources/AccountManager/AccountRecord.swift +https://github.com/TelegramMessenger/Telegram-iOS/blob/master/submodules/TelegramCore/Sources/Account/AccountManager.swift +https://github.com/TelegramMessenger/Telegram-iOS/blob/master/submodules/TelegramCore/Sources/SyncCore/SyncCore_AuthorizedAccountState.swift +https://github.com/TelegramMessenger/Telegram-iOS/blob/master/submodules/Postbox/Sources/Coding.swift +https://github.com/TelegramMessenger/Telegram-iOS/blob/master/submodules/Postbox/Sources/MetadataTable.swift +https://github.com/TelegramMessenger/Telegram-iOS/blob/master/submodules/Postbox/Sources/Postbox.swift +https://github.com/TelegramMessenger/Telegram-iOS/blob/master/submodules/Postbox/Sources/SqliteValueBox.swift +https://github.com/TelegramMessenger/Telegram-iOS/blob/master/submodules/MtProtoKit/Sources/MTDatacenterAuthInfo.m + +SQLCipher page authentication and SQLite committed-WAL format: +https://github.com/sqlcipher/sqlcipher/blob/master/src/sqlcipher.c +https://sqlite.org/fileformat.html + +Local passcode wrapper documentation and public native application profiles: +https://github.com/kolezka/tg-viewer/blob/main/apps/tool/tg_appstore_decrypt.py +https://github.com/thedemons/opentele/blob/main/src/api.py + +No real session material is included in this package or its fixtures. Fixture +keys are deliberately synthetic (byte sequences), generated using independent +Python standard-library and OpenSSL implementations; Python and OpenSSL are not +required to run the importer or tests. diff --git a/internal/macsession/crypto.go b/internal/macsession/crypto.go new file mode 100644 index 0000000..b05ec76 --- /dev/null +++ b/internal/macsession/crypto.go @@ -0,0 +1,116 @@ +// Package macsession reads native Telegram for macOS sessions without changing +// the source application's files. It does not open Telegram's message tables. +package macsession + +import ( + "crypto/aes" + "crypto/cipher" + "crypto/hmac" + "crypto/sha1" + "crypto/sha512" + "encoding/binary" + "errors" + "hash" + "math/bits" + + "golang.org/x/crypto/pbkdf2" +) + +var ErrPasscode = errors.New("native Telegram database key could not be unlocked; supply its local app passcode with -p") + +// The native client's local key wrapper is AES-CBC with SHA-512-derived key/IV. +// Its 48-byte database key/salt is followed by a seeded Murmur3 checksum. +func unlockKey(encrypted []byte, password string) ([]byte, error) { + if len(encrypted) < 64 || len(encrypted) > 4096 || len(encrypted)%aes.BlockSize != 0 { + return nil, ErrPasscode + } + if password == "" { + password = "no-matter-key" + } + digest := sha512.Sum512([]byte(password)) + block, _ := aes.NewCipher(digest[:32]) + plain := make([]byte, len(encrypted)) + defer clear(plain) + cipher.NewCBCDecrypter(block, digest[48:]).CryptBlocks(plain, encrypted) + if murmur3(plain[:48], 0xf7ca7fd2) != binary.LittleEndian.Uint32(plain[48:52]) { + return nil, ErrPasscode + } + return append([]byte(nil), plain[:48]...), nil +} + +func murmur3(data []byte, seed uint32) uint32 { + h := seed + for n := 0; n+4 <= len(data); n += 4 { + k := binary.LittleEndian.Uint32(data[n:]) * 0xcc9e2d51 + h ^= bits.RotateLeft32(k, 15) * 0x1b873593 + h = bits.RotateLeft32(h, 13)*5 + 0xe6546b64 + } + var tail uint32 + for i, b := range data[len(data)&^3:] { + tail |= uint32(b) << (8 * i) + } + if len(data)%4 != 0 { + h ^= bits.RotateLeft32(tail*0xcc9e2d51, 15) * 0x1b873593 + } + h ^= uint32(len(data)) + h ^= h >> 16 + h *= 0x85ebca6b + h ^= h >> 13 + h *= 0xc2b2ae35 + h ^= h >> 16 + return h +} + +type pageCipher struct { + block cipher.Block + macKey []byte + hash func() hash.Hash + reserve int +} + +func newPageCipher(key []byte, reserve int) (*pageCipher, error) { + if len(key) != 48 { + return nil, errors.New("invalid native database key length") + } + var hashFn func() hash.Hash + switch reserve { + case 48: + hashFn = sha1.New // SQLCipher 3 + case 80: + hashFn = sha512.New // SQLCipher 4 + default: + return nil, errors.New("unsupported native SQLCipher page format") + } + salt := append([]byte(nil), key[32:]...) + defer clear(salt) + for i := range salt { + salt[i] ^= 0x3a + } + block, err := aes.NewCipher(key[:32]) + if err != nil { + return nil, err + } + return &pageCipher{block: block, macKey: pbkdf2.Key(key[:32], salt, 2, 32, hashFn), hash: hashFn, reserve: reserve}, nil +} + +func (c *pageCipher) decrypt(raw []byte, number uint32) ([]byte, error) { + start, end := 0, len(raw)-c.reserve + if number == 1 { + start = 32 + } + if end <= start || (end-start)%aes.BlockSize != 0 { + return nil, errors.New("invalid encrypted database page size") + } + mac := hmac.New(c.hash, c.macKey) + _, _ = mac.Write(raw[start : end+16]) + var pageNumber [4]byte + binary.LittleEndian.PutUint32(pageNumber[:], number) + _, _ = mac.Write(pageNumber[:]) + if !hmac.Equal(mac.Sum(nil), raw[end+16:end+16+mac.Size()]) { + return nil, errors.New("native database page authentication failed; data changed, the key is wrong, or the database is damaged") + } + plain := make([]byte, len(raw)) + copy(plain[:start], raw[:start]) + cipher.NewCBCDecrypter(c.block, raw[end:end+16]).CryptBlocks(plain[start:end], raw[start:end]) + return plain, nil +} diff --git a/internal/macsession/database.go b/internal/macsession/database.go new file mode 100644 index 0000000..0c316d1 --- /dev/null +++ b/internal/macsession/database.go @@ -0,0 +1,237 @@ +package macsession + +import ( + "bytes" + "context" + "database/sql" + "encoding/binary" + "errors" + "fmt" + "io" + "io/fs" + "os" + "strings" + "time" + + _ "modernc.org/sqlite" + "modernc.org/sqlite/vfs" +) + +// A private, read-only VFS decrypts pages on demand. No plaintext database is +// written to disk, and opening a large chat database does not load all messages. +type database struct { + file, wal *os.File + fileInfo, walInfo fs.FileInfo + header []byte + pages map[uint32]int64 + size int64 + pageSize int + cipher *pageCipher + cache map[uint32][]byte + lastErr error +} + +func openDatabase(path string, key []byte) (*database, error) { + file, err := os.Open(path) + if err != nil { + return nil, err + } + d := &database{file: file, pages: map[uint32]int64{}, cache: map[uint32][]byte{}} + ok := false + defer func() { + if !ok { + d.Close() + } + }() + d.fileInfo, err = file.Stat() + if err != nil { + return nil, err + } + d.header = make([]byte, 32) + if _, err = file.ReadAt(d.header, 0); err != nil { + return nil, err + } + if !bytes.HasPrefix(d.header, []byte("SQLite format 3\x00")) { + return nil, errors.New("native database has an unsupported header") + } + d.pageSize = int(binary.BigEndian.Uint16(d.header[16:18])) + if d.pageSize == 1 { + d.pageSize = 65536 + } + if d.pageSize < 512 || d.pageSize > 65536 || d.pageSize&(d.pageSize-1) != 0 { + return nil, errors.New("native database has an invalid page size") + } + d.size = d.fileInfo.Size() + if d.size%int64(d.pageSize) != 0 { + return nil, errors.New("native database has a truncated page") + } + if d.header[20] != 0 { + d.cipher, err = newPageCipher(key, int(d.header[20])) + if err != nil { + return nil, err + } + } + if err := d.readWAL(path + "-wal"); err != nil { + return nil, err + } + if _, err := d.page(1); err != nil { + return nil, err + } + ok = true + return d, nil +} + +func (d *database) Close() error { + for _, page := range d.cache { + clear(page) + } + if d.cipher != nil { + clear(d.cipher.macKey) + } + var walErr error + if d.wal != nil { + walErr = d.wal.Close() + } + return errors.Join(d.file.Close(), walErr) +} + +func (d *database) page(number uint32) ([]byte, error) { + if number == 0 || int64(number)*int64(d.pageSize) > d.size { + return nil, errors.New("native database page is outside the snapshot") + } + if cached := d.cache[number]; cached != nil { + return cached, nil + } + raw := make([]byte, d.pageSize) + file, offset := d.file, int64(number-1)*int64(d.pageSize) + if walOffset, ok := d.pages[number]; ok { + file, offset = d.wal, walOffset + } + if _, err := file.ReadAt(raw, offset); err != nil { + return nil, err + } + plain := raw + if d.cipher != nil { + var err error + plain, err = d.cipher.decrypt(raw, number) + clear(raw) + if err != nil { + d.lastErr = err + return nil, err + } + } + if len(d.cache) >= 16 { + for key, value := range d.cache { + clear(value) + delete(d.cache, key) + break + } + } + d.cache[number] = plain + return plain, nil +} + +func (d *database) ReadAt(p []byte, offset int64) (int, error) { + if offset < 0 { + return 0, errors.New("negative database offset") + } + n := 0 + for n < len(p) && offset < d.size { + page, err := d.page(uint32(offset/int64(d.pageSize)) + 1) + if err != nil { + d.lastErr = err + return n, err + } + used := copy(p[n:], page[int(offset%int64(d.pageSize)):]) + n += used + offset += int64(used) + } + if n < len(p) { + return n, io.EOF + } + return n, nil +} + +func (d *database) unchanged() error { + check := func(file *os.File, before fs.FileInfo) error { + after, err := file.Stat() + if err != nil { + return err + } + if after.Size() != before.Size() || !after.ModTime().Equal(before.ModTime()) { + return errors.New("Telegram database changed during import; quit Telegram and retry") + } + return nil + } + if err := check(d.file, d.fileInfo); err != nil { + return err + } + if d.wal != nil { + return check(d.wal, d.walInfo) + } + if _, err := os.Stat(d.file.Name() + "-wal"); err == nil { + return errors.New("Telegram started a database transaction during import; quit Telegram and retry") + } else if !os.IsNotExist(err) { + return err + } + return nil +} + +type decryptedFS struct{ db *database } +type decryptedFile struct { + *io.SectionReader + size int64 +} + +func (f decryptedFS) Open(name string) (fs.File, error) { + if name != "session.db" && name != "/session.db" { + return nil, fs.ErrNotExist + } + return &decryptedFile{SectionReader: io.NewSectionReader(f.db, 0, f.db.size), size: f.db.size}, nil +} +func (f *decryptedFile) Close() error { return nil } +func (f *decryptedFile) Stat() (fs.FileInfo, error) { return databaseInfo{size: f.size}, nil } + +type databaseInfo struct{ size int64 } + +func (f databaseInfo) Name() string { return "session.db" } +func (f databaseInfo) Size() int64 { return f.size } +func (databaseInfo) Mode() fs.FileMode { return 0400 } +func (databaseInfo) ModTime() time.Time { return time.Time{} } +func (databaseInfo) IsDir() bool { return false } +func (databaseInfo) Sys() any { return nil } + +func (d *database) authorization(ctx context.Context) ([]byte, []byte, error) { + name, fsys, err := vfs.New(decryptedFS{d}) + if err != nil { + return nil, nil, err + } + defer fsys.Close() + db, err := sql.Open("sqlite", "file:session.db?vfs="+name+"&mode=ro&immutable=1") + if err != nil { + return nil, nil, err + } + db.SetMaxOpenConns(1) + defer db.Close() + var state, archive []byte + // Postbox table 0 is metadata (state key 2); table 1 is its keychain. + if err = db.QueryRowContext(ctx, "SELECT value FROM t0 WHERE key=2 AND length(value)<=1048576").Scan(&state); err == nil { + err = db.QueryRowContext(ctx, "SELECT value FROM t1 WHERE key=? AND length(value)<=1048576", []byte("persistent:datacenterAuthInfoById")).Scan(&archive) + } + if d.lastErr != nil { + return nil, nil, d.lastErr + } + if err != nil { + if strings.Contains(err.Error(), "no such table") || errors.Is(err, sql.ErrNoRows) { + return nil, nil, errors.New("native account has no saved authorization") + } + return nil, nil, fmt.Errorf("read native authorization tables: %w", err) + } + if len(state) > 1<<20 || len(archive) > 1<<20 { + return nil, nil, errors.New("native authorization exceeds supported size") + } + if err := d.unchanged(); err != nil { + return nil, nil, err + } + return state, archive, nil +} diff --git a/internal/macsession/plist.go b/internal/macsession/plist.go new file mode 100644 index 0000000..694cb89 --- /dev/null +++ b/internal/macsession/plist.go @@ -0,0 +1,278 @@ +package macsession + +import ( + "bytes" + "crypto/sha1" + "encoding/binary" + "errors" + "fmt" + "unicode/utf16" +) + +type uid uint64 + +var errArchive = errors.New("unsupported or malformed native authorization archive") + +// Reasons are fixed schema labels, never values or key material from the file. +func archiveError(reason string) error { return fmt.Errorf("%w: %s", errArchive, reason) } + +// Parse property-list primitives only. Unlike NSKeyedUnarchiver, this never +// instantiates classes named by the input archive. +type plist struct { + data []byte + refs, offsetSize int + count, table uint64 + cache map[uint64]any + active map[uint64]bool + remaining uint64 +} + +func decodePlist(data []byte) (any, error) { + if len(data) < 40 || len(data) > 1<<20 || !bytes.HasPrefix(data, []byte("bplist00")) { + return nil, archiveError("expected a binary property list within size limits") + } + tail := data[len(data)-32:] + p := &plist{data: data, offsetSize: int(tail[6]), refs: int(tail[7]), count: binary.BigEndian.Uint64(tail[8:]), table: binary.BigEndian.Uint64(tail[24:]), cache: map[uint64]any{}, active: map[uint64]bool{}, remaining: 16 << 20} + if p.offsetSize < 1 || p.offsetSize > 8 || p.refs < 1 || p.refs > 8 || p.count > 65536 || p.table > uint64(len(data)-32) || p.count*uint64(p.offsetSize) > uint64(len(data)-32)-p.table { + return nil, archiveError("invalid binary property list trailer") + } + return p.object(binary.BigEndian.Uint64(tail[16:]), 0) +} + +func bigNumber(data []byte) uint64 { + var n uint64 + for _, b := range data { + n = n<<8 | uint64(b) + } + return n +} +func (p *plist) object(index uint64, depth int) (any, error) { + if index >= p.count || depth > 64 || p.active[index] { + return nil, archiveError("invalid object reference, excessive depth, or cyclic property list") + } + if value, ok := p.cache[index]; ok { + return value, nil + } + if p.remaining < 64 { + return nil, archiveError("property list object allocation limit exceeded") + } + p.remaining -= 64 + offset := bigNumber(p.data[p.table+index*uint64(p.offsetSize) : p.table+(index+1)*uint64(p.offsetSize)]) + if offset >= p.table { + return nil, archiveError("object offset outside property list object table") + } + p.active[index] = true + defer delete(p.active, index) + marker := p.data[offset] + offset++ + kind, n := marker>>4, uint64(marker&15) + if n == 15 && kind != 0 { + if offset >= p.table || p.data[offset]>>4 != 1 || p.data[offset]&15 > 3 { + return nil, archiveError("invalid extended property list length") + } + size := uint64(1) << uint(p.data[offset]&15) + offset++ + if size > p.table-offset { + return nil, archiveError("truncated extended property list length") + } + n = bigNumber(p.data[offset : offset+size]) + offset += size + } + take := func(size uint64) ([]byte, error) { + if offset > p.table || size > p.table-offset { + return nil, archiveError("object payload exceeds property list bounds") + } + out := p.data[offset : offset+size] + offset += size + return out, nil + } + var value any + switch kind { + case 0: + switch marker { + case 0: + value = nil + case 8: + value = false + case 9: + value = true + default: + return nil, archiveError("unsupported property list simple marker") + } + case 1: + if n > 3 { + return nil, archiveError("integer wider than 64 bits") + } + b, err := take(uint64(1) << n) + if err != nil { + return nil, err + } + value = int64(bigNumber(b)) + case 4, 5, 6: + size := n + if kind == 6 { + size = n * 2 + if size/2 != n { + return nil, archiveError("UTF-16 string length overflow") + } + } + b, err := take(size) + if err != nil { + return nil, err + } + if size > p.remaining { + return nil, archiveError("property list string allocation limit exceeded") + } + p.remaining -= size + if kind == 4 { + value = b + } else if kind == 5 { + value = string(b) + } else { + runes := make([]uint16, n) + for i := range runes { + runes[i] = binary.BigEndian.Uint16(b[2*i:]) + } + value = string(utf16.Decode(runes)) + } + case 8: + if n > 7 { + return nil, archiveError("property list UID wider than 64 bits") + } + b, err := take(n + 1) + if err != nil { + return nil, err + } + value = uid(bigNumber(b)) + case 10, 13: + if n > 65536 { + return nil, archiveError("property list collection exceeds supported count") + } + count := n + if kind == 13 { + count *= 2 + } + if count*32 > p.remaining { + return nil, archiveError("property list collection allocation limit exceeded") + } + p.remaining -= count * 32 + refs, err := take(count * uint64(p.refs)) + if err != nil { + return nil, err + } + items := make([]any, count) + for i := range items { + items[i], err = p.object(bigNumber(refs[i*p.refs:(i+1)*p.refs]), depth+1) + if err != nil { + return nil, err + } + } + if kind == 10 { + value = items + } else { + dict := map[string]any{} + for i := uint64(0); i < n; i++ { + key, ok := items[i].(string) + if !ok { + return nil, archiveError("property list dictionary key is not a string") + } + dict[key] = items[n+i] + } + value = dict + } + default: + return nil, fmt.Errorf("%w: unsupported binary property list object kind 0x%x", errArchive, kind) + } + p.cache[index] = value + return value, nil +} + +func authKeyFromArchive(data []byte, dc int) ([]byte, error) { + value, err := decodePlist(data) + if err != nil { + return nil, fmt.Errorf("decode property list: %w", err) + } + root, ok := value.(map[string]any) + if !ok { + return nil, archiveError("archive root is not a dictionary") + } + objects, ok := root["$objects"].([]any) + if !ok { + return nil, archiveError("missing archive object table") + } + resolve := func(value any) any { + if ref, ok := value.(uid); ok { + if uint64(ref) >= uint64(len(objects)) { + return nil + } + return objects[ref] + } + return value + } + top, ok := root["$top"].(map[string]any) + if !ok { + return nil, archiveError("missing archive top dictionary") + } + dict, ok := resolve(top["root"]).(map[string]any) + if !ok { + return nil, archiveError("archive root reference is not a dictionary") + } + keys, ok := dict["NS.keys"].([]any) + if !ok { + return nil, archiveError("data center dictionary keys are not an array") + } + values, ok := dict["NS.objects"].([]any) + if !ok || len(keys) != len(values) { + return nil, archiveError("data center dictionary values do not match keys") + } + for i, key := range keys { + id, ok := resolve(key).(int64) + if !ok || id != int64(dc) { + continue + } + info, ok := resolve(values[i]).(map[string]any) + if !ok { + return nil, archiveError("primary authorization entry is not a dictionary") + } + class, ok := resolve(info["$class"]).(map[string]any) + if !ok || class["$classname"] != "MTDatacenterAuthInfo" { + return nil, archiveError("primary authorization class is not MTDatacenterAuthInfo") + } + keyRef, present := info["authKey"] + if !present { + return nil, archiveError("authorization entry has no authKey field") + } + keyValue := resolve(keyRef) + // Foundation emits immutable NSData directly, but NSMutableData as a + // keyed object containing NS.data. Read primitives only, never classes. + if wrapped, ok := keyValue.(map[string]any); ok { + dataClass, valid := resolve(wrapped["$class"]).(map[string]any) + if !valid || (dataClass["$classname"] != "NSData" && dataClass["$classname"] != "NSMutableData") { + return nil, archiveError("authorization key wrapper is not NSData or NSMutableData") + } + payload, present := wrapped["NS.data"] + if !present { + return nil, archiveError("authorization data wrapper has no NS.data field") + } + keyValue = resolve(payload) + } + authKey, ok := keyValue.([]byte) + if !ok { + // %T reveals only a Go primitive type, never the decoded value. + return nil, archiveError(fmt.Sprintf("authorization key payload has type %T; expected 256-byte data", keyValue)) + } + if len(authKey) != 256 { + return nil, archiveError(fmt.Sprintf("authorization key payload is %d bytes; expected 256", len(authKey))) + } + keyID, ok := info["authKeyId"].(int64) + if !ok { + return nil, archiveError("authorization fingerprint is not a 64-bit integer") + } + digest := sha1.Sum(authKey) + if binary.LittleEndian.Uint64(digest[12:]) != uint64(keyID) { + return nil, errors.New("native authorization key fingerprint does not match") + } + return append([]byte(nil), authKey...), nil + } + return nil, errors.New("native authorization has no permanent key for the primary data center") +} diff --git a/internal/macsession/postbox.go b/internal/macsession/postbox.go new file mode 100644 index 0000000..20a4d63 --- /dev/null +++ b/internal/macsession/postbox.go @@ -0,0 +1,98 @@ +package macsession + +import ( + "encoding/binary" + "errors" +) + +var errState = errors.New("native account state is malformed, unsupported, or not authorized") + +func readObject(data []byte) (uint32, []byte, error) { + if len(data) < 11 || data[0] != 1 || data[1] != '_' || data[2] != 5 { + return 0, nil, errState + } + length := int64(int32(binary.LittleEndian.Uint32(data[7:11]))) + if length < 0 || length != int64(len(data)-11) { + return 0, nil, errState + } + return binary.LittleEndian.Uint32(data[3:7]), data[11:], nil +} + +func accountState(data []byte) (dc int, userID int64, test bool, err error) { + hash, fields, err := readObject(data) + if err != nil || hash != murmur3([]byte("AuthorizedAccountState"), 0xf7ca7fd2) { + return 0, 0, false, errState + } + found := 0 + for len(fields) > 0 { + keySize := int(fields[0]) + fields = fields[1:] + if keySize > 127 || len(fields) < keySize+1 { + return 0, 0, false, errState + } + key, kind := string(fields[:keySize]), fields[keySize] + fields = fields[keySize+1:] + size := 0 + switch kind { + case 0: + size = 4 + case 1, 3: + size = 8 + case 2: + size = 1 + case 11: + size = 0 + case 4, 10: + if len(fields) < 4 { + return 0, 0, false, errState + } + n := int64(int32(binary.LittleEndian.Uint32(fields))) + if n < 0 || n > int64(len(fields)-4) { + return 0, 0, false, errState + } + size = 4 + int(n) + case 5: + if len(fields) < 8 { + return 0, 0, false, errState + } + n := int64(int32(binary.LittleEndian.Uint32(fields[4:]))) + if n < 0 || n > int64(len(fields)-8) { + return 0, 0, false, errState + } + size = 8 + int(n) + default: + return 0, 0, false, errState + } + if len(fields) < size { + return 0, 0, false, errState + } + switch key { + case "masterDatacenterId": + if kind != 0 { + return 0, 0, false, errState + } + dc = int(int32(binary.LittleEndian.Uint32(fields))) + found |= 1 + case "peerId": + if kind != 1 { + return 0, 0, false, errState + } + userID = int64(binary.LittleEndian.Uint64(fields)) + found |= 2 + case "isTestingEnvironment": + if kind != 0 { + return 0, 0, false, errState + } + test = binary.LittleEndian.Uint32(fields) != 0 + found |= 4 + } + fields = fields[size:] + if found == 7 { + if dc < 1 || dc > 5 || userID <= 0 { + return 0, 0, false, errState + } + return dc, userID, test, nil + } + } + return 0, 0, false, errState +} diff --git a/internal/macsession/read.go b/internal/macsession/read.go new file mode 100644 index 0000000..1e6f42e --- /dev/null +++ b/internal/macsession/read.go @@ -0,0 +1,225 @@ +package macsession + +import ( + "context" + "crypto/sha1" + "encoding/base64" + "encoding/json" + "errors" + "fmt" + "io" + "net" + "os" + "path/filepath" + "slices" + "strconv" + + "github.com/gotd/td/session" + "github.com/gotd/td/telegram/dcs" +) + +// Account contains sensitive authorization material. Call Clear after storing +// the chosen session. It is deliberately not JSON serializable. +type Account struct { + UserID int64 `json:"-"` + Data *session.Data `json:"-"` +} + +func (a Account) Clear() { + if a.Data != nil { + clear(a.Data.AuthKey) + clear(a.Data.AuthKeyID) + } +} + +func readLimited(path string, max int64) ([]byte, error) { + file, err := os.Open(path) + if err != nil { + return nil, err + } + defer file.Close() + data, err := io.ReadAll(io.LimitReader(file, max+1)) + if err != nil { + return nil, err + } + if int64(len(data)) > max { + clear(data) + return nil, errors.New("native session file exceeds supported size") + } + return data, nil +} + +// Read opens only account-directory metadata and the two authorization tables. +// It never edits, repairs, exports or checkpoints Telegram's databases. +func Read(ctx context.Context, root, passcode string) ([]Account, error) { + metadata, err := readLimited(filepath.Join(root, "accounts-metadata", "atomic-state"), 8<<20) + if err != nil { + return nil, accessError(err) + } + defer clear(metadata) + ids, err := accountRecords(metadata) + if err != nil { + return nil, err + } + key, err := readLimited(filepath.Join(root, ".tempkeyEncrypted"), 4096) + if err == nil { + encrypted := key + key, err = unlockKey(encrypted, passcode) + clear(encrypted) + } else if os.IsNotExist(err) { + key, err = readLimited(filepath.Join(root, ".tempkey"), 48) + if err == nil && len(key) != 48 { + clear(key) + return nil, errors.New("native database key has an invalid length") + } + } + if err != nil { + return nil, accessError(err) + } + defer clear(key) + var accounts []Account + success := false + defer func() { + if !success { + for _, account := range accounts { + account.Clear() + } + } + }() + for _, id := range ids { + if err := ctx.Err(); err != nil { + return nil, err + } + path := filepath.Join(root, "account-"+strconv.FormatUint(uint64(id), 10), "postbox", "db", "db_sqlite") + db, err := openDatabase(path, key) + if os.IsNotExist(err) { + continue + } + if err != nil { + return nil, accessError(err) + } + state, archive, readErr := db.authorization(ctx) + closeErr := db.Close() + if readErr != nil { + return nil, readErr + } + if closeErr != nil { + return nil, closeErr + } + dc, userID, test, err := accountState(state) + clear(state) + if err != nil { + clear(archive) + return nil, err + } + authKey, err := authKeyFromArchive(archive, dc) + clear(archive) + if err != nil { + return nil, err + } + list := dcs.Prod() + if test { + list = dcs.Test() + } + addr := "" + for _, option := range list.Options { + if option.ID == dc && !option.MediaOnly && !option.CDN && !option.TCPObfuscatedOnly && !option.Ipv6 { + addr = net.JoinHostPort(option.IPAddress, strconv.Itoa(option.Port)) + break + } + } + if addr == "" { + clear(authKey) + return nil, errors.New("native account uses an unknown data center") + } + digest := sha1.Sum(authKey) + accounts = append(accounts, Account{UserID: userID, Data: &session.Data{DC: dc, Addr: addr, AuthKey: authKey, AuthKeyID: append([]byte(nil), digest[12:]...), Config: session.Config{ThisDC: dc, TestMode: test, DCOptions: list.Options}}}) + } + if len(accounts) == 0 { + return nil, errors.New("no authorized native Telegram accounts found; open Telegram and sign in, then retry") + } + success = true + return accounts, nil +} + +func accessError(err error) error { + if os.IsPermission(err) { + return fmt.Errorf("macOS denied access to native Telegram data; enable Full Disk Access for the app running ta (Terminal, iTerm or Codex), reopen that app, and retry: %w", err) + } + return err +} + +func accountRecords(data []byte) ([]int64, error) { + var state struct { + Records []json.RawMessage `json:"records"` + } + if json.Unmarshal(data, &state) != nil || len(state.Records) > 1000 { + return nil, errors.New("native account metadata is malformed or unsupported") + } + var ids []int64 + for _, raw := range state.Records { + var record struct { + ID json.RawMessage `json:"id"` + Attributes []json.RawMessage `json:"attributes"` + } + if json.Unmarshal(raw, &record) != nil || len(record.ID) == 0 { + continue + } // legacy dictionary keys + loggedOut := false + for _, attribute := range record.Attributes { + var fields map[string]json.RawMessage + if json.Unmarshal(attribute, &fields) == nil { + if _, ok := fields["loggedOut"]; ok { + loggedOut = true + } + if raw, ok := fields["_"]; ok { + var legacy struct { + TypeHash int32 `json:"typeHash"` + } + if json.Unmarshal(raw, &legacy) != nil { + return nil, errors.New("native account attribute is malformed") + } + loggedOut = loggedOut || uint32(legacy.TypeHash) == murmur3([]byte("LoggedOutAccountAttribute"), 0xf7ca7fd2) + } + continue + } + var encoded string + if json.Unmarshal(attribute, &encoded) == nil { + blob, err := base64.StdEncoding.DecodeString(encoded) + if err != nil || len(blob) > 65536 { + return nil, errors.New("native account attribute is malformed") + } + hash, _, err := readObject(blob) + if err != nil { + return nil, err + } + loggedOut = loggedOut || hash == murmur3([]byte("LoggedOutAccountAttribute"), 0xf7ca7fd2) + } + } + if loggedOut { + continue + } + var id int64 + var text string + if json.Unmarshal(record.ID, &text) == nil { + n, err := strconv.ParseInt(text, 10, 64) + if err != nil { + return nil, errors.New("native account record identifier is invalid") + } + id = n + } else { + var legacy struct { + Raw int64 `json:"rawValue"` + } + if json.Unmarshal(record.ID, &legacy) != nil { + return nil, errors.New("native account record identifier is invalid") + } + id = legacy.Raw + } + if !slices.Contains(ids, id) { + ids = append(ids, id) + } + } + slices.Sort(ids) + return ids, nil +} diff --git a/internal/macsession/read_test.go b/internal/macsession/read_test.go new file mode 100644 index 0000000..7636d71 --- /dev/null +++ b/internal/macsession/read_test.go @@ -0,0 +1,266 @@ +package macsession + +import ( + "bytes" + "context" + "crypto/sha256" + "encoding/binary" + "errors" + "os" + "path/filepath" + "testing" +) + +func fixture(t *testing.T, name string) []byte { + t.Helper() + data, err := os.ReadFile(filepath.Join("testdata", name)) + if err != nil { + t.Fatal(err) + } + return data +} +func syntheticRoot(t *testing.T, version string) string { + t.Helper() + root := t.TempDir() + for _, name := range []string{"accounts-metadata", "account-123/postbox/db"} { + if err := os.MkdirAll(filepath.Join(root, name), 0700); err != nil { + t.Fatal(err) + } + } + files := map[string][]byte{ + "accounts-metadata/atomic-state": []byte(`{"records":[{"id":"123","attributes":[]}],"currentRecordId":"123"}`), + ".tempkeyEncrypted": fixture(t, "tempkey.enc"), + "account-123/postbox/db/db_sqlite": fixture(t, version+".bin"), + } + for name, data := range files { + if err := os.WriteFile(filepath.Join(root, name), data, 0600); err != nil { + t.Fatal(err) + } + } + return root +} + +func TestNativeReadIndependentEncryptedFixtures(t *testing.T) { + for _, version := range []string{"sqlcipher3", "sqlcipher4"} { + t.Run(version, func(t *testing.T) { + root := syntheticRoot(t, version) + path := filepath.Join(root, "account-123/postbox/db/db_sqlite") + before, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + accounts, err := Read(context.Background(), root, "") + if err != nil { + t.Fatal(err) + } + defer accounts[0].Clear() + if len(accounts) != 1 || accounts[0].UserID != 42 || accounts[0].Data.DC != 2 { + t.Fatal("wrong synthetic account decoded") + } + want := make([]byte, 256) + for i := range want { + want[i] = byte(i) + } + if !bytes.Equal(accounts[0].Data.AuthKey, want) { + t.Fatal("authorization key mismatch") + } + after, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + if sha256.Sum256(before) != sha256.Sum256(after) { + t.Fatal("native database was modified") + } + files, err := os.ReadDir(filepath.Dir(path)) + if err != nil || len(files) != 1 { + t.Fatal("import wrote extra source files") + } + }) + } +} + +func TestNativePasscodeAndIntegrityFailures(t *testing.T) { + wrapped := fixture(t, "tempkey.enc") + key, err := unlockKey(wrapped, "") + if err != nil || len(key) != 48 { + t.Fatal(err) + } + defer clear(key) + if _, err := unlockKey(wrapped, "incorrect passcode"); !errors.Is(err, ErrPasscode) { + t.Fatal(err) + } + for _, length := range []int{0, 1, 16, 52, 63} { + if _, err := unlockKey(make([]byte, length), ""); !errors.Is(err, ErrPasscode) { + t.Fatal("invalid key wrapper accepted") + } + } + for _, version := range []string{"sqlcipher3", "sqlcipher4"} { + root := syntheticRoot(t, version) + path := filepath.Join(root, "account-123/postbox/db/db_sqlite") + data, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + data[128] ^= 1 + if err := os.WriteFile(path, data, 0600); err != nil { + t.Fatal(err) + } + if _, err := Read(context.Background(), root, ""); err == nil { + t.Fatal("corrupted encrypted page accepted") + } + } +} + +func TestMurmurKnownVectors(t *testing.T) { + for input, want := range map[string]uint32{"": 0, "foo": 0xf6a5c420, "bar": 0x450e998d} { + if got := murmur3([]byte(input), 0); got != want { + t.Fatalf("murmur(%q)=%x", input, got) + } + } +} + +func TestBinaryArchiveGoldenAndMalformed(t *testing.T) { + data := fixture(t, "authorization.bplist") + key, err := authKeyFromArchive(data, 2) + if err != nil || len(key) != 256 { + t.Fatal(err) + } + clear(key) + if _, err := authKeyFromArchive(data, 5); err == nil { + t.Fatal("accepted missing primary data center") + } + for n := 0; n < len(data); n++ { + if _, err := decodePlist(data[:n]); err == nil { + t.Fatalf("truncated archive accepted at %d", n) + } + } + bad := append([]byte(nil), data...) + binary.BigEndian.PutUint64(bad[len(bad)-24:], 1<<62) + if _, err := decodePlist(bad); err == nil { + t.Fatal("unbounded archive allocation allowed") + } +} + +func TestFoundationAuthorizationArchive(t *testing.T) { + for _, name := range []string{"foundation-authorization.bplist", "foundation-mutable-authorization.bplist"} { + t.Run(name, func(t *testing.T) { + key, err := authKeyFromArchive(fixture(t, name), 2) + if err != nil { + t.Fatal(err) + } + defer clear(key) + if len(key) != 256 { + t.Fatal("incorrect authorization key length") + } + for i, b := range key { + if b != byte(i) { + t.Fatal("incorrect authorization key") + } + } + }) + } +} + +func TestFoundationDataWrapperRejectsMalformedKeys(t *testing.T) { + archive := fixture(t, "foundation-mutable-authorization.bplist") + for _, tc := range []struct{ name, old, replacement string }{ + {"unrecognized data class", "NSMutableData", "NSMutableDate"}, + {"missing data payload", "NS.data", "NS.fake"}, + } { + t.Run(tc.name, func(t *testing.T) { + if !bytes.Contains(archive, []byte(tc.old)) { + t.Fatal("fixture does not contain mutation target") + } + bad := bytes.Replace(archive, []byte(tc.old), []byte(tc.replacement), 1) + if _, err := authKeyFromArchive(bad, 2); !errors.Is(err, errArchive) { + t.Fatalf("malformed wrapper was accepted: %v", err) + } + }) + } + key := make([]byte, 256) + for i := range key { + key[i] = byte(i) + } + start := bytes.Index(archive, key) + if start < 0 { + t.Fatal("synthetic key missing") + } + bad := append([]byte(nil), archive...) + bad[start] ^= 1 + if _, err := authKeyFromArchive(bad, 2); err == nil || err.Error() != "native authorization key fingerprint does not match" { + t.Fatalf("wrapper bypassed fingerprint check: %v", err) + } +} + +func TestNativeRecordsSkipLoggedOutAndKeepExactIDs(t *testing.T) { + ids, err := accountRecords([]byte(`{"records":[{"id":"9223372036854775806","attributes":[]},{"id":{"rawValue":-5},"attributes":[]},{"id":"8","attributes":[{"loggedOut":{}}]},{"rawValue":-3},{"id":"-5","attributes":[]}]}`)) + if err != nil || len(ids) != 2 || ids[0] != -5 || ids[1] != 9223372036854775806 { + t.Fatalf("record decoding failed: %v", err) + } +} + +func TestNativeCommittedWALOnly(t *testing.T) { + root := syntheticRoot(t, "sqlcipher4") + path := filepath.Join(root, "account-123/postbox/db/db_sqlite") + data, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + page := append([]byte(nil), data[8192:12288]...) + data[8300] ^= 1 // base page is unusable unless its committed WAL image wins + if err := os.WriteFile(path, data, 0600); err != nil { + t.Fatal(err) + } + header := make([]byte, 32) + binary.BigEndian.PutUint32(header, 0x377f0682) + binary.BigEndian.PutUint32(header[4:], 3007000) + binary.BigEndian.PutUint32(header[8:], 4096) + copy(header[16:24], []byte("syntheti")) + a, b := walChecksum(header[:24], 0, 0, binary.LittleEndian) + binary.BigEndian.PutUint32(header[24:], a) + binary.BigEndian.PutUint32(header[28:], b) + wal := append([]byte(nil), header...) + for i := 0; i < 2; i++ { + frame := make([]byte, 24+4096) + binary.BigEndian.PutUint32(frame, 3) + if i == 0 { + binary.BigEndian.PutUint32(frame[4:], 3) + } + copy(frame[8:16], header[16:24]) + copy(frame[24:], page) + if i == 1 { + frame[100] ^= 1 + } + a, b = walChecksum(frame[:8], a, b, binary.LittleEndian) + a, b = walChecksum(frame[24:], a, b, binary.LittleEndian) + binary.BigEndian.PutUint32(frame[16:], a) + binary.BigEndian.PutUint32(frame[20:], b) + wal = append(wal, frame...) + } + if err := os.WriteFile(path+"-wal", wal, 0600); err != nil { + t.Fatal(err) + } + accounts, err := Read(context.Background(), root, "") + if err != nil { + t.Fatal(err) + } + defer accounts[0].Clear() + if len(accounts) != 1 || accounts[0].UserID != 42 { + t.Fatal("committed WAL snapshot was not used") + } +} + +func FuzzNativeDecoders(f *testing.F) { + f.Add([]byte("bplist00")) + f.Add([]byte(`{"records":[]}`)) + f.Add([]byte{1, '_', 5, 0, 0, 0, 0, 0, 0, 0, 0}) + f.Fuzz(func(t *testing.T, data []byte) { + if len(data) > 1<<20 { + return + } + _, _ = decodePlist(data) + _, _ = accountRecords(data) + _, _, _, _ = accountState(data) + _, _ = unlockKey(data, "") + }) +} diff --git a/internal/macsession/testdata/README.txt b/internal/macsession/testdata/README.txt new file mode 100644 index 0000000..7465aac --- /dev/null +++ b/internal/macsession/testdata/README.txt @@ -0,0 +1,13 @@ +Synthetic native Telegram session fixtures. No real Telegram credentials or messages. +Auth key: bytes 0..255; user 42; DC 2; record 123. Database key/salt: bytes 0..47. +Generated independently using Python sqlite3/plistlib/hashlib and OpenSSL AES-CBC. +Encrypted SQLite page fixtures have reserve 48 (SQLCipher 3) and 80 (SQLCipher 4), +a 32-byte plaintext header, authenticated little-endian page numbers, and no WAL. + +foundation-authorization.bplist uses the same synthetic key and is generated +by macOS Foundation's NSKeyedArchiver, including empty salt and attribute +collections. Regenerate on macOS (from this directory): + clang -framework Foundation -Wno-deprecated-declarations foundation-authorization.m -o /tmp/ta-native-archive + /tmp/ta-native-archive foundation-authorization.bplist + /tmp/ta-native-archive foundation-mutable-authorization.bplist mutable +The mutable fixture encodes the synthetic key as NSMutableData (NS.data wrapper). diff --git a/internal/macsession/testdata/authorization.bplist b/internal/macsession/testdata/authorization.bplist new file mode 100644 index 0000000000000000000000000000000000000000..3216fdcac7f9620db8fdc42850db63ee55bcc5d7 GIT binary patch literal 629 zcmYc)$jK}&F)+Bo$i&RT%BG|msghWfoRL|US`?v@pOlrFTv8mOQj%W~p#l^t&dkq? z7vT2`_D-!#O>u-OT+YrRC?p{#AF7g9nv-*xlZ%^&mp@D;IVZ8WINUE-FFUoeI0{HZ zjcZ_8$k)KMP@sWXfax-)u!yLbcz9xINe0l&NGR=@(!kchDtzL8_>#Pci$<3urKDvd zAO@xuM?n~QiMgqZWMpIff?YC`OMnhbEUJv~3-$-Q*lUGnwQdUt_Q`gYc($>+{(>E|QGBzQN=`{lOV7y6%FfBn%P%M_DlRE4E3c@ms;;T6t8Zv* zYHn$5Ywzgn>h9_7>z^=j(&Q;qr%j(RbJpxRbLY)puyE1hB}NRWEt>3V5 z)8;K(w{73CbJy-Yd-v@>aPZLKBS()NKXLNZ=`&}~oxgDL(&Z~xuU)@!^VaPo;%Tz5np>)8{W=zkUDl^Vjb`fB*dlhMI!nB1PGF0TJI2m&B69 z|;2{aE{?R<88(VjE@oO@Bjb+ literal 0 HcmV?d00001 diff --git a/internal/macsession/testdata/foundation-authorization.bplist b/internal/macsession/testdata/foundation-authorization.bplist new file mode 100644 index 0000000000000000000000000000000000000000..3fa1e8818331b64798a5e80b842db292a19cd13f GIT binary patch literal 789 zcmYc)$jK}&F)+Bo$i&RT%ErzWp;DGwRGgWg7pan1l$?edc4}pD6p)6R6{eD$lUQ85P_Th%p>P9p1BU?9HGXjkNhxU=Svh$H#qi?9oRZ+w zl6V2Z#L|)spoNYlB}JJ@r6sAwkx&uOlyE33UO>1kF()%6G_NExCnPgBwYVfPx1fQu zfwh5M_{9D2C3z7SjT%^l>i_@$?=Q&6zyS3#2PYRd56F#zLc$`VVo3HYDXXZescUFz zY3u0f=^Gdt8Jn1znOj&|S=-p!**iEoIlH*JxqEnedHeYK`3D3B1&4%&g-1k2MaRU( z#U~^tC8wmOrDtSjW#{DPGGAU*RJ2VdF%F_yZ7!tc=+h?lc&#~zj*oT^_#cv z-hcS`>GPMb-@gC&`Rn(ezyJPU;^S9QUC_XG3FN~lNL1t{=B7qKn5o6U7;`KtN~~O@ zsU6`L><^BAP-N=ri7Z&qzyZ`}XcXfY?2?&W0!%Q8MU{&TwSj^rrttzIz9BA&C5g$Y zc_pbuj=;F{%uCB(WTuTnhJk}YkU@$;g+Y_Sh{2q}lfj1}kRg~Mjv<91o1vJYj-i#I zouQMVo1vGXpJ5`yJceZqyBLlzoMCvx@Py$R!wZIw44)Z(F#cg;WMX1sVd7*GVUlH1 qWzt|WWU^qgWU^wiVRB^hV+v#nW6EVJU;qOqUOb0`g^nA!mZJ{z$B literal 0 HcmV?d00001 diff --git a/internal/macsession/testdata/foundation-authorization.m b/internal/macsession/testdata/foundation-authorization.m new file mode 100644 index 0000000..111daab --- /dev/null +++ b/internal/macsession/testdata/foundation-authorization.m @@ -0,0 +1,26 @@ +#import +#import +static BOOL mutableKey = NO; +@interface MTDatacenterAuthInfo : NSObject +@end +@implementation MTDatacenterAuthInfo +- (void)encodeWithCoder:(NSCoder *)coder { + uint8_t key[256], digest[20]; + for (int i=0; i<256; i++) key[i]=i; + CC_SHA1(key,256,digest); + int64_t fingerprint; memcpy(&fingerprint,digest+12,8); + NSData *data = mutableKey ? [NSMutableData dataWithBytes:key length:256] : [NSData dataWithBytes:key length:256]; + [coder encodeObject:data forKey:@"authKey"]; + [coder encodeInt64:fingerprint forKey:@"authKeyId"]; + [coder encodeInt32:INT32_MAX forKey:@"validUntilTimestamp"]; + [coder encodeObject:@[] forKey:@"saltSet"]; + [coder encodeObject:@{} forKey:@"authKeyAttributes"]; +} +- (instancetype)initWithCoder:(NSCoder *)coder { return [super init]; } +@end +int main(int argc, const char *argv[]) { @autoreleasepool { + mutableKey = argc > 2; + NSDictionary *root=@{@2: [[MTDatacenterAuthInfo alloc] init]}; + NSData *archive=[NSKeyedArchiver archivedDataWithRootObject:root requiringSecureCoding:NO error:nil]; + return [archive writeToFile:[NSString stringWithUTF8String:argv[1]] atomically:YES] ? 0 : 1; +}} diff --git a/internal/macsession/testdata/foundation-mutable-authorization.bplist b/internal/macsession/testdata/foundation-mutable-authorization.bplist new file mode 100644 index 0000000000000000000000000000000000000000..94def0abb5740a2ed60d8aebcb6107e554ce1f12 GIT binary patch literal 849 zcmYc)$jK}&F)+Bo$i&RT%ErzWp;DGwRGgWg7pan1l$?R3)!8C+9LRAHRT* zNVs3HUUq6_aTJh-8WyIKoRe5wyil-#X`yffa|5RU(=~o^2}vnw8Cf}b1;y~<#GI1g z)RK4s!Nk&%44{pUB_&0fNu?#J#gR}E&y;W|D_%gjEHNiDB{Z)jGbbc7H?_DVF}I+B ztAVY7L-@q~@FjT>7mXTNgzEqQ|9?rDUquz1_o#daBy;Q^MD*IC?qT* zDu(13C1n*=HFXV5Eo~iLJ$(a1BV!X&Gjj_|D{C8DJ9`I5CubK|H+K(DFK-`TKmUNh zpx}_uu<(e;sOXs3xcG#`q~w&;wDgS3tn8fJy!?W~qT-U$vhs?`s_L5By84F3rskH` zw)T$BuI`@RzWxalCrzF*b=ve9GiS}7Gk4zn1q&A~Ub1xA@)avrtzNTs-TDn1H*Mas zb=&qGJ9q8gvv=SA0|yTsK63Qf@e?Ocoj!B+-1!R^FI~QJ_1g6tH*ej(bNAl;2M-@T ze)9C$^A|5)y?*od-TMz8KYjl4_1pI!KY#uH^Y`EX2G&a;zePb}Brh>HH3Gs+EspgI z_AM<*Ov*`h0S4A$O>LbpzhDqE!Y|k#oGLEy@$2a?XkZ5#VQ2&lRmY;D#L7j6I-r<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C8VElcm;6}it6wz`XelZ z6g7>0PNg7qz01r{6Tre9THOx?%gYI#AdIneaU&qXRlUF2mo3V3Tq!#Vv{iIVMnao5 aUBEgY=S)UF5d&|v#HZviIea~3u%+d>-QMs3 literal 0 HcmV?d00001 diff --git a/internal/macsession/testdata/tempkey.enc b/internal/macsession/testdata/tempkey.enc new file mode 100644 index 0000000000000000000000000000000000000000..b08a01d5156e6a7541328e393c8a4395e7a64fc4 GIT binary patch literal 64 zcmV-G0KflyFRRe>0~r00@|LwMX3L(QpNjhL{nU#kOypr&kP|Ay70Q>upzJ!!Pou^7 W^^7S19`rTIrWvwdOYLbv@?hYcqa(Zk literal 0 HcmV?d00001 diff --git a/internal/macsession/wal.go b/internal/macsession/wal.go new file mode 100644 index 0000000..3d2f7c8 --- /dev/null +++ b/internal/macsession/wal.go @@ -0,0 +1,97 @@ +package macsession + +import ( + "bytes" + "encoding/binary" + "errors" + "io" + "os" +) + +// Overlay only checksum-verified, committed WAL frames. Partial transactions and +// stale tails after a WAL reset must not become part of the session snapshot. +func (d *database) readWAL(path string) error { + file, err := os.Open(path) + if os.IsNotExist(err) { + return nil + } + if err != nil { + return err + } + d.wal = file + d.walInfo, err = file.Stat() + if err != nil { + return err + } + if d.walInfo.Size() == 0 { + return nil + } + header := make([]byte, 32) + if _, err := file.ReadAt(header, 0); err != nil { + return errors.New("native WAL has a truncated header; quit Telegram and retry") + } + magic := binary.BigEndian.Uint32(header) + if magic != 0x377f0682 && magic != 0x377f0683 { + return errors.New("native WAL has an invalid header") + } + if binary.BigEndian.Uint32(header[4:]) != 3007000 || binary.BigEndian.Uint32(header[8:]) != uint32(d.pageSize) { + return errors.New("native WAL format does not match the database") + } + var order binary.ByteOrder = binary.LittleEndian + if magic&1 != 0 { + order = binary.BigEndian + } + a, b := walChecksum(header[:24], 0, 0, order) + if a != binary.BigEndian.Uint32(header[24:]) || b != binary.BigEndian.Uint32(header[28:]) { + return errors.New("native WAL header checksum failed") + } + type frame struct { + number uint32 + offset int64 + } + var frames []frame + commit, pageCount := 0, uint32(0) + buffer := make([]byte, 24+d.pageSize) + for offset := int64(32); offset+int64(len(buffer)) <= d.walInfo.Size(); offset += int64(len(buffer)) { + if len(frames) >= 262144 { + return errors.New("native WAL is too large; quit Telegram to checkpoint it, then retry") + } + if _, err := file.ReadAt(buffer, offset); err != nil && err != io.EOF { + return err + } + if !bytes.Equal(buffer[8:16], header[16:24]) { + break + } + a, b = walChecksum(buffer[:8], a, b, order) + a, b = walChecksum(buffer[24:], a, b, order) + if a != binary.BigEndian.Uint32(buffer[16:]) || b != binary.BigEndian.Uint32(buffer[20:]) { + break + } + number := binary.BigEndian.Uint32(buffer) + if number == 0 { + break + } + frames = append(frames, frame{number, offset + 24}) + if pages := binary.BigEndian.Uint32(buffer[4:]); pages != 0 { + commit, pageCount = len(frames), pages + } + } + for _, frame := range frames[:commit] { + if frame.number <= pageCount { + d.pages[frame.number] = frame.offset + } + } + if commit > 0 { + d.size = int64(pageCount) * int64(d.pageSize) + } + return nil +} + +func walChecksum(data []byte, a, b uint32, order binary.ByteOrder) (uint32, uint32) { + for len(data) >= 8 { + a += order.Uint32(data) + b + b += order.Uint32(data[4:]) + a + data = data[8:] + } + return a, b +} diff --git a/internal/taskui/chats.go b/internal/taskui/chats.go new file mode 100644 index 0000000..41ddcff --- /dev/null +++ b/internal/taskui/chats.go @@ -0,0 +1,9 @@ +package taskui + +import "encoding/json" + +type ChatEvent struct { + Kind string `json:"kind"` + Stage string `json:"stage"` + Items json.RawMessage `json:"items,omitempty"` +} diff --git a/internal/taskui/progress.go b/internal/taskui/progress.go new file mode 100644 index 0000000..629a46b --- /dev/null +++ b/internal/taskui/progress.go @@ -0,0 +1,18 @@ +// Package taskui carries bounded progress frames from isolated task workers. +package taskui + +import ( + "encoding/json" + "fmt" + "io" +) + +const ProgressPrefix = "ta-progress;" + +func WriteProgress(out io.Writer, lines []string) { + data, err := json.Marshal(lines) + if err != nil || len(data) > 4096 { + return + } + _, _ = fmt.Fprintf(out, "\x1b]777;%s%s\a", ProgressPrefix, data) +} diff --git a/internal/telegram/dialogs.go b/internal/telegram/dialogs.go index 8ee7f74..73df6cf 100644 --- a/internal/telegram/dialogs.go +++ b/internal/telegram/dialogs.go @@ -3,6 +3,7 @@ package telegram import ( "context" "fmt" + "time" "github.com/gotd/td/telegram/message/peer" "github.com/gotd/td/telegram/peers" @@ -24,7 +25,7 @@ func peerKey(p tg.PeerClass) string { // Explicitly visit both Telegram folders. Inaccessible peers can still supply a // pagination cursor, so one removed channel cannot truncate the remaining list. -func (s *Source) folderDialogs(ctx context.Context, api *tg.Client, folder int, types []string) ([]archive.Chat, error) { +func (s *Source) folderDialogs(ctx context.Context, api *tg.Client, folder int, types []string, visit func([]archive.Chat) error) ([]archive.Chat, error) { var chats []archive.Chat offsetID, offsetDate := 0, 0 var offsetPeer tg.InputPeerClass = &tg.InputPeerEmpty{} @@ -32,7 +33,13 @@ func (s *Source) folderDialogs(ctx context.Context, api *tg.Client, folder int, for { req := &tg.MessagesGetDialogsRequest{OffsetID: offsetID, OffsetDate: offsetDate, OffsetPeer: offsetPeer, Limit: 100, ExcludePinned: offsetID != 0} req.SetFolderID(folder) - raw, err := api.MessagesGetDialogs(ctx, req) + callCtx := ctx + cancel := func() {} + if visit != nil { + callCtx, cancel = context.WithTimeout(ctx, 20*time.Second) + } + raw, err := api.MessagesGetDialogs(callCtx, req) + cancel() if err != nil { return chats, fmt.Errorf("list folder %d: %w", folder, err) } @@ -65,6 +72,7 @@ func (s *Source) folderDialogs(ctx context.Context, api *tg.Client, folder int, lastMessages[peerKey(m.GetPeerID())] = m } } + pageStart := len(chats) cursorKey := "" for _, d := range dialogs { if _, ok := d.(*tg.DialogFolder); ok { @@ -118,6 +126,11 @@ func (s *Source) folderDialogs(ctx context.Context, api *tg.Client, folder int, } } } + if visit != nil && len(chats) > pageStart { + if err := visit(chats[pageStart:]); err != nil { + return chats, err + } + } if done { return chats, nil } diff --git a/internal/telegram/dialogs_test.go b/internal/telegram/dialogs_test.go index b2514ce..019596f 100644 --- a/internal/telegram/dialogs_test.go +++ b/internal/telegram/dialogs_test.go @@ -2,8 +2,11 @@ package telegram import ( "context" + "errors" "fmt" + "github.com/mo1ein/TelegramArchive/internal/archive" "testing" + "time" "github.com/gotd/td/bin" tgclient "github.com/gotd/td/telegram" @@ -57,3 +60,43 @@ func TestJoinedChannelsIncludeArchiveAndContinuePagination(t *testing.T) { t.Fatal("archive folder not queried") } } + +func TestStreamDialogsEmitsBeforeNextPageAndDoesNotFetchTopics(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + pages := make(chan int, 1) + api := tg.NewClient(tgclient.InvokeFunc(func(ctx context.Context, input bin.Encoder, output bin.Decoder) error { + req, ok := input.(*tg.MessagesGetDialogsRequest) + if !ok { + return fmt.Errorf("unexpected eager per-chat request %T", input) + } + if req.OffsetID != 0 { + <-ctx.Done() + return ctx.Err() + } + output.(*tg.MessagesDialogsBox).Dialogs = &tg.MessagesDialogsSlice{Count: 2, Dialogs: []tg.DialogClass{&tg.Dialog{Peer: &tg.PeerChannel{ChannelID: 42}, TopMessage: 10}}, Chats: []tg.ChatClass{&tg.Channel{ID: 42, AccessHash: 42, Title: "Synthetic forum", Megagroup: true, Forum: true}}, Messages: []tg.MessageClass{&tg.Message{ID: 10, Date: 100, PeerID: &tg.PeerChannel{ChannelID: 42}}}} + return nil + })) + source := &Source{api: api, manager: peers.Options{}.Build(api), chats: map[string]tg.InputPeerClass{}} + done := make(chan error, 1) + go func() { + done <- source.StreamDialogs(ctx, []string{"groups"}, func(chats []archive.Chat) error { pages <- len(chats); return nil }) + }() + select { + case count := <-pages: + if count != 1 { + t.Fatal("wrong first page size") + } + case <-time.After(time.Second): + t.Fatal("chat page hidden behind remaining requests") + } + cancel() + select { + case err := <-done: + if !errors.Is(err, context.Canceled) { + t.Fatalf("cancellation lost: %v", err) + } + case <-time.After(time.Second): + t.Fatal("stream did not stop") + } +} diff --git a/internal/telegram/source.go b/internal/telegram/source.go index 9c8ad08..bb8f937 100644 --- a/internal/telegram/source.go +++ b/internal/telegram/source.go @@ -292,6 +292,16 @@ func matches(chat archive.Chat, types []string) bool { } func (s *Source) Dialogs(ctx context.Context, types []string) ([]archive.Chat, error) { + return s.walkDialogs(ctx, types, nil) +} + +// StreamDialogs emits each page as soon as it arrives, without fetching forum +// topics or resolving every peer through additional network requests. +func (s *Source) StreamDialogs(ctx context.Context, types []string, visit func([]archive.Chat) error) error { + _, err := s.walkDialogs(ctx, types, visit) + return err +} +func (s *Source) walkDialogs(ctx context.Context, types []string, visit func([]archive.Chat) error) ([]archive.Chat, error) { if err := ValidateTypes(types); err != nil { return nil, err } @@ -307,13 +317,36 @@ func (s *Source) Dialogs(ctx context.Context, types []string) ([]archive.Chat, e var failures []error for _, api := range apis { for _, folder := range []int{0, 1} { - found, err := s.folderDialogs(ctx, api, folder, types) - for _, chat := range found { - if !seen[chat.Key] { - chats = append(chats, chat) - seen[chat.Key] = true + if err := ctx.Err(); err != nil { + return chats, err + } + var onPage func([]archive.Chat) error + if visit != nil { + onPage = func(page []archive.Chat) error { + fresh := []archive.Chat{} + for _, chat := range page { + if !seen[chat.Key] { + chats = append(chats, chat) + fresh = append(fresh, chat) + seen[chat.Key] = true + } + } + if len(fresh) > 0 { + return visit(fresh) + } + return nil } } + found, err := s.folderDialogs(ctx, api, folder, types, onPage) + if visit == nil { + for _, chat := range found { + if !seen[chat.Key] { + chats = append(chats, chat) + seen[chat.Key] = true + } + } + } + if err != nil { failures = append(failures, err) } diff --git a/internal/tui/catalog.go b/internal/tui/catalog.go new file mode 100644 index 0000000..196b059 --- /dev/null +++ b/internal/tui/catalog.go @@ -0,0 +1,241 @@ +// Package tui provides the interactive command workspace for ta. +package tui + +import ( + "encoding/csv" + "fmt" + "slices" + "strings" + + "github.com/spf13/cobra" + "github.com/spf13/pflag" +) + +type Action struct { + Title, Description, Group string + Path []string + Command *cobra.Command + Preset map[string]string +} + +var Groups = []string{"Quick start", "All commands", "Backups", "Automation", "Transfers", "Accounts", "Chat tools", "Tools"} + +// Catalog uses Cobra as the source of truth, including installed extensions. +// Hidden commands and implementation-only flags stay outside the interface. +func Catalog(root *cobra.Command) []Action { + var actions []Action + var walk func(*cobra.Command, []string) + walk = func(cmd *cobra.Command, path []string) { + if cmd.Hidden || cmd.Deprecated != "" || cmd.Name() == "tui" || cmd.Name() == "help" { + return + } + if len(path) > 0 && cmd.Runnable() { + actions = append(actions, Action{Title: strings.Join(path, " "), Description: cmd.Short, Group: group(path), Path: slices.Clone(path), Command: cmd}) + } + for _, child := range cmd.Commands() { + walk(child, append(slices.Clone(path), child.Name())) + } + } + walk(root, nil) + slices.SortFunc(actions, func(a, b Action) int { return strings.Compare(a.Title, b.Title) }) + var quick []Action + for _, preset := range []struct { + path, title, description string + values map[string]string + }{ + {"chat ls", "Browse your chats", "Choose a chat, inspect its details, and archive it without typing an ID.", nil}, + {"accounts", "Your Telegram accounts", "Select a saved account for your next backup.", nil}, + {"cron list", "Scheduled backups", "Review schedules, run a backup, or inspect its logs.", nil}, + {"login", "Connect a Telegram account", "Sign in with a QR code to get started.", map[string]string{"type": "qr"}}, + {"archive", "Archive a chat", "Save a chat with media, JSON and an offline HTML reader.", map[string]string{"chat": "me", "media": "all", "format": "both"}}, + {"archive", "Back up all channels", "Archive your joined channels, including private channels.", map[string]string{"all": "true", "types": "channels", "media": "all", "format": "both"}}, + {"sync", "Back up everything", "Incrementally sync chats, account data and Saved Messages.", map[string]string{"everything": "true", "format": "both"}}, + {"account", "Save account data", "Choose account sections and back up Saved Messages.", map[string]string{"format": "both"}}, + {"cron add", "Schedule a backup", "Install a recurring backup every six hours.", map[string]string{"everything": "true", "every": "6h", "format": "both"}}, + } { + for _, action := range actions { + if strings.Join(action.Path, " ") == preset.path { + action.Title, action.Description, action.Group, action.Preset = preset.title, preset.description, "Quick start", preset.values + quick = append(quick, action) + break + } + } + } + return append(quick, actions...) +} + +func group(path []string) string { + switch path[0] { + case "archive", "account", "sync", "render", "stats": + return "Backups" + case "cron", "schedule": + return "Automation" + case "download", "upload", "forward": + return "Transfers" + case "login", "accounts", "backup", "recover", "migrate": + return "Accounts" + case "chat": + return "Chat tools" + default: + return "Tools" + } +} + +type Field struct { + Name, Label, Help, Type, Value, Default string + Choices []string + Required, Advanced, Global, Dirty bool + Secret bool +} + +type Form struct { + Action Action + Fields []Field +} + +var common = []string{"ns", "arguments", "type", "chat", "all", "everything", "include", "account", "types", "media", "format", "output", "dir", "path", "url", "file", "from", "to", "every", "target", "since", "until", "extensions", "resume", "run-now"} + +// NewForm reads metadata without changing the flags bound to the running CLI. +func NewForm(action Action, globals map[string]string) Form { + form := Form{Action: action} + cmd := action.Command + flags := pflag.NewFlagSet("form", pflag.ContinueOnError) + flags.AddFlagSet(cmd.InheritedFlags()) + flags.AddFlagSet(cmd.Flags()) + flags.VisitAll(func(flag *pflag.Flag) { + if flag.Hidden || flag.Deprecated != "" || flag.Name == "help" || flag.Name == "version" { + return + } + value := flag.DefValue + if flag.Changed { + value = flag.Value.String() + } + if slice, ok := flag.Value.(pflag.SliceValue); ok { + value = csvString(slice.GetSlice()) + } + if flag.Value.Type() == "stringToString" { + value = strings.TrimSuffix(strings.TrimPrefix(value, "["), "]") + } + _, required := flag.Annotations[cobra.BashCompOneRequiredFlag] + global := cmd.Root().PersistentFlags().Lookup(flag.Name) == flag + field := Field{Name: flag.Name, Label: strings.ReplaceAll(flag.Name, "-", " "), Help: flag.Usage, Type: flag.Value.Type(), Value: value, Default: value, Required: required, Global: global, Advanced: !slices.Contains(common, flag.Name), Secret: flag.Name == "proxy" || strings.Contains(flag.Name, "password") || strings.Contains(flag.Name, "passcode") || strings.Contains(flag.Name, "token")} + if flag.Name == "ns" { + field.Label = "account namespace" + } + if flag.Name == "type" && strings.Join(action.Path, " ") == "login" { + field.Label = "login method" + } + field.Choices = choices(action.Path, flag.Name, flag.Usage) + if value, ok := globals[flag.Name]; ok && global { + field.Value, field.Dirty = value, true + } + if value, ok := action.Preset[flag.Name]; ok { + field.Value, field.Dirty = value, true + } + field.Advanced = field.Advanced && !required && !field.Dirty + form.Fields = append(form.Fields, field) + }) + // Some inherited commands accept arguments without declaring them in Use. + // Keep an argument field for every runnable command; Cobra validates it. + argumentHelp := "Separate arguments with spaces; quote paths or names containing spaces. Usage: " + cmd.UseLine() + if strings.Join(action.Path, " ") == "schedule" { + argumentHelp = "Backup options, for example: --all --media all --format both. These follow the -- separator." + } + argumentLabel := "arguments" + switch strings.Join(action.Path, " ") { + case "render": + argumentLabel = "archive directory" + case "stats": + argumentLabel = "JSON exports" + case "cron add", "cron remove", "cron run", "cron logs": + argumentLabel = "job name" + case "extension install": + argumentLabel = "extension sources" + case "extension remove", "extension upgrade": + argumentLabel = "extension names" + case "schedule": + argumentLabel = "backup options" + } + required := cmd.ValidateArgs(nil) != nil + noArgs := !required && cmd.ValidateArgs([]string{"example"}) != nil + form.Fields = append(form.Fields, Field{Name: "arguments", Label: argumentLabel, Help: argumentHelp, Type: "arguments", Required: required, Advanced: noArgs}) + slices.SortStableFunc(form.Fields, func(a, b Field) int { + rank := func(f Field) int { + if f.Required { + return -1 + } + if i := slices.Index(common, f.Name); i >= 0 { + return i + } + return len(common) + } + return rank(a) - rank(b) + }) + return form +} + +func choices(path []string, name, usage string) []string { + key := strings.Join(path, " ") + if name == "format" && slices.Contains([]string{"archive", "account", "sync", "render", "cron add"}, key) { + return []string{"json", "html", "both"} + } + if name == "type" && key == "login" { + return []string{"desktop", "code", "qr"} + } + if name == "target" && key == "schedule" { + return []string{"archive", "account", "sync"} + } + if !slices.Contains([]string{"type", "mode", "output", "target"}, name) { + return nil + } + if start := strings.Index(usage, "["); start >= 0 { + if end := strings.Index(usage[start:], "]"); end > 0 { + values := strings.Split(usage[start+1:start+end], ",") + if len(values) > 1 { + for i := range values { + values[i] = strings.TrimSpace(values[i]) + } + return values + } + } + } + return nil +} + +func csvString(values []string) string { + if len(values) == 0 { + return "" + } + var out strings.Builder + w := csv.NewWriter(&out) + _ = w.Write(values) + w.Flush() + return strings.TrimSuffix(out.String(), "\n") +} + +func (f Field) Display() string { + if f.Secret && f.Value != "" { + return "••••••••" + } + if f.Value == "" { + return "—" + } + if f.Type == "bool" { + if f.Value == "true" { + return "● on" + } + return "○ off" + } + return f.Value +} + +func (f Form) field(name string) *Field { + for i := range f.Fields { + if f.Fields[i].Name == name { + return &f.Fields[i] + } + } + return nil +} + +func (f Field) Error(err error) error { return fmt.Errorf("%s: %w", f.Label, err) } diff --git a/internal/tui/failure.go b/internal/tui/failure.go new file mode 100644 index 0000000..37c406c --- /dev/null +++ b/internal/tui/failure.go @@ -0,0 +1,29 @@ +package tui + +import ( + "fmt" + "regexp" + "strings" +) + +var proxyUserinfo = regexp.MustCompile(`(?i)([a-z][a-z0-9+.-]*://)[^\s/]*@`) + +func redactOutput(text string) string { + return proxyUserinfo.ReplaceAllString(text, "${1}@") +} + +func taskFailure(err error, output string) error { + if err == nil { + return nil + } + // Cobra's final Error line carries the actual transport/session failure. + // Keep it ahead of the process exit status, which is only an implementation detail. + lines := strings.Split(output, "\n") + for i := len(lines) - 1; i >= 0; i-- { + line := strings.TrimSpace(lines[i]) + if _, message, ok := strings.Cut(line, "Error:"); ok && strings.TrimSpace(message) != "" { + return fmt.Errorf("%s: %w", strings.TrimSpace(redactOutput(safeText(message))), err) + } + } + return err +} diff --git a/internal/tui/interaction.go b/internal/tui/interaction.go new file mode 100644 index 0000000..28165fa --- /dev/null +++ b/internal/tui/interaction.go @@ -0,0 +1,384 @@ +package tui + +import ( + "fmt" + "strings" + + tea "charm.land/bubbletea/v2" + "charm.land/lipgloss/v2" +) + +type button struct{ ID, Label string } + +func (m Model) buttons() []button { + switch m.screen { + case dashboard: + return []button{{"open", "Open"}, {"accounts", "Accounts"}, {"chats", "Chats"}, {"schedules", "Schedules"}} + case configure: + if m.source != nil { + return []button{{"list", "Back to list"}, {"review", "Review"}, {"advanced", "More options"}} + } + return []button{{"back", "Back"}, {"review", "Review"}, {"advanced", "More options"}} + case review: + return []button{{"edit", "Edit"}, {"run", "Run"}, {"home", "Home"}} + case running: + return []button{{"cancel", "Cancel"}, {"input", "Respond"}, {"follow", "Follow latest"}} + case result: + if m.loading { + return []button{{"cancel", "Stop loading"}, {"details", "Details"}, {"activity", "Activity"}} + } + buttons := []button{} + if m.source != nil { + buttons = append(buttons, button{"list", "Back to list"}) + } + switch m.data.Kind { + case "accounts": + buttons = append(buttons, button{"use", "Use account"}) + case "chat ls": + if len(m.data.Items) > 0 { + buttons = append(buttons, button{"archive", "Archive"}, button{"export", "Export"}, button{"members", "Members"}) + } + buttons = append(buttons, button{"refresh", "Refresh"}) + if m.last.err != nil { + buttons = append(buttons, button{"connection", "Connection settings"}) + } + case "cron list": + buttons = append(buttons, button{"jobrun", "Run backup"}, button{"joblogs", "Logs"}, button{"jobremove", "Remove"}) + } + if len(m.data.Items) > 0 { + buttons = append(buttons, button{"details", "Details"}) + } + return append(buttons, button{"activity", "Activity"}, button{"retry", "Run again"}, button{"edit", "Edit"}, button{"home", "Home"}) + } + return []button{{"home", "Home"}} +} +func (m Model) buttonBar(width int) string { + buttons := m.buttons() + start := 0 + for start < m.buttonFocus { + size := 0 + for i := start; i <= m.buttonFocus; i++ { + size += lipgloss.Width(buttons[i].Label) + 5 + } + if size <= width { + break + } + start++ + } + parts := []string{} + used := 0 + for i := start; i < len(buttons); i++ { + label := "[ " + buttons[i].Label + " ]" + size := lipgloss.Width(label) + if used+size > width { + break + } + style := selectedStyle + if i == m.buttonFocus && m.buttonsFocused { + style = lipgloss.NewStyle().Background(mint).Foreground(lipgloss.Color("#102C2C")).Bold(true) + } + parts = append(parts, style.Render(label)) + used += size + 1 + } + return strings.Join(parts, " ") +} +func (m *Model) cancelJob() { + m.cancelling = true + m.responding = false + if m.taskCancel != nil { + m.taskCancel() + } + if m.job != nil { + m.cancelling = true + m.responding = false + m.job.cancel() + } +} +func (m Model) sendInput(value string) tea.Cmd { + j := m.job + if j == nil || value == "" { + return nil + } + select { + case j.inputQ <- value: + return nil + default: + return func() tea.Msg { return inputErrorMsg{fmt.Errorf("input queue is full; wait for the task to respond")} } + } +} +func terminalKey(msg tea.KeyPressMsg) string { + if msg.Mod&tea.ModCtrl != 0 && msg.Code >= 'a' && msg.Code <= 'z' { + return string(msg.Code - 'a' + 1) + } + switch msg.String() { + case "enter": + return "\r" + case "backspace": + return "\x7f" + case "delete": + return "\x1b[3~" + case "tab": + return "\t" + case "shift+tab": + return "\x1b[Z" + case "home": + return "\x1b[H" + case "end": + return "\x1b[F" + case "up": + return "\x1b[A" + case "down": + return "\x1b[B" + case "right": + return "\x1b[C" + case "left": + return "\x1b[D" + case "space": + return " " + } + return msg.Text +} +func (m *Model) browse(action Action) tea.Cmd { + m.source = nil + m.open(action) + plan, err := m.form.Plan(m.base) + if err != nil { + m.err = err.Error() + return nil + } + m.plan = plan + if m.showChatCache() { + return nil + } + return m.begin() +} +func (m *Model) activate(id string) tea.Cmd { + if m.loading && id != "cancel" && id != "details" && id != "activity" { + m.err = "Stop loading before starting another task." + return nil + } + m.buttonsFocused = false + switch id { + case "list": + m.restoreList() + case "home", "back": + m.source = nil + m.screen = dashboard + m.err = "" + case "edit": + m.screen = configure + case "connection": + m.screen = configure + m.advanced = true + m.fieldSearch = "proxy" + m.focus = 0 + case "retry": + m.screen = review + m.scroll = 0 + case "refresh": + return m.begin() + case "run": + return m.begin() + case "cancel": + m.cancelJob() + case "input": + m.responding = !m.responding + case "follow": + m.follow = true + case "advanced": + m.advanced = !m.advanced + m.focus = 0 + case "review": + m.prepareReview() + case "open": + actions := m.filteredActions() + if len(actions) > 0 { + action := actions[m.selected] + path := strings.Join(action.Path, " ") + if path == "accounts" || path == "chat ls" || path == "cron list" { + return m.browse(action) + } + m.open(action) + } + case "accounts", "chats", "schedules": + path := map[string]string{"accounts": "accounts", "chats": "chat ls", "schedules": "cron list"}[id] + for _, action := range m.actions { + if strings.Join(action.Path, " ") == path && action.Group != "Quick start" { + return m.browse(action) + } + } + case "activity": + m.resultTab = 1 + m.scroll = 0 + case "details": + m.resultTab = 2 + m.scroll = 0 + default: + rows := m.resultItems() + if len(rows) == 0 || m.resultSelected >= len(rows) { + m.err = "Select a result first." + return nil + } + row := rows[m.resultSelected] + switch id { + case "use": + if row.Status != "ready" { + m.err = "That account is " + row.Status + "; choose an available account." + return nil + } + m.globals["ns"] = row.ID + m.screen = dashboard + m.err = "" + case "archive": + m.saveList() + m.openPath("archive", map[string]string{"chat": row.ID, "media": "all", "format": "both"}) + case "export": + m.saveList() + m.openPath("chat export", map[string]string{"chat": row.ID}) + case "members": + m.saveList() + m.openPath("chat users", map[string]string{"chat": row.ID}) + case "jobrun", "joblogs", "jobremove": + m.saveList() + path := map[string]string{"jobrun": "cron run", "joblogs": "cron logs", "jobremove": "cron remove"}[id] + m.openPath(path, map[string]string{"arguments": fmt.Sprintf("%q", row.ID)}) + plan, err := m.form.Plan(m.base) + if err != nil { + m.err = err.Error() + return nil + } + m.plan = plan + if id == "joblogs" { + return m.begin() + } + m.screen = review + } + } + return nil +} +func (m Model) mouseClick(msg tea.MouseClickMsg) (tea.Model, tea.Cmd) { + if msg.Button != tea.MouseLeft || m.help || m.editing || m.searching { + return m, nil + } + width, height := m.width-4, m.height-7 + if msg.Y == 3+height-1 { + buttons := m.buttons() + start := 0 + for start < m.buttonFocus { + size := 0 + for i := start; i <= m.buttonFocus; i++ { + size += lipgloss.Width(buttons[i].Label) + 5 + } + if size <= width { + break + } + start++ + } + x := 2 + for i := start; i < len(buttons); i++ { + size := lipgloss.Width(buttons[i].Label) + 4 + if x+size > m.width-2 { + break + } + if msg.X >= x && msg.X < x+size { + m.buttonFocus = i + cmd := m.activate(buttons[i].ID) + return m, cmd + } + x += size + 1 + } + } + bodyHeight := height - 2 + switch m.screen { + case dashboard: + if width >= 86 && msg.X < 22 && msg.Y >= 5 { + index := (msg.Y - 5) / 2 + if index < len(Groups) { + m.group = index + m.selected = 0 + m.search = "" + } + return m, nil + } + rowHeight := 3 + if bodyHeight < 23 { + rowHeight = 2 + } + page := max(1, (bodyHeight-6)/rowHeight) + start := max(0, m.selected-page+1) + index := start + (msg.Y-7)/rowHeight + actions := m.filteredActions() + if msg.Y >= 7 && index >= 0 && index < len(actions) { + m.selected = index + return m, m.activate("open") + } + case configure: + page := max(1, bodyHeight-11) + start := max(0, m.focus-page+1) + index := start + msg.Y - 8 + if msg.Y >= 8 && index >= 0 && index < len(m.visibleFields()) { + m.focus = index + next, cmd := m.Update(tea.KeyPressMsg{Code: tea.KeyEnter}) + return next, cmd + } + case result: + if msg.Y == 7 { + if msg.X >= 2 && msg.X < 10 { + m.resultTab = 0 + } else if msg.X >= 13 && msg.X < 22 { + m.resultTab = 1 + } else if msg.X >= 25 && msg.X < 33 { + m.resultTab = 2 + } + m.scroll = 0 + return m, nil + } + rows := m.resultItems() + rowStart, page := m.resultListGeometry(bodyHeight) + start := max(0, m.resultSelected-page+1) + index := start + (msg.Y-3-rowStart)/2 + if m.resultTab == 0 && msg.Y >= 3+rowStart && index >= 0 && index < len(rows) { + m.resultSelected = index + m.buttonsFocused = false + } + } + return m, nil +} + +func (m *Model) prepareReview() { + plan, err := m.form.Plan(m.base) + if err != nil { + m.err = err.Error() + return + } + m.plan = plan + for _, field := range m.form.Fields { + if field.Global { + if field.Dirty { + m.globals[field.Name] = field.Value + } else { + delete(m.globals, field.Name) + } + } + } + m.screen = review + m.scroll = 0 + m.err = "" + m.buttonsFocused = false +} + +func (m *Model) scrollActivity(delta int) { + available := max(1, m.height-16) + if m.screen == running { + available = max(1, m.height-18) + if len(m.progress) == 3 { + available = max(1, available-4) + } + } + last := max(0, len(strings.Split(m.output, "\n"))-available) + if m.follow && m.screen == running { + m.scroll = last + } + m.follow = false + m.scroll = max(0, min(last, m.scroll+delta)) +} diff --git a/internal/tui/model.go b/internal/tui/model.go new file mode 100644 index 0000000..0a8f801 --- /dev/null +++ b/internal/tui/model.go @@ -0,0 +1,612 @@ +package tui + +import ( + "context" + "os" + "path/filepath" + "slices" + "strings" + "time" + + tea "charm.land/bubbletea/v2" +) + +type screen int + +const ( + dashboard screen = iota + configure + review + result + running +) + +type Model struct { + actions []Action + base []string + globals map[string]string + ctx context.Context + run func(context.Context, Plan) tea.Cmd + width, height int + screen screen + group, selected, focus, scroll int + search, fieldSearch string + searching, advanced, editing, help bool + input []rune + cursor int + form Form + plan Plan + last finishedMsg + loading bool + stage string + taskCancel context.CancelFunc + source *resultSnapshot + showCommand bool + chatCache map[[32]byte]browseCache + cachedAt time.Time + + job *job + progress []string + output string + data resultData + resultSelected, resultTab, buttonFocus int + resultSearch string + buttonsFocused, responding, follow, cancelling bool + started time.Time + err string +} + +func New(actions []Action, base []string, namespace string, ctx context.Context) Model { + return Model{actions: actions, base: slices.Clone(base), globals: map[string]string{"ns": namespace}, ctx: ctx, run: RunCommand, width: 100, height: 32} +} + +func (m Model) Init() tea.Cmd { return nil } + +func (m Model) filteredActions() []Action { + var out []Action + for _, action := range m.actions { + if m.search == "" { + if Groups[m.group] == "All commands" && action.Group == "Quick start" { + continue + } + if Groups[m.group] != "All commands" && action.Group != Groups[m.group] { + continue + } + } else if action.Group == "Quick start" { + continue + } + if matches(action.Title+" "+action.Description+" "+action.Group, m.search) { + out = append(out, action) + } + } + return out +} + +func matches(value, query string) bool { + value = strings.ToLower(value) + for _, word := range strings.Fields(strings.ToLower(query)) { + if !strings.Contains(value, word) { + return false + } + } + return true +} + +func (m Model) visibleFields() []int { + var out []int + for i, field := range m.form.Fields { + if !m.advanced && field.Advanced && m.fieldSearch == "" { + continue + } + if matches(field.Label+" "+field.Name+" "+field.Help, m.fieldSearch) { + out = append(out, i) + } + } + return out +} + +func (m *Model) open(action Action) { + m.form = NewForm(action, m.globals) + m.screen, m.focus, m.scroll, m.err = configure, 0, 0, "" + m.advanced, m.editing, m.searching = false, false, false + m.fieldSearch = "" + m.buttonsFocused = false + m.showCommand = false + m.buttonFocus = 0 +} + +func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { + switch msg := msg.(type) { + case tea.WindowSizeMsg: + m.width, m.height = msg.Width, msg.Height + if m.job != nil { + m.job.mu.Lock() + if m.job.resize != nil { + m.job.resize(max(20, m.width-6), max(5, m.height-17)) + } + m.job.terminal.width = max(20, min(m.width-6, 500)) + m.job.terminal.height = max(5, min(m.height-17, 200)) + m.job.mu.Unlock() + } + return m, nil + case startedMsg: + m.job = msg.job + if m.cancelling { + m.job.cancel() + } + m.started = msg.job.started + msg.job.mu.Lock() + if msg.job.resize != nil { + msg.job.resize(max(20, m.width-6), max(5, m.height-17)) + } + msg.job.mu.Unlock() + return m, poll() + case pollMsg: + if m.job == nil { + return m, nil + } + m.job.mu.Lock() + m.output = redactOutput(m.job.terminal.text()) + m.progress = append([]string(nil), m.job.terminal.progress...) + m.stage = m.job.stage + if m.job.streamSeen { + m.data = resultData{Kind: "chat ls", Items: append([]item(nil), m.job.items...)} + if len(m.data.Items) > 0 { + m.screen = result + m.loading = !m.job.done + } + } + done := m.job.done + if done { + m.last = finishedMsg{taskFailure(m.job.err, m.output), m.job.ended.Sub(m.job.started)} + if m.job.structured && !m.job.overflow && !m.job.streamSeen { + data, err := decodeResults(m.plan.Path, m.job.stdout.Bytes()) + if err == nil { + m.data = data + } else { + if m.job.err == nil { + m.err = "Could not build the result list; activity output is available." + } + } + } + if m.job.overflow { + m.err = "Result exceeds the 4 MiB list limit; refine the query." + } + } + m.job.mu.Unlock() + if done { + if m.last.err == nil && m.job.streamSeen && !m.job.overflow { + m.saveChatCache() + } + m.loading = false + m.screen = result + if m.taskCancel != nil { + m.taskCancel() + } + m.responding = false + m.buttonFocus = 0 + if m.data.Kind == "" || (m.last.err != nil && len(m.data.Items) == 0) { + m.resultTab = 1 + } + return m, nil + } + return m, poll() + case inputErrorMsg: + if msg.err != nil { + m.err = msg.err.Error() + } + return m, nil + case tea.MouseClickMsg: + return m.mouseClick(msg) + case tea.MouseWheelMsg: + delta := 3 + if msg.Button == tea.MouseWheelUp { + delta = -3 + } + if m.screen == result && m.resultTab == 0 { + m.resultSelected = max(0, min(max(0, len(m.resultItems())-1), m.resultSelected+delta)) + } else if m.screen == running || m.screen == result { + m.scrollActivity(delta) + } + return m, nil + + case finishedMsg: + m.loading = false + if m.taskCancel != nil { + m.taskCancel() + } + m.resultTab = 1 + m.last, m.screen, m.scroll = msg, result, 0 + return m, nil + case tea.PasteMsg: + if m.screen == running && m.responding && m.job != nil { + return m, m.sendInput(msg.Content) + } + if m.editing || m.searching { + m.insert(strings.NewReplacer("\n", " ", "\r", " ", "\t", " ").Replace(msg.Content)) + m.syncSearch() + } + return m, nil + case tea.KeyPressMsg: + key := msg.String() + if key == "ctrl+c" { + if m.screen == running || m.loading { + m.cancelJob() + return m, nil + } + return m, tea.Quit + } + if m.screen == running && m.responding { + if key == "esc" { + m.responding = false + return m, nil + } + return m, m.sendInput(terminalKey(msg)) + } + if m.help { + switch key { + case "esc", "?", "enter": + m.help, m.scroll = false, 0 + case "up", "k", "pgup": + m.scroll = max(0, m.scroll-1) + case "down", "j", "pgdown": + m.scroll++ + } + return m, nil + } + if m.editing || m.searching { + return m.updateInput(msg) + } + if key == "?" { + m.help, m.scroll = true, 0 + return m, nil + } + if key == "q" && m.screen == dashboard { + return m, tea.Quit + } + if key == "f6" { + m.buttonsFocused = !m.buttonsFocused + m.buttonFocus = 0 + return m, nil + } + if m.buttonsFocused && (key == "tab" || key == "shift+tab") { + delta := 1 + if key == "shift+tab" { + delta = -1 + } + m.buttonFocus = (m.buttonFocus + len(m.buttons()) + delta) % len(m.buttons()) + return m, nil + } + if key == "tab" && (m.screen == review || m.screen == running || m.screen == result) { + m.buttonsFocused = true + m.buttonFocus = (m.buttonFocus + 1) % len(m.buttons()) + return m, nil + } + if key == "shift+tab" && (m.screen == review || m.screen == running || m.screen == result) { + m.buttonsFocused = true + m.buttonFocus = (m.buttonFocus + len(m.buttons()) - 1) % len(m.buttons()) + return m, nil + } + if m.buttonsFocused && (key == "left" || key == "right") { + delta := 1 + if key == "left" { + delta = -1 + } + m.buttonFocus = (m.buttonFocus + len(m.buttons()) + delta) % len(m.buttons()) + return m, nil + } + if m.buttonsFocused && key == "enter" { + return m, m.activate(m.buttons()[m.buttonFocus].ID) + } + switch m.screen { + case running: + switch key { + case "esc": + m.cancelJob() + case "i": + m.responding = true + case "up", "k", "pgup": + m.scrollActivity(-3) + case "down", "j", "pgdown": + m.scrollActivity(3) + case "end", "f": + m.follow = true + } + case dashboard: + actions := m.filteredActions() + switch key { + case "up", "k": + m.selected = max(0, m.selected-1) + case "down", "j": + m.selected = min(max(0, len(actions)-1), m.selected+1) + case "pgdown": + m.selected = min(max(0, len(actions)-1), m.selected+5) + case "pgup": + m.selected = max(0, m.selected-5) + case "home": + m.selected = 0 + case "end": + m.selected = max(0, len(actions)-1) + case "left", "shift+tab", "h": + m.group = (m.group + len(Groups) - 1) % len(Groups) + m.selected, m.search = 0, "" + case "right", "tab", "l": + m.group = (m.group + 1) % len(Groups) + m.selected, m.search = 0, "" + case "/": + m.searching = true + m.input, m.cursor = []rune(m.search), len([]rune(m.search)) + case "esc": + m.search, m.selected = "", 0 + case "enter": + if len(actions) > 0 { + action := actions[m.selected] + if path := strings.Join(action.Path, " "); path == "accounts" || path == "chat ls" || path == "cron list" { + return m, m.browse(action) + } + m.open(action) + } + } + case configure: + fields := m.visibleFields() + switch key { + case "esc": + if m.source != nil && m.fieldSearch == "" { + m.restoreList() + break + } + if m.fieldSearch != "" { + m.fieldSearch, m.focus = "", 0 + } else { + m.screen, m.err = dashboard, "" + } + case "up", "k", "shift+tab": + m.focus = max(0, m.focus-1) + case "down", "j", "tab": + m.focus = min(max(0, len(fields)-1), m.focus+1) + case "pgdown": + m.focus = min(max(0, len(fields)-1), m.focus+8) + case "pgup": + m.focus = max(0, m.focus-8) + case "ctrl+a": + m.advanced = !m.advanced + m.focus = 0 + case "/": + m.searching = true + m.input, m.cursor = []rune(m.fieldSearch), len([]rune(m.fieldSearch)) + case "ctrl+r": + m.prepareReview() + + case "enter", "space", " ", "right", "left": + if len(fields) == 0 { + break + } + field := &m.form.Fields[fields[m.focus]] + if field.Type == "bool" { + if field.Value == "true" { + field.Value = "false" + } else { + field.Value = "true" + } + field.Dirty, m.err = true, "" + } else if key != "enter" && len(field.Choices) > 0 && !strings.Contains(field.Type, "Slice") { + next := slices.Index(field.Choices, field.Value) + 1 + if key == "left" { + next -= 2 + } + field.Value, field.Dirty = field.Choices[(next+len(field.Choices))%len(field.Choices)], true + } else { + m.input, m.cursor, m.editing = []rune(field.Value), len([]rune(field.Value)), true + } + case "ctrl+d": + if len(fields) > 0 { + field := &m.form.Fields[fields[m.focus]] + field.Value, field.Dirty, m.err = field.Default, false, "" + } + } + case review: + switch key { + case "esc", "e": + m.screen, m.scroll = configure, 0 + case "c": + m.showCommand = !m.showCommand + case "enter": + return m, m.begin() + case "up", "k", "pgup": + m.scroll = max(0, m.scroll-1) + case "down", "j", "pgdown": + m.scroll++ + } + case result: + if m.loading && (key == "esc" || key == "e" || key == "r" || key == "a" || key == "s") { + m.cancelJob() + return m, nil + } + rows := m.resultItems() + switch key { + case "esc": + if m.resultSearch != "" { + m.resultSearch = "" + m.resultSelected = 0 + } else { + m.screen = dashboard + m.source = nil + m.err = "" + m.buttonsFocused = false + } + case "enter": + if len(rows) > 0 { + m.resultTab = 2 + } else { + m.screen = dashboard + } + case "up", "k": + m.buttonsFocused = false + if m.resultTab == 0 { + m.resultSelected = max(0, m.resultSelected-1) + } else { + m.scroll = max(0, m.scroll-1) + } + case "down", "j": + m.buttonsFocused = false + if m.resultTab == 0 { + m.resultSelected = min(max(0, len(rows)-1), m.resultSelected+1) + } else { + m.scroll++ + } + case "pgup": + m.scroll = max(0, m.scroll-8) + m.resultSelected = max(0, m.resultSelected-8) + case "pgdown": + m.scroll += 8 + m.resultSelected = min(max(0, len(rows)-1), m.resultSelected+8) + case "/": + m.searching = true + m.input = []rune(m.resultSearch) + m.cursor = len(m.input) + case "l": + m.resultTab = 1 + m.scroll = 0 + case "t": + m.resultTab = 0 + m.scroll = 0 + case "d": + m.resultTab = 2 + m.scroll = 0 + case "e": + m.screen = configure + m.buttonsFocused = false + case "r": + m.screen = review + m.scroll = 0 + m.buttonsFocused = false + case "a": + if m.data.Kind == "chat ls" { + return m, m.activate("archive") + } + case "s": + if m.data.Kind == "accounts" { + return m, m.activate("use") + } + } + + } + } + return m, nil +} + +func (m Model) updateInput(msg tea.KeyPressMsg) (tea.Model, tea.Cmd) { + switch msg.String() { + case "esc": + if m.searching { + m.input = nil + m.syncSearch() + } + m.editing, m.searching = false, false + case "enter": + if m.editing { + fields := m.visibleFields() + if len(fields) > 0 { + field := &m.form.Fields[fields[m.focus]] + field.Value, field.Dirty = string(m.input), true + m.err = "" + } + } + m.editing, m.searching = false, false + case "left": + m.cursor = max(0, m.cursor-1) + case "right": + m.cursor = min(len(m.input), m.cursor+1) + case "home", "ctrl+a": + m.cursor = 0 + case "end", "ctrl+e": + m.cursor = len(m.input) + case "backspace": + if m.cursor > 0 { + m.input = slices.Delete(m.input, m.cursor-1, m.cursor) + m.cursor-- + } + case "delete": + if m.cursor < len(m.input) { + m.input = slices.Delete(m.input, m.cursor, m.cursor+1) + } + case "ctrl+u": + m.input, m.cursor = nil, 0 + case "ctrl+k": + m.input = m.input[:m.cursor] + case "ctrl+w": + start := m.cursor + for start > 0 && m.input[start-1] == ' ' { + start-- + } + for start > 0 && m.input[start-1] != ' ' { + start-- + } + m.input = slices.Delete(m.input, start, m.cursor) + m.cursor = start + case "tab": + if m.editing { + m.completePath() + } + default: + if msg.Text != "" { + m.insert(msg.Text) + } + } + m.syncSearch() + return m, nil +} + +func (m *Model) insert(value string) { + runes := []rune(value) + m.input = slices.Insert(m.input, m.cursor, runes...) + m.cursor += len(runes) +} + +func (m *Model) syncSearch() { + if !m.searching { + return + } + if m.screen == dashboard { + m.search, m.selected = string(m.input), 0 + } else if m.screen == result { + m.resultSearch, m.resultSelected = string(m.input), 0 + } else { + m.fieldSearch, m.focus = string(m.input), 0 + } +} + +func (m *Model) completePath() { + value := string(m.input) + if value == "" { + return + } + if strings.HasPrefix(value, "~/") { + if home, err := os.UserHomeDir(); err == nil { + value = filepath.Join(home, value[2:]) + } + } + // Read a single directory instead of expanding arbitrary glob patterns. + dir, prefix := filepath.Split(value) + if dir == "" { + dir = "." + } + entries, err := os.ReadDir(dir) + if err != nil { + return + } + var candidates []string + for _, entry := range entries { + if strings.HasPrefix(entry.Name(), prefix) { + candidate := filepath.Join(dir, entry.Name()) + if entry.IsDir() { + candidate += string(filepath.Separator) + } + candidates = append(candidates, candidate) + } + } + if len(candidates) == 1 { + m.input = []rune(candidates[0]) + m.cursor = len(m.input) + } +} diff --git a/internal/tui/plan.go b/internal/tui/plan.go new file mode 100644 index 0000000..e24c86e --- /dev/null +++ b/internal/tui/plan.go @@ -0,0 +1,200 @@ +package tui + +import ( + "encoding/csv" + "fmt" + "slices" + "strconv" + "strings" + "time" + + "github.com/kballard/go-shellquote" +) + +type Plan struct { + Title string + Args []string + Path []string + width, height int +} + +func (f Form) Plan(base []string) (Plan, error) { + plan := Plan{Title: f.Action.Title, Args: slices.Clone(base), Path: slices.Clone(f.Action.Path)} + // Changed global fields replace startup flags, rather than repeating them in + // the preview (or appending values to a string-slice setting). + for _, field := range f.Fields { + if !field.Global || !field.Dirty { + continue + } + plan.Args = slices.DeleteFunc(plan.Args, func(arg string) bool { + return strings.HasPrefix(arg, "--"+field.Name+"=") + }) + } + var local, positionals []string + for _, field := range f.Fields { + if field.Type == "arguments" { + var err error + positionals, err = shellquote.Split(field.Value) + if err != nil { + return plan, field.Error(err) + } + continue + } + if field.Required && (!field.Dirty || strings.TrimSpace(field.Value) == "") { + return plan, fmt.Errorf("%s is required; enter a value", field.Label) + } + if !field.Dirty { + continue + } + if err := validate(field); err != nil { + return plan, field.Error(err) + } + args := []string{"--" + field.Name + "=" + field.Value} + if field.Type == "stringArray" { + args = nil + values, err := readCSV(field.Value) + if err != nil { + return plan, field.Error(err) + } + for _, value := range values { + args = append(args, "--"+field.Name+"="+value) + } + } + if field.Global { + plan.Args = append(plan.Args, args...) + } else { + local = append(local, args...) + } + } + if err := f.Action.Command.ValidateArgs(positionals); err != nil { + return plan, err + } + value := func(name string) string { + if field := f.field(name); field != nil { + return field.Value + } + return "" + } + path := strings.Join(f.Action.Path, " ") + if path == "archive" || path == "sync" || path == "cron add" { + if value("all") == "true" && value("chat") != "" { + return plan, fmt.Errorf("choose all chats or specific chats; clear one of these options") + } + if value("include-left") == "true" && (value("all") != "true" || value("takeout") != "true") { + return plan, fmt.Errorf("including left channels requires all chats and takeout") + } + } + for _, name := range []string{"since", "until"} { + if date := value(name); date != "" && !validDate(date) { + return plan, fmt.Errorf("%s: use YYYY-MM-DD, RFC3339 or Unix seconds", name) + } + } + plan.Args = append(plan.Args, f.Action.Path...) + plan.Args = append(plan.Args, local...) + if len(positionals) > 0 { + if !f.Action.Command.DisableFlagParsing { + plan.Args = append(plan.Args, "--") + } + plan.Args = append(plan.Args, positionals...) + } + return plan, nil +} + +func validate(field Field) error { + var err error + switch field.Type { + case "bool": + _, err = strconv.ParseBool(field.Value) + case "int", "int8", "int16", "int32", "int64", "count": + bits := 64 + if field.Type == "int8" { + bits = 8 + } + if field.Type == "int16" { + bits = 16 + } + if field.Type == "int32" { + bits = 32 + } + _, err = strconv.ParseInt(field.Value, 0, bits) + case "uint", "uint8", "uint16", "uint32", "uint64": + bits := 64 + if field.Type == "uint8" { + bits = 8 + } + if field.Type == "uint16" { + bits = 16 + } + if field.Type == "uint32" { + bits = 32 + } + _, err = strconv.ParseUint(field.Value, 0, bits) + case "float32", "float64": + _, err = strconv.ParseFloat(field.Value, 64) + case "duration": + _, err = time.ParseDuration(field.Value) + case "stringSlice", "stringArray", "stringToString", "intSlice", "int64Slice", "uintSlice", "boolSlice", "durationSlice", "float64Slice": + var values []string + values, err = readCSV(field.Value) + if err == nil { + for _, value := range values { + if field.Type == "stringToString" && !strings.Contains(value, "=") { + return fmt.Errorf("use comma-separated key=value pairs") + } + if subtype := strings.TrimSuffix(field.Type, "Slice"); subtype != field.Type && subtype != "string" { + if e := validate(Field{Type: subtype, Value: value}); e != nil { + return e + } + } + } + } + } + if err != nil { + return err + } + if len(field.Choices) > 0 && !strings.Contains(field.Type, "Slice") && !slices.Contains(field.Choices, field.Value) { + return fmt.Errorf("choose %s", strings.Join(field.Choices, ", ")) + } + return nil +} + +func readCSV(value string) ([]string, error) { + if value == "" { + return nil, nil + } + return csv.NewReader(strings.NewReader(value)).Read() +} + +func validDate(value string) bool { + if _, err := strconv.ParseInt(value, 10, 64); err == nil { + return true + } + for _, layout := range []string{"2006-01-02", time.RFC3339} { + if _, err := time.Parse(layout, value); err == nil { + return true + } + } + return false +} + +// Preview is suitable for display and never exposes credentials in global flags. +// Execution uses Args directly; no command string is evaluated by a shell. +func (p Plan) Preview() string { + args := append([]string{"ta"}, p.Args...) + secretNext := false + for i, arg := range args { + if secretNext { + args[i], secretNext = "", false + continue + } + name, _, hasValue := strings.Cut(arg, "=") + if strings.HasPrefix(name, "--") && (name == "--proxy" || strings.Contains(name, "password") || strings.Contains(name, "passcode") || strings.Contains(name, "token")) { + if hasValue { + args[i] = name + "=" + } else { + secretNext = true + } + } + } + return shellquote.Join(args...) +} diff --git a/internal/tui/pty_darwin.go b/internal/tui/pty_darwin.go new file mode 100644 index 0000000..224f254 --- /dev/null +++ b/internal/tui/pty_darwin.go @@ -0,0 +1,36 @@ +//go:build darwin + +package tui + +import ( + "os" + "unsafe" + + "golang.org/x/sys/unix" +) + +func openPTY(width, height int) (*os.File, *os.File, error) { + master, err := os.OpenFile("/dev/ptmx", os.O_RDWR|unix.O_NOCTTY, 0) + if err != nil { + return nil, nil, err + } + fail := func(err error) (*os.File, *os.File, error) { master.Close(); return nil, nil, err } + for _, request := range []uintptr{unix.TIOCPTYGRANT, unix.TIOCPTYUNLK} { + if _, _, errno := unix.Syscall(unix.SYS_IOCTL, master.Fd(), request, 0); errno != 0 { + return fail(errno) + } + } + var name [128]byte + if _, _, errno := unix.Syscall(unix.SYS_IOCTL, master.Fd(), unix.TIOCPTYGNAME, uintptr(unsafe.Pointer(&name[0]))); errno != 0 { + return fail(errno) + } + slave, err := os.OpenFile(unix.ByteSliceToString(name[:]), os.O_RDWR|unix.O_NOCTTY, 0) + if err != nil { + return fail(err) + } + if err := resizePTY(master, width, height); err != nil { + slave.Close() + return fail(err) + } + return master, slave, nil +} diff --git a/internal/tui/pty_linux.go b/internal/tui/pty_linux.go new file mode 100644 index 0000000..3651edf --- /dev/null +++ b/internal/tui/pty_linux.go @@ -0,0 +1,34 @@ +//go:build linux + +package tui + +import ( + "fmt" + "os" + + "golang.org/x/sys/unix" +) + +func openPTY(width, height int) (*os.File, *os.File, error) { + master, err := os.OpenFile("/dev/ptmx", os.O_RDWR|unix.O_NOCTTY, 0) + if err != nil { + return nil, nil, err + } + fail := func(err error) (*os.File, *os.File, error) { master.Close(); return nil, nil, err } + if err := unix.IoctlSetPointerInt(int(master.Fd()), unix.TIOCSPTLCK, 0); err != nil { + return fail(err) + } + number, err := unix.IoctlGetInt(int(master.Fd()), unix.TIOCGPTN) + if err != nil { + return fail(err) + } + slave, err := os.OpenFile(fmt.Sprintf("/dev/pts/%d", number), os.O_RDWR|unix.O_NOCTTY, 0) + if err != nil { + return fail(err) + } + if err := resizePTY(master, width, height); err != nil { + slave.Close() + return fail(err) + } + return master, slave, nil +} diff --git a/internal/tui/pty_other.go b/internal/tui/pty_other.go new file mode 100644 index 0000000..3bbc106 --- /dev/null +++ b/internal/tui/pty_other.go @@ -0,0 +1,17 @@ +//go:build !darwin && !linux + +package tui + +import ( + "fmt" + "os" + "os/exec" +) + +func openPTY(width, height int) (*os.File, *os.File, error) { + return nil, nil, fmt.Errorf("interactive embedded tasks currently require macOS or Linux") +} +func configurePTY(child *exec.Cmd) {} +func resizePTY(file *os.File, width, height int) error { return nil } +func interruptJob(child *exec.Cmd) { _ = child.Process.Kill() } +func killJob(child *exec.Cmd) { _ = child.Process.Kill() } diff --git a/internal/tui/pty_unix.go b/internal/tui/pty_unix.go new file mode 100644 index 0000000..7c91e27 --- /dev/null +++ b/internal/tui/pty_unix.go @@ -0,0 +1,32 @@ +//go:build darwin || linux + +package tui + +import ( + "os" + "os/exec" + "syscall" + + "golang.org/x/sys/unix" +) + +func configurePTY(child *exec.Cmd) { + child.SysProcAttr = &syscall.SysProcAttr{Setsid: true, Setctty: true, Ctty: 0} +} +func resizePTY(file *os.File, width, height int) error { + return unix.IoctlSetWinsize(int(file.Fd()), unix.TIOCSWINSZ, &unix.Winsize{Col: uint16(max(20, min(width, 500))), Row: uint16(max(5, min(height, 200)))}) +} +func interruptJob(child *exec.Cmd) { + if child.SysProcAttr != nil && child.SysProcAttr.Setsid { + _ = unix.Kill(-child.Process.Pid, unix.SIGINT) + } else { + _ = child.Process.Signal(os.Interrupt) + } +} +func killJob(child *exec.Cmd) { + if child.SysProcAttr != nil && child.SysProcAttr.Setsid { + _ = unix.Kill(-child.Process.Pid, unix.SIGKILL) + } else { + _ = child.Process.Kill() + } +} diff --git a/internal/tui/results.go b/internal/tui/results.go new file mode 100644 index 0000000..f36fbb5 --- /dev/null +++ b/internal/tui/results.go @@ -0,0 +1,270 @@ +package tui + +import ( + "context" + "crypto/sha256" + "encoding/json" + "fmt" + "slices" + "strconv" + "strings" + "time" + + tea "charm.land/bubbletea/v2" +) + +type item struct{ ID, Title, Subtitle, Detail, Status string } +type metric struct{ Label, Value string } +type resultData struct { + Kind string + Items []item + Metrics []metric +} + +func decodeResults(path []string, data []byte) (resultData, error) { + result := resultData{Kind: strings.Join(path, " ")} + switch result.Kind { + case "accounts": + var rows []struct { + Namespace, Username, Status string + ID json.Number + } + if err := json.Unmarshal(data, &rows); err != nil { + return result, err + } + for _, r := range rows { + user := r.Username + if user != "" { + user = "@" + user + } + result.Items = append(result.Items, item{r.Namespace, safeText(r.Namespace), safeText(user + " " + string(r.ID)), "Namespace: " + safeText(r.Namespace) + "\nAccount: " + safeText(string(r.ID)) + "\nStatus: " + safeText(r.Status), r.Status}) + } + case "chat ls": + var rows []struct { + ID json.Number + Type string + Name string `json:"visible_name"` + Username string + Topics []struct { + ID int + Title string + } + } + if err := json.Unmarshal(data, &rows); err != nil { + return result, err + } + for _, r := range rows { + name := r.Name + if name == "" { + name = r.Username + } + if name == "" { + name = string(r.ID) + } + sub := r.Type + " · " + string(r.ID) + if r.Username != "" { + sub += " · @" + r.Username + } + detail := safeText(name) + "\n" + safeText(sub) + for _, topic := range r.Topics { + detail += "\nTopic " + strconv.Itoa(topic.ID) + ": " + safeText(topic.Title) + } + result.Items = append(result.Items, item{string(r.ID), safeText(name), safeText(sub), detail, ""}) + } + case "cron list": + var rows []struct { + Name, Schedule, Log string + Installed bool + } + if err := json.Unmarshal(data, &rows); err != nil { + return result, err + } + for _, r := range rows { + status := "installed" + if !r.Installed { + status = "not in crontab" + } + result.Items = append(result.Items, item{r.Name, safeText(r.Name), safeText(r.Schedule + " · " + status), "Schedule: " + safeText(r.Schedule) + "\nStatus: " + status + "\nLog: " + safeText(r.Log), status}) + } + case "stats": + var values map[string]json.RawMessage + if err := json.Unmarshal(data, &values); err != nil { + return result, err + } + for _, key := range []string{"messages", "words", "media_bytes", "service_messages", "characters", "replies", "forwards", "edited"} { + var number json.Number + if json.Unmarshal(values[key], &number) == nil && number != "" { + label := strings.ReplaceAll(key, "_", " ") + result.Metrics = append(result.Metrics, metric{label, number.String()}) + result.Items = append(result.Items, item{key, label, number.String(), label + ": " + number.String(), ""}) + } + } + for _, key := range []string{"by_media", "by_day", "by_sender"} { + var counts map[string]int64 + if json.Unmarshal(values[key], &counts) != nil { + continue + } + keys := make([]string, 0, len(counts)) + for k := range counts { + keys = append(keys, k) + } + slices.Sort(keys) + for _, k := range keys { + label := safeText(k) + result.Items = append(result.Items, item{key + ":" + k, label, strings.TrimPrefix(key, "by_") + " · " + fmt.Sprint(counts[k]), label + "\nCount: " + fmt.Sprint(counts[k]), ""}) + } + } + } + return result, nil +} +func (m Model) resultItems() []item { + if m.resultSearch == "" { + return m.data.Items + } + rows := []item{} + for _, row := range m.data.Items { + if matches(row.Title+" "+row.Subtitle, m.resultSearch) { + rows = append(rows, row) + } + } + return rows +} +func (m *Model) openPath(path string, preset map[string]string) { + for _, action := range m.actions { + if strings.Join(action.Path, " ") == path && action.Group != "Quick start" { + m.open(action) + for name, value := range preset { + if f := m.form.field(name); f != nil { + f.Value, f.Dirty = value, true + } + } + return + } + } + m.err = "This action is unavailable in this build." +} +func (m *Model) begin() tea.Cmd { + if len(m.plan.Path) > 0 { + switch m.plan.Path[0] { + case "login", "recover", "migrate": + m.chatCache = nil + } + } + m.loading = false + m.cachedAt = time.Time{} + m.stage = "" + m.started = time.Now() + taskCtx, cancel := context.WithCancel(m.ctx) + m.taskCancel = cancel + m.plan.width, m.plan.height = max(20, m.width-6), max(5, m.height-17) + m.screen = running + m.last = finishedMsg{} + m.output = "" + m.progress = nil + m.data = resultData{} + if strings.Join(m.plan.Path, " ") == "chat ls" { + m.data.Kind = "chat ls" + m.stage = "Opening saved Telegram session…" + } + m.job = nil + m.cancelling = false + m.responding = false + m.follow = true + m.scroll = 0 + m.resultSelected = 0 + m.resultSearch = "" + m.resultTab = 0 + m.buttonFocus = 0 + m.buttonsFocused = false + m.err = "" + return m.run(taskCtx, m.plan) +} + +type resultSnapshot struct { + plan Plan + form Form + data resultData + output, search string + selected, tab int + last finishedMsg +} + +func (m *Model) saveList() { + m.source = &resultSnapshot{m.plan, m.form, m.data, m.output, m.resultSearch, m.resultSelected, m.resultTab, m.last} +} +func (m *Model) restoreList() { + if m.source == nil { + return + } + s := m.source + m.plan, m.form, m.data, m.output, m.resultSearch, m.resultSelected, m.resultTab, m.last = s.plan, s.form, s.data, s.output, s.search, s.selected, s.tab, s.last + m.screen = result + m.scroll = 0 + m.err = "" + m.buttonsFocused = false + m.buttonFocus = 0 + m.source = nil + m.progress = nil + m.cancelling = false + m.responding = false +} +func (m Model) resultListGeometry(height int) (int, int) { + start := 7 + if len(m.data.Metrics) > 0 { + start += 2 + } + return start, max(1, (height-start-2)/2) +} + +type browseCache struct { + data resultData + savedAt time.Time +} + +func chatCacheKey(plan Plan) [32]byte { return sha256.Sum256([]byte(strings.Join(plan.Args, "\x00"))) } +func (m *Model) saveChatCache() { + if m.chatCache == nil { + m.chatCache = map[[32]byte]browseCache{} + } + data := m.data + data.Items = slices.Clone(data.Items) + key := chatCacheKey(m.plan) + if _, exists := m.chatCache[key]; !exists && len(m.chatCache) >= 8 { + var oldest [32]byte + var savedAt time.Time + for candidate, entry := range m.chatCache { + if savedAt.IsZero() || entry.savedAt.Before(savedAt) { + oldest, savedAt = candidate, entry.savedAt + } + } + delete(m.chatCache, oldest) + } + m.chatCache[key] = browseCache{data, time.Now()} +} +func (m *Model) showChatCache() bool { + if strings.Join(m.plan.Path, " ") != "chat ls" { + return false + } + cached, ok := m.chatCache[chatCacheKey(m.plan)] + if !ok { + return false + } + m.data = cached.data + m.cachedAt = cached.savedAt + m.screen = result + m.loading = false + m.job = nil + m.taskCancel = nil + m.last = finishedMsg{} + m.resultSelected = 0 + m.resultTab = 0 + m.resultSearch = "" + m.scroll = 0 + m.stage = "" + m.progress = nil + m.err = "" + m.cancelling = false + m.responding = false + m.output = "Showing the last successful chat list from " + cached.savedAt.Format("15:04:05") + ". Choose Refresh to fetch current chats." + return true +} diff --git a/internal/tui/runner.go b/internal/tui/runner.go new file mode 100644 index 0000000..34c4e76 --- /dev/null +++ b/internal/tui/runner.go @@ -0,0 +1,248 @@ +package tui + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "github.com/mo1ein/TelegramArchive/internal/taskui" + "io" + "os" + "os/exec" + "runtime" + "slices" + "strings" + "sync" + "time" + + tea "charm.land/bubbletea/v2" +) + +type finishedMsg struct { + err error + elapsed time.Duration +} +type startedMsg struct{ job *job } +type pollMsg struct{} +type inputErrorMsg struct{ err error } + +// Workers isolate global CLI state while their entire lifecycle stays in the UI. +// No output is written to the user's terminal or persisted to an output log. +type job struct { + mu sync.Mutex + terminal *transcript + stdout bytes.Buffer + input io.WriteCloser + inputQ chan string + resize func(int, int) + cancel context.CancelFunc + doneC chan struct{} + done bool + err error + started, ended time.Time + structured, overflow bool + streamSeen bool + stage string + pending []byte + items []item + seen map[string]bool +} + +const captureLimit = 4 << 20 + +type jobWriter struct { + job *job + stdout bool +} + +func (w jobWriter) Write(p []byte) (int, error) { + j := w.job + j.mu.Lock() + defer j.mu.Unlock() + if !w.stdout || !j.structured { + j.terminal.write(p) + } + if w.stdout && j.structured { + remaining := captureLimit - j.stdout.Len() + j.stdout.Write(p[:min(len(p), remaining)]) + j.overflow = j.overflow || len(p) > remaining + j.consumeEvents(p) + } + return len(p), nil +} +func structuredArgs(plan Plan) ([]string, bool) { + args := slices.Clone(plan.Args) + switch strings.Join(plan.Path, " ") { + case "accounts", "cron list": + return append(args, "--json"), true + case "chat ls": + args = slices.DeleteFunc(args, func(s string) bool { return strings.HasPrefix(s, "--output=") }) + return append(args, "--output=json", "--tui-stream"), true + case "stats": + return args, true + } + return args, false +} +func startJob(parent context.Context, child *exec.Cmd, structured bool, width, height int) (*job, error) { + if err := parent.Err(); err != nil { + return nil, err + } + ctx, cancel := context.WithCancel(parent) + j := &job{terminal: newTranscript(width, height), cancel: cancel, doneC: make(chan struct{}), started: time.Now(), structured: structured, inputQ: make(chan string, 128)} + if child.Env == nil { + child.Env = os.Environ() + } + child.Env = append(child.Env, "TA_TUI_CHILD=1", "NO_COLOR=1", "TERM=dumb") + child.WaitDelay = 2 * time.Second + var drain chan struct{} + if structured || runtime.GOOS == "windows" { + child.Stdout, child.Stderr = jobWriter{j, true}, jobWriter{j, false} + in, err := child.StdinPipe() + if err != nil { + cancel() + return nil, err + } + j.input = in + if err := child.Start(); err != nil { + in.Close() + cancel() + return nil, err + } + } else { + master, slave, err := openPTY(width, height) + if err != nil { + cancel() + return nil, fmt.Errorf("open embedded task terminal: %w", err) + } + child.Stdin, child.Stdout, child.Stderr = slave, slave, slave + configurePTY(child) + if err := child.Start(); err != nil { + master.Close() + slave.Close() + cancel() + return nil, err + } + slave.Close() + j.input = master + j.resize = func(w, h int) { _ = resizePTY(master, w, h) } + j.terminal.respond = func(value string) { + select { + case j.inputQ <- value: + default: + } + } + drain = make(chan struct{}) + go func() { _, _ = io.Copy(jobWriter{j, false}, master); close(drain) }() + } + go func() { + for { + select { + case value := <-j.inputQ: + if _, err := io.WriteString(j.input, value); err != nil { + return + } + case <-ctx.Done(): + return + case <-j.doneC: + return + } + } + }() + go func() { + select { + case <-ctx.Done(): + interruptJob(child) + timer := time.NewTimer(2 * time.Second) + defer timer.Stop() + select { + case <-timer.C: + killJob(child) + case <-j.doneC: + } + case <-j.doneC: + } + }() + go func() { + err := child.Wait() + if drain != nil { + select { + case <-drain: + case <-time.After(500 * time.Millisecond): + } + } + j.input.Close() + if drain != nil { + <-drain + } + j.mu.Lock() + j.err = err + j.done = true + j.ended = time.Now() + j.mu.Unlock() + close(j.doneC) + cancel() + }() + return j, nil +} +func RunCommand(ctx context.Context, plan Plan) tea.Cmd { + return func() tea.Msg { + exe, err := os.Executable() + if err != nil { + return finishedMsg{err: err} + } + args, structured := structuredArgs(plan) + j, err := startJob(ctx, exec.Command(exe, args...), structured, max(20, plan.width), max(5, plan.height)) + if err != nil { + return finishedMsg{err: err} + } + return startedMsg{j} + } +} +func poll() tea.Cmd { + return tea.Tick(100*time.Millisecond, func(time.Time) tea.Msg { return pollMsg{} }) +} + +// NDJSON chat pages are published immediately, before the worker exits. Other +// structured commands keep their ordinary JSON output and final decoding. +func (j *job) consumeEvents(p []byte) { + if len(j.pending)+len(p) > 1<<20 { + j.pending = nil + j.overflow = true + return + } + j.pending = append(j.pending, p...) + for { + end := bytes.IndexByte(j.pending, '\n') + if end < 0 { + return + } + line := j.pending[:end] + var event taskui.ChatEvent + if json.Unmarshal(line, &event) == nil && event.Kind == "chat-page" { + j.streamSeen = true + j.stage = safeText(event.Stage) + j.terminal.write([]byte(j.stage + "\n")) + if len(event.Items) > 0 && !j.overflow { + rows, err := decodeResults([]string{"chat", "ls"}, event.Items) + if err != nil { + j.stage = "A chat page could not be decoded." + } else { + if j.seen == nil { + j.seen = map[string]bool{} + } + for _, row := range rows.Items { + key := row.Subtitle + if !j.seen[key] { + j.items = append(j.items, row) + j.seen[key] = true + } + } + } + } + } else { + j.terminal.write(line) + j.terminal.write([]byte{'\n'}) + } + j.pending = j.pending[end+1:] + } +} diff --git a/internal/tui/task_test.go b/internal/tui/task_test.go new file mode 100644 index 0000000..fb4b443 --- /dev/null +++ b/internal/tui/task_test.go @@ -0,0 +1,359 @@ +package tui + +import ( + "bytes" + "context" + "fmt" + "os" + "os/exec" + "runtime" + "strings" + "testing" + "time" + + tea "charm.land/bubbletea/v2" + "github.com/AlecAivazis/survey/v2" + "github.com/charmbracelet/x/ansi" + "github.com/mo1ein/TelegramArchive/internal/taskui" + "github.com/spf13/cobra" +) + +func TestTranscriptHandlesStreamingPromptsAndDropsExternalControls(t *testing.T) { + tr := newTranscript(80, 24) + input := "Old line\r\x1b[2KNew line\nآرشیو 📁\x1b]52;c;secret-clipboard\a\x1b]8;;https://invalid.test\a" + for _, b := range []byte(input) { + tr.write([]byte{b}) + } + got := tr.text() + if !strings.Contains(got, "New line\nآرشیو 📁") || strings.Contains(got, "secret-clipboard") || strings.Contains(got, "Old") || strings.Contains(got, "invalid.test") || strings.ContainsRune(got, '\x1b') { + t.Fatalf("unsafe or damaged transcript: %q", got) + } + response := "" + tr.respond = func(s string) { response = s } + tr.write([]byte("\x1b[6n")) + if !strings.HasSuffix(response, "R") { + t.Fatal("cursor query unanswered") + } + var frame bytes.Buffer + taskui.WriteProgress(&frame, []string{"file.bin", "[###...] 50%", "ETA 1s"}) + tr.write(frame.Bytes()) + if len(tr.progress) != 3 || tr.progress[0] != "file.bin" { + t.Fatalf("progress not decoded: %q", tr.progress) + } + if strings.Contains(tr.text(), "ta-progress") { + t.Fatal("internal progress frame leaked into activity") + } + tr.write([]byte(strings.Repeat("bounded line\n", 3000))) + if len(tr.lines) > 2000 { + t.Fatal("unbounded transcript") + } +} + +func TestStructuredResultsKeepIDsAndOfferNativeActions(t *testing.T) { + data, err := decodeResults([]string{"chat", "ls"}, []byte(`[{"id":9007199254740993,"type":"channel","visible_name":"Book Club","topics":[{"id":3,"title":"News"}]}]`)) + if err != nil || len(data.Items) != 1 || data.Items[0].ID != "9007199254740993" { + t.Fatalf("id changed: %+v %v", data, err) + } + root, action := fixture() + m := New(Catalog(root), nil, "work", context.Background()) + m.data = data + m.screen = result + m.output = "saved activity" + m.resultSearch = "Book" + m.plan = Plan{Title: "Chats", Path: []string{"chat", "ls"}} + m.activate("archive") + if m.screen != configure || m.form.field("chat").Value != "9007199254740993" || m.form.field("ns").Value != "work" { + t.Fatal("chat not passed to archive form") + } + if cmd := m.activate("list"); cmd != nil || m.screen != result || m.output != "saved activity" || m.resultSearch != "Book" { + t.Fatal("back to list lost state") + } + m.data, _ = decodeResults([]string{"accounts"}, []byte(`[{"namespace":"other","status":"ready","id":42,"username":"synthetic"}]`)) + m.resultSearch = "" + m.activate("use") + m.open(action) + if m.globals["ns"] != "other" || m.form.field("ns").Value != "other" { + t.Fatal("selected account did not apply to next workflow") + } + m.screen = result + m.data.Items[0].Status = "busy" + m.globals["ns"] = "work" + m.activate("use") + if m.globals["ns"] != "work" || m.err == "" { + t.Fatal("busy account was activated") + } +} + +func TestResultSearchButtonsAndMouseReview(t *testing.T) { + root, action := fixture() + m := New(Catalog(root), nil, "default", context.Background()) + m.open(action) + m.activate("review") + if m.screen != review { + t.Fatal("review button did not build plan") + } + runs := 0 + m.run = func(context.Context, Plan) tea.Cmd { runs++; return func() tea.Msg { return finishedMsg{} } } + // Bottom action row: [ Edit ] [ Run ] [ Home ]. + next, command := m.Update(tea.MouseClickMsg{X: 14, Y: m.height - 5, Button: tea.MouseLeft}) + m = next.(Model) + if m.screen != running || command == nil || runs != 1 { + t.Fatal("mouse Run did not dispatch task") + } + m = update(m, command()) + if m.screen != result { + t.Fatal("completion left result view") + } + m.data = resultData{Kind: "chat ls", Items: []item{{ID: "1", Title: "Alpha"}, {ID: "2", Title: "Beta"}}} + m = update(m, key('/', "/")) + m = update(m, tea.PasteMsg{Content: "Beta"}) + m = update(m, key(tea.KeyEnter, "")) + if len(m.resultItems()) != 1 || m.resultItems()[0].ID != "2" { + t.Fatal("result search failed") + } + m = update(m, key(tea.KeyTab, "")) + if !m.buttonsFocused { + t.Fatal("buttons not keyboard accessible") + } +} + +func waitFor(t *testing.T, j *job, needle string) { + t.Helper() + deadline := time.Now().Add(8 * time.Second) + for time.Now().Before(deadline) { + j.mu.Lock() + text := j.terminal.text() + done := j.done + j.mu.Unlock() + if strings.Contains(text, needle) { + return + } + if done { + t.Fatalf("worker exited before %q: %s", needle, text) + } + time.Sleep(10 * time.Millisecond) + } + j.cancel() + t.Fatalf("worker never displayed %q", needle) +} +func TestEmbeddedPasswordPromptAndCancellation(t *testing.T) { + if runtime.GOOS != "darwin" && runtime.GOOS != "linux" { + t.Skip("PTY integration") + } + for _, mode := range []string{"password", "wait"} { + t.Run(mode, func(t *testing.T) { + child := exec.Command(os.Args[0], "-test.run=^TestEmbeddedHelper$") + child.Env = append(os.Environ(), "TA_EMBEDDED_TEST="+mode) + j, err := startJob(context.Background(), child, false, 80, 24) + if err != nil { + t.Fatal(err) + } + defer j.cancel() + if mode == "password" { + waitFor(t, j, "Synthetic passcode") + j.inputQ <- "synthetic-local-passcode\r" + } else { + waitFor(t, j, "waiting") + j.cancel() + } + select { + case <-j.doneC: + case <-time.After(8 * time.Second): + t.Fatal("task was not reaped") + } + j.mu.Lock() + defer j.mu.Unlock() + text := j.terminal.text() + if mode == "password" && (j.err != nil || !strings.Contains(text, "accepted") || strings.Contains(text, "synthetic-local-passcode")) { + t.Fatalf("password prompt failed or leaked: err=%v text=%q", j.err, text) + } + if mode == "wait" && j.err == nil { + t.Fatal("cancelled worker reported success") + } + }) + } +} +func TestEmbeddedHelper(t *testing.T) { + switch os.Getenv("TA_EMBEDDED_TEST") { + case "password": + var value string + if err := survey.AskOne(&survey.Password{Message: "Synthetic passcode:"}, &value); err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(2) + } + if value != "synthetic-local-passcode" { + os.Exit(3) + } + fmt.Println("accepted") + os.Exit(0) + case "wait": + fmt.Println("waiting") + time.Sleep(time.Minute) + os.Exit(0) + } +} +func TestRunningAndResultViewsFitWithButtons(t *testing.T) { + root, action := fixture() + for _, size := range [][2]int{{55, 20}, {80, 24}, {120, 36}} { + for _, state := range []screen{running, result} { + m := New(Catalog(root), nil, "default", context.Background()) + m.open(action) + m.screen = state + m.width, m.height = size[0], size[1] + m.started = time.Now() + m.plan.Title = "Synthetic backup" + m.output = "retained output\nsecond line" + m.progress = []string{"file.bin", "[##..] 50%", "ETA 1s"} + m.data = resultData{Kind: "chat ls", Items: []item{{ID: "42", Title: "Synthetic chat", Subtitle: "channel", Detail: "details"}}} + text := ansi.Strip(m.View().Content) + if len(strings.Split(text, "\n")) > size[1] { + t.Fatalf("view too tall at %v", size) + } + for _, line := range strings.Split(text, "\n") { + if ansi.StringWidth(line) > size[0] { + t.Fatalf("view too wide at %v: %s", size, line) + } + } + if state == running && !strings.Contains(text, "Cancel") { + t.Fatal("Cancel button hidden") + } + if state == result && !strings.Contains(text, "Archive") { + t.Fatal("Archive action hidden") + } + } + } +} +func TestJobOutputLimitAndMalformedResultFallback(t *testing.T) { + j := &job{terminal: newTranscript(80, 24), structured: true} + writer := jobWriter{j, true} + payload := bytes.Repeat([]byte("x"), captureLimit+100) + writer.Write(payload) + if j.stdout.Len() != captureLimit || !j.overflow { + t.Fatal("result capture not bounded") + } + if _, err := decodeResults([]string{"chat", "ls"}, []byte("not json")); err == nil { + t.Fatal("malformed results accepted") + } +} + +func TestChatBrowserShowsRowsWhileWorkerStillLoading(t *testing.T) { + child := exec.Command(os.Args[0], "-test.run=^TestStreamingChatHelper$") + child.Env = append(os.Environ(), "TA_CHAT_STREAM_TEST=1") + j, err := startJob(context.Background(), child, true, 80, 24) + if err != nil { + t.Fatal(err) + } + defer j.cancel() + waitFor(t, j, "Loading chats") + root, _ := fixture() + m := New(Catalog(root), nil, "default", context.Background()) + m.screen = running + m.job = j + m.plan = Plan{Title: "Browse your chats", Path: []string{"chat", "ls"}} + m = update(m, pollMsg{}) + if len(m.data.Items) != 1 { + t.Fatalf("browser hides rows until worker finishes: got %d", len(m.data.Items)) + } + if !strings.Contains(ansi.Strip(m.View().Content), "Synthetic channel") { + t.Fatal("received chat is not visible") + } + if !m.loading || m.screen != result { + t.Fatal("partial rows are not in the interactive list") + } + j.cancel() + select { + case <-j.doneC: + case <-time.After(5 * time.Second): + t.Fatal("stream did not stop") + } + m = update(m, pollMsg{}) + if m.loading || len(m.data.Items) != 1 || m.buttons()[0].ID != "archive" { + t.Fatal("stopping loading lost partial rows or actions") + } + if strings.Contains(m.output, "chat-page") { + t.Fatal("stream protocol leaked into activity") + } + +} +func TestStreamingChatHelper(t *testing.T) { + if os.Getenv("TA_CHAT_STREAM_TEST") != "1" { + return + } + fmt.Println(`{"kind":"chat-page","stage":"Loading chats","items":[{"id":42,"type":"channel","visible_name":"Synthetic channel"}]}`) + var response [1]byte + _, _ = os.Stdin.Read(response[:]) + os.Exit(0) +} + +func TestWorkerFailureDisplaysUnderlyingConnectionError(t *testing.T) { + child := exec.Command(os.Args[0], "-test.run=^TestConnectionFailureHelper$") + child.Env = append(os.Environ(), "TA_CONNECTION_FAILURE_TEST=1") + j, err := startJob(context.Background(), child, true, 80, 24) + if err != nil { + t.Fatal(err) + } + defer j.cancel() + select { + case <-j.doneC: + case <-time.After(5 * time.Second): + t.Fatal("worker did not exit") + } + root, _ := fixture() + m := New(Catalog(root), nil, "default", context.Background()) + m.screen = running + m.job = j + m.plan = Plan{Title: "Browse chats", Path: []string{"chat", "ls"}} + m = update(m, pollMsg{}) + if m.last.err == nil || !strings.Contains(m.last.err.Error(), "connection refused") { + t.Fatalf("real error hidden behind worker status: %v", m.last.err) + } +} +func TestConnectionFailureHelper(t *testing.T) { + if os.Getenv("TA_CONNECTION_FAILURE_TEST") != "1" { + return + } + fmt.Fprintln(os.Stderr, "Error: dial failed: connection refused") + os.Exit(1) +} + +func TestConnectionErrorRedactsProxyCredentials(t *testing.T) { + output := "Error: dial socks5://synthetic-user:synthetic-password@127.0.0.1:10808: connection refused" + visible := redactOutput(output) + err := taskFailure(fmt.Errorf("exit status 1"), visible) + if err == nil || !strings.Contains(err.Error(), "connection refused") || strings.Contains(visible, "synthetic-user") || strings.Contains(err.Error(), "synthetic-password") { + t.Fatal("failure leaked credentials or hid its cause") + } +} + +func TestChatBrowserReopensLastListWithoutNetwork(t *testing.T) { + root, _ := fixture() + group := &cobra.Command{Use: "chat"} + list := &cobra.Command{Use: "ls", Args: cobra.NoArgs, RunE: func(*cobra.Command, []string) error { return nil }} + list.Flags().String("filter", "true", "") + list.Flags().String("output", "table", "") + group.AddCommand(list) + root.AddCommand(group) + m := New(Catalog(root), nil, "default", context.Background()) + action := Action{Title: "Chats", Path: []string{"chat", "ls"}, Command: list} + runs := 0 + m.run = func(context.Context, Plan) tea.Cmd { runs++; return nil } + m.browse(action) + now := time.Now() + m.job = &job{terminal: newTranscript(80, 24), done: true, started: now, ended: now, streamSeen: true, items: []item{{ID: "42", Title: "Cached synthetic chat"}}} + m = update(m, pollMsg{}) + m.activate("home") + m.browse(action) + if runs != 1 || m.screen != result || len(m.resultItems()) != 1 { + t.Fatalf("reopening fetched chats again: runs=%d items=%d", runs, len(m.resultItems())) + } + m.activate("refresh") + if runs != 2 || m.screen != running { + t.Fatal("Refresh did not explicitly fetch current chats") + } + m.activate("home") + m.globals["ns"] = "different-account" + m.browse(action) + if runs != 3 || m.screen != running { + t.Fatal("cached chats leaked across namespaces") + } +} diff --git a/internal/tui/task_view.go b/internal/tui/task_view.go new file mode 100644 index 0000000..53099dc --- /dev/null +++ b/internal/tui/task_view.go @@ -0,0 +1,157 @@ +package tui + +import ( + "fmt" + "strings" + "time" + + "charm.land/lipgloss/v2" + "github.com/charmbracelet/x/ansi" +) + +func (m Model) taskView(width, height int) string { + if m.screen == running { + spinner := []string{"◐", "◓", "◑", "◒"}[int(time.Since(m.started).Milliseconds()/150)%4] + heading := spinner + " Working" + if m.stage != "" { + heading = spinner + " " + m.stage + } + if m.cancelling { + heading = "◐ Cancelling…" + } + lines := []string{accent.Render(heading) + dim.Render(" "+time.Since(m.started).Round(time.Second).String()), "", titleStyle.Render(m.plan.Title), dim.Render("Task stays here · Ctrl+C cancels without closing the workspace"), ""} + if m.responding { + lines = append(lines, accent.Render("INPUT ACTIVE · Type your response; Enter submits · Esc returns to controls")) + } else { + lines = append(lines, dim.Render("Choose Respond (i) if the task asks for input. Passwords stay masked by the prompt.")) + } + lines = append(lines, "") + if len(m.progress) == 3 { + lines = append(lines, selectedStyle.Width(width).Render(m.progress[0]), accent.Render(m.progress[1]), dim.Render(m.progress[2]), "") + } + output := m.output + if output == "" { + if len(m.progress) > 0 { + output = "Activity will appear here as files finish." + } else { + output = "Preparing the task…" + if len(m.plan.Path) > 0 && m.plan.Path[0] == "chat" { + output = "Connecting to Telegram · the browser will show each page as it arrives." + } + } + } + available := max(1, height-len(lines)-2) + offset := m.scroll + if m.follow { + offset = max(0, len(strings.Split(output, "\n"))-available) + } + lines = append(lines, scrolled(output, width, available, offset)) + if m.err != "" { + lines = append(lines, warning.Render(clip(m.err, width))) + } + return strings.Join(lines, "\n") + } + status := "✓ Completed" + if !m.cachedAt.IsZero() { + status = "✓ Chat list · saved " + m.cachedAt.Format("15:04:05") + } + if m.loading { + status = fmt.Sprintf("◐ Loading · %d chats available", len(m.data.Items)) + } + style := accent + if m.last.err != nil { + status = "! Task stopped" + style = warning + } + if m.cancelling { + status = "■ Cancelled" + } + elapsed := m.last.elapsed + if m.loading { + elapsed = time.Since(m.started) + } + elapsedLabel := " " + elapsed.Round(time.Second).String() + if !m.cachedAt.IsZero() { + elapsedLabel = "" + } + lines := []string{style.Render(status) + dim.Render(elapsedLabel), "", titleStyle.Render(m.plan.Title), ""} + if m.loading { + lines[3] = dim.Render(clip(m.stage+" · Stop loading to use a selected chat", width)) + } + tabs := []string{"Results", "Activity", "Details"} + parts := []string{} + for i, label := range tabs { + if i == m.resultTab { + parts = append(parts, accent.Render(label)) + } else { + parts = append(parts, dim.Render(label)) + } + } + lines = append(lines, strings.Join(parts, " ")+dim.Render(" t / l / d"), "") + if m.last.err != nil && !m.cancelling { + lines[3] = warning.Render(clip(m.last.err.Error(), width)) + } + switch m.resultTab { + case 1: + content := m.output + if content == "" { + content = "The task produced no output." + } + lines = append(lines, scrolled(content, width, max(1, height-len(lines)-1), m.scroll)) + case 2: + rows := m.resultItems() + content := "No item selected." + if m.last.err != nil { + content = m.last.err.Error() + } + if len(rows) > 0 && m.resultSelected < len(rows) { + content = rows[m.resultSelected].Detail + } + lines = append(lines, scrolled(ansi.Hardwrap(content, width, false), width, max(1, height-len(lines)-1), m.scroll)) + default: + if len(m.data.Metrics) > 0 { + cards := []string{} + cellWidth := max(12, width/3-1) + for _, v := range m.data.Metrics[:min(3, len(m.data.Metrics))] { + cards = append(cards, selectedStyle.Width(cellWidth).Render(clip(" "+v.Value+" "+v.Label, cellWidth))) + } + lines = append(lines, strings.Join(cards, " "), "") + } + rows := m.resultItems() + search := dim.Render(fmt.Sprintf("%d items · / search · ↑↓ select · Enter details", len(rows))) + if m.searching { + search = accent.Render("/ ") + m.inputView(width-3, false) + } else if m.resultSearch != "" { + search = accent.Render("/ "+m.resultSearch) + dim.Render(fmt.Sprintf(" · %d matches", len(rows))) + } + lines = append(lines, clip(search, width)) + page := max(1, (height-len(lines)-2)/2) + start := max(0, m.resultSelected-page+1) + for i := start; i < min(len(rows), start+page); i++ { + row := rows[i] + marker := " " + style := textStyle + if i == m.resultSelected { + marker = "▸ " + style = selectedStyle.Bold(true).Width(width) + } + lines = append(lines, style.Render(clip(marker+row.Title, width)), dim.Render(clip(" "+row.Subtitle, width))) + } + if len(rows) == 0 && len(m.data.Metrics) == 0 { + message := "No results. Try changing the filters or refreshing." + switch m.data.Kind { + case "accounts": + message = "No saved accounts. Connect an account from the Accounts section." + case "cron list": + message = "No scheduled backups. Choose Schedule a backup from Quick start." + } + lines = append(lines, "", dim.Render(ansi.Hardwrap(message, width, false))) + } + } + if m.err != "" { + lines = append(lines, warning.Render(clip(m.err, width))) + } + return fit(strings.Join(lines, "\n"), width, height) +} + +var warning = lipgloss.NewStyle().Foreground(lipgloss.Color("#FFAFB8")) diff --git a/internal/tui/transcript.go b/internal/tui/transcript.go new file mode 100644 index 0000000..a10201d --- /dev/null +++ b/internal/tui/transcript.go @@ -0,0 +1,185 @@ +package tui + +import ( + "encoding/json" + "fmt" + "strings" + "unicode" + + "github.com/charmbracelet/x/ansi" + "github.com/mattn/go-runewidth" + "github.com/mo1ein/TelegramArchive/internal/taskui" +) + +// A bounded plain-text task surface. Child cursor/erase sequences update this +// surface, never the real terminal. OSC, clipboard and hyperlink escapes drop. +type transcript struct { + parser *ansi.Parser + lines [][]string + x, y, savedX, savedY int + width, height int + progress []string + respond func(string) +} + +func newTranscript(width, height int) *transcript { + t := &transcript{lines: [][]string{{}}, width: max(20, min(width, 500)), height: max(5, min(height, 200))} + t.parser = ansi.NewParser() + t.parser.SetDataSize(8192) + t.parser.SetHandler(ansi.Handler{HandleOsc: func(cmd int, data []byte) { + payload := strings.TrimPrefix(string(data), "777;") + if cmd == 777 && strings.HasPrefix(payload, taskui.ProgressPrefix) { + var lines []string + if json.Unmarshal([]byte(payload[len(taskui.ProgressPrefix):]), &lines) == nil && len(lines) == 3 { + for i := range lines { + lines[i] = safeText(lines[i]) + } + t.progress = lines + } + } + }, Print: t.print, Execute: t.control, HandleCsi: t.csi, HandleEsc: func(cmd ansi.Cmd) { + switch byte(cmd) { + case '7': + t.savedX, t.savedY = t.x, t.y + case '8': + t.x, t.y = t.savedX, t.savedY + t.ensure() + } + }}) + return t +} +func (t *transcript) write(p []byte) { t.parser.Parse(p) } +func (t *transcript) ensure() { + t.y = max(0, min(t.y, len(t.lines)+t.height)) + for len(t.lines) <= t.y { + t.lines = append(t.lines, []string{}) + } + if len(t.lines) > 2000 { + drop := len(t.lines) - 2000 + t.lines = t.lines[drop:] + t.y -= drop + t.savedY = max(0, t.savedY-drop) + } +} +func (t *transcript) print(r rune) { + w := runewidth.RuneWidth(r) + if w == 0 { + if t.x > 0 && t.x <= len(t.lines[t.y]) && len(t.lines[t.y][t.x-1]) < 64 { + t.lines[t.y][t.x-1] += string(r) + } + return + } + if t.x+w > t.width { + t.y++ + t.x = 0 + t.ensure() + } + t.ensure() + line := t.lines[t.y] + for len(line) < t.x+w { + line = append(line, " ") + } + line[t.x] = string(r) + for i := 1; i < w; i++ { + line[t.x+i] = "" + } + t.lines[t.y] = line + t.x += w +} +func (t *transcript) control(b byte) { + switch b { + case '\n': + t.y++ + t.x = 0 + t.ensure() + case '\r': + t.x = 0 + case '\b': + t.x = max(0, t.x-1) + case '\t': + for n := 8 - t.x%8; n > 0; n-- { + t.print(' ') + } + } +} +func (t *transcript) csi(cmd ansi.Cmd, params ansi.Params) { + param := func(i, d int) int { n, _, _ := params.Param(i, d); return n } + n := max(1, param(0, 1)) + top := max(0, len(t.lines)-t.height) + switch byte(cmd) { + case 'A': + t.y = max(top, t.y-n) + case 'B': + t.y = min(top+t.height-1, t.y+n) + t.ensure() + case 'C': + t.x = min(t.width-1, t.x+n) + case 'D': + t.x = max(0, t.x-n) + case 'E': + t.y = min(top+t.height-1, t.y+n) + t.x = 0 + t.ensure() + case 'F': + t.y = max(top, t.y-n) + t.x = 0 + case 'G': + t.x = min(t.width-1, n-1) + case 'H', 'f': + t.y = top + min(t.height-1, n-1) + t.x = max(0, min(t.width-1, max(1, param(1, 1))-1)) + t.ensure() + case 'K': + t.ensure() + line := t.lines[t.y] + switch param(0, 0) { + case 0: + if t.x < len(line) { + line = line[:t.x] + } + case 1: + for i := 0; i < min(t.x+1, len(line)); i++ { + line[i] = " " + } + case 2: + line = nil + } + t.lines[t.y] = line + case 'J': + switch param(0, 0) { + case 0: + if t.x < len(t.lines[t.y]) { + t.lines[t.y] = t.lines[t.y][:t.x] + } + t.lines = t.lines[:t.y+1] + case 2: + for i := top; i < len(t.lines); i++ { + t.lines[i] = nil + } + } + case 's': + t.savedX, t.savedY = t.x, t.y + case 'u': + t.x, t.y = t.savedX, t.savedY + t.ensure() + case 'n': + if param(0, 0) == 6 && t.respond != nil { + t.respond(fmt.Sprintf("\x1b[%d;%dR", t.y-top+1, t.x+1)) + } + } +} +func (t *transcript) text() string { + lines := make([]string, len(t.lines)) + for i, line := range t.lines { + lines[i] = strings.TrimRight(strings.Join(line, ""), " ") + } + return strings.TrimRight(strings.Join(lines, "\n"), "\n") +} +func safeText(s string) string { + return strings.Map(func(r rune) rune { + if unicode.IsControl(r) { + return ' ' + } + return r + }, ansi.Strip(s)) +} diff --git a/internal/tui/tui_test.go b/internal/tui/tui_test.go new file mode 100644 index 0000000..fcebb2a --- /dev/null +++ b/internal/tui/tui_test.go @@ -0,0 +1,387 @@ +package tui + +import ( + "context" + "errors" + "os" + "os/exec" + "path/filepath" + "reflect" + "slices" + "strings" + "testing" + "time" + + tea "charm.land/bubbletea/v2" + "github.com/charmbracelet/x/ansi" + "github.com/spf13/cobra" +) + +func fixture() (*cobra.Command, Action) { + root := &cobra.Command{Use: "ta"} + root.PersistentFlags().String("ns", "default", "saved account") + root.PersistentFlags().String("proxy", "", "proxy address") + root.PersistentFlags().StringToString("storage", map[string]string{"type": "bolt", "path": "data"}, "storage options [legacy,bolt]") + command := &cobra.Command{Use: "archive", Short: "Back up chats", Args: cobra.NoArgs, RunE: func(*cobra.Command, []string) error { panic("must never execute") }} + command.Flags().StringSlice("chat", nil, "chats") + command.Flags().Bool("all", false, "all chats") + command.Flags().Bool("resume", true, "resume") + command.Flags().String("format", "json", "format") + command.Flags().String("output", "data", "destination") + command.Flags().Duration("every", 0, "interval") + command.Flags().Int("limit", 2, "concurrency") + command.Flags().String("since", "", "date") + command.Flags().StringArray("from", nil, "sources") + command.Flags().String("private", "", "internal") + _ = command.Flags().MarkHidden("private") + root.AddCommand(command) + return root, Action{Title: "archive", Description: command.Short, Path: []string{"archive"}, Group: "Backups", Command: command} +} + +func set(form *Form, name, value string) { + f := form.field(name) + if f == nil { + panic(name) + } + f.Value, f.Dirty = value, true +} + +func key(code rune, text string, mods ...tea.KeyMod) tea.KeyPressMsg { + msg := tea.KeyPressMsg{Code: code, Text: text} + if len(mods) > 0 { + msg.Mod = mods[0] + } + return msg +} + +func update(m Model, msg tea.Msg) Model { + next, _ := m.Update(msg) + return next.(Model) +} + +func TestPlanPreservesArgumentsWithoutMutatingCobra(t *testing.T) { + root, action := fixture() + form := NewForm(action, map[string]string{"ns": "work"}) + set(&form, "chat", `"Book Club, Friends",telegram`) + set(&form, "output", `exports/hello world/$(touch nope);literal`) + set(&form, "resume", "false") + set(&form, "from", `"/path/with,a comma.json",second.json`) + set(&form, "storage", "type=bolt,path=/tmp/sessions") + plan, err := form.Plan([]string{"--proxy=socks5://user:password@example.invalid:1080", "--ns=old"}) + if err != nil { + t.Fatal(err) + } + if !slices.Contains(plan.Args, "--output=exports/hello world/$(touch nope);literal") || !slices.Contains(plan.Args, "--resume=false") { + t.Fatal(plan.Args) + } + if !slices.Contains(plan.Args, "--from=/path/with,a comma.json") || !slices.Contains(plan.Args, "--from=second.json") { + t.Fatal(plan.Args) + } + if strings.Contains(plan.Preview(), "password") || strings.Contains(plan.Preview(), "user:") { + t.Fatal("credentials in preview:", plan.Preview()) + } + if slices.Contains(plan.Args, "--ns=old") || strings.Count(plan.Preview(), "--ns=") != 1 { + t.Fatal("global overrides should replace startup arguments", plan.Args) + } + if got, _ := action.Command.Flags().GetStringSlice("chat"); len(got) != 0 { + t.Fatal("form changed actual flags", got) + } + if root.PersistentFlags().Lookup("ns").Changed { + t.Fatal("form changed the running namespace") + } + if form.field("private") != nil { + t.Fatal("hidden flag exposed") + } + + // Parse the generated arguments through the same Cobra command definitions. + clone, _ := fixture() + leaf, args, err := clone.Find(plan.Args) + if err != nil { + t.Fatal(err) + } + if err := leaf.ParseFlags(args); err != nil { + t.Fatal(err) + } + chats, _ := leaf.Flags().GetStringSlice("chat") + if !reflect.DeepEqual(chats, []string{"Book Club, Friends", "telegram"}) { + t.Fatal(chats) + } + sources, _ := leaf.Flags().GetStringArray("from") + if !reflect.DeepEqual(sources, []string{"/path/with,a comma.json", "second.json"}) { + t.Fatal(sources) + } +} + +func TestPlanValidatesBeforeExecution(t *testing.T) { + for _, tc := range []struct{ name, value, want string }{ + {"every", "tomorrow", "every"}, + {"limit", "many", "limit"}, + {"format", "pdf", "choose"}, + {"since", "yesterday", "YYYY-MM-DD"}, + {"chat", `"unfinished`, "chat"}, + {"arguments", `"unfinished`, "arguments"}, + } { + t.Run(tc.name, func(t *testing.T) { + _, action := fixture() + form := NewForm(action, nil) + set(&form, tc.name, tc.value) + if _, err := form.Plan(nil); err == nil || !strings.Contains(err.Error(), tc.want) { + t.Fatalf("got %v", err) + } + }) + } + _, action := fixture() + form := NewForm(action, nil) + set(&form, "all", "true") + set(&form, "chat", "me") + if _, err := form.Plan(nil); err == nil { + t.Fatal("accepted conflicting chat selection") + } + set(&form, "chat", "") + if _, err := form.Plan(nil); err != nil { + t.Fatal(err) + } +} + +func TestRequiredArgumentsAndPassthrough(t *testing.T) { + for _, tc := range []struct { + path, use, arguments string + raw bool + want []string + }{ + {"stats", "stats FILE...", `'a file.json' --leading-dash.json`, false, []string{"stats", "--", "a file.json", "--leading-dash.json"}}, + {"schedule", "schedule", `--all --format both`, false, []string{"schedule", "--", "--all", "--format", "both"}}, + {"my-extension", "my-extension", `--custom 'hello world'`, true, []string{"my-extension", "--custom", "hello world"}}, + } { + t.Run(tc.path, func(t *testing.T) { + command := &cobra.Command{Use: tc.use, Args: cobra.MinimumNArgs(1), DisableFlagParsing: tc.raw} + form := NewForm(Action{Path: []string{tc.path}, Command: command}, nil) + if _, err := form.Plan(nil); err == nil { + t.Fatal("missing arguments accepted") + } + set(&form, "arguments", tc.arguments) + plan, err := form.Plan(nil) + if err != nil { + t.Fatal(err) + } + if !reflect.DeepEqual(plan.Args, tc.want) { + t.Fatalf("%v != %v", plan.Args, tc.want) + } + }) + } + _, action := fixture() + action.Command.MarkFlagRequired("output") + form := NewForm(action, nil) + if _, err := form.Plan(nil); err == nil { + t.Fatal("required flag must be explicitly supplied") + } +} + +func TestModelSearchEditReviewAndReturn(t *testing.T) { + root, _ := fixture() + m := New(Catalog(root), nil, "work", context.Background()) + runs := 0 + m.run = func(_ context.Context, plan Plan) tea.Cmd { + runs++ + if !slices.Contains(plan.Args, "--ns=work") { + t.Error(plan.Args) + } + return func() tea.Msg { return finishedMsg{elapsed: time.Second} } + } + m = update(m, key('/', "/")) + m = update(m, tea.PasteMsg{Content: "BACK UP"}) + if len(m.filteredActions()) != 1 { + t.Fatal(m.filteredActions()) + } + m = update(m, key(tea.KeyEnter, "")) // Finish search. + m = update(m, key(tea.KeyEnter, "")) // Open command. + if m.screen != configure || runs != 0 { + t.Fatal("opened command ran unexpectedly") + } + m.focus = slices.Index(m.visibleFields(), slices.IndexFunc(m.form.Fields, func(f Field) bool { return f.Name == "output" })) + m = update(m, key(tea.KeyEnter, "")) + m = update(m, key('u', "", tea.ModCtrl)) + m = update(m, tea.PasteMsg{Content: "آرشیو/Book Club"}) + m = update(m, key(tea.KeyEnter, "")) + if m.form.field("output").Value != "آرشیو/Book Club" { + t.Fatal(m.form.field("output")) + } + m = update(m, key('r', "", tea.ModCtrl)) + if m.screen != review || runs != 0 { + t.Fatal("review must not execute the command") + } + m = update(m, key(tea.KeyEscape, "")) + if m.form.field("output").Value != "آرشیو/Book Club" { + t.Fatal("editing lost values") + } + m = update(m, key('r', "", tea.ModCtrl)) + next, command := m.Update(key(tea.KeyEnter, "")) + m = next.(Model) + if runs != 1 || command == nil { + t.Fatal("review did not dispatch") + } + m = update(m, command()) + if m.screen != result { + t.Fatal(m.screen) + } + m = update(m, key('e', "e")) + if m.screen != configure { + t.Fatal(m.screen) + } +} + +func TestSearchNoMatchesAndAdvancedOptions(t *testing.T) { + root, action := fixture() + m := New(Catalog(root), nil, "default", context.Background()) + m = update(m, key('/', "/")) + m = update(m, tea.PasteMsg{Content: "no such command"}) + m = update(m, key(tea.KeyEnter, "")) + m = update(m, key(tea.KeyEnter, "")) + if m.screen != dashboard { + t.Fatal(m.screen) + } + m.open(action) + m = update(m, key('/', "/")) + m = update(m, tea.PasteMsg{Content: "proxy"}) + if fields := m.visibleFields(); len(fields) != 1 || m.form.Fields[fields[0]].Name != "proxy" { + t.Fatal(fields) + } + m = update(m, key(tea.KeyEscape, "")) + if m.fieldSearch != "" { + t.Fatal("escape must clear search") + } + m = update(m, key('a', "", tea.ModCtrl)) + if !m.advanced { + t.Fatal("advanced options not enabled") + } +} + +func TestSpaceTogglesSwitchesAndCyclesChoices(t *testing.T) { + root, action := fixture() + m := New(Catalog(root), nil, "default", context.Background()) + m.open(action) + focus := func(name string) { + m.focus = slices.Index(m.visibleFields(), slices.IndexFunc(m.form.Fields, func(f Field) bool { return f.Name == name })) + } + focus("resume") + m = update(m, key(' ', " ")) + if m.form.field("resume").Value != "false" { + t.Fatal("space did not toggle the switch") + } + focus("format") + m = update(m, key(' ', " ")) + if m.form.field("format").Value != "html" { + t.Fatal("space did not cycle choices") + } + m = update(m, key('d', "", tea.ModCtrl)) + if m.form.field("format").Value != "json" || m.form.field("format").Dirty { + t.Fatal("field did not reset") + } + focus("output") + m = update(m, key(tea.KeyEnter, "")) + m = update(m, key(' ', " ")) + if string(m.input) != "data " { + t.Fatal("space should type normally in an editor") + } +} + +func TestViewsFitTerminalAndKeepValidationVisible(t *testing.T) { + root, action := fixture() + for _, size := range [][2]int{{55, 20}, {80, 24}, {100, 32}, {160, 48}} { + for _, state := range []screen{dashboard, configure, review, result} { + m := New(Catalog(root), nil, "work", context.Background()) + m.open(action) + m.width, m.height, m.screen = size[0], size[1], state + m.err = "Validation needs attention" + m.plan = Plan{Title: "archive", Args: []string{"archive", "--output=" + strings.Repeat("long/path/", 40)}} + value := ansi.Strip(m.View().Content) + lines := strings.Split(value, "\n") + if len(lines) > size[1] { + t.Fatalf("%v state %d: too many lines: %d", size, state, len(lines)) + } + for _, line := range lines { + if ansi.StringWidth(line) > size[0] { + t.Fatalf("%v state %d: too wide: %q", size, state, line) + } + } + if state == configure && !strings.Contains(value, "Validation needs attention") { + t.Fatalf("error clipped at %v:\n%s", size, value) + } + } + } +} + +func TestUniquePathCompletion(t *testing.T) { + dir := t.TempDir() + if err := os.Mkdir(filepath.Join(dir, "archive folder"), 0700); err != nil { + t.Fatal(err) + } + m := Model{input: []rune(filepath.Join(dir, "arch"))} + m.completePath() + if string(m.input) != filepath.Join(dir, "archive folder")+string(filepath.Separator) { + t.Fatal(string(m.input)) + } +} + +func TestLoginPasscodeIsHiddenInFormAndPreview(t *testing.T) { + command := &cobra.Command{Use: "login", Args: cobra.NoArgs} + command.Flags().String("passcode", "", "") + form := NewForm(Action{Path: []string{"login"}, Command: command}, nil) + set(&form, "passcode", "synthetic private passcode") + if !form.field("passcode").Secret || strings.Contains(form.field("passcode").Display(), "private") { + t.Fatal("passcode was displayed") + } + plan, err := form.Plan(nil) + if err != nil { + t.Fatal(err) + } + if strings.Contains(plan.Preview(), "synthetic private") { + t.Fatal("passcode leaked in preview") + } + if !slices.Contains(plan.Args, "--passcode=synthetic private passcode") { + t.Fatal("masking changed execution arguments") + } +} + +func TestJobKeepsOutputAndReturnsStatus(t *testing.T) { + for _, failed := range []bool{false, true} { + child := exec.Command(os.Args[0], "-test.run=^TestTerminalHelper$") + child.Env = append(os.Environ(), "TA_TUI_HELPER=1") + if failed { + child.Env = append(child.Env, "TA_TUI_FAIL=1") + } + j, err := startJob(context.Background(), child, true, 80, 24) + if err != nil { + t.Fatal(err) + } + select { + case <-j.doneC: + case <-time.After(10 * time.Second): + j.cancel() + t.Fatal("worker did not finish") + } + j.mu.Lock() + text := j.terminal.text() + gotErr := j.err + j.mu.Unlock() + if (gotErr != nil) != failed || !strings.Contains(text, "synthetic command output") { + t.Fatalf("err=%v output=%s", gotErr, text) + } + } + canceled, cancel := context.WithCancel(context.Background()) + cancel() + if _, err := startJob(canceled, exec.Command(os.Args[0]), true, 80, 24); !errors.Is(err, context.Canceled) { + t.Fatal(err) + } +} + +func TestTerminalHelper(t *testing.T) { + if os.Getenv("TA_TUI_HELPER") != "1" { + return + } + _, _ = os.Stdout.WriteString("synthetic command output\n") + if os.Getenv("TA_TUI_FAIL") == "1" { + os.Exit(2) + } + os.Exit(0) +} diff --git a/internal/tui/view.go b/internal/tui/view.go new file mode 100644 index 0000000..d1d4a81 --- /dev/null +++ b/internal/tui/view.go @@ -0,0 +1,316 @@ +package tui + +import ( + "fmt" + "os" + "strings" + + tea "charm.land/bubbletea/v2" + "charm.land/lipgloss/v2" + "github.com/charmbracelet/x/ansi" +) + +var ( + ink = lipgloss.Color("#E3E9F3") + muted = lipgloss.Color("#8995AD") + mint = lipgloss.Color("#8BE5CD") + violet = lipgloss.Color("#B9AAFF") + line = lipgloss.Color("#343E55") + panel = lipgloss.Color("#191F30") + textStyle = lipgloss.NewStyle().Foreground(ink) + dim = lipgloss.NewStyle().Foreground(muted) + accent = lipgloss.NewStyle().Foreground(mint).Bold(true) + titleStyle = lipgloss.NewStyle().Foreground(ink).Bold(true) + selectedStyle = lipgloss.NewStyle().Background(panel).Foreground(mint) + badge = lipgloss.NewStyle().Background(mint).Foreground(lipgloss.Color("#102C2C")).Bold(true).Padding(0, 1) +) + +func (m Model) View() tea.View { + w, h := m.width, m.height + var content string + if w < 55 || h < 20 { + content = "ta · Telegram Archive\n\nResize to at least 55 × 20.\nCtrl+C to exit." + } else { + width, height := w-4, h-9 + header := badge.Render("ta") + " " + titleStyle.Render("TELEGRAM ARCHIVE") + dim.Render(" / your workspace") + if w >= 85 { + namespace := m.globals["ns"] + if namespace == "" { + namespace = "inherited" + } + right := dim.Render("namespace ") + accent.Render(clip(namespace, 18)) + header += strings.Repeat(" ", max(1, width-lipgloss.Width(header)-lipgloss.Width(right))) + right + } + var body string + if m.help { + body = m.helpView(width, height) + } else { + switch m.screen { + case dashboard: + body = m.dashboardView(width, height) + case configure: + body = m.formView(width, height) + case review: + body = m.reviewView(width, height) + case result, running: + body = m.taskView(width, height) + } + } + body = fit(body, width, height) + "\n\n" + m.buttonBar(width) + footer := m.footer() + content = "\n " + header + "\n " + dim.Render(strings.Repeat("─", width)) + "\n" + indent(body, " ") + "\n " + dim.Render(strings.Repeat("─", width)) + "\n " + clip(footer, width) + } + view := tea.NewView(content) + view.AltScreen = true + view.MouseMode = tea.MouseModeCellMotion + if os.Getenv("NO_COLOR") == "" { + view.BackgroundColor = lipgloss.Color("#101522") + view.ForegroundColor = ink + } + view.WindowTitle = "ta · Telegram Archive" + return view +} + +func (m Model) dashboardView(width, height int) string { + if width < 86 { + return dim.Render("‹ ") + accent.Render(Groups[m.group]) + dim.Render(" › Tab to change section") + "\n\n" + m.actionList(width, height-2) + } + sideWidth := 20 + var nav strings.Builder + nav.WriteString(dim.Render("WORKSPACE") + "\n\n") + for i, name := range Groups { + label := " " + name + if i == m.group { + label = "▸ " + name + nav.WriteString(selectedStyle.Width(sideWidth).Render(label)) + } else { + nav.WriteString(dim.Render(label)) + } + nav.WriteString("\n\n") + } + if height >= 23 { + nav.WriteString("\n" + dim.Render("YOUR NEXT BACKUP,\nA FEW KEYS AWAY.\n\n/ Search everything\n? Keyboard guide")) + } + mainWidth := width - sideWidth - 3 + body := m.actionList(mainWidth, height) + return lipgloss.JoinHorizontal(lipgloss.Top, fit(nav.String(), sideWidth, height), " ", body) +} + +func (m Model) actionList(width, height int) string { + actions := m.filteredActions() + heading := "Choose a workflow" + if m.search != "" { + heading = "Search results" + } else if Groups[m.group] != "Quick start" { + heading = Groups[m.group] + } + count := dim.Render(fmt.Sprintf("%d available", len(actions))) + header := titleStyle.Render(heading) + header += strings.Repeat(" ", max(1, width-lipgloss.Width(header)-lipgloss.Width(count))) + count + search := dim.Render("/ Search commands, features and descriptions…") + if m.search != "" { + search = accent.Render("/ ") + textStyle.Render(m.search) + } + if m.searching { + search = accent.Render("/ ") + m.inputView(width-4, false) + } + lines := []string{header, "", clip(search, width), ""} + if len(actions) == 0 { + return strings.Join(append(lines, dim.Render("No matches. Try “archive”, “cron” or “login”.")), "\n") + } + rowHeight := 3 + if height < 23 { + rowHeight = 2 + } + page := max(1, (height-6)/rowHeight) + start := max(0, m.selected-page+1) + for i := start; i < min(len(actions), start+page); i++ { + action := actions[i] + name := " " + action.Title + if i == m.selected { + name = "▸ " + action.Title + } + if i == m.selected { + lines = append(lines, selectedStyle.Bold(true).Width(width).Render(clip(name, width))) + } else { + lines = append(lines, textStyle.Render(clip(name, width))) + } + if rowHeight == 3 { + lines = append(lines, dim.Render(clip(" "+action.Description, width))) + } + lines = append(lines, "") + } + lines = append(lines, dim.Render(fmt.Sprintf("%02d / %02d", m.selected+1, len(actions)))+" "+dim.Render("Enter to open · Review before making changes")) + return strings.Join(lines, "\n") +} + +func (m Model) formView(width, height int) string { + fields := m.visibleFields() + top := accent.Render("01 CONFIGURE") + dim.Render(" ─── 02 REVIEW ─── 03 RUN") + heading := titleStyle.Render(m.form.Action.Title) + mode := "Common options" + if m.advanced { + mode = "All options" + } + if m.fieldSearch != "" { + mode = "Matching options" + } + unit := "fields" + if len(fields) == 1 { + unit = "field" + } + status := dim.Render(fmt.Sprintf("%s · %d %s · Ctrl+A to switch", mode, len(fields), unit)) + if m.searching { + status = accent.Render("/ ") + m.inputView(width-3, false) + } + lines := []string{top, "", heading, clip(status, width), ""} + page := max(1, height-11) + start := max(0, m.focus-page+1) + labelWidth := min(25, width/2) + for n := start; n < min(len(fields), start+page); n++ { + field := m.form.Fields[fields[n]] + marker := " " + if n == m.focus { + marker = "▸ " + } + label := field.Label + if field.Required { + label += " *" + } + label = lipgloss.NewStyle().Width(labelWidth).Render(clip(marker+label, labelWidth)) + value := field.Display() + if m.editing && n == m.focus { + value = m.inputView(width-labelWidth-4, field.Secret) + } + change := " " + if field.Dirty { + change = "•" + } + row := label + " " + change + " " + clip(value, width-labelWidth-3) + if n == m.focus { + lines = append(lines, selectedStyle.Width(width).Render(row)) + } else { + lines = append(lines, textStyle.Render(row)) + } + } + if len(fields) == 0 { + lines = append(lines, dim.Render("No matching options. Esc clears the search.")) + } + for len(lines) < height-5 { + lines = append(lines, "") + } + if len(fields) > 0 { + field := m.form.Fields[fields[m.focus]] + help := field.Help + if field.Type == "stringArray" || field.Type == "stringSlice" { + help += " Comma-separated values; quote a value containing a comma." + } + if len(field.Choices) > 0 { + help += " Choices: " + strings.Join(field.Choices, ", ") + "." + } + lines = append(lines, dim.Render(strings.Repeat("─", width))) + lines = append(lines, dim.Render(fit(ansi.Wrap(help, width, ""), width, 2))) + lines = append(lines, dim.Render(fmt.Sprintf("%d / %d", m.focus+1, len(fields)))+" "+accent.Render("Ctrl+R Review command")) + } + if m.err != "" { + lines = append(lines, lipgloss.NewStyle().Foreground(lipgloss.Color("#FFAFB8")).Render(clip("! "+m.err, width))) + } + return strings.Join(lines, "\n") +} + +func (m Model) reviewView(width, height int) string { + lines := []string{accent.Render("READY TO START"), "", titleStyle.Render(m.plan.Title), ""} + for _, field := range m.form.Fields { + if field.Name == "arguments" && field.Value == "" { + continue + } + if !field.Dirty { + continue + } + lines = append(lines, dim.Render(field.Label+" ")+textStyle.Render(clip(field.Display(), max(1, width-len(field.Label)-2)))) + } + if len(lines) == 4 { + lines = append(lines, dim.Render("Using the default settings for this workflow.")) + } + if len(m.plan.Path) > 0 && m.plan.Path[0] == "login" { + lines = append(lines, "", warning.Render("This replaces the saved login in the selected namespace.")) + } + if strings.Join(m.plan.Path, " ") == "cron remove" { + lines = append(lines, "", warning.Render("Remove this schedule? Its archives and logs will be kept.")) + } + lines = append(lines, "", dim.Render("Results and progress stay in the workspace. You can cancel an active task."), "", accent.Render("Enter to start · Esc to edit")+dim.Render(" · c command preview")) + if m.showCommand { + lines = append(lines, "", dim.Render("COMMAND PREVIEW"), ansi.Hardwrap(m.plan.Preview(), width, false)) + } + return scrolled(strings.Join(lines, "\n"), width, height, m.scroll) +} + +func (m Model) helpView(width, height int) string { + content := titleStyle.Render("A few keys. Every command.") + "\n\n" + accent.Render("WORKSPACE") + "\n↑/↓ or j/k Choose a command\nTab / ←/→ Change section\n/ Search across every command\nEnter Configure the selected command\n\n" + accent.Render("OPTIONS") + "\n↑/↓ or Tab Move between fields\nEnter Edit text or toggle a switch\nSpace / ←/→ Toggle a switch or cycle choices\nCtrl+A Show or hide advanced options\n/ Find any option, including advanced ones\nCtrl+D Reset a field to its inherited default\nCtrl+R Validate and review the command\n\n" + accent.Render("EDITING") + "\nEnter saves · Esc cancels · Ctrl+U clears\nHome/End · ←/→ · Ctrl+W delete word\nTab completes a unique file or directory path\n\nRESULTS & TASKS\nTab / Shift+Tab Focus action buttons\nEnter / click Activate the focused button\n↑/↓ · / Select or search results\nt / l / d Results / Activity / Details\ni Respond to an active prompt (Esc ends input)\nCtrl+C Cancel active task; keep workspace open\n\nEsc goes back · Ctrl+C exits when idle · ? closes this guide" + return scrolled(content, width, height, m.scroll) +} + +func (m Model) footer() string { + if m.help { + return dim.Render("↑↓ scroll Esc / ? close guide") + } + if m.editing { + return accent.Render("Enter save") + dim.Render(" Esc cancel Ctrl+U clear Tab complete path") + } + if m.searching { + return accent.Render("Type to search") + dim.Render(" Enter finish Esc clear") + } + switch m.screen { + case configure: + return accent.Render("Enter edit") + dim.Render(" ↑↓ move Ctrl+A advanced Ctrl+R review F6 buttons Esc back ? help") + case review: + return accent.Render("Enter run") + dim.Render(" Esc edit ↑↓ scroll ? help") + case running: + if m.responding { + return accent.Render("Responding") + dim.Render(" Enter submit Esc controls Ctrl+C cancel") + } + return accent.Render("Tab buttons / Enter activate") + dim.Render(" i respond ↑↓ scroll f follow Ctrl+C cancel") + case result: + return accent.Render("↑↓ select · Tab buttons · Enter activate") + dim.Render(" / search t results l activity e edit Esc home") + default: + return accent.Render("Enter select") + dim.Render(" ↑↓ move Tab section F6 buttons / search ? help q quit") + } +} + +func (m Model) inputView(width int, secret bool) string { + value := string(m.input) + if secret { + value = strings.Repeat("•", len(m.input)) + } + runes := []rune(value) + start := max(0, m.cursor-max(1, width-3)) + before := string(runes[start:m.cursor]) + current, after := " ", "" + if m.cursor < len(runes) { + current, after = string(runes[m.cursor]), string(runes[m.cursor+1:]) + } + return clip(before+lipgloss.NewStyle().Reverse(true).Render(current)+after, width) +} + +func clip(value string, width int) string { return ansi.Truncate(value, max(1, width), "…") } + +func fit(value string, width, height int) string { + lines := strings.Split(value, "\n") + for len(lines) < height { + lines = append(lines, "") + } + for i := range lines { + lines[i] = clip(lines[i], width) + } + return strings.Join(lines[:min(len(lines), max(1, height))], "\n") +} + +func scrolled(value string, width, height, offset int) string { + lines := strings.Split(value, "\n") + offset = min(offset, max(0, len(lines)-height)) + return fit(strings.Join(lines[offset:], "\n"), width, height) +} + +func indent(value, prefix string) string { + return prefix + strings.ReplaceAll(value, "\n", "\n"+prefix) +} diff --git a/performance.md b/performance.md new file mode 100644 index 0000000..d64ad82 --- /dev/null +++ b/performance.md @@ -0,0 +1,36 @@ +The strongest opportunity is making ta faster and more reliable for repeated backups. It shares tdl’s download machinery, so the biggest gains are in scheduling, recovery, and avoiding repeated export work. + +I inspected the archive code, ran go test ./... successfully, and measured local performance. + +On this M1 Pro, using synthetic messages with formatted text and no network downloads: + +| Existing archive | Sync with no changes | Add one message, JSON | Add one message, JSON + HTML | +|---|---:|---:|---:| +| 10,000 messages | ~25 ms | ~163 ms | ~455 ms | +| 100,000 messages | ~25 ms | ~1.32 s | ~4.18 s | + +The last case allocated about 2.4 GB cumulatively per operation, although peak RAM is lower. Network throughput against tdl remains unmeasured. + +These are the improvements I would prioritize: + +| Priority | Current limitation | Recommended change | +|---|---|---| +| 1. Incremental rendering | One changed message invalidates the entire export cache. JSON + HTML also reads and decodes every message twice. | Track changed message IDs, update affected HTML pages, maintain statistics incrementally, and render both formats from one decoding pass. | +| 2. Continuous download scheduling | The next history page waits until every selected file in the current page finishes. Chats also run sequentially. | Prefetch a bounded number of pages and feed a shared download queue across chats, with one global concurrency budget. | +| 3. Resume partial files | Completed files are reused, but interrupted downloads lose their partial data. | Keep stable .part files and a completed-chunk bitmap; request only missing ranges after reconnecting. | +| 4. Deduplicate media | Filenames contain message IDs, so the same document posted repeatedly can be downloaded repeatedly. | Index media by Telegram resource identity and variant; reuse downloaded content across messages and chats. | +| 5. Cache resource lookups | Custom emoji documents are resolved again for each history page. | Add a bounded cache with refresh handling for expired file references. | +| 6. Tune concurrency automatically | Task count, threads, and connection pool size are static. | Adjust within a global limit using observed throughput, latency, and flood waits. Benchmark different workloads before choosing defaults. | + +The important implementation details are: + +1. Rendering is the clearest measured bottleneck. The cache checks one archive-wide revision in render_cache.go (internal/archive/render_cache.go:52), and render.go (internal/archive/render.go:160) performs separate JSON and HTML passes. Start here for recurring backups. A complete replacement result.json still requires writing the complete file; optional segmented exports or generating that compatibility file on demand would avoid this cost. +2. Scheduling should preserve checkpoint correctness. engine.go (internal/archive/engine.go:314) processes pages sequentially, while batch.go (internal/archive/batch.go:53) processes chats sequentially. Overlap fetching and downloading, but advance checkpoints only through fully completed work. Synchronize shared source state before introducing concurrent history requests. +3. Partial-file recovery would substantially reduce wasted bandwidth. engine.go (internal/archive/engine.go:406) deletes temporary downloads after failure, and source.go (internal/telegram/source.go:466) truncates the destination. Because chunks arrive out of order, file length alone cannot prove which chunks are complete. +4. Deduplication should use resource identity rather than output paths. convert.go (internal/telegram/convert.go:276) includes the message ID in filenames. The current singleflight group only combines overlapping requests for the same path within one page. + +There is also an existing advantage worth benchmarking: ta’s archive download writer avoids tdl’s 200 ms delay when writing a short final chunk. That could help workloads containing many small files. The delay is visible in tdl’s progress writer. + +To become more compelling than tdl, build around searchable, verifiable, repairable archives: search across local chats, checksum verification, repair missing media, and efficient handling of edits. Parallel downloads, takeout sessions, and resume already exist in tdl; reliable ongoing backups give ta a clearer advantage. + +No repository files were changed.