##
# Copyright (c) 2020 Valentin Weber
#
# After some minor modifications (as marked below) this EventGhost
# Python script provides a method to send requests to devices
# registered with the Join API from
# any EventGhost Python Script or Command.
#
# EventGhost usage: `eg.globals.JoinPushDevice(text="hello_world")`
##
"""Send requests to Join REST API from EventGhost."""
from inspect import getmembers, isclass
class JoinRequest:
"""Base Class for Request to Join API.
Needs personal Join API KEY to work. Besides that nothing needs
to be modified here.
Accepts all values included in the Join API documentation
but will not validate them.
Parameters not mentioned there will not cause an error before
sending the request but might return an error message from the api.
Raises `JoinApiError` if API request returns an error message.
"""
DEVICE = None # Do not replace
API_KEY = "API_KEY_PLACEHOLDER" # replace with personal API KEY
class JoinApiError(BaseException):
"""Error For Join API Requests."""
pass
import urllib
import urllib2
import json
def __init__(self, **params):
params["apikey"] = self.API_KEY
params["deviceId"] = self.DEVICE
join_request = self.urllib2.urlopen(
"https://joinjoaomgcd.appspot.com/_ah/api/messaging/v1/sendPush",
data=self.urllib.urlencode(params).encode()
)
msg = self.json.loads(
join_request.read()
).get("errorMessage", False)
if msg:
raise self.JoinApiError(msg)
class RegisterDevices:
"""Adds all nested classes to `eg.globals` using their name."""
def __init__(self):
members = [
m for m in getmembers(self, isclass) if m[0] != "__class__"
]
for name, obj in members:
try:
setattr(eg.globals, name, obj)
print("ADDED: " + name + "(**params)")
except Exception as e:
print "SKIPPED: ", name, ": " + str(e)
continue
# Device List (names may be changed for easier identification)
class JoinPushDeviceOne(JoinRequest): # optionally rename
DEVICE = "INSERT_ID_FOR_JOIN_DEVICE_ONE_HERE" # replace
class JoinPushDeviceTwo(JoinRequest): # optionally rename
DEVICE = "INSERT_ID_FOR_JOIN_DEVICE_TWO_HERE" # replace
##
# Add more devices if needed
#
# Make sure each added class is a nested class by indenting it
# with 4 spaces. Also ensure that each new class is a subclass of
# `JoinRequest` since that class contains the functionality to
# make a request to the API.
##
RegisterDevices()