-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapp.py
More file actions
8408 lines (7402 loc) · 299 KB
/
app.py
File metadata and controls
8408 lines (7402 loc) · 299 KB
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
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
SkyModderAI - Mod Compatibility Checker
Main Flask application with improved security, error handling, and Stripe integration.
"""
from __future__ import annotations
import hashlib
import html
import json
import logging
import os
import re
import secrets
import smtplib
import sqlite3
from collections import OrderedDict
from datetime import datetime, timedelta, timezone
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from functools import wraps
from time import time as _time
from typing import Any, Optional
from urllib.parse import quote, urlencode, urljoin, urlparse
import requests
from flask import (
Flask,
Response,
g,
jsonify,
make_response,
redirect,
render_template,
request,
send_from_directory,
session,
url_for,
)
from itsdangerous import URLSafeTimedSerializer
from werkzeug.middleware.proxy_fix import ProxyFix
from werkzeug.security import check_password_hash, generate_password_hash
# Local modules
from community_builds import (
get_community_builds_service,
)
from config import config
from conflict_detector import ConflictDetector, parse_mod_list_text
# Shared constants - imported from constants.py
from constants import (
MAX_INPUT_SIZE,
PLUGIN_LIMIT,
PLUGIN_LIMIT_WARN_THRESHOLD,
RATE_LIMIT_ANALYZE,
RATE_LIMIT_API,
RATE_LIMIT_SEARCH,
)
from deterministic_analysis import (
analyze_load_order_deterministic,
generate_bespoke_setups_deterministic,
scan_game_folder_deterministic,
)
from knowledge_index import (
build_ai_context as build_knowledge_context,
)
from knowledge_index import (
format_knowledge_for_ai,
get_game_resources,
get_resolution_for_conflict,
)
from list_builder import build_list_from_preferences, get_preference_options
# Logging utilities
from logging_utils import (
RequestLoggingMiddleware,
SensitiveDataFilter,
setup_logging,
)
from loot_parser import LOOTParser
from mod_recommendations import get_loot_based_suggestions
from mod_warnings import get_mod_warnings
from openclaw_engine import (
OPENCLAW_PERMISSION_SCOPES,
build_openclaw_plan,
suggest_loop_adjustments,
)
from result_consolidator import consolidate_conflicts
from search_engine import get_search_engine
# Security utilities
from security_utils import (
RateLimiter,
rate_limit,
validate_email,
validate_game_id,
validate_list_name,
validate_mod_list,
validate_search_query,
)
from system_impact import (
format_system_impact_for_ai,
format_system_impact_report,
get_system_impact,
)
from transparency_service import complete_analysis, start_analysis
from walkthrough_manager import WalkthroughManager
# -------------------------------------------------------------------
# Game Version Helpers (Replaces game_versions.py dependency)
# -------------------------------------------------------------------
_GAME_VERSIONS_CACHE = None
def _load_game_versions_data() -> dict[str, Any]:
"""Load game versions from JSON file."""
global _GAME_VERSIONS_CACHE
if _GAME_VERSIONS_CACHE is not None:
return _GAME_VERSIONS_CACHE
path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "data", "game_versions.json")
try:
with open(path) as f:
_GAME_VERSIONS_CACHE = json.load(f)
return _GAME_VERSIONS_CACHE # type: ignore[no-any-return]
except Exception as e:
logger.error(f"Failed to load game versions: {e}")
return {}
def get_versions_for_game(game_id: str) -> dict[str, Any]:
"""Get all versions for a specific game."""
data = _load_game_versions_data()
return data.get(game_id, {}).get("versions", {})
def get_default_version(game_id: str) -> str:
"""Get the default version for a specific game."""
data = _load_game_versions_data()
return data.get(game_id, {}).get("default", "")
def get_version_info(game_id: str, version: str) -> Optional[dict[str, Any]]:
"""Get version information for a specific game and version."""
versions = get_versions_for_game(game_id)
return versions.get(version)
def get_version_warning(game_id: str, version: str) -> Optional[dict[str, str]]:
"""Get version warning if applicable."""
info = get_version_info(game_id, version)
if info and info.get("warning"):
return {"message": info["warning"], "link": info.get("warning_link")}
return None
# -------------------------------------------------------------------
# PII redaction for logs (never log emails, tokens, or customer data)
# -------------------------------------------------------------------
def _redact_email(email: Optional[str]) -> str:
"""Redact email for safe logging. Returns e.g. 'u***@***'."""
if not email or not isinstance(email, str):
return "***"
e = email.strip().lower()
if "@" not in e:
return "***"
local, domain = e.split("@", 1)
if len(local) <= 1:
return "*@***"
return f"{local[0]}***@{domain[0]}***"
# -------------------------------------------------------------------
# Configuration and logging
# -------------------------------------------------------------------
# Setup enhanced logging with PII redaction and structured formatting
logger = setup_logging(
level=logging.INFO,
log_file=os.getenv("LOG_FILE", "app.log"),
enable_structured=config.FLASK_ENV == "production",
)
logger.info("SkyModderAI starting up...")
logger.info(f"Environment: {config.FLASK_ENV}")
logger.info(
f"Database: {'PostgreSQL' if config.SQLALCHEMY_DATABASE_URI.startswith('postgresql') else 'SQLite'}"
)
# Initialize global rate limiter
_app_rate_limiter = RateLimiter()
# Stripe integration
STRIPE_AVAILABLE = False
if config.PAYMENTS_ENABLED:
try:
import stripe
stripe.api_key = config.STRIPE_SECRET_KEY
if config.STRIPE_WEBHOOK_SECRET:
logger.info("Stripe payments enabled with webhook verification")
else:
logger.warning("Stripe webhook secret not set - webhook verification disabled")
STRIPE_AVAILABLE = True
except ImportError:
logger.warning("Stripe module not installed. Payment features disabled.")
STRIPE_AVAILABLE = False
# AI: key from env only, never in code
try:
import openai
OPENAI_AVAILABLE = True
except ImportError:
OPENAI_AVAILABLE = False
# Flexible LLM Configuration (OpenAI, Qwen, LocalAI, etc.)
LLM_API_KEY = (
os.environ.get("LLM_API_KEY")
or os.environ.get("OPENAI_API_KEY")
or os.environ.get("OPEN_AI_KEY", "").strip()
)
LLM_BASE_URL = os.environ.get(
"LLM_BASE_URL"
) # e.g. https://dashscope.aliyuncs.com/compatible-mode/v1
LLM_MODEL = os.environ.get("LLM_MODEL") or os.environ.get("OPENAI_CHAT_MODEL", "gpt-4o-mini")
AI_CHAT_ENABLED = OPENAI_AVAILABLE and bool(LLM_API_KEY)
if OPENAI_AVAILABLE and not LLM_API_KEY:
logger.info("LLM_API_KEY not set; AI chat disabled")
# -------------------------------------------------------------------
# Validation Utilities for API Robustness
# -------------------------------------------------------------------
def validate_game_id(game_id: str) -> str:
"""Validate and normalize game ID."""
if not game_id or not isinstance(game_id, str):
raise ValueError("Game ID is required and must be a string")
game_id = game_id.strip().lower()
allowed_games = {g["id"] for g in SUPPORTED_GAMES}
if game_id not in allowed_games:
raise ValueError(f"Invalid game ID. Must be one of: {', '.join(sorted(allowed_games))}")
return game_id
def validate_limit(limit: str, default: int = 10, max_allowed: int = 50) -> int:
"""Validate and sanitize limit parameter."""
try:
if limit is None:
return default
limit_int = int(limit)
if limit_int < 1:
return 1
if limit_int > max_allowed:
return max_allowed
return limit_int
except (TypeError, ValueError):
return default
def validate_search_query(query: str) -> str:
"""Validate and sanitize search query."""
if not query:
raise ValueError("Search query is required")
query = str(query).strip()
if len(query) < 1:
raise ValueError("Search query must be at least 1 character")
if len(query) > 200:
raise ValueError("Search query too long (max 200 characters)")
# Remove potentially harmful characters
query = re.sub(r'[<>"\']', "", query)
return query
def validate_mod_list(mod_list: str) -> str:
"""Validate mod list input."""
if not mod_list:
raise ValueError("Mod list is required")
mod_list = str(mod_list).strip()
if len(mod_list) > 100000: # 100KB limit
raise ValueError("Mod list too large (max 100KB)")
return mod_list
def validate_email(email: str) -> str:
"""Basic email validation."""
if not email:
raise ValueError("Email is required")
email = str(email).strip().lower()
if not re.match(r"^[^@]+@[^@]+\.[^@]+$", email):
raise ValueError("Invalid email format")
return email
def validate_list_name(name: str) -> str:
"""Validate saved list name."""
if not name:
raise ValueError("List name is required")
name = str(name).strip()
if len(name) < 1:
raise ValueError("List name cannot be empty")
if len(name) > 100:
raise ValueError("List name too long (max 100 characters)")
# Remove potentially harmful characters
name = re.sub(r'[<>"\']', "", name)
return name
def api_error(message: str, status_code: int = 400, details: dict = None):
"""Standardized API error response."""
response = {
"success": False,
"error": message,
"timestamp": datetime.now(timezone.utc).isoformat(),
}
if details:
response["details"] = details
return jsonify(response), status_code
def api_success(data: dict = None, message: str = None):
"""Standardized API success response."""
response = {
"success": True,
"timestamp": datetime.now(timezone.utc).isoformat(),
}
if data:
response.update(data)
if message:
response["message"] = message
return jsonify(response)
app = Flask(__name__)
# Add request logging middleware for structured request tracing (BEFORE ProxyFix)
request_logging = RequestLoggingMiddleware(app, logger=logger)
app.wsgi_app = request_logging
# ProxyFix must be applied AFTER other middleware
app.wsgi_app = ProxyFix(app.wsgi_app, x_for=1, x_proto=1, x_host=1) # Trust reverse proxy headers
# Gzip compression for faster responses (2025 best practice)
try:
from flask_compress import Compress
Compress(app)
except ImportError:
pass # Graceful fallback if Flask-Compress not installed
# Add sensitive data filter to all log handlers
for handler in logger.handlers:
handler.addFilter(SensitiveDataFilter())
# Security settings
app.config.update(
SECRET_KEY=config.SECRET_KEY,
SESSION_COOKIE_SECURE=config.SESSION_COOKIE_SECURE,
SESSION_COOKIE_HTTPONLY=config.SESSION_COOKIE_HTTPONLY,
SESSION_COOKIE_SAMESITE=config.SESSION_COOKIE_SAMESITE,
PERMANENT_SESSION_LIFETIME=86400, # 24 hours
REMEMBER_COOKIE_DURATION=86400 * 30, # 30 days
)
# Production-specific session configuration (fixes OAuth 500 errors)
if os.environ.get("FLASK_ENV") == "production":
app.config["SESSION_COOKIE_SECURE"] = True
app.config["SESSION_COOKIE_SAMESITE"] = "Lax" # NOT 'Strict' — breaks OAuth redirects
app.config["SESSION_COOKIE_HTTPONLY"] = True
app.config["PERMANENT_SESSION_LIFETIME"] = timedelta(days=30)
# Initialize database connection for each request (required for db.py get_db())
@app.before_request
def init_db_connection():
"""Initialize database connection for the request."""
from flask import g
if "db" not in g:
import sqlite3
g.db = sqlite3.connect(DB_FILE)
g.db.row_factory = sqlite3.Row
# Data file check on startup (Priority 4B)
@app.before_request
def check_data_ready():
if not hasattr(app, "_data_checked"):
app._data_checked = True
import glob
data_files = glob.glob("data/*_mod_database.json")
if not data_files:
# Trigger async data download
import threading
from loot_parser import bootstrap_loot_data
t = threading.Thread(target=bootstrap_loot_data, daemon=True)
t.start()
app._data_loading = True
else:
app._data_loading = False
def get_ai_client():
"""Return configured AI client (OpenAI or compatible)."""
return openai.OpenAI(api_key=LLM_API_KEY, base_url=LLM_BASE_URL)
# BASE_URL configuration for OAuth callbacks
BASE_URL = os.environ.get("BASE_URL", "https://skymodderai.onrender.com").rstrip("/")
# Stripe configuration (handled in config.py)
stripe_price_id = config.STRIPE_PRO_PRICE_ID or ""
stripe_openclaw_price_id = config.STRIPE_OPENCLAW_PRICE_ID or ""
stripe_webhook_secret = config.STRIPE_WEBHOOK_SECRET or ""
# Marketing revamp: Everything is free. Payments enabled for donation.
PAYMENTS_ENABLED = config.PAYMENTS_ENABLED and STRIPE_AVAILABLE
OPENCLAW_ENABLED = os.environ.get("SKYMODDERAI_OPENCLAW_ENABLED", "0").lower() in (
"1",
"true",
"yes",
)
OPENCLAW_SANDBOX_ROOT = (
os.environ.get("OPENCLAW_SANDBOX_ROOT", "").strip() or "./openclaw_workspace"
)
OPENCLAW_MAX_FILES = int(os.environ.get("OPENCLAW_MAX_FILES", "500"))
OPENCLAW_MAX_BYTES = int(os.environ.get("OPENCLAW_MAX_BYTES", str(50 * 1024 * 1024)))
OPENCLAW_MAX_PATH_DEPTH = int(os.environ.get("OPENCLAW_MAX_PATH_DEPTH", "10"))
OPENCLAW_MAX_PATH_LENGTH = int(os.environ.get("OPENCLAW_MAX_PATH_LENGTH", "220"))
OPENCLAW_REQUIRE_SAME_IP = os.environ.get("OPENCLAW_REQUIRE_SAME_IP", "1").lower() in (
"1",
"true",
"yes",
)
OPENCLAW_ALLOWED_EXTENSIONS = frozenset(
{
".txt",
".md",
".json",
".yaml",
".yml",
".ini",
".esp",
".esm",
".esl",
".psc",
".log",
}
)
OPENCLAW_ALLOWED_OPERATIONS = frozenset(
{"read", "write", "list", "delete", "move", "copy", "mkdir", "stat"}
)
OPENCLAW_DENY_SEGMENTS = frozenset(
{
".git",
".env",
"venv",
".venv",
"__pycache__",
"node_modules",
"windows",
"system32",
"syswow64",
"drivers",
"registry",
"bios",
"efi",
"boot",
"proc",
"dev",
"etc",
"usr",
"var",
"appdata",
"programdata",
"program files",
"program files (x86)",
".ssh",
".gnupg",
}
)
OFFLINE_MODE = os.environ.get("SKYMODDERAI_OFFLINE_MODE", "").lower() in ("1", "true", "yes")
PAID_TIERS = frozenset({"pro", "pro_plus", "claw"})
# -------------------------------------------------------------------
# Database setup (simple SQLite)
# -------------------------------------------------------------------
DB_FILE = "users.db"
def get_db() -> sqlite3.Connection:
"""Get a database connection (stored in Flask's g)."""
if "db" not in g:
g.db = sqlite3.connect(DB_FILE)
g.db.row_factory = sqlite3.Row
return g.db # type: ignore[no-any-return]
@app.teardown_appcontext
def close_db(error: Optional[Exception]) -> None:
"""Close the database connection at the end of the request."""
db = g.pop("db", None)
if db is not None:
db.close()
def init_db():
"""Initialize the database schema."""
with app.app_context():
db = get_db()
db.execute("""
CREATE TABLE IF NOT EXISTS users (
email TEXT PRIMARY KEY,
tier TEXT DEFAULT 'free',
customer_id TEXT,
subscription_id TEXT,
email_verified INTEGER DEFAULT 0,
password_hash TEXT,
last_updated TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
""")
try:
db.execute("ALTER TABLE users ADD COLUMN email_verified INTEGER DEFAULT 0")
db.commit()
except sqlite3.OperationalError:
db.rollback()
try:
db.execute("ALTER TABLE users ADD COLUMN password_hash TEXT")
db.commit()
except sqlite3.OperationalError:
db.rollback()
for col in ("customer_id", "subscription_id"):
try:
db.execute(f"ALTER TABLE users ADD COLUMN {col} TEXT")
db.commit()
except sqlite3.OperationalError:
db.rollback()
db.execute("""
CREATE TABLE IF NOT EXISTS user_sessions (
token TEXT PRIMARY KEY,
display_id TEXT UNIQUE NOT NULL,
user_email TEXT NOT NULL,
user_agent TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
last_seen TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
expires_at INTEGER NOT NULL
)
""")
try:
db.execute("ALTER TABLE user_sessions ADD COLUMN display_id TEXT")
db.commit()
except sqlite3.OperationalError:
db.rollback()
db.execute("""
CREATE TABLE IF NOT EXISTS password_reset_tokens (
id INTEGER PRIMARY KEY AUTOINCREMENT,
email TEXT NOT NULL,
token TEXT NOT NULL UNIQUE,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
expires_at INTEGER NOT NULL,
used INTEGER DEFAULT 0
)
""")
db.execute("""
CREATE TABLE IF NOT EXISTS api_keys (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_email TEXT NOT NULL,
key_hash TEXT NOT NULL UNIQUE,
key_prefix TEXT NOT NULL,
label TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
""")
db.execute("""
CREATE TABLE IF NOT EXISTS community_posts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_email TEXT NOT NULL,
content TEXT NOT NULL,
tag TEXT DEFAULT 'general',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
moderated INTEGER DEFAULT 0
)
""")
db.execute("""
CREATE TABLE IF NOT EXISTS community_replies (
id INTEGER PRIMARY KEY AUTOINCREMENT,
post_id INTEGER NOT NULL,
user_email TEXT NOT NULL,
content TEXT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
moderated INTEGER DEFAULT 0,
FOREIGN KEY (post_id) REFERENCES community_posts(id)
)
""")
db.execute("""
CREATE TABLE IF NOT EXISTS community_votes (
post_id INTEGER NOT NULL,
user_email TEXT NOT NULL,
vote INTEGER NOT NULL,
PRIMARY KEY (post_id, user_email),
FOREIGN KEY (post_id) REFERENCES community_posts(id)
)
""")
try:
db.execute('ALTER TABLE community_posts ADD COLUMN tag TEXT DEFAULT "general"')
db.commit()
except sqlite3.OperationalError:
db.rollback()
db.execute("""
CREATE TABLE IF NOT EXISTS user_specs (
user_email TEXT PRIMARY KEY,
specs_json TEXT,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
""")
db.execute("""
CREATE TABLE IF NOT EXISTS user_links (
user_email TEXT PRIMARY KEY,
nexus_profile_url TEXT,
github_username TEXT,
discord_handle TEXT,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
""")
db.execute("""
CREATE TABLE IF NOT EXISTS user_saved_lists (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_email TEXT NOT NULL,
name TEXT NOT NULL,
game TEXT,
game_version TEXT,
masterlist_version TEXT,
tags TEXT,
notes TEXT,
preferences_json TEXT,
source TEXT,
list_text TEXT NOT NULL,
saved_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
UNIQUE (user_email, name)
)
""")
# Add columns that might not exist yet
for col_sql in (
"ALTER TABLE user_saved_lists ADD COLUMN analysis_snapshot TEXT",
"ALTER TABLE user_saved_lists ADD COLUMN game_version TEXT",
"ALTER TABLE user_saved_lists ADD COLUMN masterlist_version TEXT",
"ALTER TABLE user_saved_lists ADD COLUMN tags TEXT",
"ALTER TABLE user_saved_lists ADD COLUMN notes TEXT",
"ALTER TABLE user_saved_lists ADD COLUMN preferences_json TEXT",
"ALTER TABLE user_saved_lists ADD COLUMN source TEXT",
"ALTER TABLE user_saved_lists ADD COLUMN updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP",
):
try:
db.execute(col_sql)
db.commit()
except sqlite3.OperationalError:
db.rollback()
db.execute("""
CREATE TABLE IF NOT EXISTS openclaw_grants (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_email TEXT NOT NULL,
token_hash TEXT NOT NULL UNIQUE,
workspace_rel TEXT NOT NULL,
ip_hash TEXT,
acknowledged_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
expires_at INTEGER NOT NULL
)
""")
db.execute("""
CREATE TABLE IF NOT EXISTS openclaw_events (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_email TEXT,
event_type TEXT NOT NULL,
operation TEXT,
rel_path TEXT,
allowed INTEGER DEFAULT 0,
reasons_json TEXT,
ip_hash TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
""")
db.execute("""
CREATE TABLE IF NOT EXISTS openclaw_permissions (
user_email TEXT NOT NULL,
scope TEXT NOT NULL,
granted INTEGER DEFAULT 0,
granted_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (user_email, scope)
)
""")
db.execute("""
CREATE TABLE IF NOT EXISTS openclaw_plan_runs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_email TEXT NOT NULL,
plan_id TEXT NOT NULL UNIQUE,
game TEXT NOT NULL,
objective TEXT,
status TEXT DEFAULT 'proposed',
plan_json TEXT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
executed_at TIMESTAMP
)
""")
db.execute("""
CREATE TABLE IF NOT EXISTS openclaw_feedback (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_email TEXT NOT NULL,
game TEXT NOT NULL,
fps_avg REAL,
crashes INTEGER DEFAULT 0,
stutter_events INTEGER DEFAULT 0,
enjoyment_score INTEGER,
notes TEXT,
feedback_json TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
""")
db.execute("""
CREATE TABLE IF NOT EXISTS user_feedback (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_email TEXT,
type TEXT NOT NULL,
category TEXT NOT NULL,
content TEXT NOT NULL,
context_json TEXT,
status TEXT DEFAULT 'open',
priority INTEGER DEFAULT 0,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
resolved_at TIMESTAMP
)
""")
db.execute("""
CREATE TABLE IF NOT EXISTS user_activity (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_email TEXT,
event_type TEXT NOT NULL,
event_data TEXT,
session_id TEXT,
ip_hash TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
""")
db.execute("""
CREATE TABLE IF NOT EXISTS satisfaction_surveys (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_email TEXT,
rating INTEGER NOT NULL,
feedback_text TEXT,
context_json TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
""")
db.execute("""
CREATE TABLE IF NOT EXISTS community_reports (
id INTEGER PRIMARY KEY AUTOINCREMENT,
post_id INTEGER,
reply_id INTEGER,
reporter_email TEXT,
reason TEXT NOT NULL,
details TEXT,
status TEXT DEFAULT 'open',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
""")
db.execute("""
CREATE TABLE IF NOT EXISTS conflict_stats (
id INTEGER PRIMARY KEY AUTOINCREMENT,
game TEXT,
mod_a TEXT,
mod_b TEXT,
conflict_type TEXT,
last_seen TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
occurrence_count INTEGER DEFAULT 1,
UNIQUE(game, mod_a, mod_b, conflict_type)
)
""")
db.commit()
# Initialize on startup
init_db()
# Initialize Walkthrough Manager
walkthrough_manager = WalkthroughManager()
# Session cookie name and lifetimes (seconds)
SESSION_COOKIE_NAME = "session_token"
SESSION_SHORT_LIFETIME = 86400 # 24 hours
SESSION_LONG_LIFETIME = 30 * 86400 # 30 days (remember me)
# Environment detection
_in_production = os.getenv("FLASK_ENV") == "production"
# OAuth configuration
GOOGLE_OAUTH_ENABLED = config.GOOGLE_OAUTH_ENABLED
GITHUB_OAUTH_ENABLED = config.GITHUB_OAUTH_ENABLED
# -------------------------------------------------------------------
# LOOT parser(s) - default game preloaded, others lazy-loaded
# -------------------------------------------------------------------
DEFAULT_GAME = "skyrimse"
SUPPORTED_GAMES = [
{"id": "skyrimse", "name": "Skyrim SE (2016 Remaster)", "nexus_slug": "skyrimspecialedition"},
{"id": "skyrim", "name": "Skyrim LE (2011 Original)", "nexus_slug": "skyrim"},
{"id": "skyrimvr", "name": "Skyrim VR", "nexus_slug": "skyrimspecialedition"},
{"id": "oblivion", "name": "Oblivion", "nexus_slug": "oblivion"},
{"id": "fallout3", "name": "Fallout 3", "nexus_slug": "fallout3"},
{"id": "falloutnv", "name": "Fallout: New Vegas", "nexus_slug": "newvegas"},
{"id": "fallout4", "name": "Fallout 4", "nexus_slug": "fallout4"},
{"id": "starfield", "name": "Starfield", "nexus_slug": "starfield"},
]
NEXUS_GAME_SLUGS = {g["id"]: g["nexus_slug"] for g in SUPPORTED_GAMES}
GAME_DISPLAY_NAMES = {g["id"]: g["name"] for g in SUPPORTED_GAMES}
MAX_PARSER_CACHE = 8
_parsers = OrderedDict() # key: (game, version), value: LOOTParser
def _extract_things_to_verify(conflicts_list) -> list:
"""From conflict messages, extract short 'things to check on your PC' items (game/SKSE/version). We can't run a PC diagnostic—this lists what the masterlist says to verify."""
seen = set()
out = []
raw = []
for c in conflicts_list:
msg = getattr(c, "message", None) or ""
raw.append(msg)
text = " ".join(raw).lower()
checks = [
("Requires SKSE", "skse"),
("Requires Skyrim", "game version (Skyrim)"),
("Requires version", "game or mod version"),
("not compatible with your version", "game/mod version match"),
("product_version", "game executable version"),
("ENBSeries", "ENB version"),
]
for phrase, label in checks:
if phrase.lower() in text and label not in seen:
seen.add(label)
out.append(label)
return out
def get_parser(game: str, version: str = "latest"):
"""Get or create LOOT parser for the given game and masterlist version. Loads from JSON cache first for fast startup."""
game = (game or DEFAULT_GAME).lower()
if game not in {g["id"] for g in SUPPORTED_GAMES}:
game = DEFAULT_GAME
version_key = version.lower() if version and version != "latest" else "latest"
key = (game, version_key)
if key in _parsers:
_parsers.move_to_end(key)
return _parsers[key]
p = LOOTParser(game, version=version)
# JSON cache first (fast path when data exists)
if p.load_database():
logger.info(f"Loaded {game} from cache ({len(p.mod_database)} mods)")
elif p.download_masterlist(force_refresh=False):
p.parse_masterlist()
p.save_database()
else:
if version_key != "latest":
return get_parser(game, "latest")
logger.warning(f"No masterlist for {game}, using {DEFAULT_GAME}")
return get_parser(DEFAULT_GAME, version)
_parsers[key] = p
_parsers.move_to_end(key)
while len(_parsers) > MAX_PARSER_CACHE:
evicted_key, _ = _parsers.popitem(last=False)
logger.info("Evicted parser cache entry: %s:%s", evicted_key[0], evicted_key[1])
return _parsers[key]
# Preload default game so app starts with working data
parser = get_parser(DEFAULT_GAME)
logger.info(f"LOOT masterlist loaded for {DEFAULT_GAME} ({len(parser.mod_database)} mods)")
# Game-specific sample mod lists: typical base + DLC + "what people download first", with some that may conflict to show utility
SAMPLE_MOD_LISTS = {
"skyrimse": """*Skyrim.esm
*Update.esm
*Dawnguard.esm
*HearthFires.esm
*Dragonborn.esm
*Unofficial Skyrim Special Edition Patch.esp
*Falskaar.esm
*LegacyoftheDragonborn.esm
*BSAssets.esm
*BSHeartland.esm
*BS_DLC_patch.esp
*SkyUI_SE.esp
*Alternate Start - Live Another Life.esp
*Ordinator - Perks of Skyrim.esp
*Immersive Citizens - AI Overhaul.esp
*Relationship Dialogue Overhaul.esp
*Cutting Room Floor.esp
*Open Cities Skyrim.esp""",
"skyrim": """*Skyrim.esm
*Update.esm
*Dawnguard.esm
*HearthFires.esm
*Dragonborn.esm
*Unofficial Skyrim Legendary Edition Patch.esp
*SkyUI.esp
*Alternate Start - Live Another Life.esp
*Ordinator - Perks of Skyrim.esp
*Immersive Citizens - AI Overhaul.esp""",
"skyrimvr": """*Skyrim.esm
*Update.esm
*Dawnguard.esm
*HearthFires.esm
*Dragonborn.esm
*Unofficial Skyrim Special Edition Patch.esp
*SkyUI_SE.esp
*VRIK Player Avatar.esp
*Spell Wheel VR.esp
*Alternate Start - Live Another Life.esp""",
"oblivion": """*Oblivion.esm
*DLCShiveringIsles.esp
*DLCBattlehornCastle.esp
*DLCFrostcrag.esp
*DLCMehrunesRazor.esp
*DLCSpellTomes.esp
*DLCThievesDen.esp
*DLCVileLair.esp
*Knights.esp
*Unofficial Oblivion Patch.esp
*Unofficial Shivering Isles Patch.esp
*DLCHorseArmor - Unofficial Patch.esp""",
"fallout3": """*Fallout3.esm
*Anchorage.esm
*ThePitt.esm
*BrokenSteel.esm
*PointLookout.esm
*Zeta.esm
*Unofficial Fallout 3 Patch.esp
*Fallout3 - Project Beauty.esp
*EVE.esp""",
"falloutnv": """*FalloutNV.esm
*DeadMoney.esm
*HonestHearts.esm
*OldWorldBlues.esm
*LonesomeRoad.esm
*GunRunnersArsenal.esm
*ClassicPack.esm
*MercenaryPack.esm
*TribalPack.esm
*CaravanPack.esm
*YUP - Base Game and All DLC.esp
*NVAC - New Vegas Anti Crash.esp
*The Mod Configuration Menu.esp
*JSawyer.esp
*Weapon Mods Expanded.esp""",
"fallout4": """*Fallout4.esm
*DLCRobot.esm
*DLCworkshop01.esm
*DLCCoast.esm
*DLCworkshop02.esm
*DLCworkshop03.esm
*DLCNukaWorld.esm
*Unofficial Fallout 4 Patch.esp
*ArmorKeywords.esm
*SimSettlements.esm
*WorkshopFramework.esm
*TrueStormsFO4.esp
*Better Settlers.esp
*Start Me Up.esp""",
"starfield": """*Starfield.esm
*Constellation.esm
*OldMars.esm
*ShatteredSpace.esm
*StarfieldCommunityPatch.esm
*BlueprintShips-Starfield.esm
*MoreDramaticGravJumps.esp""",
}
# -------------------------------------------------------------------
# Helper functions
# -------------------------------------------------------------------
def get_user_tier(email):