This repository has been archived by the owner on Nov 30, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 144
/
databaseManager.js
348 lines (293 loc) · 11 KB
/
databaseManager.js
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
const inquirer = require("inquirer");
const sqlite = require("sqlite");
const sqlite3 = require("sqlite3");
const path = require("path");
const fs = require("fs");
const Helper = require("./helpers/Helper.js");
let config = null;
let helper = null;
(async () => {
if (!fs.existsSync("./config.json")) {
console.log("Failed to find \"config.json\". Did you rename the file to \"config.json.json\"? Make sure to Enable Windows File Extensions");
return;
}
try {
config = require(path.resolve("config.json"));
} catch (err) {
let errPosition = err.message.split(": ").pop().trim();
let match = errPosition.match(/^Unexpected (?<type>.*) in JSON at position (?<position>.*)$/i);
if (!match || isNaN(parseInt(match.groups.position))) {
console.error(err);
} else {
let configRaw = fs.readFileSync("./config.json").toString();
let part = configRaw.slice(0, parseInt(match.groups.position));
let lines = part.split("\n").map(l => l.trim()).filter(l => l.length > 0);
console.log("Failed to parse \"config.json\":\nError description: " + errPosition + "\nError on line: " + lines.length + "\nText which caused the error: " + lines.pop());
console.log("Please verify your \"config.json\" and take the \"config.json.example\" file for help")
}
return;
}
helper = new Helper(config.steamWebAPIKey);
console.log("Opening database...");
let db = await sqlite.open({
filename: "./accounts.sqlite",
driver: sqlite3.Database
});
await Promise.all([
db.run("CREATE TABLE IF NOT EXISTS \"accounts\" (\"username\" TEXT NOT NULL UNIQUE, \"password\" TEXT NOT NULL, \"sharedSecret\" TEXT, \"lastCommend\" INTEGER NOT NULL DEFAULT -1, \"operational\" NUMERIC NOT NULL DEFAULT 1, PRIMARY KEY(\"username\"))"),
db.run("CREATE TABLE IF NOT EXISTS \"commended\" (\"username\" TEXT NOT NULL REFERENCES accounts(username), \"commended\" INTEGER NOT NULL, \"timestamp\" INTEGER NOT NULL)")
]);
(async function askInput() {
console.log("");
let r = await inquirer.prompt({
type: "list",
name: "response",
message: "What would you like to do?",
pageSize: 11,
choices: [
"Export account list",
"List commends for user",
"Reset commends for user",
"Remove account from database",
"Add account(s) to database",
"List not working accounts",
"Remove all not working accounts",
"Get last commend target and time",
"Set account operational",
"Remove all accounts - No history reset",
"Reset Database",
"Exit"
]
});
switch (r.response) {
case "Remove all accounts - No history reset": {
let confirm = await inquirer.prompt({
type: "confirm",
name: "confirm",
message: "Are you sure you want to remove ALL accounts from the database? Commend history will NOT be removed"
});
if (!confirm.confirm) {
break;
}
let data = await db.run("DELETE FROM accounts");
console.log("Successfully dropped " + data[0].changes + " account entries");
break;
}
case "Set account operational": {
let input = await inquirer.prompt({
type: "input",
name: "username",
message: "Enter username you want to set as operational"
});
let data = await db.run("UPDATE accounts SET operational = 1 WHERE username = ?", input.username).catch(() => { });
if (data.changes <= 0) {
console.log("Failed to set operational status of \"" + input.username + "\" to True - Username not found.");
} else {
console.log("Successfully set operational status of \"" + input.username + "\" to True");
}
break;
}
case "Get last commend target and time": {
let lastCommend = await db.get("SELECT username,lastCommend FROM accounts ORDER BY lastCommend DESC LIMIT 1");
console.log("The latest commend has been sent by account " + lastCommend.username + " at " + new Date(lastCommend.lastCommend).toLocaleString());
break;
}
case "Remove all not working accounts": {
let _export = await inquirer.prompt({
type: "list",
name: "response",
message: "Do you want to export all not working accounts to a file called \"notworking.txt\" as well?",
choices: [
"Yes",
"No",
]
});
if (_export.response === "Yes") {
let data = await db.all("SELECT username, password FROM accounts WHERE operational = 0");
fs.writeFileSync("notworking.txt", data.map(s => s.username + ":" + s.password).join("\n"));
}
await db.run("DELETE FROM accounts WHERE operational = 0");
// We keep the "commended" list, if the account start working again for some reason we don't want to have the list wiped
console.log("Successfully removed all not working accounts");
break;
}
case "Reset Database": {
let confirm = await inquirer.prompt({
type: "confirm",
name: "confirm",
message: "Are you sure you want to remove ALL entries in the database?"
});
if (!confirm.confirm) {
break;
}
let data = await Promise.all([
db.run("DELETE FROM commended"),
db.run("DELETE FROM accounts")
]);
console.log("Successfully dropped " + data[0].changes + " commend history entries and " + data[1].changes + " account entries");
break;
}
case "List not working accounts": {
let data = await db.all("SELECT username FROM accounts WHERE operational = 0");
if (data.length <= 0) {
console.log("All accounts are working!");
} else {
console.log("Got " + data.length + " account" + (data.length === 1 ? "" : "s") + "\n" + data.map(d => d.username).join(", "));
}
break;
}
case "Add account(s) to database": {
let selection = await inquirer.prompt({
type: "list",
name: "selection",
message: "What would you like to do?",
choices: [
"Import from JSON file",
"Import from username:password file",
"Manually add account"
]
});
let list = [];
if (selection.selection !== "Manually add account") {
let file = await inquirer.prompt({
type: "input",
name: "file",
message: "Enter the name of the file you want to import"
});
let filePath = selection.selection === "Import from JSON file" ? (path.join(__dirname, file.file.endsWith(".json") ? file.file : (file.file + ".json"))) : (path.join(__dirname, file.file.endsWith(".txt") ? file.file : (file.file + ".txt")));
if (!fs.existsSync(filePath)) {
console.log("Failed to find file at \"" + filePath + "\"");
break;
}
switch (selection.selection) {
case "Import from JSON file": {
list = JSON.parse(fs.readFileSync(filePath));
break;
}
case "Import from username:password file": {
list = fs.readFileSync(filePath).toString().trim().split("\n").map(s => s.trim());
break;
}
}
} else {
let input = await inquirer.prompt({
type: "input",
name: "input",
message: "Enter username and password separated by a \":\" - \"username:password\""
});
list.push(input.input);
}
if (typeof list[0] === "string") {
list = list.map((s) => {
let parts = s.split(":");
let username = parts.shift();
let password = parts.join(":");
return {
username: username.trim(),
password: password.trim(),
sharedSecret: ""
}
});
}
if (list.length <= 0) {
console.log("Cannot insert zero accounts");
break;
}
let chunks = helper.chunkArray(list, 100);
let changes = 0;
for (let chunk of chunks) {
let data = await db.run("INSERT OR IGNORE INTO accounts (\"username\", \"password\", \"sharedSecret\") VALUES " + chunk.map(s => "(?, ?, ?)").join(", "), ...chunk.map(s => [ s.username, s.password, s.sharedSecret ]).flat());
changes += data.changes;
}
console.log("Successfully added " + changes + " account" + (changes === 1 ? "" : "s") + ". Duplicates have been ignored.");
break;
}
case "Remove account from database": {
let input = await inquirer.prompt({
type: "input",
name: "input",
message: "Enter username you want to remove"
});
let data = await Promise.all([
db.run("DELETE FROM commended WHERE username = ?", input.input),
db.run("DELETE FROM accounts WHERE username = ?", input.input)
]);
console.log("Successfully removed " + data[0].changes + " entr" + (data[0].changes === 1 ? "y" : "ies") + " from the commend history and " + data[1].changes + " account" + (data[1].changes === 1 ? "" : "s"));
break;
}
case "Reset commends for user": {
let input = await inquirer.prompt({
type: "input",
name: "input",
message: "Enter the SteamID or profile URL you want to reset commend history of"
});
let sid = await helper.parseSteamID(input.input).catch(() => {});
if (!sid) {
console.log("Failed to find SteamID of input");
break;
}
let data = await db.run("DELETE FROM commended WHERE commended = ?", sid.accountid);
console.log("Removed " + data.changes + " entr" + (data.changes === 1 ? "y" : "ies") + " from the commend history");
break;
}
case "List commends for user": {
let input = await inquirer.prompt({
type: "input",
name: "input",
message: "Enter the SteamID or profile URL you want to list the commend history of"
});
let sid = await helper.parseSteamID(input.input).catch(() => {});
if (!sid) {
console.log("Failed to find SteamID of input");
break;
}
let data = await db.all("SELECT * FROM commended WHERE commended = ?", sid.accountid);
if (data.length <= 0) {
console.log("This user is not in the commend history");
break;
}
let highest = Math.max(data.map(s => s.username.length));
console.log("User has been commended " + data.length + " time" + (data.length === 1 ? "" : "s") + "\n" + data.map(s => " ".repeat(highest - s.username.length) + s.username + " - " + new Date(s.timestamp).toString()));
break;
}
case "Exit": {
console.log("Safely closing database...");
await db.close();
return;
}
case "Export account list": {
let _export = await inquirer.prompt({
type: "list",
name: "response",
message: "Do you want to export all accounts or only working ones?",
choices: [
"Export all accounts",
"Exports only working accounts",
]
});
let query = "SELECT username, password FROM accounts";
if (_export.response === "Exports only working accounts") {
query += " WHERE operational = 1";
}
let input = await inquirer.prompt({
type: "input",
name: "input",
message: "What do you want to name the output file?"
});
let filePath = path.join(__dirname, input.input.includes(".") ? input.input : (input.input + ".txt"));
if (fs.existsSync(filePath)) {
console.log("File already exists.");
break;
}
let data = await db.all(query);
if (data.length <= 0) {
console.log("No data to export");
break;
}
fs.writeFileSync(filePath, data.map(s => s.username + ":" + s.password).join("\n"));
console.log("Successfully exported " + data.length + " accounts to \"" + filePath + "\"");
}
}
askInput();
})();
})();