"""Template helper methods for rendering strings with Home Assistant data.""" from datetime import datetime import json import logging import math import random import re import jinja2 from jinja2 import contextfilter from jinja2.sandbox import ImmutableSandboxedEnvironment from homeassistant.const import ( ATTR_LATITUDE, ATTR_LONGITUDE, ATTR_UNIT_OF_MEASUREMENT, MATCH_ALL, STATE_UNKNOWN) from homeassistant.core import State, valid_entity_id from homeassistant.exceptions import TemplateError from homeassistant.helpers import location as loc_helper from homeassistant.loader import bind_hass from homeassistant.util import convert from homeassistant.util import dt as dt_util from homeassistant.util import location as loc_util from homeassistant.util.async_ import run_callback_threadsafe _LOGGER = logging.getLogger(__name__) _SENTINEL = object() DATE_STR_FORMAT = "%Y-%m-%d %H:%M:%S" _RE_NONE_ENTITIES = re.compile(r"distance\(|closest\(", re.I | re.M) _RE_GET_ENTITIES = re.compile( r"(?:(?:states\.|(?:is_state|is_state_attr|state_attr|states)" r"\((?:[\ \'\"]?))([\w]+\.[\w]+)|([\w]+))", re.I | re.M ) @bind_hass def attach(hass, obj): """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, dict): for child in obj.values(): attach(hass, child) elif isinstance(obj, Template): obj.hass = hass def render_complex(value, variables=None): """Recursive template creator helper function.""" if isinstance(value, list): return [render_complex(item, variables) for item in value] if isinstance(value, dict): return {key: render_complex(item, variables) for key, item in value.items()} return value.async_render(variables) def extract_entities(template, variables=None): """Extract all entities for state_changed listener from template string.""" if template is None or _RE_NONE_ENTITIES.search(template): return MATCH_ALL extraction = _RE_GET_ENTITIES.findall(template) extraction_final = [] for result in extraction: if result[0] == 'trigger.entity_id' and 'trigger' in variables and \ 'entity_id' in variables['trigger']: extraction_final.append(variables['trigger']['entity_id']) elif result[0]: extraction_final.append(result[0]) if variables and result[1] in variables and \ isinstance(variables[result[1]], str) and \ valid_entity_id(variables[result[1]]): extraction_final.append(variables[result[1]]) if extraction_final: return list(set(extraction_final)) return MATCH_ALL 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 = template self._compiled_code = None self._compiled = None self.hass = hass def ensure_valid(self): """Return if template is valid.""" if self._compiled_code is not None: return try: self._compiled_code = ENV.compile(self.template) except jinja2.exceptions.TemplateSyntaxError as err: raise TemplateError(err) def extract_entities(self, variables=None): """Extract all entities for state_changed listener.""" return extract_entities(self.template, variables) def render(self, variables=None, **kwargs): """Render given template.""" if variables is not None: kwargs.update(variables) return run_callback_threadsafe( self.hass.loop, self.async_render, kwargs).result() def async_render(self, variables=None, **kwargs): """Render given template. This method must be run in the event loop. """ if self._compiled is None: self._ensure_compiled() if variables is not None: kwargs.update(variables) try: return self._compiled.render(kwargs).strip() except jinja2.TemplateError as err: raise TemplateError(err) def render_with_possible_json_value(self, value, error_value=_SENTINEL): """Render template with value exposed. If valid JSON will expose value_json too. """ return run_callback_threadsafe( self.hass.loop, self.async_render_with_possible_json_value, value, error_value).result() def async_render_with_possible_json_value(self, value, error_value=_SENTINEL): """Render template with value exposed. If valid JSON will expose value_json too. This method must be run in the event loop. """ if self._compiled is None: self._ensure_compiled() variables = { 'value': value } try: variables['value_json'] = json.loads(value) except ValueError: pass try: return self._compiled.render(variables).strip() except jinja2.TemplateError as ex: _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' template_methods = TemplateMethods(self.hass) global_vars = ENV.make_globals({ 'closest': template_methods.closest, 'distance': template_methods.distance, 'is_state': self.hass.states.is_state, 'is_state_attr': template_methods.is_state_attr, 'state_attr': template_methods.state_attr, 'states': AllStates(self.hass), }) self._compiled = jinja2.Template.from_code( ENV, self._compiled_code, global_vars, 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) class AllStates: """Class to expose all HA states as attributes.""" def __init__(self, hass): """Initialize all states.""" self._hass = hass def __getattr__(self, name): """Return the domain state.""" return DomainStates(self._hass, name) def __iter__(self): """Return all states.""" return iter( _wrap_state(state) for state in sorted(self._hass.states.async_all(), key=lambda state: state.entity_id)) def __len__(self): """Return number of states.""" return len(self._hass.states.async_entity_ids()) def __call__(self, entity_id): """Return the states.""" state = self._hass.states.get(entity_id) return STATE_UNKNOWN if state is None else state.state class DomainStates: """Class to expose a specific HA domain as attributes.""" def __init__(self, hass, domain): """Initialize the domain states.""" self._hass = hass self._domain = domain def __getattr__(self, name): """Return the states.""" return _wrap_state( self._hass.states.get('{}.{}'.format(self._domain, name))) def __iter__(self): """Return the iteration over all the states.""" return iter(sorted( (_wrap_state(state) for state in self._hass.states.async_all() if state.domain == self._domain), key=lambda state: state.entity_id)) def __len__(self): """Return number of states.""" return len(self._hass.states.async_entity_ids(self._domain)) class TemplateState(State): """Class to represent a state object in a template.""" # Inheritance is done so functions that check against State keep working # pylint: disable=super-init-not-called def __init__(self, state): """Initialize template state.""" self._state = state @property def state_with_unit(self): """Return the state concatenated with the unit if available.""" state = object.__getattribute__(self, '_state') unit = state.attributes.get(ATTR_UNIT_OF_MEASUREMENT) if unit is None: return state.state return "{} {}".format(state.state, unit) def __getattribute__(self, name): """Return an attribute of the state.""" if name in TemplateState.__dict__: return object.__getattribute__(self, name) return getattr(object.__getattribute__(self, '_state'), name) def __repr__(self): """Representation of Template State.""" rep = object.__getattribute__(self, '_state').__repr__() return '