Skip to content

Commit

Permalink
maint: Re-organise todo/tasks
Browse files Browse the repository at this point in the history
  • Loading branch information
RogerSelwyn committed Oct 29, 2023
1 parent db068bb commit 33fee2f
Show file tree
Hide file tree
Showing 9 changed files with 627 additions and 525 deletions.
2 changes: 1 addition & 1 deletion custom_components/o365/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,7 @@ async def _async_setup_account(hass, account_conf, conf_type):
if is_authenticated and permissions and permissions != TOKEN_FILE_MISSING:
check_token = await _async_check_token(hass, account, account_name)
if check_token:
do_setup(hass, account_conf, account, account_name, conf_type, perms)
await do_setup(hass, account_conf, account, account_name, conf_type, perms)
else:
await _async_authorization_repair(
hass,
Expand Down
1 change: 0 additions & 1 deletion custom_components/o365/calendar.py
Original file line number Diff line number Diff line change
Expand Up @@ -242,7 +242,6 @@ def _init_data(self, account, calendar_id, entity):
max_results = entity.get(CONF_MAX_RESULTS)
search = entity.get(CONF_SEARCH)
exclude = entity.get(CONF_EXCLUDE)
# _LOGGER.debug("Initialising calendar: %s", calendar_id)
return O365CalendarData(
account,
self.entity_id,
Expand Down
2 changes: 1 addition & 1 deletion custom_components/o365/classes/sensorentity.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ def name(self):

@property
def entity_key(self):
"""Entity Keyr property."""
"""Entity Key property."""
return self._entity_id

@property
Expand Down
77 changes: 69 additions & 8 deletions custom_components/o365/classes/taskssensor.py
Original file line number Diff line number Diff line change
@@ -1,24 +1,27 @@
"""O365 tasks sensors."""
import logging
from datetime import timedelta
from datetime import datetime, timedelta

import voluptuous as vol
from homeassistant.components.sensor import SensorEntity
from homeassistant.const import CONF_ENABLED
from homeassistant.util import dt

from ..const import (
ATTR_ALL_TASKS,
ATTR_COMPLETED,
ATTR_CREATED,
ATTR_DESCRIPTION,
ATTR_DUE,
ATTR_OVERDUE_TASKS,
ATTR_REMINDER,
ATTR_SUBJECT,
ATTR_TASK_ID,
ATTR_TASKS,
CONF_DUE_HOURS_BACKWARD_TO_GET,
CONF_DUE_HOURS_FORWARD_TO_GET,
CONF_ACCOUNT,
CONF_SHOW_COMPLETED,
CONF_TODO_SENSORS,
CONF_TRACK_NEW,
DATETIME_FORMAT,
DOMAIN,
EVENT_COMPLETED_TASK,
Expand All @@ -31,6 +34,7 @@
PERM_TASKS_READWRITE,
SENSOR_TODO,
)
from ..utils.filemgmt import update_task_list_file
from .sensorentity import O365Sensor

_LOGGER = logging.getLogger(__name__)
Expand All @@ -44,14 +48,10 @@ def __init__(self, coordinator, todo, name, task, config, entity_id, unique_id):
super().__init__(coordinator, config, name, entity_id, SENSOR_TODO, unique_id)
self.todo = todo
self._show_completed = task.get(CONF_SHOW_COMPLETED)
self.query = self.todo.new_query()
if not self._show_completed:
self.query = self.query.on_attribute("status").unequal("completed")
self.start_offset = task.get(CONF_DUE_HOURS_BACKWARD_TO_GET)
self.end_offset = task.get(CONF_DUE_HOURS_FORWARD_TO_GET)

self.task_last_created = dt.utcnow() - timedelta(minutes=5)
self.task_last_completed = dt.utcnow() - timedelta(minutes=5)
self._zero_date = datetime(1, 1, 1, 0, 0, 0, tzinfo=dt.DEFAULT_TIME_ZONE)

@property
def icon(self):
Expand Down Expand Up @@ -96,6 +96,34 @@ def extra_state_attributes(self):
extra_attributes[ATTR_OVERDUE_TASKS] = overdue_tasks
return extra_attributes

def _handle_coordinator_update(self) -> None:
tasks = self.coordinator.data[self.entity_key][ATTR_TASKS]
task_last_completed = self._zero_date
task_last_created = self._zero_date
for task in tasks:
if task.completed and task.completed > self.task_last_completed:
self._raise_event_external(
EVENT_COMPLETED_TASK,
task.task_id,
ATTR_COMPLETED,
task.completed,
)
if task.completed > task_last_completed:
task_last_completed = task.completed
if task.created and task.created > self.task_last_created:
self._raise_event_external(
EVENT_NEW_TASK, task.task_id, ATTR_CREATED, task.created
)
if task.created > task_last_created:
task_last_created = task.created

if task_last_completed > self._zero_date:
self.task_last_completed = task_last_completed
if task_last_created > self._zero_date:
self.task_last_created = task_last_created

self.async_write_ha_state()

def new_task(self, subject, description=None, due=None, reminder=None):
"""Create a new task for this task list."""
if not self._validate_task_permissions():
Expand Down Expand Up @@ -186,8 +214,41 @@ def _raise_event(self, event_type, task_id):
)
_LOGGER.debug("%s - %s", event_type, task_id)

def _raise_event_external(self, event_type, task_id, time_type, task_datetime):
self.hass.bus.fire(
f"{DOMAIN}_{event_type}",
{ATTR_TASK_ID: task_id, time_type: task_datetime, EVENT_HA_EVENT: False},
)
_LOGGER.debug("%s - %s - %s", event_type, task_id, task_datetime)

def _validate_task_permissions(self):
return self._validate_permissions(
PERM_MINIMUM_TASKS_WRITE,
f"Not authorised to create new task - requires permission: {PERM_TASKS_READWRITE}",
)


class O365TasksSensorSensorServices:
"""Sensor Services."""

def __init__(self, hass):
"""Initialise the sensor services."""
self._hass = hass

async def async_scan_for_task_lists(self, call): # pylint: disable=unused-argument
"""Scan for new task lists."""
for config in self._hass.data[DOMAIN]:
config = self._hass.data[DOMAIN][config]
todo_sensor = config.get(CONF_TODO_SENSORS)
if todo_sensor and CONF_ACCOUNT in config and todo_sensor.get(CONF_ENABLED):
todos = config[CONF_ACCOUNT].tasks()

todolists = await self._hass.async_add_executor_job(todos.list_folders)
track = todo_sensor.get(CONF_TRACK_NEW)
for todo in todolists:
update_task_list_file(
config,
todo,
self._hass,
track,
)
6 changes: 6 additions & 0 deletions custom_components/o365/const.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,13 +82,16 @@ class EventResponse(Enum):
CONF_CLIENT_ID = "client_id"
CONF_CLIENT_SECRET = "client_secret" # nosec
CONF_CONFIG_TYPE = "config_type"
CONF_COORDINATOR = "coordinator"
CONF_DEVICE_ID = "device_id"
CONF_DOWNLOAD_ATTACHMENTS = "download_attachments"
CONF_DUE_HOURS_BACKWARD_TO_GET = "due_start_offset"
CONF_DUE_HOURS_FORWARD_TO_GET = "due_end_offset"
CONF_EMAIL_SENSORS = "email_sensor"
CONF_ENABLE_UPDATE = "enable_update"
CONF_ENTITIES = "entities"
CONF_ENTITY_KEY = "entity_key"
CONF_ENTITY_TYPE = "entity_type"
CONF_EXCLUDE = "exclude"
CONF_FAILED_PERMISSIONS = "failed_permissions"
CONF_GROUPS = "groups"
Expand All @@ -98,6 +101,7 @@ class EventResponse(Enum):
CONF_HTML_BODY = "html_body"
CONF_IMPORTANCE = "importance"
CONF_IS_UNREAD = "is_unread"
CONF_KEYS = "keys"
CONF_MAIL_FOLDER = "folder"
CONF_MAIL_FROM = "from"
CONF_MAX_ITEMS = "max_items"
Expand All @@ -110,11 +114,13 @@ class EventResponse(Enum):
CONF_STATUS_SENSORS = "status_sensors"
CONF_SUBJECT_CONTAINS = "subject_contains"
CONF_SUBJECT_IS = "subject_is"
CONF_TODO = "todo"
CONF_TODO_SENSORS = "todo_sensors"
CONF_TRACK = "track"
CONF_TRACK_NEW_CALENDAR = "track_new_calendar"
CONF_TRACK_NEW = "track_new"
CONF_TASK_LIST_ID = "task_list_id"
CONF_TASK_LIST = "task_list"
CONF_URL = "url"
CONST_CONFIG_TYPE_DICT = "dict"
CONST_CONFIG_TYPE_LIST = "list"
Expand Down
Loading

0 comments on commit 33fee2f

Please sign in to comment.