102 lines
3.4 KiB
Python
102 lines
3.4 KiB
Python
from flask import Flask, request, jsonify
|
|
from flask_cors import CORS
|
|
import json
|
|
import re
|
|
from datetime import datetime
|
|
from goldeval import goldeval # ⬅️ Add this at the top
|
|
|
|
app = Flask(__name__)
|
|
CORS(app)
|
|
|
|
def sanitize_filename(name):
|
|
"""Remove unsafe characters from filename."""
|
|
safe = re.sub(r'[\/:*?"<>|]', '', name)
|
|
return safe[:50] if len(safe) > 50 else safe
|
|
|
|
def save_payload_as_player_file(payload):
|
|
"""Save payload to a file named after the player, overwriting if exists."""
|
|
try:
|
|
player_name = payload.get("player", "default_player")
|
|
filename = sanitize_filename(player_name) + ".json"
|
|
|
|
with open(filename, "w", encoding="utf-8") as f:
|
|
json.dump(payload, f, ensure_ascii=False, indent=2)
|
|
|
|
print(f"📝 Payload saved to {filename}")
|
|
except Exception as e:
|
|
print("❌ Failed to save payload:", e)
|
|
goldeval(filename)
|
|
|
|
def append_prices_log(payload):
|
|
"""Append resource prices and market title to prices.txt in CSV format with timestamp."""
|
|
try:
|
|
market = payload.get("gold_market")
|
|
title = payload.get("gold_market_title", "").strip()
|
|
|
|
# Skip if title is missing, empty, or placeholder
|
|
if not title or title.lower() in ["unknown title", "n/a", "null"]:
|
|
print("⏭️ Skipping log: Missing or placeholder title")
|
|
return
|
|
|
|
# Skip if market is missing
|
|
if not market:
|
|
print("⏭️ Skipping log: Missing market data")
|
|
return
|
|
|
|
# Extract and sanitize values
|
|
wood = market.get("wood", {}).get("current", "").replace(",", "")
|
|
stone = market.get("stone", {}).get("current", "").replace(",", "")
|
|
iron = market.get("iron", {}).get("current", "").replace(",", "")
|
|
|
|
# Skip if all values are missing or zero
|
|
if not wood or not stone or not iron or (wood == "0" and stone == "0" and iron == "0"):
|
|
print("⏭️ Skipping log: Market values are empty or zero")
|
|
return
|
|
|
|
timestamp = datetime.now().isoformat()
|
|
safe_title = title.replace('"', "'")
|
|
|
|
line = f'{timestamp},{wood},{stone},{iron},"{safe_title}"\n'
|
|
|
|
with open("prices.txt", "a", encoding="utf-8") as f:
|
|
f.write(line)
|
|
|
|
print("📈 Appended to prices.txt:", line.strip())
|
|
except Exception as log_err:
|
|
print("⚠️ Failed to log to prices.txt:", log_err)
|
|
|
|
@app.route('/api/grepolis-data', methods=['POST'])
|
|
def receive_data():
|
|
print("\n📬 New request to /api/grepolis-data")
|
|
|
|
try:
|
|
payload = request.get_json(force=True)
|
|
print("✅ Parsed JSON:", payload)
|
|
|
|
# Inject server-side timestamp
|
|
payload["server_received_at"] = datetime.now().isoformat()
|
|
|
|
save_payload_as_player_file(payload)
|
|
append_prices_log(payload)
|
|
|
|
return jsonify({
|
|
"status": "success",
|
|
"message": "Grepolis data received and saved",
|
|
"server_received_at": payload["server_received_at"]
|
|
}), 200
|
|
|
|
except Exception as e:
|
|
print("❌ JSON parse error:", e)
|
|
return jsonify({
|
|
"status": "error",
|
|
"message": f"Invalid JSON: {str(e)}"
|
|
}), 400
|
|
|
|
@app.errorhandler(Exception)
|
|
def handle_error(e):
|
|
print("💥 Unhandled server error:", e)
|
|
return jsonify({"error": str(e)}), 500
|
|
|
|
if __name__ == '__main__':
|
|
app.run(host='0.0.0.0', port=5000)
|