-
-
Notifications
You must be signed in to change notification settings - Fork 38k
Add mobile_app notify platform #22580
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
Changes from 9 commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
aef5e43
Add mobile_app notify platform
robbiet480 af9f415
Requested changes
robbiet480 51f6126
Merge branch 'dev' into mobile_app-notify
robbiet480 69cb1d5
Fix incorrect param for status code
robbiet480 f246631
Move push_registrations to notify platform file
robbiet480 981a7ea
Trim down registration information sent in push
robbiet480 5aaf804
quotes
robbiet480 41567b4
Use async version of load_platform
robbiet480 604201e
Add warning for duplicate device names
robbiet480 1f17bed
Switch to async_get_service
robbiet480 90bf892
add mobile_app.notify test
robbiet480 a673563
Update tests/components/mobile_app/test_notify.py
awarecan dc8bf1d
Update tests/components/mobile_app/test_notify.py
awarecan File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,134 @@ | ||
| """Support for mobile_app push notifications.""" | ||
| import asyncio | ||
| from datetime import datetime, timezone | ||
| import logging | ||
|
|
||
| import async_timeout | ||
|
|
||
| from homeassistant.components.notify import ( | ||
| ATTR_DATA, ATTR_MESSAGE, ATTR_TARGET, ATTR_TITLE, ATTR_TITLE_DEFAULT, | ||
| BaseNotificationService) | ||
| from homeassistant.components.mobile_app.const import ( | ||
| ATTR_APP_DATA, ATTR_APP_ID, ATTR_APP_VERSION, ATTR_DEVICE_NAME, | ||
| ATTR_OS_VERSION, ATTR_PUSH_TOKEN, ATTR_PUSH_URL, DATA_CONFIG_ENTRIES, | ||
| DOMAIN) | ||
| from homeassistant.helpers.aiohttp_client import async_get_clientsession | ||
| import homeassistant.util.dt as dt_util | ||
|
|
||
| _LOGGER = logging.getLogger(__name__) | ||
|
|
||
| DEPENDENCIES = ['mobile_app'] | ||
|
|
||
|
|
||
| def push_registrations(hass): | ||
| """Return a dictionary of push enabled registrations.""" | ||
| targets = {} | ||
| for webhook_id, entry in hass.data[DOMAIN][DATA_CONFIG_ENTRIES].items(): | ||
| data = entry.data | ||
| app_data = data[ATTR_APP_DATA] | ||
| if ATTR_PUSH_TOKEN in app_data and ATTR_PUSH_URL in app_data: | ||
| device_name = data[ATTR_DEVICE_NAME] | ||
| if device_name in targets: | ||
| _LOGGER.warning("Found duplicate device name %s", device_name) | ||
| continue | ||
| targets[device_name] = webhook_id | ||
| return targets | ||
|
|
||
|
|
||
| # pylint: disable=invalid-name | ||
| def log_rate_limits(hass, device_name, resp, level=logging.INFO): | ||
|
robbiet480 marked this conversation as resolved.
|
||
| """Output rate limit log line at given level.""" | ||
| rate_limits = resp['rateLimits'] | ||
| resetsAt = dt_util.parse_datetime(rate_limits['resetsAt']) | ||
| resetsAtTime = resetsAt - datetime.now(timezone.utc) | ||
| rate_limit_msg = ("mobile_app push notification rate limits for %s: " | ||
| "%d sent, %d allowed, %d errors, " | ||
| "resets in %s") | ||
| _LOGGER.log(level, rate_limit_msg, | ||
| device_name, | ||
| rate_limits['successful'], | ||
| rate_limits['maximum'], rate_limits['errors'], | ||
| str(resetsAtTime).split(".")[0]) | ||
|
|
||
|
|
||
| async def get_service(hass, config, discovery_info=None): | ||
| """Get the mobile_app notification service.""" | ||
| session = async_get_clientsession(hass) | ||
| return MobileAppNotificationService(session) | ||
|
|
||
|
|
||
| class MobileAppNotificationService(BaseNotificationService): | ||
| """Implement the notification service for mobile_app.""" | ||
|
|
||
| def __init__(self, session): | ||
| """Initialize the service.""" | ||
| self._session = session | ||
|
|
||
| @property | ||
| def targets(self): | ||
| """Return a dictionary of registered targets.""" | ||
| return push_registrations(self.hass) | ||
|
|
||
| async def async_send_message(self, message="", **kwargs): | ||
| """Send a message to the Lambda APNS gateway.""" | ||
| data = {ATTR_MESSAGE: message} | ||
|
|
||
| if kwargs.get(ATTR_TITLE) is not None: | ||
| # Remove default title from notifications. | ||
| if kwargs.get(ATTR_TITLE) != ATTR_TITLE_DEFAULT: | ||
| data[ATTR_TITLE] = kwargs.get(ATTR_TITLE) | ||
|
|
||
| targets = kwargs.get(ATTR_TARGET) | ||
|
|
||
| if not targets: | ||
| targets = push_registrations(self.hass) | ||
|
|
||
| if kwargs.get(ATTR_DATA) is not None: | ||
| data[ATTR_DATA] = kwargs.get(ATTR_DATA) | ||
|
|
||
| for target in targets: | ||
|
|
||
| entry = self.hass.data[DOMAIN][DATA_CONFIG_ENTRIES][target] | ||
| entry_data = entry.data | ||
|
|
||
| app_data = entry_data[ATTR_APP_DATA] | ||
| push_token = app_data[ATTR_PUSH_TOKEN] | ||
| push_url = app_data[ATTR_PUSH_URL] | ||
|
|
||
| data[ATTR_PUSH_TOKEN] = push_token | ||
|
|
||
| reg_info = { | ||
| ATTR_APP_ID: entry_data[ATTR_APP_ID], | ||
| ATTR_APP_VERSION: entry_data[ATTR_APP_VERSION], | ||
| } | ||
| if ATTR_OS_VERSION in entry_data: | ||
| reg_info[ATTR_OS_VERSION] = entry_data[ATTR_OS_VERSION] | ||
|
|
||
| data['registration_info'] = reg_info | ||
|
robbiet480 marked this conversation as resolved.
|
||
|
|
||
| try: | ||
| with async_timeout.timeout(10, loop=self.hass.loop): | ||
| response = await self._session.post(push_url, json=data) | ||
| result = await response.json() | ||
|
|
||
| if response.status == 201: | ||
| log_rate_limits(self.hass, | ||
| entry_data[ATTR_DEVICE_NAME], result) | ||
| return | ||
|
|
||
| fallback_error = result.get("errorMessage", | ||
| "Unknown error") | ||
| fallback_message = ("Internal server error, " | ||
| "please try again later: " | ||
| "{}").format(fallback_error) | ||
| message = result.get("message", fallback_message) | ||
| if response.status == 429: | ||
| _LOGGER.warning(message) | ||
|
robbiet480 marked this conversation as resolved.
|
||
| log_rate_limits(self.hass, | ||
| entry_data[ATTR_DEVICE_NAME], | ||
| result, logging.WARNING) | ||
| else: | ||
| _LOGGER.error(message) | ||
|
|
||
| except asyncio.TimeoutError: | ||
| _LOGGER.error("Timeout sending notification to %s", push_url) | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.