Skip to content

Commit

Permalink
Merge pull request #4 from CNDRD/guns
Browse files Browse the repository at this point in the history
V2
  • Loading branch information
CNDRD authored Mar 17, 2022
2 parents 43790be + de2a737 commit 672cd4b
Show file tree
Hide file tree
Showing 20 changed files with 1,235 additions and 786 deletions.
20 changes: 12 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,34 +35,38 @@ pip install siegeapi

## Quick example
```python
from siegeapi import Auth, Platforms
from siegeapi import Auth
import asyncio

async def sample():
auth = Auth("UBI_EMAIL", "UBI_PASSWORD")
player = await auth.get_player(uid="7e0f63df-a39b-44c5-8de0-d39a05926e77", platform=Platforms.UPLAY)
player = await auth.get_player(uid="7e0f63df-a39b-44c5-8de0-d39a05926e77")

print(f"Name: {player.name}")
print(f"Profile pic URL: {player.profile_pic_url}")

await player.load_level()
await player.load_playtime()
print(f"Total Time Played: {player.total_time_played}")

await player.load_progress()
print(f"Level: {player.level}")
print(f"Alpha pack %: {player.lootbox_probability}")
print(f"Alpha pack %: {player.alpha_pack}")
print(f"XP: {player.xp}")

await auth.close()

asyncio.get_event_loop().run_until_complete(sample())
# Or `asyncio.run(sample())`
```
### Output
```text
Name: CNDRD
Profile pic URL: https://ubisoft-avatars.akamaized.net/7e0f63df-a39b-44c5-8de0-d39a05926e77/default_256_256.png
Level: 256
Alpha pack %: 2050
Level: 261
Alpha pack %: 3250
XP: 118420
```

> **_NOTE:_** `player.lootbox_probability` is 3 or 4-digits long E.g.: `player.lootbox_probability = 500` 👉 5.00%
---

## Docs
Expand Down
3 changes: 1 addition & 2 deletions setup.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
from setuptools import setup, find_packages

readme = ''
with open('README.md') as f:
long_description = f.read()

setup(
name="siegeapi",
version="1.2.1",
version="2.0.0",
url="https://github.com/CNDRD/siege-api",
description="Rainbow Six Siege API interface",
author="CNDRD",
Expand Down
1 change: 0 additions & 1 deletion siegeapi/__init__.py
Original file line number Diff line number Diff line change
@@ -1,2 +1 @@
from .auth import Auth
from .platforms import Platforms
99 changes: 52 additions & 47 deletions siegeapi/auth.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
from __future__ import annotations

from urllib import parse
import datetime
import aiohttp
import base64
import time
import json
import base64
from urllib import parse
import datetime

from .exceptions import FailedToConnect, InvalidRequest
from .player import Player, PlayerBatch
from .player import Player


class Auth:
Expand Down Expand Up @@ -36,7 +38,7 @@ def __init__(
self.sessionid: str = ""
self.key: str = ""
self.uncertain_spaceid: str = ""
self.spaceids: dict[str:str] = {
self.spaceids: dict[str: str] = {
"uplay": "5172a557-50b5-4665-b7db-e3f2e8c5041d",
"psn": "05bfb3f7-6c21-4c42-be1f-97a33fb5cf66",
"xbl": "98a601e5-ca91-4440-b1c5-753f601a2c90"
Expand All @@ -50,9 +52,41 @@ def __init__(
self._login_cooldown: int = 0
self._session_start: float = time.time()

async def close(self) -> None:
""" Closes the session associated with the auth object """
await self.session.close()
async def _find_players(self, name: str = None, platform: str = None, uid: str = None) -> list[Player]:
""" Get a list of players matching the search term on a given platform """

if name is None and uid is None:
raise TypeError("'name' and 'uid' are both None, exactly one must be given")

if name is not None and uid is not None:
raise TypeError("Cannot search by 'uid' and 'name' at the same time, please give one or the other")

if platform is None:
raise TypeError("platform cannot be None")

if platform not in ("uplay", "xbl", "psn"):
raise TypeError(f"'platform' has to be one of the following: 'uplay' / 'xbl' / 'psn'; Not {platform}")

if name:
data = await self.get(f"https://public-ubiservices.ubi.com/v3/profiles?"
f"nameOnPlatform={parse.quote(name)}&platformType={parse.quote(platform)}")
else:
data = await self.get(f"https://public-ubiservices.ubi.com/v3/users/{uid}/profiles?"
f"platformType={parse.quote(platform)}")

if "profiles" in data:
results = [Player(self, x) for x in data["profiles"] if x.get("platformType", "") == platform]
if len(results) == 0:
raise InvalidRequest("No results")
return results
else:
raise InvalidRequest(f"Missing key profiles in returned JSON object {str(data)}")

async def _ensure_session_valid(self) -> None:
if not self.session:
await self.refresh_session()
elif 0 <= self.refresh_session_period <= (time.time() - self._session_start):
await self.refresh_session()

async def refresh_session(self) -> None:
""" Closes the current session and opens a new one """
Expand All @@ -65,12 +99,6 @@ async def refresh_session(self) -> None:
self.session = aiohttp.ClientSession()
self._session_start = time.time()

async def _ensure_session_valid(self) -> None:
if not self.session:
await self.refresh_session()
elif 0 <= self.refresh_session_period <= (time.time() - self._session_start):
await self.refresh_session()

async def get_session(self) -> aiohttp.ClientSession():
""" Retrieves the current session, ensuring it's valid first """
await self._ensure_session_valid()
Expand Down Expand Up @@ -104,7 +132,11 @@ async def connect(self) -> None:
message = str(data["httpCode"])
raise FailedToConnect(message)

async def get(self, *args, retries=0, referer=None, json=True, **kwargs) -> dict | str:
async def close(self) -> None:
""" Closes the session associated with the auth object """
await self.session.close()

async def get(self, *args, retries: int = 0, referer: str = None, json_: bool = True, **kwargs) -> dict | str:
if not self.key:
last_error = None
for _ in range(self.max_connect_retries):
Expand All @@ -128,7 +160,7 @@ async def get(self, *args, retries=0, referer=None, json=True, **kwargs) -> dict
kwargs["headers"]["Ubi-AppId"] = self.appid
kwargs["headers"]["Ubi-SessionId"] = self.sessionid
kwargs["headers"]["Connection"] = "keep-alive"
kwargs["headers"]["expiration"] = f"{(datetime.datetime.utcnow()+datetime.timedelta(hours=2.0)).isoformat()}Z"
kwargs["headers"]["expiration"] = f"{(datetime.datetime.utcnow() + datetime.timedelta(hours=2.0)).isoformat()}Z"
kwargs["headers"]["Ubi-LocaleCode"] = "x"

if referer is not None:
Expand All @@ -139,7 +171,7 @@ async def get(self, *args, retries=0, referer=None, json=True, **kwargs) -> dict
session = await self.get_session()
resp = await session.get(*args, **kwargs)

if json:
if json_:
try:
data = await resp.json()
except:
Expand Down Expand Up @@ -167,40 +199,13 @@ async def get(self, *args, retries=0, referer=None, json=True, **kwargs) -> dict
else:
return await resp.text()

async def get_players(self, name=None, platform=None, uid=None) -> list[Player]:
""" Get a list of players matching the search term on a given platform """

if name is None and uid is None:
raise TypeError("name and uid are both None, exactly one must be given")

if name is not None and uid is not None:
raise TypeError("cannot search by uid and name at the same time, please give one or the other")

if platform is None:
raise TypeError("platform cannot be None")

if name:
data = await self.get(f"https://public-ubiservices.ubi.com/v3/profiles?"
f"nameOnPlatform={parse.quote(name)}&platformType={parse.quote(platform)}")
else:
data = await self.get(f"https://public-ubiservices.ubi.com/v3/users/{uid}/profiles?"
f"platformType={parse.quote(platform)}")

if "profiles" in data:
results = [Player(self, x) for x in data["profiles"] if x.get("platformType", "") == platform]
if len(results) == 0:
raise InvalidRequest("No results")
return results
else:
raise InvalidRequest(f"Missing key profiles in returned JSON object {str(data)}")

async def get_player(self, name=None, platform=None, uid=None) -> Player:
""" Calls get_players and returns the first element """

results = await self.get_players(name=name, platform=platform, uid=uid)
results = await self._find_players(name=name, platform=platform, uid=uid)
return results[0]

async def get_player_batch(self, platform, names=None, uids=None) -> PlayerBatch:
async def get_player_batch(self, platform, names=None, uids=None) -> dict[str: Player]:
players = {}
if names is not None:
for name in names:
Expand All @@ -211,4 +216,4 @@ async def get_player_batch(self, platform, names=None, uids=None) -> PlayerBatch
for uid in uids:
player = await self.get_player(uid=uid, platform=platform)
players[player.id] = player
return PlayerBatch(players)
return players
3 changes: 1 addition & 2 deletions siegeapi/constants/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
from .stat_names import *
from .seasons import seasons
from .operators import operator_dict
from .app_ids import SIEGE_APP_IDS
from .weapons import WEAPONS_DICT
10 changes: 0 additions & 10 deletions siegeapi/constants/app_ids.py

This file was deleted.

21 changes: 20 additions & 1 deletion siegeapi/constants/operators.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,23 @@
operator_dict = {
"azami": {
"name": "Azami",
"safename": "azami",
"year": "Y7S1",
"health": 2,
"armor": 2,
"unit": "UNAFFILIATED",
"country_code": "JP",
"roles": ["Area Denial"],
"side": "defender",
"id": "",
"icon_url": "https://i.imgur.com/AmyLoc5.png",
"unique_stats": [
{
"id": "operatorpvp_azami_something",
"name": "Kiba Barrier something"
}
]
},
"thorn": {
"name": "Thorn",
"safename": "thorn",
Expand All @@ -12,7 +31,7 @@
"Secure"
],
"side": "defender",
"id": "A00:A00",
"id": "",
"icon_url": "https://i.imgur.com/w5DB6xs.png",
"unique_stats": [
{
Expand Down
Loading

0 comments on commit 672cd4b

Please sign in to comment.