Skip to content

Commit

Permalink
Add voucher remove function
Browse files Browse the repository at this point in the history
  • Loading branch information
Markus authored and Markus committed Nov 11, 2023
1 parent 9b72b0c commit 02b8948
Show file tree
Hide file tree
Showing 5 changed files with 89 additions and 9 deletions.
13 changes: 11 additions & 2 deletions custom_components/unifi_voucher/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,10 @@
PLATFORMS,
)
from .coordinator import UnifiVoucherCoordinator
from .api import (
UnifiVoucherApiAuthenticationError,
UnifiVoucherApiAccessError,
)


async def async_setup(hass: HomeAssistant, config: dict) -> bool:
Expand All @@ -34,15 +38,20 @@ async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> b
await coordinator.initialize()
await coordinator.async_config_entry_first_refresh()

except AuthenticationRequired as err:
except (
UnifiVoucherApiAuthenticationError,
UnifiVoucherApiAccessError,
) as err:
raise ConfigEntryAuthFailed from err

except Exception as err:
raise ConfigEntryNotReady from err

hass.data[DOMAIN][config_entry.entry_id] = coordinator
await hass.config_entries.async_forward_entry_setups(config_entry, PLATFORMS)
config_entry.async_on_unload(config_entry.add_update_listener(async_reload_entry))
config_entry.async_on_unload(
config_entry.add_update_listener(async_reload_entry)
)

return True

Expand Down
34 changes: 30 additions & 4 deletions custom_components/unifi_voucher/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,10 @@

import asyncio
from dataclasses import dataclass
from typing import TypedDict
from typing import (
Self,
TypedDict,
)

from datetime import (
timedelta,
Expand Down Expand Up @@ -78,7 +81,7 @@ class UnifiVoucherListRequest(ApiRequest):
@classmethod
def create(
cls
) -> self:
) -> Self:
"""Create voucher list request."""
return cls(
method="get",
Expand All @@ -100,7 +103,7 @@ def create(
down_bandwidth: int | None = None,
byte_quota: int | None = None,
note: str | None = None,
) -> self:
) -> Self:
"""
Create voucher create request.
Expand Down Expand Up @@ -130,7 +133,30 @@ def create(
data["bytes"] = byte_quota
if note:
data["note"] = note


return cls(
method="post",
path="/cmd/hotspot",
data=data,
)


@dataclass
class UnifiVoucherRemoveRequest(ApiRequest):
"""Request object for voucher create."""

@classmethod
def create(
cls,
obj_id: int,
) -> Self:
"""
Create voucher remove request.
"""
data = {
"cmd": "delete-voucher",
"_id": obj_id,
}
return cls(
method="post",
path="/cmd/hotspot",
Expand Down
7 changes: 7 additions & 0 deletions custom_components/unifi_voucher/button.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,13 @@ async def async_setup_entry(
device_class=ButtonDeviceClass.RESTART,
press_action=lambda coordinator: coordinator.async_create_voucher(),
),
UnifiVoucherButtonDescription(
key="remove",
icon="mdi:numeric-negative-1",
translation_key="remove",
device_class=ButtonDeviceClass.RESTART,
press_action=lambda coordinator: coordinator.async_remove_voucher(),
),
]

async_add_entities(
Expand Down
36 changes: 33 additions & 3 deletions custom_components/unifi_voucher/coordinator.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
UnifiVoucherApiClient,
UnifiVouchers,
UnifiVoucherCreateRequest,
UnifiVoucherRemoveRequest,
UnifiVoucherApiAuthenticationError,
UnifiVoucherApiAccessError,
UnifiVoucherApiConnectionError,
Expand Down Expand Up @@ -194,15 +195,24 @@ async def async_update_vouchers(

async def async_create_voucher(
self,
number: int = 1,
quota: int = 1,
expire: int = 480,
number: int | None = None,
quota: int | None = None,
expire: int | None = None,
up_bandwidth: int | None = None,
down_bandwidth: int | None = None,
byte_quota: int | None = None,
) -> None:
"""Create new voucher."""
try:
if number is None:
number = 1 # TODO

if quota is None:
quota = 1 # TODO

if expire is None:
expire = 480 # TODO

await self.client.controller.request(
UnifiVoucherCreateRequest.create(
number=number,
Expand All @@ -217,3 +227,23 @@ async def async_create_voucher(
await self.async_update_vouchers()
except Exception as exception:
LOGGER.exception(exception)

async def async_remove_voucher(
self,
obj_id: int | None = None,
) -> None:
"""Remove voucher."""
try:
# No voucher ID given
if obj_id is None:
if (obj_id := self.last_voucher_id) is None:
raise ValueError

await self.client.controller.request(
UnifiVoucherRemoveRequest.create(
obj_id=obj_id,
)
)
await self.async_update_vouchers()
except Exception as exception:
LOGGER.exception(exception)
8 changes: 8 additions & 0 deletions custom_components/unifi_voucher/strings.json
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,14 @@
"name": "Last pull"
}
}
},
"remove": {
"name": "Delete voucher",
"state_attributes": {
"last_pull": {
"name": "Last pull"
}
}
}
},
"sensor": {
Expand Down

0 comments on commit 02b8948

Please sign in to comment.