Skip to content

refactor kick a bit: consolidate token refresh and fix failing tests #1204

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

Merged
merged 3 commits into from
Jun 21, 2025

Conversation

aw-was-here
Copy link
Collaborator

@aw-was-here aw-was-here commented Jun 21, 2025

  • Consolidate duplicated token refresh logic from chat.py/launch.py into utils.py
  • Add attempt_token_refresh() function to replace individual OAuth method calls
  • Change redirect URI from user-editable lineedit to auto-generated label
  • Update OAuth2 to use correct /public/v1/token/introspect endpoint (POST)
  • Fix broken help URL reference to use "Developer tab in streamer settings"
  • Add real-time OAuth status updates with 30s QTimer
  • Update tests to mock consolidated function instead of individual OAuth methods
  • Fix test expectations for redirecturi_label and port 8899 default
  • Remove 6 obsolete tests that were testing implementation details
  • Simplify authentication test scenarios from complex flows to success/failure

Summary by Sourcery

Centralize OAuth token handling by consolidating refresh and validation logic into a single utility function, auto-generate the redirect URI, add live status polling, update chat and launch flows to use the new function, and adjust tests and UI accordingly.

New Features:

  • Add attempt_token_refresh() in utils to unify token validation and refresh across components
  • Auto-generate and display redirect URI based on webserver port instead of user input
  • Introduce a QTimer to provide real-time OAuth status updates every 30 seconds
  • Include application version and platform info in the chat connection message

Bug Fixes:

  • Fix failing tests by updating expectations for redirect URI label and default port
  • Correct help URL reference text to "Developer tab in streamer settings"

Enhancements:

  • Refactor chat and launch authentication to use the consolidated token refresh utility
  • Update OAuth2 validation to use POST against /public/v1/token/introspect endpoint
  • Remove manual redirect URI handling and persistence in settings

Tests:

  • Remove obsolete tests targeting internal OAuth methods and simplify scenarios to success/failure
  • Update tests to mock attempt_token_refresh() instead of individual validation and refresh calls
  • Parameterize authentication tests to cover both refresh success and failure

Copy link

sourcery-ai bot commented Jun 21, 2025

Reviewer's Guide

This PR refactors Kick OAuth handling by centralizing token refresh into a new async utility, simplifying UI redirect URI management with an auto‐generated label, updating token introspection to the correct POST endpoint, adding a periodic status timer for real‐time updates in the settings UI, and cleaning up tests to mock the consolidated logic and drop obsolete cases.

Sequence diagram for consolidated token refresh in chat/launch

sequenceDiagram
    participant ChatOrLaunch as Chat/Launch
    participant Utils as attempt_token_refresh
    participant KickOAuth2
    participant Config as ConfigFile
    ChatOrLaunch->>Utils: await attempt_token_refresh(config)
    Utils->>KickOAuth2: new KickOAuth2(config)
    Utils->>KickOAuth2: get_stored_tokens()
    alt Access token present
        Utils->>KickOAuth2: validate_token(access_token)
        alt Token valid
            Utils-->>ChatOrLaunch: return True
        else Token invalid
            alt Refresh token present
                Utils->>KickOAuth2: refresh_access_token(refresh_token)
                Utils-->>ChatOrLaunch: return True
            else No refresh token
                Utils-->>ChatOrLaunch: return False
            end
        end
    else No access token
        Utils-->>ChatOrLaunch: return False
    end
Loading

Class diagram for consolidated Kick OAuth token refresh

classDiagram
    class KickOAuth2 {
        +get_stored_tokens() tuple[str|None, str|None]
        +refresh_access_token(refresh_token)
        +validate_token(token)
        +revoke_token(token)
        access_token
        refresh_token
        config
    }
    class ConfigFile
    class Utils {
        +attempt_token_refresh(config: ConfigFile) bool
        +validate_kick_token_async(config: ConfigFile, access_token: str|None) dict|None
        +qtsafe_validate_kick_token(access_token: str) bool
    }
    KickOAuth2 <.. Utils : uses
    ConfigFile <.. KickOAuth2 : used by
    ConfigFile <.. Utils : used by
Loading

Class diagram for KickSettings UI changes

classDiagram
    class KickSettings {
        widget
        oauth
        refresh_token
        status_timer
        +connect(uihelp, widget)
        +load(config, widget)
        +save(config, widget, subprocesses)
        +verify(widget)
        +authenticate_oauth()
        +start_status_timer()
        +stop_status_timer()
        +cleanup()
        +update_oauth_status()
    }
    class QTimer
    KickSettings --> QTimer : manages
    KickSettings --> KickOAuth2 : uses
    KickSettings --> ConfigFile : uses
Loading

File-Level Changes

Change Details Files
Centralize OAuth token refresh logic
  • Introduce async attempt_token_refresh in utils.py
  • Replace direct validate/refresh calls in chat.py with attempt_token_refresh
  • Replace direct validate/refresh calls in launch.py with attempt_token_refresh
nowplaying/kick/utils.py
nowplaying/kick/chat.py
nowplaying/kick/launch.py
Simplify redirect URI in settings UI
  • Remove editable redirecturi_lineedit and use auto‐generated redirecturi_label
  • Generate redirect URI from webserver port in load/save/auth flows
  • Remove manual redirect URI validation and saving
nowplaying/kick/settings.py
Add real‐time OAuth status updates
  • Add status_timer attribute and QTimer setup in settings
  • Implement start_status_timer, stop_status_timer, and cleanup methods
  • Trigger update_oauth_status every 30 seconds
nowplaying/kick/settings.py
Use correct token introspection endpoint
  • Change sync qtsafe_validate_kick_token to POST /public/v1/token/introspect
  • Update async validate_token in oauth2.py to use POST introspect and check 'active'
  • Adjust tests in test_kick_oauth2.py for new URL and payload structure
nowplaying/kick/utils.py
nowplaying/kick/oauth2.py
tests/kick/test_kick_oauth2.py
Refactor tests to reflect consolidated OAuth logic
  • Remove obsolete fixtures and tests tied to implementation details
  • Mock attempt_token_refresh instead of individual OAuth methods
  • Simplify parameterized authentication tests and update settings tests for redirecturi_label
tests/kick/test_kick_integration.py
tests/kick/test_kick_launch.py
tests/kick/test_kick_chat.py
tests/kick/test_kick_settings.py

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

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 @aw-was-here - I've reviewed your changes - here's some feedback:

  • Ensure Settings.cleanup() is wired up to be called when the UI closes so the QTimer is stopped and doesn’t leak resources.
  • Add a test covering non-default webserver ports to verify the auto-generated redirect URI logic works for all configured ports.
  • Consider unifying the sync and async token-introspection implementations to reduce duplicate endpoint handling logic.
Prompt for AI Agents
Please address the comments from this code review:
## Overall Comments
- Ensure Settings.cleanup() is wired up to be called when the UI closes so the QTimer is stopped and doesn’t leak resources.
- Add a test covering non-default webserver ports to verify the auto-generated redirect URI logic works for all configured ports.
- Consider unifying the sync and async token-introspection implementations to reduce duplicate endpoint handling logic.

## Individual Comments

### Comment 1
<location> `nowplaying/kick/settings.py:49` </location>
<code_context>
         # Initialize OAuth2 handler
         self.oauth = nowplaying.kick.oauth2.KickOAuth2(config)
         self.update_oauth_status()
+        self.start_status_timer()

     @staticmethod
</code_context>

<issue_to_address>
Consider stopping the status timer when the settings UI is closed.

Ensure the cleanup method reliably stops the timer whenever the settings UI is closed to avoid background processes persisting.

Suggested implementation:

```python
        self.start_status_timer()

```

```python
    def stop_status_timer(self):
        """Stop the status timer if it is running."""
        if hasattr(self, 'status_timer') and self.status_timer is not None:
            self.status_timer.stop()
            self.status_timer = None

    @staticmethod

```

You will also need to:
1. Call `self.stop_status_timer()` in the method that handles the closing or cleanup of the settings UI (e.g., in a `closeEvent`, `cleanup`, or equivalent method for your settings dialog/class).
2. Ensure that `self.status_timer` is the QTimer instance started in `start_status_timer()`.

If you provide the relevant cleanup/close method, I can show the exact code to insert the call.
</issue_to_address>

### Comment 2
<location> `nowplaying/kick/utils.py:61` </location>
<code_context>
+    return await oauth.validate_token(access_token)
+

 def qtsafe_validate_kick_token(access_token: str) -> bool:
-    ''' validate kick token synchronously (shared by settings and launch) '''
+    ''' Validate kick token synchronously (Qt-safe for UI components) '''
</code_context>

<issue_to_address>
Consider handling network errors explicitly in qtsafe_validate_kick_token.

Returning False for network errors makes them indistinguishable from invalid tokens. Logging or surfacing these errors would improve diagnostics.
</issue_to_address>

### Comment 3
<location> `nowplaying/kick/oauth2.py:276` </location>
<code_context>
+        async with aiohttp.ClientSession() as session:
</code_context>

<issue_to_address>
Consider handling non-200/401 HTTP responses more robustly in validate_token.

Logging unexpected HTTP errors as warnings or errors will make troubleshooting API issues easier.
</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.

Copy link

codecov bot commented Jun 21, 2025

Codecov Report

Attention: Patch coverage is 73.68421% with 20 lines in your changes missing coverage. Please review.

Project coverage is 66.54%. Comparing base (e9202c9) to head (d6e29ca).

Files with missing lines Patch % Lines
nowplaying/kick/utils.py 68.96% 9 Missing ⚠️
nowplaying/kick/settings.py 75.00% 6 Missing ⚠️
nowplaying/kick/chat.py 66.66% 3 Missing ⚠️
nowplaying/kick/oauth2.py 83.33% 2 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main    #1204      +/-   ##
==========================================
- Coverage   66.56%   66.54%   -0.02%     
==========================================
  Files          63       63              
  Lines       10697    10714      +17     
==========================================
+ Hits         7120     7130      +10     
- Misses       3577     3584       +7     
Flag Coverage Δ
unittests 66.54% <73.68%> (-0.02%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

Files with missing lines Coverage Δ
nowplaying/kick/launch.py 65.00% <100.00%> (-4.50%) ⬇️
nowplaying/kick/oauth2.py 90.04% <83.33%> (-0.68%) ⬇️
nowplaying/kick/chat.py 70.94% <66.66%> (-0.39%) ⬇️
nowplaying/kick/settings.py 88.47% <75.00%> (-1.40%) ⬇️
nowplaying/kick/utils.py 85.00% <68.96%> (-15.00%) ⬇️

... and 2 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

* Consolidate duplicated token refresh logic from chat.py/launch.py into utils.py
* Add attempt_token_refresh() function to replace individual OAuth method calls
* Change redirect URI from user-editable lineedit to auto-generated label
* Update OAuth2 to use correct /public/v1/token/introspect endpoint (POST)
* Fix broken help URL reference to use "Developer tab in streamer settings"
* Add real-time OAuth status updates with 30s QTimer
* Update tests to mock consolidated function instead of individual OAuth methods
* Fix test expectations for redirecturi_label and port 8899 default
* Remove 6 obsolete tests that were testing implementation details
* Simplify authentication test scenarios from complex flows to success/failure
@aw-was-here aw-was-here merged commit 92aee8b into main Jun 21, 2025
12 checks passed
@aw-was-here aw-was-here deleted the kick_is_broken branch June 21, 2025 16:13
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.

1 participant