Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: replace class-based handlers with function-based handlers #262

Merged
merged 8 commits into from
Sep 1, 2024

Conversation

HitaloM
Copy link
Owner

@HitaloM HitaloM commented Aug 25, 2024

Summary by Sourcery

Refactor the codebase to replace class-based handlers with function-based handlers, enhancing the handling of commands and events. Introduce new features for media handling and LastFM integration, and improve error handling and configuration management. Update the pre-commit configuration for better code quality checks.

New Features:

  • Introduce function-based handlers across the codebase, replacing class-based handlers to streamline the handling of various commands and events.
  • Add support for handling YouTube download requests with improved error handling and media type selection.
  • Implement a new system for managing and processing Twitter, TikTok, and Instagram media links, enhancing media handling capabilities.
  • Introduce a new command for setting LastFM usernames, allowing users to link their LastFM accounts more efficiently.

Enhancements:

  • Refactor the entire codebase to replace class-based handlers with function-based handlers, improving code readability and maintainability.
  • Enhance the error handling mechanism to provide more detailed feedback and logging for exceptions.
  • Improve the configuration management by refactoring the initialization process for better clarity and error handling.
  • Optimize the process of fetching and displaying user and group information by refining database queries and error handling.

Build:

  • Update the pre-commit configuration to use the latest version of the ruff-pre-commit hook for code formatting and linting.

@HitaloM HitaloM added the enhancement New feature or request label Aug 25, 2024
Copy link

sourcery-ai bot commented Aug 25, 2024

Reviewer's Guide by Sourcery

This pull request refactors the entire codebase to replace class-based handlers with function-based handlers. The changes aim to simplify the architecture, improve maintainability, and streamline the code structure. The refactoring affects various modules, including handlers for commands, callbacks, and error handling.

File-Level Changes

Change Details Files
Replaced class-based handlers with function-based handlers
  • Removed abstract handler classes
  • Converted handler methods to standalone functions
  • Updated router decorators to use function-based handlers
  • Simplified handler logic and removed redundant code
src/korone/modules/core.py
src/korone/decorators/factory.py
src/korone/handlers/error_handler.py
Refactored utility functions and helper methods
  • Moved helper functions out of classes into module-level functions
  • Simplified and consolidated utility functions
  • Improved type hinting and error handling in utility functions
src/korone/modules/stickers/utils/kang.py
src/korone/modules/translator/utils/helpers.py
src/korone/modules/gsm_arena/utils/scraper.py
Updated callback data structures and enums
  • Replaced string-based enums with StrEnum
  • Updated callback data classes to use new enum types
  • Simplified callback data structures
src/korone/modules/filters/callback_data.py
src/korone/modules/languages/callback_data.py
src/korone/modules/pm_menu/callback_data.py
src/korone/modules/medias/callback_data.py
Improved error handling and logging
  • Enhanced error messages and exception handling
  • Simplified error handling logic
  • Improved logging of errors and exceptions
src/korone/modules/errors/handlers/catcher.py
src/korone/config.py
Refactored database operations
  • Simplified database query operations
  • Removed redundant query object creation
  • Improved type hinting for database operations
src/korone/modules/filters/database.py
src/korone/modules/languages/database.py
src/korone/modules/lastfm/database.py
src/korone/modules/disabling/database.py
Updated command handling and routing
  • Simplified command handling logic
  • Updated router decorators for function-based handlers
  • Improved command argument parsing
src/korone/modules/pm_menu/handlers/start.py
src/korone/modules/languages/handlers/select.py
src/korone/modules/sudo/handlers/ping.py
Refactored media handling modules
  • Simplified media processing logic
  • Improved error handling in media processing
  • Updated media type detection and handling
src/korone/modules/medias/handlers/youtube.py
src/korone/modules/medias/handlers/tiktok.py
src/korone/modules/medias/handlers/instagram.py

Tips
  • Trigger a new Sourcery review by commenting @sourcery-ai review on the pull request.
  • Continue your discussion with Sourcery by replying directly to review comments.
  • You can change your review settings at any time by accessing your dashboard:
    • Enable or disable the Sourcery-generated pull request summary or reviewer's guide;
    • Change the review language;
  • You can always contact us if you have any questions or feedback.

Copy link

@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 @HitaloM - I've reviewed your changes and they look great!

Here's what I looked at during the review
  • 🟢 General issues: all looks good
  • 🟢 Security: all looks good
  • 🟢 Testing: all looks good
  • 🟡 Complexity: 1 issue found
  • 🟢 Documentation: all looks good

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 to tell me if it was helpful.

src/korone/modules/filters/handlers/delall.py Show resolved Hide resolved
src/korone/modules/errors/handlers/test.py Outdated Show resolved Hide resolved
src/korone/modules/errors/handlers/catcher.py Outdated Show resolved Hide resolved
src/korone/modules/filters/handlers/delete.py Outdated Show resolved Hide resolved
src/korone/modules/medias/handlers/tiktok.py Outdated Show resolved Hide resolved
src/korone/modules/medias/handlers/twitter.py Outdated Show resolved Hide resolved
src/korone/modules/regex/handlers/sed.py Outdated Show resolved Hide resolved
src/korone/modules/sudo/handlers/updater.py Outdated Show resolved Hide resolved
@HitaloM
Copy link
Owner Author

HitaloM commented Aug 25, 2024

@sourcery-ai review

@HitaloM HitaloM changed the title refactor(modules): use imperative style instead of classes Refactor the entire codebase to replace class-based handlers with function-based handlers. Aug 25, 2024
Copy link

@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 @HitaloM - I've reviewed your changes and they look great!

Here's what I looked at during the review
  • 🟡 General issues: 1 issue found
  • 🟢 Security: all looks good
  • 🟢 Testing: all looks good
  • 🟡 Complexity: 1 issue found
  • 🟢 Documentation: all looks good

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 to tell me if it was helpful.

src/korone/modules/afk/handlers/check.py Show resolved Hide resolved
src/korone/modules/logging/handlers/groups.py Outdated Show resolved Hide resolved
src/korone/modules/sudo/handlers/updater.py Outdated Show resolved Hide resolved
@HitaloM
Copy link
Owner Author

HitaloM commented Aug 27, 2024

@sourcery-ai review

Copy link

@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 @HitaloM - I've reviewed your changes and they look great!

Here's what I looked at during the review
  • 🟡 General issues: 3 issues found
  • 🟢 Security: all looks good
  • 🟢 Testing: all looks good
  • 🟡 Complexity: 1 issue found
  • 🟢 Documentation: all looks good

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 to tell me if it was helpful.

src/korone/modules/core.py Show resolved Hide resolved
src/korone/utils/pagination.py Show resolved Hide resolved
src/korone/modules/filters/callback_data.py Show resolved Hide resolved
src/korone/modules/filters/handlers/delall.py Outdated Show resolved Hide resolved
src/korone/modules/languages/handlers/apply.py Outdated Show resolved Hide resolved
src/korone/modules/lastfm/utils/parse_collage.py Outdated Show resolved Hide resolved
src/korone/modules/medias/handlers/youtube.py Outdated Show resolved Hide resolved
src/korone/modules/sudo/handlers/updater.py Outdated Show resolved Hide resolved
src/korone/modules/users_groups/handlers/cleanup.py Outdated Show resolved Hide resolved
@HitaloM
Copy link
Owner Author

HitaloM commented Aug 31, 2024

@sourcery-ai review

Copy link

@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 @HitaloM - I've reviewed your changes and they look great!

Here's what I looked at during the review
  • 🟡 General issues: 5 issues found
  • 🟢 Security: all looks good
  • 🟢 Testing: all looks good
  • 🟡 Complexity: 1 issue found
  • 🟡 Documentation: 1 issue found

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 to tell me if it was helpful.

return None


async def send_media(
Copy link

Choose a reason for hiding this comment

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

suggestion: Consider breaking down the send_media function into smaller helper functions

The send_media function contains a lot of conditional logic. Consider breaking it down into smaller helper functions to improve readability and maintainability. This could also make the code easier to test.

async def send_media(client: Client, message: Message):
    return await _process_and_send_media(client, message)

async def _process_and_send_media(client: Client, message: Message):


async def register_handler(client: Client, func: FunctionType) -> bool:
Copy link

Choose a reason for hiding this comment

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

suggestion: Consider adding type hints for the 'handlers' attribute

To improve type checking and code clarity, consider adding type hints for the 'handlers' attribute of the func parameter. This could be done using a Protocol or a custom type.

from typing import Protocol, Callable

class HandlerProtocol(Protocol):
    handlers: list[Callable]

async def register_handler(client: Client, func: HandlerProtocol) -> bool:
    successful = False

src/korone/modules/languages/handlers/info.py Show resolved Hide resolved
@@ -20,7 +20,7 @@ class TwitterError(Exception):
async def fetch_tweet(url: str) -> Tweet | None:
fx_url = re.sub(r"(www\.|)(twitter\.com|x\.com)", "api.fxtwitter.com", url)
try:
async with httpx.AsyncClient(http2=True) as client:
async with httpx.AsyncClient(http2=True, timeout=20) as client:
Copy link

Choose a reason for hiding this comment

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

suggestion (performance): Consider if 20 seconds is an appropriate timeout for this API call

Suggested change
async with httpx.AsyncClient(http2=True, timeout=20) as client:
async with httpx.AsyncClient(http2=True, timeout=10) as client:

@@ -0,0 +1,226 @@
# SPDX-License-Identifier: BSD-3-Clause
Copy link

Choose a reason for hiding this comment

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

suggestion: Consider breaking down the functionality in kang.py into smaller, more manageable functions

# SPDX-License-Identifier: BSD-3-Clause
# Copyright (c) 2024 Hitalo M. <https://github.com/HitaloM>

from typing import List

def process_sticker(sticker_data: bytes) -> bytes:
    # Process sticker logic here
    pass

def create_sticker_set(name: str, stickers: List[bytes]) -> bool:
    # Create sticker set logic here
    pass

src/korone/modules/core.py Show resolved Hide resolved
src/korone/modules/users_groups/handlers/cleanup.py Outdated Show resolved Hide resolved
src/korone/modules/languages/handlers/info.py Outdated Show resolved Hide resolved
await message.reply(_("Reply to a message to get the compatibility!"))
return
@router.message(Command("lfmcompat"))
async def lfmcompat_command(client: Client, message: Message) -> None: # noqa: C901, PLR0912
Copy link

Choose a reason for hiding this comment

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

issue (code-quality): Low code quality found in lfmcompat_command - 23% (low-code-quality)


ExplanationThe quality score for this function is below the quality threshold of 25%.
This score is a combination of the method length, cognitive complexity and working memory.

How can you solve this?

It might be worth refactoring this function to make it shorter and more readable.

  • Reduce the function length by extracting pieces of functionality out into
    their own functions. This is the most important thing you can do - ideally a
    function should be less than 10 lines.
  • Reduce nesting, perhaps by introducing guard clauses to return early.
  • Ensure that variables are tightly scoped, so that code using related concepts
    sits together within the function rather than being scattered.

@HitaloM HitaloM merged commit 538619f into dev Sep 1, 2024
2 checks passed
@HitaloM HitaloM changed the title Refactor the entire codebase to replace class-based handlers with function-based handlers. refactor: replace class-based handlers with function-based handlers Sep 1, 2024
@HitaloM HitaloM deleted the less-oop branch September 1, 2024 00:20
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant