Skip to content

Commit

Permalink
Add button to mark notifications read
Browse files Browse the repository at this point in the history
  • Loading branch information
tjleach98 committed Dec 11, 2023
1 parent 76f0a35 commit a5e0759
Show file tree
Hide file tree
Showing 5 changed files with 173 additions and 79 deletions.
81 changes: 81 additions & 0 deletions custom_components/zammad/button.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
"""Platform for button integration."""
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import EntityCategory
from homeassistant.util.dt import parse_datetime
from homeassistant.exceptions import HomeAssistantError
from homeassistant.components.button import (
ButtonEntity,
ButtonEntityDescription,
ButtonDeviceClass,
)

import logging
from typing import Final

from collections.abc import Callable
from dataclasses import dataclass
from datetime import datetime
from zammad_py.api import OnlineNotification

from .const import DOMAIN, INITIAL_USER_ID
from .coordinator import ZammadUpdateCoordinator
from .entity import ZammadEntity

_LOGGER = logging.getLogger(__name__)

async def async_setup_entry(hass, entry, async_add_entities):
"""Set up the Zammad buttons."""
coordinator: ZammadUpdateCoordinator = hass.data[DOMAIN][entry.entry_id]
async_add_entities(
[
ZammadButton(coordinator, entry, button)
for button in BUTTONS
]
)

@dataclass
class ZammadButtonEntityDescription(ButtonEntityDescription):
"""Describes Zammad button entity."""

value_fn: Callable[[str | int | float], str | int | float | datetime] = (
lambda value: value
)

BUTTONS: Final[list[ZammadButtonEntityDescription]] = [
ZammadButtonEntityDescription(
key="mark_all_read",
translation_key="zammad_self_mark_notifications_read",
)
]

class ZammadButton(ZammadEntity, ButtonEntity):
"""Represents a Zammad button."""

entity_description: ZammadButtonEntityDescription

async def _clear_notifications(self, zammad_client, zammad_user_id) -> None:
# Get available notifications
zammad_notifications = await self.hass.async_add_executor_job(
OnlineNotification(connection=zammad_client).all
)

for notification in zammad_notifications:
if not notification['seen']:
# Update 'seen' field to be True
await self.hass.async_add_executor_job(
OnlineNotification(connection=zammad_client).update,
notification['id'],
{"seen": True}
)

async def async_press(self) -> None:
"""Handle the button press."""
# Get connection details
zammad_client = self.coordinator.client
zammad_user_id = self.coordinator.zammad_user_id
if zammad_user_id == INITIAL_USER_ID:
raise HomeAssistantError("User ID not available")

match self.entity_description.key:
case "mark_all_read":
await self._clear_notifications(zammad_client,zammad_user_id)
5 changes: 3 additions & 2 deletions custom_components/zammad/const.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@
DOMAIN = "zammad"
PROPER_NAME = "Zammad"

PLATFORMS = ["sensor", "binary_sensor"]
PLATFORMS = ["sensor", "binary_sensor", "button"]
DEFAULT_SCAN_INTERVAL = timedelta(seconds=60)

STARTUP_MESSAGE = f"Starting setup for {DOMAIN}"
STARTUP_MESSAGE = f"Starting setup for {DOMAIN}"
INITIAL_USER_ID = -1
8 changes: 5 additions & 3 deletions custom_components/zammad/coordinator.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,14 @@
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_URL
from homeassistant.core import HomeAssistant
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator

import logging
from typing import Any
from zammad_py import ZammadAPI
from zammad_py.api import OnlineNotification

from .const import DEFAULT_SCAN_INTERVAL
from .const import DEFAULT_SCAN_INTERVAL, INITIAL_USER_ID

_LOGGER = logging.getLogger(__name__)

Expand All @@ -23,6 +23,7 @@ def __init__(
"""Initialize the Zammad coordinator."""
self.client = client
self.url = entry.data[CONF_URL]
self.zammad_user_id = INITIAL_USER_ID

super().__init__(
hass,
Expand All @@ -35,11 +36,12 @@ async def _async_update_data(self) -> dict[str, Any]:
"""Fetch all Zammad data."""

zammad_data = await self.hass.async_add_executor_job(self.client.user.me)
self.zammad_user_id = zammad_data['id']
zammad_notifications = await self.hass.async_add_executor_job(OnlineNotification(connection=self.client).all)

unread_notifs = 0
for notification in zammad_notifications:
if not notification["seen"] and notification['user_id'] == zammad_data['id']:
if not notification["seen"] and notification['user_id'] == self.zammad_user_id:
unread_notifs += 1

zammad_data["notifications"] = unread_notifs
Expand Down
79 changes: 42 additions & 37 deletions custom_components/zammad/strings.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,42 +29,47 @@
}
},
"entity": {
"binary_sensor": {
"zammad_self_verified": {
"name": "Verified"
},
"zammad_self_out_of_office": {
"name": "Out Of Office"
},
"zammad_self_active": {
"name": "Active"
},
"zammad_self_vip": {
"name": "VIP"
}
},
"sensor": {
"zammad_self_user_id": {
"name": "User ID"
},
"zammad_self_user_org_id": {
"name": "Organization ID"
},
"zammad_self_login": {
"name": "Login"
},
"zammad_self_last_login": {
"name": "Last Login"
},
"zammad_self_login_failed": {
"name": "Login Failed"
},
"zammad_self_updated_at": {
"name": "Updated At"
},
"zammad_self_notifications": {
"name": "Notifications"
}
}
"binary_sensor": {
"zammad_self_verified": {
"name": "Verified"
},
"zammad_self_out_of_office": {
"name": "Out Of Office"
},
"zammad_self_active": {
"name": "Active"
},
"zammad_self_vip": {
"name": "VIP"
}
},
"sensor": {
"zammad_self_user_id": {
"name": "User ID"
},
"zammad_self_user_org_id": {
"name": "Organization ID"
},
"zammad_self_login": {
"name": "Login"
},
"zammad_self_last_login": {
"name": "Last Login"
},
"zammad_self_login_failed": {
"name": "Login Failed"
},
"zammad_self_updated_at": {
"name": "Updated At"
},
"zammad_self_notifications": {
"name": "Notifications"
}
},
"button": {
"zammad_self_mark_notifications_read": {
"name": "Mark Notifications Read"
}
}
}
}
79 changes: 42 additions & 37 deletions custom_components/zammad/translations/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,42 +29,47 @@
}
},
"entity": {
"binary_sensor": {
"zammad_self_verified": {
"name": "Verified"
},
"zammad_self_out_of_office": {
"name": "Out Of Office"
},
"zammad_self_active": {
"name": "Active"
},
"zammad_self_vip": {
"name": "VIP"
}
},
"sensor": {
"zammad_self_user_id": {
"name": "User ID"
},
"zammad_self_user_org_id": {
"name": "Organization ID"
},
"zammad_self_login": {
"name": "Login"
},
"zammad_self_last_login": {
"name": "Last Login"
},
"zammad_self_login_failed": {
"name": "Login Failed"
},
"zammad_self_updated_at": {
"name": "Updated At"
},
"zammad_self_notifications": {
"name": "Notifications"
}
}
"binary_sensor": {
"zammad_self_verified": {
"name": "Verified"
},
"zammad_self_out_of_office": {
"name": "Out Of Office"
},
"zammad_self_active": {
"name": "Active"
},
"zammad_self_vip": {
"name": "VIP"
}
},
"sensor": {
"zammad_self_user_id": {
"name": "User ID"
},
"zammad_self_user_org_id": {
"name": "Organization ID"
},
"zammad_self_login": {
"name": "Login"
},
"zammad_self_last_login": {
"name": "Last Login"
},
"zammad_self_login_failed": {
"name": "Login Failed"
},
"zammad_self_updated_at": {
"name": "Updated At"
},
"zammad_self_notifications": {
"name": "Notifications"
}
},
"button": {
"zammad_self_mark_notifications_read": {
"name": "Mark Notifications Read"
}
}
}
}

0 comments on commit a5e0759

Please sign in to comment.