Skip to content

Commit

Permalink
General code improvements
Browse files Browse the repository at this point in the history
  • Loading branch information
RogerSelwyn committed Apr 28, 2023
1 parent d9f045c commit e3f42d1
Show file tree
Hide file tree
Showing 6 changed files with 70 additions and 97 deletions.
39 changes: 13 additions & 26 deletions custom_components/o365/classes/mailsensor.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
"""O365 mail sensors."""
import datetime

import voluptuous as vol
from homeassistant.components.sensor import SensorEntity

from O365.mailbox import ExternalAudience # pylint: disable=no-name-in-module
Expand All @@ -16,7 +15,6 @@
ATTR_START,
CONF_ACCOUNT,
CONF_BODY_CONTAINS,
CONF_CONFIG_TYPE,
CONF_DOWNLOAD_ATTACHMENTS,
CONF_HAS_ATTACHMENT,
CONF_HTML_BODY,
Expand All @@ -32,12 +30,7 @@
SENSOR_AUTO_REPLY,
SENSOR_MAIL,
)
from ..utils import (
build_token_filename,
clean_html,
get_permissions,
validate_minimum_permission,
)
from ..utils import clean_html
from .sensorentity import O365Sensor


Expand All @@ -48,7 +41,7 @@ def __init__(
self, coordinator, config, sensor_conf, mail_folder, name, entity_id, unique_id
):
"""Initialise the O365 Sensor."""
super().__init__(coordinator, name, entity_id, SENSOR_MAIL, unique_id)
super().__init__(coordinator, config, name, entity_id, SENSOR_MAIL, unique_id)
self.mail_folder = mail_folder
self.download_attachments = sensor_conf.get(CONF_DOWNLOAD_ATTACHMENTS)
self.html_body = sensor_conf.get(CONF_HTML_BODY)
Expand Down Expand Up @@ -160,9 +153,11 @@ def __init__(
class O365AutoReplySensor(O365Sensor, SensorEntity):
"""O365 Auto Reply sensor processing."""

def __init__(self, coordinator, name, entity_id, config, unqique_id):
def __init__(self, coordinator, name, entity_id, config, unique_id):
"""Initialise the Auto reply Sensor."""
super().__init__(coordinator, name, entity_id, SENSOR_AUTO_REPLY, unqique_id)
super().__init__(
coordinator, config, name, entity_id, SENSOR_AUTO_REPLY, unique_id
)
self._config = config
account = self._config[CONF_ACCOUNT]
self.mailbox = account.mailbox()
Expand Down Expand Up @@ -193,7 +188,7 @@ def auto_reply_enable(
external_audience=ExternalAudience.ALL,
):
"""Enable out of office autoreply."""
if not self._validate_permissions():
if not self._validate_autoreply_permissions():
return

self.mailbox.set_automatic_reply(
Expand All @@ -202,22 +197,14 @@ def auto_reply_enable(

def auto_reply_disable(self):
"""Disable out of office autoreply."""
if not self._validate_permissions():
if not self._validate_autoreply_permissions():
return

self.mailbox.set_disable_reply()

def _validate_permissions(self):
permissions = get_permissions(
self.hass,
filename=build_token_filename(
self._config, self._config.get(CONF_CONFIG_TYPE)
),
def _validate_autoreply_permissions(self):
return self._validate_permissions(
PERM_MINIMUM_MAILBOX_SETTINGS,
"Not authorisied to update auto reply - requires permission: "
+ f"{PERM_MAILBOX_SETTINGS}",
)
if not validate_minimum_permission(PERM_MINIMUM_MAILBOX_SETTINGS, permissions):
raise vol.Invalid(
"Not authorisied to update auto reply - requires permission: "
+ f"{PERM_MAILBOX_SETTINGS}"
)

return True
21 changes: 19 additions & 2 deletions custom_components/o365/classes/sensorentity.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,20 @@
"""Generic O465 Sensor Entity."""
import voluptuous as vol
from homeassistant.helpers.update_coordinator import CoordinatorEntity

from ..const import ATTR_STATE
from ..const import ATTR_STATE, CONF_CONFIG_TYPE
from ..utils import build_token_filename, get_permissions, validate_minimum_permission


class O365Sensor(CoordinatorEntity):
"""O365 generic Sensor class."""

_attr_should_poll = False

def __init__(self, coordinator, name, entity_id, entity_type, unique_id):
def __init__(self, coordinator, config, name, entity_id, entity_type, unique_id):
"""Initialise the O365 Sensor."""
super().__init__(coordinator)
self._config = config
self._name = name
self._entity_id = entity_id
self.entity_type = entity_type
Expand All @@ -36,3 +39,17 @@ def state(self):
def unique_id(self):
"""Entity unique id."""
return self._unique_id

def _validate_permissions(self, minimum_perm_list, required_permission):
permissions = get_permissions(
self.hass,
filename=build_token_filename(
self._config, self._config.get(CONF_CONFIG_TYPE)
),
)
if not validate_minimum_permission(minimum_perm_list, permissions):
raise vol.Invalid(
f"Not authorisied to create new task - requires permission: {required_permission}"
)

return True
38 changes: 13 additions & 25 deletions custom_components/o365/classes/taskssensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
ATTR_SUBJECT,
ATTR_TASK_ID,
ATTR_TASKS,
CONF_CONFIG_TYPE,
CONF_SHOW_COMPLETED,
DATETIME_FORMAT,
DOMAIN,
EVENT_COMPLETED_TASK,
Expand All @@ -29,7 +29,6 @@
PERM_TASKS_READWRITE,
SENSOR_TODO,
)
from ..utils import build_token_filename, get_permissions, validate_minimum_permission
from .sensorentity import O365Sensor

_LOGGER = logging.getLogger(__name__)
Expand All @@ -38,21 +37,18 @@
class O365TasksSensor(O365Sensor, SensorEntity):
"""O365 Tasks sensor processing."""

def __init__(
self, coordinator, todo, name, entity_id, config, unique_id, show_completed
):
def __init__(self, coordinator, todo, name, task, config, entity_id, unique_id):
"""Initialise the Tasks Sensor."""
super().__init__(coordinator, name, entity_id, SENSOR_TODO, unique_id)
super().__init__(coordinator, config, name, entity_id, SENSOR_TODO, unique_id)
self.todo = todo
self._show_completed = show_completed
self._show_completed = task.get(CONF_SHOW_COMPLETED)
self.query = self.todo.new_query()
if not show_completed:
if not self._show_completed:
self.query = self.query.on_attribute("status").unequal("completed")

# self.query.chain("and").on_attribute("due").less_equal(
# datetime.now().strftime("%Y-%m-%dT%H:%M:%S")
# )
self._config = config
self.task_last_created = dt.utcnow() - timedelta(minutes=5)
self.task_last_completed = dt.utcnow() - timedelta(minutes=5)

Expand Down Expand Up @@ -101,7 +97,7 @@ def extra_state_attributes(self):

def new_task(self, subject, description=None, due=None, reminder=None):
"""Create a new task for this task list."""
if not self._validate_permissions():
if not self._validate_task_permissions():
return False

new_task = self.todo.new_task()
Expand All @@ -114,7 +110,7 @@ def update_task(
self, task_id, subject=None, description=None, due=None, reminder=None
):
"""Update a task for this task list."""
if not self._validate_permissions():
if not self._validate_task_permissions():
return False

task = self.todo.get_task(task_id)
Expand All @@ -124,7 +120,7 @@ def update_task(

def delete_task(self, task_id):
"""Delete task for this task list."""
if not self._validate_permissions():
if not self._validate_task_permissions():
return False

task = self.todo.get_task(task_id)
Expand All @@ -134,7 +130,7 @@ def delete_task(self, task_id):

def complete_task(self, task_id, completed):
"""Complete task for this task list."""
if not self._validate_permissions():
if not self._validate_task_permissions():
return False

task = self.todo.get_task(task_id)
Expand Down Expand Up @@ -189,16 +185,8 @@ def _raise_event(self, event_type, task_id):
)
_LOGGER.debug("%s - %s", event_type, task_id)

def _validate_permissions(self):
permissions = get_permissions(
self.hass,
filename=build_token_filename(
self._config, self._config.get(CONF_CONFIG_TYPE)
),
def _validate_task_permissions(self):
return self._validate_permissions(
PERM_MINIMUM_TASKS_WRITE,
f"Not authorisied to create new task - requires permission: {PERM_TASKS_READWRITE}",
)
if not validate_minimum_permission(PERM_MINIMUM_TASKS_WRITE, permissions):
raise vol.Invalid(
f"Not authorisied to create new task - requires permission: {PERM_TASKS_READWRITE}"
)

return True
2 changes: 1 addition & 1 deletion custom_components/o365/classes/teamssensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ class O365TeamsSensor(O365Sensor):

def __init__(self, cordinator, account, name, entity_id, entity_type, unique_id):
"""Initialise the Teams Sensor."""
super().__init__(cordinator, name, entity_id, entity_type, unique_id)
super().__init__(cordinator, None, name, entity_id, entity_type, unique_id)
self.teams = account.teams()

@property
Expand Down
56 changes: 13 additions & 43 deletions custom_components/o365/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@

from homeassistant.const import CONF_ENABLED, CONF_NAME
from homeassistant.helpers import entity_platform
from homeassistant.helpers.entity import async_generate_entity_id
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator
from homeassistant.util import dt
from requests.exceptions import HTTPError
Expand Down Expand Up @@ -38,7 +37,6 @@
CONF_ENABLE_UPDATE,
CONF_MAIL_FOLDER,
CONF_QUERY_SENSORS,
CONF_SHOW_COMPLETED,
CONF_STATUS_SENSORS,
CONF_TASK_LIST_ID,
CONF_TODO_SENSORS,
Expand All @@ -52,7 +50,6 @@
PERM_MINIMUM_MAILBOX_SETTINGS,
PERM_MINIMUM_TASKS_WRITE,
SENSOR_AUTO_REPLY,
SENSOR_ENTITY_ID_FORMAT,
SENSOR_MAIL,
SENSOR_TEAMS_CHAT,
SENSOR_TEAMS_STATUS,
Expand All @@ -70,6 +67,7 @@
)
from .utils import (
build_config_file_path,
build_entity_id,
build_token_filename,
build_yaml_filename,
get_email_attributes,
Expand Down Expand Up @@ -158,11 +156,7 @@ async def _async_email_sensors(self):
if mail_folder := await self._async_get_mail_folder(
sensor_conf, CONF_EMAIL_SENSORS
):
entity_id = async_generate_entity_id(
SENSOR_ENTITY_ID_FORMAT,
name,
hass=self.hass,
)
entity_id = build_entity_id(self.hass, name)
unique_id = f"{mail_folder.folder_id}_{self._account_name}"
emailsensor = O365EmailSensor(
self,
Expand All @@ -189,11 +183,7 @@ async def _async_query_sensors(self):
sensor_conf, CONF_QUERY_SENSORS
):
name = sensor_conf.get(CONF_NAME)
entity_id = async_generate_entity_id(
SENSOR_ENTITY_ID_FORMAT,
name,
hass=self.hass,
)
entity_id = build_entity_id(self.hass, name)
unique_id = f"{mail_folder.folder_id}_{self._account_name}"
querysensor = O365QuerySensor(
self,
Expand All @@ -212,11 +202,7 @@ def _status_sensors(self):
entities = []
for sensor_conf in status_sensors:
name = sensor_conf.get(CONF_NAME)
entity_id = async_generate_entity_id(
SENSOR_ENTITY_ID_FORMAT,
name,
hass=self.hass,
)
entity_id = build_entity_id(self.hass, name)
unique_id = f"{name}_{self._account_name}"
teams_status_sensor = O365TeamsStatusSensor(
self, self._account, name, entity_id, unique_id
Expand All @@ -229,11 +215,7 @@ def _chat_sensors(self):
entities = []
for sensor_conf in chat_sensors:
name = sensor_conf.get(CONF_NAME)
entity_id = async_generate_entity_id(
SENSOR_ENTITY_ID_FORMAT,
name,
hass=self.hass,
)
entity_id = build_entity_id(self.hass, name)
unique_id = f"{name}_{self._account_name}"
teams_chat_sensor = O365TeamsChatSensor(
self, self._account, name, entity_id, unique_id
Expand Down Expand Up @@ -262,16 +244,15 @@ async def _async_todo_entities(self, task_lists, config):
entities = []
tasks = self._account.tasks()
for task in task_lists:
track = task.get(CONF_TRACK)
if not track:
continue

task_list_id = task.get(CONF_TASK_LIST_ID)
if self._account_name != LEGACY_ACCOUNT_NAME:
name = f"{task.get(CONF_NAME)} {self._account_name}"
else:
name = task.get(CONF_NAME)
track = task.get(CONF_TRACK)
show_completed = task.get(CONF_SHOW_COMPLETED)
task_list_id = task.get(CONF_TASK_LIST_ID)
entity_id = _build_entity_id(self.hass, name, self._config)
if not track:
continue
try:
todo = (
await self.hass.async_add_executor_job( # pylint: disable=no-member
Expand All @@ -281,9 +262,10 @@ async def _async_todo_entities(self, task_lists, config):
)
)
)
entity_id = build_entity_id(self.hass, name)
unique_id = f"{task_list_id}_{self._account_name}"
todo_sensor = O365TasksSensor(
self, todo, name, entity_id, config, unique_id, show_completed
self, todo, name, task, config, entity_id, unique_id
)
entities.append(todo_sensor)
except HTTPError:
Expand All @@ -299,11 +281,7 @@ async def _async_auto_reply_sensors(self):
entities = []
for sensor_conf in auto_reply_sensors:
name = sensor_conf.get(CONF_NAME)
entity_id = async_generate_entity_id(
SENSOR_ENTITY_ID_FORMAT,
name,
hass=self.hass,
)
entity_id = build_entity_id(self.hass, name)
unique_id = f"{name}_{self._account_name}"
auto_reply_sensor = O365AutoReplySensor(
self, name, entity_id, self._config, unique_id
Expand Down Expand Up @@ -485,14 +463,6 @@ def _raise_event(self, event_type, task_id, time_type, task_datetime):
_LOGGER.debug("%s - %s - %s", event_type, task_id, task_datetime)


def _build_entity_id(hass, name, conf):
return async_generate_entity_id(
SENSOR_ENTITY_ID_FORMAT,
f"{name}_{conf[CONF_ACCOUNT_NAME]}",
hass=hass,
)


async def _async_setup_register_services(hass, config):
await _async_setup_task_services(hass, config)
await _async_setup_mailbox_services(hass, config)
Expand Down
Loading

0 comments on commit e3f42d1

Please sign in to comment.