Skip to content

Commit

Permalink
Merge pull request #52 from caiosweet/beta
Browse files Browse the repository at this point in the history
First Beta clean code.
  • Loading branch information
jumping2000 authored Jun 10, 2023
2 parents b7737b9 + 7100fef commit c4b0512
Show file tree
Hide file tree
Showing 3 changed files with 78 additions and 95 deletions.
4 changes: 1 addition & 3 deletions apps/notifier/notification_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
class Notification_Manager(hass.Hass):

def initialize(self):
#self.text_last_message = globals.get_arg(self.args, "text_last_message")
self.text_last_message = h.get_arg(self.args, "text_last_message")
self.boolean_wrap_text = h.get_arg(self.args, "boolean_wrap_text")
self.boolean_tts_clock = h.get_arg(self.args, "boolean_tts_clock")
Expand Down Expand Up @@ -89,7 +88,6 @@ def send_notify(self, data, notify_name, assistant_name: str):
pass
#### TELEGRAM #######################
elif item.find("telegram") != -1:
if item.find("telegram") != -1:
messaggio, titolo = self.prepare_text(html, message, title, timestamp, assistant_name)
extra_data = {}
if isinstance(telegram, dict):
Expand Down Expand Up @@ -295,7 +293,7 @@ def send_notify(self, data, notify_name, assistant_name: str):
message = ("{} {}".format(message,link))
self.call_service(item, message=message, title=title)

def send_persistent(self, data, assistant_name): # persistent_notification_info, delete
def send_persistent(self, data, assistant_name):
title = assistant_name if assistant_name else "Centro Messaggi"
timestamp = datetime.datetime.now().strftime("%H:%M:%S")
messaggio=""
Expand Down
160 changes: 74 additions & 86 deletions apps/notifier/notifier_dispatch.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
DEFAULT_SIP_SERVER_NAME = "fritz.box:5060"
DEFAULT_REVERSO_TTS = "reversotts_say"

URL_PACKAGE_LATEST = "https://api.github.com/repos/caiosweet/Package-Notification-HUB-AppDaemon/releases/latest"
URL_PACKAGE_RELEASES = "https://api.github.com/repos/caiosweet/Package-Notification-HUB-AppDaemon/releases"
URL_BASE_REPO = "https://raw.githubusercontent.com/caiosweet/Package-Notification-HUB-AppDaemon/{}/{}/{}"
PATH_PACKAGES = "packages/centro_notifiche"
PATH_BLUEPRINTS = "blueprints/automation/caiosweet"
Expand All @@ -33,9 +33,9 @@

class Notifier_Dispatch(hass.Hass):
def initialize(self):
notifier_config = self.get_state("sensor.notifier_config", attribute="all", default={})
self.cfg = notifier_config.get("attributes", {})
self.log(f"Assistant name: {notifier_config.get('state')}")
# notifier_config = self.get_state("sensor.notifier_config", attribute="all", default={})
# self.cfg = notifier_config.get("attributes", {})
# self.log(f"Assistant name: {notifier_config.get('state')}")

self.debug_sensor = h.get_arg(self.args, "debug_sensor")
self.set_state(self.debug_sensor, state="off")
Expand All @@ -57,30 +57,16 @@ def initialize(self):
self.priority_message = h.get_arg(self.args, "priority_message")
self.guest_mode = h.get_arg(self.args, "guest_mode")

# self.persistent_notification_info = h.get_arg(self.args, "persistent_notification_info") # Delete

self.location_tracker = h.get_arg(self.args, "location_tracker")
self.personal_assistant_name = h.get_arg(self.args, "personal_assistant_name")
self.phone_called_number = h.get_arg(self.args, "phone_called_number")

# self.debug_sensor = h.get_arg(self.args, "debug_sensor") # delete
# self.set_state(self.debug_sensor, state="on")
#### FROM SECRET FILE ###
#### 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.notifier_config("init", {}, {}) # init
# self.log(f"configuration: {self.config}")
### old method - backward compatibility ->> delete
secretsFile = self.config_dir + "/secrets.yaml"
with open(secretsFile, "r") as ymlfile:
cfg = yaml.load(ymlfile, Loader=yaml.BaseLoader) # yaml.safe_load # FullLoader
self.gh_tts = cfg.get("tts_google", DEFAULT_TTS_GOOGLE)
self.gh_notify = cfg.get("notify_google", DEFAULT_NOTIFY_GOOGLE)
self.phone_sip_server = cfg.get("sip_server_name", DEFAULT_SIP_SERVER_NAME)
self.gh_tts_cloud = cfg.get("tts_google_cloud", DEFAULT_TTS_GOOGLE_CLOUD)
self.reverso_tts = cfg.get("reverso_tts", DEFAULT_REVERSO_TTS)
self.alexa_skill_id = cfg.get("notifier_alexa_actionable_skill_id", "")
### <<<- delete

### APP MANAGER ###
self.notification_manager = self.get_app("Notification_Manager")
self.gh_manager = self.get_app("GH_Manager")
Expand Down Expand Up @@ -112,55 +98,46 @@ def notifier_config(self, event_name, cfg, kwargs):
self.gh_tts_cloud = cfg.get("tts_google_cloud", DEFAULT_TTS_GOOGLE_CLOUD)
self.reverso_tts = cfg.get("reverso_tts", DEFAULT_REVERSO_TTS)
self.alexa_skill_id = cfg.get("alexa_skill_id", "")

self.cfg_personal_assistant = cfg.get("personal_assistant", "Assistant")
self.cfg_notify_select = cfg.get("notify_select", "notify")
self.cfg_dnd = cfg.get("dnd", "off")
self.cfg_location_tracker = cfg.get("location_tracker", "home")
# self.log(f"USER INPUT CONFIG: {cfg}")

self.log(f"---------- END UPTATED ----------")

def package_download(self, delay):
ha_config = self.config_dir + "/configuration.yaml"
cn_path = self.config_dir + f"/{PATH_PACKAGES}/"
blueprints_path = self.config_dir + f"/{PATH_BLUEPRINTS}/"
local_file_main = cn_path + FILE_MAIN
version_latest = "0.0.0" # github
version_installed = "0.0.0" # local
is_download = self.cfg.get('download')
is_beta = self.cfg.get('beta_version')

# Find the path packages
with open(ha_config, "r") as ymlfile:
config = yaml.load(ymlfile, Loader=yaml.BaseLoader)
if "homeassistant" in config and "packages" in config["homeassistant"]:
pack_folder = config["homeassistant"]["packages"]
cn_path = f"{self.config_dir}/{pack_folder}/centro_notifiche/"
self.log(f"Package folder: {pack_folder}")
else:
self.log(f"Package folder not foud.")
pack_folder = self.cfg.get('packages_folder')
cn_path = f"{pack_folder}/centro_notifiche/"
self.log(f"Package folder from user input: {pack_folder}")
if pack_folder is None:
self.log(f"Package folder not foud.")
return

# self.log(f"CN complete path: {cn_path}")
local_file_main = cn_path + FILE_MAIN
version_latest = "0.0.1" # github
version_installed = "0.0.0" # local
# self.log(f"Hub Main: {local_file_main}")

### Read tag name with api.
response = requests.get(URL_PACKAGE_LATEST)
version_latest = response.json()["tag_name"].replace("v", "")
### Takes the latest published version
response = requests.get(URL_PACKAGE_RELEASES)
version_latest = response.json()[0]["tag_name"].replace("v", "")
self.log(f"package version latest: {version_latest}")

if not os.path.isdir(cn_path):
try:
os.mkdir(cn_path)
except OSError:
self.log(f"Creation of the directory {cn_path} failed")

if not os.path.isdir(blueprints_path):
try:
os.mkdir(blueprints_path)
except OSError:
self.log(f"Creation of the directory {blueprints_path} failed")

### Compare versions
if os.path.isfile(local_file_main):
try:
with open(local_file_main, "r") as ymlfile:
Expand All @@ -174,51 +151,62 @@ def package_download(self, delay):
self.log(f"Error in configuration file: {ex}")

version_installed = version_installed.replace("Main ", "")
self.log(f"package version Installed: {version_installed}")

if (version_installed < version_latest) and self.cfg.get('download'):
### DOWNLOAD ### TODO async? run_in_executor() request downloaded mltiple file
branches = 'beta' if self.cfg.get('beta_version') else 'main'
url_main = URL_BASE_REPO.format(branches, PATH_PACKAGES, FILE_MAIN)
url_alexa = URL_BASE_REPO.format(branches, PATH_PACKAGES, FILE_ALEXA)
url_google = URL_BASE_REPO.format(branches, PATH_PACKAGES, FILE_GOOGLE)
url_message = URL_BASE_REPO.format(branches, PATH_PACKAGES, FILE_MESSAGE)
url_startup = URL_BASE_REPO.format(branches, PATH_BLUEPRINTS, FILE_STARTUP)

self.log(f"download {FILE_MAIN} start!")
response = requests.get(url_main)
self.log(f"download {FILE_MAIN} complete!")
open(cn_path + FILE_MAIN, "wb").write(response.content)

self.log(f"download {FILE_STARTUP} start!")
response = requests.get(url_startup)
self.log(f"download {FILE_STARTUP} complete!")
open(blueprints_path + FILE_STARTUP, "wb").write(response.content)
self.log(f"package version Installed: {version_installed}")

if not os.path.isfile(cn_path + FILE_MESSAGE):
response = requests.get(url_message)
self.log(f"download {FILE_MESSAGE} complete!")
open(cn_path + FILE_MESSAGE, "wb").write(response.content)
### Download
if (version_installed < version_latest) and is_download:
branche = 'beta' if is_beta else 'main'
url_main = URL_BASE_REPO.format(branche, PATH_PACKAGES, FILE_MAIN)
url_alexa = URL_BASE_REPO.format(branche, PATH_PACKAGES, FILE_ALEXA)
url_google = URL_BASE_REPO.format(branche, PATH_PACKAGES, FILE_GOOGLE)
url_message = URL_BASE_REPO.format(branche, PATH_PACKAGES, FILE_MESSAGE)
url_startup = URL_BASE_REPO.format(branche, PATH_BLUEPRINTS, FILE_STARTUP)

if not os.path.isdir(cn_path):
try:
os.mkdir(cn_path)
except OSError:
self.log(f"Creation of the directory {cn_path} failed")
self.request_and_save(url_main, cn_path, FILE_MAIN)

### Utadete blueprint
if not os.path.isdir(blueprints_path):
try:
os.mkdir(blueprints_path)
except OSError:
self.log(f"Creation of the directory {blueprints_path} failed")
self.request_and_save(url_startup, blueprints_path, FILE_STARTUP)

if "alexa_media" in self.config["components"]:
self.log(f"download {FILE_ALEXA} start!")
response = requests.get(url_alexa)
self.log(f"download {FILE_ALEXA} complete!")
open(cn_path + FILE_ALEXA, "wb").write(response.content)

if not os.path.isfile(cn_path + FILE_MESSAGE):
self.request_and_save(url_message, cn_path, FILE_MESSAGE)
if "alexa_media" in self.config["components"]:
self.request_and_save(url_alexa, cn_path, FILE_ALEXA)
if "cast" in self.config["components"]:
self.log(f"download {FILE_GOOGLE} start!")
response = requests.get(url_google)
self.log(f"download {FILE_GOOGLE} complete!")
open(cn_path + FILE_GOOGLE, "wb").write(response.content)
self.request_and_save(url_google, cn_path, FILE_GOOGLE)

self.call_service("homeassistant/reload_all")
self.restart_app("Notifier_Dispatch")
# self.call_service("app/restart", app="Notifier_Dispatch", namespace="appdaemon")
self.call_service("homeassistant/reload_all")
self.restart_app("Notifier_Dispatch")
# self.call_service("app/restart", app="Notifier_Dispatch", namespace="appdaemon")

self.log("#### PROCESS COMPLETED ####")
if version_installed > "4.0.1":
self.log(f"{self.cfg.get('personal_assistant')} ready!")
else:
self.log(f"Please, download blueprint and configure it. When done, restart AppDaemon.")

def request_and_save(self, url, path, file):
### TODO async? run_in_executor() request downloaded mltiple file
if os.path.isfile(path + file):
old = path + file
new = old.replace('.yaml', '.OLD')
os.rename(old, new)

self.log(f"download {file} start!")
response = requests.get(url)
open(path + file, "wb").write(response.content)
self.log(f"download {file} complete!")

self.log("#### PROCESS COMPLETED ####")
self.log(f"{self.cfg.get('personal_assistant')} ready!")

#####################################################################
def set_debug_sensor(self, state, error):
attributes = {}
Expand Down Expand Up @@ -254,7 +242,7 @@ def notifier(self, event_name, data, kwargs):
self.ad_command(data.get("ad"))
return

assistant_name = self.get_state(self.personal_assistant_name, default=self.cfg_personal_assistant) #Maybe BUG
assistant_name = self.cfg_personal_assistant #Maybe BUG
location_status = self.get_state(self.location_tracker, default=self.cfg_location_tracker) #1st BUG reload group
### FLAG
priority_flag = h.check_boolean(data["priority"])
Expand Down Expand Up @@ -282,8 +270,9 @@ def notifier(self, event_name, data, kwargs):
### FROM INPUT BOOLEAN ###
guest_status = self.get_state(self.guest_mode)
priority_status = (self.get_state(self.priority_message) == "on") or priority_flag
### FROM INPUT SELECT ### #TODO remember to chenge in notifier_dispatch.yaml
### FROM SELECT ###
notify_name = self.get_state(self.text_notify, default=self.cfg_notify_select) #3nd BUG reload template
### FROM INPUT SELECT ###
phone_notify_name = self.get_state(self.phone_notify)
### NOTIFICATION ###
if priority_status:
Expand Down Expand Up @@ -336,15 +325,14 @@ def notifier(self, event_name, data, kwargs):
###########################
if usePersistentNotification:
try:
self.notification_manager.send_persistent(data, assistant_name) # delete self.persistent_notification_info,
self.notification_manager.send_persistent(data, assistant_name)
except Exception as ex:
self.log("An error occurred in persistent notification: {}".format(ex),level="ERROR")
self.set_debug_sensor("Error in Persistent Notification: ", ex)
self.log(sys.exc_info())
if useNotification:
try:
self.notification_manager.send_notify(data, notify_name, assistant_name)
# self.notification_manager.send_notify(data, notify_name, self.cfg_personal_assistant) # future - no input_text entity
except Exception as ex:
self.log("An error occurred in text notification: {}".format(ex), level="ERROR")
self.set_debug_sensor("Error in Text Notification: ", ex)
Expand Down
9 changes: 3 additions & 6 deletions apps/notifier/notifier_dispatch.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -13,18 +13,15 @@ Notifier_Dispatch:
phone_notifications: input_boolean.notifier_phone_notifications

html_mode: input_boolean.notifier_html_mode

# persistent_notification_info: persistent_notification.info_messages # delete

location_tracker: group.notifier_location_tracker
text_notify: input_select.notifier_text_notify # changed to select.
# text_notify: select.notifier_text_notify
location_tracker: group.notifier_location_tracker ## To fix

text_notify: select.notifier_text_notify
phone_notify: input_select.notifier_phone_notify
priority_message: input_boolean.notifier_priority_message
guest_mode: input_boolean.notifier_guest_mode
dnd: binary_sensor.notifier_dnd

personal_assistant_name: input_text.notifier_personal_assistant # delete
phone_called_number: input_text.notifier_called_number

debug_sensor: sensor.notifier_debug_error
Expand Down

0 comments on commit c4b0512

Please sign in to comment.