Spaces:
Sleeping

YtFenixS's picture
Update app.py
36a1d2b verified
Raw History Blame Contribute Delete
13.6 kB
"""
app.py ─ Fenix Inventory Tracker Β· FastAPI backend with SQLite Caching & Background tasks
"""
from __future__ import annotations
import os
import time
import json
import random
import asyncio
import sqlite3
from pathlib import Path
from contextlib import asynccontextmanager
from fastapi import FastAPI, HTTPException
from fastapi.responses import FileResponse, JSONResponse
from fastapi.staticfiles import StaticFiles
from pydantic import BaseModel
from playwright.sync_api import sync_playwright, TimeoutError as PlaywrightTimeout
# ─── Config ──────────────────────────────────────────────────────────────────
CNY_TO_USD = 0.14
USER_AGENTS = [
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36",
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
]
DB_FILE = "fenix_bucket.db"
# ─── Database & Background Tasks ─────────────────────────────────────────────
def init_db():
with sqlite3.connect(DB_FILE) as conn:
conn.execute('''CREATE TABLE IF NOT EXISTS profiles (
url TEXT PRIMARY KEY,
status TEXT,
last_checked REAL,
last_changed REAL,
items_json TEXT
)''')
conn.execute('''CREATE TABLE IF NOT EXISTS daily_changes (
id INTEGER PRIMARY KEY AUTOINCREMENT,
url TEXT,
change_time REAL,
total_gained INTEGER,
total_lost INTEGER,
gained_json TEXT,
lost_json TEXT
)''')
def _calculate_diff(old_items, new_items):
old_counts = {}
for item in old_items:
name = item.get('name', 'Unknown')
old_counts[name] = old_counts.get(name, 0) + 1
new_counts = {}
for item in new_items:
name = item.get('name', 'Unknown')
new_counts[name] = new_counts.get(name, 0) + 1
gained = []
lost = []
total_gained = 0
total_lost = 0
all_keys = set(old_counts.keys()).union(set(new_counts.keys()))
for k in all_keys:
diff = new_counts.get(k, 0) - old_counts.get(k, 0)
if diff > 0:
gained.append({"name": k, "amount": diff})
total_gained += diff
elif diff < 0:
lost.append({"name": k, "amount": abs(diff)})
total_lost += abs(diff)
gained = sorted(gained, key=lambda x: x['amount'], reverse=True)
lost = sorted(lost, key=lambda x: x['amount'], reverse=True)
return gained, lost, total_gained, total_lost
def _update_profile_data(resolved_url: str, force: bool = False):
now = time.time()
with sqlite3.connect(DB_FILE) as conn:
c = conn.cursor()
c.execute("SELECT items_json, last_checked, status, last_changed FROM profiles WHERE url=?", (resolved_url,))
row = c.fetchone()
# Tarkistetaan CACHE
if row and not force:
items_json, last_checked, status, last_changed = row
if now - last_checked < 86400:
return json.loads(items_json), True
steamdt_url = f"https://www.steamdt.com/en/inventory/inventory?search={resolved_url}"
raw = _fetch(steamdt_url)
if not raw:
raise RuntimeError("Ei saatu yhteyttΓ€ SteamDT-palveluun tai tili ei ole vielΓ€ ehtinyt latautua.")
new_items = _parse(raw)
new_items_json = json.dumps(new_items)
with sqlite3.connect(DB_FILE) as conn:
if row:
old_items = json.loads(row[0])
last_changed = row[3]
status = row[2]
if new_items_json != row[0]:
gained, lost, tg, tl = _calculate_diff(old_items, new_items)
conn.execute("""INSERT INTO daily_changes
(url, change_time, total_gained, total_lost, gained_json, lost_json)
VALUES (?, ?, ?, ?, ?, ?)""",
(resolved_url, now, tg, tl, json.dumps(gained), json.dumps(lost)))
conn.execute("UPDATE profiles SET status=?, last_checked=?, last_changed=?, items_json=? WHERE url=?",
("active", now, now, new_items_json, resolved_url))
else:
if status == "active" and (now - last_changed > 604800):
conn.execute("UPDATE profiles SET status=?, last_checked=? WHERE url=?", ("maybe dead", now, resolved_url))
elif status == "maybe dead" and (now - last_changed > 1209600):
conn.execute("DELETE FROM profiles WHERE url=?", (resolved_url,))
else:
conn.execute("UPDATE profiles SET last_checked=? WHERE url=?", (now, resolved_url))
else:
conn.execute("INSERT INTO profiles (url, status, last_checked, last_changed, items_json) VALUES (?, ?, ?, ?, ?)",
(resolved_url, "active", now, now, new_items_json))
return new_items, False
def _run_periodic_check():
now = time.time()
with sqlite3.connect(DB_FILE) as conn:
c = conn.cursor()
c.execute("SELECT url, status, last_checked FROM profiles")
rows = c.fetchall()
for row in rows:
url, status, last_checked = row
try:
if status == "active" and (now - last_checked > 86400):
_update_profile_data(url, force=True)
elif status == "maybe dead" and (now - last_checked > 604800):
_update_profile_data(url, force=True)
except Exception as e:
print(f"Background fail for {url}: {e}")
async def background_checker():
while True:
try:
await asyncio.to_thread(_run_periodic_check)
except Exception as e:
print("Background check error:", e)
await asyncio.sleep(3600)
@asynccontextmanager
async def lifespan(app: FastAPI):
init_db()
task = asyncio.create_task(background_checker())
yield
task.cancel()
# ─── FastAPI app ──────────────────────────────────────────────────────────────
app = FastAPI(title="Fenix Inventory API", lifespan=lifespan)
if Path("static").exists():
app.mount("/static", StaticFiles(directory="static"), name="static")
@app.get("/")
def serve_index():
return FileResponse("index.html")
@app.get("/Fenix_red_and_orange.png")
def serve_logo():
if Path("Fenix_red_and_orange.png").exists():
return FileResponse("Fenix_red_and_orange.png", media_type="image/png")
return JSONResponse({"error": "Image not found on server"}, status_code=404)
# ─── Scraping helpers ─────────────────────────────────────────────────────────
def resolve_steam_url(url: str) -> str:
url = url.strip()
# Pakotetaan http alkuun jos uupuu
if not url.startswith("http"):
url = "https://" + url
# Poistetaan turhat parametrit ja kauttaviiva perΓ€stΓ€
url = url.split('?')[0].rstrip('/')
# Jos kÀyttÀjÀ vahingossa liittÀÀ /inventory pÀÀtteen linkkiin
if url.lower().endswith('/inventory'):
url = url[:-10]
return url
def _cny_usd(val) -> float:
return float(val) * CNY_TO_USD if val else 0.0
def _tag(tags: list[str], prefix: str, strip: str = "") -> str:
for t in tags:
if t.startswith(prefix + "#"):
raw = t.split("#", 1)[-1]
return raw.replace(strip, "").replace("_", " ").title()
return "Unknown"
def _parse(api_data: dict) -> list[dict]:
items_list, classinfos = [], {}
block = api_data.get("data", api_data)
# Suojataan tilanne jos data on tyhjΓ€ / null (esim private inventory)
if block is None:
return []
if isinstance(block, dict):
inv = block.get("inventory", {})
if isinstance(inv, dict):
items_list = inv.get("assets", [])
classinfos = inv.get("classinfos", {})
else:
items_list = block.get("inventory", block.get("list", []))
classinfos = block.get("classinfos", {})
elif isinstance(block, list):
items_list = block
classinfos = api_data.get("classinfos", {})
out = []
for item in items_list:
aid = str(item.get("assetId", ""))
if not aid or aid == "None":
continue
info = classinfos.get(str(item.get("classinfoKey", "")), {})
tags = info.get("tags", [])
name = info.get("marketHashName") or info.get("hashName") or f"Unknown ({item.get('classinfoKey','?')})"
price = _cny_usd(item.get("evaluatePrice"))
rarity = _tag(tags, "Rarity", "Rarity_") or "Normal"
quality = _tag(tags, "Quality", "Quality_") or "Normal"
wtype = _tag(tags, "Type", "Type_")
itype = "StatTrak" if "StatTrakβ„’" in name else "Souvenir" if "Souvenir" in name else "Normal"
is_knife = "Knife" in wtype or any(k in name for k in ("β˜…","Karambit","Butterfly","M9 Bayonet"))
is_glove = "Glove" in wtype or "Gloves" in name
out.append({"assetId":aid,"name":name,"price":price,"rarity":rarity,
"quality":quality,"type":itype,"weaponType":wtype,
"isKnife":is_knife,"isGlove":is_glove})
return out
def _fetch(url: str) -> dict | None:
for attempt in range(3):
try:
with sync_playwright() as p:
browser = p.chromium.launch(headless=True, args=[
"--disable-blink-features=AutomationControlled",
"--disable-dev-shm-usage","--no-sandbox",
])
ctx = browser.new_context(user_agent=random.choice(USER_AGENTS),
viewport={"width":1920,"height":1080},locale="en-US")
page = ctx.new_page()
page.route("**/*.{png,jpg,jpeg,gif,svg,webp,woff,woff2}", lambda r: r.abort())
captured = None
def on_response(resp):
nonlocal captured
# Joustavampi tunnistin (Varmistaa ettΓ€ osuu SteamDT Inventory APIin)
if "app_id=730" in resp.url and "inventory" in resp.url and resp.request.method != "OPTIONS":
try:
if resp.status == 200:
json_data = resp.json()
if "data" in json_data:
captured = json_data
except Exception:
pass
page.on("response", on_response)
page.goto(url, wait_until="domcontentloaded", timeout=60_000)
for _ in range(60):
if captured: break
page.wait_for_timeout(500)
browser.close()
if captured:
return captured
except PlaywrightTimeout:
pass
except Exception as e:
print(f"Attempt {attempt+1} error: {e}")
time.sleep(2)
return None
# ─── API endpoints ────────────────────────────────────────────────────────────
class ScrapeRequest(BaseModel):
steam_url: str
force: bool = False
@app.post("/api/scrape")
def scrape(req: ScrapeRequest):
if "steamcommunity.com" not in req.steam_url:
raise HTTPException(400, "Viallinen linkki. Linkin pitÀÀ sisÀltÀÀ 'steamcommunity.com'")
# Nyt url putsataan puhtaasti stringinΓ€, ei yritetΓ€ muuntaa ID:tΓ€!
resolved_url = resolve_steam_url(req.steam_url)
try:
items, cached = _update_profile_data(resolved_url, force=req.force)
except Exception as e:
raise HTTPException(502, f"Datan haku epΓ€onnistui: {e}")
if not items:
raise HTTPException(404, "Inventaariosta ei lΓΆytynyt CS2-esineitΓ€, tili on yksityinen tai SteamDT ei ole vielΓ€ indeksoinut niitΓ€.")
return JSONResponse({"items": items, "count": len(items), "resolved_url": resolved_url, "cached": cached})
@app.get("/api/recent_changes")
def get_recent_changes():
with sqlite3.connect(DB_FILE) as conn:
c = conn.cursor()
c.execute("""SELECT url, change_time, total_gained, total_lost, gained_json, lost_json
FROM daily_changes
ORDER BY change_time DESC LIMIT 100""")
rows = c.fetchall()
res = []
for r in rows:
res.append({
"url": r[0], "time": r[1],
"total_gained": r[2], "total_lost": r[3],
"gained": json.loads(r[4] or "[]"),
"lost": json.loads(r[5] or "[]")
})
return JSONResponse({"changes": res})