Skip to content

Conversation

@iamEvanYT
Copy link
Member

@iamEvanYT iamEvanYT commented May 10, 2025

Summary by CodeRabbit

  • New Features

    • Introduced a built-in content blocker with adjustable settings, allowing users to block ads, trackers, and other unwanted content.
    • Added a new option in general settings to configure the content blocker, with choices ranging from disabled to blocking all ads, trackers, and cookie notices.
  • Chores

    • Updated dependencies to include the content blocker package.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented May 10, 2025

Walkthrough

A built-in content blocker feature was integrated into the application. This involved updating dependencies, adding a new settings option for content blocking, introducing a ContentBlocker class to manage blocking logic, initializing the blocker during app startup, and extending debug output areas to include the content blocker.

Changes

File(s) Change Summary
package.json Added @ghostery/adblocker-electron dependency at version ^2.5.2.
src/main/index.ts Imported the new content blocker module to ensure initialization during app startup.
src/main/modules/basic-settings.ts Added a "Content Blocker" enum setting to general settings and inserted it into the settings card configuration.
src/main/modules/content-blocker.ts Introduced the ContentBlocker class for managing ad/tracker blocking based on user settings and session events.
src/main/modules/output.ts Added CONTENT_BLOCKER to the DEBUG_AREAS constant and fixed object syntax.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Settings
    participant ContentBlocker
    participant ElectronSession
    participant Profiles

    User->>Settings: Change "Content Blocker" setting
    Settings->>ContentBlocker: Emit settings change event
    ContentBlocker->>ContentBlocker: updateConfig()
    ContentBlocker->>Profiles: Get all loaded profiles
    loop For each profile session
        ContentBlocker->>ElectronSession: Enable/disable blocker as per setting
    end
Loading

Poem

In the code where cookies sneak and ads may try to roam,
A blocker now stands guard, defending every home.
With settings new and logic keen,
It keeps the browsing clean and serene.
Debug flags wave, dependencies grow—
Hooray for the blocker, onward we go!
🐰🛡️

Tip

⚡️ Faster reviews with caching
  • CodeRabbit now supports caching for code and dependencies, helping speed up reviews. This means quicker feedback, reduced wait times, and a smoother review experience overall. Cached data is encrypted and stored securely. This feature will be automatically enabled for all accounts on May 16th. To opt out, configure Review - Disable Cache at either the organization or repository level. If you prefer to disable all data retention across your organization, simply turn off the Data Retention setting under your Organization Settings.

Enjoy the performance boost—your workflow just got faster.


📜 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 79ca796 and b9700a2.

📒 Files selected for processing (1)
  • src/main/modules/content-blocker.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/main/modules/content-blocker.ts
✨ Finishing Touches
  • 📝 Generate Docstrings

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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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 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
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 5

🧹 Nitpick comments (3)
src/main/modules/basic-settings.ts (1)

28-54: Consider adding documentation about the blocking levels.

While the options are clear, users might benefit from more detailed information about what each blocking level entails, especially the difference between "Block Ads & Trackers" and "Block All".

Consider adding tooltip documentation or a help link that explains each blocking level in more detail, particularly what additional elements are blocked in the "Block All" option beyond ads and trackers.

src/main/modules/content-blocker.ts (2)

71-83: Unnecessary null check for blocker

The check if (!blocker) return; on line 73 is unnecessary since createBlockerInstance always returns a Promise that resolves to an ElectronBlocker. According to the method signature and implementation, it can't return null or undefined.

  private async enableBlockerForSession(blockerType: BlockerInstanceType, session: Session): Promise<void> {
    const blocker = await this.createBlockerInstance(blockerType);
-    if (!blocker) return;

    // check if session is already blocked
    if (this.blockedSessions.includes(session)) return;

55-66: Consider optimizing blocker type changes

When changing blocker types, the current implementation disables blocking on all sessions before creating a new blocker instance. This could lead to a brief period where content isn't blocked.

Consider creating the new blocker instance first, then switching sessions from the old blocker to the new one to minimize the time window where content isn't blocked:

  private async createBlockerInstance(type: BlockerInstanceType): Promise<ElectronBlocker> {
    if (this.blockerInstancePromise && this.blockerInstanceType === type) {
      return this.blockerInstancePromise;
    }

+    const oldBlockerPromise = this.blockerInstancePromise;
+    const oldBlockedSessions = [...this.blockedSessions];
+    this.blockerInstancePromise = undefined;
+    this.blockerInstanceType = undefined;
+    this.blockedSessions = [];
+
+    debugPrint("CONTENT_BLOCKER", "Creating blocker instance:", type);
+    // Create the new blocker instance
+    switch (type) {
+      case "all":
+        this.blockerInstancePromise = ElectronBlocker.fromPrebuiltFull();
+        break;
+      case "adsAndTrackers":
+        this.blockerInstancePromise = ElectronBlocker.fromPrebuiltAdsAndTracking();
+        break;
+      case "adsOnly":
+        this.blockerInstancePromise = ElectronBlocker.fromPrebuiltAdsOnly();
+        break;
+    }
+
+    // Set up the event listener for the new blocker
+    this.blockerInstancePromise.then((blocker) => {
+      blocker.on("request-blocked", (request) => {
+        debugPrint("CONTENT_BLOCKER", "Request blocked:", request.url);
+      });
+    }).catch(error => {
+      debugPrint("CONTENT_BLOCKER", "Error creating blocker instance:", error);
+    });
+
+    this.blockerInstanceType = type;
+
+    // If there was an old blocker, transition sessions to the new one
+    if (oldBlockerPromise) {
+      try {
+        const [oldBlocker, newBlocker] = await Promise.all([
+          oldBlockerPromise,
+          this.blockerInstancePromise
+        ]);
+        
+        // Enable blocking on the new blocker for all sessions
+        for (const session of oldBlockedSessions) {
+          newBlocker.enableBlockingInSession(session);
+          this.blockedSessions.push(session);
+        }
+        
+        // Disable the old blocker after enabling the new one
+        for (const session of oldBlockedSessions) {
+          oldBlocker.disableBlockingInSession(session);
+        }
+      } catch (error) {
+        debugPrint("CONTENT_BLOCKER", "Error transitioning between blockers:", error);
+        
+        // If transition fails, disable old blocker and return the new one
+        if (oldBlockerPromise) {
+          oldBlockerPromise.then(oldBlocker => {
+            for (const session of oldBlockedSessions) {
+              oldBlocker.disableBlockingInSession(session);
+            }
+          }).catch(error => {
+            debugPrint("CONTENT_BLOCKER", "Error disabling old blocker:", error);
+          });
+        }
+      }
+    }
+
+    return this.blockerInstancePromise as Promise<ElectronBlocker>;
-    if (this.blockerInstancePromise) {
-      await this.disableBlocker();
-    }
-
-    debugPrint("CONTENT_BLOCKER", "Creating blocker instance:", type);
-    switch (type) {
-      case "all":
-        this.blockerInstancePromise = ElectronBlocker.fromPrebuiltFull();
-        break;
-      case "adsAndTrackers":
-        this.blockerInstancePromise = ElectronBlocker.fromPrebuiltAdsAndTracking();
-        break;
-      case "adsOnly":
-        this.blockerInstancePromise = ElectronBlocker.fromPrebuiltAdsOnly();
-        break;
-    }
-
-    this.blockerInstancePromise.then((blocker) => {
-      blocker.on("request-blocked", (request) => {
-        debugPrint("CONTENT_BLOCKER", "Request blocked:", request.url);
-      });
-    });
-
-    this.blockerInstanceType = type;
-    return this.blockerInstancePromise as Promise<ElectronBlocker>;
  }

Note: This is a more complex implementation and might be overkill depending on your use case, but it ensures minimal blocking interruption during blocker type changes.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 73add9d and 79ca796.

⛔ Files ignored due to path filters (1)
  • bun.lock is excluded by !**/*.lock
📒 Files selected for processing (5)
  • package.json (1 hunks)
  • src/main/index.ts (1 hunks)
  • src/main/modules/basic-settings.ts (2 hunks)
  • src/main/modules/content-blocker.ts (1 hunks)
  • src/main/modules/output.ts (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
src/main/modules/content-blocker.ts (3)
src/main/modules/output.ts (1)
  • debugPrint (23-29)
src/main/index.ts (1)
  • browser (14-14)
src/main/saving/settings.ts (3)
  • getSettingValueById (54-56)
  • settingsEmitter (12-12)
  • onSettingsCached (51-51)
🔇 Additional comments (9)
src/main/index.ts (1)

11-11: Good integration of the new content blocker module.

The import follows the established pattern for module imports in this file. The side-effect import is appropriate for initializing the content blocker when the application starts.

src/main/modules/output.ts (1)

17-18: Good addition of debug area for the content blocker.

You've properly added a new debug area for the content blocker and fixed the missing comma in the previous line. This follows the established pattern in the codebase.

src/main/modules/basic-settings.ts (3)

28-54: Well-structured setting with appropriate default and options.

The content blocker setting is well-defined with clear naming and a comprehensive set of options that provide different levels of blocking. Setting the default to "disabled" is a sensible choice to avoid unexpected behavior for users.


158-158: Good placement in General Settings card.

The content blocker setting is appropriately added to the General Settings card between autoUpdate and the internal default browser setting.


28-54:

✅ Verification successful

Verify missing module implementation.

I don't see the implementation file src/main/modules/content-blocker.ts in this PR. Make sure this file is included and properly implements the logic for each of the blocking levels defined in the settings.


🏁 Script executed:

#!/bin/bash
# Check if the content-blocker.ts file exists
if [ -f src/main/modules/content-blocker.ts ]; then
    echo "Content blocker module exists"
    # Show the implementation to verify it handles all the blocking modes
    cat src/main/modules/content-blocker.ts
else
    echo "Content blocker module not found at src/main/modules/content-blocker.ts"
fi

Length of output: 4343


Content Blocker Module Verified

The src/main/modules/content-blocker.ts file exists and correctly implements all configured blocking levels (all, adsAndTrackers, adsOnly) with a fallback to disable blocking. No further action needed.

src/main/modules/content-blocker.ts (4)

1-6: Imports are well-organized

The imports are clean and properly structured, with appropriate dependencies from both internal modules and external packages.


7-8: Well-defined content blocker types

Good use of TypeScript type to define the three supported blocker modes, making the code more maintainable and type-safe.


12-16: Class properties are well-designed

The private properties provide good encapsulation of the blocker state. Using undefined for the initial state of the blocker instance and type is clear and explicit.


1-138: Overall excellent implementation of content blocking

The ContentBlocker class is well-designed with clear separation of concerns, good encapsulation, and thorough documentation. The singleton pattern is appropriate for this functionality, and the integration with the application's settings and browser profiles is well-implemented.

The code effectively leverages the Ghostery adblocker library to provide three different blocking modes and dynamically updates the blocking configuration based on user settings and profile changes.

@iamEvanYT iamEvanYT merged commit f57f49d into main May 10, 2025
1 check passed
@iamEvanYT iamEvanYT deleted the evan/native-adblocker branch May 10, 2025 12:43
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