Skip to content
This repository has been archived by the owner on Feb 16, 2024. It is now read-only.

Commit

Permalink
Merge pull request #302 from DewGew/beta
Browse files Browse the repository at this point in the history
Merge Beta into Master
  • Loading branch information
DewGew authored Jan 8, 2023
2 parents af18868 + bad3a68 commit f348192
Show file tree
Hide file tree
Showing 14 changed files with 139 additions and 116 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,5 @@ env/
config/
config/config.yaml
config/smart-home-key.json
config/token/*

16 changes: 0 additions & 16 deletions .travis.yml

This file was deleted.

2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
![GitHub release (latest by date)](https://img.shields.io/github/v/release/dewgew/Domoticz-Google-Assistant?logo=github) [![Discord](https://img.shields.io/discord/664815298284748830?logo=discord)](https://discordapp.com/invite/AmJV6AC)
![GitHub release (latest by date)](https://img.shields.io/github/v/release/dewgew/Domoticz-Google-Assistant?logo=github) [![Discord](https://img.shields.io/discord/664815298284748830?logo=discord)](https://discordapp.com/invite/AmJV6AC) [![Python Package](https://github.com/DewGew/Domoticz-Google-Assistant/actions/workflows/python-app.yml/badge.svg?branch=master)](https://github.com/DewGew/Domoticz-Google-Assistant/actions/workflows/python-app.yml) [![Docker Image CI](https://github.com/DewGew/Domoticz-Google-Assistant/actions/workflows/docker-image.yml/badge.svg?branch=master)](https://github.com/DewGew/Domoticz-Google-Assistant/actions/workflows/docker-image.yml)
# Domoticz-Google-Assistant

<img src="dzga_UI.png" alt="drawing" width="1000"/>
Expand Down
2 changes: 0 additions & 2 deletions __init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1 @@



10 changes: 5 additions & 5 deletions __main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,26 +4,26 @@
from server import *
from smarthome import *

use_ssl = ('use_ssl' in configuration and configuration['use_ssl'] == True)
use_ssl = ('use_ssl' in configuration and configuration['use_ssl'] is True)

if use_ssl:
import ssl

if 'ngrok_tunnel' in configuration and configuration['ngrok_tunnel'] == True:
if 'ngrok_tunnel' in configuration and configuration['ngrok_tunnel'] is True:
from pyngrok import ngrok

tunnel = PUBLIC_URL

def secure(server):
key = configuration['ssl_key'] if 'ssl_key' in configuration else None
key = configuration['ssl_key'] if 'ssl_key' in configuration else None
cert = configuration['ssl_cert'] if 'ssl_cert' in configuration else None

if key is None or cert is None:
logger.info('ssl_key and ssl_cert options are mandatory if use_ssl is True')
return

logger.info('Using SSL connection')
server.socket = ssl.wrap_socket (server.socket, keyfile=key, certfile=cert, server_side=True, ssl_version=ssl.PROTOCOL_TLSv1_2)
server.socket = ssl.wrap_socket(server.socket, keyfile=key, certfile=cert, server_side=True, ssl_version=ssl.PROTOCOL_TLSv1_2)

class ThreadingSimpleServer(socketserver.ThreadingMixIn, http.server.HTTPServer):
pass
Expand All @@ -48,7 +48,7 @@ def startServer():
# Create a web server and define the handler to manage the
# incoming request
server = ThreadingSimpleServer(('', configuration['port_number']), AogServer)
if(use_ssl):
if (use_ssl):
secure(server)

logger.info('========')
Expand Down
6 changes: 3 additions & 3 deletions auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ def login_post(self, s):
user = self.getUser(s.form.get("username", None), s.form.get("password", None))

if user is None:
if s.headers['X-Forwarded-For'] == None:
if s.headers['X-Forwarded-For'] is None:
logger.error("Failed login from %s", s.address_string())
else:
logger.error("Failed login from %s", s.headers['X-Forwarded-For'])
Expand Down Expand Up @@ -89,7 +89,7 @@ def login_post(self, s):
# * &response_type=token
# * &grant_type=refresh_token
# * &refresh_token=REFRESH_TOKEN
# */
# */
def token_post(self, s):
client_id = s.query_components.get("client_id", s.form.get("client_id", None))
client_secret = s.query_components.get("client_secret", s.form.get("client_secret", None))
Expand Down Expand Up @@ -155,7 +155,7 @@ def handleAuthCode(self, s):
# * token_type: "bearer",
# * access_token: "ACCESS_TOKEN",
# * }
# */
# */
def handleRefreshToken(self, s):
client_id = s.query_components.get("client_id", s.form.get("client_id", None))
client_secret = s.query_components.get("client_secret", s.form.get("client_secret", None))
Expand Down
2 changes: 0 additions & 2 deletions config/default_config
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,6 @@ ssl_cert: # /path/to/fullchain.pem
# Login on Google Home app and configuration interface
auth_user: 'admin'
auth_pass: 'admin'
# If you change authToken you need to disconnect and reconnect to Google Assistant
authToken: 'ZsokmCwKjdhk7qHLeYd2'

# Google Assistant Settings:
ClientID: 'clientid_from aog'
Expand Down
2 changes: 1 addition & 1 deletion const.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# -*- coding: utf-8 -*-

"""Constants for Google Assistant."""
VERSION = '1.22.32'
VERSION = '1.23.2'
PUBLIC_URL = 'https://[your public url]'
CONFIGFILE = 'config/config.yaml'
LOGFILE = 'dzga.log'
Expand Down
38 changes: 26 additions & 12 deletions helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
import time
import subprocess
import sys
import string
import random

import requests
import yaml
Expand Down Expand Up @@ -50,15 +52,19 @@ def saveFile(filename, text):
file.write(text)
file.close()
return code



# Random string generator
def random_string(stringLength=8):
chars = string.ascii_letters + string.digits
return ''.join(random.choice(chars) for i in range(stringLength))

try:
print('Loading configuration...')
with open(os.path.join(FILE_DIR, CONFIGFILE), 'r') as conf:
configuration = yaml.safe_load(conf)
except yaml.YAMLError as exc:
except yaml.YAMLError:
print('ERROR: Please check config.yaml')
except FileNotFoundError as err:
except FileNotFoundError:
print('No config.yaml found...')
print('Loading default configuration...')
content = readFile(os.path.join(FILE_DIR, 'config/default_config'))
Expand All @@ -84,6 +90,22 @@ def saveFile(filename, text):
ch = logging.StreamHandler()
ch.setLevel(loglevel)
logger.addHandler(ch)

# Generate and save random token with username
if 'authToken' not in configuration:
try:
with open(os.path.join(FILE_DIR, 'config/.token/.'+ configuration['auth_user']), 'r') as t:
configuration['authToken'] = t.read()
t.close()
except FileNotFoundError:
logger.info('Generating token...')
access_token = random_string(20)
os.makedirs(os.path.join(FILE_DIR, 'config/.token'), exist_ok=True)
with open(os.path.join(FILE_DIR, 'config/.token/.'+ configuration['auth_user']), 'w+') as f:
f.write(access_token)
configuration['authToken'] = f
f.close()

# Log to file
if 'pathToLogFile' not in configuration or configuration['pathToLogFile'] == '':
logfilepath = FILE_DIR
Expand Down Expand Up @@ -123,8 +145,6 @@ def saveFile(filename, text):
configuration['ClientID'] = 'sampleClientId'
if 'ClientSecret' not in configuration:
configuration['ClientSecret'] = 'sampleClientSecret'
if 'authToken' not in configuration:
configuration['authToken'] = 'ZsokmCwKjdhk7qHLeYd2'

Auth = {
'clients': {
Expand All @@ -140,12 +160,6 @@ def saveFile(filename, text):
'refreshToken': configuration['authToken'],
'userAgentId': '1234',
},
'bfrrLnxxWdULSh3Y9IU2cA5pw8s4ub': {
'uid': '2345',
'accessToken': 'bfrrLnxxWdULSh3Y9IU2cA5pw8s4ub',
'refreshToken': 'bfrrLnxxWdULSh3Y9IU2cA5pw8s4ub',
'userAgentId': '2345'
},
},
'users': {
'1234': {
Expand Down
23 changes: 11 additions & 12 deletions smarthome.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,6 @@
import subprocess
import sys
import yaml
import random
import string
from collections.abc import Mapping
from itertools import product
from pid import PidFile
Expand Down Expand Up @@ -56,7 +54,8 @@
logger,
ReportState,
Auth,
logfilepath
logfilepath,
random_string
)
from jinja2 import Environment, FileSystemLoader

Expand Down Expand Up @@ -98,7 +97,8 @@
r = requests.get(
DOMOTICZ_URL + '/json.htm?type=command&param=addlogmessage&message=Connected to Google Assistant with DZGA v' + VERSION,
auth=CREDITS, timeout=(2, 5))
except Exception as e:
r.raise_for_status()
except requests.exceptions.HTTPError as e:
logger.error('Connection to Domoticz refused with error: %s' % e)

try:
Expand Down Expand Up @@ -749,12 +749,11 @@ def notification_post(self, s):
if token is None:
raise SmartHomeError(ERR_PROTOCOL_ERROR, 'not authorized access!!')

event_id = ''.join(random.choices(string.ascii_uppercase + string.ascii_lowercase +
string.digits, k=10))

request_id = ''.join(random.choices(string.digits, k=20))
event_id = random_string(10)
request_id = random_string(20)

message = s.body

if '|' in message: message = message.replace('|', ' ').split()
if '>>' in message: message.remove('>>')
devid = message[0]
Expand Down Expand Up @@ -788,7 +787,7 @@ def notification_post(self, s):
}
}
}
ReportState.call_homegraph_api(REPORT_STATE_BASE_URL, data)
ReportState.call_homegraph_api(REPORT_STATE_BASE_URL, data)
elif aog.domain in DOMAINS['smokedetector']:
data = {
'requestId': str(request_id),
Expand All @@ -798,7 +797,7 @@ def notification_post(self, s):
'devices': {
'states': {
devid: {
'on': (True if state.lower() in ['on'] else False)
'on': (True if state.lower() in ['on', 'alarm/fire'] else False)
},
},
'notifications': {
Expand Down Expand Up @@ -1033,8 +1032,7 @@ def smarthome_query(self, payload, token):
"""
response = {}
devices = {}
#getDevices()


for device in payload.get('devices', []):
devid = device['id']
_GoogleEntity(aogDevs.get(devid, None)).async_update()
Expand Down Expand Up @@ -1069,6 +1067,7 @@ def smarthome_exec(self, payload, token):
for device, execution in product(command['devices'],
command['execution']):
entity_id = device['id']
_GoogleEntity(aogDevs.get(entity_id, None)).async_update() # Get states before execution

# Happens if error occurred. Skip entity for further processing
if entity_id in results:
Expand Down
6 changes: 6 additions & 0 deletions templates/devices.html
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
<style>
.not-allowed {
pointer-events: none! important;
cursor: not-allowed! important;
}
</style>
<div id="menu1" class="tab-pane fade" role="tabpanel">
<div class="row">
<div class="col-md-12">
Expand Down
8 changes: 4 additions & 4 deletions templates/js/functions.js
Original file line number Diff line number Diff line change
Expand Up @@ -128,13 +128,13 @@ function readDevices(devicelist){
xl += "<td>" + devicelist[i][0] + nicknames + "</td>";
xl += "<td>" + devicelist[i][2] + "</td>";
if (devicelist[i][3] == "Off" | devicelist[i][3] == "Closed"){
xl += "<td><button type='button' class='btn btn-danger btn-sm'>" + devicelist[i][3] + "</button></td>";
xl += "<td><button type='button' class='btn btn-danger btn-sm not-allowed'>" + devicelist[i][3] + "</button></td>";
}else if (devicelist[i][3] == "On" | devicelist[i][3] == "Open" | devicelist[i][3] == "Normal"){
xl += "<td><button type='button'class='btn btn-success btn-sm'>" + devicelist[i][3] + "</button></td>";
xl += "<td><button type='button'class='btn btn-success btn-sm not-allowed'>" + devicelist[i][3] + "</button></td>";
}else if (devicelist[i][3] == "Mixed"){
xl += "<td><button type='button'class='btn btn-warning btn-sm'>" + devicelist[i][3] + "</button></td>";
xl += "<td><button type='button'class='btn btn-warning btn-sm not-allowed'>" + devicelist[i][3] + "</button></td>";
}else {
xl += "<td><button type='button'class='btn btn-info btn-sm' disabled>" + devicelist[i][3] + "</button></td>";
xl += "<td><button type='button'class='btn btn-info btn-sm not-allowed'>" + devicelist[i][3] + "</button></td>";
}
xl += "<td>" + devicelist[i][4] + "</td></tr>";
};
Expand Down
Loading

0 comments on commit f348192

Please sign in to comment.