Upload files to "routes"

This commit is contained in:
2026-07-24 15:35:19 +00:00
parent 40f106fd51
commit c128e582ab
5 changed files with 1417 additions and 0 deletions

540
routes/avatar.py Normal file
View File

@@ -0,0 +1,540 @@
import json
import os
import re
import random
_GUID_RE = re.compile(
r'^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}',
re.IGNORECASE,
)
from flask import Blueprint, request, jsonify, Response
from core.auth import check_auth, get_current_profile_id
from core.limiter import limiter
from core.ws_helpers import push_profile_update, push_presence, push_consumable_added, push_consumable_removed, push_store_balance
from core.state import db, session_mgr
bp = Blueprint("avatar", __name__)
import threading as _threading
_gift_gen_locks: dict[int, _threading.Lock] = {}
_gift_gen_locks_lock = _threading.Lock()
def _get_gift_gen_lock(pid: int) -> _threading.Lock:
with _gift_gen_locks_lock:
if pid not in _gift_gen_locks:
_gift_gen_locks[pid] = _threading.Lock()
return _gift_gen_locks[pid]
_raw_items_cache = None
def _get_raw_items():
global _raw_items_cache
if _raw_items_cache is None:
_reload_items_cache()
return _raw_items_cache
def _reload_items_cache():
global _raw_items_cache, _level_map_cache, _activity_pool_cache, _rarity_map_cache, _custom_starter_guids, _always_ok_guids_cache
_always_ok_guids_cache = None
data_dir = os.path.join(os.path.dirname(__file__), "..", "data")
try:
with open(os.path.join(data_dir, "avataritems.json"), encoding="utf-8") as f:
raw = json.load(f)
except Exception as exc:
print(f"[Avatar] Could not load avataritems.json: {exc}")
raw = []
try:
with open(os.path.join(data_dir, "custom_swatches.json"), encoding="utf-8") as f:
custom_swatches = json.load(f)
except Exception:
custom_swatches = []
try:
with open(os.path.join(data_dir, "custom_items.json"), encoding="utf-8") as f:
custom_items = json.load(f)
except Exception:
custom_items = []
_custom_starter_guids = {
i["AvatarItemDesc"].split(",")[0]
for i in custom_items
if i.get("Starter") and i.get("AvatarItemDesc")
}
normalized = []
for i in raw + custom_swatches:
desc = i.get("AvatarItemDesc", "")
if not desc or not _GUID_RE.match(desc.split(",")[0]):
continue
if "," not in desc:
i = dict(i, AvatarItemDesc=desc + ",,,")
normalized.append(i)
for i in custom_items:
desc = i.get("AvatarItemDesc", "")
if not desc:
continue
if "," not in desc:
i = dict(i, AvatarItemDesc=desc + ",,,")
normalized.append(i)
_raw_items_cache = normalized
_level_map_cache = None
_activity_pool_cache = {}
_rarity_map_cache = None
print(f"[Avatar] Loaded {len(raw)} base + {len(custom_swatches)} swatches + {len(custom_items)} custom items ({len(_custom_starter_guids)} custom starters)")
def _get_avatar_items():
return _get_raw_items()
def _load_avatar_config():
cfg_path = os.path.join(os.path.dirname(__file__), "..", "data", "avatar_config.json")
with open(cfg_path, encoding="utf-8") as f:
return json.load(f)
_avatar_cfg = _load_avatar_config()
_STARTER_ITEM_GUIDS = set(_avatar_cfg["starter_item_guids"])
_custom_starter_guids = set()
def _all_starter_guids():
return _STARTER_ITEM_GUIDS | _custom_starter_guids
_RARE_ITEM_GUIDS = set(_avatar_cfg["rare_item_guids"])
_EPIC_BODY_GUIDS = set(_avatar_cfg["epic_body_guids"])
_RARE_BODY_GUIDS = set(_avatar_cfg["rare_body_guids"])
def _item_rarity(item):
guid = item.get("AvatarItemDesc", "").split(",")[0]
if guid in _EPIC_BODY_GUIDS:
return 3
if guid in _RARE_BODY_GUIDS:
return 2
return random.Random(guid).choice([0, 0, 0, 1, 1])
_rarity_map_cache = None
def _get_rarity_buckets():
global _rarity_map_cache
if _rarity_map_cache is not None:
return _rarity_map_cache
buckets = {0: [], 1: [], 2: [], 3: []}
for item in _get_raw_items():
r = _item_rarity(item)
buckets[r].append(item)
_rarity_map_cache = buckets
return buckets
_equipment_cache = None
def _get_equipment():
global _equipment_cache
if _equipment_cache is not None:
return _equipment_cache
data_dir = os.path.join(os.path.dirname(__file__), "..", "data")
try:
with open(os.path.join(data_dir, "equipment.json"), encoding="utf-8") as f:
raw = json.load(f)
except Exception:
raw = []
_equipment_cache = [e for e in raw if e.get("ModificationGuid")]
return _equipment_cache
_EQUIPMENT_ACTIVITY_MAP = _avatar_cfg["equipment_activity_map"]
_level_map_cache = None
def _get_level_map():
global _level_map_cache
if _level_map_cache is not None:
return _level_map_cache
all_items = _get_raw_items()
seen = set()
non_starter = []
for item in all_items:
guid = item["AvatarItemDesc"].split(",")[0]
if guid not in seen and guid not in _all_starter_guids():
seen.add(guid)
non_starter.append(guid)
non_starter.sort()
total = len(non_starter)
t1 = total // 4
t2 = total // 2
t3 = 3 * total // 4
guid_levels = {}
for i, guid in enumerate(non_starter):
if guid in _RARE_ITEM_GUIDS:
guid_levels[guid] = 22
elif i < t1:
guid_levels[guid] = 3
elif i < t2:
guid_levels[guid] = 8
elif i < t3:
guid_levels[guid] = 15
else:
guid_levels[guid] = 22
for guid in _all_starter_guids():
guid_levels[guid] = 1
result = {}
for item in all_items:
desc = item["AvatarItemDesc"]
guid = desc.split(",")[0]
result[desc] = guid_levels.get(guid, 22)
_level_map_cache = result
return result
_HAIR_KEYWORDS = {
"hair", "ponytail", "braid", "bun", "afro", "dreadlock", "mohawk",
"bangs", "pigtail", "bob", "curly", "wavy", "updo", "twintail",
}
_QUEST_CONSUMABLES = _avatar_cfg["quest_consumables"]
_FOOD_CONSUMABLES = _avatar_cfg["food_consumables"]
_ACTIVITY_POOLS = {
"3d474b26-26f7-45e9-9a36-9b02847d5e6f": [
"paintball", "boxer", "scout", "viking", "warrior",
],
"6d5eea4b-f069-4ed0-9916-0e2f07df0d03": [
"soccer", "field hockey", "football", "tennis", "cheer",
],
"cbad71af-0831-44d8-b8ef-69edafa841f6": [
"business", "tee", "t shirt", "sherlock", "marty", "aviator",
],
}
_activity_pool_cache = {}
_always_ok_guids_cache = None
def _get_always_ok_guids():
global _always_ok_guids_cache
if _always_ok_guids_cache is not None:
return _always_ok_guids_cache
result = set(_all_starter_guids())
for item in _get_raw_items():
name = item.get("FriendlyName", "").lower()
if any(kw in name for kw in _HAIR_KEYWORDS):
result.add(item["AvatarItemDesc"].split(",")[0])
_always_ok_guids_cache = result
return result
def _filter_outfit_selections(outfit_str, owned):
if not outfit_str:
return outfit_str
always_ok = _get_always_ok_guids()
kept = []
for entry in outfit_str.split(";"):
if not entry:
continue
guid = entry.split(",")[0]
if guid in always_ok or guid in owned:
kept.append(entry)
return ";".join(kept)
def _get_activity_item_pool(activity_guid):
if activity_guid in _activity_pool_cache:
return _activity_pool_cache[activity_guid]
all_items = _get_raw_items()
keywords = _ACTIVITY_POOLS.get(activity_guid)
if not keywords:
_activity_pool_cache[activity_guid] = all_items
return all_items
filtered = [
i for i in all_items
if any(kw in i.get("FriendlyName", "").lower() for kw in keywords)
]
pool = filtered if filtered else all_items
_activity_pool_cache[activity_guid] = pool
return pool
def _seed_starter_unlocks(profile_id, all_items):
db.migrate_unlocks_from_gifts(profile_id)
starter_descs = [
i["AvatarItemDesc"] for i in all_items
if i["AvatarItemDesc"].split(",")[0] in _all_starter_guids()
]
db.unlock_avatar_items(profile_id, starter_descs)
_CURRENCY_REC_CENTER_TOKENS = 2
_RARITY_WIRE = {0: 0, 1: 10, 2: 20, 3: 30, 4: 50}
def _is_owned(desc, owned):
return desc in owned or desc.split(",")[0] in owned
def _pick_equipment(activity_guid, profile_id):
all_equip = _get_equipment()
if not all_equip:
return None
prefab_keywords = _EQUIPMENT_ACTIVITY_MAP.get(activity_guid)
if prefab_keywords:
pool = [e for e in all_equip if any(kw in e["PrefabName"] for kw in prefab_keywords)]
else:
pool = all_equip
owned_guids = set()
if profile_id:
conn = db._get_conn()
rows = conn.execute(
"SELECT equipment_modification_guid FROM gifts WHERE profile_id = ? AND equipment_modification_guid != ''",
(profile_id,),
).fetchall()
owned_guids = {r["equipment_modification_guid"] for r in rows}
unowned = [e for e in pool if e["ModificationGuid"] not in owned_guids]
if not unowned:
unowned = [e for e in all_equip if e["ModificationGuid"] not in owned_guids]
return random.choice(unowned) if unowned else None
def _generate_gift_for_player(profile_id, activity_guid=None, xp=None, gift_context=2):
with _get_gift_gen_lock(profile_id):
return _generate_gift_for_player_locked(profile_id, activity_guid, xp, gift_context)
def _generate_gift_for_player_locked(profile_id, activity_guid=None, xp=None, gift_context=2):
from core.constants import xp_to_level, get_activity_base_xp
if xp is None:
lo, hi = get_activity_base_xp(activity_guid)
xp = random.randint(lo, hi) if hi > 0 else random.randint(50, 150)
rarity = random.choices([0, 1, 2, 3, 4], weights=[54, 29, 12, 4, 1])[0]
profile = db.get_profile(profile_id) if profile_id else None
current_xp = profile.get("XP", 0) if profile else 0
projected_level = xp_to_level(current_xp + xp)
if random.random() < 0.25:
token_amount = random.choice([50, 100, 150, 200, 250])
gift = db.add_gift(
profile_id,
xp=xp,
gift_rarity=_RARITY_WIRE[rarity],
currency_type=_CURRENCY_REC_CENTER_TOKENS,
currency=token_amount,
gift_context=gift_context,
level=projected_level,
)
return gift
if random.random() < 0.20 and activity_guid:
equip = _pick_equipment(activity_guid, profile_id)
if equip:
gift = db.add_gift(
profile_id,
xp=xp,
gift_rarity=_RARITY_WIRE[rarity],
equipment_prefab_name=equip["PrefabName"],
equipment_modification_guid=equip["ModificationGuid"],
gift_context=gift_context,
level=projected_level,
)
return gift
consumable = ""
owned = db.get_unlocked_items(profile_id) if profile_id else set()
for pending in (db.get_pending_gifts(profile_id) if profile_id else []):
desc = pending.get("AvatarItemDesc", "")
if desc:
owned.add(desc)
owned.add(desc.split(",")[0])
buckets = _get_rarity_buckets()
activity_pool = _get_activity_item_pool(activity_guid)
def _eligible(i):
desc = i["AvatarItemDesc"]
guid = desc.split(",")[0]
return (not guid.startswith("sdk_")
and guid not in _all_starter_guids()
and not _is_owned(desc, owned))
pool = [i for i in activity_pool if _item_rarity(i) == rarity and _eligible(i)]
if not pool:
pool = [i for i in buckets.get(rarity, []) if _eligible(i)]
if not pool:
pool = [i for i in activity_pool if _eligible(i)]
if not pool:
all_items = _get_raw_items()
pool = [i for i in all_items if _eligible(i)]
item = random.choice(pool) if pool else None
gift = db.add_gift(
profile_id,
xp=xp,
gift_rarity=_RARITY_WIRE[rarity],
avatar_item_desc=item["AvatarItemDesc"] if item else "",
consumable_item_desc=consumable,
gift_context=gift_context,
level=projected_level,
)
return gift
@bp.route("/api/avatar/v2", methods=["GET"])
@check_auth
def get_avatar():
pid = get_current_profile_id()
avatar = db.get_avatar(pid)
if pid and avatar.get("OutfitSelections"):
owned = db.get_unlocked_items(pid)
avatar["OutfitSelections"] = _filter_outfit_selections(avatar["OutfitSelections"], owned)
return jsonify(avatar)
@bp.route("/api/avatar/v2/set", methods=["POST"])
@check_auth
def set_avatar():
pid = get_current_profile_id()
data = request.get_json(force=True, silent=True) or {}
db.set_avatar(pid, data)
push_profile_update(pid)
push_presence(pid, session_mgr.get_player_session(pid))
return jsonify(db.get_avatar(pid))
@bp.route("/api/avatar/v3/items", methods=["GET"])
@check_auth
def get_avatar_items():
pid = get_current_profile_id()
raw = _get_raw_items()
if not db.has_unlocked_items(pid):
_seed_starter_unlocks(pid, raw)
unlocked = db.get_unlocked_items(pid)
result = []
for i in raw:
desc = i["AvatarItemDesc"]
name = i.get("FriendlyName", "").lower()
is_hair = any(kw in name for kw in _HAIR_KEYWORDS)
is_starter = desc.split(",")[0] in _all_starter_guids()
if is_hair or is_starter or _is_owned(desc, unlocked):
result.append({"AvatarItemDesc": desc, "UnlockedLevel": 1})
return jsonify(result)
@bp.route("/api/avatar/v1/saved", methods=["GET"])
@bp.route("/api/avatar/v2/saved", methods=["GET"])
@bp.route("/api/avatar/v3/saved", methods=["GET"])
@check_auth
def get_saved_outfits():
pid = get_current_profile_id()
if not pid:
return jsonify([])
outfits = db.get_saved_outfits(pid)
owned = db.get_unlocked_items(pid)
for outfit in outfits:
if outfit.get("OutfitSelections"):
outfit["OutfitSelections"] = _filter_outfit_selections(outfit["OutfitSelections"], owned)
return jsonify(outfits)
@bp.route("/api/avatar/v1/saved/set", methods=["POST"])
@bp.route("/api/avatar/v2/saved/set", methods=["POST"])
@bp.route("/api/avatar/v3/saved/set", methods=["POST"])
@check_auth
def set_saved_outfit():
pid = get_current_profile_id()
if not pid:
return jsonify({})
data = request.get_json(force=True, silent=True) or {}
slot = int(data.get("Slot", 0))
preview_image_name = str(data.get("PreviewImageName", ""))
outfit_selections = str(data.get("OutfitSelections", ""))
hair_color = str(data.get("HairColor", ""))
skin_color = str(data.get("SkinColor", ""))
face_features = str(data.get("FaceFeatures", ""))
db.save_outfit(pid, slot, preview_image_name, outfit_selections, hair_color, skin_color, face_features)
return jsonify({
"Slot": slot,
"PreviewImageName": preview_image_name,
"OutfitSelections": outfit_selections,
"HairColor": hair_color,
"SkinColor": skin_color,
"FaceFeatures": face_features,
})
@bp.route("/api/avatar/v2/gifts", methods=["GET"])
@check_auth
def get_gifts():
pid = get_current_profile_id()
gifts = db.get_pending_gifts(pid) if pid else []
return jsonify(gifts)
@bp.route("/api/avatar/v2/gifts/generate", methods=["POST"])
@check_auth
@limiter.limit("5 per 5 minutes")
def generate_gift():
pid = get_current_profile_id()
if not pid:
return jsonify({})
from core.gift_dispatch import dispatch_gift
session = session_mgr.get_player_session(pid)
if not session:
print(f"[Gifts] Rejected generate for pid={pid}: not in a session")
return jsonify({})
activity_guid = getattr(session, "activity_level_id", None) if session else None
gift_context = request.values.get("GiftContext", type=int, default=2)
gift = dispatch_gift(pid, activity_guid, gift_context=gift_context)
if gift is None:
return jsonify({})
db.mark_gift_pushed(gift["Id"])
return jsonify(gift)
@bp.route("/api/avatar/v2/gifts/consume/", methods=["POST"])
@bp.route("/api/avatar/v2/gifts/consume/<int:gift_id>", methods=["POST"])
@check_auth
def consume_gift(gift_id=None):
pid = get_current_profile_id()
if not pid:
return Response("Unauthorized", 401)
if not session_mgr.get_player_session(pid):
print(f"[Gifts] Rejected consume for pid={pid}: not in a session")
return Response("OK", 200)
if gift_id is None:
try:
_body = request.get_json(force=True, silent=True) or {}
gift_id = int(_body.get("Id") or request.values.get("Id") or 0)
except (ValueError, TypeError):
gift_id = 0
if not gift_id:
return Response("OK", 200)
owned = db.get_unlocked_items(pid)
gift = db.consume_gift(gift_id, pid)
if gift is None:
return Response("OK", 200)
if gift.get("AvatarItemDesc"):
if _is_owned(gift["AvatarItemDesc"], owned):
pool = [i for i in _get_raw_items()
if not _is_owned(i["AvatarItemDesc"], owned)
and i["AvatarItemDesc"].split(",")[0] not in _all_starter_guids()]
if pool:
import random as _rnd
replacement = _rnd.choice(pool)
gift["AvatarItemDesc"] = replacement["AvatarItemDesc"]
db.update_gift_item(gift_id, replacement["AvatarItemDesc"])
db.unlock_avatar_item(pid, gift["AvatarItemDesc"])
print(f"[Gifts] Player {pid} consumed gift {gift_id} (xp={gift['Xp']}, "
f"item={gift['AvatarItemDesc'][:30] if gift['AvatarItemDesc'] else 'none'}, "
f"tokens={gift['Currency'] if gift['CurrencyType'] == 2 else 0})")
if gift.get("ConsumableItemDesc"):
db.add_consumable(pid, gift["ConsumableItemDesc"], 1)
row = db.get_consumable_by_desc(pid, gift["ConsumableItemDesc"])
if row:
push_consumable_removed(pid, row)
push_consumable_added(pid, row)
if gift["CurrencyType"] == 2 and gift["Currency"] > 0:
new_balance = db.get_tokens(pid)
push_store_balance(pid, new_balance, 2, gift["Currency"])
if gift["Xp"] > 0 or (gift["CurrencyType"] == 2 and gift["Currency"] > 0):
push_profile_update(pid)
return Response("OK", 200)