Skip to content

Origin#25

Merged
Silentely merged 5 commits intomainfrom
origin
Jul 9, 2025
Merged

Origin#25
Silentely merged 5 commits intomainfrom
origin

Conversation

@Silentely
Copy link
Copy Markdown
Member

@Silentely Silentely commented Jul 9, 2025

Summary by Sourcery

Streamline the TOML example configuration, refine Telegram storage and message utilities, and simplify retry middleware error handling

Enhancements:

  • Clean up and reorganize config.example.toml with updated comments and storage/user sections
  • Handle Telegram chat IDs with “-100” prefix when saving files in storage/telegram
  • Use GetMediaFileNameWithId to generate non-empty filenames from message media in GenFileNameFromMessage
  • Simplify retry middleware by removing error wrapping and directly returning the original error

Summary by CodeRabbit

  • Bug Fixes

    • Improved filename generation for messages to better handle media files and ensure non-empty filenames.
    • Enhanced chat ID handling for Telegram storage, allowing support for IDs with the "-100" prefix.
  • Documentation

    • Cleaned up and clarified the example configuration file, removing deprecated storage examples and improving comments for easier setup and understanding.
  • Refactor

    • Simplified error handling in retry middleware by removing additional error context wrapping.

@sourcery-ai
Copy link
Copy Markdown

sourcery-ai Bot commented Jul 9, 2025

Reviewer's Guide

This PR reorganizes and modernizes the example configuration, enhances Telegram storage and message utilities, and simplifies retry middleware error handling.

Entity relationship diagram for revised config user and storage structure

erDiagram
    USERS {
        int id
        string[] storages
        bool blacklist
    }
    STORAGES {
        string name
        string type
        bool enable
        string base_path
        string url
        string username
        string password
        %% ... other storage-specific fields
    }
    USERS ||--o{ STORAGES : can_access

    %% Changes:
    %% - USERS now have a 'storages' list and 'blacklist' flag
    %% - STORAGES can be of type local, alist, webdav, minio, telegram
Loading

Class diagram for updated Telegram storage and message utilities

classDiagram
    class Telegram {
        +Save(ctx, r, storagePath) error
    }
    class TelegramConfig {
        +ChatID int64
    }
    class TelegramContext {
        +PeerStorage PeerStorage
    }
    class PeerStorage {
        +GetInputPeerById(chatID)
    }
    class functions {
        +GetMediaFileNameWithId(media) (string, error)
    }
    class tgutil {
        +GenFileNameFromMessage(message) string
    }

    Telegram --> TelegramConfig
    Telegram --> TelegramContext
    TelegramContext --> PeerStorage
    tgutil --> functions: uses

    %% Highlighted changes:
    %% - Telegram.Save now normalizes chatID with CutPrefix and ParseInt
    %% - tgutil.GenFileNameFromMessage uses functions.GetMediaFileNameWithId for improved filename extraction
Loading

Class diagram for retry middleware error handling update

classDiagram
    class retry {
        +Handle(next tg.Invoker) telegram.InvokeFunc
    }
    retry : - errors.Wrap removed
    retry : + returns err directly on skip

    %% The retry middleware now returns the error directly instead of wrapping it with errors.Wrap
Loading

File-Level Changes

Change Details Files
Cleaned up and expanded the example configuration file
  • Removed outdated examples and commented sections
  • Added link to external documentation
  • Improved comments for stream mode and storage types
  • Reformatted users and storages blocks with clearer blacklist/whitelist instructions
config.example.toml
Enhanced Telegram storage Save function to handle ‘-100’ chat ID prefixes
  • Imported string utilities and converter
  • Stripped ‘-100’ prefix and parsed remaining ID
  • Adjusted peer lookup and error reporting
storage/telegram/telegram.go
Improved file naming in message utility using media metadata
  • Imported new functions package
  • Attempted to fetch original media filename
  • Fell back to ID+UUID when no name returned
common/utils/tgutil/message.go
Simplified retry middleware error return
  • Removed errors.Wrap to drop extra dependency
  • Directly returned original error with comment
client/middleware/retry/retry.go

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 9, 2025

Caution

Review failed

The pull request is closed.

Walkthrough

The changes update error handling in the retry middleware, enhance fallback logic for generating filenames from Telegram messages, normalize chat ID parsing for Telegram storage, and significantly simplify the example configuration file by removing deprecated sections and improving clarity of comments and structure.

Changes

File(s) Change Summary
client/middleware/retry/retry.go Removed use of github.com/go-faster/errors; now returns original error directly with a clarifying comment.
common/utils/tgutil/message.go Improved fallback filename logic by attempting to extract a media filename before generating a unique one.
storage/telegram/telegram.go Added normalization for chat ID by stripping "-100" prefix and parsing as int64 before peer retrieval.
config.example.toml Cleaned up and simplified; removed deprecated storage configs, clarified comments, improved structure.

Poem

In fields of code, the changes grow,
Old configs trimmed, new logic flows.
Chat IDs now parsed with care,
Filenames smarter, errors bare.
A rabbit hops with glee to see,
The garden of code, neat as can be! 🐇✨


📜 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 d53914b and fcc8ff3.

📒 Files selected for processing (4)
  • client/middleware/retry/retry.go (1 hunks)
  • common/utils/tgutil/message.go (3 hunks)
  • config.example.toml (2 hunks)
  • storage/telegram/telegram.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.

@Silentely Silentely merged commit dfc1285 into main Jul 9, 2025
3 of 5 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.

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 focuses on refining core functionalities and improving the user experience through several targeted enhancements. It addresses how media files are named upon download, simplifies error handling in network operations, and ensures more robust interaction with Telegram chat IDs. Additionally, the example configuration has been cleaned up to provide clearer guidance for users.

Highlights

  • File Naming & Media Handling: Improved filename generation for downloaded media by attempting to extract meaningful names from Telegram message media, falling back to a generic ID if a specific name isn't available.
  • Error Handling: Simplified error propagation within the retry middleware by removing external error wrapping and returning the original error directly.
  • Configuration: Updated and streamlined the config.example.toml file, clarifying comments, removing outdated or less common examples, and reordering sections for better readability.
  • Telegram Integration: Enhanced the Telegram storage backend to correctly parse and handle Telegram channel/supergroup IDs, which often include a -100 prefix, ensuring proper peer resolution.
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:

  • The chat ID normalization in storage/telegram/telegram.go feels convoluted—consider handling the “-100” prefix directly on the int64 or centralizing this logic to avoid round-trip string conversions.
  • In retry middleware, removing errors.Wrap loses error context—consider wrapping the error again (e.g. with fmt.Errorf("retry middleware skip: %w", err)) to retain diagnostic information.
  • The fallback in GenFileNameFromMessage duplicates the default naming logic; you could simplify by inlining the GetMediaFileNameWithId call and falling back directly in one expression to reduce branching.
Prompt for AI Agents
Please address the comments from this code review:
## Overall Comments
- The chat ID normalization in storage/telegram/telegram.go feels convoluted—consider handling the “-100” prefix directly on the int64 or centralizing this logic to avoid round-trip string conversions.
- In retry middleware, removing errors.Wrap loses error context—consider wrapping the error again (e.g. with fmt.Errorf("retry middleware skip: %w", err)) to retain diagnostic information.
- The fallback in GenFileNameFromMessage duplicates the default naming logic; you could simplify by inlining the GetMediaFileNameWithId call and falling back directly in one expression to reduce branching.

## Individual Comments

### Comment 1
<location> `common/utils/tgutil/message.go:89` </location>
<code_context>

 	if filename == "" {
-		filename = fmt.Sprintf("%d_%s", message.GetID(), xid.New().String())
+		mname, err := functions.GetMediaFileNameWithId(message.Media)
+		if err != nil {
+			filename = fmt.Sprintf("%d_%s", message.GetID(), xid.New().String())
+		} else {
+			filename = mname
+		}
+
</code_context>

<issue_to_address>
The fallback to a generated filename is good, but the new logic may overwrite a valid filename with an empty string if GetMediaFileNameWithId returns an empty value without error.

Check that mname is not empty before assigning it to filename, or ensure GetMediaFileNameWithId never returns an empty string on success.
</issue_to_address>

### Comment 2
<location> `config.example.toml:54` </location>
<code_context>
+[[users]]
+id = 123456
+storages = ["本机1"]
+blacklist = false  # 使用白名单模式,此时,用户 123456 仅可使用标识名为 '本地1' 的存储
\ No newline at end of file
</code_context>

<issue_to_address>
There is a mismatch between the storage name in the whitelist and the defined storage name.

The example should use the correct storage name to prevent user confusion or misconfiguration.
</issue_to_address>

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.

Comment on lines +89 to +93
mname, err := functions.GetMediaFileNameWithId(message.Media)
if err != nil {
filename = fmt.Sprintf("%d_%s", message.GetID(), xid.New().String())
} else {
filename = mname
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

issue (bug_risk): The fallback to a generated filename is good, but the new logic may overwrite a valid filename with an empty string if GetMediaFileNameWithId returns an empty value without error.

Check that mname is not empty before assigning it to filename, or ensure GetMediaFileNameWithId never returns an empty string on success.

Comment thread config.example.toml
[[users]]
id = 123456
storages = ["本机1"]
blacklist = false # 使用白名单模式,此时,用户 123456 仅可使用标识名为 '本地1' 的存储 No newline at end of file
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

issue: There is a mismatch between the storage name in the whitelist and the defined storage name.

The example should use the correct storage name to prevent user confusion or misconfiguration.

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

The pull request streamlines the TOML example configuration, refines Telegram storage and message utilities, and simplifies retry middleware error handling. The changes include cleaning up the config.example.toml file, handling Telegram chat IDs with the “-100” prefix, using GetMediaFileNameWithId to generate filenames, and simplifying retry middleware error handling. The feedback focuses on improving error handling, filename generation, and chat ID parsing.

Comment on lines +39 to +40
// retry middleware skip
return err
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

Returning the error directly without any context might make debugging harder. Consider adding some context to the error message, even if it's just a simple string indicating that the error occurred during a retry attempt.

Suggested change
// retry middleware skip
return err
// retry middleware skip
return fmt.Errorf("retry middleware skip: %w", err)

Comment on lines +89 to +94
mname, err := functions.GetMediaFileNameWithId(message.Media)
if err != nil {
filename = fmt.Sprintf("%d_%s", message.GetID(), xid.New().String())
} else {
filename = mname
}
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 GetMediaFileNameWithId function might return an empty string or an invalid filename. It would be beneficial to add a check for this and fallback to the default filename generation if necessary. This will prevent empty or invalid filenames from being used.

Suggested change
mname, err := functions.GetMediaFileNameWithId(message.Media)
if err != nil {
filename = fmt.Sprintf("%d_%s", message.GetID(), xid.New().String())
} else {
filename = mname
}
mname, err := functions.GetMediaFileNameWithId(message.Media)
if err != nil || mname == "" {
filename = fmt.Sprintf("%d_%s", message.GetID(), xid.New().String())
} else {
filename = mname
}

Comment on lines +77 to +82
if after, ok0 := strings.CutPrefix(convertor.ToString(chatID), "-100"); ok0 {
cid, err := strconv.ParseInt(after, 10, 64)
if err != nil {
return fmt.Errorf("failed to parse chat ID: %w", err)
}
chatID = cid
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 code parses the chat ID from a string, but it doesn't handle the case where the chat ID is already an integer. This could lead to unnecessary string conversions and potential errors. Consider checking if the chat ID is already an integer before attempting to parse it from a string.

chatID := t.config.ChatID
if chatID < 0 && strings.HasPrefix(convertor.ToString(chatID), "-100") {
	after := convertor.ToString(chatID)[4:] // Remove "-100"
	cid, err := strconv.ParseInt(after, 10, 64)
	if err != nil {
		return fmt.Errorf("failed to parse chat ID: %w", err)
	}
	chatID = cid
}

@Silentely Silentely deleted the origin branch July 9, 2025 10:46
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