mirror of
https://github.com/CCOSTAN/Home-AssistantConfig.git
synced 2025-11-06 17:51:36 +00:00
Initial Configuration Push
This commit is contained in:
7
deps/pyfttt/__init__.py
vendored
Normal file
7
deps/pyfttt/__init__.py
vendored
Normal file
@@ -0,0 +1,7 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
VERSION = (0, 3)
|
||||
__version__ = ".".join(map(str, VERSION[0:2])) + "".join(VERSION[2:])
|
||||
__license__ = "BSD"
|
||||
|
||||
from pyfttt.sending import *
|
||||
BIN
deps/pyfttt/__pycache__/__init__.cpython-34.pyc
vendored
Normal file
BIN
deps/pyfttt/__pycache__/__init__.cpython-34.pyc
vendored
Normal file
Binary file not shown.
BIN
deps/pyfttt/__pycache__/cmd_script.cpython-34.pyc
vendored
Normal file
BIN
deps/pyfttt/__pycache__/cmd_script.cpython-34.pyc
vendored
Normal file
Binary file not shown.
BIN
deps/pyfttt/__pycache__/sending.cpython-34.pyc
vendored
Normal file
BIN
deps/pyfttt/__pycache__/sending.cpython-34.pyc
vendored
Normal file
Binary file not shown.
BIN
deps/pyfttt/__pycache__/server.cpython-34.pyc
vendored
Normal file
BIN
deps/pyfttt/__pycache__/server.cpython-34.pyc
vendored
Normal file
Binary file not shown.
BIN
deps/pyfttt/__pycache__/test_server.cpython-34.pyc
vendored
Normal file
BIN
deps/pyfttt/__pycache__/test_server.cpython-34.pyc
vendored
Normal file
Binary file not shown.
80
deps/pyfttt/cmd_script.py
vendored
Normal file
80
deps/pyfttt/cmd_script.py
vendored
Normal file
@@ -0,0 +1,80 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
"""pyfttt.py - Send IFTTT Maker Channel Events"""
|
||||
|
||||
import argparse
|
||||
import os
|
||||
import sys
|
||||
|
||||
import requests
|
||||
import pyfttt
|
||||
|
||||
|
||||
def parse_arguments():
|
||||
"""Parse command line arguments"""
|
||||
|
||||
parser = argparse.ArgumentParser(prog=sys.argv[0],
|
||||
description='Send Maker Channel events to IFTTT',
|
||||
epilog='Visit https://ifttt.com/channels/maker for more information')
|
||||
parser.add_argument('--version', action='version', version=pyfttt.__version__)
|
||||
|
||||
sgroup = parser.add_argument_group(title='sending events')
|
||||
sgroup.add_argument('-k', '--key', metavar='K',
|
||||
default=os.environ.get('IFTTT_API_KEY'),
|
||||
help='IFTTT secret key')
|
||||
sgroup.add_argument('-e', '--event', metavar='E', required=True,
|
||||
help='The name of the event to trigger')
|
||||
sgroup.add_argument('value1', nargs='?',
|
||||
help='Extra data sent with the event (optional)')
|
||||
sgroup.add_argument('value2', nargs='?',
|
||||
help='Extra data sent with the event (optional)')
|
||||
sgroup.add_argument('value3', nargs='?',
|
||||
help='Extra data sent with the event (optional)')
|
||||
|
||||
return parser.parse_args()
|
||||
|
||||
|
||||
def main():
|
||||
"""Main function for pyfttt command line tool"""
|
||||
args = parse_arguments()
|
||||
|
||||
if args.key is None:
|
||||
print("Error: Must provide IFTTT secret key.")
|
||||
sys.exit(1)
|
||||
|
||||
try:
|
||||
res = pyfttt.send_event(api_key=args.key, event=args.event,
|
||||
value1=args.value1, value2=args.value2,
|
||||
value3=args.value3)
|
||||
except requests.exceptions.ConnectionError:
|
||||
print("Error: Could not connect to IFTTT")
|
||||
sys.exit(2)
|
||||
except requests.exceptions.HTTPError:
|
||||
print("Error: Received invalid response")
|
||||
sys.exit(3)
|
||||
except requests.exceptions.Timeout:
|
||||
print("Error: Request timed out")
|
||||
sys.exit(4)
|
||||
except requests.exceptions.TooManyRedirects:
|
||||
print("Error: Too many redirects")
|
||||
sys.exit(5)
|
||||
except requests.exceptions.RequestException as reqe:
|
||||
print("Error: {e}".format(e=reqe))
|
||||
sys.exit(6)
|
||||
|
||||
|
||||
if res.status_code != requests.codes.ok:
|
||||
try:
|
||||
j = res.json()
|
||||
except ValueError:
|
||||
print('Error: Could not parse server response. Event not sent')
|
||||
sys.exit(7)
|
||||
|
||||
for err in j['errors']:
|
||||
print('Error: {}'.format(err['message']))
|
||||
sys.exit(8)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
||||
13
deps/pyfttt/sending.py
vendored
Normal file
13
deps/pyfttt/sending.py
vendored
Normal file
@@ -0,0 +1,13 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
"""Handle sending API requests to the IFTTT Maker Channel"""
|
||||
|
||||
import requests
|
||||
|
||||
def send_event(api_key, event, value1=None, value2=None, value3=None):
|
||||
"""Send an event to the IFTTT maker channel"""
|
||||
url = "https://maker.ifttt.com/trigger/{e}/with/key/{k}/".format(e=event,
|
||||
k=api_key)
|
||||
payload = {'value1': value1, 'value2': value2, 'value3': value3}
|
||||
return requests.post(url, data=payload)
|
||||
|
||||
141
deps/pyfttt/server.py
vendored
Normal file
141
deps/pyfttt/server.py
vendored
Normal file
@@ -0,0 +1,141 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
try:
|
||||
import BaseHTTPServer as server
|
||||
except ImportError:
|
||||
import http.server as server
|
||||
|
||||
try:
|
||||
from urlparse import parse_qs
|
||||
except ImportError:
|
||||
from urllib.parse import parse_qs
|
||||
|
||||
import json
|
||||
|
||||
import pyfttt
|
||||
|
||||
# https://wiki.python.org/moin/BaseHttpServer
|
||||
# https://docs.python.org/2/library/basehttpserver.html
|
||||
# http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
|
||||
# make a key with hashlib.sha1(b"hello" + b"world").hexdigest() (should have something unique in there)
|
||||
# https://docs.python.org/2/library/basehttpserver.html
|
||||
# TODO: get charset from browser instead of assuming utf-8?
|
||||
# TODO: handle HEAD (get response, but no body)
|
||||
|
||||
# Parse out the url: z=urllib.parse.urlparse('http://blah.com/api/1.0/somekey/blah?woop=21&blah=12')
|
||||
# parse the query part urllib.parse.parse_qs(z.query)
|
||||
|
||||
VALID_KEYS = ['6adfb183a4a2c94a2f92dab5ade762a47889a5a1', 'KEY']
|
||||
|
||||
class basic_handler(server.BaseHTTPRequestHandler):
|
||||
|
||||
def parse_path(self):
|
||||
""" parse the path, setting api_key, api_version, etc."""
|
||||
|
||||
print("PATH IS [{}]".format(self.path))
|
||||
path = self.path[1:].split('/')
|
||||
self.valid = True
|
||||
|
||||
if len(path) < 4:
|
||||
self.send_error(400, message='Malformed path')
|
||||
self.valid = False
|
||||
return
|
||||
pass
|
||||
|
||||
if path[0] != 'api':
|
||||
self.send_error(404)
|
||||
self.valid = False
|
||||
return
|
||||
|
||||
try:
|
||||
self.api_version = float(path[1])
|
||||
except ValueError:
|
||||
self.send_error(404, message='Unsupported API version')
|
||||
self.api_version = None
|
||||
self.valid = False
|
||||
return
|
||||
|
||||
if self.api_version not in [1.0]:
|
||||
self.send_error(404, message='Unsupported API version')
|
||||
self.valid = False
|
||||
return
|
||||
|
||||
self.api_key = path[2]
|
||||
|
||||
if self.api_key not in VALID_KEYS:
|
||||
self.send_error(403)
|
||||
self.valid = False
|
||||
return
|
||||
|
||||
self.api_command = path[3]
|
||||
if self.api_command not in ['test', 'blah']:
|
||||
self.send_error(400, message="Unknown command '{}'".format(self.api_command))
|
||||
self.valid = False
|
||||
return
|
||||
|
||||
self.api_arguments = path[4:]
|
||||
|
||||
|
||||
def do_GET(self):
|
||||
return self.do_GETPOST()
|
||||
|
||||
|
||||
def do_POST(self):
|
||||
return self.do_GETPOST()
|
||||
|
||||
|
||||
def do_GETPOST(self):
|
||||
self.server_version = 'pyfttt/{}'.format(pyfttt.__version__)
|
||||
self.parse_path()
|
||||
|
||||
if not self.valid:
|
||||
return
|
||||
|
||||
#print("COMMAND: {}".format(self.api_command))
|
||||
#print("OPTIONS: {}".format(self.api_arguments))
|
||||
|
||||
if self.command == 'POST':
|
||||
data_length = int(self.headers['Content-Length'])
|
||||
|
||||
# Payload must be under 1k
|
||||
if data_length > 1000:
|
||||
self.send_error(413)
|
||||
return
|
||||
|
||||
data_raw = self.rfile.read(data_length)
|
||||
|
||||
if self.headers['Content-Type'] == 'application/json':
|
||||
data_parsed = json.loads(bytes.decode(data_raw))
|
||||
elif self.headers['Content-Type'] == 'application/x-www-form-urlencoded':
|
||||
data_parsed = parse_qs(data_raw)
|
||||
else:
|
||||
self.send_error(400, message="Unsupported Content Type '{}'".format(self.headers['Content-Type']))
|
||||
return
|
||||
|
||||
#print("\tGot Data: [{}]".format(data_parsed))
|
||||
|
||||
self.send_response(200)
|
||||
self.send_header("Content-type", "application/json")
|
||||
self.end_headers()
|
||||
stuff = {'brian': 35, 'lori': 35, 'address': {'house': 2351, 'street': 'fairview ave e'}}
|
||||
|
||||
self.wfile.write(json.dumps(stuff, indent=4).encode('UTF-8'))
|
||||
|
||||
|
||||
def run_server(host='', port=7777, handler=basic_handler):
|
||||
httpd = server.HTTPServer(server_address=(host,port),
|
||||
RequestHandlerClass=handler)
|
||||
httpd.serve_forever()
|
||||
|
||||
run_server(port=7777, handler=basic_handler)
|
||||
|
||||
|
||||
# print("Got a POST request")
|
||||
# print("\tClient Address: {}".format(self.client_address))
|
||||
# print("\tCommand: {}".format(self.command))
|
||||
# print("\tPath: {}".format(self.path.split('/')))
|
||||
# print("\tRequest Version: {}".format(self.request_version))
|
||||
# print("\tHeaders: {}".format(self.headers))
|
||||
# print("\t\tContent-Length: {}".format(int(self.headers['Content-Length'])))
|
||||
# print("\tServer Version: {}".format(self.server_version))
|
||||
|
||||
11
deps/pyfttt/test_server.py
vendored
Normal file
11
deps/pyfttt/test_server.py
vendored
Normal file
@@ -0,0 +1,11 @@
|
||||
#!/usr/bin/env python
|
||||
|
||||
import json
|
||||
import requests
|
||||
|
||||
payload = {'value1': 'hello', 'value2': 'i am value2', 'value3': 90210}
|
||||
|
||||
#r = requests.post('http://localhost:7777/api/1.0/6adfb183a4a2c94a2f92dab5ade762a47889a5a1/test', data=payload)
|
||||
r = requests.post('http://localhost:7777/api/1.0/6adfb183a4a2c94a2f92dab5ade762a47889a5a1/test/opt1', json=json.dumps(payload))
|
||||
|
||||
print(r)
|
||||
Reference in New Issue
Block a user