blockmine 1.16.1 → 1.16.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,1719 +1,1801 @@
1
- const express = require('express');
2
- const prisma = require('../../lib/prisma');
3
- const path = require('path');
4
- const fs = require('fs/promises');
5
- const fse = require('fs-extra');
6
- const { botManager, pluginManager } = require('../../core/services');
7
- const UserService = require('../../core/UserService');
8
- const commandManager = require('../../core/system/CommandManager');
9
- const NodeRegistry = require('../../core/NodeRegistry');
10
- const { authenticate, authorize } = require('../middleware/auth');
11
- const { encrypt } = require('../../core/utils/crypto');
12
- const { randomUUID } = require('crypto');
13
- const eventGraphsRouter = require('./eventGraphs');
14
- const pluginIdeRouter = require('./pluginIde');
15
-
16
- const multer = require('multer');
17
- const archiver = require('archiver');
18
- const AdmZip = require('adm-zip');
19
- const os = require('os');
20
-
21
- const upload = multer({ storage: multer.memoryStorage() });
22
-
23
- const router = express.Router();
24
-
25
- router.use(authenticate);
26
- router.use('/:botId/event-graphs', eventGraphsRouter);
27
- router.use('/:botId/plugins/ide', pluginIdeRouter);
28
-
29
- async function setupDefaultPermissionsForBot(botId, prismaClient = prisma) {
30
- const initialData = {
31
- groups: ["User", "Admin"],
32
- permissions: [
33
- { name: "admin.*", description: "Все права администратора" },
34
- { name: "admin.cooldown.bypass", description: "Обход кулдауна для админ-команд" },
35
- { name: "user.*", description: "Все права обычного пользователя" },
36
- { name: "user.say", description: "Доступ к простым командам" },
37
- { name: "user.cooldown.bypass", description: "Обход кулдауна для юзер-команд" },
38
- ],
39
- groupPermissions: {
40
- "User": ["user.say"],
41
- "Admin": ["admin.*", "admin.cooldown.bypass", "user.cooldown.bypass", "user.*"]
42
- },
43
- };
44
-
45
- for (const perm of initialData.permissions) {
46
- await prismaClient.permission.upsert({ where: { botId_name: { botId, name: perm.name } }, update: { description: perm.description }, create: { ...perm, botId, owner: 'system' } });
47
- }
48
- for (const groupName of initialData.groups) {
49
- await prismaClient.group.upsert({ where: { botId_name: { botId, name: groupName } }, update: {}, create: { name: groupName, botId, owner: 'system' } });
50
- }
51
- for (const [groupName, permNames] of Object.entries(initialData.groupPermissions)) {
52
- const group = await prismaClient.group.findUnique({ where: { botId_name: { botId, name: groupName } } });
53
- if (group) {
54
- for (const permName of permNames) {
55
- const permission = await prismaClient.permission.findUnique({ where: { botId_name: { botId, name: permName } } });
56
- if (permission) {
57
- await prismaClient.groupPermission.upsert({ where: { groupId_permissionId: { groupId: group.id, permissionId: permission.id } }, update: {}, create: { groupId: group.id, permissionId: permission.id } });
58
- }
59
- }
60
- }
61
- }
62
- console.log(`[Setup] Для бота ID ${botId} созданы группы и права по умолчанию.`);
63
- }
64
-
65
- router.get('/', authorize('bot:list'), async (req, res) => {
66
- try {
67
- const bots = await prisma.bot.findMany({ include: { server: true }, orderBy: { createdAt: 'asc' } });
68
- res.json(bots);
69
- } catch (error) {
70
- console.error("[API /api/bots] Ошибка получения списка ботов:", error);
71
- res.status(500).json({ error: 'Не удалось получить список ботов' });
72
- }
73
- });
74
-
75
- router.get('/state', authorize('bot:list'), (req, res) => {
76
- try {
77
- const state = botManager.getFullState();
78
- res.json(state);
79
- } catch (error) { res.status(500).json({ error: 'Не удалось получить состояние ботов' }); }
80
- });
81
-
82
- router.post('/', authorize('bot:create'), async (req, res) => {
83
- try {
84
- const { username, password, prefix, serverId, note } = req.body;
85
- if (!username || !serverId) return res.status(400).json({ error: 'Имя и сервер обязательны' });
86
-
87
- const data = {
88
- username,
89
- prefix,
90
- note,
91
- serverId: parseInt(serverId, 10),
92
- password: password ? encrypt(password) : null
93
- };
94
-
95
- const newBot = await prisma.bot.create({
96
- data: data,
97
- include: { server: true }
98
- });
99
- await setupDefaultPermissionsForBot(newBot.id);
100
- res.status(201).json(newBot);
101
- } catch (error) {
102
- if (error.code === 'P2002') return res.status(409).json({ error: 'Бот с таким именем уже существует' });
103
- console.error("[API Error] /bots POST:", error);
104
- res.status(500).json({ error: 'Не удалось создать бота' });
105
- }
106
- });
107
-
108
- router.put('/:id', authorize('bot:update'), async (req, res) => {
109
- try {
110
- const {
111
- username, password, prefix, serverId, note, owners,
112
- proxyHost, proxyPort, proxyUsername, proxyPassword
113
- } = req.body;
114
-
115
- let dataToUpdate = {
116
- username,
117
- prefix,
118
- note,
119
- owners,
120
- proxyHost,
121
- proxyPort: proxyPort ? parseInt(proxyPort, 10) : null,
122
- proxyUsername,
123
- };
124
-
125
- if (password) {
126
- dataToUpdate.password = encrypt(password);
127
- }
128
- if (proxyPassword) {
129
- dataToUpdate.proxyPassword = encrypt(proxyPassword);
130
- }
131
-
132
- if (serverId !== undefined && serverId !== '') {
133
- dataToUpdate.serverId = parseInt(serverId, 10);
134
- }
135
-
136
- Object.keys(dataToUpdate).forEach(key => {
137
- if (dataToUpdate[key] === undefined) {
138
- delete dataToUpdate[key];
139
- }
140
- });
141
-
142
- if (dataToUpdate.serverId) {
143
- const serverIdValue = dataToUpdate.serverId;
144
- delete dataToUpdate.serverId;
145
- dataToUpdate.server = { connect: { id: serverIdValue } };
146
- }
147
-
148
- const botId = parseInt(req.params.id, 10);
149
- if (isNaN(botId)) {
150
- return res.status(400).json({ message: 'Неверный ID бота.' });
151
- }
152
-
153
- if (dataToUpdate.username) {
154
- const existingBot = await prisma.bot.findFirst({
155
- where: {
156
- username: dataToUpdate.username,
157
- id: { not: botId }
158
- }
159
- });
160
-
161
- if (existingBot) {
162
- return res.status(400).json({
163
- message: `Бот с именем "${dataToUpdate.username}" уже существует.`
164
- });
165
- }
166
- }
167
-
168
- const updatedBot = await prisma.bot.update({
169
- where: { id: botId },
170
- data: dataToUpdate,
171
- include: {
172
- server: true
173
- }
174
- });
175
-
176
- const botManager = req.app.get('botManager');
177
- botManager.reloadBotConfigInRealTime(botId);
178
-
179
- res.json(updatedBot);
180
- } catch (error) {
181
- console.error('Error updating bot:', error);
182
- console.error('Error details:', {
183
- code: error.code,
184
- meta: error.meta,
185
- message: error.message
186
- });
187
-
188
- if (error.code === 'P2002' && error.meta?.target?.includes('username')) {
189
- return res.status(400).json({
190
- message: 'Бот с таким именем уже существует. Выберите другое имя.'
191
- });
192
- }
193
-
194
- res.status(500).json({ message: `Не удалось обновить бота: ${error.message}` });
195
- }
196
- });
197
-
198
- router.delete('/:id', authorize('bot:delete'), async (req, res) => {
199
- try {
200
- const botId = parseInt(req.params.id, 10);
201
- if (botManager.bots.has(botId)) return res.status(400).json({ error: 'Нельзя удалить запущенного бота' });
202
- await prisma.bot.delete({ where: { id: botId } });
203
- res.status(204).send();
204
- } catch (error) { res.status(500).json({ error: 'Не удалось удалить бота' }); }
205
- });
206
-
207
- router.post('/:id/start', authorize('bot:start_stop'), async (req, res) => {
208
- try {
209
- const botId = parseInt(req.params.id, 10);
210
- const botConfig = await prisma.bot.findUnique({ where: { id: botId }, include: { server: true } });
211
- if (!botConfig) {
212
- return res.status(404).json({ success: false, message: 'Бот не найден' });
213
- }
214
- botManager.startBot(botConfig);
215
- res.status(202).json({ success: true, message: 'Команда на запуск отправлена.' });
216
- } catch (error) {
217
- console.error(`[API] Ошибка запуска бота ${req.params.id}:`, error);
218
- res.status(500).json({ success: false, message: 'Ошибка при запуске бота: ' + error.message });
219
- }
220
- });
221
-
222
- router.post('/:id/stop', authorize('bot:start_stop'), (req, res) => {
223
- try {
224
- const botId = parseInt(req.params.id, 10);
225
- botManager.stopBot(botId);
226
- res.status(202).json({ success: true, message: 'Команда на остановку отправлена.' });
227
- } catch (error) {
228
- console.error(`[API] Ошибка остановки бота ${req.params.id}:`, error);
229
- res.status(500).json({ success: false, message: 'Ошибка при остановке бота: ' + error.message });
230
- }
231
- });
232
-
233
- router.post('/:id/restart', authorize('bot:start_stop'), async (req, res) => {
234
- try {
235
- const botId = parseInt(req.params.id, 10);
236
- botManager.stopBot(botId);
237
- setTimeout(async () => {
238
- const botConfig = await prisma.bot.findUnique({ where: { id: botId }, include: { server: true } });
239
- if (!botConfig) {
240
- return res.status(404).json({ success: false, message: 'Бот не найден' });
241
- }
242
- botManager.startBot(botConfig);
243
- res.status(202).json({ success: true, message: 'Команда на перезапуск отправлена.' });
244
- }, 1000);
245
- } catch (error) {
246
- console.error(`[API] Ошибка перезапуска бота ${req.params.id}:`, error);
247
- res.status(500).json({ success: false, message: 'Ошибка при перезапуске бота: ' + error.message });
248
- }
249
- });
250
-
251
- router.post('/:id/chat', authorize('bot:interact'), (req, res) => {
252
- try {
253
- const botId = parseInt(req.params.id, 10);
254
- const { message } = req.body;
255
- if (!message) return res.status(400).json({ error: 'Сообщение не может быть пустым' });
256
- const result = botManager.sendMessageToBot(botId, message);
257
- if (result.success) res.json({ success: true });
258
- else res.status(404).json(result);
259
- } catch (error) { res.status(500).json({ error: 'Внутренняя ошибка сервера: ' + error.message }); }
260
- });
261
-
262
-
263
- router.get('/servers', authorize('bot:list'), async (req, res) => {
264
- try {
265
- const servers = await prisma.server.findMany();
266
- res.json(servers);
267
- } catch (error) {
268
- console.error("[API /api/bots] Ошибка получения списка серверов:", error);
269
- res.status(500).json({ error: 'Не удалось получить список серверов' });
270
- }
271
- });
272
-
273
- router.get('/:botId/plugins', authorize('plugin:list'), async (req, res) => {
274
- try {
275
- const botId = parseInt(req.params.botId);
276
- const plugins = await prisma.installedPlugin.findMany({ where: { botId } });
277
- res.json(plugins);
278
- } catch (error) { res.status(500).json({ error: 'Не удалось получить плагины бота' }); }
279
- });
280
-
281
- router.post('/:botId/plugins/install/github', authorize('plugin:install'), async (req, res) => {
282
- const { botId } = req.params;
283
- const { repoUrl } = req.body;
284
- try {
285
- const newPlugin = await pluginManager.installFromGithub(parseInt(botId), repoUrl);
286
- res.status(201).json(newPlugin);
287
- } catch (error) {
288
- res.status(500).json({ message: error.message });
289
- }
290
- });
291
-
292
- router.post('/:botId/plugins/install/local', authorize('plugin:install'), async (req, res) => {
293
- const { botId } = req.params;
294
- const { path } = req.body;
295
- try {
296
- const newPlugin = await pluginManager.installFromLocalPath(parseInt(botId), path);
297
- res.status(201).json(newPlugin);
298
- } catch (error) {
299
- res.status(500).json({ message: error.message });
300
- }
301
- });
302
-
303
- router.delete('/:botId/plugins/:pluginId', authorize('plugin:delete'), async (req, res) => {
304
- const { pluginId } = req.params;
305
- try {
306
- await pluginManager.deletePlugin(parseInt(pluginId));
307
- res.status(204).send();
308
- } catch (error) {
309
- res.status(500).json({ message: error.message });
310
- }
311
- });
312
-
313
- router.get('/:botId/plugins/:pluginId/settings', authorize('plugin:settings:view'), async (req, res) => {
314
- try {
315
- const pluginId = parseInt(req.params.pluginId);
316
- const plugin = await prisma.installedPlugin.findUnique({ where: { id: pluginId } });
317
- if (!plugin) return res.status(404).json({ error: 'Установленный плагин не найден' });
318
-
319
- const savedSettings = plugin.settings ? JSON.parse(plugin.settings) : {};
320
- let defaultSettings = {};
321
- const manifest = plugin.manifest ? JSON.parse(plugin.manifest) : {};
322
-
323
- if (manifest.settings) {
324
- for (const key in manifest.settings) {
325
- const config = manifest.settings[key];
326
- if (config.type === 'json_file' && config.defaultPath) {
327
- const configFilePath = path.join(plugin.path, config.defaultPath);
328
- try {
329
- const fileContent = await fs.readFile(configFilePath, 'utf-8');
330
- defaultSettings[key] = JSON.parse(fileContent);
331
- } catch (e) { defaultSettings[key] = {}; }
332
- } else {
333
- try { defaultSettings[key] = JSON.parse(config.default || 'null'); }
334
- catch { defaultSettings[key] = config.default; }
335
- }
336
- }
337
- }
338
- const finalSettings = { ...defaultSettings, ...savedSettings };
339
- res.json(finalSettings);
340
- } catch (error) {
341
- console.error("[API Error] /settings GET:", error);
342
- res.status(500).json({ error: 'Не удалось получить настройки плагина' });
343
- }
344
- });
345
-
346
- router.put('/:botId/plugins/:pluginId', authorize('plugin:settings:edit'), async (req, res) => {
347
- try {
348
- const pluginId = parseInt(req.params.pluginId);
349
- const { isEnabled, settings } = req.body;
350
- const dataToUpdate = {};
351
- if (typeof isEnabled === 'boolean') dataToUpdate.isEnabled = isEnabled;
352
- if (settings) dataToUpdate.settings = JSON.stringify(settings);
353
- if (Object.keys(dataToUpdate).length === 0) return res.status(400).json({ error: "Нет данных для обновления" });
354
- const updated = await prisma.installedPlugin.update({ where: { id: pluginId }, data: dataToUpdate });
355
- res.json(updated);
356
- } catch (error) { res.status(500).json({ error: 'Не удалось обновить плагин' }); }
357
- });
358
-
359
- router.get('/:botId/management-data', authorize('management:view'), async (req, res) => {
360
- try {
361
- const botId = parseInt(req.params.botId, 10);
362
- if (isNaN(botId)) return res.status(400).json({ error: 'Неверный ID бота' });
363
-
364
- const page = parseInt(req.query.page) || 1;
365
- const pageSize = parseInt(req.query.pageSize) || 100;
366
- const searchQuery = req.query.search || '';
367
-
368
- const userSkip = (page - 1) * pageSize;
369
-
370
- const whereClause = {
371
- botId,
372
- };
373
-
374
- if (searchQuery) {
375
- whereClause.username = {
376
- contains: searchQuery,
377
- };
378
- }
379
-
380
- const [groups, allPermissions] = await Promise.all([
381
- prisma.group.findMany({ where: { botId }, include: { permissions: { include: { permission: true } } }, orderBy: { name: 'asc' } }),
382
- prisma.permission.findMany({ where: { botId }, orderBy: { name: 'asc' } })
383
- ]);
384
-
385
- const [users, usersCount] = await Promise.all([
386
- prisma.user.findMany({
387
- where: whereClause,
388
- include: { groups: { include: { group: true } } },
389
- orderBy: { username: 'asc' },
390
- take: pageSize,
391
- skip: userSkip,
392
- }),
393
- prisma.user.count({ where: whereClause })
394
- ]);
395
-
396
- const templatesMap = new Map(commandManager.getCommandTemplates().map(t => [t.name, t]));
397
- let dbCommandsFromDb = await prisma.command.findMany({
398
- where: { botId },
399
- include: {
400
- pluginOwner: {
401
- select: {
402
- id: true,
403
- name: true,
404
- version: true,
405
- sourceType: true
406
- }
407
- }
408
- },
409
- orderBy: [{ owner: 'asc' }, { name: 'asc' }]
410
- });
411
-
412
- const commandsToCreate = [];
413
- for (const template of templatesMap.values()) {
414
- if (!dbCommandsFromDb.some(cmd => cmd.name === template.name)) {
415
- let permissionId = null;
416
- if (template.permissions) {
417
- const permission = await prisma.permission.upsert({
418
- where: { botId_name: { botId, name: template.permissions } },
419
- update: { description: `Авто-создано для команды ${template.name}` },
420
- create: {
421
- botId,
422
- name: template.permissions,
423
- description: `Авто-создано для команды ${template.name}`,
424
- owner: template.owner || 'system',
425
- }
426
- });
427
- permissionId = permission.id;
428
- }
429
-
430
- commandsToCreate.push({
431
- botId,
432
- name: template.name,
433
- isEnabled: template.isActive,
434
- cooldown: template.cooldown,
435
- aliases: JSON.stringify(template.aliases),
436
- description: template.description,
437
- owner: template.owner,
438
- permissionId: permissionId,
439
- allowedChatTypes: JSON.stringify(template.allowedChatTypes),
440
- });
441
- }
442
- }
443
-
444
- if (commandsToCreate.length > 0) {
445
- await prisma.command.createMany({ data: commandsToCreate });
446
- dbCommandsFromDb = await prisma.command.findMany({
447
- where: { botId },
448
- include: {
449
- pluginOwner: {
450
- select: {
451
- id: true,
452
- name: true,
453
- version: true,
454
- sourceType: true
455
- }
456
- }
457
- },
458
- orderBy: [{ owner: 'asc' }, { name: 'asc' }]
459
- });
460
- }
461
-
462
- const finalCommands = dbCommandsFromDb.map(cmd => {
463
- const template = templatesMap.get(cmd.name);
464
- let args = [];
465
-
466
- if (cmd.isVisual) {
467
- try {
468
- args = JSON.parse(cmd.argumentsJson || '[]');
469
- } catch (e) {
470
- console.error(`Error parsing argumentsJson for visual command ${cmd.name} (ID: ${cmd.id}):`, e);
471
- args = [];
472
- }
473
- } else {
474
- if (template && template.args && template.args.length > 0) {
475
- args = template.args;
476
- } else {
477
- try {
478
- args = JSON.parse(cmd.argumentsJson || '[]');
479
- } catch (e) {
480
- args = [];
481
- }
482
- }
483
- }
484
-
485
- return {
486
- ...cmd,
487
- args: args,
488
- aliases: JSON.parse(cmd.aliases || '[]'),
489
- allowedChatTypes: JSON.parse(cmd.allowedChatTypes || '[]'),
490
- };
491
- })
492
-
493
- res.json({
494
- groups,
495
- permissions: allPermissions,
496
- users: {
497
- items: users,
498
- total: usersCount,
499
- page,
500
- pageSize,
501
- totalPages: Math.ceil(usersCount / pageSize),
502
- },
503
- commands: finalCommands
504
- });
505
-
506
- } catch (error) {
507
- console.error(`[API Error] /management-data for bot ${req.params.botId}:`, error);
508
- res.status(500).json({ error: 'Не удалось загрузить данные управления' });
509
- }
510
- });
511
-
512
- router.put('/:botId/commands/:commandId', authorize('management:edit'), async (req, res) => {
513
- try {
514
- const commandId = parseInt(req.params.commandId, 10);
515
- const { name, description, cooldown, aliases, permissionId, allowedChatTypes, isEnabled, argumentsJson, graphJson, pluginOwnerId } = req.body;
516
-
517
- const dataToUpdate = {};
518
- if (name !== undefined) dataToUpdate.name = name;
519
- if (description !== undefined) dataToUpdate.description = description;
520
- if (cooldown !== undefined) dataToUpdate.cooldown = parseInt(cooldown, 10);
521
- if (aliases !== undefined) dataToUpdate.aliases = Array.isArray(aliases) ? JSON.stringify(aliases) : aliases;
522
- if (permissionId !== undefined) dataToUpdate.permissionId = permissionId ? parseInt(permissionId, 10) : null;
523
- if (allowedChatTypes !== undefined) dataToUpdate.allowedChatTypes = Array.isArray(allowedChatTypes) ? JSON.stringify(allowedChatTypes) : allowedChatTypes;
524
- if (isEnabled !== undefined) dataToUpdate.isEnabled = isEnabled;
525
- if (argumentsJson !== undefined) dataToUpdate.argumentsJson = Array.isArray(argumentsJson) ? JSON.stringify(argumentsJson) : argumentsJson;
526
- if (graphJson !== undefined) dataToUpdate.graphJson = graphJson;
527
- if (pluginOwnerId !== undefined) dataToUpdate.pluginOwnerId = pluginOwnerId;
528
-
529
- const updatedCommand = await prisma.command.update({
530
- where: { id: commandId },
531
- data: dataToUpdate,
532
- });
533
-
534
- if (graphJson && updatedCommand.pluginOwnerId) {
535
- try {
536
- const plugin = await prisma.installedPlugin.findUnique({
537
- where: { id: updatedCommand.pluginOwnerId }
538
- });
539
-
540
- if (plugin) {
541
- const graphDir = path.join(plugin.path, 'graph');
542
- await fse.mkdir(graphDir, { recursive: true });
543
-
544
- const graphFile = path.join(graphDir, `${updatedCommand.name}.json`);
545
- await fse.writeJson(graphFile, JSON.parse(graphJson), { spaces: 2 });
546
- console.log(`[API] Граф команды ${updatedCommand.name} сохранен в ${graphFile}`);
547
- }
548
- } catch (error) {
549
- console.error(`[API] Ошибка сохранения графа в папку плагина:`, error);
550
- }
551
- }
552
-
553
- res.json(updatedCommand);
554
- } catch (error) {
555
- console.error(`[API Error] /commands/:commandId PUT:`, error);
556
- res.status(500).json({ error: 'Failed to update command' });
557
- }
558
- });
559
-
560
- router.post('/:botId/groups', authorize('management:edit'), async (req, res) => {
561
- try {
562
- const botId = parseInt(req.params.botId);
563
- const { name, permissionIds } = req.body;
564
- if (!name) return res.status(400).json({ error: "Имя группы обязательно" });
565
-
566
- const newGroup = await prisma.group.create({
567
- data: {
568
- name,
569
- botId,
570
- owner: 'admin',
571
- permissions: { create: (permissionIds || []).map(id => ({ permissionId: id })) }
572
- }
573
- });
574
-
575
- botManager.reloadBotConfigInRealTime(botId);
576
-
577
- res.status(201).json(newGroup);
578
- } catch (error) {
579
- if (error.code === 'P2002') return res.status(409).json({ error: 'Группа с таким именем уже существует для этого бота.' });
580
- res.status(500).json({ error: 'Не удалось создать группу.' });
581
- }
582
- });
583
-
584
- router.put('/:botId/groups/:groupId', authorize('management:edit'), async (req, res) => {
585
- try {
586
- const botId = parseInt(req.params.botId, 10);
587
- const groupId = parseInt(req.params.groupId);
588
- const { name, permissionIds } = req.body;
589
- if (!name) return res.status(400).json({ error: "Имя группы обязательно" });
590
-
591
- const usersInGroup = await prisma.user.findMany({
592
- where: { botId, groups: { some: { groupId } } },
593
- select: { username: true }
594
- });
595
-
596
- await prisma.$transaction(async (tx) => {
597
- await tx.group.update({ where: { id: groupId }, data: { name } });
598
- await tx.groupPermission.deleteMany({ where: { groupId } });
599
- if (permissionIds && permissionIds.length > 0) {
600
- await tx.groupPermission.createMany({
601
- data: permissionIds.map(pid => ({ groupId, permissionId: pid })),
602
- });
603
- }
604
- });
605
-
606
- for (const user of usersInGroup) {
607
- botManager.invalidateUserCache(botId, user.username);
608
- }
609
-
610
- botManager.reloadBotConfigInRealTime(botId);
611
-
612
- res.status(200).send();
613
- } catch (error) {
614
- if (error.code === 'P2002') return res.status(409).json({ error: 'Группа с таким именем уже существует для этого бота.' });
615
- res.status(500).json({ error: 'Не удалось обновить группу.' });
616
- }
617
- });
618
-
619
- router.delete('/:botId/groups/:groupId', authorize('management:edit'), async (req, res) => {
620
- try {
621
- const botId = parseInt(req.params.botId, 10);
622
- const groupId = parseInt(req.params.groupId);
623
- const group = await prisma.group.findUnique({ where: { id: groupId } });
624
- if (group && group.owner !== 'admin') {
625
- return res.status(403).json({ error: `Нельзя удалить группу с источником "${group.owner}".` });
626
- }
627
- await prisma.group.delete({ where: { id: groupId } });
628
- botManager.reloadBotConfigInRealTime(botId);
629
-
630
- res.status(204).send();
631
- } catch (error) { res.status(500).json({ error: 'Не удалось удалить группу.' }); }
632
- });
633
-
634
- router.post('/:botId/permissions', authorize('management:edit'), async (req, res) => {
635
- try {
636
- const botId = parseInt(req.params.botId);
637
- const { name, description } = req.body;
638
- if (!name) return res.status(400).json({ error: 'Имя права обязательно' });
639
- const newPermission = await prisma.permission.create({
640
- data: { name, description, botId, owner: 'admin' }
641
- });
642
-
643
- botManager.reloadBotConfigInRealTime(botId);
644
-
645
- res.status(201).json(newPermission);
646
- } catch (error) {
647
- if (error.code === 'P2002') return res.status(409).json({ error: 'Право с таким именем уже существует для этого бота.' });
648
- res.status(500).json({ error: 'Не удалось создать право.' });
649
- }
650
- });
651
-
652
- router.put('/:botId/users/:userId', authorize('management:edit'), async (req, res) => {
653
- try {
654
- const botId = parseInt(req.params.botId, 10);
655
- const userId = parseInt(req.params.userId, 10);
656
- const { isBlacklisted, groupIds } = req.body;
657
-
658
- const updateData = {};
659
- if (typeof isBlacklisted === 'boolean') {
660
- updateData.isBlacklisted = isBlacklisted;
661
- }
662
-
663
- if (Array.isArray(groupIds)) {
664
- await prisma.userGroup.deleteMany({ where: { userId } });
665
- updateData.groups = {
666
- create: groupIds.map(gid => ({ groupId: gid })),
667
- };
668
- }
669
-
670
- const updatedUser = await prisma.user.update({
671
- where: { id: userId },
672
- data: updateData,
673
- include: { groups: true }
674
- });
675
-
676
- botManager.invalidateUserCache(botId, updatedUser.username);
677
-
678
- UserService.clearCache(updatedUser.username, botId);
679
-
680
- res.json(updatedUser);
681
-
682
- } catch (error) {
683
- console.error(`[API Error] /users/:userId PUT:`, error);
684
- res.status(500).json({ error: 'Не удалось обновить пользователя' });
685
- }
686
- });
687
-
688
- router.post('/start-all', authorize('bot:start_stop'), async (req, res) => {
689
- try {
690
- console.log('[API] Получен запрос на запуск всех ботов.');
691
- const allBots = await prisma.bot.findMany({ include: { server: true } });
692
- let startedCount = 0;
693
- for (const botConfig of allBots) {
694
- if (!botManager.bots.has(botConfig.id)) {
695
- await botManager.startBot(botConfig);
696
- startedCount++;
697
- }
698
- }
699
- res.json({ success: true, message: `Запущено ${startedCount} ботов.` });
700
- } catch (error) {
701
- console.error('[API Error] /start-all:', error);
702
- res.status(500).json({ error: 'Произошла ошибка при массовом запуске ботов.' });
703
- }
704
- });
705
-
706
- router.post('/stop-all', authorize('bot:start_stop'), (req, res) => {
707
- try {
708
- console.log('[API] Получен запрос на остановку всех ботов.');
709
- const botIds = Array.from(botManager.bots.keys());
710
- let stoppedCount = 0;
711
- for (const botId of botIds) {
712
- botManager.stopBot(botId);
713
- stoppedCount++;
714
- }
715
- res.json({ success: true, message: `Остановлено ${stoppedCount} ботов.` });
716
- } catch (error) {
717
- console.error('[API Error] /stop-all:', error);
718
- res.status(500).json({ error: 'Произошла ошибка при массовой остановке ботов.' });
719
- }
720
- });
721
-
722
- router.get('/:id/settings/all', authorize('bot:update'), async (req, res) => {
723
- try {
724
- const botId = parseInt(req.params.id, 10);
725
-
726
- const bot = await prisma.bot.findUnique({
727
- where: { id: botId },
728
- include: {
729
- server: true,
730
- installedPlugins: {
731
- orderBy: { name: 'asc' }
732
- }
733
- }
734
- });
735
-
736
- if (!bot) {
737
- return res.status(404).json({ error: 'Бот не найден' });
738
- }
739
-
740
- const allSettings = {
741
- bot: {
742
- id: bot.id,
743
- username: bot.username,
744
- prefix: bot.prefix,
745
- note: bot.note,
746
- owners: bot.owners,
747
- serverId: bot.serverId,
748
- proxyHost: bot.proxyHost,
749
- proxyPort: bot.proxyPort,
750
- proxyUsername: bot.proxyUsername,
751
- },
752
- plugins: []
753
- };
754
-
755
- const pluginSettingsPromises = bot.installedPlugins.map(async (plugin) => {
756
- const manifest = plugin.manifest ? JSON.parse(plugin.manifest) : {};
757
-
758
- if (!manifest.settings || Object.keys(manifest.settings).length === 0) {
759
- return null;
760
- }
761
-
762
- const savedSettings = plugin.settings ? JSON.parse(plugin.settings) : {};
763
- let defaultSettings = {};
764
-
765
- for (const key in manifest.settings) {
766
- const config = manifest.settings[key];
767
- if (config.type === 'json_file' && config.defaultPath) {
768
- const configFilePath = path.join(plugin.path, config.defaultPath);
769
- try {
770
- const fileContent = await fs.readFile(configFilePath, 'utf-8');
771
- defaultSettings[key] = JSON.parse(fileContent);
772
- } catch (e) { defaultSettings[key] = {}; }
773
- } else {
774
- try { defaultSettings[key] = JSON.parse(config.default || 'null'); }
775
- catch { defaultSettings[key] = config.default; }
776
- }
777
- }
778
-
779
- return {
780
- id: plugin.id,
781
- name: plugin.name,
782
- description: plugin.description,
783
- isEnabled: plugin.isEnabled,
784
- manifest: manifest,
785
- settings: { ...defaultSettings, ...savedSettings }
786
- };
787
- });
788
-
789
- allSettings.plugins = (await Promise.all(pluginSettingsPromises)).filter(Boolean);
790
-
791
- res.json(allSettings);
792
-
793
- } catch (error) {
794
- console.error("[API Error] /settings/all GET:", error);
795
- res.status(500).json({ error: 'Не удалось загрузить все настройки' });
796
- }
797
- });
798
-
799
- const nodeRegistry = require('../../core/NodeRegistry');
800
-
801
- router.get('/:botId/visual-editor/nodes', authorize('management:view'), (req, res) => {
802
- try {
803
- const { graphType } = req.query;
804
- const nodesByCategory = nodeRegistry.getNodesByCategory(graphType);
805
- res.json(nodesByCategory);
806
- } catch (error) {
807
- console.error('[API Error] /visual-editor/nodes GET:', error);
808
- res.status(500).json({ error: 'Failed to get available nodes' });
809
- }
810
- });
811
-
812
- router.get('/:botId/visual-editor/node-config', authorize('management:view'), (req, res) => {
813
- try {
814
- const { types } = req.query;
815
- if (!types) {
816
- return res.status(400).json({ error: 'Node types must be provided' });
817
- }
818
- const typeArray = Array.isArray(types) ? types : [types];
819
- const config = nodeRegistry.getNodesByTypes(typeArray);
820
- res.json(config);
821
- } catch (error) {
822
- console.error('[API Error] /visual-editor/node-config GET:', error);
823
- res.status(500).json({ error: 'Failed to get node configuration' });
824
- }
825
- });
826
-
827
- router.get('/:botId/visual-editor/permissions', authorize('management:view'), async (req, res) => {
828
- try {
829
- const botId = parseInt(req.params.botId, 10);
830
- const permissions = await prisma.permission.findMany({
831
- where: { botId },
832
- orderBy: { name: 'asc' }
833
- });
834
- res.json(permissions);
835
- } catch (error) {
836
- console.error('[API Error] /visual-editor/permissions GET:', error);
837
- res.status(500).json({ error: 'Failed to get permissions' });
838
- }
839
- });
840
-
841
- router.post('/:botId/commands/visual', authorize('management:edit'), async (req, res) => {
842
- try {
843
- const botId = parseInt(req.params.botId, 10);
844
- const {
845
- name,
846
- description,
847
- aliases = [],
848
- permissionId,
849
- cooldown = 0,
850
- allowedChatTypes = ['chat', 'private'],
851
- argumentsJson = '[]',
852
- graphJson = 'null'
853
- } = req.body;
854
-
855
- if (!name) {
856
- return res.status(400).json({ error: 'Command name is required' });
857
- }
858
-
859
- const newCommand = await prisma.command.create({
860
- data: {
861
- botId,
862
- name,
863
- description,
864
- aliases: JSON.stringify(aliases),
865
- permissionId: permissionId || null,
866
- cooldown,
867
- allowedChatTypes: JSON.stringify(allowedChatTypes),
868
- isVisual: true,
869
- argumentsJson,
870
- graphJson,
871
- pluginOwnerId: null
872
- }
873
- });
874
-
875
- botManager.reloadBotConfigInRealTime(botId);
876
- res.status(201).json(newCommand);
877
- } catch (error) {
878
- if (error.code === 'P2002') {
879
- return res.status(409).json({ error: 'Command with this name already exists' });
880
- }
881
- console.error('[API Error] /commands/visual POST:', error);
882
- res.status(500).json({ error: 'Failed to create visual command' });
883
- }
884
- });
885
-
886
- router.put('/:botId/commands/:commandId/visual', authorize('management:edit'), async (req, res) => {
887
- try {
888
- const botId = parseInt(req.params.botId, 10);
889
- const commandId = parseInt(req.params.commandId, 10);
890
- const {
891
- name,
892
- description,
893
- aliases,
894
- permissionId,
895
- cooldown,
896
- allowedChatTypes,
897
- argumentsJson,
898
- graphJson
899
- } = req.body;
900
-
901
- const dataToUpdate = { isVisual: true };
902
-
903
- if (name) dataToUpdate.name = name;
904
- if (description !== undefined) dataToUpdate.description = description;
905
- if (Array.isArray(aliases)) dataToUpdate.aliases = JSON.stringify(aliases);
906
- if (permissionId !== undefined) dataToUpdate.permissionId = permissionId || null;
907
- if (typeof cooldown === 'number') dataToUpdate.cooldown = cooldown;
908
- if (Array.isArray(allowedChatTypes)) dataToUpdate.allowedChatTypes = JSON.stringify(allowedChatTypes);
909
- if (argumentsJson !== undefined) dataToUpdate.argumentsJson = argumentsJson;
910
- if (graphJson !== undefined) dataToUpdate.graphJson = graphJson;
911
-
912
- const updatedCommand = await prisma.command.update({
913
- where: { id: commandId, botId },
914
- data: dataToUpdate
915
- });
916
-
917
- if (graphJson && updatedCommand.pluginOwnerId) {
918
- try {
919
- const plugin = await prisma.installedPlugin.findUnique({
920
- where: { id: updatedCommand.pluginOwnerId }
921
- });
922
-
923
- if (plugin) {
924
- const graphDir = path.join(plugin.path, 'graph');
925
- await fse.mkdir(graphDir, { recursive: true });
926
-
927
- const graphFile = path.join(graphDir, `${updatedCommand.name}.json`);
928
- await fse.writeJson(graphFile, JSON.parse(graphJson), { spaces: 2 });
929
- console.log(`[API] Граф команды ${updatedCommand.name} сохранен в ${graphFile}`);
930
- }
931
- } catch (error) {
932
- console.error(`[API] Ошибка сохранения графа в папку плагина:`, error);
933
- }
934
- }
935
-
936
- botManager.reloadBotConfigInRealTime(botId);
937
- res.json(updatedCommand);
938
- } catch (error) {
939
- if (error.code === 'P2002') {
940
- return res.status(409).json({ error: 'Command with this name already exists' });
941
- }
942
- console.error('[API Error] /commands/:commandId/visual PUT:', error);
943
- res.status(500).json({ error: 'Failed to update visual command' });
944
- }
945
- });
946
-
947
- router.get('/:botId/commands/:commandId/export', authorize('management:view'), async (req, res) => {
948
- try {
949
- const botId = parseInt(req.params.botId, 10);
950
- const commandId = parseInt(req.params.commandId, 10);
951
-
952
- const command = await prisma.command.findUnique({
953
- where: { id: commandId, botId: botId },
954
- });
955
-
956
- if (!command) {
957
- return res.status(404).json({ error: 'Command not found' });
958
- }
959
-
960
- const exportData = {
961
- version: '1.0',
962
- type: 'command',
963
- ...command
964
- };
965
-
966
- delete exportData.id;
967
- delete exportData.botId;
968
-
969
- res.json(exportData);
970
- } catch (error) {
971
- console.error('Failed to export command:', error);
972
- res.status(500).json({ error: 'Failed to export command' });
973
- }
974
- });
975
-
976
- router.post('/:botId/commands/import', authorize('management:edit'), async (req, res) => {
977
- try {
978
- const botId = parseInt(req.params.botId, 10);
979
- const importData = req.body;
980
-
981
- if (importData.type !== 'command') {
982
- return res.status(400).json({ error: 'Invalid file type. Expected "command".' });
983
- }
984
-
985
- let commandName = importData.name;
986
- let counter = 1;
987
-
988
- while (await prisma.command.findFirst({ where: { botId, name: commandName } })) {
989
- commandName = `${importData.name}_imported_${counter}`;
990
- counter++;
991
- }
992
-
993
- let finalGraphJson = importData.graphJson;
994
-
995
- if (finalGraphJson && finalGraphJson !== 'null') {
996
- const graph = JSON.parse(finalGraphJson);
997
- const nodeIdMap = new Map();
998
-
999
- if (graph.nodes) {
1000
- graph.nodes.forEach(node => {
1001
- const oldId = node.id;
1002
- const newId = `${node.type}-${randomUUID()}`;
1003
- nodeIdMap.set(oldId, newId);
1004
- node.id = newId;
1005
- });
1006
- }
1007
-
1008
- if (graph.connections) {
1009
- graph.connections.forEach(conn => {
1010
- conn.id = `edge-${randomUUID()}`;
1011
- conn.sourceNodeId = nodeIdMap.get(conn.sourceNodeId) || conn.sourceNodeId;
1012
- conn.targetNodeId = nodeIdMap.get(conn.targetNodeId) || conn.targetNodeId;
1013
- });
1014
- }
1015
-
1016
- finalGraphJson = JSON.stringify(graph);
1017
- }
1018
-
1019
- const newCommand = await prisma.command.create({
1020
- data: {
1021
- botId: botId,
1022
- name: commandName,
1023
- description: importData.description,
1024
- aliases: importData.aliases,
1025
- permissionId: null,
1026
- cooldown: importData.cooldown,
1027
- allowedChatTypes: importData.allowedChatTypes,
1028
- isVisual: importData.isVisual,
1029
- isEnabled: importData.isEnabled,
1030
- argumentsJson: importData.argumentsJson,
1031
- graphJson: finalGraphJson,
1032
- owner: 'visual_editor',
1033
- }
1034
- });
1035
-
1036
- botManager.reloadBotConfigInRealTime(botId);
1037
- res.status(201).json(newCommand);
1038
- } catch (error) {
1039
- console.error("Failed to import command:", error);
1040
- res.status(500).json({ error: 'Failed to import command' });
1041
- }
1042
- });
1043
-
1044
- router.post('/:botId/commands', authorize('management:edit'), async (req, res) => {
1045
- try {
1046
- const botId = parseInt(req.params.botId, 10);
1047
- const {
1048
- name,
1049
- description,
1050
- aliases = [],
1051
- permissionId,
1052
- cooldown = 0,
1053
- allowedChatTypes = ['chat', 'private'],
1054
- isVisual = false,
1055
- argumentsJson = '[]',
1056
- graphJson = 'null'
1057
- } = req.body;
1058
-
1059
- if (!name) {
1060
- return res.status(400).json({ error: 'Command name is required' });
1061
- }
1062
-
1063
- const newCommand = await prisma.command.create({
1064
- data: {
1065
- botId,
1066
- name,
1067
- description,
1068
- aliases: JSON.stringify(aliases),
1069
- permissionId: permissionId || null,
1070
- cooldown,
1071
- allowedChatTypes: JSON.stringify(allowedChatTypes),
1072
- isVisual,
1073
- argumentsJson,
1074
- graphJson,
1075
- owner: isVisual ? 'visual_editor' : 'manual',
1076
- pluginOwnerId: null
1077
- }
1078
- });
1079
-
1080
- if (graphJson && graphJson !== 'null' && req.body.pluginOwnerId) {
1081
- try {
1082
- const plugin = await prisma.installedPlugin.findUnique({
1083
- where: { id: req.body.pluginOwnerId }
1084
- });
1085
-
1086
- if (plugin) {
1087
- const graphDir = path.join(plugin.path, 'graph');
1088
- await fse.mkdir(graphDir, { recursive: true });
1089
-
1090
- const graphFile = path.join(graphDir, `${name}.json`);
1091
- await fse.writeJson(graphFile, JSON.parse(graphJson), { spaces: 2 });
1092
- console.log(`[API] Граф команды ${name} сохранен в ${graphFile}`);
1093
- }
1094
- } catch (error) {
1095
- console.error(`[API] Ошибка сохранения графа в папку плагина:`, error);
1096
- }
1097
- }
1098
-
1099
- botManager.reloadBotConfigInRealTime(botId);
1100
- res.status(201).json(newCommand);
1101
- } catch (error) {
1102
- if (error.code === 'P2002') {
1103
- return res.status(409).json({ error: 'Command with this name already exists' });
1104
- }
1105
- console.error('[API Error] /commands POST:', error);
1106
- res.status(500).json({ error: 'Failed to create command' });
1107
- }
1108
- });
1109
-
1110
- router.delete('/:botId/commands/:commandId', authorize('management:edit'), async (req, res) => {
1111
- try {
1112
- const botId = parseInt(req.params.botId, 10);
1113
- const commandId = parseInt(req.params.commandId, 10);
1114
-
1115
- await prisma.command.delete({
1116
- where: { id: commandId, botId: botId },
1117
- });
1118
-
1119
- botManager.reloadBotConfigInRealTime(botId);
1120
- res.status(204).send();
1121
- } catch (error) {
1122
- console.error(`[API Error] /commands/:commandId DELETE:`, error);
1123
- res.status(500).json({ error: 'Failed to delete command' });
1124
- }
1125
- });
1126
-
1127
- router.get('/:botId/event-graphs/:graphId', authorize('management:view'), async (req, res) => {
1128
- try {
1129
- const botId = parseInt(req.params.botId, 10);
1130
- const graphId = parseInt(req.params.graphId, 10);
1131
-
1132
- const eventGraph = await prisma.eventGraph.findUnique({
1133
- where: { id: graphId, botId },
1134
- include: { triggers: true },
1135
- });
1136
-
1137
- if (!eventGraph) {
1138
- return res.status(404).json({ error: 'Граф события не найден' });
1139
- }
1140
-
1141
- res.json(eventGraph);
1142
- } catch (error) {
1143
- console.error(`[API Error] /event-graphs/:graphId GET:`, error);
1144
- res.status(500).json({ error: 'Не удалось получить граф события' });
1145
- }
1146
- });
1147
-
1148
- router.post('/:botId/event-graphs', authorize('management:edit'), async (req, res) => {
1149
- try {
1150
- const botId = parseInt(req.params.botId, 10);
1151
- const { name, description, graphJson, variables, eventType, isEnabled = true } = req.body;
1152
-
1153
- if (!name || typeof name !== 'string' || name.trim() === '') {
1154
- return res.status(400).json({ error: 'Имя графа обязательно и должно быть непустой строкой' });
1155
- }
1156
-
1157
- let graphJsonString;
1158
- if (graphJson) {
1159
- if (typeof graphJson === 'string') {
1160
- graphJsonString = graphJson;
1161
- } else {
1162
- graphJsonString = JSON.stringify(graphJson);
1163
- }
1164
- } else {
1165
- graphJsonString = JSON.stringify({
1166
- nodes: [],
1167
- connections: []
1168
- });
1169
- }
1170
-
1171
- console.log('[API] Final graphJsonString:', graphJsonString);
1172
-
1173
- let eventTypes = [];
1174
- try {
1175
- const parsedGraph = JSON.parse(graphJsonString);
1176
- if (parsedGraph.nodes && Array.isArray(parsedGraph.nodes)) {
1177
- const eventNodes = parsedGraph.nodes.filter(node => node.type && node.type.startsWith('event:'));
1178
- eventTypes = [...new Set(eventNodes.map(node => node.type.split(':')[1]))];
1179
- }
1180
- } catch (error) {
1181
- console.warn('[API] Не удалось извлечь типы событий из графа:', error.message);
1182
- }
1183
-
1184
- const newEventGraph = await prisma.eventGraph.create({
1185
- data: {
1186
- botId,
1187
- name: name.trim(),
1188
- description: description || '',
1189
- isEnabled: isEnabled,
1190
- graphJson: graphJsonString,
1191
- variables: variables || '[]',
1192
- eventType: eventType || 'custom',
1193
- triggers: {
1194
- create: eventTypes.map(eventType => ({ eventType }))
1195
- }
1196
- },
1197
- include: { triggers: true }
1198
- });
1199
-
1200
- console.log('[API] Created event graph:', newEventGraph);
1201
- res.status(201).json(newEventGraph);
1202
- } catch (error) {
1203
- if (error.code === 'P2002') {
1204
- return res.status(409).json({ error: 'Граф событий с таким именем уже существует' });
1205
- }
1206
- console.error(`[API Error] /event-graphs POST:`, error);
1207
- res.status(500).json({ error: 'Не удалось создать граф событий' });
1208
- }
1209
- });
1210
-
1211
- router.delete('/:botId/event-graphs/:graphId', authorize('management:edit'), async (req, res) => {
1212
- try {
1213
- const botId = parseInt(req.params.botId, 10);
1214
- const graphId = parseInt(req.params.graphId, 10);
1215
-
1216
- await prisma.eventGraph.delete({
1217
- where: { id: graphId, botId: botId },
1218
- });
1219
-
1220
- res.status(204).send();
1221
- } catch (error) {
1222
- console.error(`[API Error] /event-graphs/:graphId DELETE:`, error);
1223
- res.status(500).json({ error: 'Не удалось удалить граф событий' });
1224
- }
1225
- });
1226
-
1227
- router.put('/:botId/event-graphs/:graphId', authorize('management:edit'), async (req, res) => {
1228
- const { botId, graphId } = req.params;
1229
- const { name, isEnabled, graphJson, variables, pluginOwnerId } = req.body;
1230
-
1231
- if (!name || typeof name !== 'string' || name.trim() === '') {
1232
- return res.status(400).json({ error: 'Поле name обязательно и должно быть непустой строкой.' });
1233
- }
1234
-
1235
- if (typeof isEnabled !== 'boolean') {
1236
- return res.status(400).json({ error: 'Поле isEnabled должно быть true или false.' });
1237
- }
1238
-
1239
- try {
1240
- const dataToUpdate = {
1241
- name: name.trim(),
1242
- isEnabled,
1243
- };
1244
-
1245
- if (graphJson !== undefined) {
1246
- dataToUpdate.graphJson = graphJson;
1247
- }
1248
-
1249
- if (variables !== undefined) {
1250
- dataToUpdate.variables = Array.isArray(variables) ? JSON.stringify(variables) : variables;
1251
- }
1252
-
1253
- if (pluginOwnerId !== undefined) {
1254
- dataToUpdate.pluginOwnerId = pluginOwnerId;
1255
- }
1256
-
1257
- const updatedGraph = await prisma.eventGraph.update({
1258
- where: { id: parseInt(graphId), botId: parseInt(botId) },
1259
- data: dataToUpdate
1260
- });
1261
-
1262
- res.json(updatedGraph);
1263
- } catch (error) {
1264
- console.error(`[API Error] /event-graphs/:graphId PUT:`, error);
1265
- res.status(500).json({ error: 'Ошибка при обновлении графа событий.' });
1266
- }
1267
- });
1268
-
1269
- router.post('/:botId/visual-editor/save', authorize('management:edit'), async (req, res) => {
1270
- });
1271
-
1272
- router.get('/:botId/ui-extensions', authorize('plugin:list'), async (req, res) => {
1273
- try {
1274
- const botId = parseInt(req.params.botId, 10);
1275
- const enabledPlugins = await prisma.installedPlugin.findMany({
1276
- where: { botId: botId, isEnabled: true }
1277
- });
1278
-
1279
- const extensions = [];
1280
- for (const plugin of enabledPlugins) {
1281
- if (plugin.manifest) {
1282
- try {
1283
- const manifest = JSON.parse(plugin.manifest);
1284
- if (manifest.uiExtensions && Array.isArray(manifest.uiExtensions)) {
1285
- manifest.uiExtensions.forEach(ext => {
1286
- extensions.push({
1287
- pluginName: plugin.name,
1288
- ...ext
1289
- });
1290
- });
1291
- }
1292
- } catch (e) {
1293
- console.error(`Ошибка парсинга манифеста для плагина ${plugin.name}:`, e);
1294
- }
1295
- }
1296
- }
1297
- res.json(extensions);
1298
- } catch (error) {
1299
- res.status(500).json({ error: 'Не удалось получить расширения интерфейса' });
1300
- }
1301
- });
1302
-
1303
- router.get('/:botId/plugins/:pluginName/ui-content/:path', authorize('plugin:list'), async (req, res) => {
1304
- const { botId, pluginName, path: uiPath } = req.params;
1305
- const numericBotId = parseInt(botId, 10);
1306
-
1307
- try {
1308
- const plugin = await prisma.installedPlugin.findFirst({
1309
- where: { botId: numericBotId, name: pluginName, isEnabled: true }
1310
- });
1311
-
1312
- if (!plugin) {
1313
- return res.status(404).json({ error: `Активный плагин "${pluginName}" не найден для этого бота.` });
1314
- }
1315
-
1316
- const manifest = plugin.manifest ? JSON.parse(plugin.manifest) : {};
1317
- const savedSettings = plugin.settings ? JSON.parse(plugin.settings) : {};
1318
- const defaultSettings = {};
1319
-
1320
- if (manifest.settings) {
1321
- for (const key in manifest.settings) {
1322
- const config = manifest.settings[key];
1323
- if (config.type === 'json_file' && config.defaultPath) {
1324
- const configFilePath = path.join(plugin.path, config.defaultPath);
1325
- try {
1326
- const fileContent = await fs.readFile(configFilePath, 'utf-8');
1327
- defaultSettings[key] = JSON.parse(fileContent);
1328
- } catch (e) { defaultSettings[key] = {}; }
1329
- } else {
1330
- try { defaultSettings[key] = JSON.parse(config.default || 'null'); }
1331
- catch { defaultSettings[key] = config.default; }
1332
- }
1333
- }
1334
- }
1335
- const finalSettings = { ...defaultSettings, ...savedSettings };
1336
-
1337
- const mainFilePath = manifest.main || 'index.js';
1338
- const pluginEntryPoint = path.join(plugin.path, mainFilePath);
1339
-
1340
- delete require.cache[require.resolve(pluginEntryPoint)];
1341
- const pluginModule = require(pluginEntryPoint);
1342
-
1343
- if (typeof pluginModule.getUiPageContent !== 'function') {
1344
- return res.status(501).json({ error: `Плагин "${pluginName}" не предоставляет кастомный UI контент.` });
1345
- }
1346
-
1347
- const botProcess = botManager.bots.get(numericBotId);
1348
- const botApi = botProcess ? botProcess.api : null;
1349
-
1350
- const content = await pluginModule.getUiPageContent({
1351
- path: uiPath,
1352
- bot: botApi,
1353
- botId: numericBotId,
1354
- settings: finalSettings
1355
- });
1356
-
1357
- if (content === null) {
1358
- return res.status(404).json({ error: `Для пути "${uiPath}" не найдено содержимого в плагине "${pluginName}".` });
1359
- }
1360
-
1361
- res.json(content);
1362
-
1363
- } catch (error) {
1364
- console.error(`[UI Content] Ошибка при получении контента для плагина "${pluginName}":`, error);
1365
- res.status(500).json({ error: error.message || 'Внутренняя ошибка сервера.' });
1366
- }
1367
- });
1368
-
1369
-
1370
- router.post('/:botId/plugins/:pluginName/action', authorize('plugin:list'), async (req, res) => {
1371
- const { botId, pluginName } = req.params;
1372
- const { actionName, payload } = req.body;
1373
- const numericBotId = parseInt(botId, 10);
1374
-
1375
- if (!actionName) {
1376
- return res.status(400).json({ error: 'Необходимо указать "actionName".' });
1377
- }
1378
-
1379
- try {
1380
- const botProcess = botManager.bots.get(numericBotId);
1381
-
1382
- if (!botProcess) {
1383
- return res.status(404).json({ error: 'Бот не найден или не запущен.' });
1384
- }
1385
-
1386
- const plugin = await prisma.installedPlugin.findFirst({
1387
- where: { botId: numericBotId, name: pluginName, isEnabled: true }
1388
- });
1389
-
1390
- if (!plugin) {
1391
- return res.status(404).json({ error: `Активный плагин с таким именем "${pluginName}" не найден.` });
1392
- }
1393
-
1394
- const manifest = plugin.manifest ? JSON.parse(plugin.manifest) : {};
1395
- const savedSettings = plugin.settings ? JSON.parse(plugin.settings) : {};
1396
- const defaultSettings = {};
1397
-
1398
- if (manifest.settings) {
1399
- for (const key in manifest.settings) {
1400
- const config = manifest.settings[key];
1401
- if (config.type === 'json_file' && config.defaultPath) {
1402
- const configFilePath = path.join(plugin.path, config.defaultPath);
1403
- try {
1404
- const fileContent = await fs.readFile(configFilePath, 'utf-8');
1405
- defaultSettings[key] = JSON.parse(fileContent);
1406
- } catch (e) {
1407
- console.error(`[Action] Не удалось прочитать defaultPath для ${pluginName}: ${e.message}`);
1408
- defaultSettings[key] = {};
1409
- }
1410
- } else {
1411
- try {
1412
- defaultSettings[key] = JSON.parse(config.default || 'null');
1413
- } catch {
1414
- defaultSettings[key] = config.default;
1415
- }
1416
- }
1417
- }
1418
- }
1419
- const finalSettings = { ...defaultSettings, ...savedSettings };
1420
-
1421
- const mainFilePath = manifest.main || 'index.js';
1422
- const pluginPath = path.join(plugin.path, mainFilePath);
1423
-
1424
- delete require.cache[require.resolve(pluginPath)];
1425
- const pluginModule = require(pluginPath);
1426
-
1427
- if (typeof pluginModule.handleAction !== 'function') {
1428
- return res.status(501).json({ error: `Плагин "${pluginName}" не поддерживает обработку действий.` });
1429
- }
1430
-
1431
- const result = await pluginModule.handleAction({
1432
- botProcess: botProcess,
1433
- botId: numericBotId,
1434
- action: actionName,
1435
- payload: payload,
1436
- settings: finalSettings
1437
- });
1438
-
1439
- res.json({ success: true, message: 'Действие выполнено.', result: result || null });
1440
-
1441
- } catch (error) {
1442
- console.error(`Ошибка выполнения действия "${actionName}" для плагина "${pluginName}":`, error);
1443
- res.status(500).json({ error: error.message || 'Внутренняя ошибка сервера.' });
1444
- }
1445
- });
1446
-
1447
-
1448
- router.get('/:botId/export', authorize('bot:export'), async (req, res) => {
1449
- try {
1450
- const botId = parseInt(req.params.botId, 10);
1451
- const {
1452
- includeCommands,
1453
- includePermissions,
1454
- includePluginFiles,
1455
- includePluginDataStore,
1456
- includeEventGraphs,
1457
- } = req.query;
1458
-
1459
- const bot = await prisma.bot.findUnique({ where: { id: botId } });
1460
- if (!bot) {
1461
- return res.status(404).json({ error: 'Bot not found' });
1462
- }
1463
-
1464
- const archive = archiver('zip', { zlib: { level: 9 } });
1465
- res.attachment(`bot_${bot.username}_export_${new Date().toISOString()}.zip`);
1466
- archive.pipe(res);
1467
-
1468
- const botData = { ...bot };
1469
- delete botData.password;
1470
- delete botData.proxyPassword;
1471
- archive.append(JSON.stringify(botData, null, 2), { name: 'bot.json' });
1472
-
1473
- if (includeCommands === 'true') {
1474
- const commands = await prisma.command.findMany({ where: { botId } });
1475
- archive.append(JSON.stringify(commands, null, 2), { name: 'commands.json' });
1476
- }
1477
-
1478
- if (includePermissions === 'true') {
1479
- const users = await prisma.user.findMany({ where: { botId }, include: { groups: { include: { group: true } } } });
1480
- const groups = await prisma.group.findMany({ where: { botId }, include: { permissions: { include: { permission: true } } } });
1481
- const permissions = await prisma.permission.findMany({ where: { botId } });
1482
- const permissionsData = { users, groups, permissions };
1483
- archive.append(JSON.stringify(permissionsData, null, 2), { name: 'permissions.json' });
1484
- }
1485
-
1486
- if (includeEventGraphs === 'true') {
1487
- const eventGraphs = await prisma.eventGraph.findMany({ where: { botId } });
1488
- archive.append(JSON.stringify(eventGraphs, null, 2), { name: 'event_graphs.json' });
1489
- }
1490
-
1491
- if (includePluginFiles === 'true' || includePluginDataStore === 'true') {
1492
- const installedPlugins = await prisma.installedPlugin.findMany({ where: { botId } });
1493
- archive.append(JSON.stringify(installedPlugins, null, 2), { name: 'plugins.json' });
1494
-
1495
- if (includePluginFiles === 'true') {
1496
- for (const plugin of installedPlugins) {
1497
- const pluginPath = plugin.path;
1498
- if (await fs.stat(pluginPath).then(s => s.isDirectory()).catch(() => false)) {
1499
- archive.directory(pluginPath, `plugins/${plugin.name}`);
1500
- }
1501
- }
1502
- }
1503
- if (includePluginDataStore === 'true') {
1504
- console.log(`[Export] Экспорт PluginDataStore для бота ${botId}`);
1505
- const pluginDataStore = await prisma.pluginDataStore.findMany({
1506
- where: { botId: parseInt(botId) }
1507
- });
1508
- console.log(`[Export] Найдено записей PluginDataStore: ${pluginDataStore.length}`);
1509
- if (pluginDataStore.length > 0) {
1510
- archive.append(JSON.stringify(pluginDataStore, null, 2), { name: 'plugin_data_store.json' });
1511
- console.log(`[Export] Данные PluginDataStore добавлены в архив`);
1512
- } else {
1513
- console.log(`[Export] Нет данных PluginDataStore для экспорта`);
1514
- }
1515
- }
1516
- }
1517
-
1518
- await archive.finalize();
1519
-
1520
- } catch (error) {
1521
- console.error('Failed to export bot:', error);
1522
- res.status(500).json({ error: `Failed to export bot: ${error.message}` });
1523
- }
1524
- });
1525
-
1526
- router.post('/import', authorize('bot:create'), upload.single('file'), async (req, res) => {
1527
- if (!req.file) {
1528
- return res.status(400).json({ error: 'No file uploaded.' });
1529
- }
1530
-
1531
- const botIdMap = new Map();
1532
-
1533
- try {
1534
- const zip = new AdmZip(req.file.buffer);
1535
- const zipEntries = zip.getEntries();
1536
-
1537
- const botDataEntry = zipEntries.find(e => e.entryName === 'bot.json');
1538
- if (!botDataEntry) {
1539
- return res.status(400).json({ error: 'Archive missing bot.json' });
1540
- }
1541
- const botData = JSON.parse(botDataEntry.getData().toString('utf8'));
1542
-
1543
- const server = await prisma.server.findFirst();
1544
- if (!server) {
1545
- return res.status(500).json({ error: 'No servers configured in the target system.' });
1546
- }
1547
-
1548
- let newBotName = botData.username;
1549
- let counter = 1;
1550
- while (await prisma.bot.findFirst({ where: { username: newBotName } })) {
1551
- newBotName = `${botData.username}_imported_${counter}`;
1552
- counter++;
1553
- }
1554
-
1555
- const newBot = await prisma.bot.create({
1556
- data: {
1557
- ...botData,
1558
- id: undefined,
1559
- username: newBotName,
1560
- serverId: server.id,
1561
- password: null,
1562
- proxyPassword: null
1563
- },
1564
- include: { server: true }
1565
- });
1566
-
1567
- botIdMap.set(botData.id, newBot.id);
1568
-
1569
- const permissionsEntry = zipEntries.find(e => e.entryName === 'permissions.json');
1570
- let pMap = new Map();
1571
-
1572
- if (permissionsEntry) {
1573
- const { users, groups, permissions } = JSON.parse(permissionsEntry.getData().toString('utf8'));
1574
-
1575
- await setupDefaultPermissionsForBot(newBot.id, prisma);
1576
-
1577
- for(let p of permissions.filter(p=>p.owner === 'system')) {
1578
- const existingPermission = await prisma.permission.findFirst({
1579
- where: {
1580
- botId: newBot.id,
1581
- name: p.name,
1582
- owner: 'system'
1583
- }
1584
- });
1585
- if (existingPermission) {
1586
- pMap.set(p.id, existingPermission.id);
1587
- }
1588
- }
1589
-
1590
- for(let p of permissions.filter(p=>p.owner !== 'system')) {
1591
- const newP = await prisma.permission.create({ data: { ...p, id: undefined, botId: newBot.id }});
1592
- pMap.set(p.id, newP.id);
1593
- }
1594
-
1595
- const gMap = new Map();
1596
- for(let g of groups.filter(g=>g.owner !== 'system')) {
1597
- const newG = await prisma.group.create({ data: { ...g, id: undefined, botId: newBot.id, permissions: {
1598
- create: g.permissions.map(gp => ({ permissionId: pMap.get(gp.permissionId) })).filter(p=>p.permissionId)
1599
- }}});
1600
- gMap.set(g.id, newG.id);
1601
- }
1602
-
1603
- for(let u of users) {
1604
- await prisma.user.create({ data: { ...u, id: undefined, botId: newBot.id, groups: {
1605
- create: u.groups.map(ug => ({ groupId: gMap.get(ug.groupId) })).filter(g=>g.groupId)
1606
- }}});
1607
- }
1608
- }
1609
-
1610
- const pluginDataStoreEntry = zipEntries.find(e => e.entryName === 'plugin_data_store.json');
1611
- if (pluginDataStoreEntry) {
1612
- console.log(`[Import] Импорт PluginDataStore для бота ${newBot.id}`);
1613
- const pluginDataStore = JSON.parse(pluginDataStoreEntry.getData().toString('utf8'));
1614
- console.log(`[Import] Найдено записей PluginDataStore: ${pluginDataStore.length}`);
1615
-
1616
- for (let dataRecord of pluginDataStore) {
1617
- delete dataRecord.id;
1618
- dataRecord.botId = newBot.id;
1619
- await prisma.pluginDataStore.create({ data: dataRecord });
1620
- }
1621
- console.log(`[Import] PluginDataStore успешно импортирован`);
1622
- }
1623
-
1624
- const pluginsEntry = zipEntries.find(e => e.entryName === 'plugins.json');
1625
- let pluginMap = new Map();
1626
-
1627
- if (pluginsEntry) {
1628
- const plugins = JSON.parse(pluginsEntry.getData().toString('utf8'));
1629
- const pluginsDir = path.join(os.homedir(), '.blockmine', 'storage', 'plugins');
1630
- const botPluginsDir = path.join(pluginsDir, newBot.username);
1631
- await fs.mkdir(botPluginsDir, { recursive: true });
1632
-
1633
- for (let pluginData of plugins) {
1634
- const oldPath = pluginData.path;
1635
- const pluginName = pluginData.name;
1636
- const newPluginPath = path.join(botPluginsDir, pluginName);
1637
-
1638
- const oldPluginId = pluginData.id;
1639
- delete pluginData.id;
1640
- pluginData.botId = newBot.id;
1641
- pluginData.path = path.resolve(newPluginPath);
1642
-
1643
- for (const entry of zipEntries) {
1644
- if (entry.entryName.startsWith(`plugins/${pluginName}/`)) {
1645
- const relativePath = entry.entryName.replace(`plugins/${pluginName}/`, '');
1646
- if (relativePath) {
1647
- const destPath = path.join(newPluginPath, relativePath);
1648
- const destDir = path.dirname(destPath);
1649
- await fs.mkdir(destDir, { recursive: true });
1650
-
1651
- if (!entry.isDirectory) {
1652
- await fs.writeFile(destPath, entry.getData());
1653
- }
1654
- }
1655
- }
1656
- }
1657
-
1658
- const newPlugin = await prisma.installedPlugin.create({ data: pluginData });
1659
- pluginMap.set(oldPluginId, newPlugin.id);
1660
- }
1661
- }
1662
-
1663
- const commandsEntry = zipEntries.find(e => e.entryName === 'commands.json');
1664
- if (commandsEntry) {
1665
- const commands = JSON.parse(commandsEntry.getData().toString('utf8'));
1666
- for (let command of commands) {
1667
- delete command.id;
1668
- command.botId = newBot.id;
1669
-
1670
- if (command.permissionId && pMap.has(command.permissionId)) {
1671
- command.permissionId = pMap.get(command.permissionId);
1672
- } else {
1673
- command.permissionId = null;
1674
- }
1675
-
1676
- if (command.pluginOwnerId && pluginMap.has(command.pluginOwnerId)) {
1677
- command.pluginOwnerId = pluginMap.get(command.pluginOwnerId);
1678
- } else {
1679
- command.pluginOwnerId = null;
1680
- }
1681
-
1682
- try {
1683
- await prisma.command.create({ data: command });
1684
- } catch (error) {
1685
- console.warn(`[Import] Пропущена команда ${command.name}: ${error.message}`);
1686
- }
1687
- }
1688
- }
1689
-
1690
- const eventGraphsEntry = zipEntries.find(e => e.entryName === 'event_graphs.json');
1691
- if (eventGraphsEntry) {
1692
- const eventGraphs = JSON.parse(eventGraphsEntry.getData().toString('utf8'));
1693
- for (let graph of eventGraphs) {
1694
- delete graph.id;
1695
- graph.botId = newBot.id;
1696
-
1697
- if (graph.pluginOwnerId && pluginMap.has(graph.pluginOwnerId)) {
1698
- graph.pluginOwnerId = pluginMap.get(graph.pluginOwnerId);
1699
- } else {
1700
- graph.pluginOwnerId = null;
1701
- }
1702
-
1703
- try {
1704
- await prisma.eventGraph.create({ data: graph });
1705
- } catch (error) {
1706
- console.warn(`[Import] Пропущен граф ${graph.name}: ${error.message}`);
1707
- }
1708
- }
1709
- }
1710
-
1711
- res.status(201).json(newBot);
1712
-
1713
- } catch (error) {
1714
- console.error('Failed to import bot:', error);
1715
- res.status(500).json({ error: `Failed to import bot: ${error.message}` });
1716
- }
1717
- });
1718
-
1719
- module.exports = router;
1
+ const express = require('express');
2
+ const prisma = require('../../lib/prisma');
3
+ const path = require('path');
4
+ const fs = require('fs/promises');
5
+ const fse = require('fs-extra');
6
+ const { botManager, pluginManager } = require('../../core/services');
7
+ const UserService = require('../../core/UserService');
8
+ const commandManager = require('../../core/system/CommandManager');
9
+ const NodeRegistry = require('../../core/NodeRegistry');
10
+ const { authenticate, authorize } = require('../middleware/auth');
11
+ const { encrypt } = require('../../core/utils/crypto');
12
+ const { randomUUID } = require('crypto');
13
+ const eventGraphsRouter = require('./eventGraphs');
14
+ const pluginIdeRouter = require('./pluginIde');
15
+
16
+ const multer = require('multer');
17
+ const archiver = require('archiver');
18
+ const AdmZip = require('adm-zip');
19
+ const os = require('os');
20
+
21
+ const upload = multer({ storage: multer.memoryStorage() });
22
+
23
+ const router = express.Router();
24
+
25
+ const conditionalRestartAuth = (req, res, next) => {
26
+ if (process.env.DEBUG === 'true' || process.env.NODE_ENV === 'development') {
27
+ console.log('[Debug] Роут перезапуска бота доступен без проверки прав');
28
+ return next();
29
+ }
30
+
31
+ return authenticate(req, res, (err) => {
32
+ if (err) return next(err);
33
+ return authorize('bot:start_stop')(req, res, next);
34
+ });
35
+ };
36
+
37
+ const conditionalChatAuth = (req, res, next) => {
38
+ if (process.env.DEBUG === 'true' || process.env.NODE_ENV === 'development') {
39
+ console.log('[Debug] Роут отправки сообщения боту доступен без проверки прав');
40
+ return next();
41
+ }
42
+
43
+ return authenticate(req, res, (err) => {
44
+ if (err) return next(err);
45
+ return authorize('bot:interact')(req, res, next);
46
+ });
47
+ };
48
+
49
+ const conditionalStartStopAuth = (req, res, next) => {
50
+ if (process.env.DEBUG === 'true' || process.env.NODE_ENV === 'development') {
51
+ console.log('[Debug] Роут запуска/остановки бота доступен без проверки прав');
52
+ return next();
53
+ }
54
+
55
+ return authenticate(req, res, (err) => {
56
+ if (err) return next(err);
57
+ return authorize('bot:start_stop')(req, res, next);
58
+ });
59
+ };
60
+
61
+ const conditionalListAuth = (req, res, next) => {
62
+ if (process.env.DEBUG === 'true' || process.env.NODE_ENV === 'development') {
63
+ console.log('[Debug] Роут списка ботов/состояния доступен без проверки прав');
64
+ return next();
65
+ }
66
+
67
+ return authenticate(req, res, (err) => {
68
+ if (err) return next(err);
69
+ return authorize('bot:list')(req, res, next);
70
+ });
71
+ };
72
+
73
+ router.post('/:id/restart', conditionalRestartAuth, async (req, res) => {
74
+ try {
75
+ const botId = parseInt(req.params.id, 10);
76
+ botManager.stopBot(botId);
77
+ setTimeout(async () => {
78
+ const botConfig = await prisma.bot.findUnique({ where: { id: botId }, include: { server: true } });
79
+ if (!botConfig) {
80
+ return res.status(404).json({ success: false, message: 'Бот не найден' });
81
+ }
82
+ botManager.startBot(botConfig);
83
+ res.status(202).json({ success: true, message: 'Команда на перезапуск отправлена.' });
84
+ }, 1000);
85
+ } catch (error) {
86
+ console.error(`[API] Ошибка перезапуска бота ${req.params.id}:`, error);
87
+ res.status(500).json({ success: false, message: 'Ошибка при перезапуске бота: ' + error.message });
88
+ }
89
+ });
90
+
91
+ router.post('/:id/chat', conditionalChatAuth, (req, res) => {
92
+ try {
93
+ const botId = parseInt(req.params.id, 10);
94
+ const { message } = req.body;
95
+ if (!message) return res.status(400).json({ error: 'Сообщение не может быть пустым' });
96
+ const result = botManager.sendMessageToBot(botId, message);
97
+ if (result.success) res.json({ success: true });
98
+ else res.status(404).json(result);
99
+ } catch (error) { res.status(500).json({ error: 'Внутренняя ошибка сервера: ' + error.message }); }
100
+ });
101
+
102
+ router.post('/:id/start', conditionalStartStopAuth, async (req, res) => {
103
+ try {
104
+ const botId = parseInt(req.params.id, 10);
105
+ const botConfig = await prisma.bot.findUnique({ where: { id: botId }, include: { server: true } });
106
+ if (!botConfig) {
107
+ return res.status(404).json({ success: false, message: 'Бот не найден' });
108
+ }
109
+ botManager.startBot(botConfig);
110
+ res.status(202).json({ success: true, message: 'Команда на запуск отправлена.' });
111
+ } catch (error) {
112
+ console.error(`[API] Ошибка запуска бота ${req.params.id}:`, error);
113
+ res.status(500).json({ success: false, message: 'Ошибка при запуске бота: ' + error.message });
114
+ }
115
+ });
116
+
117
+ router.post('/:id/stop', conditionalStartStopAuth, (req, res) => {
118
+ try {
119
+ const botId = parseInt(req.params.id, 10);
120
+ botManager.stopBot(botId);
121
+ res.status(202).json({ success: true, message: 'Команда на остановку отправлена.' });
122
+ } catch (error) {
123
+ console.error(`[API] Ошибка остановки бота ${req.params.id}:`, error);
124
+ res.status(500).json({ success: false, message: 'Ошибка при остановке бота: ' + error.message });
125
+ }
126
+ });
127
+
128
+ router.get('/', conditionalListAuth, async (req, res) => {
129
+ try {
130
+ const bots = await prisma.bot.findMany({ include: { server: true }, orderBy: { createdAt: 'asc' } });
131
+ res.json(bots);
132
+ } catch (error) {
133
+ console.error("[API /api/bots] Ошибка получения списка ботов:", error);
134
+ res.status(500).json({ error: 'Не удалось получить список ботов' });
135
+ }
136
+ });
137
+
138
+ router.get('/state', conditionalListAuth, (req, res) => {
139
+ try {
140
+ const state = botManager.getFullState();
141
+ res.json(state);
142
+ } catch (error) { res.status(500).json({ error: 'Не удалось получить состояние ботов' }); }
143
+ });
144
+
145
+ router.get('/:id/logs', conditionalListAuth, (req, res) => {
146
+ try {
147
+ const botId = parseInt(req.params.id, 10);
148
+ const { limit = 100, offset = 0 } = req.query;
149
+
150
+ const logs = botManager.getBotLogs(botId);
151
+
152
+ const startIndex = parseInt(offset);
153
+ const endIndex = startIndex + parseInt(limit);
154
+ const paginatedLogs = logs.slice(startIndex, endIndex);
155
+
156
+ res.json({
157
+ success: true,
158
+ data: {
159
+ logs: paginatedLogs,
160
+ pagination: {
161
+ total: logs.length,
162
+ limit: parseInt(limit),
163
+ offset: startIndex,
164
+ hasMore: endIndex < logs.length
165
+ }
166
+ }
167
+ });
168
+ } catch (error) {
169
+ console.error(`[API] Ошибка получения логов бота ${req.params.id}:`, error);
170
+ res.status(500).json({ error: 'Не удалось получить логи бота' });
171
+ }
172
+ });
173
+
174
+ router.use(authenticate);
175
+ router.use('/:botId/event-graphs', eventGraphsRouter);
176
+ router.use('/:botId/plugins/ide', pluginIdeRouter);
177
+
178
+ async function setupDefaultPermissionsForBot(botId, prismaClient = prisma) {
179
+ const initialData = {
180
+ groups: ["User", "Admin"],
181
+ permissions: [
182
+ { name: "admin.*", description: "Все права администратора" },
183
+ { name: "admin.cooldown.bypass", description: "Обход кулдауна для админ-команд" },
184
+ { name: "user.*", description: "Все права обычного пользователя" },
185
+ { name: "user.say", description: "Доступ к простым командам" },
186
+ { name: "user.cooldown.bypass", description: "Обход кулдауна для юзер-команд" },
187
+ ],
188
+ groupPermissions: {
189
+ "User": ["user.say"],
190
+ "Admin": ["admin.*", "admin.cooldown.bypass", "user.cooldown.bypass", "user.*"]
191
+ },
192
+ };
193
+
194
+ for (const perm of initialData.permissions) {
195
+ await prismaClient.permission.upsert({ where: { botId_name: { botId, name: perm.name } }, update: { description: perm.description }, create: { ...perm, botId, owner: 'system' } });
196
+ }
197
+ for (const groupName of initialData.groups) {
198
+ await prismaClient.group.upsert({ where: { botId_name: { botId, name: groupName } }, update: {}, create: { name: groupName, botId, owner: 'system' } });
199
+ }
200
+ for (const [groupName, permNames] of Object.entries(initialData.groupPermissions)) {
201
+ const group = await prismaClient.group.findUnique({ where: { botId_name: { botId, name: groupName } } });
202
+ if (group) {
203
+ for (const permName of permNames) {
204
+ const permission = await prismaClient.permission.findUnique({ where: { botId_name: { botId, name: permName } } });
205
+ if (permission) {
206
+ await prismaClient.groupPermission.upsert({ where: { groupId_permissionId: { groupId: group.id, permissionId: permission.id } }, update: {}, create: { groupId: group.id, permissionId: permission.id } });
207
+ }
208
+ }
209
+ }
210
+ }
211
+ console.log(`[Setup] Для бота ID ${botId} созданы группы и права по умолчанию.`);
212
+ }
213
+
214
+
215
+
216
+ router.post('/', authorize('bot:create'), async (req, res) => {
217
+ try {
218
+ const { username, password, prefix, serverId, note } = req.body;
219
+ if (!username || !serverId) return res.status(400).json({ error: 'Имя и сервер обязательны' });
220
+
221
+ const data = {
222
+ username,
223
+ prefix,
224
+ note,
225
+ serverId: parseInt(serverId, 10),
226
+ password: password ? encrypt(password) : null
227
+ };
228
+
229
+ const newBot = await prisma.bot.create({
230
+ data: data,
231
+ include: { server: true }
232
+ });
233
+ await setupDefaultPermissionsForBot(newBot.id);
234
+ res.status(201).json(newBot);
235
+ } catch (error) {
236
+ if (error.code === 'P2002') return res.status(409).json({ error: 'Бот с таким именем уже существует' });
237
+ console.error("[API Error] /bots POST:", error);
238
+ res.status(500).json({ error: 'Не удалось создать бота' });
239
+ }
240
+ });
241
+
242
+ router.put('/:id', authorize('bot:update'), async (req, res) => {
243
+ try {
244
+ const {
245
+ username, password, prefix, serverId, note, owners,
246
+ proxyHost, proxyPort, proxyUsername, proxyPassword
247
+ } = req.body;
248
+
249
+ let dataToUpdate = {
250
+ username,
251
+ prefix,
252
+ note,
253
+ owners,
254
+ proxyHost,
255
+ proxyPort: proxyPort ? parseInt(proxyPort, 10) : null,
256
+ proxyUsername,
257
+ };
258
+
259
+ if (password) {
260
+ dataToUpdate.password = encrypt(password);
261
+ }
262
+ if (proxyPassword) {
263
+ dataToUpdate.proxyPassword = encrypt(proxyPassword);
264
+ }
265
+
266
+ if (serverId !== undefined && serverId !== '') {
267
+ dataToUpdate.serverId = parseInt(serverId, 10);
268
+ }
269
+
270
+ Object.keys(dataToUpdate).forEach(key => {
271
+ if (dataToUpdate[key] === undefined) {
272
+ delete dataToUpdate[key];
273
+ }
274
+ });
275
+
276
+ if (dataToUpdate.serverId) {
277
+ const serverIdValue = dataToUpdate.serverId;
278
+ delete dataToUpdate.serverId;
279
+ dataToUpdate.server = { connect: { id: serverIdValue } };
280
+ }
281
+
282
+ const botId = parseInt(req.params.id, 10);
283
+ if (isNaN(botId)) {
284
+ return res.status(400).json({ message: 'Неверный ID бота.' });
285
+ }
286
+
287
+ if (dataToUpdate.username) {
288
+ const existingBot = await prisma.bot.findFirst({
289
+ where: {
290
+ username: dataToUpdate.username,
291
+ id: { not: botId }
292
+ }
293
+ });
294
+
295
+ if (existingBot) {
296
+ return res.status(400).json({
297
+ message: `Бот с именем "${dataToUpdate.username}" уже существует.`
298
+ });
299
+ }
300
+ }
301
+
302
+ const updatedBot = await prisma.bot.update({
303
+ where: { id: botId },
304
+ data: dataToUpdate,
305
+ include: {
306
+ server: true
307
+ }
308
+ });
309
+
310
+ const botManager = req.app.get('botManager');
311
+ botManager.reloadBotConfigInRealTime(botId);
312
+
313
+ if (dataToUpdate.owners !== undefined) {
314
+ botManager.invalidateAllUserCache(botId);
315
+ }
316
+
317
+ res.json(updatedBot);
318
+ } catch (error) {
319
+ console.error('Error updating bot:', error);
320
+ console.error('Error details:', {
321
+ code: error.code,
322
+ meta: error.meta,
323
+ message: error.message
324
+ });
325
+
326
+ if (error.code === 'P2002' && error.meta?.target?.includes('username')) {
327
+ return res.status(400).json({
328
+ message: 'Бот с таким именем уже существует. Выберите другое имя.'
329
+ });
330
+ }
331
+
332
+ res.status(500).json({ message: `Не удалось обновить бота: ${error.message}` });
333
+ }
334
+ });
335
+
336
+ router.delete('/:id', authorize('bot:delete'), async (req, res) => {
337
+ try {
338
+ const botId = parseInt(req.params.id, 10);
339
+ if (botManager.bots.has(botId)) return res.status(400).json({ error: 'Нельзя удалить запущенного бота' });
340
+ await prisma.bot.delete({ where: { id: botId } });
341
+ res.status(204).send();
342
+ } catch (error) { res.status(500).json({ error: 'Не удалось удалить бота' }); }
343
+ });
344
+
345
+ router.get('/servers', authorize('bot:list'), async (req, res) => {
346
+ try {
347
+ const servers = await prisma.server.findMany();
348
+ res.json(servers);
349
+ } catch (error) {
350
+ console.error("[API /api/bots] Ошибка получения списка серверов:", error);
351
+ res.status(500).json({ error: 'Не удалось получить список серверов' });
352
+ }
353
+ });
354
+
355
+ router.get('/:botId/plugins', authorize('plugin:list'), async (req, res) => {
356
+ try {
357
+ const botId = parseInt(req.params.botId);
358
+ const plugins = await prisma.installedPlugin.findMany({ where: { botId } });
359
+ res.json(plugins);
360
+ } catch (error) { res.status(500).json({ error: 'Не удалось получить плагины бота' }); }
361
+ });
362
+
363
+ router.post('/:botId/plugins/install/github', authorize('plugin:install'), async (req, res) => {
364
+ const { botId } = req.params;
365
+ const { repoUrl } = req.body;
366
+ try {
367
+ const newPlugin = await pluginManager.installFromGithub(parseInt(botId), repoUrl);
368
+ res.status(201).json(newPlugin);
369
+ } catch (error) {
370
+ res.status(500).json({ message: error.message });
371
+ }
372
+ });
373
+
374
+ router.post('/:botId/plugins/install/local', authorize('plugin:install'), async (req, res) => {
375
+ const { botId } = req.params;
376
+ const { path } = req.body;
377
+ try {
378
+ const newPlugin = await pluginManager.installFromLocalPath(parseInt(botId), path);
379
+ res.status(201).json(newPlugin);
380
+ } catch (error) {
381
+ res.status(500).json({ message: error.message });
382
+ }
383
+ });
384
+
385
+ router.delete('/:botId/plugins/:pluginId', authorize('plugin:delete'), async (req, res) => {
386
+ const { pluginId } = req.params;
387
+ try {
388
+ await pluginManager.deletePlugin(parseInt(pluginId));
389
+ res.status(204).send();
390
+ } catch (error) {
391
+ res.status(500).json({ message: error.message });
392
+ }
393
+ });
394
+
395
+ router.get('/:botId/plugins/:pluginId/settings', authorize('plugin:settings:view'), async (req, res) => {
396
+ try {
397
+ const pluginId = parseInt(req.params.pluginId);
398
+ const plugin = await prisma.installedPlugin.findUnique({ where: { id: pluginId } });
399
+ if (!plugin) return res.status(404).json({ error: 'Установленный плагин не найден' });
400
+
401
+ const savedSettings = plugin.settings ? JSON.parse(plugin.settings) : {};
402
+ let defaultSettings = {};
403
+ const manifest = plugin.manifest ? JSON.parse(plugin.manifest) : {};
404
+
405
+ if (manifest.settings) {
406
+ for (const key in manifest.settings) {
407
+ const config = manifest.settings[key];
408
+ if (config.type === 'json_file' && config.defaultPath) {
409
+ const configFilePath = path.join(plugin.path, config.defaultPath);
410
+ try {
411
+ const fileContent = await fs.readFile(configFilePath, 'utf-8');
412
+ defaultSettings[key] = JSON.parse(fileContent);
413
+ } catch (e) { defaultSettings[key] = {}; }
414
+ } else {
415
+ try { defaultSettings[key] = JSON.parse(config.default || 'null'); }
416
+ catch { defaultSettings[key] = config.default; }
417
+ }
418
+ }
419
+ }
420
+ const finalSettings = { ...defaultSettings, ...savedSettings };
421
+ res.json(finalSettings);
422
+ } catch (error) {
423
+ console.error("[API Error] /settings GET:", error);
424
+ res.status(500).json({ error: 'Не удалось получить настройки плагина' });
425
+ }
426
+ });
427
+
428
+ router.put('/:botId/plugins/:pluginId', authorize('plugin:settings:edit'), async (req, res) => {
429
+ try {
430
+ const pluginId = parseInt(req.params.pluginId);
431
+ const { isEnabled, settings } = req.body;
432
+ const dataToUpdate = {};
433
+ if (typeof isEnabled === 'boolean') dataToUpdate.isEnabled = isEnabled;
434
+ if (settings) dataToUpdate.settings = JSON.stringify(settings);
435
+ if (Object.keys(dataToUpdate).length === 0) return res.status(400).json({ error: "Нет данных для обновления" });
436
+ const updated = await prisma.installedPlugin.update({ where: { id: pluginId }, data: dataToUpdate });
437
+ res.json(updated);
438
+ } catch (error) { res.status(500).json({ error: 'Не удалось обновить плагин' }); }
439
+ });
440
+
441
+ router.get('/:botId/management-data', authorize('management:view'), async (req, res) => {
442
+ try {
443
+ const botId = parseInt(req.params.botId, 10);
444
+ if (isNaN(botId)) return res.status(400).json({ error: 'Неверный ID бота' });
445
+
446
+ const page = parseInt(req.query.page) || 1;
447
+ const pageSize = parseInt(req.query.pageSize) || 100;
448
+ const searchQuery = req.query.search || '';
449
+
450
+ const userSkip = (page - 1) * pageSize;
451
+
452
+ const whereClause = {
453
+ botId,
454
+ };
455
+
456
+ if (searchQuery) {
457
+ whereClause.username = {
458
+ contains: searchQuery,
459
+ };
460
+ }
461
+
462
+ const [groups, allPermissions] = await Promise.all([
463
+ prisma.group.findMany({ where: { botId }, include: { permissions: { include: { permission: true } } }, orderBy: { name: 'asc' } }),
464
+ prisma.permission.findMany({ where: { botId }, orderBy: { name: 'asc' } })
465
+ ]);
466
+
467
+ const [users, usersCount] = await Promise.all([
468
+ prisma.user.findMany({
469
+ where: whereClause,
470
+ include: { groups: { include: { group: true } } },
471
+ orderBy: { username: 'asc' },
472
+ take: pageSize,
473
+ skip: userSkip,
474
+ }),
475
+ prisma.user.count({ where: whereClause })
476
+ ]);
477
+
478
+ const templatesMap = new Map(commandManager.getCommandTemplates().map(t => [t.name, t]));
479
+ let dbCommandsFromDb = await prisma.command.findMany({
480
+ where: { botId },
481
+ include: {
482
+ pluginOwner: {
483
+ select: {
484
+ id: true,
485
+ name: true,
486
+ version: true,
487
+ sourceType: true
488
+ }
489
+ }
490
+ },
491
+ orderBy: [{ owner: 'asc' }, { name: 'asc' }]
492
+ });
493
+
494
+ const commandsToCreate = [];
495
+ for (const template of templatesMap.values()) {
496
+ if (!dbCommandsFromDb.some(cmd => cmd.name === template.name)) {
497
+ let permissionId = null;
498
+ if (template.permissions) {
499
+ const permission = await prisma.permission.upsert({
500
+ where: { botId_name: { botId, name: template.permissions } },
501
+ update: { description: `Авто-создано для команды ${template.name}` },
502
+ create: {
503
+ botId,
504
+ name: template.permissions,
505
+ description: `Авто-создано для команды ${template.name}`,
506
+ owner: template.owner || 'system',
507
+ }
508
+ });
509
+ permissionId = permission.id;
510
+ }
511
+
512
+ commandsToCreate.push({
513
+ botId,
514
+ name: template.name,
515
+ isEnabled: template.isActive,
516
+ cooldown: template.cooldown,
517
+ aliases: JSON.stringify(template.aliases),
518
+ description: template.description,
519
+ owner: template.owner,
520
+ permissionId: permissionId,
521
+ allowedChatTypes: JSON.stringify(template.allowedChatTypes),
522
+ });
523
+ }
524
+ }
525
+
526
+ if (commandsToCreate.length > 0) {
527
+ await prisma.command.createMany({ data: commandsToCreate });
528
+ dbCommandsFromDb = await prisma.command.findMany({
529
+ where: { botId },
530
+ include: {
531
+ pluginOwner: {
532
+ select: {
533
+ id: true,
534
+ name: true,
535
+ version: true,
536
+ sourceType: true
537
+ }
538
+ }
539
+ },
540
+ orderBy: [{ owner: 'asc' }, { name: 'asc' }]
541
+ });
542
+ }
543
+
544
+ const finalCommands = dbCommandsFromDb.map(cmd => {
545
+ const template = templatesMap.get(cmd.name);
546
+ let args = [];
547
+
548
+ if (cmd.isVisual) {
549
+ try {
550
+ args = JSON.parse(cmd.argumentsJson || '[]');
551
+ } catch (e) {
552
+ console.error(`Error parsing argumentsJson for visual command ${cmd.name} (ID: ${cmd.id}):`, e);
553
+ args = [];
554
+ }
555
+ } else {
556
+ if (template && template.args && template.args.length > 0) {
557
+ args = template.args;
558
+ } else {
559
+ try {
560
+ args = JSON.parse(cmd.argumentsJson || '[]');
561
+ } catch (e) {
562
+ args = [];
563
+ }
564
+ }
565
+ }
566
+
567
+ return {
568
+ ...cmd,
569
+ args: args,
570
+ aliases: JSON.parse(cmd.aliases || '[]'),
571
+ allowedChatTypes: JSON.parse(cmd.allowedChatTypes || '[]'),
572
+ };
573
+ })
574
+
575
+ res.json({
576
+ groups,
577
+ permissions: allPermissions,
578
+ users: {
579
+ items: users,
580
+ total: usersCount,
581
+ page,
582
+ pageSize,
583
+ totalPages: Math.ceil(usersCount / pageSize),
584
+ },
585
+ commands: finalCommands
586
+ });
587
+
588
+ } catch (error) {
589
+ console.error(`[API Error] /management-data for bot ${req.params.botId}:`, error);
590
+ res.status(500).json({ error: 'Не удалось загрузить данные управления' });
591
+ }
592
+ });
593
+
594
+ router.put('/:botId/commands/:commandId', authorize('management:edit'), async (req, res) => {
595
+ try {
596
+ const commandId = parseInt(req.params.commandId, 10);
597
+ const { name, description, cooldown, aliases, permissionId, allowedChatTypes, isEnabled, argumentsJson, graphJson, pluginOwnerId } = req.body;
598
+
599
+ const dataToUpdate = {};
600
+ if (name !== undefined) dataToUpdate.name = name;
601
+ if (description !== undefined) dataToUpdate.description = description;
602
+ if (cooldown !== undefined) dataToUpdate.cooldown = parseInt(cooldown, 10);
603
+ if (aliases !== undefined) dataToUpdate.aliases = Array.isArray(aliases) ? JSON.stringify(aliases) : aliases;
604
+ if (permissionId !== undefined) dataToUpdate.permissionId = permissionId ? parseInt(permissionId, 10) : null;
605
+ if (allowedChatTypes !== undefined) dataToUpdate.allowedChatTypes = Array.isArray(allowedChatTypes) ? JSON.stringify(allowedChatTypes) : allowedChatTypes;
606
+ if (isEnabled !== undefined) dataToUpdate.isEnabled = isEnabled;
607
+ if (argumentsJson !== undefined) dataToUpdate.argumentsJson = Array.isArray(argumentsJson) ? JSON.stringify(argumentsJson) : argumentsJson;
608
+ if (graphJson !== undefined) dataToUpdate.graphJson = graphJson;
609
+ if (pluginOwnerId !== undefined) dataToUpdate.pluginOwnerId = pluginOwnerId;
610
+
611
+ const updatedCommand = await prisma.command.update({
612
+ where: { id: commandId },
613
+ data: dataToUpdate,
614
+ });
615
+
616
+ if (graphJson && updatedCommand.pluginOwnerId) {
617
+ try {
618
+ const plugin = await prisma.installedPlugin.findUnique({
619
+ where: { id: updatedCommand.pluginOwnerId }
620
+ });
621
+
622
+ if (plugin) {
623
+ const graphDir = path.join(plugin.path, 'graph');
624
+ await fse.mkdir(graphDir, { recursive: true });
625
+
626
+ const graphFile = path.join(graphDir, `${updatedCommand.name}.json`);
627
+ await fse.writeJson(graphFile, JSON.parse(graphJson), { spaces: 2 });
628
+ console.log(`[API] Граф команды ${updatedCommand.name} сохранен в ${graphFile}`);
629
+ }
630
+ } catch (error) {
631
+ console.error(`[API] Ошибка сохранения графа в папку плагина:`, error);
632
+ }
633
+ }
634
+
635
+ res.json(updatedCommand);
636
+ } catch (error) {
637
+ console.error(`[API Error] /commands/:commandId PUT:`, error);
638
+ res.status(500).json({ error: 'Failed to update command' });
639
+ }
640
+ });
641
+
642
+ router.post('/:botId/groups', authorize('management:edit'), async (req, res) => {
643
+ try {
644
+ const botId = parseInt(req.params.botId);
645
+ const { name, permissionIds } = req.body;
646
+ if (!name) return res.status(400).json({ error: "Имя группы обязательно" });
647
+
648
+ const newGroup = await prisma.group.create({
649
+ data: {
650
+ name,
651
+ botId,
652
+ owner: 'admin',
653
+ permissions: { create: (permissionIds || []).map(id => ({ permissionId: id })) }
654
+ }
655
+ });
656
+
657
+ botManager.reloadBotConfigInRealTime(botId);
658
+
659
+ res.status(201).json(newGroup);
660
+ } catch (error) {
661
+ if (error.code === 'P2002') return res.status(409).json({ error: 'Группа с таким именем уже существует для этого бота.' });
662
+ res.status(500).json({ error: 'Не удалось создать группу.' });
663
+ }
664
+ });
665
+
666
+ router.put('/:botId/groups/:groupId', authorize('management:edit'), async (req, res) => {
667
+ try {
668
+ const botId = parseInt(req.params.botId, 10);
669
+ const groupId = parseInt(req.params.groupId);
670
+ const { name, permissionIds } = req.body;
671
+ if (!name) return res.status(400).json({ error: "Имя группы обязательно" });
672
+
673
+ const usersInGroup = await prisma.user.findMany({
674
+ where: { botId, groups: { some: { groupId } } },
675
+ select: { username: true }
676
+ });
677
+
678
+ await prisma.$transaction(async (tx) => {
679
+ await tx.group.update({ where: { id: groupId }, data: { name } });
680
+ await tx.groupPermission.deleteMany({ where: { groupId } });
681
+ if (permissionIds && permissionIds.length > 0) {
682
+ await tx.groupPermission.createMany({
683
+ data: permissionIds.map(pid => ({ groupId, permissionId: pid })),
684
+ });
685
+ }
686
+ });
687
+
688
+ for (const user of usersInGroup) {
689
+ botManager.invalidateUserCache(botId, user.username);
690
+ }
691
+
692
+ botManager.reloadBotConfigInRealTime(botId);
693
+
694
+ res.status(200).send();
695
+ } catch (error) {
696
+ if (error.code === 'P2002') return res.status(409).json({ error: 'Группа с таким именем уже существует для этого бота.' });
697
+ res.status(500).json({ error: 'Не удалось обновить группу.' });
698
+ }
699
+ });
700
+
701
+ router.delete('/:botId/groups/:groupId', authorize('management:edit'), async (req, res) => {
702
+ try {
703
+ const botId = parseInt(req.params.botId, 10);
704
+ const groupId = parseInt(req.params.groupId);
705
+ const group = await prisma.group.findUnique({ where: { id: groupId } });
706
+ if (group && group.owner !== 'admin') {
707
+ return res.status(403).json({ error: `Нельзя удалить группу с источником "${group.owner}".` });
708
+ }
709
+ await prisma.group.delete({ where: { id: groupId } });
710
+ botManager.reloadBotConfigInRealTime(botId);
711
+
712
+ res.status(204).send();
713
+ } catch (error) { res.status(500).json({ error: 'Не удалось удалить группу.' }); }
714
+ });
715
+
716
+ router.post('/:botId/permissions', authorize('management:edit'), async (req, res) => {
717
+ try {
718
+ const botId = parseInt(req.params.botId);
719
+ const { name, description } = req.body;
720
+ if (!name) return res.status(400).json({ error: 'Имя права обязательно' });
721
+ const newPermission = await prisma.permission.create({
722
+ data: { name, description, botId, owner: 'admin' }
723
+ });
724
+
725
+ botManager.reloadBotConfigInRealTime(botId);
726
+
727
+ res.status(201).json(newPermission);
728
+ } catch (error) {
729
+ if (error.code === 'P2002') return res.status(409).json({ error: 'Право с таким именем уже существует для этого бота.' });
730
+ res.status(500).json({ error: 'Не удалось создать право.' });
731
+ }
732
+ });
733
+
734
+ router.put('/:botId/users/:userId', authorize('management:edit'), async (req, res) => {
735
+ try {
736
+ const botId = parseInt(req.params.botId, 10);
737
+ const userId = parseInt(req.params.userId, 10);
738
+ const { isBlacklisted, groupIds } = req.body;
739
+
740
+ const updateData = {};
741
+ if (typeof isBlacklisted === 'boolean') {
742
+ updateData.isBlacklisted = isBlacklisted;
743
+ }
744
+
745
+ if (Array.isArray(groupIds)) {
746
+ await prisma.userGroup.deleteMany({ where: { userId } });
747
+ updateData.groups = {
748
+ create: groupIds.map(gid => ({ groupId: gid })),
749
+ };
750
+ }
751
+
752
+ const updatedUser = await prisma.user.update({
753
+ where: { id: userId },
754
+ data: updateData,
755
+ include: { groups: true }
756
+ });
757
+
758
+ botManager.invalidateUserCache(botId, updatedUser.username);
759
+
760
+ UserService.clearCache(updatedUser.username, botId);
761
+
762
+ res.json(updatedUser);
763
+
764
+ } catch (error) {
765
+ console.error(`[API Error] /users/:userId PUT:`, error);
766
+ res.status(500).json({ error: 'Не удалось обновить пользователя' });
767
+ }
768
+ });
769
+
770
+ router.post('/start-all', authorize('bot:start_stop'), async (req, res) => {
771
+ try {
772
+ console.log('[API] Получен запрос на запуск всех ботов.');
773
+ const allBots = await prisma.bot.findMany({ include: { server: true } });
774
+ let startedCount = 0;
775
+ for (const botConfig of allBots) {
776
+ if (!botManager.bots.has(botConfig.id)) {
777
+ await botManager.startBot(botConfig);
778
+ startedCount++;
779
+ }
780
+ }
781
+ res.json({ success: true, message: `Запущено ${startedCount} ботов.` });
782
+ } catch (error) {
783
+ console.error('[API Error] /start-all:', error);
784
+ res.status(500).json({ error: 'Произошла ошибка при массовом запуске ботов.' });
785
+ }
786
+ });
787
+
788
+ router.post('/stop-all', authorize('bot:start_stop'), (req, res) => {
789
+ try {
790
+ console.log('[API] Получен запрос на остановку всех ботов.');
791
+ const botIds = Array.from(botManager.bots.keys());
792
+ let stoppedCount = 0;
793
+ for (const botId of botIds) {
794
+ botManager.stopBot(botId);
795
+ stoppedCount++;
796
+ }
797
+ res.json({ success: true, message: `Остановлено ${stoppedCount} ботов.` });
798
+ } catch (error) {
799
+ console.error('[API Error] /stop-all:', error);
800
+ res.status(500).json({ error: 'Произошла ошибка при массовой остановке ботов.' });
801
+ }
802
+ });
803
+
804
+ router.get('/:id/settings/all', authorize('bot:update'), async (req, res) => {
805
+ try {
806
+ const botId = parseInt(req.params.id, 10);
807
+
808
+ const bot = await prisma.bot.findUnique({
809
+ where: { id: botId },
810
+ include: {
811
+ server: true,
812
+ installedPlugins: {
813
+ orderBy: { name: 'asc' }
814
+ }
815
+ }
816
+ });
817
+
818
+ if (!bot) {
819
+ return res.status(404).json({ error: 'Бот не найден' });
820
+ }
821
+
822
+ const allSettings = {
823
+ bot: {
824
+ id: bot.id,
825
+ username: bot.username,
826
+ prefix: bot.prefix,
827
+ note: bot.note,
828
+ owners: bot.owners,
829
+ serverId: bot.serverId,
830
+ proxyHost: bot.proxyHost,
831
+ proxyPort: bot.proxyPort,
832
+ proxyUsername: bot.proxyUsername,
833
+ },
834
+ plugins: []
835
+ };
836
+
837
+ const pluginSettingsPromises = bot.installedPlugins.map(async (plugin) => {
838
+ const manifest = plugin.manifest ? JSON.parse(plugin.manifest) : {};
839
+
840
+ if (!manifest.settings || Object.keys(manifest.settings).length === 0) {
841
+ return null;
842
+ }
843
+
844
+ const savedSettings = plugin.settings ? JSON.parse(plugin.settings) : {};
845
+ let defaultSettings = {};
846
+
847
+ for (const key in manifest.settings) {
848
+ const config = manifest.settings[key];
849
+ if (config.type === 'json_file' && config.defaultPath) {
850
+ const configFilePath = path.join(plugin.path, config.defaultPath);
851
+ try {
852
+ const fileContent = await fs.readFile(configFilePath, 'utf-8');
853
+ defaultSettings[key] = JSON.parse(fileContent);
854
+ } catch (e) { defaultSettings[key] = {}; }
855
+ } else {
856
+ try { defaultSettings[key] = JSON.parse(config.default || 'null'); }
857
+ catch { defaultSettings[key] = config.default; }
858
+ }
859
+ }
860
+
861
+ return {
862
+ id: plugin.id,
863
+ name: plugin.name,
864
+ description: plugin.description,
865
+ isEnabled: plugin.isEnabled,
866
+ manifest: manifest,
867
+ settings: { ...defaultSettings, ...savedSettings }
868
+ };
869
+ });
870
+
871
+ allSettings.plugins = (await Promise.all(pluginSettingsPromises)).filter(Boolean);
872
+
873
+ res.json(allSettings);
874
+
875
+ } catch (error) {
876
+ console.error("[API Error] /settings/all GET:", error);
877
+ res.status(500).json({ error: 'Не удалось загрузить все настройки' });
878
+ }
879
+ });
880
+
881
+ const nodeRegistry = require('../../core/NodeRegistry');
882
+
883
+ router.get('/:botId/visual-editor/nodes', authorize('management:view'), (req, res) => {
884
+ try {
885
+ const { graphType } = req.query;
886
+ const nodesByCategory = nodeRegistry.getNodesByCategory(graphType);
887
+ res.json(nodesByCategory);
888
+ } catch (error) {
889
+ console.error('[API Error] /visual-editor/nodes GET:', error);
890
+ res.status(500).json({ error: 'Failed to get available nodes' });
891
+ }
892
+ });
893
+
894
+ router.get('/:botId/visual-editor/node-config', authorize('management:view'), (req, res) => {
895
+ try {
896
+ const { types } = req.query;
897
+ if (!types) {
898
+ return res.status(400).json({ error: 'Node types must be provided' });
899
+ }
900
+ const typeArray = Array.isArray(types) ? types : [types];
901
+ const config = nodeRegistry.getNodesByTypes(typeArray);
902
+ res.json(config);
903
+ } catch (error) {
904
+ console.error('[API Error] /visual-editor/node-config GET:', error);
905
+ res.status(500).json({ error: 'Failed to get node configuration' });
906
+ }
907
+ });
908
+
909
+ router.get('/:botId/visual-editor/permissions', authorize('management:view'), async (req, res) => {
910
+ try {
911
+ const botId = parseInt(req.params.botId, 10);
912
+ const permissions = await prisma.permission.findMany({
913
+ where: { botId },
914
+ orderBy: { name: 'asc' }
915
+ });
916
+ res.json(permissions);
917
+ } catch (error) {
918
+ console.error('[API Error] /visual-editor/permissions GET:', error);
919
+ res.status(500).json({ error: 'Failed to get permissions' });
920
+ }
921
+ });
922
+
923
+ router.post('/:botId/commands/visual', authorize('management:edit'), async (req, res) => {
924
+ try {
925
+ const botId = parseInt(req.params.botId, 10);
926
+ const {
927
+ name,
928
+ description,
929
+ aliases = [],
930
+ permissionId,
931
+ cooldown = 0,
932
+ allowedChatTypes = ['chat', 'private'],
933
+ argumentsJson = '[]',
934
+ graphJson = 'null'
935
+ } = req.body;
936
+
937
+ if (!name) {
938
+ return res.status(400).json({ error: 'Command name is required' });
939
+ }
940
+
941
+ const newCommand = await prisma.command.create({
942
+ data: {
943
+ botId,
944
+ name,
945
+ description,
946
+ aliases: JSON.stringify(aliases),
947
+ permissionId: permissionId || null,
948
+ cooldown,
949
+ allowedChatTypes: JSON.stringify(allowedChatTypes),
950
+ isVisual: true,
951
+ argumentsJson,
952
+ graphJson,
953
+ pluginOwnerId: null
954
+ }
955
+ });
956
+
957
+ botManager.reloadBotConfigInRealTime(botId);
958
+ res.status(201).json(newCommand);
959
+ } catch (error) {
960
+ if (error.code === 'P2002') {
961
+ return res.status(409).json({ error: 'Command with this name already exists' });
962
+ }
963
+ console.error('[API Error] /commands/visual POST:', error);
964
+ res.status(500).json({ error: 'Failed to create visual command' });
965
+ }
966
+ });
967
+
968
+ router.put('/:botId/commands/:commandId/visual', authorize('management:edit'), async (req, res) => {
969
+ try {
970
+ const botId = parseInt(req.params.botId, 10);
971
+ const commandId = parseInt(req.params.commandId, 10);
972
+ const {
973
+ name,
974
+ description,
975
+ aliases,
976
+ permissionId,
977
+ cooldown,
978
+ allowedChatTypes,
979
+ argumentsJson,
980
+ graphJson
981
+ } = req.body;
982
+
983
+ const dataToUpdate = { isVisual: true };
984
+
985
+ if (name) dataToUpdate.name = name;
986
+ if (description !== undefined) dataToUpdate.description = description;
987
+ if (Array.isArray(aliases)) dataToUpdate.aliases = JSON.stringify(aliases);
988
+ if (permissionId !== undefined) dataToUpdate.permissionId = permissionId || null;
989
+ if (typeof cooldown === 'number') dataToUpdate.cooldown = cooldown;
990
+ if (Array.isArray(allowedChatTypes)) dataToUpdate.allowedChatTypes = JSON.stringify(allowedChatTypes);
991
+ if (argumentsJson !== undefined) dataToUpdate.argumentsJson = argumentsJson;
992
+ if (graphJson !== undefined) dataToUpdate.graphJson = graphJson;
993
+
994
+ const updatedCommand = await prisma.command.update({
995
+ where: { id: commandId, botId },
996
+ data: dataToUpdate
997
+ });
998
+
999
+ if (graphJson && updatedCommand.pluginOwnerId) {
1000
+ try {
1001
+ const plugin = await prisma.installedPlugin.findUnique({
1002
+ where: { id: updatedCommand.pluginOwnerId }
1003
+ });
1004
+
1005
+ if (plugin) {
1006
+ const graphDir = path.join(plugin.path, 'graph');
1007
+ await fse.mkdir(graphDir, { recursive: true });
1008
+
1009
+ const graphFile = path.join(graphDir, `${updatedCommand.name}.json`);
1010
+ await fse.writeJson(graphFile, JSON.parse(graphJson), { spaces: 2 });
1011
+ console.log(`[API] Граф команды ${updatedCommand.name} сохранен в ${graphFile}`);
1012
+ }
1013
+ } catch (error) {
1014
+ console.error(`[API] Ошибка сохранения графа в папку плагина:`, error);
1015
+ }
1016
+ }
1017
+
1018
+ botManager.reloadBotConfigInRealTime(botId);
1019
+ res.json(updatedCommand);
1020
+ } catch (error) {
1021
+ if (error.code === 'P2002') {
1022
+ return res.status(409).json({ error: 'Command with this name already exists' });
1023
+ }
1024
+ console.error('[API Error] /commands/:commandId/visual PUT:', error);
1025
+ res.status(500).json({ error: 'Failed to update visual command' });
1026
+ }
1027
+ });
1028
+
1029
+ router.get('/:botId/commands/:commandId/export', authorize('management:view'), async (req, res) => {
1030
+ try {
1031
+ const botId = parseInt(req.params.botId, 10);
1032
+ const commandId = parseInt(req.params.commandId, 10);
1033
+
1034
+ const command = await prisma.command.findUnique({
1035
+ where: { id: commandId, botId: botId },
1036
+ });
1037
+
1038
+ if (!command) {
1039
+ return res.status(404).json({ error: 'Command not found' });
1040
+ }
1041
+
1042
+ const exportData = {
1043
+ version: '1.0',
1044
+ type: 'command',
1045
+ ...command
1046
+ };
1047
+
1048
+ delete exportData.id;
1049
+ delete exportData.botId;
1050
+
1051
+ res.json(exportData);
1052
+ } catch (error) {
1053
+ console.error('Failed to export command:', error);
1054
+ res.status(500).json({ error: 'Failed to export command' });
1055
+ }
1056
+ });
1057
+
1058
+ router.post('/:botId/commands/import', authorize('management:edit'), async (req, res) => {
1059
+ try {
1060
+ const botId = parseInt(req.params.botId, 10);
1061
+ const importData = req.body;
1062
+
1063
+ if (importData.type !== 'command') {
1064
+ return res.status(400).json({ error: 'Invalid file type. Expected "command".' });
1065
+ }
1066
+
1067
+ let commandName = importData.name;
1068
+ let counter = 1;
1069
+
1070
+ while (await prisma.command.findFirst({ where: { botId, name: commandName } })) {
1071
+ commandName = `${importData.name}_imported_${counter}`;
1072
+ counter++;
1073
+ }
1074
+
1075
+ let finalGraphJson = importData.graphJson;
1076
+
1077
+ if (finalGraphJson && finalGraphJson !== 'null') {
1078
+ const graph = JSON.parse(finalGraphJson);
1079
+ const nodeIdMap = new Map();
1080
+
1081
+ if (graph.nodes) {
1082
+ graph.nodes.forEach(node => {
1083
+ const oldId = node.id;
1084
+ const newId = `${node.type}-${randomUUID()}`;
1085
+ nodeIdMap.set(oldId, newId);
1086
+ node.id = newId;
1087
+ });
1088
+ }
1089
+
1090
+ if (graph.connections) {
1091
+ graph.connections.forEach(conn => {
1092
+ conn.id = `edge-${randomUUID()}`;
1093
+ conn.sourceNodeId = nodeIdMap.get(conn.sourceNodeId) || conn.sourceNodeId;
1094
+ conn.targetNodeId = nodeIdMap.get(conn.targetNodeId) || conn.targetNodeId;
1095
+ });
1096
+ }
1097
+
1098
+ finalGraphJson = JSON.stringify(graph);
1099
+ }
1100
+
1101
+ const newCommand = await prisma.command.create({
1102
+ data: {
1103
+ botId: botId,
1104
+ name: commandName,
1105
+ description: importData.description,
1106
+ aliases: importData.aliases,
1107
+ permissionId: null,
1108
+ cooldown: importData.cooldown,
1109
+ allowedChatTypes: importData.allowedChatTypes,
1110
+ isVisual: importData.isVisual,
1111
+ isEnabled: importData.isEnabled,
1112
+ argumentsJson: importData.argumentsJson,
1113
+ graphJson: finalGraphJson,
1114
+ owner: 'visual_editor',
1115
+ }
1116
+ });
1117
+
1118
+ botManager.reloadBotConfigInRealTime(botId);
1119
+ res.status(201).json(newCommand);
1120
+ } catch (error) {
1121
+ console.error("Failed to import command:", error);
1122
+ res.status(500).json({ error: 'Failed to import command' });
1123
+ }
1124
+ });
1125
+
1126
+ router.post('/:botId/commands', authorize('management:edit'), async (req, res) => {
1127
+ try {
1128
+ const botId = parseInt(req.params.botId, 10);
1129
+ const {
1130
+ name,
1131
+ description,
1132
+ aliases = [],
1133
+ permissionId,
1134
+ cooldown = 0,
1135
+ allowedChatTypes = ['chat', 'private'],
1136
+ isVisual = false,
1137
+ argumentsJson = '[]',
1138
+ graphJson = 'null'
1139
+ } = req.body;
1140
+
1141
+ if (!name) {
1142
+ return res.status(400).json({ error: 'Command name is required' });
1143
+ }
1144
+
1145
+ const newCommand = await prisma.command.create({
1146
+ data: {
1147
+ botId,
1148
+ name,
1149
+ description,
1150
+ aliases: JSON.stringify(aliases),
1151
+ permissionId: permissionId || null,
1152
+ cooldown,
1153
+ allowedChatTypes: JSON.stringify(allowedChatTypes),
1154
+ isVisual,
1155
+ argumentsJson,
1156
+ graphJson,
1157
+ owner: isVisual ? 'visual_editor' : 'manual',
1158
+ pluginOwnerId: null
1159
+ }
1160
+ });
1161
+
1162
+ if (graphJson && graphJson !== 'null' && req.body.pluginOwnerId) {
1163
+ try {
1164
+ const plugin = await prisma.installedPlugin.findUnique({
1165
+ where: { id: req.body.pluginOwnerId }
1166
+ });
1167
+
1168
+ if (plugin) {
1169
+ const graphDir = path.join(plugin.path, 'graph');
1170
+ await fse.mkdir(graphDir, { recursive: true });
1171
+
1172
+ const graphFile = path.join(graphDir, `${name}.json`);
1173
+ await fse.writeJson(graphFile, JSON.parse(graphJson), { spaces: 2 });
1174
+ console.log(`[API] Граф команды ${name} сохранен в ${graphFile}`);
1175
+ }
1176
+ } catch (error) {
1177
+ console.error(`[API] Ошибка сохранения графа в папку плагина:`, error);
1178
+ }
1179
+ }
1180
+
1181
+ botManager.reloadBotConfigInRealTime(botId);
1182
+ res.status(201).json(newCommand);
1183
+ } catch (error) {
1184
+ if (error.code === 'P2002') {
1185
+ return res.status(409).json({ error: 'Command with this name already exists' });
1186
+ }
1187
+ console.error('[API Error] /commands POST:', error);
1188
+ res.status(500).json({ error: 'Failed to create command' });
1189
+ }
1190
+ });
1191
+
1192
+ router.delete('/:botId/commands/:commandId', authorize('management:edit'), async (req, res) => {
1193
+ try {
1194
+ const botId = parseInt(req.params.botId, 10);
1195
+ const commandId = parseInt(req.params.commandId, 10);
1196
+
1197
+ await prisma.command.delete({
1198
+ where: { id: commandId, botId: botId },
1199
+ });
1200
+
1201
+ botManager.reloadBotConfigInRealTime(botId);
1202
+ res.status(204).send();
1203
+ } catch (error) {
1204
+ console.error(`[API Error] /commands/:commandId DELETE:`, error);
1205
+ res.status(500).json({ error: 'Failed to delete command' });
1206
+ }
1207
+ });
1208
+
1209
+ router.get('/:botId/event-graphs/:graphId', authorize('management:view'), async (req, res) => {
1210
+ try {
1211
+ const botId = parseInt(req.params.botId, 10);
1212
+ const graphId = parseInt(req.params.graphId, 10);
1213
+
1214
+ const eventGraph = await prisma.eventGraph.findUnique({
1215
+ where: { id: graphId, botId },
1216
+ include: { triggers: true },
1217
+ });
1218
+
1219
+ if (!eventGraph) {
1220
+ return res.status(404).json({ error: 'Граф события не найден' });
1221
+ }
1222
+
1223
+ res.json(eventGraph);
1224
+ } catch (error) {
1225
+ console.error(`[API Error] /event-graphs/:graphId GET:`, error);
1226
+ res.status(500).json({ error: 'Не удалось получить граф события' });
1227
+ }
1228
+ });
1229
+
1230
+ router.post('/:botId/event-graphs', authorize('management:edit'), async (req, res) => {
1231
+ try {
1232
+ const botId = parseInt(req.params.botId, 10);
1233
+ const { name, description, graphJson, variables, eventType, isEnabled = true } = req.body;
1234
+
1235
+ if (!name || typeof name !== 'string' || name.trim() === '') {
1236
+ return res.status(400).json({ error: 'Имя графа обязательно и должно быть непустой строкой' });
1237
+ }
1238
+
1239
+ let graphJsonString;
1240
+ if (graphJson) {
1241
+ if (typeof graphJson === 'string') {
1242
+ graphJsonString = graphJson;
1243
+ } else {
1244
+ graphJsonString = JSON.stringify(graphJson);
1245
+ }
1246
+ } else {
1247
+ graphJsonString = JSON.stringify({
1248
+ nodes: [],
1249
+ connections: []
1250
+ });
1251
+ }
1252
+
1253
+ console.log('[API] Final graphJsonString:', graphJsonString);
1254
+
1255
+ let eventTypes = [];
1256
+ try {
1257
+ const parsedGraph = JSON.parse(graphJsonString);
1258
+ if (parsedGraph.nodes && Array.isArray(parsedGraph.nodes)) {
1259
+ const eventNodes = parsedGraph.nodes.filter(node => node.type && node.type.startsWith('event:'));
1260
+ eventTypes = [...new Set(eventNodes.map(node => node.type.split(':')[1]))];
1261
+ }
1262
+ } catch (error) {
1263
+ console.warn('[API] Не удалось извлечь типы событий из графа:', error.message);
1264
+ }
1265
+
1266
+ const newEventGraph = await prisma.eventGraph.create({
1267
+ data: {
1268
+ botId,
1269
+ name: name.trim(),
1270
+ description: description || '',
1271
+ isEnabled: isEnabled,
1272
+ graphJson: graphJsonString,
1273
+ variables: variables || '[]',
1274
+ eventType: eventType || 'custom',
1275
+ triggers: {
1276
+ create: eventTypes.map(eventType => ({ eventType }))
1277
+ }
1278
+ },
1279
+ include: { triggers: true }
1280
+ });
1281
+
1282
+ console.log('[API] Created event graph:', newEventGraph);
1283
+ res.status(201).json(newEventGraph);
1284
+ } catch (error) {
1285
+ if (error.code === 'P2002') {
1286
+ return res.status(409).json({ error: 'Граф событий с таким именем уже существует' });
1287
+ }
1288
+ console.error(`[API Error] /event-graphs POST:`, error);
1289
+ res.status(500).json({ error: 'Не удалось создать граф событий' });
1290
+ }
1291
+ });
1292
+
1293
+ router.delete('/:botId/event-graphs/:graphId', authorize('management:edit'), async (req, res) => {
1294
+ try {
1295
+ const botId = parseInt(req.params.botId, 10);
1296
+ const graphId = parseInt(req.params.graphId, 10);
1297
+
1298
+ await prisma.eventGraph.delete({
1299
+ where: { id: graphId, botId: botId },
1300
+ });
1301
+
1302
+ res.status(204).send();
1303
+ } catch (error) {
1304
+ console.error(`[API Error] /event-graphs/:graphId DELETE:`, error);
1305
+ res.status(500).json({ error: 'Не удалось удалить граф событий' });
1306
+ }
1307
+ });
1308
+
1309
+ router.put('/:botId/event-graphs/:graphId', authorize('management:edit'), async (req, res) => {
1310
+ const { botId, graphId } = req.params;
1311
+ const { name, isEnabled, graphJson, variables, pluginOwnerId } = req.body;
1312
+
1313
+ if (!name || typeof name !== 'string' || name.trim() === '') {
1314
+ return res.status(400).json({ error: 'Поле name обязательно и должно быть непустой строкой.' });
1315
+ }
1316
+
1317
+ if (typeof isEnabled !== 'boolean') {
1318
+ return res.status(400).json({ error: 'Поле isEnabled должно быть true или false.' });
1319
+ }
1320
+
1321
+ try {
1322
+ const dataToUpdate = {
1323
+ name: name.trim(),
1324
+ isEnabled,
1325
+ };
1326
+
1327
+ if (graphJson !== undefined) {
1328
+ dataToUpdate.graphJson = graphJson;
1329
+ }
1330
+
1331
+ if (variables !== undefined) {
1332
+ dataToUpdate.variables = Array.isArray(variables) ? JSON.stringify(variables) : variables;
1333
+ }
1334
+
1335
+ if (pluginOwnerId !== undefined) {
1336
+ dataToUpdate.pluginOwnerId = pluginOwnerId;
1337
+ }
1338
+
1339
+ const updatedGraph = await prisma.eventGraph.update({
1340
+ where: { id: parseInt(graphId), botId: parseInt(botId) },
1341
+ data: dataToUpdate
1342
+ });
1343
+
1344
+ res.json(updatedGraph);
1345
+ } catch (error) {
1346
+ console.error(`[API Error] /event-graphs/:graphId PUT:`, error);
1347
+ res.status(500).json({ error: 'Ошибка при обновлении графа событий.' });
1348
+ }
1349
+ });
1350
+
1351
+ router.post('/:botId/visual-editor/save', authorize('management:edit'), async (req, res) => {
1352
+ });
1353
+
1354
+ router.get('/:botId/ui-extensions', authorize('plugin:list'), async (req, res) => {
1355
+ try {
1356
+ const botId = parseInt(req.params.botId, 10);
1357
+ const enabledPlugins = await prisma.installedPlugin.findMany({
1358
+ where: { botId: botId, isEnabled: true }
1359
+ });
1360
+
1361
+ const extensions = [];
1362
+ for (const plugin of enabledPlugins) {
1363
+ if (plugin.manifest) {
1364
+ try {
1365
+ const manifest = JSON.parse(plugin.manifest);
1366
+ if (manifest.uiExtensions && Array.isArray(manifest.uiExtensions)) {
1367
+ manifest.uiExtensions.forEach(ext => {
1368
+ extensions.push({
1369
+ pluginName: plugin.name,
1370
+ ...ext
1371
+ });
1372
+ });
1373
+ }
1374
+ } catch (e) {
1375
+ console.error(`Ошибка парсинга манифеста для плагина ${plugin.name}:`, e);
1376
+ }
1377
+ }
1378
+ }
1379
+ res.json(extensions);
1380
+ } catch (error) {
1381
+ res.status(500).json({ error: 'Не удалось получить расширения интерфейса' });
1382
+ }
1383
+ });
1384
+
1385
+ router.get('/:botId/plugins/:pluginName/ui-content/:path', authorize('plugin:list'), async (req, res) => {
1386
+ const { botId, pluginName, path: uiPath } = req.params;
1387
+ const numericBotId = parseInt(botId, 10);
1388
+
1389
+ try {
1390
+ const plugin = await prisma.installedPlugin.findFirst({
1391
+ where: { botId: numericBotId, name: pluginName, isEnabled: true }
1392
+ });
1393
+
1394
+ if (!plugin) {
1395
+ return res.status(404).json({ error: `Активный плагин "${pluginName}" не найден для этого бота.` });
1396
+ }
1397
+
1398
+ const manifest = plugin.manifest ? JSON.parse(plugin.manifest) : {};
1399
+ const savedSettings = plugin.settings ? JSON.parse(plugin.settings) : {};
1400
+ const defaultSettings = {};
1401
+
1402
+ if (manifest.settings) {
1403
+ for (const key in manifest.settings) {
1404
+ const config = manifest.settings[key];
1405
+ if (config.type === 'json_file' && config.defaultPath) {
1406
+ const configFilePath = path.join(plugin.path, config.defaultPath);
1407
+ try {
1408
+ const fileContent = await fs.readFile(configFilePath, 'utf-8');
1409
+ defaultSettings[key] = JSON.parse(fileContent);
1410
+ } catch (e) { defaultSettings[key] = {}; }
1411
+ } else {
1412
+ try { defaultSettings[key] = JSON.parse(config.default || 'null'); }
1413
+ catch { defaultSettings[key] = config.default; }
1414
+ }
1415
+ }
1416
+ }
1417
+ const finalSettings = { ...defaultSettings, ...savedSettings };
1418
+
1419
+ const mainFilePath = manifest.main || 'index.js';
1420
+ const pluginEntryPoint = path.join(plugin.path, mainFilePath);
1421
+
1422
+ delete require.cache[require.resolve(pluginEntryPoint)];
1423
+ const pluginModule = require(pluginEntryPoint);
1424
+
1425
+ if (typeof pluginModule.getUiPageContent !== 'function') {
1426
+ return res.status(501).json({ error: `Плагин "${pluginName}" не предоставляет кастомный UI контент.` });
1427
+ }
1428
+
1429
+ const botProcess = botManager.bots.get(numericBotId);
1430
+ const botApi = botProcess ? botProcess.api : null;
1431
+
1432
+ const content = await pluginModule.getUiPageContent({
1433
+ path: uiPath,
1434
+ bot: botApi,
1435
+ botId: numericBotId,
1436
+ settings: finalSettings
1437
+ });
1438
+
1439
+ if (content === null) {
1440
+ return res.status(404).json({ error: `Для пути "${uiPath}" не найдено содержимого в плагине "${pluginName}".` });
1441
+ }
1442
+
1443
+ res.json(content);
1444
+
1445
+ } catch (error) {
1446
+ console.error(`[UI Content] Ошибка при получении контента для плагина "${pluginName}":`, error);
1447
+ res.status(500).json({ error: error.message || 'Внутренняя ошибка сервера.' });
1448
+ }
1449
+ });
1450
+
1451
+
1452
+ router.post('/:botId/plugins/:pluginName/action', authorize('plugin:list'), async (req, res) => {
1453
+ const { botId, pluginName } = req.params;
1454
+ const { actionName, payload } = req.body;
1455
+ const numericBotId = parseInt(botId, 10);
1456
+
1457
+ if (!actionName) {
1458
+ return res.status(400).json({ error: 'Необходимо указать "actionName".' });
1459
+ }
1460
+
1461
+ try {
1462
+ const botProcess = botManager.bots.get(numericBotId);
1463
+
1464
+ if (!botProcess) {
1465
+ return res.status(404).json({ error: 'Бот не найден или не запущен.' });
1466
+ }
1467
+
1468
+ const plugin = await prisma.installedPlugin.findFirst({
1469
+ where: { botId: numericBotId, name: pluginName, isEnabled: true }
1470
+ });
1471
+
1472
+ if (!plugin) {
1473
+ return res.status(404).json({ error: `Активный плагин с таким именем "${pluginName}" не найден.` });
1474
+ }
1475
+
1476
+ const manifest = plugin.manifest ? JSON.parse(plugin.manifest) : {};
1477
+ const savedSettings = plugin.settings ? JSON.parse(plugin.settings) : {};
1478
+ const defaultSettings = {};
1479
+
1480
+ if (manifest.settings) {
1481
+ for (const key in manifest.settings) {
1482
+ const config = manifest.settings[key];
1483
+ if (config.type === 'json_file' && config.defaultPath) {
1484
+ const configFilePath = path.join(plugin.path, config.defaultPath);
1485
+ try {
1486
+ const fileContent = await fs.readFile(configFilePath, 'utf-8');
1487
+ defaultSettings[key] = JSON.parse(fileContent);
1488
+ } catch (e) {
1489
+ console.error(`[Action] Не удалось прочитать defaultPath для ${pluginName}: ${e.message}`);
1490
+ defaultSettings[key] = {};
1491
+ }
1492
+ } else {
1493
+ try {
1494
+ defaultSettings[key] = JSON.parse(config.default || 'null');
1495
+ } catch {
1496
+ defaultSettings[key] = config.default;
1497
+ }
1498
+ }
1499
+ }
1500
+ }
1501
+ const finalSettings = { ...defaultSettings, ...savedSettings };
1502
+
1503
+ const mainFilePath = manifest.main || 'index.js';
1504
+ const pluginPath = path.join(plugin.path, mainFilePath);
1505
+
1506
+ delete require.cache[require.resolve(pluginPath)];
1507
+ const pluginModule = require(pluginPath);
1508
+
1509
+ if (typeof pluginModule.handleAction !== 'function') {
1510
+ return res.status(501).json({ error: `Плагин "${pluginName}" не поддерживает обработку действий.` });
1511
+ }
1512
+
1513
+ const result = await pluginModule.handleAction({
1514
+ botProcess: botProcess,
1515
+ botId: numericBotId,
1516
+ action: actionName,
1517
+ payload: payload,
1518
+ settings: finalSettings
1519
+ });
1520
+
1521
+ res.json({ success: true, message: 'Действие выполнено.', result: result || null });
1522
+
1523
+ } catch (error) {
1524
+ console.error(`Ошибка выполнения действия "${actionName}" для плагина "${pluginName}":`, error);
1525
+ res.status(500).json({ error: error.message || 'Внутренняя ошибка сервера.' });
1526
+ }
1527
+ });
1528
+
1529
+
1530
+ router.get('/:botId/export', authorize('bot:export'), async (req, res) => {
1531
+ try {
1532
+ const botId = parseInt(req.params.botId, 10);
1533
+ const {
1534
+ includeCommands,
1535
+ includePermissions,
1536
+ includePluginFiles,
1537
+ includePluginDataStore,
1538
+ includeEventGraphs,
1539
+ } = req.query;
1540
+
1541
+ const bot = await prisma.bot.findUnique({ where: { id: botId } });
1542
+ if (!bot) {
1543
+ return res.status(404).json({ error: 'Bot not found' });
1544
+ }
1545
+
1546
+ const archive = archiver('zip', { zlib: { level: 9 } });
1547
+ res.attachment(`bot_${bot.username}_export_${new Date().toISOString()}.zip`);
1548
+ archive.pipe(res);
1549
+
1550
+ const botData = { ...bot };
1551
+ delete botData.password;
1552
+ delete botData.proxyPassword;
1553
+ archive.append(JSON.stringify(botData, null, 2), { name: 'bot.json' });
1554
+
1555
+ if (includeCommands === 'true') {
1556
+ const commands = await prisma.command.findMany({ where: { botId } });
1557
+ archive.append(JSON.stringify(commands, null, 2), { name: 'commands.json' });
1558
+ }
1559
+
1560
+ if (includePermissions === 'true') {
1561
+ const users = await prisma.user.findMany({ where: { botId }, include: { groups: { include: { group: true } } } });
1562
+ const groups = await prisma.group.findMany({ where: { botId }, include: { permissions: { include: { permission: true } } } });
1563
+ const permissions = await prisma.permission.findMany({ where: { botId } });
1564
+ const permissionsData = { users, groups, permissions };
1565
+ archive.append(JSON.stringify(permissionsData, null, 2), { name: 'permissions.json' });
1566
+ }
1567
+
1568
+ if (includeEventGraphs === 'true') {
1569
+ const eventGraphs = await prisma.eventGraph.findMany({ where: { botId } });
1570
+ archive.append(JSON.stringify(eventGraphs, null, 2), { name: 'event_graphs.json' });
1571
+ }
1572
+
1573
+ if (includePluginFiles === 'true' || includePluginDataStore === 'true') {
1574
+ const installedPlugins = await prisma.installedPlugin.findMany({ where: { botId } });
1575
+ archive.append(JSON.stringify(installedPlugins, null, 2), { name: 'plugins.json' });
1576
+
1577
+ if (includePluginFiles === 'true') {
1578
+ for (const plugin of installedPlugins) {
1579
+ const pluginPath = plugin.path;
1580
+ if (await fs.stat(pluginPath).then(s => s.isDirectory()).catch(() => false)) {
1581
+ archive.directory(pluginPath, `plugins/${plugin.name}`);
1582
+ }
1583
+ }
1584
+ }
1585
+ if (includePluginDataStore === 'true') {
1586
+ console.log(`[Export] Экспорт PluginDataStore для бота ${botId}`);
1587
+ const pluginDataStore = await prisma.pluginDataStore.findMany({
1588
+ where: { botId: parseInt(botId) }
1589
+ });
1590
+ console.log(`[Export] Найдено записей PluginDataStore: ${pluginDataStore.length}`);
1591
+ if (pluginDataStore.length > 0) {
1592
+ archive.append(JSON.stringify(pluginDataStore, null, 2), { name: 'plugin_data_store.json' });
1593
+ console.log(`[Export] Данные PluginDataStore добавлены в архив`);
1594
+ } else {
1595
+ console.log(`[Export] Нет данных PluginDataStore для экспорта`);
1596
+ }
1597
+ }
1598
+ }
1599
+
1600
+ await archive.finalize();
1601
+
1602
+ } catch (error) {
1603
+ console.error('Failed to export bot:', error);
1604
+ res.status(500).json({ error: `Failed to export bot: ${error.message}` });
1605
+ }
1606
+ });
1607
+
1608
+ router.post('/import', authorize('bot:create'), upload.single('file'), async (req, res) => {
1609
+ if (!req.file) {
1610
+ return res.status(400).json({ error: 'No file uploaded.' });
1611
+ }
1612
+
1613
+ const botIdMap = new Map();
1614
+
1615
+ try {
1616
+ const zip = new AdmZip(req.file.buffer);
1617
+ const zipEntries = zip.getEntries();
1618
+
1619
+ const botDataEntry = zipEntries.find(e => e.entryName === 'bot.json');
1620
+ if (!botDataEntry) {
1621
+ return res.status(400).json({ error: 'Archive missing bot.json' });
1622
+ }
1623
+ const botData = JSON.parse(botDataEntry.getData().toString('utf8'));
1624
+
1625
+ const server = await prisma.server.findFirst();
1626
+ if (!server) {
1627
+ return res.status(500).json({ error: 'No servers configured in the target system.' });
1628
+ }
1629
+
1630
+ let newBotName = botData.username;
1631
+ let counter = 1;
1632
+ while (await prisma.bot.findFirst({ where: { username: newBotName } })) {
1633
+ newBotName = `${botData.username}_imported_${counter}`;
1634
+ counter++;
1635
+ }
1636
+
1637
+ const newBot = await prisma.bot.create({
1638
+ data: {
1639
+ ...botData,
1640
+ id: undefined,
1641
+ username: newBotName,
1642
+ serverId: server.id,
1643
+ password: null,
1644
+ proxyPassword: null
1645
+ },
1646
+ include: { server: true }
1647
+ });
1648
+
1649
+ botIdMap.set(botData.id, newBot.id);
1650
+
1651
+ const permissionsEntry = zipEntries.find(e => e.entryName === 'permissions.json');
1652
+ let pMap = new Map();
1653
+
1654
+ if (permissionsEntry) {
1655
+ const { users, groups, permissions } = JSON.parse(permissionsEntry.getData().toString('utf8'));
1656
+
1657
+ await setupDefaultPermissionsForBot(newBot.id, prisma);
1658
+
1659
+ for(let p of permissions.filter(p=>p.owner === 'system')) {
1660
+ const existingPermission = await prisma.permission.findFirst({
1661
+ where: {
1662
+ botId: newBot.id,
1663
+ name: p.name,
1664
+ owner: 'system'
1665
+ }
1666
+ });
1667
+ if (existingPermission) {
1668
+ pMap.set(p.id, existingPermission.id);
1669
+ }
1670
+ }
1671
+
1672
+ for(let p of permissions.filter(p=>p.owner !== 'system')) {
1673
+ const newP = await prisma.permission.create({ data: { ...p, id: undefined, botId: newBot.id }});
1674
+ pMap.set(p.id, newP.id);
1675
+ }
1676
+
1677
+ const gMap = new Map();
1678
+ for(let g of groups.filter(g=>g.owner !== 'system')) {
1679
+ const newG = await prisma.group.create({ data: { ...g, id: undefined, botId: newBot.id, permissions: {
1680
+ create: g.permissions.map(gp => ({ permissionId: pMap.get(gp.permissionId) })).filter(p=>p.permissionId)
1681
+ }}});
1682
+ gMap.set(g.id, newG.id);
1683
+ }
1684
+
1685
+ for(let u of users) {
1686
+ await prisma.user.create({ data: { ...u, id: undefined, botId: newBot.id, groups: {
1687
+ create: u.groups.map(ug => ({ groupId: gMap.get(ug.groupId) })).filter(g=>g.groupId)
1688
+ }}});
1689
+ }
1690
+ }
1691
+
1692
+ const pluginDataStoreEntry = zipEntries.find(e => e.entryName === 'plugin_data_store.json');
1693
+ if (pluginDataStoreEntry) {
1694
+ console.log(`[Import] Импорт PluginDataStore для бота ${newBot.id}`);
1695
+ const pluginDataStore = JSON.parse(pluginDataStoreEntry.getData().toString('utf8'));
1696
+ console.log(`[Import] Найдено записей PluginDataStore: ${pluginDataStore.length}`);
1697
+
1698
+ for (let dataRecord of pluginDataStore) {
1699
+ delete dataRecord.id;
1700
+ dataRecord.botId = newBot.id;
1701
+ await prisma.pluginDataStore.create({ data: dataRecord });
1702
+ }
1703
+ console.log(`[Import] PluginDataStore успешно импортирован`);
1704
+ }
1705
+
1706
+ const pluginsEntry = zipEntries.find(e => e.entryName === 'plugins.json');
1707
+ let pluginMap = new Map();
1708
+
1709
+ if (pluginsEntry) {
1710
+ const plugins = JSON.parse(pluginsEntry.getData().toString('utf8'));
1711
+ const pluginsDir = path.join(os.homedir(), '.blockmine', 'storage', 'plugins');
1712
+ const botPluginsDir = path.join(pluginsDir, newBot.username);
1713
+ await fs.mkdir(botPluginsDir, { recursive: true });
1714
+
1715
+ for (let pluginData of plugins) {
1716
+ const oldPath = pluginData.path;
1717
+ const pluginName = pluginData.name;
1718
+ const newPluginPath = path.join(botPluginsDir, pluginName);
1719
+
1720
+ const oldPluginId = pluginData.id;
1721
+ delete pluginData.id;
1722
+ pluginData.botId = newBot.id;
1723
+ pluginData.path = path.resolve(newPluginPath);
1724
+
1725
+ for (const entry of zipEntries) {
1726
+ if (entry.entryName.startsWith(`plugins/${pluginName}/`)) {
1727
+ const relativePath = entry.entryName.replace(`plugins/${pluginName}/`, '');
1728
+ if (relativePath) {
1729
+ const destPath = path.join(newPluginPath, relativePath);
1730
+ const destDir = path.dirname(destPath);
1731
+ await fs.mkdir(destDir, { recursive: true });
1732
+
1733
+ if (!entry.isDirectory) {
1734
+ await fs.writeFile(destPath, entry.getData());
1735
+ }
1736
+ }
1737
+ }
1738
+ }
1739
+
1740
+ const newPlugin = await prisma.installedPlugin.create({ data: pluginData });
1741
+ pluginMap.set(oldPluginId, newPlugin.id);
1742
+ }
1743
+ }
1744
+
1745
+ const commandsEntry = zipEntries.find(e => e.entryName === 'commands.json');
1746
+ if (commandsEntry) {
1747
+ const commands = JSON.parse(commandsEntry.getData().toString('utf8'));
1748
+ for (let command of commands) {
1749
+ delete command.id;
1750
+ command.botId = newBot.id;
1751
+
1752
+ if (command.permissionId && pMap.has(command.permissionId)) {
1753
+ command.permissionId = pMap.get(command.permissionId);
1754
+ } else {
1755
+ command.permissionId = null;
1756
+ }
1757
+
1758
+ if (command.pluginOwnerId && pluginMap.has(command.pluginOwnerId)) {
1759
+ command.pluginOwnerId = pluginMap.get(command.pluginOwnerId);
1760
+ } else {
1761
+ command.pluginOwnerId = null;
1762
+ }
1763
+
1764
+ try {
1765
+ await prisma.command.create({ data: command });
1766
+ } catch (error) {
1767
+ console.warn(`[Import] Пропущена команда ${command.name}: ${error.message}`);
1768
+ }
1769
+ }
1770
+ }
1771
+
1772
+ const eventGraphsEntry = zipEntries.find(e => e.entryName === 'event_graphs.json');
1773
+ if (eventGraphsEntry) {
1774
+ const eventGraphs = JSON.parse(eventGraphsEntry.getData().toString('utf8'));
1775
+ for (let graph of eventGraphs) {
1776
+ delete graph.id;
1777
+ graph.botId = newBot.id;
1778
+
1779
+ if (graph.pluginOwnerId && pluginMap.has(graph.pluginOwnerId)) {
1780
+ graph.pluginOwnerId = pluginMap.get(graph.pluginOwnerId);
1781
+ } else {
1782
+ graph.pluginOwnerId = null;
1783
+ }
1784
+
1785
+ try {
1786
+ await prisma.eventGraph.create({ data: graph });
1787
+ } catch (error) {
1788
+ console.warn(`[Import] Пропущен граф ${graph.name}: ${error.message}`);
1789
+ }
1790
+ }
1791
+ }
1792
+
1793
+ res.status(201).json(newBot);
1794
+
1795
+ } catch (error) {
1796
+ console.error('Failed to import bot:', error);
1797
+ res.status(500).json({ error: `Failed to import bot: ${error.message}` });
1798
+ }
1799
+ });
1800
+
1801
+ module.exports = router;