Skip to content

Commit

Permalink
Merge pull request #29 from sbabcock23/headersfix
Browse files Browse the repository at this point in the history
updated requests to include the content type of the header and force …
  • Loading branch information
sbabcock23 authored Apr 12, 2023
2 parents db82588 + d9730c0 commit 6bf9f61
Show file tree
Hide file tree
Showing 5 changed files with 47 additions and 35 deletions.
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,9 @@ tryfi.pets[0].monthlyNap

# Version History

# 0.0.20
- Fix - Added HTTP Header to the requests of all GraphQL requests

# 0.0.19

- Breaking Change - removed battery health as its not available in the newer collars and deprecated
Expand Down
12 changes: 9 additions & 3 deletions pytryfi/__init__.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import logging
import requests

from pytryfi.const import (API_HOST_URL_BASE, API_LOGIN, API_GRAPHQL, PYTRYFI_VERSION)
from pytryfi.const import (API_HOST_URL_BASE, API_LOGIN, PYTRYFI_VERSION, HEADER)
from pytryfi.fiUser import FiUser
from pytryfi.fiPet import FiPet
from pytryfi.fiBase import FiBase
Expand All @@ -27,8 +27,10 @@ def __init__(self, username=None, password=None):
self._session = requests.Session()
self._user_agent = "pyTryFi"
self._username = username
self._password = password
self._password = password
self.login()
#set Headers only after login for use going forward.
self.setHeaders()

self._currentUser = FiUser(self._userId)
self._currentUser.setUserDetails(self._session)
Expand Down Expand Up @@ -80,7 +82,11 @@ def __str__(self):
for p in self.pets:
petString = petString + f"{p}"
return f"TryFi Instance - {instString}\n Pets in Home:\n {petString}\n Bases In Home:\n {baseString}"


#set the headers for the session
def setHeaders(self):
self.session.headers = HEADER

#refresh pet details for all pets
def updatePets(self):
try:
Expand Down
8 changes: 5 additions & 3 deletions pytryfi/common/query.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from pytryfi.const import *
from pytryfi.exceptions import *
import json
import requests
import logging
from sentry_sdk import capture_exception
Expand Down Expand Up @@ -134,13 +135,14 @@ def mutation(sessionId, qString, qVariables):
try:
jsonObject = None
url = getGraphqlURL()
params = {"query": qString, "variables": qVariables}

params = {"query": qString, "variables": json.loads(qVariables)}
jsonObject = execute(url, sessionId, params=params, method='POST').json()
return jsonObject
except Exception as e:
LOGGER.error("Error performing query: " + e)
capture_exception(e)

def query(sessionId, qString):
try:
jsonObject = None
Expand All @@ -158,7 +160,7 @@ def execute(url, sessionId, method='GET', params=None, cookies=None):
if method == 'GET':
response = sessionId.get(url, params=params)
elif method == 'POST':
response = sessionId.post(url, data=params)
response = sessionId.post(url, json=params)
else:
raise TryFiError(f"Method Passed was invalid: {method}")
except requests.RequestException as e:
Expand Down
57 changes: 29 additions & 28 deletions pytryfi/const.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
SENTRY_URL = "https://[email protected]/5735605"

PYTRYFI_VERSION = "0.0.19"
PYTRYFI_VERSION = "0.0.20"

API_HOST_URL_BASE = "https://api.tryfi.com"
API_GRAPHQL = "/graphql"
API_LOGIN = "/auth/login"
HEADER = {'content-type': 'application/json'}

PET_MODE_NORMAL = "NORMAL"
PET_MODE_LOST = "LOST_DOG"
Expand All @@ -15,31 +16,31 @@

VAR_PET_ID = "__PET_ID__"

QUERY_CURRENT_USER = "query {\n currentUser {\n ...UserDetails\n }\n}\n"
QUERY_CURRENT_USER_FULL_DETAIL = "query {\n currentUser {\n ...UserFullDetails\n }\n}\n"
QUERY_PET_CURRENT_LOCATION = "query {\n\n pet (id: \""+VAR_PET_ID+"\") {\n ongoingActivity {\n __typename\n ...OngoingActivityDetails\n }\n }\n}\n"
QUERY_PET_ACTIVITY = "query {\n\n pet (id: \""+VAR_PET_ID+"\") {\n \n dailyStat: currentActivitySummary (period: DAILY) {\n ...ActivitySummaryDetails\n }\n weeklyStat: currentActivitySummary (period: WEEKLY) {\n ...ActivitySummaryDetails\n }\n monthlyStat: currentActivitySummary (period: MONTHLY) {\n ...ActivitySummaryDetails\n }\n }\n}\n"
QUERY_PET_REST = "query {\n pet (id: \""+VAR_PET_ID+"\") {\n dailyStat: restSummaryFeed(cursor: null, period: DAILY, limit: 1) {\n __typename\n restSummaries {\n __typename\n ...RestSummaryDetails\n }\n }\n weeklyStat: restSummaryFeed(cursor: null, period: WEEKLY, limit: 1) {\n __typename\n restSummaries {\n __typename\n ...RestSummaryDetails\n }\n }\n monthlyStat: restSummaryFeed(cursor: null, period: MONTHLY, limit: 1) {\n __typename\n restSummaries {\n __typename\n ...RestSummaryDetails\n }\n }\n }\n}"
QUERY_PET_DEVICE_DETAILS = "query {\n pet (id: \""+VAR_PET_ID+"\") {\n __typename\n ...PetProfile\n }\n}\n"
QUERY_CURRENT_USER = "query { currentUser { ...UserDetails }}"
QUERY_CURRENT_USER_FULL_DETAIL = "query { currentUser { ...UserFullDetails }}"
QUERY_PET_CURRENT_LOCATION = "query { pet (id: \""+VAR_PET_ID+"\") { ongoingActivity { __typename ...OngoingActivityDetails } }}"
QUERY_PET_ACTIVITY = "query { pet (id: \""+VAR_PET_ID+"\") { dailyStat: currentActivitySummary (period: DAILY) { ...ActivitySummaryDetails } weeklyStat: currentActivitySummary (period: WEEKLY) { ...ActivitySummaryDetails } monthlyStat: currentActivitySummary (period: MONTHLY) { ...ActivitySummaryDetails } }}"
QUERY_PET_REST = "query { pet (id: \""+VAR_PET_ID+"\") { dailyStat: restSummaryFeed(cursor: null, period: DAILY, limit: 1) { __typename restSummaries { __typename ...RestSummaryDetails } } weeklyStat: restSummaryFeed(cursor: null, period: WEEKLY, limit: 1) { __typename restSummaries { __typename ...RestSummaryDetails } } monthlyStat: restSummaryFeed(cursor: null, period: MONTHLY, limit: 1) { __typename restSummaries { __typename ...RestSummaryDetails } } }}"
QUERY_PET_DEVICE_DETAILS = "query { pet (id: \""+VAR_PET_ID+"\") { __typename ...PetProfile }}"

FRAGMENT_USER_DETAILS = "fragment UserDetails on User {\n __typename\n id\n email\n firstName\n lastName\n phoneNumber\n fiNewsNotificationsEnabled\n chipReseller {\n __typename\n id\n }\n}\n"
FRAGMENT_USER_FULL_DETAILS = "fragment UserFullDetails on User {\n __typename\n ...UserDetails\n userHouseholds {\n __typename\n household {\n __typename\n pets {\n __typename\n ...PetProfile\n }\n bases {\n __typename\n ...BaseDetails\n }\n }\n }\n}\n"
FRAGEMENT_BASE_PET_PROFILE = "fragment BasePetProfile on BasePet {\n __typename\n id\n name\n homeCityState\n yearOfBirth\n monthOfBirth\n dayOfBirth\n gender\n weight\n isPurebred\n breed {\n __typename\n ...BreedDetails\n }\n photos {\n __typename\n first {\n __typename\n ...PhotoDetails\n }\n items {\n __typename\n ...PhotoDetails\n }\n }\n instagramHandle\n \n}\n"
FRAGMENT_BREED_DETAILS = "fragment BreedDetails on Breed {\n __typename\n id\n name\n popularityScore\n}\n"
FRAGMENT_PHOTO_DETAILS = "fragment PhotoDetails on Photo {\n __typename\n id\n caption\n date\n likeCount\n liked\n image {\n __typename\n fullSize\n }\n}\n"
FRAGMENT_PET_PROFILE = "fragment PetProfile on Pet {\n __typename\n ...BasePetProfile\n chip {\n __typename\n shortId\n }\n device {\n __typename\n ...DeviceDetails\n }\n}\n"
FRAGMENT_DEVICE_DETAILS = "fragment DeviceDetails on Device {\n __typename\n id\n moduleId\n info\n subscriptionId\n hasActiveSubscription\n hasSubscriptionOverride\n nextLocationUpdateExpectedBy\n operationParams {\n __typename\n ...OperationParamsDetails\n }\n lastConnectionState {\n __typename\n ...ConnectionStateDetails\n }\n ledColor {\n __typename\n ...LedColorDetails\n }\n availableLedColors {\n __typename\n ...LedColorDetails\n }\n}\n"
FRAGMENT_LED_DETAILS = "fragment LedColorDetails on LedColor {\n __typename\n ledColorCode\n hexCode\n name\n}\n"
FRAGMENT_CONNECTION_STATE_DETAILS = "fragment ConnectionStateDetails on ConnectionState {\n __typename\n date\n ... on ConnectedToUser {\n user {\n __typename\n ...UserDetails\n }\n }\n ... on ConnectedToBase {\n chargingBase {\n __typename\n id\n }\n }\n ... on ConnectedToCellular {\n signalStrengthPercent\n }\n ... on UnknownConnectivity {\n unknownConnectivity\n }\n}\n"
FRAGMENT_OPERATIONAL_DETAILS = "fragment OperationParamsDetails on OperationParams {\n __typename\n mode\n ledEnabled\n ledOffAt\n}\n"
FRAGMENT_BASE_DETAILS = "fragment BaseDetails on ChargingBase {\n __typename\n baseId\n name\n position {\n __typename\n ...PositionCoordinates\n }\n infoLastUpdated\n networkName\n online\n onlineQuality\n}\n"
FRAGMENT_POSITION_COORDINATES = "fragment PositionCoordinates on Position {\n __typename\n latitude\n longitude\n}\n"
FRAGMENT_ONGOING_ACTIVITY_DETAILS = "fragment OngoingActivityDetails on OngoingActivity {\n __typename\n start\n presentUser {\n __typename\n ...UserDetails\n }\n areaName\n lastReportTimestamp\n obfuscatedReason\n totalSteps\n uncertaintyInfo {\n __typename\n ...UncertaintyInfoDetails\n }\n ... on OngoingWalk {\n distance\n positions {\n __typename\n ...LocationPoint\n }\n path {\n __typename\n ...PositionCoordinates\n }\n }\n ... on OngoingRest {\n position {\n __typename\n ...PositionCoordinates\n }\n place {\n __typename\n ...PlaceDetails\n }\n }\n}\n"
FRAGMENT_UNCERTAINTY_DETAILS = "fragment UncertaintyInfoDetails on UncertaintyInfo {\n __typename\n areaName\n updatedAt\n circle {\n __typename\n ...CircleDetails\n }\n}\n"
FRAGMENT_CIRCLE_DETAILS = "fragment CircleDetails on Circle {\n __typename\n radius\n latitude\n longitude\n}\n"
FRAGMENT_LOCATION_POINT = "fragment LocationPoint on Location {\n __typename\n date\n errorRadius\n position {\n __typename\n ...PositionCoordinates\n }\n}\n"
FRAGMENT_PLACE_DETAILS = "fragment PlaceDetails on Place {\n __typename\n id\n name\n address\n position {\n __typename\n ...PositionCoordinates\n }\n radius\n}\n"
FRAGMENT_ACTIVITY_SUMMARY_DETAILS = "fragment ActivitySummaryDetails on ActivitySummary {\n __typename\n start\n end\n totalSteps\n stepGoal\n dailySteps {\n __typename\n date\n totalSteps\n stepGoal\n }\n totalDistance\n}\n"
FRAGMENT_REST_SUMMARY_DETAILS = "fragment RestSummaryDetails on RestSummary {\n __typename\n start\n end\n data {\n __typename\n ... on ConcreteRestSummaryData {\n sleepAmounts {\n __typename\n type\n duration\n }\n }\n }\n}\n"
MUTATION_DEVICE_OPS = "mutation UpdateDeviceOperationParams($input: UpdateDeviceOperationParamsInput!) {\n updateDeviceOperationParams(input: $input) {\n __typename\n ...DeviceDetails\n }\n}\n"
MUTATION_SET_LED_COLOR = "mutation SetDeviceLed($moduleId: String!, $ledColorCode: Int!) {\n setDeviceLed(moduleId: $moduleId, ledColorCode: $ledColorCode) {\n __typename\n ...DeviceDetails\n }\n}\n"
FRAGMENT_USER_DETAILS = "fragment UserDetails on User { __typename id email firstName lastName phoneNumber fiNewsNotificationsEnabled chipReseller { __typename id }}"
FRAGMENT_USER_FULL_DETAILS = "fragment UserFullDetails on User { __typename ...UserDetails userHouseholds { __typename household { __typename pets { __typename ...PetProfile } bases { __typename ...BaseDetails } } }}"
FRAGEMENT_BASE_PET_PROFILE = "fragment BasePetProfile on BasePet { __typename id name homeCityState yearOfBirth monthOfBirth dayOfBirth gender weight isPurebred breed { __typename ...BreedDetails } photos { __typename first { __typename ...PhotoDetails } items { __typename ...PhotoDetails } } instagramHandle }"
FRAGMENT_BREED_DETAILS = "fragment BreedDetails on Breed { __typename id name popularityScore}"
FRAGMENT_PHOTO_DETAILS = "fragment PhotoDetails on Photo { __typename id caption date likeCount liked image { __typename fullSize }}"
FRAGMENT_PET_PROFILE = "fragment PetProfile on Pet { __typename ...BasePetProfile chip { __typename shortId } device { __typename ...DeviceDetails }}"
FRAGMENT_DEVICE_DETAILS = "fragment DeviceDetails on Device { __typename id moduleId info subscriptionId hasActiveSubscription hasSubscriptionOverride nextLocationUpdateExpectedBy operationParams { __typename ...OperationParamsDetails } lastConnectionState { __typename ...ConnectionStateDetails } ledColor { __typename ...LedColorDetails } availableLedColors { __typename ...LedColorDetails }}"
FRAGMENT_LED_DETAILS = "fragment LedColorDetails on LedColor { __typename ledColorCode hexCode name}"
FRAGMENT_CONNECTION_STATE_DETAILS = "fragment ConnectionStateDetails on ConnectionState { __typename date ... on ConnectedToUser { user { __typename ...UserDetails } } ... on ConnectedToBase { chargingBase { __typename id } } ... on ConnectedToCellular { signalStrengthPercent } ... on UnknownConnectivity { unknownConnectivity }}"
FRAGMENT_OPERATIONAL_DETAILS = "fragment OperationParamsDetails on OperationParams { __typename mode ledEnabled ledOffAt}"
FRAGMENT_BASE_DETAILS = "fragment BaseDetails on ChargingBase { __typename baseId name position { __typename ...PositionCoordinates } infoLastUpdated networkName online onlineQuality}"
FRAGMENT_POSITION_COORDINATES = "fragment PositionCoordinates on Position { __typename latitude longitude}"
FRAGMENT_ONGOING_ACTIVITY_DETAILS = "fragment OngoingActivityDetails on OngoingActivity { __typename start presentUser { __typename ...UserDetails } areaName lastReportTimestamp obfuscatedReason totalSteps uncertaintyInfo { __typename ...UncertaintyInfoDetails } ... on OngoingWalk { distance positions { __typename ...LocationPoint } path { __typename ...PositionCoordinates } } ... on OngoingRest { position { __typename ...PositionCoordinates } place { __typename ...PlaceDetails } }}"
FRAGMENT_UNCERTAINTY_DETAILS = "fragment UncertaintyInfoDetails on UncertaintyInfo { __typename areaName updatedAt circle { __typename ...CircleDetails }}"
FRAGMENT_CIRCLE_DETAILS = "fragment CircleDetails on Circle { __typename radius latitude longitude}"
FRAGMENT_LOCATION_POINT = "fragment LocationPoint on Location { __typename date errorRadius position { __typename ...PositionCoordinates }}"
FRAGMENT_PLACE_DETAILS = "fragment PlaceDetails on Place { __typename id name address position { __typename ...PositionCoordinates } radius}"
FRAGMENT_ACTIVITY_SUMMARY_DETAILS = "fragment ActivitySummaryDetails on ActivitySummary { __typename start end totalSteps stepGoal dailySteps { __typename date totalSteps stepGoal } totalDistance}"
FRAGMENT_REST_SUMMARY_DETAILS = "fragment RestSummaryDetails on RestSummary { __typename start end data { __typename ... on ConcreteRestSummaryData { sleepAmounts { __typename type duration } } }}"
MUTATION_DEVICE_OPS = "mutation UpdateDeviceOperationParams($input: UpdateDeviceOperationParamsInput!) { updateDeviceOperationParams(input: $input) { __typename ...DeviceDetails }}"
MUTATION_SET_LED_COLOR = "mutation SetDeviceLed($moduleId: String!, $ledColorCode: Int!) { setDeviceLed(moduleId: $moduleId, ledColorCode: $ledColorCode) { __typename ...DeviceDetails }}"
2 changes: 1 addition & 1 deletion pytryfi/fiPet.py
Original file line number Diff line number Diff line change
Expand Up @@ -215,7 +215,7 @@ def setLedColorCode(self, sessionId, colorCode):
moduleId = self.device.moduleId
ledColorCode = int(colorCode)
setColorJSON = query.setLedColor(sessionId, moduleId, ledColorCode)
try:
try:
self.device.setDeviceDetailsJSON(setColorJSON['setDeviceLed'])
except Exception as e:
LOGGER.warning(f"Updated LED Color but could not get current status for Pet: {self.name}\nException: {e}")
Expand Down

0 comments on commit 6bf9f61

Please sign in to comment.