qcs-python/contentapi.py

176 lines
6.9 KiB
Python
Raw Normal View History

2023-04-30 22:18:25 +00:00
2023-04-30 22:49:30 +00:00
import requests
2023-05-01 01:58:02 +00:00
import logging
2023-05-01 17:02:29 +00:00
import json
2023-04-30 22:49:30 +00:00
class AuthenticationError(Exception):
2023-05-01 01:58:02 +00:00
""" Exception for 401 errors, meaning your token was bad (expired maybe?) """
2023-04-30 22:49:30 +00:00
class BadRequestError(Exception):
2023-05-01 01:58:02 +00:00
"""Exception for 400 errors, meaning you gave something funky to the API
(maybe your search was malformed?) """
2023-04-30 22:49:30 +00:00
class NotFoundError(Exception):
2023-05-01 01:58:02 +00:00
"""Exception for 404 errors, meaning whatever you were looking for wasn't found
(This is rare from the API) """
2023-04-30 22:49:30 +00:00
2023-05-01 17:02:29 +00:00
# Given a normal result set for users, find the user by id or return some reasonable default
def get_user_or_default(users, id):
for u in users:
if "id" in u and u["id"] == id:
return u
return { "id" : id, "username" : "???", "avatar": "0" }
2023-05-01 20:06:40 +00:00
# Given a normal result set for messages, find the message by id or return None
def get_message(messages, id):
for m in messages:
if "id" in m and m["id"] == id:
return m
return None
# Constants for user actions
CREATE = 1
READ = 2
UPDATE = 4
DELETE = 8
2023-05-01 17:02:29 +00:00
2023-04-30 22:49:30 +00:00
# Your gateway to the static endpoints for contentapi. It's a context because it needs
# to track stuff like "which api am I contacting" and "which user am I authenticating as (if any)"
2023-04-30 22:18:25 +00:00
class ApiContext:
2023-04-30 22:49:30 +00:00
# You MUST define the endpoint when creating the API context! You can optionally set
# the token on startup, or you can set it at any time. Set to a "falsey" value to
# to browse as an anonymous user
2023-05-01 01:58:02 +00:00
def __init__(self, endpoint: str, logger: logging.Logger, token = False):
2023-04-30 22:18:25 +00:00
self.endpoint = endpoint
2023-04-30 22:49:30 +00:00
self.logger = logger
self.token = token
2023-05-01 01:58:02 +00:00
2023-05-01 05:55:20 +00:00
# Contentapi websocket endpoint is always wss, and we assume the websocket is always secure too.
# If these are not reasonable assumptions... I guess make a regex replacement instead?
def websocket_endpoint(self, lastId = 0):
if not self.token:
raise Exception("Cannot connect to websocket endpoint without token!!")
result = self.endpoint.replace("https:", "wss:") + "/live/ws?token=%s" % self.token
if lastId:
result += "&lastId=%d" % lastId
return result
2023-04-30 22:49:30 +00:00
# Generate the standard headers we use for most requests. You usually don't need to
# change anything here, just make sure your token is set if you want to be logged in
def gen_header(self, content_type = "application/json"):
headers = {
2023-05-01 01:58:02 +00:00
"Content-Type" : content_type,
"Accept" : content_type
2023-04-30 22:49:30 +00:00
}
if self.token:
2023-05-01 02:13:01 +00:00
headers["Authorization"] = "Bearer " + self.token
2023-04-30 22:49:30 +00:00
return headers
# Given a standard response from the API, parse the status code to throw the appropriate
# exceptions, or return the actual response from the API as a parsed object.
def parse_response(self, response):
if response.status_code == 200:
return response.json()
elif response.status_code == 400:
raise BadRequestError("Bad request: %s" % response.text)
2023-04-30 22:49:30 +00:00
elif response.status_code == 401:
raise AuthenticationError("Your token is bad!")
elif response.status_code == 404:
raise NotFoundError("Not found: %s" % response.text)
2023-04-30 22:49:30 +00:00
else:
2023-05-01 01:58:02 +00:00
raise Exception("Unknown error (%s) - %s" % (response.status_code, response.content))
2023-04-30 22:49:30 +00:00
# Perform a standard get request and return the pre-parsed object (all contentapi endpoints
# return objects). Throws exception on error
def get(self, endpoint):
2023-05-01 01:58:02 +00:00
url = self.endpoint + "/" + endpoint
# self.logger.debug("GET: " + url) # Not necessary, DEBUG in requests does this
response = requests.get(url, headers = self.gen_header())
return self.parse_response(response)
def post(self, endpoint, data):
url = self.endpoint + "/" + endpoint
# self.logger.debug("POST: " + url)
response = requests.post(url, headers = self.gen_header(), json = data)
2023-04-30 22:49:30 +00:00
return self.parse_response(response)
# Connect to the API to determine if your token is still valid. Or, if you pass a token,
# check if only the given token is valid
2023-05-01 02:13:01 +00:00
def is_token_valid(self):
2023-04-30 22:49:30 +00:00
try:
2023-05-01 04:34:56 +00:00
return self.token and self.user_me()
2023-04-30 22:49:30 +00:00
except Exception as ex:
2023-05-01 01:58:02 +00:00
self.logger.debug("Error from endpoint: %s" % ex)
2023-04-30 22:49:30 +00:00
return False
2023-05-01 17:02:29 +00:00
# Generate a completely ready websocket request (for data). You can write the result directly to the websocket
def gen_ws_request(self, type, data = None, id = None):
request = {
"type" : type
}
if data:
request["data"] = data
if id:
request["id"] = id
return json.dumps(request)
2023-05-01 01:58:02 +00:00
2023-05-01 04:34:56 +00:00
# Return info about the current user based on the token. Useful to see if your token is valid
# and who you are
def user_me(self):
return self.get("user/me")
2023-05-01 01:58:02 +00:00
# Basic login endpoint, should return your token on success
def login(self, username, password, expire_seconds = False):
data = {
"username" : username,
"password" : password
}
if expire_seconds:
data["expireSeconds"] = expire_seconds
return self.post("user/login", data)
# Get information about the API. Very useful to test your connection to the API
def api_status(self):
2023-05-01 14:35:31 +00:00
return self.get("status")
2023-05-01 15:21:45 +00:00
# Access the raw search endpoint of the API (you must construct the special contentapi request yourself!)
2023-05-01 14:35:31 +00:00
def search(self, requests):
return self.post("request", requests)
2023-05-01 15:21:45 +00:00
# A very basic search for outputting to the console. Constructs the contentapi search request for you: many assumptions are made!
2023-05-01 14:35:31 +00:00
def basic_search(self, searchterm, limit = 0):
return self.search({
"values": {
"searchterm": searchterm,
"searchtermlike": "%" + searchterm + "%"
},
"requests": [{
"type": "content",
"fields": "~text,engagement", # All fields EXCEPT text and engagement
"query": "name LIKE @searchtermlike",
"order": "lastActionDate_desc",
"limit": limit
}]
})
# Return the singular item of 'type' for the given ID. Raises a "NotFoundError" if nothing found.
def get_by_id(self, type, id, fields = "*"):
result = self.search({
"values" : {
"id" : id
},
"requests": [{
"type" : type,
"fields": fields,
"query": "id = @id"
}]
})
things = result["objects"][type]
if not len(things):
raise NotFoundError("Couldn't find %s with id %d" % (type, id))
return things[0]