-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcmd-vote.js
More file actions
488 lines (429 loc) · 15 KB
/
cmd-vote.js
File metadata and controls
488 lines (429 loc) · 15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
import BasePlugin from "./base-plugin.js";
import y18n from "y18n";
const LOG_LEVEL = 3;
const [TEAM_ONE_ID, TEAM_TWO_ID] = [1, 2];
let LOCALE = null;
export default class CMDVote extends BasePlugin {
static get description() {
return "Voting for the demotion of the squad commander. It is started by the commander of the side";
}
static get defaultEnabled() {
return false;
}
static get optionsSpecification() {
return {
language: {
required: false,
description: "Plugin language",
default: "en",
},
startVoteCommand: {
required: false,
description:
"The command for started voting for the squad leaders kick",
default: "cmdvote",
},
ignoreChats: {
required: false,
description: "Skipped Chats",
default: ["ChatSquad", "ChatAdmin"],
},
endVoteTimeout: {
required: false,
description: "Time to vote in seconds",
default: 45,
},
timeoutAfterNewMap: {
required: false,
description:
"Time after start a new match when the command is unavailable",
default: 300,
},
minSquadSizeForVote: {
required: false,
description: "The minimum size of a squad for the vote count",
default: 3,
},
minSquadsForStart: {
required: false,
description:
"The minimum count of squads per side after which the command is active",
default: 3,
},
minSquadsVotePercent: {
required: false,
description:
"The minimum percentage of those who voted in order for the voting results to be valid, fractional value",
default: 0.4,
},
periodicallyMessageTimeout: {
required: false,
description:
"The time between messages about the voting process, in seconds",
default: 6,
},
timeoutBetweenVote: {
required: false,
description: "The timeout between votes in seconds",
default: 15,
},
blockCreateSquadAfterDemote: {
required: false,
description:
"Should the demoted player be blocked from creating a squad until the end of the current map",
default: true,
},
};
}
constructor(server, options, connectors) {
super(server, options, connectors);
LOCALE = y18n({
locale: this.options.language,
directory: "./squad-server/plugins/cmd-vote-locales",
}).__;
this.votes = new Map([
[TEAM_ONE_ID, new Vote(TEAM_ONE_ID, this.server, this.options)],
[TEAM_TWO_ID, new Vote(TEAM_TWO_ID, this.server, this.options)],
]);
this.timeStartLastGame = 0;
this.onStartVoteCommand = this.onStartVoteCommand.bind(this);
}
async onStartVoteCommand(data) {
this.verbose(LOG_LEVEL, LOCALE`Message received`, data);
if (
Date.now() <
this.timeStartLastGame + this.options.timeoutAfterNewMap * 1000
) {
await this.server.rcon.warn(
data.steamID,
LOCALE`Voting is available ${this.options.timeoutAfterNewMap} seconds after the game starts`
);
return;
}
if (data.message) {
const vote = this.votes.get(data.player.teamID);
this.verbose(LOG_LEVEL, LOCALE`Voting to message`, vote);
if (vote) {
this.verbose(
LOG_LEVEL,
LOCALE`Voting object found. Start voting for the demote of the squad leader`
);
await vote.start(data);
} else {
this.verbose(LOG_LEVEL, LOCALE`Voting object not found`);
await this.server.rcon.warn(
data.player.steamID,
LOCALE`Your team ID was not found, please try again later`
);
}
}
}
async mount() {
// Если во время голосования матч закончился - убираем все таймеры и сообщения
this.server.on("NEW_GAME", async () => {
for (let vote of this.votes.values()) {
vote.clear();
}
this.timeStartLastGame = new Date().valueOf();
});
if (this.options.blockCreateSquadAfterDemote) {
this.server.on("PLAYER_NOW_IS_LEADER", async (data) => {
if (data.player) {
const vote = this.votes.get(data.player.teamID);
if (vote && vote.playerHasBeenDemoted(data.player.steamID)) {
await this.server.rcon.execute(
`AdminRemovePlayerFromSquadById ${data.player.playerID}`
);
await this.server.rcon.warn(
data.player.steamID,
LOCALE`You are not allowed to create a squad for this side in this match`
);
}
}
});
}
this.server.on(
`CHAT_COMMAND:${this.options.startVoteCommand.toLowerCase()}`,
this.onStartVoteCommand
);
}
}
/**
* Голосование на кик сквадного из его же сквада через голосование запускаемое
* командиром стороны
*/
class Vote {
constructor(teamID, server, options) {
this.isStarted = false;
this.lastVoteTime = 0;
this.votes = new Map();
this.squadIDForDemotion = null;
this.leaderForDemotion = null;
this.teamID = teamID;
this.server = server;
this.options = options;
this.messageProcessing = this.messageProcessing.bind(this);
this.start = this.start.bind(this);
this.warnSquadLeaders = this.warnSquadLeaders.bind(this);
this.end = this.end.bind(this);
this.playerHasBeenDemoted = this.playerHasBeenDemoted.bind(this);
this.periodicallyMessageTimer;
this.endVoteTimer;
this.demotedPlayers = new Set();
}
/**
* Проверка, что игрок был разжалован в этом матче
* @param {*} player
*/
playerHasBeenDemoted(steamID) {
return this.demotedPlayers.has(steamID);
}
/**
* Старт голосования, с валидацией сообщения, поиском сквада для которого
* запросили голосование и поиском игрока, который в текущий момент сквадом управляет
* @param {*} data
* @returns
*/
async start(data) {
if (!(await this.startValidate(data))) {
return;
}
this.squadIDForDemotion = data.message;
this.leaderForDemotion = await this.server.getPlayerByCondition(
(player) => {
return (
player.teamID === this.teamID &&
player.squadID == this.squadIDForDemotion &&
player.isLeader
);
},
true
);
if (this.leaderForDemotion === null) {
await this.server.rcon.warn(data.steamID, LOCALE`Squad not found`);
return;
}
this.isStarted = true;
this.votes.clear();
this.server.on("CHAT_MESSAGE", this.messageProcessing);
this.endVoteTimer = setTimeout(
this.end,
this.options.endVoteTimeout * 1000
);
await this.warnSquadLeaders(
LOCALE`Demote squad leader ${this.squadIDForDemotion}, ${this.leaderForDemotion.name}? +/- to chat`
);
this.periodicallyMessageTimer = setInterval(
this.warnSquadLeaders,
this.options.periodicallyMessageTimeout * 1000,
LOCALE`Demote squad leader ${this.squadIDForDemotion}, ${this.leaderForDemotion.name}? +/- to chat`
);
}
/**
* Удаление всех таймаутов и остановка коллбеков
*/
clearTimeoutsAndListeners() {
clearInterval(this.periodicallyMessageTimer);
clearTimeout(this.endVoteTimer);
this.server.removeListener("CHAT_MESSAGE", this.messageProcessing);
}
/**
* ПОЛНОЕ обнуление объекта и остановка голосования, если оно идёт,
* например используется при старте новый игры
*/
clear() {
this.clearTimeoutsAndListeners();
this.lastVoteTime = 0;
this.isStarted = false;
this.votes.clear();
this.demotedPlayers = new Set();
this.squadIDForDemotion = null;
this.leaderForDemotion = null;
}
/**
* Коллбек окончания голосования, подсчитывает голоса, выдаёт результат и применяет меры к сквадному
* @returns
*/
async end() {
this.clearTimeoutsAndListeners();
this.lastVoteTime = new Date().valueOf();
this.isStarted = false;
let [countPositively, countAgainst, countValidSquads, countVotedSquads] =
await this.getResult();
const countMinSquads = Math.floor(
countValidSquads * this.options.minSquadsVotePercent
);
if (countVotedSquads <= countMinSquads) {
await this.warnSquadLeaders(
LOCALE`Squad leader ${this.squadIDForDemotion} retained, less than ${this.options.minSquadsVotePercent * 100}% of squads voted (less than ${countMinSquads})`
);
return;
}
if (countPositively <= countAgainst) {
await this.warnSquadLeaders(
LOCALE`Squad leader ${this.squadIDForDemotion} retained, ${countPositively} vs ${countAgainst}, had ${countValidSquads} eligible to vote`
);
return;
}
await this.warnSquadLeaders(
LOCALE`Squad leader ${this.squadIDForDemotion} was demoted, ${countPositively} vs ${countAgainst}, had ${countValidSquads} eligible to vote`
);
this.demotedPlayers.add(this.leaderForDemotion.steamID);
// На всякий случай получаем пользователя, чтобы не кикнуть другого игрока,
// т.к. удаление игрока из сквада идёт по переиспользуемому ID
const player = await this.server.getPlayerBySteamID(
this.leaderForDemotion.steamID,
true
);
if (player) {
await this.server.rcon.execute(
`AdminRemovePlayerFromSquadById ${player.playerID}`
);
}
}
/**
* Возвращает текущий ход голосования
* @returns array [Количество "За", Количество "Против",
* Количество сквадов которые имеют право голосовать,
* Количество сквадов которые проголосовали (из тех, что имеют на это право)]
*/
async getResult() {
await this.server.updateSquadList();
const validSquads = await this.server.squads.filter((data) => {
return (
data.teamID === this.teamID &&
data.size >= this.options.minSquadSizeForVote &&
data.squadID !== this.squadIDForDemotion
);
});
let validSquadsIds = validSquads.map((squad) => squad.squadID);
let countAgainst = 0;
let countPositively = 0;
let countAllValid = validSquadsIds.length;
for (let [squadID, vote] of this.votes) {
if (validSquadsIds.includes(squadID)) {
vote ? countPositively++ : countAgainst++;
}
}
const countAllVoted = countPositively + countAgainst;
return [countPositively, countAgainst, countAllValid, countAllVoted];
}
/**
* Валидирует команду на начало голосования, кидает варны, если необходимо
* @param {object} data Данные, которые были переданы от ивента (steamID, playerID, message, etc...)
* @returns true если валидация успешна, false если нет
*/
async startValidate(data) {
if (
!(data.player.isLeader && data.player.squad.squadName === "Command Squad")
) {
return false;
}
if (isNaN(Number(data.message))) {
await this.server.rcon.warn(
data.steamID,
LOCALE`Command should be in the format - !${this.options.startVoteCommand} <squad number>`
);
}
if (this.isStarted) {
await this.server.rcon.warn(
data.steamID,
LOCALE`Voting is already in progress`
);
return false;
}
if (
Date.now() <
this.lastVoteTime.valueOf() + this.options.timeoutBetweenVote * 1000
) {
await this.server.rcon.warn(
data.steamID,
LOCALE`Voting is only available once every ${this.options.timeoutBetweenVote} seconds`
);
return false;
}
const squads = await this.server.squads.filter((squad) => {
return squad.teamID === this.teamID;
});
if (squads.length < this.options.minSquadsForStart) {
await this.server.rcon.warn(
data.steamID,
LOCALE`Voting is available when there are at least ${this.options.minSquadsForStart} squads`
);
return false;
}
return true;
}
/**
* Валидирует сообщение которое потенциально может быть голосом
* @param {object} data Данные, которые были переданы от ивента (steamID, playerID, message, etc...)
* @returns true если прошло валидацию, false если нет
*/
async messageValidate(data) {
if (
data.player.teamID !== this.teamID ||
data.player.isLeader === false ||
data.player.squad === null
) {
return false;
}
if (data.player.squadID === this.squadIDForDemotion) {
await this.server.rcon.warn(
data.steamID,
LOCALE`The vote of this squad is not counted`
);
return false;
}
if (data.player.squad.size < this.options.minSquadSizeForVote) {
await this.server.rcon.warn(
data.steamID,
LOCALE`The minimum squad size for voting is ${this.options.minSquadSizeForVote}`
);
return false;
}
return true;
}
/**
* В зависимости от содержания сообщения выставляет голос в Map
* @param {object} data Данные, которые были переданы от ивента (steamID, playerID, message, etc...)
* @returns
*/
async messageProcessing(data) {
switch (data.message) {
case "+":
if (!(await this.messageValidate(data))) {
return;
}
this.votes.set(data.player.squadID, true);
await this.server.rcon.warn(
data.steamID,
LOCALE`A positive vote is accepted`
);
break;
case "-":
if (!(await this.messageValidate(data))) {
return;
}
this.votes.set(data.player.squadID, false);
await this.server.rcon.warn(
data.steamID,
LOCALE`A negative vote is accepted`
);
break;
}
}
/**
* Кидает варны всем сквад лидерам, также обновляет список игроков, \
* чтобы не пропустить какого-либо сквад лидера
* @param {string} message Текст сообщения
*/
async warnSquadLeaders(message) {
await this.server.updatePlayerList();
const players = await this.server.players.filter((data) => {
return data.teamID === this.teamID && data.isLeader;
});
for (let player of players) {
await this.server.rcon.warn(player.steamID, message);
}
}
}