Repository: iyear/tdl Branch: master Commit: 7c1b61b0a6f1 Files: 234 Total size: 517.4 KB Directory structure: gitextract_qifrln_6/ ├── .editorconfig ├── .gitattributes ├── .github/ │ ├── CODEOWNERS │ ├── ISSUE_TEMPLATE/ │ │ ├── bug_report.yaml │ │ └── feature_request.yml │ ├── dependabot.yml │ └── workflows/ │ ├── dependabot-fix.yml │ ├── docker.yml │ ├── docs.yml │ ├── master.yml │ └── release.yml ├── .gitignore ├── .golangci.yaml ├── .goreleaser.yaml ├── Dockerfile ├── LICENSE ├── Makefile ├── README.md ├── README_zh.md ├── app/ │ ├── chat/ │ │ ├── export.go │ │ ├── export_enum.go │ │ ├── ls.go │ │ ├── ls_enum.go │ │ └── users.go │ ├── dl/ │ │ ├── dl.go │ │ ├── elem.go │ │ ├── iter.go │ │ ├── iter_test.go │ │ ├── progress.go │ │ ├── serve.go │ │ └── serve.go.tmpl │ ├── extension/ │ │ └── extension.go │ ├── forward/ │ │ ├── elem.go │ │ ├── forward.go │ │ ├── iter.go │ │ └── progress.go │ ├── internal/ │ │ └── tctx/ │ │ └── tctx.go │ ├── login/ │ │ ├── code.go │ │ ├── desktop.go │ │ ├── login.go │ │ ├── login_enum.go │ │ └── qr.go │ ├── migrate/ │ │ ├── backup.go │ │ ├── migrate.go │ │ └── recover.go │ └── up/ │ ├── elem.go │ ├── iter.go │ ├── progress.go │ ├── up.go │ └── walk.go ├── cmd/ │ ├── chat.go │ ├── dl.go │ ├── extension.go │ ├── forward.go │ ├── gen.go │ ├── login.go │ ├── migrate.go │ ├── root.go │ ├── up.go │ ├── version.go │ └── version.tmpl ├── core/ │ ├── dcpool/ │ │ ├── dcpool.go │ │ └── middlewares.go │ ├── downloader/ │ │ ├── downloader.go │ │ ├── iter.go │ │ └── progress.go │ ├── forwarder/ │ │ ├── clone.go │ │ ├── forwarder.go │ │ ├── forwarder_enum.go │ │ ├── iter.go │ │ └── progress.go │ ├── go.mod │ ├── go.sum │ ├── logctx/ │ │ └── logctx.go │ ├── middlewares/ │ │ ├── recovery/ │ │ │ └── recovery.go │ │ ├── retry/ │ │ │ └── retry.go │ │ └── takeout/ │ │ ├── middleware.go │ │ └── takeout.go │ ├── storage/ │ │ ├── keygen/ │ │ │ └── keygen.go │ │ ├── peers.go │ │ ├── session.go │ │ ├── state.go │ │ └── storage.go │ ├── tclient/ │ │ └── tclient.go │ ├── tmedia/ │ │ ├── convert.go │ │ ├── document.go │ │ ├── media.go │ │ └── photo.go │ ├── uploader/ │ │ ├── iter.go │ │ ├── progress.go │ │ └── uploader.go │ └── util/ │ ├── fsutil/ │ │ └── fsutil.go │ ├── logutil/ │ │ └── logutil.go │ ├── mediautil/ │ │ └── mediautil.go │ ├── netutil/ │ │ └── netutil.go │ └── tutil/ │ ├── device.go │ └── tutil.go ├── docs/ │ ├── assets/ │ │ └── _custom.scss │ ├── content/ │ │ ├── en/ │ │ │ ├── _index.md │ │ │ ├── getting-started/ │ │ │ │ ├── _index.md │ │ │ │ ├── installation.md │ │ │ │ ├── quick-start.md │ │ │ │ └── shell-completion.md │ │ │ ├── guide/ │ │ │ │ ├── _index.md │ │ │ │ ├── download.md │ │ │ │ ├── extensions.md │ │ │ │ ├── forward.md │ │ │ │ ├── global-config.md │ │ │ │ ├── login.md │ │ │ │ ├── migration.md │ │ │ │ ├── template.md │ │ │ │ ├── tools/ │ │ │ │ │ ├── _index.md │ │ │ │ │ ├── export-members.md │ │ │ │ │ ├── export-messages.md │ │ │ │ │ └── list-chats.md │ │ │ │ └── upload.md │ │ │ ├── more/ │ │ │ │ ├── _index.md │ │ │ │ ├── cli/ │ │ │ │ │ └── _index.md │ │ │ │ ├── data.md │ │ │ │ ├── env.md │ │ │ │ └── troubleshooting.md │ │ │ ├── reference/ │ │ │ │ ├── _index.md │ │ │ │ └── expr.md │ │ │ └── snippets/ │ │ │ ├── _index.md │ │ │ ├── chat.md │ │ │ └── link.md │ │ └── zh/ │ │ ├── _index.md │ │ ├── getting-started/ │ │ │ ├── _index.md │ │ │ ├── installation.md │ │ │ ├── quick-start.md │ │ │ └── shell-completion.md │ │ ├── guide/ │ │ │ ├── _index.md │ │ │ ├── download.md │ │ │ ├── extensions.md │ │ │ ├── forward.md │ │ │ ├── global-config.md │ │ │ ├── login.md │ │ │ ├── migration.md │ │ │ ├── template.md │ │ │ ├── tools/ │ │ │ │ ├── _index.md │ │ │ │ ├── export-members.md │ │ │ │ ├── export-messages.md │ │ │ │ └── list-chats.md │ │ │ └── upload.md │ │ ├── more/ │ │ │ ├── _index.md │ │ │ ├── cli/ │ │ │ │ └── _index.md │ │ │ ├── data.md │ │ │ ├── env.md │ │ │ └── troubleshooting.md │ │ ├── reference/ │ │ │ ├── _index.md │ │ │ └── expr.md │ │ └── snippets/ │ │ ├── _index.md │ │ ├── chat.md │ │ └── link.md │ ├── go.mod │ ├── go.sum │ ├── hugo.yaml │ ├── layouts/ │ │ ├── partials/ │ │ │ └── docs/ │ │ │ └── inject/ │ │ │ ├── footer.html │ │ │ └── head.html │ │ └── shortcodes/ │ │ ├── command.html │ │ ├── image.html │ │ └── include.html │ └── resources/ │ └── _gen/ │ └── assets/ │ └── scss/ │ ├── book.scss_e129fe35b8d0a70789c8a08429469073.content │ └── book.scss_e129fe35b8d0a70789c8a08429469073.json ├── extension/ │ ├── extension.go │ ├── go.mod │ └── go.sum ├── go.mod ├── go.sum ├── go.work ├── go.work.sum ├── hack/ │ ├── lib.sh │ └── release_mod.sh ├── main.go ├── pkg/ │ ├── clock/ │ │ └── clock.go │ ├── consts/ │ │ ├── consts.go │ │ ├── flag.go │ │ ├── path.go │ │ └── version.go │ ├── extensions/ │ │ ├── extensions.go │ │ ├── extensions_enum.go │ │ ├── extensions_test.go │ │ ├── github.go │ │ ├── local.go │ │ ├── local_test.go │ │ └── manager.go │ ├── filterMap/ │ │ └── filterMap.go │ ├── key/ │ │ └── key.go │ ├── kv/ │ │ ├── bolt.go │ │ ├── file.go │ │ ├── kv.go │ │ ├── kv_enum.go │ │ ├── kv_test.go │ │ └── legacy.go │ ├── prog/ │ │ ├── prog.go │ │ └── tracker.go │ ├── ps/ │ │ └── ps.go │ ├── tclient/ │ │ ├── app.go │ │ └── tclient.go │ ├── tdesktop/ │ │ ├── .s │ │ └── tdesktop.go │ ├── texpr/ │ │ ├── env.go │ │ ├── env_test.go │ │ ├── expr.go │ │ ├── fields.go │ │ └── fields_test.go │ ├── tmessage/ │ │ ├── files.go │ │ ├── tmessage.go │ │ └── urls.go │ ├── tpath/ │ │ ├── tpath.go │ │ ├── tpath_darwin.go │ │ ├── tpath_linux.go │ │ ├── tpath_other.go │ │ └── tpath_windows.go │ ├── tplfunc/ │ │ ├── date.go │ │ ├── date_test.go │ │ ├── func.go │ │ ├── math.go │ │ ├── math_test.go │ │ ├── string.go │ │ └── string_test.go │ ├── utils/ │ │ ├── byte.go │ │ └── cmd.go │ └── validator/ │ └── validator.go ├── scripts/ │ ├── install.ps1 │ └── install.sh └── test/ ├── archive_test.go ├── chat_ls_test.go ├── chat_users_test.go ├── download_test.go ├── suite_test.go ├── testserver/ │ ├── public_key.pem │ └── testserver.go └── upload_test.go ================================================ FILE CONTENTS ================================================ ================================================ FILE: .editorconfig ================================================ root = true [*] charset = utf-8 end_of_line = lf indent_style = space insert_final_newline = true trim_trailing_whitespace = true [*.{go,mod}] indent_style = tab [Makefile] indent_style = tab [*.md] max_line_length = off trim_trailing_whitespace = false ================================================ FILE: .gitattributes ================================================ * text=auto eol=lf *.{png,jpg,jpeg,gif,webp,woff,woff2} binary # https://joshuatz.com/posts/2019/how-to-get-github-to-recognize-a-pure-markdown-repo/ *.md linguist-vendored=false *.md linguist-generated=false *.md linguist-documentation=false *.md linguist-detectable=true ================================================ FILE: .github/CODEOWNERS ================================================ * @iyear *.go @XMLHexagram *.md @XMLHexagram ================================================ FILE: .github/ISSUE_TEMPLATE/bug_report.yaml ================================================ name: Bug Report description: Create a report to help us improve title: "[Bug] Please complete title/请完善标题" labels: ["bug"] assignees: - iyear body: - type: markdown attributes: value: | > [!IMPORTANT] > Make sure to browse the opened and closed issues before submit your issue. > > 对于中文用户,请使用英文编写标题和内容(可以选择使用机器翻译) - type: textarea id: description attributes: label: Describe the bug description: A clear and concise description of what the bug is placeholder: It always crashes when I do [...] validations: required: true - type: textarea id: reproduction attributes: label: To Reproduce description: Steps to reproduce the behavior placeholder: | 1. Run '...' 2. Click on '....' 3. See error validations: required: true - type: textarea id: expectation attributes: label: Expected behavior description: A clear and concise description of what you expected to happen. placeholder: | It should do [...] validations: required: true - type: textarea id: version attributes: label: Version description: | ```console $ tdl version // output ``` placeholder: | Version: 0.14.1 Commit: 3021de5 Date: 2024-01-05T16:27:43Z go1.19.13 windows/amd64 validations: required: true - type: dropdown id: os attributes: label: Which OS are you running tdl on? multiple: false options: - Windows - macOS - Linux - Other validations: required: true - type: textarea id: additional attributes: label: Additional context description: Add any other context about the problem here placeholder: | Logs, screenshots, etc. ================================================ FILE: .github/ISSUE_TEMPLATE/feature_request.yml ================================================ name: Feature Request description: Suggest an idea for tdl title: "[Feat] Please complete title/请完善标题" labels: ["enhancement"] assignees: - iyear body: - type: markdown attributes: value: | > [!IMPORTANT] > Make sure to browse the opened and closed issues before submit your issue. > > 对于中文用户,请使用英文编写标题和内容(可以选择使用机器翻译) - type: textarea id: proposal attributes: label: Proposal description: Write your feature request in the form of a proposal to be considered for implementation. validations: required: true - type: textarea id: background attributes: label: Background description: Describe the background problem or need that led to this feature request. validations: required: true - type: textarea id: workarounds attributes: label: Workarounds description: Are there any current workarounds that you're using that others in similar positions should know about? validations: required: true ================================================ FILE: .github/dependabot.yml ================================================ # To get started with Dependabot version updates, you'll need to specify which # package ecosystems to update and where the package manifests are located. # Please see the documentation for all configuration options: # https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates version: 2 updates: - package-ecosystem: "gomod" # See documentation for possible values directories: - "/" - "/core" - "/extension" schedule: interval: "daily" assignees: - "iyear" open-pull-requests-limit: 99 - package-ecosystem: "github-actions" directory: "/" schedule: interval: "daily" assignees: - "iyear" open-pull-requests-limit: 99 ================================================ FILE: .github/workflows/dependabot-fix.yml ================================================ name: dependabot-fix on: pull_request: branches: - dependabot/go_modules/** push: branches: - dependabot/go_modules/** jobs: tidy: runs-on: ubuntu-22.04 permissions: contents: write steps: - name: Checkout uses: actions/checkout@v6 - name: Setup Golang env uses: actions/setup-go@v6 with: go-version-file: go.mod cache: true - uses: evantorrie/mott-the-tidier@v1-beta with: # mod tidy all modules except docs(hugo module) gomods: | **/go.mod -docs/go.mod - uses: stefanzweifel/git-auto-commit-action@v7 with: commit_message: "chore(deps): tidy modules" ================================================ FILE: .github/workflows/docker.yml ================================================ name: docker on: workflow_dispatch: inputs: ref: description: 'Ref to checkout' required: true default: 'master' push: tags: - 'v*' jobs: docker: runs-on: ubuntu-22.04 steps: - name: Checkout uses: actions/checkout@v6 with: fetch-depth: 0 ref: ${{ github.event_name == 'workflow_dispatch' && inputs.ref || github.ref }} - name: Docker meta id: meta uses: docker/metadata-action@v6 with: context: git images: | ${{ github.repository }} ghcr.io/${{ github.repository }} tags: | type=match,pattern=\d+.\d+.\d+ type=ref,event=branch type=ref,event=pr - name: Set up QEMU uses: docker/setup-qemu-action@v4 - name: Set up Docker Buildx uses: docker/setup-buildx-action@v4 - name: Login to DockerHub uses: docker/login-action@v4 with: username: ${{ github.repository_owner }} password: ${{ secrets.DOCKERHUB_TOKEN }} - name: Login to GitHub Container Registry uses: docker/login-action@v4 with: registry: ghcr.io username: ${{ github.repository_owner }} password: ${{ secrets.RELEASE_TOKEN }} - name: Use latest Dockerfile if workflow_dispatch if: ${{ github.event_name == 'workflow_dispatch' }} run: | curl -s https://raw.githubusercontent.com/iyear/tdl/master/Dockerfile > Dockerfile - name: Extract Dockerfile args id: args run: | echo "commit=$(git rev-parse --short HEAD)" >> "$GITHUB_OUTPUT" echo "commit_date=$(git show -s --format=%cI)" >> "$GITHUB_OUTPUT" - name: Build and push uses: docker/build-push-action@v7 with: context: . cache-from: type=gha cache-to: type=gha,mode=max build-args: | VERSION=${{ steps.meta.outputs.version }} COMMIT=${{ steps.args.outputs.commit }} COMMIT_DATE=${{ steps.args.outputs.commit_date }} platforms: linux/amd64,linux/386,linux/arm64,linux/arm/v7,linux/arm/v6,linux/riscv64 push: true provenance: false tags: ${{ steps.meta.outputs.tags }} labels: ${{ steps.meta.outputs.labels }} ================================================ FILE: .github/workflows/docs.yml ================================================ name: deploy docs on: push: tags: - 'v*' workflow_dispatch: permissions: contents: read pages: write id-token: write concurrency: group: "pages" cancel-in-progress: false jobs: build: runs-on: ubuntu-22.04 env: HUGO_VERSION: 0.119.0 # also update cloudflare pages env variable if changed steps: - name: Install Hugo CLI run: | wget -O ${{ runner.temp }}/hugo.deb https://github.com/gohugoio/hugo/releases/download/v${HUGO_VERSION}/hugo_extended_${HUGO_VERSION}_linux-amd64.deb \ && sudo dpkg -i ${{ runner.temp }}/hugo.deb - name: Checkout uses: actions/checkout@v6 with: submodules: recursive fetch-depth: 0 - name: Setup Golang env uses: actions/setup-go@v6 with: go-version-file: go.mod cache: true - name: Generate CLI docs run: go run main.go gen doc -d docs/content/en/more/cli - name: Setup Pages id: pages uses: actions/configure-pages@v5 - name: Build with Hugo env: HUGO_ENVIRONMENT: production HUGO_ENV: production run: | cd docs hugo \ --gc \ --minify \ --baseURL "${{ steps.pages.outputs.base_url }}/" - name: Copy install scripts run: | cp -r scripts/install.* docs/public - name: Upload artifact uses: actions/upload-pages-artifact@v4 with: path: ./docs/public deploy: environment: name: github-pages url: ${{ steps.deployment.outputs.page_url }} runs-on: ubuntu-22.04 needs: build steps: - name: Deploy to GitHub Pages id: deployment uses: actions/deploy-pages@v4 ================================================ FILE: .github/workflows/master.yml ================================================ name: master builder on: pull_request: types: [opened, synchronize, reopened, labeled, unlabeled] branches: [master] push: branches: [master] paths-ignore: - "docs/**" permissions: contents: read pull-requests: read jobs: lint: runs-on: ubuntu-22.04 strategy: fail-fast: false matrix: directory: - . - core - extension steps: - name: Checkout uses: actions/checkout@v6 - name: Setup Golang env uses: actions/setup-go@v6 with: go-version-file: go.mod cache: false # conflict with golangci-lint cache - name: lint uses: golangci/golangci-lint-action@v9 with: version: v2.6.0 working-directory: ${{ matrix.directory }} unit-test: runs-on: ubuntu-22.04 steps: - name: Checkout uses: actions/checkout@v6 - name: Setup Golang env uses: actions/setup-go@v6 with: go-version-file: go.mod cache: true - name: Build run: go build - name: Unit Test run: go test -v $(go list ./... | grep -v /test) # skip e2e test e2e-test: runs-on: ubuntu-22.04 steps: - name: Checkout uses: actions/checkout@v6 - name: Setup Golang env uses: actions/setup-go@v6 with: go-version-file: go.mod cache: true - name: Install Ginkgo run: go install github.com/onsi/ginkgo/v2/ginkgo - name: Setup Teamgram Env run: | git clone https://github.com/iyear/teamgram-server.git cd teamgram-server git checkout 10151bb92555aa1bedcba9f8f24b0e7deac22dee sudo docker compose -f ./docker-compose-env.yaml up -d --quiet-pull sudo docker compose up -d --quiet-pull - name: Build run: go build - name: E2E Test run: ginkgo -v -r ./test ================================================ FILE: .github/workflows/release.yml ================================================ name: release on: workflow_dispatch: push: tags: - 'v*' permissions: contents: write jobs: homebrew: runs-on: ubuntu-22.04 steps: - name: Bump Homebrew formula uses: dawidd6/action-homebrew-bump-formula@v7 with: token: ${{ secrets.RELEASE_TOKEN }} formula: telegram-downloader goreleaser: runs-on: ubuntu-22.04 steps: - name: Checkout uses: actions/checkout@v6 with: fetch-depth: 0 - name: Fetch all tags run: git fetch --force --tags - name: Set up Go uses: actions/setup-go@v6 with: go-version-file: go.mod cache: true - name: Get previous tag run: echo "PREV_TAG=$(git describe --tags --match "v*" --abbrev=0 HEAD^)" >> $GITHUB_ENV - name: Run GoReleaser uses: goreleaser/goreleaser-action@v7 with: distribution: goreleaser version: v1.18.2 args: release --rm-dist --timeout 1h env: GITHUB_TOKEN: ${{ secrets.RELEASE_TOKEN }} GORELEASER_PREVIOUS_TAG: ${{ env.PREV_TAG }} ================================================ FILE: .gitignore ================================================ .idea log .tdl .vscode downloads *.exe tdl .hugo_build.lock .DS_Store ================================================ FILE: .golangci.yaml ================================================ version: "2" linters: default: none enable: - exhaustive - goconst - govet - ineffassign - misspell - nakedret - staticcheck - unconvert - unused - usestdlibvars settings: exhaustive: default-signifies-exhaustive: true nakedret: max-func-lines: 0 exclusions: generated: lax presets: - comments - common-false-positives - legacy - std-error-handling paths: - third_party$ - builtin$ - examples$ formatters: enable: - gci - gofumpt settings: gci: sections: - standard - default - prefix(github.com/iyear/tdl) - dot custom-order: true exclusions: generated: lax paths: - third_party$ - builtin$ - examples$ ================================================ FILE: .goreleaser.yaml ================================================ project_name: tdl dist: .tdl/dist env: - GO111MODULE=on builds: - env: - CGO_ENABLED=0 flags: - -trimpath ldflags: - -s -w - -X github.com/iyear/tdl/pkg/consts.Version={{ .Version }} - -X github.com/iyear/tdl/pkg/consts.Commit={{ .ShortCommit }} - -X github.com/iyear/tdl/pkg/consts.CommitDate={{ .CommitDate }} mod_timestamp: '{{ .CommitTimestamp }}' goos: - linux - windows - darwin goarch: - 386 - amd64 - arm - arm64 - riscv64 - loong64 goarm: - 5 - 6 - 7 checksum: name_template: '{{ .ProjectName }}_checksums.txt' archives: - name_template: '{{ .ProjectName }}_{{ .Os }}_{{ .Arch }}{{ if .Arm }}v{{ .Arm }}{{ end }}' replacements: darwin: MacOS linux: Linux windows: Windows 386: 32bit amd64: 64bit format_overrides: - goos: windows format: zip files: - README*.md - LICENSE changelog: use: github sort: asc groups: - title: New Features regexp: "^.*feat[(\\w)]*:+.*$" order: 0 - title: 'Bug fixes' regexp: "^.*fix[(\\w)]*:+.*$" order: 1 - title: 'Documentation updates' regexp: "^.*docs[(\\w)]*:+.*$" order: 2 - title: 'Refactoring' regexp: "^.*refactor[(\\w)]*:+.*$" order: 3 - title: Others order: 4 release: draft: true ================================================ FILE: Dockerfile ================================================ # https://www.docker.com/blog/faster-multi-platform-builds-dockerfile-cross-compilation-guide/ FROM --platform=$BUILDPLATFORM golang:1.25-alpine AS builder ARG VERSION="dev" ARG COMMIT="unknown" ARG COMMIT_DATE="unknown" WORKDIR / COPY . . ARG TARGETOS ARG TARGETARCH RUN --mount=type=cache,target=/root/.cache/go-build \ --mount=type=cache,target=/go/pkg \ GOOS=$TARGETOS GOARCH=$TARGETARCH \ go build -trimpath \ -ldflags "-s -w \ -X github.com/iyear/tdl/pkg/consts.Version=${VERSION} \ -X github.com/iyear/tdl/pkg/consts.Commit=${COMMIT} \ -X github.com/iyear/tdl/pkg/consts.CommitDate=${COMMIT_DATE}" \ -o tdl FROM alpine:latest RUN apk add --no-cache ca-certificates COPY --from=builder /tdl /usr/bin/tdl ENTRYPOINT ["tdl"] ================================================ FILE: LICENSE ================================================ GNU AFFERO GENERAL PUBLIC LICENSE Version 3, 19 November 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU Affero General Public License is a free, copyleft license for software and other kinds of works, specifically designed to ensure cooperation with the community in the case of network server software. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, our General Public Licenses are intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. Developers that use our General Public Licenses protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License which gives you legal permission to copy, distribute and/or modify the software. A secondary benefit of defending all users' freedom is that improvements made in alternate versions of the program, if they receive widespread use, become available for other developers to incorporate. Many developers of free software are heartened and encouraged by the resulting cooperation. However, in the case of software used on network servers, this result may fail to come about. The GNU General Public License permits making a modified version and letting the public access it on a server without ever releasing its source code to the public. The GNU Affero General Public License is designed specifically to ensure that, in such cases, the modified source code becomes available to the community. It requires the operator of a network server to provide the source code of the modified version running there to the users of that server. Therefore, public use of a modified version, on a publicly accessible server, gives the public access to the source code of the modified version. An older license, called the Affero General Public License and published by Affero, was designed to accomplish similar goals. This is a different license, not a version of the Affero GPL, but Affero has released a new version of the Affero GPL which permits relicensing under this license. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU Affero General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Remote Network Interaction; Use with the GNU General Public License. Notwithstanding any other provision of this License, if you modify the Program, your modified version must prominently offer all users interacting with it remotely through a computer network (if your version supports such interaction) an opportunity to receive the Corresponding Source of your version by providing access to the Corresponding Source from a network server at no charge, through some standard or customary means of facilitating copying of software. This Corresponding Source shall include the Corresponding Source for any work covered by version 3 of the GNU General Public License that is incorporated pursuant to the following paragraph. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the work with which it is combined will remain governed by version 3 of the GNU General Public License. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU Affero General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU Affero General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU Affero General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU Affero General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If your software can interact with users remotely through a computer network, you should also make sure that it provides a way for users to get its source. For example, if your program is a web application, its interface could display a "Source" link that leads users to an archive of the code. There are many ways you could offer source, and different solutions will be better for different programs; see section 13 for the specific requirements. You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU AGPL, see . ================================================ FILE: Makefile ================================================ .PHONY: build build: goreleaser build --rm-dist --single-target --snapshot @echo "go to '.tdl/dist' directory to see the package!" .PHONY: packaging packaging: goreleaser release --skip-publish --auto-snapshot --rm-dist @echo "go to '.tdl/dist' directory to see the packages!" ================================================ FILE: README.md ================================================ # tdl > 📥 Telegram Downloader, but more than a downloader English | 简体中文

#### Features: - Single file start-up - Low resource usage - Take up all your bandwidth - Faster than official clients - Download files from (protected) chats - Forward messages with automatic fallback and message routing - Upload files to Telegram - Export messages/members/subscribers to JSON ## Preview It reaches my proxy's speed limit, and the **speed depends on whether you are a premium** ![](docs/assets/img/preview.gif) ## Documentation Please refer to the [documentation](https://docs.iyear.me/tdl/). ## Sponsors ![](https://raw.githubusercontent.com/iyear/sponsor/master/sponsors.svg) ## Contributors contributors ## LICENSE AGPL-3.0 License ================================================ FILE: README_zh.md ================================================ > [!IMPORTANT] > 中文文档可能落后于英文文档,如果有问题请先查看英文文档。 > 请使用英文发起新的 Issue, 以便于追踪和搜索 # tdl > 📥 Telegram Downloader, but more than a downloader English | 简体中文

#### 特性: - 单文件启动 - 低资源占用 - 吃满你的带宽 - 比官方客户端更快 - 支持从受保护的会话中下载文件 - 具有自动回退和消息路由的转发功能 - 支持上传文件至 Telegram - 导出历史消息/成员/订阅者数据至 JSON 文件 ## 预览 预览中的速度已经达到了代理的限制,同时**速度取决于你是否是付费用户** ![](docs/assets/img/preview.gif) ## 文档 请参考 [文档](https://docs.iyear.me/tdl/zh/). ## 赞助者 ![](https://raw.githubusercontent.com/iyear/sponsor/master/sponsors.svg) ## 贡献者 contributors ## 协议 AGPL-3.0 License ================================================ FILE: app/chat/export.go ================================================ package chat import ( "context" "encoding/json" "fmt" "os" "time" "github.com/expr-lang/expr" "github.com/fatih/color" "github.com/go-faster/jx" "github.com/gotd/td/telegram" "github.com/gotd/td/telegram/peers" "github.com/gotd/td/telegram/query" "github.com/gotd/td/telegram/query/messages" "github.com/gotd/td/tg" "github.com/jedib0t/go-pretty/v6/progress" "go.uber.org/multierr" "github.com/iyear/tdl/core/storage" "github.com/iyear/tdl/core/tmedia" "github.com/iyear/tdl/core/util/tutil" "github.com/iyear/tdl/pkg/prog" "github.com/iyear/tdl/pkg/texpr" ) //go:generate go-enum --names --values --flag --nocase type ExportOptions struct { Type ExportType Chat string Thread int // topic id in forum, message id in group Input []int Output string Filter string OnlyMedia bool WithContent bool Raw bool All bool } type Message struct { ID int `json:"id"` Type string `json:"type"` File string `json:"file"` Date int `json:"date,omitempty"` Text string `json:"text,omitempty"` Raw *tg.Message `json:"raw,omitempty"` } // ExportType // ENUM(time, id, last) type ExportType int func Export(ctx context.Context, c *telegram.Client, kvd storage.Storage, opts ExportOptions) (rerr error) { // only output available fields if opts.Filter == "-" { fg := texpr.NewFieldsGetter(nil) fields, err := fg.Walk(&texpr.EnvMessage{}) if err != nil { return fmt.Errorf("failed to walk fields: %w", err) } fmt.Print(fg.Sprint(fields, true)) return nil } filter, err := expr.Compile(opts.Filter, expr.AsBool()) if err != nil { return fmt.Errorf("failed to compile filter: %w", err) } var peer peers.Peer manager := peers.Options{Storage: storage.NewPeers(kvd)}.Build(c.API()) if opts.Chat == "" { // defaults to me(saved messages) peer, err = manager.Self(ctx) } else { peer, err = tutil.GetInputPeer(ctx, manager, opts.Chat) } if err != nil { return fmt.Errorf("failed to get peer: %w", err) } color.Yellow("WARN: Export only generates minimal JSON for tdl download, not for backup.") color.Cyan("Occasional suspensions are due to Telegram rate limitations, please wait a moment.") fmt.Println() color.Blue("Type: %s | Input: %v", opts.Type, opts.Input) pw := prog.New(progress.FormatNumber) pw.SetUpdateFrequency(200 * time.Millisecond) pw.Style().Visibility.TrackerOverall = false pw.Style().Visibility.ETA = false pw.Style().Visibility.Percentage = false tracker := prog.AppendTracker(pw, progress.FormatNumber, fmt.Sprintf("%s-%d", peer.VisibleName(), peer.ID()), 0) go pw.Render() var q messages.Query switch { case opts.Thread != 0: // topic messages, reply messages q = query.NewQuery(c.API()).Messages().GetReplies(peer.InputPeer()).MsgID(opts.Thread) default: // history q = query.NewQuery(c.API()).Messages().GetHistory(peer.InputPeer()) } iter := messages.NewIterator(q, 100) switch opts.Type { case ExportTypeTime: iter = iter.OffsetDate(opts.Input[1] + 1) case ExportTypeId: iter = iter.OffsetID(opts.Input[1] + 1) // #89: retain the last msg id case ExportTypeLast: } f, err := os.Create(opts.Output) if err != nil { return err } defer multierr.AppendInvoke(&rerr, multierr.Close(f)) enc := jx.NewStreamingEncoder(f, 512) defer multierr.AppendInvoke(&rerr, multierr.Close(enc)) // process thread is reply type and peer is broadcast channel, // so we need to set discussion group id instead of broadcast id id := peer.ID() if p, ok := peer.(peers.Channel); opts.Thread != 0 && ok && p.IsBroadcast() { bc, _ := p.ToBroadcast() raw, err := bc.FullRaw(ctx) if err != nil { return fmt.Errorf("failed to get broadcast full raw: %w", err) } if id, ok = raw.GetLinkedChatID(); !ok { return fmt.Errorf("no linked group") } } enc.ObjStart() defer enc.ObjEnd() enc.Field("id", func(e *jx.Encoder) { e.Int64(id) }) enc.FieldStart("messages") enc.ArrStart() defer enc.ArrEnd() count := int64(0) loop: for iter.Next(ctx) { msg := iter.Value() switch opts.Type { case ExportTypeTime: if msg.Msg.GetDate() < opts.Input[0] { break loop } case ExportTypeId: if msg.Msg.GetID() < opts.Input[0] { break loop } case ExportTypeLast: if count >= int64(opts.Input[0]) { break loop } } m, ok := msg.Msg.(*tg.Message) if !ok { continue } // only get media messages media, ok := tmedia.GetMedia(m) if !ok && !opts.All { continue } b, err := texpr.Run(filter, texpr.ConvertEnvMessage(m)) if err != nil { return fmt.Errorf("failed to run filter: %w", err) } if !b.(bool) { // filtered continue } fileName := "" if media != nil { // #207 fileName = media.Name } t := &Message{ ID: m.ID, Type: "message", File: fileName, } if opts.WithContent { t.Date = m.Date t.Text = m.Message } if opts.Raw { t.Raw = m } mb, err := json.Marshal(t) if err != nil { return fmt.Errorf("failed to marshal message: %w", err) } enc.Raw(mb) count++ tracker.SetValue(count) } if err = iter.Err(); err != nil { return err } tracker.MarkAsDone() prog.Wait(ctx, pw) return nil } ================================================ FILE: app/chat/export_enum.go ================================================ // Code generated by go-enum DO NOT EDIT. // Version: 0.5.8 // Revision: 3d844c8ecc59661ed7aa17bfd65727bc06a60ad8 // Build Date: 2023-09-18T14:55:21Z // Built By: goreleaser package chat import ( "fmt" "strings" ) const ( // ExportTypeTime is a ExportType of type Time. ExportTypeTime ExportType = iota // ExportTypeId is a ExportType of type Id. ExportTypeId // ExportTypeLast is a ExportType of type Last. ExportTypeLast ) var ErrInvalidExportType = fmt.Errorf("not a valid ExportType, try [%s]", strings.Join(_ExportTypeNames, ", ")) const _ExportTypeName = "timeidlast" var _ExportTypeNames = []string{ _ExportTypeName[0:4], _ExportTypeName[4:6], _ExportTypeName[6:10], } // ExportTypeNames returns a list of possible string values of ExportType. func ExportTypeNames() []string { tmp := make([]string, len(_ExportTypeNames)) copy(tmp, _ExportTypeNames) return tmp } // ExportTypeValues returns a list of the values for ExportType func ExportTypeValues() []ExportType { return []ExportType{ ExportTypeTime, ExportTypeId, ExportTypeLast, } } var _ExportTypeMap = map[ExportType]string{ ExportTypeTime: _ExportTypeName[0:4], ExportTypeId: _ExportTypeName[4:6], ExportTypeLast: _ExportTypeName[6:10], } // String implements the Stringer interface. func (x ExportType) String() string { if str, ok := _ExportTypeMap[x]; ok { return str } return fmt.Sprintf("ExportType(%d)", x) } // IsValid provides a quick way to determine if the typed value is // part of the allowed enumerated values func (x ExportType) IsValid() bool { _, ok := _ExportTypeMap[x] return ok } var _ExportTypeValue = map[string]ExportType{ _ExportTypeName[0:4]: ExportTypeTime, strings.ToLower(_ExportTypeName[0:4]): ExportTypeTime, _ExportTypeName[4:6]: ExportTypeId, strings.ToLower(_ExportTypeName[4:6]): ExportTypeId, _ExportTypeName[6:10]: ExportTypeLast, strings.ToLower(_ExportTypeName[6:10]): ExportTypeLast, } // ParseExportType attempts to convert a string to a ExportType. func ParseExportType(name string) (ExportType, error) { if x, ok := _ExportTypeValue[name]; ok { return x, nil } // Case insensitive parse, do a separate lookup to prevent unnecessary cost of lowercasing a string if we don't need to. if x, ok := _ExportTypeValue[strings.ToLower(name)]; ok { return x, nil } return ExportType(0), fmt.Errorf("%s is %w", name, ErrInvalidExportType) } // Set implements the Golang flag.Value interface func. func (x *ExportType) Set(val string) error { v, err := ParseExportType(val) *x = v return err } // Get implements the Golang flag.Getter interface func. func (x *ExportType) Get() interface{} { return *x } // Type implements the github.com/spf13/pFlag Value interface. func (x *ExportType) Type() string { return "ExportType" } ================================================ FILE: app/chat/ls.go ================================================ package chat import ( "context" "encoding/json" "fmt" "strconv" "strings" "github.com/expr-lang/expr" "github.com/fatih/color" "github.com/go-faster/errors" "github.com/gotd/td/telegram" "github.com/gotd/td/telegram/message/peer" "github.com/gotd/td/telegram/peers" "github.com/gotd/td/telegram/query/dialogs" "github.com/gotd/td/tg" "github.com/mattn/go-runewidth" "go.uber.org/zap" "github.com/iyear/tdl/core/logctx" "github.com/iyear/tdl/core/storage" "github.com/iyear/tdl/core/util/tutil" "github.com/iyear/tdl/pkg/texpr" ) //go:generate go-enum --names --values --flag --nocase type Dialog struct { ID int64 `json:"id" comment:"ID of dialog"` Type string `json:"type" comment:"Type of dialog. Can be 'private', 'channel' or 'group'"` VisibleName string `json:"visible_name,omitempty" comment:"Title of channel and group, first and last name of user. If empty, output '-'"` Username string `json:"username,omitempty" comment:"Username of dialog. If empty, output '-'"` Topics []Topic `json:"topics,omitempty" comment:"Topics of dialog. If not set, output '-'"` } type Topic struct { ID int `json:"id" comment:"ID of topic"` Title string `json:"title" comment:"Title of topic"` } // ListOutput // ENUM(table, json) type ListOutput int // External designation, different from Telegram mtproto const ( DialogGroup = "group" DialogPrivate = "private" DialogChannel = "channel" DialogUnknown = "unknown" ) type ListOptions struct { Output ListOutput Filter string } func List(ctx context.Context, c *telegram.Client, kvd storage.Storage, opts ListOptions) error { log := logctx.From(ctx) // align output runewidth.EastAsianWidth = false runewidth.DefaultCondition.EastAsianWidth = false // output available fields if opts.Filter == "-" { fg := texpr.NewFieldsGetter(nil) fields, err := fg.Walk(&Dialog{}) if err != nil { return fmt.Errorf("failed to walk fields: %w", err) } fmt.Print(fg.Sprint(fields, true)) return nil } // compile filter filter, err := expr.Compile(opts.Filter, expr.AsBool()) if err != nil { return fmt.Errorf("failed to compile filter: %w", err) } // Manually iterate through dialogs to handle errors gracefully // This allows us to skip problematic dialogs (deleted/inaccessible channels) // rather than failing completely when ExtractPeer fails dialogs, skipped := fetchDialogsWithErrorHandling(ctx, c.API()) if skipped > 0 { log.Warn("skipped problematic dialogs during iteration", zap.Int("skipped", skipped), zap.Int("fetched", len(dialogs))) } blocked, err := tutil.GetBlockedDialogs(ctx, c.API()) if err != nil { return err } manager := peers.Options{Storage: storage.NewPeers(kvd)}.Build(c.API()) result := make([]*Dialog, 0, len(dialogs)) for _, d := range dialogs { id := tutil.GetInputPeerID(d.Peer) // we can update our access hash state if there is any new peer. if err = applyPeers(ctx, manager, d.Entities, id); err != nil { log.Warn("failed to apply peer updates", zap.Int64("id", id), zap.Error(err)) } // filter blocked peers if _, ok := blocked[id]; ok { continue } var r *Dialog switch t := d.Peer.(type) { case *tg.InputPeerUser: r = processUser(t.UserID, d.Entities) case *tg.InputPeerChannel: r = processChannel(ctx, c.API(), t.ChannelID, d.Entities) case *tg.InputPeerChat: r = processChat(t.ChatID, d.Entities) } // skip unsupported types if r == nil { continue } // filter b, err := texpr.Run(filter, r) if err != nil { return fmt.Errorf("failed to run filter: %w", err) } if !b.(bool) { continue } result = append(result, r) } switch opts.Output { case ListOutputTable: printTable(result) case ListOutputJson: bytes, err := json.MarshalIndent(result, "", "\t") if err != nil { return fmt.Errorf("marshal json: %w", err) } fmt.Println(string(bytes)) default: return fmt.Errorf("unknown output: %s", opts.Output) } return nil } func printTable(result []*Dialog) { fmt.Printf("%s %s %s %s %s\n", trunc("ID", 10), trunc("Type", 8), trunc("VisibleName", 20), trunc("Username", 20), "Topics") for _, r := range result { fmt.Printf("%s %s %s %s %s\n", trunc(strconv.FormatInt(r.ID, 10), 10), trunc(r.Type, 8), trunc(r.VisibleName, 20), trunc(r.Username, 20), topicsString(r.Topics)) } } func trunc(s string, len int) string { s = strings.TrimSpace(s) if s == "" { s = "-" } return runewidth.FillRight(runewidth.Truncate(s, len, "..."), len) } func topicsString(topics []Topic) string { if len(topics) == 0 { return "-" } s := make([]string, 0, len(topics)) for _, t := range topics { s = append(s, fmt.Sprintf("%d: %s", t.ID, t.Title)) } return strings.Join(s, ", ") } func processUser(id int64, entities peer.Entities) *Dialog { u, ok := entities.User(id) if !ok { return nil } return &Dialog{ ID: u.ID, VisibleName: visibleName(u.FirstName, u.LastName), Username: u.Username, Type: DialogPrivate, Topics: nil, } } func processChannel(ctx context.Context, api *tg.Client, id int64, entities peer.Entities) *Dialog { c, ok := entities.Channel(id) if !ok { return nil } d := &Dialog{ ID: c.ID, VisibleName: c.Title, Username: c.Username, } // channel type switch { case c.Broadcast: d.Type = DialogChannel case c.Megagroup, c.Gigagroup: d.Type = DialogGroup default: d.Type = DialogUnknown } if c.Forum { topics, err := fetchTopics(ctx, api, c.AsInput()) if err != nil { logctx.From(ctx).Error("failed to fetch topics", zap.Int64("channel_id", c.ID), zap.String("channel_username", c.Username), zap.Error(err)) return nil } d.Topics = topics } return d } // fetchTopics https://github.com/telegramdesktop/tdesktop/blob/4047f1733decd5edf96d125589f128758b68d922/Telegram/SourceFiles/data/data_forum.cpp#L135 func fetchTopics(ctx context.Context, api *tg.Client, c tg.InputChannelClass) ([]Topic, error) { log := logctx.From(ctx) res := make([]Topic, 0) limit := 100 // why can't we use 500 like tdesktop? offsetTopic, offsetID, offsetDate := 0, 0, 0 lastOffsetTopic := -1 // Track the last offsetTopic to detect infinite loops // Track seen offsetTopics to detect cycles seenOffsets := make(map[int]bool) for { // Detect infinite loop: if offsetTopic hasn't changed or we've seen it before if offsetTopic == lastOffsetTopic && lastOffsetTopic != -1 { log.Warn("pagination stuck (same offset), breaking loop", zap.Int("offset_topic", offsetTopic)) break } if seenOffsets[offsetTopic] { log.Warn("pagination cycle detected, breaking loop", zap.Int("offset_topic", offsetTopic)) break } seenOffsets[offsetTopic] = true lastOffsetTopic = offsetTopic req := &tg.ChannelsGetForumTopicsRequest{ Channel: c, Limit: limit, OffsetTopic: offsetTopic, OffsetID: offsetID, OffsetDate: offsetDate, } topics, err := api.ChannelsGetForumTopics(ctx, req) if err != nil { return nil, errors.Wrap(err, "get forum topics") } // If no topics returned, we're done if len(topics.Topics) == 0 { break } for _, tp := range topics.Topics { if t, ok := tp.(*tg.ForumTopic); ok { res = append(res, Topic{ ID: t.ID, Title: t.Title, }) offsetTopic = t.ID } } // Safety break if we've collected all topics if len(res) >= topics.Count { break } // last page if len(topics.Topics) < limit { break } // Update offset using last message if available // Use a local variable for length to be absolutely safe against index out of range msgCount := len(topics.Messages) if msgCount > 0 { if lastMsg, ok := topics.Messages[msgCount-1].AsNotEmpty(); ok { offsetID, offsetDate = lastMsg.GetID(), lastMsg.GetDate() } else { log.Debug("no valid message for offset, relying on offsetTopic only", zap.Int("offset_topic", offsetTopic)) } } else { log.Debug("no messages in topics response, relying on offsetTopic only", zap.Int("offset_topic", offsetTopic), zap.Int("topics_count", len(topics.Topics))) } } return res, nil } func processChat(id int64, entities peer.Entities) *Dialog { c, ok := entities.Chat(id) if !ok { return nil } return &Dialog{ ID: c.ID, VisibleName: c.Title, Username: "-", Type: DialogGroup, Topics: nil, } } func visibleName(first, last string) string { if first == "" && last == "" { return "" } if first == "" { return last } if last == "" { return first } return first + " " + last } func applyPeers(ctx context.Context, manager *peers.Manager, entities peer.Entities, id int64) error { users := make([]tg.UserClass, 0, 1) if user, ok := entities.User(id); ok { users = append(users, user) } chats := make([]tg.ChatClass, 0, 1) if chat, ok := entities.Chat(id); ok { chats = append(chats, chat) } if channel, ok := entities.Channel(id); ok { chats = append(chats, channel) } return manager.Apply(ctx, users, chats) } // fetchDialogsWithErrorHandling manually iterates through dialogs using the raw Telegram API // to gracefully handle errors from problematic dialogs (deleted/inaccessible channels). // Instead of failing completely when ExtractPeer fails in gotd's iterator, it logs errors // and continues, skipping bad dialogs. func fetchDialogsWithErrorHandling(ctx context.Context, api *tg.Client) ([]dialogs.Elem, int) { log := logctx.From(ctx) const batchSize = 100 var ( allElems []dialogs.Elem skipped int offsetID int offsetDate int offsetPeer tg.InputPeerClass = &tg.InputPeerEmpty{} seen = make(map[int64]bool) // Track seen dialog IDs to prevent duplicates ) for { // Fetch a batch of dialogs using raw API result, err := api.MessagesGetDialogs(ctx, &tg.MessagesGetDialogsRequest{ OffsetDate: offsetDate, OffsetID: offsetID, OffsetPeer: offsetPeer, Limit: batchSize, }) if err != nil { log.Error("failed to fetch dialog batch", zap.Error(err)) break } var ( dialogsSlice []tg.DialogClass messages []tg.MessageClass users []tg.UserClass chats []tg.ChatClass ) switch d := result.(type) { case *tg.MessagesDialogs: dialogsSlice = d.Dialogs messages = d.Messages users = d.Users chats = d.Chats case *tg.MessagesDialogsSlice: dialogsSlice = d.Dialogs messages = d.Messages users = d.Users chats = d.Chats case *tg.MessagesDialogsNotModified: // No more dialogs return allElems, skipped default: log.Error("unexpected dialog type", zap.String("type", fmt.Sprintf("%T", result))) return allElems, skipped } if len(dialogsSlice) == 0 { break } // Build entities map for this batch // Convert slices to maps as required by peer.NewEntities userMap := make(map[int64]*tg.User) for _, u := range users { if user, ok := u.(*tg.User); ok { userMap[user.ID] = user } } chatMap := make(map[int64]*tg.Chat) channelMap := make(map[int64]*tg.Channel) for _, c := range chats { switch chat := c.(type) { case *tg.Chat: chatMap[chat.ID] = chat case *tg.Channel: channelMap[chat.ID] = chat } } entities := peer.NewEntities(userMap, chatMap, channelMap) // Build message map for quick lookup by ID messageMap := make(map[int]tg.NotEmptyMessage) for _, msg := range messages { switch m := msg.(type) { case *tg.Message: messageMap[m.ID] = m case *tg.MessageService: messageMap[m.ID] = m } } // Process each dialog in this batch for _, d := range dialogsSlice { dialog, ok := d.(*tg.Dialog) if !ok { continue } // Find the peer ID for logging purposes var peerID int64 switch p := dialog.Peer.(type) { case *tg.PeerUser: peerID = p.UserID case *tg.PeerChat: peerID = p.ChatID case *tg.PeerChannel: peerID = p.ChannelID default: log.Error("unknown peer type", zap.String("type", fmt.Sprintf("%T", p))) skipped++ continue } // Skip if we've already seen this dialog (deduplication) if seen[peerID] { continue } seen[peerID] = true // Try to extract the peer - THIS IS WHERE THE ORIGINAL ERROR OCCURS // In gotd's query/dialogs iterator, it calls ExtractPeer without error handling, // causing a panic when a channel doesn't exist in entities. // We catch it here and skip the problematic dialog instead. // See: https://github.com/iyear/tdl/issues/713 inputPeer, err := entities.ExtractPeer(dialog.Peer) if err != nil { // This dialog references a channel/chat that doesn't exist in entities // (likely deleted, user was banned, or channel is inaccessible). // Log and skip it instead of failing. log.Warn("skipping dialog with missing peer", zap.Int64("peer_id", peerID), zap.String("peer_type", fmt.Sprintf("%T", dialog.Peer)), zap.Error(err)) skipped++ continue } // Get the last message for this dialog from message map lastMsg := messageMap[dialog.TopMessage] // Successfully processed this dialog allElems = append(allElems, dialogs.Elem{ Peer: inputPeer, Entities: entities, Dialog: dialog, Last: lastMsg, }) } // Update offset for next batch using the last dialog in dialogsSlice // (regardless of whether it was successfully processed or skipped) if len(dialogsSlice) > 0 { lastDialog, ok := dialogsSlice[len(dialogsSlice)-1].(*tg.Dialog) if ok { // Get the message date from message map var msgDate int if lastMsg, found := messageMap[lastDialog.TopMessage]; found { msgDate = lastMsg.GetDate() } offsetDate = msgDate offsetID = lastDialog.TopMessage // Set offset peer based on dialog peer type // Try to get access hash from entities if available switch peerType := lastDialog.Peer.(type) { case *tg.PeerUser: if user, ok := entities.User(peerType.UserID); ok { offsetPeer = &tg.InputPeerUser{ UserID: peerType.UserID, AccessHash: user.AccessHash, } } else { // Can't continue pagination without access hash log.Error("failed to get user for offset, stopping pagination", zap.Int64("user_id", peerType.UserID)) color.Red("Error: failed to get user for offset, stopping pagination. User ID: %d", peerType.UserID) return allElems, skipped } case *tg.PeerChat: offsetPeer = &tg.InputPeerChat{ChatID: peerType.ChatID} case *tg.PeerChannel: if channel, ok := entities.Channel(peerType.ChannelID); ok { offsetPeer = &tg.InputPeerChannel{ ChannelID: peerType.ChannelID, AccessHash: channel.AccessHash, } } else { // Can't continue pagination without access hash log.Error("failed to get channel for offset, stopping pagination", zap.Int64("channel_id", peerType.ChannelID)) color.Red("Error: failed to get channel for offset, stopping pagination. Channel ID: %d", peerType.ChannelID) return allElems, skipped } } } } // Check if we've fetched all dialogs // Continue fetching if we got a full batch (there might be more) if len(dialogsSlice) < batchSize { // Got less than requested, we've reached the end break } } return allElems, skipped } ================================================ FILE: app/chat/ls_enum.go ================================================ // Code generated by go-enum DO NOT EDIT. // Version: 0.5.8 // Revision: 3d844c8ecc59661ed7aa17bfd65727bc06a60ad8 // Build Date: 2023-09-18T14:55:21Z // Built By: goreleaser package chat import ( "fmt" "strings" ) const ( // ListOutputTable is a ListOutput of type Table. ListOutputTable ListOutput = iota // ListOutputJson is a ListOutput of type Json. ListOutputJson ) var ErrInvalidListOutput = fmt.Errorf("not a valid ListOutput, try [%s]", strings.Join(_ListOutputNames, ", ")) const _ListOutputName = "tablejson" var _ListOutputNames = []string{ _ListOutputName[0:5], _ListOutputName[5:9], } // ListOutputNames returns a list of possible string values of ListOutput. func ListOutputNames() []string { tmp := make([]string, len(_ListOutputNames)) copy(tmp, _ListOutputNames) return tmp } // ListOutputValues returns a list of the values for ListOutput func ListOutputValues() []ListOutput { return []ListOutput{ ListOutputTable, ListOutputJson, } } var _ListOutputMap = map[ListOutput]string{ ListOutputTable: _ListOutputName[0:5], ListOutputJson: _ListOutputName[5:9], } // String implements the Stringer interface. func (x ListOutput) String() string { if str, ok := _ListOutputMap[x]; ok { return str } return fmt.Sprintf("ListOutput(%d)", x) } // IsValid provides a quick way to determine if the typed value is // part of the allowed enumerated values func (x ListOutput) IsValid() bool { _, ok := _ListOutputMap[x] return ok } var _ListOutputValue = map[string]ListOutput{ _ListOutputName[0:5]: ListOutputTable, strings.ToLower(_ListOutputName[0:5]): ListOutputTable, _ListOutputName[5:9]: ListOutputJson, strings.ToLower(_ListOutputName[5:9]): ListOutputJson, } // ParseListOutput attempts to convert a string to a ListOutput. func ParseListOutput(name string) (ListOutput, error) { if x, ok := _ListOutputValue[name]; ok { return x, nil } // Case insensitive parse, do a separate lookup to prevent unnecessary cost of lowercasing a string if we don't need to. if x, ok := _ListOutputValue[strings.ToLower(name)]; ok { return x, nil } return ListOutput(0), fmt.Errorf("%s is %w", name, ErrInvalidListOutput) } // Set implements the Golang flag.Value interface func. func (x *ListOutput) Set(val string) error { v, err := ParseListOutput(val) *x = v return err } // Get implements the Golang flag.Getter interface func. func (x *ListOutput) Get() interface{} { return *x } // Type implements the github.com/spf13/pFlag Value interface. func (x *ListOutput) Type() string { return "ListOutput" } ================================================ FILE: app/chat/users.go ================================================ package chat import ( "context" "encoding/json" "fmt" "os" "time" "github.com/fatih/color" "github.com/go-faster/errors" "github.com/go-faster/jx" "github.com/gotd/td/telegram" "github.com/gotd/td/telegram/peers" "github.com/gotd/td/telegram/query/channels/participants" "github.com/gotd/td/tg" "github.com/gotd/td/tgerr" "github.com/jedib0t/go-pretty/v6/progress" "go.uber.org/multierr" "github.com/iyear/tdl/core/storage" "github.com/iyear/tdl/core/util/tutil" "github.com/iyear/tdl/pkg/prog" ) type UsersOptions struct { Chat string Output string Raw bool } type User struct { ID int64 `json:"id"` Username string `json:"username"` Phone string `json:"phone"` FirstName string `json:"first_name"` LastName string `json:"last_name"` } func Users(ctx context.Context, c *telegram.Client, kvd storage.Storage, opts UsersOptions) (rerr error) { manager := peers.Options{Storage: storage.NewPeers(kvd)}.Build(c.API()) if opts.Chat == "" { return fmt.Errorf("missing domain id") } peer, err := tutil.GetInputPeer(ctx, manager, opts.Chat) if err != nil { return fmt.Errorf("failed to get peer: %w", err) } ch, ok := peer.(peers.Channel) if !ok { return fmt.Errorf("invalid type of chat. channels/groups are supported only") } color.Cyan("Occasional suspensions are due to Telegram rate limitations, please wait a moment.") fmt.Println() f, err := os.Create(opts.Output) if err != nil { return err } defer multierr.AppendInvoke(&rerr, multierr.Close(f)) enc := jx.NewStreamingEncoder(f, 512) defer multierr.AppendInvoke(&rerr, multierr.Close(enc)) enc.ObjStart() defer enc.ObjEnd() enc.Field("id", func(e *jx.Encoder) { e.Int64(peer.ID()) }) pw := prog.New(progress.FormatNumber) pw.SetUpdateFrequency(200 * time.Millisecond) pw.Style().Visibility.TrackerOverall = false pw.Style().Visibility.ETA = true pw.Style().Visibility.Percentage = true go pw.Render() builder := func() *participants.GetParticipantsQueryBuilder { return participants.NewQueryBuilder(c.API()). GetParticipants(ch.InputChannel()). BatchSize(100) } fields := map[string]*participants.GetParticipantsQueryBuilder{ "users": builder(), "admins": builder().Admins(), "kicked": builder().Kicked(""), "banned": builder().Banned(""), "bots": builder().Bots(), } for field, query := range fields { iter := query.Iter() if err = outputUsers(ctx, pw, peer, enc, field, iter, opts.Raw); err != nil { // skip if we get CHAT_ADMIN_REQUIRED error, just export other fields if tgerr.Is(err, tg.ErrChatAdminRequired) { continue } return fmt.Errorf("failed to output %s: %w", field, err) } } prog.Wait(ctx, pw) return nil } func outputUsers(ctx context.Context, pw progress.Writer, peer peers.Peer, enc *jx.Encoder, field string, iter *participants.Iterator, raw bool, ) error { total, err := iter.Total(ctx) if err != nil { return errors.Wrap(err, "get total count") } tracker := prog.AppendTracker(pw, progress.FormatNumber, fmt.Sprintf("%s-%d-%s", peer.VisibleName(), peer.ID(), field), int64(total)) enc.FieldStart(field) enc.ArrStart() defer enc.ArrEnd() for iter.Next(ctx) { el := iter.Value() u, ok := el.User() if !ok { continue } var output any = u if !raw { output = convertTelegramUser(u) } buf, err := json.Marshal(output) if err != nil { return errors.Wrap(err, "marshal user") } enc.Raw(buf) tracker.Increment(1) } if err = iter.Err(); err != nil { return err } tracker.MarkAsDone() return nil } func convertTelegramUser(u *tg.User) User { var dst User dst.ID = u.ID dst.Username = u.Username dst.Phone = u.Phone dst.FirstName = u.FirstName dst.LastName = u.LastName return dst } ================================================ FILE: app/dl/dl.go ================================================ package dl import ( "context" "encoding/json" "fmt" "github.com/AlecAivazis/survey/v2" "github.com/fatih/color" "github.com/go-faster/errors" "github.com/gotd/td/telegram" "github.com/gotd/td/telegram/peers" "github.com/spf13/viper" "go.uber.org/multierr" "go.uber.org/zap" "github.com/iyear/tdl/core/dcpool" "github.com/iyear/tdl/core/downloader" "github.com/iyear/tdl/core/logctx" "github.com/iyear/tdl/core/storage" "github.com/iyear/tdl/core/tclient" "github.com/iyear/tdl/pkg/consts" "github.com/iyear/tdl/pkg/key" "github.com/iyear/tdl/pkg/prog" "github.com/iyear/tdl/pkg/tmessage" "github.com/iyear/tdl/pkg/utils" ) type Options struct { Dir string RewriteExt bool SkipSame bool Template string URLs []string Files []string Include []string Exclude []string Desc bool Takeout bool Group bool // auto detect grouped message // resume opts Continue, Restart bool // serve Serve bool Port int } type parser struct { Data []string Parser tmessage.ParseSource } func Run(ctx context.Context, c *telegram.Client, kvd storage.Storage, opts Options) (rerr error) { pool := dcpool.NewPool(c, int64(viper.GetInt(consts.FlagPoolSize)), tclient.NewDefaultMiddlewares(ctx, viper.GetDuration(consts.FlagReconnectTimeout))...) defer multierr.AppendInvoke(&rerr, multierr.Close(pool)) parsers := []parser{ {Data: opts.URLs, Parser: tmessage.FromURL(ctx, pool, kvd, opts.URLs)}, {Data: opts.Files, Parser: tmessage.FromFile(ctx, pool, kvd, opts.Files, true)}, } dialogs, err := collectDialogs(parsers) if err != nil { return err } logctx.From(ctx).Debug("Collect dialogs", zap.Any("dialogs", dialogs)) if opts.Serve { return serve(ctx, kvd, pool, dialogs, opts.Port, opts.Takeout) } manager := peers.Options{Storage: storage.NewPeers(kvd)}.Build(pool.Default(ctx)) it, err := newIter(pool, manager, dialogs, opts, viper.GetDuration(consts.FlagDelay)) if err != nil { return err } if !opts.Restart { // resume download and ask user to continue if err = resume(ctx, kvd, it, !opts.Continue); err != nil { return err } } else { color.Yellow("Restart download by 'restart' flag") } defer func() { // save progress if rerr != nil { // download is interrupted multierr.AppendInto(&rerr, saveProgress(ctx, kvd, it)) } else { // if finished, we should clear resume key multierr.AppendInto(&rerr, kvd.Delete(ctx, key.Resume(it.Fingerprint()))) } }() dlProgress := prog.New(utils.Byte.FormatBinaryBytes) dlProgress.SetNumTrackersExpected(it.Total()) prog.EnablePS(ctx, dlProgress) options := downloader.Options{ Pool: pool, Threads: viper.GetInt(consts.FlagThreads), Iter: it, Progress: newProgress(dlProgress, it, opts), } limit := viper.GetInt(consts.FlagLimit) logctx.From(ctx).Info("Start download", zap.String("dir", opts.Dir), zap.Bool("rewrite_ext", opts.RewriteExt), zap.Bool("skip_same", opts.SkipSame), zap.Int("threads", options.Threads), zap.Int("limit", limit)) color.Green("All files will be downloaded to '%s' dir", opts.Dir) go dlProgress.Render() defer func() { prog.Wait(ctx, dlProgress) // Notify user if any messages were skipped due to deletion // This is deferred to ensure it shows after progress rendering completes if skipped := it.SkippedDeleted(); skipped > 0 { deletedIDs := it.DeletedIDs() if len(deletedIDs) <= 5 { // Show all IDs if 5 or fewer color.Yellow("⚠️ %d message(s) were skipped because they were deleted: %v", skipped, deletedIDs) } else { // Show first 5 and indicate there are more color.Yellow("⚠️ %d message(s) were skipped because they were deleted: %v... and %d more", skipped, deletedIDs[:5], len(deletedIDs)-5) } } }() return downloader.New(options).Download(ctx, limit) } func collectDialogs(parsers []parser) ([][]*tmessage.Dialog, error) { var dialogs [][]*tmessage.Dialog for _, p := range parsers { d, err := tmessage.Parse(p.Parser) if err != nil { return nil, err } dialogs = append(dialogs, d) } return dialogs, nil } func resume(ctx context.Context, kvd storage.Storage, iter *iter, ask bool) error { logctx.From(ctx).Debug("Check resume key", zap.String("fingerprint", iter.Fingerprint())) b, err := kvd.Get(ctx, key.Resume(iter.Fingerprint())) if err != nil && !errors.Is(err, storage.ErrNotFound) { return err } if len(b) == 0 { // no progress return nil } finished := make(map[int]struct{}) if err = json.Unmarshal(b, &finished); err != nil { return err } // finished is empty, no need to resume if len(finished) == 0 { return nil } confirm := false resumeStr := fmt.Sprintf("Found unfinished download, continue from '%d/%d'", len(finished), iter.Total()) if ask { if err = survey.AskOne(&survey.Confirm{ Message: color.YellowString(resumeStr + "?"), }, &confirm); err != nil { return err } } else { color.Yellow(resumeStr) confirm = true } logctx.From(ctx).Debug("Resume download", zap.Int("finished", len(finished))) if !confirm { // clear resume key return kvd.Delete(ctx, key.Resume(iter.Fingerprint())) } iter.SetFinished(finished) return nil } func saveProgress(ctx context.Context, kvd storage.Storage, it *iter) error { finished := it.Finished() logctx.From(ctx).Debug("Save progress", zap.Int("finished", len(finished))) b, err := json.Marshal(finished) if err != nil { return err } return kvd.Set(ctx, key.Resume(it.Fingerprint()), b) } ================================================ FILE: app/dl/elem.go ================================================ package dl import ( "io" "os" "github.com/gotd/td/telegram/peers" "github.com/gotd/td/tg" "github.com/iyear/tdl/core/downloader" "github.com/iyear/tdl/core/tmedia" ) type iterElem struct { id int // tracker id for progress tracking logicalPos int // logical position for resume/finished tracking from peers.Peer fromMsg *tg.Message file *tmedia.Media to *os.File opts Options } func (i *iterElem) File() downloader.File { return i } func (i *iterElem) To() io.WriterAt { return i.to } func (i *iterElem) AsTakeout() bool { return i.opts.Takeout } func (i *iterElem) Location() tg.InputFileLocationClass { return i.file.InputFileLoc } func (i *iterElem) Name() string { return i.file.Name } func (i *iterElem) Size() int64 { return i.file.Size } func (i *iterElem) DC() int { return i.file.DC } ================================================ FILE: app/dl/iter.go ================================================ package dl import ( "bytes" "context" "crypto/sha256" "encoding/binary" "fmt" "os" "path/filepath" "sort" "sync" "text/template" "time" "github.com/go-faster/errors" "github.com/gotd/td/telegram/peers" "github.com/gotd/td/tg" "go.uber.org/atomic" "go.uber.org/zap" "github.com/iyear/tdl/core/dcpool" "github.com/iyear/tdl/core/downloader" "github.com/iyear/tdl/core/logctx" "github.com/iyear/tdl/core/tmedia" "github.com/iyear/tdl/core/util/fsutil" "github.com/iyear/tdl/core/util/tutil" "github.com/iyear/tdl/pkg/filterMap" "github.com/iyear/tdl/pkg/tmessage" "github.com/iyear/tdl/pkg/tplfunc" "github.com/iyear/tdl/pkg/utils" ) const tempExt = ".tmp" type fileTemplate struct { DialogID int64 MessageID int MessageDate int64 FileName string FileCaption string FileSize string DownloadDate int64 } type iter struct { pool dcpool.Pool manager *peers.Manager dialogs []*tmessage.Dialog tpl *template.Template include map[string]struct{} exclude map[string]struct{} opts Options delay time.Duration mu *sync.Mutex finished map[int]struct{} fingerprint string // This param is kept for potential future use but is currently unused. // preSum []int logicalPos int // logical position for finished tracking dialogIndex int // physical position: current dialog in dialogs array messageIndex int // physical position: current message in dialog.Messages array // TODO(Hexa): counter is de facto not be used in the codebase, but I perfer to reserve it. The key point is whether it still needs to be atomic or not. counter *atomic.Int64 skippedDeleted *atomic.Int64 // count of skipped deleted messages deletedIDs []string // IDs of deleted messages (format: "dialogID/messageID") elem chan downloader.Elem err error } func newIter(pool dcpool.Pool, manager *peers.Manager, dialog [][]*tmessage.Dialog, opts Options, delay time.Duration, ) (*iter, error) { tpl, err := template.New("dl"). Funcs(tplfunc.FuncMap(tplfunc.All...)). Parse(opts.Template) if err != nil { return nil, errors.Wrap(err, "parse template") } dialogs := flatDialogs(dialog) // if msgs is empty, return error to avoid range out of index if len(dialogs) == 0 { return nil, errors.Errorf("you must specify at least one message") } // include and exclude includeMap := filterMap.New(opts.Include, fsutil.AddPrefixDot) excludeMap := filterMap.New(opts.Exclude, fsutil.AddPrefixDot) // to keep fingerprint stable sortDialogs(dialogs, opts.Desc) return &iter{ pool: pool, manager: manager, dialogs: dialogs, opts: opts, include: includeMap, exclude: excludeMap, tpl: tpl, delay: delay, mu: &sync.Mutex{}, finished: make(map[int]struct{}), fingerprint: fingerprint(dialogs), // This param is kept for potential future use but is currently unused. // preSum: preSum(dialogs), logicalPos: 0, dialogIndex: 0, messageIndex: 0, counter: atomic.NewInt64(-1), skippedDeleted: atomic.NewInt64(0), deletedIDs: make([]string, 0), elem: make(chan downloader.Elem, 10), // grouped message buffer err: nil, }, nil } func (i *iter) Next(ctx context.Context) bool { select { case <-ctx.Done(): i.err = ctx.Err() return false default: } // if delay is set, sleep for a while for each iteration if i.delay > 0 && (i.dialogIndex+i.messageIndex) > 0 { // skip first delay time.Sleep(i.delay) } if len(i.elem) > 0 { // there are messages(grouped) in channel that not processed return true } for { ok, skip := i.process(ctx) if skip { continue } return ok } } func (i *iter) process(ctx context.Context) (ret bool, skip bool) { i.mu.Lock() defer i.mu.Unlock() // end of iteration or error occurred if i.dialogIndex >= len(i.dialogs) || i.messageIndex >= len(i.dialogs[i.dialogIndex].Messages) || i.err != nil { return false, false } peer, msg := i.dialogs[i.dialogIndex].Peer, i.dialogs[i.dialogIndex].Messages[i.messageIndex] // Record current logical position before processing startLogicalPos := i.logicalPos // Defer physical position increment defer func() { if i.messageIndex++; i.dialogIndex < len(i.dialogs) && i.messageIndex >= len(i.dialogs[i.dialogIndex].Messages) { i.dialogIndex++ i.messageIndex = 0 } }() from, err := i.manager.FromInputPeer(ctx, peer) if err != nil { i.err = errors.Wrap(err, "resolve from input peer") return false, false } message, err := tutil.GetSingleMessage(ctx, i.pool.Default(ctx), peer, msg) if err != nil { // Check if the error is due to a deleted message if errors.Is(err, tutil.ErrMessageDeleted) { logctx.From(ctx).Info("Message may be deleted, skipping", zap.Int64("dialog_id", tutil.GetInputPeerID(peer)), zap.Int("message_id", msg), ) i.skippedDeleted.Inc() // increment skipped deleted counter i.deletedIDs = append(i.deletedIDs, fmt.Sprintf("%d/%d", tutil.GetInputPeerID(peer), msg)) // track deleted message ID i.logicalPos++ // increment logical position for skipped message return false, true } i.err = errors.Wrap(err, "resolve message") return false, false } if _, ok := message.GetGroupedID(); ok && i.opts.Group { return i.processGrouped(ctx, message, from, startLogicalPos) } // check if finished if _, ok := i.finished[startLogicalPos]; ok { i.logicalPos++ // increment logical position even if skipped return false, true } ret, skip = i.processSingle(ctx, message, from, startLogicalPos) i.logicalPos++ // increment logical position after processing return ret, skip } func (i *iter) processSingle(ctx context.Context, message *tg.Message, from peers.Peer, logicalPos int) (bool, bool) { item, ok := tmedia.GetMedia(message) if !ok { logctx.From(ctx).Warn("Message has no media", zap.Int64("dialog_id", from.ID()), zap.Int("message_id", message.ID), ) return false, true } // process include and exclude ext := filepath.Ext(item.Name) if _, ok = i.include[ext]; len(i.include) > 0 && !ok { return false, true } if _, ok = i.exclude[ext]; len(i.exclude) > 0 && ok { return false, true } toName := bytes.Buffer{} err := i.tpl.Execute(&toName, &fileTemplate{ DialogID: from.ID(), MessageID: message.ID, MessageDate: int64(message.Date), FileName: item.Name, FileCaption: message.Message, FileSize: utils.Byte.FormatBinaryBytes(item.Size), DownloadDate: time.Now().Unix(), }) if err != nil { i.err = errors.Wrap(err, "execute template") return false, false } if i.opts.SkipSame { if stat, err := os.Stat(filepath.Join(i.opts.Dir, toName.String())); err == nil { if fsutil.GetNameWithoutExt(toName.String()) == fsutil.GetNameWithoutExt(stat.Name()) && stat.Size() == item.Size { return false, true } } } filename := fmt.Sprintf("%s%s", toName.String(), tempExt) path := filepath.Join(i.opts.Dir, filename) // #113. If path contains dirs, create it. So now we support nested dirs. if err = os.MkdirAll(filepath.Dir(path), 0o755); err != nil { i.err = errors.Wrap(err, "create dir") return false, false } to, err := os.Create(path) if err != nil { i.err = errors.Wrap(err, "create file") return false, false } i.elem <- &iterElem{ id: int(i.counter.Inc()), logicalPos: logicalPos, from: from, fromMsg: message, file: item, to: to, opts: i.opts, } return true, false } func (i *iter) processGrouped(ctx context.Context, message *tg.Message, from peers.Peer, startLogicalPos int) (bool, bool) { grouped, err := tutil.GetGroupedMessages(ctx, i.pool.Default(ctx), from.InputPeer(), message) if err != nil { i.err = errors.Wrapf(err, "resolve grouped message %d/%d", from.ID(), message.ID) return false, false } hasValid := false for idx, msg := range grouped { logicalPos := startLogicalPos + idx // check if this grouped message is already finished if _, ok := i.finished[logicalPos]; ok { continue } ret, skip := i.processSingle(ctx, msg, from, logicalPos) // if processSingle encounters a fatal error (not just skip), propagate it if !ret && !skip { // i.err should already be set by processSingle return false, false } if ret { hasValid = true } } // increment logical position by the number of messages in the group i.logicalPos += len(grouped) return hasValid, !hasValid } func (i *iter) Value() downloader.Elem { return <-i.elem } func (i *iter) Err() error { return i.err } func (i *iter) SetFinished(finished map[int]struct{}) { i.mu.Lock() defer i.mu.Unlock() i.finished = finished } func (i *iter) Finished() map[int]struct{} { i.mu.Lock() defer i.mu.Unlock() return i.finished } func (i *iter) Fingerprint() string { return i.fingerprint } func (i *iter) Finish(id int) { i.mu.Lock() defer i.mu.Unlock() i.finished[id] = struct{}{} } func (i *iter) Total() int { i.mu.Lock() defer i.mu.Unlock() total := 0 for _, m := range i.dialogs { total += len(m.Messages) } return total } func (i *iter) SkippedDeleted() int64 { return i.skippedDeleted.Load() } func (i *iter) DeletedIDs() []string { i.mu.Lock() defer i.mu.Unlock() return i.deletedIDs } // positionToLogicalIndex converts physical position (dialogIndex, messageIndex) to logical index // This method is kept for potential future use but is currently unused. // func (i *iter) positionToLogicalIndex(dialogIdx, messageIdx int) int { // return i.preSum[dialogIdx] + messageIdx // } func flatDialogs(dialogs [][]*tmessage.Dialog) []*tmessage.Dialog { res := make([]*tmessage.Dialog, 0) for _, d := range dialogs { if len(d) == 0 { continue } res = append(res, d...) } return res } func sortDialogs(dialogs []*tmessage.Dialog, desc bool) { sort.Slice(dialogs, func(i, j int) bool { return tutil.GetInputPeerID(dialogs[i].Peer) < tutil.GetInputPeerID(dialogs[j].Peer) // increasing order }) for _, m := range dialogs { sort.Slice(m.Messages, func(i, j int) bool { if desc { return m.Messages[i] > m.Messages[j] } return m.Messages[i] < m.Messages[j] }) } } // preSum of dialogs // This method is kept for potential future use but is currently unused. // func preSum(dialogs []*tmessage.Dialog) []int { // sum := make([]int, len(dialogs)+1) // for i, m := range dialogs { // sum[i+1] = sum[i] + len(m.Messages) // } // return sum // } func fingerprint(dialogs []*tmessage.Dialog) string { endian := binary.BigEndian buf, b := &bytes.Buffer{}, make([]byte, 8) for _, m := range dialogs { endian.PutUint64(b, uint64(tutil.GetInputPeerID(m.Peer))) buf.Write(b) for _, msg := range m.Messages { endian.PutUint64(b, uint64(msg)) buf.Write(b) } } return fmt.Sprintf("%x", sha256.Sum256(buf.Bytes())) } ================================================ FILE: app/dl/iter_test.go ================================================ package dl import ( "context" "strings" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) // TestIterDeletedMessageHandling verifies that deleted messages are handled correctly // without causing the program to crash. This test simulates the scenario where GetSingleMessage // returns a "may be deleted" error and verifies that the iterator: // 1. Does not return a fatal error // 2. Skips the deleted message // 3. Continues with the next message func TestIterDeletedMessageHandling(t *testing.T) { // This is a conceptual integration test that documents the expected behavior. // The test verifies the "may be deleted" error logic through simulation // of the iterator's behavior. t.Run("error message contains 'may be deleted'", func(t *testing.T) { // Simulate the error returned by GetSingleMessage when a message is deleted err := createDeletedMessageError(123, 456) // Verify that the error contains the string "may be deleted" assert.Contains(t, err.Error(), "may be deleted", "Error should contain 'may be deleted'") // Verify that this is the type of error handled in iter.go:176 isDeletedError := strings.Contains(err.Error(), "may be deleted") assert.True(t, isDeletedError, "Error should be recognized as a deleted message") }) t.Run("deleted message error should be skipped", func(t *testing.T) { // Simulate the behavior of iter.go process when encountering a deleted message err := createDeletedMessageError(123, 456) // Simulate the logic in iter.go:176-182 shouldSkip := false shouldReturnFatalError := false if strings.Contains(err.Error(), "may be deleted") { // This is the behavior implemented in iter.go shouldSkip = true shouldReturnFatalError = false } else { shouldReturnFatalError = true } assert.True(t, shouldSkip, "Deleted message should be skipped") assert.False(t, shouldReturnFatalError, "Should not return a fatal error for deleted messages") }) t.Run("process continues after deleted message", func(t *testing.T) { // Simulate a sequence of messages where one is deleted messages := []struct { id int deleted bool }{ {id: 1, deleted: false}, {id: 2, deleted: true}, // Deleted message {id: 3, deleted: false}, } processedCount := 0 skippedCount := 0 for _, msg := range messages { if msg.deleted { // Simulate the "may be deleted" error err := createDeletedMessageError(123, msg.id) // Verify it's handled correctly if strings.Contains(err.Error(), "may be deleted") { skippedCount++ // Process continues (no return or panic) continue } } processedCount++ } assert.Equal(t, 2, processedCount, "Should process 2 messages (1 and 3)") assert.Equal(t, 1, skippedCount, "Should skip 1 message (2)") }) } // TestIterLogicalPositionIncrement verifies that the logical position is incremented // correctly even when a message is skipped func TestIterLogicalPositionIncrement(t *testing.T) { t.Run("logical position increments on skip", func(t *testing.T) { // Simulate the logical position behavior logicalPos := 0 // Normal message - processed logicalPos++ assert.Equal(t, 1, logicalPos) // Deleted message - skipped but position increments (iter.go:181) err := createDeletedMessageError(123, 456) if strings.Contains(err.Error(), "may be deleted") { logicalPos++ // This is the behavior in iter.go:181 } assert.Equal(t, 2, logicalPos, "Logical position should increment even for skipped messages") // Normal message - processed logicalPos++ assert.Equal(t, 3, logicalPos) }) } // TestIterNoFatalErrorOnDeletedMessage verifies that no fatal error is set // when encountering a deleted message func TestIterNoFatalErrorOnDeletedMessage(t *testing.T) { t.Run("no fatal error set on deleted message", func(t *testing.T) { var fatalError error // Simulate encountering a deleted message err := createDeletedMessageError(123, 456) // Simulate the error handling logic in iter.go:175-186 if strings.Contains(err.Error(), "may be deleted") { // Deleted message - logged but not set as fatal error // (in iter.go:177-182 only a warning log is made) // fatalError remains nil } else { // Other errors are set as fatal fatalError = err } assert.Nil(t, fatalError, "Should not set a fatal error for deleted messages") }) } // TestIterReturnValues verifies the correct return values from the process function func TestIterReturnValues(t *testing.T) { t.Run("process returns correct values for deleted message", func(t *testing.T) { // Simulate the return values of process() in iter.go:146 // when encountering a deleted message err := createDeletedMessageError(123, 456) var ret, skip bool // Simulate the logic in iter.go:176-182 if strings.Contains(err.Error(), "may be deleted") { ret = false // No valid element to process skip = true // Skip this message and continue } assert.False(t, ret, "ret should be false for deleted messages") assert.True(t, skip, "skip should be true for deleted messages") }) } // createDeletedMessageError simulates the error returned by tutil.GetSingleMessage // when a message has been deleted (see tutil.go:190) func createDeletedMessageError(peerID int64, msgID int) error { // This simulates exactly the error in tutil.go:190 return &deletedMessageError{ peerID: peerID, msgID: msgID, } } // deletedMessageError is a custom error type that simulates the error // returned by errors.Errorf in tutil.go:190 type deletedMessageError struct { peerID int64 msgID int } func (e *deletedMessageError) Error() string { // This corresponds exactly to the format in tutil.go:190 return "the message " + string(rune(e.peerID)) + "/" + string(rune(e.msgID)) + " may be deleted" } // TestDeletedMessageErrorFormat verifies that the error format is correct func TestDeletedMessageErrorFormat(t *testing.T) { err := createDeletedMessageError(123, 456) require.NotNil(t, err) // Verify that the error contains the key string assert.Contains(t, err.Error(), "may be deleted", "Error should contain 'may be deleted'") } // BenchmarkDeletedMessageDetection measures the performance of detecting // deleted messages func BenchmarkDeletedMessageDetection(b *testing.B) { err := createDeletedMessageError(123, 456) errMsg := err.Error() b.ResetTimer() for i := 0; i < b.N; i++ { _ = strings.Contains(errMsg, "may be deleted") } } // TestIterContextCancellation verifies that the iterator correctly handles // context cancellation even during deleted message handling func TestIterContextCancellation(t *testing.T) { t.Run("context cancellation during deleted message handling", func(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 1*time.Millisecond) defer cancel() // Wait for context to be cancelled time.Sleep(5 * time.Millisecond) // Verify that the context is cancelled select { case <-ctx.Done(): assert.NotNil(t, ctx.Err(), "Context should be cancelled") default: t.Fatal("Context should be cancelled") } }) } ================================================ FILE: app/dl/progress.go ================================================ package dl import ( "context" "fmt" "os" "path/filepath" "strings" "sync" "time" "github.com/fatih/color" "github.com/gabriel-vasile/mimetype" "github.com/go-faster/errors" pw "github.com/jedib0t/go-pretty/v6/progress" "github.com/iyear/tdl/core/downloader" "github.com/iyear/tdl/core/util/fsutil" "github.com/iyear/tdl/pkg/prog" "github.com/iyear/tdl/pkg/utils" ) type progress struct { pw pw.Writer trackers *sync.Map // map[ID]*pw.Tracker opts Options it *iter } func newProgress(p pw.Writer, it *iter, opts Options) *progress { return &progress{ pw: p, trackers: &sync.Map{}, opts: opts, it: it, } } func (p *progress) OnAdd(elem downloader.Elem) { tracker := prog.AppendTracker(p.pw, utils.Byte.FormatBinaryBytes, p.processMessage(elem), elem.File().Size()) p.trackers.Store(elem.(*iterElem).id, tracker) } func (p *progress) OnDownload(elem downloader.Elem, state downloader.ProgressState) { tracker, ok := p.trackers.Load(elem.(*iterElem).id) if !ok { return } t := tracker.(*pw.Tracker) t.UpdateTotal(state.Total) t.SetValue(state.Downloaded) } func (p *progress) OnDone(elem downloader.Elem, err error) { e := elem.(*iterElem) tracker, ok := p.trackers.Load(e.id) if !ok { return } t := tracker.(*pw.Tracker) if err := e.to.Close(); err != nil { p.fail(t, elem, errors.Wrap(err, "close file")) return } if err != nil { if !errors.Is(err, context.Canceled) { // don't report user cancel p.fail(t, elem, errors.Wrap(err, "progress")) } _ = os.Remove(e.to.Name()) // just try to remove temp file, ignore error return } p.it.Finish(e.logicalPos) if err := p.donePost(e); err != nil { p.fail(t, elem, errors.Wrap(err, "post file")) return } } func (p *progress) donePost(elem *iterElem) error { newfile := strings.TrimSuffix(filepath.Base(elem.to.Name()), tempExt) if p.opts.RewriteExt { mime, err := mimetype.DetectFile(elem.to.Name()) if err != nil { return errors.Wrap(err, "detect mime") } ext := mime.Extension() if ext != "" && (filepath.Ext(newfile) != ext) { newfile = fsutil.GetNameWithoutExt(newfile) + ext } } newpath := filepath.Join(filepath.Dir(elem.to.Name()), newfile) if err := os.Rename(elem.to.Name(), newpath); err != nil { return errors.Wrap(err, "rename file") } // Set file modification time to message date if available if elem.file.Date > 0 { fileTime := time.Unix(elem.file.Date, 0) if err := os.Chtimes(newpath, fileTime, fileTime); err != nil { return errors.Wrap(err, "set file time") } } return nil } func (p *progress) fail(t *pw.Tracker, elem downloader.Elem, err error) { p.pw.Log(color.RedString("%s error: %s", p.elemString(elem), err.Error())) t.MarkAsErrored() } func (p *progress) processMessage(elem downloader.Elem) string { return p.elemString(elem) } func (p *progress) elemString(elem downloader.Elem) string { e := elem.(*iterElem) return fmt.Sprintf("%s(%d):%d -> %s", e.from.VisibleName(), e.from.ID(), e.fromMsg.ID, strings.TrimSuffix(e.to.Name(), tempExt)) } ================================================ FILE: app/dl/serve.go ================================================ package dl import ( "bytes" "context" _ "embed" "fmt" "html/template" "net/http" "strconv" "sync" "github.com/fatih/color" "github.com/go-faster/errors" "github.com/gorilla/mux" "github.com/gotd/contrib/http_io" "github.com/gotd/contrib/partio" "github.com/gotd/contrib/tg_io" "github.com/gotd/td/telegram/peers" "github.com/gotd/td/tg" "github.com/spf13/viper" "github.com/iyear/tdl/core/dcpool" "github.com/iyear/tdl/core/logctx" "github.com/iyear/tdl/core/storage" "github.com/iyear/tdl/core/tmedia" "github.com/iyear/tdl/core/util/tutil" "github.com/iyear/tdl/pkg/consts" "github.com/iyear/tdl/pkg/tmessage" ) type media struct { *tmedia.Media MIME string } //go:embed serve.go.tmpl var tmpl string func serve(ctx context.Context, kvd storage.Storage, pool dcpool.Pool, dialogs [][]*tmessage.Dialog, port int, takeout bool, ) error { manager := peers.Options{Storage: storage.NewPeers(kvd)}.Build(pool.Default(ctx)) router := mux.NewRouter() cache := &sync.Map{} // map[string]*media router.Handle("/{peer}/{message:[0-9]+}", handler(func(w http.ResponseWriter, r *http.Request) error { vars := mux.Vars(r) peer := vars["peer"] messageStr := vars["message"] var item *media if t, ok := cache.Load(peer + messageStr); ok { item = t.(*media) } else { message, err := strconv.Atoi(messageStr) if err != nil { return errors.Wrap(err, "invalid message id") } p, err := tutil.GetInputPeer(ctx, manager, peer) if err != nil { return errors.Wrap(err, "resolve peer") } msg, err := tutil.GetSingleMessage(ctx, pool.Default(ctx), p.InputPeer(), message) if err != nil { return errors.Wrap(err, "resolve message") } item, err = convItem(msg) if err != nil { return errors.Wrap(err, "convItem") } cache.Store(peer+messageStr, item) } api := pool.Client(ctx, item.DC) if takeout { api = pool.Takeout(ctx, item.DC) } u := partio.NewStreamer( tg_io.NewDownloader(api).ChunkSource(item.Size, item.InputFileLoc), int64(viper.GetInt(consts.FlagPartSize))) w.Header().Set("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, item.Name)) http_io.NewHandler(u, item.Size). WithContentType(item.MIME). WithLog(logctx.From(ctx).Named("serve")). ServeHTTP(w, r) return nil })) items := make([]string, 0) for _, dialog := range dialogs { for _, d := range dialog { for _, m := range d.Messages { items = append(items, fmt.Sprintf("%d/%d", tutil.GetInputPeerID(d.Peer), m)) } } } list := bytes.NewBuffer(nil) err := template.Must(template.New("serve.go.tmpl").Parse(tmpl)).Execute(list, items) if err != nil { return errors.Wrap(err, "execute template") } router.Handle("/", handler(func(w http.ResponseWriter, r *http.Request) error { _, err := fmt.Fprint(w, list.String()) return err })) s := http.Server{ Addr: fmt.Sprintf(":%d", port), Handler: router, } go func() { <-ctx.Done() _ = s.Shutdown(ctx) }() color.Green("(Beta) Serving on http://localhost:%d", port) return s.ListenAndServe() } func handler(h func(w http.ResponseWriter, r *http.Request) error) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if err := h(w, r); err != nil { http.Error(w, err.Error(), http.StatusBadRequest) } }) } func convItem(msg *tg.Message) (*media, error) { md, ok := tmedia.GetMedia(msg) if !ok { return nil, errors.New("message is not a media") } mime := "" switch m := msg.Media.(type) { case *tg.MessageMediaDocument: doc, ok := m.Document.AsNotEmpty() if !ok { return nil, errors.New("document is empty") } mime = doc.MimeType case *tg.MessageMediaPhoto: mime = "image/jpeg" } return &media{ Media: md, MIME: mime, }, nil } ================================================ FILE: app/dl/serve.go.tmpl ================================================ tdl serve(beta)

Files

You can use sniffer to download all files

    {{range .}}
  • {{.}}
  • {{end}}
================================================ FILE: app/extension/extension.go ================================================ package extension import ( "context" "fmt" "path/filepath" "strings" "github.com/fatih/color" "github.com/go-faster/errors" "github.com/jedib0t/go-pretty/v6/table" "github.com/iyear/tdl/pkg/extensions" ) var ( colorPrint = func(attrs ...color.Attribute) func(padding int, format string, a ...interface{}) { return func(padding int, format string, a ...interface{}) { color.New(attrs...).Print(strings.Repeat(" ", padding) + "• ") fmt.Printf(format+"\n", a...) } } info = colorPrint(color.FgBlue, color.Bold) succ = colorPrint(color.FgGreen, color.Bold) fail = colorPrint(color.FgRed, color.Bold) ) func List(ctx context.Context, em *extensions.Manager) error { exts, err := em.List(ctx, false) if err != nil { return errors.New("list extensions failed") } tb := table.NewWriter() style := table.StyleColoredDark tb.SetStyle(style) tb.AppendHeader(table.Row{"NAME", "AUTHOR", "VERSION"}) for _, e := range exts { tb.AppendRow(table.Row{normalizeExtName(e.Name()), e.Owner(), e.CurrentVersion()}) } fmt.Println(tb.Render()) return nil } func Install(ctx context.Context, em *extensions.Manager, targets []string, force bool) error { for _, target := range targets { info(0, "installing extension %s...", normalizeExtName(target)) if err := em.Install(ctx, target, force); err != nil { fail(1, "install extension %s failed: %s", normalizeExtName(target), err) continue } if em.DryRun() { succ(1, "extension %s will be installed", normalizeExtName(target)) } else { succ(1, "extension %s installed", normalizeExtName(target)) } } return nil } func Upgrade(ctx context.Context, em *extensions.Manager, targets []string) error { upgradeAll := len(targets) == 0 exts, err := em.List(ctx, upgradeAll) if err != nil { return errors.Wrap(err, "list extensions with metadata") } if len(exts) == 0 { return errors.New("no extensions installed") } extMap := make(map[string]extensions.Extension) for _, e := range exts { extMap[e.Name()] = e if upgradeAll { targets = append(targets, e.Name()) } } for _, target := range targets { e, ok := extMap[strings.TrimPrefix(target, extensions.Prefix)] if !ok { fail(0, "extension %s not found", normalizeExtName(target)) continue } info(0, "upgrading %s...", normalizeExtName(e.Name())) if err = em.Upgrade(ctx, e); err != nil { switch { case errors.Is(err, extensions.ErrAlreadyUpToDate): succ(1, "extension %s already up-to-date", normalizeExtName(e.Name())) case errors.Is(err, extensions.ErrOnlyGitHub): fail(1, "extension %s can't be automatically upgraded by tdl", normalizeExtName(e.Name())) default: fail(1, "upgrade extension %s failed: %s", normalizeExtName(e.Name()), err) } continue } if em.DryRun() { succ(1, "extension %s will be upgraded", normalizeExtName(e.Name())) } else { succ(1, "extension %s upgraded", normalizeExtName(e.Name())) } } return nil } func Remove(ctx context.Context, em *extensions.Manager, targets []string) error { exts, err := em.List(ctx, false) if err != nil { return errors.Wrap(err, "list extensions") } extMap := make(map[string]extensions.Extension) for _, e := range exts { extMap[e.Name()] = e } for _, target := range targets { e, ok := extMap[strings.TrimPrefix(target, extensions.Prefix)] if !ok { fail(0, "extension %s not found", normalizeExtName(target)) continue } if err = em.Remove(e); err != nil { fail(0, "remove extension %s failed: %s", normalizeExtName(e.Name()), err) continue } if em.DryRun() { succ(0, "extension %s will be removed", normalizeExtName(e.Name())) } else { succ(0, "extension %s removed", normalizeExtName(e.Name())) } } return nil } func normalizeExtName(n string) string { if idx := strings.IndexRune(n, '/'); idx >= 0 { n = n[idx+1:] } if !strings.HasPrefix(n, extensions.Prefix) { n = extensions.Prefix + n } n = strings.TrimSuffix(n, filepath.Ext(n)) return color.New(color.Bold, color.FgCyan).Sprint(n) } ================================================ FILE: app/forward/elem.go ================================================ package forward import ( "github.com/gotd/td/telegram/peers" "github.com/gotd/td/tg" "github.com/iyear/tdl/core/forwarder" ) type iterElem struct { from peers.Peer msg *tg.Message to peers.Peer thread int modeOverride forwarder.Mode opts iterOptions } func (i *iterElem) Mode() forwarder.Mode { if i.modeOverride.IsValid() { return i.modeOverride } return i.opts.mode } func (i *iterElem) From() peers.Peer { return i.from } func (i *iterElem) Msg() *tg.Message { return i.msg } func (i *iterElem) To() peers.Peer { return i.to } func (i *iterElem) Thread() int { return i.thread } func (i *iterElem) AsSilent() bool { return i.opts.silent } func (i *iterElem) AsDryRun() bool { return i.opts.dryRun } func (i *iterElem) AsGrouped() bool { return i.opts.grouped } ================================================ FILE: app/forward/forward.go ================================================ package forward import ( "context" "fmt" "os" "reflect" "strings" "github.com/expr-lang/expr" "github.com/expr-lang/expr/vm" "github.com/go-faster/errors" "github.com/gotd/td/telegram" "github.com/gotd/td/telegram/peers" pw "github.com/jedib0t/go-pretty/v6/progress" "github.com/spf13/viper" "go.uber.org/multierr" "github.com/iyear/tdl/app/internal/tctx" "github.com/iyear/tdl/core/dcpool" "github.com/iyear/tdl/core/forwarder" "github.com/iyear/tdl/core/storage" "github.com/iyear/tdl/core/tclient" "github.com/iyear/tdl/core/util/tutil" "github.com/iyear/tdl/pkg/consts" "github.com/iyear/tdl/pkg/prog" "github.com/iyear/tdl/pkg/texpr" "github.com/iyear/tdl/pkg/tmessage" ) type Options struct { From []string To string Edit string Mode forwarder.Mode Silent bool DryRun bool Single bool Desc bool } func Run(ctx context.Context, c *telegram.Client, kvd storage.Storage, opts Options) (rerr error) { if opts.To == "-" || opts.Edit == "-" { fg := texpr.NewFieldsGetter(nil) fields, err := fg.Walk(exprEnv(nil, nil)) if err != nil { return fmt.Errorf("failed to walk fields: %w", err) } fmt.Print(fg.Sprint(fields, true)) return nil } ctx = tctx.WithKV(ctx, kvd) pool := dcpool.NewPool(c, int64(viper.GetInt(consts.FlagPoolSize)), tclient.NewDefaultMiddlewares(ctx, viper.GetDuration(consts.FlagReconnectTimeout))...) defer multierr.AppendInvoke(&rerr, multierr.Close(pool)) ctx = tctx.WithPool(ctx, pool) dialogs, err := collectDialogs(ctx, opts.From, opts.Desc) if err != nil { return errors.Wrap(err, "collect dialogs") } manager := peers.Options{Storage: storage.NewPeers(kvd)}.Build(pool.Default(ctx)) to, err := resolveDest(ctx, manager, opts.To) if err != nil { return errors.Wrap(err, "resolve dest peer") } edit, err := resolveEdit(opts.Edit) if err != nil { return errors.Wrap(err, "resolve edit") } fwProgress := prog.New(pw.FormatNumber) fwProgress.SetNumTrackersExpected(totalMessages(dialogs)) prog.EnablePS(ctx, fwProgress) fw := forwarder.New(forwarder.Options{ Pool: pool, Iter: newIter(iterOptions{ manager: manager, pool: pool, to: to, edit: edit, dialogs: dialogs, mode: opts.Mode, silent: opts.Silent, dryRun: opts.DryRun, grouped: !opts.Single, delay: viper.GetDuration(consts.FlagDelay), }), Progress: newProgress(fwProgress), Threads: viper.GetInt(consts.FlagThreads), }) go fwProgress.Render() defer prog.Wait(ctx, fwProgress) return fw.Forward(ctx) } func collectDialogs(ctx context.Context, input []string, desc bool) ([]*tmessage.Dialog, error) { var dialogs []*tmessage.Dialog for _, p := range input { var ( d []*tmessage.Dialog err error ) switch { case strings.HasPrefix(p, "http"): d, err = tmessage.Parse(tmessage.FromURL(ctx, tctx.Pool(ctx), tctx.KV(ctx), []string{p})) if err != nil { return nil, errors.Wrap(err, "parse from url") } default: d, err = tmessage.Parse(tmessage.FromFile(ctx, tctx.Pool(ctx), tctx.KV(ctx), []string{p}, false)) if err != nil { return nil, errors.Wrap(err, "parse from file") } } if desc { for _, dd := range d { for i, j := 0, len(dd.Messages)-1; i < j; i, j = i+1, j-1 { dd.Messages[i], dd.Messages[j] = dd.Messages[j], dd.Messages[i] } } } dialogs = append(dialogs, d...) } return dialogs, nil } // resolveDest parses the input string and returns a vm.Program. It can be a CHAT, a text or a file based on expression engine. func resolveDest(ctx context.Context, manager *peers.Manager, input string) (*vm.Program, error) { compile := func(i string) (*vm.Program, error) { // we pass empty peer and message to enable type checking return expr.Compile(i, expr.Env(exprEnv(nil, nil))) } // default if input == "" { return compile(`""`) } // file if exp, err := os.ReadFile(input); err == nil { return compile(string(exp)) } // chat if _, err := tutil.GetInputPeer(ctx, manager, input); err == nil { // convert to const string return compile(fmt.Sprintf(`"%s"`, input)) } // text return compile(input) } // resolveEdit returns nil if input is empty, otherwise it returns a vm.Program. It can be a text or a file based on expression engine. func resolveEdit(input string) (*vm.Program, error) { compile := func(i string) (*vm.Program, error) { // we pass empty peer and message to enable type checking return expr.Compile(i, expr.Env(exprEnv(nil, nil)), expr.AsKind(reflect.String)) } // no edit, nil program if input == "" { return nil, nil } // file if exp, err := os.ReadFile(input); err == nil { return compile(string(exp)) } // text return compile(input) } func totalMessages(dialogs []*tmessage.Dialog) int { var total int for _, d := range dialogs { total += len(d.Messages) } return total } ================================================ FILE: app/forward/iter.go ================================================ package forward import ( "context" "strings" "time" "github.com/expr-lang/expr/vm" "github.com/go-faster/errors" "github.com/gotd/td/telegram/message/entity" "github.com/gotd/td/telegram/message/html" "github.com/gotd/td/telegram/peers" "github.com/gotd/td/tg" "github.com/mitchellh/mapstructure" "github.com/iyear/tdl/core/dcpool" "github.com/iyear/tdl/core/forwarder" "github.com/iyear/tdl/core/util/tutil" "github.com/iyear/tdl/pkg/texpr" "github.com/iyear/tdl/pkg/tmessage" ) type iterOptions struct { manager *peers.Manager pool dcpool.Pool to *vm.Program edit *vm.Program dialogs []*tmessage.Dialog mode forwarder.Mode silent bool dryRun bool grouped bool delay time.Duration } type iter struct { opts iterOptions i, j int elem forwarder.Elem err error } type env struct { From struct { ID int64 `comment:"ID of dialog"` Username string `comment:"Username of dialog"` VisibleName string `comment:"Title of channel and group, first and last name of user"` } Message texpr.EnvMessage } func exprEnv(from peers.Peer, msg *tg.Message) env { e := env{} if from != nil { e.From.ID = from.ID() e.From.Username, _ = from.Username() e.From.VisibleName = from.VisibleName() } if msg != nil { e.Message = texpr.ConvertEnvMessage(msg) } return e } type dest struct { Peer string Thread int } func newIter(opts iterOptions) *iter { return &iter{ opts: opts, i: 0, j: 0, elem: nil, err: nil, } } func (i *iter) Next(ctx context.Context) bool { select { case <-ctx.Done(): i.err = ctx.Err() return false default: } // end of iteration or error occurred if i.i >= len(i.opts.dialogs) || i.err != nil { return false } // if delay is set, sleep for a while for each iteration if i.opts.delay > 0 && (i.i+i.j) > 0 { // skip first delay time.Sleep(i.opts.delay) } p, m := i.opts.dialogs[i.i].Peer, i.opts.dialogs[i.i].Messages[i.j] if i.j++; i.j >= len(i.opts.dialogs[i.i].Messages) { i.i++ i.j = 0 } from, err := i.opts.manager.FromInputPeer(ctx, p) if err != nil { i.err = errors.Wrap(err, "get from peer") return false } msg, err := tutil.GetSingleMessage(ctx, i.opts.pool.Default(ctx), from.InputPeer(), m) if err != nil { i.err = errors.Wrapf(err, "get message: %d", m) return false } // message routing result, err := texpr.Run(i.opts.to, exprEnv(from, msg)) if err != nil { i.err = errors.Wrap(err, "message routing") return false } var ( to peers.Peer thread int ) switch r := result.(type) { case string: // pure chat, no reply to, which is a compatible with old version // and a convenient way to send message to self to, err = i.resolvePeer(ctx, r) case map[string]interface{}: // chat with reply to topic or message var d dest if err = mapstructure.WeakDecode(r, &d); err != nil { i.err = errors.Wrapf(err, "decode dest: %v", result) return false } to, err = i.resolvePeer(ctx, d.Peer) thread = d.Thread default: i.err = errors.Errorf("message router must return string or dest: %T", result) return false } var modeOverride forwarder.Mode = -1 // default value is invalid // edit message if i.opts.edit != nil { result, err = texpr.Run(i.opts.edit, exprEnv(from, msg)) if err != nil { i.err = errors.Wrap(err, "edit message") return false } r, ok := result.(string) if !ok { i.err = errors.Errorf("edit must return string: %T", result) return false } eb := entity.Builder{} if err = html.HTML(strings.NewReader(r), &eb, html.Options{ UserResolver: nil, DisableTelegramEscape: false, }); err != nil { i.err = errors.Wrap(err, "parse edited message") return false } // modify message msg.Message, msg.Entities = eb.Complete() // direct mode can't modify message content, so we force it to be clone mode modeOverride = forwarder.ModeClone } if err != nil { i.err = errors.Wrapf(err, "resolve dest: %v", result) return false } i.elem = &iterElem{ from: from, msg: msg, to: to, thread: thread, modeOverride: modeOverride, opts: i.opts, } return true } func (i *iter) resolvePeer(ctx context.Context, peer string) (peers.Peer, error) { if peer == "" { // self return i.opts.manager.Self(ctx) } return tutil.GetInputPeer(ctx, i.opts.manager, peer) } func (i *iter) Value() forwarder.Elem { return i.elem } func (i *iter) Err() error { return i.err } ================================================ FILE: app/forward/progress.go ================================================ package forward import ( "fmt" "strings" "github.com/fatih/color" pw "github.com/jedib0t/go-pretty/v6/progress" "github.com/mattn/go-runewidth" "github.com/iyear/tdl/core/forwarder" "github.com/iyear/tdl/pkg/prog" "github.com/iyear/tdl/pkg/utils" ) type progress struct { pw pw.Writer trackers map[tuple]*pw.Tracker // TODO(iyear): concurrent map elemName map[int64]string } type tuple struct { from int64 msg int to int64 } func newProgress(p pw.Writer) *progress { return &progress{ pw: p, trackers: make(map[tuple]*pw.Tracker), elemName: make(map[int64]string), } } func (p *progress) OnAdd(elem forwarder.Elem) { tracker := prog.AppendTracker(p.pw, pw.FormatNumber, p.processMessage(elem, false), 1) p.trackers[p.tuple(elem)] = tracker } func (p *progress) OnClone(elem forwarder.Elem, state forwarder.ProgressState) { tracker, ok := p.trackers[p.tuple(elem)] if !ok { return } // display re-upload transfer info tracker.Units.Formatter = utils.Byte.FormatBinaryBytes tracker.UpdateMessage(p.processMessage(elem, true)) tracker.UpdateTotal(state.Total) tracker.SetValue(state.Done) } func (p *progress) OnDone(elem forwarder.Elem, err error) { tracker, ok := p.trackers[p.tuple(elem)] if !ok { return } if err != nil { p.pw.Log(color.RedString("%s error: %s", p.metaString(elem), err.Error())) tracker.MarkAsErrored() return } if tracker.Total == 1 { tracker.Increment(1) } tracker.MarkAsDone() } func (p *progress) tuple(elem forwarder.Elem) tuple { return tuple{ from: elem.From().ID(), msg: elem.Msg().ID, to: elem.To().ID(), } } func (p *progress) processMessage(elem forwarder.Elem, clone bool) string { b := &strings.Builder{} b.WriteString(p.metaString(elem)) if clone { b.WriteString(" [clone]") } return b.String() } func (p *progress) metaString(elem forwarder.Elem) string { // TODO(iyear): better responsive name if _, ok := p.elemName[elem.From().ID()]; !ok { p.elemName[elem.From().ID()] = runewidth.Truncate(elem.From().VisibleName(), 15, "...") } if _, ok := p.elemName[elem.To().ID()]; !ok { p.elemName[elem.To().ID()] = runewidth.Truncate(elem.To().VisibleName(), 15, "...") } return fmt.Sprintf("%s(%d):%d -> %s(%d)", p.elemName[elem.From().ID()], elem.From().ID(), elem.Msg().ID, p.elemName[elem.To().ID()], elem.To().ID()) } ================================================ FILE: app/internal/tctx/tctx.go ================================================ package tctx import ( "context" "github.com/iyear/tdl/core/dcpool" "github.com/iyear/tdl/core/storage" ) type kvKey struct{} func KV(ctx context.Context) storage.Storage { return ctx.Value(kvKey{}).(storage.Storage) } func WithKV(ctx context.Context, kv storage.Storage) context.Context { return context.WithValue(ctx, kvKey{}, kv) } type poolKey struct{} func Pool(ctx context.Context) dcpool.Pool { return ctx.Value(poolKey{}).(dcpool.Pool) } func WithPool(ctx context.Context, pool dcpool.Pool) context.Context { return context.WithValue(ctx, poolKey{}, pool) } ================================================ FILE: app/login/code.go ================================================ package login import ( "context" "strings" "github.com/AlecAivazis/survey/v2" "github.com/fatih/color" "github.com/go-faster/errors" "github.com/gotd/td/telegram/auth" "github.com/gotd/td/tg" "github.com/spf13/viper" "github.com/iyear/tdl/pkg/consts" "github.com/iyear/tdl/pkg/key" "github.com/iyear/tdl/pkg/kv" "github.com/iyear/tdl/pkg/tclient" ) func Code(ctx context.Context) error { kvd, err := kv.From(ctx).Open(viper.GetString(consts.FlagNamespace)) if err != nil { return errors.Wrap(err, "open kv") } if err = kvd.Set(ctx, key.App(), []byte(tclient.AppDesktop)); err != nil { return errors.Wrap(err, "set app") } c, err := tclient.New(ctx, tclient.Options{ KV: kvd, Proxy: viper.GetString(consts.FlagProxy), NTP: viper.GetString(consts.FlagNTP), ReconnectTimeout: viper.GetDuration(consts.FlagReconnectTimeout), UpdateHandler: nil, }, true) if err != nil { return err } return c.Run(ctx, func(ctx context.Context) error { if err = c.Ping(ctx); err != nil { return err } flow := auth.NewFlow(termAuth{}, auth.SendCodeOptions{}) if err = c.Auth().IfNecessary(ctx, flow); err != nil { return err } user, err := c.Self(ctx) if err != nil { return err } color.Green("Login successfully! ID: %d, Username: %s", user.ID, user.Username) return nil }) } // noSignUp can be embedded to prevent signing up. type noSignUp struct{} func (c noSignUp) SignUp(_ context.Context) (auth.UserInfo, error) { return auth.UserInfo{}, errors.New("don't support sign up Telegram account") } func (c noSignUp) AcceptTermsOfService(_ context.Context, tos tg.HelpTermsOfService) error { return &auth.SignUpRequired{TermsOfService: tos} } // termAuth implements authentication via terminal. type termAuth struct { noSignUp } func (a termAuth) Phone(_ context.Context) (string, error) { phone := "" prompt := &survey.Input{ Message: "Enter your phone number:", Default: "+86 12345678900", } if err := survey.AskOne(prompt, &phone, survey.WithValidator(survey.Required)); err != nil { return "", err } color.Blue("Sending Code...") return strings.TrimSpace(phone), nil } func (a termAuth) Password(_ context.Context) (string, error) { pwd := "" prompt := &survey.Password{ Message: "Enter 2FA Password:", } if err := survey.AskOne(prompt, &pwd, survey.WithValidator(survey.Required)); err != nil { return "", err } return strings.TrimSpace(pwd), nil } func (a termAuth) Code(_ context.Context, _ *tg.AuthSentCode) (string, error) { code := "" prompt := &survey.Input{ Message: "Enter Code:", } if err := survey.AskOne(prompt, &code, survey.WithValidator(survey.Required)); err != nil { return "", err } return strings.TrimSpace(code), nil } ================================================ FILE: app/login/desktop.go ================================================ package login import ( "context" "fmt" "os" "path/filepath" "strconv" "github.com/AlecAivazis/survey/v2" "github.com/fatih/color" "github.com/go-faster/errors" "github.com/gotd/td/session" tdtdesktop "github.com/gotd/td/session/tdesktop" "github.com/spf13/viper" "github.com/iyear/tdl/core/storage" "github.com/iyear/tdl/core/util/fsutil" "github.com/iyear/tdl/pkg/consts" "github.com/iyear/tdl/pkg/key" "github.com/iyear/tdl/pkg/kv" "github.com/iyear/tdl/pkg/tclient" "github.com/iyear/tdl/pkg/tdesktop" "github.com/iyear/tdl/pkg/tpath" ) const tdata = "tdata" func Desktop(ctx context.Context, opts Options) error { ns := viper.GetString(consts.FlagNamespace) kvd, err := kv.From(ctx).Open(ns) if err != nil { return errors.Wrap(err, "open kv") } desktop, err := findDesktop(opts.Desktop) if err != nil { return err } color.Blue("Importing session from desktop client: %s", desktop) accounts, err := tdtdesktop.Read(appendTData(desktop), []byte(opts.Passcode)) if err != nil { return err } infos := make([]string, 0, len(accounts)) infoMap := make(map[string]tdtdesktop.Account) for _, acc := range accounts { id := strconv.FormatUint(acc.Authorization.UserID, 10) infos = append(infos, id) infoMap[id] = acc } fmt.Println() sel, acc := &survey.Select{ Message: "Choose a user id:", Options: infos, Help: "You can get user id from @userinfobot", }, "" if err = survey.AskOne(sel, &acc); err != nil { return err } data, err := session.TDesktopSession(infoMap[acc]) if err != nil { return err } loader := &session.Loader{Storage: storage.NewSession(kvd, true)} if err = loader.Save(ctx, data); err != nil { return err } if err = kvd.Set(ctx, key.App(), []byte(tclient.AppDesktop)); err != nil { return err } color.Green("Import %s successfully to '%s' namespace!", acc, ns) // logout confirm, logout := &survey.Confirm{ Message: "Do you want to logout existing desktop session?", Default: false, Help: "Logout existing desktop session to separate from imported session, which can prevent session conflict." + "\n NB: Ensure that you can re-login to desktop client", }, false if err = survey.AskOne(confirm, &logout); err != nil { return err } if logout { if err = forceLogout(infoMap[acc].IDx, desktop); err != nil { return err } color.Green("Logout desktop session of %d successfully! Please re-launch Telegram Desktop client", infoMap[acc].Authorization.UserID) } return nil } func findDesktop(desktop string) (string, error) { if desktop == "" { // auto detect if desktop = detectAppData(); desktop == "" { return "", fmt.Errorf("no data found in possible paths, please specify path to Telegram Desktop directory with `-d` flag") } return desktop, nil } // specified path stat, err := os.Stat(desktop) if err != nil { return "", err } if !stat.IsDir() { // process path that points to Telegram executable file desktop = filepath.Dir(desktop) } return desktop, nil } func detectAppData() string { for _, p := range tpath.Desktop.AppData(consts.HomeDir) { if path := appendTData(p); fsutil.PathExists(path) { return path } } return "" } func appendTData(path string) string { if filepath.Base(path) != tdata { path = filepath.Join(path, tdata) } return path } // forceLogout currently only remove session file func forceLogout(idx uint32, desktop string) error { dir := "data" if idx > 0 { dir = fmt.Sprintf("data#%d", idx+1) } return os.RemoveAll(filepath.Join(appendTData(desktop), tdesktop.FileKey(dir))) } ================================================ FILE: app/login/login.go ================================================ package login import ( "context" "github.com/go-faster/errors" ) //go:generate go-enum --values --names --flag --nocase // Type // ENUM(desktop, code, qr) type Type int type Options struct { Type Type Desktop string Passcode string } func Run(ctx context.Context, opts Options) error { switch opts.Type { case TypeDesktop: return Desktop(ctx, opts) case TypeCode: return Code(ctx) case TypeQr: return QR(ctx) default: return errors.Errorf("unsupported login type: %s", opts.Type) } } ================================================ FILE: app/login/login_enum.go ================================================ // Code generated by go-enum DO NOT EDIT. // Version: 0.5.8 // Revision: 3d844c8ecc59661ed7aa17bfd65727bc06a60ad8 // Build Date: 2023-09-18T14:55:21Z // Built By: goreleaser package login import ( "fmt" "strings" ) const ( // TypeDesktop is a Type of type Desktop. TypeDesktop Type = iota // TypeCode is a Type of type Code. TypeCode // TypeQr is a Type of type Qr. TypeQr ) var ErrInvalidType = fmt.Errorf("not a valid Type, try [%s]", strings.Join(_TypeNames, ", ")) const _TypeName = "desktopcodeqr" var _TypeNames = []string{ _TypeName[0:7], _TypeName[7:11], _TypeName[11:13], } // TypeNames returns a list of possible string values of Type. func TypeNames() []string { tmp := make([]string, len(_TypeNames)) copy(tmp, _TypeNames) return tmp } // TypeValues returns a list of the values for Type func TypeValues() []Type { return []Type{ TypeDesktop, TypeCode, TypeQr, } } var _TypeMap = map[Type]string{ TypeDesktop: _TypeName[0:7], TypeCode: _TypeName[7:11], TypeQr: _TypeName[11:13], } // String implements the Stringer interface. func (x Type) String() string { if str, ok := _TypeMap[x]; ok { return str } return fmt.Sprintf("Type(%d)", x) } // IsValid provides a quick way to determine if the typed value is // part of the allowed enumerated values func (x Type) IsValid() bool { _, ok := _TypeMap[x] return ok } var _TypeValue = map[string]Type{ _TypeName[0:7]: TypeDesktop, strings.ToLower(_TypeName[0:7]): TypeDesktop, _TypeName[7:11]: TypeCode, strings.ToLower(_TypeName[7:11]): TypeCode, _TypeName[11:13]: TypeQr, strings.ToLower(_TypeName[11:13]): TypeQr, } // ParseType attempts to convert a string to a Type. func ParseType(name string) (Type, error) { if x, ok := _TypeValue[name]; ok { return x, nil } // Case insensitive parse, do a separate lookup to prevent unnecessary cost of lowercasing a string if we don't need to. if x, ok := _TypeValue[strings.ToLower(name)]; ok { return x, nil } return Type(0), fmt.Errorf("%s is %w", name, ErrInvalidType) } // Set implements the Golang flag.Value interface func. func (x *Type) Set(val string) error { v, err := ParseType(val) *x = v return err } // Get implements the Golang flag.Getter interface func. func (x *Type) Get() interface{} { return *x } // Type implements the github.com/spf13/pFlag Value interface. func (x *Type) Type() string { return "Type" } ================================================ FILE: app/login/qr.go ================================================ package login import ( "context" "fmt" "strings" "github.com/AlecAivazis/survey/v2" "github.com/fatih/color" "github.com/go-faster/errors" "github.com/gotd/td/telegram/auth/qrlogin" "github.com/gotd/td/tg" "github.com/gotd/td/tgerr" "github.com/jedib0t/go-pretty/v6/text" "github.com/skip2/go-qrcode" "github.com/spf13/viper" "github.com/iyear/tdl/pkg/consts" "github.com/iyear/tdl/pkg/key" "github.com/iyear/tdl/pkg/kv" "github.com/iyear/tdl/pkg/tclient" ) func QR(ctx context.Context) error { kvd, err := kv.From(ctx).Open(viper.GetString(consts.FlagNamespace)) if err != nil { return errors.Wrap(err, "open kv") } if err = kvd.Set(ctx, key.App(), []byte(tclient.AppDesktop)); err != nil { return errors.Wrap(err, "set app") } d := tg.NewUpdateDispatcher() c, err := tclient.New(ctx, tclient.Options{ KV: kvd, Proxy: viper.GetString(consts.FlagProxy), NTP: viper.GetString(consts.FlagNTP), ReconnectTimeout: viper.GetDuration(consts.FlagReconnectTimeout), UpdateHandler: d, }, true) if err != nil { return errors.Wrap(err, "create client") } return c.Run(ctx, func(ctx context.Context) error { color.Blue("Scan QR code with your Telegram app...") var lines int _, err = c.QR().Auth(ctx, qrlogin.OnLoginToken(d), func(ctx context.Context, token qrlogin.Token) error { qr, err := qrcode.New(token.URL(), qrcode.Medium) if err != nil { return errors.Wrap(err, "create qr") } code := qr.ToSmallString(false) lines = strings.Count(code, "\n") fmt.Print(code) fmt.Print(strings.Repeat(text.CursorUp.Sprint(), lines)) return nil }) // clear qrcode out := &strings.Builder{} for i := 0; i < lines; i++ { out.WriteString(text.EraseLine.Sprint()) out.WriteString(text.CursorDown.Sprint()) } out.WriteString(text.CursorUp.Sprintn(lines)) fmt.Print(out.String()) if err != nil { // https://core.telegram.org/api/auth#2fa if !tgerr.Is(err, "SESSION_PASSWORD_NEEDED") { return errors.Wrap(err, "qr auth") } pwd := "" prompt := &survey.Password{ Message: "Enter 2FA Password:", } if err = survey.AskOne(prompt, &pwd, survey.WithValidator(survey.Required)); err != nil { return errors.Wrap(err, "2fa password") } if _, err = c.Auth().Password(ctx, pwd); err != nil { return errors.Wrap(err, "2fa auth") } } user, err := c.Self(ctx) if err != nil { return errors.Wrap(err, "get self") } fmt.Print(text.EraseLine.Sprint()) color.Green("Login successfully! ID: %d, Username: %s", user.ID, user.Username) return nil }) } ================================================ FILE: app/migrate/backup.go ================================================ package migrate import ( "context" "encoding/json" "os" "github.com/fatih/color" "github.com/go-faster/errors" "github.com/klauspost/compress/zstd" "go.uber.org/multierr" "github.com/iyear/tdl/pkg/kv" ) func Backup(ctx context.Context, dst string) (rerr error) { meta, err := kv.From(ctx).MigrateTo() if err != nil { return errors.Wrap(err, "read metadata") } f, err := os.Create(dst) if err != nil { return errors.Wrap(err, "create file") } defer multierr.AppendInvoke(&rerr, multierr.Close(f)) enc, err := zstd.NewWriter(f, zstd.WithEncoderLevel(zstd.SpeedBestCompression)) if err != nil { return errors.Wrap(err, "create zstd encoder") } defer multierr.AppendInvoke(&rerr, multierr.Close(enc)) metaB, err := json.Marshal(meta) if err != nil { return errors.Wrap(err, "marshal metadata") } if _, err = enc.Write(metaB); err != nil { return errors.Wrap(err, "write metadata") } color.Green("Backup successfully, file: %s", dst) return nil } ================================================ FILE: app/migrate/migrate.go ================================================ package migrate import ( "context" "github.com/AlecAivazis/survey/v2" "github.com/fatih/color" "github.com/go-faster/errors" "github.com/iyear/tdl/pkg/kv" ) func Migrate(ctx context.Context, to map[string]string) error { var confirm bool if err := survey.AskOne(&survey.Confirm{ Message: "It will overwrite the namespace data in the destination storage, continue?", Default: false, }, &confirm); err != nil { return errors.Wrap(err, "confirm") } if !confirm { return nil } meta, err := kv.From(ctx).MigrateTo() if err != nil { return errors.Wrap(err, "read data") } dest, err := kv.NewWithMap(to) if err != nil { return errors.Wrap(err, "create dest storage") } if err = dest.MigrateFrom(meta); err != nil { return errors.Wrap(err, "migrate from") } color.Green("Migrate successfully.") for ns := range meta { color.Green(" - %s", ns) } return nil } ================================================ FILE: app/migrate/recover.go ================================================ package migrate import ( "bytes" "context" "encoding/json" "os" "github.com/fatih/color" "github.com/go-faster/errors" "github.com/klauspost/compress/zstd" "go.uber.org/multierr" "github.com/iyear/tdl/pkg/kv" ) func Recover(ctx context.Context, file string) (rerr error) { f, err := os.Open(file) if err != nil { return errors.Wrap(err, "open file") } defer multierr.AppendInvoke(&rerr, multierr.Close(f)) dec, err := zstd.NewReader(f) if err != nil { return errors.Wrap(err, "create zstd decoder") } defer dec.Close() metaB := bytes.NewBuffer(nil) if _, err = dec.WriteTo(metaB); err != nil { return err } var meta kv.Meta if err = json.Unmarshal(metaB.Bytes(), &meta); err != nil { return errors.Wrap(err, "unmarshal metadata") } if err = kv.From(ctx).MigrateFrom(meta); err != nil { return errors.Wrap(err, "migrate from") } color.Green("Recover successfully, file: %s", file) return nil } ================================================ FILE: app/up/elem.go ================================================ package up import ( "os" "path/filepath" "github.com/gotd/td/telegram/message/entity" "github.com/gotd/td/telegram/peers" "github.com/gotd/td/tg" "github.com/iyear/tdl/core/uploader" ) type iterElem struct { file *uploaderFile thumb *uploaderFile to peers.Peer caption *entity.Builder thread int asPhoto bool remove bool } func (e *iterElem) File() uploader.File { return e.file } func (e *iterElem) Thumb() (uploader.File, bool) { if e.thumb == nil { return nil, false } return e.thumb, true } func (e *iterElem) Caption() (string, []tg.MessageEntityClass) { return e.caption.Complete() } func (e *iterElem) To() tg.InputPeerClass { return e.to.InputPeer() } func (e *iterElem) Thread() int { return e.thread } func (e *iterElem) AsPhoto() bool { return e.asPhoto } type uploaderFile struct { *os.File size int64 } func (u *uploaderFile) Name() string { return filepath.Base(u.File.Name()) } func (u *uploaderFile) Size() int64 { return u.size } ================================================ FILE: app/up/iter.go ================================================ package up import ( "context" "os" "strings" "time" "github.com/expr-lang/expr/vm" "github.com/gabriel-vasile/mimetype" "github.com/go-faster/errors" "github.com/go-viper/mapstructure/v2" "github.com/gotd/td/telegram/message/entity" "github.com/gotd/td/telegram/message/html" "github.com/gotd/td/telegram/peers" "github.com/iyear/tdl/core/uploader" "github.com/iyear/tdl/core/util/mediautil" "github.com/iyear/tdl/core/util/tutil" "github.com/iyear/tdl/pkg/texpr" ) type File struct { File string Thumb string } type dest struct { Peer string Thread int } type iter struct { files []*File to *vm.Program caption *vm.Program chat string topic int photo bool remove bool delay time.Duration manager *peers.Manager cur int err error file uploader.Elem } func newIter(files []*File, to, caption *vm.Program, chat string, topic int, photo, remove bool, delay time.Duration, manager *peers.Manager) *iter { return &iter{ files: files, to: to, caption: caption, chat: chat, topic: topic, photo: photo, remove: remove, delay: delay, manager: manager, cur: 0, err: nil, file: nil, } } func (i *iter) Next(ctx context.Context) bool { select { case <-ctx.Done(): i.err = ctx.Err() return false default: } if i.cur >= len(i.files) || i.err != nil { return false } // if delay is set, sleep for a while for each iteration if i.delay > 0 && i.cur > 0 { // skip first delay time.Sleep(i.delay) } cur := i.files[i.cur] i.cur++ file, err := i.next(ctx, cur) if err != nil { i.err = err return false } i.file = file return true } func (i *iter) next(ctx context.Context, cur *File) (*iterElem, error) { file, err := i.resolveFile(cur.File) if err != nil { return nil, errors.Wrap(err, "resolve file") } env := exprEnv(ctx, cur) to, thread, err := i.resolveDest(ctx, env) if err != nil { return nil, errors.Wrap(err, "resolve destination") } caption, err := i.resolveCaption(env) if err != nil { return nil, errors.Wrap(err, "resolve caption") } thumb, err := i.resolveThumb(cur.Thumb) if err != nil { return nil, errors.Wrap(err, "resolve thumbnail") } return &iterElem{ file: file, thumb: thumb, to: to, caption: caption, thread: thread, asPhoto: i.photo, remove: i.remove, }, nil } func (i *iter) resolveFile(path string) (*uploaderFile, error) { f, err := os.Open(path) if err != nil { return nil, errors.Wrap(err, "open file") } stat, err := f.Stat() if err != nil { return nil, errors.Wrap(err, "stat file") } return &uploaderFile{ File: f, size: stat.Size(), }, nil } func (i *iter) resolveDest(ctx context.Context, env Env) (peers.Peer, int, error) { if i.chat != "" { // compatible with old version to, err := i.resolvePeer(ctx, i.chat) if err != nil { return nil, 0, errors.Wrap(err, "resolve chat") } return to, i.topic, nil } // message routing result, err := texpr.Run(i.to, env) if err != nil { return nil, 0, errors.Wrap(err, "parse expression") } var ( to peers.Peer thread int ) switch r := result.(type) { case string: // pure chat, no reply to, which is a compatible with old version // and a convenient way to send message to self to, err = i.resolvePeer(ctx, r) case map[string]interface{}: // chat with reply to topic or message var d dest if err = mapstructure.WeakDecode(r, &d); err != nil { return nil, 0, errors.Wrapf(err, "decode dest: %v", result) } to, err = i.resolvePeer(ctx, d.Peer) thread = d.Thread default: return nil, 0, errors.Errorf("message router must return string or dest: %T", result) } if err != nil { return nil, 0, errors.Wrap(err, "resolve peer") } return to, thread, nil } func (i *iter) resolvePeer(ctx context.Context, peer string) (peers.Peer, error) { if peer == "" { // self return i.manager.Self(ctx) } return tutil.GetInputPeer(ctx, i.manager, peer) } func (i *iter) resolveCaption(env Env) (*entity.Builder, error) { // parse caption captionStr, err := texpr.Run(i.caption, env) if err != nil { return nil, errors.Wrap(err, "parse caption") } r, ok := captionStr.(string) if !ok { return nil, errors.Errorf("caption must return string, got %T", captionStr) } caption := &entity.Builder{} if len(r) > 0 { if err = html.HTML(strings.NewReader(r), caption, html.Options{ UserResolver: nil, DisableTelegramEscape: false, }); err != nil { return nil, errors.Wrap(err, "parse caption HTML") } } return caption, nil } func (i *iter) resolveThumb(path string) (*uploaderFile, error) { if path == "" { return nil, nil } // has thumbnail mime, err := mimetype.DetectFile(path) if err != nil || !mediautil.IsImage(mime.String()) { // TODO(iyear): jpg only return nil, errors.Wrapf(err, "invalid thumbnail file: %v", path) } thumb, err := os.Open(path) if err != nil { return nil, errors.Wrap(err, "open thumbnail file") } return &uploaderFile{ File: thumb, size: 0, }, nil } func (i *iter) Value() uploader.Elem { return i.file } func (i *iter) Err() error { return i.err } ================================================ FILE: app/up/progress.go ================================================ package up import ( "fmt" "os" "sync" "github.com/fatih/color" "github.com/go-faster/errors" pw "github.com/jedib0t/go-pretty/v6/progress" "github.com/iyear/tdl/core/uploader" "github.com/iyear/tdl/pkg/prog" "github.com/iyear/tdl/pkg/utils" ) type progress struct { pw pw.Writer trackers *sync.Map // map[tuple]*pw.Tracker } type tuple struct { name string to int64 } func newProgress(p pw.Writer) *progress { return &progress{ pw: p, trackers: &sync.Map{}, } } func (p *progress) OnAdd(elem uploader.Elem) { tracker := prog.AppendTracker(p.pw, utils.Byte.FormatBinaryBytes, p.processMessage(elem), elem.File().Size()) p.trackers.Store(p.tuple(elem), tracker) } func (p *progress) OnUpload(elem uploader.Elem, state uploader.ProgressState) { tracker, ok := p.trackers.Load(p.tuple(elem)) if !ok { return } t := tracker.(*pw.Tracker) t.UpdateTotal(state.Total) t.SetValue(state.Uploaded) } func (p *progress) OnDone(elem uploader.Elem, err error) { tracker, ok := p.trackers.Load(p.tuple(elem)) if !ok { return } t := tracker.(*pw.Tracker) e := elem.(*iterElem) if err := p.closeFile(e); err != nil { p.fail(t, elem, errors.Wrap(err, "close file")) return } if err != nil { p.fail(t, elem, errors.Wrap(err, "progress")) return } if e.remove { if err := os.Remove(e.file.File.Name()); err != nil { p.fail(t, elem, errors.Wrap(err, "remove file")) return } } } func (p *progress) closeFile(e *iterElem) error { if err := e.file.Close(); err != nil { return errors.Wrap(err, "close file") } if e.thumb != nil { if err := e.thumb.Close(); err != nil { return errors.Wrap(err, "close thumb") } } return nil } func (p *progress) fail(t *pw.Tracker, elem uploader.Elem, err error) { p.pw.Log(color.RedString("%s error: %s", p.elemString(elem), err.Error())) t.MarkAsErrored() } func (p *progress) tuple(elem uploader.Elem) tuple { return tuple{elem.(*iterElem).file.File.Name(), elem.(*iterElem).to.ID()} } func (p *progress) processMessage(elem uploader.Elem) string { return p.elemString(elem) } func (p *progress) elemString(elem uploader.Elem) string { e := elem.(*iterElem) return fmt.Sprintf("%s -> %s(%d)", e.file.File.Name(), e.to.VisibleName(), e.to.ID()) } ================================================ FILE: app/up/up.go ================================================ package up import ( "context" "fmt" "os" "path/filepath" "reflect" "strings" "github.com/expr-lang/expr" "github.com/expr-lang/expr/vm" "github.com/fatih/color" "github.com/gabriel-vasile/mimetype" "github.com/go-faster/errors" "github.com/gotd/td/telegram" "github.com/gotd/td/telegram/peers" "github.com/spf13/viper" "go.uber.org/multierr" "go.uber.org/zap" "github.com/iyear/tdl/core/dcpool" "github.com/iyear/tdl/core/logctx" "github.com/iyear/tdl/core/storage" "github.com/iyear/tdl/core/tclient" "github.com/iyear/tdl/core/uploader" "github.com/iyear/tdl/core/util/tutil" "github.com/iyear/tdl/pkg/consts" "github.com/iyear/tdl/pkg/prog" "github.com/iyear/tdl/pkg/texpr" "github.com/iyear/tdl/pkg/utils" ) type Options struct { Chat string Thread int To string Paths []string Includes []string Excludes []string Remove bool Photo bool Caption string } type Env struct { FilePath string `comment:"File path"` FileName string `comment:"File name"` FileExt string `comment:"File extension"` ThumbPath string `comment:"Thumbnail path"` MIME string `comment:"File mime type"` } func Run(ctx context.Context, c *telegram.Client, kvd storage.Storage, opts Options) (rerr error) { if opts.To == "-" || opts.Caption == "-" { fg := texpr.NewFieldsGetter(nil) fields, err := fg.Walk(exprEnv(context.Background(), nil)) if err != nil { return fmt.Errorf("failed to walk fields: %w", err) } fmt.Print(fg.Sprint(fields, true)) return nil } files, err := walk(opts.Paths, opts.Includes, opts.Excludes) if err != nil { return err } color.Blue("Files count: %d", len(files)) pool := dcpool.NewPool(c, int64(viper.GetInt(consts.FlagPoolSize)), tclient.NewDefaultMiddlewares(ctx, viper.GetDuration(consts.FlagReconnectTimeout))...) defer multierr.AppendInvoke(&rerr, multierr.Close(pool)) manager := peers.Options{Storage: storage.NewPeers(kvd)}.Build(pool.Default(ctx)) to, err := resolveDest(ctx, manager, opts.To) if err != nil { return errors.Wrap(err, "get target peer") } caption, err := resolveCaption(ctx, opts.Caption) if err != nil { return errors.Wrap(err, "get caption") } upProgress := prog.New(utils.Byte.FormatBinaryBytes) upProgress.SetNumTrackersExpected(len(files)) prog.EnablePS(ctx, upProgress) options := uploader.Options{ Client: pool.Default(ctx), Threads: viper.GetInt(consts.FlagThreads), Iter: newIter(files, to, caption, opts.Chat, opts.Thread, opts.Photo, opts.Remove, viper.GetDuration(consts.FlagDelay), manager), Progress: newProgress(upProgress), } up := uploader.New(options) go upProgress.Render() defer prog.Wait(ctx, upProgress) return up.Upload(ctx, viper.GetInt(consts.FlagLimit)) } func resolveDest(ctx context.Context, manager *peers.Manager, input string) (*vm.Program, error) { compile := func(i string) (*vm.Program, error) { return expr.Compile(i, expr.Env(exprEnv(ctx, nil))) } if input == "" { return compile(`""`) } if exp, err := os.ReadFile(input); err == nil { return compile(string(exp)) } if _, err := tutil.GetInputPeer(ctx, manager, input); err == nil { return compile(fmt.Sprintf(`"%s"`, input)) } return compile(input) } func resolveCaption(ctx context.Context, input string) (*vm.Program, error) { compile := func(i string) (*vm.Program, error) { // we pass empty peer and message to enable type checking return expr.Compile(i, expr.Env(exprEnv(ctx, nil)), expr.AsKind(reflect.String)) } // default if input == "" { return compile(`""`) } // file if exp, err := os.ReadFile(input); err == nil { return compile(string(exp)) } // text return compile(input) } func exprEnv(ctx context.Context, file *File) Env { if file == nil { return Env{} } extension := filepath.Ext(file.File) filename := strings.TrimSuffix(filepath.Base(file.File), extension) mime, err := mimetype.DetectFile(file.File) if err != nil { mime = &mimetype.MIME{} logctx.From(ctx).Error("detect file mime", zap.Error(err)) } return Env{ FilePath: file.File, FileName: filename, FileExt: extension, ThumbPath: file.Thumb, MIME: mime.String(), } } ================================================ FILE: app/up/walk.go ================================================ package up import ( "io/fs" "path/filepath" "strings" "github.com/iyear/tdl/core/util/fsutil" "github.com/iyear/tdl/pkg/consts" "github.com/iyear/tdl/pkg/filterMap" ) func walk(paths, includes, excludes []string) ([]*File, error) { files := make([]*File, 0) includesMap := filterMap.New(includes, fsutil.AddPrefixDot) excludesMap := filterMap.New(excludes, fsutil.AddPrefixDot) excludesMap[consts.UploadThumbExt] = struct{}{} // ignore thumbnail files for _, path := range paths { err := filepath.WalkDir(path, func(path string, d fs.DirEntry, err error) error { if err != nil { return err } if d.IsDir() { return nil } // process include and exclude ext := filepath.Ext(path) if _, ok := includesMap[ext]; len(includesMap) > 0 && !ok { return nil } if _, ok := excludesMap[ext]; len(excludesMap) > 0 && ok { return nil } f := File{File: path} t := strings.TrimRight(path, filepath.Ext(path)) + consts.UploadThumbExt if fsutil.PathExists(t) { f.Thumb = t } files = append(files, &f) return nil }) if err != nil { return nil, err } } return files, nil } ================================================ FILE: cmd/chat.go ================================================ package cmd import ( "context" "fmt" "math" "strings" "time" "github.com/gotd/contrib/middleware/ratelimit" "github.com/gotd/td/telegram" "github.com/spf13/cobra" "golang.org/x/time/rate" "github.com/iyear/tdl/app/chat" "github.com/iyear/tdl/core/logctx" "github.com/iyear/tdl/core/storage" ) var limiter = ratelimit.New(rate.Every(500*time.Millisecond), 2) func NewChat() *cobra.Command { cmd := &cobra.Command{ Use: "chat", Short: "A set of chat tools", GroupID: groupTools.ID, } cmd.AddCommand(NewChatList(), NewChatExport(), NewChatUsers()) return cmd } func NewChatList() *cobra.Command { var opts chat.ListOptions cmd := &cobra.Command{ Use: "ls", Short: "List your chats", RunE: func(cmd *cobra.Command, args []string) error { return tRun(cmd.Context(), func(ctx context.Context, c *telegram.Client, kvd storage.Storage) error { return chat.List(logctx.Named(ctx, "ls"), c, kvd, opts) }, limiter) }, } cmd.Flags().VarP(&opts.Output, "output", "o", fmt.Sprintf("output format: [%s]", strings.Join(chat.ListOutputNames(), ", "))) cmd.Flags().StringVarP(&opts.Filter, "filter", "f", "true", "filter chats by expression") return cmd } func NewChatExport() *cobra.Command { var opts chat.ExportOptions cmd := &cobra.Command{ Use: "export", Short: "export messages from (protected) chat for download", RunE: func(cmd *cobra.Command, args []string) error { switch opts.Type { case chat.ExportTypeTime, chat.ExportTypeId: // set default value switch len(opts.Input) { case 0: opts.Input = []int{0, math.MaxInt} case 1: opts.Input = append(opts.Input, math.MaxInt) } if len(opts.Input) != 2 { return fmt.Errorf("input data should be 2 integers when export type is %s", opts.Type) } // sort helper if opts.Input[0] > opts.Input[1] { opts.Input[0], opts.Input[1] = opts.Input[1], opts.Input[0] } case chat.ExportTypeLast: if len(opts.Input) != 1 { return fmt.Errorf("input data should be 1 integer when export type is %s", opts.Type) } default: return fmt.Errorf("unknown export type: %s", opts.Type) } return tRun(cmd.Context(), func(ctx context.Context, c *telegram.Client, kvd storage.Storage) error { return chat.Export(logctx.Named(ctx, "export"), c, kvd, opts) }, limiter) }, } const ( _type = "type" _chat = "chat" input = "input" ) cmd.Flags().VarP(&opts.Type, _type, "T", fmt.Sprintf("export type: [%s]", strings.Join(chat.ExportTypeNames(), ", "))) cmd.Flags().StringVarP(&opts.Chat, _chat, "c", "", "chat id or domain. If not specified, 'Saved Messages' will be used") // topic id and message id is the same field in tg.MessagesGetRepliesRequest cmd.Flags().IntVar(&opts.Thread, "topic", 0, "specify topic id") cmd.Flags().IntVar(&opts.Thread, "reply", 0, "specify channel post id") cmd.Flags().IntSliceVarP(&opts.Input, input, "i", []int{}, "input data, depends on export type") cmd.Flags().StringVarP(&opts.Filter, "filter", "f", "true", "filter messages by expression, defaults to match all messages. Specify '-' to see available fields") cmd.Flags().StringVarP(&opts.Output, "output", "o", "tdl-export.json", "output JSON file path") cmd.Flags().BoolVar(&opts.WithContent, "with-content", false, "export with message content") cmd.Flags().BoolVar(&opts.Raw, "raw", false, "export raw message struct of Telegram MTProto API, useful for debugging") cmd.Flags().BoolVar(&opts.All, "all", false, "export all messages including non-media messages, but still affected by filter and type flag") // completion and validation _ = cmd.RegisterFlagCompletionFunc(input, func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { // if user has already input something, don't do anything if toComplete != "" { return []string{}, cobra.ShellCompDirectiveNoFileComp } switch cmd.Flags().Lookup(_type).Value.String() { case chat.ExportTypeTime.String(): return []string{"0,9999999"}, cobra.ShellCompDirectiveNoFileComp case chat.ExportTypeId.String(): return []string{"0,9999999"}, cobra.ShellCompDirectiveNoFileComp case chat.ExportTypeLast.String(): return []string{"100"}, cobra.ShellCompDirectiveNoFileComp default: return []string{}, cobra.ShellCompDirectiveNoFileComp } }) return cmd } func NewChatUsers() *cobra.Command { var opts chat.UsersOptions cmd := &cobra.Command{ Use: "users", Short: "export users from (protected) channels", RunE: func(cmd *cobra.Command, args []string) error { return tRun(cmd.Context(), func(ctx context.Context, c *telegram.Client, kvd storage.Storage) error { return chat.Users(logctx.Named(ctx, "users"), c, kvd, opts) }, limiter) }, } cmd.Flags().StringVarP(&opts.Output, "output", "o", "tdl-users.json", "output JSON file path") cmd.Flags().StringVarP(&opts.Chat, "chat", "c", "", "domain id (channels, supergroups, etc.)") cmd.Flags().BoolVar(&opts.Raw, "raw", false, "export raw message struct of Telegram MTProto API, useful for debugging") return cmd } ================================================ FILE: cmd/dl.go ================================================ package cmd import ( "context" "fmt" "github.com/gotd/td/telegram" "github.com/spf13/cobra" "github.com/spf13/viper" "github.com/iyear/tdl/app/dl" "github.com/iyear/tdl/core/logctx" "github.com/iyear/tdl/core/storage" "github.com/iyear/tdl/pkg/consts" ) func NewDownload() *cobra.Command { var opts dl.Options cmd := &cobra.Command{ Use: "download", Aliases: []string{"dl"}, Short: "Download anything from Telegram (protected) chat", GroupID: groupTools.ID, RunE: func(cmd *cobra.Command, args []string) error { if len(opts.URLs) == 0 && len(opts.Files) == 0 { return fmt.Errorf("no urls or files provided") } opts.Template = viper.GetString(consts.FlagDlTemplate) return tRun(cmd.Context(), func(ctx context.Context, c *telegram.Client, kvd storage.Storage) error { return dl.Run(logctx.Named(ctx, "dl"), c, kvd, opts) }) }, } const ( file = "file" dir = "dir" include = "include" exclude = "exclude" _continue = "continue" restart = "restart" ) cmd.Flags().StringSliceVarP(&opts.URLs, "url", "u", []string{}, "telegram message links") cmd.Flags().StringSliceVarP(&opts.Files, file, "f", []string{}, "official client exported files") cmd.Flags().String(consts.FlagDlTemplate, `{{ .DialogID }}_{{ .MessageID }}_{{ filenamify .FileName }}`, "download file name template") cmd.Flags().StringSliceVarP(&opts.Include, include, "i", []string{}, "include the specified file extensions, and only judge by file name, not file MIME. Example: -i mp4,mp3") cmd.Flags().StringSliceVarP(&opts.Exclude, exclude, "e", []string{}, "exclude the specified file extensions, and only judge by file name, not file MIME. Example: -e png,jpg") cmd.Flags().StringVarP(&opts.Dir, dir, "d", "downloads", "specify the download directory. If the directory does not exist, it will be created automatically") cmd.Flags().BoolVar(&opts.RewriteExt, "rewrite-ext", false, "rewrite file extension according to file header MIME") // do not match extension, because some files' extension is corrected by --rewrite-ext flag cmd.Flags().BoolVar(&opts.SkipSame, "skip-same", false, "skip files with the same name(without extension) and size") cmd.Flags().BoolVar(&opts.Desc, "desc", false, "download files from the newest to the oldest ones (may affect resume download)") cmd.Flags().BoolVar(&opts.Takeout, "takeout", false, "takeout sessions let you export data from your account with lower flood wait limits.") cmd.Flags().BoolVar(&opts.Group, "group", false, "auto detect grouped message and download all of them") // resume flags, if both false then ask user cmd.Flags().BoolVar(&opts.Continue, _continue, false, "continue the last download directly") cmd.Flags().BoolVar(&opts.Restart, restart, false, "restart the last download directly") // serve flags cmd.Flags().BoolVar(&opts.Serve, "serve", false, "serve the media files as a http server instead of downloading them with built-in downloader") cmd.Flags().IntVar(&opts.Port, "port", 8080, "http server port") _ = viper.BindPFlag(consts.FlagDlTemplate, cmd.Flags().Lookup(consts.FlagDlTemplate)) // completion and validation _ = cmd.RegisterFlagCompletionFunc(file, completeExtFiles("json")) _ = cmd.MarkFlagDirname(dir) cmd.MarkFlagsMutuallyExclusive(include, exclude) cmd.MarkFlagsMutuallyExclusive(_continue, restart) return cmd } ================================================ FILE: cmd/extension.go ================================================ package cmd import ( "fmt" "io" "os" "os/exec" "path/filepath" "github.com/go-faster/errors" "github.com/spf13/cobra" "github.com/spf13/viper" "github.com/iyear/tdl/app/extension" "github.com/iyear/tdl/core/storage" extbase "github.com/iyear/tdl/extension" "github.com/iyear/tdl/pkg/consts" "github.com/iyear/tdl/pkg/extensions" "github.com/iyear/tdl/pkg/tclient" ) func NewExtension(em *extensions.Manager) *cobra.Command { var dryRun bool cmd := &cobra.Command{ Use: "extension", Short: "Manage tdl extensions", GroupID: groupTools.ID, Aliases: []string{"extensions", "ext"}, PersistentPreRun: func(cmd *cobra.Command, args []string) { em.SetDryRun(dryRun) }, } cmd.AddCommand(NewExtensionList(em), NewExtensionInstall(em), NewExtensionRemove(em), NewExtensionUpgrade(em)) cmd.PersistentFlags().BoolVar(&dryRun, "dry-run", false, "only print what would be done without actually doing it") return cmd } func NewExtensionList(em *extensions.Manager) *cobra.Command { cmd := &cobra.Command{ Use: "list", Short: "List installed extension commands", Aliases: []string{"ls"}, Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, args []string) error { return extension.List(cmd.Context(), em) }, } return cmd } func NewExtensionInstall(em *extensions.Manager) *cobra.Command { var force bool cmd := &cobra.Command{ Use: "install", Short: "Install a tdl extension", Args: cobra.MinimumNArgs(1), RunE: func(cmd *cobra.Command, args []string) error { return extension.Install(cmd.Context(), em, args, force) }, } cmd.Flags().BoolVar(&force, "force", false, "force install even if extension already exists") return cmd } func NewExtensionUpgrade(em *extensions.Manager) *cobra.Command { cmd := &cobra.Command{ Use: "upgrade", Short: "Upgrade a tdl extension", RunE: func(cmd *cobra.Command, args []string) error { return extension.Upgrade(cmd.Context(), em, args) }, } return cmd } func NewExtensionRemove(em *extensions.Manager) *cobra.Command { cmd := &cobra.Command{ Use: "remove", Short: "Remove an installed extension", Args: cobra.MinimumNArgs(1), RunE: func(cmd *cobra.Command, args []string) error { return extension.Remove(cmd.Context(), em, args) }, } return cmd } func NewExtensionCmd(em *extensions.Manager, ext extensions.Extension, stdin io.Reader, stdout, stderr io.Writer) *cobra.Command { return &cobra.Command{ Use: ext.Name(), Short: fmt.Sprintf("Extension %s", ext.Name()), RunE: func(cmd *cobra.Command, args []string) error { ctx := cmd.Context() opts, err := tOptions(ctx) if err != nil { return errors.Wrap(err, "build telegram options") } app, err := tclient.GetApp(opts.KV) if err != nil { return errors.Wrap(err, "get app") } session, err := storage.NewSession(opts.KV, false).LoadSession(ctx) if err != nil { return errors.Wrap(err, "load session") } dataDir := filepath.Join(consts.ExtensionsDataPath, ext.Name()) if err = os.MkdirAll(dataDir, 0o755); err != nil { return errors.Wrap(err, "create extension data dir") } env := &extbase.Env{ Name: ext.Name(), AppID: app.AppID, AppHash: app.AppHash, Session: session, Namespace: viper.GetString(consts.FlagNamespace), DataDir: dataDir, NTP: opts.NTP, Proxy: opts.Proxy, Pool: viper.GetInt64(consts.FlagPoolSize), Debug: viper.GetBool(consts.FlagDebug), } if err = em.Dispatch(ext, args, env, stdin, stdout, stderr); err != nil { var execError *exec.ExitError if errors.As(err, &execError) { return execError } return fmt.Errorf("failed to run extension: %w", err) } return nil }, GroupID: groupExtensions.ID, DisableFlagParsing: true, } } ================================================ FILE: cmd/forward.go ================================================ package cmd import ( "context" "fmt" "strings" "github.com/gotd/td/telegram" "github.com/spf13/cobra" "github.com/iyear/tdl/app/forward" "github.com/iyear/tdl/core/forwarder" "github.com/iyear/tdl/core/logctx" "github.com/iyear/tdl/core/storage" ) func NewForward() *cobra.Command { var opts forward.Options cmd := &cobra.Command{ Use: "forward", Short: "Forward messages with automatic fallback and message routing", GroupID: groupTools.ID, RunE: func(cmd *cobra.Command, args []string) error { return tRun(cmd.Context(), func(ctx context.Context, c *telegram.Client, kvd storage.Storage) error { return forward.Run(logctx.Named(ctx, "forward"), c, kvd, opts) }) }, } cmd.Flags().StringArrayVar(&opts.From, "from", []string{}, "messages to be forwarded, can be links or exported JSON files") cmd.Flags().StringVar(&opts.To, "to", "", "destination peer, can be a CHAT or router based on expression engine") cmd.Flags().StringVar(&opts.Edit, "edit", "", "edit message or caption with expression engine. Empty means no edit") cmd.Flags().Var(&opts.Mode, "mode", fmt.Sprintf("forward mode: [%s]", strings.Join(forwarder.ModeNames(), ", "))) cmd.Flags().BoolVar(&opts.Silent, "silent", false, "send messages silently") cmd.Flags().BoolVar(&opts.DryRun, "dry-run", false, "do not actually send messages, just show how they would be sent") cmd.Flags().BoolVar(&opts.Single, "single", false, "do not automatically detect and forward grouped messages") cmd.Flags().BoolVar(&opts.Desc, "desc", false, "forward messages in reverse order for each input peer") return cmd } ================================================ FILE: cmd/gen.go ================================================ package cmd import ( "fmt" "os" "path" "path/filepath" "strings" "github.com/go-faster/errors" "github.com/spf13/cobra" "github.com/spf13/cobra/doc" "github.com/iyear/tdl/core/util/fsutil" ) func NewGen() *cobra.Command { cmd := &cobra.Command{ Use: "gen", Short: "A set of gen tools", Hidden: true, } cmd.AddCommand(NewGenDoc()) return cmd } func NewGenDoc() *cobra.Command { var dir string cmd := &cobra.Command{ Use: "doc", Short: "Generate doc", RunE: func(cmd *cobra.Command, args []string) error { const frontmatter = `--- title: "%s" bookHidden: true --- ` cmd.VisitParents(func(c *cobra.Command) { // Disable the "Auto generated by spf13/cobra on DATE" // as it creates a lot of diffs. c.DisableAutoGenTag = true }) if !fsutil.PathExists(dir) { if err := os.MkdirAll(dir, os.ModePerm); err != nil { return errors.Wrap(err, "mkdir") } } prepender := func(filename string) string { name := filepath.Base(filename) base := strings.TrimSuffix(name, path.Ext(name)) return fmt.Sprintf(frontmatter, strings.ReplaceAll(base, "_", " ")) } linkHandler := func(name string) string { base := strings.TrimSuffix(name, path.Ext(name)) return "/more/cli/" + strings.ToLower(base) + "/" } fmt.Println("Generating command-line documentation in", dir, "...") err := doc.GenMarkdownTreeCustom(cmd.Root(), dir, prepender, linkHandler) if err != nil { return errors.Wrap(err, "gendoc") } fmt.Println("Done.") return nil }, } cmd.Flags().StringVarP(&dir, "dir", "d", "", "dir to generate doc") _ = cmd.MarkFlagRequired("dir") return cmd } ================================================ FILE: cmd/login.go ================================================ package cmd import ( "fmt" "strings" "github.com/fatih/color" "github.com/spf13/cobra" "github.com/iyear/tdl/app/login" "github.com/iyear/tdl/core/logctx" ) func NewLogin() *cobra.Command { var ( code bool opts login.Options ) cmd := &cobra.Command{ Use: "login", Short: "Login to Telegram", GroupID: groupAccount.ID, RunE: func(cmd *cobra.Command, args []string) error { color.Yellow("WARN: If data exists in the namespace, data will be overwritten") // Legacy flag if code { return login.Code(logctx.Named(cmd.Context(), "login")) } return login.Run(logctx.Named(cmd.Context(), "login"), opts) }, } const desktop = "desktop" cmd.Flags().VarP(&opts.Type, "type", "T", fmt.Sprintf("login mode: [%s]", strings.Join(login.TypeNames(), ", "))) cmd.Flags().StringVarP(&opts.Desktop, desktop, "d", "", "official desktop client path, and automatically find possible paths if empty") cmd.Flags().StringVarP(&opts.Passcode, "passcode", "p", "", "passcode for desktop client, keep empty if no passcode") // Deprecated cmd.Flags().BoolVar(&code, "code", false, "login with code, instead of importing session from desktop client") // completion and validation _ = cmd.MarkFlagDirname(desktop) _ = cmd.Flags().MarkDeprecated("code", "use `-T code` instead") return cmd } ================================================ FILE: cmd/migrate.go ================================================ package cmd import ( "fmt" "strings" "time" "github.com/spf13/cobra" "github.com/iyear/tdl/app/migrate" "github.com/iyear/tdl/pkg/kv" ) func NewBackup() *cobra.Command { var dst string cmd := &cobra.Command{ Use: "backup", Short: "Backup your data", GroupID: groupAccount.ID, RunE: func(cmd *cobra.Command, args []string) error { if dst == "" { dst = fmt.Sprintf("%s.backup.tdl", time.Now().Format("2006-01-02-15_04_05")) } return migrate.Backup(cmd.Context(), dst) }, } cmd.Flags().StringVarP(&dst, "dst", "d", "", "destination file path. Default: .backup.tdl") return cmd } func NewRecover() *cobra.Command { var file string cmd := &cobra.Command{ Use: "recover", Short: "Recover your data", GroupID: groupAccount.ID, RunE: func(cmd *cobra.Command, args []string) error { return migrate.Recover(cmd.Context(), file) }, } const fileFlag = "file" cmd.Flags().StringVarP(&file, fileFlag, "f", "", "backup file path") // completion and validation _ = cmd.RegisterFlagCompletionFunc(fileFlag, completeExtFiles("tdl")) _ = cmd.MarkFlagRequired(fileFlag) return cmd } func NewMigrate() *cobra.Command { var to map[string]string cmd := &cobra.Command{ Use: "migrate", Short: "Migrate your current data to another storage", GroupID: groupAccount.ID, RunE: func(cmd *cobra.Command, args []string) error { return migrate.Migrate(cmd.Context(), to) }, } cmd.Flags().StringToStringVar(&to, "to", map[string]string{}, fmt.Sprintf("destination storage options, format: type=driver,key1=value1,key2=value2. Available drivers: [%s]", strings.Join(kv.DriverNames(), ","))) return cmd } ================================================ FILE: cmd/root.go ================================================ package cmd import ( "context" "fmt" "net/http" "os" "path/filepath" "strings" "time" "github.com/go-faster/errors" "github.com/gotd/td/telegram" "github.com/ivanpirog/coloredcobra" "github.com/spf13/cobra" "github.com/spf13/viper" "go.uber.org/multierr" "go.uber.org/zap" "golang.org/x/net/proxy" "github.com/iyear/tdl/core/logctx" "github.com/iyear/tdl/core/storage" tclientcore "github.com/iyear/tdl/core/tclient" "github.com/iyear/tdl/core/util/fsutil" "github.com/iyear/tdl/core/util/logutil" "github.com/iyear/tdl/core/util/netutil" "github.com/iyear/tdl/pkg/consts" "github.com/iyear/tdl/pkg/extensions" "github.com/iyear/tdl/pkg/kv" "github.com/iyear/tdl/pkg/tclient" ) var ( defaultBoltPath = filepath.Join(consts.DataDir, "data") DefaultLegacyStorage = map[string]string{ kv.DriverTypeKey: kv.DriverLegacy.String(), "path": filepath.Join(consts.DataDir, "data.kv"), } DefaultBoltStorage = map[string]string{ kv.DriverTypeKey: kv.DriverBolt.String(), "path": defaultBoltPath, } ) // command groups var ( groupAccount = &cobra.Group{ ID: "account", Title: "Account related", } groupTools = &cobra.Group{ ID: "tools", Title: "Tools", } groupExtensions = &cobra.Group{ ID: "extensions", Title: "Extensions", } ) func New() *cobra.Command { // allow PersistentPreRun to be called for every command cobra.EnableTraverseRunHooks = true em := extensions.NewManager(consts.ExtensionsPath) cmd := &cobra.Command{ Use: "tdl", Short: "Telegram Downloader, but more than a downloader", SilenceErrors: true, SilenceUsage: true, PersistentPreRunE: func(cmd *cobra.Command, args []string) error { // init logger debug, level := viper.GetBool(consts.FlagDebug), zap.InfoLevel if debug { level = zap.DebugLevel } cmd.SetContext(logctx.With(cmd.Context(), logutil.New(level, filepath.Join(consts.LogPath, "latest.log")))) ns := viper.GetString(consts.FlagNamespace) if ns != "" { logctx.From(cmd.Context()).Info("Namespace", zap.String("namespace", ns)) } // v0.14.0: default storage changed from legacy to bolt, so we need to auto migrate to keep compatibility if !cmd.Flags().Lookup(consts.FlagStorage).Changed && !fsutil.PathExists(defaultBoltPath) { if err := migrateLegacyToBolt(); err != nil { return errors.Wrap(err, "migrate legacy to bolt") } } stg, err := kv.NewWithMap(viper.GetStringMapString(consts.FlagStorage)) if err != nil { return errors.Wrap(err, "create kv storage") } cmd.SetContext(kv.With(cmd.Context(), stg)) // extension manager client proxy var dialer proxy.ContextDialer = proxy.Direct if p := viper.GetString(consts.FlagProxy); p != "" { if t, err := netutil.NewProxy(p); err == nil { dialer = t } } em.SetClient(&http.Client{Transport: &http.Transport{ DialContext: dialer.DialContext, }}) return nil }, PersistentPostRunE: func(cmd *cobra.Command, args []string) error { return multierr.Combine( kv.From(cmd.Context()).Close(), logctx.From(cmd.Context()).Sync(), ) }, } coloredcobra.Init(&coloredcobra.Config{ RootCmd: cmd, Headings: coloredcobra.HiCyan + coloredcobra.Bold + coloredcobra.Underline, Commands: coloredcobra.HiGreen + coloredcobra.Bold, CmdShortDescr: coloredcobra.None, ExecName: coloredcobra.Bold, Flags: coloredcobra.Bold + coloredcobra.Yellow, FlagsDataType: coloredcobra.Blue, FlagsDescr: coloredcobra.None, Aliases: coloredcobra.None, Example: coloredcobra.None, NoExtraNewlines: true, NoBottomNewline: true, }) cmd.AddGroup(groupAccount, groupTools, groupExtensions) cmd.AddCommand(NewVersion(), NewLogin(), NewDownload(), NewForward(), NewChat(), NewUpload(), NewBackup(), NewRecover(), NewMigrate(), NewGen(), NewExtension(em)) // append extension command to root exts, _ := em.List(context.Background(), false) for _, e := range exts { cmd.AddCommand(NewExtensionCmd(em, e, os.Stdin, os.Stdout, os.Stderr)) } cmd.PersistentFlags().StringToString(consts.FlagStorage, DefaultBoltStorage, fmt.Sprintf("storage options, format: type=driver,key1=value1,key2=value2. Available drivers: [%s]", strings.Join(kv.DriverNames(), ","))) cmd.PersistentFlags().String(consts.FlagProxy, "", "proxy address, format: protocol://username:password@host:port") cmd.PersistentFlags().StringP(consts.FlagNamespace, "n", "default", "namespace for Telegram session") cmd.PersistentFlags().Bool(consts.FlagDebug, false, "enable debug mode") cmd.PersistentFlags().IntP(consts.FlagPartSize, "s", 512*1024, "part size for transfer") _ = cmd.PersistentFlags().MarkDeprecated(consts.FlagPartSize, "part size has been set to maximum by default, this flag will be removed in the future") cmd.PersistentFlags().IntP(consts.FlagThreads, "t", 4, "max threads for transfer one item") cmd.PersistentFlags().IntP(consts.FlagLimit, "l", 2, "max number of concurrent tasks") cmd.PersistentFlags().Int(consts.FlagPoolSize, 8, "specify the size of the DC pool, zero means infinity") cmd.PersistentFlags().Duration(consts.FlagDelay, 0, "delay between each task, zero means no delay") cmd.PersistentFlags().String(consts.FlagNTP, "", "ntp server host, if not set, use system time") cmd.PersistentFlags().Duration(consts.FlagReconnectTimeout, 5*time.Minute, "Telegram client reconnection backoff timeout, infinite if set to 0") // #158 // completion _ = cmd.RegisterFlagCompletionFunc(consts.FlagNamespace, func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { engine := kv.From(cmd.Context()) ns, err := engine.Namespaces() if err != nil { return nil, cobra.ShellCompDirectiveNoFileComp } return ns, cobra.ShellCompDirectiveNoFileComp }) _ = viper.BindPFlags(cmd.PersistentFlags()) viper.SetEnvPrefix("tdl") viper.SetEnvKeyReplacer(strings.NewReplacer("-", "_")) viper.AutomaticEnv() // extension command format: , // which means parse args layer by layer. But common command flags are flat. // To keep compatibility, we only set TraverseChildren to true for extension // command instead of other commands. foundCmd, _, err := cmd.Find(os.Args[1:]) if err == nil && foundCmd.GroupID == groupExtensions.ID { cmd.TraverseChildren = true // allow global config to be parsed before extension command is executed } return cmd } type completeFunc func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) func completeExtFiles(ext ...string) completeFunc { return func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { files := make([]string, 0) for _, e := range ext { f, err := filepath.Glob(toComplete + "*." + e) if err != nil { return nil, cobra.ShellCompDirectiveDefault } files = append(files, f...) } return files, cobra.ShellCompDirectiveFilterDirs } } func tOptions(ctx context.Context) (tclient.Options, error) { // init tclient kv kvd, err := kv.From(ctx).Open(viper.GetString(consts.FlagNamespace)) if err != nil { return tclient.Options{}, errors.Wrap(err, "open kv storage") } o := tclient.Options{ KV: kvd, Proxy: viper.GetString(consts.FlagProxy), NTP: viper.GetString(consts.FlagNTP), ReconnectTimeout: viper.GetDuration(consts.FlagReconnectTimeout), UpdateHandler: nil, } return o, nil } func tRun(ctx context.Context, f func(ctx context.Context, c *telegram.Client, kvd storage.Storage) error, middlewares ...telegram.Middleware) error { o, err := tOptions(ctx) if err != nil { return errors.Wrap(err, "build telegram options") } client, err := tclient.New(ctx, o, false, middlewares...) if err != nil { return errors.Wrap(err, "create client") } return tclientcore.RunWithAuth(ctx, client, func(ctx context.Context) error { return f(ctx, client, o.KV) }) } func migrateLegacyToBolt() (rerr error) { legacy, err := kv.NewWithMap(DefaultLegacyStorage) if err != nil { return errors.Wrap(err, "create legacy kv storage") } defer multierr.AppendInvoke(&rerr, multierr.Close(legacy)) bolt, err := kv.NewWithMap(DefaultBoltStorage) if err != nil { return errors.Wrap(err, "create bolt kv storage") } defer multierr.AppendInvoke(&rerr, multierr.Close(bolt)) meta, err := legacy.MigrateTo() if err != nil { return errors.Wrap(err, "migrate legacy to bolt") } return bolt.MigrateFrom(meta) } ================================================ FILE: cmd/up.go ================================================ package cmd import ( "context" "errors" "github.com/gotd/td/telegram" "github.com/spf13/cobra" "github.com/iyear/tdl/app/up" "github.com/iyear/tdl/core/logctx" "github.com/iyear/tdl/core/storage" ) func NewUpload() *cobra.Command { var opts up.Options cmd := &cobra.Command{ Use: "upload", Aliases: []string{"up"}, Short: "Upload anything to Telegram", GroupID: groupTools.ID, RunE: func(cmd *cobra.Command, args []string) error { return tRun(cmd.Context(), func(ctx context.Context, c *telegram.Client, kvd storage.Storage) error { if opts.Thread != 0 && opts.Chat == "" { return errors.New("error flags: --chat should be set when --topic is set") } if opts.Chat != "" && opts.To != "" { return errors.New("conflicting flags: --chat and --to cannot be set at the same time") } return up.Run(logctx.Named(ctx, "up"), c, kvd, opts) }) }, } const ( _chat = "chat" path = "path" include = "include" exclude = "exclude" ) cmd.Flags().StringVarP(&opts.Chat, _chat, "c", "", "chat id or domain, and empty means 'Saved Messages'. Can be used together with --topic flag. Conflicts with --to flag.") cmd.Flags().IntVar(&opts.Thread, "topic", 0, "specify topic id. Must be used together with --chat flag. Conflicts with --to flag.") cmd.Flags().StringVar(&opts.To, "to", "", "destination peer, can be a CHAT or router based on expression engine. Conflicts with --chat and --topic flag.") cmd.Flags().StringSliceVarP(&opts.Paths, path, "p", []string{}, "dirs or files") cmd.Flags().StringSliceVarP(&opts.Includes, include, "i", []string{}, "include the specified file extensions") cmd.Flags().StringSliceVarP(&opts.Excludes, exclude, "e", []string{}, "exclude the specified file extensions") cmd.Flags().BoolVar(&opts.Remove, "rm", false, "remove the uploaded files after uploading") cmd.Flags().BoolVar(&opts.Photo, "photo", false, "upload the image as a photo instead of a file") cmd.Flags().StringVar(&opts.Caption, "caption", `""+FileName+" - "+MIME+""`, "caption for the uploaded media") // completion and validation _ = cmd.MarkFlagRequired(path) cmd.MarkFlagsMutuallyExclusive(include, exclude) return cmd } ================================================ FILE: cmd/version.go ================================================ package cmd import ( "bytes" _ "embed" "runtime" "text/template" "github.com/fatih/color" "github.com/spf13/cobra" "github.com/iyear/tdl/pkg/consts" ) //go:embed version.tmpl var version string func NewVersion() *cobra.Command { return &cobra.Command{ Use: "version", Short: "Check the version info", RunE: func(cmd *cobra.Command, args []string) error { buf := &bytes.Buffer{} if err := template.Must(template.New("version").Parse(version)).Execute(buf, map[string]interface{}{ "Version": consts.Version, "Commit": consts.Commit, "Date": consts.CommitDate, "GoVersion": runtime.Version(), "GOOS": runtime.GOOS, "GOARCH": runtime.GOARCH, }); err != nil { return err } color.Blue(buf.String()) return nil }, } } ================================================ FILE: cmd/version.tmpl ================================================ Version: {{ .Version }} Commit: {{ .Commit }} Date: {{ .Date }} {{ .GoVersion }} {{ .GOOS }}/{{ .GOARCH }} ================================================ FILE: core/dcpool/dcpool.go ================================================ package dcpool import ( "context" "sync" "github.com/gotd/td/telegram" "github.com/gotd/td/tg" "go.uber.org/multierr" "go.uber.org/zap" "github.com/iyear/tdl/core/logctx" "github.com/iyear/tdl/core/middlewares/takeout" ) var testMode = false // EnableTestMode enables test mode, which disables takeout and pooling and directly returns original client. func EnableTestMode() { testMode = true } type Pool interface { Client(ctx context.Context, dc int) *tg.Client Takeout(ctx context.Context, dc int) *tg.Client Default(ctx context.Context) *tg.Client Close() error } type pool struct { api *telegram.Client size int64 mu *sync.Mutex middlewares []telegram.Middleware invokers map[int]tg.Invoker closes map[int]func() error takeout int64 } func NewPool(c *telegram.Client, size int64, middlewares ...telegram.Middleware) Pool { return &pool{ api: c, size: size, mu: &sync.Mutex{}, middlewares: middlewares, invokers: make(map[int]tg.Invoker), closes: make(map[int]func() error), takeout: 0, } } func (p *pool) current() int { return p.api.Config().ThisDC } func (p *pool) Client(ctx context.Context, dc int) *tg.Client { p.mu.Lock() defer p.mu.Unlock() return tg.NewClient(p.invoker(ctx, dc)) } func (p *pool) invoker(ctx context.Context, dc int) tg.Invoker { // self-hosted Telegram server can't properly handle pooling connections, // so directly return original client if testMode { return p.api } if i, ok := p.invokers[dc]; ok { return i } // lazy init var ( invoker telegram.CloseInvoker err error ) if dc == p.current() { // can't transfer dc to current dc invoker, err = p.api.Pool(p.size) } else { invoker, err = p.api.DC(ctx, dc, p.size) } if err != nil { logctx.From(ctx).Error("create invoker", zap.Error(err)) return p.api // degraded } p.closes[dc] = invoker.Close p.invokers[dc] = chainMiddlewares(invoker, p.middlewares...) return p.invokers[dc] } func (p *pool) Default(ctx context.Context) *tg.Client { return p.Client(ctx, p.current()) } func (p *pool) Close() (err error) { if p.takeout != 0 { err = takeout.UnTakeout(context.TODO(), p.Takeout(context.TODO(), p.current()).Invoker()) } for _, c := range p.closes { err = multierr.Append(err, c()) } return err } func (p *pool) Takeout(ctx context.Context, dc int) *tg.Client { p.mu.Lock() defer p.mu.Unlock() // lazy init if p.takeout == 0 { sid, err := takeout.Takeout(ctx, p.api) if err != nil { logctx.From(ctx).Warn("takeout error", zap.Error(err)) // ignore init delay error and return non-takeout client return p.Client(ctx, dc) } p.takeout = sid logctx.From(ctx).Info("get takeout id", zap.Int64("id", sid)) } return tg.NewClient(chainMiddlewares(p.invoker(ctx, dc), takeout.Middleware(p.takeout))) } ================================================ FILE: core/dcpool/middlewares.go ================================================ package dcpool import ( "github.com/gotd/td/telegram" "github.com/gotd/td/tg" ) func chainMiddlewares(invoker tg.Invoker, chain ...telegram.Middleware) tg.Invoker { if len(chain) == 0 { return invoker } for i := len(chain) - 1; i >= 0; i-- { invoker = chain[i].Handle(invoker) } return invoker } ================================================ FILE: core/downloader/downloader.go ================================================ package downloader import ( "context" "github.com/go-faster/errors" "github.com/gotd/td/telegram/downloader" "go.uber.org/zap" "golang.org/x/sync/errgroup" "github.com/iyear/tdl/core/dcpool" "github.com/iyear/tdl/core/logctx" "github.com/iyear/tdl/core/util/tutil" ) // MaxPartSize refer to https://core.telegram.org/api/files#downloading-files const MaxPartSize = 1024 * 1024 type Downloader struct { opts Options } type Options struct { Pool dcpool.Pool Threads int Iter Iter Progress Progress } func New(opts Options) *Downloader { return &Downloader{ opts: opts, } } func (d *Downloader) Download(ctx context.Context, limit int) error { wg, wgctx := errgroup.WithContext(ctx) wg.SetLimit(limit) for d.opts.Iter.Next(wgctx) { elem := d.opts.Iter.Value() wg.Go(func() (rerr error) { d.opts.Progress.OnAdd(elem) defer func() { d.opts.Progress.OnDone(elem, rerr) }() if err := d.download(wgctx, elem); err != nil { // canceled by user, so we directly return error to stop all if errors.Is(err, context.Canceled) { return errors.Wrap(err, "download") } // don't return error, just log it logctx. From(ctx). Error("Download error", zap.Any("element", elem), zap.Error(err), ) } return nil }) } if err := d.opts.Iter.Err(); err != nil { return errors.Wrap(err, "iter") } return wg.Wait() } func (d *Downloader) download(ctx context.Context, elem Elem) error { select { case <-ctx.Done(): return ctx.Err() default: } logctx.From(ctx).Debug("Start download elem", zap.Any("elem", elem)) client := d.opts.Pool.Client(ctx, elem.File().DC()) if elem.AsTakeout() { client = d.opts.Pool.Takeout(ctx, elem.File().DC()) } _, err := downloader.NewDownloader().WithPartSize(MaxPartSize). Download(client, elem.File().Location()). WithThreads(tutil.BestThreads(elem.File().Size(), d.opts.Threads)). Parallel(ctx, newWriteAt(elem, d.opts.Progress, MaxPartSize)) if err != nil { return errors.Wrap(err, "download") } return nil } ================================================ FILE: core/downloader/iter.go ================================================ package downloader import ( "context" "io" "github.com/gotd/td/tg" ) type Iter interface { Next(ctx context.Context) bool Value() Elem Err() error } type Elem interface { File() File To() io.WriterAt AsTakeout() bool } type File interface { Location() tg.InputFileLocationClass Size() int64 DC() int } ================================================ FILE: core/downloader/progress.go ================================================ package downloader import ( "time" "go.uber.org/atomic" ) type Progress interface { OnAdd(elem Elem) OnDownload(elem Elem, state ProgressState) OnDone(elem Elem, err error) // TODO: OnLog to log something that is not an error but should be sent to the user } type ProgressState struct { Downloaded int64 Total int64 } // writeAt wrapper for file to use progress bar // // do not need mutex because gotd has use syncio.WriteAt type writeAt struct { elem Elem progress Progress partSize int downloaded *atomic.Int64 } func newWriteAt(elem Elem, progress Progress, partSize int) *writeAt { return &writeAt{ elem: elem, progress: progress, partSize: partSize, downloaded: atomic.NewInt64(0), } } func (w *writeAt) WriteAt(p []byte, off int64) (int, error) { at, err := w.elem.To().WriteAt(p, off) if err != nil { return 0, err } // some small files may finish too fast, terminal history may not be overwritten // this is just a simple way to avoid the problem if at < w.partSize { // last part(every file only exec once) time.Sleep(time.Millisecond * 200) // to ensure the progress render next time } w.progress.OnDownload(w.elem, ProgressState{ Downloaded: w.downloaded.Add(int64(at)), Total: w.elem.File().Size(), }) return at, nil } ================================================ FILE: core/forwarder/clone.go ================================================ package forwarder import ( "context" "io" "os" "github.com/go-faster/errors" "github.com/gotd/td/telegram/downloader" "github.com/gotd/td/telegram/uploader" "github.com/gotd/td/tg" "go.uber.org/atomic" "go.uber.org/multierr" tdownloader "github.com/iyear/tdl/core/downloader" "github.com/iyear/tdl/core/tmedia" tuploader "github.com/iyear/tdl/core/uploader" "github.com/iyear/tdl/core/util/tutil" ) type cloneOptions struct { elem Elem media *tmedia.Media progress progressAdd } type progressAdd interface { add(n int64) } func (f *Forwarder) cloneMedia(ctx context.Context, opts cloneOptions, dryRun bool) (_ tg.InputFileClass, rerr error) { // if dry run, just return empty input file if dryRun { // directly call progress callback opts.progress.add(opts.media.Size * 2) return &tg.InputFile{}, nil } temp, err := os.CreateTemp("", "tdl_*") if err != nil { return nil, errors.Wrap(err, "create temp file") } defer func() { multierr.AppendInto(&rerr, temp.Close()) multierr.AppendInto(&rerr, os.Remove(temp.Name())) }() threads := tutil.BestThreads(opts.media.Size, f.opts.Threads) _, err = downloader.NewDownloader(). WithPartSize(tdownloader.MaxPartSize). Download(f.opts.Pool.Client(ctx, opts.media.DC), opts.media.InputFileLoc). WithThreads(threads). Parallel(ctx, writeAt{ f: temp, opts: opts, }) if err != nil { return nil, errors.Wrap(err, "download") } var file tg.InputFileClass if _, err = temp.Seek(0, io.SeekStart); err != nil { return nil, errors.Wrap(err, "seek") } upload := uploader.NewUpload(opts.media.Name, temp, opts.media.Size) file, err = uploader.NewUploader(f.opts.Pool.Default(ctx)). WithPartSize(tuploader.MaxPartSize). WithThreads(threads). WithProgress(uploaded{ opts: opts, prev: atomic.NewInt64(0), }). Upload(ctx, upload) if err != nil { return nil, errors.Wrap(err, "upload") } return file, nil } type writeAt struct { f io.WriterAt opts cloneOptions } func (w writeAt) WriteAt(p []byte, off int64) (int, error) { n, err := w.f.WriteAt(p, off) if err != nil { return 0, err } w.opts.progress.add(int64(n)) return n, nil } type uploaded struct { opts cloneOptions prev *atomic.Int64 } func (u uploaded) Chunk(_ context.Context, state uploader.ProgressState) error { u.opts.progress.add(state.Uploaded - u.prev.Swap(state.Uploaded)) return nil } ================================================ FILE: core/forwarder/forwarder.go ================================================ package forwarder import ( "context" "math/rand" "time" "github.com/go-faster/errors" "github.com/gotd/td/bin" "github.com/gotd/td/telegram/peers" "github.com/gotd/td/tg" "go.uber.org/atomic" "go.uber.org/zap" "github.com/iyear/tdl/core/dcpool" "github.com/iyear/tdl/core/logctx" "github.com/iyear/tdl/core/tmedia" "github.com/iyear/tdl/core/util/tutil" ) //go:generate go-enum --values --names --flag --nocase // Mode // ENUM(direct, clone) type Mode int type Options struct { Pool dcpool.Pool Threads int Iter Iter Progress Progress } type Forwarder struct { sent map[tuple]struct{} // used to filter grouped messages which are already sent rand *rand.Rand opts Options } type tuple struct { from int64 msg int } func New(opts Options) *Forwarder { return &Forwarder{ sent: make(map[tuple]struct{}), rand: rand.New(rand.NewSource(time.Now().UnixNano())), opts: opts, } } func (f *Forwarder) Forward(ctx context.Context) error { for f.opts.Iter.Next(ctx) { elem := f.opts.Iter.Value() if _, ok := f.sent[f.tuple(elem.From(), elem.Msg())]; ok { // skip grouped messages continue } if _, ok := elem.Msg().GetGroupedID(); ok && elem.AsGrouped() { grouped, err := tutil.GetGroupedMessages(ctx, f.opts.Pool.Default(ctx), elem.From().InputPeer(), elem.Msg()) if err != nil { continue } if err = f.forwardMessage(ctx, elem, grouped...); err != nil { continue } continue } if err := f.forwardMessage(ctx, elem); err != nil { // canceled by user, so we directly return error to stop all if errors.Is(err, context.Canceled) { return err } continue } } return f.opts.Iter.Err() } func (f *Forwarder) forwardMessage(ctx context.Context, elem Elem, grouped ...*tg.Message) (rerr error) { f.opts.Progress.OnAdd(elem) defer func() { f.sent[f.tuple(elem.From(), elem.Msg())] = struct{}{} // grouped message also should be marked as sent for _, m := range grouped { f.sent[f.tuple(elem.From(), m)] = struct{}{} } f.opts.Progress.OnDone(elem, rerr) }() log := logctx.From(ctx).With( zap.Int64("from", elem.From().ID()), zap.Int64("to", elem.To().ID()), zap.Int("message", elem.Msg().ID)) // used for clone progress totalSize, err := mediaSizeSum(elem.Msg(), grouped...) if err != nil { return errors.Wrap(err, "media total size") } done := atomic.NewInt64(0) forwardTextOnly := func(msg *tg.Message) error { if msg.Message == "" { return errors.Errorf("empty message content, skip send: %d", msg.ID) } req := &tg.MessagesSendMessageRequest{ NoWebpage: false, Silent: elem.AsSilent(), Background: false, ClearDraft: false, Noforwards: false, UpdateStickersetsOrder: false, Peer: elem.To().InputPeer(), ReplyTo: getReplyTo(elem.Thread()), Message: msg.Message, RandomID: f.rand.Int63(), ReplyMarkup: msg.ReplyMarkup, Entities: msg.Entities, ScheduleDate: 0, SendAs: nil, } req.SetFlags() if _, err := f.forwardClient(ctx, elem).MessagesSendMessage(ctx, req); err != nil { return errors.Wrap(err, "send message") } return nil } convForwardedMedia := func(msg *tg.Message) (tg.InputMediaClass, error) { if _, hasMedia := msg.GetMedia(); !hasMedia { // media can't be forwarded via simple copy(it depends on the server ids) // if it's not a media message, just break and send text copy return nil, errors.Errorf("message %d is not a media message", msg.ID) } // if it's a media message, but it's not protected, convert it to InputMediaClass // or if it's protected, but it doesn't contain photo or document, // we should clone photo and document via re-upload, it will be banned if we forward it directly. // but other media can be forwarded directly via copy if (!protectedDialog(elem.From()) && !protectedMessage(msg)) || !photoOrDocument(msg.Media) { media, ok := tmedia.ConvInputMedia(msg.Media) if !ok { return nil, errors.Errorf("can't convert message %d to input class directly", msg.ID) } return media, nil } media, ok := tmedia.GetMedia(msg) if !ok { log.Warn("Can't get media from message", zap.Int64("peer", elem.From().ID()), zap.Int("message", msg.ID)) // unsupported re-upload media return nil, errors.Errorf("unsupported media %T", msg.Media) } mediaFile, err := f.cloneMedia(ctx, cloneOptions{ elem: elem, media: media, progress: &wrapProgress{ elem: elem, progress: f.opts.Progress, done: done, total: totalSize * 2, }, }, elem.AsDryRun()) if err != nil { return nil, errors.Wrap(err, "clone media") } var inputMedia tg.InputMediaClass // now we only have to process cloned photo or document switch m := msg.Media.(type) { case *tg.MessageMediaPhoto: photo := &tg.InputMediaUploadedPhoto{ Spoiler: m.Spoiler, File: mediaFile, TTLSeconds: m.TTLSeconds, } photo.SetFlags() inputMedia = photo case *tg.MessageMediaDocument: doc, ok := m.Document.AsNotEmpty() if !ok { return nil, errors.Errorf("empty document %d", msg.ID) } document := &tg.InputMediaUploadedDocument{ NosoundVideo: false, // do not set ForceFile: false, // do not set Spoiler: m.Spoiler, File: mediaFile, MimeType: doc.MimeType, Attributes: doc.Attributes, Stickers: nil, // do not set TTLSeconds: 0, // do not set } if thumb, ok := tmedia.GetDocumentThumb(doc); ok { thumbFile, err := f.cloneMedia(ctx, cloneOptions{ elem: elem, media: thumb, progress: nopProgress{}, }, elem.AsDryRun()) if err != nil { return nil, errors.Wrap(err, "clone thumb") } document.Thumb = thumbFile } document.SetFlags() inputMedia = document default: return nil, errors.Errorf("unsupported media %T", msg.Media) } // note that they must be separately uploaded using messages uploadMedia first, // using raw inputMediaUploaded* constructors is not supported. messageMedia, err := f.forwardClient(ctx, elem).MessagesUploadMedia(ctx, &tg.MessagesUploadMediaRequest{ Peer: elem.To().InputPeer(), Media: inputMedia, }) if err != nil { return nil, errors.Wrap(err, "upload media") } inputMedia, ok = tmedia.ConvInputMedia(messageMedia) if !ok && !elem.AsDryRun() { return nil, errors.Errorf("can't convert uploaded media to input class") } return inputMedia, nil } switch elem.Mode() { case ModeDirect: // it can be forwarded via API if !protectedDialog(elem.From()) && !protectedMessage(elem.Msg()) { directForward := func(ids ...int) error { randIDs := make([]int64, 0, len(ids)) for range ids { randIDs = append(randIDs, f.rand.Int63()) } req := &tg.MessagesForwardMessagesRequest{ Silent: elem.AsSilent(), Background: false, WithMyScore: false, DropAuthor: false, DropMediaCaptions: false, Noforwards: false, FromPeer: elem.From().InputPeer(), ID: ids, RandomID: randIDs, ToPeer: elem.To().InputPeer(), TopMsgID: elem.Thread(), ScheduleDate: 0, SendAs: nil, } req.SetFlags() if _, err := f.forwardClient(ctx, elem).MessagesForwardMessages(ctx, req); err != nil { return errors.Wrap(err, "directly forward") } return nil } if len(grouped) > 0 { ids := make([]int, 0, len(grouped)) for _, m := range grouped { ids = append(ids, m.ID) } if err = directForward(ids...); err != nil { goto fallback } return nil } if err = directForward(elem.Msg().ID); err != nil { goto fallback } return nil } fallback: fallthrough case ModeClone: if len(grouped) > 0 { media := make([]tg.InputSingleMedia, 0, len(grouped)) for _, gm := range grouped { m, err := convForwardedMedia(gm) if err != nil { log.Debug("Can't convert forwarded media", zap.Error(err)) continue } single := tg.InputSingleMedia{ Media: m, RandomID: f.rand.Int63(), Message: gm.Message, Entities: gm.Entities, } single.SetFlags() media = append(media, single) } if len(media) > 0 { req := &tg.MessagesSendMultiMediaRequest{ Silent: elem.AsSilent(), Background: false, ClearDraft: false, Noforwards: false, UpdateStickersetsOrder: false, Peer: elem.To().InputPeer(), ReplyTo: getReplyTo(elem.Thread()), MultiMedia: media, ScheduleDate: 0, SendAs: nil, } req.SetFlags() if _, err := f.forwardClient(ctx, elem).MessagesSendMultiMedia(ctx, req); err != nil { return errors.Wrap(err, "send multi media") } return nil } return forwardTextOnly(elem.Msg()) } media, err := convForwardedMedia(elem.Msg()) if err != nil { log.Debug("Can't convert forwarded media", zap.Error(err)) return forwardTextOnly(elem.Msg()) } // send text copy with forwarded media req := &tg.MessagesSendMediaRequest{ Silent: elem.AsSilent(), Background: false, ClearDraft: false, Noforwards: false, UpdateStickersetsOrder: false, Peer: elem.To().InputPeer(), ReplyTo: getReplyTo(elem.Thread()), Media: media, Message: elem.Msg().Message, RandomID: rand.Int63(), ReplyMarkup: elem.Msg().ReplyMarkup, Entities: elem.Msg().Entities, ScheduleDate: 0, SendAs: nil, } req.SetFlags() if _, err := f.forwardClient(ctx, elem).MessagesSendMedia(ctx, req); err != nil { return errors.Wrap(err, "send single media") } return nil } return errors.Errorf("unsupported mode %v", elem.Mode()) } func (f *Forwarder) tuple(peer peers.Peer, msg *tg.Message) tuple { return tuple{ from: peer.ID(), msg: msg.ID, } } type nopInvoker struct{} func (n nopInvoker) Invoke(_ context.Context, _ bin.Encoder, _ bin.Decoder) error { return nil } type nopProgress struct{} func (nopProgress) add(_ int64) {} type wrapProgress struct { elem Elem progress ProgressClone done *atomic.Int64 total int64 } func (w *wrapProgress) add(n int64) { w.progress.OnClone(w.elem, ProgressState{ Done: w.done.Add(n), Total: w.total, }) } func (f *Forwarder) forwardClient(ctx context.Context, elem Elem) *tg.Client { if elem.AsDryRun() { return tg.NewClient(nopInvoker{}) } return f.opts.Pool.Default(ctx) } func protectedDialog(peer peers.Peer) bool { switch p := peer.(type) { case peers.Chat: return p.Raw().GetNoforwards() case peers.Channel: return p.Raw().GetNoforwards() } return false } func protectedMessage(msg *tg.Message) bool { return msg.GetNoforwards() } func photoOrDocument(media tg.MessageMediaClass) bool { switch media.(type) { case *tg.MessageMediaPhoto, *tg.MessageMediaDocument: return true default: return false } } func mediaSizeSum(msg *tg.Message, grouped ...*tg.Message) (int64, error) { if len(grouped) > 0 { total := int64(0) for _, gm := range grouped { m, ok := tmedia.GetMedia(gm) if !ok { return 0, errors.Errorf("can't get media from message %d", gm.ID) } total += m.Size } return total, nil } m, ok := tmedia.GetMedia(msg) if !ok { // maybe it's a text only message return 0, nil } return m.Size, nil } func getReplyTo(thread int) tg.InputReplyToClass { replyTo := &tg.InputReplyToMessage{ ReplyToMsgID: thread, } replyTo.SetFlags() return replyTo } ================================================ FILE: core/forwarder/forwarder_enum.go ================================================ // Code generated by go-enum DO NOT EDIT. // Version: 0.5.8 // Revision: 3d844c8ecc59661ed7aa17bfd65727bc06a60ad8 // Build Date: 2023-09-18T14:55:21Z // Built By: goreleaser package forwarder import ( "fmt" "strings" ) const ( // ModeDirect is a Mode of type Direct. ModeDirect Mode = iota // ModeClone is a Mode of type Clone. ModeClone ) var ErrInvalidMode = fmt.Errorf("not a valid Mode, try [%s]", strings.Join(_ModeNames, ", ")) const _ModeName = "directclone" var _ModeNames = []string{ _ModeName[0:6], _ModeName[6:11], } // ModeNames returns a list of possible string values of Mode. func ModeNames() []string { tmp := make([]string, len(_ModeNames)) copy(tmp, _ModeNames) return tmp } // ModeValues returns a list of the values for Mode func ModeValues() []Mode { return []Mode{ ModeDirect, ModeClone, } } var _ModeMap = map[Mode]string{ ModeDirect: _ModeName[0:6], ModeClone: _ModeName[6:11], } // String implements the Stringer interface. func (x Mode) String() string { if str, ok := _ModeMap[x]; ok { return str } return fmt.Sprintf("Mode(%d)", x) } // IsValid provides a quick way to determine if the typed value is // part of the allowed enumerated values func (x Mode) IsValid() bool { _, ok := _ModeMap[x] return ok } var _ModeValue = map[string]Mode{ _ModeName[0:6]: ModeDirect, strings.ToLower(_ModeName[0:6]): ModeDirect, _ModeName[6:11]: ModeClone, strings.ToLower(_ModeName[6:11]): ModeClone, } // ParseMode attempts to convert a string to a Mode. func ParseMode(name string) (Mode, error) { if x, ok := _ModeValue[name]; ok { return x, nil } // Case insensitive parse, do a separate lookup to prevent unnecessary cost of lowercasing a string if we don't need to. if x, ok := _ModeValue[strings.ToLower(name)]; ok { return x, nil } return Mode(0), fmt.Errorf("%s is %w", name, ErrInvalidMode) } // Set implements the Golang flag.Value interface func. func (x *Mode) Set(val string) error { v, err := ParseMode(val) *x = v return err } // Get implements the Golang flag.Getter interface func. func (x *Mode) Get() interface{} { return *x } // Type implements the github.com/spf13/pFlag Value interface. func (x *Mode) Type() string { return "Mode" } ================================================ FILE: core/forwarder/iter.go ================================================ package forwarder import ( "context" "github.com/gotd/td/telegram/peers" "github.com/gotd/td/tg" ) type Iter interface { Next(ctx context.Context) bool Value() Elem Err() error } type Elem interface { Mode() Mode From() peers.Peer Msg() *tg.Message To() peers.Peer Thread() int // reply to message/topic AsSilent() bool AsDryRun() bool AsGrouped() bool // detect and forward grouped messages } ================================================ FILE: core/forwarder/progress.go ================================================ package forwarder type ProgressClone interface { OnClone(elem Elem, state ProgressState) } type Progress interface { OnAdd(elem Elem) ProgressClone OnDone(elem Elem, err error) } type ProgressState struct { Done int64 Total int64 } ================================================ FILE: core/go.mod ================================================ module github.com/iyear/tdl/core go 1.25.8 require ( github.com/cenkalti/backoff/v4 v4.3.0 github.com/gabriel-vasile/mimetype v1.4.13 github.com/go-faster/errors v0.7.1 github.com/gotd/contrib v0.20.0 github.com/gotd/td v0.122.0 github.com/iyear/connectproxy v0.1.1 github.com/samber/lo v1.53.0 github.com/yapingcat/gomedia v0.0.0-20240601043430-920523f8e5c7 go.uber.org/atomic v1.11.0 go.uber.org/multierr v1.11.0 go.uber.org/zap v1.27.1 golang.org/x/net v0.51.0 golang.org/x/sync v0.19.0 gopkg.in/natefinch/lumberjack.v2 v2.2.1 ) require ( github.com/beevik/ntp v1.3.1 // indirect github.com/coder/websocket v1.8.13 // indirect github.com/dlclark/regexp2 v1.11.5 // indirect github.com/fatih/color v1.18.0 // indirect github.com/ghodss/yaml v1.0.0 // indirect github.com/go-faster/jx v1.1.0 // indirect github.com/go-faster/xor v1.0.0 // indirect github.com/go-faster/yaml v0.4.6 // indirect github.com/google/uuid v1.6.0 // indirect github.com/gotd/ige v0.2.2 // indirect github.com/gotd/neo v0.1.5 // indirect github.com/klauspost/compress v1.18.0 // indirect github.com/mattn/go-colorable v0.1.13 // indirect github.com/mattn/go-isatty v0.0.20 // indirect github.com/ogen-go/ogen v1.10.1 // indirect github.com/segmentio/asm v1.2.0 // indirect go.opentelemetry.io/otel v1.35.0 // indirect go.opentelemetry.io/otel/metric v1.35.0 // indirect go.opentelemetry.io/otel/trace v1.35.0 // indirect golang.org/x/crypto v0.48.0 // indirect golang.org/x/exp v0.0.0-20230725093048-515e97ebf090 // indirect golang.org/x/mod v0.32.0 // indirect golang.org/x/sys v0.41.0 // indirect golang.org/x/text v0.34.0 // indirect golang.org/x/tools v0.41.0 // indirect gopkg.in/yaml.v2 v2.4.0 // indirect rsc.io/qr v0.2.0 // indirect ) ================================================ FILE: core/go.sum ================================================ github.com/beevik/ntp v1.3.1 h1:Y/srlT8L1yQr58kyPWFPZIxRL8ttx2SRIpVYJqZIlAM= github.com/beevik/ntp v1.3.1/go.mod h1:fT6PylBq86Tsq23ZMEe47b7QQrZfYBFPnpzt0a9kJxw= github.com/cenkalti/backoff/v4 v4.3.0 h1:MyRJ/UdXutAwSAT+s3wNd7MfTIcy71VQueUuFK343L8= github.com/cenkalti/backoff/v4 v4.3.0/go.mod h1:Y3VNntkOUPxTVeUxJ/G5vcM//AlwfmyYozVcomhLiZE= github.com/coder/websocket v1.8.13 h1:f3QZdXy7uGVz+4uCJy2nTZyM0yTBj8yANEHhqlXZ9FE= github.com/coder/websocket v1.8.13/go.mod h1:LNVeNrXQZfe5qhS9ALED3uA+l5pPqvwXg3CKoDBB2gs= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/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/fatih/color v1.18.0 h1:S8gINlzdQ840/4pfAwic/ZE0djQEH3wM94VfqLTZcOM= github.com/fatih/color v1.18.0/go.mod h1:4FelSpRwEGDpQ12mAdzqdOukCy4u8WUtOY6lkT/6HfU= github.com/gabriel-vasile/mimetype v1.4.13 h1:46nXokslUBsAJE/wMsp5gtO500a4F3Nkz9Ufpk2AcUM= github.com/gabriel-vasile/mimetype v1.4.13/go.mod h1:d+9Oxyo1wTzWdyVUPMmXFvp4F9tea18J8ufA774AB3s= github.com/ghodss/yaml v1.0.0 h1:wQHKEahhL6wmXdzwWG11gIVCkOv05bNOh+Rxn0yngAk= github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= github.com/go-faster/errors v0.7.1 h1:MkJTnDoEdi9pDabt1dpWf7AA8/BaSYZqibYyhZ20AYg= github.com/go-faster/errors v0.7.1/go.mod h1:5ySTjWFiphBs07IKuiL69nxdfd5+fzh1u7FPGZP2quo= github.com/go-faster/jx v1.1.0 h1:ZsW3wD+snOdmTDy9eIVgQdjUpXRRV4rqW8NS3t+20bg= github.com/go-faster/jx v1.1.0/go.mod h1:vKDNikrKoyUmpzaJ0OkIkRQClNHFX/nF3dnTJZb3skg= github.com/go-faster/xor v0.3.0/go.mod h1:x5CaDY9UKErKzqfRfFZdfu+OSTfoZny3w5Ak7UxcipQ= github.com/go-faster/xor v1.0.0 h1:2o8vTOgErSGHP3/7XwA5ib1FTtUsNtwCoLLBjl31X38= github.com/go-faster/xor v1.0.0/go.mod h1:x5CaDY9UKErKzqfRfFZdfu+OSTfoZny3w5Ak7UxcipQ= github.com/go-faster/yaml v0.4.6 h1:lOK/EhI04gCpPgPhgt0bChS6bvw7G3WwI8xxVe0sw9I= github.com/go-faster/yaml v0.4.6/go.mod h1:390dRIvV4zbnO7qC9FGo6YYutc+wyyUSHBgbXL52eXk= github.com/go-logr/logr v1.4.2 h1:6pFjapn8bFcIbiKo3XT4j/BhANplGihG6tvd+8rYgrY= github.com/go-logr/logr v1.4.2/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/gotd/contrib v0.20.0 h1:1Wc4+HMQiIKYQuGHVwVksIx152HFTP6B5n88dDe0ZYw= github.com/gotd/contrib v0.20.0/go.mod h1:P6o8W4niqhDPHLA0U+SA/L7l3BQHYLULpeHfRSePn9o= github.com/gotd/ige v0.2.2 h1:XQ9dJZwBfDnOGSTxKXBGP4gMud3Qku2ekScRjDWWfEk= github.com/gotd/ige v0.2.2/go.mod h1:tuCRb+Y5Y3eNTo3ypIfNpQ4MFjrnONiL2jN2AKZXmb0= github.com/gotd/neo v0.1.5 h1:oj0iQfMbGClP8xI59x7fE/uHoTJD7NZH9oV1WNuPukQ= github.com/gotd/neo v0.1.5/go.mod h1:9A2a4bn9zL6FADufBdt7tZt+WMhvZoc5gWXihOPoiBQ= github.com/gotd/td v0.122.0 h1:xIqoYI02ElZjj+KxOfvoUjA63m7MGWZkemM4m42aqRE= github.com/gotd/td v0.122.0/go.mod h1:vPC2X2rcRQYAGVr9EgmQgswHcj8Ps0Tt66XylR3CxrI= github.com/iyear/connectproxy v0.1.1 h1:JZOF/62vvwRGBWcgSyWRb0BpKD4FSs0++B5/y5pNE4c= github.com/iyear/connectproxy v0.1.1/go.mod h1:yD4zOmSMQCmwHIT4fk8mg4k2M15z8VoMSoeY6NNJdsA= github.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo= github.com/klauspost/compress v1.18.0/go.mod h1:2Pp+KzxcywXVXMr50+X0Q/Lsb43OQHYWRCY2AiWywWQ= github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA= github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg= github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= github.com/ogen-go/ogen v1.10.1 h1:oeSN8AF9mhTVfapbMuL8pQTF2ToqyW9xXaStmOhHKTA= github.com/ogen-go/ogen v1.10.1/go.mod h1:fXCg9PsNYEzJ8ABdmZ2A7j4hMi9EDHP53jzsNtIM3d0= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 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/samber/lo v1.53.0 h1:t975lj2py4kJPQ6haz1QMgtId2gtmfktACxIXArw3HM= github.com/samber/lo v1.53.0/go.mod h1:4+MXEGsJzbKGaUEQFKBq2xtfuznW9oz/WrgyzMzRoM0= github.com/segmentio/asm v1.2.0 h1:9BQrFxC+YOHJlTlHGkTrFWf59nbL3XnCoFLTwDCI7ys= github.com/segmentio/asm v1.2.0/go.mod h1:BqMnlJP91P8d+4ibuonYZw9mfnzI9HfxselHZr5aAcs= github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA= github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= 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= go.opentelemetry.io/auto/sdk v1.1.0 h1:cH53jehLUN6UFLY71z+NDOiNJqDdPRaXzTel0sJySYA= go.opentelemetry.io/auto/sdk v1.1.0/go.mod h1:3wSPjt5PWp2RhlCcmmOial7AvC4DQqZb7a7wCow3W8A= go.opentelemetry.io/otel v1.35.0 h1:xKWKPxrxB6OtMCbmMY021CqC45J+3Onta9MqjhnusiQ= go.opentelemetry.io/otel v1.35.0/go.mod h1:UEqy8Zp11hpkUrL73gSlELM0DupHoiq72dR+Zqel/+Y= go.opentelemetry.io/otel/metric v1.35.0 h1:0znxYu2SNyuMSQT4Y9WDWej0VpcsxkuklLa4/siN90M= go.opentelemetry.io/otel/metric v1.35.0/go.mod h1:nKVFgxBZ2fReX6IlyW28MgZojkoAkJGaE8CpgeAU3oE= go.opentelemetry.io/otel/trace v1.35.0 h1:dPpEfJu1sDIqruz7BHFG3c7528f6ddfSWfFDVt/xgMs= go.opentelemetry.io/otel/trace v1.35.0/go.mod h1:WUk7DtFp1Aw2MkvqGdwiXYDZZNvA/1J8o6xRXLrIkyc= go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE= go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0= go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE= go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0= go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y= go.uber.org/zap v1.27.1 h1:08RqriUEv8+ArZRYSTXy1LeBScaMpVSTBhCeaZYfMYc= go.uber.org/zap v1.27.1/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E= golang.org/x/crypto v0.48.0 h1:/VRzVqiRSggnhY7gNRxPauEQ5Drw9haKdM0jqfcCFts= golang.org/x/crypto v0.48.0/go.mod h1:r0kV5h3qnFPlQnBSrULhlsRfryS2pmewsg+XfMgkVos= golang.org/x/exp v0.0.0-20230725093048-515e97ebf090 h1:Di6/M8l0O2lCLc6VVRWhgCiApHV8MnQurBnFSHsQtNY= golang.org/x/exp v0.0.0-20230725093048-515e97ebf090/go.mod h1:FXUEEKJgO7OQYeo8N01OfiKP8RXMtf6e8aTskBGqWdc= golang.org/x/mod v0.32.0 h1:9F4d3PHLljb6x//jOyokMv3eX+YDeepZSEo3mFJy93c= golang.org/x/mod v0.32.0/go.mod h1:SgipZ/3h2Ci89DlEtEXWUk/HteuRin+HHhN+WbNhguU= golang.org/x/net v0.51.0 h1:94R/GTO7mt3/4wIKpcR5gkGmRLOuE/2hNGeWq/GBIFo= golang.org/x/net v0.51.0/go.mod h1:aamm+2QF5ogm02fjy5Bb7CQ0WMt1/WVM7FtyaTLlA9Y= golang.org/x/sync v0.0.0-20201207232520-09787c993a3a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.19.0 h1:vV+1eWNmZ5geRlYjzm2adRgW2/mcpevXNg50YZtPCE4= golang.org/x/sync v0.19.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI= golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k= golang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= golang.org/x/text v0.34.0 h1:oL/Qq0Kdaqxa1KbNeMKwQq0reLCCaFtqu2eNuSeNHbk= golang.org/x/text v0.34.0/go.mod h1:homfLqTYRFyVYemLBFl5GgL/DWEiH5wcsQ5gSh1yziA= golang.org/x/tools v0.41.0 h1:a9b8iMweWG+S0OBnlU36rzLp20z1Rp10w+IY2czHTQc= golang.org/x/tools v0.41.0/go.mod h1:XSY6eDqxVNiYgezAVqqCeihT4j1U2CCsqvH3WhQpnlg= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo= gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/natefinch/lumberjack.v2 v2.2.1 h1:bBRl1b0OH9s/DuPhuXpNl+VtCaJXFZ5/uEFST95x9zc= gopkg.in/natefinch/lumberjack.v2 v2.2.1/go.mod h1:YD8tP3GAjkrDg1eZH7EGmyESg/lsYskCTPBJVb9jqSc= 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.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 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= rsc.io/qr v0.2.0/go.mod h1:IF+uZjkb9fqyeF/4tlBoynqmQxUoPfWEKh921coOuXs= ================================================ FILE: core/logctx/logctx.go ================================================ package logctx import ( "context" "go.uber.org/zap" ) type ctxKey struct{} func From(ctx context.Context) *zap.Logger { if l, ok := ctx.Value(ctxKey{}).(*zap.Logger); ok { return l } return zap.NewNop() } func With(ctx context.Context, logger *zap.Logger) context.Context { return context.WithValue(ctx, ctxKey{}, logger) } func Named(ctx context.Context, name string) context.Context { return With(ctx, From(ctx).Named(name)) } ================================================ FILE: core/middlewares/recovery/recovery.go ================================================ package recovery import ( "context" "time" "github.com/cenkalti/backoff/v4" "github.com/go-faster/errors" "github.com/gotd/td/bin" "github.com/gotd/td/telegram" "github.com/gotd/td/tg" "github.com/gotd/td/tgerr" "go.uber.org/zap" "github.com/iyear/tdl/core/logctx" ) type recovery struct { ctx context.Context backoff backoff.BackOff } func New(ctx context.Context, backoff backoff.BackOff) telegram.Middleware { return &recovery{ ctx: ctx, backoff: backoff, } } func (r *recovery) Handle(next tg.Invoker) telegram.InvokeFunc { return func(ctx context.Context, input bin.Encoder, output bin.Decoder) error { log := logctx.From(r.ctx) return backoff.RetryNotify(func() error { if err := next.Invoke(ctx, input, output); err != nil { if r.shouldRecover(ctx, err) { return errors.Wrap(err, "recover") } return backoff.Permanent(err) } return nil }, r.backoff, func(err error, duration time.Duration) { log.Debug("Wait for connection recovery", zap.Error(err), zap.Duration("duration", duration)) }) } } func (r *recovery) shouldRecover(ctx context.Context, err error) bool { // context in recovery is used to stop recovery process by external os signal, otherwise we will wait till max retries when user press ctrl+c select { case <-r.ctx.Done(): return false case <-ctx.Done(): return false default: } // we try recover when encountered any error that is not telegram business error _, ok := tgerr.As(err) return !ok } ================================================ FILE: core/middlewares/retry/retry.go ================================================ package retry import ( "context" "fmt" "github.com/go-faster/errors" "github.com/gotd/td/bin" "github.com/gotd/td/telegram" "github.com/gotd/td/tg" "github.com/gotd/td/tgerr" "go.uber.org/zap" "github.com/iyear/tdl/core/logctx" ) var internalErrors = []string{ "Timedout", // #373 "No workers running", "RPC_CALL_FAIL", "RPC_MCGET_FAIL", "WORKER_BUSY_TOO_LONG_RETRY", // #462 "memory limit exit", // #504 } type retry struct { max int errors []string } func (r retry) Handle(next tg.Invoker) telegram.InvokeFunc { return func(ctx context.Context, input bin.Encoder, output bin.Decoder) error { retries := 0 for retries < r.max { if err := next.Invoke(ctx, input, output); err != nil { if tgerr.Is(err, r.errors...) { logctx.From(ctx).Debug("retry middleware", zap.Int("retries", retries), zap.Error(err)) retries++ continue } return errors.Wrap(err, "retry middleware skip") } return nil } return fmt.Errorf("retry limit reached after %d attempts", r.max) } } // New returns middleware that retries request if it fails with one of provided errors. func New(max int, errors ...string) telegram.Middleware { return retry{ max: max, errors: append(errors, internalErrors...), // #373 } } ================================================ FILE: core/middlewares/takeout/middleware.go ================================================ package takeout import ( "context" "errors" "github.com/gotd/td/bin" "github.com/gotd/td/telegram" "github.com/gotd/td/tg" ) type takeout struct { id int64 } type nopDecoder struct { bin.Encoder } func (n nopDecoder) Decode(_ *bin.Buffer) error { return errors.New("bin.Decoder is not implemented") } func (t takeout) Handle(next tg.Invoker) telegram.InvokeFunc { return func(ctx context.Context, input bin.Encoder, output bin.Decoder) error { return next.Invoke(ctx, &tg.InvokeWithTakeoutRequest{ TakeoutID: t.id, Query: nopDecoder{input}, }, output) } } func Middleware(id int64) telegram.Middleware { return takeout{id: id} } ================================================ FILE: core/middlewares/takeout/takeout.go ================================================ package takeout import ( "context" "github.com/gotd/td/tg" ) func Takeout(ctx context.Context, invoker tg.Invoker) (int64, error) { req := &tg.AccountInitTakeoutSessionRequest{ Contacts: true, MessageUsers: true, MessageChats: true, MessageMegagroups: true, MessageChannels: true, Files: true, FileMaxSize: 4000 * 1024 * 1024, } req.SetFlags() session, err := tg.NewClient(invoker).AccountInitTakeoutSession(ctx, req) if err != nil { return 0, err } return session.ID, nil } // UnTakeout should be called with takeout wrapper invoker func UnTakeout(ctx context.Context, invoker tg.Invoker) error { req := &tg.AccountFinishTakeoutSessionRequest{Success: true} req.SetFlags() _, err := tg.NewClient(invoker).AccountFinishTakeoutSession(ctx, req) return err } ================================================ FILE: core/storage/keygen/keygen.go ================================================ package keygen import ( "bytes" "strings" "sync" ) var keyPool = sync.Pool{ New: func() interface{} { b := &bytes.Buffer{} b.Grow(16) return b }, } func New(indexes ...string) string { buf := keyPool.Get().(*bytes.Buffer) buf.WriteString(strings.Join(indexes, ":")) t := buf.String() buf.Reset() keyPool.Put(buf) return t } ================================================ FILE: core/storage/peers.go ================================================ package storage import ( "context" "encoding/json" "errors" "strconv" "github.com/gotd/td/telegram/peers" "github.com/iyear/tdl/core/storage/keygen" ) type Peers struct { kv Storage } func NewPeers(kv Storage) peers.Storage { return &Peers{kv: kv} } func (p *Peers) Save(ctx context.Context, key peers.Key, value peers.Value) error { bytes, err := json.Marshal(value) if err != nil { return err } return p.kv.Set(ctx, p.key(key), bytes) } func (p *Peers) Find(ctx context.Context, key peers.Key) (peers.Value, bool, error) { data, err := p.kv.Get(ctx, p.key(key)) if err != nil { if errors.Is(err, ErrNotFound) { return peers.Value{}, false, nil } return peers.Value{}, false, err } var value peers.Value if err = json.Unmarshal(data, &value); err != nil { return peers.Value{}, false, err } return value, true, nil } func (p *Peers) SavePhone(ctx context.Context, phone string, _key peers.Key) error { bytes, err := json.Marshal(_key) if err != nil { return err } return p.kv.Set(ctx, p.phoneKey(phone), bytes) } func (p *Peers) FindPhone(ctx context.Context, phone string) (peers.Key, peers.Value, bool, error) { data, err := p.kv.Get(ctx, p.phoneKey(phone)) if err != nil { if errors.Is(err, ErrNotFound) { return peers.Key{}, peers.Value{}, false, nil } return peers.Key{}, peers.Value{}, false, err } var _key peers.Key if err = json.Unmarshal(data, &_key); err != nil { return peers.Key{}, peers.Value{}, false, err } value, found, err := p.Find(ctx, _key) if err != nil { return peers.Key{}, peers.Value{}, false, err } return _key, value, found, nil } func (p *Peers) GetContactsHash(ctx context.Context) (int64, error) { data, err := p.kv.Get(ctx, p.contactsKey()) if err != nil { if errors.Is(err, ErrNotFound) { return 0, nil } return 0, err } return strconv.ParseInt(string(data), 10, 64) } func (p *Peers) SaveContactsHash(ctx context.Context, hash int64) error { return p.kv.Set(ctx, p.contactsKey(), []byte(strconv.FormatInt(hash, 10))) } func (p *Peers) key(key peers.Key) string { return keygen.New("peers", "key", key.Prefix, strconv.FormatInt(key.ID, 10)) } func (p *Peers) phoneKey(phone string) string { return keygen.New("peers", "phone", phone) } func (p *Peers) contactsKey() string { return keygen.New("peers", "contacts", "hash") } ================================================ FILE: core/storage/session.go ================================================ package storage import ( "context" "errors" "github.com/gotd/td/telegram" "github.com/iyear/tdl/core/storage/keygen" ) type Session struct { kv Storage login bool } func NewSession(kv Storage, login bool) telegram.SessionStorage { return &Session{kv: kv, login: login} } func (s *Session) LoadSession(ctx context.Context) ([]byte, error) { if s.login { return nil, nil } b, err := s.kv.Get(ctx, s.key()) if err != nil { if errors.Is(err, ErrNotFound) { return nil, nil } return nil, err } return b, nil } func (s *Session) StoreSession(ctx context.Context, data []byte) error { return s.kv.Set(ctx, s.key(), data) } func (s *Session) key() string { return keygen.New("session") } ================================================ FILE: core/storage/state.go ================================================ package storage import ( "context" "encoding/json" "errors" "strconv" "github.com/gotd/td/telegram/updates" "github.com/iyear/tdl/core/storage/keygen" ) type State struct { kv Storage } func NewState(kv Storage) updates.StateStorage { return &State{kv: kv} } func (s *State) Get(ctx context.Context, key string, v interface{}) error { data, err := s.kv.Get(ctx, key) if err != nil { return err } return json.Unmarshal(data, v) } func (s *State) Set(ctx context.Context, key string, v interface{}) error { data, err := json.Marshal(v) if err != nil { return err } return s.kv.Set(ctx, key, data) } func (s *State) GetState(ctx context.Context, userID int64) (updates.State, bool, error) { state := updates.State{} if err := s.Get(ctx, s.stateKey(userID), &state); err != nil { if errors.Is(err, ErrNotFound) { return state, false, nil } return state, false, err } return state, true, nil } func (s *State) SetState(ctx context.Context, userID int64, state updates.State) error { if err := s.Set(ctx, s.stateKey(userID), state); err != nil { return err } return s.Set(ctx, s.channelKey(userID), struct{}{}) } func (s *State) SetPts(ctx context.Context, userID int64, pts int) error { state, k := updates.State{}, s.stateKey(userID) if err := s.Get(ctx, k, &state); err != nil { return err } state.Pts = pts return s.Set(ctx, k, state) } func (s *State) SetQts(ctx context.Context, userID int64, qts int) error { state, k := updates.State{}, s.stateKey(userID) if err := s.Get(ctx, k, &state); err != nil { return err } state.Qts = qts return s.Set(ctx, k, state) } func (s *State) SetDate(ctx context.Context, userID int64, date int) error { state, k := updates.State{}, s.stateKey(userID) if err := s.Get(ctx, k, &state); err != nil { return err } state.Date = date return s.Set(ctx, k, state) } func (s *State) SetSeq(ctx context.Context, userID int64, seq int) error { state, k := updates.State{}, s.stateKey(userID) if err := s.Get(ctx, k, &state); err != nil { return err } state.Seq = seq return s.Set(ctx, k, state) } func (s *State) SetDateSeq(ctx context.Context, userID int64, date, seq int) error { state, k := updates.State{}, s.stateKey(userID) if err := s.Get(ctx, k, &state); err != nil { return err } state.Date = date state.Seq = seq return s.Set(ctx, k, state) } func (s *State) GetChannelPts(ctx context.Context, userID, channelID int64) (int, bool, error) { c := make(map[int64]int) if err := s.Get(ctx, s.channelKey(userID), &c); err != nil { if errors.Is(err, ErrNotFound) { return 0, false, nil } return 0, false, err } pts, ok := c[channelID] if !ok { return 0, false, nil } return pts, true, nil } func (s *State) SetChannelPts(ctx context.Context, userID, channelID int64, pts int) error { c, k := make(map[int64]int), s.channelKey(userID) if err := s.Get(ctx, k, &c); err != nil { return err } c[channelID] = pts return s.Set(ctx, k, c) } func (s *State) ForEachChannels(ctx context.Context, userID int64, f func(ctx context.Context, channelID int64, pts int) error) error { c := make(map[int64]int) if err := s.Get(ctx, s.channelKey(userID), &c); err != nil { return err } for channelID, pts := range c { if err := f(ctx, channelID, pts); err != nil { return err } } return nil } func (s *State) stateKey(userID int64) string { return keygen.New("state", strconv.FormatInt(userID, 10)) } func (s *State) channelKey(userID int64) string { return keygen.New("chan", strconv.FormatInt(userID, 10)) } ================================================ FILE: core/storage/storage.go ================================================ package storage import ( "context" "github.com/go-faster/errors" ) type Storage interface { Get(ctx context.Context, key string) ([]byte, error) Set(ctx context.Context, key string, value []byte) error Delete(ctx context.Context, key string) error } var ErrNotFound = errors.New("key not found") ================================================ FILE: core/tclient/tclient.go ================================================ package tclient import ( "context" "fmt" "time" "github.com/cenkalti/backoff/v4" "github.com/go-faster/errors" "github.com/gotd/contrib/clock" "github.com/gotd/contrib/middleware/floodwait" tdclock "github.com/gotd/td/clock" "github.com/gotd/td/exchange" "github.com/gotd/td/telegram" "github.com/gotd/td/telegram/dcs" "golang.org/x/net/proxy" "github.com/iyear/tdl/core/logctx" "github.com/iyear/tdl/core/middlewares/recovery" "github.com/iyear/tdl/core/middlewares/retry" "github.com/iyear/tdl/core/util/netutil" "github.com/iyear/tdl/core/util/tutil" ) // dc values can be overridden globally var ( DCList dcs.List DC int PublicKeys []exchange.PublicKey ) type Options struct { AppID int AppHash string Session telegram.SessionStorage Middlewares []telegram.Middleware Proxy string NTP string ReconnectTimeout time.Duration UpdateHandler telegram.UpdateHandler } // New creates new telegram client with given options. // Default middlewares(retry, recovery, flood wait) always added. func New(ctx context.Context, o Options) (*telegram.Client, error) { // process clock tclock := tdclock.System if ntp := o.NTP; ntp != "" { var err error tclock, err = clock.NewNTP(ntp) if err != nil { return nil, errors.Wrap(err, "create network clock") } } // process proxy var dialer dcs.DialFunc = proxy.Direct.DialContext if p := o.Proxy; p != "" { d, err := netutil.NewProxy(p) if err != nil { return nil, errors.Wrap(err, "get dialer") } dialer = d.DialContext } opts := telegram.Options{ Resolver: dcs.Plain(dcs.PlainOptions{ Dial: dialer, }), ReconnectionBackoff: func() backoff.BackOff { return newBackoff(o.ReconnectTimeout) }, DC: DC, DCList: DCList, PublicKeys: PublicKeys, UpdateHandler: o.UpdateHandler, Device: tutil.Device, SessionStorage: o.Session, RetryInterval: 5 * time.Second, MaxRetries: 5, DialTimeout: 10 * time.Second, Middlewares: append(NewDefaultMiddlewares(ctx, o.ReconnectTimeout), o.Middlewares...), Clock: tclock, Logger: logctx.From(ctx).Named("td"), } return telegram.NewClient(o.AppID, o.AppHash, opts), nil } func NewDefaultMiddlewares(ctx context.Context, timeout time.Duration) []telegram.Middleware { return []telegram.Middleware{ recovery.New(ctx, newBackoff(timeout)), retry.New(5), floodwait.NewSimpleWaiter(), } } func newBackoff(timeout time.Duration) backoff.BackOff { b := backoff.NewExponentialBackOff() b.Multiplier = 1.1 b.MaxElapsedTime = timeout b.MaxInterval = 10 * time.Second return b } func RunWithAuth(ctx context.Context, client *telegram.Client, f func(ctx context.Context) error) error { return client.Run(ctx, func(ctx context.Context) error { status, err := client.Auth().Status(ctx) if err != nil { return err } if !status.Authorized { return fmt.Errorf("not authorized. please login first") } return f(ctx) }) } ================================================ FILE: core/tmedia/convert.go ================================================ package tmedia import ( "github.com/gotd/td/tg" ) func ConvInputMedia(media tg.MessageMediaClass) (tg.InputMediaClass, bool) { switch v := media.(type) { case *tg.MessageMediaPhoto: return ConvInputMediaPhoto(v) case *tg.MessageMediaGeo: return ConvInputMediaGeo(v) case *tg.MessageMediaContact: return ConvInputMediaContact(v) case *tg.MessageMediaDocument: return ConvInputMediaDocument(v) case *tg.MessageMediaVenue: return ConvInputMediaVenue(v) case *tg.MessageMediaGame: return ConvInputMediaGame(v) case *tg.MessageMediaInvoice: return ConvInputMediaInvoice(v) case *tg.MessageMediaGeoLive: return ConvInputMediaGeoLive(v) case *tg.MessageMediaPoll: return ConvInputMediaPoll(v) case *tg.MessageMediaDice: return ConvInputMediaDice(v) case *tg.MessageMediaStory: return ConvInputMediaStory(v) case *tg.MessageMediaUnsupported: return nil, false default: return nil, false } } func ConvInputMediaPhoto(v *tg.MessageMediaPhoto) (*tg.InputMediaPhoto, bool) { switch t := v.Photo.(type) { case *tg.PhotoEmpty: return nil, false case *tg.Photo: p := &tg.InputPhoto{} p.FillFrom(t) ret := &tg.InputMediaPhoto{ Spoiler: v.Spoiler, ID: p, TTLSeconds: v.TTLSeconds, } ret.SetFlags() return ret, true default: return nil, false } } func ConvInputMediaGeo(v *tg.MessageMediaGeo) (*tg.InputMediaGeoPoint, bool) { switch t := v.Geo.(type) { case *tg.GeoPointEmpty: return nil, false case *tg.GeoPoint: g := &tg.InputGeoPoint{} g.FillFrom(t) g.SetFlags() return &tg.InputMediaGeoPoint{ GeoPoint: g, }, true default: return nil, false } } func ConvInputMediaContact(v *tg.MessageMediaContact) (*tg.InputMediaContact, bool) { c := &tg.InputMediaContact{} c.FillFrom(v) return c, true } func ConvInputMediaDocument(v *tg.MessageMediaDocument) (*tg.InputMediaDocument, bool) { switch t := v.Document.(type) { case *tg.DocumentEmpty: return nil, false case *tg.Document: d := &tg.InputDocument{} d.FillFrom(t) ret := &tg.InputMediaDocument{ Spoiler: v.Spoiler, ID: d, TTLSeconds: v.TTLSeconds, } ret.SetFlags() return ret, true default: return nil, false } } func ConvInputMediaVenue(v *tg.MessageMediaVenue) (*tg.InputMediaVenue, bool) { geo, ok := ConvInputMediaGeo(&tg.MessageMediaGeo{Geo: v.Geo}) if !ok { return nil, false } return &tg.InputMediaVenue{ GeoPoint: geo.GeoPoint, Title: v.Title, Address: v.Address, Provider: v.Provider, VenueID: v.VenueID, VenueType: v.VenueType, }, true } func ConvInputMediaGame(v *tg.MessageMediaGame) (*tg.InputMediaGame, bool) { g := &tg.InputGameID{} g.FillFrom(&v.Game) return &tg.InputMediaGame{ ID: g, }, true } func ConvInputMediaInvoice(v *tg.MessageMediaInvoice) (*tg.InputMediaInvoice, bool) { // TODO(iyear): unsupported _ = v return nil, false } func ConvInputMediaGeoLive(v *tg.MessageMediaGeoLive) (*tg.InputMediaGeoLive, bool) { // TODO(): unsupported _ = v return nil, false } func ConvInputMediaPoll(v *tg.MessageMediaPoll) (*tg.InputMediaPoll, bool) { // TODO(): unsupported _ = v return nil, false } func ConvInputMediaDice(v *tg.MessageMediaDice) (*tg.InputMediaDice, bool) { return &tg.InputMediaDice{ Emoticon: v.Emoticon, }, true } func ConvInputMediaStory(v *tg.MessageMediaStory) (*tg.InputMediaStory, bool) { // TODO(): unsupported _ = v return nil, false } ================================================ FILE: core/tmedia/document.go ================================================ package tmedia import ( "strconv" "github.com/gabriel-vasile/mimetype" "github.com/gotd/td/tg" ) func GetDocumentInfo(doc *tg.MessageMediaDocument) (*Media, bool) { d, ok := doc.Document.(*tg.Document) if !ok { return nil, false } return &Media{ InputFileLoc: &tg.InputDocumentFileLocation{ ID: d.ID, AccessHash: d.AccessHash, FileReference: d.FileReference, }, Name: GetDocumentName(d), Size: d.Size, DC: d.DCID, Date: int64(d.Date), }, true } func GetDocumentName(doc *tg.Document) string { for _, attr := range doc.Attributes { name, ok := attr.(*tg.DocumentAttributeFilename) if ok { return name.FileName } } // #185: stable file name so --skip-same can work mime := mimetype.Lookup(doc.MimeType) ext := ".unknown" if mime != nil { ext = mime.Extension() } return strconv.FormatInt(doc.ID, 10) + ext } ================================================ FILE: core/tmedia/media.go ================================================ package tmedia import ( "github.com/gotd/td/tg" ) type Media struct { InputFileLoc tg.InputFileLocationClass // mtproto file location of the media file Name string // file name Size int64 // size in bytes DC int // which DC the media is stored Date int64 // media creation(upload) timestamp } func ExtractMedia(m tg.MessageMediaClass) (*Media, bool) { switch m := m.(type) { case *tg.MessageMediaPhoto: return GetPhotoInfo(m) case *tg.MessageMediaDocument: return GetDocumentInfo(m) case *tg.MessageMediaInvoice: return GetExtendedMedia(m.ExtendedMedia) } return nil, false } func GetMedia(msg tg.MessageClass) (*Media, bool) { mm, ok := msg.(*tg.Message) if !ok { return nil, false } media, ok := mm.GetMedia() if !ok { return nil, false } return ExtractMedia(media) } func GetExtendedMedia(mm tg.MessageExtendedMediaClass) (*Media, bool) { m, ok := mm.(*tg.MessageExtendedMedia) if !ok { return nil, false } return ExtractMedia(m.Media) } func GetDocumentThumb(doc *tg.Document) (*Media, bool) { thumbs, exists := doc.GetThumbs() if !exists { return nil, false } photoSize := &tg.PhotoSize{} for _, t := range thumbs { if p, ok := t.(*tg.PhotoSize); ok { photoSize = p break } } if photoSize == nil { return nil, false } return &Media{ InputFileLoc: &tg.InputDocumentFileLocation{ ID: doc.ID, AccessHash: doc.AccessHash, FileReference: doc.FileReference, ThumbSize: photoSize.Type, }, Name: "thumb.jpg", Size: int64(photoSize.Size), DC: doc.DCID, Date: int64(doc.Date), }, true } ================================================ FILE: core/tmedia/photo.go ================================================ package tmedia import ( "strconv" "github.com/gotd/td/tg" ) func GetPhotoInfo(photo *tg.MessageMediaPhoto) (*Media, bool) { p, ok := photo.Photo.(*tg.Photo) if !ok { return nil, false } tp, size, ok := GetPhotoSize(p.Sizes) if !ok { return nil, false } return &Media{ InputFileLoc: &tg.InputPhotoFileLocation{ ID: p.ID, AccessHash: p.AccessHash, FileReference: p.FileReference, ThumbSize: tp, }, // Telegram photo is compressed, and extension is always jpg. Name: strconv.FormatInt(p.ID, 10) + ".jpg", // unique name Size: int64(size), DC: p.DCID, Date: int64(p.Date), }, true } func GetPhotoSize(sizes []tg.PhotoSizeClass) (string, int, bool) { size := sizes[len(sizes)-1] switch s := size.(type) { case *tg.PhotoSize: return s.Type, s.Size, true case *tg.PhotoSizeProgressive: return s.Type, s.Sizes[len(s.Sizes)-1], true } return "", 0, false } ================================================ FILE: core/uploader/iter.go ================================================ package uploader import ( "context" "io" "github.com/gotd/td/tg" ) type Iter interface { Next(ctx context.Context) bool Value() Elem Err() error } type File interface { io.ReadSeeker Name() string Size() int64 } type Elem interface { File() File Thumb() (File, bool) Caption() (string, []tg.MessageEntityClass) To() tg.InputPeerClass Thread() int AsPhoto() bool } ================================================ FILE: core/uploader/progress.go ================================================ package uploader import ( "context" "github.com/gotd/td/telegram/uploader" ) type Progress interface { OnAdd(elem Elem) OnUpload(elem Elem, state ProgressState) OnDone(elem Elem, err error) // TODO: OnLog to log something that is not an error but should be sent to the user } type ProgressState struct { Uploaded int64 Total int64 } type wrapProcess struct { elem Elem process Progress } func (p *wrapProcess) Chunk(_ context.Context, state uploader.ProgressState) error { p.process.OnUpload(p.elem, ProgressState{ Uploaded: state.Uploaded, Total: state.Total, }) return nil } ================================================ FILE: core/uploader/uploader.go ================================================ package uploader import ( "context" "io" "time" "github.com/gabriel-vasile/mimetype" "github.com/go-faster/errors" "github.com/gotd/td/telegram/message" "github.com/gotd/td/telegram/message/entity" "github.com/gotd/td/telegram/message/styling" "github.com/gotd/td/telegram/uploader" "github.com/gotd/td/tg" "github.com/samber/lo" "golang.org/x/sync/errgroup" "github.com/iyear/tdl/core/util/fsutil" "github.com/iyear/tdl/core/util/mediautil" ) // MaxPartSize refer to https://core.telegram.org/api/files#uploading-files const MaxPartSize = 512 * 1024 type Uploader struct { opts Options } type Options struct { Client *tg.Client Threads int Iter Iter Progress Progress } func New(o Options) *Uploader { return &Uploader{opts: o} } func (u *Uploader) Upload(ctx context.Context, limit int) error { wg, wgctx := errgroup.WithContext(ctx) wg.SetLimit(limit) for u.opts.Iter.Next(wgctx) { elem := u.opts.Iter.Value() wg.Go(func() (rerr error) { u.opts.Progress.OnAdd(elem) defer func() { u.opts.Progress.OnDone(elem, rerr) }() if err := u.upload(wgctx, elem); err != nil { // canceled by user, so we directly return error to stop all if errors.Is(err, context.Canceled) { return errors.Wrap(err, "upload") } // don't return error, just log it } return nil }) } if err := u.opts.Iter.Err(); err != nil { return errors.Wrap(err, "iter") } return wg.Wait() } func (u *Uploader) upload(ctx context.Context, elem Elem) error { select { case <-ctx.Done(): return ctx.Err() default: } up := uploader.NewUploader(u.opts.Client). WithPartSize(MaxPartSize). WithThreads(u.opts.Threads). WithProgress(&wrapProcess{ elem: elem, process: u.opts.Progress, }) f, err := up.Upload(ctx, uploader.NewUpload(elem.File().Name(), elem.File(), elem.File().Size())) if err != nil { return errors.Wrap(err, "upload file") } if _, err = elem.File().Seek(0, io.SeekStart); err != nil { return errors.Wrap(err, "seek file") } mime, err := mimetype.DetectReader(elem.File()) if err != nil { return errors.Wrap(err, "detect mime") } // here convert underlying entities to formatters for message caption caption := styling.Custom(func(eb *entity.Builder) error { msg, entities := elem.Caption() eb.Format(msg, lo.Map(entities, func(item tg.MessageEntityClass, _ int) entity.Formatter { return func(_, _ int) tg.MessageEntityClass { return item } })...) return nil }) doc := message.UploadedDocument(f, caption).MIME(mime.String()).Filename(elem.File().Name()) // upload thumbnail TODO(iyear): maybe still unavailable if thumb, ok := elem.Thumb(); ok { if thumbFile, err := uploader.NewUploader(u.opts.Client). FromReader(ctx, thumb.Name(), thumb); err == nil { doc = doc.Thumb(thumbFile) } } var media message.MediaOption = doc switch { case mediautil.IsImage(mime.String()) && elem.AsPhoto(): // webp should be uploaded as document if mime.String() == "image/webp" { break } // upload as photo media = message.UploadedPhoto(f, caption) case mediautil.IsVideo(mime.String()): // reset reader if _, err = elem.File().Seek(0, io.SeekStart); err != nil { return errors.Wrap(err, "seek file") } if dur, w, h, err := mediautil.GetMP4Info(elem.File()); err == nil { // #132. There may be some errors, but we can still upload the file media = doc.Video(). Duration(time.Duration(dur)*time.Second). Resolution(w, h). SupportsStreaming() } case mediautil.IsAudio(mime.String()): media = doc.Audio().Title(fsutil.GetNameWithoutExt(elem.File().Name())) } _, err = message.NewSender(u.opts.Client). WithUploader(up). To(elem.To()). Reply(elem.Thread()). Media(ctx, media) if err != nil { return errors.Wrap(err, "send message") } return nil } ================================================ FILE: core/util/fsutil/fsutil.go ================================================ package fsutil import ( "os" "path/filepath" "strings" ) func GetNameWithoutExt(path string) string { return strings.TrimSuffix(filepath.Base(path), filepath.Ext(path)) } func PathExists(path string) bool { _, err := os.Stat(path) return err == nil || os.IsExist(err) } // AddPrefixDot add prefix dot if extension don't have func AddPrefixDot(ext string) string { if !strings.HasPrefix(ext, ".") { return "." + ext } return ext } ================================================ FILE: core/util/logutil/logutil.go ================================================ package logutil import ( "go.uber.org/zap" "go.uber.org/zap/zapcore" "gopkg.in/natefinch/lumberjack.v2" ) func New(level zapcore.LevelEnabler, path string) *zap.Logger { rotate := &lumberjack.Logger{ Filename: path, MaxSize: 10, MaxAge: 7, MaxBackups: 3, LocalTime: true, Compress: true, } writer := zapcore.AddSync(rotate) config := zap.NewDevelopmentEncoderConfig() config.EncodeTime = zapcore.TimeEncoderOfLayout("2006-01-02 15:04:05") config.EncodeLevel = zapcore.CapitalLevelEncoder core := zapcore.NewCore(zapcore.NewConsoleEncoder(config), writer, level) return zap.New(core, zap.AddCaller()) } ================================================ FILE: core/util/mediautil/mediautil.go ================================================ package mediautil import ( "fmt" "io" "strings" "github.com/yapingcat/gomedia/go-mp4" ) func split(mime string) (primary string, sub string, ok bool) { types := strings.Split(mime, "/") if len(types) != 2 { return "", "", false } return types[0], types[1], true } func IsVideo(mime string) bool { primary, _, ok := split(mime) return primary == "video" && ok } func IsAudio(mime string) bool { primary, _, ok := split(mime) return primary == "audio" && ok } func IsImage(mime string) bool { primary, _, ok := split(mime) return primary == "image" && ok } // GetMP4Info returns duration, width, height, error func GetMP4Info(r io.ReadSeeker) (int, int, int, error) { d := mp4.CreateMp4Demuxer(r) tracks, err := d.ReadHead() if err != nil { return 0, 0, 0, err } for _, track := range tracks { if track.Cid == mp4.MP4_CODEC_H264 { info := d.GetMp4Info() return int(info.Duration / info.Timescale), int(track.Width), int(track.Height), nil } } return 0, 0, 0, fmt.Errorf("no h264 track found") } ================================================ FILE: core/util/netutil/netutil.go ================================================ package netutil import ( "net/url" "github.com/go-faster/errors" "github.com/iyear/connectproxy" "golang.org/x/net/proxy" ) func init() { connectproxy.Register(&connectproxy.Config{ InsecureSkipVerify: true, }) } func NewProxy(proxyUrl string) (proxy.ContextDialer, error) { u, err := url.Parse(proxyUrl) if err != nil { return nil, errors.Wrap(err, "parse proxy url") } dialer, err := proxy.FromURL(u, proxy.Direct) if err != nil { return nil, errors.Wrap(err, "proxy from url") } if d, ok := dialer.(proxy.ContextDialer); ok { return d, nil } return nil, errors.New("proxy dialer is not ContextDialer") } ================================================ FILE: core/util/tutil/device.go ================================================ package tutil import "github.com/gotd/td/telegram" var Device = telegram.DeviceConfig{ DeviceModel: "Desktop", SystemVersion: "Windows 10", AppVersion: "4.2.4 x64", LangCode: "en", SystemLangCode: "en-US", LangPack: "tdesktop", } ================================================ FILE: core/util/tutil/tutil.go ================================================ package tutil import ( "context" "fmt" "net/url" "strconv" "strings" "github.com/go-faster/errors" "github.com/gotd/td/telegram/peers" "github.com/gotd/td/telegram/query" "github.com/gotd/td/tg" ) // ErrMessageDeleted is returned when a message is detected as deleted. var ErrMessageDeleted = errors.New("message may be deleted") // ParseMessageLink return dialog id, msg id, error func ParseMessageLink(ctx context.Context, manager *peers.Manager, s string) (peers.Peer, int, error) { parse := func(from, msg string) (peers.Peer, int, error) { ch, err := GetInputPeer(ctx, manager, from) if err != nil { return nil, 0, errors.Wrap(err, "input peer") } m, err := strconv.Atoi(msg) if err != nil { return nil, 0, errors.Wrap(err, "parse message id") } return ch, m, nil } u, err := url.Parse(s) if err != nil { return nil, 0, err } paths := strings.Split(strings.TrimPrefix(u.Path, "/"), "/") // https://t.me/opencfdchannel/4434?comment=360409 if c := u.Query().Get("comment"); c != "" { peer, err := GetInputPeer(ctx, manager, paths[0]) if err != nil { return nil, 0, errors.Wrap(err, "input peer") } ch, ok := peer.(peers.Channel) if !ok || !ch.IsBroadcast() { return nil, 0, errors.New("not channel") } raw, err := ch.FullRaw(ctx) if err != nil { return nil, 0, errors.Wrap(err, "full raw") } linked, ok := raw.GetLinkedChatID() if !ok { return nil, 0, errors.New("no linked chat") } return parse(strconv.FormatInt(linked, 10), c) } switch len(paths) { case 2: // https://t.me/telegram/193 // https://t.me/myhostloc/1485524?thread=1485523 return parse(paths[0], paths[1]) case 3: // https://t.me/c/1697797156/151 // https://t.me/iFreeKnow/45662/55005 if paths[0] == "c" { return parse(paths[1], paths[2]) } // "45662" means topic id, we don't need it return parse(paths[0], paths[2]) case 4: // https://t.me/c/1492447836/251015/251021 if paths[0] != "c" { return nil, 0, fmt.Errorf("invalid message link") } // "251015" means topic id, we don't need it return parse(paths[1], paths[3]) default: return nil, 0, fmt.Errorf("invalid message link: %s", s) } } func GetInputPeer(ctx context.Context, manager *peers.Manager, from string) (peers.Peer, error) { id, err := strconv.ParseInt(from, 10, 64) if err != nil { // from is username p, err := manager.Resolve(ctx, from) if err != nil { return nil, err } return p, nil } var p peers.Peer if p, err = manager.ResolveChannelID(ctx, id); err == nil { return p, nil } if p, err = manager.ResolveUserID(ctx, id); err == nil { return p, nil } if p, err = manager.ResolveChatID(ctx, id); err == nil { return p, nil } return nil, fmt.Errorf("failed to get result from %d:%v", id, err) } func GetPeerID(peer tg.PeerClass) int64 { switch p := peer.(type) { case *tg.PeerUser: return p.UserID case *tg.PeerChat: return p.ChatID case *tg.PeerChannel: return p.ChannelID } return 0 } func GetInputPeerID(peer tg.InputPeerClass) int64 { switch p := peer.(type) { case *tg.InputPeerUser: return p.UserID case *tg.InputPeerChat: return p.ChatID case *tg.InputPeerChannel: return p.ChannelID } return 0 } func GetBlockedDialogs(ctx context.Context, client *tg.Client) (map[int64]struct{}, error) { blocks, err := query.GetBlocked(client).BatchSize(100).Collect(ctx) if err != nil { return nil, err } blockids := make(map[int64]struct{}) for _, b := range blocks { blockids[GetPeerID(b.Contact.PeerID)] = struct{}{} } return blockids, nil } func FileExists(msg tg.MessageClass) bool { m, ok := msg.(*tg.Message) if !ok { return false } md, ok := m.GetMedia() if !ok { return false } switch md.(type) { case *tg.MessageMediaDocument, *tg.MessageMediaPhoto: return true default: return false } } func GetSingleMessage(ctx context.Context, c *tg.Client, peer tg.InputPeerClass, msg int) (*tg.Message, error) { it := query.Messages(c). GetHistory(peer).OffsetID(msg + 1). BatchSize(1).Iter() if !it.Next(ctx) { return nil, errors.Wrap(it.Err(), "get single message") } m, ok := it.Value().Msg.(*tg.Message) if !ok { return nil, errors.Errorf("invalid message %d", msg) } // check if message is deleted if m.GetID() != msg { return nil, fmt.Errorf("the message %d/%d: %w", GetInputPeerID(peer), msg, ErrMessageDeleted) } return m, nil } type Messages []*tg.Message func (m Messages) Len() int { return len(m) } func (m Messages) Less(i, j int) bool { return m[i].ID < m[j].ID } func (m Messages) Swap(i, j int) { m[i], m[j] = m[j], m[i] } func GetGroupedMessages(ctx context.Context, c *tg.Client, peer tg.InputPeerClass, msg *tg.Message) ([]*tg.Message, error) { group, ok := msg.GetGroupedID() if !ok { return nil, errors.New("not grouped message") } // https://telegram.org/blog/albums-saved-messages // Each album can include up to 10 photos or videos batchSize := 20 it := query.Messages(c).GetHistory(peer). OffsetID(msg.ID + 11). // from latest to oldest BatchSize(batchSize).Iter() messages := make([]*tg.Message, 0, batchSize) for i := 0; it.Next(ctx) && i < batchSize; i++ { m, ok := it.Value().Msg.(*tg.Message) if !ok { continue } groupID, ok := m.GetGroupedID() if !ok { continue } if groupID != group { continue } // append argument msg to the end of messages because of it may have been modified. // Like forward edit flag. if m.ID == msg.ID { messages = append(messages, msg) } else { messages = append(messages, m) } } // reverse messages from oldest to latest, so we can forward them in order for i, j := 0, len(messages)-1; i < j; i, j = i+1, j-1 { messages[i], messages[j] = messages[j], messages[i] } return messages, nil } var threadsLevels = []struct { threads int size int64 }{ {1, 1 << 20}, {2, 5 << 20}, {4, 20 << 20}, {8, 50 << 20}, } func BestThreads(size int64, max int) int { // Get best threads num for download, based on file size for _, thread := range threadsLevels { if size < thread.size { return min(thread.threads, max) } } return max } ================================================ FILE: docs/assets/_custom.scss ================================================ @import "plugins/_scrollbars.scss"; .markdown pre { outline: none; } .command::before { content: attr(prompt); opacity: .7; display: inline; padding-right: 0.7em; font-family: SFMono-Regular, Menlo, Monaco, Consolas, monospace; border-right: 1px solid #999; margin-right: 0.6em; letter-spacing: -1px; font-size: 105%; -webkit-user-select: none; -moz-user-select: none; user-select: none; pointer-events: none; } .toast { position: fixed; bottom: 20px; left: 50%; transform: translateX(-50%); background-color: #494949; color: #fff; padding: 10px; border-radius: 8px; z-index: 9999; // top opacity: 0; transition: opacity 0.3s ease-in-out; } ================================================ FILE: docs/content/en/_index.md ================================================ --- title: Introduction --- # tdl ![](https://img.shields.io/github/go-mod/go-version/iyear/tdl?style=flat-square) ![](https://img.shields.io/github/license/iyear/tdl?style=flat-square) ![](https://img.shields.io/github/actions/workflow/status/iyear/tdl/master.yml?branch=master&style=flat-square) ![](https://img.shields.io/github/v/release/iyear/tdl?color=red&style=flat-square) ![](https://img.shields.io/github/downloads/iyear/tdl/total?style=flat-square) {{< image src="img/logo.png" align="right" height="270" width="270">}} 📥 Telegram Downloader, but more than a downloader #### Features: - Single file start-up - Low resource usage - Take up all your bandwidth - Faster than official clients - Download files from (protected) chats - Forward messages with automatic fallback and message routing - Upload files to Telegram - Export messages/members/subscribers to JSON ## Preview It reaches my proxy's speed limit, and the **speed depends on whether you are a premium** {{< image src="img/preview.gif" >}} ## Sponsors ![](https://raw.githubusercontent.com/iyear/sponsor/master/sponsors.svg) ## Contributors contributors ================================================ FILE: docs/content/en/getting-started/_index.md ================================================ --- title: "Getting Started" bookFlatSection: true weight: 10 --- ================================================ FILE: docs/content/en/getting-started/installation.md ================================================ --- title: "Installation" weight: 10 --- # Installation ## One-Line Scripts {{< tabs "scripts" >}} {{< tab "Windows" >}} `tdl` will be installed to `$Env:SystemDrive\tdl`(will be added to `PATH`), and script also can be used to upgrade `tdl` . #### Install latest version {{< command >}} iwr -useb https://docs.iyear.me/tdl/install.ps1 | iex {{< /command >}} #### Install with `ghproxy.com` {{< command >}} $Script=iwr -useb https://docs.iyear.me/tdl/install.ps1; $Block=[ScriptBlock]::Create($Script); Invoke-Command -ScriptBlock $Block -ArgumentList "", "$True" {{< /command >}} #### Install specific version {{< command >}} $Env:TDLVersion = "VERSION" $Script=iwr -useb https://docs.iyear.me/tdl/install.ps1; $Block=[ScriptBlock]::Create($Script); Invoke-Command -ScriptBlock $Block -ArgumentList "$Env:TDLVersion" {{< /command >}} {{< /tab >}} {{< tab "macOS & Linux" >}} `tdl` will be installed to `/usr/local/bin/tdl`, and script also can be used to upgrade `tdl`. #### Install latest version {{< command >}} curl -sSL https://docs.iyear.me/tdl/install.sh | sudo bash {{< /command >}} #### Install with `ghproxy.com` {{< command >}} curl -sSL https://docs.iyear.me/tdl/install.sh | sudo bash -s -- --proxy {{< /command >}} #### Install specific version {{< command >}} curl -sSL https://docs.iyear.me/tdl/install.sh | sudo bash -s -- --version VERSION {{< /command >}} {{< /tab >}} {{< /tabs >}} ## Package Managers {{< tabs "package managers" >}} {{}} {{< command >}} brew install telegram-downloader {{< /command >}} {{< /tab >}} {{}} {{< command >}} scoop bucket add extras scoop install telegram-downloader {{< /command >}} {{< /tab >}} {{}} {{< command >}} pkg install tdl {{< /command >}} {{< /tab >}} {{}} {{< command >}} yay -S tdl {{< /command >}} {{< /tab >}} {{}} #### nix-env {{< command >}} nix-env -iA nixos.tdl {{< /command >}} #### NixOS-Configuration ``` environment.systemPackages = [ pkgs.tdl ]; ``` #### nix-shell {{< command >}} nix-shell -p tdl {{< /command >}} {{< /tab >}} {{< /tabs >}} [![Packaging status](https://repology.org/badge/vertical-allrepos/telegram-downloader.svg)](https://repology.org/project/telegram-downloader/versions) ## Docker Available images: - [`iyear/tdl`](https://hub.docker.com/r/iyear/tdl) - [`ghcr.io/iyear/tdl`](https://ghcr.io/iyear/tdl) Available tags: - `latest`(default): The latest stable release - `X.Y.Z`: A specific version of `tdl` {{< tabs "docker" >}} {{< tab "Docker" >}} To run `tdl` in one-off command: {{< command >}} docker run --rm -it iyear/tdl {{< /command >}} Further, to keep config persistent, you can mount the config directory: {{< command >}} docker run --rm -it \ -v $HOME/.tdl:/root/.tdl \ iyear/tdl {{< /command >}} To get download files, you can mount the download and other directories as needed: {{< command >}} docker run --rm -it \ -v $HOME/.tdl:/root/.tdl \ -v $HOME/Downloads:/downloads \ iyear/tdl {{< /command >}} To run `tdl` inside the container shell: {{< command >}} docker run --rm -it --entrypoint sh iyear/tdl {{< /command >}} {{< details title="Preview output" open=false >}} ```1 / # tdl version Version: 0.17.7 Commit: ace2402 Date: 2024-11-01T14:40:56+08:00 go1.21.13 linux/amd64 / # ``` {{< /details >}} To use proxy with `localhost` address, run it with `host` network: {{< command >}} docker run --rm -it --network host iyear/tdl {{< /command >}} {{< /tab >}} {{< tab "Docker Compose" >}} Run `tdl` with Docker Compose to avoid typing `docker run` flags each time. {{< details title="docker-compose.yml" open=false >}} {{< hint info >}} Example configuration uses Docker Compose v2 syntax. {{< /hint >}} ```yaml services: tdl: image: iyear/tdl # or specify X.Y.Z tag for a specific version volumes: - $HOME/.tdl:/root/.tdl # keep config persistent - $HOME/Downloads:/downloads # optional # - /path/to/your/need:/path/in/container stdin_open: true tty: true # use host network if you need to use proxy with localhost address network_mode: host ``` {{< /details >}} Run `tdl` with Docker Compose: {{< command >}} docker compose run --rm tdl {{< /command >}} To run `tdl` inside the container shell: {{< command >}} docker compose run --rm --entrypoint sh tdl {{< /command >}} {{< details title="Preview output" open=false >}} ```1 / # tdl version Version: 0.17.7 Commit: ace2402 Date: 2024-11-01T14:40:56+08:00 go1.21.13 linux/amd64 / # ``` {{< /details >}} {{< /tab >}} {{< /tabs >}} ## Prebuilt Binaries 1. Download the archive for the desired operating system, and architecture: {{< tabs "prebuilt" >}} {{< tab "Windows" >}} {{< button href="https://github.com/iyear/tdl/releases/latest/download/tdl_Windows_64bit.zip" >}}x86_64/amd64{{< /button >}} {{< button href="https://github.com/iyear/tdl/releases/latest/download/tdl_Windows_32bit.zip" >}}x86{{< /button >}} {{< button href="https://github.com/iyear/tdl/releases/latest/download/tdl_Windows_arm64.zip" >}}arm64{{< /button >}} {{< button href="https://github.com/iyear/tdl/releases/latest/download/tdl_Windows_armv5.zip" >}}armv5{{< /button >}} {{< button href="https://github.com/iyear/tdl/releases/latest/download/tdl_Windows_armv6.zip" >}}armv6{{< /button >}} {{< button href="https://github.com/iyear/tdl/releases/latest/download/tdl_Windows_armv7.zip" >}}armv7{{< /button >}} {{< /tab >}} {{< tab "macOS" >}} {{< button href="https://github.com/iyear/tdl/releases/latest/download/tdl_MacOS_64bit.tar.gz" >}}Intel{{< /button >}} {{< button href="https://github.com/iyear/tdl/releases/latest/download/tdl_MacOS_arm64.tar.gz" >}}M1/M2{{< /button >}} {{< /tab >}} {{< tab "Linux" >}} {{< button href="https://github.com/iyear/tdl/releases/latest/download/tdl_Linux_64bit.tar.gz" >}}x86_64/amd64{{< /button >}} {{< button href="https://github.com/iyear/tdl/releases/latest/download/tdl_Linux_32bit.tar.gz" >}}x86{{< /button >}} {{< button href="https://github.com/iyear/tdl/releases/latest/download/tdl_Linux_arm64.tar.gz" >}}arm64{{< /button >}} {{< button href="https://github.com/iyear/tdl/releases/latest/download/tdl_Linux_armv5.tar.gz" >}}armv5{{< /button >}} {{< button href="https://github.com/iyear/tdl/releases/latest/download/tdl_Linux_armv6.tar.gz" >}}armv6{{< /button >}} {{< button href="https://github.com/iyear/tdl/releases/latest/download/tdl_Linux_armv7.tar.gz" >}}armv7{{< /button >}} {{< /tab >}} {{< /tabs >}} 2. Extract the archive 3. Move the executable to the desired directory 4. Add this directory to the PATH environment variable 5. Verify that you have execute permission on the file ## Source To build the extended edition of `tdl` from source you must: 1. Install [Git](https://git-scm.com/) 2. Install [Go](https://go.dev/) version 1.25 or later 3. Update your `PATH` environment variable as described in the Go documentation {{< hint info >}} The installation directory is controlled by the `GOPATH` and `GOBIN` environment variables. If `GOBIN` is set, binaries are installed to that directory. If `GOPATH` is set, binaries are installed to the `bin` subdirectory of the first directory in the `GOPATH` list. Otherwise, binaries are installed to the `bin` subdirectory of the default `GOPATH` (`$HOME/go` or `%USERPROFILE%\go`). {{< /hint >}} Then build: {{< command >}} go install github.com/iyear/tdl@latest tdl version {{< /command >}} ================================================ FILE: docs/content/en/getting-started/quick-start.md ================================================ --- title: "Quick Start" weight: 20 --- # Quick Start ## Login We don't specify the namespace here, so it will use the `default` namespace. You can specify the namespace with `-n` flag if you want to use another namespace. ### **Login with desktop clients** {{< hint warning >}} Please ensure that clients are downloaded from [official website](https://desktop.telegram.org/) (NOT from Microsoft Store or App Store) {{< /hint >}} Automatically find the client path: {{< command >}} tdl login {{< /command >}} Or if you set a local passcode: {{< command >}} tdl login -p YOUR_PASSCODE {{< /command >}} Or specify custom client path: {{< command >}} tdl login -d /path/to/TelegramDesktop {{< /command >}} ### **Login with QR code** {{< command >}} tdl login -T qr {{< /command >}} ### **Login with phone & code** {{< command >}} tdl login -T code {{< /command >}} ## Download We download media from Telegram official channel: {{< command >}} tdl dl -u https://t.me/telegram/193 {{< /command >}} ================================================ FILE: docs/content/en/getting-started/shell-completion.md ================================================ --- title: "Shell Completion" weight: 30 --- # Shell Completion Run corresponding command to enable shell completion in all sessions: {{< tabs "shell" >}} {{< tab "bash" >}} {{< command >}} echo "source <(tdl completion bash)" >> ~/.bashrc {{< /command >}} {{< /tab >}} {{< tab "zsh" >}} {{< command >}} echo "source <(tdl completion zsh)" >> ~/.zshrc {{< /command >}} {{< /tab >}} {{< tab "fish" >}} {{< command >}} echo "tdl completion fish | source" >> ~/.config/fish/config.fish {{< /command >}} {{< /tab >}} {{< tab "PowerShell" >}} {{< command >}} Add-Content -Path $PROFILE -Value "tdl completion powershell | Out-String | Invoke-Expression" {{< /command >}} {{< /tab >}} {{< /tabs >}} ================================================ FILE: docs/content/en/guide/_index.md ================================================ --- title: "Guide" bookFlatSection: true weight: 20 --- ================================================ FILE: docs/content/en/guide/download.md ================================================ --- title: "Download" weight: 30 --- # Download ## From Links: {{< hint info >}} Get message links from "Copy Link" button in official clients. {{< /hint >}} {{< include "snippets/link.md" >}} {{< command >}} tdl dl -u https://t.me/tdl/1 -u https://t.me/tdl/2 {{< /command >}} ## From JSON: There are two ways to export the JSON you need: {{< tabs "json" >}} {{< tab "tdl" >}} This is especially for protected chats and more powerful than the desktop client. Please refer to [Export Messages](/guide/tools/export-messages) {{< /tab >}} {{< tab "Desktop Client" >}} 1. Choose the dialog you want to export, and click the three dots in the upper right corner, then click `Export Chat History`. 2. Uncheck all boxes(you don't need to download them now) and set `Size Limit` to minimum 3. Set Format to `JSON` and select the time period you need. 4. Export it! And `result.json` is what you need. {{< /tab >}} {{< /tabs >}} {{< command >}} tdl dl -f result1.json -f result2.json {{< /command >}} ## Combine Sources: {{< command >}} tdl dl \ -u https://t.me/tdl/1 -u https://t.me/tdl/2 \ -f result1.json -f result2.json {{< /command >}} ## Custom Destination: Download files to custom directory {{< command >}} tdl dl -u https://t.me/tdl/1 -d /path/to/dir {{< /command >}} ## Custom Parameters: Download with 8 threads per task, 4 concurrent tasks: {{< command >}} tdl dl -u https://t.me/tdl/1 -t 8 -l 4 {{< /command >}} ## Descending Order: Download files in descending order(from newest to oldest) {{< hint warning >}} Different order will affect resuming download {{< /hint >}} {{< command >}} tdl dl -f result.json --desc {{< /command >}} ## MIME Detection: If the file extension is not matched with the MIME type, tdl will rename the file with the correct extension. {{< hint warning >}} Side effect: like `.apk` file, it will be renamed to `.zip`. {{< /hint >}} {{< command >}} tdl dl -u https://t.me/tdl/1 --rewrite-ext {{< /command >}} ## Album/Grouped Detection Automatically detect if the message is an album/grouped message and download all of them. {{< command >}} tdl dl -u https://t.me/tdl/1 --group {{< /command >}} ## Auto Skip Skip the same files(name and size) when downloading. {{< command >}} tdl dl -u https://t.me/tdl/1 --skip-same {{< /command >}} ## Takeout Session Download files with [takeout session](https://arabic-telethon.readthedocs.io/en/stable/extra/examples/telegram-client.html#exporting-messages): > If you plan to download a lot of media, you may prefer to do this within a takeout session. Takeout sessions let you > export data from your account with lower flood wait limits. {{< command >}} tdl dl -u https://t.me/tdl/1 --takeout {{< /command >}} ## Filters Download files with extension filters: {{< hint warning >}} The extension is only matched with the file name, not the MIME type. So it may not work as expected. Whitelist and blacklist can not be used at the same time. {{< /hint >}} Whitelist: Only download files with `.jpg` `.png` extension {{< command >}} tdl dl -u https://t.me/tdl/1 -i jpg,png {{< /command >}} Blacklist: Download all files except `.mp4` `.flv` extension {{< command >}} tdl dl -u https://t.me/tdl/1 -e mp4,flv {{< /command >}} ## Name Template Download with custom file name template: Please refer to [Template Guide](/guide/template) for more details. {{< command >}} tdl dl -u https://t.me/tdl/1 \ --template "{{ .DialogID }}_{{ .MessageID }}_{{ .DownloadDate }}_{{ .FileName }}" {{< /command >}} ## Resume/Restart Resume without UI interaction: {{< command >}} tdl dl -u https://t.me/tdl/1 --continue {{< /command >}} Restart without UI interaction: {{< command >}} tdl dl -u https://t.me/tdl/1 --restart {{< /command >}} ## Serve Expose the files as an HTTP server instead of downloading them with built-in downloader {{< hint info >}} This is useful when you want to download files with a download manager like `aria2`/`wget`/`axel`/`IDM`... {{< /hint >}} {{< command >}} tdl dl -u https://t.me/tdl/1 --serve {{< /command >}} With custom port: {{< command >}} tdl dl -u https://t.me/tdl/1 --serve --port 8081 {{< /command >}} ================================================ FILE: docs/content/en/guide/extensions.md ================================================ --- title: "Extensions 🆕" weight: 70 --- # Extensions {{< hint warning >}} Extensions are a new feature in tdl. They are still in the experimental stage, and the CLI may change in future versions. If you encounter any problems or have any suggestions, please [open an issue](https://github.com/iyear/tdl/issues/new/choose) on GitHub. {{< /hint >}} ## Overview tdl extensions are add-on tools that integrate seamlessly with tdl. They provide a way to extend the core feature set of tdl, but without requiring every new feature to be added to the core. tdl extensions have the following features: - They can be added and removed without impacting the core tdl tool. - They integrate with tdl, and will show up in tdl help and other places. tdl extensions live in `~/.tdl/extensions`, which is controlled by `tdl extension` commands. To get started with extensions, you can use the following commands: {{< command >}} tdl extension install iyear/tdl-whoami {{< /command >}} {{< command >}} tdl whoami {{< /command >}} You can see the output of the `tdl-whoami` extension. Refer to the [tdl-whoami](https://github.com/iyear/tdl-whoami) for details. ``` You are XXXXX. ID: XXXXXXXX ``` ## Finding extensions You can find extensions by browsing [repositories with the `tdl-extension` topic](https://github.com/topics/tdl-extension). ## Installing extensions To install an extension, use the `extension install` subcommand. There are two types of extensions: - `GitHub` : Extensions hosted on GitHub repositories. {{< command >}} tdl extension install / {{< /command >}} To install an extension from a private repository, you must set up a [GitHub personal access token](https://github.com/settings/personal-access-tokens/new)(with `Contents` read permission) in your environment with the `GITHUB_TOKEN` variable. {{< command >}} export GITHUB_TOKEN=YOUR_TOKEN tdl extension install / {{< /command >}} - `Local` : Extensions stored on your local machine. {{< command >}} tdl extension install /path/to/extension {{< /command >}} To install an extension even if it exists, use the `--force` flag: {{< command >}} tdl extension install --force EXTENSION {{< /command >}} To install multiple extensions at once, use the following command: {{< command >}} tdl extension install / /path/to/extension2 ... {{< /command >}} To only print information without actually installing the extension, use the `--dry-run` flag: {{< command >}} tdl extension install --dry-run EXTENSION {{< /command >}} If you already have an extension by the same name installed, the command will fail. For example, if you have installed `foo/tdl-whoami`, you must uninstall it before installing `bar/tdl-whoami`. ## Running extensions When you have installed an extension, you run the extension as you would run a native tdl command, using `tdl EXTENSION-NAME`. The `EXTENSION-NAME` is the name of the repository that contains the extension, minus the `tdl-` prefix. For example, if you installed the extension from the `iyear/tdl-whoami` repository, you would run the extension with the following command. {{< command >}} tdl whoami {{< /command >}} Global config flags are still available when running an extension. For example, you can run the following command to specify namespace and proxy when running the `tdl-whoami` extension. {{< command >}} tdl -n foo --proxy socks5://localhost:1080 whoami {{< /command >}} Flags specific to an extension can also be used. For example, you can run the following command to enable verbose mode when running the `tdl-whoami` extension. {{< hint info >}} Remember to write global flags before extension subcommands and write extension flags after extension subcommands: {{< command >}} tdl {{< /command >}} {{< /hint >}} {{< command >}} tdl -n foo whoami -v {{< /command >}} You can usually find specific information about how to use an extension in the README of the repository that contains the extension. ## Viewing installed extensions To view all installed extensions, use the `extension list` subcommand. This command will list all installed extensions, along with their authors and versions. {{< command >}} tdl extension list {{< /command >}} ## Updating extensions To update an extension, use the `extension upgrade` subcommand. Replace the `EXTENSION` parameters with the name of extensions. {{< command >}} tdl extension upgrade EXTENSION1 EXTENSION2 ... {{< /command >}} To update all installed extensions, keep the `EXTENSION` parameter empty. {{< command >}} tdl extension upgrade {{< /command >}} To upgrade an extension from a GitHub private repository, you must set up a [GitHub personal access token](https://github.com/settings/personal-access-tokens/new)(with `Contents` read permission) in your environment with the `GITHUB_TOKEN` variable. {{< command >}} export GITHUB_TOKEN=YOUR_TOKEN tdl extension upgrade EXTENSION {{< /command >}} To only print information without actually upgrading the extension, use the `--dry-run` flag: {{< command >}} tdl extension upgrade --dry-run EXTENSION {{< /command >}} ## Uninstalling extensions To uninstall an extension, use the `extension remove` subcommand. Replace the `EXTENSION` parameters with the name of extensions. {{< command >}} tdl extension remove EXTENSION1 EXTENSION2 ... {{< /command >}} To only print information without actually uninstalling the extension, use the `--dry-run` flag: {{< command >}} tdl extension remove --dry-run EXTENSION {{< /command >}} ## Developing extensions Please refer to the [tdl-extension-template](https://github.com/iyear/tdl-extension-template) repository for instructions on how to create, build, and publish extensions for tdl. ================================================ FILE: docs/content/en/guide/forward.md ================================================ --- title: "Forward" weight: 35 --- # Forward Forward messages with automatic fallback and message routing One-liner to forward messages from `https://t.me/telegram/193` to `Saved Messages`: {{< command >}} tdl forward --from https://t.me/telegram/193 {{< /command >}} ## Custom Source {{< include "snippets/link.md" >}} You can forward messages from links and [exported JSON files](/guide/download#from-json): {{< command >}} tdl forward \ --from https://t.me/telegram/193 \ --from https://t.me/telegram/195 \ --from tdl-export.json \ --from tdl-export2.json {{< /command >}} ## Custom Destination {{< include "snippets/chat.md" >}} ### Specific Chat Forward to specific one chat: {{< command >}} tdl forward --from tdl-export.json --to CHAT {{< /command >}} ### Message Routing Forward to different chats by message router which is based on [expression](/reference/expr). List all available fields: {{< command >}} tdl forward --from tdl-export.json --to - {{< /command >}} Forward to `CHAT1` if message contains `foo`, otherwise forward to `Saved Messages`: {{< hint info >}} You must return a **string** or **struct** as the target CHAT, and empty string means forward to `Saved Messages`. {{< /hint >}} {{< command >}} tdl forward --from tdl-export.json \ --to 'Message.Message contains "foo" ? "CHAT1" : ""' {{< /command >}} Forward to `CHAT1` if message contains `foo`, otherwise forward to reply to message/topic `4` in `CHAT2`: {{< command >}} tdl forward --from tdl-export.json \ --to 'Message.Message contains "foo" ? "CHAT1" : { Peer: "CHAT2", Thread: 4 }' {{< /command >}} Pass a file name if the expression is complex: {{< details "router.txt" >}} Write your expression like `switch`: ```javascript Message.Message contains "foo" ? "CHAT1" : From.ID == 123456 ? "CHAT2" : Message.Views > 30 ? { Peer: "CHAT3", Thread: 101 } : "" ``` {{< /details >}} {{< command >}} tdl forward --from tdl-export.json --to router.txt {{< /command >}} ## Mode Forward messages with automatic fallback strategy. Available modes: - `direct` (default) - `clone` ### Direct Prefer to use official forward API. If the chat or message is not allowed to use official forward API, it will be automatically downgraded to `clone` mode. {{< command >}} tdl forward --from tdl-export.json --mode direct {{< /command >}} ### Clone Forward messages by copying them, which doesn't have forwarded header. Some message content can't be copied, such as poll, invoice, etc. They will be ignored. {{< command >}} tdl forward --from tdl-export.json --mode clone {{< /command >}} ## Edit Edit the message before forwarding based on [expression](/reference/expr). {{< hint info >}} - You must pass the first message of grouped photos to edit the caption. - You can pass any message of grouped documents to edit the corresponding comment. {{< /hint >}} You can reference relevant fields from the original message in the expression. List all available fields: {{< command >}} tdl forward --from tdl-export.json --edit - {{< /command >}} Append `Test Forwarded Message` to the original message: {{< command >}} tdl forward --from tdl-export.json --edit 'Message.Message + " Test Forwarded Message"' {{< /command >}} Write styled message with [HTML](https://core.telegram.org/bots/api#html-style): {{< command >}} tdl forward --from tdl-export.json --edit \ 'Message.Message + `Bold Link`' {{< /command >}} Pass a file name if the expression is complex: {{< details "edit.txt" >}} ```javascript repeat(Message.Message, 2) + ` Google Bing bold italic code spoiler

package main

import "fmt"

func main() {
    fmt.Println("hello world")
}
` + From.VisibleName ``` {{< /details >}} {{< command >}} tdl forward --from tdl-export.json --edit edit.txt {{< /command >}} ## Dry Run Print the progress without actually sending messages, which is useful for message routing debugging. {{< command >}} tdl forward --from tdl-export.json --dry-run {{< /command >}} ## Silent Send messages without notification. {{< command >}} tdl forward --from tdl-export.json --silent {{< /command >}} ## No Grouped Detection By default, tdl will detect grouped messages and forward them as an album. You can disable this behavior by `--single` to forward it as a single message. {{< command >}} tdl forward --from tdl-export.json --single {{< /command >}} ## Descending Order Forward messages in descending order for each source. {{< command >}} tdl forward --from tdl-export.json --desc {{< /command >}} ================================================ FILE: docs/content/en/guide/global-config.md ================================================ --- title: "Global Config" weight: 10 --- # Global Config Global config is some CLI flags that can be set in every command. {{< hint info >}} **Set Global Config EVERYTIME!** Global config **does not mean** that the configuration will be persisted or only need to be set once in global settings, they will only take effect in the current command. You need to set them in each command. {{< /hint >}} ## `-n/--ns` Each namespace represents a Telegram account. Default: `default`. If you want to add another account, just add `-n YOUR_ACCOUNT_NAME` option to every command: {{< command >}} tdl -n iyear {{< /command >}} ## `--proxy` Set the proxy. Default: `""`. Format: `protocol://username:password@host:port` {{< command >}} tdl --proxy socks5://localhost:1080 tdl --proxy http://localhost:8080 tdl --proxy https://localhost:8081 {{< /command >}} ## `--storage` Set the storage. Default: `type=bolt,path=~/.tdl/data` Format: `type=DRIVER,opt1=val1,opt2=val2,...` Available drivers: | Driver | Options | Description | |:----------------:|:------------------------------:|---------------------------------------------------------------------------------------------------------------| | `bolt` (Default) | `path=/path/to/data-directory` | Store data in separate database files. So you can use it in multiple processes(must be different namespaces). | | `file` | `path=/path/to/data.json` | Store data in a single JSON file, which is useful for debugging. | | `legacy` | `path=/path/to/data.kv` | **Deprecated.** Store data in a single database file. So you **can't** use it in multiple processes. | | - | - | Wait for more drivers... | {{< command >}} tdl --storage type=bolt,path=/path/to/data-dir {{< /command >}} ## `--ntp` Set ntp server host. If it's empty, system time will be used. Default: `""`. {{< command >}} tdl --ntp pool.ntp.org {{< /command >}} ## `--reconnect-timeout` Set Telegram client reconnect timeout. Default: `2m`. {{< hint info >}} Set higher timeout or 0(INF) if your network is poor. {{< /hint >}} {{< command >}} tdl --reconnect-timeout 1m30s {{< /command >}} ## `--debug` Enable debug level log. Default: `false`. {{< command >}} tdl --debug {{< /command >}} ## `--pool` Set the DC pool size of Telegram client. Default: `8`. {{< hint info >}} Set higher timeout or 0(INF) if you want faster speed. {{< /hint >}} {{< command >}} tdl --pool 2 {{< /command >}} ## `--delay` set the delay between each task. Default: `0s`. {{< hint info >}} Set higher delay time if you want to avoid Telegram's flood control. {{< /hint >}} {{< command >}} tdl --delay 5s {{< /command >}} ================================================ FILE: docs/content/en/guide/login.md ================================================ --- type: "docs" title: "Login" weight: 20 bookHref: "/getting-started/quick-start/#login" --- # Login ================================================ FILE: docs/content/en/guide/migration.md ================================================ --- title: "Migration" weight: 50 --- # Migration Backup or recover your data ## Backup Backup all namespace data to a file. Default: `.backup.tdl`. {{< command >}} tdl backup {{< /command >}} Or specify the output file: {{< command >}} tdl backup -d /path/to/custom.tdl {{< /command >}} ## Recover Recover your data from a tdl backup file. Existing namespace data will be overwritten. {{< command >}} tdl recover -f /path/to/custom.backup.tdl {{< /command >}} ## Migrate Migrate your data to another storage See [Storage Flag](/guide/global-config/#--storage) for storage option details. Migrate current storage to file storage: {{< command >}} tdl migrate --to type=file,path=/path/to/data.json {{< /command >}} Migrate custom source storage to file storage: {{< command >}} tdl migrate --storage type=bolt,path=/path/to/data-directory --to type=file,path=/path/to/data.json {{< /command >}} ================================================ FILE: docs/content/en/guide/template.md ================================================ --- title: "Template Guide" bookHidden: true bookToC: false --- # Template Guide This guide is intended to introduce variables and functions that are available in the tdl template. Template syntax is based on [Go's text/template](https://golang.org/pkg/text/template/) package. ## Download ### Variables (beta) | Var | Desc | |:--------------:|:----------------------------------------:| | `DialogID` | Telegram dialog id | | `MessageID` | Telegram message id | | `MessageDate` | Telegram message date(timestamp) | | `FileName` | Telegram file name | | `FileCaption` | Telegram file caption, aka. text message | | `FileSize` | Human-readable file size, like `1GB` | | `DownloadDate` | Download date(timestamp) | ### Functions (beta) | Func | Desc | Usage | Example | |:------------:|:------------------------------------------------------------------------------------------------------------------------:|:------------------------------------------------------------:|:-------------------------------------------------------------------------------------:| | `repeat` | Repeat `STRING` `N` times | `repeat STRING N` | `{{ repeat "test" 3 }}` | | `replace` | Perform replacement on `STRING` with `PAIRS` | `replace STRING PAIRS...` | `{{ replace "Test" "t" "T" "e" "E" }}` | | `upper` | Convert `STRING` to uppercase | `upper STRING` | `{{ upper "Test" }}` | | `lower` | Convert `STRING` to lowercase | `lower STRING` | `{{ lower "Test" }}` | | `snakecase` | Convert `STRING` to snake_case | `snakecase STRING` | `{{ snakecase "Test" }}` | | `camelcase` | Convert `STRING` to camelCase | `camelcase STRING` | `{{ camelcase "Test" }}` | | `kebabcase` | Convert `STRING` to kebab-case | `kebabcase STRING` | `{{ kebabcase "Test" }}` | | `rand` | Generate random number in range `MIN` to `MAX` | `rand MIN MAX` | `{{ rand 1 10 }}` | | `now` | Get current timestamp | `now` | `{{ now }}` | | `formatDate` | Format `TIMESTAMP` with [format](https://golang.cafe/blog/golang-time-format-example.html)
Default: `20060102150405` | `formatDate TIMESTAMP`
`formatDate TIMESTAMP "format"` | `{{ formatDate 1600000000 }}`
`{{ formatDate 1600000000 "2006-01-02-15-04-05"}}` | | `filenamify` | Convert `STRING` to a valid filename with the best effort. Optional `MaxLength` can be used to limit string length | `filenamify STRING MaxLength` | `{{ filenamify .FileName 32 }}` | ### Examples: ```gotemplate {{ .DialogID }}_{{ .MessageID }}_{{ replace .FileCaption `/` `_` `\` `_` `:` `_` }} {{ .FileName }}_{{ formatDate .DownloadDate }}_{{ .FileSize }} {{ .FileName }}_{{ formatDate .DownloadDate "2006-01-02-15-04-05"}}_{{ .FileSize }} {{ lower (replace .FileName ` ` `_`) }} {{ formatDate (now) }} ``` ### Default: ```gotemplate {{ .DialogID }}_{{ .MessageID }}_{{ filenamify .FileName }} ``` ================================================ FILE: docs/content/en/guide/tools/_index.md ================================================ --- title: "Tools" bookCollapseSection: true weight: 60 --- ================================================ FILE: docs/content/en/guide/tools/export-members.md ================================================ --- title: "Export Members" weight: 20 --- # Export Members Export chat members/subscribers, admins, bots, etc. {{< hint info >}} Chat administrator permission is required for some types of members(kicked, banned, etc.). {{< /hint >}} {{< include "snippets/chat.md" >}} ## All Export all users to `tdl-users.json` {{< command >}} tdl chat users -c CHAT {{< /command >}} ## Custom Destination Export with specified file path {{< command >}} tdl chat users -c CHAT -o /path/to/export.json {{< /command >}} ## Raw Export Telegram MTProto raw user structure, which is useful for debugging. {{< command >}} tdl chat users -c CHAT --raw {{< /command >}} ================================================ FILE: docs/content/en/guide/tools/export-messages.md ================================================ --- title: "Export Messages" weight: 30 --- # Export Messages Export media messages from chats, channels, groups, etc. in JSON format. {{< include "snippets/chat.md" >}} {{< hint info >}} Empty CHAT means 'Saved Messages' {{< /hint >}} ## All Export all messages containing media to `tdl-export.json` {{< command >}} tdl chat export -c CHAT {{< /command >}} ## From Topic/Replies Export media messages from specific topic: {{< hint info >}} Get Topic ID: 1. Message Link: `https://t.me/c/1492447836/251011/269724` (`251011` is topic id) 2. `tdl chat ls` command {{< /hint >}} {{< command >}} tdl chat export -c CHAT --topic TOPIC_ID {{< /command >}} Export media messages from specific channel post replies: {{< command >}} tdl chat export -c CHAT --reply POST_ID {{< /command >}} ## Custom Destination Export with specific output file path. Default: `tdl-export.json`. {{< command >}} tdl chat export -c CHAT -o /path/to/output.json {{< /command >}} ## Custom Type ### Time Range Export with specific timestamp range. Default: `1970-01-01` - `NOW` {{< command >}} tdl chat export -c CHAT -T time -i 1665700000,1665761624 {{< /command >}} `time` is also the default value of `-T` option, so you can omit it {{< command >}} tdl chat export -c CHAT -i 1665700000,1665761624 {{< /command >}} ### ID Range Export with specific message id range. Default: `0` - `latest` {{< command >}} tdl chat export -c CHAT -T id -i 100,500 {{< /command >}} ### Last Export last 100 media messages: {{< command >}} tdl chat export -c CHAT -T last -i 100 {{< /command >}} ## Filter Please refer to [Filter Guide](/reference/expr) for basic knowledge about filter. List all available filter fields: {{< command >}} tdl chat export -c CHAT -f - {{< /command >}} Export last 10 zip files that `size > 5MiB` and `views > 200`: {{< command >}} tdl chat export -c CHAT -T last -i 10 -f "Views>200 && Media.Name endsWith '.zip' && Media.Size > 5*1024*1024" {{< /command >}} ## With Content Export with message content: {{< command >}} tdl chat export -c CHAT --with-content {{< /command >}} ## Raw Export Telegram MTProto raw message structure, which is useful for debugging. {{< command >}} tdl chat export -c CHAT --raw {{< /command >}} ## Non-Media Export all messages including non-media messages, which is useful for debugging/backup. {{< command >}} tdl chat export -c CHAT --all {{< /command >}} ================================================ FILE: docs/content/en/guide/tools/list-chats.md ================================================ --- title: "List Chats" weight: 10 --- # List Chats ## List all chats {{< command >}} tdl chat ls {{< /command >}} ## JSON Output {{< command >}} tdl chat ls -o json {{< /command >}} ## Filter Please refer to [Filter Guide](/reference/expr) for basic knowledge about filter. List all available filter fields: {{< command >}} tdl chat ls -f - {{< /command >}} List channels that VisibleName contains "Telegram": {{< command >}} tdl chat ls -f "Type contains 'channel' && VisibleName contains 'Telegram'" {{< /command >}} List groups that have topics: {{< command >}} tdl chat ls -f "len(Topics)>0" {{< /command >}} ================================================ FILE: docs/content/en/guide/upload.md ================================================ --- title: "Upload" weight: 40 --- # Upload ## Upload Files Upload specified files and directories to `Saved Messages`: {{< command >}} tdl up -p /path/to/file -p /path/to/dir {{< /command >}} ## Custom Destination Upload to custom chat. {{< include "snippets/chat.md" >}} ### Specific Chat Upload to specific one chat: {{< command >}} tdl up -p /path/to/file -c CHAT {{< /command >}} Upload to specific topic in a forum chat: {{< command >}} tdl up -p /path/to/file -c CHAT --topic TOPIC_ID {{< /command >}} ### Message Routing Upload to different chats by message router which is based on [expression](/reference/expr). {{< hint warning >}} The `--to` flag is conflicted with the `-c/--chat` and `--topic` flags. You can only use one of them. {{< /hint >}} List all available fields: {{< command >}} tdl up -p /path/to/file --to - {{< /command >}} Upload to `CHAT1` if MIME contains `video`, otherwise upload to `Saved Messages`: {{< hint info >}} You must return a **string** or **struct** as the target CHAT, and empty string means upload to `Saved Messages`. {{< /hint >}} {{< command >}} tdl up -p /path/to/file \ --to 'MIME contains "video" ? "CHAT1" : ""' {{< /command >}} Upload to `CHAT1` if MIME contains `video`, otherwise upload to reply to message/topic `4` in `CHAT2`: {{< command >}} tdl up -p /path/to/file \ --to 'MIME contains "video" ? "CHAT1" : { Peer: "CHAT2", Thread: 4 }' {{< /command >}} Pass a file name if the expression is complex: {{< details "router.txt" >}} Write your expression like `switch`: ```javascript MIME contains "video" ? "CHAT1" : FileExt contains ".mp3" ? "CHAT2" : FileName contains "chat3" > 30 ? {Peer: "CHAT3", Thread: 101} : "" ``` {{< /details >}} {{< command >}} tdl up -p /path/to/file --to router.txt {{< /command >}} ## Custom Parameters Upload with 8 threads per task, 4 concurrent tasks: {{< command >}} tdl up -p /path/to/file -t 8 -l 4 {{< /command >}} ## Custom Caption Custom caption is based on [expression](/reference/expr). List all available fields: {{< command >}} tdl up -p /path/to/file --caption - {{< /command >}} Custom simple caption: {{< command >}} tdl up -p /path/to/file --caption 'FileName + " - uploaded by tdl"' {{< /command >}} Write styled message with [HTML](https://core.telegram.org/bots/api#html-style): {{< command >}} tdl up -p /path/to/file --caption \ 'FileName + `Bold Link`' {{< /command >}} Pass a file name if the expression is complex: {{< details "caption.txt" >}} ```javascript repeat(FileName, 2) + ` Google Bing bold italic code spoiler

package main

import "fmt"

func main() {
    fmt.Println("hello world")
}
` + MIME ``` {{< /details >}} {{< command >}} tdl up -p /path/to/file --caption caption.txt {{< /command >}} ## Filters Upload files with extension filters: {{< hint warning >}} The extension is only matched with the file name, not the MIME type. So it may not work as expected. Whitelist and blacklist can not be used at the same time. {{< /hint >}} Whitelist: Only upload files with `.jpg` `.png` extension {{< command >}} tdl up -p /path/to/file -p /path/to/dir -i jpg,png {{< /command >}} Blacklist: Upload all files except `.mp4` `.flv` extension {{< command >}} tdl up -p /path/to/file -p /path/to/dir -e mp4 -e flv {{< /command >}} ## Delete Local Delete the uploaded file after uploading successfully: {{< command >}} tdl up -p /path/to/file --rm {{< /command >}} ## Photo Upload images as photos instead of documents: {{< command >}} tdl up -p /path/to/file --photo {{< /command >}} ================================================ FILE: docs/content/en/more/_index.md ================================================ --- title: "More" bookFlatSection: true weight: 30 --- ================================================ FILE: docs/content/en/more/cli/_index.md ================================================ --- title: "CLI" weight: 10 bookHref: "/more/cli/tdl" --- ================================================ FILE: docs/content/en/more/data.md ================================================ --- title: "Data" weight: 30 --- # Data Your account information will be stored in the `~/.tdl` directory. Log files will be stored in the `~/.tdl/log` directory. ================================================ FILE: docs/content/en/more/env.md ================================================ --- title: "Env" weight: 20 --- # Env {{< hint info >}} The values of all environment variables have a lower priority than flags. {{< /hint >}} Avoid typing the same flag values repeatedly every time by setting environment variables. | NAME | FLAG | |:-----------------------:|:---------------------:| | `TDL_NS` | `-n/--ns` | | `TDL_PROXY` | `--proxy` | | `TDL_STORAGE` | `--storage` | | `TDL_DEBUG` | `--debug` | | `TDL_SIZE` | `-s/--size` | | `TDL_THREADS` | `-t/--threads` | | `TDL_LIMIT` | `-l/--limit` | | `TDL_POOL` | `--pool` | | `TDL_NTP` | `--ntp` | | `TDL_RECONNECT_TIMEOUT` | `--reconnect-timeout` | | `TDL_TEMPLATE` | dl `--template` | {{< hint warning >}} - `TDL_STORAGE` format in env is different from that in flags: `{"type": "bolt", "path": "/path/to/data-dir"}` (JSON object). {{< /hint >}} ================================================ FILE: docs/content/en/more/troubleshooting.md ================================================ --- title: "Troubleshooting" weight: 40 --- # Troubleshooting ## Best Practices How to minimize the risk of blocking? - Login with the official client session. - Use the default download and upload options as possible. Do not set too large `threads` and `size`. - Do not use the same account to login on multiple devices at the same time. - Don't download or upload too many files at once. - Become a Telegram premium user. 😅 ## FAQ #### Q: Why no response after entering the command? And why there is `msg_id too high` in the log? **A:** Check if you need to use a proxy (use `proxy` flag); Check if your system's local time is correct (use `ntp` flag or calibrate system time) If that doesn't work, run again with `--debug` flag. Then file a new issue and paste your log in the issue. #### Q: Desktop client stop working after using tdl? **A:** If your desktop client can't receive messages, load chats, or send messages, you may encounter session conflicts. You can try re-login with `tdl login` and **select YES for logout**, which will delete the session files to separate sessions. #### Q: How to migrate session to another device? **A:** You can use the `tdl backup` and `tdl recover` commands to export and import sessions. See [Migration](/guide/migration) for more details. #### Q: Is this a form of abuse? **A:** No. The download and upload speed is limited by the server side. Since the speed of official clients usually does not reach the account limit, this tool was developed to download files at the highest possible speed. #### Q: Will this result in a ban? **A:** I am not sure. All operations do not involve dangerous actions such as actively sending messages to other people. But it's safer to use a long-term account. ================================================ FILE: docs/content/en/reference/_index.md ================================================ --- bookHidden: true --- ================================================ FILE: docs/content/en/reference/expr.md ================================================ --- title: "Expr Guide" bookHidden: true --- # Expr Guide Expr is powered by [expr](https://github.com/antonmedv/expr), which is a simple, lightweight, yet powerful expression engine. Expression engine docs: https://expr.medv.io/docs/Language-Definition It's powerful but may be a little hard to new users. So feel free to file an issue if you have any questions about the expression engine. ================================================ FILE: docs/content/en/snippets/_index.md ================================================ --- bookHidden: true --- ================================================ FILE: docs/content/en/snippets/chat.md ================================================ --- --- {{< details title="CHAT Examples" open=false >}} #### Available Values: - `@iyear` (Username) - `iyear` (Username without `@`) - `123456789` (ID) - `https://t.me/iyear` (Public Link) - `+1 123456789` (Phone) #### How to Get Chat ID on Telegram Desktop: - `Settings` → `Advanced` → `Experimental settings` → `Show Peer IDs in Profile` {{< /details >}} ================================================ FILE: docs/content/en/snippets/link.md ================================================ --- --- {{< details title="Message Link Examples" open=false >}} - `https://t.me/telegram/193` - `https://t.me/c/1697797156/151` - `https://t.me/iFreeKnow/45662/55005` - `https://t.me/c/1492447836/251015/251021` - `https://t.me/opencfdchannel/4434?comment=360409` - `https://t.me/myhostloc/1485524?thread=1485523` - `...` (File a new issue if you find a new link format) {{< /details >}} ================================================ FILE: docs/content/zh/_index.md ================================================ --- title: 介绍 --- # tdl ![](https://img.shields.io/github/go-mod/go-version/iyear/tdl?style=flat-square) ![](https://img.shields.io/github/license/iyear/tdl?style=flat-square) ![](https://img.shields.io/github/actions/workflow/status/iyear/tdl/master.yml?branch=master&style=flat-square) ![](https://img.shields.io/github/v/release/iyear/tdl?color=red&style=flat-square) ![](https://img.shields.io/github/downloads/iyear/tdl/total?style=flat-square) {{< image src="img/logo.png" align="right" height="310" width="310">}} 📥 Telegram Downloader, but more than a downloader ## 特性 - 单文件启动 - 低资源占用 - 吃满你的带宽 - 比官方客户端更快 - 支持从受保护的会话中下载文件 - 具有自动回退和消息路由的转发功能 - 支持上传文件至 Telegram - 导出历史消息/成员/订阅者数据至 JSON 文件 ## 预览 预览中的速度已经达到了代理的限制,同时**速度取决于你是否是付费用户** {{< image src="img/preview.gif" >}} ## 赞助者 ![](https://raw.githubusercontent.com/iyear/sponsor/master/sponsors.svg) ## 贡献者 contributors ================================================ FILE: docs/content/zh/getting-started/_index.md ================================================ --- title: "入门" bookFlatSection: true weight: 10 --- ================================================ FILE: docs/content/zh/getting-started/installation.md ================================================ --- title: "安装" weight: 10 --- # 安装 ## 一键脚本 {{< tabs "scripts" >}} {{< tab "Windows" >}} `tdl` 将被安装到 `$Env:SystemDrive\tdl`(将被添加到 `PATH` 中),该脚本还可用于升级 `tdl`。 #### 安装最新版本 {{< command >}} iwr -useb https://docs.iyear.me/tdl/install.ps1 | iex {{< /command >}} #### 通过 `ghproxy.com` 镜像安装 {{< command >}} $Script=iwr -useb https://docs.iyear.me/tdl/install.ps1; $Block=[ScriptBlock]::Create($Script); Invoke-Command -ScriptBlock $Block -ArgumentList "", "$True" {{< /command >}} #### 安装特定版本 {{< command >}} $Env:TDLVersion = "VERSION" $Script=iwr -useb https://docs.iyear.me/tdl/install.ps1; $Block=[ScriptBlock]::Create($Script); Invoke-Command -ScriptBlock $Block -ArgumentList "$Env:TDLVersion" {{< /command >}} {{< /tab >}} {{< tab "macOS 和 Linux" >}} `tdl` 将被安装到 `/usr/local/bin/tdl`,该脚本还可用于升级 `tdl`。 #### 安装最新版本 {{< command >}} curl -sSL https://docs.iyear.me/tdl/install.sh | sudo bash {{< /command >}} #### 通过 `ghproxy.com` 镜像安装 {{< command >}} curl -sSL https://docs.iyear.me/tdl/install.sh | sudo bash -s -- --proxy {{< /command >}} #### 安装特定版本 {{< command >}} curl -sSL https://docs.iyear.me/tdl/install.sh | sudo bash -s -- --version VERSION {{< /command >}} {{< /tab >}} {{< /tabs >}} ## 包管理器 {{< tabs "package managers" >}} {{}} {{< command >}} brew install telegram-downloader {{< /command >}} {{< /tab >}} {{}} {{< command >}} scoop bucket add extras scoop install telegram-downloader {{< /command >}} {{< /tab >}} {{}} {{< command >}} pkg install tdl {{< /command >}} {{< /tab >}} {{}} {{< command >}} yay -S tdl {{< /command >}} {{< /tab >}} {{}} #### nix-env {{< command >}} nix-env -iA nixos.tdl {{< /command >}} #### NixOS-Configuration ``` environment.systemPackages = [ pkgs.tdl ]; ``` #### nix-shell {{< command >}} nix-shell -p tdl {{< /command >}} {{< /tab >}} {{< /tabs >}} [![Packaging status](https://repology.org/badge/vertical-allrepos/telegram-downloader.svg)](https://repology.org/project/telegram-downloader/versions) ## Docker 可用镜像: - [`iyear/tdl`](https://hub.docker.com/r/iyear/tdl) - [`ghcr.io/iyear/tdl`](https://ghcr.io/iyear/tdl) 可用标签: - `latest`(默认):最新的稳定版本 - `X.Y.Z`:`tdl`的特定版本 {{< tabs "docker" >}} {{< tab "Docker" >}} 以一次性命令运行 `tdl`: {{< command >}} docker run --rm -it iyear/tdl {{< /command >}} 进一步,挂载配置目录以保持持久化: {{< command >}} docker run --rm -it \ -v $HOME/.tdl:/root/.tdl \ iyear/tdl {{< /command >}} 为了方便获取下载的文件,可以挂载下载目录和其他需要的目录: {{< command >}} docker run --rm -it \ -v $HOME/.tdl:/root/.tdl \ -v $HOME/Downloads:/downloads \ iyear/tdl {{< /command >}} 在容器内运行 `tdl`: {{< command >}} docker run --rm -it --entrypoint sh iyear/tdl {{< /command >}} {{< details title="预览输出" open=false >}} ```1 / # tdl version Version: 0.17.7 Commit: ace2402 Date: 2024-11-01T14:40:56+08:00 go1.21.13 linux/amd64 / # ``` {{< /details >}} 如果希望使用 `localhost` 地址的代理,使用 `host` 网络运行: {{< command >}} docker run --rm -it --network host iyear/tdl {{< /command >}} {{< /tab >}} {{< tab "Docker Compose" >}} 使用 Docker Compose 运行 `tdl`,避免每次输入 `docker run` 选项。 {{< details title="docker-compose.yml" open=false >}} {{< hint info >}} 示例配置使用 Docker Compose v2 语法。 {{< /hint >}} ```yaml services: tdl: image: iyear/tdl # 或指定特定版本的 X.Y.Z 版本标签 volumes: - $HOME/.tdl:/root/.tdl # 保持配置持久化 - $HOME/Downloads:/downloads # 可选 # - /path/to/your/need:/path/in/container stdin_open: true tty: true # 如果需要使用 localhost 地址的代理,使用 host 网络 network_mode: host ``` {{< /details >}} 使用 Docker Compose 运行 `tdl`: {{< command >}} docker compose run --rm tdl {{< /command >}} 在容器内运行 `tdl`: {{< command >}} docker compose run --rm --entrypoint sh tdl {{< /command >}} {{< details title="预览输出" open=false >}} ```1 / # tdl version Version: 0.17.7 Commit: ace2402 Date: 2024-11-01T14:40:56+08:00 go1.21.13 linux/amd64 / # ``` {{< /details >}} {{< /tab >}} {{< /tabs >}} ## 预编译二进制 1. 下载指定操作系统和架构的压缩包: {{< tabs "prebuilt" >}} {{< tab "Windows" >}} {{< button href="https://github.com/iyear/tdl/releases/latest/download/tdl_Windows_64bit.zip" >}}x86_64/amd64{{< /button >}} {{< button href="https://github.com/iyear/tdl/releases/latest/download/tdl_Windows_32bit.zip" >}}x86{{< /button >}} {{< button href="https://github.com/iyear/tdl/releases/latest/download/tdl_Windows_arm64.zip" >}}arm64{{< /button >}} {{< button href="https://github.com/iyear/tdl/releases/latest/download/tdl_Windows_armv5.zip" >}}armv5{{< /button >}} {{< button href="https://github.com/iyear/tdl/releases/latest/download/tdl_Windows_armv6.zip" >}}armv6{{< /button >}} {{< button href="https://github.com/iyear/tdl/releases/latest/download/tdl_Windows_armv7.zip" >}}armv7{{< /button >}} {{< /tab >}} {{< tab "macOS" >}} {{< button href="https://github.com/iyear/tdl/releases/latest/download/tdl_MacOS_64bit.tar.gz" >}}Intel{{< /button >}} {{< button href="https://github.com/iyear/tdl/releases/latest/download/tdl_MacOS_arm64.tar.gz" >}}M1/M2{{< /button >}} {{< /tab >}} {{< tab "Linux" >}} {{< button href="https://github.com/iyear/tdl/releases/latest/download/tdl_Linux_64bit.tar.gz" >}}x86_64/amd64{{< /button >}} {{< button href="https://github.com/iyear/tdl/releases/latest/download/tdl_Linux_32bit.tar.gz" >}}x86{{< /button >}} {{< button href="https://github.com/iyear/tdl/releases/latest/download/tdl_Linux_arm64.tar.gz" >}}arm64{{< /button >}} {{< button href="https://github.com/iyear/tdl/releases/latest/download/tdl_Linux_armv5.tar.gz" >}}armv5{{< /button >}} {{< button href="https://github.com/iyear/tdl/releases/latest/download/tdl_Linux_armv6.tar.gz" >}}armv6{{< /button >}} {{< button href="https://github.com/iyear/tdl/releases/latest/download/tdl_Linux_armv7.tar.gz" >}}armv7{{< /button >}} {{< /tab >}} {{< /tabs >}} 2. 解压缩压缩包 3. 将可执行文件移动到所需目录 4. 将此目录添加到 PATH 环境变量 5. 确保您对文件具有执行权限 ## 源代码 要从源代码构建 `tdl` 的扩展版本,您必须: 1. 安装 [Git](https://git-scm.com/) 2. 安装 Go 的 1.25 版本或更高版本 3. 根据 Go 文档中的描述更新您的 `PATH` 环境变量 {{< hint info >}} 安装目录由 `GOPATH` 和 `GOBIN` 环境变量控制。如果设置了 `GOBIN`,则二进制文件将安装到该目录。如果设置了 `GOPATH`,则二进制文件将安装到 `GOPATH` 列表中第一个目录的 `bin` 子目录。否则,二进制文件将安装到默认的 `GOPATH` 的 `bin` 子目录(`$HOME/go` 或 `%USERPROFILE%\go`)。 {{< /hint >}} 然后构建: {{< command >}} go install github.com/iyear/tdl@latest tdl version {{< /command >}} ================================================ FILE: docs/content/zh/getting-started/quick-start.md ================================================ --- title: "快速开始" weight: 20 --- # 快速开始 ## 登录 我们不在这里指定命名空间,它将使用 `default` 命名空间。如果你想使用其他命名空间,可以使用 `-n` 标志指定命名空间。 ### **使用桌面客户端登录** {{< hint warning >}} 请确保从[官方网站](https://desktop.telegram.org/)下载客户端(不要从 Microsoft Store 或 App Store 下载) {{< /hint >}} 使用默认路径: {{< command >}} tdl login {{< /command >}} 如果您设置了本地密码: {{< command >}} tdl login -p YOUR_PASSCODE {{< /command >}} 或者指定自定义客户端路径: {{< command >}} tdl login -d /path/to/TelegramDesktop {{< /command >}} ### **使用二维码登录** {{< command >}} tdl login -T qr {{< /command >}} ### **使用手机号码和验证码登录** {{< command >}} tdl login -T code {{< /command >}} ## 下载 我们从 Telegram 官方频道下载文件: {{< command >}} tdl dl -u https://t.me/telegram/193 {{< /command >}} ================================================ FILE: docs/content/zh/getting-started/shell-completion.md ================================================ --- title: "自动补全" weight: 30 --- # 自动补全 运行对应的命令以在所有会话中启用 Shell 自动补全: {{< tabs "shell" >}} {{< tab "bash" >}} {{< command >}} echo "source <(tdl completion bash)" >> ~/.bashrc {{< /command >}} {{< /tab >}} {{< tab "zsh" >}} {{< command >}} echo "source <(tdl completion zsh)" >> ~/.zshrc {{< /command >}} {{< /tab >}} {{< tab "fish" >}} {{< command >}} echo "tdl completion fish | source" >> ~/.config/fish/config.fish {{< /command >}} {{< /tab >}} {{< tab "PowerShell" >}} {{< command >}} Add-Content -Path $PROFILE -Value "tdl completion powershell | Out-String | Invoke-Expression" {{< /command >}} {{< /tab >}} {{< /tabs >}} ================================================ FILE: docs/content/zh/guide/_index.md ================================================ --- title: "指南" bookFlatSection: true weight: 20 --- ================================================ FILE: docs/content/zh/guide/download.md ================================================ --- title: "下载" weight: 30 --- # 下载 ## 从链接下载: {{< hint info >}} 点击官方客户端的 "复制链接" 按钮获取消息链接。 {{< /hint >}} {{< include "snippets/link.md" >}} {{< command >}} tdl dl -u https://t.me/tdl/1 -u https://t.me/tdl/2 {{< /command >}} ## 从 JSON 下载: 有两种导出 JSON 文件的方式: {{< tabs "json" >}} {{< tab "tdl" >}} 请参考 [导出消息](/zh/guide/tools/export-messages) {{< /tab >}} {{< tab "桌面客户端" >}} 1. 选择要导出的对话,点击右上角的三个点,然后点击 `导出聊天历史`。 2. 取消选中所有选项(您现在不需要下载它们),将 `大小限制` 设置为最小值。 3. 设置格式为 `JSON` 并选择您需要的时间段。 4. 导出它!`result.json` 就是您需要的文件。 {{< /tab >}} {{< /tabs >}} {{< command >}} tdl dl -f result1.json -f result2.json {{< /command >}} ## 合并下载: {{< command >}} tdl dl \ -u https://t.me/tdl/1 -u https://t.me/tdl/2 \ -f result1.json -f result2.json {{< /command >}} ## 自定义目录: 将文件下载到自定义目录 {{< command >}} tdl dl -u https://t.me/tdl/1 -d /path/to/dir {{< /command >}} ## 自定义参数: 使用每个任务8个线程,4个并发任务下载: {{< command >}} tdl dl -u https://t.me/tdl/1 -t 8 -l 4 {{< /command >}} ## 反序下载: 按反序下载文件(从最新到最旧) {{< hint warning >}} 不同的顺序将影响“恢复下载”功能 {{< /hint >}} {{< command >}} tdl dl -f result.json --desc {{< /command >}} ## MIME 探测: 如果文件扩展名与 MIME 类型不匹配,tdl将使用正确的扩展名重命名文件。 {{< hint warning >}} 副作用:例如 `.apk` 文件将被重命名为 `.zip`。 {{< /hint >}} {{< command >}} tdl dl -u https://t.me/tdl/1 --rewrite-ext {{< /command >}} ## 相册/组合消息探测 自动检测消息是否为相册/组合消息,并下载相应的所有文件。 {{< command >}} tdl dl -u https://t.me/tdl/1 --group {{< /command >}} ## 自动跳过 在下载时跳过相同的文件(即名称和大小相同)。 {{< command >}} tdl dl -u https://t.me/tdl/1 --skip-same {{< /command >}} ## "Takeout" 会话 通过 ["Takeout" 会话](https://arabic-telethon.readthedocs.io/en/stable/extra/examples/telegram-client.html#exporting-messages) 下载文件: > 如果下载大量媒体,更倾向于使用 "Takeout" 会话,它允许您以较低的速率限制从您的帐户中导出数据。 {{< command >}} tdl dl -u https://t.me/tdl/1 --takeout {{< /command >}} ## 过滤器 使用扩展名过滤器下载文件: {{< hint warning >}} 扩展名仅与文件名匹配,而不是 MIME 类型。因此,这可能不会按预期工作。 白名单和黑名单不能同时使用。 {{< /hint >}} 白名单:只下载扩展名为 `.jpg` `.png` 的文件 {{< command >}} tdl dl -u https://t.me/tdl/1 -i jpg,png {{< /command >}} 黑名单:下载除了扩展名为 `.mp4` `.flv` 的所有文件 {{< command >}} tdl dl -u https://t.me/tdl/1 -e mp4,flv {{< /command >}} ## 文件名模板 使用自定义文件名模板下载: 请参考 [模板指南](/zh/guide/template) 了解更多。 {{< command >}} tdl dl -u https://t.me/tdl/1 \ --template "{{ .DialogID }}_{{ .MessageID }}_{{ .DownloadDate }}_{{ .FileName }}" {{< /command >}} ## 恢复/重新开始下载 在不需要交互的情况下恢复下载: {{< command >}} tdl dl -u https://t.me/tdl/1 --continue {{< /command >}} 在不需要交互的情况下重新开始下载: {{< command >}} tdl dl -u https://t.me/tdl/1 --restart {{< /command >}} ## HTTP 文件服务器 将文件暴露为 HTTP 服务器,而不使用内置下载它们 {{< hint info >}} 当您想要使用下载管理器(如 `aria2`/`wget`/`axel`/`IDM`)下载文件时,适合使用此选项。 {{< /hint >}} {{< command >}} tdl dl -u https://t.me/tdl/1 --serve {{< /command >}} 使用自定义端口: {{< command >}} tdl dl -u https://t.me/tdl/1 --serve --port 8081 {{< /command >}} ================================================ FILE: docs/content/zh/guide/extensions.md ================================================ --- title: "扩展 🆕" weight: 70 --- # 扩展 {{< hint warning >}} 扩展是 tdl 的一项新功能,仍处于实验阶段,CLI 可能会在未来版本中发生变化。 如果你遇到任何问题或有任何建议,请在 GitHub 上[创建 Issue](https://github.com/iyear/tdl/issues/new/choose)。 {{< /hint >}} ## 概览 tdl 扩展是与 tdl 核心无缝集成的独立工具。它们提供了一种扩展 tdl 核心的方法,但不需要将每个新功能添加到核心代码中。 tdl 扩展具有以下特点: - 它们可以添加和删除,而不会影响 tdl 核心。 - 它们与 tdl 集成,并会显示在 tdl 命令和其他地方。 tdl 扩展位于 `~/.tdl/extensions`,由 `tdl extension` 子命令控制。 使用以下命令快速体验 tdl 扩展: {{< command >}} tdl extension install iyear/tdl-whoami {{< /command >}} {{< command >}} tdl whoami {{< /command >}} 你可以看到 `tdl-whoami` 扩展的输出。详情请参阅 [tdl-whoami](https://github.com/iyear/tdl-whoami)。 ``` You are XXXXX. ID: XXXXXXXX ``` ## 查找扩展 你可以通过浏览[带有 `tdl-extension` 主题的代码库](https://github.com/topics/tdl-extension)来查找扩展。 ## 安装扩展 要安装扩展,请使用 `extension install` 子命令。 扩展有两种类型: - `GitHub` : 托管在 GitHub 代码库上的扩展。 {{< command >}} tdl extension install / {{< /command >}} 要从私有代码库安装扩展,必须设置 `GITHUB_TOKEN` 环境变量为 [GitHub 个人访问令牌](https://github.com/settings/personal-access-tokens/new)(具有 `Contents` 读取权限)。 {{< command >}} export GITHUB_TOKEN=YOUR_TOKEN tdl extension install / {{< /command >}} - `Local` : 存储在本地计算机上的扩展。 {{< command >}} tdl extension install /path/to/extension {{< /command >}} 强制安装已经存在的扩展,请使用 `--force` 选项: {{< command >}} tdl extension install --force EXTENSION {{< /command >}} 一次安装多个扩展,请使用以下命令: {{< command >}} tdl extension install / /path/to/extension2 ... {{< /command >}} 仅打印信息而不实际安装扩展,请使用 `--dry-run` 选项: {{< command >}} tdl extension install --dry-run EXTENSION {{< /command >}} 如果你已经安装了同名的扩展,安装将失败。例如,如果你已经安装了 `foo/tdl-whoami`,则必须在安装 `bar/tdl-whoami` 之前卸载它。 ## 运行扩展 安装扩展后,可以像运行本地 tdl 命令一样运行扩展,使用 `tdl EXTENSION-NAME`。`EXTENSION-NAME` 是包含扩展的代码库的名称,去掉 `tdl-` 前缀。 例如,如果你从 `iyear/tdl-whoami` 代码库安装了扩展,可以使用以下命令运行扩展。 {{< command >}} tdl whoami {{< /command >}} 运行扩展时,全局配置仍然可用。例如,以下命令在运行 `tdl-whoami` 扩展时指定命名空间和代理。 {{< command >}} tdl -n foo --proxy socks5://localhost:1080 whoami {{< /command >}} 扩展自身的选项也可以使用。例如,以下命令在运行 `tdl-whoami` 扩展时启用详细模式。 {{< hint info >}} 请记住在扩展子命令之前写全局选项,在扩展子命令之后写扩展选项: {{< command >}} tdl <全局选项> <扩展名> <扩展选项> {{< /command >}} {{< /hint >}} {{< command >}} tdl -n foo whoami -v {{< /command >}} 通常可以在包含扩展的代码库的 README 中找到有关如何使用扩展的具体信息。 ## 查看已安装的扩展 要查看所有已安装的扩展,请使用 `extension list` 子命令。此命令将列出所有已安装的扩展及其作者和版本。 {{< command >}} tdl extension list {{< /command >}} ## 更新扩展 要更新扩展,请使用 `extension upgrade` 子命令。将 `EXTENSION` 参数替换为扩展的名称。 {{< command >}} tdl extension upgrade EXTENSION1 EXTENSION2 ... {{< /command >}} 更新所有已安装的扩展,请设置 `EXTENSION` 参数为空。 {{< command >}} tdl extension upgrade {{< /command >}} 从 GitHub 私有代码库升级扩展,必须设置 `GITHUB_TOKEN` 环境变量为 [GitHub 个人访问令牌](https://github.com/settings/personal-access-tokens/new)(具有 `Contents` 读取权限)。 {{< command >}} export GITHUB_TOKEN=YOUR_TOKEN tdl extension upgrade EXTENSION {{< /command >}} 仅打印信息而不实际升级扩展,请使用 `--dry-run` 选项: {{< command >}} tdl extension upgrade --dry-run EXTENSION {{< /command >}} ## 卸载扩展 要卸载扩展,请使用 `extension remove` 子命令。将 `EXTENSION` 参数替换为扩展的名称。 {{< command >}} tdl extension remove EXTENSION1 EXTENSION2 ... {{< /command >}} 仅打印信息而不实际卸载扩展,请使用 `--dry-run` 选项: {{< command >}} tdl extension remove --dry-run EXTENSION {{< /command >}} ## 开发扩展 请参阅 [tdl-extension-template](https://github.com/iyear/tdl-extension-template) 代码库,了解如何为 tdl 创建、构建和发布扩展。 ================================================ FILE: docs/content/zh/guide/forward.md ================================================ --- title: "转发" weight: 35 --- # 转发 具有自动回退和消息路由的转发功能 一行命令将消息从 `https://t.me/telegram/193` 转发到 `收藏夹`: {{< command >}} tdl forward --from https://t.me/telegram/193 {{< /command >}} ## 自定义来源 {{< include "snippets/link.md" >}} 您可以从链接和[导出的JSON文件](/zh/guide/download/#从-json-下载)转发消息: {{< command >}} tdl forward \ --from https://t.me/telegram/193 \ --from https://t.me/telegram/195 \ --from tdl-export.json \ --from tdl-export2.json {{< /command >}} ## 自定义目标 {{< include "snippets/chat.md" >}} ### 特定聊天 转发到特定的聊天: {{< command >}} tdl forward --from tdl-export.json --to CHAT {{< /command >}} ### 消息路由 通过基于 [expr](/zh/reference/expr) 的路由将消息转发至不同的聊天 列出所有可用的字段: {{< command >}} tdl forward --from tdl-export.json --to - {{< /command >}} 如果消息包含 `foo`,则转发到 `CHAT1`,否则转发到 `收藏夹`: {{< hint info >}} 表达式必须返回一个**字符串**或者**结构体**作为目标 CHAT,空字符串表示转发到 `收藏夹`。 {{< /hint >}} {{< command >}} tdl forward --from tdl-export.json \ --to 'Message.Message contains "foo" ? "CHAT1" : ""' {{< /command >}} 转发含有 `foo` 的消息到 `CHAT1`,否则转发到 `CHAT2` 中 ID 为 4 的消息/主题: {{< command >}} tdl forward --from tdl-export.json \ --to 'Message.Message contains "foo" ? "CHAT1" : { Peer: "CHAT2", Thread: 4 }' {{< /command >}} 如果表达式较复杂,你可以传递文件名: {{< details "router.txt" >}} 你可以像写 `switch` 一样编写表达式: ```javascript Message.Message contains "foo" ? "CHAT1" : From.ID == 123456 ? "CHAT2" : Message.Views > 30 ? { Peer: "CHAT3", Thread: 101 } : "" ``` {{< /details >}} {{< command >}} tdl forward --from tdl-export.json --to router.txt {{< /command >}} ## 模式 消息转发采取自动降级策略 可用模式: - `direct`(默认) - `clone` ### Direct 优先使用官方的转发API。 如果聊天或消息不允许使用官方转发API,将自动降级为 `clone` 模式。 {{< command >}} tdl forward --from tdl-export.json --mode direct {{< /command >}} ### Clone 通过复制方式转发消息,将不包含转发来源的标头。 将自动忽略一些无法复制的消息内容,例如投票、发票等 {{< command >}} tdl forward --from tdl-export.json --mode clone {{< /command >}} ## 编辑 使用[表达式引擎](/reference/expr)编辑转发前的消息。 {{< hint info >}} - 你必须传递合并照片的第一条消息才能编辑标题。 - 你可以传递任何合并文档的消息以编辑相应的评论。 {{< /hint >}} 你可以在表达式中引用原始消息的相关字段。 列出所有可用字段: {{< command >}} tdl forward --from tdl-export.json --edit - {{< /command >}} 在原始消息后附加 `测试转发消息`: {{< command >}} tdl forward --from tdl-export.json --edit 'Message.Message + " 测试转发消息"' {{< /command >}} 以[HTML](https://core.telegram.org/bots/api#html-style)格式编写带有样式的消息: {{< command >}} tdl forward --from tdl-export.json --edit \ 'Message.Message + `粗体 链接`' {{< /command >}} 如果表达式较复杂,可以传递文件名: {{< details "edit.txt" >}} ```javascript repeat(Message.Message, 2) + ` 谷歌 必应 粗体 斜体 代码 剧透

package main

import "fmt"

func main() {
    fmt.Println("hello world")
}
` + From.VisibleName ``` {{< /details >}} {{< command >}} tdl forward --from tdl-export.json --edit edit.txt {{< /command >}} ## 试运行 只打印进度而不实际发送消息,可以用于调试消息路由的效果。 {{< command >}} tdl forward --from tdl-export.json --dry-run {{< /command >}} ## 静默发送 发送消息而不通知其他成员。 {{< command >}} tdl forward --from tdl-export.json --silent {{< /command >}} ## 取消分组检测 默认情况下,tdl 将自动探测到分组消息并将它们转发为合并的消息。 你可以通过 `--single` 禁用此行为,将其作为单个消息转发。 {{< command >}} tdl forward --from tdl-export.json --single {{< /command >}} ## 反序 对每个来源的消息进行反序转发。 {{< command >}} tdl forward --from tdl-export.json --desc {{< /command >}} ================================================ FILE: docs/content/zh/guide/global-config.md ================================================ --- title: "全局设置" weight: 10 --- # 全局配置 全局配置是可以在每个命令中设置的选项。 {{< hint info >}} **每次都设置全局配置!** 全局配置**不代表**配置会被持久化或者只需要在全局设置一次,它们只会在当前命令中生效。 你需要在每一个命令中设置它们。 {{< /hint >}} ## `-n/--ns` 每个命名空间代表一个 Telegram 帐号。默认值:`default`。 例如你想新增一个其他账户,为所有命令都添加 `-n YOUR_ACCOUNT_NAME` 选项即可: {{< command >}} tdl -n iyear {{< /command >}} ## `--proxy` 设置代理。默认值:`""`。 格式:`protocol://username:password@host:port` {{< command >}} tdl --proxy socks5://localhost:1080 tdl --proxy http://localhost:8080 tdl --proxy https://localhost:8081 {{< /command >}} ## `--storage` 设置存储。默认值:`type=bolt,path=~/.tdl/data` 格式: `type=驱动,opt1=val1,opt2=val2,...` 可用的驱动: | 驱动名 | 选项 | 描述 | |:----------:|:------------------------------:|---------------------------------------------| | `bolt`(默认) | `path=/path/to/data-directory` | 将数据存储在单独的数据库文件中,因此您可以在多个进程中使用(但必须是不同的命名空间)。 | | `file` | `path=/path/to/data.json` | 将数据存储在单个 JSON 文件中,通常用于调试。 | | `legacy` | `path=/path/to/data.kv` | **已弃用。** 将数据存储在单个数据库文件中,因此你**不能**在多个进程中使用它。 | | - | - | 等待更多驱动... | {{< command >}} tdl --storage type=bolt,path=/path/to/data-dir {{< /command >}} ## `--ntp` 设置 NTP 服务器。如果为空,将使用系统时间。默认值:`""`。 {{< command >}} tdl --ntp pool.ntp.org {{< /command >}} ## `--reconnect-timeout` 设置 Telegram 连接的重连超时。默认值:`2m`。 {{< hint info >}} 如果您的网络不稳定,请将超时设置为更长时间或0(无限)。 {{< /hint >}} {{< command >}} tdl --reconnect-timeout 1m30s {{< /command >}} ## `--debug` 启用调试级别日志。默认值:`false`。 {{< command >}} tdl --debug {{< /command >}} ## `--pool` 设置 Telegram 客户端的连接池大小。默认值:`8`。 {{< hint info >}} 如果你想要更快的速度,请将连接池设置的更大或者0(无限)。 {{< /hint >}} {{< command >}} tdl --pool 2 {{< /command >}} ## `--delay` 设置每个任务之间的延迟。默认值:`0s`。 {{< hint info >}} 如果你想避免因为短时间内产生大量请求被限流,请设置更长的延迟时间。 {{< /hint >}} {{< command >}} tdl --delay 5s {{< /command >}} ================================================ FILE: docs/content/zh/guide/login.md ================================================ --- type: "docs" title: "登录" weight: 20 bookHref: "/zh/getting-started/quick-start/#login" --- # Login ================================================ FILE: docs/content/zh/guide/migration.md ================================================ --- title: "迁移" weight: 50 --- # 迁移 备份或恢复您的数据 ## 备份 将您的数据备份到文件中。默认值:`.backup.tdl`。 {{< command >}} tdl backup {{< /command >}} 或者指定输出文件: {{< command >}} tdl backup -d /path/to/custom.tdl {{< /command >}} ## 恢复 从备份文件中恢复您的数据。 {{< command >}} tdl recover -f /path/to/custom.backup.tdl {{< /command >}} ## 迁移 将数据迁移到另一个存储中 查看[存储](/zh/guide/global-config/#--storage)以获取存储选项的详细信息。 迁移当前存储到文件类型存储: {{< command >}} tdl migrate --to type=file,path=/path/to/data.json {{< /command >}} 迁移自定义存储到文件类型存储: {{< command >}} tdl migrate --storage type=bolt,path=/path/to/data-directory --to type=file,path=/path/to/data.json {{< /command >}} ================================================ FILE: docs/content/zh/guide/template.md ================================================ --- title: "模板指南" bookHidden: true bookToC: false --- # 模板指南 本指南将介绍可用于 tdl 模板中的变量和函数。 模板语法基于[Go text/template](https://golang.org/pkg/text/template/)。 ## 下载 ### 变量 (Beta) | 变量 | 描述 | |:--------------:|:---------------------:| | `DialogID` | Telegram 对话ID | | `MessageID` | Telegram 消息ID | | `MessageDate` | Telegram 消息日期(时间戳) | | `FileName` | Telegram 文件名 | | `FileCaption` | Telegram 文件说明,也就是文本消息 | | `FileSize` | 可读的文件大小,例如 `1GB` | | `DownloadDate` | 下载日期(时间戳) | ### 函数 (Beta) | 函数 | 描述 | 用法 | 示例 | |:------------:|:------------------------------------------------------------------------------------------:|:------------------------------------------------------------:|:-------------------------------------------------------------------------------------:| | `repeat` | 重复 `STRING` `N` 次 | `repeat STRING N` | `{{ repeat "test" 3 }}` | | `replace` | 对 `STRING` 执行 `PAIRS` 替换 | `replace STRING PAIRS...` | `{{ replace "Test" "t" "T" "e" "E" }}` | | `upper` | 将 `STRING` 转换为大写 | `upper STRING` | `{{ upper "Test" }}` | | `lower` | 将 `STRING` 转换为小写 | `lower STRING` | `{{ lower "Test" }}` | | `snakecase` | 将 `STRING` 转换为 snake_case | `snakecase STRING` | `{{ snakecase "Test" }}` | | `camelcase` | 将 `STRING` 转换为 camelCase | `camelcase STRING` | `{{ camelcase "Test" }}` | | `kebabcase` | 将 `STRING` 转换为 kebab-case | `kebabcase STRING` | `{{ kebabcase "Test" }}` | | `rand` | 在范围 `MIN` 到 `MAX` 生成随机数 | `rand MIN MAX` | `{{ rand 1 10 }}` | | `now` | 获取当前时间戳 | `now` | `{{ now }}` | | `formatDate` | [格式化](https://zhuanlan.zhihu.com/p/145009400) `TIMESTAMP` 时间戳
(默认格式: `20060102150405`) | `formatDate TIMESTAMP`
`formatDate TIMESTAMP "format"` | `{{ formatDate 1600000000 }}`
`{{ formatDate 1600000000 "2006-01-02-15-04-05"}}` | | `filenamify` | 尽可能将 `STRING` 转换为合法文件名,可选 `MaxLength` 限制字符串长度避免文件系统限制 | `filenamify STRING MaxLength` | `{{ filenamify .FileName 32 }}` | ### 示例: ```gotemplate {{ .DialogID }}_{{ .MessageID }}_{{ replace .FileCaption `/` `_` `\` `_` `:` `_` }} {{ .FileName }}_{{ formatDate .DownloadDate }}_{{ .FileSize }} {{ .FileName }}_{{ formatDate .DownloadDate "2006-01-02-15-04-05"}}_{{ .FileSize }} {{ lower (replace .FileName ` ` `_`) }} {{ formatDate (now) }} ``` ### 默认: ```gotemplate {{ .DialogID }}_{{ .MessageID }}_{{ filenamify .FileName }} ``` ================================================ FILE: docs/content/zh/guide/tools/_index.md ================================================ --- title: "工具" bookCollapseSection: true weight: 60 --- ================================================ FILE: docs/content/zh/guide/tools/export-members.md ================================================ --- title: "导出成员" weight: 20 --- # 导出成员 导出聊天成员/订阅者、管理员、机器人等。 {{< hint info >}} 部分类型用户(被禁用户/被踢出用户/……)导出需要聊天管理员权限。 {{< /hint >}} {{< include "snippets/chat.md" >}} ## 默认 将所有用户导出为 `tdl-users.json` {{< command >}} tdl chat users -c CHAT {{< /command >}} ## 自定义路径 指定文件路径进行导出 {{< command >}} tdl chat users -c CHAT -o /path/to/export.json {{< /command >}} ## 原始数据 导出 Telegram MTProto 原始用户结构,用于调试。 {{< command >}} tdl chat users -c CHAT --raw {{< /command >}} ================================================ FILE: docs/content/zh/guide/tools/export-messages.md ================================================ --- title: "导出消息" weight: 30 --- # 导出消息 以 JSON 格式导出聊天、频道、群组等中的媒体消息。 {{< include "snippets/chat.md" >}} {{< hint info >}} 空的 CHAT 表示“收藏夹” {{< /hint >}} ## 所有消息 将包含媒体的所有消息导出到 `tdl-export.json` {{< command >}} tdl chat export -c CHAT {{< /command >}} ## 从主题/回复中导出 从特定主题导出媒体消息: {{< hint info >}} 获取主题 ID 的方式: 1. 消息链接:`https://t.me/c/1492447836/251011/269724`(`251011` 是主题 ID) 2. `tdl chat ls` 命令 {{< /hint >}} {{< command >}} tdl chat export -c CHAT --topic TOPIC_ID {{< /command >}} 从特定频道帖子的回复中导出媒体消息: {{< command >}} tdl chat export -c CHAT --reply POST_ID {{< /command >}} ## 自定义路径 指定输出文件路径进行导出。默认:`tdl-export.json`。 {{< command >}} tdl chat export -c CHAT -o /path/to/output.json {{< /command >}} ## 自定义类型 ### 时间范围 根据特定的时间戳范围进行导出。默认:`1970-01-01` - `当前` {{< command >}} tdl chat export -c CHAT -T time -i 1665700000,1665761624 {{< /command >}} `time` 也是 `-T` 选项的默认值,因此您可以省略它 {{< command >}} tdl chat export -c CHAT -i 1665700000,1665761624 {{< /command >}} ### ID 范围 根据特定的消息 ID 范围进行导出。默认:`0` - `最新` {{< command >}} tdl chat export -c CHAT -T id -i 100,500 {{< /command >}} ### 最新 导出最后 100 条媒体文件: {{< command >}} tdl chat export -c CHAT -T last -i 100 {{< /command >}} ## 过滤 请参考[过滤器指南](/zh/reference/expr)以获取有关过滤器的基本知识。 列出所有可用的过滤字段: {{< command >}} tdl chat export -c CHAT -f - {{< /command >}} 导出最后的 10 个媒体文件,其中 `大小 > 5MiB` 且 `查看次数 > 200`: {{< command >}} tdl chat export -c CHAT -T last -i 10 -f "Views>200 && Media.Name endsWith '.zip' && Media.Size > 5*1024*1024" {{< /command >}} ## 包含内容 附带消息内容: {{< command >}} tdl chat export -c CHAT --with-content {{< /command >}} ## 原始数据 导出 Telegram MTProto 原始消息结构,用于调试。 {{< command >}} tdl chat export -c CHAT --raw {{< /command >}} ## 非媒体消息 导出包括非媒体消息的所有消息,用于调试/备份。 {{< command >}} tdl chat export -c CHAT --all {{< /command >}} ================================================ FILE: docs/content/zh/guide/tools/list-chats.md ================================================ --- title: "列出聊天" weight: 10 --- # 列出聊天 ## 列出所有聊天 {{< command >}} tdl chat ls {{< /command >}} ## JSON 格式 {{< command >}} tdl chat ls -o json {{< /command >}} ## 过滤器 请参考 [过滤器指南](/zh/reference/expr) 以获取有关过滤器的基本知识。 列出所有可用的过滤字段: {{< command >}} tdl chat ls -f - {{< /command >}} 列出名字包含 "Telegram" 的频道: {{< command >}} tdl chat ls -f "Type contains 'channel' && VisibleName contains 'Telegram'" {{< /command >}} 列出具有主题的群组: {{< command >}} tdl chat ls -f "len(Topics)>0" {{< /command >}} ================================================ FILE: docs/content/zh/guide/upload.md ================================================ --- title: "上传" weight: 40 --- # 上传 ## 上传文件 上传指定的文件和目录到 `保存的消息`: {{< command >}} tdl up -p /path/to/file -p /path/to/dir {{< /command >}} ## 自定义目标 上传到自定义聊天。 {{< include "snippets/chat.md" >}} ## 指定聊天 上传到指定的聊天: {{< command >}} tdl up -p /path/to/file -c CHAT {{< /command >}} 上传到论坛型聊天的指定主题: {{< command >}} tdl up -p /path/to/file -c CHAT --topic TOPIC_ID {{< /command >}} ## 消息路由 通过基于[表达式](/reference/expr)的消息路由,将文件上传到不同的聊天: {{< hint warning >}} `--to` 标志与 `-c/--chat` 和 `--topic` 标志冲突,只能使用其中一个。 {{< /hint >}} 列出所有可用字段: {{< command >}} tdl up -p /path/to/file --to - {{< /command >}} 如果 MIME 包含 `video` 则上传到 `CHAT1`,否则上传到 `收藏夹`: {{< hint info >}} 必须返回一个字符串或结构体作为目标聊天,空字符串表示上传到 `收藏夹`。 {{< /hint >}} {{< command >}} tdl up -p /path/to/file \ --to 'MIME contains "video" ? "CHAT1" : ""' {{< /command >}} 如果 MIME 包含 `video` 则上传到 `CHAT1`,否则回复 `CHAT2` 的消息/主题 `4`: {{< command >}} tdl up -p /path/to/file \ --to 'MIME contains "video" ? "CHAT1" : { Peer: "CHAT2", Thread: 4 }' {{< /command >}} 如果表达式较复杂,可以传递文件名: {{< details "router.txt" >}} 像使用 `switch` 一样编写表达式: ```javascript MIME contains "video" ? "CHAT1" : FileExt contains ".mp3" ? "CHAT2" : FileName contains "chat3" > 30 ? {Peer: "CHAT3", Thread: 101} : "" ``` {{< /details >}} {{< command >}} tdl up -p /path/to/file --to router.txt {{< /command >}} ## 自定义参数 使用每个任务8个线程、4个并发任务上传: {{< command >}} tdl up -p /path/to/file -t 8 -l 4 {{< /command >}} ## 自定义标题 使用[表达式引擎](/reference/expr)编写自定义标题。 列出所有可用字段: {{< command >}} tdl up -p /path/to/file --caption - {{< /command >}} 自定义简单的标题: {{< command >}} tdl up -p ./path/to/file --caption 'FileName + " - uploaded by tdl"' {{< /command >}} 以[HTML](https://core.telegram.org/bots/api#html-style)格式编写带有样式的消息: {{< command >}} tdl up -p /path/to/file --caption \ 'FileName + `Bold Link`' {{< /command >}} 如果表达式较复杂,可以传递文件名: {{< details "caption.txt" >}} ```javascript repeat(FileName, 2) + ` Google Bing bold italic code spoiler

package main

import "fmt"

func main() {
    fmt.Println("hello world")
}
` + MIME ``` {{< /details >}} {{< command >}} tdl up -p /path/to/file --caption caption.txt {{< /command >}} ## 过滤器 使用扩展名过滤器上传文件: {{< hint warning >}} 扩展名仅与文件名匹配,而不是 MIME 类型。因此,这可能不会按预期工作。 白名单和黑名单不能同时使用。 {{< /hint >}} 白名单:只上传扩展名为 `.jpg` `.png` 的文件 {{< command >}} tdl up -p /path/to/file -p /path/to/dir -i jpg,png {{< /command >}} 黑名单:上传除了扩展名为 `.mp4` `.flv` 的所有文件 {{< command >}} tdl up -p /path/to/file -p /path/to/dir -e mp4 -e flv {{< /command >}} ## 自动删除 删除已上传成功的文件: {{< command >}} tdl up -p /path/to/file --rm {{< /command >}} ## 照片 将图像作为照片而不是文件上传: {{< command >}} tdl up -p /path/to/file --photo {{< /command >}} ================================================ FILE: docs/content/zh/more/_index.md ================================================ --- title: "更多" bookFlatSection: true weight: 30 --- ================================================ FILE: docs/content/zh/more/cli/_index.md ================================================ --- title: "命令行" weight: 10 bookHref: "/more/cli/tdl" --- ================================================ FILE: docs/content/zh/more/data.md ================================================ --- title: "数据" weight: 30 --- # 数据 您的帐户信息将存储在 `~/.tdl` 目录中。 日志文件将存储在 `~/.tdl/log` 目录中。 ================================================ FILE: docs/content/zh/more/env.md ================================================ --- title: "环境变量" weight: 20 --- # 环境变量 {{< hint info >}} 所有环境变量的值优先级低于命令行选项。 {{< /hint >}} 通过设置环境变量,避免在每次重复输入相同的命令行选项。 | 环境变量 | 对应选项 | |:-----------------------:|:---------------------:| | `TDL_NS` | `-n/--ns` | | `TDL_PROXY` | `--proxy` | | `TDL_STORAGE` | `--storage` | | `TDL_DEBUG` | `--debug` | | `TDL_SIZE` | `-s/--size` | | `TDL_THREADS` | `-t/--threads` | | `TDL_LIMIT` | `-l/--limit` | | `TDL_POOL` | `--pool` | | `TDL_NTP` | `--ntp` | | `TDL_RECONNECT_TIMEOUT` | `--reconnect-timeout` | | `TDL_TEMPLATE` | dl `--template` | {{< hint warning >}} - `TDL_STORAGE` 环境变量的格式与命令行选项不同:`{"type": "bolt", "path": "/path/to/data-dir"}` (JSON 对象)。 {{< /hint >}} ================================================ FILE: docs/content/zh/more/troubleshooting.md ================================================ --- title: "疑难解答" weight: 40 --- # 疑难解答 ## 最佳实践 如何减小封号的风险? - 使用官方客户端会话登录。 - 尽可能使用默认的下载和上传选项。不要设置过大的 `threads` 和 `size`。 - 不要同时在多台设备上使用相同的帐户登录。 - 不要同时下载或上传太多文件。 - 成为 Telegram 大会员。😅 ## 常见问题 #### Q: 输入命令后为什么没有响应?日志中为什么出现 `msg_id too high`? **A:** 检查是否需要使用代理(使用 `--proxy` 选项);检查您系统的本地时间是否正确(使用 `--ntp` 选项或校准系统时间) 如果仍然无法解决问题,请使用 `--debug` 标志重新运行。然后创建一个新的 ISSUE 并将日志粘贴到问题中。 #### Q: 使用 tdl 后,桌面客户端停止工作怎么办? **A:** 如果您的桌面客户端无法接收消息、加载聊天或发送消息,可能遇到了会话冲突。 您可以尝试使用 `tdl login` 重新登录,并**选择 YES 以退出桌面客户端登录**,这将删除客户端会话文件以分离会话。 #### Q: 如何将会话迁移到另一台设备? **A:** 您可以使用 `tdl backup` 和 `tdl recover` 命令导出和导入会话。详细信息请参见 [迁移](/zh/guide/migration)。 #### Q: 这算滥用吗? **A:** 不是。下载和上传速度受服务器端限制。由于官方客户端的速度通常不会达到帐户限制,因此开发了此工具,以尽可能高的速度下载文件。 #### Q: 这会导致封禁吗? **A:** 我不确定。所有操作都不涉及向其他人主动发送消息等高风险行为。 ================================================ FILE: docs/content/zh/reference/_index.md ================================================ --- bookHidden: true --- ================================================ FILE: docs/content/zh/reference/expr.md ================================================ --- title: "表达式指南" bookHidden: true --- # 表达式指南 表达式由 [expr](https://github.com/antonmedv/expr) 引擎提供支持,它是一个简单、轻量但功能强大的表达式引擎。 表达式引擎文档:https://expr.medv.io/docs/Language-Definition 它功能强大,但对于新用户来说可能有些难以理解。如果您对表达式引擎有任何疑问,请随时提出 ISSUE。 ================================================ FILE: docs/content/zh/snippets/_index.md ================================================ --- bookHidden: true --- ================================================ FILE: docs/content/zh/snippets/chat.md ================================================ --- --- {{< details title="CHAT 示例" open=false >}} #### 可用值: - `@iyear` (用户名) - `iyear` (无前缀 `@` 的用户名) - `123456789`(ID) - `https://t.me/iyear` (公开链接) - `+1 123456789`(电话号码) #### 如何在 Telegram 桌面端获取聊天 ID: - `设置` → `高级` → `实验性设置` → `在资料中显示对话 ID` {{< /details >}} ================================================ FILE: docs/content/zh/snippets/link.md ================================================ --- --- {{< details title="消息链接示例" open=false >}} - `https://t.me/telegram/193` - `https://t.me/c/1697797156/151` - `https://t.me/iFreeKnow/45662/55005` - `https://t.me/c/1492447836/251015/251021` - `https://t.me/opencfdchannel/4434?comment=360409` - `https://t.me/myhostloc/1485524?thread=1485523` - `...`(如果发现新的链接格式,请提交新的 Issue) {{< /details >}} ================================================ FILE: docs/go.mod ================================================ module github.com/iyear/tdl/docs go 1.25.8 require github.com/alex-shpak/hugo-book v0.0.0-20230808113920-3f1bcccbfb24 // indirect ================================================ FILE: docs/go.sum ================================================ github.com/alex-shpak/hugo-book v0.0.0-20230808113920-3f1bcccbfb24 h1:8NjMYBSFTtBLeT1VmpZAZznPOt1OH8aNCnE86sL4p4k= github.com/alex-shpak/hugo-book v0.0.0-20230808113920-3f1bcccbfb24/go.mod h1:L4NMyzbn15fpLIpmmtDg9ZFFyTZzw87/lk7M2bMQ7ds= ================================================ FILE: docs/hugo.yaml ================================================ baseURL: "https://example.com/" title: tdl enableGitInfo: true canonifyURLs: true module: imports: - path: github.com/alex-shpak/hugo-book # Needed for mermaid/katex shortcodes markup: highlight: style: onedark goldmark: renderer: unsafe: true tableOfContents: startLevel: 1 params: BookTheme: auto BookRepo: https://github.com/iyear/tdl BookSection: "*" BookSearch: true # container will be mounted by docsearch BookEditPath: edit/master/docs BookCommitPath: commit BookDateFormat: 2006/01/02 BookTranslatedOnly: true languages: en: languageName: English contentDir: content/en weight: 1 menu: before: - name: "🔗 GitHub" url: "https://github.com/iyear/tdl" weight: 10 - name: "👨‍💻 Author" url: "https://github.com/iyear" weight: 20 - name: "🌟 Donate" url: "https://www.patreon.com/iyear" weight: 30 zh: languageName: 简体中文 contentDir: content/zh weight: 2 menu: before: - name: "🔗 项目主页" url: "https://github.com/iyear/tdl" weight: 10 - name: "👨‍💻 作者" url: "https://github.com/iyear" weight: 20 - name: "🌟 捐赠" url: "https://afdian.net/a/iyear" weight: 30 ================================================ FILE: docs/layouts/partials/docs/inject/footer.html ================================================ ================================================ FILE: docs/layouts/partials/docs/inject/head.html ================================================ ================================================ FILE: docs/layouts/shortcodes/command.html ================================================ {{- $input := trim .Inner " \t\r\n" -}} {{- $lines := split $input "\n" -}} {{- $slash := false -}}
    {{- range $line := $lines -}}
        {{- $line = trim $line " \t\r\n" -}}
        {{- if ne $line "" -}}
            {{- if not $slash -}}
                {{ $line }}
{{- else -}} {{ $line }}
{{- end -}} {{- $slash = hasSuffix $line "\\" -}} {{- end -}} {{- end -}}
================================================ FILE: docs/layouts/shortcodes/image.html ================================================ {{ $file := .Get "src" }} {{ $height := .Get "height" }} {{ $width := .Get "width" }} {{ $align := .Get "align" }} {{ with resources.Get $file }} {{ .Name }} {{ end }} ================================================ FILE: docs/layouts/shortcodes/include.html ================================================ {{ $file := .Get 0 }} {{ with .Site.GetPage $file }}{{ .Content | replaceRE "^---[\\s\\S]+?---" "" | markdownify }}{{ end }} ================================================ FILE: docs/resources/_gen/assets/scss/book.scss_e129fe35b8d0a70789c8a08429469073.content ================================================ @charset "UTF-8";:root{--gray-100:#f8f9fa;--gray-200:#e9ecef;--gray-500:#adb5bd;--color-link:#0055bb;--color-visited-link:#8440f1;--body-background:white;--body-font-color:black;--icon-filter:none;--hint-color-info:#6bf;--hint-color-warning:#fd6;--hint-color-danger:#f66}@media(prefers-color-scheme:dark){:root{--gray-100:rgba(255, 255, 255, 0.1);--gray-200:rgba(255, 255, 255, 0.2);--gray-500:rgba(255, 255, 255, 0.5);--color-link:#84b2ff;--color-visited-link:#b88dff;--body-background:#343a40;--body-font-color:#e9ecef;--icon-filter:brightness(0) invert(1);--hint-color-info:#6bf;--hint-color-warning:#fd6;--hint-color-danger:#f66}}/*!normalize.css v8.0.1 | MIT License | github.com/necolas/normalize.css*/html{line-height:1.15;-webkit-text-size-adjust:100%}body{margin:0}main{display:block}h1{font-size:2em;margin:.67em 0}hr{box-sizing:content-box;height:0;overflow:visible}pre{font-family:monospace,monospace;font-size:1em}a{background-color:transparent}abbr[title]{border-bottom:none;text-decoration:underline;text-decoration:underline dotted}b,strong{font-weight:bolder}code,kbd,samp{font-family:monospace,monospace;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}img{border-style:none}button,input,optgroup,select,textarea{font-family:inherit;font-size:100%;line-height:1.15;margin:0}button,input{overflow:visible}button,select{text-transform:none}button,[type=button],[type=reset],[type=submit]{-webkit-appearance:button}button::-moz-focus-inner,[type=button]::-moz-focus-inner,[type=reset]::-moz-focus-inner,[type=submit]::-moz-focus-inner{border-style:none;padding:0}button:-moz-focusring,[type=button]:-moz-focusring,[type=reset]:-moz-focusring,[type=submit]:-moz-focusring{outline:1px dotted ButtonText}fieldset{padding:.35em .75em .625em}legend{box-sizing:border-box;color:inherit;display:table;max-width:100%;padding:0;white-space:normal}progress{vertical-align:baseline}textarea{overflow:auto}[type=checkbox],[type=radio]{box-sizing:border-box;padding:0}[type=number]::-webkit-inner-spin-button,[type=number]::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}[type=search]::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}details{display:block}summary{display:list-item}template{display:none}[hidden]{display:none}.flex{display:flex}.flex-auto{flex:auto}.flex-even{flex:1 1}.flex-wrap{flex-wrap:wrap}.justify-start{justify-content:flex-start}.justify-end{justify-content:flex-end}.justify-center{justify-content:center}.justify-between{justify-content:space-between}.align-center{align-items:center}.mx-auto{margin:0 auto}.text-center{text-align:center}.text-left{text-align:left}.text-right{text-align:right}.hidden{display:none}input.toggle{height:0;width:0;overflow:hidden;opacity:0;position:absolute}.clearfix::after{content:"";display:table;clear:both}html{font-size:16px;scroll-behavior:smooth;touch-action:manipulation}body{min-width:20rem;color:var(--body-font-color);background:var(--body-background);letter-spacing:.33px;font-weight:400;text-rendering:optimizeLegibility;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;box-sizing:border-box}body *{box-sizing:inherit}h1,h2,h3,h4,h5{font-weight:400}a{text-decoration:none;color:var(--color-link)}img{vertical-align:baseline}:focus{outline-style:auto;outline-color:currentColor;outline-color:-webkit-focus-ring-color}aside nav ul{padding:0;margin:0;list-style:none}aside nav ul li{margin:1em 0;position:relative}aside nav ul a{display:block}aside nav ul a:hover{opacity:.5}aside nav ul ul{padding-inline-start:1rem}ul.pagination{display:flex;justify-content:center;list-style-type:none;padding-inline-start:0}ul.pagination .page-item a{padding:1rem}.container{max-width:80rem;margin:0 auto}.book-icon{filter:var(--icon-filter)}.book-brand{margin-top:0;margin-bottom:1rem}.book-brand img{height:1.5em;width:1.5em;margin-inline-end:.5rem}.book-menu{flex:0 0 16rem;font-size:.875rem}.book-menu .book-menu-content{width:16rem;padding:1rem;background:var(--body-background);position:fixed;top:0;bottom:0;overflow-x:hidden;overflow-y:auto}.book-menu a,.book-menu label{color:inherit;cursor:pointer;word-wrap:break-word}.book-menu a.active{color:var(--color-link)}.book-menu input.toggle+label+ul{display:none}.book-menu input.toggle:checked+label+ul{display:block}.book-menu input.toggle+label::after{content:"▸"}.book-menu input.toggle:checked+label::after{content:"▾"}body[dir=rtl] .book-menu input.toggle+label::after{content:"◂"}body[dir=rtl] .book-menu input.toggle:checked+label::after{content:"▾"}.book-section-flat{margin:2rem 0}.book-section-flat>a,.book-section-flat>span,.book-section-flat>label{font-weight:bolder}.book-section-flat>ul{padding-inline-start:0}.book-page{min-width:20rem;flex-grow:1;padding:1rem}.book-post{margin-bottom:3rem}.book-header{display:none;margin-bottom:1rem}.book-header label{line-height:0}.book-header img.book-icon{height:1.5em;width:1.5em}.book-search{position:relative;margin:1rem 0;border-bottom:1px solid transparent}.book-search input{width:100%;padding:.5rem;border:0;border-radius:.25rem;background:var(--gray-100);color:var(--body-font-color)}.book-search input:required+.book-search-spinner{display:block}.book-search .book-search-spinner{position:absolute;top:0;margin:.5rem;margin-inline-start:calc(100% - 1.5rem);width:1rem;height:1rem;border:1px solid transparent;border-top-color:var(--body-font-color);border-radius:50%;animation:spin 1s ease infinite}@keyframes spin{100%{transform:rotate(360deg)}}.book-search small{opacity:.5}.book-toc{flex:0 0 16rem;font-size:.75rem}.book-toc .book-toc-content{width:16rem;padding:1rem;position:fixed;top:0;bottom:0;overflow-x:hidden;overflow-y:auto}.book-toc img{height:1em;width:1em}.book-toc nav>ul>li:first-child{margin-top:0}.book-footer{padding-top:1rem;font-size:.875rem}.book-footer img{height:1em;width:1em;margin-inline-end:.5rem}.book-comments{margin-top:1rem}.book-languages{margin-block-end:2rem}.book-languages .book-icon{height:1em;width:1em;margin-inline-end:.5em}.book-languages ul{padding-inline-start:1.5em}.book-menu-content,.book-toc-content,.book-page,.book-header aside,.markdown{transition:.2s ease-in-out;transition-property:transform,margin,opacity,visibility;will-change:transform,margin,opacity}@media screen and (max-width:56rem){#menu-control,#toc-control{display:inline}.book-menu{visibility:hidden;margin-inline-start:-16rem;font-size:16px;z-index:1}.book-toc{display:none}.book-header{display:block}#menu-control:focus~main label[for=menu-control]{outline-style:auto;outline-color:currentColor;outline-color:-webkit-focus-ring-color}#menu-control:checked~main .book-menu{visibility:initial}#menu-control:checked~main .book-menu .book-menu-content{transform:translateX(16rem);box-shadow:0 0 .5rem rgba(0,0,0,.1)}#menu-control:checked~main .book-page{opacity:.25}#menu-control:checked~main .book-menu-overlay{display:block;position:absolute;top:0;bottom:0;left:0;right:0}#toc-control:focus~main label[for=toc-control]{outline-style:auto;outline-color:currentColor;outline-color:-webkit-focus-ring-color}#toc-control:checked~main .book-header aside{display:block}body[dir=rtl] #menu-control:checked~main .book-menu .book-menu-content{transform:translateX(-16rem)}}@media screen and (min-width:80rem){.book-page,.book-menu .book-menu-content,.book-toc .book-toc-content{padding:2rem 1rem}}@font-face{font-family:roboto;font-style:normal;font-weight:400;font-display:swap;src:local(""),url(fonts/roboto-v27-latin-regular.woff2)format("woff2"),url(fonts/roboto-v27-latin-regular.woff)format("woff")}@font-face{font-family:roboto;font-style:normal;font-weight:700;font-display:swap;src:local(""),url(fonts/roboto-v27-latin-700.woff2)format("woff2"),url(fonts/roboto-v27-latin-700.woff)format("woff")}@font-face{font-family:roboto mono;font-style:normal;font-weight:400;font-display:swap;src:local(""),url(fonts/roboto-mono-v13-latin-regular.woff2)format("woff2"),url(fonts/roboto-mono-v13-latin-regular.woff)format("woff")}body{font-family:roboto,sans-serif}code{font-family:roboto mono,monospace}@media print{.book-menu,.book-footer,.book-toc{display:none}.book-header,.book-header aside{display:block}main{display:block!important}}.markdown{line-height:1.6}.markdown>:first-child{margin-top:0}.markdown h1,.markdown h2,.markdown h3,.markdown h4,.markdown h5,.markdown h6{font-weight:400;line-height:1;margin-top:1.5em;margin-bottom:1rem}.markdown h1 a.anchor,.markdown h2 a.anchor,.markdown h3 a.anchor,.markdown h4 a.anchor,.markdown h5 a.anchor,.markdown h6 a.anchor{opacity:0;font-size:.75em;vertical-align:middle;text-decoration:none}.markdown h1:hover a.anchor,.markdown h1 a.anchor:focus,.markdown h2:hover a.anchor,.markdown h2 a.anchor:focus,.markdown h3:hover a.anchor,.markdown h3 a.anchor:focus,.markdown h4:hover a.anchor,.markdown h4 a.anchor:focus,.markdown h5:hover a.anchor,.markdown h5 a.anchor:focus,.markdown h6:hover a.anchor,.markdown h6 a.anchor:focus{opacity:initial}.markdown h4,.markdown h5,.markdown h6{font-weight:bolder}.markdown h5{font-size:.875em}.markdown h6{font-size:.75em}.markdown b,.markdown optgroup,.markdown strong{font-weight:bolder}.markdown a{text-decoration:none}.markdown a:hover{text-decoration:underline}.markdown a:visited{color:var(--color-visited-link)}.markdown img{max-width:100%;height:auto}.markdown code{padding:0 .25rem;background:var(--gray-200);border-radius:.25rem;font-size:.875em}.markdown pre{padding:1rem;background:var(--gray-100);border-radius:.25rem;overflow-x:auto}.markdown pre code{padding:0;background:0 0}.markdown p{word-wrap:break-word}.markdown blockquote{margin:1rem 0;padding:.5rem 1rem .5rem .75rem;border-inline-start:.25rem solid var(--gray-200);border-radius:.25rem}.markdown blockquote :first-child{margin-top:0}.markdown blockquote :last-child{margin-bottom:0}.markdown table{overflow:auto;display:block;border-spacing:0;border-collapse:collapse;margin-top:1rem;margin-bottom:1rem}.markdown table tr th,.markdown table tr td{padding:.5rem 1rem;border:1px solid var(--gray-200)}.markdown table tr:nth-child(2n){background:var(--gray-100)}.markdown hr{height:1px;border:none;background:var(--gray-200)}.markdown ul,.markdown ol{padding-inline-start:2rem;word-wrap:break-word}.markdown dl dt{font-weight:bolder;margin-top:1rem}.markdown dl dd{margin-inline-start:0;margin-bottom:1rem}.markdown .highlight table tr td:nth-child(1) pre{margin:0;padding-inline-end:0}.markdown .highlight table tr td:nth-child(2) pre{margin:0;padding-inline-start:0}.markdown details{padding:1rem;border:1px solid var(--gray-200);border-radius:.25rem}.markdown details summary{line-height:1;padding:1rem;margin:-1rem;cursor:pointer}.markdown details[open] summary{margin-bottom:0}.markdown figure{margin:1rem 0}.markdown figure figcaption p{margin-top:0}.markdown-inner>:first-child{margin-top:0}.markdown-inner>:last-child{margin-bottom:0}.markdown .book-expand{margin-top:1rem;margin-bottom:1rem;border:1px solid var(--gray-200);border-radius:.25rem;overflow:hidden}.markdown .book-expand .book-expand-head{background:var(--gray-100);padding:.5rem 1rem;cursor:pointer}.markdown .book-expand .book-expand-content{display:none;padding:1rem}.markdown .book-expand input[type=checkbox]:checked+.book-expand-content{display:block}.markdown .book-tabs{margin-top:1rem;margin-bottom:1rem;border:1px solid var(--gray-200);border-radius:.25rem;overflow:hidden;display:flex;flex-wrap:wrap}.markdown .book-tabs label{display:inline-block;padding:.5rem 1rem;border-bottom:1px transparent;cursor:pointer}.markdown .book-tabs .book-tabs-content{order:999;width:100%;border-top:1px solid var(--gray-100);padding:1rem;display:none}.markdown .book-tabs input[type=radio]:checked+label{border-bottom:1px solid var(--color-link)}.markdown .book-tabs input[type=radio]:checked+label+.book-tabs-content{display:block}.markdown .book-tabs input[type=radio]:focus+label{outline-style:auto;outline-color:currentColor;outline-color:-webkit-focus-ring-color}.markdown .book-columns{margin-left:-1rem;margin-right:-1rem}.markdown .book-columns>div{margin:1rem 0;min-width:10rem;padding:0 1rem}.markdown a.book-btn{display:inline-block;font-size:.875rem;color:var(--color-link);line-height:2rem;padding:0 1rem;border:1px solid var(--color-link);border-radius:.25rem;cursor:pointer}.markdown a.book-btn:hover{text-decoration:none}.markdown .book-hint.info{border-color:#6bf;background-color:rgba(102,187,255,.1)}.markdown .book-hint.warning{border-color:#fd6;background-color:rgba(255,221,102,.1)}.markdown .book-hint.danger{border-color:#f66;background-color:rgba(255,102,102,.1)}::-webkit-scrollbar{width:.5rem}::-webkit-scrollbar-thumb{background:0 0;border-radius:.5rem}:hover::-webkit-scrollbar-thumb{background:var(--gray-500)}body{-ms-overflow-style:-ms-autohiding-scrollbar}.book-menu nav{scrollbar-color:transparent var(--gray-500)}.markdown pre{outline:none}.command::before{content:attr(prompt);opacity:.7;display:inline;padding-right:.7em;font-family:SFMono-Regular,Menlo,Monaco,Consolas,monospace;border-right:1px solid #999;margin-right:.6em;letter-spacing:-1px;font-size:105%;-webkit-user-select:none;-moz-user-select:none;user-select:none;pointer-events:none}.toast{position:fixed;bottom:20px;left:50%;transform:translateX(-50%);background-color:#494949;color:#fff;padding:10px;border-radius:8px;z-index:9999;opacity:0;transition:opacity .3s ease-in-out} ================================================ FILE: docs/resources/_gen/assets/scss/book.scss_e129fe35b8d0a70789c8a08429469073.json ================================================ {"Target":"book.min.90a1b7a3a4485fcb940c779c3dfc891d6e9f3a078f4743cc4801844a72db8244.css","MediaType":"text/css","Data":{"Integrity":"sha256-kKG3o6RIX8uUDHecPfyJHW6fOgePR0PMSAGESnLbgkQ="}} ================================================ FILE: extension/extension.go ================================================ package extension import ( "context" "encoding/json" "fmt" "os" "os/signal" "path/filepath" "github.com/go-faster/errors" "github.com/gotd/td/session" "github.com/gotd/td/telegram" "go.uber.org/zap" "github.com/iyear/tdl/core/logctx" "github.com/iyear/tdl/core/tclient" "github.com/iyear/tdl/core/util/logutil" ) const EnvKey = "TDL_EXTENSION" type Env struct { Name string `json:"name"` Namespace string `json:"namespace"` AppID int `json:"app_id"` AppHash string `json:"app_hash"` Session []byte `json:"session"` DataDir string `json:"data_dir"` NTP string `json:"ntp"` Proxy string `json:"proxy"` Pool int64 `json:"pool"` Debug bool `json:"debug"` } type Options struct { // UpdateHandler will be passed to telegram.Client Options. UpdateHandler telegram.UpdateHandler // Middlewares will be passed to telegram.Client Options, // and recovery,retry,flood-wait will be used if nil. Middlewares []telegram.Middleware // Logger will be used as extension logger, // and default logger(write to extension data dir) will be used if nil. Logger *zap.Logger } type Extension struct { name string // extension name client *telegram.Client // telegram client log *zap.Logger // logger config *Config // extension config } type Config struct { Namespace string // tdl namespace DataDir string // data directory for extension Proxy string // proxy URL Pool int64 // pool size Debug bool // debug mode enabled } func (e *Extension) Name() string { return e.name } func (e *Extension) Client() *telegram.Client { return e.client } func (e *Extension) Log() *zap.Logger { return e.log } func (e *Extension) Config() *Config { return e.config } type Handler func(ctx context.Context, e *Extension) error func New(o Options) func(h Handler) { ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt) ext, client, err := buildExtension(ctx, o) assert(err) return func(h Handler) { defer cancel() assert(tclient.RunWithAuth(ctx, client, func(ctx context.Context) error { if err := h(ctx, ext); err != nil { if errors.Is(err, context.Canceled) { return nil } return err } return nil })) } } func buildExtension(ctx context.Context, o Options) (*Extension, *telegram.Client, error) { envFile := os.Getenv(EnvKey) if envFile == "" { return nil, nil, errors.New("please launch extension with `tdl EXTENSION_NAME`") } extEnv, err := os.ReadFile(envFile) if err != nil { return nil, nil, errors.Wrap(err, "read env file") } env := &Env{} if err = json.Unmarshal(extEnv, env); err != nil { return nil, nil, errors.Wrap(err, "unmarshal extension environment") } if o.Logger == nil { level := zap.InfoLevel if env.Debug { level = zap.DebugLevel } o.Logger = logutil.New(level, filepath.Join(env.DataDir, "log", "latest.log")) } // save logger to context ctx = logctx.With(ctx, o.Logger) if o.Middlewares == nil { o.Middlewares = tclient.NewDefaultMiddlewares(ctx, 0) } client, err := buildClient(ctx, env, o) if err != nil { return nil, nil, errors.Wrap(err, "build client") } return &Extension{ name: env.Name, client: client, log: o.Logger, config: &Config{ Namespace: env.Namespace, DataDir: env.DataDir, Proxy: env.Proxy, Pool: env.Pool, Debug: env.Debug, }, }, client, nil } func buildClient(ctx context.Context, env *Env, o Options) (*telegram.Client, error) { storage := &session.StorageMemory{} if err := storage.StoreSession(ctx, env.Session); err != nil { return nil, errors.Wrap(err, "store session") } return tclient.New(ctx, tclient.Options{ AppID: env.AppID, AppHash: env.AppHash, Session: storage, Middlewares: o.Middlewares, Proxy: env.Proxy, NTP: env.NTP, ReconnectTimeout: 0, // no timeout UpdateHandler: o.UpdateHandler, }) } func assert(err error) { if err != nil { fmt.Println(err) os.Exit(1) } } ================================================ FILE: extension/go.mod ================================================ module github.com/iyear/tdl/extension go 1.25.8 require ( github.com/go-faster/errors v0.7.1 github.com/gotd/td v0.122.0 github.com/iyear/tdl/core v0.20.1 go.uber.org/zap v1.27.1 ) require ( github.com/beevik/ntp v1.3.1 // indirect github.com/cenkalti/backoff/v4 v4.3.0 // indirect github.com/coder/websocket v1.8.13 // indirect github.com/dlclark/regexp2 v1.11.5 // indirect github.com/fatih/color v1.18.0 // indirect github.com/ghodss/yaml v1.0.0 // indirect github.com/go-faster/jx v1.1.0 // indirect github.com/go-faster/xor v1.0.0 // indirect github.com/go-faster/yaml v0.4.6 // indirect github.com/google/uuid v1.6.0 // indirect github.com/gotd/contrib v0.20.0 // indirect github.com/gotd/ige v0.2.2 // indirect github.com/gotd/neo v0.1.5 // indirect github.com/iyear/connectproxy v0.1.1 // indirect github.com/klauspost/compress v1.18.0 // indirect github.com/mattn/go-colorable v0.1.13 // indirect github.com/mattn/go-isatty v0.0.20 // indirect github.com/ogen-go/ogen v1.10.1 // indirect github.com/segmentio/asm v1.2.0 // indirect go.opentelemetry.io/otel v1.35.0 // indirect go.opentelemetry.io/otel/metric v1.35.0 // indirect go.opentelemetry.io/otel/trace v1.35.0 // indirect go.uber.org/atomic v1.11.0 // indirect go.uber.org/multierr v1.11.0 // indirect golang.org/x/crypto v0.45.0 // indirect golang.org/x/exp v0.0.0-20230725093048-515e97ebf090 // indirect golang.org/x/mod v0.29.0 // indirect golang.org/x/net v0.47.0 // indirect golang.org/x/sync v0.18.0 // indirect golang.org/x/sys v0.38.0 // indirect golang.org/x/text v0.31.0 // indirect golang.org/x/tools v0.38.0 // indirect gopkg.in/natefinch/lumberjack.v2 v2.2.1 // indirect gopkg.in/yaml.v2 v2.4.0 // indirect rsc.io/qr v0.2.0 // indirect ) ================================================ FILE: extension/go.sum ================================================ github.com/beevik/ntp v1.3.1 h1:Y/srlT8L1yQr58kyPWFPZIxRL8ttx2SRIpVYJqZIlAM= github.com/beevik/ntp v1.3.1/go.mod h1:fT6PylBq86Tsq23ZMEe47b7QQrZfYBFPnpzt0a9kJxw= github.com/cenkalti/backoff/v4 v4.3.0 h1:MyRJ/UdXutAwSAT+s3wNd7MfTIcy71VQueUuFK343L8= github.com/cenkalti/backoff/v4 v4.3.0/go.mod h1:Y3VNntkOUPxTVeUxJ/G5vcM//AlwfmyYozVcomhLiZE= github.com/coder/websocket v1.8.13 h1:f3QZdXy7uGVz+4uCJy2nTZyM0yTBj8yANEHhqlXZ9FE= github.com/coder/websocket v1.8.13/go.mod h1:LNVeNrXQZfe5qhS9ALED3uA+l5pPqvwXg3CKoDBB2gs= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/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/fatih/color v1.18.0 h1:S8gINlzdQ840/4pfAwic/ZE0djQEH3wM94VfqLTZcOM= github.com/fatih/color v1.18.0/go.mod h1:4FelSpRwEGDpQ12mAdzqdOukCy4u8WUtOY6lkT/6HfU= github.com/ghodss/yaml v1.0.0 h1:wQHKEahhL6wmXdzwWG11gIVCkOv05bNOh+Rxn0yngAk= github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= github.com/go-faster/errors v0.7.1 h1:MkJTnDoEdi9pDabt1dpWf7AA8/BaSYZqibYyhZ20AYg= github.com/go-faster/errors v0.7.1/go.mod h1:5ySTjWFiphBs07IKuiL69nxdfd5+fzh1u7FPGZP2quo= github.com/go-faster/jx v1.1.0 h1:ZsW3wD+snOdmTDy9eIVgQdjUpXRRV4rqW8NS3t+20bg= github.com/go-faster/jx v1.1.0/go.mod h1:vKDNikrKoyUmpzaJ0OkIkRQClNHFX/nF3dnTJZb3skg= github.com/go-faster/xor v0.3.0/go.mod h1:x5CaDY9UKErKzqfRfFZdfu+OSTfoZny3w5Ak7UxcipQ= github.com/go-faster/xor v1.0.0 h1:2o8vTOgErSGHP3/7XwA5ib1FTtUsNtwCoLLBjl31X38= github.com/go-faster/xor v1.0.0/go.mod h1:x5CaDY9UKErKzqfRfFZdfu+OSTfoZny3w5Ak7UxcipQ= github.com/go-faster/yaml v0.4.6 h1:lOK/EhI04gCpPgPhgt0bChS6bvw7G3WwI8xxVe0sw9I= github.com/go-faster/yaml v0.4.6/go.mod h1:390dRIvV4zbnO7qC9FGo6YYutc+wyyUSHBgbXL52eXk= github.com/go-logr/logr v1.4.2 h1:6pFjapn8bFcIbiKo3XT4j/BhANplGihG6tvd+8rYgrY= github.com/go-logr/logr v1.4.2/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/gotd/contrib v0.20.0 h1:1Wc4+HMQiIKYQuGHVwVksIx152HFTP6B5n88dDe0ZYw= github.com/gotd/contrib v0.20.0/go.mod h1:P6o8W4niqhDPHLA0U+SA/L7l3BQHYLULpeHfRSePn9o= github.com/gotd/ige v0.2.2 h1:XQ9dJZwBfDnOGSTxKXBGP4gMud3Qku2ekScRjDWWfEk= github.com/gotd/ige v0.2.2/go.mod h1:tuCRb+Y5Y3eNTo3ypIfNpQ4MFjrnONiL2jN2AKZXmb0= github.com/gotd/neo v0.1.5 h1:oj0iQfMbGClP8xI59x7fE/uHoTJD7NZH9oV1WNuPukQ= github.com/gotd/neo v0.1.5/go.mod h1:9A2a4bn9zL6FADufBdt7tZt+WMhvZoc5gWXihOPoiBQ= github.com/gotd/td v0.122.0 h1:xIqoYI02ElZjj+KxOfvoUjA63m7MGWZkemM4m42aqRE= github.com/gotd/td v0.122.0/go.mod h1:vPC2X2rcRQYAGVr9EgmQgswHcj8Ps0Tt66XylR3CxrI= github.com/iyear/connectproxy v0.1.1 h1:JZOF/62vvwRGBWcgSyWRb0BpKD4FSs0++B5/y5pNE4c= github.com/iyear/connectproxy v0.1.1/go.mod h1:yD4zOmSMQCmwHIT4fk8mg4k2M15z8VoMSoeY6NNJdsA= github.com/iyear/tdl/core v0.20.1 h1:UdnlBtI9C5wZV718MevtRtxIKgQ/jwaOjas34Qlw2us= github.com/iyear/tdl/core v0.20.1/go.mod h1:oIMvODKNqz52VmAk3M2+otHTPai4xo3y1aQ2VZE25eY= github.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo= github.com/klauspost/compress v1.18.0/go.mod h1:2Pp+KzxcywXVXMr50+X0Q/Lsb43OQHYWRCY2AiWywWQ= github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA= github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg= github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= github.com/ogen-go/ogen v1.10.1 h1:oeSN8AF9mhTVfapbMuL8pQTF2ToqyW9xXaStmOhHKTA= github.com/ogen-go/ogen v1.10.1/go.mod h1:fXCg9PsNYEzJ8ABdmZ2A7j4hMi9EDHP53jzsNtIM3d0= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 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/segmentio/asm v1.2.0 h1:9BQrFxC+YOHJlTlHGkTrFWf59nbL3XnCoFLTwDCI7ys= github.com/segmentio/asm v1.2.0/go.mod h1:BqMnlJP91P8d+4ibuonYZw9mfnzI9HfxselHZr5aAcs= github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA= github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= go.opentelemetry.io/auto/sdk v1.1.0 h1:cH53jehLUN6UFLY71z+NDOiNJqDdPRaXzTel0sJySYA= go.opentelemetry.io/auto/sdk v1.1.0/go.mod h1:3wSPjt5PWp2RhlCcmmOial7AvC4DQqZb7a7wCow3W8A= go.opentelemetry.io/otel v1.35.0 h1:xKWKPxrxB6OtMCbmMY021CqC45J+3Onta9MqjhnusiQ= go.opentelemetry.io/otel v1.35.0/go.mod h1:UEqy8Zp11hpkUrL73gSlELM0DupHoiq72dR+Zqel/+Y= go.opentelemetry.io/otel/metric v1.35.0 h1:0znxYu2SNyuMSQT4Y9WDWej0VpcsxkuklLa4/siN90M= go.opentelemetry.io/otel/metric v1.35.0/go.mod h1:nKVFgxBZ2fReX6IlyW28MgZojkoAkJGaE8CpgeAU3oE= go.opentelemetry.io/otel/trace v1.35.0 h1:dPpEfJu1sDIqruz7BHFG3c7528f6ddfSWfFDVt/xgMs= go.opentelemetry.io/otel/trace v1.35.0/go.mod h1:WUk7DtFp1Aw2MkvqGdwiXYDZZNvA/1J8o6xRXLrIkyc= go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE= go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0= go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE= go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0= go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y= go.uber.org/zap v1.27.1 h1:08RqriUEv8+ArZRYSTXy1LeBScaMpVSTBhCeaZYfMYc= go.uber.org/zap v1.27.1/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E= golang.org/x/crypto v0.45.0 h1:jMBrvKuj23MTlT0bQEOBcAE0mjg8mK9RXFhRH6nyF3Q= golang.org/x/crypto v0.45.0/go.mod h1:XTGrrkGJve7CYK7J8PEww4aY7gM3qMCElcJQ8n8JdX4= golang.org/x/exp v0.0.0-20230725093048-515e97ebf090 h1:Di6/M8l0O2lCLc6VVRWhgCiApHV8MnQurBnFSHsQtNY= golang.org/x/exp v0.0.0-20230725093048-515e97ebf090/go.mod h1:FXUEEKJgO7OQYeo8N01OfiKP8RXMtf6e8aTskBGqWdc= golang.org/x/mod v0.29.0 h1:HV8lRxZC4l2cr3Zq1LvtOsi/ThTgWnUk/y64QSs8GwA= golang.org/x/mod v0.29.0/go.mod h1:NyhrlYXJ2H4eJiRy/WDBO6HMqZQ6q9nk4JzS3NuCK+w= golang.org/x/net v0.47.0 h1:Mx+4dIFzqraBXUugkia1OOvlD6LemFo1ALMHjrXDOhY= golang.org/x/net v0.47.0/go.mod h1:/jNxtkgq5yWUGYkaZGqo27cfGZ1c5Nen03aYrrKpVRU= golang.org/x/sync v0.0.0-20201207232520-09787c993a3a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.18.0 h1:kr88TuHDroi+UVf+0hZnirlk8o8T+4MrK6mr60WkH/I= golang.org/x/sync v0.18.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI= golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.38.0 h1:3yZWxaJjBmCWXqhN1qh02AkOnCQ1poK6oF+a7xWL6Gc= golang.org/x/sys v0.38.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= golang.org/x/text v0.31.0 h1:aC8ghyu4JhP8VojJ2lEHBnochRno1sgL6nEi9WGFGMM= golang.org/x/text v0.31.0/go.mod h1:tKRAlv61yKIjGGHX/4tP1LTbc13YSec1pxVEWXzfoeM= golang.org/x/tools v0.38.0 h1:Hx2Xv8hISq8Lm16jvBZ2VQf+RLmbd7wVUsALibYI/IQ= golang.org/x/tools v0.38.0/go.mod h1:yEsQ/d/YK8cjh0L6rZlY8tgtlKiBNTL14pGDJPJpYQs= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo= gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/natefinch/lumberjack.v2 v2.2.1 h1:bBRl1b0OH9s/DuPhuXpNl+VtCaJXFZ5/uEFST95x9zc= gopkg.in/natefinch/lumberjack.v2 v2.2.1/go.mod h1:YD8tP3GAjkrDg1eZH7EGmyESg/lsYskCTPBJVb9jqSc= 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.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 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= rsc.io/qr v0.2.0/go.mod h1:IF+uZjkb9fqyeF/4tlBoynqmQxUoPfWEKh921coOuXs= ================================================ FILE: go.mod ================================================ module github.com/iyear/tdl go 1.25.8 require ( github.com/AlecAivazis/survey/v2 v2.3.7 github.com/bcicen/jstream v1.0.1 github.com/beevik/ntp v1.5.0 github.com/expr-lang/expr v1.17.8 github.com/fatih/color v1.18.0 github.com/flytam/filenamify v1.2.0 github.com/gabriel-vasile/mimetype v1.4.13 github.com/go-faster/errors v0.7.1 github.com/go-faster/jx v1.2.0 github.com/go-playground/validator/v10 v10.30.1 github.com/go-viper/mapstructure/v2 v2.5.0 github.com/google/go-github/v62 v62.0.0 github.com/google/uuid v1.6.0 github.com/gorilla/mux v1.8.1 github.com/gotd/contrib v0.20.0 github.com/gotd/td v0.122.0 github.com/iancoleman/strcase v0.3.0 github.com/ivanpirog/coloredcobra v1.0.1 github.com/iyear/tdl/core v0.20.1 github.com/iyear/tdl/extension v0.20.1 github.com/jedib0t/go-pretty/v6 v6.5.0 github.com/klauspost/compress v1.18.4 github.com/kopoli/go-terminal-size v0.0.0-20170219200355-5c97524c8b54 github.com/mattn/go-runewidth v0.0.20 github.com/mitchellh/mapstructure v1.5.0 github.com/onsi/ginkgo/v2 v2.28.1 github.com/onsi/gomega v1.39.1 github.com/shirou/gopsutil/v3 v3.24.5 github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e github.com/spf13/cast v1.10.0 github.com/spf13/cobra v1.10.2 github.com/spf13/pflag v1.0.10 github.com/spf13/viper v1.21.0 github.com/stretchr/testify v1.11.1 github.com/tidwall/gjson v1.18.0 go.etcd.io/bbolt v1.3.10 go.uber.org/atomic v1.11.0 go.uber.org/multierr v1.11.0 go.uber.org/zap v1.27.1 golang.org/x/net v0.51.0 golang.org/x/time v0.12.0 ) require ( github.com/Masterminds/semver/v3 v3.4.0 // indirect github.com/cenkalti/backoff/v4 v4.3.0 // indirect github.com/clipperhouse/uax29/v2 v2.2.0 // indirect github.com/coder/websocket v1.8.13 // indirect github.com/cpuguy83/go-md2man/v2 v2.0.6 // indirect github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect github.com/dlclark/regexp2 v1.11.5 // indirect github.com/fsnotify/fsnotify v1.9.0 // indirect github.com/ghodss/yaml v1.0.0 // indirect github.com/go-faster/xor v1.0.0 // indirect github.com/go-faster/yaml v0.4.6 // indirect github.com/go-logr/logr v1.4.3 // indirect github.com/go-ole/go-ole v1.2.6 // indirect github.com/go-playground/locales v0.14.1 // indirect github.com/go-playground/universal-translator v0.18.1 // indirect github.com/go-task/slim-sprig/v3 v3.0.0 // indirect github.com/google/go-cmp v0.7.0 // indirect github.com/google/go-querystring v1.1.0 // indirect github.com/google/pprof v0.0.0-20260115054156-294ebfa9ad83 // indirect github.com/gotd/ige v0.2.2 // indirect github.com/gotd/neo v0.1.5 // indirect github.com/inconshreveable/mousetrap v1.1.0 // indirect github.com/iyear/connectproxy v0.1.1 // indirect github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51 // indirect github.com/leodido/go-urn v1.4.0 // indirect github.com/lufia/plan9stats v0.0.0-20230326075908-cb1d2100619a // indirect github.com/mattn/go-colorable v0.1.13 // indirect github.com/mattn/go-isatty v0.0.20 // indirect github.com/mgutz/ansi v0.0.0-20200706080929-d51e80ef957d // indirect github.com/ogen-go/ogen v1.10.1 // indirect github.com/pelletier/go-toml/v2 v2.2.4 // indirect github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect github.com/power-devops/perfstat v0.0.0-20221212215047-62379fc7944b // indirect github.com/russross/blackfriday/v2 v2.1.0 // indirect github.com/sagikazarmark/locafero v0.11.0 // indirect github.com/samber/lo v1.52.0 // indirect github.com/segmentio/asm v1.2.1 // indirect github.com/shoenig/go-m1cpu v0.1.6 // indirect github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8 // indirect github.com/spf13/afero v1.15.0 // indirect github.com/subosito/gotenv v1.6.0 // indirect github.com/tidwall/match v1.1.1 // indirect github.com/tidwall/pretty v1.2.1 // indirect github.com/tklauser/go-sysconf v0.3.12 // indirect github.com/tklauser/numcpus v0.6.1 // indirect github.com/yapingcat/gomedia v0.0.0-20240601043430-920523f8e5c7 // indirect github.com/yusufpapurcu/wmi v1.2.4 // indirect go.opentelemetry.io/otel v1.35.0 // indirect go.opentelemetry.io/otel/metric v1.35.0 // indirect go.opentelemetry.io/otel/trace v1.35.0 // indirect go.yaml.in/yaml/v3 v3.0.4 // indirect golang.org/x/crypto v0.48.0 // indirect golang.org/x/exp v0.0.0-20240719175910-8a7402abbf56 // indirect golang.org/x/mod v0.32.0 // indirect golang.org/x/sync v0.19.0 // indirect golang.org/x/sys v0.41.0 // indirect golang.org/x/term v0.40.0 // indirect golang.org/x/text v0.34.0 // indirect golang.org/x/tools v0.41.0 // indirect gopkg.in/natefinch/lumberjack.v2 v2.2.1 // indirect gopkg.in/yaml.v2 v2.4.0 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect rsc.io/qr v0.2.0 // indirect ) ================================================ FILE: go.sum ================================================ 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/Masterminds/semver/v3 v3.4.0 h1:Zog+i5UMtVoCU8oKka5P7i9q9HgrJeGzI9SA1Xbatp0= github.com/Masterminds/semver/v3 v3.4.0/go.mod h1:4V+yj/TJE1HU9XfppCwVMZq3I84lprf4nC11bSS5beM= github.com/Netflix/go-expect v0.0.0-20220104043353-73e0943537d2 h1:+vx7roKuyA63nhn5WAunQHLTznkw5W8b1Xc0dNjp83s= github.com/Netflix/go-expect v0.0.0-20220104043353-73e0943537d2/go.mod h1:HBCaDeC1lPdgDeDbhX8XFpy1jqjK0IBG8W5K+xYqA0w= github.com/bcicen/jstream v1.0.1 h1:BXY7Cu4rdmc0rhyTVyT3UkxAiX3bnLpKLas9btbH5ck= github.com/bcicen/jstream v1.0.1/go.mod h1:9ielPxqFry7Y4Tg3j4BfjPocfJ3TbsRtXOAYXYmRuAQ= github.com/beevik/ntp v1.5.0 h1:y+uj/JjNwlY2JahivxYvtmv4ehfi3h74fAuABB9ZSM4= github.com/beevik/ntp v1.5.0/go.mod h1:mJEhBrwT76w9D+IfOEGvuzyuudiW9E52U2BaTrMOYow= github.com/cenkalti/backoff/v4 v4.3.0 h1:MyRJ/UdXutAwSAT+s3wNd7MfTIcy71VQueUuFK343L8= github.com/cenkalti/backoff/v4 v4.3.0/go.mod h1:Y3VNntkOUPxTVeUxJ/G5vcM//AlwfmyYozVcomhLiZE= 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/coder/websocket v1.8.13 h1:f3QZdXy7uGVz+4uCJy2nTZyM0yTBj8yANEHhqlXZ9FE= github.com/coder/websocket v1.8.13/go.mod h1:LNVeNrXQZfe5qhS9ALED3uA+l5pPqvwXg3CKoDBB2gs= github.com/cpuguy83/go-md2man/v2 v2.0.1/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= github.com/cpuguy83/go-md2man/v2 v2.0.6 h1:XJtiaUW6dEEqVuZiMTn1ldk455QWwEIsMIJlo5vtkx0= github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g= github.com/creack/pty v1.1.17 h1:QeVUsEDNrLBW4tMgZHvxy18sKtr6VI492kBhUfhDJNI= github.com/creack/pty v1.1.17/go.mod h1:MOBLtS5ELjhRRrroQr9kyvTxUAFNvYEK993ew/Vr4O4= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= 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/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= github.com/fatih/color v1.18.0 h1:S8gINlzdQ840/4pfAwic/ZE0djQEH3wM94VfqLTZcOM= github.com/fatih/color v1.18.0/go.mod h1:4FelSpRwEGDpQ12mAdzqdOukCy4u8WUtOY6lkT/6HfU= github.com/flytam/filenamify v1.2.0 h1:7RiSqXYR4cJftDQ5NuvljKMfd/ubKnW/j9C6iekChgI= github.com/flytam/filenamify v1.2.0/go.mod h1:Dzf9kVycwcsBlr2ATg6uxjqiFgKGH+5SKFuhdeP5zu8= github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8= github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0= github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k= github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0= github.com/gabriel-vasile/mimetype v1.4.13 h1:46nXokslUBsAJE/wMsp5gtO500a4F3Nkz9Ufpk2AcUM= github.com/gabriel-vasile/mimetype v1.4.13/go.mod h1:d+9Oxyo1wTzWdyVUPMmXFvp4F9tea18J8ufA774AB3s= github.com/ghodss/yaml v1.0.0 h1:wQHKEahhL6wmXdzwWG11gIVCkOv05bNOh+Rxn0yngAk= github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= github.com/gkampitakis/ciinfo v0.3.2 h1:JcuOPk8ZU7nZQjdUhctuhQofk7BGHuIy0c9Ez8BNhXs= github.com/gkampitakis/ciinfo v0.3.2/go.mod h1:1NIwaOcFChN4fa/B0hEBdAb6npDlFL8Bwx4dfRLRqAo= github.com/gkampitakis/go-diff v1.3.2 h1:Qyn0J9XJSDTgnsgHRdz9Zp24RaJeKMUHg2+PDZZdC4M= github.com/gkampitakis/go-diff v1.3.2/go.mod h1:LLgOrpqleQe26cte8s36HTWcTmMEur6OPYerdAAS9tk= github.com/gkampitakis/go-snaps v0.5.15 h1:amyJrvM1D33cPHwVrjo9jQxX8g/7E2wYdZ+01KS3zGE= github.com/gkampitakis/go-snaps v0.5.15/go.mod h1:HNpx/9GoKisdhw9AFOBT1N7DBs9DiHo/hGheFGBZ+mc= github.com/go-faster/errors v0.7.1 h1:MkJTnDoEdi9pDabt1dpWf7AA8/BaSYZqibYyhZ20AYg= github.com/go-faster/errors v0.7.1/go.mod h1:5ySTjWFiphBs07IKuiL69nxdfd5+fzh1u7FPGZP2quo= github.com/go-faster/jx v1.2.0 h1:T2YHJPrFaYu21fJtUxC9GzmluKu8rVIFDwwGBKTDseI= github.com/go-faster/jx v1.2.0/go.mod h1:UWLOVDmMG597a5tBFPLIWJdUxz5/2emOpfsj9Neg0PE= github.com/go-faster/xor v0.3.0/go.mod h1:x5CaDY9UKErKzqfRfFZdfu+OSTfoZny3w5Ak7UxcipQ= github.com/go-faster/xor v1.0.0 h1:2o8vTOgErSGHP3/7XwA5ib1FTtUsNtwCoLLBjl31X38= github.com/go-faster/xor v1.0.0/go.mod h1:x5CaDY9UKErKzqfRfFZdfu+OSTfoZny3w5Ak7UxcipQ= github.com/go-faster/yaml v0.4.6 h1:lOK/EhI04gCpPgPhgt0bChS6bvw7G3WwI8xxVe0sw9I= github.com/go-faster/yaml v0.4.6/go.mod h1:390dRIvV4zbnO7qC9FGo6YYutc+wyyUSHBgbXL52eXk= github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI= github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= github.com/go-ole/go-ole v1.2.6 h1:/Fpf6oFPoeFik9ty7siob0G6Ke8QvQEuVcuChpwXzpY= github.com/go-ole/go-ole v1.2.6/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0= github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s= github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4= github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA= github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY= github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY= github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY= github.com/go-playground/validator/v10 v10.30.1 h1:f3zDSN/zOma+w6+1Wswgd9fLkdwy06ntQJp0BBvFG0w= github.com/go-playground/validator/v10 v10.30.1/go.mod h1:oSuBIQzuJxL//3MelwSLD5hc2Tu889bF0Idm9Dg26cM= github.com/go-task/slim-sprig/v3 v3.0.0 h1:sUs3vkvUymDpBKi3qH1YSqBQk9+9D/8M2mN1vB6EwHI= github.com/go-task/slim-sprig/v3 v3.0.0/go.mod h1:W848ghGpv3Qj3dhTPRyJypKRiqCdHZiAzKg9hl15HA8= github.com/go-viper/mapstructure/v2 v2.5.0 h1:vM5IJoUAy3d7zRSVtIwQgBj7BiWtMPfmPEgAXnvj1Ro= github.com/go-viper/mapstructure/v2 v2.5.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM= github.com/goccy/go-yaml v1.18.0 h1:8W7wMFS12Pcas7KU+VVkaiCng+kG8QiFeFwzFb+rwuw= github.com/goccy/go-yaml v1.18.0/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA= github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= github.com/google/go-github/v62 v62.0.0 h1:/6mGCaRywZz9MuHyw9gD1CwsbmBX8GWsbFkwMmHdhl4= github.com/google/go-github/v62 v62.0.0/go.mod h1:EMxeUqGJq2xRu9DYBMwel/mr7kZrzUOfQmmpYrZn2a4= github.com/google/go-querystring v1.1.0 h1:AnCroh3fv4ZBgVIf1Iwtovgjaw/GiKJo8M8yD/fhyJ8= github.com/google/go-querystring v1.1.0/go.mod h1:Kcdr2DB4koayq7X8pmAG4sNG59So17icRSOU623lUBU= github.com/google/pprof v0.0.0-20260115054156-294ebfa9ad83 h1:z2ogiKUYzX5Is6zr/vP9vJGqPwcdqsWjOt+V8J7+bTc= github.com/google/pprof v0.0.0-20260115054156-294ebfa9ad83/go.mod h1:MxpfABSjhmINe3F1It9d+8exIHFvUqtLIRCdOGNXqiI= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/gorilla/mux v1.8.1 h1:TuBL49tXwgrFYWhqrNgrUNEY92u81SPhu7sTdzQEiWY= github.com/gorilla/mux v1.8.1/go.mod h1:AKf9I4AEqPTmMytcMc0KkNouC66V3BtZ4qD5fmWSiMQ= github.com/gotd/contrib v0.20.0 h1:1Wc4+HMQiIKYQuGHVwVksIx152HFTP6B5n88dDe0ZYw= github.com/gotd/contrib v0.20.0/go.mod h1:P6o8W4niqhDPHLA0U+SA/L7l3BQHYLULpeHfRSePn9o= github.com/gotd/ige v0.2.2 h1:XQ9dJZwBfDnOGSTxKXBGP4gMud3Qku2ekScRjDWWfEk= github.com/gotd/ige v0.2.2/go.mod h1:tuCRb+Y5Y3eNTo3ypIfNpQ4MFjrnONiL2jN2AKZXmb0= github.com/gotd/neo v0.1.5 h1:oj0iQfMbGClP8xI59x7fE/uHoTJD7NZH9oV1WNuPukQ= github.com/gotd/neo v0.1.5/go.mod h1:9A2a4bn9zL6FADufBdt7tZt+WMhvZoc5gWXihOPoiBQ= github.com/gotd/td v0.122.0 h1:xIqoYI02ElZjj+KxOfvoUjA63m7MGWZkemM4m42aqRE= github.com/gotd/td v0.122.0/go.mod h1:vPC2X2rcRQYAGVr9EgmQgswHcj8Ps0Tt66XylR3CxrI= github.com/hinshun/vt10x v0.0.0-20220119200601-820417d04eec h1:qv2VnGeEQHchGaZ/u7lxST/RaJw+cv273q79D81Xbog= github.com/hinshun/vt10x v0.0.0-20220119200601-820417d04eec/go.mod h1:Q48J4R4DvxnHolD5P8pOtXigYlRuPLGl6moFx3ulM68= github.com/iancoleman/strcase v0.3.0 h1:nTXanmYxhfFAMjZL34Ov6gkzEsSJZ5DbhxWjvSASxEI= github.com/iancoleman/strcase v0.3.0/go.mod h1:iwCmte+B7n89clKwxIoIXy/HfoL7AsD47ZCWhYzw7ho= github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8= github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= github.com/ivanpirog/coloredcobra v1.0.1 h1:aURSdEmlR90/tSiWS0dMjdwOvCVUeYLfltLfbgNxrN4= github.com/ivanpirog/coloredcobra v1.0.1/go.mod h1:iho4nEKcnwZFiniGSdcgdvRgZNjxm+h20acv8vqmN6Q= github.com/iyear/connectproxy v0.1.1 h1:JZOF/62vvwRGBWcgSyWRb0BpKD4FSs0++B5/y5pNE4c= github.com/iyear/connectproxy v0.1.1/go.mod h1:yD4zOmSMQCmwHIT4fk8mg4k2M15z8VoMSoeY6NNJdsA= github.com/iyear/tdl/core v0.20.1 h1:UdnlBtI9C5wZV718MevtRtxIKgQ/jwaOjas34Qlw2us= github.com/iyear/tdl/core v0.20.1/go.mod h1:oIMvODKNqz52VmAk3M2+otHTPai4xo3y1aQ2VZE25eY= github.com/iyear/tdl/extension v0.20.1 h1:3fpOcoxm87Xu8jA3jOGZBNXNZGcWISh9UdAQNI/Tobw= github.com/iyear/tdl/extension v0.20.1/go.mod h1:zM8ZaR+q25JrtVJIP5H7fknDpge/r6TVFsS4DNJfpIE= github.com/jedib0t/go-pretty/v6 v6.5.0 h1:FI0L5PktzbafnZKuPae/D3150x3XfYbFe2hxMT+TbpA= github.com/jedib0t/go-pretty/v6 v6.5.0/go.mod h1:Ndk3ase2CkQbXLLNf5QDHoYb6J9WtVfmHZu9n8rk2xs= github.com/joshdk/go-junit v1.0.0 h1:S86cUKIdwBHWwA6xCmFlf3RTLfVXYQfvanM5Uh+K6GE= github.com/joshdk/go-junit v1.0.0/go.mod h1:TiiV0PqkaNfFXjEiyjWM3XXrhVyCa1K4Zfga6W52ung= github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51 h1:Z9n2FFNUXsshfwJMBgNA0RU6/i7WVaAegv3PtuIHPMs= github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51/go.mod h1:CzGEWj7cYgsdH8dAjBGEr58BoE7ScuLd+fwFZ44+/x8= github.com/klauspost/compress v1.18.4 h1:RPhnKRAQ4Fh8zU2FY/6ZFDwTVTxgJ/EMydqSTzE9a2c= github.com/klauspost/compress v1.18.4/go.mod h1:R0h/fSBs8DE4ENlcrlib3PsXS61voFxhIs2DeRhCvJ4= github.com/kopoli/go-terminal-size v0.0.0-20170219200355-5c97524c8b54 h1:0SMHxjkLKNawqUjjnMlCtEdj6uWZjv0+qDZ3F6GOADI= github.com/kopoli/go-terminal-size v0.0.0-20170219200355-5c97524c8b54/go.mod h1:bm7MVZZvHQBfqHG5X59jrRE/3ak6HvK+/Zb6aZhLR2s= github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= 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/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/maruel/natural v1.1.1 h1:Hja7XhhmvEFhcByqDoHz9QZbkWey+COd9xWfCfn1ioo= github.com/maruel/natural v1.1.1/go.mod h1:v+Rfd79xlw1AgVBjbO0BEQmptqb5HvL/k9GRHB7ZKEg= github.com/mattn/go-colorable v0.1.2/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE= github.com/mattn/go-colorable v0.1.9/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc= github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA= github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg= github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU= github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94= github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= github.com/mattn/go-runewidth v0.0.13/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w= github.com/mattn/go-runewidth v0.0.20 h1:WcT52H91ZUAwy8+HUkdM3THM6gXqXuLJi9O3rjcQQaQ= github.com/mattn/go-runewidth v0.0.20/go.mod h1:XBkDxAl56ILZc9knddidhrOlY5R/pDhgLpndooCuJAs= github.com/mfridman/tparse v0.18.0 h1:wh6dzOKaIwkUGyKgOntDW4liXSo37qg5AXbIhkMV3vE= github.com/mfridman/tparse v0.18.0/go.mod h1:gEvqZTuCgEhPbYk/2lS3Kcxg1GmTxxU7kTC8DvP0i/A= github.com/mgutz/ansi v0.0.0-20170206155736-9520e82c474b/go.mod h1:01TrycV0kFyexm33Z7vhZRXopbI8J3TDReVlkTgMUxE= github.com/mgutz/ansi v0.0.0-20200706080929-d51e80ef957d h1:5PJl274Y63IEHC+7izoQE9x6ikvDFZS2mDVS3drnohI= 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/ogen-go/ogen v1.10.1 h1:oeSN8AF9mhTVfapbMuL8pQTF2ToqyW9xXaStmOhHKTA= github.com/ogen-go/ogen v1.10.1/go.mod h1:fXCg9PsNYEzJ8ABdmZ2A7j4hMi9EDHP53jzsNtIM3d0= github.com/onsi/ginkgo/v2 v2.28.1 h1:S4hj+HbZp40fNKuLUQOYLDgZLwNUVn19N3Atb98NCyI= github.com/onsi/ginkgo/v2 v2.28.1/go.mod h1:CLtbVInNckU3/+gC8LzkGUb9oF+e8W8TdUsxPwvdOgE= github.com/onsi/gomega v1.39.1 h1:1IJLAad4zjPn2PsnhH70V4DKRFlrCzGBNrNaru+Vf28= github.com/onsi/gomega v1.39.1/go.mod h1:hL6yVALoTOxeWudERyfppUcZXjMwIMLnuSfruD2lcfg= github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4= github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY= github.com/pkg/profile v1.6.0/go.mod h1:qBsxPvzyUincmltOk6iyRVxHYg4adc0OFOv72ZdLa18= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/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/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= 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= github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/sagikazarmark/locafero v0.11.0 h1:1iurJgmM9G3PA/I+wWYIOw/5SyBtxapeHDcg+AAIFXc= github.com/sagikazarmark/locafero v0.11.0/go.mod h1:nVIGvgyzw595SUSUE6tvCp3YYTeHs15MvlmU87WwIik= github.com/samber/lo v1.52.0 h1:Rvi+3BFHES3A8meP33VPAxiBZX/Aws5RxrschYGjomw= github.com/samber/lo v1.52.0/go.mod h1:4+MXEGsJzbKGaUEQFKBq2xtfuznW9oz/WrgyzMzRoM0= github.com/segmentio/asm v1.2.1 h1:DTNbBqs57ioxAD4PrArqftgypG4/qNpXoJx8TVXxPR0= github.com/segmentio/asm v1.2.1/go.mod h1:BqMnlJP91P8d+4ibuonYZw9mfnzI9HfxselHZr5aAcs= github.com/shirou/gopsutil/v3 v3.24.5 h1:i0t8kL+kQTvpAYToeuiVk3TgDeKOFioZO3Ztz/iZ9pI= github.com/shirou/gopsutil/v3 v3.24.5/go.mod h1:bsoOS1aStSs9ErQ1WWfxllSeS1K5D+U30r2NfcubMVk= github.com/shoenig/go-m1cpu v0.1.6 h1:nxdKQNcEB6vzgA2E2bvzKIYRuNj7XNJ4S/aRSwKzFtM= github.com/shoenig/go-m1cpu v0.1.6/go.mod h1:1JJMcUBvfNwpq05QDQVAnx3gUHr9IYF7GNg9SUEw2VQ= github.com/shoenig/test v0.6.4 h1:kVTaSd7WLz5WZ2IaoM0RSzRsUD+m8wRR+5qvntpn4LU= github.com/shoenig/test v0.6.4/go.mod h1:byHiCGXqrVaflBLAMq/srcZIHynQPQgeyvkvXnjqq0k= github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e h1:MRM5ITcdelLK2j1vwZ3Je0FKVCfqOLp5zO6trqMLYs0= github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e/go.mod h1:XV66xRDqSt+GTGFMVlhk3ULuV0y9ZmzeVGR4mloJI3M= github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8 h1:+jumHNA0Wrelhe64i8F6HNlS8pkoyMv5sreGx2Ry5Rw= github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8/go.mod h1:3n1Cwaq1E1/1lhQhtRK2ts/ZwZEhjcQeJQ1RuC6Q/8U= github.com/spf13/afero v1.15.0 h1:b/YBCLWAJdFWJTN9cLhiXXcD7mzKn9Dm86dNnfyQw1I= github.com/spf13/afero v1.15.0/go.mod h1:NC2ByUVxtQs4b3sIUphxK0NioZnmxgyCrfzeuq8lxMg= github.com/spf13/cast v1.10.0 h1:h2x0u2shc1QuLHfxi+cTJvs30+ZAHOGRic8uyGTDWxY= github.com/spf13/cast v1.10.0/go.mod h1:jNfB8QC9IA6ZuY2ZjDp0KtFO2LZZlg4S/7bzP6qqeHo= github.com/spf13/cobra v1.4.0/go.mod h1:Wo4iy3BUC+X2Fybo0PDqwJIv3dNRiZLHQymsfxlB84g= github.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU= github.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTUUS4= github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk= github.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/spf13/viper v1.21.0 h1:x5S+0EU27Lbphp4UKm1C+1oQO+rKx36vfCoaVebLFSU= github.com/spf13/viper v1.21.0/go.mod h1:P0lhsswPGWD/1lZJ9ny3fYnVqxiegrlNrEmgLjbTCAY= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.4/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8= github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU= github.com/tidwall/gjson v1.18.0 h1:FIDeeyB800efLX89e5a8Y0BNH+LOngJyGrIWxG2FKQY= github.com/tidwall/gjson v1.18.0/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk= github.com/tidwall/match v1.1.1 h1:+Ho715JplO36QYgwN9PGYNhgZvoUSc9X2c80KVTi+GA= github.com/tidwall/match v1.1.1/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM= github.com/tidwall/pretty v1.2.0/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU= github.com/tidwall/pretty v1.2.1 h1:qjsOFOWWQl+N3RsoF5/ssm1pHmJJwhjlSbZ51I6wMl4= github.com/tidwall/pretty v1.2.1/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU= github.com/tidwall/sjson v1.2.5 h1:kLy8mja+1c9jlljvWTlSazM7cKDRfJuR/bOJhcY5NcY= github.com/tidwall/sjson v1.2.5/go.mod h1:Fvgq9kS/6ociJEDnK0Fk1cpYF4FIW6ZF7LAe+6jwd28= github.com/tklauser/go-sysconf v0.3.12 h1:0QaGUFOdQaIVdPgfITYzaTegZvdCjmYO52cSFAEVmqU= 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/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= github.com/yusufpapurcu/wmi v1.2.4 h1:zFUKzehAFReQwLys1b/iSMl+JQGSCSjtVqQn9bBrPo0= github.com/yusufpapurcu/wmi v1.2.4/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0= go.etcd.io/bbolt v1.3.10 h1:+BqfJTcCzTItrop8mq/lbzL8wSGtj94UO/3U31shqG0= go.etcd.io/bbolt v1.3.10/go.mod h1:bK3UQLPJZly7IlNmV7uVHJDxfe5aK9Ll93e/74Y9oEQ= go.opentelemetry.io/auto/sdk v1.1.0 h1:cH53jehLUN6UFLY71z+NDOiNJqDdPRaXzTel0sJySYA= go.opentelemetry.io/auto/sdk v1.1.0/go.mod h1:3wSPjt5PWp2RhlCcmmOial7AvC4DQqZb7a7wCow3W8A= go.opentelemetry.io/otel v1.35.0 h1:xKWKPxrxB6OtMCbmMY021CqC45J+3Onta9MqjhnusiQ= go.opentelemetry.io/otel v1.35.0/go.mod h1:UEqy8Zp11hpkUrL73gSlELM0DupHoiq72dR+Zqel/+Y= go.opentelemetry.io/otel/metric v1.35.0 h1:0znxYu2SNyuMSQT4Y9WDWej0VpcsxkuklLa4/siN90M= go.opentelemetry.io/otel/metric v1.35.0/go.mod h1:nKVFgxBZ2fReX6IlyW28MgZojkoAkJGaE8CpgeAU3oE= go.opentelemetry.io/otel/trace v1.35.0 h1:dPpEfJu1sDIqruz7BHFG3c7528f6ddfSWfFDVt/xgMs= go.opentelemetry.io/otel/trace v1.35.0/go.mod h1:WUk7DtFp1Aw2MkvqGdwiXYDZZNvA/1J8o6xRXLrIkyc= go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE= go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0= go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE= go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0= go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y= go.uber.org/zap v1.27.1 h1:08RqriUEv8+ArZRYSTXy1LeBScaMpVSTBhCeaZYfMYc= go.uber.org/zap v1.27.1/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E= go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc= go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.48.0 h1:/VRzVqiRSggnhY7gNRxPauEQ5Drw9haKdM0jqfcCFts= golang.org/x/crypto v0.48.0/go.mod h1:r0kV5h3qnFPlQnBSrULhlsRfryS2pmewsg+XfMgkVos= golang.org/x/exp v0.0.0-20240719175910-8a7402abbf56 h1:2dVuKD2vS7b0QIHQbpyTISPd0LeHDbnYEryqj5Q1ug8= golang.org/x/exp v0.0.0-20240719175910-8a7402abbf56/go.mod h1:M4RDyNAINzryxdtnbRXRL/OHtkFuWGRjvuhBJpk2IlY= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= golang.org/x/mod v0.32.0 h1:9F4d3PHLljb6x//jOyokMv3eX+YDeepZSEo3mFJy93c= golang.org/x/mod v0.32.0/go.mod h1:SgipZ/3h2Ci89DlEtEXWUk/HteuRin+HHhN+WbNhguU= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= golang.org/x/net v0.51.0 h1:94R/GTO7mt3/4wIKpcR5gkGmRLOuE/2hNGeWq/GBIFo= golang.org/x/net v0.51.0/go.mod h1:aamm+2QF5ogm02fjy5Bb7CQ0WMt1/WVM7FtyaTLlA9Y= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20201207232520-09787c993a3a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.19.0 h1:vV+1eWNmZ5geRlYjzm2adRgW2/mcpevXNg50YZtPCE4= golang.org/x/sync v0.19.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201204225414-ed752295db88/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.11.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k= golang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.40.0 h1:36e4zGLqU4yhjlmxEaagx2KuYbJq3EwY8K943ZsHcvg= golang.org/x/term v0.40.0/go.mod h1:w2P8uVp06p2iyKKuvXIm7N/y0UCRt3UfJTfZ7oOpglM= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/text v0.4.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= golang.org/x/text v0.34.0 h1:oL/Qq0Kdaqxa1KbNeMKwQq0reLCCaFtqu2eNuSeNHbk= golang.org/x/text v0.34.0/go.mod h1:homfLqTYRFyVYemLBFl5GgL/DWEiH5wcsQ5gSh1yziA= golang.org/x/time v0.12.0 h1:ScB/8o8olJvc+CQPWrK3fPZNfh7qgwCrY0zJmoEQLSE= golang.org/x/time v0.12.0/go.mod h1:CDIdPxbZBQxdj6cxyCIdrNogrJKMJ7pr37NYpMcMDSg= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= golang.org/x/tools v0.41.0 h1:a9b8iMweWG+S0OBnlU36rzLp20z1Rp10w+IY2czHTQc= golang.org/x/tools v0.41.0/go.mod h1:XSY6eDqxVNiYgezAVqqCeihT4j1U2CCsqvH3WhQpnlg= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= google.golang.org/protobuf v1.36.7 h1:IgrO7UwFQGJdRNXH/sQux4R1Dj1WAKcLElzeeRaXV2A= google.golang.org/protobuf v1.36.7/go.mod h1:jduwjTPXsFjZGTmRluh+L6NjiWu7pchiJ2/5YcXBHnY= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo= gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/natefinch/lumberjack.v2 v2.2.1 h1:bBRl1b0OH9s/DuPhuXpNl+VtCaJXFZ5/uEFST95x9zc= gopkg.in/natefinch/lumberjack.v2 v2.2.1/go.mod h1:YD8tP3GAjkrDg1eZH7EGmyESg/lsYskCTPBJVb9jqSc= 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 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 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= rsc.io/qr v0.2.0/go.mod h1:IF+uZjkb9fqyeF/4tlBoynqmQxUoPfWEKh921coOuXs= ================================================ FILE: go.work ================================================ go 1.25.8 use ( . core extension ) ================================================ FILE: go.work.sum ================================================ cel.dev/expr v0.16.1 h1:NR0+oFYzR1CqLFhTAqg3ql59G9VfN8fKq1TCHJ6gq1g= cel.dev/expr v0.16.1/go.mod h1:AsGA5zb3WruAEQeQng1RZdGEXmBj0jvMWh6l5SnNuC8= cloud.google.com/go v0.116.0 h1:B3fRrSDkLRt5qSHWe40ERJvhvnQwdZiHu0bJOpldweE= cloud.google.com/go v0.116.0/go.mod h1:cEPSRWPzZEswwdr9BxE6ChEn01dWlTaF05LiC2Xs70U= cloud.google.com/go/auth v0.13.0 h1:8Fu8TZy167JkW8Tj3q7dIkr2v4cndv41ouecJx0PAHs= cloud.google.com/go/auth v0.13.0/go.mod h1:COOjD9gwfKNKz+IIduatIhYJQIc0mG3H102r/EMxX6Q= cloud.google.com/go/auth/oauth2adapt v0.2.6 h1:V6a6XDu2lTwPZWOawrAa9HUK+DB2zfJyTuciBG5hFkU= cloud.google.com/go/auth/oauth2adapt v0.2.6/go.mod h1:AlmsELtlEBnaNTL7jCj8VQFLy6mbZv0s4Q7NGBeQ5E8= cloud.google.com/go/compute/metadata v0.6.0 h1:A6hENjEsCDtC1k8byVsgwvVcioamEHvZ4j01OwKxG9I= cloud.google.com/go/compute/metadata v0.6.0/go.mod h1:FjyFAW1MW0C203CEOMDTu3Dk1FlqW3Rga40jzHL4hfg= cloud.google.com/go/iam v1.2.2 h1:ozUSofHUGf/F4tCNy/mu9tHLTaxZFLOUiKzjcgWHGIA= cloud.google.com/go/iam v1.2.2/go.mod h1:0Ys8ccaZHdI1dEUilwzqng/6ps2YB6vRsjIe00/+6JY= cloud.google.com/go/monitoring v1.21.2 h1:FChwVtClH19E7pJ+e0xUhJPGksctZNVOk2UhMmblmdU= cloud.google.com/go/monitoring v1.21.2/go.mod h1:hS3pXvaG8KgWTSz+dAdyzPrGUYmi2Q+WFX8g2hqVEZU= cloud.google.com/go/storage v1.49.0 h1:zenOPBOWHCnojRd9aJZAyQXBYqkJkdQS42dxL55CIMw= cloud.google.com/go/storage v1.49.0/go.mod h1:k1eHhhpLvrPjVGfo0mOUPEJ4Y2+a/Hv5PiwehZI9qGU= github.com/DataDog/zstd v1.4.5 h1:EndNeuB0l9syBZhut0wns3gV1hL8zX8LIu6ZiVHWLIQ= github.com/DataDog/zstd v1.4.5/go.mod h1:1jcaCB/ufaK+sKp1NBhlGmpz41jOoPQ35bpF36t7BBo= github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.25.0 h1:3c8yed4lgqTt+oTQ+JNMDo+F4xprBf+O/il4ZC0nRLw= github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.25.0/go.mod h1:obipzmGjfSjam60XLwGfqUkJsfiheAl+TUjG+4yzyPM= github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.48.1 h1:UQ0AhxogsIRZDkElkblfnwjc3IaltCm2HUMvezQaL7s= github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.48.1/go.mod h1:jyqM3eLpJ3IbIFDTKVz2rF9T/xWGW0rIriGwnz8l9Tk= github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping v0.48.1 h1:8nn+rsCvTq9axyEh382S0PFLBeaFwNsT43IrPWzctRU= github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping v0.48.1/go.mod h1:viRWSEhtMZqz1rhwmOVKkWl6SwmVowfL9O2YR5gI2PE= github.com/PuerkitoBio/goquery v1.10.1 h1:Y8JGYUkXWTGRB6Ars3+j3kN0xg1YqqlwvdTV8WTFQcU= github.com/PuerkitoBio/goquery v1.10.1/go.mod h1:IYiHrOMps66ag56LEH7QYDDupKXyo5A8qrjIx3ZtujY= github.com/andybalholm/brotli v1.1.1 h1:PR2pgnyFznKEugtsUo0xLdDop5SKXd5Qf5ysW+7XdTA= github.com/andybalholm/brotli v1.1.1/go.mod h1:05ib4cKhjx3OQYUY22hTVd34Bc8upXjOLL2rKwwZBoA= github.com/andybalholm/cascadia v1.3.3 h1:AG2YHrzJIm4BZ19iwJ/DAua6Btl3IwJX+VI4kktS1LM= github.com/andybalholm/cascadia v1.3.3/go.mod h1:xNd9bqTn98Ln4DwST8/nG+H0yuB8Hmgu1YHNnWw0GeA= github.com/benbjohnson/clock v1.3.0 h1:ip6w0uFQkncKQ979AypyG0ER7mqUSBdKLOgAle/AT8A= github.com/benbjohnson/clock v1.3.0/go.mod h1:J11/hYXuz8f4ySSvYwY0FKfm+ezbsZBKZxNJlLklBHA= github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= github.com/cenkalti/backoff/v3 v3.0.0 h1:ske+9nBpD9qZsTBoF41nW5L+AIuFBKMeze18XQ3eG1c= github.com/cenkalti/backoff/v3 v3.0.0/go.mod h1:cIeZDE3IrqwwJl6VUwCN6trj1oXrTS4rc0ij+ULvLYs= github.com/census-instrumentation/opencensus-proto v0.4.1 h1:iKLQ0xPNFxR/2hzXZMrBo8f1j86j5WHzznCCQxV/b8g= github.com/census-instrumentation/opencensus-proto v0.4.1/go.mod h1:4T9NM4+4Vw91VeyqjLS6ao50K5bOcLKN6Q42XnYaRYw= github.com/cespare/xxhash/v2 v2.2.0 h1:DC2CZ1Ep5Y4k3ZQ899DldepgrayRUGE6BBZ/cd9Cj44= github.com/cespare/xxhash/v2 v2.2.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= 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/chzyer/readline v1.5.1 h1:upd/6fQk4src78LMRzh5vItIt361/o4uq553V8B5sGI= github.com/chzyer/readline v1.5.1/go.mod h1:Eh+b79XXUwfKfcPLepksvw2tcLE/Ct21YObkaSkeBlk= github.com/cncf/xds/go v0.0.0-20240905190251-b4127c9b8d78 h1:QVw89YDxXxEe+l8gU8ETbOasdwEV+avkR75ZzsVV9WI= github.com/cncf/xds/go v0.0.0-20240905190251-b4127c9b8d78/go.mod h1:W+zGtBO5Y1IgJhy4+A9GOqVhqLpfZi+vwmdNXUehLA8= github.com/cockroachdb/errors v1.11.1 h1:xSEW75zKaKCWzR3OfxXUxgrk/NtT4G1MiOv5lWZazG8= github.com/cockroachdb/errors v1.11.1/go.mod h1:8MUxA3Gi6b25tYlFEBGLf+D8aISL+M4MIpiWMSNRfxw= github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b h1:r6VH0faHjZeQy818SGhaone5OnYfxFR/+AzdY3sf5aE= github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b/go.mod h1:Vz9DsVWQQhf3vs21MhPMZpMGSht7O/2vFW2xusFUVOs= github.com/cockroachdb/pebble v1.1.0 h1:pcFh8CdCIt2kmEpK0OIatq67Ln9uGDYY3d5XnE0LJG4= github.com/cockroachdb/pebble v1.1.0/go.mod h1:sEHm5NOXxyiAoKWhoFxT8xMgd/f3RA6qUqQ1BXKrh2E= github.com/cockroachdb/redact v1.1.5 h1:u1PMllDkdFfPWaNGMyLD1+so+aq3uUItthCFqzwPJ30= github.com/cockroachdb/redact v1.1.5/go.mod h1:BVNblN9mBWFyMyqK1k3AAiSxhvhfK2oOZZ2lK+dpvRg= github.com/cockroachdb/tokenbucket v0.0.0-20230807174530-cc333fc44b06 h1:zuQyyAKVxetITBuuhv3BI9cMrmStnpT18zmgmTxunpo= github.com/cockroachdb/tokenbucket v0.0.0-20230807174530-cc333fc44b06/go.mod h1:7nc4anLGjupUW/PeY5qiNYsdNXj7zopG+eqsS7To5IQ= github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78= github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc= 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/envoyproxy/go-control-plane v0.13.1 h1:vPfJZCkob6yTMEgS+0TwfTUfbHjfy/6vOJ8hUWX/uXE= github.com/envoyproxy/go-control-plane v0.13.1/go.mod h1:X45hY0mufo6Fd0KW3rqsGvQMw58jvjymeCzBU3mWyHw= github.com/envoyproxy/protoc-gen-validate v1.1.0 h1:tntQDh69XqOCOZsDz0lVJQez/2L6Uu2PdjCQwWCJ3bM= github.com/envoyproxy/protoc-gen-validate v1.1.0/go.mod h1:sXRDRVmzEbkM7CVcM06s9shE/m23dg3wzjl0UWqJ2q4= github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg= github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U= github.com/gen2brain/dlgs v0.0.0-20211108104213-bade24837f0b h1:M0/hjawi9ur15zpqL/h66ga87jlYA7iAuZ4HC6ak08k= github.com/gen2brain/dlgs v0.0.0-20211108104213-bade24837f0b/go.mod h1:/eFcjDXaU2THSOOqLxOPETIbHETnamk8FA/hMjhg/gU= github.com/getsentry/sentry-go v0.18.0 h1:MtBW5H9QgdcJabtZcuJG80BMOwaBpkRDZkxRkNC1sN0= github.com/getsentry/sentry-go v0.18.0/go.mod h1:Kgon4Mby+FJ7ZWHFUAZgVaIa8sxHtnRJRLTXZr51aKQ= github.com/go-faster/sdk v0.22.0 h1:s/Pq3lJ00MrHMoEUzeAemPz7kXzfETw2iN6outyOHoY= github.com/go-faster/sdk v0.22.0/go.mod h1:UJWFlbuRJHmXJwl4JxStMbbIZtMAz4fxrD4CnuDXCIc= github.com/go-jose/go-jose/v3 v3.0.3 h1:fFKWeig/irsp7XD2zBxvnmA/XaRWp5V3CBsZXJF7G7k= github.com/go-jose/go-jose/v3 v3.0.3/go.mod h1:5b+7YgP7ZICgJDBdfjZaIt+H/9L9T/YQrVfLAMboGkQ= github.com/go-openapi/inflect v0.21.2 h1:0gClGlGcxifcJR56zwvhaOulnNgnhc4qTAkob5ObnSM= github.com/go-openapi/inflect v0.21.2/go.mod h1:INezMuUu7SJQc2AyR3WO0DqqYUJSj8Kb4hBd7WtjlAw= github.com/go-redis/redis/v8 v8.11.5 h1:AcZZR7igkdvfVmQTPnu9WE37LRrO/YrBH5zWyjDC0oI= github.com/go-redis/redis/v8 v8.11.5/go.mod h1:gREzHqY1hg6oD9ngVRbLStwAWKhA0FEgq8Jd4h5lpwo= github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q= github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q= github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da h1:oI5xCqsCo564l8iNU+DwB5epxmsaqB+rhGL0m5jtYqE= github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= github.com/golang/snappy v0.0.4 h1:yAGX7huGHXlcLOEtBnF4w7FQwA26wojNCwOYAEhLjQM= github.com/golang/snappy v0.0.4/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/google/s2a-go v0.1.8 h1:zZDs9gcbt9ZPLV0ndSyQk6Kacx2g/X+SKYovpnz3SMM= github.com/google/s2a-go v0.1.8/go.mod h1:6iNWHTpQ+nfNRN5E00MSdfDwVesa8hhS32PhPO8deJA= github.com/googleapis/enterprise-certificate-proxy v0.3.4 h1:XYIDZApgAnrN1c855gTgghdIA6Stxb52D5RnLI1SLyw= github.com/googleapis/enterprise-certificate-proxy v0.3.4/go.mod h1:YKe7cfqYXjKGpGvmSg28/fFvhNzinZQm8DGnaburhGA= github.com/googleapis/gax-go/v2 v2.14.1 h1:hb0FFeiPaQskmvakKu5EbCbpntQn48jyHuvrkurSS/Q= github.com/googleapis/gax-go/v2 v2.14.1/go.mod h1:Hb/NubMaVM88SrNkvl8X/o8XWwDJEPqouaLeN2IUxoA= github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1 h1:EGx4pi6eqNxGaHF6qqu48+N2wcFQ5qg5FXgOdqsJ5d8= github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= github.com/gotd/getdoc v0.48.0 h1:oo0C/tNHOwZsuW5egYhrD4XLtlAnz2ubSfz6tdh0FEM= github.com/gotd/getdoc v0.48.0/go.mod h1:w5IDi4f2qAfBjk7CmzVKpTRU1/jGSZinwZ2Gxej1XvA= github.com/gotd/tl v0.4.0 h1:8k2z0drujiPyhpLDa9PRm/yU1Gwlfn3iUzeInPiXwMA= github.com/gotd/tl v0.4.0/go.mod h1:CMIcjPWFS4qxxJ+1Ce7U/ilbtPrkoVo/t8uhN5Y/D7c= github.com/hashicorp/errwrap v1.1.0 h1:OxrOeh75EUXMY8TBjag2fzXGZ40LB6IKw45YeGUDY2I= github.com/hashicorp/errwrap v1.1.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= github.com/hashicorp/go-cleanhttp v0.5.2 h1:035FKYIWjmULyFRBKPs8TBQoi0x6d9G4xc9neXJWAZQ= github.com/hashicorp/go-cleanhttp v0.5.2/go.mod h1:kO/YDlP8L1346E6Sodw+PrpBSV4/SoxCXGY6BqNFT48= github.com/hashicorp/go-multierror v1.1.1 h1:H5DkEtf6CXdFp0N0Em5UCwQpXMWke8IA0+lD48awMYo= github.com/hashicorp/go-multierror v1.1.1/go.mod h1:iw975J/qwKPdAO1clOe2L8331t/9/fmwbPZ6JB6eMoM= github.com/hashicorp/go-retryablehttp v0.6.6 h1:HJunrbHTDDbBb/ay4kxa1n+dLmttUlnP3V9oNE4hmsM= github.com/hashicorp/go-retryablehttp v0.6.6/go.mod h1:vAew36LZh98gCBJNLH42IQ1ER/9wtLZZ8meHqQvEYWY= github.com/hashicorp/go-rootcerts v1.0.2 h1:jzhAVGtqPKbwpyCPELlgNWhE1znq+qwJtW5Oi2viEzc= github.com/hashicorp/go-rootcerts v1.0.2/go.mod h1:pqUvnprVnM5bf7AOirdbb01K4ccR319Vf4pU3K5EGc8= github.com/hashicorp/go-secure-stdlib/parseutil v0.1.6 h1:om4Al8Oy7kCm/B86rLCLah4Dt5Aa0Fr5rYBG60OzwHQ= github.com/hashicorp/go-secure-stdlib/parseutil v0.1.6/go.mod h1:QmrqtbKuxxSWTN3ETMPuB+VtEiBJ/A9XhoYGv8E1uD8= github.com/hashicorp/go-secure-stdlib/strutil v0.1.2 h1:kes8mmyCpxJsI7FTwtzRqEy9CdjCtrXrXGuOpxEA7Ts= github.com/hashicorp/go-secure-stdlib/strutil v0.1.2/go.mod h1:Gou2R9+il93BqX25LAKCLuM+y9U2T4hlwvT1yprcna4= github.com/hashicorp/go-sockaddr v1.0.2 h1:ztczhD1jLxIRjVejw8gFomI1BQZOe2WoVOu0SyteCQc= github.com/hashicorp/go-sockaddr v1.0.2/go.mod h1:rB4wwRAUzs07qva3c5SdrY/NEtAUjGlgmH/UkBUC97A= github.com/hashicorp/hcl v1.0.0 h1:0Anlzjpi4vEasTeNFn2mLJgTSwt0+6sfsiTG8qcWGx4= github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ= github.com/hashicorp/vault/api v1.12.2 h1:7YkCTE5Ni90TcmYHDBExdt4WGJxhpzaHqR6uGbQb/rE= github.com/hashicorp/vault/api v1.12.2/go.mod h1:LSGf1NGT1BnvFFnKVtnvcaLBM2Lz+gJdpL6HUYed8KE= github.com/ianlancetaylor/demangle v0.0.0-20240312041847-bd984b5ce465 h1:KwWnWVWCNtNq/ewIX7HIKnELmEx2nDP42yskD/pi7QE= github.com/ianlancetaylor/demangle v0.0.0-20240312041847-bd984b5ce465/go.mod h1:gx7rwoVhcfuVKG5uya9Hs3Sxj7EIvldVofAWIUtGouw= github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= github.com/k0kubun/pp/v3 v3.4.1 h1:1WdFZDRRqe8UsR61N/2RoOZ3ziTEqgTPVqKrHeb779Y= github.com/k0kubun/pp/v3 v3.4.1/go.mod h1:+SiNiqKnBfw1Nkj82Lh5bIeKQOAkPy6Xw9CAZUZ8npI= github.com/klauspost/cpuid/v2 v2.2.6 h1:ndNyv040zDGIDh8thGkXYjnFtiN02M1PVVF+JE/48xc= github.com/klauspost/cpuid/v2 v2.2.6/go.mod h1:Lcz8mBdAVJIBVzewtcLocK12l3Y+JytZYpaMropDUws= github.com/kr/fs v0.1.0 h1:Jskdu9ieNAYnjxsi0LbQp1ulIKZV1LAFgK1tWhpZgl8= github.com/kr/fs v0.1.0/go.mod h1:FFnZGqtBN9Gxj7eW1uZ42v5BccTP0vu6NEaFoC2HwRg= github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= github.com/kr/pty v1.1.1 h1:VkoXIwSboBpnk99O/KFauAEILuNHv5DVFKZMBN/gUgw= github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= github.com/minio/md5-simd v1.1.2 h1:Gdi1DZK69+ZVMoNHRXJyNcxrMA4dSxoYHZSQbirFg34= github.com/minio/md5-simd v1.1.2/go.mod h1:MzdKDxYpY2BT9XQFocsiZf/NKVtR7nkE4RoEpN+20RM= github.com/minio/minio-go/v7 v7.0.69 h1:l8AnsQFyY1xiwa/DaQskY4NXSLA2yrGsW5iD9nRPVS0= github.com/minio/minio-go/v7 v7.0.69/go.mod h1:XAvOPJQ5Xlzk5o3o/ArO2NMbhSGkimC+bpW/ngRKDmQ= github.com/minio/sha256-simd v1.0.1 h1:6kaan5IFmwTNynnKKpDHe6FWHohJOHhCPchzK49dzMM= github.com/minio/sha256-simd v1.0.1/go.mod h1:Pz6AKMiUdngCLpeTL/RJY1M9rUuPMYujV5xJjtbRSN8= github.com/mitchellh/go-homedir v1.1.0 h1:lukF9ziXFxDFPkA1vsr5zpc1XuPDn/wFntq5mG+4E0Y= github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e h1:aoZm08cpOy4WuID//EZDgcC4zIxODThtZNPirFr42+A= github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA= github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/profile v1.6.0 h1:hUDfIISABYI59DyeB3OTay/HxSRwTQ8rB/H83k6r5dM= github.com/pkg/sftp v1.13.7 h1:uv+I3nNJvlKZIQGSr8JVQLNHFU9YhhNpvC14Y6KgmSM= github.com/pkg/sftp v1.13.7/go.mod h1:KMKI0t3T6hfA+lTR/ssZdunHo+uwq7ghoN09/FSu3DY= github.com/planetscale/vtprotobuf v0.6.1-0.20240319094008-0393e58bdf10 h1:GFCKgmp0tecUJ0sJuv4pzYCqS9+RGSn52M3FUwPs+uo= github.com/planetscale/vtprotobuf v0.6.1-0.20240319094008-0393e58bdf10/go.mod h1:t/avpk3KcrXxUnYOhZhMXJlSEyie6gQbtLq5NM3loB8= github.com/prometheus/client_golang v1.19.0 h1:ygXvpU1AoN1MhdzckN+PyD9QJOSD4x7kmXYlnfbA6JU= github.com/prometheus/client_golang v1.19.0/go.mod h1:ZRM9uEAypZakd+q/x7+gmsvXdURP+DABIEIjnmDdp+k= github.com/prometheus/client_model v0.5.0 h1:VQw1hfvPvk3Uv6Qf29VrPF32JB6rtbgI6cYPYQjL0Qw= github.com/prometheus/client_model v0.5.0/go.mod h1:dTiFglRmd66nLR9Pv9f0mZi7B7fk5Pm3gvsjB5tr+kI= github.com/prometheus/common v0.48.0 h1:QO8U2CdOzSn1BBsmXJXduaaW+dY/5QLjfB8svtSzKKE= github.com/prometheus/common v0.48.0/go.mod h1:0/KsvlIEfPQCQ5I2iNSAWKPZziNCvRs5EC6ILDTlAPc= github.com/prometheus/procfs v0.12.0 h1:jluTpSng7V9hY0O2R9DzzJHYb2xULk9VTR1V1R/k6Bo= github.com/prometheus/procfs v0.12.0/go.mod h1:pcuDEFsWDnvcgNzo4EEweacyhjeA9Zk3cnaOZAZEfOo= github.com/rivo/uniseg v0.2.0 h1:S1pD9weZBuJdFmowNwbpi7BJ8TNftyUImj/0WQi72jY= github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs= github.com/rs/xid v1.5.0 h1:mKX4bl4iPYJtEIxp6CYiUuLQ/8DYMoz0PUdtGgMFRVc= github.com/rs/xid v1.5.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg= github.com/ryanuber/go-glob v1.0.0 h1:iQh3xXAumdQ+4Ufa5b25cRpC5TYKlno6hsv6Cb3pkBk= github.com/ryanuber/go-glob v1.0.0/go.mod h1:807d1WSdnB0XRJzKNil9Om6lcp/3a0v4qIHxIXzX/Yc= github.com/sergi/go-diff v1.1.0 h1:we8PVUC3FE2uYfodKH/nBHMSetSfHDR6scGdBi+erh0= github.com/sergi/go-diff v1.1.0/go.mod h1:STckp+ISIX8hZLjrqAeVduY0gWCT9IjLuqbuNXdaHfM= github.com/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY= github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA= github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw= github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc= github.com/valyala/fasthttp v1.59.0 h1:Qu0qYHfXvPk1mSLNqcFtEk6DpxgA26hy6bmydotDpRI= github.com/valyala/fasthttp v1.59.0/go.mod h1:GTxNb9Bc6r2a9D0TWNSPwDz78UxnTGBViY3xZNEqyYU= github.com/yuin/goldmark v1.4.13 h1:fVcFKWvrslecOb/tg+Cc05dkeYx540o0FuFt3nUVDoE= go.etcd.io/gofail v0.1.0 h1:XItAMIhOojXFQMgrxjnd2EIIHun/d5qL0Pf7FzVTkFg= go.etcd.io/gofail v0.1.0/go.mod h1:VZBCXYGZhHAinaBiiqYvuDynvahNsAyLFwB3kEHKz1M= go.opencensus.io v0.24.0 h1:y73uSU6J157QMP2kn2r30vwW1A2W2WFwSCGnAVxeaD0= go.opencensus.io v0.24.0/go.mod h1:vNK8G9p7aAivkbmorf4v+7Hgx+Zs0yY+0fOtgBfjQKo= go.opentelemetry.io/contrib/detectors/gcp v1.29.0 h1:TiaiXB4DpGD3sdzNlYQxruQngn5Apwzi1X0DRhuGvDQ= go.opentelemetry.io/contrib/detectors/gcp v1.29.0/go.mod h1:GW2aWZNwR2ZxDLdv8OyC2G8zkRoQBuURgV7RPQgcPoU= go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.54.0 h1:r6I7RJCN86bpD/FQwedZ0vSixDpwuWREjW9oRMsmqDc= go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.54.0/go.mod h1:B9yO6b04uB80CzjedvewuqDhxJxi11s7/GtiGa8bAjI= go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.54.0 h1:TT4fX+nBOA/+LUkobKGW1ydGcn+G3vRw9+g5HwCphpk= go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.54.0/go.mod h1:L7UH0GbB0p47T4Rri3uHjbpCFYrVrwc1I25QhNPiGK8= go.opentelemetry.io/otel/sdk v1.35.0 h1:iPctf8iprVySXSKJffSS79eOjl9pvxV9ZqOWT0QejKY= go.opentelemetry.io/otel/sdk v1.35.0/go.mod h1:+ga1bZliga3DxJ3CQGg3updiaAJoNECOgJREo9KHGQg= go.opentelemetry.io/otel/sdk/metric v1.35.0 h1:1RriWBmCKgkeHEhM7a2uMjMUfP7MsOF5JpUCaEqEI9o= go.opentelemetry.io/otel/sdk/metric v1.35.0/go.mod h1:is6XYCUMpcKi+ZsOvfluY5YstFnhW0BidkR+gL+qN+w= go.uber.org/ratelimit v0.3.1 h1:K4qVE+byfv/B3tC+4nYWP7v/6SimcO7HzHekoMNBma0= go.uber.org/ratelimit v0.3.1/go.mod h1:6euWsTB6U/Nb3X++xEUXA8ciPJvr19Q/0h1+oDcJhRk= golang.org/x/exp v0.0.0-20230116083435-1de6713980de/go.mod h1:CxIveKay+FTh1D0yPZemJVgC/95VzuuOLq5Qi4xnoYc= golang.org/x/mod v0.19.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= golang.org/x/mod v0.21.0/go.mod h1:6SkKJ3Xj0I0BrPOZoBy3bdMptDDU9oJrpohJ3eWZ1fY= golang.org/x/mod v0.24.0/go.mod h1:IXM97Txy2VM4PJ3gI61r1YEk/gAj6zAHN3AdZt6S9Ww= golang.org/x/mod v0.26.0/go.mod h1:/j6NAhSk8iQ723BGAUyoAcn7SlD7s15Dp9Nd/SfeaFQ= golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM= golang.org/x/net v0.40.0/go.mod h1:y0hY0exeL2Pku80/zKK7tpntoX23cqL3Oa6njdgRtds= golang.org/x/net v0.42.0/go.mod h1:FF1RA5d3u7nAYA4z2TkclSCKh68eSXtiFwcWQpPXdt8= golang.org/x/oauth2 v0.25.0 h1:CY4y7XT9v0cRI9oupztF8AgiIu99L/ksR/Xp/6jrZ70= golang.org/x/oauth2 v0.25.0/go.mod h1:XYTD2NtWslqkgxebSiOHnXEap4TF09sJSc7H1sXbhtI= golang.org/x/sync v0.7.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= golang.org/x/sync v0.14.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA= golang.org/x/sys v0.0.0-20220412211240-33da011f77ad/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/sys v0.26.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/telemetry v0.0.0-20240521205824-bda55230c457 h1:zf5N6UOrA487eEFacMePxjXAJctxKmyjKUsjA11Uzuk= golang.org/x/telemetry v0.0.0-20240521205824-bda55230c457/go.mod h1:pRgIJT+bRLFKnoM1ldnzKoxTIn14Yxz928LQRYYgIN0= golang.org/x/telemetry v0.0.0-20250807160809-1a19826ec488 h1:3doPGa+Gg4snce233aCWnbZVFsyFMo/dR40KK/6skyE= golang.org/x/telemetry v0.0.0-20250807160809-1a19826ec488/go.mod h1:fGb/2+tgXXjhjHsTNdVEEMZNWA0quBnfrO+AfoDSAKw= golang.org/x/tools v0.13.0/go.mod h1:HvlwmtVNQAhOuCjW7xxvovg8wbNq7LwfXh/k7wXUl58= golang.org/x/tools v0.23.0/go.mod h1:pnu6ufv6vQkll6szChhK3C3L/ruaIv5eBeztNG8wtsI= golang.org/x/tools v0.26.0/go.mod h1:TPVVj70c7JJ3WCazhD8OdXcZg/og+b9+tH/KxylGwH0= golang.org/x/tools v0.35.0/go.mod h1:NKdj5HkL/73byiZSJjqJgKn3ep7KjFkBOkR/Hps3VPw= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4= google.golang.org/api v0.215.0 h1:jdYF4qnyczlEz2ReWIsosNLDuzXyvFHJtI5gcr0J7t0= google.golang.org/api v0.215.0/go.mod h1:fta3CVtuJYOEdugLNWm6WodzOS8KdFckABwN4I40hzY= google.golang.org/genproto v0.0.0-20241118233622-e639e219e697 h1:ToEetK57OidYuqD4Q5w+vfEnPvPpuTwedCNVohYJfNk= google.golang.org/genproto v0.0.0-20241118233622-e639e219e697/go.mod h1:JJrvXBWRZaFMxBufik1a4RpFw4HhgVtBBWQeQgUj2cc= google.golang.org/genproto/googleapis/api v0.0.0-20241209162323-e6fa225c2576 h1:CkkIfIt50+lT6NHAVoRYEyAvQGFM7xEwXUUywFvEb3Q= google.golang.org/genproto/googleapis/api v0.0.0-20241209162323-e6fa225c2576/go.mod h1:1R3kvZ1dtP3+4p4d3G8uJ8rFk/fWlScl38vanWACI08= google.golang.org/genproto/googleapis/rpc v0.0.0-20241223144023-3abc09e42ca8 h1:TqExAhdPaB60Ux47Cn0oLV07rGnxZzIsaRhQaqS666A= google.golang.org/genproto/googleapis/rpc v0.0.0-20241223144023-3abc09e42ca8/go.mod h1:lcTa1sDdWEIHMWlITnIczmw5w60CF9ffkb8Z+DVmmjA= google.golang.org/grpc v1.67.3 h1:OgPcDAFKHnH8X3O4WcO4XUc8GRDeKsKReqbQtiCj7N8= google.golang.org/grpc v1.67.3/go.mod h1:YGaHCc6Oap+FzBJTZLBzkGSYt/cvGPFTPxkn7QfSU8s= gopkg.in/ini.v1 v1.67.0 h1:Dgnx+6+nfE+IfzjUEISNeydPJh9AXNNsWbGP9KzCsOA= gopkg.in/ini.v1 v1.67.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= ================================================ FILE: hack/lib.sh ================================================ #!/usr/bin/env bash set -euo pipefail #### Convenient IO methods ##### COLOR_RED='\033[0;31m' COLOR_ORANGE='\033[0;33m' COLOR_GREEN='\033[0;32m' COLOR_BLUE='\033[0;94m' COLOR_BOLD='\033[1m' COLOR_NONE='\033[0m' # No Color function log_error { >&2 echo -n -e "${COLOR_BOLD}${COLOR_RED}" >&2 echo "$@" >&2 echo -n -e "${COLOR_NONE}" } function log_warn { >&2 echo -n -e "${COLOR_ORANGE}" >&2 echo "$@" >&2 echo -n -e "${COLOR_NONE}" } function log_succ { >&2 echo -n -e "${COLOR_GREEN}" >&2 echo "$@" >&2 echo -n -e "${COLOR_NONE}" } function log_info { >&2 echo -n -e "${COLOR_BLUE}" >&2 echo "$@" >&2 echo -n -e "${COLOR_NONE}" } ================================================ FILE: hack/release_mod.sh ================================================ #!/usr/bin/env bash # Examples: # Add tags to all submodules with version vX.Y.Z # ./hack/release_mod.sh tags v0.1.0 set -euo pipefail source ./hack/lib.sh cmd="${1}" version="${2}" if [ -z "${version}" ]; then log_error "version argument is required" exit 2 fi go mod tidy dirs=$(find . -name "go.mod" -not -path "./docs/*" -exec dirname {} \;) function tags(){ log_info "Adding tags to all modules with version ${version}" log_info "" for dir in ${dirs}; do ( log_info "Processing ${dir}" prefix="${dir#./}" prefix="${prefix#.}" # if prefix is not empty, append a slash if [ -n "${prefix}" ]; then prefix="${prefix}/" fi # if prefix is empty, it means it's just the root module, do not handle it if [ -n "${prefix}" ]; then tag="${prefix}${version}" git tag "${tag}" log_succ " Tag ${tag}" fi ) done log_succ "" log_succ "Tags added, and push them manually" log_succ "Then tag main module with ${version}, and push it to trigger the release" } # run the function "${cmd}" ================================================ FILE: main.go ================================================ package main import ( "context" "os" "os/signal" surveyterm "github.com/AlecAivazis/survey/v2/terminal" "github.com/fatih/color" "github.com/go-faster/errors" "go.etcd.io/bbolt" "github.com/iyear/tdl/cmd" ) func main() { ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt) defer cancel() humanizeErrors := map[error]string{ bbolt.ErrTimeout: "Current database is used by another process, please terminate it first", surveyterm.InterruptErr: "Interrupted", } if err := cmd.New().ExecuteContext(ctx); err != nil { for e, m := range humanizeErrors { if errors.Is(err, e) { color.Red("%s", m) os.Exit(1) } } color.Red("Error: %+v", err) os.Exit(1) } } ================================================ FILE: pkg/clock/clock.go ================================================ package clock import ( "fmt" "time" "github.com/beevik/ntp" "github.com/gotd/td/clock" ) const defaultHost = "pool.ntp.org" type networkClock struct { offset time.Duration } func (n *networkClock) Now() time.Time { return time.Now().Add(n.offset) } func (n *networkClock) Timer(d time.Duration) clock.Timer { return clock.System.Timer(d) } func (n *networkClock) Ticker(d time.Duration) clock.Ticker { return clock.System.Ticker(d) } // New default ntp host is 'pool.ntp.org' func New(ntpHost ...string) (clock.Clock, error) { var host string switch len(ntpHost) { case 0: host = defaultHost case 1: host = ntpHost[0] default: return nil, fmt.Errorf("too many ntp hosts") } resp, err := ntp.Query(host) if err != nil { return nil, err } return &networkClock{ offset: resp.ClockOffset, }, nil } ================================================ FILE: pkg/consts/consts.go ================================================ package consts import ( "os" "path/filepath" ) func init() { dir, err := os.UserHomeDir() if err != nil { panic(err) } HomeDir = dir DataDir = filepath.Join(dir, ".tdl") LogPath = filepath.Join(DataDir, "log") ExtensionsPath = filepath.Join(DataDir, "extensions") ExtensionsDataPath = filepath.Join(ExtensionsPath, "data") for _, p := range []string{DataDir, ExtensionsPath, ExtensionsDataPath} { if err = os.MkdirAll(p, 0o755); err != nil { panic(err) } } } ================================================ FILE: pkg/consts/flag.go ================================================ package consts const ( FlagStorage = "storage" FlagProxy = "proxy" FlagNamespace = "ns" FlagDebug = "debug" FlagPartSize = "size" // Deprecated: all part size should be set to maximum by default FlagThreads = "threads" FlagLimit = "limit" FlagPoolSize = "pool" FlagDelay = "delay" FlagNTP = "ntp" FlagReconnectTimeout = "reconnect-timeout" FlagDlTemplate = "template" ) ================================================ FILE: pkg/consts/path.go ================================================ package consts var ( HomeDir string DataDir string LogPath string ExtensionsPath string ExtensionsDataPath string UploadThumbExt = ".thumb" ) ================================================ FILE: pkg/consts/version.go ================================================ package consts // vars below are set by '-X' flag var ( Version = "dev" Commit = "unknown" CommitDate = "unknown" ) ================================================ FILE: pkg/extensions/extensions.go ================================================ package extensions import ( "context" "path/filepath" "strings" ) //go:generate go-enum --values --names --flag --nocase const Prefix = "tdl-" // ExtensionType ENUM(github, local) type ExtensionType string type Extension interface { Type() ExtensionType Name() string // Extension Name without tdl- prefix Path() string // Path to executable URL() string Owner() string CurrentVersion() string LatestVersion(ctx context.Context) string UpdateAvailable(ctx context.Context) bool } type baseExtension struct { path string } func (e baseExtension) Name() string { s := strings.TrimPrefix(filepath.Base(e.path), Prefix) s = strings.TrimSuffix(s, filepath.Ext(s)) return s } func (e baseExtension) Path() string { return e.path } type manifest struct { Owner string `json:"owner,omitempty"` Repo string `json:"repo,omitempty"` Tag string `json:"tag,omitempty"` } ================================================ FILE: pkg/extensions/extensions_enum.go ================================================ // Code generated by go-enum DO NOT EDIT. // Version: 0.5.8 // Revision: 3d844c8ecc59661ed7aa17bfd65727bc06a60ad8 // Build Date: 2023-09-18T14:55:21Z // Built By: goreleaser package extensions import ( "fmt" "strings" ) const ( // ExtensionTypeGithub is a ExtensionType of type github. ExtensionTypeGithub ExtensionType = "github" // ExtensionTypeLocal is a ExtensionType of type local. ExtensionTypeLocal ExtensionType = "local" ) var ErrInvalidExtensionType = fmt.Errorf("not a valid ExtensionType, try [%s]", strings.Join(_ExtensionTypeNames, ", ")) var _ExtensionTypeNames = []string{ string(ExtensionTypeGithub), string(ExtensionTypeLocal), } // ExtensionTypeNames returns a list of possible string values of ExtensionType. func ExtensionTypeNames() []string { tmp := make([]string, len(_ExtensionTypeNames)) copy(tmp, _ExtensionTypeNames) return tmp } // ExtensionTypeValues returns a list of the values for ExtensionType func ExtensionTypeValues() []ExtensionType { return []ExtensionType{ ExtensionTypeGithub, ExtensionTypeLocal, } } // String implements the Stringer interface. func (x ExtensionType) String() string { return string(x) } // IsValid provides a quick way to determine if the typed value is // part of the allowed enumerated values func (x ExtensionType) IsValid() bool { _, err := ParseExtensionType(string(x)) return err == nil } var _ExtensionTypeValue = map[string]ExtensionType{ "github": ExtensionTypeGithub, "local": ExtensionTypeLocal, } // ParseExtensionType attempts to convert a string to a ExtensionType. func ParseExtensionType(name string) (ExtensionType, error) { if x, ok := _ExtensionTypeValue[name]; ok { return x, nil } // Case insensitive parse, do a separate lookup to prevent unnecessary cost of lowercasing a string if we don't need to. if x, ok := _ExtensionTypeValue[strings.ToLower(name)]; ok { return x, nil } return ExtensionType(""), fmt.Errorf("%s is %w", name, ErrInvalidExtensionType) } // Set implements the Golang flag.Value interface func. func (x *ExtensionType) Set(val string) error { v, err := ParseExtensionType(val) *x = v return err } // Get implements the Golang flag.Getter interface func. func (x *ExtensionType) Get() interface{} { return *x } // Type implements the github.com/spf13/pFlag Value interface. func (x *ExtensionType) Type() string { return "ExtensionType" } ================================================ FILE: pkg/extensions/extensions_test.go ================================================ package extensions import ( "testing" "github.com/stretchr/testify/assert" ) func TestBaseExtension(t *testing.T) { tests := []struct { name string path string expectedName string }{ { name: "with prefix", path: "/path/to/tdl-extension", expectedName: "extension", }, { name: "without prefix", path: "/path/to/extension2", expectedName: "extension2", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { e := baseExtension{path: tt.path} assert.Equal(t, tt.expectedName, e.Name()) }) } } ================================================ FILE: pkg/extensions/github.go ================================================ package extensions import ( "context" "encoding/json" "fmt" "os" "path/filepath" "sync" "github.com/go-faster/errors" "github.com/google/go-github/v62/github" ) const ( githubHost = "github.com" manifestName = "manifest.json" ) type githubExtension struct { baseExtension client *github.Client mu sync.RWMutex // lazy loaded mf *manifest latestVersion string } func (e *githubExtension) Type() ExtensionType { return ExtensionTypeGithub } func (e *githubExtension) URL() string { if mf, err := e.loadManifest(); err == nil { return fmt.Sprintf("https://%s/%s/%s", githubHost, mf.Owner, mf.Repo) } return "" } func (e *githubExtension) Owner() string { if mf, err := e.loadManifest(); err == nil { return mf.Owner } return "" } func (e *githubExtension) CurrentVersion() string { if mf, err := e.loadManifest(); err == nil { return mf.Tag } return "" } func (e *githubExtension) LatestVersion(ctx context.Context) string { e.mu.RLock() if e.latestVersion != "" { defer e.mu.RUnlock() return e.latestVersion } e.mu.RUnlock() mf, err := e.loadManifest() if err != nil { return "" } release, _, err := e.client.Repositories.GetLatestRelease(ctx, mf.Owner, mf.Repo) if err != nil { return "" } e.mu.Lock() e.latestVersion = release.GetTagName() e.mu.Unlock() return e.latestVersion } func (e *githubExtension) loadManifest() (*manifest, error) { e.mu.RLock() if e.mf != nil { defer e.mu.RUnlock() return e.mf, nil } e.mu.RUnlock() dir, _ := filepath.Split(e.Path()) manifestPath := filepath.Join(dir, manifestName) var mfb []byte mfb, err := os.ReadFile(manifestPath) if err != nil { return nil, errors.Wrapf(err, "read manifest file %s", manifestPath) } mf := manifest{} if err = json.Unmarshal(mfb, &mf); err != nil { return nil, errors.Wrapf(err, "unmarshal manifest file %s", manifestPath) } e.mu.Lock() e.mf = &mf e.mu.Unlock() return e.mf, nil } func (e *githubExtension) UpdateAvailable(ctx context.Context) bool { if e.CurrentVersion() == "" || e.LatestVersion(ctx) == "" || e.CurrentVersion() == e.LatestVersion(ctx) { return false } return true } ================================================ FILE: pkg/extensions/local.go ================================================ package extensions import ( "context" "fmt" ) type localExtension struct { baseExtension } func (l *localExtension) Type() ExtensionType { return ExtensionTypeLocal } func (l *localExtension) URL() string { return fmt.Sprintf("file://%s", l.Path()) } func (l *localExtension) Owner() string { return "local" } func (l *localExtension) CurrentVersion() string { return "" } func (l *localExtension) LatestVersion(_ context.Context) string { return "" } func (l *localExtension) UpdateAvailable(_ context.Context) bool { return false } ================================================ FILE: pkg/extensions/local_test.go ================================================ package extensions import ( "context" "testing" "github.com/stretchr/testify/assert" ) func TestLocalExtension(t *testing.T) { tests := []struct { name string ext *localExtension expectedURL string }{ { name: "local 1", ext: &localExtension{ baseExtension: baseExtension{path: "/path/to/local"}, }, expectedURL: "file:///path/to/local", }, { name: "local 2", ext: &localExtension{ baseExtension: baseExtension{path: "/path/to/local2"}, }, expectedURL: "file:///path/to/local2", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { assert.Equal(t, tt.expectedURL, tt.ext.URL()) assert.Equal(t, "local", tt.ext.Owner()) assert.Equal(t, "", tt.ext.CurrentVersion()) assert.Equal(t, "", tt.ext.LatestVersion(context.TODO())) assert.False(t, tt.ext.UpdateAvailable(context.TODO())) }) } } ================================================ FILE: pkg/extensions/manager.go ================================================ package extensions import ( "context" "encoding/json" "fmt" "io" "net/http" "os" "os/exec" "path/filepath" "runtime" "runtime/debug" "strings" "sync" "github.com/go-faster/errors" "github.com/google/go-github/v62/github" "go.uber.org/multierr" "github.com/iyear/tdl/extension" ) var ( ErrAlreadyUpToDate = errors.New("already up to date") ErrOnlyGitHub = errors.New("only GitHub extension can be upgraded by tdl") ) type Manager struct { dir string http *http.Client github *github.Client dryRun bool } func NewManager(dir string) *Manager { return &Manager{ dir: dir, http: http.DefaultClient, github: newGhClient(http.DefaultClient), dryRun: false, } } func newGhClient(c *http.Client) *github.Client { ghToken := os.Getenv("GITHUB_TOKEN") if ghToken == "" { return github.NewClient(c) } return github.NewClient(c).WithAuthToken(ghToken) } func (m *Manager) SetDryRun(v bool) { m.dryRun = v } func (m *Manager) DryRun() bool { return m.dryRun } func (m *Manager) SetClient(client *http.Client) { m.http = client m.github = newGhClient(client) } func (m *Manager) Dispatch(ext Extension, args []string, env *extension.Env, stdin io.Reader, stdout, stderr io.Writer) (rerr error) { cmd := exec.Command(ext.Path(), args...) envFile, err := os.CreateTemp("", "*") if err != nil { return errors.Wrap(err, "create temp") } defer func() { multierr.AppendInto(&rerr, os.Remove(envFile.Name())) }() envBytes, err := json.Marshal(env) if err != nil { return errors.Wrap(err, "marshal env") } if _, err = envFile.Write(envBytes); err != nil { return errors.Wrap(err, "write env to temp") } if err = envFile.Close(); err != nil { return errors.Wrap(err, "close env file") } cmd.Env = append(os.Environ(), fmt.Sprintf("%s=%s", extension.EnvKey, envFile.Name())) cmd.Args = append([]string{Prefix + ext.Name()}, args...) // reset args[0] to extension name instead of binary path cmd.Stdin = stdin cmd.Stdout = stdout cmd.Stderr = stderr return cmd.Run() } func (m *Manager) List(ctx context.Context, includeLatestVersion bool) ([]Extension, error) { entries, err := os.ReadDir(m.dir) if err != nil { return nil, errors.Wrap(err, "read dir entries") } extensions := make([]Extension, 0, len(entries)) for _, f := range entries { if !strings.HasPrefix(f.Name(), Prefix) { continue } if !f.IsDir() { continue } if _, err = os.Stat(filepath.Join(m.dir, f.Name(), manifestName)); err == nil { extensions = append(extensions, &githubExtension{ baseExtension: baseExtension{path: filepath.Join(m.dir, f.Name(), f.Name())}, client: m.github, }) } else { extensions = append(extensions, &localExtension{ baseExtension: baseExtension{path: filepath.Join(m.dir, f.Name(), f.Name())}, }) } } if includeLatestVersion { m.populateLatestVersions(ctx, extensions) } return extensions, nil } // Upgrade only GitHub extension can be upgraded func (m *Manager) Upgrade(ctx context.Context, ext Extension) error { switch e := ext.(type) { case *githubExtension: if !ext.UpdateAvailable(ctx) { return ErrAlreadyUpToDate } mf, err := e.loadManifest() if err != nil { return errors.Wrapf(err, "load manifest of %q", e.Name()) } if !m.dryRun { if err = m.Remove(ext); err != nil { return errors.Wrapf(err, "remove old version extension") } if err = m.installGitHub(ctx, mf.Owner, mf.Repo, false); err != nil { return errors.Wrapf(err, "install GitHub extension %q", e.Name()) } } return nil default: return ErrOnlyGitHub } } // Install installs an extension by target. // Valid targets are: // - GitHub: owner/repo // - Local: path to executable. func (m *Manager) Install(ctx context.Context, target string, force bool) error { // local if _, err := os.Stat(target); err == nil { return m.installLocal(target, force) } // github ownerRepo := strings.Split(target, "/") if len(ownerRepo) != 2 { return errors.Errorf("invalid target: %q", target) } return m.installGitHub(ctx, ownerRepo[0], ownerRepo[1], force) } func (m *Manager) installLocal(path string, force bool) error { src, err := os.Lstat(path) if err != nil { return errors.Wrap(err, "source extension stat") } if !src.Mode().IsRegular() { return errors.Errorf("invalid src extension: %q, only regular file is allowed", path) } name := src.Name() if !strings.HasPrefix(name, Prefix) { name = Prefix + name } targetDir := filepath.Join(m.dir, strings.TrimSuffix(name, filepath.Ext(name))) binPath := filepath.Join(targetDir, name) if err = m.maybeExist(binPath, force); err != nil { return err } if !m.dryRun { if err = os.MkdirAll(targetDir, 0o755); err != nil { return errors.Wrapf(err, "create target dir %q for extension %q", targetDir, name) } if err = copyRegularFile(path, binPath); err != nil { return errors.Wrapf(err, "install local extension: %q", path) } } return nil } func (m *Manager) installGitHub(ctx context.Context, owner, repo string, force bool) (rerr error) { if !strings.HasPrefix(repo, Prefix) { return errors.Errorf("invalid repo name: %q, should start with %q", repo, Prefix) } platform, ext := platformBinaryName() targetDir := filepath.Join(m.dir, repo) binPath := filepath.Join(targetDir, repo) + ext if err := m.maybeExist(binPath, force); err != nil { return err } release, _, err := m.github.Repositories.GetLatestRelease(ctx, owner, repo) if err != nil { return errors.Wrapf(err, "get latest release of %s/%s", owner, repo) } // match binary name var asset *github.ReleaseAsset for _, a := range release.Assets { if strings.HasSuffix(a.GetName(), platform+ext) { asset = a break } } if asset == nil { return errors.Errorf("no matched binary(%s) found in the release(%s)", platform+ext, release.GetHTMLURL()) } if !m.dryRun { if err = os.MkdirAll(targetDir, 0o755); err != nil { return errors.Wrapf(err, "create target dir %q for extension %s/%s", targetDir, owner, repo) } if err = m.downloadGitHubAsset(ctx, owner, repo, asset, binPath); err != nil { return errors.Wrapf(err, "download github asset %s", asset.GetBrowserDownloadURL()) } } mf := &manifest{ Owner: owner, Repo: repo, Tag: release.GetTagName(), } mfb, err := json.Marshal(mf) if err != nil { return errors.Wrap(err, "marshal manifest") } if !m.dryRun { if err = os.WriteFile(filepath.Join(targetDir, manifestName), mfb, 0o644); err != nil { return errors.Wrapf(err, "write manifest to %s", targetDir) } } return nil } func (m *Manager) maybeExist(binPath string, force bool) error { targetDir := filepath.Dir(binPath) extName := filepath.Base(targetDir) if _, err := os.Lstat(binPath); err != nil { return nil } if !force { return errors.Errorf("extension already exists, please remove it first") } // force remove if !m.dryRun { if err := os.RemoveAll(targetDir); err != nil { return errors.Wrapf(err, "remove existing extension %q", extName) } } return nil } // Remove removes an extension by name(without prefix). func (m *Manager) Remove(ext Extension) error { target := Prefix + ext.Name() targetDir := filepath.Join(m.dir, target) if _, err := os.Lstat(targetDir); os.IsNotExist(err) { return errors.Errorf("no extension found: %s", targetDir) } if !m.dryRun { return os.RemoveAll(targetDir) } return nil } func (m *Manager) populateLatestVersions(ctx context.Context, exts []Extension) { wg := &sync.WaitGroup{} for _, ext := range exts { wg.Add(1) go func(e Extension) { defer wg.Done() e.LatestVersion(ctx) }(ext) } wg.Wait() } func (m *Manager) downloadGitHubAsset(ctx context.Context, owner, repo string, asset *github.ReleaseAsset, dst string) (rerr error) { readCloser, _, err := m.github.Repositories.DownloadReleaseAsset(ctx, owner, repo, asset.GetID(), m.http) if err != nil { return errors.Wrapf(err, "download release asset %s", asset.GetName()) } defer multierr.AppendInvoke(&rerr, multierr.Close(readCloser)) file, err := os.OpenFile(dst, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o755) if err != nil { return errors.Wrapf(err, "open file %s", dst) } defer multierr.AppendInvoke(&rerr, multierr.Close(file)) if _, err = io.Copy(file, readCloser); err != nil { return errors.Wrapf(err, "copy http body to %s", dst) } return nil } func copyRegularFile(src, dst string) (rerr error) { r, err := os.Open(src) if err != nil { return errors.Wrapf(err, "open src %s", src) } defer multierr.AppendInvoke(&rerr, multierr.Close(r)) info, err := r.Stat() if err != nil { return errors.Wrapf(err, "stat file %s", src) } if !info.Mode().IsRegular() { return errors.Errorf("invalid source file: %q, only regular file is allowed", src) } w, err := os.OpenFile(dst, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0o666|info.Mode()&0o777) if err != nil { return errors.Wrapf(err, "open dst %s", dst) } defer multierr.AppendInvoke(&rerr, multierr.Close(w)) if _, err = io.Copy(w, r); err != nil { return errors.Wrapf(err, "copy file %s to %s", src, dst) } return nil } func platformBinaryName() (string, string) { ext := "" if runtime.GOOS == "windows" { ext = ".exe" } arch := runtime.GOARCH switch arch { case "arm": if goarm := extractGOARM(); goarm != "" { arch += "v" + goarm } } return fmt.Sprintf("%s-%s", runtime.GOOS, arch), ext } func extractGOARM() string { info, ok := debug.ReadBuildInfo() if !ok { return "" } for _, setting := range info.Settings { if setting.Key == "GOARM" { return setting.Value } } return "" } ================================================ FILE: pkg/filterMap/filterMap.go ================================================ package filterMap func New(data []string, keyFn func(key string) string) map[string]struct{} { m := make(map[string]struct{}) for _, v := range data { m[keyFn(v)] = struct{}{} } return m } ================================================ FILE: pkg/key/key.go ================================================ package key import ( "github.com/iyear/tdl/core/storage/keygen" ) func App() string { return keygen.New("app") } func Resume(fingerprint string) string { return keygen.New("resume", fingerprint) } ================================================ FILE: pkg/kv/bolt.go ================================================ package kv import ( "os" "path/filepath" "sync" "github.com/go-faster/errors" "github.com/mitchellh/mapstructure" "go.etcd.io/bbolt" "go.uber.org/multierr" "github.com/iyear/tdl/core/storage" "github.com/iyear/tdl/pkg/validator" ) func init() { register(DriverBolt, func(m map[string]any) (Storage, error) { return newBolt(m) }) } type bolt struct { path string dbs map[string]*bbolt.DB mu *sync.Mutex } func newBolt(opts map[string]any) (*bolt, error) { type options struct { Path string `validate:"required" mapstructure:"path"` } var o options if err := mapstructure.WeakDecode(opts, &o); err != nil { return nil, errors.Wrap(err, "decode options") } if err := validator.Struct(&o); err != nil { return nil, errors.Wrap(err, "validate options") } if err := os.MkdirAll(o.Path, 0o755); err != nil { return nil, errors.Wrap(err, "create dir") } return &bolt{ path: o.Path, dbs: make(map[string]*bbolt.DB), mu: &sync.Mutex{}, }, nil } func (b *bolt) Name() string { return DriverBolt.String() } func (b *bolt) MigrateTo() (Meta, error) { meta := make(Meta) if err := b.walk(func(path string) (rerr error) { ns := filepath.Base(path) meta[ns] = make(map[string][]byte) db, err := b.open(ns) if err != nil { return errors.Wrap(err, "open") } return db.db.View(func(tx *bbolt.Tx) error { return tx.Bucket(db.ns).ForEach(func(k, v []byte) error { meta[ns][string(k)] = v return nil }) }) }); err != nil { return nil, errors.Wrap(err, "walk") } return meta, nil } func (b *bolt) MigrateFrom(meta Meta) error { for ns, pairs := range meta { db, err := b.open(ns) if err != nil { return errors.Wrap(err, "open") } if err = db.db.Update(func(tx *bbolt.Tx) error { bk, err := tx.CreateBucketIfNotExists(db.ns) if err != nil { return errors.Wrap(err, "create bucket") } for key, value := range pairs { if err = bk.Put([]byte(key), value); err != nil { return errors.Wrap(err, "put") } } return nil }); err != nil { return errors.Wrap(err, "update") } } return nil } func (b *bolt) Namespaces() ([]string, error) { namespaces := make([]string, 0) if err := b.walk(func(path string) error { namespaces = append(namespaces, filepath.Base(path)) return nil }); err != nil { return nil, errors.Wrap(err, "walk") } return namespaces, nil } func (b *bolt) walk(fn func(path string) error) error { return filepath.Walk(b.path, func(path string, info os.FileInfo, err error) error { if err != nil { return errors.Wrap(err, "walk") } if info.IsDir() { return nil } return fn(path) }) } func (b *bolt) Open(ns string) (storage.Storage, error) { return b.open(ns) } func (b *bolt) open(ns string) (*legacyKV, error) { if ns == "" { return nil, errors.New("namespace is required") } b.mu.Lock() defer b.mu.Unlock() if db, ok := b.dbs[ns]; ok { return &legacyKV{db: db, ns: []byte(ns)}, nil } db, err := bbolt.Open(filepath.Join(b.path, ns), os.ModePerm, boltOptions) if err != nil { return nil, errors.Wrap(err, "open db") } if err = db.Update(func(tx *bbolt.Tx) error { _, err := tx.CreateBucketIfNotExists([]byte(ns)) return err }); err != nil { return nil, errors.Wrap(err, "create bucket") } b.dbs[ns] = db return &legacyKV{db: db, ns: []byte(ns)}, nil } func (b *bolt) Close() error { b.mu.Lock() defer b.mu.Unlock() var err error for _, db := range b.dbs { err = multierr.Append(err, db.Close()) } return err } ================================================ FILE: pkg/kv/file.go ================================================ package kv import ( "context" "encoding/json" "os" "path/filepath" "sync" "github.com/go-faster/errors" "github.com/mitchellh/mapstructure" "github.com/iyear/tdl/core/storage" "github.com/iyear/tdl/pkg/validator" ) func init() { register(DriverFile, newFile) } type file struct { path string mu sync.Mutex } func newFile(opts map[string]any) (Storage, error) { type options struct { Path string `validate:"required" mapstructure:"path"` } var o options if err := mapstructure.WeakDecode(opts, &o); err != nil { return nil, errors.Wrap(err, "decode options") } if err := validator.Struct(&o); err != nil { return nil, errors.Wrap(err, "validate options") } _, err := os.Stat(o.Path) if err == nil { return &file{path: o.Path}, nil } if !os.IsNotExist(err) { return nil, errors.Wrap(err, "stat file") } if err = os.MkdirAll(filepath.Dir(o.Path), 0o755); err != nil { return nil, errors.Wrap(err, "create file directory") } if err = os.WriteFile(o.Path, []byte("{}"), 0o644); err != nil { return nil, errors.Wrap(err, "create file") } return &file{path: o.Path}, nil } func (f *file) Name() string { return DriverFile.String() } func (f *file) MigrateTo() (Meta, error) { meta, err := f.read() if err != nil { return nil, errors.Wrap(err, "read") } return meta, nil } func (f *file) MigrateFrom(meta Meta) error { return f.write(meta) } func (f *file) Namespaces() ([]string, error) { pairs, err := f.read() if err != nil { return nil, errors.Wrap(err, "read") } namespaces := make([]string, 0, len(pairs)) for ns := range pairs { namespaces = append(namespaces, ns) } return namespaces, nil } func (f *file) Open(ns string) (storage.Storage, error) { if ns == "" { return nil, errors.New("namespace is required") } read, err := f.read() if err != nil { return nil, errors.Wrap(err, "read") } if _, ok := read[ns]; !ok { read[ns] = make(map[string][]byte) if err = f.write(read); err != nil { return nil, errors.Wrap(err, "write") } } return &fileKV{f: f, ns: ns}, nil } func (f *file) Close() error { return nil } func (f *file) read() (map[string]map[string][]byte, error) { f.mu.Lock() defer f.mu.Unlock() bytes, err := os.ReadFile(f.path) if err != nil { return nil, err } m := make(map[string]map[string][]byte) if err = json.Unmarshal(bytes, &m); err != nil { return nil, err } return m, nil } func (f *file) write(m map[string]map[string][]byte) error { f.mu.Lock() defer f.mu.Unlock() bytes, err := json.Marshal(m) if err != nil { return err } return os.WriteFile(f.path, bytes, 0o644) } type fileKV struct { f *file ns string } func (f *fileKV) Get(_ context.Context, key string) ([]byte, error) { m, err := f.f.read() if err != nil { return nil, errors.Wrap(err, "read") } if v, ok := m[f.ns][key]; ok { return v, nil } return nil, storage.ErrNotFound } func (f *fileKV) Set(_ context.Context, key string, value []byte) error { m, err := f.f.read() if err != nil { return errors.Wrap(err, "read") } m[f.ns][key] = value return f.f.write(m) } func (f *fileKV) Delete(_ context.Context, key string) error { m, err := f.f.read() if err != nil { return errors.Wrap(err, "read") } delete(m[f.ns], key) return f.f.write(m) } ================================================ FILE: pkg/kv/kv.go ================================================ package kv import ( "context" "io" "github.com/go-faster/errors" "github.com/iyear/tdl/core/storage" ) //go:generate go-enum --values --names --flag --nocase // Driver // ENUM(legacy, bolt, file) type Driver string const DriverTypeKey = "type" type Meta map[string]map[string][]byte // namespace, key, value type Storage interface { Name() string MigrateTo() (Meta, error) MigrateFrom(Meta) error Namespaces() ([]string, error) Open(ns string) (storage.Storage, error) io.Closer } var drivers = map[Driver]func(map[string]any) (Storage, error){} func register(name Driver, fn func(map[string]any) (Storage, error)) { drivers[name] = fn } func New(driver Driver, opts map[string]any) (Storage, error) { if fn, ok := drivers[driver]; ok { return fn(opts) } return nil, errors.Errorf("unsupported driver: %s", driver) } func NewWithMap(o map[string]string) (Storage, error) { driver, err := ParseDriver(o[DriverTypeKey]) if err != nil { return nil, errors.Wrap(err, "parse driver") } opts := make(map[string]any) for k, v := range o { if k == DriverTypeKey { continue } opts[k] = v } return New(driver, opts) } type ctxKey struct{} func With(ctx context.Context, kv Storage) context.Context { return context.WithValue(ctx, ctxKey{}, kv) } func From(ctx context.Context) Storage { return ctx.Value(ctxKey{}).(Storage) } ================================================ FILE: pkg/kv/kv_enum.go ================================================ // Code generated by go-enum DO NOT EDIT. // Version: 0.5.8 // Revision: 3d844c8ecc59661ed7aa17bfd65727bc06a60ad8 // Build Date: 2023-09-18T14:55:21Z // Built By: goreleaser package kv import ( "fmt" "strings" ) const ( // DriverLegacy is a Driver of type legacy. DriverLegacy Driver = "legacy" // DriverBolt is a Driver of type bolt. DriverBolt Driver = "bolt" // DriverFile is a Driver of type file. DriverFile Driver = "file" ) var ErrInvalidDriver = fmt.Errorf("not a valid Driver, try [%s]", strings.Join(_DriverNames, ", ")) var _DriverNames = []string{ string(DriverLegacy), string(DriverBolt), string(DriverFile), } // DriverNames returns a list of possible string values of Driver. func DriverNames() []string { tmp := make([]string, len(_DriverNames)) copy(tmp, _DriverNames) return tmp } // DriverValues returns a list of the values for Driver func DriverValues() []Driver { return []Driver{ DriverLegacy, DriverBolt, DriverFile, } } // String implements the Stringer interface. func (x Driver) String() string { return string(x) } // IsValid provides a quick way to determine if the typed value is // part of the allowed enumerated values func (x Driver) IsValid() bool { _, err := ParseDriver(string(x)) return err == nil } var _DriverValue = map[string]Driver{ "legacy": DriverLegacy, "bolt": DriverBolt, "file": DriverFile, } // ParseDriver attempts to convert a string to a Driver. func ParseDriver(name string) (Driver, error) { if x, ok := _DriverValue[name]; ok { return x, nil } // Case insensitive parse, do a separate lookup to prevent unnecessary cost of lowercasing a string if we don't need to. if x, ok := _DriverValue[strings.ToLower(name)]; ok { return x, nil } return Driver(""), fmt.Errorf("%s is %w", name, ErrInvalidDriver) } // Set implements the Golang flag.Value interface func. func (x *Driver) Set(val string) error { v, err := ParseDriver(val) *x = v return err } // Get implements the Golang flag.Getter interface func. func (x *Driver) Get() interface{} { return *x } // Type implements the github.com/spf13/pFlag Value interface. func (x *Driver) Type() string { return "Driver" } ================================================ FILE: pkg/kv/kv_test.go ================================================ package kv import ( "context" "fmt" "path/filepath" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func forEachStorage(t *testing.T, fn func(e Storage, t *testing.T)) { storages := map[Driver]map[string]any{ DriverBolt: {"path": t.TempDir()}, DriverLegacy: {"path": filepath.Join(t.TempDir(), "test.db")}, DriverFile: {"path": filepath.Join(t.TempDir(), "test.json")}, } for driver, opts := range storages { storage, err := New(driver, opts) require.NoError(t, err) t.Run(driver.String(), func(t *testing.T) { fn(storage, t) }) assert.NoError(t, storage.Close()) } } func TestNew(t *testing.T) { tests := map[Driver][]struct { name string opts map[string]any wantErr bool }{ DriverBolt: { {name: "valid", opts: map[string]any{"path": t.TempDir()}, wantErr: false}, {name: "invalid", opts: map[string]any{"path": ""}, wantErr: true}, }, DriverLegacy: { {name: "valid", opts: map[string]any{"path": filepath.Join(t.TempDir(), "test.db")}, wantErr: false}, {name: "invalid", opts: map[string]any{"path": ""}, wantErr: true}, }, DriverFile: { {name: "valid", opts: map[string]any{"path": filepath.Join(t.TempDir(), "test.json")}, wantErr: false}, }, Driver("unknown"): { {name: "unknown", opts: map[string]any{"path": ""}, wantErr: true}, }, } for driver, tests := range tests { for _, tt := range tests { t.Run(fmt.Sprintf("%v/%s", driver, tt.name), func(t *testing.T) { kv, err := New(driver, tt.opts) if tt.wantErr { assert.Error(t, err) assert.Nil(t, kv) } else { assert.NoError(t, err) assert.NotNil(t, kv) assert.NoError(t, kv.Close()) } }) } } } func TestStorage_Open(t *testing.T) { forEachStorage(t, func(e Storage, t *testing.T) { for _, ns := range []string{"foo", "bar", "foo"} { kv, err := e.Open(ns) require.NoError(t, err) require.NotNil(t, kv) } }) } func TestStorage_Namespaces(t *testing.T) { namespaces := []string{"foo", "bar", "baz"} forEachStorage(t, func(e Storage, t *testing.T) { for _, ns := range namespaces { kv, err := e.Open(ns) require.NoError(t, err) require.NotNil(t, kv) } ns, err := e.Namespaces() require.NoError(t, err) require.ElementsMatch(t, namespaces, ns) }) } func TestStorage_MigrateTo(t *testing.T) { meta := Meta{ "foo": { "1": []byte("2"), "3": []byte("4"), "5": []byte("6"), }, "bar": { "7": []byte("8"), "9": []byte("10"), "11": []byte("12"), }, } forEachStorage(t, func(e Storage, t *testing.T) { for ns, pairs := range meta { kv, err := e.Open(ns) require.NoError(t, err) require.NotNil(t, kv) for key, value := range pairs { require.NoError(t, kv.Set(context.TODO(), key, value)) } } m, err := e.MigrateTo() assert.NoError(t, err) assert.Equal(t, meta, m) }) } func TestStorage_MigrateFrom(t *testing.T) { meta := Meta{ "foo": { "1": []byte("2"), "3": []byte("4"), "5": []byte("6"), }, "bar": { "7": []byte("8"), "9": []byte("10"), "11": []byte("12"), }, } forEachStorage(t, func(e Storage, t *testing.T) { require.NoError(t, e.MigrateFrom(meta)) for ns, pairs := range meta { kv, err := e.Open(ns) require.NoError(t, err) require.NotNil(t, kv) for key, value := range pairs { v, err := kv.Get(context.TODO(), key) require.NoError(t, err) require.Equal(t, value, v) } } }) } ================================================ FILE: pkg/kv/legacy.go ================================================ package kv import ( "context" "os" "time" "github.com/go-faster/errors" "github.com/mitchellh/mapstructure" "go.etcd.io/bbolt" "github.com/iyear/tdl/core/storage" "github.com/iyear/tdl/pkg/validator" ) var boltOptions = &bbolt.Options{ Timeout: time.Second, NoGrowSync: false, FreelistType: bbolt.FreelistArrayType, } func init() { register(DriverLegacy, func(m map[string]any) (Storage, error) { return newLegacy(m) }) } func newLegacy(opts map[string]any) (*legacy, error) { type options struct { Path string `validate:"required" mapstructure:"path"` } var o options if err := mapstructure.WeakDecode(opts, &o); err != nil { return nil, errors.Wrap(err, "decode options") } if err := validator.Struct(&o); err != nil { return nil, errors.Wrap(err, "validate options") } db, err := bbolt.Open(o.Path, os.ModePerm, boltOptions) if err != nil { return nil, errors.Wrap(err, "open db") } return &legacy{bolt: db}, nil } type legacy struct { bolt *bbolt.DB } func (l *legacy) Name() string { return DriverLegacy.String() } func (l *legacy) MigrateTo() (Meta, error) { meta := make(Meta) if err := l.bolt.View(func(tx *bbolt.Tx) error { return tx.ForEach(func(name []byte, b *bbolt.Bucket) error { ns := string(name) meta[ns] = make(map[string][]byte) return b.ForEach(func(k, v []byte) error { meta[ns][string(k)] = v return nil }) }) }); err != nil { return nil, errors.Wrap(err, "iterate buckets") } return meta, nil } func (l *legacy) MigrateFrom(meta Meta) error { return l.bolt.Update(func(tx *bbolt.Tx) error { for ns, pairs := range meta { b, err := tx.CreateBucketIfNotExists([]byte(ns)) if err != nil { return errors.Wrap(err, "create bucket") } for key, value := range pairs { if err = b.Put([]byte(key), value); err != nil { return errors.Wrap(err, "put") } } } return nil }) } func (l *legacy) Namespaces() ([]string, error) { namespaces := make([]string, 0) if err := l.bolt.View(func(tx *bbolt.Tx) error { return tx.ForEach(func(name []byte, _ *bbolt.Bucket) error { namespaces = append(namespaces, string(name)) return nil }) }); err != nil { return nil, errors.Wrap(err, "iterate namespaces") } return namespaces, nil } func (l *legacy) Open(ns string) (storage.Storage, error) { return l.open(ns) } func (l *legacy) open(ns string) (*legacyKV, error) { if ns == "" { return nil, errors.New("namespace is required") } if err := l.bolt.Update(func(tx *bbolt.Tx) error { _, err := tx.CreateBucketIfNotExists([]byte(ns)) return err }); err != nil { return nil, errors.Wrap(err, "create bucket") } return &legacyKV{db: l.bolt, ns: []byte(ns)}, nil } func (l *legacy) Close() error { return l.bolt.Close() } type legacyKV struct { db *bbolt.DB ns []byte } func (l *legacyKV) Get(_ context.Context, key string) ([]byte, error) { var val []byte if err := l.db.View(func(tx *bbolt.Tx) error { val = tx.Bucket(l.ns).Get([]byte(key)) return nil }); err != nil { return nil, err } if val == nil { return nil, storage.ErrNotFound } return val, nil } func (l *legacyKV) Set(_ context.Context, key string, value []byte) error { return l.db.Update(func(tx *bbolt.Tx) error { return tx.Bucket(l.ns).Put([]byte(key), value) }) } func (l *legacyKV) Delete(_ context.Context, key string) error { return l.db.Update(func(tx *bbolt.Tx) error { return tx.Bucket(l.ns).Delete([]byte(key)) }) } ================================================ FILE: pkg/prog/prog.go ================================================ package prog import ( "context" "time" "github.com/fatih/color" "github.com/jedib0t/go-pretty/v6/progress" "github.com/jedib0t/go-pretty/v6/text" tsize "github.com/kopoli/go-terminal-size" ) func New(formatter progress.UnitsFormatter) progress.Writer { pw := progress.NewWriter() pw.SetAutoStop(false) width := 100 if size, err := tsize.GetSize(); err == nil { width = size.Width } width -= 50 // tail length pw.SetTrackerLength(width / 5) pw.SetMessageWidth(width * 3 / 5) pw.SetStyle(progress.StyleDefault) pw.SetTrackerPosition(progress.PositionRight) pw.SetUpdateFrequency(time.Millisecond * 100) pw.Style().Colors = progress.StyleColorsExample pw.Style().Colors.Message = text.Colors{text.FgBlue} pw.Style().Options.PercentFormat = "%4.1f%%" pw.Style().Visibility.TrackerOverall = true pw.Style().Visibility.ETA = true pw.Style().Visibility.ETAOverall = false pw.Style().Visibility.Speed = true pw.Style().Visibility.SpeedOverall = true pw.Style().Visibility.Pinned = true pw.Style().Options.TimeInProgressPrecision = time.Millisecond pw.Style().Options.SpeedOverallFormatter = formatter pw.Style().Options.ErrorString = color.RedString("failed!") pw.Style().Options.DoneString = color.GreenString("done!") return pw } func Wait(ctx context.Context, pw progress.Writer) { for pw.IsRenderInProgress() { select { case <-ctx.Done(): return default: if pw.LengthActive() == 0 { pw.Stop() } time.Sleep(10 * time.Millisecond) } } } ================================================ FILE: pkg/prog/tracker.go ================================================ package prog import ( "context" "strings" "time" "github.com/jedib0t/go-pretty/v6/progress" "github.com/iyear/tdl/pkg/ps" ) func AppendTracker(pw progress.Writer, formatter progress.UnitsFormatter, message string, total int64) *progress.Tracker { units := progress.UnitsBytes units.Formatter = formatter tracker := progress.Tracker{ Message: message, Total: total, Units: units, } pw.AppendTracker(&tracker) return &tracker } // EnablePS enables pinned messages with ps info: cpu, memory, goroutines func EnablePS(ctx context.Context, pw progress.Writer) { go func() { f := func() { pw.SetPinnedMessages(strings.Join(ps.Humanize(ctx), " ")) } f() ticker := time.NewTicker(time.Second) defer ticker.Stop() for { select { case <-ctx.Done(): pw.SetPinnedMessages() return case <-ticker.C: f() } } }() } ================================================ FILE: pkg/ps/ps.go ================================================ package ps import ( "context" "fmt" "os" "runtime" "github.com/shirou/gopsutil/v3/process" "github.com/iyear/tdl/pkg/utils" ) var proc *process.Process // Humanize returns human-readable string slice, containing cpu, memory and network info func Humanize(ctx context.Context) []string { str := make([]string, 0, 3) if cpu, err := GetSelfCPU(ctx); err == nil { str = append(str, fmt.Sprintf("CPU: %.2f%%", cpu)) } if mem, err := GetSelfMem(ctx); err == nil { str = append(str, fmt.Sprintf("Memory: %s", utils.Byte.FormatBinaryBytes(int64(mem.RSS)))) } str = append(str, fmt.Sprintf("Goroutines: %d", GetGoroutineNum())) return str } func init() { var err error proc, err = process.NewProcess(int32(os.Getpid())) if err != nil { panic(err) } } func GetSelfCPU(ctx context.Context) (float64, error) { cpu, err := proc.PercentWithContext(ctx, 0) if err != nil { return 0, err } return cpu, nil } // GetSelfMem returns self memory info func GetSelfMem(ctx context.Context) (*process.MemoryInfoStat, error) { m, err := proc.MemoryInfoWithContext(ctx) if err != nil { return nil, err } return m, nil } func GetGoroutineNum() int { return runtime.NumGoroutine() } ================================================ FILE: pkg/tclient/app.go ================================================ package tclient const ( AppBuiltin = "builtin" AppDesktop = "desktop" ) type App struct { AppID int AppHash string } var Apps = map[string]App{ // application created by iyear AppBuiltin: {AppID: 15055931, AppHash: "021d433426cbb920eeb95164498fe3d3"}, // application created by tdesktop. // https://opentele.readthedocs.io/en/latest/documentation/authorization/api/#class-telegramdesktop AppDesktop: {AppID: 2040, AppHash: "b18441a1ff607e10a989891a5462e627"}, } ================================================ FILE: pkg/tclient/tclient.go ================================================ package tclient import ( "context" "fmt" "time" "github.com/go-faster/errors" "github.com/gotd/td/telegram" "github.com/iyear/tdl/core/storage" "github.com/iyear/tdl/core/tclient" "github.com/iyear/tdl/pkg/key" ) type Options struct { KV storage.Storage Proxy string NTP string ReconnectTimeout time.Duration UpdateHandler telegram.UpdateHandler } func GetApp(kv storage.Storage) (App, error) { mode, err := kv.Get(context.TODO(), key.App()) if err != nil { mode = []byte(AppBuiltin) } app, ok := Apps[string(mode)] if !ok { return App{}, fmt.Errorf("can't find app: %s, please try re-login", mode) } return app, nil } func New(ctx context.Context, o Options, login bool, middlewares ...telegram.Middleware) (*telegram.Client, error) { app, err := GetApp(o.KV) if err != nil { return nil, errors.Wrap(err, "get app") } return tclient.New(ctx, tclient.Options{ AppID: app.AppID, AppHash: app.AppHash, Session: storage.NewSession(o.KV, login), Middlewares: middlewares, Proxy: o.Proxy, NTP: o.NTP, ReconnectTimeout: o.ReconnectTimeout, UpdateHandler: o.UpdateHandler, }) } ================================================ FILE: pkg/tdesktop/.s ================================================ ================================================ FILE: pkg/tdesktop/tdesktop.go ================================================ // Package tdesktop exports functions from github.com/gotd/td/session/tdesktop package package tdesktop import ( _ "unsafe" // for go:linkname _ "github.com/gotd/td/session/tdesktop" // for FileKey ) //go:linkname FileKey github.com/gotd/td/session/tdesktop.fileKey func FileKey(_ string) string ================================================ FILE: pkg/texpr/env.go ================================================ package texpr import ( "github.com/gotd/td/tg" "github.com/iyear/tdl/core/tmedia" "github.com/iyear/tdl/core/util/tutil" ) type EnvMessage struct { Mentioned bool `comment:"Whether we were mentioned in this message"` Silent bool `comment:"Whether this is a silent message (no notification triggered)"` FromScheduled bool `comment:"Whether this is a scheduled message"` Pinned bool `comment:"Whether this message is pinned"` ID int `comment:"ID of the message"` FromID int64 `comment:"ID of the sender of the message"` Date int `comment:"Date of the message"` Message string `comment:"The message"` Media EnvMessageMedia `comment:"Media attachment"` Views int `comment:"View count"` Forwards int `comment:"Forward count"` } type EnvMessageMedia struct { Name string `comment:"File name"` Size int64 `comment:"File size. Unit: Byte"` DC int `comment:"DC ID"` } func ConvertEnvMessage(msg *tg.Message) EnvMessage { m := EnvMessage{} if msg == nil { return m } m.Mentioned = msg.Mentioned m.Silent = msg.Silent m.FromScheduled = msg.FromScheduled m.Pinned = msg.Pinned m.ID = msg.ID m.FromID = tutil.GetPeerID(msg.FromID) m.Date = msg.Date m.Message = msg.Message if media, ok := tmedia.GetMedia(msg); ok { m.Media = EnvMessageMedia{ Name: media.Name, Size: media.Size, DC: media.DC, } } m.Views = msg.Views m.Forwards = msg.Forwards return m } ================================================ FILE: pkg/texpr/env_test.go ================================================ package texpr import ( "testing" "github.com/expr-lang/expr" ) func TestMessageExpr(t *testing.T) { msg := &EnvMessage{ Mentioned: true, Silent: false, FromScheduled: true, Pinned: false, ID: 100, FromID: 200, Date: 1684651590, Message: "Hello World", Media: EnvMessageMedia{Size: 10240, Name: "foo.zip", DC: 3}, Views: 200, Forwards: 100, } tests := []struct { name string expr string expected bool }{ { name: "and", expr: "Mentioned && ID==100 && Date>1684650000", expected: true, }, { name: "or", expr: "Mentioned || ID<1000 || Views>100", expected: true, }, { name: "match file name .zip extension", expr: `Media.Name matches ".*\\.zip"`, expected: true, }, { name: "match file name .zip extension2", expr: `Media.Name endsWith ".zip"`, expected: true, }, { name: "match file name and DC", expr: `Media.Name matches "foo*" && Media.DC==3`, expected: true, }, { name: "file name contains", expr: `Media.Name contains "foo"`, expected: true, }, { name: "match file size", expr: `Media.Size > 5*1024`, expected: true, }, { name: "false", expr: `Media.Size > 20*1024 || Media.DC==2 || Silent`, expected: false, }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { exp, err := expr.Compile(test.expr, expr.AsBool()) if err != nil { t.Fatal(err) } got, err := Run(exp, msg) if err != nil { t.Fatal(err) } if got != test.expected { t.Errorf("name: %s, expected: %v, got: %v", test.name, test.expected, got) } }) } } ================================================ FILE: pkg/texpr/expr.go ================================================ package texpr import ( "sync" "github.com/expr-lang/expr/vm" ) var vmPool = sync.Pool{New: func() any { return &vm.VM{} }} // TODO(iyear): function helpers func Run(program *vm.Program, env any) (any, error) { v := vmPool.Get().(*vm.VM) defer vmPool.Put(v) return v.Run(program, env) } ================================================ FILE: pkg/texpr/fields.go ================================================ package texpr import ( "fmt" "reflect" "strings" "github.com/fatih/color" ) type FieldsGetter struct { opts *Options } type Field struct { Path []string Type reflect.Type Comment string } type Options struct { tagName string } type Option func(opts *Options) func NewFieldsGetter(opts *Options) *FieldsGetter { if opts == nil { opts = &Options{ tagName: "comment", } } return &FieldsGetter{ opts: opts, } } func (f *FieldsGetter) Sprint(fields []*Field, colorable bool) string { b := &strings.Builder{} for _, field := range fields { path := strings.Join(field.Path, ".") if colorable { path = color.BlueString(path) } typ := field.Type.String() if colorable { typ = color.GreenString(typ) } comment := "# " + field.Comment if colorable { comment = color.MagentaString(comment) } fmt.Fprintf(b, "%s: %s %s\n", path, typ, comment) } return b.String() } func (f *FieldsGetter) Walk(v any) ([]*Field, error) { value := reflect.TypeOf(v) if value.Kind() != reflect.Struct && value.Elem().Kind() != reflect.Struct { return nil, fmt.Errorf("please input a struct") } fields := make([]*Field, 0) f.walk(value, &Field{}, &fields) return fields, nil } func (f *FieldsGetter) walk(v reflect.Type, field *Field, fields *[]*Field) { switch v.Kind() { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Float32, reflect.Float64, reflect.String, reflect.Bool, reflect.Map: field.Type = v *fields = append(*fields, field) case reflect.Struct: for i := 0; i < v.NumField(); i++ { fd := v.Field(i) if !fd.IsExported() { continue } f.walk(fd.Type, &Field{ Path: append(field.Path, fd.Name), Comment: fd.Tag.Get(f.opts.tagName), }, fields) } case reflect.Array, reflect.Slice: field.Path[len(field.Path)-1] += "[]" // note this is an array or slice f.walk(v.Elem(), field, fields) case reflect.Pointer: f.walk(v.Elem(), field, fields) default: // do nothing } } ================================================ FILE: pkg/texpr/fields_test.go ================================================ package texpr import ( "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestFieldsGetter(t *testing.T) { type T struct { F1 int `comment:"f1 comment"` F2 int8 `comment:"f2 comment"` F3 string `comment:"f3 comment"` F4 struct { F5 uint8 `comment:"f5 comment"` F6 uint16 `comment:"f6 comment"` F7 *struct { F8 string `comment:"f8 comment"` F9 map[string]string `comment:"f9 comment"` F10 [3]bool `comment:"f10 comment"` F11 []float32 `comment:"f11 comment"` F12 []struct { F13 int `comment:"f13 comment"` } } } } fg := NewFieldsGetter(nil) fields, err := fg.Walk(&T{}) require.NoError(t, err) expected := `F1: int # f1 comment F2: int8 # f2 comment F3: string # f3 comment F4.F5: uint8 # f5 comment F4.F6: uint16 # f6 comment F4.F7.F8: string # f8 comment F4.F7.F9: map[string]string # f9 comment F4.F7.F10[]: bool # f10 comment F4.F7.F11[]: float32 # f11 comment F4.F7.F12[].F13: int # f13 comment ` assert.Equal(t, expected, fg.Sprint(fields, false)) } ================================================ FILE: pkg/tmessage/files.go ================================================ package tmessage import ( "context" "errors" "io" "os" "strconv" "github.com/bcicen/jstream" "github.com/gotd/td/telegram/peers" "github.com/gotd/td/tg" "github.com/mitchellh/mapstructure" "go.uber.org/zap" "github.com/iyear/tdl/core/dcpool" "github.com/iyear/tdl/core/logctx" "github.com/iyear/tdl/core/storage" "github.com/iyear/tdl/core/util/tutil" ) const ( keyID = "id" typeMessage = "message" ) type fMessage struct { ID int `mapstructure:"id"` Type string `mapstructure:"type"` Time string `mapstructure:"date_unixtime"` File string `mapstructure:"file"` Photo string `mapstructure:"photo"` FromID string `mapstructure:"from_id"` From string `mapstructure:"from"` Text interface{} `mapstructure:"text"` } func FromFile(ctx context.Context, pool dcpool.Pool, kvd storage.Storage, files []string, onlyMedia bool) ParseSource { return func() ([]*Dialog, error) { dialogs := make([]*Dialog, 0, len(files)) for _, file := range files { d, err := parseFile(ctx, pool.Default(ctx), kvd, file, onlyMedia) if err != nil { return nil, err } logctx.From(ctx).Debug("Parse file", zap.String("file", file), zap.Int("num", len(d.Messages))) dialogs = append(dialogs, d) } return dialogs, nil } } func parseFile(ctx context.Context, client *tg.Client, kvd storage.Storage, file string, onlyMedia bool) (*Dialog, error) { f, err := os.Open(file) if err != nil { return nil, err } defer func(f *os.File) { _ = f.Close() }(f) peer, err := getChatInfo(ctx, client, kvd, f) if err != nil { return nil, err } logctx.From(ctx).Debug("Got peer info", zap.Int64("id", peer.ID()), zap.String("name", peer.VisibleName())) if _, err = f.Seek(0, io.SeekStart); err != nil { return nil, err } return collect(ctx, f, peer, onlyMedia) } func collect(ctx context.Context, r io.Reader, peer peers.Peer, onlyMedia bool) (*Dialog, error) { d := jstream.NewDecoder(r, 2) m := &Dialog{ Peer: peer.InputPeer(), Messages: make([]int, 0), } for mv := range d.Stream() { select { case <-ctx.Done(): return nil, ctx.Err() default: fm := fMessage{} if mv.ValueType != jstream.Object { continue } if err := mapstructure.WeakDecode(mv.Value, &fm); err != nil { return nil, err } if fm.ID < 0 || fm.Type != typeMessage { continue } if fm.File == "" && fm.Photo == "" && onlyMedia { continue } m.Messages = append(m.Messages, fm.ID) } } return m, nil } func getChatInfo(ctx context.Context, client *tg.Client, kvd storage.Storage, r io.Reader) (peers.Peer, error) { d := jstream.NewDecoder(r, 1).EmitKV() chatID := int64(0) for mv := range d.Stream() { _kv, ok := mv.Value.(jstream.KV) if !ok { continue } if _kv.Key == keyID { chatID = int64(_kv.Value.(float64)) } if chatID != 0 { break } } if chatID == 0 { return nil, errors.New("can't get chat type or chat id") } manager := peers.Options{Storage: storage.NewPeers(kvd)}.Build(client) return tutil.GetInputPeer(ctx, manager, strconv.FormatInt(chatID, 10)) } ================================================ FILE: pkg/tmessage/tmessage.go ================================================ package tmessage import ( "github.com/gotd/td/tg" ) type Dialog struct { Peer tg.InputPeerClass Messages []int } type ParseSource func() ([]*Dialog, error) func Parse(src ParseSource) ([]*Dialog, error) { return src() } ================================================ FILE: pkg/tmessage/urls.go ================================================ package tmessage import ( "context" "github.com/gotd/td/telegram/peers" "go.uber.org/zap" "github.com/iyear/tdl/core/dcpool" "github.com/iyear/tdl/core/logctx" "github.com/iyear/tdl/core/storage" "github.com/iyear/tdl/core/util/tutil" ) func FromURL(ctx context.Context, pool dcpool.Pool, kvd storage.Storage, urls []string) ParseSource { return func() ([]*Dialog, error) { manager := peers.Options{Storage: storage.NewPeers(kvd)}. Build(pool.Default(ctx)) msgMap := make(map[int64]*Dialog) for _, u := range urls { ch, msgid, err := tutil.ParseMessageLink(ctx, manager, u) if err != nil { return nil, err } logctx.From(ctx).Debug("Parse URL", zap.String("url", u), zap.Int64("peer_id", ch.ID()), zap.String("peer_name", ch.VisibleName()), zap.Int("msg", msgid)) // init map value if _, ok := msgMap[ch.ID()]; !ok { msgMap[ch.ID()] = &Dialog{Peer: ch.InputPeer(), Messages: []int{}} } msgMap[ch.ID()].Messages = append(msgMap[ch.ID()].Messages, msgid) } // cap is at least len of map msgs := make([]*Dialog, 0, len(msgMap)) for _, m := range msgMap { msgs = append(msgs, m) } return msgs, nil } } ================================================ FILE: pkg/tpath/tpath.go ================================================ package tpath const AppName = "Telegram Desktop" type desktop struct{} var Desktop = desktop{} // AppData returns possible paths of Telegram Desktop's data directory based on the current platform. func (desktop) AppData(homedir string) []string { return desktopAppData(homedir) } ================================================ FILE: pkg/tpath/tpath_darwin.go ================================================ //go:build darwin package tpath import ( "path/filepath" ) // https://github.com/telegramdesktop/tdesktop/blob/dev/Telegram/SourceFiles/platform/mac/specific_mac_p.mm#L364-L370 func desktopAppData(homedir string) []string { return []string{filepath.Join(homedir, "Library", "Application Support", AppName)} } ================================================ FILE: pkg/tpath/tpath_linux.go ================================================ //go:build linux package tpath import ( "path/filepath" "github.com/iyear/tdl/core/util/fsutil" ) // https://github.com/telegramdesktop/tdesktop/blob/dev/Telegram/SourceFiles/platform/linux/specific_linux.cpp#L669-L684 func desktopAppData(homedir string) []string { oldPath := filepath.Join(homedir, ".TelegramDesktop") suffixes := []string{"0", "1", "s"} for _, s := range suffixes { if fsutil.PathExists(filepath.Join(oldPath, "tdata", "settings"+s)) { return []string{oldPath} } } path := make([]string, 0) prefix := filepath.Join(homedir, ".local", "share") path = append(path, filepath.Join(prefix, AppName), // https://github.com/iyear/tdl/issues/92#issuecomment-1699307412 filepath.Join(prefix, "KotatogramDesktop"), filepath.Join(prefix, "64Gram"), filepath.Join(prefix, "TelegramDesktop"), ) if t, err := filepath.Glob("~/snap/telegram-desktop/*/.local/share/TelegramDesktop"); err == nil { path = append(path, t...) } return path } ================================================ FILE: pkg/tpath/tpath_other.go ================================================ //go:build !linux && !darwin && !windows package tpath func desktopAppData(_ string) []string { return []string{} } ================================================ FILE: pkg/tpath/tpath_windows.go ================================================ //go:build windows package tpath import ( "os" "path/filepath" ) // https://github.com/telegramdesktop/tdesktop/blob/dev/Telegram/SourceFiles/platform/win/specific_win.cpp#L237-L249 func desktopAppData(_ string) []string { paths := make([]string, 0) dataDir := os.Getenv("APPDATA") if dataDir == "" { return paths } paths = append(paths, filepath.Join(dataDir, AppName), filepath.Join(dataDir, "Telegram Desktop UWP")) return paths } ================================================ FILE: pkg/tplfunc/date.go ================================================ package tplfunc import ( "text/template" "time" "github.com/spf13/cast" ) var Date = []Func{Now(), FormatDate()} func Now() Func { return func(funcMap template.FuncMap) { funcMap["now"] = func() int64 { return time.Now().Unix() } } } func FormatDate() Func { return func(funcMap template.FuncMap) { funcMap["formatDate"] = func(args ...any) string { switch len(args) { case 0: panic("formatDate() requires at least 1 argument") case 1: return time.Unix(cast.ToInt64(args[0]), 0).Format("20060102150405") case 2: return time.Unix(cast.ToInt64(args[0]), 0).Format(args[1].(string)) default: panic("formatDate() requires at most 2 arguments") } } } } ================================================ FILE: pkg/tplfunc/date_test.go ================================================ package tplfunc import ( "fmt" "strconv" "strings" "testing" "text/template" "time" ) func TestNow(t *testing.T) { b := strings.Builder{} err := template.Must(template.New("test"). Funcs(FuncMap(Now())). Parse(`{{ now }}`)). Execute(&b, nil) if err != nil { t.Errorf("now() error = %v", err) return } n, err := strconv.ParseInt(b.String(), 10, 64) if err != nil { t.Errorf("now() error = %v", err) return } // Allow for a second of drift. if time.Now().Unix()-n > 1 { t.Errorf("now() got = %v", n) } } func TestFormatDate(t *testing.T) { // unify time zone time.Local = time.UTC tests := []struct { name string Unix int64 want string }{ {name: "formatDate1", Unix: 0, want: "19700101000000"}, {name: "formatDate2", Unix: 1, want: "19700101000001"}, {name: "formatDate3", Unix: 1000000000, want: "20010909014640"}, {name: "formatDate4", Unix: 10000000000, want: "22861120174640"}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { b := strings.Builder{} err := template.Must(template.New("test"). Funcs(FuncMap(FormatDate())). Parse(fmt.Sprintf(`{{ formatDate %v }}`, tt.Unix))). Execute(&b, tt) if err != nil { t.Errorf("formatDate() error = %v", err) return } if b.String() != tt.want { t.Errorf("formatDate() got = %v, want %v", b.String(), tt.want) } }) } } func TestCustomFormat(t *testing.T) { // unify time zone time.Local = time.UTC tests := []struct { name string Unix int64 Format string want string }{ {name: "formatDate1", Unix: 0, Format: "2006-01-02 15:04:05", want: "1970-01-01 00:00:00"}, {name: "formatDate2", Unix: 1, Format: "2006-01-02 15:04:05", want: "1970-01-01 00:00:01"}, {name: "formatDate3", Unix: 1000000000, Format: "2006-01-02 15:04:05", want: "2001-09-09 01:46:40"}, {name: "formatDate4", Unix: 0, Format: "Mon, 02 Jan 2006 15:04:05 MST", want: "Thu, 01 Jan 1970 00:00:00 UTC"}, {name: "formatDate5", Unix: 1, Format: "Mon, 02 Jan 2006 15:04:05 MST", want: "Thu, 01 Jan 1970 00:00:01 UTC"}, {name: "formatDate6", Unix: 1000000000, Format: "Mon, 02 Jan 2006 15:04:05 MST", want: "Sun, 09 Sep 2001 01:46:40 UTC"}, {name: "formatDate7", Unix: 0, Format: "20060102150405", want: "19700101000000"}, {name: "formatDate8", Unix: 1, Format: "20060102150405", want: "19700101000001"}, {name: "formatDate9", Unix: 1000000000, Format: "20060102150405", want: "20010909014640"}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { b := strings.Builder{} err := template.Must(template.New("test"). Funcs(FuncMap(FormatDate())). Parse(fmt.Sprintf(`{{ formatDate %v "%v" }}`, tt.Unix, tt.Format))). Execute(&b, tt) if err != nil { t.Errorf("formatDate() error = %v", err) return } if b.String() != tt.want { t.Errorf("formatDate() got = %v, want %v", b.String(), tt.want) } }) } } ================================================ FILE: pkg/tplfunc/func.go ================================================ package tplfunc import ( "text/template" ) type Func func(funcMap template.FuncMap) func FuncMap(functions ...Func) template.FuncMap { m := make(template.FuncMap) for _, f := range functions { f(m) } return m } var All []Func func init() { mods := [][]Func{String, Math, Date} for _, mod := range mods { All = append(All, mod...) } } ================================================ FILE: pkg/tplfunc/math.go ================================================ package tplfunc import ( "math/rand" "text/template" "time" ) var Math = []Func{Rand()} var rnd *rand.Rand func init() { rnd = rand.New(rand.NewSource(time.Now().Unix())) } func Rand() Func { return func(funcMap template.FuncMap) { funcMap["rand"] = func(min, max int) int { return rnd.Intn(max-min) + min } } } ================================================ FILE: pkg/tplfunc/math_test.go ================================================ package tplfunc import ( "strconv" "strings" "testing" "text/template" ) func TestRand(t *testing.T) { tests := []struct { name string Min int Max int }{ {name: "rand1", Min: 0, Max: 100}, {name: "rand2", Min: 99, Max: 100}, {name: "rand3", Min: 95, Max: 100}, {name: "rand5", Min: 0, Max: 1}, } m := FuncMap(Rand()) for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got := strings.Builder{} err := template.Must(template.New("test"). Funcs(m). Parse(`{{ rand .Min .Max }}`)). Execute(&got, tt) if err != nil { t.Errorf("rand() error = %v", err) return } n, err := strconv.Atoi(got.String()) if err != nil { t.Errorf("rand() error = %v", err) return } if n < tt.Min || n > tt.Max { t.Errorf("rand() got = %v", n) } }) } } func TestRandPanic(t *testing.T) { m := FuncMap(Rand()) got := strings.Builder{} err := template.Must(template.New("test"). Funcs(m). Parse(`{{ rand .Min .Max }}`)). Execute(&got, struct { Min int Max int }{Min: 0, Max: 0}) if err == nil { t.Errorf("rand() expected error, got nil") return } } ================================================ FILE: pkg/tplfunc/string.go ================================================ package tplfunc import ( "strings" "text/template" "github.com/flytam/filenamify" "github.com/iancoleman/strcase" ) var String = []Func{ Repeat(), Replace(), ToUpper(), ToLower(), SnakeCase(), CamelCase(), KebabCase(), Filenamify(), } func Repeat() Func { return func(funcMap template.FuncMap) { funcMap["repeat"] = func(s string, n int) string { return strings.Repeat(s, n) } } } func Replace() Func { return func(funcMap template.FuncMap) { funcMap["replace"] = func(s string, pairs ...string) string { return strings.NewReplacer(pairs...).Replace(s) } } } func ToUpper() Func { return func(funcMap template.FuncMap) { funcMap["upper"] = strings.ToUpper } } func ToLower() Func { return func(funcMap template.FuncMap) { funcMap["lower"] = strings.ToLower } } func SnakeCase() Func { return func(funcMap template.FuncMap) { funcMap["snakecase"] = func(s string) string { return strcase.ToSnake(s) } } } func CamelCase() Func { return func(funcMap template.FuncMap) { funcMap["camelcase"] = func(s string) string { return strcase.ToCamel(s) } } } func KebabCase() Func { return func(funcMap template.FuncMap) { funcMap["kebabcase"] = func(s string) string { return strcase.ToKebab(s) } } } func Filenamify() Func { return func(funcMap template.FuncMap) { funcMap["filenamify"] = func(s string, maxLength ...int) string { if len(maxLength) > 1 { return "invalid-MaxLength" } res, err := filenamify.FilenamifyV2(s, func(options *filenamify.Options) { if len(maxLength) > 0 { options.MaxLength = maxLength[0] } }) if err != nil || res == "" { return "invalid-filename" } return res } } } ================================================ FILE: pkg/tplfunc/string_test.go ================================================ package tplfunc import ( "fmt" "io" "strings" "testing" "text/template" ) func stringSlice(args []string) string { s := make([]string, len(args)) for i, v := range args { s[i] = fmt.Sprintf(`"%s"`, v) } return strings.Join(s, " ") } func TestRepeat(t *testing.T) { tests := []struct { name string S string N int want string }{ {name: "empty", S: "", N: 0, want: ""}, {name: "zero", S: "test", N: 0, want: ""}, {name: "one", S: "test", N: 1, want: "test"}, {name: "two", S: "test", N: 2, want: "testtest"}, } m := FuncMap(Repeat()) for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got := strings.Builder{} err := template.Must(template.New("test"). Funcs(m). Parse(`{{ repeat .S .N }}`)). Execute(&got, tt) if err != nil { t.Errorf("repeat() error = %v", err) return } if got.String() != tt.want { t.Errorf("repeat() got = %v, want %v", got.String(), tt.want) } }) } } func TestReplace(t *testing.T) { tests := []struct { name string S string Pairs []string want string }{ {name: "empty", S: "", Pairs: nil, want: ""}, {name: "empty pairs", S: "test", Pairs: nil, want: "test"}, {name: "single pair", S: "test", Pairs: []string{"t", "T"}, want: "TesT"}, {name: "multiple pairs1", S: "test", Pairs: []string{"t", "T", "e", "E"}, want: "TEsT"}, {name: "multiple pairs2", S: "test", Pairs: []string{"t", "T", "e", "E", "s", "S"}, want: "TEST"}, } m := FuncMap(Replace()) for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got := strings.Builder{} err := template.Must(template.New("test"). Funcs(m). Parse(fmt.Sprintf(`{{ replace .S %s }}`, stringSlice(tt.Pairs)))). Execute(&got, tt) if err != nil { t.Errorf("replace() error = %v", err) return } if got.String() != tt.want { t.Errorf("replace() got = %v, want %v", got.String(), tt.want) } }) } } func TestReplacePanic(t *testing.T) { tests := []struct { name string S string Pairs []string }{ {name: "odd pairs", S: "test", Pairs: []string{"t", "T", "e"}}, } m := FuncMap(Replace()) for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { err := template.Must(template.New("test"). Funcs(m). Parse(fmt.Sprintf(`{{ replace .S %s }}`, stringSlice(tt.Pairs)))). Execute(io.Discard, tt) if err == nil { t.Errorf("replace() expected error") } }) } } func TestToUpper(t *testing.T) { tests := []struct { name string S string want string }{ {name: "empty", S: "", want: ""}, {name: "lower", S: "test", want: "TEST"}, {name: "upper", S: "TEST", want: "TEST"}, } m := FuncMap(ToUpper()) for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got := strings.Builder{} err := template.Must(template.New("test"). Funcs(m). Parse(`{{ upper .S }}`)). Execute(&got, tt) if err != nil { t.Errorf("upper() error = %v", err) return } if got.String() != tt.want { t.Errorf("upper() got = %v, want %v", got.String(), tt.want) } }) } } func TestToLower(t *testing.T) { tests := []struct { name string S string want string }{ {name: "empty", S: "", want: ""}, {name: "lower", S: "test", want: "test"}, {name: "upper", S: "TEST", want: "test"}, } m := FuncMap(ToLower()) for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got := strings.Builder{} err := template.Must(template.New("test"). Funcs(m). Parse(`{{ lower .S }}`)). Execute(&got, tt) if err != nil { t.Errorf("lower() error = %v", err) return } if got.String() != tt.want { t.Errorf("lower() got = %v, want %v", got.String(), tt.want) } }) } } func TestSnakeCase(t *testing.T) { tests := []struct { name string S string want string }{ {name: "empty", S: "", want: ""}, {name: "lower", S: "test", want: "test"}, {name: "upper", S: "TEST", want: "test"}, {name: "camel", S: "testTest", want: "test_test"}, {name: "pascal", S: "TestTest", want: "test_test"}, } m := FuncMap(SnakeCase()) for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got := strings.Builder{} err := template.Must(template.New("test"). Funcs(m). Parse(`{{ snakecase .S }}`)). Execute(&got, tt) if err != nil { t.Errorf("snakecase() error = %v", err) return } if got.String() != tt.want { t.Errorf("snakecase() got = %v, want %v", got.String(), tt.want) } }) } } func TestCamelCase(t *testing.T) { tests := []struct { name string S string want string }{ {name: "empty", S: "", want: ""}, {name: "lower", S: "test", want: "Test"}, {name: "upper", S: "TEST", want: "Test"}, {name: "snake", S: "test_test", want: "TestTest"}, {name: "pascal", S: "TestTest", want: "TestTest"}, } m := FuncMap(CamelCase()) for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got := strings.Builder{} err := template.Must(template.New("test"). Funcs(m). Parse(`{{ camelcase .S }}`)). Execute(&got, tt) if err != nil { t.Errorf("camelcase() error = %v", err) return } if got.String() != tt.want { t.Errorf("camelcase() got = %v, want %v", got.String(), tt.want) } }) } } func TestKebabCase(t *testing.T) { tests := []struct { name string S string want string }{ {name: "empty", S: "", want: ""}, {name: "lower", S: "test", want: "test"}, {name: "upper", S: "TEST", want: "test"}, {name: "camel", S: "testTest", want: "test-test"}, {name: "pascal", S: "TestTest", want: "test-test"}, } m := FuncMap(KebabCase()) for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got := strings.Builder{} err := template.Must(template.New("test"). Funcs(m). Parse(`{{ kebabcase .S }}`)). Execute(&got, tt) if err != nil { t.Errorf("kebabcase() error = %v", err) return } if got.String() != tt.want { t.Errorf("kebabcase() got = %v, want %v", got.String(), tt.want) } }) } } ================================================ FILE: pkg/utils/byte.go ================================================ package utils import "fmt" type _byte struct{} var Byte _byte func (b _byte) FormatBinaryBytes(n int64) string { if n < 1024 { return fmt.Sprintf("%d B", n) } if n < 1024*1024 { return fmt.Sprintf("%.2f KB", float64(n)/1024) } if n < 1024*1024*1024 { return fmt.Sprintf("%.2f MB", float64(n)/1024/1024) } if n < 1024*1024*1024*1024 { return fmt.Sprintf("%.2f GB", float64(n)/1024/1024/1024) } return fmt.Sprintf("%.2f TB", float64(n)/1024/1024/1024/1024) } ================================================ FILE: pkg/utils/cmd.go ================================================ package utils import ( "fmt" "strings" "github.com/spf13/cobra" "github.com/spf13/pflag" ) type cmd struct{} var Cmd = cmd{} // StringEnumFlag defines a new string flag that only allows values listed in options. func (cmd) StringEnumFlag(cmd *cobra.Command, p *string, name, shorthand, defaultValue string, options []string, usage string) *pflag.Flag { *p = defaultValue val := &enumValue{string: p, options: options} f := cmd.Flags().VarPF(val, name, shorthand, fmt.Sprintf("%s: %s", usage, formatValuesForUsageDocs(options))) _ = cmd.RegisterFlagCompletionFunc(name, func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { return options, cobra.ShellCompDirectiveNoFileComp }) return f } type enumValue struct { string *string options []string } func (e *enumValue) Set(value string) error { if !isIncluded(value, e.options) { return fmt.Errorf("valid values are %s", formatValuesForUsageDocs(e.options)) } *e.string = value return nil } func (e *enumValue) String() string { return *e.string } func (e *enumValue) Type() string { return "string" } func isIncluded(value string, opts []string) bool { for _, opt := range opts { if strings.EqualFold(opt, value) { return true } } return false } func formatValuesForUsageDocs(values []string) string { return fmt.Sprintf("{%s}", strings.Join(values, "|")) } ================================================ FILE: pkg/validator/validator.go ================================================ package validator import ( "github.com/go-playground/validator/v10" ) var v *validator.Validate func init() { v = validator.New() } func Struct(s interface{}) error { return v.Struct(s) } ================================================ FILE: scripts/install.ps1 ================================================ param( [String]$Version, [Boolean]$Proxy = $False ) $Owner = "iyear" $Repo = "tdl" $Location = "$Env:SystemDrive\tdl" $ErrorActionPreference = "Stop" # check if run as admin if (-not ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]"Administrator")) { Write-Host "Please run this script as Administrator" -ForegroundColor Red exit 1 } # use proxy if argument is passed $PROXY_PREFIX = "" if ($Proxy) { $PROXY_PREFIX = "https://mirror.ghproxy.com/" Write-Host "Using GitHub proxy: $PROXY_PREFIX" -ForegroundColor Blue } # Set download ARCH based on system architecture $Arch = "" switch ($env:PROCESSOR_ARCHITECTURE) { "AMD64" { $Arch = "64bit" } "x86" { $Arch = "32bit" } "ARM" { $Arch = "arm64" } default { Write-Host "Unsupported system architecture: $env:PROCESSOR_ARCHITECTURE" -ForegroundColor Red exit 1 } } # set version if (!$Version) { $Version = (Invoke-RestMethod -Uri "https://api.github.com/repos/$Owner/$Repo/releases/latest").tag_name } Write-Host "Target version: $Version" -ForegroundColor Blue # build download URL $URL = "${PROXY_PREFIX}https://github.com/$Owner/$Repo/releases/download/$Version/${Repo}_Windows_$Arch.zip" Write-Host "Downloading $Repo from $URL" -ForegroundColor Blue # download and extract Invoke-WebRequest -Uri $URL -OutFile "$Repo.zip" # test zip path if (-not(Test-Path "$Repo.zip")) { Write-Host "Download $URL failed" -ForegroundColor Red exit 1 } # only extract tdl.exe to $LOCATION , add to PATH and remove zip file Expand-Archive -Path "$Repo.zip" -DestinationPath "$Location" -Force # if $LOCATION has not been added to PATH yet, add it $PathEnv = [Environment]::GetEnvironmentVariable("Path", [EnvironmentVariableTarget]::Machine) if (-not($PathEnv -like "*$Location*")) { Write-Host "Adding $Location to Path Environment variable..." -ForegroundColor Blue $NewPath = $PathEnv + ";$Location" [Environment]::SetEnvironmentVariable("Path", $NewPath, [EnvironmentVariableTarget]::Machine) # update current process' PATH [Environment]::SetEnvironmentVariable("Path", $NewPath, [EnvironmentVariableTarget]::Process) Write-Host "Note: Updates to PATH might not be visible until you restart your terminal application or reboot machine" -ForegroundColor Yellow } # remove zip file Remove-Item "$Repo.zip" # test if installation is successful, and print instructions if (-not(Get-Command $Repo -ErrorAction SilentlyContinue)) { Write-Host "Installation failed" -ForegroundColor Red exit 1 } Write-Host "$Repo installed successfully! Location: $Location" -ForegroundColor Green Write-Host "Run '$Repo' to get started" -ForegroundColor Green Write-Host "To get started with tdl, please visit https://docs.iyear.me/tdl" -ForegroundColor Green ================================================ FILE: scripts/install.sh ================================================ #!/usr/bin/env bash OWNER="iyear" REPO="tdl" LOCATION="/usr/local/bin" echo_green() { echo -e "\033[32m$1\033[0m" } echo_red() { echo -e "\033[31m$1\033[0m" } echo_blue() { echo -e "\033[34m$1\033[0m" } # Check if script is run as root if [[ $EUID -ne 0 ]]; then echo_red "This script must be run as root" exit 1 fi PROXY="" VERSION="" # flags: --proxy --version while [[ $# -gt 0 ]]; do key="$1" case $key in --proxy) PROXY="https://mirror.ghproxy.com/" echo_blue "Using GitHub proxy: $PROXY" shift ;; --version) VERSION="$2" shift shift ;; *) echo "Unknown flag: $key" exit 1 ;; esac done # Set OS based on system case $(uname -s) in Linux) OS="Linux" ;; Darwin) OS="MacOS" ;; *) echo "Unsupported OS: $OS" exit 1 ;; esac # Set download ARCH based on system architecture case $(uname -m) in x86_64) ARCH="64bit" ;; i686) ARCH="32bit" ;; armv5*) ARCH="armv5" ;; armv6*) ARCH="armv6" ;; armv7*) ARCH="armv7" ;; arm64|aarch64*) ARCH="arm64" ;; *) echo "Unsupported architecture: $ARCH" exit 1 ;; esac # get latest version if [ -z "$VERSION" ]; then VERSION=$(curl --silent "https://api.github.com/repos/$OWNER/$REPO/releases/latest" | grep '"tag_name":' | sed -E 's/.*"([^"]+)".*/\1/') fi echo_blue "Target version: $VERSION" # build download URL URL=${PROXY}https://github.com/$OWNER/$REPO/releases/download/$VERSION/${REPO}_${OS}_$ARCH.tar.gz echo_blue "Downloading $REPO from $URL" # download and extract wget -q --show-progress -O - "$URL" | tar -xz && \ mv $REPO $LOCATION/$REPO && \ chmod +x $LOCATION/$REPO && \ echo_green "$REPO installed successfully! Location: $LOCATION/$REPO" && \ echo_green "Run '$REPO' to get started" && \ echo_green "To get started with tdl, please visit https://docs.iyear.me/tdl" ================================================ FILE: test/archive_test.go ================================================ package test import ( "os" "path/filepath" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) var _ = Describe("Test tdl archive", func() { AfterEach(func() { // remove zip files files, err := filepath.Glob("*.tdl") Expect(err).To(Succeed()) for _, file := range files { Expect(os.Remove(file)).To(Succeed()) } }) When("backup", func() { It("should success", func() { exec(cmd, []string{"backup"}, true) files, err := filepath.Glob("*.tdl") Expect(err).To(Succeed()) Expect(len(files)).To(Equal(1)) _, err = os.Stat(files[0]) Expect(err).To(Succeed()) }) It("should success with custom file name", func() { exec(cmd, []string{"backup", "-d", "custom.tdl"}, true) _, err := os.Stat("custom.tdl") Expect(err).To(Succeed()) }) }) When("recover", func() { It("should success", func() { exec(cmd, []string{"backup", "-d", "custom.tdl"}, true) exec(cmd, []string{"recover", "-f", "custom.tdl"}, true) }) It("should fail if do not specify file name", func() { exec(cmd, []string{"recover"}, false) }) It("should fail with invalid file name", func() { exec(cmd, []string{"recover", "-f", "foo.tdl"}, false) }) }) }) ================================================ FILE: test/chat_ls_test.go ================================================ package test import ( "encoding/json" "strings" "github.com/iyear/tdl/app/chat" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) var _ = Describe("Test tdl chat ls", FlakeAttempts(3), func() { BeforeEach(func() { args = []string{"chat", "ls"} }) expectTable := func() { lines := strings.Split(output, "\n") By("check header") Expect(len(lines)).To(BeNumerically(">=", 2)) Expect(lines[0]).To(MatchRegexp("ID\\s+Type\\s+VisibleName\\s+Username\\s+Topics")) } When("use output flag", func() { It("with default", func() { exec(cmd, args, true) expectTable() }) It("with table", func() { exec(cmd, append(args, "--output", "table"), true) expectTable() }) It("with json", func() { exec(cmd, append(args, "--output", "json"), true) Expect(json.Valid([]byte(output))).To(BeTrue()) }) }) When("use filter flag", func() { BeforeEach(func() { args = append(args, "--output", "json", "--filter") }) readDialogs := func() []*chat.Dialog { dialogs := make([]*chat.Dialog, 0) Expect(json.Unmarshal([]byte(output), &dialogs)).To(Succeed()) return dialogs } It("to display available fields", func() { exec(cmd, append(args, "-"), true) Expect(len(strings.Split(output, "\n"))).To(BeNumerically(">=", 2)) }) It("to filter id", func() { exec(cmd, append(args, "ID>2200000000"), true) for _, dialog := range readDialogs() { Expect(dialog.ID).To(BeNumerically(">", 2200000000)) } }) It("to filter type", func() { exec(cmd, append(args, "Type contains 'private'"), true) for _, dialog := range readDialogs() { Expect(dialog.Type).To(Equal("private")) } }) It("to filter visible name", func() { exec(cmd, append(args, "VisibleName contains 'Telegram'"), true) for _, dialog := range readDialogs() { Expect(dialog.VisibleName).To(ContainSubstring("Telegram")) } }) It("to filter username", func() { exec(cmd, append(args, "Username contains 'telegram'"), true) for _, dialog := range readDialogs() { Expect(dialog.Username).To(ContainSubstring("telegram")) } }) It("to filter topics", func() { exec(cmd, append(args, "len(Topics)>0"), true) for _, dialog := range readDialogs() { Expect(len(dialog.Topics)).To(BeNumerically(">", 0)) } }) It("to filter multiple fields", func() { exec(cmd, append(args, "ID>2200000000 && len(Topics)>0"), true) for _, dialog := range readDialogs() { Expect(dialog.ID).To(BeNumerically(">", 2200000000)) Expect(len(dialog.Topics)).To(BeNumerically(">", 0)) } }) }) }) ================================================ FILE: test/chat_users_test.go ================================================ package test import ( "log" "os" "strconv" "sync" "github.com/tidwall/gjson" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) var _ = Describe("Test tdl chat users", FlakeAttempts(3), func() { var ( once sync.Once skip bool id int64 ) BeforeEach(func() { Skip("no better test method, so we skip now") if skip { Skip("skip because of no channel/group") } args = []string{"chat", "users"} once.Do(func() { By("list all channels/groups to iter") args := []string{"chat", "ls", "-f", `Type in ["channel","group"]`, "-o", "json"} exec(cmd, args, true) r := gjson.Parse(output) if len(r.Array()) == 0 { skip = true return } id = r.Get("0.id").Int() Expect(id).NotTo(BeEmpty()) }) }) When("use chat flag", func() { It("should success", func() { args = append(args, "-c", strconv.FormatInt(id, 10)) exec(cmd, args, true) j, err := os.ReadFile("tdl-users.json") Expect(err).To(Succeed()) r := gjson.ParseBytes(j) Expect(r.Get("id").Int()).To(BeNumerically("==", id)) Expect(len(r.Get("users").Array())).To(BeNumerically(">", 0)) Expect(r.Get("kicked").Exists()).To(BeTrue()) Expect(r.Get("banned").Exists()).To(BeTrue()) Expect(r.Get("admins").Exists()).To(BeTrue()) Expect(r.Get("bots").Exists()).To(BeTrue()) log.Println("users:", len(r.Get("users").Array())) }) It("with invalid chat", func() { args = append(args, "-c", "invalid_username") exec(cmd, args, false) }) }) }) ================================================ FILE: test/download_test.go ================================================ package test import ( "crypto/md5" "fmt" "io/fs" "log" "os" "path/filepath" "strconv" "sync" "github.com/tidwall/gjson" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) var _ = Describe("Test tdl download", FlakeAttempts(3), func() { var ( once sync.Once fileHash = make(map[string][16]byte) id int64 remoteFiles = make([]int64, 0) ) BeforeEach(func() { once.Do(func() { By("collect local file hashes") Expect(filepath.WalkDir("testdata", func(path string, d fs.DirEntry, err error) error { if err != nil { return err } if d.IsDir() { return nil } bytes, err := os.ReadFile(path) Expect(err, Succeed()) h := md5.Sum(bytes) fileHash[filepath.Base(path)] = h log.Println("path:", path, "md5:", h) return nil })).To(Succeed()) By("upload files") exec(cmd, []string{"upload", "-p", "testdata"}, true) By("export uploaded files") exportFile := filepath.Join(GinkgoT().TempDir(), "export.json") exec(cmd, []string{"chat", "export", "-T", "last", "-i", strconv.Itoa(len(fileHash)), "-o", exportFile}, true) exportBytes, err := os.ReadFile(exportFile) Expect(err).To(Succeed()) By("get chat id and remote file ids") id = gjson.GetBytes(exportBytes, "id").Int() Expect(id).NotTo(BeZero()) gjson.GetBytes(exportBytes, "messages").ForEach(func(key, value gjson.Result) bool { remoteFiles = append(remoteFiles, value.Get("id").Int()) return true }) Expect(len(remoteFiles)).To(Equal(len(fileHash))) }) }) When("use url flag", func() { It("should success", func() { urls := make([]string, 0) for _, u := range remoteFiles { urls = append(urls, "-u", fmt.Sprintf("https://t.me/%d/%d", id, u)) } dir := GinkgoT().TempDir() args := []string{"download", "-d", dir, "--template", "{{ .FileName }}"} args = append(args, urls...) exec(cmd, args, true) log.Println("check local files") Expect(filepath.WalkDir(dir, func(path string, d fs.DirEntry, err error) error { if err != nil { return err } if d.IsDir() { return nil } bytes, err := os.ReadFile(path) Expect(err, Succeed()) h := md5.Sum(bytes) log.Println("path:", path, "md5:", h) Expect(h).To(Equal(fileHash[filepath.Base(path)])) return nil })).To(Succeed()) }) }) }) ================================================ FILE: test/suite_test.go ================================================ package test import ( "context" _ "embed" "fmt" "io" "log" "math/rand" "os" "testing" "github.com/fatih/color" "github.com/spf13/cobra" tcmd "github.com/iyear/tdl/cmd" "github.com/iyear/tdl/test/testserver" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) func TestCommand(t *testing.T) { RegisterFailHandler(Fail) RunSpecs(t, "Test tdl") } var ( cmd *cobra.Command args []string output string testAccount string sessionFile string ) var _ = BeforeSuite(func(ctx context.Context) { var err error testAccount, sessionFile, err = testserver.Setup(ctx, rand.NewSource(GinkgoRandomSeed())) Expect(err).To(Succeed()) log.SetOutput(GinkgoWriter) }) var _ = BeforeEach(func() { cmd = tcmd.New() }) func exec(cmd *cobra.Command, args []string, success bool) { r, w, err := os.Pipe() Expect(err).To(Succeed()) os.Stdout = w color.Output = w log.Printf("args: %s\n", args) cmd.SetArgs(append([]string{ "-n", testAccount, "--storage", fmt.Sprintf("type=file,path=%s", sessionFile), }, args...)) if err = cmd.Execute(); success { Expect(err).To(Succeed()) } else { Expect(err).ToNot(Succeed()) } Expect(w.Close()).To(Succeed()) o, err := io.ReadAll(r) Expect(err).To(Succeed()) output = string(o) } ================================================ FILE: test/testserver/public_key.pem ================================================ -----BEGIN RSA PUBLIC KEY----- MIIBCgKCAQEAvKLEOWTzt9Hn3/9Kdp/RdHcEhzmd8xXeLSpHIIzaXTLJDw8BhJy1 jR/iqeG8Je5yrtVabqMSkA6ltIpgylH///FojMsX1BHu4EPYOXQgB0qOi6kr08iX ZIH9/iOPQOWDsL+Lt8gDG0xBy+sPe/2ZHdzKMjX6O9B4sOsxjFrk5qDoWDrioJor AJ7eFAfPpOBf2w73ohXudSrJE0lbQ8pCWNpMY8cB9i8r+WBitcvouLDAvmtnTX7a khoDzmKgpJBYliAY4qA73v7u5UIepE8QgV0jCOhxJCPubP8dg+/PlLLVKyxU5Cdi QtZj2EMy4s9xlNKzX8XezE0MHEa6bQpnFwIDAQAB -----END RSA PUBLIC KEY----- ================================================ FILE: test/testserver/testserver.go ================================================ package testserver import ( "context" _ "embed" "log" "math/rand" "os" "path/filepath" "strconv" "github.com/go-faster/errors" "github.com/gotd/td/crypto" "github.com/gotd/td/exchange" "github.com/gotd/td/telegram" "github.com/gotd/td/telegram/auth" "github.com/gotd/td/telegram/dcs" "github.com/gotd/td/tg" "github.com/iyear/tdl/core/dcpool" "github.com/iyear/tdl/core/storage" tclientcore "github.com/iyear/tdl/core/tclient" "github.com/iyear/tdl/pkg/kv" "github.com/iyear/tdl/pkg/tclient" ) //go:embed public_key.pem var publicKeyData []byte var ( dc = 1 dcList = dcs.List{ Options: []tg.DCOption{ { ID: 1, IPAddress: "127.0.0.1", Port: 10443, }, }, Domains: nil, Test: false, } publicKeys []exchange.PublicKey phone = "+86 13858528382" ) func init() { keys, _ := crypto.ParseRSAPublicKeys(publicKeyData) for _, k := range keys { publicKeys = append(publicKeys, exchange.PublicKey{RSA: k}) } } // Setup creates test user and returns account and session file path. Namespace is the value of account. func Setup(ctx context.Context, rnd rand.Source) (account string, sessionFile string, _ error) { tclientcore.DC = dc tclientcore.DCList = dcList tclientcore.PublicKeys = publicKeys dcpool.EnableTestMode() account = strconv.FormatInt(rand.Int63(), 10) sessionFile = filepath.Join(os.TempDir(), "tdl", account) return account, sessionFile, setupTestUser(ctx, rand.New(rnd), account, sessionFile) } func setupTestUser(ctx context.Context, rnd *rand.Rand, account, sessionFile string) error { kvd, err := kv.New(kv.DriverFile, map[string]any{ "path": sessionFile, }) if err != nil { return errors.Wrapf(err, "create kv storage: %s", sessionFile) } log.Printf("session file: %s", sessionFile) stg, err := kvd.Open(account) if err != nil { return errors.Wrap(err, "open test namespace") } sess := storage.NewSession(stg, true) opts := telegram.Options{ DC: dc, DCList: dcList, PublicKeys: publicKeys, SessionStorage: sess, } app := tclient.Apps[tclient.AppDesktop] c := telegram.NewClient(app.AppID, app.AppHash, opts) if err = c.Run(ctx, func(ctx context.Context) error { if err = c.Ping(ctx); err != nil { return err } authClient := auth.NewClient(c.API(), rnd, app.AppID, app.AppHash) if err = auth.NewFlow( testAuth{phone: phone}, auth.SendCodeOptions{}, ).Run(ctx, authClient); err != nil { return errors.Wrap(err, "register test user") } user, err := c.Self(ctx) if err != nil { return errors.Wrap(err, "get self") } log.Printf("user: %v, %v, %v", user.ID, user.FirstName, user.LastName) return nil }); err != nil { return errors.Wrap(err, "run auth") } return nil } type testAuth struct { phone string } func (t testAuth) Phone(_ context.Context) (string, error) { return t.phone, nil } func (t testAuth) Password(_ context.Context) (string, error) { return "", auth.ErrPasswordNotProvided } func (t testAuth) Code(_ context.Context, _ *tg.AuthSentCode) (string, error) { return "12345", nil } func (t testAuth) AcceptTermsOfService(_ context.Context, _ tg.HelpTermsOfService) error { return nil } func (t testAuth) SignUp(_ context.Context) (auth.UserInfo, error) { return auth.UserInfo{ FirstName: "Test", LastName: "User", }, nil } ================================================ FILE: test/upload_test.go ================================================ package test import ( "log" "math/rand" "os" "path/filepath" "strconv" "github.com/google/uuid" "github.com/tidwall/gjson" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) var _ = Describe("Test tdl upload", FlakeAttempts(3), func() { BeforeEach(func() { args = []string{"upload"} }) var ( dir string files []string ) BeforeEach(func() { dir = GinkgoT().TempDir() // create files files = make([]string, 0) for i := 0; i < rand.Intn(3)+3; i++ { file := filepath.Join(dir, uuid.New().String()) // generate random file with size between 1MB and 2MB f, err := os.Create(file) Expect(err).To(Succeed()) Expect(f.Truncate(int64(rand.Intn(1e5)) + 1e5)).To(Succeed()) Expect(f.Close()).To(Succeed()) files = append(files, file) } }) checkFiles := func(chat string, n int, expected []string) { By("check if files are uploaded") exportFile := filepath.Join(dir, "export.json") exec(cmd, []string{"chat", "-c", chat, "export", "-T", "last", "-i", strconv.Itoa(n), "-o", exportFile}, true) exportBytes, err := os.ReadFile(exportFile) Expect(err).To(Succeed()) actualFiles := make([]string, 0) gjson.GetBytes(exportBytes, "messages").ForEach(func(key, value gjson.Result) bool { actualFiles = append(actualFiles, filepath.Join(dir, value.Get("file").String())) return true }) log.Printf("actual files on server: %v", actualFiles) Expect(actualFiles).To(ConsistOf(expected)) } When("use path flag", func() { It("should success", func() { args = append(args, "-p", dir) exec(cmd, args, true) checkFiles("", len(files), files) }) It("should fail with invalid path", func() { args = append(args, "-p", "foo") exec(cmd, args, false) }) It("should fail with invalid file", func() { args = append(args, "-p", "foo.bar") exec(cmd, args, false) }) }) When("use rm flag", func() { It("should success", func() { args = append(args, "-p", dir, "--rm") exec(cmd, args, true) checkFiles("", len(files), files) By("check if files are removed") for _, file := range files { _, err := os.Stat(file) Expect(os.IsNotExist(err)).To(BeTrue()) } }) }) When("use chat flag", func() { It("should success", func() { By("get a private chat id") exec(cmd, []string{"chat", "ls", "-o", "json", "-f", "Type contains 'private'"}, true) chat := gjson.Get(output, "0.id").String() Expect(chat).NotTo(BeEmpty()) args = append(args, "-p", dir, "-c", chat) exec(cmd, args, true) checkFiles(chat, len(files), files) }) It("should fail with invalid chat domain", func() { args = append(args, "-p", dir, "-c", "foo") exec(cmd, args, false) }) It("should fail with invalid chat id", func() { args = append(args, "-p", dir, "-c", "-100") exec(cmd, args, false) }) }) When("use exclude flag", func() { It("should success", func() { By("modify files' extension") modify, remain := files[:len(files)/2], files[len(files)/2:] log.Printf("modify files: %v", modify) log.Printf("remain files: %v", remain) for _, file := range modify { Expect(os.Rename(file, file+".foo")).To(Succeed()) } args = append(args, "-p", dir, "-e", ".foo") exec(cmd, args, true) checkFiles("", len(remain), remain) }) }) })