Skip to content

Commit

Permalink
Merge pull request #27 from sultur/Create-token-iotconnect
Browse files Browse the repository at this point in the history
Create token iotconnect
  • Loading branch information
hrolfurinn authored Jun 23, 2022
2 parents dffc4cf + d56a725 commit 8df2eca
Show file tree
Hide file tree
Showing 3 changed files with 133 additions and 18 deletions.
86 changes: 72 additions & 14 deletions queries/iot_connect.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,14 @@
import random
import json
import flask
import requests
import time

from query import Query, QueryStateDict, AnswerTuple
from queries import gen_answer, read_jsfile, read_grammar_file
from tree import Result, Node
from routes import better_jsonify
from util import read_api_key


class SmartLights(TypedDict):
Expand All @@ -57,17 +61,10 @@ def help_text(lemma: str) -> str:
"""Help text to return when query.py is unable to parse a query but
one of the above lemmas is found in it"""
return "Ég skil þig ef þú segir til dæmis: {0}.".format(
random.choice(
(
"Tengu miðstöðina",
"Tengdu ljósin"
"Tengdu hátalarann"
)
)
random.choice(("Tengu miðstöðina", "Tengdu ljósin" "Tengdu hátalarann"))
)



# This module wants to handle parse trees for queries
HANDLE_TREE = True

Expand All @@ -89,6 +86,7 @@ def help_text(lemma: str) -> str:
QIoTConnectLights
| QIoTConnectHub
| QIoTConnectSpeaker
| QIoTCreateSpeakerToken
QIoTConnectLights →
"tengdu" "ljósin"
Expand All @@ -99,22 +97,35 @@ def help_text(lemma: str) -> str:
QIoTConnectSpeaker →
"tengdu" "hátalarann"
QIoTCreateSpeakerToken →
"skapaðu" "tóka"
"""


def QIoTConnectLights(node: Node, params: QueryStateDict, result: Result) -> None:
result.qtype = "connect_lights"
result.action = "connect_lights"


def QIoTConnectHub(node: Node, params: QueryStateDict, result: Result) -> None:
print("Connect Hub")
result.qtype = "connect_hub"
result.action = "connect_hub"


def QIoTConnectSpeaker(node: Node, params: QueryStateDict, result: Result) -> None:
print("Connect Speaker")
result.qtype = "connect_speaker"
result.action = "connect_speaker"


def QIoTCreateSpeakerToken(node: Node, params: QueryStateDict, result: Result) -> None:
print("Create Token")
result.qtype = "create_speaker_token"
result.action = "create_speaker_token"


def sentence(state: QueryStateDict, result: Result) -> None:
"""Called when sentence processing is complete"""
q: Query = state["query"]
Expand Down Expand Up @@ -157,17 +168,66 @@ def sentence(state: QueryStateDict, result: Result) -> None:
q.set_command(js)
return
elif result.qtype == "connect_speaker":
# host = str(flask.request.host)
sonos_key = read_api_key("SonosKey")
host = str(flask.request.host)
print("Connect speaker sentence")
client_id = str(q.client_id)
answer = "Skráðu þig inn hjá Sonos"
voice_answer = answer
response = dict(answer=answer)
q.set_answer(response, answer, voice_answer)
q.set_url(f"https://api.sonos.com/login/v3/oauth?client_id=74436dd6-476a-4470-ada3-3a9da4642dec&response_type=code&state={client_id}&scope=playback-control-all&redirect_uri=http://192.168.1.69:5000/connect_sonos.api")
print("sonos_key :", sonos_key)
print("host :", host)
q.set_url(
f"https://api.sonos.com/login/v3/oauth?client_id={sonos_key}&response_type=code&state={client_id}&scope=playback-control-all&redirect_uri=http://{host}/connect_sonos.api"
)
return


elif result.qtype == "create_speaker_token":
sonos_encoded_credentials = read_api_key("SonosEncodedCredentials")
print("credientials :", sonos_encoded_credentials)
answer = "Ég bjó til tóka frá Sonos"
voice_answer = answer
response = dict(answer=answer)
code = str(q.client_data("sonos_code"))
print(code)
q.set_answer(response, answer, voice_answer)
q.set_url(f"https://google.com/")
host = str(flask.request.host)
url = f"https://api.sonos.com/login/v3/oauth/access?grant_type=authorization_code&code={code}&redirect_uri=http://{host}/connect_sonos.api"

payload = {}
headers = {
"Authorization": f"Basic {sonos_encoded_credentials}",
"Cookie": "JSESSIONID=2DEFC02D2184D987F4CCAD5E45196948; AWSELB=69BFEFC914A689BF6DC8E4652748D7B501ED60290D5EA56F2E543ABD7CF357A5F65186AEBC76E6A16196350947ED84835621A185D1BF63900D4B3E7BC7FE3CF19CCF26B78C; AWSELBCORS=69BFEFC914A689BF6DC8E4652748D7B501ED60290D5EA56F2E543ABD7CF357A5F65186AEBC76E6A16196350947ED84835621A185D1BF63900D4B3E7BC7FE3CF19CCF26B78C",
}

response = requests.request("POST", url, headers=headers, data=payload)
if response.status_code != 200:
print("Error:", response.status_code)
print(response.text)
return
response_json = response.json()
sonos_access_token = response_json["access_token"]
sonos_refresh_token = response_json["refresh_token"]
print(response.text)

# print("access token :", response.access_token)
# print("refresh token :", response.refresh_token)
current_time = time.time()
print("current time :", current_time)

q.set_client_data("sonos_access_token", sonos_access_token)
q.set_client_data("sonos_refresh_token", sonos_refresh_token)
q.set_client_data("sonos_token_time", current_time)

# if client_id and code:
# success = QueryObject.store_query_data(
# client_id, "sonos_code", code
# )
# if success:
# return better_jsonify(valid=True, msg="Registered Sonos token")

# return better_jsonify(valid=False, errmsg="Error registering Sonos token.")

# smartdevice_type = "smartlights"
# client_id = str(q.client_id)
Expand Down Expand Up @@ -199,6 +259,4 @@ def sentence(state: QueryStateDict, result: Result) -> None:
# print("selected light :", selected_light)
# print("hue credentials :", hue_credentials)



# f"var BRIDGE_IP = '192.168.1.68';var USERNAME = 'p3obluiXT13IbHMpp4X63ZvZnpNRdbqqMt723gy2';"
59 changes: 59 additions & 0 deletions queries/iot_speakers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
def getHouseholds(token):
"""
Returns the list of households of the user
"""
url = "https://api.ws.sonos.com/control/api/v1/households"

payload = {}
headers = {"Authorization": f"Bearer {token}"}

response = requests.request("GET", url, headers=headers, data=payload)

return response


def getGroups(houshold_id, token):
"""
Returns the list of groups of the user
"""
url = "https://api.ws.sonos.com/control/api/v1/households/{household_id}/groups"

payload = {}
headers = {"Authorization": f"Bearer {token}"}

response = requests.request("GET", url, headers=headers, data=payload)

return response


def createToken(code, sonos_encoded_credentials):
"""
Creates a token given a code
"""
url = f"https://api.sonos.com/login/v3/oauth/access?grant_type=authorization_code&code={code}&redirect_uri=http://localhost:5000/connect_sonos.api"

payload = {}
headers = {
"Authorization": f"Basic {sonos_encoded_credentials}",
"Cookie": "JSESSIONID=F710019AF0A3B7126A8702577C883B5F; AWSELB=69BFEFC914A689BF6DC8E4652748D7B501ED60290D5EA56F2E543ABD7CF357A5F65186AEBCFB059E28075D83A700FD504C030A53CC28683B515BE3DCA3CC587AFAF606E171; AWSELBCORS=69BFEFC914A689BF6DC8E4652748D7B501ED60290D5EA56F2E543ABD7CF357A5F65186AEBCFB059E28075D83A700FD504C030A53CC28683B515BE3DCA3CC587AFAF606E171",
}

response = requests.request("POST", url, headers=headers, data=payload)

return response


def togglePlayPause(group_id, token):
"""
Toggles the play/pause of a group
"""
url = (
f"https://api.ws.sonos.com/control/api/v1/groups/{group_id}/playback/playPause"
)

payload = {}
headers = {"Content-Type": "application/json", "Authorization": f"Bearer {token}"}

response = requests.request("POST", url, headers=headers, data=payload)

return response
6 changes: 2 additions & 4 deletions routes/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -726,10 +726,8 @@ def sonos_code(version: int = 1) -> Response:
client_id = args.get("state")
code = args.get("code")
if client_id and code:
success = QueryObject.store_query_data(
client_id, "sonos_code", code
)
success = QueryObject.store_query_data(client_id, "sonos_code", code)
if success:
return better_jsonify(valid=True, msg="Registered sonos code")

return better_jsonify(valid=False, errmsg="Error registering sonos code.")
return better_jsonify(valid=False, errmsg="Error registering sonos code.")

0 comments on commit 8df2eca

Please sign in to comment.