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

feat: MV Official API #164

Merged
merged 7 commits into from
Dec 14, 2024
Merged

feat: MV Official API #164

merged 7 commits into from
Dec 14, 2024

Conversation

geertmeersman
Copy link
Owner

@geertmeersman geertmeersman commented Dec 14, 2024

Summary by CodeRabbit

  • New Features

    • Introduced a binary sensor platform for MobileVikings, enhancing monitoring capabilities.
    • Added new sensors and binary sensors for various usage alerts and account information.
    • Implemented French and Dutch translations for improved localization support.
    • Enhanced the README.md with structured feature descriptions and new sections for better user guidance.
  • Bug Fixes

    • Enhanced error handling and connection validation for user credentials.
  • Documentation

    • Updated translation files to reflect new entities and improved clarity.
    • Revised the README.md to include detailed descriptions of features and available sensors.
  • Chores

    • Updated version number to v0.8.0-beta.20, indicating a new beta release.

Copy link
Contributor

coderabbitai bot commented Dec 14, 2024

Caution

Review failed

The pull request is closed.

Walkthrough

This pull request introduces a comprehensive update to the Mobile Vikings Home Assistant integration, transitioning it to a more robust and feature-rich implementation. The changes span multiple files, introducing asynchronous client methods, enhancing data handling, adding binary sensor support, improving error management, and expanding translation support for French and Dutch languages. The version has been updated to v0.8.0-beta.20, signaling significant improvements in the integration's functionality and reliability.

Changes

File Change Summary
.github/FUNDING.yml Minor formatting change with quote style
LICENSE Added period at the end of the last line
VERSION Updated to v0.8.0-beta.20
custom_components/mobile_vikings/manifest.json Version updated to v0.8.0-beta.20
custom_components/mobile_vikings/__init__.py Major refactoring of data update coordinator, added storage handling, improved entry lifecycle management
custom_components/mobile_vikings/client.py Transitioned to async client, enhanced authentication and request handling
custom_components/mobile_vikings/config_flow.py Updated connection validation and error handling
custom_components/mobile_vikings/const.py Updated platforms, added OAuth constants
custom_components/mobile_vikings/translations/en.json Added new translations for various entities and devices
custom_components/mobile_vikings/translations/fr.json Introduced French translations for configuration and entities
custom_components/mobile_vikings/translations/nl.json Enhanced Dutch translations for clarity and formality
custom_components/mobile_vikings/utils.py Added new utility functions for safe data retrieval and JSON compatibility

Sequence Diagram

sequenceDiagram
    participant HA as Home Assistant
    participant MV as MobileVikingsClient
    participant API as Mobile Vikings API
    
    HA->>MV: Initialize Client
    MV->>API: Authenticate
    API-->>MV: Return Tokens
    MV->>API: Fetch Customer Data
    API-->>MV: Return Customer Information
    MV->>HA: Update Coordinator with Data
    HA->>HA: Create Sensors and Binary Sensors
Loading

Possibly related PRs

  • feat: MV Official API #164: The changes in this PR directly modify the same .github/FUNDING.yml file, specifically altering the quotation marks in the custom field, which is identical to the changes made in the main PR.

Poem

🐰 Viking Rabbits Hop with Glee

Async calls now dance so free,
Sensors bloom like spring's delight,
Translations shine both dark and bright,
Mobile magic, version point eight! 🚀


📜 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 49278f1 and b817a5e.

📒 Files selected for processing (2)
  • README.md (3 hunks)
  • custom_components/mobile_vikings/__init__.py (2 hunks)

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.

@github-actions github-actions bot added feat A new feature minor A change requiring a minor version bump labels Dec 14, 2024
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: 10

🧹 Outside diff range and nitpick comments (5)
custom_components/mobile_vikings/entity.py (1)

58-58: Use lazy logging to improve performance

To avoid unnecessary string formatting when the debug level is not enabled, use lazy logging by passing variables as arguments.

Apply this diff:

-_LOGGER.debug(f"[MobileVikingsEntity|init] {self._identifier}")
+_LOGGER.debug("[MobileVikingsEntity|init] %s", self._identifier)
custom_components/mobile_vikings/binary_sensor.py (1)

189-200: Return consistent attribute types in 'extra_state_attributes'

Ensure that the extra_state_attributes property returns a dictionary with consistent data types to prevent potential issues with the state machine.

Review the attributes returned by self.entity_description.attributes_fn(self.item) and ensure they are serializable and correctly formatted.

custom_components/mobile_vikings/client.py (1)

188-188: Avoid raising generic exceptions; use specific exception types

Raising a generic Exception can make error handling less precise. Consider raising a more specific exception, such as RuntimeError, or define a custom exception class to provide clearer context.

Apply this diff to improve exception handling:

-                raise Exception(error_message)
+                raise RuntimeError(error_message)
custom_components/mobile_vikings/utils.py (2)

75-93: Add type hints to function signature

The function is well-implemented and documented, but would benefit from explicit type hints for better code maintainability and IDE support.

-def safe_get(data, keys, default=None):
+def safe_get(data: dict, keys: list[str], default: Any = None) -> Any:

Don't forget to add the following import:

from typing import Any

96-105: Enhance function documentation and type hints

The function handles JSON serialization well, but could benefit from more detailed documentation and type hints.

-def json_safe(obj):
+def json_safe(obj: Any) -> Union[dict, list, str, int, float, bool, None]:
     """Convert all non-JSON-serializable types to strings.
+
+    Args:
+        obj: Any Python object to be made JSON-safe
+
+    Returns:
+        A JSON-serializable version of the input object where unsupported types
+        are converted to strings
     """

Don't forget to add the following import if not already present:

from typing import Any, Union
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 7b13882 and 8abc852.

📒 Files selected for processing (16)
  • .github/FUNDING.yml (1 hunks)
  • LICENSE (1 hunks)
  • VERSION (1 hunks)
  • custom_components/mobile_vikings/__init__.py (2 hunks)
  • custom_components/mobile_vikings/binary_sensor.py (1 hunks)
  • custom_components/mobile_vikings/client.py (1 hunks)
  • custom_components/mobile_vikings/config_flow.py (1 hunks)
  • custom_components/mobile_vikings/const.py (1 hunks)
  • custom_components/mobile_vikings/entity.py (2 hunks)
  • custom_components/mobile_vikings/manifest.json (1 hunks)
  • custom_components/mobile_vikings/models.py (1 hunks)
  • custom_components/mobile_vikings/sensor.py (3 hunks)
  • custom_components/mobile_vikings/translations/en.json (1 hunks)
  • custom_components/mobile_vikings/translations/fr.json (1 hunks)
  • custom_components/mobile_vikings/translations/nl.json (3 hunks)
  • custom_components/mobile_vikings/utils.py (1 hunks)
✅ Files skipped from review due to trivial changes (5)
  • VERSION
  • .github/FUNDING.yml
  • custom_components/mobile_vikings/manifest.json
  • LICENSE
  • custom_components/mobile_vikings/models.py
🧰 Additional context used
🪛 Gitleaks (8.21.2)
custom_components/mobile_vikings/const.py

23-23: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)

🔇 Additional comments (9)
custom_components/mobile_vikings/entity.py (4)

25-26: Including 'invoices' and 'last_synced' in _unrecorded_attributes

Adding 'invoices' and 'last_synced' to _unrecorded_attributes ensures these attributes are not recorded in the state machine, which is appropriate if they contain redundant or sensitive information.


34-38: Verify the transition from 'item' to 'idx' in the constructor

The constructor now accepts idx: int instead of item: MobileVikingsItem. Ensure that all references to self._item have been updated to use self.idx correctly throughout the class.


49-49: Ensure 'device_name_fn(self.item)' returns valid strings for 'translation_key'

When setting translation_key, verify that self.entity_description.device_name_fn(self.item) returns a valid string. Passing None or invalid values to slugify might cause unexpected behavior.


56-56: Confirm 'unique_id_fn(self.item)' returns unique identifiers

Ensure that self.entity_description.unique_id_fn(self.item) returns a unique and valid string to prevent identifier collisions and issues with entity registration.

custom_components/mobile_vikings/__init__.py (1)

33-37: Ensure safe handling of storage directory operations

When initializing the storage directory, verify that removing existing files doesn't unintentionally delete important data. Consider checking for specific files rather than deleting the entire directory.

custom_components/mobile_vikings/client.py (1)

183-186: ⚠️ Potential issue

Avoid suppressing exceptions with bare except clauses

Swallowing exceptions with except Exception: pass can hide underlying issues and make debugging difficult. It's better to handle specific exceptions or at least log the exception details.

Apply this diff to handle exceptions appropriately:

             try:
                 error_data = response.json()
                 error_message += f", Error: {error_data}"
-            except Exception:
+            except json.JSONDecodeError:
                 error_message += f", Error: {response.text}"
custom_components/mobile_vikings/const.py (1)

23-23: ⚠️ Potential issue

Avoid hardcoding sensitive credentials; use secure storage mechanisms

Storing sensitive information like CLIENT_SECRET directly in the code is a security risk. Consider using environment variables or Home Assistant's secrets management to securely handle sensitive data.

🧰 Tools
🪛 Gitleaks (8.21.2)

23-23: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)

custom_components/mobile_vikings/translations/en.json (1)

49-127: Translations added correctly; keys are consistent

The new translation entries are well-structured and consistent with existing entries. This enhances the user experience for different language settings.

custom_components/mobile_vikings/translations/fr.json (1)

1-126: French translations look good!

The French translations are complete, grammatically correct, and follow proper French typography rules. All required keys are present and consistent with the structure of other language files.

@github-actions github-actions bot added the fix A bug fix label Dec 14, 2024
@geertmeersman geertmeersman added major A change requiring a major version bump and removed minor A change requiring a minor version bump labels Dec 14, 2024
@github-actions github-actions bot added the minor A change requiring a minor version bump label Dec 14, 2024
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: 1

🧹 Outside diff range and nitpick comments (1)
custom_components/mobile_vikings/translations/nl.json (1)

102-102: Add hyphen for consistency with other compound terms

For consistency with other compound terms in the translations, consider adding a hyphen:

-        "name": "Buitenbundel kosten"
+        "name": "Buitenbundel-kosten"
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 8abc852 and 49278f1.

📒 Files selected for processing (3)
  • custom_components/mobile_vikings/binary_sensor.py (1 hunks)
  • custom_components/mobile_vikings/entity.py (2 hunks)
  • custom_components/mobile_vikings/translations/nl.json (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • custom_components/mobile_vikings/binary_sensor.py
🔇 Additional comments (7)
custom_components/mobile_vikings/translations/nl.json (3)

5-8: LGTM! Configuration translations are accurate and consistent

The translations use proper Dutch grammar and maintain a consistent formal tone using "uw" instead of "je". Error messages are clear and concise.

Also applies to: 17-20


26-27: LGTM! Options translations maintain consistency

The translations maintain consistency with the configuration section, and the error messages are properly aligned.

Also applies to: 40-47


115-124: LGTM! Device translations are accurate

The translations are concise and use the correct brand-specific terminology.

custom_components/mobile_vikings/entity.py (4)

25-26: LGTM! Appropriate attributes marked as unrecorded.

The addition of "invoices" and "last_synced" to _unrecorded_attributes is appropriate as these are either sensitive or frequently changing data that don't need historical tracking.


73-81: LGTM! Robust error handling implementation.

The new implementation properly handles potential KeyError and IndexError exceptions, making the code more resilient. The change from MobileVikingsItem to dict also simplifies the interface.


85-86: LGTM! Flexible availability check implementation.

The use of available_fn from entity_description provides a clean way to customize availability checks per entity type.


66-70: ⚠️ Potential issue

Remove unintended positional argument in logging statement

The _LOGGER.debug call includes an extra positional argument True which may cause logging issues.

-_LOGGER.debug(
-    f"[MobileVikingsEntity|_handle_coordinator_update] {self._attr_unique_id}: async_write_ha_state ignored since API fetch failed or not found",
-    True,
-)
+_LOGGER.debug(
+    "[MobileVikingsEntity|_handle_coordinator_update] %s: async_write_ha_state ignored since API fetch failed or not found",
+    self._attr_unique_id
+)

@github-actions github-actions bot added the docs Documentation only changes label Dec 14, 2024
@geertmeersman geertmeersman merged commit e022749 into main Dec 14, 2024
9 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
docs Documentation only changes feat A new feature fix A bug fix major A change requiring a major version bump minor A change requiring a minor version bump
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant