"""Template helper methods for rendering strings with Home Assistant data.""" import asyncio import base64 import collections.abc from datetime import datetime, timedelta from functools import wraps import json import logging import math from operator import attrgetter import random import re from typing import Any, Generator, Iterable, List, Optional, Union from urllib.parse import urlencode as urllib_urlencode import weakref import jinja2 from jinja2 import contextfilter, contextfunction from jinja2.sandbox import ImmutableSandboxedEnvironment from jinja2.utils import Namespace # type: ignore import voluptuous as vol from homeassistant.const import ( ATTR_ENTITY_ID, ATTR_LATITUDE, ATTR_LONGITUDE, ATTR_UNIT_OF_MEASUREMENT, LENGTH_METERS, MATCH_ALL, STATE_UNKNOWN, ) from homeassistant.core import State, callback, split_entity_id, valid_entity_id from homeassistant.exceptions import TemplateError from homeassistant.helpers import config_validation as cv, location as loc_helper from homeassistant.helpers.frame import report from homeassistant.helpers.typing import HomeAssistantType, TemplateVarsType from homeassistant.loader import bind_hass from homeassistant.util import convert, dt as dt_util, location as loc_util from homeassistant.util.async_ import run_callback_threadsafe from homeassistant.util.thread import ThreadWithException # mypy: allow-untyped-calls, allow-untyped-defs # mypy: no-check-untyped-defs, no-warn-return-any _LOGGER = logging.getLogger(__name__) _SENTINEL = object() DATE_STR_FORMAT = "%Y-%m-%d %H:%M:%S" _RENDER_INFO = "template.render_info" _ENVIRONMENT = "template.environment" _RE_NONE_ENTITIES = re.compile(r"distance\(|closest\(", re.I | re.M) _RE_GET_ENTITIES = re.compile( r"(?:(?:(?:states\.|(?Pis_state|is_state_attr|state_attr|states|expand)\((?:[\ \'\"]?))(?P[\w]+\.[\w]+)|states\.(?P[a-z]+)|states\[(?:[\'\"]?)(?P[\w]+))|(?P[\w]+))", re.I | re.M, ) _RE_JINJA_DELIMITERS = re.compile(r"\{%|\{\{|\{#") _RESERVED_NAMES = {"contextfunction", "evalcontextfunction", "environmentfunction"} _GROUP_DOMAIN_PREFIX = "group." _COLLECTABLE_STATE_ATTRIBUTES = { "state", "attributes", "last_changed", "last_updated", "context", "domain", "object_id", "name", } DEFAULT_RATE_LIMIT = timedelta(seconds=1) @bind_hass def attach(hass: HomeAssistantType, obj: Any) -> None: """Recursively attach hass to all template instances in list and dict.""" if isinstance(obj, list): for child in obj: attach(hass, child) elif isinstance(obj, collections.abc.Mapping): for child_key, child_value in obj.items(): attach(hass, child_key) attach(hass, child_value) elif isinstance(obj, Template): obj.hass = hass def render_complex(value: Any, variables: TemplateVarsType = None) -> Any: """Recursive template creator helper function.""" if isinstance(value, list): return [render_complex(item, variables) for item in value] if isinstance(value, collections.abc.Mapping): return { render_complex(key, variables): render_complex(item, variables) for key, item in value.items() } if isinstance(value, Template): return value.async_render(variables) return value def is_complex(value: Any) -> bool: """Test if data structure is a complex template.""" if isinstance(value, Template): return True if isinstance(value, list): return any(is_complex(val) for val in value) if isinstance(value, collections.abc.Mapping): return any(is_complex(val) for val in value.keys()) or any( is_complex(val) for val in value.values() ) return False def is_template_string(maybe_template: str) -> bool: """Check if the input is a Jinja2 template.""" return _RE_JINJA_DELIMITERS.search(maybe_template) is not None def extract_entities( hass: HomeAssistantType, template: Optional[str], variables: TemplateVarsType = None, ) -> Union[str, List[str]]: """Extract all entities for state_changed listener from template string.""" report( "called template.extract_entities. Please use event.async_track_template_result instead as it can accurately handle watching entities" ) if template is None or not is_template_string(template): return [] if _RE_NONE_ENTITIES.search(template): return MATCH_ALL extraction_final = [] for result in _RE_GET_ENTITIES.finditer(template): if ( result.group("entity_id") == "trigger.entity_id" and variables and "trigger" in variables and "entity_id" in variables["trigger"] ): extraction_final.append(variables["trigger"]["entity_id"]) elif result.group("entity_id"): if result.group("func") == "expand": for entity in expand(hass, result.group("entity_id")): extraction_final.append(entity.entity_id) extraction_final.append(result.group("entity_id")) elif result.group("domain_inner") or result.group("domain_outer"): extraction_final.extend( hass.states.async_entity_ids( result.group("domain_inner") or result.group("domain_outer") ) ) if ( variables and result.group("variable") in variables and isinstance(variables[result.group("variable")], str) and valid_entity_id(variables[result.group("variable")]) ): extraction_final.append(variables[result.group("variable")]) if extraction_final: return list(set(extraction_final)) return MATCH_ALL def _true(arg: Any) -> bool: return True def _false(arg: Any) -> bool: return False class RenderInfo: """Holds information about a template render.""" def __init__(self, template): """Initialise.""" self.template = template # Will be set sensibly once frozen. self.filter_lifecycle = _true self.filter = _true self._result = None self.is_static = False self.exception = None self.all_states = False self.all_states_lifecycle = False self.domains = set() self.domains_lifecycle = set() self.entities = set() self.rate_limit = None def __repr__(self) -> str: """Representation of RenderInfo.""" return f"" def _filter_domains_and_entities(self, entity_id: str) -> bool: """Template should re-render if the entity state changes when we match specific domains or entities.""" return ( split_entity_id(entity_id)[0] in self.domains or entity_id in self.entities ) def _filter_lifecycle_domains(self, entity_id: str) -> bool: """Template should re-render if the entity is added or removed with domains watched.""" return split_entity_id(entity_id)[0] in self.domains_lifecycle def result(self) -> str: """Results of the template computation.""" if self.exception is not None: raise self.exception return self._result def _freeze_static(self) -> None: self.is_static = True self._freeze_sets() self.all_states = False def _freeze_sets(self) -> None: self.entities = frozenset(self.entities) self.domains = frozenset(self.domains) self.domains_lifecycle = frozenset(self.domains_lifecycle) def _freeze(self) -> None: self._freeze_sets() if self.rate_limit is None and ( self.domains or self.domains_lifecycle or self.all_states or self.exception ): # If the template accesses all states or an entire # domain, and no rate limit is set, we use the default. self.rate_limit = DEFAULT_RATE_LIMIT if self.exception: return if not self.all_states_lifecycle: if self.domains_lifecycle: self.filter_lifecycle = self._filter_lifecycle_domains else: self.filter_lifecycle = _false if self.all_states: return if self.entities or self.domains: self.filter = self._filter_domains_and_entities else: self.filter = _false class Template: """Class to hold a template and manage caching and rendering.""" def __init__(self, template, hass=None): """Instantiate a template.""" if not isinstance(template, str): raise TypeError("Expected template to be a string") self.template: str = template self._compiled_code = None self._compiled = None self.hass = hass self.is_static = not is_template_string(template) @property def _env(self): if self.hass is None: return _NO_HASS_ENV ret = self.hass.data.get(_ENVIRONMENT) if ret is None: ret = self.hass.data[_ENVIRONMENT] = TemplateEnvironment(self.hass) return ret def ensure_valid(self): """Return if template is valid.""" if self._compiled_code is not None: return try: self._compiled_code = self._env.compile(self.template) except jinja2.TemplateError as err: raise TemplateError(err) from err def extract_entities( self, variables: TemplateVarsType = None ) -> Union[str, List[str]]: """Extract all entities for state_changed listener.""" if self.is_static: return [] return extract_entities(self.hass, self.template, variables) def render(self, variables: TemplateVarsType = None, **kwargs: Any) -> str: """Render given template.""" if self.is_static: return self.template.strip() if variables is not None: kwargs.update(variables) return run_callback_threadsafe( self.hass.loop, self.async_render, kwargs ).result() @callback def async_render(self, variables: TemplateVarsType = None, **kwargs: Any) -> str: """Render given template. This method must be run in the event loop. """ if self.is_static: return self.template.strip() compiled = self._compiled or self._ensure_compiled() if variables is not None: kwargs.update(variables) try: return compiled.render(kwargs).strip() except jinja2.TemplateError as err: raise TemplateError(err) from err async def async_render_will_timeout( self, timeout: float, variables: TemplateVarsType = None, **kwargs: Any ) -> bool: """Check to see if rendering a template will timeout during render. This is intended to check for expensive templates that will make the system unstable. The template is rendered in the executor to ensure it does not tie up the event loop. This function is not a security control and is only intended to be used as a safety check when testing templates. This method must be run in the event loop. """ assert self.hass if self.is_static: return False compiled = self._compiled or self._ensure_compiled() if variables is not None: kwargs.update(variables) finish_event = asyncio.Event() def _render_template(): try: compiled.render(kwargs) except TimeoutError: pass finally: run_callback_threadsafe(self.hass.loop, finish_event.set) try: template_render_thread = ThreadWithException(target=_render_template) template_render_thread.start() await asyncio.wait_for(finish_event.wait(), timeout=timeout) except asyncio.TimeoutError: template_render_thread.raise_exc(TimeoutError) return True finally: template_render_thread.join() return False @callback def async_render_to_info( self, variables: TemplateVarsType = None, **kwargs: Any ) -> RenderInfo: """Render the template and collect an entity filter.""" assert self.hass and _RENDER_INFO not in self.hass.data render_info = RenderInfo(self) # pylint: disable=protected-access if self.is_static: render_info._result = self.template.strip() render_info._freeze_static() return render_info self.hass.data[_RENDER_INFO] = render_info try: render_info._result = self.async_render(variables, **kwargs) except TemplateError as ex: render_info.exception = ex finally: del self.hass.data[_RENDER_INFO] render_info._freeze() return render_info def render_with_possible_json_value(self, value, error_value=_SENTINEL): """Render template with value exposed. If valid JSON will expose value_json too. """ if self.is_static: return self.template return run_callback_threadsafe( self.hass.loop, self.async_render_with_possible_json_value, value, error_value, ).result() @callback def async_render_with_possible_json_value( self, value, error_value=_SENTINEL, variables=None ): """Render template with value exposed. If valid JSON will expose value_json too. This method must be run in the event loop. """ if self.is_static: return self.template if self._compiled is None: self._ensure_compiled() variables = dict(variables or {}) variables["value"] = value try: variables["value_json"] = json.loads(value) except (ValueError, TypeError): pass try: return self._compiled.render(variables).strip() except jinja2.TemplateError as ex: if error_value is _SENTINEL: _LOGGER.error( "Error parsing value: %s (value: %s, template: %s)", ex, value, self.template, ) return value if error_value is _SENTINEL else error_value def _ensure_compiled(self): """Bind a template to a specific hass instance.""" self.ensure_valid() assert self.hass is not None, "hass variable not set on template" env = self._env self._compiled = jinja2.Template.from_code( env, self._compiled_code, env.globals, None ) return self._compiled def __eq__(self, other): """Compare template with another.""" return ( self.__class__ == other.__class__ and self.template == other.template and self.hass == other.hass ) def __hash__(self) -> int: """Hash code for template.""" return hash(self.template) def __repr__(self) -> str: """Representation of Template.""" return 'Template("' + self.template + '")' class RateLimit: """Class to control update rate limits.""" def __init__(self, hass: HomeAssistantType): """Initialize rate limit.""" self._hass = hass def __call__(self, *args: Any, **kwargs: Any) -> str: """Handle a call to the class.""" render_info = self._hass.data.get(_RENDER_INFO) if render_info is not None: render_info.rate_limit = timedelta(*args, **kwargs) return "" def __repr__(self) -> str: """Representation of a RateLimit.""" return "