core/homeassistant/components/file/notify.py

66 lines
2.0 KiB
Python
Raw Normal View History

"""Support for file notification."""
2022-02-12 17:49:37 +00:00
from __future__ import annotations
2015-06-20 09:00:20 +00:00
import os
2022-02-12 17:49:37 +00:00
from typing import TextIO
2015-06-11 12:32:03 +00:00
2016-08-31 16:12:34 +00:00
import voluptuous as vol
from homeassistant.components.notify import (
2019-07-31 19:25:30 +00:00
ATTR_TITLE,
ATTR_TITLE_DEFAULT,
PLATFORM_SCHEMA,
BaseNotificationService,
)
from homeassistant.const import CONF_FILENAME
2022-02-12 17:49:37 +00:00
from homeassistant.core import HomeAssistant
import homeassistant.helpers.config_validation as cv
2022-02-12 17:49:37 +00:00
from homeassistant.helpers.typing import ConfigType
import homeassistant.util.dt as dt_util
2016-08-31 16:12:34 +00:00
2019-07-31 19:25:30 +00:00
CONF_TIMESTAMP = "timestamp"
2016-08-31 16:12:34 +00:00
2019-07-31 19:25:30 +00:00
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
vol.Required(CONF_FILENAME): cv.string,
vol.Optional(CONF_TIMESTAMP, default=False): cv.boolean,
}
)
2015-06-11 12:32:03 +00:00
2022-02-12 17:49:37 +00:00
def get_service(
hass: HomeAssistant, config: ConfigType, discovery_info=None
) -> FileNotificationService:
2016-03-08 10:46:32 +00:00
"""Get the file notification service."""
2022-02-12 17:49:37 +00:00
filename: str = config[CONF_FILENAME]
timestamp: bool = config[CONF_TIMESTAMP]
2015-06-11 12:32:03 +00:00
2022-02-12 17:49:37 +00:00
return FileNotificationService(filename, timestamp)
2015-06-11 12:32:03 +00:00
class FileNotificationService(BaseNotificationService):
2016-03-08 10:46:32 +00:00
"""Implement the notification service for the File service."""
2015-06-11 12:32:03 +00:00
2022-02-12 17:49:37 +00:00
def __init__(self, filename: str, add_timestamp: bool) -> None:
2016-03-08 10:46:32 +00:00
"""Initialize the service."""
2022-02-12 17:49:37 +00:00
self.filename = filename
2015-06-20 09:00:20 +00:00
self.add_timestamp = add_timestamp
2015-06-11 12:32:03 +00:00
2022-02-12 17:49:37 +00:00
def send_message(self, message="", **kwargs) -> None:
2016-03-08 10:46:32 +00:00
"""Send a message to a file."""
2022-02-12 17:49:37 +00:00
file: TextIO
if not self.hass.config.config_dir:
return
filepath: str = os.path.join(self.hass.config.config_dir, self.filename)
with open(filepath, "a", encoding="utf8") as file:
if os.stat(filepath).st_size == 0:
title = f"{kwargs.get(ATTR_TITLE, ATTR_TITLE_DEFAULT)} notifications (Log started: {dt_util.utcnow().isoformat()})\n{'-' * 80}\n"
2015-06-20 21:03:53 +00:00
file.write(title)
2016-08-31 16:12:34 +00:00
if self.add_timestamp:
text = f"{dt_util.utcnow().isoformat()} {message}\n"
2015-06-20 21:03:53 +00:00
else:
text = f"{message}\n"
file.write(text)