-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdatabase.js
More file actions
373 lines (334 loc) · 10.9 KB
/
Copy pathdatabase.js
File metadata and controls
373 lines (334 loc) · 10.9 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
// database.js
const fs = require('fs');
const path = require('path');
const sqlite3 = require('sqlite3');
const { open } = require('sqlite');
// Diretório e caminho do banco
const USERS_DIR = path.resolve(__dirname, 'users');
const DB_PATH = path.join(USERS_DIR, 'database.db');
let db;
// Decompõe milissegundos em dias, horas, minutos e segundos
function decomposeDuration(ms) {
const days = Math.floor(ms / 86400000);
ms %= 86400000;
const hours = Math.floor(ms / 3600000);
ms %= 3600000;
const minutes = Math.floor(ms / 60000);
ms %= 60000;
const seconds = Math.floor(ms / 1000);
return { days, hours, minutes, seconds };
}
// Formata duração em string legível
function formatDuration(ms) {
const { days, hours, minutes, seconds } = decomposeDuration(ms);
return `${days}d ${String(hours).padStart(2,'0')}h ${String(minutes).padStart(2,'0')}m ${String(seconds).padStart(2,'0')}s`;
}
// Converte string como "30m" ou "1h30m" em milissegundos
function parseDuration(str) {
const unitMap = { d: 86400000, h: 3600000, m: 60000, s: 1000 };
const parts = str.match(/(\d+)([dhms])/g);
let ms = 0;
if (parts) {
for (const p of parts) {
const [, v, u] = p.match(/(\d+)([dhms])/);
ms += parseInt(v, 10) * (unitMap[u] || 0);
}
}
return ms;
}
// Inicializa o banco, tabelas e migrações
async function initDatabase() {
if (!fs.existsSync(USERS_DIR)) {
fs.mkdirSync(USERS_DIR, { recursive: true });
}
db = await open({ filename: DB_PATH, driver: sqlite3.Database });
// Configurações importantes
await db.exec('PRAGMA journal_mode = WAL;');
await db.exec('PRAGMA foreign_keys = ON;');
// Cria tabelas se não existirem
await db.exec(`
CREATE TABLE IF NOT EXISTS user_time (
guild_id TEXT,
user_id TEXT,
total_time INTEGER DEFAULT 0,
open_start INTEGER,
PRIMARY KEY (guild_id, user_id)
);
`);
await db.exec(`
CREATE TABLE IF NOT EXISTS server_config (
server_id TEXT PRIMARY KEY,
panel_channel TEXT,
notify_channel TEXT,
admin_role TEXT,
active INTEGER DEFAULT 1,
server_time_start INTEGER,
auth_duration_ms INTEGER
);
`);
// Migrações: adiciona colunas novas se o DB for antigo
try {
await db.exec('ALTER TABLE server_config ADD COLUMN api_channel TEXT');
} catch (e) {}
try {
await db.exec('ALTER TABLE server_config ADD COLUMN owner_id TEXT');
} catch (e) {}
}
// Controle de pontos de usuários
async function startPoint(guildId, userId) {
const now = Date.now();
await db.run(
`INSERT INTO user_time (guild_id, user_id, total_time, open_start)
VALUES (?, ?, 0, ?)
ON CONFLICT(guild_id, user_id) DO UPDATE
SET open_start = excluded.open_start`,
guildId, userId, now
);
}
async function getOpenPoint(guildId, userId) {
const row = await db.get(
'SELECT open_start FROM user_time WHERE guild_id = ? AND user_id = ?',
guildId, userId
);
return row ? row.open_start : null;
}
async function endPoint(guildId, userId) {
const now = Date.now();
const row = await db.get(
'SELECT total_time, open_start FROM user_time WHERE guild_id = ? AND user_id = ?',
guildId, userId
);
if (!row || !row.open_start) return null;
const elapsed = now - row.open_start;
const duration = Math.min(elapsed, 86400000);
const totalNew = row.total_time + duration;
await db.run(
'UPDATE user_time SET total_time = ?, open_start = NULL WHERE guild_id = ? AND user_id = ?',
totalNew, guildId, userId
);
return formatDuration(duration);
}
async function closeExpiredPoints() {
const now = Date.now();
const rows = await db.all(
'SELECT guild_id, user_id, total_time, open_start FROM user_time WHERE open_start IS NOT NULL'
);
const expired = [];
for (const r of rows) {
const elapsed = now - r.open_start;
if (elapsed >= 86400000) {
const duration = 86400000;
const totalNew = r.total_time + duration;
await db.run(
'UPDATE user_time SET total_time = ?, open_start = NULL WHERE guild_id = ? AND user_id = ?',
totalNew, r.guild_id, r.user_id
);
expired.push({ guildId: r.guild_id, userId: r.user_id, duration: formatDuration(duration) });
}
}
return expired;
}
async function isUserPointedElsewhere(userId, currentGuild) {
const row = await db.get(
`SELECT guild_id FROM user_time
WHERE user_id = ? AND open_start IS NOT NULL AND guild_id != ? LIMIT 1`,
userId, currentGuild
);
return !!row;
}
async function getUserTime(guildId, userId) {
const now = Date.now();
const row = await db.get(
'SELECT total_time, open_start FROM user_time WHERE guild_id = ? AND user_id = ?',
guildId, userId
);
let total = row ? row.total_time : 0;
if (row && row.open_start) total += (now - row.open_start);
return decomposeDuration(total);
}
// Configurações de servidor
async function getServerConfig(serverId) {
let cfg = await db.get('SELECT * FROM server_config WHERE server_id = ?', serverId);
const now = Date.now();
if (!cfg) {
// Licença inicial de 24 horas (86400000 ms)
await db.run(
`INSERT INTO server_config (server_id, active, server_time_start, auth_duration_ms)
VALUES (?, 1, ?, ?)`,
serverId, now, 24 * 60 * 60 * 1000
);
cfg = {
server_id: serverId,
panel_channel: null,
notify_channel: null,
admin_role: null,
api_channel: null,
owner_id: null,
active: 1,
server_time_start: now,
auth_duration_ms: 24 * 60 * 60 * 1000
};
}
return {
panelChannel: cfg.panel_channel,
notifyChannel: cfg.notify_channel,
adminRole: cfg.admin_role,
apiChannel: cfg.api_channel,
ownerId: cfg.owner_id,
active: cfg.active === 1,
serverTimeStart: cfg.server_time_start,
authDurationMs: cfg.auth_duration_ms != null ? cfg.auth_duration_ms : Infinity
};
}
async function setPanelChannel(serverId, channelId) {
await db.run(
`INSERT INTO server_config (server_id, panel_channel)
VALUES (?, ?)
ON CONFLICT(server_id) DO UPDATE
SET panel_channel = excluded.panel_channel`,
serverId, channelId
);
}
async function setNotifyChannel(serverId, channelId) {
await db.run(
`INSERT INTO server_config (server_id, notify_channel)
VALUES (?, ?)
ON CONFLICT(server_id) DO UPDATE
SET notify_channel = excluded.notify_channel`,
serverId, channelId
);
}
async function setAdminRole(serverId, roleId) {
await db.run(
`INSERT INTO server_config (server_id, admin_role)
VALUES (?, ?)
ON CONFLICT(server_id) DO UPDATE
SET admin_role = excluded.admin_role`,
serverId, roleId
);
}
// Define canal de API de pagamento
async function setApiChannel(serverId, channelId) {
await db.run(
`INSERT INTO server_config (server_id, api_channel)
VALUES (?, ?)
ON CONFLICT(server_id) DO UPDATE
SET api_channel = excluded.api_channel`,
serverId, channelId
);
}
// Define ID do owner para envio de hash
async function setOwnerId(serverId, ownerId) {
await db.run(
`INSERT INTO server_config (server_id, owner_id)
VALUES (?, ?)
ON CONFLICT(server_id) DO UPDATE
SET owner_id = excluded.owner_id`,
serverId, ownerId
);
}
async function setServerAuth(serverId, durationStr) {
const now = Date.now();
// 1) Busca configuração existente
const cfg = await getServerConfig(serverId);
let newDurationMs;
if (/^[+-]/.test(durationStr)) {
// → Ajuste relativo: "+30d" ou "-00:00:05:00"
const sign = durationStr[0];
const deltaRaw = durationStr.slice(1);
// Escolhe parser: se vier com “:”, parse como dd:hh:mm:ss
const deltaMs = deltaRaw.includes(':')
? (() => {
const [d,h,m,s] = deltaRaw.split(':').map(x => parseInt(x) || 0);
return ((d*24 + h)*3600 + m*60 + s) * 1000;
})()
: parseDuration(deltaRaw);
// Calcula o que restava até agora
const elapsed = now - cfg.serverTimeStart;
const oldRemaining = (cfg.authDurationMs === Infinity ? 0 : cfg.authDurationMs) - elapsed;
// Soma ou subtrai e limita a zero
const rawNew = sign === '+'
? oldRemaining + deltaMs
: oldRemaining - deltaMs;
newDurationMs = Math.max(0, rawNew);
} else {
// → Definição absoluta: "30d", "1h30m", etc.
newDurationMs = parseDuration(durationStr);
}
// 2) Grava no banco reiniciando a contagem a partir de agora
await db.run(
`INSERT INTO server_config (server_id, active, server_time_start, auth_duration_ms)
VALUES (?, 1, ?, ?)
ON CONFLICT(server_id) DO UPDATE
SET active = excluded.active,
server_time_start = excluded.server_time_start,
auth_duration_ms = excluded.auth_duration_ms`,
serverId, now, newDurationMs
);
}
// Retorna a guild onde o usuário tem ponto aberto (se houver)
async function getAnyOpenPoint(userId) {
const row = await db.get(
`SELECT guild_id, open_start
FROM user_time
WHERE user_id = ? AND open_start IS NOT NULL
LIMIT 1`,
userId
);
return row; // { guild_id, open_start } ou undefined
}
async function checkServerAuths() {
const rows = await db.all('SELECT server_id, server_time_start, auth_duration_ms, active FROM server_config');
const now = Date.now();
for (const r of rows) {
if (r.active === 1 && r.auth_duration_ms != null && (now - r.server_time_start) > r.auth_duration_ms) {
await db.run('UPDATE server_config SET active = 0 WHERE server_id = ?', r.server_id);
}
}
}
// Ajuste manual de tempo via admin
async function adjustUserTime(guildId, userId, deltaStr) {
const m = deltaStr.match(/^([+-]?)(\d+):(\d+):(\d+):(\d+)$/);
if (!m) return 'Formato inválido. Use ±dd:hh:mm:ss';
const sign = m[1] === '-' ? -1 : 1;
const [, , dd, hh, mm, ss] = m;
const msDelta = sign * ((+dd*86400 + +hh*3600 + +mm*60 + +ss) * 1000);
const row = await db.get('SELECT total_time FROM user_time WHERE guild_id = ? AND user_id = ?', guildId, userId);
let total = row ? row.total_time : 0;
let newTotal = total + msDelta;
if (newTotal < 0) newTotal = 0;
await db.run(
`INSERT INTO user_time (guild_id, user_id, total_time)
VALUES (?, ?, ?)
ON CONFLICT(guild_id, user_id) DO UPDATE
SET total_time = excluded.total_time`,
guildId, userId, newTotal
);
const action = sign > 0 ? 'adicionou' : 'removeu';
return `${action} \`${formatDuration(Math.abs(msDelta))}\` para <@${userId}> (${userId})`;
}
async function deactivateServer(serverId) {
await db.run('UPDATE server_config SET active = 0 WHERE server_id = ?', serverId);
}
module.exports = {
initDatabase,
startPoint,
getOpenPoint,
endPoint,
closeExpiredPoints,
isUserPointedElsewhere,
getUserTime,
getServerConfig,
setPanelChannel,
setNotifyChannel,
setAdminRole,
setApiChannel,
setOwnerId,
getAnyOpenPoint,
setServerAuth,
checkServerAuths,
adjustUserTime,
deactivateServer,
parseDuration,
formatDuration
};