52 lines
1.6 KiB
Python
52 lines
1.6 KiB
Python
|
|
import requests
|
||
|
|
from .app import app
|
||
|
|
from .db import db, User, APICall
|
||
|
|
from typing import Final
|
||
|
|
|
||
|
|
API_NAME: Final = "STEAM_API"
|
||
|
|
|
||
|
|
def record_api_call():
|
||
|
|
api_call = APICall.query.filter_by(name=API_NAME).first()
|
||
|
|
if not api_call:
|
||
|
|
api_call = APICall(name=API_NAME)
|
||
|
|
db.session.add(api_call)
|
||
|
|
api_call.register_call()
|
||
|
|
return api_call
|
||
|
|
|
||
|
|
def get_user(steam_id):
|
||
|
|
# 1. Check DB
|
||
|
|
user = User.query.filter_by(steam_id=steam_id).first()
|
||
|
|
if user:
|
||
|
|
app.logger.debug("User fetch from DB")
|
||
|
|
return user
|
||
|
|
|
||
|
|
# 2. Fetch from Steam API
|
||
|
|
url = "https://api.steampowered.com/ISteamUser/GetPlayerSummaries/v2/"
|
||
|
|
params = {"key": app.config['STEAM_API_KEY'], "steamids": steam_id}
|
||
|
|
resp = requests.get(url, params=params)
|
||
|
|
api = record_api_call()
|
||
|
|
data = resp.json()
|
||
|
|
players = data.get("response", {}).get("players", [])
|
||
|
|
if not players:
|
||
|
|
app.logger.debug(f"User not found (API called: {api.call_count})")
|
||
|
|
return None
|
||
|
|
|
||
|
|
player = players[0]
|
||
|
|
|
||
|
|
# 3. Save to DB
|
||
|
|
user = User(
|
||
|
|
steam_id=steam_id,
|
||
|
|
personaname=player.get("personaname"),
|
||
|
|
profile_url=player.get("profileurl"),
|
||
|
|
avatar=player.get("avatar"),
|
||
|
|
avatar_medium=player.get("avatarmedium"),
|
||
|
|
avatar_full=player.get("avatarfull"),
|
||
|
|
community_visibility_state=player.get("communityvisibilitystate"),
|
||
|
|
profile_state=player.get("profilestate"),
|
||
|
|
last_logoff=player.get("lastlogoff")
|
||
|
|
)
|
||
|
|
db.session.add(user)
|
||
|
|
db.session.commit()
|
||
|
|
|
||
|
|
app.logger.debug(f"User fetch from API (API called: {api.call_count})")
|
||
|
|
return user
|