File size: 6,328 Bytes
2344c18
 
 
 
 
 
 
 
c24afb6
 
2344c18
 
 
 
 
 
 
 
 
 
 
 
 
e2e9c5e
2344c18
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e2e9c5e
09a1bce
 
9b33baf
cc92512
41da4fc
 
2344c18
 
 
 
 
 
 
208f0fb
2344c18
 
 
a70c737
208f0fb
a70c737
2344c18
 
 
208f0fb
2344c18
 
 
208f0fb
2344c18
e2e9c5e
 
 
 
2344c18
09a1bce
 
 
9b33baf
cc92512
41da4fc
09a1bce
a70c737
2344c18
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e2e9c5e
 
 
 
 
 
2344c18
 
 
 
 
 
 
 
e2e9c5e
09a1bce
 
9b33baf
cc92512
41da4fc
 
2344c18
 
 
 
 
 
 
e2e9c5e
2344c18
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
208f0fb
 
2344c18
 
 
 
 
 
 
 
 
208f0fb
2344c18
 
 
 
 
 
 
8758f97
2344c18
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
const fs = require('fs');
const path = require('path');

console.log(">>> [MODULE] storage.js: Initializing...");

// --- File Paths ---
// --- Persistence Configuration (Hugging Face Buckets) ---
// The bucket should be mounted at /home/node/app/data (as seen in Space settings)
const PERSISTENT_DIR = path.isAbsolute(process.env.DATA_PATH || "")
    ? process.env.DATA_PATH
    : path.join(__dirname, 'data');

console.log(`[STORAGE] Using persistent directory: ${PERSISTENT_DIR}`);

if (!fs.existsSync(PERSISTENT_DIR)) {
    console.log(`[STORAGE] Creating persistent directory...`);
    fs.mkdirSync(PERSISTENT_DIR, { recursive: true });
}

const GUILD_SETTINGS_FILE = path.join(PERSISTENT_DIR, "guild_settings.json");
const CONFIG_FILE = path.join(PERSISTENT_DIR, "lineup_access.json");
const PLAYER_STATS_FILE = path.join(PERSISTENT_DIR, "player_stats.json");
const STATE_FILE = path.join(PERSISTENT_DIR, "state.json");
const BROADCAST_FILE = path.join(PERSISTENT_DIR, "broadcast_history.json");

function loadJson(path, defaultValue = {}) {
    if (fs.existsSync(path)) {
        try {
            const data = fs.readFileSync(path, 'utf8');
            return JSON.parse(data);
        } catch (e) {
            console.warn(`[STORAGE] Failed to load ${path}:`, e.message);
        }
    }
    return defaultValue;
}

function saveJson(path, data) {
    try {
        fs.writeFileSync(path, JSON.stringify(data, null, 2));
    } catch (e) {
        console.error(`[STORAGE] Failed to save ${path}:`, e.message);
    }
}

class StorageManager {
    constructor() {
        this.data = {
            config: {},           // Guild settings
            roles: {},            // Lineup roles
            stats: {},            // Player stats
            active_polls: {},     // Active poll messages
            processed_messages: new Set(), // Processed message IDs
            settings: {},         // Global bot settings
            broadcasts: [],       // Broadcast history
            scheduled_matches: [], // Scheduled league matches
            cleanup_queue: [],     // Messages to be deleted
            onboarded: {},          // GuildId -> Set of UserIds who got the welcome DM
            dmall_sessions: {},      // SessionId -> Session Data
            muted_users: {}         // UserId -> true (users who mute friendly DMs)
        };
        this.loadAll();
    }

    loadAll() {
        // Load Guild Settings
        const guildSettings = loadJson(GUILD_SETTINGS_FILE, {});
        this.data.config = guildSettings;

        // Load Roles
        const roles = loadJson(CONFIG_FILE, {});
        this.data.roles = Object.fromEntries(
            Object.entries(roles).map(([k, v]) => [k, new Set(v)])
        );

        // Load Stats
        const stats = loadJson(PLAYER_STATS_FILE, {});
        this.data.stats = stats;

        // Load State
        const state = loadJson(STATE_FILE, {});
        this.data.active_polls = state.polls || {};
        this.data.processed_messages = new Set(state.processed || []);
        this.data.settings = state.settings || {};
        
        // Load Broadcasts
        this.data.broadcasts = loadJson(BROADCAST_FILE, []);

        // Load Reminders & Cleanup
        this.data.scheduled_matches = state.scheduled_matches || [];
        this.data.cleanup_queue = state.cleanup_queue || [];
        this.data.onboarded = state.onboarded || {};
        this.data.dmall_sessions = state.dmall_sessions || {};
        this.data.muted_users = state.muted_users || {};

        console.log('[STORAGE] Data loaded successfully');
    }

    save(type) {
        switch (type) {
            case 'config':
                saveJson(GUILD_SETTINGS_FILE, this.data.config);
                break;
            case 'roles':
                saveJson(CONFIG_FILE, Object.fromEntries(
                    Object.entries(this.data.roles).map(([k, v]) => [k, Array.from(v)])
                ));
                break;
            case 'stats':
                saveJson(PLAYER_STATS_FILE, this.data.stats);
                break;
            case 'active_polls':
                this.saveState();
                break;
            case 'settings':
                this.saveState();
                break;
            case 'broadcasts':
                saveJson(BROADCAST_FILE, this.data.broadcasts);
                break;
            default:
                console.warn(`[STORAGE] Unknown save type: ${type}`);
        }
    }

    saveState() {
        saveJson(STATE_FILE, {
            polls: this.data.active_polls,
            processed: Array.from(this.data.processed_messages),
            settings: this.data.settings,
            scheduled_matches: this.data.scheduled_matches,
            cleanup_queue: this.data.cleanup_queue,
            onboarded: this.data.onboarded,
            dmall_sessions: this.data.dmall_sessions,
            muted_users: this.data.muted_users
        });
    }

    saveAll() {
        this.save('config');
        this.save('roles');
        this.save('stats');
        this.save('broadcasts');
        this.saveState();
    }

    getPrefix(guildId) {
        return this.data.config[guildId]?.prefix || '!';
    }

    setPrefix(guildId, prefix) {
        if (!this.data.config[guildId]) this.data.config[guildId] = {};
        this.data.config[guildId].prefix = prefix;
        this.save('config');
    }

    getRecord(guildId) {
        if (!this.data.config[guildId]) this.data.config[guildId] = {};
        if (!this.data.config[guildId].record) {
            this.data.config[guildId].record = { wins: 0, losses: 0, draws: 0 };
        }
        return this.data.config[guildId].record;
    }

    addStat(userId, statType, amount = 1) {
        if (!this.data.stats[userId]) {
            this.data.stats[userId] = {
                matches: 0,
                wins: 0,
                losses: 0,
                draws: 0,
                goals: 0,
                assists: 0,
                mvps: 0
            };
        }
        this.data.stats[userId][statType] = (this.data.stats[userId][statType] || 0) + amount;
        this.save('stats');
    }
}

const storage = new StorageManager();

storage.PERSISTENT_DIR = PERSISTENT_DIR;
console.log(">>> [MODULE] storage.js: Fully initialized.");
module.exports = storage;