diff --git a/spond/club.py b/spond/club.py new file mode 100644 index 0000000..13089f8 --- /dev/null +++ b/spond/club.py @@ -0,0 +1,69 @@ +import aiohttp + + +class Spond: + def __init__(self, username, password): + self.username = username + self.password = password + self.api_url = "https://api.spond.com/club/v1/" + self.clientsession = aiohttp.ClientSession(cookie_jar=aiohttp.CookieJar()) + self.token = None + self.transactions = [] + + @property + def auth_headers(self): + return { + "content-type": "application/json", + "Authorization": f"Bearer {self.token}", + } + + async def login(self): + login_url = f"{self.api_url}login" + data = {"email": self.username, "password": self.password} + async with self.clientsession.post(login_url, json=data) as r: + login_result = await r.json() + self.token = login_result.get("loginToken", None) + if self.token is None: + err_msg = f"Login failed. Response received: {login_result}" + raise ValueError(err_msg) + + async def get_transactions( + self, group_id: str, skip: int = None, max_items: int = 100 + ): + """Get transactions / payments made + + Args: + group_id (str): This group ID is different than the Group ID from core API. + max_items (int, optional): Max transactions to grab. Defaults to 100. + skip (int, optional): This endpoint only returns 25 transactions at a time + (page scrolling). Therefore, we need to increment this `skip` param to + grab the next 25 etc. Defaults to None. It's better if users keep `skip` + at None and specify `max_items` instead. This param is only here for the + recursion implementation + + Returns: + list[dict]: each payment as a json dict + """ + if not self.token: + await self.login() + + url = f"{self.api_url}transactions" + params = None if skip is None else {"skip": skip} + headers = {**self.auth_headers, "X-Spond-Clubid": group_id} + + async with aiohttp.ClientSession() as session: + async with session.get(url, headers=headers, params=params) as response: + if response.status == 200: + t = await response.json() + if len(t) == 0: + return self.transactions + + self.transactions.extend(t) + if len(self.transactions) < max_items: + return await self.get_transactions( + group_id=group_id, + skip=len(t) if skip is None else skip + len(t), + max_items=max_items, + ) + + return self.transactions