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

Add CFPreferencesAppSynchronize(kCFPreferencesCurrentApplication) #30

Merged
merged 4 commits into from
Jan 10, 2025

Conversation

robertherber
Copy link
Member

@robertherber robertherber commented Jan 10, 2025

Needs testing - but hopefully ensures that shield config/actions are available when triggered.

Summary by CodeRabbit

Release Notes

  • New Features

    • Enhanced preference synchronization across device activity and shield action extensions.
    • Improved action handling flexibility in the shield action extension.
  • Bug Fixes

    • Added fallback mechanism for shield configuration retrieval.
    • Standardized configuration and action handling processes.
  • Refactor

    • Streamlined method signatures in shield configuration and action extensions.
    • Simplified configuration retrieval logic.

Copy link

pkg-pr-new bot commented Jan 10, 2025

Open in Stackblitz

npm i https://pkg.pr.new/kingstinct/react-native-device-activity@30

commit: a4e32c7

Copy link

coderabbitai bot commented Jan 10, 2025

Warning

Rate limit exceeded

@robertherber has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 22 minutes and 9 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between c13e2bd and a4e32c7.

📒 Files selected for processing (1)
  • package.json (1 hunks)

Walkthrough

The pull request introduces modifications to three extension files: DeviceActivityMonitorExtension, ShieldActionExtension, and ShieldConfigurationExtension. The changes primarily focus on synchronizing application preferences, refactoring action handling methods, and simplifying shield configuration retrieval. The modifications enhance the consistency and robustness of preference management and action handling across different extension components.

Changes

File Change Summary
targets/ActivityMonitorExtension/DeviceActivityMonitorExtension.swift Added CFPreferencesAppSynchronize(kCFPreferencesCurrentApplication) to synchronize app preferences after persistToUserDefaults
targets/ShieldAction/ShieldActionExtension.swift - Updated handleAction method signature
- Added preference synchronization
- Modified handle methods for different token types to call handleAction consistently
targets/ShieldConfiguration/ShieldConfigurationExtension.swift - Removed config parameter from getShieldConfiguration
- Retrieve configuration directly from userDefaults
- Added fallback to empty ShieldConfiguration

Possibly related PRs

  • Upgrade expo apple targets #28: Changes in ShieldActionExtension.swift related to synchronizing application preferences using CFPreferencesAppSynchronize()

Poem

🐰 A Rabbit's Code Review Delight 🥕
Preferences sync with might,
Extensions dancing light and bright,
Tokens flow, configurations clear,
Code refactored without a fear,
Synchronization brings such cheer!


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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.

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. (Beta)
  • @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

@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: 2

🔭 Outside diff range comments (1)
targets/ActivityMonitorExtension/DeviceActivityMonitorExtension.swift (1)

Line range hint 33-69: Synchronize user defaults before executing actions

In the executeActionsForEvent method, you're accessing userDefaults without synchronizing preferences, which may lead to inconsistent data.

Add CFPreferencesAppSynchronize(kCFPreferencesCurrentApplication) before accessing userDefaults:

func executeActionsForEvent(activityName: String, callbackName: String, eventName: String? = nil) {
    let key = eventName != nil
        ? "actions_for_\(activityName)_\(callbackName)_\(eventName!)"
        : "actions_for_\(activityName)_\(callbackName)"

+   CFPreferencesAppSynchronize(kCFPreferencesCurrentApplication)

    let placeholders = [
        "activityName": activityName, "callbackName": callbackName, "eventName": eventName
    ]
    if let actions = userDefaults?.array(forKey: key) {
        // Existing code...
    }
}

This ensures that you have the most recent preferences before executing actions.

🧹 Nitpick comments (2)
targets/ShieldAction/ShieldActionExtension.swift (1)

94-96: Consistent synchronization before accessing user defaults

In the handle methods for ApplicationToken, WebDomainToken, and ActivityCategoryToken, you are calling handleAction without ensuring that preferences are synchronized. Although handleAction synchronizes preferences, it's good practice to synchronize before making significant calls.

Consider synchronizing preferences at the beginning of each handle method to ensure consistency:

override func handle(
    action: ShieldAction, for application: ApplicationToken,
    completionHandler: @escaping (ShieldActionResponse) -> Void
  ) {
    logger.log("handle application")

+   CFPreferencesAppSynchronize(kCFPreferencesCurrentApplication)
    handleAction(
        action: action,
        completionHandler: completionHandler,
        applicationToken: application,
        webdomainToken: nil
    )
}

Apply similar changes to the other handle methods.

Also applies to: 108-110, 122-124

targets/ActivityMonitorExtension/DeviceActivityMonitorExtension.swift (1)

50-51: Redundant synchronization

You're synchronizing preferences in intervalDidEnd after calling persistToUserDefaults, which already saves to userDefaults. This may be unnecessary.

Consider reviewing if the synchronization is needed here or if it can be optimized.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 4f402b3 and 1f4fab9.

📒 Files selected for processing (3)
  • targets/ActivityMonitorExtension/DeviceActivityMonitorExtension.swift (1 hunks)
  • targets/ShieldAction/ShieldActionExtension.swift (4 hunks)
  • targets/ShieldConfiguration/ShieldConfigurationExtension.swift (5 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: swift-test

Copy link

@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: 0

♻️ Duplicate comments (1)
targets/ShieldConfiguration/ShieldConfigurationExtension.swift (1)

84-84: ⚠️ Potential issue

Avoid force unwrapping to prevent potential crashes

Force unwrapping with as! Int can lead to a runtime crash if config["backgroundBlurStyle"] is not an Int.

-    ? UIBlurEffect.Style.init(rawValue: config["backgroundBlurStyle"] as! Int) : nil,
+    ? (config["backgroundBlurStyle"] as? Int).flatMap(UIBlurEffect.Style.init) : nil,
🧹 Nitpick comments (1)
targets/ShieldConfiguration/ShieldConfigurationExtension.swift (1)

55-98: Consider extracting configuration parsing logic.

The getShieldConfiguration function handles multiple responsibilities: preference synchronization, configuration retrieval, parsing, and shield creation. Consider extracting the configuration parsing logic into a separate function for better maintainability and testability.

Example structure:

private func parseShieldConfiguration(_ config: [String: Any], placeholders: [String: String?]) -> ShieldConfiguration {
    // Move parsing logic here
}

func getShieldConfiguration(placeholders: [String: String?]) -> ShieldConfiguration {
    CFPreferencesAppSynchronize(kCFPreferencesCurrentApplication)
    
    guard let config = userDefaults?.dictionary(forKey: "shieldConfiguration") else {
        return ShieldConfiguration()
    }
    
    return parseShieldConfiguration(config, placeholders: placeholders)
}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 1f4fab9 and cce8d21.

📒 Files selected for processing (1)
  • targets/ShieldConfiguration/ShieldConfigurationExtension.swift (5 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: swift-test
🔇 Additional comments (3)
targets/ShieldConfiguration/ShieldConfigurationExtension.swift (3)

60-60: LGTM: Proper preference synchronization added.

Good addition of CFPreferencesAppSynchronize to ensure configuration is up-to-date before access.


99-100: LGTM: Proper fallback handling added.

Good addition of a default shield configuration when no configuration is found in user defaults.


121-121: LGTM: Consistent implementation across configuration methods.

The changes to use the simplified getShieldConfiguration function are applied consistently across all configuration methods while maintaining proper placeholder handling for each context.

Also applies to: 140-140, 157-157, 176-176

Copy link

@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: 0

🧹 Nitpick comments (2)
targets/ShieldConfiguration/ShieldConfigurationExtension.swift (2)

62-81: Enhance error handling and logging for configuration retrieval.

While the configuration retrieval works, consider adding more detailed logging to help diagnose issues when configurations are missing or invalid.

 if let config = userDefaults?.dictionary(forKey: "shieldConfiguration") {
+    logger.log("Shield configuration found with \(config.count) keys")
     let backgroundColor = getColor(color: config["backgroundColor"] as? [String: Double])
+    if backgroundColor == nil {
+        logger.log("Background color configuration is missing or invalid")
+    }
     // ... rest of the configuration parsing
 } else {
+    logger.log("No shield configuration found in userDefaults")
 }

82-98: Consider validating required configuration fields.

While the code handles optional fields well, consider adding validation for any fields that should be required for a valid shield configuration. This would help catch configuration issues early.

 let shield = ShieldConfiguration(
   backgroundBlurStyle: config["backgroundBlurStyle"] != nil
     ? (config["backgroundBlurStyle"] as? Int).flatMap(UIBlurEffect.Style.init) : nil,
   backgroundColor: backgroundColor,
   icon: resolveIcon(dict: config),
   title: buildLabel(text: title, with: titleColor, placeholders: placeholders),
   subtitle: buildLabel(text: subtitle, with: subtitleColor, placeholders: placeholders),
   primaryButtonLabel: buildLabel(
     text: primaryButtonLabel, with: primaryButtonLabelColor, placeholders: placeholders),
   primaryButtonBackgroundColor: primaryButtonBackgroundColor,
   secondaryButtonLabel: buildLabel(
     text: secondaryButtonLabel, with: secondaryButtonLabelColor, placeholders: placeholders)
 )
+// Validate required fields
+guard shield.title != nil else {
+    logger.log("Warning: Shield configuration created without a title")
+    // Consider if this should throw an error instead
+    return ShieldConfiguration()
+}
 logger.log("shield initialized")
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between cce8d21 and c13e2bd.

📒 Files selected for processing (1)
  • targets/ShieldConfiguration/ShieldConfigurationExtension.swift (5 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: swift-test
🔇 Additional comments (3)
targets/ShieldConfiguration/ShieldConfigurationExtension.swift (3)

55-61: LGTM! Good improvements to preference synchronization and function signature.

The changes improve the code by:

  1. Simplifying the function signature
  2. Adding preference synchronization before accessing userDefaults

121-121: LGTM! Consistent implementation across configuration methods.

The changes maintain consistency in how shield configurations are retrieved across different contexts (applications, web domains, and categories).

Also applies to: 140-140, 157-157, 176-176


Line range hint 55-176: Consider adding unit tests for the refactored configuration logic.

The changes look good, but it would be valuable to add unit tests to verify:

  1. Preference synchronization behavior
  2. Default configuration fallback
  3. Configuration parsing with various input scenarios
  4. Placeholder substitution in different contexts

Would you like me to help create a test suite for these scenarios?

@robertherber robertherber merged commit 07c1be2 into main Jan 10, 2025
6 of 7 checks passed
@robertherber robertherber deleted the add-synchronize branch January 10, 2025 13:53
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