Skip to content
Open

Beta #70

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 27 additions & 17 deletions apps/notifier/alexa_manager.py
100755 → 100644
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import json
import re
import time
from queue import Queue
import re
from threading import Thread
import time

import hassapi as hass # type: ignore

Expand Down Expand Up @@ -51,14 +51,14 @@

MOBILE_PUSH_TYPE = (PUSH, "dropin", "dropin_notification")
SUB_VOICE = [
("[\U00010000-\U0010ffff]", ""), # strip emoji
("[\?\.\!,]+(?=[\?\.\!,])", ""), # strip duplicate dot and comma
("(\s+\.|\s+\.\s+|[\.])(?! )(?![^{<]*[}>])(?![^\d.]*\d)", ". "),
("&", " and "), # escape
("[\n\*]", " "), # remove end-of-line (Carriage Return)
(" +", " "), # remove whitespace
(r"[\U00010000-\U0010ffff]", r""), # strip emoji
(r"[\?\.\!,]+(?=[\?\.\!,])", r""), # strip duplicate dot and comma
(r"(\s+\.|\s+\.\s+|[\.])(?! )(?![^{<]*[}>])(?![^\d.]*\d)", r". "),
(r"&", r" and "), # escape
(r"[\n\*]", r" "), # remove end-of-line (Carriage Return)
(r" +", r" "), # remove whitespace
]
SUB_TEXT = [(" +", " "), ("\s\s+", "\n")]
SUB_TEXT = [(r" +", r" "), (r"\s\s+", r"\n")]

SPEECHCON_IT = (
"a ah",
Expand Down Expand Up @@ -374,8 +374,10 @@ def speak(self, alexa: dict, skill_id: str, cfg: dict) -> None:
type_ = {TYPE: PUSH} if push else {TYPE: data_type}
self.call_service(
NOTIFY + ALEXA_SERVICE,
data=type_,
target=media_player[0],
service_data={
"target": media_player[0],
"data": type_
},
title=str(alexa.get(TITLE, "")),
message=message_push,
)
Expand Down Expand Up @@ -443,7 +445,7 @@ def str2list(self, string: str) -> list:

def has_numbers(self, string: str):
"""Check if a string contains a number."""
numbers = re.compile("\d{2}:\d{2}|\d{4,}|\d{3,}\.\d")
numbers = re.compile(r"\d{2}:\d{2}|\d{4,}|\d{3,}\.\d")
return numbers.search(string)

def remove_tags(self, text: str) -> str:
Expand Down Expand Up @@ -597,12 +599,18 @@ def volume_auto_silent(self, media_player: list, volume: float) -> None:
continue
self.lg(f"DIFFERENT VOLUMES: {volume_get} - DEFAULT: {volume}")
if status.get("state", "") != "playing":
self.call_service(NOTIFY + ALEXA_SERVICE, data={TYPE: "tts"}, target=i, message=m)
self.call_service(
NOTIFY + ALEXA_SERVICE,
service_data={
"target": i,
"data": {TYPE: "tts"}
},
message=m)
time.sleep(2)
self.call_service("media_player/volume_set", entity_id=i, volume_level=volume)
# Force attribute volume level in Home assistant
self.set_state(i, attributes={"volume_level": volume})
self.call_service("alexa_media/update_last_called", return_result=True)
self.call_service("alexa_media/update_last_called")

def volume_get_save(self, media_player: list, volume: float, defvol: float) -> None:
"""Get and save the volume of each media player only if different."""
Expand All @@ -622,7 +630,7 @@ def volume_restore(self) -> None:
time.sleep(1)
# Force attribute volume level in Home assistant
self.set_state(i, attributes={"volume_level": j})
self.call_service("alexa_media/update_last_called", return_result=True)
self.call_service("alexa_media/update_last_called")
self.lg(f"RESTORE VOL: {i} {j} [State:" f" {self.get_state(i, attribute='volume_level')}]")

def volume_set(self, media_player: list, volume: float) -> None:
Expand Down Expand Up @@ -717,8 +725,10 @@ def worker(self):
# Speak >>>
self.call_service(
NOTIFY + data[NOTIFIER],
data=alexa_data,
target=media_player,
service_data={
"target": media_player,
"data": alexa_data
},
message=msg.strip(),
)

Expand Down
2 changes: 1 addition & 1 deletion apps/notifier/alexa_manager.yaml
100755 → 100644
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ Alexa_Manager:
module: alexa_manager
class: Alexa_Manager

# log_level: DEBUG
log_level: DEBUG

# Alexa hub
binary_speak: binary_sensor.notifier_alexa_speak
Expand Down
36 changes: 17 additions & 19 deletions apps/notifier/gh_manager.py
100755 → 100644
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import sys
import time
from queue import Queue
import sys
from threading import Thread
import time

import hassapi as hass
import helpermodule as h
Expand All @@ -16,16 +16,16 @@

__NOTIFY__ = "notify/"
__TTS__ = "tts/"
SUB_TTS = [("[\*\-\[\]_\(\)\{\~\|\}\s]+"," ")]
SUB_TTS = [(r"[\*\-\[\]_\(\)\{\~\|\}\s]+",r" ")]
SUB_VOICE = [
("[\U00010000-\U0010ffff]", ""), # strip emoji
("[\?\.\!,]+(?=[\?\.\!,])", ""), # Exclude duplicate
("(\s+\.|\s+\.\s+|[\.])(?! )(?![^{]*})(?![^\d.]*\d)", ". "),
("<.*?>",""), # HTML TAG
("&", " and "), # escape
(r"[\U00010000-\U0010ffff]", r""), # strip emoji
(r"[\?\.\!,]+(?=[\?\.\!,])", r""), # Exclude duplicate
(r"(\s+\.|\s+\.\s+|[\.])(?! )(?![^{]*})(?![^\d.]*\d)", r". "),
(r"<.*?>",r""), # HTML TAG
(r"&", r" and "), # escape
# ("(?<!\d),(?!\d)", ", "),
("[\n\*]", " "),
(" +", " "),
(r"[\n\*]", r" "),
(r" +", r" "),
]

CONF_MEDIA_PLAYER = "media_player"
Expand All @@ -42,7 +42,6 @@

class GH_Manager(hass.Hass):
def initialize(self)->None:
self.gh_service = h.get_arg(self.args, "gh_service")
self.gh_wait_time = h.get_arg(self.args, "gh_wait_time")
self.gh_select_media_player = h.get_arg(self.args, "gh_select_media_player")
self.gh_sensor_media_player = h.get_arg(self.args, "gh_sensor_media_player")
Expand All @@ -52,13 +51,14 @@ def initialize(self)->None:
self.ytube_called = False
self.debug_sensor = h.get_arg(self.args, "debug_sensor")
self.set_state(self.debug_sensor, state="on")
self.check_gh_service = self.check_gh(self.gh_service)
##
hass_config = self.get_plugin_config()
self.tts_components = [s for s in hass_config["components"] if "tts" in s]
self._player = {}
##
for k in list(self.get_state(CONF_MEDIA_PLAYER).keys()):
if CONF_FRIENDLY_NAME in self.get_state(CONF_MEDIA_PLAYER)[k][CONF_ATTRIBUTES]:
self._player.update({str(self.get_state(CONF_MEDIA_PLAYER)[k][CONF_ATTRIBUTES][CONF_FRIENDLY_NAME]).lower():k})

self.queue = Queue(maxsize=0)
self._when_tts_done_callback_queue = Queue()
t = Thread(target=self.worker)
Expand Down Expand Up @@ -116,11 +116,9 @@ def set_debug_sensor(self, state, error):
attributes["google_error"] = error
self.set_state(self.debug_sensor, state=state, attributes=attributes)

def check_gh(self, service):
def check_gh(self, service, tts_components):
""" check if tts service exist in HA """
self.hass_config = self.get_plugin_config()
components = self.hass_config["components"]
return next((True for comp in components if service in comp), False)
return next((True for comp in tts_components if comp.replace("tts", "").replace(".", "") in service), False)

def restore_mplayer_states(self, gh_players:list, dict_info_mplayers:dict)->None:
""" Restore volumes and media-player states """
Expand Down Expand Up @@ -154,9 +152,9 @@ def restore_mplayer_states(self, gh_players:list, dict_info_mplayers:dict)->None

def speak(self, google, gh_mode: bool, gh_notifier: str, cfg: dict):
""" Speak the provided text through the media player. """
if not self.check_gh_service:
if not self.check_gh(gh_notifier,self.tts_components):
self.set_debug_sensor(
"I can't find the TTS Google component", "https://www.home-assistant.io/integrations/tts"
"I can't find the TTS Google component", "https://www.home-assistant.io/integrations/tts",
)
return
if "media_player" not in google:
Expand Down
Empty file modified apps/notifier/gh_manager.yaml
100755 → 100644
Empty file.
5 changes: 3 additions & 2 deletions apps/notifier/helpermodule.py
100755 → 100644
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
'''Miscellaneous support functions for notifier'''
import re


def check_location(data, location)->bool:
return (str(data).lower() =="" or str(data).lower()==location)

Expand Down Expand Up @@ -75,9 +76,9 @@ def replace_language(s: str)->str:

# """Remove all tags from a string."""
def remove_tags(text: str)->str:
regex = re.compile("<.*?>")
regex = re.compile(r"<.*?>")
return re.sub(regex, "", str(text).strip())

def has_numbers(string):
numbers = re.compile("\d{4,}|\d{3,}\.\d")
numbers = re.compile(r"\d{4,}|\d{3,}\.\d")
return numbers.search(string)
14 changes: 7 additions & 7 deletions apps/notifier/notification_manager.py
100755 → 100644
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,10 @@
Class Notification_Manager handles sending text to notfyng service
"""
__NOTIFY__ = "notify/"
SUB_NOTIFICHE_NOWRAP = [("\s+", " "), (" +", " ")]
SUB_NOTIFICHE_WRAP = [(" +", " "), ("\s\s+", "\n")]
SUB_NOTIFIER = [("\s+", "_"), ("\.", "/")]
SUB_REMOVE_SPACE = [("\s*,\s*", ",")]
SUB_NOTIFICHE_NOWRAP = [(r"\s+", r" "), (r" +", r" ")]
SUB_NOTIFICHE_WRAP = [(r" +", r" "), (r"\s\s+", r"\n")]
SUB_NOTIFIER = [(r"\s+", r"_"), (r"\.", r"/")]
SUB_REMOVE_SPACE = [(r"\s*,\s*", r",")]


class Notification_Manager(hass.Hass):
Expand All @@ -24,10 +24,10 @@ def initialize(self):
def prepare_text(self, html, message, title, timestamp, assistant_name):
if str(html).lower() in ["true", "on", "yes", "1"]:
title = "<b>[{} - {}] {}</b>".format(assistant_name, timestamp, title)
title = h.replace_regular(title, [("\s<", "<")])
title = h.replace_regular(title, [(r"\s<", r"<")])
else:
title = "*[{} - {}] {}*".format(assistant_name, timestamp, title)
title = h.replace_regular(title, [("\s\*", "*")])
title = h.replace_regular(title, [(r"\s\*", r"*")])
if self.get_state(self.boolean_wrap_text) == "on":
message = h.replace_regular(message, SUB_NOTIFICHE_WRAP)
else:
Expand Down Expand Up @@ -109,7 +109,7 @@ def send_notify(self, data, notify_name, assistant_name: str):
extra_data.update({"photo": file_data})
# self.log("[EXTRA-DATA]: {}".format(extra_data), ascii_encode = False)
if str(html).lower() not in ["true", "on", "yes", "1"]:
messaggio = messaggio.replace("_", "\_")
messaggio = messaggio.replace(r"_", r"\_")
else:
extra_data.update({"parse_mode": "html"})
if image != "":
Expand Down
Empty file modified apps/notifier/notification_manager.yaml
100755 → 100644
Empty file.
30 changes: 18 additions & 12 deletions apps/notifier/notifier_dispatch.py
100755 → 100644
Original file line number Diff line number Diff line change
Expand Up @@ -134,8 +134,8 @@ def initialize(self):

#### FROM CONFIGURATION BLUEPRINT ###
self.config = self.get_plugin_config()
self.config_dir = self.config["config_dir"]
self.log(f"configuration dir: {self.config_dir}")
self.configdir = self.config["config_dir"] #"/homeassistant"
self.log(f"configuration dir: {self.configdir}")
### FROM SENSOR CONFIG
sensor_config = self.get_state("sensor.notifier_config", attribute="all", default={})
self.notifier_config("initialize", sensor_config.get("attributes", {}), {})
Expand All @@ -154,9 +154,9 @@ def initialize(self):

#####################################################################
def ad_command(self, ad):
command = ad.get("command")
self.log(f"Run command: {command}")
match command: # type: ignore
c = ad.get("command")
self.log(f"Run command: {c}")
match c: # type: ignore
case "restart":
self.restart_app("Notifier_Dispatch")
case _:
Expand Down Expand Up @@ -192,12 +192,13 @@ def get_zip_file(self, file_names):
except ValueError as ex:
self.log(f"Download failed: {ex}")

def get_local_version(self, cn_path, file_names):
def get_local_version(self, cn_path, file_main):
### Get the local version ###########
version_installed = "0.0.0"
if os.path.isfile(cn_path + file_names):
cn_file = cn_path + file_main
if os.path.isfile(cn_file):
try:
with open(cn_path + file_names, "r") as ymlfile:
with open(cn_file, "r") as ymlfile:
load_main = yaml.load(ymlfile, Loader=yaml.BaseLoader)
node = load_main["homeassistant"]["customize"]
if "package.cn" in node:
Expand Down Expand Up @@ -240,7 +241,7 @@ def get_path_packges(self, ha_config_file, cn_path):
config = yaml.load(ymlfile, Loader=yaml.BaseLoader)
if "homeassistant" in config and "packages" in config["homeassistant"]:
packages_folder = config["homeassistant"]["packages"]
cn_path = f"{self.config_dir}/{packages_folder}/centro_notifiche/"
cn_path = f"{self.configdir}/{packages_folder}/centro_notifiche/"

self.log(f"Package folder: {packages_folder}")
else:
Expand All @@ -261,13 +262,18 @@ def package_download(self, delay):
is_beta = self.cfg.get("beta_version")
if not is_download:
return
ha_config_file = self.config_dir + "/configuration.yaml"
cn_path = self.config_dir + f"/{PATH_PACKAGES}/"
blueprints_path = self.config_dir + f"/{PATH_BLUEPRINTS}/"
ha_config_file = self.configdir + "/configuration.yaml"
cn_path = self.configdir + f"/{PATH_PACKAGES}/"
blueprints_path = self.configdir + f"/{PATH_BLUEPRINTS}/"
###################################################
branche = "beta" if is_beta else "main"
url_main = URL_ZIP.format(branche)
cn_path = self.get_path_packges(ha_config_file, cn_path) ##<-- cn_path
#TODO FIX for OS (get_path_packges)
if not cn_path:
ha_config_file = "/homeassistant/configuration.yaml"
cn_path = f"/homeassistant/{PATH_PACKAGES}/"
blueprints_path = f"/homeassistant/{PATH_BLUEPRINTS}/"
self.client = FileDownloader(url_main, URL_PACKAGE_RELEASES, cn_path) # <-- START THE CLIENT
version_latest = self.get_remote_version() # <-- recupero versione da github
version_installed = self.get_local_version(cn_path, FILE_MAIN) # <-- recupero versione locale
Expand Down
Empty file modified apps/notifier/notifier_dispatch.yaml
100755 → 100644
Empty file.
2 changes: 1 addition & 1 deletion apps/notifier/phone_manager.py
100755 → 100644
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
"""

__NOTIFY__ = "notify/"
SUB_TTS = [("[\*\-\[\]_\(\)\{\~\|\}\s]+", " ")]
SUB_TTS = [(r"[\*\-\[\]_\(\)\{\~\|\}\s]+", r" ")]


class Phone_Manager(hass.Hass):
Expand Down
Empty file modified apps/notifier/phone_manager.yaml
100755 → 100644
Empty file.