2019-04-03 17:40:03 +02:00
|
|
|
"""Support for file notification."""
|
2015-06-20 11:00:20 +02:00
|
|
|
import os
|
2015-06-11 14:32:03 +02:00
|
|
|
|
2016-08-31 18:12:34 +02:00
|
|
|
import voluptuous as vol
|
|
|
|
|
2019-03-27 20:36:13 -07:00
|
|
|
from homeassistant.components.notify import (
|
2019-07-31 12:25:30 -07:00
|
|
|
ATTR_TITLE,
|
|
|
|
ATTR_TITLE_DEFAULT,
|
|
|
|
PLATFORM_SCHEMA,
|
|
|
|
BaseNotificationService,
|
|
|
|
)
|
2019-12-09 11:45:11 +01:00
|
|
|
from homeassistant.const import CONF_FILENAME
|
|
|
|
import homeassistant.helpers.config_validation as cv
|
|
|
|
import homeassistant.util.dt as dt_util
|
2016-08-31 18:12:34 +02:00
|
|
|
|
2019-07-31 12:25:30 -07:00
|
|
|
CONF_TIMESTAMP = "timestamp"
|
2016-08-31 18:12:34 +02:00
|
|
|
|
2019-07-31 12:25:30 -07:00
|
|
|
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
|
|
|
|
{
|
|
|
|
vol.Required(CONF_FILENAME): cv.string,
|
|
|
|
vol.Optional(CONF_TIMESTAMP, default=False): cv.boolean,
|
|
|
|
}
|
|
|
|
)
|
2015-06-11 14:32:03 +02:00
|
|
|
|
|
|
|
|
2017-01-15 03:53:14 +01:00
|
|
|
def get_service(hass, config, discovery_info=None):
|
2016-03-08 11:46:32 +01:00
|
|
|
"""Get the file notification service."""
|
2016-08-31 18:12:34 +02:00
|
|
|
filename = config[CONF_FILENAME]
|
|
|
|
timestamp = config[CONF_TIMESTAMP]
|
2015-06-11 14:32:03 +02:00
|
|
|
|
2015-06-20 11:00:20 +02:00
|
|
|
return FileNotificationService(hass, filename, timestamp)
|
2015-06-11 14:32:03 +02:00
|
|
|
|
|
|
|
|
|
|
|
class FileNotificationService(BaseNotificationService):
|
2016-03-08 11:46:32 +01:00
|
|
|
"""Implement the notification service for the File service."""
|
2015-06-11 14:32:03 +02:00
|
|
|
|
2015-06-20 11:00:20 +02:00
|
|
|
def __init__(self, hass, filename, add_timestamp):
|
2016-03-08 11:46:32 +01:00
|
|
|
"""Initialize the service."""
|
2015-06-20 11:00:20 +02:00
|
|
|
self.filepath = os.path.join(hass.config.config_dir, filename)
|
|
|
|
self.add_timestamp = add_timestamp
|
2015-06-11 14:32:03 +02:00
|
|
|
|
|
|
|
def send_message(self, message="", **kwargs):
|
2016-03-08 11:46:32 +01:00
|
|
|
"""Send a message to a file."""
|
2021-07-28 09:41:45 +02:00
|
|
|
with open(self.filepath, "a", encoding="utf8") as file:
|
2015-06-20 23:03:53 +02:00
|
|
|
if os.stat(self.filepath).st_size == 0:
|
2020-02-25 02:54:20 +01:00
|
|
|
title = f"{kwargs.get(ATTR_TITLE, ATTR_TITLE_DEFAULT)} notifications (Log started: {dt_util.utcnow().isoformat()})\n{'-' * 80}\n"
|
2015-06-20 23:03:53 +02:00
|
|
|
file.write(title)
|
|
|
|
|
2016-08-31 18:12:34 +02:00
|
|
|
if self.add_timestamp:
|
2020-02-25 02:54:20 +01:00
|
|
|
text = f"{dt_util.utcnow().isoformat()} {message}\n"
|
2015-06-20 23:03:53 +02:00
|
|
|
else:
|
2019-09-03 17:10:56 +02:00
|
|
|
text = f"{message}\n"
|
2016-09-01 15:35:00 +02:00
|
|
|
file.write(text)
|