-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathweb.js
More file actions
140 lines (115 loc) · 4.35 KB
/
web.js
File metadata and controls
140 lines (115 loc) · 4.35 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
import http from 'http';
import { readdir, stat } from 'fs/promises';
import process from 'process';
import { basename, extname } from 'path';
import { users } from './lib/db.js';
const getCommandList = async () => {
const files = await readdir('lib/commands');
const commands = files
.filter((file) => {
const ext = extname(file);
return ext === '.js';
})
.map((file) => {
const ext = extname(file);
return basename(file, ext);
});
return commands;
};
const server = http.createServer(async (req, res) => {
if (req.method !== 'POST') {
res.statusCode = 405;
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify({ error: 'Метод не поддерживается' }));
return;
}
let body = '';
req.on('data', chunk => {
body += chunk.toString();
});
req.on('end', async () => {
try {
const data = JSON.parse(body);
const { id, text, secret } = data;
if (!id || !text || !secret) {
res.statusCode = 400;
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify({ error: 'Отсутствуют обязательные поля: id, text или secret' }));
return;
}
const userID = id.toString();
let userAccount = await users.read(userID);
if (!userAccount) {
res.statusCode = 404;
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify({ error: 'Пользователь не найден' }));
return;
}
if (userAccount.secret !== secret) {
res.statusCode = 401;
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify({ error: 'Неверный secret' }));
return;
}
if (userAccount.isBanned) {
res.statusCode = 403;
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify({ error: 'Пользователь заблокирован' }));
return;
}
const inText = text;
const params = inText.split(' ');
const cmd = params[0].replace(/^\//, '').toLowerCase();
let responseBody = {};
if (cmd.startsWith('смоук')) {
//const textContent = params.slice(1).join(' ').toLowerCase();
//responseBody = { message: IHABot(textContent) };
} else {
const commands = await getCommandList();
if (!commands.some(command => command === cmd)) {
res.statusCode = 404;
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify({ error: 'Команда не найдена' }));
return;
}
const replyedUserID = params[1] || null;
let replyedUserAccount = replyedUserID ? await users.read(replyedUserID) : null;
console.log({ id: userID, nick: userAccount.nick, text: params.join(' ') });
const modulePath = `./lib/commands/${cmd}.js`;
const mtime = (await stat(modulePath)).mtime;
const { command } = await import(`${modulePath}?${mtime}`);
const originalUserAccount = JSON.stringify(userAccount);
const originalReplyAccount = replyedUserAccount ? JSON.stringify(replyedUserAccount) : null;
const context = {
platform: "web",
text: inText,
cmd: cmd,
args: params.slice(1),
account: userAccount,
};
const responseText = await command(context);
if (JSON.stringify(userAccount) !== originalUserAccount) {
await users.update(userID, userAccount);
}
if (replyedUserAccount && JSON.stringify(replyedUserAccount) !== originalReplyAccount) {
await users.update(replyedUserAccount.id, replyedUserAccount);
}
if (responseText) {
responseBody = { message: responseText };
}
}
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify(responseBody));
} catch (error) {
console.error(error);
res.statusCode = 500;
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify({ error: 'Внутренняя ошибка сервера' }));
}
});
});
const PORT = process.env.PORT || 3333;
server.listen(PORT, () => {
console.log(`Сервер запущен на порту ${PORT}`);
});