Spaces:
Sleeping
Sleeping
File size: 13,621 Bytes
ddf2b36 3683337 ddf2b36 3683337 ddf2b36 3683337 ddf2b36 3683337 ddf2b36 3683337 c9a81f9 3683337 c9a81f9 3683337 c9a81f9 3683337 c9a81f9 3683337 c9a81f9 3683337 c9a81f9 3683337 36a1d2b c9a81f9 36a1d2b c9a81f9 36a1d2b c9a81f9 36a1d2b c9a81f9 36a1d2b c9a81f9 36a1d2b c9a81f9 3683337 c9a81f9 3683337 ddf2b36 3683337 ddf2b36 3683337 ddf2b36 3683337 36a1d2b 3683337 36a1d2b 3683337 ddf2b36 36a1d2b ddf2b36 36a1d2b ddf2b36 36a1d2b ddf2b36 3683337 36a1d2b ddf2b36 3683337 ddf2b36 c9a81f9 ddf2b36 36a1d2b 3683337 36a1d2b 3683337 c9a81f9 36a1d2b c9a81f9 ddf2b36 36a1d2b 3683337 c9a81f9 3683337 c9a81f9 3683337 c9a81f9 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 | """
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}) |