2019-12-08 22:43:49 +01:00
|
|
|
import json
|
|
|
|
import requests
|
|
|
|
from typing import Tuple, Dict, List, Any, Optional
|
2021-09-07 19:57:18 +02:00
|
|
|
from typing_extensions import Final
|
2019-12-08 22:43:49 +01:00
|
|
|
|
2022-10-15 20:56:30 +02:00
|
|
|
from bemani.common import (
|
|
|
|
APIConstants,
|
|
|
|
GameConstants,
|
|
|
|
VersionConstants,
|
|
|
|
DBConstants,
|
|
|
|
ValidatedDict,
|
2023-08-19 19:41:14 +02:00
|
|
|
Time,
|
|
|
|
cache,
|
2022-10-15 20:56:30 +02:00
|
|
|
)
|
2019-12-08 22:43:49 +01:00
|
|
|
|
|
|
|
|
|
|
|
class APIException(Exception):
|
|
|
|
pass
|
|
|
|
|
|
|
|
|
|
|
|
class NotAuthorizedAPIException(APIException):
|
|
|
|
pass
|
|
|
|
|
|
|
|
|
|
|
|
class UnsupportedRequestAPIException(APIException):
|
|
|
|
pass
|
|
|
|
|
|
|
|
|
|
|
|
class UnrecognizedRequestAPIException(APIException):
|
|
|
|
pass
|
|
|
|
|
|
|
|
|
|
|
|
class UnsupportedVersionAPIException(APIException):
|
|
|
|
pass
|
|
|
|
|
|
|
|
|
|
|
|
class RemoteServerErrorAPIException(APIException):
|
|
|
|
pass
|
|
|
|
|
|
|
|
|
|
|
|
class APIClient:
|
|
|
|
"""
|
|
|
|
A client that fully speaks BEMAPI and can pull information from a remote server.
|
|
|
|
"""
|
|
|
|
|
2022-10-15 20:56:30 +02:00
|
|
|
API_VERSION: Final[str] = "v1"
|
2019-12-08 22:43:49 +01:00
|
|
|
|
2024-01-02 03:46:24 +01:00
|
|
|
def __init__(self, base_uri: str, token: str, allow_stats: bool, allow_scores: bool) -> None:
|
2019-12-08 22:43:49 +01:00
|
|
|
self.base_uri = base_uri
|
|
|
|
self.token = token
|
|
|
|
self.allow_stats = allow_stats
|
|
|
|
self.allow_scores = allow_scores
|
|
|
|
|
2023-08-22 04:48:18 +02:00
|
|
|
def __repr__(self) -> str:
|
|
|
|
# Specifically defined so that two different instances of the same API client
|
|
|
|
# cache under the same key, as we want to share results from a given server
|
2024-06-28 02:14:27 +02:00
|
|
|
# to all local requests. We also have to be sensitive to any control character
|
|
|
|
# limitations for memcached.
|
|
|
|
repr_val = (
|
2023-08-22 04:48:18 +02:00
|
|
|
"APIClient("
|
2024-06-28 02:14:27 +02:00
|
|
|
+ f"base_uri={self.base_uri!r},"
|
|
|
|
+ f"token={self.token!r},"
|
|
|
|
+ f"allow_stats={self.allow_stats!r},"
|
2023-08-22 04:48:18 +02:00
|
|
|
+ f"allow_scores={self.allow_scores!r}"
|
|
|
|
+ ")"
|
|
|
|
)
|
2024-06-28 02:14:27 +02:00
|
|
|
repr_val = repr_val.replace(" ", "_")
|
|
|
|
repr_val = repr_val.replace("\r", "_")
|
|
|
|
repr_val = repr_val.replace("\n", "_")
|
|
|
|
return repr_val
|
2023-08-22 04:48:18 +02:00
|
|
|
|
2021-05-31 20:14:04 +02:00
|
|
|
def _content_type_valid(self, content_type: str) -> bool:
|
2022-10-15 20:56:30 +02:00
|
|
|
if ";" in content_type:
|
|
|
|
left, right = content_type.split(";", 1)
|
2021-05-08 03:49:42 +02:00
|
|
|
left = left.strip().lower()
|
|
|
|
right = right.strip().lower()
|
|
|
|
|
2022-10-15 20:56:30 +02:00
|
|
|
if left == "application/json" and ("=" in right):
|
|
|
|
identifier, charset = right.split("=", 1)
|
2021-05-08 03:49:42 +02:00
|
|
|
identifier = identifier.strip()
|
|
|
|
charset = charset.strip()
|
|
|
|
|
2022-10-15 20:56:30 +02:00
|
|
|
if identifier == "charset" and charset == "utf-8":
|
2021-05-08 03:49:42 +02:00
|
|
|
# This is valid.
|
|
|
|
return True
|
|
|
|
return False
|
|
|
|
|
2024-01-02 03:46:24 +01:00
|
|
|
def __exchange_data(self, request_uri: str, request_args: Dict[str, Any]) -> Dict[str, Any]:
|
2022-10-15 20:56:30 +02:00
|
|
|
if self.base_uri[-1:] != "/":
|
|
|
|
uri = f"{self.base_uri}/{request_uri}"
|
2019-12-08 22:43:49 +01:00
|
|
|
else:
|
2022-10-15 20:56:30 +02:00
|
|
|
uri = f"{self.base_uri}{request_uri}"
|
2019-12-08 22:43:49 +01:00
|
|
|
|
|
|
|
headers = {
|
2022-10-15 20:56:30 +02:00
|
|
|
"Authorization": f"Token {self.token}",
|
|
|
|
"Content-Type": "application/json; charset=utf-8",
|
2019-12-08 22:43:49 +01:00
|
|
|
}
|
2022-10-15 20:56:30 +02:00
|
|
|
data = json.dumps(request_args).encode("utf8")
|
2019-12-08 22:43:49 +01:00
|
|
|
|
|
|
|
try:
|
|
|
|
r = requests.request(
|
2022-10-15 20:56:30 +02:00
|
|
|
"GET",
|
2019-12-08 22:43:49 +01:00
|
|
|
uri,
|
|
|
|
headers=headers,
|
|
|
|
data=data,
|
|
|
|
allow_redirects=False,
|
|
|
|
timeout=10,
|
|
|
|
)
|
|
|
|
except Exception:
|
2022-10-15 20:56:30 +02:00
|
|
|
raise APIException("Failed to query remote server!")
|
2019-12-08 22:43:49 +01:00
|
|
|
|
2021-05-08 03:49:42 +02:00
|
|
|
# Verify that content type is in the form of "application/json; charset=utf-8".
|
2022-10-15 20:56:30 +02:00
|
|
|
if not self._content_type_valid(r.headers["content-type"]):
|
2024-01-02 03:46:24 +01:00
|
|
|
raise APIException(f'API returned invalid content type \'{r.headers["content-type"]}\'!')
|
2019-12-08 22:43:49 +01:00
|
|
|
|
|
|
|
jsondata = r.json()
|
|
|
|
|
|
|
|
if r.status_code == 200:
|
|
|
|
return jsondata
|
|
|
|
|
2022-10-15 20:56:30 +02:00
|
|
|
if "error" not in jsondata:
|
|
|
|
raise APIException(
|
|
|
|
f"API returned error code {r.status_code} but did not include 'error' attribute in response JSON!"
|
|
|
|
)
|
|
|
|
error = jsondata["error"]
|
2019-12-08 22:43:49 +01:00
|
|
|
|
|
|
|
if r.status_code == 401:
|
2024-01-02 03:46:24 +01:00
|
|
|
raise NotAuthorizedAPIException("The API token used is not authorized against this server!")
|
2019-12-08 22:43:49 +01:00
|
|
|
if r.status_code == 404:
|
2024-01-02 03:46:24 +01:00
|
|
|
raise UnsupportedRequestAPIException("The server does not support this game/version or request object!")
|
2019-12-08 22:43:49 +01:00
|
|
|
if r.status_code == 405:
|
2024-01-02 03:46:24 +01:00
|
|
|
raise UnrecognizedRequestAPIException("The server did not recognize the request!")
|
2019-12-08 22:43:49 +01:00
|
|
|
if r.status_code == 500:
|
2022-10-15 20:56:30 +02:00
|
|
|
raise RemoteServerErrorAPIException(
|
|
|
|
f"The server had an error processing the request and returned '{error}'"
|
|
|
|
)
|
2019-12-08 22:43:49 +01:00
|
|
|
if r.status_code == 501:
|
2024-01-02 03:46:24 +01:00
|
|
|
raise UnsupportedVersionAPIException("The server does not support this version of the API!")
|
|
|
|
raise APIException("The server returned an invalid status code {}!", format(r.status_code))
|
2019-12-08 22:43:49 +01:00
|
|
|
|
2021-08-19 21:21:22 +02:00
|
|
|
def __translate(self, game: GameConstants, version: int) -> Tuple[str, str]:
|
2019-12-08 22:43:49 +01:00
|
|
|
servergame = {
|
2022-10-15 20:56:30 +02:00
|
|
|
GameConstants.DDR: "ddr",
|
|
|
|
GameConstants.IIDX: "iidx",
|
|
|
|
GameConstants.JUBEAT: "jubeat",
|
|
|
|
GameConstants.MUSECA: "museca",
|
|
|
|
GameConstants.POPN_MUSIC: "popnmusic",
|
|
|
|
GameConstants.REFLEC_BEAT: "reflecbeat",
|
|
|
|
GameConstants.SDVX: "soundvoltex",
|
2019-12-08 22:43:49 +01:00
|
|
|
}.get(game)
|
|
|
|
if servergame is None:
|
2024-01-02 03:46:24 +01:00
|
|
|
raise UnsupportedRequestAPIException("The client does not support this game/version!")
|
2019-12-08 22:43:49 +01:00
|
|
|
|
|
|
|
if version >= DBConstants.OMNIMIX_VERSION_BUMP:
|
|
|
|
version = version - DBConstants.OMNIMIX_VERSION_BUMP
|
|
|
|
omnimix = True
|
|
|
|
else:
|
|
|
|
omnimix = False
|
|
|
|
|
2022-10-15 20:56:30 +02:00
|
|
|
serverversion = (
|
|
|
|
{
|
|
|
|
GameConstants.DDR: {
|
|
|
|
VersionConstants.DDR_X2: "12",
|
|
|
|
VersionConstants.DDR_X3_VS_2NDMIX: "13",
|
|
|
|
VersionConstants.DDR_2013: "14",
|
|
|
|
VersionConstants.DDR_2014: "15",
|
|
|
|
VersionConstants.DDR_ACE: "16",
|
2022-11-01 04:46:18 +01:00
|
|
|
VersionConstants.DDR_A20: "17",
|
2022-10-15 20:56:30 +02:00
|
|
|
},
|
|
|
|
GameConstants.IIDX: {
|
|
|
|
VersionConstants.IIDX_TRICORO: "20",
|
|
|
|
VersionConstants.IIDX_SPADA: "21",
|
|
|
|
VersionConstants.IIDX_PENDUAL: "22",
|
|
|
|
VersionConstants.IIDX_COPULA: "23",
|
|
|
|
VersionConstants.IIDX_SINOBUZ: "24",
|
|
|
|
VersionConstants.IIDX_CANNON_BALLERS: "25",
|
|
|
|
VersionConstants.IIDX_ROOTAGE: "26",
|
2022-11-01 04:46:18 +01:00
|
|
|
VersionConstants.IIDX_HEROIC_VERSE: "27",
|
|
|
|
VersionConstants.IIDX_BISTROVER: "28",
|
2022-10-15 20:56:30 +02:00
|
|
|
},
|
|
|
|
GameConstants.JUBEAT: {
|
|
|
|
VersionConstants.JUBEAT_SAUCER: "5",
|
|
|
|
VersionConstants.JUBEAT_SAUCER_FULFILL: "5a",
|
|
|
|
VersionConstants.JUBEAT_PROP: "6",
|
|
|
|
VersionConstants.JUBEAT_QUBELL: "7",
|
|
|
|
VersionConstants.JUBEAT_CLAN: "8",
|
|
|
|
VersionConstants.JUBEAT_FESTO: "9",
|
2022-11-01 04:46:18 +01:00
|
|
|
VersionConstants.JUBEAT_AVENUE: "10",
|
2022-10-15 20:56:30 +02:00
|
|
|
},
|
|
|
|
GameConstants.MUSECA: {
|
|
|
|
VersionConstants.MUSECA: "1",
|
|
|
|
VersionConstants.MUSECA_1_PLUS: "1p",
|
|
|
|
},
|
|
|
|
GameConstants.POPN_MUSIC: {
|
|
|
|
VersionConstants.POPN_MUSIC_TUNE_STREET: "19",
|
|
|
|
VersionConstants.POPN_MUSIC_FANTASIA: "20",
|
|
|
|
VersionConstants.POPN_MUSIC_SUNNY_PARK: "21",
|
|
|
|
VersionConstants.POPN_MUSIC_LAPISTORIA: "22",
|
|
|
|
VersionConstants.POPN_MUSIC_ECLALE: "23",
|
|
|
|
VersionConstants.POPN_MUSIC_USANEKO: "24",
|
2022-11-01 04:46:18 +01:00
|
|
|
VersionConstants.POPN_MUSIC_PEACE: "25",
|
|
|
|
VersionConstants.POPN_MUSIC_KAIMEI_RIDDLES: "26",
|
2022-10-15 20:56:30 +02:00
|
|
|
},
|
|
|
|
GameConstants.REFLEC_BEAT: {
|
|
|
|
VersionConstants.REFLEC_BEAT: "1",
|
|
|
|
VersionConstants.REFLEC_BEAT_LIMELIGHT: "2",
|
|
|
|
VersionConstants.REFLEC_BEAT_COLETTE: "3as",
|
|
|
|
VersionConstants.REFLEC_BEAT_GROOVIN: "4u",
|
|
|
|
VersionConstants.REFLEC_BEAT_VOLZZA: "5",
|
|
|
|
VersionConstants.REFLEC_BEAT_VOLZZA_2: "5a",
|
|
|
|
VersionConstants.REFLEC_BEAT_REFLESIA: "6",
|
|
|
|
},
|
|
|
|
GameConstants.SDVX: {
|
|
|
|
VersionConstants.SDVX_BOOTH: "1",
|
|
|
|
VersionConstants.SDVX_INFINITE_INFECTION: "2",
|
|
|
|
VersionConstants.SDVX_GRAVITY_WARS: "3",
|
|
|
|
VersionConstants.SDVX_HEAVENLY_HAVEN: "4",
|
|
|
|
},
|
|
|
|
}
|
|
|
|
.get(game, {})
|
|
|
|
.get(version)
|
|
|
|
)
|
2019-12-08 22:43:49 +01:00
|
|
|
if serverversion is None:
|
2024-01-02 03:46:24 +01:00
|
|
|
raise UnsupportedRequestAPIException("The client does not support this game/version!")
|
2019-12-08 22:43:49 +01:00
|
|
|
|
|
|
|
if omnimix:
|
2022-10-15 20:56:30 +02:00
|
|
|
serverversion = "o" + serverversion
|
2019-12-08 22:43:49 +01:00
|
|
|
|
|
|
|
return (servergame, serverversion)
|
|
|
|
|
2023-08-19 19:41:14 +02:00
|
|
|
# Not caching this, as it is only hit when looking at the admin panel, and we want this to
|
|
|
|
# always be up-to-date.
|
2019-12-08 22:43:49 +01:00
|
|
|
def get_server_info(self) -> ValidatedDict:
|
2022-10-15 20:56:30 +02:00
|
|
|
resp = self.__exchange_data("", {})
|
|
|
|
return ValidatedDict(
|
|
|
|
{
|
|
|
|
"name": resp["name"],
|
|
|
|
"email": resp["email"],
|
|
|
|
"versions": resp["versions"],
|
|
|
|
}
|
|
|
|
)
|
|
|
|
|
2023-08-19 19:41:14 +02:00
|
|
|
# Not caching this, as we would have to go back and ensure that any code which got outdated
|
|
|
|
# profiles from a cache didn't end up with KeyError exceptions when trying to link profiles to
|
|
|
|
# records. This is the coward's way out, but whatever.
|
2022-10-15 20:56:30 +02:00
|
|
|
def get_profiles(
|
|
|
|
self, game: GameConstants, version: int, idtype: APIConstants, ids: List[str]
|
|
|
|
) -> List[Dict[str, Any]]:
|
2019-12-08 22:43:49 +01:00
|
|
|
# Allow remote servers to be disabled
|
|
|
|
if not self.allow_scores:
|
|
|
|
return []
|
|
|
|
|
|
|
|
try:
|
|
|
|
servergame, serverversion = self.__translate(game, version)
|
|
|
|
resp = self.__exchange_data(
|
2022-10-15 20:56:30 +02:00
|
|
|
f"{self.API_VERSION}/{servergame}/{serverversion}",
|
2019-12-08 22:43:49 +01:00
|
|
|
{
|
2022-10-15 20:56:30 +02:00
|
|
|
"ids": ids,
|
|
|
|
"type": idtype.value,
|
|
|
|
"objects": ["profile"],
|
2019-12-08 22:43:49 +01:00
|
|
|
},
|
|
|
|
)
|
2022-10-15 20:56:30 +02:00
|
|
|
return resp["profile"]
|
2019-12-08 22:43:49 +01:00
|
|
|
except APIException:
|
|
|
|
# Couldn't talk to server, assume empty profiles
|
|
|
|
return []
|
|
|
|
|
2023-08-19 19:41:14 +02:00
|
|
|
@cache.memoize(Time.SECONDS_IN_MINUTE * 1)
|
2019-12-08 22:43:49 +01:00
|
|
|
def get_records(
|
|
|
|
self,
|
2021-08-19 21:21:22 +02:00
|
|
|
game: GameConstants,
|
2019-12-08 22:43:49 +01:00
|
|
|
version: int,
|
2021-08-19 21:21:41 +02:00
|
|
|
idtype: APIConstants,
|
2019-12-08 22:43:49 +01:00
|
|
|
ids: List[str],
|
2022-10-15 20:56:30 +02:00
|
|
|
since: Optional[int] = None,
|
|
|
|
until: Optional[int] = None,
|
2019-12-08 22:43:49 +01:00
|
|
|
) -> List[Dict[str, Any]]:
|
|
|
|
# Allow remote servers to be disabled
|
|
|
|
if not self.allow_scores:
|
|
|
|
return []
|
|
|
|
|
|
|
|
try:
|
|
|
|
servergame, serverversion = self.__translate(game, version)
|
|
|
|
data: Dict[str, Any] = {
|
2022-10-15 20:56:30 +02:00
|
|
|
"ids": ids,
|
|
|
|
"type": idtype.value,
|
|
|
|
"objects": ["records"],
|
2019-12-08 22:43:49 +01:00
|
|
|
}
|
|
|
|
if since is not None:
|
2022-10-15 20:56:30 +02:00
|
|
|
data["since"] = since
|
2019-12-08 22:43:49 +01:00
|
|
|
if until is not None:
|
2022-10-15 20:56:30 +02:00
|
|
|
data["until"] = until
|
2019-12-08 22:43:49 +01:00
|
|
|
resp = self.__exchange_data(
|
2022-10-15 20:56:30 +02:00
|
|
|
f"{self.API_VERSION}/{servergame}/{serverversion}",
|
2019-12-08 22:43:49 +01:00
|
|
|
data,
|
|
|
|
)
|
2022-10-15 20:56:30 +02:00
|
|
|
return resp["records"]
|
2019-12-08 22:43:49 +01:00
|
|
|
except APIException:
|
|
|
|
# Couldn't talk to server, assume empty records
|
|
|
|
return []
|
|
|
|
|
2023-08-19 19:41:14 +02:00
|
|
|
@cache.memoize(Time.SECONDS_IN_MINUTE * 5)
|
2022-10-15 20:56:30 +02:00
|
|
|
def get_statistics(
|
|
|
|
self, game: GameConstants, version: int, idtype: APIConstants, ids: List[str]
|
|
|
|
) -> List[Dict[str, Any]]:
|
2019-12-08 22:43:49 +01:00
|
|
|
# Allow remote servers to be disabled
|
|
|
|
if not self.allow_stats:
|
|
|
|
return []
|
|
|
|
|
|
|
|
try:
|
|
|
|
servergame, serverversion = self.__translate(game, version)
|
|
|
|
resp = self.__exchange_data(
|
2022-10-15 20:56:30 +02:00
|
|
|
f"{self.API_VERSION}/{servergame}/{serverversion}",
|
2019-12-08 22:43:49 +01:00
|
|
|
{
|
2022-10-15 20:56:30 +02:00
|
|
|
"ids": ids,
|
|
|
|
"type": idtype.value,
|
|
|
|
"objects": ["statistics"],
|
2019-12-08 22:43:49 +01:00
|
|
|
},
|
|
|
|
)
|
2022-10-15 20:56:30 +02:00
|
|
|
return resp["statistics"]
|
2019-12-08 22:43:49 +01:00
|
|
|
except APIException:
|
|
|
|
# Couldn't talk to server, assume empty statistics
|
|
|
|
return []
|
|
|
|
|
2023-08-19 19:41:14 +02:00
|
|
|
@cache.memoize(Time.SECONDS_IN_HOUR * 1)
|
2024-01-02 03:46:24 +01:00
|
|
|
def get_catalog(self, game: GameConstants, version: int) -> Dict[str, List[Dict[str, Any]]]:
|
2019-12-08 22:43:49 +01:00
|
|
|
# No point disallowing this, since its only ever used for bootstrapping.
|
|
|
|
|
|
|
|
try:
|
|
|
|
servergame, serverversion = self.__translate(game, version)
|
|
|
|
resp = self.__exchange_data(
|
2022-10-15 20:56:30 +02:00
|
|
|
f"{self.API_VERSION}/{servergame}/{serverversion}",
|
2019-12-08 22:43:49 +01:00
|
|
|
{
|
2022-10-15 20:56:30 +02:00
|
|
|
"ids": [],
|
|
|
|
"type": "server",
|
|
|
|
"objects": ["catalog"],
|
2019-12-08 22:43:49 +01:00
|
|
|
},
|
|
|
|
)
|
2022-10-15 20:56:30 +02:00
|
|
|
return resp["catalog"]
|
2019-12-08 22:43:49 +01:00
|
|
|
except APIException:
|
|
|
|
# Couldn't talk to server, assume empty catalog
|
|
|
|
return {}
|