Repository navigation
Expand file tree
/
Copy pathFrontierParkingSystem.cs
More file actions
482 lines (441 loc) · 19.7 KB
/
Copy pathFrontierParkingSystem.cs
File metadata and controls
482 lines (441 loc) · 19.7 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
// LuaWorld/LuaCorp - This file is licensed under AGPLv3
// Copyright (c) 2026 LuaWorld/LuaCorp
// See AGPLv3.txt for details.
using Content.Shared._NF.Bank;
using Content.Server._NF.Bank;
using Content.Server.Chat.Managers;
using Content.Server.Database;
using Content.Server.Fax;
using Content.Server.GameTicking;
using Content.Server.Popups;
using Content.Server.Preferences.Managers;
using Content.Server.Shuttles.Components;
using Content.Server.Station.Systems;
using Content.Shared._Lua.Frontier.Parking;
using Content.Shared._NF.Bank.BUI;
using Content.Shared._NF.Bank.Components;
using Content.Shared._NF.Shipyard.Components;
using Content.Shared.Chat;
using Content.Shared.Fax.Components;
using Content.Shared.Lua.CLVar;
using Content.Shared.Paper;
using Content.Shared.Popups;
using Content.Shared.Preferences;
using Robust.Server.Player;
using Robust.Shared.Configuration;
using Robust.Shared.ContentPack;
using Robust.Shared.Map;
using Robust.Shared.Network;
using Robust.Shared.Player;
using Robust.Shared.Timing;
using Robust.Shared.Utility;
using System.Threading;
using System.Threading.Tasks;
using static Content.Server._NF.Shipyard.Systems.ShipyardSystem;
namespace Content.Server._Lua.Frontier.Parking;
public sealed class FrontierParkingSystem : EntitySystem
{
public enum ManualFineResult : byte
{
Success,
Queued,
InsufficientFunds,
NoOwner,
NotPending,
NotTracked,
NoFrontierStation
}
private enum ApplyFineResult : byte
{
Applied,
Queued,
InsufficientFunds,
NoOwner
}
private const PopupType PopupInfoType = PopupType.SmallCaution;
private const PopupType PopupWarningType = PopupType.SmallCaution;
private const PopupType PopupFineType = PopupType.SmallCaution;
[Dependency] private readonly IConfigurationManager _cfg = default!;
[Dependency] private readonly IGameTiming _timing = default!;
[Dependency] private readonly StationSystem _station = default!;
[Dependency] private readonly SharedTransformSystem _xform = default!;
[Dependency] private readonly BankSystem _bank = default!;
[Dependency] private readonly FaxSystem _fax = default!;
[Dependency] private readonly IChatManager _chat = default!;
[Dependency] private readonly IResourceManager _res = default!;
[Dependency] private readonly GameTicker _ticker = default!;
[Dependency] private readonly IServerPreferencesManager _prefsManager = default!;
[Dependency] private readonly IServerDbManager _db = default!;
[Dependency] private readonly IPlayerManager _playerManager = default!;
[Dependency] private readonly PopupSystem _popup = default!;
private bool _enabled;
private TimeSpan _nextScan;
private static readonly TimeSpan ScanInterval = TimeSpan.FromSeconds(1);
private static readonly TimeSpan FineInterval = TimeSpan.FromMinutes(10);
private const int FineAmount = 10_000;
private readonly Dictionary<EntityUid, ParkingState> _tracked = new();
private readonly Dictionary<EntityUid, Task> _pendingOfflineFines = new();
private readonly HashSet<EntityUid> _inZoneBuffer = new();
private readonly List<(EntityUid Uid, TransformComponent Xform, float Range)> _exclusionsBuffer = new();
public EntityUid? FrontierStation => GetFrontierStation();
public bool TryGetTracked(EntityUid shuttleUid, out ParkingPublicState state)
{
if (_tracked.TryGetValue(shuttleUid, out var s))
{
state = s.ToPublicState();
return true;
}
state = default;
return false;
}
public IEnumerable<(EntityUid Shuttle, ShuttleDeedComponent Deed, ParkingPublicState State)> EnumerateTracked()
{
foreach (var (uid, state) in _tracked)
{
if (!TryComp<ShuttleDeedComponent>(uid, out var deed))
continue;
yield return (uid, deed, state.ToPublicState());
}
}
public bool ResetTimer(EntityUid shuttleUid)
{
if (!_tracked.TryGetValue(shuttleUid, out var s))
return false;
s.CycleStart = _timing.CurTime;
s.SentFiveMinutes = false;
s.SentFortyFiveSeconds = false;
s.ExtraMinutes = 0;
s.HasViolation = false;
s.NeedsDisposal = false;
return true;
}
public bool AddTenMinutes(EntityUid shuttleUid)
{
if (!_tracked.TryGetValue(shuttleUid, out var s))
return false;
s.ExtraMinutes = Math.Min(50, s.ExtraMinutes + 10);
return true;
}
public ManualFineResult TryApplyManualFine(EntityUid shuttleUid)
{
if (!_tracked.TryGetValue(shuttleUid, out var state))
return ManualFineResult.NotTracked;
if (!state.FinePending)
return ManualFineResult.NotPending;
if (!TryComp<ShuttleDeedComponent>(shuttleUid, out var deed))
return ManualFineResult.NoOwner;
var frontierStation = GetFrontierStation();
if (frontierStation == null)
return ManualFineResult.NoFrontierStation;
var fineResult = TryApplyFine(frontierStation.Value, shuttleUid, deed, state);
switch (fineResult)
{
case ApplyFineResult.Applied:
if (IsOwnerOnline(shuttleUid))
SendOwnerNotice(shuttleUid, deed, Loc.GetString("frontier-parking-popup-fined-extended"), PopupFineType);
state.FinePending = false;
state.Reset(_timing.CurTime);
return ManualFineResult.Success;
case ApplyFineResult.Queued:
state.FinePending = false;
state.Reset(_timing.CurTime);
return ManualFineResult.Queued;
case ApplyFineResult.InsufficientFunds:
state.FinePending = false;
return ManualFineResult.InsufficientFunds;
case ApplyFineResult.NoOwner:
return ManualFineResult.NoOwner;
default:
return ManualFineResult.NoOwner;
}
}
private TimeSpan GetAllowedInterval(ParkingState state)
{
var extra = TimeSpan.FromMinutes(Math.Clamp(state.ExtraMinutes, 0, 50));
return FineInterval + extra;
}
public override void Initialize()
{
base.Initialize();
Subs.CVar(_cfg, CLVars.FrontierParkingEnabled, v => _enabled = v, true);
_nextScan = _timing.CurTime;
}
public override void Update(float frameTime)
{
base.Update(frameTime);
if (!_enabled) return;
if (_timing.CurTime < _nextScan) return;
_nextScan = _timing.CurTime + ScanInterval;
var frontierStation = GetFrontierStation();
if (frontierStation == null) return;
GetFrontierExclusions(frontierStation.Value, _exclusionsBuffer);
if (_exclusionsBuffer.Count == 0) return;
_inZoneBuffer.Clear();
var shuttleQuery = EntityQueryEnumerator<ShuttleDeedComponent, ShuttleComponent, TransformComponent>();
while (shuttleQuery.MoveNext(out var shuttleUid, out var deed, out _, out var shuttleXform))
{
if (shuttleXform.MapID == MapId.Nullspace) continue;
if (!IsInsideAnyExclusion(shuttleXform, _exclusionsBuffer)) continue;
_inZoneBuffer.Add(shuttleUid);
if (!_tracked.TryGetValue(shuttleUid, out var state))
{
state = new ParkingState(_timing.CurTime);
_tracked[shuttleUid] = state;
SendOwnerNotice(shuttleUid, deed, Loc.GetString("frontier-parking-popup-enter"), PopupInfoType);
}
ProcessTimers(frontierStation.Value, shuttleUid, deed, state);
}
foreach (var (uid, _) in _tracked)
{ if (!_inZoneBuffer.Contains(uid)) _toRemove.Add(uid); }
foreach (var uid in _toRemove)
{
if (TryComp<ShuttleDeedComponent>(uid, out var deed)) SendOwnerNotice(uid, deed, Loc.GetString("frontier-parking-popup-leave"), PopupInfoType);
_tracked.Remove(uid);
}
_toRemove.Clear();
}
private readonly List<EntityUid> _toRemove = new();
private EntityUid? GetFrontierStation()
{
var query = EntityQueryEnumerator<FrontierParkingComponent>();
while (query.MoveNext(out var uid, out _))
{ return uid; }
return null;
}
private void GetFrontierExclusions(EntityUid frontierStation, List<(EntityUid Uid, TransformComponent Xform, float Range)> list)
{
list.Clear();
var query = EntityQueryEnumerator<FTLExclusionComponent, TransformComponent>();
while (query.MoveNext(out var uid, out var excl, out var xform))
{
if (!excl.Enabled) continue;
var ownerStation = _station.GetOwningStation(uid, xform);
if (ownerStation != frontierStation) continue;
list.Add((uid, xform, excl.Range));
}
}
private bool IsInsideAnyExclusion(TransformComponent shuttleXform, List<(EntityUid Uid, TransformComponent Xform, float Range)> exclusions)
{
var shuttlePos = _xform.GetWorldPosition(shuttleXform);
var shuttleMap = shuttleXform.MapID;
foreach (var (_, exclXform, range) in exclusions)
{
if (exclXform.MapID != shuttleMap) continue;
var exclPos = _xform.GetWorldPosition(exclXform);
if ((shuttlePos - exclPos).Length() <= range) return true;
}
return false;
}
private void ProcessTimers(EntityUid frontierStation, EntityUid shuttleUid, ShuttleDeedComponent deed, ParkingState state)
{
var elapsed = _timing.CurTime - state.CycleStart;
var allowed = GetAllowedInterval(state);
var warn5 = allowed - TimeSpan.FromMinutes(5);
var warn45 = allowed - TimeSpan.FromSeconds(45);
if (!state.SentFiveMinutes && warn5 > TimeSpan.Zero && elapsed >= warn5)
{
state.SentFiveMinutes = true;
SendOwnerNotice(shuttleUid, deed, Loc.GetString("frontier-parking-popup-remaining-5m"), PopupWarningType);
}
if (!state.SentFortyFiveSeconds && warn45 > TimeSpan.Zero && elapsed >= warn45)
{
state.SentFortyFiveSeconds = true;
SendOwnerNotice(shuttleUid, deed, Loc.GetString("frontier-parking-popup-remaining-45s"), PopupWarningType);
}
if (elapsed < allowed)
return;
if (state.FinePending || state.NeedsDisposal)
return;
state.FinePending = true;
state.HasViolation = true;
SendOwnerNotice(shuttleUid, deed, Loc.GetString("frontier-parking-popup-manual-fine-pending"), PopupFineType);
}
private ApplyFineResult TryApplyFine(EntityUid frontierStation, EntityUid shuttleUid, ShuttleDeedComponent deed, ParkingState state)
{
if (!TryGetOwnerUserId(shuttleUid, deed, out var ownerUserId, out var session))
return ApplyFineResult.NoOwner;
if (session != null && session.AttachedEntity is { } ent)
{
if (!_bank.TryBankWithdraw(ent, FineAmount))
{
state.NeedsDisposal = true;
state.HasViolation = true;
return ApplyFineResult.InsufficientFunds;
}
_bank.TrySectorDeposit(SectorBankAccount.Frontier, FineAmount, LedgerEntryType.StationDepositFines);
var notifyText = Loc.GetString("frontier-parking-notification-fined", ("amount", FineAmount));
_chat.ChatMessageToOne(ChatChannel.Notifications, notifyText, notifyText, EntityUid.Invalid, false, session.Channel);
TrySendFaxNotice(frontierStation, shuttleUid, deed);
state.NeedsDisposal = false;
state.HasViolation = true;
return ApplyFineResult.Applied;
}
if (_pendingOfflineFines.TryGetValue(shuttleUid, out var existing) && !existing.IsCompleted)
return ApplyFineResult.Queued;
_pendingOfflineFines[shuttleUid] = ApplyOfflineFine(frontierStation, shuttleUid, deed, ownerUserId);
return ApplyFineResult.Queued;
}
private bool TryGetOwnerUserId(EntityUid shuttleUid, ShuttleDeedComponent deed, out NetUserId userId, out ICommonSession? session)
{
session = null;
userId = default;
if (TryComp<ShipOwnershipComponent>(shuttleUid, out var ownership) && ownership.OwnerUserId != default && _playerManager.TryGetSessionById(ownership.OwnerUserId, out var owningSession))
{
userId = ownership.OwnerUserId;
session = owningSession;
return true;
}
if (TryComp<ShipOwnershipComponent>(shuttleUid, out ownership) && ownership.OwnerUserId != default)
{
userId = ownership.OwnerUserId;
_playerManager.TryGetSessionById(userId, out session);
return true;
}
var ownerName = deed.ShuttleOwner;
if (!string.IsNullOrWhiteSpace(ownerName))
{
foreach (var s in _playerManager.Sessions)
{
if (s.AttachedEntity is not { } ent) continue;
if (Name(ent).Equals(ownerName, StringComparison.OrdinalIgnoreCase))
{
userId = s.UserId;
session = s;
return true;
}
}
}
return false;
}
private bool IsOwnerOnline(EntityUid shuttleUid)
{ return TryComp<ShipOwnershipComponent>(shuttleUid, out var ownership) && ownership.OwnerUserId != default && _playerManager.TryGetSessionById(ownership.OwnerUserId, out _); }
private async Task ApplyOfflineFine(EntityUid frontierStation, EntityUid shuttleUid, ShuttleDeedComponent deed, NetUserId ownerUserId)
{
try
{
PlayerPreferences? prefs = null;
if (!_prefsManager.TryGetCachedPreferences(ownerUserId, out prefs)) prefs = await _db.GetPlayerPreferencesAsync(ownerUserId, CancellationToken.None);
if (prefs == null || prefs.SelectedCharacter is not HumanoidCharacterProfile profile) return;
var withdrew = await _bank.TryBankWithdrawOffline(ownerUserId, prefs, profile, FineAmount);
if (!withdrew)
{
if (_tracked.TryGetValue(shuttleUid, out var st))
{
st.NeedsDisposal = true;
st.HasViolation = true;
}
return;
}
_bank.TrySectorDeposit(SectorBankAccount.Frontier, FineAmount, LedgerEntryType.StationDepositFines);
TrySendFaxNotice(frontierStation, shuttleUid, deed);
if (_tracked.TryGetValue(shuttleUid, out var st2))
{
st2.NeedsDisposal = false;
st2.HasViolation = true;
}
}
finally { _pendingOfflineFines.Remove(shuttleUid); }
}
private void SendOwnerNotice(EntityUid shuttleUid, ShuttleDeedComponent deed, string message, PopupType type)
{
if (TryComp<ShipOwnershipComponent>(shuttleUid, out var ownership) && ownership.OwnerUserId != default && _playerManager.TryGetSessionById(ownership.OwnerUserId, out var session) && session.AttachedEntity is { } ent)
{
_popup.PopupEntity(message, ent, type);
return;
}
if (deed.DeedHolder == null || !TryComp<ActorComponent>(deed.DeedHolder.Value, out var actor)) return;
if (_playerManager.TryGetSessionById(actor.PlayerSession.UserId, out var fallbackSession) && fallbackSession.AttachedEntity is { } fallbackEnt)
{ _popup.PopupEntity(message, fallbackEnt, type); }
}
private void TrySendFaxNotice(EntityUid frontierStation, EntityUid shuttleUid, ShuttleDeedComponent deed)
{
var faxUid = FindFaxOnGrid(shuttleUid);
if (faxUid == null) return;
var content = BuildFaxContent(frontierStation, deed);
const string paperPrototype = "PaperPrintedCommand";
const string stampState = "paper_stamp-centcom";
var stampedBy = new List<StampDisplayInfo>
{
new StampDisplayInfo
{
StampedName = "stamp-component-stamped-name-centcom",
StampedColor = Color.FromHex("#006600"),
Type = StampType.RubberStamp,
Reapply = false
}
};
var printout = new FaxPrintout(content, Loc.GetString("frontier-parking-fax-title"), null, paperPrototype, stampState, stampedBy, locked: true);
_fax.Receive(faxUid.Value, printout, fromAddress: null);
}
private EntityUid? FindFaxOnGrid(EntityUid gridUid)
{
if (!TryComp<TransformComponent>(gridUid, out var xform)) return null;
var stack = new Stack<EntityUid>();
var enumerator = xform.ChildEnumerator;
while (enumerator.MoveNext(out var child)) stack.Push(child);
while (stack.Count > 0)
{
var uid = stack.Pop();
if (HasComp<FaxMachineComponent>(uid)) return uid;
if (TryComp<TransformComponent>(uid, out var childXform))
{
var childEnum = childXform.ChildEnumerator;
while (childEnum.MoveNext(out var grandChild)) stack.Push(grandChild);
}
}
return null;
}
private string BuildFaxContent(EntityUid frontierStation, ShuttleDeedComponent deed)
{
var text = _res.ContentFileReadText(new ResPath("/Paperwork/Frontier/2.xml")).ReadToEnd();
text = text.Replace("DOCUMENT NAME", "НАРУШЕНИЕ СТОЯНКИ НА ФРОНТИРЕ");
text = text.Replace("{{HOUR.MINUTE.SECOND}}", _ticker.RoundDuration().ToString("hh\\:mm\\:ss"));
text = text.Replace("{{DAY.MONTH.YEAR}}", DateTime.UtcNow.AddHours(3).ToString("dd.MM") + ".2709");
text = text.Replace("STATION XX-00", Name(frontierStation));
text = text.Replace("Я, (ФИО), в должности (полное наименование должности), фиксирую нарушение стоянки на Фронтире",
"ИИ Автономного Контроля Трафика, фиксирует нарушение стоянки на Станции Фронтир");
text = text.Replace("Причина: Злоупотребление временем стыковки",
"Причина: Злоупотребление временем стоянки на территории станции Фронтир");
var fullName = GetFullName(deed);
text = text.Replace("Шаттл: (полное наименование шаттла включая номер)",
$"Шаттл: {fullName}");
text = text.Replace("(Оплатить на стойке Представителя станции)",
"Автоматически списано с нарушителя в пользу станции Фронтир");
return text;
}
private sealed class ParkingState
{
public TimeSpan CycleStart;
public bool SentFiveMinutes;
public bool SentFortyFiveSeconds;
public int ExtraMinutes;
public bool FinePending;
public bool HasViolation;
public bool NeedsDisposal;
public ParkingState(TimeSpan start)
{ CycleStart = start; }
public void Reset(TimeSpan now)
{
CycleStart = now;
SentFiveMinutes = false;
SentFortyFiveSeconds = false;
ExtraMinutes = 0;
FinePending = false;
}
public ParkingPublicState ToPublicState()
{
return new ParkingPublicState(
CycleStart,
ExtraMinutes,
FinePending,
HasViolation,
NeedsDisposal);
}
}
}
public readonly record struct ParkingPublicState(
TimeSpan CycleStart,
int ExtraMinutes,
bool FinePending,
bool HasViolation,
bool NeedsDisposal);