Skip to content

Commit

Permalink
add new command AdminToggle (AdventureTimeSS14#785)
Browse files Browse the repository at this point in the history
## Описание PR
<!-- Что вы изменили в этом пулл реквесте? -->

- [x] Если в кратце, то введена новая команда admin_toggle для снятия и
возращения прав в ручную
- [x] fuckrule перенесено в другую категорию прав, т.е. отключена для
игроков
- [x] добавленно логирование на tippy и tip
- [x] добавлено логирование на ghostkick
- [ ] нельзя забанить пользователя с Permission по нику
- [x] нельзя ghostkick прописать пользователю с Permission
- [x] нельзя снять права с помощью admin_toggle пользователю с
Permission
- [x] за сущностями с HideGhostWarpComponent, нельзя следовать


## Требования
<!--
В связи с наплывом ПР'ов нам необходимо убедиться, что ПР'ы следуют
правильным рекомендациям.

Пожалуйста, уделите время прочтению, если делаете пулл реквест (ПР)
впервые.

Отметьте поля ниже, чтобы подтвердить, что Вы действительно видели их
(поставьте X в скобках, например [X]):
-->
- [x] Я прочитал(а) и следую [Руководство по созданию пулл
реквестов](https://docs.spacestation14.com/en/general-development/codebase-info/pull-request-guidelines.html).
Я понимаю, что в противном случае мой ПР может быть закрыт по усмотрению
мейнтейнера.
- [x] Я добавил скриншоты/видео к этому пулл реквесту, демонстрирующие
его изменения в игре, **или** этот пулл реквест не требует демонстрации
в игре

## Критические изменения
<!--
Перечислите все критические изменения, включая изменения пространства
имён, публичных классов/методов/полей, переименования прототипов, и
предоставьте инструкции по их исправлению.
-->

**Чейнджлог**
NO CL NO FUN

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

- **Новые функции**
- Добавлена команда `admin_toggle` для переключения административного
статуса игроков.
- Улучшена система управления привилегиями администраторов с добавлением
проверок на разрешения.
- Улучшена механика взаимодействия для призрачных сущностей в системе
последователей.

- **Исправления ошибок**
- Команда `ShowRulesCommand` теперь проверяет права администратора перед
отображением правил.
- Команда `KickHideCommand` теперь предоставляет более точные сообщения
об ошибках при отсутствии игрока.

- **Документация**
- Обновлены текстовые файлы с описанием и подсказками для команды
`admin_toggle`.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
  • Loading branch information
Schrodinger71 authored Nov 16, 2024
1 parent 8b53525 commit a013142
Show file tree
Hide file tree
Showing 15 changed files with 181 additions and 15 deletions.
75 changes: 75 additions & 0 deletions Content.Server/ADT/Administration/Commands/AdminToggleCommand.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
using Content.Server.Administration.Managers;
using Content.Shared.Administration;
using Robust.Shared.Console;
using Content.Server.Administration;
using Robust.Server.Player;
using System.Linq;

namespace Content.Server.ADT.Administration.Commands;


[AdminCommand(AdminFlags.Permissions)]
public sealed class AdminToggleCommand : LocalizedCommands
{
[Dependency] private readonly IPlayerLocator _locator = default!;
[Dependency] private readonly IPlayerManager _playerManager = default!;
public override string Command => "admin_toggle";

public override async void Execute(IConsoleShell shell, string argStr, string[] args)
{
if (args.Length != 2)
{
shell.WriteLine("Error: invalid arguments!");
return;
}

var target = args[0];
var located = await _locator.LookupIdByNameOrIdAsync(target);
if (located == null)
{
shell.WriteError(Loc.GetString("cmd-admin_toggle-error-args"));
return;
}

if (!_playerManager.TryGetSessionById(located.UserId, out var targetSession))
{
shell.WriteLine("Not session it's player!");
return;
}

if (targetSession == null)
return;

var mgr = IoCManager.Resolve<IAdminManager>();
if (args[1] == "deadmin")
{
mgr.DeAdmin(targetSession);
}
else if (args[1] == "readmin" && !(mgr.GetAdminData(targetSession, includeDeAdmin: true) == null))
{
mgr.ReAdmin(targetSession);
}
}

public override CompletionResult GetCompletion(IConsoleShell shell, string[] args)
{
if (args.Length == 1)
{
var options = _playerManager.Sessions.Select(c => c.Name).OrderBy(c => c).ToArray();
return CompletionResult.FromHintOptions(
options,
LocalizationManager.GetString("cmd-ban-hint"));
}
if (args.Length == 2)
{
var durations = new CompletionOption[]
{
new("deadmin", LocalizationManager.GetString("cmd-admin_toggle-deadmin")),
new("readmin", LocalizationManager.GetString("cmd-admin_toggle-readmin")),
};
return CompletionResult.FromHintOptions(durations, LocalizationManager.GetString("cmd-admin_toggle-hint-duration"));
}
return CompletionResult.Empty;
}
}

10 changes: 9 additions & 1 deletion Content.Server/ADT/Administration/Commands/BanMassCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,9 @@ public sealed class BanMassCommand : LocalizedCommands
[Dependency] private readonly IConfigurationManager _cfg = default!;
[Dependency] private readonly IPlayerManager _playerManager = default!;
[Dependency] private readonly ILogManager _logManager = default!;

[Dependency] private readonly IDiscordBanInfoSender _discordBanInfoSender = default!;
[Dependency] private readonly IServerDbManager _dbManager = default!;
[Dependency] private readonly IAdminManager _adminManager = default!;

public override string Command => "banmass";

Expand Down Expand Up @@ -81,6 +81,14 @@ public override async void Execute(IConsoleShell shell, string argStr, string[]
var targetUid = located.UserId;
var targetHWid = located.LastHWId;

var dbData = await _dbManager.GetAdminDataForAsync(targetUid);
if (dbData != null && dbData.AdminRank != null)
{
var targetPermissionsFlag = AdminFlagsHelper.NamesToFlags(dbData.AdminRank.Flags.Select(p => p.Flag));
if ((targetPermissionsFlag & AdminFlags.Permissions) == AdminFlags.Permissions) // Адмемов с правами Пермиссион не забанят
return;
}

//Start логи банов для диса
var lastServerBan = await _dbManager.GetLastServerBanAsync();
var newServerBanId = lastServerBan is not null ? lastServerBan.Id + 1 : 1;
Expand Down
2 changes: 0 additions & 2 deletions Content.Server/ADT/Administration/Commands/EchoChatCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -56,10 +56,8 @@ public override void Execute(IConsoleShell shell, string argStr, string[] args)
_chatSystem.TrySendInGameICMessage(entityUid.Value, message, InGameICChatType.Whisper, ChatTransmitRange.Normal);
}

// Проверяем, нужно ли добавлять запись в логи
if (args.Length == 4 && args[3] == "false")
{
// Не добавляем в логи
return;
}

Expand Down
11 changes: 9 additions & 2 deletions Content.Server/ADT/Administration/Commands/KickHideCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using Robust.Shared.Console;
using Content.Server.GhostKick;
using Content.Server.Administration;
using Content.Server.Administration.Managers;

namespace Content.Server.ADT.Administration.Commands;

Expand All @@ -16,6 +17,7 @@ public sealed class KickHideCommand : LocalizedCommands
[Dependency] private readonly IPlayerLocator _locator = default!;
[Dependency] private readonly IPlayerManager _playerManager = default!;
[Dependency] private readonly GhostKickManager _ghostKickManager = default!;
[Dependency] private readonly IAdminManager _adminManager = default!;

public override string Command => "kick_hide";

Expand All @@ -36,8 +38,13 @@ public override async void Execute(IConsoleShell shell, string argStr, string[]
return;
}

var targetSession = _playerManager.GetSessionById(located.UserId);
_ghostKickManager.DoDisconnect(targetSession.Channel, "Smitten.");
var players = IoCManager.Resolve<IPlayerManager>();
if (!players.TryGetSessionByUsername(target, out var player))
{
shell.WriteError($"Unable to find player: '{target}'.");
return;
}
_ghostKickManager.DoDisconnect(player.Channel, "Smitten.");
}

public override CompletionResult GetCompletion(IConsoleShell shell, string[] args)
Expand Down
14 changes: 14 additions & 0 deletions Content.Server/Administration/BanPanelEui.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ public sealed class BanPanelEui : BaseEui
[Dependency] private readonly IAdminManager _admins = default!;
[Dependency] private readonly IServerDbManager _dbManager = default!;
[Dependency] private readonly IDiscordBanInfoSender _discordBanInfoSender = default!;
[Dependency] private readonly IPlayerManager _playerManager = default!;

private readonly ISawmill _sawmill;

Expand Down Expand Up @@ -172,7 +173,20 @@ private async void BanPlayer(string? target, string? ipAddressString, bool useLa
_sawmill.Error($"Error while erasing banned player:\n{e}");
}
}
// ADT-Tweak-Start
if (targetUid != null)
{
var dbData = await _dbManager.GetAdminDataForAsync(targetUid.Value);

if (dbData != null && dbData.AdminRank != null)
{
var targetPermissionsFlag = AdminFlagsHelper.NamesToFlags(dbData.AdminRank.Flags.Select(p => p.Flag));

if ((targetPermissionsFlag & AdminFlags.Permissions) == AdminFlags.Permissions)
return;
}
}
// ADT-Tweak-End
var lastServerBan = await _dbManager.GetLastServerBanAsync();
var newServerBanId = lastServerBan is not null ? lastServerBan.Id + 1 : 1;

Expand Down
11 changes: 11 additions & 0 deletions Content.Server/Administration/Commands/BanCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ public sealed class BanCommand : LocalizedCommands
[Dependency] private readonly ILogManager _logManager = default!;
[Dependency] private readonly IDiscordBanInfoSender _discordBanInfoSender = default!;
[Dependency] private readonly IServerDbManager _dbManager = default!;
[Dependency] private readonly IAdminManager _adminManager = default!;

public override string Command => "ban";

Expand Down Expand Up @@ -94,6 +95,16 @@ public override async void Execute(IConsoleShell shell, string argStr, string[]

var targetUid = located.UserId;
var targetHWid = located.LastHWId;

// ADT-Tweak-Start: Пользователя с флагом Permission не забанить
var dbData = await _dbManager.GetAdminDataForAsync(targetUid);
if (dbData != null && dbData.AdminRank != null)
{
var targetPermissionsFlag = AdminFlagsHelper.NamesToFlags(dbData.AdminRank.Flags.Select(p => p.Flag));
if ((targetPermissionsFlag & AdminFlags.Permissions) == AdminFlags.Permissions)
return;
}
// ADT-Tweak-End
//Start-ADT-Tweak: логи банов для диса
var lastServerBan = await _dbManager.GetLastServerBanAsync();
var newServerBanId = lastServerBan is not null ? lastServerBan.Id + 1 : 1;
Expand Down
12 changes: 6 additions & 6 deletions Content.Server/Administration/Managers/AdminManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -112,10 +112,10 @@ public void Stealth(ICommonSession session)
var playerData = session.ContentData()!;
playerData.Stealthed = true;
reg.Data.Stealth = true;

// ADT Tweak commented
_chat.DispatchServerMessage(session, Loc.GetString("admin-manager-stealthed-message"));
_chat.SendAdminAnnouncement(Loc.GetString("admin-manager-self-de-admin-message", ("exAdminName", session.Name)), AdminFlags.Stealth);
_chat.SendAdminAnnouncement(Loc.GetString("admin-manager-self-enable-stealth", ("stealthAdminName", session.Name)), flagWhitelist: AdminFlags.Stealth);
// _chat.SendAdminAnnouncement(Loc.GetString("admin-manager-self-de-admin-message", ("exAdminName", session.Name)), AdminFlags.Stealth);
// _chat.SendAdminAnnouncement(Loc.GetString("admin-manager-self-enable-stealth", ("stealthAdminName", session.Name)), flagWhitelist: AdminFlags.Stealth);
}

public void UnStealth(ICommonSession session)
Expand All @@ -131,10 +131,10 @@ public void UnStealth(ICommonSession session)
var playerData = session.ContentData()!;
playerData.Stealthed = false;
reg.Data.Stealth = false;

// ADT Tweak commented
_chat.DispatchServerMessage(session, Loc.GetString("admin-manager-unstealthed-message"));
_chat.SendAdminAnnouncement(Loc.GetString("admin-manager-self-re-admin-message", ("newAdminName", session.Name)), flagBlacklist: AdminFlags.Stealth);
_chat.SendAdminAnnouncement(Loc.GetString("admin-manager-self-disable-stealth", ("exStealthAdminName", session.Name)), flagWhitelist: AdminFlags.Stealth);
// _chat.SendAdminAnnouncement(Loc.GetString("admin-manager-self-re-admin-message", ("newAdminName", session.Name)), flagBlacklist: AdminFlags.Stealth);
// _chat.SendAdminAnnouncement(Loc.GetString("admin-manager-self-disable-stealth", ("exStealthAdminName", session.Name)), flagWhitelist: AdminFlags.Stealth);
}

public void ReAdmin(ICommonSession session)
Expand Down
2 changes: 1 addition & 1 deletion Content.Server/Ghost/GhostSystem.cs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@
using System.Linq;
using System.Numerics;
using Content.Shared.ADT.OnGhostAttemtpDamage;
using Content.Server.ADT.Ghost;
using Content.Shared.ADT.Ghost;

namespace Content.Server.Ghost
{
Expand Down
18 changes: 17 additions & 1 deletion Content.Server/GhostKick/GhostKickManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@
using Robust.Shared.Console;
using Robust.Shared.Network;
using Robust.Shared.Timing;
using Content.Server.Administration.Managers;
using Content.Server.Administration.Logs;
using Content.Shared.Database;

namespace Content.Server.GhostKick;

Expand Down Expand Up @@ -47,6 +50,8 @@ public void DoDisconnect(INetChannel channel, string reason)
[AdminCommand(AdminFlags.Moderator)]
public sealed class GhostKickCommand : IConsoleCommand
{
[Dependency] private readonly IAdminManager _adminManager = default!;
[Dependency] private readonly IAdminLogManager _adminLogger = default!;
public string Command => "ghostkick";
public string Description => "Kick a client from the server as if their network just dropped.";
public string Help => "Usage: ghostkick <Player> [Reason]";
Expand All @@ -70,7 +75,18 @@ public void Execute(IConsoleShell shell, string argStr, string[] args)
shell.WriteError($"Unable to find player: '{playerName}'.");
return;
}

// ADT-Tweak-start
if (_adminManager.HasAdminFlag(player, AdminFlags.Permissions))
{
shell.WriteError($"You dont have permission to kick '{playerName}'");
return;
}
_adminLogger.Add(
LogType.AdminMessage,
LogImpact.Low,
$"[АДМИНАБУЗ] {shell.Player?.Name} used the command ghostkick on '{playerName}'."
);
// ADT-Tweak-end
ghostKick.DoDisconnect(player.Channel, reason);
}
}
7 changes: 7 additions & 0 deletions Content.Server/Info/ShowRulesCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
using Robust.Shared.Configuration;
using Robust.Shared.Console;
using Robust.Shared.Network;
using Content.Server.Administration.Managers;

namespace Content.Server.Info;

Expand All @@ -15,6 +16,7 @@ public sealed class ShowRulesCommand : IConsoleCommand
[Dependency] private readonly INetManager _net = default!;
[Dependency] private readonly IConfigurationManager _configuration = default!;
[Dependency] private readonly IPlayerManager _player = default!;
[Dependency] private readonly IAdminManager _adminManager = default!;

public string Command => "showrules";
public string Description => "Opens the rules popup for the specified player.";
Expand Down Expand Up @@ -57,6 +59,11 @@ public async void Execute(IConsoleShell shell, string argStr, string[] args)
return;
}

if (_adminManager.HasAdminFlag(player, AdminFlags.Permissions)) // ADT-Tweak
{
shell.WriteError($"You not permission for showrule '{target}'.");
return;
}
var coreRules = _configuration.GetCVar(CCVars.RulesFile);
var message = new SendRulesInformationMessage { PopupTime = seconds, CoreRules = coreRules, ShouldShowRules = true};
_net.ServerSendMessage(message, player.Channel);
Expand Down
10 changes: 10 additions & 0 deletions Content.Server/Tips/TipsSystem.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
using Robust.Shared.Prototypes;
using Robust.Shared.Random;
using Robust.Shared.Timing;
using Content.Server.Administration.Logs;
using Content.Shared.Database;

namespace Content.Server.Tips;

Expand All @@ -28,6 +30,7 @@ public sealed class TipsSystem : EntitySystem
[Dependency] private readonly GameTicker _ticker = default!;
[Dependency] private readonly IConsoleHost _conHost = default!;
[Dependency] private readonly IPlayerManager _playerManager = default!;
[Dependency] private readonly IAdminLogManager _adminLogger = default!;

private bool _tipsEnabled;
private float _tipTimeOutOfRound;
Expand Down Expand Up @@ -82,6 +85,13 @@ private void SendTippy(IConsoleShell shell, string argstr, string[] args)
return;
}

// ADT-Tweak-Start Логируем сообщение
_adminLogger.Add(
LogType.AdminMessage,
LogImpact.Low,
$"[АДМИНАБУЗ] {shell.Player?.Name} used the command tippy or tip."
);
// ADT-Tweak-End
ActorComponent? actor = null;
if (args[0] != "all")
{
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
namespace Content.Server.ADT.Ghost;
namespace Content.Shared.ADT.Ghost;

/// <summary>
/// Author: Schrodinger71, помогал _kote(Котька)
/// Вешаем на сущность, и к ней нельзя будет тепнуться через "Телепорт призрака".
/// </summary>
[RegisterComponent]
Expand Down
10 changes: 10 additions & 0 deletions Content.Shared/Follower/FollowerSystem.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@
using Robust.Shared.Physics.Systems;
using Robust.Shared.Player;
using Robust.Shared.Utility;
using Content.Shared.ADT.Ghost;
using Robust.Shared.Spawners;

namespace Content.Shared.Follower;

Expand Down Expand Up @@ -149,6 +151,14 @@ private void OnFollowedTerminating(EntityUid uid, FollowedComponent component, r
/// <param name="entity">The entity to be followed</param>
public void StartFollowingEntity(EntityUid follower, EntityUid entity)
{
// ADT-Tweak-Start: Улучшаем смысл компонента
if (HasComp<HideGhostWarpComponent>(entity))
{
var despawn = EnsureComp<TimedDespawnComponent>(follower);
despawn.Lifetime = 0.1f;
return;
}
// ADT-Tweak-End
// No recursion for you
var targetXform = Transform(entity);
while (targetXform.ParentUid.IsValid())
Expand Down
8 changes: 8 additions & 0 deletions Resources/Locale/ru-RU/ADT/administration/commands.ftl
Original file line number Diff line number Diff line change
Expand Up @@ -18,3 +18,11 @@ echo_chat-speak-help = Использовать обычную разговор
echo_chat-emote-help = Использовать чат эмоций
echo_chat-whisper-help = Использование чата шёпотом
## Команда: admin_toggle
cmd-admin_toggle-desc = Вводит в деадмин или реадмин указанного пользователя.
cmd-admin_toggle-help = Использование: admin_toggle <userName> <readmin/deadmin>
cmd-admin_toggle-hint-duration = Значение
cmd-admin_toggle-readmin = Вернуть права админу.
cmd-admin_toggle-deadmin = Ввести в деадмин.
cmd-admin_toggle-error-args = Указанный пользователь не найден.
3 changes: 2 additions & 1 deletion Resources/clientCommandPerms.yml
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
- gc
- gc_mode
- cvar
- fuckrules
# - fuckrules # ADT-Tweak
- midipanic
- replay_recording_start
- replay_recording_stop
Expand Down Expand Up @@ -79,6 +79,7 @@
- mapping
- toggleautosave
- toggledecals
- fuckrules # ADT-Tweak

- Flags: QUERY
Commands:
Expand Down

0 comments on commit a013142

Please sign in to comment.