blockmine 1.16.3 → 1.17.1

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,1801 +1,2144 @@
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;
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 botsWithoutSortOrder = await prisma.bot.findMany({
131
+ where: { sortOrder: null },
132
+ select: { id: true }
133
+ });
134
+
135
+ if (botsWithoutSortOrder.length > 0) {
136
+ console.log(`[API] Обновляем sortOrder для ${botsWithoutSortOrder.length} ботов`);
137
+ for (const bot of botsWithoutSortOrder) {
138
+ await prisma.bot.update({
139
+ where: { id: bot.id },
140
+ data: { sortOrder: bot.id }
141
+ });
142
+ }
143
+ }
144
+
145
+ const bots = await prisma.bot.findMany({
146
+ include: { server: true },
147
+ orderBy: { sortOrder: 'asc' }
148
+ });
149
+ res.json(bots);
150
+ } catch (error) {
151
+ console.error("[API /api/bots] Ошибка получения списка ботов:", error);
152
+ res.status(500).json({ error: 'Не удалось получить список ботов' });
153
+ }
154
+ });
155
+
156
+ router.get('/state', conditionalListAuth, (req, res) => {
157
+ try {
158
+ const state = botManager.getFullState();
159
+ res.json(state);
160
+ } catch (error) { res.status(500).json({ error: 'Не удалось получить состояние ботов' }); }
161
+ });
162
+
163
+ router.get('/:id/logs', conditionalListAuth, (req, res) => {
164
+ try {
165
+ const botId = parseInt(req.params.id, 10);
166
+ const { limit = 50, offset = 0 } = req.query;
167
+
168
+ const logs = botManager.getBotLogs(botId);
169
+
170
+ const startIndex = parseInt(offset);
171
+ const endIndex = startIndex + parseInt(limit);
172
+ const paginatedLogs = logs.slice(startIndex, endIndex);
173
+
174
+ res.json({
175
+ success: true,
176
+ data: {
177
+ logs: paginatedLogs,
178
+ pagination: {
179
+ total: logs.length,
180
+ limit: parseInt(limit),
181
+ offset: startIndex,
182
+ hasMore: endIndex < logs.length
183
+ }
184
+ }
185
+ });
186
+ } catch (error) {
187
+ console.error(`[API] Ошибка получения логов бота ${req.params.id}:`, error);
188
+ res.status(500).json({ error: 'Не удалось получить логи бота' });
189
+ }
190
+ });
191
+
192
+ router.use(authenticate);
193
+ router.use('/:botId/event-graphs', eventGraphsRouter);
194
+ router.use('/:botId/plugins/ide', pluginIdeRouter);
195
+
196
+ async function setupDefaultPermissionsForBot(botId, prismaClient = prisma) {
197
+ const initialData = {
198
+ groups: ["User", "Admin"],
199
+ permissions: [
200
+ { name: "admin.*", description: "Все права администратора" },
201
+ { name: "admin.cooldown.bypass", description: "Обход кулдауна для админ-команд" },
202
+ { name: "user.*", description: "Все права обычного пользователя" },
203
+ { name: "user.say", description: "Доступ к простым командам" },
204
+ { name: "user.cooldown.bypass", description: "Обход кулдауна для юзер-команд" },
205
+ ],
206
+ groupPermissions: {
207
+ "User": ["user.say"],
208
+ "Admin": ["admin.*", "admin.cooldown.bypass", "user.cooldown.bypass", "user.*"]
209
+ },
210
+ };
211
+
212
+ for (const perm of initialData.permissions) {
213
+ await prismaClient.permission.upsert({ where: { botId_name: { botId, name: perm.name } }, update: { description: perm.description }, create: { ...perm, botId, owner: 'system' } });
214
+ }
215
+ for (const groupName of initialData.groups) {
216
+ await prismaClient.group.upsert({ where: { botId_name: { botId, name: groupName } }, update: {}, create: { name: groupName, botId, owner: 'system' } });
217
+ }
218
+ for (const [groupName, permNames] of Object.entries(initialData.groupPermissions)) {
219
+ const group = await prismaClient.group.findUnique({ where: { botId_name: { botId, name: groupName } } });
220
+ if (group) {
221
+ for (const permName of permNames) {
222
+ const permission = await prismaClient.permission.findUnique({ where: { botId_name: { botId, name: permName } } });
223
+ if (permission) {
224
+ await prismaClient.groupPermission.upsert({ where: { groupId_permissionId: { groupId: group.id, permissionId: permission.id } }, update: {}, create: { groupId: group.id, permissionId: permission.id } });
225
+ }
226
+ }
227
+ }
228
+ }
229
+ console.log(`[Setup] Для бота ID ${botId} созданы группы и права по умолчанию.`);
230
+ }
231
+
232
+
233
+
234
+ router.post('/', authorize('bot:create'), async (req, res) => {
235
+ try {
236
+ const { username, password, prefix, serverId, note } = req.body;
237
+ if (!username || !serverId) return res.status(400).json({ error: 'Имя и сервер обязательны' });
238
+
239
+ const maxSortOrder = await prisma.bot.aggregate({
240
+ _max: { sortOrder: true }
241
+ });
242
+ const nextSortOrder = (maxSortOrder._max.sortOrder || 0) + 1;
243
+
244
+ const data = {
245
+ username,
246
+ prefix,
247
+ note,
248
+ serverId: parseInt(serverId, 10),
249
+ password: password ? encrypt(password) : null,
250
+ sortOrder: nextSortOrder
251
+ };
252
+
253
+ const newBot = await prisma.bot.create({
254
+ data: data,
255
+ include: { server: true }
256
+ });
257
+ await setupDefaultPermissionsForBot(newBot.id);
258
+ res.status(201).json(newBot);
259
+ } catch (error) {
260
+ if (error.code === 'P2002') return res.status(409).json({ error: 'Бот с таким именем уже существует' });
261
+ console.error("[API Error] /bots POST:", error);
262
+ res.status(500).json({ error: 'Не удалось создать бота' });
263
+ }
264
+ });
265
+
266
+ router.put('/:id', authorize('bot:update'), async (req, res) => {
267
+ try {
268
+ const {
269
+ username, password, prefix, serverId, note, owners,
270
+ proxyHost, proxyPort, proxyUsername, proxyPassword
271
+ } = req.body;
272
+
273
+ let dataToUpdate = {
274
+ username,
275
+ prefix,
276
+ note,
277
+ owners,
278
+ proxyHost,
279
+ proxyPort: proxyPort ? parseInt(proxyPort, 10) : null,
280
+ proxyUsername,
281
+ };
282
+
283
+ if (password) {
284
+ dataToUpdate.password = encrypt(password);
285
+ }
286
+ if (proxyPassword) {
287
+ dataToUpdate.proxyPassword = encrypt(proxyPassword);
288
+ }
289
+
290
+ if (serverId !== undefined && serverId !== '') {
291
+ dataToUpdate.serverId = parseInt(serverId, 10);
292
+ }
293
+
294
+ Object.keys(dataToUpdate).forEach(key => {
295
+ if (dataToUpdate[key] === undefined) {
296
+ delete dataToUpdate[key];
297
+ }
298
+ });
299
+
300
+ if (dataToUpdate.serverId) {
301
+ const serverIdValue = dataToUpdate.serverId;
302
+ delete dataToUpdate.serverId;
303
+ dataToUpdate.server = { connect: { id: serverIdValue } };
304
+ }
305
+
306
+ const botId = parseInt(req.params.id, 10);
307
+ if (isNaN(botId)) {
308
+ return res.status(400).json({ message: 'Неверный ID бота.' });
309
+ }
310
+
311
+ if (dataToUpdate.username) {
312
+ const existingBot = await prisma.bot.findFirst({
313
+ where: {
314
+ username: dataToUpdate.username,
315
+ id: { not: botId }
316
+ }
317
+ });
318
+
319
+ if (existingBot) {
320
+ return res.status(400).json({
321
+ message: `Бот с именем "${dataToUpdate.username}" уже существует.`
322
+ });
323
+ }
324
+ }
325
+
326
+ const updatedBot = await prisma.bot.update({
327
+ where: { id: botId },
328
+ data: dataToUpdate,
329
+ include: { server: true }
330
+ });
331
+
332
+ res.json(updatedBot);
333
+ } catch (error) {
334
+ console.error("[API Error] /bots PUT:", error);
335
+ res.status(500).json({ error: 'Не удалось обновить бота' });
336
+ }
337
+ });
338
+
339
+ router.put('/:id/sort-order', authorize('bot:update'), async (req, res) => {
340
+ try {
341
+ const { newPosition } = req.body;
342
+ const botId = parseInt(req.params.id, 10);
343
+
344
+ console.log(`[API] Запрос на изменение порядка бота ${botId} на позицию ${newPosition}`);
345
+
346
+ if (isNaN(botId) || typeof newPosition !== 'number') {
347
+ console.log(`[API] Неверные параметры: botId=${botId}, newPosition=${newPosition}`);
348
+ return res.status(400).json({ error: 'Неверные параметры' });
349
+ }
350
+
351
+ const currentBot = await prisma.bot.findUnique({
352
+ where: { id: botId },
353
+ select: { sortOrder: true }
354
+ });
355
+
356
+ if (!currentBot) {
357
+ console.log(`[API] Бот ${botId} не найден`);
358
+ return res.status(404).json({ error: 'Бот не найден' });
359
+ }
360
+
361
+ const currentPosition = currentBot.sortOrder;
362
+ console.log(`[API] Текущая позиция бота ${botId}: ${currentPosition}, новая позиция: ${newPosition}`);
363
+
364
+ if (newPosition === currentPosition) {
365
+ console.log(`[API] Позиция не изменилась для бота ${botId}`);
366
+ return res.json({ success: true, message: 'Позиция не изменилась' });
367
+ }
368
+
369
+ if (newPosition > currentPosition) {
370
+ console.log(`[API] Перемещаем бота ${botId} вниз с позиции ${currentPosition} на ${newPosition}`);
371
+ const updateResult = await prisma.bot.updateMany({
372
+ where: {
373
+ sortOrder: {
374
+ gt: currentPosition,
375
+ lte: newPosition
376
+ }
377
+ },
378
+ data: {
379
+ sortOrder: {
380
+ decrement: 1
381
+ }
382
+ }
383
+ });
384
+ console.log(`[API] Обновлено ${updateResult.count} ботов при перемещении вниз`);
385
+ } else {
386
+ console.log(`[API] Перемещаем бота ${botId} вверх с позиции ${currentPosition} на ${newPosition}`);
387
+ const updateResult = await prisma.bot.updateMany({
388
+ where: {
389
+ sortOrder: {
390
+ gte: newPosition,
391
+ lt: currentPosition
392
+ }
393
+ },
394
+ data: {
395
+ sortOrder: {
396
+ increment: 1
397
+ }
398
+ }
399
+ });
400
+ console.log(`[API] Обновлено ${updateResult.count} ботов при перемещении вверх`);
401
+ }
402
+
403
+ await prisma.bot.update({
404
+ where: { id: botId },
405
+ data: { sortOrder: newPosition }
406
+ });
407
+
408
+ console.log(`[API] Успешно обновлен порядок бота ${botId} на позицию ${newPosition}`);
409
+ res.json({ success: true, message: 'Порядок ботов обновлен' });
410
+ } catch (error) {
411
+ console.error("[API Error] /bots sort-order PUT:", error);
412
+ res.status(500).json({ error: 'Не удалось обновить порядок ботов' });
413
+ }
414
+ });
415
+
416
+ router.delete('/:id', authorize('bot:delete'), async (req, res) => {
417
+ try {
418
+ const botId = parseInt(req.params.id, 10);
419
+ if (botManager.bots.has(botId)) return res.status(400).json({ error: 'Нельзя удалить запущенного бота' });
420
+ await prisma.bot.delete({ where: { id: botId } });
421
+ res.status(204).send();
422
+ } catch (error) { res.status(500).json({ error: 'Не удалось удалить бота' }); }
423
+ });
424
+
425
+ router.get('/servers', authorize('bot:list'), async (req, res) => {
426
+ try {
427
+ const servers = await prisma.server.findMany();
428
+ res.json(servers);
429
+ } catch (error) {
430
+ console.error("[API /api/bots] Ошибка получения списка серверов:", error);
431
+ res.status(500).json({ error: 'Не удалось получить список серверов' });
432
+ }
433
+ });
434
+
435
+ router.get('/:botId/plugins', authorize('plugin:list'), async (req, res) => {
436
+ try {
437
+ const botId = parseInt(req.params.botId);
438
+ const plugins = await prisma.installedPlugin.findMany({ where: { botId } });
439
+ res.json(plugins);
440
+ } catch (error) { res.status(500).json({ error: 'Не удалось получить плагины бота' }); }
441
+ });
442
+
443
+ router.post('/:botId/plugins/install/github', authorize('plugin:install'), async (req, res) => {
444
+ const { botId } = req.params;
445
+ const { repoUrl } = req.body;
446
+ try {
447
+ const newPlugin = await pluginManager.installFromGithub(parseInt(botId), repoUrl);
448
+ res.status(201).json(newPlugin);
449
+ } catch (error) {
450
+ res.status(500).json({ message: error.message });
451
+ }
452
+ });
453
+
454
+ router.post('/:botId/plugins/install/local', authorize('plugin:install'), async (req, res) => {
455
+ const { botId } = req.params;
456
+ const { path } = req.body;
457
+ try {
458
+ const newPlugin = await pluginManager.installFromLocalPath(parseInt(botId), path);
459
+ res.status(201).json(newPlugin);
460
+ } catch (error) {
461
+ res.status(500).json({ message: error.message });
462
+ }
463
+ });
464
+
465
+ router.delete('/:botId/plugins/:pluginId', authorize('plugin:delete'), async (req, res) => {
466
+ const { pluginId } = req.params;
467
+ try {
468
+ await pluginManager.deletePlugin(parseInt(pluginId));
469
+ res.status(204).send();
470
+ } catch (error) {
471
+ res.status(500).json({ message: error.message });
472
+ }
473
+ });
474
+
475
+ router.get('/:botId/plugins/:pluginId/settings', authorize('plugin:settings:view'), async (req, res) => {
476
+ try {
477
+ const pluginId = parseInt(req.params.pluginId);
478
+ const plugin = await prisma.installedPlugin.findUnique({ where: { id: pluginId } });
479
+ if (!plugin) return res.status(404).json({ error: 'Установленный плагин не найден' });
480
+
481
+ const savedSettings = plugin.settings ? JSON.parse(plugin.settings) : {};
482
+ const defaultSettings = {};
483
+ const manifest = plugin.manifest ? JSON.parse(plugin.manifest) : {};
484
+ const manifestSettings = manifest.settings || {};
485
+
486
+
487
+ const firstSettingValue = Object.values(manifestSettings)[0];
488
+ const isGrouped = firstSettingValue && typeof firstSettingValue === 'object' && !firstSettingValue.type && firstSettingValue.label;
489
+
490
+ const processSetting = async (settingKey, config) => {
491
+ if (!config || !config.type) return;
492
+
493
+ if (config.type === 'json_file' && config.defaultPath) {
494
+ const configFilePath = path.join(plugin.path, config.defaultPath);
495
+ try {
496
+ const fileContent = await fs.readFile(configFilePath, 'utf-8');
497
+ defaultSettings[settingKey] = JSON.parse(fileContent);
498
+ } catch (e) {
499
+ console.error(`[API Settings] Не удалось прочитать defaultPath ${config.defaultPath} для плагина ${plugin.name}: ${e.message}`);
500
+ defaultSettings[settingKey] = {};
501
+ }
502
+ } else if (config.default !== undefined) {
503
+ try {
504
+ defaultSettings[settingKey] = JSON.parse(config.default);
505
+ } catch {
506
+ defaultSettings[settingKey] = config.default;
507
+ }
508
+ }
509
+ };
510
+
511
+ if (isGrouped) {
512
+ for (const categoryKey in manifestSettings) {
513
+ const categoryConfig = manifestSettings[categoryKey];
514
+ for (const settingKey in categoryConfig) {
515
+ if (settingKey === 'label') continue;
516
+ await processSetting(settingKey, categoryConfig[settingKey]);
517
+ }
518
+ }
519
+ } else {
520
+ for (const settingKey in manifestSettings) {
521
+ await processSetting(settingKey, manifestSettings[settingKey]);
522
+ }
523
+ }
524
+
525
+ const finalSettings = { ...defaultSettings, ...savedSettings };
526
+ res.json(finalSettings);
527
+ } catch (error) {
528
+ console.error("[API Error] /settings GET:", error);
529
+ res.status(500).json({ error: 'Не удалось получить настройки плагина' });
530
+ }
531
+ });
532
+
533
+ router.put('/:botId/plugins/:pluginId', authorize('plugin:settings:edit'), async (req, res) => {
534
+ try {
535
+ const pluginId = parseInt(req.params.pluginId);
536
+ const { isEnabled, settings } = req.body;
537
+ const dataToUpdate = {};
538
+ if (typeof isEnabled === 'boolean') dataToUpdate.isEnabled = isEnabled;
539
+ if (settings) dataToUpdate.settings = JSON.stringify(settings);
540
+ if (Object.keys(dataToUpdate).length === 0) return res.status(400).json({ error: "Нет данных для обновления" });
541
+ const updated = await prisma.installedPlugin.update({ where: { id: pluginId }, data: dataToUpdate });
542
+ res.json(updated);
543
+ } catch (error) { res.status(500).json({ error: 'Не удалось обновить плагин' }); }
544
+ });
545
+
546
+ router.get('/:botId/management-data', authorize('management:view'), async (req, res) => {
547
+ try {
548
+ const botId = parseInt(req.params.botId, 10);
549
+ if (isNaN(botId)) return res.status(400).json({ error: 'Неверный ID бота' });
550
+
551
+ const page = parseInt(req.query.page) || 1;
552
+ const pageSize = parseInt(req.query.pageSize) || 100;
553
+ const searchQuery = req.query.search || '';
554
+
555
+ const userSkip = (page - 1) * pageSize;
556
+
557
+ const whereClause = {
558
+ botId,
559
+ };
560
+
561
+ if (searchQuery) {
562
+ whereClause.username = {
563
+ contains: searchQuery,
564
+ };
565
+ }
566
+
567
+ const [groups, allPermissions] = await Promise.all([
568
+ prisma.group.findMany({ where: { botId }, include: { permissions: { include: { permission: true } } }, orderBy: { name: 'asc' } }),
569
+ prisma.permission.findMany({ where: { botId }, orderBy: { name: 'asc' } })
570
+ ]);
571
+
572
+ const [users, usersCount] = await Promise.all([
573
+ prisma.user.findMany({
574
+ where: whereClause,
575
+ include: { groups: { include: { group: true } } },
576
+ orderBy: { username: 'asc' },
577
+ take: pageSize,
578
+ skip: userSkip,
579
+ }),
580
+ prisma.user.count({ where: whereClause })
581
+ ]);
582
+
583
+ const templatesMap = new Map(commandManager.getCommandTemplates().map(t => [t.name, t]));
584
+ let dbCommandsFromDb = await prisma.command.findMany({
585
+ where: { botId },
586
+ include: {
587
+ pluginOwner: {
588
+ select: {
589
+ id: true,
590
+ name: true,
591
+ version: true,
592
+ sourceType: true
593
+ }
594
+ }
595
+ },
596
+ orderBy: [{ owner: 'asc' }, { name: 'asc' }]
597
+ });
598
+
599
+ const commandsToCreate = [];
600
+ for (const template of templatesMap.values()) {
601
+ if (!dbCommandsFromDb.some(cmd => cmd.name === template.name)) {
602
+ let permissionId = null;
603
+ if (template.permissions) {
604
+ const permission = await prisma.permission.upsert({
605
+ where: { botId_name: { botId, name: template.permissions } },
606
+ update: { description: `Авто-создано для команды ${template.name}` },
607
+ create: {
608
+ botId,
609
+ name: template.permissions,
610
+ description: `Авто-создано для команды ${template.name}`,
611
+ owner: template.owner || 'system',
612
+ }
613
+ });
614
+ permissionId = permission.id;
615
+ }
616
+
617
+ commandsToCreate.push({
618
+ botId,
619
+ name: template.name,
620
+ isEnabled: template.isActive,
621
+ cooldown: template.cooldown,
622
+ aliases: JSON.stringify(template.aliases),
623
+ description: template.description,
624
+ owner: template.owner,
625
+ permissionId: permissionId,
626
+ allowedChatTypes: JSON.stringify(template.allowedChatTypes),
627
+ });
628
+ }
629
+ }
630
+
631
+ if (commandsToCreate.length > 0) {
632
+ await prisma.command.createMany({ data: commandsToCreate });
633
+ dbCommandsFromDb = await prisma.command.findMany({
634
+ where: { botId },
635
+ include: {
636
+ pluginOwner: {
637
+ select: {
638
+ id: true,
639
+ name: true,
640
+ version: true,
641
+ sourceType: true
642
+ }
643
+ }
644
+ },
645
+ orderBy: [{ owner: 'asc' }, { name: 'asc' }]
646
+ });
647
+ }
648
+
649
+ const finalCommands = dbCommandsFromDb.map(cmd => {
650
+ const template = templatesMap.get(cmd.name);
651
+ let args = [];
652
+
653
+ if (cmd.isVisual) {
654
+ try {
655
+ args = JSON.parse(cmd.argumentsJson || '[]');
656
+ } catch (e) {
657
+ console.error(`Error parsing argumentsJson for visual command ${cmd.name} (ID: ${cmd.id}):`, e);
658
+ args = [];
659
+ }
660
+ } else {
661
+ if (template && template.args && template.args.length > 0) {
662
+ args = template.args;
663
+ } else {
664
+ try {
665
+ args = JSON.parse(cmd.argumentsJson || '[]');
666
+ } catch (e) {
667
+ args = [];
668
+ }
669
+ }
670
+ }
671
+
672
+ return {
673
+ ...cmd,
674
+ args: args,
675
+ aliases: JSON.parse(cmd.aliases || '[]'),
676
+ allowedChatTypes: JSON.parse(cmd.allowedChatTypes || '[]'),
677
+ };
678
+ })
679
+
680
+ res.json({
681
+ groups,
682
+ permissions: allPermissions,
683
+ users: {
684
+ items: users,
685
+ total: usersCount,
686
+ page,
687
+ pageSize,
688
+ totalPages: Math.ceil(usersCount / pageSize),
689
+ },
690
+ commands: finalCommands
691
+ });
692
+
693
+ } catch (error) {
694
+ console.error(`[API Error] /management-data for bot ${req.params.botId}:`, error);
695
+ res.status(500).json({ error: 'Не удалось загрузить данные управления' });
696
+ }
697
+ });
698
+
699
+ router.put('/:botId/commands/:commandId', authorize('management:edit'), async (req, res) => {
700
+ try {
701
+ const commandId = parseInt(req.params.commandId, 10);
702
+ const { name, description, cooldown, aliases, permissionId, allowedChatTypes, isEnabled, argumentsJson, graphJson, pluginOwnerId } = req.body;
703
+
704
+ const dataToUpdate = {};
705
+ if (name !== undefined) dataToUpdate.name = name;
706
+ if (description !== undefined) dataToUpdate.description = description;
707
+ if (cooldown !== undefined) dataToUpdate.cooldown = parseInt(cooldown, 10);
708
+ if (aliases !== undefined) dataToUpdate.aliases = Array.isArray(aliases) ? JSON.stringify(aliases) : aliases;
709
+ if (permissionId !== undefined) dataToUpdate.permissionId = permissionId ? parseInt(permissionId, 10) : null;
710
+ if (allowedChatTypes !== undefined) dataToUpdate.allowedChatTypes = Array.isArray(allowedChatTypes) ? JSON.stringify(allowedChatTypes) : allowedChatTypes;
711
+ if (isEnabled !== undefined) dataToUpdate.isEnabled = isEnabled;
712
+ if (argumentsJson !== undefined) dataToUpdate.argumentsJson = Array.isArray(argumentsJson) ? JSON.stringify(argumentsJson) : argumentsJson;
713
+ if (graphJson !== undefined) dataToUpdate.graphJson = graphJson;
714
+ if (pluginOwnerId !== undefined) dataToUpdate.pluginOwnerId = pluginOwnerId;
715
+
716
+ const updatedCommand = await prisma.command.update({
717
+ where: { id: commandId },
718
+ data: dataToUpdate,
719
+ });
720
+
721
+ if (graphJson && updatedCommand.pluginOwnerId) {
722
+ try {
723
+ const plugin = await prisma.installedPlugin.findUnique({
724
+ where: { id: updatedCommand.pluginOwnerId }
725
+ });
726
+
727
+ if (plugin) {
728
+ const graphDir = path.join(plugin.path, 'graph');
729
+ await fse.mkdir(graphDir, { recursive: true });
730
+
731
+ const graphFile = path.join(graphDir, `${updatedCommand.name}.json`);
732
+ await fse.writeJson(graphFile, JSON.parse(graphJson), { spaces: 2 });
733
+ console.log(`[API] Граф команды ${updatedCommand.name} сохранен в ${graphFile}`);
734
+ }
735
+ } catch (error) {
736
+ console.error(`[API] Ошибка сохранения графа в папку плагина:`, error);
737
+ }
738
+ }
739
+
740
+ res.json(updatedCommand);
741
+ } catch (error) {
742
+ console.error(`[API Error] /commands/:commandId PUT:`, error);
743
+ res.status(500).json({ error: 'Failed to update command' });
744
+ }
745
+ });
746
+
747
+ router.post('/:botId/groups', authorize('management:edit'), async (req, res) => {
748
+ try {
749
+ const botId = parseInt(req.params.botId);
750
+ const { name, permissionIds } = req.body;
751
+ if (!name) return res.status(400).json({ error: "Имя группы обязательно" });
752
+
753
+ const newGroup = await prisma.group.create({
754
+ data: {
755
+ name,
756
+ botId,
757
+ owner: 'admin',
758
+ permissions: { create: (permissionIds || []).map(id => ({ permissionId: id })) }
759
+ }
760
+ });
761
+
762
+ botManager.reloadBotConfigInRealTime(botId);
763
+
764
+ res.status(201).json(newGroup);
765
+ } catch (error) {
766
+ if (error.code === 'P2002') return res.status(409).json({ error: 'Группа с таким именем уже существует для этого бота.' });
767
+ res.status(500).json({ error: 'Не удалось создать группу.' });
768
+ }
769
+ });
770
+
771
+ router.put('/:botId/groups/:groupId', authorize('management:edit'), async (req, res) => {
772
+ try {
773
+ const botId = parseInt(req.params.botId, 10);
774
+ const groupId = parseInt(req.params.groupId);
775
+ const { name, permissionIds } = req.body;
776
+ if (!name) return res.status(400).json({ error: "Имя группы обязательно" });
777
+
778
+ const usersInGroup = await prisma.user.findMany({
779
+ where: { botId, groups: { some: { groupId } } },
780
+ select: { username: true }
781
+ });
782
+
783
+ await prisma.$transaction(async (tx) => {
784
+ await tx.group.update({ where: { id: groupId }, data: { name } });
785
+ await tx.groupPermission.deleteMany({ where: { groupId } });
786
+ if (permissionIds && permissionIds.length > 0) {
787
+ await tx.groupPermission.createMany({
788
+ data: permissionIds.map(pid => ({ groupId, permissionId: pid })),
789
+ });
790
+ }
791
+ });
792
+
793
+ for (const user of usersInGroup) {
794
+ botManager.invalidateUserCache(botId, user.username);
795
+ }
796
+
797
+ botManager.reloadBotConfigInRealTime(botId);
798
+
799
+ res.status(200).send();
800
+ } catch (error) {
801
+ if (error.code === 'P2002') return res.status(409).json({ error: 'Группа с таким именем уже существует для этого бота.' });
802
+ res.status(500).json({ error: 'Не удалось обновить группу.' });
803
+ }
804
+ });
805
+
806
+ router.delete('/:botId/groups/:groupId', authorize('management:edit'), async (req, res) => {
807
+ try {
808
+ const botId = parseInt(req.params.botId, 10);
809
+ const groupId = parseInt(req.params.groupId);
810
+ const group = await prisma.group.findUnique({ where: { id: groupId } });
811
+ if (group && group.owner !== 'admin') {
812
+ return res.status(403).json({ error: `Нельзя удалить группу с источником "${group.owner}".` });
813
+ }
814
+ await prisma.group.delete({ where: { id: groupId } });
815
+ botManager.reloadBotConfigInRealTime(botId);
816
+
817
+ res.status(204).send();
818
+ } catch (error) { res.status(500).json({ error: 'Не удалось удалить группу.' }); }
819
+ });
820
+
821
+ router.post('/:botId/permissions', authorize('management:edit'), async (req, res) => {
822
+ try {
823
+ const botId = parseInt(req.params.botId);
824
+ const { name, description } = req.body;
825
+ if (!name) return res.status(400).json({ error: 'Имя права обязательно' });
826
+ const newPermission = await prisma.permission.create({
827
+ data: { name, description, botId, owner: 'admin' }
828
+ });
829
+
830
+ botManager.reloadBotConfigInRealTime(botId);
831
+
832
+ res.status(201).json(newPermission);
833
+ } catch (error) {
834
+ if (error.code === 'P2002') return res.status(409).json({ error: 'Право с таким именем уже существует для этого бота.' });
835
+ res.status(500).json({ error: 'Не удалось создать право.' });
836
+ }
837
+ });
838
+
839
+ router.put('/:botId/users/:userId', authorize('management:edit'), async (req, res) => {
840
+ try {
841
+ const botId = parseInt(req.params.botId, 10);
842
+ const userId = parseInt(req.params.userId, 10);
843
+ const { isBlacklisted, groupIds } = req.body;
844
+
845
+ const updateData = {};
846
+ if (typeof isBlacklisted === 'boolean') {
847
+ updateData.isBlacklisted = isBlacklisted;
848
+ }
849
+
850
+ if (Array.isArray(groupIds)) {
851
+ await prisma.userGroup.deleteMany({ where: { userId } });
852
+ updateData.groups = {
853
+ create: groupIds.map(gid => ({ groupId: gid })),
854
+ };
855
+ }
856
+
857
+ const updatedUser = await prisma.user.update({
858
+ where: { id: userId },
859
+ data: updateData,
860
+ include: { groups: true }
861
+ });
862
+
863
+ botManager.invalidateUserCache(botId, updatedUser.username);
864
+
865
+ UserService.clearCache(updatedUser.username, botId);
866
+
867
+ res.json(updatedUser);
868
+
869
+ } catch (error) {
870
+ console.error(`[API Error] /users/:userId PUT:`, error);
871
+ res.status(500).json({ error: 'Не удалось обновить пользователя' });
872
+ }
873
+ });
874
+
875
+ router.post('/start-all', authorize('bot:start_stop'), async (req, res) => {
876
+ try {
877
+ console.log('[API] Получен запрос на запуск всех ботов.');
878
+ const allBots = await prisma.bot.findMany({ include: { server: true } });
879
+ let startedCount = 0;
880
+ for (const botConfig of allBots) {
881
+ if (!botManager.bots.has(botConfig.id)) {
882
+ await botManager.startBot(botConfig);
883
+ startedCount++;
884
+ }
885
+ }
886
+ res.json({ success: true, message: `Запущено ${startedCount} ботов.` });
887
+ } catch (error) {
888
+ console.error('[API Error] /start-all:', error);
889
+ res.status(500).json({ error: 'Произошла ошибка при массовом запуске ботов.' });
890
+ }
891
+ });
892
+
893
+ router.post('/stop-all', authorize('bot:start_stop'), (req, res) => {
894
+ try {
895
+ console.log('[API] Получен запрос на остановку всех ботов.');
896
+ const botIds = Array.from(botManager.bots.keys());
897
+ let stoppedCount = 0;
898
+ for (const botId of botIds) {
899
+ botManager.stopBot(botId);
900
+ stoppedCount++;
901
+ }
902
+ res.json({ success: true, message: `Остановлено ${stoppedCount} ботов.` });
903
+ } catch (error) {
904
+ console.error('[API Error] /stop-all:', error);
905
+ res.status(500).json({ error: 'Произошла ошибка при массовой остановке ботов.' });
906
+ }
907
+ });
908
+
909
+ router.get('/:id/settings/all', authorize('bot:update'), async (req, res) => {
910
+ try {
911
+ const botId = parseInt(req.params.id, 10);
912
+
913
+ const bot = await prisma.bot.findUnique({
914
+ where: { id: botId },
915
+ include: {
916
+ server: true,
917
+ installedPlugins: {
918
+ orderBy: { name: 'asc' }
919
+ }
920
+ }
921
+ });
922
+
923
+ if (!bot) {
924
+ return res.status(404).json({ error: 'Бот не найден' });
925
+ }
926
+
927
+ const allSettings = {
928
+ bot: {
929
+ id: bot.id,
930
+ username: bot.username,
931
+ prefix: bot.prefix,
932
+ note: bot.note,
933
+ owners: bot.owners,
934
+ serverId: bot.serverId,
935
+ proxyHost: bot.proxyHost,
936
+ proxyPort: bot.proxyPort,
937
+ proxyUsername: bot.proxyUsername,
938
+ },
939
+ plugins: []
940
+ };
941
+
942
+ const pluginSettingsPromises = bot.installedPlugins.map(async (plugin) => {
943
+ const manifest = plugin.manifest ? JSON.parse(plugin.manifest) : {};
944
+
945
+ if (!manifest.settings || Object.keys(manifest.settings).length === 0) {
946
+ return null;
947
+ }
948
+
949
+ const savedSettings = plugin.settings ? JSON.parse(plugin.settings) : {};
950
+ let defaultSettings = {};
951
+
952
+ for (const key in manifest.settings) {
953
+ const config = manifest.settings[key];
954
+ if (config.type === 'json_file' && config.defaultPath) {
955
+ const configFilePath = path.join(plugin.path, config.defaultPath);
956
+ try {
957
+ const fileContent = await fs.readFile(configFilePath, 'utf-8');
958
+ defaultSettings[key] = JSON.parse(fileContent);
959
+ } catch (e) { defaultSettings[key] = {}; }
960
+ } else {
961
+ try { defaultSettings[key] = JSON.parse(config.default || 'null'); }
962
+ catch { defaultSettings[key] = config.default; }
963
+ }
964
+ }
965
+
966
+ return {
967
+ id: plugin.id,
968
+ name: plugin.name,
969
+ description: plugin.description,
970
+ isEnabled: plugin.isEnabled,
971
+ manifest: manifest,
972
+ settings: { ...defaultSettings, ...savedSettings }
973
+ };
974
+ });
975
+
976
+ allSettings.plugins = (await Promise.all(pluginSettingsPromises)).filter(Boolean);
977
+
978
+ res.json(allSettings);
979
+
980
+ } catch (error) {
981
+ console.error("[API Error] /settings/all GET:", error);
982
+ res.status(500).json({ error: 'Не удалось загрузить все настройки' });
983
+ }
984
+ });
985
+
986
+ const nodeRegistry = require('../../core/NodeRegistry');
987
+
988
+ router.get('/:botId/visual-editor/nodes', authorize('management:view'), (req, res) => {
989
+ try {
990
+ const { graphType } = req.query;
991
+ const nodesByCategory = nodeRegistry.getNodesByCategory(graphType);
992
+ res.json(nodesByCategory);
993
+ } catch (error) {
994
+ console.error('[API Error] /visual-editor/nodes GET:', error);
995
+ res.status(500).json({ error: 'Failed to get available nodes' });
996
+ }
997
+ });
998
+
999
+ router.get('/:botId/visual-editor/node-config', authorize('management:view'), (req, res) => {
1000
+ try {
1001
+ const { types } = req.query;
1002
+ if (!types) {
1003
+ return res.status(400).json({ error: 'Node types must be provided' });
1004
+ }
1005
+ const typeArray = Array.isArray(types) ? types : [types];
1006
+ const config = nodeRegistry.getNodesByTypes(typeArray);
1007
+ res.json(config);
1008
+ } catch (error) {
1009
+ console.error('[API Error] /visual-editor/node-config GET:', error);
1010
+ res.status(500).json({ error: 'Failed to get node configuration' });
1011
+ }
1012
+ });
1013
+
1014
+ router.get('/:botId/visual-editor/permissions', authorize('management:view'), async (req, res) => {
1015
+ try {
1016
+ const botId = parseInt(req.params.botId, 10);
1017
+ const permissions = await prisma.permission.findMany({
1018
+ where: { botId },
1019
+ orderBy: { name: 'asc' }
1020
+ });
1021
+ res.json(permissions);
1022
+ } catch (error) {
1023
+ console.error('[API Error] /visual-editor/permissions GET:', error);
1024
+ res.status(500).json({ error: 'Failed to get permissions' });
1025
+ }
1026
+ });
1027
+
1028
+ router.post('/:botId/commands/visual', authorize('management:edit'), async (req, res) => {
1029
+ try {
1030
+ const botId = parseInt(req.params.botId, 10);
1031
+ const {
1032
+ name,
1033
+ description,
1034
+ aliases = [],
1035
+ permissionId,
1036
+ cooldown = 0,
1037
+ allowedChatTypes = ['chat', 'private'],
1038
+ argumentsJson = '[]',
1039
+ graphJson = 'null'
1040
+ } = req.body;
1041
+
1042
+ if (!name) {
1043
+ return res.status(400).json({ error: 'Command name is required' });
1044
+ }
1045
+
1046
+ const newCommand = await prisma.command.create({
1047
+ data: {
1048
+ botId,
1049
+ name,
1050
+ description,
1051
+ aliases: JSON.stringify(aliases),
1052
+ permissionId: permissionId || null,
1053
+ cooldown,
1054
+ allowedChatTypes: JSON.stringify(allowedChatTypes),
1055
+ isVisual: true,
1056
+ argumentsJson,
1057
+ graphJson,
1058
+ pluginOwnerId: null
1059
+ }
1060
+ });
1061
+
1062
+ botManager.reloadBotConfigInRealTime(botId);
1063
+ res.status(201).json(newCommand);
1064
+ } catch (error) {
1065
+ if (error.code === 'P2002') {
1066
+ return res.status(409).json({ error: 'Command with this name already exists' });
1067
+ }
1068
+ console.error('[API Error] /commands/visual POST:', error);
1069
+ res.status(500).json({ error: 'Failed to create visual command' });
1070
+ }
1071
+ });
1072
+
1073
+ router.put('/:botId/commands/:commandId/visual', authorize('management:edit'), async (req, res) => {
1074
+ try {
1075
+ const botId = parseInt(req.params.botId, 10);
1076
+ const commandId = parseInt(req.params.commandId, 10);
1077
+ const {
1078
+ name,
1079
+ description,
1080
+ aliases,
1081
+ permissionId,
1082
+ cooldown,
1083
+ allowedChatTypes,
1084
+ argumentsJson,
1085
+ graphJson
1086
+ } = req.body;
1087
+
1088
+ const dataToUpdate = { isVisual: true };
1089
+
1090
+ if (name) dataToUpdate.name = name;
1091
+ if (description !== undefined) dataToUpdate.description = description;
1092
+ if (Array.isArray(aliases)) dataToUpdate.aliases = JSON.stringify(aliases);
1093
+ if (permissionId !== undefined) dataToUpdate.permissionId = permissionId || null;
1094
+ if (typeof cooldown === 'number') dataToUpdate.cooldown = cooldown;
1095
+ if (Array.isArray(allowedChatTypes)) dataToUpdate.allowedChatTypes = JSON.stringify(allowedChatTypes);
1096
+ if (argumentsJson !== undefined) dataToUpdate.argumentsJson = argumentsJson;
1097
+ if (graphJson !== undefined) dataToUpdate.graphJson = graphJson;
1098
+
1099
+ const updatedCommand = await prisma.command.update({
1100
+ where: { id: commandId, botId },
1101
+ data: dataToUpdate
1102
+ });
1103
+
1104
+ if (graphJson && updatedCommand.pluginOwnerId) {
1105
+ try {
1106
+ const plugin = await prisma.installedPlugin.findUnique({
1107
+ where: { id: updatedCommand.pluginOwnerId }
1108
+ });
1109
+
1110
+ if (plugin) {
1111
+ const graphDir = path.join(plugin.path, 'graph');
1112
+ await fse.mkdir(graphDir, { recursive: true });
1113
+
1114
+ const graphFile = path.join(graphDir, `${updatedCommand.name}.json`);
1115
+ await fse.writeJson(graphFile, JSON.parse(graphJson), { spaces: 2 });
1116
+ console.log(`[API] Граф команды ${updatedCommand.name} сохранен в ${graphFile}`);
1117
+ }
1118
+ } catch (error) {
1119
+ console.error(`[API] Ошибка сохранения графа в папку плагина:`, error);
1120
+ }
1121
+ }
1122
+
1123
+ botManager.reloadBotConfigInRealTime(botId);
1124
+ res.json(updatedCommand);
1125
+ } catch (error) {
1126
+ if (error.code === 'P2002') {
1127
+ return res.status(409).json({ error: 'Command with this name already exists' });
1128
+ }
1129
+ console.error('[API Error] /commands/:commandId/visual PUT:', error);
1130
+ res.status(500).json({ error: 'Failed to update visual command' });
1131
+ }
1132
+ });
1133
+
1134
+ router.get('/:botId/commands/:commandId/export', authorize('management:view'), async (req, res) => {
1135
+ try {
1136
+ const botId = parseInt(req.params.botId, 10);
1137
+ const commandId = parseInt(req.params.commandId, 10);
1138
+
1139
+ const command = await prisma.command.findUnique({
1140
+ where: { id: commandId, botId: botId },
1141
+ });
1142
+
1143
+ if (!command) {
1144
+ return res.status(404).json({ error: 'Command not found' });
1145
+ }
1146
+
1147
+ const exportData = {
1148
+ version: '1.0',
1149
+ type: 'command',
1150
+ ...command
1151
+ };
1152
+
1153
+ delete exportData.id;
1154
+ delete exportData.botId;
1155
+
1156
+ res.json(exportData);
1157
+ } catch (error) {
1158
+ console.error('Failed to export command:', error);
1159
+ res.status(500).json({ error: 'Failed to export command' });
1160
+ }
1161
+ });
1162
+
1163
+ router.post('/:botId/commands/import', authorize('management:edit'), async (req, res) => {
1164
+ try {
1165
+ const botId = parseInt(req.params.botId, 10);
1166
+ const importData = req.body;
1167
+
1168
+ if (importData.type !== 'command') {
1169
+ return res.status(400).json({ error: 'Invalid file type. Expected "command".' });
1170
+ }
1171
+
1172
+ let commandName = importData.name;
1173
+ let counter = 1;
1174
+
1175
+ while (await prisma.command.findFirst({ where: { botId, name: commandName } })) {
1176
+ commandName = `${importData.name}_imported_${counter}`;
1177
+ counter++;
1178
+ }
1179
+
1180
+ let finalGraphJson = importData.graphJson;
1181
+
1182
+ if (finalGraphJson && finalGraphJson !== 'null') {
1183
+ const graph = JSON.parse(finalGraphJson);
1184
+ const nodeIdMap = new Map();
1185
+
1186
+ if (graph.nodes) {
1187
+ graph.nodes.forEach(node => {
1188
+ const oldId = node.id;
1189
+ const newId = `${node.type}-${randomUUID()}`;
1190
+ nodeIdMap.set(oldId, newId);
1191
+ node.id = newId;
1192
+ });
1193
+ }
1194
+
1195
+ if (graph.connections) {
1196
+ graph.connections.forEach(conn => {
1197
+ conn.id = `edge-${randomUUID()}`;
1198
+ conn.sourceNodeId = nodeIdMap.get(conn.sourceNodeId) || conn.sourceNodeId;
1199
+ conn.targetNodeId = nodeIdMap.get(conn.targetNodeId) || conn.targetNodeId;
1200
+ });
1201
+ }
1202
+
1203
+ finalGraphJson = JSON.stringify(graph);
1204
+ }
1205
+
1206
+ const newCommand = await prisma.command.create({
1207
+ data: {
1208
+ botId: botId,
1209
+ name: commandName,
1210
+ description: importData.description,
1211
+ aliases: importData.aliases,
1212
+ permissionId: null,
1213
+ cooldown: importData.cooldown,
1214
+ allowedChatTypes: importData.allowedChatTypes,
1215
+ isVisual: importData.isVisual,
1216
+ isEnabled: importData.isEnabled,
1217
+ argumentsJson: importData.argumentsJson,
1218
+ graphJson: finalGraphJson,
1219
+ owner: 'visual_editor',
1220
+ }
1221
+ });
1222
+
1223
+ botManager.reloadBotConfigInRealTime(botId);
1224
+ res.status(201).json(newCommand);
1225
+ } catch (error) {
1226
+ console.error("Failed to import command:", error);
1227
+ res.status(500).json({ error: 'Failed to import command' });
1228
+ }
1229
+ });
1230
+
1231
+ router.post('/:botId/commands', authorize('management:edit'), async (req, res) => {
1232
+ try {
1233
+ const botId = parseInt(req.params.botId, 10);
1234
+ const {
1235
+ name,
1236
+ description,
1237
+ aliases = [],
1238
+ permissionId,
1239
+ cooldown = 0,
1240
+ allowedChatTypes = ['chat', 'private'],
1241
+ isVisual = false,
1242
+ argumentsJson = '[]',
1243
+ graphJson = 'null'
1244
+ } = req.body;
1245
+
1246
+ if (!name) {
1247
+ return res.status(400).json({ error: 'Command name is required' });
1248
+ }
1249
+
1250
+ const newCommand = await prisma.command.create({
1251
+ data: {
1252
+ botId,
1253
+ name,
1254
+ description,
1255
+ aliases: JSON.stringify(aliases),
1256
+ permissionId: permissionId || null,
1257
+ cooldown,
1258
+ allowedChatTypes: JSON.stringify(allowedChatTypes),
1259
+ isVisual,
1260
+ argumentsJson,
1261
+ graphJson,
1262
+ owner: isVisual ? 'visual_editor' : 'manual',
1263
+ pluginOwnerId: null
1264
+ }
1265
+ });
1266
+
1267
+ if (graphJson && graphJson !== 'null' && req.body.pluginOwnerId) {
1268
+ try {
1269
+ const plugin = await prisma.installedPlugin.findUnique({
1270
+ where: { id: req.body.pluginOwnerId }
1271
+ });
1272
+
1273
+ if (plugin) {
1274
+ const graphDir = path.join(plugin.path, 'graph');
1275
+ await fse.mkdir(graphDir, { recursive: true });
1276
+
1277
+ const graphFile = path.join(graphDir, `${name}.json`);
1278
+ await fse.writeJson(graphFile, JSON.parse(graphJson), { spaces: 2 });
1279
+ console.log(`[API] Граф команды ${name} сохранен в ${graphFile}`);
1280
+ }
1281
+ } catch (error) {
1282
+ console.error(`[API] Ошибка сохранения графа в папку плагина:`, error);
1283
+ }
1284
+ }
1285
+
1286
+ botManager.reloadBotConfigInRealTime(botId);
1287
+ res.status(201).json(newCommand);
1288
+ } catch (error) {
1289
+ if (error.code === 'P2002') {
1290
+ return res.status(409).json({ error: 'Command with this name already exists' });
1291
+ }
1292
+ console.error('[API Error] /commands POST:', error);
1293
+ res.status(500).json({ error: 'Failed to create command' });
1294
+ }
1295
+ });
1296
+
1297
+ router.delete('/:botId/commands/:commandId', authorize('management:edit'), async (req, res) => {
1298
+ try {
1299
+ const botId = parseInt(req.params.botId, 10);
1300
+ const commandId = parseInt(req.params.commandId, 10);
1301
+
1302
+ await prisma.command.delete({
1303
+ where: { id: commandId, botId: botId },
1304
+ });
1305
+
1306
+ botManager.reloadBotConfigInRealTime(botId);
1307
+ res.status(204).send();
1308
+ } catch (error) {
1309
+ console.error(`[API Error] /commands/:commandId DELETE:`, error);
1310
+ res.status(500).json({ error: 'Failed to delete command' });
1311
+ }
1312
+ });
1313
+
1314
+ router.get('/:botId/event-graphs/:graphId', authorize('management:view'), async (req, res) => {
1315
+ try {
1316
+ const botId = parseInt(req.params.botId, 10);
1317
+ const graphId = parseInt(req.params.graphId, 10);
1318
+
1319
+ const eventGraph = await prisma.eventGraph.findUnique({
1320
+ where: { id: graphId, botId },
1321
+ include: { triggers: true },
1322
+ });
1323
+
1324
+ if (!eventGraph) {
1325
+ return res.status(404).json({ error: 'Граф события не найден' });
1326
+ }
1327
+
1328
+ res.json(eventGraph);
1329
+ } catch (error) {
1330
+ console.error(`[API Error] /event-graphs/:graphId GET:`, error);
1331
+ res.status(500).json({ error: 'Не удалось получить граф события' });
1332
+ }
1333
+ });
1334
+
1335
+ router.post('/:botId/event-graphs', authorize('management:edit'), async (req, res) => {
1336
+ try {
1337
+ const botId = parseInt(req.params.botId, 10);
1338
+ const { name, description, graphJson, variables, eventType, isEnabled = true } = req.body;
1339
+
1340
+ if (!name || typeof name !== 'string' || name.trim() === '') {
1341
+ return res.status(400).json({ error: 'Имя графа обязательно и должно быть непустой строкой' });
1342
+ }
1343
+
1344
+ let graphJsonString;
1345
+ if (graphJson) {
1346
+ if (typeof graphJson === 'string') {
1347
+ graphJsonString = graphJson;
1348
+ } else {
1349
+ graphJsonString = JSON.stringify(graphJson);
1350
+ }
1351
+ } else {
1352
+ graphJsonString = JSON.stringify({
1353
+ nodes: [],
1354
+ connections: []
1355
+ });
1356
+ }
1357
+
1358
+ console.log('[API] Final graphJsonString:', graphJsonString);
1359
+
1360
+ let eventTypes = [];
1361
+ try {
1362
+ const parsedGraph = JSON.parse(graphJsonString);
1363
+ if (parsedGraph.nodes && Array.isArray(parsedGraph.nodes)) {
1364
+ const eventNodes = parsedGraph.nodes.filter(node => node.type && node.type.startsWith('event:'));
1365
+ eventTypes = [...new Set(eventNodes.map(node => node.type.split(':')[1]))];
1366
+ }
1367
+ } catch (error) {
1368
+ console.warn('[API] Не удалось извлечь типы событий из графа:', error.message);
1369
+ }
1370
+
1371
+ const newEventGraph = await prisma.eventGraph.create({
1372
+ data: {
1373
+ botId,
1374
+ name: name.trim(),
1375
+ description: description || '',
1376
+ isEnabled: isEnabled,
1377
+ graphJson: graphJsonString,
1378
+ variables: variables || '[]',
1379
+ eventType: eventType || 'custom',
1380
+ triggers: {
1381
+ create: eventTypes.map(eventType => ({ eventType }))
1382
+ }
1383
+ },
1384
+ include: { triggers: true }
1385
+ });
1386
+
1387
+ console.log('[API] Created event graph:', newEventGraph);
1388
+ res.status(201).json(newEventGraph);
1389
+ } catch (error) {
1390
+ if (error.code === 'P2002') {
1391
+ return res.status(409).json({ error: 'Граф событий с таким именем уже существует' });
1392
+ }
1393
+ console.error(`[API Error] /event-graphs POST:`, error);
1394
+ res.status(500).json({ error: 'Не удалось создать граф событий' });
1395
+ }
1396
+ });
1397
+
1398
+ router.delete('/:botId/event-graphs/:graphId', authorize('management:edit'), async (req, res) => {
1399
+ try {
1400
+ const botId = parseInt(req.params.botId, 10);
1401
+ const graphId = parseInt(req.params.graphId, 10);
1402
+
1403
+ await prisma.eventGraph.delete({
1404
+ where: { id: graphId, botId: botId },
1405
+ });
1406
+
1407
+ res.status(204).send();
1408
+ } catch (error) {
1409
+ console.error(`[API Error] /event-graphs/:graphId DELETE:`, error);
1410
+ res.status(500).json({ error: 'Не удалось удалить граф событий' });
1411
+ }
1412
+ });
1413
+
1414
+ router.put('/:botId/event-graphs/:graphId', authorize('management:edit'), async (req, res) => {
1415
+ const { botId, graphId } = req.params;
1416
+ const { name, isEnabled, graphJson, variables, pluginOwnerId } = req.body;
1417
+
1418
+ if (!name || typeof name !== 'string' || name.trim() === '') {
1419
+ return res.status(400).json({ error: 'Поле name обязательно и должно быть непустой строкой.' });
1420
+ }
1421
+
1422
+ if (typeof isEnabled !== 'boolean') {
1423
+ return res.status(400).json({ error: 'Поле isEnabled должно быть true или false.' });
1424
+ }
1425
+
1426
+ try {
1427
+ const dataToUpdate = {
1428
+ name: name.trim(),
1429
+ isEnabled,
1430
+ };
1431
+
1432
+ if (graphJson !== undefined) {
1433
+ dataToUpdate.graphJson = graphJson;
1434
+ }
1435
+
1436
+ if (variables !== undefined) {
1437
+ dataToUpdate.variables = Array.isArray(variables) ? JSON.stringify(variables) : variables;
1438
+ }
1439
+
1440
+ if (pluginOwnerId !== undefined) {
1441
+ dataToUpdate.pluginOwnerId = pluginOwnerId;
1442
+ }
1443
+
1444
+ const updatedGraph = await prisma.eventGraph.update({
1445
+ where: { id: parseInt(graphId), botId: parseInt(botId) },
1446
+ data: dataToUpdate
1447
+ });
1448
+
1449
+ res.json(updatedGraph);
1450
+ } catch (error) {
1451
+ console.error(`[API Error] /event-graphs/:graphId PUT:`, error);
1452
+ res.status(500).json({ error: 'Ошибка при обновлении графа событий.' });
1453
+ }
1454
+ });
1455
+
1456
+ router.post('/:botId/visual-editor/save', authorize('management:edit'), async (req, res) => {
1457
+ });
1458
+
1459
+ router.get('/:botId/ui-extensions', authorize('plugin:list'), async (req, res) => {
1460
+ try {
1461
+ const botId = parseInt(req.params.botId, 10);
1462
+ const enabledPlugins = await prisma.installedPlugin.findMany({
1463
+ where: { botId: botId, isEnabled: true }
1464
+ });
1465
+
1466
+ const extensions = [];
1467
+ for (const plugin of enabledPlugins) {
1468
+ if (plugin.manifest) {
1469
+ try {
1470
+ const manifest = JSON.parse(plugin.manifest);
1471
+ if (manifest.uiExtensions && Array.isArray(manifest.uiExtensions)) {
1472
+ manifest.uiExtensions.forEach(ext => {
1473
+ extensions.push({
1474
+ pluginName: plugin.name,
1475
+ ...ext
1476
+ });
1477
+ });
1478
+ }
1479
+ } catch (e) {
1480
+ console.error(`Ошибка парсинга манифеста для плагина ${plugin.name}:`, e);
1481
+ }
1482
+ }
1483
+ }
1484
+ res.json(extensions);
1485
+ } catch (error) {
1486
+ res.status(500).json({ error: 'Не удалось получить расширения интерфейса' });
1487
+ }
1488
+ });
1489
+
1490
+ router.get('/:botId/plugins/:pluginName/ui-content/:path', authorize('plugin:list'), async (req, res) => {
1491
+ const { botId, pluginName, path: uiPath } = req.params;
1492
+ const numericBotId = parseInt(botId, 10);
1493
+
1494
+ try {
1495
+ const plugin = await prisma.installedPlugin.findFirst({
1496
+ where: { botId: numericBotId, name: pluginName, isEnabled: true }
1497
+ });
1498
+
1499
+ if (!plugin) {
1500
+ return res.status(404).json({ error: `Активный плагин "${pluginName}" не найден для этого бота.` });
1501
+ }
1502
+
1503
+ const manifest = plugin.manifest ? JSON.parse(plugin.manifest) : {};
1504
+ const savedSettings = plugin.settings ? JSON.parse(plugin.settings) : {};
1505
+ const defaultSettings = {};
1506
+
1507
+ if (manifest.settings) {
1508
+ for (const key in manifest.settings) {
1509
+ const config = manifest.settings[key];
1510
+ if (config.type === 'json_file' && config.defaultPath) {
1511
+ const configFilePath = path.join(plugin.path, config.defaultPath);
1512
+ try {
1513
+ const fileContent = await fs.readFile(configFilePath, 'utf-8');
1514
+ defaultSettings[key] = JSON.parse(fileContent);
1515
+ } catch (e) { defaultSettings[key] = {}; }
1516
+ } else {
1517
+ try { defaultSettings[key] = JSON.parse(config.default || 'null'); }
1518
+ catch { defaultSettings[key] = config.default; }
1519
+ }
1520
+ }
1521
+ }
1522
+ const finalSettings = { ...defaultSettings, ...savedSettings };
1523
+
1524
+ const mainFilePath = manifest.main || 'index.js';
1525
+ const pluginEntryPoint = path.join(plugin.path, mainFilePath);
1526
+
1527
+ delete require.cache[require.resolve(pluginEntryPoint)];
1528
+ const pluginModule = require(pluginEntryPoint);
1529
+
1530
+ if (typeof pluginModule.getUiPageContent !== 'function') {
1531
+ return res.status(501).json({ error: `Плагин "${pluginName}" не предоставляет кастомный UI контент.` });
1532
+ }
1533
+
1534
+ const botProcess = botManager.bots.get(numericBotId);
1535
+ const botApi = botProcess ? botProcess.api : null;
1536
+
1537
+ const content = await pluginModule.getUiPageContent({
1538
+ path: uiPath,
1539
+ bot: botApi,
1540
+ botId: numericBotId,
1541
+ settings: finalSettings
1542
+ });
1543
+
1544
+ if (content === null) {
1545
+ return res.status(404).json({ error: `Для пути "${uiPath}" не найдено содержимого в плагине "${pluginName}".` });
1546
+ }
1547
+
1548
+ res.json(content);
1549
+
1550
+ } catch (error) {
1551
+ console.error(`[UI Content] Ошибка при получении контента для плагина "${pluginName}":`, error);
1552
+ res.status(500).json({ error: error.message || 'Внутренняя ошибка сервера.' });
1553
+ }
1554
+ });
1555
+
1556
+
1557
+ router.post('/:botId/plugins/:pluginName/action', authorize('plugin:list'), async (req, res) => {
1558
+ const { botId, pluginName } = req.params;
1559
+ const { actionName, payload } = req.body;
1560
+ const numericBotId = parseInt(botId, 10);
1561
+
1562
+ if (!actionName) {
1563
+ return res.status(400).json({ error: 'Необходимо указать "actionName".' });
1564
+ }
1565
+
1566
+ try {
1567
+ const botProcess = botManager.bots.get(numericBotId);
1568
+
1569
+ if (!botProcess) {
1570
+ return res.status(404).json({ error: 'Бот не найден или не запущен.' });
1571
+ }
1572
+
1573
+ const plugin = await prisma.installedPlugin.findFirst({
1574
+ where: { botId: numericBotId, name: pluginName, isEnabled: true }
1575
+ });
1576
+
1577
+ if (!plugin) {
1578
+ return res.status(404).json({ error: `Активный плагин с таким именем "${pluginName}" не найден.` });
1579
+ }
1580
+
1581
+ const manifest = plugin.manifest ? JSON.parse(plugin.manifest) : {};
1582
+ const savedSettings = plugin.settings ? JSON.parse(plugin.settings) : {};
1583
+ const defaultSettings = {};
1584
+
1585
+ if (manifest.settings) {
1586
+ for (const key in manifest.settings) {
1587
+ const config = manifest.settings[key];
1588
+ if (config.type === 'json_file' && config.defaultPath) {
1589
+ const configFilePath = path.join(plugin.path, config.defaultPath);
1590
+ try {
1591
+ const fileContent = await fs.readFile(configFilePath, 'utf-8');
1592
+ defaultSettings[key] = JSON.parse(fileContent);
1593
+ } catch (e) {
1594
+ console.error(`[Action] Не удалось прочитать defaultPath для ${pluginName}: ${e.message}`);
1595
+ defaultSettings[key] = {};
1596
+ }
1597
+ } else {
1598
+ try {
1599
+ defaultSettings[key] = JSON.parse(config.default || 'null');
1600
+ } catch {
1601
+ defaultSettings[key] = config.default;
1602
+ }
1603
+ }
1604
+ }
1605
+ }
1606
+ const finalSettings = { ...defaultSettings, ...savedSettings };
1607
+
1608
+ const mainFilePath = manifest.main || 'index.js';
1609
+ const pluginPath = path.join(plugin.path, mainFilePath);
1610
+
1611
+ delete require.cache[require.resolve(pluginPath)];
1612
+ const pluginModule = require(pluginPath);
1613
+
1614
+ if (typeof pluginModule.handleAction !== 'function') {
1615
+ return res.status(501).json({ error: `Плагин "${pluginName}" не поддерживает обработку действий.` });
1616
+ }
1617
+
1618
+ const result = await pluginModule.handleAction({
1619
+ botProcess: botProcess,
1620
+ botId: numericBotId,
1621
+ action: actionName,
1622
+ payload: payload,
1623
+ settings: finalSettings
1624
+ });
1625
+
1626
+ res.json({ success: true, message: 'Действие выполнено.', result: result || null });
1627
+
1628
+ } catch (error) {
1629
+ console.error(`Ошибка выполнения действия "${actionName}" для плагина "${pluginName}":`, error);
1630
+ res.status(500).json({ error: error.message || 'Внутренняя ошибка сервера.' });
1631
+ }
1632
+ });
1633
+
1634
+
1635
+ router.get('/:botId/export', authorize('bot:export'), async (req, res) => {
1636
+ try {
1637
+ const botId = parseInt(req.params.botId, 10);
1638
+ const {
1639
+ includeCommands,
1640
+ includePermissions,
1641
+ includePluginFiles,
1642
+ includePluginDataStore,
1643
+ includeEventGraphs,
1644
+ } = req.query;
1645
+
1646
+ const bot = await prisma.bot.findUnique({ where: { id: botId } });
1647
+ if (!bot) {
1648
+ return res.status(404).json({ error: 'Bot not found' });
1649
+ }
1650
+
1651
+ const archive = archiver('zip', { zlib: { level: 9 } });
1652
+ res.attachment(`bot_${bot.username}_export_${new Date().toISOString()}.zip`);
1653
+ archive.pipe(res);
1654
+
1655
+ const botData = { ...bot };
1656
+ delete botData.password;
1657
+ delete botData.proxyPassword;
1658
+ archive.append(JSON.stringify(botData, null, 2), { name: 'bot.json' });
1659
+
1660
+ if (includeCommands === 'true') {
1661
+ const commands = await prisma.command.findMany({ where: { botId } });
1662
+ archive.append(JSON.stringify(commands, null, 2), { name: 'commands.json' });
1663
+ }
1664
+
1665
+ if (includePermissions === 'true') {
1666
+ const users = await prisma.user.findMany({ where: { botId }, include: { groups: { include: { group: true } } } });
1667
+ const groups = await prisma.group.findMany({ where: { botId }, include: { permissions: { include: { permission: true } } } });
1668
+ const permissions = await prisma.permission.findMany({ where: { botId } });
1669
+ const permissionsData = { users, groups, permissions };
1670
+ archive.append(JSON.stringify(permissionsData, null, 2), { name: 'permissions.json' });
1671
+ }
1672
+
1673
+ if (includeEventGraphs === 'true') {
1674
+ const eventGraphs = await prisma.eventGraph.findMany({ where: { botId } });
1675
+ archive.append(JSON.stringify(eventGraphs, null, 2), { name: 'event_graphs.json' });
1676
+ }
1677
+
1678
+ if (includePluginFiles === 'true' || includePluginDataStore === 'true') {
1679
+ const installedPlugins = await prisma.installedPlugin.findMany({ where: { botId } });
1680
+ archive.append(JSON.stringify(installedPlugins, null, 2), { name: 'plugins.json' });
1681
+
1682
+ try {
1683
+ const installedPlugins = await prisma.installedPlugin.findMany({ where: { botId } });
1684
+ const pluginSettings = installedPlugins
1685
+ .filter(plugin => plugin.settings && plugin.settings !== '{}')
1686
+ .map(plugin => ({
1687
+ pluginName: plugin.name,
1688
+ settings: plugin.settings
1689
+ }));
1690
+
1691
+ if (pluginSettings.length > 0) {
1692
+ console.log(`[Export] Экспорт настроек плагинов для бота ${botId}: ${pluginSettings.length} настроек`);
1693
+ archive.append(JSON.stringify(pluginSettings, null, 2), { name: 'settings.json' });
1694
+ } else {
1695
+ console.log(`[Export] Нет настроек плагинов для экспорта`);
1696
+ }
1697
+ } catch (error) {
1698
+ console.warn(`[Export] Ошибка при экспорте настроек плагинов:`, error.message);
1699
+ }
1700
+
1701
+ if (includePluginFiles === 'true') {
1702
+ for (const plugin of installedPlugins) {
1703
+ const pluginPath = plugin.path;
1704
+ if (await fs.stat(pluginPath).then(s => s.isDirectory()).catch(() => false)) {
1705
+ archive.directory(pluginPath, `plugins/${plugin.name}`);
1706
+ }
1707
+ }
1708
+ }
1709
+ if (includePluginDataStore === 'true') {
1710
+ console.log(`[Export] Экспорт PluginDataStore для бота ${botId}`);
1711
+ const pluginDataStore = await prisma.pluginDataStore.findMany({
1712
+ where: { botId: parseInt(botId) }
1713
+ });
1714
+ console.log(`[Export] Найдено записей PluginDataStore: ${pluginDataStore.length}`);
1715
+ if (pluginDataStore.length > 0) {
1716
+ archive.append(JSON.stringify(pluginDataStore, null, 2), { name: 'plugin_data_store.json' });
1717
+ console.log(`[Export] Данные PluginDataStore добавлены в архив`);
1718
+ } else {
1719
+ console.log(`[Export] Нет данных PluginDataStore для экспорта`);
1720
+ }
1721
+ }
1722
+ }
1723
+
1724
+ await archive.finalize();
1725
+
1726
+ } catch (error) {
1727
+ console.error('Failed to export bot:', error);
1728
+ if (!res.headersSent) {
1729
+ res.status(500).json({ error: `Failed to export bot: ${error.message}` });
1730
+ }
1731
+ }
1732
+ });
1733
+
1734
+ router.post('/import', authorize('bot:create'), upload.single('file'), async (req, res) => {
1735
+ if (!req.file) {
1736
+ return res.status(400).json({ error: 'No file uploaded.' });
1737
+ }
1738
+
1739
+ const botIdMap = new Map();
1740
+
1741
+ try {
1742
+ const zip = new AdmZip(req.file.buffer);
1743
+ const zipEntries = zip.getEntries();
1744
+
1745
+ const botDataEntry = zipEntries.find(e => e.entryName === 'bot.json');
1746
+ if (!botDataEntry) {
1747
+ return res.status(400).json({ error: 'Archive missing bot.json' });
1748
+ }
1749
+ const botData = JSON.parse(botDataEntry.getData().toString('utf8'));
1750
+
1751
+ const server = await prisma.server.findFirst();
1752
+ if (!server) {
1753
+ return res.status(500).json({ error: 'No servers configured in the target system.' });
1754
+ }
1755
+
1756
+ let newBotName = botData.username;
1757
+ let counter = 1;
1758
+ while (await prisma.bot.findFirst({ where: { username: newBotName } })) {
1759
+ newBotName = `${botData.username}_imported_${counter}`;
1760
+ counter++;
1761
+ }
1762
+
1763
+ const newBot = await prisma.bot.create({
1764
+ data: {
1765
+ ...botData,
1766
+ id: undefined,
1767
+ username: newBotName,
1768
+ serverId: server.id,
1769
+ password: null,
1770
+ proxyPassword: null
1771
+ },
1772
+ include: { server: true }
1773
+ });
1774
+
1775
+ botIdMap.set(botData.id, newBot.id);
1776
+
1777
+ const permissionsEntry = zipEntries.find(e => e.entryName === 'permissions.json');
1778
+ let pMap = new Map();
1779
+
1780
+ if (permissionsEntry) {
1781
+ const { users, groups, permissions } = JSON.parse(permissionsEntry.getData().toString('utf8'));
1782
+
1783
+ await setupDefaultPermissionsForBot(newBot.id, prisma);
1784
+
1785
+ for(let p of permissions.filter(p=>p.owner === 'system')) {
1786
+ const existingPermission = await prisma.permission.findFirst({
1787
+ where: {
1788
+ botId: newBot.id,
1789
+ name: p.name,
1790
+ owner: 'system'
1791
+ }
1792
+ });
1793
+ if (existingPermission) {
1794
+ pMap.set(p.id, existingPermission.id);
1795
+ }
1796
+ }
1797
+
1798
+ for(let p of permissions.filter(p=>p.owner !== 'system')) {
1799
+ const newP = await prisma.permission.create({ data: { ...p, id: undefined, botId: newBot.id }});
1800
+ pMap.set(p.id, newP.id);
1801
+ }
1802
+
1803
+ const gMap = new Map();
1804
+ for(let g of groups.filter(g=>g.owner !== 'system')) {
1805
+ const newG = await prisma.group.create({ data: { ...g, id: undefined, botId: newBot.id, permissions: {
1806
+ create: g.permissions.map(gp => ({ permissionId: pMap.get(gp.permissionId) })).filter(p=>p.permissionId)
1807
+ }}});
1808
+ gMap.set(g.id, newG.id);
1809
+ }
1810
+
1811
+ for(let u of users) {
1812
+ await prisma.user.create({ data: { ...u, id: undefined, botId: newBot.id, groups: {
1813
+ create: u.groups.map(ug => ({ groupId: gMap.get(ug.groupId) })).filter(g=>g.groupId)
1814
+ }}});
1815
+ }
1816
+ }
1817
+
1818
+ const pluginDataStoreEntry = zipEntries.find(e => e.entryName === 'plugin_data_store.json');
1819
+ if (pluginDataStoreEntry) {
1820
+ console.log(`[Import] Импорт PluginDataStore для бота ${newBot.id}`);
1821
+ const pluginDataStore = JSON.parse(pluginDataStoreEntry.getData().toString('utf8'));
1822
+ console.log(`[Import] Найдено записей PluginDataStore: ${pluginDataStore.length}`);
1823
+
1824
+ for (let dataRecord of pluginDataStore) {
1825
+ delete dataRecord.id;
1826
+ dataRecord.botId = newBot.id;
1827
+ await prisma.pluginDataStore.create({ data: dataRecord });
1828
+ }
1829
+ console.log(`[Import] PluginDataStore успешно импортирован`);
1830
+ }
1831
+
1832
+ const pluginsEntry = zipEntries.find(e => e.entryName === 'plugins.json');
1833
+ let pluginMap = new Map();
1834
+
1835
+ if (pluginsEntry) {
1836
+ const plugins = JSON.parse(pluginsEntry.getData().toString('utf8'));
1837
+ const pluginsDir = path.join(os.homedir(), '.blockmine', 'storage', 'plugins');
1838
+ const botPluginsDir = path.join(pluginsDir, newBot.username);
1839
+ await fs.mkdir(botPluginsDir, { recursive: true });
1840
+
1841
+ for (let pluginData of plugins) {
1842
+ const oldPath = pluginData.path;
1843
+ const pluginName = pluginData.name;
1844
+ const newPluginPath = path.join(botPluginsDir, pluginName);
1845
+
1846
+ const oldPluginId = pluginData.id;
1847
+ delete pluginData.id;
1848
+ pluginData.botId = newBot.id;
1849
+ pluginData.path = path.resolve(newPluginPath);
1850
+
1851
+ for (const entry of zipEntries) {
1852
+ if (entry.entryName.startsWith(`plugins/${pluginName}/`)) {
1853
+ const relativePath = entry.entryName.replace(`plugins/${pluginName}/`, '');
1854
+ if (relativePath) {
1855
+ const destPath = path.join(newPluginPath, relativePath);
1856
+ const destDir = path.dirname(destPath);
1857
+ await fs.mkdir(destDir, { recursive: true });
1858
+
1859
+ if (!entry.isDirectory) {
1860
+ await fs.writeFile(destPath, entry.getData());
1861
+ }
1862
+ }
1863
+ }
1864
+ }
1865
+
1866
+ const newPlugin = await prisma.installedPlugin.create({ data: pluginData });
1867
+ pluginMap.set(oldPluginId, newPlugin.id);
1868
+ }
1869
+ }
1870
+
1871
+ const commandsEntry = zipEntries.find(e => e.entryName === 'commands.json');
1872
+ if (commandsEntry) {
1873
+ const commands = JSON.parse(commandsEntry.getData().toString('utf8'));
1874
+ for (let command of commands) {
1875
+ delete command.id;
1876
+ command.botId = newBot.id;
1877
+
1878
+ if (command.permissionId && pMap.has(command.permissionId)) {
1879
+ command.permissionId = pMap.get(command.permissionId);
1880
+ } else {
1881
+ command.permissionId = null;
1882
+ }
1883
+
1884
+ if (command.pluginOwnerId && pluginMap.has(command.pluginOwnerId)) {
1885
+ command.pluginOwnerId = pluginMap.get(command.pluginOwnerId);
1886
+ } else {
1887
+ command.pluginOwnerId = null;
1888
+ }
1889
+
1890
+ try {
1891
+ await prisma.command.create({ data: command });
1892
+ } catch (error) {
1893
+ console.warn(`[Import] Пропущена команда ${command.name}: ${error.message}`);
1894
+ }
1895
+ }
1896
+ }
1897
+
1898
+ const eventGraphsEntry = zipEntries.find(e => e.entryName === 'event_graphs.json');
1899
+ if (eventGraphsEntry) {
1900
+ const eventGraphs = JSON.parse(eventGraphsEntry.getData().toString('utf8'));
1901
+ for (let graph of eventGraphs) {
1902
+ delete graph.id;
1903
+ graph.botId = newBot.id;
1904
+
1905
+ if (graph.pluginOwnerId && pluginMap.has(graph.pluginOwnerId)) {
1906
+ graph.pluginOwnerId = pluginMap.get(graph.pluginOwnerId);
1907
+ } else {
1908
+ graph.pluginOwnerId = null;
1909
+ }
1910
+
1911
+ try {
1912
+ await prisma.eventGraph.create({ data: graph });
1913
+ } catch (error) {
1914
+ console.warn(`[Import] Пропущен граф ${graph.name}: ${error.message}`);
1915
+ }
1916
+ }
1917
+ }
1918
+
1919
+ res.status(201).json(newBot);
1920
+
1921
+ } catch (error) {
1922
+ console.error('Failed to import bot:', error);
1923
+ res.status(500).json({ error: `Failed to import bot: ${error.message}` });
1924
+ }
1925
+ });
1926
+
1927
+ router.post('/import/preview', authorize('bot:create'), upload.single('file'), async (req, res) => {
1928
+ try {
1929
+ if (!req.file) {
1930
+ return res.status(400).json({ error: 'Файл не загружен' });
1931
+ }
1932
+
1933
+ const tempDir = path.join(os.tmpdir(), `import-${Date.now()}`);
1934
+ await fse.ensureDir(tempDir);
1935
+
1936
+ try {
1937
+ const zip = new AdmZip(req.file.buffer);
1938
+ zip.extractAllTo(tempDir, true);
1939
+
1940
+ console.log('[Import] Файлы в архиве:', zip.getEntries().map(entry => entry.entryName));
1941
+
1942
+ const importData = {
1943
+ plugins: [],
1944
+ commands: [],
1945
+ eventGraphs: [],
1946
+ settings: null,
1947
+ bot: null
1948
+ };
1949
+
1950
+ const botConfigPath = path.join(tempDir, 'bot.json');
1951
+ if (await fse.pathExists(botConfigPath)) {
1952
+ console.log('[Import] Найден bot.json');
1953
+ const botConfig = JSON.parse(await fse.readFile(botConfigPath, 'utf8'));
1954
+ delete botConfig.password;
1955
+ delete botConfig.proxyPassword;
1956
+ delete botConfig.id;
1957
+ delete botConfig.createdAt;
1958
+ delete botConfig.updatedAt;
1959
+ importData.bot = botConfig;
1960
+ } else {
1961
+ console.log('[Import] bot.json не найден');
1962
+ }
1963
+
1964
+ const pluginsPath = path.join(tempDir, 'plugins.json');
1965
+ if (await fse.pathExists(pluginsPath)) {
1966
+ console.log('[Import] Найден plugins.json');
1967
+ importData.plugins = JSON.parse(await fse.readFile(pluginsPath, 'utf8'));
1968
+ console.log('[Import] Плагинов:', importData.plugins.length);
1969
+ } else {
1970
+ console.log('[Import] plugins.json не найден');
1971
+ }
1972
+
1973
+ const commandsPath = path.join(tempDir, 'commands.json');
1974
+ if (await fse.pathExists(commandsPath)) {
1975
+ console.log('[Import] Найден commands.json');
1976
+ importData.commands = JSON.parse(await fse.readFile(commandsPath, 'utf8'));
1977
+ console.log('[Import] Команд:', importData.commands.length);
1978
+ } else {
1979
+ console.log('[Import] commands.json не найден');
1980
+ }
1981
+
1982
+ const eventGraphsPath = path.join(tempDir, 'event_graphs.json');
1983
+ if (await fse.pathExists(eventGraphsPath)) {
1984
+ console.log('[Import] Найден event_graphs.json');
1985
+ importData.eventGraphs = JSON.parse(await fse.readFile(eventGraphsPath, 'utf8'));
1986
+ console.log('[Import] Графов событий:', importData.eventGraphs.length);
1987
+ } else {
1988
+ console.log('[Import] event_graphs.json не найден');
1989
+ const eventGraphsPathAlt = path.join(tempDir, 'event-graphs.json');
1990
+ if (await fse.pathExists(eventGraphsPathAlt)) {
1991
+ console.log('[Import] Найден event-graphs.json');
1992
+ importData.eventGraphs = JSON.parse(await fse.readFile(eventGraphsPathAlt, 'utf8'));
1993
+ console.log('[Import] Графов событий:', importData.eventGraphs.length);
1994
+ } else {
1995
+ console.log('[Import] event-graphs.json тоже не найден');
1996
+ }
1997
+ }
1998
+
1999
+ const settingsPath = path.join(tempDir, 'settings.json');
2000
+ if (await fse.pathExists(settingsPath)) {
2001
+ console.log('[Import] Найден settings.json');
2002
+ importData.settings = JSON.parse(await fse.readFile(settingsPath, 'utf8'));
2003
+ } else {
2004
+ console.log('[Import] settings.json не найден');
2005
+ }
2006
+
2007
+ console.log('[Import] Итоговые данные:', {
2008
+ plugins: importData.plugins.length,
2009
+ commands: importData.commands.length,
2010
+ eventGraphs: importData.eventGraphs.length,
2011
+ hasSettings: !!importData.settings,
2012
+ hasBot: !!importData.bot
2013
+ });
2014
+
2015
+ res.json(importData);
2016
+
2017
+ } finally {
2018
+ await fse.remove(tempDir);
2019
+ }
2020
+
2021
+ } catch (error) {
2022
+ console.error('[API Error] /bots/import/preview:', error);
2023
+ res.status(500).json({ error: 'Не удалось обработать архив импорта' });
2024
+ }
2025
+ });
2026
+
2027
+ router.post('/import/create', authorize('bot:create'), async (req, res) => {
2028
+ try {
2029
+ const { username, password, prefix, serverId, note, owners, proxyHost, proxyPort, proxyUsername, proxyPassword, importData } = req.body;
2030
+
2031
+ if (!username || !serverId) {
2032
+ return res.status(400).json({ error: 'Имя и сервер обязательны' });
2033
+ }
2034
+
2035
+ const botData = {
2036
+ username,
2037
+ prefix,
2038
+ note,
2039
+ serverId: parseInt(serverId, 10),
2040
+ password: password ? encrypt(password) : null,
2041
+ owners: owners || '',
2042
+ proxyHost: proxyHost || null,
2043
+ proxyPort: proxyPort ? parseInt(proxyPort, 10) : null,
2044
+ proxyUsername: proxyUsername || null,
2045
+ proxyPassword: proxyPassword ? encrypt(proxyPassword) : null
2046
+ };
2047
+
2048
+ const newBot = await prisma.bot.create({
2049
+ data: botData,
2050
+ include: { server: true }
2051
+ });
2052
+
2053
+ await setupDefaultPermissionsForBot(newBot.id);
2054
+
2055
+ if (importData) {
2056
+ try {
2057
+ if (importData.plugins && Array.isArray(importData.plugins)) {
2058
+ for (const plugin of importData.plugins) {
2059
+ try {
2060
+ await prisma.installedPlugin.create({
2061
+ data: {
2062
+ ...plugin,
2063
+ botId: newBot.id,
2064
+ id: undefined
2065
+ }
2066
+ });
2067
+ console.log(`[Import] Импортирован плагин ${plugin.name}`);
2068
+ } catch (error) {
2069
+ console.warn(`[Import] Не удалось импортировать плагин ${plugin.name}:`, error.message);
2070
+ }
2071
+ }
2072
+ }
2073
+
2074
+ if (importData.commands && Array.isArray(importData.commands)) {
2075
+ for (const command of importData.commands) {
2076
+ try {
2077
+ await prisma.command.create({
2078
+ data: {
2079
+ ...command,
2080
+ botId: newBot.id,
2081
+ id: undefined
2082
+ }
2083
+ });
2084
+ } catch (error) {
2085
+ console.warn(`[Import] Не удалось импортировать команду ${command.name}:`, error.message);
2086
+ }
2087
+ }
2088
+ }
2089
+
2090
+ if (importData.eventGraphs && Array.isArray(importData.eventGraphs)) {
2091
+ for (const graph of importData.eventGraphs) {
2092
+ try {
2093
+ await prisma.eventGraph.create({
2094
+ data: {
2095
+ ...graph,
2096
+ botId: newBot.id,
2097
+ id: undefined
2098
+ }
2099
+ });
2100
+ } catch (error) {
2101
+ console.warn(`[Import] Не удалось импортировать граф событий ${graph.name}:`, error.message);
2102
+ }
2103
+ }
2104
+ }
2105
+
2106
+ if (importData.settings && Array.isArray(importData.settings)) {
2107
+ for (const setting of importData.settings) {
2108
+ try {
2109
+ const updated = await prisma.installedPlugin.updateMany({
2110
+ where: {
2111
+ botId: newBot.id,
2112
+ name: setting.pluginName
2113
+ },
2114
+ data: {
2115
+ settings: setting.settings
2116
+ }
2117
+ });
2118
+ if (updated.count > 0) {
2119
+ console.log(`[Import] Импортированы настройки плагина ${setting.pluginName}`);
2120
+ } else {
2121
+ console.warn(`[Import] Плагин ${setting.pluginName} не найден для применения настроек`);
2122
+ }
2123
+ } catch (error) {
2124
+ console.warn(`[Import] Не удалось импортировать настройки плагина ${setting.pluginName}:`, error.message);
2125
+ }
2126
+ }
2127
+ }
2128
+
2129
+ } catch (error) {
2130
+ console.error('[Import] Ошибка при импорте данных:', error);
2131
+ }
2132
+ }
2133
+
2134
+ res.status(201).json(newBot);
2135
+ } catch (error) {
2136
+ if (error.code === 'P2002') {
2137
+ return res.status(409).json({ error: 'Бот с таким именем уже существует' });
2138
+ }
2139
+ console.error("[API Error] /bots/import/create:", error);
2140
+ res.status(500).json({ error: 'Не удалось создать бота с импортированными данными' });
2141
+ }
2142
+ });
2143
+
2144
+ module.exports = router;