Skip to content

Origin#23

Merged
Silentely merged 14 commits intomainfrom
origin
Jul 4, 2025
Merged

Origin#23
Silentely merged 14 commits intomainfrom
origin

Conversation

@Silentely
Copy link
Copy Markdown
Member

@Silentely Silentely commented Jul 4, 2025

Summary by Sourcery

Add media group (album) support and enhance storage rule capabilities

New Features:

  • Support Telegram media groups by aggregating and processing album items in the bot
  • Introduce a new IS-ALBUM rule type for storage rules with "NEW-FOR-ALBUM" directory behavior
  • Enable userbot integration configuration to download from private channels and groups

Enhancements:

  • Refactor batch file task creation to handle grouped media and create album subfolders
  • Use caching and parallelism in Dockerfile for faster builds
  • Improve storage path handling in MinIO and WebDAV clients with unique filename fallback

Build:

  • Update Dockerfile to separate module download and enable build cache mounts

CI:

  • Refine GitHub Actions Docker build workflow with registry cache, conditional push, and dynamic tagging

Documentation:

  • Document IS-ALBUM rule usage and userbot configuration in Chinese docs
  • Add warning and guidance for userbot setup in deployment config

Tests:

  • Add WebDAV client test for nested directory paths

Chores:

  • Update FUNDING link
  • Rename invalid rule name check to IsUsable and adjust ruleutil types to MatchedDirPath

Summary by CodeRabbit

  • New Features

    • Added support for handling grouped media (album) messages, including batch saving and album-aware directory structuring.
    • Introduced a new rule type "IS-ALBUM" for storage rules, enabling album-based file organization.
    • Added documentation and configuration options for enabling userbot integration to support downloads from private channels and groups.
  • Improvements

    • Enhanced filename conflict handling for Minio and WebDAV storage backends to avoid excessive retries and ensure unique filenames.
    • Made Telegram RPC retry count configurable.
    • Improved Docker build efficiency with better caching and explicit dependency handling.
  • Bug Fixes

    • Fixed edge case in WebDAV file saving with double-slash paths.
  • Documentation

    • Updated usage and deployment guides to reflect new album rule type and userbot configuration.
  • Chores

    • Updated funding link.
    • Refined Docker-related configuration for clarity and efficiency.

@sourcery-ai
Copy link
Copy Markdown

sourcery-ai Bot commented Jul 4, 2025

Reviewer's Guide

This PR implements comprehensive support for Telegram media groups (albums): messages are collected by group ID with a debounce timer, then processed together as batch or single file tasks; the rule engine is extended with a new IS-ALBUM rule and matched directory paths; batch file task creation now handles albums as folders; along with related updates to handlers, storage drivers, docs, CI workflows, Dockerfile caching, config, and constants.

Sequence diagram for handling Telegram media group (album) messages

sequenceDiagram
    participant User as actor User
    participant Bot as Bot
    participant MediaGroupHandler as MediaGroupHandler
    participant Storage as Storage
    participant RuleEngine as RuleEngine

    User->>Bot: Send media group messages
    Bot->>MediaGroupHandler: handleGroupMediaMessage(ctx, update, message, groupID)
    MediaGroupHandler->>MediaGroupHandler: Collect files by groupID
    MediaGroupHandler->>MediaGroupHandler: Start debounce timer
    MediaGroupHandler-->>User: (No immediate response)
    Note over MediaGroupHandler: After timeout
    MediaGroupHandler->>MediaGroupHandler: processMediaGroup(ctx, update, groupID)
    MediaGroupHandler->>RuleEngine: Apply IS-ALBUM rule
    RuleEngine-->>MediaGroupHandler: Return storage and dir path
    MediaGroupHandler->>Storage: Create batch file task (album as folder)
    Storage-->>MediaGroupHandler: Store files
    MediaGroupHandler->>Bot: Edit message to show result
    Bot-->>User: Notify user of save result
Loading

ER diagram for IS-ALBUM rule and album directory handling

erDiagram
    RULE {
        id int
        type string
        storage_name string
        dir_path string
        data string
    }
    ALBUM {
        group_id int
        dir_name string
    }
    FILE {
        id int
        group_id int
        name string
        storage_path string
    }
    RULE ||--o{ FILE : applies
    ALBUM ||--|{ FILE : contains
    FILE }o--|| ALBUM : belongs_to
Loading

Class diagram for new and updated rule types (IS-ALBUM and MatchedDirPath)

classDiagram
    class RuleMediaType {
        - storName string
        - storPath string
        - matchAlbum bool
        + Type() RuleType
        + Match(input bool) (bool, error)
        + StorageName() string
        + StoragePath() string
    }
    class MatchedDirPath {
        + String() string
        + NeedNewForAlbum() bool
    }
    RuleMediaType --|> RuleClass
    RuleClass <|.. RuleMediaType
    MatchedDirPath <.. ApplyRule
    ApplyRule --> MatchedDirPath : returns
    ApplyRule --> RuleMediaType : uses
Loading

Class diagram for MediaGroupHandler and media group processing

classDiagram
    class MediaGroupHandler {
        - groups map[int64][]TGFileMessage
        - timers map[int64]*time.Timer
        - mu sync.Mutex
        - timeout time.Duration
        + handleGroupMediaMessage(ctx, update, message, groupID) error
        + processMediaGroup(ctx, update, groupID)
    }
    class TGFileMessage
    MediaGroupHandler "1" o-- "*" TGFileMessage : groups
Loading

File-Level Changes

Change Details Files
Add media group collection and processing logic in bot handlers
  • Detect message.GetGroupedID in handlers and route to handleGroupMediaMessage
  • Create MediaGroupHandler with maps, mutex, timer debounce
  • Implement processMediaGroup to reply and dispatch batch or single tasks
client/bot/handlers/media.go
Enhance batch task creation to support album directories
  • Introduce MatchedDirPath type for rule paths and album detection
  • Group files by groupID and create subfolders named after first file
  • Fallback to regular elements when no album or single file
client/bot/handlers/utils/shortcut/tftask.go
client/bot/handlers/utils/shortcut/tftask.go
Extend rule engine with IS-ALBUM rule and path constants
  • Add RuleDirPathNewForAlbum constant and IsAlbum enum
  • Implement RuleMediaType in pkg/rule/is_album.go
  • Update ApplyRule to return MatchedDirPath and handle IsAlbum rules
client/bot/handlers/utils/ruleutil/rule.go
pkg/consts/specific.go
pkg/enums/rule/ruletype.go
pkg/rule/is_album.go
Improve storage clients with unique filename fallback
  • Import xid and break loop after 1000 attempts
  • Append random ID for uniqueness fallback
storage/minio/client.go
storage/webdav/webdav.go
Refactor build, CI, Dockerfile, and caching
  • Use go mod download and build cache mounts in Dockerfile
  • Adjust build-push-action tags, labels, cache-from, conditional push
  • Simplify version extraction and BuildTime expression
Dockerfile
.github/workflows/build-docker.yml
Update documentation and configuration for new features
  • Add IS-ALBUM rule to usage docs
  • Add userbot settings and warnings in config docs
docs/content/zh/usage/_index.md
docs/content/zh/deployment/configuration/_index.md

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Jul 4, 2025

Caution

Review failed

The pull request is closed.

Walkthrough

The changes introduce support for album (media group) handling in Telegram bot media processing, including new rule types and directory structuring for grouped media. Workflow improvements, configuration enhancements, and documentation updates accompany these features. Additional safeguards for file storage uniqueness and minor refactoring are also included.

Changes

File(s) Change Summary
.dockerignore, Dockerfile Improved Docker build context and caching by updating ignore patterns and build steps.
.github/workflows/build-docker.yml Refined Docker image tagging, caching, and metadata extraction in the workflow.
.github/FUNDING.yml Updated the custom funding URL.
client/bot/handlers/media.go Added album (media group) message handling with batching and concurrency control.
client/bot/handlers/utils/ruleutil/rule.go, pkg/enums/rule/ruletype.go, pkg/rule/is_album.go Introduced new rule type "IS-ALBUM" and associated logic for album detection and matching.
client/bot/handlers/utils/shortcut/message.go Aliased import for clarity; no logic changes.
client/bot/handlers/utils/shortcut/tftask.go Enhanced batch file task creation to support album grouping and directory creation.
client/middleware/default.go Made retry count configurable via external config.
docs/content/zh/deployment/configuration/_index.md, docs/content/zh/usage/_index.md Documented new userbot options and album rule usage.
pkg/consts/specific.go Added constant for album-specific directory creation.
storage/minio/client.go, storage/webdav/webdav.go Added safeguards for filename uniqueness to avoid infinite loops; improved path joining.
storage/webdav/client_test.go Added test case for nested path with double slash.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Bot
    participant MediaGroupHandler
    participant Storage

    User->>Bot: Send media group messages (album)
    Bot->>MediaGroupHandler: Detects group, stores files by group ID
    MediaGroupHandler-->>MediaGroupHandler: Reset 1s timer per group
    MediaGroupHandler->>Bot: On timer expiry, batch process group
    Bot->>Storage: Save all files in group (possibly in new album folder)
    Storage-->>Bot: Confirm save
    Bot->>User: Reply with save status
Loading

Poem

A hop, a skip, a flurry of files,
Albums now grouped with rabbit smiles.
Rules for albums, new folders bloom,
No more endless loops of filename doom!
With docs and configs all in tune,
This bunny’s code will make you swoon.
🐇✨


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e786266 and 2518ad2.

📒 Files selected for processing (17)
  • .dockerignore (1 hunks)
  • .github/FUNDING.yml (1 hunks)
  • .github/workflows/build-docker.yml (2 hunks)
  • Dockerfile (1 hunks)
  • client/bot/handlers/media.go (3 hunks)
  • client/bot/handlers/utils/ruleutil/rule.go (4 hunks)
  • client/bot/handlers/utils/shortcut/message.go (2 hunks)
  • client/bot/handlers/utils/shortcut/tftask.go (4 hunks)
  • client/middleware/default.go (1 hunks)
  • docs/content/zh/deployment/configuration/_index.md (2 hunks)
  • docs/content/zh/usage/_index.md (2 hunks)
  • pkg/consts/specific.go (1 hunks)
  • pkg/enums/rule/ruletype.go (1 hunks)
  • pkg/rule/is_album.go (1 hunks)
  • storage/minio/client.go (3 hunks)
  • storage/webdav/client_test.go (1 hunks)
  • storage/webdav/webdav.go (2 hunks)
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate Unit Tests
  • Create PR with Unit Tests
  • Post Copyable Unit Tests in a Comment
  • Commit Unit Tests in branch origin

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai auto-generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Copy Markdown

@gemini-code-assist gemini-code-assist Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Summary of Changes

Hello @Silentely, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request primarily introduces comprehensive support for handling Telegram media groups (albums), allowing users to define sophisticated rules for how these grouped files are stored, including automatic directory creation. It also includes several quality-of-life improvements such as configurable API retries, more efficient Docker builds, and more reliable unique filename generation for stored files.

Highlights

  • Media Group (Album) Handling: Implemented robust handling for Telegram media groups (albums), allowing the bot to process and save multiple files sent as a single album. This includes a timeout mechanism to collect all parts of an album before processing.
  • Advanced Rule-Based Storage for Albums: Introduced a new rule type, IS-ALBUM, which enables users to define specific storage rules for media groups. Additionally, a special NEW-FOR-ALBUM path option allows the bot to automatically create a new subdirectory for each album, named after the first file in the group.
  • Configurable RPC Retries: The number of RPC retries for Telegram API calls is now configurable via the rpc_retry setting in the telegram section of the configuration, providing more control over network resilience.
  • Improved Docker Build Efficiency: The Dockerfile has been optimized to leverage Go module caching, significantly speeding up subsequent Docker builds by separating the go mod download step.
  • Enhanced Unique Filename Generation: Storage backends (Minio and WebDAV) now include a more robust fallback mechanism to generate unique filenames using xid if the standard sequential numbering approach fails after many attempts, preventing potential naming conflicts.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point in your pull request via creating an issue comment (i.e. comment on the pull request page) using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in issue comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist is currently in preview and may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments to provide feedback.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link
Copy Markdown

@sourcery-ai sourcery-ai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey @Silentely - I've reviewed your changes - here's some feedback:

  • In CreateAndAddBatchTGFileTaskWithEdit you build album tasks using the outer-scoped dirPath, which may have been overwritten in the loop; consider storing each file's computed dirPath alongside it so you don’t rely on a single loop variable when creating album directories.
  • The timer callback in handleGroupMediaMessage captures the original ctx and update by reference, which can lead to stale or invalid state when it fires; extract only the necessary values into the closure or clone the data to avoid race conditions.
  • While MediaGroupHandler protects its maps with a mutex, the processing function runs asynchronously without coordinating with the main dispatcher; ensure any shared state or context operations in processMediaGroup are properly synchronized or error-handled to prevent data races.
Prompt for AI Agents
Please address the comments from this code review:
## Overall Comments
- In CreateAndAddBatchTGFileTaskWithEdit you build album tasks using the outer-scoped `dirPath`, which may have been overwritten in the loop; consider storing each file's computed `dirPath` alongside it so you don’t rely on a single loop variable when creating album directories.
- The timer callback in `handleGroupMediaMessage` captures the original `ctx` and `update` by reference, which can lead to stale or invalid state when it fires; extract only the necessary values into the closure or clone the data to avoid race conditions.
- While MediaGroupHandler protects its maps with a mutex, the processing function runs asynchronously without coordinating with the main dispatcher; ensure any shared state or context operations in `processMediaGroup` are properly synchronized or error-handled to prevent data races.

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

@Silentely Silentely merged commit d53914b into main Jul 4, 2025
3 of 4 checks passed
Copy link
Copy Markdown

@gemini-code-assist gemini-code-assist Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces significant new features, including support for Telegram media groups and userbot integration, along with several other enhancements. I've found two high-severity correctness bugs in the new album-handling logic that could lead to files not being saved or being saved in the wrong location. I've also provided several medium-severity recommendations to improve maintainability. Addressing these points will greatly improve the quality and robustness of the new features.

Comment on lines +161 to +163
if len(afiles) <= 1 {
continue
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

The current logic skips processing for albums that contain only one file (len(afiles) <= 1). This means if a user sends a single file that matches an IS-ALBUM rule with NEW-FOR-ALBUM, the file will be dropped and not saved. This is a bug, as the user would expect the file to be saved, even if it's a single-item album. To fix this, you should remove this condition to ensure all matching files are processed.

albumDir := strings.TrimSuffix(path.Base(afiles[0].file.Name()), path.Ext(afiles[0].file.Name()))
albumStor := afiles[0].storage
for _, af := range afiles {
afstorPath := af.storage.JoinStoragePath(path.Join(dirPath, albumDir, af.file.Name()))
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

There is a logic error in how the storage path is constructed for album files. The dirPath variable is not being used correctly when joining the storage path. The path should be constructed from the generated albumDir and the filename.

Suggested change
afstorPath := af.storage.JoinStoragePath(path.Join(dirPath, albumDir, af.file.Name()))
afstorPath := af.storage.JoinStoragePath(path.Join(albumDir, af.file.Name()))

Comment on lines +97 to +99
if mediaGroupHandler.groups[groupID] == nil {
mediaGroupHandler.groups[groupID] = make([]tfile.TGFileMessage, 0)
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The check for a nil slice before appending is redundant. In Go, append can be safely called on a nil slice, and it will automatically allocate a new underlying array. Removing this check simplifies the code.

	mediaGroupHandler.groups[groupID] = append(mediaGroupHandler.groups[groupID], file)

Comment thread storage/minio/client.go
candidate := storagePath
for i := 1; m.Exists(ctx, candidate); i++ {
candidate = fmt.Sprintf("%s_%d%s", base, i, ext)
if i > 1000 {
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The value 1000 is a magic number that determines the maximum number of attempts to find a unique filename. To improve code clarity, it's best to define this as a package-level constant.

Comment thread storage/webdav/webdav.go
candidate := storagePath
for i := 1; w.Exists(ctx, candidate); i++ {
candidate = fmt.Sprintf("%s_%d%s", base, i, ext)
if i > 1000 {
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The value 1000 is a magic number that determines the maximum number of attempts to find a unique filename. To improve code clarity, it's best to define this as a package-level constant.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants